identifier
stringlengths
42
383
collection
stringclasses
1 value
open_type
stringclasses
1 value
license
stringlengths
0
1.81k
date
float64
1.99k
2.02k
title
stringlengths
0
100
creator
stringlengths
1
39
language
stringclasses
157 values
language_type
stringclasses
2 values
word_count
int64
1
20k
token_count
int64
4
1.32M
text
stringlengths
5
1.53M
__index_level_0__
int64
0
57.5k
https://github.com/mfkasim91/anoa/blob/master/anoa/functions/decorator.py
Github Open Source
Open Source
MIT
2,022
anoa
mfkasim91
Python
Code
224
651
import anoa.misc as misc import anoa.core.ops as ops from exceptions import * from importlib import import_module import functools # class to change the function representation class reprwrapper(object): def __init__(self, func, name): self._func = func self._name = name functools.update_wrapper(self, func) def __call__(self, *args, **kw): return self._func(*args, **kw) def __repr__(self): return "<Function 'anoa.%s'>" % (self._name) # function decorators def unary_function(numpy_function, operationStr): def decorator_function(func): # do type checking def intended_function(x, **kwargs): if misc._is_constant(x) and numpy_function != None: return numpy_function(x, **kwargs) elif isinstance(x, ops.Op): return func(x, **kwargs) else: raise TypeError("undefined %s function with type %s" % (operationStr, type(x))) return reprwrapper(intended_function, func.__name__) return decorator_function def binary_function(numpy_function, operationStr, is_commutative=0): def decorator_function(func): # do type checking (only execute func if at least one of the arguments is an op) def intended_function(x, y, **kwargs): if misc._is_constant(x): if misc._is_constant(y): return numpy_function(x, y, **kwargs) elif isinstance(y, ops.Op): # if the function is commutative, then put the op at the beginning if is_commutative: return func(y, x, **kwargs) else: return func(x, y, **kwargs) else: raise TypeError("undefined %s function with type %s and %s" % (operationStr, type(x), type(y))) elif isinstance(x, ops.Op): if misc._is_constant(y): return func(x, y, **kwargs) elif isinstance(y, ops.Op): return func(x, y, **kwargs) else: raise TypeError("undefined %s function with type %s and %s" % (operationStr, type(x), type(y))) else: raise TypeError("undefined %s function with type %s and %s" % (operationStr, type(x), type(y))) return reprwrapper(intended_function, func.__name__) return decorator_function
43,101
https://github.com/dmitry-suffi/PHPMetric/blob/master/src/Model/Classes/Interfaces/ConstantCollectionInterface.php
Github Open Source
Open Source
MIT
null
PHPMetric
dmitry-suffi
PHP
Code
83
232
<?php declare(strict_types=1); namespace Suffi\PHPMetric\Model\Classes\Interfaces; /** * Коллекция констант * Interface ConstantCollectionInterface */ interface ConstantCollectionInterface extends \Countable, \IteratorAggregate { /** * Добавление константы в коллекцию * * @param ConstantInterface $constant * @return void */ public function add(ConstantInterface $constant): void; /** * Проверка наличия константы с именем $name в коллекции * * @param string $name * @return bool */ public function has(string $name): bool; /** * Получение константы по имени * * @param string $name * @return ConstantInterface */ public function get(string $name): ConstantInterface; }
4,224
https://github.com/karabeliov/Telerik-Academy/blob/master/Courses/C#2/07.ExceptionHandling/01.SquareRoot/SquareRoot.cs
Github Open Source
Open Source
MIT
2,016
Telerik-Academy
karabeliov
C#
Code
131
372
using System; using System.Collections.Generic; using System.Linq; using System.Text; /// <summary> /// /// https://github.com/TelerikAcademy/CSharp-Part-2/blob/master/07.%20Exception%20Handling/README.md for example /// Write a program that reads an integer number and calculates and prints its square root. /// - If the number is invalid or negative, print Invalid number. /// - In all cases finally print Good bye. /// Use try-catch-finally block. /// /// </summary> class SquareRoot { static void Main() { Console.Write("Enter number: "); try { double number = double.Parse(Console.ReadLine()); if (number < 0) { Console.WriteLine("Invalid number!"); Console.WriteLine("The number can not be negative."); } else { double sqrt = Math.Sqrt(number); Console.WriteLine("Squrt of {0} is {1}", number, sqrt); } } catch (ArgumentNullException) { Console.WriteLine("Value is not entered!"); } catch (FormatException) { Console.WriteLine("Invalid number!"); } catch (OverflowException) { Console.WriteLine("Value overflowed!"); } finally { Console.WriteLine("Good bye!"); } } }
4,896
https://github.com/DANS-KNAW/dccd-legacy-libs/blob/master/dans-wicket/src/main/java/nl/knaw/dans/common/wicket/components/upload/postprocess/IUploadPostProcess.java
Github Open Source
Open Source
Apache-2.0
2,019
dccd-legacy-libs
DANS-KNAW
Java
Code
315
567
/******************************************************************************* * Copyright 2015 DANS - Data Archiving and Networked Services * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package nl.knaw.dans.common.wicket.components.upload.postprocess; import java.io.File; import java.util.List; import java.util.Map; import nl.knaw.dans.common.wicket.components.upload.UploadStatus; /** * Implementors of this interface may do some post processing on one or more uploaded * files. An implementation must be registered at the EasyUploadProcesess singleton. * Chaining of files lists occurs, thus each process may create more files that may then * be used by the next process. No multi-threading is used for the execution process. Another * thread must be responsible for periodically polling the status object. * * @author lobo * */ public interface IUploadPostProcess { boolean needsProcessing(List<File> files); /** * Implements the execution of a postprocessor. A postprocessor may alter uploaded files, * produce new ones, filter out files or delete files simply by getting a list of files * as input and returning a list of files that needs to be considered uploaded. * * @param files the list with files that are to be considered uploaded * @param destPath the original path in which the files were uploaded * @param clientParams parameters received from the client side (javascript) * @return a list with files that need to be considered as uploaded. * @throws UploadPostProcessException */ List<File> execute(List<File> files, File destPath, Map<String, String> clientParams) throws UploadPostProcessException; UploadStatus getStatus(); void cancel() throws UploadPostProcessException; void rollBack() throws UploadPostProcessException; }
42,832
https://github.com/acromarti01/tech-blog-repo/blob/master/controllers/dashboardRoutes.js
Github Open Source
Open Source
MIT
null
tech-blog-repo
acromarti01
JavaScript
Code
222
737
const router = require("express").Router(); const withAuth = require("../utils/authentication"); const { User, Blog } = require("../models") router.get("/", withAuth, async(req, res) => { try { if (req.session.logged_in) { next(); } else { res.redirect("/user/login"); } const dbBlogData = await Blog.findAll({ where: { user_id: 1 }, include: [ { model: User, attributes: ["name"], } ] }); const blogs = dbBlogData.map((blog) => blog.get({ plain: true })); // Send the rendered Handlebars.js template back as the response res.render("dashboard", { blogs, logged_in: req.session.logged_in, }); } catch (err) { console.log(err); res.status(500).json(err); } }); router.get("/create-post", async(req, res) => { try{ res.render("create-post"); } catch (err) { res.status(500).json(err); } }); router.get("/edit-blog", async(req, res) => { try{ console.log("SESSION", req.session); const blog = { title: req.session.title, content: req.session.content, } res.render("edit-blog", { blog, }); } catch (err) { res.status(500).json(err); } }); router.post("/", async (req, res) => { try { const date = new Date().toLocaleDateString(); const mySqlDate = modifyDateForMySql(date); const { title, content } = req.body; const blog = { title: title, content: content, posted_date: mySqlDate, user_id: 1, //req.session.user_id } await Blog.create(blog); res.status(200).json({message: "Blog is Successfully Created"}); } catch (err) { res.status(500).json(err); } }); router.post("/edit-blog", async(req,res) => { try{ req.session.save(() => { req.session.title = req.body.title; req.session.content = req.body.content; }); res.status(200).json({message: "Success"}); } catch (err) {res.status(500).json(err);} }); module.exports = router; function modifyDateForMySql(date) { const dateArray = date.split("/"); return dateArray[2] + "/" + dateArray[0] + "/" + dateArray[1]; }
32,127
https://github.com/serhepopovych/retc/blob/master/etc/cron.d
Github Open Source
Open Source
MIT
2,021
retc
serhepopovych
Makefile
Code
1
16
../.subprojects/reipset/etc/cron.d
32,601
https://github.com/gustavo-veiga/estrutura-dados/blob/master/cpp_src/lesson/include/lesson/math/factorial.h
Github Open Source
Open Source
MIT
null
estrutura-dados
gustavo-veiga
C
Code
31
86
#ifndef LESSON_MATH_FACTORIAL_H_ #define LESSON_MATH_FACTORIAL_H_ namespace lesson { namespace math { struct factorial { static int iterative(int n); static int recursive(int n); }; } // namespace math } // namespace lesson #endif
89
https://github.com/Kabouterhuisje/Goudkoorts/blob/master/Goudkoorts_DennisTijbosch_StijnHendriks/Model/Ship.cs
Github Open Source
Open Source
MIT
null
Goudkoorts
Kabouterhuisje
C#
Code
70
173
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class Ship : TrackField { public readonly int MaxLoad = 80; public int Load { get; set; } public Ship(int x, int y) : base(x, y) { this.Load = 0; X = x; Y = y; DisplayChar = 'S'; } internal bool IsFull() { if (Load >= MaxLoad) { return true; } else { return false; } } }
48,361
https://github.com/Boyquotes/Atko.Godot.Tiled/blob/master/Atko.Godot.Tiled/Tmx/TmxTile.cs
Github Open Source
Open Source
MIT
2,019
Atko.Godot.Tiled
Boyquotes
C#
Code
140
443
using Godot; // CREDIT // https://github.com/marshallward/TiledSharp/blob/master/TiledSharp/src/Layer.cs namespace Atko.Godot.Tiled.Tmx { public class TmxTile : Node2D { const uint FLIPPED_HORIZONTALLY_FLAG = 0x80000000; const uint FLIPPED_VERTICALLY_FLAG = 0x40000000; const uint FLIPPED_DIAGONALLY_FLAG = 0x20000000; public int Gid { get; set; } = 0; public uint RawGid { get; set; } = 0; public float X { get; set; } public float Y { get; set; } public bool IsDiagonallyFlipped { get; set; } public bool IsHorizontallyFlipped { get; set; } public bool IsVerticallyFlipped { get; set; } public TmxTile(uint rawGid, int x, int y) { RawGid = rawGid; X = x; Y = y; IsDiagonallyFlipped = (rawGid & FLIPPED_DIAGONALLY_FLAG) != 0; IsHorizontallyFlipped = (rawGid & FLIPPED_HORIZONTALLY_FLAG) != 0; IsVerticallyFlipped = (rawGid & FLIPPED_VERTICALLY_FLAG) != 0; // Zero the bit flags rawGid &= ~(FLIPPED_DIAGONALLY_FLAG | FLIPPED_HORIZONTALLY_FLAG | FLIPPED_VERTICALLY_FLAG); Gid = (int) rawGid; } } }
22,356
https://github.com/tross78/placematch/blob/master/node_modules/@reactivex/rxjs/dist/es6/operators/mergeAll.d.ts
Github Open Source
Open Source
MIT
null
placematch
tross78
TypeScript
Code
10
28
import Observable from '../Observable'; export default function mergeAll<R>(concurrent?: number): Observable<R>;
8,728
https://github.com/GSimas/EEL5105/blob/master/AULA3/c2.vhd
Github Open Source
Open Source
MIT
2,022
EEL5105
GSimas
VHDL
Code
33
92
library IEEE; use IEEE.Std_Logic_1164.all; entity C2 is port (A: in std_logic; B: in std_logic; F: out std_logic ); end C2; architecture c2_estr of C2 is begin F <= A xor B; end c2_estr;
6,017
https://github.com/aliyigitbireroglu/flutter-snap/blob/master/snap/lib/snap_controller.dart
Github Open Source
Open Source
MIT
2,022
flutter-snap
aliyigitbireroglu
Dart
Code
1,734
5,639
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // © Cosmos Software | Ali Yigit Bireroglu / // All material used in the making of this code, project, program, application, software et cetera (the "Intellectual Property") / // belongs completely and solely to Ali Yigit Bireroglu. This includes but is not limited to the source code, the multimedia and / // other asset files. If you were granted this Intellectual Property for personal use, you are obligated to include this copyright / // text at all times. / ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //@formatter:off import 'dart:math'; import 'package:flutter/material.dart'; import 'package:flick/flick.dart'; import 'misc.dart' as Misc; import 'Export.dart'; ///The widget that is responsible of ALL Snap related logic and UI. It is important to define two essential concepts used for this package: ///I) The view is what is being moved. It is the widget that snaps to the bound. ///II) The bound is what the view is being snapped to. class SnapController extends StatefulWidget { ///The widget that is to be displayed on your UI. final Widget uiChild; ///Set this to true if your [uiChild] doesn't change at runtime. final bool useCache; ///The [GlobalKey] of the view. final GlobalKey viewKey; ///The [GlobalKey] of the bound. final GlobalKey boundKey; ///Use this value to set the lower left boundary of the movement. final Offset constraintsMin; ///Use this value to set the upper right boundary of the movement. final Offset constraintsMax; ///Use this value to set the lower left elasticity of the movement. final Offset flexibilityMin; ///Use this value to set the upper right elasticity of the movement. final Offset flexibilityMax; ///Use this value to set a custom bound width. If not set, [SnapController] will automatically calculate it via [boundKey]. final double customBoundWidth; ///Use this value to set a custom bound height. If not set, [SnapController] will automatically calculate it via [boundKey]. final double customBoundHeight; ///The list of [SnapTarget]s your view can snap to. final List<SnapTarget>? snapTargets; ///Use this value to set the minimum distance in pixels required for the snapping to occur. If no [SnapTarget] is found that is closer to the [uiChild] than this value, the snapping will not occur. final double minSnapDistance; ///Use this value to set whether the snapping should occur directly or via an animation. final bool animateSnap; ///Use this value to set whether flick should be used or not. final bool useFlick; ///Use this value to set the sensitivity of flick. final double flickSensitivity; ///The callback for when the view moves. final Misc.MoveCallback? onMove; ///The callback for when the drag starts. final Misc.DragCallback? onDragStart; ///The callback for when the drag updates. final Misc.DragCallback? onDragUpdate; ///The callback for when the drag ends. final Misc.DragCallback? onDragEnd; ///The callback for when the view snaps. final SnapCallback? onSnap; const SnapController( this.uiChild, this.useCache, this.viewKey, this.boundKey, this.constraintsMin, this.constraintsMax, this.flexibilityMin, this.flexibilityMax, { Key? key, this.customBoundWidth: 0, this.customBoundHeight: 0, this.snapTargets, this.minSnapDistance = 0, this.animateSnap: true, this.useFlick: true, this.flickSensitivity: 0.075, this.onMove, this.onDragStart, this.onDragUpdate, this.onDragEnd, this.onSnap, }) : super(key: key); @override SnapControllerState createState() { return SnapControllerState( useCache, viewKey, boundKey, constraintsMin, constraintsMax, flexibilityMin, flexibilityMax, snapTargets, minSnapDistance, animateSnap, useFlick, flickSensitivity, onMove, onDragStart, onDragUpdate, onDragEnd, onSnap, ); } } class SnapControllerState extends State<SnapController> with TickerProviderStateMixin { Widget? uiChild; final bool useCache; final GlobalKey viewKey; final GlobalKey boundKey; Offset constraintsMin; Offset constraintsMax; late Offset normalisedConstraintsMin; late Offset normalisedConstraintsMax; final Offset flexibilityMin; final Offset flexibilityMax; final List<SnapTarget>? snapTargets; bool canMove = true; final double minSnapDistance; final bool animateSnap; bool useFlick; final double flickSensitivity; final GlobalKey<FlickControllerState> flickController = GlobalKey<FlickControllerState>(); final Misc.MoveCallback? onMove; final Misc.DragCallback? onDragStart; final Misc.DragCallback? onDragUpdate; final Misc.DragCallback? onDragEnd; final SnapCallback? onSnap; RenderBox? viewRenderBox; double viewWidth = -1; double viewHeight = -1; Offset? viewOrigin; RenderBox? boundRenderBox; double boundWidth = -1; double boundHeight = -1; Offset? boundOrigin; Offset? beginDragPosition; Offset? updateDragPosition; Offset delta = Offset.zero; Offset overrideDelta = Offset.zero; ///The [AnimationController] used to move the view during snapping if [SnapController.animateSnap] is set to true. late AnimationController animationController; late Animation<Offset> animation; final ValueNotifier<Offset> deltaNotifier = ValueNotifier<Offset>(Offset.zero); ///Use this value to determine the depth of debug logging that is actually only here for myself and the Swiss scientists. int _debugLevel = 0; SnapControllerState( this.useCache, this.viewKey, this.boundKey, this.constraintsMin, this.constraintsMax, this.flexibilityMin, this.flexibilityMax, this.snapTargets, this.minSnapDistance, this.animateSnap, this.useFlick, this.flickSensitivity, this.onMove, this.onDragStart, this.onDragUpdate, this.onDragEnd, this.onSnap, ); void animationListener() { deltaNotifier.value = animation.value; if (onMove != null) onMove!(deltaNotifier.value); } @override void initState() { super.initState(); if (!animateSnap) useFlick = false; if (useCache) uiChild = wrapper(); animationController = AnimationController( vsync: this, duration: const Duration(milliseconds: 333), lowerBound: 0, upperBound: 1, )..addListener(animationListener); animation = Tween( begin: Offset.zero, end: Offset.zero, ).animate( CurvedAnimation( parent: animationController, curve: Curves.fastOutSlowIn, ), ); checkViewAndBound(); } @override void dispose() { reset(); animationController.removeListener(animationListener); animationController.dispose(); super.dispose(); } void checkViewAndBound() { if (!viewIsSet) setView(); else checkViewOrigin(); if (!boundIsSet) setBound(); else checkBoundOrigin(); } void setView() { try { if (viewKey.currentContext == null) return; if (viewRenderBox == null) viewRenderBox = viewKey.currentContext!.findRenderObject() as RenderBox?; if (viewRenderBox != null) { if (viewRenderBox!.hasSize) { if (viewWidth == -1) viewWidth = viewRenderBox!.size.width; if (viewHeight == -1) viewHeight = viewRenderBox!.size.height; } if (viewOrigin == null) viewOrigin = viewRenderBox!.localToGlobal(Offset.zero); } } catch (_) {} } bool get viewIsSet => !(viewWidth == -1 || viewHeight == -1 || viewOrigin == null); void setBound() { try { if (boundKey.currentContext == null) return; if (boundRenderBox == null) boundRenderBox = boundKey.currentContext!.findRenderObject() as RenderBox?; if (boundRenderBox != null) { if (boundRenderBox!.hasSize) { if (boundWidth == -1) boundWidth = boundRenderBox!.size.width + widget.customBoundWidth; if (boundHeight == -1) boundHeight = boundRenderBox!.size.height + widget.customBoundHeight; if (boundWidth != -1 && boundHeight != -1) normaliseConstraints(); } } if (boundOrigin == null) boundOrigin = boundRenderBox!.localToGlobal(Offset.zero); } catch (_) {} } bool get boundIsSet => !(boundWidth == -1 || boundHeight == -1 || boundOrigin == null); void checkViewOrigin() { if (viewOrigin != viewRenderBox!.localToGlobal(Offset.zero) - deltaNotifier.value) viewOrigin = viewRenderBox!.localToGlobal(Offset.zero) - deltaNotifier.value; } void checkBoundOrigin() { if (boundOrigin != boundRenderBox!.localToGlobal(Offset.zero)) boundOrigin = boundRenderBox!.localToGlobal(Offset.zero); } void normaliseConstraints() { double constraintsMinX = constraintsMin.dx == double.negativeInfinity ? double.negativeInfinity : boundWidth * constraintsMin.dx; double constraintsMinY = constraintsMin.dy == double.negativeInfinity ? double.negativeInfinity : boundHeight * constraintsMin.dy; double constraintsMaxX = constraintsMax.dx == double.infinity ? double.infinity : boundWidth * constraintsMax.dx; double constraintsMaxY = constraintsMax.dy == double.infinity ? double.infinity : boundHeight * constraintsMax.dy; constraintsMin = Offset(constraintsMinX, constraintsMinY); constraintsMax = Offset(constraintsMaxX, constraintsMaxY); } void beginDrag(dynamic dragStartDetails) { if (!canMove) return; if (animationController.isAnimating) return; if (_debugLevel > 0) print("BeginDrag"); checkViewAndBound(); delta = deltaNotifier.value; beginDragPosition = dragStartDetails.localPosition; if (onDragStart != null) onDragStart!(dragStartDetails); } void updateDrag(dynamic dragUpdateDetails) { if (!canMove) return; if (animationController.isAnimating) return; if (_debugLevel > 0) print("UpdateDrag"); checkViewAndBound(); if (beginDragPosition == null) beginDrag(dragUpdateDetails); updateDragPosition = dragUpdateDetails.localPosition; setDelta(); if (onDragUpdate != null) onDragUpdate!(dragUpdateDetails); } void endDrag(dynamic dragEndDetails) { if (!canMove) return; if (animationController.isAnimating) return; if (_debugLevel > 0) print("EndDrag"); if (onDragEnd != null) onDragEnd!(dragEndDetails); if (!useFlick) snap(); } void onFlick(Offset offset) { snap(); } void setDelta() { if (beginDragPosition == null || updateDragPosition == null) return; if (!viewIsSet || !boundIsSet) return; Offset _delta = delta + Offset(updateDragPosition!.dx - beginDragPosition!.dx, updateDragPosition!.dy - beginDragPosition!.dy); normalisedConstraintsMin = constraintsMin - viewOrigin! + boundOrigin!; normalisedConstraintsMax = constraintsMax - viewOrigin! + boundOrigin! - Offset(viewWidth, viewHeight); if (_delta.dx < normalisedConstraintsMin.dx) _delta = Offset(normalisedConstraintsMin.dx - pow((_delta.dx - normalisedConstraintsMin.dx).abs(), flexibilityMin.dx) + 1.0, _delta.dy); if (_delta.dx > normalisedConstraintsMax.dx) _delta = Offset(normalisedConstraintsMax.dx + pow((_delta.dx - normalisedConstraintsMax.dx).abs(), flexibilityMax.dx) - 1.0, _delta.dy); if (_delta.dy < normalisedConstraintsMin.dy) _delta = Offset(_delta.dx, normalisedConstraintsMin.dy - pow((_delta.dy - normalisedConstraintsMin.dy).abs(), flexibilityMin.dy) + 1.0); if (_delta.dy > normalisedConstraintsMax.dy) _delta = Offset(_delta.dx, normalisedConstraintsMax.dy + pow((_delta.dy - normalisedConstraintsMax.dy).abs(), flexibilityMax.dy) - 1.0); deltaNotifier.value = _delta; if (onMove != null) onMove!(deltaNotifier.value); } double get maxLeft => boundOrigin!.dx - viewOrigin!.dx; double get maxRight => boundWidth + boundOrigin!.dx - viewWidth - viewOrigin!.dx; double get maxTop => boundOrigin!.dy - viewOrigin!.dy; double get maxBottom => boundHeight + boundOrigin!.dy - viewHeight - viewOrigin!.dy; Future snap() async { checkViewAndBound(); Offset snapTarget = getSnapTarget(); if (animateSnap) { await move(snapTarget); deltaNotifier.value = snapTarget; } else deltaNotifier.value = snapTarget; delta = Offset.zero; beginDragPosition = null; updateDragPosition = null; overrideDelta = Offset.zero; if (onSnap != null) onSnap!(deltaNotifier.value); } Offset getSnapTarget() { if (snapTargets == null) return deltaNotifier.value; else { Map<Offset, double> map = Map<Offset, double>(); snapTargets!.forEach((SnapTarget snapTarget) { if (Pivot.isClosestHorizontal(snapTarget.viewPivot) || Pivot.isClosestAny(snapTarget.viewPivot)) { Offset left = Offset(0 - viewOrigin!.dx + boundOrigin!.dx, deltaNotifier.value.dy.clamp(maxTop, maxBottom)); map[left] = Point(deltaNotifier.value.dx, deltaNotifier.value.dy).distanceTo(Point(left.dx, left.dy)); if (_debugLevel > 1) { print("--------------------"); print("Left"); print(snapTarget.boundPivot); print(snapTarget.viewPivot); print(boundWidth); print(boundHeight); print(boundOrigin); print(viewWidth); print(viewHeight); print(viewOrigin); print(left); print("--------------------"); } Offset right = Offset(boundWidth + -viewOrigin!.dx + boundOrigin!.dx - viewWidth, deltaNotifier.value.dy.clamp(maxTop, maxBottom)); map[right] = Point(deltaNotifier.value.dx, deltaNotifier.value.dy).distanceTo(Point(right.dx, right.dy)); if (_debugLevel > 1) { print("--------------------"); print("Right"); print(snapTarget.boundPivot); print(snapTarget.viewPivot); print(boundWidth); print(boundHeight); print(boundOrigin); print(viewWidth); print(viewHeight); print(viewOrigin); print(right); print("--------------------"); } } if (Pivot.isClosestVertical(snapTarget.viewPivot) || Pivot.isClosestAny(snapTarget.viewPivot)) { Offset top = Offset(deltaNotifier.value.dx.clamp(maxLeft, maxRight), 0 - viewOrigin!.dy + boundOrigin!.dy); map[top] = Point(deltaNotifier.value.dx, deltaNotifier.value.dy).distanceTo(Point(top.dx, top.dy)); if (_debugLevel > 1) { print("--------------------"); print("Top"); print(snapTarget.boundPivot); print(snapTarget.viewPivot); print(boundWidth); print(boundHeight); print(boundOrigin); print(viewWidth); print(viewHeight); print(viewOrigin); print(top); print("--------------------"); } Offset bottom = Offset(deltaNotifier.value.dx.clamp(maxLeft, maxRight), boundHeight + -viewOrigin!.dy + boundOrigin!.dy - viewHeight); map[bottom] = Point(deltaNotifier.value.dx, deltaNotifier.value.dy).distanceTo(Point(bottom.dx, bottom.dy)); if (_debugLevel > 1) { print("--------------------"); print("Bottom"); print(snapTarget.boundPivot); print(snapTarget.viewPivot); print(boundWidth); print(boundHeight); print(boundOrigin); print(viewWidth); print(viewHeight); print(viewOrigin); print(bottom); print("--------------------"); } } if (!Pivot.isClosestHorizontal(snapTarget.viewPivot) && !Pivot.isClosestVertical(snapTarget.viewPivot) && !Pivot.isClosestAny(snapTarget.viewPivot)) { Offset offset = Offset(boundWidth * snapTarget.boundPivot.dx + boundOrigin!.dx - viewWidth * snapTarget.viewPivot.dx - viewOrigin!.dx, boundHeight * snapTarget.boundPivot.dy + boundOrigin!.dy - viewHeight * snapTarget.viewPivot.dy - viewOrigin!.dy); if (_debugLevel > 1) { print("--------------------"); print(snapTarget.boundPivot); print(snapTarget.viewPivot); print(boundWidth); print(boundHeight); print(boundOrigin); print(viewWidth); print(viewHeight); print(viewOrigin); print(offset); print("--------------------"); } map[offset] = Point(deltaNotifier.value.dx, deltaNotifier.value.dy).distanceTo(Point(offset.dx, offset.dy)); } }); print(map.values.reduce(min)); if (map.values.reduce(min) > minSnapDistance) { return deltaNotifier.value; } return map.keys.firstWhere((Offset offset) { return map[offset] == map.values.reduce(min); }); } } Future move(Offset snapTarget) async { animation = Tween( begin: deltaNotifier.value, end: snapTarget, ).animate( CurvedAnimation( parent: animationController, curve: Curves.fastOutSlowIn, ), ); if (animationController.isAnimating) animationController.stop(); animationController.forward(from: 0); await Future.delayed(const Duration(milliseconds: 333)); return; } ///Use this function to determine if the view is moved or not. bool isMoved(double treshold) { return deltaNotifier.value.dx.abs() > treshold || deltaNotifier.value.dy.abs() > treshold; } void reset() { delta = Offset.zero; beginDragPosition = null; updateDragPosition = null; overrideDelta = Offset.zero; deltaNotifier.value = Offset.zero; } void softReset(Offset _constraintsMin, Offset _constraintsMax) { constraintsMin = _constraintsMin; constraintsMax = _constraintsMax; viewHeight = -1; viewWidth = -1; viewOrigin = null; boundHeight = -1; boundWidth = -1; boundOrigin = null; if (useFlick && flickController.currentState != null) flickController.currentState!.softReset(_constraintsMin, _constraintsMax); } Widget wrapper() { if (useFlick) return FlickController( widget.uiChild, useCache, viewKey, boundKey: boundKey, constraintsMin: constraintsMin, constraintsMax: constraintsMax, flexibilityMin: flexibilityMin, flexibilityMax: flexibilityMax, sensitivity: flickSensitivity, onDragStart: beginDrag, onDragUpdate: updateDrag, onDragEnd: endDrag, onFlick: onFlick, key: flickController, ); else return GestureDetector( behavior: HitTestBehavior.opaque, onVerticalDragStart: beginDrag, onVerticalDragUpdate: updateDrag, onVerticalDragEnd: endDrag, onHorizontalDragStart: beginDrag, onHorizontalDragUpdate: updateDrag, onHorizontalDragEnd: endDrag, child: widget.uiChild, ); } @override Widget build(BuildContext context) { checkViewAndBound(); return ValueListenableBuilder( child: useCache ? uiChild : null, builder: (BuildContext context, Offset delta, Widget? cachedChild) { return Transform.translate( offset: delta, child: useCache ? cachedChild : wrapper(), ); }, valueListenable: deltaNotifier, ); } }
14,870
https://github.com/TheNomo3000/ng-zorro-antd/blob/master/scripts/site/_site/doc/app/header/join-tip.components.ts
Github Open Source
Open Source
MIT, LicenseRef-scancode-free-unknown, LicenseRef-scancode-unknown-license-reference
2,021
ng-zorro-antd
TheNomo3000
TypeScript
Code
92
393
import { Platform } from '@angular/cdk/platform'; import { ChangeDetectionStrategy, Component } from '@angular/core'; import { Router } from '@angular/router'; @Component({ selector: 'app-join', template: ` <nz-alert [class.hide]="hideJoin" nzBanner [nzMessage]="messageTemplate" nzCloseable [nzShowIcon]="false" ></nz-alert> <ng-template #messageTemplate> 🔥阿里云实时计算部前端工程师火热招聘中,<a (click)="navigateToJoin()">点击查看</a> </ng-template> `, styles: [ ` :host { text-align: center; } .hide { display: none; } ` ], changeDetection: ChangeDetectionStrategy.OnPush }) export class JoinTipComponent { hideJoin = false; constructor(private router: Router, private platform: Platform) { if (this.platform.isBrowser) { this.isHideJoin(); } } isHideJoin(): void { this.hideJoin = localStorage.getItem('hideJoin') === 'true'; } navigateToJoin(): void { localStorage.setItem('hideJoin', 'true'); this.router.navigate(['/docs/join/zh']).then(); } }
43,302
https://github.com/devanjalisingh0811/spring-boot-saml-ssocircle/blob/master/src/test/java/com/vdenotaris/spring/boot/security/saml/web/controllers/SSOControllerTest.java
Github Open Source
Open Source
Apache-2.0
2,022
spring-boot-saml-ssocircle
devanjalisingh0811
Java
Code
235
957
/* * Copyright 2019 Vincenzo De Notaris * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.vdenotaris.spring.boot.security.saml.web.controllers; import com.vdenotaris.spring.boot.security.saml.web.CommonTestSupport; import com.vdenotaris.spring.boot.security.saml.web.TestConfig; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.security.saml.metadata.MetadataManager; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.web.servlet.View; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {TestConfig.class}) @WebAppConfiguration public class SSOControllerTest extends CommonTestSupport { private static final Set<String> IDPS = Collections.unmodifiableSet( new HashSet<>(Arrays.asList("idp1", "idp2", "idp3"))); @InjectMocks SSOController ssoController; @Mock private MetadataManager metadata; @Mock private View mockView; private MockMvc mockMvc; @Before public void setUp() { MockitoAnnotations.initMocks(this); mockMvc = standaloneSetup(ssoController).setSingleView(mockView).build(); } @Test @WithMockUser public void testIdpSelectionWithUser() throws Exception { mockMvc.perform(get("/saml/discovery")) .andExpect(status().isOk()) .andExpect(view().name("redirect:/landing")); } @Test public void testIdpSelection() throws Exception { // given when(metadata.getIDPEntityNames()).thenReturn(IDPS); // when / then mockMvc.perform(get("/saml/discovery").session(mockAnonymousHttpSession())) .andExpect(status().isOk()) .andExpect(model().attribute("idps", IDPS)) .andExpect(view().name("pages/discovery")); } }
37,843
https://github.com/liuwei792966953/cloth20191211-2/blob/master/Includes.h
Github Open Source
Open Source
MIT
2,021
cloth20191211-2
liuwei792966953
C
Code
46
217
/* * Includes.h * * Created on: 15/10/2014 * Author: sam */ #ifndef INCLUDES_H_ #define INCLUDES_H_ #include <iostream> #include <stdio.h> #include <stdlib.h> #include <vector> #include <GL/glew.h> #include <GL/glu.h> #include <GL/glut.h> #define GLM_FORCE_RADIANS #include "glm/glm.hpp" #include "glm/gtx/transform.hpp" #include "glm/gtc/type_ptr.hpp" #include "glm/gtc/matrix_transform.hpp" #include "glm/gtx/fast_square_root.hpp" #endif /* INCLUDES_H_ */
10,730
https://github.com/ischweizer/MoSeS--Server-/blob/master/website/js/profile.js
Github Open Source
Open Source
Apache-2.0
null
MoSeS--Server-
ischweizer
JavaScript
Code
188
508
/******************************************************************************* * Copyright 2013 * Telecooperation (TK) Lab * Technische Universität Darmstadt * * 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. ******************************************************************************/ /* * @author: Wladimir Schmidt */ // Send request to server to save user's profile $('.btnSaveProfile').click(function(e){ e.preventDefault(); var password1 = $('[name="password1"]').val(); var password2 = $('[name="password2"]').val(); if(password1 != password2){ alert("Please, enter same password twice to proceed."); return; } var clickedButton = $(this); clickedButton.removeClass('btn-success'); clickedButton.attr('disabled', true); clickedButton.text('Working...'); // send $.ajax({ type: "POST", url: "content_provider.php", data: $('.saveProfileForm').serialize(), }).done(function(result) { if(result == '0'){ clickedButton.addClass('btn-success'); clickedButton.text('Saved!'); setTimeout(function(){ clickedButton.attr('disabled', false); clickedButton.text('Save Profile'); },2500); }else{ clickedButton.addClass('btn-success'); clickedButton.attr('disabled', false); clickedButton.text('Save Profile'); alert("Error while updating your profile: check your internet connection."); } }); });
22,978
https://github.com/fmilepe/avito-contest/blob/master/ensemble.py
Github Open Source
Open Source
Apache-2.0
2,016
avito-contest
fmilepe
Python
Code
123
443
import csv def lerCSV(path): values = [] i = 0 with open(path, 'r') as csvfile: datareader = csv.reader(csvfile,delimiter=',') for v in datareader: if(i > 0): values.append(v[1]) i = i + 1 return values def ensemble(): arq1 = "knn.csv" arq2 = "xgboost.csv" values1 = lerCSV(arq1) values2 = lerCSV(arq2) f = open("ensemble_result.csv",'w') f.write("id,probability\n") ctz = 0 big_diff = 0 avg_cont = 0 for i in range(len(values1)): knn = float(values1[i]) xgb = float(values2[i]) if(xgb >= 0.6 or xgb <= 0.4): ctz = ctz + 1 result = xgb else: if(abs(xgb-knn) >= 0.4): big_diff = big_diff + 1 result = knn else: avg_cont = avg_cont + 1 #result = (knn+xgb)/2.0 result = xgb f.write(str(i)+","+str(result)+"\n") print("XGB ctz: ", ctz/i*100) print("Big Diff:", big_diff/i*100) print("AVG xgb & knn:", avg_cont/i*100) ensemble()
11,958
https://github.com/epfl-lasa/dynamic_obstacle_avoidance_linear/blob/master/src/dynamic_obstacle_avoidance/avoidance/obs_common_section.py
Github Open Source
Open Source
MIT
2,023
dynamic_obstacle_avoidance_linear
epfl-lasa
Python
Code
1,931
7,240
''' @author lukashuber @date 2019-02-03 ''' import numpy as np from numpy import linalg as LA from math import ceil, sin, cos, sqrt import matplotlib.pyplot as plt # for debugging import warnings # from dynamic_obstacle_avoidance.obstacle_avoidance.ellipse_obstacles import Ellipse # from dynamic_obstacle_avoidance.obstacle_avoidance.obstacle_polygon import Polygon, Cuboid # TODO: include research from graph theory & faster computation class DistanceMatrix(): '''Symmetric matrix storage. Only stores one half of the values, as a 1D ''' def __init__(self, n_obs): self._dim = n_obs # self._value_list = [None for ii in range(int((n_obs-1)*n_obs/2))] self._value_list = (-1)*np.ones(int((n_obs-1)*n_obs/2)) @property def num_obstacles(self): return self._dim def __repr__(self): matr = np.zeros((self._dim, self._dim)) for ii in range(self._dim): for jj in range(ii+1, self._dim): matr[ii, jj] = matr[jj, ii] = self[ii, jj] return str(matr) def __str__(self): return self.__repr__() def __setitem__(self, key, value): if len(key)==2: ind = self.get_index(key[0], key[1]) self._value_list[ind] = value else: raise ValueError("Not two indexes given.") def __getitem__(self, key): if len(key)==2: ind = self.get_index(key[0], key[1]) return self._value_list[ind] else: raise ValueError("Not two indexes given.") def get_matrix(self): ''' Get matrix as numpy-array.''' matr = np.zeros((self._dim, self._dim)) for ix in range(self._dim): for iy in range(ix+1, self._dim): matr[ix, iy] = matr[iy, ix] = self[ix, iy] return matr def get_index(self, row, col): '''Returns the corresponding list index [ind] from matrix index [row, col]''' if row > np.abs(self._dim): raise RuntimeError('Fist object index out of bound.') # row = 0 if col > np.abs(self._dim): raise RuntimeError('Second object index out of bound.') # col = 1 if row < 0: row = self._dim+1-row if col < 0: row = self._dim+1-col if row == col: raise RuntimeError('Self collision observation meaningless.') # row, col = 1, 0 # Symmetric matrix - reverse indices if col > row: col, row = row, col return int(int((row-col-1) + col*((self._dim-1) + self._dim-(col))*0.5)) class Intersection_matrix(DistanceMatrix): ''' Matrix uses less space this way this is useful with many obstacles! e.g. dense crowds Symmetric matrix with zero as diagonal values Stores one common point of intersecting obstacles ''' # TODO: use scipy sparse matrices to replace this partially!!! def __init__(self, n_obs, dim=2): self._value_list = [None for ii in range(int((n_obs-1)*n_obs/2))] self._dim = n_obs def __repr__(self): return str(self.get_bool_matrix()) def set(self, row, col, value): self[row, col] = value def get(self, row, col): return self[row, col] def is_intersecting(self, row, col): return bool(not (self[row, col] is None)) def get_intersection_matrix(self): # Maybe not necessary function space_dim = 2 # matr = np.zeros((self._dim, self._dim), dtype=bool) # for col in range(self._dim): # for row in range(col+1, self._dim): # matr[col, row] = matr[row, col] = not (self[row, col] is None) matr = np.zeros((space_dim, self._dim, self._dim)) for col in range(self._dim): for row in range(col+1, self._dim): if col==row: continue val = self.get(row,col) if not val is None and not isinstance(self.get(row,col), bool): matr[:, col, row] = matr[:, row, col] = self[row,col] return matr def get_bool_triangle_matrix(self): raise NotImplementedError("Function was removed. Use 'get_bool_matrix' instead.") # intersection_exists_matrix = np.zeros((self._dim+1,self._dim+1), dtype=bool) # for col in range(self._dim+1): # for row in range(col+1, self._dim+1): # intersection_exists_matrix = np.zeros((self._dim, self._dim), dtype=bool) # for col in range(self._dim): # for row in range(col+1, self._dim): # if isinstance(self.get(row,col), bool) and (self.get(row,col) == False): # continue # intersection_exists_matrix[row, col] = True # return intersection_exists_matrix def get_bool_matrix(self): bool_matrix = np.zeros((self._dim, self._dim), dtype=bool) for ii in range(self._dim): for jj in range(ii+1, self._dim): bool_matrix[ii, jj] = bool_matrix[jj, ii] = self.is_intersecting(ii, jj) return bool_matrix def obs_common_section(obs): #OBS_COMMON_SECTION finds common section of two ore more obstacles # at the moment only solution in two d is implemented # TODO: REMOVE ' depreciated warnings.warn("This function depreciated and will be removed") N_obs = len(obs) # No intersection region if N_obs <= 1: return [] # Intersction surface intersection_obs = [] intersection_sf = [] intersection_sf_temp = [] it_intersect = -1 # Ext for more dimensions dim = d = len(obs[0].center_position) N_points = 30 # Choose number of points each iteration Gamma_steps = 5 # Increases computational cost rotMat = np.zeros((dim, dim, N_obs)) for it_obs in range(N_obs): rotMat[:,:,it_obs] = np.array(( obs[it_obs].rotMatrix )) obs[it_obs].draw_obstacle() obs[it_obs].cent_dyn = np.copy(obs[it_obs].center_position) # set default value for it_obs1 in range(N_obs): intersection_with_obs1 = False # Check if current obstacle 'it_obs1' has already an intersection with another # obstacle memberFound = False for ii in range(len(intersection_obs)): if it_obs1 in intersection_obs[ii]: memberFound=True continue for it_obs2 in range(it_obs1+1,N_obs): # Check if obstacle has already an intersection with another # obstacle memberFound=False for ii in range(len(intersection_obs)): if it_obs2 in intersection_obs[ii]: memberFound=True continue if memberFound: continue if intersection_with_obs1:# Modify intersecition part obsCloseBy = False if True: N_inter = intersection_sf[it_intersect].shape[1] # Number of intersection points ## R = compute_R(d,obs[it_obs2].th_r) Gamma_temp = ( rotMat[:,:,it_obs2].T.dot(intersection_sf[it_intersect]-np.tile(obs[it_obs2].center_position,(N_inter,1)).T)/ np.tile(obs[it_obs2].a,(N_inter,1)).T ) ** (2*np.tile(obs[it_obs2].p,(N_inter,1)).T) Gamma = np.sum( 1/obs[it_obs2].sf *Gamma_temp, axis=0 ) ind = Gamma<1 if sum(ind): intersection_sf[it_intersect] = intersection_sf[it_intersect][:,ind] intersection_obs[it_intersect] = intersection_obs[it_intersect] + [it_obs2] else: if True: # get all points of obs2 in obs1 # R = compute_R(d,obs[it_obs1].th_r) # \Gamma = \sum_[i=1]^d (xt_i/a_i)^(2p_i) == 1 # if isinstance(obs[it_obs1], Ellipse): # N_points = len(obs[it_obs2].x_obs_sf) # Gamma_temp = (rotMat[:,:,it_obs1].T.dot(np.array(obs[it_obs2].x_obs_sf).T-np.tile(obs[it_obs1].center_position,(N_points,1)).T ) / np.tile(obs[it_obs1].a, (N_points,1)).T ) # Gamma = np.sum( (1/obs[it_obs1].sf * Gamma_temp) ** (2*np.tile(obs[it_obs1].p, (N_points,1)).T), axis=0) # else: Gamma = obs[it_obs1].get_gamma(obs[it_obs2].x_obs_sf, in_global_frame=True) intersection_sf_temp = np.array(obs[it_obs2].x_obs_sf)[:, Gamma<1] # Get all poinst of obs1 in obs2 # R = compute_R(d,obs[it_obs2].th_r) # if isinstance(obs[it_obs2], Ellipse): # N_points = len(obs[it_obs1].x_obs_sf) # Gamma_temp = ( rotMat[:,:,it_obs2].T.dot(np.array(obs[it_obs1].x_obs_sf).T-np.tile(obs[it_obs2].center_position,(N_points,1)).T ) / np.tile(obs[it_obs2].a, (N_points,1)).T ) # Gamma = np.sum(( 1/obs[it_obs2].sf * Gamma_temp) ** (2*np.tile(obs[it_obs2].p, (N_points,1)).T), axis=0 ) # else: Gamma = obs[it_obs2].get_gamma(obs[it_obs1].x_obs_sf, in_global_frame=True) intersection_sf_temp = np.hstack((intersection_sf_temp, np.array(obs[it_obs1].x_obs_sf)[:, Gamma<1] ) ) if intersection_sf_temp.shape[1] > 0: it_intersect = it_intersect + 1 intersection_with_obs1 = True intersection_sf.append(intersection_sf_temp) intersection_obs.append([it_obs1,it_obs2]) # Increase resolution by sampling points within # obstacle, too # obstaacles of 2 in 1 for kk in range(2): if kk == 0: it_obs1_ = it_obs1 it_obs2_ = it_obs2 elif kk ==1: # Do it both ways it_obs1_ = it_obs2 it_obs2_ = it_obs1 for ii in range(1,Gamma_steps): N_points_interior = ceil(N_points/Gamma_steps*ii) #print('a_temp_outside', np.array(obs[it_obs1_].a)/Gamma_steps*ii) # x_obs_sf_interior= obs[it_obs1_].draw_obstacle(numPoints=N_points_interior, a_temp = np.array(obs[it_obs1_].a)/Gamma_steps*ii) x_obs_sf_interior = obs[it_obs1_].get_scaled_boundary_points(1.0*ii/Gamma_steps) # resolution = x_obs_sf_interior.shape[1] # number of points # Get Gamma value # Gamma = np.sum( (1/obs[it_obs2_].sf * rotMat[:,:,it_obs2_].T.dot(x_obs_sf_interior-np.tile(obs[it_obs2_].center_position,(resolution,1)).T ) / np.tile(obs[it_obs2_].a, (resolution,1)).T ) ** (2*np.tile(obs[it_obs2_].p, (resolution,1)).T), axis=0) Gamma = obs[it_obs2_].get_gamma(x_obs_sf_interior, in_global_frame=True) intersection_sf[it_intersect] = np.hstack((intersection_sf[it_intersect],x_obs_sf_interior[:, Gamma<1] )) # Check center point # if 1 > sum( (1/obs[it_obs2_].sf*rotMat[:,:,it_obs2_].T.dot( np.array(obs[it_obs1_].center_position) - np.array(obs[it_obs2_].center_position) )/ np.array(obs[it_obs2_].a) ) ** (2*np.array(obs[it_obs2_].p))): if 1 > obs[it_obs2_].get_gamma(obs[it_obs1_].center_position, in_global_frame=True): intersection_sf[it_intersect] = np.hstack([intersection_sf[it_intersect], np.tile(obs[it_obs1_].center_position,(1,1)).T ] ) #if intersection_with_obs1 continue if len(intersection_sf)==0: return [] #plt.plot(intersection_sf[0][0,:], intersection_sf[0][1,:], 'r.') for ii in range(len(intersection_obs)): intersection_sf[ii] = np.unique(intersection_sf[ii], axis=1) # Get numerical mean x_center_dyn= np.mean(intersection_sf[ii], axis=1) for it_obs in intersection_obs[ii]: obs[it_obs].global_reference_point = x_center_dyn # TODO - replace atan2 for speed # [~, ind] = sort( atan2(intersec_sf_cent(2,:), intersec_sf_cent(1,:))) # intersection_sf = intersection_sf(:, ind) # intersection_sf = [intersection_sf, intersection_sf(:,1)] # intersection_obs = [1:size(obs,2)] return intersection_obs def obs_common_section_hirarchy(*args, **kwargs): # TODO: depreciated -- remove return get_intersections_obstacles(*args, representation_type="hirarchy", **kwargs) def get_intersections_obstacles(obs, hirarchy=True, get_intersection_matrix=False, N_points=30, Gamma_steps=5, representation_type='single_point'): ''' OBS_COMMON_SECTION finds common section of two ore more obstacles Currently implemented solution is for the 2-dimensional case ''' # at the moment only solution in 2-dimensions is implemented # TODO: cleanup comments etc. # Depreciated? Remove? warnings.warn("Depreciated --- Remove!!!") num_obstacles = len(obs) # No intersection region if num_obstacles <=1: return np.zeros((num_obstacles, num_obstacles)) # Intersction surface intersection_obs = [] intersection_sf = [] intersection_sf_temp = [] it_intersect = -1 # Exit for more dimensions dim = len(obs[0].center_position) d = dim # TODO remove! # Find Boundaries # ind_wall = obs.ind_wall # ind_wall = -1 # for o in range(num_obstacles): # if obs[o].is_boundary: # ind_wall = o # break # Choose number of points each iteration if isinstance(obs, list): Intersections = Intersection_matrix(num_obstacles) warnings.warn("We advice to use the <<Obstacle Container>> to store obstacles.") else: Intersections = (obs.get_distance()==0) # raise Warning() R_max = np.zeros((num_obstacles)) # Maximum radius for ellipsoid for it_obs in range(num_obstacles): obs[it_obs].draw_obstacle() R_max[it_obs] = obs[it_obs].get_reference_length() for it_obs1 in range(num_obstacles): for it_obs2 in range(it_obs1+1,num_obstacles): if obs.get_distance(it_obs1, it_obs2)\ or \ R_max[it_obs1]+R_max[it_obs2]< LA.norm(np.array(obs[it_obs1].center_position)-np.array(obs[it_obs2].center_position)): continue # NO intersection possible, to far away # get all points of obs2 in obs1 # N_points = len(obs[it_obs1].x_obs_sf) Gamma = obs[it_obs1].get_gamma(obs[it_obs2].x_obs_sf, in_global_frame=True) intersection_points = np.array(obs[it_obs2].x_obs_sf)[:, Gamma<1] Gamma = obs[it_obs2].get_gamma(obs[it_obs1].x_obs_sf, in_global_frame=True) intersection_points = np.hstack((intersection_points, obs[it_obs1].x_obs_sf[:, Gamma<1] ) ) # if intersection_sf_temp.shape[1] > 0: if intersection_points.shape[1]>0: # Increase resolution by sampling points within obstacle, too # obstaacles of 2 in 1 for kk in range(2): if kk == 0: it_obs1_ = it_obs1 it_obs2_ = it_obs2 elif kk ==1: # Turn around obstacles it_obs1_ = it_obs2 it_obs2_ = it_obs1 if obs[it_obs1_].is_boundary: continue for ii in range(1,Gamma_steps): x_obs_sf_interior = obs[it_obs1_].get_scaled_boundary_points(1.0*ii/Gamma_steps) # Get Gamma value Gamma = obs[it_obs2_].get_gamma(x_obs_sf_interior, in_global_frame=True) intersection_points = np.hstack((intersection_points,x_obs_sf_interior[:,Gamma<1] )) # Check center point if 1 > obs[it_obs2_].get_gamma(obs[it_obs1_].center_position, in_global_frame=True): intersection_points = np.hstack([intersection_points, np.tile(obs[it_obs1_].center_position,(1,1)).T ] ) # Get mean # intersection_points = np.unique(intersection_points, axis=1) Intersections.set(it_obs1, it_obs2, np.mean(intersection_points, axis=1)) intersection_cluster_list = get_intersection_cluster(Intersections, obs, representation_type) if get_intersection_matrix: return intersection_cluster_list, Intersections else: return intersection_cluster_list def get_intersection_cluster(Intersections, obs, representation_type='single_point'): """ Get the clusters number of the intersections. It automatically assign the reference points for intersecting clusters. """ # Get variables num_obstacles = Intersections.num_obstacles dim = obs[0].center_position.shape[0] R_max = np.zeros(num_obstacles) for it_obs in range(num_obstacles): R_max[it_obs] = obs[it_obs].get_reference_length() # Iterate over all obstacles with an intersection intersection_matrix = Intersections.get_bool_matrix() # All obstacles, which have at least one intersection intersecting_obstacles = np.arange(num_obstacles)[np.sum(intersection_matrix, axis=0)>0] if not obs.index_wall is None: # TODO solve more cleanly... intersecting_obstacles = np.delete(intersecting_obstacles, np.nonzero(intersecting_obstacles==obs.index_wall), axis=0) intersection_cluster_list = [] while intersecting_obstacles.shape[0]: intersection_matrix_reduced = intersection_matrix[intersecting_obstacles,:][:,intersecting_obstacles] intersection_cluster = np.zeros(intersecting_obstacles.shape[0], dtype=bool) intersection_cluster[0] = True # By default new obstacles in cluster new_obstacles = True # Iteratively search through clusters. Similar to google page ranking while new_obstacles: intersection_cluster_old = intersection_cluster intersection_cluster = intersection_matrix_reduced.dot(intersection_cluster) + intersection_cluster intersection_cluster = intersection_cluster.astype(bool) # Bool operation. Equals to one if not equal new_obstacles = np.any(intersection_cluster ^ intersection_cluster_old) intersection_cluster_list.append(intersecting_obstacles[intersection_cluster].tolist()) if not obs.index_wall is None: # Add wall connection if np.sum(intersection_matrix[intersection_cluster_list[-1],:][:,obs.index_wall]): # nonzero intersection_cluster_list[-1].append(obs.index_wall) # Only keep non-intersecting obstacles intersecting_obstacles = intersecting_obstacles[intersection_cluster==0] if representation_type=='single_point': # import pdb; pdb.set_trace() get_single_reference_point(obs=obs, obstacle_weight=R_max, intersection_clusters=intersection_cluster_list, Intersections=Intersections, dim=dim) elif representation_type=='hirarchy': get_obstacle_tree(obs=obs, obstacle_weight=R_max, intersection_clusters=intersection_cluster_list, Intersections=Intersections, dim=dim) else: raise NotImplementedError("Method '{}' not defined".format(representation_type)) return intersection_cluster_list def get_single_reference_point(obs, intersection_clusters, Intersections, dim=None, obstacle_weight=None): """ Assign local reference points from intersection clusters.""" # TODO: make applicable for all environments with if obstacle_weight is None: obstacle_weight = np.ones(len(obs))/len(obs) # Iterate over the list of intersection clusters and find one common # reference point for each of the clusters for ii in range(len(intersection_clusters)): # import pdb; pdb.set_trace() # Intersection points of obstacles with wall wall_intersection_points = [] if obs.index_wall in intersection_clusters[ii]: # The cluster is touching wall, hence the reference point has to be placed at the wall. for jj in intersection_clusters[ii]: if jj == obs.index_wall: continue # Check if obstacle jj is intersecting with the wall if Intersections.is_intersecting(jj, obs.index_wall): wall_intersection_points.append(Intersections.get(jj, obs.index_wall)) # break wall_intersection_points = np.array(wall_intersection_points).T for jj in intersection_clusters[ii]: if jj == obs.index_wall: continue if wall_intersection_points.shape[1] == 1: obs[jj].set_reference_point(wall_intersection_points[:, 0], in_global_frame=True) else: # In case of severall interesections with wall; take the closest. dist_intersection = np.linalg.norm(wall_intersection_points - np.tile(obs[jj].position, (wall_intersection_points.shape[1], 1)).T, axis=0) obs[jj].set_reference_point(wall_intersection_points[:, np.argmin(dist_intersection)], in_global_frame=True) else: # No intersection with wall geometric_center = np.zeros(obs.dim) total_weight = 0 # TODO: take intersection position mean for jj in intersection_clusters[ii]: geometric_center += obstacle_weight[jj]*np.array(obs[jj].center_position) total_weight += obstacle_weight[jj] geometric_center /= total_weight for jj in intersection_clusters[ii]: obs[jj].set_reference_point(geometric_center, in_global_frame=True) # Take first position of intersection # TODO make more general def get_obstacle_tree(obs, obstacle_weight, intersection_clusters, Intersection, dim): # All (close) relatives of one object intersection_relatives = intersection_matrix # Choose center geometric_center = np.zeros(dim) for ii in range(len(intersection_clusters)): # list of cluster-lists total_weight = 0 # Find center obstacle for jj in intersection_clusters[ii]: geometric_center += obstacle_weight[jj]*np.array(obs[jj].center_position) total_weight += obstacle_weight[jj] geometric_center /= total_weight center_distance = [LA.norm(geometric_center - np.array(obs[kk].center_position)) for kk in range(len(intersection_clusters[ii]))] # Center obstacle // root_index root_index = np.arange(num_obstacles)[intersection_clusters[ii]][np.argmin(center_distance)] obs[root_index].hirarchy = 0 obs[root_index].reference_point = obs[root_index].center_position obstacle_tree = [root_index] # For all elements in one cluster while len(obstacle_tree): # Iterate over all children for jj in np.arange(num_obstacles)[intersection_relatives[:,obstacle_tree[0]]]: if jj!=obstacle_tree[0]: obs[jj].hirarchy = obs[obstacle_tree[0]].hirarchy+1 obs[jj].ind_parent = obstacle_tree[0] # TODO use pointer... obs[jj].reference_point = Intersections.get(jj, obstacle_tree[0]) # intersection_relatives[jj, obstacle_tree[0]] = False intersection_relatives[obstacle_tree[0], jj] = False obstacle_tree.append(jj) del obstacle_tree[0]
3,161
https://github.com/d99kris/nmail/blob/master/ext/libetpan/src/driver/implementation/imap/imapdriver_tools.c
Github Open Source
Open Source
BSD-2-Clause, MIT, BSL-1.0, BSD-3-Clause, LicenseRef-scancode-unknown-license-reference
2,023
nmail
d99kris
C
Code
8,645
33,659
/* * libEtPan! -- a mail stuff library * * Copyright (C) 2001, 2005 - DINH Viet Hoa * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the libEtPan! project nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * $Id: imapdriver_tools.c,v 1.38 2011/06/04 13:25:56 hoa Exp $ */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include "imapdriver_tools.h" #include "imapdriver_tools_private.h" #include "maildriver.h" #include <stdlib.h> #include <string.h> #include "mail.h" #include "imapdriver_types.h" #include "maildriver_tools.h" #include "generic_cache.h" #include "mailmessage.h" #include "mail_cache_db.h" static inline struct imap_session_state_data * session_get_data(mailsession * session) { return session->sess_data; } static inline struct imap_cached_session_state_data * cached_session_get_data(mailsession * session) { return session->sess_data; } static inline mailsession * cached_session_get_ancestor(mailsession * session) { return cached_session_get_data(session)->imap_ancestor; } static inline struct imap_session_state_data * cached_session_get_ancestor_data(mailsession * session) { return session_get_data(cached_session_get_ancestor(session)); } static inline mailimap * cached_session_get_imap_session(mailsession * session) { return cached_session_get_ancestor_data(session)->imap_session; } int imap_error_to_mail_error(int error) { switch (error) { case MAILIMAP_NO_ERROR: return MAIL_NO_ERROR; case MAILIMAP_NO_ERROR_AUTHENTICATED: return MAIL_NO_ERROR_AUTHENTICATED; case MAILIMAP_NO_ERROR_NON_AUTHENTICATED: return MAIL_NO_ERROR_NON_AUTHENTICATED; case MAILIMAP_ERROR_BAD_STATE: return MAIL_ERROR_BAD_STATE; case MAILIMAP_ERROR_STREAM: return MAIL_ERROR_STREAM; case MAILIMAP_ERROR_PARSE: return MAIL_ERROR_PARSE; case MAILIMAP_ERROR_CONNECTION_REFUSED: return MAIL_ERROR_CONNECT; case MAILIMAP_ERROR_MEMORY: return MAIL_ERROR_MEMORY; case MAILIMAP_ERROR_FATAL: return MAIL_ERROR_FATAL; case MAILIMAP_ERROR_PROTOCOL: return MAIL_ERROR_PROTOCOL; case MAILIMAP_ERROR_DONT_ACCEPT_CONNECTION: return MAIL_ERROR_CONNECT; case MAILIMAP_ERROR_APPEND: return MAIL_ERROR_APPEND; case MAILIMAP_ERROR_NOOP: return MAIL_ERROR_NOOP; case MAILIMAP_ERROR_LOGOUT: return MAIL_ERROR_LOGOUT; case MAILIMAP_ERROR_CAPABILITY: return MAIL_ERROR_CAPABILITY; case MAILIMAP_ERROR_CHECK: return MAIL_ERROR_CHECK; case MAILIMAP_ERROR_CLOSE: return MAIL_ERROR_CLOSE; case MAILIMAP_ERROR_EXPUNGE: return MAIL_ERROR_EXPUNGE; case MAILIMAP_ERROR_COPY: case MAILIMAP_ERROR_UID_COPY: return MAIL_ERROR_COPY; case MAILIMAP_ERROR_CREATE: return MAIL_ERROR_CREATE; case MAILIMAP_ERROR_DELETE: return MAIL_ERROR_DELETE; case MAILIMAP_ERROR_EXAMINE: return MAIL_ERROR_EXAMINE; case MAILIMAP_ERROR_FETCH: case MAILIMAP_ERROR_UID_FETCH: return MAIL_ERROR_FETCH; case MAILIMAP_ERROR_LIST: return MAIL_ERROR_LIST; case MAILIMAP_ERROR_LOGIN: return MAIL_ERROR_LOGIN; case MAILIMAP_ERROR_LSUB: return MAIL_ERROR_LSUB; case MAILIMAP_ERROR_RENAME: return MAIL_ERROR_RENAME; case MAILIMAP_ERROR_SEARCH: case MAILIMAP_ERROR_UID_SEARCH: return MAIL_ERROR_SEARCH; case MAILIMAP_ERROR_SELECT: return MAIL_ERROR_SELECT; case MAILIMAP_ERROR_STATUS: return MAIL_ERROR_STATUS; case MAILIMAP_ERROR_STORE: case MAILIMAP_ERROR_UID_STORE: return MAIL_ERROR_STORE; case MAILIMAP_ERROR_SUBSCRIBE: return MAIL_ERROR_SUBSCRIBE; case MAILIMAP_ERROR_UNSUBSCRIBE: return MAIL_ERROR_UNSUBSCRIBE; case MAILIMAP_ERROR_STARTTLS: return MAIL_ERROR_STARTTLS; case MAILIMAP_ERROR_SSL: return MAIL_ERROR_SSL; case MAILIMAP_ERROR_INVAL: return MAIL_ERROR_INVAL; default: return MAIL_ERROR_INVAL; } } static int imap_body_parameter_to_content(struct mailimap_body_fld_param * body_parameter, char * subtype, struct mailmime_type * mime_type, struct mailmime_content ** result); static int imap_body_type_text_to_content_type(char * subtype, struct mailimap_body_fld_param * body_parameter, struct mailmime_content ** result); int imap_list_to_list(clist * imap_list, struct mail_list ** result) { clistiter * cur; clist * list; struct mail_list * resp; int r; int res; list = clist_new(); if (list == NULL) { res = MAIL_ERROR_MEMORY; goto err; } for(cur = clist_begin(imap_list) ; cur != NULL ; cur = clist_next(cur)) { struct mailimap_mailbox_list * mb_list; char * new_mb; mb_list = clist_content(cur); new_mb = strdup(mb_list->mb_name); if (new_mb == NULL) { res = MAIL_ERROR_MEMORY; goto free_list; } r = clist_append(list, new_mb); if (r != 0) { free(new_mb); res = MAIL_ERROR_MEMORY; goto free_list; } } resp = mail_list_new(list); if (resp == NULL) { res = MAIL_ERROR_MEMORY; goto free_list; } * result = resp; return MAIL_NO_ERROR; free_list: clist_foreach(list, (clist_func) free, NULL); clist_free(list); err: return res; } int imap_section_to_imap_section(struct mailmime_section * section, int type, struct mailimap_section ** result) { struct mailimap_section_part * section_part; struct mailimap_section * imap_section; clist * list; clistiter * cur; int r; int res; list = clist_new(); if (list == NULL) { res = MAIL_ERROR_MEMORY; goto err; } for(cur = clist_begin(section->sec_list) ; cur != NULL ; cur = clist_next(cur)) { uint32_t value; uint32_t * id; value = * (uint32_t *) clist_content(cur); id = malloc(sizeof(* id)); if (id == NULL) { res = MAIL_ERROR_MEMORY; goto free_list; } * id = value; r = clist_append(list, id); if (r != 0) { res = MAIL_ERROR_MEMORY; free(id); goto free_list; } } section_part = mailimap_section_part_new(list); if (section_part == NULL) { res = MAIL_ERROR_MEMORY; goto free_list; } imap_section = NULL; switch (type) { case IMAP_SECTION_MESSAGE: imap_section = mailimap_section_new_part(section_part); break; case IMAP_SECTION_HEADER: imap_section = mailimap_section_new_part_header(section_part); break; case IMAP_SECTION_MIME: imap_section = mailimap_section_new_part_mime(section_part); break; case IMAP_SECTION_BODY: imap_section = mailimap_section_new_part_text(section_part); break; } if (imap_section == NULL) { res = MAIL_ERROR_MEMORY; goto free_part; } * result = imap_section; return MAIL_NO_ERROR; free_part: mailimap_section_part_free(section_part); free_list: if (list != NULL) { clist_foreach(list, (clist_func) free, NULL); clist_free(list); } err: return res; } static int imap_body_media_basic_to_content_type(struct mailimap_media_basic * media_basic, struct mailimap_body_fld_param * body_parameter, struct mailmime_content ** result) { struct mailmime_content * content; struct mailmime_type * mime_type; struct mailmime_discrete_type * discrete_type; struct mailmime_composite_type * composite_type; char * discrete_type_extension; int discrete_type_type; int composite_type_type; int mime_type_type; int r; int res; discrete_type = NULL; composite_type = NULL; discrete_type_extension = NULL; discrete_type_type = 0; composite_type_type = 0; mime_type_type = 0; switch (media_basic->med_type) { case MAILIMAP_MEDIA_BASIC_APPLICATION: mime_type_type = MAILMIME_TYPE_DISCRETE_TYPE; discrete_type_type = MAILMIME_DISCRETE_TYPE_APPLICATION; break; case MAILIMAP_MEDIA_BASIC_AUDIO: mime_type_type = MAILMIME_TYPE_DISCRETE_TYPE; discrete_type_type = MAILMIME_DISCRETE_TYPE_AUDIO; break; case MAILIMAP_MEDIA_BASIC_IMAGE: mime_type_type = MAILMIME_TYPE_DISCRETE_TYPE; discrete_type_type = MAILMIME_DISCRETE_TYPE_IMAGE; break; case MAILIMAP_MEDIA_BASIC_MESSAGE: mime_type_type = MAILMIME_TYPE_COMPOSITE_TYPE; composite_type_type = MAILMIME_COMPOSITE_TYPE_MESSAGE; break; case MAILIMAP_MEDIA_BASIC_VIDEO: mime_type_type = MAILMIME_TYPE_DISCRETE_TYPE; discrete_type_type = MAILMIME_DISCRETE_TYPE_VIDEO; break; case MAILIMAP_MEDIA_BASIC_OTHER: mime_type_type = MAILMIME_TYPE_DISCRETE_TYPE; discrete_type_type = MAILMIME_DISCRETE_TYPE_EXTENSION; discrete_type_extension = media_basic->med_basic_type; if (discrete_type_extension == NULL) { res = MAIL_ERROR_INVAL; goto err; } break; default: res = MAIL_ERROR_INVAL; goto err; } switch (mime_type_type) { case MAILMIME_TYPE_DISCRETE_TYPE: if (discrete_type_extension != NULL) { discrete_type_extension = strdup(discrete_type_extension); if (discrete_type_extension == NULL) { res = MAIL_ERROR_MEMORY; goto err; } } discrete_type = mailmime_discrete_type_new(discrete_type_type, discrete_type_extension); if (discrete_type == NULL) { if (discrete_type_extension != NULL) free(discrete_type_extension); res = MAIL_ERROR_MEMORY; goto err; } break; case MAILMIME_TYPE_COMPOSITE_TYPE: composite_type = mailmime_composite_type_new(composite_type_type, NULL); if (composite_type == NULL) { res = MAIL_ERROR_MEMORY; goto err; } break; default: res = MAIL_ERROR_INVAL; goto err; } mime_type = mailmime_type_new(mime_type_type, discrete_type, composite_type); if (mime_type == NULL) { res = MAIL_ERROR_MEMORY; goto free; } r = imap_body_parameter_to_content(body_parameter, media_basic->med_subtype, mime_type, &content); if (r != MAIL_NO_ERROR) { res = r; goto free_type; } * result = content; return MAIL_NO_ERROR; free_type: mailmime_type_free(mime_type); free: if (discrete_type != NULL) mailmime_discrete_type_free(discrete_type); if (composite_type != NULL) mailmime_composite_type_free(composite_type); err: return res; } static int imap_disposition_to_mime_disposition(struct mailimap_body_fld_dsp * imap_dsp, struct mailmime_disposition ** result) { size_t cur_token; int r; struct mailmime_disposition_type * dsp_type; struct mailmime_disposition * dsp; clist * parameters; int res; cur_token = 0; r = mailmime_disposition_type_parse(imap_dsp->dsp_type, strlen(imap_dsp->dsp_type), &cur_token, &dsp_type); if (r == MAILIMF_ERROR_PARSE) { dsp_type = mailmime_disposition_type_new(MAILMIME_DISPOSITION_TYPE_ATTACHMENT, NULL); if (dsp_type == NULL) { res = MAIL_ERROR_MEMORY; goto err; } } else if (r != MAILIMF_NO_ERROR) { res = MAILIMF_ERROR_PARSE; goto err; } parameters = clist_new(); if (parameters == NULL) { res = MAIL_ERROR_MEMORY; goto err; } if (imap_dsp->dsp_attributes != NULL) { clistiter * cur; for(cur = clist_begin(imap_dsp->dsp_attributes->pa_list) ; cur != NULL ; cur = clist_next(cur)) { struct mailimap_single_body_fld_param * imap_param; struct mailmime_disposition_parm * dsp_param; struct mailmime_parameter * param; char * filename; char * creation_date; char * modification_date; char * read_date; size_t size; int type; imap_param = clist_content(cur); filename = NULL; creation_date = NULL; modification_date = NULL; read_date = NULL; size = 0; param = NULL; type = mailmime_disposition_guess_type(imap_param->pa_name, strlen(imap_param->pa_name), 0); switch (type) { case MAILMIME_DISPOSITION_PARM_FILENAME: if (strcasecmp(imap_param->pa_name, "filename") != 0) { type = MAILMIME_DISPOSITION_PARM_PARAMETER; break; } filename = strdup(imap_param->pa_value); if (filename == NULL) { res = MAIL_ERROR_MEMORY; goto free_dsp_type; } break; case MAILMIME_DISPOSITION_PARM_CREATION_DATE: if (strcasecmp(imap_param->pa_name, "creation-date") != 0) { type = MAILMIME_DISPOSITION_PARM_PARAMETER; break; } creation_date = strdup(imap_param->pa_value); if (creation_date == NULL) { res = MAIL_ERROR_MEMORY; goto free_dsp_type; } break; case MAILMIME_DISPOSITION_PARM_MODIFICATION_DATE: if (strcasecmp(imap_param->pa_name, "modification-date") != 0) { type = MAILMIME_DISPOSITION_PARM_PARAMETER; break; } modification_date = strdup(imap_param->pa_value); if (modification_date == NULL) { res = MAIL_ERROR_MEMORY; goto free_dsp_type; } break; case MAILMIME_DISPOSITION_PARM_READ_DATE: if (strcasecmp(imap_param->pa_name, "read-date") != 0) { type = MAILMIME_DISPOSITION_PARM_PARAMETER; break; } read_date = strdup(imap_param->pa_value); if (read_date == NULL) { res = MAIL_ERROR_MEMORY; goto free_dsp_type; } break; case MAILMIME_DISPOSITION_PARM_SIZE: if (strcasecmp(imap_param->pa_name, "size") != 0) { type = MAILMIME_DISPOSITION_PARM_PARAMETER; break; } size = strtoul(imap_param->pa_value, NULL, 10); break; } if (type == MAILMIME_DISPOSITION_PARM_PARAMETER) { char * name; char * value; name = strdup(imap_param->pa_name); if (name == NULL) { res = MAIL_ERROR_MEMORY; goto free_dsp_type; } value = strdup(imap_param->pa_value); if (value == NULL) { res = MAIL_ERROR_MEMORY; free(name); goto free_dsp_type; } param = mailmime_parameter_new(name, value); if (param == NULL) { free(value); free(name); res = MAIL_ERROR_MEMORY; goto free_dsp_type; } } dsp_param = mailmime_disposition_parm_new(type, filename, creation_date, modification_date, read_date, size, param); if (dsp_param == NULL) { if (filename != NULL) free(filename); if (creation_date != NULL) free(creation_date); if (modification_date != NULL) free(modification_date); if (read_date != NULL) free(read_date); if (param != NULL) mailmime_parameter_free(param); res = MAIL_ERROR_MEMORY; goto free_list; } r = clist_append(parameters, dsp_param); if (r != 0) { mailmime_disposition_parm_free(dsp_param); res = MAIL_ERROR_MEMORY; goto free_list; } } } dsp = mailmime_disposition_new(dsp_type, parameters); if (dsp == NULL) { res = MAIL_ERROR_MEMORY; goto free_list; } * result = dsp; return MAIL_NO_ERROR; free_list: clist_foreach(parameters, (clist_func) mailmime_disposition_parm_free, NULL); clist_free(parameters); free_dsp_type: mailmime_disposition_type_free(dsp_type); err: return res; } static int imap_language_to_mime_language(struct mailimap_body_fld_lang * imap_lang, struct mailmime_language ** result) { clist * list; clistiter * cur; int res; char * single; int r; struct mailmime_language * lang; list = clist_new(); if (list == NULL) { res = MAIL_ERROR_MEMORY; goto err; } switch (imap_lang->lg_type) { case MAILIMAP_BODY_FLD_LANG_SINGLE: if (imap_lang->lg_data.lg_single != NULL) { single = strdup(imap_lang->lg_data.lg_single); if (single == NULL) { res = MAIL_ERROR_MEMORY; goto free; } r = clist_append(list, single); if (r < 0) { free(single); res = MAIL_ERROR_MEMORY; goto free; } } break; case MAILIMAP_BODY_FLD_LANG_LIST: for(cur = clist_begin(imap_lang->lg_data.lg_list) ; cur != NULL ; cur = clist_next(cur)) { char * original_single; original_single = clist_content(cur); single = strdup(original_single); if (single == NULL) { res = MAIL_ERROR_MEMORY; goto free; } r = clist_append(list, single); if (r < 0) { free(single); res = MAIL_ERROR_MEMORY; goto free; } } } lang = mailmime_language_new(list); if (lang == NULL) { res = MAIL_ERROR_MEMORY; goto free; } * result = lang; return MAIL_NO_ERROR; free: clist_foreach(list, (clist_func) free, NULL); clist_free(list); err: return res; } static int imap_body_fields_to_mime_fields(struct mailimap_body_fields * body_fields, struct mailimap_body_fld_dsp * imap_dsp, struct mailimap_body_fld_lang * imap_lang, char * imap_loc, struct mailmime_fields ** result, uint32_t * pbody_size) { struct mailmime_field * mime_field; struct mailmime_fields * mime_fields; clist * list; char * id; struct mailmime_mechanism * encoding; char * description; struct mailmime_disposition * dsp; struct mailmime_language * lang; char * loc; int type; int r; int res; list = clist_new(); if (list == NULL) { res = MAIL_ERROR_MEMORY; goto err; } if (body_fields != NULL) { if (pbody_size != NULL) * pbody_size = body_fields->bd_size; if (body_fields->bd_id != NULL) { type = MAILMIME_FIELD_ID; id = strdup(body_fields->bd_id); if (id == NULL) { res = MAIL_ERROR_MEMORY; goto free_list; } mime_field = mailmime_field_new(type, NULL, NULL, id, NULL, 0, NULL, NULL, NULL); if (mime_field == NULL) { free(id); res = MAIL_ERROR_MEMORY; goto free_list; } r = clist_append(list, mime_field); if (r != 0) { mailmime_field_free(mime_field); res = MAIL_ERROR_MEMORY; goto free_list; } } if (body_fields->bd_description != NULL) { type = MAILMIME_FIELD_DESCRIPTION; description = strdup(body_fields->bd_description); if (description == NULL) { res = MAIL_ERROR_MEMORY; goto free_list; } mime_field = mailmime_field_new(type, NULL, NULL, NULL, description, 0, NULL, NULL, NULL); if (mime_field == NULL) { free(description); res = MAIL_ERROR_MEMORY; goto free_list; } r = clist_append(list, mime_field); if (r != 0) { mailmime_field_free(mime_field); res = MAIL_ERROR_MEMORY; goto free_list; } } if (body_fields->bd_encoding != NULL) { char * encoding_value; int encoding_type; type = MAILMIME_FIELD_TRANSFER_ENCODING; encoding_value = NULL; switch (body_fields->bd_encoding->enc_type) { case MAILIMAP_BODY_FLD_ENC_7BIT: encoding_type = MAILMIME_MECHANISM_7BIT; break; case MAILIMAP_BODY_FLD_ENC_8BIT: encoding_type = MAILMIME_MECHANISM_8BIT; break; case MAILIMAP_BODY_FLD_ENC_BINARY: encoding_type = MAILMIME_MECHANISM_BINARY; break; case MAILIMAP_BODY_FLD_ENC_BASE64: encoding_type = MAILMIME_MECHANISM_BASE64; break; case MAILIMAP_BODY_FLD_ENC_QUOTED_PRINTABLE: encoding_type = MAILMIME_MECHANISM_QUOTED_PRINTABLE; break; case MAILIMAP_BODY_FLD_ENC_OTHER: encoding_type = MAILMIME_MECHANISM_TOKEN; encoding_value = strdup(body_fields->bd_encoding->enc_value); if (encoding_value == NULL) { res = MAIL_ERROR_MEMORY; goto free_list; } break; default: res = MAIL_ERROR_INVAL; goto free_list; } encoding = mailmime_mechanism_new(encoding_type, encoding_value); if (encoding == NULL) { if (encoding_value != NULL) free(encoding_value); res = MAIL_ERROR_MEMORY; goto free_list; } mime_field = mailmime_field_new(type, NULL, encoding, NULL, NULL, 0, NULL, NULL, NULL); if (mime_field == NULL) { mailmime_mechanism_free(encoding); res = MAIL_ERROR_MEMORY; goto free_list; } r = clist_append(list, mime_field); if (r != 0) { mailmime_field_free(mime_field); res = MAIL_ERROR_MEMORY; goto free_list; } } } if (imap_dsp != NULL) { r = imap_disposition_to_mime_disposition(imap_dsp, &dsp); if (r != MAIL_ERROR_PARSE) { if (r != MAIL_NO_ERROR) { res = MAIL_ERROR_MEMORY; goto free_list; } type = MAILMIME_FIELD_DISPOSITION; mime_field = mailmime_field_new(type, NULL, NULL, NULL, NULL, 0, dsp, NULL, NULL); if (mime_field == NULL) { mailmime_disposition_free(dsp); res = MAIL_ERROR_MEMORY; goto free_list; } r = clist_append(list, mime_field); if (r != 0) { mailmime_field_free(mime_field); res = MAIL_ERROR_MEMORY; goto free_list; } } } if (imap_lang != NULL) { int has_lang; has_lang = 1; if (imap_lang->lg_type == MAILIMAP_BODY_FLD_LANG_SINGLE) if (imap_lang->lg_data.lg_single == NULL) has_lang = 0; if (has_lang) { r = imap_language_to_mime_language(imap_lang, &lang); if (r != MAIL_NO_ERROR) { res = MAIL_ERROR_MEMORY; goto free_list; } type = MAILMIME_FIELD_LANGUAGE; mime_field = mailmime_field_new(type, NULL, NULL, NULL, NULL, 0, NULL, lang, NULL); if (mime_field == NULL) { mailmime_language_free(lang); res = MAIL_ERROR_MEMORY; goto free_list; } r = clist_append(list, mime_field); if (r != 0) { mailmime_field_free(mime_field); res = MAIL_ERROR_MEMORY; goto free_list; } } } if (imap_loc != NULL) { type = MAILMIME_FIELD_LOCATION; loc = strdup(imap_loc); if (loc == NULL) { res = MAIL_ERROR_MEMORY; goto free_list; } mime_field = mailmime_field_new(type, NULL, NULL, NULL, NULL, 0, NULL, NULL, loc); if (mime_field == NULL) { mailmime_location_free(loc); res = MAIL_ERROR_MEMORY; goto free_list; } r = clist_append(list, mime_field); if (r != 0) { mailmime_field_free(mime_field); res = MAIL_ERROR_MEMORY; goto free_list; } } mime_fields = mailmime_fields_new(list); if (mime_fields == NULL) { res = MAIL_ERROR_MEMORY; goto free_list; } * result = mime_fields; return MAIL_NO_ERROR; free_list: clist_foreach(list, (clist_func) mailmime_field_free, NULL); clist_free(list); err: return res; } static int imap_body_type_basic_to_body(struct mailimap_body_type_basic * imap_type_basic, struct mailimap_body_ext_1part * body_ext_1part, struct mailmime ** result) { struct mailmime_content * content; struct mailmime_fields * mime_fields; struct mailmime * body; int r; int res; uint32_t mime_size; content = NULL; r = imap_body_media_basic_to_content_type(imap_type_basic->bd_media_basic, imap_type_basic->bd_fields->bd_parameter, &content); if (r != MAIL_NO_ERROR) { res = r; goto err; } if (body_ext_1part != NULL) r = imap_body_fields_to_mime_fields(imap_type_basic->bd_fields, body_ext_1part->bd_disposition, body_ext_1part->bd_language, body_ext_1part->bd_loc, &mime_fields, &mime_size); else r = imap_body_fields_to_mime_fields(imap_type_basic->bd_fields, NULL, NULL, NULL, &mime_fields, &mime_size); if (r != MAIL_NO_ERROR) { res = r; goto free_content; } body = mailmime_new(MAILMIME_SINGLE, NULL, mime_size, mime_fields, content, NULL, NULL, NULL, NULL, NULL, NULL); if (body == NULL) { res = MAIL_ERROR_MEMORY; goto free_fields; } * result = body; return MAIL_NO_ERROR; free_fields: mailmime_fields_free(mime_fields); free_content: mailmime_content_free(content); err: return res; } static int imap_body_type_text_to_body(struct mailimap_body_type_text * imap_type_text, struct mailimap_body_ext_1part * body_ext_1part, struct mailmime ** result) { struct mailmime_content * content; struct mailmime_fields * mime_fields; struct mailmime * body; int r; int res; uint32_t mime_size; r = imap_body_type_text_to_content_type(imap_type_text->bd_media_text, imap_type_text->bd_fields->bd_parameter, &content); if (r != MAIL_NO_ERROR) { res = r; goto err; } if (body_ext_1part == NULL) { r = imap_body_fields_to_mime_fields(imap_type_text->bd_fields, NULL, NULL, NULL, &mime_fields, &mime_size); } else { r = imap_body_fields_to_mime_fields(imap_type_text->bd_fields, body_ext_1part->bd_disposition, body_ext_1part->bd_language, body_ext_1part->bd_loc, &mime_fields, &mime_size); } if (r != MAIL_NO_ERROR) { res = r; goto free_content; } body = mailmime_new(MAILMIME_SINGLE, NULL, mime_size, mime_fields, content, NULL, NULL, NULL, NULL, NULL, NULL); if (body == NULL) { res = MAIL_ERROR_MEMORY; goto free_fields; } * result = body; return MAIL_NO_ERROR; free_fields: mailmime_fields_free(mime_fields); free_content: mailmime_content_free(content); err: return res; } static int imap_body_parameter_to_content(struct mailimap_body_fld_param * body_parameter, char * subtype, struct mailmime_type * mime_type, struct mailmime_content ** result) { clist * parameters; char * new_subtype; struct mailmime_content * content; int r; int res; new_subtype = strdup(subtype); if (new_subtype == NULL) { res = MAIL_ERROR_MEMORY; goto err; } parameters = clist_new(); if (parameters == NULL) { res = MAIL_ERROR_MEMORY; goto free_subtype; } if (body_parameter != NULL) { clistiter * cur; for(cur = clist_begin(body_parameter->pa_list) ; cur != NULL ; cur = clist_next(cur)) { struct mailimap_single_body_fld_param * imap_param; struct mailmime_parameter * param; char * name; char * value; imap_param = clist_content(cur); name = strdup(imap_param->pa_name); if (name == NULL) { res = MAIL_ERROR_MEMORY; goto free_parameters; } value = strdup(imap_param->pa_value); if (value == NULL) { free(name); res = MAIL_ERROR_MEMORY; goto free_parameters; } param = mailmime_parameter_new(name, value); if (param == NULL) { free(value); free(name); res = MAIL_ERROR_MEMORY; goto free_parameters; } r = clist_append(parameters, param); if (r != 0) { mailmime_parameter_free(param); res = MAIL_ERROR_MEMORY; goto free_parameters; } } } content = mailmime_content_new(mime_type, new_subtype, parameters); if (content == NULL) { res = MAIL_ERROR_MEMORY; goto free_parameters; } * result = content; return MAIL_NO_ERROR; free_parameters: clist_foreach(parameters, (clist_func) mailmime_parameter_free, NULL); clist_free(parameters); free_subtype: free(new_subtype); err: return res; } static int imap_body_type_text_to_content_type(char * subtype, struct mailimap_body_fld_param * body_parameter, struct mailmime_content ** result) { struct mailmime_content * content; struct mailmime_type * mime_type; struct mailmime_discrete_type * discrete_type; int r; int res; discrete_type = NULL; discrete_type = mailmime_discrete_type_new(MAILMIME_DISCRETE_TYPE_TEXT, NULL); if (discrete_type == NULL) { res = MAIL_ERROR_MEMORY; goto err; } mime_type = mailmime_type_new(MAILMIME_TYPE_DISCRETE_TYPE, discrete_type, NULL); if (mime_type == NULL) { mailmime_discrete_type_free(discrete_type); res = MAIL_ERROR_MEMORY; goto err; } r = imap_body_parameter_to_content(body_parameter, subtype, mime_type, &content); if (r != MAIL_NO_ERROR) { res = r; goto free_type; } * result = content; return MAIL_NO_ERROR; free_type: mailmime_type_free(mime_type); err: return res; } static int imap_body_type_msg_to_body(struct mailimap_body_type_msg * imap_type_msg, struct mailimap_body_ext_1part * body_ext_1part, struct mailmime ** result) { struct mailmime * body; struct mailmime * msg_body; struct mailmime_fields * mime_fields; struct mailmime_composite_type * composite_type; struct mailmime_type * mime_type; struct mailmime_content * content_type; struct mailimf_fields * fields; int r; int res; uint32_t mime_size; if (body_ext_1part != NULL) { r = imap_body_fields_to_mime_fields(imap_type_msg->bd_fields, body_ext_1part->bd_disposition, body_ext_1part->bd_language, body_ext_1part->bd_loc, &mime_fields, &mime_size); } else { r = imap_body_fields_to_mime_fields(imap_type_msg->bd_fields, NULL, NULL, NULL, &mime_fields, &mime_size); } if (r != MAIL_NO_ERROR) { res = r; goto err; } r = imap_env_to_fields(imap_type_msg->bd_envelope, NULL, 0, &fields); if (r != MAIL_NO_ERROR) { res = r; goto free_mime_fields; } r = imap_body_to_body(imap_type_msg->bd_body, &msg_body); if (r != MAIL_NO_ERROR) { res = r; goto free_fields; } composite_type = mailmime_composite_type_new(MAILMIME_COMPOSITE_TYPE_MESSAGE, NULL); if (composite_type == NULL) { res = MAIL_ERROR_MEMORY; goto free_fields; } mime_type = mailmime_type_new(MAILMIME_TYPE_COMPOSITE_TYPE, NULL, composite_type); if (mime_type == NULL) { mailmime_composite_type_free(composite_type); res = MAIL_ERROR_MEMORY; goto free_fields; } r = imap_body_parameter_to_content(imap_type_msg->bd_fields->bd_parameter, "rfc822", mime_type, &content_type); if (r != MAIL_NO_ERROR) { mailmime_type_free(mime_type); res = MAIL_ERROR_MEMORY; goto free_fields; } body = mailmime_new(MAILMIME_MESSAGE, NULL, mime_size, mime_fields, content_type, NULL, NULL, NULL, NULL, fields, msg_body); if (body == NULL) { res = MAIL_ERROR_MEMORY; goto free_content; } * result = body; return MAIL_NO_ERROR; free_content: mailmime_content_free(content_type); free_fields: mailimf_fields_free(fields); free_mime_fields: mailmime_fields_free(mime_fields); err: return res; } static int imap_body_type_1part_to_body(struct mailimap_body_type_1part * type_1part, struct mailmime ** result) { struct mailmime * body; int r; int res; body = NULL; switch (type_1part->bd_type) { case MAILIMAP_BODY_TYPE_1PART_BASIC: r = imap_body_type_basic_to_body(type_1part->bd_data.bd_type_basic, type_1part->bd_ext_1part, &body); if (r != MAIL_NO_ERROR) { res = r; goto err; } break; case MAILIMAP_BODY_TYPE_1PART_MSG: r = imap_body_type_msg_to_body(type_1part->bd_data.bd_type_msg, type_1part->bd_ext_1part, &body); if (r != MAIL_NO_ERROR) { res = r; goto err; } break; case MAILIMAP_BODY_TYPE_1PART_TEXT: r = imap_body_type_text_to_body(type_1part->bd_data.bd_type_text, type_1part->bd_ext_1part, &body); if (r != MAIL_NO_ERROR) { res = r; goto err; } break; } * result = body; return MAIL_NO_ERROR; err: return res; } static int imap_body_type_mpart_to_body(struct mailimap_body_type_mpart * type_mpart, struct mailmime ** result) { struct mailmime_fields * mime_fields; struct mailmime_composite_type * composite_type; struct mailmime_type * mime_type; struct mailmime_content * content_type; struct mailmime * body; clistiter * cur; clist * list; int r; int res; uint32_t mime_size; if (type_mpart->bd_ext_mpart == NULL) { mime_fields = mailmime_fields_new_empty(); mime_size = 0; r = MAIL_NO_ERROR; } else { r = imap_body_fields_to_mime_fields(NULL, type_mpart->bd_ext_mpart->bd_disposition, type_mpart->bd_ext_mpart->bd_language, type_mpart->bd_ext_mpart->bd_loc, &mime_fields, &mime_size); } if (r != MAIL_NO_ERROR) { res = r; goto err; } composite_type = mailmime_composite_type_new(MAILMIME_COMPOSITE_TYPE_MULTIPART, NULL); if (composite_type == NULL) { res = MAIL_ERROR_MEMORY; goto free_fields; } mime_type = mailmime_type_new(MAILMIME_TYPE_COMPOSITE_TYPE, NULL, composite_type); if (mime_type == NULL) { mailmime_composite_type_free(composite_type); res = MAIL_ERROR_MEMORY; goto free_fields; } if (type_mpart->bd_ext_mpart == NULL) { r = imap_body_parameter_to_content(NULL, type_mpart->bd_media_subtype, mime_type, &content_type); } else { r = imap_body_parameter_to_content(type_mpart->bd_ext_mpart->bd_parameter, type_mpart->bd_media_subtype, mime_type, &content_type); } if (r != MAIL_NO_ERROR) { mailmime_type_free(mime_type); res = r; goto free_fields; } list = clist_new(); if (list == NULL) { res = MAIL_ERROR_MEMORY; goto free_content; } for(cur = clist_begin(type_mpart->bd_list) ; cur != NULL ; cur = clist_next(cur)) { struct mailimap_body * imap_body; struct mailmime * sub_body; imap_body = clist_content(cur); r = imap_body_to_body(imap_body, &sub_body); if (r != MAIL_NO_ERROR) { res = r; goto free_list; } r = clist_append(list, sub_body); if (r != 0) { mailmime_free(sub_body); res = r; goto free_list; } } body = mailmime_new(MAILMIME_MULTIPLE, NULL, mime_size, mime_fields, content_type, NULL, NULL, NULL, list, NULL, NULL); if (body == NULL) { res = MAIL_ERROR_MEMORY; goto free_list; } * result = body; return MAIL_NO_ERROR; free_list: clist_foreach(list, (clist_func) mailmime_free, NULL); clist_free(list); free_content: mailmime_content_free(content_type); free_fields: mailmime_fields_free(mime_fields); err: return res; } int imap_body_to_body(struct mailimap_body * imap_body, struct mailmime ** result) { struct mailmime * body; int r; int res; body = NULL; switch (imap_body->bd_type) { case MAILIMAP_BODY_1PART: r = imap_body_type_1part_to_body(imap_body->bd_data.bd_body_1part, &body); if (r != MAIL_NO_ERROR) { res = r; goto err; } break; case MAILIMAP_BODY_MPART: r = imap_body_type_mpart_to_body(imap_body->bd_data.bd_body_mpart, &body); if (r != MAIL_NO_ERROR) { res = r; goto err; } break; default: return MAIL_ERROR_INVAL; } * result = body; return MAIL_NO_ERROR; err: return res; } int imap_address_to_mailbox(struct mailimap_address * imap_addr, struct mailimf_mailbox ** result) { char * dsp_name; char * addr; struct mailimf_mailbox * mb; int res; if (imap_addr->ad_personal_name == NULL) dsp_name = NULL; else { dsp_name = strdup(imap_addr->ad_personal_name); if (dsp_name == NULL) { res = MAIL_ERROR_MEMORY; goto err; } } if (imap_addr->ad_host_name == NULL) { if (imap_addr->ad_mailbox_name == NULL) { addr = strdup(""); } else { addr = strdup(imap_addr->ad_mailbox_name); } if (addr == NULL) { res = MAIL_ERROR_MEMORY; goto free_name; } } else if (imap_addr->ad_mailbox_name == NULL) { // fix by Gabor Cselle, (http://gaborcselle.com/), reported 8/16/2009 addr = strdup(imap_addr->ad_host_name); if (addr == NULL) { res = MAIL_ERROR_MEMORY; goto free_name; } } else { addr = malloc(strlen(imap_addr->ad_mailbox_name) + strlen(imap_addr->ad_host_name) + 2); if (addr == NULL) { res = MAIL_ERROR_MEMORY; goto free_name; } strcpy(addr, imap_addr->ad_mailbox_name); strcat(addr, "@"); strcat(addr, imap_addr->ad_host_name); } mb = mailimf_mailbox_new(dsp_name, addr); if (mb == NULL) { res = MAIL_ERROR_MEMORY; goto free_addr; } * result = mb; return MAIL_NO_ERROR; free_addr: free(addr); free_name: free(dsp_name); err: return res; } int imap_address_to_address(struct mailimap_address * imap_addr, struct mailimf_address ** result) { struct mailimf_address * addr; struct mailimf_mailbox * mb; int r; int res; r = imap_address_to_mailbox(imap_addr, &mb); if (r != MAIL_NO_ERROR) { res = r; goto err; } addr = mailimf_address_new(MAILIMF_ADDRESS_MAILBOX, mb, NULL); if (addr == NULL) { res = MAIL_ERROR_MEMORY; goto free_mb; } * result = addr; return MAIL_NO_ERROR; free_mb: mailimf_mailbox_free(mb); err: return res; } int imap_mailbox_list_to_mailbox_list(clist * imap_mailbox_list, struct mailimf_mailbox_list ** result) { clistiter * cur; clist * list; struct mailimf_mailbox_list * mb_list; int r; list = clist_new(); if (list == NULL) { goto err; } for(cur = clist_begin(imap_mailbox_list) ; cur != NULL ; cur = clist_next(cur)) { struct mailimap_address * imap_addr; struct mailimf_mailbox * mb; imap_addr = clist_content(cur); if (imap_addr->ad_mailbox_name == NULL) continue; r = imap_address_to_mailbox(imap_addr, &mb); if (r != MAIL_NO_ERROR) { goto free_list; } r = clist_append(list, mb); if (r != 0) { mailimf_mailbox_free(mb); goto free_list; } } mb_list = mailimf_mailbox_list_new(list); if (mb_list == NULL) { goto free_list; } * result = mb_list; return MAIL_NO_ERROR; free_list: clist_foreach(list, (clist_func) mailimf_mailbox_free, NULL); clist_free(list); err: return MAIL_ERROR_MEMORY; } /* at exit, imap_mb_list will fall on the last element of the group, where mailbox name will be NIL, so that imap_mailbox_list_to_address_list can continue */ static int imap_mailbox_list_to_group(clist * imap_mb_list, clistiter ** iter, struct mailimf_group ** result) { clistiter * imap_mailbox_listiter; clist * list; struct mailimf_group * group; struct mailimap_address * imap_addr; char * group_name; clistiter * cur; struct mailimf_mailbox_list * mb_list; int r; int res; imap_mailbox_listiter = * iter; imap_addr = clist_content(imap_mailbox_listiter); if (imap_addr == NULL || imap_addr->ad_mailbox_name == NULL) { res = MAIL_ERROR_INVAL; goto err; } group_name = strdup(imap_addr->ad_mailbox_name); if (group_name == NULL) { res = MAIL_ERROR_MEMORY; goto err; } list = clist_new(); if (list == NULL) { res = MAIL_ERROR_MEMORY; goto free_group_name; } for(cur = clist_next(imap_mailbox_listiter) ; cur != NULL ; cur = clist_next(cur)) { struct mailimf_mailbox * mb; imap_addr = clist_content(cur); if (imap_addr->ad_mailbox_name == NULL) { break; } r = imap_address_to_mailbox(imap_addr, &mb); if (r != MAIL_NO_ERROR) { res = r; goto free_list; } r = clist_append(list, mb); if (r != 0) { mailimf_mailbox_free(mb); res = MAIL_ERROR_MEMORY; goto free_list; } } mb_list = mailimf_mailbox_list_new(list); if (mb_list == NULL) { res = MAIL_ERROR_MEMORY; goto free_list; } group = mailimf_group_new(group_name, mb_list); if (group == NULL) { mailimf_mailbox_list_free(mb_list); res = MAIL_ERROR_MEMORY; goto free_group_name; } * result = group; * iter = cur; return MAIL_NO_ERROR; free_list: clist_foreach(list, (clist_func) mailimf_mailbox_free, NULL); clist_free(list); free_group_name: free(group_name); err: return res; } int imap_mailbox_list_to_address_list(clist * imap_mailbox_list, struct mailimf_address_list ** result) { clistiter * cur; clist * list; struct mailimf_address_list * addr_list; int r; int res; list = clist_new(); if (list == NULL) { res = MAIL_ERROR_MEMORY; goto err; } for(cur = clist_begin(imap_mailbox_list) ; cur != NULL ; cur = clist_next(cur)) { struct mailimap_address * imap_addr; struct mailimf_address * addr; imap_addr = clist_content(cur); if (imap_addr->ad_mailbox_name == NULL) continue; if ((imap_addr->ad_host_name == NULL) && (imap_addr->ad_mailbox_name != NULL)) { struct mailimf_group * group; group = NULL; r = imap_mailbox_list_to_group(imap_mailbox_list, &cur, &group); if (r != MAIL_NO_ERROR) { res = r; goto free_list; } addr = mailimf_address_new(MAILIMF_ADDRESS_GROUP, NULL, group); if (addr == NULL) { mailimf_group_free(group); res = MAIL_ERROR_MEMORY; goto free_list; } } else { r = imap_address_to_address(imap_addr, &addr); if (r != MAIL_NO_ERROR) { res = r; goto free_list; } } r = clist_append(list, addr); if (r != 0) { mailimf_address_free(addr); res = MAIL_ERROR_MEMORY; goto free_list; } } addr_list = mailimf_address_list_new(list); if (addr_list == NULL) { res = MAIL_ERROR_MEMORY; goto free_list; } * result = addr_list; return MAIL_NO_ERROR; free_list: clist_foreach(list, (clist_func) mailimf_address_free, NULL); clist_free(list); err: return res; } int imap_add_envelope_fetch_att(struct mailimap_fetch_type * fetch_type) { struct mailimap_fetch_att * fetch_att; int res; int r; char * header; clist * hdrlist; struct mailimap_header_list * imap_hdrlist; struct mailimap_section * section; fetch_att = mailimap_fetch_att_new_envelope(); if (fetch_att == NULL) { res = MAIL_ERROR_MEMORY; goto err; } r = mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att); if (r != MAILIMAP_NO_ERROR) { mailimap_fetch_att_free(fetch_att); res = MAIL_ERROR_MEMORY; goto err; } header = strdup("References"); if (header == NULL) { mailimap_fetch_att_free(fetch_att); res = MAIL_ERROR_MEMORY; goto err; } hdrlist = clist_new(); if (hdrlist == NULL) { free(header); mailimap_fetch_att_free(fetch_att); res = MAIL_ERROR_MEMORY; goto err; } r = clist_append(hdrlist, header); if (r < 0) { free(header); clist_foreach(hdrlist, (clist_func) free, NULL); clist_free(hdrlist); mailimap_fetch_att_free(fetch_att); res = MAIL_ERROR_MEMORY; goto err; } imap_hdrlist = mailimap_header_list_new(hdrlist); if (imap_hdrlist == NULL) { clist_foreach(hdrlist, (clist_func) free, NULL); clist_free(hdrlist); mailimap_fetch_att_free(fetch_att); res = MAIL_ERROR_MEMORY; goto err; } section = mailimap_section_new_header_fields(imap_hdrlist); if (section == NULL) { mailimap_header_list_free(imap_hdrlist); mailimap_fetch_att_free(fetch_att); res = MAIL_ERROR_MEMORY; goto err; } fetch_att = mailimap_fetch_att_new_body_peek_section(section); if (fetch_att == NULL) { mailimap_section_free(section); res = MAIL_ERROR_MEMORY; goto err; } r = mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att); if (r != MAILIMAP_NO_ERROR) { mailimap_fetch_att_free(fetch_att); res = MAIL_ERROR_MEMORY; goto err; } return MAIL_NO_ERROR; err: return res; } int imap_env_to_fields(struct mailimap_envelope * env, char * ref_str, size_t ref_size, struct mailimf_fields ** result) { clist * list; struct mailimf_field * field; int r; struct mailimf_fields * fields; int res; list = clist_new(); if (list == NULL) { res = MAIL_ERROR_MEMORY; goto err; } if (env->env_date != NULL) { size_t cur_token; struct mailimf_date_time * date_time; cur_token = 0; r = mailimf_date_time_parse(env->env_date, strlen(env->env_date), &cur_token, &date_time); if (r == MAILIMF_NO_ERROR) { struct mailimf_orig_date * orig; orig = mailimf_orig_date_new(date_time); if (orig == NULL) { mailimf_date_time_free(date_time); res = MAIL_ERROR_MEMORY; goto free_list; } field = mailimf_field_new(MAILIMF_FIELD_ORIG_DATE, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, orig, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); if (field == NULL) { mailimf_orig_date_free(orig); res = MAIL_ERROR_MEMORY; goto free_list; } r = clist_append(list, field); if (r != 0) { mailimf_field_free(field); res = MAIL_ERROR_MEMORY; goto free_list; } } } if (env->env_subject != NULL) { char * subject; struct mailimf_subject * subject_field; subject = strdup(env->env_subject); if (subject == NULL) { res = MAIL_ERROR_MEMORY; goto free_list; } subject_field = mailimf_subject_new(subject); if (subject_field == NULL) { free(subject); res = MAIL_ERROR_MEMORY; goto free_list; } field = mailimf_field_new(MAILIMF_FIELD_SUBJECT, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, subject_field, NULL, NULL, NULL); if (field == NULL) { mailimf_subject_free(subject_field); res = MAIL_ERROR_MEMORY; goto free_list; } r = clist_append(list, field); if (r != 0) { mailimf_field_free(field); res = MAIL_ERROR_MEMORY; goto free_list; } } if (env->env_from != NULL) { if (env->env_from->frm_list != NULL) { struct mailimf_mailbox_list * mb_list; struct mailimf_from * from; r = imap_mailbox_list_to_mailbox_list(env->env_from->frm_list, &mb_list); if (r != MAIL_NO_ERROR) { res = r; goto free_list; } from = mailimf_from_new(mb_list); if (from == NULL) { mailimf_mailbox_list_free(mb_list); res = MAIL_ERROR_MEMORY; goto free_list; } field = mailimf_field_new(MAILIMF_FIELD_FROM, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, from, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); if (field == NULL) { mailimf_from_free(from); res = MAIL_ERROR_MEMORY; goto free_list; } r = clist_append(list, field); if (r != 0) { mailimf_field_free(field); res = MAIL_ERROR_MEMORY; goto free_list; } } } if (env->env_sender != NULL) { if (env->env_sender->snd_list != NULL) { struct mailimf_sender * sender; struct mailimf_mailbox * mb; r = imap_address_to_mailbox(clist_begin(env->env_sender->snd_list)->data, &mb); if (r != MAIL_NO_ERROR) { res = r; goto free_list; } sender = mailimf_sender_new(mb); if (sender == NULL) { mailimf_mailbox_free(mb); res = MAIL_ERROR_MEMORY; goto free_list; } field = mailimf_field_new(MAILIMF_FIELD_SENDER, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, sender, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); if (field == NULL) { mailimf_sender_free(sender); res = MAIL_ERROR_MEMORY; goto free_list; } r = clist_append(list, field); if (r != 0) { mailimf_field_free(field); res = MAIL_ERROR_MEMORY; goto free_list; } } } if (env->env_reply_to != NULL) { if (env->env_reply_to->rt_list != NULL) { struct mailimf_address_list * addr_list; struct mailimf_reply_to * reply_to; r = imap_mailbox_list_to_address_list(env->env_reply_to->rt_list, &addr_list); if (r != MAIL_NO_ERROR) { res = r; goto free_list; } reply_to = mailimf_reply_to_new(addr_list); if (reply_to == NULL) { mailimf_address_list_free(addr_list); res = MAIL_ERROR_MEMORY; goto free_list; } field = mailimf_field_new(MAILIMF_FIELD_REPLY_TO, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, reply_to, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); if (field == NULL) { mailimf_reply_to_free(reply_to); res = MAIL_ERROR_MEMORY; goto free_list; } r = clist_append(list, field); if (r != 0) { mailimf_field_free(field); res = MAIL_ERROR_MEMORY; goto free_list; } } } if (env->env_to != NULL) { if (env->env_to->to_list != NULL) { struct mailimf_address_list * addr_list; struct mailimf_to * to; r = imap_mailbox_list_to_address_list(env->env_to->to_list, &addr_list); if (r != MAIL_NO_ERROR) { res = r; goto free_list; } to = mailimf_to_new(addr_list); if (to == NULL) { mailimf_address_list_free(addr_list); res = MAIL_ERROR_MEMORY; goto free_list; } field = mailimf_field_new(MAILIMF_FIELD_TO, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, to, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); if (field == NULL) { mailimf_to_free(to); res = MAIL_ERROR_MEMORY; goto free_list; } r = clist_append(list, field); if (r != 0) { mailimf_field_free(field); res = MAIL_ERROR_MEMORY; goto free_list; } } } if (env->env_cc != NULL) { if (env->env_cc->cc_list != NULL) { struct mailimf_address_list * addr_list; struct mailimf_cc * cc; r = imap_mailbox_list_to_address_list(env->env_cc->cc_list, &addr_list); if (r != MAIL_NO_ERROR) { res = r; goto free_list; } cc = mailimf_cc_new(addr_list); if (cc == NULL) { mailimf_address_list_free(addr_list); res = MAIL_ERROR_MEMORY; goto free_list; } field = mailimf_field_new(MAILIMF_FIELD_CC, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, cc, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); if (field == NULL) { mailimf_cc_free(cc); res = MAIL_ERROR_MEMORY; goto free_list; } r = clist_append(list, field); if (r != 0) { mailimf_field_free(field); res = MAIL_ERROR_MEMORY; goto free_list; } } } if (env->env_bcc != NULL) { if (env->env_bcc->bcc_list != NULL) { struct mailimf_address_list * addr_list; struct mailimf_bcc * bcc; r = imap_mailbox_list_to_address_list(env->env_bcc->bcc_list, &addr_list); if (r != MAIL_NO_ERROR) { res = r; goto free_list; } bcc = mailimf_bcc_new(addr_list); if (bcc == NULL) { mailimf_address_list_free(addr_list); res = MAIL_ERROR_MEMORY; goto free_list; } field = mailimf_field_new(MAILIMF_FIELD_BCC, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, bcc, NULL, NULL, NULL, NULL, NULL, NULL, NULL); if (field == NULL) { mailimf_bcc_free(bcc); res = MAIL_ERROR_MEMORY; goto free_list; } r = clist_append(list, field); if (r != 0) { mailimf_field_free(field); res = MAIL_ERROR_MEMORY; goto free_list; } } } if (env->env_in_reply_to != NULL) { struct mailimf_in_reply_to * in_reply_to; size_t cur_token; clist * msg_id_list; cur_token = 0; r = mailimf_msg_id_list_parse(env->env_in_reply_to, strlen(env->env_in_reply_to), &cur_token, &msg_id_list); switch (r) { case MAILIMF_NO_ERROR: in_reply_to = mailimf_in_reply_to_new(msg_id_list); if (in_reply_to == NULL) { clist_foreach(msg_id_list, (clist_func) mailimf_msg_id_free, NULL); clist_free(msg_id_list); res = MAIL_ERROR_MEMORY; goto free_list; } field = mailimf_field_new(MAILIMF_FIELD_IN_REPLY_TO, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, in_reply_to, NULL, NULL, NULL, NULL, NULL); if (field == NULL) { mailimf_in_reply_to_free(in_reply_to); res = MAIL_ERROR_MEMORY; goto free_list; } r = clist_append(list, field); if (r != 0) { mailimf_field_free(field); res = MAIL_ERROR_MEMORY; goto free_list; } break; case MAILIMF_ERROR_PARSE: break; default: res = maildriver_imf_error_to_mail_error(r); goto free_list; } } if (env->env_message_id != NULL) { char * id; struct mailimf_message_id * msg_id; size_t cur_token; cur_token = 0; r = mailimf_msg_id_parse(env->env_message_id, strlen(env->env_message_id), &cur_token, &id); switch (r) { case MAILIMF_NO_ERROR: msg_id = mailimf_message_id_new(id); if (msg_id == NULL) { mailimf_msg_id_free(id); res = MAIL_ERROR_MEMORY; goto free_list; } field = mailimf_field_new(MAILIMF_FIELD_MESSAGE_ID, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, msg_id, NULL, NULL, NULL, NULL, NULL, NULL); if (field == NULL) { mailimf_message_id_free(msg_id); res = MAIL_ERROR_MEMORY; goto free_list; } r = clist_append(list, field); if (r != 0) { mailimf_field_free(field); res = MAIL_ERROR_MEMORY; goto free_list; } break; case MAILIMF_ERROR_PARSE: break; default: res = maildriver_imf_error_to_mail_error(r); goto free_list; } } if (ref_str != NULL) { struct mailimf_references * references; size_t cur_token; cur_token = 0; r = mailimf_references_parse(ref_str, ref_size, &cur_token, &references); switch (r) { case MAILIMF_NO_ERROR: field = mailimf_field_new(MAILIMF_FIELD_REFERENCES, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, references, NULL, NULL, NULL, NULL); if (field == NULL) { mailimf_references_free(references); res = MAIL_ERROR_MEMORY; goto free_list; } r = clist_append(list, field); if (r < 0) { mailimf_field_free(field); res = MAIL_ERROR_MEMORY; goto free_list; } break; case MAILIMF_ERROR_PARSE: break; default: res = maildriver_imf_error_to_mail_error(r); goto free_list; } } fields = mailimf_fields_new(list); if (fields == NULL) { res = MAIL_ERROR_MEMORY; goto free_list; } * result = fields; return MAIL_NO_ERROR; free_list: clist_foreach(list, (clist_func) mailimf_field_free, NULL); clist_free(list); err: return res; } int imap_get_msg_att_info(struct mailimap_msg_att * msg_att, uint32_t * puid, struct mailimap_envelope ** pimap_envelope, char ** preferences, size_t * pref_size, struct mailimap_msg_att_dynamic ** patt_dyn, struct mailimap_body ** pimap_body) { clistiter * item_cur; uint32_t uid; struct mailimap_envelope * imap_envelope; char * references; size_t ref_size; struct mailimap_msg_att_dynamic * att_dyn; struct mailimap_body * imap_body; uid = 0; imap_envelope = NULL; references = NULL; ref_size = 0; att_dyn = NULL; imap_body = NULL; for(item_cur = clist_begin(msg_att->att_list) ; item_cur != NULL ; item_cur = clist_next(item_cur)) { struct mailimap_msg_att_item * item; item = clist_content(item_cur); switch (item->att_type) { case MAILIMAP_MSG_ATT_ITEM_STATIC: switch (item->att_data.att_static->att_type) { case MAILIMAP_MSG_ATT_BODYSTRUCTURE: if (imap_body == NULL) imap_body = item->att_data.att_static->att_data.att_bodystructure; break; case MAILIMAP_MSG_ATT_ENVELOPE: if (imap_envelope == NULL) { imap_envelope = item->att_data.att_static->att_data.att_env; } break; case MAILIMAP_MSG_ATT_UID: uid = item->att_data.att_static->att_data.att_uid; break; case MAILIMAP_MSG_ATT_BODY_SECTION: if (references == NULL) { references = item->att_data.att_static->att_data.att_body_section->sec_body_part; ref_size = item->att_data.att_static->att_data.att_body_section->sec_length; } break; } break; case MAILIMAP_MSG_ATT_ITEM_DYNAMIC: if (att_dyn == NULL) { att_dyn = item->att_data.att_dyn; } break; } } if (puid != NULL) * puid = uid; if (pimap_envelope != NULL) * pimap_envelope = imap_envelope; if (preferences != NULL) * preferences = references; if (pref_size != NULL) * pref_size = ref_size; if (patt_dyn != NULL) * patt_dyn = att_dyn; if (pimap_body != NULL) * pimap_body = imap_body; return MAIL_NO_ERROR; } int imap_fetch_result_to_envelop_list(clist * fetch_result, struct mailmessage_list * env_list) { clistiter * cur; int r; unsigned int i; chash * msg_hash; int res; msg_hash = chash_new(CHASH_DEFAULTSIZE, CHASH_COPYKEY); if (msg_hash == NULL) { res = MAIL_ERROR_MEMORY; goto err; } for(i = 0 ; i < carray_count(env_list->msg_tab) ; i ++) { chashdatum key; chashdatum value; mailmessage * msg; msg = carray_get(env_list->msg_tab, i); key.data = &msg->msg_index; key.len = sizeof(msg->msg_index); value.data = msg; value.len = 0; r = chash_set(msg_hash, &key, &value, NULL); if (r < 0) { res = MAIL_ERROR_MEMORY; goto free_hash; } } for(cur = clist_begin(fetch_result) ; cur != NULL ; cur = clist_next(cur)) { struct mailimap_msg_att * msg_att; uint32_t uid; struct mailimap_envelope * imap_envelope; struct mailimap_msg_att_dynamic * att_dyn; char * references; size_t ref_size; msg_att = clist_content(cur); r = imap_get_msg_att_info(msg_att, &uid, &imap_envelope, &references, &ref_size, &att_dyn, NULL); if (r == MAIL_NO_ERROR) { if (uid != 0) { chashdatum key; chashdatum value; key.data = &uid; key.len = sizeof(uid); r = chash_get(msg_hash, &key, &value); if (r == 0) { mailmessage * msg; msg = value.data; if (imap_envelope != NULL) { struct mailimf_fields * fields; r = imap_env_to_fields(imap_envelope, references, ref_size, &fields); if (r == MAIL_NO_ERROR) { msg->msg_fields = fields; } } if (att_dyn != NULL) { struct mail_flags * flags; r = imap_flags_to_flags(att_dyn, &flags); if (r == MAIL_NO_ERROR) { msg->msg_flags = flags; } } } } } } chash_free(msg_hash); return MAIL_NO_ERROR; free_hash: chash_free(msg_hash); err: return res; } int mailimf_date_time_to_imap_date(struct mailimf_date_time * date, struct mailimap_date ** result) { struct mailimap_date * imap_date; imap_date = mailimap_date_new(date->dt_day, date->dt_month, date->dt_year); if (imap_date == NULL) return MAIL_ERROR_MEMORY; * result = imap_date; return MAIL_NO_ERROR; } #if 0 int mail_search_to_imap_search(struct mail_search_key * key, struct mailimap_search_key ** result) { struct mailimap_search_key * imap_key; char * bcc; struct mailimap_date * before; char * body; char * cc; char * from; struct mailimap_date * on; struct mailimap_date * since; char * subject; char * text; char * to; char * header_name; char * header_value; size_t larger; struct mailimap_search_key * not; struct mailimap_search_key * or1; struct mailimap_search_key * or2; size_t smaller; clist * multiple; int type; clistiter * cur; int r; int res; bcc = NULL; before = NULL; body = NULL; cc = NULL; from = NULL; on = NULL; since = NULL; subject = NULL; text = NULL; to = NULL; header_name = NULL; header_value = NULL; not = NULL; or1 = NULL; or2 = NULL; multiple = NULL; larger = 0; smaller = 0; switch (key->sk_type) { case MAIL_SEARCH_KEY_ALL: type = MAILIMAP_SEARCH_KEY_ALL; break; case MAIL_SEARCH_KEY_ANSWERED: type = MAILIMAP_SEARCH_KEY_ANSWERED; break; case MAIL_SEARCH_KEY_BCC: type = MAILIMAP_SEARCH_KEY_BCC; bcc = strdup(key->sk_bcc); if (bcc == NULL) { res = MAIL_ERROR_MEMORY; goto err; } break; case MAIL_SEARCH_KEY_BEFORE: type = MAILIMAP_SEARCH_KEY_BEFORE; r = mailimf_date_time_to_imap_date(key->sk_before, &before); if (r != MAIL_NO_ERROR) { res = r; goto err; } break; case MAIL_SEARCH_KEY_BODY: type = MAILIMAP_SEARCH_KEY_BODY; body = strdup(key->sk_body); if (body == NULL) { res = MAIL_ERROR_MEMORY; goto err; } break; case MAIL_SEARCH_KEY_CC: type = MAILIMAP_SEARCH_KEY_CC; cc = strdup(key->sk_cc); if (cc == NULL) { res = MAIL_ERROR_MEMORY; goto err; } break; case MAIL_SEARCH_KEY_DELETED: type = MAILIMAP_SEARCH_KEY_DELETED; break; case MAIL_SEARCH_KEY_FLAGGED: type = MAILIMAP_SEARCH_KEY_FLAGGED; break; case MAIL_SEARCH_KEY_FROM: type = MAILIMAP_SEARCH_KEY_FROM; from = strdup(key->sk_from); if (from == NULL) { res = MAIL_ERROR_MEMORY; goto err; } break; case MAIL_SEARCH_KEY_NEW: type = MAILIMAP_SEARCH_KEY_NEW; break; case MAIL_SEARCH_KEY_OLD: type = MAILIMAP_SEARCH_KEY_OLD; break; case MAIL_SEARCH_KEY_ON: type = MAILIMAP_SEARCH_KEY_ON; r = mailimf_date_time_to_imap_date(key->sk_on, &on); if (r != MAIL_NO_ERROR) { res = r; goto err; } break; case MAIL_SEARCH_KEY_RECENT: type = MAILIMAP_SEARCH_KEY_RECENT; break; case MAIL_SEARCH_KEY_SEEN: type = MAILIMAP_SEARCH_KEY_SEEN; break; case MAIL_SEARCH_KEY_SINCE: type = MAILIMAP_SEARCH_KEY_SINCE; r = mailimf_date_time_to_imap_date(key->sk_since, &since); if (r != MAIL_NO_ERROR) { res = r; goto err; } break; case MAIL_SEARCH_KEY_SUBJECT: type = MAILIMAP_SEARCH_KEY_SUBJECT; subject = strdup(key->sk_subject); if (subject == NULL) { res = MAIL_ERROR_MEMORY; goto err; } break; case MAIL_SEARCH_KEY_TEXT: type = MAILIMAP_SEARCH_KEY_TEXT; text = strdup(key->sk_text); if (text == NULL) { res = MAIL_ERROR_MEMORY; goto err; } break; case MAIL_SEARCH_KEY_TO: type = MAILIMAP_SEARCH_KEY_TO; to = strdup(key->sk_to); if (to == NULL) { return MAIL_ERROR_MEMORY; goto err; } break; case MAIL_SEARCH_KEY_UNANSWERED: type = MAILIMAP_SEARCH_KEY_UNANSWERED; break; case MAIL_SEARCH_KEY_UNDELETED: type = MAILIMAP_SEARCH_KEY_UNFLAGGED; break; case MAIL_SEARCH_KEY_UNFLAGGED: type = MAILIMAP_SEARCH_KEY_UNANSWERED; break; case MAIL_SEARCH_KEY_UNSEEN: type = MAILIMAP_SEARCH_KEY_UNSEEN; break; case MAIL_SEARCH_KEY_HEADER: type = MAILIMAP_SEARCH_KEY_HEADER; header_name = strdup(key->sk_header_name); if (header_name == NULL) { res = MAIL_ERROR_MEMORY; goto err; } header_value = strdup(key->sk_header_value); if (header_value == NULL) { free(header_name); res = MAIL_ERROR_MEMORY; goto err; } break; case MAIL_SEARCH_KEY_LARGER: type = MAILIMAP_SEARCH_KEY_LARGER; larger = key->sk_larger; break; case MAIL_SEARCH_KEY_NOT: type = MAILIMAP_SEARCH_KEY_NOT; r = mail_search_to_imap_search(key->sk_not, &not); if (r != MAIL_NO_ERROR) { res = r; goto err; } break; case MAIL_SEARCH_KEY_OR: type = MAILIMAP_SEARCH_KEY_OR; r = mail_search_to_imap_search(key->sk_or1, &or1); if (r != MAIL_NO_ERROR) { res = r; goto err; } r = mail_search_to_imap_search(key->sk_or2, &or2); if (r != MAIL_NO_ERROR) { mailimap_search_key_free(or1); res = r; goto err; } break; case MAIL_SEARCH_KEY_SMALLER: type = MAILIMAP_SEARCH_KEY_SMALLER; smaller = key->sk_smaller; break; case MAIL_SEARCH_KEY_MULTIPLE: multiple = clist_new(); if (multiple == NULL) { res = MAIL_ERROR_MEMORY; goto err; } type = MAILIMAP_SEARCH_KEY_MULTIPLE; for(cur = clist_begin(key->sk_multiple) ; cur != NULL ; cur = clist_next(cur)) { struct mail_search_key * key_elt; struct mailimap_search_key * imap_key_elt; key_elt = clist_content(cur); r = mail_search_to_imap_search(key_elt, &imap_key_elt); if (r != MAIL_NO_ERROR) { res = r; goto free_list; } r = clist_append(multiple, imap_key_elt); if (r != 0) { mailimap_search_key_free(imap_key_elt); res = MAIL_ERROR_MEMORY; goto free_list; } } break; free_list: clist_foreach(multiple, (clist_func) mailimap_search_key_free, NULL); clist_free(multiple); goto err; default: return MAIL_ERROR_INVAL; } imap_key = mailimap_search_key_new(type, bcc, before, body, cc, from, NULL, on, since, subject, text, to, NULL, header_name, header_value, larger, not, or1, or2, NULL, NULL, NULL, smaller, NULL, NULL, multiple); if (imap_key == NULL) { res = MAIL_ERROR_MEMORY; goto free; } * result = imap_key; return MAIL_NO_ERROR; free: if (bcc != NULL) free(bcc); if (before != NULL) mailimap_date_free(before); if (body != NULL) free(body); if (cc != NULL) free(cc); if (from != NULL) free(from); if (on != NULL) mailimap_date_free(on); if (since != NULL) mailimap_date_free(since); if (subject != NULL) free(subject); if (text != NULL) free(text); if (to != NULL) free(to); if (header_name != NULL) free(header_name); if (header_value != NULL) free(header_value); if (not != NULL) mailimap_search_key_free(not); if (or1 != NULL) mailimap_search_key_free(or1); if (or2 != NULL) mailimap_search_key_free(or2); clist_foreach(multiple, (clist_func) mailimap_search_key_free, NULL); clist_free(multiple); err: return res; } #endif int imap_msg_list_to_imap_set(clist * msg_list, struct mailimap_set ** result) { struct mailimap_set * imap_set; clistiter * cur; int previous_valid; uint32_t first_seq; uint32_t previous; int r; int res; imap_set = mailimap_set_new_empty(); if (imap_set == NULL) { res = MAIL_ERROR_MEMORY; goto err; } cur = clist_begin(msg_list); previous_valid = FALSE; first_seq = 0; previous = 0; while (1) { uint32_t * pindex; if ((cur == NULL) && (previous_valid)) { if (first_seq == previous) { r = mailimap_set_add_single(imap_set, first_seq); if (r != MAILIMAP_NO_ERROR) { res = r; goto free; } } else { r = mailimap_set_add_interval(imap_set, first_seq, previous); if (r != MAILIMAP_NO_ERROR) { res = r; goto free; } } break; } pindex = clist_content(cur); if (pindex == NULL) { // Make clang static analyzer happy. break; } if (!previous_valid) { first_seq = * pindex; previous_valid = TRUE; previous = * pindex; cur = clist_next(cur); } else { if (* pindex != previous + 1) { if (first_seq == previous) { r = mailimap_set_add_single(imap_set, first_seq); if (r != MAILIMAP_NO_ERROR) { res = r; goto free; } } else { r = mailimap_set_add_interval(imap_set, first_seq, previous); if (r != MAILIMAP_NO_ERROR) { res = r; goto free; } } previous_valid = FALSE; } else { previous = * pindex; cur = clist_next(cur); } } } * result = imap_set; return MAIL_NO_ERROR; free: mailimap_set_free(imap_set); err: return res; } static int imap_uid_list_to_env_list(mailsession * session, mailmessage_driver * driver, clist * fetch_result, struct mailmessage_list ** result) { clistiter * cur; struct mailmessage_list * env_list; int r; int res; carray * tab; unsigned int i; mailmessage * msg; tab = carray_new(128); if (tab == NULL) { res = MAIL_ERROR_MEMORY; goto err; } for(cur = clist_begin(fetch_result) ; cur != NULL ; cur = clist_next(cur)) { struct mailimap_msg_att * msg_att; clistiter * item_cur; uint32_t uid; size_t size; msg_att = clist_content(cur); uid = 0; size = 0; for(item_cur = clist_begin(msg_att->att_list) ; item_cur != NULL ; item_cur = clist_next(item_cur)) { struct mailimap_msg_att_item * item; item = clist_content(item_cur); switch (item->att_type) { case MAILIMAP_MSG_ATT_ITEM_STATIC: switch (item->att_data.att_static->att_type) { case MAILIMAP_MSG_ATT_UID: uid = item->att_data.att_static->att_data.att_uid; break; case MAILIMAP_MSG_ATT_RFC822_SIZE: size = item->att_data.att_static->att_data.att_rfc822_size; break; } break; } } msg = mailmessage_new(); if (msg == NULL) { res = MAIL_ERROR_MEMORY; goto free_list; } r = mailmessage_init(msg, session, driver, uid, size); if (r != MAIL_NO_ERROR) { res = r; goto free_msg; } r = carray_add(tab, msg, NULL); if (r < 0) { res = MAIL_ERROR_MEMORY; goto free_msg; } } env_list = mailmessage_list_new(tab); if (env_list == NULL) { res = MAIL_ERROR_MEMORY; goto free_list; } * result = env_list; return MAIL_NO_ERROR; free_msg: mailmessage_free(msg); free_list: for(i = 0 ; i < carray_count(tab) ; i++) mailmessage_free(carray_get(tab, i)); err: return res; } /* MAILIMAP_FLAG_FETCH_RECENT, MAILIMAP_FLAG_FETCH_OTHER MAILIMAP_FLAG_ANSWERED, MAILIMAP_FLAG_FLAGGED, MAILIMAP_FLAG_DELETED, MAILIMAP_FLAG_SEEN, MAILIMAP_FLAG_DRAFT, MAILIMAP_FLAG_KEYWORD, MAILIMAP_FLAG_EXTENSION */ int imap_flags_to_flags(struct mailimap_msg_att_dynamic * att_dyn, struct mail_flags ** result) { struct mail_flags * flags; clist * flag_list; clistiter * cur; flags = mail_flags_new_empty(); if (flags == NULL) goto err; flags->fl_flags = 0; flag_list = att_dyn->att_list; if (flag_list != NULL) { for(cur = clist_begin(flag_list) ; cur != NULL ; cur = clist_next(cur)) { struct mailimap_flag_fetch * flag_fetch; flag_fetch = clist_content(cur); if (flag_fetch->fl_type == MAILIMAP_FLAG_FETCH_RECENT) flags->fl_flags |= MAIL_FLAG_NEW; else { char * keyword; int r; switch (flag_fetch->fl_flag->fl_type) { case MAILIMAP_FLAG_ANSWERED: flags->fl_flags |= MAIL_FLAG_ANSWERED; break; case MAILIMAP_FLAG_FLAGGED: flags->fl_flags |= MAIL_FLAG_FLAGGED; break; case MAILIMAP_FLAG_DELETED: flags->fl_flags |= MAIL_FLAG_DELETED; break; case MAILIMAP_FLAG_SEEN: flags->fl_flags |= MAIL_FLAG_SEEN; break; case MAILIMAP_FLAG_DRAFT: keyword = strdup("Draft"); if (keyword == NULL) goto free; r = clist_append(flags->fl_extension, keyword); if (r < 0) { free(keyword); goto free; } break; case MAILIMAP_FLAG_KEYWORD: if (strcasecmp(flag_fetch->fl_flag->fl_data.fl_keyword, "$Forwarded") == 0) { flags->fl_flags |= MAIL_FLAG_FORWARDED; } else { keyword = strdup(flag_fetch->fl_flag->fl_data.fl_keyword); if (keyword == NULL) goto free; r = clist_append(flags->fl_extension, keyword); if (r < 0) { free(keyword); goto free; } } break; case MAILIMAP_FLAG_EXTENSION: /* do nothing */ break; } } } /* MAIL_FLAG_NEW was set for \Recent messages. Correct this flag for \Seen messages by unsetting it. */ if ((flags->fl_flags & MAIL_FLAG_SEEN) && (flags->fl_flags & MAIL_FLAG_NEW)) { flags->fl_flags &= ~MAIL_FLAG_NEW; } } * result = flags; return MAIL_NO_ERROR; free: mail_flags_free(flags); err: return MAIL_ERROR_MEMORY; } int imap_flags_to_imap_flags(struct mail_flags * flags, struct mailimap_flag_list ** result) { struct mailimap_flag * flag; struct mailimap_flag_list * flag_list; int res; clistiter * cur; int r; flag_list = mailimap_flag_list_new_empty(); if (flag_list == NULL) { res = MAIL_ERROR_MEMORY; goto err; } if ((flags->fl_flags & MAIL_FLAG_DELETED) != 0) { flag = mailimap_flag_new_deleted(); if (flag == NULL) { res = MAIL_ERROR_MEMORY; goto free_flag_list; } r = mailimap_flag_list_add(flag_list, flag); if (r != MAILIMAP_NO_ERROR) { mailimap_flag_free(flag); res = MAIL_ERROR_MEMORY; goto free_flag_list; } } if ((flags->fl_flags & MAIL_FLAG_FLAGGED) != 0) { flag = mailimap_flag_new_flagged(); if (flag == NULL) { res = MAIL_ERROR_MEMORY; goto free_flag_list; } r = mailimap_flag_list_add(flag_list, flag); if (r != MAILIMAP_NO_ERROR) { mailimap_flag_free(flag); res = MAIL_ERROR_MEMORY; goto free_flag_list; } } if ((flags->fl_flags & MAIL_FLAG_SEEN) != 0) { flag = mailimap_flag_new_seen(); if (flag == NULL) { res = MAIL_ERROR_MEMORY; goto free_flag_list; } r = mailimap_flag_list_add(flag_list, flag); if (r != MAILIMAP_NO_ERROR) { res = MAIL_ERROR_MEMORY; goto free_flag_list; } } if ((flags->fl_flags & MAIL_FLAG_ANSWERED) != 0) { flag = mailimap_flag_new_answered(); if (flag == NULL) { res = MAIL_ERROR_MEMORY; goto free_flag_list; } r = mailimap_flag_list_add(flag_list, flag); if (r != MAILIMAP_NO_ERROR) { mailimap_flag_free(flag); res = MAIL_ERROR_MEMORY; goto free_flag_list; } } if ((flags->fl_flags & MAIL_FLAG_FORWARDED) != 0) { char * flag_str; flag_str = strdup("$Forwarded"); if (flag_str == NULL) { res = MAIL_ERROR_MEMORY; goto free_flag_list; } flag = mailimap_flag_new_flag_keyword(flag_str); if (flag == NULL) { free(flag_str); res = MAIL_ERROR_MEMORY; goto free_flag_list; } r = mailimap_flag_list_add(flag_list, flag); if (r != MAILIMAP_NO_ERROR) { mailimap_flag_free(flag); res = MAIL_ERROR_MEMORY; goto free_flag_list; } } for(cur = clist_begin(flags->fl_extension) ; cur != NULL ; cur = clist_next(cur)) { char * flag_str; flag_str = clist_content(cur); if (strcasecmp(flag_str, "Draft") == 0) { flag = mailimap_flag_new_draft(); if (flag == NULL) { res = MAIL_ERROR_MEMORY; goto free_flag_list; } r = mailimap_flag_list_add(flag_list, flag); if (r != MAILIMAP_NO_ERROR) { mailimap_flag_free(flag); res = MAIL_ERROR_MEMORY; goto free_flag_list; } } else { flag_str = strdup(flag_str); if (flag_str == NULL) { res = MAIL_ERROR_MEMORY; goto free_flag_list; } flag = mailimap_flag_new_flag_keyword(flag_str); if (flag == NULL) { free(flag_str); res = MAIL_ERROR_MEMORY; goto free_flag_list; } r = mailimap_flag_list_add(flag_list, flag); if (r != MAILIMAP_NO_ERROR) { mailimap_flag_free(flag); res = MAIL_ERROR_MEMORY; goto free_flag_list; } } } * result = flag_list; return MAIL_NO_ERROR; free_flag_list: mailimap_flag_list_free(flag_list); err: return res; } static int flags_to_imap_flags(struct mail_flags * flags, struct mailimap_store_att_flags ** result) { struct mailimap_flag_list * flag_list; struct mailimap_store_att_flags * att_flags; int res; int r; r = imap_flags_to_imap_flags(flags, &flag_list); if (r != MAIL_NO_ERROR) { res = r; goto err; } att_flags = mailimap_store_att_flags_new_set_flags_silent(flag_list); if (att_flags == NULL) { res = MAIL_ERROR_MEMORY; goto free_flag_list; } * result = att_flags; return MAIL_NO_ERROR; free_flag_list: mailimap_flag_list_free(flag_list); err: return res; } static int imap_fetch_result_to_flags(clist * fetch_result, uint32_t indx, struct mail_flags ** result) { clistiter * cur; int r; for(cur = clist_begin(fetch_result) ; cur != NULL ; cur = clist_next(cur)) { struct mailimap_msg_att * msg_att; clistiter * item_cur; uint32_t uid; struct mailimap_msg_att_dynamic * att_dyn; msg_att = clist_content(cur); uid = 0; att_dyn = NULL; for(item_cur = clist_begin(msg_att->att_list) ; item_cur != NULL ; item_cur = clist_next(item_cur)) { struct mailimap_msg_att_item * item; item = clist_content(item_cur); if (item->att_type == MAILIMAP_MSG_ATT_ITEM_STATIC) { switch (item->att_data.att_static->att_type) { case MAILIMAP_MSG_ATT_UID: uid = item->att_data.att_static->att_data.att_uid; break; } } else if (item->att_type == MAILIMAP_MSG_ATT_ITEM_DYNAMIC) { if (att_dyn == NULL) { att_dyn = item->att_data.att_dyn; } } } if (uid != 0) { if (uid == indx) { struct mail_flags * flags; if (att_dyn != NULL) { r = imap_flags_to_flags(att_dyn, &flags); if (r == MAIL_NO_ERROR) { * result = flags; return MAIL_NO_ERROR; } } } } } return MAIL_ERROR_MSG_NOT_FOUND; } int imap_fetch_flags(mailimap * imap, uint32_t indx, struct mail_flags ** result) { struct mailimap_fetch_att * fetch_att; struct mailimap_fetch_type * fetch_type; struct mailimap_set * set; int r; int res; clist * fetch_result; struct mail_flags * flags; fetch_type = mailimap_fetch_type_new_fetch_att_list_empty(); if (fetch_type == NULL) { res = MAIL_ERROR_MEMORY; goto err; } fetch_att = mailimap_fetch_att_new_uid(); if (fetch_att == NULL) { res = MAIL_ERROR_MEMORY; goto free_fetch_type; } r = mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att); if (r != MAILIMAP_NO_ERROR) { mailimap_fetch_att_free(fetch_att); res = MAIL_ERROR_MEMORY; goto free_fetch_type; } fetch_att = mailimap_fetch_att_new_flags(); if (fetch_att == NULL) { res = MAIL_ERROR_MEMORY; goto free_fetch_type; } r = mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att); if (r != MAILIMAP_NO_ERROR) { mailimap_fetch_att_free(fetch_att); res = MAIL_ERROR_MEMORY; goto free_fetch_type; } set = mailimap_set_new_single(indx); if (set == NULL) { res = MAIL_ERROR_MEMORY; goto free_fetch_type; } r = mailimap_uid_fetch(imap, set, fetch_type, &fetch_result); mailimap_fetch_type_free(fetch_type); mailimap_set_free(set); switch (r) { case MAILIMAP_NO_ERROR: break; default: return imap_error_to_mail_error(r); } flags = NULL; r = imap_fetch_result_to_flags(fetch_result, indx, &flags); mailimap_fetch_list_free(fetch_result); if (r != MAIL_NO_ERROR) { res = r; goto err; } * result = flags; return MAIL_NO_ERROR; free_fetch_type: mailimap_fetch_type_free(fetch_type); err: return res; } int imap_store_flags(mailimap * imap, uint32_t first, uint32_t last, struct mail_flags * flags) { struct mailimap_store_att_flags * att_flags; struct mailimap_set * set; int r; int res; set = mailimap_set_new_interval(first, last); if (set == NULL) { res = MAIL_ERROR_MEMORY; goto err; } r = flags_to_imap_flags(flags, &att_flags); if (r != MAIL_NO_ERROR) { res = r; goto free_set; } r = mailimap_uid_store(imap, set, att_flags); if (r != MAILIMAP_NO_ERROR) { res = imap_error_to_mail_error(r); goto free_flag; } mailimap_store_att_flags_free(att_flags); mailimap_set_free(set); return MAIL_NO_ERROR; free_flag: mailimap_store_att_flags_free(att_flags); free_set: mailimap_set_free(set); err: return res; } int imap_get_messages_list(mailimap * imap, mailsession * session, mailmessage_driver * driver, uint32_t first_index, struct mailmessage_list ** result) { struct mailmessage_list * env_list; int r; struct mailimap_fetch_att * fetch_att; struct mailimap_fetch_type * fetch_type; struct mailimap_set * set; clist * fetch_result; int res; set = mailimap_set_new_interval(first_index, 0); if (set == NULL) { res = MAIL_ERROR_MEMORY; goto err; } fetch_type = mailimap_fetch_type_new_fetch_att_list_empty(); if (fetch_type == NULL) { res = MAIL_ERROR_MEMORY; goto free_set; } fetch_att = mailimap_fetch_att_new_uid(); if (fetch_att == NULL) { res = MAIL_ERROR_MEMORY; goto free_fetch_type; } r = mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att); if (r != MAILIMAP_NO_ERROR) { mailimap_fetch_att_free(fetch_att); res = MAIL_ERROR_MEMORY; goto free_fetch_type; } fetch_att = mailimap_fetch_att_new_rfc822_size(); if (fetch_att == NULL) { res = MAIL_ERROR_MEMORY; goto free_fetch_type; } r = mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att); if (r != MAILIMAP_NO_ERROR) { mailimap_fetch_att_free(fetch_att); res = MAIL_ERROR_MEMORY; goto free_fetch_type; } r = mailimap_uid_fetch(imap, set, fetch_type, &fetch_result); mailimap_fetch_type_free(fetch_type); mailimap_set_free(set); if (r != MAILIMAP_NO_ERROR) { res = imap_error_to_mail_error(r); goto err; } env_list = NULL; r = imap_uid_list_to_env_list(session, driver, fetch_result, &env_list); mailimap_fetch_list_free(fetch_result); * result = env_list; return MAIL_NO_ERROR; free_fetch_type: mailimap_fetch_type_free(fetch_type); free_set: mailimap_set_free(set); err: return res; } static void generate_key_from_message(char * key, size_t size, mailmessage * msg_info, int type) { switch (type) { case MAILIMAP_MSG_ATT_RFC822: snprintf(key, size, "%s-rfc822", msg_info->msg_uid); break; case MAILIMAP_MSG_ATT_RFC822_HEADER: snprintf(key, size, "%s-rfc822-header", msg_info->msg_uid); break; case MAILIMAP_MSG_ATT_RFC822_TEXT: snprintf(key, size, "%s-rfc822-text", msg_info->msg_uid); break; case MAILIMAP_MSG_ATT_ENVELOPE: snprintf(key, size, "%s-envelope", msg_info->msg_uid); break; } } int imapdriver_get_cached_envelope(struct mail_cache_db * cache_db, MMAPString * mmapstr, mailsession * session, mailmessage * msg, struct mailimf_fields ** result) { int r; struct mailimf_fields * fields; int res; char keyname[PATH_MAX]; generate_key_from_message(keyname, PATH_MAX, msg, MAILIMAP_MSG_ATT_ENVELOPE); r = generic_cache_fields_read(cache_db, mmapstr, keyname, &fields); if (r != MAIL_NO_ERROR) { res = r; goto err; } * result = fields; return MAIL_NO_ERROR; err: return res; } int imapdriver_write_cached_envelope(struct mail_cache_db * cache_db, MMAPString * mmapstr, mailsession * session, mailmessage * msg, struct mailimf_fields * fields) { char keyname[PATH_MAX]; int r; int res; generate_key_from_message(keyname, PATH_MAX, msg, MAILIMAP_MSG_ATT_ENVELOPE); r = generic_cache_fields_write(cache_db, mmapstr, keyname, fields); if (r != MAIL_NO_ERROR) { res = r; goto err; } return MAIL_NO_ERROR; err: return res; }
33,853
https://github.com/SudhiR3369/FeedbackRepository/blob/master/SageFrame/Modules/PageRating/RatingSettings.ascx.cs
Github Open Source
Open Source
MIT
2,018
FeedbackRepository
SudhiR3369
C#
Code
45
171
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using SageFrame.Web; public partial class Modules_PageRating_RatingSettings :BaseAdministrationUserControl { public int userModuleID = 0; protected void Page_Load(object sender, EventArgs e) { userModuleID = Int32.Parse(SageUserModuleID); if (!IsPostBack) { IncludeJs("PageRatingSetting", "/Modules/PageRating/js/RatingSetting.js" , "/js/jquery.validate.js"); } } }
8,786
https://github.com/sprudhom/krakatoa/blob/master/gcov2covDB/src/main/java/gcov2covDB/Gcov2FuncCoverageDB.java
Github Open Source
Open Source
Apache-2.0
2,016
krakatoa
sprudhom
Java
Code
1,500
5,973
package gcov2covDB; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.esotericsoftware.yamlbeans.YamlException; import com.esotericsoftware.yamlbeans.YamlReader; import com.opencsv.CSVWriter; public class Gcov2FuncCoverageDB { private static final boolean verbose = false; private static final String TESTS_CSV = "tests.csv"; private static final String TEST_GROUPS_CSV = "test_groups.csv"; private static final String SOURCE_FILES_CSV = "source_files.csv"; private static final String FUNCTIONS_CSV = "functions.csv"; private static final String FUNCCOV_CSV = "funccov.csv"; private static final String NEW_LINE_DELIMITER = "\n"; Vector<Pattern> m_regex_func_patterns = new Vector<Pattern>(); Map<String, Integer> m_source_files_map = new HashMap<String, Integer>(); Map<String, FunctionsTableEntry> m_functions_map = new HashMap<String, FunctionsTableEntry>(); Map<String, String> m_mangled_func_map = new HashMap<String, String>(); Map<String, Integer> m_test_mangled_to_id_map = new HashMap<String, Integer>(); Map<String, TestTableEntry> m_tests_map = new HashMap<String, TestTableEntry>(); Map<Integer, String> m_test_group_names_map = new HashMap<Integer, String>(); Pattern m_func_pattern = Pattern .compile("^function\\s+(.*?)\\s+called\\s+(\\d+)\\s+returned\\s+(\\d+)%\\s+blocks\\s+executed\\s+(\\d+)%"); Pattern m_file_pattern = Pattern.compile("\\.cc\\.gcov$"); int m_func_map_next_index = 1; int m_source_files_map_next_index =1 ; /* * tests mira_summary.yaml function_map.csv func_filter.yaml */ public static void main(String[] args) { String testDataDirectory = null; String mangled_tests_file = null; String mangled_func_file = null; String filter_file = null; if (args.length == 0 ) { System.err.println("No parameters passed. Running with default test values."); testDataDirectory = "tests"; mangled_tests_file = "mira_summary.yaml"; mangled_func_file = "function_map.csv"; filter_file = "func_filter.yaml"; } else { if (args.length != 4) { System.err .println("usage: cmd testDataDirectory mangled_tests_file mangled_func_file filter_file"); System.exit(1); } testDataDirectory = args[0]; mangled_tests_file = args[1]; mangled_func_file = args[2]; filter_file = args[3]; } System.out.println(" testDataDirectory("+testDataDirectory+"), mangled_tests_file("+mangled_tests_file+"), mangled_func_file("+mangled_func_file+"), filter_file("+filter_file+")"); Gcov2FuncCoverageDB gcov2covDB = new Gcov2FuncCoverageDB(testDataDirectory, mangled_tests_file, mangled_func_file, filter_file); gcov2covDB.generateOtherCSVs(); } public Gcov2FuncCoverageDB( String testDataDirectory, String mangled_tests_file, String mangled_func_file, String filter_file){ Vector<String> regexes = parseRegexYaml(filter_file); for (String regexp : regexes) { Pattern regex_func_pattern = Pattern.compile(regexp); m_regex_func_patterns.add(regex_func_pattern); } cleanCsvFiles(); try { initMaps(testDataDirectory, mangled_tests_file, mangled_func_file); } catch (IOException e) { e.printStackTrace(); } } private void initMaps(String directory, String mangled_tests_file, String mangled_func_file) throws IOException { File folder = new File(directory); /* Table Column Headers */ String test_mangled; /* File Reader variables */ FileWriter funccovWriter = null; funccovWriter = new FileWriter(FUNCCOV_CSV); funccovWriter.append("test_id,function_id,visited"); funccovWriter.append(NEW_LINE_DELIMITER); /* Fill the mangled-to-demangled test/function maps */ parseTestInfoYaml(mangled_tests_file); parseFunctionMangledDemangledNameCsv(mangled_func_file); for (File subfolder : folder.listFiles()) { // Assumes directory name is test mangled name test_mangled = subfolder.getName(); if (null == test_mangled){ System.err.println("Could not get path for " + subfolder.toString()); System.exit(1); } Integer tests_map_index = m_test_mangled_to_id_map.get(test_mangled); if (tests_map_index == null){ System.err.println("Could not get test id for " + test_mangled); System.exit(1); } if (subfolder.isDirectory()) { /* * Directory parser fills the other two hash maps and generates * the funccov csv file */ processDirectoryAndSubdirectories(subfolder, tests_map_index, test_mangled, funccovWriter); } } funccovWriter.flush(); funccovWriter.close(); System.out.println(FUNCCOV_CSV + " created successfully."); } public void generateOtherCSVs() { generateTestGroupsCsv(TEST_GROUPS_CSV); generateTestsCsv(TESTS_CSV); generateSourceFilesCsv(SOURCE_FILES_CSV); generateFunctionsCsv(FUNCTIONS_CSV); System.out.print("\nDone!"); } private void parseTestInfoYaml(String yamlFile) { try { int test_index = 0; int test_group_index = 0; YamlReader reader = new YamlReader(new FileReader(yamlFile)); Object object = reader.read(); ArrayList<Map> list = (ArrayList<Map>) object; ArrayList<Map> list_nested = null; for (int i = 0; i < list.size(); i++) { Object test_group_name = list.get(i).get("name"); if ((null == test_group_name) ){ System.err.println("No test group name for test group: Test #"+test_group_index+" in " + yamlFile); System.exit(1); } test_group_index++; m_test_group_names_map.put(test_group_index, test_group_name.toString()); list_nested = (ArrayList<Map>) list.get(i).get("testcases"); for (int j = 0; j < list_nested.size(); j++) { Object mangled_name = list_nested.get(j).get("mangled_name"); Object name = list_nested.get(j).get("name"); Object path = list_nested.get(j).get("path"); Object execution_time_secs = list_nested.get(j).get("execution_time_secs"); Object passed = list_nested.get(j).get("pass"); Object failed = list_nested.get(j).get("fail"); test_index++; // Unique Test ID for each entry. if ((null == mangled_name) || (null==name)|| (null==path)|| (null==execution_time_secs)|| (null==passed)|| (null==failed)){ System.err.println("Test #"+test_index+", missing one of {mangled_name, name, path, execution_time_secs, pass, fail} in " + yamlFile); System.exit(1); } TestTableEntry entry = new TestTableEntry( test_index, test_group_index, mangled_name.toString(), name.toString(), path.toString(), execution_time_secs.toString(), passed.toString(), failed.toString() ); m_tests_map.put(mangled_name.toString(), entry); m_test_mangled_to_id_map.put(mangled_name.toString(), test_index); } } } catch (FileNotFoundException e) { System.err.println("Error opening " + yamlFile); e.printStackTrace(); System.exit(1); } catch (YamlException e) { System.err.println("Yaml Error encountered"); e.printStackTrace(); System.exit(1); } } /** * * @param fileName * @return vector of regular expression strings */ private static Vector<String> parseRegexYaml(String fileName) { Vector<String> regexes = new Vector<String>(); ArrayList<Map> list = null; HashMap<String, String> holder = null; try { YamlReader reader = new YamlReader(new FileReader(fileName)); Object object = reader.read(); list = (ArrayList<Map>) object; for (int i = 0; i < list.size(); i++) { holder = (HashMap<String, String>) list.get(i); String regexp = holder.get("regex"); regexes.add(regexp); System.out.println("function name regexp("+regexp+")"); } } catch (FileNotFoundException e) { System.err.println("Error opening " + fileName); System.exit(1); } catch (YamlException e) { System.err.println("Yaml Error encountered"); System.exit(1); } return regexes; } private void parseFunctionMangledDemangledNameCsv( String csvFile) { Integer count =0; Integer duplicateCount =0; try {// OpenCSV CSVReader doesn't handle large csv files and fails silently... Use BufferedReader instead. System.out.println("parsing: " + csvFile ); FileInputStream istream = new FileInputStream(csvFile); InputStreamReader iReader = new InputStreamReader(istream); BufferedReader buffReader = new BufferedReader(iReader); String line= null; while ((line = buffReader.readLine()) != null) { int secondQuotes = line.indexOf('"', 1); String key = line.substring(1, secondQuotes); int thirdQuotes = line.indexOf('"', secondQuotes+1); String value = line.substring(thirdQuotes+1, line.length()-1); //-1 to exclude closing quotes String prevValue = m_mangled_func_map.put(key, value); //System.out.println("key("+key+")"+"value("+value+")" ); if (null != prevValue){ duplicateCount++; } count++; } buffReader.close(); } catch (FileNotFoundException e) { System.err.println("Error opening " + csvFile); System.exit(1); } catch (IOException e) { System.err.println("Error parsing " + csvFile); System.exit(1); } System.out.println("parsed "+ count+ " lines from " + csvFile+ ", duplicate rows("+duplicateCount+")"); } public void processDirectoryAndSubdirectories(File file, int test_id, String test_mangled, FileWriter funccovWriter) throws IOException { if (file.isDirectory()) { for (File subfolder : file.listFiles()) { processDirectoryAndSubdirectories(subfolder, test_id, test_mangled, funccovWriter); } } else /* if(file.isFile()) */{ // normalize all file paths with "/" instead of "\" as a delimiter: String normalizedFileName = file.getPath().replaceAll("\\\\", "/"); // ignore files that don't end with .cc.gcov: Matcher file_matcher = m_file_pattern.matcher(file.getAbsolutePath()); if (file_matcher.find()) { Integer source_file_id = new Integer(0); // Remove .gcov suffix: String fullFileName = normalizedFileName.substring(0, normalizedFileName.lastIndexOf('.')); // Remove the prefix up to the mangled name (excluding the test name) String source_file = "."+fullFileName.substring(fullFileName.indexOf(test_mangled) + test_mangled.length()); source_file_id = m_source_files_map.get(source_file); if (source_file_id == null){ m_source_files_map.put(source_file, m_source_files_map_next_index); source_file_id = m_source_files_map_next_index; m_source_files_map_next_index++; } if (verbose){ System.err.println("Processing file("+ file.getPath() + "), source_file("+source_file+"), test_mangled("+test_mangled+"),");} BufferedReader inputStream = new BufferedReader(new FileReader(file)); int source_line = 1; String line = null; while ((line = inputStream.readLine()) != null) { Matcher func_matcher = m_func_pattern.matcher(line); if (func_matcher.find()) { Integer visited = (Integer.parseInt(func_matcher.group(2))>0) ? 1: 0 ; String func_mangled = func_matcher.group(1); boolean ignoreFunc = false; for (Pattern regex_func_pattern: m_regex_func_patterns) { Matcher regex_func_matcher = regex_func_pattern.matcher(func_mangled); if (regex_func_matcher.find()) { ignoreFunc = true; break; } } if (!ignoreFunc) { FunctionsTableEntry functionEntry = m_functions_map.get(func_mangled); Integer function_id = null; if (null == functionEntry){ String func_demangled = m_mangled_func_map .get(func_mangled); function_id = m_func_map_next_index; FunctionsTableEntry func_table_entry = new FunctionsTableEntry(function_id, source_file_id, source_line, func_mangled, func_demangled); m_functions_map.put(func_mangled, func_table_entry); m_func_map_next_index++; }else { function_id = functionEntry.id; } funccovWriter.append(test_id + "," + function_id + "," + visited); funccovWriter.append(NEW_LINE_DELIMITER); } } source_line++; } inputStream.close(); }else{ if(verbose) {System.out.println("Ignoring file: " + file.getPath());} } } } public static void cleanCsvFiles() { File file = new File(TESTS_CSV); if (file.delete()) { System.out.println(file.getName() + " removed."); } file = new File(SOURCE_FILES_CSV); if (file.delete()) { System.out.println(file.getName() + " removed."); } file = new File(FUNCTIONS_CSV); if (file.delete()) { System.out.println(file.getName() + " removed."); } file = new File(FUNCCOV_CSV); if (file.delete()) { System.out.println(file.getName() + " removed."); } } public void generateTestsCsv(String fileName) { final String file_header = "id,group_id,mangled_name,name,path,execution_time_secs,passed,failed"; CSVWriter writer = null; String[] record = file_header.split(","); try { writer = new CSVWriter(new FileWriter(fileName)); writer.writeNext(record); for (Entry<String, TestTableEntry> entry : m_tests_map.entrySet()) { record[0] = entry.getValue().id.toString(); record[1] = entry.getValue().group_id.toString(); record[2] = entry.getValue().mangled_name; record[3] = entry.getValue().name; record[4] = entry.getValue().path; record[5] = entry.getValue().execution_time_secs; record[6] = entry.getValue().passed; record[7] = entry.getValue().failed; writer.writeNext(record); } System.out.println(fileName + " created successfully."); } catch (IOException e) { System.out.println("Error generating " + fileName); System.exit(1); } finally { try { writer.flush(); writer.close(); } catch (IOException e) { System.out.println("Error closing " + fileName); System.exit(1); } } } public void generateTestGroupsCsv(String fileName) { final String file_header = "id,name"; CSVWriter writer = null; String[] record = file_header.split(","); try { writer = new CSVWriter(new FileWriter(fileName)); writer.writeNext(record); for (Entry<Integer, String> entry : m_test_group_names_map.entrySet()) { record[0] = entry.getKey().toString(); record[1] = entry.getValue(); writer.writeNext(record); } System.out.println(fileName + " created successfully."); } catch (IOException e) { System.out.println("Error generating " + fileName); System.exit(1); } finally { try { writer.flush(); writer.close(); } catch (IOException e) { System.out.println("Error closing " + fileName); System.exit(1); } } } public void generateSourceFilesCsv(String fileName) { final String file_header = "id,name"; CSVWriter writer = null; String[] record = file_header.split(","); try { writer = new CSVWriter(new FileWriter(fileName)); writer.writeNext(record); for (Entry<String, Integer> entry : m_source_files_map.entrySet()) { record[0] = String.valueOf(entry.getValue()); record[1] = entry.getKey(); writer.writeNext(record); } System.out.println(fileName + " created successfully."); } catch (IOException e) { System.err.println("Error generating " + fileName); System.exit(1); } finally { try { writer.flush(); writer.close(); } catch (IOException e) { System.err.println("Error closing " + fileName); System.exit(1); } } } public void generateFunctionsCsv(String fileName) { final String file_header = "id,source_file_id,source_line,mangled_name,name"; CSVWriter writer = null; String[] record = file_header.split(","); try { writer = new CSVWriter(new FileWriter(fileName)); writer.writeNext(record); for (Entry<String, FunctionsTableEntry> entry : m_functions_map.entrySet()) { record[0] = String.valueOf(entry.getValue().id); record[1] = String.valueOf(entry.getValue().source_id); record[2] = String.valueOf(entry.getValue().line_number); record[3] = entry.getValue().mangled_name; record[4] = entry.getValue().demangled_name; writer.writeNext(record); } System.out.println(fileName + " created successfully."); } catch (IOException e) { System.err.println("Error generating " + fileName); System.exit(1); } finally { try { writer.flush(); writer.close(); } catch (IOException e) { System.err.println("Error closing " + fileName); System.exit(1); } } } }
45,820
https://github.com/garora/Audit.NET/blob/master/test/Audit.EntityFramework.Full.UnitTest/ComplexTypeTests.cs
Github Open Source
Open Source
MIT
2,022
Audit.NET
garora
C#
Code
120
568
using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Audit.EntityFramework.Full.UnitTest { [TestFixture] [Category("LocalDb")] public class ComplexTypeTests { [SetUp] public void SetUp() { } [Test] public void Test_ComplexType_Logging() { var evs = new List<EntityFrameworkEvent>(); Audit.Core.Configuration.Setup() .UseDynamicProvider(config => config.OnInsert(ev => evs.Add(ev.GetEntityFrameworkEvent()))); // Reset previous config Audit.EntityFramework.Configuration.Setup() .ForAnyContext().Reset(); Audit.EntityFramework.Configuration.Setup() .ForContext<WorkContext>().Reset(); Audit.EntityFramework.Configuration.Setup() .ForAnyContext(_ => _.IncludeEntityObjects()); using (var context = new WorkContext()) { var employee = context.Set<Employee>().FirstOrDefault(); employee.Address.City = "City 2"; context.SaveChanges(); } Assert.AreEqual(2, evs.Count); Assert.AreEqual(1, evs[0].Entries.Count); Assert.AreEqual(1, evs[1].Entries.Count); Assert.AreEqual("Insert", evs[0].Entries[0].Action); Assert.AreEqual("Update", evs[1].Entries[0].Action); Assert.IsTrue(evs[0].Entries[0].ColumnValues["Address"] is Address); Assert.AreEqual("City 1", (evs[0].Entries[0].ColumnValues["Address"] as Address).City); Assert.AreEqual("City 2", (evs[1].Entries[0].ColumnValues["Address"] as Address).City); Assert.IsTrue((evs[1].Entries[0].Changes.Any(ch => ch.ColumnName == "Address" && (ch.OriginalValue as Address)?.City == "City 1"))); Assert.IsTrue((evs[1].Entries[0].Changes.Any(ch => ch.ColumnName == "Address" && (ch.NewValue as Address)?.City == "City 2"))); } } }
40,809
https://github.com/vjk10/notes/blob/master/lib/android/widgets/number_text_field.dart
Github Open Source
Open Source
MIT
2,022
notes
vjk10
Dart
Code
435
1,609
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; class NumberTextField extends StatefulWidget { final TextEditingController? controller; final FocusNode? focusNode; final int min; final int max; final int step; final double arrowsWidth; final double arrowsHeight; final EdgeInsets contentPadding; final double borderWidth; final ValueChanged<int?>? onChanged; const NumberTextField({ Key? key, this.controller, this.focusNode, this.min = 0, this.max = 999, this.step = 1, this.arrowsWidth = 24, this.arrowsHeight = kMinInteractiveDimension, this.contentPadding = const EdgeInsets.symmetric(horizontal: 8), this.borderWidth = 2, this.onChanged, }) : super(key: key); @override State<StatefulWidget> createState() => _NumberTextFieldState(); } class _NumberTextFieldState extends State<NumberTextField> { late TextEditingController _controller; late FocusNode _focusNode; bool _canGoUp = false; bool _canGoDown = false; @override void initState() { super.initState(); _controller = widget.controller ?? TextEditingController(); _focusNode = widget.focusNode ?? FocusNode(); _updateArrows(int.tryParse(_controller.text)); } @override void didUpdateWidget(covariant NumberTextField oldWidget) { super.didUpdateWidget(oldWidget); _controller = widget.controller ?? _controller; _focusNode = widget.focusNode ?? _focusNode; _updateArrows(int.tryParse(_controller.text)); } @override Widget build(BuildContext context) => TextField( controller: _controller, focusNode: _focusNode, textInputAction: TextInputAction.done, keyboardType: TextInputType.number, maxLength: widget.max.toString().length + (widget.min.isNegative ? 1 : 0), decoration: InputDecoration( counterText: '', isDense: true, filled: true, border: OutlineInputBorder( borderRadius: BorderRadius.circular(10), ), errorBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(10), ), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(10), ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(10), ), disabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(10), ), focusedErrorBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(10), ), fillColor: Theme.of(context).colorScheme.surface, contentPadding: widget.contentPadding.copyWith(right: 0), suffixIconConstraints: BoxConstraints( maxHeight: widget.arrowsHeight, maxWidth: widget.arrowsWidth + widget.contentPadding.right), suffixIcon: Container( decoration: BoxDecoration( borderRadius: BorderRadius.only( topRight: Radius.circular(widget.borderWidth), bottomRight: Radius.circular(widget.borderWidth))), clipBehavior: Clip.antiAlias, alignment: Alignment.centerRight, margin: EdgeInsets.only( top: widget.borderWidth, right: widget.borderWidth, bottom: widget.borderWidth, left: widget.contentPadding.right), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Expanded( child: Material( type: MaterialType.transparency, child: InkWell( child: Opacity( opacity: _canGoUp ? 1 : .5, child: const Icon(Icons.arrow_drop_up)), onTap: _canGoUp ? () => _update(true) : null))), Expanded( child: Material( type: MaterialType.transparency, child: InkWell( child: Opacity( opacity: _canGoDown ? 1 : .5, child: const Icon(Icons.arrow_drop_down)), onTap: _canGoDown ? () => _update(false) : null))), ]))), maxLines: 1, onChanged: (value) { final intValue = int.tryParse(value); widget.onChanged?.call(intValue); _updateArrows(intValue); }, inputFormatters: [_NumberTextInputFormatter(widget.min, widget.max)]); void _update(bool up) { var intValue = int.tryParse(_controller.text); intValue == null ? intValue = 0 : intValue += up ? widget.step : -widget.step; _controller.text = intValue.toString(); _updateArrows(intValue); _focusNode.requestFocus(); } void _updateArrows(int? value) { final canGoUp = value == null || value < widget.max; final canGoDown = value == null || value > widget.min; if (_canGoUp != canGoUp || _canGoDown != canGoDown) { setState(() { _canGoUp = canGoUp; _canGoDown = canGoDown; }); } } } class _NumberTextInputFormatter extends TextInputFormatter { final int min; final int max; _NumberTextInputFormatter(this.min, this.max); @override TextEditingValue formatEditUpdate( TextEditingValue oldValue, TextEditingValue newValue) { if (const ['-', ''].contains(newValue.text)) return newValue; final intValue = int.tryParse(newValue.text); if (intValue == null) return oldValue; if (intValue < min) return newValue.copyWith(text: min.toString()); if (intValue > max) return newValue.copyWith(text: max.toString()); return newValue.copyWith(text: intValue.toString()); } }
49,063
https://github.com/bkoruznjak/Space-Race/blob/master/app/src/main/java/hr/from/bkoruznjak/spacerace/view/SRView.java
Github Open Source
Open Source
MIT
null
Space-Race
bkoruznjak
Java
Code
1,421
5,418
package hr.from.bkoruznjak.spacerace.view; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.util.Log; import android.view.HapticFeedbackConstants; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.util.UUID; import hr.from.bkoruznjak.spacerace.R; import hr.from.bkoruznjak.spacerace.contants.BitmapSizeConstants; import hr.from.bkoruznjak.spacerace.contants.PreferenceKeyConstants; import hr.from.bkoruznjak.spacerace.model.EnemyShip; import hr.from.bkoruznjak.spacerace.model.Explosion; import hr.from.bkoruznjak.spacerace.model.Planet; import hr.from.bkoruznjak.spacerace.model.SpaceDust; import hr.from.bkoruznjak.spacerace.model.SpaceShip; import hr.from.bkoruznjak.spacerace.model.firebase.HighScore; /** * Created by bkoruznjak on 26/01/2017. */ public class SRView extends SurfaceView implements Runnable, SRControl, GameControl { private static final int TARGET_FPS = 60; //this is just a user safety feature to block immediate restart for 5secs after game ends. private static final int GAME_RESET_TIMEOUT_IN_MILLIS = 1500; private static final int NUMBER_OF_ENEMIES = 3; final float mScale; private Context mContext; private SharedPreferences mPrefs; private SharedPreferences.Editor mEditor; private EnemyShip mEnemy1; private EnemyShip mEnemy2; private EnemyShip mEnemy3; private SpaceDust[] mDustArray; private Thread gameThread = null; private SurfaceHolder mSurfaceHolder; private Canvas mScreenCanvas; private Paint mBackgroundColor; private Paint mStarColor; private Paint mHudColor; private SpaceShip mPlayerShip; private Planet mPlanet; private Bitmap mImgLife; private Bitmap mImgExplosionSprite; private float mTargetFrameDrawTime; private float mDistanceCovered; private boolean highScoreAchieved; private long mPlayerScore; private long mTimeStartCurrentFrame; private long mDelta; private long mTimeEndCurrentFrame; private long mTimeSleepInMillis; private long mTimeTaken; private long mTimeResetDelayStart; private long mTimeResetDelayEnd; private double mTimeTakenDecimal; private long mTimeStarted; private long mHighScore; private int mScreenX; private int mScreenY; private int mSpecialEffectsIndex; private Explosion[] mExplosionArray; //hud related constants private float hudGameOverSize; private float hudGameOverY; private float hudHighestScoreSize; private float hudHighestScoreY; private float hudTimeSize; private float hudTimeY; private float hudDistanceCoveredSize; private float hudDistanceCoveredY; private float hudTapToRetrySize; private float hudTapToRetryY; private float hudHighScoreSize; private float hudHighScoreY; private float hudRecordScoreSize; private float hudRecordScoreY; private boolean gameEnded; private volatile boolean playing; public SRView(Context context, int x, int y) { super(context); this.mContext = context; // Get a reference to a file called HiScores. // If id doesn't exist one is created mPrefs = context.getSharedPreferences(PreferenceKeyConstants.KEY_SHARED_PREFERENCES, context.MODE_PRIVATE); mScreenX = x; mScreenY = y; this.mTargetFrameDrawTime = 1000f / TARGET_FPS; this.mSurfaceHolder = getHolder(); this.mBackgroundColor = new Paint(); this.mStarColor = new Paint(); this.mHudColor = new Paint(); this.mExplosionArray = new Explosion[NUMBER_OF_ENEMIES]; mScale = context.getResources().getDisplayMetrics().density; // init the HUD hudGameOverSize = (35 * mScale) + 0.5f; hudGameOverY = (75 * mScale) + 0.5f; hudHighestScoreSize = (15 * mScale) + 0.5f; hudHighestScoreY = (120 * mScale) + 0.5f; hudTimeSize = (15 * mScale) + 0.5f; hudTimeY = (145 * mScale) + 0.5f; hudDistanceCoveredSize = (15 * mScale) + 0.5f; hudDistanceCoveredY = (170 * mScale) + 0.5f; hudTapToRetrySize = (30 * mScale) + 0.5f; hudTapToRetryY = (230 * mScale) + 0.5f; hudHighScoreSize = (40 * mScale) + 0.5f; hudHighScoreY = (300 * mScale) + 0.5f; hudRecordScoreSize = (50 * mScale) + 0.5f; hudRecordScoreY = (310 * mScale) + 0.5f; //load the shield graphics int life_size = (int) (16 * mScale + 0.5f); mImgLife = BitmapFactory.decodeResource (getResources(), R.drawable.img_heart); mImgLife = Bitmap.createScaledBitmap(mImgLife, life_size, life_size, false); //load the explosion graphic mImgExplosionSprite = BitmapFactory.decodeResource(getResources(), R.drawable.explosion_spritesheet); float scale = getResources().getDisplayMetrics().density; mImgExplosionSprite = Bitmap.createScaledBitmap(mImgExplosionSprite, (int) (BitmapSizeConstants.WIDTH_EXPLOSION_AIM * scale), (int) (BitmapSizeConstants.WIDTH_EXPLOSION_AIM * scale), false); init(); } private void init() { gameEnded = false; mPlayerScore = 0l; highScoreAchieved = false; mHighScore = mPrefs.getLong(PreferenceKeyConstants.KEY_PERSONAL_HIGHSCORE, 0); if (playing) { this.mPlayerShip.resetShipAttributes(); this.mEnemy1.setX(-mEnemy1.getHitbox().right); this.mEnemy2.setX(-mEnemy2.getHitbox().right); this.mEnemy3.setX(-mEnemy3.getHitbox().right); } else { this.mPlanet = new Planet .Builder(mContext) .screenX(mScreenX) .screenY(mScreenY) .build(); this.mPlayerShip = new SpaceShip .Builder(mContext) .bitmap(R.drawable.speedy) .speed(50) .x(50) .y(50) .screenX(mScreenX) .screenY(mScreenY) .build(); this.mEnemy1 = new EnemyShip .Builder(mContext) .bitmap(R.drawable.enemy_ship) .screenX(mScreenX) .screenY(mScreenY) .build(); this.mEnemy2 = new EnemyShip .Builder(mContext) .bitmap(R.drawable.enemy_ship) .screenX(mScreenX) .screenY(mScreenY) .build(); this.mEnemy3 = new EnemyShip .Builder(mContext) .bitmap(R.drawable.enemy_ship) .screenX(mScreenX) .screenY(mScreenY) .build(); int numSpecs = 40; if (mDustArray == null) { mDustArray = new SpaceDust[40]; for (int i = 0; i < numSpecs; i++) { // Where will the dust spawn? SpaceDust spec = new SpaceDust(mScreenX, mScreenY); mDustArray[i] = spec; } } } // Reset time and distance covered mDistanceCovered = 0f; mTimeTaken = 0; mTimeTakenDecimal = 0; // Get start time mTimeStarted = System.currentTimeMillis(); } @Override public void run() { while (playing) { update(); draw(); control(); } } @Override public void update() { // Collision detection on new positions // Before move because we are testing last frames // position which has just been drawn // If you are using images in excess of 100 pixels // wide then increase the -100 value accordingly boolean hitDetected = false; if (Rect.intersects (mPlayerShip.getHitbox(), mEnemy1.getHitbox())) { hitDetected = true; mExplosionArray[0] = new Explosion(mEnemy1.getX(), mEnemy1.getY(), 16, mImgExplosionSprite.getWidth() / 4); mEnemy1.setX(-mEnemy1.getHitbox().right); } if (Rect.intersects (mPlayerShip.getHitbox(), mEnemy2.getHitbox())) { hitDetected = true; mExplosionArray[1] = new Explosion(mEnemy2.getX(), mEnemy2.getY(), 16, mImgExplosionSprite.getWidth() / 4); mEnemy2.setX(-mEnemy2.getHitbox().right); } if (Rect.intersects (mPlayerShip.getHitbox(), mEnemy3.getHitbox())) { hitDetected = true; mExplosionArray[2] = new Explosion(mEnemy3.getX(), mEnemy3.getY(), 16, mImgExplosionSprite.getWidth() / 4); mEnemy3.setX(-mEnemy3.getHitbox().right); } if (hitDetected && !gameEnded) { //we vibrate to notify user he got rekt by enemy performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP); mPlayerShip.reduceShieldStrength(); if (mPlayerShip.getShieldStrength() < 0) { gameEnded = true; mTimeResetDelayStart = System.currentTimeMillis(); if (mPlayerShip.isBoosting()) { mPlayerShip.stopBoost(); } //calculate your score mPlayerScore = (mPlayerShip.getTimeSpentBoosting() != 0) ? (long) (mDistanceCovered * mPlayerShip.getTimeSpentBoosting() / 1000) : (long) mDistanceCovered; if (mPlayerScore > mHighScore) { highScoreAchieved = true; mPrefs.edit().putLong(PreferenceKeyConstants.KEY_PERSONAL_HIGHSCORE, mPlayerScore).apply(); FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference myRef = database.getReference("scores/".concat(UUID.randomUUID().toString())); myRef.setValue(new HighScore(mPrefs.getString(PreferenceKeyConstants.KEY_ALIAS, "Callsign"), mPlayerScore)); } } } mPlayerShip.update(); // Update the enemies int playerSpeed = mPlayerShip.getSpeed(); mPlanet.update(playerSpeed); mEnemy1.update(playerSpeed / 2); mEnemy2.update(playerSpeed / 2); mEnemy3.update(playerSpeed / 2); for (int i = 0; i < mDustArray.length; i++) { (mDustArray[i]).update(playerSpeed); } if (!gameEnded) { mDistanceCovered += mPlayerShip.getSpeed(); //How long has the player been flying mTimeTaken = System.currentTimeMillis() - mTimeStarted; mTimeTakenDecimal = mTimeTaken / 1000.0d; } } @Override public void draw() { if (mSurfaceHolder.getSurface().isValid()) { //Get start time for FPS calcualtion mTimeStartCurrentFrame = System.nanoTime() / 1000000; //First we lock the area of memory we will be drawing to mScreenCanvas = mSurfaceHolder.lockCanvas(); // Rub out the last frame mScreenCanvas.drawColor(Color.argb(255, 0, 0, 0)); // White specs of dust mStarColor.setColor(Color.argb(255, 255, 255, 255)); //Draw the dust from our arrayList for (int i = 0; i < mDustArray.length; i++) { mScreenCanvas.drawPoint((mDustArray[i]).getX(), (mDustArray[i]).getY(), mStarColor); } //draw the planet mScreenCanvas.drawBitmap( mPlanet.getBitmap(), mPlanet.getX(), mPlanet.getY(), mBackgroundColor); // Draw the player mScreenCanvas.drawBitmap( mPlayerShip.getBitmap(), mPlayerShip.getX(), mPlayerShip.getY(), mBackgroundColor); if (mSpecialEffectsIndex >= 3) { mSpecialEffectsIndex = 0; } if (mPlayerShip.isBoosting()) { mScreenCanvas.drawBitmap( mPlayerShip.getEffectTrailArrayEnhanced()[mSpecialEffectsIndex], mPlayerShip.getEffectBoostedX(), mPlayerShip.getEffectBoostedY(), mBackgroundColor); } else { mScreenCanvas.drawBitmap( mPlayerShip.getEffectTrailArray()[mSpecialEffectsIndex], mPlayerShip.getEffectX(), mPlayerShip.getEffectY(), mBackgroundColor); } mSpecialEffectsIndex++; mScreenCanvas.drawBitmap (mEnemy1.getBitmap(), mEnemy1.getX(), mEnemy1.getY(), mBackgroundColor); mScreenCanvas.drawBitmap (mEnemy2.getBitmap(), mEnemy2.getX(), mEnemy2.getY(), mBackgroundColor); mScreenCanvas.drawBitmap (mEnemy3.getBitmap(), mEnemy3.getX(), mEnemy3.getY(), mBackgroundColor); //draw explosions for (int i = 0; i < NUMBER_OF_ENEMIES; i++) { if (mExplosionArray[i] != null) { mExplosionArray[i].increaseFrame(); if (mExplosionArray[i].isDone()) { mExplosionArray[i] = null; } else { mScreenCanvas.drawBitmap(mImgExplosionSprite, mExplosionArray[i].getRectToBeDrawn(), mExplosionArray[i].getRectDestination(), mBackgroundColor); } } } if (!gameEnded) { // Draw the hud mHudColor.setTextAlign(Paint.Align.LEFT); mHudColor.setColor(Color.argb(255, 204, 255, 255)); // @color baby blue mHudColor.setTextSize(25); mScreenCanvas.drawText("Personal best:" + mHighScore, 10, 20, mHudColor); mScreenCanvas.drawText("Flight Time:" + mTimeTakenDecimal + "s", mScreenX / 2, 20, mHudColor); mScreenCanvas.drawText("Distance:" + mDistanceCovered / 1000 + " KM", mScreenX / 2, mScreenY - 20, mHudColor); for (int i = 0; i < mPlayerShip.getShieldStrength(); i++) { int xcoordinate = 10 + ((mImgLife.getHeight() + 20) * i); mScreenCanvas.drawBitmap( mImgLife, xcoordinate, mScreenY - mImgLife.getHeight(), mBackgroundColor); } } else { // Show end screen mHudColor.setTextSize(hudGameOverSize); mHudColor.setTextAlign(Paint.Align.CENTER); mScreenCanvas.drawText("Game Over", mScreenX / 2, hudGameOverY, mHudColor); mHudColor.setTextSize(hudHighestScoreSize); mScreenCanvas.drawText("Personal best:" + mHighScore, mScreenX / 2, hudHighestScoreY, mHudColor); mScreenCanvas.drawText("Time:" + mTimeTakenDecimal + "s", mScreenX / 2, hudTimeY, mHudColor); mScreenCanvas.drawText("Distance covered:" + mDistanceCovered / 1000 + " Km", mScreenX / 2, hudDistanceCoveredY, mHudColor); mHudColor.setTextSize(hudTapToRetrySize); mScreenCanvas.drawText("Tap to replay!", mScreenX / 2, hudTapToRetryY, mHudColor); if (highScoreAchieved) { mHudColor.setTextSize(hudRecordScoreSize); mScreenCanvas.drawText("NEW RECORD: " + mPlayerScore, mScreenX / 2, hudRecordScoreY, mHudColor); } else { mHudColor.setTextSize(hudHighScoreSize); mScreenCanvas.drawText("SCORE: " + mPlayerScore, mScreenX / 2, hudHighScoreY, mHudColor); } } // Unlock and draw the scene mSurfaceHolder.unlockCanvasAndPost(mScreenCanvas); //Get end time for FPS calcualtion mTimeEndCurrentFrame = System.nanoTime() / 1000000; } } @Override public void control() { try { //calculate FPS mDelta = mTimeEndCurrentFrame - mTimeStartCurrentFrame; mTimeSleepInMillis = (long) (mTargetFrameDrawTime - mDelta); if (mTimeSleepInMillis > 0) { gameThread.sleep(mTimeSleepInMillis); } } catch (InterruptedException e) { Log.e("bbb", "InterruptedException:" + e); } } @Override public void start() { playing = true; gameThread = new Thread(this); gameThread.start(); } @Override public void pause() { playing = false; try { gameThread.join(); } catch (InterruptedException e) { Log.e("bbb", "InterruptedException:" + e); } } @Override public void resume() { Log.d("bbb", "resuming"); playing = true; gameThread = new Thread(this); gameThread.start(); } @Override public boolean onTouchEvent(MotionEvent motionEvent) { // There are many different events in MotionEvent // We care about just 2 - for now. switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) { // Has the player lifted their finger up? case MotionEvent.ACTION_UP: if (!gameEnded) { mPlayerShip.stopBoost(); } // Do something here break; // Has the player touched the screen? case MotionEvent.ACTION_DOWN: // If we are currently on the pause screen, start a new game if (gameEnded) { mTimeResetDelayEnd = System.currentTimeMillis(); if ((mTimeResetDelayEnd - mTimeResetDelayStart) >= GAME_RESET_TIMEOUT_IN_MILLIS) { mTimeResetDelayStart = 0; mTimeResetDelayEnd = 0; init(); } } else { mPlayerShip.startBoost(); } break; } return true; } }
45,653
https://github.com/alex-melodiev/startbooking-web/blob/master/frontend/src/modules/favorite/SBFavorite.vue
Github Open Source
Open Source
MIT
null
startbooking-web
alex-melodiev
Vue
Code
68
264
<template> <div v-if="items" class="row"> <div v-for="item in items" class="row__col col col-12 col-sm-6 col-lg-4" :key="item.id"> <SBFavoriteCard :item="item" /> </div> </div> </template> <script> import { mapActions, mapGetters } from 'vuex'; import localMixin from './localMixin'; import SBFavoriteCard from "./SBFavoriteCard"; export default { name: "SBFavorite", components: {SBFavoriteCard}, methods: { ...mapActions('favorite', [ 'getFavorites' ]) }, computed: { ...mapGetters('favorite', [ 'items' ]) }, mounted() { this.getFavorites(); }, mixins: [localMixin] } </script> <style scoped> </style>
13,813
https://github.com/hex7c0/university-projects/blob/master/asm/src/fx.c
Github Open Source
Open Source
MIT
null
university-projects
hex7c0
C
Code
213
687
#include <stdio.h> #include "arr.h" int standbya=0, standbyc=0, standbyn=0, count=0; int err_input(int ape, int chi, int vol, int eff) { if (diverso_2 (ape)==0 || diverso_2 (chi)==0 || diverso_10 (vol)==0 || diverso_10 (eff)==0 ) return 0; else return 1; } int diverso_2 (int a) { if (a <0 || a >1) //range massimo tra 0 e 1 return 0; else return 1; } int diverso_10 (int v) { if ( v <0 || v >10) //range massimo tra o e 10 return 0; else return 1; } void comando_tende (int ape, int chi, int vol, int eff) { int i; if (vol>eff && ape==0) { puts("COMANDO TENDE:APRI"); for (i=0; i<=count; i++) { if (standbya>0) { puts("STAND-BY per APRI"); standbya--; } if (standbyc>0) { puts("STAND-BY per CHIUDI"); standbyc--; } if (standbyn>0) { puts("STAND-BY per Lum Uguale"); standbyn--; } } } else if (vol>eff && ape==1) { puts("STAND-BY per APRI"); standbya++; count++; } else if (vol<eff && chi==0) { puts("COMANDO TENDE:CHIUDI"); for (i=0; i<count; i++) { if (standbya>0) { puts("STAND-BY per APRI"); standbya--; } if (standbyc>0) { puts("STAND-BY per CHIUDI"); standbyc--; } if (standbyn>0) { puts("STAND-BY per Lum Uguale"); standbyn--; } } } else if (vol<eff && chi==1) { puts("STAND-BY per CHIUDI"); standbyc++; count++; } else if (vol==eff) puts("STAND-BY per Lum Uguale"); { standbyn++; count++; } }
46,965
https://github.com/rajpersram/cas-ggircs/blob/master/deploy/swrs/transform/materialized_view/contact.sql
Github Open Source
Open Source
Apache-2.0
null
cas-ggircs
rajpersram
SQL
Code
283
865
-- Deploy ggircs:materialized_view_contact to pg -- requires: table_ghgr_import begin; create materialized view swrs_transform.contact as ( select row_number() over () as id, id as ghgr_import_id, contact_details.* from swrs_extract.ghgr_import, xmltable( '//Contact[not(ancestor::ConfidentialityRequest)]' passing xml_file columns path_context varchar(1000) path 'name(./ancestor::VerifyTombstone|./ancestor::RegistrationData)', contact_idx integer path 'string(count(./ancestor-or-self::Contact/preceding-sibling::Contact))' not null, contact_type varchar(1000) path './Details/ContactType[normalize-space(.)]', given_name varchar(1000) path './Details/GivenName[normalize-space(.)]', family_name varchar(1000) path './Details/FamilyName[normalize-space(.)]', initials varchar(1000) path './Details/Initials[normalize-space(.)]', telephone_number varchar(1000) path './Details/TelephoneNumber[normalize-space(.)]', extension_number varchar(1000) path './Details/ExtensionNumber[normalize-space(.)]', fax_number varchar(1000) path './Details/FaxNumber[normalize-space(.)]', email_address varchar(1000) path './Details/EmailAddress[normalize-space(.)]', position varchar(1000) path './Details/Position[normalize-space(.)]', language_correspondence varchar(1000) path './Details/LanguageCorrespondence[normalize-space(.)]' ) as contact_details ) with no data; create unique index ggircs_contact_primary_key on swrs_transform.contact (ghgr_import_id, path_context, contact_idx); comment on materialized view swrs_transform.contact is 'The materialized view housing contact information'; comment on column swrs_transform.contact.id is 'A generated index used for keying in the ggircs schema'; comment on column swrs_transform.contact.ghgr_import_id is 'The foreign key reference to swrs_extract.ghgr_import'; comment on column swrs_transform.contact.path_context is 'The umbrella context from which the contact was pulled from the xml (VerifyTombstone or RegistrationData'; comment on column swrs_transform.contact.contact_idx is 'The number of preceding Contact siblings before this Contact node'; comment on column swrs_transform.contact.contact_type is 'The type of contact'; comment on column swrs_transform.contact.given_name is 'The given name of the contact'; comment on column swrs_transform.contact.family_name is 'The family name of the contact'; comment on column swrs_transform.contact.initials is 'The initials of the contact'; comment on column swrs_transform.contact.telephone_number is 'The phone number attached to this contact'; comment on column swrs_transform.contact.extension_number is 'The extension number attached to this contact'; comment on column swrs_transform.contact.fax_number is 'The fax number attached to this contact'; comment on column swrs_transform.contact.email_address is 'The email address attached to this contact'; comment on column swrs_transform.contact.position is 'The position of this contact'; comment on column swrs_transform.contact.language_correspondence is 'The language of correspondence for thsi contact'; commit;
470
https://github.com/sliftist/devtools-frontend/blob/master/front_end/sources/SourcesNavigator.js
Github Open Source
Open Source
BSD-3-Clause
null
devtools-frontend
sliftist
JavaScript
Code
977
3,648
/* * Copyright (C) 2011 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import * as Common from '../common/common.js'; import * as Host from '../host/host.js'; import * as Persistence from '../persistence/persistence.js'; import * as SDK from '../sdk/sdk.js'; import * as Snippets from '../snippets/snippets.js'; import * as UI from '../ui/ui.js'; import * as Workspace from '../workspace/workspace.js'; import {NavigatorUISourceCodeTreeNode, NavigatorView} from './NavigatorView.js'; // eslint-disable-line no-unused-vars /** * @unrestricted */ export class NetworkNavigatorView extends NavigatorView { constructor() { super(); self.SDK.targetManager.addEventListener(SDK.SDKModel.Events.InspectedURLChanged, this._inspectedURLChanged, this); // Record the sources tool load time after the file navigator has loaded. Host.userMetrics.panelLoaded('sources', 'DevTools.Launch.Sources'); } /** * @override * @param {!Workspace.Workspace.Project} project * @return {boolean} */ acceptProject(project) { return project.type() === Workspace.Workspace.projectTypes.Network; } /** * @param {!Common.EventTarget.EventTargetEvent} event */ _inspectedURLChanged(event) { const mainTarget = self.SDK.targetManager.mainTarget(); if (event.data !== mainTarget) { return; } const inspectedURL = mainTarget && mainTarget.inspectedURL(); if (!inspectedURL) { return; } for (const uiSourceCode of this.workspace().uiSourceCodes()) { if (this.acceptProject(uiSourceCode.project()) && uiSourceCode.url() === inspectedURL) { this.revealUISourceCode(uiSourceCode, true); } } } /** * @override * @param {!Workspace.UISourceCode.UISourceCode} uiSourceCode */ uiSourceCodeAdded(uiSourceCode) { const mainTarget = self.SDK.targetManager.mainTarget(); const inspectedURL = mainTarget && mainTarget.inspectedURL(); if (!inspectedURL) { return; } if (uiSourceCode.url() === inspectedURL) { this.revealUISourceCode(uiSourceCode, true); } } } /** * @unrestricted */ export class FilesNavigatorView extends NavigatorView { constructor() { super(); const placeholder = new UI.EmptyWidget.EmptyWidget(''); this.setPlaceholder(placeholder); placeholder.appendParagraph().appendChild(UI.Fragment.html` <div>${ls`Sync changes in DevTools with the local filesystem`}</div><br /> ${UI.XLink.XLink.create('https://developers.google.com/web/tools/chrome-devtools/workspaces/', ls`Learn more`)} `); const toolbar = new UI.Toolbar.Toolbar('navigator-toolbar'); toolbar.appendItemsAtLocation('files-navigator-toolbar').then(() => { if (!toolbar.empty()) { this.contentElement.insertBefore(toolbar.element, this.contentElement.firstChild); } }); } /** * @override * @param {!Workspace.Workspace.Project} project * @return {boolean} */ acceptProject(project) { return project.type() === Workspace.Workspace.projectTypes.FileSystem && Persistence.FileSystemWorkspaceBinding.FileSystemWorkspaceBinding.fileSystemType(project) !== 'overrides' && !Snippets.ScriptSnippetFileSystem.isSnippetsProject(project); } /** * @override * @param {!Event} event */ handleContextMenu(event) { const contextMenu = new UI.ContextMenu.ContextMenu(event); contextMenu.defaultSection().appendAction('sources.add-folder-to-workspace', undefined, true); contextMenu.show(); } } export class OverridesNavigatorView extends NavigatorView { constructor() { super(); const placeholder = new UI.EmptyWidget.EmptyWidget(''); this.setPlaceholder(placeholder); placeholder.appendParagraph().appendChild(UI.Fragment.html` <div>${ls`Override page assets with files from a local folder`}</div><br /> ${UI.XLink.XLink.create('https://developers.google.com/web/updates/2018/01/devtools#overrides', ls`Learn more`)} `); this._toolbar = new UI.Toolbar.Toolbar('navigator-toolbar'); this.contentElement.insertBefore(this._toolbar.element, this.contentElement.firstChild); self.Persistence.networkPersistenceManager.addEventListener( Persistence.NetworkPersistenceManager.Events.ProjectChanged, this._updateProjectAndUI, this); this.workspace().addEventListener(Workspace.Workspace.Events.ProjectAdded, this._onProjectAddOrRemoved, this); this.workspace().addEventListener(Workspace.Workspace.Events.ProjectRemoved, this._onProjectAddOrRemoved, this); this._updateProjectAndUI(); } /** * @param {!Common.EventTarget.EventTargetEvent} event */ _onProjectAddOrRemoved(event) { const project = /** @type {!Workspace.Workspace.Project} */ (event.data); if (project && project.type() === Workspace.Workspace.projectTypes.FileSystem && Persistence.FileSystemWorkspaceBinding.FileSystemWorkspaceBinding.fileSystemType(project) !== 'overrides') { return; } this._updateUI(); } _updateProjectAndUI() { this.reset(); const project = self.Persistence.networkPersistenceManager.project(); if (project) { this.tryAddProject(project); } this._updateUI(); } _updateUI() { this._toolbar.removeToolbarItems(); const project = self.Persistence.networkPersistenceManager.project(); if (project) { const enableCheckbox = new UI.Toolbar.ToolbarSettingCheckbox( self.Common.settings.moduleSetting('persistenceNetworkOverridesEnabled')); this._toolbar.appendToolbarItem(enableCheckbox); this._toolbar.appendToolbarItem(new UI.Toolbar.ToolbarSeparator(true)); const clearButton = new UI.Toolbar.ToolbarButton(Common.UIString.UIString('Clear configuration'), 'largeicon-clear'); clearButton.addEventListener(UI.Toolbar.ToolbarButton.Events.Click, () => { project.remove(); }); this._toolbar.appendToolbarItem(clearButton); return; } const title = Common.UIString.UIString('Select folder for overrides'); const setupButton = new UI.Toolbar.ToolbarButton(title, 'largeicon-add', title); setupButton.addEventListener(UI.Toolbar.ToolbarButton.Events.Click, this._setupNewWorkspace, this); this._toolbar.appendToolbarItem(setupButton); } async _setupNewWorkspace() { const fileSystem = await self.Persistence.isolatedFileSystemManager.addFileSystem('overrides'); if (!fileSystem) { return; } self.Common.settings.moduleSetting('persistenceNetworkOverridesEnabled').set(true); } /** * @override * @param {!Workspace.Workspace.Project} project * @return {boolean} */ acceptProject(project) { return project === self.Persistence.networkPersistenceManager.project(); } } /** * @unrestricted */ export class ContentScriptsNavigatorView extends NavigatorView { constructor() { super(); const placeholder = new UI.EmptyWidget.EmptyWidget(''); this.setPlaceholder(placeholder); placeholder.appendParagraph().appendChild(UI.Fragment.html` <div>${ls`Content scripts served by extensions appear here`}</div><br /> ${UI.XLink.XLink.create('https://developer.chrome.com/extensions/content_scripts', ls`Learn more`)} `); } /** * @override * @param {!Workspace.Workspace.Project} project * @return {boolean} */ acceptProject(project) { return project.type() === Workspace.Workspace.projectTypes.ContentScripts; } } /** * @unrestricted */ export class SnippetsNavigatorView extends NavigatorView { constructor() { super(); const placeholder = new UI.EmptyWidget.EmptyWidget(''); this.setPlaceholder(placeholder); placeholder.appendParagraph().appendChild(UI.Fragment.html` <div>${ls`Create and save code snippets for later reuse`}</div><br /> ${ UI.XLink.XLink.create( 'https://developers.google.com/web/tools/chrome-devtools/javascript/snippets', ls`Learn more`)} `); const toolbar = new UI.Toolbar.Toolbar('navigator-toolbar'); const newButton = new UI.Toolbar.ToolbarButton('', 'largeicon-add', Common.UIString.UIString('New snippet')); newButton.addEventListener(UI.Toolbar.ToolbarButton.Events.Click, () => this.create(self.Snippets.project, '')); toolbar.appendToolbarItem(newButton); this.contentElement.insertBefore(toolbar.element, this.contentElement.firstChild); } /** * @override * @param {!Workspace.Workspace.Project} project * @return {boolean} */ acceptProject(project) { return Snippets.ScriptSnippetFileSystem.isSnippetsProject(project); } /** * @override * @param {!Event} event */ handleContextMenu(event) { const contextMenu = new UI.ContextMenu.ContextMenu(event); contextMenu.headerSection().appendItem(ls`Create new snippet`, () => this.create(self.Snippets.project, '')); contextMenu.show(); } /** * @override * @param {!Event} event * @param {!NavigatorUISourceCodeTreeNode} node */ handleFileContextMenu(event, node) { const uiSourceCode = node.uiSourceCode(); const contextMenu = new UI.ContextMenu.ContextMenu(event); contextMenu.headerSection().appendItem( Common.UIString.UIString('Run'), () => Snippets.ScriptSnippetFileSystem.evaluateScriptSnippet(uiSourceCode)); contextMenu.editSection().appendItem(Common.UIString.UIString('Rename\u2026'), () => this.rename(node, false)); contextMenu.editSection().appendItem( Common.UIString.UIString('Remove'), () => uiSourceCode.project().deleteFile(uiSourceCode)); contextMenu.saveSection().appendItem( Common.UIString.UIString('Save as...'), this._handleSaveAs.bind(this, uiSourceCode)); contextMenu.show(); } /** * @param {!Workspace.UISourceCode.UISourceCode} uiSourceCode */ async _handleSaveAs(uiSourceCode) { uiSourceCode.commitWorkingCopy(); const {content} = await uiSourceCode.requestContent(); self.Workspace.fileManager.save(uiSourceCode.url(), content || '', true); self.Workspace.fileManager.close(uiSourceCode.url()); } } /** * @implements {UI.ActionDelegate.ActionDelegate} */ export class ActionDelegate { /** * @override * @param {!UI.Context.Context} context * @param {string} actionId * @return {boolean} */ handleAction(context, actionId) { switch (actionId) { case 'sources.create-snippet': self.Snippets.project.createFile('', null, '').then(uiSourceCode => Common.Revealer.reveal(uiSourceCode)); return true; case 'sources.add-folder-to-workspace': self.Persistence.isolatedFileSystemManager.addFileSystem(); return true; } return false; } }
18,757
https://github.com/automenta/aa/blob/master/src/test/java/com/cliffc/aa/view/graph/Figure.java
Github Open Source
Open Source
Apache-2.0
null
aa
automenta
Java
Code
1,103
3,219
/* * Copyright (c) 2008, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ package com.cliffc.aa.view.graph; //import com.cliffc.aa.view.InputBlock; //import com.cliffc.aa.view.InputGraph; //import com.cliffc.aa.view.InputNode; //import com.cliffc.aa.view.Source; //import com.cliffc.aa.view.layout.Cluster; //import com.cliffc.aa.view.layout.Vertex; import com.cliffc.aa.view.data.Properties; import com.cliffc.aa.view.data.*; import com.cliffc.aa.view.layout.Cluster; import com.cliffc.aa.view.layout.Vertex; import jcog.math.v2; import jcog.tree.rtree.rect.RectF; import java.awt.*; import java.awt.image.BufferedImage; import java.util.List; import java.util.*; public class Figure extends Entity implements Source.Provider, Vertex { private static final int INSET = 8; public static final int SLOT_WIDTH = 10; private static final int OVERLAPPING = 6; public static final int SLOT_START = 4; private static final int SLOT_OFFSET = 8; private static final boolean VERTICAL_LAYOUT = true; final List<InputSlot> inputSlots; final List<OutputSlot> outputSlots; private final Source source; private final Diagram diagram; private v2 position; private final List<Figure> predecessors; private final List<Figure> successors; private List<InputGraph> subgraphs; private Color color; private final int id; private final String idString; private String[] lines; private int heightCash = -1; private int widthCash = -1; private int getHeight() { if (heightCash == -1) { BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); g.setFont(diagram.getFont().deriveFont(Font.BOLD)); FontMetrics metrics = g.getFontMetrics(); String nodeText = diagram.getNodeText(); heightCash = nodeText.split("\n").length * metrics.getHeight() + INSET; } return heightCash; } public static <T> List<T> getAllBefore(List<T> inputList, T tIn) { List<T> result = new ArrayList<>(); for(T t : inputList) { if(t.equals(tIn)) { break; } result.add(t); } return result; } public static int getSlotsWidth(Collection<? extends Slot> slots) { int result = Figure.SLOT_OFFSET; for(Slot s : slots) { result += s.width() + Figure.SLOT_OFFSET; } return result; } public int getWidth() { if (widthCash == -1) { int max = 0; BufferedImage image = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); g.setFont(diagram.getFont().deriveFont(Font.BOLD)); FontMetrics metrics = g.getFontMetrics(); for (String s : getLines()) { int cur = metrics.stringWidth(s); if (cur > max) { max = cur; } } widthCash = max + INSET; widthCash = Math.max(widthCash, Figure.getSlotsWidth(inputSlots)); widthCash = Math.max(widthCash, Figure.getSlotsWidth(outputSlots)); } return widthCash; } Figure(Diagram diagram, int id) { this.diagram = diagram; this.source = new Source(); inputSlots = new ArrayList<>(5); outputSlots = new ArrayList<>(1); predecessors = new ArrayList<>(6); successors = new ArrayList<>(6); this.id = id; idString = Integer.toString(id); this.position = new v2(0, 0); this.color = Color.WHITE; } public int getId() { return id; } public void setColor(Color color) { this.color = color; } public Color getColor() { return color; } public List<Figure> getPredecessors() { return Collections.unmodifiableList(predecessors); } public Set<Figure> getPredecessorSet() { Set<Figure> result = new HashSet<>(getPredecessors()); return Collections.unmodifiableSet(result); } public Set<Figure> getSuccessorSet() { Set<Figure> result = new HashSet<>(getSuccessors()); return Collections.unmodifiableSet(result); } public List<Figure> getSuccessors() { return Collections.unmodifiableList(successors); } void addPredecessor(Figure f) { this.predecessors.add(f); } void addSuccessor(Figure f) { this.successors.add(f); } void removePredecessor(Figure f) { assert predecessors.contains(f); predecessors.remove(f); } void removeSuccessor(Figure f) { assert successors.contains(f); successors.remove(f); } public List<InputGraph> getSubgraphs() { return subgraphs; } public void setSubgraphs(List<InputGraph> subgraphs) { this.subgraphs = subgraphs; } @Override public void pos(v2 p) { this.position = p; } @Override public v2 pos() { return position; } public Diagram getDiagram() { return diagram; } @Override public Source getSource() { return source; } public InputSlot createInputSlot() { InputSlot slot = new InputSlot(this, -1); inputSlots.add(slot); return slot; } public InputSlot createInputSlot(int index) { InputSlot slot = new InputSlot(this, index); inputSlots.add(slot); inputSlots.sort(Slot.slotIndexComparator); return slot; } public void removeSlot(Slot s) { assert inputSlots.contains(s) || outputSlots.contains(s); List<Connection> connections = new ArrayList<>(s.getConnections()); for (Connection c : connections) { c.remove(); } if (inputSlots.contains(s)) { inputSlots.remove(s); } else outputSlots.remove(s); } public OutputSlot createOutputSlot() { OutputSlot slot = new OutputSlot(this, -1); outputSlots.add(slot); return slot; } public OutputSlot createOutputSlot(int index) { OutputSlot slot = new OutputSlot(this, index); outputSlots.add(slot); outputSlots.sort(Slot.slotIndexComparator); return slot; } public List<InputSlot> getInputSlots() { return Collections.unmodifiableList(inputSlots); } public Set<Slot> getSlots() { Set<Slot> result = new HashSet<>(); result.addAll(getInputSlots()); result.addAll(getOutputSlots()); return result; } public List<OutputSlot> getOutputSlots() { return Collections.unmodifiableList(outputSlots); } void removeInputSlot(InputSlot s) { s.removeAllConnections(); inputSlots.remove(s); } void removeOutputSlot(OutputSlot s) { s.removeAllConnections(); outputSlots.remove(s); } private String[] getLines() { if (lines == null) { updateLines(); } return lines; } private void updateLines() { String[] strings = diagram.getNodeText().split("\n"); String[] result = new String[strings.length]; for (int i = 0; i < strings.length; i++) { result[i] = resolveString(strings[i], getProperties()); } lines = result; } private static String resolveString(String string, Properties properties) { StringBuilder sb = new StringBuilder(); boolean inBrackets = false; StringBuilder curIdent = new StringBuilder(); for (int i = 0; i < string.length(); i++) { char c = string.charAt(i); if (inBrackets) { if (c == ']') { String value = properties.get(curIdent.toString()); if (value == null) { value = ""; } sb.append(value); inBrackets = false; } else { curIdent.append(c); } } else { if (c == '[') { inBrackets = true; curIdent = new StringBuilder(); } else { sb.append(c); } } } return sb.toString(); } @Override public v2 size() { if (VERTICAL_LAYOUT) { int width = Math.max(getWidth(), Figure.SLOT_WIDTH * (Math.max(inputSlots.size(), outputSlots.size()) + 1)); int height = getHeight() + 2 * Figure.SLOT_WIDTH - 2 * Figure.OVERLAPPING; return new v2(width, height); } else { int width = getWidth() + 2 * Figure.SLOT_WIDTH - 2*Figure.OVERLAPPING; int height = Figure.SLOT_WIDTH * (Math.max(inputSlots.size(), outputSlots.size()) + 1); return new v2(width, height); } } @Override public String toString() { return idString; } public Cluster getCluster() { if (getSource().getSourceNodes().isEmpty()) { assert false : "Should never reach here, every figure must have at least one source node!"; return null; } else { final InputBlock inputBlock = diagram.getGraph().getBlock(getSource().getSourceNodes().get(0)); assert inputBlock != null; Cluster result = diagram.getBlock(inputBlock); assert result != null; return result; } } @Override public boolean isRoot() { List<InputNode> sourceNodes = source.getSourceNodes(); if (!sourceNodes.isEmpty() && sourceNodes.get(0).getProperties().get("name") != null) { return source.getSourceNodes().get(0).getProperties().get("name").equals("Root"); } else { return false; } } @Override public int compareTo(Vertex f) { return toString().compareTo(f.toString()); } public RectF bounds() { final v2 p = this.pos(); return RectF.XYWH(p.x, p.y, this.getWidth(), this.getHeight()); } }
49,803
https://github.com/FullteaOfEEIC/tinpy2/blob/master/sample.py
Github Open Source
Open Source
MIT
2,022
tinpy2
FullteaOfEEIC
Python
Code
46
121
import tinpy from tinpy import getAccessToken FBemail = "Facebook e-mail address" FBpass = "Facebook password" token = getAccessToken(FBemail, FBpass) api = tinpy.API(token) # This is the latitude and the longitude of Shibuya Tokyo Japan. lat, lon = 35.658034, 139.701636 api.setLocation(lat, lon) for user in api.getNearbyUsers(): user.like()
42,593
https://github.com/shahraizali/Bank/blob/master/v1/connection_requests/urls.py
Github Open Source
Open Source
MIT
2,020
Bank
shahraizali
Python
Code
17
55
from django.urls import path from .views.connection_request import ConnectionRequestView urlpatterns = [ # Connection requests path('connection_requests', ConnectionRequestView.as_view()), ]
18,789
https://github.com/zlatanov/websockets/blob/master/src/Maverick.WebSockets/WebSocketDataMessage.cs
Github Open Source
Open Source
MIT
2,021
websockets
zlatanov
C#
Code
359
936
using System; using System.Buffers; using System.Diagnostics; using System.Threading.Tasks; namespace Maverick.WebSockets { internal sealed class WebSocketDataMessage : WebSocketMessage { public WebSocketDataMessage( WebSocketMessageType type, BufferSequenceSegment start, Int32 startIndex, Boolean compressed ) { Debug.Assert( start != null ); m_next = start; m_nextStartIndex = startIndex; Type = type; Length = (Int32)Buffer.Length; Compressed = compressed; } public override WebSocketMessageType Type { get; } internal Boolean Compressed { get; } internal Int32 Length { get; private set; } public override ReadOnlySequence<Byte> Buffer { get { if ( m_dirty ) { if ( m_next != null ) { var start = new Segment( m_next, m_nextStartIndex ); var end = m_next.Next != null ? start.Add( m_next.Next ) : start; m_buffer = new ReadOnlySequence<Byte>( start, 0, end, end.Memory.Length ); } m_dirty = false; } return m_buffer; } } public override void Dispose() { if ( !m_disposed ) { if ( m_previous != null ) { m_previous.Release(); m_previous = null; } if ( m_next != null ) { m_next.Release(); m_next = null; } m_buffer = default; m_disposed = true; } } internal override ValueTask WriteAsync( IWebSocketStream stream ) { if ( Buffer.IsSingleSegment ) { return stream.WriteAsync( Buffer.First ); } return new ValueTask( WriteMultipleAsync( stream ) ); } private async Task WriteMultipleAsync( IWebSocketStream stream ) { while ( MoveNext( out var memory ) ) { await stream.WriteAsync( memory ); } } private Boolean MoveNext( out ReadOnlyMemory<Byte> memory ) { if ( m_previous != null ) { m_previous.Release(); m_previous = null; m_dirty = true; } if ( m_next != null ) { memory = m_next.WrittenMemory.Slice( m_nextStartIndex ); m_nextStartIndex = 0; m_previous = m_next; m_next = m_next.Next; return true; } memory = default; return false; } private Boolean m_disposed = false; private BufferSequenceSegment m_previous; private BufferSequenceSegment m_next; private Int32 m_nextStartIndex; private Boolean m_dirty = true; private ReadOnlySequence<Byte> m_buffer; private sealed class Segment : ReadOnlySequenceSegment<Byte> { public Segment( BufferSequenceSegment start, Int32 startIndex ) { Memory = start.WrittenMemory.Slice( startIndex ); } public Segment Add( BufferSequenceSegment buffer ) { var segment = new Segment( buffer, 0 ) { RunningIndex = RunningIndex + Memory.Length }; Next = segment; if ( buffer.Next == null ) { return segment; } return segment.Add( buffer.Next ); } } } }
3,350
https://github.com/aws/aws-toolkit-azure-devops/blob/master/src/lib/ecrUtils.ts
Github Open Source
Open Source
MIT
2,023
aws-toolkit-azure-devops
aws
TypeScript
Code
132
401
/*! * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT */ import ECR = require('aws-sdk/clients/ecr') import tl = require('azure-pipelines-task-lib/task') import base64 = require('base-64') import { DockerHandler } from './dockerUtils' export async function loginToRegistry( dockerHandler: DockerHandler, dockerPath: string, encodedAuthToken: string, endpoint: string ): Promise<void> { const tokens: string[] = base64 .decode(encodedAuthToken) .trim() .split(':') await dockerHandler.runDockerCommand(dockerPath, 'login', ['-u', tokens[0], '-p', tokens[1], endpoint], { silent: true }) } export async function getEcrAuthorizationData(ecrClient: ECR): Promise<ECR.AuthorizationData | undefined> { try { console.log(tl.loc('RequestingAuthToken')) const response = await ecrClient.getAuthorizationToken().promise() if (!response.authorizationData) { return undefined } return response.authorizationData[0] } catch (err) { throw new Error(`Failed to obtain authorization token to log in to ECR, error: ${err}`) } } export function constructTaggedImageName(imageName: string, tag: string): string { if (tag) { return `${imageName}:${tag}` } return imageName }
30,535
https://github.com/Joe-Coffee/lottie-flutter/blob/master/lib/src/animation/content/content.dart
Github Open Source
Open Source
MIT
2,020
lottie-flutter
Joe-Coffee
Dart
Code
13
35
abstract class Content { String get name; void setContents(List<Content> contentsBefore, List<Content> contentsAfter); }
47,578
https://github.com/ganjardbc/btz-component/blob/master/example/src/components/CoolPopupComponent.js
Github Open Source
Open Source
MIT
null
btz-component
ganjardbc
JavaScript
Code
300
831
import React, { Component } from 'react' import { CoolPopupComponent } from 'btz-component' import 'btz-component/dist/index.css' class App extends Component { constructor (props) { super(props) this.state = { coolPopup: false, activeIndex: 0 } } render () { const {coolPopup, activeIndex} = this.state let contentCoolPopup = '' switch (activeIndex) { case 0: contentCoolPopup = ( <div style={{textAlign: 'center'}}> <h3>Content 1</h3> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p> </div> ) break; case 1: contentCoolPopup = ( <div style={{textAlign: 'center'}}> <h3>Content 2</h3> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p> </div> ) break; case 3: contentCoolPopup = ( <div style={{textAlign: 'center'}}> <h3>Content 3</h3> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p> </div> ) break; default: contentCoolPopup = ( <div style={{textAlign: 'center'}}> <h3>Content 1</h3> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p> </div> ) break; } return ( <div> <div style={{ width: 400 }}> <h2>Cool Popup</h2> <button onClick={() => this.setState({coolPopup: true})}> Open Cool Popup </button> {coolPopup && ( <CoolPopupComponent title={'Run On Your Device'} navigator={[ {title: 'Device ID'}, {title: 'Account'}, {title: 'QR Code'} ]} onClose={() => this.setState({coolPopup: false})} onChangeNavigator={(index) => this.setState({activeIndex: index})} content={contentCoolPopup} /> )} </div> </div> ) } } export default App
4,814
https://github.com/larryeedwards/openyan/blob/master/Assembly-CSharp/TitleSaveFilesScript.cs
Github Open Source
Open Source
Unlicense
2,020
openyan
larryeedwards
C#
Code
247
1,024
using System; using UnityEngine; // Token: 0x02000551 RID: 1361 public class TitleSaveFilesScript : MonoBehaviour { // Token: 0x0600219C RID: 8604 RVA: 0x00197584 File Offset: 0x00195984 private void Start() { base.transform.localPosition = new Vector3(1050f, base.transform.localPosition.y, base.transform.localPosition.z); this.UpdateHighlight(); } // Token: 0x0600219D RID: 8605 RVA: 0x001975D4 File Offset: 0x001959D4 private void Update() { if (!this.Show) { base.transform.localPosition = new Vector3(Mathf.Lerp(base.transform.localPosition.x, 1050f, Time.deltaTime * 10f), base.transform.localPosition.y, base.transform.localPosition.z); } else { base.transform.localPosition = new Vector3(Mathf.Lerp(base.transform.localPosition.x, 0f, Time.deltaTime * 10f), base.transform.localPosition.y, base.transform.localPosition.z); if (!this.ConfirmationWindow.activeInHierarchy) { if (this.InputManager.TappedDown) { this.ID++; if (this.ID > 3) { this.ID = 1; } this.UpdateHighlight(); } if (this.InputManager.TappedUp) { this.ID--; if (this.ID < 1) { this.ID = 3; } this.UpdateHighlight(); } } if (base.transform.localPosition.x < 50f) { if (!this.ConfirmationWindow.activeInHierarchy) { if (Input.GetButtonDown("A")) { GameGlobals.Profile = this.ID; Globals.DeleteAll(); GameGlobals.Profile = this.ID; this.Menu.FadeOut = true; this.Menu.Fading = true; } else if (Input.GetButtonDown("X")) { this.ConfirmationWindow.SetActive(true); } } else if (Input.GetButtonDown("A")) { PlayerPrefs.SetInt("ProfileCreated_" + this.ID, 0); this.ConfirmationWindow.SetActive(false); this.SaveDatas[this.ID].Start(); } else if (Input.GetButtonDown("B")) { this.ConfirmationWindow.SetActive(false); } } } } // Token: 0x0600219E RID: 8606 RVA: 0x0019782A File Offset: 0x00195C2A private void UpdateHighlight() { this.Highlight.localPosition = new Vector3(0f, 700f - 350f * (float)this.ID, 0f); } // Token: 0x0400367C RID: 13948 public InputManagerScript InputManager; // Token: 0x0400367D RID: 13949 public TitleSaveDataScript[] SaveDatas; // Token: 0x0400367E RID: 13950 public GameObject ConfirmationWindow; // Token: 0x0400367F RID: 13951 public TitleMenuScript Menu; // Token: 0x04003680 RID: 13952 public Transform Highlight; // Token: 0x04003681 RID: 13953 public bool Show; // Token: 0x04003682 RID: 13954 public int ID = 1; }
44,755
https://github.com/b264/Esk8/blob/master/src/common/LargeStat/index.js
Github Open Source
Open Source
MIT
2,022
Esk8
b264
JavaScript
Code
94
299
import React from 'react'; import { StyleSheet, Text, View } from 'react-native'; export default class LargeStat extends React.Component { render() { return ( <View style={styles.container}> <View style={styles.largeStatWrap}> <View> <Text style={{color: 'white', textAlign: 'center', marginBottom: 5, fontSize: 30}}>21 mph</Text> <View style={styles.hr}/> <Text style={{color: 'white', textAlign: 'center', marginTop: 5, fontSize: 10}}>CURRENT SPEED</Text> </View> </View> </View> ); } } const styles = StyleSheet.create({ container: { display: 'flex', justifyContent: 'center' }, hr: { height: 1, backgroundColor: '#ffffff' }, largeStatWrap: { justifyContent: 'center', alignItems: 'center', alignSelf: 'center', backgroundColor: 'black', width: 200, height: 200, padding: 10, borderRadius: 200 } });
45,094
https://github.com/cjangrist/oh-my-zsh/blob/master/custom/ssh_aliases.zsh
Github Open Source
Open Source
MIT
2,019
oh-my-zsh
cjangrist
Shell
Code
21
63
alias cloud-dev="mosh cloud-desktop -- screen -dRR" alias cloud="mosh cloud-desktop -- screen -dRR" sshh() { ssh -t -A hadoop@$1 'screen -dRR' }
12,152
https://github.com/Adyen/adyen-android/blob/master/components-core/src/main/java/com/adyen/checkout/components/core/internal/AlwaysAvailablePaymentMethod.kt
Github Open Source
Open Source
MIT
2,023
adyen-android
Adyen
Kotlin
Code
68
220
/* * Copyright (c) 2021 Adyen N.V. * * This file is open source and available under the MIT license. See the LICENSE file for more info. * * Created by josephj on 18/5/2021. */ package com.adyen.checkout.components.core.internal import android.app.Application import androidx.annotation.RestrictTo import com.adyen.checkout.components.core.ComponentAvailableCallback import com.adyen.checkout.components.core.PaymentMethod @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) class AlwaysAvailablePaymentMethod : PaymentMethodAvailabilityCheck<Configuration> { override fun isAvailable( applicationContext: Application, paymentMethod: PaymentMethod, configuration: Configuration?, callback: ComponentAvailableCallback ) { callback.onAvailabilityResult(true, paymentMethod) } }
24,505
https://github.com/bysouleater/interview-coding-test-compara/blob/master/src/models/FastDecreasingPriceProduct.spec.js
Github Open Source
Open Source
MIT
null
interview-coding-test-compara
bysouleater
JavaScript
Code
76
195
const { expect } = require('chai'); const FastDecreasingPriceProduct = require('./FastDecreasingPriceProduct'); describe('FastDecreasingPriceProduct tests', () => { describe('updatePrice', () => { it('Should decrease the current price value in 2 when sellIn is greater or equal 0', () => { const product = new FastDecreasingPriceProduct('Name', 10, 10); product.updatePrice(); expect(product.price).to.eq(8); }); it('Should increase the current price value in 4 when sellIn is lower than 0', () => { const product = new FastDecreasingPriceProduct('Name', -1, 5); product.updatePrice(); expect(product.price).to.eq(1); }); }); });
16,545
https://github.com/naderabdalghani/video-analyzer-distributed-system/blob/master/collector2.py
Github Open Source
Open Source
Apache-2.0
2,020
video-analyzer-distributed-system
naderabdalghani
Python
Code
66
275
import pprint import sys import time import socket import pickle import cv2 import numpy import zmq def result_collector(): context = zmq.Context() results_receiver1 = context.socket(zmq.PULL) print("I am the final collector waiting at port #%s" % (int(sys.argv[1]))) results_receiver1.bind("tcp://127.0.0.1:%s" % (int(sys.argv[1]))) file1 = open("output.txt", "w") while True: recv_msg = pickle.loads(results_receiver1.recv()) cnts = recv_msg['image'] f_num = recv_msg['frame_num'] #print(cnts,f_num) print("Frame # {} : {}\n\n".format(f_num,cnts)) file1.write("Frame # {} : {}\n\n".format(f_num,cnts)) file1.flush() result_collector()
37,612
https://github.com/w-site/redux-diff/blob/master/src/utils/index.js
Github Open Source
Open Source
MIT
2,016
redux-diff
w-site
JavaScript
Code
114
335
import { getSideBySideDiffsArray } from 'jsdifflib'; import _ from 'lodash'; const getTexts = (state) => { return _.chain(state.files).filter({ comparable: true }).map('text').value(); }; const getDiffs = (first, second) => { return _.reduce(getSideBySideDiffsArray(first, second), (memo, [old, { text, action }]) => { const oldText = old.text; const oldAction = old.action; if (_.isEqualWith(oldAction, action, 'equal') && !oldText && !text) return memo; switch (action) { case 'replace': memo.push({ action: '*', text: (oldText ? `${oldText} | ${text}` : text) }); break; case 'empty' : memo.push({ action: '-', text: oldText }); break; case 'equal': memo.push({ text }); break; case 'insert': memo.push({ action: '+', text }); break; default: return memo; } return memo; }, []); }; export { getDiffs, getTexts };
15,061
https://github.com/zflamig/WhirlyGlobe/blob/master/android/library/maply/src/main/java/com/mousebird/maply/LayoutLayer.java
Github Open Source
Open Source
Apache-2.0
2,020
WhirlyGlobe
zflamig
Java
Code
488
1,295
/* * LayoutLayer.java * WhirlyGlobeLib * * Created by Steve Gifford on 6/2/14. * Copyright 2011-2014 mousebird consulting * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.mousebird.maply; import android.os.Handler; import java.lang.ref.WeakReference; /** * The layout layer runs every so often to layout text and marker objects * on the screen. You don't need to create one of these, MaplyController does that. * */ class LayoutLayer extends Layer implements LayerThread.ViewWatcherInterface { WeakReference<BaseController> maplyControl = null; LayoutManager layoutManager = null; LayoutLayer(BaseController inMaplyControl,LayoutManager inLayoutManager) { maplyControl = new WeakReference<BaseController>(inMaplyControl); layoutManager = inLayoutManager; } public void startLayer(LayerThread inLayerThread) { super.startLayer(inLayerThread); scheduleUpdate(); if (maplyControl != null) { LayerThread layerThread = maplyControl.get().getLayerThread(); if (layerThread != null) maplyControl.get().getLayerThread().addWatcher(this); } } public void shutdown() { cancelUpdate(); layoutManager.clearClusterGenerators(); } ViewState viewState = null; ViewState lastViewState = null; // Called when the view state changes @Override public void viewUpdated(ViewState newViewState) { // This pushes back the update, which is what we want // We'd prefer to update 0.2s after the user stops moving // Note: Should do a deeper compare on the view states if (viewState == null || viewState != newViewState) { viewState = newViewState; cancelUpdate(); scheduleUpdate(); } } // Make a Runnable that repeatedly runs itself Runnable makeRepeatingTask() { return new Runnable() { @Override public void run() { runUpdate(); scheduleUpdate(); } }; } // Set if we've got an update in the queue Runnable updateRun = null; Handler updateHandle = null; // Schedule an update if there isn't one already void scheduleUpdate() { synchronized(this) { if (updateHandle == null) { updateRun = makeRepeatingTask(); if (maplyControl != null && maplyControl.get().getLayerThread() != null) { updateHandle = maplyControl.get().getLayerThread().addDelayedTask(updateRun, 200); } } } } // Cancel an update if there's one scheduled void cancelUpdate() { synchronized(this) { if (updateHandle != null) { updateHandle.removeCallbacks(updateRun); updateHandle = null; updateRun = null; } } } // Actually run the layout update void runUpdate() { updateHandle = null; updateRun = null; // Note: Should do a deeper compare on the view states if (layoutManager.hasChanges() || viewState != lastViewState) { // Note: Should wait until the user stops moving ChangeSet changes = new ChangeSet(); layoutManager.updateLayout(viewState, changes); maplyControl.get().scene.addChanges(changes); lastViewState = viewState; } } @Override public float getMinTime() { // Update every 1/10s return 0.2f; } @Override public float getMaxLagTime() { // Want an update no less often than this // Note: What? return 4.0f; } public void addClusterGenerator(ClusterGenerator generator) { synchronized (this) { Point2d clusterSize = generator.clusterLayoutSize(); this.layoutManager.addClusterGenerator(generator, generator.clusterNumber(),generator.selectable(),clusterSize.getX(),clusterSize.getY()); } } }
24,343
https://github.com/qarik-hanrattyjen/apache-airflow-backport-providers-google-2021.3.3/blob/master/venv/lib/python3.9/site-packages/pendulum/lang/sk.py
Github Open Source
Open Source
Apache-2.0
2,022
apache-airflow-backport-providers-google-2021.3.3
qarik-hanrattyjen
Python
Code
189
695
# -*- coding: utf-8 -*- translations = { # Days 'days': { 0: 'nedeľa', 1: 'pondelok', 2: 'utorok', 3: 'streda', 4: 'štvrtok', 5: 'piatok', 6: 'sobota' }, 'days_abbrev': { 0: 'ne', 1: 'po', 2: 'ut', 3: 'st', 4: 'št', 5: 'pi', 6: 'so' }, # Months 'months': { 1: 'január', 2: 'február', 3: 'marec', 4: 'apríl', 5: 'máj', 6: 'jún', 7: 'júl', 8: 'august', 9: 'september', 10: 'október', 11: 'november', 12: 'december' }, 'months_abbrev': { 1: 'jan', 2: 'feb', 3: 'mar', 4: 'apr', 5: 'máj', 6: 'jún', 7: 'júl', 8: 'aug', 9: 'sep', 10: 'okt', 11: 'nov', 12: 'dec' }, # Units of time 'year': ['rok', '{count} roky', '{count} rokov'], 'month': ['mesiac', '{count} mesiace', '{count} mesiacov'], 'week': ['týždeň', '{count} týždne', '{count} týždňov'], 'day': ['deň', '{count} dni', '{count} dní'], 'hour': ['hodinu', '{count} hodiny', '{count} hodín'], 'minute': ['minútu', '{count} minúty', '{count} minút'], 'second': ['sekundu', '{count} sekundy', '{count} sekúnd'], # Relative time 'ago': 'pred {time}', 'from_now': 'o {time}', 'after': '{time} neskôr', 'before': '{time} predtým', # Date formats 'date_formats': { 'LTS': 'H:mm:ss', 'LT': 'H:mm', 'LLLL': 'dddd D. MMMM YYYY H:mm', 'LLL': 'D. MMMM YYYY H:mm', 'LL': 'D. MMMM YYYY', 'L': 'DD.MM.YYYY', }, }
40,858
https://github.com/mkubliniak/XChange/blob/master/xchange-bitbay/src/main/java/org/knowm/xchange/bitbay/service/BitbayAccountService.java
Github Open Source
Open Source
MIT
2,019
XChange
mkubliniak
Java
Code
269
1,022
package org.knowm.xchange.bitbay.service; import java.io.IOException; import java.math.BigDecimal; import java.util.List; import org.knowm.xchange.Exchange; import org.knowm.xchange.bitbay.BitbayAdapters; import org.knowm.xchange.bitbay.service.account.params.BitbayWithdrawFundsSwiftParams; import org.knowm.xchange.currency.Currency; import org.knowm.xchange.dto.account.AccountInfo; import org.knowm.xchange.dto.account.FundingRecord; import org.knowm.xchange.exceptions.NotAvailableFromExchangeException; import org.knowm.xchange.service.account.AccountService; import org.knowm.xchange.service.trade.params.DefaultWithdrawFundsParams; import org.knowm.xchange.service.trade.params.TradeHistoryParamCurrency; import org.knowm.xchange.service.trade.params.TradeHistoryParamLimit; import org.knowm.xchange.service.trade.params.TradeHistoryParams; import org.knowm.xchange.service.trade.params.WithdrawFundsParams; /** * @author Z. Dolezal */ public class BitbayAccountService extends BitbayAccountServiceRaw implements AccountService { public BitbayAccountService(Exchange exchange) { super(exchange); } @Override public AccountInfo getAccountInfo() throws IOException { return BitbayAdapters.adaptAccountInfo(exchange.getExchangeSpecification().getUserName(), getBitbayAccountInfo()); } @Override public String withdrawFunds(Currency currency, BigDecimal amount, String address) throws IOException { return withdrawFunds(new DefaultWithdrawFundsParams(address, currency, amount)); } @Override public String withdrawFunds(WithdrawFundsParams params) throws IOException { if ( params instanceof DefaultWithdrawFundsParams) { DefaultWithdrawFundsParams defaultParams = (DefaultWithdrawFundsParams) params; transfer(defaultParams.currency, defaultParams.amount, defaultParams.address); return "Success"; } else if ( params instanceof BitbayWithdrawFundsSwiftParams ) { BitbayWithdrawFundsSwiftParams bicParams = (BitbayWithdrawFundsSwiftParams) params; withdraw(bicParams.getCurrency(), bicParams.getAmount(), bicParams.getAccount(), bicParams.isExpress(), bicParams.getBic()); return "Success"; } throw new NotAvailableFromExchangeException(); } @Override public String requestDepositAddress(Currency currency, String... args) throws IOException { throw new NotAvailableFromExchangeException(); } @Override public TradeHistoryParams createFundingHistoryParams() { throw new NotAvailableFromExchangeException(); } @Override public List<FundingRecord> getFundingHistory(TradeHistoryParams params) throws IOException { Currency currency = null; if (params instanceof TradeHistoryParamCurrency) { TradeHistoryParamCurrency tradeHistoryParamCurrency = (TradeHistoryParamCurrency) params; currency = tradeHistoryParamCurrency.getCurrency(); } Integer limit = 1000; if (params instanceof TradeHistoryParamLimit) { limit = ((TradeHistoryParamLimit) params).getLimit(); } return history(currency, limit); } public static class BitbayFundingHistory implements TradeHistoryParamCurrency, TradeHistoryParamLimit { private Currency currency; private Integer limit; public BitbayFundingHistory(Currency currency, Integer limit) { this.currency = currency; this.limit = limit; } public BitbayFundingHistory() { } @Override public void setCurrency(Currency currency) { this.currency = currency; } @Override public Currency getCurrency() { return currency; } @Override public void setLimit(Integer limit) { this.limit = limit; } @Override public Integer getLimit() { return limit; } } }
46,497
https://github.com/gwh111/UITemplateApp/blob/master/UITemplateApp/Pods/UITemplateTest/UITemplateKit/test/通用UI/列表样式/testListTypeVC.m
Github Open Source
Open Source
MIT
2,019
UITemplateApp
gwh111
Objective-C
Code
208
866
// // testListTypeVC.m // UITemplateKit // // Created by yichen on 2019/6/3. // Copyright © 2019 路飞. All rights reserved. // #import "testListTypeVC.h" #import "CatListManager.h" #import "ExampleModel.h" static NSString *const reuserId = @"reuserId"; @interface testListTypeVC ()<CatListManagerProtocol> @property (nonatomic, strong) UITableView *tableView; @property (nonatomic, strong) CatListManager *dataManager; @property (nonatomic, strong) NSArray *modelArray; @end @implementation testListTypeVC - (void)cc_viewDidLoad { self.view.backgroundColor = [UIColor whiteColor]; self.dataManager = [[CatListManager alloc]initWithIdentifier:reuserId configureBlock:^(CatListCell * cell, ExampleModel * model, NSIndexPath * _Nonnull indexPath) { cell.bottomStyle = indexPath.row % 3; cell.imageStyle = indexPath.row % 3; //根据model赋值 cell.nameLb.text = model.name; cell.headIv.isCornerShowed = YES; [cell.headIv addImageWithCornerImage:[UIImage imageNamed:@"firefox"]]; cell.timeLb.text = model.time; cell.titleLb.text = model.title; cell.contentLb.text = model.content; cell.contentLb.numberOfLines = 2; //默认title1行 content不限制行 如需要改动自行配置行数 [cell.sharedBtn setTitle:@"999" forState:UIControlStateNormal]; cell.imgArr = model.imgArr; }clickConfigure:^(id model, NSIndexPath * _Nonnull indexPath) { NSLog(@"didClickAtIndex = %@",indexPath); }]; [self.dataManager addDataArray:self.modelArray]; //设置modelArr [self.view addSubview:self.tableView]; self.tableView.dataSource = self.dataManager; self.tableView.delegate = self.dataManager; } #pragma mark - delegate - (void)didTouchCellContent:(CatListCell *)cell withType:(CatCellContentClickType)clickType withModel:(id)model withInfo:(NSInteger)info { } #pragma mark - setter/getter - (UITableView *)tableView { if (!_tableView) { _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain]; _tableView.tableFooterView = [UIView new]; _tableView.backgroundColor = [UIColor whiteColor]; [_tableView registerClass:[CatListCell class] forCellReuseIdentifier:reuserId]; } return _tableView; } -(NSArray *)modelArray { if (!_modelArray) { _modelArray = @[[[ExampleModel alloc]init],[[ExampleModel alloc]init],[[ExampleModel alloc]init],[[ExampleModel alloc]init],[[ExampleModel alloc]init],[[ExampleModel alloc]init],[[ExampleModel alloc]init],[[ExampleModel alloc]init],[[ExampleModel alloc]init]]; } return _modelArray; } @end
8,186
https://github.com/emptylight/phoenix/blob/master/src/com/index.js
Github Open Source
Open Source
MIT
2,015
phoenix
emptylight
JavaScript
Code
370
1,283
var h = require('hyperscript') var baseEmoji = require('base-emoji') var a = exports.a = function (href, text, opts) { opts = opts || {} opts.href = href return h('a', opts, text) } var icon = exports.icon = function (i) { return h('span.glyphicon.glyphicon-'+i) } var userlink = exports.userlink = function (id, text, opts) { opts = opts || {} opts.className = (opts.className || '') + ' user-link' var profileLink = a('#/profile/'+id, text, opts) var followLink = ''//followlink(id, user, events) :TODO: return h('span', [profileLink, ' ', followLink]) } var toEmoji = exports.toEmoji = function (buf, size) { size = size || 20 if (!buf) return '' if (typeof buf == 'string') buf = new Buffer(buf.slice(0, buf.indexOf('.')), 'base64') return baseEmoji.toCustom(buf, function(v, emoji) { return '<img class="emoji" width="'+size+'" height="'+size+'" src="/img/emoji/'+emoji.name+'.png" alt=":'+emoji.name+':" title="'+emoji.name+'"> '+emoji.name.replace(/_/g, ' ')+'<br>' }) } var header = exports.header = function (app) { var myid = app.api.getMyId() return h('.nav.navbar.navbar-default', [ h('.container-fluid', [ h('.navbar-header', h('a.navbar-brand', { href: '#/' }, 'secure scuttlebutt')), h('ul.nav.navbar-nav', [ h('li.hidden-xs', a('#/address-book', 'address book')), h('li.hidden-xs', a('#/profile/' + myid, app.api.getNameById(myid))) ]), h('ul.nav.navbar-nav.navbar-right', [ h('li.hidden-xs', a('#/help', 'help')) ]) ]) ]) } var sidenav = exports.sidenav = function (app) { var pages = [ ['compose', 'compose', 'compose'], '-', ['posts', '', 'posts'], ['inbox', 'inbox', 'inbox ('+app.unreadMessages+')'], ['adverts', 'adverts', 'adverts'], '-', ['feed', 'feed', 'data feed'] ] var extraPages = [ ['profile', 'profile/'+app.api.getMyId(), 'profile'], ['network', 'network', 'network'], ['help', 'help', 'help'] ] return h('.side-nav', [ pages.map(function (page) { if (page == '-') return h('hr') if (page[0] == app.page.id) return h('p', h('strong', a('#/'+page[1], page[2]))) return h('p', a('#/'+page[1], page[2])) }), extraPages.map(function (page) { if (page == '-') return h('hr') if (page[0] == app.page.id) return h('p.visible-xs', h('strong', a('#/'+page[1], page[2]))) return h('p.visible-xs', a('#/'+page[1], page[2])) }) ]) } var sidehelp = exports.sidehelp = function (app, opts) { return h('ul.list-unstyled', h('li', h('button.btn.btn-primary', { onclick: app.showUserId }, 'Get your contact id')), h('li', h('button.btn.btn-primary', { onclick: app.followPrompt }, 'Add a contact')), h('li', h('button.btn.btn-primary', { onclick: app.followPrompt }, 'Use an invite')), (!opts || !opts.noMore) ? h('li', h('span', {style:'display: inline-block; padding: 6px 12px'}, a('#/help', 'More help'))) : '' ) } var page = exports.page = function (app, id, content) { return h('div', header(app), h('#page.container-fluid.'+id+'-page', content) ) } exports.message = require('./message') exports.messageThread = require('./message-thread') exports.messageSummary = require('./message-summary') exports.postForm = require('./post-form') exports.adverts = require('./adverts') exports.advertForm = require('./advert-form') exports.addresses = require('./addresses')
5,981
https://github.com/andydansby/z88dk-MK2/blob/master/libsrc/rex/graphics/set4pix.asm
Github Open Source
Open Source
ClArtistic
2,017
z88dk-MK2
andydansby
Assembly
Code
64
260
; ; written by Waleed Hasan ; ; $Id: set4pix.asm,v 1.2 2003/03/13 15:02:09 dom Exp $ XLIB set4pix LIB setpixsave .set4pix ld a,b add a,h ld d,a ld a,c add a,l ld e,a call setpixsave ;PIX(xc+x,yc+y) ld a,b sub h ld d,a call setpixsave ;PIX(xc-x,yc+y) ld a,c sub l ld e,a call setpixsave ;PIX(xc-x,yc-y) ld a,b add a,h ld d,a call setpixsave ;PIX(xc+x,yc-y) ret
33,473
https://github.com/nwtgck/changelog-to-gh-release/blob/master/types/changelog-parser.d.ts
Github Open Source
Open Source
MIT
null
changelog-to-gh-release
nwtgck
TypeScript
Code
74
199
// I'd like to update https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/changelog-parser/index.d.ts declare module 'changelog-parser' { type Option = { filePath: string, removeMarkdown?: boolean } | { text: string }; export type Result = { title: string, description: string, versions: { version: string | null, title: string, date: string | null, body: '', parsed: { _: string[], [key:string]: string[] } }[], }; export default function parseChangelog(option: string | Option, callback?: (error: string | null, result: Result) => void): Promise<Result>; }
39,882
https://github.com/g7401/pigeon/blob/master/pigeon-gps/src/main/java/io/g740/pigeon/biz/service/impl/openapi/OpenApiServiceImpl.java
Github Open Source
Open Source
Apache-2.0
null
pigeon
g7401
Java
Code
63
341
package io.g740.pigeon.biz.service.impl.openapi; import io.g740.commons.exception.impl.ServiceException; import io.g740.commons.types.PageResult; import io.g740.pigeon.biz.object.dto.df.DfSimpleDto; import io.g740.pigeon.biz.service.handler.openapi.OpenApiHandler; import io.g740.pigeon.biz.service.interfaces.openapi.OpenApiService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import java.util.List; /** * @author bbottong */ @Service public class OpenApiServiceImpl implements OpenApiService { @Autowired private OpenApiHandler openApiHandler; @Override public PageResult<DfSimpleDto> pagedListAllDfForApp( String appKey, Pageable pageable) throws ServiceException { return this.openApiHandler.pagedListAllDfForApp(appKey, pageable); } @Override public List<DfSimpleDto> listAllDfForApp(String appKey) throws ServiceException { return this.openApiHandler.listAllDfForApp(appKey); } }
39,630
https://github.com/fabianrios/html-eslint/blob/master/website/playground/queryParamsState.js
Github Open Source
Open Source
MIT
2,021
html-eslint
fabianrios
JavaScript
Code
37
121
const queryParamsState = { get() { try { const decoded = decodeURIComponent( escape(atob(location.hash.replace("#", ""))) ); return JSON.parse(decoded); } catch {} return {}; }, set(state) { const encoded = btoa(unescape(encodeURIComponent(JSON.stringify(state)))); location.hash = encoded; }, }; export default queryParamsState;
13,222
https://github.com/JorgeHRJ/roomies/blob/master/src/Controller/App/ExpenseTagController.php
Github Open Source
Open Source
MIT
null
roomies
JorgeHRJ
PHP
Code
78
323
<?php namespace App\Controller\App; use App\Service\ExpenseTagService; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Annotation\Route; /** * @Route("/expensetag", name="expensetag_") */ class ExpenseTagController extends AbstractController { /** @var ExpenseTagService */ private $expenseTagService; public function __construct(ExpenseTagService $expenseTagService) { $this->expenseTagService = $expenseTagService; } /** * @Route("/_search", name="search") * * @param Request $request * @return JsonResponse */ public function search(Request $request): JsonResponse { if (!$request->isXmlHttpRequest()) { return new JsonResponse([], JsonResponse::HTTP_BAD_REQUEST); } $data = json_decode($request->getContent(), true); $result = $this->expenseTagService->search($data['query']); return new JsonResponse($result, JsonResponse::HTTP_OK); } }
19,498
https://github.com/jsonxr/react-native-materialcommunity-icons/blob/master/icons/SvgSharkFin.tsx
Github Open Source
Open Source
MIT
null
react-native-materialcommunity-icons
jsonxr
TypeScript
Code
145
571
// svg/shark-fin.svg import { createSvgIcon } from './createSvgIcon'; export const SvgSharkFin = createSvgIcon( `<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="mdi-shark-fin" width="24" height="24" viewBox="0 0 24 24"> <path d="M22 16V18H20C18.6 18 17.2 17.6 16 17C13.5 18.3 10.5 18.3 8 17C6.8 17.6 5.4 18 4 18H2V16H4C5.4 16 6.8 15.5 8 14.7C10.4 16.4 13.6 16.4 16 14.7C17.2 15.5 18.6 16 20 16H22M5.28 13.79C5.82 13.63 6.37 13.38 6.89 13.04L8.03 12.27L9.16 13.07C10 13.66 11 14 12 14C13 14 14 13.66 14.84 13.07L15.97 12.27L17.11 13.04C17.93 13.59 18.83 13.9 19.67 13.97C18.24 7.4 12.37 2 6 2C5.65 2 5.33 2.18 5.15 2.47C4.97 2.77 4.95 3.14 5.11 3.45C7.28 7.79 6.61 11.29 5.28 13.79M16 18.7C13.6 20.4 10.4 20.4 8 18.7C6.8 19.5 5.4 20 4 20H2V22H4C5.4 22 6.8 21.6 8 21C10.5 22.3 13.5 22.3 16 21C17.2 21.6 18.6 22 20 22H22V20H20C18.6 20 17.2 19.5 16 18.7Z"/> </svg>` );
24,587
https://github.com/sebhoof/gambit_1.5/blob/master/Printers/standalone/manual_hdf5_combine.cpp
Github Open Source
Open Source
Unlicense
2,021
gambit_1.5
sebhoof
C++
Code
981
2,724
// GAMBIT: Global and Modular BSM Inference Tool // ********************************************* /// \file /// /// This is code for a stand-alone binary which /// performs the end-of-run combination of /// temporary HDF5 files from a GAMBIT scan. /// /// It is essentially the same code that GAMBIT /// runs automatically in the HDF5 printer, just /// moved into a stand-alone tool so that the /// combination can be done "manually" if needed. /// /// ********************************************* /// /// Authors (add name and date if you modify): /// /// \author Ben Farmer /// (b.farmer@imperial.ac.uk) /// \date 2018 Mar /// /// ********************************************* #include <stdlib.h> #include <getopt.h> #include <vector> #include <sstream> #include <utility> #include <string> #include <sys/stat.h> #include <chrono> // GAMBIT headers #include "gambit/Printers/printers/hdf5printer/hdf5_combine_tools.hpp" #include "gambit/Utils/stream_overloads.hpp" #include "gambit/Utils/util_functions.hpp" // Annoying other things we need due to mostly unwanted dependencies #include "gambit/Utils/static_members.hpp" using namespace Gambit; using namespace Printers; void usage() { std::cout << "\nusage: hdf5combine <filename> <group> [options] " "\n " "\n filename - Base name of the temporary files to be combined" "\n e.g. /path/to/my/hdf5file.hdf5 " "\n group - location inside the HDF5 files which contains the datasets to be combined" "\n" "\nOptions:" "\n -h/--help Display this usage information" "\n -f/--force Attempt combination while ignoring missing temporary files" "\n -c/--cleanup Delete temporary files after successful combination" "\n -o/--out <path> Set output folder (default is same folder as temp files)" "\n (note, this first creates the output in the default place," "\n and then just moves it)" "\n -i/--in <file_with_list>" "\n Uses named files as input instead of automatically inferring" "\n them from <filename>. Filenames are to be supplied in a single" "\n ascii file, on separate lines." "\n In this mode <filename> will only be used for naming the output" "\n file (Note: WITHOUT the usual addition of '_temp_combined'!!!)." "\n All files must have the same <group>." "\n Note: Auxilliary ('RA') datasets will be IGNORED! These should" "\n be combined during 'normal' combination of results from a single" "\n run. This 'custom' mode is intended for combining results from" "\n DIFFERENT runs." "\n\n"; exit(EXIT_FAILURE); } int main(int argc, char* argv[]) { // Process command line options // Must at least have two arguments. if (argc < 3) { usage(); } // First, the required options (folder and temporary file base name) std::string finalfile = argv[1]; std::string group = argv[2]; std::string outpath; const struct option primary_options[] = { {"force", no_argument, 0, 'f'}, {"help", no_argument, 0, 'h'}, {"cleanup", no_argument, 0 , 'c'}, {"in", required_argument, 0, 'i'}, {"out", required_argument, 0, 'o'}, {0,0,0,0}, }; int index; int iarg=0; std::string filename; std::vector<std::string> input_files; bool custom_mode = false; std::string tmp_comb_file; bool error_if_inconsistent = true; bool do_cleanup = false; bool move_output = false; size_t num; bool combined_file_exists; while(iarg != -1) { iarg = getopt_long(argc, argv, "fhcoi:", primary_options, &index); switch (iarg) { case 'h': // Display usage information and exit usage(); break; case 'f': // Ignore missing temporary files error_if_inconsistent = false; break; case 'c': do_cleanup = true; break; case 'o': outpath = optarg; move_output = true; break; case 'i': { std::ifstream file_list(optarg); std::string line; while(std::getline(file_list, line)) { input_files.push_back(line); } } custom_mode = true; combined_file_exists = false; num = input_files.size(); break; case '?': // display usage message and quit (also happens on unrecognised options) usage(); break; } } // Begining timing of operation std::chrono::time_point<std::chrono::system_clock> startT = std::chrono::system_clock::now(); if(custom_mode) { // Custom specification of input files std::cout <<" Running combine code in custom filename mode" <<std::endl; std::cout <<" "<<num<<" files to be combined:"<<std::endl; for(std::vector<std::string>::iterator it=input_files.begin(); it!=input_files.end(); ++it) { std::cout << " " << *it << std::endl; } if(num<2) { std::ostringstream errmsg; errmsg << " ERROR! Less than two files parsed from '--in' argument! At least two files are required for combination to do anything!"; std::cerr << errmsg.str() << std::endl; exit(EXIT_FAILURE); } HDF5::combine_hdf5_files(finalfile, "", group, num, false, false, true, input_files); } else { // Report what we are going to do std::cout <<" Searching for temporary files to combine" <<std::endl; std::cout <<" with base filename: "<<finalfile<<std::endl; // Search for the temporary files to be combined size_t max_i = 0; std::pair<std::vector<std::string>,std::vector<size_t>> out = HDF5::find_temporary_files(finalfile, max_i); std::vector<std::string> tmp_files = out.first; std::vector<size_t> missing = out.second; std::cout <<" Found "<<tmp_files.size()<<" temporary files to be combined"<<std::endl; // Check if all temporary files found (i.e. check if output from some rank is missing) if(missing.size()>0) { std::cout <<" WARNING! Temporary files missing from the following ranks: "<<missing<<std::endl; if(error_if_inconsistent) { std::ostringstream errmsg; errmsg << " Could not locate all the expected temporary output files (found "<<tmp_files.size()<<" temporary files, but are missing the files from the ranks reported above)! If you want to attempt the combination anyway, please add the -f flag to the command line invocation."; std::cerr << errmsg.str() << std::endl; exit(EXIT_FAILURE); } } // Name of temporary combined file, if one exists std::ostringstream name; name << finalfile << "_temp_combined"; tmp_comb_file = name.str(); combined_file_exists = Utils::file_exists(tmp_comb_file); if(combined_file_exists) { std::cout<<" Found pre-existing (temporary) combined file"<<std::endl; } else { std::cout<<" No pre-existing (temporary) combined file found"<<std::endl; } num = tmp_files.size() + missing.size(); // We don't actually use their names here, Greg's code assumes that they // follow a fixed format. Previous all files had to exist in increasing // numerical order, however now, if you use the -f flag, it is allowed // for some to just be missing. These will just be ignored if they fail // to open. HDF5::combine_hdf5_files(tmp_comb_file, finalfile, group, num, combined_file_exists, do_cleanup, !error_if_inconsistent); } std::cout<<" Combination finished successfully!"<<std::endl; if(move_output) { std::string fname(Utils::base_name(tmp_comb_file)); std::string outname(outpath+"/"+fname); std::cout<<" Moving output from "<<std::endl <<" "<<tmp_comb_file<<std::endl <<" to"<<std::endl <<" "<<outname<<std::endl; int status = std::system(("mv " + tmp_comb_file+ " " + outname).c_str()); if(WEXITSTATUS(status)!=0) { std::cerr << " FAILED to move output to requested directory!! It should still be located at"<<std::endl << " "<<tmp_comb_file<<std::endl; } } // End timing of operation std::chrono::time_point<std::chrono::system_clock> endT = std::chrono::system_clock::now(); std::chrono::duration<double> interval = endT - startT; long runtime = std::chrono::duration_cast<std::chrono::seconds>(interval).count(); long mins = runtime / 60; long secs = runtime % 60; std::cout<<" Operation took "<<mins<<" minutes and "<<secs<<" seconds."<<std::endl; // Finished! exit(EXIT_SUCCESS); }
24,572
https://github.com/Idiot-Alex/linux-monitor/blob/master/linux-monitor-admin/src/main/java/com/hotstrip/linux/monitor/admin/config/ShellResultListenerConfig.java
Github Open Source
Open Source
Apache-2.0
2,021
linux-monitor
Idiot-Alex
Java
Code
73
208
package com.hotstrip.linux.monitor.admin.config; import com.hotstrip.linux.monitor.admin.listener.SSHShellResultListener; import com.hotstrip.linux.monitor.common.listener.ShellResultListener; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * config ShellResultListener Bean * @author Hotstrip */ @Configuration public class ShellResultListenerConfig { /** * return a ShellResultListener Bean * if you want to add a Bean name, the value must be "shellResultListener" * or else, it still load the default Bean, which print log message to console only * @return */ @Bean public ShellResultListener shellResultListener() { return new SSHShellResultListener(); } }
34,203
https://github.com/tienph91/Aspose.Slides-for-Java/blob/master/Examples/src/main/java/com/aspose/slides/examples/text/ApplyOuterShadow.java
Github Open Source
Open Source
MIT
2,022
Aspose.Slides-for-Java
tienph91
Java
Code
133
559
package com.aspose.slides.examples.text; import com.aspose.slides.*; import com.aspose.slides.examples.RunExamples; public class ApplyOuterShadow { public static void main(String[] args) { //ExStart:ApplyOuterShadow // The path to the documents directory. String dataDir = RunExamples.getDataDir_Text(); // Create an instance of Presentation class Presentation presentation = new Presentation(); try { // Get reference of a slide ISlide slide = presentation.getSlides().get_Item(0); // Add an AutoShape of Rectangle type IAutoShape ashp = slide.getShapes().addAutoShape(ShapeType.Rectangle, 150, 75, 400, 300); ashp.getFillFormat().setFillType(FillType.NoFill); // Add TextFrame to the Rectangle ashp.addTextFrame("Aspose TextBox"); IPortion port = ashp.getTextFrame().getParagraphs().get_Item(0).getPortions().get_Item(0); IPortionFormat pf = port.getPortionFormat(); pf.setFontHeight(50); // Enable InnerShadowEffect IEffectFormat ef = pf.getEffectFormat(); ef.enableInnerShadowEffect(); // Set all necessary parameters ef.getInnerShadowEffect().setBlurRadius(8.0); ef.getInnerShadowEffect().setDirection(90.0F); ef.getInnerShadowEffect().setDistance(6.0); ef.getInnerShadowEffect().getShadowColor().setB((byte) 189); // Set ColorType as Scheme ef.getInnerShadowEffect().getShadowColor().setColorType(ColorType.Scheme); // Set Scheme Color ef.getInnerShadowEffect().getShadowColor().setSchemeColor(SchemeColor.Accent1); // Save Presentation presentation.save(dataDir + "WordArt_out.pptx", SaveFormat.Pptx); } finally { if (presentation != null) presentation.dispose(); } //ExEnd:ApplyOuterShadow } }
46,915
https://github.com/nadirdeveloper/react-firebase-auth-example/blob/master/example/src/actions/index.ts
Github Open Source
Open Source
MIT
2,018
react-firebase-auth-example
nadirdeveloper
TypeScript
Code
19
44
import * as AuthActions from './auth'; import * as TodoActions from './todo'; export const ActionCreators = Object.assign({}, TodoActions, AuthActions);
41,863
https://github.com/billwert/azure-sdk-for-java/blob/master/sdk/iotcentral/azure-resourcemanager-iotcentral/src/samples/java/com/azure/resourcemanager/iotcentral/generated/AppsCheckSubdomainAvailabilitySamples.java
Github Open Source
Open Source
MIT
2,022
azure-sdk-for-java
billwert
Java
Code
73
294
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.iotcentral.generated; import com.azure.core.util.Context; import com.azure.resourcemanager.iotcentral.models.OperationInputs; /** Samples for Apps CheckSubdomainAvailability. */ public final class AppsCheckSubdomainAvailabilitySamples { /* * x-ms-original-file: specification/iotcentral/resource-manager/Microsoft.IoTCentral/preview/2021-11-01-preview/examples/Apps_CheckSubdomainAvailability.json */ /** * Sample code: Apps_SubdomainAvailability. * * @param manager Entry point to IotCentralManager. */ public static void appsSubdomainAvailability(com.azure.resourcemanager.iotcentral.IotCentralManager manager) { manager .apps() .checkSubdomainAvailabilityWithResponse( new OperationInputs().withName("myiotcentralapp").withType("IoTApps"), Context.NONE); } }
41,693
https://github.com/imulilla/openMSX/blob/master/src/input/KeyJoystick.cc
Github Open Source
Open Source
Naumen, Condor-1.1, MS-PL
2,021
openMSX
imulilla
C++
Code
593
2,042
#include "KeyJoystick.hh" #include "MSXEventDistributor.hh" #include "StateChangeDistributor.hh" #include "InputEvents.hh" #include "StateChange.hh" #include "checked_cast.hh" #include "serialize.hh" #include "serialize_meta.hh" using std::string; using std::shared_ptr; namespace openmsx { class KeyJoyState final : public StateChange { public: KeyJoyState() = default; // for serialize KeyJoyState(EmuTime::param time_, string name_, byte press_, byte release_) : StateChange(time_) , name(std::move(name_)), press(press_), release(release_) {} [[nodiscard]] const string& getName() const { return name; } [[nodiscard]] byte getPress() const { return press; } [[nodiscard]] byte getRelease() const { return release; } template<typename Archive> void serialize(Archive& ar, unsigned /*version*/) { ar.template serializeBase<StateChange>(*this); ar.serialize("name", name, "press", press, "release", release); } private: string name; byte press, release; }; REGISTER_POLYMORPHIC_CLASS(StateChange, KeyJoyState, "KeyJoyState"); KeyJoystick::KeyJoystick(CommandController& commandController, MSXEventDistributor& eventDistributor_, StateChangeDistributor& stateChangeDistributor_, std::string name_) : eventDistributor(eventDistributor_) , stateChangeDistributor(stateChangeDistributor_) , name(std::move(name_)) , up (commandController, tmpStrCat(name, ".up"), "key for direction up", Keys::K_UP) , down (commandController, tmpStrCat(name, ".down"), "key for direction down", Keys::K_DOWN) , left (commandController, tmpStrCat(name, ".left"), "key for direction left", Keys::K_LEFT) , right(commandController, tmpStrCat(name, ".right"), "key for direction right", Keys::K_RIGHT) , trigA(commandController, tmpStrCat(name, ".triga"), "key for trigger A", Keys::K_SPACE) , trigB(commandController, tmpStrCat(name, ".trigb"), "key for trigger B", Keys::K_M) { status = JOY_UP | JOY_DOWN | JOY_LEFT | JOY_RIGHT | JOY_BUTTONA | JOY_BUTTONB; } KeyJoystick::~KeyJoystick() { if (isPluggedIn()) { KeyJoystick::unplugHelper(EmuTime::dummy()); } } // Pluggable std::string_view KeyJoystick::getName() const { return name; } std::string_view KeyJoystick::getDescription() const { return "Key-Joystick, use your keyboard to emulate an MSX joystick. " "See manual for information on how to configure this."; } void KeyJoystick::plugHelper(Connector& /*connector*/, EmuTime::param /*time*/) { eventDistributor.registerEventListener(*this); stateChangeDistributor.registerListener(*this); } void KeyJoystick::unplugHelper(EmuTime::param /*time*/) { stateChangeDistributor.unregisterListener(*this); eventDistributor.unregisterEventListener(*this); } // KeyJoystickDevice byte KeyJoystick::read(EmuTime::param /*time*/) { return pin8 ? 0x3F : status; } void KeyJoystick::write(byte value, EmuTime::param /*time*/) { pin8 = (value & 0x04) != 0; } // MSXEventListener void KeyJoystick::signalMSXEvent(const shared_ptr<const Event>& event, EmuTime::param time) noexcept { byte press = 0; byte release = 0; switch (event->getType()) { case OPENMSX_KEY_DOWN_EVENT: case OPENMSX_KEY_UP_EVENT: { const auto& keyEvent = checked_cast<const KeyEvent&>(*event); auto key = static_cast<Keys::KeyCode>( int(keyEvent.getKeyCode()) & int(Keys::K_MASK)); if (event->getType() == OPENMSX_KEY_DOWN_EVENT) { if (key == up .getKey()) press = JOY_UP; else if (key == down .getKey()) press = JOY_DOWN; else if (key == left .getKey()) press = JOY_LEFT; else if (key == right.getKey()) press = JOY_RIGHT; else if (key == trigA.getKey()) press = JOY_BUTTONA; else if (key == trigB.getKey()) press = JOY_BUTTONB; } else { if (key == up .getKey()) release = JOY_UP; else if (key == down .getKey()) release = JOY_DOWN; else if (key == left .getKey()) release = JOY_LEFT; else if (key == right.getKey()) release = JOY_RIGHT; else if (key == trigA.getKey()) release = JOY_BUTTONA; else if (key == trigB.getKey()) release = JOY_BUTTONB; } break; } default: // ignore break; } if (((status & ~press) | release) != status) { stateChangeDistributor.distributeNew(std::make_shared<KeyJoyState>( time, name, press, release)); } } // StateChangeListener void KeyJoystick::signalStateChange(const shared_ptr<StateChange>& event) { const auto* kjs = dynamic_cast<const KeyJoyState*>(event.get()); if (!kjs) return; if (kjs->getName() != name) return; status = (status & ~kjs->getPress()) | kjs->getRelease(); } void KeyJoystick::stopReplay(EmuTime::param time) noexcept { // TODO read actual host key state byte newStatus = JOY_UP | JOY_DOWN | JOY_LEFT | JOY_RIGHT | JOY_BUTTONA | JOY_BUTTONB; if (newStatus != status) { byte release = newStatus & ~status; stateChangeDistributor.distributeNew(std::make_shared<KeyJoyState>( time, name, 0, release)); } } // version 1: Initial version, the variable status was not serialized. // version 2: Also serialize the above variable, this is required for // record/replay, see comment in Keyboard.cc for more details. template<typename Archive> void KeyJoystick::serialize(Archive& ar, unsigned version) { if (ar.versionAtLeast(version, 2)) { ar.serialize("status", status); } if constexpr (Archive::IS_LOADER) { if (isPluggedIn()) { plugHelper(*getConnector(), EmuTime::dummy()); } } // no need to serialize 'pin8' } INSTANTIATE_SERIALIZE_METHODS(KeyJoystick); REGISTER_POLYMORPHIC_INITIALIZER(Pluggable, KeyJoystick, "KeyJoystick"); } // namespace openmsx
31,205
https://github.com/sandsmark/freeage/blob/master/src/FreeAge/client/shader_program.hpp
Github Open Source
Open Source
BSD-3-Clause
2,020
freeage
sandsmark
C++
Code
417
919
// Copyright 2020 The FreeAge authors // This file is part of FreeAge, licensed under the new BSD license. // See the COPYING file in the project root for the license text. #pragma once #include <QOpenGLFunctions_3_2_Core> // Represents a shader program. At least a fragment and a vertex shader must be // attached to a program to be complete. This class assumes some common // attribute names in the shaders to simplify attribute handling: // // in_position : Position input to the vertex shader. // in_color : Color input to the vertex shader. // in_texcoord : Texture coordinate input to the vertex shader. // // A current OpenGL context is required for calling each member function except // the constructor. This includes the destructor. class ShaderProgram { public: enum class ShaderType { kVertexShader = 1 << 0, kGeometryShader = 1 << 1, kFragmentShader = 1 << 2 }; // No-op constructor, no OpenGL context required. ShaderProgram(); // Deletes the program. Attention: Requires a current OpenGL context for // this thread! You may need to explicitly delete this object at a point where // such a context still exists. ~ShaderProgram(); // Attaches a shader to the program. Returns false if the shader does not // compile. bool AttachShader(const char* source_code, ShaderType type, QOpenGLFunctions_3_2_Core* f); // Links the program. Must be called after all shaders have been attached. // Returns true if successful. bool LinkProgram(QOpenGLFunctions_3_2_Core* f); // Makes this program the active program (calls glUseProgram()). void UseProgram(QOpenGLFunctions_3_2_Core* f) const; // Returns the location of the given uniform. If the uniform name does not // exist, returns -1. GLint GetUniformLocation(const char* name, QOpenGLFunctions_3_2_Core* f) const; // Same as GetUniformLocation(), but aborts the program if the uniform does // not exist. GLint GetUniformLocationOrAbort(const char* name, QOpenGLFunctions_3_2_Core* f) const; // Uniform setters. void SetUniformMatrix2fv(GLint location, float* values, bool valuesAreColumnMajor, QOpenGLFunctions_3_2_Core* f); // Attribute setters. void SetPositionAttribute(int component_count, GLenum component_type, GLsizei stride, std::size_t offset, QOpenGLFunctions_3_2_Core* f); void SetColorAttribute(int component_count, GLenum component_type, GLsizei stride, std::size_t offset, QOpenGLFunctions_3_2_Core* f); void SetTexCoordAttribute(int component_count, GLenum component_type, GLsizei stride, std::size_t offset, QOpenGLFunctions_3_2_Core* f); inline GLuint program_name() const { return program_; } private: // OpenGL name of the program. This is zero if the program has not been // successfully linked yet. GLuint program_; // OpenGL names of the shaders attached to the program. These are zero if not // attached. GLuint vertex_shader_; GLuint geometry_shader_; GLuint fragment_shader_; // Attribute locations. These are -1 if no attribute with the common name // exists. GLint position_attribute_location_; GLint color_attribute_location_; GLint texcoord_attribute_location_; };
44,889
https://github.com/aagarwal1012/IntroViews-Flutter/blob/master/lib/src/models/page_button_view_model.dart
Github Open Source
Open Source
MIT
2,021
IntroViews-Flutter
aagarwal1012
Dart
Code
40
121
import 'package:intro_views_flutter/src/helpers/constants.dart'; /// This is view model for the skip and done buttons. class PageButtonViewModel { const PageButtonViewModel({ required this.slidePercent, required this.totalPages, required this.activePageIndex, required this.slideDirection, }); final double slidePercent; final int totalPages; final int activePageIndex; final SlideDirection slideDirection; }
27,359
https://github.com/duartepatriani/TypeScriptTypeDefinitions/blob/master/jquery.json/jquery.json.d.ts
Github Open Source
Open Source
Apache-2.0
2,017
TypeScriptTypeDefinitions
duartepatriani
TypeScript
Code
6
20
interface JQueryStatic { toJSON(data: any); }
11,805
https://github.com/FlandreCirno/AzurLaneWikiUtilitiesManual/blob/master/AzurLaneData/zh-CN/framework/puremvc/patterns/facade/facade.lua
Github Open Source
Open Source
MIT
null
AzurLaneWikiUtilitiesManual
FlandreCirno
Lua
Code
301
1,161
slot0 = import("...core.Controller") slot1 = import("...core.Model") slot2 = import("...core.View") slot3 = import("..observer.Notification") slot4 = class("Facade") slot4.Ctor = function (slot0, slot1) if slot0.instanceMap[slot1] ~= nil then error(slot0.MULTITON_MSG) end slot0:initializeNotifier(slot1) slot0.instanceMap[slot1] = slot0 slot0:initializeFacade() end slot4.initializeFacade = function (slot0) slot0:initializeModel() slot0:initializeController() slot0:initializeView() end slot4.getInstance = function (slot0) if slot0 == nil then return nil end if slot0.instanceMap[slot0] == nil then slot0.instanceMap[slot0] = slot0:New() end return slot0.instanceMap[slot0] end slot4.initializeController = function (slot0) if slot0.controller ~= nil then return end slot0.controller = slot0.getInstance(slot0.multitonKey) end slot4.initializeModel = function (slot0) if slot0.model ~= nil then return end slot0.model = slot0.getInstance(slot0.multitonKey) end slot4.initializeView = function (slot0) if slot0.view ~= nil then return end slot0.view = slot0.getInstance(slot0.multitonKey) end slot4.registerCommand = function (slot0, slot1, slot2) slot0.controller:registerCommand(slot1, slot2) end slot4.removeCommand = function (slot0, slot1) slot0.controller:removeCommand(slot1) end slot4.hasCommand = function (slot0, slot1) return slot0.controller:hasCommand(slot1) end slot4.registerProxy = function (slot0, slot1) slot0.model:registerProxy(slot1) end slot4.retrieveProxy = function (slot0, slot1) return slot0.model:retrieveProxy(slot1) end slot4.removeProxy = function (slot0, slot1) slot2 = nil if slot0.model ~= nil then slot2 = slot0.model:removeProxy(slot1) end return slot2 end slot4.hasProxy = function (slot0, slot1) return slot0.model:hasProxy(slot1) end slot4.registerMediator = function (slot0, slot1) if slot0.view ~= nil then slot0.view:registerMediator(slot1) end end slot4.retrieveMediator = function (slot0, slot1) return slot0.view:retrieveMediator(slot1) end slot4.removeMediator = function (slot0, slot1) slot2 = nil if slot0.view ~= nil then slot2 = slot0.view:removeMediator(slot1) end return slot2 end slot4.hasMediator = function (slot0, slot1) return slot0.view:hasMediator(slot1) end slot4.sendNotification = function (slot0, slot1, slot2, slot3) slot0:notifyObservers(slot0.New(slot1, slot2, slot3)) end slot4.notifyObservers = function (slot0, slot1) if slot0.view ~= nil then slot0.view:notifyObservers(slot1) end end slot4.initializeNotifier = function (slot0, slot1) slot0.multitonKey = slot1 end slot4.hasCore = function (slot0) return slot0.instanceMap[slot0] ~= nil end slot4.removeCore = function (slot0) if slot0.instanceMap[slot0] == nil then return end slot1.removeModel(slot0) slot2.removeView(slot0) slot3.removeController(slot0) slot0.instanceMap[slot0] = nil end slot4.instanceMap = {} slot4.MULTITON_MSG = "Facade instance for this Multiton key already constructed!" return slot4
31,802
https://github.com/QuinntyneBrown/meeting-backend-service/blob/master/MeetingBackendService.Web/src/app/constants/meeting-remove-success.action.ts
Github Open Source
Open Source
MIT
null
meeting-backend-service
QuinntyneBrown
TypeScript
Code
8
21
export const MEETING_REMOVE_SUCCESS = "[Meeting] Remove Meeting Success";
37,060
https://github.com/francisfuzz/doughnut-generator/blob/master/script.js
Github Open Source
Open Source
MIT
null
doughnut-generator
francisfuzz
JavaScript
Code
605
3,591
async function getColors(count) { // Fetches data from the hexbot NOOPS API // Details: https://noopschallenge.com/ const endpoint = `https://api.noopschallenge.com/hexbot?count=${count}`; const response = await fetch(endpoint); return response.json(); } async function createDoughnut() { const data = await getColors(11); // Consistent doughnut colors... const doughnutInterior = "#f4900d"; const doughnutExterior = "#ffab33"; const svg = ` <svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 47.5 47.5" style="enable-background:new 0 0 47.5 47.5;" xml:space="preserve" version="1.1" id="svg2"> <defs id="defs6"> <clipPath id="clipPath16" clipPathUnits="userSpaceOnUse"> <path id="path18" d="M 0,38 38,38 38,0 0,0 0,38 Z"/> </clipPath> </defs> <g transform="matrix(1.25,0,0,-1.25,0,47.5)" id="g10"> <g id="g12"> <g clip-path="url(#clipPath16)" id="g14"> <g transform="translate(36.3369,13.4512)" id="g20"> <path id="path22" style="fill:${doughnutExterior};fill-opacity:1;fill-rule:nonzero;stroke:none" d="m 0,0 c -1.046,-6.271 -7.722,-10.451 -17.245,-10.451 -9.523,0 -16.198,4.18 -17.243,10.451 -0.247,1.479 0.156,8.12 1.054,9.406 2.559,3.663 3.474,-10.365 16.189,-10.365 13.848,0 13.641,14.028 16.199,10.365 C -0.147,8.12 0.246,1.479 0,0"/> </g> <g transform="translate(19.0923,17.6309)" id="g24"> <path id="path26" style="fill:${ data.colors[0].value };fill-opacity:1;fill-rule:nonzero;stroke:none" d="m 0,0 c -3.174,0 -5.748,0.702 -5.748,1.568 0,0.866 2.574,1.567 5.748,1.567 3.173,0 5.748,-0.701 5.748,-1.567 C 5.748,0.702 3.173,0 0,0 m 0,13.375 c -9.331,0 -16.895,-4.584 -16.895,-10.24 0,-5.655 7.564,-10.239 16.895,-10.239 9.33,0 16.895,4.584 16.895,10.239 0,5.656 -7.565,10.24 -16.895,10.24"/> </g> <g transform="translate(2.7197,22.3774)" id="g28"> <path id="path30" style="fill:${ data.colors[0].value };fill-opacity:1;fill-rule:nonzero;stroke:none" d="m 0,0 c -0.653,-1.045 -0.92,-5.494 0.479,-7.577 2.134,-3.179 3.178,-1.567 4.746,-2.047 2.335,-0.714 2.508,-2.559 4.355,-3.483 2.09,-1.045 3.305,-0.741 6.27,0 4.181,1.045 6.837,-1.088 9.405,0 2.106,0.893 3.311,4.137 4.486,4.528 3.728,1.243 4.515,7.124 1.741,9.537 -0.87,-1.829 -5.137,-8.404 -7.88,-8.709 -2.745,-0.305 -10.974,-1 -14.457,0.784 C 5.661,-5.182 2.134,-2.961 1.698,-2.352 1.263,-1.742 0,0 0,0"/> </g> <g transform="translate(19.0923,23.1177)" id="g32"> <path id="path34" style="fill:${doughnutInterior};fill-opacity:1;fill-rule:nonzero;stroke:none" d="m 0,0 c -3.752,0 -6.793,-1.228 -6.793,-2.743 0,-0.59 0.463,-1.133 1.245,-1.58 -0.126,0.13 -0.2,0.264 -0.2,0.404 0,0.866 2.574,1.567 5.748,1.567 3.173,0 5.748,-0.701 5.748,-1.567 0,-0.14 -0.074,-0.274 -0.201,-0.404 0.783,0.447 1.246,0.99 1.246,1.58 C 6.793,-1.228 3.751,0 0,0"/> </g> <g transform="translate(5.4199,18.8496)" id="g36"> <path id="path38" style="fill:${ data.colors[1].value };fill-opacity:1;fill-rule:nonzero;stroke:none" d="M 0,0 C -0.375,0 -0.737,0.203 -0.925,0.557 -1.195,1.067 -1,1.7 -0.489,1.969 l 2.308,1.22 C 2.328,3.461 2.961,3.265 3.231,2.754 3.501,2.244 3.306,1.611 2.795,1.342 L 0.487,0.122 C 0.332,0.039 0.165,0 0,0"/> </g> <g transform="translate(17.3071,11.0557)" id="g40"> <path id="path42" style="fill:${ data.colors[2].value };fill-opacity:1;fill-rule:nonzero;stroke:none" d="m 0,0 c -0.41,0 -0.799,0.242 -0.966,0.646 l -0.74,1.786 C -1.927,2.965 -1.673,3.576 -1.14,3.797 -0.606,4.017 0.004,3.765 0.225,3.23 L 0.965,1.444 C 1.186,0.911 0.933,0.3 0.399,0.079 0.269,0.025 0.133,0 0,0"/> </g> <g transform="translate(29.1514,15.2363)" id="g44"> <path id="path46" style="fill:${ data.colors[3].value };fill-opacity:1;fill-rule:nonzero;stroke:none" d="M 0,0 C -0.181,0 -0.364,0.047 -0.53,0.146 -1.027,0.438 -1.192,1.08 -0.898,1.576 L 0.233,3.492 C 0.526,3.988 1.171,4.153 1.664,3.86 2.161,3.566 2.326,2.926 2.032,2.429 L 0.9,0.514 C 0.706,0.184 0.357,0 0,0"/> </g> <g transform="translate(30.8926,23)" id="g48"> <path id="path50" style="fill:${ data.colors[4].value };fill-opacity:1;fill-rule:nonzero;stroke:none" d="m 0,0 c -0.56,0 -1.023,0.481 -1.043,1.046 -0.02,0.576 0.431,1.079 1.007,1.1 L 1.182,2.198 C 1.769,2.205 2.243,1.771 2.263,1.194 2.283,0.618 1.832,0.099 1.256,0.078 L 0.038,0 0,0 Z"/> </g> <g transform="translate(20.792,27.1235)" id="g52"> <path id="path54" style="fill:${ data.colors[5].value };fill-opacity:1;fill-rule:nonzero;stroke:none" d="m 0,0 c -0.444,0 -0.855,0.285 -0.997,0.73 -0.173,0.551 0.132,1.138 0.682,1.312 L 0.511,2.303 C 1.066,2.478 1.648,2.172 1.822,1.622 1.997,1.071 1.691,0.484 1.142,0.31 L 0.315,0.049 C 0.21,0.016 0.104,0 0,0"/> </g> <g transform="translate(14.9976,25.4258)" id="g56"> <path id="path58" style="fill:${ data.colors[6].value };fill-opacity:1;fill-rule:nonzero;stroke:none" d="M 0,0 C -0.157,0 -0.316,0.036 -0.466,0.11 L -1.25,0.502 C -1.766,0.76 -1.976,1.388 -1.718,1.904 -1.46,2.42 -0.832,2.63 -0.315,2.372 L 0.468,1.98 C 0.984,1.722 1.194,1.095 0.936,0.578 0.753,0.212 0.384,0 0,0"/> </g> <g transform="translate(24.0996,12.1465)" id="g60"> <path id="path62" style="fill:${ data.colors[7].value };fill-opacity:1;fill-rule:nonzero;stroke:none" d="M 0,0 C -0.156,0 -0.315,0.035 -0.465,0.109 L -1.249,0.5 c -0.517,0.258 -0.727,0.885 -0.47,1.401 0.257,0.518 0.884,0.727 1.402,0.47 L 0.467,1.98 C 0.983,1.723 1.193,1.096 0.937,0.579 0.754,0.212 0.384,0 0,0"/> </g> <g transform="translate(10.4263,14.4521)" id="g64"> <path id="path66" style="fill:${ data.colors[8].value };fill-opacity:1;fill-rule:nonzero;stroke:none" d="m 0,0 c -0.138,0 -0.277,0.026 -0.412,0.085 -0.53,0.227 -0.775,0.842 -0.548,1.372 l 0.392,0.914 C -0.34,2.9 0.275,3.15 0.805,2.919 1.335,2.691 1.581,2.077 1.353,1.547 L 0.961,0.633 C 0.791,0.237 0.405,0 0,0"/> </g> <g transform="translate(26.0176,24.3369)" id="g68"> <path id="path70" style="fill:${ data.colors[9].value };fill-opacity:1;fill-rule:nonzero;stroke:none" d="m 0,0 c -0.403,0 -0.787,0.234 -0.958,0.626 -0.231,0.529 0.01,1.145 0.538,1.377 L 0.276,2.308 C 0.807,2.54 1.422,2.298 1.652,1.769 1.884,1.24 1.643,0.624 1.114,0.393 L 0.418,0.088 C 0.281,0.028 0.14,0 0,0"/> </g> <g transform="translate(9.0347,24.3804)" id="g72"> <path id="path74" style="fill:${ data.colors[10].value };fill-opacity:1;fill-rule:nonzero;stroke:none" d="m 0,0 c -0.078,0 -0.157,0.009 -0.235,0.027 l -0.566,0.13 c -0.563,0.13 -0.914,0.691 -0.784,1.253 0.129,0.563 0.691,0.913 1.252,0.784 L 0.233,2.064 C 0.796,1.934 1.147,1.373 1.018,0.811 0.906,0.327 0.476,0 0,0"/> </g> </g> </g> </g> </svg> `; return (document.getElementById("doughnut").innerHTML = svg); } window.onload = function() { // Loads the initial doughnut. createDoughnut(); // Binds the the onclick listener. document.getElementById("doughnut").addEventListener("click", function() { return createDoughnut(); }); };
11,732
https://github.com/openforis/collect-earth/blob/master/collect-earth/collect-earth-app/src/main/java/org/openforis/collect/earth/ipcc/model/AbstractManagementLandUseSubdivision.java
Github Open Source
Open Source
MIT
2,023
collect-earth
openforis
Java
Code
47
159
package org.openforis.collect.earth.ipcc.model; public abstract class AbstractManagementLandUseSubdivision extends AbstractLandUseSubdivision<ManagementTypeEnum>{ protected ManagementTypeEnum type; public AbstractManagementLandUseSubdivision( LandUseCategoryEnum category, String code, String name, ManagementTypeEnum type, Integer id) { super(category, code, name, id); setManagementType(type); } public ManagementTypeEnum getManagementType() { return type; } public void setManagementType(ManagementTypeEnum type) { this.type = type; }; }
16,477
https://github.com/csarkar373/westhillcs2/blob/master/src/tables/csabtopics.js
Github Open Source
Open Source
RSA-MD
null
westhillcs2
csarkar373
JavaScript
Code
405
1,195
import React from "react" import { Table, Tr, Th, Td } from "react-super-responsive-table" import "react-super-responsive-table" import "react-super-responsive-table/dist/SuperResponsiveTableStyle.css" import "../css/table.css" import bigO from "../logo/bigO.png" import java from "../logo/java.png" import map from "../logo/map.png" import linkedList from "../logo/LinkedList.jpg" import stack from "../logo/stack.png" import queue from "../logo/queue.png" import tree from "../logo/tree2.png" import sort from "../logo/sort.png" import hash from "../logo/hash.png" import functional from "../logo/functional.png" function CSABtopics() { return ( <Table width="75%" border="1"> <tbody> <Tr> <Th scope="col" class="goldHeader"> Language/Site </Th> <Th scope="col" class="goldHeader"> Description </Th> </Tr> <Tr> <Td> <div> <img src={bigO} width="100" height="100" alt="" /> </div> </Td> <Td> Big-Oh: The course starts by teaching the basics of Big-Oh notation. This is the only purely theoretical concept taught in the course. </Td> </Tr> <Tr> <Td> <div> <img src={java} width="100" height="100" alt="" /> </div> </Td> <Td> Java: The course teaches java topics not covered in AP CSA including additional operators and programming constructs. </Td> </Tr> <Tr> <Td> <div> <img src={map} width="100" height="100" alt="" /> </div> </Td> <Td> Java Collections: Standard Java Library classes including Maps and Sets are heavily featured in the course. </Td> </Tr> <Tr> <Td> <div> <img src={linkedList} width="100" height="100" alt="" /> </div> </Td> <Td> Linked Lists: The course continues with an introduction of advanced data structures including linked lists and double linked lists. </Td> </Tr> <Tr> <Td> <div> <img src={stack} width="100" height="100" alt="" /> </div> </Td> <Td> Stacks: The course teaches how stacks can be used as a fundamental data structure to solve common programming problems. </Td> </Tr> <Tr> <Td> <div> <img src={queue} width="100" height="100" alt="" /> </div> </Td> <Td> Queues: The course teaches how queues and circular queues can be used as fundamental data structures to solve common programming problems. </Td> </Tr> <Tr> <Td> <div> <img src={tree} width="100" height="100" alt="" /> </div> </Td> <Td> Trees: Trees are the single, most important data structure taught in the course.{" "} </Td> </Tr> <Tr> <Td> <div> <img src={sort} width="100" height="100" alt="" /> </div> </Td> <Td> Sorting: As a continuation of what was taught in AP CSA, this course takes a deeper look into QuickSort and Heap Sort. </Td> </Tr> <Tr> <Td> <div> <img src={hash} width="100" height="100" alt="" /> </div> </Td> <Td> Hashing: Students are taught how hashing can be used to speed searching. </Td> </Tr> <Tr> <Td> <div> <img src={functional} width="100" height="25" alt="" /> </div> </Td> <Td> Functional Programming:Java version 8 adds functional features to the language which can greatly shorten code length. </Td> </Tr> </tbody> </Table> ) } export default CSABtopics
7,383
https://github.com/lechium/tvOS135Headers/blob/master/System/Library/PrivateFrameworks/Home.framework/HFAccessoryProfileGroupItem.h
Github Open Source
Open Source
MIT
2,020
tvOS135Headers
lechium
Objective-C
Code
152
554
/* * This header is generated by classdump-dyld 1.0 * on Sunday, June 7, 2020 at 11:27:06 AM Mountain Standard Time * Operating System: Version 13.4.5 (Build 17L562) * Image Source: /System/Library/PrivateFrameworks/Home.framework/Home * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. */ #import <Home/Home-Structs.h> #import <Home/HFItemGroupItem.h> #import <libobjc.A.dylib/HFAccessoryProfileVendor.h> #import <libobjc.A.dylib/NSCopying.h> @protocol HFCharacteristicValueSource; @class NSSet, NSNumber, NSString; @interface HFAccessoryProfileGroupItem : HFItemGroupItem <HFAccessoryProfileVendor, NSCopying> { NSSet* _profiles; NSNumber* _groupIdentifier; id<HFCharacteristicValueSource> _valueSource; } @property (nonatomic,readonly) NSSet * profiles; //@synthesize profiles=_profiles - In the implementation block @property (nonatomic,copy,readonly) NSNumber * groupIdentifier; //@synthesize groupIdentifier=_groupIdentifier - In the implementation block @property (nonatomic,readonly) id<HFCharacteristicValueSource> valueSource; //@synthesize valueSource=_valueSource - In the implementation block @property (readonly) unsigned long long hash; @property (readonly) Class superclass; @property (copy,readonly) NSString * description; @property (copy,readonly) NSString * debugDescription; @property (nonatomic,readonly) NSSet * services; -(id)copyWithZone:(NSZone*)arg1 ; -(id)init; -(NSNumber *)groupIdentifier; -(NSSet *)profiles; -(NSSet *)services; -(id)accessories; -(id<HFCharacteristicValueSource>)valueSource; -(id)copyWithValueSource:(id)arg1 ; -(id)initWithProfiles:(id)arg1 groupIdentifier:(id)arg2 valueSource:(id)arg3 ; -(id)_buildProfileItems; @end
22,116
https://github.com/pdxrunner/geode/blob/master/geode-core/src/main/java/org/apache/geode/admin/jmx/internal/GemFireHealthJmxImpl.java
Github Open Source
Open Source
Apache-2.0, BSD-3-Clause
null
geode
pdxrunner
Java
Code
564
1,529
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.admin.jmx.internal; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import javax.management.modelmbean.ModelMBean; import org.apache.logging.log4j.Logger; import org.apache.geode.SystemFailure; import org.apache.geode.admin.AdminException; import org.apache.geode.admin.DistributedSystemHealthConfig; import org.apache.geode.admin.GemFireHealthConfig; import org.apache.geode.admin.RuntimeAdminException; import org.apache.geode.admin.internal.GemFireHealthImpl; import org.apache.geode.internal.admin.GfManagerAgent; import org.apache.geode.internal.logging.LogService; /** * The JMX "managed resource" that represents the health of GemFire. Basically, it provides the * behavior of <code>GemFireHealthImpl</code>, but does some JMX stuff like registering beans with * the agent. * * @see AdminDistributedSystemJmxImpl#createGemFireHealth * * * @since GemFire 3.5 */ public class GemFireHealthJmxImpl extends GemFireHealthImpl implements ManagedResource { private static final Logger logger = LogService.getLogger(); /** The name of the MBean that will manage this resource */ private String mbeanName; /** The ModelMBean that is configured to manage this resource */ private ModelMBean modelMBean; /** The object name of the MBean created for this managed resource */ private final ObjectName objectName; /////////////////////// Constructors /////////////////////// /** * Creates a new <code>GemFireHealthJmxImpl</code> that monitors the health of the given * distributed system and uses the given JMX agent. */ GemFireHealthJmxImpl(GfManagerAgent agent, AdminDistributedSystemJmxImpl system) throws AdminException { super(agent, system); this.mbeanName = new StringBuffer().append(MBEAN_NAME_PREFIX).append("GemFireHealth,id=") .append(MBeanUtil.makeCompliantMBeanNameProperty(system.getId())).toString(); this.objectName = MBeanUtil.createMBean(this); } ////////////////////// Instance Methods ////////////////////// public String getHealthStatus() { return getHealth().toString(); } public ObjectName manageGemFireHealthConfig(String hostName) throws MalformedObjectNameException { try { GemFireHealthConfig config = getGemFireHealthConfig(hostName); GemFireHealthConfigJmxImpl jmx = (GemFireHealthConfigJmxImpl) config; return new ObjectName(jmx.getMBeanName()); } catch (RuntimeException e) { logger.warn(e.getMessage(), e); throw e; } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Error e) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); logger.error(e.getMessage(), e); throw e; } } /** * Creates a new {@link DistributedSystemHealthConfigJmxImpl} */ @Override protected DistributedSystemHealthConfig createDistributedSystemHealthConfig() { try { return new DistributedSystemHealthConfigJmxImpl(this); } catch (AdminException ex) { throw new RuntimeAdminException( "While getting the DistributedSystemHealthConfig", ex); } } /** * Creates a new {@link GemFireHealthConfigJmxImpl} */ @Override protected GemFireHealthConfig createGemFireHealthConfig(String hostName) { try { return new GemFireHealthConfigJmxImpl(this, hostName); } catch (AdminException ex) { throw new RuntimeAdminException( "While getting the GemFireHealthConfig", ex); } } /** * Ensures that the three primary Health MBeans are registered and returns their ObjectNames. */ protected void ensureMBeansAreRegistered() { MBeanUtil.ensureMBeanIsRegistered(this); MBeanUtil.ensureMBeanIsRegistered((ManagedResource) this.defaultConfig); MBeanUtil.ensureMBeanIsRegistered((ManagedResource) this.dsHealthConfig); } public String getMBeanName() { return this.mbeanName; } public ModelMBean getModelMBean() { return this.modelMBean; } public void setModelMBean(ModelMBean modelMBean) { this.modelMBean = modelMBean; } public ManagedResourceType getManagedResourceType() { return ManagedResourceType.GEMFIRE_HEALTH; } public ObjectName getObjectName() { return this.objectName; } public void cleanupResource() { close(); } }
13,426
https://github.com/GanymedeNil/srt2fcpxml/blob/master/core/FcpXML/Library/Event/Project/Sequence/Sequence.go
Github Open Source
Open Source
MIT
2,023
srt2fcpxml
GanymedeNil
Go
Code
91
440
package Sequence import ( "fmt" "srt2fcpxml/core/FcpXML/Common" "srt2fcpxml/core/FcpXML/Library/Event/Project/Sequence/Spine" "srt2fcpxml/core/FcpXML/Resources" "srt2fcpxml/lib" ) type Sequence struct { Text string `xml:",chardata"` Duration string `xml:"duration,attr"` Format string `xml:"format,attr"` TcStart string `xml:"tcStart,attr"` TcFormat string `xml:"tcFormat,attr"` AudioLayout string `xml:"audioLayout,attr"` AudioRate string `xml:"audioRate,attr"` Spine *Spine.Spine `xml:"spine"` } func NewSequence(duration float64) *Sequence { frameRate := Resources.GetFrameRate() frameRateR := Common.FrameDuration(frameRate) frameDurationMolecular, frameDurationDenominator, _ := Common.FrameDurationFormat(frameRate) return &Sequence{ Text: "", Duration: fmt.Sprintf("%.f/%.fs", lib.Round(duration*frameRateR, 0)*frameDurationMolecular, frameDurationDenominator), Format: "r1", TcStart: "0s", TcFormat: "NDF", AudioLayout: "stereo", AudioRate: "48k", Spine: &Spine.Spine{}, } } func (s *Sequence) SetSpine(spine *Spine.Spine) *Sequence { s.Spine = spine return s }
34,302
https://github.com/txtcn/new/blob/master/txt.py
Github Open Source
Open Source
MulanPSL-1.0
null
new
txtcn
Python
Code
107
336
#!/usr/bin/env python from os.path import join from os import walk import zd from io import StringIO from LAC import LAC def site_iter(dirpath): for root, dirli, fileli in walk(dirpath): for filename in fileli: yield root, filename def txt_iter(filepath): with zd.open(filepath) as f: f = iter(f) line = next(f) if not line: return r = [line[1:-1].lower()] next(f) for line in f: if line.startswith("➜"): yield r r = [line[1:-1].lower()] next(f) else: r.append(line[:-1].lower()) yield r def main(): # 装载分词模型 lac = LAC(mode='seg') dirpath = '/data/txtcn' for root, filename in site_iter(dirpath): filepath = join(root, filename) print(filename) for txt in txt_iter(filepath): for li in lac.run(txt): print(li) # input() if __name__ == "__main__": main()
45,729
https://github.com/charleslgn-old-school-project/DeskShop/blob/master/DeskShopCommon/src/main/java/com/deskshop/common/link/ServerInterface.java
Github Open Source
Open Source
Unlicense
2,019
DeskShop
charleslgn-old-school-project
Java
Code
201
608
package com.deskshop.common.link; import com.deskshop.common.constant.EStatusPaiement; import com.deskshop.common.metier.*; import java.rmi.Remote; import java.rmi.RemoteException; import java.util.HashMap; import java.util.List; public interface ServerInterface extends Remote { void addObserver(ClientInterface o) throws RemoteException; //__________________________ Manage user __________________________ int login(String mail, String psw) throws RemoteException; int createUser(Person user) throws RemoteException; List<Person> findAllUsers() throws RemoteException; //_______________________ Shop on DashBoard _______________________ int createShop(String name, int userId, String iban) throws RemoteException; List<Magasin> findAllMagasin(int userId) throws RemoteException; List<Magasin> findMagasinByUser(int userId) throws RemoteException; //_________________________ Manage a Shop _________________________ void addArticle(int idMagasin, String name, String desc, double price, String image, int stock) throws RemoteException; void deleteArticle(Article article) throws RemoteException; void updateArticle(Article article, String name, String desc, double price, int stock) throws RemoteException; List<Article> getArticleByMagasin(int id) throws RemoteException; void uploadFile(Article article, byte[] data, String name) throws RemoteException; //_________________________ Go Shopping ___________________________ EStatusPaiement paid(HashMap<Article, Integer> cadie, int idUser, String iban, int idMagasin) throws RemoteException; //______________________ Manage Bank Acount _______________________ void credit(double sum) throws RemoteException; List<Compte> findAllCompteByUser(int userId) throws RemoteException; boolean transfert(double somme, Compte compteGiver, Compte compteReceiver) throws RemoteException; boolean editSolde(double somme, Compte compteModife) throws RemoteException; boolean isBanker(int userId) throws RemoteException; List<Compte> getComptesByAdmin(int userId) throws RemoteException; List<Compte> findAllCompte() throws RemoteException; void createCompte(String nom, double amount, int client) throws RemoteException; //______________________ Manage Movement _______________________ List<Movement> findMovementByCompte(Compte compte) throws RemoteException; }
28,369
https://github.com/getbubblenow/javicle/blob/master/src/main/java/jvc/service/JIndexType.java
Github Open Source
Open Source
Apache-2.0
null
javicle
getbubblenow
Java
Code
23
74
package jvc.service; import com.fasterxml.jackson.annotation.JsonCreator; public enum JIndexType { single, from, to; @JsonCreator public static JIndexType fromString (String v) { return valueOf(v.toLowerCase()); } }
5,661
https://github.com/AutoPas/AutoPas/blob/master/tests/testAutopas/tests/selectors/TraversalSelectorTest.h
Github Open Source
Open Source
BSD-2-Clause
2,023
AutoPas
AutoPas
C++
Code
41
168
/** * @file TraversalSelectorTest.h * @author F. Gratl * @date 21.06.18 */ #pragma once #include <gtest/gtest.h> #include "AutoPasTestBase.h" #include "autopas/particles/Particle.h" #include "autopas/selectors/TraversalSelector.h" #include "mocks/MockFunctor.h" #include "testingHelpers/commonTypedefs.h" class TraversalSelectorTest : public AutoPasTestBase { public: TraversalSelectorTest() = default; ~TraversalSelectorTest() override = default; };
42,859
https://github.com/jyczju/CVprojects/blob/master/Project4/code/SplitMerge.py
Github Open Source
Open Source
MIT
null
CVprojects
jyczju
Python
Code
936
5,048
''' 图像切割+边缘识别 浙江大学控制学院《数字图像处理与机器视觉》第三次作业 jyczju 2022/4/6 v1.0 ''' import cv2 import numpy as np import sys from imgnode import ImgNode import matplotlib.pyplot as plt def region_split_merge(img, min_area=(1,1), threshold=5.0): ''' 区域分裂合并算法,主要依靠ImgNode类实现 输入:待处理图像,分裂的最小区域,合并的相似性判断阈值 输出:前后景分割后的二值化图像 ''' draw_img = img.copy() # 用于绘制分裂结果的图像 start_node = ImgNode(img, None, 0, img.shape[0], 0, img.shape[1]) # 创建起始节点,即整幅图像 draw_img = start_node.split(draw_img, min_area) # 区域分裂 leaf_father = start_node.find_leaf_father() # 寻找开始合并的节点 region_img = np.zeros((int(img.shape[0]), int(img.shape[1]))) # 二值化图像初始化 region_img = leaf_father.sub_node3.merge(region_img, threshold) # 区域合并 return region_img,draw_img def extract_contour(region_img): ''' 轮廓提取,某一像素周边若有背景像素,则认为其为轮廓 输入:二值化图像,目标像素为黑色,背景像素为白色 输出:轮廓图像,轮廓为黑色,背景为白色 ''' contour_img = region_img.copy() # 初始化轮廓图像 for h in range(1,region_img.shape[0]-1): for w in range(1,region_img.shape[1]-1): # 遍历图像中的每一点 if np.sum(region_img[h-1:h+2, w-1:w+2]) == 0: # 如果该点为黑色且周围全为白色,则认为该点为轮廓,8邻域 # if region_img[h][w] == 0 and region_img[h-1][w] == 0 and region_img[h+1][w] == 0 and region_img[h][w-1] == 0 and region_img[h][w+1] == 0: #4邻域 contour_img[h][w] = 255 # 若像素本身及其周围像素均为黑色,则其为内部点,将其置为白色 return contour_img def track_contour(img, start_point, all_cnts): ''' 轮廓跟踪 输入:边界图像,当前轮廓起始点,已被跟踪的轮廓点集合 输出:当前轮廓freeman链码 ''' neibor = [(0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1), (1, 0), (1, 1)] # 8连通方向码 dir = 5 # 起始搜索方向 freeman = [start_point] # 用于存储轮廓方向码 current_point = start_point # 将轮廓的开始点设为当前点 neibor_point = tuple(np.array(current_point) + np.array(neibor[dir])) # 通过当前点和邻域点集以及链码值确定邻点 if neibor_point[0] >= img.shape[0] or neibor_point[1] >= img.shape[1] or neibor_point[0] < 0 or neibor_point[1] < 0: # 若邻点超出边界,则轮廓结束 return freeman while True: # 轮廓扫描循环 # print('current_point',current_point) while img[neibor_point[0], neibor_point[1]] != 0: # 邻点不是边界点 dir += 1 # 逆时针旋转45度进行搜索 if dir >= 8: dir -= 8 neibor_point = tuple(np.array(current_point) + np.array(neibor[dir])) # 更新邻点 if neibor_point[0] >= img.shape[0] or neibor_point[1] >= img.shape[1] or neibor_point[0] < 0 or neibor_point[1] < 0: # 若邻点超出边界,则轮廓结束 return freeman else: current_point = neibor_point # 将符合条件的邻域点设为当前点进行下一次的边界点搜索 if current_point in all_cnts: # 如果当前点已经在轮廓中,则轮廓结束 return freeman freeman.append(dir) # 将当前方向码加入轮廓方向码list if (dir % 2) == 0: dir += 7 else: dir += 6 if dir >= 8: dir -= 8 # 更新方向 neibor_point = tuple(np.array(current_point) + np.array(neibor[dir])) # 更新邻点 if neibor_point[0] >= img.shape[0] or neibor_point[1] >= img.shape[1] or neibor_point[0] < 0 or neibor_point[1] < 0: # 若邻点超出边界,则轮廓结束 return freeman if current_point == start_point: break # 当搜索点回到起始点,搜索结束,退出循环 return freeman def draw_contour(img, contours, color=(0, 0, 255)): ''' 在img上绘制轮廓 输入:欲绘制的图像,轮廓链码,颜色 输出:绘制好的图像 ''' for (x, y) in contours: # 绘制轮廓 img[x-1:x+1, y-1:y+1] = color # 粗 # img_cnt[x,y] = color # 细 return img def find_start_point(img, all_cnts): ''' 寻找起始点 输入:边界图像,已被识别到的轮廓list 输出:起始点 ''' start_point = (-1, -1) # 初始化起始点 # 寻找起始点 for i in range(img.shape[0]): for j in range(img.shape[1]): if img[i, j] == 0 and (i, j) not in all_cnts: # 点为黑色且不在已识别到的轮廓list中 start_point = (i, j) # 找到新的起始点 break if start_point != (-1, -1): break return start_point def find_cnts(img): ''' 寻找轮廓集合 输入:边界图像 输出:轮廓集合(list,每一项都是一个轮廓链码) ''' contours = [] # 当前边界轮廓初始化 cnts = [] # 轮廓集合初始化 freemans = [] # 轮廓方向码集合初始化 all_cnts = [] # 所有已找到的轮廓点 while True: start_point = find_start_point(img, all_cnts) # 寻找当前边界的轮廓起始点 if start_point == (-1, -1): # 若找不到新的起始点,则说明所有的轮廓点都已被找到,退出循环 break freeman = track_contour(img, start_point, all_cnts) # 寻找当前边界的轮廓 contours = freeman2contour(freeman) # 将轮廓方向码转换为轮廓链码 cnts.append(contours) # 将找到的轮廓加入轮廓集合中 freemans.append(freeman) # 将找到的轮廓方向码加入轮廓方向码集合中 all_cnts = all_cnts + contours # 将找到的轮廓点加入轮廓点集合中 # 去掉短轮廓(干扰轮廓) fms = [] for fm in freemans: if len(fm) >= 10: fms.append(fm) return fms def draw_cnts(cntlists, img, color=(0, 0, 255), mode='freeman'): ''' 绘制所有轮廓 输入:轮廓集合,欲绘制的图像,颜色 输出:绘制好的图像 ''' if mode == 'freeman': for freeman in cntlists: cnt = freeman2contour(freeman) img = draw_contour(img, cnt, color) # 逐一绘制每个轮廓 elif mode == 'contour': for cnt in cntlists: img = draw_contour(img, cnt, color) # 逐一绘制每个轮廓 return img def contours_filter(freemans, windows_size = 13): ''' 对轮廓进行滤波(均值滤波) 输入:轮廓集合,滤波窗口大小 输出:滤波后的轮廓集合 ''' if (windows_size % 2) == 0: windows_size += 1 # 保证windows_size为奇数 cnts_filter = [] # 初始化滤波后的轮廓集合 for freeman in freemans: cnt = freeman2contour(freeman) # 将轮廓方向码转换为轮廓链码 for i in range(int((windows_size-1)/2), len(cnt)-int((windows_size-1)/2)): ix = np.mean([cnt[j][0] for j in range(i-int((windows_size-1)/2), i+int((windows_size-1)/2)+1)]) iy = np.mean([cnt[j][1] for j in range(i-int((windows_size-1)/2), i+int((windows_size-1)/2)+1)]) cnt[i] = (int(ix), int(iy)) # 均值滤波 cnts_filter.append(cnt) # 将滤波后的轮廓添加到集合中 return cnts_filter def freeman2contour(freeman): ''' 轮廓方向码转换为轮廓 输入:轮廓方向码 输出:轮廓 ''' neibor = [(0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1), (1, 0), (1, 1)] # 8连通方向码 cnt = [freeman[0]] # 初始化轮廓 for i in range(1,len(freeman)): cnt.append(tuple(np.array(cnt[-1]) + np.array(neibor[freeman[i]]))) return cnt def contour2freeman(cnt): ''' 轮廓转换为轮廓方向码 输入:轮廓 输出:轮廓方向码 ''' neibor = [(0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1), (1, 0), (1, 1)] # 8连通方向码 freeman = [] # 初始化轮廓方向码 for i in range(len(cnt)-1): freeman.append(neibor.index(tuple(np.array(cnt[i+1]) - np.array(cnt[i])))) return freeman if __name__ == '__main__': sys.setrecursionlimit(100000) # 设置最大允许递归深度 # read_path = 'zju_logo.png' # 设置读取图像的路径 # read_path = 'zjui_logo.png' # 设置读取图像的路径 # read_path = 'zju_logo_gauss.png' # 设置读取图像的路径 # read_path = 'zjui_logo_gauss.png' # 设置读取图像的路径 # read_path = 'zju_logo_uneven.png' # 设置读取图像的路径 read_path = 'zjui_logo_uneven.png' # 设置读取图像的路径 save_path = read_path[:-4]+'_results.png' # 设置保存图像的路径 print('save the result to '+save_path) img = cv2.imread(read_path, 0) # 读入图像 origin_img = img.copy() # 备份原始图像 # cv2.imshow('origin_img', origin_img) region_img,draw_img = region_split_merge(img, min_area=(1,1), threshold=5.0) # 5.0 # 区域分裂合并 # cv2.imshow('draw_img', draw_img) # 显示区域分裂结果 cv2.imwrite('draw_img.png', draw_img) # cv2.imshow('region_img', region_img) # 显示区域合并结果 region_img[0:20, 0:450] = 255 # 将区域图像中的一部分置为白色 region_img[275:300, 0:450] = 255 # 将区域图像中的一部分置为白色 region_img[0:300, 445:450] = 255 # 将区域图像中的一部分置为白色 cv2.imwrite('region_img.png', region_img) contour_img = extract_contour(region_img) # 轮廓提取 # cv2.imshow('contour_img', contour_img) # 显示轮廓图像 cv2.imwrite('contour_img.png', contour_img) freemans = find_cnts(contour_img) # 轮廓跟踪 print('freemans:') print(freemans) # img_cnt = cv2.cvtColor(origin_img, cv2.COLOR_GRAY2BGR) img_cnt = 255*np.ones([img.shape[0], img.shape[1], 3]) img_cnt = draw_cnts(freemans, img_cnt, color = (0, 0, 255), mode='freeman') # 绘制轮廓跟踪结果 # cv2.imshow('img_cnt', img_cnt) cv2.imwrite('img_cnt.png', img_cnt) cnts_filter = contours_filter(freemans, windows_size = 11) # 轮廓链码滤波 # img_cnt_filter = cv2.cvtColor(origin_img, cv2.COLOR_GRAY2BGR) img_cnt_filter = 255*np.ones([img.shape[0], img.shape[1], 3]) img_cnt_filter = draw_cnts(cnts_filter, img_cnt_filter, color=(255, 0, 0), mode='contour') # 绘制轮廓链码滤波结果 # cv2.imshow('img_cnt_filter', img_cnt_filter) cv2.imwrite('img_cnt_filter.png', img_cnt_filter) plt.figure(figsize=(9, 9.5)) title_size = 12 plt.subplot(321) plt.axis('off') plt.imshow(origin_img,cmap='gray') plt.title("Figure 1: Original image",fontdict={'weight':'normal','size': title_size}) plt.subplot(322) plt.axis('off') plt.imshow(draw_img,cmap='gray') plt.title("Figure 2: Splited image",fontdict={'weight':'normal','size': title_size}) plt.subplot(323) plt.axis('off') plt.imshow(region_img,cmap='gray') plt.title("Figure 3: Merged image",fontdict={'weight':'normal','size': title_size}) plt.subplot(324) plt.axis('off') plt.imshow(contour_img,cmap='gray') plt.title("Figure 4: Contours",fontdict={'weight':'normal','size': title_size}) plt.subplot(325) plt.axis('off') plt.imshow(cv2.cvtColor(img_cnt.astype(np.float32),cv2.COLOR_BGR2RGB)) plt.title("Figure 5: Contours tracked by ChainCode",fontdict={'weight':'normal','size': title_size}) plt.subplot(326) plt.axis('off') plt.imshow(cv2.cvtColor(img_cnt_filter.astype(np.float32),cv2.COLOR_BGR2RGB)) plt.title("Figure 6: Filtered Contours",fontdict={'weight':'normal','size': title_size}) plt.savefig(save_path, bbox_inches='tight') plt.show() cv2.waitKey(0)
43,572
https://github.com/eregon/noe/blob/master/lib/noe/show_spec.rb
Github Open Source
Open Source
MIT
2,011
noe
eregon
Ruby
Code
210
443
module Noe class Main # # Show the actual noe specification that would be used by 'noe go' # # SYNOPSIS # #{program_name} #{command_name} [SPEC_FILE] # # OPTIONS # #{summarized_options} # # DESCRIPTION # This command merges the .noespec file given as first parameter (or found in # the current folder) with the noespec.yaml file of the template and prints # the result on the standard output. # # When 'noe go' is invoked, the actual specification it works with is the # merging of what you specify in your .noespec file with default values # provided by the template specification itself. In other words, your .noespec # file simply overrides the default values provided in the template itself. # # Therefore, you can always keep your .noespec files simple by not specifying # entries for which the default value is ok. However, making so could lead you # to forget about some template options and this command is useful is such # situations. # class ShowSpec < Quickl::Command(__FILE__, __LINE__) include Noe::Commons options do |opt| Commons.add_common_options(opt) end def execute(args) raise Quickl::Help if args.size > 1 spec_file = find_noespec_file(args) spec = YAML::load(File.read(spec_file)) template = template(spec['template-info']['name']) template.merge_spec(spec) puts template.to_yaml end end # class ShowSpec end # class Main end # module Noe
10,550
https://github.com/stichting-cito/QuestifyBuilder/blob/master/Builder/Plugins/PaperBased/Reports/UI/SelectReportLocation.vb
Github Open Source
Open Source
MS-PL
2,019
QuestifyBuilder
stichting-cito
Visual Basic
Code
122
466
Imports System.Windows.Forms Imports System.ComponentModel Imports System.IO Imports Questify.Builder.Configuration Public Class SelectReportLocation Implements INotifyPropertyChanged Private _OverWriteFileName As Boolean Public Event PropertyChanged(sender As Object, e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged Public Sub New() InitializeComponent() _OverWriteFileName = False Me.DataBindings.Add(New Binding("OverWriteFileName", Me.OptionValidatorWordExportBindingSource, "OverwriteExisting", False, DataSourceUpdateMode.OnPropertyChanged)) End Sub Private Sub BrowseButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BrowseButton.Click ErrorProvider.Clear If Not String.IsNullOrEmpty(FileNameTextBox.Text) Then SaveFileDialog.FileName = IO.Path.GetFileName(FileNameTextBox.Text) End If If SaveFileDialog.ShowDialog = DialogResult.OK Then FileNameTextBox.Text = SaveFileDialog.FileName ReportSettings.WordReport = Path.GetDirectoryName(FileNameTextBox.Text) Me.ValidateChildren() OverWriteFileName = IO.File.Exists(SaveFileDialog.FileName) End If Me.ValidateChildren() End Sub Private Sub NotyfyProperty(ByVal propName As String) RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propName)) End Sub <Bindable(True, BindingDirection.TwoWay)> Public Property OverWriteFileName() As Boolean Get Return _OverWriteFileName End Get Set(ByVal value As Boolean) _OverWriteFileName = value NotyfyProperty("OverWriteFileName") End Set End Property End Class
23,786
https://github.com/Phamdan7700/laravel-my-website/blob/master/app/Http/Controllers/CategoryController.php
Github Open Source
Open Source
MIT
null
laravel-my-website
Phamdan7700
PHP
Code
337
1,145
<?php namespace App\Http\Controllers; use App\Http\Requests\CategoryRequest; use App\Models\Category as MainModel; use App\Repositories\Interfaces\CategoryRepositoryInterface; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Str; class CategoryController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ protected $viewName = 'category'; protected $viewAdmin; protected $viewAdminForm; protected $viewPage; protected $numPageAdmin; protected $categoryRepository; public function __construct(CategoryRepositoryInterface $categoryRepository) { $this->categoryRepository = $categoryRepository; $this->viewAdmin = 'admin.' . $this->viewName; $this->viewAdminForm = 'admin.' . $this->viewName . '-form'; $this->viewPage = 'page' . $this->viewName; $this->numPageAdmin = config('admin.num_page_admin'); } public function index(Request $request) { $viewName = $this->viewName; $items = $this->categoryRepository->getAll(); $countAll = count($items); $countActive = count($items->where('status', '1')); $countInActive = count($items->where('status', '0')); return view( $this->viewAdmin, compact(['items', 'viewName', 'countAll', 'countActive', 'countInActive']) ); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view($this->viewAdminForm); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(CategoryRequest $request) { $items = $this->categoryRepository->create( [ 'name' => $request->name, 'slug' => Str::of($request->name)->slug('-'), 'order' => '1', 'status' => $request->status, 'created_by' => Auth::user()->id, ] ); $items->save(); return back()->with('success', 'Thêm thành công !!!'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $items = $this->categoryRepository->find($id); return view('index', compact('items')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $item = $this->categoryRepository->find($id); return view($this->viewAdminForm, compact('item')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(CategoryRequest $request, $id) { $this->categoryRepository->update($id, [ 'name' => $request->name, 'slug' => Str::of($request->name)->slug('-'), 'status' => $request->status, 'updated_by' => Auth::user()->id, ]); return redirect()->route('admin.category.index')->with('success', 'Update succesfully!'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { try { $this->categoryRepository->delete($id); } catch (\Throwable $error) { return back()->with('error', "Lỗi ! Không thể xóa"); } return back()->with('success', 'Delete Succesfully'); } public function changeStatus($id) { return $this->categoryRepository->changeStatus($id); } }
49,795
https://github.com/facebook/mcrouter/blob/master/mcrouter/OptionsUtil.cpp
Github Open Source
Open Source
MIT
2,023
mcrouter
facebook
C++
Code
131
410
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "OptionsUtil.h" #include <boost/filesystem/path.hpp> #include <folly/Format.h> #include <folly/Range.h> #include "mcrouter/options.h" namespace fs = boost::filesystem; namespace facebook { namespace memcache { namespace mcrouter { namespace { std::string getDebugFifoFullPath( const McrouterOptions& opts, folly::StringPiece fifoName) { assert(!opts.debug_fifo_root.empty()); auto directory = fs::path(opts.debug_fifo_root); auto file = fs::path( folly::sformat("{}.{}.{}", getStatPrefix(opts), fifoName, "debugfifo")); return (directory / file).string(); } } // anonymous namespace std::string getStatPrefix(const McrouterOptions& opts) { return folly::sformat( "libmcrouter.{}.{}", opts.service_name, opts.router_name); } std::string getClientDebugFifoFullPath(const McrouterOptions& opts) { return getDebugFifoFullPath(opts, "client"); } std::string getServerDebugFifoFullPath(const McrouterOptions& opts) { return getDebugFifoFullPath(opts, "server"); } } // namespace mcrouter } // namespace memcache } // namespace facebook
27,630
https://github.com/EdinburghGenomics/clarity_scripts/blob/master/prodscripts/Autoplacement96.py
Github Open Source
Open Source
MIT
2,022
clarity_scripts
EdinburghGenomics
Python
Code
254
978
#!/usr/bin/env python __author__ = 'dcrawford' from optparse import OptionParser from xml.dom.minidom import parseString from EPPs import glsapiutil def autoPlace(): stepdetailsXML = api.GET(args.stepURI + "/details") stepdetails = parseString(stepdetailsXML) ## Create the input output map iomap = {} for io in stepdetails.getElementsByTagName("input-output-map"): output = io.getElementsByTagName("output")[0] if output.getAttribute("type") == "Analyte": input = io.getElementsByTagName("input")[0] iomap[output.getAttribute("uri")] = input.getAttribute("uri") artifacts = parseString(api.getArtifacts(list(iomap.keys()) + list(iomap.values()))) ## Map the original locations of the artfacts inputMap = {} for art in artifacts.getElementsByTagName("art:artifact"): artURI = art.getAttribute("uri").split("?state")[0] if artURI in list(iomap.values()): location = art.getElementsByTagName("container")[0].getAttribute("uri") well = art.getElementsByTagName("value")[0].firstChild.data inputMap[artURI] = [location, well] inputContainers = list(set([c[0] for c in list( inputMap.values())])) # if the order of containers is going to be important, sort them here <- stepplacementsXML = api.GET(args.stepURI + "/placements") stepplacements = parseString(stepplacementsXML) output384 = stepplacements.getElementsByTagName("container")[0].getAttribute("uri") # writing the new placement XML from scratch sendplacement = [ '<stp:placements xmlns:stp="http://genologics.com/ri/step" uri="' + args.stepURI + '/placements"><step uri="' + args.stepURI + '" rel="steps"/><output-placements>'] for outArt in stepplacements.getElementsByTagName("output-placement"): outArtURI = outArt.getAttribute("uri") inputLocation = inputMap[iomap[outArtURI]] containerIndex = inputContainers.index(inputLocation[0]) sourceWell = inputLocation[1] # if len( inputContainers ) == 4: value = sourceWell # else: # value = wheredoesitgo_1to3plates( containerIndex, sourceWell ) sendplacement.append( '<output-placement uri="' + outArtURI + '"><location><container uri="' + output384 + '" limsid="' + output384.split("/containers/")[1] + '"/><value>' + value + '</value></location></output-placement>') sendplacement.append('</output-placements></stp:placements>') r = api.POST(''.join(sendplacement), args.stepURI + "/placements") def setupArguments(): Parser = OptionParser() Parser.add_option('-u', "--username", action='store', dest='username') Parser.add_option('-p', "--password", action='store', dest='password') Parser.add_option('-s', "--stepURI", action='store', dest='stepURI') return Parser.parse_args()[0] api = None def main(): global args args = setupArguments() global api api = glsapiutil.glsapiutil2() api.setURI(args.stepURI) api.setup(args.username, args.password) autoPlace() if __name__ == "__main__": main()
39,088
https://github.com/ferhatelmas/algo/blob/master/leetCode/algorithms/easy/find_all_anagrams_in_a_string.py
Github Open Source
Open Source
WTFPL
2,021
algo
ferhatelmas
Python
Code
58
145
from collections import Counter class Solution(object): def findAnagrams(self, s, p): lp, ls = len(p), [] sc, pc, p = Counter(s[: lp - 1]), Counter(p), 0 for i, c in enumerate(s[lp - 1 :], start=lp - 1): sc[c] += 1 if sc == pc: ls.append(p) sc[s[p]] -= 1 if sc[s[p]] == 0: del sc[s[p]] p += 1 return ls
15,143
https://github.com/croz-ltd/nrich/blob/master/nrich-form-configuration/src/test/java/net/croz/nrich/formconfiguration/service/DefaultFormConfigurationServiceTest.java
Github Open Source
Open Source
Apache-2.0
2,022
nrich
croz-ltd
Java
Code
308
1,561
/* * Copyright 2020-2022 CROZ d.o.o, the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.croz.nrich.formconfiguration.service; import net.croz.nrich.formconfiguration.FormConfigurationTestConfiguration; import net.croz.nrich.formconfiguration.api.model.ConstrainedPropertyClientValidatorConfiguration; import net.croz.nrich.formconfiguration.api.model.ConstrainedPropertyConfiguration; import net.croz.nrich.formconfiguration.api.model.FormConfiguration; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import java.util.Collections; import java.util.Comparator; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.catchThrowable; @SpringJUnitConfig(FormConfigurationTestConfiguration.class) class DefaultFormConfigurationServiceTest { @Autowired private DefaultFormConfigurationService formConfigurationService; @Test void shouldThrowExceptionWhenNoFormConfigurationHasBeenDefinedForFormId() { // given List<String> formIdList = Collections.singletonList("invalidFormId"); // when Throwable thrown = catchThrowable(() -> formConfigurationService.fetchFormConfigurationList(formIdList)); // then assertThat(thrown).isInstanceOf(IllegalArgumentException.class); } @Test void shouldResolveSimpleFormFieldConfiguration() { // given List<String> formIdList = Collections.singletonList(FormConfigurationTestConfiguration.SIMPLE_FORM_CONFIGURATION_FORM_ID); // when List<FormConfiguration> resultList = formConfigurationService.fetchFormConfigurationList(formIdList); // then assertThat(resultList).hasSize(1); // and when FormConfiguration formConfiguration = resultList.get(0); // then assertThat(formConfiguration.getFormId()).isEqualTo(FormConfigurationTestConfiguration.SIMPLE_FORM_CONFIGURATION_FORM_ID); assertThat(formConfiguration.getConstrainedPropertyConfigurationList()).hasSize(4); assertThat(formConfiguration.getConstrainedPropertyConfigurationList()).extracting(ConstrainedPropertyConfiguration::getPath).containsExactlyInAnyOrder( "name", "lastName", "timestamp", "value" ); assertThat(formConfiguration.getConstrainedPropertyConfigurationList().get(0).getValidatorList()).hasSize(1); formConfiguration.getConstrainedPropertyConfigurationList().sort(Comparator.comparing(ConstrainedPropertyConfiguration::getPath)); // and when ConstrainedPropertyClientValidatorConfiguration lastNameValidatorConfiguration = formConfiguration.getConstrainedPropertyConfigurationList().get(0).getValidatorList().get(0); // then assertThat(lastNameValidatorConfiguration).isNotNull(); assertThat(lastNameValidatorConfiguration.getName()).isEqualTo("Size"); assertThat(lastNameValidatorConfiguration.getArgumentMap().values()).containsExactly(1, 5); assertThat(lastNameValidatorConfiguration.getErrorMessage()).isEqualTo("Size must be between: 1 and 5"); } @Test void shouldResolveNestedFormConfiguration() { // given List<String> formIdList = Collections.singletonList(FormConfigurationTestConfiguration.NESTED_FORM_CONFIGURATION_FORM_ID); // when List<FormConfiguration> resultList = formConfigurationService.fetchFormConfigurationList(formIdList); // then assertThat(resultList).hasSize(1); // and when FormConfiguration formConfiguration = resultList.get(0); // then assertThat(formConfiguration.getFormId()).isEqualTo(FormConfigurationTestConfiguration.NESTED_FORM_CONFIGURATION_FORM_ID); assertThat(formConfiguration.getConstrainedPropertyConfigurationList()).hasSize(5); assertThat(formConfiguration.getConstrainedPropertyConfigurationList()).extracting(ConstrainedPropertyConfiguration::getPath).containsExactlyInAnyOrder( "name", "request.name", "request.lastName", "request.timestamp", "request.value" ); formConfiguration.getConstrainedPropertyConfigurationList().sort(Comparator.comparing(ConstrainedPropertyConfiguration::getPath)); assertThat(formConfiguration.getConstrainedPropertyConfigurationList().get(4).getValidatorList()).hasSize(1); // and when ConstrainedPropertyClientValidatorConfiguration valueValidatorConfiguration = formConfiguration.getConstrainedPropertyConfigurationList().get(4).getValidatorList().get(0); // then assertThat(valueValidatorConfiguration).isNotNull(); assertThat(valueValidatorConfiguration.getName()).isEqualTo("Min"); assertThat(valueValidatorConfiguration.getArgumentMap().values()).containsExactly(10L); assertThat(valueValidatorConfiguration.getErrorMessage()).isEqualTo("Minimum value is: 10"); } @Test void shouldIgnoreNestedFieldConfigurationWhenFieldIsNotValidated() { // given List<String> formIdList = Collections.singletonList(FormConfigurationTestConfiguration.NESTED_FORM_NOT_VALIDATED_CONFIGURATION_FORM_ID); // when List<FormConfiguration> resultList = formConfigurationService.fetchFormConfigurationList(formIdList); // then assertThat(resultList).hasSize(1); // and when FormConfiguration formConfiguration = resultList.get(0); // then assertThat(formConfiguration.getFormId()).isEqualTo(FormConfigurationTestConfiguration.NESTED_FORM_NOT_VALIDATED_CONFIGURATION_FORM_ID); assertThat(formConfiguration.getConstrainedPropertyConfigurationList()).isEmpty(); } }
26,595
https://github.com/Fishkudda/fobot/blob/master/Server.py
Github Open Source
Open Source
MIT
null
fobot
Fishkudda
Python
Code
1,166
4,391
import os import re import threading import datetime import time as t import Database PATH_TO_SERVER = str(os.environ.get('PATH_TO_SERVER')) SERVER_NAME = str(os.environ.get('SERVER_NAME')) SCREEN_NAME = str(os.environ.get('SCREEN_NAME')) class Server: def __init__(self,telegram_bot): self.update_counter = 0 self.screen_id = "" self.ip = "" self.name = "" self.options = "" self.current_map = "" self.players = [] self.map_list = [] self.cap_time = None self.telegram_bot = telegram_bot walk_dir = os.walk(PATH_TO_SERVER + "/csgo/maps") for x, y, z in walk_dir: for map in z: if map.split('.')[-1] == 'bsp': map_name = map.split('.')[0] self.map_list.append(map_name) Database.database_create_maps(self.map_list) # Update Once by Init self.update() # Set Timer to Update self.update_daemon = self.update_daemon(20) self.user_input_daemon = self.user_input_daemon(5) def __repr__(self): return "Server:{} on {} map: {} player: {} bots: {}".format(self.name, self.ip, self.current_map, self.get_number_of_players(), self.get_number_of_bots()) def load_cfg(self, cfg): move_cfg = "cp {} {}/csgo/cfg/{}".format(cfg.path, PATH_TO_SERVER, cfg.name) res = os.system(move_cfg) if res != 0: return "Error cant move file from {} to {}".format_map(cfg.path, PATH_TO_SERVER) exec_cfg = "screen -S {} -X stuff 'exec {}\r'".format(self.screen_id, cfg.name) res_exec = os.system(exec_cfg) if res_exec == 0: return "Executes {} Cfg".format(cfg.name) else: return "Error cant exec {}".format(cfg.name) def change_level(self, name_id): sys_var = "screen -S {} -X stuff 'changelevel {}\r'".format( self.screen_id, name_id) os.system(sys_var) def add_player(self, player): self.players.append(player) def just_say(self,message): sys_var = "screen -S {} -X stuff 'say {}\r'".format( self.screen_id,message) os.system(sys_var) def get_number_of_players(self): return len( [player for player in self.get_players() if not player.is_bot]) def get_number_of_bots(self): return len([player for player in self.get_players() if player.is_bot]) def get_players(self): return self.players def set_current_map(self, current_map): self.current_map = current_map def get_current_map(self): return self.current_map def get_map_list(self): return self.map_list def update_daemon(self, interval): class Update_Thread(threading.Thread): def __init__(self, interval, mother_class): threading.Thread.__init__(self) self.interval = interval self.mother_class = mother_class def run(self): while True: try: self.mother_class.update() t.sleep(self.interval) except Exception as Exception_update: print(Exception_update) return Update_Thread(interval, self).start() def user_input_daemon(self,interval): class UserInputThread(threading.Thread): def __init__(self, interval, mother_class): threading.Thread.__init__(self) self.interval = interval self.mother_class = mother_class def run(self): while True: try: self.mother_class.user_input_update() #t.sleep(self.interval) except Exception as Exception_user_input: print(Exception_user_input) return UserInputThread(interval, self).start() def user_input_update(self): os.system('screen -ls > /tmp/screenoutput') with open('/tmp/screenoutput', 'r') as file: result = file.readlines() self.screen_id = "" if (result[0] == 'There is a screen on:\r\n') or ( result[0] == 'There are screens on:\n') or ( result[0] == 'There is a screen on:\n'): for index, line in enumerate(result): if SCREEN_NAME in line: split_res = result[index].split('.')[0] screen_id = split_res.strip('\t') self.screen_id = screen_id if self.screen_id == "": return False cap_time = "echo "+str(datetime.datetime.utcnow())+'\n' sys_var = "screen -S {} -X stuff '{}\r'".format(screen_id, cap_time) if not self.cap_time: self.cap_time = cap_time os.system(sys_var) path_to_screenlog = PATH_TO_SERVER + "/screenlog.0" output = [] ret_counter = 4 while (self.cap_time not in output) and (cap_time not in output) and (ret_counter >= 0): try: t.sleep(7) ret_counter = ret_counter - 1 with open(path_to_screenlog, 'r') as file: output = file.readlines() except Exception as Exception_get_log: print(Exception_get_log) ret_counter = ret_counter - 1 if (self.cap_time not in output) or (cap_time not in output): return False output.reverse() end_index = None start_index = None data_input = None for index,line in enumerate(output): if line == self.cap_time: end_index = index elif line == cap_time: start_index = index if end_index and start_index: break if end_index and start_index: data_input = output[start_index:end_index] if not data_input: return False self.cap_time = cap_time player_list = Database.get_all_player() player_dic = {player.name: player for player in player_list} try: player_names = [re.escape(player.name+':') for player in player_list] j_names = r'|'.join(player_names) except Exception as Exception_create_regex: print("Fail creating regex") print(Exception_create_regex) return False msg = "" data_input.reverse() for line in data_input: if re.search(j_names, line) or re.match(r'Console:', line): msg = msg + "{}\n".format(line) if line.split(':')[-1].strip() == '!like': name = line.split(':')[0].strip() if '*DEAD*' in name: name = "".join(name.split('*')[3:]).strip() voted_msg = Database.create_votes(name, self.current_map, True) self.just_say(voted_msg) if line.split(':')[-1].strip() == '!dislike': name = line.split(':')[0].strip() if '*DEAD*' in name: name = "".join(name.split('*')[3:]).strip() voted_msg = Database.create_votes(name,self.current_map, False) self.just_say(voted_msg) index = 0 name = line.split(':')[index].strip() if '*DEAD*' in name: index = 3 name = "".join(name.split('*')[index:]).strip() print(name) if (name in player_dic.keys()) or (name == "Console"): first_w = line.split(':')[index+1].split(' ')[1] if '!ticket' == first_w: self.telegram_bot.dispatcher.bot.sendMessage( self.telegram_bot.chat_id, text="{} TICKET FROM: {}\nTEXT: {}".format(datetime.datetime.utcnow().strftime('%c'),name,line)) self.just_say("Your Ticket {} was send.".format(name)) if msg != "" and self.telegram_bot.talk: self.telegram_bot.dispatcher.bot.sendMessage(self.telegram_bot.chat_id, text=msg) def update(self): os.system('screen -ls > /tmp/screenoutput') with open('/tmp/screenoutput', 'r') as file: result = file.readlines() self.screen_id = "" if (result[0] == 'There is a screen on:\r\n') or ( result[0] == 'There are screens on:\n') or ( result[0] == 'There is a screen on:\n'): for index, line in enumerate(result): if SCREEN_NAME in line: split_res = result[index].split('.')[0] screen_id = split_res.strip('\t') self.screen_id = screen_id if self.screen_id == "": return False sys_var = "screen -S {} -X stuff 'status\r'".format(screen_id) os.system(sys_var) t.sleep(10) path_to_screenlog = PATH_TO_SERVER + "/screenlog.0" with open(path_to_screenlog, 'r') as file: output = file.readlines() output.reverse() i = 0 i_end = 0 if '#end\n' in output: for index, line in enumerate(output): if line == "#end\n": i = index if 'hostname:' in line: i_end = index break info_range = range(i, i_end) info_list = [] for i in info_range: info_list.append(output[i]) info_list.reverse() ip = "" name = SERVER_NAME for i, text in enumerate(info_list): s_text = text.split(' ') if 'map' == s_text[0]: current_map = s_text[-1].rstrip() if 'udp/ip' == s_text[0]: for tab in s_text: if re.match( r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b:\d{5}', tab): ip = tab self.ip = ip self.name = name self.current_map = current_map try: status_db = Database.create_server_status_ticker(self) except Exception as Database_Exception: print(Database_Exception) print("Database Error cant save server_status") self.players = [] for i, text in enumerate(info_list): s_text = text.split(' ') id = s_text[0].strip('#') id_f = 0 if id == "": id_f = 1 id = s_text[1] if 'BOT' in s_text: try: name_start = 0 name_end = 0 for index, char in enumerate(s_text): if ('"' in char) and (name_start == 0): name_start = index if 'BOT' == char: name_end = index name = " ".join(s_text[name_start:name_end]).strip('"') except: name = 'UNKNOWN_PLAYER_BOT' is_bot = True player = Player(id=id, name=name, is_bot=is_bot, server=self) steam_id = "NO_STEAM_ID_FOR_BOT_{}".format(name) Database.create_player_status(datetime.datetime.utcnow(),name,steam_id) self.add_player(player) elif re.match(r"^#[0-9]", s_text[0]): i = 0 id = s_text[1].strip('#') try: name = s_text[3] while name[-1] != '"': name = name + s_text[3 + i] i = i + 1 except: name = 'UNKNOWN_PLAYER' steam_id = "NO_ID_{}".format(name) is_bot = False for tab in s_text: if 'BOT' in tab: is_bot = True if re.match(r'^STEAM_',tab): steam_id = tab player = Player(id=id, name=name, is_bot=is_bot, server=self, steam_id=steam_id, ip=s_text[-1]) self.add_player(player) Database.create_player_status(datetime.datetime.utcnow(), name, steam_id) elif (s_text[0] == '#' and re.match(r'^[0-9]',s_text[2])): i = 0 id = s_text[1].strip('#') try: name = s_text[3] while name[-1] != '"': name = name + s_text[3 + i] i = i + 1 except: name = 'UNKNOWN_PLAYER' steam_id = "NO_ID_{}".format(name) is_bot = False for tab in s_text: if 'BOT' in tab: is_bot = True if re.match(r'^STEAM_',tab): steam_id = tab name = name.strip('"') player = Player(id=id, name=name, is_bot=is_bot, server=self, steam_id=steam_id, ip=s_text[-1]) Database.create_player_status(datetime.datetime.utcnow(), name, steam_id) self.add_player(player) print(str(self) + " " + datetime.datetime.utcnow().strftime( '%c') + " UPDATE DONE") self.update_counter = self.update_counter + 1 #Database.calculate_next_map_pool() return self class Player: def __init__(self, id, is_bot, name, server, steam_id=None, ip=None): self.id = id self.is_bot = is_bot self.name = name self.ip = ip self.server = server self.steam_id = steam_id def __repr__(self): return "Player: ID {} {}\n".format(self.id, self.name) def kick_player(self): screen_id = self.server.screen_id sys_var = "screen -S {} -X stuff 'kickid {}\r'".format(screen_id, self.id) os.system(sys_var) return self def to_spectators(self): screen_id = self.server.screen_id sys_var = "screen -S {} -X stuff 'sm_spec #{}\r'".format(screen_id, self.id) os.system(sys_var) return self def ban_player(self): screen_id = self.server.screen_id sys_var = "screen -S {} -X stuff 'banid {}\r'".format(screen_id, self.id) os.system(sys_var) return self
1,104
https://github.com/neil841004/Cube-Adventure/blob/master/Assets/Scripts/Function/ChangeLevelTitle.cs
Github Open Source
Open Source
MIT
null
Cube-Adventure
neil841004
C#
Code
145
392
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ChangeLevelTitle : MonoBehaviour { public int levelID = 0; public Text text_1; public Text text_2; string newText; // Start is called before the first frame update void Start() { if (levelID == 5) { if (GameData.levelOrder[0] == 5) newText = "Level 1-A"; if (GameData.levelOrder[0] == 6) newText = "Level 1-B"; } if (levelID == 6) { if (GameData.levelOrder[0] == 5) newText = "Level 1-B"; if (GameData.levelOrder[0] == 6) newText = "Level 1-A"; } if (levelID == 8) { if (GameData.levelOrder[2] == 8) newText = "Level 2-A"; if (GameData.levelOrder[2] == 9) newText = "Level 2-B"; } if (levelID == 9) { if (GameData.levelOrder[2] == 8) newText = "Level 2-B"; if (GameData.levelOrder[2] == 9) newText = "Level 2-A"; } if (levelID > 4 && levelID < 10) { text_1.text = newText; text_2.text = newText; } } }
23,960
https://github.com/kintone/kintone-java-client/blob/master/src/main/java/com/kintone/client/api/space/UpdateSpaceGuestsRequest.java
Github Open Source
Open Source
MIT, GPL-2.0-only, BSD-3-Clause, Apache-2.0, CDDL-1.0, MPL-2.0, EPL-1.0, Classpath-exception-2.0
2,023
kintone-java-client
kintone
Java
Code
50
126
package com.kintone.client.api.space; import com.kintone.client.api.KintoneRequest; import java.util.List; import lombok.Data; /** A request object for Update Guest Members API. */ @Data public class UpdateSpaceGuestsRequest implements KintoneRequest { /** The Guest Space ID (required). */ private Long id; /** A list of email addresses of Guest users (required). */ private List<String> guests; }
1,679
https://github.com/stevage/demsausage-v3/blob/master/admin/src/elections/ElectionsManager/ElectionsManager.tsx
Github Open Source
Open Source
MIT
null
demsausage-v3
stevage
TypeScript
Code
331
1,253
import * as React from "react" import styled from "styled-components" import { Link, browserHistory } from "react-router" import { IElection } from "../../redux/modules/interfaces" // import "./ElectionsManager.css" import { Table, TableBody, TableRow, TableRowColumn } from "material-ui/Table" import { ListItem } from "material-ui/List" import RaisedButton from "material-ui/RaisedButton" import IconButton from "material-ui/IconButton" import { FileFileUpload, FileCloudDownload, ImageRemoveRedEye, NavigationRefresh, ToggleStar, ToggleStarBorder, ActionPowerSettingsNew, } from "material-ui/svg-icons" import { green500, red600, yellow600 } from "material-ui/styles/colors" // Fixes issues with tooltips and tables // https://github.com/mui-org/material-ui/issues/5912 const TableRowColumnWithIconButtons = styled(TableRowColumn)` overflow: visible !important; ` const ElectionTableRowColumn = styled(TableRowColumn)` padding-left: 0px !important; ` export interface IProps { elections: Array<IElection> onMakeElectionPrimary: any onDownloadElection: any onRegenerateElectionGeoJSON: any } class ElectionsManager extends React.PureComponent<IProps, {}> { onClickElection: Function onClickFileUpload: Function onMakeElectionPrimary: Function constructor(props: any) { super(props) this.onClickElection = (election: any) => { browserHistory.push(`/election/${election.id}/`) } this.onClickFileUpload = (election: any) => { browserHistory.push(`/election/${election.id}/load_polling_places/`) } this.onMakeElectionPrimary = (election: any) => { this.props.onMakeElectionPrimary(election.id) } } render() { const { elections, onDownloadElection, onRegenerateElectionGeoJSON } = this.props return ( <div> <RaisedButton label={"Create Election"} primary={true} containerElement={<Link to={`/election/new`} />} /> <Table selectable={false}> <TableBody displayRowCheckbox={false}> {elections.map((election: IElection) => ( <TableRow key={election.id} selectable={false}> <ElectionTableRowColumn> <ListItem primaryText={election.name} secondaryText={new Date(election.election_day).toLocaleDateString("en-AU", { weekday: "long", day: "2-digit", month: "long", year: "numeric", })} onClick={this.onClickElection.bind(this, election)} /> </ElectionTableRowColumn> <TableRowColumnWithIconButtons> {election.is_primary === true && ( <IconButton tooltip={"This election is the primary election"} onClick={this.onMakeElectionPrimary.bind(this, election)} > <ToggleStar color={yellow600} /> </IconButton> )} {election.is_primary === false && ( <IconButton tooltip={"Make this election the primary election"} onClick={this.onMakeElectionPrimary.bind(this, election)} > <ToggleStarBorder hoverColor={yellow600} /> </IconButton> )} {election.is_active ? ( <IconButton tooltip={"This election is live!"}> <ActionPowerSettingsNew color={green500} /> </IconButton> ) : null} {election.hidden ? ( <IconButton tooltip={"This election is hidden - only admins can see it"}> <ImageRemoveRedEye color={red600} /> </IconButton> ) : null} </TableRowColumnWithIconButtons> <TableRowColumnWithIconButtons> <IconButton tooltip="Load a new polling places file" onClick={this.onClickFileUpload.bind(this, election)} > <FileFileUpload /> </IconButton> <IconButton tooltip="Download this election as an Excel file" onClick={onDownloadElection.bind(this, election)} > <FileCloudDownload /> </IconButton> <IconButton tooltip="Refresh the map data for this election" onClick={onRegenerateElectionGeoJSON.bind(this, election)} > <NavigationRefresh /> </IconButton> </TableRowColumnWithIconButtons> </TableRow> ))} </TableBody> </Table> </div> ) } } export default ElectionsManager
146
https://github.com/morganstanley/testplan/blob/master/tests/functional/testplan/runnable/interactive/test_reloader.py
Github Open Source
Open Source
MIT, Apache-2.0
2,023
testplan
morganstanley
Python
Code
1,156
5,062
"""Interactive reload tests.""" import os import sys import subprocess import tempfile import pytest from testplan.runnable.interactive.reloader import _GraphModuleFinder THIS_DIRECTORY = os.path.dirname(os.path.abspath(__file__)) @pytest.mark.parametrize( "script_content, module_deps", ( ("import outer", {"__main__": ("outer",)}), ( "import outer.mod", { "__main__": ("outer", "outer.mod"), }, ), ( "from outer import mod", { "__main__": ("outer", "outer.mod"), }, ), ( "import outer.mod.VAL", { "__main__": ("outer", "outer.mod"), }, ), ( "from outer.mod import VAL", { "__main__": ("outer", "outer.mod"), }, ), ( "import outer.middle", { "__main__": ("outer", "outer.middle"), "outer.middle": ( "outer", "outer.middle", "outer.middle.extra", "outer.middle.inner", "outer.middle.mod", ), "outer.middle.inner": ( "outer", "outer.middle", "outer.middle.empty", "outer.middle.inner.mod1", "outer.middle.inner.mod2", ), "outer.middle.extra": ( "outer", "outer.middle", "outer.middle.extra", "outer.middle.extra.mod1", "outer.middle.extra.mod2", ), }, ), ( "from outer import middle", { "__main__": ("outer", "outer.middle"), "outer.middle": ( "outer", "outer.middle", "outer.middle.extra", "outer.middle.inner", "outer.middle.mod", ), "outer.middle.inner": ( "outer", "outer.middle", "outer.middle.empty", "outer.middle.inner.mod1", "outer.middle.inner.mod2", ), "outer.middle.extra": ( "outer", "outer.middle", "outer.middle.extra", "outer.middle.extra.mod1", "outer.middle.extra.mod2", ), }, ), ( "import outer.middle.mod", { "__main__": ("outer", "outer.middle", "outer.middle.mod"), "outer.middle": ( "outer", "outer.middle", "outer.middle.extra", "outer.middle.inner", "outer.middle.mod", ), "outer.middle.inner": ( "outer", "outer.middle", "outer.middle.empty", "outer.middle.inner.mod1", "outer.middle.inner.mod2", ), "outer.middle.extra": ( "outer", "outer.middle", "outer.middle.extra", "outer.middle.extra.mod1", "outer.middle.extra.mod2", ), }, ), ( "from outer.middle import mod", { # "outer.middle" imports "mod" internally "__main__": ("outer", "outer.middle"), "outer.middle": ( "outer", "outer.middle", "outer.middle.extra", "outer.middle.inner", "outer.middle.mod", ), "outer.middle.inner": ( "outer", "outer.middle", "outer.middle.empty", "outer.middle.inner.mod1", "outer.middle.inner.mod2", ), "outer.middle.extra": ( "outer", "outer.middle", "outer.middle.extra", "outer.middle.extra.mod1", "outer.middle.extra.mod2", ), }, ), ( "import outer.middle.mod.VAL", { "__main__": ("outer", "outer.middle", "outer.middle.mod"), "outer.middle": ( "outer", "outer.middle", "outer.middle.extra", "outer.middle.inner", "outer.middle.mod", ), "outer.middle.inner": ( "outer", "outer.middle", "outer.middle.empty", "outer.middle.inner.mod1", "outer.middle.inner.mod2", ), "outer.middle.extra": ( "outer", "outer.middle", "outer.middle.extra", "outer.middle.extra.mod1", "outer.middle.extra.mod2", ), }, ), ( "from outer.middle.mod import VAL", { "__main__": ("outer", "outer.middle", "outer.middle.mod"), "outer.middle": ( "outer", "outer.middle", "outer.middle.extra", "outer.middle.inner", "outer.middle.mod", ), "outer.middle.inner": ( "outer", "outer.middle", "outer.middle.empty", "outer.middle.inner.mod1", "outer.middle.inner.mod2", ), "outer.middle.extra": ( "outer", "outer.middle", "outer.middle.extra", "outer.middle.extra.mod1", "outer.middle.extra.mod2", ), }, ), ( "import outer.middle.inner", { "__main__": ("outer", "outer.middle", "outer.middle.inner"), "outer.middle": ( "outer", "outer.middle", "outer.middle.extra", "outer.middle.inner", "outer.middle.mod", ), "outer.middle.inner": ( "outer", "outer.middle", "outer.middle.empty", "outer.middle.inner.mod1", "outer.middle.inner.mod2", ), "outer.middle.extra": ( "outer", "outer.middle", "outer.middle.extra", "outer.middle.extra.mod1", "outer.middle.extra.mod2", ), }, ), ( "from outer.middle import inner", { # "outer.middle" imports "inner" internally "__main__": ("outer", "outer.middle"), "outer.middle": ( "outer", "outer.middle", "outer.middle.extra", "outer.middle.inner", "outer.middle.mod", ), "outer.middle.inner": ( "outer", "outer.middle", "outer.middle.empty", "outer.middle.inner.mod1", "outer.middle.inner.mod2", ), "outer.middle.extra": ( "outer", "outer.middle", "outer.middle.extra", "outer.middle.extra.mod1", "outer.middle.extra.mod2", ), }, ), ( "from outer.middle import *", { # In "__main__": "import *" cannot build dependency "__main__": ("outer", "outer.middle"), "outer.middle": ( "outer", "outer.middle", "outer.middle.extra", "outer.middle.inner", "outer.middle.mod", ), "outer.middle.inner": ( "outer", "outer.middle", "outer.middle.empty", "outer.middle.inner.mod1", "outer.middle.inner.mod2", ), "outer.middle.extra": ( "outer", "outer.middle", "outer.middle.extra", "outer.middle.extra.mod1", "outer.middle.extra.mod2", ), }, ), ( "import outer.middle.inner.mod1", { "__main__": ( "outer", "outer.middle", "outer.middle.inner", "outer.middle.inner.mod1", ), "outer.middle": ( "outer", "outer.middle", "outer.middle.extra", "outer.middle.inner", "outer.middle.mod", ), "outer.middle.inner": ( "outer", "outer.middle", "outer.middle.empty", "outer.middle.inner.mod1", "outer.middle.inner.mod2", ), "outer.middle.extra": ( "outer", "outer.middle", "outer.middle.extra", "outer.middle.extra.mod1", "outer.middle.extra.mod2", ), }, ), ( "from outer.middle.inner import mod1", { # "outer.middle.inner" imports "mod1" internally "__main__": ("outer", "outer.middle", "outer.middle.inner"), "outer.middle": ( "outer", "outer.middle", "outer.middle.extra", "outer.middle.inner", "outer.middle.mod", ), "outer.middle.inner": ( "outer", "outer.middle", "outer.middle.empty", "outer.middle.inner.mod1", "outer.middle.inner.mod2", ), "outer.middle.extra": ( "outer", "outer.middle", "outer.middle.extra", "outer.middle.extra.mod1", "outer.middle.extra.mod2", ), }, ), ( "import outer.middle.inner.mod2", { "__main__": ( "outer", "outer.middle", "outer.middle.inner", "outer.middle.inner.mod2", ), "outer.middle": ( "outer", "outer.middle", "outer.middle.extra", "outer.middle.inner", "outer.middle.mod", ), "outer.middle.inner": ( "outer", "outer.middle", "outer.middle.empty", "outer.middle.inner.mod1", "outer.middle.inner.mod2", ), "outer.middle.extra": ( "outer", "outer.middle", "outer.middle.extra", "outer.middle.extra.mod1", "outer.middle.extra.mod2", ), }, ), ( "from outer.middle.inner import mod2", { # "outer.middle.inner" imports "mod2" internally "__main__": ("outer", "outer.middle", "outer.middle.inner"), "outer.middle": ( "outer", "outer.middle", "outer.middle.extra", "outer.middle.inner", "outer.middle.mod", ), "outer.middle.inner": ( "outer", "outer.middle", "outer.middle.empty", "outer.middle.inner.mod1", "outer.middle.inner.mod2", ), "outer.middle.extra": ( "outer", "outer.middle", "outer.middle.extra", "outer.middle.extra.mod1", "outer.middle.extra.mod2", ), }, ), ( "from outer.middle.inner.mod2 import *", { "__main__": ( "outer", "outer.middle", "outer.middle.inner", "outer.middle.inner.mod2", ), "outer.middle": ( "outer", "outer.middle", "outer.middle.extra", "outer.middle.inner", "outer.middle.mod", ), "outer.middle.inner": ( "outer", "outer.middle", "outer.middle.empty", "outer.middle.inner.mod1", "outer.middle.inner.mod2", ), "outer.middle.extra": ( "outer", "outer.middle", "outer.middle.extra", "outer.middle.extra.mod1", "outer.middle.extra.mod2", ), }, ), ( "import outer.middle.extra", { "__main__": ("outer", "outer.middle", "outer.middle.extra"), "outer.middle": ( "outer", "outer.middle", "outer.middle.extra", "outer.middle.inner", "outer.middle.mod", ), "outer.middle.inner": ( "outer", "outer.middle", "outer.middle.empty", "outer.middle.inner.mod1", "outer.middle.inner.mod2", ), "outer.middle.extra": ( "outer", "outer.middle", "outer.middle.extra", "outer.middle.extra.mod1", "outer.middle.extra.mod2", ), }, ), ( "from outer.middle import extra", { # "outer.middle" imports "extra" internally "__main__": ("outer", "outer.middle"), "outer.middle": ( "outer", "outer.middle", "outer.middle.extra", "outer.middle.inner", "outer.middle.mod", ), "outer.middle.inner": ( "outer", "outer.middle", "outer.middle.empty", "outer.middle.inner.mod1", "outer.middle.inner.mod2", ), "outer.middle.extra": ( "outer", "outer.middle", "outer.middle.extra", "outer.middle.extra.mod1", "outer.middle.extra.mod2", ), }, ), ( "import outer.middle.extra import *", { # In "__main__": "import *" cannot build dependency "__main__": ("outer", "outer.middle"), "outer.middle": ( "outer", "outer.middle", "outer.middle.extra", "outer.middle.inner", "outer.middle.mod", ), "outer.middle.inner": ( "outer", "outer.middle", "outer.middle.empty", "outer.middle.inner.mod1", "outer.middle.inner.mod2", ), "outer.middle.extra": ( "outer", "outer.middle", "outer.middle.extra", "outer.middle.extra.mod1", "outer.middle.extra.mod2", ), }, ), ), ) def atest_find_module(script_content, module_deps): """ Check that `_GraphModuleFinder` utility can correctly build dependency graph between imported modules. We should verify that all import statements should be correctly traced and a dependency relationship between modules can be built. Consider these cases: -- import foo -- import foo.bar -- import foo.bar.VAL -- from foo import bar -- from foo.bar import VAL -- from foo.bar import * -- from . import bar (inside foo) -- from .bar import VAL (inside foo) -- from .bar import * (inside foo) -- import foo.baz -- from .. import bar (inside baz) So we design the various testcases to verify that we can correctly find dependency relationship among the packages and modules we are using. Some corner cases should be considered. In __init__.py file of a package, with or without imports in it, things can be different. A known example, when bar/__init__.py has "from . import qux" or "from .qux import sth", then `_GraphModuleFinder` gets difference result for 2 statements: -- import foo.bar.qux -- from foo.bar import qux Suppose you are importing "qux" in your "__main__" module, For the former, "__main__" directly depends on "foo", "foo.bar" and "foo.bar.qux", also, "foo.bar" depends on "foo.bar.qux", while for the latter, "__main__" only depends on "foo" and "foo.bar", it means "__main__" indirectly depends on "foo.bar.qux". Our `_GraphModuleFinder` is based on the standard library `modulefinder`, overrides its `import_hook` and `import_module` methods, refer to: -- https://github.com/python/cpython/blob/3.7/Lib/modulefinder.py#L214 When importing "bar", the module "qux" will be loaded before "bar" is completely ready, thus "bar" should have an attribute called "qux", from the line above, we can know that when "__main__" loads "qux" from "bar", this piece of code is skipped and `import_module` method is not called, so, no direct dependency is built between "__main__" and "foo.bar.qux". Since that all direct/indirect dependencies will be recognized during reloading and our solution could work properly. An exception is that "from package import *" cannot always work. refer to: -- https://github.com/python/cpython/blob/3.7/Lib/modulefinder.py#L375 All names represent * will be added into local namespace, however, no `import_module` is called and no direct dependency is built (although there might be indirect dependencies but that is not guaranteed). Just bear in mind that importing everything of a module is not encouraged in Python. """ script_path = None try: with tempfile.NamedTemporaryFile("w", delete=False) as fp: fp.write(f"{script_content}\n") fp.flush() script_path = fp.name finder = _GraphModuleFinder(path=[THIS_DIRECTORY]) try: finder.run_script(script_path) except OSError: raise RuntimeError( f"Could not run main module {script_path} as a script." ) except Exception as err: print(err) else: if len(module_deps) > 0: assert len(finder._module_deps) == len(module_deps) for mod, deps in finder._module_deps.items(): assert module_deps[mod.__name__] == tuple( sorted(dep.__name__ for dep in deps) ) finally: if script_path: os.remove(script_path) def test_reload(): """Tests reload functionality.""" subprocess.check_call( [sys.executable, "interactive_executable.py"], cwd=os.path.dirname(os.path.abspath(__file__)), )
45,571
https://github.com/scala-steward/dag4s/blob/master/src/main/scala/github/dmarticus/dag/core/LazyNode.scala
Github Open Source
Open Source
MIT
null
dag4s
scala-steward
Scala
Code
76
250
package github.dmarticus.dag.core case class LazyNode[+A](get: () => A) { import LazyNode._ def map[B](f: A => B): LazyNode[B] = lazyNode(f(get())) def flatMap[B](f: A => LazyNode[B]): LazyNode[B] = map(f(_).get()) def map2[B, C](that: LazyNode[B])(f: (A, B) => C): LazyNode[C] = for { a <- this b <- that } yield f(a, b) } object LazyNode { def lazyNode[A](f: => A): LazyNode[A] = { lazy val value = f LazyNode(() => value) } def sequence[A](as: Seq[LazyNode[A]]): LazyNode[Seq[A]] = lazyNode(as.map(_.get())) }
20,533
https://github.com/narroxs93/Office/blob/master/app/Resources/views/index.html.twig
Github Open Source
Open Source
MIT
null
Office
narroxs93
Twig
Code
214
868
{# plantilla de segundo nivel de la aplicación porque de momento se necesita un navbar a todas partes. #} {% extends "layout.html.twig" %} {% block title %}Backoffice{% endblock %} {% block stylesheets %} <link href="http://getbootstrap.com/examples/starter-template/starter-template.css" rel="stylesheet"> {% endblock %} {% block fos_body %}{% endblock %} {% block navbar %} <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="{{ path('index') }}">Backoffice</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="{{ path('dashboard') }}">Dashboard</a></li> <li><a href="{{ path('avisos') }}">Avisos</a></li> <li><a href="{{ path('bloques') }}">Bloques</a></li> <li><a href="{{ path('comunicaciones') }}">Comunicaciones</a></li> <li><a href="{{ path('configuracion') }}">Configuración</a></li> <li><a href="{{ path('fos_user_security_login') }}">Log in</a></li> </ul> </div><!--/.nav-collapse --> </div> </nav> {% endblock %} {% block content %} <div class="container"> <div class="starter-template"> <h1>Ésta es tu BackOffice</h1> <p class="lead">Aquí tienes diferentes opciones para gestionar tu tienda.</p> <p><a href="{{ path('dashboard') }}">Dashboard.</a> </p> <p><a href="{{ path('avisos') }}">Avisos.</a> </p> <p><a href="{{ path('bloques') }}">Bloques.</a> </p> <p><a href="{{ path('comunicaciones') }}">Comunicaciones.</a> </p> <p><a href="{{ path('configuracion') }}">Configuración.</a> </p> <br> <p class="lead">Bienvenido a la gestión de tu tienda. </p> <p><a href="{{ path('fos_user_security_login') }}">Log in.</a> </p> <p><a href="{{ path('fos_user_security_logout') }}">Logout.</a></p> <p><a href="{{ path('fos_user_registration_register') }}">Register.</a></p> <br> {% for flashMessage in app.session.flashbag.get('notice') %} <div class="flash-notice"> {{ flashMessage }} </div> {% endfor %} </div> </div><!-- /.container --> {% endblock %}
50,763
https://github.com/pmdartus/dependabot-tester/blob/master/packages/@lwc/synthetic-shadow/src/env/slot.ts
Github Open Source
Open Source
MIT
2,020
dependabot-tester
pmdartus
TypeScript
Code
126
280
/* * Copyright (c) 2018, salesforce.com, inc. * All rights reserved. * SPDX-License-Identifier: MIT * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT */ let assignedNodes: (options?: AssignedNodesOptions) => Node[], assignedElements: (options?: AssignedNodesOptions) => Element[]; if (typeof HTMLSlotElement !== 'undefined') { assignedNodes = HTMLSlotElement.prototype.assignedNodes; assignedElements = HTMLSlotElement.prototype.assignedElements; } else { assignedNodes = () => { throw new TypeError( "assignedNodes() is not supported in current browser. Load the @lwc/synthetic-shadow polyfill to start using <slot> elements in your Lightning Web Component's template" ); }; assignedElements = () => { throw new TypeError( "assignedElements() is not supported in current browser. Load the @lwc/synthetic-shadow polyfill to start using <slot> elements in your Lightning Web Component's template" ); }; } export { assignedNodes, assignedElements };
14,929
https://github.com/inkaku/infra/blob/master/.gitignore
Github Open Source
Open Source
MIT
2,016
infra
inkaku
Ignore List
Code
6
21
# Compiled files *.tfstate.backup .envrc .terraform
26,291
https://github.com/henryco/Escapy/blob/master/src/com/game/utils/primitives/EscapyLine.java
Github Open Source
Open Source
Apache-2.0
2,018
Escapy
henryco
Java
Code
239
640
package com.game.utils.primitives; import com.badlogic.gdx.math.Vector2; // TODO: Auto-generated Javadoc /* * TODO INTERSECTION, INCLUDES and other collision methods * @author HenryCo */ /** * The Class EscapyLine. */ public class EscapyLine { private Vector2 start, end; /** * Instantiates a new escapy line. * * @param start * the start * @param end * the end */ public EscapyLine(Vector2 start, Vector2 end) { this.setStart(start); this.setEnd(end); return; } /** * Instantiates a new escapy line. * * @param x1 * the x 1 * @param y1 * the y 1 * @param x2 * the x 2 * @param y2 * the y 2 */ public EscapyLine(float x1, float y1, float x2, float y2) { this.setStart(new Vector2(x1, y1)); this.setEnd(new Vector2(x2, y2)); return; } /** * Instantiates a new escapy line. * * @param start * the start * @param end * the end */ public EscapyLine(float[] start, float[] end) { this.setStart(new Vector2(start[0], start[1])); this.setEnd(new Vector2(end[0], end[1])); return; } /** * Gets the start. * * @return the start */ public Vector2 getStart() { return start; } /** * Sets the start. * * @param start * the new start */ public void setStart(Vector2 start) { this.start = start; } /** * Gets the end. * * @return the end */ public Vector2 getEnd() { return end; } /** * Sets the end. * * @param end * the new end */ public void setEnd(Vector2 end) { this.end = end; } }
27,472
https://github.com/churchsocial/ebenezer/blob/master/sass/all.scss
Github Open Source
Open Source
MIT
null
ebenezer
churchsocial
SCSS
Code
18
71
@import "normalize"; @import "html5-boilerplate"; @import "mixins"; @import "fonts"; @import "button"; @import "template"; @import "wysiwyg"; @import "calendar"; @import "sermon_archive";
24,740
https://github.com/chromium/chromium/blob/master/chromeos/ash/services/bluetooth_config/system_properties_provider_impl.cc
Github Open Source
Open Source
BSD-3-Clause
2,023
chromium
chromium
C++
Code
239
1,051
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromeos/ash/services/bluetooth_config/system_properties_provider_impl.h" #include "base/logging.h" #include "base/trace_event/trace_event.h" #include "chromeos/ash/services/bluetooth_config/fast_pair_delegate.h" #include "components/session_manager/core/session_manager.h" #include "components/user_manager/user_manager.h" namespace ash::bluetooth_config { SystemPropertiesProviderImpl::SystemPropertiesProviderImpl( AdapterStateController* adapter_state_controller, DeviceCache* device_cache, FastPairDelegate* fast_pair_delegate) : adapter_state_controller_(adapter_state_controller), device_cache_(device_cache), fast_pair_delegate_(fast_pair_delegate) { adapter_state_controller_observation_.Observe( adapter_state_controller_.get()); device_cache_observation_.Observe(device_cache_.get()); session_manager::SessionManager::Get()->AddObserver(this); if (fast_pair_delegate_) { fast_pair_delegate_observation_.Observe(fast_pair_delegate_.get()); } } SystemPropertiesProviderImpl::~SystemPropertiesProviderImpl() { session_manager::SessionManager* session_manager = session_manager::SessionManager::Get(); // |session_manager| is null when we are shutting down and this class is being // destroyed because there is no longer a session. if (session_manager) session_manager->RemoveObserver(this); } void SystemPropertiesProviderImpl::OnAdapterStateChanged() { NotifyPropertiesChanged(); } void SystemPropertiesProviderImpl::OnSessionStateChanged() { TRACE_EVENT0("login", "SystemPropertiesProviderImpl::OnSessionStateChanged"); NotifyPropertiesChanged(); } void SystemPropertiesProviderImpl::OnPairedDevicesListChanged() { NotifyPropertiesChanged(); } void SystemPropertiesProviderImpl::OnFastPairableDevicesChanged( const std::vector<mojom::PairedBluetoothDevicePropertiesPtr>& fast_pairable_devices) { NotifyPropertiesChanged(); } mojom::BluetoothSystemState SystemPropertiesProviderImpl::ComputeSystemState() const { return adapter_state_controller_->GetAdapterState(); } std::vector<mojom::PairedBluetoothDevicePropertiesPtr> SystemPropertiesProviderImpl::GetPairedDevices() const { return device_cache_->GetPairedDevices(); } std::vector<mojom::PairedBluetoothDevicePropertiesPtr> SystemPropertiesProviderImpl::GetFastPairableDevices() const { if (fast_pair_delegate_) { return fast_pair_delegate_->GetFastPairableDeviceProperties(); } else { return std::vector<mojom::PairedBluetoothDevicePropertiesPtr>(); } } mojom::BluetoothModificationState SystemPropertiesProviderImpl::ComputeModificationState() const { // Bluetooth power setting is always mutable in login screen before any // user logs in. The changes will affect local state preferences. // // Otherwise, the bluetooth setting should be mutable only if: // * the active user is the primary user, and // * the session is not in lock screen // The changes will affect the primary user's preferences. if (!session_manager::SessionManager::Get()->IsSessionStarted()) return mojom::BluetoothModificationState::kCanModifyBluetooth; if (session_manager::SessionManager::Get()->IsScreenLocked()) return mojom::BluetoothModificationState::kCannotModifyBluetooth; return user_manager::UserManager::Get()->GetPrimaryUser() == user_manager::UserManager::Get()->GetActiveUser() ? mojom::BluetoothModificationState::kCanModifyBluetooth : mojom::BluetoothModificationState::kCannotModifyBluetooth; } } // namespace ash::bluetooth_config
1,272
https://github.com/i-gaven/Just_a_dumper/blob/master/all_headers/聚美优品 - 优选好物,精致生活-5.810(越狱应用)_headers/SCLiveShowEndView.h
Github Open Source
Open Source
MIT
2,018
Just_a_dumper
i-gaven
Objective-C
Code
246
1,131
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import <UIKit/UIView.h> @class NSArray, NSLayoutConstraint, NSString, RACSignal, SCAttentionBusiness, SCDesignableButton, SCLiveBusiness, SCLiveVipLevelNode, UIButton, UIImageView, UILabel, UIWindow; @interface SCLiveShowEndView : UIView { UIView *_gradeContainerView; UILabel *_fansCountLabel; UILabel *_hotLabel; UILabel *_lookNumberLabel; UIImageView *_logoImageView; UIImageView *_vipImageView; NSLayoutConstraint *_space3HeightCons; NSLayoutConstraint *_vipWCons; NSLayoutConstraint *_vipHCons; UILabel *_nickNameLabel; UIImageView *_sexImageView; UILabel *_certification; UILabel *_sigLabel; UIView *_jumpToHotLiveContainerView; UILabel *_jumpToHotLiveTimerLabel; UILabel *_jumpToHotLiveShowLabel; SCAttentionBusiness *_attentionBusiness; SCLiveBusiness *_liveBusiness; long long _countdownTime; NSString *_jumpToLiveURL; _Bool _followed; _Bool _hadEnterRoom; _Bool _hasJumpToOtherLiveAuth; NSString *_anchorUserId; NSString *_liveId; CDUnknownBlockType _confirmCloseLive; CDUnknownBlockType _jumpToHotLive; UIButton *_closeButton; SCDesignableButton *_followBtn; NSArray *_hiddenViews; SCLiveVipLevelNode *_vipNode; UIWindow *_tmpWindow; RACSignal *_lifeUntilSignal; RACSignal *_enterBackgroundSignal; } + (id)creatView; @property(retain, nonatomic) RACSignal *enterBackgroundSignal; // @synthesize enterBackgroundSignal=_enterBackgroundSignal; @property(retain, nonatomic) RACSignal *lifeUntilSignal; // @synthesize lifeUntilSignal=_lifeUntilSignal; @property(retain, nonatomic) UIWindow *tmpWindow; // @synthesize tmpWindow=_tmpWindow; @property(retain, nonatomic) SCLiveVipLevelNode *vipNode; // @synthesize vipNode=_vipNode; @property(retain, nonatomic) NSArray *hiddenViews; // @synthesize hiddenViews=_hiddenViews; @property(nonatomic) __weak SCDesignableButton *followBtn; // @synthesize followBtn=_followBtn; @property(nonatomic) __weak UIButton *closeButton; // @synthesize closeButton=_closeButton; @property(copy, nonatomic) CDUnknownBlockType jumpToHotLive; // @synthesize jumpToHotLive=_jumpToHotLive; @property(copy, nonatomic) CDUnknownBlockType confirmCloseLive; // @synthesize confirmCloseLive=_confirmCloseLive; @property(nonatomic) _Bool hasJumpToOtherLiveAuth; // @synthesize hasJumpToOtherLiveAuth=_hasJumpToOtherLiveAuth; @property(nonatomic) _Bool hadEnterRoom; // @synthesize hadEnterRoom=_hadEnterRoom; @property(nonatomic) _Bool followed; // @synthesize followed=_followed; @property(copy, nonatomic) NSString *liveId; // @synthesize liveId=_liveId; @property(copy, nonatomic) NSString *anchorUserId; // @synthesize anchorUserId=_anchorUserId; - (void).cxx_destruct; - (void)dealloc; - (void)refreshFollowNumberWithAddNumber:(long long)arg1; - (void)addAttention:(id)arg1; - (void)closeLive:(id)arg1; - (void)updateFollowBtnState:(_Bool)arg1; - (void)_jumpToHotLive:(id)arg1; - (void)_checkIfJumpToHotLive:(id)arg1; - (void)hiddenJumpToHotLiveContainerView; - (void)fetchUserInfoWithUserId:(id)arg1 excess:(_Bool)arg2; - (void)_init; - (void)awakeFromNib; - (void)hiddenEndView; - (void)showEndView; @end
27,168
https://github.com/emumba-com/assembla-exporter/blob/master/index.test.js
Github Open Source
Open Source
Apache-2.0
2,017
assembla-exporter
emumba-com
JavaScript
Code
59
165
const reqVal = timeout => { console.log(`[reqVal] invoked with timeout ${timeout}`) return new Promise(resolve => { // conosle.log(`Setting timeout with i=${i}`) setTimeout(() => { resolve(timeout) }, timeout) }) } async function *download() { // reqVal(1).then(v => console.log(v)) yield 1 // reqVal(1000) yield 2 // reqVal(2000) } ;(async () => { const it = download() console.log(await it.next()) console.log(await it.next()) })()
5,792
https://github.com/sepehr-laal/nofx/blob/master/nofx/nofx_ofTexture/nofx_ofGetUsingArbTex.cc
Github Open Source
Open Source
MIT
null
nofx
sepehr-laal
C++
Code
24
111
#include "nofx_ofGetUsingArbTex.h" #include "ofTexture.h" namespace nofx { namespace ClassWrappers { NAN_METHOD(nofx_ofGetUsingArbTex) { NanReturnValue(ofGetUsingArbTex()); } // !nofx_ofGetUsingArbTex } // !namespace ClassWrappers } // !namespace nofx
4,231
https://github.com/ducptruong/DnMFk/blob/master/install_dependencies/xianyi-OpenBLAS-6d2da63/lapack/CMakeFiles/ztrti2_LU.c
Github Open Source
Open Source
BSD-3-Clause
2,021
DnMFk
ducptruong
C
Code
26
158
#define UNIT #define ASMNAME ztrti2_LU #define ASMFNAME ztrti2_LU_ #define NAME ztrti2_LU_ #define CNAME ztrti2_LU #define CHAR_NAME "ztrti2_LU_" #define CHAR_CNAME "ztrti2_LU" #define DOUBLE #define COMPLEX #include "/lustre/scratch3/turquoise/rvangara/RD100/distnnmfkcpp_Src/install_dependencies/xianyi-OpenBLAS-6d2da63/lapack/trti2/ztrti2_L.c"
48,441
https://github.com/aleandrodalan/ponto-inteligente-api/blob/master/src/main/java/br/com/aleandro/pontointeligente/api/services/EmpresaService.java
Github Open Source
Open Source
MIT
null
ponto-inteligente-api
aleandrodalan
Java
Code
17
94
package br.com.aleandro.pontointeligente.api.services; import java.util.Optional; import br.com.aleandro.pontointeligente.api.entities.Empresa; public interface EmpresaService { Optional<Empresa> buscarPorCnpj(String cpnj); Empresa persistir(Empresa empresa); }
17,820
https://github.com/antonybholmes/edbw-django-app/blob/master/api/migrations/0001_initial.py
Github Open Source
Open Source
MIT
null
edbw-django-app
antonybholmes
Python
Code
533
3,339
# Generated by Django 3.0 on 2020-01-07 20:48 import django.contrib.postgres.fields.jsonb from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='APIKey', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('key', models.CharField(max_length=255)), ], options={ 'db_table': 'api_key', }, ), migrations.CreateModel( name='DataType', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('created', models.DateTimeField()), ], options={ 'db_table': 'data_types', }, ), migrations.CreateModel( name='Element', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('path', models.CharField(max_length=255)), ], options={ 'db_table': 'genomic_elements', }, ), migrations.CreateModel( name='ElementType', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ], options={ 'db_table': 'genomic_elements_types', }, ), migrations.CreateModel( name='Experiment', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('description', models.CharField(max_length=255)), ('created', models.DateTimeField(verbose_name='%Y-%m-%d')), ], options={ 'db_table': 'experiments', }, ), migrations.CreateModel( name='Genome', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('created', models.DateTimeField()), ], options={ 'db_table': 'genomes', }, ), migrations.CreateModel( name='Group', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('color', models.CharField(max_length=255)), ('created', models.DateTimeField()), ('json', django.contrib.postgres.fields.jsonb.JSONField()), ], options={ 'db_table': 'group', }, ), migrations.CreateModel( name='GroupPerson', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField()), ], options={ 'db_table': 'groups_persons', }, ), migrations.CreateModel( name='Keyword', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('created', models.DateTimeField()), ], options={ 'db_table': 'keywords', }, ), migrations.CreateModel( name='Organism', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('scientific_name', models.CharField(max_length=255)), ('created', models.DateTimeField()), ], options={ 'db_table': 'organisms', }, ), migrations.CreateModel( name='Person', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(max_length=255)), ('last_name', models.CharField(max_length=255)), ('email', models.CharField(max_length=255)), ('api_key', models.CharField(max_length=64)), ('created', models.DateTimeField()), ('json', django.contrib.postgres.fields.jsonb.JSONField()), ], options={ 'db_table': 'persons', }, ), migrations.CreateModel( name='Role', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ], options={ 'db_table': 'role', }, ), migrations.CreateModel( name='Sample', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('experiment_id', models.IntegerField()), ('name', models.CharField(max_length=255)), ('organism_id', models.IntegerField()), ('expression_type_id', models.IntegerField()), ('created', models.DateTimeField(verbose_name='%Y-%m-%d')), ('json', django.contrib.postgres.fields.jsonb.JSONField(default=list)), ], options={ 'db_table': 'samples', }, ), migrations.CreateModel( name='SampleFile', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], options={ 'db_table': 'sample_files', }, ), migrations.CreateModel( name='SampleGroup', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], options={ 'db_table': 'sample_groups', }, ), migrations.CreateModel( name='SamplePerson', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], options={ 'db_table': 'sample_persons', }, ), migrations.CreateModel( name='Set', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ], options={ 'db_table': 'sets', }, ), migrations.CreateModel( name='Tag', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('alt_name', models.CharField(max_length=255)), ], options={ 'db_table': 'tags', }, ), migrations.CreateModel( name='TagKeywordSearch', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField()), ('keyword', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.Keyword')), ('tag', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.Tag')), ], options={ 'db_table': 'tags_keywords_search', }, ), migrations.CreateModel( name='TagType', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ], options={ 'db_table': 'tag_types', }, ), migrations.CreateModel( name='TrackType', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ], options={ 'db_table': 'ucsc_track_types', }, ), migrations.CreateModel( name='VFSFile', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('parent_id', models.IntegerField()), ('name', models.CharField(max_length=255)), ('path', models.CharField(max_length=255)), ('type_id', models.IntegerField()), ('created', models.DateTimeField()), ('json', django.contrib.postgres.fields.jsonb.JSONField()), ], options={ 'db_table': 'vfs', }, ), migrations.CreateModel( name='Track', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('url', models.CharField(max_length=255)), ('sample', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.Sample')), ('track_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.TrackType')), ], options={ 'db_table': 'ucsc_tracks', }, ), migrations.CreateModel( name='TagSampleSearch', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField()), ('sample', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.Sample')), ('tag_keyword_search', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.TagKeywordSearch')), ], options={ 'db_table': 'tags_samples_search', }, ), migrations.CreateModel( name='SetSample', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('sample', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.Sample')), ('set', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.Set')), ], options={ 'db_table': 'sets_samples', }, ), migrations.CreateModel( name='SampleTag', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('str_value', models.CharField(max_length=255)), ('int_value', models.IntegerField()), ('float_value', models.FloatField()), ('created', models.DateTimeField()), ('json', django.contrib.postgres.fields.jsonb.JSONField(default=list)), ('sample', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.Sample')), ('tag', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.Tag')), ('tag_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.TagType')), ], options={ 'db_table': 'sample_tags', }, ), ]
7,777