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
5e704db09526553a3c37d574aeea11c839c5337d
1,649
asm
Assembly
Transynther/x86/_processed/NONE/_xt_/i9-9900K_12_0xca_notsx.log_16_1678.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
9
2020-08-13T19:41:58.000Z
2022-03-30T12:22:51.000Z
Transynther/x86/_processed/NONE/_xt_/i9-9900K_12_0xca_notsx.log_16_1678.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
1
2021-04-29T06:29:35.000Z
2021-05-13T21:02:30.000Z
Transynther/x86/_processed/NONE/_xt_/i9-9900K_12_0xca_notsx.log_16_1678.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
3
2020-07-14T17:07:07.000Z
2022-03-21T01:12:22.000Z
.global s_prepare_buffers s_prepare_buffers: ret .global s_faulty_load s_faulty_load: push %r10 push %r12 push %r14 push %r8 push %rbx push %rcx push %rdi push %rsi // Store lea addresses_WT+0x11d1d, %r10 nop nop nop xor %rcx, %rcx mov $0x5152535455565758, %r12 movq %r12, %xmm4 movups %xmm4, (%r10) nop nop nop nop lfence // REPMOV lea addresses_D+0xe4fd, %rsi lea addresses_RW+0x5475, %rdi nop nop nop nop and $158, %r8 mov $24, %rcx rep movsl nop nop and $31426, %r14 // Store lea addresses_WT+0x178e9, %rcx nop nop nop nop sub %r14, %r14 mov $0x5152535455565758, %r8 movq %r8, %xmm1 vmovups %ymm1, (%rcx) nop nop nop nop nop add %r10, %r10 // Faulty Load lea addresses_normal+0x1ea1d, %rbx nop xor $57830, %rcx mov (%rbx), %r8d lea oracles, %rbx and $0xff, %r8 shlq $12, %r8 mov (%rbx,%r8,1), %r8 pop %rsi pop %rdi pop %rcx pop %rbx pop %r8 pop %r14 pop %r12 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_normal', 'NT': True, 'AVXalign': False, 'size': 32, 'congruent': 0}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WT', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 8}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 2, 'type': 'addresses_D'}, 'dst': {'same': False, 'congruent': 3, 'type': 'addresses_RW'}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WT', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 0}} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_normal', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 0}} <gen_prepare_buffer> {'34': 16} 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 */
17.542553
141
0.650697
7f193374ddd36818daef929ce48cd2ec693791b0
4,110
rs
Rust
src/quantile_generator/random.rs
sitegui/fast-quantiles
543fa5504ebe543276084669e6edebbf9653932c
[ "MIT" ]
null
null
null
src/quantile_generator/random.rs
sitegui/fast-quantiles
543fa5504ebe543276084669e6edebbf9653932c
[ "MIT" ]
1
2019-11-14T21:25:59.000Z
2019-11-14T21:25:59.000Z
src/quantile_generator/random.rs
sitegui/fast-quantiles
543fa5504ebe543276084669e6edebbf9653932c
[ "MIT" ]
null
null
null
use super::QuantileGenerator; use crate::quantile_to_rank; use ordered_float::NotNan; use rand::{Rng, SeedableRng}; use rand_pcg::Pcg64; use std::iter::{ExactSizeIterator, FusedIterator}; /// An iterator that will generate random values /// /// The values are drawn randomly from the range `(x-1, x+1)` and returned in a random order. pub struct RandomGenerator { remaining_lesser: usize, remaining: usize, // excluding the target value value: f64, published_value: bool, rng: Pcg64, } impl RandomGenerator { /// Create a new iterator with the given parameters /// /// # Example /// ``` /// use fast_quantiles::quantile_generator::*; /// use ordered_float::NotNan; /// let it = RandomGenerator::new(0.5, 17., 3, 22); /// let values: Vec<_> = it.map(|f| f.into_inner()).collect(); /// assert_eq!(values, vec![16.520451506320533, 17.352059635936964, 17.0]); /// ``` pub fn new(quantile: f64, value: f64, num: usize, seed: u64) -> RandomGenerator { assert!(num > 0); let remaining_lesser = quantile_to_rank(quantile, num as u64) as usize - 1; RandomGenerator { remaining_lesser, remaining: num - 1, value, published_value: false, rng: Pcg64::seed_from_u64(seed), } } } impl RandomGenerator { fn next_random(&mut self) -> f64 { self.rng.gen() } fn next_non_zero_random(&mut self) -> f64 { let mut r = self.next_random(); while r == 0. { r = self.next_random(); } r } } impl Iterator for RandomGenerator { type Item = NotNan<f64>; fn next(&mut self) -> Option<Self::Item> { // At each step, we'll select whether to generate a greater, lesser or the target value // This decision is random, however with weights proportional to the number // of remaining draws // Check end of cursor if self.remaining == 0 && self.published_value { return None; } // Publish target value if !self.published_value { let remaining_ratio = 1. / (self.remaining + 1) as f64; if self.next_random() < remaining_ratio { self.published_value = true; return Some(NotNan::from(self.value)); } } // Publish other values let ratio = self.remaining_lesser as f64 / self.remaining as f64; self.remaining -= 1; if self.next_random() >= ratio { // Greater or equal Some(NotNan::from(self.value + self.next_random())) } else { // Lesser self.remaining_lesser -= 1; Some(NotNan::from(self.value - self.next_non_zero_random())) } } fn size_hint(&self) -> (usize, Option<usize>) { let mut size = self.remaining; if !self.published_value { size += 1; } return (size, Some(size)); } } impl FusedIterator for RandomGenerator {} impl ExactSizeIterator for RandomGenerator {} #[cfg(test)] mod test { use super::*; #[test] fn respect_seed() { fn check(seed: u64, expected_values: Vec<f64>) { let values: Vec<_> = RandomGenerator::new(0.5, 17., 7, seed) .map(NotNan::into_inner) .collect(); assert_eq!(values, expected_values); } check( 1, vec![ 16.886098289795832, 17.475850141634222, 17.0, 16.448791316457317, 17.04676166514965, 17.708530834207153, 16.61197782022746, ], ); check( 2, vec![ 17.0, 16.723992847202776, 17.473140469528996, 17.890264969958412, 16.184033271866923, 16.300485594323114, 17.527720330285856, ], ); } } impl QuantileGenerator for RandomGenerator {}
27.959184
95
0.546715
2523cb4eb58ac06695a820170d58dac6a83a9342
1,386
dart
Dart
test/src/git_test.dart
casvanluijtelaar/faker.dart
162ddc130d9278a315e9446f7986dff44600d3d8
[ "MIT" ]
21
2021-07-12T02:29:11.000Z
2022-03-17T04:01:43.000Z
test/src/git_test.dart
casvanluijtelaar/faker.dart
162ddc130d9278a315e9446f7986dff44600d3d8
[ "MIT" ]
3
2022-01-25T11:17:00.000Z
2022-03-31T08:32:23.000Z
test/src/git_test.dart
casvanluijtelaar/faker.dart
162ddc130d9278a315e9446f7986dff44600d3d8
[ "MIT" ]
3
2021-12-17T16:01:45.000Z
2022-03-29T23:07:24.000Z
import 'package:faker_dart/faker_dart.dart'; import 'package:faker_dart/src/datatype.dart'; import 'package:faker_dart/src/git.dart'; import 'package:faker_dart/src/hacker.dart'; import 'package:test/test.dart'; import 'package:mocktail/mocktail.dart'; import '../test_utils.dart'; class MockHacker extends Mock implements Hacker {} void main() { late Faker faker; late Git git; setUp(() { faker = MockFaker(); git = Git(faker); }); test('return a correctly formatted branch name', () { final hacker = MockHacker(); when(() => faker.hacker).thenReturn(hacker); when(hacker.noun).thenReturn('noun'); when(hacker.verb).thenReturn('verb'); expect(git.branch(), 'noun-verb'); }); test('return a correctly formatted commit entry', () { final dt = DataType(); when(() => faker.datatype).thenReturn(dt); final result = git.commitEntry(); final resultWithMerge = git.commitEntry(merge: true); expect(result.contains('Author'), isTrue); expect(resultWithMerge.contains('Merge'), isTrue); }); test('return a vallid commit message', () { expect(git.commitMessage(), '{{hacker.verb}} {{hacker.adjective}} {{hacker.noun}}'); }); test('return a full commit sha', () { expect(git.commitSha().length, 40); }); test('return a short commit sha', () { expect(git.shortSha().length, 7); }); }
25.2
64
0.65368
fb693a7dbe32080e8af1cf3ca018d2418c9ee51c
6,070
java
Java
src/main/java/org/torproject/collector/index/CreateIndexJson.java
voicexhtml/collector
770f55cf82a1281e5081de7731adc9e36a916622
[ "Apache-2.0" ]
null
null
null
src/main/java/org/torproject/collector/index/CreateIndexJson.java
voicexhtml/collector
770f55cf82a1281e5081de7731adc9e36a916622
[ "Apache-2.0" ]
null
null
null
src/main/java/org/torproject/collector/index/CreateIndexJson.java
voicexhtml/collector
770f55cf82a1281e5081de7731adc9e36a916622
[ "Apache-2.0" ]
null
null
null
/* Copyright 2015--2018 The Tor Project * See LICENSE for licensing information */ package org.torproject.collector.index; import org.torproject.collector.conf.Configuration; import org.torproject.collector.conf.ConfigurationException; import org.torproject.collector.conf.Key; import org.torproject.collector.cron.CollecTorMain; import org.torproject.descriptor.index.DirectoryNode; import org.torproject.descriptor.index.FileNode; import org.torproject.descriptor.index.IndexNode; import org.torproject.descriptor.internal.FileType; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStreamWriter; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Locale; import java.util.Properties; import java.util.SortedSet; import java.util.TimeZone; import java.util.TreeSet; /* Create a fresh index.json containing all directories and files in the * archive/ and recent/ directories. * * Note that if this ever takes longer than a few seconds, we'll have to * cache index parts of directories or files that haven't changed. * Example: if we parse include cryptographic hashes or @type information, * we'll likely have to do that. */ public class CreateIndexJson extends CollecTorMain { private static final Logger logger = LoggerFactory.getLogger(CreateIndexJson.class); private static File indexJsonFile; private static String basePath; private static File[] indexedDirectories; private static final String dateTimePattern = "yyyy-MM-dd HH:mm"; private static final Locale dateTimeLocale = Locale.US; private static final TimeZone dateTimezone = TimeZone.getTimeZone("UTC"); private static String buildRevision = null; /** Creates indexes of directories containing archived and recent * descriptors and write index files to disk. */ public CreateIndexJson(Configuration conf) { super(conf); Properties buildProperties = new Properties(); try (InputStream is = getClass().getClassLoader() .getResourceAsStream("collector.buildrevision.properties")) { buildProperties.load(is); buildRevision = buildProperties.getProperty("collector.build.revision", null); } catch (Exception ex) { // This doesn't hamper the index creation: only log a warning. logger.warn("No build revision available.", ex); buildRevision = null; } } @Override public String module() { return "updateindex"; } @Override protected String syncMarker() { return "IndexJson"; } @Override protected void startProcessing() throws ConfigurationException { try { indexJsonFile = new File(config.getPath(Key.IndexPath).toFile(), "index.json"); basePath = config.getProperty(Key.InstanceBaseUrl.name()); indexedDirectories = new File[] { config.getPath(Key.ArchivePath).toFile(), config.getPath(Key.RecentPath).toFile() }; writeIndex(indexDirectories()); } catch (Exception e) { logger.error("Cannot run index creation: " + e.getMessage(), e); throw new RuntimeException(e); } } private static DateFormat dateTimeFormat; static { dateTimeFormat = new SimpleDateFormat(dateTimePattern, dateTimeLocale); dateTimeFormat.setLenient(false); dateTimeFormat.setTimeZone(dateTimezone); } private IndexNode indexDirectories() { SortedSet<DirectoryNode> directoryNodes = new TreeSet<>(); logger.trace("indexing: " + indexedDirectories[0] + " " + indexedDirectories[1]); for (File directory : indexedDirectories) { if (directory.exists() && directory.isDirectory()) { DirectoryNode dn = indexDirectory(directory); if (null != dn) { directoryNodes.add(dn); } } } return new IndexNode(dateTimeFormat.format( System.currentTimeMillis()), buildRevision, basePath, null, directoryNodes); } private DirectoryNode indexDirectory(File directory) { SortedSet<FileNode> fileNodes = new TreeSet<>(); SortedSet<DirectoryNode> directoryNodes = new TreeSet<>(); logger.trace("indexing: " + directory); File[] fileList = directory.listFiles(); if (null == fileList) { logger.warn("Indexing dubious directory: " + directory); return null; } for (File fileOrDirectory : fileList) { if (fileOrDirectory.getName().startsWith(".") || fileOrDirectory.getName().endsWith(".tmp")) { continue; } if (fileOrDirectory.isFile()) { fileNodes.add(indexFile(fileOrDirectory)); } else { DirectoryNode dn = indexDirectory(fileOrDirectory); if (null != dn) { directoryNodes.add(dn); } } } DirectoryNode directoryNode = new DirectoryNode( directory.getName(), fileNodes.isEmpty() ? null : fileNodes, directoryNodes.isEmpty() ? null : directoryNodes); return directoryNode; } private FileNode indexFile(File file) { FileNode fileNode = new FileNode(file.getName(), file.length(), dateTimeFormat.format(file.lastModified())); return fileNode; } private void writeIndex(IndexNode indexNode) throws Exception { indexJsonFile.getParentFile().mkdirs(); Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation() .create(); String indexNodeString = gson.toJson(indexNode); for (String filename : new String[] {indexJsonFile.toString(), indexJsonFile + ".gz", indexJsonFile + ".xz", indexJsonFile + ".bz2"}) { FileType type = FileType.valueOf( filename.substring(filename.lastIndexOf(".") + 1).toUpperCase()); try (BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(type.outputStream( new FileOutputStream(filename))))) { bufferedWriter.write(indexNodeString); } } } }
33.169399
80
0.701812
2f274822eb0f95a8ab79cebe9eb67f0e7594d7b0
4,203
php
PHP
storage/framework/views/15e8d0a1b89395d300f17b01ad155211a76ffce6.php
markgeek95/Dashpayroll
c3fc41c3f716c6cb61566a1d0ff9ac242e99dee4
[ "MIT" ]
null
null
null
storage/framework/views/15e8d0a1b89395d300f17b01ad155211a76ffce6.php
markgeek95/Dashpayroll
c3fc41c3f716c6cb61566a1d0ff9ac242e99dee4
[ "MIT" ]
null
null
null
storage/framework/views/15e8d0a1b89395d300f17b01ad155211a76ffce6.php
markgeek95/Dashpayroll
c3fc41c3f716c6cb61566a1d0ff9ac242e99dee4
[ "MIT" ]
null
null
null
<?php $__env->startComponent('partials.header'); ?> <?php $__env->slot('title'); ?> Annual Tax <?php $__env->endSlot(); ?> <?php $__env->startSection('pagestyle'); ?> <?php $__env->stopSection(); ?> <?php $__env->startSection('template'); ?> <?php $__env->startComponent('partials.template'); ?> <?php $__env->startSection('content'); ?> <div id="page-wrapper"> <?php echo $__env->make('maintenance.tax_tables.annual_tax_new', \Illuminate\Support\Arr::except(get_defined_vars(), array('__data', '__path')))->render(); ?> <?php echo $__env->make('maintenance.tax_tables.annual_tax_edit', \Illuminate\Support\Arr::except(get_defined_vars(), array('__data', '__path')))->render(); ?> <?php echo $__env->make('partials.delete_modal', \Illuminate\Support\Arr::except(get_defined_vars(), array('__data', '__path')))->render(); ?> <div class="tab"> <?php echo $__env->make('maintenance.tax_tables.tabs', \Illuminate\Support\Arr::except(get_defined_vars(), array('__data', '__path')))->render(); ?> </div> <div class="container-fluid ml-17 mr-10 mt-40"> <div class = "row"> <div class="col-sm-12 mb-20 paneltable"> <div class="alert alert-primary"> <strong>Tax Table</strong> </div> <div class="table-responsive"> <div class = "col-xs-6 button-groups"> <button class="btn btn-success btn-sm" v-on:click="annual_tax_new"> <i class="glyphicon glyphicon-plus" aria-hidden="true"></i> <strong> New </strong> </button> </div> <table class="table table-bordered mt-50" id="AnnualTable"> <thead> <tr class="thead-primary"> <th>Range</th> <th>Fixed Rate</th> <th>Tax Rate</th> <th>Action</th> </tr> </thead> <tbody> <?php if(!$data->isEmpty()): ?> <?php $__currentLoopData = $data; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $row): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?> <tr> <td class="text-right"><?php echo e($row->ranges); ?></td> <td class="text-right"><?php echo e(number_format($row->fixed_rate, 2)); ?></td> <td class="text-right"><?php echo e(number_format($row->tax_rate, 2)); ?></td> <td class="text-center"> <button class="btn btn-update btn-sm" v-on:click="annual_tax_edit(<?php echo e($row->id); ?>)"> <i class="fa fa-pencil-square-o" aria-hidden="true"></i> </button>&nbsp; <button class="btn btn-danger btn-sm" v-on:click="global_delete(<?php echo e($row->id); ?>, 'annual_tax_delete')"> <i class="fa fa-trash-o" aria-hidden="true"></i> </button> </td> </tr> <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?> <?php else: ?> <tr> <td colspan="4"> <strong class="text-danger">No data available on table.</strong> </td> </tr> <?php endif; ?> </tbody> </table> </div> </div> </div> </div> <?php echo $__env->make('partials.footer', \Illuminate\Support\Arr::except(get_defined_vars(), array('__data', '__path')))->render(); ?> </div> <?php $__env->stopSection(); ?> <?php echo $__env->renderComponent(); ?> <?php $__env->stopSection(); ?> <?php $__env->startSection('pagescript'); ?> <?php $__env->stopSection(); ?> <?php echo $__env->renderComponent(); ?>
30.678832
193
0.480609
4a17c23cfc79a7aaab904df594bacae0c6c76740
1,745
swift
Swift
Var_Let_String_Interpolation.swift
malagutti/swift-5-essentials-training
099a1a05747362423550a6b098f77e5998014c81
[ "MIT" ]
1
2020-11-05T00:21:51.000Z
2020-11-05T00:21:51.000Z
Var_Let_String_Interpolation.swift
malagutti/swift-5-essentials-training
099a1a05747362423550a6b098f77e5998014c81
[ "MIT" ]
null
null
null
Var_Let_String_Interpolation.swift
malagutti/swift-5-essentials-training
099a1a05747362423550a6b098f77e5998014c81
[ "MIT" ]
null
null
null
// basicVariables.swift /** * 1. Create 2 variables called characterName and weaponClassification and assign them string values of your choice. * 2. Use the += operator to add a nickname string onto characterName. * 3. Create a variable called currentMana and assign it a decimal value. * 4. Create another variable called manaPercentage and assign it currentMana divided by 100, then explicitly convert it to a string. * 5. Create a variable called debugStats and use string interpolation to lay out your character stats in a creative way. (HINT: use \n to create line breaks) * 6. Create 2 boolean variables called questAccepted and canQuest respectively and assign them values of your choice. * 7. Use the AND (&&) operator to evaluate if questAccepted and canQuest are both true and store it in a variable called questStatus. * 8. Add an interpolated string that includes questStatus to debugStats using the append method and print out debugStats. */ // 1 var characterName : String = "John Brave"; var weaponClassification : String = "Legendary"; // 2 characterName += " (Warrior)"; print(characterName); // 3 var currentMana : Double = 34.56; // 4 var manaPercentage : String = String(currentMana / 100); // 5 var debugStats : String = "The character named '\(characterName)' is looking for weapons classified as '\(weaponClassification)'...\n\(characterName) has currently \(currentMana) points of mana, which represents \(manaPercentage)% of the total mana."; print(debugStats); // 6 var questAccepted : Bool = false; var canQuest : Bool = true; // 7 let questStatus : Bool = questAccepted && canQuest; print(questStatus); // 8 debugStats.append(contentsOf: "\nThe current quest status is \(questStatus)."); print(debugStats);
40.581395
251
0.755874
2496e8030e49e2ae2c90e1dba1edd39dd36a303c
574
asm
Assembly
oeis/240/A240530.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
11
2021-08-22T19:44:55.000Z
2022-03-20T16:47:57.000Z
oeis/240/A240530.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
9
2021-08-29T13:15:54.000Z
2022-03-09T19:52:31.000Z
oeis/240/A240530.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
3
2021-08-22T20:56:47.000Z
2021-09-29T06:26:12.000Z
; A240530: a(n) = 4*(2*n)! / (n!)^2. ; 4,8,24,80,280,1008,3696,13728,51480,194480,739024,2821728,10816624,41602400,160466400,620470080,2404321560,9334424880,36300541200,141381055200,551386115280,2153031497760,8416395854880,32933722910400,128990414732400,505642425751008,1983674131792416,7787757702592448,30594762403041760,120269065998164160,473058326259445696,1861713413021044352,7330496563770362136,28877713736065062960,113812165900962306960,448745111266651381728,1770050161107347116816,6984522257342504839328,27570482594773045418400 mov $1,$0 mul $0,2 bin $0,$1 mul $0,4
71.75
497
0.855401
76f79b87f577ca8244994c867d3d520104a43493
2,384
h
C
inc/parse.h
jroivas/sic
5f7ee0c72457266c56a5e5bb6ac3dc866dc1b0d4
[ "MIT" ]
null
null
null
inc/parse.h
jroivas/sic
5f7ee0c72457266c56a5e5bb6ac3dc866dc1b0d4
[ "MIT" ]
null
null
null
inc/parse.h
jroivas/sic
5f7ee0c72457266c56a5e5bb6ac3dc866dc1b0d4
[ "MIT" ]
null
null
null
#ifndef __PARSE_H #define __PARSE_H #include "sic.h" #include "scan.h" enum nodetype { A_ADD, A_MINUS, A_MUL, A_DIV, A_MOD, A_LEFT, A_RIGHT, A_AND, A_OR, A_XOR, A_LOG_AND, A_LOG_OR, A_IDENTIFIER, A_NEGATE, A_NOT, A_INT_LIT, A_DEC_LIT, A_STR_LIT, A_ASSIGN, A_ADD_ASSIGN, A_SUB_ASSIGN, A_MUL_ASSIGN, A_DIV_ASSIGN, A_MOD_ASSIGN, A_LEFT_ASSIGN, A_RIGHT_ASSIGN, A_AND_ASSIGN, A_OR_ASSIGN, A_XOR_ASSIGN, A_GLUE, A_TYPE, A_TYPESPEC, A_TYPE_QUAL, A_STORAGE_CLASS, A_TYPE_LIST, A_DECLARATION, A_PARAMS, A_FUNCTION, A_RETURN, A_POINTER, A_ADDR, A_DEREFERENCE, A_IF, A_TERNARY, A_EQ_OP, A_NE_OP, A_LT, A_GT, A_LT_EQ, A_GT_EQ, A_NULL, A_FUNC_CALL, A_POSTINC, A_PREINC, A_POSTDEC, A_PREDEC, A_TILDE, A_CAST, A_WHILE, A_DO, A_FOR, A_INDEX, A_INDEXDEF, A_ARRAYDEF, A_SIZEOF, A_STRUCT, A_UNION, A_ENUM, A_ACCESS, A_ELLIPSIS, A_BREAK, A_CONTINUE, A_GOTO, A_LABEL, A_ATTRIBUTE, A_ASM, A_TYPEDEF, A_ARRAY_INITIALIZER, A_LIST }; struct node { enum nodetype node; enum var_type type; int bits; int sign; int reg; int is_const; int is_extern; int is_static; int is_inline; int is_func; int ptr; int addr; int strnum; int array_size; const char *value_string; const char *type_name; literalnum value; literalnum fraction; struct token *token; const char *filename; int line; int linepos; struct node *parent; struct node *left; struct node *mid; struct node *right; }; struct node *parse(struct scanfile *f); void parse_end(struct scanfile *f); extern void node_walk(struct node *node); extern void node_free(struct node *node); const char *node_type_str(enum nodetype t); const char *node_str(struct node *n); struct node *make_node(struct token *t, enum nodetype node, struct node *left, struct node *mid, struct node *right); enum comma_type { COMMA_NONE, COMMA_OPT, COMMA_MANDATORY }; typedef struct node *(*list_iter_handler)(struct scanfile *f, struct token *token); struct node *iter_list(struct scanfile *f, struct token *token, list_iter_handler handler, enum comma_type comma, int force_list); #endif
18.48062
130
0.654782
f55fd4d772508f70e2caa365ea0f31a6fdf4b945
408
dart
Dart
lib/main.dart
valdio/flutter-redux-mvvm
f87a7daad47d80cee5aed78673d6a13c091aacb3
[ "MIT" ]
10
2020-03-30T15:54:23.000Z
2021-11-25T18:42:09.000Z
lib/main.dart
valdio/flutter-redux-mvvm
f87a7daad47d80cee5aed78673d6a13c091aacb3
[ "MIT" ]
null
null
null
lib/main.dart
valdio/flutter-redux-mvvm
f87a7daad47d80cee5aed78673d6a13c091aacb3
[ "MIT" ]
2
2020-12-14T00:38:03.000Z
2021-11-25T18:42:08.000Z
import 'package:flutter/material.dart'; import 'package:flutter_redux/flutter_redux.dart'; import 'package:flutter_redux_mvvm/App.dart'; import 'package:flutter_redux_mvvm/store/config.dart'; import 'store/models/AppState.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); final store = await ReduxConfig().getStore(); runApp(StoreProvider<AppState>(store: store, child: App())); }
34
62
0.779412
02244186963798c9cdea026e79b77dcb73e1d9d5
2,974
dart
Dart
lib/src/grpc_api/dart/google/devtools/containeranalysis/v1alpha1/image_basis.pbenum.dart
domesticmouse/appengine
3fd2b1238caa2cf9281ad5914b58d4c001c93d59
[ "BSD-3-Clause" ]
null
null
null
lib/src/grpc_api/dart/google/devtools/containeranalysis/v1alpha1/image_basis.pbenum.dart
domesticmouse/appengine
3fd2b1238caa2cf9281ad5914b58d4c001c93d59
[ "BSD-3-Clause" ]
null
null
null
lib/src/grpc_api/dart/google/devtools/containeranalysis/v1alpha1/image_basis.pbenum.dart
domesticmouse/appengine
3fd2b1238caa2cf9281ad5914b58d4c001c93d59
[ "BSD-3-Clause" ]
null
null
null
/// // Generated code. Do not modify. // source: google/devtools/containeranalysis/v1alpha1/image_basis.proto // // @dart = 2.3 // ignore_for_file: camel_case_types,non_constant_identifier_names,library_prefixes,unused_import,unused_shown_name,return_of_invalid_type // ignore_for_file: UNDEFINED_SHOWN_NAME,UNUSED_SHOWN_NAME import 'dart:core' as $core; import 'package:protobuf/protobuf.dart' as $pb; class DockerImage_Layer_Directive extends $pb.ProtobufEnum { static const DockerImage_Layer_Directive DIRECTIVE_UNSPECIFIED = DockerImage_Layer_Directive._(0, 'DIRECTIVE_UNSPECIFIED'); static const DockerImage_Layer_Directive MAINTAINER = DockerImage_Layer_Directive._(1, 'MAINTAINER'); static const DockerImage_Layer_Directive RUN = DockerImage_Layer_Directive._(2, 'RUN'); static const DockerImage_Layer_Directive CMD = DockerImage_Layer_Directive._(3, 'CMD'); static const DockerImage_Layer_Directive LABEL = DockerImage_Layer_Directive._(4, 'LABEL'); static const DockerImage_Layer_Directive EXPOSE = DockerImage_Layer_Directive._(5, 'EXPOSE'); static const DockerImage_Layer_Directive ENV = DockerImage_Layer_Directive._(6, 'ENV'); static const DockerImage_Layer_Directive ADD = DockerImage_Layer_Directive._(7, 'ADD'); static const DockerImage_Layer_Directive COPY = DockerImage_Layer_Directive._(8, 'COPY'); static const DockerImage_Layer_Directive ENTRYPOINT = DockerImage_Layer_Directive._(9, 'ENTRYPOINT'); static const DockerImage_Layer_Directive VOLUME = DockerImage_Layer_Directive._(10, 'VOLUME'); static const DockerImage_Layer_Directive USER = DockerImage_Layer_Directive._(11, 'USER'); static const DockerImage_Layer_Directive WORKDIR = DockerImage_Layer_Directive._(12, 'WORKDIR'); static const DockerImage_Layer_Directive ARG = DockerImage_Layer_Directive._(13, 'ARG'); static const DockerImage_Layer_Directive ONBUILD = DockerImage_Layer_Directive._(14, 'ONBUILD'); static const DockerImage_Layer_Directive STOPSIGNAL = DockerImage_Layer_Directive._(15, 'STOPSIGNAL'); static const DockerImage_Layer_Directive HEALTHCHECK = DockerImage_Layer_Directive._(16, 'HEALTHCHECK'); static const DockerImage_Layer_Directive SHELL = DockerImage_Layer_Directive._(17, 'SHELL'); static const $core.List<DockerImage_Layer_Directive> values = <DockerImage_Layer_Directive>[ DIRECTIVE_UNSPECIFIED, MAINTAINER, RUN, CMD, LABEL, EXPOSE, ENV, ADD, COPY, ENTRYPOINT, VOLUME, USER, WORKDIR, ARG, ONBUILD, STOPSIGNAL, HEALTHCHECK, SHELL, ]; static final $core.Map<$core.int, DockerImage_Layer_Directive> _byValue = $pb.ProtobufEnum.initByValue(values); static DockerImage_Layer_Directive valueOf($core.int value) => _byValue[value]; const DockerImage_Layer_Directive._($core.int v, $core.String n) : super(v, n); }
37.175
138
0.757229
127284ea2495fa12b1e5096e821f060b909dd336
5,935
dart
Dart
lib/screens/items.dart
battle-buddy/battlebuddy-android
dcb5321665bdd80db0ead5f46118a6e1de44c15c
[ "MIT" ]
2
2021-06-16T14:16:42.000Z
2022-02-11T13:24:11.000Z
lib/screens/items.dart
battle-buddy/battlebuddy-android
dcb5321665bdd80db0ead5f46118a6e1de44c15c
[ "MIT" ]
14
2021-02-02T15:39:07.000Z
2022-02-08T23:04:11.000Z
lib/screens/items.dart
battle-buddy/battlebuddy-android
dcb5321665bdd80db0ead5f46118a6e1de44c15c
[ "MIT" ]
null
null
null
import 'package:flutter/material.dart'; import '../common/cards.dart'; import '../models/items/ammunition.dart'; import '../models/items/armor.dart'; import '../models/items/chestrig.dart'; import '../models/items/firearm.dart'; import '../models/items/item.dart'; import '../models/items/medical.dart'; import '../models/items/melee.dart'; import '../models/items/throwable.dart'; import 'stacks/items/item_list.dart'; class ItemsTab extends StatelessWidget { static const String title = 'Items'; static const ImageIcon icon = ImageIcon( AssetImage('assets/images/icons/items.png'), size: 30, ); static final Map<String, Widget Function(BuildContext)> routes = {}; const ItemsTab({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return NavigationCardList( cards: <NavigationCard>[ NavigationCard( title: 'Firearms', image: 'assets/images/card_heroes/firearms.png', pageRoute: () => MaterialPageRoute<void>( builder: (context) => const ItemSectionListScreen<Firearm>(), settings: RouteSettings( name: '${ItemSectionListScreen.routeName}/firearms', arguments: ItemSectionListScreenArguments( title: 'Firearms', query: ItemType.firearm.getQuery('class'), ), ), ), ), NavigationCard( title: 'Ammunition', image: 'assets/images/card_heroes/ammo.jpg', pageRoute: () => MaterialPageRoute<void>( builder: (context) => const ItemSectionListScreen<Ammunition>(), settings: RouteSettings( name: '${ItemSectionListScreen.routeName}/ammunition', arguments: ItemSectionListScreenArguments( title: 'Ammunition', query: ItemType.ammo.getQuery('caliber'), ), ), ), ), NavigationCard( title: 'Body Armor', image: 'assets/images/card_heroes/armor.jpg', pageRoute: () => MaterialPageRoute<void>( builder: (context) => const ItemSectionListScreen<Armor>(), settings: RouteSettings( name: '${ItemSectionListScreen.routeName}/bodyArmor', arguments: ItemSectionListScreenArguments( title: 'Body Armor', query: ItemType.bodyArmor.getQuery('armor.class'), ), ), ), ), NavigationCard( title: 'Chest Rigs', image: 'assets/images/card_heroes/chest_rigs.png', pageRoute: () => MaterialPageRoute<void>( builder: (context) => const ItemSectionListScreen<ChestRig>(), settings: RouteSettings( name: '${ItemSectionListScreen.routeName}/chestRigs', arguments: ItemSectionListScreenArguments( title: 'Chest Rigs', query: ItemType.chestRig.getQuery(null), sortSections: true, ), ), ), ), NavigationCard( title: 'Helmets', image: 'assets/images/card_heroes/helmets.png', pageRoute: () => MaterialPageRoute<void>( builder: (context) => const ItemSectionListScreen<Armor>(), settings: RouteSettings( name: '${ItemSectionListScreen.routeName}/helmets', arguments: ItemSectionListScreenArguments( title: 'Helmets', query: ItemType.helmet.getQuery('armor.class'), ), ), ), ), NavigationCard( title: 'Attachments', image: 'assets/images/card_heroes/attachments.png', pageRoute: () => MaterialPageRoute<void>( builder: (context) => const ItemSectionListScreen<Armor>(), settings: RouteSettings( name: '${ItemSectionListScreen.routeName}/attachments', arguments: ItemSectionListScreenArguments( title: 'Attachments', query: ItemType.attachment.getQuery('armor.class'), ), ), ), ), NavigationCard( title: 'Medical', image: 'assets/images/card_heroes/medical.png', pageRoute: () => MaterialPageRoute<void>( builder: (context) => const ItemSectionListScreen<Medical>(), settings: RouteSettings( name: '${ItemSectionListScreen.routeName}/medical', arguments: ItemSectionListScreenArguments( title: 'Medical', query: ItemType.medical.getQuery('type'), ), ), ), ), NavigationCard( title: 'Melee Weapons', image: 'assets/images/card_heroes/melee.jpg', pageRoute: () => MaterialPageRoute<void>( builder: (context) => const ItemListScreen<Melee>(), settings: RouteSettings( name: '${ItemListScreen.routeName}/meleeWeapons', arguments: ItemListScreenArguments( title: 'Melee Weapons', query: ItemType.melee.getQuery(null), ), ), ), ), NavigationCard( title: 'Throwables', image: 'assets/images/card_heroes/throwables.jpg', routeName: '${ItemListScreen.routeName}/throwables', pageRoute: () => MaterialPageRoute<void>( builder: (context) => const ItemSectionListScreen<Throwable>(), settings: RouteSettings( name: '${ItemSectionListScreen.routeName}/throwables', arguments: ItemSectionListScreenArguments( title: 'Throwables', query: ItemType.throwable.getQuery('type'), ), ), ), ), ], ); } }
36.863354
76
0.556361
400c963470dfd2f27b05d63f68f1fc36ae3ec0ed
48,617
py
Python
TALOS/Metrics.py
pikaplan/talos
2240afca10b9b5c9f9bd32340698d06cdfa25d98
[ "MIT" ]
1
2020-03-05T05:46:00.000Z
2020-03-05T05:46:00.000Z
TALOS/Metrics.py
pankap/talos
2240afca10b9b5c9f9bd32340698d06cdfa25d98
[ "MIT" ]
null
null
null
TALOS/Metrics.py
pankap/talos
2240afca10b9b5c9f9bd32340698d06cdfa25d98
[ "MIT" ]
null
null
null
# ===================================================================================================================== # # Tensor Abstraction Layer Objects 0.0.8-ALPHA # EVALUATION METRICS # # Framework design by Pantelis I. Kaplanoglou # Licensed under the MIT License # # ===================================================================================================================== import json import numpy as np #TODO: Remove dependency of sklearn, scipy from sklearn import metrics from TALOS.FileSystem import Storage #--------------------------------------------------------------------------------------------------- def SimpleEncode(ndarray): return json.dumps(ndarray.tolist()) #--------------------------------------------------------------------------------------------------- def SimpleDecode(jsonDump): return np.array(json.loads(jsonDump)) #--------------------------------------------------------------------------------------------------- #================================================================================================== class MetricsKind: SUPERVISED_CLASSIFICATION = 0 UNSUPERVISED_CLASSIFICATION = 1 SUPERVISED_CLASSIFICATION_EXTRA = 2 UNSUPERVISED_CLASSIFICATION_EXTRA = 3 UNSUPERVISED_CLUSTERING = 4 SUPERVISED_CLUSTERING = 5 REGRESSION = 6 FUNCTION_APPROXIMATION = 8 RETRIEVAL = 10 DETECTION = 12 TRACKING = 14 #================================================================================================== #================================================================================================== class ClassificationMetricsCalculator(object): __verboseLevel = 1 #------------------------------------------------------------------------------------ def __init__(self): #........ | Instance Attributes | .............................................. # // Basic \\ self.ClassTrue = None self.ClassFalse = None self.ClassActual = None self.ClassRecall = None self.ClassPrecision = None self.ClassF1Score = None self.Recall = None self.Precision = None self.F1Score = None # // Extended Stats \\ self.RecallMean = None self.PrecisionMean = None self.F1ScoreMean = None self.RecallMedian = None self.PrecisionMedian = None self.F1ScoreMedian = None self.RecallStd = None self.PrecisionStd = None self.F1ScoreStd = None self.RecallMin = None self.PrecisionMin = None self.F1ScoreMin = None self.RecallMax = None self.PrecisionMax = None self.F1ScoreMax = None #................................................................................ #------------------------------------------------------------------------------------ def __calculateClassStats(self): self.RecallMean = np.mean(self.ClassRecall) self.PrecisionMean = np.mean(self.ClassPrecision) self.F1ScoreMean = np.mean(self.ClassF1Score) self.RecallMedian = np.median(self.ClassRecall) self.PrecisionMedian = np.median(self.ClassPrecision) self.F1ScoreMedian = np.median(self.ClassF1Score) self.RecallStd = np.std(self.ClassRecall) self.PrecisionStd = np.std(self.ClassPrecision) self.F1ScoreStd = np.std(self.ClassF1Score) self.RecallMin = np.min(self.ClassRecall) self.PrecisionMin = np.min(self.ClassPrecision) self.F1ScoreMin = np.min(self.ClassF1Score) self.RecallMax = np.max(self.ClassRecall) self.PrecisionMax = np.max(self.ClassPrecision) self.F1ScoreMax = np.max(self.ClassF1Score) if type(self).__verboseLevel >= 2: print("Recall Stats: Min:%.4f Max:%4.f Med:%.4f Mean:%.4f Std:%.4f" % (self.RecallMin, self.RecallMax, self.RecallMedian, self.RecallMean, self.RecallStd)) print("Precision Stats: Min:%.4f Max:%4.f Med:%.4f Mean:%.4f Std:%.4f" % (self.PrecisionMin, self.PrecisionMax, self.PrecisionMedian, self.PrecisionMean, self.PrecisionStd)) print("F1Score Stats: Min:%.4f Max:%4.f Med:%.4f Mean:%.4f Std:%.4f" % (self.F1ScoreMin, self.F1ScoreMax, self.F1ScoreMedian, self.F1ScoreMean, self.F1ScoreStd)) #------------------------------------------------------------------------------------ def Calculate(self, p_nTrue, p_nFalse, p_nActual): nTrue = np.sum(np.asarray(p_nTrue), axis=0) nFalse = np.sum(np.asarray(p_nFalse), axis=0) nActual = np.sum(np.asarray(p_nActual), axis=0) self.ClassTrue = nTrue self.ClassFalse = nFalse self.ClassActual = nActual #TODO: Confusion Matrix #print(nTrue) #print(nFalse) #print(nActual) #print(np.sum(nActual)) self.ClassRecall = nTrue / (nActual + 1e-7) self.ClassPrecision = nTrue / (nTrue + nFalse + 1e-7) self.ClassF1Score = (2.0 * ( self.ClassRecall * self.ClassPrecision) ) / ( self.ClassRecall + self.ClassPrecision + + 1e-7) if type(self).__verboseLevel >= 3: print("ClassRecall", self.ClassRecall) print("ClassPrecision", self.ClassPrecision) print("ClassF1Score", self.ClassF1Score) self.__calculateClassStats() #TODO: Weight by Support self.Recall = np.average(self.ClassRecall) self.Precision = np.average(self.ClassPrecision) self.F1Score = np.average(self.ClassF1Score) if type(self).__verboseLevel >= 2: print("Avg Class Recall", self.Recall) print("Avg Class Precision", self.Precision) print("Avg Class F1Score", self.F1Score) #print("Recall:%f Precision:%f F1Score:%f" % (self.Recall, self.Precision, self.F1Score)) #------------------------------------------------------------------------------------ #================================================================================================== #================================================================================================== class ClassificationMetrics(object): #------------------------------------------------------------------------------------ def __init__(self): #........ | Instance Attributes | .............................................. self.Kind = MetricsKind.SUPERVISED_CLASSIFICATION self.ActualClasses = None self.PredictedClasses = None self.PredictedProbsTop = None self.IDs = None self.TopCount = None self.Accuracy = None self.TopKAccuracy = None self.AveragePrecision = None self.AverageRecall = None self.AverageF1Score = None self.AverageSupport = None self.Precision = None self.Recall = None self.F1Score = None self.Support = None self.ConfusionMatrix = None self.ClassCount = 0 #................................................................................ #------------------------------------------------------------------------------------ def CalculateTopK(self, p_nTopKappa, p_nTopKCorrect): self.TopKappa = p_nTopKappa self.TopKAccuracy = np.mean(p_nTopKCorrect) print("TopKAccuracy", self.TopKAccuracy) #self.TopKAccuracy #------------------------------------------------------------------------------------ def Calculate(self, p_nActual, p_nPredicted, p_nPredictedProbsTop=None): self.ActualClasses = p_nActual self.PredictedClasses = p_nPredicted self.PredictedProbsTop = p_nPredictedProbsTop if self.PredictedProbsTop is not None: self.TopCount = p_nPredictedProbsTop.shape[1] # Confusion matrix layout is # predicted # - - - - - - - - # actual | # | self.ConfusionMatrix = metrics.confusion_matrix(self.ActualClasses, self.PredictedClasses) self.Accuracy = metrics.accuracy_score(self.ActualClasses, self.PredictedClasses) self.Precision, self.Recall, self.F1Score, self.Support = metrics.precision_recall_fscore_support(self.ActualClasses, self.PredictedClasses, average=None) self.AveragePrecision, self.AverageRecall, self.AverageF1Score, self.AverageSupport = metrics.precision_recall_fscore_support(self.ActualClasses, self.PredictedClasses, average='weighted') self.ClassCount = self.Recall.shape[0] #------------------------------------------------------------------------------------ def Save(self, p_sFileName): oData = { "FileFormat" : "TALOS008" ,"Kind" : self.Kind ,"IDs" : self.IDs ,"Actual" : self.ActualClasses ,"Predicted" : self.PredictedClasses ,"PredictedProbsTop" : self.PredictedProbsTop ,"TopKappa" : self.TopKappa ,"Accuracy" : self.Accuracy ,"TopKAccuracy" : self.TopKAccuracy ,"AveragePrecision" : self.AveragePrecision ,"AverageRecall" : self.AverageRecall ,"AverageF1Score" : self.AverageF1Score ,"AverageSupport" : self.AverageSupport #,"Top1Error" : None #,"Top5Error" : None ,"ClassPrecision" : self.Precision ,"ClassRecall" : self.Recall ,"ClassF1Score" : self.F1Score ,"ClassSupport" : self.Support ,"ConfusionMatrix" : self.ConfusionMatrix } Storage.SerializeObjectToFile(p_sFileName, oData) #------------------------------------------------------------------------------------ def Load(self, p_sFileName): oData = Storage.DeserializeObjectFromFile(p_sFileName) assert oData is not None, "Evaluation results file not found %s" % p_sFileName self.IDs = oData["IDs"] self.Kind = oData["Kind"] self.ActualClasses = oData["Actual"] self.PredictedClasses = oData["Predicted"] self.PredictedProbsTop = oData["PredictedProbsTop"] if self.PredictedProbsTop is not None: self.TopCount = self.PredictedProbsTop.shape[1] if "TopKappa" in oData: self.TopKappa = oData["TopKappa"] if "Accuracy" in oData: self.Accuracy = oData["Accuracy"] if "TopKAccuracy" in oData: self.TopKAccuracy = oData["TopKAccuracy"] self.AveragePrecision = oData["AveragePrecision"] self.AverageRecall = oData["AverageRecall"] self.AverageF1Score = oData["AverageF1Score"] self.AverageSupport = oData["AverageSupport"] #self.Top1Error = oData["Top1Error"] #self.Top5Error = oData["Top5Error"] self.Precision = oData["ClassPrecision"] self.Recall = oData["ClassRecall"] self.F1Score = oData["ClassF1Score"] self.Support = oData["ClassSupport"] self.ConfusionMatrix = oData["ConfusionMatrix"] self.ClassCount = self.Recall.shape[0] #------------------------------------------------------------------------------------ def MissClassified(self, p_nClassIndex): oIDs = [] for nIndex, nActual in enumerate(self.ActualClasses): if (nActual == p_nClassIndex) and (nActual != self.PredictedClasses[nIndex]): oIDs.append(self.IDs[nIndex]) return oIDs #------------------------------------------------------------------------------------ #================================================================================================== #================================================================================================== class ClassificationBest(object): #------------------------------------------------------------------------------------ def __init__(self, p_sEvaluationResultsFolder=None): #........ | Instance Attributes | .............................................. self.Folder = p_sEvaluationResultsFolder self.ResultFiles = None self.KeepEpochs = 3 self.TopCount = 5 self.EpochNumber=None self.FileNames=None self.Accuracy=None self.Recall=None self.Precision=None self.F1Score=None self.Points=None self.ClassCount=None self.IsBinary=False self.BestIndexes = None # // Persistent Data \\ self.BestEpochs = None self.Points = None self.Recall = None self.Precision = None self.F1Score = None self.CrossF1Score = None self.ObjectiveF1Score = None self.PositiveF1Score = None self.BestPoints = None self.BestRecall = None self.BestPrecision = None self.BestF1Score = None self.BestCrossF1Score = None self.BestObjectiveF1Score = None self.BestPositiveF1Score = None self.DiscardedEpochs = None self.BestRecallEpochs = None self.BestPrecisionEpochs = None self.BestF1ScoreEpochs = None self.BestCrossF1ScoreEpochs = None self.BestObjectiveF1ScoreEpochs = None self.BestPositiveScoreEpochs = None #................................................................................ if self.Folder is not None: self.__listFiles() #------------------------------------------------------------------------------------ def Save(self, p_sFileName): oData = { "FileFormat" : "TALOS008" ,"IsBinary" : self.IsBinary ,"EpochNumber" : self.EpochNumber ,"FileNames" : self.FileNames ,"Accuracy" : self.Accuracy ,"Recall" : self.Recall ,"Precision" : self.Precision ,"F1Score" : self.F1Score ,"CrossF1Score" : self.CrossF1Score ,"ObjectiveF1Score" : self.ObjectiveF1Score ,"PositiveF1Score" : self.PositiveF1Score ,"BestEpochs" : self.BestEpochs ,"BestPoints" : self.BestPoints ,"BestRecall" : self.BestRecall ,"BestPrecision" : self.BestPrecision ,"BestF1Score" : self.BestF1Score ,"BestCrossF1Score" : self.BestCrossF1Score ,"BestObjectiveF1Score" : self.BestObjectiveF1Score ,"BestPositiveF1Score" : self.BestPositiveF1Score ,"DiscardedEpochs" : self.DiscardedEpochs ,"BestRecallEpochs" : self.BestRecallEpochs ,"BestPrecisionEpochs" : self.BestPrecisionEpochs ,"BestF1ScoreEpochs" : self.BestF1ScoreEpochs ,"BestCrossF1ScoreEpochs" : self.BestCrossF1ScoreEpochs ,"BestObjectiveF1ScoreEpochs": self.BestObjectiveF1ScoreEpochs ,"BestPositiveScoreEpochs" : self.BestPositiveScoreEpochs } Storage.SerializeObjectToFile(p_sFileName, oData, p_bIsOverwritting=True) #------------------------------------------------------------------------------------ def IndexOfEpoch(self, p_nEpochNumber): nFoundPos = None for nIndex, nEpochNumber in enumerate(self.EpochNumber): if nEpochNumber == p_nEpochNumber: nFoundPos = nIndex break return nFoundPos #------------------------------------------------------------------------------------ def GetBestIndex(self): return self.IndexOfEpoch( self.BestEpochs[0] ) #------------------------------------------------------------------------------------ def Load(self, p_sFileName): oData = Storage.DeserializeObjectFromFile(p_sFileName, p_bIsVerbose=False) assert oData is not None, "File %s not found" % p_sFileName self.BestEpochs = oData["BestEpochs"] self.IsBinary = oData["IsBinary"] self.EpochNumber = oData["EpochNumber"] self.FileNames = oData["FileNames"] self.Accuracy = oData["Accuracy"] self.Recall = oData["Recall"] self.Precision = oData["Precision"] self.F1Score = oData["F1Score"] self.CrossF1Score = oData["CrossF1Score"] if "ObjectiveF1Score" in oData: self.ObjectiveF1Score = oData["ObjectiveF1Score"] self.PositiveF1Score = oData["PositiveF1Score"] self.BestPoints = oData["BestPoints"] self.BestRecall = oData["BestRecall"] self.BestPrecision = oData["BestPrecision"] self.BestF1Score = oData["BestF1Score"] self.BestCrossF1Score = oData["BestCrossF1Score"] if "BestObjectiveF1Score" in oData: self.BestObjectiveF1Score = oData["BestObjectiveF1Score"] self.BestPositiveF1Score = oData["BestPositiveF1Score"] self.DiscardedEpochs = oData["DiscardedEpochs"] self.BestRecallEpochs = oData["BestRecallEpochs"] self.BestPrecisionEpochs = oData["BestPrecisionEpochs"] self.BestF1ScoreEpochs = oData["BestF1ScoreEpochs"] self.BestCrossF1ScoreEpochs = oData["BestCrossF1ScoreEpochs"] if "BestObjectiveF1ScoreEpochs" in oData: self.BestObjectiveF1ScoreEpochs = oData["BestObjectiveF1ScoreEpochs"] self.BestPositiveScoreEpochs = oData["BestPositiveScoreEpochs"] #------------------------------------------------------------------------------------ def __listFiles(self): sEvaluationResultFiles = Storage.GetFilesSorted(self.Folder) self.FileNames = [] self.ResultFiles = [] for sFile in sEvaluationResultFiles: sFileNameFull = Storage.JoinPath(self.Folder, sFile) self.FileNames.append(sFileNameFull) self.ResultFiles.append( [sFile, sFileNameFull]) nFileCount = len(self.ResultFiles) self.EpochNumber=np.zeros((nFileCount), np.float32 ) self.Accuracy=np.zeros((nFileCount), np.float32 ) self.Recall=np.zeros((nFileCount), np.float32 ) self.Precision=np.zeros((nFileCount), np.float32 ) self.F1Score=np.zeros((nFileCount), np.float32 ) self.Points=np.zeros((nFileCount), np.float32 ) self.CrossF1Score=np.zeros((nFileCount), np.float32 ) self.ObjectiveF1Score=np.zeros((nFileCount), np.float32 ) self.PositiveF1Score=np.zeros((nFileCount), np.float32 ) #------------------------------------------------------------------------------------ def __loadAll(self): for nIndex, sFileRec in enumerate(self.ResultFiles): _, sEpochNumber, _ = Storage.SplitFileName(sFileRec[0]) sFileNameFull = sFileRec[1] oMetrics = ClassificationMetrics() oMetrics.Load(sFileNameFull) print("Accuracy:%f Top%dAccuracy%s" % (oMetrics.Accuracy, oMetrics.TopKappa, oMetrics.TopKAccuracy)) self.EpochNumber[nIndex] = int(sEpochNumber) self.Accuracy[nIndex] = oMetrics.Accuracy self.Recall[nIndex] = oMetrics.AverageRecall self.Precision[nIndex] = oMetrics.AveragePrecision self.F1Score[nIndex] = oMetrics.AverageF1Score if oMetrics.ClassCount == 2: self.IsBinary=True # Cross entropy of the F1 scores for binary classification. self.CrossF1Score[nIndex] = -(oMetrics.F1Score[0]*np.log10(oMetrics.F1Score[1])+ oMetrics.F1Score[1]*np.log10(oMetrics.F1Score[0])) self.ObjectiveF1Score[nIndex] = self.F1Score[nIndex] / self.CrossF1Score[nIndex] # Special binary classification, with the class 0 the class positives self.PositiveF1Score[nIndex] = oMetrics.F1Score[0] print(sEpochNumber, oMetrics.F1Score[0], oMetrics.F1Score[1], self.CrossF1Score[nIndex], self.ObjectiveF1Score[nIndex]) #------------------------------------------------------------------------------------ def _topKIndexes(self, p_nArray, p_nK): #print(np.sort(p_nArray)) #print(np.argsort(p_nArray)[-p_nK:]) nResult = [] for nIndex in np.argsort(p_nArray)[-p_nK:]: nResult.insert(0, nIndex) return nResult #------------------------------------------------------------------------------------ def _bottomKIndexes(self, p_nArray, p_nK): #print(np.sort(p_nArray)) #print(np.argsort(p_nArray)[-p_nK:]) nResult = [] for nIndex in np.argsort(p_nArray)[:p_nK]: nResult.insert(0, nIndex) return nResult #------------------------------------------------------------------------------------ def _mergeIdx(self, p_nFirstList, p_nSecondList): return p_nFirstList + list(set(p_nSecondList) - set(p_nFirstList)) #------------------------------------------------------------------------------------ def Run(self): #Using point system from F1 POINT_SYSTEM = [25,18,15,12,10,8,6,4,2,1] nTopCount = self.TopCount nTopPoints=np.asarray(POINT_SYSTEM[:nTopCount], np.float32) self.__loadAll() nTopRecallIdx = self._topKIndexes(self.Recall, nTopCount) nTopPrecisionIdx = self._topKIndexes(self.Precision, nTopCount) nTopF1ScoreIdx = self._topKIndexes(self.F1Score, nTopCount) if self.IsBinary: nTopCrossF1ScoreIdx = self._bottomKIndexes(self.CrossF1Score, nTopCount) nTopObjectiveF1ScoreIdx = self._topKIndexes(self.ObjectiveF1Score, nTopCount) nTopPositiveF1ScoreIdx = self._topKIndexes(self.PositiveF1Score, nTopCount) print("--------------------------") print("Top %d Recall " % nTopCount, self.EpochNumber[nTopRecallIdx], self.Recall[nTopRecallIdx]) print("Top %d Precision " % nTopCount, self.EpochNumber[nTopPrecisionIdx], self.Precision[nTopPrecisionIdx]) print("Top %d F1Score " % nTopCount , self.EpochNumber[nTopF1ScoreIdx], self.F1Score[nTopF1ScoreIdx]) if self.IsBinary: print("Top %d Cross Entropy of F1Score" % nTopCount , self.EpochNumber[nTopCrossF1ScoreIdx], self.CrossF1Score[nTopCrossF1ScoreIdx]) print("Top %d Object F1 Ratio " % nTopCount , self.EpochNumber[nTopCrossF1ScoreIdx], self.ObjectiveF1Score[nTopObjectiveF1ScoreIdx]) print("Top %d F1Score for Positives " % nTopCount , self.EpochNumber[nTopPositiveF1ScoreIdx], self.PositiveF1Score[nTopPositiveF1ScoreIdx]) if self.IsBinary: self.Points[nTopObjectiveF1ScoreIdx] += nTopPoints self.Points[nTopCrossF1ScoreIdx] += nTopPoints / 2 self.Points[nTopPositiveF1ScoreIdx] += nTopPoints / 8 self.Points[nTopRecallIdx] += (nTopPoints / 4) self.Points[nTopPrecisionIdx] += (nTopPoints / 4) self.Points[nTopF1ScoreIdx] += nTopPoints / 2 else: self.Points[nTopRecallIdx] += (nTopPoints / 2) self.Points[nTopPrecisionIdx] += (nTopPoints / 2) self.Points[nTopF1ScoreIdx] += (nTopPoints ) if self.IsBinary: nTopIdx = self._mergeIdx( nTopPositiveF1ScoreIdx, self._mergeIdx( nTopCrossF1ScoreIdx, self._mergeIdx(nTopF1ScoreIdx, self._mergeIdx(nTopRecallIdx, nTopPrecisionIdx)) ) ) else: nTopIdx = self._mergeIdx( nTopF1ScoreIdx, self._mergeIdx(nTopRecallIdx, nTopPrecisionIdx) ) print("--------------------------") print("epochs" , self.EpochNumber[nTopIdx]) print("points" , self.Points[nTopIdx]) if self.IsBinary: print("objective f1 ratio", self.ObjectiveF1Score[nTopIdx]) print("cross f1" , self.CrossF1Score[nTopIdx]) print("positive f1" , self.PositiveF1Score[nTopIdx]) print("recall" , self.Recall[nTopIdx]) print("precision" , self.Precision[nTopIdx]) print("f1" , self.F1Score[nTopIdx]) print("--------------------------") nBestIndexes = self._topKIndexes(self.Points, self.KeepEpochs) nBestEpochs = self.EpochNumber[nBestIndexes] self.BestIndexes = nBestIndexes self.BestEpochs = np.asarray(nBestEpochs, dtype=np.int32) self.BestPoints = self.Points[nBestIndexes] self.BestRecall = self.Recall[nBestIndexes] self.BestPrecision = self.Precision[nBestIndexes] self.BestF1Score = self.F1Score[nBestIndexes] self.BestCrossF1Score = self.CrossF1Score[nBestIndexes] self.BestObjectiveF1Score = self.ObjectiveF1Score[nBestIndexes] self.BestPositiveF1Score = self.PositiveF1Score[nBestIndexes] self.DiscardedEpochs = np.asarray(list(set(self.EpochNumber) - set(nBestEpochs)), dtype=np.int32) self.BestRecallEpochs = self.EpochNumber[nTopRecallIdx] self.BestPrecisionEpochs = self.EpochNumber[nTopPrecisionIdx] self.BestF1ScoreEpochs = self.EpochNumber[nTopF1ScoreIdx] if self.IsBinary: self.BestCrossF1ScoreEpochs = self.EpochNumber[nTopCrossF1ScoreIdx] self.BestObjectiveF1ScoreEpochs = self.EpochNumber[nTopObjectiveF1ScoreIdx] self.BestPositiveScoreEpochs = self.EpochNumber[nTopPositiveF1ScoreIdx] #------------------------------------------------------------------------------------ def ExportToText(self, p_sTextFileName, p_oExperiment=None): bIsAppending = p_oExperiment is not None if bIsAppending: sLearningConfigLines = Storage.ReadTextFile(p_oExperiment.RunSub.LearnConfigUsedFileName) sLearningLogLines = Storage.ReadTextFile(p_oExperiment.RunSub.LogFileName) # Dumps the class folders to a text file with open(p_sTextFileName, "w") as oOutFile: print("="*80, file=oOutFile) print("epochs :" , self.BestEpochs, file=oOutFile) print("points :" , self.BestPoints, file=oOutFile) if self.IsBinary: print("objective f1 ratio", self.BestObjectiveF1Score, file=oOutFile) print("cross f1 :" , self.BestCrossF1Score, file=oOutFile) print("positive f1 :" , self.BestPositiveF1Score * 100, file=oOutFile) print("recall :" , self.BestRecall * 100, file=oOutFile) print("precision :" , self.BestPrecision * 100, file=oOutFile) print("f1 score :" , self.BestF1Score * 100, file=oOutFile) if bIsAppending: # Appends the related configuration that generated the results print("-"*80, file=oOutFile) for sLine in sLearningConfigLines: print(sLine, file=oOutFile) print("="*80, file=oOutFile) # Appends the log at the end of the best models text file for sLine in sLearningLogLines: print(sLine, file=oOutFile) print("-"*80, file=oOutFile) print("="*80, file=oOutFile) #------------------------------------------------------------------------------------ #================================================================================================== # # #================================================================================================== # class ExperimentEvaluation(object): # __verboseLevel = 1 # # #------------------------------------------------------------------------------------ # def __init__(self, p_oExperiment): # #........ | Instance Attributes | .............................................. # self.Experiment = p_oExperiment # self.EpochModels=[] # self.WinnerModels=[ # self.DiscardedModels=[] # #TEMP # self.IsDeletingDiscardedModels=True # self.ExistModels=True # #................................................................................ # assert self.Experiment is not None, "Neural network should be associated with an experiment" # #------------------------------------------------------------------------------------ # def Evaluate(self): # self.DoOnExperimentEvaluate() # #------------------------------------------------------------------------------------ # def DoOnExperimentEvaluate(self): # pass # #------------------------------------------------------------------------------------ # def Save(self): # print("[>] Saving evaluation results for experiment %s run %s fold %i, started at %s." % # ( self.Experiment.BaseTitle, self.Experiment.MinuteUID.UID # , self.Experiment.FoldNumber, self.Experiment.Minute.strftime(taCC.ISO_DATE_FMT_MINUTE))) # # if False: #TEMP: Proven ineffective for large models like ZFNet # if self.Experiment.ExistsModel(taCC.C_MODEL_FILE_NAME_INITIAL): # if type(self).__verboseLevel >=1 : # print(" |__ Compressing initial weights: %s" % (self.Experiment.ExperimentModelFolder + taCC.C_MODEL_FILE_NAME_INITIAL)) # self.Experiment.CompressModel(taCC.C_MODEL_FILE_NAME_INITIAL) # self.Experiment.DeleteModel(taCC.C_MODEL_FILE_NAME_INITIAL, True) # # # Compresses the winner models # for nIndex,oModel in enumerate(self.WinnerModels): # if oModel is not None: # sModelName = oModel.ModelName # # if type(self).__verboseLevel >=1 : # print(" |__ Compressing epoch winner model: %s" % (self.Experiment.ExperimentModelFolder + sModelName)) # # sPickleFileName = "%s_k%02i_" % (self.Experiment.BaseTitle, self.Experiment.FoldNumber) + taCC.C_BASE_FILE_NAME_PREFIX + sModelName + ".pkl" # Storage.SerializeObjectToFile(self.Experiment.ExperimentResultsFolder + sPickleFileName, oModel) # Storage.SerializeObjectToFile(self.Experiment.ExperimentWinnersFolder + sPickleFileName, oModel) # if False: #TEMP: Proven ineffective for large models like ZFNet # self.Experiment.CompressModel(sModelName) # # if nIndex == 0: # self.AppendToFoldBestsFile(oModel) # # # # Discards the rest of the models # for oModel in self.DiscardedModels: # sModelName = oModel.ModelName # # if type(self).__verboseLevel >=1: # print(" |__ Discarding epoch model: %s" % (self.Experiment.ExperimentModelFolder + sModelName)) # sPickleFileName = "%s_k%02i_" % (self.Experiment.BaseTitle, self.Experiment.FoldNumber) + taCC.C_BASE_FILE_NAME_PREFIX + sModelName + ".pkl" # Storage.SerializeObjectToFile(self.Experiment.ExperimentResultsFolder + sPickleFileName, oModel) # if self.IsDeletingDiscardedModels: # self.Experiment.DeleteModel(sModelName) # #------------------------------------------------------------------------------------ # def AppendToFoldBestsFile(self, p_oChampionModel): # oExperiment = self.Experiment # # # with open(oExperiment.ExperimentWinnersFolder + taCC.C_EXPERIMENT_FOLDS_BESTS_FILE_NAME, "a") as oFile: # # Write the header on the first fold # if oExperiment.FoldNumber == 1: # sHeader="Title;Fold;EpochModel;Accuracy;Recall;Precision;F1Score" # print(sHeader, file=oFile) # # sLine = "%s;%i;%s;%.2f;%.2f;%.2f;%.2f" % ( # oExperiment.Title # ,oExperiment.FoldNumber # ,p_oChampionModel.ModelName # ,p_oChampionModel.Accuracy * 100.0 # ,p_oChampionModel.AverageRecall * 100.0 # ,p_oChampionModel.AveragePrecision * 100.8 # ,p_oChampionModel.AverageF1Score * 100.8 # ) # print(sLine, file=oFile) # oFile.close() # # #================================================================================================== # # # # # # # # # # # # # # #================================================================================================== # class ClassifierEvaluation(ExperimentEvaluation): # #------------------------------------------------------------------------------------ # def __init__(self, p_oNetwork): # #........ | Instance Attributes | .............................................. # self.Network = p_oNetwork # self.NoModelsFound = False # #................................................................................ # super(ClassifierEvaluation, self).__init__(p_oNetwork.Experiment) # #------------------------------------------------------------------------------------ # def DoOnExperimentEvaluate(self): # self.EpochModels = [] # sEpochModelNames = self.Experiment.ListSavedModels() # nCount = len(sEpochModelNames) # for nIndex, sModelName in enumerate(sEpochModelNames): # print("[>] Evaluating saved model %i/%i" % (nIndex + 1, nCount)) # self.Network.RestoreWeights(self.Experiment.ExperimentModelFolder + sModelName) # nActual,nPredicted = self.Network.Predict() # # #//TODO: Better encapsulation in method call # self.Network.InputQueue.RecallQueueFeeder.ContinueToFeed() # # oMetrics = ClassifierMetrics(sModelName) # self.EpochModels.append(oMetrics) # oMetrics.Calculate(nActual, nPredicted) # # self.DeterineWinners() # #------------------------------------------------------------------------------------ # def DeterineWinners(self): # print("[>] Determining winner models") # # One top model for each corresponding metric # oTopModelsForMetric=[None]*4 # # self.AveragePrecision = None # self.AverageRecall = None # self.AverageF1Score = None # self.AverageSupport = None # # # The following represents the priority order of the winner models, best of all is the one with best F1 score # nTopF1Score=0 # nTopAccuracy=0 # nTopRecall=0 # nTopPrecision=0 # for oModel in self.EpochModels: # if oModel.AverageF1Score > nTopF1Score: # nTopF1Score = oModel.AverageF1Score # oTopModelsForMetric[0] = oModel # # if oModel.Accuracy > nTopAccuracy: # nTopAccuracy = oModel.Accuracy # oTopModelsForMetric[1] = oModel # # if oModel.AverageRecall > nTopRecall: # nTopRecall = oModel.AverageRecall # oTopModelsForMetric[2] = oModel # # if oModel.AveragePrecision > nTopPrecision: # nTopPrecision = oModel.AveragePrecision # oTopModelsForMetric[3] = oModel # # print(" |__ [%s] Recall=%.2f; Precision=%.2f; F1 Score=%.2f" % ( # oModel.ModelName # ,oModel.AverageRecall * 100.0 # ,oModel.AveragePrecision * 100.0 # ,oModel.AverageF1Score * 100.0 # )) # # # # Consolidates the top performing models for all metrics # self.WinnerModels = [] # for oTopModel in oTopModelsForMetric: # if not (oTopModel in self.WinnerModels): # self.WinnerModels.append(oTopModel) # # self.DiscardedModels = [] # for oModel in self.EpochModels: # if not (oModel in self.WinnerModels): # self.DiscardedModels.append(oModel) # # # bNoModelsFound=False # if self.WinnerModels is None: # bNoModelsFound = True # else: # if (len(self.WinnerModels) == 0): # bNoModelsFound = True # elif (len(self.WinnerModels) == 1): # print(self.WinnerModels) # if self.WinnerModels[0] is None: # bNoModelsFound = True # self.NoModelsFound = bNoModelsFound # # if self.NoModelsFound: # print(" |__ No models were saved during the training process") # else: # self.PrintWinners() # # # #------------------------------------------------------------------------------------ # def PrintWinners(self): # for nIndex, oWinnerModel in enumerate(self.WinnerModels): # print(" |__ Winner #%i: [%s] Recall=%.2f; Precision=%.2f; F1 Score=%.2f" % ( # nIndex + 1 # ,oWinnerModel.ModelName # ,oWinnerModel.AverageRecall * 100.0 # ,oWinnerModel.AveragePrecision * 100.0 # ,oWinnerModel.AverageF1Score * 100.0 # )) # #------------------------------------------------------------------------------------ # #================================================================================================== # # # # # # # # # # # # # # # # # # # # # # # #================================================================================================== # class ClassificationEvaluator(object): # #/TEMP: Still in 0.1-ALPHA # PredictedClasses = None # ActualClasses = None # VerboseLevel=1 # # # ConfusionMatrix = None # ClassPrecision = None # ClassRecall = None # ClassF1Score = None # ClassSupport = None # # Accuracy = None # AveragePrecision=None # AverageRecall=None # AverageF1Score=None # AverageSupport=None # # WinnerAccuracy=[0.0]*2 # WinnerPrecision=[0.0]*2 # WinnerRecall=[0.0]*2 # WinnerF1Score=[0.0]*2 # # # #------------------------------------------------------------------------------------ # def __init__(self, p_nActualClasses=None, p_nPredictedClasses=None): # self.ActualClasses=p_nActualClasses # self.PredictedClasses=p_nPredictedClasses # #------------------------------------------------------------------------------------ # def Reset(self): # self.PredictedClasses = None # self.ActualClasses = None # # self.WinnerAccuracy[:]=0.0 # self.WinnerPrecision[:]=0.0 # self.WinnerRecall[:]=0.0 # self.WinnerF1Score[:]=0.0 # #------------------------------------------------------------------------------------ # def Evaluate(self, p_nActualClasses=None, p_nPredictedClasses=None, p_sModelName=None): # # Replaces the actual and predicted class numbers, if those provided in the method params # if p_nActualClasses is not None: # self.ActualClasses=p_nActualClasses # if p_nPredictedClasses is not None: # self.PredictedClasses=p_nPredictedClasses # # # In any case there should be actual and predicted class number # if (self.ActualClasses is None) or (self.PredictedClasses is None): # raise "Please provide actual and predicted class numbers" # # self.Accuracy=metrics.accuracy_score(self.ActualClasses, self.PredictedClasses) # self.ConfusionMatrix = metrics.confusion_matrix(self.ActualClasses, self.PredictedClasses) # # # class_recall = metrics.recall_score(val_true, val_pred, average=None) # # class_precision = metrics.precision_score(val_true, val_pred, average=None) # # class_f1_score = metrics.f1_score(val_true, val_pred, average=None) # self.ClassPrecision,self.ClassRecall,self.ClassF1Score,self.ClassSupport = metrics.precision_recall_fscore_support(self.ActualClasses, self.PredictedClasses, average=None) # # #labels=None, # #beta : float, 1.0 by default # # The strength of recall versus precision in the F-score. # self.AveragePrecision,self.AverageRecall, self.AverageF1Score, self.AverageSupport = metrics.precision_recall_fscore_support(self.ActualClasses, self.PredictedClasses, average='weighted') # # #print('validation accuracy:', val_accuracy) # if self.VerboseLevel == 2: # print('Accuracy', self.Accuracy) # print('Recall', self.ClassRecall) # print('Precision', self.ClassPrecision) # print('f1_score', self.ClassF1Score) # #np.savetxt(sRunName + '_precision.txt', class_precision, fmt='%10.7f', delimiter=';') # #np.savetxt(sRunName + '_recall.txt', class_recall, fmt='%10.7f', delimiter=';') # #np.savetxt(sRunName + '_f1_score.txt', class_f1_score, fmt='%10.7f', delimiter=';') # print('confusion_matrix') # # # self.ActualClasses=None # self.PredictedClasses=None # if p_sModelName is not None: # self.CheckForWinner(p_sModelName) # #------------------------------------------------------------------------------------ # def CheckForWinner(self, p_sModelName): # if self.Accuracy >= self.WinnerAccuracy[0]: # self.WinnerAccuracy[0] = self.Accuracy # self.WinnerAccuracy[1] = p_sModelName # # if self.AverageRecall >= self.WinnerRecall[0]: # self.WinnerRecall[0] = self.AverageRecall # self.WinnerRecall[1] = p_sModelName # # if self.AveragePrecision >= self.WinnerPrecision[0]: # self.WinnerPrecision[0] = self.AveragePrecision # self.WinnerPrecision[1] = p_sModelName # # if self.AverageF1Score >= self.WinnerF1Score[0]: # self.WinnerF1Score[0] = self.AverageF1Score # self.WinnerF1Score[1] = p_sModelName # # #------------------------------------------------------------------------------------ # def PrintWinners(self): # print("Best Accuracy %f, winner model is %s" % (self.WinnerAccuracy[0], self.WinnerAccuracy[1])) # print("Best Recall %f, winner model is %s" % (self.WinnerRecall[0], self.WinnerRecall[1])) # print("Best Precision %f, winner model is %s" % (self.WinnerPrecision[0], self.WinnerPrecision[1])) # print("Best F1 Score %f, winner model is %s" % (self.WinnerF1Score[0], self.WinnerF1Score[1])) # #------------------------------------------------------------------------------------ # def Save(self,p_sBaseFileName, p_bIsWritingJSON=False): # class_index = np.asarray( [i for i,item in enumerate(self.ClassRecall)] ) # # # Packs all into one neat file # acc_to_join=np.empty(self.ClassRecall.shape[0]) # acc_to_join[0]=self.Accuracy # acc_to_join[1]=self.AverageRecall # acc_to_join[2]=self.AveragePrecision # acc_to_join[3]=self.AverageF1Score # all_figures = np.hstack( # ( # acc_to_join[np.newaxis].T # ,self.ClassRecall[np.newaxis].T # ,self.ClassPrecision[np.newaxis].T # ,self.ClassF1Score[np.newaxis].T # ,np.asarray(class_index)[np.newaxis].T # ,self.ConfusionMatrix # ,self.ClassSupport[np.newaxis].T # )) # # sHeader = 'accuracy;recall;precision;f-score;class;' # for i,item in enumerate(class_index): # sHeader = sHeader + (str(item)) + ';' # sHeader = sHeader + 'support' # # #all_figures = np.vstack((np.asarray(sHeaders), all_figures)) # # # # Writes the file # if p_bIsWritingJSON: # with open(p_sBaseFileName + '.csv', "w") as text_file: # s = SimpleEncode(all_figures) # text_file.write(s) # #text_file.write("Purchase Amount: {0}".format(TotalAmount)) # else: # np.savetxt(p_sBaseFileName + '.csv',all_figures, fmt='%10.7f', delimiter=';', header=sHeader) # np.save(p_sBaseFileName + '.num', all_figures) # #------------------------------------------------------------------------------------ # #================================================================================================== # #
47.246842
199
0.483946
04552899b625998821b48549f0da96fef9f64326
375
java
Java
RandomExercises/Arrays.java
Majesticate/Fundamentals
c78531a8c8ae98215cccf8b31c82822b00580677
[ "MIT" ]
null
null
null
RandomExercises/Arrays.java
Majesticate/Fundamentals
c78531a8c8ae98215cccf8b31c82822b00580677
[ "MIT" ]
null
null
null
RandomExercises/Arrays.java
Majesticate/Fundamentals
c78531a8c8ae98215cccf8b31c82822b00580677
[ "MIT" ]
null
null
null
import java.util.ArrayList; public class Arrays { public static void main(String[] args) { ArrayList<String> food = new ArrayList<String>(); food.add("Pizza"); food.add("Ivan"); food.set(1, "Hello There"); for (int i = 0;i < food.size(); i++){ System.out.println(food.get(i)); } } }
19.736842
58
0.506667
04331daf00d26d50b9fa522183c66f494ad17efb
161,339
java
Java
SMBSync2/src/main/java/com/sentaroh/android/SMBSync2/SyncThreadArchiveFile.java
Sentaroh/SMBSync2
223acb2a512a43e7f0a7bc3994f06c77183b9d3b
[ "MIT" ]
119
2017-03-01T20:38:34.000Z
2022-03-18T07:50:41.000Z
SMBSync2/src/main/java/com/sentaroh/android/SMBSync2/SyncThreadArchiveFile.java
Sentaroh/SMBSync2
223acb2a512a43e7f0a7bc3994f06c77183b9d3b
[ "MIT" ]
208
2018-07-22T23:38:04.000Z
2022-02-22T12:38:08.000Z
SMBSync2/src/main/java/com/sentaroh/android/SMBSync2/SyncThreadArchiveFile.java
Sentaroh/SMBSync2
223acb2a512a43e7f0a7bc3994f06c77183b9d3b
[ "MIT" ]
37
2018-04-10T18:42:58.000Z
2022-03-20T13:36:37.000Z
package com.sentaroh.android.SMBSync2; /* The MIT License (MIT) Copyright (c) 2011 Sentaroh 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 android.media.ExifInterface; import android.os.Build; import com.drew.imaging.ImageMetadataReader; import com.drew.imaging.ImageProcessingException; import com.drew.metadata.Metadata; import com.drew.metadata.mp4.Mp4Directory; import com.sentaroh.android.SMBSync2.SyncThread.SyncThreadWorkArea; import com.sentaroh.android.Utilities.MiscUtil; import com.sentaroh.android.Utilities.SafFile; import com.sentaroh.android.Utilities.StringUtil; import com.sentaroh.jcifs.JcifsException; import com.sentaroh.jcifs.JcifsFile; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.TimeZone; import static com.sentaroh.android.SMBSync2.Constants.APP_SPECIFIC_DIRECTORY; import static com.sentaroh.android.SMBSync2.Constants.ARCHIVE_FILE_TYPE; import static com.sentaroh.android.SMBSync2.Constants.SMBSYNC2_CONFIRM_REQUEST_ARCHIVE_DATE_FROM_FILE; import static com.sentaroh.android.SMBSync2.Constants.SMBSYNC2_CONFIRM_REQUEST_MOVE; import static com.sentaroh.android.SMBSync2.Constants.SMBSYNC2_REPLACEABLE_KEYWORD_WEEK_DAY; import static com.sentaroh.android.SMBSync2.Constants.SMBSYNC2_REPLACEABLE_KEYWORD_WEEK_DAY_LONG; import static com.sentaroh.android.SMBSync2.Constants.SMBSYNC2_REPLACEABLE_KEYWORD_WEEK_NUMBER; public class SyncThreadArchiveFile { private static final Logger log= LoggerFactory.getLogger(SyncThreadArchiveFile.class); static public int syncArchiveInternalToInternal(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path, String to_path) { File mf = new File(from_path); int sync_result = buildArchiveListInternalToInternal(stwa, sti, from_path, from_path, mf, to_path, to_path); return sync_result; } static private String getTempFilePath(SyncThreadWorkArea stwa, SyncTaskItem sti, String to_path) { String tmp_path=""; if (to_path.startsWith("/storage/emulated/0")) tmp_path=stwa.gp.internalRootDirectory+"/"+APP_SPECIFIC_DIRECTORY+"/files/temp_file.tmp"; else { String[] dir_parts=to_path.split("/"); if (dir_parts.length>=3) { tmp_path="/"+dir_parts[1]+"/"+dir_parts[2]+"/"+APP_SPECIFIC_DIRECTORY+"/files/temp_file.tmp"; } } return tmp_path; } static private int moveFileInternalToInternal(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path, File mf, File tf, String to_path, String file_name) throws IOException { int sync_result=0; if (SyncThread.isValidFileNameLength(stwa, sti, tf.getName())) { if (SyncThread.sendConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_MOVE, from_path)) { if (!sti.isSyncTestMode()) { String dir=tf.getParent(); File lf_dir=new File(dir); if (!lf_dir.exists()) lf_dir.mkdirs(); String tmp_path=""; if (Build.VERSION.SDK_INT<=29) { tmp_path=stwa.gp.internalRootDirectory+"/"+APP_SPECIFIC_DIRECTORY+"/files/temp_file.tmp"; } else { tmp_path=getTempFilePath(stwa, sti, to_path); } File temp_file=new File(tmp_path); sync_result= copyFile(stwa, sti, new FileInputStream(mf), new FileOutputStream(temp_file), from_path, to_path, file_name, sti.isSyncOptionUseSmallIoBuffer()); if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) { temp_file.setLastModified(mf.lastModified()); temp_file.renameTo(tf); } } if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) { stwa.totalCopyCount++; SyncThread.showArchiveMsg(stwa, false, sti.getSyncTaskName(), "I", from_path, to_path, mf.getName(), tf.getName(), "", stwa.msgs_mirror_task_file_archived); if (!sti.isSyncTestMode()) { tf.setLastModified(mf.lastModified()); mf.delete(); stwa.totalDeleteCount++; SyncThread.scanMediaFile(stwa, mf.getPath()); SyncThread.scanMediaFile(stwa, tf.getPath()); } } } else { stwa.totalIgnoreCount++; SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "I", to_path, mf.getName(), "", stwa.context.getString(R.string.msgs_mirror_confirm_move_cancel)); } } return sync_result; } static private int archiveFileInternalToInternal(SyncThreadWorkArea stwa, SyncTaskItem sti, File[] children, String from_path, String to_path) throws IOException { int file_seq_no=0, sync_result=0; ArrayList<ArchiveFileListItem>fl=buildLocalFileList(stwa, sti, children); for(ArchiveFileListItem item:fl) { if (!stwa.gp.syncThreadCtrl.isEnabled()) { sync_result = SyncTaskItem.SYNC_STATUS_CANCEL; break; } if (sti.isSyncOptionIgnoreFileSize0ByteFile() && item.file_size==0) { stwa.util.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName()+" File was ignored, Reason=(File size equals 0), FP="+item.full_path); continue; } if (!item.date_from_exif && sti.isSyncOptionConfirmNotExistsExifDate()) { if (!SyncThread.sendArchiveConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_ARCHIVE_DATE_FROM_FILE, item.full_path)) { stwa.totalIgnoreCount++; SyncThread.showMsg(stwa, false, sti.getSyncTaskName(), "I", item.full_path, item.file_name, "", stwa.context.getString(R.string.msgs_mirror_confirm_archive_date_time_from_file_cancel)); continue; } } if (!SyncThread.isValidFileDirectoryName(stwa, sti, item.full_path)) { if (sti.isSyncOptionIgnoreDirectoriesOrFilesThatContainUnusableCharacters()) return sync_result; else return SyncTaskItem.SYNC_STATUS_ERROR; } file_seq_no++; String to_file_name="", to_file_ext="", to_file_seqno=""; if (item.file_name.lastIndexOf(".")>=0) { to_file_ext=item.file_name.substring(item.file_name.lastIndexOf(".")); to_file_name=item.file_name.substring(0,item.file_name.lastIndexOf(".")); } else { to_file_name=item.file_name; } to_file_seqno=getFileSeqNumber(stwa, sti, file_seq_no); String converted_to_path=buildArchiveTargetDirectoryName(stwa, sti, to_path, item); if (!sti.isArchiveUseRename()) { File tf=new File(converted_to_path+"/"+item.file_name); if (tf.exists()) { String new_name=createArchiveLocalNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+to_file_name, to_file_ext) ; if (new_name.equals("")) { stwa.util.addLogMsg("E","Archive sequence number overflow error."); sync_result=SyncTaskItem.SYNC_STATUS_ERROR; break; } else { tf=new File(new_name); sync_result= moveFileInternalToInternal(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(), new_name); } } else { sync_result= moveFileInternalToInternal(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(), to_file_name); } } else { to_file_name=buildArchiveFileName(stwa, sti, item, to_file_name); String temp_dir= buildArchiveSubDirectoryName(stwa, sti, item); File tf=new File(converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno+to_file_ext); if (tf.exists()) { String new_name=createArchiveLocalNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno,to_file_ext) ; if (new_name.equals("")) { stwa.util.addLogMsg("E","Archive sequence number overflow error."); sync_result=SyncTaskItem.SYNC_STATUS_ERROR; break; } else { tf=new File(new_name); sync_result= moveFileInternalToInternal(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(), new_name); } } else { sync_result= moveFileInternalToInternal(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(), converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno+to_file_ext); } } } return sync_result; } static private int buildArchiveListInternalToInternal(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_base, String from_path, File mf, String to_base, String to_path) { stwa.util.addDebugMsg(2, "I", CommonUtilities.getExecutedMethodName(), " entered, from=", from_path, ", to=", to_path); int sync_result = 0; stwa.jcifsNtStatusCode=0; File tf; try { String t_from_path = from_path.substring(from_base.length()); if (t_from_path.startsWith("/")) t_from_path = t_from_path.substring(1); if (mf.exists()) { if (mf.isDirectory()) { // Directory copy if (!SyncThread.isHiddenDirectory(stwa, sti, mf) && SyncThread.isDirectoryToBeProcessed(stwa, t_from_path)) { if (mf.canRead()) { // if (sti.isSyncOptionSyncEmptyDirectory()) { // SyncThread.createDirectoryToInternalStorage(stwa, sti, to_path); // } File[] children = mf.listFiles(); if (children != null) { sync_result=archiveFileInternalToInternal(stwa, sti, children, from_path, to_path); if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) { for (File element : children) { if (sync_result == SyncTaskItem.SYNC_STATUS_SUCCESS) { if (!element.getName().equals(".android_secure")) { if (!from_path.equals(to_path)) { if (element.isDirectory()) { if (sti.isSyncOptionSyncSubDirectory()) { sync_result = buildArchiveListInternalToInternal(stwa, sti, from_base, from_path + "/" + element.getName(), element, to_base, to_path + "/" + element.getName()); } else { stwa.util.addDebugMsg(1, "I", "Sub directory was not sync, dir=", from_path); } } } else { stwa.util.addDebugMsg(1, "W", String.format(stwa.context.getString(R.string.msgs_mirror_same_directory_ignored), from_path, "/", element.getName())); } } } else { return sync_result; } if (!stwa.gp.syncThreadCtrl.isEnabled()) { sync_result = SyncTaskItem.SYNC_STATUS_CANCEL; break; } } } } else { stwa.util.addDebugMsg(1, "I", "Directory was null, dir=" + mf.getPath()); } } else { stwa.totalIgnoreCount++; SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "W", "", "", stwa.context.getString(R.string.msgs_mirror_task_directory_ignored_because_can_not_read, from_path + "/" + mf.getName())); } } } } else { stwa.gp.syncThreadCtrl.setThreadMessage(stwa.context.getString(R.string.msgs_mirror_task_master_not_found) + " " + from_path); SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "E", "", "", stwa.gp.syncThreadCtrl.getThreadMessage()); return SyncTaskItem.SYNC_STATUS_ERROR; } } catch (IOException e) { putExceptionMsg(stwa, sti, from_path, to_path, e); return SyncTaskItem.SYNC_STATUS_ERROR; } return sync_result; } static public int syncArchiveInternalToExternal(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path, String to_path) { File mf = new File(from_path); int sync_result = buildArchiveListInternalToExternal(stwa, sti, from_path, from_path, mf, to_path, to_path); return sync_result; } static private int moveFileInternalToExternal(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path, File mf, File tf, String to_path, String file_name) throws IOException { int result=0; if (SyncThread.isValidFileNameLength(stwa, sti, tf.getName())) { if (Build.VERSION.SDK_INT>=24) result= moveFileInternalToExternalSetLastMod(stwa, sti, from_path, mf, tf, to_path, file_name); else result= moveFileInternalToExternalUnsetLastMod(stwa, sti, from_path, mf, tf, to_path, file_name); } return result; } static private int moveFileInternalToExternalUnsetLastMod(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path, File mf, File tf, String to_path, String file_name) throws IOException { int sync_result=0; if (SyncThread.sendConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_MOVE, from_path)) { if (!sti.isSyncTestMode()) { SyncThread.createDirectoryToExternalStorage(stwa, sti, tf.getParent()); SafFile t_df = SyncThread.createSafFile(stwa, sti, to_path, false); if (t_df == null) { return SyncTaskItem.SYNC_STATUS_ERROR; } sync_result= copyFile(stwa, sti, new FileInputStream(mf), stwa.context.getContentResolver().openOutputStream(t_df.getUri()), from_path, to_path, file_name, sti.isSyncOptionUseSmallIoBuffer()); } if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) { stwa.totalCopyCount++; SyncThread.showArchiveMsg(stwa, false, sti.getSyncTaskName(), "I", from_path, to_path, mf.getName(), tf.getName(), "", stwa.msgs_mirror_task_file_archived); if (!sti.isSyncTestMode()) { mf.delete(); stwa.totalDeleteCount++; SyncThread.scanMediaFile(stwa, mf.getPath()); SyncThread.scanMediaFile(stwa, tf.getPath()); } } } else { stwa.totalIgnoreCount++; SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "I", to_path, mf.getName(), "", stwa.context.getString(R.string.msgs_mirror_confirm_move_cancel)); } return sync_result; } static private boolean isSdcardPath(SyncThreadWorkArea stwa,String fp) { if (fp.startsWith(stwa.gp.safMgr.getSdcardRootPath())) return true; else return false; } static private int moveFileInternalToExternalSetLastMod(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path, File mf, File tf, String to_path, String file_name) throws IOException { int sync_result=0; if (SyncThread.sendConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_MOVE, from_path)) { if (!sti.isSyncTestMode()) { SyncThread.createDirectoryToExternalStorage(stwa, sti, tf.getParent()); String temp_path=isSdcardPath(stwa,to_path)? stwa.gp.safMgr.getSdcardRootPath()+"/"+APP_SPECIFIC_DIRECTORY+"/cache/archive_temp.tmp": stwa.gp.safMgr.getUsbRootPath()+"/"+APP_SPECIFIC_DIRECTORY+"/cache/archive_temp.tmp"; File temp_file=new File(temp_path); OutputStream os=null; try { os=new FileOutputStream(temp_file); } catch (Exception e) { SafFile sf=SyncThread.createSafFile(stwa, sti, temp_file.getPath(), false); os=stwa.context.getContentResolver().openOutputStream(sf.getUri()); } SafFile to_saf=SyncThread.createSafFile(stwa, sti, tf.getPath()); if (to_saf == null) return SyncTaskItem.SYNC_STATUS_ERROR; to_saf.deleteIfExists(); sync_result= copyFile(stwa, sti, new FileInputStream(mf), os, from_path, to_path, file_name, sti.isSyncOptionUseSmallIoBuffer()); temp_file.setLastModified(mf.lastModified()); // SyncThread.deleteTempMediaStoreItem(stwa, temp_file); SafFile from_saf = SyncThread.createSafFile(stwa, sti, temp_file.getPath()); if (from_saf == null) return SyncTaskItem.SYNC_STATUS_ERROR; from_saf.moveTo(to_saf); } if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) { stwa.totalCopyCount++; SyncThread.showArchiveMsg(stwa, false, sti.getSyncTaskName(), "I", from_path, to_path, mf.getName(), tf.getName(), "", stwa.msgs_mirror_task_file_archived); if (!sti.isSyncTestMode()) { mf.delete(); stwa.totalDeleteCount++; SyncThread.scanMediaFile(stwa, mf.getPath()); SyncThread.scanMediaFile(stwa, tf.getPath()); } } } else { stwa.totalIgnoreCount++; SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "I", to_path, mf.getName(), "", stwa.context.getString(R.string.msgs_mirror_confirm_move_cancel)); } return sync_result; } static private int archiveFileInternalToExternal(SyncThreadWorkArea stwa, SyncTaskItem sti, File[] children, String from_path, String to_path) throws IOException { int file_seq_no=0, sync_result=0; ArrayList<ArchiveFileListItem>fl=buildLocalFileList(stwa, sti, children); for(ArchiveFileListItem item:fl) { if (!stwa.gp.syncThreadCtrl.isEnabled()) { sync_result = SyncTaskItem.SYNC_STATUS_CANCEL; break; } if (sti.isSyncOptionIgnoreFileSize0ByteFile() && item.file_size==0) { stwa.util.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName()+" File was ignored, Reason=(File size equals 0), FP="+item.full_path); continue; } if (!item.date_from_exif && sti.isSyncOptionConfirmNotExistsExifDate()) { if (!SyncThread.sendArchiveConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_ARCHIVE_DATE_FROM_FILE, item.full_path)) { stwa.totalIgnoreCount++; SyncThread.showMsg(stwa, false, sti.getSyncTaskName(), "I", item.full_path, item.file_name, "", stwa.context.getString(R.string.msgs_mirror_confirm_archive_date_time_from_file_cancel)); continue; } } if (!SyncThread.isValidFileDirectoryName(stwa, sti, item.full_path)) { if (sti.isSyncOptionIgnoreDirectoriesOrFilesThatContainUnusableCharacters()) return sync_result; else return SyncTaskItem.SYNC_STATUS_ERROR; } file_seq_no++; String to_file_name="", to_file_ext="", to_file_seqno=""; if (item.file_name.lastIndexOf(".")>=0) { to_file_ext=item.file_name.substring(item.file_name.lastIndexOf(".")); to_file_name=item.file_name.substring(0,item.file_name.lastIndexOf(".")); } else { to_file_name=item.file_name; } to_file_seqno=getFileSeqNumber(stwa, sti, file_seq_no); String converted_to_path=buildArchiveTargetDirectoryName(stwa, sti, to_path, item); if (!sti.isArchiveUseRename()) { File tf=new File(converted_to_path+"/"+item.file_name); if (tf.exists()) { String new_name=createArchiveLocalNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+to_file_name, to_file_ext) ; if (new_name.equals("")) { stwa.util.addLogMsg("E","Archive sequence number overflow error."); sync_result=SyncTaskItem.SYNC_STATUS_ERROR; break; } else { tf=new File(new_name); sync_result= moveFileInternalToExternal(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(), new_name); } } else { sync_result= moveFileInternalToExternal(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(), to_file_name); } } else { to_file_name=buildArchiveFileName(stwa, sti, item, to_file_name); String temp_dir= buildArchiveSubDirectoryName(stwa, sti, item); File tf=new File(converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno+to_file_ext); if (tf.exists()) { String new_name=createArchiveLocalNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno,to_file_ext) ; if (new_name.equals("")) { stwa.util.addLogMsg("E","Archive sequence number overflow error."); sync_result=SyncTaskItem.SYNC_STATUS_ERROR; break; } else { tf=new File(new_name); sync_result= moveFileInternalToExternal(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(), new_name); } } else { sync_result= moveFileInternalToExternal(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(), converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno+to_file_ext); } } } return sync_result; } static private int buildArchiveListInternalToExternal(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_base, String from_path, File mf, String to_base, String to_path) { stwa.util.addDebugMsg(2, "I", CommonUtilities.getExecutedMethodName(), " entered, from=", from_path, ", to=", to_path); int sync_result = 0; if (!SyncThread.isValidFileDirectoryName(stwa, sti, from_path)) { if (sti.isSyncOptionIgnoreDirectoriesOrFilesThatContainUnusableCharacters()) return sync_result; else return SyncTaskItem.SYNC_STATUS_ERROR; } stwa.jcifsNtStatusCode=0; File tf; try { if (mf.exists()) { String t_from_path = from_path.substring(from_base.length()); if (t_from_path.startsWith("/")) t_from_path = t_from_path.substring(1); if (mf.isDirectory()) { // Directory copy if (!SyncThread.isHiddenDirectory(stwa, sti, mf) && SyncThread.isDirectoryToBeProcessed(stwa, t_from_path)) { if (mf.canRead()) { // if (sti.isSyncOptionSyncEmptyDirectory()) { // SyncThread.createDirectoryToExternalStorage(stwa, sti, to_path); // } File[] children = mf.listFiles(); sync_result=archiveFileInternalToExternal(stwa, sti, children, from_path, to_path); if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) { if (children != null) { for (File element : children) { if (sync_result == SyncTaskItem.SYNC_STATUS_SUCCESS) { if (!element.getName().equals(".android_secure")) { if (element.isDirectory()) { if (sti.isSyncOptionSyncSubDirectory()) { sync_result = buildArchiveListInternalToExternal(stwa, sti, from_base, from_path + "/" + element.getName(), element, to_base, to_path + "/" + element.getName()); } else { if (stwa.gp.settingDebugLevel >= 1) stwa.util.addDebugMsg(1, "I", "Sub directory was not sync, dir=" + from_path); } } } } else { return sync_result; } if (!stwa.gp.syncThreadCtrl.isEnabled()) { sync_result = SyncTaskItem.SYNC_STATUS_CANCEL; break; } } } else { stwa.util.addDebugMsg(1, "I", "Directory was null, dir=" + mf.getPath()); } } } else { stwa.totalIgnoreCount++; SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "W", "", "", stwa.context.getString(R.string.msgs_mirror_task_directory_ignored_because_can_not_read, from_path + "/" + mf.getName())); } } } } else { stwa.gp.syncThreadCtrl.setThreadMessage(stwa.context.getString(R.string.msgs_mirror_task_master_not_found) + " " + from_path); SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "E", "", "", stwa.gp.syncThreadCtrl.getThreadMessage()); return SyncTaskItem.SYNC_STATUS_ERROR; } } catch (IOException e) { putExceptionMsg(stwa, sti, from_path, to_path, e); return SyncTaskItem.SYNC_STATUS_ERROR; } return sync_result; } static public int syncArchiveInternalToSmb(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path, String to_path) { File mf = new File(from_path); int sync_result = buildArchiveListInternalToSmb(stwa, sti, from_path, from_path, mf, to_path, to_path); return sync_result; } static private int archiveFileInternalToSmb(SyncThreadWorkArea stwa, SyncTaskItem sti, File[] children, String from_path, String to_path) throws IOException, JcifsException { int file_seq_no=0, sync_result=0; ArrayList<ArchiveFileListItem>fl=buildLocalFileList(stwa, sti, children); for(ArchiveFileListItem item:fl) { if (!stwa.gp.syncThreadCtrl.isEnabled()) { sync_result = SyncTaskItem.SYNC_STATUS_CANCEL; break; } if (sti.isSyncOptionIgnoreFileSize0ByteFile() && item.file_size==0) { stwa.util.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName()+" File was ignored, Reason=(File size equals 0), FP="+item.full_path); continue; } if (!item.date_from_exif && sti.isSyncOptionConfirmNotExistsExifDate()) { if (!SyncThread.sendArchiveConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_ARCHIVE_DATE_FROM_FILE, item.full_path)) { stwa.totalIgnoreCount++; SyncThread.showMsg(stwa, false, sti.getSyncTaskName(), "I", item.full_path, item.file_name, "", stwa.context.getString(R.string.msgs_mirror_confirm_archive_date_time_from_file_cancel)); continue;//Archive cancelled } } if (!SyncThread.isValidFileDirectoryName(stwa, sti, item.full_path)) { if (sti.isSyncOptionIgnoreDirectoriesOrFilesThatContainUnusableCharacters()) return sync_result; else return SyncTaskItem.SYNC_STATUS_ERROR; } file_seq_no++; String to_file_name="", to_file_ext="", to_file_seqno=""; if (item.file_name.lastIndexOf(".")>=0) { to_file_ext=item.file_name.substring(item.file_name.lastIndexOf(".")); to_file_name=item.file_name.substring(0,item.file_name.lastIndexOf(".")); } else { to_file_name=item.file_name; } to_file_seqno=getFileSeqNumber(stwa, sti, file_seq_no); String converted_to_path=buildArchiveTargetDirectoryName(stwa, sti, to_path, item); if (!sti.isArchiveUseRename()) {//Renameしない JcifsFile jf=new JcifsFile(converted_to_path+"/"+item.file_name, stwa.targetAuth); if (jf.exists()) { String new_name=createArchiveSmbNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+to_file_name, to_file_ext) ; if (new_name.equals("")) { stwa.util.addLogMsg("E","Archive sequence number overflow error."); sync_result=SyncTaskItem.SYNC_STATUS_ERROR; break; } else { jf=new JcifsFile(new_name, stwa.targetAuth); sync_result= moveFileInternalToSmb(stwa, sti, item.full_path, (File)item.file, jf, jf.getPath(), to_file_name); } } else { sync_result= moveFileInternalToSmb(stwa, sti, item.full_path, (File)item.file, jf, jf.getPath(), to_file_name); } } else {//Renameする to_file_name=buildArchiveFileName(stwa, sti, item, to_file_name); String temp_dir= buildArchiveSubDirectoryName(stwa, sti, item); JcifsFile jf=new JcifsFile(converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno+to_file_ext, stwa.targetAuth); if (jf.exists()) { String new_name=createArchiveSmbNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno,to_file_ext) ; if (new_name.equals("")) { stwa.util.addLogMsg("E","Archive sequence number overflow error."); sync_result=SyncTaskItem.SYNC_STATUS_ERROR; break; } else { jf=new JcifsFile(new_name, stwa.targetAuth); sync_result= moveFileInternalToSmb(stwa, sti, item.full_path, (File)item.file, jf, jf.getPath(), to_file_name); } } else { sync_result= moveFileInternalToSmb(stwa, sti, item.full_path, (File)item.file, jf, jf.getPath(), to_file_name); } } } return sync_result; } static private int buildArchiveListInternalToSmb(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_base, String from_path, File mf, String to_base, String to_path) { stwa.util.addDebugMsg(2, "I", CommonUtilities.getExecutedMethodName(), " entered, from=", from_path, ", to=", to_path); stwa.jcifsNtStatusCode=0; int sync_result = 0; if (!SyncThread.isValidFileDirectoryName(stwa, sti, from_path)) { if (sti.isSyncOptionIgnoreDirectoriesOrFilesThatContainUnusableCharacters()) return sync_result; else return SyncTaskItem.SYNC_STATUS_ERROR; } JcifsFile tf; try { if (mf.exists()) { String t_from_path = from_path.substring(from_base.length()); if (t_from_path.startsWith("/")) t_from_path = t_from_path.substring(1); if (mf.isDirectory()) { // Directory copy if (!SyncThread.isHiddenDirectory(stwa, sti, mf) && SyncThread.isDirectoryToBeProcessed(stwa, t_from_path)) { if (mf.canRead()) { // if (sti.isSyncOptionSyncEmptyDirectory()) { // SyncThread.createDirectoryToSmb(stwa, sti, to_path, stwa.targetAuth); // } File[] children = mf.listFiles(); if (children != null) { sync_result=archiveFileInternalToSmb(stwa, sti, children, from_path, to_path); if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) { for (File element : children) { if (element.isDirectory()) { if (!element.getName().equals(".android_secure")) { while (stwa.syncTaskRetryCount > 0) { if (sti.isSyncOptionSyncSubDirectory()) { sync_result = buildArchiveListInternalToSmb(stwa, sti, from_base, from_path + "/" + element.getName(), element, to_base, to_path + "/" + element.getName()); } if (sync_result == SyncTaskItem.SYNC_STATUS_ERROR && SyncThread.isRetryRequiredError(stwa.jcifsNtStatusCode)) { stwa.syncTaskRetryCount--; if (stwa.syncTaskRetryCount > 0) sync_result = waitRetryInterval(stwa); if (sync_result == SyncTaskItem.SYNC_STATUS_CANCEL) break; } else { stwa.syncTaskRetryCount = stwa.syncTaskRetryCountOriginal; break; } } if (sync_result != SyncTaskItem.SYNC_STATUS_SUCCESS) break; } if (!stwa.gp.syncThreadCtrl.isEnabled()) { sync_result = SyncTaskItem.SYNC_STATUS_CANCEL; break; } } } } } else { stwa.util.addDebugMsg(1, "I", "Directory was null, dir=" + mf.getPath()); } } else { stwa.totalIgnoreCount++; SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "W", "", "", stwa.context.getString(R.string.msgs_mirror_task_directory_ignored_because_can_not_read, from_path + "/" + mf.getName())); } } } } else { stwa.gp.syncThreadCtrl.setThreadMessage(stwa.context.getString(R.string.msgs_mirror_task_master_not_found) + " " + from_path); SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "E", "", "", stwa.gp.syncThreadCtrl.getThreadMessage()); return SyncTaskItem.SYNC_STATUS_ERROR; } } catch (IOException e) { putExceptionMsg(stwa, sti, from_path, to_path, e); return SyncTaskItem.SYNC_STATUS_ERROR; } catch (JcifsException e) { putExceptionMsg(stwa, sti, from_path, to_path, e); return SyncTaskItem.SYNC_STATUS_ERROR; } return sync_result; } static private void putExceptionMsg(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path, String to_path, Exception e) { SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "E", "", "", CommonUtilities.getExecutedMethodName() + " From=" + from_path + ", To=" + to_path); SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "E", "", "", e.getMessage()); String sugget_msg=SyncTaskUtil.getJcifsErrorSugestionMessage(stwa.context, MiscUtil.getStackTraceString(e)); if (!sugget_msg.equals("")) SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "E", "", "", sugget_msg); if (e.getCause()!=null) SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "I", "", "", e.getCause().toString()); if (e instanceof JcifsException) stwa.jcifsNtStatusCode=((JcifsException)e).getNtStatus(); SyncThread.printStackTraceElement(stwa, e.getStackTrace()); stwa.gp.syncThreadCtrl.setThreadMessage(e.getMessage()); } static private String createArchiveSmbNewFilePath(SyncThreadWorkArea stwa, SyncTaskItem sti, String path, String fn, String fe) throws MalformedURLException, JcifsException { String result=""; for (int i=1;i<100000;i++) { String suffix_base=String.format("_%d", i); JcifsFile jf=new JcifsFile(fn+suffix_base+fe, stwa.targetAuth); if (!jf.exists()) { result=fn+suffix_base+fe; break; } } return result; } static private String createArchiveLocalNewFilePath(SyncThreadWorkArea stwa, SyncTaskItem sti, String path, String fn, String fe) { String result=""; for (int i=1;i<100000;i++) { String suffix_base=String.format("_%d", i); File jf=new File(fn+suffix_base+fe); if (!jf.exists()) { result=fn+suffix_base+fe; break; } } return result; } static private int moveFileInternalToSmb(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path, File mf, JcifsFile tf, String to_path, String file_name) throws IOException, JcifsException { int sync_result=0; if (SyncThread.isValidFileNameLength(stwa, sti, tf.getName())) { if (SyncThread.sendConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_MOVE, from_path)) { if (!sti.isSyncTestMode()) { String dir=tf.getParent(); JcifsFile jf_dir=new JcifsFile(dir,stwa.targetAuth); if (!jf_dir.exists()) jf_dir.mkdirs(); while (stwa.syncTaskRetryCount > 0) { sync_result= copyFile(stwa, sti, new FileInputStream(mf), tf.getOutputStream(), from_path, to_path, tf.getName(), sti.isSyncOptionUseSmallIoBuffer()); if (sync_result == SyncTaskItem.SYNC_STATUS_ERROR && SyncThread.isRetryRequiredError(stwa.jcifsNtStatusCode)) { stwa.syncTaskRetryCount--; if (stwa.syncTaskRetryCount > 0) sync_result = waitRetryInterval(stwa); if (sync_result == SyncTaskItem.SYNC_STATUS_CANCEL) break; } else { stwa.syncTaskRetryCount = stwa.syncTaskRetryCountOriginal; break; } } } if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) { stwa.totalCopyCount++; SyncThread.showArchiveMsg(stwa, false, sti.getSyncTaskName(), "I", from_path, to_path, mf.getName(), tf.getName(), "", stwa.msgs_mirror_task_file_archived); if (!sti.isSyncTestMode()) { try { tf.setLastModified(mf.lastModified()); } catch(JcifsException e) { // nop } mf.delete(); stwa.totalDeleteCount++; SyncThread.scanMediaFile(stwa, mf.getPath()); } } } else { stwa.totalIgnoreCount++; SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "I", to_path, mf.getName(), "", stwa.context.getString(R.string.msgs_mirror_confirm_move_cancel)); } } return sync_result; } static public int syncArchiveExternalToInternal(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path, String to_path) { File mf = new File(from_path); int sync_result = buildArchiveListExternalToInternal(stwa, sti, from_path, from_path, mf, to_path, to_path); return sync_result; } static private int moveFileExternalToInternal(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path, File mf, File tf, String to_path, String file_name) throws IOException { int sync_result=0; if (SyncThread.isValidFileNameLength(stwa, sti, tf.getName())) { if (SyncThread.sendConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_MOVE, from_path)) { SafFile m_df =SyncThread.createSafFile(stwa, sti, from_path, false); if (!sti.isSyncTestMode()) { SyncThread.createDirectoryToInternalStorage(stwa, sti, tf.getParent()); String temp_path=isSdcardPath(stwa,to_path)? stwa.gp.safMgr.getSdcardRootPath()+"/"+APP_SPECIFIC_DIRECTORY+"/cache/temp_file.tmp": stwa.gp.safMgr.getUsbRootPath()+ "/"+APP_SPECIFIC_DIRECTORY+"/cache/temp_file.tmp"; File temp_file=new File(temp_path); sync_result= copyFile(stwa, sti, stwa.context.getContentResolver().openInputStream(m_df.getUri()), new FileOutputStream(temp_file), from_path, to_path, file_name, sti.isSyncOptionUseSmallIoBuffer()); if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) { temp_file.setLastModified(mf.lastModified()); temp_file.renameTo(tf); } } if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) { stwa.totalCopyCount++; SyncThread.showArchiveMsg(stwa, false, sti.getSyncTaskName(), "I", from_path, to_path, mf.getName(), tf.getName(), "", stwa.msgs_mirror_task_file_archived); if (!sti.isSyncTestMode()) { m_df.delete(); stwa.totalDeleteCount++; SyncThread.scanMediaFile(stwa, from_path); SyncThread.scanMediaFile(stwa, tf.getPath()); } } } else { stwa.totalIgnoreCount++; SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "I", to_path, mf.getName(), "", stwa.context.getString(R.string.msgs_mirror_confirm_move_cancel)); } } return sync_result; } static private int archiveFileExternalToInternal(SyncThreadWorkArea stwa, SyncTaskItem sti, File[] children, String from_path, String to_path) throws IOException { int file_seq_no=0, sync_result=0; ArrayList<ArchiveFileListItem>fl= buildSafFileList(stwa, sti, children); for(ArchiveFileListItem item:fl) { if (!stwa.gp.syncThreadCtrl.isEnabled()) { sync_result = SyncTaskItem.SYNC_STATUS_CANCEL; break; } if (sti.isSyncOptionIgnoreFileSize0ByteFile() && item.file_size==0) { stwa.util.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName()+" File was ignored, Reason=(File size equals 0), FP="+item.full_path); continue; } if (!item.date_from_exif && sti.isSyncOptionConfirmNotExistsExifDate()) { if (!SyncThread.sendArchiveConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_ARCHIVE_DATE_FROM_FILE, item.full_path)) { stwa.totalIgnoreCount++; SyncThread.showMsg(stwa, false, sti.getSyncTaskName(), "I", item.full_path, item.file_name, "", stwa.context.getString(R.string.msgs_mirror_confirm_archive_date_time_from_file_cancel)); continue; } } if (!SyncThread.isValidFileDirectoryName(stwa, sti, item.full_path)) { if (sti.isSyncOptionIgnoreDirectoriesOrFilesThatContainUnusableCharacters()) return sync_result; else return SyncTaskItem.SYNC_STATUS_ERROR; } file_seq_no++; String to_file_name="", to_file_ext="", to_file_seqno=""; if (item.file_name.lastIndexOf(".")>=0) { to_file_ext=item.file_name.substring(item.file_name.lastIndexOf(".")); to_file_name=item.file_name.substring(0,item.file_name.lastIndexOf(".")); } else { to_file_name=item.file_name; } to_file_seqno=getFileSeqNumber(stwa, sti, file_seq_no); String converted_to_path=buildArchiveTargetDirectoryName(stwa, sti, to_path, item); if (!sti.isArchiveUseRename()) { File tf=new File(converted_to_path+"/"+item.file_name); if (tf.exists()) { String new_name=createArchiveLocalNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+to_file_name, to_file_ext) ; if (new_name.equals("")) { stwa.util.addLogMsg("E","Archive sequence number overflow error."); sync_result=SyncTaskItem.SYNC_STATUS_ERROR; break; } else { tf=new File(new_name); sync_result= moveFileExternalToInternal(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(), new_name); } } else { sync_result= moveFileExternalToInternal(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(), to_file_name); } } else { to_file_name=buildArchiveFileName(stwa, sti, item, to_file_name); String temp_dir= buildArchiveSubDirectoryName(stwa, sti, item); File tf=new File(converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno+to_file_ext); if (tf.exists()) { String new_name=createArchiveLocalNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno,to_file_ext) ; if (new_name.equals("")) { stwa.util.addLogMsg("E","Archive sequence number overflow error."); sync_result=SyncTaskItem.SYNC_STATUS_ERROR; break; } else { tf=new File(new_name); sync_result= moveFileExternalToInternal(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(), new_name); } } else { sync_result= moveFileExternalToInternal(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(), converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno+to_file_ext); } } } return sync_result; } static private int buildArchiveListExternalToInternal(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_base, String from_path, File mf, String to_base, String to_path) { stwa.util.addDebugMsg(2, "I", CommonUtilities.getExecutedMethodName(), " entered, from=", from_path, ", to=", to_path); int sync_result = 0; stwa.jcifsNtStatusCode=0; File tf; try { if (mf.exists()) { String t_from_path = from_path.substring(from_base.length()); if (t_from_path.startsWith("/")) t_from_path = t_from_path.substring(1); if (mf.isDirectory()) { // Directory copy if (!SyncThread.isHiddenDirectory(stwa, sti, mf) && SyncThread.isDirectoryToBeProcessed(stwa, t_from_path)) { if (mf.canRead()) { if (sti.isSyncOptionSyncEmptyDirectory()) { SyncThread.createDirectoryToInternalStorage(stwa, sti, to_path); } File[] children = mf.listFiles(); if (children != null) { sync_result=archiveFileExternalToInternal(stwa, sti, children, from_path, to_path); if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) { for (File element : children) { if (sync_result == SyncTaskItem.SYNC_STATUS_SUCCESS) { if (!element.getName().equals(".android_secure")) { if (element.isDirectory()) { if (sti.isSyncOptionSyncSubDirectory()) { sync_result = buildArchiveListExternalToInternal(stwa, sti, from_base, from_path + "/" + element.getName(), element, to_base, to_path + "/" + element.getName()); } else { stwa.util.addDebugMsg(1, "I", "Sub directory was not sync, dir=", from_path); } } } } else { return sync_result; } if (!stwa.gp.syncThreadCtrl.isEnabled()) { sync_result = SyncTaskItem.SYNC_STATUS_CANCEL; break; } } } } else { stwa.util.addDebugMsg(1, "I", "Directory was null, dir=" + mf.getPath()); } } else { stwa.totalIgnoreCount++; SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "W", "", "", stwa.context.getString(R.string.msgs_mirror_task_directory_ignored_because_can_not_read, from_path + "/" + mf.getName())); } } } } else { stwa.gp.syncThreadCtrl.setThreadMessage(stwa.context.getString(R.string.msgs_mirror_task_master_not_found) + " " + from_path); SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "E", "", "", stwa.gp.syncThreadCtrl.getThreadMessage()); return SyncTaskItem.SYNC_STATUS_ERROR; } } catch (IOException e) { putExceptionMsg(stwa, sti, from_path, to_path, e); return SyncTaskItem.SYNC_STATUS_ERROR; } return sync_result; } static public int syncArchiveExternalToExternal(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path, String to_path) { File mf = new File(from_path); int sync_result = buildArchiveListExternalToExternal(stwa, sti, from_path, from_path, mf, to_path, to_path); return sync_result; } static private int moveFileExternalToExternal(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path, File mf, File tf, String to_path, String file_name) throws IOException { int result=0; if (SyncThread.isValidFileNameLength(stwa, sti, tf.getName())) { if (Build.VERSION.SDK_INT>=24) result= moveFileExternalToExternalSetLastMod(stwa, sti, from_path, mf, tf, to_path, file_name); else result= moveFileExternalToExternalUnsetLastMod(stwa, sti, from_path, mf, tf, to_path, file_name); } return result; } static private int moveFileExternalToExternalUnsetLastMod(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path, File mf, File tf, String to_path, String file_name) throws IOException { int sync_result=0; if (SyncThread.sendArchiveConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_MOVE, from_path)) { SafFile m_df =SyncThread.createSafFile(stwa, sti, from_path, false); if (!sti.isSyncTestMode()) { SyncThread.createDirectoryToExternalStorage(stwa, sti, tf.getParent()); SafFile t_df =SyncThread.createSafFile(stwa, sti, to_path, false); if (t_df == null) { return SyncTaskItem.SYNC_STATUS_ERROR; } sync_result= copyFile(stwa, sti, stwa.context.getContentResolver().openInputStream(m_df.getUri()), stwa.context.getContentResolver().openOutputStream(t_df.getUri()), from_path, to_path, file_name, sti.isSyncOptionUseSmallIoBuffer()); } if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) { stwa.totalCopyCount++; SyncThread.showArchiveMsg(stwa, false, sti.getSyncTaskName(), "I", from_path, to_path, mf.getName(), tf.getName(), "", stwa.msgs_mirror_task_file_archived); if (!sti.isSyncTestMode()) { m_df.delete(); stwa.totalDeleteCount++; SyncThread.scanMediaFile(stwa, from_path); SyncThread.scanMediaFile(stwa, tf.getPath()); } } } else { stwa.totalIgnoreCount++; SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "I", to_path, mf.getName(), "", stwa.context.getString(R.string.msgs_mirror_confirm_move_cancel)); } return sync_result; } static private int moveFileExternalToExternalSetLastMod(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path, File mf, File tf, String to_path, String file_name) throws IOException { int sync_result=0; if (SyncThread.sendConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_MOVE, from_path)) { SafFile m_df = SyncThread.createSafFile(stwa, sti, from_path); if (!sti.isSyncTestMode()) { SyncThread.createDirectoryToExternalStorage(stwa, sti, tf.getParent()); String temp_path=isSdcardPath(stwa,to_path)? stwa.gp.safMgr.getSdcardRootPath()+"/"+APP_SPECIFIC_DIRECTORY+"/cache/archive_temp.tmp": stwa.gp.safMgr.getUsbRootPath()+ "/"+APP_SPECIFIC_DIRECTORY+"/cache/archive_temp.tmp"; File temp_file=new File(temp_path); OutputStream os=null; try { os=new FileOutputStream(temp_file); } catch (Exception e) { SafFile sf=SyncThread.createSafFile(stwa, sti, temp_file.getPath(), false); os=stwa.context.getContentResolver().openOutputStream(sf.getUri()); } sync_result= copyFile(stwa, sti, stwa.context.getContentResolver().openInputStream(m_df.getUri()), os, from_path, to_path, file_name, sti.isSyncOptionUseSmallIoBuffer()); temp_file.setLastModified(mf.lastModified()); // SyncThread.deleteTempMediaStoreItem(stwa, temp_file); SafFile from_saf = SyncThread.createSafFile(stwa, sti, temp_file.getPath()); if (from_saf == null) return SyncTaskItem.SYNC_STATUS_ERROR; SafFile to_saf = SyncThread.createSafFile(stwa, sti, tf.getPath()); if (to_saf == null) return SyncTaskItem.SYNC_STATUS_ERROR; from_saf.moveTo(to_saf); } if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) { stwa.totalCopyCount++; SyncThread.showArchiveMsg(stwa, false, sti.getSyncTaskName(), "I", from_path, to_path, mf.getName(), tf.getName(), "", stwa.msgs_mirror_task_file_archived); if (!sti.isSyncTestMode()) { m_df.delete(); stwa.totalDeleteCount++; SyncThread.scanMediaFile(stwa, from_path); SyncThread.scanMediaFile(stwa, tf.getPath()); } } } else { stwa.totalIgnoreCount++; SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "I", to_path, mf.getName(), "", stwa.context.getString(R.string.msgs_mirror_confirm_move_cancel)); } return sync_result; } static private int archiveFileExternalToExternal(SyncThreadWorkArea stwa, SyncTaskItem sti, File[] children, String from_path, String to_path) throws IOException { int file_seq_no=0, sync_result=0; ArrayList<ArchiveFileListItem>fl= buildSafFileList(stwa, sti, children); for(ArchiveFileListItem item:fl) { if (!stwa.gp.syncThreadCtrl.isEnabled()) { sync_result = SyncTaskItem.SYNC_STATUS_CANCEL; break; } if (sti.isSyncOptionIgnoreFileSize0ByteFile() && item.file_size==0) { stwa.util.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName()+" File was ignored, Reason=(File size equals 0), FP="+item.full_path); continue; } if (!item.date_from_exif && sti.isSyncOptionConfirmNotExistsExifDate()) { if (!SyncThread.sendArchiveConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_ARCHIVE_DATE_FROM_FILE, item.full_path)) { stwa.totalIgnoreCount++; SyncThread.showMsg(stwa, false, sti.getSyncTaskName(), "I", item.full_path, item.file_name, "", stwa.context.getString(R.string.msgs_mirror_confirm_archive_date_time_from_file_cancel)); continue; } } if (!SyncThread.isValidFileDirectoryName(stwa, sti, item.full_path)) { if (sti.isSyncOptionIgnoreDirectoriesOrFilesThatContainUnusableCharacters()) return sync_result; else return SyncTaskItem.SYNC_STATUS_ERROR; } file_seq_no++; String to_file_name="", to_file_ext="", to_file_seqno=""; if (item.file_name.lastIndexOf(".")>=0) { to_file_ext=item.file_name.substring(item.file_name.lastIndexOf(".")); to_file_name=item.file_name.substring(0,item.file_name.lastIndexOf(".")); } else { to_file_name=item.file_name; } to_file_seqno=getFileSeqNumber(stwa, sti, file_seq_no); String converted_to_path=buildArchiveTargetDirectoryName(stwa, sti, to_path, item); if (!sti.isArchiveUseRename()) { File tf=new File(converted_to_path+"/"+item.file_name); if (tf.exists()) { String new_name=createArchiveLocalNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+to_file_name, to_file_ext) ; if (new_name.equals("")) { stwa.util.addLogMsg("E","Archive sequence number overflow error."); sync_result=SyncTaskItem.SYNC_STATUS_ERROR; break; } else { tf=new File(new_name); sync_result= moveFileExternalToExternal(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(), new_name); } } else { sync_result= moveFileExternalToExternal(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(), to_file_name); } } else { to_file_name=buildArchiveFileName(stwa, sti, item, to_file_name); String temp_dir= buildArchiveSubDirectoryName(stwa, sti, item); File tf=new File(converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno+to_file_ext); if (tf.exists()) { String new_name=createArchiveLocalNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno,to_file_ext) ; if (new_name.equals("")) { stwa.util.addLogMsg("E","Archive sequence number overflow error."); sync_result=SyncTaskItem.SYNC_STATUS_ERROR; break; } else { tf=new File(new_name); sync_result= moveFileExternalToExternal(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(), new_name); } } else { sync_result= moveFileExternalToExternal(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(), converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno+to_file_ext); } } } return sync_result; } static private int buildArchiveListExternalToExternal(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_base, String from_path, File mf, String to_base, String to_path) { stwa.util.addDebugMsg(2, "I", CommonUtilities.getExecutedMethodName(), " entered, from=", from_path, ", to=" + to_path); int sync_result = 0; stwa.jcifsNtStatusCode=0; File tf; try { if (mf.exists()) { String t_from_path = from_path.substring(from_base.length()); if (t_from_path.startsWith("/")) t_from_path = t_from_path.substring(1); if (mf.isDirectory()) { // Directory copy if (!SyncThread.isHiddenDirectory(stwa, sti, mf) && SyncThread.isDirectoryToBeProcessed(stwa, t_from_path)) { if (mf.canRead()) { // if (sti.isSyncOptionSyncEmptyDirectory()) { // SyncThread.createDirectoryToExternalStorage(stwa, sti, to_path); // } File[] children = mf.listFiles(); sync_result=archiveFileExternalToExternal(stwa, sti, children, from_path, to_path); if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) { if (children != null) { for (File element : children) { if (sync_result == SyncTaskItem.SYNC_STATUS_SUCCESS) { if (!element.getName().equals(".android_secure")) { if (!from_path.equals(to_path)) { if (element.isDirectory()) { if (sti.isSyncOptionSyncSubDirectory()) { sync_result = buildArchiveListExternalToExternal(stwa, sti, from_base, from_path + "/" + element.getName(), element, to_base, to_path + "/" + element.getName()); } else { stwa.util.addDebugMsg(1, "I", "Sub directory was not sync, dir=" + from_path); } } } else { stwa.util.addDebugMsg(1, "W", String.format(stwa.context.getString(R.string.msgs_mirror_same_directory_ignored), from_path + "/" + element.getName())); } } } else { return sync_result; } if (!stwa.gp.syncThreadCtrl.isEnabled()) { sync_result = SyncTaskItem.SYNC_STATUS_CANCEL; break; } } } else { stwa.util.addDebugMsg(1, "I", "Directory was null, dir=" + mf.getPath()); } } } else { stwa.totalIgnoreCount++; SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "W", "", "", stwa.context.getString(R.string.msgs_mirror_task_directory_ignored_because_can_not_read, from_path + "/" + mf.getName())); } } } } else { stwa.gp.syncThreadCtrl.setThreadMessage(stwa.context.getString(R.string.msgs_mirror_task_master_not_found) + " " + from_path); SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "E", "", "", stwa.gp.syncThreadCtrl.getThreadMessage()); return SyncTaskItem.SYNC_STATUS_ERROR; } } catch (IOException e) { putExceptionMsg(stwa, sti, from_path, to_path, e); return SyncTaskItem.SYNC_STATUS_ERROR; } return sync_result; } static public int syncArchiveExternalToSmb(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path, String to_path) { File mf = new File(from_path); int sync_result = buildArchiveListExternalToSmb(stwa, sti, from_path, from_path, mf, to_path, to_path); return sync_result; } static private int moveFileExternalToSmb(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path, File mf, JcifsFile tf, String to_path, String file_name) throws IOException, JcifsException { int sync_result=0; if (SyncThread.isValidFileNameLength(stwa, sti, tf.getName())) { if (SyncThread.sendConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_MOVE, from_path)) { SafFile m_df =SyncThread.createSafFile(stwa, sti, from_path, false); if (!sti.isSyncTestMode()) { String dir=tf.getParent(); JcifsFile jf_dir=new JcifsFile(dir,stwa.targetAuth); if (!jf_dir.exists()) jf_dir.mkdirs(); while (stwa.syncTaskRetryCount > 0) { sync_result= copyFile(stwa, sti, stwa.context.getContentResolver().openInputStream(m_df.getUri()), tf.getOutputStream(), from_path, to_path, tf.getName(), sti.isSyncOptionUseSmallIoBuffer()); if (sync_result == SyncTaskItem.SYNC_STATUS_ERROR && SyncThread.isRetryRequiredError(stwa.jcifsNtStatusCode)) { stwa.syncTaskRetryCount--; if (stwa.syncTaskRetryCount > 0) sync_result = waitRetryInterval(stwa); if (sync_result == SyncTaskItem.SYNC_STATUS_CANCEL) break; } else { stwa.syncTaskRetryCount = stwa.syncTaskRetryCountOriginal; break; } } } if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) { stwa.totalCopyCount++; SyncThread.showArchiveMsg(stwa, false, sti.getSyncTaskName(), "I", from_path, to_path, mf.getName(), tf.getName(), "", stwa.msgs_mirror_task_file_archived); if (!sti.isSyncTestMode()) { try { tf.setLastModified(mf.lastModified()); } catch(JcifsException e) { // nop } if (!sti.isSyncTestMode()) { stwa.totalDeleteCount++; m_df.delete(); SyncThread.scanMediaFile(stwa, from_path); } } } } else { stwa.totalIgnoreCount++; SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "I", to_path, mf.getName(), "", stwa.context.getString(R.string.msgs_mirror_confirm_move_cancel)); } } return sync_result; } static private int archiveFileExternalToSmb(SyncThreadWorkArea stwa, SyncTaskItem sti, File[] children, String from_path, String to_path) throws IOException, JcifsException { int file_seq_no=0, sync_result=0; ArrayList<ArchiveFileListItem>fl= buildSafFileList(stwa, sti, children); for(ArchiveFileListItem item:fl) { if (!stwa.gp.syncThreadCtrl.isEnabled()) { sync_result = SyncTaskItem.SYNC_STATUS_CANCEL; break; } if (sti.isSyncOptionIgnoreFileSize0ByteFile() && item.file_size==0) { stwa.util.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName()+" File was ignored, Reason=(File size equals 0), FP="+item.full_path); continue; } if (!item.date_from_exif && sti.isSyncOptionConfirmNotExistsExifDate()) { if (!SyncThread.sendArchiveConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_ARCHIVE_DATE_FROM_FILE, item.full_path)) { stwa.totalIgnoreCount++; SyncThread.showMsg(stwa, false, sti.getSyncTaskName(), "I", item.full_path, item.file_name, "", stwa.context.getString(R.string.msgs_mirror_confirm_archive_date_time_from_file_cancel)); continue; } } if (!SyncThread.isValidFileDirectoryName(stwa, sti, item.full_path)) { if (sti.isSyncOptionIgnoreDirectoriesOrFilesThatContainUnusableCharacters()) return sync_result; else return SyncTaskItem.SYNC_STATUS_ERROR; } file_seq_no++; String to_file_name="", to_file_ext="", to_file_seqno=""; if (item.file_name.lastIndexOf(".")>=0) { to_file_ext=item.file_name.substring(item.file_name.lastIndexOf(".")); to_file_name=item.file_name.substring(0,item.file_name.lastIndexOf(".")); } else { to_file_name=item.file_name; } to_file_seqno=getFileSeqNumber(stwa, sti, file_seq_no); String converted_to_path=buildArchiveTargetDirectoryName(stwa, sti, to_path, item); if (!sti.isArchiveUseRename()) { JcifsFile tf=new JcifsFile(converted_to_path+"/"+item.file_name, stwa.targetAuth); if (tf.exists()) { String new_name=createArchiveLocalNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+to_file_name, to_file_ext) ; if (new_name.equals("")) { stwa.util.addLogMsg("E","Archive sequence number overflow error."); sync_result=SyncTaskItem.SYNC_STATUS_ERROR; break; } else { tf=new JcifsFile(new_name, stwa.targetAuth); sync_result= moveFileExternalToSmb(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(), new_name); } } else { sync_result= moveFileExternalToSmb(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(), to_file_name); } } else { to_file_name=buildArchiveFileName(stwa, sti, item, to_file_name); String temp_dir= buildArchiveSubDirectoryName(stwa, sti, item); JcifsFile tf=new JcifsFile(converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno+to_file_ext, stwa.targetAuth); if (tf.exists()) { String new_name=createArchiveLocalNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno,to_file_ext) ; if (new_name.equals("")) { stwa.util.addLogMsg("E","Archive sequence number overflow error."); sync_result=SyncTaskItem.SYNC_STATUS_ERROR; break; } else { tf=new JcifsFile(new_name, stwa.targetAuth); sync_result= moveFileExternalToSmb(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(), new_name); } } else { sync_result= moveFileExternalToSmb(stwa, sti, item.full_path, (File)item.file, tf, tf.getPath(), converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno+to_file_ext); } } } return sync_result; } static private int buildArchiveListExternalToSmb(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_base, String from_path, File mf, String to_base, String to_path) { stwa.util.addDebugMsg(2, "I", CommonUtilities.getExecutedMethodName(), " entered, from=", from_path, ", to=", to_path); int sync_result = 0; stwa.jcifsNtStatusCode=0; JcifsFile tf; try { if (mf.exists()) { String t_from_path = from_path.substring(from_base.length()); if (t_from_path.startsWith("/")) t_from_path = t_from_path.substring(1); if (mf.isDirectory()) { // Directory copy if (!SyncThread.isHiddenDirectory(stwa, sti, mf) && SyncThread.isDirectoryToBeProcessed(stwa, t_from_path)) { if (mf.canRead()) { // if (sti.isSyncOptionSyncEmptyDirectory()) { // SyncThread.createDirectoryToSmb(stwa, sti, to_path, stwa.targetAuth); // } File[] children = mf.listFiles(); if (children != null) { sync_result=archiveFileExternalToSmb(stwa, sti, children, from_path, to_path); if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) { for (File element : children) { if (sync_result == SyncTaskItem.SYNC_STATUS_SUCCESS) { if (!element.getName().equals(".android_secure")) { while (stwa.syncTaskRetryCount > 0) { if (element.isDirectory()) { if (sti.isSyncOptionSyncSubDirectory()) { sync_result = buildArchiveListExternalToSmb(stwa, sti, from_base, from_path + "/" + element.getName(), element, to_base, to_path + "/" + element.getName()); } else { if (stwa.gp.settingDebugLevel >= 1) stwa.util.addDebugMsg(1, "I", "Sub directory was not sync, dir=" + from_path); } } if (sync_result == SyncTaskItem.SYNC_STATUS_ERROR && SyncThread.isRetryRequiredError(stwa.jcifsNtStatusCode)) { stwa.syncTaskRetryCount--; if (stwa.syncTaskRetryCount > 0) sync_result = waitRetryInterval(stwa); if (sync_result == SyncTaskItem.SYNC_STATUS_CANCEL) break; } else { stwa.syncTaskRetryCount = stwa.syncTaskRetryCountOriginal; break; } } if (sync_result != SyncTaskItem.SYNC_STATUS_SUCCESS) break; } } else { return sync_result; } if (!stwa.gp.syncThreadCtrl.isEnabled()) { sync_result = SyncTaskItem.SYNC_STATUS_CANCEL; break; } } } } else { stwa.util.addDebugMsg(1, "I", "Directory was null, dir=" + mf.getPath()); } } else { stwa.totalIgnoreCount++; SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "W", "", "", stwa.context.getString(R.string.msgs_mirror_task_directory_ignored_because_can_not_read, from_path + "/" + mf.getName())); } } } } else { stwa.gp.syncThreadCtrl.setThreadMessage(stwa.context.getString(R.string.msgs_mirror_task_master_not_found) + " " + from_path); SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "E", "", "", stwa.gp.syncThreadCtrl.getThreadMessage()); return SyncTaskItem.SYNC_STATUS_ERROR; } } catch (IOException e) { putExceptionMsg(stwa, sti, from_path, to_path, e); return SyncTaskItem.SYNC_STATUS_ERROR; } catch (JcifsException e) { putExceptionMsg(stwa, sti, from_path, to_path, e); return SyncTaskItem.SYNC_STATUS_ERROR; } return sync_result; } static public int syncArchiveSmbToInternal(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path, String to_path) { JcifsFile mf = null; try { mf = new JcifsFile(from_path, stwa.masterAuth); } catch (MalformedURLException e) { stwa.util.addLogMsg("E", "", CommonUtilities.getExecutedMethodName() + " From=" + from_path + ", To=" + to_path); stwa.util.addLogMsg("E", "", e.getMessage());//e.toString()); SyncThread.printStackTraceElement(stwa, e.getStackTrace()); stwa.gp.syncThreadCtrl.setThreadMessage(e.getMessage()); return SyncTaskItem.SYNC_STATUS_ERROR; } catch (JcifsException e) { stwa.util.addLogMsg("E", "", CommonUtilities.getExecutedMethodName() + " From=" + from_path + ", To=" + to_path); stwa.util.addLogMsg("E", "", e.getMessage());//e.toString()); SyncThread.printStackTraceElement(stwa, e.getStackTrace()); stwa.gp.syncThreadCtrl.setThreadMessage(e.getMessage()); return SyncTaskItem.SYNC_STATUS_ERROR; } int sync_result = buildArchiveListSmbToInternal(stwa, sti, from_path, from_path, mf, to_path, to_path); return sync_result; } static private int moveFileSmbToInternal(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path, JcifsFile mf, File tf, String to_path, String file_name) throws IOException, JcifsException { int sync_result=0; if (SyncThread.sendConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_MOVE, from_path)) { if (!sti.isSyncTestMode()) { String dir=tf.getParent(); File lf_dir=new File(dir); if (!lf_dir.exists()) lf_dir.mkdirs(); File temp_file=new File(stwa.gp.internalRootDirectory+"/"+APP_SPECIFIC_DIRECTORY+"/cache/temp_file.tmp"); while (stwa.syncTaskRetryCount > 0) { sync_result= copyFile(stwa, sti, mf.getInputStream(), new FileOutputStream(temp_file), from_path, to_path, file_name, sti.isSyncOptionUseSmallIoBuffer()); if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) { temp_file.setLastModified(mf.getLastModified()); temp_file.renameTo(tf); } if (sync_result == SyncTaskItem.SYNC_STATUS_ERROR && SyncThread.isRetryRequiredError(stwa.jcifsNtStatusCode)) { stwa.syncTaskRetryCount--; if (stwa.syncTaskRetryCount > 0) sync_result = waitRetryInterval(stwa); if (sync_result == SyncTaskItem.SYNC_STATUS_CANCEL) break; } else { stwa.syncTaskRetryCount = stwa.syncTaskRetryCountOriginal; break; } } } if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) { stwa.totalCopyCount++; SyncThread.showArchiveMsg(stwa, false, sti.getSyncTaskName(), "I", from_path, to_path, mf.getName(), tf.getName(), "", stwa.msgs_mirror_task_file_archived); if (!sti.isSyncTestMode()) { try { tf.setLastModified(mf.getLastModified()); } catch(JcifsException e) { // nop } mf.delete(); stwa.totalDeleteCount++; SyncThread.scanMediaFile(stwa, tf.getPath()); } } } else { stwa.totalIgnoreCount++; SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "I", to_path, mf.getName(), "", stwa.context.getString(R.string.msgs_mirror_confirm_move_cancel)); } return sync_result; } static private int archiveFileSmbToInternal(SyncThreadWorkArea stwa, SyncTaskItem sti, JcifsFile[] children, String from_path, String to_path) throws IOException, JcifsException { int file_seq_no=0, sync_result=0; ArrayList<ArchiveFileListItem>fl=buildSmbFileList(stwa, sti, children); for(ArchiveFileListItem item:fl) { if (!stwa.gp.syncThreadCtrl.isEnabled()) { sync_result = SyncTaskItem.SYNC_STATUS_CANCEL; break; } if (sti.isSyncOptionIgnoreFileSize0ByteFile() && item.file_size==0) { stwa.util.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName()+" File was ignored, Reason=(File size equals 0), FP="+item.full_path); continue; } if (!item.date_from_exif && sti.isSyncOptionConfirmNotExistsExifDate()) { if (!SyncThread.sendArchiveConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_ARCHIVE_DATE_FROM_FILE, item.full_path)) { stwa.totalIgnoreCount++; SyncThread.showMsg(stwa, false, sti.getSyncTaskName(), "I", item.full_path, item.file_name, "", stwa.context.getString(R.string.msgs_mirror_confirm_archive_date_time_from_file_cancel)); continue; } } file_seq_no++; String to_file_name="", to_file_ext="", to_file_seqno=""; if (item.file_name.lastIndexOf(".")>=0) { to_file_ext=item.file_name.substring(item.file_name.lastIndexOf(".")); to_file_name=item.file_name.substring(0,item.file_name.lastIndexOf(".")); } else { to_file_name=item.file_name; } to_file_seqno=getFileSeqNumber(stwa, sti, file_seq_no); String converted_to_path=buildArchiveTargetDirectoryName(stwa, sti, to_path, item); if (!sti.isArchiveUseRename()) { File tf=new File(converted_to_path+"/"+item.file_name); if (tf.exists()) { String new_name=createArchiveLocalNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+to_file_name, to_file_ext) ; if (new_name.equals("")) { stwa.util.addLogMsg("E","Archive sequence number overflow error."); sync_result=SyncTaskItem.SYNC_STATUS_ERROR; break; } else { tf=new File(new_name); sync_result= moveFileSmbToInternal(stwa, sti, item.full_path, (JcifsFile)item.file, tf, tf.getPath(), new_name); } } else { sync_result= moveFileSmbToInternal(stwa, sti, item.full_path, (JcifsFile)item.file, tf, tf.getPath(), to_file_name); } } else { to_file_name=buildArchiveFileName(stwa, sti, item, to_file_name); String temp_dir= buildArchiveSubDirectoryName(stwa, sti, item); File tf=new File(converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno+to_file_ext); if (tf.exists()) { String new_name=createArchiveLocalNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno,to_file_ext) ; if (new_name.equals("")) { stwa.util.addLogMsg("E","Archive sequence number overflow error."); sync_result=SyncTaskItem.SYNC_STATUS_ERROR; break; } else { tf=new File(new_name); sync_result= moveFileSmbToInternal(stwa, sti, item.full_path, (JcifsFile)item.file, tf, tf.getPath(), new_name); } } else { sync_result= moveFileSmbToInternal(stwa, sti, item.full_path, (JcifsFile)item.file, tf, tf.getPath(), converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno+to_file_ext); } } } return sync_result; } static private int buildArchiveListSmbToInternal(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_base, String from_path, JcifsFile mf, String to_base, String to_path) { if (stwa.gp.settingDebugLevel >= 2) stwa.util.addDebugMsg(2, "I", CommonUtilities.getExecutedMethodName() + " entered, from=" + from_path + ", to=" + to_path); int sync_result = 0; stwa.jcifsNtStatusCode=0; try { if (mf.exists()) { String t_from_path = from_path.substring(from_base.length()); if (t_from_path.startsWith("/")) t_from_path = t_from_path.substring(1); if (mf.isDirectory()) { // Directory copy if (!SyncThread.isHiddenDirectory(stwa, sti, mf) && SyncThread.isDirectoryToBeProcessed(stwa, t_from_path)) { if (mf.canRead()) { // if (sti.isSyncOptionSyncEmptyDirectory()) { // SyncThread.createDirectoryToInternalStorage(stwa, sti, to_path); // } JcifsFile[] children = mf.listFiles(); if (children != null) { sync_result=archiveFileSmbToInternal(stwa, sti, children, from_path, to_path); if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) { for (JcifsFile element : children) { if (sync_result == SyncTaskItem.SYNC_STATUS_SUCCESS) { while (stwa.syncTaskRetryCount > 0) { if (element.isDirectory()) { if (sti.isSyncOptionSyncSubDirectory()) { sync_result = buildArchiveListSmbToInternal(stwa, sti, from_base, from_path + element.getName(), element, to_base, to_path + "/" + element.getName().replace("/", "")); } else { if (stwa.gp.settingDebugLevel >= 1) stwa.util.addDebugMsg(1, "I", "Sub directory was not sync, dir=" + from_path); } } if (sync_result == SyncTaskItem.SYNC_STATUS_ERROR && SyncThread.isRetryRequiredError(stwa.jcifsNtStatusCode)) { stwa.syncTaskRetryCount--; if (stwa.syncTaskRetryCount > 0) sync_result = waitRetryInterval(stwa); if (sync_result == SyncTaskItem.SYNC_STATUS_CANCEL) break; } else { stwa.syncTaskRetryCount = stwa.syncTaskRetryCountOriginal; break; } } if (sync_result != SyncTaskItem.SYNC_STATUS_SUCCESS) break; } else { return sync_result; } if (!stwa.gp.syncThreadCtrl.isEnabled()) { sync_result = SyncTaskItem.SYNC_STATUS_CANCEL; break; } } } } else { if (stwa.gp.settingDebugLevel >= 1) stwa.util.addDebugMsg(1, "I", "Directory was null, dir=" + mf.getPath()); } } else { stwa.totalIgnoreCount++; SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "W", "", "", stwa.context.getString(R.string.msgs_mirror_task_directory_ignored_because_can_not_read, from_path + "/" + mf.getName())); } } } } else { stwa.gp.syncThreadCtrl.setThreadMessage(stwa.context.getString(R.string.msgs_mirror_task_master_not_found) + " " + from_path); SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "E", "", "", stwa.gp.syncThreadCtrl.getThreadMessage()); return SyncTaskItem.SYNC_STATUS_ERROR; } } catch (IOException e) { putExceptionMsg(stwa, sti, from_path, to_path, e); return SyncTaskItem.SYNC_STATUS_ERROR; } catch (JcifsException e) { putExceptionMsg(stwa, sti, from_path, to_path, e); return SyncTaskItem.SYNC_STATUS_ERROR; } return sync_result; } static public int syncArchiveSmbToExternal(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path, String to_path) { stwa.smbFileList = new ArrayList<String>(); JcifsFile mf = null; try { mf = new JcifsFile(from_path, stwa.masterAuth); } catch (MalformedURLException e) { stwa.util.addLogMsg("E", "", CommonUtilities.getExecutedMethodName() + " From=" + from_path + ", To=" + to_path); stwa.util.addLogMsg("E", "", e.getMessage());//e.toString()); SyncThread.printStackTraceElement(stwa, e.getStackTrace()); stwa.gp.syncThreadCtrl.setThreadMessage(e.getMessage()); return SyncTaskItem.SYNC_STATUS_ERROR; } catch (JcifsException e) { stwa.util.addLogMsg("E", "", CommonUtilities.getExecutedMethodName() + " From=" + from_path + ", To=" + to_path); stwa.util.addLogMsg("E", "", e.getMessage());//e.toString()); SyncThread.printStackTraceElement(stwa, e.getStackTrace()); stwa.gp.syncThreadCtrl.setThreadMessage(e.getMessage()); return SyncTaskItem.SYNC_STATUS_ERROR; } int sync_result = buildArchiveListSmbToExternal(stwa, sti, from_path, from_path, mf, to_path, to_path); return sync_result; } static private int moveFileSmbToExternal(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path, JcifsFile mf, File tf, String to_path, String file_name) throws IOException, JcifsException { int result=0; if (SyncThread.isValidFileNameLength(stwa, sti, tf.getName())) { if (Build.VERSION.SDK_INT>=24) result= moveFileSmbToExternalSetLastMod(stwa, sti, from_path, mf, tf, to_path, file_name); else result= moveFileSmbToExternalUnsetLastMod(stwa, sti, from_path, mf, tf, to_path, file_name); } return result; } static private int moveFileSmbToExternalUnsetLastMod(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path, JcifsFile mf, File tf, String to_path, String file_name) throws IOException, JcifsException { int sync_result=0; if (SyncThread.sendConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_MOVE, from_path)) { if (!sti.isSyncTestMode()) { SyncThread.createDirectoryToExternalStorage(stwa, sti, tf.getParent()); SafFile t_df =SyncThread.createSafFile(stwa, sti, to_path, false); if (t_df == null) { return SyncTaskItem.SYNC_STATUS_ERROR; } while (stwa.syncTaskRetryCount > 0) { sync_result= copyFile(stwa, sti, mf.getInputStream(), stwa.context.getContentResolver().openOutputStream(t_df.getUri()), from_path, to_path, file_name, sti.isSyncOptionUseSmallIoBuffer()); if (sync_result == SyncTaskItem.SYNC_STATUS_ERROR && SyncThread.isRetryRequiredError(stwa.jcifsNtStatusCode)) { stwa.syncTaskRetryCount--; if (stwa.syncTaskRetryCount > 0) sync_result = waitRetryInterval(stwa); if (sync_result == SyncTaskItem.SYNC_STATUS_CANCEL) break; } else { stwa.syncTaskRetryCount = stwa.syncTaskRetryCountOriginal; break; } } } if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) { stwa.totalCopyCount++; SyncThread.showArchiveMsg(stwa, false, sti.getSyncTaskName(), "I", from_path, to_path, mf.getName(), tf.getName(), "", stwa.msgs_mirror_task_file_archived); if (!sti.isSyncTestMode()) { try { tf.setLastModified(mf.getLastModified()); } catch(JcifsException e) { // nop } mf.delete(); stwa.totalDeleteCount++; SyncThread.scanMediaFile(stwa, tf.getPath()); } } } else { stwa.totalIgnoreCount++; SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "I", to_path, mf.getName(), "", stwa.context.getString(R.string.msgs_mirror_confirm_move_cancel)); } return sync_result; } static private int moveFileSmbToExternalSetLastMod(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path, JcifsFile mf, File tf, String to_path, String file_name) throws IOException, JcifsException { int sync_result=0; if (SyncThread.sendConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_MOVE, from_path)) { if (!sti.isSyncTestMode()) { SyncThread.createDirectoryToExternalStorage(stwa, sti, tf.getParent()); OutputStream os=null; String temp_path=isSdcardPath(stwa,to_path)? stwa.gp.safMgr.getSdcardRootPath()+"/"+APP_SPECIFIC_DIRECTORY+"/cache/archive_temp.tmp": stwa.gp.safMgr.getUsbRootPath()+ "/"+APP_SPECIFIC_DIRECTORY+"/cache/archive_temp.tmp"; File temp_file=new File(temp_path); try { os=new FileOutputStream(temp_file); } catch (Exception e) { SafFile sf=SyncThread.createSafFile(stwa, sti, temp_file.getPath(), false); os=stwa.context.getContentResolver().openOutputStream(sf.getUri()); } while (stwa.syncTaskRetryCount > 0) { sync_result= copyFile(stwa, sti, mf.getInputStream(), os, from_path, to_path, file_name, sti.isSyncOptionUseSmallIoBuffer()); if (sync_result == SyncTaskItem.SYNC_STATUS_ERROR && SyncThread.isRetryRequiredError(stwa.jcifsNtStatusCode)) { stwa.syncTaskRetryCount--; if (stwa.syncTaskRetryCount > 0) sync_result = waitRetryInterval(stwa); if (sync_result == SyncTaskItem.SYNC_STATUS_CANCEL) break; } else { stwa.syncTaskRetryCount = stwa.syncTaskRetryCountOriginal; break; } } if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) { temp_file.setLastModified(mf.getLastModified()); // SyncThread.deleteTempMediaStoreItem(stwa, temp_file); SafFile from_saf = SyncThread.createSafFile(stwa, sti, temp_file.getPath()); if (from_saf == null) return SyncTaskItem.SYNC_STATUS_ERROR; SafFile to_saf = SyncThread.createSafFile(stwa, sti, tf.getPath()); if (to_saf == null) return SyncTaskItem.SYNC_STATUS_ERROR; from_saf.moveTo(to_saf); } } if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) { stwa.totalCopyCount++; SyncThread.showArchiveMsg(stwa, false, sti.getSyncTaskName(), "I", from_path, to_path, mf.getName(), tf.getName(), "", stwa.msgs_mirror_task_file_archived); if (!sti.isSyncTestMode()) { try { tf.setLastModified(mf.getLastModified()); } catch(JcifsException e) { // nop } mf.delete(); stwa.totalDeleteCount++; SyncThread.scanMediaFile(stwa, tf.getPath()); } } } else { stwa.totalIgnoreCount++; SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "I", to_path, mf.getName(), "", stwa.context.getString(R.string.msgs_mirror_confirm_move_cancel)); } return sync_result; } static private int archiveFileSmbToExternal(SyncThreadWorkArea stwa, SyncTaskItem sti, JcifsFile[] children, String from_path, String to_path) throws IOException, JcifsException { int file_seq_no=0, sync_result=0; ArrayList<ArchiveFileListItem>fl=buildSmbFileList(stwa, sti, children); for(ArchiveFileListItem item:fl) { if (!stwa.gp.syncThreadCtrl.isEnabled()) { sync_result = SyncTaskItem.SYNC_STATUS_CANCEL; break; } if (sti.isSyncOptionIgnoreFileSize0ByteFile() && item.file_size==0) { stwa.util.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName()+" File was ignored, Reason=(File size equals 0), FP="+item.full_path); continue; } if (!item.date_from_exif && sti.isSyncOptionConfirmNotExistsExifDate()) { if (!SyncThread.sendArchiveConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_ARCHIVE_DATE_FROM_FILE, item.full_path)) { stwa.totalIgnoreCount++; SyncThread.showMsg(stwa, false, sti.getSyncTaskName(), "I", item.full_path, item.file_name, "", stwa.context.getString(R.string.msgs_mirror_confirm_archive_date_time_from_file_cancel)); continue; } } file_seq_no++; String to_file_name="", to_file_ext="", to_file_seqno=""; if (item.file_name.lastIndexOf(".")>=0) { to_file_ext=item.file_name.substring(item.file_name.lastIndexOf(".")); to_file_name=item.file_name.substring(0,item.file_name.lastIndexOf(".")); } else { to_file_name=item.file_name; } to_file_seqno=getFileSeqNumber(stwa, sti, file_seq_no); String converted_to_path=buildArchiveTargetDirectoryName(stwa, sti, to_path, item); if (!sti.isArchiveUseRename()) { File tf=new File(converted_to_path+"/"+item.file_name); if (tf.exists()) { String new_name=createArchiveLocalNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+to_file_name, to_file_ext) ; if (new_name.equals("")) { stwa.util.addLogMsg("E","Archive sequence number overflow error."); sync_result=SyncTaskItem.SYNC_STATUS_ERROR; break; } else { tf=new File(new_name); sync_result= moveFileSmbToExternal(stwa, sti, item.full_path, (JcifsFile)item.file, tf, tf.getPath(), new_name); } } else { sync_result= moveFileSmbToExternal(stwa, sti, item.full_path, (JcifsFile)item.file, tf, tf.getPath(), to_file_name); } } else { to_file_name=buildArchiveFileName(stwa, sti, item, to_file_name); String temp_dir= buildArchiveSubDirectoryName(stwa, sti, item); File tf=new File(converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno+to_file_ext); if (tf.exists()) { String new_name=createArchiveLocalNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno,to_file_ext) ; if (new_name.equals("")) { stwa.util.addLogMsg("E","Archive sequence number overflow error."); sync_result=SyncTaskItem.SYNC_STATUS_ERROR; break; } else { tf=new File(new_name); sync_result= moveFileSmbToExternal(stwa, sti, item.full_path, (JcifsFile)item.file, tf, tf.getPath(), new_name); } } else { sync_result= moveFileSmbToExternal(stwa, sti, item.full_path, (JcifsFile)item.file, tf, tf.getPath(), converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno+to_file_ext); } } } return sync_result; } static private int buildArchiveListSmbToExternal(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_base, String from_path, JcifsFile mf, String to_base, String to_path) { stwa.util.addDebugMsg(2, "I", CommonUtilities.getExecutedMethodName(), " entered, from=", from_path + ", to=", to_path); int sync_result = 0; stwa.jcifsNtStatusCode=0; File tf; try { if (mf.exists()) { String t_from_path = from_path.substring(from_base.length()); if (t_from_path.startsWith("/")) t_from_path = t_from_path.substring(1); if (mf.isDirectory()) { // Directory copy if (!SyncThread.isHiddenDirectory(stwa, sti, mf) && SyncThread.isDirectoryToBeProcessed(stwa, t_from_path)) { if (mf.canRead()) { // if (sti.isSyncOptionSyncEmptyDirectory()) { // SyncThread.createDirectoryToExternalStorage(stwa, sti, to_path); // } JcifsFile[] children = mf.listFiles(); if (children != null) { sync_result=archiveFileSmbToExternal(stwa, sti, children, from_path, to_path); if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) { for (JcifsFile element : children) { if (sync_result == SyncTaskItem.SYNC_STATUS_SUCCESS) { while (stwa.syncTaskRetryCount > 0) { if (element.isDirectory()) { if (sti.isSyncOptionSyncSubDirectory()) { sync_result = buildArchiveListSmbToExternal(stwa, sti, from_base, from_path + element.getName(), element, to_base, to_path + "/" + element.getName().replace("/", "")); } else { if (stwa.gp.settingDebugLevel >= 1) stwa.util.addDebugMsg(1, "I", "Sub directory was not sync, dir=" + from_path); } } if (sync_result == SyncTaskItem.SYNC_STATUS_ERROR && SyncThread.isRetryRequiredError(stwa.jcifsNtStatusCode)) { stwa.syncTaskRetryCount--; if (stwa.syncTaskRetryCount > 0) sync_result = waitRetryInterval(stwa); if (sync_result == SyncTaskItem.SYNC_STATUS_CANCEL) break; } else { stwa.syncTaskRetryCount = stwa.syncTaskRetryCountOriginal; break; } } if (sync_result != SyncTaskItem.SYNC_STATUS_SUCCESS) break; } else { return sync_result; } if (!stwa.gp.syncThreadCtrl.isEnabled()) { sync_result = SyncTaskItem.SYNC_STATUS_CANCEL; break; } } } } else { stwa.util.addDebugMsg(1, "I", "Directory was null, dir=" + mf.getPath()); } } else { stwa.totalIgnoreCount++; SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "W", "", "", stwa.context.getString(R.string.msgs_mirror_task_directory_ignored_because_can_not_read, from_path + "/" + mf.getName())); } } } } else { stwa.gp.syncThreadCtrl.setThreadMessage(stwa.context.getString(R.string.msgs_mirror_task_master_not_found) + " " + from_path); SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "E", "", "", stwa.gp.syncThreadCtrl.getThreadMessage()); return SyncTaskItem.SYNC_STATUS_ERROR; } } catch (IOException e) { putExceptionMsg(stwa, sti, from_path, to_path, e); return SyncTaskItem.SYNC_STATUS_ERROR; } catch (JcifsException e) { putExceptionMsg(stwa, sti, from_path, to_path, e); return SyncTaskItem.SYNC_STATUS_ERROR; } return sync_result; } static public int syncArchiveSmbToSmb(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path, String to_path) { JcifsFile mf = null; try { mf = new JcifsFile(from_path, stwa.masterAuth); } catch (MalformedURLException e) { stwa.util.addLogMsg("E", "", CommonUtilities.getExecutedMethodName() + " From=" + from_path + ", Master file error"); stwa.util.addLogMsg("E", "", e.getMessage());//e.toString()); SyncThread.printStackTraceElement(stwa, e.getStackTrace()); stwa.gp.syncThreadCtrl.setThreadMessage(e.getMessage()); return SyncTaskItem.SYNC_STATUS_ERROR; } catch (JcifsException e) { stwa.util.addLogMsg("E", "", CommonUtilities.getExecutedMethodName() + " From=" + from_path + ", To=" + to_path); stwa.util.addLogMsg("E", "", e.getMessage());//e.toString()); SyncThread.printStackTraceElement(stwa, e.getStackTrace()); stwa.gp.syncThreadCtrl.setThreadMessage(e.getMessage()); return SyncTaskItem.SYNC_STATUS_ERROR; } int sync_result = buildArchiveListSmbToSmb(stwa, sti, from_path, from_path, mf, to_path, to_path); return sync_result; } static private int moveFileSmbToSmb(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_path, JcifsFile mf, JcifsFile tf, String to_path, String file_name) throws IOException, JcifsException { int sync_result=0; if (SyncThread.isValidFileNameLength(stwa, sti, tf.getName())) { if (SyncThread.sendConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_MOVE, from_path)) { if (!sti.isSyncTestMode()) { String dir=tf.getParent(); JcifsFile jf_dir=new JcifsFile(dir,stwa.targetAuth); if (!jf_dir.exists()) jf_dir.mkdirs(); while (stwa.syncTaskRetryCount > 0) { sync_result= copyFile(stwa, sti, mf.getInputStream(), tf.getOutputStream(), from_path, to_path, file_name, sti.isSyncOptionUseSmallIoBuffer()); if (sync_result == SyncTaskItem.SYNC_STATUS_ERROR && SyncThread.isRetryRequiredError(stwa.jcifsNtStatusCode)) { stwa.syncTaskRetryCount--; if (stwa.syncTaskRetryCount > 0) sync_result = waitRetryInterval(stwa); if (sync_result == SyncTaskItem.SYNC_STATUS_CANCEL) break; } else { stwa.syncTaskRetryCount = stwa.syncTaskRetryCountOriginal; break; } } } if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) { stwa.totalCopyCount++; SyncThread.showArchiveMsg(stwa, false, sti.getSyncTaskName(), "I", from_path, to_path, mf.getName(), tf.getName(), "", stwa.msgs_mirror_task_file_archived); if (!sti.isSyncTestMode()) { try { tf.setLastModified(mf.getLastModified()); } catch(JcifsException e) { // nop } mf.delete(); stwa.totalDeleteCount++; } } } else { stwa.totalIgnoreCount++; SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "I", to_path, mf.getName(), "", stwa.context.getString(R.string.msgs_mirror_confirm_move_cancel)); } } return sync_result; } static private int archiveFileSmbToSmb(SyncThreadWorkArea stwa, SyncTaskItem sti, JcifsFile[] children, String from_path, String to_path) throws IOException, JcifsException { int file_seq_no=0, sync_result=0; ArrayList<ArchiveFileListItem>fl=buildSmbFileList(stwa, sti, children); for(ArchiveFileListItem item:fl) { if (!stwa.gp.syncThreadCtrl.isEnabled()) { sync_result = SyncTaskItem.SYNC_STATUS_CANCEL; break; } if (sti.isSyncOptionIgnoreFileSize0ByteFile() && item.file_size==0) { stwa.util.addDebugMsg(1, "I", CommonUtilities.getExecutedMethodName()+" File was ignored, Reason=(File size equals 0), FP="+item.full_path); continue; } if (!item.date_from_exif && sti.isSyncOptionConfirmNotExistsExifDate()) { if (!SyncThread.sendArchiveConfirmRequest(stwa, sti, SMBSYNC2_CONFIRM_REQUEST_ARCHIVE_DATE_FROM_FILE, item.full_path)) { stwa.totalIgnoreCount++; SyncThread.showMsg(stwa, false, sti.getSyncTaskName(), "I", item.full_path, item.file_name, "", stwa.context.getString(R.string.msgs_mirror_confirm_archive_date_time_from_file_cancel)); continue; } } file_seq_no++; String to_file_name="", to_file_ext="", to_file_seqno=""; if (item.file_name.lastIndexOf(".")>=0) { to_file_ext=item.file_name.substring(item.file_name.lastIndexOf(".")); to_file_name=item.file_name.substring(0,item.file_name.lastIndexOf(".")); } else { to_file_name=item.file_name; } to_file_seqno=getFileSeqNumber(stwa, sti, file_seq_no); String converted_to_path=buildArchiveTargetDirectoryName(stwa, sti, to_path, item); if (!sti.isArchiveUseRename()) { JcifsFile tf=new JcifsFile(converted_to_path+"/"+item.file_name, stwa.targetAuth); if (tf.exists()) { String new_name=createArchiveSmbNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+to_file_name, to_file_ext) ; if (new_name.equals("")) { stwa.util.addLogMsg("E","Archive sequence number overflow error."); sync_result=SyncTaskItem.SYNC_STATUS_ERROR; break; } else { tf=new JcifsFile(new_name, stwa.targetAuth); sync_result= moveFileSmbToSmb(stwa, sti, item.full_path, (JcifsFile)item.file, tf, tf.getPath(), new_name); } } else { sync_result= moveFileSmbToSmb(stwa, sti, item.full_path, (JcifsFile)item.file, tf, tf.getPath(), to_file_name); } } else { to_file_name=buildArchiveFileName(stwa, sti, item, to_file_name); String temp_dir= buildArchiveSubDirectoryName(stwa, sti, item); JcifsFile tf=new JcifsFile(converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno+to_file_ext, stwa.targetAuth); if (tf.exists()) { String new_name=createArchiveSmbNewFilePath(stwa, sti, converted_to_path, converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno,to_file_ext) ; if (new_name.equals("")) { stwa.util.addLogMsg("E","Archive sequence number overflow error."); sync_result=SyncTaskItem.SYNC_STATUS_ERROR; break; } else { tf=new JcifsFile(new_name, stwa.targetAuth); sync_result= moveFileSmbToSmb(stwa, sti, item.full_path, (JcifsFile)item.file, tf, tf.getPath(), new_name); } } else { sync_result= moveFileSmbToSmb(stwa, sti, item.full_path, (JcifsFile)item.file, tf, tf.getPath(), converted_to_path+"/"+temp_dir+to_file_name+to_file_seqno+to_file_ext); } } } return sync_result; } static private int buildArchiveListSmbToSmb(SyncThreadWorkArea stwa, SyncTaskItem sti, String from_base, String from_path, JcifsFile mf, String to_base, String to_path) { stwa.util.addDebugMsg(2, "I", CommonUtilities.getExecutedMethodName(), " entered, from=", from_path, ", to=", to_path); int sync_result = 0; stwa.jcifsNtStatusCode=0; JcifsFile tf; try { if (mf.exists()) { String t_from_path = from_path.substring(from_base.length()); if (t_from_path.startsWith("/")) t_from_path = t_from_path.substring(1); if (mf.isDirectory()) { // Directory copy if (!SyncThread.isHiddenDirectory(stwa, sti, mf) && SyncThread.isDirectoryToBeProcessed(stwa, t_from_path)) { if (mf.canRead()){ // if (sti.isSyncOptionSyncEmptyDirectory()) { // SyncThread.createDirectoryToSmb(stwa, sti, to_path, stwa.targetAuth); // } JcifsFile[] children = mf.listFiles(); if (children != null) { sync_result=archiveFileSmbToSmb(stwa, sti, children, from_path, to_path); if (sync_result==SyncTaskItem.SYNC_STATUS_SUCCESS) { for (JcifsFile element : children) { if (sync_result == SyncTaskItem.SYNC_STATUS_SUCCESS) { while (stwa.syncTaskRetryCount > 0) { if (element.isDirectory()) { if (sti.isSyncOptionSyncSubDirectory()) { sync_result = buildArchiveListSmbToSmb(stwa, sti, from_base, from_path + element.getName(), element, to_base, to_path + element.getName()); } else { if (stwa.gp.settingDebugLevel >= 1) stwa.util.addDebugMsg(1, "I", "Sub directory was not sync, dir=" + from_path); } } if (sync_result == SyncTaskItem.SYNC_STATUS_ERROR && SyncThread.isRetryRequiredError(stwa.jcifsNtStatusCode)) { stwa.syncTaskRetryCount--; if (stwa.syncTaskRetryCount > 0) sync_result = waitRetryInterval(stwa); if (sync_result == SyncTaskItem.SYNC_STATUS_CANCEL) break; } else { stwa.syncTaskRetryCount = stwa.syncTaskRetryCountOriginal; break; } } if (sync_result != SyncTaskItem.SYNC_STATUS_SUCCESS) break; } else { return sync_result; } if (!stwa.gp.syncThreadCtrl.isEnabled()) { sync_result = SyncTaskItem.SYNC_STATUS_CANCEL; break; } } } } else { if (stwa.gp.settingDebugLevel >= 1) stwa.util.addDebugMsg(1, "I", "Directory was null, dir=" + mf.getPath()); } } else { stwa.totalIgnoreCount++; SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "W", "", "", stwa.context.getString(R.string.msgs_mirror_task_directory_ignored_because_can_not_read, from_path + "/" + mf.getName())); } } } } else { stwa.gp.syncThreadCtrl.setThreadMessage(stwa.context.getString(R.string.msgs_mirror_task_master_not_found) + " " + from_path); SyncThread.showMsg(stwa, true, sti.getSyncTaskName(), "E", "", "", stwa.gp.syncThreadCtrl.getThreadMessage()); return SyncTaskItem.SYNC_STATUS_ERROR; } } catch (IOException e) { putExceptionMsg(stwa, sti, from_path, to_path, e); return SyncTaskItem.SYNC_STATUS_ERROR; } catch (JcifsException e) { putExceptionMsg(stwa, sti, from_path, to_path, e); return SyncTaskItem.SYNC_STATUS_ERROR; } return sync_result; } static private int waitRetryInterval(SyncThreadWorkArea stwa) { int result = 0; if (!stwa.gp.syncThreadCtrl.isEnabled()) { result = SyncTaskItem.SYNC_STATUS_CANCEL; } else { synchronized (stwa.gp.syncThreadCtrl) { try { stwa.gp.syncThreadCtrl.wait(1000 * SyncThread.SYNC_RETRY_INTERVAL); } catch (InterruptedException e) { e.printStackTrace(); } } if (!stwa.gp.syncThreadCtrl.isEnabled()) result = SyncTaskItem.SYNC_STATUS_CANCEL; } return result; } final static int SHOW_PROGRESS_THRESHOLD_VALUE=512; static private int copyFile(SyncThreadWorkArea stwa, SyncTaskItem sti, InputStream ifs, OutputStream ofs, String from_path, String to_path, String file_name, boolean small_buffer) throws IOException { stwa.util.addDebugMsg(2, "I", "copyFile from=", from_path, ", to=", to_path); int buff_size=0, io_area_size=0; if (small_buffer) { buff_size=1024*16-1; io_area_size=buff_size; } else { buff_size=1024*1024*4; io_area_size=1024*1024*2; } long read_begin_time = System.currentTimeMillis(); if (sti.isSyncTestMode()) return SyncTaskItem.SYNC_STATUS_SUCCESS; int buffer_read_bytes = 0; long file_read_bytes = 0; long file_size = ifs.available(); boolean show_prog = (file_size > SHOW_PROGRESS_THRESHOLD_VALUE); byte[] buffer = new byte[io_area_size]; while ((buffer_read_bytes = ifs.read(buffer)) > 0) { ofs.write(buffer, 0, buffer_read_bytes); file_read_bytes += buffer_read_bytes; if (show_prog && file_size > file_read_bytes) { SyncThread.showProgressMsg(stwa, sti.getSyncTaskName(), file_name + " " + String.format(stwa.msgs_mirror_task_file_copying, (file_read_bytes * 100) / file_size)); } if (!stwa.gp.syncThreadCtrl.isEnabled()) { ifs.close(); ofs.flush(); ofs.close(); return SyncTaskItem.SYNC_STATUS_CANCEL; } } ifs.close(); ofs.flush(); ofs.close(); long file_read_time = System.currentTimeMillis() - read_begin_time; if (stwa.gp.settingDebugLevel >= 1) stwa.util.addDebugMsg(1, "I", to_path + " " + file_read_bytes + " bytes transfered in ", file_read_time + " mili seconds at " + SyncThread.calTransferRate(file_read_bytes, file_read_time)); stwa.totalTransferByte += file_read_bytes; stwa.totalTransferTime += file_read_time; return SyncTaskItem.SYNC_STATUS_SUCCESS; } static private class ArchiveFileListItem { Object file=null; String shoot_date="", shoot_time=""; String shoot_week_number="", shoot_week_day="", shoot_week_day_long=""; String file_name=""; String full_path=""; long file_size=0L; boolean date_from_exif=true; } static private ArrayList<ArchiveFileListItem> buildLocalFileList(SyncThreadWorkArea stwa, SyncTaskItem sti, File[] children) { ArrayList<ArchiveFileListItem>fl=new ArrayList<ArchiveFileListItem>(); for(File element:children) { if (element.isFile() && isFileTypeArchiveTarget(element.getName())) { String[] date_time=getFileExifDateTime(stwa, sti, element); ArchiveFileListItem afli=new ArchiveFileListItem(); afli.file=element; afli.file_name=element.getName(); afli.full_path=element.getPath(); afli.file_size=element.length(); Date date=null; if (date_time==null || date_time[0]==null) { String[] dt= StringUtil.convDateTimeTo_YearMonthDayHourMinSec(element.lastModified()).split(" "); afli.shoot_date=dt[0].replace("/","-"); afli.shoot_time=dt[1].replace(":","-"); date=new Date(element.lastModified()); afli.date_from_exif=false; } else { // Log.v("SMBSync2","name="+afli.file_name+", 0="+date_time[0]+", 1="+date_time[1]); date=new Date(date_time[0]+" "+date_time[1]); String[] dt= StringUtil.convDateTimeTo_YearMonthDayHourMinSec(date.getTime()).split(" "); afli.shoot_date=date_time[0].replace("/","-"); afli.shoot_time=date_time[1].replace(":","-"); } SimpleDateFormat sdf=new SimpleDateFormat(("w")); afli.shoot_week_number=sdf.format(date.getTime()); afli.shoot_week_day=getWeekDay(date.getTime()); afli.shoot_week_day_long=getWeekDay(date.getTime()); if (isFileArchiveRequired(stwa, sti, afli)) fl.add(afli); } } Collections.sort(fl, new Comparator<ArchiveFileListItem>(){ @Override public int compare(ArchiveFileListItem ri, ArchiveFileListItem li) { return (ri.shoot_date+ri.shoot_time+ri.file_name).compareToIgnoreCase(li.shoot_date+li.shoot_time+li.file_name); } }); return fl; } static private ArrayList<ArchiveFileListItem> buildSafFileList(SyncThreadWorkArea stwa, SyncTaskItem sti, File[] children) { ArrayList<ArchiveFileListItem>fl=new ArrayList<ArchiveFileListItem>(); for(File element:children) { if (element.isFile() && isFileTypeArchiveTarget(element.getName())) { SafFile m_df = SyncThread.createSafFile(stwa, sti, element.getPath(), false); String[] date_time=getFileExifDateTime(stwa, sti, m_df); ArchiveFileListItem afli=new ArchiveFileListItem(); afli.file=element; afli.file_name=element.getName(); afli.full_path=element.getPath(); afli.file_size=element.length(); Date date=null; if (date_time==null || date_time[0]==null) { String[] dt= StringUtil.convDateTimeTo_YearMonthDayHourMinSec(element.lastModified()).split(" "); date=new Date(dt[0]+" "+dt[1]); afli.shoot_date=dt[0].replace("/","-"); afli.shoot_time=dt[1].replace(":","-"); afli.date_from_exif=false; } else { date=new Date(date_time[0]+" "+date_time[1]); afli.shoot_date=date_time[0].replace("/","-"); afli.shoot_time=date_time[1].replace(":","-"); } SimpleDateFormat sdf=new SimpleDateFormat(("w")); afli.shoot_week_number=sdf.format(date.getTime()); afli.shoot_week_day=getWeekDay(date.getTime()); afli.shoot_week_day_long=getWeekDay(date.getTime()); if (isFileArchiveRequired(stwa, sti, afli)) fl.add(afli); } } Collections.sort(fl, new Comparator<ArchiveFileListItem>(){ @Override public int compare(ArchiveFileListItem ri, ArchiveFileListItem li) { return (ri.shoot_date+ri.shoot_time+ri.file_name).compareToIgnoreCase(li.shoot_date+li.shoot_time+li.file_name); } }); return fl; } static final private boolean isFileTypeArchiveTarget(String name) { boolean result=false; for(String item:ARCHIVE_FILE_TYPE) { if (name.toLowerCase().endsWith("."+item)) { result=true; break; } } return result; } static private ArrayList<ArchiveFileListItem> buildSmbFileList(SyncThreadWorkArea stwa, SyncTaskItem sti, JcifsFile[] children) throws JcifsException { ArrayList<ArchiveFileListItem>fl=new ArrayList<ArchiveFileListItem>(); for(JcifsFile element:children) { if (element.isFile() && isFileTypeArchiveTarget(element.getName())) { String[] date_time=getFileExifDateTime(stwa, sti, element); ArchiveFileListItem afli=new ArchiveFileListItem(); afli.file=element; afli.file_name=element.getName(); afli.full_path=element.getPath(); afli.file_size=element.length(); Date date=null; if (date_time==null || date_time[0]==null) { String[] dt= StringUtil.convDateTimeTo_YearMonthDayHourMinSec(element.getLastModified()).split(" "); date=new Date(dt[0]+" "+dt[1]); afli.shoot_date=dt[0].replace("/","-"); afli.shoot_time=dt[1].replace(":","-"); afli.date_from_exif=false; } else { date=new Date(date_time[0]+" "+date_time[1]); afli.shoot_date=date_time[0].replace("/","-"); afli.shoot_time=date_time[1].replace(":","-"); } SimpleDateFormat sdf=new SimpleDateFormat(("w")); afli.shoot_week_number=sdf.format(date.getTime()); sdf=new SimpleDateFormat(("EEE")); afli.shoot_week_day=getWeekDay(date.getTime()); afli.shoot_week_day_long=getWeekDay(date.getTime()); if (isFileArchiveRequired(stwa, sti, afli)) fl.add(afli); } } Collections.sort(fl, new Comparator<ArchiveFileListItem>(){ @Override public int compare(ArchiveFileListItem ri, ArchiveFileListItem li) { return (ri.shoot_date+ri.shoot_time+ri.file_name).compareToIgnoreCase(li.shoot_date+li.shoot_time+li.file_name); } }); return fl; } static private String getWeekDay(long time) { SimpleDateFormat sdf=new SimpleDateFormat(("w")); sdf=new SimpleDateFormat(("EEE")); String tmp=sdf.format(time).toLowerCase(); String result=tmp.endsWith(".")?tmp.substring(0, tmp.length()-1):tmp; return result; } static private String getWeekDayLong(long time) { SimpleDateFormat sdf=new SimpleDateFormat(("w")); sdf=new SimpleDateFormat(("EEEE")); String tmp=sdf.format(time).toLowerCase(); String result=tmp.endsWith(".")?tmp.substring(0, tmp.length()-1):tmp; return result; } static final public boolean isFileArchiveRequired(SyncThreadWorkArea stwa, SyncTaskItem sti, ArchiveFileListItem afli) { Calendar cal=Calendar.getInstance() ; String[] dt=afli.shoot_date.split("-"); String[] tm=afli.shoot_time.split("-"); cal.set(Integer.parseInt(dt[0]),Integer.parseInt(dt[1])-1,Integer.parseInt(dt[2]), Integer.parseInt(tm[0]),Integer.parseInt(tm[1]),Integer.parseInt(tm[2])); String c_ft= StringUtil.convDateTimeTo_YearMonthDayHourMinSec(cal.getTimeInMillis()); long exp_time=0, day_mili=1000L*60L*60L*24L; if (sti.getArchiveRetentionPeriod()==SyncTaskItem.PICTURE_ARCHIVE_RETAIN_FOR_A_7_DAYS) exp_time=day_mili*7L; else if (sti.getArchiveRetentionPeriod()==SyncTaskItem.PICTURE_ARCHIVE_RETAIN_FOR_A_30_DAYS) exp_time=day_mili*30L; else if (sti.getArchiveRetentionPeriod()==SyncTaskItem.PICTURE_ARCHIVE_RETAIN_FOR_A_60_DAYS) exp_time=day_mili*60L; else if (sti.getArchiveRetentionPeriod()==SyncTaskItem.PICTURE_ARCHIVE_RETAIN_FOR_A_90_DAYS) exp_time=day_mili*90L; else if (sti.getArchiveRetentionPeriod()==SyncTaskItem.PICTURE_ARCHIVE_RETAIN_FOR_A_180_DAYS) exp_time=day_mili*180L; else if (sti.getArchiveRetentionPeriod()==SyncTaskItem.PICTURE_ARCHIVE_RETAIN_FOR_A_1_YEARS) { int n_year=cal.getTime().getYear(); Calendar n_cal=Calendar.getInstance() ; n_cal.setTimeInMillis(cal.getTimeInMillis()); n_cal.add(Calendar.YEAR, 1); exp_time=n_cal.getTimeInMillis()-cal.getTimeInMillis(); } String n_exp= StringUtil.convDateTimeTo_YearMonthDayHourMinSec(cal.getTimeInMillis()+exp_time); // boolean result=(System.currentTimeMillis()>cal.getTimeInMillis()); boolean result=(System.currentTimeMillis()>(cal.getTimeInMillis()+exp_time)); stwa.util.addDebugMsg(1,"I","isFileArchiveRequired path=",afli.full_path,", shoot date=",afli.shoot_date, ", shoot time=", afli.shoot_time,", exif="+afli.date_from_exif,", archive required="+result, ", " + "retention period="+sti.getArchiveRetentionPeriod(), ", expiration date=", n_exp, ", expiration period="+exp_time); return result; } static private String buildArchiveSubDirectoryName(SyncThreadWorkArea stwa, SyncTaskItem sti, ArchiveFileListItem afli) { String temp_dir=""; if (sti.isArchiveCreateDirectory()) { if (!sti.getArchiveCreateDirectoryTemplate().equals("")){ String year=afli.shoot_date.substring(0,4); String month=afli.shoot_date.substring(5,7); String day=afli.shoot_date.substring(8,10); temp_dir=sti.getArchiveCreateDirectoryTemplate().replaceAll(SyncTaskItem.PICTURE_ARCHIVE_RENAME_KEYWORD_YEAR,year) .replaceAll(SyncTaskItem.PICTURE_ARCHIVE_RENAME_KEYWORD_MONTH,month) .replaceAll(SyncTaskItem.PICTURE_ARCHIVE_RENAME_KEYWORD_DAY,day) .replaceAll(SMBSYNC2_REPLACEABLE_KEYWORD_WEEK_NUMBER,afli.shoot_week_number) .replaceAll(SMBSYNC2_REPLACEABLE_KEYWORD_WEEK_DAY,afli.shoot_week_day) .replaceAll(SMBSYNC2_REPLACEABLE_KEYWORD_WEEK_DAY_LONG,afli.shoot_week_day_long) +"/"; } } return temp_dir; } static private String buildArchiveTargetDirectoryName(SyncThreadWorkArea stwa, SyncTaskItem sti, String to_path, ArchiveFileListItem afli) { String target_directory=""; if (sti.isTargetUseTakenDateTimeToDirectoryNameKeyword()) { if (!to_path.equals("")){ String year=afli.shoot_date.substring(0,4); String month=afli.shoot_date.substring(5,7); String day=afli.shoot_date.substring(8,10); target_directory=to_path.replaceAll(SyncTaskItem.PICTURE_ARCHIVE_RENAME_KEYWORD_YEAR,year) .replaceAll(SyncTaskItem.PICTURE_ARCHIVE_RENAME_KEYWORD_MONTH,month) .replaceAll(SyncTaskItem.PICTURE_ARCHIVE_RENAME_KEYWORD_DAY,day) .replaceAll(SMBSYNC2_REPLACEABLE_KEYWORD_WEEK_NUMBER,afli.shoot_week_number) .replaceAll(SMBSYNC2_REPLACEABLE_KEYWORD_WEEK_DAY,afli.shoot_week_day) .replaceAll(SMBSYNC2_REPLACEABLE_KEYWORD_WEEK_DAY_LONG,afli.shoot_week_day_long) ; } } else { target_directory=to_path; } return target_directory; } static private String buildArchiveFileName(SyncThreadWorkArea stwa, SyncTaskItem sti, ArchiveFileListItem afli, String original_name) { String to_file_name=original_name; if (!sti.getArchiveRenameFileTemplate().equals("")) { to_file_name=sti.getArchiveRenameFileTemplate() .replaceAll(SyncTaskItem.PICTURE_ARCHIVE_RENAME_KEYWORD_ORIGINAL_NAME, original_name) .replaceAll(SyncTaskItem.PICTURE_ARCHIVE_RENAME_KEYWORD_DATE, afli.shoot_date) .replaceAll(SyncTaskItem.PICTURE_ARCHIVE_RENAME_KEYWORD_TIME, afli.shoot_time) .replaceAll(SyncTaskItem.PICTURE_ARCHIVE_RENAME_KEYWORD_YYYYMMDD, afli.shoot_date.replaceAll("-","")) .replaceAll(SyncTaskItem.PICTURE_ARCHIVE_RENAME_KEYWORD_HHMMSS, afli.shoot_time.replaceAll("-","")) ; } return to_file_name; } static private String getFileSeqNumber(SyncThreadWorkArea stwa, SyncTaskItem sti, int seq_no) { String seqno=""; if (sti.getArchiveSuffixOption().equals("2")) seqno=String.format("_%02d", seq_no); else if (sti.getArchiveSuffixOption().equals("3")) seqno=String.format("_%03d", seq_no); else if (sti.getArchiveSuffixOption().equals("4")) seqno=String.format("_%04d", seq_no); else if (sti.getArchiveSuffixOption().equals("5")) seqno=String.format("_%05d", seq_no); else if (sti.getArchiveSuffixOption().equals("6")) seqno=String.format("_%06d", seq_no); return seqno; } static final public String[] getFileExifDateTime(SyncThreadWorkArea stwa, SyncTaskItem sti, File lf) { String[] date_time=null; try { FileInputStream fis=new FileInputStream(lf); FileInputStream fis_retry=new FileInputStream(lf); date_time=getFileExifDateTime(stwa, sti, fis, fis_retry, lf.lastModified(), lf.getName()); } catch (FileNotFoundException e) { e.printStackTrace(); } return date_time; } static final public String[] getFileExifDateTime(SyncThreadWorkArea stwa, SyncTaskItem sti, SafFile sf) { String[] date_time=null; try { InputStream fis=stwa.context.getContentResolver().openInputStream(sf.getUri()); InputStream fis_retry=stwa.context.getContentResolver().openInputStream(sf.getUri()); date_time=getFileExifDateTime(stwa, sti, fis, fis_retry, sf.lastModified(), sf.getName()); } catch (FileNotFoundException e) { e.printStackTrace(); } return date_time; } static final public String[] getFileExifDateTime(SyncThreadWorkArea stwa, SyncTaskItem sti, JcifsFile lf) throws JcifsException { String[] date_time=null; InputStream fis=lf.getInputStream(); InputStream fis_retry=lf.getInputStream(); date_time=getFileExifDateTime(stwa, sti, fis, fis_retry, lf.getLastModified(), lf.getName()); return date_time; } static final public String[] getFileExifDateTime(SyncThreadWorkArea stwa, SyncTaskItem sti, InputStream fis, InputStream fis_retry, long last_mod, String file_name) { String[] date_time=null; if (file_name.endsWith(".mp4") || file_name.endsWith(".mov") ) { date_time=getMp4ExifDateTime(stwa, fis); } else { try { date_time=getExifDateTime(stwa, fis);//, buff); fis.close(); if (date_time==null || date_time[0]==null) { stwa.util.addDebugMsg(1,"W","Read exif date and time failed, name="+file_name); if (Build.VERSION.SDK_INT>=24) { ExifInterface ei = new ExifInterface(fis_retry); String dt=ei.getAttribute(ExifInterface.TAG_DATETIME); if (dt!=null) { date_time=new String[2]; if (dt.endsWith("Z")) { String[] date=dt.split("T"); date_time[0]=date[0].replaceAll(":", "/");//Date date_time[1]=date[1].substring(0,date[1].length()-1);//Time } else { String[] date=dt.split(" "); date_time[0]=date[0].replaceAll(":", "/");//Date date_time[1]=date[1];//Time } } else { stwa.util.addDebugMsg(1,"I","Read exif date and time failed by ExifInterface, name="+file_name); } } } } catch (IOException e) { e.printStackTrace(); putExceptionMessage(stwa, e.getStackTrace(), e.getMessage()); } } // if (date_time==null || date_time[0]==null) { // date_time= StringUtil.convDateTimeTo_YearMonthDayHourMinSec(last_mod).split(" "); // } try {fis_retry.close();} catch(Exception e) {}; return date_time; } static final public String[] getMp4ExifDateTime(SyncThreadWorkArea stwa, SyncTaskItem sti, JcifsFile lf) throws JcifsException { String[] result=null; InputStream fis=lf.getInputStream(); result=getMp4ExifDateTime(stwa, fis); return result; } static final public String[] getMp4ExifDateTime(SyncThreadWorkArea stwa, InputStream fis) { String[] result=null; try { Metadata metaData; metaData = ImageMetadataReader.readMetadata(fis); Mp4Directory directory=null; if (metaData!=null) { directory=metaData.getFirstDirectoryOfType(Mp4Directory.class); if (directory!=null) { String date = directory.getString(Mp4Directory.TAG_CREATION_TIME); result=parseDateValue(date); if (result!=null && result[0].startsWith("1904")) result=null; } } } catch (ImageProcessingException e) { e.printStackTrace(); putExceptionMessage(stwa, e.getStackTrace(), e.getMessage()); } catch (Exception e) { e.printStackTrace(); putExceptionMessage(stwa, e.getStackTrace(), e.getMessage()); } try { fis.close(); } catch (Exception e) { e.printStackTrace(); putExceptionMessage(stwa, e.getStackTrace(), e.getMessage()); } return result; } static private void putExceptionMessage(SyncThreadWorkArea stwa, StackTraceElement[] st, String e_msg) { String st_msg=formatStackTrace(st); stwa.util.addDebugMsg(1,"E",stwa.currentSTI.getSyncTaskName()," Error="+e_msg+st_msg); } static final private String[] parseDateValue(String date_val) { String[] result=null; if (date_val!=null) { String[] dt=date_val.split(" "); int year=Integer.parseInt(dt[5]); int month=0; int day=Integer.parseInt(dt[2]); if (dt[1].equals("Jan")) month=0; else if (dt[1].equals("Feb")) month=1; else if (dt[1].equals("Mar")) month=2; else if (dt[1].equals("Apr")) month=3; else if (dt[1].equals("May")) month=4; else if (dt[1].equals("Jun")) month=5; else if (dt[1].equals("Jul")) month=6; else if (dt[1].equals("Aug")) month=7; else if (dt[1].equals("Sep")) month=8; else if (dt[1].equals("Oct")) month=9; else if (dt[1].equals("Nov")) month=10; else if (dt[1].equals("Dec")) month=11; String[] tm=dt[3].split(":"); int hours= Integer.parseInt(tm[0]); int minutes=Integer.parseInt(tm[1]); int seconds=Integer.parseInt(tm[2]); Calendar cal=Calendar.getInstance() ; TimeZone tz=TimeZone.getDefault(); tz.setID(dt[3]); cal.setTimeZone(tz); cal.set(year, month, day, hours, minutes, seconds); result= StringUtil.convDateTimeTo_YearMonthDayHourMinSec(cal.getTimeInMillis()).split(" "); } return result; } static final public String[] getMp4ExifDateTime(SyncThreadWorkArea stwa, SyncTaskItem sti, File lf) { String[] result=null; try { InputStream fis=new FileInputStream(lf); result=getMp4ExifDateTime(stwa, fis); } catch (IOException e) { e.printStackTrace(); putExceptionMessage(stwa, e.getStackTrace(), e.getMessage()); } return result; } static final public String[] getMp4ExifDateTime(SyncThreadWorkArea stwa, SyncTaskItem sti, SafFile sf) { String[] result=null; InputStream fis=null; try { fis=stwa.context.getContentResolver().openInputStream(sf.getUri()); result=getMp4ExifDateTime(stwa, fis); } catch (IOException e) { e.printStackTrace(); putExceptionMessage(stwa, e.getStackTrace(), e.getMessage()); } return result; } static private byte[] readExifData(BufferedInputStream bis, int read_size) throws IOException { byte[] buff=new byte[read_size]; int rc=bis.read(buff,0,read_size); if (rc>0) return buff; else return null; } static public String[] getExifDateTime(SyncThreadWorkArea stwa, InputStream fis) { BufferedInputStream bis=new BufferedInputStream(fis, 1024*32); String[] result=null; try { byte[] buff=readExifData(bis, 2); if (buff!=null && buff[0]==(byte)0xff && buff[1]==(byte)0xd8) { //JPEG SOI while(buff!=null) {// find dde1 jpeg segemnt buff=readExifData(bis, 4); if (buff!=null) { if (buff[0]==(byte)0xff && buff[1]==(byte)0xe1) { //APP1マーカ int seg_size=getIntFrom2Byte(false, buff[2], buff[3]); buff=readExifData(bis, 14); if (buff!=null) { boolean little_endian=false; if (buff[6]==(byte)0x49 && buff[7]==(byte)0x49) little_endian=true; int ifd_offset=getIntFrom4Byte(little_endian, buff[10], buff[11], buff[12], buff[13]); byte[] ifd_buff=new byte[seg_size+ifd_offset]; System.arraycopy(buff,6,ifd_buff,0,8); buff=readExifData(bis, seg_size); if (buff!=null) { System.arraycopy(buff,0,ifd_buff,8,seg_size); result=process0thIfdTag(little_endian, ifd_buff, ifd_offset); break; } else { stwa.util.addDebugMsg(1,"W","Read Exif date and time failed, because unpredical EOF reached."); return null; } } else { stwa.util.addDebugMsg(1,"W","Read Exif date and time failed, because unpredical EOF reached."); return null; } } else { int offset=((int)buff[2]&0xff)*256+((int)buff[3]&0xff)-2; if (offset<1) { stwa.util.addDebugMsg(1,"W","Read Exif date and time failed, because invalid offset."); return null; } buff=readExifData(bis, offset); } } else { stwa.util.addDebugMsg(1,"W","Read Exif date and time failed, because unpredical EOF reached."); return null; } } } else { stwa.util.addDebugMsg(1,"W","Read exif date and time failed, because Exif header can not be found."); } } catch (Exception e) { e.printStackTrace(); putExceptionMessage(stwa, e.getStackTrace(), e.getMessage()); return null; } return result; } // static private String[] getExifDateTime(SyncThreadWorkArea stwa, InputStream fis, byte[] buff) { // String[] result=null; // try { // if (buff[0]==(byte)0xff && buff[1]==(byte)0xd8) {//if jpeg header // int i=2; // while(i<buff.length-3) {// find dde1 jpeg segemnt // if (buff[i]==(byte)0xff && buff[i+1]==(byte)0xe1) { // int seg_size=getIntFrom2Byte(false, buff[i+2], buff[i+3]); // boolean little_endian=false; // if (buff[i+10]==(byte)0x49 && buff[i+11]==(byte)0x49) little_endian=true; // int ifd_offset=getIntFrom4Byte(little_endian, buff[i+14], buff[i+15], buff[i+16], buff[i+17]); // // byte[] ifd_buff= Arrays.copyOfRange(buff, i+10, seg_size+ifd_offset); // result=process0thIfdTag(little_endian, ifd_buff, ifd_offset); // break; // } else { // int offset=((int)buff[i+2]&0xff)*256+((int)buff[i+3]&0xff); // i=offset+i+2; // } // } // // } // } catch (Exception e) { // e.printStackTrace(); // putExceptionMessage(stwa, e.getStackTrace(), e.getMessage()); // return null; // } // return result; // } static private String formatStackTrace(StackTraceElement[] st) { String st_msg = ""; for (int i = 0; i < st.length; i++) { st_msg += "\n at " + st[i].getClassName() + "." + st[i].getMethodName() + "(" + st[i].getFileName() + ":" + st[i].getLineNumber() + ")"; } return st_msg; } static private int getIntFrom2Byte(boolean little_endian, byte b1, byte b2) { int result=0; if (little_endian) result=((int)b2&0xff)*256+((int)b1&0xff); else result=((int)b1&0xff)*256+((int)b2&0xff); return result; } static private int getIntFrom4Byte(boolean little_endian, byte b1, byte b2, byte b3, byte b4) { int result=0; if (little_endian) result=((int)b4&0xff)*65536+((int)b3&0xff)*4096+((int)b2&0xff)*256+((int)b1&0xff); else result=((int)b1&0xff)*65536+((int)b2&0xff)*4096+((int)b3&0xff)*256+((int)b4&0xff); return result; } static private String[] process0thIfdTag(boolean little_endian, byte[]ifd_buff, int ifd_offset) { int count=getIntFrom2Byte(little_endian, ifd_buff[ifd_offset+0], ifd_buff[ifd_offset+1]); int i=0; int ba=ifd_offset+2; String[] result=null; while(i<count) { int tag_number=getIntFrom2Byte(little_endian, ifd_buff[ba+0], ifd_buff[ba+1]); int tag_offset=getIntFrom4Byte(little_endian, ifd_buff[ba+8], ifd_buff[ba+9], ifd_buff[ba+10], ifd_buff[ba+11]); if (tag_number==(0x8769&0xffff)) {//Exif IFD result=processExifIfdTag(little_endian, ifd_buff, tag_offset); break; } ba+=12; i++; } return result; } static private String[] processExifIfdTag(boolean little_endian, byte[]ifd_buff, int ifd_offset) { int count=getIntFrom2Byte(little_endian, ifd_buff[ifd_offset+0], ifd_buff[ifd_offset+1]); int i=0; int ba=ifd_offset+2; String[] date_time=new String[2]; while(i<count) { int tag_number=getIntFrom2Byte(little_endian, ifd_buff[ba+0], ifd_buff[ba+1]); int tag_offset=getIntFrom4Byte(little_endian, ifd_buff[ba+8], ifd_buff[ba+9], ifd_buff[ba+10], ifd_buff[ba+11]); if (tag_number==(0x9003&0xffff)) {//Date&Time TAG String[] date = new String(ifd_buff, tag_offset, 19).split(" "); if (date.length==2) { date_time[0]=date[0].replaceAll(":", "/");//Date date_time[1]=date[1];//Time break; } } ba+=12; i++; } return date_time; } }
56.789511
174
0.533504
6356d4e95f534a756cc0867fab6cf8054b5934e1
1,572
swift
Swift
Smack Chat/Controller/AddChannelViewController.swift
yash-ganorkar/smack-chat-app
3424d1c6914f07c0ab015dd0d7c68ee8ccef0534
[ "MIT" ]
null
null
null
Smack Chat/Controller/AddChannelViewController.swift
yash-ganorkar/smack-chat-app
3424d1c6914f07c0ab015dd0d7c68ee8ccef0534
[ "MIT" ]
null
null
null
Smack Chat/Controller/AddChannelViewController.swift
yash-ganorkar/smack-chat-app
3424d1c6914f07c0ab015dd0d7c68ee8ccef0534
[ "MIT" ]
null
null
null
// // AddChannelViewController.swift // Smack Chat // // Created by Yash Ganorkar on 1/12/18. // Copyright © 2018 Yash Ganorkar. All rights reserved. // import UIKit class AddChannelViewController: UIViewController { @IBOutlet weak var channelNameText: CustomTextField! @IBOutlet weak var channelDescriptionText: CustomTextField! @IBOutlet weak var bgView: UIView! override func viewDidLoad() { super.viewDidLoad() setupView() // Do any additional setup after loading the view. } @IBAction func closeBtnTouched(_ sender: Any) { dismiss(animated: true, completion: nil) } @IBAction func createBtnTouched(_ sender: Any) { guard let channelName = channelNameText.text, channelNameText.text != "" else { return } guard let channelDescription = channelDescriptionText.text, channelDescriptionText.text != "" else { return } SocketService.instance.addNewChannel(channelName: channelName, channelDescription: channelDescription) { (success) in if success{ self.dismiss(animated: true, completion: nil) } } } func setupView() -> Void { let closeTouch = UITapGestureRecognizer(target: self, action: #selector(AddChannelViewController.closeTap(_:))) bgView.addGestureRecognizer(closeTouch) } @objc func closeTap(_ recognizer: UITapGestureRecognizer){ dismiss(animated: true, completion: nil) } }
27.103448
125
0.641858
0a295d2191d2395c78199eb2808d657b6b1a8942
1,522
h
C
interface/genParticleProducer.h
gkrintir/TopHI
a3ad9566a1ad4514844e8e9adc47eb079d4c47a1
[ "CC0-1.0" ]
null
null
null
interface/genParticleProducer.h
gkrintir/TopHI
a3ad9566a1ad4514844e8e9adc47eb079d4c47a1
[ "CC0-1.0" ]
null
null
null
interface/genParticleProducer.h
gkrintir/TopHI
a3ad9566a1ad4514844e8e9adc47eb079d4c47a1
[ "CC0-1.0" ]
null
null
null
#ifndef genParticleProducer_h #define genParticleProducer_h // // generated particles producer // #include <TNamed.h> #include <TChain.h> #include <TString.h> #include <TClonesArray.h> #include "UserCode/diall/interface/inputBase.h" #include <UserCode/diall/interface/ForestGenParticles.h> class genParticleProducer : public inputBase { public: genParticleProducer(); genParticleProducer(const char *name); virtual ~genParticleProducer() {;} Bool_t Init(); Long64_t LoadTree(Long64_t entry); Bool_t InitEventObjects(); Bool_t Run(Long64_t entry); void SetGenParticlesName(TString n) { fGenParticlesName = n; } void SetStatus(Int_t i ) { fStatus = i; } void SetSubevent(Int_t i ) { fSube = i; } const char* GetGenParticlesName() const { return fGenParticlesName.Data() ; } protected: Bool_t AcceptParticle(Int_t i); TString fGenParticlesName;// name of generated particles branch TClonesArray *fGenParticles; //!generated particles ForestGenParticles fFGenParts; //! generated particles in forest tree Int_t fStatus; // required status Int_t fSube; // required subevent private: genParticleProducer(const genParticleProducer& obj); // copy constructor genParticleProducer& operator=(const genParticleProducer& other); // assignment ClassDef(genParticleProducer,1) }; #endif
31.061224
87
0.661629
74e5ded97501f8a6b4c73cdc2734cc831c94b871
362
asm
Assembly
programs/oeis/037/A037751.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
22
2018-02-06T19:19:31.000Z
2022-01-17T21:53:31.000Z
programs/oeis/037/A037751.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
41
2021-02-22T19:00:34.000Z
2021-08-28T10:47:47.000Z
programs/oeis/037/A037751.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
5
2021-02-24T21:14:16.000Z
2021-08-09T19:48:05.000Z
; A037751: Base 4 digits are, in order, the first n terms of the periodic sequence with initial period 2,3,1,0. ; 2,11,45,180,722,2891,11565,46260,185042,740171,2960685,11842740,47370962,189483851,757935405,3031741620,12126966482,48507865931,194031463725,776125854900,3104503419602,12418013678411,49672054713645 mov $1,4 pow $1,$0 mul $1,48 div $1,17 mov $0,$1
40.222222
199
0.790055
5fd03be95d3da41d02c91ab4a682d80d6f2ad545
270
h
C
include/agumon.h
Yavuz7/VulkanProjectGF3D
4ec4570ee1a018b479b4dffab30897621dad5a6d
[ "MIT" ]
null
null
null
include/agumon.h
Yavuz7/VulkanProjectGF3D
4ec4570ee1a018b479b4dffab30897621dad5a6d
[ "MIT" ]
null
null
null
include/agumon.h
Yavuz7/VulkanProjectGF3D
4ec4570ee1a018b479b4dffab30897621dad5a6d
[ "MIT" ]
null
null
null
#ifndef __AGUMON_H__ #define __AGUMON_H__ #include "entity.h" /** * @brief Create a new agumon entity * @param position where to spawn the aguman at * @return NULL on error, or an agumon entity pointer on success */ Entity *agumon_new(Vector3D position); #endif
18
64
0.737037
5e6141c1dd300d99620f8edf5139248670499f7f
1,431
swift
Swift
Sources/VaporFirestore/Provider.swift
PitchLabsAsh/vapor-firestore
2dd38b22808fb6ef730ca9f1bf758b5b348b643e
[ "MIT" ]
4
2019-04-07T21:35:32.000Z
2021-12-15T01:31:51.000Z
Sources/VaporFirestore/Provider.swift
team360r/vapor-firestore
943d42538f61d2b1d85a463974ed78c52f5cb754
[ "MIT" ]
2
2019-12-04T15:26:30.000Z
2021-11-16T17:32:10.000Z
Sources/VaporFirestore/Provider.swift
team360r/vapor-firestore
943d42538f61d2b1d85a463974ed78c52f5cb754
[ "MIT" ]
8
2019-05-28T19:45:53.000Z
2022-01-27T23:11:56.000Z
// // Provider.swift // App // // Created by Ash Thwaites on 02/04/2019. // import Vapor public struct FirestoreConfig: Service { public let privateKey: String public let email: String public let projectId: String public init(projectId: String, email: String, privateKey: String) { self.projectId = projectId self.email = email self.privateKey = privateKey } } public final class FirestoreProvider: Provider { public init() { } public func boot(_ worker: Container) throws { } public func didBoot(_ worker: Container) throws -> EventLoopFuture<Void> { return .done(on: worker) } public func register(_ services: inout Services) throws { services.register { (container) -> FirestoreClient in let httpClient = try container.make(Client.self) let config = try container.make(FirestoreConfig.self) return FirestoreClient(client: httpClient, projectId: config.projectId, email: config.email, privateKey: config.privateKey) } } } public struct FirestoreClient: Service { public var firestore: FirestoreRoutes internal init(client: Client, projectId: String, email: String, privateKey: String) { let apiRequest = FirestoreAPIRequest(httpClient: client, projectId: projectId, email: email, privateKey: privateKey) firestore = FirestoreRoutes(request: apiRequest) } }
27.519231
135
0.684137
161b2a909515b24afe8a368684f1389d13ca8d22
412
ts
TypeScript
src/configs/firebase/index.ts
sangolariel/react-native-starter-with-typescript
74d92fc22d8d8905e8307c2e0bd16e9d867cda7b
[ "MIT" ]
null
null
null
src/configs/firebase/index.ts
sangolariel/react-native-starter-with-typescript
74d92fc22d8d8905e8307c2e0bd16e9d867cda7b
[ "MIT" ]
null
null
null
src/configs/firebase/index.ts
sangolariel/react-native-starter-with-typescript
74d92fc22d8d8905e8307c2e0bd16e9d867cda7b
[ "MIT" ]
null
null
null
// For Firebase JS SDK v7.20.0 and later, measurementId is optional export const firebaseConfig = { apiKey: 'AIzaSyDbzQ_TPPfagc4K1j4kXknnn4RFQ__JQpM', authDomain: 'bibleplans-8d687.firebaseapp.com', projectId: 'bibleplans-8d687', storageBucket: 'bibleplans-8d687.appspot.com', messagingSenderId: '366495683962', appId: '1:366495683962:web:77511e60b525a7c98ef2c3', measurementId: 'G-1YCYNQVTDL', };
37.454545
67
0.774272
64eaede5e7c0feb93f0289fb5c110405d0bd1a5b
669
java
Java
src/java/com/eazybi/mondrian/udf/CascadingChildrenSetUdf.java
rsim/mondrian_udf
d6bb52417032d975db41a01ecf37c6c92cfb4534
[ "MIT" ]
3
2016-11-15T18:16:48.000Z
2019-07-22T07:33:03.000Z
src/java/com/eazybi/mondrian/udf/CascadingChildrenSetUdf.java
rsim/mondrian_udf
d6bb52417032d975db41a01ecf37c6c92cfb4534
[ "MIT" ]
null
null
null
src/java/com/eazybi/mondrian/udf/CascadingChildrenSetUdf.java
rsim/mondrian_udf
d6bb52417032d975db41a01ecf37c6c92cfb4534
[ "MIT" ]
null
null
null
package com.eazybi.mondrian.udf; import mondrian.olap.*; import mondrian.olap.type.*; import mondrian.spi.UserDefinedFunction; import mondrian.mdx.*; import mondrian.calc.*; import java.util.*; public class CascadingChildrenSetUdf extends ChildrenSetUdf { public Object execute(Evaluator evaluator, Argument[] arguments) { Member member = (Member) arguments[0].evaluate(evaluator); return childrenSet(evaluator, member, true); } public String getDescription() { return "Returns cascading children set of aggregate calculated member (set argument of Aggregate function)."; } public String getName() { return "CascadingChildrenSet"; } }
25.730769
113
0.751868
eec0f318c6171fa0fcb44279c7d63593975f0751
1,925
asm
Assembly
programs/oeis/059/A059570.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
22
2018-02-06T19:19:31.000Z
2022-01-17T21:53:31.000Z
programs/oeis/059/A059570.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
41
2021-02-22T19:00:34.000Z
2021-08-28T10:47:47.000Z
programs/oeis/059/A059570.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
5
2021-02-24T21:14:16.000Z
2021-08-09T19:48:05.000Z
; A059570: Number of fixed points in all 231-avoiding involutions in S_n. ; 1,2,6,14,34,78,178,398,882,1934,4210,9102,19570,41870,89202,189326,400498,844686,1776754,3728270,7806066,16311182,34020466,70837134,147266674,305718158,633805938,1312351118,2714180722,5607318414,11572550770,23860929422,49153514610,101170340750,208067304562,427587855246,878082202738,1801977389966,3695580748914,7574413435790,15515330747506,31763669246862,64993353997426,132918739002254,271701540019314,555131204068238,1133718656195698,2314349808509838,4722524609256562,9632699202986894,19640698374921330,40031996687737742,81565193251265650,166132786254111630,338270372011383922,688550343029089166,1401119884070820978,2850278164166927246,5796633120384425074,11785419824869991310,23955146817942264946,48678907972289094542,98895044617387318386,200864546580392895374,407878007852022307954,828053845086517650318,1680703348937981369458,3410598015405854876558,6919578665871494028402,14035922601862556607374,28465375743964250315890,57717812568406774834062,117009747297770098072690,237167738917453292954510,480631966478732779527282,973856910245117946291086,1972899775065540667055218,3996171459281690883056526,8093086736864600864005234,16387661110331639923794830,33178297493868156239158386,67162545534146065261454222,135936992161111636089183346,275097786507862283310916494,556643177387002588886932594,1126181563516561222304064398,2278153544518234533668527218,4607887924006693245457851278,9318937517953834847157296242,18844198375788566406797779854,38101043431338926238561934450,77027380222201439327056618382,155705347163450052353978735730,314711867764994452107688469390,636026082406177599014838934642,1285256858564732587628601861006,2596923104634219954455051705458,5246664984277949467305799377806,10598967518574918051402990689394,21409210137187874336388765246350 add $0,1 seq $0,66373 ; a(n) = (3*n-2)*2^(n-3). mul $0,2 mov $1,4 add $1,$0 div $1,18 mov $0,$1
175
1,753
0.913247
857d3c448c9351312a1dde95ba0593f44dac1461
392
js
JavaScript
dist/Rx.js
ZachBray/eye-oh-see-react
377d1ef698bdafd3723a11fb0a16245d055bcd4f
[ "MIT" ]
null
null
null
dist/Rx.js
ZachBray/eye-oh-see-react
377d1ef698bdafd3723a11fb0a16245d055bcd4f
[ "MIT" ]
null
null
null
dist/Rx.js
ZachBray/eye-oh-see-react
377d1ef698bdafd3723a11fb0a16245d055bcd4f
[ "MIT" ]
null
null
null
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var rx_1 = require("rx"); /* tslint:enable */ function cache(callback) { var cached$ = this.replay(undefined, 1); var subscription = cached$.connect(); callback(function () { return subscription.dispose(); }); return cached$; } rx_1.Observable.prototype.cache = cache; //# sourceMappingURL=Rx.js.map
32.666667
62
0.688776
9b66c666af537ad0ff595198cff1c15362752535
3,304
asm
Assembly
dos_games/W Produkcji/Algorithms and Examples/flame.asm
QAston/fasm-2006
efc8911cc8b21da2b73865e30cf4c788048fe536
[ "MIT" ]
null
null
null
dos_games/W Produkcji/Algorithms and Examples/flame.asm
QAston/fasm-2006
efc8911cc8b21da2b73865e30cf4c788048fe536
[ "MIT" ]
null
null
null
dos_games/W Produkcji/Algorithms and Examples/flame.asm
QAston/fasm-2006
efc8911cc8b21da2b73865e30cf4c788048fe536
[ "MIT" ]
null
null
null
; ; ; - f l a m e - ; quality 122 byte fire ; copyright 1997 Gaffer/prometheus ; gaffer@zip.com.au ; ; optimization contribution: ; goblin,icepick,mf,patrik sundberg,pgeist ; mark andreas ;# You may wish to insert code to keep Buffer aligned on an ;# even address, regardless of the size of the program. Format binary ORG 100h ; INITIALIZATION: setup video mode & palette ; ------------------------------------------ ; SETUP VGA SEG push 0A000h pop es ; INIT VGA MODE 13h mov al,13h ;# doesn't look nice if using mode 93h int 10h ; GENERATE PALETTE dec di PaletteGen: ; alternate palette generation xor ax,ax ; (Patrick Sundberg) mov cl,63 @@L1: stosb inc ax cmpsw ; small way to advance si,di! ;# why are we advancing SI too ;# scasw works just as well (same size) loop @@L1 push di mov cl,192 @@L2: stosw inc di loop @@L2 pop di inc di jns PaletteGen ; cheesy! :) ; SET PALETTE mov ax,1012h cwd ; equivalent to 'xor dx,dx' mov cl,255 int 10h ; MAIN LOOP: Cycle through flame animation until keypress ; ------------------------------------------------------- MainLoop: push es push ds pop es ; set es=ds to use stosw ; FLAME ANIMATION inc cx mov di,Buffer mov bl,99 @@L3: mov ax,[di+639] add al,ah setc ah mov dl,[di+641] add ax,dx mov dl,[di+1280] add ax,dx shr ax,2 jz @@ZERO ; cool a bit... dec ax @@ZERO: stosb add ax,dx ; double the height shr ax,1 mov [di+319],al loop @@L3 mov cx,320 add di,cx dec bx jnz @@L3 ; FLAME GENERATOR BAR ; assumes cx=320 ; assumes di=generator bar offset (bottom of flame buffer) @@L4: ;# in ax,40h ; read from timer ;# don't need to thump the clock 320 times per frame. That just ;# kills the display on slower video cards, even on Pentiums ;# In fact, the display looks just as nice without this instruction. ;# If you decide it's needed, try moving it to be just before the ;# loop, so you're only reading the port once per frame. ;# xadd [ds:100h],ax ; "seed" is first two bytes of code ;# Instead, use the BP register as a seed. ; xadd bp,ax ;# ;# another option for allowing the program to run on a 386 is to ;# replace XADD, since that's the only 486 instruction used. ;# an alternate of the same size is: add ax,[di] inc ax mov ah,al ;# removing this instruction doesn't seem to affect the display. stosw stosw loop @@L4 pop es ; restore es=A000h ; OUTPUT FLAME TO SCREEN xor di,di lea si,[Buffer+320] mov ch,60 ; assumes cl=0 rep movsd ; change to "mov ch,120" "rep movsw" ; saves one byte but is slower ; (patrik sundberg) ; CHECK FOR KEYPRESS mov ah,1 int 16h jz MainLoop ; alternative keypress check ; "in al,60h" "das" "jc MainLoop" ; saves one byte but is not as reliable ; (icepick) ; DOS EXIT CODE: Switch to textmode, return to DOS ; ------------------------------------------------ mov ax,03h int 10h ret ;data: Buffer: times 320*203 db ?
20.146341
69
0.575363
58bbf696b319663a614429981a5ec30990b2c5c1
2,355
dart
Dart
example/lib/example.dart
larsb24/utopia
81de7ae8b7e52eadf7c53e607c062c97c3bb0157
[ "Apache-2.0" ]
null
null
null
example/lib/example.dart
larsb24/utopia
81de7ae8b7e52eadf7c53e607c062c97c3bb0157
[ "Apache-2.0" ]
null
null
null
example/lib/example.dart
larsb24/utopia
81de7ae8b7e52eadf7c53e607c062c97c3bb0157
[ "Apache-2.0" ]
null
null
null
import 'dart:math'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:utopia_wm/wm.dart'; class ExampleApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), debugShowCheckedModeBanner: false, shortcuts: {}, home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { setState(() { _counter++; }); } @override Widget build(BuildContext context) { final entry = context.watch<WindowEntry>(); return Scaffold( appBar: AppBar( title: Text("Example"), ), body: Center( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ Text( MediaQuery.of(context).size.toString(), ), Text( '$_counter', style: Theme.of(context).textTheme.headline4, ), TextButton( child: Text("Toggle toolbar"), onPressed: () { entry.usesToolbar = !entry.usesToolbar; setState(() {}); }, ), TextButton( child: Text("Change toolbar color"), onPressed: () { entry.toolbarColor = Colors .primaries[Random().nextInt(Colors.primaries.length - 1)]; setState(() {}); }, ), TextButton( child: Text("Spawn dialog"), onPressed: () { showDialog( context: context, useRootNavigator: false, builder: (context) => AlertDialog( title: Text("Helo"), content: Text("Yo"), ), ); }, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: Icon(Icons.add), ), ); } }
25.053191
78
0.501062
967d737a8e7ef96e1fc0c322ab2b4f0a5a9fdb98
926
dart
Dart
lib/src/states/router_state.dart
tnc1997/flutter-train-simulator-utilities
0443b1c950b8c9f0d8d87d6a8ed7391e4a1caea7
[ "MIT" ]
null
null
null
lib/src/states/router_state.dart
tnc1997/flutter-train-simulator-utilities
0443b1c950b8c9f0d8d87d6a8ed7391e4a1caea7
[ "MIT" ]
null
null
null
lib/src/states/router_state.dart
tnc1997/flutter-train-simulator-utilities
0443b1c950b8c9f0d8d87d6a8ed7391e4a1caea7
[ "MIT" ]
null
null
null
import 'package:flutter/widgets.dart'; import 'package:train_simulator_utilities/src/route_paths/route_path.dart'; class RouterState extends InheritedNotifier<RouterStateData> { const RouterState({ Key key, RouterStateData notifier, @required Widget child, }) : super( key: key, notifier: notifier, child: child, ); static RouterStateData of(BuildContext context) { return context.dependOnInheritedWidgetOfExactType<RouterState>().notifier; } } class RouterStateData extends ChangeNotifier { RoutePath _path; Map<String, dynamic> _state; RoutePath get path => _path; set path(RoutePath value) { if (value != _path) { _path = value; notifyListeners(); } } Map<String, dynamic> get state => _state; set state(Map<String, dynamic> value) { if (value != _state) { _state = value; notifyListeners(); } } }
22.047619
78
0.664147
7baf21915a61da5399409e5817466fc7b228296f
200
rb
Ruby
spec/models/report_spec.rb
Rim-777/Ad-Matcher
8e693c02161f45416c255b7cdc8462c89612c015
[ "MIT" ]
null
null
null
spec/models/report_spec.rb
Rim-777/Ad-Matcher
8e693c02161f45416c255b7cdc8462c89612c015
[ "MIT" ]
null
null
null
spec/models/report_spec.rb
Rim-777/Ad-Matcher
8e693c02161f45416c255b7cdc8462c89612c015
[ "MIT" ]
null
null
null
require 'spec_helper' RSpec.describe Report, type: :model do it {should belong_to(:verification)} it {should validate_presence_of(:verification)} it {should validate_presence_of(:message)} end
25
49
0.775
ff9ddbc6cdd32ffb947406e90f57cf2648d81d53
486
sql
SQL
conf/evolutions/default/2.sql
Antanukas/play-reactive-workshop
da952e17e384163ec71a6fdf48c55bfeeef05602
[ "Apache-2.0" ]
null
null
null
conf/evolutions/default/2.sql
Antanukas/play-reactive-workshop
da952e17e384163ec71a6fdf48c55bfeeef05602
[ "Apache-2.0" ]
null
null
null
conf/evolutions/default/2.sql
Antanukas/play-reactive-workshop
da952e17e384163ec71a6fdf48c55bfeeef05602
[ "Apache-2.0" ]
null
null
null
# --- !Ups CREATE TABLE "comments"( "id" SERIAL PRIMARY KEY NOT NULL, "user" INT NOT NULL, "repository_owner" VARCHAR(100) NOT NULL, "repository_name" VARCHAR(100) NOT NULL, "comment" VARCHAR(500), "created_on" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, CONSTRAINT user_fk FOREIGN KEY("user") REFERENCES "users"("id") ON DELETE RESTRICT, ); # --- !Downs DROP TABLE "comments";
30.375
89
0.574074
04fcc590e2382753d82c0ef4d5c92088ba9a076e
2,947
java
Java
support/cas-server-support-configuration/src/main/java/org/apereo/cas/config/CasConfigurationSupportUtilitiesConfiguration.java
ConnCollege/CAS-5-FS
c1c6598c561f66548034d6e30bfc2e2127cdfb85
[ "Apache-2.0" ]
null
null
null
support/cas-server-support-configuration/src/main/java/org/apereo/cas/config/CasConfigurationSupportUtilitiesConfiguration.java
ConnCollege/CAS-5-FS
c1c6598c561f66548034d6e30bfc2e2127cdfb85
[ "Apache-2.0" ]
null
null
null
support/cas-server-support-configuration/src/main/java/org/apereo/cas/config/CasConfigurationSupportUtilitiesConfiguration.java
ConnCollege/CAS-5-FS
c1c6598c561f66548034d6e30bfc2e2127cdfb85
[ "Apache-2.0" ]
1
2020-11-04T06:54:58.000Z
2020-11-04T06:54:58.000Z
package org.apereo.cas.config; import com.google.common.base.Throwables; import org.apereo.cas.config.monitor.ConfigurationDirectoryPathWatchService; import org.apereo.cas.configuration.CasConfigurationProperties; import org.apereo.cas.configuration.CasConfigurationPropertiesEnvironmentManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import javax.annotation.PostConstruct; import java.io.File; /** * This is {@link CasConfigurationSupportUtilitiesConfiguration}. * * @author Misagh Moayyed * @since 5.1.0 */ @Configuration("casConfigurationSupportUtilitiesConfiguration") @EnableConfigurationProperties(CasConfigurationProperties.class) public class CasConfigurationSupportUtilitiesConfiguration { private static final Logger LOGGER = LoggerFactory.getLogger(CasConfigurationSupportUtilitiesConfiguration.class); @Autowired private CasConfigurationProperties casProperties; /** * The watch configuration. */ @Configuration("casCoreConfigurationWatchConfiguration") @Profile("standalone") @ConditionalOnProperty(value = "spring.cloud.config.enabled", havingValue = "false") public class CasCoreConfigurationWatchConfiguration { @Autowired private ApplicationEventPublisher eventPublisher; @Autowired @Qualifier("configurationPropertiesEnvironmentManager") private CasConfigurationPropertiesEnvironmentManager configurationPropertiesEnvironmentManager; @PostConstruct public void init() { runNativeConfigurationDirectoryPathWatchService(); } public void runNativeConfigurationDirectoryPathWatchService() { try { final File config = configurationPropertiesEnvironmentManager.getStandaloneProfileConfigurationDirectory(); if (casProperties.getEvents().isTrackConfigurationModifications() && config.exists()) { LOGGER.debug("Starting to watch configuration directory [{}]", config); final Thread th = new Thread(new ConfigurationDirectoryPathWatchService(config.toPath(), eventPublisher)); th.start(); } else { LOGGER.info("CAS is configured to NOT watch configuration directory [{}]. Changes require manual reloads/restarts.", config); } } catch (final Exception e) { throw Throwables.propagate(e); } } } }
42.1
145
0.743807
1e84bb4541b577af55dd48a1b6df46bad0db8e8b
6,206
swift
Swift
clip2gether/UploadViewController.swift
re-man/2fieApp
f34714417f61ff5b507aa284700f440d92eb1a23
[ "MIT" ]
null
null
null
clip2gether/UploadViewController.swift
re-man/2fieApp
f34714417f61ff5b507aa284700f440d92eb1a23
[ "MIT" ]
null
null
null
clip2gether/UploadViewController.swift
re-man/2fieApp
f34714417f61ff5b507aa284700f440d92eb1a23
[ "MIT" ]
null
null
null
// // UploadViewController.swift // clip2gether // // Created by Ali on 20.08.15. // Copyright © 2015 Remanence. All rights reserved. // import UIKit import Foundation class UploadViewController: UIViewController, UINavigationControllerDelegate { @IBOutlet var locImage: UIImageView! @IBOutlet var message: UITextField! @IBOutlet var sendButton: UIButton! @IBAction func sendButtonPressed(sender: AnyObject) { send() } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { view.endEditing(true) super.touchesBegan(touches, withEvent: event!) } // Automatic login after textfield func textFieldShouldReturn(textField: UITextField) -> Bool { message.resignFirstResponder() if textField == message { send() } return true } override func viewWillAppear(animated: Bool) { self.navigationController?.setNavigationBarHidden(false, animated: true) dispatch_async(dispatch_get_main_queue(),{ self.message.roundCorners([UIRectCorner.BottomLeft , UIRectCorner.BottomRight], radius: 3.0) self.sendButton.layer.cornerRadius = 3.0 }) locImage.image = globalImage activityIndicator = UIActivityIndicatorView(frame: self.view.frame) activityIndicator.backgroundColor = UIColor(white: 1.0, alpha: 0.7) activityIndicator.center = self.view.center activityIndicator.hidesWhenStopped = true activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray view.addSubview(activityIndicator) } // http://www.clip2gether.com/mobile/app/v1/iOS/upload/upload.php func send() { activityIndicator.startAnimating() UIApplication.sharedApplication().beginIgnoringInteractionEvents() let request = NSMutableURLRequest(URL: NSURL(string: "http://www.clip2gether.com/mobile/app/v1/iOS/upload/upload.php")!) request.HTTPMethod = "POST" let imageData :NSData = UIImageJPEGRepresentation(globalImage, 1.0)!; let boundary = "SwiftBoundary" let contentType = "multipart/form-data; boundary=\(boundary)" let fileName = "\(globalImage.hash).jpg" let parameterName = "contest-photo" let body = NSMutableData() body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData("Content-Disposition: form-data; name=\"username\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData("\(globalUsr)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData("Content-Disposition: form-data; name=\"photo-name\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData("\(message.text!)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData("Content-Disposition: form-data; name=\"photo-description\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData("\(message.text)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData("Content-Disposition: form-data; name=\"\(parameterName)\"; filename=\"\(fileName)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData("Content-Type: image/jpeg\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) body.appendData(imageData) body.appendData("\r\n--\(boundary)--".dataUsingEncoding(NSUTF8StringEncoding)!) request.setValue(contentType, forHTTPHeaderField: "Content-Type") request.setValue("\(body.length)", forHTTPHeaderField: "Content-Length") request.HTTPBody = body request.HTTPBody = body let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in if let error = error { print(error) } if let data = data{ print("data =\(data)") } if let response = response { print("response = \(response)") dispatch_async(dispatch_get_main_queue()) { activityIndicator.stopAnimating() UIApplication.sharedApplication().endIgnoringInteractionEvents() let alertController = UIAlertController(title: "Danke", message: "Vielen Dank für das Hochladen deines 2fies.", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: { action in dispatch_async(dispatch_get_main_queue()) { self.locImage = nil self.message = nil self.performSegueWithIdentifier("afterUpload", sender: self) } })) self.presentViewController(alertController, animated: true, completion: nil) self.performSegueWithIdentifier("afterUpload", sender: self) } } }) task.resume() } } extension NSMutableData { func appendString(string: String) { let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) appendData(data!) } }
39.528662
177
0.622301
74fcf9953e582371496c4019c62252f43cc129f5
7,840
asm
Assembly
bootloader/stage2.asm
osstudy/thor-os
9b5793da647a27d7a6de2e48f6dd39dca0313d2b
[ "BSL-1.0" ]
null
null
null
bootloader/stage2.asm
osstudy/thor-os
9b5793da647a27d7a6de2e48f6dd39dca0313d2b
[ "BSL-1.0" ]
null
null
null
bootloader/stage2.asm
osstudy/thor-os
9b5793da647a27d7a6de2e48f6dd39dca0313d2b
[ "BSL-1.0" ]
1
2020-02-04T16:36:51.000Z
2020-02-04T16:36:51.000Z
;======================================================================= ; Copyright Baptiste Wicht 2013-2016. ; Distributed under the Boost Software License, Version 1.0. ; (See accompanying file LICENSE_1_0.txt or copy at ; http://www.boost.org/LICENSE_1_0.txt) ;======================================================================= [BITS 16] jmp second_step %include "intel_16.asm" FREE_SEGMENT equ 0x5000 FREE_BASE equ 0x4500 KERNEL_BASE equ 0x600 ; 0x600:0x0 (0x6000) DAP: .size db 0x10 .null db 0x0 .count dw 0 .offset dw 0 .segment dw 0x0 .lba dd 0 .lba48 dd 0 ; Perform an extended read using BIOS ; On error, jump to read_failed and never returns extended_read: mov ah, 0x42 mov si, DAP mov dl, 0x80 int 0x13 jc read_failed ret ; Loaded at 0x410:0x0 (0x4100) second_step: ; Set data segment mov ax, 0x410 mov ds, ax ; Used for disk access mov ax, FREE_SEGMENT mov gs, ax mov si, load_kernel call print_line_16 ; 1. Read the MBR to get partition table mov byte [DAP.count], 1 mov word [DAP.offset], FREE_BASE mov word [DAP.segment], FREE_SEGMENT mov dword [DAP.lba], 0 call extended_read mov ax, [gs:(FREE_BASE + 446 + 8)] mov [partition_start], ax ; 2. Read the VBR of the partition to get FAT informations mov byte [DAP.count], 1 mov word [DAP.offset], FREE_BASE mov word [DAP.segment], FREE_SEGMENT mov di, [partition_start] mov word [DAP.lba], di call extended_read mov ah, [gs:(FREE_BASE + 13)] mov [sectors_per_cluster], ah mov ax, [gs:(FREE_BASE + 14)] mov [reserved_sectors], ax mov ah, [gs:(FREE_BASE + 16)] mov [number_of_fat], ah mov ax, [gs:(FREE_BASE + 38)] test ax, ax jne sectors_per_fat_too_high ; sectors_per_fat (only low part) mov ax, [gs:(FREE_BASE + 36)] mov [sectors_per_fat], ax mov ax, [gs:(FREE_BASE + 44)] mov [root_dir_start], ax ; fat_begin = partition_start + reserved_sectors mov ax, [partition_start] mov bx, [reserved_sectors] add ax, bx mov [fat_begin], ax ; cluster_begin = (number_of_fat * sectors_per_fat) + fat_begin mov ax, [sectors_per_fat] movzx bx, [number_of_fat] mul bx mov bx, [fat_begin] add ax, bx mov [cluster_begin], ax ; entries per cluster = (512/32) * sectors_per_cluster movzx ax, byte [sectors_per_cluster] shl ax, 4 mov [entries_per_cluster], ax ; 3. Read the root directory to find the kernel executable mov ah, [sectors_per_cluster] mov byte [DAP.count], ah mov word [DAP.offset], FREE_BASE mov word [DAP.segment], FREE_SEGMENT ; Compute LBA from root_dir_start mov ax, [root_dir_start] sub ax, 2 movzx bx, byte [sectors_per_cluster] mul bx mov bx, [cluster_begin] add ax, bx mov word [DAP.lba], ax call extended_read mov si, FREE_BASE xor cx, cx .next: mov ah, [gs:si] ; Test if it is the end of the directory test ah, ah je .end_of_directory mov ax, [gs:si] cmp ax, 0x4E49 ; NI jne .continue mov ax, [gs:(si+2)] cmp ax, 0x5449 ; TI jne .continue mov ax, [gs:(si+4)] cmp ax, 0x2020 ; space space jne .continue mov ax, [gs:(si+6)] cmp ax, 0x2020 ; space space jne .continue mov ax, [gs:(si+8)] cmp ax, 0x4942; IB jne .continue mov ah, [gs:(si+10)] cmp ah, 0x4E ; N jne .continue ; cluster high mov ax, [gs:(si+20)] mov [cluster_high], ax ; cluster low mov ax, [gs:(si+26)] mov [cluster_low], ax jmp .found .continue: add si, 32 inc cx mov bx, [entries_per_cluster] cmp cx, bx jne .next .end_of_cluster: mov si, multicluster_directory call print_line_16 jmp error_end .end_of_directory: mov si, kernel_not_found call print_line_16 jmp error_end .found: mov si, kernel_found call print_line_16 ; 4. Load the kernel into memory mov ax, [cluster_high] test ax, ax jne cluster_too_high mov ax, [cluster_low] mov [current_cluster], ax mov word [current_segment], KERNEL_BASE .next_cluster: mov si, star call print_16 mov di, [current_segment] call print_int_16 mov si, star call print_16 movzx ax, [sectors_per_cluster] mov word [DAP.count], ax mov word [DAP.offset], 0x0 mov ax, [current_segment] mov [DAP.segment], ax ; Compute LBA from current_cluster mov ax, [current_cluster] sub ax, 2 movzx bx, byte [sectors_per_cluster] mul bx mov bx, [cluster_begin] add ax, bx mov word [DAP.lba], ax mov di, ax call print_int_16 mov si, star call print_16 mov di, [current_cluster] call print_int_16 call extended_read mov ax, [loaded_clusters] inc ax mov [loaded_clusters], ax ; Compute next cluster ; Compute the sector of the FAT to read mov ax, [current_cluster] shl ax, 2 ; current_cluster * 4 shr ax, 9 ; (current_cluster * 4) / 512 mov bx, [fat_begin] add ax, bx ; fat_sector ; Read the FAT sector mov word [DAP.count], 1 mov word [DAP.offset], FREE_BASE mov word [DAP.segment], FREE_SEGMENT mov word [DAP.lba], ax call extended_read mov si, [current_cluster] and si, 512 - 1 ; current_cluster % 512 shl si, 2 ; cluster low mov ax, [gs:(FREE_BASE + si)] ; cluster high mov bx, [gs:(FREE_BASE + si + 2)] cmp bx, 0x0FFF jl .ok cmp ax, 0xFFF7 je corrupted cmp ax, 0xFFF8 jge .fully_loaded .ok: test bx, bx jne cluster_too_high mov [current_cluster], ax movzx ax, byte [sectors_per_cluster] shl ax, 5 mov bx, [current_segment] add ax, bx mov [current_segment], ax jmp .next_cluster .fully_loaded: call new_line_16 mov di, [loaded_clusters] call print_int_16 mov si, clusters_loaded call print_line_16 mov si, kernel_loaded call print_line_16 call KERNEL_BASE:0x0 jmp $ cluster_too_high: mov si, cluster_too_high_msg call print_line_16 jmp error_end sectors_per_fat_too_high: mov si, sectors_per_fat_too_high_msg call print_line_16 jmp error_end corrupted: mov si, corrupted_disk call print_line_16 jmp error_end read_failed: mov si, read_failed_msg call print_line_16 error_end: mov si, load_failed call print_line_16 jmp $ ; Variables partition_start dw 0 reserved_sectors dw 0 number_of_fat db 0 sectors_per_fat dw 0 sectors_per_cluster db 0 root_dir_start dw 0 entries_per_cluster dw 0 fat_begin dw 0 cluster_begin dw 0 cluster_high dw 0 cluster_low dw 0 current_cluster dw 0 current_segment dw 0 loaded_clusters dw 0 ; Constant Datas load_kernel db 'Attempt to load the kernel...', 0 kernel_found db 'Kernel found. Starting kernel loading...', 0 kernel_loaded db 'Kernel fully loaded', 0 clusters_loaded db ' clusters loaded', 0 star db '*', 0 kernel_not_found db 'Kernel not found', 0 corrupted_disk db 'The disk seeems to be corrupted', 0 sectors_per_fat_too_high_msg db 'Error 1. The disk is probably too big', 0 multicluster_directory db 'Error 2. Multicluster directory are not supported', 0 cluster_too_high_msg db 'Error 3. Only 16bit cluster are supported', 0 read_failed_msg db 'Read disk failed', 0 load_failed db 'Kernel loading failed', 0 ; Make it sector-aligned times 1536-($-$$) db 0
20.258398
84
0.620918
d49441ecaebd704ce0a400622720a457ee73b83e
1,036
swift
Swift
Stranger-Chat/Injection/Provider.swift
Limbou/Stranger-Chat
135e8b1cd06f05c2938b79885ca5d77c25b77264
[ "MIT" ]
null
null
null
Stranger-Chat/Injection/Provider.swift
Limbou/Stranger-Chat
135e8b1cd06f05c2938b79885ca5d77c25b77264
[ "MIT" ]
4
2018-11-19T13:12:24.000Z
2019-12-08T16:35:21.000Z
Stranger-Chat/Injection/Provider.swift
Limbou/Stranger-Chat
135e8b1cd06f05c2938b79885ca5d77c25b77264
[ "MIT" ]
1
2019-12-09T07:52:23.000Z
2019-12-09T07:52:23.000Z
// // Provider.swift // Stranger-Chat // // Created by Jakub Danielczyk on 21/11/2019. // Copyright © 2019 Jakub Danielczyk. All rights reserved. // import UIKit import Swinject import SwinjectAutoregistration final class Provider { static let get = Provider() private let assembler: Assembler private init() { assembler = Assembler([ScreenAssembly(), RepositoryAssembly(), ServicesAssembly()]) } func instanceOf<Service>(_ serviceType: Service.Type) -> Service { return assembler.resolver.resolve(serviceType)! } func instanceOf<Service, Argument>(_ serviceType: Service.Type, argument: Argument) -> Service { return assembler.resolver.resolve(serviceType, argument: argument)! } func instanceOf<Service, Argument, Argument2>(_ serviceType: Service.Type, arguments: Argument, _ arg2: Argument2) -> Service { return assembler.resolver.resolve(serviceType, arguments: arguments, arg2)! } }
27.263158
131
0.664093
4ca2942128478d5ee22245d690f5bda8153e41a4
329
kt
Kotlin
brick/src/commonMain/kotlin/com/alphicc/brick/ChildScreenRouter.kt
alphicc/Brick
50f811094b0beb2e7e57a46ab08399cdfb94e91b
[ "MIT" ]
36
2021-12-09T17:02:22.000Z
2022-03-03T08:58:15.000Z
brick/src/commonMain/kotlin/com/alphicc/brick/ChildScreenRouter.kt
alphicc/Brick
50f811094b0beb2e7e57a46ab08399cdfb94e91b
[ "MIT" ]
1
2022-01-01T17:28:05.000Z
2022-01-10T17:49:37.000Z
brick/src/commonMain/kotlin/com/alphicc/brick/ChildScreenRouter.kt
alphicc/Brick
50f811094b0beb2e7e57a46ab08399cdfb94e91b
[ "MIT" ]
null
null
null
package com.alphicc.brick interface ChildScreenRouter { fun lastChildKey(): String? fun backChild() fun backToChild(key: String) fun replaceChild(screen: Screen<*>) fun addChild(screen: Screen<*>) fun <A> replaceChild(screen: Screen<*>, argument: A) fun <A> addChild(screen: Screen<*>, argument: A) }
29.909091
56
0.680851
40e403b1159f0990df0d660b8734e0b28c883bce
1,746
py
Python
test/test_cli.py
narthur/taskratchet-cli
83ad0e73bd70b6fad65607dbe7ea3ae103722fd5
[ "MIT" ]
null
null
null
test/test_cli.py
narthur/taskratchet-cli
83ad0e73bd70b6fad65607dbe7ea3ae103722fd5
[ "MIT" ]
null
null
null
test/test_cli.py
narthur/taskratchet-cli
83ad0e73bd70b6fad65607dbe7ea3ae103722fd5
[ "MIT" ]
null
null
null
import unittest from test.test_case import TestCase from tr_cli.cli import Cli class TestCli(TestCase): _cli = None def setUp(self) -> None: super().setUp() self._mock_yaml.load.return_value = {'auth': { 'user_id': 'user_id', 'token': 'token' }} self._cli = self._factory.secure(Cli) def _runRequest(self, method, endpoint, staging=False): return self._cli.run({ '--staging': staging, '<endpoint>': endpoint, '<method>': method }) def test_arbitrary_post(self): self._runRequest("post", "endpoint") self._mock_api.post.assert_any_call("endpoint") def test_authenticates_api(self): self._mock_api.authenticate.assert_any_call("user_id", "token") def test_loads_config(self): self._mock_yaml.load.assert_any_call('config.yaml') def test_returns_api_response(self): self._mock_api.post.return_value = 'response' result = self._runRequest("post", "endpoint") self.assertEqual('response', result) def test_get_command(self): self._runRequest("get", "endpoint") self._mock_api.get.assert_any_call("endpoint") def test_get_does_not_post(self): self._runRequest("get", "endpoint") self._mock_api.post.assert_not_called() def test_returns_get_response(self): self._mock_api.get.return_value = 'response' result = self._runRequest("get", "endpoint") self.assertEqual('response', result) def test_sets_api_staging(self): self._runRequest("get", "endpoint", True) self._mock_api.set_staging.assert_called() if __name__ == '__main__': unittest.main()
25.304348
71
0.63803
f0971c062f044157b3133f4c553f7e3b4edff3d9
738
js
JavaScript
client/src/components/layout/Landing.js
salmanbao/Ethereum-Base-File-Notarization
cb6d894ca337416445b211ba262f33973b0e4dff
[ "MIT" ]
null
null
null
client/src/components/layout/Landing.js
salmanbao/Ethereum-Base-File-Notarization
cb6d894ca337416445b211ba262f33973b0e4dff
[ "MIT" ]
null
null
null
client/src/components/layout/Landing.js
salmanbao/Ethereum-Base-File-Notarization
cb6d894ca337416445b211ba262f33973b0e4dff
[ "MIT" ]
null
null
null
import React from 'react' import { Link } from 'react-router-dom' const Landing = () => { return ( <div className="container text-center mt-15"> <div className="row"> <div className="col-sm-12 "> <h1>Login/Register Module</h1> <p>[Full-stack app with user authentication via passport and JWTs]</p> </div> </div> <div className="row mt-4"> <div className="col-sm-12"> <Link to="/register" className="btn btn-large btn-dark hoverable"> Register </Link> <Link to="/login" className="btn btn-large btn-light hoverable ml-5"> Log In </Link> </div> </div> </div> ) } export default Landing
27.333333
80
0.550136
909d333530396c112a3490e6e73f513288156f84
2,324
py
Python
pointnet2_cls_msg.py
HarborZeng/pointnet2-keras
8298ed6f889bbd15e55c58266e574475dc0f92fc
[ "MIT" ]
8
2019-04-10T08:03:16.000Z
2021-06-21T07:29:05.000Z
pointnet2_cls_msg.py
HarborZeng/pointnet2-keras
8298ed6f889bbd15e55c58266e574475dc0f92fc
[ "MIT" ]
1
2020-06-09T09:23:45.000Z
2021-01-01T05:31:35.000Z
pointnet2_cls_msg.py
HarborZeng/pointnet2-keras
8298ed6f889bbd15e55c58266e574475dc0f92fc
[ "MIT" ]
5
2019-04-04T14:27:28.000Z
2021-04-15T13:26:27.000Z
from util.tf_util import * from util.pointnet_util import pointnet_sa_module, pointnet_sa_module_msg import tensorflow as tf def placeholder_inputs(batch_size, num_point): pointclouds_pl = tf.placeholder(tf.float32, shape=(batch_size, num_point, 3)) labels_pl = tf.placeholder(tf.int32, shape=(batch_size)) return pointclouds_pl, labels_pl def get_model(point_cloud, is_training, bn_decay=None): """ Classification PointNet, input is BxNx3, output Bx40 """ batch_size = point_cloud.get_shape()[0].value l0_xyz = point_cloud l0_points = None # Set abstraction layers l1_xyz, l1_points = pointnet_sa_module_msg(l0_xyz, l0_points, 512, [0.1, 0.2, 0.4], [16, 32, 128], [[32, 32, 64], [64, 64, 128], [64, 96, 128]], is_training, bn_decay, scope='layer1', use_nchw=True) l2_xyz, l2_points = pointnet_sa_module_msg(l1_xyz, l1_points, 128, [0.2, 0.4, 0.8], [32, 64, 128], [[64, 64, 128], [128, 128, 256], [128, 128, 256]], is_training, bn_decay, scope='layer2') l3_xyz, l3_points, _ = pointnet_sa_module(l2_xyz, l2_points, npoint=None, radius=None, nsample=None, mlp=[256, 512, 1024], mlp2=None, group_all=True, is_training=is_training, bn_decay=bn_decay, scope='layer3') # Fully connected layers net = tf.reshape(l3_points, [batch_size, -1]) net = fully_connected(net, 512, bn=True, is_training=is_training, scope='fc1', bn_decay=bn_decay) net = dropout(net, keep_prob=0.4, is_training=is_training, scope='dp1') net = fully_connected(net, 256, bn=True, is_training=is_training, scope='fc2', bn_decay=bn_decay) net = dropout(net, keep_prob=0.4, is_training=is_training, scope='dp2') net = fully_connected(net, 40, activation_fn=None, scope='fc3') return net def get_loss(pred, label): """ pred: B*NUM_CLASSES, label: B, """ loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=pred, labels=label) classify_loss = tf.reduce_mean(loss) tf.summary.scalar('classify loss', classify_loss) tf.add_to_collection('losses', classify_loss)
48.416667
120
0.629088
04f3d01d6634ac1a68da6a7087db2576158d6198
787
java
Java
springboot-demo/src/main/java/com/itjing/controller/HelloController.java
xiaoxiaojingge/ComponentStudy
803da36583cac918dc855bcae9d3a7c38320eb2d
[ "Apache-2.0" ]
null
null
null
springboot-demo/src/main/java/com/itjing/controller/HelloController.java
xiaoxiaojingge/ComponentStudy
803da36583cac918dc855bcae9d3a7c38320eb2d
[ "Apache-2.0" ]
null
null
null
springboot-demo/src/main/java/com/itjing/controller/HelloController.java
xiaoxiaojingge/ComponentStudy
803da36583cac918dc855bcae9d3a7c38320eb2d
[ "Apache-2.0" ]
null
null
null
package com.itjing.controller; import com.itjing.entity.Person; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.*; /** * @author lijing * @date 2021年12月10日 15:39 * @description */ @RestController @RequestMapping("/hello") public class HelloController { @Value("${spring.datasource.password}") private String password; @GetMapping("/hello") public String hello(String name, String sex) { return "Hello " + name + ",你的性别是:" + sex + " !"; } @PostMapping("/add") public String add(@RequestBody Person person) { return person.toString(); } @GetMapping("/testEncryptionPropertyResolver") public String testEncryptionPropertyResolver(){ return password; } }
23.147059
58
0.683609
26978ee32a2ce2eaf30359bf755145d5e31137a9
790
java
Java
src/main/java/com/wujunshen/AggregatorApplication.java
TANGKUO/spring-cloud-aggregator
3e970bda0b6e5f504156bcea60928e366d65c866
[ "Apache-2.0" ]
null
null
null
src/main/java/com/wujunshen/AggregatorApplication.java
TANGKUO/spring-cloud-aggregator
3e970bda0b6e5f504156bcea60928e366d65c866
[ "Apache-2.0" ]
null
null
null
src/main/java/com/wujunshen/AggregatorApplication.java
TANGKUO/spring-cloud-aggregator
3e970bda0b6e5f504156bcea60928e366d65c866
[ "Apache-2.0" ]
null
null
null
package com.wujunshen; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.cloud.netflix.turbine.EnableTurbine; @SpringBootApplication @EnableTurbine public class AggregatorApplication { private static final Logger LOGGER = LoggerFactory.getLogger(AggregatorApplication.class); public static void main(String[] args) { LOGGER.info("start execute AggregatorApplication....\n"); //SpringApplication.run(AggregatorApplication.class, args); new SpringApplicationBuilder(AggregatorApplication.class).web(true).run(args); LOGGER.info("end execute AggregatorApplication....\n"); } }
37.619048
94
0.78481
c39ca01a6d45bcb096221f8488d6b1b59cff84bf
5,854
lua
Lua
lua/libk/3rdparty/glib/lua/namecache.lua
askrealcookie/LibK
a433949d5e629cb8c9f29ad47ad0c5c8d09c9dc9
[ "MIT" ]
41
2015-01-07T02:14:44.000Z
2021-09-28T10:06:54.000Z
lua/libk/3rdparty/glib/lua/namecache.lua
askrealcookie/LibK
a433949d5e629cb8c9f29ad47ad0c5c8d09c9dc9
[ "MIT" ]
38
2015-01-04T18:38:07.000Z
2022-01-14T14:14:05.000Z
lua/libk/3rdparty/glib/lua/namecache.lua
askrealcookie/LibK
a433949d5e629cb8c9f29ad47ad0c5c8d09c9dc9
[ "MIT" ]
31
2015-07-30T07:41:51.000Z
2022-01-12T18:24:07.000Z
local self = {} GLib.Lua.NameCache = GLib.MakeConstructor (self) function self:ctor () local state = {} state.NameCache = GLib.WeakKeyTable () state.QueuedTables = GLib.WeakKeyTable () state.QueueTables = {} state.QueueTableNames = {} state.QueueSeparators = {} self.GetState = function (self) return state end self.Thread = nil self:GetState ().NameCache [_G] = "_G" self:GetState ().NameCache [debug.getregistry ()] = "_R" self:Index (GLib, "GLib") self:Index (_G, "") self:Index (debug.getregistry (), "_R") if CLIENT then local _, vguiControlTable = debug.getupvalue(vgui.Register, 1) self:Index (vguiControlTable, "") end hook.Add ("GLibSystemLoaded", "GLib.Lua.NameCache", function (systemName) self:Index (_G [systemName], systemName) if CLIENT then local _, vguiControlTable = debug.getupvalue(vgui.Register, 1) self:GetState ().QueuedTables [vguiControlTable] = nil self:Index (vguiControlTable, "") end end ) end function self:GetFunctionName (func) return self:GetState ().NameCache [func] end function self:GetObjectName (object) return self:GetState ().NameCache [object] end function self:GetTableName (table) return self:GetState ().NameCache [table] end function self:IsIndexingThreadRunning () if not self.Thread then return false end return not self.Thread:IsTerminated () end function self:Index (table, tableName, dot) self:QueueIndex (table, tableName, dot) if not self:IsIndexingThreadRunning () then self:StartIndexingThread () end end local tableNameBlacklist = { ["chathud.lines"] = true, ["chathud.markup.chunks"] = true, ["chatsounds.ac.words"] = true, ["chatsounds.List"] = true, ["chatsounds.SortedList"] = true, ["chatsounds.SortedList2"] = true, ["chatsounds.SortedListKeys"] = true, ["CAC.LuaWhitelistController.DynamicLuaInformation"] = true, ["CAC.LuaWhitelistController.StaticLuaInformation"] = true, ["GAuth.Groups"] = true, ["GCAD.JITInfo"] = true, ["GCAD.NavigationGraphEntityList.NavigationGraphNodeEntityList"] = true, ["GCAD.NavigationGraphEntityList.NavigationGraphEdgeEntityList"] = true, ["GCAD.NavigationGraphRenderer"] = true, ["GCAD.RootSceneGraph"] = true, ["GLib.Loader.PackFileManager.MergedPackFileSystem.Root"] = true, ["GLib.Lua.FunctionCache"] = true, ["GCompute.GlobalNamespace"] = true, ["GCompute.IDE.Instance.DocumentManager"] = true, ["GCompute.IDE.Instance.ViewManager"] = true, ["GCompute.LanguageDetector.Extensions"] = true, ["GCompute.Languages.Languages.GLua.EditorHelper.RootNamespace"] = true, ["GCompute.TypeSystem"] = true, ["pac.ActiveParts"] = true, ["pac.OwnedParts"] = true, ["pac.UniqueIDParts"] = true, ["pac.webaudio.streams"] = true, ["pace.example_outfits"] = true, ["VFS.RealRoot"] = true, ["VFS.Root"] = true } local numericTableNameBlacklist = { ["_R"] = true } function self:ProcessTable (table, tableName, dot) if tableNameBlacklist [tableName] then return end local numericBlacklisted = numericTableNameBlacklist [tableName] local state = self:GetState () local nameCache = state.NameCache local queuedTables = state.QueuedTables for k, v in pairs (table) do GLib.CheckYield () local keyType = type (k) local valueType = type (v) if not numericBlacklisted or keyType ~= "number" then local memberName = nil if valueType == "function" or valueType == "table" then if keyType ~= "string" or not GLib.Lua.IsValidVariableName (k) then if keyType == "table" then -- ¯\_(ツ)_/¯ end memberName = tableName .. " [" .. GLib.Lua.ToCompactLuaString (k) .. "]" else memberName = tableName ~= "" and (tableName .. dot .. tostring (k)) or tostring (k) end nameCache [v] = nameCache [v] or memberName end -- Recurse if valueType == "table" then if not queuedTables [v] then self:QueueIndex (v, memberName) -- Check if this is a GLib class if GLib.IsStaticTable (v) then local metatable = GLib.GetMetaTable (v) if type (metatable) == "table" then nameCache [metatable] = nameCache [metatable] or memberName self:QueueIndex (GLib.GetMetaTable (v), memberName, ":") end else -- Do the __index metatable if it exists local metatable = debug.getmetatable (v) local __index = metatable and metatable.__index or nil if __index and not queuedTables [__index] then self:QueueIndex (__index, memberName, ":") end end end end end end end function self:QueueIndex (table, tableName, dot) if type (table) ~= "table" then return end dot = dot or "." local state = self:GetState () if state.QueuedTables [table] then return end state.QueuedTables [table] = true state.QueueTables [#state.QueueTables + 1] = table state.QueueTableNames [#state.QueueTableNames + 1] = tableName state.QueueSeparators [#state.QueueSeparators + 1] = dot end function self:StartIndexingThread () if self.Thread and not self.Thread:IsTerminated () then return end GLib.Debug ("GLib.Lua.NameCache : Indexing thread started.") self.Thread = GLib.Threading.Thread () self.Thread:Start ( function () GLib.Sleep (1000) local state = self:GetState () while #state.QueueTables > 0 do GLib.CheckYield () local t = state.QueueTables [1] local tableName = state.QueueTableNames [1] local separator = state.QueueSeparators [1] table.remove (state.QueueTables, 1) table.remove (state.QueueTableNames, 1) table.remove (state.QueueSeparators, 1) self:ProcessTable (t, tableName, separator) end GLib.Debug ("GLib.Lua.NameCache : Indexing took " .. GLib.FormatDuration (SysTime () - self.Thread:GetStartTime ()) .. ".") end ) end GLib.Lua.NameCache = GLib.Lua.NameCache ()
26.730594
126
0.687222
dc1913c6f71442d6709d98f48c85928f97229b15
2,984
py
Python
src/key.py
mabels/kleisimo
1c68217d01093ec233f81c148ad916f45510d182
[ "Apache-2.0" ]
1
2022-03-14T10:15:40.000Z
2022-03-14T10:15:40.000Z
src/key.py
mabels/kleisimo
1c68217d01093ec233f81c148ad916f45510d182
[ "Apache-2.0" ]
3
2021-11-10T07:34:40.000Z
2022-03-08T23:38:27.000Z
src/key.py
mabels/kleisimo
1c68217d01093ec233f81c148ad916f45510d182
[ "Apache-2.0" ]
null
null
null
from dataclasses import dataclass import uuid import os import re import base58 from typing import Optional from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305 from cryptography.hazmat.primitives import hashes @dataclass class SymetricKeyProps: alg: str id: Optional[str] = None nonce: bytes = os.urandom(12) key: Optional[bytes] = None hashSeed: str = str(uuid.uuid4()) key_length: int = 32 nonce_length: int = 12 class SymetricKey: _id: Optional[str] _hashSeed: str _key: Optional[bytes] _nonce: bytes _key_length: int _nonce_length: int _alg = 'chacha20-poly1305' def __init__(self, props: SymetricKeyProps): self._id = props.id self._key = props.key self._hashSeed = props.hashSeed self._key_length = props.key_length self._nonce_length = props.nonce_length self._nonce = props.nonce @staticmethod def create(props: SymetricKeyProps): return SymetricKey(props).generate() # def generate_nonce(self, length: Optional[int] = None) -> bytes: # nonce_length = length if length else self._nonce_length # self._nonce = os.urandom(nonce_length) # return self._nonce def generate(self): if self._key is None: self._key = os.urandom(self._key_length) self._nonce = self._nonce if self._nonce else self.create_nonce() if self._id is None: digest = hashes.Hash(hashes.SHA256()) digest.update(self._key) digest.update(self._nonce) self._id=base58.b58encode(digest.finalize()).decode() self._chacha = ChaCha20Poly1305(self._key) return self def create_nonce(self) -> bytes: self._nonce = os.urandom(12) return self.nonce @property def key(self) -> bytes: if self._key is None: raise Exception("key is not set") return self._key @property def id(self) -> str: if self._id is None: raise Exception("key is not set") return self._id @property def nonce(self) -> bytes: if self._nonce is None: raise Exception("nonce is not set") return self._nonce def encrypt(self, nonce: bytes, message: bytes, addition: Optional[bytes] = None ) -> bytes: return self._chacha.encrypt(nonce, message, addition) def decrypt(self, nonce: bytes, encrypted: bytes, addition: Optional[bytes] = None) -> bytes: return self._chacha.decrypt(nonce, encrypted, addition) def hash(self, enc: str)-> str: hasher = hashes.Hash(hashes.SHA256()) hasher.update(bytes(self._hashSeed, 'utf-8')); stripped = re.sub(r'[\n\r\s\t]+','', enc.upper(),flags=(re.M)) hasher.update(stripped.encode()) # 'A' means sha256 upcase und replace string_hash = base58.b58encode(hasher.finalize()).decode() return "A{}".format(string_hash)
30.141414
97
0.639075
784cb2f5a7f998af0fd35892f73bcfa369018a2c
404
dart
Dart
lib/src/database/commands/units/bossk/lying_in_wait.dart
matanlurey/swlegion
0d77d7077a770f04a19c2cab2b539e4777dc1143
[ "MIT" ]
4
2019-05-13T14:35:23.000Z
2019-10-25T16:40:26.000Z
lib/src/database/commands/units/bossk/lying_in_wait.dart
matanlurey/swlegion
0d77d7077a770f04a19c2cab2b539e4777dc1143
[ "MIT" ]
26
2018-12-22T01:36:22.000Z
2019-04-03T03:16:24.000Z
lib/src/database/commands/units/bossk/lying_in_wait.dart
swlegion/swlegion
0d77d7077a770f04a19c2cab2b539e4777dc1143
[ "MIT" ]
1
2018-12-05T05:51:06.000Z
2018-12-05T05:51:06.000Z
import 'package:swlegion/catalog.dart'; import 'package:swlegion/swlegion.dart'; final lyingInWait = CommandCard( id: 'lying-in-wait', name: 'Lying In Wait', activated: Units.bossk.name, required: [Units.bossk], pips: 3, text: r''' Bossk gains SHARPSHOOTER 1. After an enemy unit activates, Bossk gains 1 aim token. ''', waves: const [ Wave.wBosskOperativeExpansion, ], );
22.444444
76
0.683168
1cb38605ea5ebe32b18e34924b9e18c592b23f24
1,686
css
CSS
Lectures/LEC12/6.824 Lab 4_ Sharded Key_Value Service_files/style.css
aQuaYi/MIT-6.824-Distributed-Systems-Spring-2018
a49acb477d4be0cadacac89691550e4c2636bc33
[ "MIT" ]
326
2018-03-19T08:37:08.000Z
2022-03-23T01:55:00.000Z
Lectures/LEC12/6.824 Lab 4_ Sharded Key_Value Service_files/style.css
yuxiaorun/MIT-6.824-Distributed-Systems
a49acb477d4be0cadacac89691550e4c2636bc33
[ "MIT" ]
1
2018-10-09T08:38:16.000Z
2018-10-09T08:38:39.000Z
Lectures/LEC12/6.824 Lab 4_ Sharded Key_Value Service_files/style.css
yuxiaorun/MIT-6.824-Distributed-Systems
a49acb477d4be0cadacac89691550e4c2636bc33
[ "MIT" ]
85
2018-09-01T07:57:14.000Z
2022-03-14T19:44:13.000Z
body { max-width: 45em; } body pre { overflow-x: auto; } body { color: black; background-color: white; font-family: sans-serif; } .title { text-align: center } .subtitle { text-align: center; font-style: italic; } .author { text-align: center; } ul.hints, .note, .challenge, .todo, pre { margin: 1em; border: 1px dashed; padding: 1em; } ul.hints { color: #50A02D; } ul.hints li { margin-left: 1em; } ul.hints li::before { content: "Hint: "; font-weight: bold; } .important { margin: 1em; padding: 1em; background-color: #990000; color: #fff; } .important::before { content: "Important: "; background-color: #550000; width: 100%; display: block; margin: -1em -1em 1em -1em; padding: 1em; font-weight: bold; } .note { color: #4682B4; } .note::before { content: "Note: "; font-weight: bold; } .challenge, .todo { border-style: solid; } .challenge::before, .todo::before { float: right; font-weight: bold; color: white; margin-right: -1em; margin-top: -1em; margin-bottom: .5em; margin-left: 1em; padding: .5em 1em; } .todo { color: #B22222; } .todo::before { content: "TASK"; background: #B22222; } .challenge { color: #8B4513; } .challenge::before { content: "CHALLENGE"; background: #8B4513; } tt, code { font-family: monospace; border-radius: 3px; font-size: 110%; color: #657b83; background-color: #fdf6e3; padding: 0.2em; word-wrap: break-word; } pre { font-size: 100%; color: #839496; background: #002b36; } .classic { color: black; } div.required .header { font-weight: bold; } div.challenge .header { font-style: italic; } div.required { background-color: #eeeeff; }
15.189189
42
0.634045
4a9b3c50d22ecd08380986e28e77c28ce36caf53
1,239
html
HTML
partials/dbtable.html
pstros/jiloin
54ace3d9bf728b4c82db5a750b9f4aed4e1a3e6e
[ "Apache-2.0" ]
3
2017-07-10T02:43:40.000Z
2020-08-30T01:34:05.000Z
partials/dbtable.html
pstros/jiloin
54ace3d9bf728b4c82db5a750b9f4aed4e1a3e6e
[ "Apache-2.0" ]
9
2015-03-09T18:03:11.000Z
2015-04-01T10:40:16.000Z
partials/dbtable.html
pstros/jiloin
54ace3d9bf728b4c82db5a750b9f4aed4e1a3e6e
[ "Apache-2.0" ]
11
2015-07-03T06:13:00.000Z
2021-07-27T05:28:31.000Z
<div class="table"> <div class="tableName">{{data.name|tableName}}</div> <div class="db-table"> <table> <tr> <td class="columnName">time</td> <td ng-repeat="column in columnsOrder" class="columnName">{{data.columns[column]}}</td> </tr> <tr dir-paginate="row in data.points | itemsPerPage: 10" pagination-id="data.name" ng-class-even="'lightRow'" ng-class-odd="'darkRow'" ng-click="goTo($index)"> <td> <span> {{row[0]|time}} </span> </td> <td ng-repeat="column in columnsOrder" ng-class="[data.columns[column], 'cell']"> <span> {{data.columns[column] !== 'time' ? row[column] : formatTime(row[column])}} </span> </td> </tr> </table> <dir-pagination-controls template-url="/lib/dirPagination.tpl.html" pagination-id="data.name" max-size="7"> </dir-pagination-controls> </div> </div>
36.441176
99
0.426957
021581b05f553521bf4036a3617640df37341f0e
222
asm
Assembly
libsrc/target/radio86/stdio/fgetc_cons.asm
ahjelm/z88dk
c4de367f39a76b41f6390ceeab77737e148178fa
[ "ClArtistic" ]
640
2017-01-14T23:33:45.000Z
2022-03-30T11:28:42.000Z
libsrc/target/radio86/stdio/fgetc_cons.asm
C-Chads/z88dk
a4141a8e51205c6414b4ae3263b633c4265778e6
[ "ClArtistic" ]
1,600
2017-01-15T16:12:02.000Z
2022-03-31T12:11:12.000Z
libsrc/target/radio86/stdio/fgetc_cons.asm
C-Chads/z88dk
a4141a8e51205c6414b4ae3263b633c4265778e6
[ "ClArtistic" ]
215
2017-01-17T10:43:03.000Z
2022-03-23T17:25:02.000Z
SECTION code_clib PUBLIC fgetc_cons PUBLIC _fgetc_cons EXTERN getk INCLUDE "target/radio86/def/monitor.def" fgetc_cons: _fgetc_cons: call WAITKEY ld l,a ld h,0 ret
13.058824
44
0.608108
fe966870eabb7a014b6c0de075b93a837abd2d27
5,946
asm
Assembly
Transynther/x86/_processed/NONE/_xt_sm_/i7-8650U_0xd2_notsx.log_311_218.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
9
2020-08-13T19:41:58.000Z
2022-03-30T12:22:51.000Z
Transynther/x86/_processed/NONE/_xt_sm_/i7-8650U_0xd2_notsx.log_311_218.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
1
2021-04-29T06:29:35.000Z
2021-05-13T21:02:30.000Z
Transynther/x86/_processed/NONE/_xt_sm_/i7-8650U_0xd2_notsx.log_311_218.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
3
2020-07-14T17:07:07.000Z
2022-03-21T01:12:22.000Z
.global s_prepare_buffers s_prepare_buffers: push %r12 push %r14 push %r15 push %r8 push %r9 push %rbx push %rcx push %rdi push %rsi lea addresses_A_ht+0x1dda9, %r8 clflush (%r8) nop nop xor %rsi, %rsi mov $0x6162636465666768, %r12 movq %r12, %xmm7 vmovups %ymm7, (%r8) nop add $42101, %r14 lea addresses_WC_ht+0x18a7e, %r15 nop and $37870, %r14 movl $0x61626364, (%r15) nop nop nop xor %r8, %r8 lea addresses_UC_ht+0x19f10, %r14 nop and %rbx, %rbx movw $0x6162, (%r14) nop nop nop xor $41958, %r8 lea addresses_D_ht+0x13636, %rsi lea addresses_WT_ht+0x1b490, %rdi nop nop cmp %r14, %r14 mov $11, %rcx rep movsb nop nop mfence lea addresses_WC_ht+0x1b276, %r14 nop nop and %r8, %r8 mov $0x6162636465666768, %r9 movq %r9, %xmm2 vmovups %ymm2, (%r14) dec %rdi lea addresses_WC_ht+0x7650, %rsi lea addresses_D_ht+0x2350, %rdi nop nop add $13747, %r8 mov $12, %rcx rep movsw nop nop nop nop add $15037, %rbx lea addresses_D_ht+0x12150, %rdi nop nop nop nop xor %r14, %r14 mov (%rdi), %r12d nop nop nop nop xor $35716, %r14 lea addresses_D_ht+0x19a90, %r15 nop nop xor %r8, %r8 movups (%r15), %xmm2 vpextrq $1, %xmm2, %r14 nop nop nop sub $19950, %r15 lea addresses_D_ht+0x4548, %rbx nop nop nop nop nop xor $49218, %r14 mov (%rbx), %ecx nop nop nop nop nop xor %r9, %r9 lea addresses_WT_ht+0x2190, %r12 nop nop nop dec %r15 mov (%r12), %r14w nop nop nop dec %rsi lea addresses_WT_ht+0xc190, %rsi nop nop nop dec %r8 mov $0x6162636465666768, %rcx movq %rcx, %xmm3 and $0xffffffffffffffc0, %rsi movntdq %xmm3, (%rsi) cmp %r9, %r9 lea addresses_WT_ht+0x7058, %r15 nop nop nop nop nop xor %rcx, %rcx mov (%r15), %r8d nop nop nop nop nop and $34763, %rbx lea addresses_WT_ht+0xab50, %r9 add %rdi, %rdi mov $0x6162636465666768, %rbx movq %rbx, (%r9) nop nop nop and %r8, %r8 lea addresses_WC_ht+0x15890, %rsi lea addresses_D_ht+0x540, %rdi nop nop nop nop nop sub %r12, %r12 mov $87, %rcx rep movsb nop nop nop and %r9, %r9 pop %rsi pop %rdi pop %rcx pop %rbx pop %r9 pop %r8 pop %r15 pop %r14 pop %r12 ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r8 push %rcx push %rdi push %rdx push %rsi // REPMOV lea addresses_A+0x1d990, %rsi lea addresses_WT+0x1190, %rdi clflush (%rdi) nop nop nop nop nop cmp $7914, %r10 mov $23, %rcx rep movsb nop nop nop nop nop and $38515, %rcx // Store lea addresses_A+0x1d990, %rcx cmp $32049, %r11 movb $0x51, (%rcx) nop nop nop and $50645, %rcx // Faulty Load lea addresses_A+0x1d990, %rcx nop nop dec %r10 movb (%rcx), %dl lea oracles, %rdi and $0xff, %rdx shlq $12, %rdx mov (%rdi,%rdx,1), %rdx pop %rsi pop %rdx pop %rdi pop %rcx pop %r8 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_A', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_A', 'congruent': 0, 'same': True}, 'dst': {'type': 'addresses_WT', 'congruent': 11, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_A', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_A', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 1, 'same': True}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 7, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 1, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 8, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 1, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 3, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 6, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 6, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 6, 'same': True}} {'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 3, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 10, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'size': 16, 'AVXalign': False, 'NT': True, 'congruent': 11, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'size': 4, 'AVXalign': True, 'NT': False, 'congruent': 3, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 3, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 8, 'same': True}, 'dst': {'type': 'addresses_D_ht', 'congruent': 3, 'same': False}} {'51': 311} 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 */
23.409449
932
0.650353
136accc25b716a563f368eaaa6d435f064e53f4f
2,622
h
C
src/systemc/tests/systemc/misc/synth/bubble/tb.h
hyu-iot/gem5
aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5
[ "BSD-3-Clause" ]
765
2015-01-14T16:17:04.000Z
2022-03-28T07:46:28.000Z
src/systemc/tests/systemc/misc/synth/bubble/tb.h
hyu-iot/gem5
aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5
[ "BSD-3-Clause" ]
148
2018-07-20T00:58:36.000Z
2021-11-16T01:52:33.000Z
src/systemc/tests/systemc/misc/synth/bubble/tb.h
hyu-iot/gem5
aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5
[ "BSD-3-Clause" ]
807
2015-01-06T09:55:38.000Z
2022-03-30T10:23:36.000Z
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera 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. *****************************************************************************/ /***************************************************************************** tb.h -- Original Author: Martin Janssen, Synopsys, Inc., 2002-02-15 *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ /******************************************************************************/ /*************************** testbench Class Definition ********************/ /******************************************************************************/ #include "common.h" SC_MODULE( TESTBENCH ) { sc_signal<bool> reset; sc_signal<bool> in_ok; sc_signal<bool> out_ok; sc_signal<bool> instrb; sc_signal<bool> outstrb; signal_bool_vector a1,a2,a3,a4,a5,a6,a7,a8; // -128 to 127 signal_bool_vector d1,d2,d3,d4,d5,d6,d7,d8; // -128 to 127 STIM st1; BUBBLE bubble; DISPLAY disp1; TESTBENCH( sc_module_name NAME, sc_clock& TICK ) : st1 ("ST1", TICK, reset, in_ok, out_ok, instrb, outstrb, a1, a2, a3, a4, a5, a6, a7, a8, d1, d2, d3, d4, d5, d6, d7, d8) , bubble ("B1", TICK, reset, in_ok, out_ok, instrb, outstrb, a1, a2, a3, a4, a5, a6, a7, a8, d1, d2, d3, d4, d5, d6, d7, d8) , disp1 ("D1", reset, in_ok, out_ok, instrb, outstrb, a1, a2, a3, a4, a5, a6, a7, a8, d1, d2, d3, d4, d5, d6, d7, d8) {} };
35.917808
80
0.497712
c44f913d252188bac2e75303d16fad794f2b6c47
2,068
c
C
local/toolchest/ksh/shlib/unassign.c
weiss/original-bsd
b44636d7febc9dcf553118bd320571864188351d
[ "Unlicense" ]
114
2015-01-18T22:55:52.000Z
2022-02-17T10:45:02.000Z
local/toolchest/ksh/shlib/unassign.c
JamesLinus/original-bsd
b44636d7febc9dcf553118bd320571864188351d
[ "Unlicense" ]
null
null
null
local/toolchest/ksh/shlib/unassign.c
JamesLinus/original-bsd
b44636d7febc9dcf553118bd320571864188351d
[ "Unlicense" ]
29
2015-11-03T22:05:22.000Z
2022-02-08T15:36:37.000Z
/* * Copyright (c) 1984, 1985, 1986 AT&T * All Rights Reserved * THIS IS UNPUBLISHED PROPRIETARY SOURCE * CODE OF AT&T. * The copyright notice above does not * evidence any actual or intended * publication of such source code. */ /* @(#)unassign.c 1.1 */ /* * UNASSIGN.C * * Programmer: D. G. Korn * * Owner: D. A. Lambeth * * Date: April 17, 1980 * * * * UNASSIGN (NODE) * * Nullify the value and the attributes of the Namnod * given by NODE. * * * * See Also: assign(III), assnum(III), assiadr(III), asscadr(III), * valup(III) */ #include "name.h" #include "flags.h" /* * UNASSIGN (NODE) * * struct Namnod *NODE; * * Set the value of NODE to NULL, and nullify any attributes * that NODE may have had. Free any freeable space occupied * by the value of NODE. If NODE denotes an array member, it * will retain its attributes. Any node that has the * indirect (IN_DIR) attribute will retain that attribute. */ extern void free(); void unassign(node) struct Namnod *node; { register struct Namnod *np=node; register union Namval *up = &np->value.namval; #ifdef NAME_SCOPE if (attest (np, C_WRITE)) { np->value.namflg |= N_AVAIL; return; } #endif if (attest (np, ARRAY)) { register struct Namaray *ap = up->aray; if(ap->adot != NO_SUBSCRIPT) { struct Nodval *nv = unmark(ap->val[ap->adot]); if(ap->adot == ap->maxi) ap->maxi--; if(nv==NULL || (up = &nv->namval)==NULL) return; } else { for(ap->adot=0;ap->adot <= ap->maxi;ap->adot++) unassign(np); free((char*)ap); up->cp = NULL; np->value.namflg = 0; return; } } if (attest (np, IN_DIR)) up = up->up; if (attest (np, INT_GER)) { if ((attest (np, L_FLAG)) && (up->lp != NULL)) free((char *)up->lp); } else if ((!attest (np, N_FREE)) && (!isnull (np))) free(up->cp); up->cp = NULL; if (!attest (np, ARRAY)) { np->value.namflg &= IN_DIR; np->namsz = 0; } }
19.884615
69
0.5706
b01644eba92f40afadff708afac25d0504f2b236
1,182
asm
Assembly
wallpaper-one/emulator/Assembler/Speed.asm
paulscottrobson/assorted-archives
87ce21ef1556bed441fffbb5c4c3c11c06324385
[ "MIT" ]
null
null
null
wallpaper-one/emulator/Assembler/Speed.asm
paulscottrobson/assorted-archives
87ce21ef1556bed441fffbb5c4c3c11c06324385
[ "MIT" ]
null
null
null
wallpaper-one/emulator/Assembler/Speed.asm
paulscottrobson/assorted-archives
87ce21ef1556bed441fffbb5c4c3c11c06324385
[ "MIT" ]
1
2020-01-02T13:54:19.000Z
2020-01-02T13:54:19.000Z
; ****************************************************************************************************************** ; ; Speed Test ; ; ****************************************************************************************************************** cpu sc/mp org 0x0000 nop ldi 0x8 xpah p2 ldi 0x00 xpal p2 ldi 0x00 st 0(p2) st 1(p2) st 2(p2) jmp loop2 loop1: ild 0(p2) jnz loop1 ild 1(p2) jnz loop1 ild 2(p2) st 0 jmp loop1 ; ; Without DLY 255 (loop1) ; ; The classic inner loop: ; ild 0(p2) 22 cycles ; jnz loop 11 cycles (successful) ; Total 33 cycles ; ; Two inner loops are executed 65536 times ; ; 65536 * 33 = 2,162,688 ; ; Running at 2Mhz, each tick should take 2.16 seconds. ; ; Counting to 16 took 33.6 s ; 16 * 2.16 = 34.56s , near enough allowing for measuring errors. ; loop2: dly 255 ld 0(p2) ccl adi 32 st 0(p2) jnz loop2 ild 1(p2) st 0 jmp loop2 ; ; With DLY 255 (loop2) ; ; The DLY 255, executed 8 times should take approximately ; ; 255 * 514 * 8 cycles = 1,048,560 cycles ; ; 1:06 mins to count to 64 i.e. near enough ;
17.382353
116
0.463621
9c419d3e75ea767ab4ca1b6fdfe4958c40f73c50
46
js
JavaScript
kissfat/js/mpsdk/mpsdk.global.js
davidgjy/html5-game
31eafc4c6c5ce1cfd54c622ea68d7b6dbdab3651
[ "Apache-2.0" ]
null
null
null
kissfat/js/mpsdk/mpsdk.global.js
davidgjy/html5-game
31eafc4c6c5ce1cfd54c622ea68d7b6dbdab3651
[ "Apache-2.0" ]
null
null
null
kissfat/js/mpsdk/mpsdk.global.js
davidgjy/html5-game
31eafc4c6c5ce1cfd54c622ea68d7b6dbdab3651
[ "Apache-2.0" ]
null
null
null
// main space var MpSdk = MpSdk || {};
9.2
25
0.478261
7b976a5472b7cf0049f5176fcb80a5a4c9d1526f
1,697
css
CSS
assets/css/style-submited.css
TheMarcellVargaUCN/ProjectStudy
c936f171a71541de64685b926c402c7a34e33cd2
[ "MIT" ]
null
null
null
assets/css/style-submited.css
TheMarcellVargaUCN/ProjectStudy
c936f171a71541de64685b926c402c7a34e33cd2
[ "MIT" ]
null
null
null
assets/css/style-submited.css
TheMarcellVargaUCN/ProjectStudy
c936f171a71541de64685b926c402c7a34e33cd2
[ "MIT" ]
null
null
null
html { margin: 0; font-family: "lato"; line-height: 1.2; } body { width: 100%; margin: 0; padding: 0; background-color: #EBF3FA; /* height: 100%; */ overflow: hidden } /* .......................... Contact us btn .......................... */ .buttonStyle1 { font-size: 1.5vw; background-color: #F1A34F; color: #ffffff; border: none; padding: 7px; cursor: pointer; border-radius: 7px; box-shadow: 0 5px rgba(48, 48, 48, 0.23); outline: none; margin-top: 1%; } /* .......................... Contact us page intro .......................... */ .grid-submit-intro{ width: 100%; height: auto; text-align: center; } .submit-intro{ margin-top: 5vw; font-size: 1.5vw; } .submit-intro h3{ color: #203F7E; } .submit-intro-img{ margin-top: 5%; } .submit-intro-img img{ width: 30vw; margin-left: auto; margin-right: auto; } /* .......................... For tablet .......................... */ @media only screen and (max-width: 768px) { .grid-submit-intro{ margin-top: 15%; } .submit-intro{ font-size: 2vw; } .submit-intro-img img{ margin-top: 5%; width: 40vw; } .buttonStyle1 { font-size: 2vw; } } /* .......................... For phone .......................... */ @media only screen and (max-width: 600px) { .grid-submit-intro{ margin-top: 25%; } .submit-intro{ font-size: 3vw; } .submit-intro-img img{ margin-top:15%; width: 55vw; } .buttonStyle1 { font-size: 3vw; } }
16.009434
84
0.453153
05d697bd4ecc36e06b72881539b0859547dbf787
541
html
HTML
apps/shell/src/app/app.component.html
martinhlavacek/nx-mfe-poc
4eb849367de7c72b80f3d47a4d61a5357ed6e6df
[ "MIT" ]
null
null
null
apps/shell/src/app/app.component.html
martinhlavacek/nx-mfe-poc
4eb849367de7c72b80f3d47a4d61a5357ed6e6df
[ "MIT" ]
null
null
null
apps/shell/src/app/app.component.html
martinhlavacek/nx-mfe-poc
4eb849367de7c72b80f3d47a4d61a5357ed6e6df
[ "MIT" ]
null
null
null
<div class="topnav"> <a routerLinkActive="active" routerLink="/home">Home</a> <a routerLinkActive="active" routerLink="/gallery">Gallery</a> <a routerLinkActive="active" routerLink="/groceries">Groceries</a> <a routerLinkActive="active" routerLink="/takeaways">Takeaways</a> <a routerLinkActive="active" routerLink="/profile">Profile</a> <div class="topnav-right"> <a routerLinkActive="active" routerLink="/login">{{ (isLoggedIn$ | async)?.length ? 'Logout': 'Login' }}</a> </div> </div> <router-outlet></router-outlet>
38.642857
113
0.695009
8b04ebe1419e953d3ca641a9f22e8f7da3fb143b
988
asm
Assembly
programs/oeis/287/A287190.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
22
2018-02-06T19:19:31.000Z
2022-01-17T21:53:31.000Z
programs/oeis/287/A287190.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
41
2021-02-22T19:00:34.000Z
2021-08-28T10:47:47.000Z
programs/oeis/287/A287190.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
5
2021-02-24T21:14:16.000Z
2021-08-09T19:48:05.000Z
; A287190: Binary representation of the diagonal from the corner to the origin of the n-th stage of growth of the two-dimensional cellular automaton defined by "Rule 253", based on the 5-celled von Neumann neighborhood. ; 1,10,0,1110,11,111110,11,11111110,11,1111111110,11,111111111110,11,11111111111110,11,1111111111111110,11,111111111111111110,11,11111111111111111110,11,1111111111111111111110,11,111111111111111111111110,11,11111111111111111111111110,11,1111111111111111111111111110,11,111111111111111111111111111110,11,11111111111111111111111111111110,11,1111111111111111111111111111111110,11,111111111111111111111111111111111110,11 seq $0,287192 ; Decimal representation of the diagonal from the corner to the origin of the n-th stage of growth of the two-dimensional cellular automaton defined by "Rule 253", based on the 5-celled von Neumann neighborhood. seq $0,7088 ; The binary numbers (or binary words, or binary vectors, or binary expansion of n): numbers written in base 2.
164.666667
416
0.837045
176bcda8f825adff4401e6ea61e103dac6d13b7c
2,575
html
HTML
ref/1.3.5/xref/org/apache/maven/archiva/repository/content/package-frame.html
apache/archiva-web-content
af8af14010c88998efecf15983df35d28ddf298f
[ "Apache-2.0" ]
2
2019-05-21T10:55:28.000Z
2021-11-08T14:37:05.000Z
ref/1.3.5/xref/org/apache/maven/archiva/repository/content/package-frame.html
apache/archiva-web-content
af8af14010c88998efecf15983df35d28ddf298f
[ "Apache-2.0" ]
null
null
null
ref/1.3.5/xref/org/apache/maven/archiva/repository/content/package-frame.html
apache/archiva-web-content
af8af14010c88998efecf15983df35d28ddf298f
[ "Apache-2.0" ]
2
2019-05-21T10:55:18.000Z
2021-11-08T14:36:53.000Z
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <title>Archiva :: Modules 1.3.5 Reference Package org.apache.maven.archiva.repository.content</title> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="style" /> </head> <body> <h3> <a href="package-summary.html" target="classFrame">org.apache.maven.archiva.repository.content</a> </h3> <h3>Classes</h3> <ul> <li> <a href="AbstractDefaultRepositoryContent.html" target="classFrame">AbstractDefaultRepositoryContent</a> </li> <li> <a href="AbstractLegacyRepositoryContent.html" target="classFrame">AbstractLegacyRepositoryContent</a> </li> <li> <a href="ArtifactClassifierMapping.html" target="classFrame">ArtifactClassifierMapping</a> </li> <li> <a href="ArtifactExtensionMapping.html" target="classFrame">ArtifactExtensionMapping</a> </li> <li> <a href="DefaultPathParser.html" target="classFrame">DefaultPathParser</a> </li> <li> <a href="FilenameParser.html" target="classFrame">FilenameParser</a> </li> <li> <a href="LegacyPathParser.html" target="classFrame">LegacyPathParser</a> </li> <li> <a href="ManagedDefaultRepositoryContent.html" target="classFrame">ManagedDefaultRepositoryContent</a> </li> <li> <a href="ManagedLegacyRepositoryContent.html" target="classFrame">ManagedLegacyRepositoryContent</a> </li> <li> <a href="PathParser.html" target="classFrame">PathParser</a> </li> <li> <a href="RemoteDefaultRepositoryContent.html" target="classFrame">RemoteDefaultRepositoryContent</a> </li> <li> <a href="RemoteLegacyRepositoryContent.html" target="classFrame">RemoteLegacyRepositoryContent</a> </li> <li> <a href="RepositoryRequest.html" target="classFrame">RepositoryRequest</a> </li> </ul> </body> </html>
42.916667
118
0.540583
bd496c57ee7bce27a8fb1f7ea90c1c18b0a37044
1,167
rs
Rust
src/bin/kth-smallest-element-in-a-bst.rs
rustors/leetcode
4965fe47504ab56e9c84d4328b3c5a96edd89e3d
[ "MIT" ]
2
2020-12-25T03:19:27.000Z
2021-01-08T03:38:50.000Z
src/bin/kth-smallest-element-in-a-bst.rs
rustors/leetcode
4965fe47504ab56e9c84d4328b3c5a96edd89e3d
[ "MIT" ]
1
2021-07-25T15:45:07.000Z
2021-07-26T14:59:55.000Z
src/bin/kth-smallest-element-in-a-bst.rs
rustors/leetcode
4965fe47504ab56e9c84d4328b3c5a96edd89e3d
[ "MIT" ]
2
2021-09-14T14:14:32.000Z
2022-02-21T03:12:15.000Z
fn main() {} struct Solution; // Definition for a binary tree node. #[derive(Debug, PartialEq, Eq)] pub struct TreeNode { pub val: i32, pub left: Option<Rc<RefCell<TreeNode>>>, pub right: Option<Rc<RefCell<TreeNode>>>, } impl TreeNode { #[inline] pub fn new(val: i32) -> Self { TreeNode { val, left: None, right: None, } } } use std::cell::RefCell; use std::rc::Rc; impl Solution { pub fn kth_smallest(root: Option<Rc<RefCell<TreeNode>>>, k: i32) -> i32 { let mut k = k; Self::bst(root, &mut k).unwrap() } fn bst(root: Option<Rc<RefCell<TreeNode>>>, k: &mut i32) -> Option<i32> { if root.is_none() { return None; } let r1 = Self::bst(root.as_ref().unwrap().borrow_mut().left.take(), k); if r1.is_some() { return r1; } *k -= 1; if *k == 0 { return Some(root.as_ref().unwrap().borrow().val); } let r2 = Self::bst(root.as_ref().unwrap().borrow_mut().right.take(), k); if r2.is_some() { return r2; } None } }
20.839286
80
0.504713
f05b6ae51231082bc7b62c387d1abcdc6dd6c0d3
3,511
js
JavaScript
front/src/App.js
juancastillo0/wheelsUniandes
bce8de912fd187274a3cf6ac8050a6421ba85411
[ "MIT" ]
null
null
null
front/src/App.js
juancastillo0/wheelsUniandes
bce8de912fd187274a3cf6ac8050a6421ba85411
[ "MIT" ]
null
null
null
front/src/App.js
juancastillo0/wheelsUniandes
bce8de912fd187274a3cf6ac8050a6421ba85411
[ "MIT" ]
null
null
null
import React, { useState } from "react"; import './App.css'; import NavBar from './components/NavBar/NavBar'; import Home from './Home' import Login from './components/Login/Login'; import 'bootstrap/dist/css/bootstrap.css'; import Register from './components/Register/Register'; import { BrowserRouter as Router, Route } from 'react-router-dom' import PpalLog from "./components/PpalLog/PpalLog"; import CrearRuta from "./components/crearRuta/CrearRuta"; import { instanceOf } from 'prop-types'; import { withCookies, Cookies } from 'react-cookie'; import MisCarros from "./components/MisCarros/MisCarros"; import RutasDisponibles from "./components/RutasDisponibles/RutasDisponibles"; // 0: Home // 1: InicioSesion // 2: Register // 3: PpalLog function App(props) { const [wsConnection, setConnection] = useState(null); const [carros, setCarros] = useState([]); const [servicios, setServicios] = useState([]); const backUrl = "http://localhost:5000"; const wsUrl = "ws://localhost:5000/"; const funcionCookie = (cookie, user) => { props.cookies.set('wheelsToken', cookie, { path: '/' }); props.cookies.set('wheelsUser', { "uid": user }); } const signout = (e) => { e.preventDefault(); props.cookies.set('wheelsUser', ''); props.cookies.set('wheelsToken', ''); } const consultarCarros = (user, token) => { (async () => { const req = await fetch(`${backUrl}/cars/${user.uid}`, { method: 'GET', headers: { 'Authorization': `Bearer ${token}`, 'user': JSON.stringify(user), 'Content-Type': 'application/json' } }); const rta = await req.json(); console.log(rta); setCarros(rta); })(); }; const wsConn = () => { const temp = JSON.parse(props.cookies.cookies.wheelsUser); const connection = new WebSocket(wsUrl); connection.onopen = () => { connection.send(temp.uid); } connection.onmessage = (msg)=>{ if (msg.data.includes("cars#")) { const data = msg.data.split("#")[1]; const jsonData = JSON.parse(data); setCarros(jsonData); } else if(msg.data.includes("services#")) { const data = msg.data.split("#")[1]; const jsonData = JSON.parse(data); console.log(jsonData); setServicios(jsonData); } else{ //TODO } }; connection.onclose = () => { console.log("se fue papá"); }; setConnection(connection); const userId = JSON.parse(props.cookies.cookies.wheelsUser); const token =props.cookies.cookies.wheelsToken; consultarCarros(userId, token); } return ( <Router> <Route path="/" render={() => <NavBar {...props} signout={signout} wsConnection={wsConnection} />} /> <Route path="/" component={Home} exact /> <Route path="/register" render={() => <Register {...props} funcionCookie={funcionCookie} signout={signout} wsConn ={wsConn} />} /> <Route path="/login" render={() => <Login {...props} funcionCookie={funcionCookie} signout={signout} wsConn ={wsConn} />} /> <Route path='/ppalLog' render={() => <PpalLog {...props} />}/> <Route path='/crearRuta' render={() => <CrearRuta {...props} carros={carros} />} /> <Route path='/misCarros' render={() => <MisCarros {...props} carros={carros} />} /> <Route path='/rutasDisponibles' render={() => <RutasDisponibles {...props} carros={carros} />} /> </Router> ); } export default withCookies(App);
31.630631
137
0.612931
133c62117846d0c266f85462493a570e4d1e3814
1,006
h
C
cmake_targets/lte_build_oai/build/CMakeFiles/Rel14/SI-OrPSI-GERAN.h
davidraditya/OAI-Powder
a082c3e8af06cd7583c003a69ec517eb73d175b3
[ "Apache-2.0" ]
1
2019-02-22T21:33:57.000Z
2019-02-22T21:33:57.000Z
cmake_targets/lte_build_oai/build/CMakeFiles/Rel14/SI-OrPSI-GERAN.h
aygunbaltaci/OAI_BS_Master
375be88d50787cf1b7af516e1237df9005c32e0d
[ "Apache-2.0" ]
1
2021-05-28T09:06:21.000Z
2021-05-28T14:49:39.000Z
cmake_targets/lte_build_oai/build/CMakeFiles/Rel14/SI-OrPSI-GERAN.h
aygunbaltaci/OAI_BS_Master
375be88d50787cf1b7af516e1237df9005c32e0d
[ "Apache-2.0" ]
1
2018-03-04T11:09:57.000Z
2018-03-04T11:09:57.000Z
/* * Generated by asn1c-0.9.24 (http://lionet.info/asn1c) * From ASN.1 module "EUTRA-RRC-Definitions" * found in "fixed_grammar.asn" * `asn1c -gen-PER` */ #ifndef _SI_OrPSI_GERAN_H_ #define _SI_OrPSI_GERAN_H_ #include <asn_application.h> /* Including external dependencies */ #include "SystemInfoListGERAN.h" #include <constr_CHOICE.h> #ifdef __cplusplus extern "C" { #endif /* Dependencies */ typedef enum SI_OrPSI_GERAN_PR { SI_OrPSI_GERAN_PR_NOTHING, /* No components present */ SI_OrPSI_GERAN_PR_si, SI_OrPSI_GERAN_PR_psi } SI_OrPSI_GERAN_PR; /* SI-OrPSI-GERAN */ typedef struct SI_OrPSI_GERAN { SI_OrPSI_GERAN_PR present; union SI_OrPSI_GERAN_u { SystemInfoListGERAN_t si; SystemInfoListGERAN_t psi; } choice; /* Context for parsing across buffer boundaries */ asn_struct_ctx_t _asn_ctx; } SI_OrPSI_GERAN_t; /* Implementation */ extern asn_TYPE_descriptor_t asn_DEF_SI_OrPSI_GERAN; #ifdef __cplusplus } #endif #endif /* _SI_OrPSI_GERAN_H_ */ #include <asn_internal.h>
20.12
55
0.762425
b7229279fe201c0d803259f8fefb42263170fb9a
1,030
kt
Kotlin
app/src/main/java/com/crskdev/biblereaderplus/presentation/favorite/parcelmappings.kt
criske/BibleReaderPlus
a53284d8721746c2335b85919fb020ebbbe15758
[ "MIT" ]
null
null
null
app/src/main/java/com/crskdev/biblereaderplus/presentation/favorite/parcelmappings.kt
criske/BibleReaderPlus
a53284d8721746c2335b85919fb020ebbbe15758
[ "MIT" ]
null
null
null
app/src/main/java/com/crskdev/biblereaderplus/presentation/favorite/parcelmappings.kt
criske/BibleReaderPlus
a53284d8721746c2335b85919fb020ebbbe15758
[ "MIT" ]
null
null
null
/* * License: MIT * Copyright (c) Pela Cristian 2018. */ package com.crskdev.biblereaderplus.presentation.favorite import android.os.Parcelable import com.crskdev.biblereaderplus.domain.entity.FavoriteFilter import com.crskdev.biblereaderplus.domain.entity.Tag import kotlinx.android.parcel.Parcelize /** * Created by Cristian Pela on 27.11.2018. */ @Parcelize class ParcelableFavoriteFilter(val query: String? = null, val tags: List<ParcelableTag> = emptyList(), val asc: Boolean = false) : Parcelable @Parcelize class ParcelableTag(val id: String, val name: String, val color: String) : Parcelable @Suppress("IMPLICIT_CAST_TO_ANY") fun FavoriteFilter.parcelize(): ParcelableFavoriteFilter = ParcelableFavoriteFilter(query, tags.map { ParcelableTag(it.id, it.name, it.color) }, asc) fun ParcelableFavoriteFilter.deparcelize(): FavoriteFilter = FavoriteFilter(query, tags.map { Tag(it.id, it.name, it.color) }.toSet(), asc)
30.294118
85
0.705825
bc3c37f362ea06162d0464de9098c2e7907f4faf
548
asm
Assembly
programs/oeis/243/A243138.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
22
2018-02-06T19:19:31.000Z
2022-01-17T21:53:31.000Z
programs/oeis/243/A243138.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
41
2021-02-22T19:00:34.000Z
2021-08-28T10:47:47.000Z
programs/oeis/243/A243138.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
5
2021-02-24T21:14:16.000Z
2021-08-09T19:48:05.000Z
; A243138: n^2 + 15*n + 13. ; 13,29,47,67,89,113,139,167,197,229,263,299,337,377,419,463,509,557,607,659,713,769,827,887,949,1013,1079,1147,1217,1289,1363,1439,1517,1597,1679,1763,1849,1937,2027,2119,2213,2309,2407,2507,2609,2713,2819,2927,3037,3149,3263,3379,3497,3617,3739,3863,3989,4117,4247,4379,4513,4649,4787,4927,5069,5213,5359,5507,5657,5809,5963,6119,6277,6437,6599,6763,6929,7097,7267,7439,7613,7789,7967,8147,8329,8513,8699,8887,9077,9269,9463,9659,9857,10057,10259,10463,10669,10877,11087,11299 mov $1,$0 add $1,15 mul $0,$1 add $0,13
68.5
478
0.75365
53cd9a7139ac5e43f9a9ef2beeac78e98ba75e73
1,290
java
Java
reformcloud-global/reformcloud-client/src/main/java/systems/reformcloud/network/packets/in/PacketInDeleteTemplate.java
robertschuck/reformcloud
a7563fa72b14041421dc6bacc9137d1fa0ad897c
[ "Apache-2.0" ]
8
2019-04-02T12:28:12.000Z
2019-09-26T10:51:31.000Z
reformcloud-global/reformcloud-client/src/main/java/systems/reformcloud/network/packets/in/PacketInDeleteTemplate.java
robertschuck/reformcloud
a7563fa72b14041421dc6bacc9137d1fa0ad897c
[ "Apache-2.0" ]
50
2019-04-02T09:55:40.000Z
2019-11-05T08:30:08.000Z
reformcloud-global/reformcloud-client/src/main/java/systems/reformcloud/network/packets/in/PacketInDeleteTemplate.java
robertschuck/reformcloud
a7563fa72b14041421dc6bacc9137d1fa0ad897c
[ "Apache-2.0" ]
23
2019-04-30T15:12:52.000Z
2019-08-31T12:07:28.000Z
/* Copyright © 2019 Pasqual K. | All rights reserved */ package systems.reformcloud.network.packets.in; import systems.reformcloud.configurations.Configuration; import systems.reformcloud.network.interfaces.NetworkInboundHandler; import systems.reformcloud.utility.files.FileUtils; import java.io.File; import java.io.Serializable; /** * @author _Klaro | Pasqual K. / created on 03.05.2019 */ public final class PacketInDeleteTemplate implements Serializable, NetworkInboundHandler { @Override public void handle(Configuration configuration) { switch (configuration.getStringValue("type").toLowerCase()) { case "proxy": { File file = new File("reformcloud/templates/proxies/" + configuration.getStringValue("group") + "/" + configuration.getStringValue("template")); FileUtils.deleteFullDirectory(file); break; } case "server": { File file = new File("reformcloud/templates/servers/" + configuration.getStringValue("group") + "/" + configuration.getStringValue("template")); FileUtils.deleteFullDirectory(file); break; } } } }
32.25
90
0.623256
6cd8a1bfd127f547dffa2071cdc360c1fd3cd697
625
dart
Dart
lib/pages/material/material_page.dart
clin003/HLTYApp
0bc3230a4b381308f42dc38cd8a2aafa3c245b00
[ "MulanPSL-1.0" ]
3
2020-12-08T01:12:26.000Z
2021-04-08T07:56:52.000Z
lib/pages/material/material_page.dart
clin003/HLTYApp
0bc3230a4b381308f42dc38cd8a2aafa3c245b00
[ "MulanPSL-1.0" ]
null
null
null
lib/pages/material/material_page.dart
clin003/HLTYApp
0bc3230a4b381308f42dc38cd8a2aafa3c245b00
[ "MulanPSL-1.0" ]
1
2021-04-13T16:57:48.000Z
2021-04-13T16:57:48.000Z
import 'package:app/pages/goods_list/goods_list_with_material_id_v2.dart'; import 'package:app/utils/app_size.dart'; import 'package:flutter/material.dart'; class MaterialIDPage extends StatelessWidget { final String id; final String title; final int totalResults; MaterialIDPage({this.id="27161",this.title='猫超第二件0元',this.totalResults=200}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('$title',style: TextStyle(fontSize: AppSize.sp(33.0)),), ), body: MaterialIdGoodsList(id: id,title: title,totalResults:totalResults), ); } }
31.25
79
0.7248
a32455ed69b57f9157c8a8ab04ccdf0c823ab16e
5,175
lua
Lua
factai_0.1.0/commands.lua
tanner-bruce/factai
18e29994ba321a1ef7d1807715fd778299376aa4
[ "Apache-2.0" ]
null
null
null
factai_0.1.0/commands.lua
tanner-bruce/factai
18e29994ba321a1ef7d1807715fd778299376aa4
[ "Apache-2.0" ]
null
null
null
factai_0.1.0/commands.lua
tanner-bruce/factai
18e29994ba321a1ef7d1807715fd778299376aa4
[ "Apache-2.0" ]
null
null
null
local m = require("./msgpack") local util = require("./util") function clear() global["entcache"] = {} global["entcache"]["send"] = false global["entcache"]["coal"] = {} global["entcache"]["copper-ore"] = {} global["entcache"]["crude-oil"] = {} global["entcache"]["enemy-base"] = {} global["entcache"]["iron-ore"] = {} global["entcache"]["stone"] = {} global["entcache"]["trees"] = {} global["entcache"]["uranium-ore"] = {} global["entcache"]["dead-dry-hairy-tree"] = {} global["entcache"]["dead-grey-trunk"] = {} global["entcache"]["dead-tree-desert"] = {} global["entcache"]["dry-hairy-tree"] = {} global["entcache"]["dry-tree"] = {} global["entcache"]["tree-01"] = {} global["entcache"]["tree-02"] = {} global["entcache"]["tree-02-red"] = {} global["entcache"]["tree-03"] = {} global["entcache"]["tree-04"] = {} global["entcache"]["tree-05"] = {} global["entcache"]["tree-06"] = {} global["entcache"]["tree-06-brown"] = {} global["entcache"]["tree-07"] = {} global["entcache"]["tree-08"] = {} global["entcache"]["tree-08-brown"] = {} global["entcache"]["tree-08-red"] = {} global["entcache"]["tree-09"] = {} global["entcache"]["tree-09-brown"] = {} global["entcache"]["tree-09-red"] = {} end function find_nearby_entities(e, force) local radius = 110 local pos = e.position; local px = pos.x local py = pos.y local area = { {px-radius, py-radius}, {px+radius, py+radius}} return e.surface.find_entities_filtered{area = area, force = {force}} end function get_visible_offsets(e) local pos = e.position local px = pos.x local py = pos.y local max_w = 1920.0 local max_h = 1080.0 local dsc = 0.6 local dsr = e.display_resolution local w_off = ((60.0*dsr.width) / (2.0*dsc*max_w)) local h_off = ((32.0*dsr.height) / (2.0*dsc*max_h)) return {w_off, h_off} end function get_visible_bounds(e) local offs = get_visible_offsets(e) local w_off = offs[1] local h_off = offs[2] return { {e.position.x-w_off, e.position.y-h_off}, {e.position.x+w_off, e.position.y+h_off}} end function find_visible_entities(e, force) local area = get_visible_bounds(e) return e.surface.find_entities_filtered{area = area, force = {force}} end function commands.on_tick(event) local p = game.players[1] if not p then end end function commands.step(parameter) game.tick_paused = false -- if game.ticks_to_run - parameter.parameter > 0 then -- return m.pack("ip") -- end -- game.ticks_to_run = parameter.parameter end function commands.observe(parameter) game.tick_paused = false local p = game.players[1] if not p then return end local pos = p.position local ws = p.walking_state local rds = p.riding_state local ms = p.mining_state local ss = p.shooting_state local ps = p.picking_state local rs = p.repair_state local cs = p.cursor_stack local cg = p.cursor_ghost local ic = p.in_combat -- local cq = p.crafting_queue -- local cmp = p.character_mining_progress -- local ent = p.character -- local health = ent.get_health_ratio() -- local kills = ent.kills -- local effects = ent.effects -- local last_dmg = ent.tick_of_last_damage -- local sel = p.selected -- local aqbs = p.get_active_quick_bar_page -- rendering.draw_text{ -- text = "text", -- surface = p.surface, -- target = {p.position.x,p.position.y}, -- color = {r = 1}, -- } -- local insert = table.insert local player_feature_vec = {} insert(player_feature_vec, parameter.tick) insert(player_feature_vec, pos.x) insert(player_feature_vec, pos.y) insert(player_feature_vec, ws.walking_state or false) insert(player_feature_vec, ws.direction) insert(player_feature_vec, ic) insert(player_feature_vec, ss) entities = {} ec = global["entcache"] for i, ent in ipairs(find_visible_entities(p)) do if ec[ent.name] then ectx = global["entcache"][ent.position.x] or {} ectx[ent.position.y] = {ent.health, ent.get_health_ratio()} global["entcache"][ent.name][ent.position.x] = ectx else el = entities[ent.name] or {} elx = el[ent.position.x] or {} elx[ent.position.y] = {ent.health, ent.get_health_ratio()} el[ent.position.x] = elx entities[ent.name] = el end end if global["send"] == true then for ent, ents in pairs(global["entcache"]) do if next(ents) ~= nil then entities[ent] = ents end end end out = { player_feature_vec, entities } rcon.print(m.pack(out)) global["send"] = false clear() end function commands.enqueue(parameter) rcon.print("howdy") end function commands.zoom(parameter) local p = game.players[1] if not p then return end p.zoom = parameter.parameter rcon.print(m.pack{p.display_resolution,get_visible_offsets(p)}) end
29.073034
73
0.60599
723b928ee4e1edd6549155a2c3f1b515e6088146
2,445
ps1
PowerShell
virt/ansible-latest/lib/python2.7/site-packages/ansible/modules/windows/win_tempfile.ps1
lakhlaifi/RedHat-Ansible
27c5077cced9d416081fcd5d69ea44bca0317fa4
[ "Apache-2.0" ]
1
2020-03-22T01:04:39.000Z
2020-03-22T01:04:39.000Z
ansible/ansible/modules/windows/win_tempfile.ps1
SergeyCherepanov/ansible
875711cd2fd6b783c812241c2ed7a954bf6f670f
[ "MIT" ]
7
2020-09-07T17:27:56.000Z
2022-03-02T06:25:46.000Z
ansible/ansible/modules/windows/win_tempfile.ps1
SergeyCherepanov/ansible
875711cd2fd6b783c812241c2ed7a954bf6f670f
[ "MIT" ]
1
2020-03-22T01:04:48.000Z
2020-03-22T01:04:48.000Z
#!powershell # Copyright: (c) 2017, Dag Wieers (@dagwieers) <dag@wieers.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) #AnsibleRequires -CSharpUtil Ansible.Basic Function New-TempFile { Param ([string]$path, [string]$prefix, [string]$suffix, [string]$type, [bool]$checkmode) $temppath = $null $attempt = 0 # Since we don't know if the file already exists, we try 5 times with a random name do { $attempt += 1 $randomname = [System.IO.Path]::GetRandomFileName() $temppath = (Join-Path -Path $path -ChildPath "$prefix$randomname$suffix") Try { $file = New-Item -Path $temppath -ItemType $type -WhatIf:$checkmode # Makes sure we get the full absolute path of the created temp file and not a relative or DOS 8.3 dir if (-not $checkmode) { $temppath = $file.FullName } else { # Just rely on GetFulLpath for check mode $temppath = [System.IO.Path]::GetFullPath($temppath) } } Catch { $temppath = $null $error = $_ } } until (($null -ne $temppath) -or ($attempt -ge 5)) # If it fails 5 times, something is wrong and we have to report the details if ($null -eq $temppath) { $module.FailJson("No random temporary file worked in $attempt attempts. Error: $($error.Exception.Message)", $error) } return $temppath.ToString() } $spec = @{ options = @{ path = @{ type='path'; default='%TEMP%'; aliases=@( 'dest' ) } state = @{ type='str'; default='file'; choices=@( 'directory', 'file') } prefix = @{ type='str'; default='ansible.' } suffix = @{ type='str' } } supports_check_mode = $true } $module = [Ansible.Basic.AnsibleModule]::Create($args, $spec) $path = $module.Params.path $state = $module.Params.state $prefix = $module.Params.prefix $suffix = $module.Params.suffix # Expand environment variables on non-path types if ($null -ne $prefix) { $prefix = [System.Environment]::ExpandEnvironmentVariables($prefix) } if ($null -ne $suffix) { $suffix = [System.Environment]::ExpandEnvironmentVariables($suffix) } $module.Result.changed = $true $module.Result.state = $state $module.Result.path = New-TempFile -Path $path -Prefix $prefix -Suffix $suffix -Type $state -CheckMode $module.CheckMode $module.ExitJson()
33.958333
124
0.622495
c1f85b0dde11a7a5dcb33d2160e5561ae71eb661
473
lua
Lua
Interface/AddOns/EuiGarrison/Broker.lua
ChinarG/Game-Wow-Plugins-Setting
e3fd3ddec1387c1f971dc195fec4fd9045d3105d
[ "Apache-2.0" ]
null
null
null
Interface/AddOns/EuiGarrison/Broker.lua
ChinarG/Game-Wow-Plugins-Setting
e3fd3ddec1387c1f971dc195fec4fd9045d3105d
[ "Apache-2.0" ]
null
null
null
Interface/AddOns/EuiGarrison/Broker.lua
ChinarG/Game-Wow-Plugins-Setting
e3fd3ddec1387c1f971dc195fec4fd9045d3105d
[ "Apache-2.0" ]
null
null
null
local addon_name, addon_env = ... if not LibStub then return end local ldb = LibStub:GetLibrary("LibDataBroker-1.1", true) if not ldb then return end local broker = ldb:NewDataObject(addon_name, { type = "data source", label = addon_name, icon = "Interface\\ICONS\\Achievement_Garrison_Tier01_" .. UnitFactionGroup("player"), OnTooltipShow = addon_env.RemoveAllWorkers_TooltipSetText }) addon_env.broker = broker addon_env.GarrisonBuilding_UpdateBuildings()
29.5625
89
0.767442
f207c1ed49f9eba1bffc1806501cd4a814520519
622
asm
Assembly
oeis/248/A248877.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
11
2021-08-22T19:44:55.000Z
2022-03-20T16:47:57.000Z
oeis/248/A248877.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
9
2021-08-29T13:15:54.000Z
2022-03-09T19:52:31.000Z
oeis/248/A248877.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
3
2021-08-22T20:56:47.000Z
2021-09-29T06:26:12.000Z
; A248877: a(1) = 23, a(2) = 71, a(n) = 3*a(n-1) - 2*a(n-2) for n>2. ; 23,71,167,359,743,1511,3047,6119,12263,24551,49127,98279,196583,393191,786407,1572839,3145703,6291431,12582887,25165799,50331623,100663271,201326567,402653159,805306343,1610612711,3221225447,6442450919,12884901863,25769803751,51539607527,103079215079,206158430183,412316860391,824633720807,1649267441639,3298534883303,6597069766631,13194139533287,26388279066599,52776558133223,105553116266471,211106232532967,422212465065959,844424930131943,1688849860263911,3377699720527847,6755399441055719 mov $1,2 pow $1,$0 sub $1,1 mul $1,48 add $1,23 mov $0,$1
62.2
493
0.813505
758570a4e822bdb6cc925a08cf49c2a58b6378e9
7,235
rs
Rust
src/key.rs
virgesmith/crypto-rs
cf693473f3e3b3321c7a2427ee3a55d72bbe8df7
[ "MIT" ]
null
null
null
src/key.rs
virgesmith/crypto-rs
cf693473f3e3b3321c7a2427ee3a55d72bbe8df7
[ "MIT" ]
null
null
null
src/key.rs
virgesmith/crypto-rs
cf693473f3e3b3321c7a2427ee3a55d72bbe8df7
[ "MIT" ]
null
null
null
use openssl::ec::*; use openssl::ecdsa::*; use openssl::pkey::{Private, Public}; use openssl::nid::Nid; use openssl::bn::*; use std::error::Error; use std::io::prelude::*; use std::fs::File; pub struct Key { key_impl: EcKey<Private> } lazy_static!{ static ref EC_GRP: EcGroup = EcGroup::from_curve_name(Nid::SECP256K1).unwrap(); } impl Key { pub fn new() -> Result<Key, Box<dyn Error>> { Ok(Key{ key_impl: EcKey::generate(&EC_GRP)? }) } pub fn from_pem_file(filename: &str) -> Result<Key, Box<dyn Error>> { let mut file = File::open(filename)?; let mut buffer = Vec::new(); file.read_to_end(&mut buffer)?; Ok(Key{ key_impl: EcKey::private_key_from_pem(&buffer)? }) } pub fn from_private_bytes(bytes: &[u8;32]) -> Result<Key, Box<dyn Error>> { let ctx = BigNumContext::new()?; let prv = BigNum::from_slice(bytes)?; let mut pbl = EcPoint::new(&EC_GRP)?; //pbl.mul(&group, &EcPoint::new(&group).unwrap(), &prv, &ctx).unwrap(); pbl.mul_generator(&EC_GRP, &prv, &ctx).unwrap(); Ok(Key{ key_impl: EcKey::from_private_components(&EC_GRP, &prv, &pbl)? }) } fn public_key_impl(&self, form: PointConversionForm) -> Result<Vec<u8>, Box<dyn Error>> { let mut ctx = BigNumContext::new()?; Ok(self.key_impl.public_key().to_bytes(&EC_GRP, form, &mut ctx)?) } pub fn public_key(&self) -> Result<Vec<u8>, Box<dyn Error>> { self.public_key_impl(PointConversionForm::UNCOMPRESSED) } pub fn compressed_public_key(&self) -> Result<Vec<u8>, Box<dyn Error>> { self.public_key_impl(PointConversionForm::COMPRESSED) } pub fn private_key(&self) -> Result<Vec<u8>, Box<dyn Error>> { Ok(self.key_impl.private_key().to_vec()) } pub fn sign(&self, data: &[u8]) -> Result<Vec<u8>, Box<dyn Error>> { Ok(EcdsaSig::sign(data, &self.key_impl)?.to_der()?) } pub fn to_pubkey(&self) -> Result<PubKey, Box<dyn Error>> { PubKey::from_bytes(&self.public_key()?) } } pub struct PubKey { key_impl: EcKey<Public> } impl PubKey { pub fn from_pem_file(filename: &str) -> Result<PubKey, Box<dyn Error>> { let mut file = File::open(filename)?; let mut buffer = Vec::new(); file.read_to_end(&mut buffer)?; let pem = pem::parse(buffer)?; PubKey::from_bytes(&pem.contents) } pub fn from_bytes(bytes: &[u8]) -> Result<PubKey, Box<dyn Error>> { let mut ctx = BigNumContext::new()?; let pbl = EcPoint::from_bytes(&EC_GRP, &bytes, &mut ctx)?; Ok(PubKey{ key_impl: EcKey::from_public_key(&EC_GRP, &pbl)? }) } // pub fn from_signature(bytes: &[u8]) -> Result<PubKey, Box<dyn Error>> { // } fn public_key_impl(&self, form: PointConversionForm) -> Result<Vec<u8>, Box<dyn Error>> { let mut ctx = BigNumContext::new()?; Ok(self.key_impl.public_key().to_bytes(&EC_GRP, form, &mut ctx)?) } pub fn public_key(&self) -> Result<Vec<u8>, Box<dyn Error>> { self.public_key_impl(PointConversionForm::UNCOMPRESSED) } pub fn compressed_public_key(&self) -> Result<Vec<u8>, Box<dyn Error>> { self.public_key_impl(PointConversionForm::COMPRESSED) } pub fn verify(&self, msg: &[u8], sig: &[u8]) -> Result<bool, Box<dyn Error>> { Ok(EcdsaSig::from_der(&sig)?.verify(&msg, &self.key_impl)?) } } #[cfg(test)] mod tests { use super::*; use crate::hash::hash256; #[test] fn test_construction() { let prvbytes: [u8; 32] = [0x94, 0x19, 0x9c, 0x35, 0xc8, 0x84, 0x8e, 0x03, 0xe9, 0xcb, 0x43, 0x80, 0xef, 0x71, 0x2b, 0xc0, 0x77, 0xa5, 0x99, 0x1f, 0xa0, 0xbb, 0xf2, 0xc4, 0xa4, 0x0b, 0x03, 0x53, 0xe3, 0xad, 0x6c, 0x27]; let prvkey = Key::from_private_bytes(&prvbytes).unwrap(); assert_eq!(prvkey.private_key().unwrap(), prvbytes); let c_pubbytes: [u8; 33] = [2, 246, 117, 90, 253, 87, 182, 218, 67, 232, 238, 200, 20, 75, 94, 254, 99, 249, 2, 204, 193, 152, 4, 97, 252, 102, 67, 86, 113, 245, 75, 234, 2]; let pubkey = PubKey::from_bytes(&c_pubbytes).unwrap(); assert_eq!(&pubkey.compressed_public_key().unwrap(), &c_pubbytes.to_vec()); let u_pubbytes: [u8; 65] = [4, 246, 117, 90, 253, 87, 182, 218, 67, 232, 238, 200, 20, 75, 94, 254, 99, 249, 2, 204, 193, 152, 4, 97, 252, 102, 67, 86, 113, 245, 75, 234, 2, 20, 124, 143, 146, 74, 30, 124, 190, 102, 230, 205, 240, 101, 50, 19, 99, 81, 216, 134, 70, 128, 148, 169, 63, 137, 233, 148, 250, 142, 187, 208, 128]; let pubkey = PubKey::from_bytes(&u_pubbytes).unwrap(); assert_eq!(&pubkey.public_key().unwrap(), &u_pubbytes.to_vec()); } #[test] fn test_consistency() { let bytes : [u8; 32] = [0x94, 0x19, 0x9c, 0x35, 0xc8, 0x84, 0x8e, 0x03, 0xe9, 0xcb, 0x43, 0x80, 0xef, 0x71, 0x2b, 0xc0, 0x77, 0xa5, 0x99, 0x1f, 0xa0, 0xbb, 0xf2, 0xc4, 0xa4, 0x0b, 0x03, 0x53, 0xe3, 0xad, 0x6c, 0x27]; let key = Key::from_private_bytes(&bytes).unwrap(); let chex = "02f6755afd57b6da43e8eec8144b5efe63f902ccc1980461fc66435671f54bea02"; let uhex = "04f6755afd57b6da43e8eec8144b5efe63f902ccc1980461fc66435671f54bea02147c8f924a1e7cbe66e6cdf06532136351d886468094a93f89e994fa8ebbd080"; // directly get public key from private key let c_pubbytes = key.compressed_public_key().unwrap(); assert_eq!(c_pubbytes.len(), 33 as usize); assert_eq!(hex::encode(c_pubbytes), chex); let u_pubbytes = key.public_key().unwrap(); assert_eq!(u_pubbytes.len(), 65 as usize); assert_eq!(hex::encode(u_pubbytes), uhex); // construct a PubKey object and extract let pubkey = key.to_pubkey().unwrap(); let c_pubbytes = pubkey.compressed_public_key().unwrap(); assert_eq!(c_pubbytes.len(), 33 as usize); assert_eq!(hex::encode(c_pubbytes), chex); let u_pubbytes = pubkey.public_key().unwrap(); assert_eq!(u_pubbytes.len(), 65 as usize); assert_eq!(hex::encode(u_pubbytes), uhex); } #[test] fn test_signing() { let bytes : [u8; 32] = [0x94, 0x19, 0x9c, 0x35, 0xc8, 0x84, 0x8e, 0x03, 0xe9, 0xcb, 0x43, 0x80, 0xef, 0x71, 0x2b, 0xc0, 0x77, 0xa5, 0x99, 0x1f, 0xa0, 0xbb, 0xf2, 0xc4, 0xa4, 0x0b, 0x03, 0x53, 0xe3, 0xad, 0x6c, 0x27]; let key = Key::from_private_bytes(&bytes).unwrap(); let msg = hash256(b"Top secret plans"); let sig = key.sign(&msg).unwrap(); let pubkey = key.to_pubkey().unwrap(); // should verify against public key and original digest assert_eq!(pubkey.verify(&msg, &sig).unwrap(), true); let false_msg = hash256(b"Decoy plans"); // should NOT verify against public key and a different digest assert_eq!(pubkey.verify(&false_msg, &sig).unwrap(), false); let other_bytes : [u8; 32] = [0x95, 0x19, 0x9c, 0x35, 0xc8, 0x84, 0x8e, 0x03, 0xe9, 0xcb, 0x43, 0x80, 0xef, 0x71, 0x2b, 0xc0, 0x77, 0xa5, 0x99, 0x1f, 0xa0, 0xbb, 0xf2, 0xc4, 0xa4, 0x0b, 0x03, 0x53, 0xe3, 0xad, 0x6c, 0x27]; let other_pubkey = Key::from_private_bytes(&other_bytes).unwrap().to_pubkey().unwrap(); other_pubkey.compressed_public_key().unwrap(); // should NOT verify against different public key and original digest assert_eq!(other_pubkey.verify(&msg, &sig).unwrap(), false); } }
34.617225
148
0.636213
575c1838165b82040495369fb06d7c787eed5b18
127
h
C
dbi_clients_src/pin/pin-3.6-97554-g31f0a167d-gcc-linux/extras/stlport/include/stl/config/_mac.h
DigitalAlchemist/fuzzwatch
32517e7b80b680dd658e833ed2dfdd88744e6694
[ "Apache-2.0" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
dbi_clients_src/pin/pin-3.6-97554-g31f0a167d-gcc-linux/extras/stlport/include/stl/config/_mac.h
DigitalAlchemist/fuzzwatch
32517e7b80b680dd658e833ed2dfdd88744e6694
[ "Apache-2.0" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
dbi_clients_src/pin/pin-3.6-97554-g31f0a167d-gcc-linux/extras/stlport/include/stl/config/_mac.h
DigitalAlchemist/fuzzwatch
32517e7b80b680dd658e833ed2dfdd88744e6694
[ "Apache-2.0" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
#define _STLP_PLATFORM "Mac" #define _STLP_MAC 1 #error Looks like unsupported platform #define _STLP_USE_UNIX_EMULATION_IO
18.142857
38
0.826772
fc7af38248adf6c4846e69d065a4c35dc75c3c39
13,325
css
CSS
css/estilo-pUs.css
JRamirez95/Pizza-RanchCR
33774a630739e7a911f01e0fed801b0002590b4d
[ "MIT" ]
null
null
null
css/estilo-pUs.css
JRamirez95/Pizza-RanchCR
33774a630739e7a911f01e0fed801b0002590b4d
[ "MIT" ]
null
null
null
css/estilo-pUs.css
JRamirez95/Pizza-RanchCR
33774a630739e7a911f01e0fed801b0002590b4d
[ "MIT" ]
null
null
null
a,i,li,u,ul{background:transparent;border:0 none;font-size:100%;margin:0;padding:0;border:0;outline:0;vertical-align:top;} ul {list-style:none;} .top { color:#fff;background: #000;} .top p{display:inline-block;} .top ul li {display: inline-block;padding-right: 7px;} .top .mail p{background: url(../images/Mail.png) no-repeat 4px 2px;color:#fff;padding-left: 33px;font-size:15px;} .top .phone p{background: url(../images/Phone.png) no-repeat 4px 2px;color:#fff;padding-left: 33px;font-size:15px;} .top ul.top-social {margin: 5px 7px 0 0;} .top ul.top-social li a{padding: 8px 10px;display: block;width: 35px;height: 35px;border-radius: 50%;font-size: 19px;line-height: 40px;color: #ffffff;background: #E4000D;} .top ul.top-social li a:hover, ul.social-buttons li a:focus, ul.social-buttons li a:active{opacity: 0.7;} header{background: #E4000D url(../images/bg-header.png) repeat;padding:15px 0;} .logo{display:inline-block;} .logo img{max-width: 210px;} .site-title{background-color:#000; color:#fff;position: relative;padding: 12px;} .site-title:after{ content:''; background:url(../images/bg-1.png) repeat-x; height:12px; width:100%; left:0; bottom:-12px; position:absolute; z-index: 9999; } /* * ========================================================== * GENERAL * ========================================================== */ html, body {width:100%; padding:0; margin:0;} body {background: #292522 url(../images/bg.png) repeat center center;color: #3F3F3F;font: 16px/25px Arial, Helvetica, sans-serif;} section { padding: 0 15px; } a { -webkit-transition: all 0.3s; transition: all 0.3s; display: inline-block; } .dashtext-1 { color: #864DD9 !important; } .dashtext-2 { color: #CF53F9 !important; } .dashtext-3 { color: #e95f71 !important; } .dashtext-4 { color: #7127AC !important; } .dashbg-1 { background: #864DD9; } .dashbg-2 { background: #CF53F9; } .dashbg-3 { background: #007bff; } .dashbg-4 { background: #7127AC; } .text-bold { font-weight: 700; } .text-small { font-size: 0.8rem; } p { line-height: 1.7; } button { cursor: pointer; } i, span, strong { display: inline-block; } input { outline: none; } .no-padding { padding: 0 !important; } .no-padding-top { padding-top: 0 !important; } .no-padding-bottom { padding-bottom: 0 !important; } .no-margin { margin: 0 !important; } .no-margin-top { margin-top: 0 !important; } .no-margin-bottom { margin-bottom: 0 !important; } .padding-top-sm { padding-top: 30px !important; } .padding-bottom-sm { padding-bottom: 30px !important; } .margin-top-sm { margin-top: 30px !important; } .margin-bottom-sm { margin-bottom: 30px !important; } .breadcrumb { background: none; padding: 20px 20px; margin-bottom: 0; } .breadcrumb a { color: #007bff; text-decoration: none !important; } .breadcrumb li.active { color: #585a5f; } .breadcrumb-item + .breadcrumb-item::before { color: #585a5f; } .block { padding: 20px; background: #2d3035; color: #8a8d93; margin-bottom: 30px; } .page-content { background: #22252a; min-height: 100vh; width: calc(100% - 280px); padding: 0; } .page-content.active { width: 100%; } .page-header { padding: 20px 15px; background: #2d3035; color: #8a8d93; margin-bottom: 30px; } .dropdown-menu { border-radius: 0; border: 0; -webkit-box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.1), -1px -1px 2px rgba(0, 0, 0, 0.1); box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.1), -1px -1px 2px rgba(0, 0, 0, 0.1); color: #8a8d93; font-size: 1rem; min-width: 200px; margin-top: 10px; background: #2d3035; left: auto; right: 0; } .dropdown-menu a { color: inherit; } .dropdown-menu a:hover { background: #007bff; color: #fff; } .dropdown-menu a { padding: 10px 20px; } .dropdown-toggle { background: none; outline: none; border-radius: 0; } .dropdown-toggle span { color: #555; } .dropdown-toggle::after { border: none !important; content: '\f107'; vertical-align: baseline; font-family: 'FontAwesome'; margin-left: 0; } i[class*='icon-'] { -webkit-transform: translateY(2px); transform: translateY(2px); } .dropdown-menu { border-radius: 0; padding: 0; margin-top: 21px; border: 1px solid #393c43; -webkit-box-shadow: 0 0 10px rgba(34, 37, 42, 0.95); box-shadow: 0 0 10px rgba(34, 37, 42, 0.95); } .dropdown-menu a { padding: 10px 15px !important; color: #333; font-size: 0.9rem; text-transform: none !important; } .dropdown-menu a:hover { color: #fff !important; } .dropdown-menu a:active { background-color: #fff; } .dropdown-submenu { position: relative; } .dropdown-submenu > .dropdown-menu { top: 0; left: 100%; margin-top: -2px; font-size: 1rem; } .block .title { margin-bottom: 20px; } .block .title strong:first-child { font-size: 1.25rem; color: #a5a7ab; } .block .title span:first-child { font-weight: 300; font-size: 0.95rem; } /* * ========================================================== * NAVBAR * ========================================================== */ nav.navbar { background: #2d3035; color: #8a8d93; padding-top: 20px; padding-bottom: 20px; border-bottom: 1px solid #34373d; z-index: 9998; } nav.navbar .sidebar-toggle { width: 36px; height: 36px; line-height: 29px; text-align: center; border-radius: 50%; background: #282b2f; color: #8a8d93; font-size: 1.1rem; border: 2px solid #3d4148; outline: none; } nav.navbar a { color: inherit; } nav.navbar .brand-text { display: none; font-weight: 700; } nav.navbar .brand-text.visible { display: block; } nav.navbar a.nav-link { padding: .5rem .3rem; position: relative; } nav.navbar a.nav-link .badge { width: 20px; height: 20px; line-height: 20px; color: #fff; text-align: center; border-radius: 50%; padding: 0; font-size: 0.7rem; position: absolute; top: 0; right: -10px; } /* Navbar dropdown effect */ nav.navbar .dropdown .dropdown-menu { -webkit-transform: translateY(50px); transform: translateY(50px); -webkit-transition: all 0.3s ease-in-out; transition: all 0.3s ease-in-out; } nav.navbar .dropdown .dropdown-menu.active { -webkit-transform: translateY(0); transform: translateY(0); } /* Navbar Media Query ----------------------------------- */ @media (max-width: 1199px) { nav.navbar .right-menu { margin-bottom: -3px; } nav.navbar .navbar-brand { margin-right: 5px; } nav.navbar .search-inner form input { font-size: 1.25rem !important; } nav.navbar .search-inner form button.submit { position: absolute; font-size: 2rem; top: 50px; display: block; width: 100%; } nav.navbar .sidebar-toggle { width: 30px; height: 30px; line-height: 25px; font-size: 1rem; } nav.navbar .messages-toggle, nav.navbar .tasks-toggle { margin-right: 0; } nav.navbar .brand-text { display: none !important; } nav.navbar .brand-text.visible { display: none !important; } nav.navbar .brand-text.brand-sm { display: block !important; } nav.navbar .sidebar-toggle { -webkit-transform: rotateY(180deg); transform: rotateY(180deg); } } @media (max-width: 991px) { nav.navbar .dropdown-menu { right: -140px; } nav.navbar .megamenu { right: 0 !important; } nav.navbar a.nav-link { font-size: 0.85rem; } nav.navbar a.nav-link .badge { width: 16px; height: 16px; line-height: 16px; color: #fff; text-align: center; font-size: 0.6rem; } } /* * ========================================================== * SIDEBAR * ========================================================== */ nav#sidebar { width: 280px; background: #2d3035; color: #6a6c70; border-right: 1px solid #34373d; } nav#sidebar a { color: inherit; text-decoration: none; position: relative; } nav#sidebar a[data-toggle="collapse"]::after { content: '\f104'; display: inline-block; -webkit-transform: translateY(-50%); transform: translateY(-50%); font-family: 'FontAwesome'; position: absolute; top: 50%; right: 20px; } nav#sidebar a[aria-expanded="true"] { background: #34373d; } nav#sidebar a[aria-expanded="true"]::after { content: '\f107'; } nav#sidebar a i { font-size: 1.2em; margin-right: 10px; -webkit-transition: none; transition: none; } nav#sidebar ul ul a { padding: 14px; padding-left: 60px; background: #22252a; } nav#sidebar .sidebar-header { padding: 30px 20px; } nav#sidebar .sidebar-header h1, nav#sidebar .sidebar-header p { margin-bottom: 0; } nav#sidebar .sidebar-header h1 { color: #8a8d93; } nav#sidebar .sidebar-header p { font-size: 0.9rem; } nav#sidebar span.heading { font-weight: 700; margin-left: 20px; color: #494d53; font-size: 1.2rem; margin-bottom: 15px; } nav#sidebar .avatar { min-width: 70px; max-width: 70px; min-height: 70px; max-height: 70px; border-radius: 50%; overflow: hidden; margin-right: 15px; padding: 4px; border: 3px solid #282b2f; } div.avatar { /* cambia estos dos valores para definir el tamaño de tu círculo */ height: 100px; width: 100px; /* los siguientes valores son independientes del tamaño del círculo */ background-repeat: no-repeat; background-position: 50%; border-radius: 50%; background-size: 100% auto; display:block; margin:auto; } nav#sidebar ul { max-height: none; } nav#sidebar ul a { padding: 18px 20px; display: block; font-weight: 400; } nav#sidebar ul a:hover { background: #34373d; } nav#sidebar ul a:hover i { color: #007bff; } nav#sidebar ul a i { margin-right: 20px; -webkit-transition: all 0.3s; transition: all 0.3s; padding-right: 20px; border-right: 1px solid #454649; } nav#sidebar li { position: relative; } nav#sidebar li::before { content: ''; width: 2px; height: 100%; background: none; display: block; position: absolute; top: 0; left: 0; z-index: 99; } nav#sidebar li.active::before { background: #007bff; } nav#sidebar li.active a { background: #34373d; color: #bfc1c4; } nav#sidebar li.active i { color: #007bff; } nav#sidebar.shrinked { width: 80px; } nav#sidebar.shrinked .sidebar-header { padding: 10px; } nav#sidebar.shrinked .sidebar-header .title { display: none; } nav#sidebar.shrinked span.heading { margin-left: 0; display: block; text-align: center; font-size: 1rem; } nav#sidebar.shrinked ul { max-height: none; } nav#sidebar.shrinked ul a { padding: 14px 5px; display: block; font-weight: 400; text-align: center; font-size: 0.8rem; } nav#sidebar.shrinked ul i { font-size: 1.2rem; text-align: center !important; width: 100%; display: block !important; border: none !important; padding: 0 !important; } nav#sidebar.shrinked ul ul a { padding-left: 10px; } nav#sidebar.shrinked a[data-toggle="collapse"]::after { content: '\f107'; -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%); position: absolute; top: 88%; left: 50%; } nav#sidebar.shrinked a[aria-expanded="true"]::after { content: '\f106'; } /* Sidebar Media Query ----------------------------------- */ @media (max-width: 1199px) { .page-content { width: 100%; } .page-content.active { width: calc(100% - 80px); } nav#sidebar { width: 80px; margin-left: -80px; } nav#sidebar .sidebar-header { padding: 10px; } nav#sidebar .sidebar-header .title { display: none; } nav#sidebar span.heading { margin-left: 0; display: block; text-align: center; font-size: 1rem; } nav#sidebar ul { max-height: none; } nav#sidebar ul a { padding: 12px 5px; display: block; font-weight: 400; text-align: center; font-size: 0.8rem; } nav#sidebar ul i { font-size: 1.2rem; text-align: center !important; width: 100%; display: block !important; border: none !important; padding: 0 !important; } nav#sidebar ul ul a { padding-left: 10px; } nav#sidebar.shrinked { margin-left: 0; } nav#sidebar a[data-toggle="collapse"]::after { content: '\f107'; -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%); position: absolute; top: 88%; left: 50%; } nav#sidebar a[aria-expanded="true"]::after { content: '\f106'; } } .bloc_left_price { color: #c01508; text-align: center; font-weight: bold; font-size: 150%; } .category_block li:hover { background-color: #007bff; } .category_block li:hover a { color: #ffffff; } .category_block li a { color: #343a40; } .add_to_cart_block .price { color: #c01508; text-align: center; font-weight: bold; font-size: 200%; margin-bottom: 0; } .add_to_cart_block .price_discounted { color: #343a40; text-align: center; text-decoration: line-through; font-size: 140%; } .product_rassurance { padding: 10px; margin-top: 15px; background: #ffffff; border: 1px solid #6c757d; color: #6c757d; } .product_rassurance .list-inline { margin-bottom: 0; text-transform: uppercase; text-align: center; } .product_rassurance .list-inline li:hover { color: #343a40; } .reviews_product .fa-star { color: gold; }
17.743009
171
0.627467
f532529f5ffb8c68d64d8db9ff8177e73cc03af3
68,230
rs
Rust
src/google/api/servicecontrol/v1/quota_controller.rs
jrconlin/rspan
b1889e70f62a84936717ce84beb02279c76f8218
[ "MIT" ]
null
null
null
src/google/api/servicecontrol/v1/quota_controller.rs
jrconlin/rspan
b1889e70f62a84936717ce84beb02279c76f8218
[ "MIT" ]
null
null
null
src/google/api/servicecontrol/v1/quota_controller.rs
jrconlin/rspan
b1889e70f62a84936717ce84beb02279c76f8218
[ "MIT" ]
null
null
null
// This file is generated by rust-protobuf 2.0.2. Do not edit // @generated // https://github.com/Manishearth/rust-clippy/issues/702 #![allow(unknown_lints)] #![allow(clippy)] #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(box_pointers)] #![allow(dead_code)] #![allow(missing_docs)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] #![allow(unsafe_code)] #![allow(unused_imports)] #![allow(unused_results)] use protobuf::Message as Message_imported_for_functions; use protobuf::ProtobufEnum as ProtobufEnum_imported_for_functions; #[derive(PartialEq,Clone,Default)] pub struct AllocateQuotaRequest { // message fields pub service_name: ::std::string::String, pub allocate_operation: ::protobuf::SingularPtrField<QuotaOperation>, pub service_config_id: ::std::string::String, // special fields unknown_fields: ::protobuf::UnknownFields, cached_size: ::protobuf::CachedSize, } impl AllocateQuotaRequest { pub fn new() -> AllocateQuotaRequest { ::std::default::Default::default() } // string service_name = 1; pub fn clear_service_name(&mut self) { self.service_name.clear(); } // Param is passed by value, moved pub fn set_service_name(&mut self, v: ::std::string::String) { self.service_name = v; } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_service_name(&mut self) -> &mut ::std::string::String { &mut self.service_name } // Take field pub fn take_service_name(&mut self) -> ::std::string::String { ::std::mem::replace(&mut self.service_name, ::std::string::String::new()) } pub fn get_service_name(&self) -> &str { &self.service_name } // .google.api.servicecontrol.v1.QuotaOperation allocate_operation = 2; pub fn clear_allocate_operation(&mut self) { self.allocate_operation.clear(); } pub fn has_allocate_operation(&self) -> bool { self.allocate_operation.is_some() } // Param is passed by value, moved pub fn set_allocate_operation(&mut self, v: QuotaOperation) { self.allocate_operation = ::protobuf::SingularPtrField::some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_allocate_operation(&mut self) -> &mut QuotaOperation { if self.allocate_operation.is_none() { self.allocate_operation.set_default(); } self.allocate_operation.as_mut().unwrap() } // Take field pub fn take_allocate_operation(&mut self) -> QuotaOperation { self.allocate_operation.take().unwrap_or_else(|| QuotaOperation::new()) } pub fn get_allocate_operation(&self) -> &QuotaOperation { self.allocate_operation.as_ref().unwrap_or_else(|| QuotaOperation::default_instance()) } // string service_config_id = 4; pub fn clear_service_config_id(&mut self) { self.service_config_id.clear(); } // Param is passed by value, moved pub fn set_service_config_id(&mut self, v: ::std::string::String) { self.service_config_id = v; } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_service_config_id(&mut self) -> &mut ::std::string::String { &mut self.service_config_id } // Take field pub fn take_service_config_id(&mut self) -> ::std::string::String { ::std::mem::replace(&mut self.service_config_id, ::std::string::String::new()) } pub fn get_service_config_id(&self) -> &str { &self.service_config_id } } impl ::protobuf::Message for AllocateQuotaRequest { fn is_initialized(&self) -> bool { for v in &self.allocate_operation { if !v.is_initialized() { return false; } }; true } fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream) -> ::protobuf::ProtobufResult<()> { while !is.eof()? { let (field_number, wire_type) = is.read_tag_unpack()?; match field_number { 1 => { ::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.service_name)?; }, 2 => { ::protobuf::rt::read_singular_message_into(wire_type, is, &mut self.allocate_operation)?; }, 4 => { ::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.service_config_id)?; }, _ => { ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; }, }; } ::std::result::Result::Ok(()) } // Compute sizes of nested messages #[allow(unused_variables)] fn compute_size(&self) -> u32 { let mut my_size = 0; if !self.service_name.is_empty() { my_size += ::protobuf::rt::string_size(1, &self.service_name); } if let Some(ref v) = self.allocate_operation.as_ref() { let len = v.compute_size(); my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len; } if !self.service_config_id.is_empty() { my_size += ::protobuf::rt::string_size(4, &self.service_config_id); } my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); self.cached_size.set(my_size); my_size } fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream) -> ::protobuf::ProtobufResult<()> { if !self.service_name.is_empty() { os.write_string(1, &self.service_name)?; } if let Some(ref v) = self.allocate_operation.as_ref() { os.write_tag(2, ::protobuf::wire_format::WireTypeLengthDelimited)?; os.write_raw_varint32(v.get_cached_size())?; v.write_to_with_cached_sizes(os)?; } if !self.service_config_id.is_empty() { os.write_string(4, &self.service_config_id)?; } os.write_unknown_fields(self.get_unknown_fields())?; ::std::result::Result::Ok(()) } fn get_cached_size(&self) -> u32 { self.cached_size.get() } fn get_unknown_fields(&self) -> &::protobuf::UnknownFields { &self.unknown_fields } fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { &mut self.unknown_fields } fn as_any(&self) -> &::std::any::Any { self as &::std::any::Any } fn as_any_mut(&mut self) -> &mut ::std::any::Any { self as &mut ::std::any::Any } fn into_any(self: Box<Self>) -> ::std::boxed::Box<::std::any::Any> { self } fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { Self::descriptor_static() } fn new() -> AllocateQuotaRequest { AllocateQuotaRequest::new() } fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect::MessageDescriptor> = ::protobuf::lazy::Lazy { lock: ::protobuf::lazy::ONCE_INIT, ptr: 0 as *const ::protobuf::reflect::MessageDescriptor, }; unsafe { descriptor.get(|| { let mut fields = ::std::vec::Vec::new(); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( "service_name", |m: &AllocateQuotaRequest| { &m.service_name }, |m: &mut AllocateQuotaRequest| { &mut m.service_name }, )); fields.push(::protobuf::reflect::accessor::make_singular_ptr_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<QuotaOperation>>( "allocate_operation", |m: &AllocateQuotaRequest| { &m.allocate_operation }, |m: &mut AllocateQuotaRequest| { &mut m.allocate_operation }, )); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( "service_config_id", |m: &AllocateQuotaRequest| { &m.service_config_id }, |m: &mut AllocateQuotaRequest| { &mut m.service_config_id }, )); ::protobuf::reflect::MessageDescriptor::new::<AllocateQuotaRequest>( "AllocateQuotaRequest", fields, file_descriptor_proto() ) }) } } fn default_instance() -> &'static AllocateQuotaRequest { static mut instance: ::protobuf::lazy::Lazy<AllocateQuotaRequest> = ::protobuf::lazy::Lazy { lock: ::protobuf::lazy::ONCE_INIT, ptr: 0 as *const AllocateQuotaRequest, }; unsafe { instance.get(AllocateQuotaRequest::new) } } } impl ::protobuf::Clear for AllocateQuotaRequest { fn clear(&mut self) { self.clear_service_name(); self.clear_allocate_operation(); self.clear_service_config_id(); self.unknown_fields.clear(); } } impl ::std::fmt::Debug for AllocateQuotaRequest { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { ::protobuf::text_format::fmt(self, f) } } impl ::protobuf::reflect::ProtobufValue for AllocateQuotaRequest { fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef { ::protobuf::reflect::ProtobufValueRef::Message(self) } } #[derive(PartialEq,Clone,Default)] pub struct QuotaOperation { // message fields pub operation_id: ::std::string::String, pub method_name: ::std::string::String, pub consumer_id: ::std::string::String, pub labels: ::std::collections::HashMap<::std::string::String, ::std::string::String>, pub quota_metrics: ::protobuf::RepeatedField<super::metric_value::MetricValueSet>, pub quota_mode: QuotaOperation_QuotaMode, // special fields unknown_fields: ::protobuf::UnknownFields, cached_size: ::protobuf::CachedSize, } impl QuotaOperation { pub fn new() -> QuotaOperation { ::std::default::Default::default() } // string operation_id = 1; pub fn clear_operation_id(&mut self) { self.operation_id.clear(); } // Param is passed by value, moved pub fn set_operation_id(&mut self, v: ::std::string::String) { self.operation_id = v; } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_operation_id(&mut self) -> &mut ::std::string::String { &mut self.operation_id } // Take field pub fn take_operation_id(&mut self) -> ::std::string::String { ::std::mem::replace(&mut self.operation_id, ::std::string::String::new()) } pub fn get_operation_id(&self) -> &str { &self.operation_id } // string method_name = 2; pub fn clear_method_name(&mut self) { self.method_name.clear(); } // Param is passed by value, moved pub fn set_method_name(&mut self, v: ::std::string::String) { self.method_name = v; } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_method_name(&mut self) -> &mut ::std::string::String { &mut self.method_name } // Take field pub fn take_method_name(&mut self) -> ::std::string::String { ::std::mem::replace(&mut self.method_name, ::std::string::String::new()) } pub fn get_method_name(&self) -> &str { &self.method_name } // string consumer_id = 3; pub fn clear_consumer_id(&mut self) { self.consumer_id.clear(); } // Param is passed by value, moved pub fn set_consumer_id(&mut self, v: ::std::string::String) { self.consumer_id = v; } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_consumer_id(&mut self) -> &mut ::std::string::String { &mut self.consumer_id } // Take field pub fn take_consumer_id(&mut self) -> ::std::string::String { ::std::mem::replace(&mut self.consumer_id, ::std::string::String::new()) } pub fn get_consumer_id(&self) -> &str { &self.consumer_id } // repeated .google.api.servicecontrol.v1.QuotaOperation.LabelsEntry labels = 4; pub fn clear_labels(&mut self) { self.labels.clear(); } // Param is passed by value, moved pub fn set_labels(&mut self, v: ::std::collections::HashMap<::std::string::String, ::std::string::String>) { self.labels = v; } // Mutable pointer to the field. pub fn mut_labels(&mut self) -> &mut ::std::collections::HashMap<::std::string::String, ::std::string::String> { &mut self.labels } // Take field pub fn take_labels(&mut self) -> ::std::collections::HashMap<::std::string::String, ::std::string::String> { ::std::mem::replace(&mut self.labels, ::std::collections::HashMap::new()) } pub fn get_labels(&self) -> &::std::collections::HashMap<::std::string::String, ::std::string::String> { &self.labels } // repeated .google.api.servicecontrol.v1.MetricValueSet quota_metrics = 5; pub fn clear_quota_metrics(&mut self) { self.quota_metrics.clear(); } // Param is passed by value, moved pub fn set_quota_metrics(&mut self, v: ::protobuf::RepeatedField<super::metric_value::MetricValueSet>) { self.quota_metrics = v; } // Mutable pointer to the field. pub fn mut_quota_metrics(&mut self) -> &mut ::protobuf::RepeatedField<super::metric_value::MetricValueSet> { &mut self.quota_metrics } // Take field pub fn take_quota_metrics(&mut self) -> ::protobuf::RepeatedField<super::metric_value::MetricValueSet> { ::std::mem::replace(&mut self.quota_metrics, ::protobuf::RepeatedField::new()) } pub fn get_quota_metrics(&self) -> &[super::metric_value::MetricValueSet] { &self.quota_metrics } // .google.api.servicecontrol.v1.QuotaOperation.QuotaMode quota_mode = 6; pub fn clear_quota_mode(&mut self) { self.quota_mode = QuotaOperation_QuotaMode::UNSPECIFIED; } // Param is passed by value, moved pub fn set_quota_mode(&mut self, v: QuotaOperation_QuotaMode) { self.quota_mode = v; } pub fn get_quota_mode(&self) -> QuotaOperation_QuotaMode { self.quota_mode } } impl ::protobuf::Message for QuotaOperation { fn is_initialized(&self) -> bool { for v in &self.quota_metrics { if !v.is_initialized() { return false; } }; true } fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream) -> ::protobuf::ProtobufResult<()> { while !is.eof()? { let (field_number, wire_type) = is.read_tag_unpack()?; match field_number { 1 => { ::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.operation_id)?; }, 2 => { ::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.method_name)?; }, 3 => { ::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.consumer_id)?; }, 4 => { ::protobuf::rt::read_map_into::<::protobuf::types::ProtobufTypeString, ::protobuf::types::ProtobufTypeString>(wire_type, is, &mut self.labels)?; }, 5 => { ::protobuf::rt::read_repeated_message_into(wire_type, is, &mut self.quota_metrics)?; }, 6 => { ::protobuf::rt::read_proto3_enum_with_unknown_fields_into(wire_type, is, &mut self.quota_mode, 6, &mut self.unknown_fields)? }, _ => { ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; }, }; } ::std::result::Result::Ok(()) } // Compute sizes of nested messages #[allow(unused_variables)] fn compute_size(&self) -> u32 { let mut my_size = 0; if !self.operation_id.is_empty() { my_size += ::protobuf::rt::string_size(1, &self.operation_id); } if !self.method_name.is_empty() { my_size += ::protobuf::rt::string_size(2, &self.method_name); } if !self.consumer_id.is_empty() { my_size += ::protobuf::rt::string_size(3, &self.consumer_id); } my_size += ::protobuf::rt::compute_map_size::<::protobuf::types::ProtobufTypeString, ::protobuf::types::ProtobufTypeString>(4, &self.labels); for value in &self.quota_metrics { let len = value.compute_size(); my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len; }; if self.quota_mode != QuotaOperation_QuotaMode::UNSPECIFIED { my_size += ::protobuf::rt::enum_size(6, self.quota_mode); } my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); self.cached_size.set(my_size); my_size } fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream) -> ::protobuf::ProtobufResult<()> { if !self.operation_id.is_empty() { os.write_string(1, &self.operation_id)?; } if !self.method_name.is_empty() { os.write_string(2, &self.method_name)?; } if !self.consumer_id.is_empty() { os.write_string(3, &self.consumer_id)?; } ::protobuf::rt::write_map_with_cached_sizes::<::protobuf::types::ProtobufTypeString, ::protobuf::types::ProtobufTypeString>(4, &self.labels, os)?; for v in &self.quota_metrics { os.write_tag(5, ::protobuf::wire_format::WireTypeLengthDelimited)?; os.write_raw_varint32(v.get_cached_size())?; v.write_to_with_cached_sizes(os)?; }; if self.quota_mode != QuotaOperation_QuotaMode::UNSPECIFIED { os.write_enum(6, self.quota_mode.value())?; } os.write_unknown_fields(self.get_unknown_fields())?; ::std::result::Result::Ok(()) } fn get_cached_size(&self) -> u32 { self.cached_size.get() } fn get_unknown_fields(&self) -> &::protobuf::UnknownFields { &self.unknown_fields } fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { &mut self.unknown_fields } fn as_any(&self) -> &::std::any::Any { self as &::std::any::Any } fn as_any_mut(&mut self) -> &mut ::std::any::Any { self as &mut ::std::any::Any } fn into_any(self: Box<Self>) -> ::std::boxed::Box<::std::any::Any> { self } fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { Self::descriptor_static() } fn new() -> QuotaOperation { QuotaOperation::new() } fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect::MessageDescriptor> = ::protobuf::lazy::Lazy { lock: ::protobuf::lazy::ONCE_INIT, ptr: 0 as *const ::protobuf::reflect::MessageDescriptor, }; unsafe { descriptor.get(|| { let mut fields = ::std::vec::Vec::new(); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( "operation_id", |m: &QuotaOperation| { &m.operation_id }, |m: &mut QuotaOperation| { &mut m.operation_id }, )); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( "method_name", |m: &QuotaOperation| { &m.method_name }, |m: &mut QuotaOperation| { &mut m.method_name }, )); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( "consumer_id", |m: &QuotaOperation| { &m.consumer_id }, |m: &mut QuotaOperation| { &mut m.consumer_id }, )); fields.push(::protobuf::reflect::accessor::make_map_accessor::<_, ::protobuf::types::ProtobufTypeString, ::protobuf::types::ProtobufTypeString>( "labels", |m: &QuotaOperation| { &m.labels }, |m: &mut QuotaOperation| { &mut m.labels }, )); fields.push(::protobuf::reflect::accessor::make_repeated_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<super::metric_value::MetricValueSet>>( "quota_metrics", |m: &QuotaOperation| { &m.quota_metrics }, |m: &mut QuotaOperation| { &mut m.quota_metrics }, )); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeEnum<QuotaOperation_QuotaMode>>( "quota_mode", |m: &QuotaOperation| { &m.quota_mode }, |m: &mut QuotaOperation| { &mut m.quota_mode }, )); ::protobuf::reflect::MessageDescriptor::new::<QuotaOperation>( "QuotaOperation", fields, file_descriptor_proto() ) }) } } fn default_instance() -> &'static QuotaOperation { static mut instance: ::protobuf::lazy::Lazy<QuotaOperation> = ::protobuf::lazy::Lazy { lock: ::protobuf::lazy::ONCE_INIT, ptr: 0 as *const QuotaOperation, }; unsafe { instance.get(QuotaOperation::new) } } } impl ::protobuf::Clear for QuotaOperation { fn clear(&mut self) { self.clear_operation_id(); self.clear_method_name(); self.clear_consumer_id(); self.clear_labels(); self.clear_quota_metrics(); self.clear_quota_mode(); self.unknown_fields.clear(); } } impl ::std::fmt::Debug for QuotaOperation { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { ::protobuf::text_format::fmt(self, f) } } impl ::protobuf::reflect::ProtobufValue for QuotaOperation { fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef { ::protobuf::reflect::ProtobufValueRef::Message(self) } } #[derive(Clone,PartialEq,Eq,Debug,Hash)] pub enum QuotaOperation_QuotaMode { UNSPECIFIED = 0, NORMAL = 1, BEST_EFFORT = 2, CHECK_ONLY = 3, } impl ::protobuf::ProtobufEnum for QuotaOperation_QuotaMode { fn value(&self) -> i32 { *self as i32 } fn from_i32(value: i32) -> ::std::option::Option<QuotaOperation_QuotaMode> { match value { 0 => ::std::option::Option::Some(QuotaOperation_QuotaMode::UNSPECIFIED), 1 => ::std::option::Option::Some(QuotaOperation_QuotaMode::NORMAL), 2 => ::std::option::Option::Some(QuotaOperation_QuotaMode::BEST_EFFORT), 3 => ::std::option::Option::Some(QuotaOperation_QuotaMode::CHECK_ONLY), _ => ::std::option::Option::None } } fn values() -> &'static [Self] { static values: &'static [QuotaOperation_QuotaMode] = &[ QuotaOperation_QuotaMode::UNSPECIFIED, QuotaOperation_QuotaMode::NORMAL, QuotaOperation_QuotaMode::BEST_EFFORT, QuotaOperation_QuotaMode::CHECK_ONLY, ]; values } fn enum_descriptor_static() -> &'static ::protobuf::reflect::EnumDescriptor { static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect::EnumDescriptor> = ::protobuf::lazy::Lazy { lock: ::protobuf::lazy::ONCE_INIT, ptr: 0 as *const ::protobuf::reflect::EnumDescriptor, }; unsafe { descriptor.get(|| { ::protobuf::reflect::EnumDescriptor::new("QuotaOperation_QuotaMode", file_descriptor_proto()) }) } } } impl ::std::marker::Copy for QuotaOperation_QuotaMode { } impl ::std::default::Default for QuotaOperation_QuotaMode { fn default() -> Self { QuotaOperation_QuotaMode::UNSPECIFIED } } impl ::protobuf::reflect::ProtobufValue for QuotaOperation_QuotaMode { fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef { ::protobuf::reflect::ProtobufValueRef::Enum(self.descriptor()) } } #[derive(PartialEq,Clone,Default)] pub struct AllocateQuotaResponse { // message fields pub operation_id: ::std::string::String, pub allocate_errors: ::protobuf::RepeatedField<QuotaError>, pub quota_metrics: ::protobuf::RepeatedField<super::metric_value::MetricValueSet>, pub service_config_id: ::std::string::String, // special fields unknown_fields: ::protobuf::UnknownFields, cached_size: ::protobuf::CachedSize, } impl AllocateQuotaResponse { pub fn new() -> AllocateQuotaResponse { ::std::default::Default::default() } // string operation_id = 1; pub fn clear_operation_id(&mut self) { self.operation_id.clear(); } // Param is passed by value, moved pub fn set_operation_id(&mut self, v: ::std::string::String) { self.operation_id = v; } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_operation_id(&mut self) -> &mut ::std::string::String { &mut self.operation_id } // Take field pub fn take_operation_id(&mut self) -> ::std::string::String { ::std::mem::replace(&mut self.operation_id, ::std::string::String::new()) } pub fn get_operation_id(&self) -> &str { &self.operation_id } // repeated .google.api.servicecontrol.v1.QuotaError allocate_errors = 2; pub fn clear_allocate_errors(&mut self) { self.allocate_errors.clear(); } // Param is passed by value, moved pub fn set_allocate_errors(&mut self, v: ::protobuf::RepeatedField<QuotaError>) { self.allocate_errors = v; } // Mutable pointer to the field. pub fn mut_allocate_errors(&mut self) -> &mut ::protobuf::RepeatedField<QuotaError> { &mut self.allocate_errors } // Take field pub fn take_allocate_errors(&mut self) -> ::protobuf::RepeatedField<QuotaError> { ::std::mem::replace(&mut self.allocate_errors, ::protobuf::RepeatedField::new()) } pub fn get_allocate_errors(&self) -> &[QuotaError] { &self.allocate_errors } // repeated .google.api.servicecontrol.v1.MetricValueSet quota_metrics = 3; pub fn clear_quota_metrics(&mut self) { self.quota_metrics.clear(); } // Param is passed by value, moved pub fn set_quota_metrics(&mut self, v: ::protobuf::RepeatedField<super::metric_value::MetricValueSet>) { self.quota_metrics = v; } // Mutable pointer to the field. pub fn mut_quota_metrics(&mut self) -> &mut ::protobuf::RepeatedField<super::metric_value::MetricValueSet> { &mut self.quota_metrics } // Take field pub fn take_quota_metrics(&mut self) -> ::protobuf::RepeatedField<super::metric_value::MetricValueSet> { ::std::mem::replace(&mut self.quota_metrics, ::protobuf::RepeatedField::new()) } pub fn get_quota_metrics(&self) -> &[super::metric_value::MetricValueSet] { &self.quota_metrics } // string service_config_id = 4; pub fn clear_service_config_id(&mut self) { self.service_config_id.clear(); } // Param is passed by value, moved pub fn set_service_config_id(&mut self, v: ::std::string::String) { self.service_config_id = v; } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_service_config_id(&mut self) -> &mut ::std::string::String { &mut self.service_config_id } // Take field pub fn take_service_config_id(&mut self) -> ::std::string::String { ::std::mem::replace(&mut self.service_config_id, ::std::string::String::new()) } pub fn get_service_config_id(&self) -> &str { &self.service_config_id } } impl ::protobuf::Message for AllocateQuotaResponse { fn is_initialized(&self) -> bool { for v in &self.allocate_errors { if !v.is_initialized() { return false; } }; for v in &self.quota_metrics { if !v.is_initialized() { return false; } }; true } fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream) -> ::protobuf::ProtobufResult<()> { while !is.eof()? { let (field_number, wire_type) = is.read_tag_unpack()?; match field_number { 1 => { ::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.operation_id)?; }, 2 => { ::protobuf::rt::read_repeated_message_into(wire_type, is, &mut self.allocate_errors)?; }, 3 => { ::protobuf::rt::read_repeated_message_into(wire_type, is, &mut self.quota_metrics)?; }, 4 => { ::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.service_config_id)?; }, _ => { ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; }, }; } ::std::result::Result::Ok(()) } // Compute sizes of nested messages #[allow(unused_variables)] fn compute_size(&self) -> u32 { let mut my_size = 0; if !self.operation_id.is_empty() { my_size += ::protobuf::rt::string_size(1, &self.operation_id); } for value in &self.allocate_errors { let len = value.compute_size(); my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len; }; for value in &self.quota_metrics { let len = value.compute_size(); my_size += 1 + ::protobuf::rt::compute_raw_varint32_size(len) + len; }; if !self.service_config_id.is_empty() { my_size += ::protobuf::rt::string_size(4, &self.service_config_id); } my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); self.cached_size.set(my_size); my_size } fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream) -> ::protobuf::ProtobufResult<()> { if !self.operation_id.is_empty() { os.write_string(1, &self.operation_id)?; } for v in &self.allocate_errors { os.write_tag(2, ::protobuf::wire_format::WireTypeLengthDelimited)?; os.write_raw_varint32(v.get_cached_size())?; v.write_to_with_cached_sizes(os)?; }; for v in &self.quota_metrics { os.write_tag(3, ::protobuf::wire_format::WireTypeLengthDelimited)?; os.write_raw_varint32(v.get_cached_size())?; v.write_to_with_cached_sizes(os)?; }; if !self.service_config_id.is_empty() { os.write_string(4, &self.service_config_id)?; } os.write_unknown_fields(self.get_unknown_fields())?; ::std::result::Result::Ok(()) } fn get_cached_size(&self) -> u32 { self.cached_size.get() } fn get_unknown_fields(&self) -> &::protobuf::UnknownFields { &self.unknown_fields } fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { &mut self.unknown_fields } fn as_any(&self) -> &::std::any::Any { self as &::std::any::Any } fn as_any_mut(&mut self) -> &mut ::std::any::Any { self as &mut ::std::any::Any } fn into_any(self: Box<Self>) -> ::std::boxed::Box<::std::any::Any> { self } fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { Self::descriptor_static() } fn new() -> AllocateQuotaResponse { AllocateQuotaResponse::new() } fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect::MessageDescriptor> = ::protobuf::lazy::Lazy { lock: ::protobuf::lazy::ONCE_INIT, ptr: 0 as *const ::protobuf::reflect::MessageDescriptor, }; unsafe { descriptor.get(|| { let mut fields = ::std::vec::Vec::new(); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( "operation_id", |m: &AllocateQuotaResponse| { &m.operation_id }, |m: &mut AllocateQuotaResponse| { &mut m.operation_id }, )); fields.push(::protobuf::reflect::accessor::make_repeated_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<QuotaError>>( "allocate_errors", |m: &AllocateQuotaResponse| { &m.allocate_errors }, |m: &mut AllocateQuotaResponse| { &mut m.allocate_errors }, )); fields.push(::protobuf::reflect::accessor::make_repeated_field_accessor::<_, ::protobuf::types::ProtobufTypeMessage<super::metric_value::MetricValueSet>>( "quota_metrics", |m: &AllocateQuotaResponse| { &m.quota_metrics }, |m: &mut AllocateQuotaResponse| { &mut m.quota_metrics }, )); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( "service_config_id", |m: &AllocateQuotaResponse| { &m.service_config_id }, |m: &mut AllocateQuotaResponse| { &mut m.service_config_id }, )); ::protobuf::reflect::MessageDescriptor::new::<AllocateQuotaResponse>( "AllocateQuotaResponse", fields, file_descriptor_proto() ) }) } } fn default_instance() -> &'static AllocateQuotaResponse { static mut instance: ::protobuf::lazy::Lazy<AllocateQuotaResponse> = ::protobuf::lazy::Lazy { lock: ::protobuf::lazy::ONCE_INIT, ptr: 0 as *const AllocateQuotaResponse, }; unsafe { instance.get(AllocateQuotaResponse::new) } } } impl ::protobuf::Clear for AllocateQuotaResponse { fn clear(&mut self) { self.clear_operation_id(); self.clear_allocate_errors(); self.clear_quota_metrics(); self.clear_service_config_id(); self.unknown_fields.clear(); } } impl ::std::fmt::Debug for AllocateQuotaResponse { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { ::protobuf::text_format::fmt(self, f) } } impl ::protobuf::reflect::ProtobufValue for AllocateQuotaResponse { fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef { ::protobuf::reflect::ProtobufValueRef::Message(self) } } #[derive(PartialEq,Clone,Default)] pub struct QuotaError { // message fields pub code: QuotaError_Code, pub subject: ::std::string::String, pub description: ::std::string::String, // special fields unknown_fields: ::protobuf::UnknownFields, cached_size: ::protobuf::CachedSize, } impl QuotaError { pub fn new() -> QuotaError { ::std::default::Default::default() } // .google.api.servicecontrol.v1.QuotaError.Code code = 1; pub fn clear_code(&mut self) { self.code = QuotaError_Code::UNSPECIFIED; } // Param is passed by value, moved pub fn set_code(&mut self, v: QuotaError_Code) { self.code = v; } pub fn get_code(&self) -> QuotaError_Code { self.code } // string subject = 2; pub fn clear_subject(&mut self) { self.subject.clear(); } // Param is passed by value, moved pub fn set_subject(&mut self, v: ::std::string::String) { self.subject = v; } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_subject(&mut self) -> &mut ::std::string::String { &mut self.subject } // Take field pub fn take_subject(&mut self) -> ::std::string::String { ::std::mem::replace(&mut self.subject, ::std::string::String::new()) } pub fn get_subject(&self) -> &str { &self.subject } // string description = 3; pub fn clear_description(&mut self) { self.description.clear(); } // Param is passed by value, moved pub fn set_description(&mut self, v: ::std::string::String) { self.description = v; } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_description(&mut self) -> &mut ::std::string::String { &mut self.description } // Take field pub fn take_description(&mut self) -> ::std::string::String { ::std::mem::replace(&mut self.description, ::std::string::String::new()) } pub fn get_description(&self) -> &str { &self.description } } impl ::protobuf::Message for QuotaError { fn is_initialized(&self) -> bool { true } fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream) -> ::protobuf::ProtobufResult<()> { while !is.eof()? { let (field_number, wire_type) = is.read_tag_unpack()?; match field_number { 1 => { ::protobuf::rt::read_proto3_enum_with_unknown_fields_into(wire_type, is, &mut self.code, 1, &mut self.unknown_fields)? }, 2 => { ::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.subject)?; }, 3 => { ::protobuf::rt::read_singular_proto3_string_into(wire_type, is, &mut self.description)?; }, _ => { ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; }, }; } ::std::result::Result::Ok(()) } // Compute sizes of nested messages #[allow(unused_variables)] fn compute_size(&self) -> u32 { let mut my_size = 0; if self.code != QuotaError_Code::UNSPECIFIED { my_size += ::protobuf::rt::enum_size(1, self.code); } if !self.subject.is_empty() { my_size += ::protobuf::rt::string_size(2, &self.subject); } if !self.description.is_empty() { my_size += ::protobuf::rt::string_size(3, &self.description); } my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); self.cached_size.set(my_size); my_size } fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream) -> ::protobuf::ProtobufResult<()> { if self.code != QuotaError_Code::UNSPECIFIED { os.write_enum(1, self.code.value())?; } if !self.subject.is_empty() { os.write_string(2, &self.subject)?; } if !self.description.is_empty() { os.write_string(3, &self.description)?; } os.write_unknown_fields(self.get_unknown_fields())?; ::std::result::Result::Ok(()) } fn get_cached_size(&self) -> u32 { self.cached_size.get() } fn get_unknown_fields(&self) -> &::protobuf::UnknownFields { &self.unknown_fields } fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { &mut self.unknown_fields } fn as_any(&self) -> &::std::any::Any { self as &::std::any::Any } fn as_any_mut(&mut self) -> &mut ::std::any::Any { self as &mut ::std::any::Any } fn into_any(self: Box<Self>) -> ::std::boxed::Box<::std::any::Any> { self } fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { Self::descriptor_static() } fn new() -> QuotaError { QuotaError::new() } fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect::MessageDescriptor> = ::protobuf::lazy::Lazy { lock: ::protobuf::lazy::ONCE_INIT, ptr: 0 as *const ::protobuf::reflect::MessageDescriptor, }; unsafe { descriptor.get(|| { let mut fields = ::std::vec::Vec::new(); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeEnum<QuotaError_Code>>( "code", |m: &QuotaError| { &m.code }, |m: &mut QuotaError| { &mut m.code }, )); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( "subject", |m: &QuotaError| { &m.subject }, |m: &mut QuotaError| { &mut m.subject }, )); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( "description", |m: &QuotaError| { &m.description }, |m: &mut QuotaError| { &mut m.description }, )); ::protobuf::reflect::MessageDescriptor::new::<QuotaError>( "QuotaError", fields, file_descriptor_proto() ) }) } } fn default_instance() -> &'static QuotaError { static mut instance: ::protobuf::lazy::Lazy<QuotaError> = ::protobuf::lazy::Lazy { lock: ::protobuf::lazy::ONCE_INIT, ptr: 0 as *const QuotaError, }; unsafe { instance.get(QuotaError::new) } } } impl ::protobuf::Clear for QuotaError { fn clear(&mut self) { self.clear_code(); self.clear_subject(); self.clear_description(); self.unknown_fields.clear(); } } impl ::std::fmt::Debug for QuotaError { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { ::protobuf::text_format::fmt(self, f) } } impl ::protobuf::reflect::ProtobufValue for QuotaError { fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef { ::protobuf::reflect::ProtobufValueRef::Message(self) } } #[derive(Clone,PartialEq,Eq,Debug,Hash)] pub enum QuotaError_Code { UNSPECIFIED = 0, RESOURCE_EXHAUSTED = 8, BILLING_NOT_ACTIVE = 107, PROJECT_DELETED = 108, API_KEY_INVALID = 105, API_KEY_EXPIRED = 112, } impl ::protobuf::ProtobufEnum for QuotaError_Code { fn value(&self) -> i32 { *self as i32 } fn from_i32(value: i32) -> ::std::option::Option<QuotaError_Code> { match value { 0 => ::std::option::Option::Some(QuotaError_Code::UNSPECIFIED), 8 => ::std::option::Option::Some(QuotaError_Code::RESOURCE_EXHAUSTED), 107 => ::std::option::Option::Some(QuotaError_Code::BILLING_NOT_ACTIVE), 108 => ::std::option::Option::Some(QuotaError_Code::PROJECT_DELETED), 105 => ::std::option::Option::Some(QuotaError_Code::API_KEY_INVALID), 112 => ::std::option::Option::Some(QuotaError_Code::API_KEY_EXPIRED), _ => ::std::option::Option::None } } fn values() -> &'static [Self] { static values: &'static [QuotaError_Code] = &[ QuotaError_Code::UNSPECIFIED, QuotaError_Code::RESOURCE_EXHAUSTED, QuotaError_Code::BILLING_NOT_ACTIVE, QuotaError_Code::PROJECT_DELETED, QuotaError_Code::API_KEY_INVALID, QuotaError_Code::API_KEY_EXPIRED, ]; values } fn enum_descriptor_static() -> &'static ::protobuf::reflect::EnumDescriptor { static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect::EnumDescriptor> = ::protobuf::lazy::Lazy { lock: ::protobuf::lazy::ONCE_INIT, ptr: 0 as *const ::protobuf::reflect::EnumDescriptor, }; unsafe { descriptor.get(|| { ::protobuf::reflect::EnumDescriptor::new("QuotaError_Code", file_descriptor_proto()) }) } } } impl ::std::marker::Copy for QuotaError_Code { } impl ::std::default::Default for QuotaError_Code { fn default() -> Self { QuotaError_Code::UNSPECIFIED } } impl ::protobuf::reflect::ProtobufValue for QuotaError_Code { fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef { ::protobuf::reflect::ProtobufValueRef::Enum(self.descriptor()) } } static file_descriptor_proto_data: &'static [u8] = b"\ \n3google/api/servicecontrol/v1/quota_controller.proto\x12\x1cgoogle.api\ .servicecontrol.v1\x1a\x1cgoogle/api/annotations.proto\x1a/google/api/se\ rvicecontrol/v1/metric_value.proto\"\xc2\x01\n\x14AllocateQuotaRequest\ \x12!\n\x0cservice_name\x18\x01\x20\x01(\tR\x0bserviceName\x12[\n\x12all\ ocate_operation\x18\x02\x20\x01(\x0b2,.google.api.servicecontrol.v1.Quot\ aOperationR\x11allocateOperation\x12*\n\x11service_config_id\x18\x04\x20\ \x01(\tR\x0fserviceConfigId\"\xf7\x03\n\x0eQuotaOperation\x12!\n\x0coper\ ation_id\x18\x01\x20\x01(\tR\x0boperationId\x12\x1f\n\x0bmethod_name\x18\ \x02\x20\x01(\tR\nmethodName\x12\x1f\n\x0bconsumer_id\x18\x03\x20\x01(\t\ R\nconsumerId\x12P\n\x06labels\x18\x04\x20\x03(\x0b28.google.api.service\ control.v1.QuotaOperation.LabelsEntryR\x06labels\x12Q\n\rquota_metrics\ \x18\x05\x20\x03(\x0b2,.google.api.servicecontrol.v1.MetricValueSetR\x0c\ quotaMetrics\x12U\n\nquota_mode\x18\x06\x20\x01(\x0e26.google.api.servic\ econtrol.v1.QuotaOperation.QuotaModeR\tquotaMode\x1a9\n\x0bLabelsEntry\ \x12\x10\n\x03key\x18\x01\x20\x01(\tR\x03key\x12\x14\n\x05value\x18\x02\ \x20\x01(\tR\x05value:\x028\x01\"I\n\tQuotaMode\x12\x0f\n\x0bUNSPECIFIED\ \x10\0\x12\n\n\x06NORMAL\x10\x01\x12\x0f\n\x0bBEST_EFFORT\x10\x02\x12\ \x0e\n\nCHECK_ONLY\x10\x03\"\x8c\x02\n\x15AllocateQuotaResponse\x12!\n\ \x0coperation_id\x18\x01\x20\x01(\tR\x0boperationId\x12Q\n\x0fallocate_e\ rrors\x18\x02\x20\x03(\x0b2(.google.api.servicecontrol.v1.QuotaErrorR\ \x0eallocateErrors\x12Q\n\rquota_metrics\x18\x03\x20\x03(\x0b2,.google.a\ pi.servicecontrol.v1.MetricValueSetR\x0cquotaMetrics\x12*\n\x11service_c\ onfig_id\x18\x04\x20\x01(\tR\x0fserviceConfigId\"\x94\x02\n\nQuotaError\ \x12A\n\x04code\x18\x01\x20\x01(\x0e2-.google.api.servicecontrol.v1.Quot\ aError.CodeR\x04code\x12\x18\n\x07subject\x18\x02\x20\x01(\tR\x07subject\ \x12\x20\n\x0bdescription\x18\x03\x20\x01(\tR\x0bdescription\"\x86\x01\n\ \x04Code\x12\x0f\n\x0bUNSPECIFIED\x10\0\x12\x16\n\x12RESOURCE_EXHAUSTED\ \x10\x08\x12\x16\n\x12BILLING_NOT_ACTIVE\x10k\x12\x13\n\x0fPROJECT_DELET\ ED\x10l\x12\x13\n\x0fAPI_KEY_INVALID\x10i\x12\x13\n\x0fAPI_KEY_EXPIRED\ \x10p2\xc2\x01\n\x0fQuotaController\x12\xae\x01\n\rAllocateQuota\x122.go\ ogle.api.servicecontrol.v1.AllocateQuotaRequest\x1a3.google.api.servicec\ ontrol.v1.AllocateQuotaResponse\"4\x82\xd3\xe4\x93\x02.\")/v1/services/{\ service_name}:allocateQuota:\x01*B\x89\x01\n\x20com.google.api.serviceco\ ntrol.v1B\x14QuotaControllerProtoP\x01ZJgoogle.golang.org/genproto/googl\ eapis/api/servicecontrol/v1;servicecontrol\xf8\x01\x01J\xb9B\n\x07\x12\ \x05\x0e\0\xc9\x01\x01\n\xbd\x04\n\x01\x0c\x12\x03\x0e\0\x122\xb2\x04\ \x20Copyright\x202017\x20Google\x20Inc.\n\n\x20Licensed\x20under\x20the\ \x20Apache\x20License,\x20Version\x202.0\x20(the\x20\"License\");\n\x20y\ ou\x20may\x20not\x20use\x20this\x20file\x20except\x20in\x20compliance\ \x20with\x20the\x20License.\n\x20You\x20may\x20obtain\x20a\x20copy\x20of\ \x20the\x20License\x20at\n\n\x20\x20\x20\x20\x20http://www.apache.org/li\ censes/LICENSE-2.0\n\n\x20Unless\x20required\x20by\x20applicable\x20law\ \x20or\x20agreed\x20to\x20in\x20writing,\x20software\n\x20distributed\ \x20under\x20the\x20License\x20is\x20distributed\x20on\x20an\x20\"AS\x20\ IS\"\x20BASIS,\n\x20WITHOUT\x20WARRANTIES\x20OR\x20CONDITIONS\x20OF\x20A\ NY\x20KIND,\x20either\x20express\x20or\x20implied.\n\x20See\x20the\x20Li\ cense\x20for\x20the\x20specific\x20language\x20governing\x20permissions\ \x20and\n\x20limitations\x20under\x20the\x20License.\n\n\x08\n\x01\x02\ \x12\x03\x10\x08$\n\t\n\x02\x03\0\x12\x03\x12\x07%\n\t\n\x02\x03\x01\x12\ \x03\x13\x078\n\x08\n\x01\x08\x12\x03\x15\0\x1f\n\x0b\n\x04\x08\xe7\x07\ \0\x12\x03\x15\0\x1f\n\x0c\n\x05\x08\xe7\x07\0\x02\x12\x03\x15\x07\x17\n\ \r\n\x06\x08\xe7\x07\0\x02\0\x12\x03\x15\x07\x17\n\x0e\n\x07\x08\xe7\x07\ \0\x02\0\x01\x12\x03\x15\x07\x17\n\x0c\n\x05\x08\xe7\x07\0\x03\x12\x03\ \x15\x1a\x1e\n\x08\n\x01\x08\x12\x03\x16\0a\n\x0b\n\x04\x08\xe7\x07\x01\ \x12\x03\x16\0a\n\x0c\n\x05\x08\xe7\x07\x01\x02\x12\x03\x16\x07\x11\n\r\ \n\x06\x08\xe7\x07\x01\x02\0\x12\x03\x16\x07\x11\n\x0e\n\x07\x08\xe7\x07\ \x01\x02\0\x01\x12\x03\x16\x07\x11\n\x0c\n\x05\x08\xe7\x07\x01\x07\x12\ \x03\x16\x14`\n\x08\n\x01\x08\x12\x03\x17\0\"\n\x0b\n\x04\x08\xe7\x07\ \x02\x12\x03\x17\0\"\n\x0c\n\x05\x08\xe7\x07\x02\x02\x12\x03\x17\x07\x1a\ \n\r\n\x06\x08\xe7\x07\x02\x02\0\x12\x03\x17\x07\x1a\n\x0e\n\x07\x08\xe7\ \x07\x02\x02\0\x01\x12\x03\x17\x07\x1a\n\x0c\n\x05\x08\xe7\x07\x02\x03\ \x12\x03\x17\x1d!\n\x08\n\x01\x08\x12\x03\x18\05\n\x0b\n\x04\x08\xe7\x07\ \x03\x12\x03\x18\05\n\x0c\n\x05\x08\xe7\x07\x03\x02\x12\x03\x18\x07\x1b\ \n\r\n\x06\x08\xe7\x07\x03\x02\0\x12\x03\x18\x07\x1b\n\x0e\n\x07\x08\xe7\ \x07\x03\x02\0\x01\x12\x03\x18\x07\x1b\n\x0c\n\x05\x08\xe7\x07\x03\x07\ \x12\x03\x18\x1e4\n\x08\n\x01\x08\x12\x03\x19\09\n\x0b\n\x04\x08\xe7\x07\ \x04\x12\x03\x19\09\n\x0c\n\x05\x08\xe7\x07\x04\x02\x12\x03\x19\x07\x13\ \n\r\n\x06\x08\xe7\x07\x04\x02\0\x12\x03\x19\x07\x13\n\x0e\n\x07\x08\xe7\ \x07\x04\x02\0\x01\x12\x03\x19\x07\x13\n\x0c\n\x05\x08\xe7\x07\x04\x07\ \x12\x03\x19\x168\n\x9b\x02\n\x02\x06\0\x12\x04\x20\0/\x01\x1a\x8e\x02\ \x20[Google\x20Quota\x20Control\x20API](/service-control/overview)\n\n\ \x20Allows\x20clients\x20to\x20allocate\x20and\x20release\x20quota\x20ag\ ainst\x20a\x20[managed\n\x20service](https://cloud.google.com/service-ma\ nagement/reference/rpc/google.api/servicemanagement.v1#google.api.servic\ emanagement.v1.ManagedService).\n\n\n\n\x03\x06\0\x01\x12\x03\x20\x08\ \x17\n\xa2\x04\n\x04\x06\0\x02\0\x12\x04,\x02.\x03\x1a\x93\x04\x20Attemp\ ts\x20to\x20allocate\x20quota\x20for\x20the\x20specified\x20consumer.\ \x20It\x20should\x20be\x20called\n\x20before\x20the\x20operation\x20is\ \x20executed.\n\n\x20This\x20method\x20requires\x20the\x20`servicemanage\ ment.services.quota`\n\x20permission\x20on\x20the\x20specified\x20servic\ e.\x20For\x20more\x20information,\x20see\n\x20[Cloud\x20IAM](https://clo\ ud.google.com/iam).\n\n\x20**NOTE:**\x20The\x20client\x20**must**\x20fai\ l-open\x20on\x20server\x20errors\x20`INTERNAL`,\n\x20`UNKNOWN`,\x20`DEAD\ LINE_EXCEEDED`,\x20and\x20`UNAVAILABLE`.\x20To\x20ensure\x20system\n\x20\ reliability,\x20the\x20server\x20may\x20inject\x20these\x20errors\x20to\ \x20prohibit\x20any\x20hard\n\x20dependency\x20on\x20the\x20quota\x20fun\ ctionality.\n\n\x0c\n\x05\x06\0\x02\0\x01\x12\x03,\x06\x13\n\x0c\n\x05\ \x06\0\x02\0\x02\x12\x03,\x14(\n\x0c\n\x05\x06\0\x02\0\x03\x12\x03,3H\n\ \x0c\n\x05\x06\0\x02\0\x04\x12\x03-\x04_\n\x0f\n\x08\x06\0\x02\0\x04\xe7\ \x07\0\x12\x03-\x04_\n\x10\n\t\x06\0\x02\0\x04\xe7\x07\0\x02\x12\x03-\ \x0b\x1c\n\x11\n\n\x06\0\x02\0\x04\xe7\x07\0\x02\0\x12\x03-\x0b\x1c\n\ \x12\n\x0b\x06\0\x02\0\x04\xe7\x07\0\x02\0\x01\x12\x03-\x0c\x1b\n\x10\n\ \t\x06\0\x02\0\x04\xe7\x07\0\x08\x12\x03-\x1f^\n;\n\x02\x04\0\x12\x042\0\ @\x01\x1a/\x20Request\x20message\x20for\x20the\x20AllocateQuota\x20metho\ d.\n\n\n\n\x03\x04\0\x01\x12\x032\x08\x1c\n\xcc\x01\n\x04\x04\0\x02\0\ \x12\x037\x02\x1a\x1a\xbe\x01\x20Name\x20of\x20the\x20service\x20as\x20s\ pecified\x20in\x20the\x20service\x20configuration.\x20For\x20example,\n\ \x20`\"pubsub.googleapis.com\"`.\n\n\x20See\x20[google.api.Service][goog\ le.api.Service]\x20for\x20the\x20definition\x20of\x20a\x20service\x20nam\ e.\n\n\r\n\x05\x04\0\x02\0\x04\x12\x047\x022\x1e\n\x0c\n\x05\x04\0\x02\0\ \x05\x12\x037\x02\x08\n\x0c\n\x05\x04\0\x02\0\x01\x12\x037\t\x15\n\x0c\n\ \x05\x04\0\x02\0\x03\x12\x037\x18\x19\n=\n\x04\x04\0\x02\x01\x12\x03:\ \x02(\x1a0\x20Operation\x20that\x20describes\x20the\x20quota\x20allocati\ on.\n\n\r\n\x05\x04\0\x02\x01\x04\x12\x04:\x027\x1a\n\x0c\n\x05\x04\0\ \x02\x01\x06\x12\x03:\x02\x10\n\x0c\n\x05\x04\0\x02\x01\x01\x12\x03:\x11\ #\n\x0c\n\x05\x04\0\x02\x01\x03\x12\x03:&'\n\xba\x01\n\x04\x04\0\x02\x02\ \x12\x03?\x02\x1f\x1a\xac\x01\x20Specifies\x20which\x20version\x20of\x20\ service\x20configuration\x20should\x20be\x20used\x20to\x20process\n\x20t\ he\x20request.\x20If\x20unspecified\x20or\x20no\x20matching\x20version\ \x20can\x20be\x20found,\x20the\x20latest\n\x20one\x20will\x20be\x20used.\ \n\n\r\n\x05\x04\0\x02\x02\x04\x12\x04?\x02:(\n\x0c\n\x05\x04\0\x02\x02\ \x05\x12\x03?\x02\x08\n\x0c\n\x05\x04\0\x02\x02\x01\x12\x03?\t\x1a\n\x0c\ \n\x05\x04\0\x02\x02\x03\x12\x03?\x1d\x1e\nB\n\x02\x04\x01\x12\x05C\0\ \x87\x01\x01\x1a5\x20Represents\x20information\x20regarding\x20a\x20quot\ a\x20operation.\n\n\n\n\x03\x04\x01\x01\x12\x03C\x08\x16\n&\n\x04\x04\ \x01\x04\0\x12\x04E\x02Y\x03\x1a\x18\x20Supported\x20quota\x20modes.\n\n\ \x0c\n\x05\x04\x01\x04\0\x01\x12\x03E\x07\x10\nB\n\x06\x04\x01\x04\0\x02\ \0\x12\x03G\x04\x14\x1a3\x20Guard\x20against\x20implicit\x20default.\x20\ Must\x20not\x20be\x20used.\n\n\x0e\n\x07\x04\x01\x04\0\x02\0\x01\x12\x03\ G\x04\x0f\n\x0e\n\x07\x04\x01\x04\0\x02\0\x02\x12\x03G\x12\x13\n\x8f\x02\ \n\x06\x04\x01\x04\0\x02\x01\x12\x03M\x04\x0f\x1a\xff\x01\x20For\x20Allo\ cateQuota\x20request,\x20allocates\x20quota\x20for\x20the\x20amount\x20s\ pecified\x20in\n\x20the\x20service\x20configuration\x20or\x20specified\ \x20using\x20the\x20quota\x20metrics.\x20If\x20the\n\x20amount\x20is\x20\ higher\x20than\x20the\x20available\x20quota,\x20allocation\x20error\x20w\ ill\x20be\n\x20returned\x20and\x20no\x20quota\x20will\x20be\x20allocated\ .\n\n\x0e\n\x07\x04\x01\x04\0\x02\x01\x01\x12\x03M\x04\n\n\x0e\n\x07\x04\ \x01\x04\0\x02\x01\x02\x12\x03M\r\x0e\n\x81\x02\n\x06\x04\x01\x04\0\x02\ \x02\x12\x03S\x04\x14\x1a\xf1\x01\x20The\x20operation\x20allocates\x20qu\ ota\x20for\x20the\x20amount\x20specified\x20in\x20the\x20service\n\x20co\ nfiguration\x20or\x20specified\x20using\x20the\x20quota\x20metrics.\x20I\ f\x20the\x20amount\x20is\n\x20higher\x20than\x20the\x20available\x20quot\ a,\x20request\x20does\x20not\x20fail\x20but\x20all\x20available\n\x20quo\ ta\x20will\x20be\x20allocated.\n\n\x0e\n\x07\x04\x01\x04\0\x02\x02\x01\ \x12\x03S\x04\x0f\n\x0e\n\x07\x04\x01\x04\0\x02\x02\x02\x12\x03S\x12\x13\ \n\xb7\x01\n\x06\x04\x01\x04\0\x02\x03\x12\x03X\x04\x13\x1a\xa7\x01\x20F\ or\x20AllocateQuota\x20request,\x20only\x20checks\x20if\x20there\x20is\ \x20enough\x20quota\n\x20available\x20and\x20does\x20not\x20change\x20th\ e\x20available\x20quota.\x20No\x20lock\x20is\x20placed\x20on\n\x20the\ \x20available\x20quota\x20either.\n\n\x0e\n\x07\x04\x01\x04\0\x02\x03\ \x01\x12\x03X\x04\x0e\n\x0e\n\x07\x04\x01\x04\0\x02\x03\x02\x12\x03X\x11\ \x12\n\xac\x03\n\x04\x04\x01\x02\0\x12\x03c\x02\x1a\x1a\x9e\x03\x20Ident\ ity\x20of\x20the\x20operation.\x20This\x20is\x20expected\x20to\x20be\x20\ unique\x20within\x20the\x20scope\n\x20of\x20the\x20service\x20that\x20ge\ nerated\x20the\x20operation,\x20and\x20guarantees\x20idempotency\x20in\n\ \x20case\x20of\x20retries.\n\n\x20UUID\x20version\x204\x20is\x20recommen\ ded,\x20though\x20not\x20required.\x20In\x20scenarios\x20where\x20an\n\ \x20operation\x20is\x20computed\x20from\x20existing\x20information\x20an\ d\x20an\x20idempotent\x20id\x20is\n\x20desirable\x20for\x20deduplication\ \x20purpose,\x20UUID\x20version\x205\x20is\x20recommended.\x20See\n\x20R\ FC\x204122\x20for\x20details.\n\n\r\n\x05\x04\x01\x02\0\x04\x12\x04c\x02\ Y\x03\n\x0c\n\x05\x04\x01\x02\0\x05\x12\x03c\x02\x08\n\x0c\n\x05\x04\x01\ \x02\0\x01\x12\x03c\t\x15\n\x0c\n\x05\x04\x01\x02\0\x03\x12\x03c\x18\x19\ \n\x8c\x03\n\x04\x04\x01\x02\x01\x12\x03l\x02\x19\x1a\xfe\x02\x20Fully\ \x20qualified\x20name\x20of\x20the\x20API\x20method\x20for\x20which\x20t\ his\x20quota\x20operation\x20is\n\x20requested.\x20This\x20name\x20is\ \x20used\x20for\x20matching\x20quota\x20rules\x20or\x20metric\x20rules\ \x20and\n\x20billing\x20status\x20rules\x20defined\x20in\x20service\x20c\ onfiguration.\x20This\x20field\x20is\x20not\n\x20required\x20if\x20the\ \x20quota\x20operation\x20is\x20performed\x20on\x20non-API\x20resources.\ \n\n\x20Example\x20of\x20an\x20RPC\x20method\x20name:\n\x20\x20\x20\x20\ \x20google.example.library.v1.LibraryService.CreateShelf\n\n\r\n\x05\x04\ \x01\x02\x01\x04\x12\x04l\x02c\x1a\n\x0c\n\x05\x04\x01\x02\x01\x05\x12\ \x03l\x02\x08\n\x0c\n\x05\x04\x01\x02\x01\x01\x12\x03l\t\x14\n\x0c\n\x05\ \x04\x01\x02\x01\x03\x12\x03l\x17\x18\n\xdc\x01\n\x04\x04\x01\x02\x02\ \x12\x03t\x02\x19\x1a\xce\x01\x20Identity\x20of\x20the\x20consumer\x20fo\ r\x20whom\x20this\x20quota\x20operation\x20is\x20being\x20performed.\n\n\ \x20This\x20can\x20be\x20in\x20one\x20of\x20the\x20following\x20formats:\ \n\x20\x20\x20project:<project_id>,\n\x20\x20\x20project_number:<project\ _number>,\n\x20\x20\x20api_key:<api_key>.\n\n\r\n\x05\x04\x01\x02\x02\ \x04\x12\x04t\x02l\x19\n\x0c\n\x05\x04\x01\x02\x02\x05\x12\x03t\x02\x08\ \n\x0c\n\x05\x04\x01\x02\x02\x01\x12\x03t\t\x14\n\x0c\n\x05\x04\x01\x02\ \x02\x03\x12\x03t\x17\x18\n/\n\x04\x04\x01\x02\x03\x12\x03w\x02!\x1a\"\ \x20Labels\x20describing\x20the\x20operation.\n\n\r\n\x05\x04\x01\x02\ \x03\x04\x12\x04w\x02t\x19\n\x0c\n\x05\x04\x01\x02\x03\x06\x12\x03w\x02\ \x15\n\x0c\n\x05\x04\x01\x02\x03\x01\x12\x03w\x16\x1c\n\x0c\n\x05\x04\ \x01\x02\x03\x03\x12\x03w\x1f\x20\n\x9b\x04\n\x04\x04\x01\x02\x04\x12\ \x04\x83\x01\x02,\x1a\x8c\x04\x20Represents\x20information\x20about\x20t\ his\x20operation.\x20Each\x20MetricValueSet\n\x20corresponds\x20to\x20a\ \x20metric\x20defined\x20in\x20the\x20service\x20configuration.\n\x20The\ \x20data\x20type\x20used\x20in\x20the\x20MetricValueSet\x20must\x20agree\ \x20with\n\x20the\x20data\x20type\x20specified\x20in\x20the\x20metric\ \x20definition.\n\n\x20Within\x20a\x20single\x20operation,\x20it\x20is\ \x20not\x20allowed\x20to\x20have\x20more\x20than\x20one\n\x20MetricValue\ \x20instances\x20that\x20have\x20the\x20same\x20metric\x20names\x20and\ \x20identical\n\x20label\x20value\x20combinations.\x20If\x20a\x20request\ \x20has\x20such\x20duplicated\x20MetricValue\n\x20instances,\x20the\x20e\ ntire\x20request\x20is\x20rejected\x20with\n\x20an\x20invalid\x20argumen\ t\x20error.\n\n\r\n\x05\x04\x01\x02\x04\x04\x12\x04\x83\x01\x02\n\n\r\n\ \x05\x04\x01\x02\x04\x06\x12\x04\x83\x01\x0b\x19\n\r\n\x05\x04\x01\x02\ \x04\x01\x12\x04\x83\x01\x1a'\n\r\n\x05\x04\x01\x02\x04\x03\x12\x04\x83\ \x01*+\n.\n\x04\x04\x01\x02\x05\x12\x04\x86\x01\x02\x1b\x1a\x20\x20Quota\ \x20mode\x20for\x20this\x20operation.\n\n\x0f\n\x05\x04\x01\x02\x05\x04\ \x12\x06\x86\x01\x02\x83\x01,\n\r\n\x05\x04\x01\x02\x05\x06\x12\x04\x86\ \x01\x02\x0b\n\r\n\x05\x04\x01\x02\x05\x01\x12\x04\x86\x01\x0c\x16\n\r\n\ \x05\x04\x01\x02\x05\x03\x12\x04\x86\x01\x19\x1a\n>\n\x02\x04\x02\x12\ \x06\x8a\x01\0\xa0\x01\x01\x1a0\x20Response\x20message\x20for\x20the\x20\ AllocateQuota\x20method.\n\n\x0b\n\x03\x04\x02\x01\x12\x04\x8a\x01\x08\ \x1d\ny\n\x04\x04\x02\x02\0\x12\x04\x8d\x01\x02\x1a\x1ak\x20The\x20same\ \x20operation_id\x20value\x20used\x20in\x20the\x20AllocateQuotaRequest.\ \x20Used\x20for\n\x20logging\x20and\x20diagnostics\x20purposes.\n\n\x0f\ \n\x05\x04\x02\x02\0\x04\x12\x06\x8d\x01\x02\x8a\x01\x1f\n\r\n\x05\x04\ \x02\x02\0\x05\x12\x04\x8d\x01\x02\x08\n\r\n\x05\x04\x02\x02\0\x01\x12\ \x04\x8d\x01\t\x15\n\r\n\x05\x04\x02\x02\0\x03\x12\x04\x8d\x01\x18\x19\n\ 7\n\x04\x04\x02\x02\x01\x12\x04\x90\x01\x02*\x1a)\x20Indicates\x20the\ \x20decision\x20of\x20the\x20allocate.\n\n\r\n\x05\x04\x02\x02\x01\x04\ \x12\x04\x90\x01\x02\n\n\r\n\x05\x04\x02\x02\x01\x06\x12\x04\x90\x01\x0b\ \x15\n\r\n\x05\x04\x02\x02\x01\x01\x12\x04\x90\x01\x16%\n\r\n\x05\x04\ \x02\x02\x01\x03\x12\x04\x90\x01()\n\xd9\x03\n\x04\x04\x02\x02\x02\x12\ \x04\x9c\x01\x02,\x1a\xca\x03\x20Quota\x20metrics\x20to\x20indicate\x20t\ he\x20result\x20of\x20allocation.\x20Depending\x20on\x20the\n\x20request\ ,\x20one\x20or\x20more\x20of\x20the\x20following\x20metrics\x20will\x20b\ e\x20included:\n\n\x201.\x20Per\x20quota\x20group\x20or\x20per\x20quota\ \x20metric\x20incremental\x20usage\x20will\x20be\x20specified\n\x20using\ \x20the\x20following\x20delta\x20metric\x20:\n\x20\x20\x20\"servicerunti\ me.googleapis.com/api/consumer/quota_used_count\"\n\n\x202.\x20The\x20qu\ ota\x20limit\x20reached\x20condition\x20will\x20be\x20specified\x20using\ \x20the\x20following\n\x20boolean\x20metric\x20:\n\x20\x20\x20\"servicer\ untime.googleapis.com/quota/exceeded\"\n\n\r\n\x05\x04\x02\x02\x02\x04\ \x12\x04\x9c\x01\x02\n\n\r\n\x05\x04\x02\x02\x02\x06\x12\x04\x9c\x01\x0b\ \x19\n\r\n\x05\x04\x02\x02\x02\x01\x12\x04\x9c\x01\x1a'\n\r\n\x05\x04\ \x02\x02\x02\x03\x12\x04\x9c\x01*+\nD\n\x04\x04\x02\x02\x03\x12\x04\x9f\ \x01\x02\x1f\x1a6\x20ID\x20of\x20the\x20actual\x20config\x20used\x20to\ \x20process\x20the\x20request.\n\n\x0f\n\x05\x04\x02\x02\x03\x04\x12\x06\ \x9f\x01\x02\x9c\x01,\n\r\n\x05\x04\x02\x02\x03\x05\x12\x04\x9f\x01\x02\ \x08\n\r\n\x05\x04\x02\x02\x03\x01\x12\x04\x9f\x01\t\x1a\n\r\n\x05\x04\ \x02\x02\x03\x03\x12\x04\x9f\x01\x1d\x1e\no\n\x02\x04\x03\x12\x06\xa3\ \x01\0\xc9\x01\x01\x1aa\x20Represents\x20error\x20information\x20for\x20\ [QuotaOperation][google.api.servicecontrol.v1.QuotaOperation].\n\n\x0b\n\ \x03\x04\x03\x01\x12\x04\xa3\x01\x08\x12\n\xfe\x02\n\x04\x04\x03\x04\0\ \x12\x06\xa9\x01\x02\xbd\x01\x03\x1a\xed\x02\x20Error\x20codes\x20relate\ d\x20to\x20project\x20config\x20validations\x20are\x20deprecated\x20sinc\ e\x20the\n\x20quota\x20controller\x20methods\x20do\x20not\x20perform\x20\ these\x20validations.\x20Instead\x20services\n\x20have\x20to\x20call\x20\ the\x20Check\x20method,\x20without\x20quota_properties\x20field,\x20to\ \x20perform\n\x20these\x20validations\x20before\x20calling\x20the\x20quo\ ta\x20controller\x20methods.\x20These\n\x20methods\x20check\x20only\x20f\ or\x20project\x20deletion\x20to\x20be\x20wipe\x20out\x20compliant.\n\n\r\ \n\x05\x04\x03\x04\0\x01\x12\x04\xa9\x01\x07\x0b\n%\n\x06\x04\x03\x04\0\ \x02\0\x12\x04\xab\x01\x04\x14\x1a\x15\x20This\x20is\x20never\x20used.\n\ \n\x0f\n\x07\x04\x03\x04\0\x02\0\x01\x12\x04\xab\x01\x04\x0f\n\x0f\n\x07\ \x04\x03\x04\0\x02\0\x02\x12\x04\xab\x01\x12\x13\n[\n\x06\x04\x03\x04\0\ \x02\x01\x12\x04\xaf\x01\x04\x1b\x1aK\x20Quota\x20allocation\x20failed.\ \n\x20Same\x20as\x20[google.rpc.Code.RESOURCE_EXHAUSTED][].\n\n\x0f\n\ \x07\x04\x03\x04\0\x02\x01\x01\x12\x04\xaf\x01\x04\x16\n\x0f\n\x07\x04\ \x03\x04\0\x02\x01\x02\x12\x04\xaf\x01\x19\x1a\nb\n\x06\x04\x03\x04\0\ \x02\x02\x12\x04\xb3\x01\x04\x1d\x1aR\x20Consumer\x20cannot\x20access\ \x20the\x20service\x20because\x20the\x20service\x20requires\x20active\n\ \x20billing.\n\n\x0f\n\x07\x04\x03\x04\0\x02\x02\x01\x12\x04\xb3\x01\x04\ \x16\n\x0f\n\x07\x04\x03\x04\0\x02\x02\x02\x12\x04\xb3\x01\x19\x1c\nP\n\ \x06\x04\x03\x04\0\x02\x03\x12\x04\xb6\x01\x04\x1a\x1a@\x20Consumer's\ \x20project\x20has\x20been\x20marked\x20as\x20deleted\x20(soft\x20deleti\ on).\n\n\x0f\n\x07\x04\x03\x04\0\x02\x03\x01\x12\x04\xb6\x01\x04\x13\n\ \x0f\n\x07\x04\x03\x04\0\x02\x03\x02\x12\x04\xb6\x01\x16\x19\n/\n\x06\ \x04\x03\x04\0\x02\x04\x12\x04\xb9\x01\x04\x1a\x1a\x1f\x20Specified\x20A\ PI\x20key\x20is\x20invalid.\n\n\x0f\n\x07\x04\x03\x04\0\x02\x04\x01\x12\ \x04\xb9\x01\x04\x13\n\x0f\n\x07\x04\x03\x04\0\x02\x04\x02\x12\x04\xb9\ \x01\x16\x19\n0\n\x06\x04\x03\x04\0\x02\x05\x12\x04\xbc\x01\x04\x1a\x1a\ \x20\x20Specified\x20API\x20Key\x20has\x20expired.\n\n\x0f\n\x07\x04\x03\ \x04\0\x02\x05\x01\x12\x04\xbc\x01\x04\x13\n\x0f\n\x07\x04\x03\x04\0\x02\ \x05\x02\x12\x04\xbc\x01\x16\x19\n\x1b\n\x04\x04\x03\x02\0\x12\x04\xc0\ \x01\x02\x10\x1a\r\x20Error\x20code.\n\n\x0f\n\x05\x04\x03\x02\0\x04\x12\ \x06\xc0\x01\x02\xbd\x01\x03\n\r\n\x05\x04\x03\x02\0\x06\x12\x04\xc0\x01\ \x02\x06\n\r\n\x05\x04\x03\x02\0\x01\x12\x04\xc0\x01\x07\x0b\n\r\n\x05\ \x04\x03\x02\0\x03\x12\x04\xc0\x01\x0e\x0f\n\xc7\x01\n\x04\x04\x03\x02\ \x01\x12\x04\xc5\x01\x02\x15\x1a\xb8\x01\x20Subject\x20to\x20whom\x20thi\ s\x20error\x20applies.\x20See\x20the\x20specific\x20enum\x20for\x20more\ \x20details\n\x20on\x20this\x20field.\x20For\x20example,\x20\"clientip:<\ ip\x20address\x20of\x20client>\"\x20or\n\x20\"project:<Google\x20develop\ er\x20project\x20id>\".\n\n\x0f\n\x05\x04\x03\x02\x01\x04\x12\x06\xc5\ \x01\x02\xc0\x01\x10\n\r\n\x05\x04\x03\x02\x01\x05\x12\x04\xc5\x01\x02\ \x08\n\r\n\x05\x04\x03\x02\x01\x01\x12\x04\xc5\x01\t\x10\n\r\n\x05\x04\ \x03\x02\x01\x03\x12\x04\xc5\x01\x13\x14\nO\n\x04\x04\x03\x02\x02\x12\ \x04\xc8\x01\x02\x19\x1aA\x20Free-form\x20text\x20that\x20provides\x20de\ tails\x20on\x20the\x20cause\x20of\x20the\x20error.\n\n\x0f\n\x05\x04\x03\ \x02\x02\x04\x12\x06\xc8\x01\x02\xc5\x01\x15\n\r\n\x05\x04\x03\x02\x02\ \x05\x12\x04\xc8\x01\x02\x08\n\r\n\x05\x04\x03\x02\x02\x01\x12\x04\xc8\ \x01\t\x14\n\r\n\x05\x04\x03\x02\x02\x03\x12\x04\xc8\x01\x17\x18b\x06pro\ to3\ "; static mut file_descriptor_proto_lazy: ::protobuf::lazy::Lazy<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::lazy::Lazy { lock: ::protobuf::lazy::ONCE_INIT, ptr: 0 as *const ::protobuf::descriptor::FileDescriptorProto, }; fn parse_descriptor_proto() -> ::protobuf::descriptor::FileDescriptorProto { ::protobuf::parse_from_bytes(file_descriptor_proto_data).unwrap() } pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto { unsafe { file_descriptor_proto_lazy.get(|| { parse_descriptor_proto() }) } }
42.247678
170
0.633856
dcc45df5c65917829f66e0dec774cef347c55930
8,156
swift
Swift
hugoPay/hugoPayFull/Controller/CreateAccessPin/CreatePinHPFullViewController.swift
jonathan220297/hugoPay_test
ac54e01b38fab3e1167f012db6175938f44179b6
[ "MIT" ]
null
null
null
hugoPay/hugoPayFull/Controller/CreateAccessPin/CreatePinHPFullViewController.swift
jonathan220297/hugoPay_test
ac54e01b38fab3e1167f012db6175938f44179b6
[ "MIT" ]
null
null
null
hugoPay/hugoPayFull/Controller/CreateAccessPin/CreatePinHPFullViewController.swift
jonathan220297/hugoPay_test
ac54e01b38fab3e1167f012db6175938f44179b6
[ "MIT" ]
null
null
null
// // CreatePinHPFullViewController.swift // Hugo // // Created by Jose Francisco Rosales Hernandez on 29/01/21. // Copyright © 2021 Clever Mobile Apps. All rights reserved. // import UIKit import RxRelay import RxSwift class CreatePinHPFullViewController: UIViewController { // Main Delegate weak var delegate: MainHPFullViewControllerDelegate? // TabBar controller var hugoTabController: UITabBarController? @IBOutlet weak var titleLbl: UILabel! @IBOutlet weak var subTitleLbl: UILabel! @IBOutlet weak var pinView: PinInputView! @IBOutlet weak var validateBtn: UIButton! @IBOutlet weak var incorrectPinView: UIView! @IBOutlet weak var warningLbl: UILabel! var isVerification = false var firstPin : String? var secondPin : String? var fromMain = false private let disposeBag = DisposeBag() lazy var viewModel: CreatePinHPFullViewModel = { return CreatePinHPFullViewModel() }() override func viewDidLoad() { super.viewDidLoad() configurePin() configViewModel() initView() validateBtn.makeHugoButton(title: "ACEPTAR") let dismissTap = UITapGestureRecognizer(target: self, action: #selector(didTapOnDismissKeyboardAction(_:))) dismissTap.numberOfTapsRequired = 1 dismissTap.numberOfTouchesRequired = 1 self.view.addGestureRecognizer(dismissTap) self.pinView.viewBecomeFirstResponder() } @objc func didTapOnDismissKeyboardAction(_ sender: UITapGestureRecognizer) { self.view.endEditing(true) } func configViewModel(){ viewModel.hideLoading = { [weak self] () in self?.hideLoading() } viewModel.showLoading = { [weak self] () in self?.showLoading() } } func configurePin(){ self.pinView.delegate = self self.pinView.textColor = UIColor.black self.pinView.bottomBorderColor = UIColor.black self.pinView.keyboardType = UIKeyboardType.numberPad self.pinView.nextDigitBottomBorderColor = UIColor(hexString: "979797")! pinView.hideWarning = hideWarning } func hideWarning(){ incorrectPinView.isHidden = true } @IBAction func validatePin(_ sender: Any) { if isVerification{ if self.pinView.text.count == 4, let first = firstPin { secondPin = pinView.text if secondPin == first { doRegistration(pin: first) } else { showWarning() } } else { showWarningBadPin() } } else { if self.pinView.text.count == 4 { firstPin = self.pinView.text isVerification = true initView() } else { showWarningBadPin() } } } func initView(){ pinView.cleanLabels() incorrectPinView.isHidden = true if isVerification { self.pinView.viewBecomeFirstResponder() titleLbl.text = "Ingresa nuevamente tu PIN".localizedString subTitleLbl.text = "Confirmar PIN" } else { titleLbl.text = "¡Protejamos tu cuenta!".localizedString subTitleLbl.text = "Ingresa un PIN de 4 dígitos.".localizedString } } private func validateInputCode() { let text = self.pinView.text if text.count < 4 { return } self.dismissKeyboard() } func showWarning(){ let attributedString = NSMutableAttributedString(string: "¡Oops! El PIN ingresado es incorrecto.\nAmbos PIN’s deben ser iguales.\nIntenta de nuevo", attributes: [ .font: UIFont(name: "GothamHTF-Book", size: 13.0)!, .foregroundColor: UIColor(red: 128.0 / 255.0, green: 107.0 / 255.0, blue: 185.0 / 255.0, alpha: 1.0) ]) attributedString.addAttribute(.font, value: UIFont(name: "GothamHTF-Bold", size: 13.0)!, range: NSRange(location: 70, length: 16)) warningLbl.attributedText = attributedString incorrectPinView.isHidden = false } func showWarningBadPin(){ let attributedString = NSMutableAttributedString(string: "Ingresa un PIN válido de 4 digitos", attributes: [ .font: UIFont(name: "GothamHTF-Book", size: 13.0)!, .foregroundColor: UIColor(red: 128.0 / 255.0, green: 107.0 / 255.0, blue: 185.0 / 255.0, alpha: 1.0) ]) warningLbl.attributedText = attributedString incorrectPinView.isHidden = false } func doRegistration(pin : String){ showLoading() viewModel.registerPin(pin).asObservable() .subscribe(onNext: {[weak self] (providersdata) in guard let providersdata = providersdata else { return } DispatchQueue.main.async { self?.hideLoading() if let success = providersdata.success, success { if self?.fromMain ?? false { self?.dismiss(animated: true, completion: nil) } else { self?.goToPinSuccess() } } else { if let msg = providersdata.message { showErrorCustom("Error", msg) } else { showGeneralErrorCustom(ErrorCodes.HugoPay.Login.RegisterPinFail) } } } }) .disposed(by: disposeBag) } func goToHugoPay(){ self.dismiss(animated: true) { self.delegate?.dismiss() } } func goToPinSuccess() { self.dismiss(animated: true, completion: { if let vc = R.storyboard.hugoPayFull.createPinSuccessHPFViewController() { vc.modalPresentationStyle = .fullScreen vc.delegate = self.delegate vc.hugoTabController = self.hugoTabController self.hugoTabController?.present(vc, animated: true, completion: nil) } }) } @IBAction func goBack(_ sender: Any) { if isVerification { isVerification = false initView() } else { dismiss(animated: true, completion: nil) } } } extension CreatePinHPFullViewController: PinInputViewDelegate { func pinDidChange(pinInputView: PinInputView) { validateInputCode() } } // MARK: - Keyboard Handling extension CreatePinHPFullViewController { func registerKeyboardNotifications() { let notificationCenter = NotificationCenter.default notificationCenter.addObserver( self, selector: #selector(keyboardWillShow(notif:)), name: UIResponder.keyboardWillShowNotification, object: nil) notificationCenter.addObserver( self, selector: #selector(keyboardWillShow(notif:)), name: UIResponder.keyboardWillChangeFrameNotification, object: nil) notificationCenter.addObserver( self, selector: #selector(keyboardWillHide(notif:)), name: UIResponder.keyboardWillHideNotification, object: nil) } @objc func keyboardWillShow(notif: Notification) { guard let frame = notif.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return } self.validateBtn.frame = CGRect(x: self.validateBtn.frame.origin.x, y: self.view.bounds.height - (frame.height + self.validateBtn.frame.size.height), width: self.validateBtn.frame.size.width, height: self.validateBtn.frame.size.height) } @objc func keyboardWillHide(notif: Notification) { // scrollView.contentInset = UIEdgeInsets() } }
33.842324
243
0.582148
92ff9600ede229cdc447c139b5ca2dbaa3ed6dd2
512
h
C
WidgetCenterProxy/WidgetCenterProxy/WidgetCenterProxy.h
t9mike/WidgetCenterProxy
8b4a916a1de213cba1f22ea918d9bfc0e7a0a109
[ "MIT" ]
15
2020-09-30T12:55:38.000Z
2021-10-03T20:43:13.000Z
WidgetCenterProxy/WidgetCenterProxy/WidgetCenterProxy.h
t9mike/WidgetCenterProxy
8b4a916a1de213cba1f22ea918d9bfc0e7a0a109
[ "MIT" ]
1
2020-10-03T19:07:12.000Z
2020-12-07T13:11:13.000Z
WidgetCenterProxy/WidgetCenterProxy/WidgetCenterProxy.h
t9mike/WidgetCenterProxy
8b4a916a1de213cba1f22ea918d9bfc0e7a0a109
[ "MIT" ]
5
2020-10-05T13:21:42.000Z
2021-11-12T07:57:36.000Z
// // WidgetCenterProxy.h // WidgetCenterProxy // // Created by huszarcsaba on 2020. 09. 22.. // #import <Foundation/Foundation.h> //! Project version number for WidgetCenterProxy. FOUNDATION_EXPORT double WidgetCenterProxyVersionNumber; //! Project version string for WidgetCenterProxy. FOUNDATION_EXPORT const unsigned char WidgetCenterProxyVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <WidgetCenterProxy/PublicHeader.h>
26.947368
142
0.791016
86adeaed374d9f75b62fce069995830d43988288
369
kt
Kotlin
app/src/main/java/com/moegirlviewer/util/refreshWatchList.kt
koharubiyori/Moegirl-plus-native
f96574d04f50c9f273f7e1737a9ae1743a254de2
[ "MIT" ]
28
2022-01-20T12:21:11.000Z
2022-03-25T09:00:23.000Z
app/src/main/java/com/moegirlviewer/util/refreshWatchList.kt
koharubiyori/Moegirl-plus-native
f96574d04f50c9f273f7e1737a9ae1743a254de2
[ "MIT" ]
6
2022-01-29T04:41:49.000Z
2022-03-23T19:09:37.000Z
app/src/main/java/com/moegirlviewer/util/refreshWatchList.kt
koharubiyori/Moegirl-plus-native
f96574d04f50c9f273f7e1737a9ae1743a254de2
[ "MIT" ]
4
2022-02-04T04:11:13.000Z
2022-03-09T14:28:50.000Z
package com.moegirlviewer.util import com.moegirlviewer.api.watchList.WatchListApi import com.moegirlviewer.room.watchingPage.WatchingPage suspend fun refreshWatchList() { val rawWatchList = WatchListApi.getRawWatchList() Globals.room.watchingPage().clear() Globals.room.watchingPage().insertItem( *rawWatchList.map { WatchingPage(it) }.toTypedArray() ) }
30.75
57
0.794038
c476973f832734251e0a8808508f308b7f4a82db
15,896
h
C
lib/src/McuEE24.h
ErichStyger/McuOnEclipseLibrary
dd5be3c6c16a085971ccb9dc7f67d9a9ba21f718
[ "BSD-2-Clause" ]
77
2016-12-17T15:34:30.000Z
2022-03-31T16:56:26.000Z
lib/src/McuEE24.h
ErichStyger/McuOnEclipseLibrary
dd5be3c6c16a085971ccb9dc7f67d9a9ba21f718
[ "BSD-2-Clause" ]
2
2018-07-12T12:55:08.000Z
2021-07-27T06:22:47.000Z
lib/src/McuEE24.h
ErichStyger/McuOnEclipseLibrary
dd5be3c6c16a085971ccb9dc7f67d9a9ba21f718
[ "BSD-2-Clause" ]
27
2017-02-23T10:04:56.000Z
2022-03-08T14:20:17.000Z
/* ################################################################### ** This component module is generated by Processor Expert. Do not modify it. ** Filename : McuEE24.h ** Project : FRDM-K64F_Generator ** Processor : MK64FN1M0VLL12 ** Component : 24AA_EEPROM ** Version : Component 01.042, Driver 01.00, CPU db: 3.00.000 ** Compiler : GNU C Compiler ** Date/Time : 2021-04-18, 20:37, # CodeGen: 733 ** Abstract : ** Driver for Microchip 24_AA/LC EEPROMs ** Settings : ** Component name : McuEE24 ** SDK : McuLib ** Device Type : 8 ** Initial I2C Device Address Bits : 0x0 ** Block buffer size : 32 ** Acknowledge Polling : Enabled ** Page Write Time (ms) : 5 ** Wait : McuWait ** ACK Polling Time (us) : 100 ** Connection : ** I2C : McuGenericI2C ** Write Protection Pin : Enabled ** WP : SDK_BitIO ** Timeout : Enabled ** Timeout : McuTimeout ** Timeout Byte (ms) : 10 ** Timeout Block (ms) : 60 ** Shell : Enabled ** Shell : McuShell ** Utility : McuUtility ** Contents : ** ReadByte - uint8_t McuEE24_ReadByte(McuEE24_Address addr, uint8_t *data); ** WriteByte - uint8_t McuEE24_WriteByte(McuEE24_Address addr, uint8_t data); ** ReadBlock - uint8_t McuEE24_ReadBlock(McuEE24_Address addr, uint8_t *data, uint16_t... ** WriteBlock - uint8_t McuEE24_WriteBlock(McuEE24_Address addr, uint8_t *data, uint16_t... ** WriteProtect - void McuEE24_WriteProtect(void); ** WriteUnprotect - void McuEE24_WriteUnprotect(void); ** SelectDevice - uint8_t McuEE24_SelectDevice(uint8_t addrI2C); ** GetSelectedDevice - uint8_t McuEE24_GetSelectedDevice(void); ** Test - uint8_t McuEE24_Test(void); ** ParseCommand - uint8_t McuEE24_ParseCommand(const unsigned char *cmd, bool *handled, const... ** Deinit - void McuEE24_Deinit(void); ** Init - void McuEE24_Init(void); ** ** * Copyright (c) 2013-2021, Erich Styger ** * Web: https://mcuoneclipse.com ** * SourceForge: https://sourceforge.net/projects/mcuoneclipse ** * Git: https://github.com/ErichStyger/McuOnEclipse_PEx ** * All rights reserved. ** * ** * Redistribution and use in source and binary forms, with or without modification, ** * are permitted provided that the following conditions are met: ** * ** * - Redistributions of source code must retain the above copyright notice, this list ** * of conditions and the following disclaimer. ** * ** * - Redistributions in binary form must reproduce the above copyright notice, this ** * list of conditions and the following disclaimer in the documentation and/or ** * other materials provided with the distribution. ** * ** * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ** * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ** * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; ** * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ** * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ** * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ###################################################################*/ /*! ** @file McuEE24.h ** @version 01.00 ** @brief ** Driver for Microchip 24_AA/LC EEPROMs */ /*! ** @addtogroup McuEE24_module McuEE24 module documentation ** @{ */ #ifndef __McuEE24_H #define __McuEE24_H /* MODULE McuEE24. */ #include "McuLib.h" /* SDK and API used */ #include "McuEE24config.h" /* configuration */ #if McuEE24_CONFIG_USE_SHELL #include "McuShell.h" #endif #if McuEE24_CONFIG_DEVICE_ID==8 #define McuEE24_MAX_I2C_ADDR_MASK 0 /* A2|A1|A0 are not used */ #define McuEE24_MAX_ADDRESS 0x03FF /* 8 kBit is 1KByte */ #define McuEE24_ADDRT uint16_t /* a word/16bit is enough to hold the address */ #define McuEE24_PAGE_SIZE 16 /* maximum page size (for page/block operation) */ #elif McuEE24_CONFIG_DEVICE_ID==16 #define McuEE24_MAX_I2C_ADDR_MASK 0 /* A2|A1|A0 are not used */ #define McuEE24_MAX_ADDRESS 0x07FF /* 16 kBit is 2KByte */ #define McuEE24_ADDRT uint16_t /* a word/16bit is enough to hold the address */ #define McuEE24_PAGE_SIZE 16 /* maximum page size (for page/block operation) */ #elif McuEE24_CONFIG_DEVICE_ID==32 #define McuEE24_MAX_I2C_ADDR_MASK 7 /* A2|A1|A0 form the I2C device address => address cannot be more than 7 (8 devices) */ #define McuEE24_MAX_ADDRESS 0x0FFF /* 32 kBit are 4KByte */ #define McuEE24_ADDRT uint16_t /* a word/16bit is enough to hold the address */ #define McuEE24_PAGE_SIZE 8 /* maximum page size (for page/block operation) */ #elif McuEE24_CONFIG_DEVICE_ID==256 #define McuEE24_MAX_I2C_ADDR_MASK 7 /* A2|A1|A0 form the I2C device address => address cannot be more than 7 (8 devices) */ #define McuEE24_MAX_ADDRESS 0x7FFF /* 256 kBit are 32KByte */ #define McuEE24_ADDRT uint16_t /* a word/16bit is enough to hold the address */ #define McuEE24_PAGE_SIZE 64 /* maximum page size (for page/block operation) */ #elif McuEE24_CONFIG_DEVICE_ID==512 #define McuEE24_MAX_I2C_ADDR_MASK 7 /* A2|A1|A0 form the I2C device address => address cannot be more than 7 (8 devices) */ #define McuEE24_MAX_ADDRESS 0xFFFF /* 512 kBit are 64KByte */ #define McuEE24_ADDRT uint16_t /* a word/16bit is enough to hold the address */ #define McuEE24_PAGE_SIZE 128 /* maximum page size (for page/block operation) */ #elif McuEE24_CONFIG_DEVICE_ID==1025 #define McuEE24_MAX_I2C_ADDR_MASK 3 /* A1|A0 form the I2C device address => address cannot be more than 3 (4 devices) */ #define McuEE24_MAX_ADDRESS 0x1FFFF /* 1024 kBit are 128KByte */ #define McuEE24_ADDRT uint32_t /* a longword/32bit is needed to hold the address */ #define McuEE24_PAGE_SIZE 128 /* maximum page size (for page/block operation) */ #else #error "unknown device?" #endif #ifndef __BWUserType_McuEE24_Address #define __BWUserType_McuEE24_Address typedef McuEE24_ADDRT McuEE24_Address; /* A type large enought to hold the address, depending on the EEPROM used. */ #endif #define McuEE24_PARSE_COMMAND_ENABLED 1 /* set to 1 if method ParseCommand() is present, 0 otherwise */ uint8_t McuEE24_WriteByte(McuEE24_Address addr, uint8_t data); /* ** =================================================================== ** Method : WriteByte (component 24AA_EEPROM) ** ** Description : ** Writes a single byte to specified address ** Parameters : ** NAME - DESCRIPTION ** addr - The address inside the EEPROM ** data - The data value to write ** Returns : ** --- - Error code, possible values ** ERR_OK - OK ** otherwise it can return an error code of ** the underlying communication protocol. ** =================================================================== */ uint8_t McuEE24_ReadByte(McuEE24_Address addr, uint8_t *data); /* ** =================================================================== ** Method : ReadByte (component 24AA_EEPROM) ** ** Description : ** Reads a single byte from the given memory address ** Parameters : ** NAME - DESCRIPTION ** addr - The address where to read from memory. ** * data - Pointer to a location where to store the ** data ** Returns : ** --- - Error code, possible values ** ERR_OK - OK ** otherwise it can return an error code of ** the underlying communication protocol. ** =================================================================== */ uint8_t McuEE24_ReadBlock(McuEE24_Address addr, uint8_t *data, uint16_t dataSize); /* ** =================================================================== ** Method : ReadBlock (component 24AA_EEPROM) ** ** Description : ** Read a block of memory. ** Parameters : ** NAME - DESCRIPTION ** addr - Address where to read the memory ** * data - Pointer to a buffer where to store the ** data ** dataSize - Size of buffer the data pointer ** is pointing to ** Returns : ** --- - Error code, possible values ** ERR_OK - OK ** otherwise it can return an error code of ** the underlying communication protocol. ** =================================================================== */ uint8_t McuEE24_WriteBlock(McuEE24_Address addr, uint8_t *data, uint16_t dataSize); /* ** =================================================================== ** Method : WriteBlock (component 24AA_EEPROM) ** ** Description : ** Writes a block of data to the EEPROM ** Parameters : ** NAME - DESCRIPTION ** addr - Address of memory ** * data - Pointer to the data ** dataSize - Size of data ** Returns : ** --- - Error code, possible values ** ERR_OK - OK ** ERR_OVERFLOW - data block passed has either ** size of zero or exceeds internal buffer ** size ** otherwise it can return an error code of ** the underlying communication protocol. ** =================================================================== */ uint8_t McuEE24_Test(void); /* ** =================================================================== ** Method : Test (component 24AA_EEPROM) ** ** Description : ** Test routine to test the driver. Note that this routine ** writes to the EEPROM! ** Parameters : None ** Returns : ** --- - Error code, possible values ** ERR_OK - OK ** ERR_FAULT - Test failed ** =================================================================== */ void McuEE24_WriteProtect(void); /* ** =================================================================== ** Method : WriteProtect (component 24AA_EEPROM) ** ** Description : ** Prevents writing to the memory. Read operations are not ** affected. ** Parameters : None ** Returns : Nothing ** =================================================================== */ void McuEE24_WriteUnprotect(void); /* ** =================================================================== ** Method : WriteUnprotect (component 24AA_EEPROM) ** ** Description : ** Allows writing to the memory ** Parameters : None ** Returns : Nothing ** =================================================================== */ uint8_t McuEE24_SelectDevice(uint8_t addrI2C); /* ** =================================================================== ** Method : SelectDevice (component 24AA_EEPROM) ** ** Description : ** Configures the I2C address to be used for the memory. With ** this multiple devices attached to the bus can be addressed. ** Parameters : ** NAME - DESCRIPTION ** addrI2C - I2C Address of the memory device, ** formed by the address pins. ** Returns : ** --- - Error code, possible codes: ** ERR_OK - OK ** ERR_VALUE - address exceeds address pins of ** device type used ** =================================================================== */ uint8_t McuEE24_ParseCommand(const unsigned char *cmd, bool *handled, const McuShell_StdIOType *io); /* ** =================================================================== ** Method : ParseCommand (component 24AA_EEPROM) ** ** Description : ** Shell Command Line parser. This method is enabled/disabled ** depending on if you have the Shell enabled/disabled in the ** properties. ** Parameters : ** NAME - DESCRIPTION ** * cmd - Pointer to command string ** * handled - Pointer to variable which tells if ** the command has been handled or not ** * io - Pointer to I/O structure ** Returns : ** --- - Error code ** =================================================================== */ uint8_t McuEE24_GetSelectedDevice(void); /* ** =================================================================== ** Method : GetSelectedDevice (component 24AA_EEPROM) ** ** Description : ** Returns the currently used I2C address (e.g. set with ** SelectDevice()). ** Parameters : None ** Returns : ** --- - I2C device address ** =================================================================== */ uint8_t McuEE24_WriteBlockPage(McuEE24_Address addr, uint8_t *data, uint16_t dataSize); /* ** =================================================================== ** Method : McuEE24_WriteBlockPage (component 24AA_EEPROM) ** ** Description : ** This method is internal. It is used by Processor Expert only. ** =================================================================== */ void McuEE24_Deinit(void); /* ** =================================================================== ** Method : Deinit (component 24AA_EEPROM) ** ** Description : ** Driver de-initialization ** Parameters : None ** Returns : Nothing ** =================================================================== */ void McuEE24_Init(void); /* ** =================================================================== ** Method : Init (component 24AA_EEPROM) ** ** Description : ** Driver initialization ** Parameters : None ** Returns : Nothing ** =================================================================== */ /* END McuEE24. */ #endif /* ifndef __McuEE24_H */ /*! ** @} */
44.402235
127
0.497547
dd9fe03cfeb4e5574d0d2eda9fca636dd05972ec
3,949
swift
Swift
ECSTests/Performance/Prototype/EntityQueryPerformanceTests.swift
LionGameEngine/LionECS
5c83c4afd9314a1866e88fc87faf1267f7ff1df8
[ "MIT" ]
null
null
null
ECSTests/Performance/Prototype/EntityQueryPerformanceTests.swift
LionGameEngine/LionECS
5c83c4afd9314a1866e88fc87faf1267f7ff1df8
[ "MIT" ]
null
null
null
ECSTests/Performance/Prototype/EntityQueryPerformanceTests.swift
LionGameEngine/LionECS
5c83c4afd9314a1866e88fc87faf1267f7ff1df8
[ "MIT" ]
null
null
null
// // EntityQueryPerformanceTests.swift // LionECSTests // // Created by Tomasz Lewandowski on 08/01/2020. // Copyright © 2020 Lion Software Tomasz Lewandowski. All rights reserved. // import XCTest @testable import LionECS class EntityQueryPerformanceTests: XCTestCase { struct Component1: PComponent { var x: Int64 var y: Int64 } struct Component2: PComponent { let x: Int64 let y: Int64 } struct Component3: PComponent { let x: Int64 let y: Int64 } struct Component4: PComponent {} struct Component5: PComponent {} struct Component6: PComponent {} struct Component7: PComponent {} struct Component8: PComponent {} struct Component9: PComponent {} struct Component10: PComponent {} var sut: EntityRequester<ComponentManager>! let runs: Int = 1 let entitiesCount: Int = 100000 override func setUp() { super.setUp() let componentManager = ComponentManager() let prototype = PrototypeBuilder() .add(Component1.self) .add(Component2.self) .add(Component3.self) .add(Component4.self) .add(Component5.self) .add(Component6.self) .add(Component7.self) .add(Component8.self) .add(Component9.self) .add(Component10.self) .build() let entityManager = EntityManager<ComponentManager>(componentManager: componentManager) sut = EntityRequester<ComponentManager>(entityManager: entityManager, componentManager: componentManager) for _ in 0..<entitiesCount { entityManager.createEntity(withPrototype: prototype) } } func testPrototypeQueryPerformance() { measure { for _ in 1...runs { let query = EntityQuery<ComponentManager>( filters: [ Requires<Component1>(), Requires<Component2>(), Requires<Component3>(), Requires<Component4>(), Requires<Component5>(), Requires<Component6>(), Requires<Component7>(), Requires<Component8>(), Requires<Component9>(), Requires<Component10>(), Excludes<PComponentMock>() ] ) guard let result = try? sut.queryEntities(query: query) else { return } // swiftlint:disable closure_parameter_position result.forEach { ( _: Entity, _: Component1, _: Component2, _: Component3, _: Component4, _: Component5, _: Component6, _: Component7, _: Component8, _: Component9, _: Component10) in } } } } func testPrototypeQueryReadPerformance() { measure { for _ in 1...runs { let query = EntityQuery<ComponentManager>(filters: [Requires<Component1>()]) guard let result = try? sut.queryEntities(query: query) else { return } result.forEach { (_: Entity, _: Component1) in } } } } func testPrototypeQueryWritePerformance() { measure { for _ in 1...runs { let query = EntityQuery<ComponentManager>(filters: [Requires<Component1>()]) guard let result = try? sut.queryEntities(query: query) else { return } result.forEach { (_: Entity, w1: inout Component1) in w1.x = 100 } } } } }
32.908333
113
0.517346
0e585501958cf2d4cba71dee3c9b776987e1cc2e
28,809
html
HTML
server/public/global.html
Justinjdaniel/Shipment-Log
57a27ff9535af4a743b36c87e66756372412e457
[ "MIT" ]
1
2022-01-17T05:55:48.000Z
2022-01-17T05:55:48.000Z
server/public/global.html
Justinjdaniel/Shipment-Log
57a27ff9535af4a743b36c87e66756372412e457
[ "MIT" ]
null
null
null
server/public/global.html
Justinjdaniel/Shipment-Log
57a27ff9535af4a743b36c87e66756372412e457
[ "MIT" ]
null
null
null
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>SHIPMENT LOG</title> <meta charset="utf-8" /> <meta httpEquiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="keywords" content="SHIPMENT LOG" /> <meta name="description" content="SHIPMENT LOG" /> <link rel="icon" href="./favicon.png" /> <script src="scripts/prettify/prettify.js"></script> <script src="scripts/prettify/lang-css.js"></script> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css" /> <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css" /> </head> <body> <div id="main"> <h1 class="page-title">SHIPMENT LOG</h1> <section> <header> <h2></h2> </header> <article> <div class="container-overview"> <dl class="details"></dl> </div> <h3 class="subsection-title">Methods</h3> <h4 class="name" id="addApproval"> <span class="type-signature">(async) </span>addApproval<span class="signature" >(ctx, shipmentId, approvalID, approvedBy)</span ><span class="type-signature"></span> </h4> <div class="description"> <p>Add approval data</p> </div> <h5>Parameters:</h5> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>ctx</code></td> <td class="type"> <span class="param-type">context</span> </td> <td class="description last"> <p>Contract Context</p> </td> </tr> <tr> <td class="name"><code>shipmentId</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="description last"> <p>Shipment Id</p> </td> </tr> <tr> <td class="name"><code>approvalID</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="description last"> <p>Approval Id</p> </td> </tr> <tr> <td class="name"><code>approvedBy</code></td> <td class="type"> <span class="param-type">string</span> </td> <td class="description last"> <p>Name of approved official</p> </td> </tr> </tbody> </table> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"> <ul class="dummy"> <li> <a href="shipment-contract.js.html">shipment-contract.js</a>, <a href="shipment-contract.js.html#line192">line 192</a> </li> </ul> </dd> </dl> <h5>Returns:</h5> <div class="param-desc"> <p>Nothing</p> </div> <h4 class="name" id="addClearance"> <span class="type-signature">(async) </span>addClearance<span class="signature" >(ctx, shipmentId, arrivalPortData, arrivalTimestamp, clearanceID)</span ><span class="type-signature"></span> </h4> <div class="description"> <p>Add shipment clearance details</p> </div> <h5>Parameters:</h5> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>ctx</code></td> <td class="type"> <span class="param-type">context</span> </td> <td class="description last"> <p>Contract Context</p> </td> </tr> <tr> <td class="name"><code>shipmentId</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="description last"> <p>Shipment Id</p> </td> </tr> <tr> <td class="name"><code>arrivalPortData</code></td> <td class="type"> <span class="param-type">object</span> </td> <td class="description last"> <p>Arrival Port Details</p> </td> </tr> <tr> <td class="name"><code>arrivalTimestamp</code></td> <td class="type"> <span class="param-type">object</span> </td> <td class="description last"> <p>Arrival time details</p> </td> </tr> <tr> <td class="name"><code>clearanceID</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="description last"> <p>clearance ID</p> </td> </tr> </tbody> </table> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"> <ul class="dummy"> <li> <a href="shipment-contract.js.html">shipment-contract.js</a>, <a href="shipment-contract.js.html#line264">line 264</a> </li> </ul> </dd> </dl> <h5>Returns:</h5> <div class="param-desc"> <p>Nothing</p> </div> <h4 class="name" id="addReceipt"> <span class="type-signature">(async) </span>addReceipt<span class="signature" >(ctx, shipmentId, receiver)</span ><span class="type-signature"></span> </h4> <div class="description"> <p>Add receipt</p> </div> <h5>Parameters:</h5> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>ctx</code></td> <td class="type"> <span class="param-type">context</span> </td> <td class="description last"> <p>Contract Context</p> </td> </tr> <tr> <td class="name"><code>shipmentId</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="description last"> <p>Shipment Id</p> </td> </tr> <tr> <td class="name"><code>receiver</code></td> <td class="type"> <span class="param-type">object</span> </td> <td class="description last"> <p>Receiver Data</p> </td> </tr> </tbody> </table> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"> <ul class="dummy"> <li> <a href="shipment-contract.js.html">shipment-contract.js</a>, <a href="shipment-contract.js.html#line303">line 303</a> </li> </ul> </dd> </dl> <h5>Returns:</h5> <div class="param-desc"> <p>Nothing</p> </div> <h4 class="name" id="addVerification"> <span class="type-signature">(async) </span>addVerification<span class="signature" >(ctx, shipmentId, verificationID, portData)</span ><span class="type-signature"></span> </h4> <div class="description"> <p>Add shipment verification details</p> </div> <h5>Parameters:</h5> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>ctx</code></td> <td class="type"> <span class="param-type">context</span> </td> <td class="description last"> <p>Contract Context</p> </td> </tr> <tr> <td class="name"><code>shipmentId</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="description last"> <p>Shipment Id</p> </td> </tr> <tr> <td class="name"><code>verificationID</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="description last"> <p>Verification Id</p> </td> </tr> <tr> <td class="name"><code>portData</code></td> <td class="type"> <span class="param-type">object</span> </td> <td class="description last"> <p>Port Details</p> </td> </tr> </tbody> </table> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"> <ul class="dummy"> <li> <a href="shipment-contract.js.html">shipment-contract.js</a>, <a href="shipment-contract.js.html#line233">line 233</a> </li> </ul> </dd> </dl> <h5>Returns:</h5> <div class="param-desc"> <p>Nothing</p> </div> <h4 class="name" id="createPrivateAsset"> <span class="type-signature">(async) </span>createPrivateAsset<span class="signature" >(ctx, privateAssetId)</span ><span class="type-signature"></span> </h4> <div class="description"> <p>Creates a private asset</p> </div> <h5>Parameters:</h5> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>ctx</code></td> <td class="type"> <span class="param-type">context</span> </td> <td class="description last"> <p>Contract Context</p> </td> </tr> <tr> <td class="name"><code>privateAssetId</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="description last"> <p>PrivateAsset Id</p> </td> </tr> </tbody> </table> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"> <ul class="dummy"> <li> <a href="shipment-contract.js.html">shipment-contract.js</a>, <a href="shipment-contract.js.html#line31">line 31</a> </li> </ul> </dd> </dl> <h5>Returns:</h5> <div class="param-desc"> <p>Nothing</p> </div> <h4 class="name" id="createShipment"> <span class="type-signature">(async) </span>createShipment<span class="signature" >(ctx, shipmentId, sender)</span ><span class="type-signature"></span> </h4> <div class="description"> <p>Create Shipment data</p> </div> <h5>Parameters:</h5> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>ctx</code></td> <td class="type"> <span class="param-type">context</span> </td> <td class="description last"> <p>Contract Context</p> </td> </tr> <tr> <td class="name"><code>shipmentId</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="description last"> <p>Shipment Id</p> </td> </tr> <tr> <td class="name"><code>sender</code></td> <td class="type"> <span class="param-type">object</span> </td> <td class="description last"> <p>Shipment Data</p> </td> </tr> </tbody> </table> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"> <ul class="dummy"> <li> <a href="shipment-contract.js.html">shipment-contract.js</a>, <a href="shipment-contract.js.html#line100">line 100</a> </li> </ul> </dd> </dl> <h5>Returns:</h5> <div class="param-desc"> <p>Nothing</p> </div> <h4 class="name" id="deleteShipment"> <span class="type-signature">(async) </span>deleteShipment<span class="signature" >(ctx, shipmentId)</span ><span class="type-signature"></span> </h4> <div class="description"> <p> Delete shipment data. This feature is not using in this version, Hopefully available from version 2.x </p> </div> <h5>Parameters:</h5> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>ctx</code></td> <td class="type"> <span class="param-type">context</span> </td> <td class="description last"> <p>Contract Context</p> </td> </tr> <tr> <td class="name"><code>shipmentId</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="description last"> <p>Shipment Id</p> </td> </tr> </tbody> </table> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"> <ul class="dummy"> <li> <a href="shipment-contract.js.html">shipment-contract.js</a>, <a href="shipment-contract.js.html#line173">line 173</a> </li> </ul> </dd> </dl> <h5>Returns:</h5> <div class="param-desc"> <p>Nothing</p> </div> <h4 class="name" id="privateAssetExists"> <span class="type-signature">(async) </span>privateAssetExists<span class="signature" >(ctx, privateAssetId)</span ><span class="type-signature"> &rarr; {boolean}</span> </h4> <div class="description"> <p>Check privateAsset exists or not</p> </div> <h5>Parameters:</h5> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>ctx</code></td> <td class="type"> <span class="param-type">context</span> </td> <td class="description last"> <p>Contract Context</p> </td> </tr> <tr> <td class="name"><code>privateAssetId</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="description last"> <p>Private Asset Id</p> </td> </tr> </tbody> </table> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"> <ul class="dummy"> <li> <a href="shipment-contract.js.html">shipment-contract.js</a>, <a href="shipment-contract.js.html#line15">line 15</a> </li> </ul> </dd> </dl> <h5>Returns:</h5> <div class="param-desc"> <p>Exists or not</p> </div> <dl> <dt>Type</dt> <dd> <span class="param-type">boolean</span> </dd> </dl> <h4 class="name" id="readPrivateAsset"> <span class="type-signature">(async) </span>readPrivateAsset<span class="signature" >(ctx, privateAssetId)</span ><span class="type-signature"> &rarr; {String}</span> </h4> <div class="description"> <p>Retrieve private asset</p> </div> <h5>Parameters:</h5> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>ctx</code></td> <td class="type"> <span class="param-type">context</span> </td> <td class="description last"> <p>Contract Context</p> </td> </tr> <tr> <td class="name"><code>privateAssetId</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="description last"> <p>Private Asset ID</p> </td> </tr> </tbody> </table> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"> <ul class="dummy"> <li> <a href="shipment-contract.js.html">shipment-contract.js</a>, <a href="shipment-contract.js.html#line64">line 64</a> </li> </ul> </dd> </dl> <h5>Returns:</h5> <div class="param-desc"> <p>Private Data</p> </div> <dl> <dt>Type</dt> <dd> <span class="param-type">String</span> </dd> </dl> <h4 class="name" id="readShipment"> <span class="type-signature">(async) </span>readShipment<span class="signature" >(ctx, shipmentId)</span ><span class="type-signature"> &rarr; {json}</span> </h4> <div class="description"> <p>Retrieve Shipment data</p> </div> <h5>Parameters:</h5> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>ctx</code></td> <td class="type"> <span class="param-type">context</span> </td> <td class="description last"> <p>Contract Context</p> </td> </tr> <tr> <td class="name"><code>shipmentId</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="description last"> <p>Shipment Id</p> </td> </tr> </tbody> </table> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"> <ul class="dummy"> <li> <a href="shipment-contract.js.html">shipment-contract.js</a>, <a href="shipment-contract.js.html#line126">line 126</a> </li> </ul> </dd> </dl> <h5>Returns:</h5> <div class="param-desc"> <p>Asset</p> </div> <dl> <dt>Type</dt> <dd> <span class="param-type">json</span> </dd> </dl> <h4 class="name" id="shipmentExists"> <span class="type-signature">(async) </span>shipmentExists<span class="signature" >(ctx, shipmentId)</span ><span class="type-signature"> &rarr; {boolean}</span> </h4> <div class="description"> <p>Checks shipment id exist or not</p> </div> <h5>Parameters:</h5> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>ctx</code></td> <td class="type"> <span class="param-type">context</span> </td> <td class="description last"> <p>Contract Context</p> </td> </tr> <tr> <td class="name"><code>shipmentId</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="description last"> <p>Shipment Id</p> </td> </tr> </tbody> </table> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"> <ul class="dummy"> <li> <a href="shipment-contract.js.html">shipment-contract.js</a>, <a href="shipment-contract.js.html#line87">line 87</a> </li> </ul> </dd> </dl> <h5>Returns:</h5> <div class="param-desc"> <p>returns boolean</p> </div> <dl> <dt>Type</dt> <dd> <span class="param-type">boolean</span> </dd> </dl> <h4 class="name" id="updateShipment"> <span class="type-signature">(async) </span>updateShipment<span class="signature" >(ctx, shipmentId, newData)</span ><span class="type-signature"></span> </h4> <div class="description"> <p> Update shipment data with new data. This feature is not using in this version, Hopefully available from version 2.x </p> </div> <h5>Parameters:</h5> <table class="params"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>ctx</code></td> <td class="type"> <span class="param-type">context</span> </td> <td class="description last"> <p>Contract Context</p> </td> </tr> <tr> <td class="name"><code>shipmentId</code></td> <td class="type"> <span class="param-type">number</span> </td> <td class="description last"> <p>Shipment Id</p> </td> </tr> <tr> <td class="name"><code>newData</code></td> <td class="type"> <span class="param-type">object</span> </td> <td class="description last"> <p>Updated data of shipment</p> </td> </tr> </tbody> </table> <dl class="details"> <dt class="tag-source">Source:</dt> <dd class="tag-source"> <ul class="dummy"> <li> <a href="shipment-contract.js.html">shipment-contract.js</a>, <a href="shipment-contract.js.html#line144">line 144</a> </li> </ul> </dd> </dl> <h5>Returns:</h5> <div class="param-desc"> <p>Nothing</p> </div> </article> </section> </div> <nav> <h2><a href="index.html">SHIPMENT LOG</a></h2> <h3>Methods</h3> <ul> <li><a href="global.html#addApproval">addApproval</a></li> <li><a href="global.html#addClearance">addClearance</a></li> <li><a href="global.html#addReceipt">addReceipt</a></li> <li><a href="global.html#addVerification">addVerification</a></li> <li><a href="global.html#createPrivateAsset">createPrivateAsset</a></li> <li><a href="global.html#createShipment">createShipment</a></li> <li><a href="global.html#deleteShipment">deleteShipment</a></li> <li><a href="global.html#privateAssetExists">privateAssetExists</a></li> <li><a href="global.html#readPrivateAsset">readPrivateAsset</a></li> <li><a href="global.html#readShipment">readShipment</a></li> <li><a href="global.html#shipmentExists">shipmentExists</a></li> <li><a href="global.html#updateShipment">updateShipment</a></li> </ul> </nav> <br class="clear" /> <footer> Documentation generated by <a href="https://github.com/jsdoc/jsdoc">JSDoc 3.6.7</a> </footer> <script> prettyPrint(); </script> <script src="scripts/linenumber.js"></script> </body> </html>
27.178302
80
0.402964
a3e013a1ff919a915b59daf7720142b90788ec6a
366
dart
Dart
lib/pages/home-component/HomeComponentHead.dart
Worktez/worktrolly_flutter
eb51dfae5514acd4dd110597f6f7bcb6a3bf8e29
[ "MIT" ]
null
null
null
lib/pages/home-component/HomeComponentHead.dart
Worktez/worktrolly_flutter
eb51dfae5514acd4dd110597f6f7bcb6a3bf8e29
[ "MIT" ]
null
null
null
lib/pages/home-component/HomeComponentHead.dart
Worktez/worktrolly_flutter
eb51dfae5514acd4dd110597f6f7bcb6a3bf8e29
[ "MIT" ]
4
2021-07-27T13:48:30.000Z
2021-09-05T14:40:02.000Z
import 'package:flutter/material.dart'; import 'package:worktrolly_flutter/pages/home-component/profile-component/ProfileComponent.dart'; class HomeComponentHead extends StatelessWidget { const HomeComponentHead({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Container( child: ProfileComponent(), ); } }
26.142857
97
0.748634
24a09b6e525bc3387659436430305a8c0a66c18f
549
asm
Assembly
oeis/183/A183061.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
11
2021-08-22T19:44:55.000Z
2022-03-20T16:47:57.000Z
oeis/183/A183061.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
9
2021-08-29T13:15:54.000Z
2022-03-09T19:52:31.000Z
oeis/183/A183061.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
3
2021-08-22T20:56:47.000Z
2021-09-29T06:26:12.000Z
; A183061: First differences of A183060. ; Submitted by Jon Maiga ; 0,1,3,3,7,3,7,7,19,3,7,7,19,7,19,19,55,3,7,7,19,7,19,19,55,7,19,19,55,19,55,55,163,3,7,7,19,7,19,19,55,7,19,19,55,19,55,55,163,7,19,19,55,19,55,55,163,19,55,55,163,55,163,163,487,3 mov $4,2 mov $5,$0 lpb $4 mov $0,$5 sub $4,1 add $0,$4 trn $0,1 mov $2,$0 seq $0,147562 ; Number of "ON" cells at n-th stage in the "Ulam-Warburton" two-dimensional cellular automaton. div $0,2 add $0,$2 mov $3,$4 mul $3,$0 add $6,$3 lpe min $5,1 mul $5,$0 mov $0,$6 sub $0,$5
22.875
182
0.613843
016d86ee6d47474874f69275c6cfd2a1e570d687
5,690
rs
Rust
crates/ra_hir/src/query_definitions.rs
aleksanb/rust-analyzer
4a3d6aa26a1c71dadc91f37f9d5f8662b51c138a
[ "Apache-2.0", "MIT" ]
null
null
null
crates/ra_hir/src/query_definitions.rs
aleksanb/rust-analyzer
4a3d6aa26a1c71dadc91f37f9d5f8662b51c138a
[ "Apache-2.0", "MIT" ]
null
null
null
crates/ra_hir/src/query_definitions.rs
aleksanb/rust-analyzer
4a3d6aa26a1c71dadc91f37f9d5f8662b51c138a
[ "Apache-2.0", "MIT" ]
null
null
null
use std::{ sync::Arc, time::Instant, }; use rustc_hash::FxHashMap; use ra_syntax::{ AstNode, SyntaxNode, ast::{self, NameOwner, ModuleItemOwner} }; use ra_db::{SourceRootId, FileId, Cancelable,}; use crate::{ SourceFileItems, SourceItemId, DefKind, Function, DefId, Name, AsName, db::HirDatabase, function::FnScopes, module::{ ModuleSource, ModuleSourceNode, ModuleId, imp::Submodule, nameres::{InputModuleItems, ItemMap, Resolver}, }, ty::{self, InferenceResult, Ty}, adt::{StructData, EnumData}, }; pub(super) fn fn_scopes(db: &impl HirDatabase, def_id: DefId) -> Arc<FnScopes> { let function = Function::new(def_id); let syntax = function.syntax(db); let res = FnScopes::new(syntax.borrowed()); Arc::new(res) } pub(super) fn infer(db: &impl HirDatabase, def_id: DefId) -> Cancelable<Arc<InferenceResult>> { let function = Function::new(def_id); ty::infer(db, function).map(Arc::new) } pub(super) fn type_for_def(db: &impl HirDatabase, def_id: DefId) -> Cancelable<Ty> { ty::type_for_def(db, def_id) } pub(super) fn type_for_field(db: &impl HirDatabase, def_id: DefId, field: Name) -> Cancelable<Ty> { ty::type_for_field(db, def_id, field) } pub(super) fn struct_data(db: &impl HirDatabase, def_id: DefId) -> Cancelable<Arc<StructData>> { let def_loc = def_id.loc(db); assert!(def_loc.kind == DefKind::Struct); let syntax = db.file_item(def_loc.source_item_id); let struct_def = ast::StructDef::cast(syntax.borrowed()).expect("struct def should point to StructDef node"); Ok(Arc::new(StructData::new(struct_def.borrowed()))) } pub(super) fn enum_data(db: &impl HirDatabase, def_id: DefId) -> Cancelable<Arc<EnumData>> { let def_loc = def_id.loc(db); assert!(def_loc.kind == DefKind::Enum); let syntax = db.file_item(def_loc.source_item_id); let enum_def = ast::EnumDef::cast(syntax.borrowed()).expect("enum def should point to EnumDef node"); Ok(Arc::new(EnumData::new(enum_def.borrowed()))) } pub(super) fn file_items(db: &impl HirDatabase, file_id: FileId) -> Arc<SourceFileItems> { let mut res = SourceFileItems::new(file_id); let source_file = db.source_file(file_id); let source_file = source_file.borrowed(); source_file .syntax() .descendants() .filter_map(ast::ModuleItem::cast) .map(|it| it.syntax().owned()) .for_each(|it| { res.alloc(it); }); Arc::new(res) } pub(super) fn file_item(db: &impl HirDatabase, source_item_id: SourceItemId) -> SyntaxNode { match source_item_id.item_id { Some(id) => db.file_items(source_item_id.file_id)[id].clone(), None => db.source_file(source_item_id.file_id).syntax().owned(), } } pub(crate) fn submodules( db: &impl HirDatabase, source: ModuleSource, ) -> Cancelable<Arc<Vec<Submodule>>> { db.check_canceled()?; let file_id = source.file_id(); let submodules = match source.resolve(db) { ModuleSourceNode::SourceFile(it) => collect_submodules(db, file_id, it.borrowed()), ModuleSourceNode::Module(it) => it .borrowed() .item_list() .map(|it| collect_submodules(db, file_id, it)) .unwrap_or_else(Vec::new), }; return Ok(Arc::new(submodules)); fn collect_submodules<'a>( db: &impl HirDatabase, file_id: FileId, root: impl ast::ModuleItemOwner<'a>, ) -> Vec<Submodule> { modules(root) .map(|(name, m)| { if m.has_semi() { Submodule::Declaration(name) } else { let src = ModuleSource::new_inline(db, file_id, m); Submodule::Definition(name, src) } }) .collect() } } pub(crate) fn modules<'a>( root: impl ast::ModuleItemOwner<'a>, ) -> impl Iterator<Item = (Name, ast::Module<'a>)> { root.items() .filter_map(|item| match item { ast::ModuleItem::Module(m) => Some(m), _ => None, }) .filter_map(|module| { let name = module.name()?.as_name(); Some((name, module)) }) } pub(super) fn input_module_items( db: &impl HirDatabase, source_root: SourceRootId, module_id: ModuleId, ) -> Cancelable<Arc<InputModuleItems>> { let module_tree = db.module_tree(source_root)?; let source = module_id.source(&module_tree); let file_items = db.file_items(source.file_id()); let res = match source.resolve(db) { ModuleSourceNode::SourceFile(it) => { let items = it.borrowed().items(); InputModuleItems::new(&file_items, items) } ModuleSourceNode::Module(it) => { let items = it .borrowed() .item_list() .into_iter() .flat_map(|it| it.items()); InputModuleItems::new(&file_items, items) } }; Ok(Arc::new(res)) } pub(super) fn item_map( db: &impl HirDatabase, source_root: SourceRootId, ) -> Cancelable<Arc<ItemMap>> { let start = Instant::now(); let module_tree = db.module_tree(source_root)?; let input = module_tree .modules() .map(|id| { let items = db.input_module_items(source_root, id)?; Ok((id, items)) }) .collect::<Cancelable<FxHashMap<_, _>>>()?; let resolver = Resolver::new(db, &input, source_root, module_tree); let res = resolver.resolve()?; let elapsed = start.elapsed(); log::info!("item_map: {:?}", elapsed); Ok(Arc::new(res)) }
31.787709
100
0.602812
b05fe414c02bd0b01fe97ba56b967ad1bd8f02e2
4,956
html
HTML
content/slides-external/slide-correlation-to-regression.html
gcalmettes/ls40-slides
0876308cfcb51533562a83036df9bcee535dabaa
[ "MIT" ]
1
2020-11-06T04:40:31.000Z
2020-11-06T04:40:31.000Z
content/slides-external/slide-correlation-to-regression.html
gcalmettes/ls40-slides
0876308cfcb51533562a83036df9bcee535dabaa
[ "MIT" ]
null
null
null
content/slides-external/slide-correlation-to-regression.html
gcalmettes/ls40-slides
0876308cfcb51533562a83036df9bcee535dabaa
[ "MIT" ]
1
2020-11-06T04:40:39.000Z
2020-11-06T04:40:39.000Z
<section> <h3>Going beyond correlation</h3> <div class="row"> <div class="col-75"> <svg width="100%" viewBox="0 0 720 288"> <use xlink:href="content/img/correlation-simulation-graph-swap.svg#axes_1"></use> <use xlink:href="content/img/correlation-simulation-graph-swap.svg#axes_2"></use> <use class="fragment" xlink:href="content/img/correlation-simulation-graph-swap.svg#axes_3"></use> <use class="fragment" xlink:href="content/img/correlation-simulation-graph-swap.svg#axes_4"></use> </svg> </div> </div> <p class="fragment smaller"> <i class="fas fa-arrow-circle-right"></i> By analysing our sample, we are 95% confident that the true value of the correlation (<span class="pop">$\rho$</span>) between height and foot length is in the interval <bspan>(0.54, 0.86)</bspan>. </p> <div class="fragment"> <p class="rounded small bg-pink-light down-2 black"> If height and foot length are significantly correlated, couldn't we use the value of one of the variables to <span class="strong u">predict</span> the value of the other one? </p> <p> <i class="fas fa-arrow-circle-right pink"></i> Could we use foot length to <span class="pink">gain (unknown) information</span> about someone height? </p> </div> </section> <section> <h3>Why would we want to do that?</h3> <div class="row fragment" data-fragment-index=1> <div class="col-20"> <img class="framed" src="content/img/regression-ex-forensic.jpg" width=100%> </div> <div class="col-80"> <p class="small"> <span class="u em danger">Forensic analysis:</span> Most people are not accustomed to looking at foot length, so describing the suspect as having a foot of 10.5inches long would probably not help find the suspect. It would be <span class="info">far more useful</span> to tell people to look for a <span class="u-info">suspect who is of a certain <span class="info">height</span></span>. </p> <p class="fragment" data-fragment-index=3> <i class="fas fa-arrow-circle-right danger"></i> The accuracy of this prediction would depend on the size of the <span class="u-danger">correlation between foot length and height</span> </p> </div> </div> <div class="row fragment" data-fragment-index=2> <div class="col-20"> <img class="framed" src="content/img/regression-ex-anthropology.jpeg" width=100%> </div> <div class="col-80"> <p class="small"> <span class="u em danger">Anthropology:</span> Body proportions and the dimensions of various body segments, including the long bones of their limbs and the bones of the foot and hand have been used to <span class="info">estimate stature</span>. </p> <p class="fragment" data-fragment-index=3> <i class="fas fa-arrow-circle-right danger"></i> The accuracy of this prediction would depend on the size of the <span class="u-danger">correlation between foot length and height</span> </p> </div> </div> </section> <section> <h3>Going beyond correlation</h3> <p> Because the correlation coefficient only gives information about the <span class="danger">direction</span> and <span class="danger">strength</span> of an association, we cannot use it directly to get information of someone's height from his/her footprint. </p> <div class="row"> <div class="col-45"> <svg width="100%" viewBox="340 0 295 288"> <use xlink:href="content/img/correlation-simulation-graph-swap.svg#axes_2"></use> <use class="fragment" data-fragment-index=2 xlink:href="content/img/correlation-simulation-graph-swap.svg#axes_5"></use> <use class="fragment" data-fragment-index=3 xlink:href="content/img/correlation-simulation-graph-swap.svg#axes_6"></use> </svg> </div> <div class="col-55"> <p class="smaller fragment framed border-pop" data-fragment-index=1> If we decide the association is linear <bspan>(strong $r$)</bspan>, it is useful to <span class="pop">develop a mathematical model</span> of that association. </p> <p class="fragment smaller" data-fragment-index=2> <i class="fas fa-arrow-circle-right orange"></i> The process of fitting a line to a set of data is called <span class="orange em">linear regression</span>, and the line of best fit is called the <span class="orange em">regression line</span>, which is the line that gets as close as possible to all of the data points. </p> <p class="fragment smaller" data-fragment-index=3> <i class="fas fa-arrow-circle-right danger"></i> We can use the regression line to give a <span class="danger">predicted value of the response variable</span>, based on a given value of the explanatory variable. </p> </div> </div> </section>
48.116505
342
0.662228
0c7a5957fe9864225fb891e5477469385f447a91
3,456
py
Python
complex_venv/lib/python3.7/site-packages/test/test_graph_list_of_file_inputs.py
lubianat/complex_bot
e0ddabcc0487c52b14fb94950c5a812f0bdb2283
[ "MIT" ]
1
2021-10-06T00:21:10.000Z
2021-10-06T00:21:10.000Z
complex_venv/lib/python3.7/site-packages/test/test_graph_list_of_file_inputs.py
lubianat/complex_bot
e0ddabcc0487c52b14fb94950c5a812f0bdb2283
[ "MIT" ]
14
2021-01-15T21:51:38.000Z
2021-11-10T10:08:22.000Z
complex_venv/lib/python3.7/site-packages/test/test_graph_list_of_file_inputs.py
lubianat/complex_bot
e0ddabcc0487c52b14fb94950c5a812f0bdb2283
[ "MIT" ]
1
2021-01-18T10:32:56.000Z
2021-01-18T10:32:56.000Z
import unittest from shexer.shaper import Shaper from test.const import G1, BASE_FILES, G1_NT, default_namespaces, BASE_FILES_GENERAL from test.t_utils import file_vs_str_tunned_comparison import os.path as pth from shexer.consts import NT, TURTLE _BASE_DIR = BASE_FILES + "graph_list_of_files_input" + pth.sep class TestGraphListOfFilesInput(unittest.TestCase): def test_one_turtle(self): shaper = Shaper(target_classes=["http://xmlns.com/foaf/0.1/Person", "http://xmlns.com/foaf/0.1/Document"], graph_list_of_files_input=[G1], namespaces_dict=default_namespaces(), all_classes_mode=False, input_format=TURTLE, disable_comments=True) str_result = shaper.shex_graph(string_output=True) self.assertTrue(file_vs_str_tunned_comparison(file_path=BASE_FILES_GENERAL + "g1_all_classes_no_comments.shex", str_target=str_result)) def test_one_nt(self): # Should be nt shaper = Shaper(target_classes=["http://xmlns.com/foaf/0.1/Person", "http://xmlns.com/foaf/0.1/Document"], graph_list_of_files_input=[G1_NT], namespaces_dict=default_namespaces(), input_format=NT, all_classes_mode=False, disable_comments=True) str_result = shaper.shex_graph(string_output=True) self.assertTrue(file_vs_str_tunned_comparison(file_path=BASE_FILES_GENERAL + "g1_all_classes_no_comments.shex", str_target=str_result)) def test_several_nt(self): # Should be nt shaper = Shaper(target_classes=["http://xmlns.com/foaf/0.1/Person", "http://xmlns.com/foaf/0.1/Document"], graph_list_of_files_input=[_BASE_DIR + "g1_p1.nt", _BASE_DIR + "g1_p2.nt"], namespaces_dict=default_namespaces(), input_format=NT, all_classes_mode=False, disable_comments=True) str_result = shaper.shex_graph(string_output=True) self.assertTrue(file_vs_str_tunned_comparison(file_path=BASE_FILES_GENERAL + "g1_all_classes_no_comments.shex", str_target=str_result)) def test_several_turtle(self): shaper = Shaper(target_classes=["http://xmlns.com/foaf/0.1/Person", "http://xmlns.com/foaf/0.1/Document"], graph_list_of_files_input=[_BASE_DIR + "g1_p1.ttl", _BASE_DIR + "g1_p2.ttl"], namespaces_dict=default_namespaces(), all_classes_mode=False, input_format=TURTLE, disable_comments=True) str_result = shaper.shex_graph(string_output=True) self.assertTrue(file_vs_str_tunned_comparison(file_path=BASE_FILES_GENERAL + "g1_all_classes_no_comments.shex", str_target=str_result))
54.857143
120
0.550926
e1336b2ce6a566ac78b352da0bc21ff8c87ed3a3
1,058
lua
Lua
states/tutorial.lua
vrld/theotherside
9c01df06460b791c7d879342a2a13df959f1382e
[ "Zlib", "MIT" ]
1
2015-10-24T00:39:39.000Z
2015-10-24T00:39:39.000Z
states/tutorial.lua
vrld/theotherside
9c01df06460b791c7d879342a2a13df959f1382e
[ "Zlib", "MIT" ]
null
null
null
states/tutorial.lua
vrld/theotherside
9c01df06460b791c7d879342a2a13df959f1382e
[ "Zlib", "MIT" ]
null
null
null
local st = GS.new() local W, H local title, title_width, title_height local image, next_state function st:enter(_, t, ns) W = love.graphics.getWidth() H = love.graphics.getHeight() title = t image = Image[t] title_width = Font.slkscr[70]:getWidth(title) title_height = Font.slkscr[70]:getHeight(title) next_state = ns end function st:keypressed(key, code) if key == ' ' or key == 'return' then GS.transition(next_state, .5) end end local t = 0 function st:update(dt) t = t + dt end function st:draw() love.graphics.setColor(255,255,255) love.graphics.setFont(Font.slkscr[70]) love.graphics.rectangle('fill', 20,40, W-40, title_height) love.graphics.setColor(0,0,0) love.graphics.print(title, (W-title_width)/2, 40) love.graphics.setColor(255,255,255) love.graphics.draw(image, W/2,H/2+30,0,2,2, image:getWidth()/2,image:getHeight()/2) love.graphics.setColor(255,255,255,(math.sin(t)*.5+.5) * 100 + 155) love.graphics.setFont(Font.slkscr[40]) love.graphics.printf("Press [space] to continue", 0,H-70,W, 'center') end return st
23
84
0.708885
96a045b9a0699c206dc64f971f730ad43e552a33
19,251
html
HTML
bak/app/_includes/00-atoms/00-meta/01-foot.html
nicmarson/nicmarson-website
1494a8707711f89f09da86b4b7507c61d19983df
[ "MIT" ]
null
null
null
bak/app/_includes/00-atoms/00-meta/01-foot.html
nicmarson/nicmarson-website
1494a8707711f89f09da86b4b7507c61d19983df
[ "MIT" ]
null
null
null
bak/app/_includes/00-atoms/00-meta/01-foot.html
nicmarson/nicmarson-website
1494a8707711f89f09da86b4b7507c61d19983df
[ "MIT" ]
null
null
null
<svg class="hidden" xmlns="http://www.w3.org/2000/svg"> <style type="text/css"> svg * { transition: fill .1s ease-out, opacity .1s ease-out; } </style> <symbol id="shape-email" viewBox="0 0 100 100"><path d="M44.933,98.093C19.882,92.443,3.579,72.894,6.295,42.843C8.963,13.331,32.181-0.745,54.983,0.03 c18.222,0.615,37.405,13.801,38.936,38.896c0.718,11.746-3.373,22.681-9.981,29.42c-8.577,8.746-19.542,10.468-28.546,9.201 C41.647,75.631,27.999,66.319,28.748,46.28c0.265-7.127,3.676-14.744,9.178-19.788c3.56-3.269,9.475-5.933,15.366-5.743 c6.368,0.208,11.371,3.154,14.656,7.464c5.83,7.661,5.674,19.918,5.456,21.124c0,0-0.04,0.302-0.095,0.712 c-0.147,0.997-0.982,1.743-1.95,1.735l-30.047-0.182c-0.141-0.004-0.28,0.066-0.375,0.186c-0.094,0.118-0.142,0.273-0.116,0.413 c2.068,11.762,13.149,13.718,15.739,14.062c3.146,0.427,11.645,1.258,18.699-5.78c4.832-4.81,7.071-9.829,7.429-21.025 c0.353-10.708-8.132-28.569-31.131-28.653c-12.009-0.044-31.643,10.088-33.57,33.223C16.083,66.766,28.553,84.02,48.54,87.51 c27.377,4.776,38.256-7.408,38.256-7.408c0.507-0.308,1.099-0.148,1.333,0.354l4.324,8.51c0.108,0.229,0.194,0.541,0.108,0.824 c-0.093,0.273-0.172,0.361-0.468,0.604C92.101,90.392,76.226,105.138,44.933,98.093z M42.286,39.479 c-0.085,0.199-0.124,0.412-0.046,0.593c0.079,0.177,0.25,0.29,0.438,0.29l19.159,0.143c0.147,0.004,0.297-0.066,0.405-0.193 c0.102-0.129,0.146-0.291,0.125-0.442c-0.296-1.804-0.866-3.609-1.965-5.027c-1.515-1.965-4.542-3.288-7.953-3.187 c-3.004,0.09-5.087,1.144-7.031,2.97C43.801,36.147,42.614,38.669,42.286,39.479z"></path></symbol> <symbol id="shape-phone" viewBox="0 0 100 100"><path d="M68.75 62.5c-6.25 6.25-6.25 12.5-12.5 12.5s-12.5-6.25-18.75-12.5-12.5-12.5-12.5-18.75 6.25-6.25 12.5-12.5-12.5-25-18.75-25-18.75 18.75-18.75 18.75c0 12.5 12.842 37.842 25 50s37.5 25 50 25c0 0 18.75-12.5 18.75-18.75s-18.75-25-25-18.75z"></path></symbol> <symbol id="shape-facebook" viewBox="0 0 100 100"><path d="M94.48,0H5.519C2.471,0,0,2.471,0,5.52v88.96c0,3.049,2.47,5.521,5.519,5.521h63.479L53.411,100V61.273h-13.03V46.181 h13.03v-11.13c0-12.916,7.89-19.949,19.412-19.949c5.52,0,10.263,0.41,11.645,0.595v13.497l-7.991,0.004 c-6.265,0-7.479,2.979-7.479,7.348v9.636h14.945l-1.947,15.093H68.998v38.726H94.48c3.047,0,5.52-2.472,5.52-5.521V5.52 C100,2.471,97.529,0,94.48,0z"></path></symbol> <symbol id="shape-github" viewBox="0 0 100 100"><path d="M50 81.239c-1.871 0-3.741-0.968-5.678-2.905-0.763-0.763-0.763-1.999 0-2.762s1.999-0.763 2.762 0c1.192 1.192 2.146 1.772 2.916 1.772s1.724-0.579 2.916-1.772c0.763-0.762 1.999-0.762 2.762 0s0.763 1.999 0 2.762c-1.937 1.937-3.808 2.905-5.678 2.905zM0 51.318c0 4.872 0.417 9.289 1.25 13.25s2.005 7.396 3.516 10.306c1.51 2.909 3.42 5.459 5.729 7.65s4.818 3.996 7.526 5.416c2.708 1.42 5.807 2.568 9.297 3.444s7.040 1.49 10.651 1.84c3.611 0.351 7.587 0.526 11.927 0.526s8.324-0.175 11.953-0.525c3.629-0.351 7.188-0.964 10.677-1.84s6.597-2.024 9.323-3.444c2.726-1.42 5.252-3.225 7.578-5.416s4.245-4.741 5.755-7.65c1.511-2.91 2.691-6.345 3.542-10.306s1.276-8.378 1.276-13.25c0-8.729-2.709-16.247-8.125-22.557 0.313-0.841 0.581-1.805 0.807-2.892s0.443-2.62 0.651-4.601c0.209-1.981 0.13-4.268-0.234-6.862s-1.050-5.241-2.057-7.94l-0.781-0.158c-0.521-0.105-1.371-0.070-2.552 0.105s-2.561 0.49-4.14 0.946c-1.58 0.455-3.62 1.358-6.12 2.708s-5.139 3.058-7.917 5.127c-4.722-1.437-11.232-2.941-19.531-2.941s-14.826 1.504-19.583 2.941c-2.778-2.068-5.425-3.768-7.943-5.1s-4.531-2.244-6.042-2.734c-1.511-0.491-2.908-0.806-4.193-0.946s-2.11-0.184-2.474-0.131c-0.364 0.053-0.634 0.114-0.807 0.184-1.007 2.699-1.702 5.346-2.084 7.94s-0.469 4.872-0.26 6.835c0.208 1.963 0.434 3.506 0.677 4.627s0.521 2.086 0.833 2.892c-5.417 6.274-8.125 13.793-8.125 22.557zM13.334 62.442c0-5.666 2.083-10.804 6.25-15.416 1.25-1.407 2.7-2.472 4.349-3.195s3.524-1.133 5.625-1.231c2.101-0.098 4.106-0.078 6.016 0.059s4.271 0.322 7.083 0.557c2.812 0.235 5.243 0.352 7.292 0.352s4.479-0.117 7.291-0.352c2.813-0.234 5.174-0.42 7.084-0.557s3.915-0.156 6.016-0.059c2.101 0.098 3.985 0.508 5.651 1.231s3.125 1.788 4.375 3.195c4.166 4.611 6.25 9.749 6.25 15.416 0 3.321-0.347 6.282-1.042 8.88s-1.571 4.777-2.63 6.535c-1.059 1.759-2.544 3.244-4.453 4.455s-3.759 2.149-5.547 2.813c-1.788 0.664-4.097 1.182-6.927 1.553s-5.365 0.596-7.605 0.674c-2.24 0.078-5.061 0.117-8.463 0.117s-6.215-0.039-8.438-0.117c-2.222-0.078-4.748-0.303-7.578-0.674s-5.139-0.889-6.927-1.553c-1.788-0.664-3.637-1.602-5.547-2.813s-3.394-2.696-4.453-4.455c-1.059-1.758-1.936-3.937-2.63-6.535s-1.042-5.559-1.042-8.88zM25 59.375c0-5.178 2.798-9.375 6.25-9.375s6.25 4.197 6.25 9.375c0 5.178-2.798 9.375-6.25 9.375s-6.25-4.197-6.25-9.375zM62.5 59.375c0-5.178 2.798-9.375 6.25-9.375s6.25 4.197 6.25 9.375c0 5.178-2.798 9.375-6.25 9.375s-6.25-4.197-6.25-9.375z"></path></symbol> <symbol id="shape-googleplus" viewBox="0 0 100 100"><path d="M0.079 84.928c-0.024-0.247-0.044-0.495-0.057-0.745 0.013 0.25 0.033 0.498 0.057 0.745zM23.038 55.19c8.985 0.267 15.013-9.053 13.463-20.82-1.552-11.766-10.097-21.208-19.083-21.477-8.987-0.267-15.014 8.738-13.462 20.508 1.551 11.764 10.093 21.521 19.082 21.789zM100 25v-8.331c0-9.168-7.498-16.669-16.666-16.669h-66.666c-9.011 0-16.407 7.249-16.657 16.204 5.699-5.018 13.606-9.211 21.765-9.211 8.721 0 34.887 0 34.887 0l-7.807 6.603h-11.061c7.337 2.813 11.246 11.34 11.246 20.090 0 7.348-4.083 13.667-9.852 18.161-5.629 4.385-6.696 6.221-6.696 9.949 0 3.181 6.030 8.594 9.183 10.819 9.217 6.498 12.199 12.53 12.199 22.603 0 1.604-0.199 3.206-0.592 4.781h30.053c9.167 0 16.666-7.495 16.666-16.669v-52.081h-18.75v18.75h-6.25v-18.75h-18.75v-6.25h18.75v-18.75h6.25v18.75h18.75zM18.153 74.798c2.111 0 4.045-0.058 6.048-0.058-2.651-2.572-4.749-5.723-4.749-9.607 0-2.305 0.739-4.525 1.771-6.496-1.053 0.075-2.128 0.097-3.235 0.097-7.261 0-13.428-2.351-17.989-6.236v6.567l0.001 19.7c5.219-2.478 11.415-3.967 18.152-3.967zM0.334 86.646c-0.109-0.533-0.192-1.075-0.248-1.624 0.056 0.55 0.14 1.091 0.248 1.624zM44.478 93.051c-1.471-5.743-6.685-8.59-13.954-13.63-2.644-0.853-5.556-1.355-8.681-1.388-8.752-0.094-16.905 3.412-21.505 8.63 1.555 7.588 8.304 13.336 16.331 13.336h27.973c0.177-1.087 0.263-2.21 0.263-3.362 0-1.224-0.15-2.421-0.427-3.586z"></path></symbol> <symbol id="shape-pinterest" viewBox="0 0 100 100"><path d="M50 0c-27.614 0-50 22.386-50 50s22.385 50 50 50c27.614 0 50-22.386 50-50s-22.386-50-50-50zM54.848 66.808c-4.543-0.353-6.449-2.603-10.010-4.766-1.959 10.271-4.352 20.119-11.439 25.262-2.188-15.524 3.212-27.184 5.72-39.562-4.276-7.198 0.515-21.683 9.533-18.113 11.096 4.389-9.609 26.759 4.29 29.552 14.514 2.917 20.438-25.181 11.44-34.319-13.004-13.194-37.851-0.301-34.796 18.589 0.744 4.618 5.515 6.019 1.907 12.393-8.322-1.845-10.806-8.408-10.486-17.159 0.514-14.324 12.87-24.352 25.262-25.739 15.672-1.754 30.381 5.753 32.413 20.496 2.286 16.64-7.075 34.661-23.833 33.365z"></path></symbol> <symbol id="shape-twitter" viewBox="0 0 100 100"><path d="M100.001,17.942c-3.681,1.688-7.633,2.826-11.783,3.339 c4.236-2.624,7.49-6.779,9.021-11.73c-3.965,2.432-8.354,4.193-13.026,5.146C80.47,10.575,75.138,8,69.234,8 c-11.33,0-20.518,9.494-20.518,21.205c0,1.662,0.183,3.281,0.533,4.833c-17.052-0.884-32.168-9.326-42.288-22.155 c-1.767,3.133-2.778,6.773-2.778,10.659c0,7.357,3.622,13.849,9.127,17.65c-3.363-0.109-6.525-1.064-9.293-2.651 c-0.002,0.089-0.002,0.178-0.002,0.268c0,10.272,7.072,18.845,16.458,20.793c-1.721,0.484-3.534,0.744-5.405,0.744 c-1.322,0-2.606-0.134-3.859-0.379c2.609,8.424,10.187,14.555,19.166,14.726c-7.021,5.688-15.867,9.077-25.48,9.077 c-1.656,0-3.289-0.102-4.895-0.297C9.08,88.491,19.865,92,31.449,92c37.737,0,58.374-32.312,58.374-60.336 c0-0.92-0.02-1.834-0.059-2.743C93.771,25.929,97.251,22.195,100.001,17.942L100.001,17.942z"></path></symbol> <symbol id="shape-linkedin" viewBox="0 0 100 100"><path d="M83.203 0h-66.406c-9.238 0-16.797 7.559-16.797 16.797v66.406c0 9.238 7.559 16.797 16.797 16.797h66.406c9.238 0 16.797-7.559 16.797-16.797v-66.406c0-9.238-7.559-16.797-16.797-16.797zM37.5 81.25h-12.5v-43.75h12.5v43.75zM31.25 31.25c-3.452 0-6.25-2.798-6.25-6.25s2.798-6.25 6.25-6.25 6.25 2.798 6.25 6.25-2.798 6.25-6.25 6.25zM81.25 81.25h-12.5v-25c0-3.452-2.798-6.25-6.25-6.25s-6.25 2.798-6.25 6.25v25h-12.5v-43.75h12.5v7.761c2.578-3.541 6.519-7.761 10.938-7.761 7.767 0 14.063 6.996 14.063 15.625v28.125z"></path></symbol> <symbol id="shape-bullhorn" viewBox="0 0 100 100"><path d="M100 41.92c0-19.622-5.741-35.541-12.84-35.667 0.029-0.001 0.056-0.003 0.085-0.003h-8.1c0 0-19.023 14.291-46.409 19.898-0.836 4.423-1.37 9.695-1.37 15.772s0.534 11.348 1.37 15.771c27.386 5.607 46.409 19.898 46.409 19.898h8.1c-0.029 0-0.056-0.002-0.085-0.003 7.099-0.126 12.84-16.045 12.84-35.666zM84.455 72.193c-0.916 0-1.907-0.951-2.417-1.518-1.233-1.373-2.421-3.512-3.436-6.184-2.271-5.98-3.522-13.995-3.522-22.571s1.251-16.591 3.522-22.571c1.015-2.673 2.203-4.811 3.436-6.184 0.509-0.568 1.5-1.519 2.417-1.519s1.908 0.952 2.416 1.519c1.234 1.373 2.421 3.512 3.436 6.184 2.271 5.979 3.522 13.995 3.522 22.571s-1.251 16.591-3.522 22.571c-1.015 2.673-2.203 4.811-3.436 6.184-0.509 0.567-1.5 1.518-2.416 1.518zM24.591 41.92c0-5.073 0.372-10.003 1.079-14.56-4.626 0.64-8.686 1.008-13.705 1.008-6.549 0-6.549 0-6.549 0l-5.417 9.247v8.61l5.416 9.247c0 0 0 0 6.549 0 5.019 0 9.079 0.369 13.705 1.008-0.707-4.557-1.079-9.487-1.079-14.56zM35.952 62.712l-12.5-2.394 7.992 31.401c0.414 1.624 2.026 2.445 3.583 1.822l11.578-4.634c1.557-0.623 2.18-2.34 1.386-3.817l-12.039-22.378zM84.455 53.587c-0.353 0-0.735-0.367-0.931-0.585-0.476-0.529-0.933-1.354-1.324-2.384-0.875-2.305-1.357-5.394-1.357-8.699s0.482-6.394 1.357-8.699c0.391-1.030 0.849-1.854 1.324-2.384 0.196-0.219 0.578-0.585 0.931-0.585s0.735 0.367 0.931 0.585c0.476 0.529 0.933 1.353 1.324 2.384 0.875 2.304 1.358 5.394 1.358 8.699s-0.482 6.394-1.358 8.699c-0.391 1.030-0.849 1.854-1.324 2.384-0.196 0.219-0.578 0.585-0.931 0.585z"></path></symbol> <symbol id="shape-bridge" viewBox="0 0 100 100"><path d="M107.157 47.163v-1.983c-7.001-3.589-12.347-9.275-14.815-16.163l-0.102 0.043v-0.102h-6.952v0.054l-0.070-0.027c-4.344 12.105-17.074 18.48-31.7 18.48-14.621 0-27.351-6.37-31.695-18.453l-0.135 0.054v-0.108h-6.92v0.275c-2.522 6.791-7.825 12.412-14.767 15.958v1.978c1.25-0.582 2.42-1.293 3.573-2.016v9.351h-3.525v3.81h14.718v12.724h6.92v-12.724h63.6v12.724h6.952v-12.724h14.918v-3.8h-3.519v-9.351c1.137 0.706 2.285 1.412 3.519 1.999zM9.943 54.514h-5.411v-9.895c2.005-1.337 3.778-2.921 5.411-4.608v14.503zM14.767 54.514h-3.87v-15.538c1.471-1.638 2.808-3.374 3.87-5.26v20.798zM25.923 54.514h-4.236v-21.164c1.143 2.145 2.614 4.004 4.236 5.707v15.457zM33.619 54.514h-6.731v-14.422c1.978 1.87 4.252 3.406 6.731 4.689v9.733zM41.32 54.514h-6.731v-9.205c2.096 1.008 4.376 1.746 6.731 2.355v6.85zM49.022 54.514h-6.737v-6.586c2.177 0.507 4.408 0.884 6.737 1.078v5.508zM56.723 54.514h-6.737v-5.465c1.17 0.092 2.334 0.172 3.53 0.172 1.083 0 2.145-0.092 3.207-0.146v5.438zM64.419 54.514h-6.737v-5.492c2.323-0.178 4.559-0.523 6.737-1.013v6.505zM72.115 54.514h-6.731v-6.747c2.361-0.593 4.624-1.337 6.731-2.312v9.060zM79.822 54.514h-6.747v-9.545c2.484-1.234 4.759-2.732 6.747-4.533v14.077zM85.287 54.514h-4.511v-15.096c1.746-1.757 3.293-3.708 4.511-5.966v21.062zM96.303 54.514h-4.064v-21.159c1.083 2.032 2.511 3.886 4.064 5.637v15.521zM102.695 54.514h-5.433v-14.487c1.644 1.681 3.422 3.255 5.433 4.592v9.895z"></path></symbol> <symbol id="shape-home" viewBox="0 0 100 100"> <g> <path d="M100,54.661 L50,15.85 L0,54.661 L0,38.837 L50,0.026 L100,38.837 L100,54.661 Z" id="shape-home-roof"></path> <path d="M87.5,53.25 L87.5,90.75 L62.5,90.75 L62.5,65.75 L37.5,65.75 L37.5,90.75 L12.5,90.75 L12.5,53.25 L50,25.125 L87.5,53.25 Z" id="shape-home-walls"></path> </g> </symbol> <symbol id="shape-house" viewBox="0 0 100 100"><path d="M93.85 51.5l-40.12-40.155c-2.050-2.13-5.405-2.13-7.455 0l-40.125 40.155c-2.055 2.125-1.29 3.87 1.7 3.87h8.365v30.84c0 2.225 0.095 4.045 4.12 4.045h19.475v-30.94h20.375v30.94h20.445c3.070 0 3.155-1.815 3.155-4.045v-30.84h8.36c2.985 0 3.755-1.74 1.705-3.87z"></path></symbol> <symbol id="shape-user" viewBox="0 0 100 100"><path d="M82.813 100h-65.625c-2.589 0-4.688-2.099-4.688-4.688 0-6.725 2.839-14.864 7.594-21.772 3.974-5.773 8.856-10.119 14.129-12.657-2.324-2.114-4.326-4.69-5.909-7.629-2.539-4.713-3.881-10.161-3.881-15.755 0-7.774 2.559-15.119 7.206-20.683 4.85-5.807 11.371-9.005 18.363-9.005s13.512 3.198 18.363 9.005c4.646 5.563 7.206 12.908 7.206 20.683 0 5.594-1.342 11.042-3.881 15.755-1.583 2.939-3.585 5.515-5.909 7.629 5.273 2.538 10.155 6.884 14.129 12.657 4.755 6.908 7.593 15.047 7.593 21.771 0 2.589-2.099 4.688-4.688 4.688zM22.468 90.625h55.064c-0.901-3.842-2.785-8.045-5.348-11.769-4.048-5.881-9.099-9.729-14.222-10.833-2.159-0.465-3.7-2.374-3.7-4.582v-3.349c0-1.686 0.905-3.241 2.37-4.074 5.808-3.304 9.562-10.573 9.562-18.518 0-11.2-7.264-20.313-16.193-20.313s-16.193 9.112-16.193 20.313c0 7.945 3.753 15.214 9.562 18.518 1.465 0.833 2.37 2.389 2.37 4.074v3.349c0 2.208-1.541 4.117-3.7 4.582-5.123 1.104-10.174 4.951-14.223 10.833-2.563 3.723-4.447 7.927-5.348 11.769z"></path></symbol> <symbol id="shape-users" viewBox="0 0 100 100"><path d="M95.313 100h-65.625c-2.589 0-4.688-2.099-4.688-4.688 0-6.725 2.839-14.864 7.594-21.772 3.974-5.773 8.856-10.119 14.129-12.657-2.324-2.114-4.326-4.69-5.909-7.629-2.539-4.713-3.881-10.161-3.881-15.755 0-7.774 2.559-15.119 7.206-20.683 4.85-5.807 11.371-9.005 18.362-9.005s13.512 3.198 18.363 9.005c4.646 5.563 7.206 12.908 7.206 20.683 0 5.594-1.342 11.042-3.881 15.755-1.583 2.939-3.585 5.515-5.909 7.629 5.273 2.538 10.155 6.884 14.129 12.657 4.755 6.908 7.593 15.047 7.593 21.771 0 2.589-2.099 4.688-4.688 4.688zM34.968 90.625h55.064c-0.901-3.842-2.785-8.045-5.348-11.769-4.048-5.881-9.099-9.729-14.222-10.833-2.159-0.465-3.7-2.374-3.7-4.582v-3.349c0-1.686 0.905-3.241 2.37-4.074 5.808-3.304 9.562-10.573 9.562-18.518 0-11.2-7.264-20.313-16.193-20.313s-16.193 9.112-16.193 20.313c0 7.945 3.753 15.214 9.562 18.518 1.465 0.833 2.37 2.389 2.37 4.074v3.349c0 2.208-1.541 4.117-3.7 4.582-5.123 1.104-10.174 4.951-14.223 10.833-2.563 3.723-4.447 7.927-5.348 11.769zM19.249 84.375h-9.281c0.901-3.842 2.785-8.045 5.348-11.769 4.048-5.881 9.099-9.729 14.223-10.833 2.159-0.465 3.7-2.374 3.7-4.582v-3.349c0-1.686-0.905-3.241-2.37-4.074-5.809-3.304-9.562-10.573-9.562-18.518 0-11.2 7.264-20.313 16.193-20.313 0.611 0 1.213 0.044 1.807 0.127 2.574-2.865 5.492-5.193 8.656-6.934-3.241-1.683-6.787-2.568-10.463-2.568-6.991 0-13.512 3.198-18.363 9.005-4.646 5.563-7.205 12.909-7.205 20.683 0 5.594 1.342 11.042 3.881 15.755 1.583 2.939 3.585 5.515 5.909 7.629-5.273 2.538-10.155 6.884-14.129 12.657-4.755 6.908-7.594 15.047-7.594 21.771 0 2.589 2.099 4.688 4.688 4.688h12.928c0.144-3.030 0.703-6.193 1.634-9.375z"></path></symbol> <symbol id="shape-star" viewBox="0 0 100 100"><path d="M100 38.774l-34.549-5.020-15.451-31.307-15.451 31.307-34.549 5.020 25 24.369-5.902 34.409 30.902-16.246 30.902 16.246-5.902-34.409 25-24.369z"></path></symbol> <symbol id="shape-plus" viewBox="0 0 100 100"><path d="M96.875 37.5h-34.375v-34.375c0-1.726-1.399-3.125-3.125-3.125h-18.75c-1.726 0-3.125 1.399-3.125 3.125v34.375h-34.375c-1.726 0-3.125 1.399-3.125 3.125v18.75c0 1.726 1.399 3.125 3.125 3.125h34.375v34.375c0 1.726 1.399 3.125 3.125 3.125h18.75c1.726 0 3.125-1.399 3.125-3.125v-34.375h34.375c1.726 0 3.125-1.399 3.125-3.125v-18.75c0-1.726-1.399-3.125-3.125-3.125z"></path></symbol> <symbol id="shape-tag" viewBox="0 0 100 100"><path d="M90.607 0h-28.18c-5.167 0-12.382 2.989-16.036 6.642l-43.651 43.651c-3.653 3.653-3.653 9.631 0 13.284l33.683 33.682c3.653 3.653 9.631 3.653 13.284 0l43.651-43.651c3.653-3.653 6.642-10.869 6.642-16.036v-28.18c0-5.166-4.227-9.393-9.393-9.393zM78.125 31.25c-5.178 0-9.375-4.197-9.375-9.375s4.197-9.375 9.375-9.375 9.375 4.197 9.375 9.375-4.197 9.375-9.375 9.375z"></path></symbol> <symbol id="shape-tags" viewBox="0 0 100 100"><path d="M96.875 6.25h-21.875c-5.156 0-12.358 2.983-16.004 6.629l-36.742 36.742c-3.646 3.646-3.646 9.612 0 13.258l27.367 27.367c3.646 3.646 9.612 3.646 13.258 0l36.742-36.742c3.646-3.646 6.629-10.848 6.629-16.004v-21.875c0-5.156-4.219-9.375-9.375-9.375zM84.375 37.5c-5.178 0-9.375-4.197-9.375-9.375s4.197-9.375 9.375-9.375 9.375 4.197 9.375 9.375-4.197 9.375-9.375 9.375zM8.46 58.46l33.435 33.435c-3.541 1.871-8.053 1.322-11.024-1.649l-27.367-27.367c-3.646-3.646-3.646-9.612 0-13.258l36.742-36.742c3.646-3.646 10.848-6.629 16.004-6.629l-47.79 47.79c-1.215 1.215-1.215 3.204 0 4.419z"></path></symbol> <symbol id="shape-arrow-left" viewBox="0 0 100 100"><path d="M50 0c27.614 0 50 22.386 50 50s-22.386 50-50 50-50-22.386-50-50 22.386-50 50-50zM50 90.625c22.437 0 40.625-18.188 40.625-40.625s-18.188-40.625-40.625-40.625-40.625 18.188-40.625 40.625 18.188 40.625 40.625 40.625zM20.58 45.581l25-25c2.441-2.441 6.398-2.441 8.839 0s2.441 6.398 0 8.839l-14.33 14.33h34.911c3.452 0 6.25 2.798 6.25 6.25s-2.798 6.25-6.25 6.25h-34.911l14.331 14.33c2.441 2.441 2.441 6.398 0 8.839-1.221 1.22-2.82 1.83-4.42 1.83s-3.199-0.61-4.419-1.83l-25-25c-2.441-2.441-2.441-6.398 0-8.839z"></path></symbol> <symbol id="shape-arrow-right" viewBox="0 0 100 100"><path d="M50 0c-27.614 0-50 22.386-50 50s22.386 50 50 50 50-22.386 50-50-22.386-50-50-50zM50 90.625c-22.437 0-40.625-18.188-40.625-40.625s18.188-40.625 40.625-40.625 40.625 18.188 40.625 40.625-18.188 40.625-40.625 40.625zM79.42 45.581l-25-25c-2.441-2.441-6.398-2.441-8.839 0s-2.441 6.398 0 8.839l14.33 14.33h-34.911c-3.452 0-6.25 2.798-6.25 6.25s2.798 6.25 6.25 6.25h34.911l-14.331 14.33c-2.441 2.441-2.441 6.398 0 8.839 1.221 1.22 2.82 1.83 4.42 1.83s3.199-0.61 4.419-1.83l25-25c2.441-2.441 2.441-6.398 0-8.839z"></path></symbol> <symbol id="shape-camera" viewBox="0 0 100 100"><path d="M37.5 28.125c0-8.629 6.996-15.625 15.625-15.625s15.625 6.996 15.625 15.625c0 8.629-6.996 15.625-15.625 15.625s-15.625-6.996-15.625-15.625zM0 28.125c0-8.629 6.996-15.625 15.625-15.625s15.625 6.996 15.625 15.625c0 8.629-6.996 15.625-15.625 15.625s-15.625-6.996-15.625-15.625zM75 59.375v-9.375c0-3.438-2.813-6.25-6.25-6.25h-62.5c-3.438 0-6.25 2.813-6.25 6.25v31.25c0 3.438 2.813 6.25 6.25 6.25h62.5c3.438 0 6.25-2.813 6.25-6.25v-9.375l25 15.625v-43.75l-25 15.625zM62.5 75h-50v-18.75h50v18.75z"></path></symbol> </svg> <!-- build:js /scripts/vendor/foot.js --> <!-- bower:js --> <script src="/bower_components/jquery/dist/jquery.js" lazyload></script> <script src="/bower_components/picturefill/dist/picturefill.js" lazyload></script> <script src="/bower_components/magnific-popup/dist/jquery.magnific-popup.js"></script> <!-- endbower --> <script src="/scripts/vendor/tablesaw.js" lazyload></script> <script src="/scripts/vendor/waves.js" lazyload></script> <script src="/scripts/main.js" lazyload></script> <!-- endbuild --> <!-- Google Analytics: change UA-XXXXX-X to be your site's ID. --> <script> (function(b, o, i, l, e, r) { b.GoogleAnalyticsObject = l; b[l] || (b[l] = function() { (b[l].q = b[l].q || []).push(arguments) }); b[l].l = +new Date; e = o.createElement(i); r = o.getElementsByTagName(i)[0]; e.src = '//www.google-analytics.com/analytics.js'; r.parentNode.insertBefore(e, r) }(window, document, 'script', 'ga')); ga('create', 'UA-XXXXX-X'); ga('send', 'pageview'); </script>
179.915888
2,450
0.685575
ec21b166e7b5d39dd053f736c0179844e0670dfe
755
ps1
PowerShell
scripts/process/process.ps1
DevelopHeureShell/DetectionHSL
e2af5836b193d9e8b954accbb1ef56a5316e92a2
[ "MIT" ]
null
null
null
scripts/process/process.ps1
DevelopHeureShell/DetectionHSL
e2af5836b193d9e8b954accbb1ef56a5316e92a2
[ "MIT" ]
null
null
null
scripts/process/process.ps1
DevelopHeureShell/DetectionHSL
e2af5836b193d9e8b954accbb1ef56a5316e92a2
[ "MIT" ]
null
null
null
$hslmod = Get-Content $PSScriptRoot\module.json | ConvertFrom-Json Set-Location $PSScriptRoot Set-Location .. Set-Location .. Set-Location .\main $host.ui.RawUI.WindowTitle = $hslmod.name + " version " + $hslmod.version + " par " + $hslmod.author $maindir = Get-Location function Write-Hslcat { param( [string]$file = "" ) if ($file -eq "") { break } & $maindir\cat.exe $PSScriptRoot\$file } Write-Hslcat("info.txt") Set-Location $env:TEMP\detectionhsl\process Get-Process | Format-List -Property ProcessName >> process.txt Get-WmiObject -Class Win32_Product | Format-List -Property Name, Vendor, Version >> apps.txt Get-AppPackage | Format-List -Property Name, Architecture, Version >> appstore.txt Get-Service >> Services.txt
35.952381
100
0.709934
58bd74f9a33b3d626760f72d6811d67912cfb876
457
rs
Rust
os/src/driver/gpio/led_ex.rs
buhe/buguOS
ecb01d31ee2fcaad0d55e9fe663e729da4752abb
[ "Apache-2.0" ]
5
2021-09-30T05:51:05.000Z
2022-01-21T08:21:47.000Z
os/src/driver/gpio/led_ex.rs
buhe/buguOS
ecb01d31ee2fcaad0d55e9fe663e729da4752abb
[ "Apache-2.0" ]
13
2021-10-05T12:50:21.000Z
2022-02-07T04:24:13.000Z
os/src/driver/gpio/led_ex.rs
buhe/bugu
ecb01d31ee2fcaad0d55e9fe663e729da4752abb
[ "Apache-2.0" ]
null
null
null
// 外部的 led use k210_soc::{ fpioa::{self, io}, gpio, gpiohs, }; pub fn init() { // led b 映射到 gpiohs 0 // 9 fpioa::set_function(io::BPSK_P, fpioa::function::GPIOHS0); // 10 fpioa::set_function(io::BPSK_N, fpioa::function::GPIOHS1); // gpiohs 设置 0 为输出 gpiohs::set_direction(0, gpio::direction::OUTPUT); gpiohs::set_direction(1, gpio::direction::OUTPUT); gpiohs::set_pin(0, false); gpiohs::set_pin(1, true); }
21.761905
62
0.61488
dfdce3c4bfdfa03b6f396bdbd905f748f7f2ebbd
3,189
sql
SQL
DIFF_PRIV_ANALYSIS.sql
sap-archive/hana-data-anonymization-vldb-demo
8841f9900d6c4a5642460c65d3dbe74810451098
[ "BSD-Source-Code" ]
1
2019-11-05T18:22:19.000Z
2019-11-05T18:22:19.000Z
DIFF_PRIV_ANALYSIS.sql
sap-archive/hana-data-anonymization-vldb-demo
8841f9900d6c4a5642460c65d3dbe74810451098
[ "BSD-Source-Code" ]
null
null
null
DIFF_PRIV_ANALYSIS.sql
sap-archive/hana-data-anonymization-vldb-demo
8841f9900d6c4a5642460c65d3dbe74810451098
[ "BSD-Source-Code" ]
1
2020-11-09T11:18:04.000Z
2020-11-09T11:18:04.000Z
-- all -- select avg(salary) as avg_t from "ACME_SCHEMA_1"."VLDBDemo.db::tables.HRDB_TABLE"; -- 81856.78029 select avg(salary) as avg_v from "ACME_SCHEMA_1"."VLDBDemo.db::HRDB_VIEW_DIFF_PRIV"; -- 80611.35369474422, 83635.81812867535 select abs((avg_v - avg_t)/avg_t) from ( select avg(salary) as avg_t from "ACME_SCHEMA_1"."VLDBDemo.db::tables.HRDB_TABLE" ) cross join ( select avg(salary) as avg_v from "ACME_SCHEMA_1"."VLDBDemo.db::HRDB_VIEW_DIFF_PRIV" ); -- 0.015214702934119098, 0.021733542809436564 -- 1 -- select avg(salary) as avg_t from "ACME_SCHEMA_1"."VLDBDemo.db::tables.HRDB_TABLE" where start_year <= '1986'; -- 154740.2493622449 select avg(salary) as avg_v from "ACME_SCHEMA_1"."VLDBDemo.db::HRDB_VIEW_DIFF_PRIV" where start_year <= '1986'; -- 158328.75018660387, 181412.51655650948 select abs((avg_v - avg_t)/avg_t) from ( select avg(salary) as avg_t from "ACME_SCHEMA_1"."VLDBDemo.db::tables.HRDB_TABLE" where start_year <= '1986' ) cross join ( select avg(salary) as avg_v from "ACME_SCHEMA_1"."VLDBDemo.db::HRDB_VIEW_DIFF_PRIV" where start_year <= '1986' ); -- 0.023190481074890353, 0.17236799930330432 -- 2 -- select avg(salary) as avg_t from "ACME_SCHEMA_1"."VLDBDemo.db::tables.HRDB_TABLE" where '1986' < start_year and start_year <= '1996'; -- 119603.25911986103 select avg(salary) as avg_v from "ACME_SCHEMA_1"."VLDBDemo.db::HRDB_VIEW_DIFF_PRIV" where '1986' < start_year and start_year <= '1996'; -- 115149.59877376235, 137956.77469942498 select abs((avg_v - avg_t)/avg_t) from ( select avg(salary) as avg_t from "ACME_SCHEMA_1"."VLDBDemo.db::tables.HRDB_TABLE" where '1986' < start_year and start_year <= '1996' ) cross join ( select avg(salary) as avg_v from "ACME_SCHEMA_1"."VLDBDemo.db::HRDB_VIEW_DIFF_PRIV" where '1986' < start_year and start_year <= '1996' ); -- 0.03723694804700449, 0.15345330649535957 -- 3 -- select avg(salary) as avg_t from "ACME_SCHEMA_1"."VLDBDemo.db::tables.HRDB_TABLE" where '1996' < start_year and start_year <= '2006'; -- 91376.44969974106 select avg(salary) as avg_v from "ACME_SCHEMA_1"."VLDBDemo.db::HRDB_VIEW_DIFF_PRIV" where '1996' < start_year and start_year <= '2006'; -- 90897.57589316036, 95258.72151067162 select abs((avg_v - avg_t)/avg_t) from ( select avg(salary) as avg_t from "ACME_SCHEMA_1"."VLDBDemo.db::tables.HRDB_TABLE" where '1996' < start_year and start_year <= '2006' ) cross join ( select avg(salary) as avg_v from "ACME_SCHEMA_1"."VLDBDemo.db::HRDB_VIEW_DIFF_PRIV" where '1996' < start_year and start_year <= '2006' ); -- 0.005240669867939227, 0.042486568735024495 -- 4 -- select avg(salary) as avg_t from "ACME_SCHEMA_1"."VLDBDemo.db::tables.HRDB_TABLE" where '2006' < start_year; -- 65418.18246793386 select avg(salary) as avg_v from "ACME_SCHEMA_1"."VLDBDemo.db::HRDB_VIEW_DIFF_PRIV" where '2006' < start_year; -- 64130.96790709679, 61650.76454935651 select abs((avg_v - avg_t)/avg_t) from ( select avg(salary) as avg_t from "ACME_SCHEMA_1"."VLDBDemo.db::tables.HRDB_TABLE" where '2006' < start_year ) cross join ( select avg(salary) as avg_v from "ACME_SCHEMA_1"."VLDBDemo.db::HRDB_VIEW_DIFF_PRIV" where '2006' < start_year ); -- 0.019676709322640814, 0.05758976749964026
50.619048
177
0.748511
e77140f19c3905a0b3afefd55368a9e58a1ad364
455
js
JavaScript
src/plugins/vuetify.js
Imamachi-n/cc10-soloMVP-project
9bbc36d3ccce6bd3176746f6ebd222059ab26a69
[ "MIT" ]
null
null
null
src/plugins/vuetify.js
Imamachi-n/cc10-soloMVP-project
9bbc36d3ccce6bd3176746f6ebd222059ab26a69
[ "MIT" ]
4
2019-11-11T06:13:20.000Z
2019-11-12T21:30:34.000Z
src/plugins/vuetify.js
Imamachi-n/cc10-soloMVP-project
9bbc36d3ccce6bd3176746f6ebd222059ab26a69
[ "MIT" ]
null
null
null
import Vue from "vue"; import Vuetify from "vuetify/lib"; import colors from "vuetify/lib/util/colors"; import "@fortawesome/fontawesome-free/css/all.css"; Vue.use(Vuetify); export default new Vuetify({ theme: { themes: { light: { primary: colors.indigo.darken3, // #E53935 secondary: colors.red.lighten4, // #FFCDD2 accent: colors.red.darken4, // #3F51B5 }, }, }, icons: { iconfont: "fa", }, });
20.681818
51
0.613187
a38ed2c5bbb34e3d886176ee63d3f76614dec1ac
12,858
swift
Swift
Sources/AIToolbox/Pooling.swift
roznet/AIToolbox
844c47dade7864e76fa55fee9d28eca82af6b777
[ "Apache-2.0" ]
null
null
null
Sources/AIToolbox/Pooling.swift
roznet/AIToolbox
844c47dade7864e76fa55fee9d28eca82af6b777
[ "Apache-2.0" ]
null
null
null
Sources/AIToolbox/Pooling.swift
roznet/AIToolbox
844c47dade7864e76fa55fee9d28eca82af6b777
[ "Apache-2.0" ]
null
null
null
// // Pooling.swift // Convolution // // Created by Kevin Coble on 2/20/16. // Copyright © 2016 Kevin Coble. All rights reserved. // #if !os(Linux) import Foundation import Accelerate public enum PoolingType : Int { case average = 0 case minimum case maximum public func getString() ->String { switch self { case .average: return "Average" case .minimum: return "Minimum" case .maximum: return "Maximum" } } } final public class Pooling : DeepNetworkOperator { public private(set) var poolType : PoolingType public private(set) var dimension: Int public private(set) var reductionLevels: [Int] var pool : [Float] = [] var resultSize : DeepChannelSize fileprivate var inputSize = DeepChannelSize(dimensionCount: 0, dimensionValues: []) var inputUsed: [Int]? public init(type : PoolingType, dimension: Int) { poolType = type self.dimension = dimension // Max of 4 at this time - we will add error handling later reductionLevels = [Int](repeating: 1, count: dimension) resultSize = DeepChannelSize(dimensionCount: 0, dimensionValues: []) } public init(type : PoolingType, reduction: [Int]) { poolType = type self.dimension = reduction.count // Max of 4 at this time - we will add error handling later reductionLevels = reduction resultSize = DeepChannelSize(dimensionCount: 0, dimensionValues: []) } public init?(fromDictionary: [String: AnyObject]) { // Init for nil return (hopefully Swift 3 removes this need) reductionLevels = [] resultSize = DeepChannelSize(dimensionCount: 0, dimensionValues: []) // Get the pooling type let poolTypeValue = fromDictionary["poolingType"] as? NSInteger if poolTypeValue == nil { return nil } let tempPoolType = PoolingType(rawValue: poolTypeValue!) if (tempPoolType == nil) { return nil } poolType = tempPoolType! // Get the dimension let dimensionValue = fromDictionary["dimension"] as? NSInteger if dimensionValue == nil { return nil } dimension = dimensionValue! // Get the reduction levels let tempArray = getIntArray(fromDictionary, identifier: "reductionLevels") if (tempArray == nil) { return nil } reductionLevels = tempArray! resultSize = DeepChannelSize(dimensionCount: dimension, dimensionValues: reductionLevels) } public func setReductionLevel(_ forDimension: Int, newLevel: Int) { if (forDimension >= 0 && forDimension < dimension) { reductionLevels[forDimension] = newLevel } } public func getType() -> DeepNetworkOperatorType { return .poolingOperation } public func getDetails() -> String { var result : String switch poolType { case .average: result = "Avg [" case .minimum: result = "Min [" case .maximum: result = "Max [" } if (dimension > 0) { result += "\(reductionLevels[0])" } if (dimension > 1) { for i in 1..<dimension { result += ", \(reductionLevels[i])" } } result += "]" return result } public func getResultingSize(_ inputSize: DeepChannelSize) -> DeepChannelSize { // Reduce each of the dimensions by the specified reduction levels resultSize = inputSize for i in 0..<dimension { resultSize.dimensions[i] /= reductionLevels[i] } return resultSize } public func initializeParameters() { // No parameters to initialize in a pooling layer } public func feedForward(_ inputs: [Float], inputSize: DeepChannelSize) -> [Float] { self.inputSize = inputSize // Limit reduction to a 1 pixel value in each dimension var sourceSize = inputSize.dimensions sourceSize += [1, 1, 1] // Add size for missing dimensions var resultSize = inputSize.dimensions resultSize += [1, 1, 1] // Add size for missing dimensions var reduction = [Int](repeating: 1, count: 4) var sourceStride = [Int](repeating: 1, count: 4) var resultStride = [Int](repeating: 1, count: 4) var totalSize = 1 for index in 0..<dimension { reduction[index] = reductionLevels[index] if (inputSize.dimensions[index] < reduction[index]) { reduction[index] = inputSize.dimensions[index] } resultSize[index] = inputSize.dimensions[index] / reductionLevels[index] totalSize *= resultSize[index] } // Determine the stride for each dimension for index in 0..<4 { if (index > 0) { for i in 0..<index { sourceStride[index] *= sourceSize[i] } for i in 0..<index { resultStride[index] *= resultSize[i] } } } // Allocate the result array switch poolType { case .minimum: pool = [Float](repeating: Float.infinity, count: totalSize) inputUsed = [Int](repeating: 0, count: totalSize) case .maximum: pool = [Float](repeating: -Float.infinity, count: totalSize) inputUsed = [Int](repeating: 0, count: totalSize) case .average: pool = [Float](repeating: 0.0, count: totalSize) } // Reduce each dimension for w in 0..<resultSize[3] { let wResultStart = w * resultStride[3] for wGroup in 0..<reduction[3] { let wSourceStart = ((w*reduction[3] + wGroup) * sourceStride[3]) for z in 0..<resultSize[2] { let zResultStart = wResultStart + (z * resultStride[2]) for zGroup in 0..<reduction[2] { let zSourceStart = wSourceStart + ((z*reduction[2] + zGroup) * sourceStride[2]) for y in 0..<resultSize[1] { let yResultStart = zResultStart + (y * resultStride[1]) for yGroup in 0..<reduction[1] { let ySourceStart = zSourceStart + ((y*reduction[1] + yGroup) * sourceStride[1]) for x in 0..<resultSize[0] { let resultIndex = yResultStart + x let xSourceStart = ySourceStart + x*reduction[0] for xGroup in 0..<reduction[0] { let sourceIndex = xSourceStart + xGroup switch poolType { case .minimum: if (inputs[sourceIndex] < pool[resultIndex]) { pool[resultIndex] = inputs[sourceIndex] inputUsed![resultIndex] = sourceIndex } case .maximum: if (inputs[sourceIndex] > pool[resultIndex]) { pool[resultIndex] = inputs[sourceIndex] inputUsed![resultIndex] = sourceIndex } case .average: pool[resultIndex] += inputs[sourceIndex] } } } } } } } } } if (poolType == .average) { var totalCells = 1 for index in 0..<4 { totalCells *= reduction[index] } var multiplier : Float = 1.0 / Float(totalCells) vDSP_vsmul(pool, 1, &multiplier, &pool, 1, vDSP_Length(pool.count)) } return pool } public func getResults() -> [Float] { return pool } public func getResultSize() -> DeepChannelSize { return resultSize } public func getResultRange() ->(minimum: Float, maximum: Float) { // Result range is a function of the input range. Default to a value that will work, even if not optimum return (minimum: 0.0, maximum: 1.0) } public func startBatch() { // No weights in a pooling operation } // 𝟃E/𝟃h comes in, 𝟃E/𝟃x goes out public func backPropogateGradient(_ upStreamGradient: [Float]) -> [Float] { var downstreamGradient = [Float](repeating: 0.0, count: inputSize.totalSize) // If this is a minimum or maximum pooling, we have the use information to set the downstream gradient if (poolType != .average) { for sourceIndex in 0..<inputUsed!.count { downstreamGradient[inputUsed![sourceIndex]] = upStreamGradient[sourceIndex] } return downstreamGradient } // If average, the gradient just gets spread over the input space that was pooled // Get spread factor for each dimension var sourceSize = resultSize.dimensions sourceSize += [1, 1, 1] // Add size for missing dimensions var destSize = inputSize.dimensions destSize += [1, 1, 1] // Add size for missing dimensions let spreadW = destSize[3] / sourceSize[3] let spreadZ = destSize[2] / sourceSize[2] let spreadY = destSize[1] / sourceSize[1] let spreadX = destSize[0] / sourceSize[0] let multiplier = 1.0 / Float(spreadW * spreadZ * spreadY * spreadX) // Determine the stride for each dimension var sourceStride = [Int](repeating: 1, count: 4) var destStride = [Int](repeating: 1, count: 4) for index in 1..<4 { for i in 0..<index { sourceStride[index] *= sourceSize[i] } for i in 0..<index { destStride[index] *= destSize[i] } } // Spread each dimension var destIndex = 0 var wSourceStart = 0 for _ in 0..<sourceSize[3] { // Each source W for _ in 0..<spreadW { // Spread to each destination W var zSourceStart = wSourceStart for _ in 0..<sourceSize[2] { // Each source Z for _ in 0..<spreadZ { // Spread to each destination Z var ySourceStart = zSourceStart for _ in 0..<sourceSize[1] { // Each source Y for _ in 0..<spreadY { // Spread to each destination Y for x in 0..<sourceSize[0] { // Each source X let sourceIndex = ySourceStart + x for _ in 0..<spreadX { // Spread to each destination X downstreamGradient[destIndex] = upStreamGradient[sourceIndex] * multiplier destIndex += 1 } } } ySourceStart += sourceStride[1] } } zSourceStart += sourceStride[2] } } wSourceStart += sourceStride[3] } return downstreamGradient } public func updateWeights(_ trainingRate : Float, weightDecay: Float) { // No weights in a pooling operation } public func gradientCheck(ε: Float, Δ: Float, network: DeepNetwork) -> Bool { // No (stored) gradients in a pooling layer return true } public func getPersistenceDictionary() -> [String: AnyObject] { var resultDictionary : [String: AnyObject] = [:] // Set the pooling type resultDictionary["poolingType"] = poolType.rawValue as AnyObject? // Set the dimension resultDictionary["dimension"] = dimension as AnyObject? // Set the reduction levels resultDictionary["reductionLevels"] = reductionLevels as AnyObject? return resultDictionary } } #endif
38.267857
115
0.514155
6297e316ceaf50e640b256929d62496e558fc215
943
swift
Swift
Sources/ButterCMSSDK/helper/ISO8601DateFormatterHelper.swift
ButterCMS/buttercms-swift
010b7e8ba39793fe580445c0f59f5466f70e3fc8
[ "MIT" ]
null
null
null
Sources/ButterCMSSDK/helper/ISO8601DateFormatterHelper.swift
ButterCMS/buttercms-swift
010b7e8ba39793fe580445c0f59f5466f70e3fc8
[ "MIT" ]
null
null
null
Sources/ButterCMSSDK/helper/ISO8601DateFormatterHelper.swift
ButterCMS/buttercms-swift
010b7e8ba39793fe580445c0f59f5466f70e3fc8
[ "MIT" ]
1
2021-11-09T08:39:11.000Z
2021-11-09T08:39:11.000Z
// // ISO8601DateFormatterHelper.swift // ButterCMSSDK // // Created by Martin Srb on 05.08.2021. // // Swift can not automatically handle iso8601 dates with and without fractional seconds. import Foundation @available(iOS 11.0, macOS 10.13, tvOS 11.0, watchOS 4.0, *) extension ISO8601DateFormatter { convenience init(_ formatOptions: Options) { self.init() self.formatOptions = formatOptions } } extension Formatter { @available(iOS 11.0, macOS 10.13, tvOS 11.0, watchOS 4.0, *) static let iso8601withFractionalSeconds = ISO8601DateFormatter([.withInternetDateTime, .withFractionalSeconds]) @available(iOS 11.0, macOS 10.13, tvOS 11.0, watchOS 4.0, *) static let iso8601 = ISO8601DateFormatter([.withInternetDateTime]) @available(iOS 11.0, macOS 10.13, tvOS 11.0, watchOS 4.0, *) static let iso8601DateTime = ISO8601DateFormatter([.withFullDate, .withTime, .withColonSeparatorInTime]) }
34.925926
115
0.724284
2a3c88296b4eb8fcc5a627828b853039afcf1aa0
424
ps1
PowerShell
Chapter-4/webhook-runbook.ps1
srmchem/Azure-for-Architects-Third-Edition
d4f3d8bb45ed69738de6fe41c03f633753ed2dbc
[ "MIT" ]
23
2020-04-05T09:00:37.000Z
2022-03-13T02:17:09.000Z
Chapter-4/webhook-runbook.ps1
srmchem/Azure-for-Architects-Third-Edition
d4f3d8bb45ed69738de6fe41c03f633753ed2dbc
[ "MIT" ]
1
2021-09-25T19:27:11.000Z
2021-09-25T19:27:11.000Z
Chapter-4/webhook-runbook.ps1
srmchem/Azure-for-Architects-Third-Edition
d4f3d8bb45ed69738de6fe41c03f633753ed2dbc
[ "MIT" ]
31
2020-07-05T00:30:21.000Z
2022-02-28T02:33:09.000Z
param( [parameter(mandatory=$true)] [object] $WebhookData ) $webhookname = $WebhookData.WebhookName $headers = $WebhookData.RequestHeader $body = $WebhookData.RequestBody Write-output "webhook header data" Write-Output $webhookname Write-output $headers.message Write-output $headers.subject $connectionname = (ConvertFrom-Json -InputObject $body) ./connectAzure.ps1 -connectionName $connectionname[0].name
20.190476
115
0.768868
80322be7333f478895d2c86031674d13673e7320
947
lua
Lua
github/markdown.lua
czfshine/luagy
5e26e94b73b956c12e15c74e860c584b88aa5eda
[ "MIT" ]
2
2015-06-11T12:27:10.000Z
2020-10-30T10:17:10.000Z
github/markdown.lua
czfshine/luagy
5e26e94b73b956c12e15c74e860c584b88aa5eda
[ "MIT" ]
null
null
null
github/markdown.lua
czfshine/luagy
5e26e94b73b956c12e15c74e860c584b88aa5eda
[ "MIT" ]
1
2020-10-30T10:19:33.000Z
2020-10-30T10:19:33.000Z
-- load the http module http = require("socket.http") ltn12 = require("ltn12") ltn12. -- Requests information about a document, without downloading it. -- Useful, for example, if you want to display a download gauge and need -- to know the size of the document in advance t={} r, c, h = http.request { method = "POST", url = "https://api.github.com/markdown?text=1", source=ltn12.source.string("?text=1"), sink = ltn12.sink.table(t) } print(c) print(r) require"luagy.print.printtable" ptt(h) ptt(t) -- r is 1, c is 200, and h would return the following headers: -- h = { -- date = "Tue, 18 Sep 2001 20:42:21 GMT", -- server = "Apache/1.3.12 (Unix) (Red Hat/Linux)", -- ["last-modified"] = "Wed, 05 Sep 2001 06:11:20 GMT", -- ["content-length"] = 15652, -- ["connection"] = "close", -- ["content-Type"] = "text/html" -- } {"text": "Hello world github/linguist#1 **cool**, and #1!","mode": "gfm","context": "github/gollum"}
27.852941
100
0.637804
f4654186019bb253f672d4c0e09fe450f5cabb35
1,620
sql
SQL
schema.sql
joyliao07/lab-08-back-end
1be5d976975d0caf34a3ab7b0a417809ef02634c
[ "MIT" ]
null
null
null
schema.sql
joyliao07/lab-08-back-end
1be5d976975d0caf34a3ab7b0a417809ef02634c
[ "MIT" ]
1
2018-09-22T21:47:48.000Z
2018-09-22T21:47:48.000Z
schema.sql
joyliao07/lab-08-back-end
1be5d976975d0caf34a3ab7b0a417809ef02634c
[ "MIT" ]
null
null
null
DROP TABLE locations, weathers, yelps, movies, meetups; CREATE TABLE IF NOT EXISTS locations ( id SERIAL PRIMARY KEY, search_query VARCHAR(255), formatted_query VARCHAR(255), latitude NUMERIC(8, 6), longitude NUMERIC(9, 6), created_at BIGINT ); CREATE TABLE IF NOT EXISTS weathers ( id SERIAL PRIMARY KEY, forecast VARCHAR(255), time VARCHAR(255), created_at BIGINT, location_id INTEGER NOT NULL REFERENCES locations(id) ); CREATE TABLE IF NOT EXISTS yelps ( id SERIAL PRIMARY KEY, name VARCHAR (255), image_url TEXT, price VARCHAR (10), rating NUMERIC(2, 1), url TEXT, created_at BIGINT, location_id INTEGER NOT NULL REFERENCES locations(id) ); CREATE TABLE IF NOT EXISTS movies ( id SERIAL PRIMARY KEY, title VARCHAR (255), overview TEXT, average_votes NUMERIC(2,1), total_votes SMALLINT, image_url TEXT, popularity NUMERIC (6, 3), released_on VARCHAR (10), created_at BIGINT, location_id INTEGER NOT NULL REFERENCES locations(id) ); CREATE TABLE IF NOT EXISTS meetups ( id SERIAL PRIMARY KEY, link TEXT, name VARCHAR (255), creation_date VARCHAR (10), host TEXT, created_at BIGINT, location_id INTEGER NOT NULL REFERENCES locations(id) ); CREATE TABLE IF NOT EXISTS trails ( id SERIAL PRIMARY KEY, name VARCHAR (255), location TEXT, stars NUMERIC(2, 1), star_votes TEXT, summary TEXT, trail_url TEXT, conditions TEXT, condition_date TEXT, condition_time TEXT, created_at BIGINT, location_id INTEGER NOT NULL REFERENCES locations(id) );
24.179104
57
0.696296
039cc9ec997223c8686aa3b6d452952edf6b80b4
4,546
ps1
PowerShell
src/Get-EwsFolder.ps1
junecastillote/EWS.PS
97fde5330edede099d05b0fe60738c3326a3fd7c
[ "MIT" ]
null
null
null
src/Get-EwsFolder.ps1
junecastillote/EWS.PS
97fde5330edede099d05b0fe60738c3326a3fd7c
[ "MIT" ]
null
null
null
src/Get-EwsFolder.ps1
junecastillote/EWS.PS
97fde5330edede099d05b0fe60738c3326a3fd7c
[ "MIT" ]
null
null
null
Function Get-EwsFolder { [CmdletBinding(DefaultParameterSetName='Default')] param ( [parameter(Mandatory,ParameterSetName='Default')] [parameter(Mandatory,ParameterSetName='byFolderName')] [parameter(Mandatory,ParameterSetName='byFolderID')] [ValidateNotNullOrEmpty()] $Token, [parameter(Mandatory,ParameterSetName='Default')] [parameter(Mandatory,ParameterSetName='byFolderName')] [parameter(Mandatory,ParameterSetName='byFolderID')] [ValidateNotNullOrEmpty()] [string]$MailboxAddress, [parameter(Mandatory,ParameterSetName='Default')] [parameter(Mandatory,ParameterSetName='byFolderName')] [parameter(Mandatory,ParameterSetName='byFolderID')] [ValidateSet('Primary', 'Archive')] [string]$MailboxType, [parameter(Mandatory,ParameterSetName='byFolderName')] [ValidateNotNullOrEmpty()] [string]$FolderName, [parameter(Mandatory,ParameterSetName='byFolderID')] [ValidateNotNullOrEmpty()] [string]$FolderID ) ## Check registry if EWS Managed API is installed $EwsDLL = (($(Get-ItemProperty -ErrorAction SilentlyContinue -Path Registry::$(Get-ChildItem -ErrorAction SilentlyContinue -Path 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Exchange\Web Services' | Sort-Object Name -Descending | Select-Object -First 1 -ExpandProperty Name)).'Install Directory') + "Microsoft.Exchange.WebServices.dll") if (!($EwsDLL) -or !(Test-Path $EwsDLL)) { Write-Error "The EWS Managed API is not found. Go to https://www.microsoft.com/en-us/download/details.aspx?id=42951 to download and install." Return $null } ## Import the EWS Managed API Module Import-Module -Name $EwsDLL -ErrorAction Stop ## Create the EWS Object $Service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService -ArgumentList 'Exchange2013_SP1' ## Exchange Online EWS URL $Service.Url = 'https://outlook.office365.com/EWS/Exchange.asmx' ## EWS Authentication $Service.UseDefaultCredentials = $false $Service.Credentials = New-Object Microsoft.Exchange.WebServices.Data.OAuthCredentials -ArgumentList ($Token.AccessToken) ## Who are we impersonating? $service.ImpersonatedUserId = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxAddress); ## We're impersonating, so we need to anchor to the target mailbox ## https://docs.microsoft.com/en-us/exchange/client-developer/exchange-web-services/impersonation-and-ews-in-exchange#performance-considerations-for-ews-impersonation $service.HttpHeaders.Add('X-AnchorMailbox', $MailboxAddress) ## If the target mailbox is Primary, get the Primary Mailbox Folders if ($MailboxType -eq 'Primary') { $ConnectToMailboxRootFolders = New-Object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.Webservices.Data.WellKnownFolderName]::MsgFolderRoot, $MailboxAddress) } ## If the target mailbox is Archive, get the Archive Mailbox Folders elseif ($MailboxType -eq 'Archive') { $ConnectToMailboxRootFolders = New-Object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.Webservices.Data.WellKnownFolderName]::ArchiveMsgFolderRoot, $MailboxAddress) } ## Bind the mailbox folders $EWSParentFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service, $ConnectToMailboxRootFolders) ## Create the FolderView $FolderView = New-Object Microsoft.Exchange.WebServices.Data.FolderView(1000) $FolderView.Traversal = [Microsoft.Exchange.WebServices.Data.FolderTraversal]::Deep ## If -FolderName is specified, look for the said folder using its DisplayName if ($FolderName) { $SearchFilter = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName, $FolderName) $MailboxFolderList = $EWSParentFolder.FindFolders($SearchFilter, $FolderView) } ## If -FolderID is specified, get all folders and filter to look for the said folder using its ID elseif ($FolderID) { $MailboxFolderList = ($EWSParentFolder.FindFolders($FolderView) | Where-Object {$_.ID -eq $FolderID}) } ## If -FolderName and -FolderID are NOT specified, get ALL folders else { $MailboxFolderList = $EWSParentFolder.FindFolders($FolderView) } return $MailboxFolderList }
49.956044
344
0.729652
ebb40ae74ebf3e99750f643a13e798dce6f40f89
1,291
lua
Lua
config/nvim/lua/telescopes.lua
empun/dotfiles
8891b851c66b8c8907320bb2cc11c49186b168fd
[ "MIT" ]
1
2021-11-13T03:31:06.000Z
2021-11-13T03:31:06.000Z
config/nvim/lua/telescopes.lua
empun/dotfiles
8891b851c66b8c8907320bb2cc11c49186b168fd
[ "MIT" ]
null
null
null
config/nvim/lua/telescopes.lua
empun/dotfiles
8891b851c66b8c8907320bb2cc11c49186b168fd
[ "MIT" ]
null
null
null
local map = require 'map' local opts = { noremap = true, silent = true } local telescope = require 'telescope' telescope.setup { extensions = { project = { base_dirs = { { path = '~/REPO', max_depth = 4 }, }, hidden_files = true, -- default: false }, }, defaults = { preview = false, prompt_prefix = '▶ ', selection_caret = '▶ ', layout_config = { horizontal = { preview_width = 0.5 } }, file_ignore_patterns = { 'node_modules/.*', '%.env' }, }, pickers = { file_browser = { theme = 'dropdown' }, find_files = { theme = 'dropdown' }, live_grep = { theme = 'dropdown' }, buffers = { theme = 'dropdown' }, help_tags = { theme = 'dropdown' }, }, } map('n', ';;', ":lua require'telescope'.extensions.project.project{ display_type = 'full' }<CR>", opts) map('n', ';a', "<cmd> lua require('telescope.builtin').file_browser{ cwd = vim.fn.expand('%:p:h')}<cr>", opts) map( 'n', '<c-p>', "<cmd> lua require('telescope.builtin').find_files({find_command = {'rg', '--files', '--hidden', '-g', '!.git'}})<cr>", opts ) map('n', '<c-b>', "<cmd> lua require('telescope.builtin').buffers({ show_all_buffers = true })<cr>", opts) map('n', '<c-g>', "<cmd> lua require('telescope.builtin').live_grep()<cr>", opts)
32.275
121
0.572424
e63b448eec2a5eb7280c9ee7767de2c72a58e8c1
1,300
go
Go
application.go
yunzujia/mango
81f67a800f1e2602f0e137b3242c73911d0362a9
[ "MIT" ]
null
null
null
application.go
yunzujia/mango
81f67a800f1e2602f0e137b3242c73911d0362a9
[ "MIT" ]
null
null
null
application.go
yunzujia/mango
81f67a800f1e2602f0e137b3242c73911d0362a9
[ "MIT" ]
1
2018-12-14T08:20:06.000Z
2018-12-14T08:20:06.000Z
package mango import ( "fmt" "net/http" "os" "os/signal" "runtime" ) var ( CookieSecret = "fLjUfxqXtfNoIldA0A0J" Debug = false ) type Application struct { Addr string Port int Url map[string]map[string]Handler StaticPath string TemplatePath string Debug bool PreHandler Handler NotFoundHandler Handler ErrorHandler Handler } func (app *Application) Run() { runtime.GOMAXPROCS(runtime.NumCPU()) http.Handle("/", NewRouter(app.Url, app.NotFoundHandler, app.ErrorHandler, app.PreHandler)) if app.StaticPath != "" { http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir(app.StaticPath)))) } if app.TemplatePath != "" { TemplateLoader(app.TemplatePath) } fmt.Printf("http://%s:%d\n", app.Addr, app.Port) root := "" if cwd, err := os.Getwd(); err != nil { panic(fmt.Sprintf("Error getting working directory: %s", err)) } else { root = cwd } Debug = app.Debug if app.Debug { start(app.Addr, app.Port, root) } else { go func() { err := http.ListenAndServe(fmt.Sprintf("%s:%d", app.Addr, app.Port), nil) if err != nil { fmt.Println("Failed to start server:", err) } }() ch := make(chan os.Signal) signal.Notify(ch, os.Interrupt, os.Kill) <-ch } }
20.967742
98
0.631538
fd36764761fd8e68aa1cfc4bc582774232a73874
9,207
sql
SQL
tests/data/example/sql/runs.sql
UMCU-RIBS/xelo2
e8b4133f5673579f3487965f8e76d1f6569c8326
[ "MIT" ]
null
null
null
tests/data/example/sql/runs.sql
UMCU-RIBS/xelo2
e8b4133f5673579f3487965f8e76d1f6569c8326
[ "MIT" ]
18
2020-01-27T08:44:07.000Z
2021-09-24T10:59:15.000Z
tests/data/example/sql/runs.sql
UMCU-RIBS/xelo2
e8b4133f5673579f3487965f8e76d1f6569c8326
[ "MIT" ]
null
null
null
CREATE TABLE `experimenters` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(256) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `name` (`name`) ) ; INSERT INTO `experimenters` (`name`) VALUES ('Gio'),('Ryder'); CREATE TABLE `runs` ( `id` int(11) NOT NULL AUTO_INCREMENT, `session_id` int(11) DEFAULT NULL, `task_name` text NOT NULL COMMENT "Task Name: Name of the task", `start_time` timestamp(3) NULL DEFAULT NULL COMMENT "Start Time: Clock time of the beginning of the task", `duration` float DEFAULT NULL COMMENT "Duration: Length of the recording in seconds", `xelo_stem` text DEFAULT NULL COMMENT "Xelo Stem: Name of the .xml xelo file associated with this run (without .xml)", `performance` text DEFAULT NULL COMMENT "Performance: How the patient performed. Legacy from xelo", `task_description` text DEFAULT NULL COMMENT "Task Description: Longer description of the task", `acquisition` text DEFAULT NULL COMMENT "Acquisition: Comments about data acquisition. Legacy from xelo", PRIMARY KEY (`id`), KEY `session_id` (`session_id`), CONSTRAINT `runs_ibfk_1` FOREIGN KEY (`session_id`) REFERENCES `sessions` (`id`) ON DELETE CASCADE ) ; INSERT INTO `allowed_values` VALUES ('runs','task_name','DTI'),('runs','task_name','MIQ'),('runs','task_name','P300'),('runs','task_name','abled'),('runs','task_name','action_selection'),('runs','task_name','angiography_scan'),('runs','task_name','animal'),('runs','task_name','audcomsent'),('runs','task_name','audcomword'),('runs','task_name','auditory_attention'),('runs','task_name','auditory_localizer'),('runs','task_name','bair_hrfpattern'),('runs','task_name','bair_prf'),('runs','task_name','bair_spatialobject'),('runs','task_name','bair_spatialpattern'),('runs','task_name','bair_temporalpattern'),('runs','task_name','bargrasp'),('runs','task_name','bci_cursor_control_attent'),('runs','task_name','bci_cursor_control_motor'),('runs','task_name','bci_cursor_control_taal'),('runs','task_name','bci_cursor_control_visual'),('runs','task_name','bci_cursor_control_wm'),('runs','task_name','boldfinger'),('runs','task_name','boldhand'),('runs','task_name','boldsat'),('runs','task_name','calc'),('runs','task_name','checkerboard'),('runs','task_name','chill'),('runs','task_name','clickaway'),('runs','task_name','count'),('runs','task_name','deleted'),('runs','task_name','divatt'),('runs','task_name','eccentricity_mapping'),('runs','task_name','emotion'),('runs','task_name','error_potential'),('runs','task_name','eye_task'),('runs','task_name','eyes_open_close'),('runs','task_name','faces_emotion'),('runs','task_name','faces_houses'),('runs','task_name','facial_expressions'),('runs','task_name','feedback_wm'),('runs','task_name','finger_mapping'),('runs','task_name','gestures'),('runs','task_name','instant_aud_recall'),('runs','task_name','knottask'),('runs','task_name','language'),('runs','task_name','letter_picture_matching'),('runs','task_name','line_bisection'),('runs','task_name','mario'),('runs','task_name','mental_rotation'),('runs','task_name','mickey_task'),('runs','task_name','mooney'),('runs','task_name','motionmapper'),('runs','task_name','motor'),('runs','task_name','mouth_movements'),('runs','task_name','move_imagine_rest'),('runs','task_name','move_three_conditions'),('runs','task_name','movi'),('runs','task_name','movie_watching'),('runs','task_name','movieben'),('runs','task_name','multi_localizer'),('runs','task_name','music'),('runs','task_name','natural_rest'),('runs','task_name','notask'),('runs','task_name','noun'),('runs','task_name','number'),('runs','task_name','numerosity'),('runs','task_name','phonemes'),('runs','task_name','picnam'),('runs','task_name','pokemotor'),('runs','task_name','polar_mapping'),('runs','task_name','portem'),('runs','task_name','pulse'),('runs','task_name','reading_task'),('runs','task_name','reference_scan'),('runs','task_name','rest'),('runs','task_name','retinotopic_map'),('runs','task_name','rotating_sphere'),('runs','task_name','rotmotion'),('runs','task_name','saccade'),('runs','task_name','sendkeys'),('runs','task_name','single_words'),('runs','task_name','sleep'),('runs','task_name','smartbrain'),('runs','task_name','soc_patterns'),('runs','task_name','somatosensory'),('runs','task_name','sternberg'),('runs','task_name','stimulation'),('runs','task_name','story'),('runs','task_name','sweeptone'),('runs','task_name','switchspeed'),('runs','task_name','syllables'),('runs','task_name','t1_anatomy_scan'),('runs','task_name','t2_anatomy_scan'),('runs','task_name','t2star_anatomy_scan'),('runs','task_name','threshold'),('runs','task_name','tongue_movements'),('runs','task_name','touchy'),('runs','task_name','vardy_beeps'),('runs','task_name','verb'),('runs','task_name','verb_it'),('runs','task_name','visual_attention'),('runs','task_name','visual_field_map'),('runs','task_name','visual_left_right_map'),('runs','task_name','visual_speed_task'),('runs','task_name','visual_task_Serge'),('runs','task_name','visual_up_down_map'),('runs','task_name','vowels'),('runs','task_name','woezel_pip'),('runs','task_name','NOTE'),('runs','task_name','bair_finger_mapping'),('runs','task_name','ct_anatomy_scan'),('runs','task_name','flair_anatomy_scan'),('runs','task_name','frontal_eye_field'),('runs','task_name','MP2RAGE'),('runs','task_name','pd_anatomy_scan'),('runs','task_name','pRF_alessio'),('runs','task_name','top_up'),('runs','task_name','vts_prf'),('runs','task_name','vts_temporalpattern'),('runs','task_name','sixcatlocisidiff'),('runs','task_name','sixcatloctemporal'); DELIMITER ;; CREATE TRIGGER validate_task_name_before_insert_to_runs BEFORE INSERT ON runs FOR EACH ROW BEGIN IF NEW.task_name IS NOT NULL AND BINARY NEW.task_name NOT IN ( SELECT allowed_value FROM allowed_values WHERE table_name = 'runs' AND column_name = 'task_name') THEN SIGNAL SQLSTATE '2201R' SET MESSAGE_TEXT = 'Entered value in column task_name is not allowed in table runs'; END IF; END ;; CREATE TRIGGER validate_task_name_before_update_to_runs BEFORE UPDATE ON runs FOR EACH ROW BEGIN IF NEW.task_name IS NOT NULL AND BINARY NEW.task_name NOT IN ( SELECT allowed_value FROM allowed_values WHERE table_name = 'runs' AND column_name = 'task_name') THEN SIGNAL SQLSTATE '2201R' SET MESSAGE_TEXT = 'Entered value in column task_name is not allowed in table runs'; END IF; END ;; DELIMITER ; CREATE TABLE `intended_for` ( `run_id` int(11) DEFAULT NULL COMMENT 'ID of runs table: this should point to the original task (top_up)', `target` int(11) DEFAULT NULL COMMENT 'Target: this should point to the "intended-for" task (bold task)', KEY `run_id` (`run_id`), KEY `target` (`target`), CONSTRAINT `intended_for_ibfk_1` FOREIGN KEY (`run_id`) REFERENCES `runs` (`id`) ON DELETE CASCADE, CONSTRAINT `intended_for_ibfk_2` FOREIGN KEY (`target`) REFERENCES `runs` (`id`) ON DELETE CASCADE ) ; CREATE TABLE `runs_experimenters` ( `run_id` int(11) DEFAULT NULL, `experimenter_id` int(11) DEFAULT NULL, UNIQUE KEY `runs_experimenters_unique` (`run_id`,`experimenter_id`), KEY `experimenter_id` (`experimenter_id`), CONSTRAINT `runs_experimenters_ibfk_1` FOREIGN KEY (`run_id`) REFERENCES `runs` (`id`) ON DELETE CASCADE, CONSTRAINT `runs_experimenters_ibfk_2` FOREIGN KEY (`experimenter_id`) REFERENCES `experimenters` (`id`) ON DELETE CASCADE ) ; CREATE TABLE `runs_protocols` ( `run_id` int(11) DEFAULT NULL, `protocol_id` int(11) DEFAULT NULL, UNIQUE KEY `runs_protocols_unique` (`run_id`,`protocol_id`), KEY `protocol_id` (`protocol_id`), CONSTRAINT `runs_protocols_ibfk_1` FOREIGN KEY (`run_id`) REFERENCES `runs` (`id`) ON DELETE CASCADE, CONSTRAINT `runs_protocols_ibfk_2` FOREIGN KEY (`protocol_id`) REFERENCES `protocols` (`id`) ON DELETE CASCADE ) ; CREATE TABLE `events` ( `run_id` int(11) DEFAULT NULL, `onset` float DEFAULT NULL COMMENT 'Onset: Onset (in seconds) of the event measured from the beginning of the acquisition of the first volume in the corresponding task imaging data file. Negative numbers in "onset" are allowed.', `duration` float DEFAULT NULL COMMENT 'Duration: Duration of the event (measured from onset) in seconds. Must always be either zero or positive. A "duration" value of zero implies that the delta function or event is so short as to be effectively modeled as an impulse.', `trial_type` text DEFAULT NULL COMMENT 'Trial Type: Primary categorisation of each trial to identify them as instances of the experimental conditions. e.g. for a response inhibition task, it could take on values "go" and "no-go" to refer to response initiation and response inhibition experimental conditions.', `response_time` text DEFAULT NULL COMMENT 'Response Time: Response time measured in seconds. A negative response time can be used to represent preemptive responses and "n/a" denotes a missed response.', `value` text DEFAULT NULL COMMENT 'Value: Marker value associated with the event (e.g., the value of a TTL trigger that was recorded at the onset of the event).', KEY `run_id` (`run_id`), CONSTRAINT `events_ibfk_1` FOREIGN KEY (`run_id`) REFERENCES `runs` (`id`) ON DELETE CASCADE ) ;
93.94898
4,386
0.719453
f07d5c996cff48d3e4ce4edaac97743f3de1a7ce
171
py
Python
src/ihtt/__init__.py
dekoza/i-hate-time-tracking
adb6018b56c836317535f2e2346dfb8d9cce3aac
[ "Apache-2.0" ]
null
null
null
src/ihtt/__init__.py
dekoza/i-hate-time-tracking
adb6018b56c836317535f2e2346dfb8d9cce3aac
[ "Apache-2.0" ]
null
null
null
src/ihtt/__init__.py
dekoza/i-hate-time-tracking
adb6018b56c836317535f2e2346dfb8d9cce3aac
[ "Apache-2.0" ]
null
null
null
""" I Hate Time Tracking package. Get time tracking out of your way. """ from typing import List __all__: List[str] = [] # noqa: WPS410 (the only __variable__ we use)
17.1
70
0.695906
4095e7fc9ea16c98def0023de886ecdb6252a178
981
py
Python
bson-exports-in-xamarin/scripts/build/libbson-android/build_android_cmn.py
andywyatte17/csharp-experiments
6ba2b7bda463baccdbd98e53eaacd9d627d42906
[ "MIT" ]
null
null
null
bson-exports-in-xamarin/scripts/build/libbson-android/build_android_cmn.py
andywyatte17/csharp-experiments
6ba2b7bda463baccdbd98e53eaacd9d627d42906
[ "MIT" ]
null
null
null
bson-exports-in-xamarin/scripts/build/libbson-android/build_android_cmn.py
andywyatte17/csharp-experiments
6ba2b7bda463baccdbd98e53eaacd9d627d42906
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 import sys, os from os.path import join import subprocess from datetime import datetime import glob from pprint import pprint HERE = os.path.dirname(os.path.realpath(__file__)) def Build(so_result_location, log_file_name, conan_docker_name): os.chdir(HERE) slash = join(".", ".").replace('.', '') with open(log_file_name, "w") as f: f.write( datetime.now().strftime("%d/%m/%Y %H:%M:%S") ) docker_script = \ ["docker", "run", "-v", os.getcwd() + slash + ":/host/", "-v", so_result_location + ":/result/", "--rm", conan_docker_name, "/bin/sh", "-c", "sh /host/build-script.sh" ] pprint(docker_script) docker_run = subprocess.run(docker_script) for stream in (docker_run.stdout, docker_run.stderr): if stream==None: continue s = stream.decode('utf-8') print(s) f.write(s) f.write( datetime.now().strftime("%d/%m/%Y %H:%M:%S") )
27.25
64
0.598369
c8094b11a556ba021359dca9a508ca1ce651f765
743
swift
Swift
MinimedKitTests/Messages/ReadCurrentGlucosePageMessageBodyTests.swift
jbayart/rileylink_ios
bfcc69346631a22f44d2e42f447c5b067e66766b
[ "MIT" ]
137
2021-03-31T15:38:38.000Z
2022-03-27T14:26:55.000Z
MinimedKitTests/Messages/ReadCurrentGlucosePageMessageBodyTests.swift
jbayart/rileylink_ios
bfcc69346631a22f44d2e42f447c5b067e66766b
[ "MIT" ]
312
2015-08-18T14:37:54.000Z
2022-03-17T11:57:46.000Z
MinimedKitTests/Messages/ReadCurrentGlucosePageMessageBodyTests.swift
jbayart/rileylink_ios
bfcc69346631a22f44d2e42f447c5b067e66766b
[ "MIT" ]
230
2015-08-22T06:52:34.000Z
2022-01-30T23:21:18.000Z
// // ReadCurrentGlucosePageMessageBodyTests.swift // RileyLink // // Created by Timothy Mecklem on 10/19/16. // Copyright © 2016 Pete Schwamb. All rights reserved. // import XCTest @testable import MinimedKit class ReadCurrentGlucosePageMessageBodyTests: XCTestCase { func testResponseInitializer() { var responseData = Data(hexadecimalString: "0000000D6100100020")! responseData.append(contentsOf: [UInt8](repeating: 0, count: 65 - responseData.count)) let messageBody = ReadCurrentGlucosePageMessageBody(rxData: responseData)! XCTAssertEqual(messageBody.pageNum, 3425) XCTAssertEqual(messageBody.glucose, 16) XCTAssertEqual(messageBody.isig, 32) } }
28.576923
94
0.709287
b3edacfab748b22448ac527e4fdb2f0116d24d34
1,455
ps1
PowerShell
automatic/flightgear/update.ps1
tunisiano187/chocolatey-coreteampackages
7d4cb3536f200d4013abe8db03042a029eb7763c
[ "Apache-2.0" ]
145
2019-04-26T10:14:58.000Z
2021-08-18T04:51:09.000Z
automatic/flightgear/update.ps1
tunisiano187/chocolatey-coreteampackages
7d4cb3536f200d4013abe8db03042a029eb7763c
[ "Apache-2.0" ]
524
2019-04-24T13:28:52.000Z
2021-10-13T05:43:25.000Z
automatic/flightgear/update.ps1
tunisiano187/chocolatey-coreteampackages
7d4cb3536f200d4013abe8db03042a029eb7763c
[ "Apache-2.0" ]
180
2019-04-24T13:23:39.000Z
2021-10-12T20:11:16.000Z
import-module au # We can't use https for the url, otherwise powershell throws an error and closes the window. # Oddly it works when choco auto redirects http to https $downloads = 'https://sourceforge.net/projects/flightgear/files' $changelog = 'http://wiki.flightgear.org/Changelog_' $versions = 'http://www.flightgear.org/' function global:au_SearchReplace { @{ ".\tools\chocolateyInstall.ps1" = @{ "(?i)(^\s*url\s*=\s*)('.*')" = "`$1'$($Latest.URL32)'" "(?i)(^[$]version\s*=\s*)('.*')" = "`$1'$($Latest.RemoteVersion)'" } ".\$($Latest.PackageName).nuspec" = @{ "(?i)(\<releaseNotes\>).*(\<\/releaseNotes\>)" = "`$1$($Latest.ReleaseNotes)`$2" } } } function global:au_GetLatest { $version_page = Invoke-WebRequest -UseBasicParsing -Uri $versions $re = "(?i)Current stable release: (?<stable>[0-9\.]+)" if($version_page.Content -match $re) { $version = $Matches.stable $short_version = $version.Substring(0, $version.LastIndexOf(".")) } else { throw "Cannot obtain the latest version from FlightGear's homepage, please update the `"update.ps1`" script." } $url = "$downloads/release-$short_version/FlightGear-$version.exe/download" $releaseNotes = "$changelog$short_version" @{ URL32 = $url Version = $version RemoteVersion = $version ReleaseNotes = $releaseNotes } } update -ChecksumFor none
31.630435
114
0.619244
2e9cf6ef8888da255be8fddd6bc5a691a281c292
5,994
asm
Assembly
Transynther/x86/_processed/US/_zr_/i7-8650U_0xd2_notsx.log_325_1172.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
9
2020-08-13T19:41:58.000Z
2022-03-30T12:22:51.000Z
Transynther/x86/_processed/US/_zr_/i7-8650U_0xd2_notsx.log_325_1172.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
1
2021-04-29T06:29:35.000Z
2021-05-13T21:02:30.000Z
Transynther/x86/_processed/US/_zr_/i7-8650U_0xd2_notsx.log_325_1172.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
3
2020-07-14T17:07:07.000Z
2022-03-21T01:12:22.000Z
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r11 push %r12 push %r14 push %r8 push %rcx push %rdi push %rsi lea addresses_WC_ht+0x18990, %r10 nop sub $57680, %r8 mov (%r10), %r14d nop and %rcx, %rcx lea addresses_normal_ht+0x336e, %rsi lea addresses_D_ht+0x1b190, %rdi nop nop nop nop nop add $35184, %r12 mov $108, %rcx rep movsb xor %rcx, %rcx lea addresses_normal_ht+0x17486, %r8 nop nop nop nop nop and %r12, %r12 mov (%r8), %ecx nop nop nop and $40680, %r8 lea addresses_A_ht+0x10f68, %rsi lea addresses_A_ht+0x101c4, %rdi nop nop add %r10, %r10 mov $12, %rcx rep movsq nop nop inc %rsi lea addresses_WC_ht+0x1c326, %rdi nop nop nop xor $21174, %rsi mov (%rdi), %r14d nop nop nop nop cmp $50028, %r8 lea addresses_WT_ht+0x7be8, %rdi nop nop inc %r12 movw $0x6162, (%rdi) nop nop cmp $15040, %rcx lea addresses_A_ht+0x1cf68, %rsi lea addresses_WT_ht+0xede8, %rdi nop nop cmp $3046, %r11 mov $99, %rcx rep movsb nop nop add %r11, %r11 lea addresses_D_ht+0xf168, %rdi nop nop nop sub %r14, %r14 mov $0x6162636465666768, %r12 movq %r12, %xmm6 movups %xmm6, (%rdi) cmp %r8, %r8 lea addresses_A_ht+0x10a12, %rsi lea addresses_WC_ht+0x4058, %rdi nop nop nop nop nop mfence mov $99, %rcx rep movsq nop nop nop nop inc %r8 lea addresses_UC_ht+0x1c068, %r11 clflush (%r11) nop nop nop inc %r10 movw $0x6162, (%r11) nop nop nop nop cmp $22285, %r12 lea addresses_WT_ht+0x1e368, %rcx nop nop nop nop nop dec %r8 movw $0x6162, (%rcx) nop nop nop nop nop sub $10318, %r11 lea addresses_D_ht+0x9da8, %rsi lea addresses_D_ht+0x111e0, %rdi sub %r12, %r12 mov $52, %rcx rep movsb nop nop nop xor %rsi, %rsi pop %rsi pop %rdi pop %rcx pop %r8 pop %r14 pop %r12 pop %r11 pop %r10 ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r14 push %r15 push %r8 push %rbp push %rdi // Load mov $0x53bb940000000098, %rbp nop nop xor $24790, %r14 movntdqa (%rbp), %xmm1 vpextrq $1, %xmm1, %r15 nop nop nop nop cmp %r11, %r11 // Store lea addresses_normal+0x1ed68, %r15 nop nop nop nop and $10348, %r10 mov $0x5152535455565758, %rdi movq %rdi, (%r15) and $47577, %r10 // Load lea addresses_WC+0x5268, %r10 nop nop and $16781, %rbp movups (%r10), %xmm7 vpextrq $1, %xmm7, %r8 nop nop nop nop nop dec %r14 // Store lea addresses_RW+0x45e8, %r10 sub $60328, %r15 movb $0x51, (%r10) // Exception!!! mov (0), %rbp nop nop nop nop nop add $65372, %r8 // Faulty Load lea addresses_US+0xff68, %rbp nop xor $35597, %r14 mov (%rbp), %r15w lea oracles, %r8 and $0xff, %r15 shlq $12, %r15 mov (%r8,%r15,1), %r15 pop %rdi pop %rbp pop %r8 pop %r15 pop %r14 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_US', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_NC', 'size': 16, 'AVXalign': False, 'NT': True, 'congruent': 2, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_normal', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 8, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WC', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 1, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_RW', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 6, 'same': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_US', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}} <gen_prepare_buffer> {'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 2, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 1, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 2, 'same': True}} {'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 9, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 2, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 1, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 6, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 11, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 7, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 9, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 1, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 4, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 7, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 9, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 3, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 0, 'same': False}} {'00': 325} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
23.598425
974
0.650484
e78d5dd3a943aa8d5bd515f349f0d7cc470bc295
2,000
kt
Kotlin
src/commonMain/kotlin/tz/co/asoft/result.ktx.kt
aSoft-Ltd/result
1ad2ccbb39c6f1d8b3f2e698fbd3572684c7ca57
[ "MIT" ]
1
2021-03-17T06:18:26.000Z
2021-03-17T06:18:26.000Z
src/commonMain/kotlin/tz/co/asoft/result.ktx.kt
aSoft-Ltd/result
1ad2ccbb39c6f1d8b3f2e698fbd3572684c7ca57
[ "MIT" ]
null
null
null
src/commonMain/kotlin/tz/co/asoft/result.ktx.kt
aSoft-Ltd/result
1ad2ccbb39c6f1d8b3f2e698fbd3572684c7ca57
[ "MIT" ]
1
2021-03-17T06:18:44.000Z
2021-03-17T06:18:44.000Z
@file:Suppress("NOTHING_TO_INLINE") package tz.co.asoft import kotlin.contracts.ExperimentalContracts import kotlin.contracts.contract inline val <T> Result<T>.status: ResultStatus get() = when (this) { is Either.Left -> ResultStatus.Success is Either.Right -> ResultStatus.Failure } inline fun <T> Result<T>.response(): T = when (this) { is Either.Left -> value is Either.Right -> throw Exception(value.error) } inline fun <T> Result<T>.responseOrNull(): T? = try { response() } catch (e: Exception) { null } inline fun <T> Result<T>.catch(handler: (Exception) -> Unit): Result<T> { if (this is Either.Right) { handler(Exception(value.error)) } return this } inline fun <T> Result<T>.collect(handler: (T) -> Unit) { if (this is Either.Left) { handler(value) } } inline fun <T> Success(value: T): Result<T> = Either.Left(value) inline fun <T> Result<T>.success() = left() inline fun <T> Result<T>.successOrNull() = leftOrNull() inline fun Result<*>.failure() = right() inline fun Result<*>.failureOrNull() = rightOrNull() inline fun <T> catching(block: () -> T): Result<T> = try { Either.Left(block()) } catch (e: Exception) { Either.Right(e.asFailure()) } inline fun Throwable.asFailure() = Failure( error = message ?: cause?.message ?: "Unknown Error", type = this::class.simpleName ?: "Unknown type", reason = cause?.message, stackTrace = cause?.cause?.message ) inline fun <T> Throwable.toFailure(): Result<T> = asFailure().toResult() inline fun <T> T.asSuccess(): Result<T> = Success(this) @OptIn(ExperimentalContracts::class) fun <T> Result<T>.isSuccess(): Boolean { contract { returns(true) implies (this@isSuccess is Either.Left) } return this is Either.Left } @OptIn(ExperimentalContracts::class) fun <T> Result<T>.isFailure(): Boolean { contract { returns(true) implies (this@isFailure is Either.Right) } return this is Either.Right }
25.974026
73
0.656