hexsha
stringlengths 40
40
| size
int64 5
1.05M
| ext
stringclasses 98
values | lang
stringclasses 21
values | max_stars_repo_path
stringlengths 3
945
| max_stars_repo_name
stringlengths 4
118
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
sequencelengths 1
10
| max_stars_count
int64 1
368k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 3
945
| max_issues_repo_name
stringlengths 4
118
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
sequencelengths 1
10
| max_issues_count
int64 1
134k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 3
945
| max_forks_repo_name
stringlengths 4
135
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
sequencelengths 1
10
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 5
1.05M
| avg_line_length
float64 1
1.03M
| max_line_length
int64 2
1.03M
| alphanum_fraction
float64 0
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3f93098b0e16d11bbda5d7e6f57eceac9432d5b7 | 750 | php | PHP | console/migrations/m160904_025732_init_user.php | dinhduy7895/Yii2-Tour | 11091a50ddc37cc711326e7147be626e75614e1e | [
"BSD-3-Clause"
] | null | null | null | console/migrations/m160904_025732_init_user.php | dinhduy7895/Yii2-Tour | 11091a50ddc37cc711326e7147be626e75614e1e | [
"BSD-3-Clause"
] | null | null | null | console/migrations/m160904_025732_init_user.php | dinhduy7895/Yii2-Tour | 11091a50ddc37cc711326e7147be626e75614e1e | [
"BSD-3-Clause"
] | null | null | null | <?php
use yii\db\Migration;
use common\models\User;
class m160904_025732_init_user extends Migration
{
public function up()
{
$model = new User();
$model->setAttributes(array(
'username' => 'user',
'email' =>'[email protected]',
'role' => User::ROLE_USER,
'avatar' => 'no-image.jpg'
));
$model->setPassword("abc123");
$model->generateAuthKey();
$model->save(false);
}
public function down()
{
User::deleteAll(array('email' => '[email protected]'));
}
/*
// Use safeUp/safeDown to run migration code within a transaction
public function safeUp()
{
}
public function safeDown()
{
}
*/
}
| 19.230769 | 69 | 0.534667 |
588627e4ad141a004a3eba8296a916256d2b2255 | 12,058 | php | PHP | tests/Functional/Controller/Action/User/Account/NewsSubscriptionsControllerTest.php | majacQ/web.client.simplytestable.com | a4c97a94051cba6f4bda2efa96c866a4551d979b | [
"MIT"
] | 1 | 2017-12-20T20:04:49.000Z | 2017-12-20T20:04:49.000Z | tests/Functional/Controller/Action/User/Account/NewsSubscriptionsControllerTest.php | webignition/web.client.simplytestable.com | d5f31c9052205ca9f93f1a5bd36734edd8e8d58a | [
"MIT"
] | 352 | 2019-01-04T10:56:06.000Z | 2019-04-22T16:29:11.000Z | tests/Functional/Controller/Action/User/Account/NewsSubscriptionsControllerTest.php | majacQ/web.client.simplytestable.com | a4c97a94051cba6f4bda2efa96c866a4551d979b | [
"MIT"
] | 1 | 2021-05-31T01:02:57.000Z | 2021-05-31T01:02:57.000Z | <?php
/** @noinspection PhpDocSignatureInspection */
namespace App\Tests\Functional\Controller\Action\User\Account;
use Doctrine\ORM\EntityManagerInterface;
use App\Controller\Action\User\Account\NewsSubscriptionsController;
use App\Entity\MailChimp\ListRecipients;
use App\Model\MailChimp\ApiError;
use App\Services\MailChimp\ListRecipientsService;
use App\Services\UserManager;
use App\Tests\Factory\HttpResponseFactory;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
use webignition\SimplyTestableUserModel\User;
class NewsSubscriptionsControllerTest extends AbstractUserAccountControllerTest
{
const ROUTE_NAME = 'action_user_account_news_subscriptions_update';
/**
* @var NewsSubscriptionsController
*/
private $newsSubscriptionsController;
/**
* {@inheritdoc}
*/
protected function setUp()
{
parent::setUp();
$this->newsSubscriptionsController = self::$container->get(NewsSubscriptionsController::class);
}
/**
* {@inheritdoc}
*/
public function postRequestPublicUserDataProvider()
{
return [
'default' => [
'routeName' => self::ROUTE_NAME,
],
];
}
public function testUpdateActionInvalidUserPostRequest()
{
$this->httpMockHandler->appendFixtures([
HttpResponseFactory::createNotFoundResponse(),
]);
$this->client->request(
'POST',
$this->router->generate(self::ROUTE_NAME)
);
/* @var RedirectResponse $response */
$response = $this->client->getResponse();
$this->assertTrue($response->isRedirect('/signout/'));
}
/**
* @dataProvider updateActionDataProvider
*/
public function testUpdateAction(
array $httpFixtures,
User $user,
array $existingListRecipients,
Request $request,
array $expectedFlashBagValues,
bool $expectedAnnouncementsListRecipientsContains,
bool $expectedUpdatesListRecipientsContains
) {
$mailChimpListRecipientsService = self::$container->get(ListRecipientsService::class);
$flashBag = self::$container->get(FlashBagInterface::class);
$userManager = self::$container->get(UserManager::class);
$this->httpMockHandler->appendFixtures($httpFixtures);
/* @var EntityManagerInterface $entityManager */
$entityManager = self::$container->get(EntityManagerInterface::class);
$userManager->setUser($user);
/* @var ListRecipients[] $listRecipientsCollection */
$listRecipientsCollection = [];
foreach ($existingListRecipients as $listName => $recipients) {
$listRecipients = ListRecipients::create(
$mailChimpListRecipientsService->getListId($listName),
$recipients
);
$entityManager->persist($listRecipients);
$entityManager->flush();
$listRecipientsCollection[$listName] = $listRecipients;
}
/* @var RedirectResponse $response */
$response = $this->newsSubscriptionsController->updateAction($request);
$this->assertInstanceOf(RedirectResponse::class, $response);
$this->assertEquals('/account/#news-subscriptions', $response->getTargetUrl());
$this->assertEquals(
$expectedFlashBagValues,
$flashBag->get('user_account_newssubscriptions_update')
);
$this->assertEquals(
$expectedAnnouncementsListRecipientsContains,
$listRecipientsCollection['announcements']->contains($user->getUsername())
);
$this->assertEquals(
$expectedUpdatesListRecipientsContains,
$listRecipientsCollection['updates']->contains($user->getUsername())
);
}
public function updateActionDataProvider(): array
{
return [
'no request data, no existing recipients' => [
'httpFixtures' => [],
'user' => new User('[email protected]', 'password'),
'existingListRecipients' => [
'announcements' => [],
'updates' => [],
],
'request' => new Request([], []),
'expectedFlashBagValues' => [
'announcements' => 'already-unsubscribed',
'updates' => 'already-unsubscribed',
],
'expectedAnnouncementsListRecipientsContains' => false,
'expectedUpdatesListRecipientsContains' => false,
],
'no request data, not existing recipient' => [
'httpFixtures' => [],
'user' => new User('[email protected]', 'password'),
'existingListRecipients' => [
'announcements' => [
'[email protected]',
],
'updates' => [
'[email protected]',
],
],
'request' => new Request([], []),
'expectedFlashBagValues' => [
'announcements' => 'already-unsubscribed',
'updates' => 'already-unsubscribed',
],
'expectedAnnouncementsListRecipientsContains' => false,
'expectedUpdatesListRecipientsContains' => false,
],
'no request data, is existing announcements recipient' => [
'httpFixtures' => [
HttpResponseFactory::createSuccessResponse(),
],
'user' => new User('[email protected]', 'password'),
'existingListRecipients' => [
'announcements' => [
'[email protected]',
],
'updates' => [],
],
'request' => new Request([], []),
'expectedFlashBagValues' => [
'announcements' => 'unsubscribed',
'updates' => 'already-unsubscribed',
],
'expectedAnnouncementsListRecipientsContains' => false,
'expectedUpdatesListRecipientsContains' => false,
],
'no request data, is existing updates recipient' => [
'httpFixtures' => [
HttpResponseFactory::createSuccessResponse(),
],
'user' => new User('[email protected]', 'password'),
'existingListRecipients' => [
'announcements' => [],
'updates' => [
'[email protected]',
],
],
'request' => new Request([], []),
'expectedFlashBagValues' => [
'announcements' => 'already-unsubscribed',
'updates' => 'unsubscribed',
],
'expectedAnnouncementsListRecipientsContains' => false,
'expectedUpdatesListRecipientsContains' => false,
],
'request to subscribe to both, no existing recipients' => [
'httpFixtures' => [
HttpResponseFactory::createSuccessResponse(),
HttpResponseFactory::createSuccessResponse(),
],
'user' => new User('[email protected]', 'password'),
'existingListRecipients' => [
'announcements' => [],
'updates' => [],
],
'request' => new Request([], [
'announcements' => true,
'updates' => true,
]),
'expectedFlashBagValues' => [
'announcements' => 'subscribed',
'updates' => 'subscribed',
],
'expectedAnnouncementsListRecipientsContains' => true,
'expectedUpdatesListRecipientsContains' => true,
],
'request to unsubscribe from both, is existing recipient of both' => [
'httpFixtures' => [
HttpResponseFactory::createSuccessResponse(),
HttpResponseFactory::createSuccessResponse(),
],
'user' => new User('[email protected]', 'password'),
'existingListRecipients' => [
'announcements' => [
'[email protected]'
],
'updates' => [
'[email protected]'
],
],
'request' => new Request([], [
'announcements' => false,
'updates' => false,
]),
'expectedFlashBagValues' => [
'announcements' => 'unsubscribed',
'updates' => 'unsubscribed',
],
'expectedAnnouncementsListRecipientsContains' => false,
'expectedUpdatesListRecipientsContains' => false,
],
'request to subscribe to both, member exists and unknown exceptions, no existing recipients' => [
'httpFixtures' => [
HttpResponseFactory::createBadRequestResponse([], json_encode([
'title' => ApiError::TITLE_MEMBER_EXISTS,
'detail' => 'foo'
])),
HttpResponseFactory::createNotFoundResponse([], json_encode([
'title' => ApiError::TITLE_RESOURCE_NOT_FOUND,
'detail' => 'The requested resource could not be found.'
])),
],
'user' => new User('[email protected]', 'password'),
'existingListRecipients' => [
'announcements' => [],
'updates' => [],
],
'request' => new Request([], [
'announcements' => true,
'updates' => true,
]),
'expectedFlashBagValues' => [
'announcements' => 'subscribe-failed-unknown',
'updates' => 'subscribe-failed-unknown',
],
'expectedAnnouncementsListRecipientsContains' => false,
'expectedUpdatesListRecipientsContains' => false,
],
'request to unsubscribe from both, not found and unknown exception' => [
'httpFixtures' => [
HttpResponseFactory::createNotFoundResponse([], json_encode([
'title' => 'foo',
'detail' => 'foo'
])),
HttpResponseFactory::createNotFoundResponse([], json_encode([
'title' => ApiError::TITLE_RESOURCE_NOT_FOUND,
'detail' => 'The requested resource could not be found.'
])),
],
'user' => new User('[email protected]', 'password'),
'existingListRecipients' => [
'announcements' => [
'[email protected]'
],
'updates' => [
'[email protected]'
],
],
'request' => new Request([], [
'announcements' => false,
'updates' => false,
]),
'expectedFlashBagValues' => [
'announcements' => 'unsubscribed',
'updates' => 'unsubscribed',
],
'expectedAnnouncementsListRecipientsContains' => false,
'expectedUpdatesListRecipientsContains' => false,
],
];
}
}
| 39.276873 | 109 | 0.503483 |
2867fd5310ab9b6d2d2980404e2b505963bcc694 | 1,105 | swift | Swift | RickAndMortyApp/NetworkService/RMProvider.swift | zontag/RickAndMortyApp | 67bc4aea449264ebb260324f869a6827378eabb9 | [
"MIT"
] | null | null | null | RickAndMortyApp/NetworkService/RMProvider.swift | zontag/RickAndMortyApp | 67bc4aea449264ebb260324f869a6827378eabb9 | [
"MIT"
] | null | null | null | RickAndMortyApp/NetworkService/RMProvider.swift | zontag/RickAndMortyApp | 67bc4aea449264ebb260324f869a6827378eabb9 | [
"MIT"
] | null | null | null | import Foundation
import Moya
import ReactiveSwift
import ReactiveMoya
class RMProvider {
enum Failure: LocalizedError {
case fetchFailure
var localizedDescription: String {
switch self {
case .fetchFailure:
return "Sorry, something really strange happened. 🤯"
}
}
}
static let shared = RMProvider()
private lazy var rmService: MoyaProvider<RMService> = appEnvironment.resolve()
private init () { }
func fetchCharacters(
page: Int,
name: String,
status: String,
gender: String,
species: String)
-> SignalProducer<([Character], Int), Failure> {
rmService.reactive.request(.characters(
page: page,
name: name,
status: status,
gender: gender,
species: species))
.map(Response<Character>.self)
.map { ($0.results, $0.info.pages) }
.mapError { _ in return Failure.fetchFailure }
}
}
| 25.697674 | 82 | 0.534842 |
9f2f94d30c0fcdf1082e15f6dd0559a700944f48 | 637 | sql | SQL | scripts/dm/mv_dm_metadata_site.sql | lindsay-stevens/openclinica_sqldatamart | ecdda4208021ff5a1cb7a20036eed23bd4196af0 | [
"MIT"
] | 8 | 2016-03-31T08:49:35.000Z | 2021-03-11T06:31:43.000Z | scripts/dm/mv_dm_metadata_site.sql | lindsay-stevens-kirby/openclinica_sqldatamart | ecdda4208021ff5a1cb7a20036eed23bd4196af0 | [
"MIT"
] | 4 | 2015-04-20T05:57:58.000Z | 2016-01-20T04:35:59.000Z | scripts/dm/mv_dm_metadata_site.sql | lindsay-stevens/openclinica_sqldatamart | ecdda4208021ff5a1cb7a20036eed23bd4196af0 | [
"MIT"
] | 5 | 2016-05-18T06:56:04.000Z | 2019-01-24T16:12:53.000Z | CREATE MATERIALIZED VIEW dm.metadata_site AS
SELECT
study.study_id AS site_id,
study.name AS site_name,
openclinica_fdw.dm_clean_name_string(study.oc_oid) AS site_name_clean,
study.oc_oid AS site_oid,
study.unique_identifier AS site_unique_identifier,
status.name AS site_status,
study.date_created AS site_date_created,
study.date_updated AS site_date_updated,
study.parent_study_id AS site_parent_study_id
FROM openclinica_fdw.study
LEFT JOIN openclinica_fdw.status
ON status.status_id = study.status_id
WHERE
study.status_id NOT IN (5, 7)
AND study.parent_study_id IS NOT NULL;; | 37.470588 | 74 | 0.77865 |
4619b41940eea62c6437938320928c539749dfa6 | 139 | ts | TypeScript | trms-front-end/src/models/utils/clone.ts | 210524training/ddl-trms | da0a6138301e216caa7c6134153db53a5967e109 | [
"MIT"
] | null | null | null | trms-front-end/src/models/utils/clone.ts | 210524training/ddl-trms | da0a6138301e216caa7c6134153db53a5967e109 | [
"MIT"
] | null | null | null | trms-front-end/src/models/utils/clone.ts | 210524training/ddl-trms | da0a6138301e216caa7c6134153db53a5967e109 | [
"MIT"
] | null | null | null | export default function clone<T>(obj: T): T {
const str = JSON.stringify(obj);
const cloned = JSON.parse(str) as T;
return cloned;
}
| 23.166667 | 45 | 0.676259 |
54f55c2ef077f629d71cd6162e8136a59aef4970 | 4,240 | css | CSS | src/css/gallery.css | capricci-parrucchieri/website | 2916c12c0be21215216a6ac5b053cc1600b7cf56 | [
"MIT"
] | null | null | null | src/css/gallery.css | capricci-parrucchieri/website | 2916c12c0be21215216a6ac5b053cc1600b7cf56 | [
"MIT"
] | null | null | null | src/css/gallery.css | capricci-parrucchieri/website | 2916c12c0be21215216a6ac5b053cc1600b7cf56 | [
"MIT"
] | null | null | null | a{
color: black;
text-decoration: underline;
}
.navbar a{ /* restore navbar default */
text-decoration: none;
}
.navbar-brand img {
max-width: 100%;
max-height: 100%;
}
header h1{
font-family: 'Mouse Memoirs', sans-serif;
font-size: 5em;
font-weight: lighter;
}
header h2{
font-family: 'BenchNine', sans-serif;
font-size: 1.8em;
letter-spacing: 1px;
font-weight: lighter;
}
@media (max-width: 377px){
header h1{
font-size: 4em;
}
}
@media (max-width: 377px){
header h2{
font-size: 1.4em;
}
}
body {
padding: 0;
margin: 0
}
nav.nav {
height: 50px;
background-color: #333;
color: #ccc
}
footer.footer {
display: block;
height: 50px;
background-color: black;
color: white;
text-align: right
}
body {
background-color: #00143A;
color: white
}
header {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
-webkit-box-align: center;
-webkit-align-items: center;
-ms-flex-align: center;
align-items: center;
height: 250px;
margin-top: 50px;
}
article.ga-ThumbsWrapper {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column
}
article.ga-ThumbsWrapper .ga-Thumb {
position: relative;
padding: 0 15px 15px 15px
}
article.ga-ThumbsWrapper .ga-Thumb figure {
overflow: hidden;
margin: 0
}
article.ga-ThumbsWrapper .ga-Thumb img {
display: block;
width: 100%;
height: auto;
-webkit-transition: -webkit-transform 0.3s ease-in-out;
transition: -webkit-transform 0.3s ease-in-out;
transition: transform 0.3s ease-in-out;
transition: transform 0.3s ease-in-out, -webkit-transform 0.3s ease-in-out
}
article.ga-ThumbsWrapper .ga-Thumb:hover img {
-webkit-transform: scale(1.5);
transform: scale(1.5)
}
article.ga-ThumbsWrapper .ga-Thumb:hover figure:before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: #00143A;
opacity: 0.85;
z-index: 2;
}
@media (min-width:600px) {
article.ga-ThumbsWrapper {
-webkit-box-orient: horizontal;
-webkit-box-direction: normal;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-flex-wrap: wrap;
-ms-flex-wrap: wrap;
flex-wrap: wrap
}
article.ga-ThumbsWrapper .ga-Thumb {
padding: 0 15px 15px 0;
box-sizing: content-box;
width: calc( ( 100% - 5*15px) / 4)
}
article.ga-ThumbsWrapper .ga-Thumb:nth-child(4n+1) {
padding-left: 15px
}
article.ga-ThumbsWrapper .ga-Thumb:nth-child(4n) {
padding-right: 15px
}
}
.thumbnail {
position: relative;
width: 200px;
height: 200px;
overflow: hidden
}
.thumbnail img {
position: absolute;
left: 50%;
top: 50%;
height: 100%;
width: auto;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%)
}
.thumbnail img.portrait {
width: 100%;
height: auto
}
.u-Modal {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
-webkit-box-align: center;
-webkit-align-items: center;
-ms-flex-align: center;
align-items: center;
display: none
}
.u-Modal:before {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.85)
}
.u-Modal figure {
z-index: 99;
width: 80vmin
}
.u-Modal figure img{
max-width: 100%
}
| 19.272727 | 78 | 0.618396 |
dc1b2cacc1493c37127cb8f1f5f1e5c5e592ad3c | 463 | ts | TypeScript | ddd-library/typescript-ddd/src/Contexts/Mooc/Shared/infrastructure/EventBus/RabbitMq/RabbitMqConfigFactory.ts | beyondnetPeru/BeyondNet.Sample.Typescript | 0cce64b1f3d504fa2f1a5ced8b0dcd48b4ec8d5a | [
"MIT"
] | null | null | null | ddd-library/typescript-ddd/src/Contexts/Mooc/Shared/infrastructure/EventBus/RabbitMq/RabbitMqConfigFactory.ts | beyondnetPeru/BeyondNet.Sample.Typescript | 0cce64b1f3d504fa2f1a5ced8b0dcd48b4ec8d5a | [
"MIT"
] | null | null | null | ddd-library/typescript-ddd/src/Contexts/Mooc/Shared/infrastructure/EventBus/RabbitMq/RabbitMqConfigFactory.ts | beyondnetPeru/BeyondNet.Sample.Typescript | 0cce64b1f3d504fa2f1a5ced8b0dcd48b4ec8d5a | [
"MIT"
] | null | null | null | import config from '../../config';
import RabbitMqConfig from '../../../../../Shared/infrastructure/EventBus/RabbitMq/RabbitMqConfig';
export class RabbitMqConfigFactory {
static createConfig(): RabbitMqConfig {
return {
host: config.get('rabbitMQ.host'),
user: config.get('rabbitMQ.user'),
password: config.get('rabbitMQ.password'),
queue: config.get('rabbitMQ.queue'),
exchange: config.get('rabbitMQ.exchange')
};
}
}
| 30.866667 | 99 | 0.667387 |
0acda47f5a51c6a78a0fe18f975fa89144b6a73c | 7,349 | cs | C# | sdk/resources/Azure.ResourceManager.Resources/src/Generated/Extensions/ArmClientExtensions.cs | mikeblakeuk/azure-sdk-for-net | 8ad38efecac8bd7ec33297f416cbc330f5a1d782 | [
"MIT"
] | 2 | 2021-08-05T13:32:05.000Z | 2021-12-01T15:56:12.000Z | sdk/resources/Azure.ResourceManager.Resources/src/Generated/Extensions/ArmClientExtensions.cs | mikeblakeuk/azure-sdk-for-net | 8ad38efecac8bd7ec33297f416cbc330f5a1d782 | [
"MIT"
] | 7 | 2021-08-25T09:09:53.000Z | 2022-03-17T01:01:13.000Z | sdk/resources/Azure.ResourceManager.Resources/src/Generated/Extensions/ArmClientExtensions.cs | mikeblakeuk/azure-sdk-for-net | 8ad38efecac8bd7ec33297f416cbc330f5a1d782 | [
"MIT"
] | 1 | 2022-01-14T19:07:05.000Z | 2022-01-14T19:07:05.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using Azure.ResourceManager;
namespace Azure.ResourceManager.Resources
{
/// <summary> A class to add extension methods to ArmClient. </summary>
public static partial class ArmClientExtensions
{
#region Deployment
/// <summary> Gets an object representing a Deployment along with the instance operations that can be performed on it but with no data. </summary>
/// <param name="armClient"> The <see cref="ArmClient" /> instance the method will execute against. </param>
/// <param name="id"> The resource ID of the resource to get. </param>
/// <returns> Returns a <see cref="Deployment" /> object. </returns>
public static Deployment GetDeployment(this ArmClient armClient, ResourceIdentifier id)
{
return armClient.UseClientContext((uri, credential, clientOptions, pipeline) => new Deployment(clientOptions, credential, uri, pipeline, id));
}
#endregion
#region DeploymentOperation
/// <summary> Gets an object representing a DeploymentOperation along with the instance operations that can be performed on it but with no data. </summary>
/// <param name="armClient"> The <see cref="ArmClient" /> instance the method will execute against. </param>
/// <param name="id"> The resource ID of the resource to get. </param>
/// <returns> Returns a <see cref="DeploymentOperation" /> object. </returns>
public static DeploymentOperation GetDeploymentOperation(this ArmClient armClient, ResourceIdentifier id)
{
return armClient.UseClientContext((uri, credential, clientOptions, pipeline) => new DeploymentOperation(clientOptions, credential, uri, pipeline, id));
}
#endregion
#region Application
/// <summary> Gets an object representing a Application along with the instance operations that can be performed on it but with no data. </summary>
/// <param name="armClient"> The <see cref="ArmClient" /> instance the method will execute against. </param>
/// <param name="id"> The resource ID of the resource to get. </param>
/// <returns> Returns a <see cref="Application" /> object. </returns>
public static Application GetApplication(this ArmClient armClient, ResourceIdentifier id)
{
return armClient.UseClientContext((uri, credential, clientOptions, pipeline) => new Application(clientOptions, credential, uri, pipeline, id));
}
#endregion
#region ApplicationDefinition
/// <summary> Gets an object representing a ApplicationDefinition along with the instance operations that can be performed on it but with no data. </summary>
/// <param name="armClient"> The <see cref="ArmClient" /> instance the method will execute against. </param>
/// <param name="id"> The resource ID of the resource to get. </param>
/// <returns> Returns a <see cref="ApplicationDefinition" /> object. </returns>
public static ApplicationDefinition GetApplicationDefinition(this ArmClient armClient, ResourceIdentifier id)
{
return armClient.UseClientContext((uri, credential, clientOptions, pipeline) => new ApplicationDefinition(clientOptions, credential, uri, pipeline, id));
}
#endregion
#region JitRequestDefinition
/// <summary> Gets an object representing a JitRequestDefinition along with the instance operations that can be performed on it but with no data. </summary>
/// <param name="armClient"> The <see cref="ArmClient" /> instance the method will execute against. </param>
/// <param name="id"> The resource ID of the resource to get. </param>
/// <returns> Returns a <see cref="JitRequestDefinition" /> object. </returns>
public static JitRequestDefinition GetJitRequestDefinition(this ArmClient armClient, ResourceIdentifier id)
{
return armClient.UseClientContext((uri, credential, clientOptions, pipeline) => new JitRequestDefinition(clientOptions, credential, uri, pipeline, id));
}
#endregion
#region DeploymentScript
/// <summary> Gets an object representing a DeploymentScript along with the instance operations that can be performed on it but with no data. </summary>
/// <param name="armClient"> The <see cref="ArmClient" /> instance the method will execute against. </param>
/// <param name="id"> The resource ID of the resource to get. </param>
/// <returns> Returns a <see cref="DeploymentScript" /> object. </returns>
public static DeploymentScript GetDeploymentScript(this ArmClient armClient, ResourceIdentifier id)
{
return armClient.UseClientContext((uri, credential, clientOptions, pipeline) => new DeploymentScript(clientOptions, credential, uri, pipeline, id));
}
#endregion
#region ScriptLog
/// <summary> Gets an object representing a ScriptLog along with the instance operations that can be performed on it but with no data. </summary>
/// <param name="armClient"> The <see cref="ArmClient" /> instance the method will execute against. </param>
/// <param name="id"> The resource ID of the resource to get. </param>
/// <returns> Returns a <see cref="ScriptLog" /> object. </returns>
public static ScriptLog GetScriptLog(this ArmClient armClient, ResourceIdentifier id)
{
return armClient.UseClientContext((uri, credential, clientOptions, pipeline) => new ScriptLog(clientOptions, credential, uri, pipeline, id));
}
#endregion
#region TemplateSpec
/// <summary> Gets an object representing a TemplateSpec along with the instance operations that can be performed on it but with no data. </summary>
/// <param name="armClient"> The <see cref="ArmClient" /> instance the method will execute against. </param>
/// <param name="id"> The resource ID of the resource to get. </param>
/// <returns> Returns a <see cref="TemplateSpec" /> object. </returns>
public static TemplateSpec GetTemplateSpec(this ArmClient armClient, ResourceIdentifier id)
{
return armClient.UseClientContext((uri, credential, clientOptions, pipeline) => new TemplateSpec(clientOptions, credential, uri, pipeline, id));
}
#endregion
#region TemplateSpecVersion
/// <summary> Gets an object representing a TemplateSpecVersion along with the instance operations that can be performed on it but with no data. </summary>
/// <param name="armClient"> The <see cref="ArmClient" /> instance the method will execute against. </param>
/// <param name="id"> The resource ID of the resource to get. </param>
/// <returns> Returns a <see cref="TemplateSpecVersion" /> object. </returns>
public static TemplateSpecVersion GetTemplateSpecVersion(this ArmClient armClient, ResourceIdentifier id)
{
return armClient.UseClientContext((uri, credential, clientOptions, pipeline) => new TemplateSpecVersion(clientOptions, credential, uri, pipeline, id));
}
#endregion
}
}
| 63.904348 | 165 | 0.684719 |
05046c763af45a0005db03cacb8a137cd5f7d504 | 474 | css | CSS | src/components/Label/Label.css | chohanjoo/aladdin-ui | 88360268cd162adce58aaa205fa73a8be4a8767a | [
"Apache-2.0"
] | null | null | null | src/components/Label/Label.css | chohanjoo/aladdin-ui | 88360268cd162adce58aaa205fa73a8be4a8767a | [
"Apache-2.0"
] | 8 | 2021-03-01T22:47:07.000Z | 2022-03-08T22:47:16.000Z | src/components/Label/Label.css | chohanjoo/aladdin-ui | 88360268cd162adce58aaa205fa73a8be4a8767a | [
"Apache-2.0"
] | 4 | 2019-07-14T02:13:58.000Z | 2019-09-17T06:45:13.000Z | .label-collection{overflow:hidden}.label-pair{margin:3px 2px 2px;max-width:100%;float:left;display:block}.label-pair .label{min-width:50px}.label-pair .label:first-child{border-radius:2px 0 0 2px}.label-pair .label:last-child{border-radius:0 2px 2px 0}.label-pair .label-key{background-color:#bee1f4;color:#00659c;padding-top:4px;padding-bottom:4px;margin-left:0}.label-pair .label-value{background-color:#7dc3e8;color:#fff;padding-top:4px;padding-bottom:4px;margin-left:0}
| 237 | 473 | 0.791139 |
f45aee4d8f3d899759565bb63ed9eb4ac1743252 | 2,984 | cs | C# | disfr-core/Doc/StringPool.cs | AlissaSabre/disfr | 7f47558659e07308c300342af68caac8f87f1db6 | [
"BSD-1-Clause"
] | 7 | 2019-01-10T08:06:47.000Z | 2022-01-14T07:50:49.000Z | disfr-core/Doc/StringPool.cs | AlissaSabre/disfr | 7f47558659e07308c300342af68caac8f87f1db6 | [
"BSD-1-Clause"
] | 25 | 2016-07-01T02:37:15.000Z | 2021-05-30T10:44:07.000Z | disfr-core/Doc/StringPool.cs | AlissaSabre/disfr | 7f47558659e07308c300342af68caac8f87f1db6 | [
"BSD-1-Clause"
] | 4 | 2016-12-06T13:38:24.000Z | 2022-01-18T11:02:38.000Z | using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace disfr.Doc
{
/// <summary>
/// Provides a local/private equivalent of the CLR's intern pool.
/// </summary>
public interface IStringPool
{
/// <summary>
/// Returns a locally pooled version of a string.
/// </summary>
/// <param name="s">A string to look in the pool.</param>
/// <returns>A pooled string that is equal to <paramref name="s"/>.</returns>
/// <remarks>
/// This method may or may not be thread safe, depending on the implementation.
/// </remarks>
string Intern(string s);
}
/// <summary>
/// Provides a local/private equivalent of the CLR's intern pool.
/// </summary>
/// <remarks>
/// This class is not thread safe.
/// Use <see cref="ConcurrentStringPool"/> for concurrent access.
/// </remarks>
public class StringPool : IStringPool
{
private readonly Dictionary<string, string> Pool = new Dictionary<string, string>();
/// <summary>
/// Returns a locally pooled version of a string.
/// </summary>
/// <param name="s">A string to look in the pool.</param>
/// <returns>A pooled string that is equal to <paramref name="s"/>.</returns>
/// <remarks>
/// This method is not thread safe.
/// Use <see cref="ConcurrentStringPool"/> for concurrent access.
/// </remarks>
public string Intern(string s)
{
if (s == null) return null;
string t;
if (Pool.TryGetValue(s, out t)) return t;
#if false
if ((t = string.IsInterned(s)) != null) s = t;
#endif
Pool.Add(s, s);
return s;
}
}
/// <summary>
/// Provides a local/private equivalent of the CLR's intern pool.
/// </summary>
/// <remarks>
/// This class is thread safe.
/// It has a slight overhead over <see cref="StringPool"/> if used singlethreadedly.
/// </remarks>
public class ConcurrentStringPool : IStringPool
{
private readonly ConcurrentDictionary<string, string> Pool = new ConcurrentDictionary<string, string>();
/// <summary>
/// Returns a locally pooled version of a string.
/// </summary>
/// <param name="s">A string to look in the pool.</param>
/// <returns>A pooled string that is equal to <paramref name="s"/>.</returns>
/// <remarks>
/// This method is thread safe.
/// </remarks>
public string Intern(string s)
{
if (s == null) return null;
string t;
if (Pool.TryGetValue(s, out t)) return t;
#if false
if ((t = string.IsInterned(s)) != null) s = t;
#endif
if (Pool.TryAdd(s, s)) return s;
return Pool[s];
}
}
}
| 32.791209 | 112 | 0.567694 |
5d9c7d7a913afeb9727e54b28667784ea8069fbf | 576 | hpp | C++ | Code/Asset/IAsset.hpp | Mu-L/Luna-Engine-0.6 | 05ae1037f0d173589a535eb6ec2964f20d80e5c1 | [
"MIT"
] | 167 | 2020-06-17T06:09:41.000Z | 2022-03-13T20:31:26.000Z | Code/Asset/IAsset.hpp | Mu-L/Luna-Engine-0.6 | 05ae1037f0d173589a535eb6ec2964f20d80e5c1 | [
"MIT"
] | 2 | 2020-07-11T15:12:50.000Z | 2021-06-01T01:45:49.000Z | Code/Asset/IAsset.hpp | Mu-L/Luna-Engine-0.6 | 05ae1037f0d173589a535eb6ec2964f20d80e5c1 | [
"MIT"
] | 22 | 2020-06-12T02:26:10.000Z | 2022-01-02T14:04:32.000Z | // Copyright 2018-2020 JXMaster. All rights reserved.
/*
* @file IAsset.cpp
* @author JXMaster
* @date 2020/4/15
*/
#pragma once
#include <Core/Core.hpp>
namespace Luna
{
namespace Asset
{
struct IAssetMeta;
//! @interface IAsset
//! @threadsafe
//! Implement this interface to define your own asset object type.
struct IAsset : public IObject
{
luiid("{f99ee83a-8c39-4355-96af-3c6fe5c454f9}");
//! Gets the asset meta object of this asset. The asset object always keep a strong reference to the meta object.
virtual IAssetMeta* meta() = 0;
};
}
} | 21.333333 | 116 | 0.694444 |
0a99bffc5e3971d5540cecfd1c20900ab5aba8e8 | 4,355 | cs | C# | src/AupDotNet/ExEdit/Effects/NoiseEffect.cs | karoterra/AupDotNet | f4dd088d04f34e2aa761f295bad3c71fe1ac71ff | [
"MIT"
] | 10 | 2021-06-03T17:14:21.000Z | 2022-02-12T09:13:56.000Z | src/AupDotNet/ExEdit/Effects/NoiseEffect.cs | karoterra/AupDotNet | f4dd088d04f34e2aa761f295bad3c71fe1ac71ff | [
"MIT"
] | null | null | null | src/AupDotNet/ExEdit/Effects/NoiseEffect.cs | karoterra/AupDotNet | f4dd088d04f34e2aa761f295bad3c71fe1ac71ff | [
"MIT"
] | null | null | null | using System;
using System.IO;
using Karoterra.AupDotNet.Extensions;
namespace Karoterra.AupDotNet.ExEdit.Effects
{
/// <summary>
/// ノイズ
/// </summary>
public class NoiseEffect : Effect
{
/// <summary>
/// ノイズのフィルタ効果定義。
/// </summary>
public static EffectType EffectType { get; }
/// <summary>強さ</summary>
public Trackbar Intensity => Trackbars[0];
/// <summary>速度X</summary>
public Trackbar SpeedX => Trackbars[1];
/// <summary>速度Y</summary>
public Trackbar SpeedY => Trackbars[2];
/// <summary>変化速度</summary>
public Trackbar NoiseSpeed => Trackbars[3];
/// <summary>周期X</summary>
public Trackbar PeriodX => Trackbars[4];
/// <summary>周期Y</summary>
public Trackbar PeriodY => Trackbars[5];
/// <summary>しきい値</summary>
public Trackbar Threshold => Trackbars[6];
/// <summary>ノイズの種類</summary>
public int NoiseType { get; set; }
/// <summary>
/// 合成モード
/// 0: アルファ値と乗算
/// 1: 輝度と乗算
/// </summary>
public int Mode { get; set; }
/// <summary>シード</summary>
public int Seed { get; set; }
/// <summary>
/// 拡張データのオフセットアドレス 0xC。
/// </summary>
public int Field0xC { get; set; }
/// <summary>
/// <see cref="NoiseEffect"/> のインスタンスを初期化します。
/// </summary>
public NoiseEffect()
: base(EffectType)
{
}
/// <summary>
/// トラックバーとチェックボックスの値を指定して <see cref="NoiseEffect"/> のインスタンスを初期化します。
/// </summary>
/// <param name="trackbars">トラックバー</param>
/// <param name="checkboxes">チェックボックス</param>
public NoiseEffect(Trackbar[] trackbars, int[] checkboxes)
: base(EffectType, trackbars, checkboxes)
{
}
/// <summary>
/// トラックバーとチェックボックス、拡張データを指定して <see cref="NoiseEffect"/> のインスタンスを初期化します。
/// </summary>
/// <param name="trackbars">トラックバー</param>
/// <param name="checkboxes">チェックボックス</param>
/// <param name="data">拡張データ</param>
public NoiseEffect(Trackbar[] trackbars, int[] checkboxes, ReadOnlySpan<byte> data)
: base(EffectType, trackbars, checkboxes, data)
{
}
/// <inheritdoc/>
protected override void ParseExtDataInternal(ReadOnlySpan<byte> data)
{
NoiseType = data.Slice(0, 4).ToInt32();
Mode = data.Slice(4, 4).ToInt32();
Seed = data.Slice(8, 4).ToInt32();
Field0xC = data.Slice(0xC, 4).ToInt32();
}
/// <inheritdoc/>
public override byte[] DumpExtData()
{
var data = new byte[Type.ExtSize];
NoiseType.ToBytes().CopyTo(data, 0);
Mode.ToBytes().CopyTo(data, 4);
Seed.ToBytes().CopyTo(data, 8);
Field0xC.ToBytes().CopyTo(data, 0xC);
return data;
}
/// <inheritdoc/>
public override void ExportExtData(TextWriter writer)
{
writer.Write("type=");
writer.WriteLine(NoiseType);
writer.Write("mode=");
writer.WriteLine(Mode);
writer.Write("seed=");
writer.WriteLine(Seed);
}
static NoiseEffect()
{
EffectType = new EffectType(
70, 0x04000420, 7, 3, 16, "ノイズ",
new TrackbarDefinition[]
{
new TrackbarDefinition("強さ", 10, 0, 2000, 1000),
new TrackbarDefinition("速度X", 10, -4000, 8000, 0),
new TrackbarDefinition("速度Y", 10, -4000, 8000, 0),
new TrackbarDefinition("変化速度", 10, 0, 8000, 0),
new TrackbarDefinition("周期X", 100, 0, 10000, 100),
new TrackbarDefinition("周期Y", 100, 0, 10000, 100),
new TrackbarDefinition("しきい値", 10, 0, 1000, 0),
},
new CheckboxDefinition[]
{
new CheckboxDefinition("アルファ値と乗算", false, 0),
new CheckboxDefinition("Type1", false, 0),
new CheckboxDefinition("設定", false, 0),
}
);
}
}
}
| 31.107143 | 91 | 0.510677 |
7970d45707128036c16f6262232e10b248b738c3 | 2,825 | php | PHP | app/Repositories/rolFerro/ruta/RutaRepositories.php | mtiendar/arconesycanastas.pe | dc9450a8767fe4556d1ad66ae55b424ab185e9b8 | [
"MIT"
] | null | null | null | app/Repositories/rolFerro/ruta/RutaRepositories.php | mtiendar/arconesycanastas.pe | dc9450a8767fe4556d1ad66ae55b424ab185e9b8 | [
"MIT"
] | 1 | 2021-06-30T18:19:30.000Z | 2021-06-30T18:19:30.000Z | app/Repositories/rolFerro/ruta/RutaRepositories.php | mtiendar/arconesycanastas.pe | dc9450a8767fe4556d1ad66ae55b424ab185e9b8 | [
"MIT"
] | 2 | 2021-04-24T17:58:52.000Z | 2021-06-09T17:26:30.000Z | <?php
namespace App\Repositories\rolFerro\ruta;
// Models
use App\Models\Ruta;
// Events
use App\Events\layouts\ActividadRegistrada;
// Servicios
use App\Repositories\servicio\crypt\ServiceCrypt;
// Repositories
use App\Repositories\papeleraDeReciclaje\PapeleraDeReciclajeRepositories;
// Otros
use Illuminate\Support\Facades\Auth;
use DB;
class RutaRepositories implements RutaInterface {
protected $serviceCrypt;
protected $papeleraDeReciclajeRepo;
public function __construct(ServiceCrypt $serviceCrypt, PapeleraDeReciclajeRepositories $papeleraDeReciclajeRepositories) {
$this->serviceCrypt = $serviceCrypt;
$this->papeleraDeReciclajeRepo = $papeleraDeReciclajeRepositories;
}
public function rutaFindOrFailById($id_ruta, $relaciones) {
$id_ruta = $this->serviceCrypt->decrypt($id_ruta);
return Ruta::with($relaciones)->findOrFail($id_ruta);
}
public function getPagination($request) {
return Ruta::buscar($request->opcion_buscador, $request->buscador)->orderBy('id', 'DESC')->paginate($request->paginador);
}
public function store($request) {
try { DB::beginTransaction();
$ruta = new Ruta();
$ruta->nom = $request->nombre_de_la_ruta;
$ruta->created_at_reg = Auth::user()->email_registro;
$ruta->save();
$ruta->rut = 'R'.$ruta->id;
$ruta->save();
DB::commit();
return $ruta;
} catch(\Exception $e) { DB::rollback(); throw $e; }
}
public function update($request, $id_ruta) {
try { DB::beginTransaction();
$ruta = $this->rutaFindOrFailById($id_ruta, []);
$ruta->nom = $request->nombre_de_la_ruta;
if($ruta->isDirty()) {
// Dispara el evento registrado en App\Providers\EventServiceProvider.php
ActividadRegistrada::dispatch(
'Rutas (Rol Ferro)', // Módulo
'rolFerro.ruta.show', // Nombre de la ruta
$id_ruta, // Id del registro debe ir encriptado
$this->serviceCrypt->decrypt($id_ruta), // Id del registro a mostrar, este valor no debe sobrepasar los 100 caracteres
array('Nombre de la ruta'), // Nombre de los inputs del formulario
$ruta, // Request
array('nom') // Nombre de los campos en la BD
);
$ruta->updated_at_reg = Auth::user()->email_registro;
}
$ruta->save();
DB::commit();
return $ruta;
} catch(\Exception $e) { DB::rollback(); throw $e; }
}
public function destroy($id_ruta) {
try { DB::beginTransaction();
$ruta = $this->rutaFindOrFailById($id_ruta, []);
$ruta->forceDelete();
DB::commit();
return $ruta;
} catch(\Exception $e) { DB::rollback(); throw $e; }
}
public function allRutasPlunk() {
return Ruta::orderBy('nom', 'ASC')->pluck('nom', 'rut');
}
} | 35.3125 | 128 | 0.645664 |
908029fac5ac503e188ecdb16e74a86772a74dcb | 3,498 | h | C | include/comm/binstream/netstream.h | Outerra/anteworld | 7c95cd0a4c53937c7572387333a00f8542ebf236 | [
"Unlicense"
] | 16 | 2017-02-28T20:03:06.000Z | 2021-01-25T05:27:05.000Z | include/comm/binstream/netstream.h | Outerra/anteworld | 7c95cd0a4c53937c7572387333a00f8542ebf236 | [
"Unlicense"
] | null | null | null | include/comm/binstream/netstream.h | Outerra/anteworld | 7c95cd0a4c53937c7572387333a00f8542ebf236 | [
"Unlicense"
] | 7 | 2019-09-25T17:48:51.000Z | 2021-10-05T08:43:37.000Z | /* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is COID/comm module.
*
* The Initial Developer of the Original Code is
* PosAm.
* Portions created by the Initial Developer are Copyright (C) 2003
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Brano Kemen
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef __COID_COMM_NETSTREAM__HEADER_FILE__
#define __COID_COMM_NETSTREAM__HEADER_FILE__
#include "../namespace.h"
#include "../retcodes.h"
#include "../str.h"
#include "../net.h"
#include "binstream.h"
COID_NAMESPACE_BEGIN
////////////////////////////////////////////////////////////////////////////////
///Base class for connectable streams
class netstream : public binstream
{
protected:
//netSocket _socket;
uint _timeout;
public:
netstream()
{
_timeout = UMAX32;
}
virtual opcd read_until( const substring& ss, binstream* bout, uints max_size=UMAXS )
{ return ersUNAVAILABLE; }
virtual opcd open( const zstring& arg, const zstring& attr = zstring() )
{
return connect(arg.get_token());
}
virtual opcd close( bool linger=false ) = 0;
virtual opcd connect( const token& addr, int port=0, bool portoverride=false )
{
netAddress naddr;
naddr.set( addr, port, portoverride );
return connect(naddr);
}
virtual opcd connect( const netAddress& addr ) = 0;
opcd get_error() { return read_error(); }
opcd set_timeout( uint ms )
{
_timeout = ms;
return 0;
}
static netAddress* get_local_address( netAddress* addr )
{
return netAddress::getLocalHost(addr);
}
virtual netAddress* get_remote_address( netAddress* addr ) const = 0;
virtual bool is_socket_connected() = 0;
static charstr& get_name_from_address( charstr& buf, const netAddress* addr )
{
addr->getHostName( buf, true );
return buf;
}
static void get_address_from_name( const char* name, netAddress* addr )
{
addr->set( name, 0, false );
}
};
COID_NAMESPACE_END
#endif //__COID_COMM_NETSTREAM__HEADER_FILE__
| 28.909091 | 89 | 0.670097 |
a420ec2baed244b660ce3d3be006a77495dccb35 | 663 | php | PHP | success.php | prashantevolvus/crux | f76dab56ff5187672c6ba9ea095d64bb44eb27b6 | [
"MIT"
] | null | null | null | success.php | prashantevolvus/crux | f76dab56ff5187672c6ba9ea095d64bb44eb27b6 | [
"MIT"
] | 2 | 2017-09-28T07:50:29.000Z | 2017-10-01T08:51:11.000Z | success.php | prashantevolvus/crux | f76dab56ff5187672c6ba9ea095d64bb44eb27b6 | [
"MIT"
] | null | null | null | <html>
<?php
session_name("Project");
session_start();
require_once('dbconn.php');
if(!checkUserSession($_SESSION["user"]))
{
header("Location:login.php");
}
?>
<body>
<?php
echo $q=$_GET["redirectproject"];
$riskid=$_GET["projectid"];
if($q != "")
{
header("Location:viewprojdetails.php?proj_id=".$q."&redirect=success");
}
include 'header.php'; ?>
<h2>Successfully updated the details....</h2>
<?php
if($riskid !='')
{
// echo "<form action='updateacceptcr.php' method='post' onsubmit="return formSubmit();" >";
echo "<a href='createrisk.php'><button>Continue</button></a>";
}
?>
</body>
</html>
| 17 | 96 | 0.597285 |
dd9368ebccf5d771b10b936861adab456f3a942f | 2,545 | java | Java | admin/src/main/java/com/wupaas/boot/admin/model/UserAuthModel.java | jueyue/windbell | 8af280adcac4da0d96801999a667935871b5bdd1 | [
"MulanPSL-1.0"
] | 4 | 2019-09-11T01:56:43.000Z | 2022-01-24T07:05:42.000Z | admin/src/main/java/com/wupaas/boot/admin/model/UserAuthModel.java | jueyue/windbell | 8af280adcac4da0d96801999a667935871b5bdd1 | [
"MulanPSL-1.0"
] | 14 | 2020-05-31T07:10:21.000Z | 2022-02-16T00:58:32.000Z | admin/src/main/java/com/wupaas/boot/admin/model/UserAuthModel.java | jueyue/windbell | 8af280adcac4da0d96801999a667935871b5bdd1 | [
"MulanPSL-1.0"
] | 2 | 2020-03-20T07:23:43.000Z | 2020-12-09T05:02:17.000Z | /**
* Copyright 2017-2019 JueYue ([email protected])
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.wupaas.boot.admin.model;
import com.wupaas.boot.core.business.model.IdTenantBaseModel;
import cn.afterturn.easypoi.excel.annotation.Excel;
import com.baomidou.mybatisplus.annotation.FieldStrategy;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* 用户秘钥
*
* @author JueYue
* @Date 2019-11-09 14:01:51
*/
@Data
@ApiModel("用户秘钥")
@TableName(value = "t_system_user_auth", resultMap = UserAuthModel.BASE_RESULT_MAP)
public class UserAuthModel extends IdTenantBaseModel<UserAuthModel> {
private static final long serialVersionUID = 1L;
@Excel(name = "用户ID")
@TableField(value = "USER_ID", strategy = FieldStrategy.NOT_EMPTY)
@ApiModelProperty(value = "用户ID", required = true)
private String userId;
@Excel(name = "头像")
@TableField(value = "AVATAR", strategy = FieldStrategy.NOT_EMPTY)
@ApiModelProperty("头像")
private String avatar;
@Excel(name = "账号")
@TableField(value = "ACCOUNT", strategy = FieldStrategy.NOT_EMPTY)
@ApiModelProperty("账号")
private String account;
@Excel(name = "密码")
@TableField(value = "PASSWORD", strategy = FieldStrategy.NOT_EMPTY)
@ApiModelProperty("密码")
private String password;
@Excel(name = "MD5密码盐")
@TableField(value = "SALT", strategy = FieldStrategy.NOT_EMPTY)
@ApiModelProperty("MD5密码盐")
private String salt;
@Excel(name = "名字")
@TableField(value = "NAME", strategy = FieldStrategy.NOT_EMPTY)
@ApiModelProperty("名字")
private String name;
@Excel(name = "类型")
@TableField(value = "TYPE")
@ApiModelProperty(value = "类型", required = true)
private Integer type;
@Excel(name = "状态")
@TableField(value = "STATUS")
@ApiModelProperty("状态")
private Integer status;
}
| 31.419753 | 83 | 0.715521 |
439fcb8fbb3ced62b41798b14d5511dade9f2174 | 183 | ts | TypeScript | node_modules/@guildeducationinc/recess/components/CardContent/CardContent.d.ts | rwarbelow/uaservices | b1cf5e07e330c85c3fb76d5cb32606562eda1c32 | [
"MIT"
] | null | null | null | node_modules/@guildeducationinc/recess/components/CardContent/CardContent.d.ts | rwarbelow/uaservices | b1cf5e07e330c85c3fb76d5cb32606562eda1c32 | [
"MIT"
] | null | null | null | node_modules/@guildeducationinc/recess/components/CardContent/CardContent.d.ts | rwarbelow/uaservices | b1cf5e07e330c85c3fb76d5cb32606562eda1c32 | [
"MIT"
] | null | null | null | import * as React from 'react';
export declare type CardContentProps = React.HTMLAttributes<HTMLElement>;
export declare const CardContent: React.FunctionComponent<CardContentProps>;
| 45.75 | 76 | 0.830601 |
b5704c79bf026d4830e43427cb8ce7125e2ead06 | 6,468 | swift | Swift | FittedSheets/ExamplesViewController.swift | daresaydigital/FittedSheets | b9a9af8692507a8578dd38284f3319cf17ad2834 | [
"MIT"
] | null | null | null | FittedSheets/ExamplesViewController.swift | daresaydigital/FittedSheets | b9a9af8692507a8578dd38284f3319cf17ad2834 | [
"MIT"
] | null | null | null | FittedSheets/ExamplesViewController.swift | daresaydigital/FittedSheets | b9a9af8692507a8578dd38284f3319cf17ad2834 | [
"MIT"
] | null | null | null | //
// ViewController.swift
// FittedSheets
//
// Created by Gordon Tucker on 8/16/18.
// Copyright © 2018 Gordon Tucker. All rights reserved.
//
import UIKit
import FittedSheetsPod
class ExamplesViewController: UIViewController {
@IBOutlet weak var stackView: UIStackView!
@IBOutlet weak var sizesTextField: UITextField!
@IBOutlet weak var halfScreenSwitch: UISwitch!
@IBOutlet weak var fullScreenSwitch: UISwitch!
@IBOutlet weak var adjustForBottomSafeAreaSwitch: UISwitch!
@IBOutlet weak var blurBottomSafeAreaSwitch: UISwitch!
@IBOutlet weak var dismissOnBackgroundTapSwitch: UISwitch!
@IBOutlet weak var navigationControllerSwitch: UISwitch!
@IBOutlet weak var useStockFirstInNavigationSwitch: UISwitch!
@IBOutlet weak var extendBackgroundBehindHandleSwitch: UISwitch!
@IBOutlet weak var roundedCornersSwitch: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
addExample("Color Tests", controller: { ColorExampleViewController.instantiate() })
addExample("Scroll View", controller: { ScrollViewExampleViewController.instantiate() })
addExample("Table View", controller: { TableViewExampleViewController.instantiate() }, mode: .top)
addExample("Table View Controller", controller: { ExampleTableViewController.instantiate() })
addExample("Intrinsic Height", controller: { IntrinsicExampleViewController.instantiate() })
addExample("Self Resizing", controller: { ResizingExampleViewController.instantiate() })
}
func addExample(_ name: String, controller: @escaping () -> UIViewController, mode: SheetViewMode = .bottom) {
let button = UIButton(type: .custom)
button.setTitle(name, for: .normal)
button.onTap { [weak self] in
guard let self = self else { return }
var controller = controller()
let stringSizes = self.sizesTextField.text!.components(separatedBy: ",")
var sizes: [SheetSize] = stringSizes.compactMap({
Int($0.trimmingCharacters(in: .whitespacesAndNewlines))
}).map({
SheetSize.fixed(CGFloat($0))
})
if self.fullScreenSwitch.isOn {
sizes.append(.fullScreen)
}
if self.halfScreenSwitch.isOn {
sizes.append(.halfScreen)
}
if self.navigationControllerSwitch.isOn {
if self.useStockFirstInNavigationSwitch.isOn {
controller = NavigationRootViewController.instantiate(exampleViewController: controller)
}
controller = UINavigationController(rootViewController: controller)
}
let sheetController = SheetViewController(controller: controller, sizes: sizes, sheetViewMode: mode)
sheetController.adjustForBottomSafeArea = self.adjustForBottomSafeAreaSwitch.isOn
sheetController.blurBottomSafeArea = self.blurBottomSafeAreaSwitch.isOn
sheetController.dismissOnBackgroundTap = self.dismissOnBackgroundTapSwitch.isOn
sheetController.extendBackgroundBehindHandle = self.extendBackgroundBehindHandleSwitch.isOn
sheetController.topCornersRadius = self.roundedCornersSwitch.isOn ? 15 : 0
sheetController.willDismiss = { _ in
print("Will dismiss \(name)")
}
sheetController.didDismiss = { _ in
print("Will dismiss \(name)")
}
self.present(sheetController, animated: false, completion: nil)
}
button.heightAnchor.constraint(equalToConstant: 50).isActive = true
button.setTitleColor(UIColor.black, for: .normal)
button.layer.cornerRadius = 4
button.layer.borderWidth = 1
button.layer.borderColor = UIColor.black.cgColor
self.stackView.addArrangedSubview(button)
}
@IBAction func dismissKeyboard(_ sender: Any) {
self.view.endEditing(true)
}
@IBAction func presentSheet1(_ sender: Any) {
let controller = SheetViewController(controller: UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "sheet1"))
controller.blurBottomSafeArea = false
self.present(controller, animated: false, completion: nil)
}
@IBAction func presentSheet2(_ sender: Any) {
let controller = SheetViewController(controller: UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "sheet2"), sizes: [.halfScreen, .fullScreen, .fixed(250)])
self.present(controller, animated: false, completion: nil)
}
@IBAction func presentSheet3(_ sender: Any) {
let controller = SheetViewController(controller: UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "sheet3"), sizes: [.fullScreen, .fixed(200)])
controller.adjustForBottomSafeArea = true
self.present(controller, animated: false, completion: nil)
}
@IBAction func presentSheet3v2(_ sender: Any) {
let controller = SheetViewController(controller: UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "sheet3"), sizes: [.fixed(100)])
controller.adjustForBottomSafeArea = true
self.present(controller, animated: false, completion: nil)
}
@IBAction func presentSheet4(_ sender: Any) {
let controller = SheetViewController(controller: UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "sheet4"), sizes: [.fixed(450), .fixed(300), .fixed(600), .fullScreen])
self.present(controller, animated: false, completion: nil)
}
@IBAction func presentSheet5(_ sender: Any) {
let controller = SheetViewController(controller: UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "sheet5"), sizes: [.fixed(450), .fixed(300), .fixed(160), .fullScreen])
self.present(controller, animated: false, completion: nil)
}
@IBAction func presentSelfSizingSheet(_ sender: Any) {
let controller = SheetViewController(controller: UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "selfsizing"), sizes: [.fullScreen])
self.present(controller, animated: false, completion: nil)
}
}
| 49 | 210 | 0.678417 |
e149704f25dd28a7751991e44325d6dea3adaf98 | 2,862 | go | Go | fab3/cmd/main.go | andrewyuau/fabric-chaincode-evm | dcad7d5df15943fcb18b0cea54be81109d79761a | [
"Apache-2.0"
] | null | null | null | fab3/cmd/main.go | andrewyuau/fabric-chaincode-evm | dcad7d5df15943fcb18b0cea54be81109d79761a | [
"Apache-2.0"
] | null | null | null | fab3/cmd/main.go | andrewyuau/fabric-chaincode-evm | dcad7d5df15943fcb18b0cea54be81109d79761a | [
"Apache-2.0"
] | null | null | null | /*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package main
import (
"fmt"
"os"
"strconv"
"go.uber.org/zap"
"github.com/hyperledger/fabric-chaincode-evm/fab3"
"github.com/hyperledger/fabric-sdk-go/pkg/client/channel"
"github.com/hyperledger/fabric-sdk-go/pkg/client/ledger"
"github.com/hyperledger/fabric-sdk-go/pkg/core/config"
"github.com/hyperledger/fabric-sdk-go/pkg/fabsdk"
)
const usage = `Fab3 uses environment variables to be able to start communicating with a Fabric network
Required Environment Variables:
FAB3_CONFIG - Path to a compatible Fabric SDK Go config file
FAB3_USER - User identity being used for the proxy (Matches the users names in the crypto-config directory specified in the config)
FAB3_ORG - Organization of the specified user
FAB3_CHANNEL - Channel to be used for the transactions
FAB3_CCID - ID of the EVM Chaincode deployed in your fabric network
Other Environment Variables:
PORT - Port the Fab3 will be running on. Default is 5000
`
var logger *zap.SugaredLogger
func main() {
rawLogger, _ := zap.NewProduction()
logger = rawLogger.Named("fab3").Sugar()
cfg := grabEnvVar("FAB3_CONFIG", true)
org := grabEnvVar("FAB3_ORG", true)
user := grabEnvVar("FAB3_USER", true)
ch := grabEnvVar("FAB3_CHANNEL", true)
ccid := grabEnvVar("FAB3_CCID", true)
port := grabEnvVar("PORT", false)
portNumber := 5000
if port != "" {
var err error
portNumber, err = strconv.Atoi(port)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to convert the environment variable `PORT`, %s, to an int\n", port)
os.Exit(1)
}
}
sdk, err := fabsdk.New(config.FromFile(cfg))
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to create Fabric SDK Client: %s\n", err)
os.Exit(1)
}
defer sdk.Close()
clientChannelContext := sdk.ChannelContext(ch, fabsdk.WithUser(user), fabsdk.WithOrg(org))
client, err := channel.New(clientChannelContext)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to create Fabric SDK Channel Client: %s\n", err)
os.Exit(1)
}
ledger, err := ledger.New(clientChannelContext)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to create Fabric SDK Ledger Client: %s\n", err)
os.Exit(1)
}
ethService := fab3.NewEthService(client, ledger, ch, ccid, logger)
logger.Infof("Starting Fab3 on port %d\n", portNumber)
proxy := fab3.NewFab3(ethService)
err = proxy.Start(portNumber)
if err != nil {
fmt.Fprintf(os.Stderr, "Error starting Fab3: %s", err)
}
defer func() {
logger.Info("Shutting down Fab3")
proxy.Shutdown()
logger.Info("Fab3 has exited")
}()
}
func grabEnvVar(varName string, required bool) string {
envVar := os.Getenv(varName)
if required && envVar == "" {
fmt.Fprintf(os.Stderr, "Fab3 requires the environment variable %s to be set\n\n%s\n\n", varName, usage)
os.Exit(1)
}
return envVar
}
| 28.336634 | 134 | 0.710692 |
af856c9b5e243afebc9e6b576c37f5bcd21545da | 9,230 | py | Python | pauxy/estimators/ueg.py | pauxy-qmc/pauxy | 1da80284284769b59361c73cfa3c2d914c74a73f | [
"Apache-2.0"
] | 16 | 2020-08-05T17:17:17.000Z | 2022-03-18T04:06:18.000Z | pauxy/estimators/ueg.py | pauxy-qmc/pauxy | 1da80284284769b59361c73cfa3c2d914c74a73f | [
"Apache-2.0"
] | 4 | 2020-05-17T21:28:20.000Z | 2021-04-22T18:05:50.000Z | pauxy/estimators/ueg.py | pauxy-qmc/pauxy | 1da80284284769b59361c73cfa3c2d914c74a73f | [
"Apache-2.0"
] | 5 | 2020-05-18T01:03:18.000Z | 2021-04-13T15:36:29.000Z | import time
import numpy
import scipy.linalg
try:
from pauxy.estimators.ueg_kernels import (
exchange_greens_function_per_qvec,
coulomb_greens_function_per_qvec,
build_J_opt, build_K_opt
)
except ImportError:
pass
def exchange_greens_function(nq, kpq_i, kpq, pmq_i, pmq, Gprod, G):
for iq in range(nq):
for (idxkpq,i) in zip(kpq[iq],kpq_i[iq]):
for (idxpmq,j) in zip(pmq[iq],pmq_i[iq]):
Gprod[iq] += G[j,idxkpq]*G[i,idxpmq]
def coulomb_greens_function(nq, kpq_i, kpq, pmq_i, pmq, Gkpq, Gpmq, G):
for iq in range(nq):
for (idxkpq,i) in zip(kpq[iq],kpq_i[iq]):
Gkpq[iq] += G[i,idxkpq]
for (idxpmq,i) in zip(pmq[iq],pmq_i[iq]):
Gpmq[iq] += G[i,idxpmq]
def local_energy_ueg(system, G, Ghalf=None, two_rdm=None):
"""Local energy computation for uniform electron gas
Parameters
----------
system :
system class
G :
Green's function
Returns
-------
etot : float
total energy
ke : float
kinetic energy
pe : float
potential energy
"""
if (system.diagH1):
ke = numpy.einsum('sii,sii->',system.H1,G)
else:
ke = numpy.einsum('sij,sij->',system.H1,G)
Gkpq = numpy.zeros((2,len(system.qvecs)), dtype=numpy.complex128)
Gpmq = numpy.zeros((2,len(system.qvecs)), dtype=numpy.complex128)
Gprod = numpy.zeros((2,len(system.qvecs)), dtype=numpy.complex128)
ne = [system.nup, system.ndown]
nq = numpy.shape(system.qvecs)[0]
for s in [0, 1]:
# exchange_greens_function(nq, system.ikpq_i, system.ikpq_kpq, system.ipmq_i,system.ipmq_pmq, Gprod[s],G[s])
# coulomb_greens_function(nq, system.ikpq_i, system.ikpq_kpq, system.ipmq_i, system.ipmq_pmq,Gkpq[s], Gpmq[s],G[s])
for iq in range(nq):
Gkpq[s,iq], Gpmq[s,iq] = coulomb_greens_function_per_qvec(system.ikpq_i[iq],
system.ikpq_kpq[iq],
system.ipmq_i[iq],
system.ipmq_pmq[iq],
G[s])
Gprod[s,iq] = exchange_greens_function_per_qvec(system.ikpq_i[iq],
system.ikpq_kpq[iq],
system.ipmq_i[iq],
system.ipmq_pmq[iq],
G[s])
if two_rdm is None:
two_rdm = numpy.zeros((2,2,len(system.qvecs)), dtype=numpy.complex128)
two_rdm[0,0] = numpy.multiply(Gkpq[0],Gpmq[0]) - Gprod[0]
essa = (1.0/(2.0*system.vol))*system.vqvec.dot(two_rdm[0,0])
two_rdm[1,1] = numpy.multiply(Gkpq[1],Gpmq[1]) - Gprod[1]
essb = (1.0/(2.0*system.vol))*system.vqvec.dot(two_rdm[1,1])
two_rdm[0,1] = numpy.multiply(Gkpq[0],Gpmq[1])
two_rdm[1,0] = numpy.multiply(Gkpq[1],Gpmq[0])
eos = (
(1.0/(2.0*system.vol))*system.vqvec.dot(two_rdm[0,1])
+ (1.0/(2.0*system.vol))*system.vqvec.dot(two_rdm[1,0])
)
pe = essa + essb + eos
return (ke+pe, ke, pe)
# JHLFML
def build_J(system, Gpmq, Gkpq):
J = [numpy.zeros((system.nbasis, system.nbasis), dtype = numpy.complex128),
numpy.zeros((system.nbasis, system.nbasis), dtype = numpy.complex128)]
for (iq, q) in enumerate(system.qvecs):
for idxi, i in enumerate(system.basis):
for idxj, j in enumerate(system.basis):
jpq = j + q
idxjpq = system.lookup_basis(jpq)
if (idxjpq is not None) and (idxjpq == idxi):
J[0][idxj,idxi] += (1.0/(2.0*system.vol)) * system.vqvec[iq] * (Gkpq[0][iq] + Gkpq[1][iq])
for (iq, q) in enumerate(system.qvecs):
for idxi, i in enumerate(system.basis):
for idxj, j in enumerate(system.basis):
jpq = j - q
idxjmq = system.lookup_basis(jpq)
if (idxjmq is not None) and (idxjmq == idxi):
J[0][idxj,idxi] += (1.0/(2.0*system.vol)) * system.vqvec[iq] * (Gpmq[0][iq] + Gpmq[1][iq])
J[1] = J[0]
return J
def build_K(system, G):
K = numpy.zeros((2,system.nbasis, system.nbasis), dtype = numpy.complex128)
for s in [0, 1]:
for iq in range(len(system.vqvec)):
for (idxjmq,idxj) in zip(system.ipmq_pmq[iq],system.ipmq_i[iq]):
for (idxkpq,idxk) in zip(system.ikpq_kpq[iq],system.ikpq_i[iq]):
K[s, idxj, idxkpq] += - (1.0/(2.0*system.vol)) * system.vqvec[iq] * G[s][idxjmq, idxk]
for iq in range(len(system.vqvec)):
for (idxjpq,idxj) in zip(system.ikpq_kpq[iq],system.ikpq_i[iq]):
for (idxpmq,idxp) in zip(system.ipmq_pmq[iq],system.ipmq_i[iq]):
K[s, idxj, idxpmq] += - (1.0/(2.0*system.vol)) * system.vqvec[iq] * G[s][idxjpq, idxp]
return K
def fock_ueg(sys, G):
"""Fock matrix computation for uniform electron gas
Parameters
----------
sys : :class`pauxy.systems.ueg.UEG`
UEG system class.
G : :class:`numpy.ndarray`
Green's function.
Returns
-------
F : :class:`numpy.ndarray`
Fock matrix (2, nbasis, nbasis).
"""
nbsf = sys.nbasis
nq = len(sys.qvecs)
assert nq == len(sys.vqvec)
Fock = numpy.zeros((2, nbsf, nbsf), dtype=numpy.complex128)
Gkpq = numpy.zeros((2, nq), dtype=numpy.complex128)
Gpmq = numpy.zeros((2, nq), dtype=numpy.complex128)
for s in [0, 1]:
coulomb_greens_function(nq, sys.ikpq_i, sys.ikpq_kpq,
sys.ipmq_i, sys.ipmq_pmq,
Gkpq[s], Gpmq[s], G[s])
J = build_J_opt(nq, sys.vqvec, sys.vol, sys.nbasis,
sys.ikpq_i, sys.ikpq_kpq, sys.ipmq_i, sys.ipmq_pmq,
Gkpq, Gpmq)
K = build_K_opt(nq, sys.vqvec, sys.vol, sys.nbasis,
sys.ikpq_i, sys.ikpq_kpq, sys.ipmq_i, sys.ipmq_pmq,
G)
for s in [0, 1]:
Fock[s] = sys.H1[s] + J[s] + K[s]
return Fock
def unit_test():
from pauxy.systems.ueg import UEG
import numpy as np
inputs = {'nup':7,
'ndown':7,
'rs':1.0,
'ecut':2.0}
system = UEG(inputs, True)
nbsf = system.nbasis
Pa = np.zeros([nbsf,nbsf],dtype = np.complex128)
Pb = np.zeros([nbsf,nbsf],dtype = np.complex128)
na = system.nup
nb = system.ndown
for i in range(na):
Pa[i,i] = 1.0
for i in range(nb):
Pb[i,i] = 1.0
P = np.array([Pa, Pb])
etot, ekin, epot = local_energy_ueg(system, G=P)
print("ERHF = {}, {}, {}".format(etot, ekin, epot))
from pauxy.utils.linalg import exponentiate_matrix, reortho
from pauxy.estimators.greens_function import gab
# numpy.random.seed()
rCa = numpy.random.randn(nbsf, na)
zCa = numpy.random.randn(nbsf, na)
rCb = numpy.random.randn(nbsf, nb)
zCb = numpy.random.randn(nbsf, nb)
Ca = rCa + 1j * zCa
Cb = rCb + 1j * zCb
Ca, detR = reortho(Ca)
Cb, detR = reortho(Cb)
# S = print(Ca.dot(Cb.T))
# print(S)
# exit()
Ca = numpy.array(Ca, dtype=numpy.complex128)
Cb = numpy.array(Cb, dtype=numpy.complex128)
P = [gab(Ca, Ca), gab(Cb, Cb)]
# diff = P[0] - P[1]
# print("fro = {}".format(numpy.linalg.norm(diff,ord='fro')))
# solver = lib.diis.DIIS()
# dt = 0.1
# for i in range(100):
# # Compute Fock matrix
# Fock = fock_ueg(system, G=P)
# # Compute DIIS Errvec
# PFmFPa = P[0].dot(Fock[0]) - Fock[0].dot(P[0])
# PFmFPb = P[1].dot(Fock[1]) - Fock[1].dot(P[1])
# errvec = numpy.append(numpy.reshape(PFmFPa, nbsf*nbsf),numpy.reshape(PFmFPb, nbsf*nbsf))
# RMS = np.sqrt(np.dot(errvec, errvec))
# print ("{} {} {}".format(i,numpy.real(local_energy_ueg(system, P)), numpy.real(RMS)))
# # Form Fockvec
# Fock[0] = numpy.array(Fock[0])
# Fock[1] = numpy.array(Fock[1])
# Fockvec = numpy.append(numpy.reshape(Fock[0],nbsf*nbsf), numpy.reshape(Fock[1],nbsf*nbsf))
# # Extrapolate Fockvec
# # Fockvec = solver.update(Fockvec, xerr=errvec)
# # Apply Propagator
# Fock = numpy.reshape(Fockvec, (2, nbsf, nbsf))
# ea, Ca = numpy.linalg.eig(Fock[0])
# eb, Cb = numpy.linalg.eig(Fock[1])
# sort_perm = ea.argsort()
# ea.sort()
# Ca = Ca[:, sort_perm]
# sort_perm = eb.argsort()
# eb.sort()
# Cb = Cb[:, sort_perm]
# Ca = Ca[:,:na]
# Cb = Cb[:,:nb]
# Ca, detR = reortho(Ca)
# Cb, detR = reortho(Cb)
# P = [gab(Ca, Ca), gab(Cb, Cb)]
# # expF = [exponentiate_matrix(-dt*Fock[0]), exponentiate_matrix(-dt*Fock[1])]
# # Ca = expF[0].dot(Ca)
# # Cb = expF[1].dot(Cb)
# # diff = P[0] - P[1]
# # print("fro = {}".format(numpy.linalg.norm(diff,ord='fro')))
if __name__=="__main__":
unit_test()
| 35.775194 | 124 | 0.534345 |
e7395941a683bb8dacc88bece82a4087a34b73a3 | 1,256 | php | PHP | app/Http/Controllers/Report/UserAssignReport.php | md-rabiul-hasan/agent-banking-report | 746644fcdb1bd1606c3b0a16b6c5d182b282396a | [
"MIT"
] | null | null | null | app/Http/Controllers/Report/UserAssignReport.php | md-rabiul-hasan/agent-banking-report | 746644fcdb1bd1606c3b0a16b6c5d182b282396a | [
"MIT"
] | null | null | null | app/Http/Controllers/Report/UserAssignReport.php | md-rabiul-hasan/agent-banking-report | 746644fcdb1bd1606c3b0a16b6c5d182b282396a | [
"MIT"
] | null | null | null | <?php
namespace App\Http\Controllers\Report;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
class UserAssignReport extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$roles=DB::table('roles')->whereNotNull('name')->orderby('name', 'ASC')->get();
return view('report.userAssign.index', compact('roles'));
}
public function show(Request $req)
{
$role_d = $req->role_d;
/*if($role_d =='all')
{
$users=DB::table('users as u')
->leftJoin('roles as r', 'r.id', 'u.role_id')
->leftJoin('branches as b', 'b.branch_id', 'u.branch_id')
->select('u.*', 'r.name as role_name', 'b.branch_name')
->get();
}else{
$users=DB::table('users as u')
->leftJoin('roles as r', 'r.id', 'u.role_id')
->leftJoin('branches as b', 'b.branch_id', 'u.branch_id')
->select('u.*', 'r.name as role_name', 'b.branch_name')
->where('u.role_id', $role_d)
->get();
}*/
$users = DB::select('EXEC get_user_list');
return view('report.userAssign.show_user', compact('users'));
}
}
| 23.259259 | 84 | 0.593949 |
786f9b533bab09d7531c6061a746971f62cd9db6 | 152 | sql | SQL | SQL/EmployeeSalaries.sql | WinrichSy/HackerRank-Solutions | ed928de50cbbbdf0aee471630f6c04f9a0f69a1f | [
"Apache-2.0"
] | null | null | null | SQL/EmployeeSalaries.sql | WinrichSy/HackerRank-Solutions | ed928de50cbbbdf0aee471630f6c04f9a0f69a1f | [
"Apache-2.0"
] | null | null | null | SQL/EmployeeSalaries.sql | WinrichSy/HackerRank-Solutions | ed928de50cbbbdf0aee471630f6c04f9a0f69a1f | [
"Apache-2.0"
] | null | null | null | --Employee Salaries
--https://www.hackerrank.com/challenges/salary-of-employees/problem
SELECT name
FROM employee
WHERE salary > 2000 AND months < 10;
| 21.714286 | 67 | 0.782895 |
1abf4cb881c4f3e60d1cfc3f8381caa53f423178 | 627 | py | Python | resources/home/dnanexus/get_reference.py | edawson/parliament2 | 2632aa3484ef64c9539c4885026b705b737f6d1e | [
"Apache-2.0"
] | null | null | null | resources/home/dnanexus/get_reference.py | edawson/parliament2 | 2632aa3484ef64c9539c4885026b705b737f6d1e | [
"Apache-2.0"
] | null | null | null | resources/home/dnanexus/get_reference.py | edawson/parliament2 | 2632aa3484ef64c9539c4885026b705b737f6d1e | [
"Apache-2.0"
] | 1 | 2020-05-28T23:01:44.000Z | 2020-05-28T23:01:44.000Z | def main():
reference_chosen = False
with open("ref.fa", 'r') as f:
chrs = set()
for line in f:
if line.startswith(">chr1") and "LN:248956422" in line:
print "hg38"
reference_chosen = True
break
if line.startswith('>'):
chrs.add(line)
if not line.startswith('>chr'):
print "b37"
reference_chosen = True
break
if not reference_chosen:
if len(chrs) == 195:
print "hg38"
else:
print "hg19"
main() | 27.26087 | 67 | 0.441786 |
80b5ff5ae4cd9ca498df8d3b3ffcd4caca4b11fd | 359 | sql | SQL | sql2_persediaan/beban_rinci_sql/beban_barang4_bappeda.sql | muntaza/Open_Persediaan | 8010839926cc6a357faf40481c7d7f43c1f66a3e | [
"BSD-2-Clause"
] | 4 | 2020-05-26T07:52:34.000Z | 2022-01-09T17:02:21.000Z | sql2_persediaan/beban_rinci_sql/beban_barang4_bappeda.sql | muntaza/Open_Persediaan | 8010839926cc6a357faf40481c7d7f43c1f66a3e | [
"BSD-2-Clause"
] | null | null | null | sql2_persediaan/beban_rinci_sql/beban_barang4_bappeda.sql | muntaza/Open_Persediaan | 8010839926cc6a357faf40481c7d7f43c1f66a3e | [
"BSD-2-Clause"
] | 1 | 2020-05-26T07:52:36.000Z | 2020-05-26T07:52:36.000Z | DROP VIEW IF EXISTS view_beban_barang4_bappeda;
CREATE VIEW view_beban_barang4_bappeda AS
SELECT
*,
beban * harga AS jumlah_harga
FROM
view_beban_barang3_bappeda
WHERE
1 = 1 AND
beban > 0 AND
id_skpd = 21;
GRANT ALL PRIVILEGES ON view_beban_barang4_bappeda TO lap_bappeda;
REVOKE INSERT, UPDATE, DELETE ON view_beban_barang4_bappeda FROM lap_bappeda;
| 17.095238 | 77 | 0.818942 |
e2f9eea9d08c8b6cb00c0ccdad7cf21c9c379f52 | 5,794 | py | Python | sdk/python/pulumi_keycloak/openid/client_time_policy.py | jaxxstorm/pulumi-keycloak | 2fc7b1060b725a40d2ada745aa0d10130243a0b5 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_keycloak/openid/client_time_policy.py | jaxxstorm/pulumi-keycloak | 2fc7b1060b725a40d2ada745aa0d10130243a0b5 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_keycloak/openid/client_time_policy.py | jaxxstorm/pulumi-keycloak | 2fc7b1060b725a40d2ada745aa0d10130243a0b5 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from .. import utilities, tables
class ClientTimePolicy(pulumi.CustomResource):
day_month: pulumi.Output[str]
day_month_end: pulumi.Output[str]
decision_strategy: pulumi.Output[str]
description: pulumi.Output[str]
hour: pulumi.Output[str]
hour_end: pulumi.Output[str]
logic: pulumi.Output[str]
minute: pulumi.Output[str]
minute_end: pulumi.Output[str]
month: pulumi.Output[str]
month_end: pulumi.Output[str]
name: pulumi.Output[str]
not_before: pulumi.Output[str]
not_on_or_after: pulumi.Output[str]
realm_id: pulumi.Output[str]
resource_server_id: pulumi.Output[str]
year: pulumi.Output[str]
year_end: pulumi.Output[str]
def __init__(__self__, resource_name, opts=None, day_month=None, day_month_end=None, decision_strategy=None, description=None, hour=None, hour_end=None, logic=None, minute=None, minute_end=None, month=None, month_end=None, name=None, not_before=None, not_on_or_after=None, realm_id=None, resource_server_id=None, year=None, year_end=None, __props__=None, __name__=None, __opts__=None):
"""
Create a ClientTimePolicy resource with the given unique name, props, and options.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
if __name__ is not None:
warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning)
resource_name = __name__
if __opts__ is not None:
warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning)
opts = __opts__
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = dict()
__props__['day_month'] = day_month
__props__['day_month_end'] = day_month_end
if decision_strategy is None:
raise TypeError("Missing required property 'decision_strategy'")
__props__['decision_strategy'] = decision_strategy
__props__['description'] = description
__props__['hour'] = hour
__props__['hour_end'] = hour_end
__props__['logic'] = logic
__props__['minute'] = minute
__props__['minute_end'] = minute_end
__props__['month'] = month
__props__['month_end'] = month_end
__props__['name'] = name
__props__['not_before'] = not_before
__props__['not_on_or_after'] = not_on_or_after
if realm_id is None:
raise TypeError("Missing required property 'realm_id'")
__props__['realm_id'] = realm_id
if resource_server_id is None:
raise TypeError("Missing required property 'resource_server_id'")
__props__['resource_server_id'] = resource_server_id
__props__['year'] = year
__props__['year_end'] = year_end
super(ClientTimePolicy, __self__).__init__(
'keycloak:openid/clientTimePolicy:ClientTimePolicy',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name, id, opts=None, day_month=None, day_month_end=None, decision_strategy=None, description=None, hour=None, hour_end=None, logic=None, minute=None, minute_end=None, month=None, month_end=None, name=None, not_before=None, not_on_or_after=None, realm_id=None, resource_server_id=None, year=None, year_end=None):
"""
Get an existing ClientTimePolicy resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param str id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = dict()
__props__["day_month"] = day_month
__props__["day_month_end"] = day_month_end
__props__["decision_strategy"] = decision_strategy
__props__["description"] = description
__props__["hour"] = hour
__props__["hour_end"] = hour_end
__props__["logic"] = logic
__props__["minute"] = minute
__props__["minute_end"] = minute_end
__props__["month"] = month
__props__["month_end"] = month_end
__props__["name"] = name
__props__["not_before"] = not_before
__props__["not_on_or_after"] = not_on_or_after
__props__["realm_id"] = realm_id
__props__["resource_server_id"] = resource_server_id
__props__["year"] = year
__props__["year_end"] = year_end
return ClientTimePolicy(resource_name, opts=opts, __props__=__props__)
def translate_output_property(self, prop):
return tables._CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
def translate_input_property(self, prop):
return tables._SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
| 47.105691 | 389 | 0.669831 |
144e8563d356054ea2b723034e4066aa0ed2013d | 10,574 | ts | TypeScript | src/tokens/parsers.ts | functional-script/fscript | ff25134cc9a7f4322223f3290a15049b7c30759a | [
"MIT"
] | null | null | null | src/tokens/parsers.ts | functional-script/fscript | ff25134cc9a7f4322223f3290a15049b7c30759a | [
"MIT"
] | null | null | null | src/tokens/parsers.ts | functional-script/fscript | ff25134cc9a7f4322223f3290a15049b7c30759a | [
"MIT"
] | null | null | null | import { TokenParser, Token, KEYWORD_LITERAL } from './types'
import { TokenList } from './list'
import { TokenError } from './error'
import { CompilerOptions } from '../options'
/**
* Allows to parse a new line token
*/
export class NewLineToken implements TokenParser {
constructor(options: CompilerOptions) {}
get re(): RegExp {
return /^(\r|\n)/
}
static get ID(): string {
return 'NEW_LINE'
}
public supports(code: string): boolean {
return code.trim() === '' || this.re.test(code)
}
public parse(code: string, list: TokenList): Token {
let lastToken = list.hasLast ? list.last : null
return {
name: NewLineToken.ID,
value: '\n',
rawValue: '\n',
position: {
line: lastToken
? lastToken.name === NewLineToken.ID
? lastToken.position.line + 1
: lastToken.position.line
: 1,
start: lastToken
? lastToken.name === NewLineToken.ID
? 0
: lastToken.position.end + 1
: 0,
end: lastToken
? lastToken.name === NewLineToken.ID
? 0
: lastToken.position.end + 1
: 0,
},
}
}
public substract(code: string, tokens: TokenList): string {
if (this.re.test(code)) {
return code.replace(this.re, '')
}
return code.trim()
}
}
/**
* Allow to parse an indentation
*/
export class IndentToken implements TokenParser {
private kind: CompilerOptions['indentKind']
private size: CompilerOptions['indentSize']
constructor(options: CompilerOptions) {
this.kind = options.indentKind
this.size = options.indentSize
}
static get ID(): string {
return 'INDENT'
}
public supports(code: string, list: TokenList): boolean {
let re =
this.kind === 'space'
? new RegExp(`^${' '.repeat(this.size)}`)
: new RegExp('^\t')
let lastToken = list.hasLast ? list.last : null
if (!lastToken) {
return re.test(code) && list.length === 0
}
return (
re.test(code) &&
(lastToken.name === NewLineToken.ID || lastToken.name === IndentToken.ID)
)
}
public parse(code: string, list: TokenList): Token {
let re =
this.kind === 'space'
? new RegExp(`^${' '.repeat(this.size)}`)
: new RegExp('^\t')
let match = code.match(re)
let position = list.calculateNextPostion(match ? match[0] : { length: 0 })
if (!match) {
throw new TokenError(IndentToken.ID, code, position)
}
return {
name: IndentToken.ID,
value: match[0].length,
rawValue: match[0],
position,
}
}
public substract(code: string): string {
let re =
this.kind === 'space'
? new RegExp(`^${' '.repeat(this.size)}`)
: new RegExp('^\t')
return code.replace(re, '')
}
}
/**
* Allows to parse spaces
*/
export class SpaceToken implements TokenParser {
constructor(options: CompilerOptions) {}
static get ID(): string {
return 'SPACE'
}
public supports(code: string, list: TokenList): boolean {
return /^ /.test(code)
}
public parse(code: string, list: TokenList): Token {
let match = code.match(/^ +/)
let position = list.calculateNextPostion(match ? match[0] : { length: 0 })
if (!match) {
throw new TokenError(SpaceToken.ID, code, position)
}
return {
name: SpaceToken.ID,
value: ' ',
rawValue: match[0],
position,
}
}
public substract(line: string): string {
return line.replace(/^ +/, '')
}
}
/**
* Parse an fscript keyword
*/
export class KeywordToken implements TokenParser {
constructor(options: CompilerOptions) {}
static get ID(): string {
return 'KEYWORD'
}
private re =
/^(def|var|let|const|class|type|interface|if|else|for|while|do|throw|new|async|await|yield|return|then|import|export|from|as|in|with|function|and|or)/
public supports(code: string): boolean {
return this.re.test(code)
}
public parse(code: string, list: TokenList): Token {
let match = code.match(this.re)
let position = list.calculateNextPostion(match ? match[1] : { length: 0 })
if (!match) {
throw new TokenError(KeywordToken.ID, code, position)
}
return {
name: KeywordToken.ID,
value: match[1],
rawValue: match[1],
position,
}
}
public substract(code: string): string {
return code.replace(this.re, '')
}
}
/**
* Parse an fscript separator
*/
export class SeparatorToken implements TokenParser {
constructor(options: CompilerOptions) {}
static get ID(): string {
return 'SEPARATOR'
}
private re = /^(,)/
public supports(code: string): boolean {
return this.re.test(code)
}
public parse(code: string, list: TokenList): Token {
let match = code.match(this.re)
let position = list.calculateNextPostion(match ? match[1] : { length: 0 })
if (!match) {
throw new TokenError(SeparatorToken.ID, code, position)
}
return {
name: SeparatorToken.ID,
value: match[1],
rawValue: match[1],
position,
}
}
public substract(code: string): string {
return code.replace(this.re, '')
}
}
/**
* Parse any fscript operator
*/
export class OperatorToken implements TokenParser {
constructor(options: CompilerOptions) {}
static get ID(): string {
return 'OPERATOR'
}
private re =
/^(:|=>|\+|\->|\-|\*|\/|\.\.\.|\.\.|\.|=>|<=|===|==|=|is|and|or|not|!=|!==|!|gte|lte|gt|lt|eq)/
public supports(code: string): boolean {
return this.re.test(code)
}
public parse(code: string, list: TokenList): Token {
let match = code.match(this.re)
let position = list.calculateNextPostion(match ? match[1] : { length: 0 })
if (!match) {
throw new TokenError(OperatorToken.ID, code, position)
}
return {
name: OperatorToken.ID,
value: match[1],
rawValue: match[1],
position,
}
}
public substract(code: string): string {
return code.replace(this.re, '')
}
}
/**
* Parse an fscript identifier
*/
export class IdentifierToken implements TokenParser {
constructor(options: CompilerOptions) {}
static get ID(): string {
return 'IDENTIFIER'
}
private re = /^([a-zA-Z][a-zA-Z0-9_-]*)/
public supports(code: string): boolean {
return this.re.test(code)
}
public parse(code: string, list: TokenList): Token {
let match = code.match(this.re)
let position = list.calculateNextPostion(match ? match[1] : { length: 0 })
if (!match) {
throw new TokenError(IdentifierToken.ID, code, position)
}
return {
name: IdentifierToken.ID,
value: match[1],
rawValue: match[1],
position,
}
}
public substract(code: string): string {
return code.replace(this.re, '')
}
}
/**
* Parse an fscript literral
*/
export class LiteralToken implements TokenParser {
private re: RegExp
constructor(options: CompilerOptions) {
this.re = new RegExp(
`^(([0-9.]+)|("[^"]*")|('[^']*')|(\`[^\`]*\`)|(${KEYWORD_LITERAL.join(
'|',
)}))`,
)
}
static get ID(): string {
return 'LITTERAL'
}
public supports(code: string): boolean {
return this.re.test(code)
}
public parse(code: string, list: TokenList): Token {
let match = code.match(this.re)
let position = list.calculateNextPostion(match ? match[1] : { length: 0 })
if (!match) {
throw new TokenError(LiteralToken.ID, code, position)
}
return {
name: LiteralToken.ID,
value: match[1],
rawValue: match[1],
position,
}
}
public substract(code: string): string {
return code.replace(this.re, '')
}
}
/**
* Parse an fscript group using parenthesis
*/
export class GroupToken implements TokenParser {
constructor(options: CompilerOptions) {}
static get ID_START(): string {
return 'GROUP_START'
}
static get ID_END(): string {
return 'GROUP_END'
}
private re = /^(\)|\()/
public supports(code: string): boolean {
return this.re.test(code)
}
public parse(code: string, list: TokenList): Token {
let match = code.match(this.re)
let position = list.calculateNextPostion(match ? match[1] : { length: 0 })
if (!match) {
throw new TokenError(
`${GroupToken.ID_START}|${GroupToken.ID_END}`,
code,
position,
)
}
return {
name: match[1] === ')' ? GroupToken.ID_END : GroupToken.ID_START,
value: match[1],
rawValue: match[1],
position,
}
}
public substract(code: string): string {
return code.replace(this.re, '')
}
}
/**
* Parse instruction block or objet group definitions
* "{}"
*/
export class BlockToken implements TokenParser {
constructor(options: CompilerOptions) {}
static get ID_START(): string {
return 'BLOCK_START'
}
static get ID_END(): string {
return 'BLOCK_END'
}
private re = /^(\}|\{)/
public supports(code: string): boolean {
return this.re.test(code)
}
public parse(code: string, list: TokenList): Token {
let match = code.match(this.re)
let position = list.calculateNextPostion(match ? match[1] : { length: 0 })
if (!match) {
throw new TokenError(
`${BlockToken.ID_START}|${BlockToken.ID_END}`,
code,
position,
)
}
return {
name: match[1] === '}' ? BlockToken.ID_END : BlockToken.ID_START,
value: match[1],
rawValue: match[1],
position,
}
}
public substract(code: string): string {
return code.replace(this.re, '')
}
}
/**
* Parse array bracket syntax "[]"
*/
export class ArrayToken implements TokenParser {
constructor(options: CompilerOptions) {}
static get ID_START(): string {
return 'ARRAY_START'
}
static get ID_END(): string {
return 'ARRAY_END'
}
private re = /^(\]|\[)/
public supports(code: string): boolean {
return this.re.test(code)
}
public parse(code: string, list: TokenList): Token {
let match = code.match(this.re)
let position = list.calculateNextPostion(match ? match[1] : { length: 0 })
if (!match) {
throw new TokenError(
`${ArrayToken.ID_START}|${ArrayToken.ID_END}`,
code,
position,
)
}
return {
name: match[1] === ']' ? ArrayToken.ID_END : ArrayToken.ID_START,
value: match[1],
rawValue: match[1],
position,
}
}
public substract(code: string): string {
return code.replace(this.re, '')
}
}
| 21.712526 | 154 | 0.597882 |
ec6f0dddc3a4c8a09f5ac89ce0a6de2c5f94d1e7 | 10,058 | lua | Lua | tests/lutl_assert_tests.lua | Saend/cutl | 31c091ec3155185a7764682654ad9ed3932f6267 | [
"MIT"
] | null | null | null | tests/lutl_assert_tests.lua | Saend/cutl | 31c091ec3155185a7764682654ad9ed3932f6267 | [
"MIT"
] | null | null | null | tests/lutl_assert_tests.lua | Saend/cutl | 31c091ec3155185a7764682654ad9ed3932f6267 | [
"MIT"
] | null | null | null | require('tests/tests')
local T = {}
-- ASSERT_TRUE
function T.assert_true_true_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_true(true)
end)
-- Asserts
lutl:assert_equal(fix.lutl:get_failed(), 0)
end
function T.assert_true_number_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_true(0)
end)
-- Asserts
lutl:assert_equal(fix.lutl:get_failed(), 0)
end
function T.assert_true_string_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_true('foo')
end)
-- Asserts
lutl:assert_equal(fix.lutl:get_failed(), 0)
end
function T.assert_true_table_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_true({})
end)
-- Asserts
lutl:assert_equal(fix.lutl:get_failed(), 0)
end
function T.assert_true_userdata_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_true(lutl)
end)
-- Asserts
lutl:assert_equal(fix.lutl:get_failed(), 0)
end
function T.assert_true_false_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_true(false)
end)
-- Asserts
lutl:assert_false(fix.lutl:get_error())
lutl:assert_equal(fix.lutl:get_failed(), 1)
end
function T.assert_true_nil_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_true(nil)
end)
-- Asserts
lutl:assert_false(fix.lutl:get_error())
lutl:assert_equal(fix.lutl:get_failed(), 1)
end
-- ASSERT_FALSE
function T.assert_false_false_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_false(false)
end)
-- Asserts
lutl:assert_equal(fix.lutl:get_failed(), 0)
end
function T.assert_false_nil_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_false(nil)
end)
-- Asserts
lutl:assert_equal(fix.lutl:get_failed(), 0)
end
function T.assert_false_true_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_false(true)
end)
-- Asserts
lutl:assert_false(fix.lutl:get_error())
lutl:assert_equal(fix.lutl:get_failed(), 1)
end
function T.assert_false_number_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_false(0)
end)
-- Asserts
lutl:assert_false(fix.lutl:get_error())
lutl:assert_equal(fix.lutl:get_failed(), 1)
end
function T.assert_false_string_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_false('foo')
end)
-- Asserts
lutl:assert_false(fix.lutl:get_error())
lutl:assert_equal(fix.lutl:get_failed(), 1)
end
function T.assert_false_table_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_false({})
end)
-- Asserts
lutl:assert_false(fix.lutl:get_error())
lutl:assert_equal(fix.lutl:get_failed(), 1)
end
function T.assert_false_userdata_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_false(lutl)
end)
-- Asserts
lutl:assert_false(fix.lutl:get_error())
lutl:assert_equal(fix.lutl:get_failed(), 1)
end
-- ASSERT_EQUAL
function T.assert_equal_numbers_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_equal(10, 6+4)
end)
-- Asserts
lutl:assert_equal(fix.lutl:get_failed(), 0)
end
function T.assert_equal_strings_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_equal('foobar', 'foo'..'bar')
end)
-- Asserts
lutl:assert_equal(fix.lutl:get_failed(), 0)
end
function T.assert_equal_userdata_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_equal(lutl, lutl)
end)
-- Asserts
lutl:assert_equal(fix.lutl:get_failed(), 0)
end
function T.assert_equal_tables_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_equal({}, {})
end)
-- Asserts
lutl:assert_false(fix.lutl:get_error())
lutl:assert_equal(fix.lutl:get_failed(), 1)
end
function T.assert_equal_numbers2_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_equal(11, 6+4)
end)
-- Asserts
lutl:assert_false(fix.lutl:get_error())
lutl:assert_equal(fix.lutl:get_failed(), 1)
end
function T.assert_equal_strings2_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_equal('foobar', 'Foo'..'bar')
end)
-- Asserts
lutl:assert_false(fix.lutl:get_error())
lutl:assert_equal(fix.lutl:get_failed(), 1)
end
function T.assert_equal_number_string_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_equal(36, '36')
end)
-- Asserts
lutl:assert_false(fix.lutl:get_error())
lutl:assert_equal(fix.lutl:get_failed(), 1)
end
function T.assert_equal_number_bool_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_equal(0, false)
end)
-- Asserts
lutl:assert_false(fix.lutl:get_error())
lutl:assert_equal(fix.lutl:get_failed(), 1)
end
function T.assert_equal_nil_false_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_equal(nil, false)
end)
-- Asserts
lutl:assert_false(fix.lutl:get_error())
lutl:assert_equal(fix.lutl:get_failed(), 1)
end
-- ASSERT_NIL
function T.assert_nil_nil_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_nil(nil)
end)
-- Asserts
lutl:assert_equal(fix.lutl:get_failed(), 0)
end
function T.assert_nil_undefined_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_nil(something)
end)
-- Asserts
lutl:assert_equal(fix.lutl:get_failed(), 0)
end
function T.assert_nil_false_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_nil(false)
end)
-- Asserts
lutl:assert_false(fix.lutl:get_error())
lutl:assert_equal(fix.lutl:get_failed(), 1)
end
function T.assert_nil_number_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_nil(0)
end)
-- Asserts
lutl:assert_false(fix.lutl:get_error())
lutl:assert_equal(fix.lutl:get_failed(), 1)
end
function T.assert_nil_string_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_nil('foo')
end)
-- Asserts
lutl:assert_false(fix.lutl:get_error())
lutl:assert_equal(fix.lutl:get_failed(), 1)
end
function T.assert_nil_table_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_nil({})
end)
-- Asserts
lutl:assert_false(fix.lutl:get_error())
lutl:assert_equal(fix.lutl:get_failed(), 1)
end
function T.assert_nil_userdata_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_nil(lutl)
end)
-- Asserts
lutl:assert_false(fix.lutl:get_error())
lutl:assert_equal(fix.lutl:get_failed(), 1)
end
-- ASSERT_NOT_NIL
function T.assert_notnil_false_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_notnil(false)
end)
-- Asserts
lutl:assert_equal(fix.lutl:get_failed(), 0)
end
function T.assert_notnil_number_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_notnil(0)
end)
-- Asserts
lutl:assert_equal(fix.lutl:get_failed(), 0)
end
function T.assert_notnil_string_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_notnil('foo')
end)
-- Asserts
lutl:assert_equal(fix.lutl:get_failed(), 0)
end
function T.assert_notnil_table_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_notnil({})
end)
-- Asserts
lutl:assert_equal(fix.lutl:get_failed(), 0)
end
function T.assert_notnil_userdata_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_notnil(lutl)
end)
-- Asserts
lutl:assert_equal(fix.lutl:get_failed(), 0)
end
function T.assert_notnil_nil_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_notnil(nil)
end)
-- Asserts
lutl:assert_false(fix.lutl:get_error())
lutl:assert_equal(fix.lutl:get_failed(), 1)
end
function T.assert_notnil_undefined_test(lutl, fix)
-- Function under test
fix.lutl:run(nil, function(lutl)
lutl:assert_notnil(something)
end)
-- Asserts
lutl:assert_false(fix.lutl:get_error())
lutl:assert_equal(fix.lutl:get_failed(), 1)
end
-- ASSERT SUITE
return function(lutl)
lutl:at_start(fixture_setup)
lutl:at_end(fixture_clean)
lutl:test(T, 'assert_true_true_test')
lutl:test(T, 'assert_true_number_test')
lutl:test(T, 'assert_true_string_test')
lutl:test(T, 'assert_true_table_test')
lutl:test(T, 'assert_true_userdata_test')
lutl:test(T, 'assert_true_false_test')
lutl:test(T, 'assert_true_nil_test')
lutl:test(T, 'assert_false_false_test')
lutl:test(T, 'assert_false_nil_test')
lutl:test(T, 'assert_false_true_test')
lutl:test(T, 'assert_false_number_test')
lutl:test(T, 'assert_false_string_test')
lutl:test(T, 'assert_false_table_test')
lutl:test(T, 'assert_false_userdata_test')
lutl:test(T, 'assert_equal_numbers_test')
lutl:test(T, 'assert_equal_strings_test')
lutl:test(T, 'assert_equal_userdata_test')
lutl:test(T, 'assert_equal_tables_test')
lutl:test(T, 'assert_equal_numbers2_test')
lutl:test(T, 'assert_equal_strings2_test')
lutl:test(T, 'assert_equal_number_string_test')
lutl:test(T, 'assert_equal_number_bool_test')
lutl:test(T, 'assert_equal_nil_false_test')
lutl:test(T, 'assert_nil_nil_test')
lutl:test(T, 'assert_nil_undefined_test')
lutl:test(T, 'assert_nil_false_test')
lutl:test(T, 'assert_nil_number_test')
lutl:test(T, 'assert_nil_string_test')
lutl:test(T, 'assert_nil_table_test')
lutl:test(T, 'assert_nil_userdata_test')
lutl:test(T, 'assert_notnil_nil_test')
lutl:test(T, 'assert_notnil_undefined_test')
lutl:test(T, 'assert_notnil_false_test')
lutl:test(T, 'assert_notnil_number_test')
lutl:test(T, 'assert_notnil_string_test')
lutl:test(T, 'assert_notnil_table_test')
lutl:test(T, 'assert_notnil_userdata_test')
end
| 21.537473 | 53 | 0.747664 |
d03816ec0b0945bc98e9139da6daa3df998bcf13 | 4,617 | cpp | C++ | common/filesystem.cpp | Thalhammer/pve-simple-container | bfe7e72961fe6ae350587c71c71ef1be8e5fd5f5 | [
"MIT"
] | 1 | 2020-05-12T03:17:51.000Z | 2020-05-12T03:17:51.000Z | common/filesystem.cpp | Thalhammer/pve-simple-container | bfe7e72961fe6ae350587c71c71ef1be8e5fd5f5 | [
"MIT"
] | 6 | 2018-09-08T13:00:49.000Z | 2019-02-12T13:43:23.000Z | common/filesystem.cpp | Thalhammer/pve-simple-container | bfe7e72961fe6ae350587c71c71ef1be8e5fd5f5 | [
"MIT"
] | null | null | null | #include "filesystem.h"
#include <cstdlib>
#include <experimental/filesystem>
#include <fstream>
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
#include "string_helper.h"
#include <regex>
namespace fs = std::experimental::filesystem;
namespace pvesc {
namespace common {
std::string filesystem::create_temporary_directory(const std::string& tpl)
{
char buf[tpl.size() + 1];
std::string::traits_type::copy(buf, tpl.c_str(), tpl.size());
buf[tpl.size()] = 0x00;
auto res = mkdtemp(buf);
if(res == nullptr) throw std::runtime_error("Failed to temporary create directory:" + std::to_string(errno));
else return res;
}
void filesystem::delete_directory(const std::string& dir)
{
for(auto& p: fs::directory_iterator(dir)) {
if(p.status().type() == fs::file_type::directory) {
delete_directory(p.path());
} else {
if(!fs::remove(p.path())) throw std::runtime_error("Failed to remove directory");
}
}
if(!fs::remove(dir)) throw std::runtime_error("Failed to remove directory");
}
void filesystem::copy_file(const std::string& source, const std::string& dest) {
fs::path pdest(dest);
if (!fs::is_directory(pdest.parent_path()) && !fs::create_directories(pdest.parent_path())) throw std::runtime_error("Failed to create directory");
if (!fs::copy_file(source, dest)) throw std::runtime_error("Failed to copy file");
}
std::map<std::string, std::string> filesystem::glob_files(const std::string& glob, const std::string& dest) {
auto pos = glob.find('*');
pos = std::min(pos, glob.find('?'));
if(pos != std::string::npos) {
auto regex = glob;
auto base = glob;
pos = glob.substr(0, pos).find_last_of('/');
if(pos == std::string::npos) base = ".";
else {
base = base.substr(0, pos + 1);
}
common::replace(regex, ".", "\\.");
common::replace(regex, "*", "(.*)");
common::replace(regex, "?", "(.)");
std::regex reg("^" + regex + "$");
std::smatch matches;
std::map<std::string, std::string> res;
for(auto& p : fs::recursive_directory_iterator(base)) {
auto path = p.path().string();
if(std::regex_match(path, matches, reg)) {
res.insert({path, matches.format(dest)});
}
}
return res;
} else return {{glob, dest}};
}
void filesystem::create_directories(const std::string& dir) {
if (!fs::is_directory(dir) && !fs::create_directories(dir)) throw std::runtime_error("Failed to create directory");
}
std::string filesystem::current_directory() {
return fs::current_path().string();
}
size_t filesystem::tree_size(const std::string& dir) {
size_t size = 0;
for(auto& p : fs::recursive_directory_iterator(dir)) {
if(p.symlink_status().type() == fs::file_type::regular) {
auto s = fs::file_size(p.path());
size += s;
} else size += 4096;
}
return size;
}
bool filesystem::try_read_file(const std::string& fname, std::string& out) {
if(fs::exists(fname)) {
std::ifstream stream(fname, std::ios::binary);
if(stream) {
out = read_stream(stream);
return true;
}
}
return false;
}
std::string filesystem::read_stream(std::istream& stream) {
std::string res;
while(!stream.eof()) {
char buf[4096];
auto size = stream.read(buf, sizeof(buf)).gcount();
res += std::string(buf, buf + size);
}
return res;
}
std::string filesystem::read_file(const std::string& path) {
std::ifstream stream(path, std::ios::binary);
if(!stream) throw std::runtime_error("Failed to open file");
return read_stream(stream);
}
std::string filesystem::get_home_directory() {
auto homedir = getenv("HOME");
if(homedir == nullptr) {
struct passwd pwd;
struct passwd *result;
int s;
size_t bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
if (bufsize == size_t(-1))
bufsize = 0x4000; // = all zeroes with the 14th bit set (1 << 14)
std::string buf(bufsize, '\0');
s = getpwuid_r(getuid(), &pwd, (char*)buf.data(), buf.size(), &result);
if (result == NULL) {
if (s == 0)
throw std::runtime_error("Failed to get home directory: user not found");
else {
throw std::runtime_error("Failed to get home directory:" + std::to_string(s));
}
}
homedir = result->pw_dir;
}
return homedir;
}
bool filesystem::exists(const std::string& path) {
return fs::exists(path);
}
void filesystem::make_executable(const std::string& path) {
fs::permissions(path, fs::status(path).permissions() | fs::perms::group_exec | fs::perms::others_exec | fs::perms::owner_exec);
}
}
} | 31.408163 | 150 | 0.632012 |
f7d26d75fbebc2a6614e39f936399a27076885a7 | 733 | sql | SQL | CMP/CmpWap/CmpWapExtension/CmpWapDb/dbo/Tables/SQLVersion.sql | grazies/Phoenix | eed35547ed52611f9a1b131cb993f7cd8f424690 | [
"MIT"
] | 38 | 2016-03-01T01:07:55.000Z | 2019-02-23T05:06:10.000Z | CMP/CmpWap/CmpWapExtension/CmpWapDb/dbo/Tables/SQLVersion.sql | grazies/Phoenix | eed35547ed52611f9a1b131cb993f7cd8f424690 | [
"MIT"
] | 12 | 2016-03-02T22:19:03.000Z | 2018-10-17T08:45:17.000Z | CMP/CmpWap/CmpWapExtension/CmpWapDb/dbo/Tables/SQLVersion.sql | grazies/Phoenix | eed35547ed52611f9a1b131cb993f7cd8f424690 | [
"MIT"
] | 10 | 2016-03-05T02:27:56.000Z | 2019-03-27T07:44:03.000Z | CREATE TABLE [dbo].[SQLVersion] (
[SQLVersionId] INT IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (100) NOT NULL,
[Description] NVARCHAR (500) NOT NULL,
[IsActive] BIT NOT NULL,
[CreatedOn] DATETIME CONSTRAINT [DF_SQLVersion_CreatedOn] DEFAULT (getdate()) NOT NULL,
[CreatedBy] NVARCHAR (256) CONSTRAINT [DF_SQLVersion_CreatedBy] DEFAULT (suser_sname()) NOT NULL,
[LastUpdatedOn] DATETIME CONSTRAINT [DF_SQLVersion_LastUpdatedOn] DEFAULT (getdate()) NOT NULL,
[LastUpdatedBy] VARCHAR (50) CONSTRAINT [DF_SQLVersion_LastUpdatedBy] DEFAULT (suser_sname()) NOT NULL,
CONSTRAINT [PK_SQLVersion] PRIMARY KEY CLUSTERED ([SQLVersionId] ASC)
);
| 56.384615 | 109 | 0.673943 |
c3c59824cad122aaa17e03f09a19d6677339fb6c | 3,515 | cs | C# | src/1.Framework/Vita/4.Internals/Data/Linq/Translation/ExpressionMutatorExtensions.cs | rivantsov/vita | d164701816b25dd67586c56b736c30a2c43bd767 | [
"MIT"
] | 66 | 2016-05-16T23:12:44.000Z | 2021-03-06T13:12:50.000Z | src/1.Framework/Vita/4.Internals/Data/Linq/Translation/ExpressionMutatorExtensions.cs | rivantsov/vita | d164701816b25dd67586c56b736c30a2c43bd767 | [
"MIT"
] | 207 | 2016-05-15T17:33:56.000Z | 2022-03-13T23:56:11.000Z | src/1.Framework/Vita/4.Internals/Data/Linq/Translation/ExpressionMutatorExtensions.cs | rivantsov/vita | d164701816b25dd67586c56b736c30a2c43bd767 | [
"MIT"
] | 20 | 2016-07-06T13:50:06.000Z | 2020-10-05T07:23:42.000Z |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Vita.Data.Linq.Translation.Expressions;
namespace Vita.Data.Linq.Translation {
internal static class ExpressionMutatorExtensions
{
/// <summary>
/// Enumerates all subexpressions related to this one
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
public static IList<Expression> GetOperands(this Expression expression)
{
var result = ExpressionMutator.GetOperands(expression);
return result;
}
public static T ChangeOperands<T>(this T expression, IList<Expression> operands, IEnumerable<Expression> oldOperands = null)
where T : Expression
{
if (!HaveOperandsChanged(operands, oldOperands))
return expression;
var mutableExpression = expression as IMutableExpression;
if (mutableExpression != null)
return (T)mutableExpression.Mutate(operands);
// RI: new version
var result = (T) ExpressionMutator.Mutate(expression, operands);
return result;
// return (T)ExpressionMutatorFactory.GetMutator(expression).Mutate(operands);
}
/// <summary>
/// Determines if operands have changed for a given expression
/// </summary>
private static bool HaveOperandsChanged(IList<Expression> operands, IEnumerable<Expression> oldOperands = null) {
if (oldOperands == null)
return true;
var oldList = oldOperands.ToList();
if (operands.Count != oldList.Count)
return true;
for (int operandIndex = 0; operandIndex < operands.Count; operandIndex++)
if (operands[operandIndex] != oldList[operandIndex])
return true;
return false;
}
/// <summary>
/// Returns the expression result
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
public static object Evaluate(this Expression expression)
{
/*
var executableExpression = expression as IExecutableExpression;
if (executableExpression != null)
return executableExpression.Execute();
*/
var lambda = Expression.Lambda(expression);
var compiled = lambda.Compile();
var value = compiled.DynamicInvoke();
return value;
}
/// <summary>
/// Down-top pattern analysis.
/// </summary>
/// <param name="expression">The original expression</param>
/// <param name="analyzer"></param>
/// <returns>A new QueryExpression or the original one</returns>
public static Expression Recurse(this Expression expression, Func<Expression, Expression> analyzer)
{
var oldOperands = GetOperands(expression);
var newOperands = new List<Expression>();
// first, work on children (down)
foreach (var operand in oldOperands)
{
if (operand != null)
newOperands.Add(Recurse(operand, analyzer));
else
newOperands.Add(null);
}
// then on expression itself (top)
return analyzer(expression.ChangeOperands(newOperands, oldOperands));
}
}
} | 38.206522 | 132 | 0.586344 |
e222e3ee992c49276a838ad051cb0ebb5f371a0d | 1,618 | py | Python | display_ssd1306.py | mkvenkit/simple_audio_pi | 826d8ef9adfd480ac7676b34e10b8027441fe79c | [
"MIT"
] | 9 | 2021-02-20T02:54:35.000Z | 2022-02-15T16:36:49.000Z | display_ssd1306.py | mkvenkit/simple_audio_pi | 826d8ef9adfd480ac7676b34e10b8027441fe79c | [
"MIT"
] | null | null | null | display_ssd1306.py | mkvenkit/simple_audio_pi | 826d8ef9adfd480ac7676b34e10b8027441fe79c | [
"MIT"
] | 1 | 2021-09-02T09:58:52.000Z | 2021-09-02T09:58:52.000Z | """
display_ssd1306.py
Helper class for Adafruit_SSD1306. Displays text on 128x32 OLED display.
Author: Mahesh Venkitachalam
Website: electronut.in
"""
import Adafruit_GPIO.SPI as SPI
import Adafruit_SSD1306
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
class SSD1306_Display:
"""Helper class to use OLED display"""
def __init__(self):
# 128x32 display with hardware I2C:
self.disp = Adafruit_SSD1306.SSD1306_128_32(rst=None)
# Initialize library.
self.disp.begin()
# Clear display.
self.disp.clear()
self.disp.display()
# Create blank image for drawing.
# Make sure to create image with mode '1' for 1-bit color.
self.image = Image.new('1', (self.disp.width, self.disp.height))
# Get drawing object to draw on image.
self.draw = ImageDraw.Draw(self.image)
# Draw a black filled box to clear the image.
self.draw.rectangle((0,0,self.disp.width,self.disp.height), outline=0, fill=0)
# Load default font.
self.font = ImageFont.load_default()
def show_txt(self, x, y, str_data, clear_display):
"""display given text"""
# clear old data if flag set
if clear_display:
# Draw a black filled box to clear the image.
self.draw.rectangle((0,0,self.disp.width, self.disp.height),
outline=0, fill=0)
self.draw.text((x,y), str_data, font=self.font, fill=255)
# Display image.
self.disp.image(self.image)
self.disp.display()
| 33.020408 | 86 | 0.630408 |
472ef5b0dd43bdefdae7d704c4db60a42935a774 | 2,751 | swift | Swift | Templates/Xcode/Default.xctemplate/___FILEBASENAME___Module.swift | viaszkadi/VIPERA | 6a9ebfd85454c3d26b59b4c4ecf9031673461e57 | [
"WTFPL"
] | null | null | null | Templates/Xcode/Default.xctemplate/___FILEBASENAME___Module.swift | viaszkadi/VIPERA | 6a9ebfd85454c3d26b59b4c4ecf9031673461e57 | [
"WTFPL"
] | null | null | null | Templates/Xcode/Default.xctemplate/___FILEBASENAME___Module.swift | viaszkadi/VIPERA | 6a9ebfd85454c3d26b59b4c4ecf9031673461e57 | [
"WTFPL"
] | null | null | null | //
// ___FILENAME___
// ___PROJECTNAME___
//
// Created ___FULLUSERNAME___ on ___DATE___.
// Copyright © ___YEAR___ ___ORGANIZATIONNAME___. All rights reserved.
//
import Foundation
import UIKit
// MARK: - router
protocol ___VARIABLE_MODULE_NAME___RouterPresenterInterface: RouterPresenterInterface {
}
protocol ___VARIABLE_MODULE_NAME___RouterInterface: RouterInterface &
___VARIABLE_MODULE_NAME___RouterPresenterInterface {
var presenter: ___VARIABLE_MODULE_NAME___PresenterRouterInterface! { get }
}
// MARK: - interactor
protocol ___VARIABLE_MODULE_NAME___InteractorPresenterInterface: InteractorPresenterInterface {
}
protocol ___VARIABLE_MODULE_NAME___InteractorInterface: InteractorInterface &
___VARIABLE_MODULE_NAME___InteractorPresenterInterface {
var presenter: ___VARIABLE_MODULE_NAME___PresenterInteractorInterface! { get }
}
// MARK: - presenter
protocol ___VARIABLE_MODULE_NAME___PresenterRouterInterface: PresenterRouterInterface {
}
protocol ___VARIABLE_MODULE_NAME___PresenterInteractorInterface: PresenterInteractorInterface {
}
protocol ___VARIABLE_MODULE_NAME___PresenterViewInterface: PresenterViewInterface {
}
protocol ___VARIABLE_MODULE_NAME___PresenterInterface: PresenterInterface &
___VARIABLE_MODULE_NAME___PresenterRouterInterface &
___VARIABLE_MODULE_NAME___PresenterInteractorInterface &
___VARIABLE_MODULE_NAME___PresenterViewInterface {
var router: ___VARIABLE_MODULE_NAME___RouterPresenterInterface! { get }
var interactor: ___VARIABLE_MODULE_NAME___InteractorPresenterInterface! { get }
var view: ___VARIABLE_MODULE_NAME___ViewPresenterInterface! { get }
}
// MARK: - view
protocol ___VARIABLE_MODULE_NAME___ViewPresenterInterface: ViewPresenterInterface {
}
protocol ___VARIABLE_MODULE_NAME___ViewInterface: ViewInterface &
___VARIABLE_MODULE_NAME___ViewPresenterInterface {
var presenter: ___VARIABLE_MODULE_NAME___PresenterViewInterface! { get }
}
// MARK: - module builder
final class ___VARIABLE_MODULE_NAME___Module: ModuleInterface {
func build() -> UIViewController {
let view = ___VARIABLE_MODULE_NAME___View()
let interactor = ___VARIABLE_MODULE_NAME___Interactor()
let presenter = ___VARIABLE_MODULE_NAME___Presenter()
let router = ___VARIABLE_MODULE_NAME___Router()
view.presenter = presenter
presenter.interactor = interactor
presenter.view = view
presenter.router = router
interactor.presenter = presenter
router.presenter = presenter
return view
}
}
| 28.360825 | 95 | 0.755725 |
e280c8817629d452d98a7ce7731e4614c914e1a5 | 1,324 | py | Python | dbdaora/sorted_set/entity.py | dutradda/sqldataclass | 5c87a3818e9d736bbf5e1438edc5929a2f5acd3f | [
"MIT"
] | 21 | 2019-10-14T14:33:33.000Z | 2022-02-11T04:43:07.000Z | dbdaora/sorted_set/entity.py | dutradda/sqldataclass | 5c87a3818e9d736bbf5e1438edc5929a2f5acd3f | [
"MIT"
] | null | null | null | dbdaora/sorted_set/entity.py | dutradda/sqldataclass | 5c87a3818e9d736bbf5e1438edc5929a2f5acd3f | [
"MIT"
] | 1 | 2019-09-29T23:51:44.000Z | 2019-09-29T23:51:44.000Z | from typing import ( # type: ignore
Any,
Dict,
Optional,
Protocol,
Sequence,
Tuple,
Type,
TypeVar,
TypedDict,
Union,
_TypedDictMeta,
)
from dbdaora.data_sources.memory import RangeOutput
from dbdaora.entity import init_subclass
SortedSetInput = Sequence[Union[str, float]]
SortedSetData = Union[RangeOutput, SortedSetInput]
class SortedSetEntityProtocol(Protocol):
data: SortedSetData
max_size: Optional[int] = None
def __init__(
self,
*,
data: SortedSetData,
max_size: Optional[int] = None,
**kwargs: Any,
):
...
class SortedSetEntity(SortedSetEntityProtocol):
data: SortedSetData
max_size: Optional[int] = None
def __init_subclass__(cls) -> None:
init_subclass(cls, (SortedSetEntity,))
class SortedSetDictEntityMeta(_TypedDictMeta): # type: ignore
def __init__(
cls, name: str, bases: Tuple[Type[Any], ...], attrs: Dict[str, Any]
):
super().__init__(name, bases, attrs)
init_subclass(cls, bases)
class SortedSetDictEntity(TypedDict, metaclass=SortedSetDictEntityMeta):
data: SortedSetData
max_size: Optional[int]
SortedSetEntityHint = TypeVar(
'SortedSetEntityHint',
bound=Union[SortedSetEntityProtocol, SortedSetDictEntity],
)
| 21.015873 | 75 | 0.674471 |
38aaea97676487b75e7c46fe9f8c53797c28b123 | 933 | php | PHP | tests/EventObjectStorePerformanceTestIntegration.php | mad654/php-event-store | 6c445cfa61fe69b248f395db4434dce551e8e69d | [
"MIT"
] | null | null | null | tests/EventObjectStorePerformanceTestIntegration.php | mad654/php-event-store | 6c445cfa61fe69b248f395db4434dce551e8e69d | [
"MIT"
] | null | null | null | tests/EventObjectStorePerformanceTestIntegration.php | mad654/php-event-store | 6c445cfa61fe69b248f395db4434dce551e8e69d | [
"MIT"
] | null | null | null | <?php
namespace mad654\eventstore;
use mad654\eventstore\example\LightSwitch;
use mad654\eventstore\FileEventStream\FileEventStreamFactory;
use mad654\eventstore\TestCase\FileTestCase;
class EventObjectStorePerformanceTestIntegration extends FileTestCase
{
/**
* @test
*/
public function get_singleSubjectWith10000Events_loadsIn100ms()
{
$id = StringSubjectId::fromString('foo');
$store = new EventSourcedObjectStore(new FileEventStreamFactory($this->rootDirPath()));
$subject = new LightSwitch($id);
$store->attach($subject);
foreach (range(1, 10000) as $i) {
$subject->switchOn($i);
}
$diff = take_time(function () use ($id) {
$store = new EventSourcedObjectStore(new FileEventStreamFactory($this->rootDirPath()));
$store->get($id);
});
$this->assertlessThanOrEqual(100, $diff, $diff);
}
} | 27.441176 | 99 | 0.654877 |
d7069b51f7b218bc00bb33623b559206246d0ce0 | 604 | kt | Kotlin | src/main/kotlin/io/dkozak/eobaly/controller/AuthenticationController.kt | d-kozak/webpage-parser | f1eb7334dfae0d8207fad176a87da9c98019cd4b | [
"MIT"
] | null | null | null | src/main/kotlin/io/dkozak/eobaly/controller/AuthenticationController.kt | d-kozak/webpage-parser | f1eb7334dfae0d8207fad176a87da9c98019cd4b | [
"MIT"
] | null | null | null | src/main/kotlin/io/dkozak/eobaly/controller/AuthenticationController.kt | d-kozak/webpage-parser | f1eb7334dfae0d8207fad176a87da9c98019cd4b | [
"MIT"
] | null | null | null | package io.dkozak.eobaly.controller
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.ui.set
import org.springframework.web.bind.annotation.GetMapping
@Controller
class AuthenticationController {
@GetMapping("/login")
fun login() = "login.html"
@GetMapping("/login-error")
fun loginError(model: Model): String {
model["loginError"] = true
return "login.html"
}
@GetMapping("/login-logout")
fun logout(model: Model): String {
model["logout"] = true
return "login.html"
}
} | 22.37037 | 57 | 0.688742 |
c99acd19a258611205f41343c5551d68811e0dda | 406 | ts | TypeScript | test.ts | satyarohith/deno_local_file_fetch | a464f5615be68be47d05114a0f5b32ccb2c26038 | [
"MIT"
] | null | null | null | test.ts | satyarohith/deno_local_file_fetch | a464f5615be68be47d05114a0f5b32ccb2c26038 | [
"MIT"
] | null | null | null | test.ts | satyarohith/deno_local_file_fetch | a464f5615be68be47d05114a0f5b32ccb2c26038 | [
"MIT"
] | null | null | null | import "./mod.ts";
import { assertEquals } from "https://deno.land/[email protected]/testing/asserts.ts";
Deno.test("fetch local file URL", async () => {
const req = await fetch(new URL("./fixtures/test.json", import.meta.url));
assertEquals(req.status, 200);
assertEquals(req.headers.get("content-type"), "application/json");
const json = await req.json();
assertEquals(json, { hello: "world" });
});
| 36.909091 | 79 | 0.674877 |
7f509aa534cc771063d24260617bc2aae5457078 | 1,983 | php | PHP | src/Event/ProophVersionUpcastingMessageFactory.php | proophsoftware/mongo-read-event-store | 565cf8d1d7a9151e6819510fbac062a4f4dda073 | [
"BSD-3-Clause"
] | 2 | 2017-04-28T20:11:46.000Z | 2017-04-28T20:23:06.000Z | src/Event/ProophVersionUpcastingMessageFactory.php | proophsoftware/mongo-read-event-store | 565cf8d1d7a9151e6819510fbac062a4f4dda073 | [
"BSD-3-Clause"
] | null | null | null | src/Event/ProophVersionUpcastingMessageFactory.php | proophsoftware/mongo-read-event-store | 565cf8d1d7a9151e6819510fbac062a4f4dda073 | [
"BSD-3-Clause"
] | null | null | null | <?php
/**
* This file is part of the proophsoftware/mongo-read-event-store.
* (c) 2017 prooph software GmbH <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Prooph\ReadOnlyMongoEventStore\Event;
use Prooph\Common\Messaging\Message;
use Prooph\Common\Messaging\MessageFactory;
use Ramsey\Uuid\Uuid;
final class ProophVersionUpcastingMessageFactory implements MessageFactory
{
/**
* {@inheritdoc}
*/
public function createMessageFromArray(string $messageName, array $messageData): Message
{
if (! isset($messageData['message_name'])) {
$messageData['message_name'] = $messageName;
}
if (! isset($messageData['uuid'])) {
$messageData['uuid'] = Uuid::uuid4();
}
if (! isset($messageData['created_at'])) {
$time = (string) microtime(true);
if (false === strpos($time, '.')) {
$time .= '.0000';
}
$messageData['created_at'] = \DateTimeImmutable::createFromFormat('U.u', $time);
}
if (! isset($messageData['metadata'])) {
$messageData['metadata'] = [];
}
//Upcast to prooph/event-store v7 format
if (isset($messageData['version'])) {
$messageData['metadata']['_aggregate_version'] = $messageData['version'];
unset($messageData['version']);
}
if (isset($messageData['aggregate_id'])) {
$messageData['metadata']['_aggregate_id'] = $messageData['aggregate_id'];
unset($messageData['aggregate_id']);
}
if (isset($messageData['aggregate_type'])) {
$messageData['metadata']['_aggregate_type'] = $messageData['aggregate_type'];
unset($messageData['aggregate_type']);
}
return GenericEvent::fromArray($messageData);
}
}
| 31.47619 | 92 | 0.603127 |
ccd4c15fa91d108adaf2957c818e96e08c4a4d60 | 742 | rb | Ruby | app/models/ban.rb | Yaze/moebooru | 1c1230b12ba9e7386af5e4c7c457094c9eee0d17 | [
"0BSD"
] | 1 | 2015-02-05T19:43:45.000Z | 2015-02-05T19:43:45.000Z | app/models/ban.rb | neplus/moebooru | bfd91cf63c8e9421354dce46378dd62fe90ab0b2 | [
"0BSD"
] | null | null | null | app/models/ban.rb | neplus/moebooru | bfd91cf63c8e9421354dce46378dd62fe90ab0b2 | [
"0BSD"
] | null | null | null | class Ban < ActiveRecord::Base
before_create :save_level
after_create :save_to_record
after_create :update_level
after_destroy :restore_level
def restore_level
User.find(user_id).update_attribute(:level, old_level)
end
def save_level
self.old_level = User.find(user_id).level
end
def update_level
user = User.find(user_id)
user.level = CONFIG["user_levels"]["Blocked"]
user.save
end
def save_to_record
UserRecord.create(:user_id => self.user_id, :reported_by => self.banned_by, :is_positive => false, :body => "Blocked: #{self.reason}")
end
def duration=(dur)
self.expires_at = (dur.to_f * 60*60*24).seconds.from_now
@duration = dur
end
def duration
@duration
end
end
| 21.823529 | 138 | 0.706199 |
b05367807d977b790052d5901c99cdeee135137c | 97 | py | Python | lsunmodel/__init__.py | Hourout/lsunmodel | 176dcf0a97016830841589c51443d0b48ac90dcd | [
"Apache-2.0"
] | null | null | null | lsunmodel/__init__.py | Hourout/lsunmodel | 176dcf0a97016830841589c51443d0b48ac90dcd | [
"Apache-2.0"
] | null | null | null | lsunmodel/__init__.py | Hourout/lsunmodel | 176dcf0a97016830841589c51443d0b48ac90dcd | [
"Apache-2.0"
] | null | null | null | # from lsunmodel import datasets
# from lsunmodel import trainer
from lsunmodel import predictor
| 24.25 | 32 | 0.835052 |
b36a11a52537268fd878e410e54cd635db94dd2d | 3,980 | py | Python | codes/s3-3_HH.py | HiroshiARAKI/snn_from_scratch | e26e7ce2bbebaa35ad3e325c09f05c334d753049 | [
"MIT"
] | 7 | 2021-01-30T16:04:32.000Z | 2022-02-22T05:06:21.000Z | codes/s3-3_HH.py | HiroshiARAKI/snn_from_scratch | e26e7ce2bbebaa35ad3e325c09f05c334d753049 | [
"MIT"
] | null | null | null | codes/s3-3_HH.py | HiroshiARAKI/snn_from_scratch | e26e7ce2bbebaa35ad3e325c09f05c334d753049 | [
"MIT"
] | 2 | 2021-06-10T08:18:11.000Z | 2021-09-17T08:25:26.000Z | """
ゼロから学ぶスパイキングニューラルネットワーク
- Spiking Neural Networks from Scratch
Copyright (c) 2020 HiroshiARAKI. All Rights Reserved.
"""
import numpy as np
import matplotlib.pyplot as plt
class HodgkinHuxley:
def __init__(self, time, dt, rest=-65., Cm=1.0, gNa=120., gK=36., gl=0.3, ENa=50., EK=-77., El=-54.387):
"""
Initialize Neuron parameters
:param time: experimental time
:param dt: time step
:param rest: resting potential
:param Cm: membrane capacity
:param gNa: Na+ channel conductance
:param gK: K+ channel conductance
:param gl: other (Cl) channel conductance
:param ENa: Na+ equilibrium potential
:param EK: K+ equilibrium potential
:param El: other (Cl) equilibrium potentials
"""
self.time = time
self.dt = dt
self.rest = rest
self.Cm = Cm
self.gNa = gNa
self.gK = gK
self.gl = gl
self.ENa = ENa
self.EK = EK
self.El = El
def calc(self, i):
""" compute membrane potential """
# initialize parameters
v = self.rest
n = 0.32
m = 0.05
h = 0.6
v_monitor = []
n_monitor = []
m_monitor = []
h_monitor = []
time = int(self.time / self.dt)
# update time
for t in range(time):
# calc channel gating kinetics
n += self.dn(v, n)
m += self.dm(v, m)
h += self.dh(v, h)
# calc tiny membrane potential
dv = (i[t] -
self.gK * n**4 * (v - self.EK) - # K+ current
self.gNa * m**3 * h * (v - self.ENa) - # Na+ current
self.gl * (v - self.El)) / self.Cm # other current
# calc new membrane potential
v += dv * self.dt
# record
v_monitor.append(v)
n_monitor.append(n)
m_monitor.append(m)
h_monitor.append(h)
return v_monitor, n_monitor, m_monitor, h_monitor
def dn(self, v, n):
return (self.alpha_n(v) * (1 - n) - self.beta_n(v) * n) * self.dt
def dm(self, v, m):
return (self.alpha_m(v) * (1 - m) - self.beta_m(v) * m) * self.dt
def dh(self, v, h):
return (self.alpha_h(v) * (1 - h) - self.beta_h(v) * h) * self.dt
def alpha_n(self, v):
return 0.01 * (10 - (v - self.rest)) / (np.exp((10 - (v - self.rest))/10) - 1)
def alpha_m(self, v):
return 0.1 * (25 - (v - self.rest)) / (np.exp((25 - (v - self.rest))/10) - 1)
def alpha_h(self, v):
return 0.07 * np.exp(-(v - self.rest) / 20)
def beta_n(self, v):
return 0.125 * np.exp(-(v - self.rest) / 80)
def beta_m(self, v):
return 4 * np.exp(-(v - self.rest) / 18)
def beta_h(self, v):
return 1 / (np.exp((30 - (v - self.rest))/10) + 1)
if __name__ == '__main__':
# init experimental time and time-step
time = 300 # 実験時間 (観測時間)
dt = 2**-4 # 時間分解能 (HHモデルは結構小さめでないと上手く計算できない)
# Hodgkin-Huxley Neuron
neuron = HodgkinHuxley(time, dt)
# 入力データ (面倒臭いので適当な矩形波とノイズを合成して作った)
input_data = np.sin(0.5 * np.arange(0, time, dt))
input_data = np.where(input_data > 0, 20, 0) + 10 * np.random.rand(int(time/dt))
input_data_2 = np.cos(0.4 * np.arange(0, time, dt) + 0.5)
input_data_2 = np.where(input_data_2 > 0, 10, 0)
input_data += input_data_2
# 膜電位などを計算
v, m, n, h = neuron.calc(input_data)
# plot
plt.figure(figsize=(12, 6))
x = np.arange(0, time, dt)
plt.subplot(3, 1, 1)
plt.plot(x, input_data)
plt.ylabel('I [μA/cm2]')
plt.subplot(3, 1, 2)
plt.plot(x, v)
plt.ylabel('V [mV]')
plt.subplot(3, 1, 3)
plt.plot(x, n, label='n')
plt.plot(x, m, label='m')
plt.plot(x, h, label='h')
plt.xlabel('time [ms]')
plt.ylabel('Conductance param')
plt.legend()
plt.show()
| 27.448276 | 108 | 0.526131 |
b41b0cea19e1f40177d1b6e1ba18fc98e6dfd42c | 6,054 | rs | Rust | components/sup/src/package/updater.rs | rrxtns/habitat | 0ed0a22d8906cc7e55ca1bc2dbed7c6d4045587d | [
"Apache-2.0"
] | null | null | null | components/sup/src/package/updater.rs | rrxtns/habitat | 0ed0a22d8906cc7e55ca1bc2dbed7c6d4045587d | [
"Apache-2.0"
] | 2 | 2021-05-20T23:44:08.000Z | 2021-09-28T05:46:05.000Z | components/sup/src/package/updater.rs | rrxtns/habitat | 0ed0a22d8906cc7e55ca1bc2dbed7c6d4045587d | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2016 Chef Software Inc. and/or applicable contributors
//
// 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.
use std::sync::{Arc, RwLock};
use std::path::Path;
use depot_client::Client;
use common::ui::UI;
use hcore::crypto::default_cache_key_path;
use hcore::fs::{CACHE_ARTIFACT_PATH, FS_ROOT_PATH};
use hcore::package::PackageIdent;
use wonder;
use wonder::actor::{GenServer, InitResult, HandleResult, ActorSender, ActorResult};
use {PRODUCT, VERSION};
use error::SupError;
use package::Package;
const TIMEOUT_MS: u64 = 60_000;
pub type PackageUpdaterActor = wonder::actor::Actor<UpdaterMessage>;
pub struct PackageUpdater;
impl PackageUpdater {
pub fn start(url: &str, package: Arc<RwLock<Package>>) -> PackageUpdaterActor {
let state = UpdaterState::new(url.to_string(), package);
wonder::actor::Builder::new(PackageUpdater)
.name("package-updater".to_string())
.start(state)
.unwrap()
}
/// Signal a package updater to transition it's status from `stopped` to `running`. An updater
/// has the `stopped` status after it has found and notified the main thread of an updated
/// package.
pub fn run(actor: &PackageUpdaterActor) -> ActorResult<()> {
actor.cast(UpdaterMessage::Run)
}
}
pub struct UpdaterState {
pub depot: String,
pub package: Arc<RwLock<Package>>,
pub status: UpdaterStatus,
}
impl UpdaterState {
pub fn new(depot: String, package: Arc<RwLock<Package>>) -> Self {
UpdaterState {
depot: depot,
package: package,
status: UpdaterStatus::Stopped,
}
}
}
#[derive(Debug)]
pub enum UpdaterMessage {
Ok,
Run,
Stop,
Update(Package),
}
pub enum UpdaterStatus {
Running,
Stopped,
}
impl GenServer for PackageUpdater {
type T = UpdaterMessage;
type S = UpdaterState;
type E = SupError;
fn init(&self, _tx: &ActorSender<Self::T>, state: &mut Self::S) -> InitResult<Self::E> {
state.status = UpdaterStatus::Running;
Ok(Some(TIMEOUT_MS))
}
fn handle_timeout(&self,
tx: &ActorSender<Self::T>,
_me: &ActorSender<Self::T>,
state: &mut Self::S)
-> HandleResult<Self::T> {
let package = state.package.read().unwrap();
// JW TODO: Store and use the version if the package was started with a specific version.
// This will allow an operator to lock to a version and receive security updates
// in the form of release updates for a package.
let ident = PackageIdent::new(package.origin.clone(), package.name.clone(), None, None);
let depot_client = match Client::new(&state.depot, PRODUCT, VERSION, None) {
Ok(client) => client,
Err(e) => {
debug!("Failed to create HTTP client: {:?}", e);
return HandleResult::NoReply(Some(TIMEOUT_MS));
}
};
match depot_client.show_package(ident) {
Ok(remote) => {
let latest_ident: PackageIdent = remote.get_ident().clone().into();
if &latest_ident > package.ident() {
let mut ui = UI::default();
match depot_client.fetch_package(latest_ident.clone(),
&Path::new(FS_ROOT_PATH)
.join(CACHE_ARTIFACT_PATH),
ui.progress()) {
Ok(archive) => {
debug!("Updater downloaded new package to {:?}", archive);
// JW TODO: actually handle verify and unpack results
archive.verify(&default_cache_key_path(None)).unwrap();
archive.unpack(None).unwrap();
let latest_package = Package::load(&latest_ident, None).unwrap();
state.status = UpdaterStatus::Stopped;
let msg = wonder::actor::Message::Cast(UpdaterMessage::Update(latest_package));
tx.send(msg).unwrap();
HandleResult::NoReply(None)
}
Err(e) => {
debug!("Failed to download package: {:?}", e);
HandleResult::NoReply(Some(TIMEOUT_MS))
}
}
} else {
debug!("Package found is not newer than ours");
HandleResult::NoReply(Some(TIMEOUT_MS))
}
}
Err(e) => {
debug!("Updater failed to get latest package: {:?}", e);
HandleResult::NoReply(Some(TIMEOUT_MS))
}
}
}
fn handle_cast(&self,
msg: Self::T,
_tx: &ActorSender<Self::T>,
_me: &ActorSender<Self::T>,
state: &mut Self::S)
-> HandleResult<Self::T> {
match msg {
UpdaterMessage::Run => HandleResult::NoReply(Some(TIMEOUT_MS)),
_ => {
match state.status {
UpdaterStatus::Running => HandleResult::NoReply(Some(TIMEOUT_MS)),
UpdaterStatus::Stopped => HandleResult::NoReply(None),
}
}
}
}
}
| 37.141104 | 107 | 0.546911 |
d83dcb1675af31ccc59439db66fa3d97be74016a | 540 | rb | Ruby | lib/administrate_collapsible_navigation.rb | mrysav/administrate_collapsible_navigation | e09894fc6c4adec12b84d1365172b9c480f6f314 | [
"MIT"
] | 1 | 2020-03-24T13:40:16.000Z | 2020-03-24T13:40:16.000Z | lib/administrate_collapsible_navigation.rb | mrysav/administrate_collapsible_navigation | e09894fc6c4adec12b84d1365172b9c480f6f314 | [
"MIT"
] | 7 | 2019-03-24T23:52:56.000Z | 2021-05-27T01:14:04.000Z | lib/administrate_collapsible_navigation.rb | mrysav/administrate_collapsible_navigation | e09894fc6c4adec12b84d1365172b9c480f6f314 | [
"MIT"
] | 2 | 2020-03-24T20:27:03.000Z | 2021-05-27T00:17:58.000Z | require 'administrate_collapsible_navigation/version'
require 'administrate/engine'
module AdministrateCollapsibleNavigation
class Engine < ::Rails::Engine
initializer "administrate_collapsible_navigation.assets.precompile" do |app|
app.config.assets.precompile += %w( menu_open.png menu_closed.png )
end
Administrate::Engine.add_javascript(
'administrate_collapsible_navigation/application'
)
Administrate::Engine.add_stylesheet(
'administrate_collapsible_navigation/application'
)
end
end
| 28.421053 | 80 | 0.775926 |
dbf9fd7a0551ac94c5f54d4eae43b36c79d2fcd3 | 28,041 | php | PHP | application/models/discount/Discount_rule_model.php | sutouch08/wms | 42d4b3fc459837ecd9d0ca0c32a0043061b3511f | [
"MIT"
] | null | null | null | application/models/discount/Discount_rule_model.php | sutouch08/wms | 42d4b3fc459837ecd9d0ca0c32a0043061b3511f | [
"MIT"
] | null | null | null | application/models/discount/Discount_rule_model.php | sutouch08/wms | 42d4b3fc459837ecd9d0ca0c32a0043061b3511f | [
"MIT"
] | null | null | null | <?php
class Discount_rule_model extends CI_Model
{
public function __construct()
{
parent::__construct();
}
public function add(array $ds = array())
{
$rs = $this->db->insert('discount_rule', $ds);
if($rs)
{
return $this->db->insert_id();
}
return FALSE;
}
public function update($id, array $ds = array())
{
if(!empty($ds))
{
return $this->db->where('id', $id)->update('discount_rule', $ds);
}
return FALSE;
}
public function get($id)
{
$rs = $this->db->where('id', $id)->get('discount_rule');
if($rs->num_rows() == 1)
{
return $rs->row();
}
return array();
}
public function get_policy_id($id)
{
$rs = $this->db->select('id_policy')->where('id', $id)->get('discount_rule');
if($rs->num_rows() === 1)
{
return $rs->row()->id_policy;
}
return NULL;
}
/*
|----------------------------------
| BEGIN ใช้สำหรับแสดงรายละเอียดในหน้าพิมพ์
|----------------------------------
*/
public function getCustomerRuleList($id)
{
$qr = "SELECT cs.code, cs.name FROM discount_rule_customer AS cr ";
$qr .= "JOIN customers AS cs ON cr.customer_code = cs.code ";
$qr .= "WHERE cr.id_rule = ".$id;
return $this->db->query($qr);
}
public function getCustomerGroupRule($id)
{
$qr = "SELECT cs.code, cs.name FROM discount_rule_customer_group AS cr ";
$qr .= "JOIN customer_group AS cs ON cr.group_code = cs.code ";
$qr .= "WHERE id_rule = ".$id;
return $this->db->query($qr);
}
public function getCustomerTypeRule($id)
{
$qr = "SELECT cs.code, cs.code, cs.name FROM discount_rule_customer_type AS cr ";
$qr .= "JOIN customer_type AS cs ON cr.type_code = cs.code ";
$qr .= "WHERE id_rule = ".$id;
return $this->db->query($qr);
}
public function getCustomerKindRule($id)
{
$qr = "SELECT cs.code, cs.code, cs.name FROM discount_rule_customer_kind AS cr ";
$qr .= "JOIN customer_kind AS cs ON cr.kind_code = cs.code ";
$qr .= "WHERE id_rule = ".$id;
return $this->db->query($qr);
}
public function getCustomerAreaRule($id)
{
$qr = "SELECT cs.code, cs.code, cs.name FROM discount_rule_customer_area AS cr ";
$qr .= "JOIN customer_area AS cs ON cr.area_code = cs.code ";
$qr .= "WHERE id_rule = ".$id;
return $this->db->query($qr);
}
public function getCustomerClassRule($id)
{
$qr = "SELECT cs.code, cs.code, cs.name FROM discount_rule_customer_class AS cr ";
$qr .= "JOIN customer_class AS cs ON cr.class_code = cs.code ";
$qr .= "WHERE id_rule = ".$id;
return $this->db->query($qr);
}
public function getProductStyleRule($id)
{
$qr = "SELECT ps.code FROM discount_rule_product_style AS sr ";
$qr .= "JOIN product_style AS ps ON sr.style_code = ps.code ";
$qr .= "WHERE id_rule = ".$id;
return $this->db->query($qr);
}
public function getProductGroupRule($id)
{
$qr = "SELECT ps.code, ps.name FROM discount_rule_product_group AS sr ";
$qr .= "JOIN product_group AS ps ON sr.group_code = ps.code ";
$qr .= "WHERE id_rule = ".$id;
return $this->db->query($qr);
}
public function getProductSubGroupRule($id)
{
$qr = "SELECT ps.code, ps.name FROM discount_rule_product_sub_group AS sr ";
$qr .= "JOIN product_sub_group AS ps ON sr.sub_group_code = ps.code ";
$qr .= "WHERE id_rule = ".$id;
return $this->db->query($qr);
}
public function getProductTypeRule($id)
{
$qr = "SELECT ps.code, ps.name FROM discount_rule_product_type AS sr ";
$qr .= "JOIN product_type AS ps ON sr.type_code = ps.code ";
$qr .= "WHERE id_rule = ".$id;
return $this->db->query($qr);
}
public function getProductKindRule($id)
{
$qr = "SELECT ps.code, ps.name FROM discount_rule_product_kind AS sr ";
$qr .= "JOIN product_kind AS ps ON sr.kind_code = ps.code ";
$qr .= "WHERE id_rule = ".$id;
return $this->db->query($qr);
}
public function getProductCategoryRule($id)
{
$qr = "SELECT ps.code, ps.name FROM discount_rule_product_category AS sr ";
$qr .= "JOIN product_category AS ps ON sr.category_code = ps.code ";
$qr .= "WHERE id_rule = ".$id;
return $this->db->query($qr);
}
public function getProductBrandRule($id)
{
$qr = "SELECT ps.code, ps.name FROM discount_rule_product_brand AS sr ";
$qr .= "JOIN product_brand AS ps ON sr.brand_code = ps.code ";
$qr .= "WHERE id_rule = ".$id;
return $this->db->query($qr);
}
public function getProductYearRule($id)
{
$qr = "SELECT year FROM discount_rule_product_year WHERE id_rule = ".$id;
return $this->db->query($qr);
}
public function getChannelsRule($id)
{
$qr = "SELECT cn.name FROM discount_rule_channels AS cr ";
$qr .= "JOIN channels AS cn ON cr.channels_code = cn.code ";
$qr .= "WHERE id_rule = ".$id;
return $this->db->query($qr);
}
public function getPaymentRule($id)
{
$qr = "SELECT cn.name FROM discount_rule_payment AS cr ";
$qr .= "JOIN payment_method AS cn ON cr.payment_code = cn.code ";
$qr .= "WHERE id_rule = ".$id;
return $this->db->query($qr);
}
/*
|----------------------------------
| END ใช้สำหรับแสดงรายละเอียดในหน้าพิมพ์
|----------------------------------
*/
/*
|----------------------------------
| BEGIN ใช้สำหรับหน้ากำหนดเงื่อนไข
|----------------------------------
*/
public function getRuleCustomerId($id)
{
$sc = array();
$rs = $this->db->where('id_rule', $id)->get('discount_rule_customer');
if($rs->num_rows() > 0)
{
foreach($rs->result() as $rd)
{
$sc[$rd->customer_code] = $rd->customer_code;
}
}
return $sc;
}
public function getRuleCustomerGroup($id)
{
$sc = array();
$rs = $this->db->where('id_rule', $id)->get('discount_rule_customer_group');
if($rs->num_rows() > 0)
{
foreach($rs->result() as $rd)
{
$sc[$rd->group_code] = $rd->group_code;
}
}
return $sc;
}
public function getRuleCustomerType($id)
{
$sc = array();
$rs = $this->db->where('id_rule', $id)->get('discount_rule_customer_type');
if($rs->num_rows() > 0)
{
foreach($rs->result() as $rd)
{
$sc[$rd->type_code] = $rd->type_code;
}
}
return $sc;
}
public function getRuleCustomerKind($id)
{
$sc = array();
$rs = $this->db->where('id_rule', $id)->get('discount_rule_customer_kind');
if($rs->num_rows() > 0)
{
foreach($rs->result() as $rd)
{
$sc[$rd->kind_code] = $rd->kind_code;
}
}
return $sc;
}
public function getRuleCustomerArea($id)
{
$sc = array();
$rs = $this->db->where('id_rule', $id)->get('discount_rule_customer_area');
if($rs->num_rows() > 0)
{
foreach($rs->result() as $rd)
{
$sc[$rd->area_code] = $rd->area_code;
}
}
return $sc;
}
public function getRuleCustomerClass($id)
{
$sc = array();
$rs = $this->db->where('id_rule', $id)->get('discount_rule_customer_class');
if($rs->num_rows() > 0)
{
foreach($rs->result() as $rd)
{
$sc[$rd->class_code] = $rd->class_code;
}
}
return $sc;
}
public function getRuleProductStyle($id)
{
$sc = array();
$rs = $this->db->where('id_rule', $id)->get('discount_rule_product_style');
if($rs->num_rows() > 0)
{
foreach($rs->result() as $rd)
{
$sc[$rd->style_code] = $rd->style_code;
}
}
return $sc;
}
public function getRuleProductGroup($id)
{
$sc = array();
$rs = $this->db->where('id_rule', $id)->get('discount_rule_product_group');
if($rs->num_rows() > 0)
{
foreach($rs->result() as $rd)
{
$sc[$rd->group_code] = $rd->group_code;
}
}
return $sc;
}
public function getRuleProductSubGroup($id)
{
$sc = array();
$rs = $this->db->where('id_rule', $id)->get('discount_rule_product_sub_group');
if($rs->num_rows() > 0)
{
foreach($rs->result() as $rd)
{
$sc[$rd->sub_group_code] = $rd->sub_group_code;
}
}
return $sc;
}
public function getRuleProductType($id)
{
$sc = array();
$rs = $this->db->where('id_rule', $id)->get('discount_rule_product_type');
if($rs->num_rows() > 0)
{
foreach($rs->result() as $rd)
{
$sc[$rd->type_code] = $rd->type_code;
}
}
return $sc;
}
public function getRuleProductKind($id)
{
$sc = array();
$rs = $this->db->where('id_rule', $id)->get('discount_rule_product_kind');
if($rs->num_rows() > 0)
{
foreach($rs->result() as $rd)
{
$sc[$rd->kind_code] = $rd->kind_code;
}
}
return $sc;
}
public function getRuleProductCategory($id)
{
$sc = array();
$rs = $this->db->where('id_rule', $id)->get('discount_rule_product_category');
if($rs->num_rows() > 0)
{
foreach($rs->result() as $rd)
{
$sc[$rd->category_code] = $rd->category_code;
}
}
return $sc;
}
public function getRuleProductYear($id)
{
$sc = array();
$rs = $this->db->where('id_rule', $id)->get('discount_rule_product_year');
if($rs->num_rows() > 0)
{
foreach($rs->result() as $rd)
{
$sc[$rd->year] = $rd->year;
}
}
return $sc;
}
public function getRuleProductBrand($id)
{
$sc = array();
$rs = $this->db->where('id_rule', $id)->get('discount_rule_product_brand');
if($rs->num_rows() > 0)
{
foreach($rs->result() as $rd)
{
$sc[$rd->brand_code] = $rd->brand_code;
}
}
return $sc;
}
public function getRuleChannels($id)
{
$sc = array();
$rs = $this->db->where('id_rule', $id)->get('discount_rule_channels');
if($rs->num_rows() > 0)
{
foreach($rs->result() as $rd)
{
$sc[$rd->channels_code] = $rd->channels_code;
}
}
return $sc;
}
public function getRulePayment($id)
{
$sc = array();
$rs = $this->db->where('id_rule', $id)->get('discount_rule_payment');
if($rs->num_rows() > 0)
{
foreach($rs->result() as $rd)
{
$sc[$rd->payment_code] = $rd->payment_code;
}
}
return $sc;
}
public function set_all_customer($id, $value)
{
/*
1. set all customer = 1
2. delete customer rule
3. delete customer_group rule;
4. delete customer_type rule;
5. delete customer_kind rule;
6. delete customer_area rule;
7. delete customer_class rule;
*/
$result = new stdClass();
$result->status = TRUE;
$result->message = 'success';
if($value === 1)
{
//--- start transection
$this->db->trans_start();
//--- 1
$this->db->query("UPDATE discount_rule SET all_customer = 1 WHERE id = $id");
//--- 2
$this->db->query("DELETE FROM discount_rule_customer WHERE id_rule = $id");
//--- 3
$this->db->query("DELETE FROM discount_rule_customer_group WHERE id_rule = $id");
//--- 4
$this->db->query("DELETE FROM discount_rule_customer_type WHERE id_rule = $id");
//--- 5
$this->db->query("DELETE FROM discount_rule_customer_kind WHERE id_rule = $id");
//--- 6
$this->db->query("DELETE FROM discount_rule_customer_area WHERE id_rule = $id");
//--- 7
$this->db->query("DELETE FROM discount_rule_customer_class WHERE id_rule = $id");
//--- end transection
$this->db->trans_complete();
if($this->db->trans_status() === FALSE)
{
$result->status = FALSE;
$result->message = 'กำหนดลูกค้าทั้งหมดไม่สำเร็จ';
}
}
else
{
$rs = $this->db->query("UPDATE discount_rule SET all_customer = 0 WHERE id = $id");
if($rs === FALSE)
{
$result->status = FALSE;
$result->message = 'กำหนดลูกค้าทั้งหมดไม่สำเร็จ';
}
}
return $result;
}
public function set_customer_list($id, $cust_list)
{
/*
1. set all customer = 0
2. delete customers rule;
2.1 set customer rule;
3. delete customer_group rule;
4. delete customer_type rule;
5. delete customer_kind rule;
6. delete customer_area rule;
7. delete customer_class rule;
*/
$result = new stdClass();
$result->status = TRUE;
$result->message = 'success';
//---- start transection
$this->db->trans_start();
//--- 1.
$this->db->query("UPDATE discount_rule SET all_customer = 0 WHERE id = $id");
//--- 2.
$this->db->query("DELETE FROM discount_rule_customer WHERE id_rule = $id");
if(!empty($cust_list))
{
foreach($cust_list as $code)
{
$this->db->query("INSERT INTO discount_rule_customer (id_rule, customer_code) VALUES ($id, '$code')");
}
}
//--- 3
$this->db->query("DELETE FROM discount_rule_customer_group WHERE id_rule = $id");
//--- 4
$this->db->query("DELETE FROM discount_rule_customer_type WHERE id_rule = $id");
//--- 5
$this->db->query("DELETE FROM discount_rule_customer_kind WHERE id_rule = $id");
//--- 6
$this->db->query("DELETE FROM discount_rule_customer_area WHERE id_rule = $id");
//--- 7
$this->db->query("DELETE FROM discount_rule_customer_class WHERE id_rule = $id");
//--- end transection
$this->db->trans_complete();
if($this->db->trans_status() === FALSE)
{
$result->status = FALSE;
$result->message = 'กำหนดรายชื่อลูกค้าไม่สำเร็จ';
}
return $result;
}
public function set_customer_attr($id, $group, $type, $kind, $area, $class)
{
$result = new stdClass();
$result->status = TRUE;
$result->message = 'message';
//--- start transection
$this->db->trans_start();
//--- 1.
$this->db->query("DELETE FROM discount_rule_customer WHERE id_rule = $id");
//--- 2
$this->db->query("DELETE FROM discount_rule_customer_group WHERE id_rule = $id");
if(!empty($group))
{
foreach($group as $code)
{
$this->db->query("INSERT INTO discount_rule_customer_group (id_rule, group_code) VALUES ($id, '$code')");
}
}
//--- 3
$this->db->query("DELETE FROM discount_rule_customer_type WHERE id_rule = $id");
if(!empty($type))
{
foreach($type as $code)
{
$this->db->query("INSERT INTO discount_rule_customer_type (id_rule, type_code) VALUES ($id, '$code')");
}
}
//--- 4
$this->db->query("DELETE FROM discount_rule_customer_kind WHERE id_rule = $id");
if(!empty($kind))
{
foreach($kind as $code)
{
$this->db->query("INSERT INTO discount_rule_customer_kind (id_rule, kind_code) VALUES ($id, '$code')");
}
}
//--- 5
$this->db->query("DELETE FROM discount_rule_customer_area WHERE id_rule = $id");
if(!empty($area))
{
foreach($area as $code)
{
$this->db->query("INSERT INTO discount_rule_customer_area (id_rule, area_code) VALUES ($id, '$code')");
}
}
//--- 6
$this->db->query("DELETE FROM discount_rule_customer_class WHERE id_rule = $id");
if(!empty($class))
{
foreach($class as $code)
{
$this->db->query("INSERT INTO discount_rule_customer_class (id_rule, class_code) VALUES ($id, '$code')");
}
}
//--- end transection
$this->db->trans_complete();
if($this->db->trans_status() === FALSE)
{
$result->status = FALSE;
$result->message = 'กำหนดเงื่อนไขคุณลักษณะลูกค้าไม่สำเร็จ';
}
return $result;
}
public function set_all_product($id, $value)
{
$result = new stdClass();
$result->status = TRUE;
$result->message = 'success';
if($value == 1)
{
//--- start transection
$this->db->trans_start();
//--- 1.
$this->db->query("UPDATE discount_rule SET all_product = 1 WHERE id = $id");
//--- 2.
$this->db->query("DELETE FROM discount_rule_product_style WHERE id_rule = $id");
//--- 3
$this->db->query("DELETE FROM discount_rule_product_group WHERE id_rule = $id");
//--- 4
$this->db->query("DELETE FROM discount_rule_product_sub_group WHERE id_rule = $id");
//--- 5
$this->db->query("DELETE FROM discount_rule_product_category WHERE id_rule = $id");
//--- 6
$this->db->query("DELETE FROM discount_rule_product_type WHERE id_rule = $id");
//--- 7
$this->db->query("DELETE FROM discount_rule_product_kind WHERE id_rule = $id");
//--- 8
$this->db->query("DELETE FROM discount_rule_product_brand WHERE id_rule = $id");
//--- 9
$this->db->query("DELETE FROM discount_rule_product_year WHERE id_rule = $id");
//--- end transection
$this->db->trans_complete();
if($this->db->trans_status() === FALSE)
{
$result->status = FALSE;
$result->message = "บันทึกเงือนไขสินค้าไม่สำเร็จ";
}
}
else
{
//--- 1.
$this->db->query("UPDATE discount_rule SET all_product = 0 WHERE id = $id");
}
return $result;
}
public function set_product_style($id, $style)
{
$result = new stdClass();
$result->status = TRUE;
$result->message = 'success';
//---- start transection
$this->db->trans_start();
//--- 1.
$this->db->query("UPDATE discount_rule SET all_product = 0 WHERE id = $id");
//--- 2 ลบข้อมูลเก่าก่อน
$this->db->query("DELETE FROM discount_rule_product_style WHERE id_rule = $id");
if(!empty($style))
{
foreach($style as $code)
{
$this->db->query("INSERT INTO discount_rule_product_style (id_rule, style_code) VALUES ($id, '$code')");
}
}
//--- 3
$this->db->query("DELETE FROM discount_rule_product_group WHERE id_rule = $id");
//--- 4
$this->db->query("DELETE FROM discount_rule_product_sub_group WHERE id_rule = $id");
//--- 5
$this->db->query("DELETE FROM discount_rule_product_category WHERE id_rule = $id");
//--- 6
$this->db->query("DELETE FROM discount_rule_product_type WHERE id_rule = $id");
//--- 7
$this->db->query("DELETE FROM discount_rule_product_kind WHERE id_rule = $id");
//--- 8
$this->db->query("DELETE FROM discount_rule_product_brand WHERE id_rule = $id");
//--- 9
$this->db->query("DELETE FROM discount_rule_product_year WHERE id_rule = $id");
//--- end transection
$this->db->trans_complete();
if($this->db->trans_status() === FALSE)
{
$result->status = FALSE;
$result->message = 'กำหนดเงื่อนไขรุ่นสินค้าไม่สำเร็จ';
}
return $result;
}
public function set_product_attr($id, $group, $sub_group, $category, $type, $kind, $brand, $year)
{
$result = new stdClass();
$result->status = TRUE;
$result->message = 'success';
$this->db->trans_start();
//--- ลบเงื่อนไขรุ่นสินค้าก่อน
$this->db->where('id_rule', $id)->delete('discount_rule_product_style');
//--- กลุ่มสินค้า
$this->db->where('id_rule', $id)->delete('discount_rule_product_group');
if(!empty($group))
{
foreach($group as $code)
{
$this->db->insert('discount_rule_product_group', array('id_rule' => $id, 'group_code' => $code));
}
}
//--- กลุ่มย่อยสินค้า
$this->db->where('id_rule', $id)->delete('discount_rule_product_sub_group');
if(!empty($sub_group))
{
foreach($sub_group as $code)
{
$this->db->insert('discount_rule_product_sub_group', array('id_rule' => $id, 'sub_group_code' => $code));
}
}
//--- หมวดหมู่สินค้า
$this->db->where('id_rule', $id)->delete('discount_rule_product_category');
if(!empty($category))
{
foreach($category as $code)
{
$this->db->insert('discount_rule_product_category', array('id_rule' => $id, 'category_code' => $code));
}
}
//--- ประเภทสินค้า
$this->db->where('id_rule', $id)->delete('discount_rule_product_type');
if(!empty($type))
{
foreach($type as $code)
{
$this->db->insert('discount_rule_product_type', array('id_rule' => $id, 'type_code' => $code));
}
}
//--- ชนิดสินค้า
$this->db->where('id_rule', $id)->delete('discount_rule_product_kind');
if(!empty($kind))
{
foreach($kind as $code)
{
$this->db->insert('discount_rule_product_kind', array('id_rule' => $id, 'kind_code' => $code));
}
}
//--- ยี่ห้อ
$this->db->where('id_rule', $id)->delete('discount_rule_product_brand');
if(!empty($brand))
{
foreach($brand as $code)
{
$this->db->insert('discount_rule_product_brand', array('id_rule' => $id, 'brand_code' => $code));
}
}
//--- ปีสินค้า
$this->db->where('id_rule', $id)->delete('discount_rule_product_year');
if(!empty($year))
{
foreach($year as $code)
{
$this->db->insert('discount_rule_product_year', array('id_rule' => $id, 'year' => $code));
}
}
//--- end transection
$this->db->trans_complete();
if($this->db->trans_status() === FALSE)
{
$result->status = FALSE;
$result->message = 'กำหนดเงื่อนไขคุณลักษณะสินค้าไม่สำเร็จ';
}
return $result;
}
public function set_all_channels($id)
{
$result = new stdClass();
$result->status = TRUE;
$result->message = 'success';
$this->db->trans_start();
//--- ลบเงื่อนไขช่องทางขายทั้งหมดก่อน
$this->db->where('id_rule', $id)->delete('discount_rule_channels');
//--- update เงือนไข
$this->db->set('all_channels', 1)->where('id', $id)->update('discount_rule');
//--- end transection
$this->db->trans_complete();
if($this->db->trans_status() === FALSE)
{
$result->status = FALSE;
$result->message = 'กำหนดเงื่อนไขช่องทางขายไม่สำเร็จ';
}
return $result;
}
public function set_channels($id, $channels)
{
$result = new stdClass();
$result->status = TRUE;
$result->message = 'success';
$this->db->trans_start();
//--- update เงือนไข
$this->db->set('all_channels', 0)->where('id', $id)->update('discount_rule');
//--- ลบเงื่อนไขช่องทางขายทั้งหมดก่อน
$this->db->where('id_rule', $id)->delete('discount_rule_channels');
//--- insert ใหม่
if(!empty($channels))
{
foreach($channels as $code)
{
$this->db->insert('discount_rule_channels', array('id_rule' => $id, 'channels_code' => $code));
}
}
//--- end transection
$this->db->trans_complete();
if($this->db->trans_status() === FALSE)
{
$result->status = FALSE;
$result->message = 'กำหนดเงื่อนไขช่องทางขายไม่สำเร็จ';
}
return $result;
}
public function set_all_payment($id)
{
$result = new stdClass();
$result->status = TRUE;
$result->message = 'success';
$this->db->trans_start();
//--- ลบเงื่อนไขทั้งหมดก่อน
$this->db->where('id_rule', $id)->delete('discount_rule_payment');
//--- update เงือนไข
$this->db->set('all_payment', 1)->where('id', $id)->update('discount_rule');
//--- end transection
$this->db->trans_complete();
if($this->db->trans_status() === FALSE)
{
$result->status = FALSE;
$result->message = 'กำหนดเงื่อนไขช่องการชำระเงินไม่สำเร็จ';
}
return $result;
}
public function set_payment($id, $payment)
{
$result = new stdClass();
$result->status = TRUE;
$result->message = 'success';
$this->db->trans_start();
//--- update เงือนไข
$this->db->set('all_payment', 0)->where('id', $id)->update('discount_rule');
//--- ลบเงื่อนไขช่องทางขายทั้งหมดก่อน
$this->db->where('id_rule', $id)->delete('discount_rule_payment');
//--- insert ใหม่
if(!empty($payment))
{
foreach($payment as $code)
{
$this->db->insert('discount_rule_payment', array('id_rule' => $id, 'payment_code' => $code));
}
}
//--- end transection
$this->db->trans_complete();
if($this->db->trans_status() === FALSE)
{
$result->status = FALSE;
$result->message = 'กำหนดเงื่อนไขช่องทางการชำระเงินไม่สำเร็จ';
}
return $result;
}
/*
|----------------------------------
| END ใช้สำหรับหน้ากำหนดเงื่อนไข
|----------------------------------
*/
public function update_policy($id_rule, $id_policy)
{
return $this->db->set('id_policy', $id_policy)->where('id', $id_rule)->update('discount_rule');
}
public function count_rows($code, $name, $active, $policy, $discount)
{
$qr = "SELECT id FROM discount_rule WHERE isDeleted = 0 ";
if($code != "")
{
$qr .= "AND code LIKE '%".$code."%' ";
}
if($name != "")
{
$qr .= "AND name LIKE '%".$name."%' ";
}
if($active != 2)
{
$qr .= "AND active = ".$active." ";
}
if($policy != "")
{
$policies = discount_policy_in($policy);
$qr .= "AND id_policy IN(".$policies.") ";
}
if($discount != "")
{
$qr .= "AND item_disc = ".$discount." ";
}
$rs = $this->db->query($qr);
if($rs->num_rows() > 0)
{
return $rs->num_rows();
}
return 0;
}
public function get_data($code, $name, $active, $policy, $discount, $perpage = '', $offset = '')
{
$qr = "SELECT * FROM discount_rule WHERE isDeleted = 0 ";
if($code != "")
{
$qr .= "AND code LIKE '%".$code."%' ";
}
if($name != "")
{
$qr .= "AND name LIKE '%".$name."%' ";
}
if($active != 2)
{
$qr .= "AND active = ".$active." ";
}
if($policy != "")
{
$policies = discount_policy_in($policy);
$qr .= "AND id_policy IN(".$policies.") ";
}
if($discount != "")
{
$qr .= "AND item_disc = ".$discount." ";
}
$qr .= "ORDER BY code DESC";
$rs = $this->db->query($qr);
if($rs->num_rows() > 0)
{
return $rs->result();
}
return array();
}
public function get_policy_rules($id_policy)
{
$rs = $this->db->where('id_policy', $id_policy)->get('discount_rule');
if($rs->num_rows() > 0)
{
return $rs->result();
}
return array();
}
public function get_active_rule()
{
$rs = $this->db->where('active', 1)->where('id_policy IS NULL')->get('discount_rule');
if($rs->num_rows() > 0)
{
return $rs->result();
}
return array();
}
public function get_max_code($code)
{
$qr = "SELECT MAX(code) AS code FROM discount_rule WHERE code LIKE '".$code."%' ORDER BY code DESC";
$rs = $this->db->query($qr);
return $rs->row()->code;
}
public function search($txt)
{
$rs = $this->db->select('id')
->like('code', $txt)
->like('name', $txt)
->get('discount_rule');
if($rs->num_rows() > 0)
{
return $rs->result();
}
return array();
}
public function delete_rule($id)
{
//--- start transection
$this->db->trans_start();
//--- 1.
$this->db->where('id_rule', $id)->delete('discount_rule_product_style');
//--- 2.
$this->db->where('id_rule', $id)->delete('discount_rule_product_group');
//--- 3
$this->db->where('id_rule', $id)->delete('discount_rule_product_sub_group');
//--- 4
$this->db->where('id_rule', $id)->delete('discount_rule_product_category');
//--- 5
$this->db->where('id_rule', $id)->delete('discount_rule_product_type');
//--- 6
$this->db->where('id_rule', $id)->delete('discount_rule_product_kind');
//--- 7
$this->db->where('id_rule', $id)->delete('discount_rule_product_brand');
//--- 8
$this->db->where('id_rule', $id)->delete('discount_rule_product_year');
//--- 9
$this->db->where('id', $id)->delete('discount_rule');
//--- end transection
$this->db->trans_complete();
return $this->db->trans_status();
}
} //--- end class
?>
| 22.450761 | 113 | 0.559181 |
2f0b655a19b075ecf78018be2c999286ddd5ed70 | 8,305 | js | JavaScript | subsystem/enjs_overload.js | phoxy/phoxy | 45aefc229e86a1d17404ccfd771f74b503c71447 | [
"Apache-2.0"
] | 1 | 2015-10-28T18:27:05.000Z | 2015-10-28T18:27:05.000Z | subsystem/enjs_overload.js | phoxy/phoxy | 45aefc229e86a1d17404ccfd771f74b503c71447 | [
"Apache-2.0"
] | 91 | 2015-06-21T03:29:39.000Z | 2017-11-29T14:12:54.000Z | subsystem/enjs_overload.js | phoxy/phoxy | 45aefc229e86a1d17404ccfd771f74b503c71447 | [
"Apache-2.0"
] | 4 | 2015-06-12T19:17:09.000Z | 2016-04-14T10:19:08.000Z | /***
* Overloading EJS method: this.DeferCascade, this.DeferRender etc.
***/
phoxy.OverrideENJS =
{
_: {}
};
phoxy._.enjs =
{
OverloadENJSCanvas: function()
{
EJS.Canvas.prototype.recursive = 0;
phoxy.state.RenderCalls = 0;
phoxy._.internal.Override(EJS.Canvas.prototype, 'RenderCompleted', phoxy._.enjs.RenderCompleted);
phoxy._.internal.Override(EJS.Canvas.prototype, 'Defer', phoxy._.enjs.Defer);
phoxy._.internal.Override(EJS.Canvas.prototype, 'CheckIsCompleted', phoxy._.enjs.CheckIsCompleted);
phoxy._.internal.Override(EJS.Canvas.prototype, 'hook_first', phoxy._.enjs.hook_first);
phoxy._.internal.Override(EJS.Canvas.across.prototype, 'DeferCascade', phoxy._.enjs.DeferCascade);
phoxy._.internal.Override(EJS.Canvas.across.prototype, 'CascadeDesign', phoxy._.enjs.CascadeDesign);
phoxy._.internal.Override(EJS.Canvas.across.prototype, 'CascadeRequest', phoxy._.enjs.CascadeRequest);
phoxy._.internal.Override(EJS.Canvas.across.prototype, 'CascadeSupply', phoxy._.enjs.CascadeSupply);
phoxy._.internal.Override(EJS.Canvas.across.prototype, 'ForeachDesign', phoxy._.enjs.ForeachDesign);
phoxy._.internal.Override(EJS.Canvas.across.prototype, 'ForeachRequest', phoxy._.enjs.ForeachRequest);
}
,
RenderCompleted: function()
{
arguments.callee.origin.apply(this);
// In case of recursive rendering, forbid later using
// If you losed context from this, and access it with __this
// Then probably its too late to use this methods:
delete this.across.Defer;
delete this.across.DeferRender;
delete this.across.DeferCascade;
if (this.recursive)
return;
// not single DeferRender was invoked
// but Canvas.on_completed not prepared
// So render plan is plain, and we attach CheckIsCompleted in this.Defer queue
this.recursive++;
phoxy.state.RenderCalls++;
this.across.Defer(this.CheckIsCompleted);
}
,
CheckIsCompleted: function()
{
var escape = this.escape();
if (--escape.recursive === 0)
{
escape.log("FireUp");
escape.fired_up = true;
for (var k in escape.cascade)
if (typeof (escape.cascade[k]) === 'function')
escape.cascade[k].apply(this);
if (typeof(escape.on_complete) === 'function')
escape.on_complete();
}
}
,
hook_first: function(result)
{
var root = result;
while (true)
{
if (!root)
break;
if (root.nodeType == 1 &&
['defer_render','render'].indexOf(root.tagName) === -1 &&
root.classList.contains('phoxy_ignore') === false &&
root.classList.contains('ejs_ancor') === false)
break;
root = root.nextSibling;
}
phoxy._.enjs.update_context_after_cascade_finished(this, root);
return root;
}
,
update_context_after_cascade_finished: function(context, root)
{
if (root == null || root.tagName.search('CASCADE') == -1)
return;
root.addEventListener('phoxy.rendered.alpha', function(e)
{
if (e.target != root)
return;
context.first_dom_element_cached = undefined;
context.get_first_context_dom_element(root.getAttribute('id'));
});
}
,
CascadeInit: function(across, ejs, data, callback, tag, sync_cascade)
{
var that = across.escape();
phoxy._.enjs.RequireENJSRutime(that);
that.recursive++;
phoxy.state.RenderCalls++;
function CBHook()
{
if (typeof callback === 'function')
callback.call(this); // Local fancy context
phoxy.state.RenderCalls--;
that.CheckIsCompleted.call(that.across);
}
if (Array.isArray(data))
{
var origin = data;
data = data.reduce(function(o, v, i)
{
o[i] = v;
return o;
}, {});
data.length = origin.length;
data.origin = origin;
}
// Handling non arrays (ex: strings) as data objects
if (['object', 'undefined', 'function'].indexOf(typeof data) == -1)
data = { data: data };
if (phoxy.state.sticky_cascade_strategy)
sync_cascade = sync_cascade || that.sync_cascade;
var ancor = phoxy.DeferRender(ejs, data, CBHook, tag, sync_cascade);
that.Append(ancor);
return "<!-- <%= %> IS OBSOLETE. Refactor " + that.name + " -->";
}
,
CascadeDesign: function(ejs, data, callback, tag, sync_cascade)
{
if (data === undefined || data === null)
if (typeof ejs !== 'object')
data = {};
this.escape().log("Design", ejs, data);
return phoxy._.enjs.CascadeInit(this, ejs, data, callback, tag || "<CascadeDesign>", sync_cascade);
}
,
CascadeRequest: function(url, callback, tag, sync_cascade)
{
if (typeof url !== 'string' && !Array.isArray(url))
return phoxy.Log(1, "Are you sure that URL parameters of CascadeRequest right?");
this.escape().log("Request", url);
return phoxy._.enjs.CascadeInit(this, url, undefined, callback, tag || "<CascadeRequest>", sync_cascade);
}
,
CascadeSupply: function(design, url, callback, tag, sync_cascade)
{
if (typeof url !== 'string' && !Array.isArray(url))
return phoxy.Log(1, "Are you sure that URL parameters of CascadeRequest right?");
this.escape().log("Supply", design, url);
// Workaround issue caused cascade support array/string types
// - main types for url handling
function hook_data_ready(cb)
{
phoxy.AJAX(url, function (data)
{
cb(data.data);
});
}
return phoxy._.enjs.CascadeInit(this, design, hook_data_ready, callback, tag || "<CascadeRequest>", sync_cascade);
}
,
ShortcutCallback: function(k, callback)
{
if (typeof callback !== 'function')
return undefined;
return function()
{
var args = arguments;
args.unshift(k);
return callback.apply(this, args);
}
}
,
ForeachDesign: function(ejs, dataset, callback, tag, sync_cascade)
{
if (phoxy.state.sync_foreach_design)
sync_cascade = sync_cascade || true;
for (var k in dataset)
if (dataset.hasOwnProperty(k))
this.CascadeDesign(ejs, dataset[k], phoxy._.enjs.ShortcutCallback(k, callback), tag, sync_cascade);
}
,
ForeachRequest: function(dataset, callback, tag, sync_cascade)
{
if (phoxy.state.sync_foreach_request)
sync_cascade = sync_cascade || false;
for (var k in dataset)
if (dataset.hasOwnProperty(k))
this.CascadeRequest(dataset[k], phoxy._.enjs.ShortcutCallback(k, callback), tag, sync_cascade);
}
,
Defer: function(callback, time)
{
var that = this.escape();
that.log("Defer", callback, time);
that.recursive++;
phoxy._.enjs.RequireENJSRutime(that);
function defer_cb()
{
if (typeof callback === 'function')
callback.call(that.across);
that.CheckIsCompleted.call(that.across);
}
// In sync cascade defer executing immideately
var OriginDefer = arguments.callee.origin;
if (that.sync_cascade)
return OriginDefer.call(this, defer_cb, time);
if (typeof that.defer === 'undefined')
that.defer = [];
return that.defer.push(function enjs_defer_sheduler()
{
return OriginDefer(defer_cb, time);
})
}
,
DeferCascade: function(callback)
{
var that = this.escape();
that.log("DeferCascade", callback);
phoxy._.enjs.RequireENJSRutime(that);
if (typeof that.cascade === 'undefined')
that.cascade = [];
that.cascade.push(callback);
}
,
RequireENJSRutime: function(that)
{
if (!that.fired_up)
return; // requirment ment. continue;
phoxy.Log(0, "You can't invoke __this.Defer... methods after rendering finished.\
Because parent cascade callback already executed, and probably you didn't expect new elements on your context.\
Check if you call __this.Defer... on DOM(jquery) events? Thats too late. (It mean DOM event exsist -> Render completed).\
In that case use phoxy.Defer methods directly. They context-dependence free.");
}
};
| 30.09058 | 121 | 0.628898 |
f422b0931daacebb33d5518959d22fa83c77642a | 19,188 | cs | C# | Configuration/Paths.cs | RW74/StockSharp | 6071725d2a0fb1aceea6977cd5184221dd3133be | [
"Apache-2.0"
] | 5,213 | 2015-03-25T21:44:36.000Z | 2022-03-31T17:10:14.000Z | Configuration/Paths.cs | ywscr/StockSharp | 9471f2e26135e5fc98e66950a360adaed8264a7c | [
"Apache-2.0"
] | 150 | 2015-03-23T21:07:37.000Z | 2020-10-05T05:35:56.000Z | Configuration/Paths.cs | ywscr/StockSharp | 9471f2e26135e5fc98e66950a360adaed8264a7c | [
"Apache-2.0"
] | 1,638 | 2015-03-24T17:10:13.000Z | 2022-03-30T05:33:04.000Z | namespace StockSharp.Configuration
{
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Collections.Generic;
using Ecng.Common;
using Ecng.Security;
using Ecng.Configuration;
using Ecng.Serialization;
using Ecng.ComponentModel;
using Ecng.Localization;
using NuGet.Configuration;
using StockSharp.Localization;
using StockSharp.Messages;
using StockSharp.Logging;
/// <summary>
/// System paths.
/// </summary>
public static class Paths
{
static Paths()
{
var companyPath = ConfigManager.TryGet<string>("companyPath");
CompanyPath = companyPath.IsEmpty() ? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "StockSharp") : companyPath.ToFullPathIfNeed();
AppName = ConfigManager.TryGet("appName", TypeHelper.ApplicationName);
var settingsPath = ConfigManager.TryGet<string>("settingsPath");
AppDataPath = settingsPath.IsEmpty() ? Path.Combine(CompanyPath, AppName2) : settingsPath.ToFullPathIfNeed();
PlatformConfigurationFile = Path.Combine(AppDataPath, $"platform_config{DefaultSettingsExt}");
ProxyConfigurationFile = Path.Combine(CompanyPath, $"proxy_config{DefaultSettingsExt}");
SecurityNativeIdDir = Path.Combine(AppDataPath, "NativeId");
SecurityMappingDir = Path.Combine(AppDataPath, "Symbol mapping");
SecurityExtendedInfo = Path.Combine(AppDataPath, "Extended info");
StorageDir = Path.Combine(AppDataPath, "Storage");
SnapshotsDir = Path.Combine(AppDataPath, "Snapshots");
InstallerDir = Path.Combine(CompanyPath, "Installer");
InstallerInstallationsConfigPath = Path.Combine(InstallerDir, $"installer_apps_installed{DefaultSettingsExt}");
var settings = Settings.LoadDefaultSettings(null);
HistoryDataPath = GetHistoryDataPath(SettingsUtility.GetGlobalPackagesFolder(settings));
}
/// <summary>
/// Get history data path.
/// </summary>
/// <param name="startDir">Directory.</param>
/// <returns>History data path.</returns>
public static string GetHistoryDataPath(string startDir)
{
static DirectoryInfo FindHistoryDataSubfolder(DirectoryInfo packageRoot)
{
if (!packageRoot.Exists)
return null;
foreach (var di in packageRoot.GetDirectories().OrderByDescending(di => di.Name))
{
var d = new DirectoryInfo(Path.Combine(di.FullName, "HistoryData"));
if (d.Exists)
return d;
}
return null;
}
var dir = new DirectoryInfo(Path.GetDirectoryName(startDir));
while (dir != null)
{
var hdRoot = FindHistoryDataSubfolder(new DirectoryInfo(Path.Combine(dir.FullName, "packages", "stocksharp.samples.historydata")));
if (hdRoot != null)
return hdRoot.FullName;
dir = dir.Parent;
}
return null;
}
/// <summary>
/// App title.
/// </summary>
public static readonly string AppName;
/// <summary>
///
/// </summary>
public static string AppName2 => AppName.Remove("S#.", true);
/// <summary>
/// App title with version.
/// </summary>
public static string AppNameWithVersion => $"{AppName} v{InstalledVersion}";
/// <summary>
/// The path to directory with all applications.
/// </summary>
public static readonly string CompanyPath;
/// <summary>
/// The path to the settings directory.
/// </summary>
public static readonly string AppDataPath;
/// <summary>
/// The path to the configuration file of platform definition.
/// </summary>
public static readonly string PlatformConfigurationFile;
/// <summary>
/// The path to the configuration file of proxy settings.
/// </summary>
public static readonly string ProxyConfigurationFile;
/// <summary>
/// The path to the directory with native security identifiers.
/// </summary>
public static readonly string SecurityNativeIdDir;
/// <summary>
/// The path to the directory with securities id mapping.
/// </summary>
public static readonly string SecurityMappingDir;
/// <summary>
/// The path to the directory with securities extended info.
/// </summary>
public static readonly string SecurityExtendedInfo;
/// <summary>
/// The path to the directory with market data.
/// </summary>
public static readonly string StorageDir;
/// <summary>
/// The path to the directory with snapshots of market data.
/// </summary>
public static readonly string SnapshotsDir;
/// <summary>
/// The path to the installer directory.
/// </summary>
public static readonly string InstallerDir;
/// <summary>
/// The path to the installer directory.
/// </summary>
public static readonly string InstallerInstallationsConfigPath;
/// <summary>
/// Web site domain.
/// </summary>
public static string Domain => LocalizedStrings.ActiveLanguage == LangCodes.Ru ? "ru" : "com";
/// <summary>
/// Get website url.
/// </summary>
/// <returns>Localized url.</returns>
public static string GetWebSiteUrl() => $"https://stocksharp.{Domain}";
/// <summary>
/// Get user url.
/// </summary>
/// <param name="userId">Identifier.</param>
/// <returns>Localized url.</returns>
public static string GetUserUrl(long userId) => $"{GetWebSiteUrl()}/users/{userId}/";
/// <summary>
/// Get strategy url.
/// </summary>
/// <param name="robotId">Identifier.</param>
/// <returns>Localized url.</returns>
[Obsolete]
public static string GetRobotLink(long robotId) => $"{GetWebSiteUrl()}/robot/{robotId}/";
/// <summary>
/// Get produdct url.
/// </summary>
/// <param name="productId">Identifier.</param>
/// <returns>Localized url.</returns>
public static string GetProductLink(object productId) => $"{GetWebSiteUrl()}/store/{productId}/";
/// <summary>
/// Get topic url.
/// </summary>
/// <param name="topicId">Identifier.</param>
/// <returns>Localized url.</returns>
public static string GetTopicLink(long topicId) => $"{GetWebSiteUrl()}/topic/{topicId}/";
/// <summary>
/// Get message url.
/// </summary>
/// <param name="messageId">Identifier.</param>
/// <returns>Localized url.</returns>
public static string GetMessageLink(long messageId) => $"{GetWebSiteUrl()}/posts/m/{messageId}/";
/// <summary>
/// Get file url.
/// </summary>
/// <param name="fileId">File ID.</param>
/// <returns>Localized url.</returns>
public static string GetFileLink(object fileId) => $"{GetWebSiteUrl()}/file/{fileId}/";
/// <summary>
/// To create localized url.
/// </summary>
/// <param name="docUrl">Help topic.</param>
/// <returns>Localized url.</returns>
public static string GetDocUrl(string docUrl) => $"https://doc.stocksharp.{Domain}/{docUrl}";
/// <summary>
/// Get open account url.
/// </summary>
/// <returns>Localized url.</returns>
public static string GetOpenAccountUrl() => $"{GetWebSiteUrl()}/broker/openaccount/";
/// <summary>
/// Get sign up url.
/// </summary>
/// <returns>Localized url.</returns>
public static string GetSignUpUrl() => $"{GetWebSiteUrl()}/register/";
/// <summary>
/// Get forgot password url.
/// </summary>
/// <returns>Localized url.</returns>
public static string GetForgotUrl() => $"{GetWebSiteUrl()}/forgot/";
private static string _installedVersion;
/// <summary>
/// Installed version of the product.
/// </summary>
public static string InstalledVersion
{
get
{
if (_installedVersion != null)
return _installedVersion;
static string GetAssemblyVersion() => (Assembly.GetEntryAssembly() ?? typeof(Paths).Assembly).GetName().Version.To<string>();
try
{
_installedVersion = GetInstalledVersion(Directory.GetCurrentDirectory()) ?? GetAssemblyVersion();
}
catch
{
_installedVersion = GetAssemblyVersion();
}
_installedVersion ??= "<error>";
return _installedVersion;
}
}
/// <summary>
/// Get currently installed version of the product.
/// </summary>
/// <param name="productInstallPath">File system path to product installation.</param>
/// <returns>Installed version of the product.</returns>
public static string GetInstalledVersion(string productInstallPath)
{
if (productInstallPath.IsEmpty())
throw new ArgumentException(nameof(productInstallPath));
if (!File.Exists(InstallerInstallationsConfigPath) && !File.Exists(InstallerInstallationsConfigPath.MakeLegacy()))
return null;
var storage = Do.Invariant(() =>
InstallerInstallationsConfigPath.DeserializeWithMigration<SettingsStorage>());
var installations = storage?.GetValue<SettingsStorage[]>("Installations");
if (!(installations?.Length > 0))
return null;
var installation = installations.FirstOrDefault(ss => productInstallPath.ComparePaths(ss.TryGet<string>("InstallDirectory")));
if(installation == null)
return null;
var identityStr = installation
.TryGet<SettingsStorage>("Version")
?.TryGet<SettingsStorage>("Metadata")
?.TryGet<string>("Identity");
if (identityStr.IsEmpty())
return null;
// ReSharper disable once PossibleNullReferenceException
var parts = identityStr.Split('|');
return parts.Length != 2 ? null : parts[1];
}
/// <summary>
/// Sample history data.
/// </summary>
public static readonly string HistoryDataPath;
private static ProcessSingleton _isRunningMutex;
/// <summary>
/// Check if an instance of the application already started.
/// </summary>
/// <returns>Check result.</returns>
public static bool StartIsRunning() => StartIsRunning(AppDataPath);
/// <summary>
/// Check if an instance of the application already started.
/// </summary>
/// <returns>Check result.</returns>
public static bool StartIsRunning(string appKey)
{
if (_isRunningMutex != null)
throw new InvalidOperationException("mutex was already initialized");
try
{
_isRunningMutex = new ProcessSingleton(appKey);
}
catch (Exception)
{
return false;
}
return true;
}
/// <summary>
/// Release all resources allocated by <see cref="StartIsRunning()"/>.
/// </summary>
public static void StopIsRunning()
{
_isRunningMutex?.Dispose();
_isRunningMutex = null;
}
private class ProcessSingleton : Disposable
{
private readonly ManualResetEvent _stop = new(false);
private readonly ManualResetEvent _stopped = new(false);
public ProcessSingleton(string key)
{
Exception error = null;
var started = new ManualResetEvent(false);
// mutex должен освобождаться из того же потока, в котором захвачен. некоторые приложения вызывают StopIsRunning из другого потока нежели StartIsRunning
// выделяя отдельный поток, обеспечивается гарантия корректной работы в любом случае
ThreadingHelper.Thread(() =>
{
Mutex mutex;
try
{
var mutexName = "stocksharp_app_" + key.UTF8().Md5();
if (!ThreadingHelper.TryGetUniqueMutex(mutexName, out mutex))
throw new InvalidOperationException($"can't acquire the mutex {mutexName}, (key={key})");
}
catch (Exception e)
{
error = e;
_stopped.Set();
return;
}
finally
{
started.Set();
}
try
{
_stop.WaitOne();
mutex.ReleaseMutex();
}
finally
{
_stopped.Set();
}
})
.Name("process_singleton")
.Launch();
started.WaitOne();
if (error != null)
throw error;
}
protected override void DisposeManaged()
{
_stop.Set();
_stopped.WaitOne();
base.DisposeManaged();
}
}
/// <summary>
/// Default extension for settings file.
/// </summary>
public const string DefaultSettingsExt = ".json";
/// <summary>
/// Legacy extension for settings file.
/// </summary>
public const string LegacySettingsExt = ".xml";
/// <summary>
/// Backup extension for settings file.
/// </summary>
public const string BackupExt = ".bak";
/// <summary>
/// Returns an files with <see cref="DefaultSettingsExt"/> and <see cref="LegacySettingsExt"/> extensions.
/// </summary>
/// <param name="path">The relative or absolute path to the directory to search.</param>
/// <param name="filter">The search string to match against the names of files in path.</param>
/// <returns>Files.</returns>
public static IEnumerable<string> EnumerateDefaultAndLegacy(string path, string filter = "*")
=> Directory.EnumerateFiles(path, $"{filter}{DefaultSettingsExt}").Concat(
Directory.EnumerateFiles(path, $"{filter}{LegacySettingsExt}"));
/// <summary>
/// Make the specified <paramref name="filePath"/> with <see cref="LegacySettingsExt"/> extension.
/// </summary>
/// <param name="filePath">File path.</param>
/// <returns>File path.</returns>
public static string MakeLegacy(this string filePath)
=> Path.ChangeExtension(filePath, LegacySettingsExt);
/// <summary>
/// Make the specified <paramref name="filePath"/> with <see cref="BackupExt"/> extension.
/// </summary>
/// <param name="filePath">File path.</param>
/// <returns>File path.</returns>
public static string MakeBackup(this string filePath)
=> $"{filePath}{BackupExt}";
/// <summary>
/// Rename the specified file with <see cref="BackupExt"/> extension.
/// </summary>
/// <param name="filePath">File path.</param>
/// <param name="backupFilePath">Backup file path.</param>
public static void MoveToBackup(this string filePath, string backupFilePath = null)
{
var target = backupFilePath ?? filePath;
var bak = target.MakeBackup();
var idx = 0;
do
{
if(!File.Exists(bak))
break;
bak = (target + $".{++idx}").MakeBackup();
} while(true);
File.Move(filePath, bak);
}
/// <summary>
/// Create serializer.
/// </summary>
/// <typeparam name="T">Value type.</typeparam>
/// <returns>Serializer.</returns>
public static ISerializer<T> CreateSerializer<T>()
=> new JsonSerializer<T> { FillMode = true, Indent = true, EnumAsString = true };
/// <summary>
/// Create serializer.
/// </summary>
/// <param name="type">Value type.</param>
/// <returns>Serializer.</returns>
public static ISerializer CreateSerializer(Type type)
=> CreateSerializer<int>().GetSerializer(type);
/// <summary>
/// Serialize value into the specified file.
/// </summary>
/// <typeparam name="T">Value type.</typeparam>
/// <param name="value">Value.</param>
/// <param name="filePath">File path.</param>
public static void Serialize<T>(this T value, string filePath)
=> CreateSerializer<T>().Serialize(value, filePath);
/// <summary>
/// Serialize value into byte array.
/// </summary>
/// <typeparam name="T">Value type.</typeparam>
/// <param name="value">Value.</param>
/// <returns>Serialized data.</returns>
public static byte[] Serialize<T>(this T value)
=> CreateSerializer<T>().Serialize(value);
/// <summary>
/// Deserialize value from the specified file.
/// </summary>
/// <typeparam name="T">Value type.</typeparam>
/// <param name="filePath">File path.</param>
/// <returns>Value.</returns>
public static T DeserializeWithMigration<T>(this string filePath)
{
var defFile = Path.ChangeExtension(filePath, DefaultSettingsExt);
var defSer = CreateSerializer<T>();
T value;
var legacyFile = filePath.MakeLegacy();
if (File.Exists(legacyFile))
{
// TODO 2021-09-09 remove 1 year later
#pragma warning disable CS0618 // Type or member is obsolete
value = new XmlSerializer<T>().Deserialize(legacyFile);
#pragma warning restore CS0618 // Type or member is obsolete
static void TryFix(SettingsStorage storage)
{
foreach (var pair in storage.ToArray())
{
var value = pair.Value;
if (value is List<Range<TimeSpan>> times)
{
storage.Set(pair.Key, times.Select(r => r.ToStorage()).ToArray());
}
else if (value is Dictionary<DayOfWeek, Range<TimeSpan>[]> specialDays)
{
storage.Set(pair.Key, specialDays.Select(p => new SettingsStorage()
.Set("Day", p.Key)
.Set("Periods", p.Value.Select(r => r.ToStorage()).ToArray())
).ToArray());
}
else if (value is Dictionary<DateTime, Range<TimeSpan>[]> specialDays2)
{
storage.Set(pair.Key, specialDays2.Select(p => new SettingsStorage()
.Set("Day", p.Key)
.Set("Periods", p.Value.Select(p1 => p1.ToStorage()).ToArray())
).ToArray());
}
else if (value is Dictionary<UserPermissions, IDictionary<Tuple<string, string, object, DateTime?>, bool>> permissions)
{
storage.Set(pair.Key, permissions
.Select(p =>
new SettingsStorage()
.Set("Permission", p.Key)
.Set("Settings", p.Value
.Select(p1 =>
new SettingsStorage()
.Set("Name", p1.Key.Item1)
.Set("Param", p1.Key.Item2)
.Set("Extra", p1.Key.Item3)
.Set("Till", p1.Key.Item4)
.Set("IsEnabled", p1.Value)
).ToArray()
)
).ToArray()
);
}
else if (value is IEnumerable<RefPair<Guid, string>> pairs)
{
storage.Set(pair.Key, pairs.Select(p => p.ToStorage()).ToArray());
}
else if (value is SettingsStorage s1)
TryFix(s1);
else if (value is IEnumerable<SettingsStorage> set)
{
foreach (var item in set)
TryFix(item);
}
}
}
if (value is SettingsStorage s)
TryFix(s);
else if (value is IEnumerable<SettingsStorage> set)
{
foreach (var item in set)
TryFix(item);
}
try
{
// !!! serialize and deserialize (check our new serializer)
value = defSer.Deserialize(defSer.Serialize(value));
// saving data in new format
defSer.Serialize(value, defFile);
// make backup only if everything is ok
legacyFile.MoveToBackup();
}
catch (Exception ex)
{
ex.LogError();
}
}
else
value = defSer.Deserialize(defFile);
return value;
}
/// <summary>
/// Deserialize value from the serialized data.
/// </summary>
/// <typeparam name="T">Value type.</typeparam>
/// <param name="data">Serialized data.</param>
/// <returns>Value.</returns>
public static T DeserializeWithMigration<T>(this byte[] data)
=> (T)CreateSerializer<T>().DeserializeWithMigration(data);
/// <summary>
/// Deserialize value from the serialized data.
/// </summary>
/// <param name="serializer">Serializer.</param>
/// <param name="data">Serialized data.</param>
/// <returns>Value.</returns>
public static object DeserializeWithMigration(this ISerializer serializer, byte[] data)
{
if (serializer is null)
throw new ArgumentNullException(nameof(serializer));
try
{
return serializer.Deserialize(data);
}
catch
{
#pragma warning disable CS0618 // Type or member is obsolete
var xmlSer = typeof(XmlSerializer<>).Make(serializer.Type).CreateInstance<ISerializer>();
#pragma warning restore CS0618 // Type or member is obsolete
if (xmlSer.GetType() == serializer.GetType())
throw;
return xmlSer.Deserialize(data);
}
}
}
} | 29.52 | 167 | 0.660413 |
c6b8d2b3cd466d699843b4ad1fb86e101ccc464a | 2,615 | css | CSS | css/seasons.css | edivaldolluisb/Formula_1 | 0f1d84a39f648ab6af8fb3d2de2c98e8b864723f | [
"MIT"
] | null | null | null | css/seasons.css | edivaldolluisb/Formula_1 | 0f1d84a39f648ab6af8fb3d2de2c98e8b864723f | [
"MIT"
] | null | null | null | css/seasons.css | edivaldolluisb/Formula_1 | 0f1d84a39f648ab6af8fb3d2de2c98e8b864723f | [
"MIT"
] | null | null | null | @import url('https://fonts.googleapis.com/css2?family=Racing+Sans+One&display=swap');
#rankers_3{
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
gap: 1rem;
padding-top: 5rem;
}
/*#rankers_3 > div:nth-child(2){
height: 25rem;
padding-bottom: 2rem;
}*/
.driver_rank {
background-color: #fff;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 15rem;
height: 24rem;
transition: width 2s;
}
.driver_rank:hover {
width: 17rem;
}
.div_imagem{
position: relative;
display: grid;
place-items: center;
margin-bottom: 2rem;
}
.driver_rank img{
width: 50%;
border-radius: 50%;
margin: auto;
}
.driver_detail{
text-align: center;
color: #333536;
}
.driver_detail p:first-of-type{
text-align: center;
color: #A41F1F;
font-weight: bold;
font-size: 1.4rem;
}
.ranked_driver > p:first-of-type{
text-align: center;
width: 3rem;
height: 3rem;
border-radius: 50%;
background-color: #FFA692;
color: #A41F1F;
font-family: 'Racing Sans One', cursive;
font-size: 3rem;
}
/*sessão dois, tabela dos drivers constructors e races*/
#drivers_constructors_races{
position: relative;
display: flex;
flex-direction: column;
margin: 5rem auto 5rem;
}
#butoes_escolha_dcr{
display: flex;
flex-direction: row;
gap: 1rem;
justify-content: center;
align-items: center;
background-color: #A41F1F;
padding: 2rem ;
}
#butoes_escolha_dcr button{
border: none;
padding: 0.2rem 1.5rem;
font-weight: bold;
border-radius: 1px;
background-color: #fff;
color: #333536;
}
#butoes_escolha_dcr button:hover{
border: none;
padding: 0.2rem 1.5rem;
font-weight: bold;
border-radius: 1px;
background-color: #333536;
color: #fff;
}
/*tabelas*/
.select_item{
display: grid;
place-items: center;
padding-bottom: 2rem;
}
.select_item select{
padding: 0.5rem 2rem;
font-weight: bold;
border-radius: 2px;
background-color: #A41F1F;
color: #fff;
border: none;
}
#driver_table, #constructor_table, #race_table{
width: 100%;
color: #fff;
}
#constructor_table, #race_table{
display: none;
}
tr, td{
padding: 0.5rem;
font-weight: normal;
text-align: center;
}
th{
padding: 1rem;
}
tr:nth-child(even) {
background-color: #A41F1F;
}
/*link de outras pags*/
.link_outras_pags{
color: #fff;
}
.link_outras_pags p{
text-align: center;
margin: 1rem auto;
}
| 17.091503 | 85 | 0.634417 |
7b2e60f67cfef4a8eb88c7558129e2f2a5cb827c | 1,065 | rb | Ruby | app/models/flogiston/layout.rb | flogic/flogiston-cms | bee42188bf63e50974f152ee82c14634fdec7ba2 | [
"MIT"
] | 1 | 2016-05-09T06:02:59.000Z | 2016-05-09T06:02:59.000Z | app/models/flogiston/layout.rb | flogic/flogiston-cms | bee42188bf63e50974f152ee82c14634fdec7ba2 | [
"MIT"
] | null | null | null | app/models/flogiston/layout.rb | flogic/flogiston-cms | bee42188bf63e50974f152ee82c14634fdec7ba2 | [
"MIT"
] | null | null | null | class Flogiston::Layout < Flogiston::AbstractPage
validates_uniqueness_of :handle
validates_presence_of :handle
def self.default
first(:conditions => { :default => true })
end
def make_default!
Layout.update_all({ :default => false }, "id <> #{self.id}")
update_attributes!(:default => true)
end
def full_contents(replacements = {})
self.class.expand(contents, replacements)
end
### for ActionView Layout fakery
def path_without_format_and_extension
"<Layout '#{handle}'>"
end
def render_template(view, local_assigns = {})
renderer = ActionView::Template.new('')
renderer.instance_eval <<-eval_string
def source
#{full_contents.inspect}
end
def recompile?
true
end
def extension
#{format.inspect}
end
eval_string
renderer.render_template(view, local_assigns)
end
def refresh
reload unless new_record?
self
end
###
### for ActionView Template (view) fakery
def exempt_from_layout?
false
end
###
end
| 20.09434 | 64 | 0.652582 |
8e67e84f3b1ed13a5a0c8dbf7d4d5f337cf2697c | 651 | rb | Ruby | app/jobs/dttp/sync_accounts_job.rb | DFE-Digital/register-trainee-teacher-data | 4e71073f39a3f76409786a201ffc209df7e84173 | [
"MIT"
] | null | null | null | app/jobs/dttp/sync_accounts_job.rb | DFE-Digital/register-trainee-teacher-data | 4e71073f39a3f76409786a201ffc209df7e84173 | [
"MIT"
] | 70 | 2020-08-25T08:52:41.000Z | 2020-10-08T08:49:20.000Z | app/jobs/dttp/sync_accounts_job.rb | DFE-Digital/register-trainee-teacher-data | 4e71073f39a3f76409786a201ffc209df7e84173 | [
"MIT"
] | null | null | null | # frozen_string_literal: true
module Dttp
class SyncAccountsJob < ApplicationJob
queue_as :dttp
def perform(request_uri = nil)
@account_list = RetrieveAccounts.call(request_uri: request_uri)
Account.upsert_all(account_attributes, unique_by: :dttp_id)
Dttp::SyncAccountsJob.perform_later(next_page_url) if next_page?
end
private
attr_reader :account_list
def account_attributes
Parsers::Account.to_account_attributes(accounts: account_list[:items])
end
def next_page_url
account_list[:meta][:next_page_url]
end
def next_page?
next_page_url.present?
end
end
end
| 20.34375 | 76 | 0.725038 |
a14d03c58320380dbeef43480fca5e9da7898633 | 2,201 | ts | TypeScript | src/visualizations/symbol.ts | sgratzl/cytoscape.js-overlays | 4b0c36a6f10b62885e66d53a803e328353232c44 | [
"MIT"
] | 10 | 2020-07-20T15:50:07.000Z | 2022-01-03T10:48:08.000Z | src/visualizations/symbol.ts | sgratzl/cytoscape.js-overlays | 4b0c36a6f10b62885e66d53a803e328353232c44 | [
"MIT"
] | 2 | 2021-03-30T07:51:31.000Z | 2021-05-26T20:25:23.000Z | src/visualizations/symbol.ts | sgratzl/cytoscape.js-overlays | 4b0c36a6f10b62885e66d53a803e328353232c44 | [
"MIT"
] | 1 | 2021-09-24T22:21:43.000Z | 2021-09-24T22:21:43.000Z | import {
symbolCircle,
symbolCross,
symbolDiamond,
symbolSquare,
symbolStar,
symbolTriangle,
SymbolType,
symbolWye,
} from 'd3-shape';
import { INodeFunction, IVisualization } from './interfaces';
import { resolveFunction } from './utils';
const symbols = {
circle: symbolCircle,
cross: symbolCross,
diamond: symbolDiamond,
square: symbolSquare,
star: symbolStar,
triangle: symbolTriangle,
wye: symbolWye,
};
export interface ITextSymbol {
text: string;
font?: string;
}
export interface ISymbolOptions {
symbol: INodeFunction<keyof typeof symbols | CanvasImageSource | SymbolType | ITextSymbol | null>;
color: INodeFunction<string | null>;
}
function isSymbol(s: any): s is SymbolType {
return typeof (s as SymbolType).draw === 'function';
}
function isTextSymbol(s: any): s is ITextSymbol {
return typeof (s as ITextSymbol).text === 'string';
}
export function renderSymbol(options: Partial<ISymbolOptions> = {}): IVisualization {
const o = Object.assign(
{
symbol: 'circle',
color: '#cccccc',
} as ISymbolOptions,
options
);
const symbol = resolveFunction(o.symbol);
const backgroundColor = resolveFunction(o.color);
const r: IVisualization = (ctx, node, dim) => {
const bg = backgroundColor(node);
const s = symbol(node);
if (bg == null || s == null) {
return;
}
ctx.fillStyle = bg;
if (isSymbol(s) || typeof s === 'string') {
const sym = isSymbol(s) ? s : symbols[s as keyof typeof symbols] || symbolCircle;
ctx.translate(dim.width / 2, dim.height / 2);
ctx.beginPath();
sym.draw(ctx, 0.5 * (dim.width * dim.height));
ctx.fill();
ctx.translate(-dim.width / 2, -dim.height / 2);
} else if (isTextSymbol(s)) {
ctx.save();
if (s.font) {
ctx.font = s.font;
}
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(s.text, dim.width / 2, dim.height / 2);
ctx.restore();
} else {
// image source
ctx.drawImage(s as CanvasImageSource, 0, 0, dim.width, dim.height);
}
};
r.defaultHeight = 8;
r.defaultWidth = 8;
r.defaultPosition = 'top-left';
return r;
}
| 25.011364 | 100 | 0.636075 |
f41f62b51c168260824700040ea0a4d5d2b47bf1 | 1,347 | cs | C# | Dictionaries, Lambda and LINQ/1. Phonebook - Exercises/Phonebook.cs | alexandrateneva/Programming-Fundamentals-SoftUni | 714fa8b04f97ece21f4eeb04868c741148c180fb | [
"MIT"
] | null | null | null | Dictionaries, Lambda and LINQ/1. Phonebook - Exercises/Phonebook.cs | alexandrateneva/Programming-Fundamentals-SoftUni | 714fa8b04f97ece21f4eeb04868c741148c180fb | [
"MIT"
] | null | null | null | Dictionaries, Lambda and LINQ/1. Phonebook - Exercises/Phonebook.cs | alexandrateneva/Programming-Fundamentals-SoftUni | 714fa8b04f97ece21f4eeb04868c741148c180fb | [
"MIT"
] | null | null | null | namespace _1.Phonebook___Exercises
{
using System;
using System.Collections.Generic;
using System.Linq;
public class Phonebook
{
public static void Main()
{
string command = null;
var result = new List<string>();
var phoneBook = new Dictionary<string, string>();
while (command != "END")
{
var listOfCommand = Console.ReadLine().Split(' ').ToList();
command = listOfCommand[0];
if (command == "A")
{
phoneBook[listOfCommand[1]] = listOfCommand[2];
}
else if (command == "S")
{
if (phoneBook.ContainsKey(listOfCommand[1]))
{
result.Add($"{listOfCommand[1]} -> {phoneBook[listOfCommand[1]]}");
}
else
{
result.Add($"Contact {listOfCommand[1]} does not exist.");
}
}
else if (command == "END")
{
for (int i = 0; i < result.Count; i++)
{
Console.WriteLine(result[i]);
}
}
}
}
}
} | 29.933333 | 91 | 0.393467 |
8ef3b95ef49e940a84c5c863cdaabb149eccd46e | 395 | kt | Kotlin | app/src/main/java/app/foodtracker/de/foodtracker/Presenter/Extensions.kt | jofranz/FoodTrackerAndroid | fa38e89dbf93b6e40c0038380542e279a3cc644f | [
"FTL"
] | 1 | 2018-01-24T17:51:10.000Z | 2018-01-24T17:51:10.000Z | app/src/main/java/app/foodtracker/de/foodtracker/Presenter/Extensions.kt | jofranz/FoodTrackerAndroid | fa38e89dbf93b6e40c0038380542e279a3cc644f | [
"FTL"
] | null | null | null | app/src/main/java/app/foodtracker/de/foodtracker/Presenter/Extensions.kt | jofranz/FoodTrackerAndroid | fa38e89dbf93b6e40c0038380542e279a3cc644f | [
"FTL"
] | null | null | null | package app.foodtracker.de.foodtracker.Presenter
import android.support.annotation.LayoutRes
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
/**
* Created by normen on 06.11.17.
*/
fun ViewGroup.inflate(@LayoutRes layoutRes: Int, attachToRoot: Boolean = false): View {
return LayoutInflater.from(context).inflate(layoutRes, this,attachToRoot)
}
| 28.214286 | 87 | 0.794937 |
5ae8fb5496af06de9414c30c5083bf9ef92e1ad6 | 5,651 | cs | C# | framework/Furion/DataValidation/Extensions/DataValidationExtensions.cs | dannylincn/Furion | 44a18b894a9bba045179a8c90801ff500f5c9d78 | [
"Apache-2.0"
] | 1 | 2021-06-10T10:11:07.000Z | 2021-06-10T10:11:07.000Z | framework/Furion/DataValidation/Extensions/DataValidationExtensions.cs | dannylincn/Furion | 44a18b894a9bba045179a8c90801ff500f5c9d78 | [
"Apache-2.0"
] | null | null | null | framework/Furion/DataValidation/Extensions/DataValidationExtensions.cs | dannylincn/Furion | 44a18b894a9bba045179a8c90801ff500f5c9d78 | [
"Apache-2.0"
] | null | null | null | // -----------------------------------------------------------------------------
// 让 .NET 开发更简单,更通用,更流行。
// Copyright © 2020-2021 Furion, 百小僧, Baiqian Co.,Ltd.
//
// 框架名称:Furion
// 框架作者:百小僧
// 框架版本:2.8.3
// 源码地址:Gitee: https://gitee.com/dotnetchina/Furion
// Github:https://github.com/monksoul/Furion
// 开源协议:Apache-2.0(https://gitee.com/dotnetchina/Furion/blob/master/LICENSE)
// -----------------------------------------------------------------------------
using Furion.DependencyInjection;
using Furion.FriendlyException;
using Furion.JsonSerialization;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text.RegularExpressions;
namespace Furion.DataValidation
{
/// <summary>
/// 数据验证拓展类
/// </summary>
[SkipScan]
public static class DataValidationExtensions
{
/// <summary>
/// 拓展方法,验证类类型对象
/// </summary>
/// <param name="obj">对象实例</param>
/// <param name="validateAllProperties">是否验证所有属性</param>
/// <returns>验证结果</returns>
public static DataValidationResult TryValidate(this object obj, bool validateAllProperties = true)
{
return DataValidator.TryValidateObject(obj, validateAllProperties);
}
/// <summary>
/// 拓展方法,验证单个值
/// </summary>
/// <param name="value">单个值</param>
/// <param name="validationAttributes">验证特性</param>
/// <returns></returns>
public static DataValidationResult TryValidate(this object value, params ValidationAttribute[] validationAttributes)
{
return DataValidator.TryValidateValue(value, validationAttributes);
}
/// <summary>
/// 拓展方法,验证单个值
/// </summary>
/// <param name="value">单个值</param>
/// <param name="validationTypes">验证类型</param>
/// <returns></returns>
public static DataValidationResult TryValidate(this object value, params object[] validationTypes)
{
return DataValidator.TryValidateValue(value, validationTypes);
}
/// <summary>
/// 拓展方法,验证单个值
/// </summary>
/// <param name="value">单个值</param>
/// <param name="validationOptionss">验证逻辑</param>
/// <param name="validationTypes">验证类型</param>
/// <returns></returns>
public static DataValidationResult TryValidate(this object value, ValidationPattern validationOptionss, params object[] validationTypes)
{
return DataValidator.TryValidateValue(value, validationOptionss, validationTypes);
}
/// <summary>
/// 拓展方法,验证类类型对象
/// </summary>
/// <param name="obj">对象实例</param>
/// <param name="validateAllProperties">是否验证所有属性</param>
public static void Validate(this object obj, bool validateAllProperties = true)
{
DataValidator.TryValidateObject(obj, validateAllProperties).ThrowValidateFailedModel();
}
/// <summary>
/// 拓展方法,验证单个值
/// </summary>
/// <param name="value">单个值</param>
/// <param name="validationAttributes">验证特性</param>
public static void Validate(this object value, params ValidationAttribute[] validationAttributes)
{
DataValidator.TryValidateValue(value, validationAttributes).ThrowValidateFailedModel();
}
/// <summary>
/// 拓展方法,验证单个值
/// </summary>
/// <param name="value">单个值</param>
/// <param name="validationTypes">验证类型</param>
public static void Validate(this object value, params object[] validationTypes)
{
DataValidator.TryValidateValue(value, validationTypes).ThrowValidateFailedModel();
}
/// <summary>
/// 拓展方法,验证单个值
/// </summary>
/// <param name="value">单个值</param>
/// <param name="validationOptionss">验证逻辑</param>
/// <param name="validationTypes">验证类型</param>
public static void Validate(this object value, ValidationPattern validationOptionss, params object[] validationTypes)
{
DataValidator.TryValidateValue(value, validationOptionss, validationTypes).ThrowValidateFailedModel();
}
/// <summary>
/// 拓展方法,验证单个值
/// </summary>
/// <param name="value">单个值</param>
/// <param name="regexPattern">正则表达式</param>
/// <param name="regexOptions">正则表达式选项</param>
/// <returns></returns>
public static bool TryValidate(this object value, string regexPattern, RegexOptions regexOptions = RegexOptions.None)
{
return DataValidator.TryValidateValue(value, regexPattern, regexOptions);
}
/// <summary>
/// 直接抛出异常信息
/// </summary>
/// <param name="dataValidationResult"></param>
public static void ThrowValidateFailedModel(this DataValidationResult dataValidationResult)
{
if (!dataValidationResult.IsValid)
throw Oops.Oh("[Validation]" + JSON.Serialize(
dataValidationResult.ValidationResults
.Select(u => new {
MemberNames = u.MemberNames.Any() ? u.MemberNames : new[] { $"{dataValidationResult.MemberOrValue}" },
u.ErrorMessage
})
.OrderBy(u => u.MemberNames.First())
.GroupBy(u => u.MemberNames.First())
.Select(u =>
new ValidateFailedModel(u.Key,
u.Select(c => c.ErrorMessage).ToArray()))));
}
}
} | 38.705479 | 144 | 0.580959 |
da33b09796e5c22d4e1c22b28455b0408f8dd58e | 551 | php | PHP | application/controllers/Detail.php | Elijah8802/projectshark | c7d946734caac5e4e77c66f0177b6443f0650af0 | [
"MIT"
] | null | null | null | application/controllers/Detail.php | Elijah8802/projectshark | c7d946734caac5e4e77c66f0177b6443f0650af0 | [
"MIT"
] | null | null | null | application/controllers/Detail.php | Elijah8802/projectshark | c7d946734caac5e4e77c66f0177b6443f0650af0 | [
"MIT"
] | null | null | null | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Detail extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('DetailModel');//Model insert here
}
public function index()
{
$id = (int)$_GET["id"];
//$id = 37013900; //sample shark id
$result['allSharkDetail']=$this->DetailModel->getAllSharkDetail();
$result['getSharkDetail'] = $this->DetailModel->getSharkDetailByID($id);
$this->load->view('template/header');
$this->load->view('detail',$result);
}
}
| 22.04 | 74 | 0.676951 |
79cf0885876660c8c0bfca9fad8c8c9528526052 | 15,879 | php | PHP | resources/views/dashboard/orders/show.blade.php | dev3bbas/so3rat | fa42bf0ac2a61608fef7b3753eee9352e15d1db4 | [
"MIT"
] | null | null | null | resources/views/dashboard/orders/show.blade.php | dev3bbas/so3rat | fa42bf0ac2a61608fef7b3753eee9352e15d1db4 | [
"MIT"
] | null | null | null | resources/views/dashboard/orders/show.blade.php | dev3bbas/so3rat | fa42bf0ac2a61608fef7b3753eee9352e15d1db4 | [
"MIT"
] | null | null | null | @extends('layouts.dashboard')
@section('content')
<div class="app-content content">
<div class="content-wrapper">
<div class="content-header row">
<div class="content-header-left col-md-6 col-12 mb-2">
<div class="row breadcrumbs-top">
<div class="breadcrumb-wrapper col-12">
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="{{route('dashboard.home')}}">
{{__('global.home')}}
</a>
</li>
<li class="breadcrumb-item active">
{{__('dashboard/order.title')}}
</li>
</ol>
</div>
</div>
</div>
<div class="content-header-right col-md-6 col-12">
<div class="btn-group float-md-right" role="group"
aria-label="Button group with nested dropdown">
<button
class="btn btn-info round dropdown-toggle dropdown-menu-right box-shadow-2 px-2 mb-1"
id="btnGroupDrop1" type="button" data-toggle="dropdown"
aria-haspopup="true"
aria-expanded="false"><i class="ft-settings icon-left"></i>
{{__('global.actions')}}</button>
<div class="dropdown-menu" aria-labelledby="btnGroupDrop1">
<form
action="{{ route('dashboard.orders.delete', $order->id) }}"
method="POST"
onsubmit="return confirm('{{ __('global.areYouSure') }}');"
style="display: inline-block;">
@csrf
<input type="hidden" name="_method" value="DELETE">
<a href="#" class="dropdown-item"
onclick="$(this).parent().submit()">
<i class="ft-trash-2"></i>
{{__('global.delete')}}
</a>
</form>
{{-- <a href="{{route('dashboard.orders.change_status',$order->id)}}"--}}
{{-- class="dropdown-item"--}}
{{-- onclick="return confirm('{{__('dashboard/order.change_status')}}');">--}}
{{-- @if($order->status == 0)--}}
{{-- <i class="ft-lock primary"></i>--}}
{{-- {{__('global.activate')}}--}}
{{-- @else--}}
{{-- <i class="ft-unlock primary"></i>--}}
{{-- {{__('global.deactivate')}}--}}
{{-- @endif--}}
{{-- </a>--}}
</div>
</div>
</div>
</div>
<div class="content-body">
<!-- Basic form layout section start -->
<section id="basic-form-layouts">
<div class="row match-height">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h4 class="card-title" id="basic-layout-form">
{{__('dashboard/order.show')}}
</h4>
<a class="heading-elements-toggle"><i
class="la la-ellipsis-v font-medium-3"></i></a>
<div class="heading-elements">
<ul class="list-inline mb-0">
<li><a data-action="collapse"><i class="ft-minus"></i></a></li>
<li><a data-action="reload"><i class="ft-rotate-cw"></i></a></li>
<li><a data-action="expand"><i class="ft-maximize"></i></a></li>
<li><a data-action="close"><i class="ft-x"></i></a></li>
</ul>
</div>
</div>
@include('dashboard.includes.alerts.success')
@include('dashboard.includes.alerts.errors')
<div class="card-body">
<div class="mb-2">
<div class="card-content collapse show">
<div class="card-body card-dashboard">
<div id="accordionWrap5" role="tablist"
aria-multiselectable="true">
<div class="card collapse-icon accordion-icon-rotate">
<div class="row">
<div class="card-content collapse show">
<div class="table-responsive">
<table class="table table-borderless mb-0">
<tbody>
<tr>
<td>{{__('user.name')}}:</td>
<td>
@foreach($users as $user)
@if($user->id == $order->user_id)
{{$user->name}}
@endif
@endforeach
</td>
</tr>
<tr>
<td>{{__('dashboard/order.day')}}:</td>
@foreach($timeSlots as $timeSlot)
@if($timeSlot->id == $order->time_slot_id)
<td>
{{$timeSlot->day}}
</td>
</tr>
<tr>
<td>{{__('dashboard/order.time')}}</td>
<td>
{{$timeSlot->from}} : {{$timeSlot->to}}
</td>
@endif
@endforeach
</tr>
<tr>
<td>{{__('dashboard/visit.name')}}:</td>
@foreach($visits as $visit)
@if ($visit->id == $order->visit_id)
<td>{{$visit->name}}</td>
@endif
@endforeach
</tr>
<tr>
<td>{{__('dashboard/order.firstname')}}</td>
<td>{{$order->first_name}}</td>
</tr>
<tr>
<td>{{__('dashboard/order.lastname')}}</td>
<td>{{$order->last_name}}</td>
</tr>
<tr>
<td>{{__('dashboard/order.phone')}}</td>
<td>{{$order->phone}}</td>
</tr>
<tr>
<td>{{__('dashboard/order.description')}}</td>
<td>{{$order->description}}</td>
</tr>
<tr>
<td>{{__('dashboard/order.building_type')}}</td>
<td>{{$order->building_type}}</td>
</tr>
<tr>
<td>{{__('dashboard/order.address')}}</td>
<td>{{$order->address}}</td>
</tr>
<tr>
<td>{{__('dashboard/order.visit_at')}}</td>
<td>{{$order->visit_at}}</td>
</tr>
<tr>
<td>{{__('dashboard/order.status')}}:</td>
@if($order->status == '1' )
<td><span
class="badge badge-default badge-success pt-1 pb-1"> {{__('global.complete')}}</span>
</td>
@else
<td><span
class="badge badge-default badge-danger pt-1 pb-1"> {{__('global.uncomplete')}}</span>
</td>
@endif
</tr>
<tr>
<td>{{__('dashboard/order.description')}}:
</td>
<td>{{$order->description}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<nav class="mb-3">
<div class="nav nav-tabs">
</div>
</nav>
<div class="tab-content">
</div>
</div>
</div>
</div>
</div>
</section>
<!-- // Basic form layout section end -->
</div>
</div>
</div>
@endsection
@section('vendor')
<script src="{{asset('assets/dashboard/vendors/js/forms/toggle/bootstrap-switch.min.js')}}"
type="text/javascript"></script>
<script src="{{asset('assets/dashboard/vendors/js/forms/toggle/bootstrap-checkbox.min.js')}}"
type="text/javascript"></script>
<script src="{{asset('assets/dashboard/vendors/js/forms/toggle/switchery.min.js')}}"
type="text/javascript"></script>
<script src="{{asset('assets/dashboard/js/scripts/forms/switch.js')}}" type="text/javascript"></script>
<script src="{{asset('assets/dashboard/vendors/js/forms/select/select2.full.min.js')}}"
type="text/javascript"></script>
<script src="{{asset('assets/dashboard/js/scripts/forms/select/form-select2.js')}}" type="text/javascript"></script>
@endsection
| 72.177273 | 174 | 0.227218 |
e3dc2ae6572c768e346b8d34e556ec35d94a0d9b | 3,264 | lua | Lua | scripts/AC02-JP/c100290008.lua | Zayelion/ygopro-pre-script | c1d06d8824aa8398023cd41d9207d4704580eb3c | [
"Unlicense"
] | null | null | null | scripts/AC02-JP/c100290008.lua | Zayelion/ygopro-pre-script | c1d06d8824aa8398023cd41d9207d4704580eb3c | [
"Unlicense"
] | 2 | 2016-01-07T20:41:53.000Z | 2016-01-08T06:25:15.000Z | scripts/AC02-JP/c100290008.lua | Zayelion/ygopro-pre-script | c1d06d8824aa8398023cd41d9207d4704580eb3c | [
"Unlicense"
] | null | null | null | --ENシャッフル
--
--Script by Trishula9 & mercury233
function c100290008.initial_effect(c)
aux.AddCodeList(c,89943723)
aux.AddSetNameMonsterList(c,0x3008)
--spsummon
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_TODECK+CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCountLimit(1,100290008)
e1:SetTarget(c100290008.sptg)
e1:SetOperation(c100290008.spop)
c:RegisterEffect(e1)
--draw
local e2=Effect.CreateEffect(c)
e2:SetCategory(CATEGORY_TODECK+CATEGORY_DRAW)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_GRAVE)
e2:SetCountLimit(1,100290008+100)
e2:SetCost(aux.bfgcost)
e2:SetTarget(c100290008.drtg)
e2:SetOperation(c100290008.drop)
c:RegisterEffect(e2)
end
function c100290008.tdfilter(c,e,tp)
return c:IsFaceup() and c:IsSetCard(0x3008,0x1f) and c:IsType(TYPE_MONSTER)
and c:IsAbleToDeck() and Duel.GetMZoneCount(tp,c)>0
and Duel.IsExistingMatchingCard(c100290008.spfilter,tp,LOCATION_DECK,0,1,nil,e,tp,c:GetCode())
end
function c100290008.spfilter(c,e,tp,code)
return c:IsSetCard(0x3008,0x1f) and not c:IsCode(code) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c100290008.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c100290008.tdfilter,tp,LOCATION_MZONE,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_TODECK,nil,1,tp,LOCATION_MZONE)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c100290008.spop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local tc=Duel.SelectMatchingCard(tp,c100290008.tdfilter,tp,LOCATION_MZONE,0,1,1,nil,e,tp):GetFirst()
if not tc then return end
local code=tc:GetCode()
if Duel.SendtoDeck(tc,nil,SEQ_DECKSHUFFLE,REASON_EFFECT)>0 and tc:IsLocation(LOCATION_DECK+LOCATION_EXTRA)
and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c100290008.spfilter,tp,LOCATION_DECK,0,1,1,nil,e,tp,code)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
end
function c100290008.filter(c)
return c:IsType(TYPE_MONSTER) and c:IsAbleToDeck() and (c:IsSetCard(0x3008,0x1f) or c:IsCode(89943723))
end
function c100290008.gcheck(g)
return #g==1 and g:GetFirst():IsCode(89943723) or aux.gfcheck(g,Card.IsSetCard,0x3008,0x1f)
end
function c100290008.drtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then
if not Duel.IsPlayerCanDraw(tp,1) then return false end
local g=Duel.GetMatchingGroup(c100290008.filter,tp,LOCATION_GRAVE,0,nil)
return g:CheckSubGroup(c100290008.gcheck,1,2)
end
Duel.SetOperationInfo(0,CATEGORY_TODECK,nil,1,tp,LOCATION_GRAVE)
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1)
end
function c100290008.drop(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(aux.NecroValleyFilter(c100290008.filter),tp,LOCATION_GRAVE,0,nil)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local sg=g:SelectSubGroup(tp,c100290008.gcheck,false,1,2)
if sg and Duel.SendtoDeck(sg,nil,SEQ_DECKSHUFFLE,REASON_EFFECT)>0 then
local og=Duel.GetOperatedGroup()
if not og:IsExists(Card.IsLocation,1,nil,LOCATION_DECK) then return end
Duel.ShuffleDeck(tp)
Duel.BreakEffect()
Duel.Draw(tp,1,REASON_EFFECT)
end
end
| 40.296296 | 107 | 0.798407 |
21ce7130a6038b168dee6d9536818a7d0273af34 | 1,837 | js | JavaScript | public/index.js | SaiSrichandra/Link-Previwer | 64468c7490f5102705270e9442e7d9a0da03a2d4 | [
"MIT"
] | null | null | null | public/index.js | SaiSrichandra/Link-Previwer | 64468c7490f5102705270e9442e7d9a0da03a2d4 | [
"MIT"
] | null | null | null | public/index.js | SaiSrichandra/Link-Previwer | 64468c7490f5102705270e9442e7d9a0da03a2d4 | [
"MIT"
] | null | null | null | const getInfo = async (e) => {
e.preventDefault();
url = textBox.value
if (! url.startsWith("http")) {
url = "http://" + url
}
if (url){
try {
resp = await fetch('http://localhost:3000/scrape', {
method : "POST",
body : JSON.stringify({url}),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
} catch (error) {
console.error("unsuccessful post")
}
jsonData = await resp.json()
// console.log(jsonData)
}
renderCard(jsonData)
}
const resetCard = () => {
cardImg.src = "https://i.stack.imgur.com/y9DpT.jpg"
cardDesc.textContent = "Example ( Previews info about the links )"
cardTitle.textContent = "Link Previewer"
cardUrl.textContent = "Link Previewer"
cardUrl.href = "#"
cardKeyword.textContent = ""
}
const renderCard = (jsonData) => {
resetCard();
if (jsonData.img){
cardImg.src = jsonData.img;
cardImg.classList.remove('hidden')
}
cardDesc.textContent = jsonData.desc
cardTitle.textContent = jsonData.title
cardUrl.textContent = jsonData.sitename || jsonData.url || jsonData.orgURL
cardUrl.href = jsonData.url || jsonData.orgURL
if (jsonData.keywords) {
keywords = jsonData.keywords.split(",")
keywords = keywords.map(key => {
content = key.trim()
const li = document.createElement('li')
li.textContent = content
li.classList.add("bg-red-400", "px-2" , "py-1", "rounded-md");
cardKeyword.appendChild(li)
})
}
}
button.addEventListener('click', getInfo) | 27.41791 | 79 | 0.534023 |
437b16b2e30cc7f2f5b0d36c6ac0a5afd1eea29f | 418 | tsx | TypeScript | src/components/Naver/NaverDetailsModal/ImageLoader/index.tsx | gustavomaltez/navedex-frontend-challenge | d5d54281b9dbbc08e603342de36bcddb30d45a24 | [
"MIT"
] | 1 | 2021-03-06T18:06:29.000Z | 2021-03-06T18:06:29.000Z | src/components/Naver/NaverDetailsModal/ImageLoader/index.tsx | gustavomaltez/navedex-frontend-challenge | d5d54281b9dbbc08e603342de36bcddb30d45a24 | [
"MIT"
] | null | null | null | src/components/Naver/NaverDetailsModal/ImageLoader/index.tsx | gustavomaltez/navedex-frontend-challenge | d5d54281b9dbbc08e603342de36bcddb30d45a24 | [
"MIT"
] | null | null | null | import React from 'react';
import ContentLoader from 'react-content-loader';
const ImageLoader: React.FC = () => {
return (
<ContentLoader
speed={2}
viewBox="0 0 400 400"
style={{ width: '100%' }}
backgroundColor="#f3f3f3"
foregroundColor="#ecebeb"
>
<rect x="20" y="20" rx="2" ry="2" width="360" height="360" />
</ContentLoader>
);
};
export default ImageLoader;
| 22 | 67 | 0.595694 |
7aabadfe87cc23bc913f2f4e724856dccb2996da | 8,688 | sql | SQL | src/main/resources/db/migration/V001__initial-creation-of-tables.sql | GabrielDiasgd/Store | b12059cb6ff632d8ec18e58a2a9a52691cc9535d | [
"Apache-2.0"
] | 2 | 2021-02-11T17:29:27.000Z | 2022-01-03T20:05:22.000Z | src/main/resources/db/migration/V001__initial-creation-of-tables.sql | GabrielDiasgd/Store | b12059cb6ff632d8ec18e58a2a9a52691cc9535d | [
"Apache-2.0"
] | null | null | null | src/main/resources/db/migration/V001__initial-creation-of-tables.sql | GabrielDiasgd/Store | b12059cb6ff632d8ec18e58a2a9a52691cc9535d | [
"Apache-2.0"
] | null | null | null | CREATE TABLE IF NOT EXISTS state (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
`date_creation` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`date_update` DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS city (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
`state_id` bigint unsigned NOT NULL,
`date_creation` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`date_update` DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
INDEX `fk_city_state_id` (`state_id` ASC),
CONSTRAINT `fk_city_state`
FOREIGN KEY (`state_id`)
REFERENCES state (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS address (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`street` VARCHAR(60) NOT NULL,
`number` VARCHAR(10) NOT NULL,
`neighborhood` VARCHAR(60) NOT NULL,
`complement` VARCHAR(60) NULL,
`cep` VARCHAR(45) NOT NULL,
`city_id` bigint unsigned NOT NULL,
`date_creation` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`date_update` DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
index `fk_address_city_id` (`city_id` ASC),
constraint `fk_address_city`
foreign key (`city_id`)
references city(`id`)
)
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS provider (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
`cnpj` VARCHAR(45) NOT NULL,
`email` VARCHAR(45) NULL,
`phone` varchar(12) null,
`cell_phone` varchar(12) null,
`sac` varchar(45) null,
`site` varchar(30) null,
`contact` varchar (45),
`note` VARCHAR(90) NULL,
`active` TINYINT NOT NULL,
`address_id` bigint unsigned NOT NULL,
`date_creation` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`date_update` DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
index `fk_povider_address_id` (`address_id` ASC),
CONSTRAINT `fk_provider_address`
Foreign key (`address_id`)
references address(`id`)
)
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS category (
`id` bigint unsigned NOT NULL auto_increment,
`description` VARCHAR(45) NOT NULL,
`date_creation` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`date_update` DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS product (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
`description` VARCHAR(120) NULL,
`stock` bigint unsigned NULL,
`price` DECIMAL(10,4) NULL,
`buy_price` DECIMAL(10,4) NULL,
`active` TINYINT(1) NOT NULL,
`date_last_sale` DATETIME NULL,
`date_last_purchase` DATETIME NULL,
`date_creation` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`date_update` DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
`provider_id` bigint unsigned NOT NULL,
`category_id` bigint unsigned NOT NULL,
PRIMARY KEY (`id`),
INDEX `fk_product_provider_id` (`provider_id` ASC),
INDEX `fk_product_category_id` (`category_id` ASC),
CONSTRAINT `fk_product_provider`
FOREIGN KEY (`provider_id`)
REFERENCES provider(`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_product_category`
FOREIGN KEY (`category_id`)
REFERENCES category (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS client (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`name` VARCHAR(70) NOT NULL,
`cpf` VARCHAR(20) NULL,
`rg` VARCHAR(15) NULL,
`birth_date` DATETIME NULL,
`email` VARCHAR(60) NULL,
`active` TINYINT(1) NOT NULL,
`note` VARCHAR(100) NULL,
`client_type` TINYINT(3) NOT NULL,
`client_status` TINYINT(3) NOT NULL,
`date_creation` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`date_update` DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS profile (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`description` VARCHAR(45) NOT NULL,
`date_creation` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`date_update` DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS user (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`name` VARCHAR(60) NOT NULL,
`cpf` VARCHAR(20) NULL,
`rg` VARCHAR(15) NULL,
`email` VARCHAR(60) NOT NULL,
`password` VARCHAR(120) NOT NULL,
`active` TINYINT(1) NOT NULL,
`date_creation` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`date_update` DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
`profile_id` BIGINT unsigned NOT NULL,
PRIMARY KEY (`id`),
INDEX `fk_user_profile_id` (`profile_id` ASC),
CONSTRAINT `fk_user_profile`
FOREIGN KEY (`profile_id`)
REFERENCES profile (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS sale (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`date_sale` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`subtotal` DECIMAL(10,4) NOT NULL,
`total_value` DECIMAL(10,4) NOT NULL,
`code_sale` VARCHAR(45) NULL,
`status_sale` TINYINT(2) NULL,
`change` DECIMAL(10,4) NULL,
`client_id` bigint unsigned NOT NULL,
`user_id` bigint unsigned NOT NULL,
PRIMARY KEY (`id`),
INDEX `fk_sale_client_id` (`client_id` ASC) ,
INDEX `fk_sale_user_id` (`user_id` ASC),
CONSTRAINT `fk_sale_client`
FOREIGN KEY (`client_id`)
REFERENCES client (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_sale_user`
FOREIGN KEY (`user_id`)
REFERENCES user (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS product_sale (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`product_id` bigint unsigned NOT NULL,
`sale_id` bigint unsigned NOT NULL,
`unitary_value` DECIMAL(10,4) NOT NULL,
`total_value` DECIMAL(10,4) NOT NULL,
`quantity` bigint NOT NULL,
INDEX `fk_product_has_sale_sale_id` (`sale_id` ASC) ,
INDEX `fk_product_has_sale_product_id` (`product_id` ASC),
PRIMARY KEY (`id`),
CONSTRAINT `fk_product_has_sale_product`
FOREIGN KEY (`product_id`)
REFERENCES product (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_product_has_sale_sale`
FOREIGN KEY (`sale_id`)
REFERENCES sale (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS client_address (
`client_id` bigint unsigned NOT NULL,
`address_id` bigint unsigned NOT NULL,
INDEX `fk_client_has_address_address_id` (`address_id` ASC) ,
INDEX `fk_client_has_address_client_id` (`client_id` ASC),
CONSTRAINT `fk_client_has_address_client`
FOREIGN KEY (`client_id`)
REFERENCES client (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_client_has_address_address`
FOREIGN KEY (`address_id`)
REFERENCES address (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS phone (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`number` VARCHAR(20) NOT NULL,
`date_creation` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`date_update` DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS client_phone (
`client_id` bigint unsigned NOT NULL,
`phone_id` bigint unsigned NOT NULL,
INDEX `fk_client_has_phone_phone_id` (`phone_id` ASC) ,
INDEX `fk_client_has_phone_client_id` (`client_id` ASC),
CONSTRAINT `fk_client_has_phone_client`
FOREIGN KEY (`client_id`)
REFERENCES client (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_client_has_phone_phone`
FOREIGN KEY (`phone_id`)
REFERENCES phone (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS permission (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`descripiton` VARCHAR(45) NOT NULL,
`date_creation` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`date_upadate` DATETIME NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS permission_profile(
`permission_id` bigint unsigned NOT NULL,
`profile_id` bigint unsigned NOT NULL,
INDEX `fk_permission_has_perfil_perfil_id` (`profile_id` ASC),
INDEX `fk_permission_has_perfil_permission_id` (`permission_id` ASC),
CONSTRAINT `fk_permission_has_perfil_permission`
FOREIGN KEY (`permission_id`)
REFERENCES permission (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_permission_has_profile_profile`
FOREIGN KEY (`profile_id`)
REFERENCES profile (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB; | 32.297398 | 71 | 0.726519 |
31e46511955a33d6c02d8a956b47e7c216159e3b | 15,824 | ps1 | PowerShell | MC.ps1 | briantehowenerer/Maintenance-Checkup | 7a8e4e5b78db1fb800ea8442168810f11d67dc62 | [
"BSD-3-Clause"
] | 1 | 2022-03-28T16:45:23.000Z | 2022-03-28T16:45:23.000Z | MC.ps1 | briantehowenerer/Maintenance-Checkup | 7a8e4e5b78db1fb800ea8442168810f11d67dc62 | [
"BSD-3-Clause"
] | null | null | null | MC.ps1 | briantehowenerer/Maintenance-Checkup | 7a8e4e5b78db1fb800ea8442168810f11d67dc62 | [
"BSD-3-Clause"
] | null | null | null | Clear-Host
##Initialize Variables
$DesktopPath = [Environment]::GetFolderPath("Desktop")
$SecureUpdaterurl = "https://secureupdater.s3.us-east-2.amazonaws.com/downloads/SecureUpdater.msi"
$SUoutpath = "$PSScriptRoot\SecureUpdater.msi"
$DriveAdvisorurl = "https://secureupdater.s3.us-east-2.amazonaws.com/downloads/driveadviser.msi"
$DAoutpath = "$PSScriptRoot\driveadvisor.msi"
$MCZipUrl = "https://secureupdater.s3.us-east-2.amazonaws.com/downloads/mc.zip"
$MCzippath = "$PSScriptRoot\mc.zip"
$endlog = $PSScriptRoot + "\MCResults.txt"
<#
.SYNOPSIS
Main fuction
.DESCRIPTION
This is just this way in order for the script to keep the top down script style language while being able to utilize function calls
This just calls the menu so we can go from there.
Also initialize the enviornmental variables here.
.NOTES
General notes
#>
function Main {
Menu
}
<#
.SYNOPSIS
Menu to select what we are doing
.DESCRIPTION
Menu system to select what part of the process we are on. easily extnedable to add new functions as needed
#>
Function Menu {
Clear-Host
Do {
Clear-Host
Write-Host -Object 'Please choose an option'
Write-Host -Object '**********************'
Write-Host -Object 'Maitance Check Options' -ForegroundColor Yellow
Write-Host -Object '**********************'
Write-Host -Object '1. Install DriveAdvisor/SecureUpdater '
Write-Host -Object ''
Write-Host -Object '2. Download and Install MC tools '
Write-Host -Object ''
Write-Host -Object '3. Run Scripts for MC '
Write-Host -Object ''
Write-Host -Object '4. Reports --Work in Progress'
Write-Host -Object ''
Write-Host -Object '5. Cleanup --Work in Progress'
Write-Host -Object $errout
$Menu = Read-Host -Prompt '(0-5 or Q to Quit)'
switch ($Menu) {
1 {
InstallDAandSU
anyKey
}
2 {
DownloadFiles
anyKey
}
3 {
RunMCScript
anyKey
}
4 {
Reports
anyKey
}
5 {
Cleanup
anyKey
}
Q {
Exit
}
default {
$errout = 'Invalid option please try again........Try 0-5 or Q only'
}
}
}
until ($Menu -eq 'q')
}
Function InstallDAandSU {
#checks for SU and Drive Advisor, if not found installs them from the folders.
if (Test-Path -Path "C:\Program Files (x86)\Secure Updater\Secure Updater.exe") {
Write-Host "SU is already installed"
}
else {
Invoke-WebRequest -Uri $SecureUpdaterurl -OutFile $SUoutpath
Start-Process $SUoutpath "/quiet"
}
if (Test-Path -Path "C:\Program Files (x86)\Drive Adviser\Drive Adviser.exe") {
Write-Host "Drive Adviser already installed"
}
else {
Invoke-WebRequest -Uri $DriveAdvisorurl -OutFile $DAoutpath
Start-Process $DAoutpath "/quiet"
Start-Process "C:\Program Files (x86)\Drive Adviser\Drive Adviser.exe"
}
#$DAschedualedtask = schtasks -query /TN "Drive Adviser"
#if ($DAschedualedtask -notmatch "Drive") {
# Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; Invoke-Expression ((New-Object System.Net.WebClient).DownloadString('https://raw.githubusercontent.com/briantehowenerer/WorkScripts/main/DAFix.ps1'))
# Write-Host "Drive Adviser set to run at startup"
#}
#else { Write-host "Drive Adviser already set to start on boot" }
Write-Host 'Press any key to continue...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');
}
Function DownloadFiles {
Write-Host "Downloading and running jrt/cpu test/ccleaner"
#Download and Extract zip file with MC programs
Invoke-WebRequest -Uri $MCZipUrl -OutFile $MCzippath
Expand-Archive -Path $MCzippath -DestinationPath $PSScriptRoot -force
#Installs a program called chocolatey https://chocolatey.org/ which will allow
#Us to install the latest MBAM/SAS/ADW
Write-Host "installing chocolatly for adw/mbam/sas."
#Gets Chocolatey and installs it from the internet
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; Invoke-Expression ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
"Installing SAS, ADW, and MBAM..."
choco install adwcleaner malwarebytes superantispyware -y --ignore-checksums --allow-empty-checksums
Write-Host -NoNewLine 'Press any key to continue...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');
}
Function RunMCScript {
#turns on system restore for drive C and takes a snapshot.
Enable-ComputerRestore -Drive "C:\"
"System restore enabled"
Checkpoint-Computer -Description "Schrock Maintance Checkup" -RestorePointType "MODIFY_SETTINGS"
#Gets the current power configureation scheme
$powercfgGUID = powercfg /getactivescheme
#Splits out just the GUID from the active scheme
$powercfgGUID = $powercfgGUID.split(" ")[3]
#Imports our custom power config as that dumb GUID, then sets it as active
powercfg /import $PSScriptRoot + "\MCpowercfg.pow" 11111111-1111-2222-2222-333333333333
powercfg /setactive 11111111-1111-2222-2222-333333333333
#Optimize the C drive
Get-PhysicalDisk | Where-Object mediatype -match "SSD"
Write-Output "Optimize c drive"
Optimize-Volume -DriveLetter C -ReTrim
#Killing web browser processess
taskkill.exe /IM chrome.exe /F
taskkill.exe /IM firefox.exe /F
taskkill.exe /IM edge.exe /F
#Installs the intel CPU tester, then runs ccleaner and the battery info view
Start-Process $PSScriptRoot\CPUTester.exe /passive -wait
start-process "C:\Program Files\Intel Corporation\Intel Processor Diagnostic Tool 64bit\Win-IPDT64.exe" `
-WorkingDirectory "C:\Program Files\Intel Corporation\Intel Processor Diagnostic Tool 64bit\" -Wait
#Running sfc scan and placing file into the SMC cpuLogsResultsFolderSearch
start-process sfc /scannow -RedirectStandardOutput $PSScriptRoot\sfc.txt -NoNewWindow
#Starts an old CCleaner (does Tracking cookies, temp and reg without a lot of hastle)
Start-Process $PSScriptRoot\CCleaner64.exe -Wait
#runs a batch file that puts the batteryinfo to a text file to parase later
Start-Process $PSScriptRoot\BatteryInfoView.bat -WorkingDirectory $PSScriptRoot
#Running sfc scan and placing file onto desktop
start-process sfc /scannow -RedirectStandardOutput $PSScriptRoot\sfc.txt -NoNewWindow
#runs ADWCLEANER and cleans what it finds while loging to the MC Folder
Start-Process adwcleaner "/eula /clean /noreboot /path $PSScriptRoot" -passthru -wait
#Runs ADW and JRT, waits till jrt is closed
Start-Process $PSScriptRoot\get.bat -wait -passthru
#Runs HDtune, SAS and MBAM and pauses untill mbam is closed.
start-process $PSScriptRoot\HDTune.exe
Start-Process "C:\Program Files\SuperAntiSpyware\SuperAntiSpyware.exe"
Start-Process "C:\Program Files\Malwarebytes\Anti-Malware\mbam.exe" -Wait
#reset powercfg settings to pre-MC settings and delete our custom powercfg
powercfg /setactive $powercfgGUID.split(" ")[3]
powercfg /delete 11111111-1111-2222-2222-333333333333
#wait for imput at the end of the script
Write-Host -NoNewLine 'Press any key to continue...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');
}
Function Reports {
if (Test-Path -Path "C:\Program Files\Sophos\Sophos File Scanner\SophosFS.exe") {
$SohposRegName = Get-ItemPropertyValue -Path `
'HKLM:\SOFTWARE\WOW6432Node\Sophos\Management Communications System\' `
-Name ComputerNameOverride
$SophosInstalled = "Sophos is Installed"
}
else {
$SophosInstalled = "Sophos is Not Installed"
$SohposRegName = "Sophos is Not Installed"
}
$sfclog = get-content $PSScriptRoot\sfc.txt -Encoding unicode | Select-String -Pattern Resource
#Im only going to comment one of these, as they are all the same.
#This grabs the location of the SAS Logs, ie the cpuLogsResultsFolderSearch they are in.
$SASlogLocation = $env:APPDATA + "\SUPERAntiSpyware.com\SUPERAntiSpyware\Logs\"
#This line grabs all the fimes, and then grabs the newest file from the list (ie the one that was just created by our last scan)
$SASlogFileName = Get-ChildItem $SASlogLocation | Sort-Object LastAccessTime | Select-Object -First 1
#And then puts them together for the full file path and name (C:\blabla\bla\log.txt)
$SASlognameandloc = $SASlogLocation + $SASlogFileName.name
#This reads through the file looking for the patterern "detected" and pulling out all lines with that pattern
$SASResults = get-content $SASlognameandloc | Select-String -Pattern detected -CaseSensitive
$MbamLogLocation = "C:\ProgramData\Malwarebytes\MBAMService\ScanResults\"
$MBAMLogName = Get-ChildItem $MbamLogLocation | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$MBAMLogAndName = $MbamLogLocation + $MBAMLogName.name
$MBAMResults = get-content $MBAMLogAndName | Select-Object -Skip 1 | ConvertFrom-Json
$JRTLogAndName = $PSScriptRoot + "\jrt\temp\jrt.txt"
$JRTResults = get-content $JRTLogAndName | Select-String -Pattern ": [1-9]"
$ADWLogLocation = $PSScriptRoot + "\Logs\"
$ADWLogName = Get-ChildItem $ADWLogLocation | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$ADWLogAndName = $ADWLogLocation + $ADWLogName.name
$ADWResults = get-content -Literalpath $ADWLogAndName | Select-String -Pattern Detected -CaseSensitive
$Batteryinfolog = $PSScriptRoot + "\BatteryInfoView.txt"
$BatteryResults = get-content $Batteryinfolog | Select-String -Pattern "Battery Health"
#check memory diagnostics results, if empty writes "no resutls found"
$Memdiagresults = (get-eventlog -logname system -Source "Microsoft-Windows-MemoryDiagnostics-Results" -newest 1)
$MemdiagresultsMessage = $Memdiagresults.Message
$MemdiagresultsTime = $Memdiagresults.Time
if (!$Memdiagresults) {
$MemdiagresultsMessage = "No results found for Windows Memory Diagnostics"
$MemdiagresultsTime = "No results found for Windows Memory Diagnostics"
}
#This block is a bit of a mess, so I put it into its own function.
#It loops through the processor diagnostics folder and snags all the RESULTS files
#Then searches for the word fail, if it finds it it adds that filename to a list
$CpuLogsResultsFolderSearch = "C:\Program Files\Intel Corporation\Intel Processor Diagnostic Tool 64bit\*"
$CpuLogsandFilenames = Get-ChildItem -Path $cpuLogsResultsFolderSearch -Include *_Results.txt
$CpuLogsResultsFolderLiteral = "C:\Program Files\Intel Corporation\Intel Processor Diagnostic Tool 64bit\"
CpuTestFailures = "CPU Test Results Failed"
foreach ( $filename in $CpuLogsandFilenames.name) {
$cpulogs = $CpuLogsResultsFolderLiteral + $filename
if (get-content -literalpath $cpulogs | Select-String -Pattern Fail) {
$CpuTestFailures += Write-Output $filename `n
}
}
$CpuTestFailures = $CpuTestFailures -replace "genintel_1_Results.txt", "Not an intel CPU"
$CpuTestFailures = $CpuTestFailures -replace "brandstring_1_Results.txt", "Branding string"
$CpuTestFailures = $CpuTestFailures -replace "cache_1_Results.txt", "Cache"
$CpuTestFailures = $CpuTestFailures -replace "mmxsse_1_Results.txt", "MMXSSE"
$CpuTestFailures = $CpuTestFailures -replace "imc_1_Results.txt", "IMC"
$CpuTestFailures = $CpuTestFailures -replace "Math_PrimeNum_Parallel_Math_1_Results.txt", "Prime Number Generation"
$CpuTestFailures = $CpuTestFailures -replace "Parallel_PrimeNum_1_Results.txt", "Prime Number Generation"
$CpuTestFailures = $CpuTestFailures -replace "Math_PrimeNum_Parallel_PrimeNum_1_Results.txt", "Prime Number Generation"
$CpuTestFailures = $CpuTestFailures -replace "Math_FP_Parallel_Math_1_Results.txt", "Floating Point Math"
$CpuTestFailures = $CpuTestFailures -replace "Math_FP_Parallel_FP_1_Results.txt", "Floating Point Math"
$CpuTestFailures = $CpuTestFailures -replace "Parallel_FP_1_Results.txt", "Floating Point Math"
$CpuTestFailures = $CpuTestFailures -replace "AVX_Parallel_Math_1_Results.txt FMA3_Parallel_Math_1_Results.txt", "Math"
$CpuTestFailures = $CpuTestFailures -replace "Parallel_GPUStressW_1_Results.txt", "Software Rendering Stress Test"
$CpuTestFailures = $CpuTestFailures -replace "AVX_Parallel_GPUStressW_1_Results.txt" , "Software Rendering Stress Test"
$CpuTestFailures = $CpuTestFailures -replace "FMA3_Parallel_GPUStressW_1_Results.txt", "Software Rendering Stress Test"
$CpuTestFailures = $CpuTestFailures -replace "dgemm_1_Results.txt", "CPU Load Stressing"
$CpuTestFailures = $CpuTestFailures -replace "cpufreq_1_Results.txt", "CPU Frequency Changing (Amd CPUs fail regularly)"
$CpuTestFailures = $CpuTestFailures -replace "pch_1_Results.txt", "PCH"
$CpuTestFailures = $CpuTestFailures -replace "spbc_1_Results.txt", "SPBC"
$CpuTestFailures = $CpuTestFailures -replace "Temperature_Results.txt", "Tempurature"
#Writes log via another fuction for results to try and keep it cleaner
"Full Mantiance Checkup Results" | Out-File -FilePath $endlog
$SophosInstalled | Out-File -FilePath $endlog -Append
"With the name of " + $SohposRegName | Out-File -FilePath $endlog -Append
"==============================" | Out-File -FilePath $endlog -Append
"Memory diagnostics ran at " + $MemdiagresultsTime | Out-File -FilePath $endlog -Append
$MemdiagresultsMessage | Out-File -FilePath $endlog -Append
"==============================" | Out-File -FilePath $endlog -Append
"MalwareBytes Scan Results" | Out-File -FilePath $endlog -Append
"Total Pups Found: " + $MBAMResults.threatsDetected | Out-File -FilePath $endlog -Append
"==============================" | Out-File -FilePath $endlog -Append
"SAS Scan Results" | Out-File -FilePath $endlog -Append
$SASResults[0] | Out-File -FilePath $endlog -Append
$SASResults[1] | Out-File -FilePath $endlog -Append
$SASResults[2] | Out-File -FilePath $endlog -Append
"==============================" | Out-File -FilePath $endlog -Append
"ADW Cleaner Results: " | Out-File -FilePath $endlog -Append
$ADWResults | Out-File -FilePath $endlog -Append
"==============================" | Out-File -FilePath $endlog -Append
"JRT Cleaned up: " | Out-File -FilePath $endlog -Append
$JRTResults | Out-File -FilePath $endlog -Append
"==============================" | Out-File -FilePath $endlog -Append
"Battery Health state" | Out-File -FilePath $endlog -Append
$BatteryResults | Out-File -FilePath $endlog -Append
"==============================" | Out-File -FilePath $endlog -Append
"SFC Scan Results" | Out-File -FilePath $endlog -Append
$sfclog | Out-File -FilePath $endlog -Append
"==============================" | Out-File -FilePath $endlog -Append
$CpuTestFailures | Out-File -FilePath $endlog -Append
"==============================" | Out-File -FilePath $endlog -Append
"Full List Of MBAM Threats Cleaned up" | Out-File -FilePath $endlog -Append
$MBAMResults.threats.threatname | Out-File -FilePath $endlog -Append
#opens notepad with the log file.
notepad.exe $endlog
}
Function Cleanup {
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope LocalMachine
#this removes the install listing for an the migration tool we used during symantec to sophos migration.
Remove-Item -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\SophosMigrationUtility"
#Uninstalls SAS, MBAM, and ADW
choco uninstall adwcleaner malwarebytes superantispyware -y
#Delete downloaded files needs more testing before i let it delete everything
#Remove-Item $SUoutpath -Force
#Remove-Item $DAoutpath -Force
#Remove-Item $MCzippath -Force
#Remove-Item $PSScriptRoot/MC -recurse -Force
#delete Powershell MC Script itself
#Remove-Item -LiteralPath $MyInvocation.MyCommand.Path -Force
Write-Host -NoNewLine 'Press any key to continue...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');
}
# Launch The Program. finnaly after all this code!
Main
| 44.32493 | 317 | 0.742101 |
da48d316f9e7f7e74343e134a7d9ae403bf6f879 | 1,922 | php | PHP | src/Controller/StatusController.php | H3R0M0/servicecenter | 57bdbe83e0466cbf1e0fc22b6f085bbbba2c260a | [
"MIT"
] | 1 | 2021-08-31T08:15:27.000Z | 2021-08-31T08:15:27.000Z | src/Controller/StatusController.php | Wiwaltill/servicecenter | 1f6fba32ed846dbf2dfe6fb6dee2da7799725e41 | [
"MIT"
] | 37 | 2020-01-05T15:00:32.000Z | 2022-02-07T18:22:48.000Z | src/Controller/StatusController.php | Wiwaltill/servicecenter | 1f6fba32ed846dbf2dfe6fb6dee2da7799725e41 | [
"MIT"
] | 3 | 2020-06-27T00:11:14.000Z | 2021-06-15T06:35:30.000Z | <?php
namespace App\Controller;
use App\Entity\Announcement;
use App\Entity\Device;
use App\Entity\Room;
use App\Helper\Status\CurrentStatusHelper;
use App\Repository\AnnouncementRepositoryInterface;
use SchulIT\CommonBundle\Helper\DateHelper;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
class StatusController extends AbstractController {
private $currentStatusHelper;
public function __construct(CurrentStatusHelper $currentStatusHelper) {
$this->currentStatusHelper = $currentStatusHelper;
}
/**
* @Route("/status", name="current_status")
*/
public function index(Request $request) {
$status = $this->currentStatusHelper->getCurrentStatus();
return $this->render('status/index.html.twig', [
'status' => $status
]);
}
/**
* @Route("/status/r/{uuid}", name="status_room")
*/
public function roomStatus(Request $request, Room $room) {
$status = $this->currentStatusHelper->getCurrentStatusForRoom($room);
return $this->render('status/room.html.twig', [
'room' => $room,
'status' => $status
]);
}
/**
* @Route("/status/d/{uuid}", name="status_device")
*/
public function deviceStatus(Device $device, DateHelper $dateHelper, AnnouncementRepositoryInterface $announcementRepository) {
$status = $this->currentStatusHelper->getCurrentStatusForDevice($device);
/** @var Announcement[] $announcements */
$announcements = $announcementRepository
->findActiveByRoom($device->getRoom(), $dateHelper->getToday());
return $this->render('status/device.html.twig', [
'device' => $device,
'status' => $status,
'announcements' => $announcements
]);
}
} | 31.508197 | 131 | 0.657128 |
c3d13f750bff0f07a14062245a5161ac6627318b | 230 | cs | C# | HabrCacheQueryInfrastructure/IQuery/IQuery.cs | brager17/Cached-Query | 7a4fbcc08b9c2c9cc8be0b1663f1104bc29edfff | [
"MIT"
] | 1 | 2019-05-25T07:50:08.000Z | 2019-05-25T07:50:08.000Z | HabrCacheQueryInfrastructure/IQuery/IQuery.cs | brager17/Cached-Query | 7a4fbcc08b9c2c9cc8be0b1663f1104bc29edfff | [
"MIT"
] | null | null | null | HabrCacheQueryInfrastructure/IQuery/IQuery.cs | brager17/Cached-Query | 7a4fbcc08b9c2c9cc8be0b1663f1104bc29edfff | [
"MIT"
] | null | null | null | using System.Threading.Tasks;
namespace HabrCacheQuery.Query
{
public interface IQuery<TIn, TOut>
{
TOut Query(TIn input);
}
public interface IAsyncQuery<TIn, TOut> : IQuery<TIn, Task<TOut>>
{
}
} | 17.692308 | 69 | 0.643478 |
6b8ae10ba121da8d911033b32eb2706f21781582 | 6,787 | cpp | C++ | src/TestSymmetry.cpp | morpheus-org/hpcg | 62501f64b83831ee01601bc9873f1ab0605199f5 | [
"BSD-3-Clause"
] | null | null | null | src/TestSymmetry.cpp | morpheus-org/hpcg | 62501f64b83831ee01601bc9873f1ab0605199f5 | [
"BSD-3-Clause"
] | null | null | null | src/TestSymmetry.cpp | morpheus-org/hpcg | 62501f64b83831ee01601bc9873f1ab0605199f5 | [
"BSD-3-Clause"
] | null | null | null | //@HEADER
// ***************************************************
//
// HPCG: High Performance Conjugate Gradient Benchmark
//
// Contact:
// Michael A. Heroux ( [email protected])
// Jack Dongarra ([email protected])
// Piotr Luszczek ([email protected])
//
// ***************************************************
//@HEADER
/*!
@file TestSymmetry.cpp
HPCG routine
*/
// The MPI include must be first for Windows platforms
#ifndef HPCG_NO_MPI
#include <mpi.h>
#endif
#include <fstream>
#include <iostream>
#include <cfloat>
using std::endl;
#include <vector>
#include <cmath>
#include "hpcg.hpp"
#include "ComputeSPMV.hpp"
#include "ComputeMG.hpp"
#include "ComputeDotProduct.hpp"
#include "ComputeResidual.hpp"
#include "Geometry.hpp"
#include "SparseMatrix.hpp"
#include "TestSymmetry.hpp"
#ifdef HPCG_WITH_MORPHEUS
#include "MorpheusUtils.hpp"
#endif // HPCG_WITH_MORPHEUS
/*!
Tests symmetry-preserving properties of the sparse matrix vector multiply and
multi-grid routines.
@param[in] geom The description of the problem's geometry.
@param[in] A The known system matrix
@param[in] b The known right hand side vector
@param[in] xexact The exact solution vector
@param[inout] testsymmetry_data The data structure with the results of the CG
symmetry test including pass/fail information
@return returns 0 upon success and non-zero otherwise
@see ComputeDotProduct
@see ComputeDotProduct_ref
@see ComputeSPMV
@see ComputeSPMV_ref
@see ComputeMG
@see ComputeMG_ref
*/
int TestSymmetry(SparseMatrix& A, Vector& b, Vector& xexact,
TestSymmetryData& testsymmetry_data) {
local_int_t nrow = A.localNumberOfRows;
local_int_t ncol = A.localNumberOfColumns;
Vector x_ncol, y_ncol, z_ncol;
InitializeVector(x_ncol, ncol);
InitializeVector(y_ncol, ncol);
InitializeVector(z_ncol, ncol);
double t4 = 0.0; // Needed for dot-product call, otherwise unused
testsymmetry_data.count_fail = 0;
// Test symmetry of matrix
// First load vectors with random values
FillRandomVector(x_ncol);
FillRandomVector(y_ncol);
double xNorm2, yNorm2;
double ANorm = 2 * 26.0;
#ifdef HPCG_WITH_MORPHEUS
MorpheusInitializeVector(x_ncol);
MorpheusInitializeVector(y_ncol);
MorpheusInitializeVector(z_ncol);
MorpheusOptimizeVector(x_ncol);
MorpheusOptimizeVector(y_ncol);
MorpheusOptimizeVector(z_ncol);
HPCG_Morpheus_Vec* xncolopt = (HPCG_Morpheus_Vec*)x_ncol.optimizationData;
HPCG_Morpheus_Vec* yncolopt = (HPCG_Morpheus_Vec*)y_ncol.optimizationData;
HPCG_Morpheus_Vec* zncolopt = (HPCG_Morpheus_Vec*)z_ncol.optimizationData;
HPCG_Morpheus_Vec* xexactopt = (HPCG_Morpheus_Vec*)xexact.optimizationData;
#endif
// Next, compute x'*A*y
ComputeDotProduct(nrow, y_ncol, y_ncol, yNorm2, t4, A.isDotProductOptimized);
int ierr = ComputeSPMV(A, y_ncol, z_ncol); // z_nrow = A*y_overlap
if (ierr) HPCG_fout << "Error in call to SpMV: " << ierr << ".\n" << endl;
double xtAy = 0.0;
ierr = ComputeDotProduct(nrow, x_ncol, z_ncol, xtAy, t4,
A.isDotProductOptimized); // x'*A*y
if (ierr) HPCG_fout << "Error in call to dot: " << ierr << ".\n" << endl;
// Next, compute y'*A*x
ComputeDotProduct(nrow, x_ncol, x_ncol, xNorm2, t4, A.isDotProductOptimized);
ierr = ComputeSPMV(A, x_ncol, z_ncol); // b_computed = A*x_overlap
if (ierr) HPCG_fout << "Error in call to SpMV: " << ierr << ".\n" << endl;
double ytAx = 0.0;
ierr = ComputeDotProduct(nrow, y_ncol, z_ncol, ytAx, t4,
A.isDotProductOptimized); // y'*A*x
if (ierr) HPCG_fout << "Error in call to dot: " << ierr << ".\n" << endl;
testsymmetry_data.depsym_spmv =
std::fabs((long double)(xtAy - ytAx)) /
((xNorm2 * ANorm * yNorm2 + yNorm2 * ANorm * xNorm2) * (DBL_EPSILON));
if (testsymmetry_data.depsym_spmv > 1.0)
++testsymmetry_data.count_fail; // If the difference is > 1, count it wrong
if (A.geom->rank == 0)
HPCG_fout
<< "Departure from symmetry (scaled) for SpMV abs(x'*A*y - y'*A*x) = "
<< testsymmetry_data.depsym_spmv << endl;
// Test symmetry of multi-grid
#ifdef HPCG_WITH_MORPHEUS
Morpheus::copy(yncolopt->dev, yncolopt->host);
#endif
// Compute x'*Minv*y
ierr = ComputeMG(A, y_ncol, z_ncol); // z_ncol = Minv*y_ncol
if (ierr) HPCG_fout << "Error in call to MG: " << ierr << ".\n" << endl;
#ifdef HPCG_WITH_MORPHEUS
Morpheus::copy(zncolopt->host, zncolopt->dev);
#endif
double xtMinvy = 0.0;
ierr = ComputeDotProduct(nrow, x_ncol, z_ncol, xtMinvy, t4,
A.isDotProductOptimized); // x'*Minv*y
if (ierr) HPCG_fout << "Error in call to dot: " << ierr << ".\n" << endl;
#ifdef HPCG_WITH_MORPHEUS
Morpheus::copy(xncolopt->dev, xncolopt->host);
#endif
// Next, compute z'*Minv*x
ierr = ComputeMG(A, x_ncol, z_ncol); // z_ncol = Minv*x_ncol
if (ierr) HPCG_fout << "Error in call to MG: " << ierr << ".\n" << endl;
#ifdef HPCG_WITH_MORPHEUS
Morpheus::copy(zncolopt->host, zncolopt->dev);
#endif
double ytMinvx = 0.0;
ierr = ComputeDotProduct(nrow, y_ncol, z_ncol, ytMinvx, t4,
A.isDotProductOptimized); // y'*Minv*x
if (ierr) HPCG_fout << "Error in call to dot: " << ierr << ".\n" << endl;
testsymmetry_data.depsym_mg =
std::fabs((long double)(xtMinvy - ytMinvx)) /
((xNorm2 * ANorm * yNorm2 + yNorm2 * ANorm * xNorm2) * (DBL_EPSILON));
if (testsymmetry_data.depsym_mg > 1.0)
++testsymmetry_data.count_fail; // If the difference is > 1, count it wrong
if (A.geom->rank == 0)
HPCG_fout << "Departure from symmetry (scaled) for MG abs(x'*Minv*y - "
"y'*Minv*x) = "
<< testsymmetry_data.depsym_mg << endl;
#ifdef HPCG_WITH_MORPHEUS
Morpheus::copy(xexactopt->host, xncolopt->host, 0, xexactopt->host.size());
#else
CopyVector(xexact, x_ncol); // Copy exact answer into overlap vector
#endif
int numberOfCalls = 2;
double residual = 0.0;
for (int i = 0; i < numberOfCalls; ++i) {
ierr = ComputeSPMV(A, x_ncol, z_ncol); // b_computed = A*x_overlap
if (ierr) HPCG_fout << "Error in call to SpMV: " << ierr << ".\n" << endl;
#ifdef HPCG_WITH_MORPHEUS
// Needed for computing residual on host
Morpheus::copy(zncolopt->dev, zncolopt->host);
#endif
if ((ierr = ComputeResidual(A.localNumberOfRows, b, z_ncol, residual)))
HPCG_fout << "Error in call to compute_residual: " << ierr << ".\n"
<< endl;
if (A.geom->rank == 0)
HPCG_fout << "SpMV call [" << i << "] Residual [" << residual << "]"
<< endl;
}
DeleteVector(x_ncol);
DeleteVector(y_ncol);
DeleteVector(z_ncol);
return 0;
}
| 34.627551 | 80 | 0.652866 |
dbec2cea382b676b19daa521af9ccbf48bc90bed | 19,989 | php | PHP | Subir_Imagenes.php | nercar/preciosusd | 8070f03be4296f0279437541841a98582bcf9f51 | [
"MIT"
] | null | null | null | Subir_Imagenes.php | nercar/preciosusd | 8070f03be4296f0279437541841a98582bcf9f51 | [
"MIT"
] | null | null | null | Subir_Imagenes.php | nercar/preciosusd | 8070f03be4296f0279437541841a98582bcf9f51 | [
"MIT"
] | null | null | null | <?php
include("seguridad.php");
include("conex.php");
$su_usu = new AdminBD();
$su_usu->Conectar();
error_reporting(E_ALL);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Precios USD | Consultar</title>
<link rel="stylesheet" href="plugins/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
<link rel="stylesheet" href="dist/css/adminlte.min.css">
<link rel="stylesheet" href="plugins/datatables/dataTables.bootstrap4.css">
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700" rel="stylesheet">
<link rel="shortcut icon" href="dist/img/favicon.png" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<!--<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">-->
<link href="https://unpkg.com/[email protected]/css/gijgo.min.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/gijgo.min.js"></script>
<script src="gijgo.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
</head>
<body class="hold-transition sidebar-mini">
<!--<form name="form1" method="POST" id="form1" action="" enctype="multipart/form-data">-->
<div class="wrapper">
<!-- Navbar -->
<nav class="main-header navbar navbar-expand bg-info navbar-light border-bottom">
<!-- Left navbar links -->
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" data-widget="pushmenu" href="#"><i class="fa fa-bars"></i></a>
</li>
<li class="nav-item d-none d-sm-inline-block">
<a href="index3.php" class="nav-link">Precios USD</a>
</li>
</ul>
</nav>
<!-- /.navbar -->
<!-- Main Sidebar Container -->
<aside class="main-sidebar sidebar-dark-primary elevation-4">
<!-- Brand Logo -->
<a href="index3.php" class="brand-link">
<img src="dist/img/GG.jpg" alt="AdminLTE Logo" class="brand-image img-circle elevation-3"
style="opacity: .8">
<span class="brand-text font-weight-light">Grupo Garzon C.A.</span>
</a>
<!-- Sidebar -->
<div class="sidebar">
<!-- Sidebar user panel (optional) -->
<div class="user-panel mt-3 pb-3 mb-3 d-flex">
<div class="image">
<img src="dist/img/avatar5.png" class="img-circle elevation-2" alt="User Image">
</div>
<div class="info">
<a href="#" class="d-block"><?php echo $LOGusuario;?></a>
</div>
</div>
<!-- Sidebar Menu -->
<nav class="mt-2">
<ul class="nav nav-pills nav-sidebar flex-column" data-widget="treeview" role="menu" data-accordion="false">
<!-- Add icons to the links using the .nav-icon class
with font-awesome or any other icon font library -->
<li class="nav-item has-treeview menu-open">
<a href="#" class="nav-link active">
<i class="nav-icon fa fa-dollar fa-spin fa-1x fa-fw"></i>
<p>
Precios USD
<i class="right fa fa-angle-left"></i>
</p>
</a>
<ul class="nav nav-treeview">
<li class="nav-item">
<a href="./Agregar_USD.php" class="nav-link">
<i class="nav-icon fa fa-file-excel-o text-info"></i>
<p> Importar Archivo</p>
</a>
</li>
<li class="nav-item">
<a href="./Ingresar_USD.php" class="nav-link">
<i class="nav-icon fa fa-file-text-o text-info"></i>
<p> Agregar</p>
</a>
</li>
<li class="nav-item">
<a href="./Consultar_USD.php" class="nav-link">
<i class="nav-icon fa fa-search text-info"></i>
<p> Consultar</p>
</a>
</li>
<li class="nav-item">
<a href="./Modificar_USD.php" class="nav-link">
<i class="nav-icon fa fa-edit text-info"></i>
<p> Modificar</p>
</a>
</li>
<li class="nav-item">
<a href="./Listar_USD.php" class="nav-link">
<i class="nav-icon fa fa-list-alt text-info"></i>
<p> Listar</p>
</a>
</li>
</ul>
</li>
</ul>
</nav>
<?php
$contraseña = "";
$usuario = "sa";
$nombreBaseDeDatos = "BDES";
$rutaServidor = "192.168.20.207";
$valores = array();
try
{
$base_de_datos = new PDO("sqlsrv:server=$rutaServidor;database=$nombreBaseDeDatos", $usuario, $contraseña);
$base_de_datos->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo "Conexion realizada a la base de datos: ";
}
catch (Exception $e)
{
echo "Ocurrió un error con la base de datos: " . $e->getMessage();
}
// FETCH_ASSOC
$sentencia = $base_de_datos->prepare("SELECT BDES.dbo.ESFormasPago_FactorC.codigo, BDES.dbo.ESFormasPago_FactorC.factor, BDES.dbo.ESFormasPago_FactorC.fechahora FROM BDES.dbo.ESFormasPago_FactorC");
$sentencia->setFetchMode(PDO::FETCH_ASSOC);
$sentencia->execute();
// Ahora le vamos a indicar el fetch mode para llamar al fetch:
$i=0;
while($row = $sentencia->fetch(PDO::FETCH_OBJ))
{
$valores[$i][0] = $row->codigo;
$valores[$i][1] = $row->factor;
$valores[$i][2] = $row->fechahora;
$valores[$i][3] = $row->fechahora;
$valores[$i][2] = date_create($valores[$i][2]);
$valores[$i][3] = date_create($valores[$i][3]);
$valores[$i][2] = date_format($valores[$i][2], 'd/m/Y');
$valores[$i][3] = date_format($valores[$i][3], 'G:i:s a');
$i++;
}
?>
<nav class="mt-2">
<ul class="nav nav-pills nav-sidebar flex-column" data-widget="treeview" role="menu" data-accordion="false">
<!-- Add icons to the links using the .nav-icon class
with font-awesome or any other icon font library -->
<li class="nav-item has-treeview menu-open">
<a href="#" class="nav-link active">
<i class="nav-icon fa fa-gear fa-spin fa-1x fa-fw"></i>
<p>
Tasas
<i class="right fa fa-angle-left"></i>
</p>
</a>
<ul class="nav nav-treeview">
<li class="nav-item">
<a href="./phpinfo.php" class="nav-link">
<i class="nav-icon fa fa-files-o text-info"></i>
<p> Monitor: <?php echo number_format($valores[0][1], 2, ',', '.')." BsS.";?></p>
</a>
</li>
<li class="nav-item">
<a href="./phpinfo.php" class="nav-link">
<i class="nav-icon fa fa-files-o text-info"></i>
<p> Pesos: <?php echo number_format($valores[1][1], 3, ',', '.')." COP";?></p>
</a>
</li>
<li class="nav-item">
<a href="./phpinfo.php" class="nav-link">
<i class="nav-icon fa fa-files-o text-info"></i>
<p> BCV: <?php echo number_format($valores[2][1], 2, ',', '.')." BsS.";?></p>
</a>
</li>
</ul>
</li>
</ul>
</nav>
</div>
</aside>
<div class="content-wrapper">
<div class="row">
<div class="col-md-4">
<div class="card card-widget widget-user-2">
<div class="widget-user-header bg-primary">
<h5 class="widget-user-desc">Dolar Monitor</h5>
</div>
<div class="card-footer p-0">
<ul class="nav flex-column">
<li class="nav-item">
<a href="#" class="nav-link">
Codigo: <span class="float-right badge bg-primary"><?php echo $valores[0][0];?></span>
</a>
</li>
<li class="nav-item">
<a href="#" class="nav-link">
Tasa: <span class="float-right badge bg-info"><?php echo number_format($valores[0][1], 2, ',', '.')." BsS.";?></span>
</a>
</li>
<li class="nav-item">
<a href="#" class="nav-link">
Ultima Actualización: <span class="float-right badge bg-success"><?php echo $valores[0][2];?></span>
</a>
</li>
<li class="nav-item">
<a href="#" class="nav-link">
Hora: <span class="float-right badge bg-danger"><?php echo $valores[0][3];?></span>
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card card-widget widget-user-2">
<div class="widget-user-header bg-success">
<h5 class="widget-user-desc">Tasa Pesos</h5>
</div>
<div class="card-footer p-0">
<ul class="nav flex-column">
<li class="nav-item">
<a href="#" class="nav-link">
Codigo: <span class="float-right badge bg-primary"><?php echo $valores[1][0];?></span>
</a>
</li>
<li class="nav-item">
<a href="#" class="nav-link">
Tasa: <span class="float-right badge bg-info"><?php echo number_format($valores[1][1], 3, ',', '.')." COP";?></span>
</a>
</li>
<li class="nav-item">
<a href="#" class="nav-link">
Ultima Actualización: <span class="float-right badge bg-success"><?php echo $valores[1][2];?></span>
</a>
</li>
<li class="nav-item">
<a href="#" class="nav-link">
Hora: <span class="float-right badge bg-danger"><?php echo $valores[1][3];?></span>
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card card-widget widget-user-2">
<div class="widget-user-header bg-warning">
<h5 class="widget-user-desc">Dolar BCV</h5>
</div>
<div class="card-footer p-0">
<ul class="nav flex-column">
<li class="nav-item">
<a href="#" class="nav-link">
Codigo: <span class="float-right badge bg-primary"><?php echo $valores[2][0];?></span>
</a>
</li>
<li class="nav-item">
<a href="#" class="nav-link">
Tasa: <span class="float-right badge bg-info"><?php echo number_format($valores[2][1], 2, ',', '.')." BsS.";?></span>
</a>
</li>
<li class="nav-item">
<a href="#" class="nav-link">
Ultima Actualización: <span class="float-right badge bg-success"><?php echo $valores[2][2];?></span>
</a>
</li>
<li class="nav-item">
<a href="#" class="nav-link">
Hora: <span class="float-right badge bg-danger"><?php echo $valores[2][3];?></span>
</a>
</li>
</ul>
</div>
</div>
</div>
</div>
<h1>Galería de imágenes</h1>
<p></p>
<?php
$borrar= filter_input(INPUT_GET, 'borrar');
if(!empty($borrar))
{
unlink("uploads/".$borrar);
}
if(isset($_FILES['imagen']))
{
if(explode("/", $_FILES['imagen']['type'])[0] == 'image')
{
move_uploaded_file($_FILES['imagen']['tmp_name'], "uploads/" . $_FILES['imagen']['name']);
?>
<div class="alert alert-success alert-dismissible">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>Ok</strong> El archivo se ha subido con éxito.
</div>
<?php
}
else
{
?>
<div class="alert alert-danger alert-dismissible">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>Error</strong> El archivo subido no es de tipo imagen.
</div>
<?php
}
}
?>
<form action='Subir_Imagenes.php' method="post" enctype="multipart/form-data">
<input type="file" name="imagen">
<input type="submit" class="btn btn-success" value="Guardar Imagen">
</form>
<hr/>
<div style='display:flex;flex-wrap: wrap;'>
<?php
$imagenes = scandir("./uploads");
for($i=2; $i<count($imagenes); $i++)
{
?>
<div class="card" style="width:125px" >
<img class="card-img-top" src="uploads/<?= $imagenes[$i] ?>" alt="Card image">
<div class="card-body">
<h4 class="card-title"><?= $imagenes[$i] ?></h4>
<a href="?borrar=<?= $imagenes[$i] ?>" class="btn btn-danger">Borrar</a>
</div>
</div>
<?php
}
?>
</div>
<!--
<p></p>
<div class="container">
<h3 align="center">Subir imágenes al servidor FTP</h3>
<div align="center">
<button type="button" data-toggle="modal" data-target="#src_img_upload" class="btn btn-success btn-lg">Subir archivos</button>
</div>
<br/>
<div id="image_gallery">
<?php
/*$images = glob("uploads/*.*");
foreach($images as $image)
{
echo '<div class="col-md-2" align="center"><img src="' . $image .'" width="50px" height="50px" style="border:1px dotted #cacaca; margin-top:10px;"/></div>';
}*/
?>
</div>
</div>
<br/>
<div id="src_img_upload" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h1 class="modal-title">Subir multiples imágenes</h1>
</div>
<div class="modal-body">
<form method="POST" id="upload_form">
<label>Seleccione las imágenes</label>
<input type="file" name="images[]" id="img_select" multiple class='form-control'>
</form>
</div>
</div>
</div>
</div>
-->
</div>
<br></br>
<footer class="main-footer">
<div class="float-right d-sm-none d-md-block"></div>
<strong>Copyright © 2020 <a href="http://www.elgarzon.com">Grupo Garzon C.A.</a></strong> Todos los derechos reservados.
</footer>
<aside class="control-sidebar control-sidebar-dark"></aside>
</div>
<!-- jQuery -->
<script src="plugins/jquery/jquery.min.js"></script>
<!-- Bootstrap -->
<script src="plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- AdminLTE App -->
<script src="dist/js/adminlte.js"></script>
<!-- OPTIONAL SCRIPTS -->
<script src="dist/js/demo.js"></script>
<!-- PAGE PLUGINS -->
<!-- SparkLine -->
<script src="plugins/sparkline/jquery.sparkline.min.js"></script>
<!-- jVectorMap -->
<script src="plugins/jvectormap/jquery-jvectormap-1.2.2.min.js"></script>
<script src="plugins/jvectormap/jquery-jvectormap-world-mill-en.js"></script>
<!-- SlimScroll 1.3.0 -->
<script src="plugins/slimScroll/jquery.slimscroll.min.js"></script>
<!-- PAGE SCRIPTS -->
<script src="dist/js/pages/dashboard2.js"></script>
<link rel="stylesheet" type="text/css" href="http://www.shieldui.com/shared/components/latest/css/light/all.min.css" />
<script type="text/javascript" src="http://www.shieldui.com/shared/components/latest/js/shieldui-all.min.js"></script>
<script type="text/javascript" src="http://www.shieldui.com/shared/components/latest/js/jszip.min.js"></script>
<!-- DataTables -->
<script src="plugins/datatables/jquery.dataTables.js"></script>
<script src="plugins/datatables/dataTables.bootstrap4.js"></script>
<!-- SlimScroll -->
<script src="plugins/slimScroll/jquery.slimscroll.min.js"></script>
<!-- FastClick -->
<script src="plugins/fastclick/fastclick.js"></script>
<script>
$(function ()
{
$("#example1").DataTable(
{
pageLength: 15,
lengthMenu: [[15, 25, 50, -1], [15, 25, 50, "Todos"]],
//"dom": '<"dt-buttons"Bf><"clear">lirtp',
paging: true,
autoWidth: true,
language:
{
lengthMenu: "Mostrar _MENU_ Registros",
zeroRecords: "Disculpe - No se encontraron Registros",
info: "Mostrando _END_ de _MAX_ Registros",
infoEmpty: "Pagina _PAGE_ de _PAGES_",
infoFiltered: "(Filtrado de _MAX_ entradas totales)",
sSearch: "Buscar:",
processing: "Por favor espere, Consultando...",
emptyTable: "Ningún dato disponible en esta tabla",
loadingRecords: "Cargando...",
zeroRecords: "No se encontraron resultados",
paginate:
{
first: "Primero",
last: "Ultimo",
next: "Siguiente",
previous: "Anterior"
},
aria:
{
sortAscending: ": Activar para ordenar la columna de manera ascendente",
sortDescending: ": Activar para ordenar la columna de manera descendente"
}
}
}
);
});
</script>
<script>
$(document).ready(function(){
$('#img_select').change(function(){
$('#upload_form').submit();
});
$('#upload_form').on('submit', function(e){
e.preventDefault();
$.ajax({
url : "upload.php",
method : "POST",
data: new FormData(this),
contentType:false,
processData:false,
success: function(data){
$('#img_select').val('');
$('#src_img_upload').modal('hide');
$('#image_gallery').html(data);
}
})
});
});
</script>
<!--</form>-->
</body>
</html> | 37.786389 | 217 | 0.514733 |
add6a13dde705905327a973461d6710e9ab4b9ff | 893 | asm | Assembly | MSIEXEC/download_execute_msiexec.asm | kartikdurg/Shellcode-Windows | cf4ea40a9d143952274fdae866b00b70333dbbb3 | [
"MIT"
] | 3 | 2019-02-05T20:42:23.000Z | 2020-03-12T11:08:00.000Z | MSIEXEC/download_execute_msiexec.asm | kartikdurg/Shellcode-Windows | cf4ea40a9d143952274fdae866b00b70333dbbb3 | [
"MIT"
] | null | null | null | MSIEXEC/download_execute_msiexec.asm | kartikdurg/Shellcode-Windows | cf4ea40a9d143952274fdae866b00b70333dbbb3 | [
"MIT"
] | null | null | null | xor eax, eax ;Get the msvcrt.dll
mov ax, 0x7472 ;"tr\0\0"
push eax
push dword 0x6376736d ;"cvsm"
push esp
; LoadLibrary
mov ebx, 0x7717de85 ;Address of function LoadLibraryA (win7)
call ebx
mov ebp, eax ;msvcrt.dll is saved in ebp
xor eax, eax ;zero out EAX
PUSH eax ;NULL at the end of string
PUSH 0x6e712f20 ;"nq/ "
PUSH 0x69736d2e ;"ism."
PUSH 0x736d2f33 ;"sm/3"
PUSH 0x2e312e38 ;".1.8"
PUSH 0x36312e32 ;"61.2"
PUSH 0x39312f2f ;"91//"
PUSH 0x3a707474 ;":ptt"
PUSH 0x6820692f ;"h i/"
PUSH 0x20636578 ;" cex"
PUSH 0x6569736d ;"eism"
MOV EDI,ESP ;adding a pointer to the stack
PUSH EDI
MOV EAX,0x7587b177 ;calling the system()(win7)
CALL EAX
xor eax, eax
push eax
mov eax, 0x7718be52 ; ExitProcess
call eax
| 27.060606 | 65 | 0.581187 |
4350b1fae6a666c7eb326de4253ee1c3f5a12705 | 30 | ts | TypeScript | core/core.ts | DevEngage/engage-data | b6d7881935d8cc11db062ec1ae14fc0734c5b1fb | [
"MIT"
] | 1 | 2018-12-19T05:49:10.000Z | 2018-12-19T05:49:10.000Z | core/core.ts | DevEngage/engage-data | b6d7881935d8cc11db062ec1ae14fc0734c5b1fb | [
"MIT"
] | null | null | null | core/core.ts | DevEngage/engage-data | b6d7881935d8cc11db062ec1ae14fc0734c5b1fb | [
"MIT"
] | null | null | null |
export class EngageCore {
} | 6 | 25 | 0.7 |
93f0954a6a79bf5704cf5fca812999e6d8a541da | 1,592 | cs | C# | src/AppGet/CreatePackage/Parsers/VersionParser.cs | shakeyourbunny/appget | 8b016568537f59412570afb64264150adca7fe7e | [
"Apache-2.0"
] | 428 | 2018-06-14T21:17:39.000Z | 2022-03-31T16:31:29.000Z | src/AppGet/CreatePackage/Parsers/VersionParser.cs | AppGet/AppGet | 822ee991670cb6ed961a1e44f0041a4eb03bcd29 | [
"Apache-2.0"
] | 70 | 2018-06-14T06:45:26.000Z | 2022-02-22T09:09:15.000Z | src/AppGet/CreatePackage/Parsers/VersionParser.cs | AppGet/AppGet | 822ee991670cb6ed961a1e44f0041a4eb03bcd29 | [
"Apache-2.0"
] | 64 | 2019-03-28T10:01:50.000Z | 2022-02-22T23:15:14.000Z | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace AppGet.CreatePackage.Parsers
{
public static class VersionParser
{
private static readonly Regex[] VersionRegexes =
{
new Regex(@"\d+(\.\d+){1,3}", RegexOptions.Compiled),
new Regex(@"\d{2,4}", RegexOptions.Compiled)
};
private static readonly Regex[] KnownNumberCleanup =
{
new Regex(@"(\w|\b)(ia|x|win)(64|32)(\w|\b)", RegexOptions.IgnoreCase | RegexOptions.Compiled),
new Regex(@"(\w|\b)i?(x|\d)86(\w|\b)", RegexOptions.IgnoreCase | RegexOptions.Compiled),
new Regex(@"(\w|\b)win(dows)?.?\d{1,4}(\w|\b)", RegexOptions.IgnoreCase | RegexOptions.Compiled),
new Regex(@"id=\d{2,}", RegexOptions.IgnoreCase | RegexOptions.Compiled)
};
public static string Parse(string text)
{
return ParseAll(text).OrderByDescending(c => c.Split('.').Length).ThenByDescending(c => c.Length).FirstOrDefault();
}
public static IEnumerable<string> ParseAll(string text)
{
foreach (var regex in KnownNumberCleanup)
{
text = regex.Replace(text, "");
}
return VersionRegexes.SelectMany(r => r.Matches(text).Cast<Capture>().Select(c => c.Value)).Where(v => v != "32" && v != "64");
}
public static string Parse(Uri uri)
{
var source = uri.LocalPath + uri.Query;
return Parse(source);
}
}
} | 34.608696 | 139 | 0.575377 |
a19049332d93fd876fd7fc510e5d3274213d0549 | 269 | ts | TypeScript | src/api/office/office.module.ts | raphaelmj/mycms-be-web | 59ce2539ef40527d0eaa069dbc61440037ae2526 | [
"MIT"
] | null | null | null | src/api/office/office.module.ts | raphaelmj/mycms-be-web | 59ce2539ef40527d0eaa069dbc61440037ae2526 | [
"MIT"
] | null | null | null | src/api/office/office.module.ts | raphaelmj/mycms-be-web | 59ce2539ef40527d0eaa069dbc61440037ae2526 | [
"MIT"
] | null | null | null | import { Module } from '@nestjs/common';
import { OfficeController } from './office.controller';
import { ServicesModule } from '../../services/services.module';
@Module({
imports: [ServicesModule],
controllers: [OfficeController],
})
export class OfficeModule {}
| 26.9 | 64 | 0.717472 |
ae3faea5528dbc270d7cf0773acd430520c983ed | 2,670 | cs | C# | src/ZKWeb.MVVMPlugins/MVVM.Common.Organization/src/Domain/Extensions/UserExtensions.cs | zkweb-framework/ZKWeb.MVVMDemo | 7c7ae3a2df1235b2105e804e35ba8390ceb79fff | [
"MIT"
] | 94 | 2017-04-17T06:17:06.000Z | 2021-09-15T02:07:36.000Z | src/ZKWeb.MVVMPlugins/MVVM.Common.Organization/src/Domain/Extensions/UserExtensions.cs | zkweb-framework/ZKWeb.MVVMDemo | 7c7ae3a2df1235b2105e804e35ba8390ceb79fff | [
"MIT"
] | 5 | 2018-05-29T07:20:58.000Z | 2022-02-26T10:06:13.000Z | src/ZKWeb.MVVMPlugins/MVVM.Common.Organization/src/Domain/Extensions/UserExtensions.cs | zkweb-framework/ZKWeb.MVVMDemo | 7c7ae3a2df1235b2105e804e35ba8390ceb79fff | [
"MIT"
] | 30 | 2017-04-17T06:17:08.000Z | 2020-09-09T06:52:26.000Z | using System;
using System.Collections;
using System.Collections.Generic;
using System.FastReflection;
using System.Linq;
using System.Reflection;
using ZKWeb.MVVMPlugins.MVVM.Common.Organization.src.Domain.Entities;
using ZKWeb.MVVMPlugins.MVVM.Common.Organization.src.Domain.Entities.Interfaces;
using ZKWebStandard.Utils;
namespace ZKWeb.MVVMPlugins.MVVM.Common.Organization.src.Domain.Extensions
{
/// <summary>
/// 用户的扩展函数
/// </summary>
public static class UserExtensions
{
/// <summary>
/// 设置密码
/// </summary>
public static void SetPassword(this User user, string password)
{
if (string.IsNullOrEmpty(password))
{
throw new ArgumentNullException("password");
}
user.SetPasswordInfo(PasswordInfo.FromPassword(password));
}
/// <summary>
/// 检查密码
/// </summary>
public static bool CheckPassword(this User user, string password)
{
var passwordInfo = user.GetPasswordInfo();
if (string.IsNullOrEmpty(passwordInfo.Hash))
{
return false;
}
return passwordInfo.Check(password);
}
/// <summary>
/// 获取用户类型对象
/// </summary>
public static IUserType GetUserType(this User user)
{
var type = ZKWeb.Application.Ioc.ResolveMany<IUserType>()
.FirstOrDefault(t => t.Type == user?.Type);
if (type == null)
{
throw new NotSupportedException(string.Format(
"Unsupported user type: {0}", user.Type));
}
return type;
}
/// <summary>
/// 获取已实现的用户类型列表
/// </summary>
public static IEnumerable<Type> GetImplementedUserTypes(this User user)
{
var result = new HashSet<Type>();
var type = user.GetUserType().GetType();
foreach (var interfaceType in type.FastGetInterfaces())
{
result.Add(interfaceType);
}
while (type != null && type != typeof(object))
{
result.Add(type);
type = type.GetTypeInfo().BaseType;
}
return result;
}
/// <summary>
/// 获取用户拥有的权限列表
/// </summary>
public static IEnumerable<string> GetPrivileges(this User user)
{
return user.Roles.SelectMany(r => r.To.GetPrivileges()).Distinct();
}
}
}
| 31.046512 | 81 | 0.529963 |
2c6f0fbf70e68f642664a33a8d58589ae4e97681 | 1,594 | py | Python | example_client/example_client.py | fermin-eb/example_service | 743c8218eebdebb17adb8c6e2353f9df42f4b1e2 | [
"Apache-2.0"
] | null | null | null | example_client/example_client.py | fermin-eb/example_service | 743c8218eebdebb17adb8c6e2353f9df42f4b1e2 | [
"Apache-2.0"
] | null | null | null | example_client/example_client.py | fermin-eb/example_service | 743c8218eebdebb17adb8c6e2353f9df42f4b1e2 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/python3
import json
import os
import sys
import attr
from pysoa.client import Client
from pysoa.common.transport.redis_gateway.constants import REDIS_BACKEND_TYPE_STANDARD
if __name__ == '__main__':
if len(sys.argv) < 2 or sys.argv[1] not in ('call_service', 'square', 'status'):
print('Usage: example_client.sh [square|status] ARGS')
exit(1)
client = Client({
'example': {
'transport': {
'path': 'pysoa.common.transport.redis_gateway.client:RedisClientTransport',
'kwargs': {
'backend_type': REDIS_BACKEND_TYPE_STANDARD,
'backend_layer_kwargs': {
'hosts': [
(os.environ['REDIS_PORT_6379_TCP_ADDR'], int(os.environ['REDIS_PORT_6379_TCP_PORT'])),
],
},
},
}
}
})
if sys.argv[1] == 'call_service':
body = {}
action = 'call_service'
elif sys.argv[1] == 'square':
if len(sys.argv) != 3:
print('Usage: example_client.sh square [number to square]')
exit(2)
body = {'number': int(sys.argv[2])}
action = 'square'
else:
body = {}
action = 'status'
print('Calling `example.{}` with request body:'.format(action))
print(json.dumps(body, indent=4, sort_keys=True))
print()
response = client.call_action('example', action, body=body)
print('Response:')
print(json.dumps(attr.asdict(response), indent=4, sort_keys=True))
| 30.075472 | 114 | 0.553325 |
0aeef81849501f9d1fb885b8263b6deb37e7b321 | 3,029 | cs | C# | Samples/Office365Api.Overview/Office365Api.Helpers/MailHelper.cs | Sollertix/PnP | 4f1172726d3a6e0e1eaeb863cb49b2f5718de6bc | [
"MIT"
] | 885 | 2015-01-02T18:31:39.000Z | 2016-11-24T23:50:41.000Z | Samples/Office365Api.Overview/Office365Api.Helpers/MailHelper.cs | Sollertix/PnP | 4f1172726d3a6e0e1eaeb863cb49b2f5718de6bc | [
"MIT"
] | 819 | 2015-01-02T09:11:13.000Z | 2016-11-25T12:21:38.000Z | Samples/Office365Api.Overview/Office365Api.Helpers/MailHelper.cs | Sollertix/PnP | 4f1172726d3a6e0e1eaeb863cb49b2f5718de6bc | [
"MIT"
] | 1,986 | 2015-01-01T18:57:14.000Z | 2016-11-25T00:52:15.000Z | using Microsoft.Office365.OutlookServices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Office365Api.Helpers
{
public class MailHelper : BaseOffice365Helper
{
public MailHelper(AuthenticationHelper authenticationHelper) :
base(authenticationHelper)
{
}
public async Task<IEnumerable<IMessage>> GetMessages()
{
var client = await this.AuthenticationHelper
.EnsureOutlookServicesClientCreatedAsync(
Office365Capabilities.Mail.ToString());
client.Context.IgnoreMissingProperties = true;
List<IMessage> mails = new List<IMessage>();
// ***********************************************************
// Note from @PaoloPia: To not stress the server, limit the
// the query to no more than 50 email items
// ***********************************************************
var query = (from i in client.Me.Messages
orderby i.DateTimeSent descending
select i).Take(50);
var messageResults = await query.ExecuteAsync();
if (messageResults != null)
{
do
{
mails.AddRange(messageResults.CurrentPage);
messageResults = await messageResults.GetNextPageAsync();
}
while (messageResults != null && messageResults.MorePagesAvailable);
}
return mails;
}
public async Task SendMail(string to, string subject, string body)
{
var client = await this.AuthenticationHelper
.EnsureOutlookServicesClientCreatedAsync(
Office365Capabilities.Mail.ToString());
Message mail = new Message();
mail.ToRecipients.Add(new Recipient()
{
EmailAddress = new EmailAddress
{
Address = to,
}
});
mail.Subject = subject;
mail.Body = new ItemBody() { Content = body, ContentType = BodyType.HTML };
await client.Me.SendMailAsync(mail, true);
}
public async Task DraftMail(string to, string subject, string body)
{
var client = await this.AuthenticationHelper
.EnsureOutlookServicesClientCreatedAsync(
Office365Capabilities.Mail.ToString());
Message mail = new Message();
mail.ToRecipients.Add(new Recipient()
{
EmailAddress = new EmailAddress
{
Address = to,
}
});
mail.Subject = subject;
mail.Body = new ItemBody() { Content = body, ContentType = BodyType.HTML };
await client.Me.Messages.AddMessageAsync(mail);
}
}
}
| 32.923913 | 87 | 0.525916 |
1a5760f9c2e25742e6a68174a2e1797f30088f0b | 3,446 | py | Python | interfazqr.py | AngelAlexQC/lector-bonilla | 63c9cbdf9dabd93d168c4b0fb59b19bba5e356fb | [
"MIT"
] | null | null | null | interfazqr.py | AngelAlexQC/lector-bonilla | 63c9cbdf9dabd93d168c4b0fb59b19bba5e356fb | [
"MIT"
] | null | null | null | interfazqr.py | AngelAlexQC/lector-bonilla | 63c9cbdf9dabd93d168c4b0fb59b19bba5e356fb | [
"MIT"
] | null | null | null | from tkinter import*
raiz=Tk()
import psycopg2
from bd import conexion
import cv2
from datetime import datetime
import time
cap = cv2.VideoCapture(0)
detector = cv2.QRCodeDetector()
control='u'
#se declara un fram dentro de la ventana con dimenciones
miFrame=Frame(raiz,width=1200, height=600)
#se empaqueta
miFrame.pack()
snombre=StringVar()
sapellido=StringVar()
scedula=StringVar()
sfecha=StringVar()
#se declara un cuadro de texto
NombreBox=Entry(miFrame, textvariable=snombre)
NombreBox.grid(row=0, column=1, padx=10, pady=10)
#se declara un cuadro de texto
ApellidoBox=Entry(miFrame,textvariable=sapellido)
ApellidoBox.grid(row=1, column=1, padx=10, pady=10)
#se declara un cuadro de texto
CedulaBox=Entry(miFrame, textvariable=scedula)
CedulaBox.grid(row=2, column=1, padx=10, pady=10)
#se declara un cuadro de texto
FechaBox=Entry(miFrame, textvariable=sfecha)
FechaBox.grid(row=3, column=1, padx=10, pady=10)
#se declara una etiqueta
NombreLabel= Label(miFrame, text="Nombre:")
NombreLabel.grid(row=0, column=0, sticky="e", padx=10, pady=10)
#se declara una etiqueta
ApellidoLabel= Label(miFrame, text="Apellido:")
ApellidoLabel.grid(row=1, column=0, sticky="e", padx=10, pady=10)
#se declara una etiqueta
CedulaLabel= Label(miFrame, text="Cedula:")
CedulaLabel.grid(row=2, column=0, sticky="e", padx=10, pady=10)
#se declara una etiqueta
FechaLabel= Label(miFrame, text="Fecha:")
FechaLabel.grid(row=3, column=0, sticky="e", padx=10, pady=10)
def codigoBoton():
while True:
_, img = cap.read()
data, bbox, _ = detector.detectAndDecode(img)
if(bbox is not None):
for i in range(len(bbox)):
cv2.line(img, tuple(bbox[i][0]), tuple(bbox[(i+1) % len(bbox)][0]), color=(255,
0, 255), thickness=2)
cv2.putText(img, data, (int(bbox[0][0][0]), int(bbox[0][0][1]) - 10), cv2.FONT_HERSHEY_SIMPLEX,
0.5, (0, 255, 0), 2)
if data:
if(control!=data):
try:
with conexion.cursor() as cursor:
consulta = "SELECT nombre, apellido FROM datos WHERE cedula = %s;"
cursor.execute(consulta, (data,))
# Con fetchall traemos todas las filas
datos = cursor.fetchall()
#print(datos)
# Recorrer e imprimir
#for dato in datos:
#print(dato)
except psycopg2.Error as e:
print("Ocurrió un error al consultar con where: ", e)
if datos:
tiempo=str(datetime.now())
for dato in datos:
snombre.set(dato[0])
sapellido.set(dato[1])
scedula.set(data)
sfecha.set(tiempo)
print( data, dato[0], tiempo)
else:
print("No registrado")
snombre.set("No registrado")
control=data
#cv2.imshow("Scanner QR", img)
#if(cv2.waitKey(1) == ord("q")):
break
botonEnvio=Button(raiz, text="Enviar", command=codigoBoton)
botonEnvio.pack()
conexion.close()
#cap.release()
#cv2.destroyAllWindows()
raiz.mainloop()
| 35.895833 | 107 | 0.572258 |
ab52a5eb73868fd22bc5762e5f9fdc6980193418 | 602 | asm | Assembly | oeis/140/A140404.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 11 | 2021-08-22T19:44:55.000Z | 2022-03-20T16:47:57.000Z | oeis/140/A140404.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 9 | 2021-08-29T13:15:54.000Z | 2022-03-09T19:52:31.000Z | oeis/140/A140404.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 3 | 2021-08-22T20:56:47.000Z | 2021-09-29T06:26:12.000Z | ; A140404: a(n) = binomial(n+5, 5)*7^n.
; 1,42,1029,19208,302526,4235364,54353838,652246056,7419298887,80787921214,848273172747,8636963213424,85649885199788,830145041167176,7886377891088172,73606193650156272,676256904160810749,6126091955339109138,54794489156088698401,484498640959100070072,4239363108392125613130,36741146939398421980460,315639853252104625195770,2689800488583152458190040,22751229132599164542190755,191110324713832982154402342,1595036171650067581827127239,13232892683319079197380611168,109171364637382403378390042136
mov $1,7
pow $1,$0
mov $2,$0
add $2,5
bin $2,$0
mul $1,$2
mov $0,$1
| 54.727273 | 492 | 0.862126 |
356759a2d64d2473e198748df1bcde154065994b | 555 | sql | SQL | sql/sp/sp_emails.sql | DanielNeodata/Cementerio.Disidentes | f815158c12ff953e7cbf2270c12bcb7a705d934d | [
"MIT"
] | null | null | null | sql/sp/sp_emails.sql | DanielNeodata/Cementerio.Disidentes | f815158c12ff953e7cbf2270c12bcb7a705d934d | [
"MIT"
] | null | null | null | sql/sp/sp_emails.sql | DanielNeodata/Cementerio.Disidentes | f815158c12ff953e7cbf2270c12bcb7a705d934d | [
"MIT"
] | null | null | null | USE [disidentes_new]
GO
/****** Object: StoredProcedure [dbo].[sp_emails] Script Date: 16/5/2021 23:49:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[sp_emails](
@remite varchar(max),
@destinatario varchar(max),
@subject varchar(max),
@body varchar(max),
@toName varchar(max),
@fromName varchar(max)
)
AS
INSERT INTO [dbo].[emails]
(remite,destinatario,[subject],[body],fecha_envio,toName,fromName)
VALUES
(@remite,@destinatario,@subject,@body,null,@toNmae,@fromName)
GO
| 19.137931 | 94 | 0.675676 |
da3a52750bf7373a979a047098e257b328e13bbf | 722 | php | PHP | Homework Submission/Homework 2/Insert_Table_Departments.php | antarmortuzansu/CSE311L_Section_1_Summer2020_NSU | 07c4a4154601e2def114001e147e33cfe257fd3e | [
"MIT"
] | null | null | null | Homework Submission/Homework 2/Insert_Table_Departments.php | antarmortuzansu/CSE311L_Section_1_Summer2020_NSU | 07c4a4154601e2def114001e147e33cfe257fd3e | [
"MIT"
] | null | null | null | Homework Submission/Homework 2/Insert_Table_Departments.php | antarmortuzansu/CSE311L_Section_1_Summer2020_NSU | 07c4a4154601e2def114001e147e33cfe257fd3e | [
"MIT"
] | null | null | null | <?php
$conn = mysqli_connect('localhost' , 'Heisenberg', 'Antarmeth26','Homework_002');
if ($error = $conn->connect_error) {
die("Not Connected, error: " . $error);
}
$sql = "INSERT INTO Departments(Department_id, Department_Name, Manager_id, Location_id)
VALUES
(10, 'Administration', 200, 1700),
(20, 'Marketing', 201, 1800),
(50, 'Shipping', 124, 1500),
(60, 'IT', 103, 1400),
(80, 'Sales', 149, 2500),
(90, 'Executive', 100, 1700),
(110, 'Accounting', 250, 1700),
(190, 'Contracting', 00 ,1700)";
if (mysqli_query($conn, $sql)) {
echo "Row Inserted in Table";
} else {
echo "Error: Could not Insert into Table. " . mysqli_connect_error($conn) . " " . mysqli_error($conn);
}
mysqli_close($conn);
| 23.290323 | 106 | 0.646814 |
c66e49a060bfee068df065edc564071652396da9 | 6,803 | py | Python | captcha_solver_object_detection/captcha_solver.py | gabrielmvas/captcha-solver | 94ec61ba9219fcef316d907257a5d42b20a90944 | [
"MIT"
] | null | null | null | captcha_solver_object_detection/captcha_solver.py | gabrielmvas/captcha-solver | 94ec61ba9219fcef316d907257a5d42b20a90944 | [
"MIT"
] | null | null | null | captcha_solver_object_detection/captcha_solver.py | gabrielmvas/captcha-solver | 94ec61ba9219fcef316d907257a5d42b20a90944 | [
"MIT"
] | null | null | null | from object_detection.utils import label_map_util, visualization_utils as vis_util
import tensorflow as tf
import pandas as pd
import numpy as np
import cv2 as cv
import sys
import os
import collections
from pathlib import Path
BASE_DIR = Path(__file__).parent
class CaptchaSolver(object):
def __init__(self):
self.num_classes = 36
self.labels_path = str((BASE_DIR / 'model/labelmap.pbtxt').resolve())
self.modelckpt_path = str((BASE_DIR / 'model/frozen_inference_graph.pb').resolve())
self.tolerance = 0.6
self.model = None
self.detection_graph = None
def __load_label_map(self):
label_map = label_map_util.load_labelmap(self.labels_path)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=self.num_classes, use_display_name=True)
category_index = label_map_util.create_category_index(categories)
return category_index
def __load_tfmodel(self):
self.detection_graph = tf.Graph()
with self.detection_graph.as_default():
od_graph_def = tf.GraphDef()
with tf.gfile.GFile(self.modelckpt_path , 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
self.model = tf.Session(graph=self.detection_graph)
def get_boxes_coordinates(self, image, boxes, classes, scores, category_index, instance_masks=None, instance_boundaries=None, keypoints=None, use_normalized_coordinates=False, max_boxes_to_draw=6, min_score_thresh=.5, agnostic_mode=False, line_thickness=4, groundtruth_box_visualization_color='black', skip_scores=False, skip_labels=False):
box_to_display_str_map = collections.defaultdict(list)
box_to_color_map = collections.defaultdict(str)
box_to_instance_masks_map = {}
box_to_instance_boundaries_map = {}
box_to_score_map = {}
box_to_keypoints_map = collections.defaultdict(list)
if not max_boxes_to_draw:
max_boxes_to_draw = boxes.shape[0]
for i in range(min(max_boxes_to_draw, boxes.shape[0])):
if scores is None or scores[i] > min_score_thresh:
box = tuple(boxes[i].tolist())
if instance_masks is not None:
box_to_instance_masks_map[box] = instance_masks[i]
if instance_boundaries is not None:
box_to_instance_boundaries_map[box] = instance_boundaries[i]
if keypoints is not None:
box_to_keypoints_map[box].extend(keypoints[i])
if scores is None:
box_to_color_map[box] = groundtruth_box_visualization_color
else:
display_str = ''
if not skip_labels:
if not agnostic_mode:
if classes[i] in category_index.keys():
class_name = category_index[classes[i]]['name']
else:
class_name = 'N/A'
display_str = str(class_name)
if not skip_scores:
if not display_str:
display_str = '{}%'.format(int(100*scores[i]))
else:
display_str = '{}: {}%'.format(display_str, int(100*scores[i]))
box_to_display_str_map[box].append(display_str)
box_to_score_map[box] = scores[i]
if agnostic_mode:
box_to_color_map[box] = 'DarkOrange'
else:
box_to_color_map[box] = vis_util.STANDARD_COLORS[classes[i] % len(vis_util.STANDARD_COLORS)]
coordinates_list = []
for box, color in box_to_color_map.items():
ymin, xmin, ymax, xmax = box
height, width, channels = image.shape
coordinate = dict(xmin=int(),xmax=int(),ymin=int(),ymax=int())
coordinate['ymin'] = int(ymin*height)
coordinate['ymax'] = int(ymax*height)
coordinate['xmin'] = int(xmin*width)
coordinate['xmax'] = int(xmax*width)
coordinates_list.append(coordinate)
return coordinates_list
def predict_captcha(self, image_path):
self.__load_tfmodel()
image_tensor = self.detection_graph.get_tensor_by_name('image_tensor:0')
detection_boxes = self.detection_graph.get_tensor_by_name('detection_boxes:0')
detection_scores = self.detection_graph.get_tensor_by_name('detection_scores:0')
detection_classes = self.detection_graph.get_tensor_by_name('detection_classes:0')
num_detections = self.detection_graph.get_tensor_by_name('num_detections:0')
image = cv.imread(image_path)
image_rgb = cv.cvtColor(image, cv.COLOR_BGR2RGB)
image_expanded = np.expand_dims(image_rgb, axis=0)
(boxes, scores, classes, num) = self.model.run([detection_boxes, detection_scores, detection_classes, num_detections],
feed_dict={image_tensor: image_expanded})
category_index = self.__load_label_map()
coordinates = self.get_boxes_coordinates(image, np.squeeze(boxes), np.squeeze(classes).astype(np.int32), np.squeeze(scores), category_index, min_score_thresh=self.tolerance)
digits = self.__get_digits_prediction(category_index, (boxes, scores, classes, num), coordinates)
solved_captcha = self.__get_solved_captcha(digits)
return solved_captcha
def __get_digits_prediction(self, category_index, model_output, coordinates, threshold=0.6):
digits = []
for x in range(len(model_output[1][0])):
if model_output[1][0][x] > threshold:
digits.append(dict(label=category_index[model_output[2][0][x]]['name'], score=float(model_output[1][0][x]),
coordenadas=coordinates[x], xmin=coordinates[x]['xmin']))
return sorted(digits, key=lambda digit:digit['xmin'])
def __get_solved_captcha(self, digits):
solved_captcha = ''
for digit in digits:
solved_captcha = solved_captcha + digit['label']
return solved_captcha
| 47.908451 | 344 | 0.593121 |
af9003a53d4c4f8783b32f064683910bb226ed82 | 8,946 | py | Python | shipt/receipts.py | dcalacci/shipt-calculator | b53f3d09594f9ed0b0f950f8646b9ba5dae94fd9 | [
"MIT"
] | 4 | 2021-03-14T21:43:30.000Z | 2021-11-17T10:53:10.000Z | shipt/receipts.py | dcalacci/shipt-calculator | b53f3d09594f9ed0b0f950f8646b9ba5dae94fd9 | [
"MIT"
] | 3 | 2021-01-20T17:34:13.000Z | 2021-09-13T17:05:04.000Z | shipt/receipts.py | dcalacci/shipt-calculator | b53f3d09594f9ed0b0f950f8646b9ba5dae94fd9 | [
"MIT"
] | null | null | null | from PIL import Image, ImageEnhance, ImageFilter
from datetime import datetime
import pytesseract
import argparse
import cv2
import os
import glob
import pandas as pd
import numpy as np
import string
import random
import math
def strip_punc(s): return s.translate(
str.maketrans('', '', string.punctuation))
def image_to_text(image_filename):
image = cv2.imread(image_filename)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# scale 1.5x
gray = cv2.resize(gray, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)
# enhancer = ImageEnhance.Contrast(gray)
# gray = enhancer.enhance(2)
# gray = gray.convert('1')
# random filename
filename = "/tmp/{}.png".format(os.getpid() + random.randint(1, 100))
cv2.imwrite(filename, gray)
text = pytesseract.image_to_string(Image.open(filename),
config='--psm 6')
os.remove(filename)
return text
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
def bad_entries_to_na(data):
for k, v in data.items():
if k in ['delivery_window_start', 'delivery_window_end',
'order_pay', 'order_total', 'tip', 'total_pay']:
test_str = str(v).replace("PM", "").replace("AM", "")
if not is_number(test_str):
data[k] = np.nan
return data
def to_number_or_none(x):
try:
return pd.to_numeric(x)
except:
return None
def guess_better_numbers(data):
""" Guesses better numbers if the order pay, tip, promo pay, and total pay don't add up.
also creates a new order number from the pay #s if it's been parsed wrong. We check if the order
number has been parsed wrong by testing if it's parse-able into a number.
new order # is: <tip><totalpay><delivery day-of-month>
"""
if 'tip' not in data or 'order_pay' not in data or 'promo_pay' not in data:
return data
data['tip'] = to_number_or_none(data['tip'])
data['total_pay'] = to_number_or_none(data['total_pay'])
data['order_pay'] = to_number_or_none(data['order_pay'])
data['promo_pay'] = to_number_or_none(data['promo_pay'])
if (data['order_pay'] == None or data['total_pay'] == None):
return data
while data['order_pay'] > data['total_pay']:
data['order_pay'] = round(data['order_pay'] / 10, 2)
while data['tip'] > data['total_pay']:
data['tip'] = round(data['tip'] / 10, 2)
if data['tip'] + data['order_pay'] + data['promo_pay'] != data['total_pay']:
# the order pay is *always* a decimal, basically. if it's not,
# it almost definitely means it was parsed incorrectly.
# breaks, obviously, when tip is greater than promo pay, but that
# rarely happens.
if data['order_pay'] > data['total_pay']:
data['order_pay'] == data['total_pay'] - \
data['promo_pay'] - data['tip']
elif data['total_pay'] > data['order_pay'] + data['tip'] + data['promo_pay']:
data['total_pay'] = data['order_pay'] + \
data['tip'] + data['promo_pay']
elif data['tip'] > data['total_pay']:
data['tip'] = data['total_pay'] - \
data['order_pay'] - data['promo_pay']
# order number
new_ordernum = "{}{}{}".format(
int(data['tip']),
int(data['total_pay']),
data['delivery_date'].split('/')[1])
if 'order_number' not in data:
data['order_number'] = new_ordernum
else:
try:
ordernum = int(data['order_number'])
except ValueError:
data['order_number'] = new_ordernum
return data
def receipt_to_df(image_filename, verbose=False):
text = image_to_text(image_filename)
def fword(s): return s.split(" ")[0]
def line_items(s): return s.split(" ")
all_data = []
data = {}
if verbose:
print("-----------------")
print(image_filename)
lines = text.split("\n")
for n, line in enumerate(lines):
first_word = fword(line)
if verbose:
print(line_items(line))
print('window' in line.lower())
print(line.lower())
print(first_word)
if (first_word == 'Window'):
if (verbose):
print("new delivery window parsing...")
lm = line_items(line)
month = lm[1]
day = lm[2]
times = lm[3].split("-")
# assume current year
year = datetime.today().year
date = datetime.strptime("{} {} {}".format(
month, day, year), "%b %d, %Y")
datestr = datetime.strftime(date, "%m/%d/%Y")
data['delivery_window_start'] = times[0]
data['delivery_window_end'] = times[1]
data['delivery_date'] = datestr
data['delivered_date'] = datestr
elif (first_word == 'Delivery'):
if line_items(line)[1] == "Only":
data["delivery_only"] = True
continue
elif "delivery_only" not in data:
data["delivery_only"] = False
if 'window' in line.lower():
if (verbose):
print("delivery window parsing...", line, lines[n+1])
if len(line_items(line)) == 2:
line = " ".join([line, lines[n+1]])
delivery_window = line.split(":")[-1] # gets the XX to XX
data["delivery_date"] = line_items(line)[2].split(":")[
0].strip() # removes colon
data["delivery_window_start"] = strip_punc(
delivery_window.split("to")[0].strip())
data["delivery_window_end"] = strip_punc(
delivery_window.split("to")[1].strip())
elif (first_word == 'Delivered'):
data["delivered_date"] = line_items(line)[1][:-1] # removes comma
if data["delivered_date"] == "Today":
data["delivered_date"] = datetime.now().strftime("%m/%d/%Y")
data["delivered_time"] = " ".join(
line_items(line)[2:]) # merges time and AM/PM
elif (first_word == 'Order' and line_items(line)[1] == 'Pay'):
data["order_pay"] = line_items(
line)[2][1:].strip().replace(",", "")
elif (first_word == 'Order'):
# new cards only have 4 on this line
data["order_number"] = strip_punc(
line_items(line)[1]) # remove hash
# Some of them don't have an order total
if len(line_items(line)) >= 4:
# sometimes it picks up the dot between total and the amount as a plus
# or an arrow but sometimes, it doesn't. If it has this, it's pretty
# likely there's an order total.
if (any(c in line_items(line)[2].strip() for c in ["+", "*", "-", "»", "«"]) or
len(line_items(line)[2]) == 1):
print("ORDER TOTAL")
data["order_total"] = line_items(
line)[3][1:].strip().replace(",", "")
print(data['order_total'])
else:
print("ORDER total 2222")
data["order_total"] = line_items(
line)[2][1:].strip().replace(",", "")
print(data['order_total'])
else:
data["order_total"] = np.nan
if "Time" in line_items(line)[-1]:
data["late"] = False
elif "Late" in line_items(line)[-1]:
data["late"] = True
elif (first_word == "Tip"):
data["tip"] = line_items(line)[-1][1:]
elif (first_word == 'Promo'):
data["promo_pay"] = line_items(line)[2][1:].strip()
elif (first_word == "Total"):
data["total_pay"] = line_items(
line)[2][1:].strip().replace(",", "")
if 'promo_pay' not in data:
data['promo_pay'] = 0
data["filename"] = image_filename
data = guess_better_numbers(data)
## make sure order_total is in there too -- if it's not, we can't use it as data.
if 'order_number' in data and data['order_number'] != '' and 'order_total' in data:
if verbose:
print("Adding", data, "to all_data...")
all_data.append(data)
data = {}
else:
continue
df = pd.DataFrame(all_data)
df["date_submitted"] = datetime.now().strftime("%m/%d/%Y")
df[["order_pay", "tip", "order_total", "total_pay", "promo_pay"]] = df[["order_pay", "tip",
"order_total", "total_pay", "promo_pay"]].apply(to_number_or_none)
return df.fillna("")
| 39.409692 | 142 | 0.533646 |
7293b57a54d892d8eb4e6b11205f498da8e62a76 | 438 | cs | C# | 2021-01-07 left join in entity framework/Person.cs | jtenos/60-second-dev | 24f3e73cc57d137a699daa0e249b426a552bd1d5 | [
"CC0-1.0"
] | 2 | 2021-07-08T15:45:18.000Z | 2021-08-15T13:48:27.000Z | 2021-01-07 left join in entity framework/Person.cs | jtenos/60-second-dev | 24f3e73cc57d137a699daa0e249b426a552bd1d5 | [
"CC0-1.0"
] | null | null | null | 2021-01-07 left join in entity framework/Person.cs | jtenos/60-second-dev | 24f3e73cc57d137a699daa0e249b426a552bd1d5 | [
"CC0-1.0"
] | 4 | 2021-05-18T22:40:30.000Z | 2022-03-06T19:40:57.000Z | using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
[Table("People")]
public class Person
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int PersonID { get; set; }
public string FirstName { get; set; } = default!;
public int? FavoriteFoodID { get; set; }
[ForeignKey(nameof(FavoriteFoodID))]
public Food? FavoriteFood { get; set; }
} | 31.285714 | 63 | 0.705479 |
ee8d15bd96c257b041c33ed8028b9dbc5249b23f | 449 | sql | SQL | delab/sql/find_bad_tweets.sql | juliandehne/delab | 763dbab38527e3fcc1caa5e19c74678f591fcc64 | [
"MIT"
] | null | null | null | delab/sql/find_bad_tweets.sql | juliandehne/delab | 763dbab38527e3fcc1caa5e19c74678f591fcc64 | [
"MIT"
] | 12 | 2021-11-01T07:03:15.000Z | 2022-03-31T13:03:38.000Z | delab/sql/find_bad_tweets.sql | juliandehne/delab | 763dbab38527e3fcc1caa5e19c74678f591fcc64 | [
"MIT"
] | null | null | null | select language,text from delab_tweet where to_tsvector(text) @@ to_tsquery('beaner | chinc | chink | coon | dego | gook | guido | heeb | kike | kyke | jigaboo | negro | nigger | niglet | porchmonkey | pollock | ruski | sandnigger | wop') and language='den';
select language,text from delab_tweet where to_tsvector(text) @@ to_tsquery('Judensau | Kopftuchträger | Neger | Schlitzauge | Zigeuner | Schlampe | Schwuchtel | Nutte' ) and language='de'
| 112.25 | 258 | 0.728285 |
dcf3d63ccc846a7d2d072fd26c10a1679db88d50 | 54 | rb | Ruby | app/models/dictionaries/address_type.rb | LeonidMarushevskyi/CALS | 42542c93cc105751ed5b757beb84139bcc135f2d | [
"MIT",
"Ruby",
"Apache-2.0",
"BSD-3-Clause"
] | 1 | 2021-06-03T05:34:49.000Z | 2021-06-03T05:34:49.000Z | app/models/dictionaries/address_type.rb | LeonidMarushevskyi/CALS | 42542c93cc105751ed5b757beb84139bcc135f2d | [
"MIT",
"Ruby",
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | app/models/dictionaries/address_type.rb | LeonidMarushevskyi/CALS | 42542c93cc105751ed5b757beb84139bcc135f2d | [
"MIT",
"Ruby",
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | class Dictionaries::AddressType < DictionaryBase
end
| 13.5 | 48 | 0.833333 |
77817f927a0cf9941f5441a8d8ecf2c5bf9880eb | 1,127 | h | C | Frameworks/IDEFoundation/IDECodesignParameterSnapshot.h | cameroncooke/XcodeHeaders | be955d30b5fc62c4312b354045b4561d164ebd9c | [
"MIT"
] | 1 | 2016-03-30T10:07:37.000Z | 2016-03-30T10:07:37.000Z | Frameworks/IDEFoundation/IDECodesignParameterSnapshot.h | cameroncooke/XcodeHeaders | be955d30b5fc62c4312b354045b4561d164ebd9c | [
"MIT"
] | null | null | null | Frameworks/IDEFoundation/IDECodesignParameterSnapshot.h | cameroncooke/XcodeHeaders | be955d30b5fc62c4312b354045b4561d164ebd9c | [
"MIT"
] | null | null | null | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "NSObject.h"
@class DVTSigningCertificate, NSString;
@interface IDECodesignParameterSnapshot : NSObject
{
id <DVTProvisioningProfile> _provisioningProfile;
DVTSigningCertificate *_signingCertificate;
NSString *_identityHash;
}
+ (id)_snapshotForAdHocSigning;
+ (id)_snapshotForNullSigning;
+ (id)_snapshotWithProvisioningProfile:(id)arg1 andSigningCertificate:(id)arg2;
+ (id)_snapshotWithSigningCertificate:(id)arg1;
+ (id)_snapshotWithIdentityHash:(id)arg1;
@property(copy) NSString *identityHash; // @synthesize identityHash=_identityHash;
@property(retain) DVTSigningCertificate *signingCertificate; // @synthesize signingCertificate=_signingCertificate;
@property(retain) id <DVTProvisioningProfile> provisioningProfile; // @synthesize provisioningProfile=_provisioningProfile;
- (void).cxx_destruct;
- (BOOL)isEqual:(id)arg1;
- (unsigned long long)hash;
@property(readonly) _Bool willSign;
@property(readonly) _Bool isAdHocIdentity;
- (id)description;
@end
| 32.2 | 123 | 0.781721 |
5d82b2ab1383988cec2233998bf0abb3ca909c65 | 1,157 | dart | Dart | main.dart | Ddhruv-IOT/Let-s-Gossip-code | 0ef03d8a3f6bf1317812f7fda172b3cb2959b48a | [
"MIT"
] | null | null | null | main.dart | Ddhruv-IOT/Let-s-Gossip-code | 0ef03d8a3f6bf1317812f7fda172b3cb2959b48a | [
"MIT"
] | null | null | null | main.dart | Ddhruv-IOT/Let-s-Gossip-code | 0ef03d8a3f6bf1317812f7fda172b3cb2959b48a | [
"MIT"
] | null | null | null | import 'package:whatschat/maps.dart';
import 'splash.dart';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'home.dart';
import 'register.dart';
import 'login.dart';
import 'chat.dart';
import 'location.dart';
//import 'myimage_camera.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
Firebase.initializeApp();
runApp(
MaterialApp(
theme: ThemeData(
fontFamily: 'Georgia',
textTheme: TextTheme(
headline1: TextStyle(fontSize: 72.0, fontWeight: FontWeight.bold),
headline6: TextStyle(fontSize: 36.0, fontStyle: FontStyle.italic),
bodyText2: TextStyle(fontSize: 14.0, fontFamily: 'Hind'),
),
),
initialRoute: "splash",
routes: {
"splash": (context) => MyApp(),
"home": (context) => Myhome(),
"reg": (context) => MyReg(),
"login": (context) => MyLogin(),
"chat": (context) => Mychat(),
"location": (context) => Gmaps(),
"maps": (context) => Maps(),
},
debugShowCheckedModeBanner: false,
),
);
}
| 29.666667 | 77 | 0.589455 |
a0770e77657585d618ea2e03af953d28e493fd4f | 743 | swift | Swift | SwiftWamp/Messages/PubSub/Subscriber/UnsubscribeSwampMessage.swift | theochemel/SwiftWamp | 71d10ba8dad07a9420b045873545ce960a2cc9cb | [
"MIT"
] | null | null | null | SwiftWamp/Messages/PubSub/Subscriber/UnsubscribeSwampMessage.swift | theochemel/SwiftWamp | 71d10ba8dad07a9420b045873545ce960a2cc9cb | [
"MIT"
] | null | null | null | SwiftWamp/Messages/PubSub/Subscriber/UnsubscribeSwampMessage.swift | theochemel/SwiftWamp | 71d10ba8dad07a9420b045873545ce960a2cc9cb | [
"MIT"
] | 1 | 2019-08-31T07:38:30.000Z | 2019-08-31T07:38:30.000Z | //
// UnsubscribeSwampMessage.swift
// Pods
//
// Created by Yossi Abraham on 24/08/2016.
//
//
import Foundation
/// [UNSUBSCRIBE, requestId|number, subscription|number]
class UnsubscribeSwampMessage: SwampMessage {
let type: SwampMessageType = .unsubscribe
let requestId: Int
let subscription: NSNumber
init(requestId: Int, subscription: NSNumber) {
self.requestId = requestId
self.subscription = subscription
}
// MARK: SwampMessage protocol
required init(payload: [Any]) {
self.requestId = payload[0] as! Int
self.subscription = payload[1] as! NSNumber
}
func marshal() -> [Any] {
return [self.type.rawValue, self.requestId, self.subscription]
}
}
| 21.228571 | 70 | 0.66218 |
81b86e64e6951416c487d33c6c9efa699bcd2df4 | 2,168 | swift | Swift | Sources/SoundpipeAudioKit/Effects/VariableDelay.swift | Moriquendi/SoundpipeAudioKit | 086653b852094586f11c84d48286beae1e2b0929 | [
"MIT"
] | 30 | 2021-05-21T14:09:12.000Z | 2022-03-17T16:12:09.000Z | Sources/SoundpipeAudioKit/Effects/VariableDelay.swift | Moriquendi/SoundpipeAudioKit | 086653b852094586f11c84d48286beae1e2b0929 | [
"MIT"
] | 12 | 2021-05-29T06:56:08.000Z | 2022-01-29T15:59:06.000Z | Sources/SoundpipeAudioKit/Effects/VariableDelay.swift | Moriquendi/SoundpipeAudioKit | 086653b852094586f11c84d48286beae1e2b0929 | [
"MIT"
] | 19 | 2021-06-10T03:30:07.000Z | 2022-03-22T16:48:04.000Z | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
// This file was auto-autogenerated by scripts and templates at http://github.com/AudioKit/AudioKitDevTools/
import AVFoundation
import AudioKit
import AudioKitEX
import CSoundpipeAudioKit
/// A delay line with cubic interpolation.
public class VariableDelay: Node {
let input: Node
/// Connected nodes
public var connections: [Node] { [input] }
/// Underlying AVAudioNode
public var avAudioNode = instantiate(effect: "vdla")
// MARK: - Parameters
/// Specification details for time
public static let timeDef = NodeParameterDef(
identifier: "time",
name: "Delay time (Seconds)",
address: akGetParameterAddress("VariableDelayParameterTime"),
defaultValue: 0,
range: 0 ... 10,
unit: .seconds)
/// Delay time (in seconds) This value must not exceed the maximum delay time.
@Parameter(timeDef) public var time: AUValue
/// Specification details for feedback
public static let feedbackDef = NodeParameterDef(
identifier: "feedback",
name: "Feedback (%)",
address: akGetParameterAddress("VariableDelayParameterFeedback"),
defaultValue: 0,
range: 0 ... 1,
unit: .generic)
/// Feedback amount. Should be a value between 0-1.
@Parameter(feedbackDef) public var feedback: AUValue
// MARK: - Initialization
/// Initialize this delay node
///
/// - Parameters:
/// - input: Input node to process
/// - time: Delay time (in seconds) This value must not exceed the maximum delay time.
/// - feedback: Feedback amount. Should be a value between 0-1.
/// - maximumTime: The maximum delay time, in seconds.
///
public init(
_ input: Node,
time: AUValue = timeDef.defaultValue,
feedback: AUValue = feedbackDef.defaultValue,
maximumTime: AUValue = 5
) {
self.input = input
setupParameters()
akVariableDelaySetMaximumTime(au.dsp, maximumTime)
self.time = time
self.feedback = feedback
}
}
| 30.111111 | 108 | 0.654059 |
54fede4e6e6c93355e88c1c9098476e86f428f8b | 890 | css | CSS | frontend/web/public/css/pagecss.css | zcwzz/gittao | fa776047adacadc2eb1fda6c6e47eb592abf5821 | [
"BSD-3-Clause"
] | null | null | null | frontend/web/public/css/pagecss.css | zcwzz/gittao | fa776047adacadc2eb1fda6c6e47eb592abf5821 | [
"BSD-3-Clause"
] | null | null | null | frontend/web/public/css/pagecss.css | zcwzz/gittao | fa776047adacadc2eb1fda6c6e47eb592abf5821 | [
"BSD-3-Clause"
] | null | null | null | .tcdPageCode{
padding: 15px 20px;
text-align: left;
color: #ccc;
}
.tcdPageCode a{
display: inline-block;
color: #666;
display: inline-block;
height: 25px;
line-height: 25px;
padding: 5px 15px;
border: 1px solid #ddd;
margin-right: 10px;
border-radius: 4px;
vertical-align: middle;
background-color: #fff;
}
.tcdPageCode a:hover{
text-decoration: none;
border: 1px solid #428bca;
}
.tcdPageCode span.current{
display: inline-block;
height: 25px;
line-height: 25px;
padding: 5px 15px;
margin-right: 10px;
color: #f33b36;
/* background-color: #428bca; */
border: 1px solid #428bca;
border-radius: 4px;
vertical-align: middle;
}
.tcdPageCode span.disabled{
display: inline-block;
height: 25px;
line-height: 25px;
padding: 5px 15px;
margin-right: 10px;
color: #666;
background: #f2f2f2;
border: 1px solid #bfbfbf;
border-radius: 4px;
vertical-align: middle;
} | 19.347826 | 33 | 0.708989 |
2c62f406122f411034e72c66b8c2b1d7643ab8be | 5,239 | py | Python | Experiments/CodeBert_CodeToText/Preprocessing/jsonl_to_java.py | wubero/Lampion | 8a81b3381dee48ffab8cf7ee1b57e0eea8aaeba2 | [
"MIT"
] | 1 | 2022-02-20T11:42:18.000Z | 2022-02-20T11:42:18.000Z | Experiments/CodeBert_CodeToText/Preprocessing/jsonl_to_java.py | ciselab/Lampion | ba457d152a83e9b58072ec4676cc340b5b5afb1b | [
"MIT"
] | 28 | 2021-12-06T07:10:27.000Z | 2022-03-25T09:42:51.000Z | Experiments/CodeBert_CodeToText/Preprocessing/jsonl_to_java.py | wubero/Lampion | 8a81b3381dee48ffab8cf7ee1b57e0eea8aaeba2 | [
"MIT"
] | 2 | 2021-11-25T08:32:45.000Z | 2022-02-20T11:42:27.000Z | import jsonlines # For adressing json values as dictionaries in jsonl files
import os # For File/Directory Creation
import sys # For handling command args
"""
Notes:
The filename needs to be class+function as otherwise they will overwrite each other
"""
#TODO: Add a bit of debug info
def readJsonl_andPrintAllToJava(jsonl_file: str, output_prefix:str = "./output/") -> ():
"""
This method reads a jsonl_file and creates a javafile for each entry found.
It also adds the remaining information of the json as a header to the file in a comment.
:param jsonl_file: the filepath to look for the jsonl
:return: nothing, creates one java file per line found
"""
counter = 0
with jsonlines.open(jsonl_file) as f:
for line in f.iter():
write_to_file(line,output_prefix)
counter = counter + 1
print(f"Wrote {counter} Entries from the JSONL file {jsonl_file} to .java files in {output_prefix}.")
def write_to_file(line:str, output_prefix: str = "./output/" ) -> ():
"""
This method creates a full java file given a jsonl line.
The java file will be created and named according to the the path and file name specified in the json line.
:param line: The JsonL line to be written to the file
:param output_prefix: the directory to which to write all the files, default to ./output/
:return: creates a directory
"""
# Read all relevant position information from the jsonl
(path, filename, package, classname) = split_path_to_parts(line['path'])
# Create the directories if necessary
p = output_prefix + "/" + path
os.makedirs(p,exist_ok=True)
# create the file, fill it with the java class and close it
func = line['func_name'].split('.')[1]
f = open(output_prefix + "/" + path + "/" + classname + "_" + func + ".java","w")
f.write(wrap_in_class_and_package(line))
f.close()
# This var simply holds all seen combinations of function and class names
# It is necessary as some methods are overloaded and would result in the same file
# Which results in issues with the java obfuscation which fails on duplicate java classes
seen_class_names = []
def wrap_in_class_and_package(line):
"""
Wraps the content of the given line into a java package+class+markup_info
Required as the entries are on function level,but the obfuscator runs on class level.
This method does not write to a file, it simply alters the dictionary to a string.
TODO: Maybe better format for markups, maybe move header up before the package
:param line: the line of jsonl to be wrapped in a .java file with markup words for other attributes
:return: the line wrapped in package and class
"""
(path, file, package, classname) = split_path_to_parts(line['path'])
func = line['func_name'].split('.')[1]
# There was an issue on the java-obfuscation side that had troubles with duplicate java classes
# This was due to the naming here, especially for overloaded functions
# Hence, if there was a method already seen, just add a counter at the end of the classname to be unique
final_classname=f"{classname}_{func}"
counter = 2
while(final_classname in seen_class_names):
final_classname=f"{classname}_{func}_{counter}"
counter = counter + 1
seen_class_names.append(final_classname)
# Python has escape, but double { are the {-escape
filecontent = f"""
package {package};
/*
python_helper_header_start
ur_repo {line['repo']} ur_repo
ur_url {line['url']} ur_url
ur_path {line['path']} ur_path
ur_func_name {line['func_name']} ur_func_name
ur_docstring {(line['docstring']).encode('utf-8')} ur_docstring
ur_doctokens {line['docstring_tokens']} ur_doctokens
ur_sha {line['sha']} ur_sha
ur_partition {line['partition']} ur_partition
python_helper_header_end
*/
public class {final_classname} {{
{line['code']}
}}
"""
return filecontent
def split_path_to_parts(path: str):
"""
Helper to separate paths into information pieces
:param path: the path of a java file including the file itself
:return: a tuple of path,file,package name derived from path and class name derived from file
"""
parts = path.split('/')
package = ".".join(parts[:-1])
path = "/".join(parts[:-1])
file_name = parts[-1]
classname = file_name.split(".")[0]
values = (path,file_name,package,classname)
return values
if __name__ == '__main__':
"""
Note: The args start at 1, because sys.argv[0] is the script name itself
"""
print("Running JsonL to Java ")
if(len(sys.argv)==1):
print("received no arguments - trying to default to 'java.jsonl' and writing to 'output'")
readJsonl_andPrintAllToJava('java.jsonl')
elif(len(sys.argv)==2):
print(f"Trying to read {sys.argv[1]}, writing to 'output'")
readJsonl_andPrintAllToJava(sys.argv[1])
elif(len(sys.argv)==3):
print(f"Trying to read {sys.argv[1]}, writing to {sys.argv[2]}")
readJsonl_andPrintAllToJava(sys.argv[1],sys.argv[2])
else:
print("Received an unkown number of arguments - aborting") | 41.912 | 111 | 0.683718 |
f95562523b9fa2158501687fbdb772073ea275a2 | 6,235 | go | Go | utils/wal.go | homingway/hickwall | 2e1063aa3cf5eeee29adc3a494c3633ec8fc4e0c | [
"Apache-2.0"
] | 2 | 2016-10-21T12:24:49.000Z | 2017-03-30T06:04:51.000Z | utils/wal.go | homingway/hickwall | 2e1063aa3cf5eeee29adc3a494c3633ec8fc4e0c | [
"Apache-2.0"
] | null | null | null | utils/wal.go | homingway/hickwall | 2e1063aa3cf5eeee29adc3a494c3633ec8fc4e0c | [
"Apache-2.0"
] | 1 | 2019-01-14T07:09:16.000Z | 2019-01-14T07:09:16.000Z | package utils
import (
"bufio"
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
// "path"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"time"
)
type Wal struct {
lock sync.Mutex
filename string // should be set to the actual filename
fp *os.File
max_size_kb int64 // max size in kb
max_rolls int
stop chan bool // stop chan
is_index bool
}
var (
islast bool
indexfilename string
datafile string
offset int64
)
// func Split(path string) (dir, file string) {
// i := strings.LastIndex(path, "\\")
// return path[:i+1], path[i+1:]
// }
// func Join(elem ...string) string {
// for i, e := range elem {
// if e != "" {
// return path.Clean(strings.Join(elem[i:], ""))
// }
// }
// return ""
// }
// fileExists return flag whether a given file exists
// and operation error if an unclassified failure occurs.
func fileExists(path string) (bool, error) {
_, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
return true, nil
}
//the position of string in slice
func pos(value string, slice []string) int {
for p, v := range slice {
if v == value {
return p
}
}
return -1
}
// Make a new wal. Return nil if error occurs during setup.
func NewWal(filename string, max_size_kb int64, max_rolls int, is_index bool) (*Wal, error) {
var lock sync.Mutex
w := &Wal{filename: filename,
lock: lock,
max_size_kb: max_size_kb,
max_rolls: max_rolls,
stop: make(chan bool),
is_index: is_index,
}
err := w.create_output(filename)
if err != nil {
return nil, err
}
if is_index {
indexfilename = filename + ".index"
}
go w.watching_myself(w.stop)
return w, nil
}
func (w *Wal) Close() error {
w.stop <- true
return nil
}
func (w *Wal) ListArchives() []string {
archives := []string{}
dir, _ := filepath.Split(w.filename)
// dir := w.filename[:strings.LastIndex(w.filename, "\\")+1]
files, _ := ioutil.ReadDir(dir)
for _, file := range files {
if file.IsDir() {
continue
} else {
archives = append(archives, filepath.Join(dir, file.Name()))
}
}
sort.Sort(sort.StringSlice(archives))
return archives
}
// Write satisfies the io.Writer interface.
func (w *Wal) Write(output []byte) (int, error) {
w.lock.Lock()
defer w.lock.Unlock()
return w.fp.Write(output)
}
func (w *Wal) WriteLine(data string) (int, error) {
return w.Write([]byte(data + "\n"))
}
func (w *Wal) watching_myself(stop chan bool) {
if stop == nil {
panic("stop chan is nil")
}
tick := time.Tick(time.Second)
for {
select {
case <-tick:
currentSize, err := w.GetSizeKb()
if err != nil {
return
}
if currentSize > w.GetLimitKb() {
// rotate.
err := w.rotate()
if err != nil {
fmt.Println(err)
}
}
case <-stop:
return
}
}
}
func (w *Wal) GetSizeKb() (int64, error) {
fi, err := os.Stat(w.filename)
if err != nil {
return 0, err
}
return fi.Size() / 1024, nil
}
func (w *Wal) GetLimitKb() int64 {
return w.max_size_kb
}
func (w *Wal) create_output(log_filepath string) (err error) {
w.lock.Lock()
defer w.lock.Unlock()
if w.fp != nil {
w.fp.Close()
w.fp = nil
}
output, err := os.OpenFile(log_filepath[:], os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)
w.fp = output
if err != nil {
return err
}
return
}
// Perform the actual act of rotating and reopening file.
func (w *Wal) rotate() (err error) {
w.lock.Lock()
defer w.lock.Unlock()
// Close existing file if open
if w.fp != nil {
err = w.fp.Close()
w.fp = nil
if err != nil {
return
}
}
// Rename dest file if it already exists
var newname string
_, err = os.Stat(w.filename)
if err == nil {
newname = w.filename + "." + time.Now().Format("20060102_150405")
err = os.Rename(w.filename, newname)
if err != nil {
return
}
}
//remove over file
files := w.ListArchives()
if len(files) > w.max_rolls {
for _, file := range files[:len(files)-w.max_rolls] {
os.Remove(file)
}
}
// Create a file.
// w.fp, err = os.Create(w.filename)
w.fp, err = os.OpenFile(w.filename, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)
if w.is_index {
datafile, _, err = w.GetIndex()
if err == nil {
if datafile == "" || datafile == w.filename {
datafile = newname
}
err := w.SetIndex()
if err != nil {
fmt.Println(err)
}
}
}
return
}
// commit index.
func (w *Wal) Commit() (err error) {
if islast == true {
err = w.DeleteFinishedArchives()
if err == nil {
islast = false
}
}
if exist, _ := fileExists(datafile); exist == true {
w.SetIndex()
}
return
}
func (w *Wal) DeleteFinishedArchives() (err error) {
w.lock.Lock()
defer w.lock.Unlock()
err = os.Remove(datafile)
if err != nil {
fmt.Println(err)
}
files := w.ListArchives()
if len(files) >= 2 {
datafile = files[len(files)-2]
}
offset = 0
return
}
//read line refer to index
func (w *Wal) ReadLine() (line string, err error) {
var (
file *os.File
part []byte
prefix bool
)
datafile, offset, err = w.GetIndex()
exist, err := fileExists(datafile)
if datafile == "" || !exist {
files := w.ListArchives()
if len(files) >= 1 {
datafile = files[len(files)-1]
} else {
datafile = w.filename
}
}
if file, err = os.Open(datafile); err != nil {
return
}
defer file.Close()
file.Seek(offset, os.SEEK_CUR)
reader := bufio.NewReader(file)
buffer := bytes.NewBuffer(make([]byte, 1024))
part, prefix, err = reader.ReadLine()
buffer.Write(part)
if !prefix {
line = buffer.String()
buffer.Reset()
}
if err == io.EOF {
islast = true
return
}
offset += int64(len(line) - 1024 + len("\n"))
return
}
//set index
func (w *Wal) SetIndex() error {
newindex := datafile + "|" + strconv.FormatInt(offset, 10)
ioutil.WriteFile(indexfilename, []byte(newindex), 0)
return nil
}
//get index
func (w *Wal) GetIndex() (string, int64, error) {
if exist, _ := fileExists(indexfilename); exist != true {
return "", 0, nil
}
buf, err := ioutil.ReadFile(indexfilename)
if err != nil {
return "", 0, err
}
index := string(buf)
ss := strings.Split(index, "|")
off, err := strconv.ParseInt(ss[1], 10, 64)
file := ss[0]
return file, off, nil
}
| 18.836858 | 93 | 0.615557 |
d310bafd38f4867ca68c0927fe1c06ca477bae33 | 1,194 | cs | C# | YouGe.Core.DbContexts/YouGeUnitWork.cs | chenqiangdage/YouGe.Core | 72e19fc1efac5ece86cef10f3c9c770deb0b42ae | [
"MIT"
] | null | null | null | YouGe.Core.DbContexts/YouGeUnitWork.cs | chenqiangdage/YouGe.Core | 72e19fc1efac5ece86cef10f3c9c770deb0b42ae | [
"MIT"
] | null | null | null | YouGe.Core.DbContexts/YouGeUnitWork.cs | chenqiangdage/YouGe.Core | 72e19fc1efac5ece86cef10f3c9c770deb0b42ae | [
"MIT"
] | 1 | 2021-06-21T12:48:15.000Z | 2021-06-21T12:48:15.000Z | using Microsoft.EntityFrameworkCore.Storage;
using System;
using System.Collections.Generic;
using System.Text;
using YouGe.Core.Interface.IDbContexts;
namespace YouGe.Core.DbContexts
{
public class YouGeUnitWork: IYouGeUnitWork
{
public IYouGeDbContext _baseDbContext;
public YouGeUnitWork(IYouGeDbContext baseDbContext)
{
_baseDbContext = baseDbContext;
}
public IDbContextTransaction StartTransation()
{
return this._baseDbContext.GetDatabase().BeginTransaction();
}
public bool TransationSave(int resultcount)
{
using (var tran = this._baseDbContext.GetDatabase().BeginTransaction())
{
int result = this._baseDbContext.SaveChanges();
if (result == resultcount)
{
tran.Commit();
return true;
}
else
{
tran.Rollback();
return false;
}
}
}
public int Save()
{
return this._baseDbContext.SaveChanges();
}
}
}
| 25.956522 | 83 | 0.539363 |
7478201dcafc8a2a68729a6ccd13ac1cff279ed7 | 5,348 | css | CSS | public/static/wap/css/44.873f484cbdb7c889c5a2.css | yuan954/falv | 2c8ba437dbc0c84d967d61a820ef15073d14ba07 | [
"Apache-2.0"
] | null | null | null | public/static/wap/css/44.873f484cbdb7c889c5a2.css | yuan954/falv | 2c8ba437dbc0c84d967d61a820ef15073d14ba07 | [
"Apache-2.0"
] | null | null | null | public/static/wap/css/44.873f484cbdb7c889c5a2.css | yuan954/falv | 2c8ba437dbc0c84d967d61a820ef15073d14ba07 | [
"Apache-2.0"
] | null | null | null | .titleBox[data-v-77b08f5f]{width:7.5rem;height:.88rem;line-height:.88rem;background:#fff;padding:0 .2rem 0 .18rem;color:#1972ea;z-index:10}.titleBox[data-v-77b08f5f] img{width:.44rem;height:.44rem;vertical-align:middle}.titleBox .is-right[data-v-77b08f5f] img{position:absolute;right:.22rem;top:.22rem}.titleBox .is-left img[data-v-77b08f5f]{margin-right:.44rem}.titleBox>.is-left[data-v-77b08f5f],.titleBox>.is-right[data-v-77b08f5f]{width:.61rem}.titleBox h1[data-v-77b08f5f]{color:#333;font-weight:600;font-size:.36rem}.titleBox .is-right[data-v-77b08f5f] a{display:block;width:100%;height:.88rem}.titleBox .is-right[data-v-77b08f5f] a span{position:absolute;top:.11rem;right:.1rem;width:.32rem;height:.32rem;line-height:.32rem;text-align:center;font-size:.2rem;background:#eb3232;border-radius:50%;color:#fff}.titleBox.vip[data-v-77b08f5f]{background:#0f1a35}.titleBox.vip a[data-v-77b08f5f],.titleBox.vip h1[data-v-77b08f5f]{color:#c5996e}.headerRight[data-v-78b678fa]{font-size:.28rem;font-family:PingFangSC-Medium;font-weight:700;color:#1972ea}.tips[data-v-78b678fa]{width:100%;height:1.2rem;background:rgba(25,114,234,.8);overflow:hidden}.tips div[data-v-78b678fa]{float:left}.tips-inner[data-v-78b678fa]{text-align:left;width:5.8rem;height:1rem;font-size:.24rem;font-family:PingFangSC-Medium;font-weight:500;color:#fff;line-height:.33rem;margin-left:.1rem;padding-top:.24rem}.successfully[data-v-78b678fa]{width:100%;height:3.3rem;border-bottom:1px solid #ddd;position:relative}.successfully-img[data-v-78b678fa]{width:1rem;height:1rem;margin:.37rem auto}.successfully-img img[data-v-78b678fa]{width:.96rem;height:.96rem}.successfully-p[data-v-78b678fa]{height:.3rem;font-size:.24rem;line-height:.3rem;margin:.37rem 0}.successfully-money[data-v-78b678fa],.successfully-p[data-v-78b678fa]{width:100%;font-family:PingFangSC-Semibold;font-weight:600;color:#333;text-align:center}.successfully-money[data-v-78b678fa]{height:.34rem;font-size:.28rem;line-height:.34rem;margin:.24rem 0}.successfully-money span[data-v-78b678fa]{font-size:.34rem}.successRight[data-v-78b678fa]{position:absolute;right:.2rem;top:0;z-index:100}.mui-li[data-v-78b678fa],.successRight[data-v-78b678fa]{font-size:.28rem;font-family:PingFangSC-Medium;font-weight:500;color:#1972ea}.mui-li[data-v-78b678fa]{line-height:1rem;text-align:center;border-bottom:1px solid #ddd}.orderNumber[data-v-78b678fa]{width:1.5rem;height:.34rem;font-size:.28rem;font-family:PingFangSC-Medium;font-weight:500;color:#666;line-height:.34rem;letter-spacing:.01rem}.table1[data-v-78b678fa]{overflow:hidden}.table1 p[data-v-78b678fa]{float:left}.table2[data-v-78b678fa]{margin-right:.2rem}.orderNumbering[data-v-78b678fa]{width:2rem;height:.34rem}.orderNumbering[data-v-78b678fa],.orderNumberinp[data-v-78b678fa]{font-size:.28rem;font-family:DIN-Bold;font-weight:700;color:#333;line-height:.36rem;margin-left:.12rem}.orderNumberinp[data-v-78b678fa]{float:right;text-align:left;width:5.2rem;margin-bottom:.15rem;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2;overflow:hidden;white-space:normal}.table2[data-v-78b678fa]{-webkit-box-sizing:border-box;box-sizing:border-box;overflow:hidden;margin-top:.15rem;padding-bottom:.2rem}.orderDetails[data-v-78b678fa]{float:left;width:1.5rem;font-size:.28rem;font-family:PingFangSC-Medium;font-weight:500;color:#666;line-height:.34rem;letter-spacing:.01rem}.paymentMethod[data-v-78b678fa]{width:100%;height:1.24rem;font-size:.32rem;font-family:PingFangSC-Semibold;font-weight:600;color:#333;line-height:1.24rem;padding-left:.24rem;border-bottom:1px solid #ddd}.paymentMethod-inner[data-v-78b678fa]{width:100%;height:3.62rem;overflow:hidden}.paymentMethod-inner div[data-v-78b678fa]{float:left}.paymentMethod-img1[data-v-78b678fa]{width:.56rem;height:.56rem;margin-left:.24rem;margin-top:.27rem}.paymentMethod-img1 img[data-v-78b678fa]{width:.6rem;height:.6rem}.paymentMethod-div[data-v-78b678fa]{width:100%;height:1.2rem;border-bottom:1px solid #ddd}.paymentMethod-zhifu[data-v-78b678fa]{margin-left:.2rem;width:5rem;margin-top:.2rem}.paymentMethod-zhifu div[data-v-78b678fa]{width:4rem;height:.4rem}.Next[data-v-78b678fa]{width:.3rem;height:.3rem;margin-top:.38rem;margin-left:1rem}.Next img[data-v-78b678fa]{width:.3rem;height:.4rem}.tips-icon[data-v-78b678fa]{width:.36rem;height:.36rem;margin-left:.22rem;margin-top:.22rem}.tips-icon img[data-v-78b678fa]{width:.36rem;height:.36rem}.tips-del[data-v-78b678fa]{width:.36rem;height:.36rem;margin-top:.42rem}.tips-del img[data-v-78b678fa]{width:.36rem;height:.36rem}.mui-collapse-content[data-v-78b678fa]{-webkit-box-sizing:border-box;box-sizing:border-box;padding-left:.24rem;padding-right:.24rem}.paymentBusiness[data-v-78b678fa]{width:1.5rem;height:.4rem;font-size:.28rem;font-family:PingFangSC-Medium;font-weight:500;color:#333;line-height:.4rem}.payment-explain[data-v-78b678fa]{width:5rem;height:.33rem;font-size:.24rem;font-family:PingFangSC-Regular;font-weight:400;color:#999;line-height:.33rem}.mui-navigate-right[data-v-78b678fa]{position:relative}.navigate-img[data-v-78b678fa]{position:absolute;width:.24rem;height:.24rem;top:.09rem;right:-.3rem}footer[data-v-78b678fa]{position:fixed;bottom:0;width:100%;height:.74rem;background:#dfedff;line-height:.74rem;padding:0 .24rem}footer img[data-v-78b678fa]{width:.5rem;margin-top:.1rem}footer a[data-v-78b678fa]{color:#1972ea} | 5,348 | 5,348 | 0.791324 |
44d3312e0e689e20afc922d73b6c979b13bbce15 | 1,802 | lua | Lua | luigi/hooker.lua | poke1024/luigi | a909e037a5e8464ea33be305081408470b08bd3e | [
"MIT"
] | 119 | 2015-10-22T00:19:02.000Z | 2022-03-13T15:54:19.000Z | luigi/hooker.lua | poke1024/luigi | a909e037a5e8464ea33be305081408470b08bd3e | [
"MIT"
] | 87 | 2019-03-28T03:35:16.000Z | 2021-12-18T01:21:17.000Z | luigi/hooker.lua | poke1024/luigi | a909e037a5e8464ea33be305081408470b08bd3e | [
"MIT"
] | 24 | 2015-10-22T00:19:05.000Z | 2022-02-02T07:04:05.000Z | local Hooker = {}
local wrapped = setmetatable({}, { __mode = 'k' })
local hooks = setmetatable({}, { __mode = 'k' })
local function unhook (item)
if item.prev then
item.prev.next = item.next
end
if item.next then
item.next.prev = item.prev
end
if hooks[item.host][item.key] == item then
hooks[item.host][item.key] = item.next
end
end
local function hook (host, key, func, atEnd)
if not func then
return
end
if not hooks[host] then
hooks[host] = {}
end
local current = hooks[host][key]
local item = {
next = not atEnd and current or nil,
unhook = unhook,
host = host,
key = key,
func = func,
}
if atEnd then
if current then
while current.next do
current = current.next
end
current.next = item
item.prev = current
else
hooks[host][key] = item
end
return item
end
if current then
current.prev = item
end
hooks[host][key] = item
return item
end
function Hooker.unhook (item)
return unhook(item)
end
function Hooker.hook (host, key, func, atEnd)
if not wrapped[host] then
wrapped[host] = {}
end
if not wrapped[host][key] then
wrapped[host][key] = true
hook(host, key, host[key])
host[key] = function (...)
local item = hooks[host][key]
while item do
local result = item.func(...)
if result ~= nil then
return result
end
item = item.next
end -- while
end -- function
end -- if
return hook(host, key, func, atEnd)
end
return Hooker
| 19.586957 | 50 | 0.523307 |
da1581bf80ab01e34e4cd6936905f2fbd21f42fd | 2,251 | php | PHP | src/applications/packages/query/PhabricatorPackagesVersionSearchEngine.php | hach-que/phabricator | 69e0a3ffcc3815eca6629f4dbbdb84a7fda3531d | [
"Apache-2.0"
] | null | null | null | src/applications/packages/query/PhabricatorPackagesVersionSearchEngine.php | hach-que/phabricator | 69e0a3ffcc3815eca6629f4dbbdb84a7fda3531d | [
"Apache-2.0"
] | null | null | null | src/applications/packages/query/PhabricatorPackagesVersionSearchEngine.php | hach-que/phabricator | 69e0a3ffcc3815eca6629f4dbbdb84a7fda3531d | [
"Apache-2.0"
] | null | null | null | <?php
final class PhabricatorPackagesVersionSearchEngine
extends PhabricatorApplicationSearchEngine {
public function getResultTypeDescription() {
return pht('Package Versions');
}
public function getApplicationClassName() {
return 'PhabricatorPackagesApplication';
}
public function newQuery() {
return id(new PhabricatorPackagesVersionQuery());
}
protected function buildQueryFromParameters(array $map) {
$query = $this->newQuery();
if ($map['match'] !== null) {
$query->withNameNgrams($map['match']);
}
if ($map['packagePHIDs']) {
$query->withPackagePHIDs($map['packagePHIDs']);
}
return $query;
}
protected function buildCustomSearchFields() {
return array(
id(new PhabricatorSearchTextField())
->setLabel(pht('Name Contains'))
->setKey('match')
->setDescription(pht('Search for versions by name substring.')),
id(new PhabricatorSearchDatasourceField())
->setLabel(pht('Packages'))
->setKey('packagePHIDs')
->setAliases(array('packagePHID', 'package', 'packages'))
->setDatasource(new PhabricatorPackagesPackageDatasource())
->setDescription(pht('Search for versions by package.')),
);
}
protected function getURI($path) {
return '/packages/version/'.$path;
}
protected function getBuiltinQueryNames() {
$names = array(
'all' => pht('All Versions'),
);
return $names;
}
public function buildSavedQueryFromBuiltin($query_key) {
$query = $this->newSavedQuery();
$query->setQueryKey($query_key);
switch ($query_key) {
case 'all':
return $query;
}
return parent::buildSavedQueryFromBuiltin($query_key);
}
protected function renderResultList(
array $versions,
PhabricatorSavedQuery $query,
array $handles) {
assert_instances_of($versions, 'PhabricatorPackagesVersion');
$viewer = $this->requireViewer();
$list = id(new PhabricatorPackagesVersionListView())
->setViewer($viewer)
->setVersions($versions)
->newListView();
return id(new PhabricatorApplicationSearchResultView())
->setObjectList($list)
->setNoDataString(pht('No versions found.'));
}
}
| 25.292135 | 72 | 0.660595 |
dd983da6968dcd19725ffa8bd7f7734dc6463e7a | 10,167 | py | Python | pedrec/tools/resultwriters/h36m_to_results.py | noboevbo/PedRec | 891d19bd6a2c7a7d71c2e41d37e7b4c4bfc7762e | [
"MIT"
] | 1 | 2022-03-09T01:24:10.000Z | 2022-03-09T01:24:10.000Z | pedrec/tools/resultwriters/h36m_to_results.py | noboevbo/PedRec | 891d19bd6a2c7a7d71c2e41d37e7b4c4bfc7762e | [
"MIT"
] | null | null | null | pedrec/tools/resultwriters/h36m_to_results.py | noboevbo/PedRec | 891d19bd6a2c7a7d71c2e41d37e7b4c4bfc7762e | [
"MIT"
] | null | null | null | import os
import sys
from pathlib import Path
from pedrec.datasets.pedrec_dataset import PedRecDataset
from pedrec.training.experiments.experiment_initializer import initialize_weights_with_same_name_and_shape
sys.path.append(".")
from torch.utils.data import DataLoader
from pedrec.networks.net_pedrec.pedrec_net import PedRecNet
from pedrec.training.experiments.experiment_path_helper import get_experiment_paths_home
from pedrec.configs.dataset_configs import get_h36m_val_dataset_cfg_default
from pedrec.evaluations.eval_helper import get_total_coords
from pedrec.models.constants.dataset_constants import DatasetType
import torch
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torchvision.transforms as transforms
from pedrec.configs.pedrec_net_config import PedRecNet50Config
from pedrec.training.experiments.experiment_train_helper import init_experiment
from pedrec.utils.torch_utils.torch_helper import get_device, move_to_device
import pandas as pd
import numpy as np
from pedrec.models.constants.skeleton_pedrec import SKELETON_PEDREC_JOINTS
def set_df_dtypes(df: pd.DataFrame):
for joint in SKELETON_PEDREC_JOINTS:
df[f"skeleton2d_{joint.name}_x"] = df[f"skeleton2d_{joint.name}_x"].astype("float32")
df[f"skeleton2d_{joint.name}_y"] = df[f"skeleton2d_{joint.name}_y"].astype("float32")
df[f"skeleton2d_{joint.name}_score"] = df[f"skeleton2d_{joint.name}_score"].astype("float32")
df[f"skeleton2d_{joint.name}_visible"] = df[f"skeleton2d_{joint.name}_visible"].astype("category")
df[f"skeleton2d_{joint.name}_supported"] = df[f"skeleton2d_{joint.name}_visible"].astype("category")
df[f"skeleton3d_{joint.name}_x"] = df[f"skeleton3d_{joint.name}_x"].astype("float32")
df[f"skeleton3d_{joint.name}_y"] = df[f"skeleton3d_{joint.name}_y"].astype("float32")
df[f"skeleton3d_{joint.name}_z"] = df[f"skeleton3d_{joint.name}_z"].astype("float32")
df[f"skeleton3d_{joint.name}_score"] = df[f"skeleton3d_{joint.name}_score"].astype("float32")
df[f"skeleton3d_{joint.name}_visible"] = df[f"skeleton3d_{joint.name}_visible"].astype("category")
df[f"skeleton3d_{joint.name}_supported"] = df[f"skeleton3d_{joint.name}_visible"].astype("category")
def get_column_names():
column_names = [
"img_path"
]
for joint in SKELETON_PEDREC_JOINTS:
column_names.append(f"skeleton2d_{joint.name}_x")
column_names.append(f"skeleton2d_{joint.name}_y")
column_names.append(f"skeleton2d_{joint.name}_score")
column_names.append(f"skeleton2d_{joint.name}_visible")
column_names.append(f"skeleton2d_{joint.name}_supported")
for joint in SKELETON_PEDREC_JOINTS:
column_names.append(f"skeleton3d_{joint.name}_x")
column_names.append(f"skeleton3d_{joint.name}_y")
column_names.append(f"skeleton3d_{joint.name}_z")
column_names.append(f"skeleton3d_{joint.name}_score")
column_names.append(f"skeleton3d_{joint.name}_visible")
column_names.append(f"skeleton3d_{joint.name}_supported")
return column_names
def get_preds_mtl(outputs: torch.Tensor):
return {
"skeleton": outputs[0].cpu().detach().numpy(),
"skeleton_3d": outputs[1].cpu().detach().numpy(),
"orientation": outputs[2].cpu().detach().numpy(),
}
def main(output_dir: str, output_postfix: str, net_cfg, h36m_val, weights_path: str):
init_experiment(42)
device = get_device(use_gpu=True)
####################################################################################################################
############################################ Initialize Network ####################################################
####################################################################################################################
net = PedRecNet(net_cfg)
net.init_weights()
initialize_weights_with_same_name_and_shape(net, weights_path, "model.")
net.to(device)
batch_size = 48
data_loader = DataLoader(h36m_val, batch_size=batch_size, shuffle=False, num_workers=12)
net.eval()
gt_rows = []
result_rows = []
# count = 0
# column_names = get_column_names()
with torch.no_grad():
for test_data in data_loader:
# if count > 2:
# break
# count += 1
images, labels = test_data
images = images.to(device)
labels = move_to_device(labels, device)
outputs = net(images)
preds = get_preds_mtl(outputs)
idxs = labels["idx"].cpu().detach().numpy()
centers = labels["center"].cpu().detach().numpy()
scales = labels["scale"].cpu().detach().numpy()
rotations = labels["rotation"].cpu().detach().numpy()
pose2d_gts = labels["skeleton"].cpu().detach().numpy()
pose3d_gts = labels["skeleton_3d"].cpu().detach().numpy()
# orientation_gts = labels["orientation"].cpu().detach().numpy()
img_paths = labels["img_path"]
# img_sizes = labels["img_size"].cpu().detach().numpy().tolist()
pose2d_gts = get_total_coords(pose2d_gts, net_cfg.model.input_size, centers, scales, rotations)
pose2d_preds = preds["skeleton"]
pose2d_preds = get_total_coords(pose2d_preds, net_cfg.model.input_size, centers, scales, rotations)
pose3d_preds = preds["skeleton_3d"]
pose3d_preds[:, :, :3] = (pose3d_preds[:, :, :3] * 3000) - 1500 # to cm
pose3d_gts[:, :, :3] = (pose3d_gts[:, :, :3] * 3000) - 1500 # to cm
#
# orientation_preds = preds["orientation"]
for i in range(0, pose2d_preds.shape[0]):
img_path = img_paths[i]
idx = idxs[i]
pose2d_pred = pose2d_preds[i]
pose2d_gt = pose2d_gts[i]
visibles = pose2d_gt[:, 3]
supported = pose2d_gt[:, 4]
visible_supported = np.array([visibles, supported]).transpose(1, 0)
pose2d_pred = np.concatenate((pose2d_pred, visible_supported), axis=1)
pose2d_pred = pose2d_pred.reshape(-1).tolist()
pose2d_gt = pose2d_gt.reshape(-1).tolist()
pose3d_pred = pose3d_preds[i]
pose3d_gt = pose3d_gts[i]
visibles = pose3d_gt[:, 4]
supported = pose3d_gt[:, 5]
visible_supported = np.array([visibles, supported]).transpose(1, 0)
pose3d_pred = np.concatenate((pose3d_pred, visible_supported), axis=1)
pose3d_pred = pose3d_pred.reshape(-1).tolist()
pose3d_gt = pose3d_gt.reshape(-1).tolist()
result_rows.append([img_path] + pose2d_pred + pose3d_pred)
gt_rows.append([img_path] + pose2d_gt + pose3d_gt)
df_pred = pd.DataFrame(data=result_rows, columns=get_column_names())
set_df_dtypes(df_pred)
output_path = os.path.join(output_dir, f"H36M_pred_df_{output_postfix}.pkl")
df_pred.to_pickle(output_path)
df_gt = pd.DataFrame(data=gt_rows, columns=get_column_names())
set_df_dtypes(df_gt)
output_path = os.path.join(output_dir, f"H36M_gt_df_{output_postfix}.pkl")
df_gt.to_pickle(output_path)
if __name__ == '__main__':
experiment_paths = get_experiment_paths_home()
network_paths = [
# experiment_paths.pose_2d_coco_only_weights_path,
# experiment_paths.pedrec_2d_h36m_path,
# experiment_paths.pedrec_2d_sim_path,
# experiment_paths.pedrec_2d3d_h36m_path,
# experiment_paths.pedrec_2d3d_sim_path,
# experiment_paths.pedrec_2d3d_h36m_sim_path,
# experiment_paths.pedrec_2d3d_c_h36m_path,
# experiment_paths.pedrec_2d3d_c_sim_path,
# experiment_paths.pedrec_2d3d_c_h36m_sim_path,
# experiment_paths.pedrec_2d3d_c_o_h36m_mebow_path,
# experiment_paths.pedrec_2d3d_c_o_sim_path,
# experiment_paths.pedrec_2d3d_c_o_h36m_sim_path,
experiment_paths.pedrec_2d3d_c_o_h36m_sim_mebow_path
]
net_cfg = PedRecNet50Config()
trans = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
h36m_val_dataset_cfg = get_h36m_val_dataset_cfg_default()
h36m_val_dataset_cfg.subsample = 1
h36m_val_dataset_cfg.flip = False
h36m_val_dataset_cfg.scale_factor = 0
h36m_val_dataset_cfg.rotation_factor = 0
h36m_val_dataset_cfg.gt_result_ratio = 1
h36m_val = PedRecDataset(experiment_paths.h36m_val_dir,
experiment_paths.h36m_val_filename,
DatasetType.VALIDATE, h36m_val_dataset_cfg,
net_cfg.model.input_size, trans, is_h36m=True)
h36m_val_flipped = PedRecDataset(experiment_paths.h36m_val_dir,
experiment_paths.h36m_val_filename,
DatasetType.VALIDATE, h36m_val_dataset_cfg,
net_cfg.model.input_size, trans, is_h36m=True, flip_all=True)
for net_path in network_paths:
print(f"Working on {net_path}")
main(output_dir="data/datasets/Human3.6m/",
output_postfix=Path(net_path).stem,
net_cfg=net_cfg,
h36m_val=h36m_val,
weights_path=net_path)
main(output_dir="data/datasets/Human3.6m/",
output_postfix=f"{Path(net_path).stem}_flipped",
net_cfg=net_cfg,
h36m_val=h36m_val_flipped,
weights_path=net_path)
#
# h36m_val = PedRecDataset(experiment_paths.h36m_train_dir,
# experiment_paths.h36m_train_filename,
# DatasetType.VALIDATE, h36m_val_dataset_cfg,
# net_cfg.model.input_size, trans)
# main(output_dir="data/datasets/Human3.6m/", output_postfix="train_direct_4", net_cfg=net_cfg, h36m_val=h36m_val)
| 45.186667 | 120 | 0.643356 |
58428f9a396ca0fba7e947a0066dc3d9795bb816 | 2,391 | css | CSS | multi-purpose-board/src/app/core/header/header.component.css | Shtekata/Kanban-Board | dfab9086d0a75022bab4bb778edf9b324692f5da | [
"MIT"
] | null | null | null | multi-purpose-board/src/app/core/header/header.component.css | Shtekata/Kanban-Board | dfab9086d0a75022bab4bb778edf9b324692f5da | [
"MIT"
] | null | null | null | multi-purpose-board/src/app/core/header/header.component.css | Shtekata/Kanban-Board | dfab9086d0a75022bab4bb778edf9b324692f5da | [
"MIT"
] | null | null | null | @import url('https://fonts.googleapis.com/css2?family=Texturina:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap');
header {
background: linear-gradient(0deg, rgb(182, 179, 0) 0%, rgb(40, 0, 182) 35%, rgb(255, 0, 84) 100%);
position: sticky;
top: 0;
}
header ul {
padding: 0;
display: flex;
align-items: center;
width: 75%;
margin: auto;
}
header ul span {
color: white;
padding: 0.5em;
}
header li {
list-style: none;
margin: .35em;
padding: 0 .95em;
}
header a {
color: white;
cursor: pointer;
}
nav {
border-top: 1px solid #00acf4;
min-height: 25px;
}
.logo {
font-size: 1.3em;
color: white;
padding-bottom: 0;
}
.logo-wrap {
font-family: 'Texturina', serif;
letter-spacing: .5em;
margin: 0.5em 0;
}
p {
padding: 0.3em 0 0.2em;
margin: 0;
}
.mini-navbar-wrap {
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
width: 75%;
margin: auto;
min-height: 50px;
}
.mini-navbar ul {
background-color: #008000;
border-radius: 20px;
border: 1px solid #00d4ff;
padding-left: 0;
width: 100%;
}
.mini-navbar ul li+li {
border-left: 1px solid lightgrey;
padding-left: .5em;
}
.image {
width: 37px;
display: flex;
align-items: center;
margin-left: 5px;
}
img {
width: 100%;
border-radius: 50%;
}
.navbar-picture {
display: flex;
}
@media all and (max-width:991.98px) {
.mini-navbar-wrap {
width: auto;
justify-content: space-around;
}
}
@media all and (max-width:767.98px) {
.logo {
font-size: 20px;
display: block;
}
.logo-wrap {
margin: 0;
}
nav {
font-size: 12px;
}
.mini-navbar ul li {
padding: 2px;
font-size: 12px;
}
}
@media all and (max-width:575.98px) {
.logo {
font-size: 16px;
display: block;
}
nav {
font-size: 10px;
}
.mini-navbar ul li {
padding: 2px;
font-size: 10px;
}
}
@media all and (max-width:499.98px) {
.logo {
font-size: 14px;
display: block;
}
.logo-wrap {
margin: 0;
}
.mini-navbar ul li {
padding: 2px;
font-size: 8px;
}
} | 16.72028 | 197 | 0.552488 |
2c4203c788bae20329c3c432c52b90e0ed71b658 | 2,474 | py | Python | api/tests/audit_log/favourite/test_get_favourite_logs.py | nzediegwu1/favourites-backend | ad3587795d1dd44d350879364d443c43b727ca0c | [
"MIT"
] | 2 | 2019-08-05T08:03:05.000Z | 2021-10-03T16:36:31.000Z | api/tests/audit_log/favourite/test_get_favourite_logs.py | nzediegwu1/favourites-backend | ad3587795d1dd44d350879364d443c43b727ca0c | [
"MIT"
] | 8 | 2020-02-12T00:56:35.000Z | 2022-02-10T12:12:31.000Z | api/tests/audit_log/favourite/test_get_favourite_logs.py | nzediegwu1/favorite-things | ad3587795d1dd44d350879364d443c43b727ca0c | [
"MIT"
] | null | null | null | from rest_framework.test import APITestCase
from api.models import Category
from api.tests.mocks import brite_core, brite_core_update
class TestGetFavouriteAuditLog(APITestCase):
favourite_id = 0
def setUp(self):
category = Category.objects.create(name='Company')
response = self.client.post('/favourites',
brite_core(category.id),
format='json')
self.favourite_id = response.data['id']
url = f'/favourites/{self.favourite_id}'
self.client.put(url, brite_core_update(category.id), format='json')
self.client.delete(url)
def test_get_audit_log_succeeds_with_existing_favourite_id(self):
response = self.client.get(f'/favourites/{self.favourite_id}/logs')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data['message'], 'BriteCore-Audit Log')
self.assertEqual(len(response.data['data']), 3)
delete_audit_log = response.data['data'][0]
self.assertEqual(delete_audit_log['action'], 'delete')
self.assertEqual(delete_audit_log['resource_id'], self.favourite_id)
self.assertEqual(delete_audit_log['model'], 'favourite')
self.assertEqual(delete_audit_log['before']['title'], 'BriteCore')
self.assertEqual(delete_audit_log['after'], {})
update_audit_log = response.data['data'][1]
self.assertEqual(update_audit_log['action'], 'update')
self.assertEqual(update_audit_log['before']['title'], 'Brite Core')
self.assertEqual(update_audit_log['after']['title'], 'BriteCore')
self.assertEqual(update_audit_log['before']['ranking'], 3)
self.assertEqual(update_audit_log['after']['ranking'], 10)
creation_audit_log = response.data['data'][2]
self.assertEqual(creation_audit_log['action'], 'create')
self.assertEqual(creation_audit_log['before'], {})
self.assertEqual(creation_audit_log['after']['title'], 'Brite Core')
self.assertTrue('created_date' in creation_audit_log['after'])
self.assertTrue('modified_date' in creation_audit_log['after'])
def test_get_audit_log_fails_with_unexisting_favourite_id(self):
response = self.client.get(f'/favourites/4343434/logs')
self.assertEqual(response.status_code, 404)
self.assertEqual(response.data['detail'],
'favourite with pk 4343434, does not exist')
| 48.509804 | 76 | 0.672999 |
a32a966d46c5676c02a9c04df9ab92587784b50b | 4,806 | java | Java | google-ads/src/test/java/com/google/ads/googleads/lib/utils/ResourceNamesTest.java | duperran/google-ads-java | da810ba8e1b5328a4b9b510eb582dc692a071408 | [
"Apache-2.0"
] | null | null | null | google-ads/src/test/java/com/google/ads/googleads/lib/utils/ResourceNamesTest.java | duperran/google-ads-java | da810ba8e1b5328a4b9b510eb582dc692a071408 | [
"Apache-2.0"
] | null | null | null | google-ads/src/test/java/com/google/ads/googleads/lib/utils/ResourceNamesTest.java | duperran/google-ads-java | da810ba8e1b5328a4b9b510eb582dc692a071408 | [
"Apache-2.0"
] | null | null | null | // Copyright 2018 Google LLC
//
// 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.google.ads.googleads.lib.utils;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class ResourceNamesTest {
@Test
public void testAccountBudgetProposal() {
String expected = "customers/1234/accountBudgetProposals/5678";
assertEquals(expected, ResourceNames.accountBudgetProposal(1234L, 5678L));
}
@Test
public void testAdGroupAd() {
String expected = "customers/1234/adGroupAds/5678_1011";
assertEquals(expected, ResourceNames.adGroupAd(1234L, 5678L, 1011L));
}
@Test
public void testAdGroupBidModifier() {
String expected = "customers/1234/adGroupBidModifiers/5678_1011";
assertEquals(expected, ResourceNames.adGroupBidModifier(1234L, 5678L, 1011L));
}
@Test
public void testAdGroupCriterion() {
String expected = "customers/1234/adGroupCriteria/5678_1011";
assertEquals(expected, ResourceNames.adGroupCriterion(1234L, 5678L, 1011L));
}
@Test
public void testAdGroup() {
String expected = "customers/1234/adGroups/5678";
assertEquals(expected, ResourceNames.adGroup(1234L, 5678L));
}
@Test
public void testBiddingStrategy() {
String expected = "customers/1234/biddingStrategies/5678";
assertEquals(expected, ResourceNames.biddingStrategy(1234L, 5678L));
}
@Test
public void testBillingSetup() {
String expected = "customers/1234/billingSetups/5678";
assertEquals(expected, ResourceNames.billingSetup(1234L, 5678L));
}
@Test
public void testCampaign() {
String expected = "customers/1234/campaigns/5678";
assertEquals(expected, ResourceNames.campaign(1234L, 5678L));
}
@Test
public void testCampaignBidModifier() {
String expected = "customers/1234/campaignBidModifiers/5678_1011";
assertEquals(expected, ResourceNames.campaignBidModifier(1234L, 5678L, 1011L));
}
@Test
public void testCampaignBudget() {
String expected = "customers/1234/campaignBudgets/5678";
assertEquals(expected, ResourceNames.campaignBudget(1234L, 5678L));
}
@Test
public void testCampaignCriteria() {
String expected = "customers/1234/campaignCriteria/5678_1011";
assertEquals(expected, ResourceNames.campaignCriterion(1234L, 5678L, 1011L));
}
@Test
public void testCampaignGroup() {
String expected = "customers/1234/campaignGroups/5678";
assertEquals(expected, ResourceNames.campaignGroup(1234L, 5678L));
}
@Test
public void testCampaignSharedSet() {
String expected = "customers/1234/campaignSharedSets/5678";
assertEquals(expected, ResourceNames.campaignSharedSet(1234L, 5678L));
}
@Test
public void testChangeStatus() {
String expected = "customers/1234/changeStatus/5678";
assertEquals(expected, ResourceNames.changeStatus(1234L, 5678L));
}
@Test
public void testConversionAction() {
String expected = "customers/1234/conversionActions/5678";
assertEquals(expected, ResourceNames.conversionAction(1234L, 5678L));
}
@Test
public void testCustomer() {
String expected = "customers/1234";
assertEquals(expected, ResourceNames.customer(1234L));
}
@Test
public void testGeoTargetConstant() {
String expected = "geoTargetConstants/1234";
assertEquals(expected, ResourceNames.geoTargetConstant(1234L));
}
@Test
public void testGoogleAdsField() {
String expected = "googleAdsFields/ad_group_criterion.effective_cpm_bid_micros";
assertEquals(
expected, ResourceNames.googleAdsField("ad_group_criterion.effective_cpm_bid_micros"));
}
@Test
public void testKeywordView() {
String expected = "customers/1234/keywordViews/5678_1011";
assertEquals(expected, ResourceNames.keywordView(1234L, 5678L, 1011L));
}
@Test
public void testSharedSet() {
String expected = "customers/1234/sharedSets/5678";
assertEquals(expected, ResourceNames.sharedSet(1234L, 5678L));
}
@Test
public void testSharedCriterion() {
String expected = "customers/1234/sharedCriteria/5678";
assertEquals(expected, ResourceNames.sharedCriterion(1234L, 5678L));
}
@Test
public void testVideo() {
String expected = "customers/1234/videos/5678";
assertEquals(expected, ResourceNames.video(1234L, 5678L));
}
}
| 30.807692 | 95 | 0.740117 |
beb8cbd40a93ab87dc2f1b9e51d04f455cb17472 | 1,999 | ts | TypeScript | hooks/useWallet.ts | unit410/polyfile | 1b9164606090209ef317caa13e71c43cb536aa93 | [
"BlueOak-1.0.0"
] | null | null | null | hooks/useWallet.ts | unit410/polyfile | 1b9164606090209ef317caa13e71c43cb536aa93 | [
"BlueOak-1.0.0"
] | null | null | null | hooks/useWallet.ts | unit410/polyfile | 1b9164606090209ef317caa13e71c43cb536aa93 | [
"BlueOak-1.0.0"
] | null | null | null | import { useEffect, useState } from 'react';
import type FilecoinApp from '@zondax/ledger-filecoin';
import Address from '~/common/Address';
import Wallet, { SignResponse, WalletAddress, WalletError } from '~/common/Wallet';
import { useLedger } from '~/components/LedgerProvider';
class LedgerWallet implements Wallet {
#app: FilecoinApp;
constructor(app: FilecoinApp) {
this.#app = app;
}
async addresses(): Promise<WalletAddress[]> {
const addresses = new Array<WalletAddress>();
// Load the first 10 addresses from the ledger
// This path is compatible with glif wallet addresses when using ledger
const pathBase = "m/44'/461'/0'/0";
for (let i = 0; i < 10; ++i) {
const path = `${pathBase}/${i}`;
const addrResponse = await this.#app.getAddressAndPubKey(path);
if (addrResponse.error_message !== 'No errors') {
console.error(new Error(`Error loading address at ${path}: ${addrResponse.error_message}`));
continue;
}
addresses.push({
path,
address: Address.FromString(addrResponse.addrString),
});
}
return addresses;
}
async sign(address: WalletAddress, message: Buffer): Promise<SignResponse> {
const resp = await this.#app.sign(address.path, message);
if (resp.error_message && resp.error_message !== 'No errors') {
throw new WalletError(resp.error_message, resp.return_code);
}
if (!resp.signature_compact || !resp.signature_der) {
throw new Error('missing signatures in ledger.sign response');
}
return {
returnCode: resp.return_code,
signatureCompact: resp.signature_compact,
signatureDer: resp.signature_der,
};
}
}
export default function useWallet(): Wallet | null {
const ledger = useLedger();
const [wallet, setWallet] = useState<LedgerWallet | null>(null);
useEffect(() => {
if (!ledger) {
return;
}
setWallet(new LedgerWallet(ledger));
}, [ledger]);
return wallet;
}
| 28.15493 | 100 | 0.65933 |
79895c73c2c2063bb52ae08dadee7cb15b250e09 | 2,521 | php | PHP | resources/views/admin/Account/login.blade.php | ThangDao01/project-sam2-ex-example | 71688bacb0dc1437c1691f1343ed141bd2b2c652 | [
"MIT"
] | 3 | 2021-08-18T15:07:12.000Z | 2021-08-30T07:43:52.000Z | resources/views/admin/Account/login.blade.php | ThangDao01/project-sam2-ex-example | 71688bacb0dc1437c1691f1343ed141bd2b2c652 | [
"MIT"
] | null | null | null | resources/views/admin/Account/login.blade.php | ThangDao01/project-sam2-ex-example | 71688bacb0dc1437c1691f1343ed141bd2b2c652 | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<head>
<title>Visitors an Admin Panel Category Bootstrap Responsive Website Template | Login :: w3layouts</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="keywords" content="Visitors Responsive web template, Bootstrap Web Templates, Flat Web Templates, Android Compatible web template,
Smartphone Compatible web template, free webdesigns for Nokia, Samsung, LG, SonyEricsson, Motorola web design" />
<script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script>
<!-- bootstrap-css -->
@include('layout.css')
<style>
.alert-success{
color: green;
}
.alert-error{
color: yellow !important;
}
.alert-danger{
color: red !important;
}
</style>
<!-- //font-awesome icons -->
@include('layout.js-head')
</head>
<body>
<div class="log-w3">
<div class="w3layouts-main" >
<h2>Sign In Now</h2>
{{-- @if(\Illuminate\Support\Facades\Session::has('error'))--}}
{{-- <p style="color: red" class=" alert alert">{{ Session::get('error') }}</p>--}}
{{-- @endif--}}
@if(Session::has('message'))
<p class="alert alert-{{Session::get('type') }}">{{Session::get('message') }}</p>
@endif
<form action="/admin/login" method="post">
@csrf
<div class="form-group">
<input type="email" class="ggg" name="Email" placeholder="E-MAIL" required="" value="{{old('Email')}}">
@error('Email')
<div class="text-danger"> *{{$message}}</div>
@enderror
</div>
<div class="form-group">
<input type="password" class="ggg" name="password" placeholder="PASSWORD" required="">
@error('password')
<div class="text-danger"> *{{$message}}</div>
@enderror
</div>
<span>
<input type="checkbox"/>Remember Me</span>
<h6><a href="#">Forgot Password?</a></h6>
<div class="clearfix"></div>
<input type="submit" value="Sign In" name="login">
</form>
<p>Don't Have an Account ?<a href="/admin/register">Create an account</a></p>
</div>
</div>
@include('layout.js-footer')
</body>
</html>
| 38.784615 | 177 | 0.560889 |
f47dd2835238b3c14c192c1a398ef4bbe48e0e18 | 555 | tsx | TypeScript | src/components/layout/Navbar.tsx | bhumong/simple-project-management-redux | e2e4f7326e3d8d554f83983867cc46e413e271e8 | [
"MIT"
] | null | null | null | src/components/layout/Navbar.tsx | bhumong/simple-project-management-redux | e2e4f7326e3d8d554f83983867cc46e413e271e8 | [
"MIT"
] | 2 | 2020-05-23T08:14:39.000Z | 2022-01-22T12:23:29.000Z | src/components/layout/Navbar.tsx | bhumong/simple-project-management-redux | e2e4f7326e3d8d554f83983867cc46e413e271e8 | [
"MIT"
] | null | null | null | import React from 'react';
import { Link } from 'react-router-dom';
import SigninLink from './SigninLink';
import SignoutLink from './SignoutLink';
function Navbar(props: any) {
const user = props.user ? props.user : null;
const initial = props.userData?.initals;
return (
<nav className='nav-wrapper grey darken-3'>
<div className='container'>
<Link to='/' className='brand-logo left'>Mario Plan</Link>
{!user ? <SignoutLink /> : <SigninLink initial={initial} />}
</div>
</nav>
);
}
export default (Navbar);
| 27.75 | 68 | 0.648649 |
6d9066ee474e543bb4ae6884c20f913e88b3c108 | 1,012 | ts | TypeScript | MEAN - MongoDB, ExpressJS, AngularJS, NodeJS - SCRUM/frontend/src/app/service/auth.service.ts | alzheimeer/Tasks-JS-Angular | 22e8fe3e68a8a9b1de1e5336f2fca9c7f9968611 | [
"MIT"
] | null | null | null | MEAN - MongoDB, ExpressJS, AngularJS, NodeJS - SCRUM/frontend/src/app/service/auth.service.ts | alzheimeer/Tasks-JS-Angular | 22e8fe3e68a8a9b1de1e5336f2fca9c7f9968611 | [
"MIT"
] | null | null | null | MEAN - MongoDB, ExpressJS, AngularJS, NodeJS - SCRUM/frontend/src/app/service/auth.service.ts | alzheimeer/Tasks-JS-Angular | 22e8fe3e68a8a9b1de1e5336f2fca9c7f9968611 | [
"MIT"
] | null | null | null | import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
@Injectable({
providedIn: 'root',
})
export class AuthService {
private registroUrl = 'http://localhost:3000/api/usuario/';
private loginUrl = 'http://localhost:3000/api/auth';
constructor(private http: HttpClient,
private router: Router) { }
// Creamos un obserbable
// usuario seria un json
registroUsuario(usuario) {
return this.http.post<any>(this.registroUrl, usuario);
}
loginUsuario(usuario) {
return this.http.post<any>(this.loginUrl, usuario);
}
loginOn() {
//!! convierte en true o false
//hay o no hay token
return !!localStorage.getItem('token');
}
obtenerToken() {
//devuelve el token
return localStorage.getItem('token');
}
cerrarSesion() {
localStorage.removeItem('token');
this.router.navigate(['/login']);
}
}
| 26.631579 | 63 | 0.62253 |
a30e014d30f4aeb33056fcfee8de4a653593da92 | 27,194 | h | C | YahooKeyKey-Source-1.1.2528/Frameworks/PlainVanilla/Headers/PVCandidate.h | linpc/yKeyKey | 81e05f070c070af65cac21e8da28ca4ff2d58905 | [
"BSD-3-Clause"
] | 31 | 2019-05-28T09:08:09.000Z | 2022-02-21T02:19:21.000Z | YahooKeyKey-Source-1.1.2528/Frameworks/PlainVanilla/Headers/PVCandidate.h | mhtxi3d/KeyKey | 24a21491398069317879ba07c95d9b0056806728 | [
"BSD-3-Clause"
] | null | null | null | YahooKeyKey-Source-1.1.2528/Frameworks/PlainVanilla/Headers/PVCandidate.h | mhtxi3d/KeyKey | 24a21491398069317879ba07c95d9b0056806728 | [
"BSD-3-Clause"
] | 19 | 2019-04-22T09:56:12.000Z | 2022-02-27T18:38:40.000Z | //
// PVCandidate.h
//
// Copyright (c) 2007-2010 Lukhnos D. Liu (http://lukhnos.org)
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
#ifndef PVCandidate_h
#define PVCandidate_h
#if defined(__APPLE__)
#include <OpenVanilla/OpenVanilla.h>
#else
#include "OpenVanilla.h"
#endif
namespace OpenVanilla {
using namespace std;
class PVCandidateList : public OVCandidateList {
public:
virtual void clear()
{
m_list.clear();
}
virtual size_t size() const
{
return m_list.size();
}
virtual string candidateAtIndex(size_t index) const
{
if (index >= m_list.size())
return string();
return m_list[index];
}
virtual void setCandidate(size_t index, const string& candidate)
{
if (index >= m_list.size()) {
for (size_t inc = m_list.size(); inc <= index; inc++)
m_list.push_back(string());
}
m_list[index] = candidate;
}
virtual void setCandidates(const vector<string>& candidates)
{
m_list = candidates;
}
virtual void addCandidate(const string& candidate)
{
m_list.push_back(candidate);
}
virtual void addCandidates(const vector<string>& candidates)
{
for (size_t index = 0; index < candidates.size(); index++)
m_list.push_back(candidates[index]);
}
protected:
vector<string> m_list;
};
class PVCandidateState {
public:
enum State {
Ignored = 0,
Canceled = 1,
ReachedPageBoundary = 2,
UpdatePage = 3,
UpdateCandidateHighlight = 4,
CandidateChosen = 5,
InvalidCandidateKey = 6
};
};
class PVOneDimensionalCandidatePanel : public OVOneDimensionalCandidatePanel {
protected:
bool m_visible;
bool m_shouldUpdate;
bool m_allowsPageWrapping;
bool m_inControl;
string m_prompt;
PVCandidateList m_candidateList;
size_t m_candidatesPerPage;
size_t m_currentPage;
OVKeyVector m_candidateKeys;
OVKeyVector m_nextPageKeys;
OVKeyVector m_previousPageKeys;
OVKeyVector m_nextCandidateKeys;
OVKeyVector m_previousCandidateKeys;
OVKeyVector m_cancelKeys;
OVKeyVector m_chooseHighlightedCandidateKeys;
OVKeyVector m_defaultCandidateKeys;
OVKeyVector m_defaultChooseHighlightedCandidateKeys;
OVKeyVector m_defaultNextPageKeys;
OVKeyVector m_defaultPreviousPageKeys;
OVKeyVector m_defaultNextCandidateKeys;
OVKeyVector m_defaultPreviousCandidateKeys;
OVKeyVector m_defaultCancelKeys;
size_t m_currentHighlightedCandidateIndex;
size_t m_chosenCandidateIndex;
string m_chosenCandidateString;
protected:
bool isKeyInVector(const OVKey& key, OVKeyVector& keyVector)
{
OVKeyVector::iterator it = keyVector.begin();
for ( ; it != keyVector.end(); it++) {
if (key == *it)
return true;
}
return false;
}
size_t indexOfKeyInVector(const OVKey& key, const OVKeyVector& keyVector)
{
size_t index;
for (index = 0; index < keyVector.size(); index++)
if (key == keyVector[index]) return index;
return 0;
}
public:
bool isInControl()
{
return m_inControl;
}
void reset()
{
m_shouldUpdate = false;
m_visible = false;
m_prompt = "";
m_candidateList.clear();
m_currentPage = 0;
m_inControl = false;
m_chosenCandidateString = "";
m_chosenCandidateIndex = 0;
m_currentHighlightedCandidateIndex = 0;
m_candidatesPerPage = 10;
setToDefaultKeys();
}
void setShouldUpdate(bool shouldUpdate)
{
m_shouldUpdate = shouldUpdate;
}
bool shouldUpdate()
{
return m_shouldUpdate;
}
void stopControl()
{
m_inControl = false;
}
void finishUpdate()
{
m_shouldUpdate = false;
}
size_t chosenCandidateIndex() const
{
return m_chosenCandidateIndex;
}
const string chosenCandidateString() const
{
return m_chosenCandidateString;
}
size_t lastCurrentPageCandidateIndex()
{
size_t count = currentPageCandidateCount();
return count > 0 ? count - 1 : 0;
}
PVCandidateState::State handleKeyEvent(const OVKey& key, OVLoaderService* loaderService)
{
if (isKeyInVector(key, m_cancelKeys)) {
reset();
return PVCandidateState::Canceled;
}
if (isKeyInVector(key, m_chooseHighlightedCandidateKeys)) {
m_chosenCandidateIndex = m_currentPage * m_candidatesPerPage + m_currentHighlightedCandidateIndex;
m_chosenCandidateString = m_candidateList.candidateAtIndex(m_chosenCandidateIndex);
return PVCandidateState::CandidateChosen;
}
if (isKeyInVector(key, m_candidateKeys)) {
if (!currentPageCandidateCount())
return PVCandidateState::InvalidCandidateKey;
size_t index = indexOfKeyInVector(key, m_candidateKeys);
if (index > lastCurrentPageCandidateIndex())
return PVCandidateState::InvalidCandidateKey;
m_chosenCandidateIndex = m_currentPage * m_candidatesPerPage + index;
m_chosenCandidateString = m_candidateList.candidateAtIndex(m_chosenCandidateIndex);
return PVCandidateState::CandidateChosen;
}
bool directionForward = false;
bool changeHighlight = false;
size_t oldCandidateIndex = m_currentHighlightedCandidateIndex;
size_t oldPageIndex = m_currentPage;
if (isKeyInVector(key, m_nextCandidateKeys)) {
changeHighlight = true;
directionForward = true;
}
if (isKeyInVector(key, m_previousCandidateKeys)) {
changeHighlight = true;
directionForward = false;
}
if (changeHighlight) {
if (directionForward) {
m_currentHighlightedCandidateIndex++;
if (m_currentHighlightedCandidateIndex > lastCurrentPageCandidateIndex()) {
goToNextPage();
// see if we'v really flipped the page
if (m_currentPage != oldPageIndex) {
m_currentHighlightedCandidateIndex = 0;
}
else {
// if not, either the list is empty, or page wrapping is off, we have to rollback
m_currentHighlightedCandidateIndex = oldCandidateIndex;
}
}
}
else {
if (m_currentHighlightedCandidateIndex > 0) {
m_currentHighlightedCandidateIndex--;
}
else {
// we need to flip to the previous the page; see if we can do it
goToPreviousPage();
if (m_currentPage != oldPageIndex) {
// flipped, so we set the candidate highlight to the last item of the new page
m_currentHighlightedCandidateIndex = lastCurrentPageCandidateIndex();
}
else {
// failed--page wrapping is off or list is empty--now we rollback (actually do nothing)
;
}
}
}
if (m_currentPage != oldPageIndex)
return PVCandidateState::UpdatePage;
if (m_currentHighlightedCandidateIndex != oldCandidateIndex)
return PVCandidateState::UpdateCandidateHighlight;
return PVCandidateState::ReachedPageBoundary;
}
bool changePage = false;
directionForward = false;
if (isKeyInVector(key, m_nextPageKeys)) {
changePage = true;
directionForward = true;
}
if (isKeyInVector(key, m_previousPageKeys)) {
changePage = true;
directionForward = false;
}
if (changePage) {
size_t oldPageIndex = m_currentPage;
if (directionForward) {
goToNextPage();
m_currentHighlightedCandidateIndex = 0;
}
else {
goToPreviousPage();
m_currentHighlightedCandidateIndex = 0;
}
if (m_currentPage != oldPageIndex)
return PVCandidateState::UpdatePage;
return PVCandidateState::ReachedPageBoundary;
}
return PVCandidateState::Ignored;
}
public:
PVOneDimensionalCandidatePanel()
: m_visible(false)
, m_shouldUpdate(false)
, m_candidatesPerPage(10)
, m_currentPage(0)
, m_allowsPageWrapping(true)
, m_inControl(false)
, m_currentHighlightedCandidateIndex(m_candidatesPerPage)
, m_chosenCandidateIndex(0)
, m_prompt("")
{
}
virtual void hide()
{
m_visible = false;
}
virtual void show()
{
m_visible = true;
}
virtual void updateDisplay()
{
m_shouldUpdate = true;
}
virtual bool isVisible()
{
return m_visible;
}
virtual void setPrompt(const string& prompt)
{
m_prompt = prompt;
}
virtual string prompt()
{
return m_prompt;
}
virtual bool yieldToCandidateEventHandler()
{
if (m_candidateList.size()) {
// yield control to candidate handler, so we start using hightlight
m_currentHighlightedCandidateIndex = 0;
m_inControl = true;
return true;
}
return false;
}
virtual void cancelEventHandler()
{
m_currentHighlightedCandidateIndex = m_candidatesPerPage;
m_inControl = false;
}
virtual bool isOneDimensionalPanel()
{
return true;
}
virtual bool isHorizontal() const
{
return false;
}
virtual bool isVertical() const
{
return false;
}
virtual OVCandidateList* candidateList()
{
return &m_candidateList;
}
virtual size_t candidatesPerPage() const
{
return m_candidatesPerPage;
}
virtual void setCandidatesPerPage(size_t number)
{
if (number > 0 && number <= m_candidateKeys.size())
m_candidatesPerPage = number;
}
virtual size_t lastPage() const
{
size_t size = m_candidateList.size();
if (!size)
return 0;
if (size % m_candidatesPerPage)
return size / m_candidatesPerPage;
return (size / m_candidatesPerPage) - 1;
}
virtual size_t pageCount() const
{
if (!m_candidateList.size())
return 0;
return lastPage() + 1;
}
virtual size_t currentPage() const
{
return m_currentPage;
}
size_t currentPageCandidateCount() const
{
if (m_currentPage < lastPage()) {
return m_candidatesPerPage;
}
return m_candidateList.size() - lastPage() * m_candidatesPerPage;
}
virtual bool allowsPageWrapping() const
{
return m_allowsPageWrapping;
}
virtual void setAllowsPageWrapping(bool allowsPageWrapping)
{
m_allowsPageWrapping = allowsPageWrapping;
}
virtual size_t currentHightlightIndex() const
{
return m_currentHighlightedCandidateIndex;
}
virtual void setHighlightIndex(size_t index)
{
m_currentHighlightedCandidateIndex = index;
if (m_currentHighlightedCandidateIndex >= m_candidatesPerPage)
m_currentHighlightedCandidateIndex = m_candidatesPerPage;
}
virtual size_t currentHightlightIndexInCandidateList() const
{
if (m_currentHighlightedCandidateIndex >= m_candidatesPerPage)
return 0;
return m_currentPage * m_candidatesPerPage + m_currentHighlightedCandidateIndex;
}
virtual size_t goToNextPage()
{
if (pageCount() > 0 && m_currentPage < lastPage()) {
m_currentPage++;
}
else {
if (m_allowsPageWrapping) {
m_currentPage = 0;
}
}
return m_currentPage;
}
virtual size_t goToPreviousPage() {
if (m_currentPage > 0) {
m_currentPage--;
}
else {
if (m_allowsPageWrapping && pageCount() > 0) {
m_currentPage = lastPage();
}
}
return m_currentPage;
}
virtual size_t goToPage(size_t page)
{
if (page <= lastPage()) {
m_currentPage = page;
}
return m_currentPage;
}
virtual const OVKey candidateKeyAtIndex(size_t index)
{
return index < m_candidateKeys.size() ? m_candidateKeys[index] : OVKey();
}
virtual void setCandidateKeys(const OVKeyVector& keys)
{
m_candidateKeys = keys;
}
virtual void setNextPageKeys(const OVKeyVector& keys)
{
m_nextPageKeys = keys;
}
virtual void setPreviousPageKeys(const OVKeyVector& keys)
{
m_previousPageKeys = keys;
}
virtual void setNextCandidateKeys(const OVKeyVector& keys)
{
m_nextCandidateKeys = keys;
}
virtual void setPreviousCandidateKeys(const OVKeyVector& keys)
{
m_previousCandidateKeys = keys;
}
virtual void setCancelKeys(const OVKeyVector& keys)
{
m_cancelKeys = keys;
}
virtual void setChooseHighlightedCandidateKeys(const OVKeyVector& keys)
{
m_chooseHighlightedCandidateKeys = keys;
}
virtual const OVKeyVector defaultCandidateKeys() const
{
return m_defaultCandidateKeys;
}
virtual const OVKeyVector defaultNextPageKeys() const
{
return m_defaultNextPageKeys;
}
virtual const OVKeyVector defaultNextCandidateKeys() const
{
return m_defaultNextCandidateKeys;
}
virtual const OVKeyVector defaultPreviousPageKeys() const
{
return m_defaultPreviousPageKeys;
}
virtual const OVKeyVector defaultPreviousCandidateKeys() const
{
return m_defaultPreviousCandidateKeys;
}
virtual const OVKeyVector defaultCancelKeys() const
{
return m_defaultCancelKeys;
}
virtual const OVKeyVector defaultChooseHighlightedCandidateKeys() const
{
return m_defaultChooseHighlightedCandidateKeys;
}
protected:
virtual void populateDefaultCandidateKeys(OVLoaderService* loaderService)
{
string defaultCandidates = "1234567890";
for (size_t index = 0; index < defaultCandidates.length(); index++)
m_defaultCandidateKeys.push_back(loaderService->makeOVKey(defaultCandidates[index]));
}
virtual void populateDefaultCancelKeys(OVLoaderService* loaderService)
{
m_defaultCancelKeys.push_back(loaderService->makeOVKey(OVKeyCode::Esc));
}
virtual void populateDefaultChooseHighlightedCandidateKeys(OVLoaderService* loaderService)
{
m_defaultChooseHighlightedCandidateKeys.push_back(loaderService->makeOVKey(OVKeyCode::Return));
}
virtual void setToDefaultKeys()
{
setCandidateKeys(defaultCandidateKeys());
setNextCandidateKeys(defaultNextCandidateKeys());
setPreviousCandidateKeys(defaultPreviousCandidateKeys());
setNextPageKeys(defaultNextPageKeys());
setPreviousPageKeys(defaultPreviousPageKeys());
setCancelKeys(defaultCancelKeys());
setChooseHighlightedCandidateKeys(defaultChooseHighlightedCandidateKeys());
}
virtual void populateAndSetDefaultKeys(OVLoaderService* loaderService)
{
populateDefaultCandidateKeys(loaderService);
populateDefaultCancelKeys(loaderService);
populateDefaultChooseHighlightedCandidateKeys(loaderService);
}
};
class PVHorizontalCandidatePanel : public PVOneDimensionalCandidatePanel
{
public:
PVHorizontalCandidatePanel(OVLoaderService* loaderService)
{
populateAndSetDefaultKeys(loaderService);
m_defaultNextCandidateKeys.push_back(loaderService->makeOVKey(OVKeyCode::Right));
m_defaultPreviousCandidateKeys.push_back(loaderService->makeOVKey(OVKeyCode::Left));
m_defaultNextPageKeys.push_back(loaderService->makeOVKey(OVKeyCode::PageDown));
m_defaultNextPageKeys.push_back(loaderService->makeOVKey(OVKeyCode::Down));
m_defaultNextPageKeys.push_back(loaderService->makeOVKey(OVKeyCode::Space));
m_defaultPreviousPageKeys.push_back(loaderService->makeOVKey(OVKeyCode::PageUp));
m_defaultPreviousPageKeys.push_back(loaderService->makeOVKey(OVKeyCode::Up));
setToDefaultKeys();
}
virtual bool isHorizontal() const
{
return true;
}
};
class PVVerticalCandidatePanel : public PVOneDimensionalCandidatePanel
{
public:
PVVerticalCandidatePanel(OVLoaderService* loaderService)
{
populateAndSetDefaultKeys(loaderService);
PVOneDimensionalCandidatePanel::populateAndSetDefaultKeys(loaderService);
m_defaultNextCandidateKeys.push_back(loaderService->makeOVKey(OVKeyCode::Down));
m_defaultPreviousCandidateKeys.push_back(loaderService->makeOVKey(OVKeyCode::Up));
m_defaultNextPageKeys.push_back(loaderService->makeOVKey(OVKeyCode::PageDown));
m_defaultNextPageKeys.push_back(loaderService->makeOVKey(OVKeyCode::Space));
m_defaultPreviousPageKeys.push_back(loaderService->makeOVKey(OVKeyCode::PageUp));
m_defaultNextPageKeys.push_back(loaderService->makeOVKey(OVKeyCode::Right));
m_defaultPreviousPageKeys.push_back(loaderService->makeOVKey(OVKeyCode::Left));
setToDefaultKeys();
}
virtual bool isVertical() const
{
return true;
}
};
class PVFreeContentStorage : public OVFreeContentStorage {
public:
virtual void clear()
{
m_content = "";
}
virtual void setContent(const string& content)
{
m_content = content;
}
virtual void appendContent(const string& content)
{
m_content += content;
}
virtual const string content() const
{
return m_content;
}
public:
string m_content;
};
class PVPlainTextCandidatePanel : public OVPlainTextCandidatePanel {
public:
PVPlainTextCandidatePanel()
: m_visible(false)
, m_shouldUpdate(false)
{
}
virtual OVFreeContentStorage* textStorage()
{
return &m_textStorage;
}
virtual PVFreeContentStorage* accessTextStorage()
{
return &m_textStorage;
}
virtual void hide()
{
m_visible = false;
}
virtual void show()
{
m_visible = true;
}
virtual void setPrompt(const string& prompt)
{
m_prompt = prompt;
}
virtual string prompt()
{
return m_prompt;
}
virtual void updateDisplay()
{
m_shouldUpdate = true;
}
virtual bool isVisible()
{
return m_visible;
}
virtual bool yieldToCandidateEventHandler()
{
return false;
}
virtual void cancelEventHandler()
{
}
public:
void reset()
{
m_shouldUpdate = false;
m_visible = false;
m_prompt = "";
m_textStorage.clear();
}
void finishUpdate()
{
m_shouldUpdate = false;
}
bool shouldUpdate()
{
return m_shouldUpdate;
}
protected:
bool m_visible;
bool m_shouldUpdate;
string m_prompt;
PVFreeContentStorage m_textStorage;
};
class PVCandidateService : public OVCandidateService {
public:
PVCandidateService(OVLoaderService* loaderService)
: m_verticalCandidatePanel(loaderService)
, m_horizontalCandidatePanel(loaderService)
, m_oneDimensionalPanelIsVertical(true)
{
}
virtual OVPlainTextCandidatePanel* usePlainTextCandidatePanel()
{
m_lastUsedPanel = &m_plainTextCandidatePanel;
return &m_plainTextCandidatePanel;
}
virtual OVOneDimensionalCandidatePanel* useVerticalCandidatePanel()
{
m_lastUsedPanel = &m_verticalCandidatePanel;
return &m_verticalCandidatePanel;
}
virtual OVOneDimensionalCandidatePanel* useHorizontalCandidatePanel()
{
m_lastUsedPanel = &m_horizontalCandidatePanel;
return &m_horizontalCandidatePanel;
}
virtual OVOneDimensionalCandidatePanel* useOneDimensionalCandidatePanel()
{
return m_oneDimensionalPanelIsVertical ? useVerticalCandidatePanel() : useHorizontalCandidatePanel();
}
public:
virtual void resetAll()
{
m_horizontalCandidatePanel.reset();
m_verticalCandidatePanel.reset();
m_plainTextCandidatePanel.reset();
m_lastUsedPanel = 0;
}
virtual void resetExcept(OVCandidatePanel* panel)
{
if (panel != &m_horizontalCandidatePanel)
m_horizontalCandidatePanel.reset();
if (panel != &m_verticalCandidatePanel)
m_verticalCandidatePanel.reset();
if (panel != &m_plainTextCandidatePanel)
m_plainTextCandidatePanel.reset();
}
virtual OVCandidatePanel* lastUsedPanel()
{
return m_lastUsedPanel;
}
virtual PVVerticalCandidatePanel* accessVerticalCandidatePanel()
{
return &m_verticalCandidatePanel;
}
virtual PVHorizontalCandidatePanel* accessHorizontalCandidatePanel()
{
return &m_horizontalCandidatePanel;
}
virtual PVPlainTextCandidatePanel* accessPlainTextCandidatePanel()
{
return &m_plainTextCandidatePanel;
}
public:
virtual void setOneDimensionalPanelVertical(bool vertical = true)
{
m_oneDimensionalPanelIsVertical = vertical;
}
protected:
bool m_oneDimensionalPanelIsVertical;
PVPlainTextCandidatePanel m_plainTextCandidatePanel;
PVHorizontalCandidatePanel m_horizontalCandidatePanel;
PVVerticalCandidatePanel m_verticalCandidatePanel;
OVCandidatePanel* m_lastUsedPanel;
};
};
#endif | 30.867196 | 115 | 0.550636 |
f43b4990c12c5dbb183467b9b3f53ef02adfa009 | 720 | tsx | TypeScript | libs/service-portal/finance/src/screens/FinanceEmployeeClaims/FinanceEmployeeClaims.tsx | rafnarnason/island.is | 3972cfbdee21b9bc7b2f055b144c30e37310983f | [
"MIT"
] | 154 | 2020-09-05T21:44:32.000Z | 2022-03-29T09:40:53.000Z | libs/service-portal/finance/src/screens/FinanceEmployeeClaims/FinanceEmployeeClaims.tsx | rafnarnason/island.is | 3972cfbdee21b9bc7b2f055b144c30e37310983f | [
"MIT"
] | 3,029 | 2020-09-01T08:55:21.000Z | 2022-03-31T23:31:50.000Z | libs/service-portal/finance/src/screens/FinanceEmployeeClaims/FinanceEmployeeClaims.tsx | rafnarnason/island.is | 3972cfbdee21b9bc7b2f055b144c30e37310983f | [
"MIT"
] | 32 | 2020-09-14T09:59:52.000Z | 2022-02-26T18:29:56.000Z | import React from 'react'
import { useLocale, useNamespaces } from '@island.is/localization'
import { m } from '@island.is/service-portal/core'
import DocumentScreen from '../../components/DocumentScreen/DocumentScreen'
const EmployeeClaims = () => {
useNamespaces('sp.employee-claims')
const { formatMessage } = useLocale()
return (
<DocumentScreen
title={formatMessage(m.financeEmployeeClaims)}
intro={formatMessage({
id: 'sp.employee-claims:intro',
defaultMessage:
'Hér er að finna opinber gjöld utan staðgreiðslu sem dregin eru af starfsmönnum.',
})}
listPath="employeeClaims"
defaultDateRangeMonths={12}
/>
)
}
export default EmployeeClaims
| 30 | 92 | 0.693056 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.