hexsha stringlengths 40 40 | size int64 5 1.05M | ext stringclasses 98
values | lang stringclasses 21
values | max_stars_repo_path stringlengths 3 945 | max_stars_repo_name stringlengths 4 118 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 368k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 945 | max_issues_repo_name stringlengths 4 118 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 134k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 945 | max_forks_repo_name stringlengths 4 135 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 5 1.05M | avg_line_length float64 1 1.03M | max_line_length int64 2 1.03M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
40c4c9de90fca80240c7e19d6e6bc48e679fac34 | 303 | py | Python | bagua/torch_api/contrib/__init__.py | Youhe-Jiang/bagua | b404eda6574b48e0642b9a3160f1cc49c3f91737 | [
"MIT"
] | null | null | null | bagua/torch_api/contrib/__init__.py | Youhe-Jiang/bagua | b404eda6574b48e0642b9a3160f1cc49c3f91737 | [
"MIT"
] | null | null | null | bagua/torch_api/contrib/__init__.py | Youhe-Jiang/bagua | b404eda6574b48e0642b9a3160f1cc49c3f91737 | [
"MIT"
] | null | null | null | from .fused_optimizer import FusedOptimizer # noqa: F401
from .load_balancing_data_loader import ( # noqa: F401
LoadBalancingDistributedSampler,
LoadBalancingDistributedBatchSampler,
)
from .cache_loader import CacheLoader # noqa: F401
from .cached_dataset import CachedDataset # noqa: F401
| 37.875 | 57 | 0.805281 |
5b6ffe4567fa836d75bf35bbc07d1fd5d7e4c3a0 | 912 | sql | SQL | migrations/20190224124720_users.up.sql | vedhavyas/cortex | 2988c879d5db9b632c36a18c27e67fc5e3c70b43 | [
"Apache-2.0"
] | 1 | 2019-05-22T12:13:07.000Z | 2019-05-22T12:13:07.000Z | migrations/20190224124720_users.up.sql | vedhavyas/cortex | 2988c879d5db9b632c36a18c27e67fc5e3c70b43 | [
"Apache-2.0"
] | null | null | null | migrations/20190224124720_users.up.sql | vedhavyas/cortex | 2988c879d5db9b632c36a18c27e67fc5e3c70b43 | [
"Apache-2.0"
] | null | null | null | CREATE OR REPLACE FUNCTION update_timestamp()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = now();
RETURN NEW;
END;
$$ language 'plpgsql';
CREATE EXTENSION if not exists citext;
CREATE TYPE user_type AS ENUM ('user', 'guest');
CREATE TABLE IF NOT EXISTS Users (
id BIGSERIAL PRIMARY KEY NOT NULL,
username citext UNIQUE NOT NULL check (length(username) <= 255),
email citext UNIQUE,
salt VARCHAR UNIQUE NOT NULL,
password VARCHAR NOT NULL,
type user_type NOT NULL DEFAULT 'user',
active BOOLEAN DEFAULT TRUE NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT current_timestamp NOT NULL,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT current_timestamp NOT NULL
);
CREATE TRIGGER user_timestamp BEFORE INSERT OR UPDATE on users FOR EACH ROW EXECUTE PROCEDURE update_timestamp();
CREATE UNIQUE INDEX users_username ON users (username);
CREATE UNIQUE INDEX users_email ON users (email); | 31.448276 | 113 | 0.77193 |
164638c47a26d687f3c69562a9317df1f1755d77 | 236 | ts | TypeScript | src/context/BlogContext.ts | paolotiu17/blog_client | f29432af56c4be90b789f7eb62b92cba60aa1ca9 | [
"MIT"
] | null | null | null | src/context/BlogContext.ts | paolotiu17/blog_client | f29432af56c4be90b789f7eb62b92cba60aa1ca9 | [
"MIT"
] | null | null | null | src/context/BlogContext.ts | paolotiu17/blog_client | f29432af56c4be90b789f7eb62b92cba60aa1ca9 | [
"MIT"
] | null | null | null | import { IBlog } from './../types';
import { createContext } from 'react';
export const BlogContext = createContext<{
setBlogs?: React.Dispatch<React.SetStateAction<IBlog[] | null | undefined>>;
blogs?: IBlog[] | null;
}>({});
| 29.5 | 80 | 0.65678 |
166c1ad47b6fee3f01e769f85159d0a415354ed3 | 5,714 | h | C | src/transaction/log_writer.h | eido5/cubrid | f32dbe7cb90f096035c255d7b5f348438bbb5830 | [
"Apache-2.0",
"BSD-3-Clause"
] | 253 | 2016-03-12T01:03:42.000Z | 2022-03-14T08:24:39.000Z | src/transaction/log_writer.h | eido5/cubrid | f32dbe7cb90f096035c255d7b5f348438bbb5830 | [
"Apache-2.0",
"BSD-3-Clause"
] | 1,124 | 2016-03-31T03:48:58.000Z | 2022-03-31T23:44:04.000Z | src/transaction/log_writer.h | eido5/cubrid | f32dbe7cb90f096035c255d7b5f348438bbb5830 | [
"Apache-2.0",
"BSD-3-Clause"
] | 268 | 2016-03-02T06:48:44.000Z | 2022-03-04T05:17:24.000Z | /*
* Copyright 2008 Search Solution Corporation
* Copyright 2016 CUBRID Corporation
*
* 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.
*
*/
/*
* log_writer.h - DECLARATIONS FOR LOG WRITER (AT CLIENT & SERVER)
*/
#ifndef _LOG_WRITER_HEADER_
#define _LOG_WRITER_HEADER_
#ident "$Id$"
#include "client_credentials.hpp"
#include "log_archives.hpp"
#include "log_common_impl.h"
#include "log_lsa.hpp"
#include "tde.h"
#include "storage_common.h"
#if defined (SERVER_MODE)
#include "thread_compat.hpp"
#endif // SERVER_MODE
#include <stdio.h>
typedef struct logwr_context LOGWR_CONTEXT;
struct logwr_context
{
int rc;
int last_error;
bool shutdown;
};
enum logwr_mode
{
LOGWR_MODE_ASYNC = 1,
LOGWR_MODE_SEMISYNC,
LOGWR_MODE_SYNC
};
typedef enum logwr_mode LOGWR_MODE;
#define LOGWR_COPY_FROM_FIRST_PHY_PAGE_MASK (0x80000000)
#if defined(CS_MODE)
enum logwr_action
{
LOGWR_ACTION_NONE = 0x00,
LOGWR_ACTION_DELAYED_WRITE = 0x01,
LOGWR_ACTION_ASYNC_WRITE = 0x02,
LOGWR_ACTION_HDR_WRITE = 0x04,
LOGWR_ACTION_ARCHIVING = 0x08
};
typedef enum logwr_action LOGWR_ACTION;
typedef struct logwr_global LOGWR_GLOBAL;
struct logwr_global
{
LOG_HEADER hdr;
LOG_PAGE *loghdr_pgptr;
char db_name[PATH_MAX];
char *hostname;
char log_path[PATH_MAX];
char loginf_path[PATH_MAX];
char active_name[PATH_MAX];
int append_vdes;
char *logpg_area;
int logpg_area_size;
int logpg_fill_size;
LOG_PAGE **toflush;
int max_toflush;
int num_toflush;
LOGWR_MODE mode;
LOGWR_ACTION action;
LOG_PAGEID last_chkpt_pageid;
LOG_PAGEID last_recv_pageid;
LOG_PAGEID last_arv_fpageid;
LOG_PAGEID last_arv_lpageid;
int last_arv_num;
bool force_flush;
struct timeval last_flush_time;
/* background log archiving info */
BACKGROUND_ARCHIVING_INFO bg_archive_info;
char bg_archive_name[PATH_MAX];
/* original next logical page to archive */
LOG_PAGEID ori_nxarv_pageid;
/* start pageid */
LOG_PAGEID start_pageid;
bool reinit_copylog;
};
#define LOGWR_AT_NEXT_ARCHIVE_PAGE_ID(pageid) \
(logwr_to_physical_pageid(pageid) == logwr_Gl.hdr.nxarv_phy_pageid)
#define LOGWR_IS_ARCHIVE_PAGE(pageid) \
((pageid) != LOGPB_HEADER_PAGE_ID && (pageid) < logwr_Gl.hdr.nxarv_pageid)
#define LOGWR_AT_SERVER_ARCHIVING() \
(LOGWR_AT_NEXT_ARCHIVE_PAGE_ID(logwr_Gl.hdr.append_lsa.pageid) \
&& (logwr_Gl.hdr.eof_lsa.pageid < logwr_Gl.hdr.append_lsa.pageid))
extern LOGWR_GLOBAL logwr_Gl;
extern void logwr_flush_header_page (void);
extern int logwr_write_log_pages (void);
extern int logwr_set_hdr_and_flush_info (void);
#if !defined(WINDOWS)
extern int logwr_copy_log_header_check (const char *db_name, bool verbose, LOG_LSA * master_eof_lsa);
#endif /* !WINDOWS */
#else /* !CS_MODE = SERVER_MODE || SA_MODE */
enum logwr_status
{
LOGWR_STATUS_WAIT,
LOGWR_STATUS_FETCH,
LOGWR_STATUS_DONE,
LOGWR_STATUS_DELAY,
LOGWR_STATUS_ERROR
};
typedef enum logwr_status LOGWR_STATUS;
typedef struct logwr_entry LOGWR_ENTRY;
struct logwr_entry
{
THREAD_ENTRY *thread_p;
LOG_PAGEID fpageid;
LOGWR_MODE mode;
LOGWR_STATUS status;
LOG_LSA eof_lsa;
LOG_LSA last_sent_eof_lsa;
LOG_LSA tmp_last_sent_eof_lsa;
INT64 start_copy_time;
bool copy_from_first_phy_page;
LOGWR_ENTRY *next;
};
typedef struct logwr_info LOGWR_INFO;
struct logwr_info
{
LOGWR_ENTRY *writer_list;
pthread_mutex_t wr_list_mutex;
pthread_cond_t flush_start_cond;
pthread_mutex_t flush_start_mutex;
pthread_cond_t flush_wait_cond;
pthread_mutex_t flush_wait_mutex;
pthread_cond_t flush_end_cond;
pthread_mutex_t flush_end_mutex;
bool skip_flush;
bool flush_completed;
bool is_init;
/* to measure the time spent by the last LWT delaying LFT */
bool trace_last_writer;
CLIENTIDS last_writer_client_info;
INT64 last_writer_elapsed_time;
// *INDENT-OFF*
logwr_info ()
: writer_list (NULL)
, wr_list_mutex PTHREAD_MUTEX_INITIALIZER
, flush_start_cond PTHREAD_COND_INITIALIZER
, flush_start_mutex PTHREAD_MUTEX_INITIALIZER
, flush_wait_cond PTHREAD_COND_INITIALIZER
, flush_wait_mutex PTHREAD_MUTEX_INITIALIZER
, flush_end_cond PTHREAD_COND_INITIALIZER
, flush_end_mutex PTHREAD_MUTEX_INITIALIZER
, skip_flush (false)
, flush_completed (false)
, is_init (false)
, trace_last_writer (false)
, last_writer_client_info ()
, last_writer_elapsed_time (0)
{
}
// *INDENT-ON*
};
#endif /* !CS_MODE = SERVER_MODE || SA_MODE */
extern bool logwr_force_shutdown (void);
extern int logwr_copy_log_file (const char *db_name, const char *log_path, int mode, INT64 start_page_id);
extern LOG_PHY_PAGEID logwr_to_physical_pageid (LOG_PAGEID logical_pageid);
extern const char *logwr_log_ha_filestat_to_string (enum LOG_HA_FILESTAT val);
#if 0
extern TDE_ALGORITHM logwr_get_tde_algorithm (const LOG_PAGE * log_pgptr);
extern void logwr_set_tde_algorithm (THREAD_ENTRY * thread_p, LOG_PAGE * log_pgptr, const TDE_ALGORITHM tde_algo);
#endif
#if defined(SERVER_MODE)
int xlogwr_get_log_pages (THREAD_ENTRY * thread_p, LOG_PAGEID first_pageid, LOGWR_MODE mode);
extern LOG_PAGEID logwr_get_min_copied_fpageid (void);
#endif /* SERVER_MODE */
#endif /* _LOG_WRITER_HEADER_ */
| 26.826291 | 114 | 0.774589 |
e77c795de3b13a64df5d00acf9bc956e7e62055b | 16 | js | JavaScript | external/esprima/test_fixtures/comment/migrated_0037.js | exced/hermes | c53fbe3f27677d5cda2a0c5b4e79e429eb5cd9e6 | [
"MIT"
] | 20,996 | 2015-01-01T13:51:47.000Z | 2022-03-31T17:44:01.000Z | external/esprima/test_fixtures/comment/migrated_0037.js | exced/hermes | c53fbe3f27677d5cda2a0c5b4e79e429eb5cd9e6 | [
"MIT"
] | 8,315 | 2015-01-01T19:56:43.000Z | 2022-03-31T15:58:10.000Z | external/esprima/test_fixtures/comment/migrated_0037.js | exced/hermes | c53fbe3f27677d5cda2a0c5b4e79e429eb5cd9e6 | [
"MIT"
] | 2,338 | 2015-01-05T03:28:26.000Z | 2022-03-26T20:40:56.000Z | var x = 1<!--foo | 16 | 16 | 0.5 |
bdcbd3c07ba84cdcc26beaeb37a7b7e44450e573 | 48 | sql | SQL | MORE_JOIN/5.sql | peterrobert/SQL_SQLZOO | 227389c6b6894a89f045349f326a4eaa539b20e7 | [
"MIT"
] | 5 | 2020-04-22T15:39:41.000Z | 2020-12-04T04:58:23.000Z | MORE_JOIN/5.sql | peterrobert/SQL_SQLZOO | 227389c6b6894a89f045349f326a4eaa539b20e7 | [
"MIT"
] | null | null | null | MORE_JOIN/5.sql | peterrobert/SQL_SQLZOO | 227389c6b6894a89f045349f326a4eaa539b20e7 | [
"MIT"
] | null | null | null | SELECT id
FROM movie
WHERE title = 'Casablanca' | 16 | 26 | 0.770833 |
3d238d6a6e35dd9449ab92eabfd502e8e7e9c381 | 1,187 | go | Go | config/config.go | patarra/jira-todo-sync | 736a1bb8b5a76894138a8bd3b0f37a85d10871ae | [
"MIT"
] | null | null | null | config/config.go | patarra/jira-todo-sync | 736a1bb8b5a76894138a8bd3b0f37a85d10871ae | [
"MIT"
] | null | null | null | config/config.go | patarra/jira-todo-sync | 736a1bb8b5a76894138a8bd3b0f37a85d10871ae | [
"MIT"
] | null | null | null | package config
import (
"errors"
"fmt"
"github.com/spf13/viper"
"sync"
)
type JiraConfig struct {
Server string `mapstructure:"server"`
User string `mapstructure:"user"`
Password string `mapstructure:"password"`
}
type TodoistConfig struct {
Token string `mapstructure:"token"`
}
type Config struct {
Jira JiraConfig `mapstructure:"jira"`
Todoist TodoistConfig `mapstructure:"todoist"`
}
var instance Config
var once sync.Once
var initialised = false
func InitConfig(cfgFile string) (*Config, error) {
var onceErr error = nil
once.Do(func() {
viper.SetConfigFile(cfgFile)
viper.SetConfigType("toml")
if err := viper.ReadInConfig(); err != nil {
onceErr = errors.New(fmt.Sprintf("couldn't load config from %s: %s\n", cfgFile, err))
}
if err := viper.Unmarshal(&instance); err != nil {
onceErr = errors.New(fmt.Sprintf("couldn't read config: %s\n", err))
}
initialised = true
})
if onceErr == nil {
return &instance, nil
} else {
return nil, onceErr
}
}
func GetConfig() (*Config, error) {
if !initialised {
return nil, errors.New("config is not initialised yet, please call InitConfig(cfgFile)")
}
return &instance, nil
}
| 20.824561 | 90 | 0.689132 |
4088a5fea9f6b72e7b61ee7b08f9e889f462f416 | 1,032 | py | Python | _includes/code/course-schedule-ii/solution.py | rajat19/interview-questions | cb1fa382a76f2f287f1c12dd3d1fca9bfb7fa311 | [
"MIT"
] | null | null | null | _includes/code/course-schedule-ii/solution.py | rajat19/interview-questions | cb1fa382a76f2f287f1c12dd3d1fca9bfb7fa311 | [
"MIT"
] | 2 | 2022-03-01T06:30:35.000Z | 2022-03-13T07:05:50.000Z | _includes/code/course-schedule-ii/solution.py | rajat19/interview-questions | cb1fa382a76f2f287f1c12dd3d1fca9bfb7fa311 | [
"MIT"
] | 1 | 2022-02-09T12:13:36.000Z | 2022-02-09T12:13:36.000Z | from collections import defaultdict, deque
class Solution:
def findOrder(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: List[int]
"""
adj_list = defaultdict(list)
indegree = {}
for dest, src in prerequisites:
adj_list[src].append(dest)
indegree[dest] = indegree.get(dest, 0) + 1
zero_indegree_queue = deque([k for k in range(numCourses) if k not in indegree])
topological_sorted_order = []
while zero_indegree_queue:
vertex = zero_indegree_queue.popleft()
topological_sorted_order.append(vertex)
if vertex in adj_list:
for neighbor in adj_list[vertex]:
indegree[neighbor] -= 1
if indegree[neighbor] == 0:
zero_indegree_queue.append(neighbor)
return topological_sorted_order if len(topological_sorted_order) == numCourses else []
| 34.4 | 94 | 0.597868 |
b1dcf6b0dd1712542e23a3a1821ecd8f704b6446 | 320 | h | C | Ui/UiApi.h | zemo/naali | a02ee7a0547c5233579eda85dedb934b61c546ab | [
"Apache-2.0"
] | null | null | null | Ui/UiApi.h | zemo/naali | a02ee7a0547c5233579eda85dedb934b61c546ab | [
"Apache-2.0"
] | null | null | null | Ui/UiApi.h | zemo/naali | a02ee7a0547c5233579eda85dedb934b61c546ab | [
"Apache-2.0"
] | 1 | 2021-09-04T12:37:34.000Z | 2021-09-04T12:37:34.000Z | // For conditions of distribution and use, see copyright notice in license.txt
#ifndef incl_UiApi_h
#define incl_UiApi_h
#if defined (_WINDOWS) && defined(UI_API_DLL)
#if defined(UI_API_EXPORTS)
#define UI_API __declspec(dllexport)
#else
#define UI_API __declspec(dllimport)
#endif
#else
#define UI_API
#endif
#endif
| 18.823529 | 78 | 0.790625 |
d253dd16ffe83e3d0be3845d62c57e7b2f6af64c | 5,032 | php | PHP | resources/views/frontend/donate.blade.php | hridoy-roy/mofa | 9d9f46fedc1cff8256d83f17920da0ff41620954 | [
"MIT"
] | 1 | 2022-03-01T18:13:35.000Z | 2022-03-01T18:13:35.000Z | resources/views/frontend/donate.blade.php | hridoy-roy/mofa | 9d9f46fedc1cff8256d83f17920da0ff41620954 | [
"MIT"
] | null | null | null | resources/views/frontend/donate.blade.php | hridoy-roy/mofa | 9d9f46fedc1cff8256d83f17920da0ff41620954 | [
"MIT"
] | null | null | null | @extends('layouts.frontend.app')
@section('nev_sub')
@endsection
@section('main-section')
<div id="page" class="site">
<div id="content" class="site-content" style="margin-top: 141px;">
<div class="textured-bg">
<div class="container donate__page">
<h1 class="donate__title">
From all of us at MOPA:<br>
Thank you for your generous donation! </h1>
<section class="donate__content">
<p>Your support increases access to the arts and teaches visual literacy through programs and
exhibitions that empower communities.</p>
</section>
</div>
<section class="donate__donation-type">
<div class="donate__donation-type-wrapper" style="max-height: 500px;">
<article data-donation="Donate Now">
<div>
<span class="donate__donation-heading">Let The Lens Tell Your Story</span>
<span class="donate__donation-value">Donate Now</span>
<a class="mopa-btn mopa-btn--gradient mopa-btn--fixed-width" href="#" target="_blank"
rel="noopener noreferrer">Donate</a>
</div>
<picture>
<img alt="" class="attachment-full size-full ls-is-cached lazyloaded"
src="https://mopa.org/wp-content/uploads/2021/10/Tim_Hardy-wide.jpg" width="100%"
height="auto">
</picture>
</article>
</div>
</section>
<div class="container donate__page">
<section class="donate__content-block">
<h2>More Ways to Give</h2>
<div class="donate__content-block-items">
<article>
<h3>Legacy Giving</h3>
<p>One easy way to include the Museum in your estate plan is to name MOPA as a beneficiary
of your of your retirement plan, IRA, or life insurance policy.</p>
<a class="mopa-btn mopa-btn--hollow mopa-btn--fixed-width" href="#">Learn more</a>
</article>
<article>
<h3>Gifts of Stock</h3>
<p>To make a charitable contribution of securities, please contact Deputy Director Vivienne
Esrig at 619.238.7559 extension 205 or esrig@mopa.org.</p>
<a class="mopa-btn mopa-btn--hollow mopa-btn--fixed-width" href="#">Learn more</a>
</article>
<article>
<h3>Sponsor a Program</h3>
<p>MOPA relies on customized sponsorships from our corporate community to help bring
world-class exhibitions, learning and film programming year-round to San Diego and the
world.</p>
<a class="mopa-btn mopa-btn--hollow mopa-btn--fixed-width" href="#">Learn more</a>
</article>
<article>
<h3>Volunteer</h3>
<p>For your and our staff’s safety, we are currently not taking new volunteers. Please check
back later.</p>
</article>
</div>
<div class="contact-block-footer-text">
<p>Tax deductibility is determined to be 100%. Tax ID: 95-2889390.<br>
For any other questions, contact development@MOPA.org</p>
</div>
</section>
<section class="mopa-section-contact" id="mopa-section-contact">
<h2>Start a Conversation</h2>
<p>To discover more ways for your business or organization to partner with MOPA, please contact our
development team.</p>
<div class="mopa-section-contact__wrapper">
<a class="mopa-section-contact__phone" href="tel:619.238.7559">
<i style="font-size: 20px;" class="bi bi-telephone-fill"></i>
<span style="margin-left: 7px;">619.238.7559</span>
</a>
<a class="mopa-section-contact__email" href="mailto:development@mopa.org">
<i style="font-size: 24px;" class="bi bi-envelope-fill"></i>
<span style="margin-left: 7px;">development@mopa.org</span>
</a>
</div>
</section>
</div>
</div>
</div>
</div>
@endsection | 55.911111 | 120 | 0.475159 |
3853bf4a5b0afd6f92ba1e13221933766ac40b47 | 232 | kt | Kotlin | CodersStrikeBack/src/main/kotlin/org/neige/codingame/codersstrikeback/Move.kt | CedrickFlocon/Codingame | 1d1204237884aac30f16084c01d9fb847eef8289 | [
"WTFPL"
] | 4 | 2017-10-07T19:36:12.000Z | 2021-11-02T19:39:21.000Z | CodersStrikeBack/src/main/kotlin/org/neige/codingame/codersstrikeback/Move.kt | CedrickFlocon/Codingame | 1d1204237884aac30f16084c01d9fb847eef8289 | [
"WTFPL"
] | null | null | null | CodersStrikeBack/src/main/kotlin/org/neige/codingame/codersstrikeback/Move.kt | CedrickFlocon/Codingame | 1d1204237884aac30f16084c01d9fb847eef8289 | [
"WTFPL"
] | 1 | 2021-11-02T19:39:24.000Z | 2021-11-02T19:39:24.000Z | package org.neige.codingame.codersstrikeback
data class Move(val coordinate: Coordinate, val thrust: String) {
override fun toString(): String {
return "${coordinate.x.toInt()} ${coordinate.y.toInt()} $thrust"
}
} | 25.777778 | 72 | 0.689655 |
af6d7764a4d7c7e544c85ae8fb35bdae9564b19e | 966 | gemspec | Ruby | block_editor.gemspec | yamasolutions/block-editor | 3454f449b22a041191a6eee53c645e0d764841d3 | [
"MIT"
] | 12 | 2021-04-07T12:47:40.000Z | 2022-01-13T03:45:03.000Z | block_editor.gemspec | yamasolutions/block-editor | 3454f449b22a041191a6eee53c645e0d764841d3 | [
"MIT"
] | 1 | 2021-05-12T08:16:38.000Z | 2021-05-19T07:09:23.000Z | block_editor.gemspec | yamasolutions/block-editor | 3454f449b22a041191a6eee53c645e0d764841d3 | [
"MIT"
] | 4 | 2021-07-11T13:12:36.000Z | 2022-03-29T21:18:39.000Z | require_relative "lib/block_editor/version"
Gem::Specification.new do |spec|
spec.name = "block_editor"
spec.version = BlockEditor::VERSION
spec.authors = ["Patrick Lindsay"]
spec.email = ["patrick@yamasolutions.com"]
spec.homepage = "https://github.com/yamasolutions/block-editor"
spec.summary = "Ruby on Rails Block Editor"
spec.description = "A block editor for Ruby on Rails built from the Wordpress Gutenberg project"
spec.license = "MIT"
spec.metadata["homepage_uri"] = spec.homepage
spec.metadata["source_code_uri"] = "https://github.com/yamasolutions/block-editor"
spec.metadata["changelog_uri"] = "https://github.com/yamasolutions/block-editor/blob/master/CHANGELOG.md"
spec.files = Dir["{app,bin,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.md", "package.json", "yarn.lock", "postcss.config.js"]
spec.add_dependency "rails", "~> 6.0"
spec.add_dependency 'webpacker', '~> 5.1'
end
| 43.909091 | 140 | 0.698758 |
39c5f61747da2b9f59c548162d3faf044d30a725 | 4,770 | js | JavaScript | src/app/main/apps/scrumboard/boards/Boards.js | RobertLbebber/electr-client | d5d6c7047a3a154c64b8fe232534b9f3cfc6dfe8 | [
"Apache-2.0"
] | null | null | null | src/app/main/apps/scrumboard/boards/Boards.js | RobertLbebber/electr-client | d5d6c7047a3a154c64b8fe232534b9f3cfc6dfe8 | [
"Apache-2.0"
] | 6 | 2021-03-01T21:06:31.000Z | 2022-02-26T01:53:05.000Z | src/app/main/apps/scrumboard/boards/Boards.js | RobertLbebber/electr-client | d5d6c7047a3a154c64b8fe232534b9f3cfc6dfe8 | [
"Apache-2.0"
] | null | null | null | import React, {Component} from 'react';
import {withStyles, Typography, Icon} from '@material-ui/core';
import {fade} from '@material-ui/core/styles/colorManipulator';
import {FuseAnimateGroup, FuseAnimate} from '@fuse';
import {bindActionCreators} from 'redux';
import {Link, withRouter} from 'react-router-dom';
import {connect} from 'react-redux';
import classNames from 'classnames';
import withReducer from 'app/store/withReducer';
import * as Actions from '../store/actions';
import reducer from '../store/reducers';
const styles = theme => ({
root : {
background: theme.palette.primary.main,
color : theme.palette.getContrastText(theme.palette.primary.main)
},
board : {
cursor : 'pointer',
boxShadow : theme.shadows[0],
transitionProperty : 'box-shadow border-color',
transitionDuration : theme.transitions.duration.short,
transitionTimingFunction: theme.transitions.easing.easeInOut,
background : theme.palette.primary.dark,
color : theme.palette.getContrastText(theme.palette.primary.dark),
'&:hover' : {
boxShadow: theme.shadows[6]
}
},
newBoard: {
borderWidth: 2,
borderStyle: 'dashed',
borderColor: fade(theme.palette.getContrastText(theme.palette.primary.main), 0.6),
'&:hover' : {
borderColor: fade(theme.palette.getContrastText(theme.palette.primary.main), 0.8)
}
}
});
class Boards extends Component {
componentDidMount()
{
this.props.getBoards();
}
componentWillUnmount()
{
this.props.resetBoards();
}
render()
{
const {classes, boards, newBoard} = this.props;
return (
<div className={classNames(classes.root, "flex flex-grow flex-no-shrink flex-col items-center")}>
<div className="flex flex-grow flex-no-shrink flex-col items-center container px-16 md:px-24">
<FuseAnimate>
<Typography className="mt-44 sm:mt-88 sm:py-24 text-32 sm:text-40 font-300" color="inherit">Scrumboard App</Typography>
</FuseAnimate>
<div>
<FuseAnimateGroup
className="flex flex-wrap w-full justify-center py-32 px-16"
enter={{
animation: "transition.slideUpBigIn",
duration : 300
}}
>
{boards.map(board => (
<div className="w-224 h-224 p-16" key={board.id}>
<Link
to={'/apps/scrumboard/boards/' + board.id + '/' + board.uri}
className={classNames(classes.board, "flex flex-col items-center justify-center w-full h-full rounded py-24")}
role="button"
>
<Icon className="text-56">assessment</Icon>
<Typography className="text-16 font-300 text-center pt-16 px-32" color="inherit">{board.name}</Typography>
</Link>
</div>
))}
<div className="w-224 h-224 p-16">
<div
className={classNames(classes.board, classes.newBoard, "flex flex-col items-center justify-center w-full h-full rounded py-24")}
onClick={() => newBoard()}
>
<Icon className="text-56">add_circle</Icon>
<Typography className="text-16 font-300 text-center pt-16 px-32" color="inherit">Add new board</Typography>
</div>
</div>
</FuseAnimateGroup>
</div>
</div>
</div>
);
}
}
function mapDispatchToProps(dispatch)
{
return bindActionCreators({
getBoards : Actions.getBoards,
resetBoards: Actions.resetBoards,
newBoard : Actions.newBoard
}, dispatch);
}
function mapStateToProps({scrumboardApp})
{
return {
boards: scrumboardApp.boards
}
}
export default withReducer('scrumboardApp', reducer)(withStyles(styles, {withTheme: true})(withRouter(connect(mapStateToProps, mapDispatchToProps)(Boards))));
| 39.421488 | 164 | 0.510273 |
96755aaf8b844e7086ec629336693c828f6cd86f | 123 | php | PHP | resources/views/example.blade.php | metalkorshik/Arca | b8f166c3d5a0ee9960a1e48a2c5c7a059c7a622a | [
"MIT"
] | null | null | null | resources/views/example.blade.php | metalkorshik/Arca | b8f166c3d5a0ee9960a1e48a2c5c7a059c7a622a | [
"MIT"
] | null | null | null | resources/views/example.blade.php | metalkorshik/Arca | b8f166c3d5a0ee9960a1e48a2c5c7a059c7a622a | [
"MIT"
] | null | null | null | @extends('layouts.app')
@section('user-panel')
@endsection
@section('page', 'contracts')
@section('content')
@endsection | 13.666667 | 29 | 0.707317 |
3b1c839312e9e2bc379489d80f3a3d1a99f9270a | 1,636 | c | C | ports/stm32/src/runTimeStatsInit.c | ygjukim/hFramework | 994ea7550c34b4943e2fa2d5e9ca447aa555f39e | [
"MIT"
] | 33 | 2017-07-03T22:49:30.000Z | 2022-03-31T19:32:55.000Z | ports/stm32/src/runTimeStatsInit.c | ygjukim/hFramework | 994ea7550c34b4943e2fa2d5e9ca447aa555f39e | [
"MIT"
] | 6 | 2017-07-13T13:23:22.000Z | 2019-10-25T17:51:28.000Z | ports/stm32/src/runTimeStatsInit.c | ygjukim/hFramework | 994ea7550c34b4943e2fa2d5e9ca447aa555f39e | [
"MIT"
] | 17 | 2017-07-01T05:35:47.000Z | 2022-03-22T23:33:00.000Z | #include "stm32f4xx.h"
#include "FreeRTOS.h"
//=============FOR RUN TIME STATS START =================================
volatile uint32_t tim_cnt = 0;
void TIM6_DAC_IRQHandler(void)
{
// extern int tim_cnt;
tim_cnt++;
TIM_ClearITPendingBit(TIM6, TIM_IT_Update);
} /* TIM2_IRQHandler */
// to generate runtime stats
void tim_config(void)
{
//sys_log("\r\nRUNTIME stats tim_config");
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
NVIC_InitTypeDef NVIC_InitStructure;
/* Enable the TIM2 gloabal Interrupt */
NVIC_InitStructure.NVIC_IRQChannel = TIM6_DAC_IRQn;
// NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
// NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY + 2;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
// /* PCLK1 = HCLK/4 */
// RCC_PCLK1Config(RCC_HCLK_Div4);
/* TIM2 clock enable */
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM6, ENABLE);
/* Time base configuration */
TIM_TimeBaseStructure.TIM_Period = 65535;
TIM_TimeBaseStructure.TIM_Prescaler = 1000;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM6, &TIM_TimeBaseStructure);
/* TIM IT enable */
TIM_ITConfig(TIM6, TIM_IT_Update, ENABLE);
TIM_Cmd(TIM6, ENABLE);
tim_cnt = 0;
TIM6->CNT = 0;
}
uint32_t get_tim(void)
{
return (tim_cnt << 16) + TIM_GetCounter(TIM6);
}
//=============FOR RUN TIME STATS END ===================================
| 24.41791 | 105 | 0.733496 |
5aa894e359b05fc0f915b3d740b6d17531117e9f | 1,681 | sql | SQL | backend/de.metas.adempiere.adempiere/migration/src/main/sql/postgresql/system/10-de.metas.adempiere/5534510_sys_gh5551_PickingTerminal_menu_names.sql | dram/metasfresh | a1b881a5b7df8b108d4c4ac03082b72c323873eb | [
"RSA-MD"
] | 1,144 | 2016-02-14T10:29:35.000Z | 2022-03-30T09:50:41.000Z | backend/de.metas.adempiere.adempiere/migration/src/main/sql/postgresql/system/10-de.metas.adempiere/5534510_sys_gh5551_PickingTerminal_menu_names.sql | vestigegroup/metasfresh | 4b2d48c091fb2a73e6f186260a06c715f5e2fe96 | [
"RSA-MD"
] | 8,283 | 2016-04-28T17:41:34.000Z | 2022-03-30T13:30:12.000Z | backend/de.metas.adempiere.adempiere/migration/src/main/sql/postgresql/system/10-de.metas.adempiere/5534510_sys_gh5551_PickingTerminal_menu_names.sql | vestigegroup/metasfresh | 4b2d48c091fb2a73e6f186260a06c715f5e2fe96 | [
"RSA-MD"
] | 441 | 2016-04-29T08:06:07.000Z | 2022-03-28T06:09:56.000Z | -- 2019-10-16T21:11:32.066Z
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_Menu SET AD_Element_ID=574217, Description='Items ready to be picked', Name='Kommissionier Terminal (v2)', WEBUI_NameBrowse=NULL, WEBUI_NameNew=NULL, WEBUI_NameNewBreadcrumb=NULL,Updated=TO_TIMESTAMP('2019-10-17 00:11:32','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_Menu_ID=541138
;
-- 2019-10-16T21:11:32.079Z
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
/* DDL */ select update_menu_translation_from_ad_element(574217)
;
-- 2019-10-16T21:11:45.323Z
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
DELETE FROM AD_Element_Trl WHERE AD_Element_ID=575796
;
-- 2019-10-16T21:11:45.330Z
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
DELETE FROM AD_Element WHERE AD_Element_ID=575796
;
-- 2019-10-16T21:17:09.847Z
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
UPDATE AD_Menu SET AD_Element_ID=574330, Description='', Name='Kommissionier Terminal', WEBUI_NameBrowse=NULL, WEBUI_NameNew=NULL, WEBUI_NameNewBreadcrumb=NULL,Updated=TO_TIMESTAMP('2019-10-17 00:17:09','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_Menu_ID=540868
;
-- 2019-10-16T21:17:09.848Z
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
/* DDL */ select update_menu_translation_from_ad_element(574330)
;
-- 2019-10-16T21:17:17.637Z
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
DELETE FROM AD_Element_Trl WHERE AD_Element_ID=574670
;
-- 2019-10-16T21:17:17.646Z
-- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator
DELETE FROM AD_Element WHERE AD_Element_ID=574670
;
| 41 | 294 | 0.797145 |
df8e0f1fdaa8498fdd9d6c663d0fae947ada1e27 | 539 | tsx | TypeScript | src/Components/Banner/Banner.tsx | CodeTheChangeUBC/OLPCWebsite | f50b55be296ba8b565413412aaeb765581e301cd | [
"MIT"
] | null | null | null | src/Components/Banner/Banner.tsx | CodeTheChangeUBC/OLPCWebsite | f50b55be296ba8b565413412aaeb765581e301cd | [
"MIT"
] | 7 | 2018-10-22T14:45:50.000Z | 2018-10-26T00:59:28.000Z | src/Components/Banner/Banner.tsx | CodeTheChangeUBC/OLPCWebsite | f50b55be296ba8b565413412aaeb765581e301cd | [
"MIT"
] | null | null | null | import * as React from 'react';
// import './Banner.css';
export const Banner = () => {
return (
<header>
O
<span className = "hide"><span className = "purple">NE</span></span>
L
<span className = "hide">APTOP</span>
P
<span className = "hide"><span className = "yellow">ER</span></span>
C
<span className = "hide"><span className = "green">HILD</span></span>
</header>
)
}
export default Banner; | 25.666667 | 84 | 0.504638 |
5f0418ca8931055500c9c7d769ecf3c076d7deb7 | 987 | ts | TypeScript | cloud_functions/functions/src/history/index.ts | viveknimkarde/firetable | f3157ba39678233246532b227b1613975edd3203 | [
"Apache-2.0"
] | 1 | 2020-03-18T04:29:13.000Z | 2020-03-18T04:29:13.000Z | cloud_functions/functions/src/history/index.ts | GourmetPro/firetable | 22fc635345cfb38b53d86e246a6cc33a4210f2a1 | [
"Apache-2.0"
] | null | null | null | cloud_functions/functions/src/history/index.ts | GourmetPro/firetable | 22fc635345cfb38b53d86e246a6cc33a4210f2a1 | [
"Apache-2.0"
] | null | null | null | import * as functions from "firebase-functions";
import * as _ from "lodash";
import { db } from "../config";
const historySnapshot = (trackedFields: string[]) => async (
change: functions.Change<FirebaseFirestore.DocumentSnapshot>
) => {
const before = change.before.data();
const after = change.after.data();
const docPath = change.after.ref.path;
if (!before || !after) return false;
const trackedChanges: any = {};
trackedFields.forEach(field => {
if (!_.isEqual(before[field], after[field]))
trackedChanges[field] = after[field];
});
if (!_.isEmpty(trackedChanges)) {
await db
.doc(docPath)
.collection("historySnapshots")
.add({ ...before, archivedAt: new Date() });
return true;
} else return false;
};
const historySnapshotFnsGenerator = collection =>
functions.firestore
.document(`${collection.name}/{docId}`)
.onUpdate(historySnapshot(collection.trackedFields));
export default historySnapshotFnsGenerator;
| 30.84375 | 62 | 0.685917 |
86c00a49c52c47b35d18100802fe2158dd8b08c2 | 740 | rs | Rust | crates/server/src/store/sqlite/config.rs | faern/trust-dns | a44e3f3e60f25ae091a9b598ee49d86dd147e152 | [
"Apache-2.0",
"MIT-0",
"MIT"
] | 2,348 | 2015-08-10T06:41:59.000Z | 2022-03-30T19:49:48.000Z | crates/server/src/store/sqlite/config.rs | faern/trust-dns | a44e3f3e60f25ae091a9b598ee49d86dd147e152 | [
"Apache-2.0",
"MIT-0",
"MIT"
] | 1,519 | 2015-09-09T20:55:52.000Z | 2022-03-31T08:03:58.000Z | crates/server/src/store/sqlite/config.rs | faern/trust-dns | a44e3f3e60f25ae091a9b598ee49d86dd147e152 | [
"Apache-2.0",
"MIT-0",
"MIT"
] | 342 | 2015-09-17T12:29:11.000Z | 2022-03-29T10:52:59.000Z | // Copyright 2015-2018 Benjamin Fry <benjaminfry -@- me.com>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
use serde::Deserialize;
/// Configuration for zone file for sqlite based zones
#[derive(Deserialize, PartialEq, Debug)]
pub struct SqliteConfig {
/// path to initial zone file
pub zone_file_path: String,
/// path to the sqlite journal file
pub journal_file_path: String,
/// Are updates allowed to this zone
#[serde(default)]
pub allow_update: bool,
}
| 35.238095 | 77 | 0.718919 |
6515124d4e3250bc474b369d4832ef055edc0d00 | 5,031 | py | Python | decomp/c/gen.py | nihilus/epanos | 998a9e3f45337df98b1bbc40b64954b079a1d4de | [
"MIT"
] | 1 | 2017-07-25T00:05:09.000Z | 2017-07-25T00:05:09.000Z | decomp/c/gen.py | nihilus/epanos | 998a9e3f45337df98b1bbc40b64954b079a1d4de | [
"MIT"
] | null | null | null | decomp/c/gen.py | nihilus/epanos | 998a9e3f45337df98b1bbc40b64954b079a1d4de | [
"MIT"
] | null | null | null | from itertools import imap, chain
from pycparser import c_generator, c_ast
from decomp import data, ida
from decomp.c import decl as cdecl, types as ep_ct
from decomp.cpu import ida as cpu_ida
XXX_INTRO_HACK = cpu_ida.ida_current_cpu().insns.support_header + '''
#include <stdint.h>
typedef union EPANOS_REG {
uint8_t u8;
int32_t i32;
uint32_t u32;
int64_t i64;
uint64_t u64;
float s;
double d;
} EPANOS_REG;
typedef struct EPANOS_ARGS {
EPANOS_REG v0;
EPANOS_REG v1;
EPANOS_REG a0;
EPANOS_REG a1;
EPANOS_REG a2;
EPANOS_REG a3;
EPANOS_REG a4;
EPANOS_REG a5;
EPANOS_REG a6;
EPANOS_REG a7;
EPANOS_REG f0;
EPANOS_REG f2;
EPANOS_REG f12;
EPANOS_REG f13;
EPANOS_REG f14;
EPANOS_REG f15;
EPANOS_REG f16;
EPANOS_REG f17;
EPANOS_REG f18;
EPANOS_REG f19;
} EPANOS_ARGS;
'''
gen_from_node = c_generator.CGenerator().visit
flatten = chain.from_iterable
def c_for_insn(ea, our_fns, extern_reg_map, stkvars):
while True:
(ea, c) = cpu_ida.ida_current_cpu().gen.fmt_insn(ea, our_fns, extern_reg_map, stkvars, from_delay=False)
yield c
if ea == ida.BADADDR:
break
def generate(ea, decl, our_fns, extern_reg_map, stkvar_map, stkvar_decls):
'''ea_t -> c_ast() -> frozenset(str) -> {str : reg_sig} ->
{str : {int : tinfo_t}} {str : [c_ast]} -> c_ast'''
try:
stkvars = stkvar_map[decl.name]
var_decls = stkvar_decls[decl.name]
except KeyError:
stkvars = {}
var_decls = []
start_ea = ida.get_func(ea).startEA
body = [XXX_STACKVAR_HACK()] + [var_decls] + [x for x in
c_for_insn(start_ea, our_fns, extern_reg_map, stkvars)]
funcdef = c_ast.FuncDef(decl, None, c_ast.Compound(flatten(body)))
return funcdef
def XXX_STACKVAR_HACK():
# XXX FIXME this will be going away once we've added elision of unnecessary
# stack variables (probably will just stick declarations into the AST)
regs = list(c_ast.Decl(x, [], [], [], c_ast.TypeDecl(x, [], c_ast.IdentifierType(['EPANOS_REG'])), None, None)
for x in
list('t%s' % str(n) for n in range(4, 8))
+ list('s%s' % str(n) for n in range(0, 8))
+ ['at', 't8', 't9', 'gp', 'sp', 'ra', 'fp', 'f1']
+ list('f%s' % str(n) for n in range(3, 12))
+ list('f%s' % str(n) for n in range(20, 32)))
regs += [c_ast.Decl('EPANOS_fp_cond', [], [], [], c_ast.TypeDecl('EPANOS_fp_cond', [], c_ast.IdentifierType(['int'])), None, None)]
return regs
def run(externs, our_fns, cpp_filter, cpp_all, decompile=True):
'''frozenset(str) -> frozenset(str) -> str -> str -> opt:bool -> [c_ast]'''
global OUR_FNS, EXTERN_REG_MAP, STKVAR_MAP # for repl convenience
OUR_FNS = our_fns
fn_segs = data.get_segs(['extern', '.text'])
rodata_segs = data.get_segs(['.rodata', '.srdata'])
data_segs = data.get_segs(['.data', '.bss'])
lit_segs = data.get_segs(['.lit4', '.lit8'])
num_lits = data.get_num_literals(lit_segs)
str_lits = data.get_str_literals(rodata_segs)
data_txt = data.get_data(data_segs, cpp_filter)
# XXX FIXME this will be going away once we've added emitting numeric and
# string constants directly at their site of use
if decompile is True:
for (k, v) in num_lits.iteritems():
ty = type(v)
if ty is ep_ct.cfloat:
print 'float %s = %s;' % (k, v)
elif ty is ep_ct.cdouble:
print 'double %s = %s;' % (k, v)
else:
raise Exception('o no')
for (k, v) in str_lits.iteritems():
print 'const char *%s = %s;' % (k, data.c_stringify(v))
protos = map(cdecl.make_internal_fn_decl, our_fns)
(lib_fns, tds) = data.get_fns_and_types(fn_segs, externs, cpp_all)
all_tds = {x.name: x for x in tds}
typedefs = cdecl.resolve_typedefs(all_tds)
EXTERN_REG_MAP = data.get_fn_arg_map(lib_fns, typedefs)
STKVAR_MAP = data.get_stkvars(our_fns)
stkvar_decls = data.make_stkvar_txt(our_fns, STKVAR_MAP, cpp_filter)
if decompile is True:
print XXX_INTRO_HACK
return gen_from_node(c_ast.FileAST(
data_txt +
protos +
list(generate(ida.loc_by_name(decl.name), decl, our_fns,
EXTERN_REG_MAP, STKVAR_MAP, stkvar_decls)
for decl in protos)))
else:
return
def repl_make_insn(ea, from_delay):
# for testing: print the C that will be generated from a line of assembly.
# note that if you ask for the ea of an insn in a delay slot, you get only
# that instruction; if you ask for a delayed instruction, you get both
try:
stkvars = STKVAR_MAP[ida.get_func_name(ea)]
except KeyError:
stkvars = {}
return list(gen_from_node(x) for x in
cpu_ida.ida_current_cpu().gen.fmt_insn(
ea, OUR_FNS, EXTERN_REG_MAP, stkvars, from_delay).c)
| 33.993243 | 135 | 0.624329 |
7f71cd62fefa40eebb9ea107e698b6ca746b7814 | 1,427 | go | Go | internal/logger/logger.go | vsdmars/actor | 7f5a8a9ca8801684a2008213435ecff4f142506c | [
"MIT"
] | null | null | null | internal/logger/logger.go | vsdmars/actor | 7f5a8a9ca8801684a2008213435ecff4f142506c | [
"MIT"
] | 4 | 2019-03-04T19:39:25.000Z | 2019-04-03T02:28:27.000Z | internal/logger/logger.go | vsdmars/actor | 7f5a8a9ca8801684a2008213435ecff4f142506c | [
"MIT"
] | null | null | null | package logger
import (
"fmt"
"os"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
var logger serviceLogger
var origLogger serviceLogger
func init() {
initLogger()
}
// LogSync sync logger output
func LogSync() {
// ignore logger Sync error
logger.Sync()
}
// SetLogger sets caller provided zap logger
//
// reset to service's default logger by passing in nil pointer
func SetLogger(l *zap.Logger) {
if l != nil {
logger.Logger = l
logger.provided = true
return
}
logger = origLogger
}
// SetLogLevel sets the service log level
//
// noop if caller provides it's own zap logger
func SetLogLevel(level zapcore.Level) {
if logger.provided {
return
}
logger.config.Level.SetLevel(level)
}
func initLogger() {
// default log level set to 'info'
atom := zap.NewAtomicLevelAt(zap.InfoLevel)
config := zap.Config{
Level: atom,
Development: false,
Sampling: &zap.SamplingConfig{
Initial: 100,
Thereafter: 100,
},
Encoding: "json", // console, json, toml
EncoderConfig: zap.NewProductionEncoderConfig(),
OutputPaths: []string{"stderr"},
ErrorOutputPaths: []string{"stderr"},
}
mylogger, err := config.Build()
if err != nil {
fmt.Printf("Initialize zap logger error: %v\n", err)
os.Exit(1)
}
logger = serviceLogger{mylogger, &config, false}
origLogger = logger
}
// GetLog gets the current logger
func GetLog() serviceLogger {
return logger
}
| 18.063291 | 62 | 0.683952 |
0eed0cf725e6dedad38742b3d2ed191c8a3f6086 | 2,909 | sql | SQL | models/sources/stg_hubspot_crm/bigquery/fivetran/stg_hubspot_crm_deals.sql | HirenBhikha-Qrious/RA_Analytics | 815579ef1c4a1bead4a0d661f513e872dc0a1813 | [
"Apache-2.0"
] | 1 | 2022-01-30T21:12:44.000Z | 2022-01-30T21:12:44.000Z | models/sources/stg_hubspot_crm/bigquery/fivetran/stg_hubspot_crm_deals.sql | HirenBhikha-Qrious/RA_Analytics | 815579ef1c4a1bead4a0d661f513e872dc0a1813 | [
"Apache-2.0"
] | 4 | 2021-11-01T18:31:22.000Z | 2021-11-15T01:32:08.000Z | models/sources/stg_hubspot_crm/bigquery/fivetran/stg_hubspot_crm_deals.sql | HirenBhikha-Qrious/RA_Analytics | 815579ef1c4a1bead4a0d661f513e872dc0a1813 | [
"Apache-2.0"
] | null | null | null | {% if target.type == 'bigquery' %}
{% if var("marketing_warehouse_deal_sources") %}
{% if 'hubspot_crm' in var("marketing_warehouse_deal_sources") %}
{% if var("stg_hubspot_crm_etl") == 'fivetran' %}
with source as (
select *
from {{ source('fivetran_hubspot_crm','deals') }}
),
hubspot_deal_company as (
select *
from {{ source('fivetran_hubspot_crm','deal_companies') }}
),
hubspot_deal_pipelines_source as (
select *
from {{ source('fivetran_hubspot_crm','pipelines') }}
)
,
hubspot_deal_property_history as (
select *
from {{ source('fivetran_hubspot_crm','property_history') }}
)
,
hubspot_deal_stages as (
select *
from {{ source('fivetran_hubspot_crm','pipeline_stages') }}
),
hubspot_deal_owners as (
SELECT *
FROM {{ source('fivetran_hubspot_crm','owners') }}
),
renamed as (
SELECT
deal_id as deal_id,
property_dealname as deal_name,
property_dealtype as deal_type,
property_description as deal_description,
deal_pipeline_stage_id as deal_pipeline_stage_id,
deal_pipeline_id as deal_pipeline_id,
is_deleted as deal_is_deleted,
property_amount as deal_amount,
owner_id as deal_owner_id,
property_amount_in_home_currency as deal_amount_local_currency,
property_closed_lost_reason as deal_closed_lost_reason,
property_closedate as deal_closed_date,
property_createdate as deal_created_date,
property_hs_lastmodifieddate as deal_last_modified_date
FROM
source
),
joined as (
select
d.deal_id,
concat('{{ var('stg_hubspot_crm_id-prefix') }}',cast(a.company_id as string)) as company_id,
d.* except (deal_id),
timestamp_millis(safe_cast(h.value as int64)) as deal_pipeline_stage_ts,
p.label as pipeline_label,
p.display_order as pipeline_display_order,
s.label as pipeline_stage_label,
s.display_order as pipeline_stage_display_order,
s.probability as pipeline_stage_close_probability_pct,
s.closed_won as pipeline_stage_closed_won,
concat(u.first_name,' ',u.last_name) as owner_full_name,
u.email as owner_email
from
renamed d
left outer join
hubspot_deal_company a
on
d.deal_id = a.deal_id
left outer join
hubspot_deal_property_history h
on
d.deal_id = h.deal_id and h.name = concat('hs_date_entered_',d.deal_pipeline_stage_id)
join
hubspot_deal_stages s
on
d.deal_pipeline_stage_id = s.stage_id
join
hubspot_deal_pipelines_source p
on
s.pipeline_id = p.pipeline_id
left outer join
hubspot_deal_owners u
on
safe_cast(d.deal_owner_id as int64) = u.owner_id
)
select * from joined
{% else %} {{config(enabled=false)}} {% endif %}
{% else %} {{config(enabled=false)}} {% endif %}
{% else %} {{config(enabled=false)}} {% endif %}
{% else %} {{config(enabled=false)}} {% endif %}
| 30.621053 | 96 | 0.698866 |
38666e3481b15ff6dda48b2b7ab948892c0d668b | 1,157 | lua | Lua | tag-vim/config/nvim/lua/config/lsp/emmet.lua | delianides/dotfiles | fa95997eb173979716344506c24fe6531319f126 | [
"MIT"
] | 1 | 2017-11-08T00:08:00.000Z | 2017-11-08T00:08:00.000Z | tag-vim/config/nvim/lua/config/lsp/emmet.lua | delianides/dotfiles | fa95997eb173979716344506c24fe6531319f126 | [
"MIT"
] | 7 | 2016-03-25T20:02:08.000Z | 2016-10-15T20:57:33.000Z | tag-vim/config/nvim/lua/config/lsp/emmet.lua | delianides/dotfiles | fa95997eb173979716344506c24fe6531319f126 | [
"MIT"
] | 1 | 2017-01-03T19:11:22.000Z | 2017-01-03T19:11:22.000Z | local lspconfig = require "lspconfig"
local configs = require "lspconfig.configs"
local servers = require "nvim-lsp-installer.servers"
local server = require "nvim-lsp-installer.server"
local path = require "nvim-lsp-installer.path"
local npm = require "nvim-lsp-installer.installers.npm"
local server_name = "emmet-language-server"
configs[server_name] = {
default_config = {
filetypes = {
"html",
"typescriptreact",
"javascriptreact",
"javascript",
"typescript",
"javascript.jsx",
"typescript.tsx",
"css",
},
root_dir = lspconfig.util.root_pattern ".git",
},
}
local root_dir = server.get_server_root_path(server_name)
-- You may also use one of the prebuilt installers (e.g., std, npm, pip3, go, gem, shell).
local my_installer = npm.packages { "@kozer/emmet-language-server" }
-- 2. (mandatory) Create an nvim-lsp-installer Server instance
local my_server = server.Server:new {
name = server_name,
root_dir = root_dir,
installer = my_installer,
default_options = {
cmd = { npm.executable(root_dir, "emmet-language-server"), "--stdio" },
},
}
servers.register(my_server)
| 28.219512 | 90 | 0.692308 |
dd5d1944b23dd5028afdc87591d0074485d2f138 | 182 | lua | Lua | resources/pausemenu-title/server_name.lua | Kyominii/HorizonRP | 0eec91919ac4d888e3a2aec244ae97214124ca17 | [
"MIT"
] | 1 | 2019-09-24T02:59:46.000Z | 2019-09-24T02:59:46.000Z | resources/pausemenu-title/server_name.lua | Kyominii/HorizonRP | 0eec91919ac4d888e3a2aec244ae97214124ca17 | [
"MIT"
] | null | null | null | resources/pausemenu-title/server_name.lua | Kyominii/HorizonRP | 0eec91919ac4d888e3a2aec244ae97214124ca17 | [
"MIT"
] | 1 | 2019-12-06T13:37:39.000Z | 2019-12-06T13:37:39.000Z | function AddTextEntry(key, value)
Citizen.InvokeNative(GetHashKey("ADD_TEXT_ENTRY"), key, value)
end
Citizen.CreateThread(function()
AddTextEntry('FE_THDR_GTAO', 'Horizon')
end)
| 22.75 | 63 | 0.785714 |
53b76f46f47710d939ed133289656be69f7f63fb | 586 | java | Java | iot-ruleengine/ruleengine-core/src/main/java/org/iotp/analytics/ruleengine/core/action/mail/SendMailRuleToPluginActionMsg.java | soncd19/iotplatform | c3f5545f58944b06145fd737fd5a85dc5b97d019 | [
"Apache-2.0"
] | 107 | 2017-08-16T13:52:16.000Z | 2022-03-15T10:00:39.000Z | iot-ruleengine/ruleengine-core/src/main/java/org/iotp/analytics/ruleengine/core/action/mail/SendMailRuleToPluginActionMsg.java | soncd19/iotplatform | c3f5545f58944b06145fd737fd5a85dc5b97d019 | [
"Apache-2.0"
] | 19 | 2019-04-02T02:25:29.000Z | 2022-03-08T21:11:19.000Z | iot-ruleengine/ruleengine-core/src/main/java/org/iotp/analytics/ruleengine/core/action/mail/SendMailRuleToPluginActionMsg.java | soncd19/iotplatform | c3f5545f58944b06145fd737fd5a85dc5b97d019 | [
"Apache-2.0"
] | 58 | 2017-08-09T02:07:47.000Z | 2022-02-09T12:05:57.000Z | package org.iotp.analytics.ruleengine.core.action.mail;
import org.iotp.analytics.ruleengine.plugins.msg.AbstractRuleToPluginMsg;
import org.iotp.infomgt.data.id.CustomerId;
import org.iotp.infomgt.data.id.DeviceId;
import org.iotp.infomgt.data.id.TenantId;
import lombok.Data;
/**
*/
@Data
public class SendMailRuleToPluginActionMsg extends AbstractRuleToPluginMsg<SendMailActionMsg> {
public SendMailRuleToPluginActionMsg(TenantId tenantId, CustomerId customerId, DeviceId deviceId,
SendMailActionMsg payload) {
super(tenantId, customerId, deviceId, payload);
}
}
| 27.904762 | 99 | 0.805461 |
f082f1a5e72ad8bfbcd78ff461df9a440088b680 | 3,011 | js | JavaScript | dist/OrthographicCamera/index.js | WolfgaungBeer/massiv-engine | 637e207d216438e44d2794e62258e3ede395c9aa | [
"MIT"
] | null | null | null | dist/OrthographicCamera/index.js | WolfgaungBeer/massiv-engine | 637e207d216438e44d2794e62258e3ede395c9aa | [
"MIT"
] | null | null | null | dist/OrthographicCamera/index.js | WolfgaungBeer/massiv-engine | 637e207d216438e44d2794e62258e3ede395c9aa | [
"MIT"
] | null | null | null | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _glMatrix = require('gl-matrix');
var _Camera2 = require('../Camera');
var _Camera3 = _interopRequireDefault(_Camera2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var OrthographicCamera = function (_Camera) {
_inherits(OrthographicCamera, _Camera);
function OrthographicCamera(left, right, bottom, top, near, far) {
_classCallCheck(this, OrthographicCamera);
var _this = _possibleConstructorReturn(this, (OrthographicCamera.__proto__ || Object.getPrototypeOf(OrthographicCamera)).call(this));
_this.type = 'OrthographicCamera';
_this.left = left;
_this.right = right;
_this.bottom = bottom;
_this.top = top;
_this.near = near;
_this.far = far;
_this.updateProjectionMatrix(left, right, bottom, top, near, far);
return _this;
}
_createClass(OrthographicCamera, [{
key: 'updateProjectionMatrix',
value: function updateProjectionMatrix(left, right, bottom, top, near, far) {
this.left = left;
this.right = right;
this.bottom = bottom;
this.top = top;
this.near = near;
this.far = far;
this.projectionMatrix = _glMatrix.mat4.ortho(_glMatrix.mat4.create(), left, right, bottom, top, near, far);
}
}]);
return OrthographicCamera;
}(_Camera3.default);
exports.default = OrthographicCamera; | 51.913793 | 564 | 0.692461 |
a177f39146401ad59fbd803fa8662d3f895c0aab | 2,105 | go | Go | src/server/msg/msg.go | Dreamgoing/gameServer | c9a98568bc220454fda24057b3e25a5d56696fe4 | [
"Apache-2.0"
] | 29 | 2017-07-26T15:56:36.000Z | 2022-03-09T13:51:49.000Z | src/server/msg/msg.go | Dreamgoing/gameServer | c9a98568bc220454fda24057b3e25a5d56696fe4 | [
"Apache-2.0"
] | null | null | null | src/server/msg/msg.go | Dreamgoing/gameServer | c9a98568bc220454fda24057b3e25a5d56696fe4 | [
"Apache-2.0"
] | 8 | 2018-01-31T18:21:59.000Z | 2021-11-27T14:18:56.000Z | package msg
import (
//"github.com/name5566/leaf/network"
"github.com/name5566/leaf/network/json"
)
//var Processor network.Processor
var Processor = json.NewProcessor()
//var SignUp_processor = json.NewProcessor()
func init() {
///注册json消息
Processor.Register(&Ok{})
Processor.Register(&SignUp{})
Processor.Register(&SignIn{})
Processor.Register(&State{})
Processor.Register(&Up{})
Processor.Register(&Right{})
Processor.Register(&Left{})
Processor.Register(&Down{})
Processor.Register(&Command{})
Processor.Register(&UpLoad{})
Processor.Register(&Match{})
Processor.Register(&Admin{})
Processor.Register(&UserMsg{})
Processor.Register(&MatchMode{})
Processor.Register(&Order{})
Processor.Register(&Finished{})
}
///结构体定义了一个JSON消息格式
///测试消息结构
type Ok struct {
Name string
}
type Admin struct {
Name string `json:"name"`
}
///注册消息结构
type SignUp struct {
Name string `json:"name"`
Password string `json:"password"`
}
///登录消息结构
type SignIn struct {
Name string `json:"name"`
Password string `json:"password"`
}
///用来同步用户的个人资料
type UpLoad struct {
ID int `json:"id"`
Data UserData `json:"data"`
}
type MatchMode struct {
Name string `json:"name"` ///参加匹配的玩家名
}
///状态消息(向客户端发送)的状态信息
const (
Login_success = iota
Login_mismatch
Login_noexist
Login_duplicate
SignUp_success
SignUp_duplicate
)
type State struct {
Kind int `json:"kind"`
}
///匹配消息
type Match struct {
///匹配名
Name string `json:"name"`
Car int `json:"car"`
}
type Order struct {
Name string `json:"name"`
Val int `json:"val"`
}
///测试的向前开车消息
type Up struct {
Direction float32
}
///向左转
type Left struct {
Direction float32
}
///向右转
type Right struct {
Direction float32
}
type Down struct {
Direction float32
}
type UserMsg struct {
Src string `json:"src"`
Dst string `json:"dst"`
Context string `json:"context"`
}
type Finished struct {
Name string `json:"name"`
Time int `json:"time"`
}
///定义了具体的命令
const (
UpCom = iota
DownCom
LeftCom
RightCom
)
type Command struct {
CarID int `json:"car_id"`
ID int `json:"id"`
Cmd int `json:"cmd"`
Val float32 `json:"val"`
} | 15.143885 | 44 | 0.697862 |
d259ccd525f85fc931c1f5df31d38c914d32d864 | 4,576 | php | PHP | resources/views/index/gallery.blade.php | HuCiao/template | 8758593b5ba0cc5d6bc85676ae420d6b6aa5369c | [
"MIT"
] | null | null | null | resources/views/index/gallery.blade.php | HuCiao/template | 8758593b5ba0cc5d6bc85676ae420d6b6aa5369c | [
"MIT"
] | null | null | null | resources/views/index/gallery.blade.php | HuCiao/template | 8758593b5ba0cc5d6bc85676ae420d6b6aa5369c | [
"MIT"
] | null | null | null | @extends('layouts.layout')
@section('title','Gallery')
@section('content')
<!-- Gallery start Here -->
<div class="gallery-2 padding-tb" style="padding-top: 40px">
<div class="container">
{{-- 面包屑导航 --}}
<div style="margin-bottom:20px;font-size:20px">
<a href="{{route('home.index')}}" style="color: gray">Home</a> >> Gallery
</div>
<div class="row mb-15">
<div class="col-12">
<div class="gallery-grid-item">
<div class="grid-items">
<a href="{{URL::asset('images/gallery/mason/01.jpg')}}" data-rel="lightcase:myCollection:slideshow">
<img src="{{URL::asset('images/gallery/mason/01.jpg')}}" alt="gallery-img">
</a>
</div>
<div class="grid-items">
<a href="{{URL::asset('images/gallery/mason/02.jpg')}}" data-rel="lightcase:myCollection:slideshow">
<img src="{{URL::asset('images/gallery/mason/02.jpg')}}" alt="gallery-img">
</a>
</div>
<div class="grid-items">
<a href="{{URL::asset('images/gallery/mason/03.jpg')}}" data-rel="lightcase:myCollection:slideshow">
<img src="{{URL::asset('images/gallery/mason/03.jpg')}}" alt="gallery-img">
</a>
</div>
<div class="grid-items">
<a href="{{URL::asset('images/gallery/mason/04.jpg')}}" data-rel="lightcase:myCollection:slideshow">
<img src="{{URL::asset('images/gallery/mason/04.jpg')}}" alt="gallery-img">
</a>
</div>
<div class="grid-items">
<a href="{{URL::asset('images/gallery/mason/05.jpg')}}" data-rel="lightcase:myCollection:slideshow">
<img src="{{URL::asset('images/gallery/mason/05.jpg')}}" alt="gallery-img">
</a>
</div>
<div class="grid-items">
<a href="{{URL::asset('images/gallery/mason/06.jpg')}}" data-rel="lightcase:myCollection:slideshow">
<img src="{{URL::asset('images/gallery/mason/06.jpg')}}" alt="gallery-img">
</a>
</div>
<div class="grid-items">
<a href="{{URL::asset('images/gallery/mason/07.jpg')}}" data-rel="lightcase:myCollection:slideshow">
<img src="{{URL::asset('images/gallery/mason/07.jpg')}}" alt="gallery-img">
</a>
</div>
<div class="grid-items">
<a href="{{URL::asset('images/gallery/mason/08.jpg')}}" data-rel="lightcase:myCollection:slideshow">
<img src="{{URL::asset('images/gallery/mason/08.jpg')}}" alt="gallery-img">
</a>
</div>
<div class="grid-items">
<a href="{{URL::asset('images/gallery/mason/09.jpg')}}" data-rel="lightcase:myCollection:slideshow">
<img src="{{URL::asset('images/gallery/mason/09.jpg')}}" alt="gallery-img">
</a>
</div>
<div class="grid-items">
<a href="{{URL::asset('images/gallery/mason/10.jpg')}}" data-rel="lightcase:myCollection:slideshow">
<img src="{{URL::asset('images/gallery/mason/10.jpg')}}" alt="gallery-img">
</a>
</div>
<div class="grid-items">
<a href="{{URL::asset('images/gallery/mason/11.jpg')}}" data-rel="lightcase:myCollection:slideshow">
<img src="{{URL::asset('images/gallery/mason/11.jpg')}}" alt="gallery-img">
</a>
</div>
<div class="grid-items">
<a href="{{URL::asset('images/gallery/mason/12.jpg')}}" data-rel="lightcase:myCollection:slideshow">
<img src="{{URL::asset('images/gallery/mason/12.jpg')}}" alt="gallery-img">
</a>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Gallery ending Here -->
@endsection
| 55.13253 | 124 | 0.447552 |
9c682bb657ddd0706f74792c92e6b03c7d98dc35 | 7,682 | js | JavaScript | ui-modules/utils/yaml-editor/addon/hint/schema-matcher.js | jathanasiou/brooklyn-ui | 17ad9307bb29c129171875d73363e711ddd2bbb5 | [
"Apache-2.0"
] | 19 | 2016-02-02T19:39:10.000Z | 2021-11-07T20:03:32.000Z | ui-modules/utils/yaml-editor/addon/hint/schema-matcher.js | jathanasiou/brooklyn-ui | 17ad9307bb29c129171875d73363e711ddd2bbb5 | [
"Apache-2.0"
] | 179 | 2016-02-04T23:00:00.000Z | 2022-03-14T14:59:25.000Z | ui-modules/utils/yaml-editor/addon/hint/schema-matcher.js | jathanasiou/brooklyn-ui | 17ad9307bb29c129171875d73363e711ddd2bbb5 | [
"Apache-2.0"
] | 62 | 2016-02-02T09:23:54.000Z | 2021-11-07T20:03:21.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
const TYPE = {
null: 'null',
boolean: 'boolean',
object: 'object',
array: 'array',
number: 'number',
string: 'string'
};
const CONDITION = {
anyOf: 'anyOf',
oneOf: 'oneOf',
allOf: 'allOf'
};
/**
* Find the related schema, based on an input JSON and the level (how deep are we in the json) and return the list of
* defined properties.
*/
export class SchemaMatcher {
constructor() {
this.schemas = new Map();
}
/**
* Register a JSON schema, to be referenced by other schemas. Will throw an exception if the field "$id" is not
* defined, as per as the specification.
*
* @param {Object} schema The schema to register
*/
registerSchema(schema) {
if (!schema.hasOwnProperty('$id')) {
throw new Error('Schema miss "$id" property');
}
this.schemas.set(schema.$id, schema);
}
/**
* Find and retrieve the properties, based on the matching schema for the given json and level. Returns a promise
* that will be resolved with an array of properties. If for the given level, a schema is defined by a operator
* such as "oneOf", "anyOf", etc, the resolved properties array will contains all properties for all schemas
* defined by this operator.
*
* The promise will be rejected if a referenced schema is encountered but not registered.
*
* @param {Object} json The JSON object
* @param {Object} schema The root schema defining the given json
* @param {Integer} level The level to get the properties from
* @return {Promise}
*/
findProperties(json, schema, level) {
return new Promise((resolve, reject) => {
try {
resolve(this._findProperties(json, schema, level, 0));
} catch (ex) {
reject(ex);
}
})
}
_findProperties(json, schema, level, currentLevel) {
// We are at the right level, let's return the resolved properties
if (currentLevel === level) {
return this._resolveProperties(schema);
}
// Retrieve the last key of the JSON to get the properties from
let keys = Object.keys(json || {});
let key = keys[keys.length - 1];
// If the schema declare a type, then we resolve the properties based on that
if (schema.hasOwnProperty('type')) {
let subSchema;
let subLevel = currentLevel;
let subJson = json[key] || {};
switch (schema.type) {
case TYPE.object:
subSchema = schema.properties[key];
break;
case TYPE.array:
subSchema = schema.items;
break;
}
if (!subSchema) {
return [];
}
if (subSchema.type === TYPE.array) {
subLevel = subLevel - 1;
}
if (subSchema.hasOwnProperty('$ref')) {
return this._findProperties(subJson, Object.assign({}, this._resolveSchema(schema, subSchema.$ref), subSchema), level, subLevel + 1);
}
let condition = Object.keys(subSchema).find(key => Object.keys(CONDITION).some(condition => condition === key));
if (condition) {
return subSchema[condition].reduce((properties, subSchema) => {
let resolvedSubSchema = subSchema;
if (subSchema.hasOwnProperty('$ref')) {
resolvedSubSchema = Object.assign({}, this._resolveSchema(schema, subSchema.$ref), subSchema);
}
return properties.concat(this._findProperties(subJson, resolvedSubSchema, level, subLevel + 1));
}, []);
}
return this._findProperties(subJson, Object.assign({definitions: schema.definitions}, subSchema), level, subLevel + 1);
}
// If we have any conditions (i.e. anyOf, oneOf, etc) we iterate over the sub-schemas, resolve them
// if we need to and concat all their properties
let condition = Object.keys(schema).find(key => Object.keys(CONDITION).some(condition => condition === key));
if (condition) {
return schema[condition].reduce((properties, subSchema) => {
let resolvedSubSchema = subSchema;
if (subSchema.hasOwnProperty('$ref')) {
resolvedSubSchema = Object.assign({}, this._resolveSchema(schema, subSchema.$ref), subSchema);
}
return properties.concat(this._findProperties(json, resolvedSubSchema, level, currentLevel));
}, []);
}
// If we arrive here, it means tht the schema does not have anything useful so return an empty array
return [];
}
_resolveSchema(baseSchema, $ref) {
if ($ref.startsWith('#/')) {
let refSchema = baseSchema;
let path = $ref.replace('#/', '').split('/');
for (let i = 0; i < path.length; i++) {
if (!refSchema.hasOwnProperty(path[i])) {
throw new Error(`Schema with id "${$ref.replace('#/', '')}" is not registered`)
}
refSchema = refSchema[path[i]];
}
return Object.assign({definitions: baseSchema.definitions}, refSchema);
}
if (!this.schemas.has($ref)) {
throw new Error(`Schema with id "${$ref}" is not registered`);
}
return this.schemas.get($ref);
}
_resolveProperties(schema) {
// If the schema has some properties, we resolve them is we need to and return them
if (schema.hasOwnProperty('properties')) {
return Object.keys(schema.properties).map(key => {
return Object.assign({'$key': key},
schema.properties[key].hasOwnProperty('$ref') ?
this._resolveSchema(schema, schema.properties[key]['$ref']) :
schema.properties[key]);
});
}
// If we have any conditions (i.e. anyOf, oneOf, etc) we iterate over the sub-schemas, resolve them
// if we need to and concat all their properties
let condition = Object.keys(schema).find(key => Object.keys(CONDITION).some(condition => condition === key));
if (condition) {
return schema[condition].reduce((properties, subSchema) => {
let resolvedSubSchema = subSchema;
if (subSchema.hasOwnProperty('$ref')) {
resolvedSubSchema = Object.assign({}, this._resolveSchema(schema, subSchema.$ref), subSchema);
}
return properties.concat(this._resolveProperties(resolvedSubSchema));
}, []);
}
return [];
}
}
| 40.010417 | 149 | 0.583181 |
1626a3acf28778d524bc94d37895f2b731ec2b1d | 1,036 | c | C | src/memory.c | niefeng2015/k802 | e422d56f276758ea1c4fd1522adbc9639e241cb3 | [
"MIT"
] | 2 | 2017-01-24T18:49:12.000Z | 2019-09-05T22:14:39.000Z | src/memory.c | niefeng2015/k802 | e422d56f276758ea1c4fd1522adbc9639e241cb3 | [
"MIT"
] | 1 | 2017-02-28T06:37:19.000Z | 2017-02-28T06:37:19.000Z | src/memory.c | Crazycatz00/hashcat | c54008438780c81fac5eb975090123c9a26d9cb6 | [
"MIT"
] | 1 | 2021-05-31T12:32:02.000Z | 2021-05-31T12:32:02.000Z | /**
* Author......: See docs/credits.txt
* License.....: MIT
*/
#include "common.h"
#include "types.h"
#include "memory.h"
void *hccalloc (const size_t nmemb, const size_t sz)
{
void *p = calloc (nmemb, sz);
if (p == NULL)
{
fprintf (stderr, "%s\n", MSG_ENOMEM);
return (NULL);
}
return (p);
}
void *hcmalloc (const size_t sz)
{
void *p = malloc (sz);
if (p == NULL)
{
fprintf (stderr, "%s\n", MSG_ENOMEM);
return (NULL);
}
memset (p, 0, sz);
return (p);
}
void *hcrealloc (void *ptr, const size_t oldsz, const size_t addsz)
{
void *p = realloc (ptr, oldsz + addsz);
if (p == NULL)
{
fprintf (stderr, "%s\n", MSG_ENOMEM);
return (NULL);
}
memset ((char *) p + oldsz, 0, addsz);
return (p);
}
char *hcstrdup (const char *s)
{
const size_t len = strlen (s);
char *b = (char *) hcmalloc (len + 1);
if (b == NULL) return (NULL);
memcpy (b, s, len);
b[len] = 0;
return (b);
}
void hcfree (void *ptr)
{
if (ptr == NULL) return;
free (ptr);
}
| 13.454545 | 67 | 0.550193 |
857b8c2dbc0be5ef308797b18469cd500d2836fa | 1,470 | js | JavaScript | lib/setup.js | jkresner/meanair-scream | c5c179e83692f371c722178d4af62398d0eabe1c | [
"MIT"
] | 3 | 2015-09-22T03:20:03.000Z | 2016-03-02T12:10:44.000Z | lib/setup.js | jkresner/meanair-scream | c5c179e83692f371c722178d4af62398d0eabe1c | [
"MIT"
] | null | null | null | lib/setup.js | jkresner/meanair-scream | c5c179e83692f371c722178d4af62398d0eabe1c | [
"MIT"
] | null | null | null | module.exports = ({log}) => ({
data(done) {
log.step('data:db')
global.DB = require('./db')(() => {
let seeder = require('./db.seed')(DB, OPTS)
seeder.testToSeed(y => y ? seeder.restoreBSONData(done) : done())
})
let ISODate = global.ISODate = str => moment(str).toDate()
let ID = global.ID = global.ObjectId = (DB||{}).ObjectId
log.step('data:fixture')
global.FIXTURE = require('./data.fixture')
if (!DB) done()
return { ISODate, ID }
},
runner() {
let Mocha = require('mocha')
log.step('tests:init')
return new Mocha(OPTS.config.mocha)
.addFile(join(__dirname,'runner'))
.run(status => {
log.info('DONE', `${status==0?'No':'With'} errors\n`).flush()
process.exit(status)
})
},
app(done) {
let start = new Date()
log.step('app:init')
global.APP = OPTS.App(function(e) {
log.info('APP', `${e?'fail':'ready'} (${new Date()-start}ms)`).flush()
log.step('tests:run')
done(e)
})
},
/*
If unhandledPromiseRejection f => Error, p => Profile
If failed test / assertion f => mocha.ctx, p => Error
*/
fail(f, p) {
// console.log('in fail....', f, p)
if (f.stack)
log.error(f)
else if ((p instanceof Error))
log.error(p)
log.info('FAIL', `${log.step()} `.white + `${log.runner.scope.join(' > ')}`.spec)
process.exit(1) // Exiting stops default mocha exit output
}
})
| 23.709677 | 85 | 0.542857 |
f076aaf49a3d8fba6fb5ba17c6020bb113d2de01 | 5,417 | py | Python | src/jsonengine/main.py | youhengzhou/json-crud-engine | 8ee614af6dddbe1236a78a7debf71048f476a3ff | [
"MIT"
] | 2 | 2021-07-02T04:33:36.000Z | 2022-01-09T23:40:30.000Z | src/jsonengine/main.py | youhengzhou/json-crud-engine | 8ee614af6dddbe1236a78a7debf71048f476a3ff | [
"MIT"
] | null | null | null | src/jsonengine/main.py | youhengzhou/json-crud-engine | 8ee614af6dddbe1236a78a7debf71048f476a3ff | [
"MIT"
] | null | null | null | # JSON engine 21 9 16
# database
# eng.json
# engine
# eng.py
import os
import json
path = os.getcwd() + '\\json_engine_database\\'
path_string = ''
def set_path(string):
global path
path = os.getcwd() + string
def dictionary_kv(dictionary, key, value):
dictionary[key] = value
return dictionary
def set_path_string(args,create_flag):
global path_string
if (args):
path_string = str(args[0]) + '\\'
if os.path.exists(path + path_string)==False:
if create_flag == True:
os.makedirs(path + path_string)
else:
return False
return path_string
def create(dictionary, *args):
path_string = set_path_string(args,True)
with open(path + path_string + 'eng.json', 'w') as outfile:
json.dump(dictionary, outfile, indent=4)
def retrieve(*args):
path_string = set_path_string(args,False)
if path_string == False:
return False
with open(path + path_string + 'eng.json', 'r') as f:
return(json.load(f))
def retrieve_k(key, *args):
path_string = set_path_string(args,False)
if path_string == False:
return False
with open(path + path_string + 'eng.json', 'r') as f:
if key in json.load(f):
with open(path + path_string + 'eng.json', 'r') as f:
return(json.load(f)[key])
else:
return False
def update(dictionary, *args):
path_string = set_path_string(args,False)
if path_string == False:
return False
with open(path + path_string + 'eng.json', 'w') as outfile:
json.dump(dictionary, outfile, indent=4)
return True
def update_kv(key, value, *args):
path_string = set_path_string(args,False)
if path_string == False:
return False
with open(path + path_string + 'eng.json', 'w') as outfile:
json.dump({key: value}, outfile, indent=4)
return True
def patch(dictionary, *args):
path_string = set_path_string(args,False)
if path_string == False:
return False
with open(path + path_string + 'eng.json', 'r') as f:
data=(json.load(f))
data.update(dictionary)
with open(path + path_string + 'eng.json', 'w') as outfile:
json.dump(data, outfile, indent=4)
return True
def patch_kv(key, value, *args):
path_string = set_path_string(args,False)
if path_string == False:
return False
with open(path + path_string + 'eng.json', 'r') as f:
data=(json.load(f))
data.update({key: value})
with open(path + path_string + 'eng.json', 'w') as outfile:
json.dump(data, outfile, indent=4)
return True
def delete(*args):
if (args):
path_string = str(args[0]) + '\\'
if os.path.exists(path + path_string + 'eng.json'):
os.remove(path + path_string + 'eng.json')
os.rmdir(path + path_string)
return True
else:
return False
def delete_k(key, *args):
if (args):
path_string = str(args[0]) + '\\'
if os.path.exists(path + path_string + 'eng.json'):
with open(path + path_string + 'eng.json', 'r') as f:
if key in json.load(f):
data = json.load(f)
data.pop(key)
with open(path + path_string + 'eng.json', 'w') as outfile:
json.dump(data, outfile, indent=4)
return True
else:
return False
else:
return False
def display(*args):
if (args):
path_string = str(args[0]) + '\\'
if os.path.exists(path + path_string + 'eng.json'):
with open(path + path_string + 'eng.json', 'r') as f:
print(json.load(f))
return True
else:
print('The selected file does not exist')
return False
def display_key(key, *args):
if (args):
path_string = str(args[0]) + '\\'
if os.path.exists(path + path_string + 'eng.json'):
with open(path + path_string + 'eng.json', 'r') as f:
if key in json.load(f):
print(key + ' ' + str(json.load(f)[key]))
return True
else:
print('The selected file does not exist')
return False
def display_nkv(key, *args):
if (args):
path_string = str(args[0]) + '\\'
if os.path.exists(path + path_string + 'eng.json'):
with open(path + path_string + 'eng.json', 'r') as f:
if key in json.load(f):
data = json.load(f)
data.pop(key,'key not found')
print(data)
return True
else:
print('The selected file does not exist')
return False
def display_ind(*args):
if (args):
path_string = str(args[0]) + '\\'
if os.path.exists(path + path_string + 'eng.json'):
with open(path + path_string + 'eng.json', 'r') as f:
print(json.dumps(json.load(f), indent=4))
else:
print('The selected file does not exist')
def display_ind_nkv(key, *args):
if (args):
path_string = str(args[0]) + '\\'
if os.path.exists(path + path_string + 'eng.json'):
with open(path + path_string + 'eng.json', 'r') as f:
data = json.load(f)
data.pop(key,'key not found')
print(json.dumps(data, indent=4))
else:
print('The selected file does not exist')
| 31.132184 | 75 | 0.568027 |
5804f268da979f80d10b4306ebf0349d86b9fef9 | 420 | c | C | solutions/001-025/25/main.c | PysKa-Ratzinger/personal_project_euler_solutions | ff05c38f3c9cbcd4d6f09f81034bc299c7144476 | [
"MIT"
] | 1 | 2019-04-19T01:05:07.000Z | 2019-04-19T01:05:07.000Z | solutions/001-025/25/main.c | PysKa-Ratzinger/personal_project_euler_solutions | ff05c38f3c9cbcd4d6f09f81034bc299c7144476 | [
"MIT"
] | null | null | null | solutions/001-025/25/main.c | PysKa-Ratzinger/personal_project_euler_solutions | ff05c38f3c9cbcd4d6f09f81034bc299c7144476 | [
"MIT"
] | null | null | null | #include <stdio.h>
int main(){
double a = 1.0;
double b = 1.0;
double c = a + b;
double limit = 10.0;
int digits = 1;
int index = 3;
while(digits < 1000){
a = b;
b = c;
c = a + b;
if(c >= limit){
a /= limit;
b /= limit;
c /= limit;
digits++;
}
index++;
}
printf("If you can trust me, the number you are looking for is %d\n", index);
return 0;
}
| 14.482759 | 79 | 0.478571 |
9d895e6423a625663df470c37941b2beb5d20881 | 223 | kt | Kotlin | database/src/main/java/com/constantin/microflux/database/Settings.kt | ConstantinCezB/Microflux | 84e8a146cd27096aa41dd7f1a446e8bd974c8d01 | [
"MIT"
] | 36 | 2020-07-12T18:19:08.000Z | 2021-09-03T06:34:02.000Z | database/src/main/java/com/constantin/microflux/database/Settings.kt | ConstantinCezB/Microflux | 84e8a146cd27096aa41dd7f1a446e8bd974c8d01 | [
"MIT"
] | 3 | 2020-10-04T11:14:15.000Z | 2021-08-22T13:15:36.000Z | database/src/main/java/com/constantin/microflux/database/Settings.kt | ConstantinCezarBegu/Microflux | 84e8a146cd27096aa41dd7f1a446e8bd974c8d01 | [
"MIT"
] | 2 | 2020-07-20T15:09:41.000Z | 2021-03-04T16:57:50.000Z | package com.constantin.microflux.database
import com.constantin.microflux.data.ServerUrl
fun ServerQueries.insert(serverUrl: ServerUrl) = insertImpl(serverUrl = serverUrl).run {
selectForId(serverUrl).executeAsOne()
} | 31.857143 | 88 | 0.811659 |
d7adfa6d86c3679b9a16bf8acf500b32cb585f47 | 518 | lua | Lua | src/test/module/import/_case2.lua | yuhangwang/PackageToolkit.lua | 48b637f0d24cab682a98257a93944d603ccd6e3b | [
"MIT"
] | null | null | null | src/test/module/import/_case2.lua | yuhangwang/PackageToolkit.lua | 48b637f0d24cab682a98257a93944d603ccd6e3b | [
"MIT"
] | null | null | null | src/test/module/import/_case2.lua | yuhangwang/PackageToolkit.lua | 48b637f0d24cab682a98257a93944d603ccd6e3b | [
"MIT"
] | null | null | null | local me = ...
local M = { }
local name1 = "module"
local name2 = "import"
local TK = require("PackageToolkit")
local m = TK[name1][name2](me, "m/../m/./m2")
M.run = function(msg)
if msg == nil then
msg = ""
end
print(TK.ui.dashed_line(80, '-'))
print(string.format("test %s.%s()", name1, name2))
print(msg)
local result = m.hello()
local solution = "hello from m1"
print("Result: ", result)
assert(result == solution)
print("VERIFIED!")
return print(TK.ui.dashed_line(80, '-'))
end
return M
| 23.545455 | 52 | 0.621622 |
19d428aad36966348419dd413eabc7e98a9aa51d | 13,103 | lua | Lua | Plugins/UnrealLua/LuaSource/luahotupdate.lua | asomfai/unreal.lua | 61a7f3fd2e967ffd970c9b2ac72f12aa2af34bd8 | [
"MIT"
] | 311 | 2017-01-31T04:24:13.000Z | 2022-03-02T10:12:58.000Z | Plugins/UnrealLua/LuaSource/luahotupdate.lua | asomfai/unreal.lua | 61a7f3fd2e967ffd970c9b2ac72f12aa2af34bd8 | [
"MIT"
] | 39 | 2017-02-14T09:33:02.000Z | 2020-02-14T07:45:33.000Z | Plugins/UnrealLua/LuaSource/luahotupdate.lua | asomfai/unreal.lua | 61a7f3fd2e967ffd970c9b2ac72f12aa2af34bd8 | [
"MIT"
] | 98 | 2017-01-30T17:49:34.000Z | 2022-03-15T08:16:34.000Z | if _VERSION == "Lua 5.3" then
function getfenv(f)
if type(f) == "function" then
local name, value = debug.getupvalue(f, 1)
if name == "_ENV" then
return value
else
return _ENV
end
end
end
function setfenv(f, Env)
if type(f) == "function" then
local name, value = debug.getupvalue(f, 1)
if name == "_ENV" then
debug.setupvalue(f, 1, Env)
end
end
end
debug = debug or {}
debug.setfenv = setfenv
function loadstring( ... )
return load(...)
end
end
local HU = {}
function HU.FailNotify(...)
if HU.NotifyFunc then HU.NotifyFunc(...) end
end
function HU.DebugNofity(...)
if HU.DebugNofityFunc then HU.DebugNofityFunc(...) end
end
local function GetWorkingDir()
if HU.WorkingDir == nil then
local p = io.popen("echo %cd%")
if p then
HU.WorkingDir = p:read("*l").."\\"
p:close()
end
end
return HU.WorkingDir
end
local function Normalize(path)
path = path:gsub("/","\\")
if path:find(":") == nil then
path = GetWorkingDir()..path
end
local pathLen = #path
if path:sub(pathLen, pathLen) == "\\" then
path = path:sub(1, pathLen - 1)
end
local parts = { }
for w in path:gmatch("[^\\]+") do
if w == ".." and #parts ~=0 then table.remove(parts)
elseif w ~= "." then table.insert(parts, w)
end
end
return table.concat(parts, "\\")
end
function HU.InitFileMap(RootPath)
local TheMap = {}
for _, rootpath in pairs(RootPath) do
rootpath = Normalize(rootpath)
local file = io.popen("dir /S/B /A:A \""..rootpath.."\"")
io.input(file)
for line in io.lines() do
local FileName = string.match(line,".*\\(.*)%.lua")
if FileName ~= nil then
if TheMap[FileName] == nil then
TheMap[FileName] = {}
end
local luapath = string.sub(line, #rootpath+2, #line-4)
luapath = string.gsub(luapath, "\\", ".")
HU.LuaPathToSysPath[luapath] = SysPath
table.insert(TheMap[FileName], {SysPath = line, LuaPath = luapath})
end
end
file:close()
end
return TheMap
end
function HU.InitFakeTable()
local meta = {}
HU.Meta = meta
local function FakeT() return setmetatable({}, meta) end
local function EmptyFunc() end
local function pairs() return EmptyFunc end
local function setmetatable(t, metaT)
HU.MetaMap[t] = metaT
return t
end
local function getmetatable(t, metaT)
return setmetatable({}, t)
end
local function require(LuaPath)
if not HU.RequireMap[LuaPath] then
local FakeTable = FakeT()
HU.RequireMap[LuaPath] = FakeTable
end
return HU.RequireMap[LuaPath]
end
function meta.__index(t, k)
if k == "setmetatable" then
return setmetatable
elseif k == "pairs" or k == "ipairs" then
return pairs
elseif k == "next" then
return EmptyFunc
elseif k == "require" then
return require
elseif HU.CallOriginFunctions and HU.CallOriginFunctions[k] then
return _G[k]
else
local FakeTable = FakeT()
rawset(t, k, FakeTable)
return FakeTable
end
end
function meta.__newindex(t, k, v) rawset(t, k, v) end
function meta.__call() return FakeT(), FakeT(), FakeT() end
function meta.__add() return meta.__call() end
function meta.__sub() return meta.__call() end
function meta.__mul() return meta.__call() end
function meta.__div() return meta.__call() end
function meta.__mod() return meta.__call() end
function meta.__pow() return meta.__call() end
function meta.__unm() return meta.__call() end
function meta.__concat() return meta.__call() end
function meta.__eq() return meta.__call() end
function meta.__lt() return meta.__call() end
function meta.__le() return meta.__call() end
function meta.__len() return meta.__call() end
return FakeT
end
function HU.InitProtection()
HU.Protection = {}
HU.Protection[setmetatable] = true
HU.Protection[pairs] = true
HU.Protection[ipairs] = true
HU.Protection[next] = true
HU.Protection[require] = true
HU.Protection[HU] = true
HU.Protection[HU.Meta] = true
HU.Protection[math] = true
HU.Protection[string] = true
HU.Protection[table] = true
end
function HU.AddFileFromHUList()
package.loaded[HU.UpdateListFile] = nil
local FileList = require (HU.UpdateListFile)
HU.ALL = false
HU.HUMap = {}
for _, file in pairs(FileList) do
if file == "_ALL_" then
HU.ALL = true
for k, v in pairs(HU.FileMap) do
for _, path in pairs(v) do
HU.HUMap[path.LuaPath] = path.SysPath
end
end
return
end
if not HU.FileMap[file] then
if HU.TryReloadFileCount[file] == nil or HU.TryReloadFileCount[file] == 0 then
HU.FileMap = HU.InitFileMap(HU.RootPath)
if not HU.FileMap[file] then
HU.FailNotify("HotUpdate can't not find "..file)
HU.TryReloadFileCount[file] = 3
end
else
HU.TryReloadFileCount[file] = HU.TryReloadFileCount[file] - 1
end
end
if HU.FileMap[file] then
for _, path in pairs(HU.FileMap[file]) do
HU.HUMap[path.LuaPath] = path.SysPath
end
end
end
end
function HU.ErrorHandle(e)
HU.FailNotify("HotUpdate Error\n"..tostring(e))
HU.ErrorHappen = true
end
function HU.LoadStringFunc(SysPath)
io.input(SysPath)
local CodeStr = io.read("*all")
io.input():close()
return CodeStr
end
function HU.BuildNewCode(SysPath, LuaPath)
local NewCode = HU.LoadStringFunc(SysPath)
if HU.ALL and HU.OldCode[SysPath] == nil then
HU.OldCode[SysPath] = NewCode
return
end
if HU.OldCode[SysPath] == NewCode then
return false
end
HU.DebugNofity(SysPath)
local chunk = "--[["..LuaPath.."]] "
chunk = chunk..NewCode
local NewFunction = loadstring(chunk)
if not NewFunction then
HU.FailNotify(SysPath.." has syntax error.")
collectgarbage("collect")
return false
else
HU.FakeENV = HU.FakeT()
HU.MetaMap = {}
HU.RequireMap = {}
setfenv(NewFunction, HU.FakeENV)
local NewObject
HU.ErrorHappen = false
xpcall(function () NewObject = NewFunction() end, HU.ErrorHandle)
if not HU.ErrorHappen then
HU.OldCode[SysPath] = NewCode
return true, NewObject
else
collectgarbage("collect")
return false
end
end
end
function HU.Travel_G()
local visited = {}
visited[HU] = true
local function f(t)
if (type(t) ~= "function" and type(t) ~= "table") or visited[t] or HU.Protection[t] then return end
visited[t] = true
if type(t) == "function" then
for i = 1, math.huge do
local name, value = debug.getupvalue(t, i)
if not name then break end
if type(value) == "function" then
for _, funcs in ipairs(HU.ChangedFuncList) do
if value == funcs[1] then
debug.setupvalue(t, i, funcs[2])
end
end
end
f(value)
end
elseif type(t) == "table" then
f(debug.getmetatable(t))
local changeIndexs = {}
for k,v in pairs(t) do
f(k); f(v);
if type(v) == "function" then
for _, funcs in ipairs(HU.ChangedFuncList) do
if v == funcs[1] then t[k] = funcs[2] end
end
end
if type(k) == "function" then
for index, funcs in ipairs(HU.ChangedFuncList) do
if k == funcs[1] then changeIndexs[#changeIndexs+1] = index end
end
end
end
for _, index in ipairs(changeIndexs) do
local funcs = HU.ChangedFuncList[index]
t[funcs[2]] = t[funcs[1]]
t[funcs[1]] = nil
end
end
end
f(_G)
local registryTable = debug.getregistry()
f(registryTable)
for _, funcs in ipairs(HU.ChangedFuncList) do
if funcs[3] == "HUDebug" then funcs[4]:HUDebug() end
end
end
function HU.ReplaceOld(OldObject, NewObject, LuaPath, From, Deepth)
if type(OldObject) == type(NewObject) then
if type(NewObject) == "table" then
HU.UpdateAllFunction(OldObject, NewObject, LuaPath, From, "")
elseif type(NewObject) == "function" then
HU.UpdateOneFunction(OldObject, NewObject, LuaPath, nil, From, "")
end
end
end
function HU.HotUpdateCode(LuaPath, SysPath)
local OldObject = package.loaded[LuaPath]
if OldObject ~= nil then
HU.VisitedSig = {}
HU.ChangedFuncList = {}
local Success, NewObject = HU.BuildNewCode(SysPath, LuaPath)
if Success then
HU.ReplaceOld(OldObject, NewObject, LuaPath, "Main", "")
for LuaPath, NewObject in pairs(HU.RequireMap) do
local OldObject = package.loaded[LuaPath]
HU.ReplaceOld(OldObject, NewObject, LuaPath, "Main_require", "")
end
setmetatable(HU.FakeENV, nil)
HU.UpdateAllFunction(HU.ENV, HU.FakeENV, " ENV ", "Main", "")
if #HU.ChangedFuncList > 0 then
HU.Travel_G()
end
collectgarbage("collect")
end
elseif HU.OldCode[SysPath] == nil then
HU.OldCode[SysPath] = HU.LoadStringFunc(SysPath)
end
end
function HU.ResetENV(object, name, From, Deepth)
local visited = {}
local function f(object, name)
if not object or visited[object] then return end
visited[object] = true
if type(object) == "function" then
HU.DebugNofity(Deepth.."HU.ResetENV", name, " from:"..From)
xpcall(function () setfenv(object, HU.ENV) end, HU.FailNotify)
elseif type(object) == "table" then
HU.DebugNofity(Deepth.."HU.ResetENV", name, " from:"..From)
for k, v in pairs(object) do
f(k, tostring(k).."__key", " HU.ResetENV ", Deepth.." " )
f(v, tostring(k), " HU.ResetENV ", Deepth.." ")
end
end
end
f(object, name)
end
function HU.UpdateUpvalue(OldFunction, NewFunction, Name, From, Deepth)
HU.DebugNofity(Deepth.."HU.UpdateUpvalue", Name, " from:"..From)
local OldUpvalueMap = {}
local OldExistName = {}
for i = 1, math.huge do
local name, value = debug.getupvalue(OldFunction, i)
if not name then break end
OldUpvalueMap[name] = value
OldExistName[name] = true
end
for i = 1, math.huge do
local name, value = debug.getupvalue(NewFunction, i)
if not name then break end
if OldExistName[name] then
local OldValue = OldUpvalueMap[name]
if type(OldValue) ~= type(value) then
debug.setupvalue(NewFunction, i, OldValue)
elseif type(OldValue) == "function" then
HU.UpdateOneFunction(OldValue, value, name, nil, "HU.UpdateUpvalue", Deepth.." ")
elseif type(OldValue) == "table" then
HU.UpdateAllFunction(OldValue, value, name, "HU.UpdateUpvalue", Deepth.." ")
debug.setupvalue(NewFunction, i, OldValue)
else
debug.setupvalue(NewFunction, i, OldValue)
end
else
HU.ResetENV(value, name, "HU.UpdateUpvalue", Deepth.." ")
end
end
end
function HU.UpdateOneFunction(OldObject, NewObject, FuncName, OldTable, From, Deepth)
if HU.Protection[OldObject] or HU.Protection[NewObject] then return end
if OldObject == NewObject then return end
local signature = tostring(OldObject)..tostring(NewObject)
if HU.VisitedSig[signature] then return end
HU.VisitedSig[signature] = true
HU.DebugNofity(Deepth.."HU.UpdateOneFunction "..FuncName.." from:"..From)
if pcall(debug.setfenv, NewObject, getfenv(OldObject)) then
HU.UpdateUpvalue(OldObject, NewObject, FuncName, "HU.UpdateOneFunction", Deepth.." ")
HU.ChangedFuncList[#HU.ChangedFuncList + 1] = {OldObject, NewObject, FuncName, OldTable}
end
end
function HU.UpdateAllFunction(OldTable, NewTable, Name, From, Deepth)
if HU.Protection[OldTable] or HU.Protection[NewTable] then return end
local IsSame = getmetatable(OldTable) == getmetatable(NewTable)
local IsSame = IsSame and OldTable == NewTable
if IsSame == true then return end
local signature = tostring(OldTable)..tostring(NewTable)
if HU.VisitedSig[signature] then return end
HU.VisitedSig[signature] = true
HU.DebugNofity(Deepth.."HU.UpdateAllFunction "..Name.." from:"..From)
for ElementName, Element in pairs(NewTable) do
local OldElement = OldTable[ElementName]
if type(Element) == type(OldElement) then
if type(Element) == "function" then
HU.UpdateOneFunction(OldElement, Element, ElementName, OldTable, "HU.UpdateAllFunction", Deepth.." ")
elseif type(Element) == "table" then
HU.UpdateAllFunction(OldElement, Element, ElementName, "HU.UpdateAllFunction", Deepth.." ")
end
elseif OldElement == nil and type(Element) == "function" then
if pcall(setfenv, Element, HU.ENV) then
OldTable[ElementName] = Element
end
end
end
local OldMeta = debug.getmetatable(OldTable)
local NewMeta = HU.MetaMap[NewTable]
if type(OldMeta) == "table" and type(NewMeta) == "table" then
HU.UpdateAllFunction(OldMeta, NewMeta, Name.."'s Meta", "HU.UpdateAllFunction", Deepth.." ")
end
end
function HU.SetFileLoader(InitFileMapFunc, LoadStringFunc)
HU.InitFileMap = InitFileMapFunc
HU.LoadStringFunc = LoadStringFunc
end
function HU.Init(UpdateListFile, RootPath, FailNotify, ENV, CallOriginFunctions)
HU.UpdateListFile = UpdateListFile
HU.HUMap = {}
HU.FileMap = {}
HU.NotifyFunc = FailNotify
HU.OldCode = {}
HU.ChangedFuncList = {}
HU.VisitedSig = {}
HU.FakeENV = nil
HU.ENV = ENV or _G
HU.LuaPathToSysPath = {}
HU.RootPath = RootPath
HU.FileMap = HU.InitFileMap(RootPath)
HU.FakeT = HU.InitFakeTable()
HU.CallOriginFunctions = CallOriginFunctions
HU.InitProtection()
HU.ALL = false
HU.TryReloadFileCount = {}
end
function HU.Update()
HU.AddFileFromHUList()
for LuaPath, SysPath in pairs(HU.HUMap) do
HU.HotUpdateCode(LuaPath, SysPath)
end
end
return HU
| 28.861233 | 108 | 0.6845 |
5a4ef283daf5ad1cfe6625ef4de0e61e044aeaf7 | 4,655 | swift | Swift | Sources/ComicsInfoCore/Services/Database/Providers/DynamoDB/DynamoDB+ItemGetDBService.swift | AleksandarDinic/comics-info-backend | 1fa831743c62b00f767f86456a69b455c82a8521 | [
"MIT"
] | null | null | null | Sources/ComicsInfoCore/Services/Database/Providers/DynamoDB/DynamoDB+ItemGetDBService.swift | AleksandarDinic/comics-info-backend | 1fa831743c62b00f767f86456a69b455c82a8521 | [
"MIT"
] | null | null | null | Sources/ComicsInfoCore/Services/Database/Providers/DynamoDB/DynamoDB+ItemGetDBService.swift | AleksandarDinic/comics-info-backend | 1fa831743c62b00f767f86456a69b455c82a8521 | [
"MIT"
] | null | null | null | //
// DynamoDB+ItemGetDBService.swift
// ComicsInfoCore
//
// Created by Aleksandar Dinic on 27/08/2020.
// Copyright © 2020 Aleksandar Dinic. All rights reserved.
//
import Foundation
import SotoDynamoDB
extension DynamoDB: ItemGetDBService {
func getItem<Item: Codable>(_ query: GetItemQuery) -> EventLoopFuture<Item> {
return self.query(query.dynamoDBQuery.input, type: Item.self).flatMapThrowing {
guard let item = $0.items?.first else {
throw DatabaseError.itemNotFound(withID: query.dynamoDBQuery.ID)
}
return item
}.flatMapErrorThrowing {
print("GetItem ERROR: \($0)")
throw $0
}
}
func getItems<Item: ComicInfoItem>(_ query: GetItemsQuery) -> EventLoopFuture<[Item]> {
var futures = [EventLoopFuture<Item>]()
for (id, input) in query.dynamoDBQuery.inputs {
let future: EventLoopFuture<Item> = self.query(input, type: Item.self)
.flatMapThrowing {
guard let item = $0.items?.first else {
throw DatabaseError.itemNotFound(withID: id)
}
return item
}
.flatMapErrorThrowing {
print("GetItems ERROR: \($0)")
throw $0
}
futures.append(future)
}
let futureResult = EventLoopFuture.reduce([Item](), futures, on: client.eventLoopGroup.next()) { (items, item) in
var items = items
items.append(item)
return items
}
return futureResult.flatMapThrowing { items in
guard !items.isEmpty else {
throw DatabaseError.itemsNotFound(withIDs: query.dynamoDBQuery.IDs)
}
return items
}.flatMapErrorThrowing {
print("GetItems ERROR: \($0)")
throw $0
}
}
func getAll<Item: ComicInfoItem>(_ query: GetAllItemsQuery<Item>) -> EventLoopFuture<[Item]> {
queryPaginator(query.dynamoDBQuery.input, query.initialValue, type: Item.self) { (result, output, eventLoop) -> EventLoopFuture<(Bool, [Item])> in
guard let items = output.items, !items.isEmpty else {
return eventLoop.submit { (false, result) }
}
return eventLoop.submit { (false, result + items) }
}.flatMapThrowing { items in
guard !items.isEmpty else {
throw DatabaseError.itemsNotFound(withIDs: nil)
}
return items
}.flatMapErrorThrowing {
print("GetAll ERROR: \($0)")
throw $0
}
}
func getSummaries<Summary: ItemSummary>(_ query: GetSummariesQuery<Summary>) -> EventLoopFuture<[Summary]?> {
return queryPaginator(query.dynamoDBQuery.input, query.initialValue, type: Summary.self) { (result, output, eventLoop) -> EventLoopFuture<(Bool, [Summary])> in
print("RESULT: \(result)")
print("OUTPUT: \(output)")
guard let items = output.items, !items.isEmpty else {
return eventLoop.submit { (false, result) }
}
return eventLoop.submit { (false, result + items) }
}.flatMapThrowing { items in
print("ITEMS: \(items)")
guard !items.isEmpty else {
throw DatabaseError.itemsNotFound(withIDs: nil)
}
return items
}.flatMapErrorThrowing {
print("GetSummaries ERROR: \($0)")
throw $0
}
}
func getSummary<Summary: ItemSummary>(_ query: GetSummaryQuery) -> EventLoopFuture<[Summary]?> {
var futures = [EventLoopFuture<Summary?>]()
for input in query.dynamoDBQuery.inputs {
print("GetSummary INPUT: \(input)")
futures.append(
self.query(input, type: Summary.self)
.map {
print("GetSummary OUTPUT: \($0)")
return $0.items?.first
}
.flatMapErrorThrowing {
print("GetSummary ERROR: \($0)")
throw $0
}
)
}
let futureResult = EventLoopFuture.reduce([Summary](), futures, on: client.eventLoopGroup.next()) { (items, item) in
guard let item = item else { return items }
var items = items
items.append(item)
return items
}
return futureResult.map { !$0.isEmpty ? $0 : nil }
}
}
| 36.944444 | 167 | 0.541139 |
bb3330c2a0a0ba7f2bf1a3acaefc51a99a73bae4 | 596 | html | HTML | p5-0.html | ma1988rco/practicasp5js | 178afc24d56f0c83e3a470513c2c57a502be32a0 | [
"MIT"
] | null | null | null | p5-0.html | ma1988rco/practicasp5js | 178afc24d56f0c83e3a470513c2c57a502be32a0 | [
"MIT"
] | null | null | null | p5-0.html | ma1988rco/practicasp5js | 178afc24d56f0c83e3a470513c2c57a502be32a0 | [
"MIT"
] | null | null | null |
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.6/p5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.6/addons/p5.dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.6/addons/p5.sound.js"></script>
</head>
<body>
<h3>Script: p5-0.html</h3>
<script>
var capture;
function setup() {
createCanvas(390, 240);
capture = createCapture(VIDEO);
capture.size(320, 240);
//capture.hide();
}
function draw() {
background(255);
image(capture, 0, 0, 320, 240);
filter('INVERT');
}
</script>
</body>
</html>
| 19.866667 | 93 | 0.662752 |
e562e836a1c20a62a91f28da06ca955552cd5f8d | 329 | ts | TypeScript | src/heroicons.d.ts | fanaticscripter/CoopTracker | 4686715bddd9a59b8f3cc2e223c87b4da663c694 | [
"MIT"
] | 2 | 2021-05-26T07:31:11.000Z | 2022-02-20T16:03:12.000Z | src/heroicons.d.ts | fanaticscripter/CoopTracker | 4686715bddd9a59b8f3cc2e223c87b4da663c694 | [
"MIT"
] | null | null | null | src/heroicons.d.ts | fanaticscripter/CoopTracker | 4686715bddd9a59b8f3cc2e223c87b4da663c694 | [
"MIT"
] | null | null | null | // @heroicons/vue does not have type declarations.
// https://github.com/tailwindlabs/heroicons/issues/252
// https://github.com/tailwindlabs/heroicons/pull/254
declare module '@heroicons/vue/solid' {
import { DefineComponent } from 'vue';
export let CheckIcon: DefineComponent;
export let SelectorIcon: DefineComponent;
}
| 36.555556 | 55 | 0.765957 |
e78715859fa9a39cbbbd921de1dca1ab700bb661 | 1,034 | js | JavaScript | models/organization.js | AugustineUmeagudosi/trello-clone-api | 937aaf41f51651e13ee233dba3b3b44fb69bc667 | [
"MIT"
] | null | null | null | models/organization.js | AugustineUmeagudosi/trello-clone-api | 937aaf41f51651e13ee233dba3b3b44fb69bc667 | [
"MIT"
] | null | null | null | models/organization.js | AugustineUmeagudosi/trello-clone-api | 937aaf41f51651e13ee233dba3b3b44fb69bc667 | [
"MIT"
] | null | null | null | const { Model } = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class Organization extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
Organization.belongsTo(models.User, { foreignKey: 'createdBy', as: 'Owner', });
Organization.hasMany(models.Project, { foreignKey: 'organizationId' });
Organization.hasMany(models.Invitation, { foreignKey: 'organizationId' });
Organization.hasMany(models.OrganizationMember, { foreignKey: 'organizationId' });
}
}
Organization.init({
slug: { type: DataTypes.STRING, allowNull: false, },
name: { type: DataTypes.STRING, allowNull: false, },
createdBy: { type: DataTypes.UUID, allowNull: false, foreignKey: true, references: {model: 'User'} },
}, {
sequelize,
modelName: 'Organization',
timestamps: true
});
return Organization;
}; | 38.296296 | 105 | 0.672147 |
16540c56a06ad2207e4d3b04cdce7c9ca434c3d2 | 250 | ts | TypeScript | src/enums/DamageClasses.ts | comokj7/suikadex | 896c31627b8374e8833ad01bc69398cd94fff738 | [
"MIT"
] | null | null | null | src/enums/DamageClasses.ts | comokj7/suikadex | 896c31627b8374e8833ad01bc69398cd94fff738 | [
"MIT"
] | null | null | null | src/enums/DamageClasses.ts | comokj7/suikadex | 896c31627b8374e8833ad01bc69398cd94fff738 | [
"MIT"
] | null | null | null | export const DamageClasses = Object.freeze({
status: {
id: 1,
label: 'status',
name: '보조',
},
physical: {
id: 2,
label: 'physical',
name: '물리',
},
special: {
id: 3,
label: 'special',
name: '특수',
},
});
| 13.888889 | 44 | 0.48 |
e75bcca1da5c51880fed0261e0910e512401e4e9 | 1,101 | asm | Assembly | test/pinsr32.asm | bitwiseworks/nasm-os2 | ef78e4ee1ca3220ac3b60a61b084a693b8032ab6 | [
"BSD-2-Clause"
] | 3 | 2015-03-21T07:35:15.000Z | 2018-01-12T01:24:02.000Z | 3rdParties/src/nasm/nasm-2.15.02/test/pinsr32.asm | blue3k/StormForge | 1557e699a673ae9adcc8f987868139f601ec0887 | [
"Apache-2.0"
] | 1 | 2020-03-26T19:58:54.000Z | 2020-04-24T08:58:04.000Z | test/pinsr32.asm | bitwiseworks/nasm-os2 | ef78e4ee1ca3220ac3b60a61b084a693b8032ab6 | [
"BSD-2-Clause"
] | 5 | 2015-03-21T07:35:21.000Z | 2021-01-14T10:54:46.000Z | ;Testname=test; Arguments=-O0 -fbin -opinsr32.bin; Files=stdout stderr pinsr32.bin
bits 32
pinsrw mm0,eax,0
pinsrw mm1,si,0
pinsrw mm2,[ecx],0
pinsrw mm3,word [ecx],0
pinsrb xmm0,eax,0
pinsrb xmm1,sil,0
; pinsrb xmm1,bh,0
pinsrb xmm2,[ecx],0
pinsrb xmm3,byte [ecx],0
pinsrw xmm0,eax,0
pinsrw xmm1,si,0
pinsrw xmm2,[ecx],0
pinsrw xmm3,word [ecx],0
pinsrd xmm0,eax,0
pinsrd xmm1,esi,0
pinsrd xmm2,[ecx],0
pinsrd xmm3,dword [ecx],0
vpinsrb xmm0,eax,0
vpinsrb xmm1,bl,0
vpinsrb xmm2,[ecx],0
vpinsrb xmm3,byte [ecx],0
vpinsrw xmm0,eax,0
vpinsrw xmm1,si,0
vpinsrw xmm2,[ecx],0
vpinsrw xmm3,word [ecx],0
vpinsrd xmm0,eax,0
vpinsrd xmm1,esi,0
vpinsrd xmm2,[ecx],0
vpinsrd xmm3,dword [ecx],0
vpinsrb xmm4,xmm0,eax,0
vpinsrb xmm5,xmm1,bl,0
vpinsrb xmm6,xmm2,[ecx],0
vpinsrb xmm7,xmm3,byte [ecx],0
vpinsrw xmm4,xmm0,eax,0
vpinsrw xmm5,xmm1,si,0
vpinsrw xmm6,xmm2,[ecx],0
vpinsrw xmm7,xmm3,word [ecx],0
vpinsrd xmm4,xmm0,eax,0
vpinsrd xmm5,xmm1,esi,0
vpinsrd xmm6,xmm2,[ecx],0
vpinsrd xmm7,xmm3,dword [ecx],0
| 20.388889 | 83 | 0.680291 |
d97afaed87e7c80cd82dba65b5999297dbcb30d8 | 8,185 | swift | Swift | Client/Carthage/Checkouts/swift-protobuf/Sources/protoc-gen-swift/ReservedWords.swift | perezCamargo/SwiftProtobufSample | b167da8dd9d095abbde82e2d08441b3103885149 | [
"MIT"
] | 14 | 2016-12-27T05:00:10.000Z | 2021-06-03T01:09:52.000Z | Client/Carthage/Checkouts/swift-protobuf/Sources/protoc-gen-swift/ReservedWords.swift | perezCamargo/SwiftProtobufSample | b167da8dd9d095abbde82e2d08441b3103885149 | [
"MIT"
] | 1 | 2021-06-11T17:32:31.000Z | 2021-06-11T17:32:31.000Z | Client/Carthage/Checkouts/swift-protobuf/Sources/protoc-gen-swift/ReservedWords.swift | perezCamargo/SwiftProtobufSample | b167da8dd9d095abbde82e2d08441b3103885149 | [
"MIT"
] | 2 | 2020-05-27T11:32:10.000Z | 2021-06-03T01:12:36.000Z | // Sources/protoc-gen-swift/ReservedWords.swift - Reserved words database and sanitizing
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Reserved words that the Swift code generator will avoid using.
///
// -----------------------------------------------------------------------------
import PluginLibrary
///
/// We won't generate types (structs, enums) with these names:
///
private let reservedTypeNames: Set<String> = {
() -> Set<String> in
var names: Set<String> = []
// Main SwiftProtobuf namespace
// Shadowing this leads to Bad Things.
names.insert("SwiftProtobuf")
// Subtype of many messages, used to scope nested extensions
names.insert("Extensions")
// Subtypes are static references, so can conflict with static
// class properties:
names.insert("protoMessageName")
// Methods on Message that we need to avoid shadowing. Testing
// shows we do not need to avoid `serializedData` or `isEqualTo`,
// but it's not obvious to me what's different about them. Maybe
// because these two are generic? Because they throw?
names.insert("decodeMessage")
names.insert("traverse")
// Basic Message properties we don't want to shadow:
names.insert("isInitialized")
names.insert("unknownFields")
// Standard Swift property names we don't want
// to conflict with:
names.insert("debugDescription")
names.insert("description")
names.insert("dynamicType")
names.insert("hashValue")
// We don't need to protect all of these keywords, just the ones
// that interfere with type expressions:
// names = names.union(PluginLibrary.swiftKeywordsReservedInParticularContexts)
names.insert("Type")
names.insert("Protocol")
names = names.union(PluginLibrary.swiftKeywordsUsedInDeclarations)
names = names.union(PluginLibrary.swiftKeywordsUsedInStatements)
names = names.union(PluginLibrary.swiftKeywordsUsedInExpressionsAndTypes)
names = names.union(PluginLibrary.swiftCommonTypes)
names = names.union(PluginLibrary.swiftSpecialVariables)
return names
}()
private func sanitizeTypeName(_ s: String, disambiguator: String) -> String {
if reservedTypeNames.contains(s) {
return s + disambiguator
} else if isAllUnderscore(s) {
return s + disambiguator
} else if s.hasSuffix(disambiguator) {
// If `foo` and `fooMessage` both exist, and `foo` gets
// expanded to `fooMessage`, then we also should expand
// `fooMessage` to `fooMessageMessage` to avoid creating a new
// conflict. This can be resolved recursively by stripping
// the disambiguator, sanitizing the root, then re-adding the
// disambiguator:
let e = s.index(s.endIndex, offsetBy: -disambiguator.characters.count)
let truncated = s.substring(to: e)
return sanitizeTypeName(truncated, disambiguator: disambiguator) + disambiguator
} else {
return s
}
}
func sanitizeMessageTypeName(_ s: String) -> String {
return sanitizeTypeName(s, disambiguator: "Message")
}
func sanitizeEnumTypeName(_ s: String) -> String {
return sanitizeTypeName(s, disambiguator: "Enum")
}
func sanitizeOneofTypeName(_ s: String) -> String {
return sanitizeTypeName(s, disambiguator: "Oneof")
}
private let reservedFieldNames: Set<String> = {
() -> Set<String> in
var names: Set<String> = []
// Properties are instance names, so can't shadow static class
// properties such as `protoMessageName`.
// Properties can't shadow methods. For example, we don't need to
// avoid `isEqualTo` as a field name.
// Basic Message properties that we don't want to shadow
names.insert("isInitialized")
names.insert("unknownFields")
// Standard Swift property names we don't want
// to conflict with:
names.insert("debugDescription")
names.insert("description")
names.insert("dynamicType")
names.insert("hashValue")
// We don't need to protect all of these keywords, just the ones
// that interfere with type expressions:
// names = names.union(PluginLibrary.swiftKeywordsReservedInParticularContexts)
names.insert("Type")
names.insert("Protocol")
names = names.union(PluginLibrary.swiftKeywordsUsedInDeclarations)
names = names.union(PluginLibrary.swiftKeywordsUsedInStatements)
names = names.union(PluginLibrary.swiftKeywordsUsedInExpressionsAndTypes)
names = names.union(PluginLibrary.swiftCommonTypes)
names = names.union(PluginLibrary.swiftSpecialVariables)
return names
}()
/// Struct and class field names go through
/// this before going into the source code.
/// It appends "_p" to any name that can't be
/// used as a field name in Swift source code.
func sanitizeFieldName(_ s: String, basedOn: String) -> String {
if basedOn.hasPrefix("clear") {
return s + "_p"
} else if basedOn.hasPrefix("has") {
return s + "_p"
} else if reservedFieldNames.contains(basedOn) {
return s + "_p"
} else if isAllUnderscore(basedOn) {
return s + "__"
} else {
return s
}
}
func sanitizeFieldName(_ s: String) -> String {
return sanitizeFieldName(s, basedOn: s)
}
/*
* Many Swift reserved words can be used as enum cases if we put
* backticks around them:
*/
private let quotableEnumCases: Set<String> = {
() -> Set<String> in
var names: Set<String> = []
// We don't need to protect all of these keywords, just the ones
// that interfere with enum cases:
// names = names.union(PluginLibrary.swiftKeywordsReservedInParticularContexts)
names.insert("associativity")
names.insert("dynamicType")
names.insert("optional")
names.insert("required")
names = names.union(PluginLibrary.swiftKeywordsUsedInDeclarations)
names = names.union(PluginLibrary.swiftKeywordsUsedInStatements)
names = names.union(PluginLibrary.swiftKeywordsUsedInExpressionsAndTypes)
// Common type and variable names don't cause problems as enum
// cases, because enum case names only appear in special contexts:
// names = names.union(PluginLibrary.swiftCommonTypes)
// names = names.union(PluginLibrary.swiftSpecialVariables)
return names
}()
/*
* Some words cannot be used for enum cases, even if they
* are quoted with backticks:
*/
private let reservedEnumCases: Set<String> = [
// Don't conflict with standard Swift property names:
"debugDescription",
"description",
"dynamicType",
"hashValue",
"init",
"rawValue",
"self",
]
/*
* Many Swift reserved words can be used as Extension names if we put
* backticks around them.
*
* Note: To avoid the duplicate list to maintain, currently just reusing the
* EnumCases one.
*/
private let quotableMessageScopedExtensionNames: Set<String> = quotableEnumCases
/// enum case names are sanitized by adding
/// backticks `` around them.
func isAllUnderscore(_ s: String) -> Bool {
if s.isEmpty {
return false
}
for c in s.characters {
if c != "_" {return false}
}
return true
}
func sanitizeEnumCase(_ s: String) -> String {
if reservedEnumCases.contains(s) {
return "\(s)_"
} else if quotableEnumCases.contains(s) {
return "`\(s)`"
} else if isAllUnderscore(s) {
return s + "__"
} else {
return s
}
}
func sanitizeMessageScopedExtensionName(_ s: String, skipBackticks: Bool = false) -> String {
// Since thing else is added to the "enum Extensions" for scoped
// extensions, there is no need to have a reserved list.
if quotableMessageScopedExtensionNames.contains(s) {
if skipBackticks {
return s
}
return "`\(s)`"
} else if isAllUnderscore(s) {
return s + "__"
} else {
return s
}
}
| 33.272358 | 93 | 0.671961 |
dfb3f3d311a4f01a32b1895aaf03ed28632024fa | 684 | swift | Swift | EPI/Stacks and Queues/Implement a stack with max API/swift/test.swift | peferron/algo | cea32e7f3555ce09eceeb7f4793baf54a658a812 | [
"MIT"
] | 104 | 2015-02-28T06:28:34.000Z | 2022-03-23T18:06:46.000Z | EPI/Stacks and Queues/Implement a stack with max API/swift/test.swift | peferron/algo | cea32e7f3555ce09eceeb7f4793baf54a658a812 | [
"MIT"
] | 4 | 2015-01-04T01:36:54.000Z | 2021-05-06T20:07:58.000Z | EPI/Stacks and Queues/Implement a stack with max API/swift/test.swift | peferron/algo | cea32e7f3555ce09eceeb7f4793baf54a658a812 | [
"MIT"
] | 12 | 2016-06-13T06:18:56.000Z | 2022-03-05T10:54:06.000Z | import Darwin
var stack = Stack<Int>()
assert(stack.isEmpty)
stack.push(10)
assert(!stack.isEmpty)
assert(stack.max == 10)
stack.push(10)
stack.push(6)
stack.push(13)
stack.push(15)
stack.push(15)
stack.push(14)
assert(stack.max == 15)
assert(stack.pop() == 14)
assert(stack.max == 15)
assert(stack.pop() == 15)
assert(stack.max == 15)
assert(stack.pop() == 15)
assert(stack.max == 13)
stack.push(20)
assert(stack.max == 20)
assert(stack.pop() == 20)
assert(stack.max == 13)
assert(stack.pop() == 13)
assert(stack.max == 10)
assert(stack.pop() == 6)
assert(stack.max == 10)
assert(stack.pop() == 10)
assert(stack.max == 10)
assert(stack.pop() == 10)
assert(stack.isEmpty)
| 15.545455 | 25 | 0.666667 |
2f222ff5447fdcc40966a45cad1120ae4d8802d2 | 1,020 | php | PHP | routes/web.php | quanit94/getfb | fd0e9121a1cd0a757cf7755d3fbd04f93e49f56d | [
"MIT"
] | null | null | null | routes/web.php | quanit94/getfb | fd0e9121a1cd0a757cf7755d3fbd04f93e49f56d | [
"MIT"
] | null | null | null | routes/web.php | quanit94/getfb | fd0e9121a1cd0a757cf7755d3fbd04f93e49f56d | [
"MIT"
] | null | null | null | <?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of the routes that are handled
| by your application. Just tell Laravel the URIs it should respond
| to using a Closure or controller method. Build something great!
|
*/
Route::get('/', function () {
// echo 'xxx';
return view('welcome');
});
Route::group(['middleware' => 'web'], function () {
// Route::auth();
// Route::get('/', 'PagesController@index');
// Route::get('terms-of-service', 'PagesController@terms');
// Route::get('privacy', 'PagesController@privacy');
// Route::get('combo', 'PagesController@combo');
Route::get('/admin', [
'uses' => 'AdminController@index',
'as' => 'admin'
]);
Route::get('/login', [
'uses' => 'AuthController@index',
'as' => 'login'
]);
});
//Route::get('/admin', 'AdminController@index'); | 25.5 | 75 | 0.502941 |
4a917d196e00f07d1013bab9bdb2e40de61ba940 | 352 | asm | Assembly | programs/oeis/044/A044457.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 22 | 2018-02-06T19:19:31.000Z | 2022-01-17T21:53:31.000Z | programs/oeis/044/A044457.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 41 | 2021-02-22T19:00:34.000Z | 2021-08-28T10:47:47.000Z | programs/oeis/044/A044457.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 5 | 2021-02-24T21:14:16.000Z | 2021-08-09T19:48:05.000Z | ; A044457: Numbers n such that string 3,3 occurs in the base 4 representation of n but not of n+1.
; 15,31,47,63,79,95,111,127,143,159,175,191,207,223,255,271,287,303,319,335,351,367,383,399,415,431,447,463,479,511,527,543,559,575,591,607,623,639,655,671,687,703,719,735,767,783,799
add $0,1
mov $1,32
mul $1,$0
div $1,30
mul $1,16
sub $1,1
mov $0,$1
| 32 | 183 | 0.701705 |
08015b5a41313bf927fc756f65ad969e5f843e13 | 138 | sql | SQL | K2/SQL/CheckEmptyRole.sql | mikerodionov/ps_scripts | 7f100ca7622fdab19f0d525d2a83ec6d2b96ab59 | [
"MIT"
] | null | null | null | K2/SQL/CheckEmptyRole.sql | mikerodionov/ps_scripts | 7f100ca7622fdab19f0d525d2a83ec6d2b96ab59 | [
"MIT"
] | null | null | null | K2/SQL/CheckEmptyRole.sql | mikerodionov/ps_scripts | 7f100ca7622fdab19f0d525d2a83ec6d2b96ab59 | [
"MIT"
] | null | null | null | SELECT dq.*,dqu.[User] FROM [Server].[DestQueue] dq LEFT JOIN [Server].[DestQueueUser] dqu ON dqu.QueueID = dq.ID
WHERE dqu.[user] IS NULL | 69 | 113 | 0.724638 |
e75e7bd433813bb75bd6c24ef4b936a01bdc162b | 83 | js | JavaScript | src/modules/Teams/controllers/index.js | MehdizadeMilad/uefa | e09c46a2e2222fd8eb28b3f8839cf51c38b755ba | [
"MIT"
] | null | null | null | src/modules/Teams/controllers/index.js | MehdizadeMilad/uefa | e09c46a2e2222fd8eb28b3f8839cf51c38b755ba | [
"MIT"
] | null | null | null | src/modules/Teams/controllers/index.js | MehdizadeMilad/uefa | e09c46a2e2222fd8eb28b3f8839cf51c38b755ba | [
"MIT"
] | null | null | null |
const TeamController = require('./team');
module.exports = {
TeamController
} | 13.833333 | 41 | 0.686747 |
2704fae61ba59f125c29834526b198e80914a616 | 5,373 | kt | Kotlin | app/src/main/java/com/moovel/gpsrecorderplayer/repo/Signal.kt | nakaharanaoji/gps_lib | 7b115be913e0ce97960b13bb811c293bf3a67768 | [
"MIT"
] | 20 | 2018-10-29T09:19:23.000Z | 2020-03-21T15:29:51.000Z | app/src/main/java/com/moovel/gpsrecorderplayer/repo/Signal.kt | nakaharanaoji/gps_lib | 7b115be913e0ce97960b13bb811c293bf3a67768 | [
"MIT"
] | 1 | 2019-06-11T14:40:15.000Z | 2019-06-11T14:40:15.000Z | app/src/main/java/com/moovel/gpsrecorderplayer/repo/Signal.kt | nakaharanaoji/gps_lib | 7b115be913e0ce97960b13bb811c293bf3a67768 | [
"MIT"
] | 2 | 2019-03-20T19:42:40.000Z | 2019-06-20T16:51:51.000Z | /**
* Copyright (c) 2010-2018 Moovel Group GmbH - moovel.com
*
* 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 com.moovel.gpsrecorderplayer.repo
import android.telephony.ServiceState
import android.telephony.TelephonyManager
data class Signal(
/**
* see [android.telephony.TelephonyManager.getNetworkType]
*/
val networkType: Int,
/**
* see [android.telephony.TelephonyManager.getServiceState]
*/
val serviceState: Int,
/**
* see [android.telephony.SignalStrength]
*/
val gsmSignalStrength: Int,
val gsmBitErrorRate: Int,
val cdmaDbm: Int,
val cdmaEcio: Int,
val evdoDbm: Int,
val evdoEcio: Int,
val evdoSnr: Int,
val gsm: Boolean = false,
val level: Int
) {
companion object {
const val LEVEL_NONE = 0
const val LEVEL_POOR = 1
const val LEVEL_MODERATE = 2
const val LEVEL_GOOD = 3
const val LEVEL_GREAT = 4
fun networkTypeName(networkType: Int) = when (networkType) {
TelephonyManager.NETWORK_TYPE_UNKNOWN -> "UNKNOWN"
TelephonyManager.NETWORK_TYPE_GPRS -> "GPRS"
TelephonyManager.NETWORK_TYPE_EDGE -> "EDGE"
TelephonyManager.NETWORK_TYPE_UMTS -> "UMTS"
TelephonyManager.NETWORK_TYPE_HSDPA -> "HSDPA"
TelephonyManager.NETWORK_TYPE_HSUPA -> "HSUPA"
TelephonyManager.NETWORK_TYPE_HSPA -> "HSPA"
TelephonyManager.NETWORK_TYPE_CDMA -> "CDMA"
TelephonyManager.NETWORK_TYPE_EVDO_0 -> "CDMA - EvDo rev. 0"
TelephonyManager.NETWORK_TYPE_EVDO_A -> "CDMA - EvDo rev. A"
TelephonyManager.NETWORK_TYPE_EVDO_B -> "CDMA - EvDo rev. B"
TelephonyManager.NETWORK_TYPE_1xRTT -> "CDMA - 1xRTT"
TelephonyManager.NETWORK_TYPE_LTE -> "LTE"
TelephonyManager.NETWORK_TYPE_EHRPD -> "CDMA - eHRPD"
TelephonyManager.NETWORK_TYPE_IDEN -> "iDEN"
TelephonyManager.NETWORK_TYPE_HSPAP -> "HSPA+"
TelephonyManager.NETWORK_TYPE_GSM -> "GSM"
TelephonyManager.NETWORK_TYPE_TD_SCDMA -> "TD_SCDMA"
TelephonyManager.NETWORK_TYPE_IWLAN -> "IWLAN"
else -> "UNSUPPORTED($networkType)"
}
fun networkClassName(networkType: Int) = when (networkType) {
TelephonyManager.NETWORK_TYPE_UNKNOWN -> "UNKNOWN"
TelephonyManager.NETWORK_TYPE_GPRS -> "2G"
TelephonyManager.NETWORK_TYPE_EDGE -> "2G"
TelephonyManager.NETWORK_TYPE_CDMA -> "2G"
TelephonyManager.NETWORK_TYPE_1xRTT -> "2G"
TelephonyManager.NETWORK_TYPE_IDEN -> "2G"
TelephonyManager.NETWORK_TYPE_GSM -> "2G"
TelephonyManager.NETWORK_TYPE_UMTS -> "3G"
TelephonyManager.NETWORK_TYPE_EVDO_0 -> "3G"
TelephonyManager.NETWORK_TYPE_EVDO_A -> "3G"
TelephonyManager.NETWORK_TYPE_HSDPA -> "3G"
TelephonyManager.NETWORK_TYPE_HSUPA -> "3G"
TelephonyManager.NETWORK_TYPE_HSPA -> "3G"
TelephonyManager.NETWORK_TYPE_EVDO_B -> "3G"
TelephonyManager.NETWORK_TYPE_EHRPD -> "3G"
TelephonyManager.NETWORK_TYPE_HSPAP -> "3G"
TelephonyManager.NETWORK_TYPE_TD_SCDMA -> "3G"
TelephonyManager.NETWORK_TYPE_LTE -> "4G"
TelephonyManager.NETWORK_TYPE_IWLAN -> "4G"
else -> "UNSUPPORTED($networkType)"
}
fun serviceStateName(serviceState: Int) = when (serviceState) {
ServiceState.STATE_IN_SERVICE -> "IN_SERVICE"
ServiceState.STATE_OUT_OF_SERVICE -> "OUT_OF_SERVICE"
ServiceState.STATE_EMERGENCY_ONLY -> "EMERGENCY_ONLY"
ServiceState.STATE_POWER_OFF -> "POWER_OFF"
else -> "UNSUPPORTED($serviceState)"
}
fun levelName(level: Int) = when (level) {
0 -> "NONE"
1 -> "POOR"
2 -> "MODERATE"
3 -> "GOOD"
4 -> "GREAT"
else -> "UNSUPPORTED($level)"
}
}
val networkTypeName: String by lazy { networkTypeName(networkType) }
val networkClassName: String by lazy { networkClassName(networkType) }
val levelName: String by lazy { levelName(level) }
}
| 41.651163 | 80 | 0.648427 |
a38e758db648b9cc292e3bf35e85aa1d8184d8ed | 3,007 | kt | Kotlin | library/src/main/java/com/getroadmap/r2rlib/models/Route.kt | janvde/Rome2RioAndroid | c3e320a0024a11cdcbeb56efdc05199cb680fa2a | [
"Apache-2.0"
] | null | null | null | library/src/main/java/com/getroadmap/r2rlib/models/Route.kt | janvde/Rome2RioAndroid | c3e320a0024a11cdcbeb56efdc05199cb680fa2a | [
"Apache-2.0"
] | null | null | null | library/src/main/java/com/getroadmap/r2rlib/models/Route.kt | janvde/Rome2RioAndroid | c3e320a0024a11cdcbeb56efdc05199cb680fa2a | [
"Apache-2.0"
] | null | null | null | package com.getroadmap.r2rlib.models
import android.os.Parcel
import android.os.Parcelable
import java.util.ArrayList
/**
* https://www.rome2rio.com/documentation/search#Route
*/
/**
* name string Route display name
* depPlace integer Departure place (index into places array)
* arrPlace integer Arrival place (index into places array)
* distance float Estimated total distance (in km)
* totalDuration float Estimated total duration (in minutes, includes transfers)
* totalTransitDuration float Estimated total duration spent in transit (in minutes)
* totalTransferDuration float Estimated total duration spent waiting for transfers (in minutes)
* indicativePrices IndicativePrice[] Array of indicative prices (optional)
* segments Segment[] Array of segments
* alternatives Alternative[] Array of alternative segments (optional)
*/
data class Route(val name: String?,
val depPlace: Int?,
val arrPlace: Int?,
val distance: Float?,
val totalDuration: Float?,
val totalTransitDuration: Float?,
val totalTransferDuration: Float?,
val indicativePrices: List<IndicativePrice>?,
val segments: List<Segment>?,
val alternatives: List<Alternative>?) : Parcelable {
constructor(parcel: Parcel) : this(
parcel.readString(),
parcel.readValue(Int::class.java.classLoader) as? Int,
parcel.readValue(Int::class.java.classLoader) as? Int,
parcel.readValue(Float::class.java.classLoader) as? Float,
parcel.readValue(Float::class.java.classLoader) as? Float,
parcel.readValue(Float::class.java.classLoader) as? Float,
parcel.readValue(Float::class.java.classLoader) as? Float,
parcel.createTypedArrayList(IndicativePrice),
parcel.createTypedArrayList(Segment),
parcel.createTypedArrayList(Alternative)) {
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(name)
parcel.writeValue(depPlace)
parcel.writeValue(arrPlace)
parcel.writeValue(distance)
parcel.writeValue(totalDuration)
parcel.writeValue(totalTransitDuration)
parcel.writeValue(totalTransferDuration)
parcel.writeTypedList(indicativePrices)
parcel.writeTypedList(segments)
parcel.writeTypedList(alternatives)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<Route> {
override fun createFromParcel(parcel: Parcel): Route {
return Route(parcel)
}
override fun newArray(size: Int): Array<Route?> {
return arrayOfNulls(size)
}
}
} | 40.093333 | 110 | 0.626206 |
df5f983c09427facdbbdc99b9c5553049b96b004 | 1,549 | rb | Ruby | spec/publisher/publishing_content_to_frontend_spec.rb | uk-gov-mirror/alphagov.publishing-e2e-tests | 66223e224d82dc009a631e4cc732035a53c7d119 | [
"MIT"
] | 10 | 2017-03-13T08:56:31.000Z | 2021-04-13T09:19:01.000Z | spec/publisher/publishing_content_to_frontend_spec.rb | uk-gov-mirror/alphagov.publishing-e2e-tests | 66223e224d82dc009a631e4cc732035a53c7d119 | [
"MIT"
] | 120 | 2016-12-05T14:03:35.000Z | 2022-03-28T16:10:34.000Z | spec/publisher/publishing_content_to_frontend_spec.rb | uk-gov-mirror/alphagov.publishing-e2e-tests | 66223e224d82dc009a631e4cc732035a53c7d119 | [
"MIT"
] | 11 | 2017-10-11T12:58:58.000Z | 2021-04-10T20:11:05.000Z | feature "Publishing content from Publisher to Frontend", publisher: true, frontend: true, flaky: true do
include PublisherHelpers
let(:title) { unique_title }
let(:slug) { "publishing-content-publisher-to-frontend-#{SecureRandom.uuid}" }
let(:subpart_title) { unique_title }
scenario "Publishing an artefact" do
given_there_is_a_draft_artefact_with_subpage
and_i_publish_it
then_i_can_view_the_artefact_on_gov_uk
and_i_can_view_the_subpage_on_gov_uk
end
private
def signin_to_signon
@user = signin_with_next_user(
"Publisher" => %w[skip_review],
)
end
def given_there_is_a_draft_artefact_with_subpage
signin_to_signon if use_signon?
create_publisher_artefact(slug: slug, title: title, format: "Guide")
add_part_to_artefact(title: unique_title)
@subpart_slug = add_part_to_artefact(title: subpart_title)
end
def and_i_publish_it
publish_artefact
end
def then_i_can_view_the_artefact_on_gov_uk
wait_for_artefact_to_be_published
click_link("View this on the GOV.UK website")
expect(page).to have_content(title)
expect_url_matches_live_gov_uk
end
def and_i_can_view_the_subpage_on_gov_uk
visit(subpage_url)
expect(page).to have_content(subpart_title)
expect_url_matches_live_gov_uk
end
def wait_for_artefact_to_be_published
@published_url = find_link("View this on the GOV.UK website")[:href]
wait_for_artefact_to_be_viewable(@published_url)
end
def subpage_url
[@published_url, @subpart_slug].join("/")
end
end
| 27.175439 | 104 | 0.769529 |
bc5bf135a68e1a20f8283e82b82ae3e27ca64d3a | 4,800 | asm | Assembly | source/tokeniser/tokenise/tokenise.asm | paulscottrobson/6502-basic | d4c360041bfa49427a506465e58bb0ef94beaa44 | [
"MIT"
] | 3 | 2021-09-30T19:34:11.000Z | 2021-10-31T06:55:50.000Z | source/tokeniser/tokenise/tokenise.asm | paulscottrobson/6502-Basic | d4c360041bfa49427a506465e58bb0ef94beaa44 | [
"MIT"
] | null | null | null | source/tokeniser/tokenise/tokenise.asm | paulscottrobson/6502-Basic | d4c360041bfa49427a506465e58bb0ef94beaa44 | [
"MIT"
] | 1 | 2021-12-07T21:58:44.000Z | 2021-12-07T21:58:44.000Z | ; ************************************************************************************************
; ************************************************************************************************
;
; Name: tokenise.asm
; Purpose: Tokenise a string
; Created: 8th March 2021
; Reviewed: 16th March 2021
; Author: Paul Robson (paul@robsons.org.uk)
;
; ************************************************************************************************
; ************************************************************************************************
.section storage
tokenHeader: ; bytes (all zero) to create a fake 'program line'
.fill 3
tokenBuffer: ; token buffer.
.fill 256
tokenBufferIndex: ; count of characters in buffer.
.fill 1
.send storage
.section code
; ************************************************************************************************
;
; Tokenise string at (codePtr) into tokenising buffer
; A != 0 if tokenising successful.
;
; ************************************************************************************************
Tokenise: ;; <tokenise>
jsr TokeniseMakeASCIIZ ; convert to ASCIIZ string.
TokeniseASCIIZ: ;; <tokenisez>
jsr TokeniseFixCase ; remove controls and lower case outside quotes.
lda #0 ; reset the token buffer index
sta tokenBufferIndex
tay ; start pointer
lda #$80 ; empty token buffer ($80 ends it)
sta tokenBuffer
;
; Main tokenisation loop
;
_TokLoop:
lda (codePtr),y ; get next character
beq _TokExit ; if zero, then exit.
iny ; skip over spaces.
cmp #" "
beq _TokLoop
dey ; point back to character.
cmp #"&" ; Hexadecimal constant.
beq _TokHexConst
cmp #'"' ; Quoted String
beq _TokQString
cmp #"Z"+1 ; > 'Z' is punctuation
bcs _TokPunctuation
cmp #"A" ; A..Z identifier
bcs _TokIdentifier
cmp #"9"+1
bcs _TokPunctuation ; between 9 and A exclusive, punctuation
cmp #"0"
bcc _TokPunctuation ; < 0, punctuation.
lda #10 ; 0..9 constant in base 10.
bne _TokConst
;
; Handle hexadecimal constant.
;
_TokHexConst:
iny ; consume token.
lda #TKW_AMP ; Write ampersand token out
jsr TokenWrite
lda #16
;
; Handle constant in base A
;
_TokConst:
jsr TokeniseInteger
bcs _TokLoop
bcc _TokFail
;
; Quoted string
;
_TokQString:
jsr TokeniseString
bcs _TokLoop
bcc _TokFail
;
; Punctuation token.
;
_TokPunctuation:
jsr TokenisePunctuation
bcs _TokLoop
bcc _TokFail
;
; Identifier or text token
;
_TokIdentifier:
jsr TokeniseIdentifier
bcs _TokLoop
bcc _TokFail
_TokExit:
lda #1
rts
_TokFail:
lda #0
rts
; ************************************************************************************************
;
; Write A to tokenise buffer
;
; ************************************************************************************************
TokenWrite:
sta tempShort ; save XA
pha
.pshx
lda tempShort
ldx tokenBufferIndex ; geet index
sta tokenBuffer,x ; write byte to buffer
lda #TOK_EOL ; pre-emptively write EOL marker after
sta tokenBuffer+1,x
inc tokenBufferIndex ; bump index
.pulx
pla
rts
; ************************************************************************************************
;
; Make string at (codePtr) ASCIIZ
;
; ************************************************************************************************
TokeniseMakeASCIIZ:
ldy #0 ; get length of string.
lda (codePtr),y
tay
iny ; +1, the NULL goes here.
lda #0
sta (codePtr),y ; write the trailing NULL.
inc codePtr ; bump the pointer.
bne _TMKAExit
inc codePtr+1
_TMKAExit:
rts
; ************************************************************************************************
;
; Make upper case and remove controls for everything outside quotes.
;
; ************************************************************************************************
TokeniseFixCase:
ldy #0 ; position in buffer.
ldx #1 ; bit 0 of this is 'in quotes'
_TFCFlipQ:
txa
eor #1
tax
_TFCLoop:
lda (codePtr),y ; get character
beq _TFCExit ; if zero exit.
cmp #32 ; if control
bcc _TFCControl
iny ; preconsume
cmp #'"'
beq _TFCFlipQ
cmp #"a" ; check if L/C
bcc _TFCLoop
cmp #"z"+1
bcs _TFCLoop
;
cpx #0 ; in quotes, if so, leave alone.
bne _TFCLoop
dey
eor #"A"^"a" ; make U/C
_TFCWrite:
sta (codePtr),y
iny
jmp _TFCLoop
;
_TFCControl:
lda #" "
bne _TFCWrite
_TFCExit:
rts
.send code
| 25.13089 | 98 | 0.4625 |
edde4f8e6d7c67a42d82387577e32296b493d966 | 7,841 | asm | Assembly | Transynther/x86/_processed/NONE/_xt_/i7-7700_9_0x48.log_21829_1956.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 9 | 2020-08-13T19:41:58.000Z | 2022-03-30T12:22:51.000Z | Transynther/x86/_processed/NONE/_xt_/i7-7700_9_0x48.log_21829_1956.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 1 | 2021-04-29T06:29:35.000Z | 2021-05-13T21:02:30.000Z | Transynther/x86/_processed/NONE/_xt_/i7-7700_9_0x48.log_21829_1956.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 3 | 2020-07-14T17:07:07.000Z | 2022-03-21T01:12:22.000Z | .global s_prepare_buffers
s_prepare_buffers:
push %r8
push %rax
push %rbp
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_WC_ht+0x148b8, %rsi
lea addresses_D_ht+0xb118, %rdi
dec %r8
mov $89, %rcx
rep movsl
nop
and %rbp, %rbp
lea addresses_WT_ht+0x1b0d8, %rax
nop
nop
nop
sub %rdx, %rdx
mov $0x6162636465666768, %rbp
movq %rbp, %xmm7
movups %xmm7, (%rax)
nop
nop
nop
cmp $811, %rbp
lea addresses_D_ht+0x12aa8, %rax
nop
nop
nop
inc %rdx
mov (%rax), %cx
cmp $56862, %rdi
lea addresses_A_ht+0x1cb14, %rsi
lea addresses_normal_ht+0x18f58, %rdi
nop
nop
nop
nop
dec %rax
mov $66, %rcx
rep movsq
nop
nop
nop
nop
dec %rcx
lea addresses_WC_ht+0x18228, %r8
nop
nop
nop
nop
sub $46115, %rdi
movb (%r8), %al
nop
nop
nop
sub $47797, %rdi
lea addresses_D_ht+0x4228, %rbp
add $11665, %rax
mov (%rbp), %di
nop
nop
nop
nop
nop
sub %rbp, %rbp
lea addresses_normal_ht+0xc1a8, %rsi
nop
nop
nop
nop
nop
inc %rdx
movb $0x61, (%rsi)
nop
nop
xor %rcx, %rcx
lea addresses_D_ht+0xed14, %rbp
xor $48796, %rax
mov $0x6162636465666768, %r8
movq %r8, %xmm3
vmovups %ymm3, (%rbp)
and $62823, %rdi
lea addresses_D_ht+0x46e8, %rdx
nop
nop
nop
and %rcx, %rcx
movb $0x61, (%rdx)
nop
nop
nop
nop
and %rdi, %rdi
lea addresses_A_ht+0x628, %rbp
nop
nop
xor $52441, %rdx
mov (%rbp), %edi
and $24326, %rbp
lea addresses_A_ht+0x9fe8, %rax
nop
xor $12473, %rsi
movb $0x61, (%rax)
nop
nop
nop
sub %rcx, %rcx
lea addresses_D_ht+0x1cb28, %rsi
lea addresses_A_ht+0x3fa8, %rdi
dec %r8
mov $55, %rcx
rep movsb
nop
nop
nop
nop
add $47272, %rdx
lea addresses_WT_ht+0x228, %rax
xor $2450, %r8
movups (%rax), %xmm7
vpextrq $1, %xmm7, %rdx
nop
nop
nop
dec %r8
lea addresses_D_ht+0x1bdc8, %rdi
nop
nop
nop
nop
xor $14044, %rax
movb $0x61, (%rdi)
nop
nop
nop
nop
nop
add %rcx, %rcx
lea addresses_normal_ht+0xc38, %rax
clflush (%rax)
xor $6696, %rdx
mov $0x6162636465666768, %rcx
movq %rcx, %xmm0
movups %xmm0, (%rax)
nop
nop
nop
nop
nop
xor %r8, %r8
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbp
pop %rax
pop %r8
ret
.global s_faulty_load
s_faulty_load:
push %r13
push %r15
push %r8
push %rax
push %rbp
push %rbx
push %rdi
// Store
lea addresses_UC+0x13a28, %rdi
nop
nop
nop
cmp $1331, %rbx
mov $0x5152535455565758, %r8
movq %r8, (%rdi)
nop
nop
nop
nop
nop
dec %rbp
// Faulty Load
lea addresses_PSE+0x10228, %r15
and %r13, %r13
mov (%r15), %bp
lea oracles, %rbx
and $0xff, %rbp
shlq $12, %rbp
mov (%rbx,%rbp,1), %rbp
pop %rdi
pop %rbx
pop %rbp
pop %rax
pop %r8
pop %r15
pop %r13
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_PSE', 'AVXalign': False, 'congruent': 0, 'size': 32, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC', 'AVXalign': False, 'congruent': 11, 'size': 8, 'same': False, 'NT': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_PSE', 'AVXalign': False, 'congruent': 0, 'size': 2, 'same': True, 'NT': False}}
<gen_prepare_buffer>
{'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 4, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 4, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 0, 'size': 16, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 7, 'size': 2, 'same': False, 'NT': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 1, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 4, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 11, 'size': 1, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 11, 'size': 2, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 7, 'size': 1, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 0, 'size': 32, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 5, 'size': 1, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 9, 'size': 4, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 5, 'size': 1, 'same': False, 'NT': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 8, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 4, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 11, 'size': 16, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 5, 'size': 1, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 2, 'size': 16, 'same': True, 'NT': False}}
{'33': 21829}
33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33
*/
| 33.797414 | 2,999 | 0.654381 |
c33f38d12c39e8373865237d79a638934ff9f64b | 33 | rs | Rust | skia-safe/src/core/milestone.rs | katyo/rust-skia | a85f21b986a3504981e46d3628d4197ad90ded29 | [
"MIT"
] | null | null | null | skia-safe/src/core/milestone.rs | katyo/rust-skia | a85f21b986a3504981e46d3628d4197ad90ded29 | [
"MIT"
] | null | null | null | skia-safe/src/core/milestone.rs | katyo/rust-skia | a85f21b986a3504981e46d3628d4197ad90ded29 | [
"MIT"
] | null | null | null | pub const MILESTONE: usize = 79;
| 16.5 | 32 | 0.727273 |
91007f4896d1834244812f6909a8a319b6d7afc0 | 764 | asm | Assembly | src/util/oli/wm/amky.asm | olifink/qspread | d6403d210bdad9966af5d2a0358d4eed3f1e1c02 | [
"MIT"
] | null | null | null | src/util/oli/wm/amky.asm | olifink/qspread | d6403d210bdad9966af5d2a0358d4eed3f1e1c02 | [
"MIT"
] | null | null | null | src/util/oli/wm/amky.asm | olifink/qspread | d6403d210bdad9966af5d2a0358d4eed3f1e1c02 | [
"MIT"
] | null | null | null | ; multiple keystroke routine for application subwinodw
include win1_mac_oli
section utility
xdef xwm_amky
;+++
; multiple keystroke routine for application subwinodw
;
; Entry Exit
; d2.l keystroke code multiple keystroke code
; a1 ptr to keystroke counter (.l) preserved
;---
xwm_amky
tst.l d2 ; any keystroke at all?
beq.s exit
cmp.b 3(a1),d2 ; counter for the same key?
bne.s exit
move.l (a1),d2 ; get old counter
add.l #$100,d2 ; increase it
exit move.l d2,(a1) ; store it again
rts
end
| 28.296296 | 71 | 0.479058 |
01e1cd6a3478abd1bf56dfef8ae88dbc54bb570c | 891 | rs | Rust | src/tokens.rs | FuzzyWuzzie/wish-api | 43d6bcba9d9f9c25ae1b4488e5ba3be42cfba130 | [
"Apache-2.0"
] | null | null | null | src/tokens.rs | FuzzyWuzzie/wish-api | 43d6bcba9d9f9c25ae1b4488e5ba3be42cfba130 | [
"Apache-2.0"
] | null | null | null | src/tokens.rs | FuzzyWuzzie/wish-api | 43d6bcba9d9f9c25ae1b4488e5ba3be42cfba130 | [
"Apache-2.0"
] | null | null | null | extern crate jsonwebtoken as jwt;
use self::jwt::{decode, encode, Header, Validation};
use auth::AuthToken;
#[derive(Debug, Serialize, Deserialize)]
struct Claims {
iss: String,
uid: u32,
adm: bool,
}
pub fn build_token(secret: &str, uid: u32, adm: bool) -> String {
let claims = Claims {
iss: "wish-api".to_owned(),
uid,
adm,
};
let token = encode(&Header::default(), &claims, secret.as_bytes()).unwrap();
token
}
pub fn validate_token(secret: &str, token: &str) -> Result<AuthToken, ()> {
let validation = Validation {
iss: Some("wish-api".to_string()),
..Default::default()
};
let tok = decode::<Claims>(&token, secret.as_bytes(), &validation);
match tok {
Ok(t) => Ok(AuthToken {
uid: t.claims.uid,
adm: t.claims.adm,
}),
Err(_) => Err(()),
}
}
| 22.846154 | 80 | 0.56229 |
40af8c8f3236438b38a2ec95b565b4efbf998b1b | 4,709 | py | Python | dsbox/utils/utils.py | Pandinosaurus/dsbox | aea56049025ed7e6e66427f8636286f8be1b6e03 | [
"Apache-2.0"
] | 16 | 2020-05-11T09:10:15.000Z | 2021-04-13T08:43:28.000Z | dsbox/utils/utils.py | Pandinosaurus/dsbox | aea56049025ed7e6e66427f8636286f8be1b6e03 | [
"Apache-2.0"
] | 1 | 2020-12-03T20:02:32.000Z | 2020-12-03T20:02:32.000Z | dsbox/utils/utils.py | Pandinosaurus/dsbox | aea56049025ed7e6e66427f8636286f8be1b6e03 | [
"Apache-2.0"
] | 1 | 2020-05-11T17:22:20.000Z | 2020-05-11T17:22:20.000Z | import gzip
import pickle
import networkx as nx
import matplotlib.pyplot as plt
from smart_open import open
"""
Some util functions used to navigate into Airflow DAGs.
"""
def breadth_first_search_task_list(task_root, task_list=[], mode='upstream'):
sub_task_list = []
queue = [task_root]
while len(queue) > 0:
task = queue.pop(0)
sub_task_list.append(task)
next_tasks = None
if mode == 'upstream':
next_tasks = task.upstream_list
else:
next_tasks = task.downstream_list
for next_task in next_tasks:
if next_task not in queue and next_task not in task_list and next_task not in sub_task_list:
queue.append(next_task)
return sub_task_list
def breadth_first_search_shell_list(task_roots):
shell_task_list = [task_roots]
done_tasks = set()
queue = task_roots
while len(queue) > 0:
tasks = queue
next_tasks = []
for task in tasks:
for next_task in task.downstream_list:
if next_task not in done_tasks:
next_tasks.append(next_task)
done_tasks.add(next_task)
if len(next_tasks) > 0:
shell_task_list.append(next_tasks)
queue = next_tasks
return shell_task_list
def get_dag_roots(dag):
roots = []
for task in dag.tasks:
if len(task.upstream_list) == 0:
roots.append(task)
return roots
def execute_dag(dag, verbose=False, mode='downstream'):
task_list = []
roots = dag.roots
for root in roots:
sub_task_list = breadth_first_search_task_list(root, task_list, mode=mode)
task_list = sub_task_list + task_list
for task in task_list:
if verbose:
print(dag.dag_id + '-' + str(task))
if task.task_type == 'SubDagOperator':
execute_dag(task.subdag, verbose=verbose)
else:
task.execute(dag.get_template_env())
return task_list
def plot_dag(dag):
fig, ax = plt.subplots(figsize=(15, 10), dpi=150)
G = nx.DiGraph()
color_list = []
for task in dag.tasks:
if len(task.downstream_list) > 0:
for next_task in task.downstream_list:
G.add_edge(task, next_task)
for node in G.nodes():
if len(node.ui_color) == 7:
color_list.append(node.ui_color)
else:
last_code = node.ui_color[-1]
color_list.append(str(node.ui_color).ljust(7, last_code))
pos = nx.drawing.nx_agraph.graphviz_layout(G, prog='dot')
nx.draw_networkx_nodes(G, pos, node_shape='D', node_color=color_list)
nx.draw_networkx_edges(G, pos, edge_color='gray', alpha=0.8)
nx.draw_networkx_labels(G, pos, font_size=5)
ax.set_axis_off()
plt.title("DAG preview", fontsize=8)
plt.show()
"""
Some utils function used to persist objects.
"""
def pickle_compress(obj):
return gzip.zlib.compress(pickle.dumps(obj))
def decompress_unpickle(obj_zp):
return pickle.loads(gzip.zlib.decompress(obj_zp))
def write_object_file(file_path, obj):
obj_pz = pickle_compress(obj)
file_obj = open(file_path, 'wb')
file_obj.write(obj_pz)
file_obj.close()
def load_object_file(file_path):
file_obj = open(file_path, 'rb')
obj_pz = file_obj.read()
obj = decompress_unpickle(obj_pz)
return obj
"""
Some misc utils.
"""
def pandas_downcast_numeric(df_to_downcast, float_type_to_downcast=("float64", "float32"),
int_type_to_downcast=("int64", "int32")):
float_cols = [c for c in df_to_downcast.columns if df_to_downcast[c].dtype == float_type_to_downcast[0]]
int_cols = [c for c in df_to_downcast.columns if df_to_downcast[c].dtype == int_type_to_downcast[0]]
df_to_downcast[float_cols] = df_to_downcast[float_cols].apply(lambda x: x.astype(float_type_to_downcast[1]))
df_to_downcast[int_cols] = df_to_downcast[int_cols].apply(lambda x: x.astype(int_type_to_downcast[1]))
def format_dict_path_items(dictionary, replace_value):
for k, v in dictionary.items():
if isinstance(v, dict):
dictionary[k] = format_dict_path_items(v, replace_value)
else:
if isinstance(v, list):
formatted_list = []
for list_item in v:
if type(list_item) == str:
list_item = list_item.format(replace_value)
formatted_list.append(list_item)
dictionary[k] = formatted_list
else:
if type(dictionary[k]) == str:
dictionary[k] = dictionary[k].format(replace_value)
return dictionary
| 28.539394 | 112 | 0.637078 |
71e3cc773a36f573496f26d9bd939f2ae64141fd | 766 | ts | TypeScript | src/shared/model/task.model.ts | moedarrah/typing-in-the-dark | 6d225c8a015baf597da0181a185104f27781b6a5 | [
"MIT"
] | 2 | 2020-11-11T07:14:20.000Z | 2020-11-11T07:14:46.000Z | src/shared/model/task.model.ts | mmdarrah/typing-in-the-dark | 6d225c8a015baf597da0181a185104f27781b6a5 | [
"MIT"
] | null | null | null | src/shared/model/task.model.ts | mmdarrah/typing-in-the-dark | 6d225c8a015baf597da0181a185104f27781b6a5 | [
"MIT"
] | null | null | null | export interface ITask {
completed?: boolean;
exercise: ITypedText[];
instructions: ITaskInstructions;
taskId: number;
}
interface ITypedText {
text: string;
correct: boolean;
}
interface ITaskInstructions {
missionText: string;
missionTextEn: string;
missionSummary: string;
missionSummaryEn: string;
missionAlreadyCompleted: string;
missionAlreadyCompletedEn: string;
character: string;
characterEn: string;
p1a: string;
p1aEn: string;
p1b: string;
p1bEn: string;
p2: string;
p2En: string;
p3: string;
p3En: string;
img1: string;
alt1: string;
img2: string;
alt2: string;
img3?: string;
alt3?: string;
img4?: string;
alt4?: string;
img5?: string;
alt5?: string;
img6?: string;
alt6?: string;
}
| 17.813953 | 36 | 0.691906 |
7d52a1dcf4f5c6d3dbae9aef31c82209c3b90ed8 | 90 | html | HTML | _includes/author_skills.html | Rajsingh92/Rajsingh92.github.io | 113a10ac2492faf091c3ae26ce8a3d79eaeba1fe | [
"MIT"
] | null | null | null | _includes/author_skills.html | Rajsingh92/Rajsingh92.github.io | 113a10ac2492faf091c3ae26ce8a3d79eaeba1fe | [
"MIT"
] | 2 | 2022-02-11T21:53:41.000Z | 2022-03-30T22:00:07.000Z | _includes/author_skills.html | Rajsingh92/Rajsingh92.github.io | 113a10ac2492faf091c3ae26ce8a3d79eaeba1fe | [
"MIT"
] | null | null | null | <p> Python,Machine Learning,Deep Learning </p>
<p> Git,Linux,Docker and k8s,Power BI </p>
| 30 | 46 | 0.711111 |
397a2655a705f3cd061a78005725d87d334dbc89 | 1,551 | html | HTML | src/scripts/views/0-Core/_/ModerationPanel/MassModerateReportedContents/templates/FilterSelectCard.html | Jovantri10/BrainlyTools_Extension | 3130d7c27fca31b4c7614959023b0340a1710d59 | [
"MIT"
] | null | null | null | src/scripts/views/0-Core/_/ModerationPanel/MassModerateReportedContents/templates/FilterSelectCard.html | Jovantri10/BrainlyTools_Extension | 3130d7c27fca31b4c7614959023b0340a1710d59 | [
"MIT"
] | null | null | null | src/scripts/views/0-Core/_/ModerationPanel/MassModerateReportedContents/templates/FilterSelectCard.html | Jovantri10/BrainlyTools_Extension | 3130d7c27fca31b4c7614959023b0340a1710d59 | [
"MIT"
] | null | null | null | <div class="sg-card__hole">
<div class="sg-actions-list sg-actions-list--no-wrap">
<div class="sg-actions-list__hole sg-actions-list__hole--grow sg-actions-list__hole--space-bellow">
<div class="sg-select sg-select--full-width">
<div class="sg-select__icon"></div>
<select class="sg-select__element">
<option selected value="" class="sg-box--gray-secondary-lightest sg-text--gray">${System.data.locale.core.massModerateReportedContents.selectAFilter}</option>
<option value="CONTENT_TYPE" class="sg-box--peach sg-text--white">${System.data.locale.core.massModerateReportedContents.filters.byContentType}</option>
<option value="REPORTER" class="sg-box--mint sg-text--white" title="${System.data.locale.core.massModerateReportedContents.filters.byReporter.title}">${System.data.locale.core.massModerateReportedContents.filters.byReporter.text}</option>
<option value="REPORTEE" class="sg-box--blue-secondary sg-text--gray" title="${System.data.locale.core.massModerateReportedContents.filters.byReportee.title}">${System.data.locale.core.massModerateReportedContents.filters.byReportee.text}</option>
<option value="DATE_RANGE" class="sg-box--lavender sg-text--white">${System.data.locale.core.massModerateReportedContents.filters.byDateRange}</option>
<option value="REPORT_REASON" class="sg-box--dark sg-text--gray">${System.data.locale.core.massModerateReportedContents.filters.byReportReason}</option>
</select>
</div>
</div>
</div>
</div>
| 86.166667 | 257 | 0.731786 |
1665fcc2aa97c64683fe50f8c93aee49b1fabaa3 | 355 | ts | TypeScript | findyourtrashcan-mobile/src/providers/rang/rang-types.ts | FEMMLille/findYourTrashCan | f7f23c78137c6f33acb9946d6c9a27511c2ab0c0 | [
"MIT"
] | null | null | null | findyourtrashcan-mobile/src/providers/rang/rang-types.ts | FEMMLille/findYourTrashCan | f7f23c78137c6f33acb9946d6c9a27511c2ab0c0 | [
"MIT"
] | 18 | 2017-10-09T15:05:32.000Z | 2018-04-01T11:42:12.000Z | findyourtrashcan-mobile/src/providers/rang/rang-types.ts | FEMMLille/findYourTrashCan | f7f23c78137c6f33acb9946d6c9a27511c2ab0c0 | [
"MIT"
] | null | null | null | import 'rxjs/add/operator/toPromise';
import { Observable } from 'rxjs/Rx';
import { Injectable } from '@angular/core';
import { Api } from '../api/api';
@Injectable()
export class RangTypeService {
constructor(public api: Api) { }
getRankDetails(rankId: number): Observable<any> {
return this.api.get('rank-type/' + rankId);
}
} | 20.882353 | 53 | 0.659155 |
6191b56409da4f2d51541a3fc44a0ca10a01b642 | 1,663 | kt | Kotlin | app/src/main/java/alektas/telecomapp/utils/L.kt | Alektas/Telecom-System | 1e83fbe6daa496f4c4f47d41f404d3e66fb200ff | [
"Apache-2.0"
] | null | null | null | app/src/main/java/alektas/telecomapp/utils/L.kt | Alektas/Telecom-System | 1e83fbe6daa496f4c4f47d41f404d3e66fb200ff | [
"Apache-2.0"
] | null | null | null | app/src/main/java/alektas/telecomapp/utils/L.kt | Alektas/Telecom-System | 1e83fbe6daa496f4c4f47d41f404d3e66fb200ff | [
"Apache-2.0"
] | null | null | null | package alektas.telecomapp.utils
import alektas.telecomapp.BuildConfig
class L {
companion object {
private const val MEASURING_TIME_TAG = "MEASURING_TIME"
private val startPoints = mutableListOf<Pair<String, Long>>()
fun d(log: String) {
if (BuildConfig.DEBUG) println(log)
}
fun d(where: Any, log: String) {
if (BuildConfig.DEBUG) println("[${Thread.currentThread().name}][${where.javaClass.simpleName}]: $log")
}
fun d(tag: String, log: String) {
if (BuildConfig.DEBUG) println("[${Thread.currentThread().name}][$tag]: $log")
}
/**
* Start measuring time. Invoke this method at the moment where you want to start measuring.
* To count time use [stop] method at right moment. It will log measured time to the Lagcat.
*/
fun start(pointName: String = "") {
d(MEASURING_TIME_TAG, "Start measuring from |Point-$pointName|")
startPoints.add(pointName to System.nanoTime())
}
/**
* Stop measuring time. Invoke this method at the moment where you want to stop measuring.
* To start measuring use [start] method at right moment.
* This method will log measured time to the Lagcat.
*/
fun stop() {
val endTime = System.nanoTime()
d(MEASURING_TIME_TAG, "*** Stop measuring ***")
startPoints.forEachIndexed { i, p ->
d(MEASURING_TIME_TAG, "Time from |Point-$i:${p.first}| |${(endTime - p.second) * 1.0e-9}| seconds")
}
startPoints.clear()
}
}
} | 36.152174 | 115 | 0.583885 |
a57604d397dba1c27de45d476e0617ee2ca6c2b0 | 1,353 | kt | Kotlin | meijue-ui/src/main/java/com/obsez/mobile/meijue/ui/ext/SharedPrefsExtensions.kt | hedzr/meijue-ui | aa0782c8d42d412011faac9b7787eeb53efe7528 | [
"MIT"
] | 3 | 2018-10-31T08:08:00.000Z | 2019-04-27T16:45:41.000Z | meijue-ui/src/main/java/com/obsez/mobile/meijue/ui/ext/SharedPrefsExtensions.kt | hedzr/meijue-ui | aa0782c8d42d412011faac9b7787eeb53efe7528 | [
"MIT"
] | null | null | null | meijue-ui/src/main/java/com/obsez/mobile/meijue/ui/ext/SharedPrefsExtensions.kt | hedzr/meijue-ui | aa0782c8d42d412011faac9b7787eeb53efe7528 | [
"MIT"
] | null | null | null | package com.obsez.mobile.meijue.ui.ext
import android.content.SharedPreferences
import android.util.Base64
fun SharedPreferences.applyString(key: String, value: String?) = edit().putString(key, value).apply()
fun SharedPreferences.commitString(key: String, value: String?) = edit().putString(key, value).commit()
fun SharedPreferences.getString(key: String): String? = getString(key, null)
fun SharedPreferences.applyBoolean(key: String, value: Boolean = false) = edit().putBoolean(key, value).apply()
fun SharedPreferences.commitBoolean(key: String, value: Boolean = false) = edit().putBoolean(key, value).commit()
fun SharedPreferences.getBoolean(key: String): Boolean = getBoolean(key, false)
fun SharedPreferences.applyInt(key: String, value: Int = 0) = edit().putInt(key, value).apply()
fun SharedPreferences.commitInt(key: String, value: Int = 0) = edit().putInt(key, value).commit()
fun SharedPreferences.getInt(key: String): Int = getInt(key, 0)
fun SharedPreferences.applyClear() = edit().clear().apply()
fun SharedPreferences.applyByteArray(key: String, value: ByteArray) {
val encoded = Base64.encodeToString(value, Base64.NO_WRAP)
applyString(key, encoded)
}
fun SharedPreferences.getByteArray(key: String): ByteArray? {
val encoded = getString(key) ?: return null
return Base64.decode(encoded, Base64.NO_WRAP)
} | 39.794118 | 113 | 0.755358 |
301ddf5d127ec46b62da7151f577640fefc0ab9f | 1,172 | kt | Kotlin | app/src/main/java/com/eneskayiklik/wallup/feature_home/domain/use_case/HomeUseCase.kt | Enes-Kayiklik/Wall-Up | 03a9d3f07b7f788f6c36a059fe882eae78065937 | [
"Apache-2.0"
] | 19 | 2022-01-16T08:37:30.000Z | 2022-03-25T18:29:29.000Z | app/src/main/java/com/eneskayiklik/wallup/feature_home/domain/use_case/HomeUseCase.kt | Enes-Kayiklik/Wall-Up | 03a9d3f07b7f788f6c36a059fe882eae78065937 | [
"Apache-2.0"
] | 1 | 2022-01-16T10:24:47.000Z | 2022-01-18T11:16:10.000Z | app/src/main/java/com/eneskayiklik/wallup/feature_home/domain/use_case/HomeUseCase.kt | Enes-Kayiklik/Wall-Up | 03a9d3f07b7f788f6c36a059fe882eae78065937 | [
"Apache-2.0"
] | null | null | null | package com.eneskayiklik.wallup.feature_home.domain.use_case
import com.eneskayiklik.wallup.feature_home.domain.repository.HomeRepository
import com.eneskayiklik.wallup.utils.network.Resource
import com.eneskayiklik.wallup.utils.transfer_extensions.toUIModel
import kotlinx.coroutines.flow.flow
import javax.inject.Inject
class HomeUseCase @Inject constructor(
private val repository: HomeRepository
) {
suspend fun getRandomPhotos() = flow {
emit(Resource.Loading())
when (val data = repository.getRandomPhotos()) {
is Resource.Error -> emit(Resource.Error(data.message))
is Resource.Loading -> emit(Resource.Loading())
is Resource.Success -> {
try {
emit(Resource.Success(data.data.map { it.toUIModel() }))
} catch (e: Exception) {
emit(Resource.Error("An unexpected error occurred"))
}
}
}
}
suspend fun getColorList() = flow {
emit(repository.getColorList().shuffled())
}
suspend fun getCategoryList() = flow {
emit(repository.getCategoryList().shuffled())
}
} | 34.470588 | 76 | 0.646758 |
27e117c9b08468bfa56bc90d659312c8df922e82 | 4,326 | swift | Swift | goyotashi/UI/Pages/Profile/ProfileEdit/ProfileEditViewController.swift | jphacks/B_2121_1 | eff8d6db7feec31f9c145e1bd2c1ed472b7b141b | [
"MIT"
] | 1 | 2021-10-30T06:45:58.000Z | 2021-10-30T06:45:58.000Z | goyotashi/UI/Pages/Profile/ProfileEdit/ProfileEditViewController.swift | jphacks/B_2121_1 | eff8d6db7feec31f9c145e1bd2c1ed472b7b141b | [
"MIT"
] | 27 | 2021-10-29T18:02:03.000Z | 2021-10-30T13:55:46.000Z | goyotashi/UI/Pages/Profile/ProfileEdit/ProfileEditViewController.swift | jphacks/B_2121_1 | eff8d6db7feec31f9c145e1bd2c1ed472b7b141b | [
"MIT"
] | null | null | null | //
// ProfileEditViewController.swift
// goyotashi
//
// Created by 山河絵利奈 on 2021/10/29.
//
import UIKit
import ReactorKit
// import SegementSlide
final class ProfileEditViewController: UIViewController, View, ViewConstructor {
struct Const {
static let profileImageSize: CGFloat = 84
}
// MARK: - Variables
var disposeBag = DisposeBag()
// MARK: - Views
private let closeButton = UIButton().then {
$0.setImage(R.image.close(), for: .normal)
}
private let profileImageLabel = UILabel().then {
$0.apply(fontStyle: .regular, size: 15, color: Color.gray01)
$0.text = "プロフィール画像"
}
private let userNameLabel = UILabel().then {
$0.apply(fontStyle: .regular, size: 15, color: Color.gray01)
$0.text = "ニックネーム"
}
private let profileImageView = UIImageView().then {
$0.contentMode = .scaleAspectFill
$0.layer.cornerRadius = Const.profileImageSize / 2
$0.layer.masksToBounds = true
}
private let userNameTextField = UITextField().then {
$0.font = UIFont(name: FontStyle.regular.rawValue, size: 18)
}
private let doneButton = UIBarButtonItem(title: "完了", style: .done, target: nil, action: nil).then {
$0.tintColor = Color.gray01
}
// MARK: - Lify Cycles
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
setupViewConstraints()
}
// MARK: - Setup Methods
func setupViews() {
view.addSubview(profileImageLabel)
view.addSubview(profileImageView)
view.addSubview(userNameLabel)
view.addSubview(userNameTextField)
view.backgroundColor = Color.white
title = "プロフィール編集"
navigationItem.rightBarButtonItem = doneButton
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: closeButton)
}
func setupViewConstraints() {
profileImageLabel.snp.makeConstraints {
$0.top.equalTo(view.safeAreaLayoutGuide).inset(32)
$0.left.right.equalToSuperview().inset(16)
}
profileImageView.snp.makeConstraints {
$0.top.equalTo(profileImageLabel.snp.bottom).offset(24)
$0.left.equalToSuperview().inset(16)
$0.size.equalTo(Const.profileImageSize)
}
userNameLabel.snp.makeConstraints {
$0.top.equalTo(profileImageView.snp.bottom).offset(24)
$0.left.right.equalToSuperview().inset(16)
}
userNameTextField.snp.makeConstraints {
$0.top.equalTo(userNameLabel.snp.bottom).offset(24)
$0.left.right.equalToSuperview().inset(16)
}
}
// MARK: - Bind Method
func bind(reactor: ProfileEditReactor) {
// Action
reactor.action.onNext(.refresh)
doneButton.rx.tap
.map { Reactor.Action.update }
.bind(to: reactor.action)
.disposed(by: disposeBag)
userNameTextField.rx.text
.distinctUntilChanged()
.map { Reactor.Action.updateName($0) }
.bind(to: reactor.action)
.disposed(by: disposeBag)
// State
reactor.state.map { $0.profileImageUrl }
.distinctUntilChanged()
.filterNil()
.bind { [weak self] urlString in
self?.profileImageView.kf.setImage(with: URL(string: urlString), placeholder: R.image.dish())
}
.disposed(by: disposeBag)
reactor.state.map { $0.name }
.distinctUntilChanged()
.bind(to: userNameTextField.rx.text)
.disposed(by: disposeBag)
reactor.state.map { $0.apiStatus }
.distinctUntilChanged()
.bind { [weak self] apiStatus in
self?.doneButton.isEnabled = apiStatus == .pending
if apiStatus == .succeeded {
self?.dismiss(animated: false, completion: nil)
}
if apiStatus == .failed {
logger.error("failed to create a group")
}
}
.disposed(by: disposeBag)
closeButton.rx.tap
.bind { [weak self] _ in
self?.dismiss(animated: true, completion: nil)
}
.disposed(by: disposeBag)
}
}
| 30.9 | 109 | 0.590153 |
de949fcf422250d46d4d86904f710d05471a152f | 2,658 | lua | Lua | interfaces/mqtt/mqtt311.lua | hwhw/zigbee-lua | 5ac78e0d1e917f0c1681e31b3853943f024bca0c | [
"MIT"
] | 28 | 2018-12-30T09:35:41.000Z | 2021-12-16T05:01:10.000Z | interfaces/mqtt/mqtt311.lua | hwhw/zigbee-lua | 5ac78e0d1e917f0c1681e31b3853943f024bca0c | [
"MIT"
] | 8 | 2019-01-29T14:54:44.000Z | 2021-12-14T14:27:30.000Z | interfaces/mqtt/mqtt311.lua | hwhw/zigbee-lua | 5ac78e0d1e917f0c1681e31b3853943f024bca0c | [
"MIT"
] | 4 | 2020-02-13T18:54:43.000Z | 2021-08-04T05:54:16.000Z | return require"lib.codec"(function()
msg{"MQTT",
bitfield{"Header", parts={
{"RETAIN", length=1},
{"QoS", length=2},
{"DUP", length=1},
map{"ControlPacketType", length=4, values={
"Reserved",
"CONNECT",
"CONNACK",
"PUBLISH",
"PUBACK",
"PUBREC",
"PUBREL",
"PUBCOMP",
"SUBSCRIBE",
"SUBACK",
"UNSUBSCRIBE",
"UNSUBACK",
"PINGREQ",
"PINGRESP",
"DISCONNECT",
"Reserved"
}}
}},
arr{"Remainder", type=t_U8, counter=t_varint},
}
local function String(name) return arr{name, asstring=true, type=t_U8, counter=t_U16r} end
msg{"CONNECT",
arr{"ProtocolName", asstring=true, type=t_U8, counter=t_U16r, default="MQTT"},
U8{"ProtocolLevel", default=4},
bitfield{"ConnectFlags", parts={
{"Reserved", length=1, default=0},
bool{"CleanSession", length=1, default=false},
bool{"WillFlag", length=1, default=false},
{"WillQoS", length=2, default=0},
bool{"WillRetain", length=1, default=false},
bool{"PasswordFlag", length=1, default=false},
bool{"UserNameFlag", length=1, default=false},
}},
U16r{"KeepAlive", default=0},
-- Payload:
String("ClientIdentifier"),
opt{nil, when=function(v) return v.ConnectFlags.WillFlag end,
String("WillTopic"),
String("WillMessage")
},
opt{nil, when=function(v) return v.ConnectFlags.UserNameFlag end, String("UserName")},
opt{nil, when=function(v) return v.ConnectFlags.PasswordFlag end, String("Password")},
}
msg{"CONNACK",
bitfield{"ConnectAcknowledgeFlags", parts={
bool{"SessionPresent", length=1},
{"Reserved", length=7, default=0},
}},
map{"ConnectReturnCode", type=t_U8, values={
"ConnectionAccepted",
"ConnectionRefusedUnacceptableProtocolVersion",
"ConnectionRefusedIdentifierRejected",
"ConnectionRefusedServerUnavailable",
"ConnectionRefusedBadUserNameOrPassword",
"ConnectionRefusedNotAuthorized"
}},
}
msg{"PUBLISH",
String("TopicName"),
opt{nil, when=function(v,_,ctx) return ctx.QoS and ctx.QoS>0 end, U16r{"PacketIdentifier"}},
arr{"Payload", type=t_U8},
}
msg{"PUBACK",
U16r{"PacketIdentifier"},
}
msg{"PUBREC",
U16r{"PacketIdentifier"},
}
msg{"PUBREL",
U16r{"PacketIdentifier"},
}
msg{"PUBCOMP",
U16r{"PacketIdentifier"},
}
msg{"SUBSCRIBE",
U16r{"PacketIdentifier"},
arr{"Payload",
String("TopicFilter"),
U8{"QoS"},
},
}
msg{"SUBACK",
U16r{"PacketIdentifier"},
arr{"Payload", type=t_U8}, -- error on 0x80
}
msg{"UNSUBSCRIBE",
U16r{"PacketIdentifier"},
arr{"Payload",
String("TopicFilter"),
},
}
msg{"UNSUBACK",
U16r{"PacketIdentifier"},
}
end)
| 22.336134 | 94 | 0.645974 |
0f76e39431cb5a1a928072ce5fc82f88bdc34443 | 8,678 | swift | Swift | SimpleFeedUI/Modules/Feed/Single/EditAbstractFeedVC.swift | fonok3/Simple-Feed | 3e9a1f7b0f24a78270c3276320ac98805779af9e | [
"MIT"
] | null | null | null | SimpleFeedUI/Modules/Feed/Single/EditAbstractFeedVC.swift | fonok3/Simple-Feed | 3e9a1f7b0f24a78270c3276320ac98805779af9e | [
"MIT"
] | 1 | 2021-09-27T17:05:23.000Z | 2021-09-27T17:05:23.000Z | SimpleFeedUI/Modules/Feed/Single/EditAbstractFeedVC.swift | fonok3/Simple-Feed | 3e9a1f7b0f24a78270c3276320ac98805779af9e | [
"MIT"
] | null | null | null | //
// Simple Feed
// Copyright © 2020 Florian Herzog. All rights reserved.
//
import CoreData
import SimpleFeedCore
import UIKit
class EditAbstractFeedVC<Element: AbstractFeed, SelectType: AbstractFeed>: UIViewController, UITextFieldDelegate,
UITableViewDelegate, UITableViewDataSource, NSFetchedResultsControllerDelegate {
var currentFeed: Element
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
init(abstractFeed: Element) {
currentFeed = abstractFeed
super.init(nibName: nil, bundle: nil)
if #available(iOS 11.0, *) {
navigationItem.largeTitleDisplayMode = .never
}
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self as UITableViewDelegate
tableView.dataSource = self as UITableViewDataSource
extendedLayoutIncludesOpaqueBars = false
edgesForExtendedLayout = UIRectEdge()
view.backgroundColor = FHColor.fill.primary
title = NSLocalizedString("EDIT_FEED", comment: "Edit Feed")
deleteButton.addTarget(self, action: #selector(deleteFeed), for: .touchUpInside)
titleTextField.text = currentFeed.title
titleTextField.delegate = self
urlTextField.text = ""
setUpViews()
}
override func viewWillDisappear(_: Bool) {
if titleTextField.text != nil, titleTextField.text != "" {
let title = titleTextField.text ?? ""
CoreDataService.shared.performBackgroundTask { context in
guard let feed = context.object(with: self.currentFeed.objectID) as? Element else { return }
feed.title = title
feed.lastEdited = Date()
}
}
}
@objc func deleteFeed(_: UIButton) {
CoreDataService.shared.performBackgroundTask { context in
context.delete(context.object(with: self.currentFeed.objectID))
}
_ = navigationController?.popViewController(animated: true)
}
// - Mark: TextFieldDelegate
func textFieldShouldReturn(_: UITextField) -> Bool {
view.endEditing(true)
return false
}
// - Mark: TableViewDataSource
func numberOfSections(in _: UITableView) -> Int {
return fetchedResultsController?.sections?.count ?? 0
}
func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
return fetchedResultsController?.sections![section].objects?.count ?? 0
}
func tableView(_: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
if let abstractFeed = fetchedResultsController?.object(at: indexPath) {
configure(cell, with: abstractFeed)
}
return cell
}
func tableView(_: UITableView, didSelectRowAt _: IndexPath) {}
func configureCellAt(_ indexPath: IndexPath) {
let cell = UITableViewCell()
if let abstractFeed = fetchedResultsController?.object(at: indexPath) {
configure(cell, with: abstractFeed)
}
}
func configure(_ cell: UITableViewCell, with abstractFeed: SelectType) {
cell.textLabel?.text = abstractFeed.title
}
// - NSFetchedResultsControllerDelegate
var fetchedResultsController: NSFetchedResultsController<SelectType>? {
if internalFetchedResultsController != nil,
internalFetchedResultsController?.managedObjectContext == CoreDataService.shared.viewContext {
return internalFetchedResultsController!
}
let context = CoreDataService.shared.viewContext
let fetchRequest = NSFetchRequest<SelectType>(entityName: String(describing: SelectType.self))
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "index", ascending: true),
NSSortDescriptor(key: "title", ascending: true)]
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest,
managedObjectContext: context,
sectionNameKeyPath: nil, cacheName: nil)
aFetchedResultsController.delegate = self
internalFetchedResultsController = aFetchedResultsController
do {
try internalFetchedResultsController!.performFetch()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
return internalFetchedResultsController!
}
var internalFetchedResultsController: NSFetchedResultsController<SelectType>?
func controllerWillChangeContent(_: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.beginUpdates()
}
func controller(_: NSFetchedResultsController<NSFetchRequestResult>, didChange _: Any, at indexPath: IndexPath?,
for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .insert:
tableView.insertRows(at: [newIndexPath!], with: .fade)
case .update:
configureCellAt(indexPath!)
case .delete:
tableView.deleteRows(at: [indexPath!], with: .fade)
default:
break
}
}
func controllerDidChangeContent(_: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.endUpdates()
}
func setUpViews() {
view.addSubview(titleTextField)
view.addSubview(deleteButton)
view.addSubview(titleLabel)
view.addSubview(urlTextField)
view.addConstraintsWithFormat("H:[v0(70)]-8-[v1]", views: titleLabel, titleTextField)
view.addConstraintsWithFormat("H:[v0(150)]", views: deleteButton)
view.addConstraintsWithFormat("V:|-20-[v0(30)]", views: titleLabel)
view.addConstraintsWithFormat("V:|-20-[v0(30)]-20-[v1]-30-[v2(30)]", views: titleTextField, urlTextField, deleteButton)
view.addConstraint(NSLayoutConstraint(item: deleteButton, attribute: .centerX,
relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 1))
view.addSubview(tableViewDescriptionLabel)
view.addSubview(tableView)
view.addConstraintsWithFormat("V:[v0]-8-[v1]-8-[v2]-8-|", views: deleteButton, tableViewDescriptionLabel, tableView)
view.addConstraintsWithFormat("H:|[v0]|", views: tableView)
titleLabel.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor).isActive = true
titleTextField.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor).isActive = true
urlTextField.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor).isActive = true
urlTextField.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor).isActive = true
tableViewDescriptionLabel.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor).isActive = true
tableViewDescriptionLabel.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor).isActive = true
}
let titleTextField: UITextField = {
let textField = UITextField()
textField.backgroundColor = FHColor.fill.secondary
textField.tintColor = FHColor.label.secondary
textField.textAlignment = .center
textField.clearButtonMode = .whileEditing
textField.returnKeyType = .done
return textField
}()
let deleteButton: UIButton = {
let button = UIButton(type: .system)
button.setTitleColor(UIColor.white, for: UIControl.State())
button.backgroundColor = FHColor.simpleFeedRed
button.setTitle(NSLocalizedString("DELETE", comment: "DELETE"), for: UIControl.State())
return button
}()
let titleLabel: UILabel = {
let label = UILabel()
label.text = NSLocalizedString("TITLE", comment: "Title") + ":"
return label
}()
let urlTextField: UITextField = {
let textField = UITextField()
textField.isEnabled = false
textField.textAlignment = .center
return textField
}()
let tableView: UITableView = {
let tableView = UITableView()
tableView.allowsSelection = true
tableView.allowsMultipleSelection = true
return tableView
}()
let tableViewDescriptionLabel: UILabel = {
let label = UILabel()
return label
}()
}
| 38.229075 | 128 | 0.663978 |
1c7b71e7edee14ef1b915e1a40df74305c6b00ae | 2,194 | css | CSS | style.css | NjaalWiik/front-end-infinite-scroll | a18c4b4146cb7b5168c15e70faed2b8f104f61d3 | [
"MIT"
] | null | null | null | style.css | NjaalWiik/front-end-infinite-scroll | a18c4b4146cb7b5168c15e70faed2b8f104f61d3 | [
"MIT"
] | null | null | null | style.css | NjaalWiik/front-end-infinite-scroll | a18c4b4146cb7b5168c15e70faed2b8f104f61d3 | [
"MIT"
] | null | null | null | @import url('https://fonts.googleapis.com/css2?family=Bebas+Neue&display=swap');
html {
box-sizing: border-box;
}
body {
margin: 0;
min-height: 100vh;
font-family: Bebas Neue, sans-serif;
background: whitesmoke;
}
h1 {
text-align: center;
margin-top: 25px;
margin-bottom: 15px;
font-size: 40px;
font-weight: 700;
letter-spacing: 5px;
}
.image-container {
margin: 10px 30%;
}
.image-container img {
width: 100%;
margin-top: 10px;
}
.spinner {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: rgba(255, 255, 255, 0.8);
}
.spinner div {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, 50%);
}
.cube1,
.cube2 {
background-color: #333;
width: 15px;
height: 15px;
position: absolute;
top: 0;
left: 0;
-webkit-animation: sk-cubemove 1.8s infinite ease-in-out;
animation: sk-cubemove 1.8s infinite ease-in-out;
}
.cube2 {
-webkit-animation-delay: -0.9s;
animation-delay: -0.9s;
}
@-webkit-keyframes sk-cubemove {
25% {
-webkit-transform: translateX(42px) rotate(-90deg) scale(0.5);
}
50% {
-webkit-transform: translateX(42px) translateY(42px) rotate(-180deg);
}
75% {
-webkit-transform: translateX(0px) translateY(42px) rotate(-270deg)
scale(0.5);
}
100% {
-webkit-transform: rotate(-360deg);
}
}
@keyframes sk-cubemove {
25% {
transform: translateX(42px) rotate(-90deg) scale(0.5);
-webkit-transform: translateX(42px) rotate(-90deg) scale(0.5);
}
50% {
transform: translateX(42px) translateY(42px) rotate(-179deg);
-webkit-transform: translateX(42px) translateY(42px) rotate(-179deg);
}
50.1% {
transform: translateX(42px) translateY(42px) rotate(-180deg);
-webkit-transform: translateX(42px) translateY(42px) rotate(-180deg);
}
75% {
transform: translateX(0px) translateY(42px) rotate(-270deg) scale(0.5);
-webkit-transform: translateX(0px) translateY(42px) rotate(-270deg)
scale(0.5);
}
100% {
transform: rotate(-360deg);
-webkit-transform: rotate(-360deg);
}
}
@media screen and (max-width: 600px) {
h1 {
font-size: 20px;
}
.image-container {
margin: 10px;
}
}
| 19.078261 | 80 | 0.643573 |
7f2cfc56b5458e586ead541532f65f3e419f23a5 | 2,942 | go | Go | cloud/metainfo/utils.go | baijinping/gopkg | 5163f120fcf9db6c7bd0a10a3f7794fa29c28570 | [
"Apache-2.0"
] | 534 | 2021-04-21T08:14:10.000Z | 2022-03-31T05:13:30.000Z | cloud/metainfo/utils.go | 5for3to1/gopkg | 4ff9dac569408b0ffa51156efcd8de9d8dc11357 | [
"Apache-2.0"
] | 37 | 2021-05-11T02:37:07.000Z | 2022-03-31T08:52:43.000Z | cloud/metainfo/utils.go | 5for3to1/gopkg | 4ff9dac569408b0ffa51156efcd8de9d8dc11357 | [
"Apache-2.0"
] | 73 | 2021-05-18T12:10:33.000Z | 2022-03-29T11:58:28.000Z | // Copyright 2021 ByteDance Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package metainfo
import (
"context"
"strings"
)
// HasMetaInfo detects whether the given context contains metainfo.
func HasMetaInfo(ctx context.Context) bool {
return getNode(ctx) != nil
}
// SetMetaInfoFromMap retrieves metainfo key-value pairs from the given map and sets then into the context.
// Only those keys with prefixes defined in this module would be used.
// If the context has been carrying metanifo pairs, they will be merged as a basis.
func SetMetaInfoFromMap(ctx context.Context, m map[string]string) context.Context {
if ctx == nil {
return nil
}
if len(m) == 0 {
return ctx
}
var mv *mapView
if x := getNode(ctx); x != nil {
mv = x.mapView()
} else {
mv = newMapView()
}
for k, v := range m {
if len(k) == 0 || len(v) == 0 {
continue
}
switch {
case strings.HasPrefix(k, PrefixTransientUpstream):
if len(k) > lenPTU { // do not move this condition to the case statement to prevent a PTU matches PT
mv.stale[k[lenPTU:]] = v
}
case strings.HasPrefix(k, PrefixTransient):
if len(k) > lenPT {
mv.transient[k[lenPT:]] = v
}
case strings.HasPrefix(k, PrefixPersistent):
if len(k) > lenPP {
mv.persistent[k[lenPP:]] = v
}
}
}
if mv.size() == 0 {
// TODO: remove this?
return ctx
}
return withNode(ctx, mv.toNode())
}
// SaveMetaInfoToMap set key-value pairs from ctx to m while filtering out transient-upstream data.
func SaveMetaInfoToMap(ctx context.Context, m map[string]string) {
if ctx == nil || m == nil {
return
}
ctx = TransferForward(ctx)
for k, v := range GetAllValues(ctx) {
m[PrefixTransient+k] = v
}
for k, v := range GetAllPersistentValues(ctx) {
m[PrefixPersistent+k] = v
}
}
// sliceToMap converts a kv slice to map. If the slice is empty, an empty map will be returned instead of nil.
func sliceToMap(slice []kv) (m map[string]string) {
if size := len(slice); size == 0 {
m = make(map[string]string)
} else {
m = make(map[string]string, size)
}
for _, kv := range slice {
m[kv.key] = kv.val
}
return
}
// mapToSlice converts a map to a kv slice. If the map is empty, the return value will be nil.
func mapToSlice(kvs map[string]string) (slice []kv) {
size := len(kvs)
if size == 0 {
return
}
slice = make([]kv, 0, size)
for k, v := range kvs {
slice = append(slice, kv{key: k, val: v})
}
return
}
| 25.807018 | 110 | 0.67811 |
ec44f43397d0134c9075ec8bce576209623fbbc3 | 67 | sql | SQL | src/test/resources/sql/drop_table/466fcccd.sql | Shuttl-Tech/antlr_psql | fcf83192300abe723f3fd3709aff5b0c8118ad12 | [
"MIT"
] | 66 | 2018-06-15T11:34:03.000Z | 2022-03-16T09:24:49.000Z | src/test/resources/sql/drop_table/466fcccd.sql | Shuttl-Tech/antlr_psql | fcf83192300abe723f3fd3709aff5b0c8118ad12 | [
"MIT"
] | 13 | 2019-03-19T11:56:28.000Z | 2020-08-05T04:20:50.000Z | src/test/resources/sql/drop_table/466fcccd.sql | Shuttl-Tech/antlr_psql | fcf83192300abe723f3fd3709aff5b0c8118ad12 | [
"MIT"
] | 28 | 2019-01-05T19:59:02.000Z | 2022-03-24T11:55:50.000Z | -- file:truncate.sql ln:128 expect:true
DROP TABLE trunc_f CASCADE
| 22.333333 | 39 | 0.791045 |
21f809769067bfcd173d27df8a56c55de218fd85 | 2,941 | html | HTML | estudos/desafios/modulo-01/d005/index.html | lucasllimati/html-css-cursoemvideo | 7f4184577a1487124268293f8bf63faf6d768911 | [
"MIT"
] | null | null | null | estudos/desafios/modulo-01/d005/index.html | lucasllimati/html-css-cursoemvideo | 7f4184577a1487124268293f8bf63faf6d768911 | [
"MIT"
] | null | null | null | estudos/desafios/modulo-01/d005/index.html | lucasllimati/html-css-cursoemvideo | 7f4184577a1487124268293f8bf63faf6d768911 | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="../d002/imagens/favicon.ico" type="image/x-icon">
<title>Social - Desafio 05</title>
</head>
<body>
<h1>Minhas redes sociais - Gustavo Guanabara</h1>
<h2>Quem sou eu?</h2>
<img src="imagens/foto-perfil-guanabara.png" alt="foto-perfil">
<p>Meu nome é <strong>Gustavo Guanabara</strong>, sou professor de Tecnologia desde 1994 e hoje produzo conteúdo para quem está iniciando no ramo da programação e desenvolvimento de site/aplicações. São muitos anos dentro de sala de aula, tentando mostrar de forma simples e objetiva alguns conceitos que muita gente iniciante acha muito difícil.</p>
<h2>Como falar comigo?</h2>
<li>
<abbr title="Youtube">
<img src="imagens/icone-youtube.png" alt="Imagem logo Youtube">
</abbr>
<a
href="https://www.youtube.com/user/cursosemvideo" target="_blank" rel="external">/cursosemvideo</a> - Se inscreva lá no meu canal do YouTube
</li>
<li>
<abbr title="GitHub">
<img src="imagens/icone-github.png" alt="Imagem logo GitHub">
</abbr>
<a
href="https://github.com/gustavoguanabara" target="_blank" rel="external">/gustavoguanabara</a> - Acessa meu repositório público no GitHub
</li>
<li>
<abbr title="Instagram">
<img src="imagens/icone-instagram.png" alt="Imagem logo Instagram">
</abbr>
<a
href="https://www.instagram.com/cursoemvideo/" target="_blank" rel="external">/gustavoguanabara</a> - Me segue lá no Instagram
</li>
<li>
<abbr title="LinkedIn">
<img src="imagens/icone-linkedin.png" alt="Imagem logo LinkedIn">
</abbr>
<a
href="https://www.linkedin.com/in/guanabara/" target="_blank" rel="external">/guanabara</a> - Me adiciona lá no LinkedIn
</li>
<li>
<abbr title="Twitter">
<img src="imagens/icone-twitter.png" alt="Imagem logo Twitter">
</abbr>
<a
href="https://twitter.com/guanabara" target="_blank" rel="external">guanabara</a> - Me segue lá no Twitter
</li>
<li>
<abbr title="Facebook">
<img src="imagens/icone-facebook.png" alt="Imagem logo Facebook">
</abbr>
<a
href="https://www.facebook.com/CursosEmVideo/" target="_blank" rel="external">/gustavoguanabara</a> - Me acompanha lá no Facebook
</li>
<li>
<abbr title="Site">
<img src="imagens/icone-facebook.png" alt="Imagem logo Site">
</abbr>
<a
href="https://www.cursoemvideo.com/" target="_blank" rel="external">/gustavoguanabara</a> - Me acompanha lá no Facebook
</li>
</body>
</html> | 42.014286 | 354 | 0.618837 |
6ee519820ddcceed03f747faf1c47917623d1c4a | 785 | html | HTML | Front-End/Primeiro-Bimestre/Aula-09/index.html | issaotakeuchi/CertifiedTechDeveloper | 908e52871e886e3e3558b0d0272c6442f1d57987 | [
"MIT"
] | null | null | null | Front-End/Primeiro-Bimestre/Aula-09/index.html | issaotakeuchi/CertifiedTechDeveloper | 908e52871e886e3e3558b0d0272c6442f1d57987 | [
"MIT"
] | null | null | null | Front-End/Primeiro-Bimestre/Aula-09/index.html | issaotakeuchi/CertifiedTechDeveloper | 908e52871e886e3e3558b0d0272c6442f1d57987 | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="menu">
<ul>
<li>anéis</li>
<li>brincos</li>
<li>colares</li>
<li>pulseiras</li>
<li>relógios</li>
<li>acessórios</li>
</ul>
</div>
<div class="banner"></div>
<div class="produtos">
<ul>
<li>relogio xpto</li>
<li>relogio xyz</li>
<li>brinco xpto</li>
<li>brinco xyz</li>
<li>anel abc</li>
<li>anel xpto</li>
</ul>
</div>
</body>
</html> | 20.128205 | 74 | 0.513376 |
2f5d5eb28b75ce92f382548bbd46910dc8dd3d33 | 4,540 | php | PHP | resources/views/vehicleBrands.blade.php | heshananupama/autohub-php | de2ea276d35e8dcffd2068aaa2f3d16bf9bb3956 | [
"MIT"
] | null | null | null | resources/views/vehicleBrands.blade.php | heshananupama/autohub-php | de2ea276d35e8dcffd2068aaa2f3d16bf9bb3956 | [
"MIT"
] | null | null | null | resources/views/vehicleBrands.blade.php | heshananupama/autohub-php | de2ea276d35e8dcffd2068aaa2f3d16bf9bb3956 | [
"MIT"
] | null | null | null |
@extends('index')
@section('content')
<h3 class="text-left" style="margin-left: 20px;">Search Results for BMW</h3>
<div class="panel-default" style="margin:20px 100px;">
<div class="panel-heading">Refinements </div>
<div class="panel-body">
<div class="row">
<div class="col-sm-2">
<div class="form-group">
<label for="condition" class="control-label">
Condition</label>
<select id="condition" name="condition" type="text"
class="form-control" required>
<option value="">Brand New</option>
<option value="">Re Condition</option>
<option value="">Any Condition</option>
</select>
</div>
</div>
<div class="col-sm-2">
<div class="form-group">
<label for="condition" class="control-label">
Price From</label>
<input id="price1" name="priceFrom" type="number"
placeholder="Rs." class="form-control" required/>
</div>
</div>
<div class="col-sm-2">
<div class="form-group">
<label for="condition" class="control-label">
Price To</label>
<input id="price2" name="priceTo" type="number"
placeholder="Rs." class="form-control" required/>
</div>
</div>
<div class="col-sm-2">
<div class="form-group">
<label for="SortBy" class="control-label">
Sort By</label>
<select id="sortby" name="sortby" type="text"
class="form-control" required>
<option value="">Name</option>
<option value="">Price</option>
<option value="">Part Category</option>
</select>
</div>
</div>
<div class="col-sm-2">
<div class="form-group">
<label for="condition" class="control-label">
Car Model</label>
<select id="model" name="condition" type="text"
class="form-control" required>
<option value="">All</option>
<option value="">BMW i3 BEV</option>
<option value="">BMW 330e M </option>
<option value="">BMW 520D</option>
</select>
</div>
</div>
<div class="col-sm-2">
<div class="form-group">
<label for="condition" class="control-label">
Part Category</label>
<select id="category" name="condition" type="text"
class="form-control" required>
<option value="">Alternator</option>
<option value="">Bearings</option>
<option value="">Belts</option>
<option value="">Body Parts</option>
<option value="">Braking System</option>
<option value="">Cables</option>
<option value="">Clutch</option>
<option value="">Drivetrain</option>
<option value="">Electricals</option>
<option value="">Electronics</option>
<option value="">Engine parts</option>
<option value="">Filters</option>
<option value="">Gaskets</option>
<option value="">Belts</option>
</select>
</div>
</div>
</div>
</div>
</div>
<div class="container">
<h4>Sorry No Results Found </h4>
</div>
<br>
<br><br><br><br><br><br><br><br><br><br>
@endsection
| 38.151261 | 82 | 0.392291 |
66c33f57c8b8c2e015b7386d708b314fd8014982 | 1,060 | swift | Swift | Player/Context/Manifest/Manifest.swift | EricssonBroadcastServices/iOSClientPlayer | cca18ad5a80f1573969b8dd1ec9ed56dabdc5cb3 | [
"Apache-2.0"
] | 12 | 2019-07-12T05:01:24.000Z | 2022-03-22T02:06:47.000Z | Player/Context/Manifest/Manifest.swift | EricssonBroadcastServices/iOSClientPlayer | cca18ad5a80f1573969b8dd1ec9ed56dabdc5cb3 | [
"Apache-2.0"
] | 1 | 2018-03-06T20:10:46.000Z | 2018-03-06T20:10:46.000Z | Player/Context/Manifest/Manifest.swift | EricssonBroadcastServices/iOSClientPlayer | cca18ad5a80f1573969b8dd1ec9ed56dabdc5cb3 | [
"Apache-2.0"
] | 5 | 2018-03-07T20:49:50.000Z | 2022-02-20T14:17:10.000Z | //
// Manifest.swift
// Player
//
// Created by Fredrik Sjöberg on 2017-11-23.
// Copyright © 2017 emp. All rights reserved.
//
import Foundation
/// Basic `MediaSource` that can do simple playback of *unencrypted* media sources.
///
/// It has an optional drm agent in the form of a `FairplayRequester` that, if implemented, can be used to play *FairPlay* protected media using the `HLSNative` tech.
public class Manifest: MediaSource {
/// Basic connector
public var analyticsConnector: AnalyticsConnector = PassThroughConnector()
/// Drm agent to play *FairPlay* using the `HLSNative` tech.
public let fairplayRequester: FairplayRequester?
/// Unique playsession id
public let playSessionId: String
/// Media locator for the media source.
public let url: URL
public init(url: URL, playSessionId: String = UUID().uuidString, fairplayRequester: FairplayRequester? = nil) {
self.url = url
self.playSessionId = playSessionId
self.fairplayRequester = fairplayRequester
}
} | 33.125 | 166 | 0.7 |
252a7e7fbadd13a20e101809c6dfe0bf95856270 | 2,514 | kt | Kotlin | src/main/kotlin/lain/Lexer.kt | liminalitythree/bakadesu | 6d5fbcc29da148fd72ecb58b164fc5c845267e5c | [
"CC0-1.0"
] | null | null | null | src/main/kotlin/lain/Lexer.kt | liminalitythree/bakadesu | 6d5fbcc29da148fd72ecb58b164fc5c845267e5c | [
"CC0-1.0"
] | null | null | null | src/main/kotlin/lain/Lexer.kt | liminalitythree/bakadesu | 6d5fbcc29da148fd72ecb58b164fc5c845267e5c | [
"CC0-1.0"
] | null | null | null | package lain
import java.time.Clock
class Lexer(val source: List<String>) {
private val tokens = mutableListOf<Token>()
private var start = 0
private var current = 0
fun scanTokens(): List<Token> {
while (!isAtEnd()) {
// we are at the beginning of the next lexeme
start = current
scanToken()
}
tokens.add(Token(TokenType.EOF, "", null))
return tokens.toList()
}
// scan one token maybe
private fun scanToken() {
val c:String = advance()
when (c) {
"\uD83E\uDD1C" -> addToken(TokenType.LEFT_PAREN)
"\uD83E\uDD1B" -> addToken(TokenType.RIGHT_PAREN)
"\uD83D\uDC49" -> addToken(TokenType.LEFT_BRACKET)
"\uD83D\uDC48" -> addToken(TokenType.RIGHT_BRACKET)
"〰" -> addToken(TokenType.COMMA)
else -> {
if (isDigit(c)) number()
else identifier(c)
}
}
}
// turns [0-9]+ into a token and adds it to token list
private fun number() {
while (ClockNumbers.isClock(peek())) advance()
addToken(TokenType.NUMBER, ClockNumbers.parseClocks(source.subList(start, current)))
}
// identifier is just 1 emoji
private fun identifier(c: String) {
addToken(TokenType.IDENTIFIER, c)
}
// consumes current character if matches expected, else returns false
private fun match(expected: String): Boolean {
if (isAtEnd()) return false
if (source[current] != expected) return false
current++
return true
}
// returns character without consuming it
private fun peek(): String {
if (isAtEnd()) return "\u0000"
return source[current]
}
// returns true if c is [0-9]
private fun isDigit(c: String): Boolean {
return ClockNumbers.isClock(c)
}
// returns true if at end of string source, false if not
private fun isAtEnd(): Boolean {
return current >= source.size
}
// advance the pointer and return the new current char
private fun advance(): String {
current++
return source[current - 1]
}
// adds a token to the list of tokens
private fun addToken(type: TokenType, literal: Any?) {
val text = source.subList(start, current).reduce { a, e -> a.plus(e) }
tokens.add(Token(type, text, literal))
}
private fun addToken(type: TokenType) {
addToken(type, null)
}
} | 27.326087 | 92 | 0.585919 |
64e001a125c823bf162f4795a42b3d093c67a517 | 1,868 | rs | Rust | basic/src/main.rs | honkkki/rust-practice | 73a0715c25ffb6ae10885cde092748d0effc5457 | [
"MIT"
] | null | null | null | basic/src/main.rs | honkkki/rust-practice | 73a0715c25ffb6ae10885cde092748d0effc5457 | [
"MIT"
] | null | null | null | basic/src/main.rs | honkkki/rust-practice | 73a0715c25ffb6ae10885cde092748d0effc5457 | [
"MIT"
] | null | null | null | const MAX_POINTS: u32 = 1000;
fn main() {
let i: i64 = 1;
println!("{}", i);
let f = 1.1; // default f64
let a = 1; // default i32
let cc = '\u{1F601}';
println!("{}", f);
println!("{}", a);
println!("{}", cc);
println!("{}", MAX_POINTS);
// while
let max = 10;
let mut num = 0;
while num * num < max {
println!("{0} * {0} = {1}", num, num * num);
num += 1;
}
let mut x = 1;
const MAX_NUM: i8 = 10;
while x < MAX_NUM {
// 允许重复定义相同变量名
let mut y = x;
while y < MAX_NUM {
print!("{}*{}={} ", x, y, x * y);
y += 1;
}
println!();
x += 1;
}
let mut num = 0;
// loop无限循环
loop {
println!("{0} * {0} = {1}", num, num * num);
num += 1;
if num * num > max {
break;
}
}
let t: bool = true;
println!("{}", t);
println!("--------------------------");
// tuple
let tup: (i32, i64) = (500, 1000);
println!("{}, {}", tup.0, tup.1);
let (x, y) = tup;
println!("{}, {}", x, y);
println!("--------------------------");
// array
let arr: [i32; 3] = [1, 2, 3];
println!("{}", arr[0]);
for elem in arr {
println!("arr: {}", elem)
}
println!("--------------------------");
// 控制流
let y = {
let x = 1;
x + 1
};
println!("{}", y);
let num = get_num();
println!("{}", num);
let condition = true;
let num = if condition {1} else {0};
println!("{}", num);
println!("--------------------------");
range_num();
let mut str = "hello";
println!("{}", str);
str = "rust";
println!("{}", str);
}
fn get_num() -> i32 {
6
}
fn range_num() {
for num in 1..6 { // 1-5
println!("{}", num)
}
}
| 18.868687 | 52 | 0.367773 |
f50498bd7531d81d4826d528e71a90c5dd07a06e | 388 | swift | Swift | CooeeSDK/models/DeviceAuthResponse.swift | letscooee/cooee-ios-sdk | 2f18810ca1597c712551c088d54b066d198f30ca | [
"MIT"
] | null | null | null | CooeeSDK/models/DeviceAuthResponse.swift | letscooee/cooee-ios-sdk | 2f18810ca1597c712551c088d54b066d198f30ca | [
"MIT"
] | null | null | null | CooeeSDK/models/DeviceAuthResponse.swift | letscooee/cooee-ios-sdk | 2f18810ca1597c712551c088d54b066d198f30ca | [
"MIT"
] | null | null | null | //
// DeviceAuthResponse.swift
// CooeeSDK
//
// Created by Ashish Gaikwad on 21/09/21.
//
import Foundation
import HandyJSON
/**
DeviceAuthResponse Holds successful response from server if device get register
- Author: Ashish Gaikwad
- Since: 1.3.0
*/
struct DeviceAuthResponse: Decodable, HandyJSON {
var id: String?
var deviceID: String?
var sdkToken: String?
}
| 16.869565 | 80 | 0.71134 |
1bea4f9170d93c869c69aa3eaf4ff1dbd4272e44 | 202 | py | Python | science_data_structure/test_config.py | woutervanveen/science_data_structure | 90a7438d65020f0e7c3be1df7f9e72f54e97f119 | [
"MIT"
] | null | null | null | science_data_structure/test_config.py | woutervanveen/science_data_structure | 90a7438d65020f0e7c3be1df7f9e72f54e97f119 | [
"MIT"
] | null | null | null | science_data_structure/test_config.py | woutervanveen/science_data_structure | 90a7438d65020f0e7c3be1df7f9e72f54e97f119 | [
"MIT"
] | null | null | null | import unittest
import config
class TestConfig(unittest.TestCase):
def setUp(self):
pass
def test_config_loading(self):
pass
if __name__ == "__main__":
unittest.main()
| 12.625 | 36 | 0.658416 |
1699f4caf242a31e826c7cee672dcb770f3f9684 | 511 | h | C | apps/on_boarding/localization_controller.h | VersiraSec/epsilon-cfw | d12b44c6c6668ecc14b60d8dd098ba5c230b1291 | [
"FSFAP"
] | 1,442 | 2017-08-28T19:39:45.000Z | 2022-03-30T00:56:14.000Z | apps/on_boarding/localization_controller.h | VersiraSec/epsilon-cfw | d12b44c6c6668ecc14b60d8dd098ba5c230b1291 | [
"FSFAP"
] | 1,321 | 2017-08-28T23:03:10.000Z | 2022-03-31T19:32:17.000Z | apps/on_boarding/localization_controller.h | VersiraSec/epsilon-cfw | d12b44c6c6668ecc14b60d8dd098ba5c230b1291 | [
"FSFAP"
] | 421 | 2017-08-28T22:02:39.000Z | 2022-03-28T20:52:21.000Z | #ifndef ON_BOARDING_LOCALIZATION_CONTROLLER_H
#define ON_BOARDING_LOCALIZATION_CONTROLLER_H
#include <apps/shared/localization_controller.h>
namespace OnBoarding {
class LocalizationController : public Shared::LocalizationController {
public:
using Shared::LocalizationController::LocalizationController;
int indexOfCellToSelectOnReset() const override;
bool shouldDisplayTitle() const override { return mode() == Mode::Country; }
bool handleEvent(Ion::Events::Event event) override;
};
}
#endif
| 24.333333 | 78 | 0.808219 |
e7758916a2997e692c1b72e7eff177386089ee1c | 3,520 | js | JavaScript | bot/bot.js | andrewhayward/basic-slack-bot | b18dbedb03d45d215f761427fe3ac874424827f9 | [
"0BSD"
] | null | null | null | bot/bot.js | andrewhayward/basic-slack-bot | b18dbedb03d45d215f761427fe3ac874424827f9 | [
"0BSD"
] | 4 | 2017-11-12T04:12:16.000Z | 2017-11-13T18:06:48.000Z | bot/bot.js | andrewhayward/basic-slack-bot | b18dbedb03d45d215f761427fe3ac874424827f9 | [
"0BSD"
] | null | null | null | const {
RtmClient,
WebClient,
CLIENT_EVENTS,
RTM_EVENTS
} = require('@slack/client');
const debug = require('./lib/debug');
const models = require('./models');
const Filter = require('./lib/filter');
function meta (bot) {
if (!meta.map.has(bot)) {
meta.map.set(bot, {});
}
return meta.map.get(bot);
}
meta.map = new WeakMap();
class Bot {
constructor (token, opts = {}) {
if (!token) {
throw new Error('Missing token');
}
const config = Object.assign({ useRtmConnect: false }, opts, {
autoMark: true,
autoReconnect: true,
logger: (logLevel, logString) => {},
logLevel: 'error'
});
meta(this).rtm = new RtmClient(token, config);
meta(this).web = new WebClient(token);
meta(this).ready = new Promise((resolve, reject) => {
const client = meta(this).rtm;
client.on(CLIENT_EVENTS.RTM.AUTHENTICATED, (state) => {
debug('Successfully connected');
const { prefs, ...self } = state.self;
meta(this).meta = Object.freeze(self);
resolve(this);
});
client.on(CLIENT_EVENTS.RTM.DISCONNECT, (reason) => {
if (reason === 'account_inactive is not recoverable') {
debug('Connection failed');
reject(reason);
}
});
});
const { dataStore } = meta(this).rtm;
Object.keys(dataStore.constructor.prototype).forEach((key) => {
if (key.startsWith('get') && typeof dataStore[key] === 'function') {
this[key] = (...args) => {
const data = dataStore[key](...args);
if (typeof data === 'undefined') return Promise.resolve(undefined);
// eslint-disable-next-line no-underscore-dangle
const Model = models[data._modelName];
return Promise.resolve(new Model(data, this));
};
}
});
meta(this).handlers = [];
meta(this).rtm.on(RTM_EVENTS.MESSAGE, (msg) => {
if (msg.hidden || msg.user === this.meta.id) return;
models.Message.create(msg, this).then((message) => {
const { handlers } = meta(this);
debug('Dispatching message to %d handlers: %O', handlers.length, message);
handlers.every(({ filter, callback }, index) => {
let rsp = true;
if (filter.test(message)) {
debug('Message passed filter: %O', filter);
rsp = callback.call(this, message, this);
if (typeof rsp === 'undefined') rsp = true;
}
if (!rsp) {
debug('Breaking after %d iterations', index + 1);
}
return !!rsp;
});
});
});
}
get meta () {
return meta(this).meta;
}
connect () {
meta(this).rtm.start();
return meta(this).ready;
}
disconnect () {
meta(this).rtm.disconnect('client disconnected');
}
ready (callback) {
meta(this).ready.then(callback);
return this;
}
postMessage (target, { text, ...msg }, callback) {
const message = { ...msg, as_user: true };
meta(this).web.chat.postMessage(target, text, message, callback);
}
onMessage (filter, callback) {
if (arguments.length === 1 && typeof filter === 'function') {
// eslint-disable-next-line no-param-reassign
callback = filter;
// eslint-disable-next-line no-param-reassign
filter = undefined;
}
if (typeof callback === 'function') {
meta(this).handlers.push({
filter: new Filter(filter),
callback: callback
});
}
}
}
module.exports = Bot;
| 25.507246 | 82 | 0.564773 |
dd61ec61aea44701166b8715de5282909c3fb2f0 | 10,874 | go | Go | pkg/storage/redis/redis.go | rspier/pomerium | 2dc8879583298f6dff600881ccdbd715951c519e | [
"Apache-2.0"
] | 1 | 2021-04-19T18:40:21.000Z | 2021-04-19T18:40:21.000Z | pkg/storage/redis/redis.go | rspier/pomerium | 2dc8879583298f6dff600881ccdbd715951c519e | [
"Apache-2.0"
] | 2 | 2020-09-09T14:17:52.000Z | 2020-09-09T14:24:57.000Z | pkg/storage/redis/redis.go | rspier/pomerium | 2dc8879583298f6dff600881ccdbd715951c519e | [
"Apache-2.0"
] | null | null | null | // Package redis is the redis database, implements storage.Backend interface.
package redis
import (
"context"
"crypto/tls"
"fmt"
"net"
"strconv"
"sync"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes"
"github.com/gomodule/redigo/redis"
"google.golang.org/protobuf/types/known/anypb"
"github.com/pomerium/pomerium/config"
"github.com/pomerium/pomerium/internal/log"
"github.com/pomerium/pomerium/internal/telemetry/metrics"
"github.com/pomerium/pomerium/internal/telemetry/trace"
"github.com/pomerium/pomerium/pkg/grpc/databroker"
"github.com/pomerium/pomerium/pkg/storage"
)
// Name is the storage type name for redis backend.
const Name = config.StorageRedisName
const watchAction = "zadd"
var _ storage.Backend = (*DB)(nil)
// DB wraps redis conn to interact with redis server.
type DB struct {
pool *redis.Pool
deletePermanentlyAfter int64
recordType string
lastVersionKey string
versionSet string
deletedSet string
tlsConfig *tls.Config
notifyChMu sync.Mutex
closeOnce sync.Once
closed chan struct{}
}
// New returns new DB instance.
func New(rawURL, recordType string, deletePermanentAfter int64, opts ...Option) (*DB, error) {
db := &DB{
deletePermanentlyAfter: deletePermanentAfter,
recordType: recordType,
versionSet: recordType + "_version_set",
deletedSet: recordType + "_deleted_set",
lastVersionKey: recordType + "_last_version",
closed: make(chan struct{}),
}
for _, o := range opts {
o(db)
}
db.pool = &redis.Pool{
Wait: true,
Dial: func() (redis.Conn, error) {
c, err := redis.DialURL(rawURL, redis.DialTLSConfig(db.tlsConfig))
if err != nil {
return nil, fmt.Errorf(`redis.DialURL(): %w`, err)
}
return c, nil
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
if time.Since(t) < time.Minute {
return nil
}
_, err := c.Do("PING")
if err != nil {
return fmt.Errorf(`c.Do("PING"): %w`, err)
}
return nil
},
}
metrics.AddRedisMetrics(db.pool.Stats)
return db, nil
}
// Close closes the redis db connection.
func (db *DB) Close() error {
db.closeOnce.Do(func() {
close(db.closed)
})
return nil
}
// Put sets new record for given id with input data.
func (db *DB) Put(ctx context.Context, id string, data *anypb.Any) (err error) {
c := db.pool.Get()
_, span := trace.StartSpan(ctx, "databroker.redis.Put")
defer span.End()
defer recordOperation(ctx, time.Now(), "put", err)
defer c.Close()
record, err := db.Get(ctx, id)
if err != nil {
record = new(databroker.Record)
record.CreatedAt = ptypes.TimestampNow()
}
lastVersion, err := redis.Int64(c.Do("INCR", db.lastVersionKey))
if err != nil {
return err
}
record.Data = data
record.ModifiedAt = ptypes.TimestampNow()
record.Type = db.recordType
record.Id = id
record.Version = fmt.Sprintf("%012X", lastVersion)
b, err := proto.Marshal(record)
if err != nil {
return err
}
cmds := []map[string][]interface{}{
{"MULTI": nil},
{"HSET": {db.recordType, id, string(b)}},
{"ZADD": {db.versionSet, lastVersion, id}},
}
if err := db.tx(c, cmds); err != nil {
return err
}
return nil
}
// Get retrieves a record from redis.
func (db *DB) Get(ctx context.Context, id string) (rec *databroker.Record, err error) {
c := db.pool.Get()
_, span := trace.StartSpan(ctx, "databroker.redis.Get")
defer span.End()
defer recordOperation(ctx, time.Now(), "get", err)
defer c.Close()
b, err := redis.Bytes(c.Do("HGET", db.recordType, id))
if err != nil {
return nil, err
}
return db.toPbRecord(b)
}
// GetAll retrieves all records from redis.
func (db *DB) GetAll(ctx context.Context) (recs []*databroker.Record, err error) {
_, span := trace.StartSpan(ctx, "databroker.redis.GetAll")
defer span.End()
defer recordOperation(ctx, time.Now(), "get_all", err)
return db.getAll(ctx, func(record *databroker.Record) bool { return true })
}
// List retrieves all records since given version.
//
// "version" is in hex format, invalid version will be treated as 0.
func (db *DB) List(ctx context.Context, sinceVersion string) (rec []*databroker.Record, err error) {
c := db.pool.Get()
_, span := trace.StartSpan(ctx, "databroker.redis.List")
defer span.End()
defer recordOperation(ctx, time.Now(), "list", err)
defer c.Close()
v, err := strconv.ParseUint(sinceVersion, 16, 64)
if err != nil {
v = 0
}
ids, err := redis.Strings(c.Do("ZRANGEBYSCORE", db.versionSet, fmt.Sprintf("(%d", v), "+inf"))
if err != nil {
return nil, err
}
pbRecords := make([]*databroker.Record, 0, len(ids))
for _, id := range ids {
b, err := redis.Bytes(c.Do("HGET", db.recordType, id))
if err != nil {
return nil, err
}
pbRecord, err := db.toPbRecord(b)
if err != nil {
return nil, err
}
pbRecords = append(pbRecords, pbRecord)
}
return pbRecords, nil
}
// Delete sets a record DeletedAt field and set its TTL.
func (db *DB) Delete(ctx context.Context, id string) (err error) {
c := db.pool.Get()
_, span := trace.StartSpan(ctx, "databroker.redis.Delete")
defer span.End()
defer recordOperation(ctx, time.Now(), "delete", err)
defer c.Close()
r, err := db.Get(ctx, id)
if err != nil {
return fmt.Errorf("failed to get record: %w", err)
}
lastVersion, err := redis.Int64(c.Do("INCR", db.lastVersionKey))
if err != nil {
return err
}
r.DeletedAt = ptypes.TimestampNow()
r.Version = fmt.Sprintf("%012X", lastVersion)
b, err := proto.Marshal(r)
if err != nil {
return err
}
cmds := []map[string][]interface{}{
{"MULTI": nil},
{"HSET": {db.recordType, id, string(b)}},
{"SADD": {db.deletedSet, id}},
{"ZADD": {db.versionSet, lastVersion, id}},
}
if err := db.tx(c, cmds); err != nil {
return err
}
return nil
}
// ClearDeleted clears all the currently deleted records older than the given cutoff.
func (db *DB) ClearDeleted(ctx context.Context, cutoff time.Time) {
c := db.pool.Get()
_, span := trace.StartSpan(ctx, "databroker.redis.ClearDeleted")
defer span.End()
var opErr error
defer func(startTime time.Time) {
recordOperation(ctx, startTime, "clear_deleted", opErr)
}(time.Now())
defer c.Close()
ids, _ := redis.Strings(c.Do("SMEMBERS", db.deletedSet))
for _, id := range ids {
b, _ := redis.Bytes(c.Do("HGET", db.recordType, id))
record, err := db.toPbRecord(b)
if err != nil {
continue
}
ts, _ := ptypes.Timestamp(record.DeletedAt)
if ts.Before(cutoff) {
cmds := []map[string][]interface{}{
{"MULTI": nil},
{"HDEL": {db.recordType, id}},
{"ZREM": {db.versionSet, id}},
{"SREM": {db.deletedSet, id}},
}
opErr = db.tx(c, cmds)
}
}
}
// doNotifyLoop receives event from redis and send signal to the channel.
func (db *DB) doNotifyLoop(ctx context.Context, ch chan struct{}) {
eb := backoff.NewExponentialBackOff()
psConn := db.pool.Get()
psc := redis.PubSubConn{Conn: psConn}
defer func(psc *redis.PubSubConn) {
psc.Conn.Close()
}(&psc)
if err := db.subscribeRedisChannel(&psc); err != nil {
log.Error().Err(err).Msg("failed to subscribe to version set channel")
return
}
for {
select {
case <-db.closed:
return
case <-ctx.Done():
return
default:
}
switch v := psc.Receive().(type) {
case redis.Message:
log.Debug().Str("action", string(v.Data)).Msg("got redis message")
recordOperation(ctx, time.Now(), "sub_received", nil)
if string(v.Data) != watchAction {
continue
}
select {
case <-db.closed:
return
case <-ctx.Done():
log.Warn().Err(ctx.Err()).Msg("context done, stop receive from redis channel")
return
default:
db.notifyChMu.Lock()
select {
case <-db.closed:
db.notifyChMu.Unlock()
return
case <-ctx.Done():
db.notifyChMu.Unlock()
log.Warn().Err(ctx.Err()).Msg("context done while holding notify lock, stop receive from redis channel")
return
case ch <- struct{}{}:
}
db.notifyChMu.Unlock()
}
case error:
log.Warn().Err(v).Msg("failed to receive from redis channel")
recordOperation(ctx, time.Now(), "sub_received", v)
if _, ok := v.(net.Error); ok {
return
}
time.Sleep(eb.NextBackOff())
log.Warn().Msg("retry with new connection")
_ = psc.Conn.Close()
psc.Conn = db.pool.Get()
_ = db.subscribeRedisChannel(&psc)
}
}
}
// watch runs the doNotifyLoop. It returns when ctx was done or doNotifyLoop exits.
func (db *DB) watch(ctx context.Context, ch chan struct{}) {
defer func() {
db.notifyChMu.Lock()
close(ch)
db.notifyChMu.Unlock()
}()
done := make(chan struct{})
go func() {
defer close(done)
db.doNotifyLoop(ctx, ch)
}()
select {
case <-db.closed:
case <-ctx.Done():
case <-done:
}
}
func (db *DB) subscribeRedisChannel(psc *redis.PubSubConn) error {
return psc.PSubscribe("__keyspace*__:" + db.versionSet)
}
// Watch returns a channel to the caller, when there is a change to the version set,
// sending message to the channel to notify the caller.
func (db *DB) Watch(ctx context.Context) <-chan struct{} {
ch := make(chan struct{})
go func() {
c := db.pool.Get()
// Setup notifications, we only care about changes to db.version_set.
if _, err := c.Do("CONFIG", "SET", "notify-keyspace-events", "Kz"); err != nil {
log.Error().Err(err).Msg("failed to setup redis notification")
c.Close()
return
}
c.Close()
db.watch(ctx, ch)
}()
return ch
}
func (db *DB) getAll(_ context.Context, filter func(record *databroker.Record) bool) ([]*databroker.Record, error) {
c := db.pool.Get()
defer c.Close()
iter := 0
records := make([]*databroker.Record, 0)
for {
arr, err := redis.Values(c.Do("HSCAN", db.recordType, iter, "MATCH", "*"))
if err != nil {
return nil, err
}
iter, _ = redis.Int(arr[0], nil)
pairs, _ := redis.StringMap(arr[1], nil)
for _, v := range pairs {
record, err := db.toPbRecord([]byte(v))
if err != nil {
return nil, err
}
if filter(record) {
records = append(records, record)
}
}
if iter == 0 {
break
}
}
return records, nil
}
func (db *DB) toPbRecord(b []byte) (*databroker.Record, error) {
record := &databroker.Record{}
if err := proto.Unmarshal(b, record); err != nil {
return nil, err
}
return record, nil
}
func (db *DB) tx(c redis.Conn, commands []map[string][]interface{}) error {
for _, m := range commands {
for cmd, args := range m {
if err := c.Send(cmd, args...); err != nil {
return err
}
}
}
_, err := c.Do("EXEC")
return err
}
func recordOperation(ctx context.Context, startTime time.Time, operation string, err error) {
metrics.RecordStorageOperation(ctx, &metrics.StorageOperationTags{
Operation: operation,
Error: err,
Backend: Name,
}, time.Since(startTime))
}
| 25.585882 | 116 | 0.647232 |
3e817e4997df88adffabb8da5e0a76af8c34804c | 8,985 | h | C | CommandLineParser.h | malord/prime | f0e8be99b7dcd482708b9c928322bc07a3128506 | [
"MIT"
] | null | null | null | CommandLineParser.h | malord/prime | f0e8be99b7dcd482708b9c928322bc07a3128506 | [
"MIT"
] | null | null | null | CommandLineParser.h | malord/prime | f0e8be99b7dcd482708b9c928322bc07a3128506 | [
"MIT"
] | null | null | null | // Copyright 2000-2021 Mark H. P. Lord
#ifndef PRIME_COMMANDLINEPARSER_H
#define PRIME_COMMANDLINEPARSER_H
#include "Config.h"
namespace Prime {
class Log;
/// A command line reader that supports short option (-v) and long options (--verbose), combined short options
/// (e.g., -v -n -r can be shortened to -vnr) and -- to mark the end of the options. In option names containing
/// a '-', the '-' is optional (e.g., --nocolour will match "no-colour"). A flag is an option that may be followed
/// by a '-' to disable it, e.g., -G- or --colours-, or a + to enable it. Long name flags can also be specified
/// with a "no-" or "disable-" prefix to negate them, e.g., --no-colours has the same result as --colours-. It is
/// also possible to use long options by default, e.g., -trace instead of --trace, by using
/// setImplicitLongOptionsEnabled(), which defaults to false. Values are options which expect one or more
/// parameters, e.g., --dest ~/Desktop.
class PRIME_PUBLIC CommandLineParser {
public:
CommandLineParser()
{
construct();
reset();
}
explicit CommandLineParser(char** argv)
{
construct();
init(argv);
}
virtual ~CommandLineParser();
/// Set the arguments to be read. The last element argv must be null (i.e., like the argument array which
/// is passed to main()). Note that returned strings are commonly pointers in to the strings in this array,
/// so the array must remain valid until the command line has been read.
bool init(char** argv);
class PRIME_PUBLIC ResponseFileLoader {
public:
virtual ~ResponseFileLoader() { }
/// Update ***argv to point to a new list of arguments to be parsed. The file name of the response file
/// comes from path, which may itself come from another response file.
virtual void loadResponseFile(const char* path, char*** argv, Log* log) = 0;
};
void setResponseFileLoader(char responseFileChar, ResponseFileLoader* responseFileLoader)
{
_responseFileChar = responseFileChar;
_responseFileLoader = responseFileLoader;
}
void reset();
/// If true, -trace will be considered to match --trace, rather than -t -r -a -c -e. Defaults to false. For
/// this to work, the application must check for the long options before the short options.
bool getImplicitLongOptionsEnabled() const { return _allowImplicitLongOptions; }
void setImplicitLongOptionsEnabled(bool enabled) { _allowImplicitLongOptions = enabled; }
/// Parse the next token from the argument list. Returns false if there are no more arguments to read.
bool next();
/// Returns true if a basic, not-an-option argument was read.
bool isFilename() const { return !_state.opt; }
/// If a file name was read, returns it.
const char* getFilename() const { return _state.opt ? NULL : _state.filename; }
/// Returns true if a "--" argument has been encountered, signifying that all remaining arguments are files.
bool hasOptionTerminatorBeenRead() const { return _state.noMoreOptions; }
/// Returns true if an option, value or flag was read.
bool isOption() const { return _state.opt ? true : false; }
/// Returns the option that hasn't been read (for use when reporting errors, don't compare this, use
/// readOption(), readFlag() or readValue()).
const char* getOption() const { return _state.opt; }
/// Returns the last option that was successfully read (with readOption(), readFlag() or readValue()).
const char* getCurrentOption() const { return _state.currentOption; }
/// Return the option or filename that was parsed.
const char* getOptionOrFilename() const { return _state.opt ? _state.opt : _state.filename; }
/// Returns true if the next argument is one of the | separated words. For example, for an archive utility
/// you might ask cl.readCommand("add|a"), which would match "add", "a", "--add" and "-a" (and "-add" if
/// implicit long options are enabled).
bool readCommand(const char* words);
/// Returns true if the specified option was read. e.g., readOption("verbose|v")
bool readOption(const char* option)
{
return readOptionOrValueOrFlag(option, NULL, false);
}
/// If the specified option was read, returns true and sets *flag to true or false depending on whether the
/// option was followed by a + or -, respectively. So -f or -f+ would set *flag to true, -f- to false.
/// If flag is NULL, the result is stored internally and can be read by calling getFlag().
bool readFlag(const char* option, bool* flag = NULL)
{
return readOptionOrValueOrFlag(option, flag ? flag : &_state.flag, false);
}
/// Returns the flag read by readFlag() (or readColourFlag()) if they were called with a NULL flag pointer.
bool getFlag() const { return _state.flag; }
/// Returns true if the specified option, which should have a value, was read. After calling this you should
/// call one of the fetch*() methods (fetchString(), fetchInt() etc.) to fetch the option's value. A value
/// differs from a plain option in that it may be followed by an '=' sign, e.g., `--path=/bin`, which could
/// also be supplied as `--path /bin` and `--path= /bin`. An option can have multiple values, e.g.,
/// `--offset 160 120`, and the fetch*() methods should be called for each.
bool readValue(const char* option)
{
return readOptionOrValueOrFlag(option, NULL, true);
}
/// Fetch a string from the command line. Exits if there are no more arguments.
const char* fetchString();
/// Fetch an intmax_t from the command line. Exits if there are no more arguments or the argument is invalid.
intmax_t fetchIntmax();
/// Fetch an int from the command line. Exits if there are no more arguments or the argument is invalid.
int fetchInt();
/// Fetch an intmax_t from the command line. If the next argument isn't a valid number, returns the default
/// value and leaves the next argument to be read.
intmax_t fetchOptionalIntmax(intmax_t defaultValue);
/// Fetch an int from the command line. If the next argument isn't a valid number, returns the default
/// value and leaves the next argument to be read.
int fetchOptionalInt(int defaultValue);
/// Fetch a float from the command line. Exits if there are no more arguments or the argument is invalid.
float fetchFloat();
/// Fetch a double from the command line. Exits if there are no more arguments or the argument is invalid.
double fetchDouble();
/// Fetch the next argument and convert the result to a bool. If there's no argument, or the next argument
/// begins with the switch character (- or /) then true is assumed, but if there is an argument then yes,
/// true, on, 1 and + are all considered true and no, false, off, 0 and - are all considered false. So,
/// -f 1, -f+, -f and even -f YES are all considered true. -f -x will be considered true, and -x will
/// correctly be read next.
bool fetchBool();
/// Reads the standard colour/no colour flags (colour|color|colours|colors|G).
bool readColourFlag(bool* flag = NULL);
void skipLongOption();
void skipShortOption();
/// Skip an option's value. If unlessOption is true, if the next argument begins with a - then treat it as
/// an option and don't skip it.
void skipValue(bool unlessOption = false)
{
(void)fetchArgument(unlessOption);
}
// You can overload exit(ExitReason) to change how these are handled.
void exitDueToMissingArgument() { exit(ExitReasonMissingArgument); }
void exitDueToInvalidArgument() { exit(ExitReasonInvalidArgument); }
void exitDueToUnknownOption() { exit(ExitReasonUnknownOption); }
void exitDueToUnexpectedArgument() { exit(ExitReasonUnexpectedArgument); }
void exitDueToUnknownOptionOrUnexpectedArgument() { exit(ExitReasonUnknownOptionOrUnexpectedArgument); }
protected:
enum ExitReason {
ExitReasonMissingArgument,
ExitReasonInvalidArgument,
ExitReasonUnknownOption,
ExitReasonUnexpectedArgument,
ExitReasonUnknownOptionOrUnexpectedArgument,
};
virtual void exit(ExitReason reason);
private:
void construct();
bool readOptionOrValueOrFlag(const char* option, bool* flag, bool hasParam);
static bool equalLongOptionName(const char* have, const char* want, const char*& ptr, bool hasParam, bool hasFlag);
const char* fetchArgument(bool optional);
struct State {
char** argv;
const char* opt;
const char* filename;
bool noMoreOptions;
bool isLongOption;
bool flag;
char currentOption[64];
} _state;
bool _allowImplicitLongOptions;
int _responseFileChar;
ResponseFileLoader* _responseFileLoader;
PRIME_UNCOPYABLE(CommandLineParser);
};
}
#endif
| 41.790698 | 119 | 0.689482 |
53bdcf43ea00e81a186d68c5156a2e741db266f6 | 165,604 | java | Java | Cosmos-Android/app/src/main/java/wannabit/io/cosmostaion/activities/TxDetailActivity.java | Manny27nyc/cosmostation-mobile | ca0b8be2354746ff984453f12aabb5d04d01fde4 | [
"MIT"
] | null | null | null | Cosmos-Android/app/src/main/java/wannabit/io/cosmostaion/activities/TxDetailActivity.java | Manny27nyc/cosmostation-mobile | ca0b8be2354746ff984453f12aabb5d04d01fde4 | [
"MIT"
] | null | null | null | Cosmos-Android/app/src/main/java/wannabit/io/cosmostaion/activities/TxDetailActivity.java | Manny27nyc/cosmostation-mobile | ca0b8be2354746ff984453f12aabb5d04d01fde4 | [
"MIT"
] | null | null | null | package wannabit.io.cosmostaion.activities;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.math.BigDecimal;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import wannabit.io.cosmostaion.R;
import wannabit.io.cosmostaion.base.BaseActivity;
import wannabit.io.cosmostaion.dialog.Dialog_MoreWait;
import wannabit.io.cosmostaion.dialog.Dialog_WatchMode;
import wannabit.io.cosmostaion.model.StarNameResource;
import wannabit.io.cosmostaion.model.type.Coin;
import wannabit.io.cosmostaion.model.type.Input;
import wannabit.io.cosmostaion.model.type.Msg;
import wannabit.io.cosmostaion.model.type.Output;
import wannabit.io.cosmostaion.model.type.Validator;
import wannabit.io.cosmostaion.network.ApiClient;
import wannabit.io.cosmostaion.network.res.ResBnbNodeInfo;
import wannabit.io.cosmostaion.network.res.ResBnbSwapInfo;
import wannabit.io.cosmostaion.network.res.ResBnbTxInfo;
import wannabit.io.cosmostaion.network.res.ResKavaSwapInfo;
import wannabit.io.cosmostaion.network.res.ResTxInfo;
import wannabit.io.cosmostaion.utils.WDp;
import wannabit.io.cosmostaion.utils.WLog;
import wannabit.io.cosmostaion.utils.WUtil;
import static wannabit.io.cosmostaion.base.BaseChain.AKASH_MAIN;
import static wannabit.io.cosmostaion.base.BaseChain.BAND_MAIN;
import static wannabit.io.cosmostaion.base.BaseChain.BNB_MAIN;
import static wannabit.io.cosmostaion.base.BaseChain.BNB_TEST;
import static wannabit.io.cosmostaion.base.BaseChain.CERTIK_MAIN;
import static wannabit.io.cosmostaion.base.BaseChain.CERTIK_TEST;
import static wannabit.io.cosmostaion.base.BaseChain.COSMOS_MAIN;
import static wannabit.io.cosmostaion.base.BaseChain.IOV_MAIN;
import static wannabit.io.cosmostaion.base.BaseChain.IOV_TEST;
import static wannabit.io.cosmostaion.base.BaseChain.IRIS_MAIN;
import static wannabit.io.cosmostaion.base.BaseChain.KAVA_MAIN;
import static wannabit.io.cosmostaion.base.BaseChain.KAVA_TEST;
import static wannabit.io.cosmostaion.base.BaseChain.OK_TEST;
import static wannabit.io.cosmostaion.base.BaseChain.SECRET_MAIN;
import static wannabit.io.cosmostaion.base.BaseChain.getChain;
import static wannabit.io.cosmostaion.base.BaseConstant.BNB_MSG_TYPE_HTLC;
import static wannabit.io.cosmostaion.base.BaseConstant.BNB_MSG_TYPE_HTLC_CLIAM;
import static wannabit.io.cosmostaion.base.BaseConstant.BNB_MSG_TYPE_HTLC_REFUND;
import static wannabit.io.cosmostaion.base.BaseConstant.CERTIK_MSG_TYPE_TRANSFER;
import static wannabit.io.cosmostaion.base.BaseConstant.COSMOS_MSG_TYPE_DELEGATE;
import static wannabit.io.cosmostaion.base.BaseConstant.COSMOS_MSG_TYPE_REDELEGATE2;
import static wannabit.io.cosmostaion.base.BaseConstant.COSMOS_MSG_TYPE_TRANSFER;
import static wannabit.io.cosmostaion.base.BaseConstant.COSMOS_MSG_TYPE_TRANSFER2;
import static wannabit.io.cosmostaion.base.BaseConstant.COSMOS_MSG_TYPE_TRANSFER3;
import static wannabit.io.cosmostaion.base.BaseConstant.COSMOS_MSG_TYPE_UNDELEGATE2;
import static wannabit.io.cosmostaion.base.BaseConstant.COSMOS_MSG_TYPE_VOTE;
import static wannabit.io.cosmostaion.base.BaseConstant.COSMOS_MSG_TYPE_WITHDRAW_DEL;
import static wannabit.io.cosmostaion.base.BaseConstant.COSMOS_MSG_TYPE_WITHDRAW_MIDIFY;
import static wannabit.io.cosmostaion.base.BaseConstant.COSMOS_MSG_TYPE_WITHDRAW_VAL;
import static wannabit.io.cosmostaion.base.BaseConstant.ERROR_CODE_BROADCAST;
import static wannabit.io.cosmostaion.base.BaseConstant.ERROR_CODE_UNKNOWN;
import static wannabit.io.cosmostaion.base.BaseConstant.EXPLORER_AKASH_MAIN;
import static wannabit.io.cosmostaion.base.BaseConstant.EXPLORER_BAND_MAIN;
import static wannabit.io.cosmostaion.base.BaseConstant.EXPLORER_BINANCE_MAIN;
import static wannabit.io.cosmostaion.base.BaseConstant.EXPLORER_BINANCE_TEST;
import static wannabit.io.cosmostaion.base.BaseConstant.EXPLORER_CERTIK;
import static wannabit.io.cosmostaion.base.BaseConstant.EXPLORER_COSMOS_MAIN;
import static wannabit.io.cosmostaion.base.BaseConstant.EXPLORER_IOV_MAIN;
import static wannabit.io.cosmostaion.base.BaseConstant.EXPLORER_IRIS_MAIN;
import static wannabit.io.cosmostaion.base.BaseConstant.EXPLORER_KAVA_MAIN;
import static wannabit.io.cosmostaion.base.BaseConstant.EXPLORER_KAVA_TEST;
import static wannabit.io.cosmostaion.base.BaseConstant.EXPLORER_OKEX_TEST;
import static wannabit.io.cosmostaion.base.BaseConstant.EXPLORER_SECRET_MAIN;
import static wannabit.io.cosmostaion.base.BaseConstant.FEE_BNB_SEND;
import static wannabit.io.cosmostaion.base.BaseConstant.IOV_MSG_TYPE_DELETE_ACCOUNT;
import static wannabit.io.cosmostaion.base.BaseConstant.IOV_MSG_TYPE_DELETE_DOMAIN;
import static wannabit.io.cosmostaion.base.BaseConstant.IOV_MSG_TYPE_REGISTER_ACCOUNT;
import static wannabit.io.cosmostaion.base.BaseConstant.IOV_MSG_TYPE_REGISTER_DOMAIN;
import static wannabit.io.cosmostaion.base.BaseConstant.IOV_MSG_TYPE_RENEW_ACCOUNT;
import static wannabit.io.cosmostaion.base.BaseConstant.IOV_MSG_TYPE_RENEW_DOMAIN;
import static wannabit.io.cosmostaion.base.BaseConstant.IOV_MSG_TYPE_REPLACE_ACCOUNT_RESOURCE;
import static wannabit.io.cosmostaion.base.BaseConstant.IRIS_MSG_TYPE_COMMISSION;
import static wannabit.io.cosmostaion.base.BaseConstant.IRIS_MSG_TYPE_DELEGATE;
import static wannabit.io.cosmostaion.base.BaseConstant.IRIS_MSG_TYPE_REDELEGATE;
import static wannabit.io.cosmostaion.base.BaseConstant.IRIS_MSG_TYPE_TRANSFER;
import static wannabit.io.cosmostaion.base.BaseConstant.IRIS_MSG_TYPE_UNDELEGATE;
import static wannabit.io.cosmostaion.base.BaseConstant.IRIS_MSG_TYPE_VOTE;
import static wannabit.io.cosmostaion.base.BaseConstant.IRIS_MSG_TYPE_WITHDRAW;
import static wannabit.io.cosmostaion.base.BaseConstant.IRIS_MSG_TYPE_WITHDRAW_ALL;
import static wannabit.io.cosmostaion.base.BaseConstant.IRIS_MSG_TYPE_WITHDRAW_MIDIFY;
import static wannabit.io.cosmostaion.base.BaseConstant.IS_SHOWLOG;
import static wannabit.io.cosmostaion.base.BaseConstant.KAVA_MSG_TYPE_BEP3_CLAM_SWAP;
import static wannabit.io.cosmostaion.base.BaseConstant.KAVA_MSG_TYPE_BEP3_CREATE_SWAP;
import static wannabit.io.cosmostaion.base.BaseConstant.KAVA_MSG_TYPE_BEP3_REFUND_SWAP;
import static wannabit.io.cosmostaion.base.BaseConstant.KAVA_MSG_TYPE_CLAIM_HAVEST;
import static wannabit.io.cosmostaion.base.BaseConstant.KAVA_MSG_TYPE_CREATE_CDP;
import static wannabit.io.cosmostaion.base.BaseConstant.KAVA_MSG_TYPE_DEPOSIT_CDP;
import static wannabit.io.cosmostaion.base.BaseConstant.KAVA_MSG_TYPE_DEPOSIT_HAVEST;
import static wannabit.io.cosmostaion.base.BaseConstant.KAVA_MSG_TYPE_DRAWDEBT_CDP;
import static wannabit.io.cosmostaion.base.BaseConstant.KAVA_MSG_TYPE_INCENTIVE_REWARD;
import static wannabit.io.cosmostaion.base.BaseConstant.KAVA_MSG_TYPE_POST_PRICE;
import static wannabit.io.cosmostaion.base.BaseConstant.KAVA_MSG_TYPE_REPAYDEBT_CDP;
import static wannabit.io.cosmostaion.base.BaseConstant.KAVA_MSG_TYPE_WITHDRAW_CDP;
import static wannabit.io.cosmostaion.base.BaseConstant.KAVA_MSG_TYPE_WITHDRAW_HAVEST;
import static wannabit.io.cosmostaion.base.BaseConstant.OK_MSG_TYPE_DEPOSIT;
import static wannabit.io.cosmostaion.base.BaseConstant.OK_MSG_TYPE_DIRECT_VOTE;
import static wannabit.io.cosmostaion.base.BaseConstant.OK_MSG_TYPE_MULTI_TRANSFER;
import static wannabit.io.cosmostaion.base.BaseConstant.OK_MSG_TYPE_TRANSFER;
import static wannabit.io.cosmostaion.base.BaseConstant.OK_MSG_TYPE_WITHDRAW;
import static wannabit.io.cosmostaion.base.BaseConstant.TOKEN_BNB;
import static wannabit.io.cosmostaion.network.res.ResBnbSwapInfo.BNB_STATUS_OPEN;
import static wannabit.io.cosmostaion.network.res.ResKavaSwapInfo.STATUS_EXPIRED;
public class TxDetailActivity extends BaseActivity implements View.OnClickListener {
private Toolbar mToolbar;
private RecyclerView mTxRecyclerView;
private CardView mErrorCardView;
private TextView mErrorMsgTv;
private RelativeLayout mLoadingLayer;
private TextView mLoadingMsgTv;
private LinearLayout mControlLayer;
private Button mDismissBtn;
private RelativeLayout mRefundBtn;
private LinearLayout mControlLayer2;
private Button mShareBtn;
private boolean mIsGen;
private boolean mIsSuccess;
private int mErrorCode;
private String mErrorMsg;
private String mTxHash;
private TxDetailAdapter mTxDetailAdapter;
private ResTxInfo mResTxInfo;
private ResKavaSwapInfo mResKavaSwapInfo;
private ResBnbTxInfo mResBnbTxInfo;
private ResBnbSwapInfo mResBnbSwapInfo;
private ResBnbNodeInfo mResBnbNodeInfo;
private String mBnbTime;
private String mSwapId = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tx_detail);
mToolbar = findViewById(R.id.tool_bar);
mTxRecyclerView = findViewById(R.id.tx_recycler);
mErrorCardView = findViewById(R.id.error_Card);
mErrorMsgTv = findViewById(R.id.error_details);
mLoadingLayer = findViewById(R.id.loadingLayer);
mLoadingMsgTv = findViewById(R.id.tx_loading_msg);
mControlLayer = findViewById(R.id.bottom_control);
mDismissBtn = findViewById(R.id.btn_dismiss);
mRefundBtn = findViewById(R.id.btn_refund);
mControlLayer2 = findViewById(R.id.control_after);
mShareBtn = findViewById(R.id.btn_share);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mAccount = getBaseDao().onSelectAccount(getBaseDao().getLastUser());
mBaseChain = getChain(mAccount.baseChain);
mIsGen = getIntent().getBooleanExtra("isGen", false);
mIsSuccess = getIntent().getBooleanExtra("isSuccess", false);
mErrorCode = getIntent().getIntExtra("errorCode", ERROR_CODE_UNKNOWN);
mErrorMsg = getIntent().getStringExtra("errorMsg");
mTxHash = getIntent().getStringExtra("txHash");
mBnbTime = getIntent().getStringExtra("bnbTime");
mAllValidators = getBaseDao().mAllValidators;
if (mIsGen) {
mLoadingMsgTv.setVisibility(View.VISIBLE);
}
if (TextUtils.isEmpty(mTxHash)) {
mLoadingLayer.setVisibility(View.GONE);
mErrorCardView.setVisibility(View.VISIBLE);
mErrorMsgTv.setText(getString(R.string.error_network));
return;
}
if (mIsSuccess) {
onFetchTx(mTxHash);
} else {
mLoadingLayer.setVisibility(View.GONE);
mErrorCardView.setVisibility(View.VISIBLE);
if (mErrorCode == ERROR_CODE_BROADCAST) {
mErrorMsgTv.setText(getString(R.string.error_network));
} else {
mErrorMsgTv.setText("error code : " + mErrorCode + "\n" + mErrorMsg);
}
}
mTxRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
mTxRecyclerView.setHasFixedSize(true);
mTxDetailAdapter = new TxDetailAdapter();
mTxRecyclerView.setAdapter(mTxDetailAdapter);
mDismissBtn.setOnClickListener(this);
mRefundBtn.setOnClickListener(this);
mShareBtn.setOnClickListener(this);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onBackPressed() {
if (!mIsGen) {
super.onBackPressed();
} else {
onStartMainActivity(0);
}
}
private void onUpdateView() {
mLoadingLayer.setVisibility(View.GONE);
mControlLayer2.setVisibility(View.VISIBLE);
if (mBaseChain.equals(BNB_MAIN) || mBaseChain.equals(BNB_TEST)) {
if (mResBnbTxInfo != null) {
mTxDetailAdapter.notifyDataSetChanged();
mTxRecyclerView.setVisibility(View.VISIBLE);
}
} else {
if (mResTxInfo != null) {
mTxDetailAdapter.notifyDataSetChanged();
mTxRecyclerView.setVisibility(View.VISIBLE);
}
}
}
@Override
public void onClick(View v) {
if (v.equals(mDismissBtn)) {
onBackPressed();
} else if (v.equals(mShareBtn)) {
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
if (mBaseChain.equals(COSMOS_MAIN)) {
shareIntent.putExtra(Intent.EXTRA_TEXT, EXPLORER_COSMOS_MAIN + "txs/" + mResTxInfo.txhash);
} else if (mBaseChain.equals(IRIS_MAIN)) {
shareIntent.putExtra(Intent.EXTRA_TEXT, EXPLORER_IRIS_MAIN + "txs/" + mResTxInfo.hash);
} else if (mBaseChain.equals(BNB_MAIN)) {
shareIntent.putExtra(Intent.EXTRA_TEXT, EXPLORER_BINANCE_MAIN + "txs/" + mResBnbTxInfo.hash);
} else if (mBaseChain.equals(BNB_TEST)) {
shareIntent.putExtra(Intent.EXTRA_TEXT, EXPLORER_BINANCE_TEST + "tx/" + mResBnbTxInfo.hash);
} else if (mBaseChain.equals(KAVA_MAIN)) {
shareIntent.putExtra(Intent.EXTRA_TEXT, EXPLORER_KAVA_MAIN + "txs/" + mResTxInfo.txhash);
} else if (mBaseChain.equals(KAVA_TEST)) {
shareIntent.putExtra(Intent.EXTRA_TEXT, EXPLORER_KAVA_TEST + "txs/" + mResTxInfo.txhash);
} else if (mBaseChain.equals(OK_TEST)) {
shareIntent.putExtra(Intent.EXTRA_TEXT, EXPLORER_OKEX_TEST + "tx/" + mResTxInfo.txhash);
} else if (mBaseChain.equals(BAND_MAIN)) {
shareIntent.putExtra(Intent.EXTRA_TEXT, EXPLORER_BAND_MAIN + "tx/" + mResTxInfo.txhash);
} else if (mBaseChain.equals(IOV_MAIN)) {
shareIntent.putExtra(Intent.EXTRA_TEXT, EXPLORER_IOV_MAIN + "txs/" + mResTxInfo.txhash);
} else if (mBaseChain.equals(CERTIK_MAIN) || mBaseChain.equals(CERTIK_TEST)) {
shareIntent.putExtra(Intent.EXTRA_TEXT, EXPLORER_CERTIK + "Transactions/" + mResTxInfo.txhash + "?net=" + mBaseChain.getChain());
} else if (mBaseChain.equals(SECRET_MAIN)) {
shareIntent.putExtra(Intent.EXTRA_TEXT, EXPLORER_SECRET_MAIN + "transactions/" + mResTxInfo.txhash);
} else if (mBaseChain.equals(AKASH_MAIN)) {
shareIntent.putExtra(Intent.EXTRA_TEXT, EXPLORER_AKASH_MAIN + "txs/" + mResTxInfo.txhash);
}
shareIntent.setType("text/plain");
startActivity(Intent.createChooser(shareIntent, "send"));
} else if (v.equals(mRefundBtn)) {
if (!mAccount.hasPrivateKey) {
Dialog_WatchMode add = Dialog_WatchMode.newInstance();
add.setCancelable(true);
getSupportFragmentManager().beginTransaction().add(add, "dialog").commitNowAllowingStateLoss();
return;
}
if (mBaseChain.equals(BNB_MAIN) || mBaseChain.equals(BNB_TEST)) {
if (WDp.getAvailableCoin(mAccount.balances, TOKEN_BNB).compareTo(new BigDecimal(FEE_BNB_SEND)) < 0) {
Toast.makeText(getBaseContext(), R.string.error_not_enough_budget, Toast.LENGTH_SHORT).show();
return;
}
}
Intent refundIntent = new Intent(TxDetailActivity.this, HtlcRefundActivity.class);
refundIntent.putExtra("swapId", mSwapId);
startActivity(refundIntent);
}
}
private class TxDetailAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_TX_COMMON = 0;
private static final int TYPE_TX_TRANSFER = 1;
private static final int TYPE_TX_DELEGATE = 2;
private static final int TYPE_TX_UNDELEGATE = 3;
private static final int TYPE_TX_REDELEGATE = 4;
private static final int TYPE_TX_REWARD = 5;
private static final int TYPE_TX_ADDRESS_CHANGE = 6;
private static final int TYPE_TX_VOTE = 7;
private static final int TYPE_TX_COMMISSION = 8;
private static final int TYPE_TX_MULTI_SEND = 9;
private static final int TYPE_TX_POST_PRICE = 10;
private static final int TYPE_TX_CREATE_CDP = 11;
private static final int TYPE_TX_DEPOSIT_CDP = 12;
private static final int TYPE_TX_WITHDRAW_CDP = 13;
private static final int TYPE_TX_DRAW_DEBT_CDP = 14;
private static final int TYPE_TX_REPAY_CDP = 15;
private static final int TYPE_TX_HTLC_CREATE = 16;
private static final int TYPE_TX_HTLC_CLAIM = 17;
private static final int TYPE_TX_HTLC_REFUND = 18;
private static final int TYPE_TX_INCENTIVE_REWARD = 19;
private static final int TYPE_TX_REWARD_ALL = 20;
private static final int TYPE_TX_OK_STAKE = 21;
private static final int TYPE_TX_OK_DIRECT_VOTE = 22;
private static final int TYPE_REGISTER_DOMAIN = 23;
private static final int TYPE_REGISTER_ACCOUNT = 24;
private static final int TYPE_DELETE_ACCOUNT = 25;
private static final int TYPE_DELETE_DOMAIN = 26;
private static final int TYPE_REPLACE_ACCOUNT_RESOURCE = 27;
private static final int TYPE_TX_RENEW_STARNAME = 28;
private static final int TYPE_TX_HARVEST_DEPOSIT = 29;
private static final int TYPE_TX_HARVEST_WITHDRAW = 30;
private static final int TYPE_TX_HARVEST_CLIAM = 31;
private static final int TYPE_TX_UNKNOWN = 999;
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
if (viewType == TYPE_TX_COMMON) {
return new TxCommonHolder(getLayoutInflater().inflate(R.layout.item_tx_common, viewGroup, false));
} else if (viewType == TYPE_TX_TRANSFER) {
return new TxTransferHolder(getLayoutInflater().inflate(R.layout.item_tx_transfer, viewGroup, false));
} else if (viewType == TYPE_TX_DELEGATE) {
return new TxDelegateHolder(getLayoutInflater().inflate(R.layout.item_tx_delegate, viewGroup, false));
} else if (viewType == TYPE_TX_UNDELEGATE) {
return new TxUndelegateHolder(getLayoutInflater().inflate(R.layout.item_tx_undelegate, viewGroup, false));
} else if (viewType == TYPE_TX_REDELEGATE) {
return new TxRedelegateHolder(getLayoutInflater().inflate(R.layout.item_tx_redelegate, viewGroup, false));
} else if (viewType == TYPE_TX_REWARD) {
return new TxRewardHolder(getLayoutInflater().inflate(R.layout.item_tx_reward, viewGroup, false));
} else if (viewType == TYPE_TX_ADDRESS_CHANGE) {
return new TxAddressHolder(getLayoutInflater().inflate(R.layout.item_tx_reward_address, viewGroup, false));
} else if (viewType == TYPE_TX_VOTE) {
return new TxVoteHolder(getLayoutInflater().inflate(R.layout.item_tx_vote, viewGroup, false));
} else if (viewType == TYPE_TX_COMMISSION) {
return new TxCommissionHolder(getLayoutInflater().inflate(R.layout.item_tx_commission, viewGroup, false));
} else if (viewType == TYPE_TX_MULTI_SEND) {
return new TxMultiSendHolder(getLayoutInflater().inflate(R.layout.item_tx_multisend, viewGroup, false));
} else if (viewType == TYPE_TX_POST_PRICE) {
return new TxPostPriceHolder(getLayoutInflater().inflate(R.layout.item_tx_post_price, viewGroup, false));
} else if (viewType == TYPE_TX_CREATE_CDP) {
return new TxCreateCdpHolder(getLayoutInflater().inflate(R.layout.item_tx_create_cdp, viewGroup, false));
} else if (viewType == TYPE_TX_DEPOSIT_CDP) {
return new TxDepositCdpHolder(getLayoutInflater().inflate(R.layout.item_tx_deposit_cdp, viewGroup, false));
} else if (viewType == TYPE_TX_WITHDRAW_CDP) {
return new TxWithdrawCdpHolder(getLayoutInflater().inflate(R.layout.item_tx_withdraw_cdp, viewGroup, false));
} else if (viewType == TYPE_TX_DRAW_DEBT_CDP) {
return new TxDrawDebtCdpHolder(getLayoutInflater().inflate(R.layout.item_tx_drawdebt_cdp, viewGroup, false));
} else if (viewType == TYPE_TX_REPAY_CDP) {
return new TxRepayDebtCdpHolder(getLayoutInflater().inflate(R.layout.item_tx_repaydebt_cdp, viewGroup, false));
} else if (viewType == TYPE_TX_HTLC_CREATE) {
return new TxCreateHtlcHolder(getLayoutInflater().inflate(R.layout.item_tx_htlc_create, viewGroup, false));
} else if (viewType == TYPE_TX_HTLC_CLAIM) {
return new TxClaimHtlcHolder(getLayoutInflater().inflate(R.layout.item_tx_htlc_claim, viewGroup, false));
} else if (viewType == TYPE_TX_HTLC_REFUND) {
return new TxRefundHtlcHolder(getLayoutInflater().inflate(R.layout.item_tx_htlc_refund, viewGroup, false));
} else if (viewType == TYPE_TX_INCENTIVE_REWARD) {
return new TxIncentiveHolder(getLayoutInflater().inflate(R.layout.item_tx_incentive_reward, viewGroup, false));
} else if (viewType == TYPE_TX_HARVEST_DEPOSIT) {
return new TxHarvestDepositHolder(getLayoutInflater().inflate(R.layout.item_tx_deposit_harvest, viewGroup, false));
} else if (viewType == TYPE_TX_HARVEST_WITHDRAW) {
return new TxHarvestWithdrawHolder(getLayoutInflater().inflate(R.layout.item_tx_withdraw_harvest, viewGroup, false));
} else if (viewType == TYPE_TX_HARVEST_CLIAM) {
return new TxHarvestClaimHolder(getLayoutInflater().inflate(R.layout.item_tx_claim_harvest, viewGroup, false));
} else if (viewType == TYPE_TX_OK_STAKE) {
return new TxOkStakeHolder(getLayoutInflater().inflate(R.layout.item_tx_ok_stake, viewGroup, false));
} else if (viewType == TYPE_TX_REWARD_ALL) {
return new TxRewardAllHolder(getLayoutInflater().inflate(R.layout.item_tx_reward_all, viewGroup, false));
} else if (viewType == TYPE_REGISTER_DOMAIN) {
return new TxRegisterDomainHolder(getLayoutInflater().inflate(R.layout.item_tx_starname_register_domain, viewGroup, false));
} else if (viewType == TYPE_REGISTER_ACCOUNT) {
return new TxRegisterAccountHolder(getLayoutInflater().inflate(R.layout.item_tx_starname_register_account, viewGroup, false));
} else if (viewType == TYPE_DELETE_ACCOUNT) {
return new TxDeleteAccountHolder(getLayoutInflater().inflate(R.layout.item_tx_starname_delete_account, viewGroup, false));
} else if (viewType == TYPE_DELETE_DOMAIN) {
return new TxDeleteDomainHolder(getLayoutInflater().inflate(R.layout.item_tx_starname_delete_domain, viewGroup, false));
} else if (viewType == TYPE_REPLACE_ACCOUNT_RESOURCE) {
return new TxReplaceResourceHolder(getLayoutInflater().inflate(R.layout.item_tx_starname_resource, viewGroup, false));
} else if (viewType == TYPE_TX_RENEW_STARNAME) {
return new TxRenewStarNameHolder(getLayoutInflater().inflate(R.layout.item_tx_starname_renew, viewGroup, false));
}
return new TxUnKnownHolder(getLayoutInflater().inflate(R.layout.item_tx_unknown, viewGroup, false));
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {
if (getItemViewType(position) == TYPE_TX_COMMON) {
onBindCommon(viewHolder);
} else if (getItemViewType(position) == TYPE_TX_TRANSFER) {
onBindTransfer(viewHolder, position);
} else if (getItemViewType(position) == TYPE_TX_DELEGATE) {
onBindDelegate(viewHolder, position);
} else if (getItemViewType(position) == TYPE_TX_UNDELEGATE) {
onBindUndelegate(viewHolder, position);
} else if (getItemViewType(position) == TYPE_TX_REDELEGATE) {
onBindRedelegate(viewHolder, position);
} else if (getItemViewType(position) == TYPE_TX_REWARD) {
onBindReward(viewHolder, position);
} else if (getItemViewType(position) == TYPE_TX_ADDRESS_CHANGE) {
onBindAddress(viewHolder, position);
} else if (getItemViewType(position) == TYPE_TX_VOTE) {
onBindVote(viewHolder, position);
} else if (getItemViewType(position) == TYPE_TX_COMMISSION) {
onBindCommission(viewHolder, position);
} else if (getItemViewType(position) == TYPE_TX_MULTI_SEND) {
onBindMultiSend(viewHolder, position);
} else if (getItemViewType(position) == TYPE_TX_POST_PRICE) {
onBindPostPrice(viewHolder, position);
} else if (getItemViewType(position) == TYPE_TX_CREATE_CDP) {
onBindCreateCdp(viewHolder, position);
} else if (getItemViewType(position) == TYPE_TX_DEPOSIT_CDP) {
onBindDepositCdp(viewHolder, position);
} else if (getItemViewType(position) == TYPE_TX_WITHDRAW_CDP) {
onBindWithdrawCdp(viewHolder, position);
} else if (getItemViewType(position) == TYPE_TX_DRAW_DEBT_CDP) {
onBindDrawDebtCdp(viewHolder, position);
} else if (getItemViewType(position) == TYPE_TX_REPAY_CDP) {
onBindRepayDebtCdp(viewHolder, position);
} else if (getItemViewType(position) == TYPE_TX_HTLC_CREATE) {
onBindCreateHTLC(viewHolder, position);
} else if (getItemViewType(position) == TYPE_TX_HTLC_CLAIM) {
onBindClaimHTLC(viewHolder, position);
} else if (getItemViewType(position) == TYPE_TX_HTLC_REFUND) {
onBindRefundHTLC(viewHolder, position);
} else if (getItemViewType(position) == TYPE_TX_INCENTIVE_REWARD) {
onBindIncentive(viewHolder, position);
} else if (getItemViewType(position) == TYPE_TX_HARVEST_DEPOSIT) {
onBindHarvestDeposit(viewHolder, position);
} else if (getItemViewType(position) == TYPE_TX_HARVEST_WITHDRAW) {
onBindHarvestWithdraw(viewHolder, position);
} else if (getItemViewType(position) == TYPE_TX_HARVEST_CLIAM) {
onBindHarvestReward(viewHolder, position);
} else if (getItemViewType(position) == TYPE_TX_REWARD_ALL) {
onBindRewardAll(viewHolder, position);
} else if (getItemViewType(position) == TYPE_TX_OK_STAKE) {
onBindOkStake(viewHolder, position);
} else if (getItemViewType(position) == TYPE_TX_OK_DIRECT_VOTE) {
onBindOkDirectVote(viewHolder, position);
} else if (getItemViewType(position) == TYPE_REGISTER_DOMAIN) {
onBindRegisterDomain(viewHolder, position);
} else if (getItemViewType(position) == TYPE_REGISTER_ACCOUNT) {
onBindRegisterAccount(viewHolder, position);
} else if (getItemViewType(position) == TYPE_DELETE_DOMAIN) {
onBindDeleteDomain(viewHolder, position);
} else if (getItemViewType(position) == TYPE_DELETE_ACCOUNT) {
onBindDeleteAccount(viewHolder, position);
} else if (getItemViewType(position) == TYPE_REPLACE_ACCOUNT_RESOURCE) {
onBindReplaceResource(viewHolder, position);
} else if (getItemViewType(position) == TYPE_TX_RENEW_STARNAME) {
onBindRenewStarName(viewHolder, position);
}
else {
onBindUnKnown(viewHolder, position);
}
}
@Override
public int getItemCount() {
if (mBaseChain.equals(BNB_MAIN) || mBaseChain.equals(BNB_TEST)) {
if (mResBnbTxInfo != null && mResBnbTxInfo.tx.value.msg != null) {
return mResBnbTxInfo.tx.value.msg.size() + 1;
}
return 0;
} else {
if (mResTxInfo != null && mResTxInfo.tx.value.msg != null) {
return mResTxInfo.tx.value.msg.size() + 1;
}
return 0;
}
}
@Override
public int getItemViewType(int position) {
if (position == 0) {
return TYPE_TX_COMMON;
} else {
if (mBaseChain.equals(BNB_MAIN) || mBaseChain.equals(BNB_TEST)) {
if (mResBnbTxInfo.getMsgType(position - 1).equals(BNB_MSG_TYPE_HTLC)) {
return TYPE_TX_HTLC_CREATE;
} else if (mResBnbTxInfo.getMsgType(position - 1).equals(BNB_MSG_TYPE_HTLC_CLIAM)) {
return TYPE_TX_HTLC_CLAIM;
} else if (mResBnbTxInfo.getMsgType(position - 1).equals(BNB_MSG_TYPE_HTLC_REFUND)) {
return TYPE_TX_HTLC_REFUND;
} else if (mResBnbTxInfo.getMsgType(position - 1).equals(COSMOS_MSG_TYPE_TRANSFER)) {
return TYPE_TX_TRANSFER;
}
return TYPE_TX_UNKNOWN;
} else {
if (mResTxInfo.getMsgType(position - 1).equals(COSMOS_MSG_TYPE_TRANSFER2) ||
mResTxInfo.getMsgType(position - 1).equals(OK_MSG_TYPE_TRANSFER) ||
mResTxInfo.getMsgType(position - 1).equals(OK_MSG_TYPE_MULTI_TRANSFER) ||
mResTxInfo.getMsgType(position - 1).equals(CERTIK_MSG_TYPE_TRANSFER)) {
return TYPE_TX_TRANSFER;
} else if (mResTxInfo.getMsgType(position - 1).equals(COSMOS_MSG_TYPE_TRANSFER3) ||
mResTxInfo.getMsgType(position - 1).equals(IRIS_MSG_TYPE_TRANSFER)) {
if (mResTxInfo.getMsg(position - 1).value.inputs.size() == 1 &&
mResTxInfo.getMsg(position - 1).value.outputs.size() == 1) {
return TYPE_TX_TRANSFER;
}
return TYPE_TX_MULTI_SEND;
} else if (mResTxInfo.getMsgType(position - 1) .equals(COSMOS_MSG_TYPE_DELEGATE) ||
mResTxInfo.getMsgType(position - 1) .equals(IRIS_MSG_TYPE_DELEGATE)) {
return TYPE_TX_DELEGATE;
} else if (mResTxInfo.getMsgType(position - 1) .equals(COSMOS_MSG_TYPE_UNDELEGATE2) ||
mResTxInfo.getMsgType(position - 1) .equals(IRIS_MSG_TYPE_UNDELEGATE)) {
return TYPE_TX_UNDELEGATE;
} else if (mResTxInfo.getMsgType(position - 1) .equals(COSMOS_MSG_TYPE_REDELEGATE2) ||
mResTxInfo.getMsgType(position - 1) .equals(IRIS_MSG_TYPE_REDELEGATE)) {
return TYPE_TX_REDELEGATE;
} else if (mResTxInfo.getMsgType(position - 1) .equals(COSMOS_MSG_TYPE_WITHDRAW_DEL) ||
mResTxInfo.getMsgType(position - 1) .equals(IRIS_MSG_TYPE_WITHDRAW)) {
return TYPE_TX_REWARD;
} else if (mResTxInfo.getMsgType(position - 1) .equals(COSMOS_MSG_TYPE_WITHDRAW_MIDIFY) ||
mResTxInfo.getMsgType(position - 1) .equals(IRIS_MSG_TYPE_WITHDRAW_MIDIFY)) {
return TYPE_TX_ADDRESS_CHANGE;
} else if (mResTxInfo.getMsgType(position - 1) .equals(COSMOS_MSG_TYPE_VOTE) ||
mResTxInfo.getMsgType(position - 1) .equals(IRIS_MSG_TYPE_VOTE)) {
return TYPE_TX_VOTE;
} else if (mResTxInfo.getMsgType(position - 1) .equals(KAVA_MSG_TYPE_POST_PRICE)) {
return TYPE_TX_POST_PRICE;
} else if (mResTxInfo.getMsgType(position - 1) .equals(KAVA_MSG_TYPE_CREATE_CDP)) {
return TYPE_TX_CREATE_CDP;
} else if (mResTxInfo.getMsgType(position - 1) .equals(KAVA_MSG_TYPE_DEPOSIT_CDP)) {
return TYPE_TX_DEPOSIT_CDP;
} else if (mResTxInfo.getMsgType(position - 1) .equals(KAVA_MSG_TYPE_WITHDRAW_CDP)) {
return TYPE_TX_WITHDRAW_CDP;
} else if (mResTxInfo.getMsgType(position - 1) .equals(KAVA_MSG_TYPE_DRAWDEBT_CDP)) {
return TYPE_TX_DRAW_DEBT_CDP;
} else if (mResTxInfo.getMsgType(position - 1) .equals(KAVA_MSG_TYPE_REPAYDEBT_CDP)) {
return TYPE_TX_REPAY_CDP;
} else if (mResTxInfo.getMsgType(position - 1) .equals(COSMOS_MSG_TYPE_WITHDRAW_VAL) ||
mResTxInfo.getMsgType(position - 1) .equals(IRIS_MSG_TYPE_COMMISSION)) {
return TYPE_TX_COMMISSION;
} else if (mResTxInfo.getMsgType(position - 1) .equals(KAVA_MSG_TYPE_BEP3_CREATE_SWAP)) {
return TYPE_TX_HTLC_CREATE;
} else if (mResTxInfo.getMsgType(position - 1) .equals(KAVA_MSG_TYPE_BEP3_CLAM_SWAP)) {
return TYPE_TX_HTLC_CLAIM;
} else if (mResTxInfo.getMsgType(position - 1) .equals(KAVA_MSG_TYPE_BEP3_REFUND_SWAP)) {
return TYPE_TX_HTLC_REFUND;
} else if (mResTxInfo.getMsgType(position - 1) .equals(KAVA_MSG_TYPE_INCENTIVE_REWARD)) {
return TYPE_TX_INCENTIVE_REWARD;
} else if (mResTxInfo.getMsgType(position - 1) .equals(KAVA_MSG_TYPE_DEPOSIT_HAVEST)) {
return TYPE_TX_HARVEST_DEPOSIT;
} else if (mResTxInfo.getMsgType(position - 1) .equals(KAVA_MSG_TYPE_WITHDRAW_HAVEST)) {
return TYPE_TX_HARVEST_WITHDRAW;
} else if (mResTxInfo.getMsgType(position - 1) .equals(KAVA_MSG_TYPE_CLAIM_HAVEST)) {
return TYPE_TX_HARVEST_CLIAM;
} else if (mResTxInfo.getMsgType(position - 1) .equals(IRIS_MSG_TYPE_WITHDRAW_ALL)) {
return TYPE_TX_REWARD_ALL;
} else if (mResTxInfo.getMsgType(position - 1) .equals(OK_MSG_TYPE_DEPOSIT) ||
mResTxInfo.getMsgType(position - 1) .equals(OK_MSG_TYPE_WITHDRAW)) {
return TYPE_TX_OK_STAKE;
} else if (mResTxInfo.getMsgType(position - 1) .equals(OK_MSG_TYPE_DIRECT_VOTE)) {
return TYPE_TX_OK_DIRECT_VOTE;
} else if (mResTxInfo.getMsgType(position - 1) .equals(IOV_MSG_TYPE_REGISTER_DOMAIN)) {
return TYPE_REGISTER_DOMAIN;
} else if (mResTxInfo.getMsgType(position - 1) .equals(IOV_MSG_TYPE_REGISTER_ACCOUNT)) {
return TYPE_REGISTER_ACCOUNT ;
} else if (mResTxInfo.getMsgType(position - 1) .equals(IOV_MSG_TYPE_DELETE_DOMAIN)) {
return TYPE_DELETE_DOMAIN ;
} else if (mResTxInfo.getMsgType(position - 1) .equals(IOV_MSG_TYPE_DELETE_ACCOUNT)) {
return TYPE_DELETE_ACCOUNT ;
} else if (mResTxInfo.getMsgType(position - 1) .equals(IOV_MSG_TYPE_REPLACE_ACCOUNT_RESOURCE)) {
return TYPE_REPLACE_ACCOUNT_RESOURCE ;
} else if (mResTxInfo.getMsgType(position - 1) .equals(IOV_MSG_TYPE_RENEW_DOMAIN) ||
mResTxInfo.getMsgType(position - 1) .equals(IOV_MSG_TYPE_RENEW_ACCOUNT)) {
return TYPE_TX_RENEW_STARNAME;
}
return TYPE_TX_UNKNOWN;
}
}
}
private void onBindCommon(RecyclerView.ViewHolder viewHolder) {
final TxCommonHolder holder = (TxCommonHolder)viewHolder;
WDp.DpMainDenom(getBaseContext(), mBaseChain.getChain(), holder.itemFeeDenom);
WDp.DpMainDenom(getBaseContext(), mBaseChain.getChain(), holder.itemFeeUsedDenom);
WDp.DpMainDenom(getBaseContext(), mBaseChain.getChain(), holder.itemFeeLimitDenom);
if (mBaseChain.equals(COSMOS_MAIN) || mBaseChain.equals(KAVA_MAIN) || mBaseChain.equals(KAVA_TEST) ||
mBaseChain.equals(BAND_MAIN) || mBaseChain.equals(IOV_MAIN) || mBaseChain.equals(IOV_TEST) ||
mBaseChain.equals(CERTIK_MAIN) || mBaseChain.equals(CERTIK_TEST) || mBaseChain.equals(AKASH_MAIN) || mBaseChain.equals(SECRET_MAIN)) {
if (mResTxInfo.isSuccess()) {
holder.itemStatusImg.setImageDrawable(getResources().getDrawable(R.drawable.success_ic));
holder.itemStatusTxt.setText(R.string.str_success_c);
} else {
holder.itemStatusImg.setImageDrawable(getResources().getDrawable(R.drawable.fail_ic));
holder.itemStatusTxt.setText(R.string.str_failed_c);
if (mResTxInfo.failMessage().replace("\u00A0", "").startsWith("atomicswapnotfound")) {
holder.itemFailTxt.setText("atomic swap not found");
} else {
holder.itemFailTxt.setText(mResTxInfo.failMessage());
}
holder.itemFailTxt.setVisibility(View.VISIBLE);
}
holder.itemHeight.setText(mResTxInfo.height);
holder.itemMsgCnt.setText(String.valueOf(mResTxInfo.getMsgs().size()));
holder.itemGas.setText(String.format("%s / %s", mResTxInfo.gas_used, mResTxInfo.gas_wanted));
holder.itemFee.setText(WDp.getDpAmount2(getBaseContext(), mResTxInfo.simpleFee(), 6, 6));
holder.itemFeeLayer.setVisibility(View.VISIBLE);
holder.itemTime.setText(WDp.getTimeTxformat(getBaseContext(), mResTxInfo.timestamp));
holder.itemTimeGap.setText(WDp.getTimeTxGap(getBaseContext(), mResTxInfo.timestamp));
holder.itemHash.setText(mResTxInfo.txhash);
holder.itemMemo.setText(mResTxInfo.tx.value.memo);
} else if (mBaseChain.equals(IRIS_MAIN)) {
if (mResTxInfo.isIrisSuccess()) {
holder.itemStatusImg.setImageDrawable(getResources().getDrawable(R.drawable.success_ic));
holder.itemStatusTxt.setText(R.string.str_success_c);
} else {
holder.itemStatusImg.setImageDrawable(getResources().getDrawable(R.drawable.fail_ic));
holder.itemStatusTxt.setText(R.string.str_failed_c);
holder.itemFailTxt.setText(mResTxInfo.failMsgIris());
holder.itemFailTxt.setVisibility(View.VISIBLE);
}
holder.itemHeight.setText(mResTxInfo.height);
holder.itemMsgCnt.setText(String.valueOf(mResTxInfo.getMsgs().size()));
holder.itemGas.setText(String.format("%s / %s", mResTxInfo.result.GasUsed, mResTxInfo.result.GasWanted));
holder.itemFeeUsed.setText(WDp.getDpAmount2(getBaseContext(), mResTxInfo.simpleUsedFeeIris(), 18, 18));
holder.itemFeeUsedLayer.setVisibility(View.VISIBLE);
holder.itemFeeLimit.setText(WDp.getDpAmount2(getBaseContext(), mResTxInfo.simpleFee(), 18, 18));
holder.itemFeeLimitLayer.setVisibility(View.VISIBLE);
holder.itemTime.setText(WDp.getTimeTxformat(getBaseContext(), mResTxInfo.timestamp));
holder.itemTimeGap.setText(WDp.getTimeTxGap(getBaseContext(), mResTxInfo.timestamp));
holder.itemHash.setText(mResTxInfo.hash);
holder.itemMemo.setText(mResTxInfo.tx.value.memo);
} else if (mBaseChain.equals(BNB_MAIN) || mBaseChain.equals(BNB_TEST)) {
holder.itemStatusImg.setImageDrawable(getResources().getDrawable(R.drawable.success_ic));
holder.itemStatusTxt.setText(R.string.str_success_c);
holder.itemHeight.setText(mResBnbTxInfo.height);
holder.itemMsgCnt.setText(String.valueOf(mResBnbTxInfo.tx.value.msg.size()));
holder.itemGas.setText("-");
holder.itemFee.setText(WDp.getDpAmount2(getBaseContext(), new BigDecimal(FEE_BNB_SEND), 0, 8));
holder.itemFeeLayer.setVisibility(View.VISIBLE);
holder.itemTime.setText(WDp.getTimeformat(getBaseContext(), mBnbTime));
holder.itemTimeGap.setText(WDp.getTimeGap(getBaseContext(), mBnbTime));
holder.itemHash.setText(mResBnbTxInfo.hash);
holder.itemMemo.setText(mResBnbTxInfo.tx.value.memo);
} else if (mBaseChain.equals(OK_TEST)) {
if (mResTxInfo.isSuccess()) {
holder.itemStatusImg.setImageDrawable(getResources().getDrawable(R.drawable.success_ic));
holder.itemStatusTxt.setText(R.string.str_success_c);
} else {
holder.itemStatusImg.setImageDrawable(getResources().getDrawable(R.drawable.fail_ic));
holder.itemStatusTxt.setText(R.string.str_failed_c);
holder.itemFailTxt.setText(mResTxInfo.failMessage());
holder.itemFailTxt.setVisibility(View.VISIBLE);
}
holder.itemHeight.setText(mResTxInfo.height);
holder.itemMsgCnt.setText(String.valueOf(mResTxInfo.getMsgs().size()));
holder.itemGas.setText(String.format("%s / %s", mResTxInfo.gas_used, mResTxInfo.gas_wanted));
holder.itemFee.setText(WDp.getDpAmount2(getBaseContext(), mResTxInfo.simpleFee(), 0, 8));
holder.itemFeeLayer.setVisibility(View.VISIBLE);
holder.itemTime.setText(WDp.getTimeTxformat(getBaseContext(), mResTxInfo.timestamp));
holder.itemTimeGap.setText(WDp.getTimeTxGap(getBaseContext(), mResTxInfo.timestamp));
holder.itemHash.setText(mResTxInfo.txhash);
holder.itemMemo.setText(mResTxInfo.tx.value.memo);
}
holder.itemBtnHashLink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent webintent = new Intent(getBaseContext(), WebActivity.class);
if (mBaseChain.equals(COSMOS_MAIN) || mBaseChain.equals(KAVA_MAIN) || mBaseChain.equals(BAND_MAIN) || mBaseChain.equals(OK_TEST) ||
mBaseChain.equals(IOV_MAIN) || mBaseChain.equals(KAVA_TEST) || mBaseChain.equals(CERTIK_MAIN) || mBaseChain.equals(CERTIK_TEST) || mBaseChain.equals(AKASH_MAIN) || mBaseChain.equals(SECRET_MAIN)) {
webintent.putExtra("txid", mResTxInfo.txhash);
} else if (mBaseChain.equals(IRIS_MAIN)) {
webintent.putExtra("txid", mResTxInfo.hash);
} else if (mBaseChain.equals(BNB_MAIN) || mBaseChain.equals(BNB_TEST)) {
webintent.putExtra("txid", mResBnbTxInfo.hash);
} else {
return;
}
webintent.putExtra("chain", mBaseChain.getChain());
webintent.putExtra("goMain", mIsGen);
startActivity(webintent);
}
});
}
private void onBindTransfer(RecyclerView.ViewHolder viewHolder, int position) {
final TxTransferHolder holder = (TxTransferHolder)viewHolder;
holder.itemSendReceiveImg.setColorFilter(WDp.getChainColor(getBaseContext(), mBaseChain), android.graphics.PorterDuff.Mode.SRC_IN);
if (mBaseChain.equals(COSMOS_MAIN) || mBaseChain.equals(KAVA_MAIN) || mBaseChain.equals(KAVA_TEST) ||
mBaseChain.equals(BAND_MAIN) || mBaseChain.equals(IOV_MAIN) || mBaseChain.equals(IOV_TEST) ||
mBaseChain.equals(OK_TEST) || mBaseChain.equals(CERTIK_MAIN) || mBaseChain.equals(CERTIK_TEST) || mBaseChain.equals(AKASH_MAIN) || mBaseChain.equals(SECRET_MAIN)) {
final Msg msg = mResTxInfo.getMsg(position - 1);
ArrayList<Coin> toDpCoin = new ArrayList<>();
if (msg.type.equals(COSMOS_MSG_TYPE_TRANSFER2) || msg.type.equals(OK_MSG_TYPE_TRANSFER) || msg.type.equals(CERTIK_MSG_TYPE_TRANSFER)) {
holder.itemFromAddress.setText(msg.value.from_address);
holder.itemToAddress.setText(msg.value.to_address);
if (mAccount.address.equals(msg.value.from_address)) {
holder.itemSendRecieveTv.setText(R.string.tx_send);
}
if (mAccount.address.equals(msg.value.to_address)) {
holder.itemSendRecieveTv.setText(R.string.tx_receive);
}
toDpCoin = msg.value.getCoins();
WUtil.onSortingCoins(toDpCoin, mBaseChain);
} else if (msg.type.equals(COSMOS_MSG_TYPE_TRANSFER3) && (msg.value.inputs != null && msg.value.outputs != null)) {
holder.itemFromAddress.setText(msg.value.inputs.get(0).address);
holder.itemToAddress.setText(msg.value.outputs.get(0).address);
if (mAccount.address.equals(msg.value.inputs.get(0).address)) {
holder.itemSendRecieveTv.setText(R.string.tx_send);
}
if (mAccount.address.equals(msg.value.outputs.get(0).address)) {
holder.itemSendRecieveTv.setText(R.string.tx_receive);
}
toDpCoin = msg.value.inputs.get(0).coins;
} else if (msg.type.equals(OK_MSG_TYPE_MULTI_TRANSFER)) {
holder.itemFromAddress.setText(msg.value.from);
holder.itemToAddress.setText(msg.value.transfers.get(0).to);
if (mAccount.address.equals(msg.value.from)) {
holder.itemSendRecieveTv.setText(R.string.tx_send);
}
if (mAccount.address.equals(msg.value.transfers.get(0).to)) {
holder.itemSendRecieveTv.setText(R.string.tx_receive);
}
toDpCoin = msg.value.transfers.get(0).coins;
WUtil.onSortingCoins(toDpCoin, mBaseChain);
}
//support multi type(denom) coins transfer
if (toDpCoin.size() == 1) {
holder.itemSingleCoinLayer.setVisibility(View.VISIBLE);
WDp.showCoinDp(getBaseContext(), toDpCoin.get(0), holder.itemAmountDenom, holder.itemAmount, mBaseChain);
} else {
holder.itemMultiCoinLayer.setVisibility(View.VISIBLE);
if (toDpCoin.size() > 0) {
WDp.showCoinDp(getBaseContext(), toDpCoin.get(0), holder.itemAmountDenom0, holder.itemAmount0, mBaseChain);
}
if (toDpCoin.size() > 1) {
holder.itemAmountLayer1.setVisibility(View.VISIBLE);
WDp.showCoinDp(getBaseContext(), toDpCoin.get(1), holder.itemAmountDenom1, holder.itemAmount1, mBaseChain);
}
if (toDpCoin.size() > 2) {
holder.itemAmountLayer2.setVisibility(View.VISIBLE);
WDp.showCoinDp(getBaseContext(), toDpCoin.get(2), holder.itemAmountDenom2, holder.itemAmount2, mBaseChain);
}
if (toDpCoin.size() > 3) {
holder.itemAmountLayer3.setVisibility(View.VISIBLE);
WDp.showCoinDp(getBaseContext(), toDpCoin.get(3), holder.itemAmountDenom3, holder.itemAmount3, mBaseChain);
}
if (toDpCoin.size() > 4) {
holder.itemAmountLayer4.setVisibility(View.VISIBLE);
WDp.showCoinDp(getBaseContext(), toDpCoin.get(4), holder.itemAmountDenom4, holder.itemAmount4, mBaseChain);
}
}
} else if (mBaseChain.equals(IRIS_MAIN)) {
final Msg msg = mResTxInfo.getMsg(position - 1);
holder.itemFromAddress.setText(msg.value.inputs.get(0).address);
holder.itemToAddress.setText(msg.value.outputs.get(0).address);
if (mAccount.address.equals(msg.value.inputs.get(0).address)) {
holder.itemSendRecieveTv.setText(R.string.tx_send);
}
if (mAccount.address.equals(msg.value.outputs.get(0).address)) {
holder.itemSendRecieveTv.setText(R.string.tx_receive);
}
ArrayList<Coin> toDpCoin = msg.value.inputs.get(0).coins;
if (toDpCoin.size() == 1) {
holder.itemSingleCoinLayer.setVisibility(View.VISIBLE);
WDp.showCoinDp(getBaseContext(), toDpCoin.get(0), holder.itemAmountDenom, holder.itemAmount, mBaseChain);
} else {
holder.itemMultiCoinLayer.setVisibility(View.VISIBLE);
if (toDpCoin.size() > 0) {
WDp.showCoinDp(getBaseContext(), toDpCoin.get(0), holder.itemAmountDenom0, holder.itemAmount0, mBaseChain);
}
if (toDpCoin.size() > 1) {
holder.itemAmountLayer1.setVisibility(View.VISIBLE);
WDp.showCoinDp(getBaseContext(), toDpCoin.get(1), holder.itemAmountDenom1, holder.itemAmount1, mBaseChain);
}
if (toDpCoin.size() > 2) {
holder.itemAmountLayer2.setVisibility(View.VISIBLE);
WDp.showCoinDp(getBaseContext(), toDpCoin.get(2), holder.itemAmountDenom2, holder.itemAmount2, mBaseChain);
}
if (toDpCoin.size() > 3) {
holder.itemAmountLayer3.setVisibility(View.VISIBLE);
WDp.showCoinDp(getBaseContext(), toDpCoin.get(3), holder.itemAmountDenom3, holder.itemAmount3, mBaseChain);
}
if (toDpCoin.size() > 4) {
holder.itemAmountLayer4.setVisibility(View.VISIBLE);
WDp.showCoinDp(getBaseContext(), toDpCoin.get(4), holder.itemAmountDenom4, holder.itemAmount4, mBaseChain);
}
}
} else if (mBaseChain.equals(BNB_MAIN) || mBaseChain.equals(BNB_TEST)) {
final Msg msg = mResBnbTxInfo.getMsg(position - 1);
holder.itemFromAddress.setText(msg.value.inputs.get(0).address);
holder.itemToAddress.setText(msg.value.outputs.get(0).address);
if (mAccount.address.equals(msg.value.inputs.get(0).address)) {
holder.itemSendRecieveTv.setText(R.string.tx_send);
}
if (mAccount.address.equals(msg.value.outputs.get(0).address)) {
holder.itemSendRecieveTv.setText(R.string.tx_receive);
}
ArrayList<Coin> toDpCoin = msg.value.inputs.get(0).coins;
holder.itemSingleCoinLayer.setVisibility(View.VISIBLE);
WDp.showCoinDp(getBaseContext(), toDpCoin.get(0), holder.itemAmountDenom, holder.itemAmount, mBaseChain);
}
}
//TODO now not perfect support with multi transfer with multi coins!!
private void onBindMultiSend(RecyclerView.ViewHolder viewHolder, int position) {
final TxMultiSendHolder holder = (TxMultiSendHolder)viewHolder;
WDp.DpMainDenom(getBaseContext(), mBaseChain.getChain(), holder.itemInputDenom0);
WDp.DpMainDenom(getBaseContext(), mBaseChain.getChain(), holder.itemInputDenom1);
WDp.DpMainDenom(getBaseContext(), mBaseChain.getChain(), holder.itemInputDenom2);
WDp.DpMainDenom(getBaseContext(), mBaseChain.getChain(), holder.itemInputDenom3);
WDp.DpMainDenom(getBaseContext(), mBaseChain.getChain(), holder.itemOutputDenom0);
WDp.DpMainDenom(getBaseContext(), mBaseChain.getChain(), holder.itemOutputDenom1);
WDp.DpMainDenom(getBaseContext(), mBaseChain.getChain(), holder.itemOutputDenom2);
WDp.DpMainDenom(getBaseContext(), mBaseChain.getChain(), holder.itemOutputDenom3);
holder.itemSendReceiveImg.setColorFilter(WDp.getChainColor(getBaseContext(), mBaseChain), android.graphics.PorterDuff.Mode.SRC_IN);
if (mBaseChain.equals(COSMOS_MAIN) || mBaseChain.equals(KAVA_MAIN) || mBaseChain.equals(KAVA_TEST) || mBaseChain.equals(BAND_MAIN) || mBaseChain.equals(IOV_MAIN) ||
mBaseChain.equals(OK_TEST) || mBaseChain.equals(CERTIK_MAIN) || mBaseChain.equals(CERTIK_TEST) || mBaseChain.equals(IOV_TEST) || mBaseChain.equals(AKASH_MAIN) || mBaseChain.equals(SECRET_MAIN)) {
final Msg msg = mResTxInfo.getMsg(position - 1);
holder.itemInputAddress0.setText(msg.value.inputs.get(0).address);
holder.itemInputAmount0.setText(WDp.getDpAmount(getBaseContext(), new BigDecimal(msg.value.inputs.get(0).coins.get(0).amount), 6, mBaseChain));
holder.itemOutputAddress0.setText(msg.value.outputs.get(0).address);
holder.itemOutputAmount0.setText(WDp.getDpAmount(getBaseContext(), new BigDecimal(msg.value.outputs.get(0).coins.get(0).amount), 6, mBaseChain));
if (msg.value.inputs.size() > 1) {
holder.itemInputLayer1.setVisibility(View.VISIBLE);
holder.itemInputAddress1.setText(msg.value.inputs.get(1).address);
holder.itemInputAmount1.setText(WDp.getDpAmount(getBaseContext(), new BigDecimal(msg.value.inputs.get(1).coins.get(0).amount), 6, mBaseChain));
}
if (msg.value.inputs.size() > 2) {
holder.itemInputLayer2.setVisibility(View.VISIBLE);
holder.itemInputAddress2.setText(msg.value.inputs.get(2).address);
holder.itemInputAmount2.setText(WDp.getDpAmount(getBaseContext(), new BigDecimal(msg.value.inputs.get(2).coins.get(0).amount), 6, mBaseChain));
}
if (msg.value.inputs.size() > 3) {
holder.itemInputLayer3.setVisibility(View.VISIBLE);
holder.itemInputAddress3.setText(msg.value.inputs.get(3).address);
holder.itemInputAmount3.setText(WDp.getDpAmount(getBaseContext(), new BigDecimal(msg.value.inputs.get(3).coins.get(0).amount), 6, mBaseChain));
}
if (msg.value.outputs.size() > 1) {
holder.itemOutputLayer1.setVisibility(View.VISIBLE);
holder.itemOutputAddress1.setText(msg.value.outputs.get(1).address);
holder.itemOutputAmount1.setText(WDp.getDpAmount(getBaseContext(), new BigDecimal(msg.value.outputs.get(1).coins.get(0).amount), 6, mBaseChain));
}
if (msg.value.outputs.size() > 2) {
holder.itemOutputLayer2.setVisibility(View.VISIBLE);
holder.itemOutputAddress2.setText(msg.value.outputs.get(2).address);
holder.itemOutputAmount2.setText(WDp.getDpAmount(getBaseContext(), new BigDecimal(msg.value.outputs.get(2).coins.get(0).amount), 6, mBaseChain));
}
if (msg.value.outputs.size() > 3) {
holder.itemOutputLayer3.setVisibility(View.VISIBLE);
holder.itemOutputAddress3.setText(msg.value.outputs.get(3).address);
holder.itemOutputAmount3.setText(WDp.getDpAmount(getBaseContext(), new BigDecimal(msg.value.outputs.get(3).coins.get(0).amount), 6, mBaseChain));
}
for (Input input:msg.value.inputs) {
if (mAccount.address.equals(input.address)) {
holder.itemSendRecieveTv.setText(R.string.tx_send);
}
}
for (Output output:msg.value.outputs) {
if (mAccount.address.equals(output.address)) {
holder.itemSendRecieveTv.setText(R.string.tx_receive);
}
}
} else if (mBaseChain.equals(IRIS_MAIN)) {
final Msg msg = mResTxInfo.getMsg(position - 1);
holder.itemInputAddress0.setText(msg.value.inputs.get(0).address);
holder.itemInputAmount0.setText(WDp.getDpAmount2(getBaseContext(), new BigDecimal(msg.value.inputs.get(0).coins.get(0).amount), 18, 18));
holder.itemOutputAddress0.setText(msg.value.outputs.get(0).address);
holder.itemOutputAmount0.setText(WDp.getDpAmount2(getBaseContext(), new BigDecimal(msg.value.outputs.get(0).coins.get(0).amount), 18, 18));
}
}
private void onBindDelegate(RecyclerView.ViewHolder viewHolder, int position) {
final TxDelegateHolder holder = (TxDelegateHolder)viewHolder;
WDp.DpMainDenom(getBaseContext(), mBaseChain.getChain(), holder.itemDelegateAmountDenom);
WDp.DpMainDenom(getBaseContext(), mBaseChain.getChain(), holder.itemAutoRewardAmountDenom);
holder.itemDelegateImg.setColorFilter(WDp.getChainColor(getBaseContext(), mBaseChain), android.graphics.PorterDuff.Mode.SRC_IN);
if (mBaseChain.equals(COSMOS_MAIN) || mBaseChain.equals(KAVA_MAIN) || mBaseChain.equals(KAVA_TEST) ||
mBaseChain.equals(BAND_MAIN) || mBaseChain.equals(IOV_MAIN) || mBaseChain.equals(IOV_TEST) ||
mBaseChain.equals(CERTIK_MAIN) || mBaseChain.equals(CERTIK_TEST) || mBaseChain.equals(AKASH_MAIN) || mBaseChain.equals(SECRET_MAIN)) {
final Msg msg = mResTxInfo.getMsg(position - 1);
holder.itemDelegator.setText(msg.value.delegator_address);
holder.itemMoniker.setText(WUtil.getMonikerName(msg.value.validator_address, mAllValidators, true));
holder.itemValidator.setText(msg.value.validator_address);
holder.itemDelegateAmount.setText(WDp.getDpAmount2(getBaseContext(), new BigDecimal(msg.value.getCoins().get(0).amount), 6, 6));
holder.itemAutoRewardAmount.setText(WDp.getDpAmount2(getBaseContext(), mResTxInfo.simpleAutoReward(mAccount.address, position - 1), 6, 6));
if (mResTxInfo.getMsgs().size() == 1) {
holder.itemAutoRewardLayer.setVisibility(View.VISIBLE);
}
} else if (mBaseChain.equals(IRIS_MAIN)) {
final Msg msg = mResTxInfo.getMsg(position - 1);
holder.itemDelegator.setText(msg.value.delegator_addr);
holder.itemMoniker.setText(WUtil.getMonikerName(msg.value.validator_addr, mAllValidators, true));
holder.itemValidator.setText(msg.value.validator_addr);
holder.itemDelegateAmount.setText(WDp.getDpAmount2(getBaseContext(), new BigDecimal(msg.value.delegation.amount), 18, 18));
}
}
private void onBindUndelegate(RecyclerView.ViewHolder viewHolder, int position) {
final TxUndelegateHolder holder = (TxUndelegateHolder)viewHolder;
WDp.DpMainDenom(getBaseContext(), mBaseChain.getChain(), holder.itemUnDelegateAmountDenom);
WDp.DpMainDenom(getBaseContext(), mBaseChain.getChain(), holder.itemAutoRewardAmountDenom);
holder.itemUndelegateImg.setColorFilter(WDp.getChainColor(getBaseContext(), mBaseChain), android.graphics.PorterDuff.Mode.SRC_IN);
if (mBaseChain.equals(COSMOS_MAIN) || mBaseChain.equals(KAVA_MAIN) || mBaseChain.equals(KAVA_TEST) ||
mBaseChain.equals(BAND_MAIN) || mBaseChain.equals(IOV_MAIN) || mBaseChain.equals(IOV_TEST) ||
mBaseChain.equals(CERTIK_MAIN) || mBaseChain.equals(CERTIK_TEST) || mBaseChain.equals(AKASH_MAIN) || mBaseChain.equals(SECRET_MAIN)) {
final Msg msg = mResTxInfo.getMsg(position - 1);
holder.itemUnDelegator.setText(msg.value.delegator_address);
holder.itemMoniker.setText(WUtil.getMonikerName(msg.value.validator_address, mAllValidators, true));
holder.itemValidator.setText(msg.value.validator_address);
holder.itemUndelegateAmount.setText(WDp.getDpAmount(getBaseContext(), new BigDecimal(msg.value.getCoins().get(0).amount), 6, mBaseChain));
holder.itemAutoRewardAmount.setText(WDp.getDpAmount(getBaseContext(), mResTxInfo.simpleAutoReward(mAccount.address, position - 1), 6, mBaseChain));
if (mResTxInfo.getMsgs().size() == 1) {
holder.itemAutoRewardLayer.setVisibility(View.VISIBLE);
}
} else if (mBaseChain.equals(IRIS_MAIN)) {
final Msg msg = mResTxInfo.getMsg(position - 1);
holder.itemUnDelegator.setText(msg.value.delegator_addr);
holder.itemMoniker.setText(WUtil.getMonikerName(msg.value.validator_addr, mAllValidators, true));
holder.itemValidator.setText(msg.value.validator_addr);
holder.itemUndelegateAmount.setText(WDp.getDpAmount2(getBaseContext(), new BigDecimal(msg.value.shares_amount), 18, 18));
}
}
private void onBindRedelegate(RecyclerView.ViewHolder viewHolder, int position) {
final TxRedelegateHolder holder = (TxRedelegateHolder)viewHolder;
WDp.DpMainDenom(getBaseContext(), mBaseChain.getChain(), holder.itemReDelegateAmountDenom);
WDp.DpMainDenom(getBaseContext(), mBaseChain.getChain(), holder.itemAutoRewardAmountDenom);
holder.itemRedelegateImg.setColorFilter(WDp.getChainColor(getBaseContext(), mBaseChain), android.graphics.PorterDuff.Mode.SRC_IN);
if (mBaseChain.equals(COSMOS_MAIN) || mBaseChain.equals(KAVA_MAIN) || mBaseChain.equals(KAVA_TEST) ||
mBaseChain.equals(BAND_MAIN) || mBaseChain.equals(IOV_MAIN) || mBaseChain.equals(IOV_TEST) ||
mBaseChain.equals(CERTIK_MAIN) || mBaseChain.equals(CERTIK_TEST) || mBaseChain.equals(AKASH_MAIN) || mBaseChain.equals(SECRET_MAIN)) {
final Msg msg = mResTxInfo.getMsg(position - 1);
holder.itemReDelegator.setText(msg.value.delegator_address);
holder.itemFromValidator.setText(msg.value.validator_src_address);
holder.itemFromMoniker.setText(WUtil.getMonikerName(msg.value.validator_src_address, mAllValidators, true));
holder.itemToValidator.setText(msg.value.validator_dst_address);
holder.itemToMoniker.setText(WUtil.getMonikerName(msg.value.validator_dst_address, mAllValidators, true));
holder.itemRedelegateAmount.setText(WDp.getDpAmount(getBaseContext(), new BigDecimal(msg.value.getCoins().get(0).amount), 6, mBaseChain));
holder.itemAutoRewardAmount.setText(WDp.getDpAmount(getBaseContext(), mResTxInfo.simpleAutoReward(mAccount.address, position - 1), 6, mBaseChain));
if (mResTxInfo.getMsgs().size() == 1) {
holder.itemAutoRewardLayer.setVisibility(View.VISIBLE);
}
} else if (mBaseChain.equals(IRIS_MAIN)) {
final Msg msg = mResTxInfo.getMsg(position - 1);
holder.itemReDelegator.setText(msg.value.delegator_addr);
holder.itemFromValidator.setText(msg.value.validator_src_addr);
holder.itemFromMoniker.setText(WUtil.getMonikerName(msg.value.validator_src_addr, mAllValidators, true));
holder.itemToValidator.setText(msg.value.validator_dst_addr);
holder.itemToMoniker.setText(WUtil.getMonikerName(msg.value.validator_dst_addr, mAllValidators, true));
holder.itemRedelegateAmount.setText(WDp.getDpAmount2(getBaseContext(), new BigDecimal(msg.value.shares_amount), 18, 18));
}
}
private void onBindReward(RecyclerView.ViewHolder viewHolder, int position) {
final TxRewardHolder holder = (TxRewardHolder)viewHolder;
WDp.DpMainDenom(getBaseContext(), mBaseChain.getChain(), holder.itemRewardAmountDenom);
holder.itemRewardImg.setColorFilter(WDp.getChainColor(getBaseContext(), mBaseChain), android.graphics.PorterDuff.Mode.SRC_IN);
if (mBaseChain.equals(COSMOS_MAIN) || mBaseChain.equals(KAVA_MAIN) || mBaseChain.equals(KAVA_TEST) ||
mBaseChain.equals(BAND_MAIN) || mBaseChain.equals(IOV_MAIN) || mBaseChain.equals(IOV_TEST) ||
mBaseChain.equals(CERTIK_MAIN) || mBaseChain.equals(CERTIK_TEST) || mBaseChain.equals(AKASH_MAIN) || mBaseChain.equals(SECRET_MAIN)) {
final Msg msg = mResTxInfo.getMsg(position - 1);
holder.itemDelegator.setText(msg.value.delegator_address);
holder.itemMoniker.setText(WUtil.getMonikerName(msg.value.validator_address, mAllValidators, true));
holder.itemValidator.setText(msg.value.validator_address);
holder.itemRewardAmount.setText(WDp.getDpAmount(getBaseContext(), mResTxInfo.simpleReward(msg.value.validator_address, position - 1), 6, mBaseChain));
} else if (mBaseChain.equals(IRIS_MAIN)) {
final Msg msg = mResTxInfo.getMsg(position - 1);
holder.itemDelegator.setText(msg.value.delegator_addr);
holder.itemMoniker.setText(WUtil.getMonikerName(msg.value.validator_addr, mAllValidators, true));
holder.itemValidator.setText(msg.value.validator_addr);
holder.itemRewardAmount.setText(WDp.getDpAmount2(getBaseContext(), mResTxInfo.simpleRewardIris(), 18, 18));
}
}
private void onBindRewardAll(RecyclerView.ViewHolder viewHolder, int position) {
final TxRewardAllHolder holder = (TxRewardAllHolder)viewHolder;
WDp.DpMainDenom(getBaseContext(), mBaseChain.getChain(), holder.itemRewardAllAmountDenom);
holder.itemMsgImg.setColorFilter(WDp.getChainColor(getBaseContext(), mBaseChain), android.graphics.PorterDuff.Mode.SRC_IN);
if (mBaseChain.equals(IRIS_MAIN)) {
final Msg msg = mResTxInfo.getMsg(position - 1);
holder.itemDelegator.setText(msg.value.delegator_addr);
holder.itemRewardValidatorCnt.setText( " (" + String.valueOf(mResTxInfo.rewardValidatorsIris().size()) + ")");
holder.itemRewardValidator0.setText(mResTxInfo.rewardValidatorIris(0));
holder.itemRewardMoniker0.setText(WUtil.getMonikerName(mResTxInfo.rewardValidatorIris(0), mAllValidators, true));
if (mResTxInfo.rewardValidatorsIris().size() > 1) {
holder.itemRewardValidator1.setVisibility(View.VISIBLE);
holder.itemRewardMoniker1.setVisibility(View.VISIBLE);
holder.itemRewardValidator1.setText(mResTxInfo.rewardValidatorIris(1));
holder.itemRewardMoniker1.setText(WUtil.getMonikerName(mResTxInfo.rewardValidatorIris(1), mAllValidators, true));
}
if (mResTxInfo.rewardValidatorsIris().size() > 2) {
holder.itemRewardValidator2.setVisibility(View.VISIBLE);
holder.itemRewardMoniker2.setVisibility(View.VISIBLE);
holder.itemRewardValidator2.setText(mResTxInfo.rewardValidatorIris(2));
holder.itemRewardMoniker2.setText(WUtil.getMonikerName(mResTxInfo.rewardValidatorIris(2), mAllValidators, true));
}
if (mResTxInfo.rewardValidatorsIris().size() > 3) {
holder.itemRewardValidator3.setVisibility(View.VISIBLE);
holder.itemRewardMoniker3.setVisibility(View.VISIBLE);
holder.itemRewardValidator3.setText(mResTxInfo.rewardValidatorIris(3));
holder.itemRewardMoniker3.setText(WUtil.getMonikerName(mResTxInfo.rewardValidatorIris(3), mAllValidators, true));
}
if (mResTxInfo.rewardValidatorsIris().size() > 4) {
holder.itemRewardValidator4.setVisibility(View.VISIBLE);
holder.itemRewardMoniker4.setVisibility(View.VISIBLE);
holder.itemRewardValidator4.setText(mResTxInfo.rewardValidatorIris(4));
holder.itemRewardMoniker4.setText(WUtil.getMonikerName(mResTxInfo.rewardValidatorIris(4), mAllValidators, true));
}
if (mResTxInfo.rewardValidatorsIris().size() > 5) {
holder.itemRewardValidator5.setVisibility(View.VISIBLE);
holder.itemRewardMoniker5.setVisibility(View.VISIBLE);
holder.itemRewardValidator5.setText(mResTxInfo.rewardValidatorIris(5));
holder.itemRewardMoniker5.setText(WUtil.getMonikerName(mResTxInfo.rewardValidatorIris(5), mAllValidators, true));
}
if (mResTxInfo.rewardValidatorsIris().size() > 6) {
holder.itemRewardValidator6.setVisibility(View.VISIBLE);
holder.itemRewardMoniker6.setVisibility(View.VISIBLE);
holder.itemRewardValidator6.setText(mResTxInfo.rewardValidatorIris(6));
holder.itemRewardMoniker6.setText(WUtil.getMonikerName(mResTxInfo.rewardValidatorIris(6), mAllValidators, true));
}
if (mResTxInfo.rewardValidatorsIris().size() > 7) {
holder.itemRewardValidator7.setVisibility(View.VISIBLE);
holder.itemRewardMoniker7.setVisibility(View.VISIBLE);
holder.itemRewardValidator7.setText(mResTxInfo.rewardValidatorIris(7));
holder.itemRewardMoniker7.setText(WUtil.getMonikerName(mResTxInfo.rewardValidatorIris(7), mAllValidators, true));
}
holder.itemRewardAllAmount.setText(WDp.getDpAmount2(getBaseContext(), mResTxInfo.simpleRewardIris(), 18, 18));
}
}
private void onBindAddress(RecyclerView.ViewHolder viewHolder, int position) {
final TxAddressHolder holder = (TxAddressHolder)viewHolder;
holder.itemAddressImg.setColorFilter(WDp.getChainColor(getBaseContext(), mBaseChain), android.graphics.PorterDuff.Mode.SRC_IN);
if (mBaseChain.equals(COSMOS_MAIN) || mBaseChain.equals(KAVA_MAIN) || mBaseChain.equals(KAVA_TEST) ||
mBaseChain.equals(BAND_MAIN) || mBaseChain.equals(IOV_MAIN) || mBaseChain.equals(IOV_TEST) ||
mBaseChain.equals(CERTIK_MAIN) || mBaseChain.equals(CERTIK_TEST) || mBaseChain.equals(AKASH_MAIN) || mBaseChain.equals(SECRET_MAIN)) {
final Msg msg = mResTxInfo.getMsg(position - 1);
holder.itemDelegator.setText(msg.value.delegator_address);
holder.itemWithdrawAddress.setText(msg.value.withdraw_address);
} else if (mBaseChain.equals(IRIS_MAIN)) {
final Msg msg = mResTxInfo.getMsg(position - 1);
holder.itemDelegator.setText(msg.value.delegator_addr);
holder.itemWithdrawAddress.setText(msg.value.withdraw_addr);
}
}
private void onBindVote(RecyclerView.ViewHolder viewHolder, int position) {
final TxVoteHolder holder = (TxVoteHolder)viewHolder;
holder.itemVoteImg.setColorFilter(WDp.getChainColor(getBaseContext(), mBaseChain), android.graphics.PorterDuff.Mode.SRC_IN);
if (mBaseChain.equals(COSMOS_MAIN) || mBaseChain.equals(KAVA_MAIN) || mBaseChain.equals(KAVA_TEST) ||
mBaseChain.equals(BAND_MAIN) || mBaseChain.equals(IOV_MAIN) || mBaseChain.equals(IOV_TEST) ||
mBaseChain.equals(CERTIK_MAIN) || mBaseChain.equals(CERTIK_TEST) || mBaseChain.equals(AKASH_MAIN) || mBaseChain.equals(SECRET_MAIN)) {
final Msg msg = mResTxInfo.getMsg(position - 1);
holder.itemDelegator.setText(msg.value.voter);
holder.itemProposalId.setText(msg.value.proposal_id);
holder.itemOpinion.setText(msg.value.option);
} else if (mBaseChain.equals(IRIS_MAIN)) {
final Msg msg = mResTxInfo.getMsg(position - 1);
holder.itemDelegator.setText(msg.value.voter);
holder.itemProposalId.setText(msg.value.proposal_id);
holder.itemOpinion.setText(msg.value.option);
}
}
private void onBindCommission(RecyclerView.ViewHolder viewHolder, int position) {
final TxCommissionHolder holder = (TxCommissionHolder)viewHolder;
WDp.DpMainDenom(getBaseContext(), mBaseChain.getChain(), holder.itemCommissionAmountDenom);
holder.itemCommissionImg.setColorFilter(WDp.getChainColor(getBaseContext(), mBaseChain), android.graphics.PorterDuff.Mode.SRC_IN);
if (mBaseChain.equals(COSMOS_MAIN) || mBaseChain.equals(KAVA_MAIN) || mBaseChain.equals(KAVA_TEST) ||
mBaseChain.equals(BAND_MAIN) || mBaseChain.equals(IOV_MAIN) || mBaseChain.equals(IOV_TEST) ||
mBaseChain.equals(CERTIK_MAIN) || mBaseChain.equals(CERTIK_TEST) || mBaseChain.equals(AKASH_MAIN) || mBaseChain.equals(SECRET_MAIN)) {
final Msg msg = mResTxInfo.getMsg(position - 1);
holder.itemCommissionValidator.setText(msg.value.validator_address);
holder.itemCommissionValidatorMoniker.setText(WUtil.getMonikerName(msg.value.validator_address, mAllValidators, true));
holder.itemCommissionAmount.setText(WDp.getDpAmount2(getBaseContext(), mResTxInfo.simpleCommission(position - 1), 6, 6));
} else if (mBaseChain.equals(IRIS_MAIN)) {
final Msg msg = mResTxInfo.getMsg(position - 1);
holder.itemCommissionValidator.setText(msg.value.validator_addr);
holder.itemCommissionValidatorMoniker.setText(WUtil.getMonikerName(msg.value.validator_addr, mAllValidators, true));
holder.itemCommissionAmount.setText(WDp.getDpAmount2(getBaseContext(), mResTxInfo.simpleCommissionIris(), 18, 18));
}
}
private void onBindPostPrice(RecyclerView.ViewHolder viewHolder, int position) {
final TxPostPriceHolder holder = (TxPostPriceHolder)viewHolder;
holder.itemMsgImg.setColorFilter(WDp.getChainColor(getBaseContext(), mBaseChain), android.graphics.PorterDuff.Mode.SRC_IN);
if (mBaseChain.equals(KAVA_MAIN) || mBaseChain.equals(KAVA_TEST)) {
final Msg msg = mResTxInfo.getMsg(position - 1);
holder.itemPoster.setText(msg.value.from);
holder.itemMakerId.setText(msg.value.market_id);
holder.itemPostPrice.setText(msg.value.price);
holder.itemTime.setText(WDp.getTimeTxformat(getBaseContext(), msg.value.expiry) + " (" + msg.value.expiry + ")");
}
}
private void onBindCreateCdp(RecyclerView.ViewHolder viewHolder, int position) {
final TxCreateCdpHolder holder = (TxCreateCdpHolder)viewHolder;
holder.itemMsgImg.setColorFilter(WDp.getChainColor(getBaseContext(), mBaseChain), android.graphics.PorterDuff.Mode.SRC_IN);
if (mBaseChain.equals(KAVA_MAIN) || mBaseChain.equals(KAVA_TEST)) {
final Msg msg = mResTxInfo.getMsg(position - 1);
holder.itemSender.setText(msg.value.sender);
WDp.showCoinDp(getBaseContext(), msg.value.collateral, holder.itemCollateralDenom, holder.itemCollateralAmount, mBaseChain);
WDp.showCoinDp(getBaseContext(), msg.value.principal, holder.itemPrincipalDenom, holder.itemPrincipalAmount, mBaseChain);
}
}
private void onBindDepositCdp(RecyclerView.ViewHolder viewHolder, int position) {
final TxDepositCdpHolder holder = (TxDepositCdpHolder)viewHolder;
holder.itemMsgImg.setColorFilter(WDp.getChainColor(getBaseContext(), mBaseChain), android.graphics.PorterDuff.Mode.SRC_IN);
if (mBaseChain.equals(KAVA_MAIN) || mBaseChain.equals(KAVA_TEST)) {
final Msg msg = mResTxInfo.getMsg(position - 1);
holder.itemOwner.setText(msg.value.owner);
holder.itemDepositor.setText(msg.value.depositor);
WDp.showCoinDp(getBaseContext(), msg.value.collateral, holder.itemCollateralDenom, holder.itemCollateralAmount, mBaseChain);
}
}
private void onBindWithdrawCdp(RecyclerView.ViewHolder viewHolder, int position) {
final TxWithdrawCdpHolder holder = (TxWithdrawCdpHolder)viewHolder;
holder.itemMsgImg.setColorFilter(WDp.getChainColor(getBaseContext(), mBaseChain), android.graphics.PorterDuff.Mode.SRC_IN);
if (mBaseChain.equals(KAVA_MAIN) || mBaseChain.equals(KAVA_TEST)) {
final Msg msg = mResTxInfo.getMsg(position - 1);
holder.itemOwner.setText(msg.value.owner);
holder.itemDepositor.setText(msg.value.depositor);
WDp.showCoinDp(getBaseContext(), msg.value.collateral, holder.itemCollateralDenom, holder.itemCollateralAmount, mBaseChain);
}
}
private void onBindDrawDebtCdp(RecyclerView.ViewHolder viewHolder, int position) {
final TxDrawDebtCdpHolder holder = (TxDrawDebtCdpHolder)viewHolder;
holder.itemMsgImg.setColorFilter(WDp.getChainColor(getBaseContext(), mBaseChain), android.graphics.PorterDuff.Mode.SRC_IN);
if (mBaseChain.equals(KAVA_MAIN) || mBaseChain.equals(KAVA_TEST)) {
final Msg msg = mResTxInfo.getMsg(position - 1);
holder.itemSender.setText(msg.value.sender);
if (!TextUtils.isEmpty(msg.value.cdp_denom)) {
holder.itemCdpDenom.setText(msg.value.cdp_denom.toUpperCase());
} else if (!TextUtils.isEmpty(msg.value.collateral_type)) {
holder.itemCdpDenom.setText(msg.value.collateral_type.toUpperCase());
}
WDp.showCoinDp(getBaseContext(), msg.value.principal, holder.itemPrincipalDenom, holder.itemPrincipalAmount, mBaseChain);
}
}
private void onBindRepayDebtCdp(RecyclerView.ViewHolder viewHolder, int position) {
final TxRepayDebtCdpHolder holder = (TxRepayDebtCdpHolder)viewHolder;
holder.itemMsgImg.setColorFilter(WDp.getChainColor(getBaseContext(), mBaseChain), android.graphics.PorterDuff.Mode.SRC_IN);
if (mBaseChain.equals(KAVA_MAIN) || mBaseChain.equals(KAVA_TEST)) {
final Msg msg = mResTxInfo.getMsg(position - 1);
holder.itemSender.setText(msg.value.sender);
if (!TextUtils.isEmpty(msg.value.cdp_denom)) {
holder.itemCdpDenom.setText(msg.value.cdp_denom.toUpperCase());
} else if (!TextUtils.isEmpty(msg.value.collateral_type)) {
holder.itemCdpDenom.setText(msg.value.collateral_type.toUpperCase());
}
WDp.showCoinDp(getBaseContext(), msg.value.payment, holder.itemPaymentDenom, holder.itemPaymentAmount, mBaseChain);
}
}
private void onBindCreateHTLC(RecyclerView.ViewHolder viewHolder, int position) {
final TxCreateHtlcHolder holder = (TxCreateHtlcHolder)viewHolder;
holder.itemMsgImg.setColorFilter(WDp.getChainColor(getBaseContext(), mBaseChain), android.graphics.PorterDuff.Mode.SRC_IN);
if (mBaseChain.equals(KAVA_MAIN) || mBaseChain.equals(KAVA_TEST)) {
final Msg msg = mResTxInfo.getMsg(position - 1);
Coin sendCoin = msg.value.getCoins().get(0);
WDp.showCoinDp(getBaseContext(), sendCoin, holder.itemSendDenom, holder.itemSendAmount, mBaseChain);
holder.itemSender.setText(msg.value.from);
holder.itemRecipient.setText(msg.value.recipient_other_chain);
holder.itemRandomHash.setText(msg.value.random_number_hash);
holder.itemExpectIncome.setText(msg.value.expected_income);
holder.itemStatus.setText(WDp.getKavaHtlcStatus(getBaseContext(), mResTxInfo, mResKavaSwapInfo));
if (mResKavaSwapInfo != null && mResKavaSwapInfo.result.status.equals(STATUS_EXPIRED)) {
mRefundBtn.setVisibility(View.VISIBLE);
mSwapId = mResTxInfo.simpleSwapId();
}
} else if (mBaseChain.equals(BNB_MAIN) || mBaseChain.equals(BNB_TEST)) {
final Msg msg = mResBnbTxInfo.getMsg(position - 1);
if (mAccount.address.equals(msg.value.from)) {
holder.itemMsgTitle.setText(getString(R.string.tx_send_htlc2));
holder.itemSender.setText(msg.value.from);
holder.itemRecipient.setText(msg.value.recipient_other_chain);
} else if (mAccount.address.equals(msg.value.to)) {
holder.itemMsgTitle.setText(getString(R.string.tx_receive_htlc2));
holder.itemSender.setText(msg.value.sender_other_chain);
holder.itemRecipient.setText(msg.value.to);
} else {
holder.itemMsgTitle.setText(getString(R.string.tx_create_htlc2));
holder.itemSender.setText(msg.value.from);
holder.itemRecipient.setText(msg.value.to);
}
Coin sendCoin = msg.value.getCoins().get(0);
WDp.showCoinDp(getBaseContext(), sendCoin, holder.itemSendDenom, holder.itemSendAmount, mBaseChain);
holder.itemRandomHash.setText(msg.value.random_number_hash);
holder.itemExpectIncome.setText(msg.value.expected_income);
holder.itemStatus.setText(WDp.getBnbHtlcStatus(getBaseContext(), mResBnbSwapInfo, mResBnbNodeInfo));
if (mResBnbSwapInfo != null &&
mResBnbNodeInfo != null &&
mResBnbSwapInfo.status == BNB_STATUS_OPEN &&
mResBnbSwapInfo.expireHeight < mResBnbNodeInfo.getCHeight()) {
mRefundBtn.setVisibility(View.VISIBLE);
mSwapId = mResBnbTxInfo.simpleSwapId();
}
}
}
private void onBindClaimHTLC(RecyclerView.ViewHolder viewHolder, int position) {
final TxClaimHtlcHolder holder = (TxClaimHtlcHolder)viewHolder;
holder.itemMsgImg.setColorFilter(WDp.getChainColor(getBaseContext(), mBaseChain), android.graphics.PorterDuff.Mode.SRC_IN);
if (mBaseChain.equals(KAVA_MAIN) || mBaseChain.equals(KAVA_TEST)) {
final Msg msg = mResTxInfo.getMsg(position - 1);
Coin receiveCoin = mResTxInfo.simpleSwapCoin();
try {
if (!TextUtils.isEmpty(receiveCoin.denom)) {
WDp.showCoinDp(getBaseContext(), receiveCoin, holder.itemReceiveDenom, holder.itemReceiveAmount, mBaseChain);
}
} catch (Exception e) {}
holder.itemClaimer.setText(msg.value.from);
holder.itemRandomNumber.setText(msg.value.random_number);
holder.itemSwapId.setText(msg.value.swap_id);
} else if (mBaseChain.equals(BNB_MAIN) || mBaseChain.equals(BNB_TEST)) {
final Msg msg = mResBnbTxInfo.getMsg(position - 1);
holder.itemAmountLayer.setVisibility(View.GONE);
holder.itemClaimer.setText(msg.value.from);
holder.itemRandomNumber.setText(msg.value.random_number);
holder.itemSwapId.setText(msg.value.swap_id);
}
}
private void onBindRefundHTLC(RecyclerView.ViewHolder viewHolder, int position) {
final TxRefundHtlcHolder holder = (TxRefundHtlcHolder)viewHolder;
holder.itemMsgImg.setColorFilter(WDp.getChainColor(getBaseContext(), mBaseChain), android.graphics.PorterDuff.Mode.SRC_IN);
if (mBaseChain.equals(KAVA_MAIN) || mBaseChain.equals(KAVA_TEST)) {
final Msg msg = mResTxInfo.getMsg(position - 1);
Coin refundCoin = mResTxInfo.simpleRefund();
try {
if (!TextUtils.isEmpty(refundCoin.denom)) {
WDp.showCoinDp(getBaseContext(), refundCoin, holder.itemRefundDenom, holder.itemRefundAmount, mBaseChain);
}
} catch (Exception e) { }
holder.itemFromAddr.setText(msg.value.from);
holder.itemSwapId.setText(msg.value.swap_id);
} else if (mBaseChain.equals(BNB_MAIN) || mBaseChain.equals(BNB_TEST)) {
final Msg msg = mResBnbTxInfo.getMsg(position - 1);
holder.itemAmountLayer.setVisibility(View.GONE);
holder.itemFromAddr.setText(msg.value.from);
holder.itemSwapId.setText(msg.value.swap_id);
}
}
private void onBindIncentive(RecyclerView.ViewHolder viewHolder, int position) {
final TxIncentiveHolder holder = (TxIncentiveHolder)viewHolder;
holder.itemMsgImg.setColorFilter(WDp.getChainColor(getBaseContext(), mBaseChain), android.graphics.PorterDuff.Mode.SRC_IN);
if (mBaseChain.equals(KAVA_MAIN) || mBaseChain.equals(KAVA_TEST)) {
final Msg msg = mResTxInfo.getMsg(position - 1);
holder.itemSender.setText(msg.value.sender);
holder.itemDenom.setText(msg.value.collateral_type);
holder.itemMultiplier.setText(msg.value.multiplier_name);
Coin incentiveCoin = mResTxInfo.simpleIncentive(position - 1);
try {
if (!TextUtils.isEmpty(incentiveCoin.denom)) {
WDp.showCoinDp(getBaseContext(), incentiveCoin, holder.itemIncentiveDenom, holder.itemIncentiveAmount, mBaseChain);
} else {
holder.itemIncentiveDenom.setText("");
holder.itemIncentiveAmount.setText("");
}
} catch (Exception e) {
holder.itemIncentiveDenom.setText("");
holder.itemIncentiveAmount.setText("");
}
}
}
private void onBindHarvestDeposit(RecyclerView.ViewHolder viewHolder, int position) {
final TxHarvestDepositHolder holder = (TxHarvestDepositHolder)viewHolder;
holder.itemMsgImg.setColorFilter(WDp.getChainColor(getBaseContext(), mBaseChain), android.graphics.PorterDuff.Mode.SRC_IN);
final Msg msg = mResTxInfo.getMsg(position - 1);
holder.itemDepositor.setText(msg.value.depositor);
holder.itemDepositType.setText(msg.value.deposit_type);
WDp.showCoinDp(getBaseContext(), msg.value.getCoins().get(0), holder.itemDepositAmountDenom, holder.itemDepositAmount, mBaseChain);
}
private void onBindHarvestWithdraw(RecyclerView.ViewHolder viewHolder, int position) {
final TxHarvestWithdrawHolder holder = (TxHarvestWithdrawHolder)viewHolder;
holder.itemMsgImg.setColorFilter(WDp.getChainColor(getBaseContext(), mBaseChain), android.graphics.PorterDuff.Mode.SRC_IN);
final Msg msg = mResTxInfo.getMsg(position - 1);
holder.itemDepositor.setText(msg.value.depositor);
holder.itemDepositType.setText(msg.value.deposit_type);
WDp.showCoinDp(getBaseContext(), msg.value.getCoins().get(0), holder.itemWithdrawAmountDenom, holder.itemWithdrawAmount, mBaseChain);
}
private void onBindHarvestReward(RecyclerView.ViewHolder viewHolder, int position) {
final TxHarvestClaimHolder holder = (TxHarvestClaimHolder)viewHolder;
holder.itemMsgImg.setColorFilter(WDp.getChainColor(getBaseContext(), mBaseChain), android.graphics.PorterDuff.Mode.SRC_IN);
final Msg msg = mResTxInfo.getMsg(position - 1);
holder.itemSender.setText(msg.value.sender);
holder.itemReceiver.setText(msg.value.receiver);
holder.itemCoinType.setText(msg.value.deposit_denom);
holder.itemMultiplier.setText(msg.value.multiplier_name);
holder.itemDepositType.setText(msg.value.deposit_type);
Coin rewardCoin = mResTxInfo.simpleHarvestReward();
try {
if (!TextUtils.isEmpty(rewardCoin.denom)) {
WDp.showCoinDp(getBaseContext(), rewardCoin, holder.itemRewardAmountDenom, holder.itemRewardAmount, mBaseChain);
}
} catch (Exception e) { }
}
private void onBindOkStake(RecyclerView.ViewHolder viewHolder, int position) {
final TxOkStakeHolder holder = (TxOkStakeHolder)viewHolder;
holder.itemMsgImg.setColorFilter(WDp.getChainColor(getBaseContext(), mBaseChain), android.graphics.PorterDuff.Mode.SRC_IN);
if (mBaseChain.equals(OK_TEST)) {
final Msg msg = mResTxInfo.getMsg(position - 1);
if (msg.type.equals(OK_MSG_TYPE_DEPOSIT)) {
holder.itemMsgTitle.setText(R.string.str_deposit);
holder.itemMsgImg.setImageDrawable(getResources().getDrawable(R.drawable.deposit_ic));
} else if (msg.type.equals(OK_MSG_TYPE_WITHDRAW)) {
holder.itemMsgTitle.setText(R.string.str_withdraw);
holder.itemMsgImg.setImageDrawable(getResources().getDrawable(R.drawable.withdraw_ic));
}
holder.itemDeleagtor.setText(msg.value.delegator_address);
WDp.showCoinDp(getBaseContext(), msg.value.quantity, holder.itemAmountDenom, holder.itemAmount, mBaseChain);
}
}
private void onBindOkDirectVote(RecyclerView.ViewHolder viewHolder, int position) {
final TxOkVoteHolder holder = (TxOkVoteHolder)viewHolder;
holder.itemMsgImg.setColorFilter(WDp.getChainColor(getBaseContext(), mBaseChain), android.graphics.PorterDuff.Mode.SRC_IN);
if (mBaseChain.equals(OK_TEST)) {
final Msg msg = mResTxInfo.getMsg(position - 1);
holder.itemVoter.setText(msg.value.delegator_address);
mAllValidators.clear();
mAllValidators.addAll(getBaseDao().mTopValidators);
mAllValidators.addAll(getBaseDao().mOtherValidators);
ArrayList<String> toValAdd = msg.value.validator_addresses;
String monikers = "";
for (String valOp:toValAdd) {
for (Validator validator:mAllValidators) {
if (validator.operator_address.equals(valOp)) {
monikers = monikers + validator.description.moniker + "\n";
}
}
}
holder.itemValList.setText(monikers);
// ArrayList<String> toValAdd = msg.value.validator_addresses;
// String monikers = "";
// for (String valOp:toValAdd) {
// monikers = monikers + valOp + "\n";
// }
// WLog.w("toValAdd " + toValAdd);
}
}
private void onBindRegisterDomain(RecyclerView.ViewHolder viewHolder, int position) {
final TxRegisterDomainHolder holder = (TxRegisterDomainHolder)viewHolder;
if (mBaseChain.equals(IOV_MAIN) || mBaseChain.equals(IOV_TEST) ) {
final Msg msg = mResTxInfo.getMsg(position - 1);
holder.itemDomain.setText("*" + msg.value.domain);
holder.itemAdmin.setText( msg.value.admin);
holder.itemType.setText( msg.value.type);
BigDecimal starnameFee = getBaseDao().mStarNameFee.getDomainFee(msg.value.domain.trim(), msg.value.type);
holder.itemStarnameFee.setText(WDp.getDpAmount2(getBaseContext(), starnameFee, 6, 6));
}
}
private void onBindRegisterAccount(RecyclerView.ViewHolder viewHolder, int position) {
final TxRegisterAccountHolder holder = (TxRegisterAccountHolder)viewHolder;
if (mBaseChain.equals(IOV_MAIN) || mBaseChain.equals(IOV_TEST) ) {
final Msg msg = mResTxInfo.getMsg(position - 1);
holder.itemStarname.setText(msg.value.name + "*" + msg.value.domain);
holder.itemOwner.setText( msg.value.owner);
holder.itemRegister.setText( msg.value.registerer);
BigDecimal starnameFee = getBaseDao().mStarNameFee.getAccountFee(true);
holder.itemStarnameFee.setText(WDp.getDpAmount2(getBaseContext(), starnameFee, 6, 6));
ArrayList<StarNameResource> resources = msg.value.resources;
if (resources != null && resources.size() > 0) {
holder.itemResBar.setVisibility(View.VISIBLE);
holder.itemResLayer.setVisibility(View.VISIBLE);
holder.itemAddressCnt.setText("" + resources.size());
for(int i = 0; i < resources.size(); i++) {
holder.itemAddessLayer[i].setVisibility(View.VISIBLE);
holder.itemChain[i].setText(WUtil.getStarNameChainName(resources.get(i)));
holder.itemAddess[i].setText(resources.get(i).resource);
holder.itemAddressImg[i].setImageDrawable(WUtil.getStarNameChainImg(getBaseContext(), resources.get(i)));
}
}
}
}
private void onBindDeleteDomain(RecyclerView.ViewHolder viewHolder, int position) {
final TxDeleteDomainHolder holder = (TxDeleteDomainHolder)viewHolder;
if (mBaseChain.equals(IOV_MAIN) || mBaseChain.equals(IOV_TEST) ) {
final Msg msg = mResTxInfo.getMsg(position - 1);
holder.itemDomain.setText("*" + msg.value.domain);
holder.itemOwner.setText( msg.value.owner);
}
}
private void onBindDeleteAccount(RecyclerView.ViewHolder viewHolder, int position) {
final TxDeleteAccountHolder holder = (TxDeleteAccountHolder)viewHolder;
if (mBaseChain.equals(IOV_MAIN) || mBaseChain.equals(IOV_TEST) ) {
final Msg msg = mResTxInfo.getMsg(position - 1);
holder.itemAccount.setText(msg.value.name + "*" + msg.value.domain);
holder.itemOwner.setText( msg.value.owner);
}
}
private void onBindReplaceResource(RecyclerView.ViewHolder viewHolder, int position) {
final TxReplaceResourceHolder holder = (TxReplaceResourceHolder)viewHolder;
if (mBaseChain.equals(IOV_MAIN) || mBaseChain.equals(IOV_TEST) ) {
final Msg msg = mResTxInfo.getMsg(position - 1);
holder.itemStarname.setText(msg.value.name + "*" + msg.value.domain);
BigDecimal starnameFee = getBaseDao().mStarNameFee.getReplaceFee();
holder.itemStarnameFee.setText(WDp.getDpAmount2(getBaseContext(), starnameFee, 6, 6));
ArrayList<StarNameResource> resources = msg.value.new_resources;
if (resources == null || resources.size() == 0) {
holder.itemAddressCnt.setText("0");
} else {
holder.itemAddressCnt.setText("" + resources.size());
for(int i = 0; i < resources.size(); i++) {
holder.itemAddessLayer[i].setVisibility(View.VISIBLE);
holder.itemChain[i].setText(WUtil.getStarNameChainName(resources.get(i)));
holder.itemAddess[i].setText(resources.get(i).resource);
holder.itemAddressImg[i].setImageDrawable(WUtil.getStarNameChainImg(getBaseContext(), resources.get(i)));
}
}
}
}
private void onBindRenewStarName(RecyclerView.ViewHolder viewHolder, int position) {
final TxRenewStarNameHolder holder = (TxRenewStarNameHolder)viewHolder;
if (mBaseChain.equals(IOV_MAIN) || mBaseChain.equals(IOV_TEST) ) {
final Msg msg = mResTxInfo.getMsg(position - 1);
if (msg.type.equals(IOV_MSG_TYPE_RENEW_DOMAIN)) {
holder.itemMsgImg.setImageDrawable(getResources().getDrawable(R.drawable.ic_msgs_renewaccount));
holder.itemMsgTitle.setText(getString(R.string.tx_starname_renew_domain));
} else if (msg.type.equals(IOV_MSG_TYPE_RENEW_ACCOUNT)) {
holder.itemMsgImg.setImageDrawable(getResources().getDrawable(R.drawable.ic_msgs_renewdomain));
holder.itemMsgTitle.setText(getString(R.string.tx_starname_renew_account));
}
String starName = "";
if (!TextUtils.isEmpty(msg.value.name)) {
starName = msg.value.name + "*" + msg.value.domain;
} else {
starName = "*" + msg.value.domain;
}
holder.itemStarname.setText(starName);
holder.itemSigner.setText(msg.value.signer);
}
}
private void onBindUnKnown(RecyclerView.ViewHolder viewHolder, int position) {
final TxUnKnownHolder holder = (TxUnKnownHolder)viewHolder;
holder.itemUnknownImg.setColorFilter(WDp.getChainColor(getBaseContext(), mBaseChain), android.graphics.PorterDuff.Mode.SRC_IN);
}
public class TxCommonHolder extends RecyclerView.ViewHolder {
ImageView itemStatusImg;
TextView itemStatusTxt, itemFailTxt, itemHash, itemHeight, itemMsgCnt, itemGas,
itemTime, itemTimeGap, itemMemo, itemFee, itemFeeDenom , itemFeeUsed, itemFeeUsedDenom,
itemFeeLimit, itemFeeLimitDenom;
RelativeLayout itemFeeLayer, itemFeeUsedLayer, itemFeeLimitLayer;
ImageView itemBtnHashLink;
public TxCommonHolder(@NonNull View itemView) {
super(itemView);
itemStatusImg = itemView.findViewById(R.id.tx_status_img);
itemStatusTxt = itemView.findViewById(R.id.tx_status);
itemFailTxt = itemView.findViewById(R.id.tx_fail_msg);
itemHeight = itemView.findViewById(R.id.tx_block_height);
itemMsgCnt = itemView.findViewById(R.id.tx_msg_cnt);
itemGas = itemView.findViewById(R.id.tx_gas_info);
itemTime = itemView.findViewById(R.id.tx_block_time);
itemTimeGap = itemView.findViewById(R.id.tx_block_time_gap);
itemHash = itemView.findViewById(R.id.tx_hash);
itemMemo = itemView.findViewById(R.id.str_tx_memo);
itemBtnHashLink = itemView.findViewById(R.id.tx_hash_link);
itemFeeLayer = itemView.findViewById(R.id.tx_fee_layer);
itemFee = itemView.findViewById(R.id.tx_fee);
itemFeeDenom = itemView.findViewById(R.id.tx_fee_symbol);
itemFeeUsedLayer = itemView.findViewById(R.id.tx_fee_used_layer);
itemFeeUsed = itemView.findViewById(R.id.tx_used_fee);
itemFeeUsedDenom = itemView.findViewById(R.id.tx_fee_used_symbol);
itemFeeLimitLayer = itemView.findViewById(R.id.tx_fee_limit_layer);
itemFeeLimit = itemView.findViewById(R.id.tx_limit_fee);
itemFeeLimitDenom = itemView.findViewById(R.id.tx_fee_limit_symbol);
}
}
public class TxTransferHolder extends RecyclerView.ViewHolder {
ImageView itemSendReceiveImg;
TextView itemSendRecieveTv;
TextView itemFromAddress, itemToAddress;
RelativeLayout itemSingleCoinLayer;
TextView itemAmount, itemAmountDenom;
LinearLayout itemMultiCoinLayer;
RelativeLayout itemAmountLayer0, itemAmountLayer1, itemAmountLayer2, itemAmountLayer3, itemAmountLayer4;
TextView itemAmount0, itemAmountDenom0, itemAmount1, itemAmountDenom1, itemAmount2, itemAmountDenom2,
itemAmount3, itemAmountDenom3, itemAmount4, itemAmountDenom4;
public TxTransferHolder(@NonNull View itemView) {
super(itemView);
itemSendReceiveImg = itemView.findViewById(R.id.tx_send_icon);
itemSendRecieveTv = itemView.findViewById(R.id.tx_send_text);
itemFromAddress = itemView.findViewById(R.id.tx_send_from_address);
itemToAddress = itemView.findViewById(R.id.tx_send_to_address);
itemSingleCoinLayer = itemView.findViewById(R.id.tx_send_single_coin_layer);
itemAmount = itemView.findViewById(R.id.tx_transfer_amount);
itemAmountDenom = itemView.findViewById(R.id.tx_transfer_amount_symbol);
itemMultiCoinLayer = itemView.findViewById(R.id.tx_send_multi_coin_layer);
itemAmountLayer0 = itemView.findViewById(R.id.tx_transfer_amount_layer0);
itemAmountLayer1 = itemView.findViewById(R.id.tx_transfer_amount_layer1);
itemAmountLayer2 = itemView.findViewById(R.id.tx_transfer_amount_layer2);
itemAmountLayer3 = itemView.findViewById(R.id.tx_transfer_amount_layer3);
itemAmountLayer4 = itemView.findViewById(R.id.tx_transfer_amount_layer4);
itemAmount0 = itemView.findViewById(R.id.tx_transfer_amount0);
itemAmount1 = itemView.findViewById(R.id.tx_transfer_amount1);
itemAmount2 = itemView.findViewById(R.id.tx_transfer_amount2);
itemAmount3 = itemView.findViewById(R.id.tx_transfer_amount3);
itemAmount4 = itemView.findViewById(R.id.tx_transfer_amount4);
itemAmountDenom0 = itemView.findViewById(R.id.tx_transfer_amount_symbol0);
itemAmountDenom1 = itemView.findViewById(R.id.tx_transfer_amount_symbol1);
itemAmountDenom2 = itemView.findViewById(R.id.tx_transfer_amount_symbol2);
itemAmountDenom3 = itemView.findViewById(R.id.tx_transfer_amount_symbol3);
itemAmountDenom4 = itemView.findViewById(R.id.tx_transfer_amount_symbol4);
}
}
public class TxMultiSendHolder extends RecyclerView.ViewHolder {
ImageView itemSendReceiveImg;
TextView itemSendRecieveTv;
RelativeLayout itemInputLayer0, itemInputLayer1, itemInputLayer2,itemInputLayer3;
TextView itemInputAddress0, itemInputAddress1, itemInputAddress2, itemInputAddress3;
TextView itemInputAmount0, itemInputAmount1, itemInputAmount2, itemInputAmount3;
TextView itemInputDenom0, itemInputDenom1, itemInputDenom2, itemInputDenom3;
RelativeLayout itemOutputLayer0, itemOutputLayer1, itemOutputLayer2,itemOutputLayer3;
TextView itemOutputAddress0, itemOutputAddress1, itemOutputAddress2, itemOutputAddress3;
TextView itemOutputAmount0, itemOutputAmount1, itemOutputAmount2, itemOutputAmount3;
TextView itemOutputDenom0, itemOutputDenom1, itemOutputDenom2, itemOutputDenom3;
public TxMultiSendHolder(@NonNull View itemView) {
super(itemView);
itemSendReceiveImg = itemView.findViewById(R.id.tx_send_icon);
itemSendRecieveTv = itemView.findViewById(R.id.tx_send_text);
itemInputLayer0 = itemView.findViewById(R.id.tx_send_from0);
itemInputLayer1 = itemView.findViewById(R.id.tx_send_from1);
itemInputLayer2 = itemView.findViewById(R.id.tx_send_from2);
itemInputLayer3 = itemView.findViewById(R.id.tx_send_from3);
itemInputAddress0 = itemView.findViewById(R.id.tx_send_from0_address);
itemInputAddress1 = itemView.findViewById(R.id.tx_send_from1_address);
itemInputAddress2 = itemView.findViewById(R.id.tx_send_from2_address);
itemInputAddress3 = itemView.findViewById(R.id.tx_send_from3_address);
itemInputAmount0 = itemView.findViewById(R.id.tx_send_from0_amount);
itemInputAmount1 = itemView.findViewById(R.id.tx_send_from1_amount);
itemInputAmount2 = itemView.findViewById(R.id.tx_send_from2_amount);
itemInputAmount3 = itemView.findViewById(R.id.tx_send_from3_amount);
itemInputDenom0 = itemView.findViewById(R.id.tx_send_from0_symbol);
itemInputDenom1 = itemView.findViewById(R.id.tx_send_from1_symbol);
itemInputDenom2 = itemView.findViewById(R.id.tx_send_from2_symbol);
itemInputDenom3 = itemView.findViewById(R.id.tx_send_from3_symbol);
itemOutputLayer0 = itemView.findViewById(R.id.tx_send_to0);
itemOutputLayer1 = itemView.findViewById(R.id.tx_send_to1);
itemOutputLayer2 = itemView.findViewById(R.id.tx_send_to2);
itemOutputLayer3 = itemView.findViewById(R.id.tx_send_to3);
itemOutputAddress0 = itemView.findViewById(R.id.tx_send_to0_address);
itemOutputAddress1 = itemView.findViewById(R.id.tx_send_to1_address);
itemOutputAddress2 = itemView.findViewById(R.id.tx_send_to2_address);
itemOutputAddress3 = itemView.findViewById(R.id.tx_send_to3_address);
itemOutputAmount0 = itemView.findViewById(R.id.tx_send_to0_amount);
itemOutputAmount1 = itemView.findViewById(R.id.tx_send_to1_amount);
itemOutputAmount2 = itemView.findViewById(R.id.tx_send_to2_amount);
itemOutputAmount3 = itemView.findViewById(R.id.tx_send_to3_amount);
itemOutputDenom0 = itemView.findViewById(R.id.tx_send_to0_symbol);
itemOutputDenom1 = itemView.findViewById(R.id.tx_send_to1_symbol);
itemOutputDenom2 = itemView.findViewById(R.id.tx_send_to2_symbol);
itemOutputDenom3 = itemView.findViewById(R.id.tx_send_to3_symbol);
}
}
public class TxDelegateHolder extends RecyclerView.ViewHolder {
ImageView itemDelegateImg;
TextView itemDelegateTitle;
TextView itemDelegator, itemValidator, itemMoniker, itemDelegateAmount, itemDelegateAmountDenom,
itemAutoRewardAmount, itemAutoRewardAmountDenom;
RelativeLayout itemAutoRewardLayer;
public TxDelegateHolder(@NonNull View itemView) {
super(itemView);
itemDelegateImg = itemView.findViewById(R.id.tx_delegate_icon);
itemDelegateTitle = itemView.findViewById(R.id.tx_delegate_text);
itemDelegator = itemView.findViewById(R.id.tx_delegate_delegator);
itemValidator = itemView.findViewById(R.id.tx_delegate_validator);
itemMoniker = itemView.findViewById(R.id.tx_delegate_moniker);
itemDelegateAmount = itemView.findViewById(R.id.tx_delegate_amount);
itemDelegateAmountDenom = itemView.findViewById(R.id.tx_delegate_amount_symbol);
itemAutoRewardAmount = itemView.findViewById(R.id.tx_auto_claimed);
itemAutoRewardAmountDenom = itemView.findViewById(R.id.tx_auto_claimed_symbol);
itemAutoRewardLayer = itemView.findViewById(R.id.tx_delegate_auto_reward);
}
}
public class TxUndelegateHolder extends RecyclerView.ViewHolder {
ImageView itemUndelegateImg;
TextView itemUndelegateTitle;
TextView itemUnDelegator, itemValidator, itemMoniker, itemUndelegateAmount, itemUnDelegateAmountDenom,
itemAutoRewardAmount, itemAutoRewardAmountDenom;
RelativeLayout itemAutoRewardLayer;
public TxUndelegateHolder(@NonNull View itemView) {
super(itemView);
itemUndelegateImg = itemView.findViewById(R.id.tx_undelegate_icon);
itemUndelegateTitle = itemView.findViewById(R.id.tx_undelegate_text);
itemUnDelegator = itemView.findViewById(R.id.tx_undelegate_undelegator);
itemValidator = itemView.findViewById(R.id.tx_undelegate_validator);
itemMoniker = itemView.findViewById(R.id.tx_undelegate_moniker);
itemUndelegateAmount = itemView.findViewById(R.id.tx_undelegate_amount);
itemUnDelegateAmountDenom = itemView.findViewById(R.id.tx_undelegate_amount_symbol);
itemAutoRewardAmount = itemView.findViewById(R.id.tx_auto_claimed);
itemAutoRewardAmountDenom = itemView.findViewById(R.id.tx_auto_claimed_symbol);
itemAutoRewardLayer = itemView.findViewById(R.id.tx_undelegate_auto_reward);
}
}
public class TxRedelegateHolder extends RecyclerView.ViewHolder {
ImageView itemRedelegateImg;
TextView itemRedelegateTitle;
TextView itemReDelegator, itemFromValidator, itemFromMoniker, itemToValidator, itemToMoniker, itemRedelegateAmount, itemReDelegateAmountDenom,
itemAutoRewardAmount, itemAutoRewardAmountDenom;
RelativeLayout itemAutoRewardLayer;
public TxRedelegateHolder(@NonNull View itemView) {
super(itemView);
itemRedelegateImg = itemView.findViewById(R.id.tx_redelegate_icon);
itemRedelegateTitle = itemView.findViewById(R.id.tx_undelegate_text);
itemReDelegator = itemView.findViewById(R.id.tx_redelegate_redelegator);
itemFromValidator = itemView.findViewById(R.id.tx_redelegate_from_validator);
itemFromMoniker = itemView.findViewById(R.id.tx_redelegate_from_moniker);
itemToValidator = itemView.findViewById(R.id.tx_redelegate_to_validator);
itemToMoniker = itemView.findViewById(R.id.tx_redelegate_to_moniker);
itemRedelegateAmount = itemView.findViewById(R.id.tx_redelegate_amount);
itemReDelegateAmountDenom = itemView.findViewById(R.id.tx_redelegate_amount_symbol);
itemAutoRewardAmount = itemView.findViewById(R.id.tx_auto_claimed);
itemAutoRewardAmountDenom = itemView.findViewById(R.id.tx_auto_claimed_symbol);
itemAutoRewardLayer = itemView.findViewById(R.id.tx_redelegate_auto_reward);
}
}
public class TxRewardHolder extends RecyclerView.ViewHolder {
ImageView itemRewardImg;
TextView itemRewardTitle;
TextView itemDelegator, itemValidator, itemMoniker, itemRewardAmount, itemRewardAmountDenom;
public TxRewardHolder(@NonNull View itemView) {
super(itemView);
itemRewardImg = itemView.findViewById(R.id.tx_reward_icon);
itemRewardTitle = itemView.findViewById(R.id.tx_reward_text);
itemDelegator = itemView.findViewById(R.id.tx_reward_delegator);
itemValidator = itemView.findViewById(R.id.tx_reward_validator);
itemMoniker = itemView.findViewById(R.id.tx_reward_moniker);
itemRewardAmount = itemView.findViewById(R.id.tx_reward_amount);
itemRewardAmountDenom = itemView.findViewById(R.id.tx_reward_amount_symbol);
}
}
public class TxRewardAllHolder extends RecyclerView.ViewHolder {
ImageView itemMsgImg;
TextView itemDelegator;
TextView itemRewardValidatorCnt;
TextView itemRewardValidator0, itemRewardValidator1, itemRewardValidator2, itemRewardValidator3, itemRewardValidator4, itemRewardValidator5, itemRewardValidator6, itemRewardValidator7;
TextView itemRewardMoniker0, itemRewardMoniker1, itemRewardMoniker2, itemRewardMoniker3, itemRewardMoniker4, itemRewardMoniker5, itemRewardMoniker6, itemRewardMoniker7;
TextView itemRewardAllAmount, itemRewardAllAmountDenom;
public TxRewardAllHolder(@NonNull View itemView) {
super(itemView);
itemMsgImg = itemView.findViewById(R.id.tx_msg_icon);
itemDelegator = itemView.findViewById(R.id.tx_reward_all_delegator);
itemRewardValidatorCnt = itemView.findViewById(R.id.validator_count);
itemRewardValidator0 = itemView.findViewById(R.id.tx_reward_validator0);
itemRewardValidator1 = itemView.findViewById(R.id.tx_reward_validator1);
itemRewardValidator2 = itemView.findViewById(R.id.tx_reward_validator2);
itemRewardValidator3 = itemView.findViewById(R.id.tx_reward_validator3);
itemRewardValidator4 = itemView.findViewById(R.id.tx_reward_validator4);
itemRewardValidator5 = itemView.findViewById(R.id.tx_reward_validator5);
itemRewardValidator6 = itemView.findViewById(R.id.tx_reward_validator6);
itemRewardValidator7 = itemView.findViewById(R.id.tx_reward_validator7);
itemRewardMoniker0 = itemView.findViewById(R.id.tx_reward_moniker0);
itemRewardMoniker1 = itemView.findViewById(R.id.tx_reward_moniker1);
itemRewardMoniker2 = itemView.findViewById(R.id.tx_reward_moniker2);
itemRewardMoniker3 = itemView.findViewById(R.id.tx_reward_moniker3);
itemRewardMoniker4 = itemView.findViewById(R.id.tx_reward_moniker4);
itemRewardMoniker5 = itemView.findViewById(R.id.tx_reward_moniker5);
itemRewardMoniker6 = itemView.findViewById(R.id.tx_reward_moniker6);
itemRewardMoniker7 = itemView.findViewById(R.id.tx_reward_moniker7);
itemRewardAllAmount = itemView.findViewById(R.id.tx_reward_all_sum_amount);
itemRewardAllAmountDenom = itemView.findViewById(R.id.tx_reward_all_sum_symbol);
}
}
public class TxAddressHolder extends RecyclerView.ViewHolder {
ImageView itemAddressImg;
TextView itemAddressTitle;
TextView itemDelegator, itemWithdrawAddress;
public TxAddressHolder(@NonNull View itemView) {
super(itemView);
itemAddressImg = itemView.findViewById(R.id.tx_address_icon);
itemAddressTitle = itemView.findViewById(R.id.tx_address_text);
itemDelegator = itemView.findViewById(R.id.tx_address_delegator);
itemWithdrawAddress = itemView.findViewById(R.id.tx_address_withdraw);
}
}
public class TxVoteHolder extends RecyclerView.ViewHolder {
ImageView itemVoteImg;
TextView itemVoteTitle;
TextView itemDelegator, itemProposalId, itemOpinion;
public TxVoteHolder(@NonNull View itemView) {
super(itemView);
itemVoteImg = itemView.findViewById(R.id.tx_vote_icon);
itemVoteTitle = itemView.findViewById(R.id.tx_vote_text);
itemDelegator = itemView.findViewById(R.id.tx_vote_voter);
itemProposalId = itemView.findViewById(R.id.tx_vote_proposal_id);
itemOpinion = itemView.findViewById(R.id.tx_vote_proposal_opinion);
}
}
public class TxCommissionHolder extends RecyclerView.ViewHolder {
ImageView itemCommissionImg;
TextView itemCommissionTitle;
TextView itemCommissionValidator, itemCommissionValidatorMoniker, itemCommissionAmount, itemCommissionAmountDenom;
public TxCommissionHolder(@NonNull View itemView) {
super(itemView);
itemCommissionImg = itemView.findViewById(R.id.tx_commission_icon);
itemCommissionTitle = itemView.findViewById(R.id.tx_commission_text);
itemCommissionValidator = itemView.findViewById(R.id.tx_commission_validator);
itemCommissionValidatorMoniker = itemView.findViewById(R.id.tx_commission_moniker);
itemCommissionAmount = itemView.findViewById(R.id.tx_commission_amount);
itemCommissionAmountDenom = itemView.findViewById(R.id.tx_commission_amount_symbol);
}
}
public class TxPostPriceHolder extends RecyclerView.ViewHolder {
ImageView itemMsgImg;
TextView itemMsgTitle;
TextView itemPoster, itemMakerId, itemPostPrice, itemTime;
public TxPostPriceHolder(@NonNull View itemView) {
super(itemView);
itemMsgImg = itemView.findViewById(R.id.tx_msg_icon);
itemMsgTitle = itemView.findViewById(R.id.tx_msg_text);
itemPoster = itemView.findViewById(R.id.tx_price_poster);
itemMakerId = itemView.findViewById(R.id.tx_market_id);
itemPostPrice = itemView.findViewById(R.id.tx_post_price);
itemTime = itemView.findViewById(R.id.tx_validity_time);
}
}
public class TxCreateCdpHolder extends RecyclerView.ViewHolder {
ImageView itemMsgImg;
TextView itemMsgTitle;
TextView itemSender, itemCollateralAmount, itemCollateralDenom,
itemPrincipalAmount, itemPrincipalDenom;
public TxCreateCdpHolder(@NonNull View itemView) {
super(itemView);
itemMsgImg = itemView.findViewById(R.id.tx_msg_icon);
itemMsgTitle = itemView.findViewById(R.id.tx_msg_text);
itemSender = itemView.findViewById(R.id.tx_cdp_sender);
itemCollateralAmount = itemView.findViewById(R.id.tx_collateral_amount);
itemCollateralDenom = itemView.findViewById(R.id.tx_collateral_symbol);
itemPrincipalAmount = itemView.findViewById(R.id.tx_principal_amount);
itemPrincipalDenom = itemView.findViewById(R.id.tx_principal_symbol);
}
}
public class TxDepositCdpHolder extends RecyclerView.ViewHolder {
ImageView itemMsgImg;
TextView itemMsgTitle;
TextView itemOwner, itemDepositor, itemCollateralAmount, itemCollateralDenom;
public TxDepositCdpHolder(@NonNull View itemView) {
super(itemView);
itemMsgImg = itemView.findViewById(R.id.tx_msg_icon);
itemMsgTitle = itemView.findViewById(R.id.tx_msg_text);
itemOwner = itemView.findViewById(R.id.tx_cdp_owner);
itemDepositor = itemView.findViewById(R.id.tx_cdp_depositor);
itemCollateralAmount = itemView.findViewById(R.id.tx_collateral_amount);
itemCollateralDenom = itemView.findViewById(R.id.tx_collateral_symbol);
}
}
public class TxWithdrawCdpHolder extends RecyclerView.ViewHolder {
ImageView itemMsgImg;
TextView itemMsgTitle;
TextView itemOwner, itemDepositor, itemCollateralAmount, itemCollateralDenom;
public TxWithdrawCdpHolder(@NonNull View itemView) {
super(itemView);
itemMsgImg = itemView.findViewById(R.id.tx_msg_icon);
itemMsgTitle = itemView.findViewById(R.id.tx_msg_text);
itemOwner = itemView.findViewById(R.id.tx_cdp_owner);
itemDepositor = itemView.findViewById(R.id.tx_cdp_depositor);
itemCollateralAmount = itemView.findViewById(R.id.tx_collateral_amount);
itemCollateralDenom = itemView.findViewById(R.id.tx_collateral_symbol);
}
}
public class TxDrawDebtCdpHolder extends RecyclerView.ViewHolder {
ImageView itemMsgImg;
TextView itemMsgTitle;
TextView itemSender, itemCdpDenom, itemPrincipalAmount, itemPrincipalDenom;
public TxDrawDebtCdpHolder(@NonNull View itemView) {
super(itemView);
itemMsgImg = itemView.findViewById(R.id.tx_msg_icon);
itemMsgTitle = itemView.findViewById(R.id.tx_msg_text);
itemSender = itemView.findViewById(R.id.tx_cdp_sender);
itemCdpDenom = itemView.findViewById(R.id.tx_cdp_denom);
itemPrincipalAmount = itemView.findViewById(R.id.tx_principal_amount);
itemPrincipalDenom = itemView.findViewById(R.id.tx_principal_symbol);
}
}
public class TxRepayDebtCdpHolder extends RecyclerView.ViewHolder {
ImageView itemMsgImg;
TextView itemMsgTitle;
TextView itemSender, itemCdpDenom, itemPaymentAmount, itemPaymentDenom;
public TxRepayDebtCdpHolder(@NonNull View itemView) {
super(itemView);
itemMsgImg = itemView.findViewById(R.id.tx_msg_icon);
itemMsgTitle = itemView.findViewById(R.id.tx_msg_text);
itemSender = itemView.findViewById(R.id.tx_cdp_sender);
itemCdpDenom = itemView.findViewById(R.id.tx_cdp_denom);
itemPaymentAmount = itemView.findViewById(R.id.tx_payment_amount);
itemPaymentDenom = itemView.findViewById(R.id.tx_payment_symbol);
}
}
public class TxCreateHtlcHolder extends RecyclerView.ViewHolder {
ImageView itemMsgImg;
TextView itemMsgTitle;
LinearLayout itemExpectedLayer;
TextView itemSendAmount, itemSendDenom, itemSender, itemRecipient, itemRandomHash, itemExpectIncome, itemStatus;
public TxCreateHtlcHolder(@NonNull View itemView) {
super(itemView);
itemMsgImg = itemView.findViewById(R.id.tx_msg_icon);
itemMsgTitle = itemView.findViewById(R.id.tx_msg_text);
itemExpectedLayer = itemView.findViewById(R.id.expected_layer);
itemSendAmount = itemView.findViewById(R.id.send_amount);
itemSendDenom = itemView.findViewById(R.id.send_amount_denom);
itemSender = itemView.findViewById(R.id.sender_addr);
itemRecipient = itemView.findViewById(R.id.recipient_addr);
itemRandomHash = itemView.findViewById(R.id.random_hash);
itemExpectIncome = itemView.findViewById(R.id.expected_income);
itemStatus = itemView.findViewById(R.id.status_txt);
}
}
public class TxClaimHtlcHolder extends RecyclerView.ViewHolder {
ImageView itemMsgImg;
TextView itemMsgTitle;
RelativeLayout itemAmountLayer;
TextView itemReceiveAmount, itemReceiveDenom, itemClaimer, itemRandomNumber, itemSwapId;
public TxClaimHtlcHolder(@NonNull View itemView) {
super(itemView);
itemMsgImg = itemView.findViewById(R.id.tx_msg_icon);
itemMsgTitle = itemView.findViewById(R.id.tx_msg_text);
itemAmountLayer = itemView.findViewById(R.id.claim_amount_layer);
itemReceiveAmount = itemView.findViewById(R.id.claim_amount);
itemReceiveDenom = itemView.findViewById(R.id.claim_amount_denom);
itemClaimer = itemView.findViewById(R.id.claimer_addr);
itemRandomNumber = itemView.findViewById(R.id.claim_random_number);
itemSwapId = itemView.findViewById(R.id.claim_swap_id);
}
}
public class TxRefundHtlcHolder extends RecyclerView.ViewHolder {
ImageView itemMsgImg;
TextView itemMsgTitle;
RelativeLayout itemAmountLayer;
TextView itemRefundAmount, itemRefundDenom, itemFromAddr, itemSwapId;
public TxRefundHtlcHolder(@NonNull View itemView) {
super(itemView);
itemMsgImg = itemView.findViewById(R.id.tx_msg_icon);
itemMsgTitle = itemView.findViewById(R.id.tx_msg_text);
itemAmountLayer = itemView.findViewById(R.id.refund_amount_layer);
itemRefundAmount = itemView.findViewById(R.id.refund_amount);
itemRefundDenom = itemView.findViewById(R.id.refund_amount_denom);
itemFromAddr = itemView.findViewById(R.id.refund_addr);
itemSwapId = itemView.findViewById(R.id.refund_swap_id);
}
}
public class TxIncentiveHolder extends RecyclerView.ViewHolder {
ImageView itemMsgImg;
TextView itemMsgTitle;
TextView itemIncentiveAmount, itemIncentiveDenom, itemSender, itemDenom, itemMultiplier;
public TxIncentiveHolder(@NonNull View itemView) {
super(itemView);
itemMsgImg = itemView.findViewById(R.id.tx_msg_icon);
itemMsgTitle = itemView.findViewById(R.id.tx_msg_text);
itemIncentiveAmount = itemView.findViewById(R.id.tx_incentive_amount);
itemIncentiveDenom = itemView.findViewById(R.id.tx_incentive_symbol);
itemSender = itemView.findViewById(R.id.tx_incentive_sender);
itemDenom = itemView.findViewById(R.id.tx_incentive_denom);
itemMultiplier = itemView.findViewById(R.id.tx_multiplier_name);
}
}
public class TxHarvestDepositHolder extends RecyclerView.ViewHolder {
ImageView itemMsgImg;
TextView itemMsgTitle;
TextView itemDepositor, itemDepositType, itemDepositAmount, itemDepositAmountDenom;
public TxHarvestDepositHolder(@NonNull View itemView) {
super(itemView);
itemMsgImg = itemView.findViewById(R.id.tx_msg_icon);
itemMsgTitle = itemView.findViewById(R.id.tx_msg_text);
itemDepositor = itemView.findViewById(R.id.tx_depositor);
itemDepositType = itemView.findViewById(R.id.tx_deposit_type);
itemDepositAmount = itemView.findViewById(R.id.tx_deposit_amount);
itemDepositAmountDenom = itemView.findViewById(R.id.tx_deposit_symbol);
}
}
public class TxHarvestWithdrawHolder extends RecyclerView.ViewHolder {
ImageView itemMsgImg;
TextView itemMsgTitle;
TextView itemDepositor, itemDepositType, itemWithdrawAmount, itemWithdrawAmountDenom;
public TxHarvestWithdrawHolder(@NonNull View itemView) {
super(itemView);
itemMsgImg = itemView.findViewById(R.id.tx_msg_icon);
itemMsgTitle = itemView.findViewById(R.id.tx_msg_text);
itemDepositor = itemView.findViewById(R.id.tx_depositor);
itemDepositType = itemView.findViewById(R.id.tx_deposit_type);
itemWithdrawAmount = itemView.findViewById(R.id.tx_withdraw_amount);
itemWithdrawAmountDenom = itemView.findViewById(R.id.tx_withdraw_symbol);
}
}
public class TxHarvestClaimHolder extends RecyclerView.ViewHolder {
ImageView itemMsgImg;
TextView itemMsgTitle;
TextView itemSender, itemReceiver, itemCoinType, itemMultiplier, itemDepositType, itemRewardAmount, itemRewardAmountDenom;
;
public TxHarvestClaimHolder(@NonNull View itemView) {
super(itemView);
itemMsgImg = itemView.findViewById(R.id.tx_msg_icon);
itemMsgTitle = itemView.findViewById(R.id.tx_msg_text);
itemSender = itemView.findViewById(R.id.tx_sender);
itemReceiver = itemView.findViewById(R.id.tx_receiver);
itemCoinType = itemView.findViewById(R.id.tx_coin_type);
itemMultiplier = itemView.findViewById(R.id.tx_multiplier_name);
itemDepositType = itemView.findViewById(R.id.tx_deposit_type);
itemRewardAmount = itemView.findViewById(R.id.tx_reward_amount);
itemRewardAmountDenom = itemView.findViewById(R.id.tx_reward_symbol);
}
}
public class TxOkStakeHolder extends RecyclerView.ViewHolder {
ImageView itemMsgImg;
TextView itemMsgTitle;
TextView itemDeleagtor, itemAmountDenom, itemAmount;
public TxOkStakeHolder(@NonNull View itemView) {
super(itemView);
itemMsgImg = itemView.findViewById(R.id.tx_msg_icon);
itemMsgTitle = itemView.findViewById(R.id.tx_msg_text);
itemDeleagtor = itemView.findViewById(R.id.tx_delegator);
itemAmount = itemView.findViewById(R.id.tx_amount);
itemAmountDenom = itemView.findViewById(R.id.tx_amount_symbol);
}
}
public class TxOkVoteHolder extends RecyclerView.ViewHolder {
ImageView itemMsgImg;
TextView itemMsgTitle;
TextView itemVoter, itemValList;
public TxOkVoteHolder(@NonNull View itemView) {
super(itemView);
itemMsgImg = itemView.findViewById(R.id.tx_msg_icon);
itemMsgTitle = itemView.findViewById(R.id.tx_msg_text);
itemVoter = itemView.findViewById(R.id.tx_vote_voter);
itemValList = itemView.findViewById(R.id.tx_vote_val_list);
}
}
public class TxRegisterDomainHolder extends RecyclerView.ViewHolder {
ImageView itemMsgImg;
TextView itemMsgTitle;
TextView itemDomain, itemAdmin, itemType, itemStarnameFee;
public TxRegisterDomainHolder(@NonNull View itemView) {
super(itemView);
itemMsgImg = itemView.findViewById(R.id.tx_msg_icon);
itemMsgTitle = itemView.findViewById(R.id.tx_msg_text);
itemDomain = itemView.findViewById(R.id.tx_domain);
itemAdmin = itemView.findViewById(R.id.tx_admin_address);
itemType = itemView.findViewById(R.id.tx_domain_type);
itemStarnameFee = itemView.findViewById(R.id.tx_starname_fee_amount);
}
}
public class TxRegisterAccountHolder extends RecyclerView.ViewHolder {
ImageView itemMsgImg;
TextView itemMsgTitle;
TextView itemStarname, itemOwner, itemRegister, itemStarnameFee, itemAddressCnt;
View itemResBar;
LinearLayout itemResLayer;
LinearLayout[] itemAddessLayer = new LinearLayout[11];
ImageView[] itemAddressImg = new ImageView[11];
TextView[] itemChain = new TextView[11];
TextView[] itemAddess = new TextView[11];
public TxRegisterAccountHolder(@NonNull View itemView) {
super(itemView);
itemMsgImg = itemView.findViewById(R.id.tx_msg_icon);
itemMsgTitle = itemView.findViewById(R.id.tx_msg_text);
itemStarname = itemView.findViewById(R.id.tx_starname);
itemOwner = itemView.findViewById(R.id.tx_owner);
itemRegister = itemView.findViewById(R.id.tx_register);
itemStarnameFee = itemView.findViewById(R.id.tx_starname_fee_amount);
itemResBar = itemView.findViewById(R.id.tx_resource_bar);
itemResLayer = itemView.findViewById(R.id.tx_resource_layer);
itemAddressCnt = itemView.findViewById(R.id.tx_address_cnt);
for(int i = 0; i < itemAddessLayer.length; i++) {
itemAddessLayer[i] = itemView.findViewById(getResources().getIdentifier("tx_resource_layer_" + i , "id", getPackageName()));
itemAddressImg[i] = itemView.findViewById(getResources().getIdentifier("tx_resource_icon_" + i , "id", getPackageName()));
itemChain[i] = itemView.findViewById(getResources().getIdentifier("tx_resource_chain_" + i , "id", getPackageName()));
itemAddess[i] = itemView.findViewById(getResources().getIdentifier("tx_resource_address_" + i , "id", getPackageName()));
}
}
}
public class TxDeleteDomainHolder extends RecyclerView.ViewHolder {
ImageView itemMsgImg;
TextView itemMsgTitle;
TextView itemDomain, itemOwner;
public TxDeleteDomainHolder(@NonNull View itemView) {
super(itemView);
itemMsgImg = itemView.findViewById(R.id.tx_msg_icon);
itemMsgTitle = itemView.findViewById(R.id.tx_msg_text);
itemDomain = itemView.findViewById(R.id.tx_domain);
itemOwner = itemView.findViewById(R.id.tx_owner);
}
}
public class TxDeleteAccountHolder extends RecyclerView.ViewHolder {
ImageView itemMsgImg;
TextView itemMsgTitle;
TextView itemAccount, itemOwner;
public TxDeleteAccountHolder(@NonNull View itemView) {
super(itemView);
itemMsgImg = itemView.findViewById(R.id.tx_msg_icon);
itemMsgTitle = itemView.findViewById(R.id.tx_msg_text);
itemAccount = itemView.findViewById(R.id.tx_account);
itemOwner = itemView.findViewById(R.id.tx_owner);
}
}
public class TxReplaceResourceHolder extends RecyclerView.ViewHolder {
ImageView itemMsgImg;
TextView itemMsgTitle;
TextView itemStarname, itemStarnameFee, itemAddressCnt;
LinearLayout[] itemAddessLayer = new LinearLayout[11];
ImageView[] itemAddressImg = new ImageView[11];
TextView[] itemChain = new TextView[11];
TextView[] itemAddess = new TextView[11];
public TxReplaceResourceHolder(@NonNull View itemView) {
super(itemView);
itemMsgImg = itemView.findViewById(R.id.tx_msg_icon);
itemMsgTitle = itemView.findViewById(R.id.tx_msg_text);
itemStarname = itemView.findViewById(R.id.tx_starname);
itemStarnameFee = itemView.findViewById(R.id.tx_starname_fee_amount);
itemAddressCnt = itemView.findViewById(R.id.tx_address_cnt);
for(int i = 0; i < itemAddessLayer.length; i++) {
itemAddessLayer[i] = itemView.findViewById(getResources().getIdentifier("tx_resource_layers_" + i , "id", getPackageName()));
itemAddressImg[i] = itemView.findViewById(getResources().getIdentifier("tx_resource_icons_" + i , "id", getPackageName()));
itemChain[i] = itemView.findViewById(getResources().getIdentifier("tx_resource_chains_" + i , "id", getPackageName()));
itemAddess[i] = itemView.findViewById(getResources().getIdentifier("tx_resource_addresses_" + i , "id", getPackageName()));
}
}
}
public class TxRenewStarNameHolder extends RecyclerView.ViewHolder {
ImageView itemMsgImg;
TextView itemMsgTitle;
TextView itemStarname, itemSigner, itemStarnameFee;
public TxRenewStarNameHolder(@NonNull View itemView) {
super(itemView);
itemMsgImg = itemView.findViewById(R.id.tx_msg_icon);
itemMsgTitle = itemView.findViewById(R.id.tx_msg_text);
itemStarname = itemView.findViewById(R.id.tx_starname);
itemSigner = itemView.findViewById(R.id.tx_signer);
itemStarnameFee = itemView.findViewById(R.id.tx_starname_fee_amount);
}
}
public class TxUnKnownHolder extends RecyclerView.ViewHolder {
ImageView itemUnknownImg;
TextView itemUnknownTitle;
public TxUnKnownHolder(@NonNull View itemView) {
super(itemView);
itemUnknownImg = itemView.findViewById(R.id.tx_unknown_icon);
itemUnknownTitle = itemView.findViewById(R.id.tx_unknown_text);
}
}
}
private void onShowMoreWait() {
Dialog_MoreWait waitMore = Dialog_MoreWait.newInstance(null);
waitMore.setCancelable(false);
getSupportFragmentManager().beginTransaction().add(waitMore, "dialog").commitNowAllowingStateLoss();
}
public void onWaitMore() {
FetchCnt = 0;
onFetchTx(mTxHash);
}
private int FetchCnt = 0;
private void onFetchTx(String hash) {
WLog.w("hash "+ hash);
if (mBaseChain.equals(COSMOS_MAIN)) {
ApiClient.getCosmosChain(getBaseContext()).getSearchTx(hash).enqueue(new Callback<ResTxInfo>() {
@Override
public void onResponse(Call<ResTxInfo> call, Response<ResTxInfo> response) {
if (isFinishing()) return;
WLog.w("onFetchTx " + response.toString());
if (response.isSuccessful() && response.body() != null) {
mResTxInfo = response.body();
onUpdateView();
} else {
if (mIsSuccess && FetchCnt < 10) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
FetchCnt++;
onFetchTx(mTxHash);
}
}, 6000);
} else if (!mIsGen) {
onBackPressed();
} else {
onShowMoreWait();
}
}
}
@Override
public void onFailure(Call<ResTxInfo> call, Throwable t) {
if (IS_SHOWLOG) t.printStackTrace();
if (isFinishing()) return;
}
});
} else if (mBaseChain.equals(IRIS_MAIN)) {
ApiClient.getIrisChain(getBaseContext()).getSearchTx(hash).enqueue(new Callback<ResTxInfo>() {
@Override
public void onResponse(Call<ResTxInfo> call, Response<ResTxInfo> response) {
if (isFinishing()) return;
WLog.w("onFetchTx " + response.toString());
if (response.isSuccessful() && response.body() != null) {
mResTxInfo = response.body();
onUpdateView();
} else {
if (mIsSuccess && FetchCnt < 10) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
FetchCnt++;
onFetchTx(mTxHash);
}
}, 6000);
} else if (!mIsGen) {
onBackPressed();
} else {
onShowMoreWait();
}
}
}
@Override
public void onFailure(Call<ResTxInfo> call, Throwable t) {
if (IS_SHOWLOG) t.printStackTrace();
if (isFinishing()) return;
}
});
} else if (mBaseChain.equals(BNB_MAIN)) {
ApiClient.getBnbChain(getBaseContext()).getSearchTx(hash, "json").enqueue(new Callback<ResBnbTxInfo>() {
@Override
public void onResponse(Call<ResBnbTxInfo> call, Response<ResBnbTxInfo> response) {
if (isFinishing()) return;
WLog.w("onFetchTx " + response.toString());
if (response.isSuccessful() && response.body() != null) {
mResBnbTxInfo = response.body();
mResBnbTxInfo = response.body();
if (mResBnbTxInfo.getMsg(0).type.equals(BNB_MSG_TYPE_HTLC) &&
mAccount.address.equals(mResBnbTxInfo.getMsg(0).value.from)) {
onFetchHtlcStatus(mResBnbTxInfo.simpleSwapId());
} else {
onUpdateView();
}
} else {
if (mIsSuccess && FetchCnt < 10) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
FetchCnt++;
onFetchTx(mTxHash);
}
}, 6000);
} else if (!mIsGen) {
onBackPressed();
} else {
onShowMoreWait();
}
}
}
@Override
public void onFailure(Call<ResBnbTxInfo> call, Throwable t) {
WLog.w("BNB onFailure");
if (IS_SHOWLOG) t.printStackTrace();
if (isFinishing()) return;
}
});
} else if (mBaseChain.equals(BNB_TEST)) {
ApiClient.getBnbTestChain(getBaseContext()).getSearchTx(hash, "json").enqueue(new Callback<ResBnbTxInfo>() {
@Override
public void onResponse(Call<ResBnbTxInfo> call, Response<ResBnbTxInfo> response) {
if (isFinishing()) return;
WLog.w("onFetchTx " + response.toString());
if (response.isSuccessful() && response.body() != null) {
mResBnbTxInfo = response.body();
if (mResBnbTxInfo.getMsg(0).type.equals(BNB_MSG_TYPE_HTLC) &&
mAccount.address.equals(mResBnbTxInfo.getMsg(0).value.from)) {
onFetchHtlcStatus(mResBnbTxInfo.simpleSwapId());
} else {
onUpdateView();
}
} else {
if (mIsSuccess && FetchCnt < 10) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
FetchCnt++;
onFetchTx(mTxHash);
}
}, 6000);
} else if (!mIsGen) {
onBackPressed();
} else {
onShowMoreWait();
}
}
}
@Override
public void onFailure(Call<ResBnbTxInfo> call, Throwable t) {
WLog.w("BNB onFailure");
if (IS_SHOWLOG) t.printStackTrace();
if (isFinishing()) return;
}
});
} else if (mBaseChain.equals(KAVA_MAIN)) {
ApiClient.getKavaChain(getBaseContext()).getSearchTx(hash).enqueue(new Callback<ResTxInfo>() {
@Override
public void onResponse(Call<ResTxInfo> call, Response<ResTxInfo> response) {
if (isFinishing()) return;
WLog.w("onFetchTx " + response.toString());
if (response.isSuccessful() && response.body() != null) {
mResTxInfo = response.body();
if (mResTxInfo.getMsgType(0).equals(KAVA_MSG_TYPE_BEP3_CREATE_SWAP)) {
onFetchHtlcStatus(mResTxInfo.simpleSwapId());
} else {
onUpdateView();
}
} else {
if (mIsSuccess && FetchCnt < 10) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
FetchCnt++;
onFetchTx(mTxHash);
}
}, 6000);
} else if (!mIsGen) {
onBackPressed();
} else {
onShowMoreWait();
}
}
}
@Override
public void onFailure(Call<ResTxInfo> call, Throwable t) {
if (IS_SHOWLOG) t.printStackTrace();
if (isFinishing()) return;
}
});
} else if (mBaseChain.equals(KAVA_TEST)) {
ApiClient.getKavaTestChain(getBaseContext()).getSearchTx(hash).enqueue(new Callback<ResTxInfo>() {
@Override
public void onResponse(Call<ResTxInfo> call, Response<ResTxInfo> response) {
if (isFinishing()) return;
WLog.w("onFetchTx " + response.toString());
if (response.isSuccessful() && response.body() != null) {
mResTxInfo = response.body();
if (mResTxInfo.getMsgType(0).equals(KAVA_MSG_TYPE_BEP3_CREATE_SWAP)) {
onFetchHtlcStatus(mResTxInfo.simpleSwapId());
} else {
onUpdateView();
}
} else {
if(mIsSuccess && FetchCnt < 10) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
FetchCnt++;
onFetchTx(mTxHash);
}
}, 6000);
} else if (!mIsGen) {
onBackPressed();
} else {
onShowMoreWait();
}
}
}
@Override
public void onFailure(Call<ResTxInfo> call, Throwable t) {
if (IS_SHOWLOG) t.printStackTrace();
if (isFinishing()) return;
}
});
} else if (mBaseChain.equals(BAND_MAIN)) {
ApiClient.getBandChain(getBaseContext()).getSearchTx(hash).enqueue(new Callback<ResTxInfo>() {
@Override
public void onResponse(Call<ResTxInfo> call, Response<ResTxInfo> response) {
if (isFinishing()) return;
WLog.w("onFetchTx " + response.toString());
if (response.isSuccessful() && response.body() != null) {
mResTxInfo = response.body();
onUpdateView();
} else {
if (mIsSuccess && FetchCnt < 10) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
FetchCnt++;
onFetchTx(mTxHash);
}
}, 6000);
} else if (!mIsGen) {
onBackPressed();
} else {
onShowMoreWait();
}
}
}
@Override
public void onFailure(Call<ResTxInfo> call, Throwable t) {
if (IS_SHOWLOG) t.printStackTrace();
if (isFinishing()) return;
}
});
} else if (mBaseChain.equals(IOV_MAIN)) {
ApiClient.getIovChain(getBaseContext()).getSearchTx(hash).enqueue(new Callback<ResTxInfo>() {
@Override
public void onResponse(Call<ResTxInfo> call, Response<ResTxInfo> response) {
if (isFinishing()) return;
WLog.w("onFetchTx " + response.toString());
if (response.isSuccessful() && response.body() != null) {
mResTxInfo = response.body();
onUpdateView();
} else {
if (mIsSuccess && FetchCnt < 10) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
FetchCnt++;
onFetchTx(mTxHash);
}
}, 6000);
} else if (!mIsGen) {
onBackPressed();
} else {
onShowMoreWait();
}
}
}
@Override
public void onFailure(Call<ResTxInfo> call, Throwable t) {
if (IS_SHOWLOG) t.printStackTrace();
if (isFinishing()) return;
}
});
} else if (mBaseChain.equals(IOV_TEST)) {
ApiClient.getIovTestChain(getBaseContext()).getSearchTx(hash).enqueue(new Callback<ResTxInfo>() {
@Override
public void onResponse(Call<ResTxInfo> call, Response<ResTxInfo> response) {
if (isFinishing()) return;
WLog.w("onFetchTx " + response.toString());
if (response.isSuccessful() && response.body() != null) {
mResTxInfo = response.body();
onUpdateView();
} else {
if (mIsSuccess && FetchCnt < 10) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
FetchCnt++;
onFetchTx(mTxHash);
}
}, 6000);
} else if (!mIsGen) {
onBackPressed();
} else {
onShowMoreWait();
}
}
}
@Override
public void onFailure(Call<ResTxInfo> call, Throwable t) {
if (IS_SHOWLOG) t.printStackTrace();
if (isFinishing()) return;
}
});
} else if (mBaseChain.equals(OK_TEST)) {
ApiClient.getOkTestChain(getBaseContext()).getSearchTx(hash).enqueue(new Callback<ResTxInfo>() {
@Override
public void onResponse(Call<ResTxInfo> call, Response<ResTxInfo> response) {
if (isFinishing()) return;
WLog.w("onFetchTx " + response.toString());
if (response.isSuccessful() && response.body() != null) {
mResTxInfo = response.body();
onUpdateView();
} else {
if (mIsSuccess && FetchCnt < 10) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
FetchCnt++;
onFetchTx(mTxHash);
}
}, 6000);
} else if (!mIsGen) {
onBackPressed();
} else {
onShowMoreWait();
}
}
}
@Override
public void onFailure(Call<ResTxInfo> call, Throwable t) {
if (IS_SHOWLOG) t.printStackTrace();
if (isFinishing()) return;
}
});
} else if (mBaseChain.equals(CERTIK_MAIN)) {
ApiClient.getCertikChain(getBaseContext()).getSearchTx(hash).enqueue(new Callback<ResTxInfo>() {
@Override
public void onResponse(Call<ResTxInfo> call, Response<ResTxInfo> response) {
if (isFinishing()) return;
WLog.w("onFetchTx " + response.toString());
if (response.isSuccessful() && response.body() != null) {
mResTxInfo = response.body();
onUpdateView();
} else {
if (mIsSuccess && FetchCnt < 10) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
FetchCnt++;
onFetchTx(mTxHash);
}
}, 6000);
} else if (!mIsGen) {
onBackPressed();
} else {
onShowMoreWait();
}
}
}
@Override
public void onFailure(Call<ResTxInfo> call, Throwable t) {
if (IS_SHOWLOG) t.printStackTrace();
if (isFinishing()) return;
}
});
} else if (mBaseChain.equals(CERTIK_TEST)) {
ApiClient.getCertikTestChain(getBaseContext()).getSearchTx(hash).enqueue(new Callback<ResTxInfo>() {
@Override
public void onResponse(Call<ResTxInfo> call, Response<ResTxInfo> response) {
if (isFinishing()) return;
WLog.w("onFetchTx " + response.toString());
if (response.isSuccessful() && response.body() != null) {
mResTxInfo = response.body();
onUpdateView();
} else {
if (mIsSuccess && FetchCnt < 10) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
FetchCnt++;
onFetchTx(mTxHash);
}
}, 6000);
} else if (!mIsGen) {
onBackPressed();
} else {
onShowMoreWait();
}
}
}
@Override
public void onFailure(Call<ResTxInfo> call, Throwable t) {
if (IS_SHOWLOG) t.printStackTrace();
if (isFinishing()) return;
}
});
} else if (mBaseChain.equals(SECRET_MAIN)) {
ApiClient.getSecretChain(getBaseContext()).getSearchTx(hash).enqueue(new Callback<ResTxInfo>() {
@Override
public void onResponse(Call<ResTxInfo> call, Response<ResTxInfo> response) {
if (isFinishing()) return;
WLog.w("onFetchTx " + response.toString());
if (response.isSuccessful() && response.body() != null) {
mResTxInfo = response.body();
onUpdateView();
} else {
if (mIsSuccess && FetchCnt < 10) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
FetchCnt++;
onFetchTx(mTxHash);
}
}, 6000);
} else if (!mIsGen) {
onBackPressed();
} else {
onShowMoreWait();
}
}
}
@Override
public void onFailure(Call<ResTxInfo> call, Throwable t) {
if (IS_SHOWLOG) t.printStackTrace();
if (isFinishing()) return;
}
});
} else if (mBaseChain.equals(AKASH_MAIN)) {
ApiClient.getAkashChain(getBaseContext()).getSearchTx(hash).enqueue(new Callback<ResTxInfo>() {
@Override
public void onResponse(Call<ResTxInfo> call, Response<ResTxInfo> response) {
if (isFinishing()) return;
WLog.w("onFetchTx " + response.toString());
if (response.isSuccessful() && response.body() != null) {
mResTxInfo = response.body();
onUpdateView();
} else {
if (mIsSuccess && FetchCnt < 10) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
FetchCnt++;
onFetchTx(mTxHash);
}
}, 6000);
} else if (!mIsGen) {
onBackPressed();
} else {
onShowMoreWait();
}
}
}
@Override
public void onFailure(Call<ResTxInfo> call, Throwable t) {
if (IS_SHOWLOG) t.printStackTrace();
if (isFinishing()) return;
}
});
}
}
private void onFetchHtlcStatus(String swapId) {
// WLog.w("onFetchHtlcStatus " +swapId);
if (!TextUtils.isEmpty(swapId)) {
if (mBaseChain.equals(KAVA_MAIN)) {
ApiClient.getKavaChain(getBaseContext()).getSwapById(swapId).enqueue(new Callback<ResKavaSwapInfo>() {
@Override
public void onResponse(Call<ResKavaSwapInfo> call, Response<ResKavaSwapInfo> response) {
if (response.isSuccessful() && response.body() != null) {
mResKavaSwapInfo = response.body();
}
onUpdateView();
}
@Override
public void onFailure(Call<ResKavaSwapInfo> call, Throwable t) {
WLog.w("onFetchHtlcStatus " + t.getMessage());
onUpdateView();
}
});
} else if (mBaseChain.equals(KAVA_TEST)) {
ApiClient.getKavaTestChain(getBaseContext()).getSwapById(swapId).enqueue(new Callback<ResKavaSwapInfo>() {
@Override
public void onResponse(Call<ResKavaSwapInfo> call, Response<ResKavaSwapInfo> response) {
if (response.isSuccessful() && response.body() != null) {
mResKavaSwapInfo = response.body();
}
onUpdateView();
}
@Override
public void onFailure(Call<ResKavaSwapInfo> call, Throwable t) {
WLog.w("onFetchHtlcStatus " + t.getMessage());
onUpdateView();
}
});
} else if (mBaseChain.equals(BNB_MAIN)) {
ApiClient.getBnbChain(getBaseContext()).getSwapById(swapId).enqueue(new Callback<ResBnbSwapInfo>() {
@Override
public void onResponse(Call<ResBnbSwapInfo> call, Response<ResBnbSwapInfo> response) {
if (response.isSuccessful() && response.body() != null) {
WLog.w("onFetchHtlcStatus url " + call.request().url());
mResBnbSwapInfo = response.body();
}
onFetchBnbNodeInfo();
}
@Override
public void onFailure(Call<ResBnbSwapInfo> call, Throwable t) {
WLog.w("onFetchHtlcStatus " + t.getMessage());
onUpdateView();
}
});
} else if (mBaseChain.equals(BNB_TEST)) {
ApiClient.getBnbTestChain(getBaseContext()).getSwapById(swapId).enqueue(new Callback<ResBnbSwapInfo>() {
@Override
public void onResponse(Call<ResBnbSwapInfo> call, Response<ResBnbSwapInfo> response) {
if (response.isSuccessful() && response.body() != null) {
WLog.w("onFetchHtlcStatus url " + call.request().url());
mResBnbSwapInfo = response.body();
}
onFetchBnbNodeInfo();
}
@Override
public void onFailure(Call<ResBnbSwapInfo> call, Throwable t) {
WLog.w("onFetchHtlcStatus " + t.getMessage());
onUpdateView();
}
});
}
} else {
onUpdateView();
}
}
private void onFetchBnbNodeInfo() {
if (mBaseChain.equals(BNB_MAIN)) {
ApiClient.getBnbChain(getBaseContext()).getNodeInfo().enqueue(new Callback<ResBnbNodeInfo>() {
@Override
public void onResponse(Call<ResBnbNodeInfo> call, Response<ResBnbNodeInfo> response) {
if (response.isSuccessful() && response.body() != null) {
mResBnbNodeInfo = response.body();
}
onUpdateView();
}
@Override
public void onFailure(Call<ResBnbNodeInfo> call, Throwable t) {
WLog.w("onFetchBnbNodeInfo " + t.getMessage());
onUpdateView();
}
});
} else if (mBaseChain.equals(BNB_TEST)) {
ApiClient.getBnbTestChain(getBaseContext()).getNodeInfo().enqueue(new Callback<ResBnbNodeInfo>() {
@Override
public void onResponse(Call<ResBnbNodeInfo> call, Response<ResBnbNodeInfo> response) {
if (response.isSuccessful() && response.body() != null) {
mResBnbNodeInfo = response.body();
}
onUpdateView();
}
@Override
public void onFailure(Call<ResBnbNodeInfo> call, Throwable t) {
WLog.w("onFetchBnbNodeInfo " + t.getMessage());
onUpdateView();
}
});
}
}
}
| 56.810978 | 225 | 0.611459 |
2a43274d427da46ff0a34706f6899f952b537707 | 3,422 | java | Java | osgp/platform/osgp-adapter-ws-core/src/test/java/org/opensmartgridplatform/adapter/ws/core/application/mapping/DeviceInstallationMapperTest.java | Jefro/open-smart-grid-platform | 35fd4d9aeac38dc835fd86bc1982ef5638f092e5 | [
"Apache-2.0"
] | null | null | null | osgp/platform/osgp-adapter-ws-core/src/test/java/org/opensmartgridplatform/adapter/ws/core/application/mapping/DeviceInstallationMapperTest.java | Jefro/open-smart-grid-platform | 35fd4d9aeac38dc835fd86bc1982ef5638f092e5 | [
"Apache-2.0"
] | null | null | null | osgp/platform/osgp-adapter-ws-core/src/test/java/org/opensmartgridplatform/adapter/ws/core/application/mapping/DeviceInstallationMapperTest.java | Jefro/open-smart-grid-platform | 35fd4d9aeac38dc835fd86bc1982ef5638f092e5 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2018 Smart Society Services B.V.
*
* 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
*/
package org.opensmartgridplatform.adapter.ws.core.application.mapping;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.opensmartgridplatform.adapter.ws.schema.core.deviceinstallation.Device;
import org.opensmartgridplatform.domain.core.entities.Ssld;
import org.opensmartgridplatform.domain.core.valueobjects.Address;
import org.opensmartgridplatform.domain.core.valueobjects.GpsCoordinates;
public class DeviceInstallationMapperTest {
private final static String DEVICE_IDENTIFICATION = "device_identification";
private final static String ALIAS = "alias";
private final static String CITY = "city";
private final static String POSTAL_CODE = "postal_code";
private final static String STREET = "street";
private final static int NUMBER = 83;
private final static String NUMBER_ADDITION = "D";
private final static String MUNICIPALITY = "municipality";
private final static float GPS_LATITUDE = 50f;
private final static float GPS_LONGITUDE = 5f;
private final static boolean PUBLIC_KEY_PRESENT = true;
DeviceInstallationMapper mapper = new DeviceInstallationMapper();
private Address createAddress() {
return new Address(CITY, POSTAL_CODE, STREET, NUMBER, NUMBER_ADDITION, MUNICIPALITY);
}
private Ssld createSsld() {
final Address containerAddress = this.createAddress();
final GpsCoordinates gps = new GpsCoordinates(GPS_LATITUDE, GPS_LONGITUDE);
final Ssld ssld = new Ssld(DEVICE_IDENTIFICATION, ALIAS, containerAddress, gps, null);
ssld.setPublicKeyPresent(PUBLIC_KEY_PRESENT);
return ssld;
}
private org.opensmartgridplatform.adapter.ws.schema.core.common.Address createWsAddress() {
final org.opensmartgridplatform.adapter.ws.schema.core.common.Address address = new org.opensmartgridplatform.adapter.ws.schema.core.common.Address();
address.setCity(CITY);
address.setPostalCode(POSTAL_CODE);
address.setStreet(STREET);
address.setNumber(NUMBER);
address.setNumberAddition(NUMBER_ADDITION);
address.setMunicipality(MUNICIPALITY);
return address;
}
private Device createWsDevice() {
final Device device = new Device();
device.setDeviceIdentification(DEVICE_IDENTIFICATION);
device.setAlias(ALIAS);
device.setContainerAddress(this.createWsAddress());
device.setGpsLatitude(GPS_LATITUDE);
device.setGpsLongitude(GPS_LONGITUDE);
device.setPublicKeyPresent(PUBLIC_KEY_PRESENT);
return device;
}
@BeforeEach
public void setup() {
this.mapper.initialize();
}
@Test
public void testConversionFromWsDeviceToSsld() {
// Arrange
final Device device = this.createWsDevice();
final Ssld expected = this.createSsld();
// Act
final Ssld actual = this.mapper.map(device, Ssld.class);
// Assert
assertThat(actual).isEqualToIgnoringGivenFields(expected, "creationTime", "modificationTime");
}
}
| 38.886364 | 172 | 0.726476 |
c7ec47a3076738e4be95e8bf9ddf59ff3366ff0f | 1,433 | java | Java | code/spring-boot-shiro-sample/spring-boot-shiro-simple/src/main/java/com/lcg/shiro/webconfigurer/LoginController.java | 87-midnight/NewbieInProgramin | c0df1f7e58ea5fedd83e305ddaecfcc7bd5dae2f | [
"MIT"
] | 1 | 2021-12-30T14:16:26.000Z | 2021-12-30T14:16:26.000Z | code/spring-boot-shiro-sample/spring-boot-shiro-simple/src/main/java/com/lcg/shiro/webconfigurer/LoginController.java | 87-midnight/NewbieInProgramin | c0df1f7e58ea5fedd83e305ddaecfcc7bd5dae2f | [
"MIT"
] | 2 | 2019-10-22T08:21:09.000Z | 2019-10-22T08:21:09.000Z | code/spring-boot-sample/spring-boot-shiro-sample/spring-boot-shiro-simple/src/main/java/com/lcg/shiro/webconfigurer/LoginController.java | 87-midnight/NewbieInJava | ba84153c6b3a382e620c4df7892d653be2e1a607 | [
"MIT"
] | 1 | 2019-12-01T16:43:02.000Z | 2019-12-01T16:43:02.000Z | package com.lcg.shiro.webconfigurer;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
/**
* @author linchuangang
* @createTime 2020/11/4
**/
@RestController
public class LoginController {
@GetMapping(value = "/login")
public String login(){
return "require auth";
}
@PostMapping(value = "/unauth/login")
public String login(@RequestBody Map<String,Object> params){
Subject subject = SecurityUtils.getSubject();
try {
String username = (String) params.get("username");
String password = (String) params.get("password");
subject.login(new UsernamePasswordToken(username, password));
System.out.println("登录成功!");
} catch (AuthenticationException e) {
e.printStackTrace();
System.out.println("登录失败!");
}catch (Exception e){
e.printStackTrace();
}
return "success";
}
@GetMapping(value = "/")
public String index(){
return "hello world";
}
}
| 29.854167 | 73 | 0.674808 |
155b04baf93f358e724ba8a4698be5c9ea6d3713 | 988 | rb | Ruby | spec/makimono/style_spec.rb | fuji-nakahara/makimono | 7712dd5d2406072ebc4b9642b82274489732947f | [
"MIT"
] | null | null | null | spec/makimono/style_spec.rb | fuji-nakahara/makimono | 7712dd5d2406072ebc4b9642b82274489732947f | [
"MIT"
] | 2 | 2020-10-12T07:24:26.000Z | 2020-10-25T03:16:29.000Z | spec/makimono/style_spec.rb | fuji-nakahara/makimono | 7712dd5d2406072ebc4b9642b82274489732947f | [
"MIT"
] | null | null | null | # frozen_string_literal: true
RSpec.describe Makimono::Style do
describe '.from_style_config' do
context 'with a preset' do
let(:style_config) { 'fuji' }
it 'returns Style instance with the preset path' do
style = described_class.from_style_config(style_config)
expect(style).to be_a described_class
expect(style.path).to eq 'fuji.css'
end
end
context 'with a custom style' do
let(:style_config) { fixture_path('style.css') }
it 'returns Style instance with custom style path' do
style = described_class.from_style_config(style_config)
expect(style).to be_a described_class
expect(style.path).to eq 'style.css'
end
end
context 'with an invalid style' do
let(:style_config) { 'invalid.css' }
it 'raises InvalidStyleError' do
expect { described_class.from_style_config(style_config) }.to raise_error Makimono::InvalidStyleError
end
end
end
end
| 27.444444 | 109 | 0.677126 |
2a554260878deb379b2a2f22d40d60ef4f484776 | 2,904 | java | Java | app/src/main/java/com/rosendal/elevkarrosendal/fragments/schedule/ImageEditor.java | HampusAdolfsson/RosenApp | b14660d1366774e48a9893019aff7afe62bfc0c4 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/rosendal/elevkarrosendal/fragments/schedule/ImageEditor.java | HampusAdolfsson/RosenApp | b14660d1366774e48a9893019aff7afe62bfc0c4 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/rosendal/elevkarrosendal/fragments/schedule/ImageEditor.java | HampusAdolfsson/RosenApp | b14660d1366774e48a9893019aff7afe62bfc0c4 | [
"Apache-2.0"
] | null | null | null | package com.rosendal.elevkarrosendal.fragments.schedule;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import java.util.Calendar;
public class ImageEditor {
public static Bitmap cropWeekSchedule(Bitmap bmp, ScheduleImageValues values) {
if (bmp == null) return null;
Rect cropValuesRect = values.getCropValues();
return Bitmap.createBitmap(bmp, cropValuesRect.left, cropValuesRect.top, cropValuesRect.right - cropValuesRect.left, cropValuesRect.bottom - cropValuesRect.top);
}
private static double getTimeOffset(Calendar cal) {
cal.add(Calendar.HOUR_OF_DAY, -8);
return (60 * cal.get(Calendar.HOUR_OF_DAY) + cal.get(Calendar.MINUTE)) / (60.0 * 10.0 + 30);
}
public static Bitmap fillColor(Bitmap bmp, int color) {
Bitmap bitmap = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), Bitmap.Config.ARGB_4444);
for (int x = 0; x < bmp.getWidth(); x++) {
for (int y = 0; y < bmp.getHeight(); y++) {
int alpha = Color.alpha(bmp.getPixel(x, y));
if ((alpha) != 0x00) {
bitmap.setPixel(x, y, Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color)));
}
}
}
return bitmap;
}
public static Bitmap drawableToBitmap(Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
public static Bitmap getRoundedBitmap(Bitmap bitmap) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap
.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = bitmap.getWidth() / 2;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
}
| 37.714286 | 169 | 0.660813 |
7450abeca8f480a6eee4469d0fd2a95967d421b4 | 683 | h | C | pintos/src/vm/frame.h | taeguk/OS-pintos | 67fcf17711680a8b064fddfc7aa1e981c1b9cbfb | [
"MIT"
] | 10 | 2016-09-30T02:19:01.000Z | 2021-11-27T10:44:52.000Z | pintos/src/vm/frame.h | taeguk/OS-pintos | 67fcf17711680a8b064fddfc7aa1e981c1b9cbfb | [
"MIT"
] | null | null | null | pintos/src/vm/frame.h | taeguk/OS-pintos | 67fcf17711680a8b064fddfc7aa1e981c1b9cbfb | [
"MIT"
] | 8 | 2016-10-25T22:15:28.000Z | 2021-07-01T14:03:02.000Z | #ifndef VM_FRAME_H
#define VM_FRAME_H
#include "threads/thread.h"
#include <list.h>
#include "suppage.h"
struct frame
{
void *kpage; // kernel page = paddr + PYS_BASE.
struct suppage *suppage; // supplemental page.
struct thread *owner; // owner of frame.
//int64_t access_ticks; // last access ticks. for LRU.
/* will be added more. */
struct list_elem elem; // for frame table.
};
/* Initialize frame list. */
void frame_init (void);
/* Mapping upage to frame */
bool frame_map (struct suppage *suppage, bool load_from_swap);
/* Unmap a frame from frame list. */
void frame_unmap (struct frame *);
#endif /* vm/frame.h */
| 23.551724 | 64 | 0.651537 |
7407c4a7dadd8358c5cd7ac779b0b7b70e054021 | 10,195 | c | C | gdb/arch/arm.c | greyblue9/binutils-gdb | 05377632b124fe7600eea7f4ee0e9a35d1b0cbdc | [
"BSD-3-Clause"
] | 1 | 2020-10-14T03:24:35.000Z | 2020-10-14T03:24:35.000Z | gdb/arch/arm.c | greyblue9/binutils-gdb | 05377632b124fe7600eea7f4ee0e9a35d1b0cbdc | [
"BSD-3-Clause"
] | null | null | null | gdb/arch/arm.c | greyblue9/binutils-gdb | 05377632b124fe7600eea7f4ee0e9a35d1b0cbdc | [
"BSD-3-Clause"
] | null | null | null | /* Common target dependent code for GDB on ARM systems.
Copyright (C) 1988-2021 Free Software Foundation, Inc.
This file is part of GDB.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include "gdbsupport/common-defs.h"
#include "gdbsupport/common-regcache.h"
#include "arm.h"
#include "../features/arm/arm-core.c"
#include "../features/arm/arm-vfpv2.c"
#include "../features/arm/arm-vfpv3.c"
#include "../features/arm/xscale-iwmmxt.c"
#include "../features/arm/arm-m-profile.c"
#include "../features/arm/arm-m-profile-with-fpa.c"
/* See arm.h. */
int
thumb_insn_size (unsigned short inst1)
{
if ((inst1 & 0xe000) == 0xe000 && (inst1 & 0x1800) != 0)
return 4;
else
return 2;
}
/* See arm.h. */
int
condition_true (unsigned long cond, unsigned long status_reg)
{
if (cond == INST_AL || cond == INST_NV)
return 1;
switch (cond)
{
case INST_EQ:
return ((status_reg & FLAG_Z) != 0);
case INST_NE:
return ((status_reg & FLAG_Z) == 0);
case INST_CS:
return ((status_reg & FLAG_C) != 0);
case INST_CC:
return ((status_reg & FLAG_C) == 0);
case INST_MI:
return ((status_reg & FLAG_N) != 0);
case INST_PL:
return ((status_reg & FLAG_N) == 0);
case INST_VS:
return ((status_reg & FLAG_V) != 0);
case INST_VC:
return ((status_reg & FLAG_V) == 0);
case INST_HI:
return ((status_reg & (FLAG_C | FLAG_Z)) == FLAG_C);
case INST_LS:
return ((status_reg & (FLAG_C | FLAG_Z)) != FLAG_C);
case INST_GE:
return (((status_reg & FLAG_N) == 0) == ((status_reg & FLAG_V) == 0));
case INST_LT:
return (((status_reg & FLAG_N) == 0) != ((status_reg & FLAG_V) == 0));
case INST_GT:
return (((status_reg & FLAG_Z) == 0)
&& (((status_reg & FLAG_N) == 0)
== ((status_reg & FLAG_V) == 0)));
case INST_LE:
return (((status_reg & FLAG_Z) != 0)
|| (((status_reg & FLAG_N) == 0)
!= ((status_reg & FLAG_V) == 0)));
}
return 1;
}
/* See arm.h. */
int
thumb_advance_itstate (unsigned int itstate)
{
/* Preserve IT[7:5], the first three bits of the condition. Shift
the upcoming condition flags left by one bit. */
itstate = (itstate & 0xe0) | ((itstate << 1) & 0x1f);
/* If we have finished the IT block, clear the state. */
if ((itstate & 0x0f) == 0)
itstate = 0;
return itstate;
}
/* See arm.h. */
int
arm_instruction_changes_pc (uint32_t this_instr)
{
if (bits (this_instr, 28, 31) == INST_NV)
/* Unconditional instructions. */
switch (bits (this_instr, 24, 27))
{
case 0xa:
case 0xb:
/* Branch with Link and change to Thumb. */
return 1;
case 0xc:
case 0xd:
case 0xe:
/* Coprocessor register transfer. */
if (bits (this_instr, 12, 15) == 15)
error (_("Invalid update to pc in instruction"));
return 0;
default:
return 0;
}
else
switch (bits (this_instr, 25, 27))
{
case 0x0:
if (bits (this_instr, 23, 24) == 2 && bit (this_instr, 20) == 0)
{
/* Multiplies and extra load/stores. */
if (bit (this_instr, 4) == 1 && bit (this_instr, 7) == 1)
/* Neither multiplies nor extension load/stores are allowed
to modify PC. */
return 0;
/* Otherwise, miscellaneous instructions. */
/* BX <reg>, BXJ <reg>, BLX <reg> */
if (bits (this_instr, 4, 27) == 0x12fff1
|| bits (this_instr, 4, 27) == 0x12fff2
|| bits (this_instr, 4, 27) == 0x12fff3)
return 1;
/* Other miscellaneous instructions are unpredictable if they
modify PC. */
return 0;
}
/* Data processing instruction. */
/* Fall through. */
case 0x1:
if (bits (this_instr, 12, 15) == 15)
return 1;
else
return 0;
case 0x2:
case 0x3:
/* Media instructions and architecturally undefined instructions. */
if (bits (this_instr, 25, 27) == 3 && bit (this_instr, 4) == 1)
return 0;
/* Stores. */
if (bit (this_instr, 20) == 0)
return 0;
/* Loads. */
if (bits (this_instr, 12, 15) == ARM_PC_REGNUM)
return 1;
else
return 0;
case 0x4:
/* Load/store multiple. */
if (bit (this_instr, 20) == 1 && bit (this_instr, 15) == 1)
return 1;
else
return 0;
case 0x5:
/* Branch and branch with link. */
return 1;
case 0x6:
case 0x7:
/* Coprocessor transfers or SWIs can not affect PC. */
return 0;
default:
internal_error (__FILE__, __LINE__, _("bad value in switch"));
}
}
/* See arm.h. */
int
thumb_instruction_changes_pc (unsigned short inst)
{
if ((inst & 0xff00) == 0xbd00) /* pop {rlist, pc} */
return 1;
if ((inst & 0xf000) == 0xd000) /* conditional branch */
return 1;
if ((inst & 0xf800) == 0xe000) /* unconditional branch */
return 1;
if ((inst & 0xff00) == 0x4700) /* bx REG, blx REG */
return 1;
if ((inst & 0xff87) == 0x4687) /* mov pc, REG */
return 1;
if ((inst & 0xf500) == 0xb100) /* CBNZ or CBZ. */
return 1;
return 0;
}
/* See arm.h. */
int
thumb2_instruction_changes_pc (unsigned short inst1, unsigned short inst2)
{
if ((inst1 & 0xf800) == 0xf000 && (inst2 & 0x8000) == 0x8000)
{
/* Branches and miscellaneous control instructions. */
if ((inst2 & 0x1000) != 0 || (inst2 & 0xd001) == 0xc000)
{
/* B, BL, BLX. */
return 1;
}
else if (inst1 == 0xf3de && (inst2 & 0xff00) == 0x3f00)
{
/* SUBS PC, LR, #imm8. */
return 1;
}
else if ((inst2 & 0xd000) == 0x8000 && (inst1 & 0x0380) != 0x0380)
{
/* Conditional branch. */
return 1;
}
return 0;
}
if ((inst1 & 0xfe50) == 0xe810)
{
/* Load multiple or RFE. */
if (bit (inst1, 7) && !bit (inst1, 8))
{
/* LDMIA or POP */
if (bit (inst2, 15))
return 1;
}
else if (!bit (inst1, 7) && bit (inst1, 8))
{
/* LDMDB */
if (bit (inst2, 15))
return 1;
}
else if (bit (inst1, 7) && bit (inst1, 8))
{
/* RFEIA */
return 1;
}
else if (!bit (inst1, 7) && !bit (inst1, 8))
{
/* RFEDB */
return 1;
}
return 0;
}
if ((inst1 & 0xffef) == 0xea4f && (inst2 & 0xfff0) == 0x0f00)
{
/* MOV PC or MOVS PC. */
return 1;
}
if ((inst1 & 0xff70) == 0xf850 && (inst2 & 0xf000) == 0xf000)
{
/* LDR PC. */
if (bits (inst1, 0, 3) == 15)
return 1;
if (bit (inst1, 7))
return 1;
if (bit (inst2, 11))
return 1;
if ((inst2 & 0x0fc0) == 0x0000)
return 1;
return 0;
}
if ((inst1 & 0xfff0) == 0xe8d0 && (inst2 & 0xfff0) == 0xf000)
{
/* TBB. */
return 1;
}
if ((inst1 & 0xfff0) == 0xe8d0 && (inst2 & 0xfff0) == 0xf010)
{
/* TBH. */
return 1;
}
return 0;
}
/* See arm.h. */
unsigned long
shifted_reg_val (struct regcache *regcache, unsigned long inst,
int carry, unsigned long pc_val, unsigned long status_reg)
{
unsigned long res, shift;
int rm = bits (inst, 0, 3);
unsigned long shifttype = bits (inst, 5, 6);
if (bit (inst, 4))
{
int rs = bits (inst, 8, 11);
shift = (rs == 15
? pc_val + 8
: regcache_raw_get_unsigned (regcache, rs)) & 0xFF;
}
else
shift = bits (inst, 7, 11);
res = (rm == ARM_PC_REGNUM
? (pc_val + (bit (inst, 4) ? 12 : 8))
: regcache_raw_get_unsigned (regcache, rm));
switch (shifttype)
{
case 0: /* LSL */
res = shift >= 32 ? 0 : res << shift;
break;
case 1: /* LSR */
res = shift >= 32 ? 0 : res >> shift;
break;
case 2: /* ASR */
if (shift >= 32)
shift = 31;
res = ((res & 0x80000000L)
? ~((~res) >> shift) : res >> shift);
break;
case 3: /* ROR/RRX */
shift &= 31;
if (shift == 0)
res = (res >> 1) | (carry ? 0x80000000L : 0);
else
res = (res >> shift) | (res << (32 - shift));
break;
}
return res & 0xffffffff;
}
/* See arch/arm.h. */
target_desc *
arm_create_target_description (arm_fp_type fp_type)
{
target_desc_up tdesc = allocate_target_description ();
#ifndef IN_PROCESS_AGENT
if (fp_type == ARM_FP_TYPE_IWMMXT)
set_tdesc_architecture (tdesc.get (), "iwmmxt");
else
set_tdesc_architecture (tdesc.get (), "arm");
#endif
long regnum = 0;
regnum = create_feature_arm_arm_core (tdesc.get (), regnum);
switch (fp_type)
{
case ARM_FP_TYPE_NONE:
break;
case ARM_FP_TYPE_VFPV2:
regnum = create_feature_arm_arm_vfpv2 (tdesc.get (), regnum);
break;
case ARM_FP_TYPE_VFPV3:
regnum = create_feature_arm_arm_vfpv3 (tdesc.get (), regnum);
break;
case ARM_FP_TYPE_IWMMXT:
regnum = create_feature_arm_xscale_iwmmxt (tdesc.get (), regnum);
break;
default:
error (_("Invalid Arm FP type: %d"), fp_type);
}
return tdesc.release ();
}
/* See arch/arm.h. */
target_desc *
arm_create_mprofile_target_description (arm_m_profile_type m_type)
{
target_desc *tdesc = allocate_target_description ().release ();
#ifndef IN_PROCESS_AGENT
set_tdesc_architecture (tdesc, "arm");
#endif
long regnum = 0;
switch (m_type)
{
case ARM_M_TYPE_M_PROFILE:
regnum = create_feature_arm_arm_m_profile (tdesc, regnum);
break;
case ARM_M_TYPE_VFP_D16:
regnum = create_feature_arm_arm_m_profile (tdesc, regnum);
regnum = create_feature_arm_arm_vfpv2 (tdesc, regnum);
break;
case ARM_M_TYPE_WITH_FPA:
regnum = create_feature_arm_arm_m_profile_with_fpa (tdesc, regnum);
break;
default:
error (_("Invalid Arm M type: %d"), m_type);
}
return tdesc;
}
| 22.756696 | 76 | 0.585483 |
9bca316a65ac796acec71507caaf0fe6209b3958 | 547 | js | JavaScript | tests/cucumber/support/widgets/dialogs/boundary_conditions_dialog.js | triplepoint/materials-designer | 1691376e1324509c5b4e3201bc7093cf308573a1 | [
"Apache-2.0"
] | 9 | 2019-10-19T23:31:52.000Z | 2022-01-20T09:50:25.000Z | tests/cucumber/support/widgets/dialogs/boundary_conditions_dialog.js | triplepoint/materials-designer | 1691376e1324509c5b4e3201bc7093cf308573a1 | [
"Apache-2.0"
] | 16 | 2020-04-15T13:11:19.000Z | 2022-03-12T03:15:25.000Z | tests/cucumber/support/widgets/dialogs/boundary_conditions_dialog.js | triplepoint/materials-designer | 1691376e1324509c5b4e3201bc7093cf308573a1 | [
"Apache-2.0"
] | 6 | 2019-07-05T04:54:13.000Z | 2021-04-28T17:44:36.000Z | import {Widget} from "../../widget";
import {SELECTORS} from "../../selectors";
export class BoundaryConditionsDialogWidget extends Widget {
constructor(selector) {
super(selector);
this.selectors = this.getWrappedSelectors(SELECTORS.headerMenu.boundaryConditionsDialog);
}
addBoundaryConditions({type, offset}) {
exabrowser.selectByValue(this.selectors.type, type);
exabrowser.setValue(this.selectors.offset, offset);
};
submit() {exabrowser.scrollAndClick(this.selectors.submitButton);}
}
| 30.388889 | 97 | 0.709324 |
39740d3fca249ef0e3e37f6e86d51dd153cc8bd0 | 3,824 | html | HTML | www/download.html | TomAnthony/intercooler-js | 1702aee2a15a57b0fe27b7b5e2cdca6bfaf78bde | [
"MIT"
] | 1 | 2017-12-06T08:26:56.000Z | 2017-12-06T08:26:56.000Z | www/download.html | TomAnthony/intercooler-js | 1702aee2a15a57b0fe27b7b5e2cdca6bfaf78bde | [
"MIT"
] | null | null | null | www/download.html | TomAnthony/intercooler-js | 1702aee2a15a57b0fe27b7b5e2cdca6bfaf78bde | [
"MIT"
] | null | null | null | ---
layout: default
nav: download
---
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>Downloads</h2>
</div>
</div>
<div class="row">
<div class="col-md-12">
<h3><i class="fa fa-bolt"></i> S3 latest</h3>
<pre>
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="https://s3.amazonaws.com/intercoolerjs.org/release/intercooler-0.4.1.min.js">
</script>
</pre>
</div>
</div>
<div class="row">
<div class="col-md-12">
<h3><i class="fa fa-cloud-download"></i> Releases</h3>
<ul class="list-unstyled">
<li>
<a href="https://s3.amazonaws.com/intercoolerjs.org/release/intercooler-0.4.1.js">intercooler-0.4.1.js</a> -
<a href="/release/CHANGES-0.4.1.html">CHANGES</a> -
<a href="/release/unit-tests-0.4.1.html">Unit Tests</a>
</li>
<li>
<a
href="https://s3.amazonaws.com/intercoolerjs.org/release/intercooler-0.4.1.min.js">intercooler-0.4.1.min.js</a>
</li>
<li>
<a href="https://s3.amazonaws.com/intercoolerjs.org/release/intercooler-0.4.0.js">intercooler-0.4.0.js</a> -
<a href="/release/CHANGES-0.4.0.html">CHANGES</a> -
<a href="/release/unit-tests-0.4.0.html">Unit Tests</a>
</li>
<li>
<a
href="https://s3.amazonaws.com/intercoolerjs.org/release/intercooler-0.4.0.min.js">intercooler-0.4.0.min.js</a>
</li>
<li>
<a href="https://s3.amazonaws.com/intercoolerjs.org/release/intercooler-0.3.2.js">intercooler-0.3.2.js</a> -
<a href="/release/upgrade-steps-0.3.0.html">UPGRADE GUIDE</a> -
<a href="/release/unit-tests-0.3.2.html">Unit Tests</a>
</li>
<li>
<a
href="https://s3.amazonaws.com/intercoolerjs.org/release/intercooler-0.3.2.min.js">intercooler-0.3.2.min.js</a>
</li>
<li>
<a href="https://s3.amazonaws.com/intercoolerjs.org/release/intercooler-0.2.0.js">intercooler-0.2.0.js</a>
</li>
<li>
<a
href="https://s3.amazonaws.com/intercoolerjs.org/release/intercooler-0.2.0.min.js">intercooler-0.2.0.min.js</a>
</li>
<li>
<em><a href="#" onclick="$('#older').slideToggle()">Show Older Releases</a></em>
</li>
</ul>
<ul id="older" style="display:none;" class="list-unstyled">
<li>
<a href="https://s3.amazonaws.com/intercoolerjs.org/release/intercooler-0.0.1.js">intercooler-0.0.1.js</a>
</li>
<li>
<a
href="https://s3.amazonaws.com/intercoolerjs.org/release/intercooler-0.0.1.min.js">intercooler-0.0.1.min.js</a>
</li>
</ul>
</div>
</div>
<div class="row">
<div class="col-md-12">
<h3><i class='fa fa-bullhorn'></i> Newsgroup</h3>
<p>
<a href="https://groups.google.com/forum/#!forum/intercooler-js">https://groups.google.com/forum/#!forum/intercooler-js</a>
</p>
</div>
</div>
<div class="row">
<div class="col-md-12">
<h3><i class='fa fa-github'></i> Github</h3>
<p>
<a href="https://github.com/LeadDyno/intercooler-js">https://github.com/LeadDyno/intercooler-js</a>
</p>
</div>
</div>
<div class="row">
<div class="col-md-12">
<h3><i class='fa fa-github'></i> Rails Demo Application</h3>
<p>
Source: <a href="https://github.com/LeadDyno/intercooler-js-demo-rails-app">https://github.com/LeadDyno/intercooler-js-demo-rails-app</a>
</p>
<p>
On Heroku: <a href="http://intercoolerjs.herokuapp.com/">http://intercoolerjs.herokuapp.com/</a> (Running on a single free dyno, probably slammed... :))
</p>
</div>
</div>
</div> | 35.082569 | 161 | 0.564331 |
fb2b96accbc2fe2b0ca62463a37a0b609aa455d7 | 3,120 | c | C | LinkedListIterator/linked_list_iterator_main.c | Nam-H-Nguyen/DataStructure | 61c86abf47171aecc66ba39e33364d12b12f94c1 | [
"MIT"
] | 1 | 2019-07-05T16:40:12.000Z | 2019-07-05T16:40:12.000Z | LinkedListIterator/linked_list_iterator_main.c | Nam-H-Nguyen/DataStructure | 61c86abf47171aecc66ba39e33364d12b12f94c1 | [
"MIT"
] | null | null | null | LinkedListIterator/linked_list_iterator_main.c | Nam-H-Nguyen/DataStructure | 61c86abf47171aecc66ba39e33364d12b12f94c1 | [
"MIT"
] | null | null | null | /*
* @file linked_list_iterator_main.c
*
* This file exercises the singly linked list and singly linked list
* iterators functions.
*
* @since Oct 24, 2018
* @author: Nam H. Nguyen
*/
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include "linked_list_iterator.h"
/**
* Test LinkedListIterator functions
*/
void testLinkedListIterator(void) {
printf("\nstart testLinkedListIterator\n");
printf("initial list\n");
LinkedList *list = newLinkedList(5);
printLinkedList(list);
printf("list size: %ld\n", linkedListSize(list));
// add 5 nodes to the list
printf("\nAdding 5 values to list\n");
addLastLinkedListVal(list, "A");
addLastLinkedListVal(list, "B");
addLastLinkedListVal(list, "C");
addLastLinkedListVal(list, "D");
addLastLinkedListVal(list, "E");
printLinkedList(list);
printf("list size: %ld\n", linkedListSize(list));
printf("\nTraversing list forward with iterator\n");
LinkedListIterator *itr = newLinkedListIterator(list);
printf("iterator count: %ld\n", getLinkedListIteratorCount(itr));
printf("iterator avail: %ld\n", getLinkedListIteratorAvailable(itr));
while (hasNextLinkedListIteratorVal(itr)) {
const char *val;
if (getNextLinkedListIteratorVal(itr, &val)) {
printf("iterator next: \"%s\"\n", val);
} else {
printf("iterator next: unavailable\n");
}
}
printf("iterator count: %ld\n", getLinkedListIteratorCount(itr));
printf("iterator avail: %ld\n", getLinkedListIteratorAvailable(itr));
printf("\nMoving back one from end with iterator\n");
printf("iterator has prev: %s\n", hasPrevLinkedListIteratorVal(itr) ? "true" : "false");
const char *val;
if (getPrevLinkedListIteratorVal(itr, &val)) {
printf("iterator prev: \"%s\"\n", val);
} else {
printf("iterator prev: unavailable\n");
}
printf("iterator count: %ld\n", getLinkedListIteratorCount(itr));
printf("iterator avail: %ld\n", getLinkedListIteratorAvailable(itr));
printf("\nMoving forward one to end with iterator\n");
if (getNextLinkedListIteratorVal(itr, &val)) {
printf("iterator next: \"%s\"\n", val);
} else {
printf("iterator next: unavailable\n");
}
printf("iterator count: %ld\n", getLinkedListIteratorCount(itr));
printf("iterator avail: %ld\n", getLinkedListIteratorAvailable(itr));
printf("\nResetting iterator\n");
resetLinkedListIterator(itr);
printf("iterator has next: %s\n", hasNextLinkedListIteratorVal(itr) ? "true" : "false");
printf("iterator count: %ld\n", getLinkedListIteratorCount(itr));
printf("iterator avail: %ld\n", getLinkedListIteratorAvailable(itr));
printf("\nTrying to move back one from beginning with iterator\n");
printf("iterator has prev: %s\n", hasPrevLinkedListIteratorVal(itr) ? "true" : "false");
if (getPrevLinkedListIteratorVal(itr, &val)) {
printf("iterator prev: \"%s\"\n", val);
} else {
printf("iterator prev: unavailable\n");
}
printf("\nDeleting iterator and linked list\n");
deleteLinkedListIterator(itr);
deleteLinkedList(list);
printf("end testLinkedListIterator\n");
}
/**
* Test functions.
*/
int main(void) {
testLinkedListIterator();
printf("program exiting\n");
}
| 30.588235 | 89 | 0.714103 |
70f57d00faf1c20e85e7189a3d5aed566f6cbef2 | 1,128 | h | C | RecoVertex/KinematicFitPrimitives/interface/ExtendedPerigeeTrajectoryError.h | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | RecoVertex/KinematicFitPrimitives/interface/ExtendedPerigeeTrajectoryError.h | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | RecoVertex/KinematicFitPrimitives/interface/ExtendedPerigeeTrajectoryError.h | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | #ifndef ExtendedPerigeeTrajectoryError_H
#define ExtendedPerigeeTrajectoryError_H
#include "DataFormats/CLHEP/interface/AlgebraicObjects.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
class ExtendedPerigeeTrajectoryError {
public:
ExtendedPerigeeTrajectoryError() : weightAvailable(false), vl(false) {}
ExtendedPerigeeTrajectoryError(const AlgebraicSymMatrix66& covariance)
: cov(covariance), weightAvailable(false), vl(true) {}
/**
* Access methods
*/
bool isValid() const { return vl; }
bool weightIsAvailable() const { return weightAvailable; }
const AlgebraicSymMatrix66& covarianceMatrix() const { return cov; }
const AlgebraicSymMatrix66& weightMatrix(int& error) const {
error = 0;
if (!weightIsAvailable()) {
weight = cov.Inverse(error);
if (error != 0)
LogDebug("RecoVertex/ExtendedPerigeeTrajectoryError") << "unable to invert covariance matrix\n";
weightAvailable = true;
}
return weight;
}
private:
AlgebraicSymMatrix66 cov;
mutable AlgebraicSymMatrix66 weight;
mutable bool weightAvailable;
mutable bool vl;
};
#endif
| 26.857143 | 104 | 0.741135 |
102a5fbc0f62801aa677881da7f13808b96d3229 | 1,172 | swift | Swift | Sources/CardVisionCLI/main.swift | BergQuester/CardVision | dd6e866f118196e2868fc051d476b8fb94bb5238 | [
"MIT"
] | 8 | 2021-02-26T21:27:04.000Z | 2022-02-12T20:38:10.000Z | Sources/CardVisionCLI/main.swift | BergQuester/CardVision | dd6e866f118196e2868fc051d476b8fb94bb5238 | [
"MIT"
] | null | null | null | Sources/CardVisionCLI/main.swift | BergQuester/CardVision | dd6e866f118196e2868fc051d476b8fb94bb5238 | [
"MIT"
] | 1 | 2021-03-13T22:49:13.000Z | 2021-03-13T22:49:13.000Z | //
// File.swift
//
//
// Created by Daniel Bergquist on 2/7/21.
//
// This is a quick and dirty commandline tool for processing Apple card screenshots
// using CardVision. Pull requests welcome.
import Foundation
import CardVision
// Commandline argument keys
let imagePathKey = "imagePath"
let outputPathKey = "outputPath"
// Fetch commandline arguments
let defaults = UserDefaults.standard
guard let imagePath = defaults.string(forKey: imagePathKey) else {
print("error: no \(imagePathKey) set")
printHelp()
exit(-1)
}
guard let outputPath = defaults.string(forKey: outputPathKey) else {
print("error: no \(outputPathKey) defined")
printHelp()
exit(-1)
}
// process images
let csvData = FileManager()
.images(inPath: imagePath)
.allTransactions()
.filtered(isDeclined: false)
.csvData
// Output
let outputURL = URL(fileURLWithPath: outputPath)
do {
try csvData?.write(to: outputURL)
} catch {
print("\(error)")
exit(-1)
}
/// Prints commandline help
func printHelp() {
let help =
"""
cardvision -\(imagePathKey) <path_to_cropped_images> -\(outputPathKey) <path_to_output_file>
"""
print(help)
}
| 20.206897 | 92 | 0.697099 |
f01b93fd62ec0d32ae52b76226ebbdc809441a67 | 10,427 | js | JavaScript | lib/resources-exec.js | itsshivaverma/node-client-api | a24196afbd07faf629b0dd9f301fe869ed68ceab | [
"Apache-2.0"
] | null | null | null | lib/resources-exec.js | itsshivaverma/node-client-api | a24196afbd07faf629b0dd9f301fe869ed68ceab | [
"Apache-2.0"
] | null | null | null | lib/resources-exec.js | itsshivaverma/node-client-api | a24196afbd07faf629b0dd9f301fe869ed68ceab | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2014-2019 MarkLogic Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
var requester = require('./requester.js');
var mlutil = require('./mlutil.js');
var Operation = require('./operation.js');
/**
* Provides functions to execute resource services on the REST server
* for the client. The resource service extensions must have been
* installed previously on the REST server using the
* {@link config.resources#write} function.
* @namespace resources
*/
/** @ignore */
function checkArgs() {
if (arguments.length === 0) {
throw new Error('no argument for executing resource service');
}
var args = arguments[0];
if (args.name === void 0) {
throw new Error('no name for executing resource service');
}
return args;
}
/** @ignore */
function makeRequestOptions(client, args) {
var path = '/v1/resources/'+args.name;
var sep ='?';
var params = args.params;
var keys = (params === void 0) ? null : Object.keys(params);
var keyLen = (keys === null) ? 0 : keys.length;
var key = null;
var prefix = null;
var i=0;
var value = null;
var j=0;
for (; i < keyLen; i++) {
key = keys[i];
value = params[key];
if (Array.isArray(value)) {
prefix = sep+encodeURIComponent('rs:'+key)+'=';
for (j=0; j < value.length; j++) {
path += prefix+encodeURIComponent(value[j]);
if (i === 0 && j === 0) {
sep ='&';
prefix = sep+encodeURIComponent('rs:'+key)+'=';
}
}
} else {
path += sep+'rs:'+key+'='+encodeURIComponent(value);
if (i === 0) {
sep ='&';
}
}
}
var txid = mlutil.convertTransaction(args.txid);
if (txid !== undefined && txid != null) {
path += sep+'txid='+mlutil.getTxidParam(txid);
if (sep === '?') {
sep ='&';
}
}
var connectionParams = client.connectionParams;
var requestOptions = mlutil.copyProperties(connectionParams);
requestOptions.path = mlutil.databaseParam(connectionParams, path, sep);
mlutil.addTxidHeaders(requestOptions, txid);
return requestOptions;
}
function validateStatusCode(statusCode) {
return (statusCode < 400) ? null : "response with invalid "+statusCode+" status";
}
function Resources(client) {
if (!(this instanceof Resources)) {
return new Resources(client);
}
this.client = client;
}
//TODO: stream parameter should control whether object or chunked
/**
* Invokes the get() function in the resource service.
* @method resources#get
* @since 1.0
* @param {string} name - the name of the service
* @param {object} [params] - an object in which each property has
* a variable name as a key and a number, string, or boolean value
* @param {string|transactions.Transaction} [txid] - a string
* transaction id or Transaction object identifying an open
* multi-statement transaction
* @returns {ResultProvider} an object whose stream() function returns
* a stream that receives the response
*/
Resources.prototype.get = function getResourceExec() {
return readResourceExec(
this, 'multipart', 'multipart/mixed; boundary='+mlutil.multipartBoundary,
checkArgs.apply(null, arguments)
);
};
Resources.prototype.getReadStream = function getResourceExecStream() {
var args = checkArgs.apply(null, arguments);
var contentType = args.contentType;
if (contentType == null) {
throw new Error('no content type for reading stream from resource service');
}
return readResourceExec(this, 'chunked', contentType, args);
};
/** @ignore */
function readResourceExec(self, responseType, contentType, args) {
var requestOptions = makeRequestOptions(self.client, args);
requestOptions.method = 'GET';
requestOptions.headers = {
'Accept': contentType
};
var operation = new Operation(
'execute remove service', self.client, requestOptions, 'empty', responseType
);
operation.name = args.name;
operation.statusCodeValidator = validateStatusCode;
return requester.startRequest(operation);
}
/**
* Invokes the post() function in the resource service.
* @method resources#post
* @since 1.0
* @param {string} name - the name of the service
* @param {object} [params] - an object in which each property has
* a variable name as a key and a number, string, or boolean value
* @param {string|object|Buffer|ReadableStream} [documents] - any document
* content to send to the server
* @param {string|transactions.Transaction} [txid] - a string
* transaction id or Transaction object identifying an open
* multi-statement transaction
* @returns {ResultProvider} an object whose stream() function returns
* a stream that receives the response
*/
Resources.prototype.post = function postResourceExec() {
return writeResources(this, 'POST', 'multipart', checkArgs.apply(null, arguments));
};
/**
* Invokes the put() function in the resource service.
* @method resources#put
* @since 1.0
* @param {string} name - the name of the service
* @param {object} [params] - an object in which each property has
* a variable name as a key and a number, string, or boolean value
* @param {string|object|Buffer|ReadableStream} [documents] - any document
* content to send to the server
* @param {string|transactions.Transaction} [txid] - a string
* transaction id or Transaction object identifying an open
* multi-statement transaction
*/
Resources.prototype.put = function putResourceExec() {
return writeResources(this, 'PUT', 'single', checkArgs.apply(null, arguments));
};
Resources.prototype.postWriteStream = function postResourceExecStream() {
return writeResourceStream(this, 'POST', 'multipart', checkArgs.apply(null, arguments));
};
Resources.prototype.putWriteStream = function putResourceExecStream() {
return writeResourceStream(this, 'PUT', 'single', checkArgs.apply(null, arguments));
};
/** @ignore */
function writeResourceStream(self, method, responseType, args) {
var contentType = args.contentType;
if (contentType == null) {
throw new Error('no content type for writing stream to resource service');
}
var requestOptions = makeRequestOptions(self.client, args);
requestOptions.headers = {
'Content-Type': contentType,
'Accept': 'application/json'
};
requestOptions.method = method;
var operation = new Operation(
'execute '+method+' service stream', self.client, requestOptions,
'chunked', responseType
);
operation.name = args.name;
operation.statusCodeValidator = validateStatusCode;
return requester.startRequest(operation);
}
/** @ignore */
function writeResources(self, method, responseType, args) {
var documents = args.documents;
var isEmpty = (documents == null);
if (!isEmpty && !Array.isArray(documents)) {
documents = [documents];
}
var multipartBoundary = mlutil.multipartBoundary;
var requestOptions = makeRequestOptions(self.client, args);
requestOptions.method = method;
requestOptions.headers = (!isEmpty) ?
{
'Content-Type': 'multipart/mixed; boundary='+multipartBoundary,
'Accept': 'application/json'
} :
{
'Accept': 'application/json'
};
var partList = [];
if (typeof documents !== 'undefined') {
for (var i=0; i < documents.length; i++) {
addPart(partList, documents[i]);
}
}
var operation = new Operation(
'execute '+method+' service', self.client, requestOptions,
(isEmpty ? 'empty' : 'multipart'), responseType
);
operation.name = args.name;
if (!isEmpty) {
operation.multipartBoundary = multipartBoundary;
}
operation.requestPartList = partList;
operation.statusCodeValidator = validateStatusCode;
return requester.startRequest(operation);
}
/** @ignore */
function addPart(partList, document) {
var headers = {};
var part = {
headers: headers
};
var content = document.content;
var hasContent = (content != null);
var contentType = hasContent ? document.contentType : null;
if (hasContent && (contentType != null)) {
var marshaledData = mlutil.marshal(content);
/* TODO: allow encoding in multipart parse
headers['Content-Type'] = contentType +
((typeof marshaledData === 'string' || marshaledData instanceof String) ? '; charset=utf-8' : '');
*/
headers['Content-Type'] = contentType;
part.content = marshaledData;
} else if (typeof document === 'string' || document instanceof String) {
part.content = document;
// headers['Content-Type'] = 'text/plain; charset=utf-8';
headers['Content-Type'] = 'text/plain';
} else if (Buffer.isBuffer(document)) {
part.content = document;
headers['Content-Type'] = 'application/x-unknown-content-type';
} else {
part.content = JSON.stringify(document);
// headers['Content-Type'] = 'application/json; charset=utf-8';
headers['Content-Type'] = 'application/json';
}
partList.push(part);
}
/**
* Invokes the delete() function in the resource service.
* @method resources#remove
* @since 1.0
* @param {string} name - the name of the service
* @param {object} [params] - an object in which each property has
* a variable name as a key and a number, string, or boolean value
* @param {string|transactions.Transaction} [txid] - a string
* transaction id or Transaction object identifying an open
* multi-statement transaction
*/
Resources.prototype.remove = function removeResourceExec() {
var args = checkArgs.apply(null, arguments);
var requestOptions = makeRequestOptions(this.client, args);
requestOptions.headers = {
'Accept': 'application/json'
};
requestOptions.method = 'DELETE';
var operation = new Operation(
'execute remove service', this.client, requestOptions, 'empty', 'single'
);
operation.name = args.name;
operation.statusCodeValidator = validateStatusCode;
return requester.startRequest(operation);
};
module.exports = Resources;
| 32.68652 | 104 | 0.68735 |
775a72b4447a6e9ef2166f8709c46023777f7df2 | 378 | html | HTML | app/gybr/index.html | jackens/jc | 08cf99f9730737766b1be045369ee7d881305a6c | [
"MIT"
] | 3 | 2019-05-17T05:52:30.000Z | 2021-07-15T10:36:20.000Z | app/gybr/index.html | jackens/jc | 08cf99f9730737766b1be045369ee7d881305a6c | [
"MIT"
] | null | null | null | app/gybr/index.html | jackens/jc | 08cf99f9730737766b1be045369ee7d881305a6c | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
<title>GYBR</title>
<link rel="apple-touch-icon" href="gybr.png" />
<link rel="shortcut icon" type="image/png" href="gybr.png" />
</head>
<body>
<script type="module" src="gybr.js"></script>
</body>
</html>
| 27 | 105 | 0.671958 |
875cf2f9dfba7dd891455581857443bcef6492d9 | 152 | html | HTML | _includes/header.html | kgrons/Sandbox | 042e6bb80a0384ec025c332538c729c7b227e7ed | [
"MIT"
] | null | null | null | _includes/header.html | kgrons/Sandbox | 042e6bb80a0384ec025c332538c729c7b227e7ed | [
"MIT"
] | null | null | null | _includes/header.html | kgrons/Sandbox | 042e6bb80a0384ec025c332538c729c7b227e7ed | [
"MIT"
] | null | null | null | <header>
<span>
<a href="/"><img size="100%" class="img-responsive" class="center-block" src="/img/dlf-aig.png"/></a>
</span>
</header>
| 25.333333 | 109 | 0.559211 |
759a14715a44a9847dac1ec3a755b4fbbe4dec3e | 2,765 | c | C | software/Dave Beck's C interception server code for FileMakerPro/dataServer.c | BeckResearchLab/odin | 85af6f162e55142636c5bf7a38eb75d5f6b0a808 | [
"MIT"
] | null | null | null | software/Dave Beck's C interception server code for FileMakerPro/dataServer.c | BeckResearchLab/odin | 85af6f162e55142636c5bf7a38eb75d5f6b0a808 | [
"MIT"
] | null | null | null | software/Dave Beck's C interception server code for FileMakerPro/dataServer.c | BeckResearchLab/odin | 85af6f162e55142636c5bf7a38eb75d5f6b0a808 | [
"MIT"
] | 1 | 2021-04-05T19:50:51.000Z | 2021-04-05T19:50:51.000Z | /*******************************************************************************
** dataServer.c
** UDP packet logger as data logger for OD device
** David Andrew Crawford Beck
** dacb@uw.edu
** Original:
** Mon Apr 1 10:30:16 PDT 2013
** Modified: Nov 23 2018 Jessica Hardwicke
*******************************************************************************/
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h> /* memset */
#include "packet.h"
#define TIME_SIZE 64
int main(int argc, char *argv[]) {
// logging variables
FILE *fp;
time_t now;
struct tm* nowlocal;
unsigned int total_packets = 0, i;
char *log_file, time_text[TIME_SIZE];
packet_t p;
unsigned int port;
// UDP socket server variables
int sock_fd, rlen;
struct sockaddr_in servaddr, cliaddr;
socklen_t len;
// argument checking & handling
if (argc != 3) {
fprintf(stderr, "usage: %s <UDP port #> <output filename>\n", argv[0]);
exit(EXIT_FAILURE);
}
port = atoi(argv[1]);
log_file = argv[2];
if ((fp = fopen(log_file, "w")) == NULL) {
fprintf(stderr, "%s: unable to open output file '%s'\n", argv[0], log_file);
exit(EXIT_FAILURE);
}
// initial setup of logging
now = time(NULL);
nowlocal = localtime(&now);
strftime(time_text, TIME_SIZE, "%m/%d/%y %H:%M:%S %z", nowlocal);
fprintf(fp, "# %s - logging started at %s on UDP port %d\n", log_file, time_text, port);
fprintf(fp, "# time\terror_flag\tsequenceID");
for (i = 0; i < ADCs; ++i) {
fprintf(fp, "\tADC_%d", i);
}
fprintf(fp, "\n");
fflush(fp);
// initial setup of UDP server
sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(port);
bind(sock_fd, (struct sockaddr *)&servaddr, sizeof(servaddr));
len = sizeof(cliaddr);
fprintf(stderr, "UDP server listening on port %d\n", port);
// main capture loop
while (1) {
uint8_t error = 0;
rlen = recvfrom(sock_fd, &p, sizeof(packet_t), 0, (struct sockaddr *)&cliaddr, &len);
now = time(NULL);
nowlocal = localtime(&now);
++total_packets;
if (rlen != sizeof(packet_t)) {
fprintf(stderr, "%s: invalid packet received of size %d\n", argv[0], rlen);
memset(&p, 0, sizeof(packet_t));
error = 1;
}
// time, error flag, sequence ID, values
strftime(time_text, TIME_SIZE, "%m/%d/%y %H:%M:%S %z", nowlocal);
fprintf(fp, "%s\t%d\t%u", time_text, error, p.sequenceID);
for (i = 0; i < ADCs; ++i)
fprintf(fp, "\t%d", p.adc[i]);
fprintf(fp, "\n");
if (total_packets % 1000 == 0) fprintf(stderr, "%s: at %s - %d total packets received\n", argv[0], time_text, total_packets);
fflush(fp);
}
exit(EXIT_SUCCESS);
}
| 28.802083 | 127 | 0.616275 |
d9adc71b31dd99f15c97a734c914b78d9b784a2c | 1,159 | sql | SQL | students/y2337/Kolotushkin_Danil/Pr3.1/Movie_Rating.db.sql | kibarik/ITMO_FSPO_DataBases_2020-2021 | f6a1ee821efada82a873767d499fa5c89e747668 | [
"MIT"
] | 2 | 2020-10-20T13:38:23.000Z | 2021-03-20T10:09:46.000Z | students/y2337/Kolotushkin_Danil/Pr3.1/Movie_Rating.db.sql | kibarik/ITMO_FSPO_DataBases_2020-2021 | f6a1ee821efada82a873767d499fa5c89e747668 | [
"MIT"
] | 67 | 2020-09-08T15:27:18.000Z | 2021-10-18T08:46:41.000Z | students/y2337/Kolotushkin_Danil/Pr3.1/Movie_Rating.db.sql | kibarik/ITMO_FSPO_DataBases_2020-2021 | f6a1ee821efada82a873767d499fa5c89e747668 | [
"MIT"
] | 97 | 2020-09-08T12:26:53.000Z | 2021-09-22T13:02:50.000Z | BEGIN TRANSACTION;
CREATE TABLE IF NOT EXISTS "Reviewer" (
"rID" INTEGER NOT NULL UNIQUE,
"name" TEXT NOT NULL,
PRIMARY KEY("rID" AUTOINCREMENT)
);
CREATE TABLE IF NOT EXISTS "Movie" (
"mID" INTEGER NOT NULL UNIQUE,
"title" TEXT NOT NULL,
"year" DATE,
"director" TEXT NOT NULL,
PRIMARY KEY("mID" AUTOINCREMENT)
);
CREATE TABLE IF NOT EXISTS "Ratings" (
"rID" INTEGER NOT NULL,
"mID" INTEGER NOT NULL,
"stars" INTEGER NOT NULL,
"ratingDate" DATE NOT NULL,
FOREIGN KEY("mID") REFERENCES "Movie"("mID"),
FOREIGN KEY("rID") REFERENCES "Reviewer"("rID"),
PRIMARY KEY("rID","mID")
);
INSERT INTO "Reviewer" VALUES (1,'Sarah Martinez');
INSERT INTO "Reviewer" VALUES (2,'Daniel Lewis');
INSERT INTO "Reviewer" VALUES (3,'Jhon North');
INSERT INTO "Movie" VALUES (1,'Gone with The Wind',1939,'Victor Fleming');
INSERT INTO "Movie" VALUES (2,'Star Wars',1977,'George Lucas');
INSERT INTO "Movie" VALUES (3,'The Sound of Music',1965,'Robert Wise');
INSERT INTO "Movie" VALUES (4,'E.T.',1982,'Steven Spielberg');
INSERT INTO "Movie" VALUES (5,'Interstellar',2014,'Christopher Nolan');
INSERT INTO "Movie" VALUES (6,'Some title',NULL,'Director?');
COMMIT;
| 35.121212 | 74 | 0.704918 |
dc12fe3a72634b5363c218ab0b3d9830282fc7ea | 6,959 | py | Python | causalinference/core/propensity.py | youngminju-phd/Causalinference | 630e8fb195754a720da41791b725d3dadabfb257 | [
"BSD-3-Clause"
] | 392 | 2016-06-08T19:43:08.000Z | 2022-03-29T14:18:07.000Z | causalinference/core/propensity.py | youngminju-phd/Causalinference | 630e8fb195754a720da41791b725d3dadabfb257 | [
"BSD-3-Clause"
] | 12 | 2017-04-28T20:25:54.000Z | 2021-11-14T10:25:40.000Z | causalinference/core/propensity.py | youngminju-phd/Causalinference | 630e8fb195754a720da41791b725d3dadabfb257 | [
"BSD-3-Clause"
] | 82 | 2016-06-08T19:43:11.000Z | 2022-03-28T13:36:28.000Z | from __future__ import division
import numpy as np
from scipy.optimize import fmin_bfgs
from itertools import combinations_with_replacement
import causalinference.utils.tools as tools
from .data import Dict
class Propensity(Dict):
"""
Dictionary-like class containing propensity score data.
Propensity score related data includes estimated logistic regression
coefficients, maximized log-likelihood, predicted propensity scores,
and lists of the linear and quadratic terms that are included in the
logistic regression.
"""
def __init__(self, data, lin, qua):
Z = form_matrix(data['X'], lin, qua)
Z_c, Z_t = Z[data['controls']], Z[data['treated']]
beta = calc_coef(Z_c, Z_t)
self._data = data
self._dict = dict()
self._dict['lin'], self._dict['qua'] = lin, qua
self._dict['coef'] = beta
self._dict['loglike'] = -neg_loglike(beta, Z_c, Z_t)
self._dict['fitted'] = sigmoid(Z.dot(beta))
self._dict['se'] = calc_se(Z, self._dict['fitted'])
def __str__(self):
table_width = 80
coefs = self._dict['coef']
ses = self._dict['se']
output = '\n'
output += 'Estimated Parameters of Propensity Score\n\n'
entries1 = ['', 'Coef.', 'S.e.', 'z', 'P>|z|',
'[95% Conf. int.]']
entry_types1 = ['string']*6
col_spans1 = [1]*5 + [2]
output += tools.add_row(entries1, entry_types1,
col_spans1, table_width)
output += tools.add_line(table_width)
entries2 = tools.gen_reg_entries('Intercept', coefs[0], ses[0])
entry_types2 = ['string'] + ['float']*6
col_spans2 = [1]*7
output += tools.add_row(entries2, entry_types2,
col_spans2, table_width)
lin = self._dict['lin']
for (lin_term, coef, se) in zip(lin, coefs[1:], ses[1:]):
entries3 = tools.gen_reg_entries('X'+str(lin_term),
coef, se)
output += tools.add_row(entries3, entry_types2,
col_spans2, table_width)
qua = self._dict['qua']
lin_num = len(lin)+1 # including intercept
for (qua_term, coef, se) in zip(qua, coefs[lin_num:],
ses[lin_num:]):
name = 'X'+str(qua_term[0])+'*X'+str(qua_term[1])
entries4 = tools.gen_reg_entries(name, coef, se)
output += tools.add_row(entries4, entry_types2,
col_spans2, table_width)
return output
class PropensitySelect(Propensity):
"""
Dictionary-like class containing propensity score data.
Propensity score related data includes estimated logistic regression
coefficients, maximized log-likelihood, predicted propensity scores,
and lists of the linear and quadratic terms that are included in the
logistic regression.
"""
def __init__(self, data, lin_B, C_lin, C_qua):
X_c, X_t = data['X_c'], data['X_t']
lin = select_lin_terms(X_c, X_t, lin_B, C_lin)
qua = select_qua_terms(X_c, X_t, lin, C_qua)
super(PropensitySelect, self).__init__(data, lin, qua)
def form_matrix(X, lin, qua):
N, K = X.shape
mat = np.empty((N, 1+len(lin)+len(qua)))
mat[:, 0] = 1 # constant term
current_col = 1
if lin:
mat[:, current_col:current_col+len(lin)] = X[:, lin]
current_col += len(lin)
for term in qua: # qua is a list of tuples of column numbers
mat[:, current_col] = X[:, term[0]] * X[:, term[1]]
current_col += 1
return mat
def sigmoid(x, top_threshold=100, bottom_threshold=-100):
high_x = (x >= top_threshold)
low_x = (x <= bottom_threshold)
mid_x = ~(high_x | low_x)
values = np.empty(x.shape[0])
values[high_x] = 1.0
values[low_x] = 0.0
values[mid_x] = 1/(1+np.exp(-x[mid_x]))
return values
def log1exp(x, top_threshold=100, bottom_threshold=-100):
high_x = (x >= top_threshold)
low_x = (x <= bottom_threshold)
mid_x = ~(high_x | low_x)
values = np.empty(x.shape[0])
values[high_x] = 0.0
values[low_x] = -x[low_x]
values[mid_x] = np.log(1 + np.exp(-x[mid_x]))
return values
def neg_loglike(beta, X_c, X_t):
return log1exp(X_t.dot(beta)).sum() + log1exp(-X_c.dot(beta)).sum()
def neg_gradient(beta, X_c, X_t):
return (sigmoid(X_c.dot(beta))*X_c.T).sum(1) - \
(sigmoid(-X_t.dot(beta))*X_t.T).sum(1)
def calc_coef(X_c, X_t):
K = X_c.shape[1]
neg_ll = lambda b: neg_loglike(b, X_c, X_t)
neg_grad = lambda b: neg_gradient(b, X_c, X_t)
logit = fmin_bfgs(neg_ll, np.zeros(K), neg_grad,
full_output=True, disp=False)
return logit[0]
def calc_se(X, phat):
H = np.dot(phat*(1-phat)*X.T, X)
return np.sqrt(np.diag(np.linalg.inv(H)))
def get_excluded_lin(K, included):
included_set = set(included)
return [x for x in range(K) if x not in included_set]
def get_excluded_qua(lin, included):
whole_set = list(combinations_with_replacement(lin, 2))
included_set = set(included)
return [x for x in whole_set if x not in included_set]
def calc_loglike(X_c, X_t, lin, qua):
Z_c = form_matrix(X_c, lin, qua)
Z_t = form_matrix(X_t, lin, qua)
beta = calc_coef(Z_c, Z_t)
return -neg_loglike(beta, Z_c, Z_t)
def select_lin(X_c, X_t, lin_B, C_lin):
# Selects, through a sequence of likelihood ratio tests, the
# variables that should be included linearly in propensity
# score estimation.
K = X_c.shape[1]
excluded = get_excluded_lin(K, lin_B)
if excluded == []:
return lin_B
ll_null = calc_loglike(X_c, X_t, lin_B, [])
def lr_stat_lin(lin_term):
ll_alt = calc_loglike(X_c, X_t, lin_B+[lin_term], [])
return 2 * (ll_alt - ll_null)
lr_stats = np.array([lr_stat_lin(term) for term in excluded])
argmax_lr = lr_stats.argmax()
if lr_stats[argmax_lr] < C_lin:
return lin_B
else:
new_term = [excluded[argmax_lr]]
return select_lin(X_c, X_t, lin_B+new_term, C_lin)
def select_lin_terms(X_c, X_t, lin_B, C_lin):
# Mostly a wrapper around function select_lin to handle cases that
# require little computation.
if C_lin <= 0:
K = X_c.shape[1]
return lin_B + get_excluded_lin(K, lin_B)
elif C_lin == np.inf:
return lin_B
else:
return select_lin(X_c, X_t, lin_B, C_lin)
def select_qua(X_c, X_t, lin, qua_B, C_qua):
# Selects, through a sequence of likelihood ratio tests, the
# variables that should be included quadratically in propensity
# score estimation.
excluded = get_excluded_qua(lin, qua_B)
if excluded == []:
return qua_B
ll_null = calc_loglike(X_c, X_t, lin, qua_B)
def lr_stat_qua(qua_term):
ll_alt = calc_loglike(X_c, X_t, lin, qua_B+[qua_term])
return 2 * (ll_alt - ll_null)
lr_stats = np.array([lr_stat_qua(term) for term in excluded])
argmax_lr = lr_stats.argmax()
if lr_stats[argmax_lr] < C_qua:
return qua_B
else:
new_term = [excluded[argmax_lr]]
return select_qua(X_c, X_t, lin, qua_B+new_term, C_qua)
def select_qua_terms(X_c, X_t, lin, C_qua):
# Mostly a wrapper around function select_qua to handle cases that
# require little computation.
if lin == []:
return []
if C_qua <= 0:
return get_excluded_qua(lin, [])
elif C_qua == np.inf:
return []
else:
return select_qua(X_c, X_t, lin, [], C_qua)
| 24.765125 | 69 | 0.674522 |