text
stringlengths 20
812k
| id
stringlengths 40
40
| metadata
dict |
---|---|---|
# Server Routes
```
/
/lobby
/game
```
## overview
Route: /
### Enter lobby:
expects:
{
"request" : "enter_lobby",
"data" :
{
"player_name": <player_name>
}
}
returns:
{
"name" : "enter_lobby",
"data" :
{
"session": <session>
}
}
Client should redirect to ```/lobby?session=<session>```
Some kind of overview page. Shows highscore, register and login players.
### login
A session key is generated and it is stored locally inside the URL as get parameter `?session=@@@@@@@`.
## lobby
__Route:__ /lobby
__Sends frequently:__
{
"name" : "game_list",
"data" :
{
games :
[
{
"game_id" : <game_id>,
"game_label" : <label of the game>,
"player_list" : [],
"game_status" : <initialized | started | finished>
}
]
}
}
__Requests:__
### Create a game:
expects:
{
"request" : "create_game",
"data" :
{
"game_label" : "<label_of_the_game>"
}
}
returns:
{
"name" : "create_game",
"data" :
{
"game_id": <game_id>
}
}
Client should redirect to ```/game?game_id=<game_id>&session=<session>```
## Game
__Route:__ /game
__Incoming Events:__
```
{
"name" : "possible_requests",
"data" :
{
requests : [{request:<request>, data: {}}]
}
}
```
```
{
"name" : "error",
"data" :
{
"id" : <id>,
"message" : <message>
}
}
```
Where id is:
EXPECT_EQ(Error::NoError, 0);
EXPECT_EQ(Error::InvalidRoute, 1);
EXPECT_EQ(Error::UnsupportedAction, 2);
EXPECT_EQ(Error::MalformedRequest, 3);
EXPECT_EQ(Error::InvalidRequest, 4);
EXPECT_EQ(Error::InternalError, 5);
EXPECT_EQ(Error::InsufficientMoney, 6);
EXPECT_EQ(Error::InsufficientCoins, 7);
```
{
"name" : "money_change",
"data" :
{
player: <name>,
deposit: <new_value>
}
}
```
```
{
"name" : "property_change",
"data" :
{
index: <index>,
owner: <player_name>,
construction_level: <level>
}
}
```
```
{
"name" : "player_move",
"data" :
{
player_name : <player_name>,
type : <forward | backward | jump>
target : <field_index>
}
}
```
```
{
"name" : "end_game"
}
```
__Requests:__
### Game Board
Expects:
{
"request" : "game_board"
}
Returns:
{
"name" : "game_board",
"data" : {
fields :
[
{
name : <field_name>,
type : < start | street | station | event_card | society_card | jail | free | go_to_jail | tax | utility >,
group : < 0 | 1 | ... | 9 >,
price : <price>,
house_price : <price>,
rent : [ <base_rent>, <one_house_rent>, ..., <hotel_rent> ]
},
...
]
}
}
### Join Game
Expects:
{
"request" : "join_game"
}
Returns:
{
"name" : "join_game",
"data" :
{
player_name : <player_name>
}
}
### Ready
Expects:
{
"request" : "player_ready"
}
Returns:
{
"name" : "player_ready",
"data" :
{
player_name : <player_name>
}
}
### Start a game:
Expects:
{
"request" : "game_start"
}
Returns:
{
"name" : "game_start"
}
### End turn:
Expects:
{
"request" : "end_turn"
}
Returns:
{
"name" : "change_turn",
"data" :
{
player_name : <player_name>
}
}
### Roll dices:
Expects:
{
"request" : "roll_dice"
}
Returns:
{
"name" : "roll_dice",
"data" :
{
player_name : <player_name>,
eyes : [<eye1>, <eye2>]
}
}
### Don't buy a Street
Possible Request:
```
{
"request" : "dont_buy_field",
}
```
### Buy a Street
Possible Request:
```
{
"request" : "buy_field",
}
```
Returns:
on success:
```
{
"name" : "property_change",
"data" :
{
index: <index>,
owner: <player_name>,
construction_level: <level>
}
}
```
or
on failure:
```
{
"name" : "error",
"data" :
{
"id" : <id>,
"message" : <message>
}
}
```
### Pay a Debt
Possible Request:
```
{
"request" : pay_debt,
"data": {
"amount": <amount>,
"beneficiary" : <name>
}
}
```
Request:
```
{
"request" : pay_debt,
"data": {
"beneficiary": <name>
}
}
```
Returns:
on success:
```
{
"name" : "money_change",
"data" :
{
player: <name>,
deposit: <new_value>
}
}
```
or
on failure:
```
{
"name" : "error",
"data" :
{
"id" : <id>,
"message" : <message>
}
}
```
### Build Houses
Possible Request:
```
{
"request" : build_houses,
"data": {
"groups": [<group_id>, ...]
}
}
```
Request:
Construction level needs to be in range from 0 = no building, 1 = one house, ... up to 5 = hotel.
A request can only contain fields from one group.
```
{
"request" : build_houses,
"data": {
"building_sites": { <field_id> : <construction_level>, ... }
}
}
```
Returns:
on success:
```
{
"name" : "property_change",
"data" :
{
index: <index>,
owner: <player_name>,
construction_level: <level>
}
}
```
or
on failure:
```
{
"name" : "error",
"data" :
{
"id" : <id>,
"message" : <message>
}
}
```
#
## Watson
Is a game manipulating instance, which allows the player to cheat around in the game. But it comes for a price. Watson demands real life actions and informations.
Some actions have direct impact on the game while others generate Watson Coins.
__Watson Coins__
can be used as currency by the course of 1 coin to 50 ingame money.
### Advertising
Client sends on click to server:
```
{
"request" : "clicked_on_add",
"data" :
{
"add_name" : <add_name>
}
}
```
Effect:
Server manipulates the current players roll dice result.
### Scanned GMail Account
Client sends on scan gmail account to server:
```
{
"request" : "scanned_gmail_account",
"data" :
{
"dices" : [ <eyes>, <eyes> ]
}
}
```
Effect:
Player will roll the requested eyes on next roll dice.
### Add Watson Coins
Client sends for each round a player hast activated bitcoin mining a request to add a watson coin:
```
{
"request" : "add_watson_coin",
"data" :
{
"amount" : <amount>,
"source" : "bitcoin_mining"
}
}
```
|
b3c8348d7a51d916aff62ce6a238ef0f8972a71e
|
{
"blob_id": "b3c8348d7a51d916aff62ce6a238ef0f8972a71e",
"branch_name": "refs/heads/master",
"committer_date": "2018-10-07T08:36:53",
"content_id": "26ea4a46f3ddabe79389171a717a26b7b78f25c4",
"detected_licenses": [
"MIT"
],
"directory_id": "a3cf247e8702f42566f631022c79947e1bfa04a6",
"extension": "md",
"filename": "api.md",
"fork_events_count": 0,
"gha_created_at": "2018-04-20T09:12:56",
"gha_event_created_at": "2019-01-31T08:09:57",
"gha_language": "C++",
"gha_license_id": "MIT",
"github_id": 130338757,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 7326,
"license": "MIT",
"license_type": "permissive",
"path": "/api/api.md",
"provenance": "stack-edu-markdown-0006.json.gz:51695",
"repo_name": "ratnim/SelfawareMonopoly",
"revision_date": "2018-10-07T08:36:53",
"revision_id": "d378d3d30a8d432113a881f335e5272842f65d12",
"snapshot_id": "a3e01151d11ce76aeb83139bfa32dff946b28756",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/ratnim/SelfawareMonopoly/d378d3d30a8d432113a881f335e5272842f65d12/api/api.md",
"visit_date": "2021-07-05T21:48:29.889288",
"added": "2024-11-18T19:14:19.162046+00:00",
"created": "2018-10-07T08:36:53",
"int_score": 3,
"score": 3.296875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0006.json.gz"
}
|
---
title: bud.when
description: Conditionally execute a function based on conditions
---
Executes a function if a given test is `true`.
- The first parameter is the conditional check.
- The second parameter is the function to run if `true`.
- The third parameter is optional; executed if the conditional is not `true`.
## Usage
Only produce a vendor bundle when running in `production` mode:
```js
bud.when(bud.isProduction, () => bud.vendor())
```
Use `eval` sourcemap in development mode and `hidden-source-map` in production:
```js
bud.when(
bud.isDevelopment,
() => bud.devtool('eval'),
() => bud.devtool('hidden-source-map'),
)
```
For clarity, here is a very verbose version of the same thing:
```js
const test = bud.isDevelopment
const inProduction = () => bud.devtool('eval')
const inDevelopment = () => bud.devtool('hidden-source-map')
bud.when(test, inProduction, inDevelopment)
```
|
7013511ba68a819a974178ea55a401b73a1d69c9
|
{
"blob_id": "7013511ba68a819a974178ea55a401b73a1d69c9",
"branch_name": "refs/heads/main",
"committer_date": "2023-08-24T16:36:33",
"content_id": "3eadd1d0bdd58e1e717ec486a2db5e098c9087e9",
"detected_licenses": [
"MIT"
],
"directory_id": "ce7b6b3a0f405a965e44dc3bcc7ea6e9e36e7bc2",
"extension": "mdx",
"filename": "bud.when.mdx",
"fork_events_count": 45,
"gha_created_at": "2020-06-13T07:56:37",
"gha_event_created_at": "2023-09-13T16:35:03",
"gha_language": "TypeScript",
"gha_license_id": "MIT",
"github_id": 271965695,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 910,
"license": "MIT",
"license_type": "permissive",
"path": "/sources/@repo/docs/content/reference/bud.when.mdx",
"provenance": "stack-edu-markdown-0005.json.gz:206609",
"repo_name": "roots/bud",
"revision_date": "2023-08-24T16:36:33",
"revision_id": "189de01ad6611d6a9f14c015ce69e93eafa73cf9",
"snapshot_id": "db0d45e87c945ea79987cc54db27c4a216cf92f8",
"src_encoding": "UTF-8",
"star_events_count": 277,
"url": "https://raw.githubusercontent.com/roots/bud/189de01ad6611d6a9f14c015ce69e93eafa73cf9/sources/@repo/docs/content/reference/bud.when.mdx",
"visit_date": "2023-08-24T16:49:13.767031",
"added": "2024-11-18T22:10:07.855053+00:00",
"created": "2023-08-24T16:36:33",
"int_score": 4,
"score": 3.859375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0005.json.gz"
}
|
<div class="h-50 h-width-100" style="text-align:center">
<div style="text-align:center" id="top1">
<img style="width:400px" src="https://i.ibb.co/9tKSzNv/h-Trixx-Framework-Logo-Small.png" id="htrixxLogo" />
</div>
<br />
<br />
<h5 class="h-p-30 h-p-r-300 h-p-l-300" id="use0">
Htrixx is an open-source web development framework.
In htrixx you will find many html components that will change from the moment you add hTrixx as a reference in your project.
</h5>
<h6 class="h-p-30 h-p-r-300 h-p-l-300" id="use0">
Some things about hTrixx:
</h6>
<p class="h-p-r-400 h-p-l-400" id="use2">
✓ It is very easy to use
</p>
<p class="h-p-r-400 h-p-l-400" id="use1">
✓ It can be used together with Bootstrap and jQuery
</p>
<p class="h-p-r-400 h-p-l-400" id="use1">
✓ Contains all HTML elements
</p>
<p class="h-p-r-400 h-p-l-400" id="use1">
✓ It's responsive
</p>
<p class="h-p-r-400 h-p-l-400" id="use1">
✓ It is free and so it will always be
</p>
<p class="h-p-r-400 h-p-l-400" id="use1">
✓ New components are still being developed which will be released after testing
</p>
</div>
<div class="h-grey-b-new h-50 h-width-100">
<br />
<br />
<h5 class="h-p-r-300 h-p-l-300 text-center h-white">
Explore our components
</h5>
<br />
<div class="row h-m-30 h-white">
<div class="col-md-12 col-12 text-center">
<p>hTrixx is constantly developing. All the components will remain unchanged, so you can work with the current version, and instead new components will be added.</p>
</div>
</div>
<address class="text-center h-white">
<strong>Contact me at:</strong>
<a href="mailto:s.darco.stefan<EMAIL_ADDRESS> </address>
<br />
<br />
</div>
|
84ad90008559d595458f9d00eb27731e18cdab30
|
{
"blob_id": "84ad90008559d595458f9d00eb27731e18cdab30",
"branch_name": "refs/heads/master",
"committer_date": "2022-04-07T17:25:50",
"content_id": "cf6d6e6efc5e5e058b8cc21048030170e56303f7",
"detected_licenses": [
"MIT"
],
"directory_id": "880addb5a98c5c3f4552d0eaa5c7cd433a6968ef",
"extension": "md",
"filename": "README.md",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 184127173,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1918,
"license": "MIT",
"license_type": "permissive",
"path": "/README.md",
"provenance": "stack-edu-markdown-0003.json.gz:162769",
"repo_name": "darcostoianov/hTrixx",
"revision_date": "2022-04-07T17:25:50",
"revision_id": "c7ec3ca9a6212cbe5fee13ff8556469ef885868a",
"snapshot_id": "4e683daa5de927be110336ee6cee66c991551536",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/darcostoianov/hTrixx/c7ec3ca9a6212cbe5fee13ff8556469ef885868a/README.md",
"visit_date": "2022-05-05T07:23:06.767637",
"added": "2024-11-18T22:19:33.869434+00:00",
"created": "2022-04-07T17:25:50",
"int_score": 2,
"score": 2.03125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0003.json.gz"
}
|
<?php
namespace App\Facades\Components;
class FileCheck
{
/**
* ファイルサイズが指定した最大サイズより小さいかどうか
*
* @param int $maxSize
* @param int $fileSize
* @return bool
*/
public function isLowerMaxSize(int $maxSize, int $fileSize){
return ($maxSize > $fileSize)
? true
: false;
}
/**
* ファイルが指定した拡張子かどうか
*
* @param array $extensions
* @param string $fileExtension
* @return bool
*/
public function isExtension(array $extensions, string $fileExtension)
{
return in_array($fileExtension, $extensions )
? true
: false;
}
}
|
57c67fda7806239160454388a0b825a4c798f707
|
{
"blob_id": "57c67fda7806239160454388a0b825a4c798f707",
"branch_name": "refs/heads/master",
"committer_date": "2019-07-06T04:03:52",
"content_id": "f6004555cd38eda3a5b6b19e6614b5a5a8926101",
"detected_licenses": [
"MIT"
],
"directory_id": "561bb49e484579b3cfd379d16f5777470c9b6560",
"extension": "php",
"filename": "FileCheck.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 182502938,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 742,
"license": "MIT",
"license_type": "permissive",
"path": "/application/app/Facades/Components/FileCheck.php",
"provenance": "stack-edu-0053.json.gz:272599",
"repo_name": "suupoo/kss-lab",
"revision_date": "2019-07-06T04:03:52",
"revision_id": "2f3e226ecdddc535b006b10cd52ffbb715022cd5",
"snapshot_id": "c7beb8a2db55b08ab21615619dd4e7ebc10a0cc4",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/suupoo/kss-lab/2f3e226ecdddc535b006b10cd52ffbb715022cd5/application/app/Facades/Components/FileCheck.php",
"visit_date": "2022-03-13T13:21:30.275972",
"added": "2024-11-18T23:15:20.830281+00:00",
"created": "2019-07-06T04:03:52",
"int_score": 3,
"score": 2.984375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0071.json.gz"
}
|
//
// AdvancedSearchBandsResultsViewController.swift
// Metal Archives
//
// Created by Thanh-Nhon Nguyen on 12/03/2019.
// Copyright © 2019 Thanh-Nhon Nguyen. All rights reserved.
//
import UIKit
import Toaster
import FirebaseAnalytics
final class AdvancedSearchBandsResultsViewController: RefreshableViewController {
var optionsList: String!
private var bandAdvancedSearchResultPagableManager: PagableManager<AdvancedSearchResultBand>!
weak var simpleNavigationBarView: SimpleNavigationBarView?
override func viewDidLoad() {
super.viewDidLoad()
initBandAdvancedSearchResultPagableManager()
bandAdvancedSearchResultPagableManager.fetch()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
simpleNavigationBarView?.setRightButtonIcon(nil)
simpleNavigationBarView?.isHidden = false
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
simpleNavigationBarView?.isHidden = !isMovingToParent
}
override func initAppearance() {
super.initAppearance()
tableView.contentInset = UIEdgeInsets(top: baseNavigationBarViewHeightWithoutTopInset, left: 0, bottom: UIApplication.shared.keyWindow?.safeAreaInsets.bottom ?? 0, right: 0)
AdvancedBandNameTableViewCell.register(with: tableView)
LoadingTableViewCell.register(with: tableView)
}
override func refresh() {
bandAdvancedSearchResultPagableManager.reset()
tableView.reloadData()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
self.bandAdvancedSearchResultPagableManager.fetch()
}
Analytics.logEvent("refresh_advanced_search_band_results", parameters: nil)
}
func initBandAdvancedSearchResultPagableManager() {
guard var formattedOptionsList = optionsList.addingPercentEncoding(withAllowedCharacters: customURLQueryAllowedCharacterSet) else {
assertionFailure("Error adding percent encoding to option list.")
return
}
// encode space by + instead of %20
formattedOptionsList = formattedOptionsList.replacingOccurrences(of: "%20", with: "+")
bandAdvancedSearchResultPagableManager = PagableManager<AdvancedSearchResultBand>(options: ["<OPTIONS_LIST>": formattedOptionsList])
bandAdvancedSearchResultPagableManager.delegate = self
}
private func updateTitle() {
guard let totalRecords = bandAdvancedSearchResultPagableManager.totalRecords else {
simpleNavigationBarView?.setTitle("No result found")
return
}
if totalRecords == 0 {
simpleNavigationBarView?.setTitle("No result found")
} else if totalRecords == 1 {
simpleNavigationBarView?.setTitle("Loaded \(bandAdvancedSearchResultPagableManager.objects.count) of \(totalRecords) result")
} else {
simpleNavigationBarView?.setTitle("Loaded \(bandAdvancedSearchResultPagableManager.objects.count) of \(totalRecords) results")
}
}
}
//MARK: - PagableManagerDelegate
extension AdvancedSearchBandsResultsViewController: PagableManagerDelegate {
func pagableManagerDidBeginFetching<T>(_ pagableManager: PagableManager<T>) where T : Pagable {
simpleNavigationBarView?.setTitle("Loading...")
showHUD()
}
func pagableManagerDidFailFetching<T>(_ pagableManager: PagableManager<T>) where T : Pagable {
hideHUD()
endRefreshing()
Toast.displayMessageShortly(errorLoadingMessage)
}
func pagableManagerDidFinishFetching<T>(_ pagableManager: PagableManager<T>) where T : Pagable {
hideHUD()
endRefreshing()
updateTitle()
tableView.reloadData()
}
}
//MARK: - UITableViewDelegate
extension AdvancedSearchBandsResultsViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
guard let manager = bandAdvancedSearchResultPagableManager else {
return
}
if manager.objects.indices.contains(indexPath.row) {
let result = manager.objects[indexPath.row]
pushBandDetailViewController(urlString: result.band.urlString, animated: true)
Analytics.logEvent("select_an_advanced_search_result", parameters: nil)
}
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard let _ = bandAdvancedSearchResultPagableManager.totalRecords else {
return
}
if bandAdvancedSearchResultPagableManager.moreToLoad && indexPath.row == bandAdvancedSearchResultPagableManager.objects.count {
bandAdvancedSearchResultPagableManager.fetch()
} else if !bandAdvancedSearchResultPagableManager.moreToLoad && indexPath.row == bandAdvancedSearchResultPagableManager.objects.count - 1 {
Toast.displayMessageShortly(endOfListMessage)
}
}
}
//MARK: - UITableViewDataSource
extension AdvancedSearchBandsResultsViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let manager = bandAdvancedSearchResultPagableManager else {
return 0
}
if manager.moreToLoad {
if manager.objects.count == 0 {
return 0
}
return manager.objects.count + 1
}
return manager.objects.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if bandAdvancedSearchResultPagableManager.moreToLoad && indexPath.row == bandAdvancedSearchResultPagableManager.objects.count {
let loadingCell = LoadingTableViewCell.dequeueFrom(tableView, forIndexPath: indexPath)
loadingCell.displayIsLoading()
return loadingCell
}
let cell = AdvancedBandNameTableViewCell.dequeueFrom(tableView, forIndexPath: indexPath)
let result = bandAdvancedSearchResultPagableManager.objects[indexPath.row]
cell.fill(with: result)
cell.tappedThumbnailImageView = { [unowned self] in
self.presentPhotoViewerWithCacheChecking(photoUrlString: result.band.imageURLString, description: result.band.name, fromImageView: cell.thumbnailImageView)
Analytics.logEvent("view_advanced_search_result_thumbnail", parameters: nil)
}
return cell
}
}
// MARK: - UIScrollViewDelegate
extension AdvancedSearchBandsResultsViewController: UIScrollViewDelegate {
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
simpleNavigationBarView?.transformWith(scrollView)
}
}
|
0e8fffbd4fd91f5c75b494f3a56d5bbca5b3caef
|
{
"blob_id": "0e8fffbd4fd91f5c75b494f3a56d5bbca5b3caef",
"branch_name": "refs/heads/master",
"committer_date": "2021-03-27T21:08:03",
"content_id": "cdb3983c189e499e5c45c1f8f98c25691b5209b7",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "69a4ccf0fe074f924c5c2746c86d971da3cb5582",
"extension": "swift",
"filename": "AdvancedSearchBandsResultsViewController.swift",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Swift",
"length_bytes": 7136,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Metal Archives/Metal Archives/Controllers/Search/AdvancedSearch/AdvancedSearchBands/AdvancedSearchBandsResultsViewController.swift",
"provenance": "stack-edu-0071.json.gz:722076",
"repo_name": "mohsinalimat/Metal-Archives-iOS",
"revision_date": "2021-03-27T21:08:03",
"revision_id": "274527b791c90b916511d76f6e37982fb5742a42",
"snapshot_id": "b5d9b271cf92566b454d77399e6b0942ec24a1f2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mohsinalimat/Metal-Archives-iOS/274527b791c90b916511d76f6e37982fb5742a42/Metal Archives/Metal Archives/Controllers/Search/AdvancedSearch/AdvancedSearchBands/AdvancedSearchBandsResultsViewController.swift",
"visit_date": "2023-04-02T22:47:34.281621",
"added": "2024-11-18T21:24:20.429614+00:00",
"created": "2021-03-27T21:08:03",
"int_score": 2,
"score": 2.296875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0089.json.gz"
}
|
#coding:utf-8
#创建和使用字典
def first():
phonebook = {'Alice':'2341','Beth':'9102','Cecil':'3258'}
print phonebook,phonebook['Alice']
#dict函数通过其他映射或者键值对的序列建立字典
def second():
items = [('name','Gumby'),('age',42)]
d = dict(items)
print d['name'],'\n',d
dic = dict(name = 'fuzongjian',age = 42)
print dic
#基本字典操作
'''
len(dict)返回dict中项(键-值对)的数量
del dict[k]删除键为k的项
k in dict 检查d中是否含有键为k的项
'''
def third():
people = {
'Alice':{
'phone':'1234',
'addr':'Foo drive 23'
},
'Beth':{
'phone':'2364',
'addr':'Foo drive 23'
},
'Cecil':{
'phone':'2345',
'addr':'Foo drive 23'
}
}
print len(people)
#字典的格式化字符串
def firth():
template = '''
<html>
<head><title>%(title)s</title></head>
<body>
<h1>%(title)s</h1>
<p>%(text)s</p>
</body>
</html>
'''
data = {'title':'My Home Page','text':'Welcome to my home page!'}
print template % data
#字典方法
from copy import deepcopy
def fifth():
#clear方法清除字典中的所有想。
dic = {}
dic['name'] = 'fuzongjian'
print dic,'-----',dic.clear(),'-----',dic
#copy方法返回一个具有相同键值对的新字典-----浅复制
print '浅复制'
x = {'name':'fuzongjian','age':['1','2','3']}
y = x.copy()
print x,'---',y
y['name'] = 'fuzongyang'
y['age'].remove('1')
print x,'---',y
#deepcopy深复制
print '深复制'
d = {}
d['name'] = ['fuzongjian','fuzongyang']
c = d.copy()
dc = deepcopy(d)
d['name'].append('fuzonglin')
print c,'---',dc
print 'fromkeys方法使用给定的键建立新的字典,每个键都对应一个默认的值None'
print {}.fromkeys(['name','age'])
print dict.fromkeys(['name','age'])
print dict.fromkeys(['name','age'],'(unknown)')
print 'get方法是个更宽松的访问字典项的方法'
'''
当我们使用dict[key]时,如果key不存在的话,一般会报错,而选择dict.get(key)不会报错,会返回一个None,同时自己也可自定义
一个“默认值”,替换None
'''
test = {}
print test.get('name')
print test.get('name','fuzongjian')
#has_key方法可以检查字典中是否含有特定的键
sy = {'name':'fuzongjian'}
print sy.has_key('age'),'---',sy.has_key('name')
#items和iteritems
#items方法将字典所有的项以列表的方式返回,列表中的每一项都标示为键值对的形式,但是项在返回时并没有遵循特定的次序
wx = {'name':'fuzongjian','age':20,'hobby':'running'}
print wx.items()
#iteritems方法的作用大致相同,但是返回一个迭代器对象而不是列表
print wx.iteritems(),'---',list(wx.iteritems())
#key和iterkeys ----values和itervalues
#key方法将字典中的键以列表形式返回,而iterkeys则返回针对键的迭代器
print wx.keys(),'---',wx.iterkeys(),'---',list(wx.iterkeys())
print wx.values(),'---',wx.itervalues(),'---',list(wx.itervalues())
#pop方法用来获取对应于给定键的值,然后将这个键-值对从字典中移除
nb = {'name':'fuzongjian','hobby':'running'}
print nb.pop('hobby'),'---',nb
#popitem方法类似于list.pop,后者会弹出列表的最后一个元素,popitem弹出随机的项,因为字典元素随机
ue = {'name':'fuzongjian','hobby':'running','age':1993}
print ue.popitem()
#setdefault方法在某种程度上类似于get方法,能够获得与给定键相关联的值,
#除此之外,setdefault还能在字典这个不含有给定键的情况下设定相应的键值
xn = {}
print xn.setdefault('name','fuzongjian')
xn['name'] = 'rabbit'
print xn.setdefault('name','1234')
print xn
print xn.setdefault('age')
#update方法可以利用一个字典更新另外一个字典
vr = {'name':'fuzongjian'}
ar = {'age':1993}
vr.update(ar)
print vr
def appRun():
fifth()
# firth()
# third()
# second()
# first()
if __name__ == '__main__':
appRun()
|
e1cd3f4e53cdd8d7c645519b0fc4b72692fa096e
|
{
"blob_id": "e1cd3f4e53cdd8d7c645519b0fc4b72692fa096e",
"branch_name": "refs/heads/master",
"committer_date": "2016-12-19T11:58:55",
"content_id": "960290ae3dc234fa9289eafbebe0a9edd6fa0cf0",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "4df7feb529d6f57d00a61f9f47634ddeadc9a8f7",
"extension": "py",
"filename": "base.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 67490254,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3942,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/字典/base.py",
"provenance": "stack-edu-0058.json.gz:332264",
"repo_name": "fuzongjian/PythonStudy",
"revision_date": "2016-12-19T11:58:55",
"revision_id": "1977b08733235946230bb73d3ad92d4853e12f7d",
"snapshot_id": "42ee59d3719a1ed5e88cc7428b5b107f52bad84d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/fuzongjian/PythonStudy/1977b08733235946230bb73d3ad92d4853e12f7d/字典/base.py",
"visit_date": "2020-09-10T08:18:08.354978",
"added": "2024-11-19T00:43:45.826813+00:00",
"created": "2016-12-19T11:58:55",
"int_score": 4,
"score": 4.5,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0076.json.gz"
}
|
from datetime import datetime,timedelta
import numpy
'''
-----------------------------------------------------------------
mydatetime v0.2 for python
Copyright (c) 2015 hadacchi
-----------------------------------------------------------------
*** This script requires numpy, i.e. numerical python ***
This script converts from/into date into/from serial date.
MS Excel counts 1900/2/29 (ref. Microsoft Help & Support No. 214019),
but python doesn't count. Thus, return value from this script
`toSerial()' is equals only after 1900/3/1
If you need valid serial date, change base date `__ZERODATE'
from (datetime.datetime(1970,1,1),25569)
to (datetime.datetime(1900,1,1),1)
'''
class mydatetime(datetime):
## base date
# to identify Excels
__ZERODATE=(datetime(1970,1,1,0,0,0,0),25569)
# to return valid serial date
#__ZERODATE=(datetime(1900,1,1,0,0,0,0),1)
## expression for milliseconds
__MILLIFMT='%u'
def __sub__(self,t):
# if return value is <type 'timedelta'>
if t.__class__ == self.__class__ or \
t.__class__ == self.__ZERODATE[0].__class__:
#return super(mydatetime,self).__sub__(self,t)
return super().__sub__(t)
# else (mydatetime-timedelta) should be mydatetime
else:
#tmp = super(mydatetime,self).__sub__(t)
tmp = super().__sub__(t)
return self.__class__(
tmp.year,tmp.month,tmp.day,tmp.hour,
tmp.minute,tmp.second,tmp.microsecond,tmp.tzinfo
)
def __add__(self,t):
# if return value is <type 'timedelta'>
if t.__class__ == self.__class__ or \
t.__class__ == self.__ZERODATE[0].__class__:
return datetime.__add__(t)
# else (mydatetime-timedelta) should be mydatetime
else:
#tmp = super(mydatetime,self).__add__(self,t)
tmp = super().__add__(t)
return self.__class__(
tmp.year,tmp.month,tmp.day,tmp.hour,
tmp.minute,tmp.second,tmp.microsecond,tmp.tzinfo
)
def strftime(self,fmt):
'''milliseconds (output by %u) is implemented'''
tmp=[]
for i in fmt.split('%%'):
tmp.append(('%06d'%self.microsecond)[:3]\
.join(i.split(self.__MILLIFMT)))
return super(mydatetime,self).strftime(self,'%%'.join(tmp))
def toSerial(self):
'''return serial date'''
tmp=self-self.__ZERODATE[0]
serial_val=self.__ZERODATE[1]+tmp.days
serial_val=serial_val+float(tmp.seconds)/24/3600\
+float(tmp.microseconds)/24/3600/1000000
return serial_val
@staticmethod
def fromTuple(d,t=(0,0,0)):
'''d=(year,month,day),t=(hour,min,sec),sec can be float'''
if type(t[2]) is float: f=int(t[2]*1000000-int(t[2])*1000000)
elif len(t)>=4: f=t[3]
else: f=0
# call parent's constructor
return mydatetime(d[0],d[1],d[2],t[0],t[1],int(t[2]),f)
@staticmethod
def fromSerial(val):
'''return mydatetime from serial value'''
tmp=val-mydatetime._mydatetime__ZERODATE[1]
day=int(tmp)
sec=round((tmp-day)*24*3600,3)
dt=timedelta(days=day,seconds=sec)
tmp=mydatetime._mydatetime__ZERODATE[0]+dt
# call parent's constructor
return mydatetime(tmp.year,tmp.month,tmp.day,
tmp.hour,tmp.minute,tmp.second,tmp.microsecond,tmp.tzinfo)
@staticmethod
def Serial2Sec(val,comp=False):
'''if comp is True, return complete seconds(LongInt) from ZERODATE '''
if type(val)!=numpy.ndarray:
if type(val)!=type([]): numpy.array([val])
else: numpy.array(val)
else: True
c=24*3600
if not comp: return numpy.round((val-numpy.array(val,dtype=int))*c,3)
else:
val=val-mydatetime._mydatetime__ZERODATE[1]
return numpy.round((val-numpy.array(val,dtype=int))*c+numpy.array(val,dtype=int)*c,3)
if len(ret)==1: return ret[0]
else: return ret
|
7dd43b2d969279641dc8d71a33090478634f9a05
|
{
"blob_id": "7dd43b2d969279641dc8d71a33090478634f9a05",
"branch_name": "refs/heads/master",
"committer_date": "2017-02-06T12:51:07",
"content_id": "fe33d14f3ce3fbab01a6b3264f0122a30e8220d0",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "2b2d4e0eaff5953f68b150f5611936ec652e9316",
"extension": "py",
"filename": "mydatetime.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 43641323,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4126,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/mydatetime.py",
"provenance": "stack-edu-0054.json.gz:777761",
"repo_name": "hadacchi/mydatetime",
"revision_date": "2017-02-06T12:51:07",
"revision_id": "7fdcc682be3ede7cd22ee9221a4ee90d4ded4c14",
"snapshot_id": "d4d891d2859e28129ce31be8fcc0e84f9a4a1869",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hadacchi/mydatetime/7fdcc682be3ede7cd22ee9221a4ee90d4ded4c14/mydatetime.py",
"visit_date": "2021-01-17T14:51:06.518323",
"added": "2024-11-19T00:07:11.707961+00:00",
"created": "2017-02-06T12:51:07",
"int_score": 3,
"score": 3.15625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0072.json.gz"
}
|
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: bug
assignees: ''
---
**Before you open an issue**
- [ ] Are you using [the latest Gordon version](https://github.com/Banno/Gordon/releases/latest)? If not, try updating.
- [ ] Are you using [the latest Gradle version](https://gradle.org/releases)? If not, try updating. If you can't update your Gradle version, you may have to use an older Gordon version that supports the outdated Gradle version.
- [ ] Are you using [the latest Android Gradle Plugin version](https://developer.android.com/studio/releases/gradle-plugin)? If not, try updating. If you can't update your AGP version, you may have to use an older Gordon version that supports the outdated AGP version.
- [ ] Are you sure this is a bug? If it's a feature request or idea for improvement, or if you're just not sure that your problem is caused by a Gordon bug rather than something else, consider posting in the ["Ideas"](https://github.com/Banno/Gordon/discussions/categories/ideas) or ["Q&A"](https://github.com/Banno/Gordon/discussions/categories/q-a) Discussion categories instead of opening an issue.
**Describe the bug**
<!-- A clear and concise description of what the bug is -->
**To Reproduce**
<!-- Edit the following example steps to explain exactly how to reproduce your issue -->
1. Apply Gordon to an Android [app|library|feature] module.
2. The module has the following special setup (or n/a if it has fairly standard setup). Feel free to paste your whole buildscript with any proprietary details redacted.
3. Run the following gradle task with these arguments.
4. See error
**Expected behavior**
<!-- A clear and concise description of what you expected to happen -->
**Additional context**
<!-- Any other context about the problem -->
|
447e9048da6ff1197d75a46051585f910c5e2d1e
|
{
"blob_id": "447e9048da6ff1197d75a46051585f910c5e2d1e",
"branch_name": "refs/heads/main",
"committer_date": "2023-07-06T14:42:39",
"content_id": "cdb084185b2f0869f3609da852de8faf0e5c1611",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "15043d686442ad4576f97ba5fe6e23a110689fe0",
"extension": "md",
"filename": "bug_report.md",
"fork_events_count": 18,
"gha_created_at": "2019-10-25T14:57:10",
"gha_event_created_at": "2023-09-08T21:46:09",
"gha_language": "Kotlin",
"gha_license_id": "Apache-2.0",
"github_id": 217557173,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1803,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/.github/ISSUE_TEMPLATE/bug_report.md",
"provenance": "stack-edu-markdown-0003.json.gz:305540",
"repo_name": "Banno/Gordon",
"revision_date": "2023-07-06T14:42:39",
"revision_id": "12df78e9ebe1f08c244434d38092b06adf86cab6",
"snapshot_id": "9ca57afeaf4a109bc56943ff84ca102078e35545",
"src_encoding": "UTF-8",
"star_events_count": 160,
"url": "https://raw.githubusercontent.com/Banno/Gordon/12df78e9ebe1f08c244434d38092b06adf86cab6/.github/ISSUE_TEMPLATE/bug_report.md",
"visit_date": "2023-07-23T03:16:27.844635",
"added": "2024-11-18T21:28:30.831320+00:00",
"created": "2023-07-06T14:42:39",
"int_score": 3,
"score": 3.453125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0003.json.gz"
}
|
### [CVE-2007-6753](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2007-6753)



### Description
Untrusted search path vulnerability in Shell32.dll in Microsoft Windows 2000, Windows XP, Windows Vista, Windows Server 2008, and Windows 7, when using an environment configured with a string such as %APPDATA% or %PROGRAMFILES% in a certain way, allows local users to gain privileges via a Trojan horse DLL under the current working directory, as demonstrated by iTunes and Safari.
### POC
#### Reference
- http://blog.acrossecurity.com/2010/10/breaking-setdlldirectory-protection.html
#### Github
No PoCs found on GitHub currently.
|
04be1356778cb8d73f7518fa9b2630a2184b54d7
|
{
"blob_id": "04be1356778cb8d73f7518fa9b2630a2184b54d7",
"branch_name": "refs/heads/main",
"committer_date": "2023-08-22T10:57:28",
"content_id": "262801dbf7a96b4e1aee6e65872608ad7303e9c9",
"detected_licenses": [
"MIT"
],
"directory_id": "9b96a77fdd7eeba74a3d66d09eb8ebbf28b7b8b9",
"extension": "md",
"filename": "CVE-2007-6753.md",
"fork_events_count": 647,
"gha_created_at": "2022-01-31T13:23:51",
"gha_event_created_at": "2023-05-24T04:54:19",
"gha_language": "HTML",
"gha_license_id": "MIT",
"github_id": 454015416,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 880,
"license": "MIT",
"license_type": "permissive",
"path": "/2007/CVE-2007-6753.md",
"provenance": "stack-edu-markdown-0010.json.gz:287425",
"repo_name": "trickest/cve",
"revision_date": "2023-08-22T10:57:28",
"revision_id": "193d43877d4d88120833461ebab51acc2e5e37f0",
"snapshot_id": "2d5fdbb47e0baf6ce74e016190dec666cdfd9bfe",
"src_encoding": "UTF-8",
"star_events_count": 5091,
"url": "https://raw.githubusercontent.com/trickest/cve/193d43877d4d88120833461ebab51acc2e5e37f0/2007/CVE-2007-6753.md",
"visit_date": "2023-08-22T19:53:39.850122",
"added": "2024-11-19T01:53:15.637727+00:00",
"created": "2023-08-22T10:57:28",
"int_score": 3,
"score": 3.125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0010.json.gz"
}
|
<?php
declare(strict_types=1);
/*
* +----------------------------------------------------------------------+
* | ThinkSNS Plus |
* +----------------------------------------------------------------------+
* | Copyright (c) 2017 Chengdu ZhiYiChuangXiang Technology Co., Ltd. |
* +----------------------------------------------------------------------+
* | This source file is subject to version 2.0 of the Apache license, |
* | that is bundled with this package in the file LICENSE, and is |
* | available through the world-wide-web at the following url: |
* | http://www.apache.org/licenses/LICENSE-2.0.html |
* +----------------------------------------------------------------------+
* | Author: Slim Kit Group <master@zhiyicx.com> |
* | Homepage: www.thinksns.com |
* +----------------------------------------------------------------------+
*/
namespace Zhiyi\Component\ZhiyiPlus\PlusComponentFeed\Tests\API2;
use Zhiyi\Plus\Models\User;
use Zhiyi\Plus\Tests\TestCase;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class TestGetDetailFeed extends TestCase
{
use DatabaseTransactions;
private $user;
/**
* 前置条件.
*/
public function setUp()
{
parent::setUp();
$this->user = factory(User::class)->create();
$this->user->roles()->sync([2]);
}
public function testGetFeedList()
{
$this->addTestFeedData($this->user);
$response = $this->get('/api/v2/feeds/'.$this->feed['id']);
$response->assertStatus(200)
->assertJsonStructure([
'id',
'user_id',
'feed_content',
'feed_from',
'like_count',
'feed_view_count',
'feed_comment_count',
'feed_latitude',
'feed_longtitude',
'feed_geohash',
'audit_status',
'feed_mark',
'created_at',
'updated_at',
'deleted_at',
'has_collect',
'has_like',
'reward',
'images',
'paid_node',
'likes',
]);
}
/**
* @param $user
* @return mixed
*/
protected function addTestFeedData($user)
{
$data = [
'feed_content' => '单元测试动态数据',
'feed_from' => 1,
'feed_mark' => time(),
'feed_latitude' => '',
'feed_longtitude' => '',
'feed_geohash' => '',
'amount' => 100,
'images' => [],
];
$this->feed = $this->actingAs($user, 'api')->post('api/v2/feeds', $data)->json();
}
}
|
3ccc8a0aca1cbb2ac47eafbf6dd848c9bf72636c
|
{
"blob_id": "3ccc8a0aca1cbb2ac47eafbf6dd848c9bf72636c",
"branch_name": "refs/heads/master",
"committer_date": "2018-02-06T10:24:22",
"content_id": "37c70cedc2d1dcb046c3562d66b37ebe41688ff1",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "df980e64e6e6c998fa66f8a9f869020929e9b6a4",
"extension": "php",
"filename": "TestGetDetailFeed.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 2912,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/packages/slimkit-plus-feed/tests/API2/TestGetDetailFeed.php",
"provenance": "stack-edu-0052.json.gz:901057",
"repo_name": "XiaoqingWang/thinksns-plus",
"revision_date": "2018-02-06T10:24:22",
"revision_id": "013e65d1326fdca6588c181778e63a8af8676486",
"snapshot_id": "50c17682bb9c6ebc4c20d3326f9b81d99aa351d3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/XiaoqingWang/thinksns-plus/013e65d1326fdca6588c181778e63a8af8676486/packages/slimkit-plus-feed/tests/API2/TestGetDetailFeed.php",
"visit_date": "2021-05-03T15:15:22.480427",
"added": "2024-11-18T22:56:39.064538+00:00",
"created": "2018-02-06T10:24:22",
"int_score": 2,
"score": 2.125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0070.json.gz"
}
|
import numpy as np
from scipy.optimize import linear_sum_assignment
def intersection_over_union(segmented_map, gt_map):
s_array = segmented_map.getEmMap().data()
gt_array = gt_map.getEmMap().data()
labels = np.unique(gt_array)
if s_array.shape != gt_array.shape:
return ValueError("Arrays must have same shape")
else:
iou_list = []
for label in labels:
if label == 0:
continue
s_mask = s_array == label
gt_mask = gt_array == label
overlap = np.sum(np.logical_and(s_mask,gt_mask))
union = np.sum(np.logical_or(s_mask,gt_mask))
iou_list.append(overlap/union)
iou = np.mean(iou_list)
return iou
def iou(s_array, gt_array, restricted=False):
if restricted:
labels = np.unique(gt_array)
else:
labels = np.unique(s_array)
if s_array.shape != gt_array.shape:
return ValueError("Arrays must have same shape")
else:
iou_list = []
for label in labels:
if label == 0:
continue
s_mask = s_array == label
gt_mask = gt_array == label
overlap = np.sum(np.logical_and(s_mask,gt_mask))
union = np.sum(np.logical_or(s_mask,gt_mask))
iou_list.append(overlap/union)
iou = np.mean(iou_list)
return iou
def matching_iou(segmented_map, gt_map):
s_array = segmented_map.getEmMap().data()
gt_array = gt_map.getEmMap().data()
segmented_labels = np.unique(s_array)
segmented_labels = segmented_labels[segmented_labels!=0]
gt_labels = np.unique(gt_array)
gt_labels = gt_labels[gt_labels!=0]
print(segmented_labels)
print(gt_labels)
iou_tensor = np.zeros([len(segmented_labels), len(gt_labels)])
for i,s in enumerate(segmented_labels):
for j,g in enumerate(gt_labels):
seg_mask = s_array==s
gt_mask = gt_array==g
iou_tensor[i, j] = iou(seg_mask, gt_mask)
row_ind, col_ind = linear_sum_assignment(iou_tensor, maximize=True)
last_label = len(segmented_labels)
label_replace_dict = {segmented_labels[r]:gt_labels[c]+last_label for c,r in zip(col_ind,row_ind)}
label_replace_back_dict = {v:v-last_label for v in label_replace_dict.values() }
iou_after = iou(s_array,gt_array)
print("**",label_replace_dict)
print("**",label_replace_back_dict)
vol_before = { l:np.sum(s_array==l) for l in np.unique(s_array)}
for k in label_replace_dict.keys():
s_array[s_array==k]=label_replace_dict[k]
for k in label_replace_back_dict.keys():
new_label = label_replace_back_dict[k]
existing_labels = np.unique(s_array)
if new_label in existing_labels:
s_array[s_array==new_label]= np.max(existing_labels)+1
s_array[s_array==k]= new_label
vol_after = {l:np.sum(s_array==l) for l in np.unique(s_array)}
print("**vol before: ", vol_before)
print("**vol after ", vol_after)
return iou(s_array,gt_array)
def average_precision(segmented_map, gt_map, thresholds=np.arange(0.05,0.95,0.1)):
segmented_array = segmented_map.getEmMap().data()
gt_array = gt_map.getEmMap().data()
segmented_labels = np.unique(segmented_array)
segmented_labels = segmented_labels[segmented_labels!=0]
gt_labels = np.unique(gt_array)
gt_labels = gt_labels[gt_labels!=0]
segmented_masks = [ segmented_array==l for l in segmented_labels ]
gt_masks = [ gt_array==l for l in gt_labels ]
iou_tensor = np.zeros([len(thresholds), len(segmented_masks), len(gt_masks)])
for i,seg_mask in enumerate(segmented_masks):
for j,gt_mask in enumerate(gt_masks):
iou_tensor[:, i, j] = iou_at_thresholds(gt_mask, seg_mask, thresholds)
TP = np.sum((np.sum(iou_tensor, axis=2) == 1), axis=1)
FP = np.sum((np.sum(iou_tensor, axis=1) == 0), axis=1)
FN = np.sum((np.sum(iou_tensor, axis=2) == 0), axis=1)
precision = TP / (TP + FP + FN + np.finfo(float).eps)
print(precision)
return np.mean(precision)
def iou_at_thresholds(seg_mask, gt_mask, thresholds=np.arange(0.05,0.95,0.1)):
intersection = np.logical_and(gt_mask, seg_mask)
union = np.logical_or(gt_mask, seg_mask)
iou = np.sum(intersection > 0) / np.sum(union > 0)
return iou > thresholds
def dice(segmented_map, gt_map):
s_array = segmented_map.getEmMap().data()
gt_array = gt_map.getEmMap().data()
labels = np.unique(gt_array)
if s_array.shape != gt_array.shape:
return ValueError("Arrays must have same shape")
else:
dice_list = []
for label in labels:
#if label == 0:
# continue
s_mask = s_array == label
gt_mask = gt_array == label
overlap = np.sum(np.logical_and(s_mask,gt_mask))
added = np.sum(s_mask) + np.sum(gt_mask)
dice_list.append(2*overlap/added)
dice = np.mean(dice_list)
return dice
def homogenity(segmented_map, gt_map):
s_array = segmented_map.getEmMap().data()
gt_array = gt_map.getEmMap().data()
labels = np.unique(s_array)
if s_array.shape != gt_array.shape:
return ValueError("Arrays must have same shape")
else:
h_list = []
for label in labels:
if label == 0:
continue
s_mask = s_array == label
gt_mask = gt_array == label
overlap = np.sum(np.logical_and(s_mask,gt_mask))
volume = np.sum(gt_mask)
h_list.append(overlap/(volume+np.finfo(float).eps))
print("label {} overlap {} falses {} result {}".format(label, overlap,volume, overlap/(volume+np.finfo(float).eps)))
h = np.mean(h_list)
return h
def proportion(segmented_map, gt_map):
s_array = segmented_map.getEmMap().data()
gt_array = gt_map.getEmMap().data()
labels = np.unique(gt_array)
if s_array.shape != gt_array.shape:
return ValueError("Arrays must have same shape")
else:
p_list = []
count_labels = 0
for label in labels:
if label == 0:
continue
s_mask = s_array == label
gt_mask = gt_array == label
s_mask_non_background = s_array != 0
proportion_mask = gt_mask * s_mask_non_background
# need to check if should remove 0s
num_labels = len(np.unique(s_array[proportion_mask]))
p_list.append(num_labels)
count_labels +=1
print("label {} proportion {}".format(label, num_labels))
p = np.sum(p_list)/count_labels
return p
def consistency(segmented_map, gt_map):
s_array = segmented_map.getEmMap().data()
gt_array = gt_map.getEmMap().data()
labels = np.unique(gt_array)
if s_array.shape != gt_array.shape:
return ValueError("Arrays must have same shape")
else:
volumes_dict = {}
for label in labels:
if label == 0:
continue
s_mask = s_array == label
gt_mask = gt_array == label
volumes_dict[label] = np.sum(s_mask)
label = max(volumes_dict, key=volumes_dict.get)
gt_mask = gt_array == label
c = len(np.unique(s_array[gt_mask]))
return c
|
180abff5811182532ee07bfd44c920e1845d1f79
|
{
"blob_id": "180abff5811182532ee07bfd44c920e1845d1f79",
"branch_name": "refs/heads/master",
"committer_date": "2021-06-05T20:21:45",
"content_id": "1053671d2efb3bcbff0f12731c2f9a421bb4da2e",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "38453ed90ea825bda25e6fcdda05744eefda855e",
"extension": "py",
"filename": "metrics.py",
"fork_events_count": 0,
"gha_created_at": "2019-01-08T18:53:02",
"gha_event_created_at": "2023-01-07T18:31:01",
"gha_language": "PLpgSQL",
"gha_license_id": "Apache-2.0",
"github_id": 164712917,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7377,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/em/src/dataset/metrics.py",
"provenance": "stack-edu-0061.json.gz:570564",
"repo_name": "tecdatalab/biostructure",
"revision_date": "2021-06-05T20:21:45",
"revision_id": "a30e907e83fa5bbfb934d951b7c663b622104fcc",
"snapshot_id": "4b50f297932b2394d924e7de64f0d957f219dffd",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/tecdatalab/biostructure/a30e907e83fa5bbfb934d951b7c663b622104fcc/em/src/dataset/metrics.py",
"visit_date": "2023-08-31T00:32:08.694944",
"added": "2024-11-19T03:12:09.709491+00:00",
"created": "2021-06-05T20:21:45",
"int_score": 3,
"score": 2.625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0079.json.gz"
}
|
<?php
namespace App\Http\Controllers;
use App\Http\Requests\LoginRequest;
use App\Http\Requests\SignUpRequest;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AuthController extends Controller
{
//
protected $user;
public function __construct(User $user)
{
$this->user = $user;
}
public function getSignup()
{
return view('layout.signup');
}
public function signup(Signuprequest $request)
{
$user = $request->all();
$this->user->createUser($user);
// dd($user);
return redirect()->route('login')->with('key', 'Đăng ký thành công');
}
public function getLogin()
{
return view('layout.login');
}
public function login(LoginRequest $request)
{
if (Auth::attempt(['username' => $request->username, 'password' => $request->password])) {
// login thành công
// check xem user này thuộc cái nào. và chuyển hướng tới cái đó.
if (Auth::user()->user_type == 3) {
return redirect()->route('getuser')->with('key', 'Đăng nhập thành công');
}
elseif (Auth::user()->user_type == 2) {
return redirect()->route('listtopic')->with('key', 'Đăng nhập thành công');
}
elseif (Auth::user()->user_type == 1) {
return redirect()->route('gettopic')->with('key', 'Đăng nhập thành công');
}
} else {
return redirect()->route('login')->with('error', 'Sai username hoặc mật khẩu');
}
}
public function logout()
{
Auth::logout();
return redirect()->route('login');
}
}
|
9f50a46452849d7ab3d733e0613bc7eb67f99950
|
{
"blob_id": "9f50a46452849d7ab3d733e0613bc7eb67f99950",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-23T13:52:35",
"content_id": "a6344401f98ba9d39ee2053ab6e003acd2606ecd",
"detected_licenses": [
"MIT"
],
"directory_id": "87e51d4b338c13b7e56b63cdfded7ea280f0a196",
"extension": "php",
"filename": "AuthController.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 323913827,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 1766,
"license": "MIT",
"license_type": "permissive",
"path": "/app/Http/Controllers/AuthController.php",
"provenance": "stack-edu-0046.json.gz:449830",
"repo_name": "thanhtrung1999/projectregister",
"revision_date": "2020-12-23T13:52:35",
"revision_id": "90dd69d4b304e9229e245ef40e90f46c4d1c3db9",
"snapshot_id": "6efab33540e54a2040401949a8c3e229489976dc",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/thanhtrung1999/projectregister/90dd69d4b304e9229e245ef40e90f46c4d1c3db9/app/Http/Controllers/AuthController.php",
"visit_date": "2023-02-03T14:51:31.680395",
"added": "2024-11-19T00:43:34.717563+00:00",
"created": "2020-12-23T13:52:35",
"int_score": 3,
"score": 2.59375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0064.json.gz"
}
|
<?php
namespace realSamy\reBot\Abstracts;
/**
* This object represents a bot command.
*
* @property string $command text of the command, 1-32 characters. can contain only lowercase english letters,
* digits and underscores.
* @property string $description description of the command, 3-256 characters.
* @package realSamy\reBot\Abstracts
*/
abstract class BotCommand
{
}
|
4750c12e283c589d8a5abf84a00f4554d177b64e
|
{
"blob_id": "4750c12e283c589d8a5abf84a00f4554d177b64e",
"branch_name": "refs/heads/master",
"committer_date": "2021-01-01T14:03:52",
"content_id": "f172a54972ec6af49547195e451792442faae829",
"detected_licenses": [
"MIT"
],
"directory_id": "448a4fdb87cadf25b74c0c807d00391af1769ba3",
"extension": "php",
"filename": "BotCommand.php",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 325378206,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 405,
"license": "MIT",
"license_type": "permissive",
"path": "/src/reBot/Abstracts/BotCommand.php",
"provenance": "stack-edu-0052.json.gz:926936",
"repo_name": "realSamy/reBot",
"revision_date": "2021-01-01T14:03:52",
"revision_id": "da773e4230400b0f5411994d3cf1fcfe194bdaf9",
"snapshot_id": "1c30f5d2fe2cd269bb59ebb03c8349d498aa34c7",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/realSamy/reBot/da773e4230400b0f5411994d3cf1fcfe194bdaf9/src/reBot/Abstracts/BotCommand.php",
"visit_date": "2023-02-08T07:49:23.635490",
"added": "2024-11-19T01:09:36.098276+00:00",
"created": "2021-01-01T14:03:52",
"int_score": 3,
"score": 2.828125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0070.json.gz"
}
|
import os, os.path as op
import numpy as np
import cv2
import logging
from glob import glob
import shutil
import simplejson as json
from progressbar import progressbar
from pprint import pformat
from shuffler.backend import backend_db
from shuffler.backend import backend_media
from shuffler.utils import general as general_utils
def add_parsers(subparsers):
importCityscapesParser(subparsers)
exportCityscapesParser(subparsers)
def _importJson(c, jsonpath, imagefile, imheight, imwidth):
''' Imports one file with polygons of Cityscapes format. '''
with open(jsonpath) as f:
image_dict = json.load(f)
if image_dict['imgHeight'] != imheight or image_dict['imgWidth'] != imwidth:
raise Exception('Image size is inconsistent to json: %dx%d vs %dx%d' %
(image_dict['imgHeight'], image_dict['imgWidth'],
imheight, imwidth))
objects = image_dict['objects']
for object_ in objects:
name = object_['label']
polygon = object_['polygon']
x1 = np.min([point[0] for point in polygon])
y1 = np.min([point[1] for point in polygon])
x2 = np.max([point[0] for point in polygon])
y2 = np.max([point[1] for point in polygon])
width = x2 - x1
height = y2 - y1
c.execute(
'INSERT INTO objects(imagefile,x1,y1,width,height,name) '
'VALUES (?,?,?,?,?,?)', (imagefile, x1, y1, width, height, name))
objectid = c.lastrowid
for point in polygon:
s = 'INSERT INTO polygons(objectid,x,y) VALUES (?,?,?)'
c.execute(s, (objectid, point[0], point[1]))
def importCityscapesParser(subparsers):
parser = subparsers.add_parser(
'importCityscapes',
description='Import Cityscapes annotations into the database. '
'Images are assumed to be from leftImg8bit. For the CityScapes format, '
'please visit https://github.com/mcordts/cityscapesScripts.')
parser.set_defaults(func=importCityscapes)
parser.add_argument(
'--cityscapes_dir',
required=True,
help='Root directory of Cityscapes. It should contain subdirs '
'"gtFine_trainvaltest", "leftImg8bit_trainvaltest", etc.')
parser.add_argument(
'--type',
default='gtFine',
choices=['gtFine', 'gtCoarse'],
help='Which annotations to parse. '
'Will not parse both to keep the logic straightforward.')
parser.add_argument(
'--splits',
nargs='+',
default=['train', 'test', 'val'],
choices=['train', 'test', 'val', 'train_extra', 'demoVideo'],
help='Splits to be parsed.')
parser.add_argument('--mask_type',
choices=['labelIds', 'instanceIds', 'color'],
help='Which mask to import, if any.')
parser.add_argument('--display', action='store_true')
def importCityscapes(c, args):
if args.display:
imreader = backend_media.MediaReader(args.rootdir)
logging.info('Will load splits: %s', args.splits)
logging.info('Will load json type: %s', args.type)
logging.info('Will load mask type: %s', args.mask_type)
if not op.exists(args.cityscapes_dir):
raise Exception('Cityscape directory "%s" does not exist' %
args.cityscapes_dir)
# Directory accessed by label type and by split.
dirs_by_typesplit = {}
for type_ in [args.type, 'leftImg8bit']:
type_dir_template = op.join(args.cityscapes_dir, '%s*' % type_)
for type_dir in [x for x in glob(type_dir_template) if op.isdir(x)]:
logging.debug('Looking for splits in %s', type_dir)
for split in args.splits:
typesplit_dir = op.join(type_dir, split)
if op.exists(typesplit_dir):
logging.debug('Found split %s in %s', split, type_dir)
# Add the info into the main dictionary "dirs_by_typesplit".
if split not in dirs_by_typesplit:
dirs_by_typesplit[split] = {}
dirs_by_typesplit[split][type_] = typesplit_dir
logging.info('Found the following directories: \n%s',
pformat(dirs_by_typesplit))
for split in args.splits:
# List of cities.
assert 'leftImg8bit' in dirs_by_typesplit[split]
leftImg8bit_dir = dirs_by_typesplit[split]['leftImg8bit']
cities = os.listdir(leftImg8bit_dir)
cities = [x for x in cities if op.isdir(op.join(leftImg8bit_dir, x))]
logging.info('Found %d cities in %s', len(cities), leftImg8bit_dir)
for city in cities:
image_names = os.listdir(op.join(leftImg8bit_dir, city))
logging.info('In split "%s", city "%s" has %d images', split, city,
len(image_names))
for image_name in image_names:
# Get the image path.
image_path = op.join(leftImg8bit_dir, city, image_name)
name_parts = op.splitext(image_name)[0].split('_')
if len(name_parts) != 4:
raise Exception(
'Expect to have 4 parts in the name of image "%s"' %
image_name)
if name_parts[0] != city:
raise Exception('The first part of name of image "%s" '
'is expected to be city "%s".' %
(image_name, city))
if name_parts[3] != 'leftImg8bit':
raise Exception('The last part of name of image "%s" '
'is expected to be city "leftImg8bit".' %
image_name)
imheight, imwidth = backend_media.getPictureSize(image_path)
imagefile = op.relpath(image_path, args.rootdir)
c.execute(
'INSERT INTO images(imagefile,width,height) VALUES (?,?,?)',
(imagefile, imwidth, imheight))
# Get the json label.
if args.type in dirs_by_typesplit[split]:
city_dir = op.join(dirs_by_typesplit[split][args.type],
city)
if op.exists(city_dir):
json_name = '_'.join(name_parts[:3] +
[args.type, 'polygons']) + '.json'
json_path = op.join(city_dir, json_name)
if op.exists(json_path):
_importJson(c, json_path, imagefile, imheight,
imwidth)
if args.mask_type is not None:
mask_name = '_'.join(
name_parts[:3] +
[args.type, args.mask_type]) + '.png'
mask_path = op.join(city_dir, mask_name)
if op.exists(mask_path):
maskfile = op.relpath(mask_path, args.rootdir)
c.execute(
'UPDATE images SET maskfile=? WHERE imagefile=?',
(maskfile, imagefile))
if args.display:
img = imreader.imread(imagefile)
c.execute(
'SELECT objectid,name FROM objects WHERE imagefile=?',
(imagefile, ))
for objectid, name in c.fetchall():
# Draw polygon.
c.execute('SELECT y, x FROM polygons WHERE objectid=?',
(objectid, ))
polygon = c.fetchall()
general_utils.drawScoredPolygon(img, polygon, name)
cv2.imshow('importCityscapes', img[:, :, ::-1])
if cv2.waitKey(-1) == 27:
args.display = False
cv2.destroyWindow('importCityscapes')
# Statistics.
c.execute('SELECT COUNT(1) FROM images')
logging.info('Imported %d images', c.fetchone()[0])
c.execute('SELECT COUNT(1) FROM images WHERE maskfile IS NOT NULL')
logging.info('Imported %d masks', c.fetchone()[0])
c.execute('SELECT COUNT(DISTINCT(imagefile)) FROM objects')
logging.info('Objects are found in %d images', c.fetchone()[0])
def _makeLabelName(name, city, type_, was_imported_from_cityscapes):
'''
If a name is like {X}_{Y}_{Z}, then city_{Y}_type.
If a name is like {Y}, then city_{Y}_type.
'''
# Drop extension.
core = op.splitext(name)[0]
# Split into parts, and put them together with correct city and type.
if was_imported_from_cityscapes:
core_parts = core.split('_')
if len(core_parts) >= 3:
core = '_'.join(core_parts[1:-1])
out_name = '_'.join([city, core, type_])
logging.debug('Made name "%s" out of input name "%s".', out_name, name)
return out_name
def _exportLabel(c, out_path_noext, imagefile):
'''
Writes objects to json file.
Please use https://github.com/mcordts/cityscapesScripts to generate masks.
'''
c.execute('SELECT width,height FROM images WHERE imagefile=?',
(imagefile, ))
imgWidth, imgHeight = c.fetchone()
data = {'imgWidth': imgWidth, 'imgHeight': imgHeight, 'objects': []}
c.execute('SELECT * FROM objects WHERE imagefile=?', (imagefile, ))
for object_ in c.fetchall():
objectid = backend_db.objectField(object_, 'objectid')
name = backend_db.objectField(object_, 'name')
# Polygon = [[x1, y1], [x2, y2], ...].
# Check if the object has a polygon.
c.execute('SELECT x,y FROM polygons WHERE objectid=?', (objectid, ))
polygon = c.fetchall()
if len(polygon) == 0:
# If there is no polygon, make one from bounding box.
[y1, x1, y2, x2] = backend_db.objectField(object_, 'roi')
polygon = [(x1, y1), (x2, y1), (x2, y2), (x1, y2)]
color = (255, )
cv2.rectangle(mask, (x1, y1), (x2, y2), color, -1)
data['objects'].append({'label': name, 'polygon': polygon})
json_path = '%s_polygons.json' % out_path_noext
with open(json_path, 'w') as f:
json.dump(data, f, indent=4)
def exportCityscapesParser(subparsers):
parser = subparsers.add_parser(
'exportCityscapes',
description='Export the database into Cityscapes format. '
'Export to a single annotations <type>. Furthermore, export to a '
'single <split> and <city> or infer them from the folder structure. '
'If an object has no polygons, a rectangular polygon is generated from '
'its bounding box. To generate masks from polygons, use the official '
'tool from CityScapes: https://github.com/mcordts/cityscapesScripts')
parser.set_defaults(func=exportCityscapes)
parser.add_argument('--cityscapes_dir',
required=True,
help='Root directory of Cityscapes')
parser.add_argument(
'--image_type',
default='leftImg8bit',
help='If specified, images will be copied to that folder.'
'If NOT specified, images will not be exported in any way.')
parser.add_argument(
'--type',
default='gtFine',
help='Will use this type name. Cityscapes uses "gtFine", "gtCoarse".')
parser.add_argument(
'--split',
help='If specified, will use this split name. '
'Cityscapes uses "train", "val", "test". If NOT specified, will infer '
'from the grandparent directory of each imagefile.')
parser.add_argument(
'--city',
help='If specified, only that city will be used. If NOT specified, '
'will infer from the parent directory of each imagefile.')
parser.add_argument(
'--was_imported_from_cityscapes',
action='store_true',
help='"Imagefiles" with underscore are parsed as '
'{city}_{name}_{type}{ext}, '
'{City} and {type} are changed according to the export settings.')
def exportCityscapes(c, args):
c.execute('SELECT imagefile FROM images')
for imagefile, in progressbar(c.fetchall()):
# Parse the image name, city, and split.
imagename = op.basename(imagefile)
city = args.city if args.city is not None else op.basename(
op.dirname(imagefile))
split = args.split if args.split is not None else op.basename(
op.dirname(op.dirname(imagefile)))
logging.debug('Will write imagefile %s to split %s and city %s.',
imagefile, split, city)
out_name = _makeLabelName(imagename, city, args.type,
args.was_imported_from_cityscapes)
# Write image.
if args.image_type:
in_imagepath = op.join(args.rootdir, imagefile)
if not op.exists(in_imagepath):
raise Exception(
'Problem with the database: image does not exist at %s. '
'Check that imagefile refers to an image (not a video frame).'
% in_imagepath)
# TODO: do something if the input is video.
out_imagedir = op.join(args.cityscapes_dir, args.image_type, split,
city)
if not op.exists(out_imagedir):
os.makedirs(out_imagedir)
out_imagepath = op.join(out_imagedir, '%s.png' % out_name)
shutil.copyfile(in_imagepath, out_imagepath)
# TODO: do something if the inout is not png.
# Write label.
out_labeldir = op.join(args.cityscapes_dir, args.type, split, city)
if not op.exists(out_labeldir):
os.makedirs(out_labeldir)
out_path_noext = op.join(out_labeldir, out_name)
_exportLabel(c, out_path_noext, imagefile)
|
e604267143dcb0fdd7ca55185ad8c6be31b0decf
|
{
"blob_id": "e604267143dcb0fdd7ca55185ad8c6be31b0decf",
"branch_name": "refs/heads/master",
"committer_date": "2023-06-24T20:20:52",
"content_id": "eb77433022c6edcd361173f52368b21835f4eb9d",
"detected_licenses": [
"MIT"
],
"directory_id": "7a539354d327d8a17db160f231e6b74410c6f433",
"extension": "py",
"filename": "cityscapes.py",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 137785127,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 14081,
"license": "MIT",
"license_type": "permissive",
"path": "/shuffler/operations/datasets/cityscapes.py",
"provenance": "stack-edu-0063.json.gz:299796",
"repo_name": "kukuruza/shuffler",
"revision_date": "2023-06-24T20:20:52",
"revision_id": "af6ab60f299ef339408bd22151cf270a2da33997",
"snapshot_id": "431d44f0ac28092fa510083fea8c936c7c47f648",
"src_encoding": "UTF-8",
"star_events_count": 24,
"url": "https://raw.githubusercontent.com/kukuruza/shuffler/af6ab60f299ef339408bd22151cf270a2da33997/shuffler/operations/datasets/cityscapes.py",
"visit_date": "2023-07-17T15:06:43.199004",
"added": "2024-11-18T21:10:50.501970+00:00",
"created": "2023-06-24T20:20:52",
"int_score": 2,
"score": 2.328125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0081.json.gz"
}
|
<?php
/**
* Storage class for MySQL type.
*/
class Storage
{
var $db_link = 0;
/**
* Check content file to see if it exists, then save data.
* @param string $name Content area name.
* @param string $data Content area data.
*/
function ContentSave($name, $data)
{
$this->ContentCheck($name, "Edit Me!"); // Make sure database entry exists.
$this->db_link = @mysqli_connect(NC_DB_HOST, NC_DB_USER, NC_DB_PASSWORD);
$this->db_link = $this->DatabaseLink($this->db_link, NC_DB_DATABASE);
$db_result = mysqli_query($this->db_link, "UPDATE ".NC_DB_PREFIX."content SET content='".$this->EscapeString($this->db_link, $data)."' WHERE name='".$name."'");
if(!$db_result) // Check for query errors.
{
NCUtility::Error("MySQL reported: ".mysqli_error($this->db_link));
exit();
}
mysqli_close($this->db_link); // Close connection.
}
/**
* Check content file to see if it exists, if not, create it. Open it and return data.
* @param string $name Content area name.
* @return $data Data found in storage.
*/
function ContentLoad($name)
{
$this->ContentCheck($name, "Edit Me! (".$name.")"); // Make sure database entry exists.
$this->db_link = mysqli_connect(NC_DB_HOST, NC_DB_USER, NC_DB_PASSWORD);
$this->db_link = $this->DatabaseLink($this->db_link, NC_DB_DATABASE);
$db_result = mysqli_query($this->db_link, "SELECT name,content FROM ".NC_DB_PREFIX."content WHERE name='".$name."'");
if(!$db_result) // Check for query errors.
{
NCUtility::Error("MySQL reported: ".mysqli_error($this->db_link));
exit();
}
$row = mysqli_fetch_row($db_result);
$data = $row[1];
mysqli_close($this->db_link); // Close connection.
return $data;
}
/**
* USED INTERNALLY. Check content file to see if it exists. And if it doesn't, create it. $path contains the file path, $default contains the default text to go in the file if it is new.
* @param string $name Content area name.
*/
function ContentCheck($name, $default)
{
$create_entry = false;
$this->db_link = mysqli_connect(NC_DB_HOST, NC_DB_USER, NC_DB_PASSWORD);
$this->db_link = $this->DatabaseLink($this->db_link, NC_DB_DATABASE);
$db_result = mysqli_query($this->db_link, "SELECT name FROM ".NC_DB_PREFIX."content WHERE name='".$name."'");
if(!$db_result) // Check for query errors.
{
NCUtility::Error("MySQL reported: ".mysqli_error($this->db_link));
exit();
}
// See if a row exsists
if(mysqli_num_rows($db_result) < 1)
$create_entry = true;
mysqli_close($this->db_link); // Close connection.
if ($create_entry) // No entries existed. Create one instead.
{
$this->db_link = mysqli_connect(NC_DB_HOST, NC_DB_USER, NC_DB_PASSWORD);
$this->db_link = $this->DatabaseLink($this->db_link, NC_DB_DATABASE);
$db_result = mysqli_query($this->db_link, "INSERT INTO ".NC_DB_PREFIX."content (name,content) VALUES ('".$name."','".$default."')");
if(!$db_result) // Check for query errors.
{
NCUtility::Error("MySQL reported: ".mysqli_error($this->db_link));
exit();
}
mysqli_close($this->db_link); // Close connection.
}
}
/**
* USED INTERNALLY. Checks the validity of the mysql link. Selects the database. Returns the db link, presents any errors if any are found.
* @param string $name Content area name.
*/
function DatabaseLink($link, $_database)
{
if ($link)
{
if (mysqli_select_db($link, $_database))
return $link;
else
{
NCUtility::Error("MySQL reported: ".mysqli_error($link));
exit();
}
}
else
{
NCUtility::Error("MySQL reported: ".mysqli_error($link));
exit();
}
}
/**
* USED INTERNALLY. Escapes the string passed to it for secuirty.
* @param string $name Content area name.
*/
function EscapeString($link, $string)
{
if(get_magic_quotes_gpc())
$string = stripslashes($string); // Remove PHP magic quotes because we don't want to double-escape.
return mysqli_real_escape_string($link, $string);
}
}
|
5fa7d1b185a661daf91241daa5128f262d3c5cc2
|
{
"blob_id": "5fa7d1b185a661daf91241daa5128f262d3c5cc2",
"branch_name": "refs/heads/master",
"committer_date": "2023-02-12T11:51:25",
"content_id": "cd10f4a3e55220ec33723c5c944272219fe0234e",
"detected_licenses": [
"Zlib"
],
"directory_id": "0a9f74cca56902a398d32a35dbdb1b48d56d52ab",
"extension": "php",
"filename": "MySQL.php",
"fork_events_count": 0,
"gha_created_at": "2020-02-16T18:17:23",
"gha_event_created_at": "2020-02-22T10:47:32",
"gha_language": "PHP",
"gha_license_id": null,
"github_id": 240941479,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 3971,
"license": "Zlib",
"license_type": "permissive",
"path": "/nc-cms/system/lib/storage/MySQL.php",
"provenance": "stack-edu-0048.json.gz:573348",
"repo_name": "tirun/nc-cms",
"revision_date": "2023-02-12T11:51:25",
"revision_id": "09ad823dfe5ad101ed8e56063e32933b053ea6aa",
"snapshot_id": "27439c333605f95f6aa3a216052d1f910837f188",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/tirun/nc-cms/09ad823dfe5ad101ed8e56063e32933b053ea6aa/nc-cms/system/lib/storage/MySQL.php",
"visit_date": "2023-02-16T15:47:41.022936",
"added": "2024-11-18T21:01:15.901466+00:00",
"created": "2023-02-12T11:51:25",
"int_score": 3,
"score": 3.234375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0066.json.gz"
}
|
package ch.uzh.ifi.seal.soprafs20.repository;
import ch.uzh.ifi.seal.soprafs20.constant.GameStatus;
import ch.uzh.ifi.seal.soprafs20.entity.Game;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import static org.junit.jupiter.api.Assertions.*;
@DataJpaTest
public class GameRepositoryIntegrationTest {
@Qualifier("gameRepository")
@Autowired
private GameRepository gameRepository;
@Test
public void findByGameId_success() {
// given
Game game = new Game();
game.setGameId(1L);
game.setGameStatus(GameStatus.WAITING);
game.setIsWhiteTurn(true);
// save game in database
gameRepository.save(game);
gameRepository.flush();
// when
Game found = gameRepository.findByGameId(game.getGameId());
// then
assertNotNull(found.getGameId());
assertEquals(game.getGameStatus(), GameStatus.WAITING);
assertTrue(game.getIsWhiteTurn());
}
}
|
05689ca6b7f436ae4d267182503b59cbaf9d798f
|
{
"blob_id": "05689ca6b7f436ae4d267182503b59cbaf9d798f",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-24T19:56:46",
"content_id": "9baa568b81f0de7a45f800f3e14537b3015b9e33",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "b3a15759f1538975c4c52e7a8bede9af078a4dfc",
"extension": "java",
"filename": "GameRepositoryIntegrationTest.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 248264368,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1154,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/test/java/ch/uzh/ifi/seal/soprafs20/repository/GameRepositoryIntegrationTest.java",
"provenance": "stack-edu-0021.json.gz:9936",
"repo_name": "sopra-fs20-group02/sopra-fs20-group02-server",
"revision_date": "2020-05-24T19:56:46",
"revision_id": "cfa011ec626f4daa0e8c71078e5be8c79c4be521",
"snapshot_id": "ef084cfda78643ca32789cb4b1c1bf60cbd8f22e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/sopra-fs20-group02/sopra-fs20-group02-server/cfa011ec626f4daa0e8c71078e5be8c79c4be521/src/test/java/ch/uzh/ifi/seal/soprafs20/repository/GameRepositoryIntegrationTest.java",
"visit_date": "2021-04-02T10:35:25.706499",
"added": "2024-11-18T22:42:16.637525+00:00",
"created": "2020-05-24T19:56:46",
"int_score": 2,
"score": 2.328125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0039.json.gz"
}
|
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Knowledgebase.Models;
using Knowledgebase.Models.Thread;
namespace Knowledgebase.Api.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class ThreadsController : ControllerBase
{
private readonly Application.Services.ThreadService _threadService;
public ThreadsController(
Application.Services.ThreadService threadService)
{
_threadService = threadService;
}
[HttpGet]
public IActionResult GetThreads(Guid? category_id, Guid? tag_id, string keyword)
{
var data = _threadService.GetAll(new ThreadSearch
{
TagId = tag_id,
CategoryId = category_id,
Keyword = keyword
});
return Ok(data);
}
[HttpGet("{id}")]
public IActionResult GetSingleThread(Guid id)
{
var data = _threadService.GetDetails(id);
return Ok(data);
}
[HttpPost]
[Filters.Transactional]
public IActionResult CreateThread([FromBody] ThreadCreate input)
{
var result = _threadService.Create(input);
return Ok(result);
}
[HttpPut]
[Filters.Transactional]
public IActionResult UpdateThread([FromBody] ThreadUpdate input)
{
_threadService.UpdateThread(input);
return Ok();
}
[HttpPut("title")]
[Filters.Transactional]
public IActionResult UpdateThreadTitle([FromBody] ThreadUpdateTitle input)
{
_threadService.UpdateThreadTitle(input);
return Ok();
}
[HttpPut("tags")]
[Filters.Transactional]
public IActionResult UpdateThreadTags([FromBody] ThreadUpdateTags input)
{
_threadService.UpdateThreadTags(input);
return Ok();
}
[HttpPut("contents")]
[Filters.Transactional]
public IActionResult UpdateThreadContents([FromBody] ThreadUpdateContents input)
{
var result = _threadService.UpdateThreadContents(input);
return Ok(result);
}
[HttpDelete("{id}")]
[Filters.Transactional]
public IActionResult DeleteThread(Guid id)
{
_threadService.DeleteThread(id);
return Ok();
}
[HttpGet("{thread_id}/contents")]
public IActionResult GetContentsOfThread(Guid thread_id)
{
var data = _threadService.GetAllContents(thread_id);
return Ok(data);
}
[HttpGet("contents/{content_id}")]
public IActionResult GetContentDetails(Guid content_id)
{
var data = _threadService.GetContent(content_id);
return Ok(data);
}
[HttpGet("tags")]
public IActionResult GetAllTags()
{
var result = _threadService.GetAllTags();
return Ok(result);
}
}
}
|
3d04d7b1f3a8ef7e762ba8d821e41b8a25e53e3a
|
{
"blob_id": "3d04d7b1f3a8ef7e762ba8d821e41b8a25e53e3a",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-06T17:30:35",
"content_id": "182867056e9fbc55020a49af2fea660336461f3e",
"detected_licenses": [
"MIT"
],
"directory_id": "e24e85b1ecf82028116a8f072c2ef8467922110d",
"extension": "cs",
"filename": "ThreadsController.cs",
"fork_events_count": 0,
"gha_created_at": "2020-07-19T08:32:45",
"gha_event_created_at": "2020-08-03T13:20:34",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 280824492,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 3132,
"license": "MIT",
"license_type": "permissive",
"path": "/src/Knowledgebase.Api/Controllers/ThreadsController.cs",
"provenance": "stack-edu-0011.json.gz:171065",
"repo_name": "deploca/knowledgebase",
"revision_date": "2020-08-06T17:30:35",
"revision_id": "990f192026d44bee7147d0076e6cee2eef406b0b",
"snapshot_id": "8c17b7d1baf0eb69711fdbe742839e09d4cf359e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/deploca/knowledgebase/990f192026d44bee7147d0076e6cee2eef406b0b/src/Knowledgebase.Api/Controllers/ThreadsController.cs",
"visit_date": "2022-11-26T05:57:05.185084",
"added": "2024-11-19T02:14:20.163708+00:00",
"created": "2020-08-06T17:30:35",
"int_score": 2,
"score": 2.40625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0029.json.gz"
}
|
/* eslint-disable no-param-reassign */
import * as t from '../constants/MutationTypes';
const mutations = {
[t.CHANGE_GRADE](state, payload) {
state.grades.splice(payload.index, 1, payload.grade);
},
[t.CHANGE_DESIRED_GRADE](state, payload) {
state.desiredGrade = payload.grade;
},
[t.CHANGE_WEIGHT](state, payload) {
state.weights.splice(payload.index, 1, payload.weight);
},
};
export default mutations;
|
fa6d9fa4913b4314ff630fdcc47274df3ce66568
|
{
"blob_id": "fa6d9fa4913b4314ff630fdcc47274df3ce66568",
"branch_name": "refs/heads/master",
"committer_date": "2017-01-01T18:39:23",
"content_id": "59fa0e9e0dd9a74a78d043263eb5771d76e3bfd6",
"detected_licenses": [
"MIT"
],
"directory_id": "86f4d2456deb2470e4885f6ea7aeaf1b8c627e85",
"extension": "js",
"filename": "mutations.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 77647424,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 432,
"license": "MIT",
"license_type": "permissive",
"path": "/src/store/mutations.js",
"provenance": "stack-edu-0033.json.gz:591956",
"repo_name": "nathanhleung/vue-gradecalculator",
"revision_date": "2017-01-01T18:39:23",
"revision_id": "493f507031201179f2148b6f336ff9e030fc96ac",
"snapshot_id": "de24bcf9724785dbe397c7c931d2f64c921caa96",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/nathanhleung/vue-gradecalculator/493f507031201179f2148b6f336ff9e030fc96ac/src/store/mutations.js",
"visit_date": "2021-01-13T03:11:27.208311",
"added": "2024-11-19T00:07:39.124508+00:00",
"created": "2017-01-01T18:39:23",
"int_score": 2,
"score": 2.1875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0051.json.gz"
}
|
//
// Tools.swift
// ClogAmpSwift
//
// Created by Roessel, Pascal on 13.02.19.
// Copyright © 2019 Pascal Roessel. All rights reserved.
//
import Foundation
public func delayWithSeconds(_ seconds: Double, closure: @escaping () -> ()) {
DispatchQueue.main.asyncAfter(deadline: .now() + seconds, qos: .userInitiated) {
closure()
}
}
|
5f09ee2c20085316fe1e4d5c73fd9db6274cacd2
|
{
"blob_id": "5f09ee2c20085316fe1e4d5c73fd9db6274cacd2",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-19T13:27:26",
"content_id": "f761a2ba5454a3434d0ce39d6df5557183302fbf",
"detected_licenses": [
"MIT"
],
"directory_id": "c41b60a6c87f4f4ab214a4def82b89a26f3018c7",
"extension": "swift",
"filename": "Tools.swift",
"fork_events_count": 1,
"gha_created_at": "2018-04-13T06:31:44",
"gha_event_created_at": "2019-11-19T13:53:41",
"gha_language": "Swift",
"gha_license_id": "MIT",
"github_id": 129358851,
"is_generated": false,
"is_vendor": false,
"language": "Swift",
"length_bytes": 355,
"license": "MIT",
"license_type": "permissive",
"path": "/ClogAmpSwift/Utils/Tools.swift",
"provenance": "stack-edu-0072.json.gz:138261",
"repo_name": "lunk22/ClogAmpSwift",
"revision_date": "2023-07-19T12:49:31",
"revision_id": "2ce4e36c40df055e198e6b0160767719485243b0",
"snapshot_id": "8311574b530876fd1249a5e19364b4fd682046cf",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/lunk22/ClogAmpSwift/2ce4e36c40df055e198e6b0160767719485243b0/ClogAmpSwift/Utils/Tools.swift",
"visit_date": "2023-07-21T11:10:58.366446",
"added": "2024-11-19T02:38:07.581051+00:00",
"created": "2023-07-19T12:49:31",
"int_score": 2,
"score": 2.5,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0090.json.gz"
}
|
<?php
namespace App\Vehicle\Domain;
interface VehicleInterface
{
public function getId(): string;
public function getManufacturer(): string;
public function getModel(): string;
}
|
100573bb87258541417f518ef60013428340cc2f
|
{
"blob_id": "100573bb87258541417f518ef60013428340cc2f",
"branch_name": "refs/heads/master",
"committer_date": "2023-02-23T20:28:06",
"content_id": "5a05b9fca413c42d06663453f85d1b2f7021956a",
"detected_licenses": [
"MIT"
],
"directory_id": "65f55851117f72227f00ac86fec6709af00cd254",
"extension": "php",
"filename": "VehicleInterface.php",
"fork_events_count": 5,
"gha_created_at": "2018-05-10T12:58:16",
"gha_event_created_at": "2023-04-19T21:25:10",
"gha_language": "PHP",
"gha_license_id": "MIT",
"github_id": 132900635,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 195,
"license": "MIT",
"license_type": "permissive",
"path": "/src/Vehicle/Domain/VehicleInterface.php",
"provenance": "stack-edu-0048.json.gz:90146",
"repo_name": "Samffy/graphql-poc",
"revision_date": "2023-02-23T20:28:06",
"revision_id": "d62cd064badac64d529acf715dcb500edf9691f9",
"snapshot_id": "9cbffb3a86cb69397d2e4189a49767fd9b148283",
"src_encoding": "UTF-8",
"star_events_count": 22,
"url": "https://raw.githubusercontent.com/Samffy/graphql-poc/d62cd064badac64d529acf715dcb500edf9691f9/src/Vehicle/Domain/VehicleInterface.php",
"visit_date": "2023-05-04T00:32:12.970024",
"added": "2024-11-18T21:53:47.626576+00:00",
"created": "2023-02-23T20:28:06",
"int_score": 3,
"score": 2.828125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0066.json.gz"
}
|
<?php
declare(strict_types=1);
namespace EonX\EasyDoctrine\Events;
interface EntityActionEventInterface
{
/**
* @return array<string, mixed>
*/
public function getChangeSet(): array;
public function getEntity(): object;
}
|
f9dda65fca45c2dca98175205f83d8084b848145
|
{
"blob_id": "f9dda65fca45c2dca98175205f83d8084b848145",
"branch_name": "refs/heads/master",
"committer_date": "2022-10-27T23:58:22",
"content_id": "bff6bb68b291a889647b4528086b0130685aec02",
"detected_licenses": [
"MIT"
],
"directory_id": "ea39c7b4f0c8db5d34787b781c4242db07abdf4c",
"extension": "php",
"filename": "EntityActionEventInterface.php",
"fork_events_count": 0,
"gha_created_at": "2020-03-04T01:46:51",
"gha_event_created_at": "2020-03-04T01:46:52",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 244782947,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 248,
"license": "MIT",
"license_type": "permissive",
"path": "/packages/EasyDoctrine/src/Events/EntityActionEventInterface.php",
"provenance": "stack-edu-0047.json.gz:201774",
"repo_name": "dextercampos/easy-monorepo",
"revision_date": "2022-10-27T23:58:22",
"revision_id": "bbd61b5a4123a27335cd6550b84efe79160bcbeb",
"snapshot_id": "df5ed27a75edb478cf499e12e93852d46c6381e3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dextercampos/easy-monorepo/bbd61b5a4123a27335cd6550b84efe79160bcbeb/packages/EasyDoctrine/src/Events/EntityActionEventInterface.php",
"visit_date": "2022-11-13T15:33:54.799219",
"added": "2024-11-18T20:57:08.289524+00:00",
"created": "2022-10-27T23:58:22",
"int_score": 2,
"score": 2.25,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0065.json.gz"
}
|
import numpy as np
from typing import List, Optional, Dict, Tuple
from camera.image_recognition import Point, PolarPoint
try:
dataclass # python 3.7.1
except:
from dataclasses import dataclass
class StreamingMovingAverage:
def __init__(self, window_size):
self.window_size = window_size
self.values = []
self.sum = 0
def __call__(self, value):
if np.isnan(value):
return value
self.values.append(value)
self.sum += value
if len(self.values) > self.window_size:
self.sum -= self.values.pop(0)
return float(self.sum) / len(self.values)
Centimeter = float
@dataclass
class RecognitionState:
"""Class for keeping track of the recognition state."""
balls: List[PolarPoint] = list
goal_yellow: Optional[PolarPoint] = None
goal_blue: Optional[PolarPoint] = None
closest_edge: Optional[PolarPoint] = None
angle_adjust: float = None
h_bigger: int = None
h_smaller: int = None
field_contours: List[Tuple[int, int, int, int]] = None
goal_yellow_rect: List[Tuple[int, int, int, int]] = None
goal_blue_rect: List[Tuple[int, int, int, int]] = None
@staticmethod # for some reason type analysis didn't work for classmethod
def from_dict(packet: dict) -> 'RecognitionState':
balls: List[PolarPoint] = [PolarPoint(**b) for b in packet.get('balls', [])]
goal_yellow: Optional[PolarPoint] = packet.get('goal_yellow') and PolarPoint(**packet['goal_yellow'])
goal_blue: Optional[PolarPoint] = packet.get('goal_blue') and PolarPoint(**packet['goal_blue'])
closest_edge: Optional[PolarPoint] = packet.get('closest_edge') and PolarPoint(**packet['closest_edge'])
angle_adjust, h_bigger, h_smaller = packet.get('goal_angle_adjust', [None, None, None])
field_contours = packet.get('field_contours', [])
goal_yellow_rect = packet.get('goal_yellow_rect', [])
goal_blue_rect = packet.get('goal_blue_rect', [])
return RecognitionState(
balls, goal_yellow, goal_blue, closest_edge, angle_adjust, h_bigger, h_smaller,
field_contours, goal_yellow_rect, goal_blue_rect)
|
46e99476198c8a82b5d05d470577f3fa43efe94b
|
{
"blob_id": "46e99476198c8a82b5d05d470577f3fa43efe94b",
"branch_name": "refs/heads/master",
"committer_date": "2019-12-01T02:32:09",
"content_id": "e0d1ef0e794d8aed1da2cbe7d07502d9a99af8c6",
"detected_licenses": [
"MIT"
],
"directory_id": "a195ccf86fc3cf401c5993071d28588a01f959ab",
"extension": "py",
"filename": "utils.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2201,
"license": "MIT",
"license_type": "permissive",
"path": "/khajiit/utils.py",
"provenance": "stack-edu-0060.json.gz:269747",
"repo_name": "vegetablejuiceftw/zoidberg",
"revision_date": "2019-12-01T02:32:09",
"revision_id": "46eaef75db7caac95a6c0089f04c720fd1936e5b",
"snapshot_id": "4a1a3f9842ece51a2c7d785254c45c346dbdde5c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/vegetablejuiceftw/zoidberg/46eaef75db7caac95a6c0089f04c720fd1936e5b/khajiit/utils.py",
"visit_date": "2021-01-08T01:08:35.772584",
"added": "2024-11-19T00:36:47.302657+00:00",
"created": "2019-12-01T02:32:09",
"int_score": 3,
"score": 2.640625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0078.json.gz"
}
|
$(document)
.ready(function() {
var height = $(window)
.height() - 57;
$(".selected")
.css("color", "white");
$(".codecontainer")
.css("height", height + "px");
$(".selector")
.click(function() {
$(this)
.toggleClass("selected");
var id = $(this)
.attr("name");
var clase = $(this)
.attr("class");
if (clase == "selector selected") {
$(this)
.css("color", "white");
} else {
$(this)
.css("color", "transparent");
}
if (id == "html" && clase == "selector selected") {
$(this)
.css("background-color", "#E44D26");
} else if (id == "css" && clase == "selector selected") {
$(this)
.css("background-color", "#379AD6");
} else if (id == "js" && clase == "selector selected") {
$(this)
.css("background-color", "#F0DB4F");
} else if (id == "result" && clase == "selector selected") {
$(this)
.css("background-color", "green");
} else {
$(this)
.css("background-color", "grey");
}
$("#" + id + "Container")
.toggle();
var number = $('.codecontainer')
.filter(function() {
return $(this)
.css('display') !== 'none';
})
.length;
var width = 100 / number;
$(".codecontainer")
.css("width", width + "%");
//show codemirror windows already at line #1.
htmlCodeMirror.refresh();
cssCodeMirror.refresh();
jsCodeMirror.refresh();
});
//Setup codemirror editors
$("#run")
.click(function() {
$('#resultFrame')
.contents()
.find('html')
.html("<style>" + cssCodeMirror.getValue() + "</style>" + htmlCodeMirror.getValue());
document.getElementById('resultFrame')
.contentWindow.eval(jsCodeMirror.getValue());
});
$("#htmlClear").click(function() {
htmlCodeMirror.setValue("");
});
$("#cssClear").click(function() {
cssCodeMirror.setValue("");
});
$("#jsClear").click(function() {
jsCodeMirror.setValue("");
});
//Asks user if he really wants to leave when refreshing or backspacing
window.onbeforeunload = function() {
return "";
};
});
|
86f99abacfa06a51b9362a08bbbbf83a8f8ebd37
|
{
"blob_id": "86f99abacfa06a51b9362a08bbbbf83a8f8ebd37",
"branch_name": "refs/heads/master",
"committer_date": "2017-05-14T07:27:09",
"content_id": "dcf72858c03fdee735d3a4b419adc0785375aabf",
"detected_licenses": [
"MIT"
],
"directory_id": "5a04737bdd91f128ec1a92652c6e5609bebc346d",
"extension": "js",
"filename": "script.js",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 90172398,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 2142,
"license": "MIT",
"license_type": "permissive",
"path": "/javascript/script.js",
"provenance": "stack-edu-0033.json.gz:570290",
"repo_name": "OscarAD/CodeFiddle",
"revision_date": "2017-05-14T07:27:09",
"revision_id": "3262dddf8623051bf4fb3a2906158347aab97da2",
"snapshot_id": "f3104af7ba21f9e0d922dabf1db25a4a152974a1",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/OscarAD/CodeFiddle/3262dddf8623051bf4fb3a2906158347aab97da2/javascript/script.js",
"visit_date": "2021-01-20T08:38:13.187654",
"added": "2024-11-19T01:41:54.777590+00:00",
"created": "2017-05-14T07:27:09",
"int_score": 2,
"score": 2.375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0051.json.gz"
}
|
import React, { Component } from 'react';
import { Text, StyleSheet, View } from 'react-native';
import { colors } from '../utils';
const styles = StyleSheet.create({
container: {
borderRadius: 8,
backgroundColor: colors.WHITE,
paddingVertical: 5,
paddingHorizontal: 10,
marginTop: 5,
marginRight: 5,
elevation: 3,
shadowColor: colors.SHADOW,
shadowOffset: { width: 2, height: 2 },
shadowOpacity: 0.8,
shadowRadius: 2,
},
title: {
fontWeight: 'bold',
},
text: {
fontSize: 15,
textAlign: 'right',
},
});
class AssetInfoBox extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.title}>{this.props.title}</Text>
<Text style={styles.text}>
{this.props.text}
{this.props.children}
</Text>
</View>
);
}
}
export default AssetInfoBox;
|
968fbe9c5bbe9b81a9d6f297ecd6ba13187f5249
|
{
"blob_id": "968fbe9c5bbe9b81a9d6f297ecd6ba13187f5249",
"branch_name": "refs/heads/master",
"committer_date": "2019-06-17T23:41:32",
"content_id": "a3fa7d79c0d19d4e31a36c9f56850884720509d2",
"detected_licenses": [
"MIT"
],
"directory_id": "9d9dce4fe3b905d8e6bd1f3c7229725179658f70",
"extension": "js",
"filename": "AssetInfoBox.js",
"fork_events_count": 1,
"gha_created_at": "2019-08-07T09:00:32",
"gha_event_created_at": "2019-08-07T09:00:32",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 201012952,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 905,
"license": "MIT",
"license_type": "permissive",
"path": "/src/components/AssetInfoBox.js",
"provenance": "stack-edu-0045.json.gz:208632",
"repo_name": "wepobid/personal-cryptofolio",
"revision_date": "2019-06-17T23:41:32",
"revision_id": "6733236e2031d76eb50febb0fcd15ddc7fafd1e3",
"snapshot_id": "ffeafe3ce0cd94539e5f39f15db1529cdab4fb69",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/wepobid/personal-cryptofolio/6733236e2031d76eb50febb0fcd15ddc7fafd1e3/src/components/AssetInfoBox.js",
"visit_date": "2020-07-01T01:53:41.309881",
"added": "2024-11-19T00:11:55.783713+00:00",
"created": "2019-06-17T23:41:32",
"int_score": 2,
"score": 2.234375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0063.json.gz"
}
|
import { calculateVectorArea } from './calculateVectorArea';
import { createVector } from './createVector';
describe('calculateVectorArea', () => {
it('the area of 2,3 should be 6', () => {
expect(calculateVectorArea(createVector(2, 3))).toBe(6);
});
});
|
86fc581aee6e6a16b6223f194fb038adb4f139fb
|
{
"blob_id": "86fc581aee6e6a16b6223f194fb038adb4f139fb",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-05T01:14:56",
"content_id": "d53214cf63a861bd8cd610c69edd46b906c09d79",
"detected_licenses": [
"MIT"
],
"directory_id": "0a648f8f5a6e1950e304d969f9df2374c1505af8",
"extension": "ts",
"filename": "calculateVectorArea.test.ts",
"fork_events_count": 0,
"gha_created_at": "2019-06-27T22:18:31",
"gha_event_created_at": "2023-01-04T01:17:49",
"gha_language": "TypeScript",
"gha_license_id": "MIT",
"github_id": 194170093,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 264,
"license": "MIT",
"license_type": "permissive",
"path": "/src/vector/calculateVectorArea.test.ts",
"provenance": "stack-edu-0073.json.gz:979356",
"repo_name": "jedster1111/simple-vectors",
"revision_date": "2020-04-05T00:06:48",
"revision_id": "b166cf17f02375f51806fa256ab3a17cf3fc84a3",
"snapshot_id": "fcc138ff2e410023c6ba0b261e385e9737d5ae68",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jedster1111/simple-vectors/b166cf17f02375f51806fa256ab3a17cf3fc84a3/src/vector/calculateVectorArea.test.ts",
"visit_date": "2023-01-08T07:27:55.585037",
"added": "2024-11-18T23:40:01.820121+00:00",
"created": "2020-04-05T00:06:48",
"int_score": 2,
"score": 2.125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0091.json.gz"
}
|
package com.herb2sy.lib.exception;
public class EncryptionException extends Exception {
public EncryptionException() {
}
public EncryptionException(String message) {
super(message);
}
}
|
9622afcddb53bbf84de075aaadd41dab6f55ecaa
|
{
"blob_id": "9622afcddb53bbf84de075aaadd41dab6f55ecaa",
"branch_name": "refs/heads/master",
"committer_date": "2019-08-03T13:41:31",
"content_id": "7505cf0158bdeb2d665d2c0ae9b102c867a3dc56",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "76c9b202168242712c4e412e17217e69dfe7482c",
"extension": "java",
"filename": "EncryptionException.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 192110217,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 212,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/lib/src/main/java/com/herb2sy/lib/exception/EncryptionException.java",
"provenance": "stack-edu-0020.json.gz:353355",
"repo_name": "HerbLee/kotlin_android",
"revision_date": "2019-08-03T13:41:31",
"revision_id": "fb64658ddce19219236e2177e9d6da46fe6d65a3",
"snapshot_id": "7b8ce852b27561b0b6103b202c63586d1d8971b2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/HerbLee/kotlin_android/fb64658ddce19219236e2177e9d6da46fe6d65a3/lib/src/main/java/com/herb2sy/lib/exception/EncryptionException.java",
"visit_date": "2020-06-04T17:06:13.328247",
"added": "2024-11-18T22:43:43.019136+00:00",
"created": "2019-08-03T13:41:31",
"int_score": 2,
"score": 2.0625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0038.json.gz"
}
|
# Futu Algo: Algorithmic High-Frequency Trading Framework
#
# 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.
#
# Written by Bill Chan <billpwchan@hotmail.com>, 2021
# Copyright (c) billpwchan - All Rights Reserved
import pandas as pd
from filters.Filters import Filters
class TripleCross(Filters):
def __init__(self, ma_period1: int = 5, ma_period2: int = 10, ma_period3: int = 20):
self.MA_PERIOD1 = ma_period1
self.MA_PERIOD2 = ma_period2
self.MA_PERIOD3 = ma_period3
super().__init__()
def validate(self, input_data: pd.DataFrame, info_data: dict) -> bool:
"""
:param input_data: Yahoo Finance Quantitative Data (Price, Volume, etc.)
:param info_data: Yahoo Finance Fundamental Data (Company Description. PE Ratio, Etc.)
:return:
"""
if input_data.empty or input_data.shape[0] < 20:
return False
input_data['MA_1'] = input_data['close'].rolling(window=self.MA_PERIOD1).mean()
input_data['MA_2'] = input_data['close'].rolling(window=self.MA_PERIOD2).mean()
input_data['MA_3'] = input_data['close'].rolling(window=self.MA_PERIOD3).mean()
current_record = input_data.iloc[-1]
previous_record = input_data.iloc[-2]
criterion_1 = current_record['volume'] > input_data.iloc[-10:]['volume'].max()
criterion_2 = max([current_record['MA_1'], current_record['MA_2'], current_record['MA_3']]) / \
min([current_record['MA_1'], current_record['MA_2'], current_record['MA_3']]) < 1.01
criterion_3 = current_record['close'] > current_record['MA_1'] and \
current_record['close'] > current_record['MA_2'] and \
current_record['close'] > current_record['MA_3']
criterion_4 = previous_record['close'] < previous_record['MA_1'] and \
previous_record['close'] < previous_record['MA_2'] and \
previous_record['close'] < previous_record['MA_3']
criteria = [criterion_1, criterion_2, criterion_3, criterion_4]
return all(criterion for criterion in criteria)
|
28b2e5e7e6e50bd96a34c310f3013723968d43c1
|
{
"blob_id": "28b2e5e7e6e50bd96a34c310f3013723968d43c1",
"branch_name": "refs/heads/master",
"committer_date": "2021-10-21T18:34:22",
"content_id": "8903f82ab198b62e4bf920122d13aa1dddda59bb",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "9d5e3599b633a79f32725c453677ef367ca8dbff",
"extension": "py",
"filename": "Triple_Cross.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2655,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/filters/Triple_Cross.py",
"provenance": "stack-edu-0060.json.gz:78659",
"repo_name": "eaglepix/futu_algo",
"revision_date": "2021-10-21T18:34:22",
"revision_id": "bc4a8b9e56cff8ac1add9a2cd309ee568ca9b2dc",
"snapshot_id": "bb8cac22d07626e5029df3aa623fb58da67f4ac0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/eaglepix/futu_algo/bc4a8b9e56cff8ac1add9a2cd309ee568ca9b2dc/filters/Triple_Cross.py",
"visit_date": "2023-08-31T06:33:05.534841",
"added": "2024-11-18T21:52:09.023927+00:00",
"created": "2021-10-21T18:34:22",
"int_score": 3,
"score": 2.703125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0078.json.gz"
}
|
/*
* Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.identity.sts.passive.custom.handler;
import org.apache.cxf.rt.security.claims.Claim;
import org.apache.cxf.rt.security.claims.ClaimCollection;
import org.apache.cxf.sts.claims.ClaimsHandler;
import org.apache.cxf.sts.claims.ClaimsParameters;
import org.apache.cxf.sts.claims.ProcessedClaim;
import org.apache.cxf.sts.claims.ProcessedClaimCollection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* A custom ClaimsHandler implementation to be used in the implementation.
*/
public class CustomClaimsHandler implements ClaimsHandler {
private static List<String> knownURIs = new ArrayList<>();
private HashMap<String, String> requestedClaims = new HashMap<>();
/**
* Create a processed claim collection using the claim values and params provided.
*
* @param claims The unprocessed claims.
* @param parameters The claim parameters.
* @return The processed claims.
*/
public ProcessedClaimCollection retrieveClaimValues(
ClaimCollection claims, ClaimsParameters parameters) {
if (claims != null && !claims.isEmpty()) {
ProcessedClaimCollection claimCollection = new ProcessedClaimCollection();
for (Claim requestClaim : claims) {
ProcessedClaim claim = new ProcessedClaim();
claim.setClaimType(requestClaim.getClaimType());
if (knownURIs.contains(requestClaim.getClaimType()) &&
requestedClaims.containsKey(requestClaim.getClaimType())) {
claim.addValue(requestedClaims.get(requestClaim.getClaimType()));
}
claimCollection.add(claim);
}
return claimCollection;
}
return null;
}
/**
* Get the list of supported claim URIs.
*
* @return List of supported claim URIs.
*/
public List<String> getSupportedClaimTypes() {
return knownURIs;
}
/**
* Set the list of supported claim URIs.
*
* @param knownURIs New list to be set as the known URIs.
*/
public static void setKnownURIs(List<String> knownURIs) {
CustomClaimsHandler.knownURIs = knownURIs;
}
/**
* Get claim URIs and values in the form of a HashMap.
*
* @return HashMap containing the claim URIs and values.
*/
public HashMap<String, String> getRequestedClaims() {
return requestedClaims;
}
/**
* Set claim key value pair(the URI and value).
*
* @param requestedClaims The new HashMap of claims key value pair.
*/
public void setRequestedClaims(HashMap<String, String> requestedClaims) {
this.requestedClaims = requestedClaims;
}
}
|
686e44ae7d05d42682fa306de6ebc2dbd2928211
|
{
"blob_id": "686e44ae7d05d42682fa306de6ebc2dbd2928211",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-22T06:29:06",
"content_id": "86336ae88ea94806345d971e2eb80a0b84ef9cbc",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "fa604017fb71006cd00863fd05f8008fd01e9149",
"extension": "java",
"filename": "CustomClaimsHandler.java",
"fork_events_count": 78,
"gha_created_at": "2016-02-29T02:51:28",
"gha_event_created_at": "2023-09-04T09:47:28",
"gha_language": "Java",
"gha_license_id": "Apache-2.0",
"github_id": 52759259,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 3414,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/components/org.wso2.carbon.identity.sts.passive/src/main/java/org/wso2/carbon/identity/sts/passive/custom/handler/CustomClaimsHandler.java",
"provenance": "stack-edu-0024.json.gz:753920",
"repo_name": "wso2-extensions/identity-inbound-auth-sts",
"revision_date": "2023-08-22T06:29:06",
"revision_id": "dd4c399d98319a3a712e18d22f2c87b183947127",
"snapshot_id": "3d59e5a42598e70c9d20d88e6ff81c1cfb5e63ad",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/wso2-extensions/identity-inbound-auth-sts/dd4c399d98319a3a712e18d22f2c87b183947127/components/org.wso2.carbon.identity.sts.passive/src/main/java/org/wso2/carbon/identity/sts/passive/custom/handler/CustomClaimsHandler.java",
"visit_date": "2023-08-30T22:10:13.376689",
"added": "2024-11-19T00:12:52.342657+00:00",
"created": "2023-08-22T06:29:06",
"int_score": 2,
"score": 2.078125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0042.json.gz"
}
|
<?php
namespace App\Http\Controllers;
use App\Appointment;
use App\Doctor;
use App\Patient;
use App\WorkingHour;
use Carbon\Carbon;
use http\Env\Response;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\DB;
use Yajra\DataTables\DataTables;
class AppointmentController extends Controller
{
public function newPatient()
{
// $doctors = Doctor::select('doctorId', 'firstName', 'lastName')->get();
$doctors = Doctor::select('doctorId', 'firstName', 'lastName')->get();
$patients = Patient::get();
return view('appointment.new_patient', compact('doctors', 'patients'));
}
public function oldPatient()
{
$patients = Patient::get();
$days = WorkingHour::get();
$doctors = WorkingHour::select('fkdoctorId', 'doctorId', 'firstName', 'lastName')->leftjoin('doctor', 'fkdoctorId', 'doctorId')->get();
return view('appointment.old_patient', compact('doctors', 'days', 'patients'));
}
public function insert(Request $r)
{
$rules = [
'phone' => 'phone:BD',
'age' => 'digits_between:0,200',
'address' => 'regex:/^[a-zA-Z]+$/u|max:255|',
'email' => 'email',
'firstName' => 'regex:/^[a-zA-Z]+$/u|max:255|',
'lastName' => 'regex:/^[a-zA-Z]+$/u|max:255|',
];
$this->validate($r, $rules);
$checkday = WorkingHour::where('fkdoctorId', $r->doctorId)
->where('day', date('l', strtotime($r->day)))
->where('start_time', '<=', date('H:i:p', strtotime($r->appointment_time)))
->where('end_time', '>=', date('H:i:p', strtotime($r->appointment_time)))->get();
// return Response()->json($start[4]);
if (count($checkday) < 1) {
Session::flash('message', 'Doctor is not available this day ot this time!');
Session::flash('message', 'Doctor is not available this day ot this time!!');
Session::flash('alert-class', 'alert-danger');
return back();
} else {
$appointment = new Appointment();
$appointment->phone = $r->phone;
$appointment->age = $r->age;
$appointment->email = $r->email;
$appointment->gender = $r->gender;
$appointment->fkpatientId = $r->patientId;
$appointment->fkdoctorId = $r->doctorId;
$appointment->address = $r->address;
$appointment->day = date('l', strtotime($r->day));
$appointment->appointment_time = date('H:i', strtotime($r->appointment_time));
$appointment->status = $r->status;
// $appointment->phone = $r->phone;
$appointment->save();
Session::flash('message', 'Appointment Created!');
Session::flash('alert-class', 'alert-success');
return redirect()->route('appointment');
}
}
public function showAppointment()
{
$appointmentInfo = Appointment::select(DB::raw("concat(`patient`.`firstName`, ' ' , `patient`.`lastName`) as patientname"), DB::raw("concat(`doctor`.`firstName`, ' ' , `doctor`.`lastName`) as doctorname"), DB::raw("CASE WHEN patient.gender = 1 THEN 'Male' WHEN patient.gender = 2 THEN 'Female' END AS gender"), DB::raw("DATE_FORMAT(`appointment_time`,'%h:%i %p') as appointment_time"), 'fkdoctorId', 'fkpatientId', 'patient.age', 'appointment.email', 'patient.phone', 'patient.address', 'appointment.day', DB::raw("CASE WHEN doctor.status = 0 THEN 'Deleted' WHEN doctor.status = 1 THEN 'Active' WHEN doctor.status = 2 THEN 'Inactive' END AS status"))
->leftjoin('doctor', 'fkdoctorId', 'doctorId')
->leftjoin('patient', 'fkpatientId', 'patientId')->get();
$datatables = Datatables::of($appointmentInfo);
return $datatables->make(true);
}
public function index()
{
return view('appointment.index');
}
public function add()
{
$doctors = Doctor::get();
$patients = Patient::get();
return view('appointment.add', compact('doctors', 'patients'));
}
public function checkoldpatient(Request $r)
{
$patient = Patient::where('phone', $r->phone)->first();
return $patient;
// echo $patient;
// var_dump($patient);
// return view('appointment.add', compact('patient'));
// $appointment = Patient::where('phone', $r->phone)->first();
// return $appointment;
}
public function checkpatient(Request $r)
{
$appointment = Patient::where('patient', $r->patient)->first();
return $appointment;
}
public function checkappointmenttime(Request $r)
{
$time = date('H:i ', strtotime($r->time));
$doctorId = $r->doctorId;
$appointmenttime = Appointment::
leftJoin('working_hour', 'working_hour.fkdoctorId', 'appointment.fkdoctorId')
->where('working_hour.fkdoctorId', $doctorId)
->where('appointment.fkdoctorId', $doctorId)
->where('appointment_time', $time)
->where(function ($query) use ($time) {
$query->where('start_time', '<=', $time)
->Where('end_time', '>=', $time);
})
->first();
return $appointmenttime;
}
public function deleteAppointment(Request $request)
{
$appointment = WorkingHour::findOrFail($request->id);
$appointment->delete();
}
}
|
dda3e187ff4b4c8007424b3623989234acba0f71
|
{
"blob_id": "dda3e187ff4b4c8007424b3623989234acba0f71",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-11T13:19:37",
"content_id": "57458a2b285aeff8fb1f795f260b8e42cfae406c",
"detected_licenses": [
"MIT"
],
"directory_id": "3540ce346ae75c5424b442b4295a5dbd298c4866",
"extension": "php",
"filename": "AppointmentController.php",
"fork_events_count": 1,
"gha_created_at": "2019-05-22T06:52:07",
"gha_event_created_at": "2023-02-02T07:18:16",
"gha_language": "HTML",
"gha_license_id": null,
"github_id": 187980020,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 5555,
"license": "MIT",
"license_type": "permissive",
"path": "/app/Http/Controllers/AppointmentController.php",
"provenance": "stack-edu-0048.json.gz:240890",
"repo_name": "vedlct/Medico",
"revision_date": "2019-11-11T13:19:37",
"revision_id": "eb34e84d69dd944f9743a7925431c38789c0af23",
"snapshot_id": "5ad868899907590bbbe9b897ed87eb3694a910be",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/vedlct/Medico/eb34e84d69dd944f9743a7925431c38789c0af23/app/Http/Controllers/AppointmentController.php",
"visit_date": "2023-02-08T05:04:44.293738",
"added": "2024-11-19T02:32:07.265582+00:00",
"created": "2019-11-11T13:19:37",
"int_score": 2,
"score": 2.453125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0066.json.gz"
}
|
package com.hcl.myhotel.exception;
/**
* @author Sridhar reddy
* Genric class for all Resource not found like 404
*/
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException() {
super();
}
public ResourceNotFoundException(String message, Throwable cause) {
super(message, cause);
}
public ResourceNotFoundException(String message) {
super(message);
}
public ResourceNotFoundException(Throwable cause) {
super(cause);
}
}
|
a24ae688b9fb6ec7abc94da4050dfb2104065640
|
{
"blob_id": "a24ae688b9fb6ec7abc94da4050dfb2104065640",
"branch_name": "refs/heads/master",
"committer_date": "2018-07-26T10:30:37",
"content_id": "01a6a8c96698e8a1e31f8886fb17efbaa4c5e4b0",
"detected_licenses": [
"MIT"
],
"directory_id": "477ba417ef71d123d1b43b8f01e573560c98c60f",
"extension": "java",
"filename": "ResourceNotFoundException.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 142419216,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 535,
"license": "MIT",
"license_type": "permissive",
"path": "/HybridReservationSystem/src/main/java/com/hcl/myhotel/exception/ResourceNotFoundException.java",
"provenance": "stack-edu-0022.json.gz:799730",
"repo_name": "sridharreddych/Spring1",
"revision_date": "2018-07-26T10:30:37",
"revision_id": "ff171d05f907fa397222a097799109a9eeb29932",
"snapshot_id": "89519de97719acd5d3a526b1643be07f556c6835",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/sridharreddych/Spring1/ff171d05f907fa397222a097799109a9eeb29932/HybridReservationSystem/src/main/java/com/hcl/myhotel/exception/ResourceNotFoundException.java",
"visit_date": "2020-03-24T03:25:53.828701",
"added": "2024-11-18T22:55:16.782202+00:00",
"created": "2018-07-26T10:30:37",
"int_score": 2,
"score": 2.34375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0040.json.gz"
}
|
package com.gsma.android.xoperatorapidemo.discovery;
public class DiscoveryDeveloperOperatorSettings {
// private static final DeveloperOperatorSetting atelDev=new DeveloperOperatorSetting("ATel Development", "https://integration-sb2.apiexchange.org/v1/discovery",
// "dev2-test-app-test-key");
//
// private static final DeveloperOperatorSetting attDev=new DeveloperOperatorSetting("AT&T Development", "https://integration-att.apiexchange.org/v1/discovery",
// "att-dev1-payment-app-test-key");
//
// private static final DeveloperOperatorSetting attProd=new DeveloperOperatorSetting("AT&T Production", "https://integration-att.apiexchange.org/v1/discovery",
// "att-dev1-payment-app-prod-key");
//
// private static final DeveloperOperatorSetting dtDev=new DeveloperOperatorSetting("DT Development", "https://integration-dt.apiexchange.org/v1/discovery",
// "dt-dev1-payment-app-test-key");
//
// private static final DeveloperOperatorSetting dtProd=new DeveloperOperatorSetting("DT Production", "https://integration-dt.apiexchange.org/v1/discovery",
// "dt-dev1-payment-app-prod-key");
//
// private static final DeveloperOperatorSetting vodDev=new DeveloperOperatorSetting("Vodafone Development", "https://integration-vod.apiexchange.org/v1/discovery",
// "vod-dev1-payment-app-test-key");
//
// private static final DeveloperOperatorSetting vodProd=new DeveloperOperatorSetting("Vodafone Production", "https://integration-vod.apiexchange.org/v1/discovery",
// "vod-dev1-payment-app-prod-key");
//
// private static final DeveloperOperatorSetting[] operators={atelDev, attDev, attProd, dtDev, dtProd, vodDev, vodProd};
// private static final DeveloperOperatorSetting testDev=new DeveloperOperatorSetting("MWC 2014 Demo",
// "https://etelco-prod.apigee.net/v1/discovery", "DmaPIXFihqJhHhVQwpk9NHd7BzIzQxOe", "Doul7PiXVFCNI77g");
// private static final DeveloperOperatorSetting testDev=new DeveloperOperatorSetting("ETel Demo",
// "https://etelco-prod.apigee.net/v1/discovery", "BJL7na81ZEaaFuoz1bbqT3CyS5x9CAFS", "Mt6HAx5Ujb39Sbs0", "https://etelco-prod.apigee.net/v1/logo");
private static final DeveloperOperatorSetting testDev=new DeveloperOperatorSetting("ETel Demo",
"https://etelco-prod.apigee.net/v1/discovery", "BJL7na81ZEaaFuoz1bbqT3CyS5x9CAFS", "Mt6HAx5Ujb39Sbs0", "https://integration-dt.apiexchange.org/v1/logo");
private static String[] operatorNames=null;
private static final DeveloperOperatorSetting[] operators={testDev};
static {
operatorNames=new String[operators.length];
int index=0;
for (DeveloperOperatorSetting operator:operators) {
operatorNames[index++]=operator.getName();
}
}
public static String[] getOperatorNames() { return operatorNames; }
public static DeveloperOperatorSetting getOperator(int index) { return operators[index]; }
}
|
26ebb9d0db2cfd278da2c8b2f761e714487e53e1
|
{
"blob_id": "26ebb9d0db2cfd278da2c8b2f761e714487e53e1",
"branch_name": "refs/heads/master",
"committer_date": "2014-05-01T19:43:38",
"content_id": "7ef95bb848410ff4a747a2d6bad6875ff1edf8f4",
"detected_licenses": [
"MIT"
],
"directory_id": "61fe9bdd2522d482f5b46f992083b12243d85232",
"extension": "java",
"filename": "DiscoveryDeveloperOperatorSettings.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2858,
"license": "MIT",
"license_type": "permissive",
"path": "/src/com/gsma/android/xoperatorapidemo/discovery/DiscoveryDeveloperOperatorSettings.java",
"provenance": "stack-edu-0019.json.gz:230541",
"repo_name": "biddyweb/CrossOperatorAPIDemo",
"revision_date": "2014-05-01T19:43:38",
"revision_id": "9f593875da727927404f3772d798cce554a765ae",
"snapshot_id": "846234531c183db083adf15d5ca171db2714a19c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/biddyweb/CrossOperatorAPIDemo/9f593875da727927404f3772d798cce554a765ae/src/com/gsma/android/xoperatorapidemo/discovery/DiscoveryDeveloperOperatorSettings.java",
"visit_date": "2021-01-18T10:20:57.359173",
"added": "2024-11-18T22:03:48.997957+00:00",
"created": "2014-05-01T19:43:38",
"int_score": 2,
"score": 2.046875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0037.json.gz"
}
|
define([
"locale"
],function(_){
var delete_column = { width:37, id:"crud:remove", header:"", template:"<span class='webix_icon fa-trash-o'></span>" };
var delete_handler = function(data){
return {
"fa-trash-o":function(ev, id){
webix.confirm({
text:_("Crud.NoUndoMessage"),
ok:_("OK"),
cancel:_("Cancel"),
callback:function(res){
if (res){
var target = typeof data === "string" ? webix.$$(data) : data;
target.remove(id.row);
}
}
});
}
};
};
var empty_template = function(obj, common, value){
if (value === null) return "";
return value;
};
var add_button = function(callback){
return {
view:"button", maxWidth:200, value:_("Crud.AddNew"), click:callback
};
};
function crud_collection(data, fields, name, params){
var id = webix.uid().toString();
if (data === null) data = id;
var columns = [ delete_column ];
for (var i = 0; i < fields.length; i++){
var next = fields[i];
if (typeof next === "string")
columns[i+1] = { id:next, editor:"text", sort:"string", fillspace:1, template: empty_template};
else
columns[i+1] = next;
}
var table = {
view:"datatable", columns:columns, id:id, scrollX:false,
editable:true,
onClick:delete_handler(data)
};
if (params)
for (var key in params)
table[key] = params[key];
var toolbar = {
view:"toolbar", elements:[
{ view:"label", label:(name||"") },
add_button(function(){
var view = data;
if (typeof view === "string")
view = webix.$$(data);
var nid = view.add({});
var grid = $$(id);
grid.showItem(nid);
var columns = grid.config.columns;
for (var i = 0; i < columns.length; i++) {
if (columns[i].editor && columns[i].editor != "inline-checkbox"){
grid.editCell(nid, grid.config.columns[i].id);
return;
}
}
})
]
};
return {
$ui:{ type:"clean", rows:[ toolbar, table ] },
$oninit:function(){
if (data != id)
$$(id).sync($$(data));
}
};
}
function crud_model(model, fields, name, params){
var ui = crud_collection(null, fields, name, params);
var table = ui.$ui.rows[1];
table.url = model.find;
table.save = model.save;
return ui;
}
return {
collection: crud_collection,
model: crud_model,
remove:{
column: delete_column,
handler: delete_handler
},
add:{
button: add_button
}
};
});
|
bc3b0973c9b5ebfb314608e206504f879df80a20
|
{
"blob_id": "bc3b0973c9b5ebfb314608e206504f879df80a20",
"branch_name": "refs/heads/master",
"committer_date": "2017-08-12T22:30:33",
"content_id": "8d399652d53fce9e9ff4e5cf4e5fbc7b6f2046b5",
"detected_licenses": [
"MIT"
],
"directory_id": "660ee129876379762a5784423c38528a4f0fa527",
"extension": "js",
"filename": "crud.js",
"fork_events_count": 0,
"gha_created_at": "2017-08-12T19:45:19",
"gha_event_created_at": "2017-08-12T19:45:19",
"gha_language": null,
"gha_license_id": null,
"github_id": 100134340,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 2424,
"license": "MIT",
"license_type": "permissive",
"path": "/helpers/crud.js",
"provenance": "stack-edu-0031.json.gz:783331",
"repo_name": "bituls/jet-core",
"revision_date": "2017-08-12T22:30:33",
"revision_id": "e98ae7edfde52c01215b9a5516e36b6434d67e79",
"snapshot_id": "62407074ffe8c3df2a070bbb8fa264395dfdac79",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/bituls/jet-core/e98ae7edfde52c01215b9a5516e36b6434d67e79/helpers/crud.js",
"visit_date": "2021-01-16T19:06:18.115130",
"added": "2024-11-18T20:43:33.971044+00:00",
"created": "2017-08-12T22:30:33",
"int_score": 2,
"score": 2.140625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0049.json.gz"
}
|
package gov.va.escreening.serializer;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by pouncilt on 7/13/14.
*/
public class JsonDateDeserializer extends JsonDeserializer<Date> {
private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
@Override
public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
if (jsonParser.getText() != null && !jsonParser.getText().trim().equals("")) {
String date = jsonParser.getText().substring(0, jsonParser.getText().length() -1);
try {
return dateFormat.parse(date);
} catch (ParseException e) {
throw new RuntimeException(e);
}
} else {
return null;
}
}
}
|
bc66eea74ebcd64d7540e769a632385996cee55c
|
{
"blob_id": "bc66eea74ebcd64d7540e769a632385996cee55c",
"branch_name": "refs/heads/master",
"committer_date": "2017-09-27T19:13:53",
"content_id": "fa0615c7c1fadfea748b09697cfa4ff6c0b5d9d8",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "087ad3481ae046b538104674e43e79100b206672",
"extension": "java",
"filename": "JsonDateDeserializer.java",
"fork_events_count": 0,
"gha_created_at": "2018-03-22T18:49:50",
"gha_event_created_at": "2018-03-22T18:49:52",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 126381247,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1154,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/escreening/src/main/java/gov/va/escreening/serializer/JsonDateDeserializer.java",
"provenance": "stack-edu-0029.json.gz:362374",
"repo_name": "majia2968/Mental-Health-eScreening",
"revision_date": "2017-09-27T19:13:53",
"revision_id": "46538020c1bd71f12f352d4a82d7174bcbaa7b2a",
"snapshot_id": "eba4676812a8b3ab79b8b379b4d9276bf6445ed9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/majia2968/Mental-Health-eScreening/46538020c1bd71f12f352d4a82d7174bcbaa7b2a/escreening/src/main/java/gov/va/escreening/serializer/JsonDateDeserializer.java",
"visit_date": "2021-04-18T19:41:40.325138",
"added": "2024-11-18T22:26:09.586785+00:00",
"created": "2017-09-27T19:13:53",
"int_score": 3,
"score": 2.578125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0047.json.gz"
}
|
# 重启后生效
# 开启
chkconfig iptables on
# 关闭
chkconfig iptables off
# 即时生效,重启后失效
# 开启
service iptables start
# 关闭
service iptables stop
# 需要说明的是对于Linux下的其它服务都可以用以上命令执行开启和关闭操作。
# 在开启了防火墙时,做如下设置,开启相关端口
vim /etc/sysconfig/iptables
# 添加以下内容
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
|
505dad572fdf4d35ddd0e328d91b1c12e3b5474d
|
{
"blob_id": "505dad572fdf4d35ddd0e328d91b1c12e3b5474d",
"branch_name": "refs/heads/master",
"committer_date": "2016-12-07T13:02:45",
"content_id": "ae8dc53c73ea1a468ebbf65a49e54dc33bf003a7",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "203e602370f4673f65f3c3022355ff6634c268ac",
"extension": "sh",
"filename": "iptables.sh",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 75520188,
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 563,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/shell/sys/iptables.sh",
"provenance": "stack-edu-0068.json.gz:564822",
"repo_name": "WeAreChampion/notes",
"revision_date": "2016-12-07T13:02:45",
"revision_id": "6c0f726d1003e5083d9cf1b75ac6905dc1c19c07",
"snapshot_id": "4942fbd5c238559eb318787adc27be72f848de44",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/WeAreChampion/notes/6c0f726d1003e5083d9cf1b75ac6905dc1c19c07/shell/sys/iptables.sh",
"visit_date": "2020-06-14T03:54:00.587873",
"added": "2024-11-18T20:03:29.583164+00:00",
"created": "2016-12-07T13:02:45",
"int_score": 3,
"score": 2.53125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0086.json.gz"
}
|
from unittest import TestCase
from mock import mock
from pictures.dedupe import dedupe
from tests import helpers
def create_mock_cmp(equal_files):
return lambda f1, f2: f1 in equal_files and f2 in equal_files
class TestDedupe(TestCase):
EQUAL_FILES = ['filename1', 'filename2', 'filename3']
NON_EQUAL_FILES = ['filename4', 'filename5']
FILES = EQUAL_FILES + NON_EQUAL_FILES
@mock.patch('os.remove')
@mock.patch('filecmp.cmp', side_effect=create_mock_cmp(EQUAL_FILES))
def test_dedupe_prefer_shorter(self, mock_cmp, mock_remove):
dedupe(self.FILES)
self.assertEquals(mock_cmp.mock_calls, helpers.calls_from([
('filename1', 'filename2'),
('filename1', 'filename3'),
('filename1', 'filename4'),
('filename1', 'filename5'),
('filename4', 'filename5')
]))
self.assertEquals(mock_remove.mock_calls, helpers.calls_from([
('filename2',),
('filename3',)
]))
@mock.patch('os.remove')
@mock.patch('filecmp.cmp', side_effect=create_mock_cmp(EQUAL_FILES))
def test_dedupe_prefer_longer(self, mock_cmp, mock_remove):
dedupe(self.FILES, prefer_shorter=False)
self.assertEquals(mock_cmp.mock_calls, helpers.calls_from([
('filename1', 'filename2'),
('filename2', 'filename3'),
('filename3', 'filename4'),
('filename3', 'filename5'),
('filename4', 'filename5')
]))
self.assertEquals(mock_remove.mock_calls, helpers.calls_from([
('filename1',),
('filename2',)
]))
|
86dabe3f5fd337ccdbead103c72fadfa55a18984
|
{
"blob_id": "86dabe3f5fd337ccdbead103c72fadfa55a18984",
"branch_name": "refs/heads/master",
"committer_date": "2017-01-16T10:28:16",
"content_id": "d5469ec5195f32963b8935309beeddc13e7cb210",
"detected_licenses": [
"MIT"
],
"directory_id": "afb1a8008dde1663408e2c6a4359b7764e1c7562",
"extension": "py",
"filename": "test_dedupe.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 78937676,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1640,
"license": "MIT",
"license_type": "permissive",
"path": "/tests/test_dedupe.py",
"provenance": "stack-edu-0056.json.gz:409013",
"repo_name": "mina-asham/pictures-dedupe-and-rename",
"revision_date": "2017-01-16T10:28:16",
"revision_id": "7abc60282b5df6f2d4bf058a82af6d7adcdeca63",
"snapshot_id": "0b6727aacaeea235ffaae569853afd1dec3c4d4e",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/mina-asham/pictures-dedupe-and-rename/7abc60282b5df6f2d4bf058a82af6d7adcdeca63/tests/test_dedupe.py",
"visit_date": "2021-01-13T15:12:33.450302",
"added": "2024-11-19T02:42:23.419003+00:00",
"created": "2017-01-16T10:28:16",
"int_score": 3,
"score": 2.6875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0074.json.gz"
}
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Jobs\SendOrderEmail;
use App\Mail\OrderShipped;
use App\Order;
use Log;
class MailController extends Controller
{
public function index() {
// $order = Order::findOrFail( rand(1,50) );
$order = Order::findOrFail( rand(1, 1) );
$recipient = 'steven@example.com';
Mail::to($recipient)->send(new OrderShipped($order));
return 'Sent order ' . $order->id;
}
public function testQueue() {
// $order = Order::findOrFail( rand(1,50) );
$order = Order::findOrFail( rand(1, 1) );
SendOrderEmail::dispatch($order);
Log::info('Dispatched order ' . $order->id);
return 'Dispatched order ' . $order->id;
}
}
|
212a8c8296d6b489dbe804b5068f9814f7e941b1
|
{
"blob_id": "212a8c8296d6b489dbe804b5068f9814f7e941b1",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-26T06:05:45",
"content_id": "afd26d3eadc85c9ac1aad66ab2fa5712a37ac28b",
"detected_licenses": [
"MIT"
],
"directory_id": "7a868ba3237fad3a75982c6748d6761a0f3363ca",
"extension": "php",
"filename": "MailController.php",
"fork_events_count": 0,
"gha_created_at": "2019-11-09T04:02:50",
"gha_event_created_at": "2023-02-02T08:38:39",
"gha_language": "PHP",
"gha_license_id": "MIT",
"github_id": 220589042,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 813,
"license": "MIT",
"license_type": "permissive",
"path": "/example-project/app/Http/Controllers/MailController.php",
"provenance": "stack-edu-0054.json.gz:294485",
"repo_name": "trung85/k8s_laravel",
"revision_date": "2019-11-26T06:05:45",
"revision_id": "51613d935c2b668591e9cd323550ba6d427c7a05",
"snapshot_id": "3a046083e212fa8afbd57cf11550148748ddf572",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/trung85/k8s_laravel/51613d935c2b668591e9cd323550ba6d427c7a05/example-project/app/Http/Controllers/MailController.php",
"visit_date": "2023-02-09T22:32:12.825055",
"added": "2024-11-19T00:32:32.770884+00:00",
"created": "2019-11-26T06:05:45",
"int_score": 2,
"score": 2.390625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0072.json.gz"
}
|
package main
import "github.com/gin-gonic/gin"
/**
参数作为请求URL - rest
*/
func main() {
r := gin.Default()
r.GET(":name/:id", func(context *gin.Context) {
context.JSON(200, gin.H{
"name": context.Param("name"),
"id": context.Param("id"),
})
})
r.Run("0.0.0.0:8082")
}
|
c8303fdd22c0faca6f8dbcbcbe3b9ed97980f51f
|
{
"blob_id": "c8303fdd22c0faca6f8dbcbcbe3b9ed97980f51f",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-08T15:23:22",
"content_id": "94d497f40de4c7efbb7aa750771c67716e74f3f2",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "71b9e781af3a7c4c55e69f96f555cf6388113e5f",
"extension": "go",
"filename": "main.go",
"fork_events_count": 12,
"gha_created_at": "2019-05-10T10:58:58",
"gha_event_created_at": "2023-06-19T15:18:03",
"gha_language": "Java",
"gha_license_id": "Apache-2.0",
"github_id": 185972999,
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 298,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/golang/imooc-gin-study/router_url/main.go",
"provenance": "stack-edu-0019.json.gz:105874",
"repo_name": "imyzt/learning-technology-code",
"revision_date": "2023-07-08T15:23:22",
"revision_id": "8c01f8b6aa15ca78c1c86015e49e9ffbe10e29c3",
"snapshot_id": "67231e38a33798552c00507a87082970451a729b",
"src_encoding": "UTF-8",
"star_events_count": 7,
"url": "https://raw.githubusercontent.com/imyzt/learning-technology-code/8c01f8b6aa15ca78c1c86015e49e9ffbe10e29c3/golang/imooc-gin-study/router_url/main.go",
"visit_date": "2023-07-24T22:22:45.799759",
"added": "2024-11-19T03:16:16.094978+00:00",
"created": "2023-07-08T15:23:22",
"int_score": 2,
"score": 2.03125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0037.json.gz"
}
|
# Copyright 2020 The Weakly-Supervised Control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Opening a door with a Sawyer arm.
To test:
python -m weakly_supervised_control.envs.sawyer_door
"""
from typing import Dict
import os
from gym import spaces
import numpy as np
from multiworld.envs.mujoco.sawyer_xyz.sawyer_door_hook import SawyerDoorHookEnv
class SawyerDoorGoalEnv(SawyerDoorHookEnv):
def __init__(self, **sawyer_xyz_kwargs):
from multiworld.envs import env_util
old_asset_dir = env_util.ENV_ASSET_DIR
env_util.ENV_ASSET_DIR = os.path.join(
os.path.dirname(__file__), 'assets')
super().__init__(**sawyer_xyz_kwargs)
env_util.ENV_ASSET_DIR = old_asset_dir
self._door_start_id = self.model.site_name2id('door_start')
self._door_end_id = self.model.site_name2id('door_end')
@property
def factor_names(self):
return ['hand_x', 'hand_y', 'hand_z', 'door_angle']
@property
def door_endpoints(self):
door_start = self.data.get_site_xpos('door_start')
door_end = self.data.get_site_xpos('door_end')
return [door_start, door_end]
def set_to_goal_angle(self, angle):
self.data.set_joint_qpos('doorjoint', angle)
self.data.set_joint_qvel('doorjoint', angle)
self.sim.forward()
def set_to_goal_pos(self, xyz, error_tol: float = 1e-2, max_iters: int = 1000):
self.data.set_mocap_pos('mocap', np.array(xyz))
self.data.set_mocap_quat('mocap', np.array([1, 0, 1, 0]))
u = self.data.ctrl.copy()
u[:-1] = 0
# Step the simulation until the hand is close enough to the desired pos.
error = 0
for sim_iter in range(max_iters // self.frame_skip):
self.do_simulation(u, self.frame_skip)
cur_hand_pos = self.get_endeff_pos()
error = np.linalg.norm(xyz - cur_hand_pos)
if error < error_tol:
break
# print(f'Took {sim_iter * self.frame_skip} (error={error}) to converge')
def set_to_goal(self, goal: Dict[str, np.ndarray]):
"""
This function can fail due to mocap imprecision or impossible object
positions.
"""
state_goal = goal['state_desired_goal']
assert state_goal.shape == (4,), state_goal.shape
self.set_to_goal_pos(state_goal[:3])
self.set_to_goal_angle(state_goal[-1])
def sample_goals(self, batch_size, close_threshold: float = 0.05):
goals = np.random.uniform(
self.goal_space.low,
self.goal_space.high,
size=(batch_size, self.goal_space.low.size),
)
# This only works for 2D control
# goals[:, 2] = self.fixed_hand_z
for goal in goals:
hand_pos = goal[:3]
door_angle = goal[3]
self.set_to_goal_angle(door_angle)
door_start, door_end = self.door_endpoints
door_vec = door_end - door_start
door_vec /= np.linalg.norm(door_vec)
door_to_hand = hand_pos - door_start
door_to_hand[2] = 0
proj = np.dot(door_vec, door_to_hand) * door_vec
normal_vec = door_to_hand - proj
length = np.linalg.norm(normal_vec)
# If the arm is inside the door, move it outside.
if normal_vec[1] > 0:
hand_pos = hand_pos - 2 * normal_vec
normal_vec *= -1
if length < close_threshold:
perturb = normal_vec * 2 * close_threshold / length
hand_pos += perturb
goal[:3] = hand_pos
return {
'desired_goal': goals,
'state_desired_goal': goals,
}
def _set_debug_pos(self, pos, i):
marker_id = self.model.geom_name2id(f'marker{i}')
self.model.geom_pos[marker_id, :] = pos
self.sim.forward()
if __name__ == '__main__':
import gym
from weakly_supervised_control.envs import register_all_envs
from weakly_supervised_control.envs.env_wrapper import MujocoSceneWrapper
from weakly_supervised_control.envs.multiworld.envs.mujoco import cameras
register_all_envs()
env = gym.make('SawyerDoorGoalEnv-v1')
env = MujocoSceneWrapper(env)
for e in range(20):
env.reset()
env.initialize_camera(cameras.sawyer_pick_and_place_camera)
goal = env.sample_goals(1)
goal = {k: v[0] for k, v in goal.items()}
env.set_to_goal(goal)
for _ in range(100):
env.render()
|
d0efac8f26f7f846d6055ddd1e3b8402919ac971
|
{
"blob_id": "d0efac8f26f7f846d6055ddd1e3b8402919ac971",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-02T22:37:05",
"content_id": "39dfeef74b3812be24be2e08792ab365d5071759",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "2bb263fe87061291e91193c8b8ae4eeecc53e479",
"extension": "py",
"filename": "sawyer_door.py",
"fork_events_count": 4,
"gha_created_at": "2020-10-02T22:19:17",
"gha_event_created_at": "2020-10-03T05:54:48",
"gha_language": "Python",
"gha_license_id": "Apache-2.0",
"github_id": 300748294,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5075,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/weakly_supervised_control/envs/sawyer_door.py",
"provenance": "stack-edu-0062.json.gz:210841",
"repo_name": "google-research/weakly_supervised_control",
"revision_date": "2020-10-02T22:37:05",
"revision_id": "998034581710d148f7576a720383633e39b84a09",
"snapshot_id": "6e7b5902a54cdbfcb4dcc6d5fcf5bce8405c9630",
"src_encoding": "UTF-8",
"star_events_count": 7,
"url": "https://raw.githubusercontent.com/google-research/weakly_supervised_control/998034581710d148f7576a720383633e39b84a09/weakly_supervised_control/envs/sawyer_door.py",
"visit_date": "2022-12-23T00:01:27.168266",
"added": "2024-11-18T23:11:07.371407+00:00",
"created": "2020-10-02T22:37:05",
"int_score": 2,
"score": 2.296875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0080.json.gz"
}
|
《 **Eye of the Tiger** 》是电影《洛奇3》(Rocky III)主题曲。由Survivor演唱。
西尔维斯特·史泰龙再任导演拍摄《洛奇》第三集,竟然为这个传奇性的英雄角色开拓了新的戏剧空间,主题亦有新的突破,成绩相当亮眼。在本片中,洛基已连任数届拳王,名成利就之下安于逸乐生活而丧失斗志。黑人拳师T先生在大庭广众下公开向洛基叫阵,并且真的在擂台上打败了洛基,老教练因而病发去世。在洛基陷入低潮时,昔日死对头阿波罗毛遂自荐担任洛基的教练,重新激发他的斗志,终于在重赛时赢回了拳王宝座。在探讨名人高处不胜寒的心境方面,效果出奇的深刻和富于自省,故事的发展也跌宕有致。T先生原为重量级拳王阿里的保镖,造型和演出均具有爆炸性。
Survivor所演唱的《洛基第三集(Rocky III)》血脉喷张电影主题曲Eye of the
Tiger,此作蝉联了全美单曲榜6周冠军,并一举拿下了Grammy最佳摇滚团体演唱奖,1992年奥斯卡最佳电影歌曲奖,将Survivor
的全球声势推向了高峰!
歌词下方是 _Eye of the Tiger钢琴谱_ ,欢迎大家使用。
###
Eye of the Tiger歌词:
Risin' up
back on the street
did my time took my chances
went the distance
now i'm back on my feet
just a man and and his will to survive
so many times
it happens too fast
you trade your passion for glory
don't lose your grip on the dreams of the past
you must fight just to keep them alive
Chorus
It's the eye of the tiger
It's the eye of the tiger
It's the eye of the tiger
it's the thrill of the fight
it's the thrill of the fight
it's the thrill of the fight
risin' up to the challenge of our rival
risin' up to the challenge of our rival
risin' up to the challenge of our rival
and the last known survivor stalks his prey in the night
and the last known survivor stalks his prey in the night
and the last known survivor stalks his prey in the night
and he's watchin us all with the eye
and he's watchin us all with the eye
and he's watchin us all with the eye
of the tiger
of the tiger
of the tiger
Face to face
out in the heat
hangin' tough
stayin' hungry
they stack the odds
still we take to the street
for the kill with the will to survive
Risin' up
straight to the top
had the guts
got the glory
went the distance
now i'm not gonna stop
just a man and his will to survive
|
a71621b5587fd3d4dfdc5ac723176ef3b89adab1
|
{
"blob_id": "a71621b5587fd3d4dfdc5ac723176ef3b89adab1",
"branch_name": "refs/heads/main",
"committer_date": "2021-08-14T14:43:39",
"content_id": "6d362dac7b517c03d0f7b5bbb4965df92e43a911",
"detected_licenses": [
"MIT"
],
"directory_id": "fa64bbf8af245c26daaba1fe0c2b05c90b65092b",
"extension": "md",
"filename": "README.md",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2551,
"license": "MIT",
"license_type": "permissive",
"path": "/流行/Eye of the Tiger-洛奇3主題歌/README.md",
"provenance": "stack-edu-markdown-0017.json.gz:42049",
"repo_name": "Emptyspirit/everyonepiano-music-database",
"revision_date": "2021-08-14T14:43:39",
"revision_id": "fb8ba03dd9474f049b18d9822c40a395229b7aca",
"snapshot_id": "e44a184efc15830289dee957c3410de169e5a212",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Emptyspirit/everyonepiano-music-database/fb8ba03dd9474f049b18d9822c40a395229b7aca/流行/Eye of the Tiger-洛奇3主題歌/README.md",
"visit_date": "2023-07-16T15:02:39.001936",
"added": "2024-11-19T00:14:49.092435+00:00",
"created": "2021-08-14T14:43:39",
"int_score": 2,
"score": 2.171875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0017.json.gz"
}
|
//@@parrot-mock
class MockExampleDataFetcherWithOtherParameter: ExampleDataFetcherWithOtherParameter {
final class Stub {
var fetchCallCount = 0
var fetchCalledWith = [(options: Bool, completion: () -> ())]()
}
var stub = Stub()
func parrotResetMock() {
stub = Stub()
}
func fetch(options: Bool, completion: @escaping () -> ()) {
stub.fetchCallCount += 1
stub.fetchCalledWith.append((options, completion))
}
}
|
ca69dc71033ec5e99b0dfe126d1c9033f9a2c638
|
{
"blob_id": "ca69dc71033ec5e99b0dfe126d1c9033f9a2c638",
"branch_name": "refs/heads/master",
"committer_date": "2019-08-09T17:42:32",
"content_id": "8ed1a0d4fa7aa74634c8a898e039bd46173d4d1e",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "434d9285927defb17cc213b34377eac3c6bd2b29",
"extension": "swift",
"filename": "MockExampleDataFetcherWithOtherParameter.swift",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 142589444,
"is_generated": false,
"is_vendor": false,
"language": "Swift",
"length_bytes": 435,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/ParrotTests/RunExamples/Tests/MockExampleDataFetcherWithOtherParameter.swift",
"provenance": "stack-edu-0072.json.gz:86791",
"repo_name": "Bayer-Group/Parrot",
"revision_date": "2019-08-09T17:42:32",
"revision_id": "b0db2ed5965d53a6084511cc406b3f9cf66ab846",
"snapshot_id": "ed4be519aaa61db712dc87cbc958c720bb0dd7f4",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/Bayer-Group/Parrot/b0db2ed5965d53a6084511cc406b3f9cf66ab846/ParrotTests/RunExamples/Tests/MockExampleDataFetcherWithOtherParameter.swift",
"visit_date": "2022-02-08T14:04:04.802451",
"added": "2024-11-19T00:26:38.644105+00:00",
"created": "2019-08-09T17:42:32",
"int_score": 2,
"score": 2.28125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0090.json.gz"
}
|
import { Component, Output, EventEmitter, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { SessionStorageService, PessoaService, AuthenticationService } from 'src/app/shared/_services';
import { LocalUser } from 'src/app/shared/_models';
@Component({
selector: 'app-sidebar',
templateUrl: './sidebar.component.html',
styleUrls: ['./sidebar.component.scss']
})
export class SidebarComponent implements OnInit {
isActive: boolean;
collapsed: boolean;
showMenu: string;
pushRightClass: string;
localUser: LocalUser;
permissao: string;
@Output() collapsedEvent = new EventEmitter<boolean>();
constructor(
private router: Router,
private authenticationService: AuthenticationService,
private sessionStorageService: SessionStorageService,
private pessoaService: PessoaService
) {
this.router.events.subscribe(val => {
if (
val instanceof NavigationEnd &&
window.innerWidth <= 992 &&
this.isToggled()
) {
this.toggleSidebar();
}
});
}
ngOnInit() {
this.isActive = false;
this.collapsed = false;
this.showMenu = '';
this.pushRightClass = 'push-right';
this.localUser = this.sessionStorageService.getValue();
this.permissao = this.localUser.pessoa.pesPermissao
}
resetarSenha() {
let retorno: boolean;
this.pessoaService.resetarSenha(this.localUser.pessoa).subscribe(ret => {
retorno = ret.data;
}, err => {
console.log(err)
alert("Erro ao Resetar Senha!")
}, () => {
alert("Senha Resetada com Sucesso!")
});
/*
if (retorno) {
alert("Senha Resetada com Sucesso!")
} else {
alert("Erro ao Resetar Senha!")
}*/
}
eventCalled() {
this.isActive = !this.isActive;
}
addExpandClass(element: any) {
if (element === this.showMenu) {
this.showMenu = '0';
} else {
this.showMenu = element;
}
}
togglecollapsed() {
this.collapsed = !this.collapsed;
this.collapsedEvent.emit(this.collapsed);
}
isToggled(): boolean {
const dom: Element = document.querySelector('body');
return dom.classList.contains(this.pushRightClass);
}
toggleSidebar() {
const dom: any = document.querySelector('body');
dom.classList.toggle(this.pushRightClass);
}
rltAndLtr() {
const dom: any = document.querySelector('body');
dom.classList.toggle('rtl');
}
deslogar() {
this.authenticationService.deslogar();
}
}
|
385391d902478ad2b81623ce7a4bd43fd52be65d
|
{
"blob_id": "385391d902478ad2b81623ce7a4bd43fd52be65d",
"branch_name": "refs/heads/master",
"committer_date": "2020-03-16T01:36:07",
"content_id": "f58187a212f8073127cf4a9dca0938950c4f3466",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "bbfa3e1c5bbb8813213e6eb17274e7e382aa0809",
"extension": "ts",
"filename": "sidebar.component.ts",
"fork_events_count": 0,
"gha_created_at": "2020-02-26T23:12:23",
"gha_event_created_at": "2020-03-16T01:36:08",
"gha_language": "TypeScript",
"gha_license_id": "NOASSERTION",
"github_id": 243385492,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 2836,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/app/layout/components/sidebar/sidebar.component.ts",
"provenance": "stack-edu-0074.json.gz:441027",
"repo_name": "OrganizeRooms/NEW-FrontEnd-OrganizeRooms",
"revision_date": "2020-03-16T01:36:07",
"revision_id": "8ffc00b2a358c82e5245510dd08649b9dd9d2200",
"snapshot_id": "44803c3ba485dd95d5baffc5f9f889583ad5881e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/OrganizeRooms/NEW-FrontEnd-OrganizeRooms/8ffc00b2a358c82e5245510dd08649b9dd9d2200/src/app/layout/components/sidebar/sidebar.component.ts",
"visit_date": "2021-01-26T08:34:06.818236",
"added": "2024-11-18T22:31:23.487849+00:00",
"created": "2020-03-16T01:36:07",
"int_score": 2,
"score": 2.15625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0092.json.gz"
}
|
//http://brownbuffalo.sourceforge.net/RoundOfGolfClues.html
package main
import "fmt"
import l "gologic"
type Dude struct {
First, Last, Job, Score interface{}
}
type Round struct {
D1,D2,D3,D4 interface{}
}
func v () l.V {
return l.Fresh()
}
func betweeno(p interface{}, low, high int) l.Goal {
if low > high {
return l.Fail()
} else {
return l.Or(
l.Unify(low,p),
l.Call(betweeno,p,low+1,high))
}
}
func scoreo (q interface{}) l.Goal {
a,b,c,d := l.Fresh4()
return l.And(
l.Unify(Round{Dude{v(),v(),v(),a}, Dude{v(),v(),v(),b}, Dude{v(),v(),v(),c}, Dude{v(),v(),v(),d}},q),
betweeno(a,70,85),
betweeno(b,70,85),
betweeno(c,70,85),
betweeno(d,70,85))
}
func golfo (q l.V) l.Goal {
membero := l.StructMemberoConstructor4(func (a,b,c,d interface{}) interface{} {return Round{a,b,c,d}})
bills_job := v()
bills_score := v()
mr_clubb_first_name := v()
mr_clubbs_score := v()
pro_shop_clerk_score := v()
frank_score := v()
caddy_score := v()
sands_score := v()
score1,score2,score3,score4 := l.Fresh4()
mr_carters_first_name := v()
return l.And(
l.Unify(Round{Dude{"Bill",v(),v(),score1},Dude{"Jack",v(),v(),score2},Dude{"Frank",v(),v(),score3},Dude{"Paul",v(),v(),score4}},q),
l.Neq(score1,score2),
l.Neq(score1,score3),
l.Neq(score1,score4),
l.Neq(score2,score3),
l.Neq(score2,score4),
l.Neq(score3,score4),
membero(Dude{"Jack", v(), v(), v()}, q),
membero(Dude{v(), "Green", v(), v()}, q),
membero(Dude{v(), v(), "short-order cook", v()}, q),
// // 1
membero(Dude{"Bill", v(), bills_job, bills_score}, q),
l.Neq(bills_job,"maintenance man"),
membero(Dude{v(), v(), "maintenance man", v()}, q),
l.Increasing(bills_score,score2),
l.Increasing(bills_score,score3),
l.Increasing(bills_score,score4),
// // 2
membero(Dude{mr_clubb_first_name, "Clubb", v(), mr_clubbs_score}, q),
l.Neq(mr_clubb_first_name, "Paul"),
membero(Dude{v(), v(), "pro-shop clerk", pro_shop_clerk_score}, q),
l.Difference(mr_clubbs_score,10,pro_shop_clerk_score),
// //3
membero(Dude{"Frank", v(), v(), frank_score}, q),
membero(Dude{v(), v(), "caddy", caddy_score}, q),
membero(Dude{v(), "Sands", v(), sands_score}, q),
l.Or(l.And(l.Difference(frank_score, 7, sands_score),
l.Difference(caddy_score, 4, sands_score)),
l.And(l.Difference(frank_score, 4, sands_score),
l.Difference(caddy_score, 7, sands_score))),
// // // 4
membero(Dude{mr_carters_first_name, "Carter", v(), 78}, q),
l.Increasing(frank_score, 78),
l.Neq(mr_carters_first_name,"Frank"),
// // // 5
l.Neq(score1,81),
l.Neq(score2,81),
l.Neq(score3,81),
l.Neq(score4,81),
scoreo(q),
)
}
func main() {
q := l.Fresh()
c := l.Run(q,golfo(q))
for n := 0 ; n < 10 ; n++ {
i := <- c
if i != nil {
fmt.Println(i)
} else {
break
}
}
}
|
3bb30b2d6c6559f1c427111cf61be7e4801fae90
|
{
"blob_id": "3bb30b2d6c6559f1c427111cf61be7e4801fae90",
"branch_name": "refs/heads/master",
"committer_date": "2013-10-26T08:35:38",
"content_id": "02940b7bb837c564aa085f37cd29be626ad15d87",
"detected_licenses": [
"MIT"
],
"directory_id": "bc059e43ad4647bb467c5534c93e5a4ce6a10186",
"extension": "go",
"filename": "golf.go",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 3780,
"license": "MIT",
"license_type": "permissive",
"path": "/examples/golf.go",
"provenance": "stack-edu-0018.json.gz:302369",
"repo_name": "sarvex/gologic",
"revision_date": "2013-10-26T08:35:38",
"revision_id": "65feb61c6b9733af7e63dfec8877d2ad667d974c",
"snapshot_id": "9549e59f569ca94f27198cf60837ac493c22ce11",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/sarvex/gologic/65feb61c6b9733af7e63dfec8877d2ad667d974c/examples/golf.go",
"visit_date": "2021-01-17T08:13:39.210130",
"added": "2024-11-18T19:51:02.281643+00:00",
"created": "2013-10-26T08:35:38",
"int_score": 3,
"score": 3,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0036.json.gz"
}
|
import { simbolo } from "./simbolo"
export class entorno{
public anterior: entorno
public tabla: {[id:string] : simbolo}
public consola: string
constructor(anterior){
this.anterior = anterior
this.tabla = {}
this.consola = ""
}
agregar(id:string,simbolo:simbolo){
this.tabla[id.toLocaleLowerCase()] = simbolo
}
existeActual(id:string){
let existe = this.tabla[id.toLocaleLowerCase()]
if (existe != null){
return true
}
return false
}
existe(id:string){
let ts:entorno = this
while (ts != null){
let existe = ts.tabla[id.toLocaleLowerCase()]
if (existe != null){
return true
}
ts = ts.anterior
}
return false
}
getSimbol(id:string){
let ts: entorno = this
while (ts != null){
let existe = ts.tabla[id.toLocaleLowerCase()]
if (existe != null){
return existe
}
ts = ts.anterior
}
return null
}
appEnd(cadena: string){
return this.consola+= cadena + "\n"
}
}
|
3956d49d9e9f4355cc6e69c9d1432ae2a98836d1
|
{
"blob_id": "3956d49d9e9f4355cc6e69c9d1432ae2a98836d1",
"branch_name": "refs/heads/main",
"committer_date": "2021-07-07T02:55:16",
"content_id": "9a6f791de44db6c5f96c6ca002dfbd9bf6f1dd7d",
"detected_licenses": [
"MIT"
],
"directory_id": "4dd1aef620dfa836a877733be203472cc0fe51d0",
"extension": "ts",
"filename": "entorno.ts",
"fork_events_count": 1,
"gha_created_at": "2021-06-12T07:16:02",
"gha_event_created_at": "2021-07-07T02:42:04",
"gha_language": "JavaScript",
"gha_license_id": "MIT",
"github_id": 376227052,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 1191,
"license": "MIT",
"license_type": "permissive",
"path": "/20211SVAC/G29/codigo fuente/clases/ast/entorno.ts",
"provenance": "stack-edu-0074.json.gz:914404",
"repo_name": "Jacks128/tytusx",
"revision_date": "2021-07-07T02:55:16",
"revision_id": "028100c10321948a1d2e07bce3cb96731e161cde",
"snapshot_id": "a762b0b9d4ddfaeb2cfa8f5603c3ddfa20dae378",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Jacks128/tytusx/028100c10321948a1d2e07bce3cb96731e161cde/20211SVAC/G29/codigo fuente/clases/ast/entorno.ts",
"visit_date": "2023-06-12T20:50:07.041654",
"added": "2024-11-18T23:37:48.683320+00:00",
"created": "2021-07-07T02:55:16",
"int_score": 3,
"score": 2.9375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0092.json.gz"
}
|
import { html } from "lit-html"
import { conditions, Conditions } from "../conditions"
import { dateTime, DateTime } from "../dateTime"
import { temperature, Temperature } from "../temperature"
export const app = {
initialState: () => Object.assign({},
dateTime.initialState(),
conditions.initialState(),
{ air: temperature.initialState("Air") },
{ water: temperature.initialState("Air") }
),
actions: update => Object.assign({},
dateTime.actions(update),
conditions.actions(update),
temperature.actions(update)
)
}
export const App = (state, actions) => html`
<div class="row">
<div class="col-md-4">
${DateTime(state, actions)}
</div>
<div class="col-md-4">
${Conditions(state, actions)}
${Temperature(state, "air", actions)}
${Temperature(state, "water", actions)}
</div>
</div>
`
|
9bf66eb38718a00ee2dfe0591aaad8b7e993fd3d
|
{
"blob_id": "9bf66eb38718a00ee2dfe0591aaad8b7e993fd3d",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-20T02:38:12",
"content_id": "9d32af65a39dd928c7f0dcdf534e138695d34297",
"detected_licenses": [
"MIT"
],
"directory_id": "f6e8cae40fad6a3d1d6b4ea7b323a0bd758362ba",
"extension": "js",
"filename": "index.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 867,
"license": "MIT",
"license_type": "permissive",
"path": "/examples/setup/lit-html/src/app/index.js",
"provenance": "stack-edu-0033.json.gz:709025",
"repo_name": "disciplezero/meiosis-examples",
"revision_date": "2019-01-20T02:38:12",
"revision_id": "6649aab1567fd776c4f29183511179e21e3557c8",
"snapshot_id": "9d2b09bc68822d83dcc976d19ca5221131dee10e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/disciplezero/meiosis-examples/6649aab1567fd776c4f29183511179e21e3557c8/examples/setup/lit-html/src/app/index.js",
"visit_date": "2020-04-30T01:55:07.955717",
"added": "2024-11-18T21:22:07.543958+00:00",
"created": "2019-01-20T02:38:12",
"int_score": 2,
"score": 2.421875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0051.json.gz"
}
|
#!/bin/bash
REMOTES_COUNT=$(git remote | wc -l)
if [ $REMOTES_COUNT -eq 0 ]; then
echo "No remotes" > /dev/stderr
exit 1
elif [ $REMOTES_COUNT -eq 1 ]; then
exec git remote
else
CURRENT_REMOTE=$(git config branch.$(git name-rev --name-only HEAD).remote)
if [ ! -z "$CURRENT_REMOTE" ]; then
echo $CURRENT_REMOTE
else
if git remote | grep -E '^origin$'; then
exit 0
else
echo "Can't pick a remote" > /dev/stderr
exit 1
fi
fi
fi
|
296fed924a017651b4ae3ba7a96ad044fb6d7c20
|
{
"blob_id": "296fed924a017651b4ae3ba7a96ad044fb6d7c20",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-23T15:45:36",
"content_id": "1c02e3332ce58d4c519a0edf753145f262ae018b",
"detected_licenses": [
"MIT"
],
"directory_id": "497c58bbe24bc3eae889b4290e941b0ab56197ff",
"extension": "",
"filename": "get-remote",
"fork_events_count": 15,
"gha_created_at": "2020-11-16T15:17:07",
"gha_event_created_at": "2023-09-14T14:12:21",
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 313342327,
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 475,
"license": "MIT",
"license_type": "permissive",
"path": "/.orchestra/ci/get-remote",
"provenance": "stack-edu-0070.json.gz:201193",
"repo_name": "revng/orchestra",
"revision_date": "2023-07-25T14:24:21",
"revision_id": "5e5595a4961210e06a5697610e53ecec4c8a9270",
"snapshot_id": "d813c2f1adf63bc5b71219b23f44c1f426187a96",
"src_encoding": "UTF-8",
"star_events_count": 25,
"url": "https://raw.githubusercontent.com/revng/orchestra/5e5595a4961210e06a5697610e53ecec4c8a9270/.orchestra/ci/get-remote",
"visit_date": "2023-08-30T22:51:33.369098",
"added": "2024-11-19T00:42:42.740017+00:00",
"created": "2023-07-25T14:24:21",
"int_score": 4,
"score": 3.703125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0088.json.gz"
}
|
# elasticsearch-curator [](https://community.opscode.com/cookbooks/elasticsearch-curator) [](https://travis-ci.org/cyberflow/chef-elasticsearch-curator)
Chef cookbook to install and configure [elasticsearch-curator](https://www.elastic.co/guide/en/elasticsearch/client/curator/current/index.html) from version 4.
## Tested Platforms
* ubuntu 16.04
* centos 7
## Usage
This cookbook can be used by including `elasticsearch-curator::default` in your run list and settings attributes as needed. Alternatively, you can use the custom resources directly.
If you are using elasticsearch-curator < 5 you might want to use the cookbook version v0.2.8.
### Attributes
| Key | Type | Description | Default |
|--------------------------------------|--------|-------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| node['elasticsearch-curator']['version'] | String | Version of elasticsearch-curator to install, nil = latest | nil |
| node['elasticsearch-curator']['repository_url'] | String | URL of elasticsearch-curator package repository | 'http://packages.elastic.co/curator/4/debian' |
| node['elasticsearch-curator']['repository_key'] | String | elasticsearch-curator repository key | 'https://packages.elastic.co/GPG-KEY-elasticsearch' |
| node['elasticsearch-curator']['bin_path'] | String | bin path for elasticsearch-curator | '/usr/bin' |
|node['elasticsearch-curator']['username']|String|user for running curator|'curator'|
|node['elasticsearch-curator']['config_file_path']|String|path to direct curator config file|"/home/#{node['elasticsearch-curator']['username']}/.curator"|
|node['elasticsearch-curator']['action_file_path']|String|path to direct action config file|"/home/#{node['elasticsearch-curator']['username']}/.curator"|
|node['elasticsearch-curator']['cron_minute']|String|Minute to run the curator cron job|'0'|
|node['elasticsearch-curator']['cron_hour']|String|Hour to run the curator cron job|'*'|
|node['elasticsearch-curator']['config']|Hash|config elasticsearch-curator| {<br> 'client' => {<br> 'hosts' => ['<IP_ADDRESS>'],<br> 'port' => 9200,<br> 'use_ssl' => false,<br> 'ssl_no_validate' => false,<br> 'timeout' => 30,<br> 'master_only' => false<br> },<br> 'logging' => {<br> 'loglevel' => 'INFO',<br> 'logformat' => 'default'<br> }<br>}|
This cookbook ships with custom resources for install elasticsearch-curator and managing the configuration file:
### Custom Resources
#### elasticsearch_curator_install
Installs elasticsearch-curator. Optionally specifies a version, otherwise the latest available is installed
```ruby
elasticsearch_curator_install 'curator' do
install_method node['elasticsearch-curator']['install_method']
action :install
end
```
#### elasticsearch_curator_config
Writes out the elasticsearch-curator configuration file.
```ruby
elasticsearch_curator_config 'default' do
config node['elasticsearch-curator']['config']
action :configure
end
```
This method also supports a http_auth property to allow passing a string with this format : "username:password". This allows retrieving the credentials from the wrapper cookbook (for example using chef-vault) and not store this sensitive information in the attributes.
#### elasticsearch_curator_action
This will setup a cron job and create action.yaml file for elasticsearch-curator.
```ruby
elasticsearch_curator_action 'action' do
config node['elasticsearch-curator']['action_config']
minute '0'
hour '*'
action :create
end
```
## Tests
To run tests, install all dependencies with [bundler](http://bundler.io/):
bundle install
bundle exec cookstyle
bundle exec foodcritic .
|
36dbb0e296922a34d4cd215c8eae2513fc3ffc06
|
{
"blob_id": "36dbb0e296922a34d4cd215c8eae2513fc3ffc06",
"branch_name": "refs/heads/master",
"committer_date": "2019-07-25T08:00:54",
"content_id": "3a25f2f276296802422f267ab729709b0cfa4356",
"detected_licenses": [
"MIT"
],
"directory_id": "a2edf11ac47fb53118ba7da6cc2743756deb56ab",
"extension": "md",
"filename": "README.md",
"fork_events_count": 27,
"gha_created_at": "2016-07-07T13:28:27",
"gha_event_created_at": "2019-07-25T08:00:58",
"gha_language": "Ruby",
"gha_license_id": "MIT",
"github_id": 62808851,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 4441,
"license": "MIT",
"license_type": "permissive",
"path": "/README.md",
"provenance": "stack-edu-markdown-0014.json.gz:208386",
"repo_name": "cyberflow/chef-elasticsearch-curator",
"revision_date": "2019-07-25T08:00:54",
"revision_id": "3296bf1d509990a9c784f691a4166fb1e9f96fac",
"snapshot_id": "4c400845467a2e4a551013af3e83c9d7c529073b",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/cyberflow/chef-elasticsearch-curator/3296bf1d509990a9c784f691a4166fb1e9f96fac/README.md",
"visit_date": "2021-01-17T19:16:38.128657",
"added": "2024-11-18T23:21:53.200826+00:00",
"created": "2019-07-25T08:00:54",
"int_score": 4,
"score": 3.75,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0014.json.gz"
}
|
import React from 'react';
import { connect } from 'react-redux';
import {api} from '../../actions/_request';
import {
Modal,
ModalHeader,
ModalBody,
ModalFooter,
Button,
Label,
Input,
Row,
Col
} from 'reactstrap';
import Moment from 'moment';
import swal2 from 'sweetalert2';
export default class ModalPrestamo extends React.Component
{
constructor(props)
{
super(props);
this.state = {
insumo : {
id : '',
insumo : '',
desc_insumo : '',
},
action : 'save',
};
this.handleInputChange = this.handleInputChange.bind(this);
this.resetModal= this.resetModal.bind(this);
}
componentDidMount()
{
let id = this.props.id;
let self = this;
if(id != null )
{
api().get(`/producto_id/${id}`)
.then(function(response)
{
self.setState({
insumo: response.data,
action: 'update',
});
});
}
else
{
self.resetModal();
}
}
resetModal(){
this.setState({
prestamo : {
id : '',
insumo : '',
descripcion : '',
},
action : 'save',
});
}
handleInputChange(event){
let {insumo} = this.state;
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
if(target.type == 'number'){
if(value.length <= event.target.getAttribute('maxlengh')){
insumo[name] = value;
}
}else{
insumo[name] = value;
}
this.setState({
insumo : insumo
});
}
handleSubmit = (evt) =>{
evt.preventDefault();
let {action, insumo} = this.state;
let url = '';
let _self = this;
if(action == 'save'){
url = '/prod';
}else{
url = '/edit_prod';
}
api().post(url, insumo)
.then((res)=>{
if(!res.data){
_self.props.toggle();
_self.props.refresh();
}else{
swal2(
'Error!',
'Insumo duplicado',
'error'
)
}
})
.catch((err)=>{console.log(err)})
}
render()
{
let {insumo , action} = this.state;
return(
<Modal isOpen={this.props.open} toggle={this.props.toggle} className="default modal-lg ">
<form onSubmit={this.handleSubmit}>
<ModalHeader toggle={this.props.toggle}>{this.props.title}</ModalHeader>
<ModalBody>
<Row>
<Col xs="12" sm="12">
<div className="form-group">
<label className="">Insumo:</label>
<Input
name="insumo"
type="number"
onChange={this.handleInputChange}
value={insumo.insumo}
maxlengh={6}
/>
</div>
</Col>
<Col xs="12" sm="12">
<div className="form-group">
<label className="">Descripcion:</label>
<Input
placeholder=""
type="textarea"
name="desc_insumo"
value={insumo.desc_insumo}
onChange={this.handleInputChange}
required
cols={4}
/>
</div>
</Col>
</Row>
</ModalBody>
<ModalFooter>
{
<div>
<Button color="success" type="submit">
Guardar
</Button>
<Button color="secondary" onClick={this.props.toggle}>
Cerrar
</Button>
</div>
}
</ModalFooter>
</form>
</Modal>
);
}
}
|
2f94613cc0446f86f4851297433bcb463e672be0
|
{
"blob_id": "2f94613cc0446f86f4851297433bcb463e672be0",
"branch_name": "refs/heads/master",
"committer_date": "2020-01-24T00:46:25",
"content_id": "1d9f029dfeb1cf87bc91de4566e103e0027bcb16",
"detected_licenses": [
"MIT"
],
"directory_id": "db1b95c9832b01c899b74b826426aff9ac2ba801",
"extension": "js",
"filename": "insumoModal.js",
"fork_events_count": 0,
"gha_created_at": "2018-09-22T19:31:08",
"gha_event_created_at": "2023-01-04T13:21:04",
"gha_language": "CSS",
"gha_license_id": "MIT",
"github_id": 149910330,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 4794,
"license": "MIT",
"license_type": "permissive",
"path": "/src/views/Insumos/insumoModal.js",
"provenance": "stack-edu-0035.json.gz:684518",
"repo_name": "Rodrigocoronel/todoappreact",
"revision_date": "2020-01-24T00:46:25",
"revision_id": "4b279c12ffe7782111bb7422761e567ae8dee416",
"snapshot_id": "a449c854fa656319b4aeaf6a74e24f4f6efb9309",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Rodrigocoronel/todoappreact/4b279c12ffe7782111bb7422761e567ae8dee416/src/views/Insumos/insumoModal.js",
"visit_date": "2023-01-11T08:36:45.019792",
"added": "2024-11-19T01:32:29.606914+00:00",
"created": "2020-01-24T00:46:25",
"int_score": 2,
"score": 2.34375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0053.json.gz"
}
|
function create(obj){
var el;
if (obj.tag){
el = document.createElement(obj.tag);
}
else if(obj.text){
el = document.createElement('span');
}
else{
console.log('cannot create this element.');
el = document.createElement('span');
return el;
}
if (obj.text){
el.innerText = obj.text;
}
if (obj.classes){
el.className = obj.classes;
}
if (obj.html){
el.innerHTML = obj.html;
}
if(obj.attributes && obj.attributes.length){
for(var i in obj.attributes){
var attr = obj.attributes[i];
if(attr.name && attr.value){
el.setAttribute(attr.name, attr.value);
}
}
}
if (obj.data && obj.data.length){
for (var item in obj.data){
el.appendChild(create(obj.data[item]));
}
}
return el;
}
var e = create(obj);
var x = $('div').html(e);
{
'bold': {
tag: 'button',
classes: 'btn btn-default',
attributes: [{
name: "title",
value: 'Bold'
}, {
name: 'ng-click',
value: 'format(\'bold\')'
}, {
name: 'ng-class',
value: '{ active: isBold }'
}],
data: [{
tag: 'i',
classes: 'fa fa-bold'
}]
},
'italic': {
tag: 'button',
classes: 'btn btn-default',
attributes: [{
name: "title",
value: 'Italic'
}, {
name: 'ng-click',
value: 'format(\'italic\')'
}, {
name: 'ng-class',
value: '{ active: isItalic }'
}],
data: [{
tag: 'i',
classes: 'fa fa-italic'
}]
},
'underline': {
tag: 'button',
classes: 'btn btn-default',
attributes: [{
name: "title",
value: 'Underline'
}, {
name: 'ng-click',
value: 'format(\'underline\')'
}, {
name: 'ng-class',
value: '{ active: isUnderline }'
}],
data: [{
tag: 'i',
classes: 'fa fa-underline'
}]
},
'strikethrough': {
tag: 'button',
classes: 'btn btn-default',
attributes: [{
name: "title",
value: 'Strikethrough'
}, {
name: 'ng-click',
value: 'format(\'strikethrough\')'
}, {
name: 'ng-class',
value: '{ active: isStrikethrough }'
}],
data: [{
tag: 'i',
classes: 'fa fa-strikethrough'
}]
},
'subscript': {
tag: 'button',
classes: 'btn btn-default',
attributes: [{
name: "title",
value: 'Subscript'
}, {
name: 'ng-click',
value: 'format(\'subscript\')'
}, {
name: 'ng-class',
value: '{ active: isSubscript }'
}],
data: [{
tag: 'i',
classes: 'fa fa-subscript'
}]
},
'superscript': {
tag: 'button',
classes: 'btn btn-default',
attributes: [{
name: "title",
value: 'Superscript'
}, {
name: 'ng-click',
value: 'format(\'superscript\')'
}, {
name: 'ng-class',
value: '{ active: isSuperscript }'
}],
data: [{
tag: 'i',
classes: 'fa fa-superscript'
}]
},
'remove-format': {
tag: 'button',
classes: 'btn btn-default',
attributes: [{
name: "title",
value: 'Remove Formatting'
}, {
name: 'ng-click',
value: 'format(\'removeFormat\')'
}],
data: [{
tag: 'i',
classes: 'fa fa-eraser'
}]
},
'ordered-list': {
tag: 'button',
classes: 'btn btn-default',
attributes: [{
name: "title",
value: 'Ordered List'
}, {
name: 'ng-click',
value: 'format(\'insertorderedlist\')'
}, {
name: 'ng-class',
value: '{ active: isOrderedList }'
}],
data: [{
tag: 'i',
classes: 'fa fa-list-ol'
}]
},
'unordered-list': {
tag: 'button',
classes: 'btn btn-default',
attributes: [{
name: "title",
value: 'Unordered List'
}, {
name: 'ng-click',
value: 'format(\'insertunorderedlist\')'
}, {
name: 'ng-class',
value: '{ active: isUnorderedList }'
}],
data: [{
tag: 'i',
classes: 'fa fa-list-ul'
}]
},
'outdent': {
tag: 'button',
classes: 'btn btn-default',
attributes: [{
name: "title",
value: 'Outdent'
}, {
name: 'ng-click',
value: 'format(\'outdent\')'
}],
data: [{
tag: 'i',
classes: 'fa fa-outdent'
}]
},
'indent': {
tag: 'button',
classes: 'btn btn-default',
attributes: [{
name: "title",
value: 'Indent'
}, {
name: 'ng-click',
value: 'format(\'indent\')'
}],
data: [{
tag: 'i',
classes: 'fa fa-indent'
}]
},
'left-justify': {
tag: 'button',
classes: 'btn btn-default',
attributes: [{
name: "title",
value: 'Left Justify'
}, {
name: 'ng-click',
value: 'format(\'justifyleft\')'
}, {
name: 'ng-class',
value: '{ active: isLeftJustified }'
}],
data: [{
tag: 'i',
classes: 'fa fa-align-left'
}]
},
'center-justify': {
tag: 'button',
classes: 'btn btn-default',
attributes: [{
name: "title",
value: 'Center Justify'
}, {
name: 'ng-click',
value: 'format(\'justifycenter\')'
}, {
name: 'ng-class',
value: '{ active: isCenterJustified }'
}],
data: [{
tag: 'i',
classes: 'fa fa-align-center'
}]
},
'right-justify': {
tag: 'button',
classes: 'btn btn-default',
attributes: [{
name: "title",
value: 'Right Justify'
}, {
name: 'ng-click',
value: 'format(\'justifyright\')'
}, {
name: 'ng-class',
value: '{ active: isRightJustified }'
}],
data: [{
tag: 'i',
classes: 'fa fa-align-right'
}]
},
'code': {
tag: 'button',
classes: 'btn btn-default',
attributes: [{
name: "title",
value: 'Code'
}, {
name: 'ng-click',
value: 'format(\'formatblock\', \'pre\')'
}, {
name: 'ng-class',
value: '{ active: isPre }'
}],
data: [{
tag: 'i',
classes: 'fa fa-code'
}]
},
'quote': {
tag: 'button',
classes: 'btn btn-default',
attributes: [{
name: "title",
value: 'Quote'
}, {
name: 'ng-click',
value: 'format(\'formatblock\', \'blockquote\')'
}, {
name: 'ng-class',
value: '{ active: isBlockquote }'
}],
data: [{
tag: 'i',
classes: 'fa fa-quote-right'
}]
},
'paragraph': {
tag: 'button',
classes: 'btn btn-default',
text: 'P',
attributes: [{
name: "title",
value: 'Paragragh'
}, {
name: 'ng-click',
value: 'format(\'insertParagraph\')'
}, {
name: 'ng-class',
value: '{ active: isParagraph }'
}]
},
'image': {
tag: 'button',
classes: 'btn btn-default',
attributes: [{
name: "title",
value: 'Image'
}, {
name: 'ng-click',
value: 'insertImage()'
}, {
name: 'ng-class',
value: '{ active: isParagraph }'
}],
data: [{
tag: 'i',
classes: 'fa fa-picture-0'
}]
},
'font-color': {
tag: 'button',
classes: 'btn btn-default wysiwyg-colorpicker wysiwyg-fontcolor',
text: 'A',
attributes: [{
name: "title",
value: 'Font Color'
}, {
name: 'colorpicker',
value: 'rgba'
}, {
name: 'colorpicker-position',
value: 'top'
}, {
name: 'ng-model',
value: 'fontColor'
}, {
name: 'ng-change',
value: 'setFontColor()'
}]
},
'hilite-color': {
tag: 'button',
classes: 'btn btn-default wysiwyg-colorpicker wysiwyg-fontcolor',
text: 'H',
attributes: [{
name: "title",
value: 'Hilite Color'
}, {
name: 'colorpicker',
value: 'rgba'
}, {
name: 'colorpicker-position',
value: 'top'
}, {
name: 'ng-model',
value: 'hiliteColor'
}, {
name: 'ng-change',
value: 'setHiliteColor()'
}]
},
'font': {
tag: 'select',
classes: 'form-control wysiwyg-select',
attributes: [{
name: "title",
value: 'Image'
}, {
name: 'ng-model',
value: 'font'
}, {
name: 'ng-options',
value: 'f for f in fonts'
}, {
name: 'ng-change',
value: 'setFont()'
}]
},
'font-size': {
tag: 'select',
classes: 'form-control wysiwyg-select',
attributes: [{
name: "title",
value: 'Image'
}, {
name: 'ng-model',
value: 'fontSize'
}, {
name: 'ng-options',
value: 'f.size for f in fontSizes'
}, {
name: 'ng-change',
value: 'setFontSize()'
}]
},
'link': {
tag: 'span',
data: [
{
tag: 'button',
classes: 'btn btn-default',
attributes: [{
name: "title",
value: 'Link'
}, {
name: 'ng-click',
value: 'createLink()'
}, {
name: 'ng-show',
value: '!isLink'
}],
data: [{
tag: 'i',
classes: 'fa fa-link'
}]
}, {
tag: 'button',
classes: 'btn btn-default',
attributes: [{
name: "title",
value: 'Unlink'
}, {
name: 'ng-click',
value: 'format(\'unlink\')'
}, {
name: 'ng-show',
value: 'isLink'
}],
data: [{
tag: 'i',
classes: 'fa fa-unlink'
}]
}
]
}
};
|
1450b081c0fdd16a8b481d1bb2031b7460736524
|
{
"blob_id": "1450b081c0fdd16a8b481d1bb2031b7460736524",
"branch_name": "refs/heads/master",
"committer_date": "2015-04-22T18:59:20",
"content_id": "0941a70e8ee428a162eb396db34fd0847c631ad0",
"detected_licenses": [
"MIT"
],
"directory_id": "06af2542d5ea538e3b2d3dce9554bd815ec1f963",
"extension": "js",
"filename": "elements.js",
"fork_events_count": 2,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 34109494,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 10773,
"license": "MIT",
"license_type": "permissive",
"path": "/Gab.Blog/public/lib/angular-wysiwyg/src/elements.js",
"provenance": "stack-edu-0033.json.gz:711863",
"repo_name": "lurumad/gab2015",
"revision_date": "2015-04-22T18:59:20",
"revision_id": "c394be313c952e3a909663526b38269324514437",
"snapshot_id": "9a2cdd92ea0d4c65f001a49ccbf3dcf08905585e",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/lurumad/gab2015/c394be313c952e3a909663526b38269324514437/Gab.Blog/public/lib/angular-wysiwyg/src/elements.js",
"visit_date": "2016-09-09T17:34:10.078401",
"added": "2024-11-18T23:30:11.044053+00:00",
"created": "2015-04-22T18:59:20",
"int_score": 2,
"score": 2.46875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0051.json.gz"
}
|
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 13 01:54:35 2020
@author: willi
"""
import numpy as np
import math
import random
import copy
class Nodes:
def __init__(self, f, t):
self.arr = []
self.f = f
self.t = t
self.activation = None
self.dactivation = None
def println(self, label_type):
log(label_type(self.f), label_type(self.t))
i = 0
while i < len(self.arr):
log("node {} {}".format(i, self.activation), self.arr[i])
i += 1
def println_type(self, label_type):
log(label_type(self.f), label_type(self.t))
class Network:
def __init__(self, show_error = False):
self.links = []
self.input_size = 0
self.inputs = []
self.expected_outputs = []
self.learning = .05
self.outputs_derivate = []
self.sum_weights = []
self.bias = []
self.show_error = show_error
self.INPUT = 1
self.HIDDEN = 2
self.OUTPUT = 3
# temp arrays
self.nodes = None
self.weights = []
self.last_size = 0
# self.println()
def label_type(self, t):
if t == self.INPUT:
return "INPUT"
if t == self.HIDDEN:
return "HIDDEN"
return "OUTPUT"
def add(self, t, size, activation = None):
if t == self.INPUT:
self.input_size = size
elif t == self.OUTPUT:
self.new_layer_weights(self.HIDDEN, self.OUTPUT, self.last_size, size)
self.attachActivation(activation)
self.generate_bias(size)
else:
if len(self.links) == 0:
self.new_layer_weights(self.INPUT, self.HIDDEN, self.input_size, size)
else:
self.new_layer_weights(self.HIDDEN, self.HIDDEN, self.last_size, size)
self.attachActivation(activation)
self.generate_bias(size)
self.last_size = size
def attachActivation(self, activation):
if activation == "sigmoid":
self.nodes.activation = self.sigmoid
self.nodes.dactivation = self.dsigmoid
elif activation == "relu":
self.nodes.activation = self.relu
self.nodes.dactivation = self.drelu
elif activation == "lrelu":
self.nodes.activation = self.lrelu
self.nodes.dactivation = self.dlrelu
def newNodes(self, f, t):
self.nodes = Nodes(f, t)
def newWeights(self):
self.weights = []
def appendWeight(self, weight):
self.weights.append(weight)
def appendWeightsToNode(self):
self.nodes.arr.append(self.weights)
def appendNode(self):
self.links.append(self.nodes)
def leng_input(self):
return len(self.inputs[0])
def new_layer_weights(self, fr, t, qtd_from, qtd_to):
f = 0
self.newNodes(fr, t)
while f < qtd_from:
t = 0
self.newWeights()
while t < qtd_to:
self.appendWeight(random.random())
t += 1
self.appendWeightsToNode()
f += 1
self.appendNode()
def generate_bias(self, nodes):
i = 0
arr = []
while i < nodes:
arr.append(random.random())
i += 1
self.bias.append(arr)
def clear_vars(self):
self.sum_weights = []
self.outputs_derivate= []
for inp in self.links:
self.outputs_derivate.append([])
self.sum_weights.append(0)
def handle_input(self, inputs):
init = inputs
self.inputs.clear()
self.inputs.append(init)
def handle_expected_output(self, expected_outputs):
self.expected_outputs = expected_outputs
def train(self, inputs, expected_outputs):
self.feedfoword(inputs, expected_outputs)
self.backpropagation()
def predict(self, inputs, expected_outputs):
self.feedfoword(inputs, expected_outputs)
# log("Inputs", self.inputs[0])
log("Output", self.output())
def feedfoword(self, inputs, expected_outputs):
leng = len(self.links)
link = 0
self.clear_vars()
self.handle_input(inputs)
self.handle_expected_output(expected_outputs)
while link < leng:
self.inputs.append([])
if link < leng - 1:
out_size = len(self.links[link + 1].arr)
else:
out_size = len(self.expected_outputs)
out = 0
while out < out_size:
inp = 0
res = 0
while inp < len(self.inputs[link]):
res += self.inputs[link][inp] * self.links[link].arr[inp][out]
inp += 1
res = self.links[link].activation(res + self.bias[link][out])
self.inputs[len(self.inputs) - 1].append(res)
out += 1
link += 1
return self.output()
def backpropagation(self):
output_cost = 0
links_copy = copy.deepcopy(self.links)
bias_copy = copy.deepcopy(self.bias)
first = True
link = len(self.links) - 1
while link >= 0:
weights_sum = 0
for w_node in self.links[link].arr:
for w in w_node:
weights_sum += w
self.sum_weights[link] = weights_sum
link_out = link + 1
if first:
first = False
out = 0
res = 0
out_len = len(self.expected_outputs)
while out < out_len:
res += self.inputs[link_out][out] - self.expected_outputs[out]
out += 1
output_cost = res * 2
inputs_sum = 0
for inp in self.inputs[link]:
inputs_sum += inp
output = 0
while output < out_len:
output_derivate = self.links[link].dactivation(self.inputs[link_out][output])
self.outputs_derivate[link].append(output_derivate)
output += 1
node = 0
while node < len(self.links[link].arr):
output = 0
while output < out_len:
res = output_cost * self.outputs_derivate[link][output] * inputs_sum * self.learning
links_copy[link].arr[node][output] -= res
bias_copy[link][output] -= output_cost * self.outputs_derivate[link][output] * self.learning
output += 1
node += 1
else:
inputs_sum = 0
for inp in self.inputs[link]:
inputs_sum += inp
out_len = len(self.inputs[link_out])
output = 0
while output < out_len:
output_derivate = self.links[link].dactivation(self.inputs[link_out][output])
self.outputs_derivate[link].append(output_derivate)
output += 1
sum_weights = self.multiplication_sum_weights(link)
outputs_derivate = self.multiplication_outputs_derivate(link)
node = 0
while node < len(self.links[link].arr):
output = 0
while output < out_len:
res = output_cost * outputs_derivate * sum_weights * self.outputs_derivate[link][output] * inputs_sum * self.learning
links_copy[link].arr[node][output] -= res
bias_copy[link][output] -= output_cost * outputs_derivate * sum_weights * self.outputs_derivate[link][output] * self.learning
output += 1
node += 1
link -= 1
self.links = copy.deepcopy(links_copy)
self.bias = copy.deepcopy(bias_copy)
def output(self):
if self.show_error:
e = 0
i = 0
while i < len(self.expected_outputs):
e += self.inputs[len(self.inputs) - 1][i] - self.expected_outputs[i]
i += 1
log("Error", e)
return self.inputs[len(self.inputs) - 1]
def multiplication_sum_weights(self, link):
w = 1
actual_link = len(self.links) - 1
while actual_link > link:
w *= self.sum_weights[actual_link]
actual_link -= 1
return w
def multiplication_outputs_derivate(self, link):
d = 1
actual_link = len(self.links) - 1
while actual_link > link:
for derivate in self.outputs_derivate[actual_link]:
d *= derivate
actual_link -= 1
return d
def sigmoid(self, x):
return 1 / (1 + math.exp(-x))
def dsigmoid(self, x):
return x * (1 - x)
def relu(self, x, alpha = 0.01):
return np.maximum(alpha * x, x)
def drelu(self, x, alpha = 0.01):
return 1 if x > 0 else 0
def lrelu(self, x):
return np.tanh(x)
def dlrelu(self, x):
return 1 - x**2
def println(self):
log("INPUTS")
i = 0
while i < len(self.inputs):
log("input {}".format(i), self.inputs[i])
i += 1
for w in self.links:
w.println(self.label_type)
log("BIAS")
while i < len(self.bias):
log("bias {}".format(i), self.bias[i])
i += 1
log("EXPECTED OUTPUTS")
i = 0
while i < len(self.expected_outputs):
log("expected {}".format(i), self.expected_outputs[i])
i += 1
def log(t = '', m = ''):
print(t, m, end='\n\n')
|
8c8f03ec880d1d16fcac6dc08075feae4c29fc6c
|
{
"blob_id": "8c8f03ec880d1d16fcac6dc08075feae4c29fc6c",
"branch_name": "refs/heads/master",
"committer_date": "2020-11-09T09:36:22",
"content_id": "29331e7c8ff6986e93e0dc6c5519d08b1632e651",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "8d844a7fa7d8a7a377cda4e7df913d12ce07c4c5",
"extension": "py",
"filename": "network.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 241112264,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 10399,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/machine_learning/using network lib/lib/network.py",
"provenance": "stack-edu-0060.json.gz:390652",
"repo_name": "willigro/Self-Challenges",
"revision_date": "2020-11-09T09:36:22",
"revision_id": "67d35afebd9ac8acb910ec0af6ee217d55af40de",
"snapshot_id": "4109fe2bb10d89a7f65bb6d11879712ddce36ee2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/willigro/Self-Challenges/67d35afebd9ac8acb910ec0af6ee217d55af40de/machine_learning/using network lib/lib/network.py",
"visit_date": "2021-08-16T09:54:30.911250",
"added": "2024-11-19T01:31:59.375318+00:00",
"created": "2020-11-09T09:36:22",
"int_score": 3,
"score": 2.734375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0078.json.gz"
}
|
import copy
import logging
import os
import re
import time
import urllib.parse
from dataclasses import dataclass
from datetime import datetime
from enum import Enum, unique
from typing import Optional
from email.utils import parsedate_to_datetime
import requests
from mopidy_spotify import utils
logger = logging.getLogger(__name__)
def _trace(*args, **kwargs):
logger.log(utils.TRACE, *args, **kwargs)
class OAuthTokenRefreshError(Exception):
def __init__(self, reason):
message = f"OAuth token refresh failed: {reason}"
super().__init__(message)
class OAuthClientError(Exception):
pass
class OAuthClient:
def __init__(
self,
base_url,
refresh_url,
client_id=None,
client_secret=None,
proxy_config=None,
expiry_margin=60,
timeout=10,
retries=3,
retry_statuses=(500, 502, 503, 429),
):
if client_id and client_secret:
self._auth = (client_id, client_secret)
else:
self._auth = None
self._base_url = base_url
self._refresh_url = refresh_url
self._margin = expiry_margin
self._expires = 0
self._authorization_failed = False
self._timeout = timeout
self._number_of_retries = retries
self._retry_statuses = retry_statuses
self._backoff_factor = 0.5
self._headers = {"Content-Type": "application/json"}
self._session = utils.get_requests_session(proxy_config or {})
def get(self, path, cache=None, *args, **kwargs):
if self._authorization_failed:
logger.debug("Blocking request as previous authorization failed.")
return WebResponse(None, None)
params = kwargs.pop("params", None)
path = self._normalise_query_string(path, params)
_trace(f"Get '{path}'")
ignore_expiry = kwargs.pop("ignore_expiry", False)
if cache is not None and path in cache:
cached_result = cache.get(path)
if cached_result.still_valid(ignore_expiry):
return cached_result
kwargs.setdefault("headers", {}).update(cached_result.etag_headers)
# TODO: Factor this out once we add more methods.
# TODO: Don't silently error out.
try:
if self._should_refresh_token():
self._refresh_token()
except OAuthTokenRefreshError as e:
logger.error(e)
return WebResponse(None, None)
# Make sure our headers always override user supplied ones.
kwargs.setdefault("headers", {}).update(self._headers)
result = self._request_with_retries("GET", path, *args, **kwargs)
if result is None or "error" in result:
logger.error(
"Spotify Web API request failed: "
f"{result.get('error','Unknown') if result else 'Unknown'}"
)
return WebResponse(None, None)
if self._should_cache_response(cache, result):
previous_result = cache.get(path)
if previous_result and previous_result.updated(result):
result = previous_result
cache[path] = result
return result
def _should_cache_response(self, cache, response):
return cache is not None and response.status_ok
def _should_refresh_token(self):
# TODO: Add jitter to margin?
return not self._auth or time.time() > self._expires - self._margin
def _refresh_token(self):
logger.debug(f"Fetching OAuth token from {self._refresh_url}")
data = {"grant_type": "client_credentials"}
result = self._request_with_retries(
"POST", self._refresh_url, auth=self._auth, data=data
)
if result is None:
raise OAuthTokenRefreshError("Unknown error.")
elif result.get("error"):
raise OAuthTokenRefreshError(
f"{result['error']} {result.get('error_description', '')}"
)
elif not result.get("access_token"):
raise OAuthTokenRefreshError("missing access_token")
elif result.get("token_type") != "Bearer":
raise OAuthTokenRefreshError(
f"wrong token_type: {result.get('token_type')}"
)
self._headers["Authorization"] = f"Bearer {result['access_token']}"
self._expires = time.time() + result.get("expires_in", float("Inf"))
if result.get("expires_in"):
logger.debug(
f"Token expires in {result['expires_in']} seconds.",
)
if result.get("scope"):
logger.debug(f"Token scopes: {result['scope']}")
def _request_with_retries(self, method, url, *args, **kwargs):
prepared_request = self._session.prepare_request(
requests.Request(method, self._prepare_url(url, *args), **kwargs)
)
try_until = time.time() + self._timeout
result = None
backoff_time = 0
for i in range(self._number_of_retries):
remaining_timeout = max(try_until - time.time(), 1)
# Give up if we don't have any timeout left after sleeping.
if backoff_time > remaining_timeout:
break
elif backoff_time > 0:
time.sleep(backoff_time)
try:
response = self._session.send(
prepared_request, timeout=remaining_timeout
)
except requests.RequestException as e:
logger.debug(f"Fetching {prepared_request.url} failed: {e}")
status_code = None
backoff_time = 0
result = None
else:
status_code = response.status_code
backoff_time = self._parse_retry_after(response)
result = WebResponse.from_requests(prepared_request, response)
if status_code and 400 <= status_code < 600:
logger.debug(
f"Fetching {prepared_request.url} failed: {status_code}"
)
# Filter out cases where we should not retry.
if status_code and status_code not in self._retry_statuses:
break
# TODO: Provider might return invalid JSON for "OK" responses.
# This should really not happen, so ignoring for the purpose of
# retries. It would be easier if they correctly used 204, but
# instead some endpoints return 200 with no content, or true/false.
# Decide how long to sleep in the next iteration.
backoff_time = backoff_time or (2**i * self._backoff_factor)
logger.debug(
f"Retrying {prepared_request.url} in {backoff_time:.3f} "
"seconds."
)
if status_code == 401:
self._authorization_failed = True
logger.error(
"Authorization failed, not attempting Spotify API "
"request. Please get new credentials from "
"https://www.mopidy.com/authenticate and/or restart "
"Mopidy to resolve this problem."
)
return result
def _prepare_url(self, url, *args, **kwargs):
# TODO: Move this out as a helper and unit-test it directly?
b = urllib.parse.urlsplit(self._base_url)
u = urllib.parse.urlsplit(url.format(*args))
if u.scheme or u.netloc:
scheme, netloc, path = u.scheme, u.netloc, u.path
query = urllib.parse.parse_qsl(u.query, keep_blank_values=True)
else:
scheme, netloc = b.scheme, b.netloc
path = os.path.normpath(os.path.join(b.path, u.path))
query = urllib.parse.parse_qsl(b.query, keep_blank_values=True)
query.extend(
urllib.parse.parse_qsl(u.query, keep_blank_values=True)
)
for key, value in kwargs.items():
query.append((key, value))
encoded_query = urllib.parse.urlencode(dict(query))
return urllib.parse.urlunsplit(
(scheme, netloc, path, encoded_query, "")
)
def _normalise_query_string(self, url, params=None):
u = urllib.parse.urlsplit(url)
scheme, netloc, path = u.scheme, u.netloc, u.path
query = dict(urllib.parse.parse_qsl(u.query, keep_blank_values=True))
if isinstance(params, dict):
query.update(params)
sorted_unique_query = sorted(query.items())
encoded_query = urllib.parse.urlencode(sorted_unique_query)
return urllib.parse.urlunsplit(
(scheme, netloc, path, encoded_query, "")
)
def _parse_retry_after(self, response):
"""Parse Retry-After header from response if it is set."""
value = response.headers.get("Retry-After")
if not value:
seconds = 0
elif re.match(r"^\s*[0-9]+\s*$", value):
seconds = int(value)
else:
now = datetime.utcnow()
try:
date_tuple = parsedate_to_datetime(value)
seconds = (date_tuple - now).total_seconds()
except Exception:
seconds = 0
return max(0, seconds)
class WebResponse(dict):
def __init__(self, url, data, expires=0.0, etag=None, status_code=400):
self._from_cache = False
self.url = url
self._expires = expires
self._etag = etag
self._status_code = status_code
super().__init__(data or {})
_trace(f"New WebResponse {self}")
@classmethod
def from_requests(cls, request, response):
expires = cls._parse_cache_control(response)
etag = cls._parse_etag(response)
json = cls._decode(response)
return cls(request.url, json, expires, etag, response.status_code)
@staticmethod
def _decode(response):
# Deal with 204 and other responses with empty body.
if not response.content:
return None
try:
return response.json()
except ValueError as e:
url = response.request.url
logger.error(f"JSON decoding {url} failed: {e}")
return None
@staticmethod
def _parse_cache_control(response):
"""Parse Cache-Control header from response if it is set."""
value = response.headers.get("Cache-Control", "no-store").lower()
if "no-store" in value:
seconds = 0
else:
max_age = re.match(r".*max-age=\s*([0-9]+)\s*", value)
if not max_age:
seconds = 0
else:
seconds = int(max_age.groups()[0])
return time.time() + seconds
@staticmethod
def _parse_etag(response):
"""Parse ETag header from response if it is set."""
value = response.headers.get("ETag")
if value:
# 'W/' (case-sensitive) indicates that a weak validator is used,
# currently ignoring this.
# Format is string of ASCII characters placed between double quotes
# but can seemingly also include hyphen characters.
etag = re.match(r'^(W/)?("[!#-~]+")$', value)
if etag and len(etag.groups()) == 2:
return etag.groups()[1]
def still_valid(self, ignore_expiry=False):
if ignore_expiry:
result = True
status = "forced"
elif self._expires >= time.time():
result = True
status = "fresh"
else:
result = False
status = "expired"
self._from_cache = result
_trace("Cached data %s for %s", status, self)
return result
@property
def status_unchanged(self):
return self._from_cache or 304 == self._status_code
@property
def status_ok(self):
return self._status_code >= 200 and self._status_code < 400
@property
def etag_headers(self):
if self._etag is not None:
return {"If-None-Match": self._etag}
else:
return {}
def updated(self, response):
self._from_cache = False
if self._etag is None:
return False
elif self.url != response.url:
logger.error(f"ETag mismatch (different URI) for {self} {response}")
return False
elif not response.status_ok:
logger.debug(f"ETag mismatch (bad response) for {self} {response}")
return False
elif response._status_code != 304:
_trace(f"ETag mismatch for {self} {response}")
return False
_trace(f"ETag match for {self} {response}")
self._expires = response._expires
self._etag = response._etag
self._status_code = response._status_code
return True
def __str__(self):
return (
f"URL: {self.url} "
f"expires at: {datetime.fromtimestamp(self._expires)} "
f"[ETag: {self._etag}]"
)
def increase_expiry(self, delta_seconds):
if self.status_ok and not self._from_cache:
self._expires += delta_seconds
class SpotifyOAuthClient(OAuthClient):
TRACK_FIELDS = (
"next,items(track(type,uri,name,duration_ms,disc_number,track_number,"
"artists,album,is_playable,linked_from.uri))"
)
PLAYLIST_FIELDS = (
f"name,owner.id,type,uri,snapshot_id,tracks({TRACK_FIELDS}),"
)
DEFAULT_EXTRA_EXPIRY = 10
def __init__(self, *, client_id, client_secret, proxy_config):
super().__init__(
base_url="https://api.spotify.com/v1",
refresh_url="https://auth.mopidy.com/spotify/token",
client_id=client_id,
client_secret=client_secret,
proxy_config=proxy_config,
)
self.user_id = None
self._cache = {}
self._extra_expiry = self.DEFAULT_EXTRA_EXPIRY
def get_one(self, path, *args, **kwargs):
_trace(f"Fetching page {path!r}")
result = self.get(path, cache=self._cache, *args, **kwargs)
result.increase_expiry(self._extra_expiry)
return result
def get_all(self, path, *args, **kwargs):
while path is not None:
result = self.get_one(path, *args, **kwargs)
path = result.get("next")
yield result
def login(self):
self.user_id = self.get("me").get("id")
if self.user_id is None:
logger.error("Failed to load Spotify user profile")
return False
else:
logger.info(f"Logged into Spotify Web API as {self.user_id}")
return True
@property
def logged_in(self):
return self.user_id is not None
def get_user_playlists(self):
pages = self.get_all(
f"users/{self.user_id}/playlists", params={"limit": 50}
)
for page in pages:
yield from page.get("items", [])
def _with_all_tracks(self, obj, params=None):
if params is None:
params = {}
tracks_path = obj.get("tracks", {}).get("next")
track_pages = self.get_all(
tracks_path,
params=params,
ignore_expiry=obj.status_unchanged,
)
more_tracks = []
for page in track_pages:
if "items" not in page:
return {} # Return nothing on error, or what we have so far?
more_tracks += page["items"]
if more_tracks:
# Take a copy to avoid changing the cached response.
obj = copy.deepcopy(obj)
obj.setdefault("tracks", {}).setdefault("items", [])
obj["tracks"]["items"] += more_tracks
return obj
def get_playlist(self, uri):
try:
parsed = WebLink.from_uri(uri)
if parsed.type != LinkType.PLAYLIST:
raise ValueError(
f"Could not parse {uri!r} as a Spotify playlist URI"
)
except ValueError as exc:
logger.error(exc)
return {}
playlist = self.get_one(
f"playlists/{parsed.id}",
params={"fields": self.PLAYLIST_FIELDS, "market": "from_token"},
)
return self._with_all_tracks(playlist, {"fields": self.TRACK_FIELDS})
def get_album(self, web_link):
if web_link.type != LinkType.ALBUM:
logger.error("Expecting Spotify album URI")
return {}
album = self.get_one(
f"albums/{web_link.id}",
params={"market": "from_token"},
)
return self._with_all_tracks(album)
def get_artist_albums(self, web_link, all_tracks=True):
if web_link.type != LinkType.ARTIST:
logger.error("Expecting Spotify artist URI")
return []
pages = self.get_all(
f"artists/{web_link.id}/albums",
params={"market": "from_token", "include_groups": "single,album"},
)
for page in pages:
for album in page["items"]:
if all_tracks:
try:
web_link = WebLink.from_uri(album.get("uri"))
except ValueError as exc:
logger.error(exc)
continue
yield self.get_album(web_link)
else:
yield album
def get_artist_top_tracks(self, web_link):
if web_link.type != LinkType.ARTIST:
logger.error("Expecting Spotify artist URI")
return []
return self.get_one(
f"artists/{web_link.id}/top-tracks",
params={"market": "from_token"},
).get("tracks")
def get_track(self, web_link):
if web_link.type != LinkType.TRACK:
logger.error("Expecting Spotify track URI")
return {}
return self.get_one(
f"tracks/{web_link.id}", params={"market": "from_token"}
)
def clear_cache(self, extra_expiry=None):
self._cache.clear()
@unique
class LinkType(Enum):
TRACK = "track"
ALBUM = "album"
ARTIST = "artist"
PLAYLIST = "playlist"
YOUR = "your"
@dataclass
class WebLink:
uri: str
type: LinkType
id: Optional[str] = None
owner: Optional[str] = None
@classmethod
def from_uri(cls, uri):
parsed_uri = urllib.parse.urlparse(uri)
schemes = ("http", "https")
netlocs = ("open.spotify.com", "play.spotify.com")
if parsed_uri.scheme == "spotify":
parts = parsed_uri.path.split(":")
elif parsed_uri.scheme in schemes and parsed_uri.netloc in netlocs:
parts = parsed_uri.path[1:].split("/")
else:
parts = []
# Strip out empty parts to ensure we are strict about URI parsing.
parts = [p for p in parts if p.strip()]
if len(parts) == 2 and parts[0] in (
"track",
"album",
"artist",
"playlist",
):
return cls(uri, LinkType(parts[0]), parts[1], None)
elif len(parts) == 2 and parts[0] == "your":
return cls(uri, LinkType(parts[0]))
elif len(parts) == 3 and parts[0] == "user" and parts[2] == "starred":
if parsed_uri.scheme == "spotify":
return cls(uri, LinkType.PLAYLIST, None, parts[1])
elif len(parts) == 3 and parts[0] == "playlist":
return cls(uri, LinkType.PLAYLIST, parts[2], parts[1])
elif len(parts) == 4 and parts[0] == "user" and parts[2] == "playlist":
return cls(uri, LinkType.PLAYLIST, parts[3], parts[1])
raise ValueError(f"Could not parse {uri!r} as a Spotify URI")
class WebError(Exception):
def __init__(self, message):
super().__init__(message)
|
c50a7f37ffd62c83944cf7a22f9af915d64dbffa
|
{
"blob_id": "c50a7f37ffd62c83944cf7a22f9af915d64dbffa",
"branch_name": "refs/heads/main",
"committer_date": "2023-06-21T21:34:23",
"content_id": "a937d06126ec989c374ff9294f9469837f6cdb9f",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "e3a87f6c0afa04af7db9fb811f3abe90934722f4",
"extension": "py",
"filename": "web.py",
"fork_events_count": 126,
"gha_created_at": "2013-10-08T20:30:02",
"gha_event_created_at": "2023-06-21T21:34:25",
"gha_language": "Python",
"gha_license_id": "Apache-2.0",
"github_id": 13424771,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 19907,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/mopidy_spotify/web.py",
"provenance": "stack-edu-0057.json.gz:318393",
"repo_name": "mopidy/mopidy-spotify",
"revision_date": "2023-06-21T21:34:23",
"revision_id": "a82e1b2016dbfeddb4ac9c6027c2cdaf0331b9b1",
"snapshot_id": "6fdc4b01289909c8a32ebcb4a19974e7e1f9549a",
"src_encoding": "UTF-8",
"star_events_count": 918,
"url": "https://raw.githubusercontent.com/mopidy/mopidy-spotify/a82e1b2016dbfeddb4ac9c6027c2cdaf0331b9b1/mopidy_spotify/web.py",
"visit_date": "2023-07-19T11:18:45.874684",
"added": "2024-11-18T21:46:35.411569+00:00",
"created": "2023-06-21T21:34:23",
"int_score": 2,
"score": 2.1875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0075.json.gz"
}
|
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013, 2014 Damien P. George
* Copyright (c) 2019 Analog Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "py/runtime.h"
#include "py/mphal.h"
#include "systick.h"
#include "modmachine.h"
#include <services/tmr/adi_tmr.h>
#define SYSTICK_TMR_ID 0
#define MAX_REGISTERED_CALLBACKS 3
volatile uint64_t system_milliticks = 0;
ADI_TMR_HANDLE timer_handle;
uint8_t timer_instance_memory[ADI_TMR_MEMORY];
uint32_t us_divider;
CALLBACK_HANDLER systick_callbacks[MAX_REGISTERED_CALLBACKS];
static void systemtimer_handler(void *pCBParam,
uint32_t Event,
void *pArg) {
switch (Event)
{
case ADI_TMR_EVENT_DATA_INT:
system_milliticks++;
// If a user callback has been set for the 1ms tick event, call it
for (int i = 0; i < MAX_REGISTERED_CALLBACKS; i++) {
if (systick_callbacks[i] != NULL) {
systick_callbacks[i](system_milliticks);
}
}
break;
default:
break;
}
}
void sys_tick_init() {
uint32_t fsclk0 = machine_get_fsclk0();
for (int i = 0; i < MAX_REGISTERED_CALLBACKS; i++) {
systick_callbacks[i] = NULL;
}
// Initialize 1ms timer
if (adi_tmr_Open(SYSTICK_TMR_ID,
timer_instance_memory,
ADI_TMR_MEMORY,
systemtimer_handler,
NULL,
&timer_handle) != ADI_TMR_SUCCESS) {
mp_raise_msg(&mp_type_RuntimeError, "Error initializing timer.");
}
// Set the mode to PWM OUT
if (adi_tmr_SetMode(timer_handle, ADI_TMR_MODE_CONTINUOUS_PWMOUT) != ADI_TMR_SUCCESS) {
mp_raise_msg(&mp_type_RuntimeError, "Error setting the timer mode.");
}
// Set the IRQ mode to get interrupt after timer counts to Delay + Width
if (adi_tmr_SetIRQMode(timer_handle, ADI_TMR_IRQMODE_WIDTH_DELAY) != ADI_TMR_SUCCESS) {
mp_raise_msg(&mp_type_RuntimeError, "Error setting the timer IRQ mode.");
}
// Set the Period - once per ms
if (adi_tmr_SetPeriod(timer_handle, fsclk0 / 1000) != ADI_TMR_SUCCESS) {
mp_raise_msg(&mp_type_RuntimeError, "Error setting the timer period.");
}
// Set the timer width
if (adi_tmr_SetWidth(timer_handle, fsclk0 / 1000 / 2 - 1) != ADI_TMR_SUCCESS) {
mp_raise_msg(&mp_type_RuntimeError, "Error setting the timer width.");
}
// Set the timer delay
if (adi_tmr_SetDelay(timer_handle, fsclk0 / 1000 / 2) != ADI_TMR_SUCCESS) {
mp_raise_msg(&mp_type_RuntimeError, "Error setting the timer delay.");
}
// Enable the timer
if ((adi_tmr_Enable(timer_handle, true)) != ADI_TMR_SUCCESS) {
mp_raise_msg(&mp_type_RuntimeError, "Error enabling the timer.");
}
// This is used to calculate the us tick
us_divider = fsclk0 / 1000000;
}
void sys_tick_set_callback(CALLBACK_HANDLER callback) {
// If a callback has been provided to be called when a 1ms tick event occurs, set it here
for (int i = 0; i < MAX_REGISTERED_CALLBACKS; i++) {
if (systick_callbacks[i] == NULL) {
systick_callbacks[i] = callback;
break;
}
}
}
void sys_tick_disable_irq(void) {
adi_tmr_EnableDataInt(timer_handle, false);
}
void sys_tick_enable_irq(void) {
adi_tmr_EnableDataInt(timer_handle, true);
}
// Core delay function that does an efficient sleep and may switch thread context.
// If IRQs are enabled then we must have the GIL.
void mp_hal_delay_ms(mp_uint_t Delay) {
// if (query_irq() == IRQ_STATE_ENABLED) {
// IRQs enabled, so can use systick counter to do the delay
uint64_t start = system_milliticks;
// Wraparound of tick is taken care of by 2's complement arithmetic.
while (system_milliticks - start < Delay) {
// This macro will execute the necessary idle behaviour. It may
// raise an exception, switch threads or enter sleep mode (waiting for
// (at least) the SysTick interrupt).
//MICROPY_EVENT_POLL_HOOK
__asm("nop");
}
/* } else {
// IRQs disabled, so need to use a busy loop for the delay.
// To prevent possible overflow of the counter we use a double loop.
const uint32_t count_1ms = HAL_RCC_GetSysClockFreq() / 4000;
for (int i = 0; i < Delay; i++) {
for (uint32_t count = 0; ++count <= count_1ms;) {
}
}
}*/
}
// delay for given number of microseconds
void mp_hal_delay_us(mp_uint_t usec) {
// if (query_irq() == IRQ_STATE_ENABLED) {
// IRQs enabled, so can use systick counter to do the delay
uint64_t start = mp_hal_ticks_us();
while (mp_hal_ticks_us() - start < usec) {
}
/* } else {
// IRQs disabled, so need to use a busy loop for the delay
// sys freq is always a multiple of 2MHz, so division here won't lose precision
const uint32_t ucount = HAL_RCC_GetSysClockFreq() / 2000000 * usec / 2;
for (uint32_t count = 0; ++count <= ucount;) {
}
}*/
}
bool sys_tick_has_passed(uint32_t start_tick, uint32_t delay_ms) {
return system_milliticks - start_tick >= delay_ms;
}
// waits until at least delay_ms milliseconds have passed from the sampling of
// startTick. Handles overflow properly. Assumes stc was taken from
// HAL_GetTick() some time before calling this function.
void sys_tick_wait_at_least(uint32_t start_tick, uint32_t delay_ms) {
while (!sys_tick_has_passed(start_tick, delay_ms)) {
__WFI(); // enter sleep mode, waiting for interrupt
}
}
mp_uint_t mp_hal_ticks_ms(void) {
return system_milliticks;
}
mp_uint_t mp_hal_ticks_us(void) {
// use current count to determine us inside one ms
uint32_t raw_count;
// STW to avoid interrupt between 2 reads
adi_tmr_Enable(timer_handle, false);
adi_tmr_GetCount(timer_handle, &raw_count);
// prevent optimization
volatile uint32_t ticks = system_milliticks * 1000 + raw_count / us_divider;
adi_tmr_Enable(timer_handle, true);
return ticks;
}
|
89282970515bce293f16c4b4983d8bf80011604a
|
{
"blob_id": "89282970515bce293f16c4b4983d8bf80011604a",
"branch_name": "refs/heads/master",
"committer_date": "2019-07-25T18:21:35",
"content_id": "5091889dec609866c28b49dabaa1c141103b029c",
"detected_licenses": [
"BSD-3-Clause-Clear",
"MIT"
],
"directory_id": "3b87e5b7b2dd6680fd3324f2eb5a65d9dded9266",
"extension": "c",
"filename": "systick.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7340,
"license": "BSD-3-Clause-Clear,MIT",
"license_type": "permissive",
"path": "/ports/sc5xx/systick.c",
"provenance": "stack-edu-0000.json.gz:497824",
"repo_name": "sedurCode/micropython",
"revision_date": "2019-07-25T18:21:35",
"revision_id": "b17791276de4a4ccf1d14e96b80b0c13d53a8d0f",
"snapshot_id": "3fa733364d911a262d06a6b324963f7a5d7bbcd9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/sedurCode/micropython/b17791276de4a4ccf1d14e96b80b0c13d53a8d0f/ports/sc5xx/systick.c",
"visit_date": "2023-03-16T15:36:57.025318",
"added": "2024-11-18T23:25:18.425661+00:00",
"created": "2019-07-25T18:21:35",
"int_score": 2,
"score": 2.0625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0018.json.gz"
}
|
<?php
/**
* A Phing task to run Behat commands.
*/
require_once 'phing/Task.php';
/**
* A Behat task. Runs behavior-driven development tests against a codebase.
*
* @author Adam Malone <adam@adammalone.net>
*/
class BehatTask extends Task
{
protected $file; // the source file (from xml attribute)
protected $filesets = array(); // all fileset objects assigned to this task
/**
* Path the the Behat executable.
*
* @var string
*/
protected $executable = 'behat';
/**
* Optional path(s) to execute.
*
* @var null
*/
protected $path = null;
/**
* Specify config file to use.
*
* @var null
*/
protected $config = null;
/**
* Only executeCall the feature elements which match part
* of the given name or regex.
*
* @var null
*/
protected $name = null;
/**
* Only executeCall the features or scenarios with tags
* matching tag filter expression.
*
* @var null
*/
protected $tags = null;
/**
* Only executeCall the features with actor role matching
* a wildcard.
*
* @var null
*/
protected $role = null;
/**
* Specify config profile to use.
*
* @var null
*/
protected $profile = null;
/**
* Only execute a specific suite.
*
* @var null
*/
protected $suite = null;
/**
* Passes only if all tests are explicitly passing.
*
* @var bool
*/
protected $strict = false;
/**
* Increase verbosity of exceptions.
*
* @var bool
*/
protected $verbose = false;
/**
* Force ANSI color in the output.
*
* @var bool
*/
protected $colors = true;
/**
* Invokes formatters without executing the tests and hooks.
*
* @var bool
*/
protected $dryRun = false;
/**
* Stop processing on first failed scenario.
*
* @var bool
*/
protected $haltonerror = false;
/**
* The output logs to be returned.
*
* @var null
*/
protected $output_property = null;
/**
* The return value.
*
* @var null
*/
protected $return_property = null;
/**
* All Behat options to be used to create the command.
*
* @var array
*/
protected $options = array();
/**
* Set the path to the Behat executable.
*
* @param string $str The executable
*
* @return void
*/
public function setExecutable($str)
{
$this->executable = $str;
}
/**
* Set the path to features to test.
*
* @param string $path The path to features.
*
* @return void
*/
public function setPath($path)
{
$this->path = $path;
}
/**
* Sets the Behat config file to use.
*
* @param string $config The config file
*
* @return void
*/
public function setConfig($config)
{
$this->config = $config;
}
/**
* Sets the name of tests to run.
*
* @param string $name The feature name to match
*
* @return void
*/
public function setName($name)
{
$this->name = $name;
}
/**
* Sets the test tags to use.
*
* @param string $tags The tag(s) to use
*
* @return void
*/
public function setTags($tags)
{
$this->tags = $tags;
}
/**
* Sets the role able to run tests.
*
* @param string $role The actor role to match.
*
* @return void
*/
public function setRole($role)
{
$this->role = $role;
}
/**
* Set the profile to use for tests.
*
* @param string $profile The profile to use.
*
* @return void
*/
public function setProfile($profile)
{
$this->profile = $profile;
}
/**
* Set the test suite to use.
*
* @param string $suite The suite to use.
*
* @return void
*/
public function setSuite($suite)
{
$this->suite = $suite;
}
/**
* Sets the flag if strict testing should be enabled.
*
* @param bool $strict Behat strict mode.
*
* @return void
*/
public function setStrict($strict)
{
$this->strict = StringHelper::booleanValue($strict);
}
/**
* Sets the flag if a verbose output should be used.
*
* @param bool $verbose Use verbose output.
*
* @return void
*/
public function setVerbose($verbose)
{
$this->verbose = StringHelper::booleanValue($verbose);
}
/**
* Either force ANSI colors on or off.
*
* @param bool $colors Use ANSI colors.
*
* @return void
*/
public function setColors($colors)
{
$this->colors = StringHelper::booleanValue($colors);
}
/**
* Invokes test formatters without running tests against a site.
*
* @param bool $dryrun Run without testing.
*
* @return void
*/
public function setDryRun($dryrun)
{
$this->dryRun = StringHelper::booleanValue($dryrun);
}
/**
* Sets the flag if test execution should stop in the event of a failure.
*
* @param bool $stop If all tests should stop on failure.
*
* @return void
*/
public function setHaltonerror($stop)
{
$this->haltonerror = StringHelper::booleanValue($stop);
}
/**
* The Phing property output should be assigned to.
*
* @param string $str The Phing property.
*
* @return void
*/
public function setOutputProperty($str)
{
$this->output_property = $str;
}
/**
* The Phing property the return code should be assigned to.
*
* @param string $str The Phing property.
*
* @return void
*/
public function setReturnProperty($str)
{
$this->return_property = $str;
}
/**
* Rejigs the options array into a meaningful string of
* command line arguments.
*
* @param mixed $name The option name
* @param string $value The option value
*
* @return string
*/
protected function createOption($name, $value)
{
if (is_numeric($name)) {
return '--'.$value;
}
return '--'.$name.'='.$value;
}
/**
* Checks if the Behat executable exists.
*
* @param string $executable The path to Behat
*
* @return bool
*/
protected function behatExists($executable)
{
// First check if the executable path is a file.
if (is_file($executable)) {
return true;
}
// Now check to see if the executable has a path.
$return = shell_exec('type '.escapeshellarg($executable));
return (empty($return) ? false : true);
}
/**
* The main entry point method.
*
* @throws BuildException
* @return bool $return
*/
public function main()
{
$command = array();
if (!$this->behatExists($this->executable)) {
throw new BuildException(
'ERROR: the Behat executable "'.$this->executable.'" does not exist.',
$this->getLocation()
);
}
$command[] = $this->executable;
if ($this->path) {
if (!file_exists($this->path)) {
throw new BuildException(
'ERROR: the "'.$this->path.'" path does not exist.',
$this->getLocation()
);
}
}
$command[] = !empty($this->path) ? $this->path : '';
if ($this->config) {
if (!file_exists($this->config)) {
throw new BuildException(
'ERROR: the "'.$this->config.'" config file does not exist.',
$this->getLocation()
);
}
$this->options['config'] = $this->config;
}
if ($this->name) {
$this->options['name'] = $this->name;
}
if ($this->tags) {
$this->options['tags'] = $this->tags;
}
if ($this->role) {
$this->options['role'] = $this->role;
}
if ($this->profile) {
$this->options['profile'] = $this->profile;
}
if ($this->suite) {
$this->options['suite'] = $this->suite;
}
if ($this->strict) {
$this->options[] = 'strict';
}
if ($this->verbose) {
$this->options[] = 'verbose';
}
if (!$this->colors) {
$this->options[] = 'no-colors';
}
if ($this->dryRun) {
$this->options[] = 'dry-run';
}
if ($this->haltonerror) {
$this->options[] = 'stop-on-failure';
}
// Contract all options into the form Behat expects.
foreach ($this->options as $name => $value) {
$command[] = $this->createOption($name, $value);
}
$command = implode(' ', $command);
$this->log("Running '$command'");
// Run Behat.
$output = array();
exec($command, $output, $return);
// Collect Behat output for display through the Phing log.
foreach ($output as $line) {
$this->log($line);
}
// Return the output into a Phing property if specified.
if (!empty($this->output_property)) {
$this->getProject()
->setProperty($this->output_property, implode("\n", $output));
}
// Return the Behat exit value to a Phing property if specified.
if (!empty($this->return_property)) {
$this->getProject()
->setProperty($this->return_property, $return);
}
// Throw an exception if Behat fails.
if ($this->haltonerror && $return != 0) {
throw new BuildException("Behat exited with code $return");
}
return $return != 0;
}
}
|
7258d3b5af37354142da62dc0fb437f282b86166
|
{
"blob_id": "7258d3b5af37354142da62dc0fb437f282b86166",
"branch_name": "refs/heads/master",
"committer_date": "2019-04-24T23:10:02",
"content_id": "a929fc4d76db2581d767b106b60557b2fc74c611",
"detected_licenses": [
"MIT"
],
"directory_id": "af9c3b67e4464efc303705c744f1ba6e6a1be77b",
"extension": "php",
"filename": "BehatTask.php",
"fork_events_count": 0,
"gha_created_at": "2018-04-03T22:12:40",
"gha_event_created_at": "2019-07-11T16:15:32",
"gha_language": "PHP",
"gha_license_id": "MIT",
"github_id": 127974510,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 9036,
"license": "MIT",
"license_type": "permissive",
"path": "/build/phingcludes/BehatTask.php",
"provenance": "stack-edu-0049.json.gz:105362",
"repo_name": "tobybellwood/govcms-composer-test",
"revision_date": "2019-04-24T23:10:02",
"revision_id": "9c533963f1d1edea23846b917cc3c6963b9a3a83",
"snapshot_id": "8f4f902433c5dd45922ea8192cff0b2e408f4286",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/tobybellwood/govcms-composer-test/9c533963f1d1edea23846b917cc3c6963b9a3a83/build/phingcludes/BehatTask.php",
"visit_date": "2020-03-08T06:33:02.476779",
"added": "2024-11-19T01:09:41.451179+00:00",
"created": "2019-04-24T23:10:02",
"int_score": 3,
"score": 2.921875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0067.json.gz"
}
|
package marathons.topcoder.pathDefense;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.security.SecureRandom;
import java.util.*;
import java.util.List;
import java.util.concurrent.Callable;
class CreepType {
public static final int MIN_CREEP_HEALTH = 1;
public static final int MAX_CREEP_HEALTH = 20;
public static final int MIN_CREEP_MONEY = 1;
public static final int MAX_CREEP_MONEY = 20;
int health;
int money;
public CreepType(Random rnd) {
health = rnd.nextInt(MAX_CREEP_HEALTH - MIN_CREEP_HEALTH + 1) + MIN_CREEP_HEALTH;
money = rnd.nextInt(MAX_CREEP_MONEY - MIN_CREEP_MONEY + 1) + MIN_CREEP_MONEY;
}
}
class Creep {
int id;
int health;
int x, y;
int spawnTime;
ArrayList<Integer> moves = new ArrayList<Integer>();
}
class TowerType {
public static final int MIN_TOWER_RANGE = 1;
public static final int MAX_TOWER_RANGE = 5;
public static final int MIN_TOWER_DAMAGE = 1;
public static final int MAX_TOWER_DAMAGE = 5;
public static final int MIN_TOWER_COST = 5;
public static final int MAX_TOWER_COST = 40;
int range;
int damage;
int cost;
public TowerType(Random rnd) {
range = rnd.nextInt(MAX_TOWER_RANGE - MIN_TOWER_RANGE + 1) + MIN_TOWER_RANGE;
damage = rnd.nextInt(MAX_TOWER_DAMAGE - MIN_TOWER_DAMAGE + 1) + MIN_TOWER_DAMAGE;
cost = rnd.nextInt(MAX_TOWER_COST - MIN_TOWER_COST + 1) + MIN_TOWER_COST;
}
}
class Tower {
int x, y;
int type;
}
class AttackVis {
int x1, y1, x2, y2;
public AttackVis(int _x1, int _y1, int _x2, int _y2) {
x1 = _x1;
y1 = _y1;
x2 = _x2;
y2 = _y2;
}
}
class TestCase {
public static final int MIN_CREEP_COUNT = 500;
public static final int MAX_CREEP_COUNT = 2000;
public static final int MIN_TOWER_TYPES = 1;
public static final int MAX_TOWER_TYPES = 20;
public static final int MIN_BASE_COUNT = 1;
public static final int MAX_BASE_COUNT = 8;
public static final int MIN_WAVE_COUNT = 1;
public static final int MAX_WAVE_COUNT = 15;
public static final int MIN_BOARD_SIZE = 20;
public static final int MAX_BOARD_SIZE = 60;
public int boardSize;
public int money;
public CreepType creepType;
public int towerTypeCnt;
public TowerType[] towerTypes;
public char[][] board;
public int pathCnt;
public int[] spawnX;
public int[] spawnY;
public int[][] boardPath;
public int tx, ty;
public int baseCnt;
public int[] baseX;
public int[] baseY;
public int creepCnt;
public Creep[] creeps;
public int waveCnt;
public SecureRandom rnd = null;
public void connect(Random random, int x1, int y1, int x2, int y2) {
while (x1!=x2 || y1!=y2) {
if (board[y1][x1]>='0' && board[y1][x1]<='9') return;
board[y1][x1] = '.';
int x1_ = x1;
int y1_ = y1;
if (x1==x2) {
if (y2>y1) {
y1++;
} else {
y1--;
}
} else if (y1==y2) {
if (x2>x1) {
x1++;
} else {
x1--;
}
} else {
int nx = x1;
int ny = y1;
if (x2>x1) nx++; else nx--;
if (y2>y1) ny++; else ny--;
if (board[ny][x1]=='.') { y1 = ny; }
else if (board[y1][nx]=='.') { x1 = nx; }
else {
if (random.nextInt(2)==0)
y1 = ny;
else
x1 = nx;
}
}
if (x1>x1_) boardPath[y1_][x1_] |= 8;
else if (x1<x1_) boardPath[y1_][x1_] |= 2;
else if (y1>y1_) boardPath[y1_][x1_] |= 1;
else if (y1<y1_) boardPath[y1_][x1_] |= 4;
}
}
public void addPath(Random random, int baseIdx) {
int sx=0,sy=0;
boolean nextTo = false;
int tryEdge = 0;
do
{
tryEdge++;
if (tryEdge>boardSize) break;
nextTo = false;
sx = random.nextInt(boardSize-1)+1;
if (random.nextInt(2)==0) {
sy = random.nextInt(2)*(boardSize-1);
if (sx>0 && board[sy][sx-1]=='.') nextTo = true;
if (sx+1<boardSize && board[sy][sx+1]=='.') nextTo = true;
} else
{
sy = sx;
sx = random.nextInt(2)*(boardSize-1);
if (sy>0 && board[sy-1][sx]=='.') nextTo = true;
if (sy+1<boardSize && board[sy+1][sx]=='.') nextTo = true;
}
} while (nextTo || board[sy][sx]!='#');
if (tryEdge>boardSize) return;
board[sy][sx] = '.';
spawnX[baseIdx] = sx;
spawnY[baseIdx] = sy;
if (sx==0) { boardPath[sy][sx] |= 8; sx++; }
else if (sy==0) { boardPath[sy][sx] |= 1; sy++; }
else if (sx==boardSize-1) { boardPath[sy][sx] |= 2; sx--; }
else { boardPath[sy][sx] |= 4; sy--; }
int b = baseIdx%baseCnt;
if (baseIdx>=baseCnt) b = random.nextInt(baseCnt);
connect(random, sx, sy, baseX[b], baseY[b]);
}
public TestCase(long seed) {
try {
rnd = SecureRandom.getInstance("SHA1PRNG");
} catch (Exception e) {
System.err.println("ERROR: unable to generate test case.");
System.exit(1);
}
rnd.setSeed(seed);
boolean genDone = true;
do {
boardSize = rnd.nextInt(MAX_BOARD_SIZE - MIN_BOARD_SIZE + 1) + MIN_BOARD_SIZE;
if (seed==1) boardSize = 20;
board = new char[boardSize][boardSize];
boardPath = new int[boardSize][boardSize];
creepType = new CreepType(rnd);
towerTypeCnt = rnd.nextInt(MAX_TOWER_TYPES - MIN_TOWER_TYPES + 1) + MIN_TOWER_TYPES;
towerTypes = new TowerType[towerTypeCnt];
money = 0;
for (int i = 0; i < towerTypeCnt; i++) {
towerTypes[i] = new TowerType(rnd);
money += towerTypes[i].cost;
}
baseCnt = rnd.nextInt(MAX_BASE_COUNT - MIN_BASE_COUNT + 1) + MIN_BASE_COUNT;
for (int y=0;y<boardSize;y++) {
for (int x=0;x<boardSize;x++) {
board[y][x] = '#';
boardPath[y][x] = 0;
}
}
baseX = new int[baseCnt];
baseY = new int[baseCnt];
for (int i=0;i<baseCnt;i++) {
int bx,by;
do
{
bx = rnd.nextInt(boardSize-8)+4;
by = rnd.nextInt(boardSize-8)+4;
} while (board[by][bx]!='#');
board[by][bx] = (char)('0'+i);
baseX[i] = bx;
baseY[i] = by;
}
pathCnt = rnd.nextInt(baseCnt*10 - baseCnt + 1) + baseCnt;
spawnX = new int[pathCnt];
spawnY = new int[pathCnt];
for (int i=0;i<pathCnt;i++) {
addPath(rnd, i);
}
creepCnt = rnd.nextInt(MAX_CREEP_COUNT - MIN_CREEP_COUNT + 1) + MIN_CREEP_COUNT;
if (seed==1) creepCnt = MIN_CREEP_COUNT;
creeps = new Creep[creepCnt];
for (int i=0;i<creepCnt;i++) {
Creep c = new Creep();
int j = rnd.nextInt(pathCnt);
c.x = spawnX[j];
c.y = spawnY[j];
c.id = i;
c.spawnTime = rnd.nextInt(PathDefense.SIMULATION_TIME);
c.health = creepType.health * (1<<(c.spawnTime / PathDefense.DOUBLING_TIME));
creeps[i] = c;
}
// waves
waveCnt = rnd.nextInt(MAX_WAVE_COUNT - MIN_WAVE_COUNT + 1) + MIN_WAVE_COUNT;
int wi = 0;
for (int w=0;w<waveCnt;w++) {
int wavePath = rnd.nextInt(pathCnt);
int waveSize = 5+rnd.nextInt(creepCnt/20);
int waveStartT = rnd.nextInt(PathDefense.SIMULATION_TIME-waveSize);
for (int i=0;i<waveSize;i++) {
if (wi>=creepCnt) break;
creeps[wi].x = spawnX[wavePath];
creeps[wi].y = spawnY[wavePath];
creeps[wi].spawnTime = waveStartT + rnd.nextInt(waveSize);
creeps[wi].health = creepType.health * (1<<(creeps[wi].spawnTime / PathDefense.DOUBLING_TIME));
wi++;
}
if (wi>=creepCnt) break;
}
// determine paths for each creep
genDone = true;
for (Creep c :creeps) {
c.moves.clear();
int x = c.x;
int y = c.y;
int prevx = -1;
int prevy = -1;
int tryPath = 0;
while (!(board[y][x]>='0' && board[y][x]<='9')) {
int dir = 0;
tryPath++;
if (tryPath>boardSize*boardSize) break;
// select a random direction that will lead to a base, don't go back to where the creep was in the previous time step
int tryDir = 0;
do
{
if (tryDir==15) { tryDir = -1; break; }
dir = rnd.nextInt(4);
tryDir |= (1<<dir);
} while ((boardPath[y][x]&(1<<dir))==0 ||
(x+PathDefense.DX[dir]==prevx && y+PathDefense.DY[dir]==prevy));
if (tryDir<0) break;
c.moves.add(dir);
prevx = x;
prevy = y;
x += PathDefense.DX[dir];
y += PathDefense.DY[dir];
}
if (!(board[y][x]>='0' && board[y][x]<='9')) {
genDone = false;
break;
}
}
} while (!genDone);
}
}
@SuppressWarnings("serial")
class Drawer extends JFrame {
public World world;
public DrawerPanel panel;
public int cellSize, boardSize;
public int width, height;
public boolean pauseMode = false;
public boolean stepMode = false;
public boolean debugMode = false;
class DrawerKeyListener extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e) {
synchronized (keyMutex) {
if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
Drawer.this.dispose();
}
if (e.getKeyChar() == 'q') {
Drawer.this.dispose();
PathDefense._vis = false;
}
if (e.getKeyChar() == '[') {
PathDefense._speed /= 2;
}
if (e.getKeyChar() == ']') {
PathDefense._speed *= 2;
}
if (e.getKeyChar() == ' ') {
pauseMode = !pauseMode;
}
if (e.getKeyChar() == 'd') {
debugMode = !debugMode;
}
if (e.getKeyChar() == 's') {
stepMode = !stepMode;
}
keyPressed = true;
keyMutex.notifyAll();
}
}
}
class DrawerPanel extends JPanel {
@Override
public void paint(Graphics g) {
synchronized (world.worldLock) {
int cCnt[][] = new int[boardSize][boardSize];
double m = (PathDefenseVis.pathDefense.move % PathDefense.DOUBLING_TIME) * 1.0 / PathDefense.DOUBLING_TIME;
g.setColor(new Color(0,(int) (128 * (1 - m)),(int) (128 * m)));
g.fillRect(15, 15, cellSize * boardSize + 1, cellSize * boardSize + 1);
g.setColor(Color.BLACK);
for (int i = 0; i <= boardSize; i++) {
g.drawLine(15 + i * cellSize, 15, 15 + i * cellSize, 15 + cellSize * boardSize);
g.drawLine(15, 15 + i * cellSize, 15 + cellSize * boardSize, 15 + i * cellSize);
}
for (int i=0; i < boardSize; i++) {
for (int j=0; j < boardSize; j++) {
if (world.tc.board[i][j]=='.') {
cCnt[i][j] = 0;
// int wc = PathDefenseVis.pathDefense.dirLeadsToBase[i][j] * 15;
int swc = PathDefenseVis.pathDefense.simWalkingCount[i][j] * 3 / 2;
swc = Math.min(swc, 255);
g.setColor(new Color(swc, swc, swc));
g.fillRect(15 + j * cellSize + 1, 15 + i * cellSize + 1, cellSize - 1, cellSize - 1);
int mawc = Math.max(PathDefenseVis.pathDefense.maxActualWalkingCount, 1);
int awc = PathDefenseVis.pathDefense.actualWalkingCount[i][j] * 255 / mawc;
awc = Math.min(awc, 255);
g.setColor(new Color(awc, awc, awc));
g.fillRect(15 + j * cellSize + 1, 15 + i * cellSize + 1, cellSize - 1, cellSize / 3 - 1);
}
}
}
g.setColor(Color.WHITE);
for (int i=0; i < boardSize; i++) {
for (int j=0; j < boardSize; j++) {
if (world.tc.board[i][j]>='0' && world.tc.board[i][j]<='9') {
g.fillRect(15 + j * cellSize + 1, 15 + i * cellSize + 1, cellSize - 1, cellSize - 1);
}
}
}
// draw the health of each base
for (int b=0;b<world.tc.baseCnt;b++) {
int col = world.baseHealth[b]*255/PathDefense.INITIAL_BASE_HEALTH;
g.setColor(new Color(col, col, col));
g.fillRect(15 + world.tc.baseX[b] * cellSize + 1+cellSize/4, 15 + world.tc.baseY[b] * cellSize + 1+cellSize/4, cellSize/2 - 1, cellSize/2 - 1);
}
for (int i=0; i < boardSize; i++) {
for (int j=0; j < boardSize; j++) {
if (world.tc.board[i][j]>='A') {
int ttype = world.tc.board[i][j]-'A';
float hue = (float)(ttype) / world.tc.towerTypeCnt;
// tower color
g.setColor(Color.getHSBColor(hue, 0.9f, 1.0f));
g.fillOval(15 + j * cellSize + 2, 15 + i * cellSize + 2, cellSize - 4, cellSize - 4);
if (debugMode) {
// draw area of attack
int r = world.tc.towerTypes[ttype].range;
g.drawOval(15 + (j-r) * cellSize + 1, 15 + (i-r) * cellSize + 1, cellSize*(r*2+1) - 1, cellSize*(r*2+1) - 1);
g.setColor(new Color(128, 128, 128, 30));
g.fillOval(15 + (j-r) * cellSize + 1, 15 + (i-r) * cellSize + 1, cellSize*(r*2+1) - 1, cellSize*(r*2+1) - 1);
}
}
}
}
int z1 = 2;
for (Creep c : world.tc.creeps)
if (c.health>0 && c.spawnTime<world.curStep) {
float h = Math.min(1.f, (float)(c.health) / (world.tc.creepType.health));
g.setColor(new Color(h,0,0));
g.fillRect(15 + c.x * cellSize + 1 + cCnt[c.y][c.x], 15 + c.y * cellSize + 1 + cCnt[c.y][c.x], cellSize - 1, cellSize - 1);
g.setColor(new Color(255,0,0));
g.drawOval(15 + z1 + c.x * cellSize + 1 + cCnt[c.y][c.x], 15 + z1 + c.y * cellSize + 1 + cCnt[c.y][c.x], cellSize - 3 - z1, cellSize - 3 - z1);
cCnt[c.y][c.x]+=2;
}
g.setColor(Color.GREEN);
for (AttackVis a : world.attacks) {
g.drawLine(15 + a.x1 * cellSize + cellSize/2, 15 + a.y1 * cellSize + cellSize/2,
15 + a.x2 * cellSize + cellSize/2, 15 + a.y2 * cellSize + cellSize/2);
}
g.setColor(Color.BLACK);
g.setFont(new Font("Arial", Font.BOLD, 12));
Graphics2D g2 = (Graphics2D)g;
int horPos = 20 + boardSize * cellSize;
int verPos = horPos + 10;
for (String s : PathDefenseVis.pathDefense.toString().split("\\n")) {
g2.drawString(s, 10, verPos);
verPos += 18;
}
g2.drawString("Board size = " + boardSize, horPos, 30);
g2.drawString("Simulation Step = " + world.curStep, horPos, 50);
g2.drawString("Creeps Spawned = " + world.numSpawned, horPos, 70);
g2.drawString("Creeps killed = " + world.numKilled, horPos, 90);
g2.drawString("Towers placed = " + world.numTowers, horPos, 110);
g2.drawString("Money gained = " + world.moneyIncome, horPos, 130);
g2.drawString("Money spend = " + world.moneySpend, horPos, 150);
g2.drawString("Money = " + world.totMoney, horPos, 170);
int baseh = 0;
for (int i=0;i<world.baseHealth.length;i++) {
g.setColor(Color.GREEN);
g.fillRect(horPos+30, 205+i*20, world.baseHealth[i]/10, 19);
g.setColor(Color.BLACK);
g.fillRect(horPos+30+world.baseHealth[i]/10, 205+i*20, 100 - world.baseHealth[i]/10, 19);
g2.drawString(Integer.toString(world.baseHealth[i]), horPos, 220+i*20);
baseh += world.baseHealth[i];
g2.drawString(Integer.toString(i), 15 + world.tc.baseX[i] * cellSize + 2, 15 + (world.tc.baseY[i]+1) * cellSize-1);
}
g2.drawString("Base health = " + baseh, horPos, 195);
int score = world.totMoney + baseh;
g2.drawString("Score = " + score, horPos, 225+world.baseHealth.length*20);
}
}
}
@Override
public void dispose() {
PathDefenseVis.stopSolution();
super.dispose();
PathDefenseVis.drawer = null;
}
class DrawerWindowListener extends WindowAdapter {
@Override
public void windowClosing(@SuppressWarnings("unused") WindowEvent event) {
dispose();
}
}
final Object keyMutex = new Object();
boolean keyPressed;
public void processPause() {
synchronized (keyMutex) {
if (!stepMode && !pauseMode) {
return;
}
keyPressed = false;
while (!keyPressed) {
try {
keyMutex.wait();
} catch (InterruptedException e) {
// do nothing
}
}
}
}
public Drawer(World world, int cellSize) {
super();
panel = new DrawerPanel();
getContentPane().add(panel);
addWindowListener(new DrawerWindowListener());
this.world = world;
boardSize = world.tc.boardSize;
this.cellSize = cellSize;
width = cellSize * boardSize + 400;
height = cellSize * boardSize + 150;
addKeyListener(new DrawerKeyListener());
setSize(width, height);
setTitle("" + PathDefense._seed + " HEALTH=" + world.tc.creepType.health + " $" + world.tc.creepType.money);
setResizable(true);
setVisible(true);
}
}
class World {
final Object worldLock = new Object();
TestCase tc;
int totMoney;
int curStep = -1;
int numSpawned;
int numKilled;
int numTowers;
int moneyIncome;
int moneySpend;
int[] baseHealth;
List<Tower> towers = new ArrayList<Tower>();
List<AttackVis> attacks = new ArrayList<AttackVis>();
public World(TestCase tc) {
this.tc = tc;
totMoney = tc.money;
numSpawned = 0;
numKilled = 0;
numTowers = 0;
moneyIncome = 0;
moneySpend = 0;
baseHealth = new int[tc.baseCnt];
for (int i=0;i<tc.baseCnt;i++)
baseHealth[i] = PathDefense.INITIAL_BASE_HEALTH;
}
public void updateCreeps() {
synchronized (worldLock) {
for (Creep c : tc.creeps)
if (c.health>0 && c.spawnTime<curStep) {
int dir = c.moves.get(curStep-c.spawnTime-1);
c.x += PathDefense.DX[dir];
c.y += PathDefense.DY[dir];
if (tc.board[c.y][c.x]>='0' && tc.board[c.y][c.x]<='9') {
// reached a base
int b = tc.board[c.y][c.x]-'0';
// decrease the health of the base
baseHealth[b] = Math.max(0, baseHealth[b]-c.health);
c.health = 0;
}
} else if (c.spawnTime==curStep) {
numSpawned++;
}
}
}
public void updateAttack() {
synchronized (worldLock) {
attacks.clear();
for (Tower t : towers) {
// search for nearest attackable creep
int cidx = -1;
int cdist = 1<<29;
for (int i=0;i<tc.creeps.length;i++)
if (tc.creeps[i].health>0 && tc.creeps[i].spawnTime<=curStep) {
int dst = (t.x-tc.creeps[i].x)*(t.x-tc.creeps[i].x) + (t.y-tc.creeps[i].y)*(t.y-tc.creeps[i].y);
// within range of tower?
if (dst<=tc.towerTypes[t.type].range*tc.towerTypes[t.type].range) {
// nearest creep?
if (dst<cdist) {
cdist = dst;
cidx = i;
} else if (dst==cdist) {
// creep with smallest id gets attacked first if they are the same distance away
if (tc.creeps[i].id<tc.creeps[cidx].id) {
cdist = dst;
cidx = i;
}
}
}
}
if (cidx>=0) {
// we hit something
tc.creeps[cidx].health -= tc.towerTypes[t.type].damage;
attacks.add(new AttackVis(t.x, t.y, tc.creeps[cidx].x, tc.creeps[cidx].y));
if (tc.creeps[cidx].health<=0) {
// killed it!
totMoney += tc.creepType.money;
numKilled++;
moneyIncome += tc.creepType.money;
}
}
}
}
}
public void startNewStep() {
curStep++;
}
}
public class PathDefenseVis implements Callable<Void> {
public static String execCommand = null;
// public static long seed = 1;
// public static boolean vis = true;
public static boolean debug = false;
public static int cellSize = 16;
public static boolean startPaused = false;
public static Process solution;
public static PathDefense pathDefense;
public static Drawer drawer = null;
@Override
public Void call() {
runTest();
return null;
}
public static int runTest() {
solution = null;
if (execCommand != null) {
try {
solution = Runtime.getRuntime().exec(execCommand);
} catch (Exception e) {
System.err.println("ERROR: Unable to execute your solution using the provided command: "
+ execCommand + ".");
return -1;
}
} else {
pathDefense = new PathDefense();
}
TestCase tc = new TestCase(PathDefense._seed);
World world = new World(tc);
// Board information
String[] tcBoard = new String[tc.boardSize];
for (int y=0;y<tc.boardSize;y++) {
tcBoard[y] = "";
for (int x=0;x<tc.boardSize;x++) {
tcBoard[y] += tc.board[y][x];
}
}
// Tower type information
int[] towerTypeData = new int[tc.towerTypeCnt*3];
int ii = 0;
for (int i=0;i<tc.towerTypeCnt;i++) {
towerTypeData[ii++] = tc.towerTypes[i].range;
towerTypeData[ii++] = tc.towerTypes[i].damage;
towerTypeData[ii++] = tc.towerTypes[i].cost;
}
BufferedReader reader = null;
PrintWriter writer = null;
if (solution != null) {
reader = new BufferedReader(new InputStreamReader(solution.getInputStream()));
writer = new PrintWriter(solution.getOutputStream());
new ErrorStreamRedirector(solution.getErrorStream()).start();
writer.println(tc.boardSize);
writer.println(tc.money);
// Board information
for (int y=0;y<tc.boardSize;y++) {
writer.println(tcBoard[y]);
}
// Creep type information
writer.println(tc.creepType.health);
writer.println(tc.creepType.money);
writer.flush();
// Tower type information
writer.println(towerTypeData.length);
for (int v : towerTypeData)
writer.println(v);
writer.flush();
} else {
PathDefense._time = -System.currentTimeMillis();
pathDefense.init(tcBoard, tc.money, tc.creepType.health, tc.creepType.money, towerTypeData);
PathDefense._time += System.currentTimeMillis();
}
if (PathDefense._vis) {
int c = cellSize;
if (world.tc.boardSize > 40) {
c = c * 40 / world.tc.boardSize;
}
drawer = new Drawer(world, c);
drawer.debugMode = debug;
if (startPaused) {
drawer.pauseMode = true;
}
}
for (int t = 0; t < PathDefense.SIMULATION_TIME; t++) {
world.startNewStep();
int numLive = 0;
for (Creep c : world.tc.creeps)
if (c.health>0 && c.spawnTime<world.curStep) numLive++;
int[] creeps = new int[numLive*4];
int ci = 0;
for (Creep c : world.tc.creeps)
if (c.health>0 && c.spawnTime<world.curStep) {
creeps[ci++] = c.id;
creeps[ci++] = c.health;
creeps[ci++] = c.x;
creeps[ci++] = c.y;
}
int[] newTowers = null;
if (solution != null) {
assert writer != null;
writer.println(world.totMoney);
writer.println(creeps.length);
for (int v : creeps)
writer.println(v);
writer.println(world.baseHealth.length);
for (int v : world.baseHealth)
writer.println(v);
writer.flush();
} else {
PathDefense._time -= System.currentTimeMillis();
newTowers = pathDefense.placeTowers(creeps, world.totMoney, world.baseHealth);
PathDefense._time += System.currentTimeMillis();
}
int commandCnt;
try {
if (solution != null) {
assert reader != null;
commandCnt = Integer.parseInt(reader.readLine());
if (commandCnt>tc.boardSize*tc.boardSize*3) {
System.err.println("ERROR: Return array from placeTowers too large.");
return -1;
}
if ((commandCnt%3)!=0) {
System.err.println("ERROR: Return array from placeTowers must be a multiple of 3.");
return -1;
}
newTowers = new int[commandCnt];
for (int i=0;i<commandCnt;i++) {
newTowers[i] = Integer.parseInt(reader.readLine());
}
}
assert newTowers != null;
for (int i=0;i<newTowers.length;i+=3) {
Tower newT = new Tower();
newT.x = newTowers[i];
newT.y = newTowers[i+1];
newT.type = newTowers[i+2];
if (newT.x<0 || newT.x>=tc.boardSize || newT.y<0 || newT.y>=tc.boardSize) {
System.err.println("ERROR: Placement (" + newT.x + "," + newT.y + ") outside of bounds.");
return -1;
}
if (tc.board[newT.y][newT.x]!='#') {
System.err.println("ERROR: Cannot place a tower at (" + newT.x + "," + newT.y + "): " + tc.board[newT.y][newT.x]);
return -1;
}
if (newT.type<0 || newT.type>=tc.towerTypeCnt) {
System.err.println("ERROR: Trying to place an illegal tower type.");
return -1;
}
if (world.totMoney<tc.towerTypes[newT.type].cost) {
System.err.println("ERROR: Not enough money to place tower.");
return -1;
}
world.totMoney -= tc.towerTypes[newT.type].cost;
tc.board[newT.y][newT.x] = (char)('A'+newT.type);
world.towers.add(newT);
world.numTowers++;
world.moneySpend += tc.towerTypes[newT.type].cost;
}
} catch (Exception e) {
System.err.println("ERROR: time step = " + t + " (0-based). Unable to get the build commands" +
" from your solution.");
return -1;
}
world.updateCreeps();
world.updateAttack();
if (drawer != null) {
drawer.processPause();
if (drawer != null) {
drawer.repaint();
try {
Thread.sleep(1 + (int) (PathDefense._delay * PathDefense._speed));
} catch (Exception e) {
// do nothing
}
}
}
}
stopSolution();
if (drawer != null) {
drawer.dispose();
}
int score = world.totMoney;
for (int b=0;b<world.baseHealth.length;b++)
score += world.baseHealth[b];
// System.err.println("Money = " + world.totMoney);
// System.err.println("Total base health = " + (score-world.totMoney));
PathDefense._score = score;
return score;
}
public static void stopSolution() {
if (solution != null) {
try {
solution.destroy();
} catch (Exception e) {
// do nothing
}
}
}
public static void main1(String[] args) {
for (int i = 0; i < args.length; i++)
if (args[i].equals("-exec")) {
execCommand = args[++i];
} else if (args[i].equals("-seed")) {
PathDefense._seed = Long.parseLong(args[++i]);
} else if (args[i].equals("-novis")) {
PathDefense._vis = false;
} else if (args[i].equals("-debug")) {
debug = true;
} else if (args[i].equals("-sz")) {
cellSize = Integer.parseInt(args[++i]);
} else if (args[i].equals("-delay")) {
PathDefense._delay = Integer.parseInt(args[++i]);
} else if (args[i].equals("-pause")) {
startPaused = true;
} else {
System.out.println("WARNING: unknown argument " + args[i] + ".");
}
if (execCommand == null) {
System.err.println("ERROR: You did not provide the command to execute your solution." +
" Please use -exec <command> for this.");
System.exit(1);
}
try {
int score = PathDefenseVis.runTest();
System.out.println("Score = " + score);
} catch (RuntimeException e) {
System.err.println("ERROR: Unexpected error while running your test case.");
e.printStackTrace();
PathDefenseVis.stopSolution();
}
}
}
class ErrorStreamRedirector extends Thread {
public BufferedReader reader;
public ErrorStreamRedirector(InputStream is) {
reader = new BufferedReader(new InputStreamReader(is));
}
@Override
public void run() {
while (true) {
String s;
try {
s = reader.readLine();
} catch (Exception e) {
//e.printStackTrace();
return;
}
if (s == null) {
break;
}
System.err.println(s);
}
}
}
|
e08bdd530d8a76a0998f18f849cbfcefd2342834
|
{
"blob_id": "e08bdd530d8a76a0998f18f849cbfcefd2342834",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-24T20:24:58",
"content_id": "12101178c9d8f6d6bd5979d4a4d51966363c1431",
"detected_licenses": [
"Unlicense"
],
"directory_id": "d03142402e2e050d68d083fa84b25cb8223221fb",
"extension": "java",
"filename": "PathDefenseVis.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 93438157,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 26118,
"license": "Unlicense",
"license_type": "permissive",
"path": "/marathons/topcoder/pathDefense/PathDefenseVis.java",
"provenance": "stack-edu-0023.json.gz:861837",
"repo_name": "mikhail-dvorkin/competitions",
"revision_date": "2023-08-24T20:24:58",
"revision_id": "4e781da37faf8c82183f42d2789a78963f9d79c3",
"snapshot_id": "b859028712d69d6a14ac1b6194e43059e262d227",
"src_encoding": "UTF-8",
"star_events_count": 10,
"url": "https://raw.githubusercontent.com/mikhail-dvorkin/competitions/4e781da37faf8c82183f42d2789a78963f9d79c3/marathons/topcoder/pathDefense/PathDefenseVis.java",
"visit_date": "2023-09-01T03:45:21.589421",
"added": "2024-11-19T01:50:32.995648+00:00",
"created": "2023-08-24T20:24:58",
"int_score": 3,
"score": 2.609375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0041.json.gz"
}
|
import React from 'react';
import { Text, TouchableOpacity } from 'react-native';
export default class Button extends React.Component {
render() {
return (
<TouchableOpacity style={this.props.style} onPress={this.props.onPress}>
<Text style={this.props.textStyle}>{this.props.text}</Text>
</TouchableOpacity>
);
}
}
|
74d6fa53a4b31dd50fc76c64a6c4ad8966daec53
|
{
"blob_id": "74d6fa53a4b31dd50fc76c64a6c4ad8966daec53",
"branch_name": "refs/heads/master",
"committer_date": "2019-10-24T19:53:18",
"content_id": "0cb54a57620d825e48ca3db4128b6bd1a7048ed3",
"detected_licenses": [
"MIT"
],
"directory_id": "b83024823d0c519a5c3cf3ea94f11811f3267276",
"extension": "js",
"filename": "Button.js",
"fork_events_count": 0,
"gha_created_at": "2017-11-30T20:58:04",
"gha_event_created_at": "2021-03-26T23:40:17",
"gha_language": "JavaScript",
"gha_license_id": "MIT",
"github_id": 112659771,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 381,
"license": "MIT",
"license_type": "permissive",
"path": "/src/components/atoms/Button.js",
"provenance": "stack-edu-0035.json.gz:777279",
"repo_name": "srct/masontoday",
"revision_date": "2019-10-24T19:53:18",
"revision_id": "4c44914f2b416141b7c511fb1aefd62ec00c84e0",
"snapshot_id": "e7f1b9f43b60723f7cf5d570ffad4029b65987ed",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/srct/masontoday/4c44914f2b416141b7c511fb1aefd62ec00c84e0/src/components/atoms/Button.js",
"visit_date": "2021-06-01T13:39:14.284756",
"added": "2024-11-19T02:14:04.588800+00:00",
"created": "2019-10-24T19:53:18",
"int_score": 2,
"score": 2.015625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0053.json.gz"
}
|
using BeatSaberMarkupLanguage.Components;
using ServerBrowser.Assets;
using ServerBrowser.Core;
using ServerBrowser.Utils;
using System;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
namespace ServerBrowser.UI.Components
{
public class HostedGameCell : CustomListTableData.CustomCellInfo
{
public HostedGameData Game
{
get;
private set;
}
private static CancellationTokenSource _cancellationTokenSource;
private static Action<HostedGameCell> _onContentChange;
public HostedGameCell(CancellationTokenSource cancellationTokenSource, Action<HostedGameCell> onContentChange, HostedGameData game)
: base("A game", "Getting details...", Sprites.BeatSaverIcon)
{
_cancellationTokenSource = cancellationTokenSource;
_onContentChange = onContentChange;
Game = game;
UpdateUi();
}
public void UpdateUi()
{
this.text = Game.GameName;
if (Game.OwnerId == "SERVER_MSG")
{
// Special case: the server can inject a fake game here as a message, e.g. to notify that an update is available
this.text = $"<color=#cf0389>{Game.GameName}</color>";
this.subtext = Game.SongName;
this.icon = Sprites.Portal;
return;
}
if (Game.IsModded)
{
this.text += " <color=#8f48db>(Modded)</color>";
}
else
{
this.text += " <color=#00ff00>(Vanilla)</color>";
}
if (Game.IsOnCustomMaster)
{
this.text += $" <color=#59b0f4><size=3>({Game.MasterServerHost})</size></color>";
}
this.subtext = $"[{Game.PlayerCount} / {Game.PlayerLimit}]";
if (Game.LobbyState == MultiplayerLobbyState.GameRunning && Game.LevelId != null)
{
if (!String.IsNullOrEmpty(Game.SongAuthor))
{
this.subtext += $" {Game.SongAuthor} -";
}
this.subtext += $" {Game.SongName}";
}
else
{
this.subtext += $" In lobby";
}
if (Game.Difficulty.HasValue && !String.IsNullOrEmpty(Game.LevelId))
{
this.subtext += $" ({Game.Difficulty})";
}
try
{
SetCoverArt();
}
catch (Exception ex)
{
Plugin.Log?.Error($"Could not set cover art for level {Game.LevelId}: {ex}");
}
}
private async Task<bool> SetCoverArt()
{
if (String.IsNullOrEmpty(Game.LevelId) || Game.LobbyState != MultiplayerLobbyState.GameRunning)
{
// No level info / we are in a lobby
UpdateIcon(Sprites.PortalUser);
return true;
}
var coverArtSprite = await CoverArtGrabber.GetCoverArtSprite(Game, _cancellationTokenSource.Token);
if (coverArtSprite != null)
{
// Official level, or installed custom level found
UpdateIcon(coverArtSprite);
return true;
}
// Failed to get level info, show beatsaver icon as placeholder
UpdateIcon(Sprites.BeatSaverIcon);
return false;
}
private void UpdateIcon(Sprite nextIcon)
{
if (this.icon == null || this.icon.name != nextIcon.name)
{
this.icon = nextIcon;
_onContentChange(this);
}
}
}
}
|
946f8bc47d74ccfdfd22ad3b2c5a8ac8429ec385
|
{
"blob_id": "946f8bc47d74ccfdfd22ad3b2c5a8ac8429ec385",
"branch_name": "refs/heads/master",
"committer_date": "2021-01-14T15:56:42",
"content_id": "332d1c7f87c8f123fbeb087ac69227e2297860ca",
"detected_licenses": [
"MIT"
],
"directory_id": "837dc2719635861f432065c795396e934ee26f1c",
"extension": "cs",
"filename": "HostedGameCell.cs",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 3803,
"license": "MIT",
"license_type": "permissive",
"path": "/UI/Components/HostedGameCell.cs",
"provenance": "stack-edu-0014.json.gz:433577",
"repo_name": "Kevman95/BeatSaberServerBrowser",
"revision_date": "2021-01-14T15:56:42",
"revision_id": "5bdab3fbeaed7f358a7004a68f72b3a633a454e4",
"snapshot_id": "87b1307855797035d35ee332775f5fd8e986efc0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Kevman95/BeatSaberServerBrowser/5bdab3fbeaed7f358a7004a68f72b3a633a454e4/UI/Components/HostedGameCell.cs",
"visit_date": "2023-02-12T16:11:47.827048",
"added": "2024-11-18T23:55:07.231290+00:00",
"created": "2021-01-14T15:56:42",
"int_score": 2,
"score": 2.25,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0032.json.gz"
}
|
#include "first.h"
#include "buffer.h"
#include <stdlib.h>
#include <string.h>
#include "sys-time.h" /* strftime() */
static const char hex_chars_lc[] = "0123456789abcdef";
static const char hex_chars_uc[] = "0123456789ABCDEF";
__attribute_noinline__
buffer* buffer_init(void) {
#if 0 /* buffer_init() and chunk_init() can be hot,
* so avoid the additional hop of indirection */
return ck_calloc(1, sizeof(buffer));
#else
buffer * const b = calloc(1, sizeof(*b));
force_assert(b);
return b;
#endif
}
void buffer_free(buffer *b) {
if (NULL == b) return;
free(b->ptr);
free(b);
}
void buffer_free_ptr(buffer *b) {
free(b->ptr);
b->ptr = NULL;
b->used = 0;
b->size = 0;
}
void buffer_move(buffer * restrict b, buffer * restrict src) {
buffer tmp;
buffer_clear(b);
tmp = *src; *src = *b; *b = tmp;
}
/* make sure buffer is at least "size" big + 1 for '\0'. keep old data */
__attribute_cold__
__attribute_noinline__
__attribute_nonnull__()
__attribute_returns_nonnull__
static char* buffer_realloc(buffer * const restrict b, const size_t len) {
#define BUFFER_PIECE_SIZE 64uL /*(must be power-of-2)*/
size_t sz = (len + 1 + BUFFER_PIECE_SIZE-1) & ~(BUFFER_PIECE_SIZE-1);
force_assert(sz > len);
if ((sz & (sz-1)) && sz < INT_MAX) {/* not power-2; huge val not expected */
/*(optimizer should recognize this and use ffs or clz or equivalent)*/
const size_t psz = sz;
for (sz = 256; sz < psz; sz <<= 1) ;
}
sz |= 1; /*(extra +1 for '\0' when needed buffer size is exact power-2)*/
b->size = sz;
b->ptr = realloc(b->ptr, sz);
force_assert(NULL != b->ptr);
return b->ptr;
}
__attribute_cold__
__attribute_noinline__
__attribute_nonnull__()
__attribute_returns_nonnull__
static char* buffer_alloc_replace(buffer * const restrict b, const size_t size) {
/*(discard old data so realloc() does not copy)*/
if (NULL != b->ptr) {
free(b->ptr);
b->ptr = NULL;
}
/*(note: if size larger than one lshift, use size instead of power-2)*/
const size_t bsize2x = (b->size & ~1uL) << 1;
return buffer_realloc(b, bsize2x > size ? bsize2x-1 : size);
}
char* buffer_string_prepare_copy(buffer * const b, const size_t size) {
b->used = 0;
#ifdef __COVERITY__ /*(b->ptr is not NULL if b->size is not 0)*/
force_assert(size >= b->size || b->ptr);
#endif
return (size < b->size)
? b->ptr
: buffer_alloc_replace(b, size);
}
__attribute_cold__
__attribute_noinline__
__attribute_nonnull__()
__attribute_returns_nonnull__
static char* buffer_string_prepare_append_resize(buffer * const restrict b, const size_t size) {
if (b->used < 2) { /* buffer_is_blank(b) */
char * const s = buffer_string_prepare_copy(b, size);
*s = '\0'; /*(for case (1 == b->used))*/
return s;
}
/* not empty, b->used already includes a terminating 0 */
/*(note: if size larger than one lshift, use size instead of power-2)*/
const size_t bsize2x = (b->size & ~1uL) << 1;
const size_t req_size = (bsize2x - b->used > size)
? bsize2x-1
: b->used + size;
/* check for overflow: unsigned overflow is defined to wrap around */
force_assert(req_size >= b->used);
return buffer_realloc(b, req_size) + b->used - 1;
}
char* buffer_string_prepare_append(buffer * const b, const size_t size) {
const uint32_t len = b->used ? b->used-1 : 0;
return (b->size - len >= size + 1)
? b->ptr + len
: buffer_string_prepare_append_resize(b, size);
}
/*(prefer smaller code than inlining buffer_extend in many places in buffer.c)*/
__attribute_noinline__
char*
buffer_extend (buffer * const b, const size_t x)
{
/* extend buffer to append x (reallocate by power-2 (or larger), if needed)
* (combine buffer_string_prepare_append() and buffer_commit())
* (future: might make buffer.h static inline func for HTTP/1.1 performance)
* pre-sets '\0' byte and b->used (unlike buffer_string_prepare_append())*/
#if 0
char * const s = buffer_string_prepare_append(b, x);
b->used += x + (0 == b->used);
#else
const uint32_t len = b->used ? b->used-1 : 0;
char * const s = (b->size - len >= x + 1)
? b->ptr + len
: buffer_string_prepare_append_resize(b, x);
b->used = len+x+1;
#endif
s[x] = '\0';
return s;
}
void buffer_commit(buffer *b, size_t size)
{
size_t sz = b->used;
if (0 == sz) sz = 1;
if (size > 0) {
/* check for overflow: unsigned overflow is defined to wrap around */
sz += size;
force_assert(sz > size);
}
b->used = sz;
b->ptr[sz - 1] = '\0';
}
__attribute_cold__ /*(reduce code size due to inlining)*/
void buffer_copy_string(buffer * restrict b, const char * restrict s) {
if (__builtin_expect( (NULL == s), 0)) s = "";
buffer_copy_string_len(b, s, strlen(s));
}
void buffer_copy_string_len(buffer * const restrict b, const char * const restrict s, const size_t len) {
b->used = len + 1;
char * const restrict d = (len < b->size)
? b->ptr
: buffer_alloc_replace(b, len);
d[len] = '\0';
memcpy(d, s, len);
}
__attribute_cold__ /*(reduce code size due to inlining)*/
void buffer_append_string(buffer * restrict b, const char * restrict s) {
if (__builtin_expect( (NULL == s), 0)) s = "";
buffer_append_string_len(b, s, strlen(s));
}
/**
* append a string to the end of the buffer
*
* the resulting buffer is terminated with a '\0'
* s is treated as a un-terminated string (a \0 is handled a normal character)
*
* @param b a buffer
* @param s the string
* @param s_len size of the string (without the terminating \0)
*/
void buffer_append_string_len(buffer * const restrict b, const char * const restrict s, const size_t len) {
memcpy(buffer_extend(b, len), s, len);
}
void buffer_append_str2(buffer * const restrict b, const char * const s1, const size_t len1, const char * const s2, const size_t len2) {
char * const restrict s = buffer_extend(b, len1+len2);
#ifdef HAVE_MEMPCPY
mempcpy(mempcpy(s, s1, len1), s2, len2);
#else
memcpy(s, s1, len1);
memcpy(s+len1, s2, len2);
#endif
}
void buffer_append_str3(buffer * const restrict b, const char * const s1, const size_t len1, const char * const s2, const size_t len2, const char * const s3, const size_t len3) {
char * restrict s = buffer_extend(b, len1+len2+len3);
#ifdef HAVE_MEMPCPY
mempcpy(mempcpy(mempcpy(s, s1, len1), s2, len2), s3, len3);
#else
memcpy(s, s1, len1);
memcpy((s+=len1), s2, len2);
memcpy((s+=len2), s3, len3);
#endif
}
void buffer_append_iovec(buffer * const restrict b, const struct const_iovec * const iov, const size_t n) {
size_t len = 0;
for (size_t i = 0; i < n; ++i)
len += iov[i].iov_len;
char *s = buffer_extend(b, len);
for (size_t i = 0; i < n; ++i) {
if (0 == iov[i].iov_len) continue;
#ifdef HAVE_MEMPCPY
s = mempcpy(s, iov[i].iov_base, iov[i].iov_len);
#else
memcpy(s, iov[i].iov_base, iov[i].iov_len);
s += iov[i].iov_len;
#endif
}
}
void buffer_append_path_len(buffer * restrict b, const char * restrict a, size_t alen) {
char * restrict s = buffer_string_prepare_append(b, alen+1);
#ifdef _WIN32
const int aslash = (alen && (a[0] == '/' || a[0] == '\\'));
if (b->used > 1 && (s[-1] == '/' || s[-1] == '\\'))
#else
const int aslash = (alen && a[0] == '/');
if (b->used > 1 && s[-1] == '/')
#endif
{
if (aslash) {
++a;
--alen;
}
}
else {
if (0 == b->used) b->used = 1;
if (!aslash) {
*s++ = '/';
++b->used;
}
}
b->used += alen;
s[alen] = '\0';
memcpy(s, a, alen);
}
void
buffer_copy_path_len2 (buffer * const restrict b, const char * const restrict s1, size_t len1, const char * const restrict s2, size_t len2)
{
/*(similar to buffer_copy_string_len(b, s1, len1) but combined allocation)*/
memcpy(buffer_string_prepare_copy(b, len1+len2+1), s1, len1);
b->used = len1 + 1; /*('\0' byte will be written below)*/
buffer_append_path_len(b, s2, len2);/*(choice: not inlined, special-cased)*/
}
void
buffer_copy_string_len_lc (buffer * const restrict b, const char * const restrict s, const size_t len)
{
char * const restrict d = buffer_string_prepare_copy(b, len);
b->used = len+1;
d[len] = '\0';
for (size_t i = 0; i < len; ++i)
d[i] = (!light_isupper(s[i])) ? s[i] : s[i] | 0x20;
}
void buffer_append_uint_hex_lc(buffer *b, uintmax_t value) {
char *buf;
unsigned int shift = 0;
{
uintmax_t copy = value;
do {
copy >>= 8;
shift += 8; /* counting bits */
} while (0 != copy);
}
buf = buffer_extend(b, shift >> 2); /*nibbles (4 bits)*/
while (shift > 0) {
shift -= 4;
*(buf++) = hex_chars_lc[(value >> shift) & 0x0F];
}
}
__attribute_nonnull__()
__attribute_returns_nonnull__
static char* utostr(char buf[LI_ITOSTRING_LENGTH], uintmax_t val) {
char *cur = buf+LI_ITOSTRING_LENGTH;
uintmax_t x;
do {
*(--cur) = (char) ('0' + (int)(val - (x = val/10) * 10));
} while (0 != (val = x)); /* val % 10 */
return cur;
}
__attribute_nonnull__()
__attribute_returns_nonnull__
static char* itostr(char buf[LI_ITOSTRING_LENGTH], intmax_t val) {
/* absolute value not defined for INTMAX_MIN, but can take absolute
* value of any negative number via twos complement cast to unsigned.
* negative sign is prepended after (now unsigned) value is converted
* to string */
uintmax_t uval = val >= 0 ? (uintmax_t)val : ((uintmax_t)~val) + 1;
char *cur = utostr(buf, uval);
if (val < 0) *(--cur) = '-';
return cur;
}
void buffer_append_int(buffer *b, intmax_t val) {
char buf[LI_ITOSTRING_LENGTH];
const char * const str = itostr(buf, val);
buffer_append_string_len(b, str, buf+sizeof(buf) - str);
}
void buffer_append_strftime(buffer * const restrict b, const char * const restrict format, const struct tm * const restrict tm) {
/*(localtime_r() or gmtime_r() producing tm should not have failed)*/
if (__builtin_expect( (NULL == tm), 0)) return;
/*(expecting typical format strings to result in < 64 bytes needed;
* skipping buffer_string_space() calculation and providing fixed size)*/
size_t rv = strftime(buffer_string_prepare_append(b, 63), 64, format, tm);
/* 0 (in some apis) signals the string may have been too small;
* but the format could also just have lead to an empty string */
if (__builtin_expect( (0 == rv), 0) || __builtin_expect( (rv > 63), 0)) {
/* unexpected; give it a second try with a larger string */
rv = strftime(buffer_string_prepare_append(b, 4095), 4096, format, tm);
if (__builtin_expect( (rv > 4095), 0))/*(input format was ridiculous)*/
return;
}
/*buffer_commit(b, rv);*/
b->used += (uint32_t)rv + (0 == b->used);
}
size_t li_itostrn(char *buf, size_t buf_len, intmax_t val) {
char p_buf[LI_ITOSTRING_LENGTH];
char* const str = itostr(p_buf, val);
size_t len = (size_t)(p_buf+sizeof(p_buf)-str);
force_assert(len <= buf_len);
memcpy(buf, str, len);
return len;
}
size_t li_utostrn(char *buf, size_t buf_len, uintmax_t val) {
char p_buf[LI_ITOSTRING_LENGTH];
char* const str = utostr(p_buf, val);
size_t len = (size_t)(p_buf+sizeof(p_buf)-str);
force_assert(len <= buf_len);
memcpy(buf, str, len);
return len;
}
#define li_ntox_lc(n) ((n) <= 9 ? (n) + '0' : (n) + 'a' - 10)
/* c (char) and n (nibble) MUST be unsigned integer types */
#define li_cton(c,n) \
(((n) = (c) - '0') <= 9 || (((n) = ((c)&0xdf) - 'A') <= 5 ? ((n) += 10) : 0))
/* converts hex char (0-9, A-Z, a-z) to decimal.
* returns 0xFF on invalid input.
*/
char hex2int(unsigned char hex) {
unsigned char n;
return li_cton(hex,n) ? (char)n : 0xFF;
}
int li_hex2bin (unsigned char * const bin, const size_t binlen, const char * const hexstr, const size_t len)
{
/* validate and transform 32-byte MD5 hex string to 16-byte binary MD5,
* or 64-byte SHA-256 or SHA-512-256 hex string to 32-byte binary digest */
if (len > (binlen << 1)) return -1;
for (int i = 0, ilen = (int)len; i < ilen; i+=2) {
int hi = hexstr[i];
int lo = hexstr[i+1];
if ('0' <= hi && hi <= '9') hi -= '0';
else if ((uint32_t)(hi |= 0x20)-'a' <= 'f'-'a')hi += -'a' + 10;
else return -1;
if ('0' <= lo && lo <= '9') lo -= '0';
else if ((uint32_t)(lo |= 0x20)-'a' <= 'f'-'a')lo += -'a' + 10;
else return -1;
bin[(i >> 1)] = (unsigned char)((hi << 4) | lo);
}
return 0;
}
__attribute_noinline__
int buffer_eq_icase_ssn(const char * const a, const char * const b, const size_t len) {
for (size_t i = 0; i < len; ++i) {
unsigned int ca = ((unsigned char *)a)[i];
unsigned int cb = ((unsigned char *)b)[i];
if (ca != cb && ((ca ^ cb) != 0x20 || !light_isalpha(ca))) return 0;
}
return 1;
}
int buffer_eq_icase_ss(const char * const a, const size_t alen, const char * const b, const size_t blen) {
/* 1 = equal; 0 = not equal */ /* short string sizes expected (< INT_MAX) */
return (alen == blen) ? buffer_eq_icase_ssn(a, b, blen) : 0;
}
int buffer_eq_icase_slen(const buffer * const b, const char * const s, const size_t slen) {
/* Note: b must be initialized, i.e. 0 != b->used; uninitialized is not eq*/
/* 1 = equal; 0 = not equal */ /* short string sizes expected (< INT_MAX) */
return (b->used == slen + 1) ? buffer_eq_icase_ssn(b->ptr, s, slen) : 0;
}
int buffer_eq_slen(const buffer * const b, const char * const s, const size_t slen) {
/* Note: b must be initialized, i.e. 0 != b->used; uninitialized is not eq*/
/* 1 = equal; 0 = not equal */ /* short string sizes expected (< INT_MAX) */
return (b->used == slen + 1 && 0 == memcmp(b->ptr, s, slen));
}
/**
* check if two buffer contain the same data
*/
int buffer_is_equal(const buffer *a, const buffer *b) {
/* 1 = equal; 0 = not equal */
return (a->used == b->used && 0 == memcmp(a->ptr, b->ptr, a->used));
}
void li_tohex_lc(char * const restrict buf, size_t buf_len, const char * const restrict s, size_t s_len) {
force_assert(2 * s_len > s_len);
force_assert(2 * s_len < buf_len);
for (size_t i = 0; i < s_len; ++i) {
buf[2*i] = hex_chars_lc[(s[i] >> 4) & 0x0F];
buf[2*i+1] = hex_chars_lc[s[i] & 0x0F];
}
buf[2*s_len] = '\0';
}
void li_tohex_uc(char * const restrict buf, size_t buf_len, const char * const restrict s, size_t s_len) {
force_assert(2 * s_len > s_len);
force_assert(2 * s_len < buf_len);
for (size_t i = 0; i < s_len; ++i) {
buf[2*i] = hex_chars_uc[(s[i] >> 4) & 0x0F];
buf[2*i+1] = hex_chars_uc[s[i] & 0x0F];
}
buf[2*s_len] = '\0';
}
void buffer_substr_replace (buffer * const restrict b, const size_t offset,
const size_t len, const buffer * const restrict replace)
{
const size_t blen = buffer_clen(b);
const size_t rlen = buffer_clen(replace);
if (rlen > len) {
buffer_extend(b, rlen-len);
memmove(b->ptr+offset+rlen, b->ptr+offset+len, blen-offset-len);
}
memcpy(b->ptr+offset, replace->ptr, rlen);
if (rlen < len) {
memmove(b->ptr+offset+rlen, b->ptr+offset+len, blen-offset-len);
buffer_truncate(b, blen-len+rlen);
}
}
void buffer_append_string_encoded_hex_lc(buffer * const restrict b, const char * const restrict s, size_t len) {
unsigned char * const p = (unsigned char *)buffer_extend(b, len*2);
for (size_t i = 0; i < len; ++i) {
p[(i<<1)] = hex_chars_lc[(s[i] >> 4) & 0x0F];
p[(i<<1)+1] = hex_chars_lc[(s[i]) & 0x0F];
}
}
void buffer_append_string_encoded_hex_uc(buffer * const restrict b, const char * const restrict s, size_t len) {
unsigned char * const p = (unsigned char *)buffer_extend(b, len*2);
for (size_t i = 0; i < len; ++i) {
p[(i<<1)] = hex_chars_uc[(s[i] >> 4) & 0x0F];
p[(i<<1)+1] = hex_chars_uc[(s[i]) & 0x0F];
}
}
/* everything except: ! ( ) * - . 0-9 A-Z _ a-z */
static const char encoded_chars_rel_uri_part[] = {
/*
0 1 2 3 4 5 6 7 8 9 A B C D E F
*/
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00 - 0F control chars */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 10 - 1F */
1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, /* 20 - 2F space " # $ % & ' + , / */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, /* 30 - 3F : ; < = > ? */
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 40 - 4F @ */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, /* 50 - 5F [ \ ] ^ */
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 60 - 6F ` */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, /* 70 - 7F { | } DEL */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 80 - 8F */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 90 - 9F */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* A0 - AF */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* B0 - BF */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* C0 - CF */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* D0 - DF */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* E0 - EF */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* F0 - FF */
};
/* everything except: ! ( ) * - . / 0-9 A-Z _ a-z */
static const char encoded_chars_rel_uri[] = {
/*
0 1 2 3 4 5 6 7 8 9 A B C D E F
*/
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00 - 0F control chars */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 10 - 1F */
1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, /* 20 - 2F space " # $ % & ' + , */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, /* 30 - 3F : ; < = > ? */
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 40 - 4F @ */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, /* 50 - 5F [ \ ] ^ */
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 60 - 6F ` */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, /* 70 - 7F { | } DEL */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 80 - 8F */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 90 - 9F */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* A0 - AF */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* B0 - BF */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* C0 - CF */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* D0 - DF */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* E0 - EF */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* F0 - FF */
};
static const char encoded_chars_html[] = {
/*
0 1 2 3 4 5 6 7 8 9 A B C D E F
*/
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00 - 0F control chars */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 10 - 1F */
0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, /* 20 - 2F " & ' */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, /* 30 - 3F < > */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 40 - 4F */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 50 - 5F */
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 60 - 6F ` */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, /* 70 - 7F DEL */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 80 - 8F */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 90 - 9F */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* A0 - AF */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* B0 - BF */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* C0 - CF */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* D0 - DF */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* E0 - EF */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* F0 - FF */
};
static const char encoded_chars_minimal_xml[] = {
/*
0 1 2 3 4 5 6 7 8 9 A B C D E F
*/
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00 - 0F control chars */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 10 - 1F */
0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, /* 20 - 2F " & ' */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, /* 30 - 3F < > */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 40 - 4F */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 50 - 5F */
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 60 - 6F ` */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, /* 70 - 7F DEL */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 80 - 8F */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 90 - 9F */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* A0 - AF */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0 - BF */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* C0 - CF */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* D0 - DF */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* E0 - EF */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* F0 - FF */
};
void buffer_append_string_encoded(buffer * const restrict b, const char * const restrict s, size_t s_len, buffer_encoding_t encoding) {
unsigned char *ds, *d;
size_t d_len, ndx;
const char *map = NULL;
switch(encoding) {
case ENCODING_REL_URI:
map = encoded_chars_rel_uri;
break;
case ENCODING_REL_URI_PART:
map = encoded_chars_rel_uri_part;
break;
case ENCODING_HTML:
map = encoded_chars_html;
break;
case ENCODING_MINIMAL_XML:
map = encoded_chars_minimal_xml;
break;
}
/* count to-be-encoded-characters */
for (ds = (unsigned char *)s, d_len = 0, ndx = 0; ndx < s_len; ds++, ndx++) {
if (map[*ds & 0xFF]) {
switch(encoding) {
case ENCODING_REL_URI:
case ENCODING_REL_URI_PART:
d_len += 3;
break;
case ENCODING_HTML:
case ENCODING_MINIMAL_XML:
d_len += 6;
break;
}
} else {
d_len++;
}
}
d = (unsigned char*) buffer_extend(b, d_len);
if (d_len == s_len) { /*(short-circuit; nothing to encoded)*/
memcpy(d, s, s_len);
return;
}
for (ds = (unsigned char *)s, d_len = 0, ndx = 0; ndx < s_len; ds++, ndx++) {
if (map[*ds & 0xFF]) {
switch(encoding) {
case ENCODING_REL_URI:
case ENCODING_REL_URI_PART:
d[d_len++] = '%';
d[d_len++] = hex_chars_uc[((*ds) >> 4) & 0x0F];
d[d_len++] = hex_chars_uc[(*ds) & 0x0F];
break;
case ENCODING_HTML:
case ENCODING_MINIMAL_XML:
d[d_len++] = '&';
d[d_len++] = '#';
d[d_len++] = 'x';
d[d_len++] = hex_chars_uc[((*ds) >> 4) & 0x0F];
d[d_len++] = hex_chars_uc[(*ds) & 0x0F];
d[d_len++] = ';';
break;
}
} else {
d[d_len++] = *ds;
}
}
}
void buffer_append_string_c_escaped(buffer * const restrict b, const char * const restrict s, size_t s_len) {
unsigned char *ds, *d;
size_t d_len, ndx;
/* count to-be-encoded-characters */
for (ds = (unsigned char *)s, d_len = 0, ndx = 0; ndx < s_len; ds++, ndx++) {
if (__builtin_expect( (*ds >= ' ' && *ds <= '~'), 1))
d_len++;
else { /* CTLs or non-ASCII characters */
switch (*ds) {
case '\t':
case '\r':
case '\n':
d_len += 2;
break;
default:
d_len += 4; /* \xCC */
break;
}
}
}
d = (unsigned char*) buffer_extend(b, d_len);
if (d_len == s_len) { /*(short-circuit; nothing to encoded)*/
memcpy(d, s, s_len);
return;
}
for (ds = (unsigned char *)s, d_len = 0, ndx = 0; ndx < s_len; ds++, ndx++) {
if (__builtin_expect( (*ds >= ' ' && *ds <= '~'), 1))
d[d_len++] = *ds;
else { /* CTLs or non-ASCII characters */
d[d_len++] = '\\';
switch (*ds) {
case '\t':
d[d_len++] = 't';
break;
case '\r':
d[d_len++] = 'r';
break;
case '\n':
d[d_len++] = 'n';
break;
default:
d[d_len++] = 'x';
d[d_len++] = hex_chars_lc[(*ds) >> 4];
d[d_len++] = hex_chars_lc[(*ds) & 0x0F];
break;
}
}
}
}
void
buffer_append_bs_escaped (buffer * const restrict b,
const char * restrict s, const size_t len)
{
/* replaces non-printable chars with escaped string
* default: \xHH where HH is the hex representation of the byte
* exceptions: " => \", \ => \\, whitespace chars => \n \t etc. */
/* Intended for use escaping string to be surrounded by double-quotes */
/* Performs single pass over string and is optimized for ASCII;
* non-ASCII escaping might be slightly sped up by walking input twice,
* first to calculate escaped length and extend the destination b, and
* second to do the escaping. (This non-ASCII optim is not done here) */
buffer_string_prepare_append(b, len);
for (const char * const end = s+len; s < end; ++s) {
unsigned int c;
const char * const ptr = s;
do {
c = *(const unsigned char *)s;
} while (c >= ' ' && c <= '~' && c != '"' && c != '\\' && ++s < end);
if (s - ptr) buffer_append_string_len(b, ptr, s - ptr);
if (s == end)
return;
/* ('\a', '\v' shortcuts are technically not json-escaping) */
/* ('\0' is also omitted due to the possibility of string corruption if
* the receiver supports decoding octal escapes (\000) and the escaped
* string contains \0 followed by two digits not part of escaping)*/
char *d;
switch (c) {
case '\a':case '\b':case '\t':case '\n':case '\v':case '\f':case '\r':
c = "0000000abtnvfr"[c];
__attribute_fallthrough__
case '"': case '\\':
d = buffer_extend(b, 2);
d[0] = '\\';
d[1] = c;
break;
default:
/* non printable char => \xHH */
d = buffer_extend(b, 4);
d[0] = '\\';
d[1] = 'x';
d[2] = hex_chars_uc[c >> 4];
d[3] = hex_chars_uc[c & 0xF];
break;
}
}
}
void
buffer_append_bs_escaped_json (buffer * const restrict b,
const char * restrict s, const size_t len)
{
/* replaces non-printable chars with escaped string
* json: \u00HH where HH is the hex representation of the byte
* exceptions: " => \", \ => \\, whitespace chars => \n \t etc. */
/* Intended for use escaping string to be surrounded by double-quotes */
buffer_string_prepare_append(b, len);
for (const char * const end = s+len; s < end; ++s) {
unsigned int c;
const char * const ptr = s;
do {
c = *(const unsigned char *)s;
} while (c >= ' ' && c != '"' && c != '\\' && ++s < end);
if (s - ptr) buffer_append_string_len(b, ptr, s - ptr);
if (s == end)
return;
/* ('\a', '\v' shortcuts are technically not json-escaping) */
/* ('\0' is also omitted due to the possibility of string corruption if
* the receiver supports decoding octal escapes (\000) and the escaped
* string contains \0 followed by two digits not part of escaping)*/
char *d;
switch (c) {
case '\a':case '\b':case '\t':case '\n':case '\v':case '\f':case '\r':
c = "0000000abtnvfr"[c];
__attribute_fallthrough__
case '"': case '\\':
d = buffer_extend(b, 2);
d[0] = '\\';
d[1] = c;
break;
default:
d = buffer_extend(b, 6);
d[0] = '\\';
d[1] = 'u';
d[2] = '0';
d[3] = '0';
d[4] = hex_chars_uc[c >> 4];
d[5] = hex_chars_uc[c & 0xF];
break;
}
}
}
/* decodes url-special-chars inplace.
* replaces non-printable characters with '_'
* (If this is used on a portion of query string, then query string should be
* split on '&', and '+' replaced with ' ' before calling this routine)
*/
void buffer_urldecode_path(buffer * const b) {
const size_t len = buffer_clen(b);
char *src = len ? memchr(b->ptr, '%', len) : NULL;
if (NULL == src) return;
char *dst = src;
do {
/* *src == '%' */
unsigned char high = ((unsigned char *)src)[1];
unsigned char low = high ? hex2int(((unsigned char *)src)[2]) : 0xFF;
if (0xFF != (high = hex2int(high)) && 0xFF != low) {
high = (high << 4) | low; /* map ctrls to '_' */
*dst = (high >= 32 && high != 127) ? high : '_';
src += 2;
} /* else ignore this '%'; leave as-is and move on */
while ((*++dst = *++src) != '%' && *src) ;
} while (*src);
b->used = (dst - b->ptr) + 1;
}
int buffer_is_valid_UTF8(const buffer *b) {
/* https://www.w3.org/International/questions/qa-forms-utf-8 */
/*assert(b->used);*//*(b->ptr must exist and be '\0'-terminated)*/
const unsigned char *c = (unsigned char *)b->ptr;
while (*c) {
/*(note: includes ctrls)*/
if ( c[0] < 0x80 ) { ++c; continue; }
if ( 0xc2 <= c[0] && c[0] <= 0xdf
&& 0x80 <= c[1] && c[1] <= 0xbf ) { c+=2; continue; }
if ( ( ( 0xe0 == c[0]
&& 0xa0 <= c[1] && c[1] <= 0xbf)
|| ( 0xe1 <= c[0] && c[0] <= 0xef && c[0] != 0xed
&& 0x80 <= c[1] && c[1] <= 0xbf)
|| ( 0xed == c[0]
&& 0x80 <= c[1] && c[1] <= 0x9f) )
&& 0x80 <= c[2] && c[2] <= 0xbf ) { c+=3; continue; }
if ( ( ( 0xf0 == c[0]
&& 0x90 <= c[1] && c[1] <= 0xbf)
|| ( 0xf1 <= c[0] && c[0] <= 0xf3
&& 0x80 <= c[1] && c[1] <= 0xbf)
|| ( 0xf4 == c[0]
&& 0x80 <= c[1] && c[1] <= 0x8f) )
&& 0x80 <= c[2] && c[2] <= 0xbf
&& 0x80 <= c[3] && c[3] <= 0xbf ) { c+=4; continue; }
return 0; /* invalid */
}
return 1; /* valid */
}
/* - special case: empty string returns empty string
* - on windows or cygwin: replace \ with /
* - strip leading spaces
* - prepends "/" if not present already
* - resolve "/../", "//" and "/./" the usual way:
* the first one removes a preceding component, the other two
* get compressed to "/".
* - "/." and "/.." at the end are similar, but always leave a trailing
* "/"
*
* /blah/.. gets /
* /blah/../foo gets /foo
* /abc/./xyz gets /abc/xyz
* /abc//xyz gets /abc/xyz
*/
void buffer_path_simplify(buffer *b)
{
char *out = b->ptr;
char * const end = b->ptr + b->used - 1;
if (__builtin_expect( (buffer_is_blank(b)), 0)) {
buffer_blank(b);
return;
}
#if defined(_WIN32) || defined(__CYGWIN__)
/* cygwin is treating \ and / the same, so we have to that too */
for (char *p = b->ptr; *p; p++) {
if (*p == '\\') *p = '/';
}
#endif
*end = '/'; /*(end of path modified to avoid need to check '\0')*/
char *walk = out;
if (__builtin_expect( (*walk == '/'), 1)) {
/* scan to detect (potential) need for path simplification
* (repeated '/' or "/.") */
do {
if (*++walk == '.' || *walk == '/')
break;
do { ++walk; } while (*walk != '/');
} while (walk != end);
if (__builtin_expect( (walk == end), 1)) {
/* common case: no repeated '/' or "/." */
*end = '\0'; /* overwrite extra '/' added to end of path */
return;
}
out = walk-1;
}
else {
if (walk[0] == '.' && walk[1] == '/')
*out = *++walk;
else if (walk[0] == '.' && walk[1] == '.' && walk[2] == '/')
*out = *(walk += 2);
else {
while (*++walk != '/') ;
out = walk;
}
++walk;
}
while (walk <= end) {
/* previous char is '/' at this point (or start of string w/o '/') */
if (__builtin_expect( (walk[0] == '/'), 0)) {
/* skip repeated '/' (e.g. "///" -> "/") */
if (++walk < end)
continue;
else {
++out;
break;
}
}
else if (__builtin_expect( (walk[0] == '.'), 0)) {
/* handle "./" and "../" */
if (walk[1] == '.' && walk[2] == '/') {
/* handle "../" */
while (out > b->ptr && *--out != '/') ;
*out = '/'; /*(in case path had not started with '/')*/
if ((walk += 3) >= end) {
++out;
break;
}
else
continue;
}
else if (walk[1] == '/') {
/* handle "./" */
if ((walk += 2) >= end) {
++out;
break;
}
continue;
}
else {
/* accept "." if not part of "../" or "./" */
*++out = '.';
++walk;
}
}
while ((*++out = *walk++) != '/') ;
}
*out = *end = '\0'; /* overwrite extra '/' added to end of path */
b->used = (out - b->ptr) + 1;
/*buffer_truncate(b, out - b->ptr);*/
}
void buffer_to_lower(buffer * const b) {
unsigned char * const restrict s = (unsigned char *)b->ptr;
const uint_fast32_t used = b->used;
for (uint_fast32_t i = 0; i < used; ++i) {
if (light_isupper(s[i])) s[i] |= 0x20;
}
}
void buffer_to_upper(buffer * const b) {
unsigned char * const restrict s = (unsigned char *)b->ptr;
const uint_fast32_t used = b->used;
for (uint_fast32_t i = 0; i < used; ++i) {
if (light_islower(s[i])) s[i] &= 0xdf;
}
}
|
8ea73b85538c6b2b0f83d38d6bf4225ffe8c070e
|
{
"blob_id": "8ea73b85538c6b2b0f83d38d6bf4225ffe8c070e",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-30T17:40:54",
"content_id": "7cacfb305e6ef63aaaf1f974bb78ef9c46e18b95",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "7df190df28da7e4ff166e55dc8ce780f11236a9f",
"extension": "c",
"filename": "buffer.c",
"fork_events_count": 281,
"gha_created_at": "2013-01-06T17:21:29",
"gha_event_created_at": "2023-05-29T20:56:24",
"gha_language": null,
"gha_license_id": null,
"github_id": 7470282,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 33813,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/router/lighttpd/src/buffer.c",
"provenance": "stack-edu-0000.json.gz:179789",
"repo_name": "mirror/dd-wrt",
"revision_date": "2023-08-30T17:40:54",
"revision_id": "8f2934a5a2adfbb59b471375aa3a38de5d036531",
"snapshot_id": "25416946e6132aa54b35809de61834a1825a9a36",
"src_encoding": "UTF-8",
"star_events_count": 520,
"url": "https://raw.githubusercontent.com/mirror/dd-wrt/8f2934a5a2adfbb59b471375aa3a38de5d036531/src/router/lighttpd/src/buffer.c",
"visit_date": "2023-08-31T14:54:47.496685",
"added": "2024-11-19T02:37:18.531152+00:00",
"created": "2023-08-30T17:40:54",
"int_score": 3,
"score": 2.71875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0018.json.gz"
}
|
package navigator;
import com.vaadin.navigator.Navigator;
import com.vaadin.server.VaadinRequest;
import com.vaadin.ui.UI;
/**
*
* @author Alejandro Duarte.
*
*/
@SuppressWarnings("serial")
public class NavigatorUI extends UI {
@Override
protected void init(VaadinRequest request) {
Navigator navigator = new Navigator(this, this);
navigator.addView("", new Welcome());
navigator.addView("page1", new Page1());
navigator.addView("page2", new Page2());
}
}
|
c23f0d0fb80a1733b403d0fadadbbf3527cf34eb
|
{
"blob_id": "c23f0d0fb80a1733b403d0fadadbbf3527cf34eb",
"branch_name": "refs/heads/main",
"committer_date": "2020-12-30T01:29:17",
"content_id": "9f5cc4fceb36a8fafbe220968f0c440a07e8fc66",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "dd4a8106f9bdb2cb42d192644766fd93cb529eb5",
"extension": "java",
"filename": "NavigatorUI.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 319441484,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 502,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/_/04/navigator/src/navigator/NavigatorUI.java",
"provenance": "stack-edu-0022.json.gz:693117",
"repo_name": "paullewallencom/vaadin-978-1-7821-6226-1",
"revision_date": "2020-12-30T01:29:17",
"revision_id": "ee8d5a97822834d93c59058b38e35a49055c69a0",
"snapshot_id": "42c8b1a503875b9626b83c4fbc74dc50994ff9ab",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/paullewallencom/vaadin-978-1-7821-6226-1/ee8d5a97822834d93c59058b38e35a49055c69a0/_/04/navigator/src/navigator/NavigatorUI.java",
"visit_date": "2023-02-05T20:29:23.100623",
"added": "2024-11-19T01:40:53.365500+00:00",
"created": "2020-12-30T01:29:17",
"int_score": 2,
"score": 2.171875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0040.json.gz"
}
|
import IMMOClientMutator from "../../../mmocore/IMMOClientMutator";
import GameClient from "../../GameClient";
import PartyMemberPosition from "../../incoming/game/PartyMemberPosition";
import { GlobalEvents } from "../../../mmocore/EventEmitter";
export default class PartyMemberPositionMutator extends IMMOClientMutator<
GameClient,
PartyMemberPosition
> {
update(packet: PartyMemberPosition): void {
Object.keys(packet.Members).forEach(k => {
const objId: number = parseInt(k, 10);
const char = this.Client.PartyList.getEntryByObjectId(objId);
if (char) {
const [_x, _y, _z] = packet.Members[objId];
char.setLocation(_x, _y, _z);
char.calculateDistance(this.Client.ActiveChar);
GlobalEvents.fire("PartyMemberPosition", { member: char });
}
});
}
}
|
9426ea39a2193943975a02fe0cf9cf05824c233e
|
{
"blob_id": "9426ea39a2193943975a02fe0cf9cf05824c233e",
"branch_name": "refs/heads/master",
"committer_date": "2021-10-08T17:54:25",
"content_id": "dd4a1e4e1c6e1efdcee5d5cdf8d15737be53eacf",
"detected_licenses": [
"MIT"
],
"directory_id": "572ea71e3ce818bec51f6c591929b29bf5c7e67a",
"extension": "ts",
"filename": "PartyMemberPositionMutator.ts",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 824,
"license": "MIT",
"license_type": "permissive",
"path": "/src/network/mutators/game/PartyMemberPositionMutator.ts",
"provenance": "stack-edu-0073.json.gz:951193",
"repo_name": "VardanNersesyan/l2js-client",
"revision_date": "2021-10-08T17:54:25",
"revision_id": "027e85f5c8b563765ec5afab6c2c2a44813a2897",
"snapshot_id": "4788723dafadd70c322b07d32e24d7ca30803a79",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/VardanNersesyan/l2js-client/027e85f5c8b563765ec5afab6c2c2a44813a2897/src/network/mutators/game/PartyMemberPositionMutator.ts",
"visit_date": "2023-08-14T15:45:48.200144",
"added": "2024-11-19T01:12:36.030450+00:00",
"created": "2021-10-08T17:54:25",
"int_score": 2,
"score": 2.40625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0091.json.gz"
}
|
<?php
namespace App\Http\Controllers\Backend;
use App\Models\Pr;
use App\Models\PrDetail;
use App\Models\Po;
use App\User;
use App\Models\Division;
use App\Models\Spk;
use App\Models\Supplier;
use App\Notifications\Notif;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Cache;
use Session;
use File;
use Hash;
use Validator;
use PDF;
use Excel;
use Yajra\Datatables\Facades\Datatables;
use App\Http\Controllers\Controller;
class PrController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index(Request $request)
{
$year = Pr::select(DB::raw('YEAR(datetime_order) as year'))->orderBy('datetime_order', 'ASC')->distinct()->get();
$month = ['Januari', 'Febuari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];
$user = Pr::join('users', 'users.id', '=', 'pr.user_id')
->select('users.first_name', 'users.last_name', 'users.id')
->orderBy('users.first_name', 'ASC')->distinct();
if(!Auth::user()->can('allUser-pr'))
{
$user->whereIn('pr.user_id', Auth::user()->staff());
}
$user = $user->get();
$division = Division::where('active', 1)->get();
$spk = Spk::all();
return view('backend.pr.index')->with(compact('request', 'year', 'month', 'user', 'spk', 'division'));
}
public function datatables(Request $request)
{
$f_user = $this->filter($request->f_user, Auth::id());
$f_month = $this->filter($request->f_month, date('n'));
$f_year = $this->filter($request->f_year, date('Y'));
$search = $this->filter($request->search);
$index = Pr::leftJoin('spk', 'pr.spk_id', 'spk.id')
->leftJoin('users', 'users.id', '=', 'pr.user_id')
->select('pr.*')
->addSelect('spk.no_spk', 'spk.name as spk_name', 'users.first_name', 'users.last_name')
->orderBy('pr.id', 'DESC');
if($search != '')
{
$index->where(function ($query) use ($search) {
$query->where('spk.no_spk', 'like', '%'.$search.'%')
->orWhere('spk.name', 'like', '%'.$search.'%')
->orWhere('pr.no_pr', 'like', '%'.$search.'%')
->orWhere('pr.barcode', 'like', '%'.$search.'%');
});
}
else
{
if($f_month != '')
{
$index->whereMonth('pr.datetime_order', $f_month);
}
if($f_year != '')
{
$index->whereYear('pr.datetime_order', $f_year);
}
if($f_user == 'staff')
{
$index->whereIn('pr.user_id', Auth::user()->staff());
}
else if($f_user != '')
{
$index->where('pr.user_id', $f_user);
}
}
$index = $index->get();
$datatables = Datatables::of($index);
$datatables->editColumn('name', function ($index) {
$html = '<b>Name</b> : ' . $index->name . '<br/>';
$html .= '<b>User</b> : ' . $index->users->fullname . '<br/>';
$html .= '<b>No SPK</b> : ' . ($index->no_spk ?? $index->type) . '<br/>';
$html .= '<b>Created At</b> : ' . date('d-m-Y H:i', strtotime($index->created_at)) . '<br/>';
$html .= '<b>Division</b> : ' . $index->divisions->name . '<br/>';
$html .= '<b>No PR</b> : ' . $index->no_pr . '<br/>';
return $html;
});
$datatables->editColumn('spk', function ($index){
return $index->no_spk ?? $index->type;
});
$datatables->editColumn('first_name', function ($index){
return $index->users->fullname ?? 'No Name';
});
$datatables->editColumn('datetime_order', function ($index){
return date('d-m-Y', strtotime($index->datetime_order));
});
$datatables->editColumn('created_at', function ($index){
return date('d-m-Y H:i', strtotime($index->created_at));
});
$datatables->editColumn('deadline', function ($index){
return date('d-m-Y', strtotime($index->deadline));
});
$datatables->editColumn('division_id', function ($index){
return $index->divisions->name;
});
$datatables->addColumn('check', function ($index) {
$html = '';
if( Auth::user()->can('check-pr', $index) )
{
$html .= '
<input type="checkbox" class="check" value="'.$index->id.'" name="id[]" form="action">
';
}
return $html;
});
$datatables->addColumn('action', function ($index) {
$html = '';
if( Auth::user()->can('update-pr', $index) )
{
$html .= '
<a href="'.route('backend.pr.edit', ['id' => $index->id]).'" class="btn btn-xs btn-warning"><i class="fa fa-edit"></i> Edit</a><br/>
';
}
if( Auth::user()->can('delete-pr', $index) )
{
$html .= '
<button type="button" class="btn btn-xs btn-danger delete-pr" data-toggle="modal" data-target="#delete-pr" data-id="'.$index->id.'"><i class="fa fa-trash" aria-hidden="true"></i> Delete</button><br/>
';
}
if( Auth::user()->can('pdf-pr') )
{
$html .= '
<button type="button" class="btn btn-xs btn-primary pdf-pr" data-toggle="modal" data-target="#pdf-pr" data-id="'.$index->id.'"><i class="fa fa-file-pdf-o" aria-hidden="true"></i> PDF</button><br/>
';
}
return $html;
});
$datatables = $datatables->make(true);
return $datatables;
}
public function storeProjectPr(Request $request)
{
$deleted = Pr::onlyTrashed()->where('no_pr', $this->getPr($request))->get();
if($deleted)
{
Pr::onlyTrashed()->where('no_pr', $this->getPr($request))->forceDelete();
}
$index = new Pr;
$spk = Spk::find($request->spk_id);
$validator = Validator::make($request->all(), [
'spk_id' => 'required',
'division_id' => 'required',
]);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput()->with('createProjectPr-pr-error', 'Something Errors');;
}
$index->spk_id = $request->spk_id;
$index->user_id = Auth::id();
$index->type = 'PROJECT';
$index->no_pr = $this->getPr($request);
$index->name = $request->name;
$index->datetime_order = date('Y-m-d H:i:s');
$index->division_id = $request->division_id;
$index->barcode = substr($spk->spk, -3) . substr($index->no_pr, -4) . date('dm', strtotime($index->datetime_order)) . getConfigValue('pr_code');
$index->save();
saveArchives($index, Auth::id(), 'Create pr', $request->except('_token'));
return redirect()->route('backend.pr.edit', [$index->id]);
}
public function storeOfficePr(Request $request)
{
$deleted = Pr::onlyTrashed()->where('no_pr', $this->getPr($request))->get();
if($deleted)
{
Pr::onlyTrashed()->where('no_pr', $this->getPr($request))->forceDelete();
}
$index = new Pr;
$index->spk_id = null;
$index->user_id = Auth::id();
$index->type = 'OFFICE';
$index->no_pr = $this->getPr($request);
$index->name = "For Office";
$index->datetime_order = date('Y-m-d H:i:s');
$index->division_id = Auth::user()->division_id;
$index->barcode = '000' . substr($index->no_pr, -4) . date('dm', strtotime($index->datetime_order)) . getConfigValue('pr_code');
$index->save();
saveArchives($index, Auth::id(), 'Create pr', $request->except('_token'));
return redirect()->route('backend.pr.edit', [$index->id]);
}
public function storePaymentPr(Request $request)
{
$deleted = Pr::onlyTrashed()->where('no_pr', $this->getPr($request))->get();
if($deleted)
{
Pr::onlyTrashed()->where('no_pr', $this->getPr($request))->forceDelete();
}
$index = new Pr;
$index->spk_id = NULL;
$index->user_id = Auth::id();
$index->type = 'PAYMENT';
$index->no_pr = $this->getPr($request);
$index->name = "For Payment";
$index->datetime_order = date('Y-m-d H:i:s');
$index->division_id = $request->division_id;
$index->barcode = '001' . substr($index->no_pr, -4) . date('dm', strtotime($index->datetime_order)) . getConfigValue('pr_code');
$index->save();
saveArchives($index, Auth::id(), 'Create pr', $request->except('_token'));
return redirect()->route('backend.pr.edit', [$index->id]);
}
public function edit(Pr $index)
{
if(!Auth::user()->can('update-pr', $index))
{
return redirect()->route('backend.pr')->with('failed', 'Access Denied');
}
if($index->type == 'PAYMENT')
{
$purchasing = User::where(function ($query) {
$query->whereIn('position_id', getConfigValue('financial_position', true))
->orWhereIn('id', getConfigValue('financial_user', true));
})->where('active', 1)->get();
}
else
{
$purchasing = User::where(function ($query) {
$query->whereIn('position_id', getConfigValue('purchasing_position', true))
->orWhereIn('id', getConfigValue('purchasing_user', true));
})->where('active', 1)->get();
}
$division = Division::all();
$spk = Spk::all();
return view('backend.pr.edit')->with(compact('index', 'purchasing', 'division', 'spk'));
}
public function update(Pr $index, Request $request)
{
if(!Auth::user()->can('update-pr', $index))
{
return redirect()->route('backend.pr')->with('failed', 'Access Denied');
}
$validator = Validator::make($request->all(), [
'spk_id' => 'required',
'name' => 'required',
'division_id' => 'required',
]);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput();
}
saveArchives($index, Auth::id(), 'update pr', $request->except('_token'));
$index->spk_id = $request->spk_id;
$index->name = $request->name;
$index->division_id = $request->division_id;
$index->save();
return redirect()->back()->with('success', 'Data has been updated');
}
public function delete(Request $request)
{
$index = Pr::find($request->id);
if(!Auth::user()->can('delete-pr', $index))
{
return redirect()->route('backend.pr')->with('failed', 'Access Denied');
}
saveArchives($index, Auth::id(), 'delete pr');
Pr::destroy($request->id);
return redirect()->back()->with('success', 'Data has been deleted');
}
public function action(Request $request)
{
if ($request->action == 'delete' && is_array($request->id)) {
foreach ($request->id as $list){
if (Auth::user()->can('delete-pr', Pr::find($list)))
{
$id[] = $list;
}
}
$index = Pr::whereIn('id', $id)->get();
saveMultipleArchives(Pr::class, $index, Auth::id(), "delete pr");
Pr::destroy($id);
return redirect()->back()->with('success', 'Data Selected Has Been Deleted');
}
return redirect()->back()->with('info', 'No data change');
}
public function datatablesPrDetail(Pr $index, Request $request)
{
$datatables = Datatables::of($index->pr_details);
$datatables->editColumn('quantity', function ($index) {
return $index->quantity . ' ' . $index->unit;
});
$datatables->editColumn('purchasing_id', function ($index) {
return $index->purchasing->fullname;
});
$datatables->editColumn('status', function ($index) {
$html = $index->status;
if($index->po->count() > 0)
{
$html .= ' (ORDERED)';
}
return $html;
});
$datatables->editColumn('item', function ($index) {
if($index->type == 'PAYMENT')
{
return $index->item . ' ' . number_format($index->value);
}
else
{
return $index->item;
}
});
$datatables->editColumn('deadline', function ($index) {
return date('d-m-Y H:i', strtotime($index->deadline));
});
$datatables->addColumn('check', function ($index) {
$html = '';
if(Auth::user()->can('checkDetail-pr', $index) )
{
$html .= '
<input type="checkbox" class="check-detail" value="'.$index->id.'" name="id[]" form="action-detail">
';
}
return $html;
});
$datatables->addColumn('action', function ($index) {
$html = '';
if(Auth::user()->can('updateDetail-pr', $index))
{
$html .= '
<button type="button" class="btn btn-xs btn-warning edit-detail" data-toggle="modal" data-target="#edit-detail"
data-id="'.$index->id.'"
data-item="'.$index->item.'"
data-quantity="'.$index->quantity.'"
data-unit="'.$index->unit.'"
data-purchasing_id="'.$index->purchasing_id.'"
data-deadline="'.date('d F Y', strtotime($index->deadline)).'"
data-no_rekening="'.$index->no_rekening.'"
data-value="'.$index->value.'"
><i class="fa fa-pencil" aria-hidden="true"></i></button>
';
}
if(Auth::user()->can('deleteDetail-pr', $index))
{
$html .= '
<button type="button" class="btn btn-xs btn-danger delete-detail" data-toggle="modal" data-target="#delete-detail" data-id="'.$index->id.'"><i class="fa fa-trash" aria-hidden="true"></i></button>
';
}
return $html;
});
$datatables = $datatables->make(true);
return $datatables;
}
public function storePrDetail(Request $request)
{
$pr = Pr::find($request->pr_id);
if(!Auth::user()->can('update-pr', $pr))
{
return redirect()->route('backend.pr')->with('failed', 'Access Denied');
}
$index = new PrDetail;
if(isset($pr->spk))
{
if($pr->spk->code_admin != 0 && $pr->spk->code_admin != -2)
{
$index->service = 1;
}
}
if(in_array($pr->type, ['PROJECT', 'OFFICE']))
{
$validator = Validator::make($request->all(), [
'item' => 'required',
'quantity' => 'required|integer',
'unit' => 'required',
'purchasing_id' => 'required|integer',
'deadline' => 'required|date',
]);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput()->with('create-detail-error', '');
}
$index->pr_id = $request->pr_id;
$index->item = $request->item;
$index->quantity = $request->quantity;
$index->unit = $request->unit;
$index->deadline = date('Y-m-d H:i:s', strtotime($request->deadline));
$index->purchasing_id = $request->purchasing_id;
$index->save();
}
else
{
$validator = Validator::make($request->all(), [
'item' => 'required',
'purchasing_id' => 'required|integer',
'deadline' => 'deadline|date',
]);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput()->with('create-detail-error', '');
}
$index->pr_id = $request->pr_id;
$index->item = $request->item;
$index->quantity = 1;
$index->unit = '';
$index->deadline = date('Y-m-d H:i:s', strtotime($request->deadline));
$index->purchasing_id = $request->purchasing_id;
$index->no_rekening = $request->no_rekening;
$index->value = $request->value;
$index->save();
}
saveArchives($index, Auth::id(), 'create pr detail', $request->except('_token'));
$super_admin_notif = User::where(function ($query) {
$query->whereIn('position_id', getConfigValue('super_admin_position', true))
->orWhereIn('id', getConfigValue('super_admin_user', true));
})
->get();
$html = '
New Purchase Request, Item : '.$request->item.'
';
foreach ($super_admin_notif as $list) {
$list->notify(new Notif(Auth::user()->nickname, $html, route('backend.pr.unconfirm') ) );
}
return redirect()->back()->with('success', 'Data Has Been Added');
}
public function updatePrDetail(Request $request)
{
$index = PrDetail::find($request->id);
if(!Auth::user()->can('updateDetail-pr', $index))
{
return redirect()->route('backend.pr')->with('failed', 'Access Denied');
}
saveArchives($index, Auth::id(), 'update pr detail', $request->except('_token'));
if(in_array($index->pr->type, ['PROJECT', 'OFFICE']))
{
$validator = Validator::make($request->all(), [
'item' => 'required',
'quantity' => 'required|integer',
'unit' => 'required',
'purchasing_id' => 'required|integer',
'deadline' => 'required|date',
]);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput()->with('create-detail-error', '');
}
$index->item = $request->item;
$index->quantity = $request->quantity;
$index->unit = $request->unit;
$index->deadline = date('Y-m-d H:i:s', strtotime($request->deadline));
$index->purchasing_id = $request->purchasing_id;
$index->value = 0;
$index->confirm = 0;
$index->save();
}
else
{
$validator = Validator::make($request->all(), [
'item' => 'required',
'purchasing_id' => 'required|integer',
'deadline' => 'required|date',
]);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput()->with('create-detail-error', '');
}
$index->item = $request->item;
$index->quantity = 1;
$index->unit = '';
$index->deadline = date('Y-m-d H:i:s', strtotime($request->deadline));
$index->purchasing_id = $request->purchasing_id;
$index->value = $request->value;
$index->save();
}
return redirect()->back()->with('success', 'Data Has Been Updated');
}
public function deletePrDetail(Request $request)
{
$index = PrDetail::find($request->id);
if(!Auth::user()->can('deleteDetail-pr', $index))
{
return redirect()->route('backend.pr')->with('failed', 'Access Denied');
}
saveArchives($index, Auth::id(), 'delete pr detail');
PrDetail::destroy($request->id);
return redirect()->back()->with('success', 'Data Has Been Deleted');
}
public function actionPrDetail(Request $request)
{
if ($request->action == 'delete' && is_array($request->id)) {
foreach ($request->id as $list){
if (Auth::user()->can('deleteDetail-pr', PrDetail::find($list)))
{
$id[] = $list;
}
}
$index = PrDetail::whereIn('id', $id)->get();
saveMultipleArchives(PrDetail::class, $index, Auth::id(), "delete pr detail");
PrDetail::destroy($id);
return redirect()->back()->with('success', 'Data Selected Has Been Deleted');
}
return redirect()->back()->with('info', 'No data change');
}
public function getSpkItem(Request $request)
{
$index = PrDetail::select(DB::raw('
pr_details.*,
spk.no_spk
'))
->leftJoin('pr', 'pr_details.pr_id', '=', 'pr.id')
->leftJoin('users', 'pr.user_id', '=', 'users.id')
->select('pr.no_pr', 'pr_details.item', DB::raw('CONCAT(users.first_name, " ", users.last_name) AS name'), 'pr_details.quantity', 'pr_details.unit')
->where('pr.spk_id', $request->id)
->where('pr_details.status', 'CONFIRMED')
->get();
return $index;
}
public function unconfirm(Request $request)
{
$year = Pr::select(DB::raw('YEAR(datetime_order) as year'))->orderBy('datetime_order', 'ASC')->distinct()->get();
$month = ['Januari', 'Febuari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];
return view('backend.pr.unconfirm')->with(compact('request', 'year', 'month'));
}
public function datatablesUnconfirm(Request $request)
{
$f_month = $this->filter($request->f_month);
$f_year = $this->filter($request->f_year);
$f_service = $this->filter($request->f_service);
$search = $this->filter($request->search);
$index = PrDetail::where('pr_details.status', 'WAITING')->leftJoin('pr', 'pr.id', 'pr_details.pr_id')->leftJoin('spk', 'spk.id', 'pr.spk_id')->select('pr_details.*');
if($search != '')
{
$index->where(function($query) use ($search) {
$query->where('pr.no_pr', 'like', '%'.$search.'%')
->orWhere('pr.name', 'like', '%'.$search.'%')
->orWhere('pr_details.item', 'like', '%'.$search.'%')
->orWhere('spk.no_spk', 'like', '%'.$search.'%')
->orWhere('spk.name', 'like', '%'.$search.'%');
});
}
else
{
if($f_month != '')
{
$index->whereMonth('pr.datetime_order', $f_month);
}
if($f_year != '')
{
$index->whereYear('pr.datetime_order', $f_year);
}
if($f_service != '')
{
$index->where('pr_details.service', $f_service);
}
}
$index = $index->get();
$datatables = Datatables::of($index);
$datatables->editColumn('pr_id', function ($index) {
$html = '<b>No SPK</b> : ' . ($index->pr->spk->no_spk ?? $index->pr->type) . '<br/>';
$html .= '<b>Name SPK</b> : ' . ($index->pr->spk->name ?? $index->pr->type) . '<br/>';
$html .= '<b>No PR</b> : ' . ($index->pr->no_pr) . '<br/>';
$html .= '<b>Order Name</b> : ' . ($index->pr->users->fullname) . '<br/>';
return $html;
});
$datatables->editColumn('item', function ($index) {
$html = '<b>Item</b> : ' . $index->item . '<br/>';
$html .= '<b>Quantity</b> : ' . ($index->quantity . ' ' . $index->unit) . '<br/>';
return $html;
});
$datatables->editColumn('deadline', function ($index){
return date('d-m-Y H:i', strtotime($index->deadline));
});
$datatables->addColumn('confirm', function ($index) {
$html = '';
if(Auth::user()->can('confirm-pr'))
{
$html .= '
<input type="checkbox" class="check-confirm" value="'.$index->id.'" name="confirm[]" form="action">
';
}
return $html;
});
$datatables->addColumn('confirm_not_service', function ($index) {
$html = '';
if(Auth::user()->can('confirm-pr'))
{
$html .= '
<input type="checkbox" class="check-confirm_not_service" value="'.$index->id.'" name="confirm_not_service[]" form="action">
';
}
return $html;
});
$datatables->addColumn('reject', function ($index) {
$html = '';
if(Auth::user()->can('confirm-pr'))
{
$html .= '
<input type="checkbox" class="check-reject" value="'.$index->id.'" name="reject[]" form="action">
';
}
return $html;
});
$datatables = $datatables->make(true);
return $datatables;
}
public function updateConfirm(Request $request)
{
$date = date('Y-m-d H:i:s');
if (!empty($request->confirm)) {
$index = PrDetail::whereIn('id', $request->confirm)->orderBy('purchasing_id', 'ASC')->get();
saveMultipleArchives(PrDetail::class, $index, Auth::id(), "confirm pr detail");
$number_item_purchasing = 0;
$current_purchasing = -1;
$data = '';
foreach ($index as $list) {
if($current_purchasing == $list->purchasing_id)
{
$number_item_purchasing++;
array_push($data, $list->id);
}
else
{
if($current_purchasing != -1)
{
$html = '
New Confirm Purchase Request, Count Item : '.$number_item_purchasing.'
';
User::find($current_purchasing)->notify(new Notif(Auth::user()->nickname, $html, route('backend.pr.confirm', ['f_id' => implode(',', $data)]) ) );
}
$number_item_purchasing = 1;
$current_purchasing = $list->purchasing_id;
$data = [$list->id];
}
}
$html = '
New Confirm Purchase Request, Count Item : '.$number_item_purchasing.'
';
PrDetail::whereIn('id', $request->confirm)->update(['status' => 'CONFIRMED', 'datetime_confirm' => $date]);
}
if (!empty($request->confirm_not_service)) {
$index = PrDetail::whereIn('id', $request->confirm_not_service)->orderBy('purchasing_id', 'ASC')->get();
saveMultipleArchives(PrDetail::class, $index, Auth::id(), "confirm pr detail");
$number_item_purchasing = 0;
$current_purchasing = -1;
$data = '';
foreach ($index as $list) {
if($current_purchasing == $list->purchasing_id)
{
$number_item_purchasing++;
array_push($data, $list->id);
}
else
{
if($current_purchasing != -1)
{
$html = '
New Confirm Purchase Request, Count Item : '.$number_item_purchasing.'
';
User::find($current_purchasing)->notify(new Notif(Auth::user()->nickname, $html, route('backend.pr.confirm', ['f_id' => implode(',', $data)]) ) );
}
$number_item_purchasing = 1;
$current_purchasing = $list->purchasing_id;
$data = [$list->id];
}
}
$html = '
New Confirm Purchase Request, Count Item : '.$number_item_purchasing.'
';
PrDetail::whereIn('id', $request->confirm_not_service)->update(['status' => 'CONFIRMED', 'service' => 0, 'datetime_confirm' => $date]);
}
if (!empty($request->reject)) {
$index = PrDetail::whereIn('id', $request->reject)->orderBy('pr_id', 'ASC')->get();
saveMultipleArchives(PrDetail::class, $index, Auth::id(), "reject pr detail");
$number_item_pr = 0;
$user_id = -1;
$current_pr = -1;
foreach ($index as $list) {
if($current_pr == $list->pr_id)
{
$number_item_pr++;
}
else
{
if($current_pr != -1)
{
$html = '
Item has been rejected, Count Item : '.$number_item_pr.'
';
User::find($user_id)->notify(new Notif(Auth::user()->nickname, $html, route('backend.pr.edit', $current_pr) ) );
}
$number_item_pr = 1;
$current_pr = $list->pr_id;
$user_id = Pr::find($current_pr)->user_id;
}
}
$html = '
Item has been rejected, Count Item : '.$number_item_pr.'
';
PrDetail::whereIn('id', $request->reject)->update(['status' => 'REJECTED', 'datetime_confirm' => $date]);
}
return redirect()->back()->with('success', 'Data Has Been Updated');
}
public function confirm(Request $request)
{
$year = Pr::select(DB::raw('YEAR(datetime_order) as year'))->orderBy('datetime_order', 'ASC')->distinct()->get();
$month = ['Januari', 'Febuari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];
$purchasing = User::where(function ($query) {
$query->whereIn('position_id', getConfigValue('purchasing_position', true))
->orWhereIn('id', getConfigValue('purchasing_user', true));
})->where('active', 1);
$finance = User::where(function ($query) {
$query->whereIn('position_id', getConfigValue('financial_position', true))
->orWhereIn('id', getConfigValue('financial_user', true));
})->where('active', 1);
$purchasing = $purchasing->get();
$finance = $finance->get();
$supplier = Supplier::all();
return view('backend.pr.confirm')->with(compact('request', 'year', 'month', 'purchasing', 'finance', 'supplier'));
}
public function datatablesConfirm(Request $request)
{
$f_month = $this->filter($request->f_month, date('n'));
$f_year = $this->filter($request->f_year, date('Y'));
$f_purchasing = $this->filter($request->f_purchasing);
$f_status = $this->filter($request->f_status);
$f_day = $this->filter($request->f_day);
$f_value = $this->filter($request->f_value);
$f_audit = $this->filter($request->f_audit);
$f_finance = $this->filter($request->f_finance);
$f_id = $this->filter($request->f_id);
$search = $this->filter($request->search);
$type = $this->filter($request->type);
$purchasing = User::where(function ($query) {
$query->whereIn('position_id', getConfigValue('purchasing_position' , true))
->orWhereIn('id', getConfigValue('purchasing_user' , true));
})
->get();
$finance = User::where(function ($query) {
$query->whereIn('position_id', getConfigValue('financial_position' , true))
->orWhereIn('id', getConfigValue('financial_user' , true));
})
->get();
$supplier = Supplier::select('*');
$index = PrDetail::withStatisticPo()
->join('pr', 'pr.id', 'pr_details.pr_id')
->leftJoin('spk', 'spk.id', 'pr.spk_id')
->select('pr_details.*')
->orderBy('pr_details.id', 'DESC');
switch ($type) {
case 'PROJECT':
$index->whereIn('pr.type', ['PROJECT', 'OFFICE']);
break;
case 'PAYMENT':
$index->where('pr.type', 'PAYMENT');
break;
default:
# code...
break;
}
if($search != '')
{
$index->where(function($query) use ($search) {
$query->where('pr_details.item', 'like', '%'.$search.'%')
->orWhere('pr.name', 'like', '%'.$search.'%')
->orWhere('pr.no_pr', 'like', '%'.$search.'%')
->orWhere('spk.no_spk', 'like', '%'.$search.'%');
});
}
else
{
if($f_month != '')
{
$index->whereMonth('pr_details.datetime_confirm', $f_month);
}
if($f_year != '')
{
$index->whereYear('pr_details.datetime_confirm', $f_year);
}
if($f_purchasing == 'staff')
{
$index->whereIn('pr_details.purchasing_id', Auth::user()->staff());
}
else if($f_purchasing != '')
{
$index->where('pr_details.purchasing_id', $f_purchasing);
}
if($f_status != '')
{
$index->where('pr_details.status_purchasing', $f_status);
}
switch ($f_day) {
case '4':
$index->whereDate('pr_details.datetime_confirm', '<=', date('Y-m-d', strtotime('-4 days')));
break;
case '3':
$index->whereDate('pr_details.datetime_confirm', date('Y-m-d', strtotime('-3 days')));
break;
case '2':
$index->whereDate('pr_details.datetime_confirm', date('Y-m-d', strtotime('-2 days')));
break;
case '1':
$index->whereDate('pr_details.datetime_confirm', date('Y-m-d', strtotime('-1 day')));
break;
case '0':
$index->whereDate('pr_details.datetime_confirm', date('Y-m-d'));
break;
default:
//
break;
}
if ($f_value != '' && $f_value == 0)
{
$index->whereColumn('pr_details.quantity', '>', DB::raw('COALESCE(`po`.`totalQuantity`, 0)'));
}
else if ($f_value == 1)
{
$index->whereColumn('pr_details.quantity', '<=', DB::raw('COALESCE(`po`.`totalQuantity`, 0)'));
}
if ($f_audit != '' && $f_audit == 0)
{
$index->where(function($query){
$query->whereColumn(DB::raw('COALESCE(count_po, 0)'), '>', DB::raw('COALESCE(count_check_audit, 0)'))
->orWhere(DB::raw('COALESCE(count_po, 0)'), 0);
});
}
else if ($f_audit == 1)
{
$index->where(function($query){
$query->whereColumn(DB::raw('COALESCE(count_po, 0)'), '<=', DB::raw('COALESCE(count_check_audit, 0)'))
->where(DB::raw('COALESCE(count_po, 0)'), '<>',0);
});
}
if ($f_finance != '' && $f_finance == 0)
{
$index->whereColumn(DB::raw('COALESCE(count_po, 0)'), '>', DB::raw('COALESCE(count_check_finance, 0)'));
}
else if ($f_finance == 1)
{
$index->whereColumn(DB::raw('COALESCE(count_po, 0)'), '<=', DB::raw('COALESCE(count_check_finance, 0)'));
}
}
$index = $index->get();
$datatables = Datatables::of($index);
$datatables->addColumn('info', function ($index) {
$html = '<b>No SPK</b> : ' . ($index->pr->spk->no_spk ?? $index->pr->type) . '<br/>';
$html .= '<b>Name SPK</b> : ' . ($index->pr->spk->name ?? $index->pr->type) . '<br/>';
$html .= '<b>No PR</b> : ' . ($index->pr->no_pr) . '<br/>';
$html .= '<b>Order Name</b> : ' . ($index->pr->users->fullname) . '<br/><br/>';
$html .= '<b>Item</b> : ' . $index->item . '<br/>';
$html .= '<b>Quantity</b> : ' . ($index->quantity . ' ' . $index->unit) . '<br/><br/>';
$html .= '<b>Deadline</b> : ' . date('d-m-Y H:i', strtotime($index->deadline)) . '<br/>';
$html .= '<b>Confirm</b> : ' . date('d-m-Y H:i', strtotime($index->datetime_confirm)) . '<br/>';
$html .= '<b>Request At</b> : ' . date('d-m-Y H:i', strtotime($index->created_at)) . '<br/>';
return $html;
});
$datatables->editColumn('purchasing', function ($index) use ($purchasing, $finance, $type) {
$html = '';
if(Auth::user()->can('changePurchasing-pr'))
{
$html .= '<select class="form-control change-purchasing" name="purchasing_id" data-id='.$index->id.'>';
if($type == "PROJECT")
{
foreach($purchasing as $list)
{
$html .= '<option value="'.$list->id.'" '. ($list->id == $index->purchasing_id ? 'selected' : '') .'>'.$list->fullname.'</option>';
}
}
else if ($type == "PAYMENT")
{
foreach($finance as $list)
{
$html .= '<option value="'.$list->id.'" '. ($list->id == $index->purchasing_id ? 'selected' : '') .'>'.$list->fullname.'</option>';
}
}
$html .= '</select>';
}
else
{
$html .= $index->purchasing;
}
$html .= '<br/><select class="form-control change-status" name="status" data-id='.$index->id.'>';
$html .= '<option value="NONE" '. ($index->status == "NONE" ? 'selected' : '') .'>Set Status</option>';
$html .= '<option value="PENDING" '. ($index->status == "PENDING" ? 'selected' : '') .'>Pending</option>';
$html .= '<option value="STOCK" '. ($index->status == "STOCK" ? 'selected' : '') .'>Stock</option>';
$html .= '<option value="CANCEL" '. ($index->status == "CANCEL" ? 'selected' : '') .'>Cancel</option>';
$html .= '</select>';
if(Auth::user()->can('changePurchasing-pr'))
{
$html .= '<br/>
<button type="button" class="btn btn-block btn-xs btn-warning revision-detail" data-toggle="modal" data-target="#revision-detail" data-id="'.$index->id.'">Set Revision</button>
';
}
return $html;
});
// with table po
$datatables->addColumn('po', function ($index) use ($supplier) {
return view('backend.pr.datatables.poProject', compact('index', 'supplier'));
});
$datatables->editColumn('check_audit', function ($index) {
$html = '';
if($index->value !== NULL && Auth::user()->can('checkAudit-pr'))
{
$html .= '<input type="checkbox" data-id="' . $index->id . '" value="1" name="check_audit" '.($index->check_audit ? 'checked' : '').'>';
}
else
{
$html .= $index->check_audit ? '<i class="fa fa-check" aria-hidden="true"></i>' : '';
}
return $html;
});
$datatables->editColumn('check_finance', function ($index) {
$html = '';
if($index->value !== NULL && Auth::user()->can('checkFinance-pr'))
{
$html .= '<input type="checkbox" data-id="' . $index->id . '" value="1" name="check_finance" '.($index->check_finance ? 'checked' : '').'>';
}
else
{
$html .= $index->check_finance ? '<i class="fa fa-check" aria-hidden="true"></i>' : '';
}
return $html;
});
$datatables->editColumn('note_audit', function ($index) {
$html = '';
if($index->value !== NULL && Auth::user()->can('noteAudit-pr'))
{
$html .= '<textarea class="note_audit form-control" data-id="' . $index->id . '" name="note_audit">'.$index->note_audit.'</textarea>';
}
else
{
$html .= $index->note_audit;
}
return $html;
});
$datatables->addColumn('action', function ($index) {
$html = '';
if( Auth::user()->can('deleteDetail-pr', $index) )
{
$html .= '
<button type="button" class="btn btn-xs btn-danger delete-detail" data-toggle="modal" data-target="#delete-detail" data-id="'.$index->id.'"><i class="fa fa-trash" aria-hidden="true"></i></button>
';
}
return $html;
});
$datatables->setRowClass(function ($index) {
if($index->deadline >= '2010-01-01' && $index->deadline < date('Y-m-d') && $index->status_received == 'WAITING')
{
return 'alert-danger';
}
});
$datatables = $datatables->make(true);
return $datatables;
}
public function getStatusConfirm(Request $request)
{
$f_month = $this->filter($request->f_month, date('n'));
$f_year = $this->filter($request->f_year, date('Y'));
$f_purchasing = $this->filter($request->f_purchasing, (
in_array(Auth::user()->position_id, getConfigValue('purchasing_position' , true))
|| in_array(Auth::id(), getConfigValue('purchasing_user' , true)) ? Auth::id() : ''));
$f_status = $this->filter($request->f_status);
$f_day = $this->filter($request->f_day);
$f_value = $this->filter($request->f_value);
$f_audit = $this->filter($request->f_audit);
$f_finance = $this->filter($request->f_finance);
$f_id = $this->filter($request->f_id);
$search = $this->filter($request->search);
$type = $this->filter($request->type);
$index = PrDetail::withStatisticPo()
->join('pr', 'pr.id', 'pr_details.pr_id')
->leftJoin('spk', 'spk.id', 'pr.spk_id')
->select('pr_details.*')
->orderBy('pr_details.id', 'DESC');
switch ($type) {
case 'PROJECT':
$index->whereIn('pr.type', ['PROJECT', 'OFFICE']);
break;
case 'PAYMENT':
$index->where('pr.type', 'PAYMENT');
break;
default:
# code...
break;
}
if($search != '')
{
$index->where(function($query) use ($search) {
$query->where('pr_details.item', 'like', '%'.$search.'%')
->orWhere('pr.name', 'like', '%'.$search.'%')
->orWhere('pr.no_pr', 'like', '%'.$search.'%')
->orWhere('spk.no_spk', 'like', '%'.$search.'%');
});
}
else
{
if($f_month != '')
{
$index->whereMonth('pr_details.datetime_confirm', $f_month);
}
if($f_year != '')
{
$index->whereYear('pr_details.datetime_confirm', $f_year);
}
if($f_purchasing == 'staff')
{
$index->whereIn('pr_details.purchasing_id', Auth::user()->staff());
}
else if($f_purchasing != '')
{
$index->where('pr_details.purchasing_id', $f_purchasing);
}
if($f_status != '')
{
$index->where('pr_details.status_purchasing', $f_status);
}
switch ($f_day) {
case '4':
$index->whereDate('pr_details.datetime_confirm', '<=', date('Y-m-d', strtotime('-4 days')));
break;
case '3':
$index->whereDate('pr_details.datetime_confirm', date('Y-m-d', strtotime('-3 days')));
break;
case '2':
$index->whereDate('pr_details.datetime_confirm', date('Y-m-d', strtotime('-2 days')));
break;
case '1':
$index->whereDate('pr_details.datetime_confirm', date('Y-m-d', strtotime('-1 day')));
break;
case '0':
$index->whereDate('pr_details.datetime_confirm', date('Y-m-d'));
break;
default:
//
break;
}
if ($f_value != '' && $f_value == 0)
{
$index->whereColumn('pr_details.quantity', '>', DB::raw('COALESCE(`po`.`totalQuantity`, 0)'));
}
else if ($f_value == 1)
{
$index->whereColumn('pr_details.quantity', '<=', DB::raw('COALESCE(`po`.`totalQuantity`, 0)'));
}
if ($f_audit != '' && $f_audit == 0)
{
$index->where(function($query){
$query->whereColumn(DB::raw('COALESCE(count_po, 0)'), '>', DB::raw('COALESCE(count_check_audit, 0)'))
->orWhere(DB::raw('COALESCE(count_po, 0)'), 0);
});
}
else if ($f_audit == 1)
{
$index->where(function($query){
$query->whereColumn(DB::raw('COALESCE(count_po, 0)'), '<=', DB::raw('COALESCE(count_check_audit, 0)'))
->where(DB::raw('COALESCE(count_po, 0)'), '<>',0);
});
}
if ($f_finance != '' && $f_finance == 0)
{
$index->whereColumn(DB::raw('COALESCE(count_po, 0)'), '>', DB::raw('COALESCE(count_check_finance, 0)'));
}
else if ($f_finance == 1)
{
$index->whereColumn(DB::raw('COALESCE(count_po, 0)'), '<=', DB::raw('COALESCE(count_check_finance, 0)'));
}
}
$index = $index->get();
$count = 0;
foreach ($index as $key => $value) {
$count++;
}
return compact('count');
}
public function revision(Request $request)
{
$index = PrDetail::find($request->id);
saveArchives($index, Auth::id(), 'revision pr detail');
$index->status = 'REVISION';
$index->datetime_confirm = null;
$index->save();
return redirect()->back()->with('success', 'Data Has Been Updated');
}
public function storePoProject(Request $request)
{
$prDetail = PrDetail::find($request->pr_detail_id);
if(!$this->usergrant($prDetail->purchasing_id, 'allPurchasing-pr') || !$this->levelgrant($prDetail->purchasing_id))
{
return redirect()->route('backend.pr.confirm')->with('failed', 'Access Denied');
}
$sumPoQuantity = Po::where('pr_detail_id', $request->pr_detail_id)->where('status_received', '<>', 'COMPLAIN')->sum('quantity');
$max = $prDetail->quantity - $sumPoQuantity;
$message = [
'pr_detail_id.required' => 'Error',
'pr_detail_id.integer' => 'Error',
'quantity.required' => 'This field required.',
'quantity.integer' => 'Number only.',
'quantity.max' => 'Maximum ' . $max,
'no_po.required' => 'This field required.',
'date_po.required' => 'This field required.',
'date_po.date' => 'Date format only.',
'type.required' => 'Select one.',
'supplier_id.required' => 'This field required.',
'name_supplier.required_if' => 'This field required.',
'value.required' => 'This field required.',
'value.numeric' => 'This field required.',
];
$validator = Validator::make($request->all(), [
'pr_detail_id' => 'required|integer',
'quantity' => 'required|integer|max:'.$max,
'no_po' => 'required',
'date_po' => 'required|date',
'type' => 'required',
'supplier_id' => 'required',
'name_supplier' => 'required_if:supplier_id,0',
'value' => 'required|numeric',
], $message);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput()->with('add-poProject-error', '');
}
$supplier = Supplier::find($request->supplier_id);
$index = new Po;
$index->pr_detail_id = $request->pr_detail_id;
$index->quantity = $request->quantity;
$index->no_po = $request->no_po;
$index->date_po = date('Y-m-d', strtotime($request->date_po));
$index->type = $request->type;
$index->bank = $supplier->bank ?? '';
$index->name_supplier = $supplier->name ?? $request->name_supplier;
$index->no_rekening = $supplier->no_rekening ?? '';
$index->name_rekening = $supplier->name_rekening ?? '';
$index->value = $request->value;
$index->status_received = 'WAITING';
$index->save();
$pr = Pr::find($prDetail->pr_id);
$html = '
Your item requested is on the way, Item : '.$prDetail->item.', Quantity : '.$request->quantity.'
';
User::find($pr->user_id)->notify(new Notif(Auth::user()->nickname, $html, route('backend.pr.item', ['f_id' => $index->id]) ) );
return redirect()->back()->with('success', 'Data Has Been Added');
}
public function updatePoProject(Request $request)
{
$index = Po::find($request->id);
$prDetail = PrDetail::find($index->pr_detail_id);
if((!$this->usergrant($prDetail->purchasing_id, 'allPurchasing-pr') || !$this->levelgrant($prDetail->purchasing_id)) || $index->check_audit == 1 || $index->check_finance == 1)
{
return redirect()->route('backend.pr.confirm')->with('failed', 'Access Denied');
}
$sumPoQuantity = Po::where('pr_detail_id', $index->pr_detail_id)->where('id', '<>', $request->id)->where('status_received', '<>', 'COMPLAIN')->sum('quantity');
$max = $prDetail->quantity - $sumPoQuantity;
$message = [
'quantity.required' => 'This field required.',
'quantity.integer' => 'Number only.',
'quantity.max' => 'Maximum ' . $max,
'no_po.required' => 'This field required.',
'date_po.required' => 'This field required.',
'date_po.date' => 'Date format only.',
'type.required' => 'Select one.',
'supplier_id.required' => 'This field required.',
'name_supplier.required' => 'This field required.',
'value.required' => 'This field required.',
'value.numeric' => 'This field required.',
];
$validator = Validator::make($request->all(), [
'quantity' => 'required|integer|max:'.$max,
'no_po' => 'required',
'date_po' => 'required|date',
'type' => 'required',
'supplier_id' => 'required',
'name_supplier' => 'required_if:supplier_id,0',
'value' => 'required|numeric',
], $message);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput()->with('edit-poProject-error', '');
}
$this->saveArchive('App\Models\Po', 'UPDATED', $index);
$supplier = Supplier::find($request->supplier_id);
$index->quantity = $request->quantity;
$index->no_po = $request->no_po;
$index->date_po = date('Y-m-d', strtotime($request->date_po));
$index->type = $request->type;
$index->bank = $supplier->bank ?? '';
$index->name_supplier = $supplier->name ?? $request->name_supplier;
$index->no_rekening = $supplier->no_rekening ?? '';
$index->name_rekening = $supplier->name_rekening ?? '';
$index->value = $request->value;
$index->save();
return redirect()->back()->with('success', 'Data Has Been Updated');
}
public function storePoPayment(Request $request)
{
$prDetail = PrDetail::find($request->pr_detail_id);
if(!$this->usergrant($prDetail->purchasing_id, 'allPurchasing-pr') || !$this->levelgrant($prDetail->purchasing_id))
{
return redirect()->route('backend.pr.confirm')->with('failed', 'Access Denied');
}
$sumPoQuantity = Po::where('pr_detail_id', $request->pr_detail_id)->where('status_received', '<>', 'COMPLAIN')->sum('quantity');
$max = $prDetail->quantity - $sumPoQuantity;
$message = [
'pr_detail_id.required' => 'Error',
'pr_detail_id.integer' => 'Error',
'date_po.required' => 'This field required.',
'date_po.date' => 'Date format only.',
];
$validator = Validator::make($request->all(), [
'pr_detail_id' => 'required|integer',
'date_po' => 'required|date',
], $message);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput()->with('add-poPayment-error', '');
}
$supplier = Supplier::find($request->supplier_id);
$index = new Po;
$index->pr_detail_id = $request->pr_detail_id;
$index->quantity = 1;
$index->no_po = 'Payment';
$index->date_po = date('Y-m-d', strtotime($request->date_po));
$index->type = '-';
$index->bank = '-';
$index->name_supplier = '-';
$index->no_rekening = $prDetail->no_rekening;
$index->name_rekening = '-';
$index->value = $request->value ?? $prDetail->value;
$index->status_received = 'CONFIRMED';
$index->save();
$pr = Pr::find($prDetail->pr_id);
$html = '
Your item requested is on the way, Item : '.$prDetail->item.', Quantity : '.$request->quantity.'
';
User::find($pr->user_id)->notify(new Notif(Auth::user()->nickname, $html, route('backend.pr.item', ['f_id' => $index->id]) ) );
return redirect()->back()->with('success', 'Data Has Been Added');
}
public function updatePoPayment(Request $request)
{
$index = Po::find($request->id);
$prDetail = PrDetail::find($index->pr_detail_id);
if((!$this->usergrant($prDetail->purchasing_id, 'allPurchasing-pr') || !$this->levelgrant($prDetail->purchasing_id)) || $index->check_audit == 1 || $index->check_finance == 1)
{
return redirect()->route('backend.pr.confirm')->with('failed', 'Access Denied');
}
$message = [
'date_po.required' => 'This field required.',
'date_po.date' => 'Date format only.',
];
$validator = Validator::make($request->all(), [
'date_po' => 'required|date',
], $message);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput()->with('edit-poPayment-error', '');
}
$this->saveArchive('App\Models\Po', 'UPDATED', $index);
$supplier = Supplier::find($request->supplier_id);
$index->value = $request->value;
$index->date_po = date('Y-m-d', strtotime($request->date_po));
$index->save();
return redirect()->back()->with('success', 'Data Has Been Updated');
}
public function deletePo(Request $request)
{
$index = Po::find($request->id);
if($index->status_received == 'CONFIRMED')
{
return redirect()->back()->with('failed', 'Data Can\'t update, if item already confirmed');
}
if((!$this->usergrant($index->prDetail->purchasing_id, 'allPurchasing-pr') || !$this->levelgrant($index->prDetail->purchasing_id)) || $index->check_audit == 1 || $index->check_finance == 1)
{
return redirect()->route('backend.pr.confirm')->with('failed', 'Access Denied');
}
$this->saveArchive('App\Models\Po', 'DELETED', $index);
Po::destroy($request->id);
return redirect()->back()->with('success', 'Data Has Been Deleted');
}
public function changePurchasing(Request $request)
{
$index = PrDetail::find($request->id);
$this->saveArchive('App\Models\Po', 'CHANGE_PURCHASING', $index);
$index->purchasing_id = $request->purchasing_id;
$index->save();
}
public function changeStatus(Request $request)
{
$index = PrDetail::find($request->id);
if($index->status != "CANCEL")
{
$this->saveArchive('App\Models\Po', 'CHANGE_STATUS', $index);
$index->status = $request->status;
$index->save();
}
}
public function checkAudit(Request $request)
{
$index = Po::find($request->id);
$this->saveArchive('App\Models\Po', 'CHECK_AUDIT', $index);
$index->check_audit = $request->check_audit;
$index->save();
}
public function checkFinance(Request $request)
{
$index = Po::find($request->id);
$this->saveArchive('App\Models\Po', 'CHECK_FINANCE', $index);
$index->check_finance = $request->check_finance;
$index->save();
}
public function noteAudit(Request $request)
{
$index = Po::find($request->id);
$this->saveArchive('App\Models\Po', 'NOTE_AUDIT', $index);
$index->note_audit = $request->note_audit;
$index->save();
}
public function pdf(Request $request)
{
$message = [
'size.required' => 'This field required.',
'orientation.required' => 'This field required.',
];
$validator = Validator::make($request->all(), [
'size' => 'required',
'orientation' => 'required',
], $message);
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator)
->withInput()
->with('pdf-pr-error', 'Something Errors');
}
$index = Pr::find($request->pr_id);
$pdf = PDF::loadView('backend.pr.pdf', compact('index', 'request'))->setPaper($request->size, $request->orientation);
return $pdf->stream($index->no_pr.'_'.date('Y-m-d').'.pdf');
}
public function dashboard(Request $request)
{
$year = Pr::select(DB::raw('YEAR(datetime_order) as year'))->orderBy('datetime_order', 'ASC')->distinct()->get();
$month = ['Januari', 'Febuari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];
$sales = Spk::join('users as sales', 'sales.id', '=', 'spk.sales_id')
->select('sales.fullname', 'sales.id')
->orderBy('sales.fullname', 'ASC')->distinct();
if (!Auth::user()->can('allSales-spk')) {
$sales->whereIn('sales_id', Auth::user()->staff());
}
$sales = $sales->get();
return view('backend.pr.dashboard')->with(compact('request', 'year', 'month', 'sales'));
}
public function ajaxDashboard(Request $request)
{
$f_month = $this->filter($request->f_month, date('n'));
$f_year = $this->filter($request->f_year, date('Y'));
$f_sales = $this->filter($request->f_sales, Auth::id());
$f_budget = $this->filter($request->f_budget);
$sql_production = '
(
/* sales -> spk */
SELECT production.spk_id, SUM(production.totalHM) AS totalHM, SUM(production.totalHE) AS totalHE, SUM(production.totalHJ) As totalHJ, SUM(production.totalRealOmset) AS totalRealOmset
FROM
(
/* spk -> production with realOmset */
SELECT
production.spk_id,
production.name,
production.sales_id,
(@totalHM := production.totalHM) as totalHM,
production.totalHE,
(@totalHJ := production.totalHJ) as totalHJ,
@profit := (CASE WHEN production.totalHE > 0 THEN @totalHJ - (@totalHE + ((@totalHE * 5) / 100)) ELSE @totalHJ - (@totalHM + ((@totalHM * 5) / 100)) END) AS profit,
@percent := (@profit / (CASE WHEN production.totalHE > 0 THEN production.totalHE ELSE IF(@totalHM<>0,@totalHM,1) END) ) * 100 AS percent,
(CASE WHEN @percent < 30 THEN (@profit / 0.3) + @profit ELSE @totalHJ END) AS totalRealOmset
FROM
(
/* spk -> production */
SELECT
spk.id AS spk_id,
spk.sales_id, spk.name,
SUM(production.hm * production.quantity) AS totalHM,
SUM(production.he * production.quantity) AS totalHE,
SUM(production.hj * production.quantity) AS totalHJ
FROM spk join production ON spk.id = production.spk_id
GROUP BY spk.id
) production
) production
GROUP BY production.spk_id
) production
';
$sql_pr = '
(
/* spk -> pr */
SELECT pr.spk_id, SUM(pr.totalPR) as totalPR
FROM
(
/* spk -> pr */
SELECT pr.id AS pr_id, pr.spk_id, COALESCE(SUM(pr_detail.totalValue),0) AS totalPR
FROM `pr`
LEFT JOIN
(
/* pr_detail -> po */
SELECT
`pr_detail`.`id` as pr_detail_id,
`pr_id`, SUM(`po`.`quantity`) as totalQuantity,
SUM(`po`.`value`) as totalValue
FROM `pr_detail`
JOIN `po` ON `po`.`pr_detail_id` = `pr_detail`.`id`
GROUP BY `pr_detail`.`id`
) pr_detail ON pr.id = pr_detail.pr_id
WHERE pr.type = "PROJECT"
GROUP BY pr.id
) pr
GROUP BY pr.spk_id
) pr
';
$index = Spk::select(
'spk.id',
'spk.name',
'spk.no_spk',
'production.totalHM',
'production.totalHE',
'production.totalHJ',
DB::raw('COALESCE(pr.totalPR, 0) AS totalPR'),
DB::raw('(@profit := production.totalHJ - COALESCE(pr.totalPR, 0)) AS profit'),
DB::raw('(
CASE WHEN COALESCE(pr.totalPR, 0) = 0
THEN 100
ELSE ( @profit / COALESCE(pr.totalPR, 0 ) ) * 100
END
) AS margin
'),
DB::raw('production.totalHM - COALESCE(pr.totalPR, 0) AS budget'),
DB::raw('production.totalHE - COALESCE(pr.totalPR, 0) AS budgetE')
)
->leftJoin(DB::raw($sql_production), 'spk.id', 'production.spk_id')
->leftJoin(DB::raw($sql_pr), 'spk.id', 'pr.spk_id');
if($f_month != '')
{
$index->whereMonth('spk.date', $f_month);
}
if($f_year != '')
{
$index->whereYear('spk.date', $f_year);
}
if($f_sales == 'staff')
{
$index->whereIn('spk.sales_id', Auth::user()->staff());
}
else if($f_sales != '')
{
$index->where('spk.sales_id', $f_sales);
}
if ($f_budget != '') {
if ($f_budget == 1) {
$index->where(DB::raw('( production.totalHM - COALESCE(pr.totalPR, 0) )'), '>=', 0);
} else {
$index->where(DB::raw('( production.totalHM - COALESCE(pr.totalPR, 0) )'), '<', 0);
}
}
$index = $index->get();
$data = '';
$allTotalHM = $allTotalHE = $allTotalHJ = $allTotalPR = $allTotalProfit = $allTotalBudget = $allTotalBudgetE = 0;
foreach ($index as $list) {
$data[] = [
'id' => $list->id,
'spk' => $list->spk,
'name' => $list->name,
'totalHM' => number_format($list->totalHM),
'totalHE' => number_format($list->totalHE),
'totalHJ' => number_format($list->totalHJ),
'totalPR' => number_format($list->totalPR),
'profit' => number_format($list->profit),
'margin' => number_format($list->margin, 2).' %',
'budget' => number_format($list->budget),
'budgetE' => number_format($list->budgetE),
];
$allTotalHM += $list->totalHM;
$allTotalHE += $list->totalHE;
$allTotalHJ += $list->totalHJ;
$allTotalPR += $list->totalPR;
$allTotalProfit += $list->profit;
$allTotalBudget += $list->budget;
$allTotalBudgetE += $list->budgetE;
}
return compact('data', 'allTotalHM', 'allTotalHE', 'allTotalHJ', 'allTotalPR', 'allTotalProfit', 'allTotalBudget', 'allTotalBudgetE');;
}
public function datatablesDetailDashboard(Request $request)
{
$sql = '
(
/* pr_detail -> po */
SELECT
`pr_detail`.`id` as pr_detail_id,
`pr_id`, SUM(`po`.`quantity`) as totalQuantity,
SUM(`po`.`value`) as totalValue,
COUNT(`po`.`id`) as countPO,
countCheckAudit,
countCheckFinance
FROM `pr_detail`
JOIN `po` ON `po`.`pr_detail_id` = `pr_detail`.`id`
LEFT JOIN (
SELECT `pr_detail`.`id` as pr_detail_id, COUNT(`po`.`id`) as countCheckAudit FROM `pr_detail` JOIN `po` ON `po`.`pr_detail_id` = `pr_detail`.`id` WHERE `po`.`check_audit` = 1 GROUP BY `pr_detail`.`id`
) `audit` on `audit`.`pr_detail_id` = `pr_detail`.`id`
LEFT JOIN (
SELECT `pr_detail`.`id` as pr_detail_id, COUNT(`po`.`id`) as countCheckFinance FROM `pr_detail` JOIN `po` ON `po`.`pr_detail_id` = `pr_detail`.`id` WHERE `po`.`check_finance` = 1 GROUP BY `pr_detail`.`id`
) `finance` on `finance`.`pr_detail_id` = `pr_detail`.`id`
GROUP BY `pr_detail`.`id`
) po
';
$index = PrDetail::where('pr_detail.confirm', 1)
->leftJoin('pr', 'pr.id', 'pr_detail.pr_id')
->leftJoin(DB::raw($sql), 'pr_detail.id', 'po.pr_detail_id')
->leftJoin('spk', 'spk.id', 'pr.spk_id')
->leftJoin('users', 'users.id', 'pr_detail.purchasing_id')
->select(
'pr_detail.*',
'spk.no_spk',
'spk.name as spk_name',
'pr.id as pr_id',
'pr.name',
'pr.deadline',
'pr.no_pr',
'users.fullname as purchasing',
'pr_detail.purchasing_id',
'po.countPO',
DB::raw('COALESCE(po.totalQuantity, 0) as totalPoQty'),
DB::raw('COALESCE(countCheckAudit, 0) as countCheckAudit'),
DB::raw('COALESCE(countCheckFinance, 0) as countCheckFinance')
)
->where('spk.id', $request->id)
->orderBy('pr_detail.id', 'DESC')
->distinct();
$index = $index->get();
$datatables = Datatables::of($index);
$datatables->addColumn('po', function ($index){
$html = '';
$html .= '<table class="table table-striped">';
$html .= '
<tr>
<th>No App\Models\Po</th>
<th>Date</th>
<th>Quantity</th>
<th>Value</th>
</tr>
';
foreach ($index->po as $list) {
$html .= '
<tr>
<td>'.$list->no_po.'</td>
<td>'.date('d/m/Y', strtotime($list->date_po)).'</td>
<td>'.number_format($list->quantity).'</td>
<td>'.number_format($list->value).'</td>
</tr>
';
}
$html .= '</table>';
return $html;
});
$datatables->editColumn('purchasing', function ($index){
return $index->purchasing ?? 'not set';
});
$datatables->editColumn('date_po', function ($index){
return date('d/m/Y', strtotime($index->date_po));
});
$datatables->editColumn('value', function ($index){
return number_format($index->value);
});
$datatables->editColumn('quantity', function ($index){
return $index->quantity . ' ' . $index->unit;
});
$datatables->addColumn('action', function ($index) {
$html = '';
if( Auth::user()->can('view-pr') )
{
$html .= '
<a href="'.route('backend.pr.edit', ['id' => $index->pr_id]).'" class="btn btn-xs btn-warning"><i class="fa fa-eye"></i></a>
';
}
// if( Auth::user()->can('delete-pr') && ($this->usergrant($index->user_id, 'allUser-pr') || $this->levelgrant($index->user_id)) )
// {
// $html .= '
// <button type="button" class="btn btn-xs btn-danger delete-pr" data-toggle="modal" data-target="#delete-pr" data-id="'.$index->id.'"><i class="fa fa-trash" aria-hidden="true"></i></button>
// ';
// }
// if( Auth::user()->can('pdf-pr') )
// {
// $html .= '
// <button type="button" class="btn btn-xs btn-primary pdf-pr" data-toggle="modal" data-target="#pdf-pr" data-id="'.$index->pr_id.'"><i class="fa fa-file-pdf-o" aria-hidden="true"></i></button>
// ';
// }
return $html;
});
$datatables = $datatables->make(true);
return $datatables;
}
public function excel(Request $request)
{
$f_month = $this->filter($request->xls_month, date('n'));
$f_year = $this->filter($request->xls_year, date('Y'));
$config = Config::all();
foreach ($config as $list) {
eval("\$".$list->for." = App\Config::find(".$list->id.");");
}
Excel::create('pr-'.$f_year.$f_month.'-'.date('dmYHis'), function ($excel) use ($f_year, $f_month, $purchasing_position, $purchasing_user) {
$excel->sheet('Dashboard', function ($sheet) use ($f_year, $f_month) {
$sql_production = '
(
/* sales -> spk */
SELECT production.spk_id, SUM(production.totalHM) AS totalHM, SUM(production.totalHE) AS totalHE, SUM(production.totalHJ) As totalHJ, SUM(production.totalRealOmset) AS totalRealOmset
FROM
(
/* spk -> production with realOmset */
SELECT
production.spk_id,
production.name,
production.sales_id,
(@totalHM := production.totalHM) as totalHM,
production.totalHE,
(@totalHJ := production.totalHJ) as totalHJ,
@profit := (CASE WHEN production.totalHE > 0 THEN @totalHJ - (@totalHE + ((@totalHE * 5) / 100)) ELSE @totalHJ - (@totalHM + ((@totalHM * 5) / 100)) END) AS profit,
@percent := (@profit / (CASE WHEN production.totalHE > 0 THEN production.totalHE ELSE IF(@totalHM<>0,@totalHM,1) END) ) * 100 AS percent,
(CASE WHEN @percent < 30 THEN (@profit / 0.3) + @profit ELSE @totalHJ END) AS totalRealOmset
FROM
(
/* spk -> production */
SELECT
spk.id AS spk_id,
spk.sales_id, spk.name,
SUM(production.hm * production.quantity) AS totalHM,
SUM(production.he * production.quantity) AS totalHE,
SUM(production.hj * production.quantity) AS totalHJ
FROM spk join production ON spk.id = production.spk_id
GROUP BY spk.id
) production
) production
GROUP BY production.spk_id
) production
';
$sql_pr = '
(
/* spk -> pr */
SELECT pr.spk_id, SUM(pr.totalPR) as totalPR
FROM
(
/* spk -> pr */
SELECT pr.id AS pr_id, pr.spk_id, COALESCE(SUM(pr_detail.totalValue),0) AS totalPR
FROM `pr`
LEFT JOIN
(
/* pr_detail -> po */
SELECT
`pr_detail`.`id` as pr_detail_id,
`pr_id`, SUM(`po`.`quantity`) as totalQuantity,
SUM(`po`.`value`) as totalValue,
COUNT(`po`.`id`) as countPO,
countCheckAudit,
countCheckFinance
FROM `pr_detail`
JOIN `po` ON `po`.`pr_detail_id` = `pr_detail`.`id`
LEFT JOIN (
SELECT `pr_detail`.`id` as pr_detail_id, COUNT(`po`.`id`) as countCheckAudit FROM `pr_detail` JOIN `po` ON `po`.`pr_detail_id` = `pr_detail`.`id` WHERE `po`.`check_audit` = 1 GROUP BY `pr_detail`.`id`
) `audit` on `audit`.`pr_detail_id` = `pr_detail`.`id`
LEFT JOIN (
SELECT `pr_detail`.`id` as pr_detail_id, COUNT(`po`.`id`) as countCheckFinance FROM `pr_detail` JOIN `po` ON `po`.`pr_detail_id` = `pr_detail`.`id` WHERE `po`.`check_finance` = 1 GROUP BY `pr_detail`.`id`
) `finance` on `finance`.`pr_detail_id` = `pr_detail`.`id`
GROUP BY `pr_detail`.`id`
) pr_detail ON pr.id = pr_detail.pr_id
GROUP BY pr.id
) pr
GROUP BY pr.spk_id
) pr
';
$index = Spk::select(
'spk.id',
'spk.name',
'spk.no_spk',
'production.totalHM',
'production.totalHE',
'production.totalHJ',
DB::raw('COALESCE(pr.totalPR, 0) AS totalPR'),
DB::raw('(@profit := production.totalHJ - COALESCE(pr.totalPR, 0)) AS profit'),
DB::raw('(
CASE WHEN COALESCE(pr.totalPR, 0) = 0
THEN 100
ELSE ( @profit / COALESCE(pr.totalPR, 0 ) ) * 100
END
) AS margin
'),
DB::raw('production.totalHM - COALESCE(pr.totalPR, 0) AS budget'),
DB::raw('production.totalHE - COALESCE(pr.totalPR, 0) AS budgetE')
)
->leftJoin(DB::raw($sql_production), 'spk.id', 'production.spk_id')
->leftJoin(DB::raw($sql_pr), 'spk.id', 'pr.spk_id');
if($f_month != '')
{
$index->whereMonth('spk.date', $f_month);
}
if($f_year != '')
{
$index->whereYear('spk.date', $f_year);
}
$index = $index->get();
$data = '';
$allTotalHM = $allTotalHE = $allTotalHJ = $allTotalPR = $allTotalProfit = $allTotalBudget = $allTotalBudgetE = 0;
foreach ($index as $list) {
$data[] = [
'id' => $list->id,
'spk' => $list->spk,
'name' => $list->name,
'totalHM' => number_format($list->totalHM),
'totalHE' => number_format($list->totalHE),
'totalHJ' => number_format($list->totalHJ),
'totalPR' => number_format($list->totalPR),
'profit' => number_format($list->profit),
'margin' => number_format($list->margin, 2).' %',
'budget' => number_format($list->budget),
'budgetE' => number_format($list->budgetE),
];
$allTotalHM += $list->totalHM;
$allTotalHE += $list->totalHE;
$allTotalHJ += $list->totalHJ;
$allTotalPR += $list->totalPR;
$allTotalProfit += $list->profit;
$allTotalBudget += $list->budget;
$allTotalBudgetE += $list->budgetE;
}
$index = compact('data', 'allTotalHM', 'allTotalHE', 'allTotalHJ', 'allTotalPR', 'allTotalProfit', 'allTotalBudget', 'allTotalBudgetE');
$sheet->fromArray($index['data']);
$sheet->row(1, [
'SPK',
'Project Name',
'Total Modal Price',
'Total Estimator Price',
'Total Sell Price',
'Total App\Pr',
'Profit',
'Margin',
'Budget',
'Budget Estimator'
]);
$sheet->setFreeze('A1');
});
$excel->sheet('Overbudget', function ($sheet) use ($f_year, $f_month, $purchasing_position, $purchasing_user) {
$sql_production = '
(
/* sales -> spk */
SELECT production.spk_id, SUM(production.totalHM) AS totalHM, SUM(production.totalHE) AS totalHE, SUM(production.totalHJ) As totalHJ, SUM(production.totalRealOmset) AS totalRealOmset
FROM
(
/* spk -> production with realOmset */
SELECT
production.spk_id,
production.name,
production.sales_id,
(@totalHM := production.totalHM) as totalHM,
production.totalHE,
(@totalHJ := production.totalHJ) as totalHJ,
@profit := (CASE WHEN production.totalHE > 0 THEN @totalHJ - (@totalHE + ((@totalHE * 5) / 100)) ELSE @totalHJ - (@totalHM + ((@totalHM * 5) / 100)) END) AS profit,
@percent := (@profit / (CASE WHEN production.totalHE > 0 THEN production.totalHE ELSE IF(@totalHM<>0,@totalHM,1) END) ) * 100 AS percent,
(CASE WHEN @percent < 30 THEN (@profit / 0.3) + @profit ELSE @totalHJ END) AS totalRealOmset
FROM
(
/* spk -> production */
SELECT
spk.id AS spk_id,
spk.sales_id, spk.name,
SUM(production.hm * production.quantity) AS totalHM,
SUM(production.he * production.quantity) AS totalHE,
SUM(production.hj * production.quantity) AS totalHJ
FROM spk join production ON spk.id = production.spk_id
GROUP BY spk.id
) production
) production
GROUP BY production.spk_id
) production
';
$sql_pr = '
(
/* spk -> pr */
SELECT pr.spk_id, SUM(pr.totalPR) as totalPR
FROM
(
/* spk -> pr */
SELECT pr.id AS pr_id, pr.spk_id, COALESCE(SUM(pr_detail.totalValue),0) AS totalPR
FROM `pr`
LEFT JOIN
(
/* pr_detail -> po */
SELECT
`pr_detail`.`id` as pr_detail_id,
`pr_id`, SUM(`po`.`quantity`) as totalQuantity,
SUM(`po`.`value`) as totalValue,
COUNT(`po`.`id`) as countPO,
countCheckAudit,
countCheckFinance
FROM `pr_detail`
JOIN `po` ON `po`.`pr_detail_id` = `pr_detail`.`id`
LEFT JOIN (
SELECT `pr_detail`.`id` as pr_detail_id, COUNT(`po`.`id`) as countCheckAudit FROM `pr_detail` JOIN `po` ON `po`.`pr_detail_id` = `pr_detail`.`id` WHERE `po`.`check_audit` = 1 GROUP BY `pr_detail`.`id`
) `audit` on `audit`.`pr_detail_id` = `pr_detail`.`id`
LEFT JOIN (
SELECT `pr_detail`.`id` as pr_detail_id, COUNT(`po`.`id`) as countCheckFinance FROM `pr_detail` JOIN `po` ON `po`.`pr_detail_id` = `pr_detail`.`id` WHERE `po`.`check_finance` = 1 GROUP BY `pr_detail`.`id`
) `finance` on `finance`.`pr_detail_id` = `pr_detail`.`id`
GROUP BY `pr_detail`.`id`
) pr_detail ON pr.id = pr_detail.pr_id
GROUP BY pr.id
) pr
GROUP BY pr.spk_id
) pr
';
$index = Spk::select(
'spk.id',
'spk.name',
'spk.no_spk',
'production.totalHM',
'production.totalHE',
'production.totalHJ',
DB::raw('COALESCE(pr.totalPR, 0) AS totalPR'),
DB::raw('(@profit := production.totalHJ - COALESCE(pr.totalPR, 0)) AS profit'),
DB::raw('(
CASE WHEN COALESCE(pr.totalPR, 0) = 0
THEN 100
ELSE ( @profit / COALESCE(pr.totalPR, 0 ) ) * 100
END
) AS margin
'),
DB::raw('production.totalHM - COALESCE(pr.totalPR, 0) AS budget'),
DB::raw('production.totalHE - COALESCE(pr.totalPR, 0) AS budgetE')
)
->leftJoin(DB::raw($sql_production), 'spk.id', 'production.spk_id')
->leftJoin(DB::raw($sql_pr), 'spk.id', 'pr.spk_id');
if($f_month != '')
{
$index->whereMonth('spk.date', $f_month);
}
if($f_year != '')
{
$index->whereYear('spk.date', $f_year);
}
$index->where(DB::raw('( production.totalHM - COALESCE(pr.totalPR, 0) )'), '<', 0);
$index = $index->get();
$data = '';
$allTotalHM = $allTotalHE = $allTotalHJ = $allTotalPR = $allTotalProfit = $allTotalBudget = $allTotalBudgetE = 0;
foreach ($index as $list) {
$data[] = [
'id' => $list->id,
'spk' => $list->spk,
'name' => $list->name,
'totalHM' => number_format($list->totalHM),
'totalHE' => number_format($list->totalHE),
'totalHJ' => number_format($list->totalHJ),
'totalPR' => number_format($list->totalPR),
'profit' => number_format($list->profit),
'margin' => number_format($list->margin, 2).' %',
'budget' => number_format($list->budget),
'budgetE' => number_format($list->budgetE),
];
$allTotalHM += $list->totalHM;
$allTotalHE += $list->totalHE;
$allTotalHJ += $list->totalHJ;
$allTotalPR += $list->totalPR;
$allTotalProfit += $list->profit;
$allTotalBudget += $list->budget;
$allTotalBudgetE += $list->budgetE;
}
$index = compact('data', 'allTotalHM', 'allTotalHE', 'allTotalHJ', 'allTotalPR', 'allTotalProfit', 'allTotalBudget', 'allTotalBudgetE');
$sheet->fromArray($index['data']);
$sheet->row(1, [
'SPK',
'Project Name',
'Total Modal Price',
'Total Estimator Price',
'Total Sell Price',
'Total App\Pr',
'Profit',
'Margin',
'Budget',
'Budget Estimator'
]);
$sheet->setFreeze('A1');
});
$purchasing = User::where(function ($query) use ($purchasing_position, $purchasing_user) {
$query->whereIn('position', explode(', ' , $purchasing_position->value))
->orWhereIn('id', explode(', ' , $purchasing_user->value));
})->get();
foreach ($purchasing as $list) {
$excel->sheet($list->fullname, function ($sheet) use ($f_year, $f_month, $list) {
$index = PrDetail::select(DB::raw('
pr_detail.*,
spk.no_spk,
users.fullname as purchasing,
pr.created_at as date_submit
'))
->leftJoin('spk', 'pr_detail.spk_id', '=', 'spk.id')
->leftJoin('users', 'pr_detail.purchasing_id', '=', 'users.id')
->join('pr', 'pr_detail.pr_id', '=', 'pr.id')
->where('pr_detail.confirm', 1)
->where('purchasing_id', $list->id);
if($f_month != '')
{
$index->whereMonth('spk.date', $f_month);
}
if($f_year != '')
{
$index->whereYear('spk.date', $f_year);
}
$index = $index->get();
$data = '';
foreach ($index as $list) {
$data[] = [
'SPK' => $list->spk,
'No App\Pr' => $list->no_pr,
'Item' => $list->item,
'Purchasing' => $list->purchasing,
'No App\Models\Po' => $list->no_po,
'Date App\Models\Po' => $list->date_po,
'Type' => $list->type,
'Supplier' => $list->name_supplier,
'Name Rekening' => $list->name_rekening,
'No Rekening' => $list->no_rekening,
'Value' => number_format($list->value),
'Date Confirm' => $list->datetime_confirm,
'Check Audit' => $list->check_audit ? 'Yes' : 'No',
];
}
$sheet->fromArray($data);
$sheet->setFreeze('A1');
});
}
})->download('xls');
}
public function item(Request $request)
{
$year = Pr::select(DB::raw('YEAR(datetime_order) as year'))->orderBy('datetime_order', 'ASC')->distinct()->get();
$month = ['Januari', 'Febuari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];
$user = Pr::join('users', 'users.id', '=', 'pr.user_id')
->select('users.first_name', 'users.last_name', 'users.id')
->orderBy('users.first_name', 'ASC')->distinct();
if(!Auth::user()->can('allUser-pr'))
{
$user->whereIn('pr.user_id', Auth::user()->staff());
}
$user = $user->get();
return view('backend.pr.item')->with(compact('request', 'year', 'month', 'user'));
}
public function datatablesItem(Request $request)
{
$f_user = $this->filter($request->f_user, Auth::id());
$f_month = $this->filter($request->f_month, date('n'));
$f_year = $this->filter($request->f_year, date('Y'));
$f_status = $this->filter($request->f_status, 'WAITING');
$f_id = $this->filter($request->f_id);
$index = Po::leftJoin('pr_detail', 'pr_detail.id', 'po.pr_detail_id')
->leftJoin('pr', 'pr.id', 'pr_detail.pr_id')
->leftJoin('spk', 'spk.id', 'pr.spk_id')
->leftJoin('users', 'users.id', 'pr.user_id')
->select('po.id', 'po.quantity', 'po.status_received', 'pr_detail.item', 'pr.no_pr', 'pr.datetime_order', 'pr_detail.deadline', 'spk.no_spk', 'spk.name', 'users.first_name', 'users.last_name', 'pr.user_id');
if($f_id != '')
{
$index->where('po.id', $f_id);
}
else
{
if($f_month != '')
{
$index->whereMonth('pr.datetime_order', $f_month);
}
if($f_year != '')
{
$index->whereYear('pr.datetime_order', $f_year);
}
if($f_user == 'staff')
{
$index->whereIn('pr.user_id', Auth::user()->staff());
}
else if($f_user != '')
{
$index->where('pr.user_id', $f_user);
}
if($f_status != '')
{
$index->where('po.status_received', $f_status);
}
}
$index = $index->get();
$datatables = Datatables::of($index);
$datatables->editColumn('fullname', function ($index){
return $index->fullname ?? 'not set';
});
$datatables->editColumn('datetime_order', function ($index){
return date('d/m/Y', strtotime($index->datetime_order));
});
$datatables->editColumn('deadline', function ($index){
return date('d/m/Y', strtotime($index->deadline));
});
$datatables->editColumn('status_received', function ($index){
if($index->status_received == "CONFIRMED")
{
return "Confirmed, Date Received : " . date('d/m/Y', strtotime($index->date_received));
}
else if($index->status_received == "COMPLAIN")
{
return "Complain, Reason : " . $index->note_received;
}
else
{
return "Item on process";
}
});
$datatables->addColumn('check', function ($index) {
$html = '';
if( $this->usergrant($index->user_id, 'allUser-pr') || $this->levelgrant($index->user_id) )
{
$html .= '
<input type="checkbox" class="check" value="'.$index->id.'" name="id[]" form="action">
';
}
return $html;
});
$datatables->addColumn('action', function ($index) {
$html = '';
if( Auth::user()->can('receivedItem-pr') && $index->status_received == 'WAITING')
{
$html .= '
<button type="button" class="btn btn-xs btn-success pr-confirmItem" data-toggle="modal" data-target="#pr-confirmItem" data-id="'.$index->id.'">Confirm</button>
';
$html .= '
<button type="button" class="btn btn-xs btn-danger pr-complainItem" data-toggle="modal" data-target="#pr-complainItem" data-id="'.$index->id.'">Complain</button>
';
}
return $html;
});
$datatables = $datatables->make(true);
return $datatables;
}
public function receivedItem(Request $request)
{
$index = Po::find($request->id);
if($index->status_received == 'CONFIRMED')
{
return redirect()->back()->with('failed', 'Data Can\'t update, if item already confirmed');
}
$this->saveArchive('App\Models\Po', 'RECEIVED_ITEM', $index);
$index->status_received = "CONFIRMED";
$index->rating = $request->rating;
$index->date_received = date('Y-m-d');
$index->save();
$prDetail = PrDetail::find($index->pr_detail_id);
$html = '
Item Has Been recieved, Item : '.$prDetail->item.'
';
User::find($prDetail->purchasing_id)->notify(new Notif(Auth::user()->nickname, $html, route('backend.pr.confirm', ['f_id' => $prDetail->id]) ) );
return redirect()->back()->with('success', 'Data Has Been Updated');
}
public function complainItem(Request $request)
{
$index = Po::find($request->id);
if($index->status_received == 'CONFIRMED')
{
return redirect()->back()->with('failed', 'Data Can\'t update, if item already confirmed');
}
$message = [
'date_received.date' => 'Date format only.',
];
$validator = Validator::make($request->all(), [
'note_received' => 'required',
], $message);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput()->with('pr-complainItem-error', '');
}
$this->saveArchive('App\Models\Po', 'COMPLAIN', $index);
$index->status_received = "COMPLAIN";
$index->date_received = date('Y-m-d');
$index->rating = 0;
$index->note_received = $request->note_received;
$index->save();
$prDetail = PrDetail::find($index->pr_detail_id);
$html = '
There is a complain item, Item : '.$prDetail->item.'
';
User::find($prDetail->purchasing_id)->notify(new Notif(Auth::user()->nickname, $html, route('backend.pr.confirm', ['f_id' => $prDetail->id]) ) );
return redirect()->back()->with('success', 'Data Has Been Updated');
}
public function getPr(Request $request)
{
$date = date('Y-m-d');
if (isset($request->date) && $request->date != '') {
$date = $request->date;
}
$user = Auth::user();
if (isset($request->user_id) && $request->user_id != '') {
$user = User::find($request->user_id);
}
$pr = Pr::select('no_pr')
->where('no_pr', 'like', date('y', strtotime($date)) . substr(strtolower($user->nickname), 0, 3) . "%")
->orderBy('no_pr', 'desc');
$count = $pr->count();
$current = $pr->first();
if ($count == 0) {
$numberPr = 0;
} else {
$numberPr = intval(substr($current->no_pr, -4, 4));
}
return date('y', strtotime($date)) . substr(strtolower($user->nickname), 0, 3) . str_pad($numberPr + 1, 4, '0', STR_PAD_LEFT);
}
}
|
df5f67b69ce8f2794c325749394d783d0dd1afd1
|
{
"blob_id": "df5f67b69ce8f2794c325749394d783d0dd1afd1",
"branch_name": "refs/heads/master",
"committer_date": "2019-04-18T08:28:19",
"content_id": "16e588fb0630a3b61dc36cf08313e1cdc436a2ba",
"detected_licenses": [
"MIT"
],
"directory_id": "370545a5f64a810aa5c66645f6e9c9fd73bcb6c8",
"extension": "php",
"filename": "PrController.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 175773629,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 99270,
"license": "MIT",
"license_type": "permissive",
"path": "/application/app/Http/Controllers/Backend/PrController.php",
"provenance": "stack-edu-0048.json.gz:593972",
"repo_name": "darthan914/edigindo-v3",
"revision_date": "2019-04-18T08:28:19",
"revision_id": "2ce9bc76affb3f916bcbc4da36e8bbc868ad1470",
"snapshot_id": "8987b34c279ed9be5785f18f80530560e3d62d81",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/darthan914/edigindo-v3/2ce9bc76affb3f916bcbc4da36e8bbc868ad1470/application/app/Http/Controllers/Backend/PrController.php",
"visit_date": "2020-04-29T02:33:23.942769",
"added": "2024-11-18T22:47:09.688460+00:00",
"created": "2019-04-18T08:28:19",
"int_score": 2,
"score": 2,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0066.json.gz"
}
|
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\PlataformaBanco;
use Carbon\Carbon;
class ActualizarSaldos extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'saldos:update';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Actualizacion de Saldos Mensual de Colegiados';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$mesActual = Now()->format('m');
$anioActual = Now()->format('Y');
$mesAnterior=Carbon::Now()->startOfMonth()->subMonth();
$mes=$mesAnterior->format('m');
$anio=$mesAnterior->format('Y');
$ageFrom=Carbon::Now()->startOfMonth()->subMonth();
$ageTo=Carbon::Now()->startOfMonth()->subSecond();
$cuenta = \App\EstadoDeCuentaMaestro::orderBy("colegiado_id", "asc")->get();
foreach ($cuenta as $key => $value) {
$saldoActual =\App\SigecigSaldoColegiados::where('no_colegiado',$value->colegiado_id)->where('mes_id',$mes)->where('año',$anio)->get()->last();
$abono=\App\EstadoDeCuentaDetalle::where('estado_cuenta_maestro_id',$value->id)->whereBetween('updated_at', [$ageFrom, $ageTo])->sum('abono');
if(empty($abono)){
$abono=0;
}
$cargo=\App\EstadoDeCuentaDetalle::where('estado_cuenta_maestro_id',$value->id)->whereBetween('updated_at', [$ageFrom, $ageTo])->sum('cargo');
if(empty($cargo)){
$cargo=0;
}
if(empty($saldoActual)){
$total = $cargo-$abono;
}else{
$total = $saldoActual->saldo+$cargo-$abono;
}
$saldos = \App\SigecigSaldoColegiados::create([
'no_colegiado' => $value->colegiado_id,
'mes_id' => $mesActual,
'año' => $anioActual,
'saldo' => $total,
'fecha' => Now(),
]);
}
}
}
|
0b69cbb85e071ca3c2b7acafa7d6d72b5cd5e3e7
|
{
"blob_id": "0b69cbb85e071ca3c2b7acafa7d6d72b5cd5e3e7",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-01T14:48:18",
"content_id": "095cb62984dc9299e316e0552ba53206216d3188",
"detected_licenses": [
"MIT"
],
"directory_id": "f98c7244b3fd56a2ca6b2c8d495cf7fd74b0b173",
"extension": "php",
"filename": "ActualizarSaldos.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 251730706,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 2356,
"license": "MIT",
"license_type": "permissive",
"path": "/app/Console/Commands/ActualizarSaldos.php",
"provenance": "stack-edu-0053.json.gz:400525",
"repo_name": "ingivargas84/sigecig",
"revision_date": "2020-10-01T14:48:18",
"revision_id": "a9e44766b24a9fc9645a890164d6ebda53816083",
"snapshot_id": "b166fda7ad2c008048db7b5008368e25aaa5e3c6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ingivargas84/sigecig/a9e44766b24a9fc9645a890164d6ebda53816083/app/Console/Commands/ActualizarSaldos.php",
"visit_date": "2022-12-31T16:11:42.975691",
"added": "2024-11-18T23:09:47.518871+00:00",
"created": "2020-10-01T14:48:18",
"int_score": 2,
"score": 2.390625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0071.json.gz"
}
|
//
// Data+Extensions.swift
// TermiNetwork
//
// Created by Vasilis Panagiotopoulos on 22/02/2018.
//
import Foundation
extension Data {
public func deserializeJSONData<T>() throws -> T where T:Decodable {
let jsonDecoder = JSONDecoder()
return try jsonDecoder.decode(T.self, from: self)
}
internal func toJSONString() -> String? {
if let dictionary = try? JSONSerialization.jsonObject(with: self, options: []) {
if let jsonData = try? JSONSerialization.data(withJSONObject: dictionary, options: .prettyPrinted), let jsonString = String(data: jsonData, encoding: .utf8) {
return jsonString
}
}
return nil
}
internal func toString() -> String? {
return String(data: self, encoding: .utf8)
}
}
|
5c6eeea164a30221f9275b5ab03a1b68b69b2bf7
|
{
"blob_id": "5c6eeea164a30221f9275b5ab03a1b68b69b2bf7",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-04T12:10:19",
"content_id": "e876be3071275c86f4e2caef1e4f9c32d24d6b1e",
"detected_licenses": [
"MIT"
],
"directory_id": "62c7ef712c47b62b0c5bc897029e1f2c1bca3f7a",
"extension": "swift",
"filename": "Data+Extensions.swift",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 291112570,
"is_generated": false,
"is_vendor": false,
"language": "Swift",
"length_bytes": 821,
"license": "MIT",
"license_type": "permissive",
"path": "/Pods/TermiNetwork/TermiNetwork/Classes/Extensions/Data+Extensions.swift",
"provenance": "stack-edu-0071.json.gz:777635",
"repo_name": "alexanderathan/demo",
"revision_date": "2020-09-04T12:10:19",
"revision_id": "385524bf1e35786f4285219c9cd1d5da8e057e82",
"snapshot_id": "90fc817802339f871052538e690159dd7a2401b2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/alexanderathan/demo/385524bf1e35786f4285219c9cd1d5da8e057e82/Pods/TermiNetwork/TermiNetwork/Classes/Extensions/Data+Extensions.swift",
"visit_date": "2022-12-07T03:25:28.763327",
"added": "2024-11-19T02:38:07.484442+00:00",
"created": "2020-09-04T12:10:19",
"int_score": 3,
"score": 2.953125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0089.json.gz"
}
|
require 'optparse'
require 'buff/extensions'
module Berkshelf
module API
class SrvCtl
class << self
# @param [Array] args
#
# @return [Hash]
def parse_options(args, filename)
options = Hash.new
OptionParser.new("Usage: #{filename} [options]") do |opts|
opts.on("-h", "--host HOST", String, "set the listening address") do |h|
options[:host] = h
end
opts.on("-p", "--port PORT", Integer, "set the listening port") do |v|
options[:port] = v
end
opts.on("-V", "--verbose", "run with verbose output") do
options[:log_level] = "INFO"
end
opts.on("-d", "--debug", "run with debug output") do
options[:log_level] = "DEBUG"
end
opts.on("-q", "--quiet", "silence output") do
options[:log_location] = '/dev/null'
end
opts.on("-c", "--config FILE", String, "path to a configuration file to use") do |v|
options[:config_file] = v
end
opts.on("-v", "--version", "show version") do |v|
require 'berkshelf/api/version'
puts Berkshelf::API::VERSION
exit
end
opts.on_tail("-h", "--help", "show this message") do
puts opts
exit
end
end.parse!(args)
options.symbolize_keys
end
# @param [Array] args
# @param [String] filename
def run(args, filename)
options = parse_options(args, filename)
new(options).start
end
end
attr_reader :options
# @param [Hash] options
# @see {Berkshelf::API::Application.run} for the list of valid options
def initialize(options = {})
@options = options
@options[:eager_build] = true
end
def start
require 'berkshelf/api'
Berkshelf::API::Application.run(options)
end
end
end
end
|
1e0ef29e62d8603664edcc1cf1bc2f2f020a6939
|
{
"blob_id": "1e0ef29e62d8603664edcc1cf1bc2f2f020a6939",
"branch_name": "refs/heads/master",
"committer_date": "2015-09-16T16:58:18",
"content_id": "8284e6b2097388eb901da4853fcb83d94181f769",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "21c9b36a8952ecef3a9b2be373f5c507426266c6",
"extension": "rb",
"filename": "srv_ctl.rb",
"fork_events_count": 0,
"gha_created_at": "2015-02-22T21:08:39",
"gha_event_created_at": "2023-04-12T07:09:43",
"gha_language": "Ruby",
"gha_license_id": "Apache-2.0",
"github_id": 31180622,
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 2093,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/lib/berkshelf/api/srv_ctl.rb",
"provenance": "stack-edu-0067.json.gz:586817",
"repo_name": "ruizink/berkshelf-api",
"revision_date": "2015-09-16T16:58:18",
"revision_id": "52382d99354138e9f3a94a84f42c436fee60c52b",
"snapshot_id": "d6251723e0118ca640868546220bc78b2520cf91",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/ruizink/berkshelf-api/52382d99354138e9f3a94a84f42c436fee60c52b/lib/berkshelf/api/srv_ctl.rb",
"visit_date": "2023-04-27T18:09:38.562323",
"added": "2024-11-18T21:43:15.281546+00:00",
"created": "2015-09-16T16:58:18",
"int_score": 2,
"score": 2.09375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0085.json.gz"
}
|
//================================================================
// It must be permitted by Dabo.Zhang that this program is used for
// any purpose in any situation.
// Copyright (C) Dabo.Zhang 2000-2003
// All rights reserved by ZhangDabo.
// This program is written(created) by Zhang.Dabo in 2000.3
// The last modification of this program is in 2003.7
//=================================================================
//include file;
#ifndef DBCOMMON_H
#define DBCOMMON_H
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0501
#endif
#ifndef _WIN32_WINDOWS
#define _WIN32_WINDOWS 0x501
#endif
#ifndef USING_TAO //使用Win32基本Platform SDK
#include <winsock2.h> //确保调用新的WinSock2.2版本
#include <windows.h>
#else
#include "TAOSpecial.h"
#endif
//----------------------------------------------------------------
#define _DBC_BEGIN namespace dbc {
#define _DBC_END };
#define _DBC_USING using namespace dbc;
extern "C"
{
WINBASEAPI
BOOL
WINAPI
InitializeCriticalSectionAndSpinCount(
IN OUT LPCRITICAL_SECTION lpCriticalSection,
IN DWORD dwSpinCount
);
WINBASEAPI
BOOL
WINAPI
TryEnterCriticalSection(
IN OUT LPCRITICAL_SECTION lpCriticalSection
);
};
_DBC_BEGIN
#pragma pack(push)
#pragma pack(4)
//=================================================================
#define nil 0
//typedef type define
typedef char Char; //带符号8个二进制位(=1个字节)整型/字符数据
typedef wchar_t wChar;
typedef short Short; //带符号2字节整型数据
typedef long Long; //带符号4字节整型数据
typedef int Int; //带符号系统依赖整数数据(32位机实现为uLong)
typedef const char cChar;
typedef const wchar_t cwChar;
typedef const short cShort;
typedef const long cLong;
typedef const int cInt;
typedef unsigned char uChar; //无符号8个二进制位(=1个字节)整型/字符数据
typedef unsigned short uShort; //无符号2字节整型数据
typedef unsigned long uLong; //无符号4字节整型数据
typedef unsigned int uInt; //无符号系统依赖整数数据(32位机实现为uLong)
typedef const unsigned char cuChar;
typedef const unsigned short cuShort;
typedef const unsigned long cuLong;
typedef const unsigned int cuInt;
typedef wchar_t WChar; //2字节字符数据
typedef __int64 LLong; //带符号8字节整型数据
#define SIGN32 uLong(0x80000000)
#define SIGN16 uShort(0x8000)
#define SIGN8 uChar(0x80)
//=========================InterLockedLong========================================
#pragma pack(push)
#pragma pack(4)
class InterLockedLong
{
public:
InterLockedLong(LONG lInitVal=0);
InterLockedLong(const InterLockedLong &val);
operator LONG()const {return m_plVal/*Add(0)*/;}
LONG operator=(LONG val) {Assign(val);return val;}
LONG operator=(InterLockedLong &val){Assign(val);return val;}
LONG operator++() {return Increment();}
LONG operator++(int) {LONG lret =Increment();return lret -1;}
LONG operator--() {return Decrement();}
LONG operator--(int) {LONG lret =Decrement();return lret +1;}
LONG operator+=(LONG val) {LONG lret =Add(val);return lret +val;}
LONG operator-=(LONG val) {LONG lret =Add(-val);return lret -val;}
LONG operator+=(InterLockedLong &val){LONG lret =Add(LONG(val));return lret +val;}
LONG operator-=(InterLockedLong &val){LONG lret =Add(-LONG(val));return lret -val;}
LONG SetZero() {return Assign(0);}//返回原始值
LONG Increment(); //The return value is the resulting incremented value
LONG Decrement(); //The return value is the resulting decremented value
LONG Add(LONG Value); //The return value is the initial value
LONG Assign(LONG newval); //The return value is the initial value
LONG CompareAssign(LONG Comperand,LONG newval); //相等时候才赋值,The return value is the initial value
private:
LONG volatile m_plVal;
};
#pragma pack(pop)
struct RefArmor
{
RefArmor(InterLockedLong &count):m_count(count){++m_count;}
~RefArmor(){--m_count;}
private:
InterLockedLong &m_count;
};
//==============================BitMaskStatus===================================
//
class BitMaskStatus
{
public:
BitMaskStatus(uLong initmask =0):m_BitMask(initmask){}
int operator=(uLong mask) {return (m_BitMask = mask);}
void ClearBit(uLong mask) {m_BitMask &=~mask;}
void SetBit(uLong mask) {m_BitMask |= mask;}
bool IsTrue() {return (m_BitMask )?true:false;}
bool IsFalse() {return (m_BitMask )?false:true;}
bool IsTrue(uLong mask) {return (m_BitMask & mask)?true:false;}
bool IsFalse(uLong mask) {return (m_BitMask & mask)?false:true;}
private:
uLong m_BitMask;
};
//=================================================================
inline void *MakePointer(uLong ul_num)
{
return reinterpret_cast<void*>(reinterpret_cast<char*>(0)+ul_num);
}
inline uLong MakeULong(void *ponter)
{
return uLong(reinterpret_cast<char*>(ponter) -reinterpret_cast<char*>(0));
}
//=================================================================
inline char* MemCpy(char *dest,cChar *src,uLong size)
{
return (char*)memcpy(dest,src,size);
}
inline char* MemSet(char *dest,int val,uLong size)
{
return (char*)memset(dest,val,size);
}
//=================================================================
inline int wctmbcpy(char *dst,cwChar *src)
{
return WideCharToMultiByte(936,
#if(WINVER >= 0x0500)/* WINVER >= 0x0500 */
WC_NO_BEST_FIT_CHARS|
#endif
WC_COMPOSITECHECK,
src,-1,dst,dst?0x7FFFFFFF:0,0,0);
}
inline int wctmbcpy(uChar *dst,cwChar *src){return wctmbcpy(reinterpret_cast<char*>(dst),src);}
//=================================================================
class Mutex
{
public:
Mutex(uLong ulSpinCount =4000):m_ulSpinCount(ulSpinCount),m_create(false){Create(false);}
~Mutex(){if(m_create){m_create =false;lock();DeleteCriticalSection(&m_handle);}}
bool Create(bool bInitialOwner)
{
if(!m_create)
{
InitializeCriticalSectionAndSpinCount(&m_handle,0x80000000 +m_ulSpinCount);
m_create =true;
}
if(bInitialOwner)
{
lock();
}
return m_create;
}
operator bool()const {return m_create;}
void lock()const {if(m_create){EnterCriticalSection(&m_handle);}}
BOOL trylock()const {return m_create?TryEnterCriticalSection(&m_handle):0;}
void unlock()const {if(m_create){LeaveCriticalSection(&m_handle);}}
private:
bool m_create;
uLong m_ulSpinCount;
mutable CRITICAL_SECTION m_handle;
};
class MutexArmor{
public:
MutexArmor(const Mutex& mtx):m_mtx(mtx),m_locknum(0){lock();};
~MutexArmor()
{
while(m_locknum)
{
unlock();
}
};
operator bool()const{return m_mtx;};
void lock()const
{
m_mtx.lock();
m_locknum++;
}
BOOL trylock()const
{
BOOL l_ret =m_mtx.trylock();
if(l_ret)
{
m_locknum++;
}
return l_ret;
}
void unlock()const
{
if(m_locknum)
{
m_locknum--;
m_mtx.unlock();
}
}
private:
mutable uLong m_locknum;
const Mutex & m_mtx;
};
//=================================================================
class Sema
{
public:
Sema():m_handle(0),m_lMaximumCount(0){}
Sema(LONG lInitialCount,LONG lMaximumCount,LPCTSTR lpName =0):m_handle(0),m_lMaximumCount(0){Create(lInitialCount,lMaximumCount,lpName);}
~Sema(){Destroy();}
void Destroy() {if(m_handle){CloseHandle(m_handle);m_handle=0;}}
operator bool(){return m_handle!=0;};
BOOL Create(LONG lInitialCount,LONG lMaximumCount,LPCTSTR lpName =0)
{
if(!m_handle)
{
m_handle =CreateSemaphore(0,lInitialCount,lMaximumCount,lpName);
return TRUE;
}else
{
return FALSE;
}
}
DWORD lock() {return WaitForSingleObject(m_handle,INFINITE);}
DWORD trylock() {return WaitForSingleObject(m_handle,0);}
DWORD timelock(DWORD dwMilliseconds){return WaitForSingleObject(m_handle,dwMilliseconds);}
BOOL unlock(Long relcount =1) {return ReleaseSemaphore(m_handle,relcount,0);}
private:
HANDLE m_handle; //LockSemaphore
InterLockedLong m_ilCount;
LONG m_lMaximumCount; //只是一个标志,没有控制最大计数的功能
};
//比较操作符定义
template<class T> int operator <(const T &t1,const T &t2){return (t2>t1);}
template<class T> int operator<=(const T &t1,const T &t2){return !(t1>t2);}
template<class T> int operator>=(const T &t1,const T &t2){return !(t2>t1);}
template<class T> int operator!=(const T &t1,const T &t2){return !(t1==t2);}
/*/=================================================================
class Mutex{
public:
Mutex():m_handle(0){}
~Mutex(){if(m_handle){CloseHandle(m_handle);m_handle=0;}}
HANDLE Create(BOOL bInitialOwner,LPCTSTR lpName)
{
m_handle =CreateMutex(0,bInitialOwner,lpName);
return m_handle;
};
operator bool()const{return m_handle!=0;};
DWORD lock()const {return WaitForSingleObject(m_handle,INFINITE);}
DWORD trylock()const {return WaitForSingleObject(m_handle,0);}
DWORD timelock(DWORD time)const {return WaitForSingleObject(m_handle,time);}
BOOL unlock()const {return ReleaseMutex(m_handle);}
private:
HANDLE m_handle;
};
class MutexArmor{
public:
MutexArmor(Mutex& mtx):m_mtx(mtx),m_locknum(0){};
~MutexArmor()
{
while(m_locknum >0)
{
unlock();
}
};
operator bool()const{return m_mtx;};
DWORD lock()const
{
DWORD l_ret =m_mtx.lock();
if(l_ret ==WAIT_OBJECT_0)
{
m_locknum++;
}else
if(l_ret ==WAIT_ABANDONED)
{
m_locknum =1;
}
return l_ret;
}
DWORD trylock()const
{
DWORD l_ret =m_mtx.trylock();
if(l_ret ==WAIT_OBJECT_0)
{
m_locknum++;
}else
if(l_ret ==WAIT_ABANDONED)
{
m_locknum =1;
}
return l_ret;
}
DWORD timelock(DWORD time)const
{
DWORD l_ret =m_mtx.timelock(time);
if(l_ret ==WAIT_OBJECT_0)
{
m_locknum++;
}else
if(l_ret ==WAIT_ABANDONED)
{
m_locknum =1;
}
return l_ret;
}
BOOL unlock()const
{
BOOL l_ret =m_mtx.unlock();
if(l_ret)
{
m_locknum--;
}
return l_ret;
}
private:
mutable uLong m_locknum;
Mutex & m_mtx;
};
*/
#pragma pack(pop)
_DBC_END
#endif
|
3c86d865a36bfa59bd0113718c119498f872486b
|
{
"blob_id": "3c86d865a36bfa59bd0113718c119498f872486b",
"branch_name": "refs/heads/main",
"committer_date": "2021-06-02T15:35:36",
"content_id": "f8794476e5172d8355af3cafaf06082e6e4f61d4",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "67563a4436b914654dd441eb2e1915bbd41aa8ca",
"extension": "h",
"filename": "DBCCommon.h",
"fork_events_count": 0,
"gha_created_at": "2021-06-01T08:17:07",
"gha_event_created_at": "2021-06-02T15:26:17",
"gha_language": "C++",
"gha_license_id": "Apache-2.0",
"github_id": 372753278,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 9930,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Common/Server/sdk/include/DBCCommon.h",
"provenance": "stack-edu-0007.json.gz:93139",
"repo_name": "PKO-Community-Sources/ClientSide-Sources",
"revision_date": "2021-06-02T15:35:36",
"revision_id": "ddbcd293d6ef3f58ff02290c02382cbb7e0939a2",
"snapshot_id": "1cab923af538ffe9d9cb9154b14dd3e0a903ca14",
"src_encoding": "GB18030",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/PKO-Community-Sources/ClientSide-Sources/ddbcd293d6ef3f58ff02290c02382cbb7e0939a2/Common/Server/sdk/include/DBCCommon.h",
"visit_date": "2023-05-13T00:15:04.162386",
"added": "2024-11-18T23:31:36.879615+00:00",
"created": "2021-06-02T15:35:36",
"int_score": 2,
"score": 2.0625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0025.json.gz"
}
|
package com.identos.contracing.ui;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.google.android.material.snackbar.Snackbar;
public class BluetoothStateReciever extends BroadcastReceiver {
private BluetoothStateChangeHandler bluetoothStateChangeHandler;
public BluetoothStateReciever(BluetoothStateChangeHandler bluetoothStateChangeHandler) {
this.bluetoothStateChangeHandler = bluetoothStateChangeHandler;
}
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
this.bluetoothStateChangeHandler.handleBluetoothStateChange(state);
}
}
}
|
db5f4e33a2862ada8eae0337302197350238d140
|
{
"blob_id": "db5f4e33a2862ada8eae0337302197350238d140",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-05T01:49:08",
"content_id": "5ddd1fa482980723c13865301496fad1cf60e049",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "106775e7631f968ec2e69722c3c089dbd3f9fe17",
"extension": "java",
"filename": "BluetoothStateReciever.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 942,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/android/app/src/main/java/com/identos/contracing/ui/BluetoothStateReciever.java",
"provenance": "stack-edu-0030.json.gz:173984",
"repo_name": "sidwashere/contact_tracing",
"revision_date": "2020-05-05T01:49:08",
"revision_id": "6059d49cb5178fc4c92dbb49a975e5f55cfbded2",
"snapshot_id": "b426026f9f8f0327d4795128f97462169a16fd30",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/sidwashere/contact_tracing/6059d49cb5178fc4c92dbb49a975e5f55cfbded2/android/app/src/main/java/com/identos/contracing/ui/BluetoothStateReciever.java",
"visit_date": "2022-07-08T01:48:55.026825",
"added": "2024-11-19T02:39:37.030738+00:00",
"created": "2020-05-05T01:49:08",
"int_score": 2,
"score": 2.25,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0048.json.gz"
}
|
<?php
namespace backend\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use backend\models\Alumni;
/**
* AlumniSearch represents the model behind the search form about `backend\models\Alumni`.
*/
class AlumniSearch extends Alumni
{
/**
* @inheritdoc
*/
public function rules()
{
return [
[['alumni_id', 'e_jantina'], 'integer'],
[['e_nama', 'e_kp', 'e_alamat', 'e_poskod', 'e_alamat_tetap', 'e_poskod_tetap', 'e_tel_rumah', 'e_tel_hp', 'e_emel1', 'e_emel2', 'e_program', 'e_fakulti', 'e_tahun_tamat'], 'safe'],
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = Alumni::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere([
'alumni_id' => $this->alumni_id,
'e_jantina' => $this->e_jantina,
]);
$query->andFilterWhere(['like', 'e_nama', $this->e_nama])
->andFilterWhere(['like', 'e_kp', $this->e_kp])
->andFilterWhere(['like', 'e_alamat', $this->e_alamat])
->andFilterWhere(['like', 'e_poskod', $this->e_poskod])
->andFilterWhere(['like', 'e_alamat_tetap', $this->e_alamat_tetap])
->andFilterWhere(['like', 'e_poskod_tetap', $this->e_poskod_tetap])
->andFilterWhere(['like', 'e_tel_rumah', $this->e_tel_rumah])
->andFilterWhere(['like', 'e_tel_hp', $this->e_tel_hp])
->andFilterWhere(['like', 'e_emel1', $this->e_emel1])
->andFilterWhere(['like', 'e_emel2', $this->e_emel2])
->andFilterWhere(['like', 'e_program', $this->e_program])
->andFilterWhere(['like', 'e_fakulti', $this->e_fakulti])
->andFilterWhere(['like', 'e_tahun_tamat', $this->e_tahun_tamat]);
return $dataProvider;
}
}
|
1d97e8a11bcb3a7475ab9ee5bb541773cf794362
|
{
"blob_id": "1d97e8a11bcb3a7475ab9ee5bb541773cf794362",
"branch_name": "refs/heads/master",
"committer_date": "2015-10-07T03:52:11",
"content_id": "766898c397e0242107a8d3593b899a4da6a65950",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "5ab23535be3319fcadb7d993f9a8705a5dbff5ac",
"extension": "php",
"filename": "AlumniSearch.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 43793036,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 2459,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/backend/models/AlumniSearch.php",
"provenance": "stack-edu-0048.json.gz:339723",
"repo_name": "NeroJz/admbackend",
"revision_date": "2015-10-07T03:52:11",
"revision_id": "67e6f359ca6490714a09ed922e1ac20ac1fe2c00",
"snapshot_id": "374f62a0d45d9e21d589d7a26bb2fbd8103fcfcf",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/NeroJz/admbackend/67e6f359ca6490714a09ed922e1ac20ac1fe2c00/backend/models/AlumniSearch.php",
"visit_date": "2016-08-12T16:01:28.549657",
"added": "2024-11-18T22:10:23.466628+00:00",
"created": "2015-10-07T03:52:11",
"int_score": 2,
"score": 2.46875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0066.json.gz"
}
|
// **Livecoding** is the parent component. It includes all other
// components. It listens and responds to events when necessary.
// It maintains the application's state.
// Include React.
var React = require('react');
// Include libraries.
var PubSub = require('pubsub-js');
var GitHub = require('../util/GitHub.js');
var _ = require('lodash');
var util = require('../util/util.js');
// Include all top-level components.
var MenuBar = require('./MenuBar.jsx');
var Output = require('./Output.jsx');
var Editor = require('./Editor.jsx');
var Updates = require('./Updates.jsx');
var Avatar = require('./Avatar.jsx');
// Get latest updates.
var updateData = require('../../../.tmp/updates.json');
// Create the React component.
var Livecoding = React.createClass({
statics: {
TOKEN: 'LIVECODING_TOKEN',
USER: 'LIVECODING_USER',
USER_AVATAR_URL: 'LIVECODING_USER_AVATAR_URL'
},
getToken: function() { return localStorage.getItem(Livecoding.TOKEN); },
setToken: function(token) { localStorage.setItem(Livecoding.TOKEN, token); },
getUser: function() { return localStorage.getItem(Livecoding.USER); },
setUser: function(user) { localStorage.setItem(Livecoding.USER, user); },
getUserAvatarUrl: function() { return localStorage.getItem(Livecoding.USER_AVATAR_URL); },
setUserAvatarUrl: function(userAvatarUrl) { localStorage.setItem(Livecoding.USER_AVATAR_URL, userAvatarUrl); },
// Set the initial state. As the application grows, so
// will the number of state properties.
getInitialState: function() {
return {
html: '',
javascript: '',
css: '',
mode: 'html', // specify what mode we're editing
user: this.getUser(),
userAvatarUrl: this.getUserAvatarUrl(),
gist: null
};
},
// Each React component has a `render` method. It gets called
// every time the application's state changes.
render: function() {
// Get the current mode.
var mode = this.state.mode;
// Get the current mode's content.
var content = this.state[mode];
var html = this.state.html;
var javascript = this.state.javascript;
var css = this.state.css;
// Should output render all code?
var makeOutputRenderAllCode = this.makeOutputRenderAllCode.pop();
this.makeOutputRenderAllCode.push(this._defaultMakeOutputRenderAllCode);
// Should we update the Editor?
var updateEditor = this.updateEditorContent.pop();
this.updateEditorContent.push(this._defaultUpdateEditorContent);
var isDirty = this.isDirty();
var isBlank = !html.length && !javascript.length && !css.length;
// Render the application. This will recursively call
// `render` on all the components.
return (
<div className='livecoding'>
<MenuBar
mode={mode}
gistUrl={this.state.gist ? this.state.gist.html_url : null}
gistVersion={this.state.gist ? this.state.gist.history[0].version : null}
user={this.state.user}
userAvatarUrl={this.state.userAvatarUrl}
savedMessage={this.flashSaved.pop()}
isDirty={isDirty}
isBlank={isBlank}
/>
<div className='content'>
<Output
html={html}
javascript={javascript}
css={css}
mode={mode}
renderAllCode={makeOutputRenderAllCode}
/>
<Editor
content={content}
mode={mode}
update={updateEditor}
/>
</div>
<Updates updates={updateData} />
</div>
);
},
// This function gets called once, before the initial render.
componentWillMount: function() {
var self = this;
// Setup all the subscriptions.
PubSub.subscribe(Editor.topics().ContentChange, self.handleContentChange);
PubSub.subscribe(MenuBar.topics().ModeChange, self.handleModeChange);
PubSub.subscribe(MenuBar.topics().ItemClick, self.handleMenuItemClick);
PubSub.subscribe(GitHub.topics().Token, self.handleGatekeeperToken);
PubSub.subscribe(Avatar.topics().LoginClick, self.handleLoginClick);
// If there's a gist id in the url, retrieve the gist.
var match = location.href.match(/[a-z\d]+$/);
if (match) {
GitHub.readGist(this.getToken(), match[0])
.then(function(gist) {
// Instruct Output to render all code.
self.makeOutputRenderAllCode.pop();
self.makeOutputRenderAllCode.push(true);
// Extract code contents and selected mode.
var data = GitHub.convertGistToLivecodingData(gist);
// Update the state.
var state = _.assign({}, data, {gist: gist});
self.setState(state);
}).catch(function(error) {
console.log('Error', error);
});
}
},
handleLoginClick: function() {
GitHub.login();
},
// Every time **Editor**'s content changes it hands **Livecoding**
// the new content. **Livecoding** then updates its current state
// with the new content. This setup enforces React's one-way data
// flow.
handleContentChange: function(topic, content) {
// Get the current mode.
var mode = this.state.mode;
// Update application state with new content.
var change = {};
change[mode] = content;
// Don't update Editor contents.
this.updateEditorContent.pop();
this.updateEditorContent.push(false);
this.setState(change);
},
// Handle mode change.
handleModeChange: function(topic, mode) {
this.setState({
mode: mode
});
},
// Handle menu item click.
handleMenuItemClick: function(topic, menuItem) {
var self = this;
function file_new() {
// If not dirty, then go ahead.
// Otherwise ask for confirmation first.
if (!self.isDirty() || confirm('Are you sure? You will lose any unsaved changes.')) {
// Reset all state properties.
self.setState({
html: '',
javascript: '',
css: '',
mode: 'html',
gist: null
});
// Blank out url.
history.pushState(null, '', '#');
}
}
function file_save() {
// Is user logged in? If so, save.
if (self.getToken()) {
self.save();
} else {
// There's no way to tell GitHub "after you give me a token, I want to save/delete/etc"
// So we'll store the desired function call in a stack,
self.afterAuthentication.push('save');
// and then we'll make the login call.
GitHub.login();
}
}
var menuItems = {
'file:new': file_new,
'file:save': file_save
};
menuItems[menuItem]();
},
// Handle gatekeeper token.
handleGatekeeperToken: function(topic, response) {
// Save the token.
this.setToken(response.token);
var self = this;
// Get user information.
GitHub.getUser(this.getToken())
.then(function(user) {
// Save user info on local storage,
self.setUser(user.login);
self.setUserAvatarUrl(user.avatar_url);
// and update Livecoding's state.
self.setState({
user: self.getUser(),
userAvatarUrl: self.getUserAvatarUrl()
});
// JS version of a switch statement.
var nextSteps = {
'save': function() {
self.save();
}
};
// Get next step after authentication.
var next = self.afterAuthentication.pop();
// If we have a next step,
if (next) {
// call it.
nextSteps[next]();
}
}).catch(function(error) {
console.log('Error', error);
});
},
// Save gist.
save: function() {
// Create payload.
var data = _.pick(this.state, [
'html',
'javascript',
'css',
'mode'
]);
var self = this;
// If there is no gist,
if (!this.state.gist) {
// create a new gist,
GitHub.createGist(this.getToken(), data)
.then(function(gist) {
// set flash message,
self.flashSaved.push('saved');
// and update state.
self.setState({gist: gist});
history.pushState(gist.id, '', '#' + gist.id);
}).catch(function(error) {
console.log('Error', error);
});
} else {
// There is a gist. Are we the owner?
if (this.state.gist.owner && (this.state.gist.owner.login === this.state.user)) {
// We're the gist owner. Update the gist,
GitHub.updateGist(this.getToken(), data, this.state.gist.id)
.then(function(gist) {
// set flash message,
self.flashSaved.push('saved');
// and update state.
self.setState({gist: gist});
}).catch(function(error) {
console.log('Error', error);
});
} else {
// We're not the gist owner. Fork,
GitHub.forkGist(this.getToken(), this.state.gist.id)
.then(function(gist) {
// then update the gist,
return GitHub.updateGist(self.getToken(), data, gist.id);
})
.then(function(gist) {
// set flash message,
self.flashSaved.push('saved');
// and update state.
self.setState({gist: gist});
history.pushState(gist.id, '', '#' + gist.id);
}).catch(function(error) {
console.log('Error', error);
});
}
}
},
// Check if user has made unsaved changes.
isDirty: function() {
var gist = this.state.gist;
var html = this.state.html;
var javascript = this.state.javascript;
var css = this.state.css;
// If gist is null, return true if user has typed code.
if (!gist) {
return html.length || javascript.length || css.length;
} else {
// If gist is not null, compare gist and code contents.
var data = GitHub.convertGistToLivecodingData(gist);
return !(data.html === html && data.javascript === javascript && data.css == css);
}
},
// Store the desired function call after authentication.
afterAuthentication: [],
// Decide whether to render all code in Output.
_defaultMakeOutputRenderAllCode: false,
makeOutputRenderAllCode: [this._defaultMakeOutputRenderAllCode],
// Decide whether to render update Editor contents.
_defaultUpdateEditorContent: true,
updateEditorContent: [this._defaultUpdateEditorContent],
// Flash saved message.
flashSaved: []
});
// Render the entire application to `.main`.
React.render(
<Livecoding />,
document.querySelector('.main')
);
|
dee2ea10e6070d39c6eb999073971a7efe5fa4ad
|
{
"blob_id": "dee2ea10e6070d39c6eb999073971a7efe5fa4ad",
"branch_name": "refs/heads/gh-pages",
"committer_date": "2015-01-04T05:03:06",
"content_id": "3608e96cae4a767b95952a06def582b4dd23f4db",
"detected_licenses": [
"MIT"
],
"directory_id": "c7cd6b508f4ea46bdc58ba143efeecd244225985",
"extension": "jsx",
"filename": "Livecoding.jsx",
"fork_events_count": 0,
"gha_created_at": "2015-01-02T00:48:53",
"gha_event_created_at": "2015-01-02T00:48:53",
"gha_language": null,
"gha_license_id": null,
"github_id": 28699714,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 9830,
"license": "MIT",
"license_type": "permissive",
"path": "/src/js/components/Livecoding.jsx",
"provenance": "stack-edu-0039.json.gz:627064",
"repo_name": "kustomzone/livecoding",
"revision_date": "2015-01-04T05:03:06",
"revision_id": "427d16522ecc742068d6e9a95ea1d2194092b86f",
"snapshot_id": "2561d55e18658594f821c419c724e0918fb5caa5",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/kustomzone/livecoding/427d16522ecc742068d6e9a95ea1d2194092b86f/src/js/components/Livecoding.jsx",
"visit_date": "2021-01-18T11:57:02.174387",
"added": "2024-11-19T00:18:08.239700+00:00",
"created": "2015-01-04T05:03:06",
"int_score": 2,
"score": 2.15625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0057.json.gz"
}
|
#!/bin/bash
# Provide source directive to shellcheck.
# shellcheck source=meta-fii/meta-kudo/recipes-kudo/kudo-fw-utility/kudo-fw/kudo-lib.sh
source /usr/libexec/kudo-fw/kudo-lib.sh
function set_mux_default(){
# set all mux route to CPU before power on host
# BMC_CPU_RTC_I2C_SEL
set_gpio_ctrl CPU_RTC_SEL 1
# BMC_CPU_DDR_I2C_SEL
set_gpio_ctrl CPU_DDR_SEL 1
# BMC_CPU_EEPROM_I2C_SEL
set_gpio_ctrl CPU_EEPROM_SEL 1
# BMC_CPU_PMBUS_SEL
set_gpio_ctrl CPU_VRD_SEL 1
# LED control
# LED_BMC_LIVE
set_gpio_ctrl LED_BMC_ALIVE 1
# SPI control
# Send command to CPLD to switch the bios spi interface to host
i2cset -y -f -a "${I2C_BMC_CPLD[0]}" 0x"${I2C_BMC_CPLD[1]}" 0x10 0x00
}
# 0 - 63 EVT
# 64 + DVT/PVT
boardver=$(printf '%d' "$(awk '{print $6}' /sys/bus/i2c/drivers/fiicpld/"${I2C_MB_CPLD[0]}"-00"${I2C_MB_CPLD[1]}"/CMD00)")
# On EVT machines, the secondary SCP EEPROM is used.
# Set BMC_I2C_BACKUP_SEL to secondary.
if [[ $boardver -lt $BOARDVER_EVT_LAST ]]; then
echo "EVT system. Choosing secondary SCP EEPROM."
set_gpio_ctrl BACKUP_SCP_SEL 0
set_mux_default
# Power control
# S0_BMC_OK
set_gpio_ctrl S0_BMC_OK 1
else
echo "DVT or PVT system"
# sleep so that FRU and all ipmitool Devices are ready before HOST OS
# HPM_STBY_RST_N to DC-SCM spec
set_gpio_ctrl HPM_STBY_RST_N 1 # on DVT this became HPM_STBY_RST_N (EVT1 came from CPLD)
sleep 5 # for the MUX to get ready
set_mux_default
# Power control
# S0_BMC_OK
set_gpio_ctrl S0_BMC_OK 1
fi
# Disable CPU 1 CLK when cpu not detected
# echo init_once cpu $CPU1_STATUS > /dev/ttyS0
# echo init_once board $boardver > /dev/ttyS0
CPU1_STATUS_N=$(get_gpio_ctrl S1_STATUS_N)
if [[ $CPU1_STATUS_N == 1 ]]; then
#Execute this only on DVT systems
if [[ $boardver -lt $BOARDVER_EVT_LAST ]]; then
echo EVT system "$boardver"
else
echo DVT system "$boardver"
i2cset -y -a -f "${I2C_S1_CLKGEN[0]}" 0x"${I2C_S1_CLKGEN[1]}" 0x05 0x03
fi
#These i2c deviecs are already installed on EVT systems
i2cset -y -a -f "${I2C_S1_PCIE_CLKGEN1[0]}" 0x"${I2C_S1_PCIE_CLKGEN1[1]}" 0 1 0xdf i
i2cset -y -a -f "${I2C_S1_PCIE_CLKGEN1[0]}" 0x"${I2C_S1_PCIE_CLKGEN1[1]}" 11 1 0x01 i
i2cset -y -a -f "${I2C_S1_PCIE_CLKGEN2[0]}" 0x"${I2C_S1_PCIE_CLKGEN2[1]}" 1 2 0x3f 0x0c i
fi
# Create /run/openbmc for system power files
mkdir "/run/openbmc"
# Restart psusensor service to enusre that the VBAT sensor doesn't say "no reading" until
# it's second query after a hotswap
(sleep 45; systemctl restart xyz.openbmc_project.psusensor.service)&
|
a3f2d1fa7ece25eddcc3ca34eb16b34562d8fc5f
|
{
"blob_id": "a3f2d1fa7ece25eddcc3ca34eb16b34562d8fc5f",
"branch_name": "refs/heads/master",
"committer_date": "2023-09-01T02:46:41",
"content_id": "6e931524d6ee029a6dcb5d5a4e902a9216011f74",
"detected_licenses": [
"MIT",
"Apache-2.0"
],
"directory_id": "89ded8c781da45ab288ec31441d5819758bb407c",
"extension": "sh",
"filename": "init_once.sh",
"fork_events_count": 877,
"gha_created_at": "2015-09-15T19:51:42",
"gha_event_created_at": "2023-08-16T08:21:27",
"gha_language": "Python",
"gha_license_id": "NOASSERTION",
"github_id": 42542702,
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 2643,
"license": "MIT,Apache-2.0",
"license_type": "permissive",
"path": "/meta-fii/meta-kudo/recipes-kudo/kudo-sys-utility/kudo-boot/init_once.sh",
"provenance": "stack-edu-0069.json.gz:228982",
"repo_name": "openbmc/openbmc",
"revision_date": "2023-08-14T02:10:35",
"revision_id": "3596dc23c54f7c26579558a03214ef8017c8df10",
"snapshot_id": "0cc1ffe401bf38a3512ef76e12f0b0346d09e46a",
"src_encoding": "UTF-8",
"star_events_count": 1604,
"url": "https://raw.githubusercontent.com/openbmc/openbmc/3596dc23c54f7c26579558a03214ef8017c8df10/meta-fii/meta-kudo/recipes-kudo/kudo-sys-utility/kudo-boot/init_once.sh",
"visit_date": "2023-09-01T13:27:27.075873",
"added": "2024-11-19T01:36:19.314524+00:00",
"created": "2023-08-14T02:10:35",
"int_score": 3,
"score": 3.125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0087.json.gz"
}
|
package com.zheng.home.data;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.zheng.home.data.model.Quiz;
import com.zheng.home.data.remote.QuizApi;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import javax.inject.Inject;
import javax.inject.Singleton;
import io.reactivex.Single;
import kotlin.Pair;
@Singleton
public class DataManager {
private QuizApi quizApi;
@Inject
public DataManager(QuizApi quizApi) {
this.quizApi = quizApi;
}
public Single<Pair<Integer, Quiz>> getResponse() {
return quizApi.getQuizItemList()
.toObservable()
.flatMapIterable(json ->
getQuizList(json))
.toList().map(quizList -> {
Random random = new Random();
int i = random.nextInt(quizList.size());
Quiz quiz = quizList.get(i);
return new Pair<Integer, Quiz>(getQuizAnswer(quiz), quiz);
})
;
}
public Quiz getRandomQuiz(List<Quiz> quizList) {
Random random = new Random();
int i = random.nextInt(quizList.size());
return quizList.get(i);
}
public int getQuizAnswer(Quiz quiz) {
List<String> answers = quiz.getImages();
String correctAnswer = answers.get(0);
Collections.shuffle(answers);
return answers.indexOf(correctAnswer);
}
public List<Quiz> getQuizList(String json) {
JsonParser jsonParser = new JsonParser();
JsonElement parse = jsonParser.parse(json);
JsonObject asJsonObject = parse.getAsJsonObject();
Set<Map.Entry<String, JsonElement>> entries = asJsonObject.entrySet();
List<Quiz> quizList = new ArrayList<>();
for (Map.Entry<String, JsonElement> entry : entries) {
String key = entry.getKey();
JsonElement value = entry.getValue();
JsonArray asJsonArray = value.getAsJsonArray();
List<String> images = new ArrayList<>();
for (int i = 0; i < asJsonArray.size(); i++) {
images.add(asJsonArray.get(i).getAsString());
}
quizList.add(new Quiz(key, images));
}
return quizList;
}
}
|
46a02403bd5095dfe736e53bd27803c4a924f393
|
{
"blob_id": "46a02403bd5095dfe736e53bd27803c4a924f393",
"branch_name": "refs/heads/master",
"committer_date": "2018-04-08T01:43:44",
"content_id": "bf7bfcb345550c3aba8661de318a92072fe308ee",
"detected_licenses": [
"MIT"
],
"directory_id": "eba0edd7d6c140f4f7f10fd82b20f3b8b4935707",
"extension": "java",
"filename": "DataManager.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 128493315,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2456,
"license": "MIT",
"license_type": "permissive",
"path": "/app/src/main/java/com/zheng/home/data/DataManager.java",
"provenance": "stack-edu-0022.json.gz:46166",
"repo_name": "dzzheng3/mvp_quiz_kotlin",
"revision_date": "2018-04-08T01:43:44",
"revision_id": "c11dbf778a4a76bc88dca7009adf61247f5a0bcc",
"snapshot_id": "099510eb011c253eb1060d1c11ad2932502a8038",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dzzheng3/mvp_quiz_kotlin/c11dbf778a4a76bc88dca7009adf61247f5a0bcc/app/src/main/java/com/zheng/home/data/DataManager.java",
"visit_date": "2020-03-09T00:38:54.645352",
"added": "2024-11-18T23:03:35.981459+00:00",
"created": "2018-04-08T01:43:44",
"int_score": 3,
"score": 2.5625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0040.json.gz"
}
|
import { TTS } from "../utils";
const command =
"/process?INPUT_TYPE=TEXT&AUDIO=WAVE_FILE&OUTPUT_TYPE=AUDIO&LOCALE=en_US&INPUT_TEXT=";
export default (phrase: string): string => {
return `${TTS}${command}${encodeURIComponent(phrase)}`;
};
|
1d7a7772e8fcfa8071319a365c736562db783772
|
{
"blob_id": "1d7a7772e8fcfa8071319a365c736562db783772",
"branch_name": "refs/heads/main",
"committer_date": "2020-08-28T22:34:57",
"content_id": "fef7d56df91115ce6d99cbf463adec54a6a573bb",
"detected_licenses": [
"MIT"
],
"directory_id": "1d179e09086d579af7848425534b829647d344ef",
"extension": "ts",
"filename": "tts-controller.ts",
"fork_events_count": 0,
"gha_created_at": "2020-08-20T04:43:45",
"gha_event_created_at": "2020-08-28T22:34:58",
"gha_language": "TypeScript",
"gha_license_id": "MIT",
"github_id": 288908187,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 245,
"license": "MIT",
"license_type": "permissive",
"path": "/src/controllers/tts-controller.ts",
"provenance": "stack-edu-0073.json.gz:906733",
"repo_name": "nzcodarnoc/korerorero-voice-service",
"revision_date": "2020-08-28T22:34:57",
"revision_id": "172b351a5b19fe1894cf80f88c9550c4237b61a1",
"snapshot_id": "eee5b3674bc7b360c620a751840c187b96bcffb7",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/nzcodarnoc/korerorero-voice-service/172b351a5b19fe1894cf80f88c9550c4237b61a1/src/controllers/tts-controller.ts",
"visit_date": "2022-12-07T23:30:42.975921",
"added": "2024-11-18T22:11:39.979614+00:00",
"created": "2020-08-28T22:34:57",
"int_score": 2,
"score": 2.109375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0091.json.gz"
}
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/4/3 12:09
# @Author : tiancai.wu
# import logging
#
# from celery._state import get_current_task
#
# class Formatter(logging.Formatter):
# """Formatter for tasks, adding the task name and id."""
#
# def format(self, record):
# task = get_current_task()
# if task and task.request:
# record.__dict__.update(task_id='666666666666666',#'%s ' % task.request.id,
# task_name='%s ' % task.name)
# else:
# record.__dict__.setdefault('task_name', '777777')
# record.__dict__.setdefault('task_id', '')
# return logging.Formatter.format(self, record)
#
#
# root_logger = logging.getLogger() # 返回logging.root
# root_logger.setLevel(logging.DEBUG)
#
# # 将日志输出到文件
# fh = logging.FileHandler('celery_worker.log') # 这里注意不要使用TimedRotatingFileHandler,celery的每个进程都会切分,导致日志丢失
# formatter = Formatter('[%(task_name)s%(task_id)s%(process)s %(thread)s %(asctime)s %(pathname)s:%(lineno)s] %(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
# fh.setFormatter(formatter)
# fh.setLevel(logging.DEBUG)
# root_logger.addHandler(fh)
#
# # 将日志输出到控制台
# sh = logging.StreamHandler()
# formatter = Formatter('[%(task_name)s%(task_id)s%(process)s %(thread)s %(asctime)s %(pathname)s:%(lineno)s] %(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
# sh.setFormatter(formatter)
# sh.setLevel(logging.INFO)
# root_logger.addHandler(sh)
class CeleryConfig(object):
BROKER_URL = 'redis://localhost:6379/2'
# CELERY_RESULT_BACKEND = 'redis://localhost:6379/0'
CELERY_TASK_SERIALIZER = 'pickle' # " json从4.0版本开始默认json,早期默认为pickle(可以传二进制对象)
CELERY_RESULT_SERIALIZER = 'pickle'
CELERY_ACCEPT_CONTENT = ['json', 'pickle']
CELERY_ENABLE_UTC = True # 启用UTC时区
CELERY_TIMEZONE = 'Asia/Shanghai' # 上海时区
CELERYD_HIJACK_ROOT_LOGGER = True # 拦截根日志配置
CELERYD_MAX_TASKS_PER_CHILD = 1 # 每个进程最多执行1个任务后释放进程(再有任务,新建进程执行,解决内存泄漏)
|
def0adf6ffac05fbe45b71ff0ac61cb72338ec23
|
{
"blob_id": "def0adf6ffac05fbe45b71ff0ac61cb72338ec23",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-26T01:19:08",
"content_id": "d1599a475e994757df4b36baab889d9acc504962",
"detected_licenses": [
"MIT"
],
"directory_id": "5288a2057e0876207b7215acad1a2fd7bef1bd24",
"extension": "py",
"filename": "celeryconfig.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 305357459,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2232,
"license": "MIT",
"license_type": "permissive",
"path": "/backend/新建文件夹/DjangoRestAuth/config/celeryconfig.py",
"provenance": "stack-edu-0054.json.gz:594668",
"repo_name": "wutiancai/electron-vue-admin",
"revision_date": "2020-10-26T01:19:08",
"revision_id": "81528ea4a1a4dddf9fd6af28a104b6a1a0151169",
"snapshot_id": "019c07f330aeed6501a2f634231b74578595efcf",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/wutiancai/electron-vue-admin/81528ea4a1a4dddf9fd6af28a104b6a1a0151169/backend/新建文件夹/DjangoRestAuth/config/celeryconfig.py",
"visit_date": "2023-01-01T12:17:03.614877",
"added": "2024-11-18T21:10:04.143268+00:00",
"created": "2020-10-26T01:19:08",
"int_score": 2,
"score": 2.25,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0072.json.gz"
}
|
import { DateSpec } from './date-spec.js'
/**
* An object containing data about a specific meal.
*/
export interface CanteenMeal {
name: string
price: string
classifiers: string[]
additives: string[]
}
/**
* An object describing a line that is part of a canteen plan, and that contains a list of meals.
*/
export interface CanteenLine {
id: string | null
name: string
meals: CanteenMeal[]
}
/**
* An object describing a canteen at a specific date, which contains lines with meal information.
*/
export interface CanteenPlan {
id: string | null
name: string
date: DateSpec
lines: CanteenLine[]
}
|
82218326cbf5835aa142bd9cd61f85102a827ef6
|
{
"blob_id": "82218326cbf5835aa142bd9cd61f85102a827ef6",
"branch_name": "refs/heads/main",
"committer_date": "2023-08-10T20:58:48",
"content_id": "decc24381e4c7424ed8056df3b269ae9f61c7607",
"detected_licenses": [
"MIT"
],
"directory_id": "34b633d86461d8bedfa0ef2fbae3f7f3558ca28b",
"extension": "ts",
"filename": "canteen-plan.ts",
"fork_events_count": 0,
"gha_created_at": "2019-11-17T18:39:49",
"gha_event_created_at": "2023-09-11T01:11:40",
"gha_language": "TypeScript",
"gha_license_id": "MIT",
"github_id": 222294513,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 626,
"license": "MIT",
"license_type": "permissive",
"path": "/src/types/canteen-plan.ts",
"provenance": "stack-edu-0074.json.gz:351720",
"repo_name": "meyfa/ka-mensa-fetch",
"revision_date": "2023-08-10T20:58:48",
"revision_id": "5f2400a415d26fb119efda916b3a217187bd3b1d",
"snapshot_id": "eff1f0ab36e126fef95831b27c9b6c7332e2dc56",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/meyfa/ka-mensa-fetch/5f2400a415d26fb119efda916b3a217187bd3b1d/src/types/canteen-plan.ts",
"visit_date": "2023-08-24T13:09:12.975429",
"added": "2024-11-19T01:02:58.490281+00:00",
"created": "2023-08-10T20:58:48",
"int_score": 3,
"score": 2.890625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0092.json.gz"
}
|
#include <Keypad.h>
#include <LiquidCrystal.h>
#include <Servo.h>
String tempPassword = ""; // String variable to hold the PIN that will be entered
boolean unlocked = false; // lock is not yet unlocked
int failCount = 0; // initialize the number of times that the code was entered incorrectly to 0
// ======== MOTOR CLASS ========= //
/*
* This class provides the angles that the motor would
* spin to, as well as the methods necessary to get these
* angles as well as open and close the "lock" by setting
* the servo to move to these angles. Utilizes the Servo.h
* library, which provides basic servo attach and write
* methods.
*/
Servo servo; // create an instance of Servo called servo
class Motor {
// list of all the private variables
private:
const int openAngle = 178; // the angle at which the servo should be in order to open lock
const int closeAngle = 68; // the angle at which the servo should be in order to close lock
const int servoPin = 3; // the digital I/O pin to which the servo is connected
// list of all the public methods
public:
Motor();
int getOpenAngle();
int getCloseAngle();
void motorSetup();
void motorOpenAndClose();
};
// Constructor
Motor::Motor() {
}
// Getter for the angle that opens the lock
int Motor::getOpenAngle() {
return this->openAngle;
}
// Getter for the angle that closes the lock
int Motor::getCloseAngle() {
return this->closeAngle;
}
/*
* Initializes the servo motor to the right pin
* on the Arduino and sets the angle to the
* close angle
*/
void Motor::motorSetup() {
servo.attach(servoPin); // initialize the servo to be connected to
// the right digital I/O pin on the Arduino
servo.write(closeAngle);
}
/*
* Opens the lock by turning the servo to the
* open angle and then closes the lock by turning
* the servo to the close angle
*/
void Motor::motorOpenAndClose() {
servo.write(openAngle);
delay(3000); // wait for a few seconds to allow the user to enter through the entrance
servo.write(closeAngle);
}
Motor* motor; // create an instance of motor to be used in the main loop
// ========= LCD CLASS ========== //
/*
* This class contains all the messages that are to be
* displayed on the LCD screen, as well as the methods
* that sets up, and writes messages to the LCD. Uses the LiquidCrystal.h
* library, which provides basic LCD begin, clear, setCursor, and print
* methods.
*/
// create a LiquidCrystal.h LiquidCrystal with pins 8-13, where:
// pins 8-11 are data pins D4-D7
// pin 12 is the E (enable) pin
// pin 13 is the RS (register select) pin
LiquidCrystal lcd(13, 12, 11, 10, 9, 8);
const String enterPinMessage = "Enter PIN:";
const String unlockedMessage = "Unlocked";
const String correctPinMessage = "Correct PIN";
const String incorrectPinMessage = "Wrong! Try again";
const String wrongFiveTimesMessage = "Wrong 5 times";
const String timedOutMessage = "Timed out";
/*
* Setup the LCD display using the LiquidCrystal.h
* begin method
*/
void lcdSetup() {
lcd.begin(16,2);
}
// Method to display the Enter Pin message
void lcdEnterPinMessage() {
lcd.clear();
lcd.setCursor(0,0); // move cursor to top left corner of LCD display
lcd.print(enterPinMessage);
}
// Method to display the Correct PIN and Unlocked message
void lcdUnlockedMessage() {
lcd.clear();
lcd.setCursor(0,0);
lcd.print(correctPinMessage);
lcd.setCursor(0,1); // move cursor to the second line, far left of LCD display
lcd.print(unlockedMessage);
}
// Method to display the Incorrect PIN message
void lcdIncorrectPinMessage() {
lcd.setCursor(0,1);
lcd.print(incorrectPinMessage);
}
// Method to display the Wrong Five Times message and Timed Out message
void lcdTimedOutMessage() {
lcd.clear();
lcd.setCursor(0,0);
lcd.print(wrongFiveTimesMessage);
lcd.setCursor(0,1);
lcd.print(timedOutMessage);
}
// ========= KEYPAD CLASS ========= //
/*
* The Keypad class contains variables that describe the keypad
* structure, as well as methods that take in a PIN and store it
* in a string variable and sends this PIN to the server in order
* to get it verified. Utilizes the Keypad.h library for basic
* methods like getKey.
*/
char keys[4][3] = { //declare an array that describes the physical 4x3 keypad
{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'}
};
byte rowPins[4] = {7, 6, 5, 4}; // the digital I/O pins that are used to control the rows of the keypad
byte colPins[3] = {14, 2, 15}; // the analog pins (14 and 15) and digital I/O pin that are used to
// control the columns of the keypad
char keypressed; // char variable used to store the character that is pressed on the keypad
/*
* Initialize an instance of class Keypad (from Keypad.h); requires the 4x3 array of keys,
* the array of pins controlling the rows, the array of pins controlling the columns,
* the number of rows, and the number of columns
*/
Keypad mykeypad = Keypad(makeKeymap(keys), rowPins, colPins, 4, 3);
/*
* Method used to continuously take in characters of the key pressed and
* display '*' to represent the numbers of the PIN until
* four characters have been taken in and the '*' is pressed. Sets the
* tempPassword to equal this taken-in PIN and returns the tempPassword
*/
String keypadEnterPin() {
int placeCursor=5; // start the cursor at the center of the LCD display to center the entered PIN
int numKeysPressed=1; // variable to keep track of how many keys have been pressed so far
tempPassword = ""; // ensure that the variable that stores the password to be entered is blank first
while(keypressed != '*') {
keypressed = mykeypad.getKey(); // use a Keypad.h function to get key
if (keypressed != NO_KEY && numKeysPressed <= 4){
if (keypressed == '0' || keypressed == '1' || keypressed == '2' || keypressed == '3' ||
keypressed == '4' || keypressed == '5' || keypressed == '6' || keypressed == '7' ||
keypressed == '8' || keypressed == '9' ) {
tempPassword += keypressed; // add the character pressed to the temporary password
lcd.setCursor(placeCursor,1);
lcd.print("*");
placeCursor++; // advance the cursor one spot to the right
// in order to display the '*' that represents the PIN
numKeysPressed++;
}
}
}
return tempPassword;
}
/*
* Method that takes in the entered password, sends it to the
* server in order for it to be verified, and receives a '1'
* back if the PIN was correct and sets the unlocked variable
* accordingly to be returned.
*/
boolean keypadVerifyPin(String tempPassword) {
// verify that the PIN is of the correct length
if(tempPassword.length() == 4) {
Serial.println(tempPassword); // send the PIN to the server through serial interface
delay(2000); // wait for the server to validate PIN and send a signal back
// receive signal sent from server, if '1' then PIN was correct, set unlocked to true
if(Serial.read() == '1') {
unlocked = true;
}
// PIN was incorrect, set unlocked to false
else {
unlocked = false;
}
}
return unlocked;
}
/*
* Sets up the Arduino and all the hardware components that are attached to it
*/
void setup() {
// Initializes the serial baud rate to 9600 in order to communicate with the server
Serial.begin(9600);
// Sets up the analog pins 14 and 15 to be inputs in order to use with the keypad
pinMode(14, INPUT);
pinMode(15, INPUT);
// Create an instance of the motor class and initializes it
motor = new Motor();
motor -> motorSetup();
// Initializes the LCD
lcdSetup();
}
/*
* Continuous loop that allows user to enter a PIN, have the PIN
* sent to the server to be verified, and either open and close the
* lock according to the message received from the server, or
* keep the lock closed and inflict a time out if the PIN has been
* entered incorrectly five times.
*/
void loop() {
lcdEnterPinMessage(); // display "Enter PIN: " on the LCD
// if the PIN entered on the keypad is valid, display
// unlocked message and make motor move to unlock door
if (keypadVerifyPin(keypadEnterPin())){
lcdUnlockedMessage();
motor -> motorOpenAndClose();
unlocked = false; // set unlocked back to false for the next cycle
//failCount = 0;
}
else {
lcdIncorrectPinMessage();
delay(2000); // display the incorrect PIN message for two seconds
failCount++; // increment the number of times that the PIN was entered incorrectly
}
delay(2000);
// if the server sent back a '5' and the failCount reached 5, time out
if (Serial.read() == '5' && failCount >= 5) {
lcdTimedOutMessage();
delay(10000); // time out for 10 seconds
failCount = 0; // reset the failCount back to 0 for the next cycle
}
keypressed = mykeypad.getKey(); // keeps the keypad expectant for a key
}
|
2f9e8f41dede3933f6e35b54932949e1009b7d18
|
{
"blob_id": "2f9e8f41dede3933f6e35b54932949e1009b7d18",
"branch_name": "refs/heads/master",
"committer_date": "2017-12-04T16:47:17",
"content_id": "eaa6289a14c1d524da002ccc96002f9ad4c52c55",
"detected_licenses": [
"MIT"
],
"directory_id": "ff535dd2548723729b676a5b67dcb406709a180e",
"extension": "ino",
"filename": "Revised_Arduino_and_Pi_Connect.ino",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 105560364,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 9021,
"license": "MIT",
"license_type": "permissive",
"path": "/Arduino/Revised_Arduino_and_Pi_Connect.ino",
"provenance": "stack-edu-0007.json.gz:502984",
"repo_name": "alaguveerappan/SYSC3010",
"revision_date": "2017-12-04T16:46:43",
"revision_id": "810653124940787237e615b19b4d3bc1ea634afd",
"snapshot_id": "c8ea876fbcd4ae70d3dd82262305141574f6a35d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/alaguveerappan/SYSC3010/810653124940787237e615b19b4d3bc1ea634afd/Arduino/Revised_Arduino_and_Pi_Connect.ino",
"visit_date": "2021-08-23T11:11:40.582345",
"added": "2024-11-18T21:18:46.992330+00:00",
"created": "2017-12-04T16:46:43",
"int_score": 3,
"score": 3.28125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0025.json.gz"
}
|
# canvassnakegame
Build a "Snake" Game
Goal:
Build an interactive Snake clone in JavaScript. If you have never played Snake, you can read about it here: http://en.wikipedia.org/wiki/Snake_(video_game)
Musts:
* Use JavaScript
* Run on latest versions of Chrome, Safari, and FireFox
* Use Canvas 2D
* Use requestAnimationFrame
* Support different screen pixel ratios (densities)
* Use arrow keys to change direction of the Snake
* Increase the length of the Snake by one block for each block it "eats"
* Increase the speed of the Snake by a small percentage for each block it "eats"
* When the snake "eats" a block, randomly place a new block on the board that is a certain distance from the snake's current position and the walls.
* End the game if the Snake "bites its own tail" or runs into a wall
Shoulds:
* Use underscore
* Keep score
* Pause the game with SPACE key
* Reset the game by clicking on the Canvas
* Design the game using JavaScript objects and inheritance (use _.extend)
Coulds:
* Use jquery for DOM manipulation and event binding (though not really needed for this exercise)
* Use requirejs for dependency injection
* Deploy the game to Heroku using Node.js
* Save highscores in browser localstorage
* Provide different difficulty levels
* Provide different board sizes
* Support the fullscreen API
* Write unit tests using Mocha
Live version
Currently deployed on Heroku.
Heroku: https://canvassnakegame.herokuapp.com/
To run locally:
npm install
grunt
node app.js
License
Copyright (c) 2015 Chris Nichols
Licensed under the MIT license.
|
8eb55c09526ecc1617751078b1914e55701213f4
|
{
"blob_id": "8eb55c09526ecc1617751078b1914e55701213f4",
"branch_name": "refs/heads/master",
"committer_date": "2015-04-03T14:59:41",
"content_id": "ba865f91ac296ffbb719f5a875c4f33e7e274349",
"detected_licenses": [
"MIT"
],
"directory_id": "ff5f40ec2193e54c5516b42f6841f60340001f65",
"extension": "md",
"filename": "README.md",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 33093501,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1570,
"license": "MIT",
"license_type": "permissive",
"path": "/README.md",
"provenance": "stack-edu-markdown-0006.json.gz:7101",
"repo_name": "skytow/canvassnakegame",
"revision_date": "2015-04-03T14:59:41",
"revision_id": "57443c1a4321539912a247da84c3642441d4e3e0",
"snapshot_id": "ca0b2658e46c745776a8ad4d7218a99662e5db9e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/skytow/canvassnakegame/57443c1a4321539912a247da84c3642441d4e3e0/README.md",
"visit_date": "2020-04-01T19:35:05.837412",
"added": "2024-11-18T22:44:15.460237+00:00",
"created": "2015-04-03T14:59:41",
"int_score": 3,
"score": 2.90625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0006.json.gz"
}
|
<?php namespace FHIR\Resources\Clinical\AdverseReaction;
use FHIR\Common\AbstractFHIRObject;
use FHIR\Elements\Complex\FHIRCodeableConcept;
use FHIR\Elements\Simple\FHIRCode;
/**
* Class FHIRAdverseReactionSymptom
* @package FHIR\Resources\Clinical\AdverseReaction
*/
class FHIRAdverseReactionSymptom extends AbstractFHIRObject
{
// TODO Implement http://www.hl7.org/implement/standards/fhir/reactionSeverity.html
/** @var FHIRCodeableConcept */
protected $code = null;
/** @var FHIRCode */
protected $severity = null;
/**
* @return FHIRCodeableConcept
*/
public function getCode()
{
return $this->code;
}
/**
* @param FHIRCodeableConcept $code
*/
public function setCode(FHIRCodeableConcept $code)
{
$this->code = $code;
}
/**
* @return FHIRCode
*/
public function getSeverity()
{
return $this->severity;
}
/**
* @param FHIRCode $severity
*/
public function setSeverity(FHIRCode $severity)
{
$this->severity = $severity;
}
}
|
1db3edf850f10340887669634fa139bd80533563
|
{
"blob_id": "1db3edf850f10340887669634fa139bd80533563",
"branch_name": "refs/heads/master",
"committer_date": "2016-01-24T19:11:45",
"content_id": "b698765f7c3feb99b71d7fb51aeded56ee9b5267",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "31f7752c9caafa273669331110df6cd1c6c2f2a8",
"extension": "php",
"filename": "FHIRAdverseReactionSymptom.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 33500835,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 1092,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/Clinical/AdverseReaction/FHIRAdverseReactionSymptom.php",
"provenance": "stack-edu-0047.json.gz:384440",
"repo_name": "dcarbone/php-fhir-resources",
"revision_date": "2016-01-24T19:11:45",
"revision_id": "20daa462629653b795409627b7cf9b2d34993235",
"snapshot_id": "b46018ab4494729f5b5c97046fa9df01fa7b9648",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/dcarbone/php-fhir-resources/20daa462629653b795409627b7cf9b2d34993235/src/Clinical/AdverseReaction/FHIRAdverseReactionSymptom.php",
"visit_date": "2023-08-11T15:59:56.313530",
"added": "2024-11-18T21:50:51.576515+00:00",
"created": "2016-01-24T19:11:45",
"int_score": 3,
"score": 2.796875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0065.json.gz"
}
|
/*
* Copyright 2015 xinjunli (micromagic@sina.com).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package self.micromagic.eterna.dao.impl;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import self.micromagic.dbvm.DataBaseLocker;
import self.micromagic.eterna.dao.Dao;
import self.micromagic.util.StringAppender;
import self.micromagic.util.StringTool;
import self.micromagic.util.ref.IntegerRef;
import self.micromagic.util.ref.ObjectRef;
/**
* 数据操作脚本的解析器.
*/
public class ScriptParser
{
/**
* 节点类型为一个操作符.
*/
public static final int ELEMENT_GROUP = 1000;
/**
* 节点类型为一个操作符.
*/
public static final int BASE_TYPE_OPERATOR = 1;
/**
* 节点类型为一个控制标识符.
*/
public static final int BASE_TYPE_FLAG = 2;
/**
* 节点类型为一个转义操作符.
*/
public static final int BASE_TYPE_ESCAPE = 3;
/**
* 节点类型为一个参数符.
*/
public static final int BASE_TYPE_PARAM = 5;
/**
* 节点类型为一个关键字.
*/
public static final int BASE_TYPE_KEY = 31;
/**
* 节点类型为一个次要关键字.
*/
public static final int BASE_TYPE_KEY_MINOR = 32;
/**
* 节点类型为一个字符串.
*/
public static final int BASE_TYPE_STRING = 21;
/**
* 节点类型为一个数字.
*/
public static final int BASE_TYPE_NUMBER = 22;
/**
* 节点类型为一个名称.
*/
public static final int BASE_TYPE_NAME = 10;
/**
* 节点类型为一个带有引号的名称.
*/
public static final int BASE_TYPE_NAME_QUOT = 11;
/**
* 引号.
*/
public static final String QUOTE = "\"";
/**
* 引号, 字符型.
*/
public static final char QUOTE_CHAR = '\"';
/**
* 字符串的标识符.
*/
public static final char STRING_FLAG = '\'';
/**
* 对一个脚本进行解析并返回词法节点列表.
*
* @param script 需要解析的脚本
* @param level 需要解析的等级
*/
public Element[] parseScript(String script, int level)
{
List r = this.parseScript0(script);
if (level > 0)
{
r = this.parseElement1(r);
}
if (level > 1)
{
r = this.parseElement2(r);
}
int count = r.size();
return (Element[]) r.toArray(new Element[count]);
}
/**
* 解析一个脚本并返回词法节点列表.
* 即前置解析.
*/
List parseScript0(String script)
{
List r = new ArrayList();
int count = script.length();
boolean notMatch = false;
int begin = 0;
int i = 0;
while (i < count)
{
char c = script.charAt(i);
if (c <= ' ' || operators.get(c))
{
if (notMatch)
{
r.add(new ParserBaseElement(begin, script.substring(begin, i)));
notMatch = false;
}
r.add(new ParserBaseElement(i, script.substring(i, i + 1)));
begin = ++i;
continue;
}
notMatch = true;
i++;
}
if (notMatch)
{
r.add(new ParserBaseElement(begin, script.substring(begin)));
}
return r;
}
/**
* 对每个词法节点进行第二轮解析.
* 处理操作符, 分组等.
*/
List parseElement2(List elements)
{
return elements;
}
private static final int P1_NORMAL_MODE = 0;
private static final int P1_STRING_MODE = 1;
private static final int P1_NAME_MODE = 2;
/**
* 对每个词法节点进行第一轮解析.
* 去除空白字符, 合并字符串, 添加类型等.
*/
List parseElement1(List elements)
{
List r = new ArrayList();
IntegerRef mode = new IntegerRef(P1_NORMAL_MODE);
IntegerRef begin = new IntegerRef();
Iterator itr = elements.iterator();
ObjectRef buf = new ObjectRef();
while (itr.hasNext())
{
ParserBaseElement e = (ParserBaseElement) itr.next();
this.parseElement1_0(e, itr, mode, begin, buf, r);
}
return r;
}
/**
* 解析单个词法节点.
* 第一轮.
*/
private void parseElement1_0(ParserBaseElement element, Iterator elements,
IntegerRef mode, IntegerRef begin, ObjectRef buf, List result)
{
ParserBaseElement next = null;
if (mode.value == P1_STRING_MODE)
{
StringAppender tmpBuf = (StringAppender) buf.getObject();
tmpBuf.append(element.text);
if (isStringFlag(element))
{
if (elements.hasNext())
{
next = (ParserBaseElement) elements.next();
if (isStringFlag(next))
{
// 连续两个字符串标识, 作为转义符
tmpBuf.append(next.text);
return;
}
}
ParserBaseElement e = new ParserBaseElement(begin.value, tmpBuf.toString());
e.type = BASE_TYPE_STRING;
result.add(e);
buf.setObject(null);
mode.value = P1_NORMAL_MODE;
}
}
else if (mode.value == P1_NAME_MODE)
{
StringAppender tmpBuf = (StringAppender) buf.getObject();
tmpBuf.append(element.text);
if (isNameFlag(element))
{
ParserBaseElement e = new ParserBaseElement(begin.value, tmpBuf.toString());
e.type = BASE_TYPE_NAME_QUOT;
result.add(e);
buf.setObject(null);
mode.value = P1_NORMAL_MODE;
}
}
else if (!emptyElement(element))
{
int c = checkOperatorFlag(element);
if (c != -1)
{
begin.value = element.begin;
if (c == STRING_FLAG)
{
mode.value = P1_STRING_MODE;
StringAppender tmpBuf = StringTool.createStringAppender(32);
tmpBuf.append(element.text);
buf.setObject(tmpBuf);
}
else if (c == QUOTE_CHAR)
{
mode.value = P1_NAME_MODE;
StringAppender tmpBuf = StringTool.createStringAppender(32);
tmpBuf.append(element.text);
buf.setObject(tmpBuf);
}
else
{
if (c == '?')
{
element.type = BASE_TYPE_PARAM;
}
else if (c == '#')
{
element.type = BASE_TYPE_OPERATOR;
if (elements.hasNext())
{
next = (ParserBaseElement) elements.next();
int tmpChar = checkOperatorFlag(next);
if (tmpChar != -1)
{
if (tmpChar != STRING_FLAG && tmpChar != QUOTE_CHAR)
{
// 可作为转义符
element.type = BASE_TYPE_ESCAPE;
element.text = element.text.concat(next.text);
next = null;
}
}
else if (!emptyElement(next))
{
String tmpTxt = next.text.toUpperCase();
if (!isNumber(tmpTxt))
{
element.type = BASE_TYPE_FLAG;
// 控制标识不转大写
element.text = element.text.concat(next.text);
next = null;
}
}
}
}
else if (c == '.')
{
element.type = BASE_TYPE_OPERATOR;
if (elements.hasNext())
{
next = (ParserBaseElement) elements.next();
String tmpTxt = next.text.toUpperCase();
if (isNumber(tmpTxt))
{
element.type = BASE_TYPE_NUMBER;
element.text = element.text.concat(tmpTxt);
next = null;
}
}
}
else
{
element.type = BASE_TYPE_OPERATOR;
}
result.add(element);
}
}
else
{
String tmp = element.text.toUpperCase();
Boolean flag = (Boolean) keys.get(tmp);
if (flag == null)
{
if (isNumber(tmp))
{
if (elements.hasNext())
{
next = (ParserBaseElement) elements.next();
if (checkOperatorFlag(next) == '.')
{
tmp = tmp.concat(next.text);
if (elements.hasNext())
{
next = (ParserBaseElement) elements.next();
String tmpTxt = next.text.toUpperCase();
if (isNumber(tmpTxt))
{
tmp = tmp.concat(tmpTxt);
next = null;
}
}
else
{
next = null;
}
}
}
element.type = BASE_TYPE_NUMBER;
}
else
{
element.type = BASE_TYPE_NAME;
}
}
else
{
element.type = flag.booleanValue() ?
BASE_TYPE_KEY : BASE_TYPE_KEY_MINOR;
}
element.text = tmp;
result.add(element);
}
}
if (next != null)
{
// 有预读的节点, 需要对其进行处理
this.parseElement1_0(next, elements, mode, begin, buf, result);
}
}
/**
* 检查给出的文本是否可作为一个数字.
* 文本必须都转为大写.
*/
private static boolean isNumber(String text)
{
int count = text.length();
boolean hasX = false;
for (int i = 0; i < count; i++)
{
char c = text.charAt(i);
if (c < '0' || c > '9')
{
if (c == 'E')
{
continue;
}
if ((c == 'X' && i == 1))
{
hasX = true;
continue;
}
if (hasX && c >= 'A' && c <= 'F')
{
continue;
}
return false;
}
}
return true;
}
/**
* 检测是否为操作标识节点.
* 如果是则返回操作字符, 否则返回-1.
*/
private static int checkOperatorFlag(ParserBaseElement e)
{
if (e.text.length() == 1)
{
char c = e.text.charAt(0);
if (operators.get(c))
{
return c;
}
}
return -1;
}
/**
* 检测是否为字符串标识节点.
*/
private static boolean isStringFlag(ParserBaseElement e)
{
return e.text.length() == 1 && e.text.charAt(0) == STRING_FLAG;
}
/**
* 检测是否为名称标识节点.
*/
private static boolean isNameFlag(ParserBaseElement e)
{
return e.text.length() == 1 && e.text.charAt(0) == QUOTE_CHAR;
}
/**
* 检测是否为空白字符节点.
*/
private static boolean emptyElement(ParserBaseElement e)
{
return e.text.length() == 1 && e.text.charAt(0) <= ' ';
}
/**
* 检查名称, 如果需要添加引号则添上.
*/
public static String checkNameForQuote(String name)
{
return checkNeedQuote(name) ? QUOTE.concat(name).concat(QUOTE) : name;
}
/**
* 检查名称是否需要添加引号.
*/
public static boolean checkNeedQuote(String name)
{
if (StringTool.isEmpty(name))
{
return false;
}
int len = name.length();
for (int i = 0; i < len; i++)
{
char c = name.charAt(i);
if (c == QUOTE_CHAR)
{
// 包含引号的名称不能再添加引号
return false;
}
if (c != '_' && (c < 'A' || c > 'Z') && (c < 'a' || c > 'z'))
{
if (i == 0 || (c < '0' || c > '9'))
{
return true;
}
}
}
if (len <= MAX_MAIN_KEY_LENGTH && keys.get(name.toUpperCase()) == Boolean.TRUE)
{
// 如果是主要关键字, 需要添加引号
return true;
}
return false;
}
/**
* 检查名称, 如果是主要关键字, 则添加引号.
*/
public static String checkNameWithKey(String name)
{
return isKey(name) == Boolean.TRUE ? QUOTE.concat(name).concat(QUOTE) : name;
}
/**
* 判断所给出的名称是否为关键字.
*
* @return TRUE 为主要关键字, FALSE 为次要关键字, null 不是关键字
*/
public static Boolean isKey(String name)
{
if (StringTool.isEmpty(name) || name.startsWith(QUOTE))
{
// 为空或以引号开始的不会是关键字
return null;
}
return (Boolean) keys.get(name.toUpperCase());
}
/**
* 检查数据库连接是否需要添加回滚记录点.
*/
public static boolean needSavepoint(Connection conn)
throws SQLException
{
if (conn.getAutoCommit())
{
return false;
}
String dbName = DataBaseLocker.getDataBaseProductName(conn);
return DataBaseLocker.DB_NAME_POSTGRES.equals(dbName);
}
/**
* 检查语句中的名称标识符, 替换成数据库相关的名称标识符.
*/
public static String checkScriptNameQuote(Connection conn, String script)
throws SQLException
{
if (conn == null || StringTool.isEmpty(script))
{
return script;
}
String dbName = DataBaseLocker.getDataBaseProductName(conn);
char[] nameQuote = (char[]) nameQuoteIndex.get(dbName);
if (nameQuote == null || nameQuote[0] == QUOTE_CHAR)
{
return script;
}
return checkScriptNameQuote0(nameQuote, script);
}
static String checkScriptNameQuote0(char[] nameQuote, String script)
{
int nameIndex = script.indexOf(QUOTE_CHAR);
if (nameIndex == -1)
{
return script;
}
// 处理数据库相关的名称标识符
int strIndex = script.indexOf(STRING_FLAG);
if (strIndex == -1 && nameQuote[0] == nameQuote[1])
{
return script.replace(QUOTE_CHAR, nameQuote[0]);
}
int count = script.length();
StringAppender buf = null;
if (strIndex == -1)
{
strIndex = count;
}
int baseIndex = 0;
while (strIndex < count || nameIndex < count)
{
if (strIndex < nameIndex)
{
// 字符串标识在引号前, 需要判断名称标识符是否在字符串内
int next = getStringFlagEnd(script, strIndex + 1, count);
if (next == -1)
{
// 字符串标识有问题, 不做处理
return script;
}
// 查找下一个字符串标识符
strIndex = script.indexOf(STRING_FLAG, next + 1);
if (strIndex == -1)
{
strIndex = count;
}
if (next > nameIndex)
{
// 如果字符串标识结束位置大于名称标识符, 说明这个名称标识符在字符串内, 重新查找下一个名称标识符
nameIndex = script.indexOf(QUOTE_CHAR, next + 1);
if (nameIndex == -1)
{
nameIndex = count;
}
}
}
else
{
if (buf == null)
{
buf = StringTool.createStringAppender(script.length());
}
buf.append(script.substring(baseIndex, nameIndex)).append(nameQuote[0]);
int next = script.indexOf(QUOTE_CHAR, nameIndex + 1);
if (next == -1)
{
// 名称标识有问题, 不做处理
return script;
}
buf.append(script.substring(nameIndex + 1, next)).append(nameQuote[1]);
baseIndex = next + 1;
// 查找下一个名称标识符
nameIndex = script.indexOf(QUOTE_CHAR, next + 1);
if (nameIndex == -1)
{
nameIndex = count;
}
if (next > strIndex)
{
// 如果名称标识结束位置大于字符串标识符, 说明这个字符串标识符在名称内, 重新查找下一个字符串标识符
strIndex = script.indexOf(STRING_FLAG, next + 1);
if (strIndex == -1)
{
strIndex = count;
}
}
}
}
return buf == null ? script
: buf.append(script.substring(baseIndex, count)).toString();
}
/**
* 获取字符串标识的结束位置.
*/
private static int getStringFlagEnd(String script, int fromInde, int count)
{
int next = script.indexOf(STRING_FLAG, fromInde);
while (next != -1)
{
if (next < count - 1 && script.charAt(next + 1) == STRING_FLAG)
{
// 连续两个字符串标识符是转义, 继续查找后面的
next = script.indexOf(STRING_FLAG, next + 2);
}
else
{
return next;
}
}
return next;
}
/**
* 名称引用符号的索引表.
*/
private static Map nameQuoteIndex = new HashMap();
/**
* 操作字符集合.
*/
private static BitSet operators = new BitSet();
/**
* 关键字集合.
*/
private static Map keys = new HashMap();
/**
* 主要关键字的最大长度.
*/
private static int MAX_MAIN_KEY_LENGTH = 8;
static
{
operators.set('?');
operators.set(',');
operators.set('(');
operators.set(')');
operators.set('[');
operators.set(']');
operators.set(STRING_FLAG);
operators.set(QUOTE_CHAR);
operators.set('.');
operators.set('=');
operators.set('<');
operators.set('>');
operators.set('!');
operators.set('*');
operators.set('/');
operators.set('|');
operators.set('+');
operators.set('-');
operators.set('#');
char[] defaultNameQuote = new char[] {QUOTE_CHAR, QUOTE_CHAR};
nameQuoteIndex.put(DataBaseLocker.DB_NAME_ORACLE, defaultNameQuote);
nameQuoteIndex.put(DataBaseLocker.DB_NAME_H2, defaultNameQuote);
nameQuoteIndex.put(DataBaseLocker.DB_NAME_MYSQL, new char[] {'`', '`'});
nameQuoteIndex.put(DataBaseLocker.DB_NAME_POSTGRES, defaultNameQuote);
try
{
String tmpStr = StringTool.toString(
Dao.class.getResourceAsStream("script_key.res"), "UTF-8");
String[] arr = StringTool.separateString(tmpStr, "\n", true);
for (int i = 0; i < arr.length; i++)
{
if (!StringTool.isEmpty(arr[i]))
{
if (arr[i].charAt(0) == '*')
{
keys.put(arr[i].substring(1).intern(), Boolean.TRUE);
int len = arr[i].length() - 1;
if (len > MAX_MAIN_KEY_LENGTH)
{
MAX_MAIN_KEY_LENGTH = len;
}
}
else
{
keys.put(arr[i].intern(), Boolean.FALSE);
}
}
}
}
catch (Exception ex)
{
DaoManager.log.error("Error in init script key.", ex);
}
}
/**
* 解析后的节点.
*/
public interface Element
{
/**
* 获取节点的类型.
*/
public int getType();
/**
* 获取节点的文本.
*/
public String getText();
}
}
/**
* 解析后的基本词法节点.
*/
class ParserBaseElement
implements ScriptParser.Element
{
ParserBaseElement(int begin, String text)
{
this.begin = begin;
this.text = text;
}
/**
* 词法节点的起始位置.
*/
int begin;
/**
* 词法节点的类型.
*/
int type;
/**
* 词法节点的文本.
*/
String text;
/**
* 是否为解析完成的词法节点.
*/
boolean finish;
public int getType()
{
return this.type;
}
public String getText()
{
return this.text;
}
public String toString()
{
return this.finish ? this.text : this.begin + ":" + this.type + ":" + this.text;
}
}
/**
* 解析后的聚合节点.
*/
class ParserGroupElement
{
}
|
690f02a670db310fae66169d5c144b9923b6b8f0
|
{
"blob_id": "690f02a670db310fae66169d5c144b9923b6b8f0",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-29T01:41:53",
"content_id": "86ed298637268670ca94d58c44d0bffdbbe2704a",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "79e0d9b45b7daefbcbc2a06cbbd595a29aae022c",
"extension": "java",
"filename": "ScriptParser.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 18592,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/main/src/java/main/self/micromagic/eterna/dao/impl/ScriptParser.java",
"provenance": "stack-edu-0024.json.gz:629690",
"repo_name": "biankudingcha/eterna",
"revision_date": "2020-04-29T01:41:53",
"revision_id": "ab32d1b804dc5698a0f85bcf457d0c05b72e852c",
"snapshot_id": "fd3863273008b370072129ed4a1ca8fb390cb503",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/biankudingcha/eterna/ab32d1b804dc5698a0f85bcf457d0c05b72e852c/main/src/java/main/self/micromagic/eterna/dao/impl/ScriptParser.java",
"visit_date": "2023-03-18T15:46:29.987896",
"added": "2024-11-18T21:39:52.101546+00:00",
"created": "2020-04-29T01:41:53",
"int_score": 2,
"score": 2.3125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0042.json.gz"
}
|
import webpack from 'webpack';
import { WebpackPlugin } from '../../types';
import {
ASSET_EXTENSIONS,
getAssetExtensionsRegExp,
SCALABLE_ASSETS,
} from '../utils/assetExtensions';
import {
AssetResolver,
AssetResolverConfig,
} from './AssetsResolverPlugin/AssetResolver';
/**
* {@link AssetsPlugin} configuration options.
*/
export interface AssetsPluginConfig extends AssetResolverConfig {
/**
* Whether the development server is enabled.
*/
devServerEnabled?: boolean;
/**
* Whether `AssetsPlugin` should configure asset loader automatically.
*
* Set to `false` if you want to configure it manually, for example if you are using
* `@svgr/webpack`.
*/
configureLoader?: boolean;
}
/**
* Plugin for loading and processing assets (images, audio, video etc) for
* React Native applications.
*
* Assets processing in React Native differs from Web, Node.js or other targets. This plugin allows
* you to use assets in the same way as you would do when using Metro.
*
* @deprecated Use dedicated rule with `@callstack/repack/assets-loader` and `AssetsResolverPlugin`.
* More information can be found here: https://github.com/callstack/repack/pull/81
*
* @category Webpack Plugin
*/
export class AssetsPlugin implements WebpackPlugin {
/**
* Constructs new `AssetsPlugin`.
*
* @param config Plugin configuration options.
*/
constructor(private config: AssetsPluginConfig) {
this.config.configureLoader = this.config.configureLoader ?? true;
this.config.extensions = this.config.extensions ?? ASSET_EXTENSIONS;
this.config.scalableExtensions =
this.config.scalableExtensions ?? SCALABLE_ASSETS;
}
/**
* Apply the plugin.
*
* @param compiler Webpack compiler instance.
*/
apply(compiler: webpack.Compiler) {
const assetResolver = new AssetResolver(this.config, compiler);
if (this.config.configureLoader) {
compiler.options.module.rules.push({
test: getAssetExtensionsRegExp(assetResolver.config.extensions!),
use: [
{
loader: require.resolve('../../../assets-loader.js'),
options: {
platform: this.config.platform,
scalableAssetExtensions: SCALABLE_ASSETS,
devServerEnabled: this.config.devServerEnabled,
},
},
],
});
}
compiler.options.resolve.plugins = (
compiler.options.resolve.plugins || []
).concat(assetResolver);
}
}
|
a6e6d342504b40e2c48472877c213170b9e096d3
|
{
"blob_id": "a6e6d342504b40e2c48472877c213170b9e096d3",
"branch_name": "refs/heads/main",
"committer_date": "2021-09-15T15:08:20",
"content_id": "6ccc7d1e23b62a2af3bfab2b1c4364a817986485",
"detected_licenses": [
"MIT"
],
"directory_id": "9d3407d936fde642422739fe5146f71d30d46c4e",
"extension": "ts",
"filename": "AssetsPlugin.ts",
"fork_events_count": 0,
"gha_created_at": "2021-09-20T03:44:56",
"gha_event_created_at": "2021-09-20T03:44:57",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 408302121,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 2489,
"license": "MIT",
"license_type": "permissive",
"path": "/packages/repack/src/webpack/plugins/AssetsPlugin.ts",
"provenance": "stack-edu-0075.json.gz:908915",
"repo_name": "jackHedaya/repack",
"revision_date": "2021-09-15T15:08:20",
"revision_id": "6e37e0a58c5506f1ee36fa72d8a8ffdb04317627",
"snapshot_id": "3d8e41362978e4e33d944e5fed7097c30b30e11c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jackHedaya/repack/6e37e0a58c5506f1ee36fa72d8a8ffdb04317627/packages/repack/src/webpack/plugins/AssetsPlugin.ts",
"visit_date": "2023-08-24T23:11:30.946739",
"added": "2024-11-18T22:21:35.304811+00:00",
"created": "2021-09-15T15:08:20",
"int_score": 2,
"score": 2.453125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0093.json.gz"
}
|
package rdap
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestRdapParsing(t *testing.T) {
for _, tt := range []struct {
domain string
err string
}{
{domain: "google.ai", err: "No RDAP servers found for 'google.ai'"},
{domain: "domreg.lt", err: "No RDAP servers found for 'domreg.lt'"},
{domain: "fakedomain.foo", err: "RDAP server returned 404, object does not exist."},
{domain: "google.cn", err: "No RDAP servers found for 'google.cn'"},
{domain: "google.com", err: ""},
{domain: "google.de", err: "No RDAP servers found for 'google.de'"},
{domain: "nic.ua", err: "No RDAP servers found for 'nic.ua'"},
{domain: "taiwannews.com.tw", err: "No RDAP servers found for 'taiwannews.com.tw'"},
{domain: "bbc.co.uk", err: "No RDAP servers found for 'bbc.co.uk'"},
{domain: "google.sk", err: "No RDAP servers found for 'google.sk'"},
{domain: "google.ro", err: "No RDAP servers found for 'google.ro'"},
{domain: "watchub.pw", err: ""},
{domain: "google.co.id", err: ""},
{domain: "google.kr", err: "No RDAP servers found for 'google.kr'"},
} {
tt := tt
t.Run(tt.domain, func(t *testing.T) {
t.Parallel()
expiry, err := NewClient().ExpireTime(context.Background(), tt.domain)
if tt.err == "" {
require.NoError(t, err)
require.True(t, time.Since(expiry).Hours() < 0, "domain must not be expired")
} else {
require.Error(t, err)
require.Contains(t, err.Error(), tt.err)
}
})
}
}
|
2e68a9f355f2397d29f95319902b338ba0bb0110
|
{
"blob_id": "2e68a9f355f2397d29f95319902b338ba0bb0110",
"branch_name": "refs/heads/master",
"committer_date": "2021-10-15T09:30:30",
"content_id": "92e434c3397f5983acabac31cfbc807f9f31d51a",
"detected_licenses": [
"MIT"
],
"directory_id": "5f3787b98c0d3eccfe91459135dcf1d3ce326c4b",
"extension": "go",
"filename": "rdap_test.go",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 417439903,
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 1489,
"license": "MIT",
"license_type": "permissive",
"path": "/internal/rdap/rdap_test.go",
"provenance": "stack-edu-0018.json.gz:558056",
"repo_name": "vorobiovv/domain_exporter",
"revision_date": "2021-10-15T09:30:30",
"revision_id": "0713e5fd1e48d9a0e134933e768c18fcd95e1eee",
"snapshot_id": "6e2d09f80cae700465ab0c3e2e985f0d7c7ffde3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/vorobiovv/domain_exporter/0713e5fd1e48d9a0e134933e768c18fcd95e1eee/internal/rdap/rdap_test.go",
"visit_date": "2023-08-30T23:48:36.260368",
"added": "2024-11-18T19:53:53.771001+00:00",
"created": "2021-10-15T09:30:30",
"int_score": 2,
"score": 2.34375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0036.json.gz"
}
|
module Mocks
def `(command)
case command
when /^git branch -r/
" master\n origin/feature/love-me-tender\n origin/feature/all-shock-up\n origin/feature/dont-be-cruel\n"
when /^git rev-parse --verify origin/
"830537aa0d35ae6b3a44610a1a0c1d7388224ca7"
when /^git rev-parse --is-inside-work-tree/
"true"
else
command
end
end
class Repository
attr_reader :path
def initialize(path)
@path = Pathname.new(path)
end
def to_path
@path.to_s
end
def locked?
false
end
end
class Branch
def self.factory(src)
src.split(",").map do |name|
new(name.strip)
end
end
def initialize(name)
@name = name
end
def to_s
@name
end
def valid?
true
end
def exists?(remote = true)
true
end
end
class Computer
def initialize(repo:, branches:, origin: "origin", default: "master")
@repo = repo
@origin = origin
@default = default
@branches = branches
end
%w[create remove rebase aggregate].each do |msg|
define_method(msg) do
"#{msg} on #{@repo}@#{@origin}/#{@default}"
end
end
end
class Prompt
include GitCommands::Prompt
def out
@out ||= StringIO.new
end
end
class Aggregator
def timestamp
"2017-02-01"
end
def call
"aggregate/#{timestamp}"
end
end
end
|
c3eb183064b363f6cbea7e60a6969014dda4d997
|
{
"blob_id": "c3eb183064b363f6cbea7e60a6969014dda4d997",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-09T07:42:54",
"content_id": "118cebfd2eb51cabd5d03be50909f4b1d4c92d48",
"detected_licenses": [
"MIT"
],
"directory_id": "5091980c3c842188133f55f36be4ea518c5c5b05",
"extension": "rb",
"filename": "mocks.rb",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 16404586,
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1454,
"license": "MIT",
"license_type": "permissive",
"path": "/spec/mocks.rb",
"provenance": "stack-edu-0067.json.gz:330523",
"repo_name": "costajob/git_commands",
"revision_date": "2020-07-09T07:42:54",
"revision_id": "5ec0f53dee99a398f6e6c62d652a5a1d47907c4b",
"snapshot_id": "7d4203a660893adb6110b77fd8154cbffcff4a86",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/costajob/git_commands/5ec0f53dee99a398f6e6c62d652a5a1d47907c4b/spec/mocks.rb",
"visit_date": "2022-11-15T12:06:33.897744",
"added": "2024-11-19T02:33:18.722148+00:00",
"created": "2020-07-09T07:42:54",
"int_score": 2,
"score": 2.40625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0085.json.gz"
}
|
package com.example.diegommir.skiptest.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
/**
* Entity class representing a Business.
*
* @author Diego Miranda
*/
@Entity
public class Business {
@Id
@GeneratedValue
private Long id;
@NotBlank
@Size(min=3, max=100)
private String name;
@NotBlank
@Size(min=3, max=150)
private String description;
@NotBlank
@Size(min=3, max=150)
private String address;
/**
* Default constructor.
*/
public Business() {
super();
}
/**
* Constructor using fields.
*
* @param id
* @param name
* @param description
* @param address
*/
public Business(Long id, String name, String description, String address) {
super();
this.id = id;
this.name = name;
this.description = description;
this.address = address;
}
/**
* @return the id
*/
public Long getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Long id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the description
*/
public String getDescription() {
return description;
}
/**
* @param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* @return the address
*/
public String getAddress() {
return address;
}
/**
* @param address the address to set
*/
public void setAddress(String address) {
this.address = address;
}
}
|
406136c25fe4514271bd778a08fb8fd6d5a465f9
|
{
"blob_id": "406136c25fe4514271bd778a08fb8fd6d5a465f9",
"branch_name": "refs/heads/master",
"committer_date": "2018-03-18T23:23:08",
"content_id": "2be5e1f412f674d914d3fda8b263033b1d205022",
"detected_licenses": [
"ISC"
],
"directory_id": "2e8d71b3f728235b237c626a0d356dbf0ed24bd3",
"extension": "java",
"filename": "Business.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 125663000,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1843,
"license": "ISC",
"license_type": "permissive",
"path": "/src/main/java/com/example/diegommir/skiptest/entity/Business.java",
"provenance": "stack-edu-0021.json.gz:227273",
"repo_name": "diegommir/skip-test",
"revision_date": "2018-03-18T23:23:08",
"revision_id": "55762ac3439b4d430eba5aa618ef7b2ef77ca9a3",
"snapshot_id": "db8c55dc3345ba6ec1a769957e15f34cd930f277",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/diegommir/skip-test/55762ac3439b4d430eba5aa618ef7b2ef77ca9a3/src/main/java/com/example/diegommir/skiptest/entity/Business.java",
"visit_date": "2021-04-09T14:50:06.363783",
"added": "2024-11-19T00:41:11.387733+00:00",
"created": "2018-03-18T23:23:08",
"int_score": 3,
"score": 3,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0039.json.gz"
}
|
package org.pushingpixels.demo.flamingo.svg.filetypes.transcoded;
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.lang.ref.WeakReference;
import java.util.Base64;
import javax.imageio.ImageIO;
import javax.swing.plaf.UIResource;
import org.pushingpixels.neon.api.icon.ResizableIcon;
import org.pushingpixels.neon.api.icon.ResizableIconUIResource;
/**
* This class has been automatically generated using <a
* href="https://github.com/kirill-grouchnikov/radiance">Photon SVG transcoder</a>.
*/
public class ext_indd implements ResizableIcon {
@SuppressWarnings("unused")
private void innerPaint(Graphics2D g) {
Shape shape = null;
Paint paint = null;
Stroke stroke = null;
Shape clip = null;
float origAlpha = 1.0f;
Composite origComposite = g.getComposite();
if (origComposite instanceof AlphaComposite) {
AlphaComposite origAlphaComposite =
(AlphaComposite)origComposite;
if (origAlphaComposite.getRule() == AlphaComposite.SRC_OVER) {
origAlpha = origAlphaComposite.getAlpha();
}
}
AffineTransform defaultTransform_ = g.getTransform();
//
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
AffineTransform defaultTransform__0 = g.getTransform();
g.transform(new AffineTransform(0.009999999776482582f, 0.0f, 0.0f, 0.009999999776482582f, 0.13999999687075615f, -0.0f));
// _0
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
AffineTransform defaultTransform__0_0 = g.getTransform();
g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f));
// _0_0
shape = new GeneralPath();
((GeneralPath)shape).moveTo(45.2, 1.0);
((GeneralPath)shape).lineTo(72.2, 27.7);
((GeneralPath)shape).lineTo(72.2, 99.0);
((GeneralPath)shape).lineTo(0.2, 99.0);
((GeneralPath)shape).lineTo(0.2, 1.0);
((GeneralPath)shape).lineTo(45.2, 1.0);
((GeneralPath)shape).closePath();
paint = new LinearGradientPaint(new Point2D.Double(36.20000076293945, -1.0), new Point2D.Double(36.20000076293945, 97.0), new float[] {0.312f,1.0f}, new Color[] {new Color(255, 234, 246, 255),new Color(219, 0, 123, 255)}, MultipleGradientPaint.CycleMethod.NO_CYCLE, MultipleGradientPaint.ColorSpaceType.SRGB, new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 2.0f));
g.setPaint(paint);
g.fill(shape);
g.setTransform(defaultTransform__0_0);
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
AffineTransform defaultTransform__0_1 = g.getTransform();
g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f));
// _0_1
shape = new GeneralPath();
((GeneralPath)shape).moveTo(45.2, 1.0);
((GeneralPath)shape).lineTo(72.2, 27.7);
((GeneralPath)shape).lineTo(72.2, 99.0);
((GeneralPath)shape).lineTo(0.2, 99.0);
((GeneralPath)shape).lineTo(0.2, 1.0);
((GeneralPath)shape).lineTo(45.2, 1.0);
((GeneralPath)shape).closePath();
paint = new Color(0, 0, 0, 0);
g.setPaint(paint);
g.fill(shape);
paint = new Color(219, 0, 123, 255);
stroke = new BasicStroke(2.0f,0,0,4.0f,null,0.0f);
shape = new GeneralPath();
((GeneralPath)shape).moveTo(45.2, 1.0);
((GeneralPath)shape).lineTo(72.2, 27.7);
((GeneralPath)shape).lineTo(72.2, 99.0);
((GeneralPath)shape).lineTo(0.2, 99.0);
((GeneralPath)shape).lineTo(0.2, 1.0);
((GeneralPath)shape).lineTo(45.2, 1.0);
((GeneralPath)shape).closePath();
g.setPaint(paint);
g.setStroke(stroke);
g.draw(shape);
g.setTransform(defaultTransform__0_1);
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
AffineTransform defaultTransform__0_2 = g.getTransform();
g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f));
// _0_2
shape = new GeneralPath();
((GeneralPath)shape).moveTo(8.7, 91.1);
((GeneralPath)shape).lineTo(8.7, 73.9);
((GeneralPath)shape).lineTo(12.2, 73.9);
((GeneralPath)shape).lineTo(12.2, 91.100006);
((GeneralPath)shape).lineTo(8.7, 91.100006);
((GeneralPath)shape).closePath();
((GeneralPath)shape).moveTo(15.6, 91.1);
((GeneralPath)shape).lineTo(15.6, 73.9);
((GeneralPath)shape).lineTo(19.0, 73.9);
((GeneralPath)shape).lineTo(26.1, 85.4);
((GeneralPath)shape).lineTo(26.1, 73.9);
((GeneralPath)shape).lineTo(29.4, 73.9);
((GeneralPath)shape).lineTo(29.4, 91.100006);
((GeneralPath)shape).lineTo(25.9, 91.100006);
((GeneralPath)shape).lineTo(18.9, 79.90001);
((GeneralPath)shape).lineTo(18.9, 91.100006);
((GeneralPath)shape).lineTo(15.599999, 91.100006);
((GeneralPath)shape).closePath();
((GeneralPath)shape).moveTo(33.0, 73.9);
((GeneralPath)shape).lineTo(39.4, 73.9);
((GeneralPath)shape).curveTo(40.800003, 73.9, 41.9, 74.0, 42.7, 74.200005);
((GeneralPath)shape).curveTo(43.7, 74.50001, 44.600002, 75.00001, 45.3, 75.8);
((GeneralPath)shape).curveTo(45.999996, 76.6, 46.6, 77.5, 47.0, 78.600006);
((GeneralPath)shape).curveTo(47.4, 79.70001, 47.6, 81.100006, 47.6, 82.700005);
((GeneralPath)shape).curveTo(47.6, 84.100006, 47.399998, 85.3, 47.1, 86.4);
((GeneralPath)shape).curveTo(46.699997, 87.6, 46.0, 88.700005, 45.199997, 89.4);
((GeneralPath)shape).curveTo(44.6, 90.0, 43.799995, 90.4, 42.699997, 90.8);
((GeneralPath)shape).curveTo(41.899998, 91.0, 40.899998, 91.200005, 39.6, 91.200005);
((GeneralPath)shape).lineTo(33.0, 91.200005);
((GeneralPath)shape).lineTo(33.0, 73.9);
((GeneralPath)shape).closePath();
((GeneralPath)shape).moveTo(36.5, 76.8);
((GeneralPath)shape).lineTo(36.5, 88.200005);
((GeneralPath)shape).lineTo(39.1, 88.200005);
((GeneralPath)shape).curveTo(40.1, 88.200005, 40.8, 88.100006, 41.199997, 88.00001);
((GeneralPath)shape).curveTo(41.799995, 87.90001, 42.199997, 87.600006, 42.6, 87.30001);
((GeneralPath)shape).curveTo(43.0, 87.000015, 43.3, 86.40001, 43.5, 85.60001);
((GeneralPath)shape).curveTo(43.7, 84.80001, 43.9, 83.80001, 43.9, 82.500015);
((GeneralPath)shape).curveTo(43.9, 81.20002, 43.800003, 80.20001, 43.5, 79.40002);
((GeneralPath)shape).curveTo(43.3, 78.70002, 42.9, 78.10001, 42.5, 77.70002);
((GeneralPath)shape).curveTo(42.1, 77.300026, 41.5, 77.00002, 40.9, 76.90002);
((GeneralPath)shape).curveTo(40.4, 76.80002, 39.5, 76.70002, 38.0, 76.70002);
((GeneralPath)shape).lineTo(36.5, 76.70002);
((GeneralPath)shape).closePath();
((GeneralPath)shape).moveTo(50.5, 73.9);
((GeneralPath)shape).lineTo(56.9, 73.9);
((GeneralPath)shape).curveTo(58.300003, 73.9, 59.4, 74.0, 60.2, 74.200005);
((GeneralPath)shape).curveTo(61.2, 74.50001, 62.100002, 75.00001, 62.8, 75.8);
((GeneralPath)shape).curveTo(63.5, 76.600006, 64.1, 77.5, 64.5, 78.600006);
((GeneralPath)shape).curveTo(64.9, 79.70001, 65.1, 81.100006, 65.1, 82.700005);
((GeneralPath)shape).curveTo(65.1, 84.100006, 64.9, 85.3, 64.6, 86.4);
((GeneralPath)shape).curveTo(64.2, 87.6, 63.5, 88.700005, 62.699997, 89.4);
((GeneralPath)shape).curveTo(62.1, 90.0, 61.299995, 90.4, 60.199997, 90.8);
((GeneralPath)shape).curveTo(59.399998, 91.0, 58.399998, 91.200005, 57.1, 91.200005);
((GeneralPath)shape).lineTo(50.5, 91.200005);
((GeneralPath)shape).lineTo(50.5, 73.9);
((GeneralPath)shape).closePath();
((GeneralPath)shape).moveTo(54.0, 76.8);
((GeneralPath)shape).lineTo(54.0, 88.200005);
((GeneralPath)shape).lineTo(56.6, 88.200005);
((GeneralPath)shape).curveTo(57.6, 88.200005, 58.3, 88.100006, 58.699997, 88.00001);
((GeneralPath)shape).curveTo(59.299995, 87.90001, 59.699997, 87.600006, 60.1, 87.30001);
((GeneralPath)shape).curveTo(60.5, 87.000015, 60.8, 86.40001, 61.0, 85.60001);
((GeneralPath)shape).curveTo(61.2, 84.80001, 61.4, 83.80001, 61.4, 82.500015);
((GeneralPath)shape).curveTo(61.4, 81.20002, 61.300003, 80.20001, 61.0, 79.40002);
((GeneralPath)shape).curveTo(60.8, 78.70002, 60.4, 78.10001, 60.0, 77.70002);
((GeneralPath)shape).curveTo(59.6, 77.30002, 59.0, 77.00002, 58.4, 76.90002);
((GeneralPath)shape).curveTo(57.9, 76.80002, 57.0, 76.70002, 55.5, 76.70002);
((GeneralPath)shape).lineTo(54.0, 76.70002);
((GeneralPath)shape).closePath();
paint = new Color(255, 255, 255, 255);
g.setPaint(paint);
g.fill(shape);
g.setTransform(defaultTransform__0_2);
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
AffineTransform defaultTransform__0_3 = g.getTransform();
g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f));
// _0_3
shape = new GeneralPath();
((GeneralPath)shape).moveTo(45.2, 1.0);
((GeneralPath)shape).lineTo(72.2, 27.7);
((GeneralPath)shape).lineTo(45.199997, 27.7);
((GeneralPath)shape).lineTo(45.199997, 1.0);
((GeneralPath)shape).closePath();
paint = new LinearGradientPaint(new Point2D.Double(45.275001525878906, 25.774999618530273), new Point2D.Double(58.775001525878906, 12.274999618530273), new float[] {0.0f,0.378f,0.515f,0.612f,0.69f,0.757f,0.817f,0.871f,0.921f,0.965f,1.0f}, new Color[] {new Color(249, 239, 246, 255),new Color(248, 237, 245, 255),new Color(243, 230, 241, 255),new Color(236, 219, 235, 255),new Color(227, 204, 226, 255),new Color(215, 184, 215, 255),new Color(202, 161, 201, 255),new Color(188, 136, 187, 255),new Color(174, 108, 171, 255),new Color(159, 77, 155, 255),new Color(147, 42, 142, 255)}, MultipleGradientPaint.CycleMethod.NO_CYCLE, MultipleGradientPaint.ColorSpaceType.SRGB, new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 2.0f));
g.setPaint(paint);
g.fill(shape);
g.setTransform(defaultTransform__0_3);
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
AffineTransform defaultTransform__0_4 = g.getTransform();
g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f));
// _0_4
shape = new GeneralPath();
((GeneralPath)shape).moveTo(45.2, 1.0);
((GeneralPath)shape).lineTo(72.2, 27.7);
((GeneralPath)shape).lineTo(45.199997, 27.7);
((GeneralPath)shape).lineTo(45.199997, 1.0);
((GeneralPath)shape).closePath();
paint = new Color(0, 0, 0, 0);
g.setPaint(paint);
g.fill(shape);
paint = new Color(219, 0, 123, 255);
stroke = new BasicStroke(2.0f,0,2,4.0f,null,0.0f);
shape = new GeneralPath();
((GeneralPath)shape).moveTo(45.2, 1.0);
((GeneralPath)shape).lineTo(72.2, 27.7);
((GeneralPath)shape).lineTo(45.199997, 27.7);
((GeneralPath)shape).lineTo(45.199997, 1.0);
((GeneralPath)shape).closePath();
g.setPaint(paint);
g.setStroke(stroke);
g.draw(shape);
g.setTransform(defaultTransform__0_4);
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
AffineTransform defaultTransform__0_5 = g.getTransform();
g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f));
// _0_5
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
AffineTransform defaultTransform__0_5_0 = g.getTransform();
g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f));
// _0_5_0
shape = new GeneralPath();
((GeneralPath)shape).moveTo(24.6, 61.3);
((GeneralPath)shape).lineTo(24.6, 34.5);
((GeneralPath)shape).lineTo(28.2, 34.5);
((GeneralPath)shape).lineTo(28.2, 61.3);
((GeneralPath)shape).lineTo(24.6, 61.3);
((GeneralPath)shape).closePath();
paint = new Color(219, 0, 123, 255);
g.setPaint(paint);
g.fill(shape);
g.setTransform(defaultTransform__0_5_0);
g.setTransform(defaultTransform__0_5);
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
AffineTransform defaultTransform__0_6 = g.getTransform();
g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f));
// _0_6
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
AffineTransform defaultTransform__0_6_0 = g.getTransform();
g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f));
// _0_6_0
paint = new Color(219, 0, 123, 255);
stroke = new BasicStroke(1.25f,0,0,10.0f,null,0.0f);
shape = new GeneralPath();
((GeneralPath)shape).moveTo(24.6, 61.3);
((GeneralPath)shape).lineTo(24.6, 34.5);
((GeneralPath)shape).lineTo(28.2, 34.5);
((GeneralPath)shape).lineTo(28.2, 61.3);
((GeneralPath)shape).lineTo(24.6, 61.3);
((GeneralPath)shape).closePath();
g.setPaint(paint);
g.setStroke(stroke);
g.draw(shape);
g.setTransform(defaultTransform__0_6_0);
g.setTransform(defaultTransform__0_6);
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
AffineTransform defaultTransform__0_7 = g.getTransform();
g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f));
// _0_7
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
AffineTransform defaultTransform__0_7_0 = g.getTransform();
g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f));
// _0_7_0
shape = new GeneralPath();
((GeneralPath)shape).moveTo(42.5, 61.7);
((GeneralPath)shape).curveTo(36.5, 61.7, 33.3, 58.0, 33.3, 52.5);
((GeneralPath)shape).curveTo(33.3, 47.0, 36.399998, 42.7, 42.5, 42.7);
((GeneralPath)shape).curveTo(43.6, 42.7, 44.6, 42.8, 45.7, 43.100002);
((GeneralPath)shape).lineTo(45.7, 34.5);
((GeneralPath)shape).lineTo(49.100002, 34.5);
((GeneralPath)shape).lineTo(49.100002, 60.5);
((GeneralPath)shape).curveTo(47.7, 61.1, 45.2, 61.7, 42.500004, 61.7);
((GeneralPath)shape).closePath();
((GeneralPath)shape).moveTo(45.7, 44.800003);
((GeneralPath)shape).curveTo(44.9, 44.600002, 43.9, 44.500004, 43.0, 44.500004);
((GeneralPath)shape).curveTo(38.2, 44.500004, 36.6, 48.200005, 36.6, 52.200005);
((GeneralPath)shape).curveTo(36.6, 56.600006, 38.3, 59.700005, 42.6, 59.700005);
((GeneralPath)shape).curveTo(44.0, 59.700005, 44.899998, 59.500004, 45.6, 59.200005);
((GeneralPath)shape).lineTo(45.6, 44.8);
((GeneralPath)shape).closePath();
paint = new Color(219, 0, 123, 255);
g.setPaint(paint);
g.fill(shape);
g.setTransform(defaultTransform__0_7_0);
g.setTransform(defaultTransform__0_7);
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
AffineTransform defaultTransform__0_8 = g.getTransform();
g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f));
// _0_8
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
AffineTransform defaultTransform__0_8_0 = g.getTransform();
g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f));
// _0_8_0
paint = new Color(219, 0, 123, 255);
stroke = new BasicStroke(1.25f,0,0,10.0f,null,0.0f);
shape = new GeneralPath();
((GeneralPath)shape).moveTo(42.5, 61.7);
((GeneralPath)shape).curveTo(36.5, 61.7, 33.3, 58.0, 33.3, 52.5);
((GeneralPath)shape).curveTo(33.3, 47.0, 36.399998, 42.7, 42.5, 42.7);
((GeneralPath)shape).curveTo(43.6, 42.7, 44.6, 42.8, 45.7, 43.100002);
((GeneralPath)shape).lineTo(45.7, 34.5);
((GeneralPath)shape).lineTo(49.100002, 34.5);
((GeneralPath)shape).lineTo(49.100002, 60.5);
((GeneralPath)shape).curveTo(47.7, 61.1, 45.2, 61.7, 42.500004, 61.7);
((GeneralPath)shape).closePath();
((GeneralPath)shape).moveTo(45.7, 44.800003);
((GeneralPath)shape).curveTo(44.9, 44.600002, 43.9, 44.500004, 43.0, 44.500004);
((GeneralPath)shape).curveTo(38.2, 44.500004, 36.6, 48.200005, 36.6, 52.200005);
((GeneralPath)shape).curveTo(36.6, 56.600006, 38.3, 59.700005, 42.6, 59.700005);
((GeneralPath)shape).curveTo(44.0, 59.700005, 44.899998, 59.500004, 45.6, 59.200005);
((GeneralPath)shape).lineTo(45.6, 44.8);
((GeneralPath)shape).closePath();
g.setPaint(paint);
g.setStroke(stroke);
g.draw(shape);
g.setTransform(defaultTransform__0_8_0);
g.setTransform(defaultTransform__0_8);
g.setTransform(defaultTransform__0);
g.setTransform(defaultTransform_);
}
/**
* Returns the X of the bounding box of the original SVG image.
*
* @return The X of the bounding box of the original SVG image.
*/
public static double getOrigX() {
return 0.13199996948242188;
}
/**
* Returns the Y of the bounding box of the original SVG image.
*
* @return The Y of the bounding box of the original SVG image.
*/
public static double getOrigY() {
return 0.0;
}
/**
* Returns the width of the bounding box of the original SVG image.
*
* @return The width of the bounding box of the original SVG image.
*/
public static double getOrigWidth() {
return 0.7400000095367432;
}
/**
* Returns the height of the bounding box of the original SVG image.
*
* @return The height of the bounding box of the original SVG image.
*/
public static double getOrigHeight() {
return 1.0;
}
/** The current width of this resizable icon. */
private int width;
/** The current height of this resizable icon. */
private int height;
/**
* Creates a new transcoded SVG image. This is marked as private to indicate that app
* code should be using the {@link #of(int, int)} method to obtain a pre-configured instance.
*/
private ext_indd() {
this.width = (int) getOrigWidth();
this.height = (int) getOrigHeight();
}
@Override
public int getIconHeight() {
return height;
}
@Override
public int getIconWidth() {
return width;
}
@Override
public void setDimension(Dimension newDimension) {
this.width = newDimension.width;
this.height = newDimension.height;
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g2d.translate(x, y);
double coef1 = (double) this.width / getOrigWidth();
double coef2 = (double) this.height / getOrigHeight();
double coef = Math.min(coef1, coef2);
g2d.clipRect(0, 0, this.width, this.height);
g2d.scale(coef, coef);
g2d.translate(-getOrigX(), -getOrigY());
if (coef1 != coef2) {
if (coef1 < coef2) {
int extraDy = (int) ((getOrigWidth() - getOrigHeight()) / 2.0);
g2d.translate(0, extraDy);
} else {
int extraDx = (int) ((getOrigHeight() - getOrigWidth()) / 2.0);
g2d.translate(extraDx, 0);
}
}
Graphics2D g2ForInner = (Graphics2D) g2d.create();
innerPaint(g2ForInner);
g2ForInner.dispose();
g2d.dispose();
}
/**
* Returns a new instance of this icon with specified dimensions.
*
* @param width Required width of the icon
* @param height Required height of the icon
* @return A new instance of this icon with specified dimensions.
*/
public static ResizableIcon of(int width, int height) {
ext_indd base = new ext_indd();
base.width = width;
base.height = height;
return base;
}
/**
* Returns a new {@link UIResource} instance of this icon with specified dimensions.
*
* @param width Required width of the icon
* @param height Required height of the icon
* @return A new {@link UIResource} instance of this icon with specified dimensions.
*/
public static ResizableIconUIResource uiResourceOf(int width, int height) {
ext_indd base = new ext_indd();
base.width = width;
base.height = height;
return new ResizableIconUIResource(base);
}
/**
* Returns a factory that returns instances of this icon on demand.
*
* @return Factory that returns instances of this icon on demand.
*/
public static Factory factory() {
return ext_indd::new;
}
}
|
4551ce2ca07fe693579c12b3c29c153039d4f62f
|
{
"blob_id": "4551ce2ca07fe693579c12b3c29c153039d4f62f",
"branch_name": "refs/heads/master",
"committer_date": "2020-03-06T03:27:26",
"content_id": "dc56fab753445ca7de5bb91e62c60c12f7c9363c",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "0f0b75d189bec77cde5f6870de0c746959665b28",
"extension": "java",
"filename": "ext_indd.java",
"fork_events_count": 0,
"gha_created_at": "2020-03-16T20:44:38",
"gha_event_created_at": "2020-03-16T20:44:39",
"gha_language": null,
"gha_license_id": "BSD-3-Clause",
"github_id": 247813010,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 19056,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/demos/flamingo-demo/src/main/java/org/pushingpixels/demo/flamingo/svg/filetypes/transcoded/ext_indd.java",
"provenance": "stack-edu-0029.json.gz:842691",
"repo_name": "vad-babushkin/radiance",
"revision_date": "2020-03-06T03:27:26",
"revision_id": "42d17c7018e009f16131e3ddc0e3e980f42770f6",
"snapshot_id": "08f21bf6102261a1bba6407bab738ab33baf9cd5",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/vad-babushkin/radiance/42d17c7018e009f16131e3ddc0e3e980f42770f6/demos/flamingo-demo/src/main/java/org/pushingpixels/demo/flamingo/svg/filetypes/transcoded/ext_indd.java",
"visit_date": "2021-03-27T22:28:06.062205",
"added": "2024-11-19T00:49:58.606273+00:00",
"created": "2020-03-06T03:27:26",
"int_score": 2,
"score": 2.21875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0047.json.gz"
}
|
<?php
// +----------------------------------------------------------------------+
// | PHP versions 4 and 5 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1998-2008 Manuel Lemos, Paul Cooper, Lorenzo Alberton |
// | All rights reserved. |
// +----------------------------------------------------------------------+
// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
// | API as well as database abstraction for PHP applications. |
// | This LICENSE is in the BSD license style. |
// | |
// | Redistribution and use in source and binary forms, with or without |
// | modification, are permitted provided that the following conditions |
// | are met: |
// | |
// | Redistributions of source code must retain the above copyright |
// | notice, this list of conditions and the following disclaimer. |
// | |
// | Redistributions in binary form must reproduce the above copyright |
// | notice, this list of conditions and the following disclaimer in the |
// | documentation and/or other materials provided with the distribution. |
// | |
// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
// | Lukas Smith nor the names of his contributors may be used to endorse |
// | or promote products derived from this software without specific prior|
// | written permission. |
// | |
// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
// | POSSIBILITY OF SUCH DAMAGE. |
// +----------------------------------------------------------------------+
// | Authors: Paul Cooper <pgc@ucecom.com> |
// | Lorenzo Alberton <l dot alberton at quipo dot it> |
// | Daniel Convissor <danielc@php.net> |
// +----------------------------------------------------------------------+
//
// $Id$
require_once dirname(__DIR__) . '/autoload.inc';
class Standard_ManagerTest extends Standard_Abstract {
//test table name (it is dynamically created/dropped)
public $table = 'newtable';
/**
* The non-standard helper
* @var Nonstandard_Base
*/
protected $nonstd;
/**
* Can not use setUp() because we are using a dataProvider to get multiple
* MDB2 objects per test.
*
* @param array $ci an associative array with two elements. The "dsn"
* element must contain an array of DSN information.
* The "options" element must be an array of connection
* options.
*/
protected function manualSetUp($ci) {
parent::manualSetUp($ci);
$this->nonstd = Nonstandard_Base::factory($this->db, $this);
$this->db->loadModule('Manager', null, true);
$this->fields = array(
'id' => array(
'type' => 'integer',
'unsigned' => true,
'notnull' => true,
'default' => 0,
),
'somename' => array(
'type' => 'text',
'length' => 12,
),
'somedescription' => array(
'type' => 'text',
'length' => 12,
),
'sex' => array(
'type' => 'text',
'length' => 1,
'default' => 'M',
),
);
$options = array();
if ('mysql' === mb_substr($this->db->phptype, 0, 5)) {
$options['type'] = 'innodb';
}
if (!$this->tableExists($this->table)) {
$result = $this->db->manager->createTable($this->table, $this->fields, $options);
$this->checkResultForErrors($result, 'createTable');
}
}
public function tearDown() {
if (!$this->db || MDB2::isError($this->db)) {
return;
}
if ($this->tableExists($this->table)) {
$this->db->manager->dropTable($this->table);
}
parent::tearDown();
}
/**
* @covers MDB2_Driver_Manager_Common::createTable()
* @covers MDB2_Driver_Manager_Common::listTables()
* @covers MDB2_Driver_Manager_Common::dropTable()
* @dataProvider provider
*/
public function testTableActions($ci) {
$this->manualSetUp($ci);
// Make sure it doesn't exist before trying to create it.
if ($this->methodExists($this->db->manager, 'dropTable')) {
$this->db->manager->dropTable($this->table);
} else {
$this->db->exec("DROP TABLE $this->table");
}
$action = 'createTable';
if (!$this->methodExists($this->db->manager, $action)) {
$this->markTestSkipped("Driver lacks $action() method");
}
$result = $this->db->manager->createTable($this->table, $this->fields);
$this->checkResultForErrors($result, $action);
$this->assertEquals(MDB2_OK, $result,
"$action did not return MDB2_OK");
$action = 'listTables';
if ($this->methodExists($this->db->manager, $action)) {
$result = $this->db->manager->listTables();
$this->checkResultForErrors($result, $action);
$this->assertContains($this->table, $result,
"Result of $action() does not contain expected value");
}
$action = 'dropTable';
if (!$this->methodExists($this->db->manager, $action)) {
$this->db->exec("DROP TABLE $this->table");
$this->markTestSkipped("Driver lacks $action() method");
}
$result = $this->db->manager->dropTable($this->table);
$this->checkResultForErrors($result, $action);
$this->assertEquals(MDB2_OK, $result,
"$action did not return MDB2_OK");
// Check that it's actually gone.
if ($this->tableExists($this->table)) {
$this->fail("dropTable() passed but the table still exists");
}
}
/**
* Create a sample table, test the new fields, and drop it.
* @dataProvider provider
*/
public function testCreateAutoIncrementTable($ci) {
$this->manualSetUp($ci);
if (!$this->methodExists($this->db->manager, 'createTable')) {
$this->markTestSkipped("Driver lacks createTable() method");
}
if ($this->tableExists($this->table)) {
$this->db->manager->dropTable($this->table);
}
$seq_name = $this->table;
if ('ibase' == $this->db->phptype) {
$seq_name .= '_id';
}
//remove existing PK sequence
$sequences = $this->db->manager->listSequences();
if (in_array($seq_name, $sequences)) {
$this->db->manager->dropSequence($seq_name);
}
$action = 'createTable';
$fields = $this->fields;
$fields['id']['autoincrement'] = true;
$result = $this->db->manager->createTable($this->table, $fields);
$this->checkResultForErrors($result, $action);
$this->assertEquals(MDB2_OK, $result,
"$action did not return MDB2_OK");
$query = 'INSERT INTO '.$this->db->quoteIdentifier($this->table, true);
$query.= ' (somename, somedescription)';
$query.= ' VALUES (:somename, :somedescription)';
$stmt = $this->db->prepare($query, array('text', 'text'), MDB2_PREPARE_MANIP);
$this->checkResultForErrors($stmt, 'prepare');
$values = array(
'somename' => 'foo',
'somedescription' => 'bar',
);
$rows = 5;
for ($i =0; $i < $rows; ++$i) {
$result = $stmt->execute($values);
$this->checkResultForErrors($result, 'execute');
}
$stmt->free();
$query = 'SELECT id FROM '.$this->table;
$data = $this->db->queryCol($query, 'integer');
$this->checkResultForErrors($data, 'queryCol');
for ($i=0; $i<$rows; ++$i) {
if (!isset($data[$i])) {
$this->fail('Error in data returned by select');
}
if ($data[$i] !== ($i+1)) {
$this->fail('Error executing autoincrementing insert');
}
}
}
/**
* @dataProvider provider
*/
public function testListTableFields($ci) {
$this->manualSetUp($ci);
if (!$this->methodExists($this->db->manager, 'listTableFields')) {
$this->markTestSkipped("Driver lacks listTableFields() method");
}
$this->assertEquals(
array_keys($this->fields),
$this->db->manager->listTableFields($this->table),
'Error creating table: incorrect fields'
);
}
/**
* @covers MDB2_Driver_Manager_Common::createIndex()
* @covers MDB2_Driver_Manager_Common::listTableIndexes()
* @covers MDB2_Driver_Manager_Common::dropIndex()
* @dataProvider provider
*/
public function testIndexActions($ci) {
$this->manualSetUp($ci);
$index = array(
'fields' => array(
'somename' => array(
'sorting' => 'ascending',
),
),
);
$name = 'simpleindex';
$action = 'createIndex';
if (!$this->methodExists($this->db->manager, $action)) {
$this->markTestSkipped("Driver lacks $action() method");
}
$result = $this->db->manager->createIndex($this->table, $name, $index);
$this->checkResultForErrors($result, $action);
$this->assertEquals(MDB2_OK, $result,
"$action did not return MDB2_OK");
$action = 'listTableIndexes';
if ($this->methodExists($this->db->manager, $action)) {
$result = $this->db->manager->listTableIndexes($this->table);
$this->checkResultForErrors($result, $action);
$this->assertContains($name, $result,
"Result of $action() does not contain expected value");
}
$action = 'dropIndex';
if (!$this->methodExists($this->db->manager, $action)) {
$this->markTestSkipped("Driver lacks $action() method");
}
$result = $this->db->manager->dropIndex($this->table, $name);
$this->checkResultForErrors($result, $action);
$this->assertEquals(MDB2_OK, $result,
"$action did not return MDB2_OK");
// Check that it's actually gone.
$action = 'listTableIndexes';
if ($this->methodExists($this->db->manager, $action)) {
$result = $this->db->manager->listTableIndexes($this->table);
$this->checkResultForErrors($result, $action);
$this->assertNotContains($name, $result,
"dropIndex() passed but the index is still there");
}
}
/**
* @dataProvider provider
*/
public function testCreatePrimaryKey($ci) {
$this->manualSetUp($ci);
if (!$this->methodExists($this->db->manager, 'createConstraint')) {
$this->markTestSkipped("Driver lacks createConstraint() method");
}
$constraint = array(
'fields' => array(
'id' => array(
'sorting' => 'ascending',
),
),
'primary' => true,
);
$name = 'pkindex';
$action = 'createConstraint';
if (!$this->methodExists($this->db->manager, $action)) {
$this->markTestSkipped("Driver lacks $action() method");
}
$result = $this->db->manager->createConstraint($this->table, $name, $constraint);
$this->checkResultForErrors($result, $action);
$this->assertEquals(MDB2_OK, $result,
"$action did not return MDB2_OK");
}
/**
* @covers MDB2_Driver_Manager_Common::createConstraint()
* @covers MDB2_Driver_Manager_Common::listTableConstraints()
* @covers MDB2_Driver_Manager_Common::dropConstraint()
* @dataProvider provider
*/
public function testConstraintActions($ci) {
$this->manualSetUp($ci);
$constraint = array(
'fields' => array(
'id' => array(
'sorting' => 'ascending',
),
),
'unique' => true,
);
$name = 'uniqueindex';
$action = 'createConstraint';
if (!$this->methodExists($this->db->manager, $action)) {
$this->markTestSkipped("Driver lacks $action() method");
}
// Make sure it doesn't exist before trying to create it.
$this->db->manager->dropConstraint($this->table, $name);
$result = $this->db->manager->createConstraint($this->table, $name, $constraint);
$this->checkResultForErrors($result, $action);
$this->assertEquals(MDB2_OK, $result,
"$action did not return MDB2_OK");
$action = 'listTableConstraints';
$result = $this->db->manager->listTableConstraints($this->table);
$this->checkResultForErrors($result, $action);
$this->assertContains($name, $result,
"Result of $action() does not contain expected value");
$action = 'dropConstraint';
$result = $this->db->manager->dropConstraint($this->table, $name);
$this->checkResultForErrors($result, $action);
$this->assertEquals(MDB2_OK, $result,
"$action did not return MDB2_OK");
// Check that it's actually gone.
$action = 'listTableConstraints';
$result = $this->db->manager->listTableConstraints($this->table);
$this->checkResultForErrors($result, $action);
$this->assertNotContains($name, $result,
"dropConstraint() passed but the constraint is still there");
}
/**
* MYSQL NOTE: If this test fails with native code 1005
* "Can't create table './peartest/#sql-540_2c871.frm' (errno: 150)"
* that means your server's default storage engine is MyISAM.
* Edit my.cnf to have "default-storage-engine = InnoDB"
*
* @dataProvider provider
*/
public function testCreateForeignKeyConstraint($ci) {
$this->manualSetUp($ci);
$constraint = array(
'fields' => array(
'id' => array(
'sorting' => 'ascending',
),
),
'foreign' => true,
'references' => array(
'table' => $this->table_users,
'fields' => array(
'user_id' => array(
'position' => 1,
),
),
),
'initiallydeferred' => false,
'deferrable' => false,
'match' => 'SIMPLE',
'onupdate' => 'CASCADE',
'ondelete' => 'CASCADE',
);
$name = 'fkconstraint';
$action = 'createConstraint';
if (!$this->methodExists($this->db->manager, $action)) {
$this->markTestSkipped("Driver lacks $action() method");
}
// Make sure it doesn't exist before trying to create it.
$this->db->manager->dropConstraint($this->table, $name);
$result = $this->db->manager->createConstraint($this->table, $name, $constraint);
$this->checkResultForErrors($result, $action);
$this->assertEquals(MDB2_OK, $result,
"$action did not return MDB2_OK");
$action = 'listTableConstraints';
$result = $this->db->manager->listTableConstraints($this->table);
$this->checkResultForErrors($result, $action);
$name_idx = $this->db->getIndexName($name);
$this->checkResultForErrors($name_idx, 'getIndexName');
$this->assertTrue(in_array($name_idx, $result)
|| in_array($name, $result),
"Result of $action() does not contain expected value");
//now check that it is enforced...
//insert a row in the primary table
$result = $this->db->exec('INSERT INTO ' . $this->table_users . ' (user_id) VALUES (1)');
$this->checkResultForErrors($result, 'exec');
//insert a row in the FK table with an id that references
//the newly inserted row on the primary table: should not fail
$query = 'INSERT INTO '.$this->db->quoteIdentifier($this->table, true)
.' ('.$this->db->quoteIdentifier('id', true).') VALUES (1)';
$result = $this->db->exec($query);
$this->checkResultForErrors($result, 'exec');
//try to insert a row into the FK table with an id that does not
//exist in the primary table: should fail
$query = 'INSERT INTO '.$this->db->quoteIdentifier($this->table, true)
.' ('.$this->db->quoteIdentifier('id', true).') VALUES (123456)';
$this->db->pushErrorHandling(PEAR_ERROR_RETURN);
$this->db->expectError('*');
$result = $this->db->exec($query);
$this->db->popExpect();
$this->db->popErrorHandling();
$this->assertInstanceOf('MDB2_Error', $result,
'Foreign Key constraint was not enforced for INSERT query');
$this->assertEquals(MDB2_ERROR_CONSTRAINT, $result->getCode(),
"Wrong error code. See full output for clues.\n"
. $result->getUserInfo());
//try to update the first row of the FK table with an id that does not
//exist in the primary table: should fail
$query = 'UPDATE '.$this->db->quoteIdentifier($this->table, true)
.' SET '.$this->db->quoteIdentifier('id', true).' = 123456 '
.' WHERE '.$this->db->quoteIdentifier('id', true).' = 1';
$this->db->expectError('*');
$result = $this->db->exec($query);
$this->db->popExpect();
$this->assertInstanceOf('MDB2_Error', $result,
'Foreign Key constraint was not enforced for UPDATE query');
$this->assertEquals(MDB2_ERROR_CONSTRAINT, $result->getCode(),
"Wrong error code. See full output for clues.\n"
. $result->getUserInfo());
$numrows_query = 'SELECT COUNT(*) FROM '. $this->db->quoteIdentifier($this->table, true);
$numrows = $this->db->queryOne($numrows_query, 'integer');
$this->assertEquals(1, $numrows, 'Invalid number of rows in the FK table');
//update the PK value of the primary table: the new value should be
//propagated to the FK table (ON UPDATE CASCADE)
$result = $this->db->exec('UPDATE ' . $this->table_users . ' SET user_id = 2');
$this->checkResultForErrors($result, 'exec');
$numrows = $this->db->queryOne($numrows_query, 'integer');
$this->assertEquals(1, $numrows, 'Invalid number of rows in the FK table');
$query = 'SELECT id FROM '.$this->db->quoteIdentifier($this->table, true);
$newvalue = $this->db->queryOne($query, 'integer');
$this->assertEquals(2, $newvalue, 'The value of the FK field was not updated (CASCADE failed)');
//delete the row of the primary table: the row in the FK table should be
//deleted automatically (ON DELETE CASCADE)
$result = $this->db->exec('DELETE FROM ' . $this->table_users);
$this->checkResultForErrors($result, 'exec');
$numrows = $this->db->queryOne($numrows_query, 'integer');
$this->assertEquals(0, $numrows, 'Invalid number of rows in the FK table (CASCADE failed)');
$action = 'dropConstraint';
$result = $this->db->manager->dropConstraint($this->table, $name);
$this->checkResultForErrors($result, $action);
$this->assertEquals(MDB2_OK, $result,
"$action did not return MDB2_OK");
}
/**
* @dataProvider provider
*/
public function testDropPrimaryKey($ci) {
$this->manualSetUp($ci);
if (!$this->methodExists($this->db->manager, 'dropConstraint')) {
$this->markTestSkipped("Driver lacks dropConstraint() method");
}
$index = array(
'fields' => array(
'id' => array(
'sorting' => 'ascending',
),
),
'primary' => true,
);
$name = 'pkindex';
$action = 'createConstraint';
$result = $this->db->manager->createConstraint($this->table, $name, $index);
$this->checkResultForErrors($result, $action);
$this->assertEquals(MDB2_OK, $result,
"$action did not return MDB2_OK");
$action = 'dropConstraint';
$result = $this->db->manager->dropConstraint($this->table, $name, true);
$this->checkResultForErrors($result, $action);
$this->assertEquals(MDB2_OK, $result,
"$action did not return MDB2_OK");
}
/**
* @dataProvider provider
*/
public function testListDatabases($ci) {
$this->manualSetUp($ci);
$action = 'listDatabases';
if (!$this->methodExists($this->db->manager, $action)) {
$this->markTestSkipped("Driver lacks $action() method");
}
$result = $this->db->manager->listDatabases();
$this->checkResultForErrors($result, $action);
$this->assertTrue(in_array(mb_strtolower($this->database), $result), 'Error listing databases');
}
/**
* @dataProvider provider
*/
public function testAlterTable($ci) {
$this->manualSetUp($ci);
$newer = 'newertable';
if ($this->tableExists($newer)) {
$this->db->manager->dropTable($newer);
}
$changes = array(
'add' => array(
'quota' => array(
'type' => 'integer',
'unsigned' => 1,
),
'note' => array(
'type' => 'text',
'length' => '20',
),
),
'rename' => array(
'sex' => array(
'name' => 'gender',
'definition' => array(
'type' => 'text',
'length' => 1,
'default' => 'M',
),
),
),
'change' => array(
'id' => array(
'unsigned' => false,
'definition' => array(
'type' => 'integer',
'notnull' => false,
'default' => 0,
),
),
'somename' => array(
'length' => '20',
'definition' => array(
'type' => 'text',
'length' => 20,
),
)
),
'remove' => array(
'somedescription' => array(),
),
'name' => $newer,
);
$action = 'alterTable';
if (!$this->methodExists($this->db->manager, $action)) {
$this->markTestSkipped("Driver lacks $action() method");
}
$this->db->expectError(MDB2_ERROR_CANNOT_ALTER);
$result = $this->db->manager->alterTable($this->table, $changes, true);
$this->db->popExpect();
$this->checkResultForErrors($result, $action);
$this->assertEquals(MDB2_OK, $result,
"$action did not return MDB2_OK");
$result = $this->db->manager->alterTable($this->table, $changes, false);
$this->checkResultForErrors($result, $action);
$this->assertEquals(MDB2_OK, $result,
"$action did not return MDB2_OK");
}
/**
* @dataProvider provider
*/
public function testAlterTable2($ci) {
$this->manualSetUp($ci);
$newer = 'newertable2';
if ($this->tableExists($newer)) {
$this->db->manager->dropTable($newer);
}
$changes_all = array(
'add' => array(
'quota' => array(
'type' => 'integer',
'unsigned' => 1,
),
),
'rename' => array(
'sex' => array(
'name' => 'gender',
'definition' => array(
'type' => 'text',
'length' => 1,
'default' => 'M',
),
),
),
'change' => array(
'somename' => array(
'length' => '20',
'definition' => array(
'type' => 'text',
'length' => 20,
),
)
),
'remove' => array(
'somedescription' => array(),
),
'name' => $newer,
);
$action = 'alterTable';
if (!$this->methodExists($this->db->manager, $action)) {
$this->markTestSkipped("Driver lacks $action() method");
}
foreach ($changes_all as $type => $change) {
$changes = array($type => $change);
$this->db->expectError(MDB2_ERROR_CANNOT_ALTER);
$result = $this->db->manager->alterTable($this->table, $changes, true);
$this->db->popExpect();
$this->checkResultForErrors($result, $action);
$this->assertEquals(MDB2_OK, $result,
"$action did not return MDB2_OK");
$result = $this->db->manager->alterTable($this->table, $changes, false);
$this->checkResultForErrors($result, $action);
$this->assertEquals(MDB2_OK, $result,
"$action did not return MDB2_OK");
switch ($type) {
case 'add':
$altered_table_fields = $this->db->manager->listTableFields($this->table);
$this->checkResultForErrors($altered_table_fields, 'listTableFields');
foreach ($change as $newfield => $dummy) {
$this->assertContains($newfield, $altered_table_fields,
"Field '$newfield' was not added");
}
break;
case 'rename':
$altered_table_fields = $this->db->manager->listTableFields($this->table);
$this->checkResultForErrors($altered_table_fields, 'listTableFields');
foreach ($change as $oldfield => $newfield) {
$this->assertNotContains($oldfield, $altered_table_fields,
"Field '$oldfield' was not renamed");
$this->assertContains($newfield['name'], $altered_table_fields,
"While '$oldfield' is gone, '{$newfield['name']}' is not there");
}
break;
case 'change':
break;
case 'remove':
$altered_table_fields = $this->db->manager->listTableFields($this->table);
$this->checkResultForErrors($altered_table_fields, 'listTableFields');
foreach ($change as $newfield => $dummy) {
$this->assertNotContains($newfield, $altered_table_fields,
"Field '$oldfield' was not removed");
}
break;
case 'name':
if ($this->tableExists($newer)) {
$this->db->manager->dropTable($newer);
} else {
$this->fail('Error: table "'.$this->table.'" not renamed');
}
break;
}
}
}
/**
* @dataProvider provider
*/
public function testTruncateTable($ci) {
$this->manualSetUp($ci);
if (!$this->methodExists($this->db->manager, 'truncateTable')) {
$this->markTestSkipped("Driver lacks truncateTable() method");
}
$query = 'INSERT INTO '.$this->table;
$query.= ' (id, somename, somedescription)';
$query.= ' VALUES (:id, :somename, :somedescription)';
$stmt = $this->db->prepare($query, array('integer', 'text', 'text'), MDB2_PREPARE_MANIP);
$this->checkResultForErrors($stmt, 'prepare');
$rows = 5;
for ($i=1; $i<=$rows; ++$i) {
$values = array(
'id' => $i,
'somename' => 'foo'.$i,
'somedescription' => 'bar'.$i,
);
$result = $stmt->execute($values);
$this->checkResultForErrors($result, 'execute');
}
$stmt->free();
$count = $this->db->queryOne('SELECT COUNT(*) FROM '.$this->table, 'integer');
$this->checkResultForErrors($count, 'queryOne');
$this->assertEquals($rows, $count, 'Error: invalid number of rows returned');
$action = 'truncateTable';
$result = $this->db->manager->truncateTable($this->table);
$this->checkResultForErrors($result, $action);
$this->assertEquals(MDB2_OK, $result,
"$action did not return MDB2_OK");
$count = $this->db->queryOne('SELECT COUNT(*) FROM '.$this->table, 'integer');
$this->checkResultForErrors($count, 'queryOne');
$this->assertEquals(0, $count, 'Error: invalid number of rows returned');
}
/**
* @dataProvider provider
*/
public function testListTablesNoTable($ci) {
$this->manualSetUp($ci);
if (!$this->methodExists($this->db->manager, 'listTables')) {
$this->markTestSkipped("Driver lacks listTables() method");
}
$result = $this->db->manager->dropTable($this->table);
$this->assertFalse($this->tableExists($this->table), 'Error listing tables');
}
/**
* @covers MDB2_Driver_Manager_Common::createSequence()
* @covers MDB2_Driver_Manager_Common::listSequences()
* @covers MDB2_Driver_Manager_Common::dropSequence()
* @dataProvider provider
*/
public function testSequences($ci) {
$this->manualSetUp($ci);
$name = 'testsequence';
$action = 'createSequence';
if (!$this->methodExists($this->db->manager, $action)) {
$this->markTestSkipped("Driver lacks $action() method");
}
// Make sure it doesn't exist before trying to create it.
$this->db->manager->dropSequence($name);
$result = $this->db->manager->createSequence($name);
$this->checkResultForErrors($result, $action);
$this->assertEquals(MDB2_OK, $result,
"$action did not return MDB2_OK");
$action = 'listSequences';
$result = $this->db->manager->listSequences();
$this->checkResultForErrors($result, $action);
$this->assertContains($name, $result,
"Result of $action() does not contain expected value");
$action = 'dropSequence';
$result = $this->db->manager->dropSequence($name);
$this->checkResultForErrors($result, $action);
$this->assertEquals(MDB2_OK, $result,
"$action did not return MDB2_OK");
// Check that it's actually gone.
$action = 'listSequences';
$result = $this->db->manager->listSequences();
$this->checkResultForErrors($result, $action);
$this->assertNotContains($name, $result,
"dropSequence() passed but the sequence is still there");
}
/**
* @covers MDB2_Driver_Manager_Common::listTableTriggers()
* @dataProvider provider
*/
public function testListTableTriggers($ci) {
$this->manualSetUp($ci);
if (!$this->nonstd) {
$this->markTestSkipped('No Nonstandard Helper for this phptype.');
}
$name = 'test_newtrigger';
/*
* Have test suite helper functions setup the environment.
*/
$this->nonstd->dropTrigger($name, $this->table);
$result = $this->nonstd->createTrigger($name, $this->table);
$this->checkResultForErrors($result, 'create trigger helper');
/*
* The actual tests.
*/
$action = 'listTableTriggers';
$result = $this->db->manager->listTableTriggers($this->table);
$this->checkResultForErrors($result, $action);
$this->assertContains($name, $result,
"Result of $action() does not contain expected value");
$action = 'listTableTriggers on non-existant table';
$result = $this->db->manager->listTableTriggers('fake_table');
$this->checkResultForErrors($result, $action);
$this->assertNotContains($name, $result,
"$action should not contain this view");
/*
* Have test suite helper functions clean up the environment.
*/
$result = $this->nonstd->dropTrigger($name, $this->table);
$this->checkResultForErrors($result, 'drop trigger helper');
}
/**
* @covers MDB2_Driver_Manager_Common::listTableViews()
* @dataProvider provider
*/
public function testListTableViews($ci) {
$this->manualSetUp($ci);
if (!$this->nonstd) {
$this->markTestSkipped('No Nonstandard Helper for this phptype.');
}
$name = 'test_newview';
/*
* Have test suite helper functions setup the environment.
*/
$this->nonstd->dropView($name);
$result = $this->nonstd->createView($name, $this->table);
$this->checkResultForErrors($result, 'create view helper');
/*
* The actual tests.
*/
$action = 'listTableViews';
$result = $this->db->manager->listTableViews($this->table);
$this->checkResultForErrors($result, $action);
$this->assertContains($name, $result,
"Result of $action() does not contain expected value");
$action = 'listTableViews on non-existant table';
$result = $this->db->manager->listTableViews('fake_table');
$this->checkResultForErrors($result, $action);
$this->assertNotContains($name, $result,
"$action should not contain this view");
/*
* Have test suite helper functions clean up the environment.
*/
$result = $this->nonstd->dropView($name);
$this->checkResultForErrors($result, 'drop view helper');
}
/**
* Test listUsers()
* @dataProvider provider
*/
public function testListUsers($ci) {
$this->manualSetUp($ci);
$action = 'listUsers';
$result = $this->db->manager->listUsers();
$this->checkResultForErrors($result, $action);
$result = array_map('mb_strtolower', $result);
$this->assertContains(mb_strtolower($this->db->dsn['username']), $result,
"Result of $action() does not contain expected value");
}
/**
* @covers MDB2_Driver_Manager_Common::listFunctions()
* @dataProvider provider
*/
public function testFunctionActions($ci) {
$this->manualSetUp($ci);
if (!$this->nonstd) {
$this->markTestSkipped('No Nonstandard Helper for this phptype.');
}
$name = 'test_add';
/*
* Have test suite helper functions setup the environment.
*/
$this->nonstd->dropFunction($name);
$this->db->pushErrorHandling(PEAR_ERROR_RETURN);
$this->db->expectError('*');
$result = $this->nonstd->createFunction($name);
$this->db->popExpect();
$this->db->popErrorHandling();
$this->checkResultForErrors($result, 'crete function helper');
/*
* The actual tests.
*/
$action = 'listFunctions';
$result = $this->db->manager->listFunctions();
$this->checkResultForErrors($result, $action);
$this->assertContains($name, $result,
"Result of $action() does not contain expected value");
/*
* Have test suite helper functions clean up the environment.
*/
$result = $this->nonstd->dropFunction($name);
$this->checkResultForErrors($result, 'drop function helper');
}
/**
* @covers MDB2_Driver_Manager_Common::createDatabase()
* @covers MDB2_Driver_Manager_Common::alterDatabase()
* @covers MDB2_Driver_Manager_Common::listDatabases()
* @covers MDB2_Driver_Manager_Common::dropDatabase()
* @dataProvider provider
*/
public function testCrudDatabase($ci) {
$this->manualSetUp($ci);
$name = 'mdb2_test_newdb';
$rename = $name . '_renamed';
$unlink = false;
switch ($this->db->phptype) {
case 'sqlite':
$name = tempnam(sys_get_temp_dir(), $name);
$rename = $name . '_renamed';
unlink($name);
$unlink = true;
break;
}
$options = array(
'charset' => 'UTF8',
'collation' => 'utf8_bin',
);
$changes = array(
'name' => $rename,
'charset' => 'UTF8',
);
if ('pgsql' === mb_substr($this->db->phptype, 0, 5)) {
$options['charset'] = 'WIN1252';
}
if ('mssql' === mb_substr($this->db->phptype, 0, 5)) {
$options['collation'] = 'WIN1252';
$options['collation'] = 'Latin1_General_BIN';
}
$action = 'createDatabase';
$result = $this->db->manager->createDatabase($name, $options);
$this->checkResultForErrors($result, $action);
$this->assertEquals(MDB2_OK, $result,
"$action did not return MDB2_OK");
$action = 'listDatabases';
$result = $this->db->manager->listDatabases();
$this->checkResultForErrors($result, $action);
$this->assertContains($name, $result,
"Result of $action() does not contain expected value");
$action = 'alterDatabase';
$result = $this->db->manager->alterDatabase($name, $changes);
$this->checkResultForErrors($result, $action);
$this->assertEquals(MDB2_OK, $result,
"$action did not return MDB2_OK");
$action = 'listDatabases';
$result = $this->db->manager->listDatabases();
$this->checkResultForErrors($result, $action);
if (!in_array($rename, $result)) {
$this->db->manager->dropDatabase($name);
$this->fail('Error: could not find renamed database');
}
$action = 'dropDatabase';
$result = $this->db->manager->dropDatabase($rename);
$this->checkResultForErrors($result, $action);
$this->assertEquals(MDB2_OK, $result,
"$action did not return MDB2_OK");
// Check that it's actually gone.
$action = 'listDatabases';
$result = $this->db->manager->listDatabases();
$this->checkResultForErrors($result, $action);
$this->assertNotContains($rename, $result,
"dropDatabase() passed but the database is still there");
}
/**
* Test vacuum
* @dataProvider provider
*/
public function testVacuum($ci) {
$this->manualSetUp($ci);
$action = 'vacuum table';
$result = $this->db->manager->vacuum($this->table);
$this->checkResultForErrors($result, $action);
$this->assertEquals(MDB2_OK, $result,
"$action did not return MDB2_OK");
$action = 'vacuum and analyze table';
$options = array(
'analyze' => true,
'full' => true,
'freeze' => true,
);
$result = $this->db->manager->vacuum($this->table, $options);
$this->checkResultForErrors($result, $action);
$this->assertEquals(MDB2_OK, $result,
"$action did not return MDB2_OK");
$action = 'vacuum all tables';
$result = $this->db->manager->vacuum();
$this->checkResultForErrors($result, $action);
$this->assertEquals(MDB2_OK, $result,
"$action did not return MDB2_OK");
}
}
|
797691352a33ad0958ca4bbf881fc3c83a263c14
|
{
"blob_id": "797691352a33ad0958ca4bbf881fc3c83a263c14",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-29T02:10:29",
"content_id": "b2e1337d84e3d4e20683287a03af33e9395ea2ca",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "9fd0bd87a77d2947f59b11d7dbe7e2977a18a92c",
"extension": "php",
"filename": "ManagerTest.php",
"fork_events_count": 11,
"gha_created_at": "2016-01-08T21:27:39",
"gha_event_created_at": "2020-09-29T02:10:50",
"gha_language": "PHP",
"gha_license_id": "NOASSERTION",
"github_id": 49297783,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 41728,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/tests/Standard/ManagerTest.php",
"provenance": "stack-edu-0048.json.gz:162333",
"repo_name": "silverorange/MDB2",
"revision_date": "2020-09-29T02:10:29",
"revision_id": "28df9a5cfa10cdc1b8a2d44fda454e0f48dfb30c",
"snapshot_id": "12ed7288f8aa978b9aa87bb5bcdc16149d72b5ba",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/silverorange/MDB2/28df9a5cfa10cdc1b8a2d44fda454e0f48dfb30c/tests/Standard/ManagerTest.php",
"visit_date": "2020-12-25T15:29:24.049817",
"added": "2024-11-18T22:30:11.404405+00:00",
"created": "2020-09-29T02:10:29",
"int_score": 2,
"score": 2.21875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0066.json.gz"
}
|
# rfc-js-from-import
A proposal for JavaScript to support inverted `import * from *` syntax as `from * import *`, so that autocompletion in editors works better since they will be able to suggest names of exported identifiers in the targeted module, which would now be known upfront.
```js
from 'my-module' import MyModule, { AnotherMethod }
from 'other-module' import { OtherMethod }
// ...
```
or:
```js
import from 'my-module' MyModule, { AnotherMethod }
import from 'other-module' { OtherMethod }
// ...
```
or:
```js
import from 'my-module' as MyModule, { AnotherMethod }
import from 'other-module' as { OtherMethod }
// ...
```
An editor could allow autocompletion after only:
```js
from 'my-module' import { ...
```
or:
```js
from 'my-module' import { O...
```
## Related
* https://github.com/AndersDJohnson/rfc-js-import-multiple
* https://github.com/AndersDJohnson/rfc-js-import-infer-identifier
* https://github.com/AndersDJohnson/rfc-js-import-object-alignment
* https://github.com/AndersDJohnson/rfc-js-import-composition
|
1218ddc084bb568752b1950a4264071f6b358afe
|
{
"blob_id": "1218ddc084bb568752b1950a4264071f6b358afe",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-24T14:32:51",
"content_id": "bb101b4cf89e32375c3f9b19702e40d738d32b66",
"detected_licenses": [
"MIT"
],
"directory_id": "e9687e669dd9e7db559f8e447c0b2c708627cf98",
"extension": "md",
"filename": "README.md",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 109522949,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1048,
"license": "MIT",
"license_type": "permissive",
"path": "/README.md",
"provenance": "stack-edu-markdown-0007.json.gz:50535",
"repo_name": "AndersDJohnson/rfc-js-from-import",
"revision_date": "2020-12-24T14:32:51",
"revision_id": "7955a43c230cc1f3a080b08bb3e3759c923f1dfa",
"snapshot_id": "5c2a02ce50978e89afd2551012564a8cc440b882",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/AndersDJohnson/rfc-js-from-import/7955a43c230cc1f3a080b08bb3e3759c923f1dfa/README.md",
"visit_date": "2023-02-03T17:15:44.936992",
"added": "2024-11-18T19:17:06.555272+00:00",
"created": "2020-12-24T14:32:51",
"int_score": 3,
"score": 3.203125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0007.json.gz"
}
|
//
// OtherUserProfileViewController.swift
// sway
//
// Created by Hina Sakazaki on 10/28/15.
// Copyright © 2015 VCH. All rights reserved.
//
import UIKit
import CoreData
protocol OtherUserProfileViewControllerDelegate {
var detailSegue: String {get}
func load(onCompletion: () -> ())
func rowCount() -> Int
func setComposition(cell: TuneCell, indexPath: NSIndexPath)
func deleteComposition(indexPath: NSIndexPath)
func prepareForSegue(destinationViewController: UIViewController, indexPath: NSIndexPath)
}
class OtherUserProfileViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var userName: UILabel!
@IBOutlet weak var userProfileImage: UIImageView!
@IBOutlet weak var userHandle: UILabel!
@IBOutlet weak var userDescription: UILabel!
@IBOutlet weak var followButton: UIButton!
@IBOutlet weak var tuneCell: TuneCell!
var selectedIndex: NSIndexPath?
var tunes : [Tune] = []
@IBOutlet weak var tableView: UITableView!
var user : User! {
didSet{
}
}
override func viewDidLoad() {
tableView.delegate = self
tableView.dataSource = self
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 160.0
tableView.registerNib(UINib(nibName: "TuneCell", bundle: nil), forCellReuseIdentifier: "TuneCell")
super.viewDidLoad()
if (user != nil) {
self.userName.text = user.name
if let profileImageUrl = user.profileImageURL {
let imageData = NSData(contentsOfURL: NSURL(string: profileImageUrl)!)
let profileImage = UIImage(data:imageData!)
userProfileImage.image = profileImage
userProfileImage.layer.cornerRadius = 36.5
userProfileImage.clipsToBounds = true
}
if (user.screenName != nil){
self.userHandle.text = "@\(user.screenName!)"
} else {
self.userHandle.text = ""
}
self.userDescription.text = user.tagLine
load({ () -> () in
//do stuff
self.tableView.reloadData()
})
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func load(onCompletion: () -> ()) {
ParseAPI.sharedInstance.getRecordingsForUserId(user.userId!) { (tunes: [Tune]?, error: NSError?) -> Void in
dispatch_async(dispatch_get_main_queue(), {
if tunes != nil {
self.tunes = tunes!
print(tunes)
onCompletion()
}
if (error != nil) {
print("Error in getting user's recordings \(error)")
}
})
}
}
// private func delegate() -> UserProfileViewControllerDelegate {
// return delegates[typeControl.selectedSegmentIndex]
// }
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (tunes.count > 0) {
return tunes.count
}
return 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("TuneCell", forIndexPath: indexPath) as! TuneCell
cell.setTune(tunes[indexPath.row])
//cell.userImageView.hidden = true
//cell.collaboratorImageView.hidden = true
cell.accessoryType = UITableViewCellAccessoryType.None
return cell
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
selectedIndex = indexPath
performSegueWithIdentifier("tuneToDetail", sender: indexPath)
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if let segueId = segue.identifier {
if segueId == "tuneToDetail" {
if let _ = segue.destinationViewController as? UINavigationController {
let destinationNavigationController = segue.destinationViewController as! UINavigationController
if let tuneDetailViewController = destinationNavigationController.topViewController! as? TrackDetailViewController {
tuneDetailViewController.tune = tunes[sender!.row]
}
} else {
if let tuneDetailViewController = segue.destinationViewController as? TrackDetailViewController {
tuneDetailViewController.tune = tunes[sender!.row]
}
}
}
}
}
}
|
4948d9d51508e31842e93f1111f29817c9afde18
|
{
"blob_id": "4948d9d51508e31842e93f1111f29817c9afde18",
"branch_name": "refs/heads/master",
"committer_date": "2015-11-15T06:51:44",
"content_id": "b738cf974039e9a8f49f1a6d648ac6c592047e02",
"detected_licenses": [
"MIT"
],
"directory_id": "05f61378fbac03e6367881624ab1a0e868a9b4de",
"extension": "swift",
"filename": "OtherUserProfileViewController.swift",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Swift",
"length_bytes": 5444,
"license": "MIT",
"license_type": "permissive",
"path": "/sway/OtherUserProfileViewController.swift",
"provenance": "stack-edu-0072.json.gz:144651",
"repo_name": "hinasakazaki/sway",
"revision_date": "2015-11-15T06:51:44",
"revision_id": "75a5ad903e427b61cf2940b5c519da6a7eb26192",
"snapshot_id": "6e670dbfe10ef40849909ae4ae4823a814d86602",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hinasakazaki/sway/75a5ad903e427b61cf2940b5c519da6a7eb26192/sway/OtherUserProfileViewController.swift",
"visit_date": "2021-05-30T23:29:25.873180",
"added": "2024-11-18T21:28:18.245047+00:00",
"created": "2015-11-15T06:51:44",
"int_score": 2,
"score": 2.3125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0090.json.gz"
}
|
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using UserServiceAccount.Domain.Entities;
namespace UserServiceAccount.Data.Mappings
{
public class UserMap : IEntityTypeConfiguration<UserEntity>
{
public void Configure(EntityTypeBuilder<UserEntity> builder)
{
builder.ToTable("Users");
builder.HasKey(e => e.Id);
builder.Property(e => e.UserName)
.IsRequired()
.HasColumnName("UserName");
builder.Property(e => e.Password)
.IsRequired()
.HasColumnName("Password");
}
}
}
|
01ccb9e43ba06db976e1e78d75852ae637222d7f
|
{
"blob_id": "01ccb9e43ba06db976e1e78d75852ae637222d7f",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-29T01:27:42",
"content_id": "de1afdd57ad7ab953e4e54603c7e314c10872b68",
"detected_licenses": [
"MIT"
],
"directory_id": "635bc39cb1e3281023402ef45fac1e4b0d65bb89",
"extension": "cs",
"filename": "UserMap.cs",
"fork_events_count": 0,
"gha_created_at": "2020-07-28T00:07:41",
"gha_event_created_at": "2023-01-06T20:33:42",
"gha_language": "C#",
"gha_license_id": "MIT",
"github_id": 283048524,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 670,
"license": "MIT",
"license_type": "permissive",
"path": "/src/Infra/Data/UserServiceAccount.Data/Mappings/UserMap.cs",
"provenance": "stack-edu-0011.json.gz:134907",
"repo_name": "leovene/userserviceaccount",
"revision_date": "2020-07-29T01:27:42",
"revision_id": "87a0c1721f9cabd6ac0126f94bb104d813666725",
"snapshot_id": "12e6c132ef7385b2f1324844b1890ece66dc675a",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/leovene/userserviceaccount/87a0c1721f9cabd6ac0126f94bb104d813666725/src/Infra/Data/UserServiceAccount.Data/Mappings/UserMap.cs",
"visit_date": "2023-01-20T06:36:26.424493",
"added": "2024-11-19T02:23:52.063373+00:00",
"created": "2020-07-29T01:27:42",
"int_score": 2,
"score": 2.5,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0029.json.gz"
}
|
import PySimpleGUI as psg
class PrimaryUI(psg.Window):
GENERATE = 'Generate'
def __init__(self):
super().__init__('WordCloud Generator')
self.txt_words = psg.Multiline(size=(25,5), do_not_clear=True)
self.btn_generator = psg.Button(self.GENERATE)
self.Layout(
[
[psg.Text('Input')],
[self.txt_words],
[self.btn_generator]
]
)
def start(self, generator_callback):
while True:
event, values = self.Read()
print(event)
if event is None: break
elif event == self.GENERATE:
# Generate Word Cloud
input_text = self.txt_words.Get()
generator_callback(input_text)
self.Close()
|
93f1a89bc7096fcfc3c9b4e1051827d9ef1561d6
|
{
"blob_id": "93f1a89bc7096fcfc3c9b4e1051827d9ef1561d6",
"branch_name": "refs/heads/master",
"committer_date": "2019-02-06T00:57:08",
"content_id": "1358c8132e4e43691b9370a940ad2cc9ac8b38cf",
"detected_licenses": [
"MIT"
],
"directory_id": "bdc057f869391d2ff0a4632053f6aec3fc76a09e",
"extension": "py",
"filename": "primary_ui.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 169334435,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 822,
"license": "MIT",
"license_type": "permissive",
"path": "/wordcloud_generator/primary_ui.py",
"provenance": "stack-edu-0064.json.gz:622271",
"repo_name": "William-Lake/WordCloudGenerator",
"revision_date": "2019-02-06T00:57:08",
"revision_id": "6090d9b281128c8b4e50fedc5602d2590fd77da5",
"snapshot_id": "7ea2cc21fe4f01f1f49f5d4aefec64043d8e0dfe",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/William-Lake/WordCloudGenerator/6090d9b281128c8b4e50fedc5602d2590fd77da5/wordcloud_generator/primary_ui.py",
"visit_date": "2020-04-21T05:13:54.296742",
"added": "2024-11-19T00:50:15.138284+00:00",
"created": "2019-02-06T00:57:08",
"int_score": 3,
"score": 3.109375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0082.json.gz"
}
|
package leetcode;
import java.util.HashMap;
import java.util.Map;
/**
* https://leetcode.com/problems/can-i-win/
*/
public class Problem464 {
public boolean canIWin(int maxChoosableInteger, int desiredTotal) {
if (maxChoosableInteger >= desiredTotal) {
return true;
}
int sum = 0;
for (int i = 1; i <= maxChoosableInteger; i++) {
sum += i;
}
if (sum < desiredTotal) {
return false;
}
return canIWin(0, maxChoosableInteger, desiredTotal, 0, Player.P2,
new HashMap<>()) == Player.P1;
}
private enum Player {
P1, P2
}
private static Player canIWin(int bits, int max, int desired, int accu,
Player player, Map<Integer, Player> memo) {
if (accu >= desired) {
return player;
}
if (memo.containsKey(bits)) {
return memo.get(bits);
}
Player win = player;
for (int num = 0; num < max; num++) {
if ((bits & (1 << num)) == (1 << num)) {
continue;
}
bits |= 1 << num;
Player nextPlayer = (player == Player.P1) ? Player.P2 : Player.P1;
if (player == Player.P1) {
win = canIWin(bits, max, desired, accu + num + 1, nextPlayer, memo);
if (win == Player.P2) {
bits &= ~(1 << num);
break;
}
} else if (player == Player.P2) {
win = canIWin(bits, max, desired, accu + num + 1, nextPlayer, memo);
if (win == Player.P1) {
bits &= ~(1 << num);
break;
}
}
bits &= ~(1 << num);
}
memo.put(bits, win);
return win;
}
}
|
5208e24f211a7042767ee3421e55eba758a08a1d
|
{
"blob_id": "5208e24f211a7042767ee3421e55eba758a08a1d",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-30T05:45:58",
"content_id": "14daa7593f08a24a0dbeb9f0f048dd3f0f9de06f",
"detected_licenses": [
"MIT"
],
"directory_id": "7f7c0ee0efc37528e7a9a6c96b240515b751eee1",
"extension": "java",
"filename": "Problem464.java",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 28460187,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1860,
"license": "MIT",
"license_type": "permissive",
"path": "/src/main/java/leetcode/Problem464.java",
"provenance": "stack-edu-0024.json.gz:763919",
"repo_name": "fredyw/leetcode",
"revision_date": "2023-08-30T05:45:58",
"revision_id": "3dae006f4a38c25834f545e390acebf6794dc28f",
"snapshot_id": "ac7d95361cf9ada40eedd8925dc29fdf69bbb7c5",
"src_encoding": "UTF-8",
"star_events_count": 7,
"url": "https://raw.githubusercontent.com/fredyw/leetcode/3dae006f4a38c25834f545e390acebf6794dc28f/src/main/java/leetcode/Problem464.java",
"visit_date": "2023-09-01T21:29:23.960806",
"added": "2024-11-19T01:42:35.177035+00:00",
"created": "2023-08-30T05:45:58",
"int_score": 3,
"score": 3.0625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0042.json.gz"
}
|
from enum import Enum
class Direction(Enum):
"""Represents the direction options for the
`Movers` service.
### Usage
----
>>> from td.enums import Directions
>>> Directions.Up.value
"""
Up = 'up'
Down = 'down'
class Change(Enum):
"""Represents the change options for the
`Movers` service.
### Usage
----
>>> from td.enums import Change
>>> Change.Percent.value
"""
Percent = 'percent'
Value = 'value'
class TransactionTypes(Enum):
"""Represents the types of transaction you
can query from TD Ameritrade using the `Accounts`
services.
### Usage
----
>>> from td.enums import TransactionTypes
>>> TransactionTypes.Trade.value
"""
All = 'ALL'
Trade = 'TRADE'
BuyOnly = 'BUY_ONLY'
SellOnly = 'SELL_ONLY'
CashInOrCashOut = 'CASH_IN_OR_CASH_OUT'
Checking = 'CHECKING'
Dividend = 'DIVIDEND'
Interest = 'INTEREST'
Other = 'OTHER'
AdvisorFees = 'ADVISOR_FEES'
class Markets(Enum):
"""Represents the different markets you can request
hours for the `MarketHours` service.
### Usage
----
>>> from td.enums import Markets
>>> Markets.Bond.Value
"""
Bond = 'BOND'
Equity = 'EQUITY'
Option = 'OPTION'
Forex = 'FOREX'
Futures = 'FUTURES'
class Projections(Enum):
"""Represents the different search types you can use for
the `Instruments` service.
### Usage
----
>>> from td.enums import Projections
>>> Projections.Bond.Value
"""
SymbolSearch = 'symbol-search'
SymbolRegex = 'symbol-regex'
DescriptionSearch = 'desc-search'
DescriptionRegex = 'desc-regex'
Fundamental = 'fundamental'
class DefaultOrderLegInstruction(Enum):
"""Represents the different Default Order Leg Instructions
for the `UserInfo` service.
### Usage
----
>>> from td.enums import DefaultOrderLegInstruction
>>> DefaultOrderLegInstruction.Sell.Value
"""
Buy = 'BUY'
Sell = 'SELL'
BuyToCover = 'BUY_TO_COVER'
SellShort = 'SELL_SHORT'
NoneSpecified = 'NONE'
class DefaultOrderType(Enum):
"""Represents the different Default Order Type
for the `UserInfo` service.
### Usage
----
>>> from td.enums import DefaultOrderType
>>> DefaultOrderType.Market.Value
"""
Market = 'MARKET'
Limit = 'LIMIT'
Stop = 'STOP'
StopLimit = 'STOP_LIMIT'
TrailingStop = 'TRAILING_STOP'
MarketOnClose = 'MARKET_ON_CLOSE'
NoneSpecified = 'NONE'
class DefaultOrderPriceLinkType(Enum):
"""Represents the different Default Order Price Link Type
for the `UserInfo` service.
### Usage
----
>>> from td.enums import DefaultOrderPriceLinkType
>>> DefaultOrderPriceLinkType.Value.Value
"""
Value = 'VALUE'
Percent = 'PERCENT'
NoneSpecified = 'NONE'
class DefaultOrderDuration(Enum):
"""Represents the different Default Order Duration
for the `UserInfo` service.
### Usage
----
>>> from td.enums import DefaultOrderDuration
>>> DefaultOrderDuration.Day.Value
"""
Day = 'DAY'
GoodTillCancel = 'GOOD_TILL_CANCEL'
FillOrKill = 'FILL_OR_KILL'
NoneSpecified = 'NONE'
class DefaultOrderMarketSession(Enum):
"""Represents the different Default Order Market Session
for the `UserInfo` service.
### Usage
----
>>> from td.enums import DefaultOrderMarketSession
>>> DefaultOrderMarketSession.Day.Value
"""
Am = 'AM'
Pm = 'PM'
Normal = 'NORMAL'
Seamless = 'SEAMLESS'
NoneSpecified = 'NONE'
class TaxLotMethod(Enum):
"""Represents the different Tax Lot Methods
for the `UserInfo` service.
### Usage
----
>>> from td.enums import MutualFundTaxLotMethod
>>> MutualFundTaxLotMethod.Day.Value
"""
Fifo = 'FIFO'
Lifo = 'LIFO'
HighCost = 'HIGH_COST'
LowCost = 'LOW_COST'
MinimumTax = 'MINIMUM_TAX'
AverageCost = 'AVERAGE_COST'
NoneSpecified = 'NONE'
class DefaultAdvancedToolLaunch(Enum):
"""Represents the different Default Advanced Tool
Lauch for the `UserInfo` service.
### Usage
----
>>> from td.enums import DefaultAdvancedToolLaunch
>>> DefaultAdvancedToolLaunch.Tos.Value
"""
Ta = 'Ta'
No = 'N'
Yes = 'Y'
Tos = 'TOS'
Cc2 = 'CC2'
NoneSpecified = 'NONE'
class AuthTokenTimeout(Enum):
"""Represents the different Auth Token Timeout
properties for the `UserInfo` service.
### Usage
----
>>> from td.enums import AuthTokenTimeout
>>> AuthTokenTimeout.FiftyFiveMinutes.Value
"""
FiftyFiveMinutes = 'FIFTY_FIVE_MINUTES'
TwoHours = 'TWO_HOURS'
FourHours = 'FOUR_HOURS'
EightHours = 'EIGHT_HOURS'
class FrequencyType(Enum):
"""Represents the different chart frequencies
for the `PriceHistory` service.
### Usage
----
>>> from td.enums import PriceFrequency
>>> PriceFrequency.Daily.Value
"""
Minute = 'minute'
Daily = 'daily'
Weekly = 'weekly'
Monthly = 'monthly'
class PeriodType(Enum):
"""Represents the different chart periods
for the `PriceHistory` service.
### Usage
----
>>> from td.enums import PriceFrequency
>>> PeriodType.Daily.Value
"""
Day = 'day'
Month = 'month'
Year = 'year'
YearToDate = 'ytd'
class StrategyType(Enum):
"""Represents the different strategy types
when querying the `OptionChain` service.
### Usage
----
>>> from td.enums import StrategyType
>>> StrategyType.Analytical.Value
"""
Analytical = 'ANALYTICAL'
Butterfly = 'BUTTERFLY'
Calendar = 'CALENDAR'
Collar = 'COLLAR'
Condor = 'CONDOR'
Covered = 'COVERED'
Diagonal = 'DIAGONAL'
Roll = 'ROLL'
Single = 'SINGLE'
Straddle = 'STRADDLE'
Strangle = 'STRANGLE'
Vertical = 'VERTICAL'
class OptionaRange(Enum):
"""Represents the different option range types
when querying the `OptionChain` service.
### Usage
----
>>> from td.enums import OptionaRange
>>> OptionaRange.InTheMoney.Value
"""
All = 'ALL'
InTheMoney = 'ITM'
NearTheMoney = 'NTM'
OutTheMoney = 'OTM'
StrikesAboveMarket = 'SAK'
StrikesBelowMarket = 'SBK'
StrikesNearMarket = 'SNK'
class ExpirationMonth(Enum):
"""Represents the different option expiration months
when querying the `OptionChain` service.
### Usage
----
>>> from td.enums import ExpirationMonth
>>> ExpirationMonth.Janurary.Value
"""
All = 'ALL'
Janurary = 'JAN'
Feburary = 'FEB'
March = 'MAR'
April = 'April'
May = 'MAY'
June = 'JUN'
July = 'JUL'
August = 'AUG'
September = 'SEP'
October = 'OCT'
November = 'NOV'
December = 'DEC'
class ContractType(Enum):
"""Represents the different option contract types
when querying the `OptionChain` service.
### Usage
----
>>> from td.enums import ContractType
>>> ContractType.Call.Value
"""
All = 'ALL'
Call = 'CALL'
Put = 'PUT'
class OptionType(Enum):
"""Represents the different option types
when querying the `OptionChain` service.
### Usage
----
>>> from td.enums import OptionType
>>> OptionType.Call.Value
"""
All = 'ALL'
StandardContracts = 'S'
NonStandardContracts = 'NS'
class OrderStatus(Enum):
"""Represents the different order status types
when querying the `Orders` service.
### Usage
----
>>> from td.enums import OrderStatus
>>> OrderStatus.Working.Value
"""
AwaitingParentOrder = 'AWAITING_PARENT_ORDER'
AwaitingCondition = 'AWAITING_CONDITION'
AwaitingManualReview = 'AWAITING_MANUAL_REVIEW'
Accepted = 'ACCEPTED'
AwaitingUrOut = 'AWAITING_UR_OUT'
PendingActivation = 'PENDING_ACTIVATION'
Queded = 'QUEUED'
Working = 'WORKING'
Rejected = 'REJECTED'
PendingCancel = 'PENDING_CANCEL'
Canceled = 'CANCELED'
PendingReplace = 'PENDING_REPLACE'
Replaced = 'REPLACED'
Filled = 'FILLED'
Expired = 'EXPIRED'
class OrderStrategyType(Enum):
"""Represents the different order strategy types
when constructing and `Order` object.
### Usage
----
>>> from td.enums import OrderStrategyType
>>> OrderStrategyType.Single.Value
"""
Single = 'SINGLE'
Oco = 'OCO'
Trigger = 'TRIGGER'
class QuantityType(Enum):
"""Represents the different order quantity types
when constructing and `Order` object.
### Usage
----
>>> from td.enums import QuantityType
>>> QuantityType.Dollars.Value
"""
AllShares = 'ALL_SHARES'
Dollars = 'DOLLARS'
Shares = 'SHARES'
class AssetType(Enum):
"""Represents the different order Asset types
when constructing and `Order` object.
### Usage
----
>>> from td.enums import AssetType
>>> AssetType.Equity.Value
"""
Equity = 'EQUITY'
Option = 'OPTION'
Index = 'INDEX'
MutualFund = 'MUTUAL_FUND'
CashEquivalent = 'CASH_EQUIVALENT'
FixedIncome = 'FIXED_INCOME'
Currency = 'CURRENCY'
class ComplexOrderStrategyType(Enum):
"""Represents the different order Asset types
when constructing and `Order` object.
### Usage
----
>>> from td.enums import ComplexOrderStrategyType
>>> ComplexOrderStrategyType.IronCondor.Value
"""
NoneProvided = 'NONE'
Covered = 'COVERED'
Vertical = 'VERTICAL'
BackRatio = 'BACK_RATIO'
Calendar = 'CALENDAR'
Diagonal = 'DIAGONAL'
Straddle = 'STRADDLE'
Strangle = 'STRANGLE'
CollarSynthetic = 'COLLAR_SYNTHETIC'
Butterfly = 'BUTTERFLY'
Condor = 'CONDOR'
IronCondor = 'IRON_CONDOR'
VerticalRoll = 'VERTICAL_ROLL'
CollarWithStock = 'COLLAR_WITH_STOCK'
DoubleDiagonal = 'DOUBLE_DIAGONAL'
UnbalancedButterfly = 'UNBALANCED_BUTTERFLY'
UnbalancedCondor = 'UNBALANCED_CONDOR'
UnbalancedIronCondor = 'UNBALANCED_IRON_CONDOR'
UnbalancedVerticalRoll = 'UNBALANCED_VERTICAL_ROLL'
Custom = 'CUSTOM'
class OrderInstructions(Enum):
"""Represents the different order instructions
when constructing and `Order` object.
### Usage
----
>>> from td.enums import OrderInstructions
>>> OrderInstructions.SellShort.Value
"""
Buy = 'BUY'
Sell = 'SELL'
BuyToCover = 'BUY_TO_COVER'
SellShort = 'SELL_SHORT'
BuyToOpen = 'BUY_TO_OPEN'
BuyToClose = 'BUY_TO_CLOSE'
SellToOpen = 'SELL_TO_OPEN'
SellToClose = 'SELL_TO_CLOSE'
Exchange = 'EXCHANGE'
class RequestedDestination(Enum):
"""Represents the different order requested
destinations when constructing and `Order` object.
### Usage
----
>>> from td.enums import RequestedDestination
>>> RequestedDestination.Cboe.Value
"""
Inet = 'INET'
EcnArca = 'ECN_ARCA'
Cboe = 'CBOE'
Amex = 'AMEX'
Phlx = 'PHLX'
Ise = 'ISE'
Box = 'BOX'
Nyse = 'NYSE'
Nasdaq = 'NASDAQ'
Bats = 'BATS'
C2 = 'C2'
Auto = 'AUTO'
class StopPriceLinkBasis(Enum):
"""Represents the different stop price link basis
when constructing and `Order` object.
### Usage
----
>>> from td.enums import StopPriceLinkBasis
>>> StopPriceLinkBasis.Trigger.Value
"""
Manual = 'MANUAL'
Base = 'BASE'
Trigger = 'TRIGGER'
Last = 'LAST'
Bid = 'BID'
Ask = 'ASK'
AskBid = 'ASK_BID'
Mark = 'MARK'
Average = 'AVERAGE'
class StopPriceLinkType(Enum):
"""Represents the different stop price link type
when constructing and `Order` object.
### Usage
----
>>> from td.enums import StopPriceLinkType
>>> StopPriceLinkType.Trigger.Value
"""
Value = 'VALUE'
Percent = 'PERCENT'
Tick = 'TICK'
class StopType(Enum):
"""Represents the different stop type
when constructing and `Order` object.
### Usage
----
>>> from td.enums import StopType
>>> StopType.Standard.Value
"""
Standard = 'STANDARD'
Bid = 'BID'
Ask = 'ASK'
Last = 'LAST'
Mark = 'MARK'
class PriceLinkBasis(Enum):
"""Represents the different price link basis
when constructing and `Order` object.
### Usage
----
>>> from td.enums import PriceLinkBasis
>>> PriceLinkBasis.Manual.Value
"""
Manual = 'MANUAL'
Base = 'BASE'
Trigger = 'TRIGGER'
Last = 'LAST'
Bid = 'BID'
Ask = 'ASK'
AskBid = 'ASK_BID'
Mark = 'MARK'
Average = 'AVERAGE'
class PriceLinkType(Enum):
"""Represents the different price link type
when constructing and `Order` object.
### Usage
----
>>> from td.enums import PriceLinkType
>>> PriceLinkType.Trigger.Value
"""
Value = 'VALUE'
Percent = 'PERCENT'
Tick = 'TICK'
class OrderType(Enum):
"""Represents the different order type
when constructing and `Order` object.
### Usage
----
>>> from td.enums import OrderType
>>> OrderType.Market.Value
"""
Market = 'MARKET'
Limit = 'LIMIT'
Stop = 'STOP'
StopLimit = 'STOP_LIMIT'
TrailingStop = 'TRAILING_STOP'
MarketOnClose = 'MARKET_ON_CLOSE'
Exercise = 'EXERCISE'
TrailingStopLimit = 'TRAILING_STOP_LIMIT'
NetDebit = 'NET_DEBIT'
NetCredit = 'NET_CREDIT'
NetZero = 'NET_ZERO'
class PositionEffect(Enum):
"""Represents the different position effects
when constructing and `Order` object.
### Usage
----
>>> from td.enums import PositionEffect
>>> PositionEffect.Opening.Value
"""
Opening = 'OPENING'
Closing = 'CLOSING'
Automatic = 'AUTOMATIC'
class OrderTaxLotMethod(Enum):
"""Represents the different order tax lot methods
when constructing and `Order` object.
### Usage
----
>>> from td.enums import OrderTaxLotMethod
>>> OrderTaxLotMethod.Fifo.Value
"""
Fifo = 'FIFO'
Lifo = 'LIFO'
HighCost = 'HIGH_COST'
LowCost = 'LOW_COST'
AverageCost = 'AVERAGE_COST'
SpecificLot = 'SPECIFIC_LOT'
class SpecialInstructions(Enum):
"""Represents the different order special instructions
when constructing and `Order` object.
### Usage
----
>>> from td.enums import SpecialInstructions
>>> SpecialInstructions.AllOrNone.Value
"""
AllOrNone = 'ALL_OR_NONE'
DoNotReduce = 'DO_NOT_REDUCE'
AllOrNoneDoNotReduce = 'ALL_OR_NONE_DO_NOT_REDUCE'
class LevelOneQuotes(Enum):
"""Represents the different fields for the Level One
Quotes Feed.
### Usage
----
>>> from td.enums import LevelOneQuotes
>>> LevelOneQuotes.All.Value
"""
All = [str(item) for item in range(0, 53)]
Symbol = 0
BidPrice = 1
AskPrice = 2
LastPrice = 3
BidSize = 4
AskSize = 5
AskId = 6
BidId = 7
TotalVolume = 8
LastSize = 9
TradeTime = 10
QuoteTime = 11
HighPrice = 12
LowPrice = 13
BidTick = 14
ClosePrice = 15
ExchangeId = 16
Marginable = 17
Shortable = 18
IslandBid = 19
IslandAsk = 20
IslandVolume = 21
QuoteDay = 22
TradeDay = 23
Volatility = 24
Description = 25
LastId = 26
Digits = 27
OpenPrice = 28
NetChange = 29
FiftyTwoWeekHigh = 30
FiftyTwoWeekLow = 31
PeRatio = 32
DividendAmount = 33
DividendYield = 34
IslandBidSize = 35
IslandAskSize = 36
Nav = 37
FundPrice = 38
ExchangeName = 39
DividendDate = 40
RegularMarketQuote = 41
RegularMarketTrade = 42
RegularMarketLastPrice = 43
RegularMarketLastSize = 44
RegularMarketTradeTime = 45
RegularMarketTradeDay = 46
RegularMarketNetChange = 47
SecurityStatus = 48
Mark = 49
QuoteTimeInLong = 50
TradeTimeInLong = 51
RegularMarketTradeTimeInLong = 52
class LevelOneOptions(Enum):
"""Represents the different fields for the Level One
Options Feed.
### Usage
----
>>> from td.enums import LevelOneOptions
>>> LevelOneOptions.All.Value
"""
All = [str(item) for item in range(0, 42)]
Symbol = 0
Description = 1
BidPrice = 2
AskPrice = 3
LastPrice = 4
HighPrice = 5
LowPrice = 6
ClosePrice = 7
TotalVolume = 8
OpenInterest = 9
Volatility = 10
QuoteTime = 11
TradeTime = 12
MoneyIntrinsicValue = 13
QuoteDay = 14
TradeDay = 15
ExpirationYear = 16
Multiplier = 17
Digits = 18
OpenPrice = 19
BidSize = 20
AskSize = 21
LastSize = 22
NetChange = 23
StrikePrice = 24
ContractType = 25
Underlying = 26
ExpirationMonth = 27
Deliverables = 28
TimeValue = 29
ExpirationDay = 30
DaysToExpiration = 31
Delta = 32
Gamma = 33
Theta = 34
Vega = 35
Rho = 36
SecurityStatus = 37
TheoreticalOptionValue = 38
UnderlyingPrice = 39
UvExpirationType = 40
Mark = 41
class LevelOneFutures(Enum):
"""Represents the different fields for the Level One
Futures Feed.
### Usage
----
>>> from td.enums import LevelOneFutures
>>> LevelOneFutures.All.Value
"""
All = [str(item) for item in range(0, 36)]
Symbol = 0
BidPrice = 1
AskPrice = 2
LastPrice = 3
BidSize = 4
AskSize = 5
AskId = 6
BidId = 7
TotalVolume = 8
LastSize = 9
QuoteTime = 10
TradeTime = 11
HighPrice = 12
LowPrice = 13
ClosePrice = 14
ExchangeId = 15
Description = 16
LastId = 17
OpenPrice = 18
NetChange = 19
FuturePercentChange = 20
ExhangeName = 21
SecurityStatus = 22
OpenInterest = 23
Mark = 24
Tick = 25
TickAmount = 26
Product = 27
FuturePriceFormat = 28
FutureTradingHours = 29
FutureIsTradable = 30
FutureMultiplier = 31
FutureIsActive = 32
FutureSettlementPrice = 33
FutureActiveSymbol = 34
FutureExpirationDate = 35
class LevelOneForex(Enum):
"""Represents the different fields for the Level One
Forex Feed.
### Usage
----
>>> from td.enums import LevelOneForex
>>> LevelOneForex.All.Value
"""
All = [str(item) for item in range(0, 30)]
Symbol = 0
BidPrice = 1
AskPrice = 2
LastPrice = 3
BidSize = 4
AskSize = 5
TotalVolume = 6
LastSize = 7
QuoteTime = 8
TradeTime = 9
HighPrice = 10
LowPrice = 11
ClosePrice = 12
ExchangeId = 13
Description = 14
OpenPrice = 15
NetChange = 16
PercentChange = 17
ExchangeName = 18
Digits = 19
SecurityStatus = 20
Tick = 21
TickAmount = 22
Product = 23
TradingHours = 24
IsTradable = 25
MarketMaker = 26
FiftyTwoWeekHigh = 27
FiftyTwoWeekLow = 28
Mark = 29
class NewsHeadlines(Enum):
"""Represents the different fields for the News
Headline Feed.
### Usage
----
>>> from td.enums import NewsHeadlines
>>> NewsHeadlines.All.Value
"""
All = [str(item) for item in range(0, 11)]
Symbol = 0
ErrorCode = 1
StoryDatetime = 2
HeadlineId = 3
Status = 4
Headline = 5
StoryId = 6
CountForKeyword = 7
KeywordArray = 8
IsHot = 9
StorySource = 10
class LevelOneFuturesOptions(Enum):
"""Represents the different fields for the Level
One Futures Options feed.
### Usage
----
>>> from td.enums import LevelOneFuturesOptions
>>> LevelOneFuturesOptions.All.Value
"""
All = [str(item) for item in range(0, 36)]
Symbol = 0
BidPrice = 1
AskPrice = 2
LastPrice = 3
BidSize = 4
AskSize = 5
AskId = 6
BidId = 7
TotalVolume = 8
LastSize = 9
QuoteTime = 10
TradeTime = 11
HighPrice = 12
LowPrice = 13
ClosePrice = 14
ExchangeId = 15
Description = 16
LastId = 17
OpenPrice = 18
NetChange = 19
FuturePercentChange = 20
ExhangeName = 21
SecurityStatus = 22
OpenInterest = 23
Mark = 24
Tick = 25
TickAmount = 26
Product = 27
FuturePriceFormat = 28
FutureTradingHours = 29
FutureIsTradable = 30
FutureMultiplier = 31
FutureIsActive = 32
FutureSettlementPrice = 33
FutureActiveSymbol = 34
FutureExpirationDate = 35
class ChartServices(Enum):
"""Represents the different streaming chart
services.
### Usage
----
>>> from td.enums import ChartServices
>>> ChartServices.ChartEquity.Value
"""
ChartEquity = "CHART_EQUITY"
_ChartFutures = "CHART_FUTURES"
ChartOptions = "CHART_OPTIONS"
class ChartEquity(Enum):
"""Represents the different streaming chart
equity fields.
### Usage
----
>>> from td.enums import ChartEquity
>>> ChartEquity.All.Value
"""
All = [str(item) for item in range(0, 9)]
Symbol = 0
OpenPrice = 1
HighPrice = 2
LowPrice = 3
Close_Price = 4
Volume = 5
Sequence = 6
Chart_Time = 7
Chart_Day = 8
class ChartFutures(Enum):
"""Represents the different streaming chart
futures fields.
### Usage
----
>>> from td.enums import ChartFutures
>>> ChartFutures.All.Value
"""
All = [str(item) for item in range(0, 7)]
Symbol = 0
ChartTime = 1
OpenPrice = 2
HighPrice = 3
LowPrice = 4
ClosePrice = 5
Volume = 6
class TimesaleServices(Enum):
"""Represents the different streaming timesale
services.
### Usage
----
>>> from td.enums import TimesaleServices
>>> TimesaleServices.TimesaleEquity.Value
"""
TimesaleEquity = 'TIMESALE_EQUITY'
TimesaleForex = 'TIMESALE_FOREX'
TimesaleFutures = 'TIMESALE_FUTURES'
TimesaleOptions = 'TIMESALE_OPTIONS'
class Timesale(Enum):
"""Represents the different streaming timesale
fields.
### Usage
----
>>> from td.enums import Timesale
>>> Timesale.All.Value
"""
All = [str(item) for item in range(0, 5)]
Symbol = 0
TradeTime = 1
LastPrice = 2
LastSize = 3
LastSequence = 4
class ActivesServices(Enum):
"""Represents the different streaming actives
services.
### Usage
----
>>> from td.enums import ActivesServices
>>> ActivesServices.ActivesNasdaq.Value
"""
ActivesNasdaq = 'ACTIVES_NASDAQ'
ActivesNyse = 'ACTIVES_NYSE'
ActivesOptions = 'ACTIVES_OPTIONS'
ActivesOtcbb = 'ACTIVES_OTCBB'
class ActivesVenues(Enum):
"""Represents the different streaming actives
venues.
### Usage
----
>>> from td.enums import ActivesVenues
>>> ActivesVenues.Nasdaq.Value
"""
NasdaqExchange = 'NASDAQ'
NewYorkStockExchange = 'NYSE'
OverTheCounterBulletinBoard = 'OTCBB'
Calls = 'CALLS'
Puts = 'PUTS'
Options = 'OPTS'
CallsDesc = 'CALLS-DESC'
PutsDesc = 'PUTS-DESC'
OptionsDec = 'OPTS-DESC'
class ActivesDurations(Enum):
"""Represents the different durations for the
Actives Service.
### Usage
----
>>> from td.enums import ActivesDurations
>>> ActivesDurations.All.Value
"""
All = 'ALL'
SixtySeconds = '60'
ThreeHundredSeconds = '300'
SixHundredSeconds = '600'
EighteenHundredSeconds = '1800'
ThritySixHundredSeconds = '3600'
class ChartFuturesFrequencies(Enum):
"""Represents the different frequencies for the
Chart History Futures streaming service.
### Usage
----
>>> from td.enums import ChartFuturesFrequencies
>>> ChartFuturesFrequencies.OneMinute.Value
"""
OneMinute = 'm1'
FiveMinute = 'm5'
TenMinute = 'm10'
ThirtyMinute = 'm30'
OneHour = 'h1'
OneDay = 'd1'
OneWeek = 'w1'
OneMonth = 'n1'
class ChartFuturesPeriods(Enum):
"""Represents the different periods for the
Chart History Futures streaming service.
### Usage
----
>>> from td.enums import ChartFuturesPeriods
>>> ChartFuturesPeriods.OneDay.Value
"""
OneDay = 'd1'
FiveDay = 'd5'
FourWeeks = 'w4'
TenMonths = 'n10'
OneYear = 'y1'
TenYear = 'y10'
class LevelTwoQuotes(Enum):
"""Represents the Level Two Quotes Fields.
### Usage
----
>>> from td.enums import LevelTwoQuotes
>>> LevelTwoQuotes.All.Value
"""
All = [str(item) for item in range(0, 3)]
Key = 0
Time = 1
Data = 2
class LevelTwoOptions(Enum):
"""Represents the Level Two Options Fields.
### Usage
----
>>> from td.enums import LevelTwoOptions
>>> LevelTwoOptions.All.Value
"""
All = [str(item) for item in range(0, 3)]
Key = 0
Time = 1
Data = 2
|
f7f867c204811f52ff1e9707521cf0469309d868
|
{
"blob_id": "f7f867c204811f52ff1e9707521cf0469309d868",
"branch_name": "refs/heads/master",
"committer_date": "2021-10-31T18:59:17",
"content_id": "8bd98251fbf8f1bfddc7740ea060d7a44ba4a23f",
"detected_licenses": [
"MIT"
],
"directory_id": "e7823c85962f7b7b08339cbcf7aa05de422c0fe2",
"extension": "py",
"filename": "enums.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 25007,
"license": "MIT",
"license_type": "permissive",
"path": "/td/utils/enums.py",
"provenance": "stack-edu-0061.json.gz:24395",
"repo_name": "Aftermath213/td-ameritrade-api",
"revision_date": "2021-10-31T18:59:17",
"revision_id": "e5132f13c883d9bd6d15f282662f548467b6ef55",
"snapshot_id": "1a8a4a63b98b2fef1543ef24b069de90f1ef9612",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Aftermath213/td-ameritrade-api/e5132f13c883d9bd6d15f282662f548467b6ef55/td/utils/enums.py",
"visit_date": "2023-09-02T23:44:40.935626",
"added": "2024-11-18T21:31:29.022337+00:00",
"created": "2021-10-31T18:59:17",
"int_score": 2,
"score": 2.015625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0079.json.gz"
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SiteWatcher.Core.Configs.ConfigsBase
{
public class ConfigsManager<ConfigModel>
{
/// <summary>
/// 文件修改时间
/// </summary>
//private bool isChange;
/// <summary>
/// 配置文件所在路径
/// </summary>
private string _filename;
/// <summary>
/// 初始化文件修改时间和对象实例
/// </summary>
public ConfigsManager(string filename)
{
_filename = filename;
DateTime dtNew = System.IO.File.GetLastWriteTime(_filename);
}
/// <summary>
/// 返回配置类实例
/// </summary>
/// <returns></returns>
public ConfigModel LoadConfig()
{
return DeserializeInfo();
}
private ConfigModel DeserializeInfo()
{
return (ConfigModel)SerializationBll.Load(typeof(ConfigModel), _filename);
}
/// <summary>
/// 保存配置类实例
/// </summary>
/// <returns></returns>
public bool Save(ConfigModel ConfigInfo)
{
return SerializationBll.Save(ConfigInfo, _filename);
}
}
}
|
8a8100b34b20d5dc84f7c36a9e59838565fc496d
|
{
"blob_id": "8a8100b34b20d5dc84f7c36a9e59838565fc496d",
"branch_name": "refs/heads/main",
"committer_date": "2021-01-29T05:36:43",
"content_id": "edc6f5c1c731a334437a76ad975a60a07f91d13d",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "be8c072e9f56381e1c58d30b8f85bed3f332014f",
"extension": "cs",
"filename": "ConfigManager.cs",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 1314,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/SiteWatcher.Core/Configs/ConfigsBase/ConfigManager.cs",
"provenance": "stack-edu-0013.json.gz:585369",
"repo_name": "tobaba/SiteWatcher",
"revision_date": "2021-01-29T05:36:43",
"revision_id": "2334417963ded99cd8377e95c571fab00bc31577",
"snapshot_id": "6a0f7a2a90f4f75eb1e53c39b15a297ba91699cf",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/tobaba/SiteWatcher/2334417963ded99cd8377e95c571fab00bc31577/SiteWatcher.Core/Configs/ConfigsBase/ConfigManager.cs",
"visit_date": "2023-03-20T21:10:04.082481",
"added": "2024-11-18T20:06:34.801555+00:00",
"created": "2021-01-29T05:36:43",
"int_score": 3,
"score": 2.625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0031.json.gz"
}
|
SELECT c.oid AS oid, c.pubname AS name,
pubinsert AS evnt_insert, pubupdate AS evnt_update, pubdelete AS evnt_delete, pubtruncate AS evnt_truncate,
puballtables AS all_table,
pubviaroot AS publish_via_partition_root,
pga.rolname AS pubowner FROM pg_catalog.pg_publication c
JOIN pg_catalog.pg_roles pga ON c.pubowner= pga.oid
{% if pbid %}
WHERE c.oid = {{ pbid }}
{% endif %}
|
512347e40dd29e4b9b8b8897d7f174a84aa5ab3a
|
{
"blob_id": "512347e40dd29e4b9b8b8897d7f174a84aa5ab3a",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-31T09:32:30",
"content_id": "186aeb279997b4e349a83487011fb97ddb1f6818",
"detected_licenses": [
"PostgreSQL"
],
"directory_id": "423ca5205aaf0b2d3bfff9affe2172fec21bfad0",
"extension": "sql",
"filename": "properties.sql",
"fork_events_count": 0,
"gha_created_at": "2021-10-20T06:34:38",
"gha_event_created_at": "2023-01-02T05:37:03",
"gha_language": "Python",
"gha_license_id": "NOASSERTION",
"github_id": 419212569,
"is_generated": false,
"is_vendor": false,
"language": "SQL",
"length_bytes": 382,
"license": "PostgreSQL",
"license_type": "permissive",
"path": "/web/pgadmin/browser/server_groups/servers/databases/publications/templates/publications/ppas/13_plus/sql/properties.sql",
"provenance": "stack-edu-0070.json.gz:417600",
"repo_name": "adityatoshniwal/pgadmin4",
"revision_date": "2023-07-31T09:32:30",
"revision_id": "2aea5b41ad8b6bd4a408a87a6743fcbfc88ed329",
"snapshot_id": "25cc665d1438f82bdb17f13270933c43e3a98f4b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/adityatoshniwal/pgadmin4/2aea5b41ad8b6bd4a408a87a6743fcbfc88ed329/web/pgadmin/browser/server_groups/servers/databases/publications/templates/publications/ppas/13_plus/sql/properties.sql",
"visit_date": "2023-09-03T20:04:15.941551",
"added": "2024-11-18T22:23:39.839184+00:00",
"created": "2023-07-31T09:32:30",
"int_score": 3,
"score": 3,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0088.json.gz"
}
|
package velos;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;
import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.base.BaseRichBolt;
import org.apache.storm.tuple.Tuple;
public class SaveResultsBolt extends BaseRichBolt {
private OutputCollector outputCollector;
@Override
public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) {
outputCollector = collector;
}
@Override
public void execute(Tuple input) {
try {
process(input);
outputCollector.ack(input);
} catch (IOException e) {
e.printStackTrace();
outputCollector.fail(input);
}
}
public void process(Tuple input) throws IOException {
String city = input.getStringByField("city");
String date = input.getStringByField("date");
Double availableStands = input.getDoubleByField("available_stands");
String filePath = String.format("/tmp/%s.csv", city);
// Check if file exists
File csvFile = new File(filePath);
if(!csvFile.exists()) {
FileWriter fileWriter = new FileWriter(filePath);
fileWriter.write("date;available stands\n");
fileWriter.close();
}
// Write stats to file
FileWriter fileWriter = new FileWriter(filePath, true);
System.out.printf("====== SaveResultsBolt: %s %s - %f available stands\n", date, city, availableStands);
fileWriter.write(String.format("%s;%f\n", date, availableStands));
fileWriter.close();
}
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
}
}
|
00e331458ed1523448ceb37a19dca5c65eaef44c
|
{
"blob_id": "00e331458ed1523448ceb37a19dca5c65eaef44c",
"branch_name": "refs/heads/main",
"committer_date": "2021-03-26T07:22:10",
"content_id": "6e034bf1f3d23046df290b0b993c04a2e7e45c18",
"detected_licenses": [
"MIT"
],
"directory_id": "1f23c337a3e2a7e1a1ff8768d91963a06ec08833",
"extension": "java",
"filename": "SaveResultsBolt.java",
"fork_events_count": 15,
"gha_created_at": "2021-02-04T08:26:12",
"gha_event_created_at": "2021-02-26T03:46:28",
"gha_language": "Java",
"gha_license_id": "MIT",
"github_id": 335887239,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1650,
"license": "MIT",
"license_type": "permissive",
"path": "/src/storm/velos/src/main/java/velos/SaveResultsBolt.java",
"provenance": "stack-edu-0020.json.gz:275240",
"repo_name": "nael-fridhi/bigdata-spark-kafka-course",
"revision_date": "2021-03-26T07:22:10",
"revision_id": "6f1686dd150c6b703ec706001153a9315980f793",
"snapshot_id": "b6c3d5e755381fcb30f07e536e457bde3f53ff43",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/nael-fridhi/bigdata-spark-kafka-course/6f1686dd150c6b703ec706001153a9315980f793/src/storm/velos/src/main/java/velos/SaveResultsBolt.java",
"visit_date": "2023-03-30T07:24:04.875824",
"added": "2024-11-18T22:25:34.603035+00:00",
"created": "2021-03-26T07:22:10",
"int_score": 2,
"score": 2.5,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0038.json.gz"
}
|
package phrase
import (
"testing"
"github.com/go-ego/gse"
"github.com/vcaesar/tt"
)
func BenchmarkParagraph(b *testing.B) {
for i := 0; i < b.N; i++ {
// about 0.046ms/op
Paragraph("西雅图太空针, The Space Nedle")
}
}
func TestParagraph(t *testing.T) {
expects := map[string]string{
"西雅图太空针, The Space Nedle, MT. Rainier": "xi ya tu tai kong zhen, The Space Nedle, MT. Rainier",
"旧金山湾金门大桥": "jiu jin shan wan jin men da qiao",
"纽约帝国大厦, 纽约时代广场, 世贸中心": "niu yue di guo da sha, niu yue shi dai guang chang, shi mao zhong xin",
"多伦多加拿大国家电视塔, the CN Tower, 尼亚加拉大瀑布": "duo lun duo jia na da guo jia dian shi ta, the CN Tower, ni ya jia la da pu bu",
"伦敦泰晤士河, 大笨钟, 摘星塔": "lun dun tai wu shi he, da ben zhong, zhai xing ta",
"洛杉矶好莱坞": "luo shan ji hao lai wu",
"悉尼歌剧院": "xi ni ge ju yuan",
"雅典帕特农神庙": "ya dian pa te nong shen miao",
"东京都, 东京晴空塔, 富士山": "dong jing du, dong jing qing kong ta, fu shi shan",
"巴黎埃菲尔铁塔": "ba li ai fei er tie ta",
"香港维多利亚港": "xiang gang wei duo li ya gang",
"上海外滩, 陆家嘴上海中心大厦": "shang hai wai tan, lu jia zui shang hai zhong xin da sha",
"北京八达岭长城": "bei jing ba da ling chang cheng",
}
seg, err := gse.New("zh, ../examples/dict.txt")
tt.Nil(t, err)
for source, expect := range expects {
actual := Paragraph(source, seg)
if expect != actual {
tt.Equal(t, expect, actual)
break
}
}
}
func TestPinyin(t *testing.T) {
seg, _ := gse.New("zh, ../examples/dict.txt")
WithGse(seg)
text := "西雅图都会区, 西雅图太空针"
AddDict("都会区", "dū huì qū")
p := Pinyin(text)
tt.Equal(t, "[xi ya tu du hui qu, xi ya tu tai kong zhen]", p)
i := Initial("都会区")
tt.Equal(t, "dhq", i)
Cut = false
s := seg.Trim(seg.CutAll(text))
i += ", "
for _, v := range s {
i1 := Initial(v)
i += i1 + " "
}
tt.Equal(t, "dhq, xyt dhq xyt tk z ", i)
Cut = true
}
|
882353dc3c745dcd1b28a413fc3368c55d0445fa
|
{
"blob_id": "882353dc3c745dcd1b28a413fc3368c55d0445fa",
"branch_name": "refs/heads/master",
"committer_date": "2021-11-13T18:07:43",
"content_id": "ed9c6327eef17ad2e3dd87345bb6b771af5466cf",
"detected_licenses": [
"MIT"
],
"directory_id": "86c9bfbcada1de48b1264da95ee107f8de25b634",
"extension": "go",
"filename": "paragraph_test.go",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 2224,
"license": "MIT",
"license_type": "permissive",
"path": "/phrase/paragraph_test.go",
"provenance": "stack-edu-0017.json.gz:585438",
"repo_name": "doudouwyh/gpy",
"revision_date": "2021-11-13T18:07:43",
"revision_id": "f2aba393625d587f4cb3f6eeefb6877e240ee6f5",
"snapshot_id": "d97bd29a3061dcecfc12103f53bc56eed7e828f4",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/doudouwyh/gpy/f2aba393625d587f4cb3f6eeefb6877e240ee6f5/phrase/paragraph_test.go",
"visit_date": "2023-08-26T08:02:31.184282",
"added": "2024-11-18T21:37:51.497743+00:00",
"created": "2021-11-13T18:07:43",
"int_score": 3,
"score": 2.640625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0035.json.gz"
}
|
// Copyright (c) 2022 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package radixsort32
import (
"testing"
"github.com/stretchr/testify/assert"
)
// TestRadixSort tests radix sort correctness
func TestRadixSort(t *testing.T) {
sorter := makeSorter(16, 100, 15000)
// short break
testRadixSortReversedSlice(t, sorter, 10)
// radix sort with buffers in pool
testRadixSortReversedSlice(t, sorter, 300)
// radix sort with dynamically allocated buffers
testRadixSortReversedSlice(t, sorter, 20000)
}
// TestOptions tests options and fallbacks
func TestOptions(t *testing.T) {
sorter := makeSorter(3, 500000, 100)
assert.Equal(t, uint(8), sorter.radix)
assert.Equal(t, 100, sorter.maxLength)
assert.Equal(t, 100, sorter.minLength)
sorter2 := makeSorter(3, -50, 100)
assert.Equal(t, 0, sorter2.minLength)
assert.Equal(t, 100, sorter2.maxLength)
}
func testRadixSortReversedSlice(t *testing.T, sorter *RadixSorter32, size int) {
slice := makeRevertedSlice(size)
sorter.Sort(slice)
assert.EqualValues(t, makeSortedSlice(size), slice)
}
func makeSorter(radix, minLen, maxLen int) *RadixSorter32 {
sorter := New(
Radix(radix),
MinLen(minLen),
MaxLen(maxLen))
return sorter
}
func makeRevertedSlice(size int) []uint32 {
a := make([]uint32, size)
for i := size - 1; i >= 0; i-- {
a[i] = uint32(len(a) - 1 - i)
}
return a
}
func makeSortedSlice(size int) []uint32 {
a := make([]uint32, size)
for i := 0; i < len(a); i++ {
a[i] = uint32(i)
}
return a
}
// Benchmarks
func BenchmarkSortSize150KCompare(b *testing.B) {
benchmarkCompareSort(b, 150000)
}
func BenchmarkSortSize150KRadix4(b *testing.B) {
benchmarkRadixSort(b, 4, 150000)
}
func BenchmarkSortSize150KRadix8(b *testing.B) {
benchmarkRadixSort(b, 8, 150000)
}
func BenchmarkSortSize150KRadix16(b *testing.B) {
benchmarkRadixSort(b, 16, 150000)
}
func BenchmarkSortSize15KCompare(b *testing.B) {
benchmarkCompareSort(b, 15000)
}
func BenchmarkSortSize15KRadix4(b *testing.B) {
benchmarkRadixSort(b, 4, 15000)
}
func BenchmarkSortSize15KRadix8(b *testing.B) {
benchmarkRadixSort(b, 8, 15000)
}
func BenchmarkSortSize15KRadix16(b *testing.B) {
benchmarkRadixSort(b, 16, 15000)
}
func BenchmarkSortSize1500Compare(b *testing.B) {
benchmarkCompareSort(b, 1500)
}
func BenchmarkSortSize1500Radix4(b *testing.B) {
benchmarkRadixSort(b, 4, 1500)
}
func BenchmarkSortSize1500Radix8(b *testing.B) {
benchmarkRadixSort(b, 8, 1500)
}
func BenchmarkSortSize15000KRadix16(b *testing.B) {
benchmarkRadixSort(b, 16, 1500)
}
const par = 8
func benchmarkRadixSort(b *testing.B, radix, size int) {
sorter := makeSorter(radix, 0, size)
b.SetParallelism(par)
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
sorter.Sort(makeRevertedSlice(size))
}
})
}
func benchmarkCompareSort(b *testing.B, size int) {
sorter := makeSorter(8, size, size)
b.SetParallelism(par)
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
sorter.Sort(makeRevertedSlice(size))
}
})
}
|
145c2993869269d53f6083d9899c41f2ccea0217
|
{
"blob_id": "145c2993869269d53f6083d9899c41f2ccea0217",
"branch_name": "refs/heads/dev",
"committer_date": "2023-08-03T18:10:14",
"content_id": "cdb1c577115b2505b6907a6bce8ecf81b3284163",
"detected_licenses": [
"MIT"
],
"directory_id": "30ddc3dd64cf73e7d853458acf2ba7c8c8ce56db",
"extension": "go",
"filename": "radixsort_test.go",
"fork_events_count": 110,
"gha_created_at": "2016-01-26T00:04:14",
"gha_event_created_at": "2023-08-31T21:18:19",
"gha_language": "Go",
"gha_license_id": "MIT",
"github_id": 50390111,
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 4072,
"license": "MIT",
"license_type": "permissive",
"path": "/peer/hashring32/internal/radixsort32/radixsort_test.go",
"provenance": "stack-edu-0017.json.gz:550704",
"repo_name": "yarpc/yarpc-go",
"revision_date": "2023-08-03T18:10:14",
"revision_id": "42f4b29c52412a32c0f08b5686e42cdfd418975b",
"snapshot_id": "4c4a899b19544090e42f527b5ad54a4bc7d219cc",
"src_encoding": "UTF-8",
"star_events_count": 409,
"url": "https://raw.githubusercontent.com/yarpc/yarpc-go/42f4b29c52412a32c0f08b5686e42cdfd418975b/peer/hashring32/internal/radixsort32/radixsort_test.go",
"visit_date": "2023-08-17T03:35:31.137235",
"added": "2024-11-19T02:10:11.336886+00:00",
"created": "2023-08-03T18:10:14",
"int_score": 3,
"score": 2.609375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0035.json.gz"
}
|
package com.randomappsinc.simpleflashcards.ocr;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.randomappsinc.simpleflashcards.R;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/** Adapter for rendering a list of the text blocks recognized by OCR */
public class OcrTextSelectionAdapter extends RecyclerView.Adapter<OcrTextSelectionAdapter.TextBlockViewHolder> {
public interface Listener {
void onNumSelectedTextBlocksUpdated(int numSelectedSets);
}
protected List<String> textBlocks = new ArrayList<>();
protected List<String> selectedTextBlocks = new ArrayList<>();
protected Listener listener;
public OcrTextSelectionAdapter(Listener listener) {
this.listener = listener;
}
public void setTextBlocks(List<String> newTextBlocks) {
textBlocks.clear();
textBlocks.addAll(newTextBlocks);
selectedTextBlocks.clear();
notifyDataSetChanged();
listener.onNumSelectedTextBlocksUpdated(selectedTextBlocks.size());
}
public String getSelectedText() {
return TextUtils.join("\n", selectedTextBlocks);
}
@NonNull
@Override
public OcrTextSelectionAdapter.TextBlockViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.text_block_selection_cell,
parent,
false);
return new TextBlockViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull OcrTextSelectionAdapter.TextBlockViewHolder holder, int position) {
holder.loadTextBlock(position);
}
@Override
public int getItemCount() {
return textBlocks.size();
}
public class TextBlockViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.text_block)
TextView textBlockTextView;
@BindView(R.id.set_selected_toggle)
CheckBox setSelectedToggle;
TextBlockViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
void loadTextBlock(int position) {
String textBlock = textBlocks.get(position);
textBlockTextView.setText(textBlock);
setSelectedToggle.setChecked(selectedTextBlocks.contains(textBlock));
}
@OnClick(R.id.text_block_for_selection_parent)
public void onTextBlockCellClicked() {
String textBlock = textBlocks.get(getAdapterPosition());
if (selectedTextBlocks.contains(textBlock)) {
selectedTextBlocks.remove(textBlock);
setSelectedToggle.setChecked(false);
} else {
selectedTextBlocks.add(textBlock);
setSelectedToggle.setChecked(true);
}
listener.onNumSelectedTextBlocksUpdated(selectedTextBlocks.size());
}
@OnClick(R.id.set_selected_toggle)
public void onTextBlockSelection() {
String flashcardSet = textBlocks.get(getAdapterPosition());
if (selectedTextBlocks.contains(flashcardSet)) {
selectedTextBlocks.remove(flashcardSet);
} else {
selectedTextBlocks.add(flashcardSet);
}
listener.onNumSelectedTextBlocksUpdated(selectedTextBlocks.size());
}
}
}
|
597276f9e6343955de15d39941925504abf3e6f2
|
{
"blob_id": "597276f9e6343955de15d39941925504abf3e6f2",
"branch_name": "refs/heads/master",
"committer_date": "2019-08-27T05:19:22",
"content_id": "374d07f1bbb45af2650853ebfac58f04a02a758f",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "09a631fbd3d75e9b578fee760f30165590fff0a7",
"extension": "java",
"filename": "OcrTextSelectionAdapter.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 3693,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/app/src/main/java/com/randomappsinc/simpleflashcards/ocr/OcrTextSelectionAdapter.java",
"provenance": "stack-edu-0021.json.gz:841986",
"repo_name": "laithhas/Simple-Flashcards",
"revision_date": "2019-08-27T05:19:22",
"revision_id": "bdbec74e6047e8ad5fab16d9a85081e8dc4d8711",
"snapshot_id": "f7532d806fc2be6e591549499845836c024f970e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/laithhas/Simple-Flashcards/bdbec74e6047e8ad5fab16d9a85081e8dc4d8711/app/src/main/java/com/randomappsinc/simpleflashcards/ocr/OcrTextSelectionAdapter.java",
"visit_date": "2022-02-17T20:07:16.470019",
"added": "2024-11-19T00:37:39.893860+00:00",
"created": "2019-08-27T05:19:22",
"int_score": 3,
"score": 2.578125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0039.json.gz"
}
|
package com.panelcomposer.enumerations;
/**
File generated using Kroki EnumGenerator
@Author MiloradFilipovic
Creation date: 14.06.2013 13:02:07h
**/
public enum PaymentMethodPaymentEnum {
_EXCHANGING(" Exchanging"),
PROVISIONING("Provisioning");
String label;
PaymentMethodPaymentEnum() {
}
PaymentMethodPaymentEnum(String label) {
this.label = label;
}
}
|
0b1137fcf88bcbd063593687fbd1b389f88d402c
|
{
"blob_id": "0b1137fcf88bcbd063593687fbd1b389f88d402c",
"branch_name": "refs/heads/master",
"committer_date": "2013-06-21T10:35:57",
"content_id": "1b7628f3059fff1cad2df2411c1a6601c243f677",
"detected_licenses": [
"MIT"
],
"directory_id": "7c1a5466ac8eb5ecabf66711f0c04914a2a9fe67",
"extension": "java",
"filename": "PaymentMethodPaymentEnum.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 413,
"license": "MIT",
"license_type": "permissive",
"path": "/SwingApp/src/com/panelcomposer/enumerations/PaymentMethodPaymentEnum.java",
"provenance": "stack-edu-0029.json.gz:756567",
"repo_name": "djuka88/KROKI-integracija",
"revision_date": "2013-06-21T10:35:57",
"revision_id": "226ba003add49c8e35b35c77c6a4542aa5d9682c",
"snapshot_id": "55d4cae3bbdf755483af479e561e8379635819c8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/djuka88/KROKI-integracija/226ba003add49c8e35b35c77c6a4542aa5d9682c/SwingApp/src/com/panelcomposer/enumerations/PaymentMethodPaymentEnum.java",
"visit_date": "2020-12-24T09:39:13.825895",
"added": "2024-11-19T01:36:27.967104+00:00",
"created": "2013-06-21T10:35:57",
"int_score": 2,
"score": 2.3125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0047.json.gz"
}
|
/*
* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.registry.deployment.synchronizer.services;
import org.apache.axiom.om.OMElement;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.deployment.synchronizer.DeploymentSynchronizationManager;
import org.wso2.carbon.deployment.synchronizer.DeploymentSynchronizer;
import org.wso2.carbon.registry.common.eventing.RegistryEvent;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import javax.xml.namespace.QName;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* This service is used to receive repository update event notifications for the auto checkout
* activities. The message format of the events is similar to the update notifications generated
* by the governance registry. Therefore it integrates out of the box with the registry based
* repository.
*/
public class AutoCheckoutService {
private static final Log log = LogFactory.getLog(AutoCheckoutService.class);
private static final QName TIMESTAMP = new QName(RegistryEvent.REGISTRY_EVENT_NS, "Timestamp");
private static final QName DETAILS = new QName(RegistryEvent.REGISTRY_EVENT_NS, "Details");
private static final QName SESSION = new QName(RegistryEvent.REGISTRY_EVENT_NS, "Session");
private static final QName TENANT = new QName(RegistryEvent.REGISTRY_EVENT_NS, "TenantId");
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
public void notifyUpdate(OMElement element) {
if (log.isDebugEnabled()) {
log.debug("Received new event: " + element);
}
OMElement timestampElement = element.getFirstChildWithName(TIMESTAMP);
if (timestampElement == null) {
log.warn("Timestamp element not available in the event");
return;
}
OMElement detailElement = element.getFirstChildWithName(DETAILS);
OMElement sessionElement = detailElement.getFirstChildWithName(SESSION);
OMElement tenantElement = sessionElement.getFirstChildWithName(TENANT);
if (tenantElement == null) {
log.warn("Tenant ID not available in the event");
return;
}
String timestamp = timestampElement.getText();
int tenantId = Integer.parseInt(tenantElement.getText());
DeploymentSynchronizationManager syncManager = DeploymentSynchronizationManager.getInstance();
// TODO: Implement an alternative way to get the file path
String filePath = MultitenantUtils.getAxis2RepositoryPath(tenantId);
DeploymentSynchronizer synchronizer = syncManager.getSynchronizer(filePath);
if (synchronizer == null || !synchronizer.isAutoCheckout()) {
log.warn("Unable to find the synchronizer for the file path: " + filePath);
return;
}
try {
Date date = DATE_FORMAT.parse(timestamp);
synchronizer.requestCheckout(date.getTime());
} catch (ParseException e) {
log.error("Error while parsing the registry event time stamp: " + timestamp, e);
}
}
}
|
48c3038ce618509b3781d233de616b822d661c1d
|
{
"blob_id": "48c3038ce618509b3781d233de616b822d661c1d",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-27T06:26:02",
"content_id": "32ddd0699045c47826156bb3feb40f84fda57757",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "0bff529c184813c9d38e67287dc09314679ea150",
"extension": "java",
"filename": "AutoCheckoutService.java",
"fork_events_count": 195,
"gha_created_at": "2014-01-21T11:42:25",
"gha_event_created_at": "2023-08-10T04:37:32",
"gha_language": "Java",
"gha_license_id": "Apache-2.0",
"github_id": 16100959,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 3844,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/components/registry/org.wso2.carbon.registry.deployment.synchronizer/src/main/java/org/wso2/carbon/registry/deployment/synchronizer/services/AutoCheckoutService.java",
"provenance": "stack-edu-0026.json.gz:792015",
"repo_name": "wso2/carbon-registry",
"revision_date": "2023-07-27T06:26:02",
"revision_id": "16d853878e79b833e17842c24eda684d6ac5684a",
"snapshot_id": "06083122c9f56bc82d917cbea2baad6c64d78757",
"src_encoding": "UTF-8",
"star_events_count": 44,
"url": "https://raw.githubusercontent.com/wso2/carbon-registry/16d853878e79b833e17842c24eda684d6ac5684a/components/registry/org.wso2.carbon.registry.deployment.synchronizer/src/main/java/org/wso2/carbon/registry/deployment/synchronizer/services/AutoCheckoutService.java",
"visit_date": "2023-09-05T02:46:42.536411",
"added": "2024-11-18T21:51:08.963074+00:00",
"created": "2023-07-27T06:26:02",
"int_score": 2,
"score": 2.046875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0044.json.gz"
}
|
#!/bin/env python3
#
# Copyright 2020 Associated Universities, Inc. Washington DC, USA.
#
# 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.
#
import argparse
import itertools
import re
import subprocess
import sys
import tempfile
def named_result(ln):
end_state = ln.find('\t')
end_name = ln.rfind('\t')
if end_name == end_state:
end_name = -1
if end_name != -1:
return (ln[end_state + 2:end_name], ln[0:end_state])
else:
return (ln[end_state + 2:], ln[0:end_state])
def run_test(compare_with, compare_by, test, *args):
with tempfile.TemporaryFile('w+t') as out:
cp = subprocess.run(
args=[test] + list(args), stdout=out.fileno(), stderr=out.fileno())
if cp.returncode != 0:
sys.exit(cp.returncode)
out.seek(0)
log = [l for ln in out
for l in [ln.strip()]
if len(l) > 0
and re.match("PASS|FAIL|SKIPPED", l) is not None]
if compare_with is None:
fails = map(lambda lg: lg[0:lg.find('\t')] == 'FAIL', log)
sys.exit(1 if any(fails) else 0)
elif compare_by == 'line':
eq = map(lambda lns: lns[0].strip() == lns[1],
itertools.zip_longest(compare_with, log, fillvalue=''))
sys.exit(0 if all(eq) else 1)
else:
results = dict(named_result(lg) for lg in log)
expected = dict(named_result(l) for ln in compare_with
for l in [ln.strip()]
if len(l) > 0)
eq_keys = set(results.keys()) == set(expected.keys())
eq = map(lambda k: k in expected and expected[k] == results[k],
results.keys())
sys.exit(0 if eq_keys and all(eq) else 1)
return
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Run a TestLog-based test program')
parser.add_argument(
'--compare-with',
nargs='?',
type=argparse.FileType('r'),
help='file with expected output',
metavar='FILE',
dest='compare_with')
parser.add_argument(
'--compare-by',
choices=['line', 'name'],
nargs='?',
default='name',
help='compare by line number or test name (default "%(default)s")',
metavar='line|name',
dest='compare_by')
parser.add_argument(
'test',
nargs=1,
type=argparse.FileType('r'),
help='test executable name',
metavar='TEST')
parser.add_argument(
'args',
nargs=argparse.REMAINDER,
help='test arguments',
metavar='ARGS')
args = parser.parse_args()
if 'compare_with' in args:
compare_with = args.compare_with
else:
compare_with = None
test_name = args.test[0].name
args.test[0].close()
run_test(compare_with, args.compare_by, test_name, *args.args)
|
99f4c74affcf521d70002f3d7bd71383a1834272
|
{
"blob_id": "99f4c74affcf521d70002f3d7bd71383a1834272",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-28T21:39:20",
"content_id": "00f1c314c7981fa34a90ae93d8cd63927476a379",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "a6ee7e0d154d8cc88b792d6cddf1b50d5d7e85d4",
"extension": "py",
"filename": "TestRunner.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 162762692,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3439,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/hyperion/testing/TestRunner.py",
"provenance": "stack-edu-0059.json.gz:28937",
"repo_name": "mpokorny/hyperion",
"revision_date": "2020-09-28T21:39:20",
"revision_id": "8ea5d1899ac5e2658ebe481b706430474685bb2d",
"snapshot_id": "f40884a7d90c12059d7619c8c1a385f285070b4c",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/mpokorny/hyperion/8ea5d1899ac5e2658ebe481b706430474685bb2d/hyperion/testing/TestRunner.py",
"visit_date": "2021-06-29T05:57:25.008827",
"added": "2024-11-18T22:43:26.452249+00:00",
"created": "2020-09-28T21:39:20",
"int_score": 2,
"score": 2.34375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0077.json.gz"
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import {TPromise} from 'vs/base/common/winjs.base';
import errors = require('vs/base/common/errors');
import {IMessageService} from 'vs/platform/message/common/message';
import {BaseLifecycleService} from 'vs/platform/lifecycle/common/baseLifecycleService';
import {IWindowService} from 'vs/workbench/services/window/electron-browser/windowService';
import severity from 'vs/base/common/severity';
import {ipcRenderer as ipc} from 'electron';
export class LifecycleService extends BaseLifecycleService {
constructor(
private messageService: IMessageService,
private windowService: IWindowService
) {
super();
this.registerListeners();
}
private registerListeners(): void {
let windowId = this.windowService.getWindowId();
// Main side indicates that window is about to unload, check for vetos
ipc.on('vscode:beforeUnload', (event, reply: { okChannel: string, cancelChannel: string }) => {
let veto = this.beforeUnload();
if (typeof veto === 'boolean') {
ipc.send(veto ? reply.cancelChannel : reply.okChannel, windowId);
}
else {
veto.done(v => ipc.send(v ? reply.cancelChannel : reply.okChannel, windowId));
}
});
}
private beforeUnload(): boolean|TPromise<boolean> {
let veto = this.vetoShutdown();
if (typeof veto === 'boolean') {
return this.handleVeto(veto);
}
else {
return veto.then(v => this.handleVeto(v));
}
}
private handleVeto(veto: boolean): boolean {
if (!veto) {
try {
this.fireShutdown();
} catch (error) {
errors.onUnexpectedError(error); // unexpected program error and we cause shutdown to cancel in this case
return false;
}
}
return veto;
}
private vetoShutdown(): boolean|TPromise<boolean> {
let participants = this.beforeShutdownParticipants;
let vetoPromises: TPromise<void>[] = [];
let hasPromiseWithVeto = false;
for (let i = 0; i < participants.length; i++) {
let participantVeto = participants[i].beforeShutdown();
if (participantVeto === true) {
return true; // return directly when any veto was provided
}
else if (participantVeto === false) {
continue; // skip
}
// We have a promise
let vetoPromise = (<TPromise<boolean>>participantVeto).then(veto => {
if (veto) {
hasPromiseWithVeto = true;
}
}, (error) => {
hasPromiseWithVeto = true;
this.messageService.show(severity.Error, errors.toErrorMessage(error));
});
vetoPromises.push(vetoPromise);
}
if (vetoPromises.length === 0) {
return false; // return directly when no veto was provided
}
return TPromise.join(vetoPromises).then(() => hasPromiseWithVeto);
}
}
|
2eab809fa4dd9c753d8880432812cf99c0c375c3
|
{
"blob_id": "2eab809fa4dd9c753d8880432812cf99c0c375c3",
"branch_name": "refs/heads/master",
"committer_date": "2021-09-19T19:24:10",
"content_id": "bc1de9b6110d1cd091277edbd8f3a938cd6c9a57",
"detected_licenses": [
"MIT"
],
"directory_id": "3a744c64aeda70c5322312db4117072db3e299ed",
"extension": "ts",
"filename": "lifecycleService.ts",
"fork_events_count": 0,
"gha_created_at": "2016-02-16T19:41:59",
"gha_event_created_at": "2023-06-21T04:40:50",
"gha_language": "TypeScript",
"gha_license_id": "MIT",
"github_id": 51863104,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 3001,
"license": "MIT",
"license_type": "permissive",
"path": "/src/vs/workbench/services/lifecycle/electron-browser/lifecycleService.ts",
"provenance": "stack-edu-0073.json.gz:152028",
"repo_name": "javifelices/vscode",
"revision_date": "2021-09-19T19:24:10",
"revision_id": "f9e3147368b8926cdb62555f44534088fb3d9616",
"snapshot_id": "834151ebc5f70572a6deb349f52b0b821723976b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/javifelices/vscode/f9e3147368b8926cdb62555f44534088fb3d9616/src/vs/workbench/services/lifecycle/electron-browser/lifecycleService.ts",
"visit_date": "2023-07-06T14:09:22.437343",
"added": "2024-11-19T00:53:57.173393+00:00",
"created": "2021-09-19T19:24:10",
"int_score": 2,
"score": 2,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0091.json.gz"
}
|
using System.Windows;
using System.Windows.Controls;
namespace Logitech.Windows
{
#region IZoomElement
/// <summary>
/// Represent common interface for FlowDocumentScrollViewer and FlowDocumentPageViewer classes
/// </summary>
public interface IZoomElement : IFrameworkLevelElement
{
bool CanIncreaseZoom { get; }
bool CanDecreaseZoom { get; }
double MinZoom { get; set; }
double MaxZoom { get; set; }
double Zoom { get; set; }
double ZoomIncrement { get; set; }
void IncreaseZoom();
void DecreaseZoom();
}
#endregion
#region ZoomElementFactory
/// <summary>
/// Acts as a factory for FlowDocumentScrollViewerProxy and FlowDocumentPageViewerProxy
/// </summary>
public abstract class ZoomElementFactory : FrameworkLevelElementFactory
{
#region Instance
#region Initialization
protected ZoomElementFactory(DependencyObject proxiedObject) : base(proxiedObject)
{
}
#endregion
#endregion
#region Static
public new static IZoomElement FromElement(DependencyObject element)
{
var viewer = element as FlowDocumentScrollViewer;
if (viewer != null) return new FlowDocumentScrollViewerProxy(viewer);
var proxied = element as FlowDocumentPageViewer;
return proxied != null ? new FlowDocumentPageViewerProxy(proxied) : null;
}
#endregion
#region FlowDocumentScrollViewerProxy
protected class FlowDocumentScrollViewerProxy : FrameworkElementProxy, IZoomElement
{
#region Initialization
public FlowDocumentScrollViewerProxy(FlowDocumentScrollViewer proxied) : base(proxied)
{
}
#endregion
#region Helpers
private FlowDocumentScrollViewer Handle => Proxied as FlowDocumentScrollViewer;
#endregion
#region IZoomElement
#region Queries
public bool CanIncreaseZoom => Handle.CanIncreaseZoom;
public bool CanDecreaseZoom => Handle.CanDecreaseZoom;
#endregion
#region Properties
public double MinZoom
{
get { return Handle.MinZoom; }
set { Handle.MinZoom = value; }
}
public double MaxZoom
{
get { return Handle.MaxZoom; }
set { Handle.MaxZoom = value; }
}
public double Zoom
{
get { return Handle.Zoom; }
set { Handle.Zoom = value; }
}
public double ZoomIncrement
{
get { return Handle.ZoomIncrement; }
set { Handle.ZoomIncrement = value; }
}
#endregion
#region Methods
public void IncreaseZoom()
{
Handle.IncreaseZoom();
}
public void DecreaseZoom()
{
Handle.DecreaseZoom();
}
#endregion
#endregion
}
#endregion
#region FlowDocumentPageViewerProxy
protected class FlowDocumentPageViewerProxy : FrameworkElementProxy, IZoomElement
{
#region Initialization
public FlowDocumentPageViewerProxy(FlowDocumentPageViewer proxied) : base(proxied)
{
}
#endregion
#region Helpers
private FlowDocumentPageViewer Handle => Proxied as FlowDocumentPageViewer;
#endregion
#region IZoomElement
#region Queries
public bool CanIncreaseZoom => Handle.CanIncreaseZoom;
public bool CanDecreaseZoom => Handle.CanDecreaseZoom;
#endregion
#region Properties
public double MinZoom
{
get { return Handle.MinZoom; }
set { Handle.MinZoom = value; }
}
public double MaxZoom
{
get { return Handle.MaxZoom; }
set { Handle.MaxZoom = value; }
}
public double Zoom
{
get { return Handle.Zoom; }
set { Handle.Zoom = value; }
}
public double ZoomIncrement
{
get { return Handle.ZoomIncrement; }
set { Handle.ZoomIncrement = value; }
}
#endregion
#region Methods
public void IncreaseZoom()
{
Handle.IncreaseZoom();
}
public void DecreaseZoom()
{
Handle.DecreaseZoom();
}
#endregion
#endregion
}
#endregion
}
#endregion
}
|
c98cb4e821aa73239ceea01cba183b766cc6beb9
|
{
"blob_id": "c98cb4e821aa73239ceea01cba183b766cc6beb9",
"branch_name": "refs/heads/master",
"committer_date": "2016-06-07T23:15:59",
"content_id": "9e623dedba9bead7ba749ab035a7cc1d1e4f5088",
"detected_licenses": [
"MIT"
],
"directory_id": "eee83c78206923e412581848ffd517ed18ac4df9",
"extension": "cs",
"filename": "ZoomElement.cs",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 60652829,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 4975,
"license": "MIT",
"license_type": "permissive",
"path": "/src/Lib/Windows/ZoomElement.cs",
"provenance": "stack-edu-0013.json.gz:312903",
"repo_name": "mike-ward/WpfMouseWheel",
"revision_date": "2016-06-07T23:15:59",
"revision_id": "5daee897d8483b78fa251e597c05b332e080819d",
"snapshot_id": "e1e0712b08c4e766ed4d17a04df76e3d4956552d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mike-ward/WpfMouseWheel/5daee897d8483b78fa251e597c05b332e080819d/src/Lib/Windows/ZoomElement.cs",
"visit_date": "2021-01-19T06:31:04.043289",
"added": "2024-11-19T03:03:09.098258+00:00",
"created": "2016-06-07T23:15:59",
"int_score": 3,
"score": 2.5625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0031.json.gz"
}
|
from django.contrib import admin
from django.contrib.auth import admin as auth_admin
from django.contrib.auth import get_user_model
from django.utils.translation import gettext_lazy as _
from farm_management.users.forms import UserChangeForm, UserCreationForm
# Models
from farm_management.users.models import Profile, PhoneCode
User = get_user_model()
class ProfileInline(admin.StackedInline):
""" Profile in-line admin por users """
model = Profile
can_delete = False
verbose_name_plural = 'profiles'
@admin.register(User)
class UserAdmin(auth_admin.UserAdmin):
form = UserChangeForm
add_form = UserCreationForm
fieldsets = (
(None, {"fields": ("username", "password")}),
(_("Personal info"), {"fields": ("name", "email", "phone_number", "is_verified")}),
(
_("Permissions"),
{
"fields": (
"is_active",
"is_staff",
"is_superuser",
"groups",
"user_permissions",
),
},
),
(_("Important dates"), {"fields": ("last_login", "date_joined")}),
)
inlines = (ProfileInline,)
list_display = ["username", "name", "is_superuser", "is_verified"]
search_fields = ["name"]
@admin.register(Profile)
class ProfileAdmin(admin.ModelAdmin):
"""Profile model admin."""
list_display = ('user', 'picture', 'biography')
search_fields = ('user__username', 'user__email', 'user__name')
fieldsets = (
('Profile', {
'fields': (
('user', 'picture'),
('biography')
)
}),
('Metadata', {
'fields': (('created', 'modified'),),
})
)
readonly_fields = ('created', 'modified')
@admin.register(PhoneCode)
class PhoneCodeAdmin(admin.ModelAdmin):
"""Profile model admin."""
list_display = ('user', 'phone_code', 'is_verified')
search_fields = ('user__username', 'user__email', 'user__name')
fieldsets = (
('PhoneCode', {
'fields': (
('user', 'phone_code'),
)
}),
('Metadata', {
'fields': (('created', 'modified'),),
})
)
readonly_fields = ('user', 'phone_code', 'created', 'modified')
|
9cf84a4984aad35bc843e8dc78335e0746eb02d0
|
{
"blob_id": "9cf84a4984aad35bc843e8dc78335e0746eb02d0",
"branch_name": "refs/heads/main",
"committer_date": "2021-09-01T04:22:59",
"content_id": "97f9dd36b726177dc83c385e4242715a8e11629b",
"detected_licenses": [
"MIT"
],
"directory_id": "6fa42c2dd3d2fad482e354495ee15616784425e8",
"extension": "py",
"filename": "admin.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 384026009,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2350,
"license": "MIT",
"license_type": "permissive",
"path": "/farm_management/users/admin.py",
"provenance": "stack-edu-0056.json.gz:549087",
"repo_name": "alexanders0/farm-management",
"revision_date": "2021-09-01T04:22:59",
"revision_id": "53ed821bbbed312848cf331f8f961ef16c59fb99",
"snapshot_id": "ccf74f9a9d99f4d20173e360e6f776288ce636f3",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/alexanders0/farm-management/53ed821bbbed312848cf331f8f961ef16c59fb99/farm_management/users/admin.py",
"visit_date": "2023-07-18T08:51:20.876231",
"added": "2024-11-18T22:01:08.299291+00:00",
"created": "2021-09-01T04:22:59",
"int_score": 2,
"score": 2.0625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0074.json.gz"
}
|
package ru.javawebinar.basejava;
import ru.javawebinar.basejava.model.*;
import java.time.LocalDate;
import java.util.ArrayList;
public class ResumeTestData {
public static void main(String[] args) {
Resume test = new Resume("Alexander Smirnov");
for (ContactType element : ContactType.values()) {
test.getContacts().put(element, "something info");
}
for (SectionType element : SectionType.values()) {
if (element.name().equals("PERSONAL") || element.name().equals("OBJECTIVE")) {
StringSection elementInfo = new StringSection("simpleInfo");
test.getPersonInfo().put(element, elementInfo);
}
if (element.name().equals("ACHIEVEMENTS") || element.name().equals("QUALIFICATION")) {
ListSection elementInfo = new ListSection(new ArrayList<>());
elementInfo.addItem("someListInfo");
test.getPersonInfo().put(element, elementInfo);
}
if (element.name().equals("EXPERIENCE") || element.name().equals("EDUCATION")) {
OrganizationSection elementInfo = new OrganizationSection(new ArrayList<>());
elementInfo.addOrganization(new Organization(new Link("someOrganizatiion", null), new Organization.Position(
"someTitle", LocalDate.of(1, 1, 1), LocalDate.of(2, 2, 2), "someDescription")));
test.getPersonInfo().put(element, elementInfo);
}
}
System.out.println(test.toString());
}
}
|
a131c80b8e563d774e993932ac5985e5ad08a14e
|
{
"blob_id": "a131c80b8e563d774e993932ac5985e5ad08a14e",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-05T18:54:27",
"content_id": "bee6018d52b68bac77ec332efb73e1d25e5ef96b",
"detected_licenses": [],
"directory_id": "7358c710616b68ad374cb09fc3d1cdb46853fda1",
"extension": "java",
"filename": "ResumeTestData.java",
"fork_events_count": 0,
"gha_created_at": "2019-07-14T19:46:52",
"gha_event_created_at": "2019-07-17T14:47:39",
"gha_language": "Java",
"gha_license_id": "Apache-2.0",
"github_id": 196876897,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1569,
"license": "",
"license_type": "permissive",
"path": "/src/ru/javawebinar/basejava/ResumeTestData.java",
"provenance": "stack-edu-0019.json.gz:377833",
"repo_name": "memphis35/basejava",
"revision_date": "2020-08-05T18:54:27",
"revision_id": "0c1af313955506ed3765e80d39b08e76c8374eed",
"snapshot_id": "46066a5614ff1df1a8bcd0ee8c55326928bda598",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/memphis35/basejava/0c1af313955506ed3765e80d39b08e76c8374eed/src/ru/javawebinar/basejava/ResumeTestData.java",
"visit_date": "2021-07-16T09:32:31.113969",
"added": "2024-11-18T21:03:37.663780+00:00",
"created": "2020-08-05T18:54:27",
"int_score": 3,
"score": 2.90625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0037.json.gz"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.