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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
79bd6d51da05a57dc45fc6179ce4f81626eaa618
| 115
|
php
|
PHP
|
app/Modelos/CiudadModel.php
|
piperodriguez/disponibilidad
|
ab26c100e1a13f5d9d0f5c566aa7d94e0713c28f
|
[
"MIT"
] | null | null | null |
app/Modelos/CiudadModel.php
|
piperodriguez/disponibilidad
|
ab26c100e1a13f5d9d0f5c566aa7d94e0713c28f
|
[
"MIT"
] | 5
|
2021-03-09T22:58:07.000Z
|
2022-02-26T20:04:59.000Z
|
app/Modelos/CiudadModel.php
|
piperodriguez/disponibilidad
|
ab26c100e1a13f5d9d0f5c566aa7d94e0713c28f
|
[
"MIT"
] | null | null | null |
<?php
namespace App\Modelos;
use Illuminate\Database\Eloquent\Model;
class CiudadModel extends Model
{
//
}
| 10.454545
| 39
| 0.730435
|
82ecfa7982bb07c1dc18058e8d2a5c81acc9c752
| 5,406
|
kt
|
Kotlin
|
omisego-core/src/test/kotlin/co/omisego/omisego/custom/retrofit2/adapter/OMGCallbackWrapperTest.kt
|
omgnetwork/android-sdk
|
de12e344d6437b9c23df35d158fb247bac6c8055
|
[
"Apache-2.0"
] | 21
|
2018-02-28T07:38:47.000Z
|
2018-12-01T22:54:53.000Z
|
omisego-core/src/test/kotlin/co/omisego/omisego/custom/retrofit2/adapter/OMGCallbackWrapperTest.kt
|
omgnetwork/android-sdk
|
de12e344d6437b9c23df35d158fb247bac6c8055
|
[
"Apache-2.0"
] | 26
|
2018-03-01T04:38:10.000Z
|
2018-12-11T08:09:47.000Z
|
omisego-core/src/test/kotlin/co/omisego/omisego/custom/retrofit2/adapter/OMGCallbackWrapperTest.kt
|
omisego/android-sdk
|
de12e344d6437b9c23df35d158fb247bac6c8055
|
[
"Apache-2.0"
] | 7
|
2018-02-28T07:35:24.000Z
|
2019-05-18T15:04:21.000Z
|
package co.omisego.omisego.custom.retrofit2.adapter
/*
* OmiseGO
*
*
* Created by Phuchit Sirimongkolsathien on 14/3/2018 AD.
* Copyright © 2017-2018 OmiseGO. All rights reserved.
*/
import co.omisego.omisego.constant.Versions
import co.omisego.omisego.constant.enums.ErrorCode
import co.omisego.omisego.custom.OMGCallback
import co.omisego.omisego.exception.OMGAPIErrorException
import co.omisego.omisego.helpers.delegation.GsonDelegator
import co.omisego.omisego.helpers.delegation.ResourceFile
import co.omisego.omisego.model.APIError
import co.omisego.omisego.model.OMGResponse
import co.omisego.omisego.model.User
import com.google.gson.reflect.TypeToken
import com.nhaarman.mockito_kotlin.times
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.verifyNoMoreInteractions
import okhttp3.MediaType
import okhttp3.ResponseBody
import org.amshove.kluent.mock
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.junit.MockitoJUnitRunner
import retrofit2.Call
import retrofit2.Response
import java.io.File
import java.io.IOException
import java.util.concurrent.Executor
@RunWith(MockitoJUnitRunner::class)
class OMGCallbackWrapperTest : GsonDelegator() {
private val userFile: File by ResourceFile("user.json")
private val errorFile: File by ResourceFile("error-invalid_auth.json")
private lateinit var sampleUser: User
private lateinit var sampleError: APIError
private lateinit var userResult: Response<OMGResponse<User>>
private lateinit var mockCall: Call<OMGResponse<User>>
private lateinit var mockOMGCallback: OMGCallback<User>
private lateinit var callback: OMGCallbackWrapper<User>
@Before
fun setup() {
mockCall = mock()
mockOMGCallback = mock()
val executor = Executor { it.run() }
callback = OMGCallbackWrapper(mockOMGCallback, executor)
sampleUser = gson.fromJson<OMGResponse<User>>(userFile.readText(),
object : TypeToken<OMGResponse<User>>() {}.type).data
sampleError = gson.fromJson<OMGResponse<APIError>>(errorFile.readText(),
object : TypeToken<OMGResponse<APIError>>() {}.type).data
userResult = Response.success(OMGResponse(Versions.EWALLET_API, true, sampleUser))
}
@Test
fun `OMGCallbackWrapper delegates OMGAPIErrorException to the failed callback successfully`() {
val expectedError = OMGResponse(Versions.EWALLET_API, false, sampleError)
val throwable = OMGAPIErrorException(expectedError)
callback.onFailure(mockCall, throwable)
verify(mockOMGCallback, times(1)).fail(expectedError)
verifyNoMoreInteractions(mockOMGCallback)
}
@Test
fun `OMGCallbackWrapper delegates network error to the failed callback successfully`() {
val errorMsg = "Request timeout."
val throwable = IOException(errorMsg)
val expectedError = OMGResponse(Versions.EWALLET_API, false, APIError(ErrorCode.SDK_NETWORK_ERROR, errorMsg))
callback.onFailure(mockCall, throwable)
verify(mockOMGCallback, times(1)).fail(expectedError)
verifyNoMoreInteractions(mockOMGCallback)
}
@Test
fun `OMGCallbackWrapper delegates the successful response to the success callback successfully`() {
val expectedUser = OMGResponse(Versions.EWALLET_API, true, sampleUser)
callback.onResponse(mockCall, userResult)
verify(mockOMGCallback, times(1)).success(expectedUser)
verifyNoMoreInteractions(mockOMGCallback)
}
@Test
fun `OMGCallbackWrapper delegates the server 500 error to the failed callback successfully`() {
val errorResponse = Response.error<OMGResponse<User>>(500, mock(ResponseBody::class))
val expectedResponse = OMGResponse(Versions.EWALLET_API, false,
APIError(ErrorCode.SERVER_INTERNAL_SERVER_ERROR,
"The EWallet API was 500 Internal Server Error"))
callback.onResponse(mockCall, errorResponse)
verify(mockOMGCallback, times(1)).fail(expectedResponse)
verifyNoMoreInteractions(mockOMGCallback)
}
@Test
fun `OMGCallbackWrapper delegates the unexpected error to the failed callback successfully`() {
val response: Response<OMGResponse<User>> = Response.success(null)
val expectedResponse = OMGResponse(Versions.EWALLET_API, false,
APIError(ErrorCode.SDK_UNEXPECTED_ERROR,
"Unexpected Error"))
callback.onResponse(mockCall, response)
verify(mockOMGCallback, times(1)).fail(expectedResponse)
verifyNoMoreInteractions(mockOMGCallback)
}
@Test
fun `OMGCallbackWrapper delegates the server unknown error to the failed callback successfully`() {
val json = MediaType.parse("application/json")
val responseText = "A bug is never just a mistake. It represents something bigger."
val body = ResponseBody.create(json, responseText)
val response: Response<OMGResponse<User>> = Response.error(400, body)
val expectedResponse = OMGResponse(Versions.EWALLET_API, false,
APIError(ErrorCode.SERVER_UNKNOWN_ERROR, responseText))
callback.onResponse(mockCall, response)
verify(mockOMGCallback, times(1)).fail(expectedResponse)
verifyNoMoreInteractions(mockOMGCallback)
}
}
| 39.459854
| 117
| 0.736219
|
bff277a2bf20dfb579ebb64a75f52f485b33d481
| 2,482
|
lua
|
Lua
|
lua/ds1820_mqtt_mokki.lua
|
calmjm/esp8266
|
5a99a279d41808784006d9f86801cc676a89cfe7
|
[
"Apache-2.0"
] | null | null | null |
lua/ds1820_mqtt_mokki.lua
|
calmjm/esp8266
|
5a99a279d41808784006d9f86801cc676a89cfe7
|
[
"Apache-2.0"
] | null | null | null |
lua/ds1820_mqtt_mokki.lua
|
calmjm/esp8266
|
5a99a279d41808784006d9f86801cc676a89cfe7
|
[
"Apache-2.0"
] | null | null | null |
IO_PIN = 3 -- gpio0
DS_PIN = 2 -- gpio4
ws2812.init() -- gpio2
t = require('modds18b20')
state = 0
timer_round = 0
fade_round = 0
buffer = ws2812.newBuffer(15, 3)
buffer:fill(0, 0, 0)
ws2812.write(buffer)
function start_timer()
for i=1, 15 do
buffer:set(i, 100, 100, 100)
end
ws2812.write(buffer)
tmr.alarm(1, 1000, tmr.ALARM_AUTO, function()
print('ON timer round ' .. timer_round)
for i=1, 15 do
if i == timer_round then
buffer:set(i, 0, 0, 0)
ws2812.write(buffer)
end
end
timer_round = timer_round + 1
if timer_round == 16 then
print("Swithcing OFF")
gpio.write(IO_PIN, gpio.LOW)
state = 0
stop_timer()
end
end)
end
function stop_timer()
tmr.unregister(1)
fade_round = 0
tmr.alarm(2, 50, tmr.ALARM_AUTO, function()
buffer:fade(2)
ws2812.write(buffer)
fade_round = fade_round + 1
if fade_round == 8 then
tmr.unregister(2)
end
end)
end
if adc.force_init_mode(adc.INIT_VDD33)
then
node.restart()
return
end
print("System voltage (mV):", adc.readvdd33())
t.setup(DS_PIN)
addrs = t.addrs()
for i=1, table.getn(addrs) do print(t.read(addrs[i])) end
m = mqtt.Client("esp2", 120)
m:on("connect", function(con)
print ("Connected")
m:subscribe("trigger", 0, function(conn) print("trigger subscribe success") end)
end)
m:on("offline", function(con)
print ("Offline")
node.restart()
end)
m:on("message", function(conn, topic, data)
print(topic .. ":" )
if data ~= nil then
if state == 0 then
print("Switching ON")
gpio.write(IO_PIN, gpio.HIGH)
state = 1
timer_round = 1
start_timer()
else
print("Swithcing OFF")
gpio.write(IO_PIN, gpio.LOW)
state = 0
stop_timer()
end
end
end)
m:connect("192.168.2.1", 1883, 0, 1,
function(client)
print("Connected to MQTT")
m:subscribe("trigger", 0, function(conn) print("trigger subscribe success") end)
end,
function(client, reason)
print("Failed to connect, reason: " .. reason)
node.restart()
end)
tmr.alarm(0, 60000, 1, function()
print('Measuring..')
output ="esp3: "
for i=1, table.getn(addrs) do
output = output .. t.read(addrs[i]) .. " "
end
vcc = adc.readvdd33()
rssi = wifi.sta.getrssi()
output = output .. " " .. vcc .. " " .. rssi .. " " .. state
print(output)
m:publish("mokkimittaukset", output, 2, 0, function(conn)
print("sent")
end)
end)
| 22.36036
| 85
| 0.614827
|
0d545d1ad9dcad5fbcdd0ba5b9d880ba0243933a
| 3,587
|
h
|
C
|
src/openalpha/logger.h
|
caoruicn/openalpha
|
3a61ddfef01ce179b24685c4144c05144bbd0a92
|
[
"Apache-2.0"
] | 3
|
2021-11-08T23:15:00.000Z
|
2022-02-24T10:36:43.000Z
|
src/openalpha/logger.h
|
caoruicn/openalpha
|
3a61ddfef01ce179b24685c4144c05144bbd0a92
|
[
"Apache-2.0"
] | null | null | null |
src/openalpha/logger.h
|
caoruicn/openalpha
|
3a61ddfef01ce179b24685c4144c05144bbd0a92
|
[
"Apache-2.0"
] | 2
|
2022-02-19T17:29:22.000Z
|
2022-02-24T07:37:57.000Z
|
#ifndef OPENALPHA_LOGGER_H_
#define OPENALPHA_LOGGER_H_
#include <log4cxx/basicconfigurator.h>
#include <log4cxx/logger.h>
#include <log4cxx/propertyconfigurator.h>
#include <unistd.h>
namespace openalpha {
class Logger {
public:
static auto Get(const std::string& name) {
return log4cxx::Logger::getLogger(name);
}
static void Initialize(const std::string& name,
const std::string& config_file) {
Logger::config_file = config_file;
if (!config_file.empty())
log4cxx::PropertyConfigurator::configure(config_file);
else
log4cxx::BasicConfigurator::configure();
if (!name.empty()) logger = Get(name);
}
inline static auto logger = log4cxx::Logger::getRootLogger();
inline static std::string config_file;
};
inline const char* kDefaultLogConf = R"(
log4j.rootLogger=debug, stdout_debug
log4j.logger.openalpha=debug, stdout, openalpha
log4j.additivity.openalpha=false # not inherit appender from parent
log4j.logger.sql=debug, sql
log4j.additivity.sql=false # not inherit appender from parent
log4j.appender.stdout_debug.Threshold=debug
log4j.appender.stdout_debug=org.apache.log4j.ConsoleAppender
log4j.appender.stdout_debug.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout_debug.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p - %m%n
log4j.appender.stdout.Threshold=info
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p - %m%n
log4j.appender.openalpha=org.apache.log4j.RollingFileAppender
log4j.appender.openalpha.rollingPolicy=org.apache.log4j.rolling.TimeBasedRollingPolicy
log4j.appender.openalpha.rollingPolicy.FileNamePattern=logs/openalpha.%d{yyyy-MM-dd}.log
log4j.appender.openalpha.rollingPolicy.ActiveFileName=logs/openalpha.log
log4j.appender.openalpha.File=logs/openalpha.log
log4j.appender.openalpha.Append=true
log4j.appender.openalpha.MaxFileSize=100MB
log4j.appender.openalpha.MaxBackupIndex=10
log4j.appender.openalpha.layout=org.apache.log4j.PatternLayout
log4j.appender.openalpha.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p - %m%n
log4j.appender.sql=org.apache.log4j.RollingFileAppender
log4j.appender.sql.rollingPolicy=org.apache.log4j.rolling.TimeBasedRollingPolicy
log4j.appender.sql.rollingPolicy.FileNamePattern=logs/sql.%d{yyyy-MM-dd}.log
log4j.appender.sql.rollingPolicy.ActiveFileName=logs/sql.log
log4j.appender.sql.File=logs/sql.log
log4j.appender.sql.Append=true
log4j.appender.sql.MaxFileSize=100MB
log4j.appender.sql.MaxBackupIndex=10
log4j.appender.sql.layout=org.apache.log4j.PatternLayout
log4j.appender.sql.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p - %m%n
)";
} // namespace openalpha
#define LOG_TRACE(msg) LOG4CXX_TRACE(openalpha::Logger::logger, msg)
#define LOG_DEBUG(msg) LOG4CXX_DEBUG(openalpha::Logger::logger, msg)
#define LOG_INFO(msg) LOG4CXX_INFO(openalpha::Logger::logger, msg)
#define LOG_WARN(msg) LOG4CXX_WARN(openalpha::Logger::logger, msg)
#define LOG_ERROR(msg) LOG4CXX_ERROR(openalpha::Logger::logger, msg)
#define LOG_FATAL(msg) \
{ \
LOG4CXX_FATAL(openalpha::Logger::logger, msg); \
/* to-do: safe exit */ \
if (system(("kill -9 " + std::to_string(getpid())).c_str())) { \
} \
}
#endif // OPENALPHA_LOGGER_H_
| 41.229885
| 91
| 0.731809
|
8626d6412eb29ab679f9dacd818ed0f0fc2237c4
| 194
|
rb
|
Ruby
|
spec/spec_helper.rb
|
timuruski/graceful_shutdown
|
b51e907ca40fda1e348c9e676d8a241ca937dbf2
|
[
"MIT"
] | 3
|
2015-05-12T19:29:36.000Z
|
2017-11-09T17:49:58.000Z
|
spec/spec_helper.rb
|
timuruski/graceful_shutdown
|
b51e907ca40fda1e348c9e676d8a241ca937dbf2
|
[
"MIT"
] | null | null | null |
spec/spec_helper.rb
|
timuruski/graceful_shutdown
|
b51e907ca40fda1e348c9e676d8a241ca937dbf2
|
[
"MIT"
] | null | null | null |
$LOAD_PATH.unshift File.expand_path('../lib')
require 'rspec'
require 'ruby_block'
RSpec.configure do |conf|
conf.formatter = 'documentation'
conf.color = true
conf.order = 'random'
end
| 17.636364
| 45
| 0.721649
|
be9b80ee7b15cb33bfc71102ac93a08733f63aed
| 1,499
|
ts
|
TypeScript
|
src/converter.ts
|
sbip-sg/typescriptllvm
|
42621774352f55b1d23a5ab5678201b0e5d19085
|
[
"Apache-2.0"
] | 4
|
2022-01-21T05:07:24.000Z
|
2022-03-15T12:43:20.000Z
|
src/converter.ts
|
sbip-sg/tsll
|
42621774352f55b1d23a5ab5678201b0e5d19085
|
[
"Apache-2.0"
] | 11
|
2021-11-23T01:02:21.000Z
|
2022-03-03T09:54:05.000Z
|
src/converter.ts
|
sbip-sg/typescriptllvm
|
42621774352f55b1d23a5ab5678201b0e5d19085
|
[
"Apache-2.0"
] | null | null | null |
import ts from 'typescript';
import { Visitor } from './core/ast/visitor';
import { Builder } from './core/ir/builder';
import { Debugger } from './core/ir/debugger';
import { Scope } from './common/scope';
export function convert(files: string[], emitIR: boolean, bitcodeOutput?: string) {
const program = ts.createProgram(files, {
target: ts.ScriptTarget.ES5
});
// Make sure all the declared dependencies have been analysed before our main source files.
// const fileSet = new Set(files);
// for (const srcFile of program.getSourceFiles()) {
// if (!fileSet.has(srcFile.fileName))
// }
const diagnostics = ts.getPreEmitDiagnostics(program);
// Print out diagnostic messages
for (const diagnosis of diagnostics) {
console.log(diagnosis.messageText.toString());
}
if (diagnostics.length > 0) return;
for (const file of files) {
const srcFile = program.getSourceFile(file);
if (srcFile === undefined) continue;
const names = file.trim().split('/');
const moduleId = names[names.length - 1];
const irBuilder = new Builder(moduleId);
const irDebugger = new Debugger(srcFile, irBuilder);
let scope = new Scope(program);
let visitor = Visitor.getVisitor(irBuilder, irDebugger);
visitor.visitSourceFile(srcFile, scope);
if (emitIR) irBuilder.printIR();
// if (bitcodeOutput !== undefined) irBuilder.toBitcodeFile(bitcodeOutput);
}
}
| 36.560976
| 95
| 0.655103
|
20b70ae93142441d24f3ca831a12fc7819e85c9d
| 467
|
cs
|
C#
|
src/Cake.OpenApiGenerator/Maven/IWebClient.cs
|
lukoerfer/cake-codegen-openapi
|
d5760330a13acf7ef64fd7ef64c6928b0be40124
|
[
"MIT"
] | 3
|
2021-05-12T15:00:16.000Z
|
2022-03-05T12:24:33.000Z
|
src/Cake.OpenApiGenerator/Maven/IWebClient.cs
|
lukoerfer/cake-codegen-openapi
|
d5760330a13acf7ef64fd7ef64c6928b0be40124
|
[
"MIT"
] | 3
|
2019-08-01T20:19:59.000Z
|
2020-01-29T18:40:23.000Z
|
src/Cake.OpenApiGenerator/Maven/IWebClient.cs
|
lukoerfer/cake-openapi-generator
|
d5760330a13acf7ef64fd7ef64c6928b0be40124
|
[
"MIT"
] | 1
|
2020-01-27T13:12:38.000Z
|
2020-01-27T13:12:38.000Z
|
using System.IO;
namespace Cake.OpenApiGenerator.Maven
{
/// <summary>
/// Encapsulates the functionality to read resources from the web
/// </summary>
public interface IWebClient
{
/// <summary>
/// Opens a stream that reads from a resource
/// </summary>
/// <param name="path">A resource path</param>
/// <returns>The resource content as stream</returns>
Stream OpenRead(string path);
}
}
| 24.578947
| 69
| 0.603854
|
fd49611f1c0cc5cc940fd49cc02246594b80a9b0
| 3,255
|
h
|
C
|
Foundation/NSNumber/NSNumber.h
|
HinTak/darling-cocotron
|
1a430280c118c75b5256195aef8579cfb350af79
|
[
"MIT"
] | null | null | null |
Foundation/NSNumber/NSNumber.h
|
HinTak/darling-cocotron
|
1a430280c118c75b5256195aef8579cfb350af79
|
[
"MIT"
] | null | null | null |
Foundation/NSNumber/NSNumber.h
|
HinTak/darling-cocotron
|
1a430280c118c75b5256195aef8579cfb350af79
|
[
"MIT"
] | 1
|
2021-06-29T03:09:28.000Z
|
2021-06-29T03:09:28.000Z
|
/* Copyright (c) 2006-2007 Christopher J. W. Lloyd
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. */
#import <Foundation/NSDecimal.h>
#import <Foundation/NSValue.h>
@class NSDictionary;
@interface NSNumber : NSValue
- initWithBool: (BOOL) value;
- initWithChar: (char) value;
- initWithShort: (short) value;
- initWithInt: (int) value;
- initWithLong: (long) value;
- initWithLongLong: (long long) value;
- initWithFloat: (float) value;
- initWithDouble: (double) value;
- initWithInteger: (NSInteger) value;
- initWithUnsignedChar: (unsigned char) value;
- initWithUnsignedShort: (unsigned short) value;
- initWithUnsignedInt: (unsigned int) value;
- initWithUnsignedLong: (unsigned long) value;
- initWithUnsignedLongLong: (unsigned long long) value;
- initWithUnsignedInteger: (NSUInteger) value;
+ (NSNumber *) numberWithBool: (BOOL) value;
+ (NSNumber *) numberWithChar: (char) value;
+ (NSNumber *) numberWithShort: (short) value;
+ (NSNumber *) numberWithInt: (int) value;
+ (NSNumber *) numberWithLong: (long) value;
+ (NSNumber *) numberWithLongLong: (long long) value;
+ (NSNumber *) numberWithFloat: (float) value;
+ (NSNumber *) numberWithDouble: (double) value;
+ (NSNumber *) numberWithInteger: (NSInteger) value;
+ (NSNumber *) numberWithUnsignedChar: (unsigned char) value;
+ (NSNumber *) numberWithUnsignedShort: (unsigned short) value;
+ (NSNumber *) numberWithUnsignedInt: (unsigned int) value;
+ (NSNumber *) numberWithUnsignedLong: (unsigned long) value;
+ (NSNumber *) numberWithUnsignedLongLong: (unsigned long long) value;
+ (NSNumber *) numberWithUnsignedInteger: (NSUInteger) value;
- (NSComparisonResult) compare: (NSNumber *) other;
- (BOOL) isEqualToNumber: (NSNumber *) other;
- (char) charValue;
- (short) shortValue;
- (int) intValue;
- (long) longValue;
- (long long) longLongValue;
- (float) floatValue;
- (double) doubleValue;
- (BOOL) boolValue;
- (NSDecimal) decimalValue;
- (NSInteger) integerValue;
- (unsigned char) unsignedCharValue;
- (unsigned short) unsignedShortValue;
- (unsigned int) unsignedIntValue;
- (unsigned long) unsignedLongValue;
- (unsigned long long) unsignedLongLongValue;
- (NSUInteger) unsignedIntegerValue;
- (NSString *) stringValue;
- (NSString *) descriptionWithLocale: (NSDictionary *) locale;
@end
| 37.413793
| 80
| 0.758525
|
b5b38eb4569b0b08df73d312e738777704a3676e
| 45
|
rb
|
Ruby
|
lib/openfoodfacts/version.rb
|
openfoodfacts/openfoodfacts-ruby
|
4df0e128716878096fdb08d549234cd3c9142b8e
|
[
"MIT"
] | 26
|
2015-05-18T18:56:08.000Z
|
2022-03-02T20:10:38.000Z
|
lib/openfoodfacts/version.rb
|
openfoodfacts/openfoodfacts-ruby
|
4df0e128716878096fdb08d549234cd3c9142b8e
|
[
"MIT"
] | 21
|
2015-05-21T09:53:11.000Z
|
2022-03-02T12:29:45.000Z
|
lib/openfoodfacts/version.rb
|
openfoodfacts/openfoodfacts-ruby
|
4df0e128716878096fdb08d549234cd3c9142b8e
|
[
"MIT"
] | 13
|
2015-05-21T13:34:56.000Z
|
2022-02-02T14:21:57.000Z
|
module Openfoodfacts
VERSION = "0.6.0"
end
| 11.25
| 20
| 0.711111
|
ed3547ae68efe2ead19a34eac16ce984d54f7d9f
| 16,262
|
h
|
C
|
ClothSim/Cloth.h
|
henry9836/ClothSim
|
b609340117abad318f3812c5f6f9fc5ab41c0088
|
[
"MIT"
] | null | null | null |
ClothSim/Cloth.h
|
henry9836/ClothSim
|
b609340117abad318f3812c5f6f9fc5ab41c0088
|
[
"MIT"
] | null | null | null |
ClothSim/Cloth.h
|
henry9836/ClothSim
|
b609340117abad318f3812c5f6f9fc5ab41c0088
|
[
"MIT"
] | 2
|
2020-01-23T17:26:46.000Z
|
2020-04-12T20:22:18.000Z
|
#pragma once
#include <iostream>
#include <glew.h>
#include <freeglut.h>
#include <SOIL.h>
#include <glm.hpp>
#include <gtc/matrix_transform.hpp>
#include <gtc/type_ptr.hpp>
#include <ft2build.h>
#include FT_FREETYPE_H
#include "ConsoleController.h"
#include "Util.h"
#include "SimpleObjects.h"
const glm::vec3 zVector = glm::vec3(0, 0, 0);
struct clothNode {
protected:
const float phyStep = 0.25f;
public:
bool staticNode = false;
float mass = 10.0f;
float damping = 0.01f;
glm::vec3 spawnPos = glm::vec3(0, 0, 0);
glm::vec3 position = glm::vec3(0, 0, 0);
glm::vec3 oldPosition = glm::vec3(0, 0, 0);
glm::vec3 acceleration = glm::vec3(0, 0, 0);
glm::vec3 normal = glm::vec3(0, 0, 0); //Used for shading
clothNode();
clothNode(glm::vec3 pos) {
spawnPos = pos;
position = pos;
oldPosition = pos;
};
void Reset() {
position = spawnPos;
oldPosition = spawnPos;
acceleration = zVector;
damping = 0.01f;
}
void addForce(glm::vec3 force, float groundLevel)
{
//Check if on ground
if (position.y < groundLevel) {
//if we are get rid of the y force
force.y = 0.0f;
}
acceleration += force / mass;
};
void Tick(float deltaTime, float groundLevel) {
//Are we below the ground?
if (position.y < groundLevel) {
//put us back on the ground
position.y = groundLevel;
acceleration.y = 0;
}
//If moveable
if (!staticNode) {
//Are we on ground?
if (position.y > groundLevel) {
glm::vec3 _p = position;
position = position + (position - oldPosition) * (1.0f - damping) + acceleration * phyStep;
oldPosition = _p;
acceleration = zVector;
}
else {
//acceleration = zVector;
acceleration.y = 0;
}
}
}
void moveBy(glm::vec3 pos) {
if (!staticNode) {
position += pos;
}
}
};
struct clothConstraint {
public:
float stableDistance = 0.0f;
float currDistance = 0.0f;
float tearDistance = 10.0f;
bool torn = false;
clothNode* p1 = nullptr;
clothNode* p2 = nullptr;
clothConstraint(clothNode* _p1, clothNode* _p2) {
p1 = _p1;
p2 = _p2;
stableDistance = glm::length(glm::vec3(p2->position - p1->position));
tearDistance = stableDistance * 7.0f;
}
~clothConstraint() {
delete p1;
delete p2;
}
glm::vec4 FindStress() {
//white - red
//good - extreme stress
//1.0f - 0.0f
float stress = 1.0f;
//Find current distance between the points
glm::vec3 direction = p2->position - p1->position; //get direction from p2 to p1
currDistance = glm::length(direction); //get the distance between the points
//If we are torn
if ((currDistance > tearDistance) || torn) {
return glm::vec4(0.0f, 0.0f, 0.0f, 0.0f);
}
//Find how much stress we are under
stress = ((currDistance / tearDistance)-1)*-1;
//Return a color
return glm::vec4(1.0f, stress, stress, 1.0f);
}
void Reset() {
stableDistance = glm::length(glm::vec3(p2->position - p1->position));
tearDistance = stableDistance * 10.0f;
torn = false;
}
void Tick(float deltaTime) {
//Tear constraint if we go beyond our tear distance
if (currDistance > tearDistance) {
torn = true;
}
glm::vec3 direction = p2->position - p1->position; //get direction from p2 to p1
currDistance = glm::length(direction); //get the distance between the points
glm::vec3 corrVec = (direction * (1 - stableDistance / currDistance)) * 0.5f; //find the vector to move the points towards each other if they are stretching
//If the cloth is not torn
if (!torn) {
p1->moveBy(corrVec);
p2->moveBy(-corrVec);
}
}
};
class Cloth {
public:
~Cloth() {
}
Cloth(glm::vec2 _size, float _scaleFactor, float _gL) {
Console_OutputLog(to_wstring("Creating Cloth Object Of Size: " + to_string(_size.x) + ":" + to_string(_size.y)), LOGINFO);
groundLevel = _gL;
//set size of cloth
size = _size;
this->scaleFactor = _scaleFactor;
//resize vectors to size
clothNodes.resize((unsigned int) size.y);
//Generate nodes
Console_OutputLog(L"Creating Cloth Nodes", LOGINFO);
for (size_t y = 0; y < size.y; y++)
{
for (size_t x = 0; x < size.x; x++)
{
clothNodes.at(y).push_back(new clothNode(glm::vec3(x,y,0)*scaleFactor));
}
}
//Connect nodes
Console_OutputLog(L"Connecting Cloth Nodes", LOGINFO);
for (size_t y = 0; y < size.y-1; y++)
{
for (size_t x = 0; x < size.x-1; x++)
{
//A---B
//| / |
//C---D
//A-B
clothConstraints.push_back(new clothConstraint(clothNodes.at(y).at(x), clothNodes.at(y).at(x + 1)));
//B-C
clothConstraints.push_back(new clothConstraint(clothNodes.at(y).at(x + 1), clothNodes.at(y + 1).at(x)));
//C-A
clothConstraints.push_back(new clothConstraint(clothNodes.at(y + 1).at(x), clothNodes.at(y).at(x)));
//B-D
clothConstraints.push_back(new clothConstraint(clothNodes.at(y).at(x + 1), clothNodes.at(y + 1).at(x + 1)));
//D-C
clothConstraints.push_back(new clothConstraint(clothNodes.at(y + 1).at(x + 1), clothNodes.at(y + 1).at(x)));
//C-B
clothConstraints.push_back(new clothConstraint(clothNodes.at(y + 1).at(x), clothNodes.at(y).at(x + 1)));
}
}
//Static Nodes
Console_OutputLog(L"Setting Static Cloth Nodes", LOGINFO);
for (size_t i = 0; i < size.x; i++)
{
clothNodes.at(((unsigned int)size.y)-1).at(i)->staticNode = true;
}
Console_OutputLog(L"Created Cloth Object", LOGINFO);
}
glm::vec3 calcNormalSection(clothNode* p1, clothNode* p2, clothNode* p3)
{
glm::vec3 v1 = p2->position - p1->position;
glm::vec3 v2 = p3->position - p1->position;
return glm::cross(v1, v2);
}
void calcNormals() {
//reset normals
for (size_t y = 0; y < size.y; y++)
{
for (size_t x = 0; x < size.x; x++)
{
clothNodes.at(y).at(x)->normal = zVector;
}
}
for (size_t y = 0; y < size.y - 1; y++)
{
for (size_t x = 0; x < size.x - 1; x++)
{
//A---B
//| / |
//C---D
//A-B-C
glm::vec3 normal = calcNormalSection(clothNodes.at(y).at(x), clothNodes.at(y).at(x + 1), clothNodes.at(y + 1).at(x));
clothNodes.at(y).at(x)->normal += normal;
clothNodes.at(y).at(x + 1)->normal += normal;
clothNodes.at(y + 1).at(x)->normal += normal;
//B-D-C
normal = calcNormalSection(clothNodes.at(y).at(x + 1), clothNodes.at(y + 1).at(x + 1), clothNodes.at(y + 1).at(x));
clothNodes.at(y).at(x + 1)->normal += normal;
clothNodes.at(y + 1).at(x + 1)->normal += normal;
clothNodes.at(y + 1).at(x)->normal += normal;
}
}
}
void Render() {
calcNormals();
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glBegin(GL_LINES);
//Color
//glColor3f(1.0f, 1.0f, 1.0f);
int i = 0;
for (size_t y = 0; y < size.y - 1; y++)
{
for (size_t x = 0; x < size.x - 1; x++)
{
//Draw vertex and normals
//A---B
//| / |
//C---D
//Color
glm::vec4 color = clothConstraints.at(i)->FindStress();
glColor4f(color.x, color.y, color.z, color.w);
i++;
//Don't Render if it is transparent
if (color.w > 0.5) {
//A
glVertex3f(clothNodes.at(y).at(x)->position.x, clothNodes.at(y).at(x)->position.y, clothNodes.at(y).at(x)->position.z);
glm::vec3 normNormal = glm::normalize(clothNodes.at(y).at(x)->normal);
glNormal3f(normNormal.x, normNormal.y, normNormal.z);
//B
glVertex3f(clothNodes.at(y).at(x + 1)->position.x, clothNodes.at(y).at(x + 1)->position.y, clothNodes.at(y).at(x + 1)->position.z);
normNormal = glm::normalize(clothNodes.at(y).at(x + 1)->normal);
glNormal3f(normNormal.x, normNormal.y, normNormal.z);
}
//Color
color = clothConstraints.at(i)->FindStress();
glColor4f(color.x, color.y, color.z, color.w);
i++;
if (color.w > 0.5) {
//C
glVertex3f(clothNodes.at(y + 1).at(x)->position.x, clothNodes.at(y + 1).at(x)->position.y, clothNodes.at(y + 1).at(x)->position.z);
glm::vec3 normNormal = glm::normalize(clothNodes.at(y + 1).at(x)->normal);
glNormal3f(normNormal.x, normNormal.y, normNormal.z);
//B
glVertex3f(clothNodes.at(y).at(x + 1)->position.x, clothNodes.at(y).at(x + 1)->position.y, clothNodes.at(y).at(x + 1)->position.z);
normNormal = glm::normalize(clothNodes.at(y).at(x + 1)->normal);
glNormal3f(normNormal.x, normNormal.y, normNormal.z);
}
//Color
color = clothConstraints.at(i)->FindStress();
glColor4f(color.x, color.y, color.z, color.w);
i++;
if (color.w > 0.5) {
//C
glVertex3f(clothNodes.at(y + 1).at(x)->position.x, clothNodes.at(y + 1).at(x)->position.y, clothNodes.at(y + 1).at(x)->position.z);
glm::vec3 normNormal = glm::normalize(clothNodes.at(y + 1).at(x)->normal);
glNormal3f(normNormal.x, normNormal.y, normNormal.z);
//A
glVertex3f(clothNodes.at(y).at(x)->position.x, clothNodes.at(y).at(x)->position.y, clothNodes.at(y).at(x)->position.z);
normNormal = glm::normalize(clothNodes.at(y).at(x)->normal);
glNormal3f(normNormal.x, normNormal.y, normNormal.z);
}
//Second Triangle
//Color
color = clothConstraints.at(i)->FindStress();
glColor4f(color.x, color.y, color.z, color.w);
i++;
if (color.w > 0.5) {
//B
glVertex3f(clothNodes.at(y).at(x + 1)->position.x, clothNodes.at(y).at(x + 1)->position.y, clothNodes.at(y).at(x + 1)->position.z);
glm::vec3 normNormal = glm::normalize(clothNodes.at(y).at(x + 1)->normal);
glNormal3f(normNormal.x, normNormal.y, normNormal.z);
//D
glVertex3f(clothNodes.at(y + 1).at(x + 1)->position.x, clothNodes.at(y + 1).at(x + 1)->position.y, clothNodes.at(y + 1).at(x + 1)->position.z);
normNormal = glm::normalize(clothNodes.at(y + 1).at(x + 1)->normal);
glNormal3f(normNormal.x, normNormal.y, normNormal.z);
}
//Color
color = clothConstraints.at(i)->FindStress();
glColor4f(color.x, color.y, color.z, color.w);
i++;
if (color.w > 0.5) {
//D
glVertex3f(clothNodes.at(y + 1).at(x + 1)->position.x, clothNodes.at(y + 1).at(x + 1)->position.y, clothNodes.at(y + 1).at(x + 1)->position.z);
glm::vec3 normNormal = glm::normalize(clothNodes.at(y + 1).at(x + 1)->normal);
glNormal3f(normNormal.x, normNormal.y, normNormal.z);
//C
glVertex3f(clothNodes.at(y + 1).at(x)->position.x, clothNodes.at(y + 1).at(x)->position.y, clothNodes.at(y + 1).at(x)->position.z);
normNormal = glm::normalize(clothNodes.at(y + 1).at(x)->normal);
glNormal3f(normNormal.x, normNormal.y, normNormal.z);
}
//Color
color = clothConstraints.at(i)->FindStress();
glColor4f(color.x, color.y, color.z, color.w);
i++;
if (color.w > 0.5) {
//C
glVertex3f(clothNodes.at(y + 1).at(x)->position.x, clothNodes.at(y + 1).at(x)->position.y, clothNodes.at(y + 1).at(x)->position.z);
glm::vec3 normNormal = glm::normalize(clothNodes.at(y + 1).at(x)->normal);
glNormal3f(normNormal.x, normNormal.y, normNormal.z);
//B
glVertex3f(clothNodes.at(y).at(x + 1)->position.x, clothNodes.at(y).at(x + 1)->position.y, clothNodes.at(y).at(x + 1)->position.z);
normNormal = glm::normalize(clothNodes.at(y).at(x + 1)->normal);
glNormal3f(normNormal.x, normNormal.y, normNormal.z);
}
}
}
//glDisable(GL_BLEND);
glEnd();
}
void Reset() {
for (size_t y = 0; y < size.y; y++)
{
for (size_t x = 0; x < size.x; x++)
{
clothNodes.at(y).at(x)->Reset();
}
}
for (size_t i = 0; i < clothConstraints.size(); i++)
{
clothConstraints.at(i)->Reset();
}
//Static Nodes
Console_OutputLog(L"Setting Static Cloth Nodes", LOGINFO);
for (size_t i = 0; i < size.x; i++)
{
clothNodes.at(((unsigned int)size.y) - 1).at(i)->staticNode = true;
}
}
void Tick(float deltaTime) {
for (size_t i = 0; i < clothConstraints.size(); i++)
{
clothConstraints.at(i)->Tick(deltaTime);
}
if (clothNodes.size() > 0) {
for (size_t y = 0; y < size.y; y++)
{
for (size_t x = 0; x < size.x; x++)
{
clothNodes.at(y).at(x)->Tick(deltaTime, groundLevel);
}
}
}
}
void AdjustDamping(float amount) {
for (size_t y = 0; y < clothNodes.size(); y++)
{
for (size_t x = 0; x < clothNodes.at(0).size(); x++)
{
clothNodes.at(y).at(x)->damping += amount;
}
}
}
void CollisionLogic(Sphere* sphere, glm::vec3 rayDir, glm::vec3 camPos, bool mouseDown) {
//Check if a node in inside a sphere
for (size_t y = 0; y < clothNodes.size(); y++)
{
for (size_t x = 0; x < clothNodes.at(0).size(); x++)
{
//If we are in a sphere
if (glm::distance(sphere->transform.position, clothNodes.at(y).at(x)->position) < sphere->radius) {
//Push out of sphere
glm::vec3 directionVec = clothNodes.at(y).at(x)->position - sphere->transform.position;
directionVec = glm::normalize(directionVec);
//clothNodes.at(y).at(x)->moveBy(directionVec - (sphere->radius - 10)); //black hole
clothNodes.at(y).at(x)->moveBy(directionVec);
}
}
}
if (mouseDown) {
//If we are holding mouse down
for (size_t y = 0; y < clothNodes.size(); y++)
{
for (size_t x = 0; x < clothNodes.at(0).size(); x++)
{
//If the ray hit our node
float Scale = 0.1f;
glm::vec3 dirfrac;
// r.dir is unit direction vector of ray
dirfrac.x = 1.0f / rayDir.x;
dirfrac.y = 1.0f / rayDir.y;
dirfrac.z = 1.0f / rayDir.z;
// lb is the corner of AABB with minimal coordinates - left bottom, rt is maximal corner
// r.org is origin of ray
float t1 = ((clothNodes.at(y).at(x)->position.x - Scale) - camPos.x) * dirfrac.x;
float t2 = ((clothNodes.at(y).at(x)->position.x + Scale) - camPos.x) * dirfrac.x;
float t3 = ((clothNodes.at(y).at(x)->position.y - Scale) - camPos.y) * dirfrac.y;
float t4 = ((clothNodes.at(y).at(x)->position.y + Scale) - camPos.y) * dirfrac.y;
float t5 = ((clothNodes.at(y).at(x)->position.z) - camPos.z) * dirfrac.z;
float t6 = ((clothNodes.at(y).at(x)->position.z) - camPos.z) * dirfrac.z;
float tmin = fmax(fmax(fmin(t1, t2), fmin(t3, t4)), fmin(t5, t6));
float tmax = fmin(fmin(fmax(t1, t2), fmax(t3, t4)), fmax(t5, t6));
// if tmax < 0, ray (line) is intersecting AABB, but the whole AABB is behind us
if (tmax < 0)
{
//Console_OutputLog(L"BEHIND", LOGINFO);
clothNodes.at(y).at(x)->addForce(-rayDir * 15.0f, groundLevel);
}
// if tmin > tmax, ray doesn't intersect AABB
else if (tmin > tmax)
{
//Console_OutputLog(L"MISSED", LOGINFO);
}
else {
//Apply Force
Console_OutputLog(L"HIT", LOGINFO);
clothNodes.at(y).at(x)->addForce(-rayDir * 15.0f, groundLevel);
}
}
}
}
}
void ApplyWind(glm::vec3 windDir, float amp) {
for (size_t y = 0; y < size.y-1; y++)
{
for (size_t x = 0; x < size.x-1; x++)
{
//Add force onto the section of the cloth
glm::vec3 windNorm = glm::normalize(calcNormalSection(clothNodes.at(y).at(x), clothNodes.at(y).at(x + 1), clothNodes.at(y + 1).at(x)));
float dot = glm::dot(windDir, windNorm);
glm::vec3 force = (windNorm * dot) * amp;
clothNodes.at(y).at(x)->addForce(force, groundLevel);
}
}
}
void AllDyanmic() {
for (size_t y = 0; y < size.y; y++)
{
for (size_t x = 0; x < size.x; x++)
{
clothNodes.at(y).at(x)->staticNode = false;
}
}
}
void globalForce(glm::vec3 dir) {
if (clothNodes.size() > 0) {
for (size_t y = 0; y < size.y; y++)
{
for (size_t x = 0; x < size.x; x++)
{
clothNodes.at(y).at(x)->addForce(dir, groundLevel);
}
}
}
}
glm::vec2 size;
vector<vector<clothNode*>> clothNodes;
vector<clothConstraint*> clothConstraints;
float groundLevel = 0;
float scaleFactor = 10;
};
| 28.884547
| 159
| 0.588734
|
2ffe6616d8044d4fc9d06b0d7a8cb28470508338
| 1,339
|
py
|
Python
|
WebServices/ErrorHandler.py
|
david-c-stein/Python-HouseLEDs
|
ba01368179f30fe7612b30f1257838b715fd866b
|
[
"MIT"
] | null | null | null |
WebServices/ErrorHandler.py
|
david-c-stein/Python-HouseLEDs
|
ba01368179f30fe7612b30f1257838b715fd866b
|
[
"MIT"
] | null | null | null |
WebServices/ErrorHandler.py
|
david-c-stein/Python-HouseLEDs
|
ba01368179f30fe7612b30f1257838b715fd866b
|
[
"MIT"
] | null | null | null |
import os
import tornado.web
import logging
import logging.config
class ErrorHandler(tornado.web.RequestHandler):
"""Generates an error response with status_code for all requests."""
def __init__(self, application, request, status_code):
tornado.web.RequestHandler.__init__(self, application, request)
self.set_status(status_code)
self.logger = logging.getLogger(__name__)
self.logger.info("Initializing " + __file__)
def get_error_html(self, status_code, **kwargs):
self.require_setting("static_path")
if status_code in [404, 500, 503, 403]:
filename = os.path.join(self.settings['static_path'], '%d.html' % status_code)
if os.path.exists(filename):
f = open(filename, 'r')
data = f.read()
f.close()
return data
return "<html><title>%(code)d: %(message)s</title>" \
"<body class='bodyErrorPage'>%(code)d: %(message)s</body></html>" % {
"code": status_code,
"message": httplib.responses[status_code],
}
## override the tornado.web.ErrorHandler with our default ErrorHandler
tornado.web.ErrorHandler = ErrorHandler
| 38.257143
| 91
| 0.57655
|
a7513d871da3c609c5689b3a2823c2f53bebf94f
| 2,088
|
lua
|
Lua
|
ICP.lua
|
andreaskoepf/torch-pcl
|
54244b69f9483d84e4f7d1da637c09d1de73acf1
|
[
"BSD-3-Clause"
] | 36
|
2016-02-11T06:57:33.000Z
|
2020-05-30T05:08:18.000Z
|
ICP.lua
|
andreaskoepf/torch-pcl
|
54244b69f9483d84e4f7d1da637c09d1de73acf1
|
[
"BSD-3-Clause"
] | 13
|
2015-10-23T13:00:34.000Z
|
2017-01-05T16:35:32.000Z
|
ICP.lua
|
andreaskoepf/torch-pcl
|
54244b69f9483d84e4f7d1da637c09d1de73acf1
|
[
"BSD-3-Clause"
] | 8
|
2016-02-21T01:47:46.000Z
|
2019-11-01T12:48:57.000Z
|
local ffi = require 'ffi'
local torch = require 'torch'
local utils = require 'pcl.utils'
local pcl = require 'pcl.PointTypes'
local ICP = torch.class('pcl.ICP', pcl)
local func_by_type = {}
local function init()
local ICP_method_names = {
'new',
'delete',
'setInputSource',
'setInputTarget',
'setMaxCorrespondenceDistance',
'setMaximumIterations',
'setTransformationEpsilon',
'setEuclideanFitnessEpsilon',
'getFinalTransformation',
'getFitnessScore',
'align'
}
for k,v in pairs(utils.type_key_map) do
func_by_type[k] = utils.create_typed_methods("pcl_ICP_TYPE_KEY_", ICP_method_names, v)
end
end
init()
function ICP:__init(pointType)
local cloud
if torch.isTypeOf(pointType, pcl.PointCloud) then
cloud = pointType
pointType = cloud.pointType
end
self.pointType = pcl.pointType(pointType or pcl.PointXYZ)
self.f = func_by_type[self.pointType]
self.o = self.f.new()
end
function ICP:cdata()
return self.o
end
function ICP:setInputSource(cloud)
self.f.setInputSource(self.o, cloud:cdata())
end
function ICP:setInputTarget(cloud)
self.f.setInputTarget(self.o, cloud:cdata())
end
function ICP:setMaxCorrespondenceDistance(distance)
self.f.setMaxCorrespondenceDistance(self.o, distance)
end
function ICP:setMaximumIterations(count)
self.f.setMaximumIterations(self.o, count)
end
function ICP:setTransformationEpsilon(epsilon)
self.f.setTransformationEpsilon(self.o, epsilon)
end
function ICP:setEuclideanFitnessEpsilon(epsilon)
self.f.setEuclideanFitnessEpsilon(self.o, epsilon)
end
function ICP:getFinalTransformation()
local t = torch.FloatTensor()
self.f.getFinalTransformation(self.o, t:cdata())
return t
end
function ICP:getFitnessScore(max_range)
return self.f.getFitnessScore(self.o, max_range or pcl.range.double.max)
end
function ICP:align(output, initial_guess)
output = output or pcl.PointCloud(self.pointType)
if initial_guess then
initial_guess = initial_guess:cdata()
end
self.f.align(self.o, output:cdata(), initial_guess)
return output
end
| 22.945055
| 90
| 0.750479
|
241e3954838eef39baa626c3908ce3a920421b45
| 705
|
asm
|
Assembly
|
oeis/052/A052761.asm
|
neoneye/loda-programs
|
84790877f8e6c2e821b183d2e334d612045d29c0
|
[
"Apache-2.0"
] | 11
|
2021-08-22T19:44:55.000Z
|
2022-03-20T16:47:57.000Z
|
oeis/052/A052761.asm
|
neoneye/loda-programs
|
84790877f8e6c2e821b183d2e334d612045d29c0
|
[
"Apache-2.0"
] | 9
|
2021-08-29T13:15:54.000Z
|
2022-03-09T19:52:31.000Z
|
oeis/052/A052761.asm
|
neoneye/loda-programs
|
84790877f8e6c2e821b183d2e334d612045d29c0
|
[
"Apache-2.0"
] | 3
|
2021-08-22T20:56:47.000Z
|
2021-09-29T06:26:12.000Z
|
; A052761: a(n) = 3!*n*S(n-1,3), where S denotes the Stirling numbers of second kind.
; Submitted by Jon Maiga
; 0,0,0,0,24,180,900,3780,14448,52164,181500,615780,2052072,6749028,21976500,71007300,228009696,728451972,2317445100,7346047140,23213772120,73156412196,229989358500,721474964100,2258832312144,7059480120900,22026886599900,68624941546980,213505455290568,663403627309284,2058863002564500,6382525236944580,19765342522656192,61149241030348548,189007183089559500,583699555602065700,1801131912712245816,5553493878127049892,17110772755817204100,52683184828531579140,162102140150061384240,498464148581403864516
mov $1,$0
trn $1,1
seq $1,392 ; Stirling numbers of second kind S(n,3).
mul $0,$1
mul $0,6
| 70.5
| 501
| 0.839716
|
dc5b025f99e364d7dcdfa0a9d43645b38ef3b6e1
| 2,547
|
ps1
|
PowerShell
|
scripts/build-sdk.ps1
|
rawkode/pulumi
|
b3524e9e1353364daf1e265837ddd30c36f923bf
|
[
"Apache-2.0"
] | null | null | null |
scripts/build-sdk.ps1
|
rawkode/pulumi
|
b3524e9e1353364daf1e265837ddd30c36f923bf
|
[
"Apache-2.0"
] | null | null | null |
scripts/build-sdk.ps1
|
rawkode/pulumi
|
b3524e9e1353364daf1e265837ddd30c36f923bf
|
[
"Apache-2.0"
] | 1
|
2020-09-02T06:12:36.000Z
|
2020-09-02T06:12:36.000Z
|
param (
$VersionTag,
$PulumiRef
)
Set-StrictMode -Version 2.0
$ErrorActionPreference = "Stop"
$S3ProdBucketRoot="s3://get.pulumi.com/releases/"
$S3EngBucketRoot="s3://eng.pulumi.com/releases/"
$S3PublishFolderSdk="${S3ProdBucketRoot}sdk/"
function New-TemporaryDirectory {
New-Item -ItemType Directory -Path (Join-Path ([System.IO.Path]::GetTempPath()) ([System.IO.Path]::GetRandomFileName()))
}
function New-TemporaryFile {
New-Item -ItemType File -Path (Join-Path ([System.IO.Path]::GetTempPath()) ([System.IO.Path]::GetRandomFileName()))
}
function Download-Release ($repoName, $repoCommit, [ValidateSet("zip", "tgz")]$ext) {
Write-Host "downloading $repoName@$repoCommit"
$file="${repoCommit}.${ext}"
$s3File="${S3EngBucketRoot}${repoName}/windows/amd64/${file}"
aws s3 cp --only-show-errors "$s3File" ".\$file"
switch($ext) {
"zip" { 7z x ${file} }
"tgz" { cmd /C "7z x ${file} -tgzip -so | 7z x -ttar -si" }
default { Write-Error "Unknown extention type $ext" }
}
Remove-Item -Force "$file"
}
if (!$VersionTag) { $VersionTag=Get-Date -UFormat '%Y%m%d_%H%M%S' }
if (!$PulumiRef) { $PulumiRef="master" }
$SdkFileName="pulumi-$VersionTag-windows-x64.zip"
$PulumiFolder=(Join-Path (New-TemporaryDirectory) "Pulumi")
New-Item -ItemType Directory -Path $PulumiFolder | Out-Null
Push-Location "$PulumiFolder" | Out-Null
Write-Host "pulumi: $PulumiRef"
Write-Host ""
Download-Release "pulumi" $PulumiRef "zip"
Remove-Item -Recurse -Force -Path "$PulumiFolder\node_modules"
$SdkPackagePath=(Join-Path ([System.IO.Path]::GetTempPath()) $SdkFileName)
if (Test-Path $SdkPackagePath) {
Remove-Item -Force -Path $SdkPackagePath
}
7z a -tzip "$SdkPackagePath" "$(Join-Path (Split-Path -Parent $PulumiFolder) '.')"
Write-Host "uploading SDK to ${S3PublishFolderSdk}${SdkFileName}"
$AWSCreds=((aws sts assume-role `
--role-arn "arn:aws:iam::058607598222:role/UploadPulumiReleases" `
--role-session-name "upload-sdk" `
--external-id "upload-pulumi-release") | ConvertFrom-Json)
$env:AWS_ACCESS_KEY_ID=$AWSCreds.Credentials.AccessKeyId
$env:AWS_SECRET_ACCESS_KEY=$AWSCreds.Credentials.SecretAccessKey
$env:AWS_SECURITY_TOKEN=$AWSCreds.Credentials.SessionToken
aws s3 cp --acl public-read --only-show-errors "$SdkPackagePath" "${S3PublishFolderSdk}${SdkFileName}"
Pop-Location | Out-Null
Remove-Item -Path $SdkPackagePath
Remove-Item -Path (Split-Path -Parent $PulumiFolder) -Force -Recurse
Write-Host "done"
| 30.686747
| 124
| 0.695328
|
62e8092ed678e1e133f132240fe4f573d6b4e274
| 213
|
h
|
C
|
lib/config/config.h
|
ozdevguy/C-General-Library
|
8e2cc206604e5c4f13df6e9c3e388b5902d00d9a
|
[
"Apache-2.0"
] | 1
|
2017-04-06T05:10:50.000Z
|
2017-04-06T05:10:50.000Z
|
lib/config/config.h
|
ozdevguy/C-General-Library
|
8e2cc206604e5c4f13df6e9c3e388b5902d00d9a
|
[
"Apache-2.0"
] | null | null | null |
lib/config/config.h
|
ozdevguy/C-General-Library
|
8e2cc206604e5c4f13df6e9c3e388b5902d00d9a
|
[
"Apache-2.0"
] | null | null | null |
/* MANAGED HEAP | DEFAULT VALUES */
//Default serialization pool size = 16MB, starting at address 0x2800000
#define DEFAULT_SERIALIZATION_POOL_SIZE 0x1000000
#define DEFAULT_SERIALIZATION_POOL_STARTADDR 0x2800000
| 42.6
| 71
| 0.840376
|
25698deb4fca3e2e7de521f8cfc47ab67745adfc
| 4,977
|
js
|
JavaScript
|
src/Measurement/MeasureAngle.js
|
ZeaInc/zea-ux
|
f3a4705655b9043e8ee2ea70780f695af6b0cb74
|
[
"MIT"
] | null | null | null |
src/Measurement/MeasureAngle.js
|
ZeaInc/zea-ux
|
f3a4705655b9043e8ee2ea70780f695af6b0cb74
|
[
"MIT"
] | 40
|
2020-09-23T15:59:15.000Z
|
2022-03-18T18:28:43.000Z
|
src/Measurement/MeasureAngle.js
|
ZeaInc/zea-ux
|
f3a4705655b9043e8ee2ea70780f695af6b0cb74
|
[
"MIT"
] | 2
|
2020-11-17T20:41:14.000Z
|
2022-02-14T08:34:00.000Z
|
import {
TreeItem,
Material,
Color,
Sphere,
Lines,
BillboardItem,
Label,
GeomItem,
Xfo,
Vec3,
ColorParameter,
Registry,
Ray,
} from '@zeainc/zea-engine'
const sphere = new Sphere(0.003, 24, 12, false)
const line = new Lines(0.0)
line.setNumVertices(2)
line.setNumSegments(1)
line.setSegmentVertexIndices(0, 0, 1)
line.getVertexAttribute('positions').getValueRef(1).setFromOther(new Vec3(0, 0, 1))
/**
*
*
* @extends {TreeItem}
*/
class MeasureAngle extends TreeItem {
/**
* Creates an instance of MeasureAngle.
* @param {string} name
* @param {Color} color
*/
constructor(name = 'MeasureAngle', color = new Color('#00AA00')) {
super(name)
this.colorParam = this.addParameter(new ColorParameter('Color', color))
this.markerMaterial = new Material('Marker', 'HandleShader')
this.markerMaterial.getParameter('BaseColor').setValue(this.colorParam.getValue())
this.markerMaterial.getParameter('MaintainScreenSize').setValue(1)
this.markerMaterial.getParameter('Overlay').setValue(0.5)
this.markerMaterialB = new Material('Marker', 'HandleShader')
this.markerMaterialB.getParameter('BaseColor').setValue(new Color(1, 0, 0))
this.markerMaterialB.getParameter('MaintainScreenSize').setValue(1)
this.markerMaterialB.getParameter('Overlay').setValue(0.5)
this.lineMaterial = new Material('Line', 'LinesShader')
this.lineMaterial.getParameter('BaseColor').setValue(this.colorParam.getValue())
this.lineMaterial.getParameter('Overlay').setValue(0.5)
this.markerA = new GeomItem(`markerA`, sphere, this.markerMaterial)
this.markerB = new GeomItem(`markerB`, sphere, this.markerMaterialB)
this.addChild(this.markerA)
this.addChild(this.markerB)
}
/**
* Given the 2 marker positions, calculate and display the angle.
*/
createLinesAndLabel() {
this.markerA.addChild(new GeomItem('Line', line, this.lineMaterial), false)
this.markerB.addChild(new GeomItem('Line', line, this.lineMaterial), false)
this.label = new Label('Distance')
this.label.getParameter('FontSize').setValue(20)
this.label.getParameter('BackgroundColor').setValue(this.colorParam.getValue())
this.billboard = new BillboardItem('DistanceBillboard', this.label)
this.billboard.getParameter('LocalXfo').setValue(new Xfo())
this.billboard.getParameter('PixelsPerMeter').setValue(1500)
this.billboard.getParameter('AlignedToCamera').setValue(true)
this.billboard.getParameter('DrawOnTop').setValue(true)
this.billboard.getParameter('FixedSizeOnscreen').setValue(true)
this.billboard.getParameter('Alpha').setValue(1)
this.addChild(this.billboard)
this.colorParam.on('valueChanged', () => {
const color = this.colorParam.getValue()
this.markerMaterial.getParameter('BaseColor').setValue(color)
this.lineMaterial.getParameter('BaseColor').setValue(color)
this.label.getParameter('BackgroundColor').setValue(color)
})
// ////////////////////////////////////////
// Calculate the angle
const xfoA = this.markerA.getParameter('GlobalXfo').getValue()
const xfoB = this.markerB.getParameter('GlobalXfo').getValue()
const normA = xfoA.ori.getZaxis()
const normB = xfoB.ori.getZaxis()
const axis = normA.cross(normB).normalize()
const tangentA = axis.cross(normA).normalize()
const tangentB = axis.cross(normB).normalize()
const rayA = new Ray(xfoA.tr, tangentA)
const rayB = new Ray(xfoB.tr, tangentB)
const params = rayA.intersectRayVector(rayB)
const angle = tangentA.angleTo(tangentB)
const labelXfo = new Xfo()
labelXfo.tr.addInPlace(rayA.pointAtDist(params[0]))
labelXfo.tr.addInPlace(rayB.pointAtDist(params[1]))
labelXfo.tr.scaleInPlace(0.5)
xfoA.ori.setFromDirectionAndUpvector(tangentA, normA)
this.markerA.getParameter('GlobalXfo').setValue(xfoA)
xfoB.ori.setFromDirectionAndUpvector(tangentB, normA)
this.markerB.getParameter('GlobalXfo').setValue(xfoB)
const lineAXfo = new Xfo()
lineAXfo.sc.z = params[0]
this.markerA.getChild(0).getParameter('LocalXfo').setValue(lineAXfo)
const lineBXfo = new Xfo()
lineBXfo.sc.z = params[1]
this.markerB.getChild(0).getParameter('LocalXfo').setValue(lineBXfo)
this.label.getParameter('Text').setValue(`${(angle / (Math.PI / 180)).toFixed(3)} °`)
this.billboard.getParameter('GlobalXfo').setValue(labelXfo)
}
/**
*
*
* @param {Xfo} xfo
*/
setXfoA(xfo) {
this.markerA.getParameter('GlobalXfo').setValue(xfo)
this.markerB.getParameter('GlobalXfo').setValue(xfo)
}
/**
*
*
* @return {Xfo}
*/
getXfoA() {
return this.markerA.getParameter('GlobalXfo').getValue()
}
/**
*
*
* @param {Xfo} xfo
*/
setXfoB(xfo) {
this.markerB.getParameter('GlobalXfo').setValue(xfo)
this.createLinesAndLabel()
}
}
Registry.register('MeasureAngle', MeasureAngle)
export { MeasureAngle }
| 31.10625
| 89
| 0.697207
|
8ed44d2f55b8ee6e9226d30582618918c8695ce7
| 6,988
|
js
|
JavaScript
|
src/services/PrivateKeyService.js
|
fincrypchain-io/hybrid-exchange-sdk
|
3fa11053c5226017e5a798fe9df9e139f1960db8
|
[
"MIT"
] | 11
|
2019-02-12T14:22:35.000Z
|
2020-02-13T17:05:21.000Z
|
src/services/PrivateKeyService.js
|
fincrypchain-io/hybrid-exchange-sdk
|
3fa11053c5226017e5a798fe9df9e139f1960db8
|
[
"MIT"
] | 75
|
2019-02-12T15:52:34.000Z
|
2021-09-01T01:09:07.000Z
|
src/services/PrivateKeyService.js
|
fincrypchain-io/hybrid-exchange-sdk
|
3fa11053c5226017e5a798fe9df9e139f1960db8
|
[
"MIT"
] | 5
|
2019-03-17T04:08:32.000Z
|
2021-04-18T15:36:09.000Z
|
const { promisify } = require('util')
const bip39 = require('bip39')
const crypto = require('crypto')
const ethereumUtil = require('ethereumjs-util')
const fs = require('fs')
const hdkey = require('ethereumjs-wallet/hdkey')
const keythereum = require('keythereum')
const writeFileAsync = promisify(fs.writeFile)
const readFileAsync = promisify(fs.readFile)
const { BaseError } = require('../utils/errors')
class EthereumAddressError extends BaseError {}
class InvalidPrivateKeyError extends BaseError {}
class InvalidPrivateKeyFile extends BaseError {}
class InvalidMnemonicError extends BaseError {}
class InvalidKeystoreFile extends BaseError {}
class InvalidKeystoreParams extends BaseError {}
const HD_PATH = "m/44'/60'/0/0"
const encoding = 'utf8'
/**
* Class representing a service that manage private key.
*/
class PrivateKeyService {
constructor(privateKeyValidator, logger) {
if (!privateKeyValidator) {
throw new TypeError(`Invalid "privateKeyValidator" value: ${privateKeyValidator}`)
}
this.privateKeyValidator = privateKeyValidator
if (!logger) {
throw new TypeError(`Invalid "logger" value: ${logger}`)
}
this.log = logger.child({ module: this.constructor.name })
this.keyStoreOptions = {
kdf: 'pbkdf2',
cipher: 'aes-128-ctr',
kdfparams: {
c: 262144,
dklen: 32,
prf: 'hmac-sha256',
},
}
}
/**
* It gets a palin private key reading it from file.
*
* @param {String} privateKeyPath The path of private key file.
*
* @throws {InvalidPrivateKeyFile} If does not exist the file.
*/
async getPrivateKeyAsync(privateKeyPath) {
try {
const extractedData = await readFileAsync(privateKeyPath, encoding)
// Regex for both windows and unix system.
const rawPrivateKey = extractedData.split(/[\r\n]+/).shift()
const privateKey = ethereumUtil.addHexPrefix(rawPrivateKey)
this.log.debug({ privateKeyPath, fn: 'getPrivateKeyAsync' },
'Get private key from file.')
return privateKey
} catch (err) {
this.log.error({ privateKeyPath, fn: 'getPrivateKeyAsync' },
'Error getting private key from file.')
throw new InvalidPrivateKeyFile(err)
}
}
/**
* It gets the keystore object from a keystore file.
*
* @param {String} keystoreFilePath The path of the keystore.
*
* @throws {InvalidKeystoreFile} If does not exist the file.
*/
async getKeystoreAsync(keystoreFilePath) {
try {
const extractedData = await readFileAsync(keystoreFilePath, encoding)
// Regex for both windows and unix system.
const keyStoreObject = extractedData.split(/[\r\n]+/).shift()
this.log.debug({ keystoreFilePath, fn: 'getKeyStoreAsync' },
'Get private keystore from file.')
return JSON.parse(keyStoreObject)
} catch (err) {
this.log.error({ keystoreFilePath, fn: 'getKeyStoreAsync' },
'Error getting keystore from file.')
throw new InvalidKeystoreFile(err)
}
}
/**
* It gets the private key from a keystore.
*
* @param {String} password The password to decrypt the keystore.
* @param {String} keystore The keystore.
*
* @throws {InvalidKeystoreParams} If something goes wrong during the recovering.
*/
async getPrivateKeyFromKeystore(password, keystore) {
try {
const bufferPrivateKey = keythereum.recover(password, keystore)
const privateKey = bufferPrivateKey.toString('hex')
this.log.info({ fn: 'getPrivateKeyFromKeystore', privateKey }, 'Get privatekey from keystore using the password.')
return privateKey
} catch (err) {
this.log.error({ keystore, fn: 'getPrivateKeyFromKeystore' },
'Error recovering keystore using the password.')
throw new InvalidKeystoreParams(err)
}
}
/**
* It gets the address from private key.
*
* @param {String} privateKey The private key.
*
* @throws {EthereumAddressError} If the address is not an ethereum address.
*/
getAddressFromPrivateKey(privateKey) {
try {
const privateKeyWithPrefix = ethereumUtil.addHexPrefix(privateKey)
const privateKeyBuffered = ethereumUtil.toBuffer(privateKeyWithPrefix)
const addressBufferedFromPrivateKey = ethereumUtil.privateToAddress(privateKeyBuffered)
const personalWalletAddress = ethereumUtil.bufferToHex(addressBufferedFromPrivateKey)
this.log.debug({ fn: 'getAddressFromPrivateKey' },
'Get address from private key.')
return personalWalletAddress
} catch (err) {
this.log.error({ fn: 'getAddressFromPrivateKey' },
'Get address from private key.')
throw new EthereumAddressError(err)
}
}
/**
* It gets the private key from mnemonic
*
* @param {String} mnemonic The mnemonic.
*
* @throws {InvalidMnemonicError} If the menomic is not valid.
*/
getPrivateKeyFromMnemonic(mnemonic, hdPath = HD_PATH) {
try {
const validMnemonic = this.privateKeyValidator.validateMnemonic(mnemonic)
const hdwallet = hdkey.fromMasterSeed(bip39.mnemonicToSeed(validMnemonic))
const wallet = hdwallet.derivePath(hdPath).getWallet()
const privateKey = wallet._privKey.toString('hex')
this.log.debug({ fn: 'getPrivateKeyFromMnemonic' }, 'Retrieve private key from mnemonic.')
return privateKey
} catch (err) {
this.log.error({ fn: 'getPrivateKeyFromMnemonic', err },
'Get address from private key.')
throw new InvalidMnemonicError(err)
}
}
/**
* It generates keystore file.
*
* @param {String} privateKey The private key.
* @param {String} keyStoreFilePath The keystore file path destination.
* @param {String} keyStorePassword The keystore password.
*/
async generateKeyStoreAsync(privateKey, keyStorePassword) {
const params = { keyBytes: 32, ivBytes: 16 }
const randomBytes = crypto.randomBytes(params.keyBytes + params.ivBytes + params.keyBytes)
const iv = randomBytes.slice(params.keyBytes, params.keyBytes + params.ivBytes)
const salt = randomBytes.slice(params.keyBytes + params.ivBytes)
const keyStore = keythereum.dump(keyStorePassword, privateKey, salt, iv, this.keyStoreOptions)
return keyStore
}
/**
* It writes the keystore into a file.
*
* @param {String} keyStoreFilePath The keystore file path destination.
*/
async writeKeyStoreToFileAsync(keyStore, keyStoreFilePath) {
const parsedkeyStoreFilePath = keyStoreFilePath.split(/[\r\n]+/).shift()
const fileName = `${parsedkeyStoreFilePath}/UTC--${new Date().toISOString()}--${keyStore.address}`
await writeFileAsync(fileName, JSON.stringify(keyStore))
this.log.info({ fn: 'generateKeyStore', fileName }, 'Generate keyStore file.')
return fileName
}
}
module.exports = {
InvalidKeystoreFile,
InvalidKeystoreParams,
InvalidMnemonicError,
InvalidPrivateKeyError,
InvalidPrivateKeyFile,
PrivateKeyService,
}
| 35.292929
| 120
| 0.695335
|
23ed32b310800b9bede7d9c3b45137d902568392
| 1,143
|
js
|
JavaScript
|
src/writer-console.js
|
wildoak/logawesome
|
ae0c4c022bb13f5095fa5d8450aeb3c03d2c6dd1
|
[
"MIT"
] | null | null | null |
src/writer-console.js
|
wildoak/logawesome
|
ae0c4c022bb13f5095fa5d8450aeb3c03d2c6dd1
|
[
"MIT"
] | null | null | null |
src/writer-console.js
|
wildoak/logawesome
|
ae0c4c022bb13f5095fa5d8450aeb3c03d2c6dd1
|
[
"MIT"
] | null | null | null |
import debug from './debug';
const consoleLog = (logLevel, ...args) => {
switch (logLevel) {
case 'DEBUG':
console.log(...args); // eslint-disable-line no-console
break;
case 'INFO':
console.info(...args); // eslint-disable-line no-console
break;
case 'WARN':
console.warn(...args); // eslint-disable-line no-console
break;
case 'ERROR':
console.error(...args); // eslint-disable-line no-console
break;
default:
debug('unknown logLevel %s, will not log %o', logLevel, args);
}
};
export const createConsoleWriter = (formatter, mapper = logLevel => logLevel) => {
if (typeof formatter !== 'function') {
throw new TypeError('expected function as formatter');
}
// not a function but the mapping itself
if (typeof mapper === 'object') {
const mapping = mapper;
mapper = logLevel => mapping[logLevel];
}
return logEntry => {
const logLevel = logEntry.logLevel;
consoleLog(mapper(logLevel), formatter(logEntry));
};
};
| 29.307692
| 82
| 0.56168
|
6abb1c0cfac9fefc642d031fee685e0e9a094113
| 1,368
|
dart
|
Dart
|
lib/src/types/utils/known_type_kind.dart
|
bartekpacia/contractsgenerator-dart
|
8c4bcf01b1dca6b7de70a6240f54e82585581c05
|
[
"Apache-2.0"
] | null | null | null |
lib/src/types/utils/known_type_kind.dart
|
bartekpacia/contractsgenerator-dart
|
8c4bcf01b1dca6b7de70a6240f54e82585581c05
|
[
"Apache-2.0"
] | null | null | null |
lib/src/types/utils/known_type_kind.dart
|
bartekpacia/contractsgenerator-dart
|
8c4bcf01b1dca6b7de70a6240f54e82585581c05
|
[
"Apache-2.0"
] | null | null | null |
import '../type_handler.dart';
enum KnownTypeKind {
/// those that can be handled by a simple `as` cast
primitive,
/// require special serde
complex,
/// cqrs-related interfaces
cqrs,
/// attributes
attribute
}
KnownTypeKind knownTypeKind(KnownType knownType) {
switch (knownType) {
case KnownType.Object_:
case KnownType.Guid:
case KnownType.String:
case KnownType.Boolean:
case KnownType.UInt8:
case KnownType.Int8:
case KnownType.Int16:
case KnownType.UInt16:
case KnownType.Int32:
case KnownType.UInt32:
case KnownType.Int64:
case KnownType.UInt64:
case KnownType.Float:
case KnownType.Double:
case KnownType.Decimal:
return KnownTypeKind.primitive;
case KnownType.Uri:
case KnownType.Date:
case KnownType.Time:
case KnownType.TimeSpan:
case KnownType.DateTime:
case KnownType.DateTimeOffset:
case KnownType.Array:
case KnownType.Map:
return KnownTypeKind.complex;
case KnownType.Query:
case KnownType.Command:
return KnownTypeKind.cqrs;
case KnownType.AuthorizeWhenAttribute:
case KnownType.AuthorizeWhenHasAnyOfAttribute:
case KnownType.QueryCacheAttribute:
case KnownType.Attribute:
return KnownTypeKind.attribute;
}
throw UnimplementedError('There was no mapping for the type $knownType');
}
| 24.428571
| 75
| 0.715643
|
a4894b95808fd2ddf58b8f3f0b71373c108ced4a
| 1,487
|
php
|
PHP
|
app/Controllers/ironman/Datatable_ex.php
|
nirobabhee/workinprocess
|
6a2d4c53752f337e967aee7aa2c01d3c99463efa
|
[
"MIT"
] | null | null | null |
app/Controllers/ironman/Datatable_ex.php
|
nirobabhee/workinprocess
|
6a2d4c53752f337e967aee7aa2c01d3c99463efa
|
[
"MIT"
] | null | null | null |
app/Controllers/ironman/Datatable_ex.php
|
nirobabhee/workinprocess
|
6a2d4c53752f337e967aee7aa2c01d3c99463efa
|
[
"MIT"
] | null | null | null |
<?php
namespace App\Controllers\ironman;
use App\Controllers\BaseController;
class Datatable_ex extends BaseController
{
public function index()
{
$data['title'] = "DataTable Example";
echo view('ironman/template/header', $data);
echo view('ironman/template/left_nav');
echo view('ironman/template/top_nav');
echo view('ironman/datatable/datatable_example_view');
echo view('ironman/template/footer');
}
public function scroller()
{
$data['title'] = "DataTable Scroller";
echo view('ironman/template/header', $data);
echo view('ironman/template/left_nav');
echo view('ironman/template/top_nav');
echo view('ironman/datatable/datatable_scroller_view');
echo view('ironman/template/footer');
}
public function report()
{
$data['title'] = "DataTable Report";
echo view('ironman/template/header', $data);
echo view('ironman/template/left_nav');
echo view('ironman/template/top_nav');
echo view('ironman/datatable/datatable_report');
echo view('ironman/template/footer');
}
public function five_m()
{
$data['title'] = "DataTable 5M";
echo view('ironman/template/header', $data);
echo view('ironman/template/left_nav');
echo view('ironman/template/top_nav');
echo view('ironman/datatable/datatable_five_m');
echo view('ironman/template/footer');
}
}
| 32.326087
| 63
| 0.634163
|
93d4f3d09bf6ff0678595aa461597478a006a668
| 1,090
|
cs
|
C#
|
sdk/dotnet/ApiManagement/Inputs/BackendTlsGetArgs.cs
|
adnang/pulumi-azure
|
32360d2f1e41e27d7fdd6522cb26d65e531f279f
|
[
"ECL-2.0",
"Apache-2.0"
] | 109
|
2018-06-18T00:19:44.000Z
|
2022-02-20T05:32:57.000Z
|
sdk/dotnet/ApiManagement/Inputs/BackendTlsGetArgs.cs
|
adnang/pulumi-azure
|
32360d2f1e41e27d7fdd6522cb26d65e531f279f
|
[
"ECL-2.0",
"Apache-2.0"
] | 663
|
2018-06-18T21:08:46.000Z
|
2022-03-31T20:10:11.000Z
|
sdk/dotnet/ApiManagement/Inputs/BackendTlsGetArgs.cs
|
adnang/pulumi-azure
|
32360d2f1e41e27d7fdd6522cb26d65e531f279f
|
[
"ECL-2.0",
"Apache-2.0"
] | 41
|
2018-07-19T22:37:38.000Z
|
2022-03-14T10:56:26.000Z
|
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Azure.ApiManagement.Inputs
{
public sealed class BackendTlsGetArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Flag indicating whether SSL certificate chain validation should be done when using self-signed certificates for the backend host.
/// </summary>
[Input("validateCertificateChain")]
public Input<bool>? ValidateCertificateChain { get; set; }
/// <summary>
/// Flag indicating whether SSL certificate name validation should be done when using self-signed certificates for the backend host.
/// </summary>
[Input("validateCertificateName")]
public Input<bool>? ValidateCertificateName { get; set; }
public BackendTlsGetArgs()
{
}
}
}
| 34.0625
| 141
| 0.682569
|
9e4c1aa66a0424c4c1e725924cc93154e8fbf726
| 67
|
sql
|
SQL
|
fdb-sql-layer-core/src/test/resources/com/foundationdb/sql/optimizer/rule/reverse-and-clean-up-ins/not-in.sql
|
geophile/sql-layer
|
0eab8b596b729081b9265631230a6703b854a4ec
|
[
"MIT"
] | null | null | null |
fdb-sql-layer-core/src/test/resources/com/foundationdb/sql/optimizer/rule/reverse-and-clean-up-ins/not-in.sql
|
geophile/sql-layer
|
0eab8b596b729081b9265631230a6703b854a4ec
|
[
"MIT"
] | null | null | null |
fdb-sql-layer-core/src/test/resources/com/foundationdb/sql/optimizer/rule/reverse-and-clean-up-ins/not-in.sql
|
geophile/sql-layer
|
0eab8b596b729081b9265631230a6703b854a4ec
|
[
"MIT"
] | null | null | null |
SELECT cid FROM customers WHERE name NOT IN (SELECT sku FROM items)
| 67
| 67
| 0.80597
|
1465f8c29b36e440944a173f5b6810742aecedcb
| 470
|
ts
|
TypeScript
|
packages/embed/src/utils/get-transitive-search-params.ts
|
eliseumds/embed
|
1a77fd9d9d17b417dcf661ab045c627426574200
|
[
"MIT"
] | 108
|
2020-04-21T16:39:18.000Z
|
2022-03-31T06:17:52.000Z
|
packages/embed/src/utils/get-transitive-search-params.ts
|
eliseumds/embed
|
1a77fd9d9d17b417dcf661ab045c627426574200
|
[
"MIT"
] | 439
|
2020-04-21T07:51:22.000Z
|
2022-03-25T15:06:27.000Z
|
packages/embed/src/utils/get-transitive-search-params.ts
|
eliseumds/embed
|
1a77fd9d9d17b417dcf661ab045c627426574200
|
[
"MIT"
] | 81
|
2020-05-14T08:48:55.000Z
|
2022-03-30T19:57:12.000Z
|
export const getTransitiveSearchParams = (transitiveSearchParams?: string[]) => {
const url = new URL(window.location.href)
const queryParamsWithTransitiveParams = {}
if (transitiveSearchParams && transitiveSearchParams.length > 0) {
transitiveSearchParams.forEach((key: string) => {
if (url.searchParams.has(key)) {
queryParamsWithTransitiveParams[key] = url.searchParams.get(key)
}
})
}
return queryParamsWithTransitiveParams
}
| 31.333333
| 81
| 0.719149
|
1002df5e860ee770ec44782d7c9452fb2a496b36
| 14,318
|
dart
|
Dart
|
example/lib/example_default/main.dart
|
rydmike/flex_color_scheme
|
1cea994dcdb330fa17e6d68cbcd345bc6d9efb84
|
[
"BSD-3-Clause"
] | 284
|
2020-12-21T12:18:12.000Z
|
2022-03-29T08:03:11.000Z
|
example/lib/example_default/main.dart
|
rydmike/flex_color_scheme
|
1cea994dcdb330fa17e6d68cbcd345bc6d9efb84
|
[
"BSD-3-Clause"
] | 30
|
2021-01-01T06:49:30.000Z
|
2022-03-28T16:02:44.000Z
|
example/lib/example_default/main.dart
|
rydmike/flex_color_scheme
|
1cea994dcdb330fa17e6d68cbcd345bc6d9efb84
|
[
"BSD-3-Clause"
] | 47
|
2020-12-23T13:19:16.000Z
|
2022-02-20T17:33:42.000Z
|
import 'package:flex_color_scheme/flex_color_scheme.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_fonts/google_fonts.dart';
import '../shared/all_shared_imports.dart';
// This is a copy of the default main.dart file in the example/lib folder.
// It is just here to have a handy copy of it. To build the tutorials in
// examples 1-5 on a device, you can just copy/paste the main.dart code without
// imports from these examples to example/lib/main.dart file. Then you do not
// have to setup build configs for them in your project.
/// FlexColorScheme default example.
///
/// This example shows how you can use define a few colors, use
/// [FlexColorScheme] to theme your app with them, and also define other custom
/// theme properties and how to use a [GoogleFonts] based font as the overall
/// default font for your theme, and how to use a customized [TextTheme].
///
/// To learn more about how to use FlexColorScheme and all its features,
/// please go through the examples in the readme documentation.
void main() => runApp(const DemoApp());
// For our custom color scheme we will define primary and secondary colors,
// but no variant or other colors.
// ignore: unused_element
final FlexSchemeColor _mySchemeLight = FlexSchemeColor.from(
primary: const Color(0xFF3B5997),
// If you do not want to define secondary, primaryVariant and
// secondaryVariant, error and appBar colors you do not have to,
// they will get defined automatically when using the FlexSchemeColor.from()
// factory. With raw default constructor FlexSchemeColor() you have to define
// more required color properties.
//
// Here we do define a secondary color, but if you don't it will get a
// default shade based on the primary color.
secondary: const Color(0xFFFB8123),
);
// These are custom defined matching dark mode colors, but below we instead show
// how to base them of the light color scheme. You can swap in these too in the
// code example further below.
// ignore: unused_element
final FlexSchemeColor _mySchemeDark = FlexSchemeColor.from(
primary: const Color(0xFF8B9DC3),
secondary: const Color(0xFFFCB075),
);
// We define a custom text theme for our app. Here we have decided that
// Headline1 is too big to be useful for us, so we make it a bit smaller.
// We also think buttons should have a bit bigger text, tighter letter spacing,
// and that overline is a bit too small and have weird letter spacing,
// so we change them too.
const TextTheme _myTextTheme = TextTheme(
headline1: TextStyle(
fontSize: 70, // Defaults to 96 in Material2018 Typography.
),
button: TextStyle(
fontSize: 16, // Defaults to 14 in Material2018 Typography.
letterSpacing: 0.9, // Defaults to 1.25 in Material2018 Typography.
),
overline: TextStyle(
fontSize: 11, // Defaults to 10 in Material2018 Typography.
letterSpacing: 0.5, // Defaults to 1.5 in Material2018 Typography.
),
);
class DemoApp extends StatelessWidget {
const DemoApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Default Example',
// Define the light theme for the app, based on defined colors.
theme: FlexThemeData.light(
colors: _mySchemeLight,
// Just want to use a built in scheme? Then comment colors above and
// use scheme below to select a built-in one:
// scheme: FlexScheme.hippieBlue,
surfaceStyle: FlexSurface.medium,
surfaceMode: FlexSurfaceMode.scaffoldSurfaceBackground,
blendLevel: FlexBlendLevel.zero,
//
appBarStyle: FlexAppBarStyle.primary,
appBarElevation: 0,
transparentStatusBar: true,
tabBarStyle: FlexTabBarStyle.forAppBar,
tooltipsMatchBackground: false,
swapColors: false,
visualDensity: FlexColorScheme.comfortablePlatformDensity,
// Set the default font for the ThemeData using GoogleFonts.
fontFamily: GoogleFonts.lato().fontFamily,
// And custom text themes.
textTheme: _myTextTheme,
primaryTextTheme: _myTextTheme,
),
// Define the dark theme for the app, based on custom colors.
darkTheme: FlexThemeData.dark(
// If you want to base the dark scheme on your light colors, this is
// a nice shortcut if you do not want to design your dark theme.
// The whiteBlend for the desaturation of the light theme colors
// defaults to 35%, you can try other values too, here we use 30.
colors: _mySchemeLight.toDark(30),
// If you want to use the defined custom dark colors, use it instead:
// colors: _mySchemeDark,
// Just want to use a built in scheme? Then comment colors above and
// use scheme below to select a built-in one:
// scheme: FlexScheme.hippieBlue,
surfaceStyle: FlexSurface.strong,
appBarStyle: FlexAppBarStyle.background,
appBarElevation: 0,
transparentStatusBar: true,
tabBarStyle: FlexTabBarStyle.forAppBar,
tooltipsMatchBackground: false,
swapColors: false,
darkIsTrueBlack: false,
visualDensity: FlexColorScheme.comfortablePlatformDensity,
fontFamily: GoogleFonts.lato().fontFamily,
textTheme: _myTextTheme,
primaryTextTheme: _myTextTheme,
),
// Use the above dark or light theme based on active themeMode below.
// Toggle in code here, or set to system to toggle with device.
themeMode: ThemeMode.dark,
home: const HomePage(),
);
}
}
// The content of the HomePage below is not relevant for using FlexColorScheme
// based application theming. The critical parts are in the MaterialApp
// theme definitions. The HomePage just contains UI to visually show what the
// defined example looks like in an application and with commonly used Widgets.
class HomePage extends StatefulWidget {
const HomePage({
Key? key,
}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
// The reason why HomePage is using a stateful widget is that it holds the
// state of the dummy side menu/rail locally.
double _menuWidth = App.expandWidth;
bool _isExpanded = true;
// The state for the system navbar style and divider usage is local as it is
// is only used by the AnnotatedRegion.
// Used to control system navbar style via an AnnotatedRegion.
FlexSystemNavBarStyle systemNavBarStyle = FlexSystemNavBarStyle.background;
// Used to control if we have a top divider on the system navigation bar.
bool useSysNavDivider = false;
@override
Widget build(BuildContext context) {
final MediaQueryData media = MediaQuery.of(context);
final double topPadding = media.padding.top;
final double bottomPadding = media.padding.bottom;
final bool menuAvailable = media.size.width > 650;
final ThemeData theme = Theme.of(context);
final TextTheme textTheme = theme.textTheme;
final TextStyle headline4 = textTheme.headline4!;
final Color appBarColor =
theme.appBarTheme.backgroundColor ?? theme.primaryColor;
// Give the width of the side panel some automatic adaptive behavior and
// make it rail sized when there is not enough room for a menu, even if
// menu size is requested.
if (!menuAvailable) {
_menuWidth = App.shrinkWidth;
}
if (menuAvailable && !_isExpanded) {
_menuWidth = App.shrinkWidth;
}
if (menuAvailable && _isExpanded) {
_menuWidth = App.expandWidth;
}
return AnnotatedRegion<SystemUiOverlayStyle>(
// FlexColorScheme contains a helper that can be use to theme
// the system navigation bar using an AnnotatedRegion. Without this
// page wrapper the system navigation bar in Android will not change
// theme color as we change themes for the page. This is a
// Flutter "feature", but with this annotated region we can have the
// navigation bar follow desired background color and theme-mode,
// which looks nicer and more as it should on an Android device.
value: FlexColorScheme.themedSystemNavigationBar(
context,
systemNavBarStyle: systemNavBarStyle,
useDivider: useSysNavDivider,
),
child: Row(
children: <Widget>[
// Contains the demo menu and side rail.
ConstrainedBox(
constraints: const BoxConstraints(maxWidth: App.expandWidth),
child: Material(
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
width: _menuWidth,
child: SideMenu(
maxWidth: App.expandWidth,
onTap: menuAvailable
? () {
setState(() {
_isExpanded = !_isExpanded;
});
}
: null,
),
),
),
),
// The actual page content is a normal Scaffold.
Expanded(
child: Scaffold(
// For scrolling behind the app bar
extendBodyBehindAppBar: true,
// For scrolling behind the bottom nav bar, if there would be one.
extendBody: true,
appBar: AppBar(
title: Text(App.title(context)),
actions: const <Widget>[AboutIconButton()],
backgroundColor: Colors.transparent,
// Gradient partially transparent AppBar, just because it looks
// nice and we can see content scroll behind it.
flexibleSpace: Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(color: Theme.of(context).dividerColor),
),
gradient: LinearGradient(
begin: AlignmentDirectional.centerStart,
end: AlignmentDirectional.centerEnd,
colors: <Color>[
appBarColor,
appBarColor.withOpacity(0.85),
],
),
),
),
),
body: PageBody(
constraints: const BoxConstraints(maxWidth: App.maxBodyWidth),
child: ListView(
padding: EdgeInsets.fromLTRB(
App.edgePadding,
topPadding + kToolbarHeight + App.edgePadding,
App.edgePadding,
App.edgePadding + bottomPadding,
),
children: <Widget>[
Text('Theme', style: headline4),
const Text(
'This example shows how you can use custom colors '
'with FlexColorScheme in light and dark mode, '
'just as defined values in a stateless app.\n\n'
'It uses ThemeMode.system and device settings to '
'toggle between light and dark theme.\n\n'
'The example also has property place holders that '
'you can modify to test other FlexColorScheme '
'features.'),
const SizedBox(height: 8),
// Active theme color indicators.
const Padding(
padding:
EdgeInsets.symmetric(horizontal: App.edgePadding),
child: ShowThemeColors(),
),
const SizedBox(height: 8),
// Open a sub-page
ListTile(
title: const Text('Open a demo subpage'),
subtitle: const Text(
'The subpage will use the same '
'color scheme based theme automatically.',
),
trailing: const Icon(Icons.arrow_forward_ios),
onTap: () {
Subpage.show(context);
},
),
const Divider(),
// Splash pages...
ListTile(
title: const Text('Splash page demo 1a'),
subtitle: const Text(
'No scrim and normal status icons.\n'
'Using themedSystemNavigationBar (noAppBar:true)',
),
trailing: const Icon(Icons.arrow_forward_ios),
onTap: () {
SplashPageOne.show(context, false);
},
),
ListTile(
title: const Text('Splash page demo 1b'),
subtitle: const Text(
'No scrim and inverted status icons.\n'
'Using themedSystemNavigationBar (noAppBar:true, '
'invertStatusIcons:true)',
),
trailing: const Icon(Icons.arrow_forward_ios),
onTap: () {
SplashPageOne.show(context, true);
},
),
ListTile(
title: const Text('Splash page demo 2'),
subtitle: const Text(
'No status icons or navigation bar.\n'
'Using setEnabledSystemUIOverlays([])',
),
trailing: const Icon(Icons.arrow_forward_ios),
onTap: () {
SplashPageTwo.show(context, true);
},
),
const Divider(),
Text('Theme Showcase', style: headline4),
const ThemeShowcase(),
],
),
),
),
),
],
),
);
}
}
| 42.486647
| 80
| 0.589677
|
14c2d9a04ac8b86fe2416f89737ce182186e1264
| 116
|
ts
|
TypeScript
|
backend/src/auth/index.ts
|
my-imouto/my-imouto-viewer
|
2fe8a384113012544de3d1c0932a334cf0360ff1
|
[
"MIT"
] | null | null | null |
backend/src/auth/index.ts
|
my-imouto/my-imouto-viewer
|
2fe8a384113012544de3d1c0932a334cf0360ff1
|
[
"MIT"
] | 3
|
2021-03-10T08:47:16.000Z
|
2021-09-21T07:30:18.000Z
|
backend/src/auth/index.ts
|
my-imouto/my-imouto-viewer
|
2fe8a384113012544de3d1c0932a334cf0360ff1
|
[
"MIT"
] | null | null | null |
export { Session }from './schema/session.schema';
export { AuthObject as ExpressRequestAuth } from './auth-object';
| 38.666667
| 65
| 0.741379
|
dc127011b78b8aedca7826aa818025fd789dcbbe
| 8,936
|
ts
|
TypeScript
|
src/packages/core/src/di/src/BeanFactory.ts
|
jsdevtom/springtype
|
3cccb5af4ddb1b9a26e9f2eaa8368e19c07c982c
|
[
"MIT"
] | null | null | null |
src/packages/core/src/di/src/BeanFactory.ts
|
jsdevtom/springtype
|
3cccb5af4ddb1b9a26e9f2eaa8368e19c07c982c
|
[
"MIT"
] | null | null | null |
src/packages/core/src/di/src/BeanFactory.ts
|
jsdevtom/springtype
|
3cccb5af4ddb1b9a26e9f2eaa8368e19c07c982c
|
[
"MIT"
] | null | null | null |
import {ComponentReflector} from "./ComponentReflector";
import {InjectionProfile} from './enum/InjectionProfile';
import {InjectionStrategy} from "./enum/InjectionStrategy";
import {ComponentImpl} from "./interface/ComponentImpl";
import {resolveInjectionArgumentValue} from "./function/resolveInjectionArgumentValue";
import {ArgumentsInjectionMetadata} from "./interface/ArgumentsInjectionMetadata";
import {ConstructorArgumentInitializer} from "./interface/ConstructorArgumentInitializer";
const PRIMITIVE_TYPE_NAMES = ['Number', 'Array', 'String', 'Boolean', 'RegExp', 'Date'];
export class BeanFactory {
registry = {};
singletonInstances = {};
getBean<T extends ComponentImpl<any>>(
componentCtor: T,
injectionProfile: InjectionProfile = InjectionProfile.DEFAULT,
injectionStrategy: InjectionStrategy = InjectionStrategy.SINGLETON): any {
const originalCtor = componentCtor;
// validate component reference
componentCtor = this.getComponent(componentCtor);
if (!componentCtor || !ComponentReflector.isComponent(componentCtor)) {
return this.solveUnresolvableBean(
originalCtor
);
}
// web component injected via "st-inject"
if (componentCtor.prototype instanceof HTMLElement) {
return componentCtor;
}
const classSymbol = ComponentReflector.getSymbol(componentCtor);
const beanConfig = ComponentReflector.getConfig(componentCtor);
if (injectionProfile === InjectionProfile.TEST &&
beanConfig &&
beanConfig.mockedBy &&
ComponentReflector.isComponent(beanConfig.mockedBy)) {
componentCtor = this.getComponent(beanConfig.mockedBy);
ComponentReflector.setIsMockComponent(componentCtor);
}
// only in case of singleton instance retrieval,
// try to fetch from cache, otherwise directly head to new instance creation
if (injectionStrategy === InjectionStrategy.SINGLETON) {
const singletonInstance = this.getSingletonBeanInstance(classSymbol);
if (singletonInstance) {
return singletonInstance;
}
}
// injectionStrategy === InjectionStrategy.FACTORY || singleton instance not found
const beanInstance = new componentCtor(
...this.resolveConstructorArguments(componentCtor, injectionProfile)
);
this.initializeBeanInstance(beanInstance, ComponentReflector.getInitializers(componentCtor));
if (injectionStrategy === InjectionStrategy.SINGLETON) {
this.setSingletonBeanInstance(classSymbol, beanInstance);
}
return beanInstance;
}
setComponent(componentCtor: ComponentImpl<any>) {
Reflect.set(this.registry, ComponentReflector.getSymbol(componentCtor), componentCtor);
}
getComponent(componentCtor: ComponentImpl<any>) {
return Reflect.get(this.registry, ComponentReflector.getSymbol(componentCtor)) || null;
}
initializeBeanInstance(instance: any, initializers: Array<Function>) {
initializers.forEach((initializer) => {
initializer(instance);
});
}
getSingletonBeanInstance(
classSymbol: symbol
): any {
return Reflect.get(this.singletonInstances, classSymbol);
}
setSingletonBeanInstance(
classSymbol: symbol,
beanInstance: any
): void {
Reflect.set(this.singletonInstances, classSymbol, beanInstance);
}
resolveConstructorArguments<T extends ComponentImpl<any>>(
componentCtor: T,
injectionProfile: InjectionProfile = InjectionProfile.DEFAULT,
): Array<any> {
componentCtor = this.getComponent(componentCtor);
const isTestComponent = ComponentReflector.getIsMockComponent(componentCtor);
const cachedConstructorArguments = ComponentReflector.getResolvedConstructorArguments(componentCtor);
if (cachedConstructorArguments) {
return cachedConstructorArguments;
}
// fetch constructor parameter types from reflection metadata
const constructorParameterTypes: Array<ComponentImpl<any>> = ComponentReflector.getConstructorArgumentTypes(
componentCtor
);
// and do the default round-trip to get all instances by type
const constructorArguments = this.getBeans(
constructorParameterTypes,
componentCtor,
injectionProfile
);
const constructorArgumentsParameterInjectionMetadata: ArgumentsInjectionMetadata =
ComponentReflector.getConstructorArgumentsInjectionMetadata(componentCtor);
// but if there are special @Inject decorations,
// we head to resolve them and use these values instead
if (constructorArgumentsParameterInjectionMetadata &&
constructorArgumentsParameterInjectionMetadata.arguments &&
constructorArgumentsParameterInjectionMetadata.arguments.length) {
const overrideInjectParamValues = constructorArgumentsParameterInjectionMetadata.arguments;
for (let i = 0; i < overrideInjectParamValues.length; i++) {
if (typeof overrideInjectParamValues[i] !== 'undefined') {
constructorArguments[overrideInjectParamValues[i].index] =
resolveInjectionArgumentValue(
constructorArgumentsParameterInjectionMetadata,
overrideInjectParamValues[i].index,
isTestComponent
);
}
}
}
const constructorArgumentInitializers = ComponentReflector.getConstructorArgumentInitializers(componentCtor);
if (constructorArgumentInitializers.length) {
constructorArgumentInitializers.forEach((initializer: ConstructorArgumentInitializer) => {
constructorArguments[initializer.argumentIndex] = initializer.initializer(
constructorArguments[initializer.argumentIndex]
);
});
}
// cache
ComponentReflector.setResolvedConstructorArguments(componentCtor, constructorArguments);
return constructorArguments;
}
getBeans<T extends ComponentImpl<any>>(
types: Array<ComponentImpl<any>>,
forComponentCtor: T,
injectionProfile: InjectionProfile = InjectionProfile.DEFAULT,
): Array<ComponentImpl<any>> {
if (types && types.length > 0) {
const beans: Array<any> = [];
types.forEach((_componentCtor: ComponentImpl<any>) => {
const componentCtor = this.getComponent(_componentCtor);
// the component to inject (componentCtor) matches the component to inject in (forComponentCtor)
if (forComponentCtor === componentCtor) {
beans.push(
this.solveCyclicDependency(componentCtor)
);
} else if (!componentCtor) {
// bean unresolvable -> inject undefined
beans.push(
this.solveUnresolvableBean(
_componentCtor
)
);
} else {
const singletonBeanInstanceFromRegistry = this.getSingletonBeanInstance(
ComponentReflector.getSymbol(componentCtor)
);
if (singletonBeanInstanceFromRegistry) {
beans.push(singletonBeanInstanceFromRegistry)
} else {
beans.push(
// follow down the rabbit hole
this.getBean(componentCtor, injectionProfile)
);
}
}
});
return beans;
}
return [];
}
solveUnresolvableBean<T extends ComponentImpl<any>>(
componentCtor: T
): any {
// inject interfaces as empty objects
if (componentCtor.prototype.constructor === Object) {
return {};
} else {
const typeName = (<any>componentCtor).name;
if (!typeName.match(/HTML.*Element/) && !typeName.match(/SVG.*Element/) && PRIMITIVE_TYPE_NAMES.indexOf(typeName) === -1) {
console.warn(`The component referenced for injection is missing a @Component decorator: ${typeName}`);
}
return undefined;
}
}
solveCyclicDependency<T extends ComponentImpl<any>>(componentCtor: T): T {
console.warn(`Cyclic dependency detected in @Component: ${ComponentReflector.getName(componentCtor)}`);
return componentCtor;
}
}
| 35.460317
| 135
| 0.631155
|
f143a1f888e4d50dd16d5d2cde91f05905e955b4
| 399
|
rb
|
Ruby
|
app/models/user.rb
|
zqianem/unosmium
|
b428c98823c66a3251ae8b5c0e821e28ac5db913
|
[
"MIT"
] | 2
|
2019-06-03T17:44:35.000Z
|
2020-03-01T14:56:48.000Z
|
app/models/user.rb
|
zqianem/unosmium
|
b428c98823c66a3251ae8b5c0e821e28ac5db913
|
[
"MIT"
] | 19
|
2019-05-12T19:49:08.000Z
|
2020-04-07T15:49:06.000Z
|
app/models/user.rb
|
zqianem/unosmium
|
b428c98823c66a3251ae8b5c0e821e28ac5db913
|
[
"MIT"
] | null | null | null |
class User < ApplicationRecord
has_many :admin_roles
has_many :tournaments, through: :admin_roles
has_many :event_supervisor_roles
has_many :events, through: :event_supervisor_roles
validates :first_name, presence: true
validates :last_name, presence: true
validates :email, presence: true
validates_uniqueness_of :email
def full_name
"#{first_name} #{last_name}"
end
end
| 23.470588
| 52
| 0.769424
|
67533126c4dcc95bd7eda71b7db285c02f2c2382
| 958
|
lua
|
Lua
|
src/PipePlacer.lua
|
ccuser44/Hexolus-StructurePlacer
|
ecb62bd060423e9f3ce24bb7575206071d85cf8d
|
[
"BSL-1.0"
] | null | null | null |
src/PipePlacer.lua
|
ccuser44/Hexolus-StructurePlacer
|
ecb62bd060423e9f3ce24bb7575206071d85cf8d
|
[
"BSL-1.0"
] | 2
|
2021-03-14T06:48:58.000Z
|
2021-03-14T06:57:43.000Z
|
src/PipePlacer.lua
|
ccuser44/Hexolus-StructurePlacer
|
ecb62bd060423e9f3ce24bb7575206071d85cf8d
|
[
"BSL-1.0"
] | 1
|
2021-03-11T19:00:13.000Z
|
2021-03-11T19:00:13.000Z
|
local PiperPlacer = {}
function PiperPlacer.new(model)
local Placer = {}
Placer.Model = model
Placer.Rotation = 0
local endEvent = Instance.new("BindableEvent")
Placer.Ended = endEvent.Event
Placer.Valid = false
local previousPosition, previousNormal, previousCenter
function Placer:Update(position, normal, center)
previousPosition, previousNormal, previousCenter = position, normal, center
self.Valid = true
end
function Placer:Add(...)
self:Update(...)
if self.Valid then
self:Cancel(true)
end
end
function Placer:Rotate(amount)
self.Rotation = (self.Rotation + amount) % 360
if previousPosition and previousNormal and previousCenter then
Placer:Update(previousPosition, previousNormal, previousCenter)
end
end
function Placer:Cancel(didPlace)
if endEvent then
local event = endEvent
endEvent = nil
event:Fire(didPlace)
event:Destroy()
end
end
return Placer
end
return PiperPlacer
| 20.382979
| 77
| 0.73904
|
686f978487bc9b35977d428b06d4b0f00f17a795
| 452
|
kt
|
Kotlin
|
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/utils/LogHelper.kt
|
NieKam/WykopMobilny
|
ba14f6426f84ef3b12b846de4efd6275e268dbbb
|
[
"MIT"
] | 193
|
2017-07-21T20:51:41.000Z
|
2022-02-25T15:54:51.000Z
|
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/utils/LogHelper.kt
|
NieKam/WykopMobilny
|
ba14f6426f84ef3b12b846de4efd6275e268dbbb
|
[
"MIT"
] | 125
|
2017-07-21T19:50:11.000Z
|
2022-01-06T11:07:35.000Z
|
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/utils/LogHelper.kt
|
NieKam/WykopMobilny
|
ba14f6426f84ef3b12b846de4efd6275e268dbbb
|
[
"MIT"
] | 80
|
2017-07-21T19:22:32.000Z
|
2022-01-06T08:30:36.000Z
|
package io.github.feelfreelinux.wykopmobilny.utils
import android.util.Log
import io.github.feelfreelinux.wykopmobilny.BuildConfig
public var APP_TAG = "WykopAPI"
fun printout(msg: String) {
if (BuildConfig.DEBUG) Log.v(APP_TAG, msg)
}
fun wykopLog(logger: (String, String, Throwable) -> Int, msg: String, th: Throwable) {
logger(APP_TAG, msg, th)
}
fun wykopLog(logger: (String, String) -> Int, msg: String) {
logger(APP_TAG, msg)
}
| 22.6
| 86
| 0.723451
|
af565596f1c076d19b66d56e36147eb9f11b8b55
| 854
|
py
|
Python
|
108.Convert-Sorted-Array-to-Binary-Search-Tree.py
|
mickey0524/leetcode
|
6bedeb6ff29b02a97178cca464c5fd639951801f
|
[
"MIT"
] | 18
|
2018-07-14T12:45:37.000Z
|
2022-03-26T14:51:04.000Z
|
108.Convert-Sorted-Array-to-Binary-Search-Tree.py
|
mickey0524/leetcode
|
6bedeb6ff29b02a97178cca464c5fd639951801f
|
[
"MIT"
] | null | null | null |
108.Convert-Sorted-Array-to-Binary-Search-Tree.py
|
mickey0524/leetcode
|
6bedeb6ff29b02a97178cca464c5fd639951801f
|
[
"MIT"
] | 3
|
2019-05-29T04:09:22.000Z
|
2021-06-07T23:37:46.000Z
|
# https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
#
# algorithms
# Easy (48.15%)
# Total Accepted: 222,749
# Total Submissions: 462,569
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
length = len(nums)
if length == 0:
return None
if length == 1:
return TreeNode(nums[0])
middle = length / 2
node = TreeNode(nums[middle])
node.left = self.sortedArrayToBST(nums[:middle])
node.right = self.sortedArrayToBST(nums[middle + 1:])
return node
| 25.117647
| 75
| 0.552693
|
43a5b7a0095aa5ba3848ba5eb10075ef211576f9
| 468
|
tsx
|
TypeScript
|
apps/web/hooks/useKeys.tsx
|
faisalsayed10/firefiles
|
655e9fbc451bb4df65c08a60738d9993127fb852
|
[
"MIT"
] | 81
|
2021-11-29T05:22:25.000Z
|
2022-03-15T03:07:35.000Z
|
apps/web/hooks/useKeys.tsx
|
faisalsayed10/firefiles
|
655e9fbc451bb4df65c08a60738d9993127fb852
|
[
"MIT"
] | 18
|
2022-01-23T14:23:22.000Z
|
2022-03-12T15:54:13.000Z
|
apps/web/hooks/useKeys.tsx
|
faisalsayed10/firefiles
|
655e9fbc451bb4df65c08a60738d9993127fb852
|
[
"MIT"
] | 13
|
2022-01-23T12:23:25.000Z
|
2022-03-27T01:04:13.000Z
|
import { Drive } from "@prisma/client";
import { createContext, useContext, useState } from "react";
type ContextValue = {
keys: Drive;
};
interface Props {
data: Drive;
}
const KeysContext = createContext<ContextValue>(null);
export default () => useContext(KeysContext);
export const KeysProvider: React.FC<Props> = ({ data, children }) => {
const [keys] = useState(data);
return <KeysContext.Provider value={{ keys }}>{children}</KeysContext.Provider>;
};
| 23.4
| 81
| 0.702991
|
439eff6538276bedc286c73c85f926c70759686b
| 3,410
|
ts
|
TypeScript
|
packages/glide-runtime/src/resolver.ts
|
postlight/glide
|
3cb730d83d7faff9da8d03c80829a04916485663
|
[
"Apache-2.0",
"MIT"
] | 79
|
2019-05-21T16:06:25.000Z
|
2022-03-17T09:44:19.000Z
|
packages/glide-runtime/src/resolver.ts
|
postlight/glide
|
3cb730d83d7faff9da8d03c80829a04916485663
|
[
"Apache-2.0",
"MIT"
] | 6
|
2019-05-21T20:08:46.000Z
|
2021-08-16T18:04:57.000Z
|
packages/glide-runtime/src/resolver.ts
|
postlight/glide
|
3cb730d83d7faff9da8d03c80829a04916485663
|
[
"Apache-2.0",
"MIT"
] | 5
|
2019-09-16T21:49:55.000Z
|
2020-07-31T19:33:00.000Z
|
import soql, { and, cmp } from "@glide/soql";
import * as graphql from "graphql";
import { Connection } from "jsforce";
import { find, get, set } from "lodash";
import { Maybe, Table, bail, expect } from "./helpers";
import { Definition } from "./define";
export type ASTNode = Maybe<graphql.ASTNode[] | graphql.ASTNode>;
export type Arguments = Table<unknown>;
export type Parameters = Table<Definition<"Parameter">>;
export interface Resolver {
(obj: null, args: Arguments, context: Connection, info: graphql.GraphQLResolveInfo): Promise<
object
>;
}
export function resolve(
_schema: Definition<"Schema">,
params: Parameters,
type: Definition<"Type">,
): Resolver {
const primaryKey = expect(find(type.fields, "primaryKey"));
return async (_obj, _args, context, info) => {
const { directives, operation } = info.operation;
const ancestors = [] as string[];
const changes = {};
const query = soql(type.table);
let where = and();
function pathFromNode(node: graphql.NameNode, root = true) {
const { source } = type.fields[node.value];
return [...ancestors.slice(root ? 0 : 1), source].join(".");
}
function valueFromNode(node: graphql.ValueNode) {
return graphql.valueFromASTUntyped(node, info.variableValues);
}
visit(Array.from(directives || []), {
Argument: ({ name, value }) => {
switch (name.value) {
case "limit": {
query.limit(valueFromNode(value));
break;
}
case "offset": {
query.offset(valueFromNode(value));
break;
}
}
},
});
visit(nodeFor(info), {
Argument: argument => {
const { operator } = expect(params[argument.name.value]);
const value = valueFromNode(argument.value);
if (operator === "assign") {
set(changes, pathFromNode(argument.name, false), value);
} else {
where = and(where, cmp[operator](pathFromNode(argument.name), value));
}
},
Field: {
enter: ({ name, selectionSet }) => {
if (ancestors.length === 0) {
ancestors.push(type.table);
} else if (selectionSet) {
ancestors.push(type.fields[name.value].source);
} else {
const { source } = type.fields[name.value];
query.select([...ancestors, source].join("."));
}
},
leave: ({ selectionSet }) => {
if (selectionSet) {
ancestors.pop();
}
},
},
});
query.where(where);
switch (operation) {
case "mutation": {
const result = await context.upsert(type.table, changes, primaryKey.source);
return get(await context.query(`${query}`), "records.0");
}
case "query": {
return get(await context.query(`${query}`), "records");
}
default: {
return bail(`Operations of type "%s" are not supported.`, operation);
}
}
};
}
function nodeFor(info: graphql.GraphQLResolveInfo): Maybe<graphql.FieldNode> {
return info.fieldNodes.find(node => info.fieldName === node.name.value);
}
function visit(node: ASTNode, visitor: graphql.ASTVisitor): void {
if (Array.isArray(node)) {
node.forEach(child => graphql.visit(child, visitor));
} else if (node && "kind" in node) {
graphql.visit(node, visitor);
}
}
| 29.652174
| 95
| 0.583578
|
23a3138e025d60a562acd7b46727bfa11673c53f
| 172
|
js
|
JavaScript
|
dist/es2019/popup/tools/findAccount.js
|
willmendesneto/willmendesneto-playground
|
767cf7ef5843315ac0148426aba8f19728585c3b
|
[
"Apache-2.0"
] | null | null | null |
dist/es2019/popup/tools/findAccount.js
|
willmendesneto/willmendesneto-playground
|
767cf7ef5843315ac0148426aba8f19728585c3b
|
[
"Apache-2.0"
] | 2
|
2020-06-28T17:32:22.000Z
|
2020-08-01T03:59:30.000Z
|
dist/es2019/popup/tools/findAccount.js
|
willmendesneto/willmendesneto-playground
|
767cf7ef5843315ac0148426aba8f19728585c3b
|
[
"Apache-2.0"
] | null | null | null |
export const findAccount = function (accounts, accountId) {
return accounts.filter((account) => account.id === accountId)[0];
};
//# sourceMappingURL=findAccount.js.map
| 43
| 69
| 0.726744
|
f4446990a09cf688431916b1c47423c77c2c5fe1
| 331
|
cs
|
C#
|
src/BasicService/GreeterLogic.Tests/UnitTest1.cs
|
ozziepeeps/featherservicetest
|
2203cb5c40de07a7500ac0156cfe28b741540b2d
|
[
"Apache-2.0"
] | 2
|
2021-04-28T23:46:22.000Z
|
2021-05-20T10:55:58.000Z
|
src/BasicService/GreeterLogic.Tests/UnitTest1.cs
|
ozziepeeps/featherservicetest
|
2203cb5c40de07a7500ac0156cfe28b741540b2d
|
[
"Apache-2.0"
] | 1
|
2021-04-30T19:27:58.000Z
|
2021-04-30T19:27:58.000Z
|
src/BasicService/GreeterLogic.Tests/UnitTest1.cs
|
ozziepeeps/featherservicetest
|
2203cb5c40de07a7500ac0156cfe28b741540b2d
|
[
"Apache-2.0"
] | 3
|
2021-04-30T03:12:11.000Z
|
2021-05-20T10:56:09.000Z
|
using System;
using Xunit;
namespace GreeterLogic.Tests
{
public class UnitTest
{
[Fact]
public void Test1()
{
GreeterProvider provider = new GreeterProvider();
var greeting = provider.SayHello("James");
Assert.True(greeting == "Hello James");
}
}
}
| 19.470588
| 61
| 0.561934
|
23c772650ece50a34fb272114127e2f8f37546a6
| 4,491
|
js
|
JavaScript
|
src/NowPlayingService.js
|
idarryl/homebridge-dacp
|
8a8f472f72eab24eb9b0c7ce0e9c599a7be723f3
|
[
"MIT"
] | 159
|
2017-12-09T18:48:14.000Z
|
2022-02-01T12:44:48.000Z
|
src/NowPlayingService.js
|
Leonoerlemans/homebridge-dacp
|
8a8f472f72eab24eb9b0c7ce0e9c599a7be723f3
|
[
"MIT"
] | 69
|
2017-12-09T23:55:46.000Z
|
2022-01-31T20:53:19.000Z
|
src/NowPlayingService.js
|
Leonoerlemans/homebridge-dacp
|
8a8f472f72eab24eb9b0c7ce0e9c599a7be723f3
|
[
"MIT"
] | 24
|
2017-12-25T18:43:48.000Z
|
2021-08-25T08:11:46.000Z
|
'use strict';
let Characteristic, Service;
const moment = require('moment');
const util = require('util');
const fs = require('fs');
class NowPlayingService {
constructor(homebridge, log, name, dacp, artworkFile) {
Characteristic = homebridge.Characteristic;
Service = homebridge.Service;
this.log = log;
this.name = name;
this._dacp = dacp;
this._timeout = undefined;
this._artworkFile = artworkFile;
this.createService();
}
getService() {
return this._service;
}
createService() {
this._service = new Service.NowPlayingService(this.name);
this._resetCharacteristicsToDefaults();
}
accessoryDown() {
this._resetCharacteristicsToDefaults();
}
_resetCharacteristicsToDefaults() {
this._state = {
track: '',
album: '',
artist: '',
genre: '',
type: -1,
position: Number.NaN,
duration: Number.NaN,
playerState: 0
};
this._updateCharacteristics();
}
update(response) {
const prevTrack = this._state.track;
this._state = {
track: this._getProperty(response, 'cann', ''),
album: this._getProperty(response, 'canl', ''),
artist: this._getProperty(response, 'cana', ''),
genre: this._getProperty(response, 'cang', ''),
mediaType: this._getProperty(response, 'cmmk', 0),
remaining: this._getProperty(response, 'cant', Number.NaN),
duration: this._getProperty(response, 'cast', Number.NaN),
playerState: this._getProperty(response, 'caps', 0)
};
this._updateCharacteristics();
if (prevTrack !== this._state.track) {
this._updateArtwork();
}
}
_getProperty(response, prop, defaultValue) {
if (response.hasOwnProperty(prop)) {
return response[prop];
}
return defaultValue;
}
_updateCharacteristics() {
this._service.getCharacteristic(Characteristic.Title)
.updateValue(this._state.track);
this._service.getCharacteristic(Characteristic.Album)
.updateValue(this._state.album);
this._service.getCharacteristic(Characteristic.Artist)
.updateValue(this._state.artist);
this._service.getCharacteristic(Characteristic.Genre)
.updateValue(this._state.genre);
this._service.getCharacteristic(Characteristic.MediaType)
.updateValue(this._state.mediaType);
this._updatePosition();
this._respectPlayerState();
}
_updatePosition() {
this._setTime(Characteristic.MediaCurrentPosition, (this._state.duration - this._state.remaining) / 1000);
this._setTime(Characteristic.MediaItemDuration, this._state.duration / 1000);
}
_setTime(characteristic, totalSeconds) {
let minutes = Math.floor(totalSeconds / 60);
let seconds = Math.round(totalSeconds - (minutes * 60));
let value = '';
if (!Number.isNaN(seconds)) {
value = moment({ minutes: minutes, seconds: seconds }).format('mm:ss');
}
this._service.getCharacteristic(characteristic)
.updateValue(value);
}
_respectPlayerState() {
if (this._state.playerState === 4) {
if (!this._timeout) {
this._timeout = setTimeout(this._requestPlaybackPosition.bind(this), 1000);
}
}
else if (this._timeout) {
clearTimeout(this._timeout);
this._timeout = undefined;
}
}
async _requestPlaybackPosition() {
try {
const response = await this._dacp.getProperty('dacp.playingtime');
this._timeout = undefined;
this._state.remaining = this._getProperty(response, 'cant', Number.NaN);
this._state.duration = this._getProperty(response, 'cast', Number.NaN);
this._updateCharacteristics();
this._respectPlayerState();
}
catch (e) {
this.log(`Failed to retrieve the current playback position. Stopping continuous updates. Error: ${util.inspect(e)}`);
this._resetCharacteristicsToDefaults();
}
}
_updateArtwork() {
if (typeof this._artworkFile === 'string') {
this._dacp.getArtwork()
.then(response => {
fs.writeFile(this._artworkFile, response.body, (err) => {
if (err) {
this.log(`Failed to write artwork: ${util.inspect(err)}`);
this.log('Will not write any artwork from now on.');
this._artworkFile = undefined;
}
});
})
.catch(e => {
this.log(`Artwork request failed. Error: ${util.inspect(e)}`);
});
}
}
}
module.exports = NowPlayingService;
| 26.573964
| 123
| 0.644623
|
1d0300a838cd574632b40b67fe61a5c8fb401f44
| 875
|
lua
|
Lua
|
lua/plugins/tmux.lua
|
gcoguiec/nvimfiles
|
08915ce2e380b916f5f83b0e32f1fe0cd2f6bc47
|
[
"BSD-2-Clause"
] | 3
|
2021-12-12T02:20:22.000Z
|
2021-12-14T00:04:59.000Z
|
lua/plugins/tmux.lua
|
gcoguiec/nvimfiles
|
08915ce2e380b916f5f83b0e32f1fe0cd2f6bc47
|
[
"BSD-2-Clause"
] | null | null | null |
lua/plugins/tmux.lua
|
gcoguiec/nvimfiles
|
08915ce2e380b916f5f83b0e32f1fe0cd2f6bc47
|
[
"BSD-2-Clause"
] | null | null | null |
local map = vim.api.nvim_set_keymap
-- mappings
local opts = { noremap = true, silent = true, nowait = true }
map('n', '<M-z>', '<cmd>lua require(\'tmux\').move_top()<cr>', opts)
map('n', '<M-q>', '<cmd>lua require(\'tmux\').move_left()<cr>', opts)
map('n', '<M-s>', '<cmd>lua require(\'tmux\').move_bottom()<cr>', opts)
map('n', '<M-d>', '<cmd>lua require(\'tmux\').move_right()<cr>', opts)
map('n', '<C-M-z>', '<cmd>lua require(\'tmux\').resize_top()<cr>', opts)
map('n', '<C-M-q>', '<cmd>lua require(\'tmux\').resize_left()<cr>', opts)
map('n', '<C-M-s>', '<cmd>lua require(\'tmux\').resize_bottom()<cr>', opts)
map('n', '<C-M-d>', '<cmd>lua require(\'tmux\').resize_right()<cr>', opts)
require('tmux').setup {
navigation = { enable_default_keybindings = false },
resize = {
enable_default_keybindings = false,
resize_step_x = 2,
resize_step_y = 2
}
}
| 39.772727
| 75
| 0.593143
|
4464e604aa4eb12b8295527274ec65ad4d4cc7b7
| 704
|
py
|
Python
|
4-web-apps/javascript-ajax-apis/foursquare/foursquare-explore.py
|
alwaleedibrahim/udacity-fsnd
|
45f38f6eb42f1540b10bc60ffe999ebc7d9193b7
|
[
"MIT"
] | 72
|
2018-02-26T10:28:21.000Z
|
2022-03-17T17:42:40.000Z
|
4-web-apps/javascript-ajax-apis/foursquare/foursquare-explore.py
|
MohamedHaggag/udacity-fsnd
|
9fa58bfba98ddb2597ed7c37f71db1c2052dc479
|
[
"MIT"
] | 1
|
2020-07-11T10:18:58.000Z
|
2020-07-11T10:18:58.000Z
|
4-web-apps/javascript-ajax-apis/foursquare/foursquare-explore.py
|
MohamedHaggag/udacity-fsnd
|
9fa58bfba98ddb2597ed7c37f71db1c2052dc479
|
[
"MIT"
] | 53
|
2018-02-26T10:27:58.000Z
|
2022-01-22T00:19:17.000Z
|
import json
import requests
url = 'https://api.foursquare.com/v2/venues/search'
params = dict(client_id='PASTE_YOUR_KEY_HERE',
client_secret='PASTE_YOUR_SECRET_HERE',
v='20180323',
ll='42.3495694,-71.0836727',
query='george howell',
limit=1)
resp = requests.get(url=url, params=params)
data = json.loads(resp.text)
# If this file is called as a standalone program:
if __name__ == '__main__':
# Run a sample location for debugging
print(data)
print('\n Venue name: {} \n Venue address: {}'
.format(data['response']['venues'][0]['name'],
data['response']['venues'][0]['location']['address']))
| 32
| 72
| 0.606534
|
00f32c444f3d65ce83eac38fa505693c8076aa76
| 382
|
rs
|
Rust
|
src/sonic/sonic/mod.rs
|
adetante/bellman
|
b6125d2093abb645827e8ef279896f8f6998053b
|
[
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 77
|
2019-02-20T17:08:57.000Z
|
2022-02-16T14:16:49.000Z
|
src/sonic/sonic/mod.rs
|
adetante/bellman
|
b6125d2093abb645827e8ef279896f8f6998053b
|
[
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 23
|
2019-03-31T13:02:04.000Z
|
2022-02-05T09:50:08.000Z
|
src/sonic/sonic/mod.rs
|
adetante/bellman
|
b6125d2093abb645827e8ef279896f8f6998053b
|
[
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 55
|
2019-02-20T15:59:35.000Z
|
2022-03-11T08:42:21.000Z
|
mod adaptor;
mod synthesis_drivers;
mod backends;
mod constraint_systems;
pub use self::adaptor::{Adaptor, AdaptorCircuit};
pub use self::synthesis_drivers::{Basic, Nonassigning, Permutation3};
pub use self::backends::{CountNandQ, CountN, Preprocess, Wires};
pub use self::constraint_systems::{NonassigningSynthesizer, Synthesizer, PermutationSynthesizer};
pub const M: usize = 3;
| 34.727273
| 97
| 0.795812
|
bf97eca7113d6b2e67fdc323ba2d0560a1f17d88
| 1,354
|
ps1
|
PowerShell
|
Repository/pages/inputs/radio.ps1
|
ironmansoftware/poshud.com
|
dfef84220854a05443c4b4dce1ac75acee9de06d
|
[
"MIT"
] | 1
|
2021-10-03T13:21:49.000Z
|
2021-10-03T13:21:49.000Z
|
Repository/pages/inputs/radio.ps1
|
ironmansoftware/poshud.com
|
dfef84220854a05443c4b4dce1ac75acee9de06d
|
[
"MIT"
] | null | null | null |
Repository/pages/inputs/radio.ps1
|
ironmansoftware/poshud.com
|
dfef84220854a05443c4b4dce1ac75acee9de06d
|
[
"MIT"
] | null | null | null |
New-ComponentPage -Title 'Radio' -Description 'Radio buttons allow the user to select one option from a set.' -SecondDescription "Use radio buttons when the user needs to see all available options. If available options can be collapsed, consider using a dropdown menu because it uses less space.
Radio buttons should have the most commonly used option selected by default." -Content {
New-Example -Title 'Simple Radio' -Description '' -Example {
New-UDRadioGroup -Label "Day" -Content {
New-UDRadio -Label Monday -Value 'monday'
New-UDRadio -Label Tuesday -Value 'tuesday'
New-UDRadio -Label Wednesday -Value 'wednesday'
New-UDRadio -Label Thursday -Value 'thursday'
New-UDRadio -Label Friday -Value 'friday'
New-UDRadio -Label Saturday -Value 'saturday'
New-UDRadio -Label Sunday -Value 'sunday'
}
}
New-Example -Title 'OnChange' -Description '' -Example {
New-UDRadioGroup -Label "Day" -Content {
New-UDRadio -Label Monday -Value 'monday'
New-UDRadio -Label Tuesday -Value 'tuesday'
New-UDRadio -Label Wednesday -Value 'wednesday'
New-UDRadio -Label Thursday -Value 'thursday'
New-UDRadio -Label Friday -Value 'friday'
New-UDRadio -Label Saturday -Value 'saturday'
New-UDRadio -Label Sunday -Value 'sunday'
} -OnChange { Show-UDToast -Message $Body }
}
} -Cmdlet "New-UDRadio"
| 50.148148
| 295
| 0.723781
|
4cdb2bb5b0f4ac11fc917ca03d7d5afb927c4706
| 1,454
|
py
|
Python
|
test/json/_JSONObjectTest.py
|
waikato-datamining/wai-json
|
cb013fb16e7c1b8d91e040a387a143d29d4ced96
|
[
"MIT"
] | null | null | null |
test/json/_JSONObjectTest.py
|
waikato-datamining/wai-json
|
cb013fb16e7c1b8d91e040a387a143d29d4ced96
|
[
"MIT"
] | 2
|
2020-07-30T22:41:42.000Z
|
2021-09-21T23:18:06.000Z
|
test/json/_JSONObjectTest.py
|
waikato-datamining/wai-json
|
cb013fb16e7c1b8d91e040a387a143d29d4ced96
|
[
"MIT"
] | null | null | null |
from wai.test import AbstractTest
from wai.test.decorators import RegressionTest, Test, ExceptionTest
from json import loads
from wai.json.object import JSONObject
from wai.json.object.property import *
class JSONObjectTest(AbstractTest):
"""
Unit tests for JSON objects.
"""
@classmethod
def subject_type(cls):
# Default test subject is a plain object
return JSONObject
@Test
def properties(self, subject: JSONObject):
"""
Test creating a new sub-class of JSONObject.
"""
class TestObject(JSONObject):
a = NumberProperty()
b = StringProperty()
c = BoolProperty()
d = EnumProperty(values=(1, 2, "three", "blue"))
e = ConstantProperty(value="test")
f = ArrayProperty(element_property=NumberProperty())
g = MapProperty(value_property=StringProperty())
h = JSONObjectProperty(object_type=JSONObject)
i = AnyOfProperty(sub_properties=(NumberProperty(), StringProperty()))
j = AllOfProperty(sub_properties=(NumberProperty(multiple_of=3), NumberProperty(multiple_of=5)))
k = OneOfProperty(sub_properties=(NumberProperty(multiple_of=3), NumberProperty(multiple_of=5)))
@Test
def set_additional_property(self, subject: JSONObject):
subject.set_property("test", 13)
self.assertDictEqual(subject.to_raw_json(), {"test": 13})
| 34.619048
| 108
| 0.658872
|
82baecf267966bbdff8daa4ab379ffb5559852e4
| 3,225
|
lua
|
Lua
|
ProtoplugFiles/effects/pitch delay.lua
|
Sin-tel/protoplug
|
8dada61a466f94b0450faabe4a3fe45950cc9b23
|
[
"MIT"
] | 13
|
2019-07-27T14:15:53.000Z
|
2022-02-06T17:58:24.000Z
|
ProtoplugFiles/effects/pitch delay.lua
|
Sin-tel/protoplug
|
8dada61a466f94b0450faabe4a3fe45950cc9b23
|
[
"MIT"
] | null | null | null |
ProtoplugFiles/effects/pitch delay.lua
|
Sin-tel/protoplug
|
8dada61a466f94b0450faabe4a3fe45950cc9b23
|
[
"MIT"
] | 3
|
2020-09-30T16:28:44.000Z
|
2021-06-03T09:44:22.000Z
|
require "include/protoplug"
FLine = require "include/dsp/fdelay_line"
local cbFilter = require "include/dsp/cookbook filters"
local maxLength = 3*44100
local fadeSpeed = 20/44100
local balance = 0.5
local lpfilters = {}
local hpfilters = {}
stereoFx.init()
function stereoFx.Channel:init()
self.delayline = FLine(maxLength)
self.length = 0
self.ptr1 = 0
self.ptr2 = 0
self.a1 = 1.0
self.a2 = 0.0
self.fade = 1
self.lp = cbFilter
{
type = "lp";
f = 12000;
gain = 0;
Q = 0.7;
}
table.insert(lpfilters, self.lp)
self.hp = cbFilter
{
type = "hp";
f = 350;
gain = 0;
Q = 0.7;
}
table.insert(hpfilters, self.hp)
end
function stereoFx.Channel:processBlock(samples, smax)
for i = 0,smax do
self.length = self.length*0.999 + length*0.001
local l = self.length*44100
self.ptr1 = self.ptr1 - (speed - 1)
self.ptr2 = self.ptr2 - (speed - 1)
if self.fade == 1 then
self.a1 = math.min(1.0,self.a1+fadeSpeed)
self.a2 = math.max(0.0,self.a2-fadeSpeed)
else
self.a2 = math.min(1.0,self.a2+fadeSpeed)
self.a1 = math.max(0.0,self.a1-fadeSpeed)
end
if speed >= 1 then
if self.ptr1 < l*0.5 and self.fade == 1 then
self.ptr2 = l*1.5
self.fade = 2
end
if self.ptr2 < l*0.5 and self.fade == 2 then
self.ptr1 = l*1.5
self.fade = 1
end
else
if self.ptr1 > l*1.5 and self.fade == 1 then
self.ptr2 = l*0.5
self.fade = 2
end
if self.ptr2 > l*1.5 and self.fade == 2 then
self.ptr1 = l*0.5
self.fade = 1
end
end
--self.ptr = self.ptr % maxLength
local s = samples[i]
local d = self.delayline.goBack(self.ptr1)*self.a1 + self.delayline.goBack(self.ptr2)*self.a2
d = self.lp.process(d)
d = self.hp.process(d)
if (gain > 1) then
d = softclip(d*gain)/gain
end
local signal = s+d*feedback
self.delayline.push(signal)
samples[i] = s*(1.0-balance)+d*balance
end
end
function softclip(x)
if x <= -1 then
return -2.0/3.0
elseif x >= 1 then
return 2.0/3.0
else
return x - (x*x*x)/3.0
end
end
local function updateFilters(filters,args)
for _, f in pairs(filters) do
f.update(args)
end
end
params = plugin.manageParams {
{
name = "Length";
max = 2;
changed = function(val) length = val end;
};
{
name = "Feedback";
max = 1.2;
changed = function(val) feedback = val end;
};
{
name = "Speed";
max = 3;
min = -3;
changed = function(val) speed = val end;
};
{
name = "Distort";
max = 4;
min = 1;
changed = function(val) gain = val end;
};
{
name = "Dry/Wet";
min = 0;
max = 1;
changed = function(val) balance = val end;
};
{
name = "Highpass";
min = 0;
max = 1000;
changed = function(val) updateFilters(hpfilters,{f=val}) end;
};
{
name = "Lowpass";
min = 5000;
max = 22000;
changed = function(val) updateFilters(lpfilters,{f=val}) end;
};
}
| 20.806452
| 98
| 0.543566
|
72a1a1b68871a8c8ddc6374be32124cc5ab866d9
| 559
|
asm
|
Assembly
|
03-bootsector-memory/boot_sect_memory_2.asm
|
gyuki1029/os-tutorial
|
8a69dfac07abeaa2d319ba0a842c74e53193fd7f
|
[
"BSD-3-Clause"
] | null | null | null |
03-bootsector-memory/boot_sect_memory_2.asm
|
gyuki1029/os-tutorial
|
8a69dfac07abeaa2d319ba0a842c74e53193fd7f
|
[
"BSD-3-Clause"
] | null | null | null |
03-bootsector-memory/boot_sect_memory_2.asm
|
gyuki1029/os-tutorial
|
8a69dfac07abeaa2d319ba0a842c74e53193fd7f
|
[
"BSD-3-Clause"
] | null | null | null |
mov ah, 0x0e
; attempt 2
; It tries to print the memory address of 'the_secret' which is the correct approach.
; However, BIOS places our bootsector binary at address 0x7c00
; so we need to add that padding beforehand. We'll do that in attempt 3
mov al, "2"
int 0x10
mov al, [the_secret]
int 0x10
jmp $ ; infinite loop
the_secret:
; ASCII code 0x58 ('X') is stored just before the zero-padding.
; On this code that is at byte 0x2d (check it out using 'xxd file.bin')
db "X"
; zero padding and magic bios number
times 510-($-$$) db 0
dw 0xaa55
| 25.409091
| 85
| 0.710197
|
26594a35981323777c1c204b57c4aeb684729316
| 4,584
|
rs
|
Rust
|
src/types_impl/lob/wire.rs
|
PSeitz/rust-hdbconnect
|
0098a266e16b6da2560c5e4663c0b78ef2d4d249
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
src/types_impl/lob/wire.rs
|
PSeitz/rust-hdbconnect
|
0098a266e16b6da2560c5e4663c0b78ef2d4d249
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
src/types_impl/lob/wire.rs
|
PSeitz/rust-hdbconnect
|
0098a266e16b6da2560c5e4663c0b78ef2d4d249
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
use crate::conn::AmConnCore;
use crate::protocol::parts::{AmRsCore, TypeId};
use crate::protocol::util;
use crate::types::{BLob, CLob, NCLob};
use crate::HdbValue;
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
pub(crate) fn parse_blob(
am_conn_core: &AmConnCore,
o_am_rscore: &Option<AmRsCore>,
nullable: bool,
rdr: &mut dyn std::io::Read,
) -> std::io::Result<HdbValue<'static>> {
let (is_null, is_data_included, is_last_data) = parse_lob_1(rdr)?;
if is_null {
if nullable {
Ok(HdbValue::NULL)
} else {
Err(util::io_error("found null value for not-null BLOB column"))
}
} else {
let (_, length, locator_id, data) = parse_lob_2(rdr, is_data_included)?;
Ok(HdbValue::BLOB(BLob::new(
am_conn_core,
o_am_rscore,
is_last_data,
length,
locator_id,
data,
)))
}
}
pub(crate) fn parse_clob(
am_conn_core: &AmConnCore,
o_am_rscore: &Option<AmRsCore>,
nullable: bool,
rdr: &mut dyn std::io::Read,
) -> std::io::Result<HdbValue<'static>> {
let (is_null, is_data_included, is_last_data) = parse_lob_1(rdr)?;
if is_null {
if nullable {
Ok(HdbValue::NULL)
} else {
Err(util::io_error("found null value for not-null CLOB column"))
}
} else {
let (char_length, byte_length, locator_id, data) = parse_lob_2(rdr, is_data_included)?;
Ok(HdbValue::CLOB(
CLob::new(
am_conn_core,
o_am_rscore,
is_last_data,
char_length,
byte_length,
locator_id,
data,
)
.map_err(|e| util::io_error(e.to_string()))?,
))
}
}
pub(crate) fn parse_nclob(
am_conn_core: &AmConnCore,
o_am_rscore: &Option<AmRsCore>,
nullable: bool,
type_id: TypeId,
rdr: &mut dyn std::io::Read,
) -> std::io::Result<HdbValue<'static>> {
let (is_null, is_data_included, is_last_data) = parse_lob_1(rdr)?;
if is_null {
if nullable {
Ok(HdbValue::NULL)
} else {
Err(util::io_error("found null value for not-null NCLOB column"))
}
} else {
let (char_length, byte_length, locator_id, data) = parse_lob_2(rdr, is_data_included)?;
Ok(match type_id {
TypeId::TEXT | TypeId::NCLOB => HdbValue::NCLOB(
NCLob::new(
am_conn_core,
o_am_rscore,
is_last_data,
char_length,
byte_length,
locator_id,
data,
)
.map_err(|e| util::io_error(e.to_string()))?,
),
_ => return Err(util::io_error("unexpected type id for nclob")),
})
}
}
fn parse_lob_1(rdr: &mut dyn std::io::Read) -> std::io::Result<(bool, bool, bool)> {
let _data_type = rdr.read_u8()?; // I1
let options = rdr.read_u8()?; // I1
let is_null = (options & 0b_1_u8) != 0;
let is_data_included = (options & 0b_10_u8) != 0;
let is_last_data = (options & 0b_100_u8) != 0;
Ok((is_null, is_data_included, is_last_data))
}
fn parse_lob_2(
rdr: &mut dyn std::io::Read,
is_data_included: bool,
) -> std::io::Result<(u64, u64, u64, Vec<u8>)> {
util::skip_bytes(2, rdr)?; // U2 (filler)
let total_char_length = rdr.read_u64::<LittleEndian>()?; // I8
let total_byte_length = rdr.read_u64::<LittleEndian>()?; // I8
let locator_id = rdr.read_u64::<LittleEndian>()?; // I8
let chunk_length = rdr.read_u32::<LittleEndian>()?; // I4
if is_data_included {
let data = util::parse_bytes(chunk_length as usize, rdr)?; // B[chunk_length]
Ok((total_char_length, total_byte_length, locator_id, data))
} else {
Ok((
total_char_length,
total_byte_length,
locator_id,
Vec::<u8>::new(),
))
}
}
#[allow(clippy::cast_possible_truncation)]
pub(crate) fn emit_lob_header(
length: u64,
offset: &mut i32,
w: &mut dyn std::io::Write,
) -> std::io::Result<()> {
// bit 0: not used; bit 1: data is included; bit 2: no more data remaining
w.write_u8(0b_000_u8)?; // I1 Bit set for options
w.write_i32::<LittleEndian>(length as i32)?; // I4 LENGTH OF VALUE
w.write_i32::<LittleEndian>(*offset as i32)?; // I4 position
*offset += length as i32;
Ok(())
}
| 32.055944
| 95
| 0.558028
|
38c2b51564f758c6189b5716dcfcb217817b9ce4
| 1,172
|
php
|
PHP
|
views/supermarkets/assign.php
|
kradarc/supermercado
|
550a82c8d11dcfc105f39aaca4ee372dfe641982
|
[
"BSD-3-Clause"
] | null | null | null |
views/supermarkets/assign.php
|
kradarc/supermercado
|
550a82c8d11dcfc105f39aaca4ee372dfe641982
|
[
"BSD-3-Clause"
] | null | null | null |
views/supermarkets/assign.php
|
kradarc/supermercado
|
550a82c8d11dcfc105f39aaca4ee372dfe641982
|
[
"BSD-3-Clause"
] | null | null | null |
<?php
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use yii\widgets\ActiveForm;
$this->title = Yii::t('app', 'Asignación de productos');
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Supermarkets'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="products-index">
<h3>Asigna productos al supermercado <?= $supermarket->name; ?></h3>
<div class="container">
<?php $form = ActiveForm::begin(); ?>
<input type="hidden" name="supermarket_id" value="<?= $supermarket->id; ?>">
<div class="form-group">
<select id='pre-selected-options' multiple='multiple' name="products[]">
<?php foreach ($productos as $key => $value) { ?>
<?php if(ArrayHelper::keyExists($key, $selected_products, false)){ ?>
<option value='<?= $key; ?>' selected><?= $value; ?></option>
<?php }else{ ?>
<option value='<?= $key; ?>'><?= $value; ?></option>
<?php } ?>
<?php } ?>
</select>
</div>
<div class="form-group">
<button class="btn btn-primary" type="submit">Guardar cambios</button>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
| 27.904762
| 96
| 0.573379
|
ed471384350b4dd124f767e1da825539ff695f20
| 3,126
|
h
|
C
|
google/cloud/internal/rest_options.h
|
GoogleCloudPlatform/google-cloud-cpp
|
c4fc35de9e15f95b1dbf585f1c96de5dba609e2b
|
[
"Apache-2.0"
] | 80
|
2017-11-24T00:19:45.000Z
|
2019-01-25T10:24:33.000Z
|
google/cloud/internal/rest_options.h
|
GoogleCloudPlatform/google-cloud-cpp
|
c4fc35de9e15f95b1dbf585f1c96de5dba609e2b
|
[
"Apache-2.0"
] | 1,579
|
2017-11-24T01:01:21.000Z
|
2019-01-28T23:41:21.000Z
|
google/cloud/internal/rest_options.h
|
GoogleCloudPlatform/google-cloud-cpp
|
c4fc35de9e15f95b1dbf585f1c96de5dba609e2b
|
[
"Apache-2.0"
] | 51
|
2017-11-24T00:56:11.000Z
|
2019-01-18T20:35:02.000Z
|
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_INTERNAL_REST_OPTIONS_H
#define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_INTERNAL_REST_OPTIONS_H
#include "google/cloud/options.h"
#include "google/cloud/version.h"
#include <chrono>
#include <memory>
#include <string>
namespace google {
namespace cloud {
namespace rest_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
/**
* Configure the UserIp query parameter.
*
* This can be used to separate quota usage by source IP address.
*
* @deprecated prefer using `google::cloud::QuotaUser`.
*/
struct UserIpOption {
using Type = std::string;
};
/**
* Sets the transfer stall timeout.
*
* If a transfer (upload, download, or request) *stalls*, i.e., no bytes are
* sent or received for a significant period, it may be better to restart the
* transfer as this may indicate a network glitch. For downloads the
* google::cloud::storage::DownloadStallTimeoutOption takes precedence.
*
* For large requests (e.g. downloads in the GiB to TiB range) this is a better
* configuration parameter than a simple timeout, as the transfers will take
* minutes or hours to complete. Relying on a timeout value for them would not
* work, as the timeout would be too large to be useful. For small requests,
* this is as effective as a timeout parameter, but maybe unfamiliar and thus
* harder to reason about.
*/
struct TransferStallTimeoutOption {
using Type = std::chrono::seconds;
};
/**
* Sets the download stall timeout.
*
* If a download *stalls*, i.e., no bytes are received for a significant period,
* it may be better to restart the download as this may indicate a network
* glitch.
*
* For large requests (e.g. downloads in the GiB to TiB range) this is a better
* configuration parameter than a simple timeout, as the transfers will take
* minutes or hours to complete. Relying on a timeout value for them would not
* work, as the timeout would be too large to be useful. For small requests,
* this is as effective as a timeout parameter, but maybe unfamiliar and thus
* harder to reason about.
*/
struct DownloadStallTimeoutOption {
using Type = std::chrono::seconds;
};
/// The complete list of options accepted by `CurlRestClient`
using RestOptionList =
::google::cloud::OptionList<UserIpOption, TransferStallTimeoutOption,
DownloadStallTimeoutOption>;
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace rest_internal
} // namespace cloud
} // namespace google
#endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_INTERNAL_REST_OPTIONS_H
| 35.522727
| 80
| 0.75048
|
97e9ac0dc4b252ee516a40ec4f9c5bc4ae2fa083
| 497
|
tsx
|
TypeScript
|
src/modules/date.tsx
|
pedrocelso/task-ui
|
5de6fa71d2bca8655078fecadb2d1dff12a8a1a5
|
[
"Apache-2.0"
] | 1
|
2020-07-27T19:28:53.000Z
|
2020-07-27T19:28:53.000Z
|
src/modules/date.tsx
|
pedrocelso/task-ui
|
5de6fa71d2bca8655078fecadb2d1dff12a8a1a5
|
[
"Apache-2.0"
] | 47
|
2019-04-11T09:48:54.000Z
|
2022-02-26T10:22:11.000Z
|
src/modules/date.tsx
|
pedrocelso/task-ui
|
5de6fa71d2bca8655078fecadb2d1dff12a8a1a5
|
[
"Apache-2.0"
] | null | null | null |
import moment from 'moment-timezone'
import { curry, pathOr, sort } from 'ramda';
export function formatTime(time: number): string {
const date = new Date(time)
return time ? moment(date, moment.tz.guess()).format("YYYY/MM/DD, h:mm:ss a") : `n/a`
}
function sortByDateFunc<T>(fieldName: string, l: T[]): T[] {
const sortBy = (a: T, b: T) => pathOr(0, [fieldName], a) - pathOr(0, [fieldName], b)
return sort(sortBy, l)
}
//@ts-ignore
export const sortByDate = curry<T, T>(sortByDateFunc)
| 33.133333
| 87
| 0.668008
|
43a3e74e0c5484eaf54b551f4ff3da0e3cdbf1ae
| 155
|
ts
|
TypeScript
|
src/modules/vpc/dto/requests/list-vpc-request-dto.ts
|
cloudforge/node-digitalocean
|
7dff0aaa31cb5e5c2760c320f9f22d1535a4ae3e
|
[
"MIT"
] | null | null | null |
src/modules/vpc/dto/requests/list-vpc-request-dto.ts
|
cloudforge/node-digitalocean
|
7dff0aaa31cb5e5c2760c320f9f22d1535a4ae3e
|
[
"MIT"
] | null | null | null |
src/modules/vpc/dto/requests/list-vpc-request-dto.ts
|
cloudforge/node-digitalocean
|
7dff0aaa31cb5e5c2760c320f9f22d1535a4ae3e
|
[
"MIT"
] | null | null | null |
import { CommonRequestOptions } from "../../../dto/common/common-request-options";
export interface ListVPCRequestOptions extends CommonRequestOptions {}
| 38.75
| 82
| 0.787097
|
4911cda038fa8cd237f540c3aaaa30044c5dbdd8
| 887
|
swift
|
Swift
|
ios/Classes/CodeScannerViewFactory.swift
|
ycherniavskyi/code_scanner
|
fc55341aaf05a9c4ff15d87820f46b57f31912fe
|
[
"MIT"
] | 3
|
2021-05-17T09:23:15.000Z
|
2022-02-15T06:37:52.000Z
|
ios/Classes/CodeScannerViewFactory.swift
|
ycherniavskyi/code_scanner
|
fc55341aaf05a9c4ff15d87820f46b57f31912fe
|
[
"MIT"
] | 2
|
2021-12-16T21:33:13.000Z
|
2021-12-16T22:31:59.000Z
|
ios/Classes/CodeScannerViewFactory.swift
|
ycherniavskyi/code_scanner
|
fc55341aaf05a9c4ff15d87820f46b57f31912fe
|
[
"MIT"
] | 3
|
2021-08-09T18:59:23.000Z
|
2021-12-16T23:51:14.000Z
|
//
// CodeScannerViewFactory.swift
// code_scanner
//
// Created by honda on 2021/04/19.
//
import Foundation
import Flutter
class CodeScannerViewFactory: NSObject, FlutterPlatformViewFactory {
// private var messenger: FlutterBinaryMessenger
var registrar: FlutterPluginRegistrar?
public init(withRegistrar registrar: FlutterPluginRegistrar){
super.init()
self.registrar = registrar
}
func create(withFrame frame: CGRect, viewIdentifier viewId: Int64, arguments args: Any?) -> FlutterPlatformView {
// var dict = args as! Dictionary<String, Double>
return CodeScannerView(withFrame: frame, viewIdentifier: viewId, withRegistrar: registrar!)
}
func createArgsCodec() -> FlutterMessageCodec & NSObjectProtocol {
return FlutterStandardMessageCodec(readerWriter: FlutterStandardReaderWriter())
}
}
| 30.586207
| 117
| 0.722661
|
0d470619ce71c44044b110f1d12d7738ec6e729d
| 1,308
|
ps1
|
PowerShell
|
WindowsFirewallcommands/Get-ExecutablebyPort.ps1
|
murrahjm/misc-scripts
|
5e7a320b973ca173e67d53931ac7c43966051088
|
[
"MIT"
] | 3
|
2018-04-30T06:48:58.000Z
|
2019-06-29T01:34:59.000Z
|
WindowsFirewallcommands/Get-ExecutablebyPort.ps1
|
murrahjm/misc-scripts
|
5e7a320b973ca173e67d53931ac7c43966051088
|
[
"MIT"
] | null | null | null |
WindowsFirewallcommands/Get-ExecutablebyPort.ps1
|
murrahjm/misc-scripts
|
5e7a320b973ca173e67d53931ac7c43966051088
|
[
"MIT"
] | null | null | null |
Function Get-ExecutablebyPort {
[cmdletbinding()]
Param (
[String]$Port,
[String]$Computername,
[PSCredential]$Credential
)
If ($Credential){
$Session = New-PSSession -ComputerName $Computername -Credential $Credential
} else {
$Session = New-PSSession -ComputerName $Computername
}
If ($Session){
$Netstatoutput = invoke-command -Session $Session -ScriptBlock {netstat -ano}
write-verbose "netstat retrieved, looking for port $port listening entry"
$NetstatString = $netstatoutput | ?{$_ -like "*$Port*LISTENING*"}
If ($NetstatString){
write-verbose "netstat entry found: $netstatstring"
$processID = $netstatstring.split(' ')[-1]
write-verbose "associated PID: $processID"
$Path = invoke-command -session $Session -ScriptBlock {get-process -pid $args[0] | select -ExpandProperty Path} -ArgumentList $ProcessID
write-verbose "Path for PID $processID`: $path"
if ($Path){return $Path}
} else {
Write-Warning "Port $port not found in netstat output. Process may be stop"
}
Remove-PSSession $Session
} else {
write-error "unable to connect remotely to $computername"
return
}
}
| 39.636364
| 148
| 0.617737
|
4558826d3e00bec833420e830ff88a9f92ed2c4d
| 1,154
|
py
|
Python
|
src/lorempicsum/cli.py
|
Expan75/py-lorem-picsum
|
2940fd10e8c277fad21e2901be5ece9315e4ecf4
|
[
"MIT"
] | 1
|
2021-07-29T13:32:31.000Z
|
2021-07-29T13:32:31.000Z
|
src/lorempicsum/cli.py
|
Expan75/py-lorem-picsum
|
2940fd10e8c277fad21e2901be5ece9315e4ecf4
|
[
"MIT"
] | 1
|
2022-01-19T20:45:14.000Z
|
2022-01-19T20:45:14.000Z
|
src/lorempicsum/cli.py
|
Expan75/py-lorem-picsum
|
2940fd10e8c277fad21e2901be5ece9315e4ecf4
|
[
"MIT"
] | null | null | null |
import argparse
parser = argparse.ArgumentParser(description='CLI tool for complimenting image classification')
parser.add_argument('-f', '--folder', default='images', help='Specify the path of a directory in which to store photos')
parser.add_argument('-n', '--number', help='Specify how many images you want to download', type=int)
parser.add_argument('-s', '--seed', type=int,
help='Used to ensure the same images are downloaded. Useful for reproduction of experiements and datasets')
parser.add_argument('-z', '--size', type=int,
help='The size of the downloaded image. Right now only square images are supported.')
args = parser.parse_args()
def main():
from .engine import verify_valid_directory, download_images
if not args.number or not args.seed:
raise RuntimeError('Please provide both an integer for the number of images to download, as well as an integer seed to ensure replication! See --help for more information on arguments.')
verify_valid_directory(args.folder)
download_images(master_seed=args.seed, n_images=args.number, image_directory=args.folder, size=args.size)
if __name__ == '__main__':
main()
| 57.7
| 194
| 0.754766
|
38b2e3cf039e7f9879d1cc6d0518e05b1c9afb7f
| 4,089
|
php
|
PHP
|
html/dev/tests/integration/testsuite/Magento/Test/Integrity/Modular/LayoutFilesTest.php
|
tarikgwa/test
|
4b2f33b14d59f60609e432de28051fb5a7092431
|
[
"Apache-2.0"
] | null | null | null |
html/dev/tests/integration/testsuite/Magento/Test/Integrity/Modular/LayoutFilesTest.php
|
tarikgwa/test
|
4b2f33b14d59f60609e432de28051fb5a7092431
|
[
"Apache-2.0"
] | null | null | null |
html/dev/tests/integration/testsuite/Magento/Test/Integrity/Modular/LayoutFilesTest.php
|
tarikgwa/test
|
4b2f33b14d59f60609e432de28051fb5a7092431
|
[
"Apache-2.0"
] | 2
|
2020-11-04T08:26:46.000Z
|
2020-11-06T07:38:14.000Z
|
<?php
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Test\Integrity\Modular;
class LayoutFilesTest extends \PHPUnit_Framework_TestCase
{
/**
* @var \Magento\Framework\View\Layout\Argument\Parser
*/
protected $_argParser;
/**
* @var \Magento\Framework\Data\Argument\InterpreterInterface
*/
protected $_argInterpreter;
protected function setUp()
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->_argParser = $objectManager->get('Magento\Framework\View\Layout\Argument\Parser');
$this->_argInterpreter = $objectManager->get('layoutArgumentGeneratorInterpreter');
}
/**
* @param string $area
* @param string $layoutFile
* @dataProvider layoutArgumentsDataProvider
*/
public function testLayoutArguments($area, $layoutFile)
{
\Magento\TestFramework\Helper\Bootstrap::getInstance()->loadArea($area);
$dom = new \DOMDocument();
$dom->load($layoutFile);
$xpath = new \DOMXPath($dom);
$argumentNodes = $xpath->query('/layout//arguments/argument | /layout//action/argument');
/** @var \DOMNode $argumentNode */
foreach ($argumentNodes as $argumentNode) {
try {
$argumentData = $this->_argParser->parse($argumentNode);
if ($this->isSkippedArgument($argumentData)) {
continue;
}
$this->_argInterpreter->evaluate($argumentData);
} catch (\Exception $e) {
$this->fail($e->getMessage());
}
}
}
/**
* @return array
*/
public function layoutArgumentsDataProvider()
{
$areas = ['adminhtml', 'frontend', 'email'];
$data = [];
foreach ($areas as $area) {
$layoutFiles = \Magento\Framework\App\Utility\Files::init()->getLayoutFiles(['area' => $area], false);
foreach ($layoutFiles as $layoutFile) {
$data[substr($layoutFile, strlen(BP))] = [$area, $layoutFile];
}
}
return $data;
}
/**
* Whether an argument should be skipped, because it cannot be evaluated in the testing environment
*
* @param array $argumentData
* @return bool
*/
protected function isSkippedArgument(array $argumentData)
{
// Do not take into account argument name and parameters
unset($argumentData['name']);
unset($argumentData['param']);
$isUpdater = isset($argumentData['updater']);
unset($argumentData['updater']);
// Arguments, evaluation of which causes a run-time error, because of unsafe assumptions to the environment
$typeAttr = \Magento\Framework\View\Model\Layout\Merge::TYPE_ATTRIBUTE;
$prCollection = 'Magento\GroupedProduct\Model\ResourceModel\Product\Type\Grouped\AssociatedProductsCollection';
$ignoredArguments = [
[
$typeAttr => 'object',
'value' => $prCollection,
],
[$typeAttr => 'object', 'value' => 'Magento\Solr\Model\ResourceModel\Search\Grid\Collection'],
[$typeAttr => 'object', 'value' => 'Magento\Wishlist\Model\ResourceModel\Item\Collection\Grid'],
[
$typeAttr => 'object',
'value' => 'Magento\CustomerSegment\Model\ResourceModel\Segment\Report\Detail\Collection'
],
[$typeAttr => 'options', 'model' => 'Magento\Solr\Model\Adminhtml\Search\Grid\Options'],
[$typeAttr => 'options', 'model' => 'Magento\Logging\Model\ResourceModel\Grid\ActionsGroup'],
[$typeAttr => 'options', 'model' => 'Magento\Logging\Model\ResourceModel\Grid\Actions'],
];
$isIgnoredArgument = in_array($argumentData, $ignoredArguments, true);
unset($argumentData[$typeAttr]);
$hasValue = !empty($argumentData);
return $isIgnoredArgument || $isUpdater && !$hasValue;
}
}
| 37.172727
| 119
| 0.601125
|
dd653b297df8c367d36f978097c723788abc21a2
| 13,689
|
java
|
Java
|
hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyCommitter.java
|
wulfnoth/hadoop-main
|
89ef5cb780137645e35d99c62d33586a2c1c711b
|
[
"Apache-2.0"
] | 1
|
2021-09-16T14:01:30.000Z
|
2021-09-16T14:01:30.000Z
|
hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyCommitter.java
|
wulfnoth/hadoop-main
|
89ef5cb780137645e35d99c62d33586a2c1c711b
|
[
"Apache-2.0"
] | 9
|
2019-11-13T09:26:51.000Z
|
2022-01-27T16:19:19.000Z
|
hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyCommitter.java
|
wulfnoth/hadoop-main
|
89ef5cb780137645e35d99c62d33586a2c1c711b
|
[
"Apache-2.0"
] | 3
|
2019-03-19T14:33:34.000Z
|
2021-11-24T10:07:11.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.
*/
package org.apache.hadoop.tools.mapred;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.JobStatus;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter;
import org.apache.hadoop.tools.CopyListing;
import org.apache.hadoop.tools.CopyListingFileStatus;
import org.apache.hadoop.tools.DistCpConstants;
import org.apache.hadoop.tools.DistCpOptions;
import org.apache.hadoop.tools.DistCpOptions.FileAttribute;
import org.apache.hadoop.tools.GlobbedCopyListing;
import org.apache.hadoop.tools.util.DistCpUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
/**
* The CopyCommitter class is DistCp's OutputCommitter implementation. It is
* responsible for handling the completion/cleanup of the DistCp run.
* Specifically, it does the following:
* 1. Cleanup of the meta-folder (where DistCp maintains its file-list, etc.)
* 2. Preservation of user/group/replication-factor on any directories that
* have been copied. (Files are taken care of in their map-tasks.)
* 3. Atomic-move of data from the temporary work-folder to the final path
* (if atomic-commit was opted for).
* 4. Deletion of files from the target that are missing at source (if opted for).
* 5. Cleanup of any partially copied files, from previous, failed attempts.
*/
public class CopyCommitter extends FileOutputCommitter {
private static final Log LOG = LogFactory.getLog(CopyCommitter.class);
private final TaskAttemptContext taskAttemptContext;
private boolean syncFolder = false;
private boolean overwrite = false;
private boolean targetPathExists = true;
/**
* Create a output committer
*
* @param outputPath the job's output path
* @param context the task's context
* @throws IOException - Exception if any
*/
public CopyCommitter(Path outputPath, TaskAttemptContext context) throws IOException {
super(outputPath, context);
this.taskAttemptContext = context;
}
/** {@inheritDoc} */
@Override
public void commitJob(JobContext jobContext) throws IOException {
Configuration conf = jobContext.getConfiguration();
syncFolder = conf.getBoolean(DistCpConstants.CONF_LABEL_SYNC_FOLDERS, false);
overwrite = conf.getBoolean(DistCpConstants.CONF_LABEL_OVERWRITE, false);
targetPathExists = conf.getBoolean(DistCpConstants.CONF_LABEL_TARGET_PATH_EXISTS, true);
super.commitJob(jobContext);
cleanupTempFiles(jobContext);
String attributes = conf.get(DistCpConstants.CONF_LABEL_PRESERVE_STATUS);
final boolean preserveRawXattrs =
conf.getBoolean(DistCpConstants.CONF_LABEL_PRESERVE_RAWXATTRS, false);
if ((attributes != null && !attributes.isEmpty()) || preserveRawXattrs) {
preserveFileAttributesForDirectories(conf);
}
try {
if (conf.getBoolean(DistCpConstants.CONF_LABEL_DELETE_MISSING, false)) {
deleteMissing(conf);
} else if (conf.getBoolean(DistCpConstants.CONF_LABEL_ATOMIC_COPY, false)) {
commitData(conf);
}
taskAttemptContext.setStatus("Commit Successful");
}
finally {
cleanup(conf);
}
}
/** {@inheritDoc} */
@Override
public void abortJob(JobContext jobContext,
JobStatus.State state) throws IOException {
try {
super.abortJob(jobContext, state);
} finally {
cleanupTempFiles(jobContext);
cleanup(jobContext.getConfiguration());
}
}
private void cleanupTempFiles(JobContext context) {
try {
Configuration conf = context.getConfiguration();
Path targetWorkPath = new Path(conf.get(DistCpConstants.CONF_LABEL_TARGET_WORK_PATH));
FileSystem targetFS = targetWorkPath.getFileSystem(conf);
String jobId = context.getJobID().toString();
deleteAttemptTempFiles(targetWorkPath, targetFS, jobId);
deleteAttemptTempFiles(targetWorkPath.getParent(), targetFS, jobId);
} catch (Throwable t) {
LOG.warn("Unable to cleanup temp files", t);
}
}
private void deleteAttemptTempFiles(Path targetWorkPath,
FileSystem targetFS,
String jobId) throws IOException {
if (targetWorkPath == null) {
return;
}
FileStatus[] tempFiles = targetFS.globStatus(
new Path(targetWorkPath, ".distcp.tmp." + jobId.replaceAll("job","attempt") + "*"));
if (tempFiles != null && tempFiles.length > 0) {
for (FileStatus file : tempFiles) {
LOG.info("Cleaning up " + file.getPath());
targetFS.delete(file.getPath(), false);
}
}
}
/**
* Cleanup meta folder and other temporary files
*
* @param conf - Job Configuration
*/
private void cleanup(Configuration conf) {
Path metaFolder = new Path(conf.get(DistCpConstants.CONF_LABEL_META_FOLDER));
try {
FileSystem fs = metaFolder.getFileSystem(conf);
LOG.info("Cleaning up temporary work folder: " + metaFolder);
fs.delete(metaFolder, true);
} catch (IOException ignore) {
LOG.error("Exception encountered ", ignore);
}
}
// This method changes the target-directories' file-attributes (owner,
// user/group permissions, etc.) based on the corresponding source directories.
private void preserveFileAttributesForDirectories(Configuration conf) throws IOException {
String attrSymbols = conf.get(DistCpConstants.CONF_LABEL_PRESERVE_STATUS);
final boolean syncOrOverwrite = syncFolder || overwrite;
LOG.info("About to preserve attributes: " + attrSymbols);
EnumSet<FileAttribute> attributes = DistCpUtils.unpackAttributes(attrSymbols);
final boolean preserveRawXattrs =
conf.getBoolean(DistCpConstants.CONF_LABEL_PRESERVE_RAWXATTRS, false);
Path sourceListing = new Path(conf.get(DistCpConstants.CONF_LABEL_LISTING_FILE_PATH));
FileSystem clusterFS = sourceListing.getFileSystem(conf);
SequenceFile.Reader sourceReader = new SequenceFile.Reader(conf,
SequenceFile.Reader.file(sourceListing));
long totalLen = clusterFS.getFileStatus(sourceListing).getLen();
Path targetRoot = new Path(conf.get(DistCpConstants.CONF_LABEL_TARGET_WORK_PATH));
long preservedEntries = 0;
try {
CopyListingFileStatus srcFileStatus = new CopyListingFileStatus();
Text srcRelPath = new Text();
// Iterate over every source path that was copied.
while (sourceReader.next(srcRelPath, srcFileStatus)) {
// File-attributes for files are set at the time of copy,
// in the map-task.
if (! srcFileStatus.isDirectory()) continue;
Path targetFile = new Path(targetRoot.toString() + "/" + srcRelPath);
//
// Skip the root folder when syncOrOverwrite is true.
//
if (targetRoot.equals(targetFile) && syncOrOverwrite) continue;
FileSystem targetFS = targetFile.getFileSystem(conf);
DistCpUtils.preserve(targetFS, targetFile, srcFileStatus, attributes,
preserveRawXattrs);
taskAttemptContext.progress();
taskAttemptContext.setStatus("Preserving status on directory entries. [" +
sourceReader.getPosition() * 100 / totalLen + "%]");
}
} finally {
IOUtils.closeStream(sourceReader);
}
LOG.info("Preserved status on " + preservedEntries + " dir entries on target");
}
// This method deletes "extra" files from the target, if they're not
// available at the source.
private void deleteMissing(Configuration conf) throws IOException {
LOG.info("-delete option is enabled. About to remove entries from " +
"target that are missing in source");
// Sort the source-file listing alphabetically.
Path sourceListing = new Path(conf.get(DistCpConstants.CONF_LABEL_LISTING_FILE_PATH));
FileSystem clusterFS = sourceListing.getFileSystem(conf);
Path sortedSourceListing = DistCpUtils.sortListing(clusterFS, conf, sourceListing);
// Similarly, create the listing of target-files. Sort alphabetically.
Path targetListing = new Path(sourceListing.getParent(), "targetListing.seq");
CopyListing target = new GlobbedCopyListing(new Configuration(conf), null);
List<Path> targets = new ArrayList<Path>(1);
Path targetFinalPath = new Path(conf.get(DistCpConstants.CONF_LABEL_TARGET_FINAL_PATH));
targets.add(targetFinalPath);
Path resultNonePath = Path.getPathWithoutSchemeAndAuthority(targetFinalPath)
.toString().startsWith(DistCpConstants.HDFS_RESERVED_RAW_DIRECTORY_NAME)
? DistCpConstants.RAW_NONE_PATH : DistCpConstants.NONE_PATH;
DistCpOptions options = new DistCpOptions(targets, resultNonePath);
//
// Set up options to be the same from the CopyListing.buildListing's perspective,
// so to collect similar listings as when doing the copy
//
options.setOverwrite(overwrite);
options.setSyncFolder(syncFolder);
options.setTargetPathExists(targetPathExists);
target.buildListing(targetListing, options);
Path sortedTargetListing = DistCpUtils.sortListing(clusterFS, conf, targetListing);
long totalLen = clusterFS.getFileStatus(sortedTargetListing).getLen();
SequenceFile.Reader sourceReader = new SequenceFile.Reader(conf,
SequenceFile.Reader.file(sortedSourceListing));
SequenceFile.Reader targetReader = new SequenceFile.Reader(conf,
SequenceFile.Reader.file(sortedTargetListing));
// Walk both source and target file listings.
// Delete all from target that doesn't also exist on source.
long deletedEntries = 0;
try {
CopyListingFileStatus srcFileStatus = new CopyListingFileStatus();
Text srcRelPath = new Text();
CopyListingFileStatus trgtFileStatus = new CopyListingFileStatus();
Text trgtRelPath = new Text();
FileSystem targetFS = targetFinalPath.getFileSystem(conf);
boolean srcAvailable = sourceReader.next(srcRelPath, srcFileStatus);
while (targetReader.next(trgtRelPath, trgtFileStatus)) {
// Skip sources that don't exist on target.
while (srcAvailable && trgtRelPath.compareTo(srcRelPath) > 0) {
srcAvailable = sourceReader.next(srcRelPath, srcFileStatus);
}
if (srcAvailable && trgtRelPath.equals(srcRelPath)) continue;
// Target doesn't exist at source. Delete.
boolean result = (!targetFS.exists(trgtFileStatus.getPath()) ||
targetFS.delete(trgtFileStatus.getPath(), true));
if (result) {
LOG.info("Deleted " + trgtFileStatus.getPath() + " - Missing at source");
deletedEntries++;
} else {
throw new IOException("Unable to delete " + trgtFileStatus.getPath());
}
taskAttemptContext.progress();
taskAttemptContext.setStatus("Deleting missing files from target. [" +
targetReader.getPosition() * 100 / totalLen + "%]");
}
} finally {
IOUtils.closeStream(sourceReader);
IOUtils.closeStream(targetReader);
}
LOG.info("Deleted " + deletedEntries + " from target: " + targets.get(0));
}
private void commitData(Configuration conf) throws IOException {
Path workDir = new Path(conf.get(DistCpConstants.CONF_LABEL_TARGET_WORK_PATH));
Path finalDir = new Path(conf.get(DistCpConstants.CONF_LABEL_TARGET_FINAL_PATH));
FileSystem targetFS = workDir.getFileSystem(conf);
LOG.info("Atomic commit enabled. Moving " + workDir + " to " + finalDir);
if (targetFS.exists(finalDir) && targetFS.exists(workDir)) {
LOG.error("Pre-existing final-path found at: " + finalDir);
throw new IOException("Target-path can't be committed to because it " +
"exists at " + finalDir + ". Copied data is in temp-dir: " + workDir + ". ");
}
boolean result = targetFS.rename(workDir, finalDir);
if (!result) {
LOG.warn("Rename failed. Perhaps data already moved. Verifying...");
result = targetFS.exists(finalDir) && !targetFS.exists(workDir);
}
if (result) {
LOG.info("Data committed successfully to " + finalDir);
taskAttemptContext.setStatus("Data committed successfully to " + finalDir);
} else {
LOG.error("Unable to commit data to " + finalDir);
throw new IOException("Atomic commit failed. Temporary data in " + workDir +
", Unable to move to " + finalDir);
}
}
}
| 41.607903
| 92
| 0.70816
|
ec489a56c711b003adec66a143c6efffac96f299
| 1,193
|
lua
|
Lua
|
WheresMyHome/Locales/PL.lua
|
Syvokobylenko/RunesofMagic_Addon_Pack
|
3edeacf3823c62b176d202d76fd87658f5ff8295
|
[
"Unlicense"
] | null | null | null |
WheresMyHome/Locales/PL.lua
|
Syvokobylenko/RunesofMagic_Addon_Pack
|
3edeacf3823c62b176d202d76fd87658f5ff8295
|
[
"Unlicense"
] | null | null | null |
WheresMyHome/Locales/PL.lua
|
Syvokobylenko/RunesofMagic_Addon_Pack
|
3edeacf3823c62b176d202d76fd87658f5ff8295
|
[
"Unlicense"
] | null | null | null |
local locales = {}
locales["ADDON_DESCRIPTION"] = "Wtyczka do ZZInfoBar pokazująca gdzie masz zapisany punkt przywołania."
locales["ADDON_LOADED"] = "Addon załadowany"
locales["ALT_LEFT_MOUSEBUTTON"] = "Alt + LPM"
locales["ALT_RIGHT_MOUSEBUTTON"] = "Alt + PPM"
locales["BUTTON"] = "Przycisk ZZIB"
locales["CTRL_LEFT_MOUSEBUTTON"] = "Ctrl + LPM"
locales["CTRL_RIGHT_MOUSEBUTTON"] = "Ctrl + PPM"
locales["LEFT_MOUSEBUTTON"] = "LPM"
--Translation missing
-- locales["REVERSECODEX"] = "Reverse black codex order"
locales["RIGHT_MOUSEBUTTON"] = "PPM"
locales["SHIFT_LEFT_MOUSEBUTTON"] = "Shift + LPM"
locales["SHIFT_RIGHT_MOUSEBUTTON"] = "Shift + PPM"
locales["TRANSPORTACTION1"] = "otwórz Księgę Transportu RoM"
locales["TRANSPORTACTION2"] = "otwórz rozwijaną listę transportów"
locales["TRANSPORTACTION3"] = "otwórz okno transportu WheresMyHome"
locales["TRANSPORTBOOK_ADD_ENTRY"] = "Zaznacz Punkt Transportu"
locales["TRANSPORTBOOK_FULL"] = "Twoja Księga Transportu jest pełna. Proszę najpierw usunąć niepotrzebne pozycje."
locales["TRANSPORTBOOKSORT"] = "Posortuj Księgę Transportu alfabetycznie"
locales["TRANSPORTMODE"] = "akcja LPM"
locales["WRITTEN_BY"] = "Napisane przez"
return locales
| 47.72
| 114
| 0.767812
|
da8c4f0dd6e7085613a251770414315f3ab76375
| 5,272
|
php
|
PHP
|
src/AppBundle/Entity/Question.php
|
tonknaf/dictionary
|
3dd768384a62d4eec66cc6ed793347d72ee2b7a2
|
[
"MIT"
] | 2
|
2019-12-23T02:25:44.000Z
|
2020-05-11T18:36:10.000Z
|
src/AppBundle/Entity/Question.php
|
tonknaf/dictionary
|
3dd768384a62d4eec66cc6ed793347d72ee2b7a2
|
[
"MIT"
] | 1
|
2017-11-17T19:53:49.000Z
|
2017-11-17T19:53:49.000Z
|
src/AppBundle/Entity/Question.php
|
sentiens/dictionary
|
3dd768384a62d4eec66cc6ed793347d72ee2b7a2
|
[
"MIT"
] | null | null | null |
<?php
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use AppBundle\Entity\Exception as DomainExceptions;
/**
* Question
*
* @ORM\Table(name="question")
* @ORM\Entity()
*/
class Question {
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var Quiz
*
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\Quiz", inversedBy="questions")
*/
private $quiz;
/**
* @var Word
*
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\Word", cascade={"persist"})
*/
private $question;
/**
* @var Word
*
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\Word", cascade={"persist"})
*/
private $rightAnswer;
/**
* @var Word
*
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\Word", cascade={"persist"})
*/
private $answer1;
/**
* @var Word
*
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\Word", cascade={"persist"})
*/
private $answer2;
/**
* @var Word
*
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\Word", cascade={"persist"})
*/
private $answer3;
/**
* @var Word
*
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\Word", cascade={"persist"})
*/
private $answer4;
/**
* @var ArrayCollection
*
* @ORM\ManyToMany(targetEntity="AppBundle\Entity\Word", cascade={"persist", "remove"})
* @ORM\JoinTable(
* name="failed_answers",
* joinColumns={@ORM\JoinColumn(name="question_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="word_id", referencedColumnName="id")}
* )
*/
private $failedAnswers;
public function __construct() {
$this->wrongAnswers = new ArrayCollection();
$this->failedAnswers = new ArrayCollection();
}
/**
* @param Quiz $quiz
* @param Word $question
* @param Word $rightAnswer
* @param array $wrongAnswers
*
* @return Question
* @throws DomainExceptions\LogicException
*/
public static function ask(Quiz $quiz, Word $question, Word $rightAnswer, array $wrongAnswers) : Question {
if ($question->getLang() === $rightAnswer->getLang()) {
throw new DomainExceptions\LogicException('Question and answer are of the same language.');
}
if (count($wrongAnswers) !== 3) {
throw new DomainExceptions\LogicException('There are should be 3 wrong answers.');
}
foreach ($wrongAnswers as $wrongAnswer) {
if ($rightAnswer->getLang() !== $wrongAnswer->getLang()) {
throw new DomainExceptions\LogicException('Wrong answer should be of the same language as right answer.');
}
if (!$wrongAnswer instanceof Word) {
throw new DomainExceptions\LogicException('Wrong answers should be instances of Word class.');
}
}
$q = new Question();
$q->quiz = $quiz;
$q->question = $question;
$q->rightAnswer = $rightAnswer;
$answers = array_merge($wrongAnswers, [$rightAnswer]);
shuffle($answers);
list($q->answer1, $q->answer2, $q->answer3, $q->answer4) = $answers;
return $q;
}
/**
* Get id
* @codeCoverageIgnore
* @return int
*/
public function getId() {
return $this->id;
}
/**
* @return Word
*/
public function getQuestion() : Word {
return $this->question;
}
/**
* @return Word
*/
public function getRightAnswer() : Word {
return $this->rightAnswer;
}
/**
* @return ArrayCollection
*/
public function getAnswers() {
return new ArrayCollection(array_map(function ($i) {
$prop = 'answer' . $i;
return $this->$prop;
}, [1, 2, 3, 4]));
}
public function isFailedAnswer(Word $word) : bool {
return $this->failedAnswers->contains($word);
}
/**
* @param Word $word
*
* @throws DomainExceptions\AnswerDoesNotBelongToTheQuestionException
* @throws DomainExceptions\RepeatingAnswerException
* @throws DomainExceptions\WrongAnswerException
*/
public function answer(Word $word) {
if ($this->hasAnswer($word)) {
if ($this->rightAnswer === $word) {
return;
} else {
if ($this->failedAnswers->contains($word)) {
throw new DomainExceptions\RepeatingAnswerException;
} else {
$this->failedAnswers->add($word);
throw new DomainExceptions\WrongAnswerException;
}
}
} else {
throw new DomainExceptions\AnswerDoesNotBelongToTheQuestionException;
}
}
private function hasAnswer(Word $answer) : bool {
foreach ([1, 2, 3, 4] as $i) {
$prop = 'answer' . $i;
if ($this->$prop === $answer) {
return true;
}
}
return false;
}
}
| 24.183486
| 122
| 0.556904
|
190d239661f2c353f48e79d0a11ea08b4557ff88
| 359
|
kt
|
Kotlin
|
tmp/arrays/youTrackTests/3716.kt
|
vitekkor/bbfgradle
|
b4ec701a7a3b7523db97631fa0ed6484149ca9cd
|
[
"Apache-2.0"
] | 1
|
2021-04-06T16:59:24.000Z
|
2021-04-06T16:59:24.000Z
|
tmp/arrays/youTrackTests/3716.kt
|
vitekkor/bbfgradle
|
b4ec701a7a3b7523db97631fa0ed6484149ca9cd
|
[
"Apache-2.0"
] | null | null | null |
tmp/arrays/youTrackTests/3716.kt
|
vitekkor/bbfgradle
|
b4ec701a7a3b7523db97631fa0ed6484149ca9cd
|
[
"Apache-2.0"
] | 11
|
2020-03-23T08:28:36.000Z
|
2022-03-22T07:04:42.000Z
|
// Original bug: KT-34696
package packageName
import packageName.MyEnum.*
enum class MyEnum {
A, B, C, D, E
}
fun main() {
println(A)
println(A)
println(B)
println(C)
// here: MyEnum shouldn't be highlighted as 'Redundant qualified name'
MyEnum.valueOf("A")
for (value in MyEnum.values()) {
println(value)
}
}
| 15.608696
| 74
| 0.615599
|
a10ea9d076859ec48e9f52929c28ae085a67afe3
| 438
|
tsx
|
TypeScript
|
client/src/components/Form/index.tsx
|
sonergonencler/fullstack-nextjs-typegraphql-apollo-budget-app
|
2fd8e8b0476f2c658f245c1e172ad6777f4fb7fd
|
[
"MIT"
] | null | null | null |
client/src/components/Form/index.tsx
|
sonergonencler/fullstack-nextjs-typegraphql-apollo-budget-app
|
2fd8e8b0476f2c658f245c1e172ad6777f4fb7fd
|
[
"MIT"
] | null | null | null |
client/src/components/Form/index.tsx
|
sonergonencler/fullstack-nextjs-typegraphql-apollo-budget-app
|
2fd8e8b0476f2c658f245c1e172ad6777f4fb7fd
|
[
"MIT"
] | null | null | null |
import styles from './index.module.scss';
interface Props {
handleSubmit: () => void;
}
const Form: React.FC<Props> = ({ children, handleSubmit }) => {
const onSubmit = (event: React.FormEvent) => {
event.preventDefault();
handleSubmit();
};
return (
<form onSubmit={onSubmit} className={styles.form}>
<div className={styles.content}>
{children}
</div>
</form>
);
};
export default Form;
| 19.043478
| 63
| 0.609589
|
2cc4e25b160f6afea15deb30691075ab8d1a5b9a
| 1,228
|
py
|
Python
|
backend/api/fixtures/operational/0001_add_vehicle_makes.py
|
emi-hi/zeva
|
19c3090c6f4b86d12c95a156727f2535ca16ca55
|
[
"Apache-2.0"
] | null | null | null |
backend/api/fixtures/operational/0001_add_vehicle_makes.py
|
emi-hi/zeva
|
19c3090c6f4b86d12c95a156727f2535ca16ca55
|
[
"Apache-2.0"
] | null | null | null |
backend/api/fixtures/operational/0001_add_vehicle_makes.py
|
emi-hi/zeva
|
19c3090c6f4b86d12c95a156727f2535ca16ca55
|
[
"Apache-2.0"
] | null | null | null |
from django.db import transaction
from api.management.data_script import OperationalDataScript
from api.models.vehicle_make import Make
class AddVehicleMakes(OperationalDataScript):
"""
Adds the vehicle makes that we can find from the NRCAN document such as
BMW, Chevrolet, Chrysler, Ford, Honda, Hyundai
"""
is_revertable = False
comment = 'Adds the vehicle makes found in the NRCAN document'
def check_run_preconditions(self):
return True
@transaction.atomic
def run(self):
list_of_makes = [
"Aston Martin", "Audi", "BMW", "Chevrolet", "Chrysler",
"Ferrari", "Fiat", "Ford", "GMC", "Honda", "Hyundai", "Isuzu",
"Jaguar", "Karma", "Kia", "Mazda", "Mercedes-Benz", "Mini",
"Mitsubishi", "Nissan", "Porsche", "Smart EQ", "Subaru", "Suzuki",
"Tesla", "Toyota", "Volkswagen", "Volvo"
]
makes_added = 0
for make_name in list_of_makes:
(_, created) = Make.objects.get_or_create(
name=make_name
)
if created:
makes_added += 1
print("Added {} Vehicles Makes.".format(makes_added))
script_class = AddVehicleMakes
| 29.238095
| 78
| 0.607492
|
6b7aba9014934d8bf74dda56dbfc32920e48f693
| 1,847
|
js
|
JavaScript
|
src/index-manager/index-manager.js
|
palmerusaf/image-carousel-slider
|
750e1d5afc2fe58564faa46f24744003e946787e
|
[
"MIT"
] | null | null | null |
src/index-manager/index-manager.js
|
palmerusaf/image-carousel-slider
|
750e1d5afc2fe58564faa46f24744003e946787e
|
[
"MIT"
] | null | null | null |
src/index-manager/index-manager.js
|
palmerusaf/image-carousel-slider
|
750e1d5afc2fe58564faa46f24744003e946787e
|
[
"MIT"
] | null | null | null |
import { pubsub } from "../pubsub";
export const IndexManager = (() => {
const firstIndex = 0;
let indexes = undefined;
let activeIndex = undefined;
let lastIndex = undefined;
let _cycleIndexAtFiveSeconds = undefined;
pubsub.subscribe("changeActiveIndex", _setActiveIndex);
pubsub.subscribe("changeActiveIndex", _resetIntervalForCycleNextIndex);
pubsub.subscribe("nextButtonPressed", _cycleActiveIndexForward);
pubsub.subscribe("previousButtonPressed", _cycleActiveIndexBackward);
function initWithIndexSize(numberOfIndexes) {
if (!indexes) {
indexes = Number(numberOfIndexes);
_setActiveIndex(0);
lastIndex = Number(numberOfIndexes) - 1;
pubsub.publish("changeActiveIndex", activeIndex);
} else console.error("Indexes already set in IndexManager module.");
}
function _setActiveIndex(index) {
activeIndex = Number(index);
}
function _cycleActiveIndexForward() {
const nextIndex = Number(activeIndex) + 1;
if (Number(activeIndex) === Number(lastIndex)) {
pubsub.publish("changeActiveIndex", Number(firstIndex));
} else {
pubsub.publish("changeActiveIndex", Number(nextIndex));
}
}
function _cycleActiveIndexBackward() {
const previousIndex = Number(activeIndex) - 1;
if (Number(activeIndex) === Number(firstIndex)) {
pubsub.publish("changeActiveIndex", Number(lastIndex));
} else {
pubsub.publish("changeActiveIndex", Number(previousIndex));
}
}
function _resetIntervalForCycleNextIndex() {
clearInterval(_cycleIndexAtFiveSeconds);
_cycleIndexAtFiveSeconds = _executeEveryFiveSeconds(
_cycleActiveIndexForward
);
}
function _executeEveryFiveSeconds(executable) {
const FIVE_SECONDS = 5000;
return setInterval(executable, FIVE_SECONDS);
}
return { initWithIndexSize };
})();
| 29.790323
| 73
| 0.716297
|
b8fc5b1cfd3b269286c44c62a6ad882fc25ea624
| 2,736
|
h
|
C
|
main_asm.h
|
Nezgun/Microcontroller-Rhythm-Game
|
e007a3f2b37419106aa5294a9d7e42a20be73d95
|
[
"MIT"
] | null | null | null |
main_asm.h
|
Nezgun/Microcontroller-Rhythm-Game
|
e007a3f2b37419106aa5294a9d7e42a20be73d95
|
[
"MIT"
] | null | null | null |
main_asm.h
|
Nezgun/Microcontroller-Rhythm-Game
|
e007a3f2b37419106aa5294a9d7e42a20be73d95
|
[
"MIT"
] | null | null | null |
#ifndef _MAIN_ASM_H
#define _MAIN_ASM_H
#ifdef __cplusplus
extern "C" { /* our assembly functions have C calling convention */
#endif
void asm_main(void);
/* interface to my assembly main function */
void PLL_init(void);
void led_enable(void);
void leds_on(int);
void leds_off(void);
void led_disable(void);
void led_on(int);
void led_off(int);
void seg7_enable(void);
void seg7_on(int, int);
void seg7_disable(void);
void seg7s_off(void);
void ms_delay(int);
void seg7dec(int,int);
void SW_enable(void);
short SW2_down(void);
short SW2_up(void);
short SW3_down(void);
short SW3_up(void);
short SW4_down(void);
short SW4_up(void);
short SW5_down(void);
short SW5_up(void);
char SW1_dip(void);
void keypad_enable(void);
int keyscan(void);
char getkey(void);
void wait_keyup(void);
void instr8(char);
void data8(char);
void lcd_init(void);
void clear_lcd(void);
void hex2lcd(char);
char hex2asc(char);
void type_lcd(char*);
void write_int_lcd(int);
void write_long_lcd(long);
void set_lcd_addr(char);
void SCI0_init(int);
char inchar0(void);
void outchar0(unsigned char);
void SCI1_init(int);
char inchar1(void);
void outchar1(unsigned char);
long number(char*);
void ad0_enable(void);
int ad0conv(char);
void ad1_enable(void);
int ad1conv(char);
void servo54_init(void);
void servo76_init(void);
void set_servo54(int);
void set_servo76(int);
void motor0_init(void);
void motor1_init(void);
void motor2_init(void);
void motor3_init(void);
void motor4_init(void);
void motor5_init(void);
void motor6_init(void);
void motor7_init(void);
void motor0(int);
void motor1(int);
void motor2(int);
void motor3(int);
void motor4(int);
void motor5(int);
void motor6(int);
void motor7(int);
void SPI0_init(void);
void SPI1_init(void);
void SPI2_init(void);
char send_SPI0(char);
char send_SPI1(char);
char send_SPI2(char);
void SS0_HI(void);
void SS1_HI(void);
void SS2_HI(void);
void SS0_LO(void);
void SS1_LO(void);
void SS2_LO(void);
void RTI_init(void);
void clear_RTI_flag(void);
void RTI_disable(void);
void SCI0_int_init(int);
char read_SCI0_Rx(void);
void ptrain6_init(void);
void ptrain6(int,int);
void sound_init(void);
void sound_on(void);
void sound_off(void);
void tone(int);
void HILO1_init(void);
void HILOtimes1(void);
int get_HI_time1(void);
int get_LO_time1(void);
void fill_weights(unsigned char*,unsigned char*,int,unsigned char);
void fire_rules(unsigned char*,unsigned char*,unsigned char*,int);
unsigned char calc_output(unsigned char*,unsigned char*,int);
#ifdef __cplusplus
}
#endif
#endif /* _MAIN_ASM_H */
| 24
| 72
| 0.706871
|
a38dfa4a234d04220c1718cb9eb4f6a9ec3443c9
| 764
|
psd1
|
PowerShell
|
PSArchiveItemByDate/PSArchiveItemByDate.psd1
|
kumarstack55/PSArchiveItemByDate
|
2c6d24c5122fb999f578fd7a2320dd63a2b42985
|
[
"MIT"
] | null | null | null |
PSArchiveItemByDate/PSArchiveItemByDate.psd1
|
kumarstack55/PSArchiveItemByDate
|
2c6d24c5122fb999f578fd7a2320dd63a2b42985
|
[
"MIT"
] | null | null | null |
PSArchiveItemByDate/PSArchiveItemByDate.psd1
|
kumarstack55/PSArchiveItemByDate
|
2c6d24c5122fb999f578fd7a2320dd63a2b42985
|
[
"MIT"
] | null | null | null |
@{
ModuleVersion = '1.0.0'
GUID = 'ecbb468e-dee3-4018-926b-19bc22b4b956'
Author = 'kumarstack55'
Description = 'Move files or directories to the YYYYMM folder using the first 8 characters of the specified file name, YYYYMMDD.'
Copyright = '(c) 2022 kumarstack55. All rights reserved.'
PowerShellVersion = '5.1'
NestedModules = @('PSArchiveItemByDate.psm1')
FunctionsToExport = @('Move-ItemToArchiveDirectoryByDateInName')
CmdletsToExport = @()
AliasesToExport = @()
PrivateData = @{
PSData = @{
Tags = @()
LicenseUri = 'https://github.com/kumarstack55/PSArchiveItemByDate/blob/main/LICENSE'
ProjectUri = 'https://github.com/kumarstack55/PSArchiveItemByDate'
}
}
}
| 38.2
| 133
| 0.658377
|
e28c84f8f423fad72ebd1293cc2c34d90a876f15
| 1,346
|
bzl
|
Python
|
research/carls/third_party/rocksdb/workspace.bzl
|
srihari-humbarwadi/neural-structured-learning
|
345b8d644dd7745179263bf6dc9aeb8a921528f4
|
[
"Apache-2.0"
] | 939
|
2019-08-28T06:50:30.000Z
|
2022-03-30T02:37:07.000Z
|
research/carls/third_party/rocksdb/workspace.bzl
|
srihari-humbarwadi/neural-structured-learning
|
345b8d644dd7745179263bf6dc9aeb8a921528f4
|
[
"Apache-2.0"
] | 80
|
2019-09-01T19:47:30.000Z
|
2022-02-02T20:38:38.000Z
|
research/carls/third_party/rocksdb/workspace.bzl
|
srihari-humbarwadi/neural-structured-learning
|
345b8d644dd7745179263bf6dc9aeb8a921528f4
|
[
"Apache-2.0"
] | 196
|
2019-09-01T19:38:53.000Z
|
2022-02-08T01:25:57.000Z
|
"""Provides the repository macro to import rocksdb."""
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def repo():
"""Imports rocksdb."""
ROCKSDB_VERSION = "6.15.5"
ROCKSDB_SHA256 = "d7b994e1eb4dff9dfefcd51a63f86630282e1927fc42a300b93c573c853aa5d0"
http_archive(
name = "rocksdb",
build_file = "//research/carls/third_party/rocksdb:rocksdb.BUILD",
sha256 = ROCKSDB_SHA256,
strip_prefix = "rocksdb-{version}".format(version = ROCKSDB_VERSION),
url = "https://github.com/facebook/rocksdb/archive/v{version}.tar.gz".format(version = ROCKSDB_VERSION),
)
# A dependency of rocksdb that is required for rocksdb::ClockCache.
http_archive(
name = "tbb",
build_file = "//research/carls/third_party/rocksdb:tbb.BUILD",
sha256 = "b182c73caaaabc44ddc5ad13113aca7e453af73c1690e4061f71dfe4935d74e8",
strip_prefix = "oneTBB-2021.1.1",
url = "https://github.com/oneapi-src/oneTBB/archive/v2021.1.1.tar.gz",
)
http_archive(
name = "gflags",
sha256 = "ce2931dd537eaab7dab78b25bec6136a0756ca0b2acbdab9aec0266998c0d9a7",
strip_prefix = "gflags-827c769e5fc98e0f2a34c47cef953cc6328abced",
url = "https://github.com/gflags/gflags/archive/827c769e5fc98e0f2a34c47cef953cc6328abced.tar.gz",
)
| 39.588235
| 112
| 0.698366
|
570859f11e3c659055ef11eec8a67534187e3222
| 2,581
|
js
|
JavaScript
|
js/main.js
|
rafael-romero/js-xmas-edition
|
88f4b1f5ecd4261bea85a51a45ddae82662a5071
|
[
"MIT"
] | null | null | null |
js/main.js
|
rafael-romero/js-xmas-edition
|
88f4b1f5ecd4261bea85a51a45ddae82662a5071
|
[
"MIT"
] | null | null | null |
js/main.js
|
rafael-romero/js-xmas-edition
|
88f4b1f5ecd4261bea85a51a45ddae82662a5071
|
[
"MIT"
] | null | null | null |
function validarNombre(nombre) {
if (nombre.length === 0) {
return "Este campo debe tener algun caracter";
}
if (nombre.length > 50) {
return "Este campo debe tener menos de 50 caracteres";
}
if (!/^[a-z]+$/i.test(nombre)) {
return "El campo nombre solo acepta letras";
}
return "";
}
function validarCiudad(ciudad) {
if (ciudad === "") {
return "Debe elegir una ciudad por favor!";
}
return "";
}
function validarDescripcionRegalo(descripcionRegalo) {
if (descripcionRegalo.length === 0) {
return "Debe escribir que le gustaria recibir";
} else if (descripcionRegalo.length >= 100) {
return "El texto que escribio es demasiado largo, debe achicarlo";
} else if (!/^[a-z0-9]+$/i.test(descripcionRegalo)) {
return "El campo descripcion solo puede tener numeros y letras";
} else {
return "";
}
}
function redirigirAListaDeDeseos(){
window.location.href = "wishlist.html";
}
function validarFormulario(event) {
const nombre = $formulario.nombre.value;
const ciudad = $formulario.ciudad.value;
const descripcionRegalo = $formulario["descripcion-regalo"].value;
const errorNombre = validarNombre(nombre);
const errorCiudad = validarCiudad(ciudad);
const errorDescripcionRegalo = validarDescripcionRegalo(descripcionRegalo);
const errores = {
nombre: errorNombre,
ciudad: errorCiudad,
"descripcion-regalo": errorDescripcionRegalo,
};
esExito = manejarErrores(errores) === 0;
if (esExito) {
$formulario.className = "oculto";
document.querySelector("#exito").className = "";
const tiempoDeEspera = setTimeout(redirigirAListaDeDeseos, 5000);
}
event.preventDefault();
}
function manejarErrores(errores) {
const llaves = Object.keys(errores);
const $errores = document.querySelector("#errores");
let cantidadErrores = 0;
llaves.forEach(function (llave) {
const error = errores[llave];
if (error) {
cantidadErrores++;
$formulario[llave].className = "error";
const $error = document.createElement("li");
$error.innerText = error;
$error.id = llave + "errorEnLi";
if (!document.querySelector(`#${llave}errorEnLi`)) {
$errores.appendChild($error);
}
} else {
$formulario[llave].className = "";
if (document.querySelector(`#${llave}errorEnLi`)) {
document.querySelector(`#${llave}errorEnLi`).remove();
}
}
});
return cantidadErrores;
}
const $formulario = document.querySelector("#carta-a-santa");
$formulario.onsubmit = validarFormulario;
| 26.885417
| 77
| 0.667183
|
1b2c185d091f34ea6751ffe4974eae004392d52d
| 2,071
|
cs
|
C#
|
src/Stripe.Client.Sdk/Constants/Expandables.cs
|
johnallers/Stripe.Client
|
7407fdbde78a8919a5f385a08c90b310da1d53cf
|
[
"MIT"
] | null | null | null |
src/Stripe.Client.Sdk/Constants/Expandables.cs
|
johnallers/Stripe.Client
|
7407fdbde78a8919a5f385a08c90b310da1d53cf
|
[
"MIT"
] | null | null | null |
src/Stripe.Client.Sdk/Constants/Expandables.cs
|
johnallers/Stripe.Client
|
7407fdbde78a8919a5f385a08c90b310da1d53cf
|
[
"MIT"
] | null | null | null |
namespace Stripe.Client.Sdk.Constants
{
public static class Expandables
{
public const string Account = "account";
public const string Application = "application";
public const string ApplicationFee = "application_fee";
public const string BalanceTransaction = "balance_transaction";
public const string CancellationPolicy = "cancellation_policy";
public const string Charge = "charge";
public const string Customer = "customer";
public const string CustomerCommunication = "customer_communication";
public const string CustomerSignature = "customer_signature";
public const string Data = "data";
public const string DefaultCard = "default_card";
public const string DefaultSource = "default_source";
public const string Destination = "destination";
public const string DestinationPayment = "destination_payment";
public const string Document = "document";
public const string DuplicateChargeDocumentation = "duplicate_charge_documentation";
public const string Fee = "fee";
public const string Invoice = "invoice";
public const string MigratedTo = "migrated_to";
public const string Order = "order";
public const string OriginatingTransaction = "originating_transaction";
public const string Parent = "parent";
public const string Product = "product";
public const string Receipt = "receipt";
public const string Recipient = "recipient";
public const string RefundPolicy = "refund_policy";
public const string ServiceDocumentation = "service_documentation";
public const string ShippingDocumentation = "shipping_documentation";
public const string Source = "source";
public const string SourceTransaction = "source_transaction";
public const string SourceTransfer = "source_transfer";
public const string Transfer = "transfer";
public const string UncategorizedFile = "uncategorized_file";
}
}
| 53.102564
| 92
| 0.699179
|
bd2754a291729a3b909e043433a019409865bfb1
| 183
|
rb
|
Ruby
|
app/controllers/chatroom_controller.rb
|
aakashjhawar/chat-app
|
07775242901a20492a8defa0d91a7e34e5356817
|
[
"MIT"
] | 1
|
2019-02-12T17:51:46.000Z
|
2019-02-12T17:51:46.000Z
|
app/controllers/chatroom_controller.rb
|
aakashjhawar/ChatApp
|
07775242901a20492a8defa0d91a7e34e5356817
|
[
"MIT"
] | 42
|
2020-02-29T00:49:33.000Z
|
2022-03-30T23:00:27.000Z
|
app/controllers/chatroom_controller.rb
|
aakashjhawar/ChatApp
|
07775242901a20492a8defa0d91a7e34e5356817
|
[
"MIT"
] | 1
|
2020-09-06T07:15:59.000Z
|
2020-09-06T07:15:59.000Z
|
class ChatroomController < ApplicationController
# before_action :require_user
def index
@message = Message.new
@messages = Message.custom_display
@users = User.all
end
end
| 18.3
| 48
| 0.770492
|
0dfe3cffcba9c5fef590f52fa87d03ae71ed291b
| 3,708
|
css
|
CSS
|
catfish2/wwwroot/assets/css/manager-styles.css
|
arcualberta/Catfish-Deployment
|
e0fe76c881a1116343c7974815d091b61836dd78
|
[
"MIT"
] | null | null | null |
catfish2/wwwroot/assets/css/manager-styles.css
|
arcualberta/Catfish-Deployment
|
e0fe76c881a1116343c7974815d091b61836dd78
|
[
"MIT"
] | 7
|
2020-05-19T19:26:09.000Z
|
2022-02-28T01:26:38.000Z
|
catfish2/wwwroot/assets/css/manager-styles.css
|
arcualberta/Catfish-Deployment
|
e0fe76c881a1116343c7974815d091b61836dd78
|
[
"MIT"
] | null | null | null |
.section-heading {
margin: 10px;
}
.section-heading .label {
font-size: large;
font-weight: bold;
}
.navbar-brand {
/* replace Piranha Logo on the top of the menu */
/*background: url(../img/logo-menu.png) 0 50% no-repeat;
background-size: contain;
*/
}
.email-template .field-list{
border:solid 1px #ccc;
border-radius: 5px;
}
.email-template .field-list .field {
margin: 15px 5px;
}
.email-template .field-list .fa-edit {
margin: 5px;
}
.table.field-set-view td {
background-color: white;
}
.table-bordered tr {
border-color: #eee !important;
}
.table-bordered tr .option-value {
margin: 0 -12px;
padding: 5px;
border-bottom: solid 1px #ccc;
}
/* .table-bordered tr .option-value:nth-child(odd) {
background-color: #ebe39e !important;
}
.table-bordered tr .option-value:nth-child(even) {
background-color: #c2f2ef !important;
}
*/
.table-bordered tr .option-value:first-child {
margin-top: -12px !important;
}
.table-bordered tr .option-value:last-child {
margin-bottom: -12px !important;
}
/*=======================================================================================================================================================*/
/* ======================================== WORKFLOW EDITOR ============================================================================= */
.hide{
display: none;
}
.show{
display: block;
}
.editableText, .addOptionText {
position: relative;
display: inline-block;
margin: 1px;
border: 1px double blue;
width: 100%;
}
.inline-editor i, .new-option-value i, .option-value i{
margin-left: 10px;
}
.inline-editor .fa-window-close, .option-value .fa-trash-alt, .new-option-value > .fa-window-close {
color: red;
}
.inline-editor .fa-save, .new-option-value > .fa-plus-square, .new-option-value > .fa-save {
color: green;
}
.new-option-value > .fa-plus-square {
font-size: 18px;
margin-right: -5px;
/* margin-top: 5px; */
}
.new-option-value {
padding-top: 5px;
padding-bottom: 5px;
width: 100%;
}
.addOptionText {
border-color: #80808012;
}
.addOptionText select{
border: 1px solid Grey;
width:25%;
}
.addOptionText input {
width: 74%;
}
/* jquery confirm dialog */
.jconfirm-title-c{
border-bottom: 2px solid Grey;
}
.jconfirm-title-c .danger.fa-exclamation-triangle {
color: #c70f0f;
padding-right: 5px;
}
.jconfirm-title-c .warning.fa-exclamation-triangle {
color: #fdb051;
padding-right: 5px;
}
.jconfirm-title .success.fa-check {
color: forestgreen;
padding-right: 5px;
}
.jconfirm-content {
padding: 5px;
color: #582322;
background-color: #eedad9;
border-color: #e7cbca;
border-bottom: 2px solid grey;
}
.jconfirm-buttons button:nth-child(1) {
color: #fff !important;
background-color: #a94441 !important;
border-color: #a94441 !important;
}
.jconfirm-buttons .btn:nth-child(2) {
color: #fff !important;
background-color: #6c757d !important;
border-color: #6c757d !important;
}
.jconfirm-content .warning{
padding: 5px;
color: #856404;
background-color: #fff3cd;
margin: -7px;
}
.jconfirm-content .success {
color: #155724;
background-color: #d4edda;
border-color: #c3e6cb;
margin: -7px;
padding: 5px;
}
/*=======================================================================================================================================================*/
| 23.468354
| 159
| 0.535329
|
62d57c8030054ed8ee5643dce79cfecfc0ea3101
| 107
|
sql
|
SQL
|
ulicms/lib/migrations/up/017.sql
|
derUli/ulicms
|
4a5fb4b468f5c862644955cad61caa7de90f5bd5
|
[
"BSD-3-Clause"
] | 14
|
2016-02-06T01:41:17.000Z
|
2022-02-12T20:36:17.000Z
|
ulicms/lib/migrations/up/017.sql
|
derUli/ulicms
|
4a5fb4b468f5c862644955cad61caa7de90f5bd5
|
[
"BSD-3-Clause"
] | 608
|
2015-04-23T21:38:08.000Z
|
2022-03-15T13:43:45.000Z
|
ulicms/lib/migrations/up/017.sql
|
derUli/ulicms
|
4a5fb4b468f5c862644955cad61caa7de90f5bd5
|
[
"BSD-3-Clause"
] | 3
|
2016-12-04T16:48:22.000Z
|
2022-03-16T23:39:43.000Z
|
ALTER TABLE `{prefix}content` DROP COLUMN `og_type`;
delete from `{prefix}settings` where name = 'og_type';
| 53.5
| 54
| 0.747664
|
d62e17aaf0b9370b5e815aaf3b6aa1c5aacf4a86
| 4,550
|
swift
|
Swift
|
iOS/WifiRemote/RemoteViewController.swift
|
itaybachar/WifiRemote
|
df0176a1a511f6cc84e94d5189747862923472e0
|
[
"MIT"
] | null | null | null |
iOS/WifiRemote/RemoteViewController.swift
|
itaybachar/WifiRemote
|
df0176a1a511f6cc84e94d5189747862923472e0
|
[
"MIT"
] | 1
|
2021-12-17T03:18:08.000Z
|
2021-12-17T03:18:08.000Z
|
iOS/WifiRemote/RemoteViewController.swift
|
itaybachar/WifiRemote
|
df0176a1a511f6cc84e94d5189747862923472e0
|
[
"MIT"
] | null | null | null |
//
// RemoteViewController.swift
// WifiRemote
//
// Created by Chang Yaramothu on 12/15/21.
//
import UIKit
class RemoteViewController : UIViewController {
var client: UDPClient?
var mouseStart: CGPoint?
var mousePos: CGPoint?
var mouseSpeed: CGFloat = 5
@IBOutlet var panRecognizer: UIPanGestureRecognizer!
let sem = NSCondition()
override func viewDidLoad() {
super.viewDidLoad()
hideKeyboardWhenTappedAround()
client?.connectionFailedCallback = disconnect
}
//Remote Screen
@IBOutlet weak var MousePad: UIImageView!
{
didSet
{
MousePad.isUserInteractionEnabled=true
MousePad.layer.cornerRadius=20
}
}
@IBAction func cursorSpeedChange(_ sender: UISlider) {
mouseSpeed = CGFloat(sender.value)
}
@IBAction func handleTap(_ sender: UITapGestureRecognizer) {
if(sender.state == .ended)
{
if(sender.numberOfTouches == 1)
{
client!.sendUDP("Left Click")
}
else
{
client!.sendUDP("Right Click")
}
}
}
@IBAction func handlePan(_ sender: UIPanGestureRecognizer) {
var diff: CGPoint
switch (sender.state)
{
case UIPanGestureRecognizer.State.began:
mouseStart = sender.location(in: MousePad)
if(sender.numberOfTouches == 1)
{
DispatchQueue.global().async {
while(self.panRecognizer.state != .ended)
{
guard let pos = self.mousePos else {
//usleep(10000)
continue
}
let out = pos.norm().scale(mult: self.mouseSpeed).toString()
self.client!.sendUDP(out)
usleep(10000)
}
}
}
return
case UIPanGestureRecognizer.State.ended:
mousePos = nil
return
default:
if (sender.numberOfTouches == 2)
{
let vel = sender.velocity(in: MousePad)
let cur = sender.location(in: MousePad)
if((cur-mouseStart!).magSqrd() > 80)
{
mouseStart = cur
if(vel.y<0)
{
client?.sendUDP("\\/")
}
else
{
client?.sendUDP("/\\")
}
}
}
else
{
guard let pos = mouseStart else {
return
}
mousePos = sender.location(in: MousePad) - pos
}
}
}
@IBAction func handleButtonClick(_ sender: UIButton) {
var outmsg = ""
if sender.titleLabel?.text != nil
{
outmsg += sender.titleLabel!.text!
}
client!.sendUDP(outmsg)
}
@IBAction func handleDisconnect(_ sender: Any) {
disconnect()
}
@IBAction func returnandle(_ sender: UITextField) {
client!.sendUDP("RET")
}
@IBAction func valueChanged(_ sender: UITextField) {
var msg = ""
if(sender.text! == "")
{
msg += "BACK"
}
else
{
msg += "KEY: " + (sender.text?.last.map(String.init))!
}
sender.text = " "
client!.sendUDP(msg)
}
func disconnect()
{
DispatchQueue.main.async {
self.client = nil
self.dismiss(animated: true, completion: nil)
}
}
}
func -(lhs: CGPoint, rhs: CGPoint) -> CGPoint {
return CGPoint(x: lhs.x - rhs.x, y: lhs.y - rhs.y)
}
func /(lhs: CGPoint, rhs: CGFloat) -> CGPoint {
return CGPoint(x: lhs.x/rhs, y: lhs.y/rhs)
}
extension CGPoint {
func norm() -> CGPoint
{
let denom = (x*x + y*y).squareRoot()
return CGPoint(x: self.x/denom,y:self.y/denom)
}
func magSqrd() -> Float
{
return Float(self.x*self.x + self.y*self.y)
}
func scale(mult: CGFloat) -> CGPoint
{
return CGPoint(x: self.x*mult,y:self.y*mult)
}
func toString() ->String
{
return String(format: "MV: %.2f,%.2f", x,y)
}
}
| 25
| 84
| 0.470989
|
c60e4cf38411fd3c8eb52c8310cf0ce78807a6c3
| 218
|
java
|
Java
|
src/main/java/io/snow/core/codec/ProtocolDecode.java
|
tulipR/Snow
|
713caf53326fa1eb9f2513c815bee5d389ca5ff4
|
[
"Apache-2.0"
] | 2
|
2019-02-18T17:05:03.000Z
|
2019-02-20T06:35:57.000Z
|
src/main/java/io/snow/core/codec/ProtocolDecode.java
|
tulipR/Snow
|
713caf53326fa1eb9f2513c815bee5d389ca5ff4
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/io/snow/core/codec/ProtocolDecode.java
|
tulipR/Snow
|
713caf53326fa1eb9f2513c815bee5d389ca5ff4
|
[
"Apache-2.0"
] | null | null | null |
package io.snow.core.codec;
import java.nio.ByteBuffer;
import java.util.LinkedList;
/**
*
* @author zhangliang 2019.03.05
*
*/
public interface ProtocolDecode {
LinkedList<Object> decode(ByteBuffer data);
}
| 14.533333
| 44
| 0.724771
|
c29471827b46f5b849dcf0b03f4e1507df07f02f
| 3,576
|
html
|
HTML
|
client/webapp/app/matchday/edit-score/edit-score.html
|
tekdungtralala/eplweb
|
bbd02f5c918ebcfd17a9880b50c3b5826acec324
|
[
"MIT"
] | null | null | null |
client/webapp/app/matchday/edit-score/edit-score.html
|
tekdungtralala/eplweb
|
bbd02f5c918ebcfd17a9880b50c3b5826acec324
|
[
"MIT"
] | null | null | null |
client/webapp/app/matchday/edit-score/edit-score.html
|
tekdungtralala/eplweb
|
bbd02f5c918ebcfd17a9880b50c3b5826acec324
|
[
"MIT"
] | null | null | null |
<table class="table borderless epl-table">
<thead>
<tr>
<td>#</td>
<td>ID</td>
<td class="epl-right" colspan="2">Home Team</td>
<td class="epl-center">VS</td>
<td colspan="2">Away Team</td>
</tr>
</thead>
<tbody>
<tr class="odd" ng-repeat="(k,v) in vm.datas">
<td>{{k+1}}</td>
<td>{{v.id}}</td>
<td class="epl-right">
{{v.homeTeam.name}}
<img class="image epl-mini-team-logo"
ng-src="eplweb_components/image/logo/150x150/{{v.homeTeam.id}}.png" alt="">
</td>
<td> {{v.homeGoal < 0 ? "-" : v.homeGoal}} </td>
<td class="epl-center">
<button class="btn btn-block btn-primary btn-xs" ng-click="vm.preEditScore(v)">
<i class="fa fa-pencil"></i>
</button>
</td>
<td> {{v.awayGoal < 0 ? "-" : v.awayGoal}} </td>
<td>
<img class="image epl-mini-team-logo"
ng-src="eplweb_components/image/logo/150x150/{{v.awayTeam.id}}.png" alt="">
{{v.awayTeam.name}}
</td>
</tr>
</tbody>
</table>
<span class="epl-note">
* After finished update score some matchday, don't forget to update rank table through menu "Update Rank" above
</span>
<script type="text/ng-template" id="editScore.html">
<div class="modal-header epl-modal-header-edit-score">
<h4 class="modal-title">
Update Score
</h4>
</div>
<div class="modal-body epl-center epl-modal-body-edit-score">
<form name="editScore">
<table class="table borderless epl-tbl-edit-score">
<tbody>
<tr>
<td colspan='2'></td>
<td>
<a href="" class="btn btn-link epl-score-btn"
ng-click="vm.score[0] = vm.score[0] + 1">
<i class="fa fa-angle-up"></i>
</a>
</td>
<td></td>
<td>
<a href="" class="btn btn-link epl-score-btn"
ng-click="vm.score[1] = vm.score[1] + 1">
<i class="fa fa-angle-up"></i>
</a>
</td>
<td colspan='2'></td>
</tr>
<tr>
<td>{{vm.currMatch.homeTeam.simpleName}}</td>
<td>
<img class="image epl-mini-team-logo"
ng-src="eplweb_components/image/logo/150x150/{{vm.currMatch.homeTeam.id}}.png"/>
</td>
<td>
<input type="number" class="epl-input-text epl-center" autofocus
required="true" name="homeGoal" min="0"
ng-model="vm.score[0]"/>
</td>
<td>VS</td>
<td>
<input type="number" class="epl-input-text epl-center"
required="true" name="awayGoal" min="0"
ng-model="vm.score[1]"/>
</td>
<td>
<img class="image epl-mini-team-logo"
ng-src="eplweb_components/image/logo/150x150/{{vm.currMatch.awayTeam.id}}.png"/>
</td>
<td>{{vm.currMatch.awayTeam.simpleName}}</td>
</tr>
<tr>
<td colspan='2'></td>
<td>
<a href="" class="btn btn-link epl-score-btn"
ng-click="vm.score[0] = (vm.score[0] - 1) < 0 ? 0 : vm.score[0] - 1">
<i class="fa fa-angle-down"></i>
</a>
</td>
<td></td>
<td>
<a href="" class="btn btn-link epl-score-btn"
ng-click="vm.score[1] = (vm.score[1] - 1) < 0 ? 0 : vm.score[1] - 1">
<i class="fa fa-angle-down"></i>
</a>
</td>
<td colspan='2'></td>
</tr>
</tbody>
</table>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-default" ng-click="vm.cancelEditScore()">
<span class="glyphicon glyphicon-ban-circle"></span>
Cancel
</button>
<button class="btn btn-{{!editScore.$valid ? 'default' : 'primary'}}"
ng-click="vm.doEditScore()" ng-disabled="!editScore.$valid">
<span class="glyphicon glyphicon-save"></span>
Save
</button>
</div>
</script>
| 29.311475
| 112
| 0.562081
|
ea770034ea3eb1851107670eb8fde7ba87aca208
| 3,384
|
go
|
Go
|
bracket_test.go
|
falmar/smarty-bracket-delim
|
a8c005c39e0004912979cd29993911242f048a7c
|
[
"MIT"
] | null | null | null |
bracket_test.go
|
falmar/smarty-bracket-delim
|
a8c005c39e0004912979cd29993911242f048a7c
|
[
"MIT"
] | null | null | null |
bracket_test.go
|
falmar/smarty-bracket-delim
|
a8c005c39e0004912979cd29993911242f048a7c
|
[
"MIT"
] | null | null | null |
// Copyright 2016 David Lavieri. All rights reserved.
// Use of this source code is governed by a MIT License
// License that can be found in the LICENSE file.
package main
import "testing"
// ------------ LEFT BRACE
var leftBrace = []string{
"function () {",
"call({",
"myObject: { // random comment",
"let array = [{",
"{",
"calling({my: {",
"const single = {}",
"{}",
}
var expLeftBrace = []string{
"function () {ldelim}",
"call({ldelim}",
"myObject: {ldelim} // random comment",
"let array = [{ldelim}",
"{ldelim}",
"calling({ldelim}my: {ldelim}",
"const single = {ldelim}}",
"{ldelim}}",
}
var nonLeftBrace = []string{
`<body>`,
`{$some_variable}`,
`Outside the script tag may be pure html or may not`,
`<script type="text/javascript">`,
`let myVar = {json_decode($jsonVariable)}`,
`let myOtherVar = '{$wuuuu}'`,
`console.log({include file=$myCustomFile})`,
`const myObject = {hello: "world", myObject:{one: 1, two: [2, 2]}}`,
`}`,
`hello: "world"`,
`world: "hello"`,
`})`,
`hello: "world",`,
`one: 1,`,
`two: [2, 2]`,
`}`,
`}]`,
`</script>`,
`</body>`,
}
func TestParseLeftBraceMatch(t *testing.T) {
for i, line := range leftBrace {
nl, matched := parseLeftBrace(line)
if !matched {
t.Fatalf("Should match %s", line)
}
if nl != expLeftBrace[i] {
t.Fatalf("Expected left brace parsed: %s; got: %s", expLeftBrace[i], nl)
}
}
}
func TestParseLeftBraceNoMatch(t *testing.T) {
for _, line := range nonLeftBrace {
nl, matched := parseLeftBrace(line)
if matched && nl != line {
t.Fatalf("Should not match %s; %s", line, nl)
}
}
}
// ------------ RIGHT BRACE
var rightBrace = []string{
`everthing }`,
`}, { should`,
`be }) good`,
`or }] not?`,
`... maybe }] }?`,
`}, {ldelim}`,
`}, maybe: ""}, did: "not"}, work: {"entirely"}`,
`}, maybe: ""}, did: "not"}, work: {"entir}ely"}`,
"const single = {}",
"{}",
}
var expRightBrace = []string{
`everthing {rdelim}`,
`{rdelim}, { should`,
`be {rdelim}) good`,
`or {rdelim}] not?`,
`... maybe {rdelim}] {rdelim}?`,
`{rdelim}, {ldelim}`,
`{rdelim}, maybe: ""{rdelim}, did: "not"{rdelim}, work: {"entirely"}`,
`{rdelim}, maybe: ""{rdelim}, did: "not"{rdelim}, work: {"entir}ely"{rdelim}`,
"const single = {{rdelim}",
"{{rdelim}",
}
var nonRightBrace = []string{
`<body>`,
`{$some_variable}`,
`Outside the script tag may be pure html or may not`,
`<script type="text/javascript">`,
`let myVar = {json_decode($jsonVariable)}`,
`let myOtherVar = '{$wuuuu}'`,
`console.log({include file=$myCustomFile})`,
`funcion () {`,
`const myObject = {hello: "world", myObject:{one: 1, two: [2, 2]}`,
`call({`,
`hello: "world"`,
`, {`,
`world: "hello"`,
`)`,
`let array = [{`,
`hello: "world",`,
`myObject:{`,
`one: 1,`,
`two: [2, 2] `,
`]`,
`inline_call({hello: "world", myObject:{one: 1, two: [2, 2]})`,
`</script>`,
`</body>`,
}
func TestParseRightBrace(t *testing.T) {
for i, line := range rightBrace {
nl, matched := parseRightBrace(line)
if !matched {
t.Fatalf("Should match: %s", line)
}
if nl != expRightBrace[i] {
t.Fatalf("Expected right brace parsed: %s; got: %s", expRightBrace[i], nl)
}
}
}
func TestParseRightBraceNoMatch(t *testing.T) {
for _, line := range nonRightBrace {
nl, matched := parseRightBrace(line)
if matched && nl != line {
t.Fatalf("Should not match %s; %s", line, nl)
}
}
}
| 21.692308
| 79
| 0.578014
|
e2a2135dd3ff9ef9f9051f3af53c51c85d07ef28
| 549
|
py
|
Python
|
lib/interpreter/SImport.py
|
vini175pa/sublime-import-js
|
4b95e5fd68bb1c9f5e06f791eb415d7c6c49ce88
|
[
"MIT"
] | 8
|
2016-03-25T21:32:43.000Z
|
2016-05-07T19:59:38.000Z
|
lib/interpreter/SImport.py
|
vini175pa/simple-import-js
|
4b95e5fd68bb1c9f5e06f791eb415d7c6c49ce88
|
[
"MIT"
] | 4
|
2016-08-14T21:18:37.000Z
|
2022-01-13T17:39:37.000Z
|
lib/interpreter/SImport.py
|
vini175pa/simple-import-js
|
4b95e5fd68bb1c9f5e06f791eb415d7c6c49ce88
|
[
"MIT"
] | 1
|
2016-08-15T17:10:16.000Z
|
2016-08-15T17:10:16.000Z
|
import re
from sublime import Region
class SImport:
@staticmethod
def getExpressionInContext(expression, context):
match = re.search(r"[^\{{\}}\(\)\<\>\.;\s]*{0}$".format(expression), context)
if match:
return match.group(0)
return expression
def __init__(self, expression, context, region, context_region):
self.expression = self.getExpressionInContext(expression, context)
self.region = Region(region.end() - len(self.expression), region.end())
self.context = context
self.context_region = context_region
| 32.294118
| 81
| 0.703097
|
340b88b0d5c149d725aec15e4c506a5748692cdb
| 4,591
|
dart
|
Dart
|
lib/model/common_audit.dart
|
eZmaxinc/eZmax-SDK-dart
|
96c489d8d6f8d95536c11a2ea72624b9895522bf
|
[
"MIT"
] | null | null | null |
lib/model/common_audit.dart
|
eZmaxinc/eZmax-SDK-dart
|
96c489d8d6f8d95536c11a2ea72624b9895522bf
|
[
"MIT"
] | null | null | null |
lib/model/common_audit.dart
|
eZmaxinc/eZmax-SDK-dart
|
96c489d8d6f8d95536c11a2ea72624b9895522bf
|
[
"MIT"
] | null | null | null |
//
// AUTO-GENERATED FILE, DO NOT MODIFY!
//
// @dart=2.0
// ignore_for_file: unused_element, unused_import
// ignore_for_file: always_put_required_named_parameters_first
// ignore_for_file: constant_identifier_names
// ignore_for_file: lines_longer_than_80_chars
part of openapi.api;
class CommonAudit {
/// Returns a new [CommonAudit] instance.
CommonAudit({
@required this.fkiUserIDCreated,
@required this.fkiUserIDModified,
this.fkiApikeyIDCreated,
this.fkiApikeyIDModified,
@required this.dtCreatedDate,
@required this.dtModifiedDate,
});
/// The unique ID of the User
int fkiUserIDCreated;
/// The unique ID of the User
int fkiUserIDModified;
/// The unique ID of the Apikey
int fkiApikeyIDCreated;
/// The unique ID of the Apikey
int fkiApikeyIDModified;
/// Represent a Date Time. The timezone is the one configured in the User's profile.
String dtCreatedDate;
/// Represent a Date Time. The timezone is the one configured in the User's profile.
String dtModifiedDate;
@override
bool operator ==(Object other) => identical(this, other) || other is CommonAudit &&
other.fkiUserIDCreated == fkiUserIDCreated &&
other.fkiUserIDModified == fkiUserIDModified &&
other.fkiApikeyIDCreated == fkiApikeyIDCreated &&
other.fkiApikeyIDModified == fkiApikeyIDModified &&
other.dtCreatedDate == dtCreatedDate &&
other.dtModifiedDate == dtModifiedDate;
@override
int get hashCode =>
// ignore: unnecessary_parenthesis
(fkiUserIDCreated == null ? 0 : fkiUserIDCreated.hashCode) +
(fkiUserIDModified == null ? 0 : fkiUserIDModified.hashCode) +
(fkiApikeyIDCreated == null ? 0 : fkiApikeyIDCreated.hashCode) +
(fkiApikeyIDModified == null ? 0 : fkiApikeyIDModified.hashCode) +
(dtCreatedDate == null ? 0 : dtCreatedDate.hashCode) +
(dtModifiedDate == null ? 0 : dtModifiedDate.hashCode);
@override
String toString() => 'CommonAudit[fkiUserIDCreated=$fkiUserIDCreated, fkiUserIDModified=$fkiUserIDModified, fkiApikeyIDCreated=$fkiApikeyIDCreated, fkiApikeyIDModified=$fkiApikeyIDModified, dtCreatedDate=$dtCreatedDate, dtModifiedDate=$dtModifiedDate]';
Map<String, dynamic> toJson() {
final json = <String, dynamic>{};
json[r'fkiUserIDCreated'] = fkiUserIDCreated;
json[r'fkiUserIDModified'] = fkiUserIDModified;
if (fkiApikeyIDCreated != null) {
json[r'fkiApikeyIDCreated'] = fkiApikeyIDCreated;
}
if (fkiApikeyIDModified != null) {
json[r'fkiApikeyIDModified'] = fkiApikeyIDModified;
}
json[r'dtCreatedDate'] = dtCreatedDate;
json[r'dtModifiedDate'] = dtModifiedDate;
return json;
}
/// Returns a new [CommonAudit] instance and imports its values from
/// [value] if it's a [Map], null otherwise.
// ignore: prefer_constructors_over_static_methods
static CommonAudit fromJson(dynamic value) {
if (value is Map) {
final json = value.cast<String, dynamic>();
return CommonAudit(
fkiUserIDCreated: mapValueOfType<int>(json, r'fkiUserIDCreated'),
fkiUserIDModified: mapValueOfType<int>(json, r'fkiUserIDModified'),
fkiApikeyIDCreated: mapValueOfType<int>(json, r'fkiApikeyIDCreated'),
fkiApikeyIDModified: mapValueOfType<int>(json, r'fkiApikeyIDModified'),
dtCreatedDate: mapValueOfType<String>(json, r'dtCreatedDate'),
dtModifiedDate: mapValueOfType<String>(json, r'dtModifiedDate'),
);
}
return null;
}
static List<CommonAudit> listFromJson(dynamic json, {bool emptyIsNull, bool growable,}) =>
json is List && json.isNotEmpty
? json.map(CommonAudit.fromJson).toList(growable: true == growable)
: true == emptyIsNull ? null : <CommonAudit>[];
static Map<String, CommonAudit> mapFromJson(dynamic json) {
final map = <String, CommonAudit>{};
if (json is Map && json.isNotEmpty) {
json
.cast<String, dynamic>()
.forEach((key, dynamic value) => map[key] = CommonAudit.fromJson(value));
}
return map;
}
// maps a json object with a list of CommonAudit-objects as value to a dart map
static Map<String, List<CommonAudit>> mapListFromJson(dynamic json, {bool emptyIsNull, bool growable,}) {
final map = <String, List<CommonAudit>>{};
if (json is Map && json.isNotEmpty) {
json
.cast<String, dynamic>()
.forEach((key, dynamic value) {
map[key] = CommonAudit.listFromJson(
value,
emptyIsNull: emptyIsNull,
growable: growable,
);
});
}
return map;
}
}
| 35.315385
| 255
| 0.693531
|
da592414a0bb0756f010dc5b454b95d8d0726182
| 5,684
|
php
|
PHP
|
resources/views/auth/passwords/changePassword.blade.php
|
Adinathg94/test
|
e748a3378734a3c7fc65cc390f3d52dabde34f75
|
[
"MIT"
] | null | null | null |
resources/views/auth/passwords/changePassword.blade.php
|
Adinathg94/test
|
e748a3378734a3c7fc65cc390f3d52dabde34f75
|
[
"MIT"
] | null | null | null |
resources/views/auth/passwords/changePassword.blade.php
|
Adinathg94/test
|
e748a3378734a3c7fc65cc390f3d52dabde34f75
|
[
"MIT"
] | null | null | null |
@extends('index')
@section('content')
<div class="content-wrapper">
<!-- Page header -->
<div class="page-header page-header-default">
<div class="page-header-content">
<div class="page-title">
<h4> <span class="text-semibold">Change</span> Password</h4>
</div>
</div>
<div class="breadcrumb-line">
<ul class="breadcrumb">
<li><a href="{{url('/home')}}"><i class="icon-home2 position-left"></i> Home</a></li>
<!-- <li><a href="{{url('/home')}}">Account Settings</a></li> -->
<li class="active">Change Password</li>
</ul>
</div>
</div>
<!-- /page header -->
<!-- Content area -->
<div class="content">
<!-- Info alert -->
<!-- /info alert -->
<!-- Sidebars overview -->
<div class="panel panel-flat panel-body">
<div class="panel-heading">
<h5 class="panel-title">Change Password</h5>
<!-- <div class="heading-elements">
<ul class="icons-list">
<li><a data-action="collapse"></a></li>
<li><a data-action="reload"></a></li>
<li><a data-action="close"></a></li>
</ul>
</div> -->
</div>
<div class="panel-body">
</div>
<div id="msg" class=""></div>
@if(session()->has('message'))
<div class="alert alert-success">
{{ session()->get('message') }}
</div>
@endif
@if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<form class="form-horizontal" id="changePassword" role="form" method="POST" action="{{ route('update_password') }}">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
<label for="password" class="col-md-4 control-label">Old Password</label>
<div class="col-md-6">
<input id="oldpassword" type="password" class="form-control" name="oldpassword" required>
@if ($errors->has('oldpassword'))
<span class="help-block">
<strong>{{ $errors->first('oldpassword') }}</strong>
</span>
@endif
</div>
</div>
<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
<label for="password" class="col-md-4 control-label">New Password</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control" name="password" required>
@if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
@endif
</div>
</div>
<div class="form-group{{ $errors->has('password_confirmation') ? ' has-error' : '' }}">
<label for="password-confirm" class="col-md-4 control-label">Confirm Password</label>
<div class="col-md-6">
<input id="password-confirm" type="password" class="form-control" name="password_confirmation" required>
@if ($errors->has('password_confirmation'))
<span class="help-block">
<strong>{{ $errors->first('password_confirmation') }}</strong>
</span>
@endif
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Reset Password
</button>
</div>
</div>
</form>
</div></div></div>
@endsection
@push('script')
<script>
$(document).ready(function() {
$("#changePassword").validate({
rules : {
password : {
required : true,
minlength:5
},
oldpassword:{
required:true,
minlength:5
},
password_confirmation : {
required: true,
minlength: 5,
equalTo: "#password"
},
},
messages : {
password_confirmation : {
equalTo: "Password does not match!"
}
},
});
});
</script>
@endpush
| 36.909091
| 132
| 0.374912
|
a44b5d2d0ddae5546bc27f9423b5b7e35518f25c
| 1,874
|
php
|
PHP
|
src/Providers/MetadataServiceProvider.php
|
markusjwetzel/laravel-data-mapper
|
8fac20e5bca8fb81eefa7dacc49269b4a6241cbf
|
[
"MIT"
] | 11
|
2015-08-09T18:57:51.000Z
|
2017-01-27T06:51:18.000Z
|
src/Providers/MetadataServiceProvider.php
|
markusjwetzel/laravel-data-mapper
|
8fac20e5bca8fb81eefa7dacc49269b4a6241cbf
|
[
"MIT"
] | 2
|
2015-12-29T01:10:59.000Z
|
2016-01-11T02:25:14.000Z
|
src/Providers/MetadataServiceProvider.php
|
markusjwetzel/laravel-data-mapper
|
8fac20e5bca8fb81eefa7dacc49269b4a6241cbf
|
[
"MIT"
] | 3
|
2015-08-11T10:17:14.000Z
|
2016-09-29T01:26:37.000Z
|
<?php
namespace ProAI\Datamapper\Providers;
use Illuminate\Support\ServiceProvider;
use ProAI\Datamapper\Metadata\ClassFinder;
use Illuminate\Filesystem\ClassFinder as FilesystemClassFinder;
use ProAI\Datamapper\Metadata\AnnotationLoader;
use Doctrine\Common\Annotations\AnnotationReader;
class MetadataServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->registerAnnotations();
$this->registerAnnotationReader();
$this->registerClassFinder();
}
/**
* Registers all annotation classes
*
* @return void
*/
public function registerAnnotations()
{
$app = $this->app;
$loader = new AnnotationLoader($app['files'], __DIR__ . '/../Annotations');
$loader->registerAll();
}
/**
* Register the class finder implementation.
*
* @return void
*/
protected function registerAnnotationReader()
{
$this->app->singleton('datamapper.annotationreader', function ($app) {
return new AnnotationReader;
});
}
/**
* Register the class finder implementation.
*
* @return void
*/
protected function registerClassFinder()
{
$this->app->singleton('datamapper.classfinder', function ($app) {
$finder = new FilesystemClassFinder;
return new ClassFinder($finder);
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return [
'datamapper.classfinder',
'datamapper.annotationreader',
];
}
}
| 21.54023
| 83
| 0.60032
|
6f260603df2f160556abdbeee8159ddb65cde36f
| 15,278
|
dart
|
Dart
|
pkg/compiler/lib/src/closure.dart
|
Alkarar1122/sdk
|
a00c5c29da1ff24a13cbeb608f90357861e23922
|
[
"BSD-Source-Code"
] | 40
|
2021-11-22T02:54:40.000Z
|
2022-03-31T03:33:35.000Z
|
pkg/compiler/lib/src/closure.dart
|
Alkarar1122/sdk
|
a00c5c29da1ff24a13cbeb608f90357861e23922
|
[
"BSD-Source-Code"
] | 5
|
2021-12-28T03:22:35.000Z
|
2022-01-25T03:29:44.000Z
|
pkg/compiler/lib/src/closure.dart
|
Alkarar1122/sdk
|
a00c5c29da1ff24a13cbeb608f90357861e23922
|
[
"BSD-Source-Code"
] | 5
|
2021-11-22T06:57:51.000Z
|
2022-03-10T09:33:20.000Z
|
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:kernel/ast.dart' as ir;
import 'common.dart';
import 'elements/entities.dart';
import 'js_model/closure.dart';
import 'js_model/element_map.dart';
import 'serialization/serialization.dart';
/// Class that provides information for how closures are rewritten/represented
/// to preserve Dart semantics when compiled to JavaScript. Given a particular
/// node to look up, it returns a information about the internal representation
/// of how closure conversion is implemented. T is an ir.Node or Node.
abstract class ClosureData {
/// Deserializes a [ClosureData] object from [source].
factory ClosureData.readFromDataSource(
JsToElementMap elementMap, DataSource source) =
ClosureDataImpl.readFromDataSource;
/// Serializes this [ClosureData] to [sink].
void writeToDataSink(DataSink sink);
/// Look up information about the variables that have been mutated and are
/// used inside the scope of [node].
ScopeInfo getScopeInfo(MemberEntity member);
ClosureRepresentationInfo getClosureInfo(ir.LocalFunction localFunction);
/// Look up information about a loop, in case any variables it declares need
/// to be boxed/snapshotted.
CapturedLoopScope getCapturedLoopScope(ir.Node loopNode);
/// Accessor to the information about scopes that closures capture. Used by
/// the SSA builder.
CapturedScope getCapturedScope(MemberEntity entity);
/// If [entity] is a closure call method or closure signature method, the
/// original enclosing member is returned. Otherwise [entity] is returned.
///
/// A member and its nested closure share the underlying AST, we need to
/// ensure that locals are shared between them. We therefore store the
/// locals in the global locals map using the enclosing member as key.
MemberEntity getEnclosingMember(MemberEntity entity);
}
/// Enum used for identifying [ScopeInfo] subclasses in serialization.
enum ScopeInfoKind {
scopeInfo,
capturedScope,
capturedLoopScope,
closureRepresentationInfo,
}
/// Class that represents one level of scoping information, whether this scope
/// is a closure or not. This is specifically used to store information
/// about the usage of variables in try or sync blocks, because they need to be
/// boxed.
///
/// Variables that are used in a try must be treated as boxed because the
/// control flow can be non-linear. Also parameters to a `sync*` generator must
/// be boxed, because of the way we rewrite sync* functions. See also comments
/// in [ClosureClassMap.useLocal].
class ScopeInfo {
const ScopeInfo();
/// Deserializes a [ScopeInfo] object from [source].
factory ScopeInfo.readFromDataSource(DataSource source) {
ScopeInfoKind kind = source.readEnum(ScopeInfoKind.values);
switch (kind) {
case ScopeInfoKind.scopeInfo:
return new JsScopeInfo.readFromDataSource(source);
case ScopeInfoKind.capturedScope:
return new JsCapturedScope.readFromDataSource(source);
case ScopeInfoKind.capturedLoopScope:
return new JsCapturedLoopScope.readFromDataSource(source);
case ScopeInfoKind.closureRepresentationInfo:
return new JsClosureClassInfo.readFromDataSource(source);
}
throw new UnsupportedError('Unexpected ScopeInfoKind $kind');
}
/// Serializes this [ScopeInfo] to [sink].
void writeToDataSink(DataSink sink) {
throw new UnsupportedError('${runtimeType}.writeToDataSink');
}
/// Convenience reference pointer to the element representing `this`.
/// If this scope is not in an instance member, it will be null.
Local get thisLocal => null;
/// Returns true if this [variable] is used inside a `try` block or a `sync*`
/// generator (this is important to know because boxing/redirection needs to
/// happen for those local variables).
///
/// Variables that are used in a try must be treated as boxed because the
/// control flow can be non-linear.
///
/// Also parameters to a `sync*` generator must be boxed, because of the way
/// we rewrite sync* functions. See also comments in
/// [ClosureClassMap.useLocal].
bool localIsUsedInTryOrSync(KernelToLocalsMap localsMap, Local variable) =>
false;
/// Loop through each variable that has been defined in this scope, modified
/// anywhere (this scope or another scope) and used in another scope. Because
/// it is used in another scope, these variables need to be "boxed", creating
/// a thin wrapper around accesses to these variables so that accesses get
/// the correct updated value. The variables in localsUsedInTryOrSync may
/// be included in this set.
///
/// In the case of loops, this is the set of iteration variables (or any
/// variables declared in the for loop expression (`for (...here...)`) that
/// need to be boxed to snapshot their value.
void forEachBoxedVariable(
KernelToLocalsMap localsMap, f(Local local, FieldEntity field)) {}
/// True if [variable] has been mutated and is also used in another scope.
bool isBoxedVariable(KernelToLocalsMap localsMap, Local variable) => false;
}
/// Class representing the usage of a scope that has been captured in the
/// context of a closure.
class CapturedScope extends ScopeInfo {
const CapturedScope();
/// Deserializes a [CapturedScope] object from [source].
factory CapturedScope.readFromDataSource(DataSource source) {
ScopeInfoKind kind = source.readEnum(ScopeInfoKind.values);
switch (kind) {
case ScopeInfoKind.scopeInfo:
case ScopeInfoKind.closureRepresentationInfo:
throw new UnsupportedError('Unexpected CapturedScope kind $kind');
case ScopeInfoKind.capturedScope:
return new JsCapturedScope.readFromDataSource(source);
case ScopeInfoKind.capturedLoopScope:
return new JsCapturedLoopScope.readFromDataSource(source);
}
throw new UnsupportedError('Unexpected ScopeInfoKind $kind');
}
/// If true, this closure accesses a variable that was defined in an outside
/// scope and this variable gets modified at some point (sometimes we say that
/// variable has been "captured"). In this situation, access to this variable
/// is controlled via a wrapper (box) so that updates to this variable
/// are done in a way that is in line with Dart's closure rules.
bool get requiresContextBox => false;
/// Accessor to the local environment in which a particular closure node is
/// executed. This will encapsulate the value of any variables that have been
/// scoped into this context from outside. This is an accessor to the
/// contextBox that [requiresContextBox] is testing is required.
Local get contextBox => null;
}
/// Class that describes the actual mechanics of how values of variables
/// instantiated in a loop are captured inside closures in the loop body.
/// Unlike JS, the value of a declared loop iteration variable in any closure
/// is captured/snapshotted inside at each iteration point, as if we created a
/// new local variable for that value inside the loop. For example, for the
/// following loop:
///
/// var lst = [];
/// for (int i = 0; i < 5; i++) lst.add(()=>i);
/// var result = list.map((f) => f()).toList();
///
/// `result` will be [0, 1, 2, 3, 4], whereas were this JS code
/// the result would be [5, 5, 5, 5, 5]. Because of this difference we need to
/// create a closure for these sorts of loops to capture the variable's value at
/// each iteration, by boxing the iteration variable[s].
class CapturedLoopScope extends CapturedScope {
const CapturedLoopScope();
/// Deserializes a [CapturedLoopScope] object from [source].
factory CapturedLoopScope.readFromDataSource(DataSource source) {
ScopeInfoKind kind = source.readEnum(ScopeInfoKind.values);
switch (kind) {
case ScopeInfoKind.scopeInfo:
case ScopeInfoKind.closureRepresentationInfo:
case ScopeInfoKind.capturedScope:
throw new UnsupportedError('Unexpected CapturedLoopScope kind $kind');
case ScopeInfoKind.capturedLoopScope:
return new JsCapturedLoopScope.readFromDataSource(source);
}
throw new UnsupportedError('Unexpected ScopeInfoKind $kind');
}
/// True if this loop scope declares in the first part of the loop
/// `for (<here>;...;...)` any variables that need to be boxed.
bool get hasBoxedLoopVariables => false;
/// The set of iteration variables (or variables declared in the for loop
/// expression (`for (<here>; ... ; ...)`) that need to be boxed to snapshot
/// their value. These variables are also included in the set of
/// `forEachBoxedVariable` method. The distinction between these two sets is
/// in this example:
///
/// run(f) => f();
/// var a;
/// for (int i = 0; i < 3; i++) {
/// var b = 3;
/// a = () => b = i;
/// }
///
/// `i` would be a part of the boxedLoopVariables AND boxedVariables, but b
/// would only be a part of boxedVariables.
List<Local> getBoxedLoopVariables(KernelToLocalsMap localsMap) =>
const <Local>[];
}
/// Class that describes the actual mechanics of how the converted, rewritten
/// closure is implemented. For example, for the following closure (named foo
/// for convenience):
///
/// var foo = (x) => y + x;
///
/// We would produce the following class to control access to these variables in
/// the following way (modulo naming of variables, assuming that y is modified
/// elsewhere in its scope):
///
/// class FooClosure {
/// int y;
/// FooClosure(this.y);
/// call(x) => this.y + x;
/// }
///
/// and then to execute this closure, for example:
///
/// var foo = new FooClosure(1);
/// foo.call(2);
///
/// if `y` is modified elsewhere within its scope, accesses to y anywhere in the
/// code will be controlled via a box object.
///
/// Because in these examples `y` was declared in some other, outer scope, but
/// used in the inner scope of this closure, we say `y` is a "captured"
/// variable.
/// TODO(efortuna): Make interface simpler in subsequent refactorings.
class ClosureRepresentationInfo extends ScopeInfo {
const ClosureRepresentationInfo();
/// Deserializes a [ClosureRepresentationInfo] object from [source].
factory ClosureRepresentationInfo.readFromDataSource(DataSource source) {
ScopeInfoKind kind = source.readEnum(ScopeInfoKind.values);
switch (kind) {
case ScopeInfoKind.scopeInfo:
case ScopeInfoKind.capturedScope:
case ScopeInfoKind.capturedLoopScope:
throw new UnsupportedError(
'Unexpected ClosureRepresentationInfo kind $kind');
case ScopeInfoKind.closureRepresentationInfo:
return new JsClosureClassInfo.readFromDataSource(source);
}
throw new UnsupportedError('Unexpected ScopeInfoKind $kind');
}
/// The original local function before any translation.
///
/// Will be null for methods.
Local getClosureEntity(KernelToLocalsMap localsMap) => null;
/// The entity for the class used to represent the rewritten closure in the
/// emitted JavaScript.
///
/// Closures are rewritten in the form of classes that have fields to control
/// the redirection and editing of captured variables.
ClassEntity get closureClassEntity => null;
/// The function that implements the [local] function as a `call` method on
/// the closure class.
FunctionEntity get callMethod => null;
/// The signature method for [callMethod] if needed.
FunctionEntity get signatureMethod => null;
/// List of locals that this closure class has created corresponding field
/// entities for.
@deprecated
List<Local> getCreatedFieldEntities(KernelToLocalsMap localsMap) =>
const <Local>[];
/// As shown in the example in the comments at the top of this class, we
/// create fields in the closure class for each captured variable. This is an
/// accessor the [local] for which [field] was created.
/// Returns the [local] for which [field] was created.
Local getLocalForField(KernelToLocalsMap localsMap, FieldEntity field) {
failedAt(field, "No local for $field.");
return null;
}
/// Convenience pointer to the field entity representation in the closure
/// class of the element representing `this`.
FieldEntity get thisFieldEntity => null;
/// Loop through each variable that has been boxed in this closure class. Only
/// captured variables that are mutated need to be "boxed" (which basically
/// puts a thin layer between updates and reads to this variable to ensure
/// that every place that accesses it gets the correct updated value). This
/// includes looping over variables that were boxed from other scopes, not
/// strictly variables defined in this closure, unlike the behavior in
/// the superclass ScopeInfo.
@override
void forEachBoxedVariable(
KernelToLocalsMap localsMap, f(Local local, FieldEntity field)) {}
/// Loop through each free variable in this closure. Free variables are the
/// variables that have been captured *just* in this closure, not in nested
/// scopes.
void forEachFreeVariable(
KernelToLocalsMap localsMap, f(Local variable, FieldEntity field)) {}
// TODO(efortuna): Remove this method. The old system was using
// ClosureClassMaps for situations other than closure class maps, and that's
// just confusing.
bool get isClosure => false;
}
/// A local variable that contains the box object holding the [BoxFieldElement]
/// fields.
class BoxLocal extends Local {
final ClassEntity container;
BoxLocal(this.container);
@override
String get name => container.name;
@override
bool operator ==(other) {
return other is BoxLocal && other.container == container;
}
@override
int get hashCode => container.hashCode;
@override
String toString() => 'BoxLocal($name)';
}
/// A local variable used encode the direct (uncaptured) references to [this].
class ThisLocal extends Local {
final ClassEntity enclosingClass;
ThisLocal(this.enclosingClass);
@override
String get name => 'this';
@override
bool operator ==(other) {
return other is ThisLocal && other.enclosingClass == enclosingClass;
}
@override
int get hashCode => enclosingClass.hashCode;
}
/// A type variable as a local variable.
class TypeVariableLocal implements Local {
final TypeVariableEntity typeVariable;
TypeVariableLocal(this.typeVariable);
@override
String get name => typeVariable.name;
@override
int get hashCode => typeVariable.hashCode;
@override
bool operator ==(other) {
if (other is! TypeVariableLocal) return false;
return typeVariable == other.typeVariable;
}
@override
String toString() {
StringBuffer sb = new StringBuffer();
sb.write('type_variable_local(');
sb.write(typeVariable);
sb.write(')');
return sb.toString();
}
}
///
/// Move the below classes to a JS model eventually.
///
abstract class JSEntity implements MemberEntity {
String get declaredName;
}
abstract class PrivatelyNamedJSEntity implements JSEntity {
Entity get rootOfScope;
}
| 38.483627
| 80
| 0.720317
|
b8f95bb818dff3bf53789248a23bfea3974a62a6
| 328
|
py
|
Python
|
Exercise_8_12.py
|
kushrami/Python-Crash-Course-book-Excersice
|
7093181940a90d9f4bab5775ef56f57963450393
|
[
"Apache-2.0"
] | null | null | null |
Exercise_8_12.py
|
kushrami/Python-Crash-Course-book-Excersice
|
7093181940a90d9f4bab5775ef56f57963450393
|
[
"Apache-2.0"
] | null | null | null |
Exercise_8_12.py
|
kushrami/Python-Crash-Course-book-Excersice
|
7093181940a90d9f4bab5775ef56f57963450393
|
[
"Apache-2.0"
] | null | null | null |
#sandwiches:
def orderedsandwich(items):
list_of_items = []
for item in items:
list_of_items.append(item)
print("This is items you ordered in your sandwich:")
for item in list_of_items:
print(item)
orderedsandwich(['kela','aloo'])
orderedsandwich(['cheese','poteto'])
orderedsandwich(['uiyer'])
| 25.230769
| 56
| 0.682927
|
d7f483c141ad97baf69be9360a7b812a27970331
| 1,061
|
rb
|
Ruby
|
app/models/url.rb
|
mnutt/octo.cat
|
0c42c41aec18228c2044d4b489f75f5036898124
|
[
"Unlicense",
"MIT"
] | 2
|
2015-11-05T14:57:58.000Z
|
2019-04-16T09:05:07.000Z
|
app/models/url.rb
|
mnutt/octo.cat
|
0c42c41aec18228c2044d4b489f75f5036898124
|
[
"Unlicense",
"MIT"
] | null | null | null |
app/models/url.rb
|
mnutt/octo.cat
|
0c42c41aec18228c2044d4b489f75f5036898124
|
[
"Unlicense",
"MIT"
] | null | null | null |
require 'shortener'
class Url < ActiveRecord::Base
before_validation :check_for_repo
before_validation :set_short
def self.create_from_url(u)
u = normalize(u)
uri = URI::parse(u)
return unless uri.kind_of? URI::HTTP or uri.kind_of? URI::HTTPS
url = Url.where(:url => u).first
if url.nil?
url = self.create(:url => u)
end
url
end
def self.normalize(u)
# downcase
u.sub!(/^http/i, 'http')
# add http if it wasn't there
u = "http://#{u}" unless u =~ /^http/
# github is always https now, no need for an extra redirect
u.sub!(/^http:\/\/github.com/, 'https://github.com')
u
end
def set_short
last_record = Url.order('id desc').first
next_id = last_record.nil? ? 1 : last_record.id + 1
self.short = Shortener.encode(next_id)
end
def check_for_repo
self.is_repo = true if self.url =~ /^https:\/\/github.com\/[A-Za-z0-9\-\.]+\/[A-Za-z0-9\_\.]+\/?$/
end
def optimized_url
self.is_repo? ? self.url.sub(/^https:\/\/github.com/, '') : self.url
end
end
| 21.22
| 102
| 0.61263
|
d68bd61a2df4cc3cbe2cd79bc0e3b0a53c090e5c
| 8,839
|
cs
|
C#
|
src/Redstone/Core/Redstone.ServiceNode/ServiceNodeManager.cs
|
RedstonePlatform/Redstone
|
3384c7b73c2978b7eb4296890bd31ed286259fb2
|
[
"MIT"
] | 3
|
2018-12-14T00:07:55.000Z
|
2019-07-15T16:47:15.000Z
|
src/Redstone/Core/Redstone.ServiceNode/ServiceNodeManager.cs
|
spartacrypt/Redstone
|
3384c7b73c2978b7eb4296890bd31ed286259fb2
|
[
"MIT"
] | 12
|
2018-04-29T16:54:05.000Z
|
2018-09-25T15:36:09.000Z
|
src/Redstone/Core/Redstone.ServiceNode/ServiceNodeManager.cs
|
spartacrypt/Redstone
|
3384c7b73c2978b7eb4296890bd31ed286259fb2
|
[
"MIT"
] | 2
|
2018-04-26T07:59:17.000Z
|
2018-07-30T12:02:04.000Z
|
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging;
using NBitcoin;
using Redstone.ServiceNode.Events;
using Redstone.ServiceNode.Models;
using Redstone.ServiceNode.Utils;
using Stratis.Bitcoin.Configuration;
using Stratis.Bitcoin.Signals;
using Stratis.Bitcoin.Utilities;
namespace Redstone.ServiceNode
{
public interface IServiceNodeManager
{
/// <summary><c>true</c> in case current node is a registered service node.</summary>
bool IsServiceNode { get; }
/// <summary>
/// Starts the service node manager.
/// </summary>
void Start();
/// <summary>
/// Stops the service node manager.
/// <para>Internally it waits for async loops to complete before saving the wallets to disk.</para>
/// </summary>
void Stop();
/// <summary>Provides up to date list of service nodes.</summary>
/// <remarks>
/// Blocks that are not signed with private keys that correspond
/// to public keys from this list are considered to be invalid.
/// </remarks>
List<IServiceNode> GetServiceNodes();
IServiceNode GetByServerId(string serverId);
void AddServiceNode(IServiceNode serviceNodeMember);
void RemoveServiceNode(IServiceNode serviceNodeMember);
int SyncedHeight { get; set; }
uint256 SyncedBlockHash { get; set; }
}
public abstract class ServiceNodeManagerBase : IServiceNodeManager
{
/// <inheritdoc />
public bool IsServiceNode { get; private set; }
/// <inheritdoc />
public Key CurrentServiceNodeKey { get; private set; }
protected readonly IKeyValueRepository KeyValueRepo;
protected readonly ILogger Logger;
private readonly NodeSettings settings;
private readonly Network network;
private readonly ISignals signals;
/// <summary>Collection of all active service nodes.</summary>
/// <remarks>All access should be protected by <see cref="locker"/>.</remarks>
protected List<IServiceNode> ServiceNodes;
/// <summary>Protects access to <see cref="ServiceNodes"/>.</summary>
private readonly object locker;
protected ServiceNodeManagerBase(NodeSettings nodeSettings, Network network, ILoggerFactory loggerFactory, IKeyValueRepository keyValueRepo, ISignals signals)
{
this.settings = Guard.NotNull(nodeSettings, nameof(nodeSettings));
this.network = Guard.NotNull(network, nameof(network));
this.KeyValueRepo = Guard.NotNull(keyValueRepo, nameof(keyValueRepo));
this.signals = Guard.NotNull(signals, nameof(signals));
this.Logger = loggerFactory.CreateLogger(GetType().FullName);
this.locker = new object();
}
public virtual void Start()
{
LoadServiceNodes();
// TODO: what if load fails? Shouldn't we sync again
if (this.ServiceNodes == null)
{
this.ServiceNodes = new List<IServiceNode>();
SaveServiceNodes();
}
this.Logger.LogInformation("Network contains {0} service nodes. Their public keys are: {1}",
this.ServiceNodes.Count, Environment.NewLine + string.Join(Environment.NewLine, this.ServiceNodes));
// Load key.
Key key = new KeyTool(this.settings.DataFolder).LoadPrivateKey();
this.CurrentServiceNodeKey = key;
SetIsServiceNode();
if (this.CurrentServiceNodeKey == null)
{
this.Logger.LogTrace("(-)[NOT_SERVICE_NODE]");
return;
}
// Loaded key has to be a key for current service node.
if (this.ServiceNodes.All(x => x.EcdsaPubKey != this.CurrentServiceNodeKey.PubKey))
{
string message = "Key provided is not registered on the network!";
this.Logger.LogWarning(message);
}
this.Logger.LogInformation("ServiceNode key pair was successfully loaded. Your public key is: '{0}'.", this.CurrentServiceNodeKey.PubKey);
}
public virtual void Stop()
{
this.SaveServiceNodes();
}
private void SetIsServiceNode()
{
this.IsServiceNode = this.ServiceNodes.Any(x => x.EcdsaPubKey == this.CurrentServiceNodeKey?.PubKey);
}
/// <inheritdoc />
public List<IServiceNode> GetServiceNodes()
{
lock (this.locker)
{
return new List<IServiceNode>(this.ServiceNodes);
}
}
public IServiceNode GetByServerId(string serverId)
{
lock (this.locker)
{
return this.ServiceNodes.FirstOrDefault(sn => sn.ServerId == serverId);
}
}
protected void SetServiceNodes(List<IServiceNode> serviceNodesToSet)
{
lock (this.locker)
{
this.ServiceNodes = serviceNodesToSet;
}
}
public void AddServiceNode(IServiceNode serviceNode)
{
lock (this.locker)
{
if (this.ServiceNodes.Contains(serviceNode))
{
this.Logger.LogTrace("(-)[ALREADY_EXISTS]");
return;
}
// Remove any that have a matching collateral address
BitcoinAddress serviceNodeCollateralAddress = serviceNode.GetCollateralAddress(this.network);
var nodesWithMatchingPubKeys = this.ServiceNodes.Where(sn => sn.GetCollateralAddress(this.network) == serviceNodeCollateralAddress).ToList();
foreach (IServiceNode matchingNode in nodesWithMatchingPubKeys)
{
this.ServiceNodes.Remove(matchingNode);
}
// Add new one
this.ServiceNodes.Add(serviceNode);
SaveServiceNodes();
SetIsServiceNode();
this.Logger.LogInformation("Federation member '{0}' was added!", serviceNode);
// Publish events
foreach (IServiceNode node in nodesWithMatchingPubKeys)
{
this.signals.Publish(new ServiceNodeRemoved(serviceNode));
}
this.signals.Publish(new ServiceNodeAdded(serviceNode));
}
}
public void RemoveServiceNode(IServiceNode serviceNode)
{
lock (this.locker)
{
this.ServiceNodes.Remove(serviceNode);
SaveServiceNodes();
SetIsServiceNode();
this.Logger.LogInformation("Federation member '{0}' was removed!", serviceNode);
this.signals.Publish(new ServiceNodeRemoved(serviceNode));
}
}
public int SyncedHeight { get; set; }
public uint256 SyncedBlockHash { get; set; }
protected abstract void SaveServiceNodes();
/// <summary>Loads saved collection of service nodes from the database.</summary>
protected abstract void LoadServiceNodes();
}
public class ServiceNodeManager : ServiceNodeManagerBase
{
private const string SyncedHeightKey = "syncedheight";
private const string SyncedBlockHashKey = "syncedblockhash";
private const string ServiceNodesKey = "servicenodes";
public ServiceNodeManager(NodeSettings nodeSettings, Network network, ILoggerFactory loggerFactory, IKeyValueRepository keyValueRepo, ISignals signals)
: base(nodeSettings, network, loggerFactory, keyValueRepo, signals)
{
}
protected override void SaveServiceNodes()
{
this.KeyValueRepo.SaveValueJson(SyncedHeightKey, this.SyncedHeight);
this.KeyValueRepo.SaveValueJson(SyncedBlockHashKey, this.SyncedBlockHash);
this.KeyValueRepo.SaveValueJson(ServiceNodesKey, GetServiceNodes());
}
/// <inheritdoc />
protected override void LoadServiceNodes()
{
this.SyncedHeight = this.KeyValueRepo.LoadValueJson<int>(SyncedHeightKey);
this.SyncedBlockHash = this.KeyValueRepo.LoadValueJson<uint256>(SyncedBlockHashKey);
var loadedNodes = this.KeyValueRepo.LoadValueJson<List<Models.ServiceNode>>(ServiceNodesKey)?.ToList<IServiceNode>();
if (loadedNodes != null)
{
SetServiceNodes(loadedNodes);
}
if (this.ServiceNodes == null)
{
this.Logger.LogTrace("(-)[NOT_FOUND]:null");
}
}
}
}
| 34.799213
| 166
| 0.605046
|
46d6d445810ca2e9c7dfadd37d525bce446ba093
| 4,063
|
py
|
Python
|
codewars/tests/test_validate_sudoku.py
|
nelsonlove/coding-exercises
|
71081a9ecb17f4aa50b232a93624822f9eeeb37e
|
[
"MIT"
] | null | null | null |
codewars/tests/test_validate_sudoku.py
|
nelsonlove/coding-exercises
|
71081a9ecb17f4aa50b232a93624822f9eeeb37e
|
[
"MIT"
] | null | null | null |
codewars/tests/test_validate_sudoku.py
|
nelsonlove/coding-exercises
|
71081a9ecb17f4aa50b232a93624822f9eeeb37e
|
[
"MIT"
] | null | null | null |
from unittest import TestCase
from kata import validate_sudoku
class Test(TestCase):
def test_validate_sudoku(self):
self.assertEqual(validate_sudoku([[5, 3, 4, 6, 7, 8, 9, 1, 2],
[6, 7, 2, 1, 9, 5, 3, 4, 8],
[1, 9, 8, 3, 4, 2, 5, 6, 7],
[8, 5, 9, 7, 6, 1, 4, 2, 3],
[4, 2, 6, 8, 5, 3, 7, 9, 1],
[7, 1, 3, 9, 2, 4, 8, 5, 6],
[9, 6, 1, 5, 3, 7, 2, 8, 4],
[2, 8, 7, 4, 1, 9, 6, 3, 5],
[3, 4, 5, 2, 8, 6, 1, 7, 9]]), 'Finished!');
self.assertEqual(validate_sudoku([[5, 3, 4, 6, 7, 8, 9, 1, 2],
[6, 7, 2, 1, 9, 0, 3, 4, 9],
[1, 0, 0, 3, 4, 2, 5, 6, 0],
[8, 5, 9, 7, 6, 1, 0, 2, 0],
[4, 2, 6, 8, 5, 3, 7, 9, 1],
[7, 1, 3, 9, 2, 4, 8, 5, 6],
[9, 0, 1, 5, 3, 7, 2, 1, 4],
[2, 8, 7, 4, 1, 9, 6, 3, 5],
[3, 0, 0, 4, 8, 1, 1, 7, 9]]), 'Try again!');
self.assertEqual(validate_sudoku([[1, 3, 2, 5, 7, 9, 4, 6, 8]
, [4, 9, 8, 2, 6, 1, 3, 7, 5]
, [7, 5, 6, 3, 8, 4, 2, 1, 9]
, [6, 4, 3, 1, 5, 8, 7, 9, 2]
, [5, 2, 1, 7, 9, 3, 8, 4, 6]
, [9, 8, 7, 4, 2, 6, 5, 3, 1]
, [2, 1, 4, 9, 3, 5, 6, 8, 7]
, [3, 6, 5, 8, 1, 7, 9, 2, 4]
, [8, 7, 9, 6, 4, 2, 1, 5, 3]]), 'Finished!');
self.assertEqual(validate_sudoku([[1, 3, 2, 5, 7, 9, 4, 6, 8]
, [4, 9, 8, 2, 6, 1, 3, 7, 5]
, [7, 5, 6, 3, 8, 4, 2, 1, 9]
, [6, 4, 3, 1, 5, 8, 7, 9, 2]
, [5, 2, 1, 7, 9, 3, 8, 4, 6]
, [9, 8, 7, 4, 2, 6, 5, 3, 1]
, [2, 1, 4, 9, 3, 5, 6, 8, 7]
, [3, 6, 5, 8, 1, 7, 9, 2, 4]
, [8, 7, 9, 6, 4, 2, 1, 3, 5]]), 'Try again!');
self.assertEqual(validate_sudoku([[1, 3, 2, 5, 7, 9, 4, 6, 8]
, [4, 9, 8, 2, 6, 0, 3, 7, 5]
, [7, 0, 6, 3, 8, 0, 2, 1, 9]
, [6, 4, 3, 1, 5, 0, 7, 9, 2]
, [5, 2, 1, 7, 9, 0, 8, 4, 6]
, [9, 8, 0, 4, 2, 6, 5, 3, 1]
, [2, 1, 4, 9, 3, 5, 6, 8, 7]
, [3, 6, 0, 8, 1, 7, 9, 2, 4]
, [8, 7, 0, 6, 4, 2, 1, 3, 5]]), 'Try again!');
self.assertEqual(validate_sudoku([[1, 2, 3, 4, 5, 6, 7, 8, 9]
, [2, 3, 4, 5, 6, 7, 8, 9, 1]
, [3, 4, 5, 6, 7, 8, 9, 1, 2]
, [4, 5, 6, 7, 8, 9, 1, 2, 3]
, [5, 6, 7, 8, 9, 1, 2, 3, 4]
, [6, 7, 8, 9, 1, 2, 3, 4, 5]
, [7, 8, 9, 1, 2, 3, 4, 5, 6]
, [8, 9, 1, 2, 3, 4, 5, 6, 7]
, [9, 1, 2, 3, 4, 5, 6, 7, 8]]), 'Try again!');
| 60.641791
| 88
| 0.200098
|
1f543bcc3755dde506f00ba9c71e53b43e075d39
| 1,745
|
cs
|
C#
|
WebMvcNetCore/Controllers/VendasController.cs
|
Fernandsantana/WebMvcNetCore
|
7942a2f8450b4578101feb0a6a5929d9a5e2b4f3
|
[
"MIT"
] | null | null | null |
WebMvcNetCore/Controllers/VendasController.cs
|
Fernandsantana/WebMvcNetCore
|
7942a2f8450b4578101feb0a6a5929d9a5e2b4f3
|
[
"MIT"
] | null | null | null |
WebMvcNetCore/Controllers/VendasController.cs
|
Fernandsantana/WebMvcNetCore
|
7942a2f8450b4578101feb0a6a5929d9a5e2b4f3
|
[
"MIT"
] | null | null | null |
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebMvcNetCore.Serviços;
namespace WebMvcNetCore.Controllers
{
public class VendasController : Controller
{
private readonly ServicoVendas _servicoVendas;
public VendasController(ServicoVendas servicoVendas)
{
_servicoVendas = servicoVendas;
}
public IActionResult Index()
{
return View();
}
public async Task<IActionResult> SimpleSearch(DateTime? minDate, DateTime? maxDate)
{
if (!minDate.HasValue)
{
minDate = new DateTime(DateTime.Now.Year, 1, 1);
}
if(!maxDate.HasValue)
{
maxDate = DateTime.Now;
}
ViewData["minDate"] = minDate.Value.ToString("yyyy-MM-dd");
ViewData["maxDate"] = maxDate.Value.ToString("yyyy-MM-dd");
var result = await _servicoVendas.FindByDateAsync(minDate, maxDate);
return View(result);
}
public async Task<IActionResult> GroupingSearch(DateTime? minDate, DateTime? maxDate)
{
if (!minDate.HasValue)
{
minDate = new DateTime(DateTime.Now.Year, 1, 1);
}
if (!maxDate.HasValue)
{
maxDate = DateTime.Now;
}
ViewData["minDate"] = minDate.Value.ToString("yyyy-MM-dd");
ViewData["maxDate"] = maxDate.Value.ToString("yyyy-MM-dd");
var result = await _servicoVendas.FindByDateGroupingAsync(minDate, maxDate);
return View(result);
}
}
}
| 27.698413
| 93
| 0.570774
|
46bbebb0d9309b8110e638a3568019a0b3f23840
| 1,047
|
py
|
Python
|
main.py
|
edwardhuahan/csc110-project
|
42ccee47588960faa3013135a22489514eb1c629
|
[
"MIT"
] | 1
|
2022-02-20T01:21:24.000Z
|
2022-02-20T01:21:24.000Z
|
main.py
|
edwardhuahan/csc110-project
|
42ccee47588960faa3013135a22489514eb1c629
|
[
"MIT"
] | null | null | null |
main.py
|
edwardhuahan/csc110-project
|
42ccee47588960faa3013135a22489514eb1c629
|
[
"MIT"
] | null | null | null |
""" CSC110 Final Project
This file is Copyright (c) 2021 Edward Han, Zekun Liu, Arvin Gingoyon
"""
import analyzer
import graph_1
import graph_2
import graph_3
import reader
if __name__ == '__main__':
list_of_topics = ['vaccine', 'masks', 'quarantine', 'conspiracy', 'covid']
read_data = reader.read_tweet_data('test_data.csv')
# graph_1 processing
read_data_1 = analyzer.analyze_tweets(read_data)
a = graph_1.categorize(list_of_topics, read_data_1)
graph_1_data = graph_1.average_scores(a)
# graph_2 processing
scores = analyzer.analyze_sentiment(read_data)
clean = analyzer.clean_input(read_data)
roots = analyzer.split_into_stems(clean)
graph_2_data = analyzer.calc_word_emotions(scores, roots)
# graph_3 processing
read_data_3 = analyzer.analyze_tweets(read_data)
sorted_tweets = graph_3.sort_tweets_by_date(read_data_3)
graph_3_data = graph_3.average_scores(sorted_tweets)
graph_1.graph_1(graph_1_data)
graph_2.graph_2(graph_2_data)
graph_3.graph_3(graph_3_data)
| 29.914286
| 78
| 0.754537
|
8e2dbd54a348ae2c99796ea8eb1233939cb58646
| 7,784
|
rb
|
Ruby
|
gem/lib/textmate_grammar/pattern_variations/repeatable_pattern.rb
|
DoDoENT/cpp-textmate-grammar
|
f8c66603957ae3240ff828256d6d6d32e01913be
|
[
"MIT"
] | 1
|
2021-10-17T06:35:01.000Z
|
2021-10-17T06:35:01.000Z
|
gem/lib/textmate_grammar/pattern_variations/repeatable_pattern.rb
|
DoDoENT/cpp-textmate-grammar
|
f8c66603957ae3240ff828256d6d6d32e01913be
|
[
"MIT"
] | null | null | null |
gem/lib/textmate_grammar/pattern_variations/repeatable_pattern.rb
|
DoDoENT/cpp-textmate-grammar
|
f8c66603957ae3240ff828256d6d6d32e01913be
|
[
"MIT"
] | null | null | null |
# frozen_string_literal: true
require_relative "./base_pattern.rb"
#
# RepeatablePattern provides quantifiers for patterns
#
class RepeatablePattern < PatternBase
# @return [Integer,nil] the minimum amount that can be matched
attr_accessor :at_least
# @return [Integer,nil] the maximum amount that can be matched
attr_accessor :at_most
# (see PatternBase#initialize)
def initialize(*arguments)
super(*arguments)
@at_least = nil
@at_most = nil
process_quantifiers_from_arguments
end
#
# sets @at_least and @at_most based on arguments
#
# @return [void]
#
# @api private
#
def process_quantifiers_from_arguments
# this sets the @at_most and @at_least value based on the arguments
#
# Simplify the quantity down to just :at_least and :at_most
#
attributes_clone = @arguments.clone
# convert Enumerators to numbers
[:at_least, :at_most, :how_many_times?].each do |each|
if attributes_clone[each].is_a?(Enumerator)
attributes_clone[each] = attributes_clone[each].size
end
end
# canonize dont_back_track? and as_few_as_possible?
@arguments[:dont_back_track?] ||= @arguments[:possessive?]
@arguments[:as_few_as_possible?] ||= @arguments[:lazy?]
if @arguments[:greedy?]
@arguments[:dont_back_track?] = false
@arguments[:as_few_as_possible?] = false
end
# extract the data
at_least = attributes_clone[:at_least]
at_most = attributes_clone[:at_most]
how_many_times = attributes_clone[:how_many_times?]
# simplify to at_least and at_most
at_least = at_most = how_many_times if how_many_times.is_a?(Integer)
# check if quantifying is allowed
# check after everything else in case additional quantifying options
# are created in the future
if quantifying_allowed?
@at_least = at_least
@at_most = at_most
# if a quantifying value was set and quantifying is not allowed, raise an error
# telling the user that its not allowed
elsif !(at_most.nil? && at_least.nil?)
raise <<-HEREDOC.remove_indent
Inside of the #{name} pattern, there are some quantity arguments like:
:at_least
:at_most
or :how_many_times?
These are not allowed in this kind of #{do_get_to_s_name}) pattern
If you did this intentionally please wrap it inside of a Pattern.new()
ex: #{do_get_to_s_name} Pattern.new( *your_arguments* ) )
HEREDOC
end
return unless @arguments[:dont_back_track?] && @arguments[:as_few_as_possible?]
raise ":dont_back_track? and :as_few_as_possible? cannot both be provided"
end
#
# converts @at_least and @at_most into the appropriate quantifier
# this is a simple_quantifier because it does not include atomic-ness
#
# @return [String] the quantifier
#
def simple_quantifier
# Generate the ending based on :at_least and :at_most
# by default assume no quantifiers
quantifier = ""
# if there is no at_least, at_most, or how_many_times, then theres no quantifier
if @at_least.nil? and @at_most.nil?
quantifier = ""
# if there is a quantifier
else
# if there's no at_least, then assume at_least = 1
@at_least = 1 if @at_least.nil?
quantifier =
if @at_least == 1 and @at_most == 1
# no qualifier
""
elsif @at_least == 0 and @at_most == 1
# this is just a different way of "maybe"
"?"
elsif @at_least == 0 and @at_most.nil?
# this is just a different way of "zeroOrMoreOf"
"*"
elsif @at_least == 1 and @at_most.nil?
# this is just a different way of "oneOrMoreOf"
"+"
elsif @at_least == @at_most
# exactly N times
"{#{@at_least}}"
else
# if it is more complicated than that, just use a range
"{#{@at_least},#{@at_most}}"
end
end
# quantifiers can be made possessive without requiring atomic groups
quantifier += "+" if quantifier != "" && @arguments[:dont_back_track?] == true
quantifier += "?" if quantifier != "" && @arguments[:as_few_as_possible?] == true
quantifier
end
#
# Adds quantifiers to match
#
# @param [String, PatternBase] match the pattern to add a quantifier to
# @param [Array] groups group information, used for evaluating match
#
# @return [String] match with quantifiers applied
#
def add_quantifier_options_to(match, groups)
match = match.evaluate(groups) if match.is_a? PatternBase
quantifier = simple_quantifier
# check if there are quantifiers
if quantifier != ""
# if the match is not a single entity, then it needs to be wrapped
match = "(?:#{match})" unless string_single_entity?(match)
# add the quantified ending
match += quantifier
elsif @arguments[:dont_back_track?] == true
# make atomic, which allows arbitrary expression to be prevented from backtracking
match = "(?>#{match})"
end
if @arguments[:word_cannot_be_any_of]
word_pattern = @arguments[:word_cannot_be_any_of].map { |w| Regexp.escape w }.join "|"
match = "(?!\\b(?:#{word_pattern})\\b)#{match}"
end
match
end
# (see PatternBase#do_evaluate_self)
def do_evaluate_self(groups)
add_capture_group_if_needed(add_quantifier_options_to(@match, groups))
end
# controls weather @arguments[:at_most] et. al. set @at_most et. al.
# @note override when inheriting. Return false unless the subclass allow quantifying
# @return [Boolean] if quantifying is allowed
# @note the default implementation returns True
def quantifying_allowed?
true
end
#
# (see PatternBase#do_add_attributes)
#
def do_add_attributes(indent)
# rubocop:disable Metrics/LineLength
output = ""
# special #then arguments
if quantifying_allowed?
output += ",\n#{indent} at_least: " + @arguments[:at_least].to_s if @arguments[:at_least]
output += ",\n#{indent} at_most: " + @arguments[:at_most].to_s if @arguments[:at_most]
output += ",\n#{indent} how_many_times: " + @arguments[:how_many_times].to_s if @arguments[:how_many_times]
output += ",\n#{indent} word_cannot_be_any_of: " + @arguments[:word_cannot_be_any_of].to_s if @arguments[:word_cannot_be_any_of]
end
output += ",\n#{indent} dont_back_track?: " + @arguments[:dont_back_track?].to_s if @arguments[:dont_back_track?]
output
# rubocop:enable Metrics/LineLength
end
#
# Does this pattern potentially rematch any capture groups
#
# @note this is used by FixRepeatedTagAs to modify patterns
# The answer of true is a safe, but expensive to runtime, default
#
# @return [Boolean] True if this pattern potentially rematches capture groups
#
def self_capture_group_rematch
# N or more
return true if @at_most.nil? && !@at_least.nil?
# up to N
return true if !@at_most.nil? && @at_most > 1
false
end
end
| 38.156863
| 141
| 0.603674
|
0d337ff9bdf8d70beccfd6478e4c3fb1adeffbd4
| 581
|
cs
|
C#
|
src/Infrastructure/Multitenancy/TenantDbContext.cs
|
slingncrypto/dotnet-webapi-boilerplate
|
3a541f8a9bceb636071968ba5175f57f28446cac
|
[
"MIT"
] | 1,657
|
2021-08-20T17:09:08.000Z
|
2022-03-31T19:40:29.000Z
|
src/Infrastructure/Multitenancy/TenantDbContext.cs
|
slingncrypto/dotnet-webapi-boilerplate
|
3a541f8a9bceb636071968ba5175f57f28446cac
|
[
"MIT"
] | 208
|
2021-08-20T12:34:37.000Z
|
2022-03-30T18:58:05.000Z
|
src/Infrastructure/Multitenancy/TenantDbContext.cs
|
slingncrypto/dotnet-webapi-boilerplate
|
3a541f8a9bceb636071968ba5175f57f28446cac
|
[
"MIT"
] | 375
|
2021-08-29T08:03:35.000Z
|
2022-03-31T17:55:36.000Z
|
using Finbuckle.MultiTenant.Stores;
using FSH.WebApi.Infrastructure.Persistence.Configuration;
using Microsoft.EntityFrameworkCore;
namespace FSH.WebApi.Infrastructure.Multitenancy;
public class TenantDbContext : EFCoreStoreDbContext<FSHTenantInfo>
{
public TenantDbContext(DbContextOptions<TenantDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<FSHTenantInfo>().ToTable("Tenants", SchemaNames.MultiTenancy);
}
}
| 29.05
| 90
| 0.771084
|
147796501440eb230918045b2f28b41640ccaa63
| 1,498
|
tsx
|
TypeScript
|
src/components/auth/views/Checkboxes.tsx
|
apotdevin/thunderhub-next
|
61ab9b1e6c6bd0b159c8897ae713d712178797fe
|
[
"MIT"
] | null | null | null |
src/components/auth/views/Checkboxes.tsx
|
apotdevin/thunderhub-next
|
61ab9b1e6c6bd0b159c8897ae713d712178797fe
|
[
"MIT"
] | 3
|
2021-03-10T14:09:44.000Z
|
2021-09-02T09:33:47.000Z
|
src/components/auth/views/Checkboxes.tsx
|
apotdevin/thunderhub-next
|
61ab9b1e6c6bd0b159c8897ae713d712178797fe
|
[
"MIT"
] | null | null | null |
import React from 'react';
import { Checkbox } from '../../checkbox/Checkbox';
import { CheckboxText, StyledContainer, FixedWidth } from '../Auth.styled';
import { AlertCircle } from '../../generic/Icons';
import { fontColors } from '../../../styles/Themes';
import { ColorButton } from '../../buttons/colorButton/ColorButton';
type CheckboxProps = {
handleClick: () => void;
disabled: boolean;
checked: boolean;
onChange: (state: boolean) => void;
};
export const RiskCheckboxAndConfirm = ({
handleClick,
disabled,
checked,
onChange,
}: CheckboxProps) => (
<>
<Checkbox checked={checked} onChange={onChange}>
<CheckboxText>
I'm feeling reckless - I understand that Lightning, LND and ThunderHub
are under constant development and that there is always a risk of losing
funds.
</CheckboxText>
</Checkbox>
<ColorButton
disabled={disabled}
onClick={handleClick}
withMargin={'32px 0 0'}
fullWidth={true}
arrow={true}
>
Connect
</ColorButton>
<WarningBox />
</>
);
export const WarningBox = () => {
return (
<StyledContainer>
<FixedWidth>
<AlertCircle color={fontColors.grey7} />
</FixedWidth>
<CheckboxText>
Macaroons are handled by the ThunderHub server to connect to your LND
node but are never stored. Still, this involves a certain degree of
trust you must be aware of.
</CheckboxText>
</StyledContainer>
);
};
| 26.75
| 80
| 0.640187
|
3ac3b26cd315a295818480d13e693321399428ae
| 334
|
go
|
Go
|
cmd/example_interface.go
|
cnative/servicebuilder
|
11e92554e94f9743bbf32a63d81ec21480d84565
|
[
"Apache-2.0"
] | 25
|
2020-03-09T16:46:41.000Z
|
2021-12-09T08:01:16.000Z
|
cmd/example_interface.go
|
cnative/servicebuilder
|
11e92554e94f9743bbf32a63d81ec21480d84565
|
[
"Apache-2.0"
] | null | null | null |
cmd/example_interface.go
|
cnative/servicebuilder
|
11e92554e94f9743bbf32a63d81ec21480d84565
|
[
"Apache-2.0"
] | 5
|
2020-03-09T11:27:39.000Z
|
2022-03-27T09:45:08.000Z
|
package cmd
import (
"context"
"io"
)
//Store example interface
type Store interface {
Serve(ctx context.Context) error
io.Closer
Create(ctx context.Context, c *string) (*string, error)
Get(ctx context.Context, id string) (string, error)
Filter(ctx context.Context, filterReq string, opts ...io.Closer) ([]*string, error)
}
| 19.647059
| 84
| 0.718563
|
ef49f924291afec905629709e3f17d90ccb6b4f9
| 10,344
|
php
|
PHP
|
application/views/admin/simpananBMT/viewDaftarNasabah.php
|
dimasmahendra/koperasi
|
9862d1ab7dcdc2749dcdaf6086cf9a8b8a4b2a93
|
[
"MIT"
] | null | null | null |
application/views/admin/simpananBMT/viewDaftarNasabah.php
|
dimasmahendra/koperasi
|
9862d1ab7dcdc2749dcdaf6086cf9a8b8a4b2a93
|
[
"MIT"
] | null | null | null |
application/views/admin/simpananBMT/viewDaftarNasabah.php
|
dimasmahendra/koperasi
|
9862d1ab7dcdc2749dcdaf6086cf9a8b8a4b2a93
|
[
"MIT"
] | null | null | null |
<link href="<?= base_url('asset_admin/css/jquery.dataTables.min.css') ?>" rel="stylesheet">
<link href="<?= base_url('asset_admin/css/select.dataTables.css') ?>" rel="stylesheet">
<script src="<?= base_url('asset_admin/js/jquery-2.2.0.min.js') ?>" rel="stylesheet"></script>
<script src="<?= base_url('asset_admin/js/jquery.dataTables.min.js') ?>" rel="stylesheet"></script>
<script src="<?= base_url('asset_admin/js/dataTables.bootstrap.min.js') ?>" rel="stylesheet"></script>
<script src="<?= base_url('asset_admin/js/dataTables.select.js') ?>" rel="stylesheet"></script>
<script src="<?= base_url('asset_admin/js/autoNumeric-1.9.41.js') ?>" rel="stylesheet"></script>
<script src="<?= base_url('asset_admin/js/autoNumeric-1.8.0-sample.js') ?>" rel="stylesheet"></script>
<style>
/*
Max width before this PARTICULAR table gets nasty
This query will take effect for any screen smaller than 760px
and also iPads specifically.
*/
@media
only screen and (max-width: 768px) {
body {
margin-top:27px;
}
/* Force table to not be like tables anymore */
#tabelDaftarNasabah table, #tabelDaftarNasabah thead, #tabelDaftarNasabah tbody, #tabelDaftarNasabah th, #tabelDaftarNasabah td, #tabelDaftarNasabah tr {
display: block;
}
/* Hide table headers (but not display: none;, for accessibility) */
#tabelDaftarNasabah thead tr {
position: absolute;
top: -9999px;
left: -9999px;
}
#tabelDaftarNasabah tr { border: 3px solid #ccc; }
#tabelDaftarNasabah td {
/* Behave like a "row" */
border: none;
border-bottom: 1px solid #eee;
position: relative;
padding-left: 50%;
}
#tabelDaftarNasabah td:before {
/* Now like a table header */
position: absolute;
/* Top/left values mimic padding */
top: 6px;
left: 6px;
width: 45%;
padding-right: 10px;
white-space: nowrap;
}
/*
Label the data
*/
#tabelDaftarNasabah td:nth-of-type(1):before { content: "No"; text-align: left;}
#tabelDaftarNasabah td:nth-of-type(2):before { content: "Username"; text-align: left;}
#tabelDaftarNasabah td:nth-of-type(3):before { content: "Nama"; text-align: left;}
#tabelDaftarNasabah td:nth-of-type(4):before { content: "Email"; text-align: left;}
#tabelDaftarNasabah td:nth-of-type(5):before { content: "Telepon"; text-align: left;}
#tabelDaftarNasabah td:nth-of-type(6):before { content: "Akses Admin"; text-align: left;}
#tabelDaftarNasabah td:nth-of-type(7):before { content: "Foto"; text-align: left;}
#tabelDaftarNasabah td:nth-of-type(8):before { content: "Status"; text-align: left;}
#tabelDaftarNasabah td:nth-child(1) { text-align: right;}
#tabelDaftarNasabah td:nth-child(2) { text-align: right;}
#tabelDaftarNasabah td:nth-child(3) { text-align: right;}
#tabelDaftarNasabah td:nth-child(4) { text-align: right;}
#tabelDaftarNasabah td:nth-child(5) { text-align: right;}
#tabelDaftarNasabah td:nth-child(6) { text-align: right;}
#tabelDaftarNasabah td:nth-child(7) { text-align: right;}
#tabelDaftarNasabah td:nth-child(8) { text-align: right;}
}
}
</style>
<div class="modal fade" id="ambilSimpanan" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header" style="background-color: #203864;">
<button type="button" class="close" data-dismiss="modal" style="color:white;">×</button>
<h4 class="modal-title" style="color:white;">Pengambilan Simpanan Syariah</h4>
</div>
<form name="form1" id="form1" class="form-horizontal" enctype="multipart/form-data" method="POST" style="margin-top: 0px; margin-bottom: 0px; margin-left:15px" action="<?php echo base_url(); ?>SimpananNasabah/ambilSimpananSyariah">
<div class="modal-body edit-content">
<input type="hidden" id="id" name="id" value="">
<div class="box-body">
<div class="form-group">
<label class="control-label col-sm-3" >Penerima</label>
<div class="col-md-7">
<input type="text" id="penerima" name="penerima" class="form-control" required>
</div>
</div>
</div>
<div class="box-body">
<div class="form-group">
<label class="control-label col-sm-3" >No. Bukti</label>
<div class="col-md-7">
<input type="text" id="nobukti" name="nobukti" class="form-control" required>
</div>
</div>
</div>
<div class="box-body">
<div class="form-group">
<label class="control-label col-sm-3" >Token</label>
<div class="col-md-7">
<input type="text" id="token" name="token" class="form-control" required>
</div>
</div>
</div>
<div class="box-body">
<div class="form-group">
<label class="control-label col-sm-3" >Reference Number SSP</label>
<div class="col-md-7">
<input type="text" id="refNumberSSP" name="refNumberSSP" class="form-control" required>
</div>
</div>
</div>
<div class="box-body">
<div class="form-group">
<label class="control-label col-sm-3" >Jumlah</label>
<div class="col-md-7">
<input type="text" id="jumlah" name="jumlah" class="form-control formatRupiah" data-a-sign="Rp " data-a-dec="," data-a-sep="." required>
</div>
</div>
</div>
<div class="box-body">
<div class="form-group">
<label class="control-label col-sm-3" >Metode</label>
<div class="col-md-7">
<select name="metode" class="form-control" id="metode" required>
<option value="">- Pilih Metode -</option>
<option value="Cash">Cash</option>
<option value="SSP">SSP</option>
</select>
</div>
</div>
</div>
<div class="modal-footer">
<button href="#" id="etombolSimpan" type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="col-sm-9 col-sm-offset-3 col-lg-10 col-lg-offset-2 main">
</br>
<!-- Tabel Inputan Admin -->
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">Daftar Nasabah Simpanan BMT
<a class="btn-sm btn-primary" href ="<?= base_url('SimpananNasabah/index') ?>">Tambah Simpanan</a>
</div>
<div class="panel-body">
<?php if($this->session->flashdata('message')){?>
<div class="alert bg-success" role="alert">
<svg class="glyph stroked checkmark"><use xlink:href="#stroked-checkmark"></use></svg>
<?php echo $this->session->flashdata('message')?>
</div><?php } ?>
<?php if($this->session->flashdata('error')){?>
<div class="alert bg-danger" role="alert">
<svg class="glyph stroked cancel"><use xlink:href="#stroked-cancel"></use></svg>
<?php echo $this->session->flashdata('error')?>
</div><?php } ?>
<!-- <table class="table table-bordered"> -->
<table id="tabelDaftarNasabah" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>No</th>
<th>Anggota</th>
<th>Produk Simpanan</th>
<th>No. Rekening</th>
<th>Saldo</th>
<th>Tanggal Ambil</th>
<th style="width: 14%">Aksi</th>
</tr>
</thead>
<tbody>
<?php
$no = 1;
foreach ($result['data'] as $row)
{ ?>
<tr>
<td><?php echo $no;$no++; ?></td>
<td><?php echo $row['anggotakoperasi']['nama']; ?></td>
<td><?php echo $row['tabunganproduk']['namaprogram']; ?></td>
<td><?php echo $row['rekening']; ?></td>
<td><?php echo "Rp ".number_format ($row['saldo'], 2, ',', '.');?></td>
<td><?php echo $row['diambilpada']; ?></td>
<td>
<a class="btn-sm btn-primary" href ="<?= base_url('SimpananNasabah/daftarLihatMutasiSimpanan')?>/<?php echo $row['id']?>">
Lihat Mutasi</a>
<!-- <a href ="#" class="edit" data-toggle="modal" data-target="#ambilSimpanan" data-indikator="<?php echo $row['id']; ?>"><button class="btn btn-success btn-xs">Ambil</button></a>
<a class="btn-sm btn-danger" href ="<?= base_url('SimpananNasabah/hapusNasabah') ?>/<?php echo $row['id']?>" onclick="return confirm('Apakah Anda yakin ingin menghapus nasabah ini?');">
Hapus</a> -->
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
</div><!--/.row-->
</div>
<script type="text/javascript">
$(document).ready(function() {
var table = $('#tabelDaftarNasabah').DataTable();
$('#tabelDaftarNasabah tbody').on( 'click', 'tr', function () {
if ( $(this).hasClass('selected') ) {
$(this).removeClass('selected');
}
else {
table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
} );
$('#hapus').click( function () {
table.row('.selected').remove().draw( false );
} );
} );
</script>
<script>
$('.edit').click(function(){
var id = $(this).data('indikator');
if (id) {
$('#id').val(id);
}
else{
alert('Data tidak ditemukan !!!');
}
});
</script>
| 40.724409
| 237
| 0.531323
|
d7ed2a9bef81adaf846700b7cf9aa3ef492c3aad
| 413
|
rb
|
Ruby
|
lib/buffer.rb
|
chetabahana/buffer-ruby
|
eb88e4872f3755e75b09c1f9094bb7338c54439b
|
[
"MIT"
] | 40
|
2015-01-03T10:22:23.000Z
|
2021-06-03T18:46:36.000Z
|
lib/buffer.rb
|
chetabahana/buffer-ruby
|
eb88e4872f3755e75b09c1f9094bb7338c54439b
|
[
"MIT"
] | 4
|
2015-04-05T04:30:27.000Z
|
2018-12-23T21:07:56.000Z
|
lib/buffer.rb
|
chetabahana/buffer-ruby
|
eb88e4872f3755e75b09c1f9094bb7338c54439b
|
[
"MIT"
] | 15
|
2015-04-04T19:40:53.000Z
|
2022-03-04T13:58:48.000Z
|
require 'faraday'
require 'faraday_middleware'
require 'json'
require 'hashie/mash'
require 'addressable/uri'
require 'environs'
require 'buffer/version'
require 'buffer/core'
require 'buffer/user'
require 'buffer/profile'
require 'buffer/update'
require 'buffer/link'
require 'buffer/error'
require 'buffer/encode'
require 'buffer/datastructure'
require 'buffer/info'
require 'buffer/client'
module Buffer
end
| 18.772727
| 30
| 0.791768
|
1e7a11a10e11f3ad7b5bf1f7de9a50382ca0482b
| 848
|
dart
|
Dart
|
lib/app/providers/active_contacts_provider.dart
|
SatYu26/Flutter-Training-App
|
3ef9545235ef95e3c164c4bc195e7da21de64ea6
|
[
"MIT"
] | 3
|
2020-12-15T07:31:46.000Z
|
2021-07-03T12:57:48.000Z
|
lib/app/providers/active_contacts_provider.dart
|
SatYu26/Flutter-Training-App
|
3ef9545235ef95e3c164c4bc195e7da21de64ea6
|
[
"MIT"
] | null | null | null |
lib/app/providers/active_contacts_provider.dart
|
SatYu26/Flutter-Training-App
|
3ef9545235ef95e3c164c4bc195e7da21de64ea6
|
[
"MIT"
] | null | null | null |
import 'package:flutter/cupertino.dart';
class Actives {
final String id;
final String image;
final int totalSteps;
Actives({
@required this.id,
@required this.image,
@required this.totalSteps
});
}
class ActiveContactsProvider with ChangeNotifier {
List<Actives> _activeContact = [
Actives(
id: 'a1',
image: 'assets/images/person5.png',
totalSteps: 5000,
),
Actives(
id: 'a2',
image: 'assets/images/person6.png',
totalSteps: 5000,
),
Actives(
id: 'a3',
image: 'assets/images/person7.png',
totalSteps: 5000,
),
Actives(
id: 'a4',
image: 'assets/images/person8.png',
totalSteps: 5000,
),
];
List<Actives> get activeContact {
return [..._activeContact];
}
void addcontact() {
notifyListeners();
}
}
| 18.042553
| 50
| 0.596698
|
0a8fd80a73e3d2d1a2c8c965c1b0ff5635433504
| 500
|
cs
|
C#
|
Askmethat.Aspnet.JsonLocalizer.Shared/Localizer/Modes/ILocalizationModeGenerator.cs
|
ErikApption/Askmethat-Aspnet-JsonLocalizer
|
025a0c183ca28568ea42e22784bd99b34395ad4d
|
[
"MIT"
] | 84
|
2018-04-03T15:00:36.000Z
|
2022-03-26T04:16:09.000Z
|
Askmethat.Aspnet.JsonLocalizer.Shared/Localizer/Modes/ILocalizationModeGenerator.cs
|
ErikApption/Askmethat-Aspnet-JsonLocalizer
|
025a0c183ca28568ea42e22784bd99b34395ad4d
|
[
"MIT"
] | 78
|
2017-10-30T15:10:00.000Z
|
2022-03-26T04:14:20.000Z
|
Askmethat.Aspnet.JsonLocalizer.Shared/Localizer/Modes/ILocalizationModeGenerator.cs
|
ErikApption/Askmethat-Aspnet-JsonLocalizer
|
025a0c183ca28568ea42e22784bd99b34395ad4d
|
[
"MIT"
] | 34
|
2018-06-12T23:49:47.000Z
|
2021-12-09T06:39:24.000Z
|
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using Askmethat.Aspnet.JsonLocalizer.Format;
using Askmethat.Aspnet.JsonLocalizer.JsonOptions;
namespace Askmethat.Aspnet.JsonLocalizer.Localizer.Modes
{
internal interface ILocalizationModeGenerator
{
ConcurrentDictionary<string, LocalizatedFormat> ConstructLocalization(
IEnumerable<string> myFiles, CultureInfo currentCulture, JsonLocalizationOptions options);
}
}
| 33.333333
| 102
| 0.81
|
89def64e6966789d007cdfcc830965f0bcd78d04
| 3,697
|
dart
|
Dart
|
lib/src/state/mouseover_data.dart
|
scadnano-test-define-env/scadnano
|
9675e861d09a5671ea43ac9f55fdec026c71cf10
|
[
"MIT"
] | 13
|
2020-07-17T04:19:29.000Z
|
2021-09-23T07:53:34.000Z
|
lib/src/state/mouseover_data.dart
|
scadnano-test-define-env/scadnano
|
9675e861d09a5671ea43ac9f55fdec026c71cf10
|
[
"MIT"
] | 442
|
2020-01-24T07:56:19.000Z
|
2022-03-29T09:47:48.000Z
|
lib/src/state/mouseover_data.dart
|
scadnano-test-define-env/scadnano
|
9675e861d09a5671ea43ac9f55fdec026c71cf10
|
[
"MIT"
] | 14
|
2020-05-28T04:39:15.000Z
|
2022-01-29T23:38:54.000Z
|
import 'package:built_value/built_value.dart';
import 'package:built_value/serializer.dart';
import 'package:color/color.dart';
import '../serializers.dart';
import 'design.dart';
import 'helix.dart';
import 'domain.dart';
import 'strand.dart';
import 'substrand.dart';
import '../constants.dart' as constants;
part 'mouseover_data.g.dart';
abstract class MouseoverParams
with BuiltJsonSerializable
implements Built<MouseoverParams, MouseoverParamsBuilder> {
int get helix_idx;
int get offset;
bool get forward;
@memoized
int get hashCode;
/************************ begin BuiltValue boilerplate ************************/
factory MouseoverParams(int helix_idx, int offset, bool forward) => MouseoverParams.from((b) => b
..helix_idx = helix_idx
..offset = offset
..forward = forward);
factory MouseoverParams.from([void Function(MouseoverParamsBuilder) updates]) = _$MouseoverParams;
MouseoverParams._();
static Serializer<MouseoverParams> get serializer => _$mouseoverParamsSerializer;
}
abstract class MouseoverData
with BuiltJsonSerializable
implements Built<MouseoverData, MouseoverDataBuilder> {
Helix get helix;
int get offset;
Color get color_forward;
Color get color_reverse;
double get roll_forward;
double get minor_groove_angle;
@nullable
Domain get domain;
@memoized
int get hashCode;
/// Converts from raw mouseover data (helix, offset, forward) to data user wants to see in the footer (substrand)
static List<MouseoverData> from_params(Design design, Iterable<MouseoverParams> params) {
Domain domain_in_direction = null;
List<MouseoverData> mouseover_datas_builder = [];
for (var param in params) {
int helix_idx = param.helix_idx;
int offset = param.offset;
bool forward = param.forward;
Color color_forward = constants.color_forward_rotation_arrow_no_strand;
Color color_reverse = constants.color_forward_rotation_arrow_no_strand;
Helix helix = design.helices[helix_idx];
double roll_forward = design.helix_rotation_forward(helix.idx, offset);
int num_domains_found = 0;
for (Domain domain in design.domains_on_helix(helix_idx)) {
if (domain.contains_offset(offset)) {
if (domain.forward == forward) {
domain_in_direction = domain;
}
num_domains_found++;
Strand strand = design.substrand_to_strand[domain];
if (domain.forward) {
color_forward = strand.color;
} else {
color_reverse = strand.color;
}
}
if (num_domains_found >= 2) {
break;
}
}
double minor_groove_angle = design.geometry.minor_groove_angle;
mouseover_datas_builder.add(MouseoverData(helix, offset, domain_in_direction, color_forward,
color_reverse, roll_forward, minor_groove_angle));
}
return mouseover_datas_builder;
}
/************************ begin BuiltValue boilerplate ************************/
factory MouseoverData(Helix helix, int offset, Domain domain, Color color_forward, Color color_reverse,
double roll_forward, double minor_groove_angle) =>
MouseoverData.from((b) => b
..helix.replace(helix)
..domain = domain?.toBuilder()
..offset = offset
..color_forward = color_forward
..color_reverse = color_reverse
..roll_forward = roll_forward
..minor_groove_angle = minor_groove_angle);
factory MouseoverData.from([void Function(MouseoverDataBuilder) updates]) = _$MouseoverData;
MouseoverData._();
static Serializer<MouseoverData> get serializer => _$mouseoverDataSerializer;
}
| 31.87069
| 115
| 0.687314
|
46fc92dae62430d1057d28a22adcb41f4ec23f44
| 1,712
|
py
|
Python
|
brown/core/multi_staff_object.py
|
craigvear/school_improv_bot
|
a7efafb145ab7a07fc708204e6806d641e1b0ed4
|
[
"MIT"
] | null | null | null |
brown/core/multi_staff_object.py
|
craigvear/school_improv_bot
|
a7efafb145ab7a07fc708204e6806d641e1b0ed4
|
[
"MIT"
] | null | null | null |
brown/core/multi_staff_object.py
|
craigvear/school_improv_bot
|
a7efafb145ab7a07fc708204e6806d641e1b0ed4
|
[
"MIT"
] | null | null | null |
from brown.core.graphic_object import GraphicObject
class MultiStaffObject:
"""An object which spans several staves.
This is a Mixin class, meant to be combined with GraphicObject classes.
`MultiStaffObject`s must have their visually highest staff as their parent.
If an class is both a `MultiStaffObject` and a `StaffObject`,
the parent staff should be the visually highest staff listed in
`self.staves`.
"""
def __init__(self, staves):
"""
Args:
staves (set(Staff)): The set of Staff objects this belongs to.
"""
self.staves = staves
######## PUBLIC PROPERTIES ########
@property
def visually_sorted_staves(self):
"""list[Staff]: self.staves as a list in visually descending order"""
return sorted(list(self.staves),
key=lambda s: s.y)
@property
def highest_staff(self):
"""Staff: The visually highest staff in self.staves"""
return self.visually_sorted_staves[0]
@property
def lowest_staff(self):
"""Staff: The visually lowest staff in self.staves"""
return self.visually_sorted_staves[-1]
@property
def vertical_span(self):
"""StaffUnit: The vertical distance covered by the staves
The distance from the top of `self.highest_staff` to the bottom
of `self.lowest_staff`, in `self.highest_staff.unit` StaffUnits.
"""
return self.highest_staff.unit(GraphicObject.map_between_items(
self.highest_staff,
self.lowest_staff).y
+ self.lowest_staff.height)
| 32.301887
| 79
| 0.61215
|
c9c340ef978a6cf38b8c865ddfa237b26be39981
| 808
|
ts
|
TypeScript
|
SuiteCommerce Advanced/SC_21.1_Live/Commons/BackboneExtras/JavaScript/Backbone.CachedCollection.ts
|
Rudracool/MotherCareBackend-
|
1e38dd4c839929b026b8565739fcc7879a9b79c3
|
[
"MIT"
] | null | null | null |
SuiteCommerce Advanced/SC_21.1_Live/Commons/BackboneExtras/JavaScript/Backbone.CachedCollection.ts
|
Rudracool/MotherCareBackend-
|
1e38dd4c839929b026b8565739fcc7879a9b79c3
|
[
"MIT"
] | null | null | null |
SuiteCommerce Advanced/SC_21.1_Live/Commons/BackboneExtras/JavaScript/Backbone.CachedCollection.ts
|
Rudracool/MotherCareBackend-
|
1e38dd4c839929b026b8565739fcc7879a9b79c3
|
[
"MIT"
] | null | null | null |
/*
© 2020 NetSuite Inc.
User may not copy, modify, distribute, or re-bundle or otherwise make available this code;
provided, however, if you are an authorized user with a NetSuite account or log-in, you
may use this code subject to the terms that govern your access and use.
*/
/// <amd-module name="Backbone.CachedCollection"/>
// It's just an extension of the original Backbone.Collection but it uses the Backbone.cachedSync
import Backbone = require('../../../Commons/Utilities/JavaScript/backbone.custom');
import BackboneCachedSync = require('./Backbone.CachedSync');
Backbone.CachedCollection = Backbone.Collection.extend({
sync: BackboneCachedSync.cachedSync,
addToCache: BackboneCachedSync.addToCache,
isCached: BackboneCachedSync.isCached
});
export = Backbone.CachedCollection;
| 38.47619
| 97
| 0.768564
|
9a29220ee54f529c18d505381b95254db00716d6
| 2,541
|
swift
|
Swift
|
Sources/App/Models/AppInfo.swift
|
kikohz/firapp
|
46972d798e264f199569cc4d75d78c35b3bcc6a8
|
[
"MIT"
] | null | null | null |
Sources/App/Models/AppInfo.swift
|
kikohz/firapp
|
46972d798e264f199569cc4d75d78c35b3bcc6a8
|
[
"MIT"
] | null | null | null |
Sources/App/Models/AppInfo.swift
|
kikohz/firapp
|
46972d798e264f199569cc4d75d78c35b3bcc6a8
|
[
"MIT"
] | null | null | null |
//
// File.swift
//
//
// Created by Bllgo on 2021/9/24.
//
import Foundation
import Vapor
import Fluent
extension FieldKey {
static var name:Self{"name"}
static var desc:Self{"desc"}
static var screenshot:Self{"screenshot"}
static var filePath:Self{"filePath"}
static var platform:Self{"platform"}
static var icon:Self{"icon"}
static var bundleId:Self{"bundleId"}
static var bid:Self{"bid"}
static var plistPath:Self{"plistPath"}
}
final class AppInfo: Model, Content {
static let schema = "appinfo"
@ID(key: .id)
var id: UUID?
@Field(key: .name)
var name:String
@Field(key: .desc)
var desc:String
@Field(key: .screenshot)
var screenshot:String
@Field(key: .filePath)
var filePath:String?
@Field(key: .platform)
var platform:String
@Field(key: .icon)
var icon:String
@Field(key: .bundleId)
var bundleId:String
@Field(key: .bid)
var bid:String
@Field(key: .plistPath)
var plistPath:String?
init() {}
init(
id:UUID? = nil ,
name:String,
desc:String,
screenshot:String,
filePath:String = "",
plistPath:String = "",
platform:String,
icon:String,
bundleId:String = "",
bid:String = "") {
self.id = id
self.name = name
self.desc = desc
self.screenshot = screenshot
self.filePath = filePath
self.bundleId = bundleId
self.bid = bid
self.plistPath = plistPath
}
}
extension AppInfo {
func create(_ input:AppInfpCreateObject) {
name = input.name
desc = input.desc
screenshot = input.scteenshot ?? ""
platform = input.platform
icon = "https://objectstorage.ap-seoul-1.oraclecloud.com/n/cno3iavztv8w/b/mybox/o/appicon.png" //预留字段,后续接续安装包获取到
bundleId = input.bundleId
bid = bundleId.toBase64()
}
}
//api
struct AppInfpCreateObject:Codable {
let name:String
let desc:String
let scteenshot:String?
let platform:String
let bundleId:String
}
//通过用户信息查找用户用到模型
struct AppFindObject:Content {
// var id: String
var appid: String?
}
//通过bid查找应用信息
//struct AppFindBid:Content {
// var bid: String?
//}
struct AppFileObject:Codable {
var filePath: String?
var infoPlistPath:String?
}
struct AppDeleteObj:Codable {
var appid:UUID?
}
extension AppInfpCreateObject: Content {}
| 21.175
| 124
| 0.600945
|
38d408d68f9907174f0c3ec0df8196bcf9dc662e
| 676
|
asm
|
Assembly
|
data/pokemon/base_stats/moltres.asm
|
Karkino/KarkCrystal16
|
945dde0354016f9357e9d3798312cc6efa52ff7a
|
[
"blessing"
] | null | null | null |
data/pokemon/base_stats/moltres.asm
|
Karkino/KarkCrystal16
|
945dde0354016f9357e9d3798312cc6efa52ff7a
|
[
"blessing"
] | null | null | null |
data/pokemon/base_stats/moltres.asm
|
Karkino/KarkCrystal16
|
945dde0354016f9357e9d3798312cc6efa52ff7a
|
[
"blessing"
] | null | null | null |
db 0 ; species ID placeholder
db 90, 100, 90, 90, 125, 85
; hp atk def spd sat sdf
db FIRE, FLYING ; type
db 3 ; catch rate
db 217 ; base exp
db NO_ITEM, NO_ITEM ; items
db GENDER_UNKNOWN ; gender ratio
db 100 ; unknown 1
db 80 ; step cycles to hatch
db 5 ; unknown 2
INCBIN "gfx/pokemon/moltres/front.dimensions"
db 0, 0, 0, 0 ; padding
db GROWTH_SLOW ; growth rate
dn EGG_NONE, EGG_NONE ; egg groups
; tm/hm learnset
tmhm CURSE, ROAR, TOXIC, ROCK_SMASH, SUNNY_DAY, SNORE, HYPER_BEAM, PROTECT, RAIN_DANCE, RETURN, FEATHERDANCE, DOUBLE_TEAM, SWAGGER, SLEEP_TALK, SANDSTORM, FIRE_BLAST, SWIFT, PURSUIT, REST, STEEL_WING, FLY, FLAMETHROWER
; end
| 30.727273
| 219
| 0.710059
|
21cd1656aa292c2f7262c11acd0688b7661c3559
| 361
|
js
|
JavaScript
|
dist/js/chunk-2d0baeab.1ea0d9a4.js
|
hxj2221/Security-Information
|
249335339d34ff188e2556047946e6f5cf9c777d
|
[
"MIT"
] | null | null | null |
dist/js/chunk-2d0baeab.1ea0d9a4.js
|
hxj2221/Security-Information
|
249335339d34ff188e2556047946e6f5cf9c777d
|
[
"MIT"
] | 1
|
2021-02-06T23:49:23.000Z
|
2021-02-06T23:49:23.000Z
|
dist/js/chunk-2d0baeab.1ea0d9a4.js
|
hxj2221/Security-Information
|
249335339d34ff188e2556047946e6f5cf9c777d
|
[
"MIT"
] | 1
|
2020-12-22T02:14:52.000Z
|
2020-12-22T02:14:52.000Z
|
(window["webpackJsonp"]=window["webpackJsonp"]||[]).push([["chunk-2d0baeab"],{"38f6":function(n,e,t){"use strict";t.r(e);var o=function(){var n=this,e=n.$createElement,t=n._self._c||e;return t("div")},a=[],c={components:{},props:{},data:function(){return{}},methods:{}},r=c,s=t("2877"),u=Object(s["a"])(r,o,a,!1,null,"f4216898",null);e["default"]=u.exports}}]);
| 361
| 361
| 0.637119
|
ff676ac5125896a3cd98ca2a8bbb44d8a045d193
| 3,723
|
py
|
Python
|
main.py
|
kala51773/py
|
dca23193f74a17a8c3cf9907be172a030592c05a
|
[
"MIT"
] | null | null | null |
main.py
|
kala51773/py
|
dca23193f74a17a8c3cf9907be172a030592c05a
|
[
"MIT"
] | null | null | null |
main.py
|
kala51773/py
|
dca23193f74a17a8c3cf9907be172a030592c05a
|
[
"MIT"
] | null | null | null |
#-*- coding:utf-8 -*-
import random
import time
import json
import requests
import re
class TiebaSpider:
def __init__(self,name):
self.Encoding = 'gbk'
self.name =name
self.url_temp='https://search.51job.com/list/170200%252C170300,000000,0000,00,9,99,'+name+',2,{}.html?lang=c&postchannel=0000&workyear=99&cotype=99°reefrom=99&jobterm=99&companysize=99&ord_field=0&dibiaoid=0&line=&welfare='
self.heards={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36 Edg/98.0.1108.62'}
self.config={'last':1}
self.file=open('config.conf','r')
# print(self.config)
self.config['last'] =json.loads(self.file.read())['last']
print(self.config)
def __del__(self):
print("拜~")
self.file.close()
def get_url_list(self,num=2):
return [self.url_temp.format(i) for i in range(self.config['last'],683)]
def parse_url(self,url):
response = requests.get(url,headers=self.heards)
return response.content.decode('gbk')
def save(self,html,num):
file_path = '{}-第{}页.json'.format(self.name,num)
with open(file_path,"w",encoding=self.Encoding) as f:
f.write(html)
def useRegex(self, input):
pattern = re.compile("^(window.__SEARCH_RESULT__) = .*$",re.M)
x = pattern.search(input)
list = [i for i in x.group()]
return "".join(list).replace('window.__SEARCH_RESULT__ = ','').replace("</script>","")
def run(self):
url_list = self.get_url_list()
flag = 0
for i in url_list:
print(i)
try:
html = self.parse_url(i)
data=self.useRegex(html)
JSON = json.loads(data)
self.config['last']+=1
job_list = JSON['engine_jds']
job_count = JSON['jobid_count']
print(job_list)
if flag == 0:
print(job_count)
flag = 1
page_num = url_list.index(i) + 1
self.save(json.dumps(job_list), page_num)
time.sleep(random.randint(10, 20))
except AttributeError:
print("触发反爬机制")
self.file.close()
self.file = open('config.conf','w')
self.file.write(json.dumps(self.config))
self.file.close()
exit()
a = TiebaSpider("java")
a.run()
# url='https://search.51job.com/list/170200%252c170300,000000,0000,00,9,99,java,2,2.html?lang=c&postchannel=0000&workyear=99&cotype=99°reefrom=99&jobterm=99&companysize=99&ord_field=0&dibiaoid=0&line=&welfare='
# r=requests.get(url)
# print(r.content.decode('gbk'))
# input='"engine_jds":[{"type":"engine_jds","jt":"0_0","tags":[],"ad_track":"","jobid":"82332481","coid":"2720339","effect":"1","is_special_job":"","job_href":"https:\/\/jobs.51job.com\/erqiqu\/82332481.html?s=sou_sou_soulb&t=0_0","job_name":"诚聘 Java中、高级软件工程师","job_title":"诚聘 Java中、高级软件工程师","company_href":"https:\/\/jobs.51job.com\/all\/co2720339.html","company_name":"云计划软件科技(上海)有限公司","providesalary_text":"0.7-1万\/月","workarea":"170202","workarea_text":"郑州-二七区","updatedate":"03-04","iscommunicate":"","companytype_text":"合资","degreefrom":"5","workyear":"4","issuedate":"2022-03-04 18:22:17","isFromXyz":"","isIntern":"","jobwelf":"免费班车 专业培训 定期体检 年终奖金 五险 补充医疗保险 员工旅游","jobwelf_list":["免费班车","专业培训","定期体检","年终奖金","五险","补充医疗保险","员工旅游"],"isdiffcity":"","attribute_text":["郑州-二七区","2年经验","大专","招8人"],"companysize_text":"150-500人","companyind_text":"计算机软件","adid":""},xxx]'
# x=useRegex(input)
# print("".join(list))
| 46.5375
| 872
| 0.601128
|
cab8d036398914e18926a47b109744dab93f63cc
| 318
|
cs
|
C#
|
Its.Log.Monitoring/IApplyToApplication.cs
|
ckurt/Its.Monitoring
|
23fe4f88ac884c4693405cf6f57f948da2baeaba
|
[
"MIT"
] | null | null | null |
Its.Log.Monitoring/IApplyToApplication.cs
|
ckurt/Its.Monitoring
|
23fe4f88ac884c4693405cf6f57f948da2baeaba
|
[
"MIT"
] | null | null | null |
Its.Log.Monitoring/IApplyToApplication.cs
|
ckurt/Its.Monitoring
|
23fe4f88ac884c4693405cf6f57f948da2baeaba
|
[
"MIT"
] | null | null | null |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Its.Log.Monitoring
{
public interface IApplyToApplication : IMonitoringTest
{
bool AppliesToApplication(string application);
}
}
| 31.8
| 101
| 0.72956
|
f4492bd5f18eeac19fbfec034f6b904d42ae9440
| 365
|
ts
|
TypeScript
|
frontend/src/API/authAPI.ts
|
DMikhailiets/chirpstack
|
90243f894545a0d6066138fb01df79bc2904ca48
|
[
"MIT"
] | null | null | null |
frontend/src/API/authAPI.ts
|
DMikhailiets/chirpstack
|
90243f894545a0d6066138fb01df79bc2904ca48
|
[
"MIT"
] | null | null | null |
frontend/src/API/authAPI.ts
|
DMikhailiets/chirpstack
|
90243f894545a0d6066138fb01df79bc2904ca48
|
[
"MIT"
] | null | null | null |
import Notification from '../components/Notification';
import { default as axios } from '../core/axios';
import errorHandler from './utils/errorHandler';
export const authAPI = {
authUser: async (authData: any) => {
try {
return await axios.post('/api/chirpLogin', authData)
} catch (err) {
return errorHandler (err)
}
}
}
export default authAPI
| 26.071429
| 55
| 0.687671
|
2390b5212059e923596355009b1eef40decd03af
| 1,498
|
js
|
JavaScript
|
client/src/components/tools/platform-icon/index.js
|
AlfiyaRF/cloud-pipeline
|
532c02a7e88928f42b28be87545aab93db404df5
|
[
"Apache-2.0"
] | 126
|
2019-03-22T19:40:38.000Z
|
2022-02-16T13:01:44.000Z
|
client/src/components/tools/platform-icon/index.js
|
AlfiyaRF/cloud-pipeline
|
532c02a7e88928f42b28be87545aab93db404df5
|
[
"Apache-2.0"
] | 1,189
|
2019-03-25T10:39:27.000Z
|
2022-03-31T12:50:33.000Z
|
client/src/components/tools/platform-icon/index.js
|
AlfiyaRF/cloud-pipeline
|
532c02a7e88928f42b28be87545aab93db404df5
|
[
"Apache-2.0"
] | 62
|
2019-03-22T22:09:49.000Z
|
2022-03-08T12:05:56.000Z
|
/*
* Copyright 2017-2021 EPAM Systems, Inc. (https://www.epam.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from 'react';
import PropTypes from 'prop-types';
import WindowsIcon from './windows-icon';
import LinuxIcon from './linux-icon';
import CentosIcon from './centos-icon';
import UbuntuIcon from './ubuntu-icon';
function PlatformIcon ({className, platform, style}) {
if (/^windows$/i.test(platform)) {
return (<WindowsIcon className={className} style={style} />);
}
if (/^linux/i.test(platform)) {
return (<LinuxIcon className={className} style={style} />);
}
if (/^centos/i.test(platform)) {
return (<CentosIcon className={className} style={style} />);
}
if (/^ubuntu/i.test(platform)) {
return (<UbuntuIcon className={className} style={style} />);
}
return null;
}
PlatformIcon.propTypes = {
className: PropTypes.string,
platform: PropTypes.string,
style: PropTypes.object
};
export default PlatformIcon;
| 31.87234
| 76
| 0.704272
|
a3bfe58a41f9f9d5cb11a3cfb8b72b872a0842e8
| 2,872
|
java
|
Java
|
src/main/java/com/dbal/jdbc/builders/schema/Table.java
|
MontealegreLuis/dbal-jdbc
|
6838fe94a8c87d310269a544c5221fc0c1761f94
|
[
"MIT"
] | 1
|
2018-08-17T13:12:22.000Z
|
2018-08-17T13:12:22.000Z
|
src/main/java/com/dbal/jdbc/builders/schema/Table.java
|
MontealegreLuis/dbal-jdbc
|
6838fe94a8c87d310269a544c5221fc0c1761f94
|
[
"MIT"
] | null | null | null |
src/main/java/com/dbal/jdbc/builders/schema/Table.java
|
MontealegreLuis/dbal-jdbc
|
6838fe94a8c87d310269a544c5221fc0c1761f94
|
[
"MIT"
] | 1
|
2018-08-17T13:30:05.000Z
|
2018-08-17T13:30:05.000Z
|
/*
* This source file is subject to the license that is bundled with this package in the file LICENSE.
*/
package com.dbal.jdbc.builders.schema;
import com.dbal.jdbc.builders.HasSQLRepresentation;
import java.util.ArrayList;
import java.util.List;
public class Table implements HasSQLRepresentation {
private final String name;
private List<Column> columns;
private PrimaryKey primaryKey;
private List<ForeignKey> foreignKeys;
private boolean ifNotExists = false;
Table(String name) {
this.name = name;
columns = new ArrayList<>();
foreignKeys = new ArrayList<>();
}
public Column string(String name) {
return string(name, 256);
}
public Column string(String name, int length) {
StringColumn column = new StringColumn(name, length);
columns.add(column);
return column;
}
public IntColumn integer(String name) {
IntColumn column = new IntColumn(name);
columns.add(column);
return column;
}
public IntColumn increments(String name) {
Column id = new IntColumn(name)
.autoIncrement()
.unsigned()
.makeRequired()
;
primaryKey = new PrimaryKey(id);
columns.add(id);
return (IntColumn) id;
}
public ForeignKey foreign(Column column) {
ForeignKey foreignKey = new ForeignKey(column);
foreignKeys.add(foreignKey);
return foreignKey;
}
public PrimaryKey primary(Column... columns) {
primaryKey = PrimaryKey.composed(columns);
return primaryKey;
}
public Table ifNotExists() {
ifNotExists = true;
return this;
}
@Override
public String toSQL() {
assertPrimaryKeyIsPresent();
return String.format(
"CREATE TABLE %s %s (%s %s %s) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8;",
ifNotExistsSQL(),
name,
columnDefinitions(),
primaryKey.toSQL(),
foreignKeysSQL()
).replaceAll("( )+", " ");
}
private String ifNotExistsSQL() {
return ifNotExists ? "IF NOT EXISTS" : "";
}
private void assertPrimaryKeyIsPresent() {
if (primaryKey == null) {
throw new IllegalStateException("Cannot create table without a primary key");
}
}
private String foreignKeysSQL() {
StringBuilder sql = new StringBuilder();
foreignKeys.forEach(
foreignKey -> sql.append(", ").append(foreignKey.toSQL())
);
return sql.toString();
}
private String columnDefinitions() {
StringBuilder definition = new StringBuilder();
columns.forEach(
column -> definition.append(column.toSQL()).append(", ")
);
return definition.toString().trim();
}
}
| 26.841121
| 100
| 0.604109
|