language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
499
1.84375
2
[]
no_license
package com.epc.web.facade.terdering.answer.handle; import lombok.Data; /** * <p>Description : 回复问题 * <p>Date : 2018-09-20 15:06 * <p>@Author : wjq */ @Data public class HandleReplyQuestion { /** * 回答内容 */ private String answer; /** * 问题ID */ private Long id; /** * 操作人ID */ private Long operateId; /** * 操作人姓名 */ private String operateName; private String answerPersonType; }
Java
UTF-8
9,019
2.546875
3
[ "BSD-3-Clause" ]
permissive
package qux.lang; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkElementIndex; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndex; import static java.util.Arrays.asList; import static java.util.Arrays.copyOf; import static java.util.Arrays.copyOfRange; import static qux.lang.Bool.FALSE; import static qux.lang.Bool.TRUE; import java.math.BigInteger; import qux.util.Iterable; import qux.util.Iterator; /** * TODO: Documentation * * @author Henry J. Wylde * @since 0.1.3 */ public final class Set extends AbstractObj implements Iterable { private AbstractObj[] data; private int count; private int refs; private Set() { data = new AbstractObj[10]; count = 0; } private Set(Set set) { data = set.data; count = set.count; // Lazily clone the data only when the first write is performed refs = 1; // Can't forget the fact that this set also references the prior set! set.refs++; } private Set(AbstractObj[] data) { this(); checkArgument(!asList(data).contains(null), "data cannot contain null"); for (AbstractObj datum : data) { add(datum); } } public AbstractObj _access_(Int index) { return get(index); } public Set _add_(Set set) { Set union = new Set(this); union.ensureCapacity(set._len_()); for (Iterator it = set._iter_(); it.hasNext() == TRUE; ) { union.add(it.next()); } return union; } /** * {@inheritDoc} */ @Override public Int _comp_(AbstractObj obj) { if (!(obj instanceof Set)) { return meta()._comp_(obj.meta()); } Set that = (Set) obj; Int comp = _len_()._comp_(that._len_()); if (!comp.equals(Int.ZERO)) { return comp; } Iterator thisIt = _iter_(); Iterator thatIt = that._iter_(); while (thisIt.hasNext() == TRUE) { comp = thisIt.next()._comp_(thatIt.next()); if (comp._eq_(Int.ZERO) == FALSE) { return comp; } } return Int.ZERO; } public Bool _contains_(AbstractObj obj) { return indexOf(obj) >= 0 ? TRUE : FALSE; } /** * {@inheritDoc} */ @Override public Str _desc_() { StringBuilder sb = new StringBuilder(); sb.append("{"); for (Iterator it = _iter_(); it.hasNext() == TRUE; ) { sb.append(it.next()._desc_()); if (it.hasNext() == TRUE) { sb.append(", "); } } sb.append("}"); return Str.valueOf(sb.toString()); } /** * {@inheritDocn} */ @Override public Set _dup_() { return new Set(this); } /** * {@inheritDoc} */ @Override public Bool _eq_(AbstractObj obj) { if (super._eq_(obj) == FALSE) { return FALSE; } Set that = (Set) obj; if (!_len_().equals(that._len_())) { return FALSE; } Iterator thisIt = _iter_(); Iterator thatIt = that._iter_(); while (thisIt.hasNext() == TRUE) { if (thisIt.next()._eq_(thatIt.next()) == FALSE) { return FALSE; } } return TRUE; } /** * {@inheritDoc} */ @Override public Int _hash_() { Int hash = Int.ZERO; for (Iterator it = _iter_(); it.hasNext() == TRUE; ) { hash = hash._add_(it.next()._hash_()); } return hash; } /** * {@inheritDoc} */ @Override public synchronized Iterator _iter_() { refs++; return new Iterator() { private AbstractObj[] data = Set.this.data; private int count = Set.this.count; private int index = 0; @Override public Bool hasNext() { if (index < count) { return TRUE; } // Check if the set is still the same, if it is we can decrement the refs count if (Set.this.data == data) { refs--; } return FALSE; } @Override public AbstractObj next() { return data[index++]; } }; } public Int _len_() { return Int.valueOf(count); } public Set _slice_(Int from, Int to) { return subset(from, to); } public Set _sub_(Set set) { Set difference = new Set(this); for (Iterator it = set._iter_(); it.hasNext() == TRUE; ) { difference.remove(it.next()); } return difference; } /** * {@inheritDoc} */ @Override public Meta meta() { Set types = new Set(); for (Iterator it = _iter_(); it.hasNext() == TRUE; ) { types.add(it.next().meta()); } // TODO: Normalise the set before the checks // The normalisation should happen in the Meta.forSet methods if (types.isEmpty() == TRUE) { return Meta.forSet(Meta.META_ANY); } if (types._len_().equals(Int.ONE)) { return Meta.forSet((Meta) types.data[0]); } return Meta.forSet(Meta.forUnion(types)); } public static Set valueOf(AbstractObj... data) { return new Set(data); } synchronized void add(AbstractObj obj) { checkNotNull(obj, "obj cannot be null"); checkRefs(); ensureCapacity(); int index = indexOf(obj); if (index >= 0) { return; } index = -index - 1; System.arraycopy(data, index, data, index + 1, count - index); data[index] = obj; count++; } AbstractObj get(Int index) { return get(index._value_()); } synchronized AbstractObj get(int index) { checkElementIndex(index, count); return data[index]; } AbstractObj get(BigInteger index) { checkArgument(index.bitLength() < 32, "sets of size larger than 32 bits is unsupported"); return get(index.intValue()); } Bool isEmpty() { return count == 0 ? TRUE : FALSE; } synchronized void remove(AbstractObj obj) { checkNotNull(obj, "obj cannot be null"); checkRefs(); int index = indexOf(obj); if (index < 0) { return; } System.arraycopy(data, index + 1, data, index, count - (index + 1)); count--; } Set subset(Int from, Int to) { return subset(from._value_(), to._value_()); } synchronized Set subset(int from, int to) { checkPositionIndex(from, count, "from"); checkPositionIndex(to, count, "to"); checkArgument(from <= to, "from must be less than or equal to to (from=%s, to=%s)", from, to); return valueOf(copyOfRange(data, from, to)); } Set subset(BigInteger from, BigInteger to) { checkArgument(from.bitLength() < 32, "sets of size larger than 32 bits is unsupported"); checkArgument(to.bitLength() < 32, "sets of size larger than 32 bits is unsupported"); return subset(from.intValue(), to.intValue()); } private synchronized void checkRefs() { if (refs > 0) { data = data.clone(); refs = 0; } } private synchronized void ensureCapacity() { ensureCapacity(1); } private synchronized void ensureCapacity(Int capacity) { ensureCapacity(capacity._value_()); } private synchronized void ensureCapacity(BigInteger capacity) { checkArgument(capacity.bitLength() < 32, "sets of size larger than 32 bits is unsupported"); ensureCapacity(capacity.intValue()); } private synchronized void ensureCapacity(int capacity) { checkArgument(capacity >= 0, "capacity must be non-negative"); while (count + capacity > data.length) { data = copyOf(data, data.length * 2); } } private synchronized int indexOf(AbstractObj obj) { return indexOf(obj, 0, count); } private synchronized int indexOf(AbstractObj obj, int low, int high) { if (low == high) { return -low - 1; } // Javas integer division rounds up, so let's force the truncation of the division // (emulates floor) int mid = (int) ((double) (low + high) / 2); if (obj.equals(data[mid])) { return mid; } else if (obj._comp_(data[mid])._lt_(Int.ZERO) == TRUE) { high = mid; } else { low = mid + 1; } return indexOf(obj, low, high); } }
Java
UTF-8
680
3
3
[]
no_license
package th.pocket.gems; public class FindOverlap { public static String findOverlap(String a, String b) { int[] flag = new int['z'-'A'+1]; StringBuilder result = new StringBuilder(); for(int i = 0; i < a.length(); i++) { flag[a.charAt(i) - 'A']++; } for(int i = 0; i < b.length(); i++) { if(flag[b.charAt(i) - 'A'] > 0) { result.append(b.charAt(i)); flag[b.charAt(i) - 'A']--; } } return result.toString(); } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Case 1:" + findOverlap("abcda", "aba")); System.out.println("Case 2:" + findOverlap("", "aaaa")); } }
C++
UTF-8
9,427
2.515625
3
[ "Apache-2.0" ]
permissive
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace facebook { namespace cachelib { namespace detail { // Object-cache's c++ allocator will need to create a zero refcount handle in // order to access CacheAllocator API. We don't need to have any refcount // pending for this, because the contract of ObjectCache is that user must // hold an outstanding refcount (via an ItemHandle or ObjectHandle) at any // time when they're accessing the data structures backed by the item. template <typename ItemHandle, typename Item, typename Cache> ItemHandle* objcacheInitializeZeroRefcountHandle(void* handleStorage, Item* it, Cache& alloc) { return new (handleStorage) typename Cache::ItemHandle{it, alloc}; } // Object-cache's c++ allocator needs to access CacheAllocator directly from // an item handle in order to access CacheAllocator APIs template <typename ItemHandle2> typename ItemHandle2::CacheT& objcacheGetCache(const ItemHandle2& hdl) { return hdl.getCache(); } } // namespace detail namespace objcache { template <typename Impl, typename CacheDescriptor> void* AllocatorResource<Impl, CacheDescriptor>::allocateFallback( size_t bytes, size_t alignment) { switch (alignment) { default: return std::allocator<uint8_t>{}.allocate(bytes); case std::alignment_of<uint16_t>(): return std::allocator<uint16_t>{}.allocate(bytes); case std::alignment_of<uint32_t>(): return std::allocator<uint32_t>{}.allocate(bytes); case std::alignment_of<uint64_t>(): return std::allocator<uint64_t>{}.allocate(bytes); case std::alignment_of<std::max_align_t>(): return std::allocator<std::max_align_t>{}.allocate(bytes); } } template <typename Impl, typename CacheDescriptor> void AllocatorResource<Impl, CacheDescriptor>::deallocateFallback( void* alloc, size_t bytes, size_t alignment) { switch (alignment) { default: std::allocator<uint8_t>{}.deallocate(reinterpret_cast<uint8_t*>(alloc), bytes); break; case std::alignment_of<uint16_t>(): std::allocator<uint16_t>{}.deallocate(reinterpret_cast<uint16_t*>(alloc), bytes); break; case std::alignment_of<uint32_t>(): std::allocator<uint32_t>{}.deallocate(reinterpret_cast<uint32_t*>(alloc), bytes); break; case std::alignment_of<uint64_t>(): std::allocator<uint64_t>{}.deallocate(reinterpret_cast<uint64_t*>(alloc), bytes); break; case std::alignment_of<std::max_align_t>(): std::allocator<std::max_align_t>{}.deallocate( reinterpret_cast<std::max_align_t*>(alloc), bytes); break; } } template <typename CacheDescriptor> void MonotonicBufferResource<CacheDescriptor>::deallocateImpl( void* /* alloc */, size_t bytes, size_t /* alignment */) { getMetadata()->usedBytes -= bytes; // Do not deallocate since we don't reuse any previously freed bytes } template <typename CacheDescriptor> void* MonotonicBufferResource<CacheDescriptor>::allocateImpl(size_t bytes, size_t alignment) { auto* alloc = allocateFast(bytes, alignment); if (!alloc) { return allocateSlow(bytes, alignment); } return alloc; } template <typename CacheDescriptor> void* MonotonicBufferResource<CacheDescriptor>::allocateFast(size_t bytes, size_t alignment) { auto* metadata = getMetadata(); if (metadata->remainingBytes < bytes) { return nullptr; } alignment = alignment >= std::alignment_of<std::max_align_t>() ? std::alignment_of<std::max_align_t>() : alignment; auto alloc = reinterpret_cast<uintptr_t>(metadata->buffer); auto alignedAlloc = (alloc + alignment - 1) / alignment * alignment; size_t padding = alignedAlloc - alloc; size_t allocBytes = bytes + padding; if (metadata->remainingBytes < allocBytes) { return nullptr; } metadata->usedBytes += allocBytes; metadata->buffer += allocBytes; metadata->remainingBytes -= allocBytes; return reinterpret_cast<void*>(alignedAlloc); } template <typename CacheDescriptor> void* MonotonicBufferResource<CacheDescriptor>::allocateSlow(size_t bytes, size_t alignment) { // Minimal new buffer size is 2 times the requested size for now constexpr uint32_t kNewBufferSizeFactor = 2; uint32_t newBufferSize = std::max(getMetadata()->usedBytes * 2, static_cast<uint32_t>(bytes) * kNewBufferSizeFactor); newBufferSize = std::min(newBufferSize, static_cast<uint32_t>(Slab::kSize) - 1000); // The layout in our chained item is as follows. // // |-header-|-key-|-GAP-|-storage-| // // The storage always start at aligned boundary alignment = alignment >= std::alignment_of<std::max_align_t>() ? std::alignment_of<std::max_align_t>() : alignment; // Key is 4 bytes for chained item because it is a compressed pointer uint32_t itemTotalSize = sizeof(ChainedItem) + 4 + newBufferSize; // We may have to add 8 bytes additional to an item if our alignment // is larger than 8 bytes boundary (which means 16 bytes aka std::max_align_t) uint32_t alignedItemTotalSize = alignment > std::alignment_of<uint64_t>() ? util::getAlignedSize(itemTotalSize + 8, alignment) : util::getAlignedSize(itemTotalSize, alignment); uint32_t extraBytes = alignedItemTotalSize - itemTotalSize; auto chainedItemHandle = detail::objcacheGetCache(*this->hdl_) .allocateChainedItem(*this->hdl_, newBufferSize + extraBytes); if (!chainedItemHandle) { throw exception::ObjectCacheAllocationError( folly::sformat("Slow Path. Failed to allocate a chained item. " "Requested size: {}. Associated Item: {}", newBufferSize, (*this->hdl_)->toString())); } uintptr_t bufferStart = reinterpret_cast<uintptr_t>(chainedItemHandle->getMemory()); uintptr_t alignedBufferStart = (bufferStart + (alignment - 1)) / alignment * alignment; detail::objcacheGetCache(*this->hdl_) .addChainedItem(*this->hdl_, std::move(chainedItemHandle)); auto* metadata = getMetadata(); uint8_t* alloc = reinterpret_cast<uint8_t*>(alignedBufferStart); metadata->usedBytes += bytes; metadata->buffer = alloc + bytes; metadata->remainingBytes = newBufferSize - bytes; return alloc; } template <typename MonotonicBufferResource, typename Cache> std::pair<typename Cache::ItemHandle, MonotonicBufferResource> createMonotonicBufferResource(Cache& cache, PoolId poolId, folly::StringPiece key, uint32_t reservedBytes, uint32_t additionalBytes, size_t alignment) { // The layout in our parent item is as follows. // // |-header-|-key-|-metadata-|-GAP-|-reserved-|-additional-| // // The "reserved" storage always start at aligned boundary alignment = alignment >= std::alignment_of<std::max_align_t>() ? std::alignment_of<std::max_align_t>() : alignment; uint32_t sizeOfMetadata = sizeof(typename MonotonicBufferResource::Metadata); uint32_t bytes = sizeOfMetadata + reservedBytes + additionalBytes; uint32_t extraBytes = 0; if (reservedBytes > 0) { // We add at least "alignment" bytes to we can align the buffer start. // In addition, if the alignment is greater than 8 bytes, we pad an // additional 8 bytes because cachelib only guarantees alignment on 8 // bytes boundary. extraBytes = alignment + 8 * (alignment > std::alignment_of<uint64_t>()); } auto hdl = cache.allocate(poolId, key, bytes + extraBytes); if (!hdl) { throw exception::ObjectCacheAllocationError(folly::sformat( "Unable to allocate a new item for allocator. Key: {}, Requested " "bytes: {}", key, bytes)); } auto* bufferStart = reinterpret_cast<uint8_t*>(MonotonicBufferResource::getReservedStorage( hdl->getMemory(), alignment)) + reservedBytes; auto* metadata = new (hdl->getMemory()) typename MonotonicBufferResource::Metadata(); metadata->remainingBytes = additionalBytes; metadata->buffer = bufferStart; auto sharedHdl = detail::objcacheInitializeZeroRefcountHandle<typename Cache::ItemHandle>( &metadata->itemHandleStorage, hdl.get(), cache); return {std::move(hdl), MonotonicBufferResource{sharedHdl}}; } } // namespace objcache } // namespace cachelib } // namespace facebook
PHP
UTF-8
421
3
3
[]
no_license
<?php namespace mvc\db; use \PDO; /** * 数据库基类 */ class Db{ protected $_dbHandle; public function connect($host, $user, $pass, $dbname){ try { $dsn = sprintf("mysql:host=%s;dbname=%s;charset=utf8", $host, $dbname); $this->_dbHandle = new PDO($dsn, $user, $pass, array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC)); } catch (PDOException $e) { exit('错误:'.$e->getMessage()); } } }
Java
UTF-8
1,577
2.78125
3
[ "Apache-2.0" ]
permissive
package kotlin.collections; import java.util.RandomAccess; import org.jetbrains.annotations.NotNull; public final class ArraysKt___ArraysJvmKt$asList$5 extends AbstractList<Float> implements RandomAccess { final /* synthetic */ float[] $this_asList; ArraysKt___ArraysJvmKt$asList$5(float[] fArr) { this.$this_asList = fArr; } public final /* bridge */ boolean contains(Object obj) { if (obj instanceof Float) { return contains(((Number) obj).floatValue()); } return false; } public final /* bridge */ int indexOf(Object obj) { if (obj instanceof Float) { return indexOf(((Number) obj).floatValue()); } return -1; } public final /* bridge */ int lastIndexOf(Object obj) { if (obj instanceof Float) { return lastIndexOf(((Number) obj).floatValue()); } return -1; } public int getSize() { return this.$this_asList.length; } public boolean isEmpty() { return this.$this_asList.length == 0; } public boolean contains(float f) { return ArraysKt___ArraysKt.contains(this.$this_asList, f); } @NotNull public Float get(int i) { return Float.valueOf(this.$this_asList[i]); } public int indexOf(float f) { return ArraysKt___ArraysKt.indexOf(this.$this_asList, f); } public int lastIndexOf(float f) { return ArraysKt___ArraysKt.lastIndexOf(this.$this_asList, f); } }
Java
UTF-8
5,169
2.453125
2
[]
no_license
package reagodjj.example.com.sqlitestudent; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.CursorAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.SimpleCursorAdapter; import android.widget.Toast; import reagodjj.example.com.sqlitestudent.dao.StudentDao; import reagodjj.example.com.sqlitestudent.entity.Student; public class SecondActivity extends AppCompatActivity { private EditText etName; private EditText etAge; private RadioGroup rgGender; private RadioButton rbMale; private RadioButton rbFemale; private EditText etNumber; private ListView lvSelectItem; private StudentDao studentDao; private String gender = "男"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); initView(); // String path = Environment.getExternalStorageDirectory() + "/student.db"; studentDao = new StudentDao(this); } private void initView() { etName = findViewById(R.id.et_name); etAge = findViewById(R.id.et_age); rgGender = findViewById(R.id.rg_gender); rbMale = findViewById(R.id.rb_male); rbFemale = findViewById(R.id.rb_female); etNumber = findViewById(R.id.et_number); lvSelectItem = findViewById(R.id.lv_select_item); rgGender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if (checkedId == R.id.rb_male) gender = rbMale.getText().toString(); else if (checkedId == R.id.rb_female) gender = rbFemale.getText().toString(); } }); } public void operate(View view) { String name = etName.getText().toString(); String age = etAge.getText().toString(); String condition_id = etNumber.getText().toString(); switch (view.getId()) { case R.id.bt_insert: if (!age.equals("")) { Student student = new Student(name, Integer.parseInt(age), gender); studentDao.addStudent(student); } break; case R.id.bt_delete: String d_key = ""; String d_value = ""; if (!age.equals("")) { d_key = "age"; d_value = age; } else if (!condition_id.equals("")) { d_key = "_id"; d_value = condition_id; } else if (!name.equals("")) { d_key = "name"; d_value = name; } int count; if (d_key.equals("")) count = studentDao.deleteStudent(); else count = studentDao.deleteStudent(d_key, d_value); if (count > 0) Toast.makeText(SecondActivity.this, R.string.delete_success, Toast.LENGTH_SHORT).show(); break; case R.id.bt_update: Student student = new Student(Integer.parseInt(condition_id), name, Integer.parseInt(age), gender); int count_1 = studentDao.updateStudent(student, "_id", condition_id); if (count_1 > 0) Toast.makeText(SecondActivity.this, R.string.update_success, Toast.LENGTH_SHORT).show(); break; case R.id.bt_select: String s_key = ""; String s_value = ""; if (!age.equals("")) { s_key = "age"; s_value = age; } else if (!condition_id.equals("")) { s_key = "_id"; s_value = condition_id; } else if (!name.equals("")) { s_key = "name"; s_value = name; } Cursor cursor; if (s_key.equals("")) cursor = studentDao.selectStudent(); else { cursor = studentDao.selectStudent(s_key, s_value); } SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(this, R.layout.select_item, cursor, new String[]{"_id", "name", "age", "gender"}, new int[]{R.id.tv_id, R.id.tv_name, R.id.tv_age, R.id.tv_gender}, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); lvSelectItem.setAdapter(simpleCursorAdapter); break; } etName.setText(""); etAge.setText(""); etNumber.setText(""); rbMale.setChecked(true); } }
Markdown
UTF-8
2,624
3.140625
3
[ "MIT" ]
permissive
# Inline-Importer [![Documentation Status](https://readthedocs.org/projects/inline-importer/badge/?version=latest)](https://inline-importer.readthedocs.io/en/latest/?badge=latest) Inline-Importer is a library for python projects that uses the PEP 302 import protocol to inline libraries into a single-file script. ## Why? Because we can. But in all seriousness, this came out from spending days managing adhoc scripts that shared a lot of functionality. For ease of development, it would have been nice to extract the common pieces to a common library, but that would have meant distributing a whole directory and managing import paths on the destination systems versus a single self-contained file. ## How it works PEP 302 defined a protocol for managing module imports. The protocol defines two components: `Finder`s and `Loader`s. The Finder is responsible for, unsurprisingly, finding modules. If a Finder finds a module, i.e. _knows_ which loader can load a module, it returns a `ModuleSpec`. This ModuleSpec gives details on some parameters of the module, such as filename and package, and states which Loader can load the module. The Loader is, as you've guessed it, responsible for loading modules into the environment. It does so by first creating a module object, which the python machinery places into the `sys.modules` dictionary, then executing the module code. An object that can both Find and Load is called an `Importer`. Inline-Importer works by placing the source code of modules in a dictionary, keyed by module name. The finder searche the dictionary for a key matching the given module name. If found, it returns a ModuleSpec with itself listed as the loader. The loader simply compiles the inlined source code to python bytecode, and executes it as the normal python loader does. ## Usage Include `inline-importer` in your development dependencies. **`inline-importer` is not a runtime dependency, but a build-time dependency instead.** Build your final script using `inline-python` or `python -m inline_importer` and distribute the output of that instead. Your users will not require `inline-importer`. However, if you have dependencies on other modules, your users will have to install those. ## What's next While the importer is built, the rest of the machinery isn't. * [x] Importer with PoC. * [x] Script to collect all the modules to be inlined and build the dictionary. * [x] Script that can combine the importer and the modules. * [ ] Support for compressing the inlined modules. * [ ] Support for inlining distributed python libraries. * [ ] Support for pre-compiled bytecode.
C#
UTF-8
3,944
3.53125
4
[ "MIT" ]
permissive
using System; using System.Linq; namespace _7._Knight_Game { class Program { static void Main(string[] args) { int dimensions = int.Parse(Console.ReadLine()); char[,] chessBoard = ReadMatrix(dimensions, dimensions); int knightCount = 0; int killerRow = 0; int killerCol = 0; while (true) { int maxAttaaks = 0; for (int row = 0; row < chessBoard.GetLength(0); row++) { for (int col = 0; col < chessBoard.GetLength(1); col++) { int currentAttacks = 0; if (chessBoard[row, col] == 'K') { if (IsInside(chessBoard, row + 1, col - 2) && chessBoard[row + 1, col - 2] == 'K') { currentAttacks++; } if (IsInside(chessBoard, row + 1, col + 2) && chessBoard[row + 1, col + 2] == 'K') { currentAttacks++; } if (IsInside(chessBoard, row + 2, col - 1) && chessBoard[row + 2, col - 1] == 'K') { currentAttacks++; } if (IsInside(chessBoard, row + 2, col + 1) && chessBoard[row + 2, col + 1] == 'K') { currentAttacks++; } if (IsInside(chessBoard, row - 2, col - 1) && chessBoard[row - 2, col - 1] == 'K') { currentAttacks++; } if (IsInside(chessBoard, row - 2, col + 1) && chessBoard[row - 2, col + 1] == 'K') { currentAttacks++; } if (IsInside(chessBoard, row - 1, col - 2) && chessBoard[row - 1, col - 2] == 'K') { currentAttacks++; } if (IsInside(chessBoard, row - 1, col + 2) && chessBoard[row - 1, col + 2] == 'K') { currentAttacks++; } } if (currentAttacks > maxAttaaks) { maxAttaaks = currentAttacks; killerCol = col; killerRow = row; } } } if (maxAttaaks > 0) { chessBoard[killerRow, killerCol] = '0'; knightCount++; } else { Console.WriteLine(knightCount); break; } } } private static bool IsInside(char[,] chessBoard, int row, int column) { return row >= 0 && row < chessBoard.GetLength(0) && column >= 0 && column < chessBoard.GetLength(1); } private static char[,] ReadMatrix(int rows, int cols) { char[,] matrix = new char[rows, cols]; for (int row = 0; row < matrix.GetLength(0); row++) { char[] rowDate = Console .ReadLine() .ToCharArray(); for (int col = 0; col < matrix.GetLength(1); col++) { matrix[row, col] = rowDate[col]; } } return matrix; } } }
SQL
UTF-8
947
3.828125
4
[]
no_license
USE sakila; select * from film; ## todos os filmes select title, release_year, rating from film; ## filmes, ano de lançamento e também a classificação select count(title) from film; ## quantos filmes select distinct last_name from actor; ## sobrenomes listados e não repetidos select count(distinct last_name) from actor; ## numero de last name de atores select last_name from actor order by last_name desc; ## ordenando os last_name em ordem decrescente select * from language limit 5 offset 1; ## mostrando 5 idiomas cadastrados menos o inglish select title, release_year,rental_duration, replacement_cost from film order by rental_duration; ## crie uma query para encontrar os 20 primeiros filmes , incluindo o título , o ano de lançamento , a duração , a classificação indicativa e o custo de substituição select title, release_year,rental_duration, replacement_cost from film order by rental_duration desc; ## ordenando por dsc
Python
UTF-8
2,086
2.828125
3
[]
no_license
import praw import requests import getpass import datetime import sys # you need to get your client key and client secret after registering for the reddit API client_key = '' client_secret = '' # reddit credentials. getpass() allows password entry on the command line in unix-style: no visibility username = '' password = getpass.getpass() useragent = '' op_dir = '' # initialising the API connection reddit = praw.Reddit(client_id = client_key, client_secret = client_secret, username = username, password = password, user_agent = useragent) # default to 1 post search per sub num_posts = 1 # if number_of_posts not entered as command line arg if len(sys.argv) < 2: print('# posts not entered. Defaulting to 1 post per sub') # if args entered else: try: # try casting the argument to an int num_posts = int(sys.argv[1]) # negative number handling if num_posts < 0: print('-ve entered. Defaulting to 1 post per sub') num_posts = 1 # non integer entered handling except ValueError: print('Enter integer. Defaulting to 1 post per sub.') # list of subreddits to scrape subs = ['me_irl', 'ProgrammerHumor'] try: for sub in subs: ctr = 0 print('\nDOWNLOADING FROM r/', sub) posts = reddit.subreddit(sub).new(limit=num_posts) for post in posts: # these are posts that stay at the top of the subreddit, eg. rules of the sub, etc. if post.stickied: continue # if the post contains an image - jpg, it will be present at the end of the url if post.url.split('.')[-1] == 'jpg': ctr += 1 print(ctr, ' ', post.url) r = requests.get(post.url) # if we get a succesful response after sending a get request to this URL, if r.status_code == 200: # come up with a random name to store the image on disk randstr = datetime.datetime.now().strftime('%Y%m%d%H%M%s') # and store it in the configured output directory. with open(op_dir + randstr + post.url.split('/')[-1], 'wb') as f: f.write(r.content) except Exception as e: print('Invalid creds - ', e) print('Done') sys.exit(0)
Java
UTF-8
2,125
3.578125
4
[]
no_license
package archive.algorithms; import archive.domain.ListNode; public class LinkedList { void insert(ListNode head, int d) { while (head.next != null) { head = head.next; } head.next = new ListNode(d); } void insert(ListNode head, int d, int k) { for (int i = 0; i < k - 1; i++) { if (head.next != null) { head = head.next; } else { return; } } ListNode next = head.next; head.next = new ListNode(d); head.next.next = next; } public ListNode merge(ListNode node1, ListNode node2) { if (node1 == null) { return node2; } if (node2 == null) { return node1; } int val1 = node1.val; int val2 = node2.val; ListNode head; if (val1 < val2) { head = node1; node1 = node1.next; } else { head = node2; node2 = node2.next; } System.out.println("headval: " + head.val); ListNode ptr = head; while (node1 != null && node2 != null) { val1 = node1.val; val2 = node2.val; if (val1 < val2) { System.out.println("n1"); ptr.next = node1; node1 = node1.next; } else { System.out.println("n2"); ptr.next = node2; node2 = node2.next; } ptr = ptr.next; } if (node1 != null) { ptr.next = node1; } if (node2 != null) { ptr.next = node2; } return head; } public static void main(String[] args) { LinkedList l = new LinkedList(); ListNode head = ListNode.makeList(); ListNode head2 = ListNode.makeList(); l.insert(head, 123); l.insert(head, 456, 2); ListNode.printList(head); ListNode merged = l.merge(head, head2); System.out.println("merged: "); ListNode.printList(merged); } }
C#
UTF-8
8,430
2.609375
3
[ "MIT" ]
permissive
namespace AgileObjects.AgileMapper.UnitTests.SimpleTypeConversion { using System.Collections.Generic; using Common; using Common.TestClasses; using TestClasses; #if !NET35 using Xunit; #else using Fact = NUnit.Framework.TestAttribute; [NUnit.Framework.TestFixture] #endif public class WhenConvertingToDecimals { [Fact] public void ShouldMapASignedByteOverADecimal() { var source = new PublicProperty<sbyte> { Value = 83 }; var result = Mapper.Map(source).Over(new PublicField<decimal> { Value = 64738 }); result.Value.ShouldBe(83); } [Fact] public void ShouldMapAByteOntoADecimal() { var source = new PublicProperty<byte> { Value = 99 }; var result = Mapper.Map(source).OnTo(new PublicField<decimal>()); result.Value.ShouldBe(99); } [Fact] public void ShouldMapAShortToADecimal() { var source = new PublicProperty<short> { Value = 9287 }; var result = Mapper.Map(source).ToANew<PublicField<decimal>>(); result.Value.ShouldBe(9287); } [Fact] public void ShouldMapAnIntToADecimal() { var source = new PublicField<int> { Value = 32156 }; var result = Mapper.Map(source).ToANew<PublicProperty<decimal>>(); result.Value.ShouldBe(32156); } [Fact] public void ShouldMapAnUnsignedIntToADecimal() { var source = new PublicField<uint> { Value = 32658 }; var result = Mapper.Map(source).ToANew<PublicProperty<decimal>>(); result.Value.ShouldBe(32658); } [Fact] public void ShouldMapALongToADecimal() { var source = new PublicField<long> { Value = 3156 }; var result = Mapper.Map(source).ToANew<PublicProperty<decimal>>(); result.Value.ShouldBe(3156); } [Fact] public void ShouldMapAnUnsignedLongToADecimal() { var source = new PublicField<ulong> { Value = 9292726 }; var result = Mapper.Map(source).ToANew<PublicProperty<decimal>>(); result.Value.ShouldBe(9292726); } [Fact] public void ShouldMapAnUnsignedLongToANullableDecimal() { var source = new PublicField<ulong> { Value = 9383625 }; var result = Mapper.Map(source).ToANew<PublicProperty<decimal?>>(); result.Value.ShouldBe(9383625); } [Fact] public void ShouldMapAWholeNumberFloatOverADecimal() { var source = new PublicField<float> { Value = 8532.00f }; var result = Mapper.Map(source).ToANew<PublicProperty<decimal>>(); result.Value.ShouldBe(8532); } [Fact] public void ShouldMapANonWholeNumberNullableFloatToANullableDecimal() { var source = new PublicProperty<float?> { Value = 73.62f }; var result = Mapper.Map(source).ToANew<PublicField<decimal?>>(); result.Value.ShouldBe(73.62); } [Fact] public void ShouldMapATooBigWholeNumberFloatToANullableDecimal() { var source = new PublicProperty<float> { Value = float.MaxValue }; var result = Mapper.Map(source).ToANew<PublicField<decimal?>>(); result.Value.ShouldBeNull(); } [Fact] public void ShouldMapATooSmallWholeNumberFloatToANullableDecimal() { var source = new PublicProperty<float> { Value = float.MinValue }; var result = Mapper.Map(source).ToANew<PublicField<decimal?>>(); result.Value.ShouldBeNull(); } [Fact] public void ShouldMapAWholeNumberDecimalToANullableDecimal() { var source = new PublicGetMethod<decimal>(5332.00m); var result = Mapper.Map(source).ToANew<PublicProperty<decimal?>>(); result.Value.ShouldBe(5332); } [Fact] public void ShouldMapANonWholeNumberNullableDecimalOverADecimal() { var source = new PublicProperty<decimal> { Value = 938378.637m }; var target = Mapper.Map(source).Over(new PublicProperty<decimal>()); target.Value.ShouldBe(938378.637); } [Fact] public void ShouldMapAnInRangeWholeNumberDoubleToADecimal() { var source = new PublicField<double> { Value = 637128 }; var result = Mapper.Map(source).ToANew<PublicProperty<decimal>>(); result.Value.ShouldBe(637128); } [Fact] public void ShouldMapATooBigWholeNumberDoubleOnToANullableDecimal() { var source = new PublicField<double> { Value = double.MaxValue }; var result = Mapper.Map(source).OnTo(new PublicField<decimal?>()); result.Value.ShouldBeNull(); } [Fact] public void ShouldMapATooSmallWholeNumberDoubleOverADecimal() { var source = new PublicProperty<double> { Value = double.MinValue }; var result = Mapper.Map(source).Over(new PublicSetMethod<decimal>()); result.Value.ShouldBeDefault(); } [Fact] public void ShouldMapANullableBoolFalseToNullableDecimalOne() { var source = new PublicProperty<bool?> { Value = false }; var result = Mapper.Map(source).ToANew<PublicField<decimal?>>(); result.Value.ShouldBe(decimal.Zero); } [Fact] public void ShouldMapAnEnumOverADecimal() { var source = new PublicField<Title> { Value = Title.Miss }; var target = Mapper.Map(source).Over(new PublicProperty<decimal>()); target.Value.ShouldBe((decimal)Title.Miss); } [Fact] public void ShouldMapACharacterToANullableDecimal() { var source = new PublicProperty<char> { Value = '3' }; var result = Mapper.Map(source).ToANew<PublicField<decimal?>>(); result.Value.ShouldBe(3); } [Fact] public void ShouldMapAnUnparsableCharacterToADecimal() { var source = new PublicProperty<char> { Value = 'g' }; var result = Mapper.Map(source).ToANew<PublicField<decimal>>(); result.Value.ShouldBeDefault(); } [Fact] public void ShouldMapAParsableWholeNumberStringOnToADecimal() { var source = new PublicField<string> { Value = "6347687" }; var result = Mapper.Map(source).OnTo(new PublicSetMethod<decimal>()); result.Value.ShouldBe(6347687); } [Fact] public void ShouldMapAParsableNonWholeNumberStringOverANullableDecimal() { var source = new PublicProperty<string> { Value = "6372389.63" }; var result = Mapper.Map(source).Over(new PublicSetMethod<decimal?>()); result.Value.ShouldBe(6372389.63); } [Fact] public void ShouldMapAnUnparsableStringToADecimal() { var source = new PublicProperty<string> { Value = "GIBLETS" }; var result = Mapper.Map(source).ToANew<PublicField<decimal>>(); result.Value.ShouldBeDefault(); } [Fact] public void ShouldMapAnUnparsableNumericStringOverADecimal() { var source = new PublicField<string> { Value = "938383737383839209220202928287272727282829292092020202020296738732.637" }; var target = Mapper.Map(source).Over(new PublicField<decimal>()); target.Value.ShouldBeDefault(); } [Fact] public void ShouldMapAnUnparsableStringToANullableDecimal() { var source = new PublicProperty<string> { Value = "PFFFFFT" }; var result = Mapper.Map(source).ToANew<PublicField<decimal?>>(); result.Value.ShouldBeNull(); } [Fact] public void ShouldMapACharacterArrayOnToADecimalList() { var source = new[] { '1', '9', '7' }; IList<decimal> target = new List<decimal> { 9, 9 }; var result = Mapper.Map(source).OnTo(target); result.ShouldBe(target); result.ShouldBe(9m, 9m, 1m, 7m); } } }
JavaScript
UTF-8
458
3.796875
4
[]
no_license
var currentDate = new Date(); var currentHour = currentDate.getHours(); var greeting = ""; if (currentHour < 12) { // Before noon. Good morning greeting = 'Good Morning'; } else if ((currentHour >= 12) && (currentHour < 17)) // Good afternoon { greeting = 'Good Afternoon'; } else if ((hrs >= 17) && (hrs <= 24)) // Good evening { greeting = 'Good Evening'; } greeting += " " + currentDate; document.getElementById('holder').innerHTML = greeting;
JavaScript
UTF-8
4,991
2.53125
3
[ "BSD-3-Clause" ]
permissive
$(document).ready(function() { if ($("form[name=entryform]").length > 0) { $("form[name=entryform]").submit(specifyWhichButton); $("input[name=whichbutton]").val("save"); } if ($("form[name=commentform]").length > 0) { $("textarea[name=commentarea]","#commentbox").val("Type your comment here"); $("textarea[name=commentarea]","#commentbox").focus(removeDefaultText); $("textarea[name=commentarea]","#commentbox").blur(addDefaultText); if ($("input[name=username]").length > 0 ) { $("input[name=username]","#commentbox").val("Name"); $("input[name=username]","#commentbox").focus(removeDefaultText); $("input[name=username]","#commentbox").blur(addDefaultText); $("input[name=webaddress]","#commentbox").val("Website (Optional)"); $("input[name=webaddress]","#commentbox").focus(removeDefaultText); $("input[name=webaddress]","#commentbox").blur(addDefaultText); } } }); function removeDefaultText() { name = $(this).attr('name'); value = $(this).val(); if (name =="commentarea") { if (value == "Type your comment here") { $("textarea[name=commentarea]","#commentbox").val(""); } } else if (name == "username") { if (value == "Name") { $("input[name=username]","#commentbox").val(""); } } else if (name == "webaddress") { if (value == "Website (Optional)") { $("input[name=webaddress]","#commentbox").val(""); } } } function addDefaultText() { name = $(this).attr('name'); value = $(this).val(); if (name =="commentarea") { if ($.trim(value).length == 0 ) { $("textarea[name=commentarea]","#commentbox").val("Type your comment here"); } } else if (name == "username") { if ($.trim(value).length == 0 ) { $("input[name=username]","#commentbox").val("Name"); } } else if (name == "webaddress") { if ($.trim(value).length == 0 ) { $("input[name=webaddress]","#commentbox").val("Website (Optional)"); } } } function postComment(entryid) { var data = {}; text = $("textarea[name=commentarea]","#commentbox").val(); if (($.trim(text).length <= 0 ) | ($.trim(text) == "Type your comment here")) { window.alert("Please enter the Comment........."); return ; } $("#sendbutton").before("<span id='mesageajaximage'> &nbsp; &nbsp; <img src='/appmedia/images/alumclubajax.gif' alt='ajax image'/> </span>"); $("#sendbutton").attr("disabled", "true"); //Bring answer send an ajax request serverurl = "/blog/postcomment/"+entryid+"/"; data.text = text; if ($("input[name=username]").length > 0 ) { username = $("input[name=username]").val(); if ( ($.trim(username).length <= 0) | ($.trim(username) == "Name") ) { window.alert("Please enter the Username........."); return ; } data.username = $("input[name=username]").val(); data.webaddress = $("input[name=webaddress]").val(); } //Get the answer $.post(serverurl, data, messagePosted, "json" ); } function messagePosted(data) { if (data['error'] === undefined ) { $("#entrycomments").append("<div class='ecomment'>"+data['text']+"</div>"); $("#sendbutton").removeAttr("disabled"); $("#mesageajaximage").remove(); $("#errormessagespan").html(""); $("#commentsuccess").html("Sucessfully posted the comment"); $("textarea[name=commentarea]","#commentbox").val("Type your comment here"); if ($("input[name=username]").length > 0 ) { $("input[name=username]","#commentbox").val("Name"); $("input[name=webaddress]","#commentbox").val("Website (Optional)"); } } else{ $("#errormessagespan").html(data['error'] +" &nbsp "+"Resubmit again"); $("#mesageajaximage").remove(); $("#sendbutton").removeAttr("disabled"); } } function unhide(divid) { divid = "#"+divid toggle = $(divid).css("display"); if (toggle.indexOf("block") >= 0 ) { $(divid).css("display","none"); } else { $("textarea[name=commentarea]","#commentbox").val(""); $(divid).css("display","block"); $("textarea[name=commentarea]","#commentbox").focus(); $("#errormessagespan").html(""); } } function specifyWhichButton() { $("input[name=whichbutton]").val("submit"); return true; }
C#
UTF-8
1,142
2.546875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace NovosAres.WebUserControl { /// <summary> /// Classe do UserControl Descricao. /// </summary> public partial class wucDescricao : System.Web.UI.UserControl { /// <summary> /// Recupera o conteúdo da descrição. /// </summary> public string GetValue() { string descricao = txtDescricao.Text; return descricao; } /// <summary> /// Grava o conteúdo da descrição. /// </summary> public void SetValue(string descricao) { txtDescricao.Text = descricao; } /// <summary> /// Responsável por efetuar o carregamento da página. /// </summary> /// <param name="sender">Objeto gerador do eventos.</param> /// <param name="e">Contém os parâmetros do evento gerado.</param> protected void Page_Load(object sender, EventArgs e) { } } }
Go
UTF-8
498
3.296875
3
[]
no_license
package main import ( "flag" "fmt" ) // flag包的基本使用 func main() { // 定义几个变量用于接受命令行的参数值 var user string var pwd string var host string var port int flag.StringVar(&user, "u", "", "用户名,默认为空") flag.StringVar(&pwd, "pwd", "", "密码") flag.StringVar(&host, "h", "localhost", "host") flag.IntVar(&port, "p", 0, "port") flag.Parse() // 讲数据转换 fmt.Printf("user=%v ,pwd=%v ,host=%v ,post=%d", user, pwd, host, port) }
C++
UTF-8
744
3.265625
3
[]
no_license
#include <iostream> #include <algorithm> #include <cstring> using namespace std; void swap(char*,char*); int main(int argc, char const *argv[]) { int t; cin>>t; while(t--) { char* str = new char[101](); cin.clear(); cin>>str; //cout<<str<<endl; int length = strlen(str); int i = length-1; while(str[i-1]>=str[i]) { i--; if(i<=0) break; } if(i==0) { cout<<"no answer"<<endl; } else { char current = str[i-1]; int j; sort(str+i-1, str+length); for (j = i-1; j < length; j++) { if(str[j]>current) break; } swap(&str[j],&str[i-1]); sort(str+i,str+j+1); cout<<str<<endl; } } return 0; } void swap(char* a, char* b) { char temp = *a; *a = *b; *b = temp; }
C
UTF-8
1,590
3.390625
3
[]
no_license
/** File: mmstack.c Enter a description for this file. */ #include <assert.h> #include "mmstack.h" #include <stdlib.h> #include <stdio.h> struct llnode { int item; struct llnode *next; int minc; int maxc; }; struct mmstack { int len ; struct llnode *topnode; }; MMStack create_MMStack(void) { struct mmstack *new = malloc(sizeof(struct mmstack)); new->topnode = NULL; new->len =0; return new ; } void destroy_MMStack(MMStack mms) { while(mms->len !=0) { mms_pop(mms); } free(mms); } int mms_length(MMStack mms) { assert(mms); return mms->len; } void mms_push(MMStack mms, int i) { struct llnode *new = malloc(sizeof(struct llnode)); new->item = i; if(mms->len!=0) { new->next = mms->topnode; mms->topnode = new; } else { new->next = NULL; mms->topnode = new; } if (mms->len == 0) { mms->topnode->minc = i; mms->topnode->maxc = i; } else { mms->topnode->maxc = mms->topnode->next->maxc; mms->topnode->minc = mms->topnode->next->minc; if(mms->topnode->maxc < i) { mms->topnode->maxc = i; } if(i<mms->topnode->minc) { mms->topnode->minc = i; } } mms->len++; } int mms_pop(MMStack mms) { assert(mms); int ret = mms->topnode->item; struct llnode *backup = mms->topnode; mms->topnode = mms->topnode->next; mms->len--; free(backup); return ret; } int mms_min(MMStack mms) { assert(mms->len > 0); return mms->topnode->minc ; } int mms_max(MMStack mms) { assert(mms->len > 0); return mms->topnode->maxc ; }
Python
UTF-8
6,630
3.15625
3
[]
no_license
import logging import pandas as pd class create_db: def __init__(self): logging.basicConfig(level=logging.DEBUG, format='\n %(asctime)s - %(levelname)s - %(message)s)') self.skip_check = "no" # Lists self.train_class = [] self.test_class = [] self.classifiers = [] self.column_names = [] self.feature_names = [] self.features = [] # Dictionaries self.feature_values = {} # Misc Values self.train_data = pd.read_csv('./ml_data/titanic/train.csv') # self.train_data = pd.read_pickle('./covid_data/new_dataset.pkl') # self.train_data = pd.read_csv('./ml_data/census_income_real.data', header=None) # http://archive.ics.uci.edu/ml/machine-learning-databases/census-income-mld/census-income.test.gz self.test_data = pd.read_csv('./ml_data/titanic/test.csv') # self.test_data = pd.read_pickle('./covid_data/new_dataset.pkl') # self.test_data = pd.read_csv('./ml_data/census_income_test.test', header=None) # https://archive.ics.uci.edu/ml/machine-learning-databases/census-income-mld/census-income.data.gz self.data = self.train_data # START def learning_method(self, data): data_type = input("Will this be supervised? Yes/No: ") # Ideally a switch for unsupervised which does not feature a classifier if data_type.lower() == "yes": classifier = input("What column will the classifier be found?") try: classifier = data.columns[int(classifier)] except ValueError: print("Please enter the column number where the classifier can be found.") self.learning_method(data) logging.debug('Classifier entered: ' + str(classifier)) self.features = self.supervised_learning(data, classifier) return self.features else: print("Invalid selection.") self.learning_method(data) def supervised_learning(self, data, classifier): categorical = [] # Number of features in the dataset logging.debug("Entering create_db.supervised_learning") print("Beginning discovery...") for every in range(len(self.data.columns)): for each in range(len(self.data)): # for each column, use every row up to a 25th of the dataset if type(self.data.iloc[each][every]) == str: try: int(self.data.iloc[each][every]) break except ValueError: # If any value within that column is a string, it categorical logging.debug('Feature ' + str(every) + ' entered due to ' + str(self.data.iloc[each][every])) categorical.append(data.columns[every]) # Add it to the list then break to the next column break # If it is a not a string, then it is a number # Make a list of the remaining, non-categorical features logging.debug('Categorical' + str(categorical)) logging.debug('Columns ' + str(data.columns)) numerical = list(set(data.columns) - set(categorical)) logging.debug('Numerical' + str(numerical)) # Check if the classifier has been placed in either of the created lists # If it has been, remove it for eachFeature in categorical: if eachFeature == classifier: categorical.remove(classifier) for everyFeature in numerical: if everyFeature == classifier: numerical.remove(classifier) logging.debug("Discovered " + str(len(categorical)) + " categorical features.") logging.debug("Discovered " + str(len(numerical)) + " numerical features.") # doubleCheck = input("Is this correct?") # if doubleCheck.lower() == "yes": return categorical, numerical, classifier def get_dataset(self): TTD = input("Would you like to import the training and test data separately or split automatically?") if TTD == "separately": url = input("Enter the URL for the training data:") # Import dataset. Input cleaning needed self.train_data = pd.read_csv(url) self.data = self.train_data # Run algorithms needed to format self.format_chain() # Skip the future test set, which will have the same features self.skip_check = "yes" # Ensure train_data is properly updated before switching to test data next self.train_data = self.data # Ensure training class values are updated before switching to test class self.train_class = self.classifiers url = input("Enter the URL for the test data:") self.test_data = pd.read_csv(url) self.data = self.test_data self.format_chain() self.test_data = self.data self.test_class = self.classifiers self.menu() def set_column_names(self): # Replace feature names as this function is only called when names are being written. self.feature_names.clear() for each in range(len(self.data.columns)): # feature_values only includes categorical features/columns for categories in self.feature_values: # Cycle each column that has categorical values if each == self.feature_values[categories]: # If the current column is one of those values print(self.feature_values[categories]) # Print those values for input clarity column_name = input("Enter the name for this feature:") self.feature_names.append(column_name) else: continue # Otherwise those columns are numerical print(self.data.iloc[:5][each]) column_name = input("Enter the name for this feature:") self.feature_names.append(column_name) def backup_database(self): temp_data = self.data[:].astype('category') # Store column values in a list of lists for catFeatures in self.features[0]: current_feature = list(temp_data[catFeatures].cat.categories) # Create dictionary of categorical features and their list of values self.feature_values.update({catFeatures: current_feature})
C
UTF-8
3,657
2.9375
3
[ "MIT" ]
permissive
#ifndef _RTC_H_ #define _RTC_H_ #include <pc.h> #include <dos.h> #include "utypes.h" /** @defgroup RealTimeController RealTimeController * @{ * * Real Time Controller related functions */ /** Time structure. Atributes in plain decimal */ typedef struct { Byte hour, ///< The hour of the day min, ///< The minute of the day sec; ///< The second of the day } RTC_TIME; /** Data structure. Atributes in plain decimal */ typedef struct { Byte day, ///< The day of the month month, ///< The day of the year year; ///< The year } RTC_DATE; /** @name The RTC registers */ /*@{*/ enum rtc_regs {SEC, SEC_ALARM, MIN, MIN_ALARM, HOUR, HOUR_ALARM, WEEK_DAY, MONTH_DAY, MONTH, YEAR, RTC_STAT_A, RTC_STAT_B, RTC_STAT_C, RTC_STAT_D}; /*@}*/ /** @name PC I/O register address used to comunicate with the RTC */ /*@{*/ #define RTC_ADDR_REG 0x70 ///< I/O address that contains the RTC address to communicate with #define RTC_DATA_REG 0x71 ///< I/O address that contains the data read from or written to the RTC /*@}*/ /** @name Bit Meaning in STAT-A register */ /*@{*/ #define RTC_UIP (1 << 7) ///< 1-update in progress, 0-data valid for next 244 usec #define RTC_DV2 (1 << 6) ///< Divider #define RTC_DV1 (1 << 5) ///< Divider #define RTC_DV0 (1 << 4) ///< Divider #define RTC_RS3 (1 << 3) ///< Rate selector #define RTC_RS2 (1 << 2) ///< Rate selector #define RTC_RS1 (1 << 1) ///< Rate selector #define RTC_RS0 (1 << 0) ///< Rate selector /*@}*/ /** @name Bit Meaning in STAT-B register */ /*@{*/ #define RTC_SET (1 << 7) ///< 1-Stop updating, 0-update normally #define RTC_PIE (1 << 6) ///< 1-Periodic interrupt enable #define RTC_AIE (1 << 5) ///< 1-Alarm interrupt enable #define RTC_UIE (1 << 4) ///< 1-Update-ended interrupt enable #define RTC_SQWE (1 << 3) ///< 1-Square Wave Enable #define RTC_DM (1 << 2) ///< Data Mode, 1-Binary, 0-BCD #define RTC_12_24 (1 << 1) ///< 1-24 hours, 0-12 hours #define RTC_DSE (1 << 0) ///< 1-Day-light saving /*@}*/ /** @name Bit Meaning in STAT-C register */ /*@{*/ #define RTC_IRQF (1 << 7) ///< 1-An interrupt occurred, if PF=PIE=1 || AF=AIE=1 || UF=UIE=1 #define RTC_PF (1 << 6) ///< 1-Periodic interrupt occurred #define RTC_AF (1 << 5) ///< 1-Alarm interrupt occurred #define RTC_UF (1 << 4) ///< 1-Update interrupt occurred /*@}*/ /** @name Bit Meaning in STAT-D register */ /*@{*/ #define RTC_VRT (1 << 7) ///< 1-Valid RAM and time /*@}*/ /** converts BCD (Binary Coded Decimal) to decimal */ Byte bcd2dec(Byte i); /** converts decimal to BCD (Binary Coded Decimal) */ Byte dec2bcd(Byte i); /** Wait until data in rtc is valid. * Data is valid until +/- 240 usec after this function returns, * thus a read/write can be done to the RTC within this time period */ void rtc_valid(); /** Returns rtc data from I/O address add. Doesn't check valid bit */ Byte read_rtc(Byte add); /** Returns rtc data from I/O address add. Check valid bit */ Byte read_rtcv(Byte add); /** Write value to I/O address add. Doesn't check valid bit */ void write_rtc(Byte add, Byte value); /** Write value to I/O address add. Check valid bit */ void write_rtcv(Byte add, Byte value); /** Read RTC stored time * * Uses read_rtcv() and bcd2dec() */ void rtc_read_time(RTC_TIME *); /** Read RTC stored date * * Uses read_rtcv() and bcd2dec() */ void rtc_read_date(RTC_DATE *); /** Read RTC stored alarm * * Uses read_rtcv() and bcd2dec() */ void rtc_read_alarm(RTC_TIME *); /** Write alarm to RTC * * Uses write_rtcv() and dec2bcd() */ void rtc_write_alarm(RTC_TIME *); /** @} end of RealTimeController */ #endif
Python
UTF-8
855
3.125
3
[]
no_license
# -*- coding: utf-8 -*- import sqlite3 conn = sqlite3.connect('dados.db') cursor = conn.cursor() print("--------Apagar: Livros--------") while True: id = int(input("Id: ")) cursor.execute("select * from livros where id == ?", [id]) result = cursor.fetchone() print(result) while True: op = input("Confirmar remoção desses dados?(y\\n): ") if (op in ['y', 'Y', 'n', 'N']): break if(op == 'y' or op == 'Y'): cursor.execute("delete from livros where id == ?", [id]); conn.commit() print("---Dados apagados---") while True: continuar = input("Apagar outro?(y\\n): ") if (continuar in ['Y', 'y', 'N', 'n']): break; if (continuar == 'n' or continuar == 'N'): break; conn.close()
Python
UTF-8
890
2.90625
3
[]
no_license
from pathlib import Path from pylatex import Document, Figure from pylatex.figure import SubFigure class ExportPdf: def __init__(self): images = self.separate_by_image(list(map(lambda x: str(x), Path("Output").rglob("*.png")))) doc = Document('Output') for group in images: with doc.create(Figure(position='h')) as image_grouper: for image in group: with image_grouper.create(SubFigure()) as card_image: card_image.add_image(image, width='120px') doc.generate_pdf(clean_tex=True) def separate_by_image(self, images): ans = [] tmp = [] for image in images: if(len(tmp) == 3): ans.append(tmp) tmp = [] tmp.append(image) if(len(tmp) != 0): ans.append(tmp) return ans
C#
UTF-8
441
2.609375
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lan_Tic_Tac_Toe.GameComponents { class Player { public enum PlayerTypes { Spectator, PlayerX, PlayerO, } public PlayerTypes CurrentPlayerType; public Player(PlayerTypes TypeOfPlayer) { CurrentPlayerType = TypeOfPlayer; } } }
PHP
UTF-8
1,983
2.578125
3
[ "MIT" ]
permissive
<?php declare(strict_types = 1); namespace PHPStan\Rules\Deprecations; use PhpParser\Node; use PhpParser\Node\Expr\ConstFetch; use PHPStan\Analyser\Scope; use PHPStan\Reflection\ReflectionProvider; use PHPStan\Rules\Rule; use function sprintf; use const PHP_VERSION_ID; /** * @implements Rule<ConstFetch> */ class FetchingDeprecatedConstRule implements Rule { /** @var ReflectionProvider */ private $reflectionProvider; /** @var DeprecatedScopeHelper */ private $deprecatedScopeHelper; /** @var array<string,string> */ private $deprecatedConstants = []; public function __construct(ReflectionProvider $reflectionProvider, DeprecatedScopeHelper $deprecatedScopeHelper) { $this->reflectionProvider = $reflectionProvider; $this->deprecatedScopeHelper = $deprecatedScopeHelper; // phpcs:ignore SlevomatCodingStandard.ControlStructures.EarlyExit.EarlyExitNotUsed if (PHP_VERSION_ID >= 70300) { $this->deprecatedConstants['FILTER_FLAG_SCHEME_REQUIRED'] = 'Use of constant %s is deprecated since PHP 7.3.'; $this->deprecatedConstants['FILTER_FLAG_HOST_REQUIRED'] = 'Use of constant %s is deprecated since PHP 7.3.'; } } public function getNodeType(): string { return ConstFetch::class; } public function processNode(Node $node, Scope $scope): array { if ($this->deprecatedScopeHelper->isScopeDeprecated($scope)) { return []; } if (!$this->reflectionProvider->hasConstant($node->name, $scope)) { return []; } $constantReflection = $this->reflectionProvider->getConstant($node->name, $scope); if ($constantReflection->isDeprecated()->yes()) { return [sprintf( $constantReflection->getDeprecatedDescription() ?? 'Use of constant %s is deprecated.', $constantReflection->getName() )]; } if (isset($this->deprecatedConstants[$constantReflection->getName()])) { return [sprintf( $this->deprecatedConstants[$constantReflection->getName()], $constantReflection->getName() )]; } return []; } }
JavaScript
UTF-8
2,345
3.6875
4
[]
no_license
$(document).ready(onReady); const employees = []; function onReady() { console.log('page is READY'); $('.js-btn-submit').on('click', submitEmployee); // adding event listener for delete $('.js-employee-list').on('click', '.js-btn-delete', deleteEmployee); } function deleteEmployee() { // find individual employee const index = $(this).data('index'); // data-index // remove from employees employees.splice(index, 1); console.log(employees); render(); // ONLY REMOVES FROM DOM // $(this) // .parent() // td // .parent() // tr // .remove(); } function submitEmployee() { console.log('Clicked Submit'); // gather entered data from inputs/fields const employeeObject = { firstName: $('.js-input-firstName').val(), lastName: $('.js-input-lastName').val(), id: Number($('.js-input-id').val()), title: $('.js-input-title').val(), annualSalary: Number($('.js-input-annualSalary').val()), }; // store my new employee storeEmployee(employeeObject); } function storeEmployee(newEmployee) { employees.push(newEmployee); console.log('Employees:', employees); // render list to DOM render(); } // TODO - clear fields function render() { const $employeeList = $('.js-employee-list'); let totalAnnualSalary = 0; $employeeList.empty(); for (let i = 0; i < employees.length; i++) { const employeeData = employees[i]; totalAnnualSalary += employeeData.annualSalary; $employeeList.append(` <tr> <td>${employeeData.firstName}</td> <td>${employeeData.lastName}</td> <td>${employeeData.id}</td> <td>${employeeData.title}</td> <td>${employeeData.annualSalary}</td> <td><button class="js-btn-delete" data-index="${i}">Delete</button></td> </tr> `); } renderMonthly(totalAnnualSalary); } function renderMonthly(totalAnnualSalary) { const monthsInYear = 12; const maxMonthly = 20000; let monthlySalary = totalAnnualSalary / monthsInYear; // round for change to nearest cent monthlySalary = Math.round(monthlySalary * 100) / 100; const $monthlySalaryEl = $('.js-monthly-salary'); $monthlySalaryEl.text(monthlySalary); if (monthlySalary > maxMonthly) { $monthlySalaryEl.parent().addClass('warning'); } else { $monthlySalaryEl.parent().removeClass('warning'); } }
JavaScript
UTF-8
1,637
2.78125
3
[]
no_license
const StockPrice = require("../models/StockPrice"); const fetch = require("isomorphic-unfetch"); function StockController() { this.handleOneStock = async function(stock, like, ip) { // console.log(stock, like); const stockData = await StockPrice.findOne({ stock: stock.toUpperCase() }); if (!stockData) { //find and create new stock const resData = await fetch( `https://repeated-alpaca.glitch.me/v1/stock/${stock}/quote` ); const data = await resData.json(); if (data.symbol) { // console.log(data.latestPrice); const newStock = new StockPrice({ stock: data.symbol, price: data.latestPrice, likes: 0 }); if (like) { newStock.likes++; newStock.ipsLiked.push(ip); } await newStock.save(); return newStock; // res.send({ // stockData: { // stock: newStock.stock, // price: newStock.price, // likes: newStock.likes // } // }); // return; } throw new Error("Invalid Stock"); // res.send("invalid stock"); // return; } if (like) { //verify if ip already liked it. if (stockData.ipsLiked.includes(ip)) { stockData.likes++; } } await stockData.save(); return stockData; // return res.send({ // stockData: { // stock: stockData.stock, // price: stockData.price, // likes: stockData.likes // } // }); }; } module.exports = StockController;
Python
UTF-8
260
3.015625
3
[]
no_license
import string def sort(data): let_map = dict((key, 0) for key in string.ascii_lowercase) for c in data.lower(): if c in let_map: let_map[c] += 1 res = "" for key in let_map: res += key*let_map[key] return res
Python
UTF-8
547
2.71875
3
[]
no_license
from model.Publicacion import Publicacion class Revista(Publicacion): def __init__(self,any,nro,referencia, titol): Publicacion.__init__(self, referencia, titol) self.any = any self.nro = nro def get_any(self): return self.any def set_any(self,any): self.any = any def get_nro(self): return self.nro def set_nro(self,nro): self.nro = nro def visualitzar(self): Publicacion.visualitzar(self) print("any: "+self.any) print("nro: "+self.nro)
Python
UTF-8
2,201
2.96875
3
[]
no_license
#authored by kchadha 03/20/2014 #simple Python Bot meant for logging purposes. import socket import sys import datetime import time server = "ircserver.ece.arizona.edu" #settings channel = "#acl" botnick = "bot" irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #defines the socket print "connecting to:"+server irc.connect((server, 6667)) #connects to the server irc.send("USER "+ botnick +" "+ botnick +" "+ botnick +" :hoila!\n") #user authentication irc.send("NICK "+ botnick +"\n") #sets nick #irc.send("PRIVMSG nickserv :iNOOPE\r\n") #auth irc.send("JOIN "+ channel +"\n") #join the chan print "connected to %s" %channel; def ping(): # This is our first function! It will respond to server Pings. irc.send('PONG ' + text.split() [1] + '\r\n') #returnes 'PONG' back to the server (prevents pinging out!) def privmsg(nick,destination,message,st): #print text; print "%s %s -> %s: %s" %(st,nick,destination,message); f.write("%s %s -> %s: %s\n" %(st,nick,destination,message)); def topic(nick,destination,message,st): print "%s TOPIC changed %s -> %s to -> %s" %(st,nick,destination,message); #f.write("%s TOPIC changed %s -> %s to -> %s\n" %(st,nick,destination,message)) f = open(channel+".log",'a'); f.write("\n\n### BEGIN LOGGING ####\n\n"); while 1: #puts it in a loop ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') text=irc.recv(2040) #receive the text text = text.strip('\n\r') nick = text.split('!')[ 0 ].replace(':',' ') #The nick of the user issueing the command is taken from the hostname message = ':'.join(text.split (':')[2:]) #Split the command from the message destination = ''.join (text.split(':')[:2]).split (' ')[-2] #Destination is taken from the data if text.find("PING :") != -1: # if the server pings us then we've got to respond! ping(); if text.find('PRIVMSG') != -1: #IF PRIVMSG only then display privmsg(nick,destination,message,st); if text.find('TOPIC') != -1: #IF PRIVMSG only then display topic(nick,destination,message,st);
C++
UTF-8
1,853
2.734375
3
[]
no_license
#include "screen.h" #include "screena.h" #include <map> #include <iostream> namespace romeo{ Tile::Tile(){ } Tile::Tile(sf::Texture* tex,sf::Vector3i loca,int Tile_Width){ TileWidth = Tile_Width; bool done = false; while(!done){ hitbox.setSize(sf::Vector2f(Tile_Width,Tile_Width)); hitbox.setFillColor(sf::Color::Transparent); hitbox.setOutlineColor(sf::Color::White); hitbox.setOutlineThickness(2); setLocation(loca); S.setTexture(*tex); sf:: Vector3i temploca = convert_to_Iso(location); S.setPosition(temploca.x,temploca.y); hitbox.setPosition(temploca.x,temploca.y); done = true; } } void Tile::setTexture(sf::Texture* Tex){ T= Tex; } sf::Texture Tile::getTexture(){ return *T; } void Tile::setSprite(sf::Texture* T){ S.setTexture(*T); } sf::Vector3i Tile::convert_to_Iso(sf::Vector3i Location){ sf::Vector3i converted((Location.x+Location.y)*TileWidth,((Location.x-Location.y)*TileWidth*0.5),0); return converted; } void Tile::setLocation(int x,int y,int z){ location.x = x; location.y = y; location.z = z; } void Tile::setLocation(sf::Vector3i loca){ location = loca; } sf::Vector3i Tile::getLocation(){ return location; } bool Tile::Am_I_Here(sf::Vector2i here){ if(S.getGlobalBounds().contains(here.x,here.y-30)){ std::cout<<S.getPosition().x<<"~~~~" <<S.getPosition().y<<std::endl; return true; } return false; } void Tile::render(sf::RenderWindow* mywindow,float t){ mywindow->draw(S); mywindow->draw(hitbox); } ; }
Java
UTF-8
6,025
3.65625
4
[]
no_license
package aufgabe_4; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; public class MyHashTable implements HashTable4Dict { // repraesentiert die Hashtabelle; eine Liste repraesentiert einen Bucket private List<Object>[] data = null; // welches Verfahren soll zur Bestimmung des Buckets fuer ein Wort verwendet // werden? private HashOption hashoption; // Konstruktor // TODO Nachfragen wegen initialisierung der Liste public MyHashTable(int numBuckets, HashOption hashoption) { if (numBuckets < 0 ) { System.err .println("Buckets müssen größer gleich null sein und die Hashoptions BaezaYates oder Hashcode müssen gewählt werden!"); } else { // TODO können wir die Meldung umgehen? Verstehst du das aus dem VC // Forum? data = new ArrayList[numBuckets]; for (int i = 0; i < numBuckets; i++) { data[i] = new ArrayList<Object>(); } this.hashoption = hashoption; } } /** * Fuegt ein Objekt in die Hashtabelle ein. <br/> * <br/> * * Entscheidend fuer das Einordnen in einen Bucket ist der Betrag des Wertes * der Methode <code>getHashCode</code> (falls die <code>HashOption</code> * <code>HASHCODE</code> gesetzt wurde) bzw. <code>getBaezaYates</code> * (falls die <code>HashOption</code> <code>BAEZAYATES</code> gesetzt * wurde). * * @param object * das einzufuegende Objekt. * * @throws RuntimeException * Wenn das uebergebene Objekt kein String ist. */ public void insert(Object object) throws RuntimeException { if (object instanceof String) { if (hashoption == HashOption.BAEZAYATES) { int baeza = getBaezaYates(object); data[baeza].add(object); } else { data[getHashCode(object)].add(object); } } else { throw new RuntimeException("The given object is no String!"); } } /** * Prueft, ob ein Objekt in der Hashtabelle verwaltet wird. Fuer die * Bestimmung des buckets gilt das gleiche wie fuer die <code>insert</code> * -Methode. * * @param object * das zu pruefende Objekt * @return ob <code>object</code> in der Hashtabelle verwaltet wird * * @throws RuntimeException * Wenn das uebergebene Objekt kein String ist. */ public boolean contains(Object object) throws RuntimeException { if (!(object instanceof String)) { throw new RuntimeException("Object is not a String!"); } // Wir sollen hier genauso vorgehen wie in insert --> Hashcode berechnen int hashcode; if (hashoption == HashOption.BAEZAYATES) { hashcode = getBaezaYates(object); } else { hashcode = getHashCode(object); } return data[hashcode].contains(object); } /** * Liefert die maximale Anzahl an Elementen pro Bucket. * * @return maximale Anzahl an Elementen pro Bucket */ public int getMaxChainLength() { int maximum = 0; for (List<Object> list : data) { if (list.size() > maximum) { maximum = list.size(); } } return maximum; } /** * Liefert die minimale Anzahl an Elementen pro Bucket, die von 0 * verschieden ist. * * @return minimale Anzahl an Elementen pro Bucket (verschieden von 0) * * @throws RuntimeException * Wenn alle Buckets leer sind (= die Groesse 0 haben). */ public int getMinNonZeroChainLength() throws RuntimeException { int minimum = getMaxChainLength(); if (minimum == 0) { throw new RuntimeException("Buckets are empty!"); } for (List<Object> list : data) { int size = list.size(); if (size > 0 && size < minimum) { minimum = size; } } return minimum; } /** * Liefert die Anzahl an Kollisionen in der Hashtabelle. * * @return Anzahl an Kollisionen in der Hashtabelle. */ public int countCollisions() { // TODO stimmt das? int collisions = 0; for (List<Object> list : data) { int size = list.size(); if (size > 1) { collisions += size - 1; } } return collisions; } /** * Liefert das Array, das die Hashtabelle repraesentiert. * * @return Array, das die Hashtabelle repraesentiert. */ public List<Object>[] getData() { return data; } /** * Berechnet den Bucket fuer das uebergebene Objekt <code>object</code> * gemaess der Beschreibung in der Aufgabenstellung (basierend auf der * <code>hashCode()</code>-Methode). * * Ist zur Bestimmung des Buckets zu verwenden, wenn <code>hashoption</code> * den Wert <code>HashOption.HASHCODE</code> besitzt. * * @param object * Objekt, dessen Bucket bestimmt werden soll. * @return Index des Buckets, in den <code>object</code> eingefuegt werden * muss. */ private int getHashCode(Object object) { return (Math.abs(object.hashCode()) % data.length); } /** * Berechnet den Bucket fuer das uebergebene Objekt <code>object</code> * gemaess des Algorithmus von Gonnet & Baeza-Yates (Kap.3, S.13 im Skript). * * Ist zur Bestimmung des Buckets zu verwenden, wenn <code>hashoption</code> * den Wert <code>HashOption.BAEZAYATES</code> besitzt. * * @param object * Objekt, dessen Bucket bestimmt werden soll. * @return Index des Buckets, in den <code>object</code> eingefuegt werden * muss. */ private int getBaezaYates(Object object) { BigInteger b = BigInteger.valueOf(131); char[] charArray = object.toString().toCharArray(); BigInteger sum = BigInteger.ZERO; // Durchlaufen des String-Objects Buchstabe für Buchstabe for (int i = 0; i < charArray.length; i++) { // Auslesen des aktuellen Buchstabens Object c = charArray[i]; // HashCode des aktuellen Buchstabens int hashInt = c.hashCode(); BigInteger hash = BigInteger.valueOf(hashInt); // Addieren von B^i * den Hashwert sum = sum.add(hash.multiply(Utility.pow(b,BigInteger.valueOf(i)))); } // Summe modulo 2^w modulo m sum = (sum.mod(Utility.pow(BigInteger.valueOf(2), BigInteger.valueOf(32)))).mod(BigInteger.valueOf(data.length)); int baeza = sum.intValue(); return baeza; } }
PHP
UTF-8
531
2.875
3
[ "BSD-3-Clause" ]
permissive
<?php namespace App\Http\Collections; use Illuminate\Support\Collection; class PositionCollection { /** * Prepare a collection of positions. * * @param mixed $positions * * @return Collection */ public static function prepare($positions): Collection { $positionCollection = collect([]); foreach ($positions as $position) { $positionCollection->push( $position->toObject() ); } return $positionCollection; } }
Java
UTF-8
47,513
1.507813
2
[]
no_license
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.google.android.gms.maps.internal; import android.location.Location; import android.os.Bundle; import android.os.IBinder; import android.os.Parcel; import android.os.RemoteException; import com.google.android.gms.dynamic.zzd; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.CircleOptions; import com.google.android.gms.maps.model.GroundOverlayOptions; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.PolygonOptions; import com.google.android.gms.maps.model.PolylineOptions; import com.google.android.gms.maps.model.TileOverlayOptions; import com.google.android.gms.maps.model.internal.IPolylineDelegate; import com.google.android.gms.maps.model.internal.zzc; import com.google.android.gms.maps.model.internal.zze; import com.google.android.gms.maps.model.internal.zzh; import com.google.android.gms.maps.model.internal.zzi; import com.google.android.gms.maps.model.internal.zzj; import com.google.android.gms.maps.model.internal.zzl; import com.google.android.gms.maps.model.internal.zzm; import com.google.android.gms.maps.model.internal.zzn; import com.google.android.gms.maps.model.internal.zzp; import com.google.android.gms.maps.model.zza; // Referenced classes of package com.google.android.gms.maps.internal: // IGoogleMapDelegate, zzb, zzm, zzd, // zze, ILocationSourceDelegate, zzf, zzg, // zzh, zzj, zzk, zzl, // zzn, zzo, zzp, zzq, // zzv, IProjectionDelegate, IUiSettingsDelegate private static class zzle implements IGoogleMapDelegate { private IBinder zzle; public zzh addCircle(CircleOptions circleoptions) throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (circleoptions == null) { break MISSING_BLOCK_LABEL_66; } parcel.writeInt(1); circleoptions.writeToParcel(parcel, 0); _L1: zzle.transact(35, parcel, parcel1, 0); parcel1.readException(); circleoptions = com.google.android.gms.maps.model.internal.(parcel1.readStrongBinder()); parcel1.recycle(); parcel.recycle(); return circleoptions; parcel.writeInt(0); goto _L1 circleoptions; parcel1.recycle(); parcel.recycle(); throw circleoptions; } public zzi addGroundOverlay(GroundOverlayOptions groundoverlayoptions) throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (groundoverlayoptions == null) { break MISSING_BLOCK_LABEL_66; } parcel.writeInt(1); groundoverlayoptions.writeToParcel(parcel, 0); _L1: zzle.transact(12, parcel, parcel1, 0); parcel1.readException(); groundoverlayoptions = com.google.android.gms.maps.model.internal.(parcel1.readStrongBinder()); parcel1.recycle(); parcel.recycle(); return groundoverlayoptions; parcel.writeInt(0); goto _L1 groundoverlayoptions; parcel1.recycle(); parcel.recycle(); throw groundoverlayoptions; } public zzi addGroundOverlay2(GroundOverlayOptions groundoverlayoptions, zze zze1) throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (groundoverlayoptions == null) goto _L2; else goto _L1 _L1: parcel.writeInt(1); groundoverlayoptions.writeToParcel(parcel, 0); _L3: if (zze1 == null) { break MISSING_BLOCK_LABEL_106; } parcel.writeInt(1); zze1.writeToParcel(parcel, 0); _L4: zzle.transact(70, parcel, parcel1, 0); parcel1.readException(); groundoverlayoptions = com.google.android.gms.maps.model.internal.(parcel1.readStrongBinder()); parcel1.recycle(); parcel.recycle(); return groundoverlayoptions; _L2: parcel.writeInt(0); goto _L3 groundoverlayoptions; parcel1.recycle(); parcel.recycle(); throw groundoverlayoptions; parcel.writeInt(0); goto _L4 } public zzl addMarker(MarkerOptions markeroptions) throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (markeroptions == null) { break MISSING_BLOCK_LABEL_66; } parcel.writeInt(1); markeroptions.writeToParcel(parcel, 0); _L1: zzle.transact(11, parcel, parcel1, 0); parcel1.readException(); markeroptions = com.google.android.gms.maps.model.internal.(parcel1.readStrongBinder()); parcel1.recycle(); parcel.recycle(); return markeroptions; parcel.writeInt(0); goto _L1 markeroptions; parcel1.recycle(); parcel.recycle(); throw markeroptions; } public zzl addMarker2(MarkerOptions markeroptions, zzp zzp1) throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (markeroptions == null) goto _L2; else goto _L1 _L1: parcel.writeInt(1); markeroptions.writeToParcel(parcel, 0); _L3: if (zzp1 == null) { break MISSING_BLOCK_LABEL_106; } parcel.writeInt(1); zzp1.writeToParcel(parcel, 0); _L4: zzle.transact(68, parcel, parcel1, 0); parcel1.readException(); markeroptions = com.google.android.gms.maps.model.internal.(parcel1.readStrongBinder()); parcel1.recycle(); parcel.recycle(); return markeroptions; _L2: parcel.writeInt(0); goto _L3 markeroptions; parcel1.recycle(); parcel.recycle(); throw markeroptions; parcel.writeInt(0); goto _L4 } public zzm addPolygon(PolygonOptions polygonoptions) throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (polygonoptions == null) { break MISSING_BLOCK_LABEL_66; } parcel.writeInt(1); polygonoptions.writeToParcel(parcel, 0); _L1: zzle.transact(10, parcel, parcel1, 0); parcel1.readException(); polygonoptions = com.google.android.gms.maps.model.internal.(parcel1.readStrongBinder()); parcel1.recycle(); parcel.recycle(); return polygonoptions; parcel.writeInt(0); goto _L1 polygonoptions; parcel1.recycle(); parcel.recycle(); throw polygonoptions; } public IPolylineDelegate addPolyline(PolylineOptions polylineoptions) throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (polylineoptions == null) { break MISSING_BLOCK_LABEL_66; } parcel.writeInt(1); polylineoptions.writeToParcel(parcel, 0); _L1: zzle.transact(9, parcel, parcel1, 0); parcel1.readException(); polylineoptions = com.google.android.gms.maps.model.internal._11__08_P(parcel1.readStrongBinder()); parcel1.recycle(); parcel.recycle(); return polylineoptions; parcel.writeInt(0); goto _L1 polylineoptions; parcel1.recycle(); parcel.recycle(); throw polylineoptions; } public zzn addTileOverlay(TileOverlayOptions tileoverlayoptions) throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (tileoverlayoptions == null) { break MISSING_BLOCK_LABEL_66; } parcel.writeInt(1); tileoverlayoptions.writeToParcel(parcel, 0); _L1: zzle.transact(13, parcel, parcel1, 0); parcel1.readException(); tileoverlayoptions = com.google.android.gms.maps.model.internal._11__08_P(parcel1.readStrongBinder()); parcel1.recycle(); parcel.recycle(); return tileoverlayoptions; parcel.writeInt(0); goto _L1 tileoverlayoptions; parcel1.recycle(); parcel.recycle(); throw tileoverlayoptions; } public void animateCamera(zzd zzd1) throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (zzd1 == null) { break MISSING_BLOCK_LABEL_57; } zzd1 = zzd1.asBinder(); _L1: parcel.writeStrongBinder(zzd1); zzle.transact(5, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; zzd1 = null; goto _L1 zzd1; parcel1.recycle(); parcel.recycle(); throw zzd1; } public void animateCamera2(zzc zzc1) throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (zzc1 == null) { break MISSING_BLOCK_LABEL_57; } parcel.writeInt(1); zzc1.writeToParcel(parcel, 0); _L1: zzle.transact(65, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; parcel.writeInt(0); goto _L1 zzc1; parcel1.recycle(); parcel.recycle(); throw zzc1; } public void animateCameraWithCallback(zzd zzd1, zzb zzb1) throws RemoteException { Object obj; Parcel parcel; Parcel parcel1; obj = null; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (zzd1 == null) { break MISSING_BLOCK_LABEL_88; } zzd1 = zzd1.asBinder(); _L1: parcel.writeStrongBinder(zzd1); zzd1 = obj; if (zzb1 == null) { break MISSING_BLOCK_LABEL_49; } zzd1 = zzb1.asBinder(); parcel.writeStrongBinder(zzd1); zzle.transact(6, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; zzd1 = null; goto _L1 zzd1; parcel1.recycle(); parcel.recycle(); throw zzd1; } public void animateCameraWithCallback2(zzc zzc1, zzb zzb1) throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (zzc1 == null) goto _L2; else goto _L1 _L1: parcel.writeInt(1); zzc1.writeToParcel(parcel, 0); _L3: if (zzb1 == null) { break MISSING_BLOCK_LABEL_97; } zzc1 = zzb1.asBinder(); _L4: parcel.writeStrongBinder(zzc1); zzle.transact(66, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; _L2: parcel.writeInt(0); goto _L3 zzc1; parcel1.recycle(); parcel.recycle(); throw zzc1; zzc1 = null; goto _L4 } public void animateCameraWithDurationAndCallback(zzd zzd1, int i, zzb zzb1) throws RemoteException { Object obj; Parcel parcel; Parcel parcel1; obj = null; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (zzd1 == null) { break MISSING_BLOCK_LABEL_96; } zzd1 = zzd1.asBinder(); _L1: parcel.writeStrongBinder(zzd1); parcel.writeInt(i); zzd1 = obj; if (zzb1 == null) { break MISSING_BLOCK_LABEL_57; } zzd1 = zzb1.asBinder(); parcel.writeStrongBinder(zzd1); zzle.transact(7, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; zzd1 = null; goto _L1 zzd1; parcel1.recycle(); parcel.recycle(); throw zzd1; } public void animateCameraWithDurationAndCallback2(zzc zzc1, int i, zzb zzb1) throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (zzc1 == null) goto _L2; else goto _L1 _L1: parcel.writeInt(1); zzc1.writeToParcel(parcel, 0); _L3: parcel.writeInt(i); if (zzb1 == null) { break MISSING_BLOCK_LABEL_112; } zzc1 = zzb1.asBinder(); _L4: parcel.writeStrongBinder(zzc1); zzle.transact(67, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; _L2: parcel.writeInt(0); goto _L3 zzc1; parcel1.recycle(); parcel.recycle(); throw zzc1; zzc1 = null; goto _L4 } public IBinder asBinder() { return zzle; } public void clear() throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); zzle.transact(14, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; Exception exception; exception; parcel1.recycle(); parcel.recycle(); throw exception; } public CameraPosition getCameraPosition() throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); zzle.transact(1, parcel, parcel1, 0); parcel1.readException(); if (parcel1.readInt() == 0) goto _L2; else goto _L1 _L1: CameraPosition cameraposition = CameraPosition.CREATOR.zzdS(parcel1); _L4: parcel1.recycle(); parcel.recycle(); return cameraposition; _L2: cameraposition = null; if (true) goto _L4; else goto _L3 _L3: Exception exception; exception; parcel1.recycle(); parcel.recycle(); throw exception; } public zzj getFocusedBuilding() throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); zzj zzj1; parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); zzle.transact(44, parcel, parcel1, 0); parcel1.readException(); zzj1 = com.google.android.gms.maps.model.internal._11__08_P(parcel1.readStrongBinder()); parcel1.recycle(); parcel.recycle(); return zzj1; Exception exception; exception; parcel1.recycle(); parcel.recycle(); throw exception; } public void getMapAsync(com.google.android.gms.maps.internal.zzm zzm1) throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (zzm1 == null) { break MISSING_BLOCK_LABEL_58; } zzm1 = zzm1.asBinder(); _L1: parcel.writeStrongBinder(zzm1); zzle.transact(53, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; zzm1 = null; goto _L1 zzm1; parcel1.recycle(); parcel.recycle(); throw zzm1; } public int getMapType() throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); int i; parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); zzle.transact(15, parcel, parcel1, 0); parcel1.readException(); i = parcel1.readInt(); parcel1.recycle(); parcel.recycle(); return i; Exception exception; exception; parcel1.recycle(); parcel.recycle(); throw exception; } public float getMaxZoomLevel() throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); float f; parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); zzle.transact(2, parcel, parcel1, 0); parcel1.readException(); f = parcel1.readFloat(); parcel1.recycle(); parcel.recycle(); return f; Exception exception; exception; parcel1.recycle(); parcel.recycle(); throw exception; } public float getMinZoomLevel() throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); float f; parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); zzle.transact(3, parcel, parcel1, 0); parcel1.readException(); f = parcel1.readFloat(); parcel1.recycle(); parcel.recycle(); return f; Exception exception; exception; parcel1.recycle(); parcel.recycle(); throw exception; } public Location getMyLocation() throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); zzle.transact(23, parcel, parcel1, 0); parcel1.readException(); if (parcel1.readInt() == 0) goto _L2; else goto _L1 _L1: Location location = (Location)Location.CREATOR.omParcel(parcel1); _L4: parcel1.recycle(); parcel.recycle(); return location; _L2: location = null; if (true) goto _L4; else goto _L3 _L3: Exception exception; exception; parcel1.recycle(); parcel.recycle(); throw exception; } public IProjectionDelegate getProjection() throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); IProjectionDelegate iprojectiondelegate; parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); zzle.transact(26, parcel, parcel1, 0); parcel1.readException(); iprojectiondelegate = Q(parcel1.readStrongBinder()); parcel1.recycle(); parcel.recycle(); return iprojectiondelegate; Exception exception; exception; parcel1.recycle(); parcel.recycle(); throw exception; } public IUiSettingsDelegate getUiSettings() throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); IUiSettingsDelegate iuisettingsdelegate; parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); zzle.transact(25, parcel, parcel1, 0); parcel1.readException(); iuisettingsdelegate = V(parcel1.readStrongBinder()); parcel1.recycle(); parcel.recycle(); return iuisettingsdelegate; Exception exception; exception; parcel1.recycle(); parcel.recycle(); throw exception; } public boolean isBuildingsEnabled() throws RemoteException { Parcel parcel; Parcel parcel1; boolean flag; flag = false; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); int i; parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); zzle.transact(40, parcel, parcel1, 0); parcel1.readException(); i = parcel1.readInt(); if (i != 0) { flag = true; } parcel1.recycle(); parcel.recycle(); return flag; Exception exception; exception; parcel1.recycle(); parcel.recycle(); throw exception; } public boolean isIndoorEnabled() throws RemoteException { Parcel parcel; Parcel parcel1; boolean flag; flag = false; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); int i; parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); zzle.transact(19, parcel, parcel1, 0); parcel1.readException(); i = parcel1.readInt(); if (i != 0) { flag = true; } parcel1.recycle(); parcel.recycle(); return flag; Exception exception; exception; parcel1.recycle(); parcel.recycle(); throw exception; } public boolean isMyLocationEnabled() throws RemoteException { Parcel parcel; Parcel parcel1; boolean flag; flag = false; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); int i; parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); zzle.transact(21, parcel, parcel1, 0); parcel1.readException(); i = parcel1.readInt(); if (i != 0) { flag = true; } parcel1.recycle(); parcel.recycle(); return flag; Exception exception; exception; parcel1.recycle(); parcel.recycle(); throw exception; } public boolean isTrafficEnabled() throws RemoteException { Parcel parcel; Parcel parcel1; boolean flag; flag = false; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); int i; parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); zzle.transact(17, parcel, parcel1, 0); parcel1.readException(); i = parcel1.readInt(); if (i != 0) { flag = true; } parcel1.recycle(); parcel.recycle(); return flag; Exception exception; exception; parcel1.recycle(); parcel.recycle(); throw exception; } public void moveCamera(zzd zzd1) throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (zzd1 == null) { break MISSING_BLOCK_LABEL_57; } zzd1 = zzd1.asBinder(); _L1: parcel.writeStrongBinder(zzd1); zzle.transact(4, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; zzd1 = null; goto _L1 zzd1; parcel1.recycle(); parcel.recycle(); throw zzd1; } public void moveCamera2(zzc zzc1) throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (zzc1 == null) { break MISSING_BLOCK_LABEL_57; } parcel.writeInt(1); zzc1.writeToParcel(parcel, 0); _L1: zzle.transact(64, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; parcel.writeInt(0); goto _L1 zzc1; parcel1.recycle(); parcel.recycle(); throw zzc1; } public void onCreate(Bundle bundle) throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (bundle == null) { break MISSING_BLOCK_LABEL_57; } parcel.writeInt(1); bundle.writeToParcel(parcel, 0); _L1: zzle.transact(54, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; parcel.writeInt(0); goto _L1 bundle; parcel1.recycle(); parcel.recycle(); throw bundle; } public void onDestroy() throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); zzle.transact(57, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; Exception exception; exception; parcel1.recycle(); parcel.recycle(); throw exception; } public void onLowMemory() throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); zzle.transact(58, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; Exception exception; exception; parcel1.recycle(); parcel.recycle(); throw exception; } public void onPause() throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); zzle.transact(56, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; Exception exception; exception; parcel1.recycle(); parcel.recycle(); throw exception; } public void onResume() throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); zzle.transact(55, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; Exception exception; exception; parcel1.recycle(); parcel.recycle(); throw exception; } public void onSaveInstanceState(Bundle bundle) throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (bundle == null) { break MISSING_BLOCK_LABEL_69; } parcel.writeInt(1); bundle.writeToParcel(parcel, 0); _L1: zzle.transact(60, parcel, parcel1, 0); parcel1.readException(); if (parcel1.readInt() != 0) { bundle.readFromParcel(parcel1); } parcel1.recycle(); parcel.recycle(); return; parcel.writeInt(0); goto _L1 bundle; parcel1.recycle(); parcel.recycle(); throw bundle; } public void setBuildingsEnabled(boolean flag) throws RemoteException { Parcel parcel; Parcel parcel1; int i; i = 0; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (flag) { i = 1; } parcel.writeInt(i); zzle.transact(41, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; Exception exception; exception; parcel1.recycle(); parcel.recycle(); throw exception; } public void setContentDescription(String s) throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); parcel.writeString(s); zzle.transact(61, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; s; parcel1.recycle(); parcel.recycle(); throw s; } public boolean setIndoorEnabled(boolean flag) throws RemoteException { Parcel parcel; Parcel parcel1; boolean flag1; flag1 = true; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); int i; if (flag) { i = 1; } else { i = 0; } parcel.writeInt(i); zzle.transact(20, parcel, parcel1, 0); parcel1.readException(); i = parcel1.readInt(); if (i != 0) { flag = flag1; } else { flag = false; } parcel1.recycle(); parcel.recycle(); return flag; Exception exception; exception; parcel1.recycle(); parcel.recycle(); throw exception; } public void setInfoWindowAdapter(com.google.android.gms.maps.internal.zzd zzd1) throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (zzd1 == null) { break MISSING_BLOCK_LABEL_58; } zzd1 = zzd1.asBinder(); _L1: parcel.writeStrongBinder(zzd1); zzle.transact(33, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; zzd1 = null; goto _L1 zzd1; parcel1.recycle(); parcel.recycle(); throw zzd1; } public void setInfoWindowRenderer(com.google.android.gms.maps.internal.zze zze1) throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (zze1 == null) { break MISSING_BLOCK_LABEL_58; } zze1 = zze1.asBinder(); _L1: parcel.writeStrongBinder(zze1); zzle.transact(69, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; zze1 = null; goto _L1 zze1; parcel1.recycle(); parcel.recycle(); throw zze1; } public void setLocationSource(ILocationSourceDelegate ilocationsourcedelegate) throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (ilocationsourcedelegate == null) { break MISSING_BLOCK_LABEL_58; } ilocationsourcedelegate = ilocationsourcedelegate.asBinder(); _L1: parcel.writeStrongBinder(ilocationsourcedelegate); zzle.transact(24, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; ilocationsourcedelegate = null; goto _L1 ilocationsourcedelegate; parcel1.recycle(); parcel.recycle(); throw ilocationsourcedelegate; } public void setMapType(int i) throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); parcel.writeInt(i); zzle.transact(16, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; Exception exception; exception; parcel1.recycle(); parcel.recycle(); throw exception; } public void setMyLocationEnabled(boolean flag) throws RemoteException { Parcel parcel; Parcel parcel1; int i; i = 0; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (flag) { i = 1; } parcel.writeInt(i); zzle.transact(22, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; Exception exception; exception; parcel1.recycle(); parcel.recycle(); throw exception; } public void setOnCameraChangeListener(zzf zzf1) throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (zzf1 == null) { break MISSING_BLOCK_LABEL_58; } zzf1 = zzf1.asBinder(); _L1: parcel.writeStrongBinder(zzf1); zzle.transact(27, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; zzf1 = null; goto _L1 zzf1; parcel1.recycle(); parcel.recycle(); throw zzf1; } public void setOnIndoorStateChangeListener(zzg zzg1) throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (zzg1 == null) { break MISSING_BLOCK_LABEL_58; } zzg1 = zzg1.asBinder(); _L1: parcel.writeStrongBinder(zzg1); zzle.transact(45, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; zzg1 = null; goto _L1 zzg1; parcel1.recycle(); parcel.recycle(); throw zzg1; } public void setOnInfoWindowClickListener(com.google.android.gms.maps.internal.zzh zzh1) throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (zzh1 == null) { break MISSING_BLOCK_LABEL_58; } zzh1 = zzh1.asBinder(); _L1: parcel.writeStrongBinder(zzh1); zzle.transact(32, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; zzh1 = null; goto _L1 zzh1; parcel1.recycle(); parcel.recycle(); throw zzh1; } public void setOnMapClickListener(com.google.android.gms.maps.internal.zzj zzj1) throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (zzj1 == null) { break MISSING_BLOCK_LABEL_58; } zzj1 = zzj1.asBinder(); _L1: parcel.writeStrongBinder(zzj1); zzle.transact(28, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; zzj1 = null; goto _L1 zzj1; parcel1.recycle(); parcel.recycle(); throw zzj1; } public void setOnMapLoadedCallback(zzk zzk1) throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (zzk1 == null) { break MISSING_BLOCK_LABEL_58; } zzk1 = zzk1.asBinder(); _L1: parcel.writeStrongBinder(zzk1); zzle.transact(42, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; zzk1 = null; goto _L1 zzk1; parcel1.recycle(); parcel.recycle(); throw zzk1; } public void setOnMapLongClickListener(com.google.android.gms.maps.internal.zzl zzl1) throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (zzl1 == null) { break MISSING_BLOCK_LABEL_58; } zzl1 = zzl1.asBinder(); _L1: parcel.writeStrongBinder(zzl1); zzle.transact(29, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; zzl1 = null; goto _L1 zzl1; parcel1.recycle(); parcel.recycle(); throw zzl1; } public void setOnMarkerClickListener(com.google.android.gms.maps.internal.zzn zzn1) throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (zzn1 == null) { break MISSING_BLOCK_LABEL_58; } zzn1 = zzn1.asBinder(); _L1: parcel.writeStrongBinder(zzn1); zzle.transact(30, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; zzn1 = null; goto _L1 zzn1; parcel1.recycle(); parcel.recycle(); throw zzn1; } public void setOnMarkerDragListener(zzo zzo1) throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (zzo1 == null) { break MISSING_BLOCK_LABEL_58; } zzo1 = zzo1.asBinder(); _L1: parcel.writeStrongBinder(zzo1); zzle.transact(31, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; zzo1 = null; goto _L1 zzo1; parcel1.recycle(); parcel.recycle(); throw zzo1; } public void setOnMyLocationButtonClickListener(com.google.android.gms.maps.internal.zzp zzp1) throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (zzp1 == null) { break MISSING_BLOCK_LABEL_58; } zzp1 = zzp1.asBinder(); _L1: parcel.writeStrongBinder(zzp1); zzle.transact(37, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; zzp1 = null; goto _L1 zzp1; parcel1.recycle(); parcel.recycle(); throw zzp1; } public void setOnMyLocationChangeListener(zzq zzq1) throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (zzq1 == null) { break MISSING_BLOCK_LABEL_58; } zzq1 = zzq1.asBinder(); _L1: parcel.writeStrongBinder(zzq1); zzle.transact(36, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; zzq1 = null; goto _L1 zzq1; parcel1.recycle(); parcel.recycle(); throw zzq1; } public void setPadding(int i, int j, int k, int l) throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); parcel.writeInt(i); parcel.writeInt(j); parcel.writeInt(k); parcel.writeInt(l); zzle.transact(39, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; Exception exception; exception; parcel1.recycle(); parcel.recycle(); throw exception; } public void setTrafficEnabled(boolean flag) throws RemoteException { Parcel parcel; Parcel parcel1; int i; i = 0; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (flag) { i = 1; } parcel.writeInt(i); zzle.transact(18, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; Exception exception; exception; parcel1.recycle(); parcel.recycle(); throw exception; } public void snapshot(zzv zzv1, zzd zzd1) throws RemoteException { Object obj; Parcel parcel; Parcel parcel1; obj = null; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); if (zzv1 == null) { break MISSING_BLOCK_LABEL_88; } zzv1 = zzv1.asBinder(); _L1: parcel.writeStrongBinder(zzv1); zzv1 = obj; if (zzd1 == null) { break MISSING_BLOCK_LABEL_49; } zzv1 = zzd1.asBinder(); parcel.writeStrongBinder(zzv1); zzle.transact(38, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; zzv1 = null; goto _L1 zzv1; parcel1.recycle(); parcel.recycle(); throw zzv1; } public void stopAnimation() throws RemoteException { Parcel parcel; Parcel parcel1; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); zzle.transact(8, parcel, parcel1, 0); parcel1.readException(); parcel1.recycle(); parcel.recycle(); return; Exception exception; exception; parcel1.recycle(); parcel.recycle(); throw exception; } public boolean useViewLifecycleWhenInFragment() throws RemoteException { Parcel parcel; Parcel parcel1; boolean flag; flag = false; parcel = Parcel.obtain(); parcel1 = Parcel.obtain(); int i; parcel.writeInterfaceToken("com.google.android.gms.maps.internal.IGoogleMapDelegate"); zzle.transact(59, parcel, parcel1, 0); parcel1.readException(); i = parcel1.readInt(); if (i != 0) { flag = true; } parcel1.recycle(); parcel.recycle(); return flag; Exception exception; exception; parcel1.recycle(); parcel.recycle(); throw exception; } (IBinder ibinder) { zzle = ibinder; } }
PHP
UTF-8
1,142
2.78125
3
[ "MIT" ]
permissive
<?php /* * This file is part of the nodika project. * * (c) Florian Moser <git@famoser.ch> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace App\Model\EventLineGeneration\Nodika; class EventTypeConfiguration { /** * EventTypeConfiguration constructor. * * @param $data */ public function __construct($data) { if (null !== $data) { $this->weekday = $data->weekday; $this->saturday = $data->saturday; $this->sunday = $data->sunday; $this->holiday = $data->holiday; } else { $this->weekday = 0; $this->saturday = 0; $this->sunday = 0; $this->holiday = 0; } } /* @var double $weekday */ public $weekday; /* @var double $saturday */ public $saturday; /* @var double $sunday */ public $sunday; /* @var double $holiday */ public $holiday; public function getSumOfDays() { return $this->weekday + $this->saturday + $this->sunday + $this->holiday; } }
Markdown
UTF-8
461
2.859375
3
[ "MIT" ]
permissive
--- title: Plugin structure order: 50 --- Plugins can do two things: - They can use hooks - They can provide macros Your plugin should export an object with the following structure: ```js { name: 'myPlugin', version: '1.0.0', hooks: {}, macros: {} }; ``` The `name` and `version` attributes are self-explanatory. The [hooks](/guides/plugins/hooks/) and [macros](/guides/plugins/macros/) sections explain the `hooks` and `macros` properties.
C++
UTF-8
5,927
3.046875
3
[ "MIT" ]
permissive
#include "spaceInvaders.h" extern byte lost[]; extern byte up[]; /** * Generates a new invader at position x,y by allocating memory for a point * structure, and then adding the pointer to this point struct ot the invaders * list. * * @param x: The x coord * @param y: The y coord * @param ll: pointer to the linked lis to add the point to **/ point *SpaceInvaders::spawnInvader(uint8_t y, uint8_t x, LinkedList<point*> *ll) { point *position; position = (struct point*)malloc(sizeof(struct point)); position->x = x; position->y = y; ll->add(position); return position; } void SpaceInvaders::setupLevel() { point *inv; // Spawn the invaders - always one row of invaders more than the current // level for(uint8_t r=0; r<=level; r++) { // Now the columns - INVADERS_PER_LINE on a line, with one column open // between them for(uint8_t c=1, i=0; i<INVADERS_PER_LINE && c<LEDMATRIX_X; i++, c=c+2) { inv = spawnInvader(r, c, &invaders); display->drawPixel(inv->x, inv->y); } } changeInvDir = false; outMissile = NULL; inMissile = NULL; invadersMoveDelay = 800 - level*100; } void SpaceInvaders::moveInvaders() { point *inv; bool changeDirNext = false; for(int8_t i=invaders.size()-1; i>=0; i--) { inv = invaders.get(i); // Switch it off in old position display->drawPixel(inv->x, inv->y, false); if(changeInvDir) { // We only drop to the next row inv->y++; // Safety to see if end of screen has been reached. Normally // crashing into the ship will be the end, but we do a second check // here. if(inv->y==LEDMATRIX_Y) { gameOver = true; return; } } else { // We move in the required dir and check if we need to change the // next time we have to move again. inv->x += invadersDir; if(inv->x<=0 || inv->x>=LEDMATRIX_X-1) changeDirNext = true; } // Hit the ship? if(inv->x==ship.x && inv->y==ship.y) { gameOver=true; return; } // Draw in new position display->drawPixel(inv->x, inv->y); } // If we dropped down, we are changing direction. if(changeInvDir) { // Change direction invadersDir *= -1; // Show that we are done with the change direction changeInvDir = false; // Decrease delay invadersMoveDelay -= 10; } // Did we detect that a direction change should be done next time? if(changeDirNext) { // Set it up changeInvDir = true; } } void SpaceInvaders::destroyInvader(uint8_t i) { point *inv = invaders.remove(i); display->drawPixel(inv->x, inv->y, false); free(inv); } void SpaceInvaders::reset() { display->clear(); // Always start slow gameDelay = 200; controller->objWidth = 1; // Set the controller min and max to the screen size controller->xMin = 0; controller->xMax = LEDMATRIX_X; controller->update(); // Position ship ship.x = controller->xPos; ship.y = LEDMATRIX_Y - 1; display->drawPixel(ship.x, ship.y); // Start at level 1 level = 1; setupLevel(); // Slight delay to allow buttons to settle so we do not send a shot off // immediatly as the game starts. delay(100); // Give the user some time to gether bearings before we start moving the // invaders. nextInvadersMove = millis() + 1000; } void SpaceInvaders::updateShipMissile() { // Do we have a missile ready to move? if(outMissile && millis()>=outMissileMove) { // First check if we have hit any invaders point *p; //Serial << "Mis: " << outMissile->x << "," << outMissile->y << " Invs:"; for(int8_t i=invaders.size()-1; i>=0; i--) { p = invaders.get(i); //Serial << " " << p->x << "," << p->y; if(p->x==outMissile->x && p->y==outMissile->y) { //Serial << " bang!"; destroyInvader(i); free(outMissile); outMissile=NULL; // Any invaders left? if(invaders.size()==0) { level++; setupLevel(); } return; } } // No hits, so switch off old position display->drawPixel(outMissile->x, outMissile->y, false); // Move it in the Y plane outMissile->y--; // Out of bounds? if(outMissile->y<0) { free(outMissile); outMissile = NULL; } else { display->drawPixel(outMissile->x, outMissile->y); } //Serial << endl; // Reset the next move time outMissileMove = millis() + MISSILEDELAY; } } void SpaceInvaders::update() { // Update the ship if(controller->xPos != ship.x) { display->drawPixel(ship.x, ship.y, false); ship.x = controller->xPos; display->drawPixel(ship.x, ship.y); } // Time to move the invaders? if(millis() >= nextInvadersMove) { moveInvaders(); nextInvadersMove = millis() + invadersMoveDelay; } // Update any ship missile updateShipMissile(); // Fire a missile? if(!outMissile && (controller->rightButtonPressed || controller->leftButtonPressed)) { outMissile = (struct point*)malloc(sizeof(struct point)); outMissile->x = ship.x; outMissile->y = ship.y-1; display->drawPixel(outMissile->x, outMissile->y); outMissileMove = millis() + MISSILEDELAY; } // Clean up on game over if(gameOver) { while(invaders.size()) destroyInvader(0); display->flashSprite(lost, 4, 500); } }
JavaScript
UTF-8
2,326
3.0625
3
[]
no_license
const express = require("express"); const cors = require("cors"); const { v4: uuid, validate: isUuid } = require('uuid'); const app = express(); app.use(express.json()); app.use(cors()); const repositories = []; app.get("/repositories", (request, response) => { // TODO return response.status(200).json(repositories) }); app.post("/repositories", (request, response) => { // TODO const { title, url, techs } = request.body; const repositorie = { id: uuid(), title: title, url: url, techs: techs, likes: 0 } repositories.push(repositorie); return response.status(200).json(repositorie) }); app.put("/repositories/:id", (request, response) => { // TODO const { id } = request.params; const { title, url, techs } = request.body; const repositorieIndex = repositories.findIndex(repositorie => repositorie.id === id); if(repositorieIndex < 0){ return response.status(400).json({ error: "Repositorio não encontado" }) } // const repositorie = repositories[repositorieIndex]; const repositorie = { id, title, url, techs, } repositorie.likes = repositories[repositorieIndex].likes; repositories[repositorieIndex] = repositorie; return response.status(200).json(repositorie); }); app.delete("/repositories/:id", (request, response) => { // TODO const { id } = request.params; const repositorieIndex = repositories.findIndex(repositorie => repositorie.id === id); if(repositorieIndex < 0){ return response.status(400).json({ error: "Repositorio não encontado" }) } // tirando do array. primeiro passa o indece que quer remover, e quantas posições que remover a partir desse indice, como so quer remover ele, passa 1 repositories.splice(repositorieIndex, 1) return response.status(204).send(); }); app.post("/repositories/:id/like", (request, response) => { // TODO const {id} = request.params; const repositorieIndex = repositories.findIndex(repositorie => repositorie.id === id); if(repositorieIndex < 0){ return response.status(400).json({ error: "Repositorio não encontrado, não foi possivel dar like " }) } const repositorie = repositories[repositorieIndex]; repositorie.likes += 1; return response.status(200).json(repositorie); }); module.exports = app;
TypeScript
UTF-8
1,510
2.640625
3
[]
no_license
/* eslint-disable no-unused-vars */ /* eslint-disable no-undef */ /* eslint-disable prettier/prettier */ import { Request, Response} from "express"; import { where } from "sequelize/dist"; import { UserModel } from "../database/models/UserModels"; class UserController{ async findAll(req: Request, res: Response){ const users = await UserModel.findAll(); return users.length > 0 ? res.status(200).json(users) : res.status(204).send(); } async findOne(req: Request, res: Response){ const {userID} = req.params; const user = await UserModel.findOne({ where: { id: userID, }, }); return user ? res.status(200).json(user) : res.status(404); } async create(req: Request, res: Response){ const { name, email, age, designation, created} = req.body; console.log("teste"); const user = await UserModel.create({ name, email, age, designation, created }); return res.status(201).json(user); } async update(req: Request, res: Response){ const { userID } = req.params; await UserModel.update(req.body, { where: { id: userID, }, }); return res.status(204).send(); } async destroy(req: Request, res: Response){ const { userID } = req.params; await UserModel.destroy( { where: { id: userID, }, }); return res.status(204).send(); } } export default new UserController();
Java
UTF-8
1,810
2.390625
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2016 Althaf K Backer * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alkber.geektrust.beq1.view; /** * Display the help. * * @author Althaf K Backer <althafkbacker@gmail.com> */ public class HelpView extends View { private static String helpContent; public HelpView(final String input) { super(input); helpContent = (new StringBuilder()) .append(" rlist") .append("\n") .append(" \\_list available relations ") .append("\n") .append(" Person = { member name } ; Relation = { a relation }") .append("\n") .append(" \\_find members in the Relation wrt Person") .append("\n") .append(" Person = { member name } ; Relative = { member name }") .append("\n") .append(" \\_find Relations of Person wrt Relative") .append("\n") .append(" Father/Mother = { member name } ; Daughter/Son = { new member name }") .append("\n") .append(" \\_create a son/daughter to an existing mother / father") .append("\n") .append(" #Daughter = { member name } ;") .append("\n") .append(" \\_find max daughter count and member related, wrt member") .append("\n") .append(" bye ") .append("\n") .append(" \\_exit query session ") .toString(); } @Override public String output() { return helpContent; } }
Java
UTF-8
1,441
1.632813
2
[]
no_license
package tencent.im.cs.smart_device_proxy; import com.tencent.mobileqq.hotpatch.NotVerifyClass; import com.tencent.mobileqq.pb.ByteStringMicro; import com.tencent.mobileqq.pb.MessageMicro; import com.tencent.mobileqq.pb.MessageMicro.FieldMap; import com.tencent.mobileqq.pb.PBBytesField; import com.tencent.mobileqq.pb.PBField; import com.tencent.mobileqq.pb.PBInt32Field; public final class smart_device_proxy$ReqBody extends MessageMicro { public static final int BYTES_BODY_FIELD_NUMBER = 3; public static final int INT32_CMD_FIELD_NUMBER = 1; public static final int MSG_HEADER_FIELD_NUMBER = 2; static final MessageMicro.FieldMap __fieldMap__; public final PBBytesField bytes_body = PBField.initBytes(ByteStringMicro.EMPTY); public final PBInt32Field int32_cmd = PBField.initInt32(0); public smart_device_proxy.CommonHead msg_header = new smart_device_proxy.CommonHead(); static { boolean bool = NotVerifyClass.DO_VERIFY_CLASS; ByteStringMicro localByteStringMicro = ByteStringMicro.EMPTY; __fieldMap__ = MessageMicro.initFieldMap(new int[] { 8, 18, 26 }, new String[] { "int32_cmd", "msg_header", "bytes_body" }, new Object[] { Integer.valueOf(0), null, localByteStringMicro }, ReqBody.class); } } /* Location: E:\apk\QQ_91\classes5-dex2jar.jar!\tencent\im\cs\smart_device_proxy\smart_device_proxy$ReqBody.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
JavaScript
UTF-8
2,249
2.75
3
[]
no_license
makeHandleEvent = (client, clientManager, chatroomManager) => { ensureExists = (getter, rejectionMessage) => { return new Promise((resolve, reject) => { const res = getter(); return res ? resolve(res) : reject(rejectionMessage); }) } ensureValidChatroom = (chatroomName) => { return ensureExists(() => chatroomManager.getChatroomByName(chatroomName), `invalid chatroom name: ${chatroomName}`); } handleEvent = (chatroomName, username, createEntry) => { return ensureValidChatroom(chatroomName) .then((chatroom) => { const entry = { client: username, ...createEntry() }; chatroom.addEntry(entry); chatroom.broadcastMessage({ chat: chatroomName, ...entry }); return chatroom; }) } return handleEvent; } module.exports = (client, clientManager, chatroomManager) => { const handleEvent = makeHandleEvent(client, clientManager, chatroomManager); handleJoin = (chatroomName, username, cb) => { const entry = { sender: username, timestamp: new Date().getTime(), msg: `${username} joined ${chatroomName}` }; const chatroom = chatroomManager.getChatroomByName(chatroomName); chatroom.addClient(client); chatroom.broadcastMessage({ chat: chatroomName, ...entry }, username); chatroom.getChatHistory().then((chatHistory) => { console.log(chatHistory); cb(null, chatHistory); }).catch((e) => cb(e, null)); } handleMessage = (chatroomName, sender, message, cb) => { const entry = { sender, timestamp: new Date().getTime(), msg : message }; if (!chatroomManager.chatroomExists(chatroomName)) cb('Chatroom does not exist', null); const chatroom = chatroomManager.getChatroomByName(chatroomName); chatroom.addEntry(entry).then(() => { chatroom.broadcastMessage(entry, sender); return chatroom.getChatHistory(); }).then((chatHistory) => { console.log(chatHistory); cb(null, chatHistory); }).catch(e => cb(e, null)); } return { handleJoin, handleMessage } }
Ruby
UTF-8
1,581
2.765625
3
[]
no_license
require 'nokogiri' require 'open-uri' require 'pry' require 'csv' require 'rest-client' require "selenium-webdriver" require 'watir' # MAIN_PAGE = 'https://eth.2miners.com/en/miners' # url = 'https://btg.2miners.com/api/miners' # response = RestClient.get(url, headers={}) # miners = JSON.parse(response.body)['miners'].keys # miners.each do |wallet_id| # info_url = "https://btg.2miners.com/api/accounts/#{wallet_id}" # response = RestClient.get(info_url, headers={}) # data = JSON.parse(response.body) # binding.pry # end # Fetch and parse HTML document # doc = Nokogiri::HTML(open(MAIN_PAGE)) driver = Selenium::WebDriver.for :chrome # browser = Watir::Browser.new :chrome existing_accounts = CSV.read('data.csv').map {|e| e[0] } CSV.foreach("/Users/egorvorobiev/Downloads/miners.csv") do |row| url = row.last account_id = url.split('/').last if existing_accounts.include?(account_id) p 'SKIPPED ' + account_id next end driver.navigate.to url elements = driver.find_elements(class: 'textfill') total_paid = elements[2].text average_rate = elements[6].text CSV.open("data.csv", "ab") do |csv| csv << [account_id, total_paid, average_rate] end end # puts "### Search for nodes by css" # doc.css('nav ul.menu li a', 'article h2').each do |link| # puts link.content # end # puts "### Search for nodes by xpath" # doc.xpath('//nav//ul//li/a', '//article//h2').each do |link| # puts link.content # end # puts "### Or mix and match." # doc.search('nav ul.menu li a', '//article//h2').each do |link| # puts link.content # end
Java
UTF-8
2,604
1.570313
2
[]
no_license
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.ebay.mobile.recents; import android.text.TextUtils; import com.ebay.nautilus.domain.EbaySite; import com.ebay.nautilus.domain.data.PdsSearchItemAttribute; import com.ebay.nautilus.domain.net.EbayRequest; import com.ebay.nautilus.domain.net.api.pds.PdsSetAttrRequest; import com.ebay.nautilus.kernel.content.ResultStatus; import java.util.List; // Referenced classes of package com.ebay.mobile.recents: // RecentsDataManager private final class productPrefix extends productPrefix { final long categoryId; final boolean isSellerPrefix; final boolean isSpelledCorrectly; final String keyword; final List list = null; final String productPrefix; final int searchResultCount; final RecentsDataManager this$0; protected volatile EbayRequest getRequest() { return getRequest(); } protected PdsSetAttrRequest getRequest() { PdsSearchItemAttribute pdssearchitemattribute = new PdsSearchItemAttribute(keyword, categoryId, searchResultCount, isSpelledCorrectly, isSellerPrefix, productPrefix); return new PdsSetAttrRequest(iafToken, cguid, site.idString, "10203", pdssearchitemattribute.toString()); } protected void onCancelled(ResultStatus resultstatus) { super.Cancelled(resultstatus); RecentsDataManager.access$500(RecentsDataManager.this, this, null); } protected volatile void onCancelled(Object obj) { onCancelled((ResultStatus)obj); } protected void onPostExecute(ResultStatus resultstatus) { super.PostExecute(resultstatus); RecentsDataManager.access$500(RecentsDataManager.this, this, resultstatus); } protected volatile void onPostExecute(Object obj) { onPostExecute((ResultStatus)obj); } (String s, boolean flag, long l, int i, boolean flag1, String s1) { Object obj = null; this$0 = RecentsDataManager.this; super(RecentsDataManager.this, RecentsDataManager.access$200(RecentsDataManager.this).nit>); categoryId = l; searchResultCount = i; isSpelledCorrectly = flag1; isSellerPrefix = flag; keyword = s; recentsdatamanager = obj; if (!TextUtils.isEmpty(s1)) { recentsdatamanager = (new StringBuilder()).append(s1).append(":").toString(); } productPrefix = RecentsDataManager.this; } }
Java
UTF-8
92
1.90625
2
[]
no_license
package dao; import model.Order; public interface OrderDao { Long save(Order order); }
TypeScript
UTF-8
782
2.6875
3
[]
no_license
import Vue from 'vue' import Vuex from 'vuex' import axios from 'axios' Vue.use(Vuex) interface RootState { results: Array<any>; total: number | null; } const store = { state: { results: [], total: null }, getters: {}, mutations: { SET_RESULTS(state, { items, total }) { state.results = items state.total = total }, RESET_RESULTS(state) { state.results = [] } }, actions: { async GET_RESULTS({ commit }, payload) { const { data } = await axios.get('https://api.github.com/search/users', { params: { q: payload } }) commit('SET_RESULTS', { items: data.items, total: data.total_count }) } } } export default new Vuex.Store<RootState>(store)
Python
UTF-8
814
2.625
3
[ "MIT" ]
permissive
class Account: def __init__(self, twitter_handle='', name='', bio='', following=False, followers=False, total_tweets=0): self.id = -1 self.bio = bio self.name = name self.twitter_handle = twitter_handle self.followers = followers self.following = following self.is_following_me = False self.iam_following = False self.total_tweets = total_tweets def get_data(self): if self.is_following_me: f_me = 1 else: f_me = 0 if self.iam_following: iam_f = 1 else: iam_f = 0 return (self.name, self.twitter_handle, self.bio, \ self.followers, self.following, self.total_tweets, \ f_me, iam_f)
C++
UTF-8
877
3
3
[ "MIT" ]
permissive
#pragma once #include "GameConst.h" #include "Evaluator.h" class GameState { public: GameState(void); GameState(const GameState& state); ~GameState(void); const GameState& operator=(const GameState& state); void SetCurrentPlayer(int player_id) { m_playerId = player_id; }; int GetCurrentPlayer() const { return m_playerId; }; void ClearGameCell(int cell) { m_board[cell] = PLAYER_NULL; } void SetGameCell(int cell, int player_id); int GetGameCell(int cell) { return m_board[cell]; }; bool IsEmptyCell(int cell) const; void PrintGame(); void InitGameState(int firstPlayer); void SwitchPlayer(); bool IsGameOver(); int GetWinner(); protected: CellType GetCellType(int player_id); int CountThreeLine(int player_id); int CountEmptyCell(); protected: int m_playerId; int m_board[BOARD_CELLS]; };
Java
UTF-8
1,737
2.5625
3
[]
no_license
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.text.*; import java.util.*; public class updateProductsDB extends HttpServlet implements Serializable{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter printWriter = response.getWriter(); try { String id = request.getParameter("prodid"); String qtyup = request.getParameter("qtyup"); OracleDB odb = new OracleDB(); boolean check = odb.checkCapacity(qtyup); if(check==false) { HttpSession ses = request.getSession(); String seqVal; seqVal = (String)ses.getAttribute("seqValue"); if(seqVal == null){ int newSeq = odb.getPurchaseSeqValue(); ses.setAttribute("seqValue", String.valueOf(newSeq)); seqVal = (String)ses.getAttribute("seqValue"); odb.updatePurchaseHeader(Integer.parseInt(id),Integer.parseInt(seqVal)); } odb.updateProductInventory(id,qtyup); System.out.println("Sending id in updateProductsDB :"+Integer.parseInt(id)); odb.updatePurchaseLines(Integer.parseInt(id),Integer.parseInt(qtyup),Integer.parseInt(seqVal)); response.sendRedirect("updateProducts"); } else { StringBuilder s = new StringBuilder(); s.append("<h2> Cannot add more products, Store capacity already full</h2>\n" +"<br>"); Utilities utility = new Utilities(printWriter,request); utility.printHtml("header.html",""); utility.printHtml("sidebar.html",""); utility.printHtml("cart",s.toString()); utility.printHtml("footer.html",""); } } catch(Exception e) { e.printStackTrace(); } } }
Java
UTF-8
2,239
2.453125
2
[]
no_license
package com.spring.mybatis; public class User { /** * This field was generated by MyBatis Generator. This field corresponds to the database column user.id * @mbg.generated Fri Apr 21 12:30:52 CST 2017 */ private Integer id; /** * This field was generated by MyBatis Generator. This field corresponds to the database column user.name * @mbg.generated Fri Apr 21 12:30:52 CST 2017 */ private String name; /** * This field was generated by MyBatis Generator. This field corresponds to the database column user.age * @mbg.generated Fri Apr 21 12:30:52 CST 2017 */ private Integer age; /** * This method was generated by MyBatis Generator. This method returns the value of the database column user.id * @return the value of user.id * @mbg.generated Fri Apr 21 12:30:52 CST 2017 */ public Integer getId() { return id; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column user.id * @param id the value for user.id * @mbg.generated Fri Apr 21 12:30:52 CST 2017 */ public void setId(Integer id) { this.id = id; } /** * This method was generated by MyBatis Generator. This method returns the value of the database column user.name * @return the value of user.name * @mbg.generated Fri Apr 21 12:30:52 CST 2017 */ public String getName() { return name; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column user.name * @param name the value for user.name * @mbg.generated Fri Apr 21 12:30:52 CST 2017 */ public void setName(String name) { this.name = name; } /** * This method was generated by MyBatis Generator. This method returns the value of the database column user.age * @return the value of user.age * @mbg.generated Fri Apr 21 12:30:52 CST 2017 */ public Integer getAge() { return age; } /** * This method was generated by MyBatis Generator. This method sets the value of the database column user.age * @param age the value for user.age * @mbg.generated Fri Apr 21 12:30:52 CST 2017 */ public void setAge(Integer age) { this.age = age; } }
TypeScript
UTF-8
3,363
2.578125
3
[ "MIT" ]
permissive
"use strict"; import {Logger} from "../../src/logger"; import {Severity} from "../../src/interfaces"; describe("Test logger", () => { it("should log message with 'trace' severity", () => { const logger = new Logger('app'); const sourceMessage = "some log message"; const destMessage = { facility: 'app', severity: 'trace', message: ['some log message'] }; expect(logger.trace(sourceMessage)).toMatchObject(destMessage); expect(logger.trace(sourceMessage)).toHaveProperty('date'); }); it("should log message with 'debug' severity", () => { const logger = new Logger('app'); const sourceMessage = "some log message"; const destMessage = { facility: 'app', severity: 'debug', message: ['some log message'] }; expect(logger.debug(sourceMessage)).toMatchObject(destMessage); expect(logger.debug(sourceMessage)).toHaveProperty('date'); }); it("should log message with 'warn' severity", () => { const logger = new Logger('app'); const sourceMessage = "some log message"; const destMessage = { facility: 'app', severity: 'warn', message: ['some log message'] }; expect(logger.warn(sourceMessage)).toMatchObject(destMessage); expect(logger.warn(sourceMessage)).toHaveProperty('date'); }); it("should log message with 'info' severity", () => { const logger = new Logger('app'); const sourceMessage = "some log message"; const destMessage = { facility: 'app', severity: 'info', message: ['some log message'] }; expect(logger.info(sourceMessage)).toMatchObject(destMessage); expect(logger.info(sourceMessage)).toHaveProperty('date'); }); it("should log message with 'error' severity", () => { const logger = new Logger('app'); const sourceMessage = "some log message"; const destMessage = { facility: 'app', severity: 'error', message: ['some log message'] }; expect(logger.error(sourceMessage)).toMatchObject(destMessage); expect(logger.error(sourceMessage)).toHaveProperty('date'); }); it("should log message with 'fatal' severity", () => { const logger = new Logger('app'); const sourceMessage = "some log message"; const destMessage = { facility: 'app', severity: 'fatal', message: ['some log message'] }; expect(logger.fatal(sourceMessage)).toMatchObject(destMessage); expect(logger.fatal(sourceMessage)).toHaveProperty('date'); }); it("should format message", () => { const logger = new Logger('app'); const sourceMessage = "some log message"; expect(logger.prepareMessage(Date.now(), Severity.Debug, sourceMessage)).toHaveProperty('date'); expect(logger.prepareMessage(Date.now(), Severity.Debug, sourceMessage)).toHaveProperty('facility'); expect(logger.prepareMessage(Date.now(), Severity.Debug, sourceMessage)).toHaveProperty('severity'); expect(logger.prepareMessage(Date.now(), Severity.Debug, sourceMessage)).toHaveProperty('message'); }); });
Python
UTF-8
1,903
3.921875
4
[]
no_license
# -*- coding: utf-8 -*- #Forklarer programmet til brukeren: print("Dette programmet kan regne ut en bestand av dyr etter et bestemt antall år, hvis du vet endringsprosenten og nåværende bestand") endring = input("Synker eller vokser bestanden?") #Det første brukeren ser - bestemmer hvilken "if" synker=["Synker", " Synker", "synker", " synker", "Den synker", "Bestanden synker"] #Lister, så flere måter å skrive 'synker' og 'vokser' forstås vokser=["Vokser", " Vokser", "vokser", " vokser", "Den vokser", "Bestanden vokser"] if endring in synker: Bnå=int(input("Hva er den nåverende bestanden?")) #Finner variablene programmet trenger for å regne ut bestanden p=float(input("Hvor mange prosent synker bestanden med per år?")) t=float(input("Hvor mange år fra i dag vil du vite hva bestanden er?")) #Setter r=1 for å ha en variabel som kan 'avbryte' løkken r=1 while r<=t: Bny=(Bnå*(1-(p/100))) Bnå=Bny r+=1 print("Bestanden etter ", t, "år, er ", int(Bny), "individer") #Output elif endring in vokser: Bnå=int(input("Hva er den nåværende bestanden?")) #Finner variablene programmet trenger for å regne ut bestanden p=float(input("Hvor mange prosent vokser bestanden med per år?")) t=float(input("Hvor mange år fra i dag vil du vite hva bestanden er?")) #Setter r=1 for å ha en variabel som kan 'avbryte' løkken r=1 while r<=t: Bny=(Bnå*(1+(p/100))) Bnå=Bny r+=1 print("Bestanden etter ", t, "år, er ", int(Bny), "individer") #Output else: print("Oi da, jeg skjønte ikke hva du skrev. Prøv igjen!") #Feilmelding hvis programmet ikke skjønner svaret fra første input
Java
UTF-8
1,074
2.28125
2
[]
no_license
package com.ss.stg; import com.ss.stg.R; import android.view.View; import android.widget.ImageView; import android.widget.TextView; public class TourViewWrapper { private View view; private String id; private ImageView statusImageView; private TextView nameTextView; private TextView dateTextView; public TourViewWrapper(View view) { this.view = view; } public String getId() { return id; } public void setId(String id) { this.id = id; } public View getView() { return view; } public TextView getNameTextView() { if (this.nameTextView == null) { this.nameTextView = (TextView) this.view.findViewById(R.id.tour_item_name); } return this.nameTextView; } public TextView getDateTextView() { if (this.dateTextView == null) { this.dateTextView = (TextView) this.view.findViewById(R.id.tour_item_time); } return dateTextView; } public ImageView getStatusImageView() { if (this.statusImageView == null) { this.statusImageView = (ImageView) this.view.findViewById(R.id.tour_item_image); } return statusImageView; } }
Java
UTF-8
857
2.515625
3
[]
no_license
private void run(final String prefix, final MessageDigest messageDigest) throws IOException { if (inputs == null) { println(prefix, DigestUtils.digest(messageDigest, System.in)); return; } for(final String source : inputs) { final File file = new File(source); if (file.isFile()) { println(prefix, DigestUtils.digest(messageDigest, file), source); } else if (file.isDirectory()) { final File[] listFiles = file.listFiles(); if (listFiles != null) { run(prefix, messageDigest, listFiles); } } else { // use the default charset for the command-line parameter final byte[] bytes = source.getBytes(Charset.defaultCharset()); println(prefix, DigestUtils.digest(messageDigest, bytes)); } } }
Python
UTF-8
216
2.5625
3
[]
no_license
import pandas as pd import numpy as np own = pd.read_csv('sub_cat_5.csv') best = pd.read_csv('sub_gbm_4.csv') alpha = 0.1 new = own*(1-alpha) + best*alpha new.to_csv('stack_3.csv', index=False) print(new.head())
JavaScript
UTF-8
4,144
2.984375
3
[]
no_license
/* jWidget Lib source file. Copyright (C) 2015 Egor Nepomnyaschih This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * @class * * `<T>` * * View synchronizer with array. Listens all array events and reduces them to 2 granular functions: * item is added into specific position and item is removed from specific position. In optimization purposes, * you can define a third function: array is cleared * (in case if there is more effective clearing algorithm than iterative items deletion). * Unlike JW.AbstractCollection.Observer, tracks items order. * * Use JW.AbstractArray#createInserter method to create the synchronizer. * * var inserter = array.{@link JW.AbstractArray#createInserter createInserter}({ * {@link #cfg-addItem addItem}: function(item, index) { this.store.insert(item, index); }, * {@link #cfg-removeItem removeItem}: function(item, index) { this.store.remove(index); }, * {@link #cfg-scope scope}: this * }); * * The method will select which synchronizer implementation fits better (simple or observable). * * Synchronizer rules: * * - Function {@link #cfg-addItem} is called for all items of source array on synchronizer initialization. * - Function {@link #cfg-clearItems} is called for array, or function {@link #cfg-removeItem} is called for * all items of source array on synchronizer destruction. * - On source array reordering, items order is synchorinized by callback functions calls. * * @extends JW.Class * * @constructor * Creates synchronizer. JW.AbstractArray#createInserter method is preferrable instead. * @param {JW.AbstractArray} source `<T>` Source array. * @param {Object} config Configuration (see Config options). */ JW.AbstractArray.Inserter = function(source, config) { JW.AbstractArray.Inserter._super.call(this); config = config || {}; this.source = source; this.addItem = config.addItem; this.removeItem = config.removeItem; this.clearItems = config.clearItems; this.scope = config.scope || this; this._addItems(this.source.getItems(), 0); }; JW.extend(JW.AbstractArray.Inserter, JW.Class, { /** * @cfg {Function} addItem * * `addItem(item: T, index: number): void` * * Item is added to specific position in array. */ /** * @cfg {Function} removeItem * * `removeItem(item: T, index: number): void` * * Item is removed from specific position in array. */ /** * @cfg {Function} clearItems * * `clearItems(items: Array<T>): void` * * Array is cleared. By default, calls {@link #removeItem} for all array items. */ /** * @cfg {Object} scope {@link #addItem}, {@link #removeItem}, {@link #clearItems} call scope. */ /** * @property {JW.AbstractArray} source `<T>` Source array. */ destroyObject: function() { this._clearItems(this.source.getItems()); this.source = null; this.addItem = null; this.removeItem = null; this.clearItems = null; this.scope = null; this._super(); }, _addItems: function(items, index) { if (!this.addItem) { return; } for (var i = 0; i < items.length; ++i) { this.addItem.call(this.scope, items[i], i + index); } }, _removeItems: function(items, index) { if (!this.removeItem) { return; } for (var i = items.length - 1; i >= 0; --i) { this.removeItem.call(this.scope, items[i], i + index); } }, _clearItems: function(items) { if (items.length === 0) { return; } if (this.clearItems) { this.clearItems.call(this.scope || this, items); } else { this._removeItems(items, 0); } } });
Markdown
UTF-8
6,183
2.828125
3
[]
no_license
--- id: overrides title: Overrides sidebar_label: Overrides --- When making a custom contract type, ideally you want to reuse as much logic as possible between the maps your custom contract type is used on. All common logic to build and power your custom contract type is in the `common.jsonc` file. See [Structure](../contract-builder/structure.md) for more information on the `common.jsonc` format). As much as you can reuse, there will always be bits of your contract type that are map specific and need to be set for the specific map. These are mostly things like: - Positions (Spawns, turrets, regions etc) - Map boundary (Position and size) - Plots (Which plots are enabled) - ...Any other map-specific variation for your custom contract type you wish to change The override files look different to the `common.jsonc` file structure. It uses the [Json.NET query/select system](https://www.newtonsoft.com/json/help/html/QueryJsonSelectTokenJsonPath.htm) system to select parts of your `common.jsonc` and change the data with newly specified data. A good way to learn is to open up the Mission Control mod folder and read the files in `MissionControl/contractTypeBuilds/(ContactType)`. The naming convention for override files is freeform, however, MissionControl uses: `mapname_descriptivevariation`, for example `deathvalley_desert_open_area` where the map is `mapArena_deathValley_aDes` and this override limits the contract type to take place in the open area of that map. You can have multiple overrides for the same map and contract type combination as long as a unique 'encounter layer' is created per variation. ## Override Structure ```json // This file overrides the contract type 'common.jsonc' file with map specific values (such as locations and rotations) { "EncounterLayerId": "mapStory_StoryEncounter3_mMoon.5f862402-45c0-495c-9fb2-604dae9a2ad6", "Overrides": [ { "Path": "Chunks[?(@.Name == 'Chunk_PlayerLance')].Children[?(@.Name == 'Spawner_PlayerLance')]", "Action": "ObjectMerge", "Value": { "Name": "Spawner_PlayerLance", "Position": { "Type": "World", "Value": { "x": -300, "y": 140, "z": 20 } }, "Rotation": { "Type": "World", "Value": { "x": 0, "y": 30, "z": 0 } } } }, { "Path": "Chunks[?(@.Name == 'Chunk_DestroyWholeLance')].Children[?(@.Name == 'Lance_Enemy_OpposingForce')]", "Action": "ObjectMerge", "Value": { "Name": "Lance_Enemy_OpposingForce", "Position": { "Type": "World", "Value": { "x": 230, "y": 150, "z": 420 } }, "Rotation": { "Type": "World", "Value": { "x": 0, "y": 270, "z": 0 } } } }, { "Path": "Chunks[?(@.Name == 'Chunk_EncounterBoundary')].Children[?(@.Name == 'EncounterBoundaryRect')]", "Action": "ObjectMerge", "Value": { "Name": "EncounterBoundaryRect", "Position": { "Type": "World", "Value": { "x": 15, "y": 50, "z": 450 } }, "Width": 900, "Length": 1024 } } ] } ``` ### Top level | Property | Required | Default | Details | | ---------------- | -------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | EncounterLayerId | true | - | ID of the encounter layer (contract type + map combination) you wish to override. <br /><br /> You find this from the encounter layers you created as mentioned [in the set up](../contract-builder/setup.md) or on existing modder created encounter layers found in `MissionControl/overrides/encounterLayers/(ContractType)` or elsewhere defined. <br /><br /> The format is always `(map name).(uuid)` | | Overrides | true | - | List of override operations to perform to override data | ### Overrides | Property | Required | Default | Details | | -------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Path | true | - | [Json.NET query/select system](https://www.newtonsoft.com/json/help/html/QueryJsonSelectTokenJsonPath.htm) path naviagion method. <br /><br />A good tip is to review existing overrides and copy their structure. | | Action | true | - | This defines the action to perform on the selected JSON property.<br /><br />Available actions are: `Replace`, `Remove`, `ObjectMerge`. Mostly `ObjectMerge` is used. | | Value | true | - | This defines the new JSON, or value, you wish to use if you selected `Replace` or `ObjectMerge` actions |
PHP
UTF-8
2,339
2.59375
3
[ "MIT" ]
permissive
<?php namespace App\Service\Master; use DB; use Auth; use Illuminate\Validation\Rule; use App\Repository\Master\Sasaran; class SasaranService { public static function get_validation($id = 0) { $rules = [ 'id_program_kerja' => ['required'] ]; if ($id == 0) { $rules = array_merge( $rules, ['nama' => [ 'required', Rule::unique('mst_sasaran', 'nama')->where(function ($query) { return $query->where('is_deleted', 0); }) ]] ); } else { $rules = array_merge( $rules, ['nama' => [ 'required', Rule::unique('mst_sasaran', 'nama')->where(function ($query) use ($id) { return $query->where('is_deleted', 0)->where("id", "!=", $id); }) ]] ); } $label = [ 'nama.required' => 'Nama Sasaran harus diisi!', 'nama.unique' => 'Nama Sasaran sudah ada!', ]; return (object) array( 'rules' => $rules, 'label' => $label ); } public static function create($data) { $t = new Sasaran; return self::proccess_data($t, $data); } public static function update($id, $data) { $t = Sasaran::findOrFail($id); return self::proccess_data($t, $data); } public static function createOrUpdate($id, $data) { $t = Sasaran::findOrNew($id); return self::proccess_data($t, $data); } private static function proccess_data(Sasaran $sasaran, $data) { DB::transaction(function () use ($sasaran, $data) { $t = $sasaran; $t->nama = $data['nama']; $t->id_program_kerja = $data['id_program_kerja']; $t->save(); DB::commit(); }); return $sasaran; } public static function delete($id) { $t = Sasaran::findOrFail($id)->delete(); } public static function delete_by_program_kerja($id_program_kerja) { $t = Sasaran::where('id_program_kerja', $id_program_kerja)->update(array('is_deleted' => 1)); } public static function get_by_id_sasaran($id_sasaran = 0) { $data = Sasaran::where('id_sasaran', $id_sasaran)->get(); return $data; } public static function get_sasaran_by_id_program_kerja($id = 0) { $data = Sasaran::where('id_program_kerja', $id) ->where('is_deleted', 0) ->get(); return $data; } }
C++
UTF-8
1,155
2.515625
3
[]
no_license
#include<stdio.h> #include<queue> #include<memory.h> using namespace std; int dx[4] = { 0, 0, 1, -1 }; int dy[4] = { 1, -1, 0, 0 }; char map[55][55] = {}; int chk[55][55] = {}; int l, w; queue<int>qx; queue<int>qy; int qstart(int x, int y) { memset(chk, 40, sizeof(chk)); chk[x][y] = 0; qx.push(x); qy.push(y); while (qx.size()) { int nx = qx.front(); qx.pop(); int ny = qy.front(); qy.pop(); for (int d = 0; d < 4; d++) { if (map[nx + dx[d]][ny + dy[d]] == 'L'&&chk[nx + dx[d]][ny + dy[d]] > chk[nx][ny] + 1) { chk[nx + dx[d]][ny + dy[d]] = chk[nx][ny] + 1; qx.push(nx + dx[d]); qy.push(ny + dy[d]); } } } int maxi = 0; for (int i = 1; i <= l; i++) { for (int j = 1; j <= w; j++) { if (chk[i][j]<10000 && chk[i][j]>maxi) maxi = chk[i][j]; } } return maxi; } int main() { memset(map, 'W', sizeof(map)); scanf("%d %d", &l, &w); for (int i = 1; i <= l; i++) { scanf("%s", map[i] + 1); } int ans = 0; for (int i = 1; i <= l; i++) { for (int j = 1; j <= w; j++) { if (map[i][j] == 'L') { int tmp = qstart(i, j); if (ans < tmp) ans = tmp; } } } printf("%d\n", ans); return 0; }
Java
UTF-8
2,310
2.78125
3
[]
no_license
package com.angelo.androidprova.core; import java.io.Serializable; import android.util.Log; class CPPMnode implements Serializable { public CPPMnode child; public CPPMnode next; public CPPMnode vine; public short count; public int symbol; public int id; static int CPPMNOdeCount = 0; /* * CSFS: Found that the C++ code used a short to represent a symbol in * certain places and an int in others. As such, I've changed it to int * everywhere. This ought to cause no trouble except in the case that * behaviour on overflow is relied upon. */ public CPPMnode(int sym) { Log.e("CPPMnode sym", "CPPMNOdeCount" + (CPPMNOdeCount++)); child = null; next = null; vine = null; count = 1; symbol = sym; } public CPPMnode() { // Log.e("CPPMnode null", "CPPMNOdeCount" + (CPPMNOdeCount++)); child = null; next = null; vine = null; count = 1; id = CPPMNOdeCount++; } public boolean isLeaf() { return child == null; } public CPPMnode find_symbol(int sym) // see if symbol is a child of node { CPPMnode found = child; /* * CSFS: I *think* this is supposed to be a pointer-copy but I'm not * perfectly sure. If the find_symbol method fails, this may need to * become a .clone() */ while (found != null) { if (found.symbol == sym) { return found; } found = found.next; } return null; } @Override public String toString() { StringBuffer sb = new StringBuffer("CHILD_LIST: "); int childCount = 0; CPPMnode found = child; while (found != null) { childCount++; sb.append(found.symbol+" "); found = found.next; } // TODO Auto-generated method stub return "symbol " + (symbol + 0x60) + (vine == null ? "" : (" vine " + vine.symbol)) + " childCount " + childCount + " count " + count + sb; } /* * private void writeObject(ObjectOutputStream out) throws IOException { * * out.writeObject(child); out.writeObject(next); out.writeObject(vine); * out.writeInt(symbol); out.writeInt(count); * * } * * private void readObject(ObjectInputStream in) throws IOException, * ClassNotFoundException { * * child = (CPPMnode) in.readObject(); next = (CPPMnode) in.readObject(); * vine = (CPPMnode) in.readObject(); symbol = in.readInt(); count = * in.readShort(); } */ }
C++
UTF-8
405
2.53125
3
[]
no_license
#pragma once #include "IWriter.h" #include <string> class MediaPlayer { public: MediaPlayer(); ~MediaPlayer(); void setTitle(const std::string&); std::string getTitle(); void setDuration(const double&); double getDuration(); virtual void WriteTo(IWriter* write) = 0; private: std::string title_; double duration_; };
Python
UTF-8
1,340
2.984375
3
[ "MIT" ]
permissive
from typing import List from matplotlib import pyplot as plt FILE_NAME = 'cwnd_data.log' with open(FILE_NAME, 'r') as f_in: data: List[str] = f_in.readlines() data: List[str] = [x.strip(' \n') for x in data] initial_time = float(data[0].split(' ')[1]) data_time, data_cwnd, data_ssthresh = [], [], [] for line in data: tokens: List[str] = line.split(' ') data_time.append(float(tokens[1]) - initial_time) data_cwnd.append(float(tokens[5])) data_ssthresh.append(float(tokens[7])) window_size = 5 ignore_initial_data_points = 100 def moving_average(numbers: List): moving_averages = [] i = 0 while i < len(numbers) - window_size + 1: this_window = numbers[i: i + window_size] window_average = sum(this_window) / window_size moving_averages.append(window_average) i += 1 return moving_averages data_time = moving_average(data_time[ignore_initial_data_points:]) data_cwnd = moving_average(data_cwnd[ignore_initial_data_points:]) data_ssthresh = moving_average(data_ssthresh[ignore_initial_data_points:]) plt.plot(data_time, data_cwnd, label='cwnd', c='r') plt.plot(data_time, data_ssthresh, label='ssthresh', c='b') plt.xlabel('Time Diff from initial in seconds', fontsize=25) plt.ylabel('cwnd/ssthresh in MSS', fontsize=25) plt.legend(fontsize = 25) plt.show()
Java
UTF-8
2,618
2.578125
3
[]
no_license
package com.yc.myTomcat; import com.yc.javax.servlet.Servlet; import com.yc.javax.servlet.http.HttpServlet; import com.yc.javax.servlet.http.HttpServletRequest; import com.yc.javax.servlet.http.HttpServletResponse; import java.io.OutputStream; import java.net.URL; import java.net.URLClassLoader; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class DynamicProcessor implements Processor{ //存放servlet实例 static Map<String,Servlet> servletMap=new ConcurrentHashMap<>(); @Override public void process(HttpServletRequest request, HttpServletResponse response) { //1.取出uri中servlet的名字 -> HelloServlet的字节码 String uri=request.getUri(); int slash=uri.lastIndexOf("/")+1; int dot=uri.lastIndexOf("."); String basePath=request.getRealPath();//D:\ideaworkspace\myTomcat\webapps\ String servletName=uri.substring(slash,dot); try { Servlet servlet=null; HttpServlet ser=null; if(servletMap.containsKey(servletName+".action")){ servlet=servletMap.get(servletName+".action"); }else{ //2.加载 URLClassLoader URL url=new URL("file",null,basePath); URL[] urls=new URL[]{url}; URLClassLoader ucl=new URLClassLoader(urls); Class cls=ucl.loadClass(servletName); //3.反射 -> Class.newInstance servlet=(Servlet)cls.newInstance(); ser=(HttpServlet)servlet; ser.init(); servletMap.put(servletName+".action",servlet); } //4.按Servlet的生命周期调用 if(servlet!=null && servlet instanceof HttpServlet){ ser=(HttpServlet)servlet; ser.service(request,response); } }catch (Exception e){ e.printStackTrace(); String content=e.getMessage(); String protocal=gen500(content.getBytes()); try(OutputStream oos=response.getOutputStream();){ oos.write(protocal.getBytes()); oos.flush(); oos.write(content.getBytes()); oos.flush(); }catch (Exception ex){ ex.printStackTrace(); } } } public String gen500(byte[] fileContent){ String result=null; result="HTTP/1.1 500 Internal Server Error\r\nAccept-Ranges: bytes\r\nContent-Type: text/html;charset=UTF-8\r\nContent-Length: 0\r\n\r\n"; return result; } }
Python
UTF-8
1,923
2.53125
3
[]
no_license
__author__ = 'reiner' import matplotlib.pyplot as plt import numpy as np import sequence_generation as sg import ex3delitel as ex3 def mntkrleq(): #в предположении,что имеет смысл держать центр эллипса совмещённым с центром прямоугольника global funcstrdict global spreadvarslist, V ksu2=0.955 ksu3=0.888 diap=0.001 leftksu2=ksu2-diap rightksu2=ksu2+diap leftksu3=ksu3-diap rightksu3=ksu3+diap bestpercent=0 vectr=[] for r2 in range(1,500, 1): r3=ksu3*r2/(ksu2-ksu3) r1=r2/(ksu2-ksu3)-r2-r3 xvectorlistsdict = {"u1":[100], "r1":[r1], "r2":[r2], "r3":[r3]} xvectorlistsdictc = {"u1":100, "r1":r1, "r2":r2, "r3":r3} #для проверки centerksu2=eval(funcstrdict["u2"], xvectorlistsdictc) centerksu3=eval(funcstrdict["u3"], xvectorlistsdictc) print (r1, r2, r3) resdict=sg.generate (funcstrdict, xvectorlistsdict, spreadvarslist, V, 1000, nvoly=1) mkprc=ex3.makepercent(leftksu2, rightksu2, leftksu3, rightksu3, resdict, draw=0) print ("Percent of good products: ", mkprc[0]) if max(bestpercent, mkprc[0])!=bestpercent: bestpercent=max (bestpercent, mkprc[0]) vectr=r1,r2,r3 print (bestpercent, "\n", vectr) #отображаем лучший вариант xvectorlistsdict = {"u1":[100], "r1":[r1], "r2":[r2], "r3":[r3]} resdict=sg.generate (funcstrdict, xvectorlistsdict, spreadvarslist, V, 10000, nvoly=1) mkprc=ex3.makepercent(leftksu2, rightksu2, leftksu3, rightksu3, resdict, draw=1) #test area: funcstrdict= {"u2":"u1* (r2+r3)/(r1+r2+r3)", "u3":"u1* r3/(r1+r2+r3)"} spreadvarslist = ["r1", "r2", "r3"] V=np.array ( [[4, 2, 3], [2, 9, 6], [3, 6, 16]]) mntkrleq()
C++
UTF-8
919
2.671875
3
[]
no_license
#include "serialport.h" #include <QIODevice> SerialPort::SerialPort(QObject *parent) : BaseParent(parent) { serial = new QSerialPort(this); connect(serial,&QSerialPort::readyRead,this,&SerialPort::handleReadyRead); } bool SerialPort::Open(Para *para) { if(serial->isOpen()) serial->close(); serial->setPortName(QString("COM%1").arg(para->com)); if(!serial->open(QIODevice::ReadWrite)) return false; serial->setBaudRate(para->baud); serial->setParity(para->parity); serial->setDataBits(QSerialPort::Data8); serial->setStopBits(QSerialPort::OneStop); return true; } void SerialPort::Close() { serial->close(); } void SerialPort::handleReadyRead() { emit sig_recv_data(serial->readAll()); } void SerialPort::slot_send_data(QByteArray hex) { if(serial->isOpen() && serial->isWritable()) { serial->write(hex); serial->flush(); } }
C++
UTF-8
3,957
3.609375
4
[ "Apache-2.0" ]
permissive
#include<iostream> #include<string> #include<cctype> using namespace std; int Length(const string& str) { int i =0; for(i; str[i] != '\0'; i++) {} return i; } void ToggleCaser(string& str) { for(int i = 0; i < str.length(); i++) { if(str[i] >= 65 && str[i] <= 90) { str[i] = str[i] + 32; } else if(str[i] >= 97 && str[i] <= 122) { str[i] = str[i] - 32; } } } void CountVowelsAndConsonants(string& str1) { int vowels=0; int consonants=0; for(int i=0; i < str1.length(); i++) { if(str1[i] == 'A' || str1[i] == 'a' || str1[i] == 'E' || str1[i] == 'e' || str1[i] == 'I' || str1[i] == 'i' || str1[i] == 'O' || str1[i] == 'o' || str1[i] == 'U' || str1[i] == 'u') { vowels++; } else consonants++; } cout << "Number of Vowels: " << vowels << endl; cout << "Number of Consonants: " << consonants << endl; } void WordCalculator(string& str) { //no of words = space + 1; Space's ASCII code = 13 int space=0; for(int i = 0; i < str.length(); i++) { if(str[i] == ' ' && str[i-1] != ' ') { space++; } } cout << "Number of words are: " << space+1 << endl; } void isPalindrome(string& str) { int i = 0; int j = str.length()-1; for(i,j; i < j; i++, j--) { if(tolower(str[i]) != tolower(str[j])) { cout << "Not Palindrome" << endl; return; } } cout << "Palindrome" << endl; } void Reverse(string str) { int i =0; int j = str.length() - 1; for(i, j; i < j; i++, j--) { char temp = str[i]; str[i] = str[j]; str[j] = temp;; } cout << "String after Reversing: " << str << endl; } void Compareor(string& str1, string& str2) { int i = 0; int j = 0; for(i,j; i < str1.length() && j < str2.length(); i++, j++) { if(str1[i] != str2[i]) { break; } } if(str1[i] == '\0' && str2[j] == '\0') { cout << "Same Strings" << endl; } else if(str1[i] < str2[j]) { cout << "Second string is larger than first string" << endl; } else if(str1[i] > str2[j]) { cout << "First string is larger than the second string" << endl; } } /* - Both strings must be of same length - Both string must consists of same letters - Iterative Solution Presented Here - Do not expect duplicated in the string - Hash Table Solutions Can Work on strings containing duplicates */ void AreAnagrams_Bitset(string& str1, string& str2) { } void AreAnagrams_Hash(string& str1, string& str2) { if(str1.length() != str2.length()) { cout << "Strings are not Anagrams" << endl; return; } int Hash[27]{0}; //initialized with zero //traverse over str1 for(int i=0; str1[i] != '\0'; i++) { Hash[str1[i] - 97]++; } for(int j=0; str2[j] != '\0'; j++) { Hash[str2[j] - 97]--; if(Hash[str2[j] - 97] < 0) { cout << "Strings are not Anagrams." << endl; return; } } cout << "Strings are Anagrams." << endl; } void Duplicates_Hash(string& str) { int Hash[27]{0}; for(int i=0; i < str.length(); i++) { Hash[str[i] - 97]++; } for(int i = 1; i < 27; i++) { if(Hash[i] > 1) { cout << char(i+97) << " is repeating " << Hash[i] << " times." << endl; } } } int main() { string str1{"FaceBook Interview IS on jAN 7th 2020."}; cout << "Length of " << Length(str1) << endl; ToggleCaser(str1); cout << str1 << endl; CountVowelsAndConsonants(str1); WordCalculator(str1); Reverse(str1); Reverse(str1); string str2 = "Ranveer"; isPalindrome(str2); Compareor(str1, str2); string str3 = "delcimal"; string str4 = "medicall"; AreAnagrams_Hash(str3, str4); string str5 = "ranveer"; Duplicates_Hash(str5); return 0; }
Rust
UTF-8
2,027
3.0625
3
[]
no_license
use super::ray::Ray; use super::vec::Vec3; extern crate rand; use rand::Rng; pub fn drand48() -> f32 { let random_float: f32 = rand::thread_rng().gen(); random_float } pub struct Camera { origin: Vec3, lower_left_corner: Vec3, vertical: Vec3, horizontal: Vec3, u: Vec3, v: Vec3, w: Vec3, lens_radius: f32, } impl Camera { pub fn new( look_from: Vec3, look_at: Vec3, vup: Vec3, vfov: f32, aspect: f32, aperture: f32, focus_dist: f32, ) -> Self { let lens_radius = aperture / 2.0; let theta = vfov * std::f32::consts::PI / 180.0; let half_height = f32::tan(theta / 2.0); let half_width = aspect * half_height; let origin = look_from; let w = Vec3::make_unit_vector(look_from - look_at); let u = Vec3::make_unit_vector(Vec3::cross(vup, w)); let v = Vec3::cross(w, u); let mut lower_left_corner = Vec3::new(-half_width, -half_height, -1.0); lower_left_corner = origin - half_width * focus_dist * u - half_height * focus_dist * v - focus_dist * w; let horizontal = 2.0 * half_width * focus_dist * u; let vertical = 2.0 * half_height * focus_dist * v; Camera { origin, lower_left_corner, horizontal, vertical, u, v, w, lens_radius, } } pub fn get_ray(&self, u: f32, v: f32) -> Ray { let rd: Vec3 = self.lens_radius * random_in_unit_sphere(); let offset = self.u * rd.x() + self.v * rd.y(); Ray::new( self.origin + offset, self.lower_left_corner + u * self.horizontal + v * self.vertical - self.origin - offset, ) } } fn random_in_unit_sphere() -> Vec3 { let mut p: Vec3; while { p = 2.0 * Vec3::new(drand48(), drand48(), drand48()) - Vec3::new(1.0, 1.0, 1.0); p.squared_length() >= 1.0 } {} return p; }
Markdown
UTF-8
4,781
2.9375
3
[ "MIT" ]
permissive
# tko-subs This tool allows: * To check whether a subdomain can be taken over because it has: * a dangling CNAME pointing to a CMS provider (Heroku, Github, Shopify, Amazon S3, Amazon CloudFront, etc.) that can be taken over. * a dangling CNAME pointing to a non-existent domain name * one or more wrong/typoed NS records pointing to a nameserver that can be taken over by an attacker to gain control of the subdomain's DNS records * To specify your own CMS providers and check for them via the [providers-data.csv](providers-data.csv) file. In that file, you would mention the CMS name, their CNAME value, their string that you want to look for and whether it only works over HTTP or not. Check it out for some examples. ### Disclaimer: DONT BE A JERK! Needless to mention, please use this tool very very carefully. The authors won't be responsible for any consequences. ### Pre-requisites We need GO installed. Once you have GO, just type `go get github.com/anshumanbh/tko-subs` to download the tool. Once the tool is downloaded, type `tko-subs -h`. ### How to run? Once you have everything installed, `cd` into the directory and type: `tko-subs -domains=domains.txt -data=providers-data.csv -output=output.csv` If you just want to check for a single domain, type: `tko-subs -domain <domain-name>` If you just want to check for multiple domains, type: `tko-subs -domain <domain-name-1>,<domain-name-2>` By default: * the `domains` flag is set to `domains.txt` * the `data` flag is set to `providers-data.csv` * the `output` flag is set to `output.csv` * the `domain` flag is NOT set so it will always check for all the domains mentioned in the `domains.txt` file. If the `domain` flag is mentioned, it will only check that domain and ignore the `domains.txt` file, even if present * the `threads` flag is set to `5` So, simply running `tko-subs` would run with the default values mentioned above. ### How is providers-data.csv formatted? name,cname,string,http * name: The name of the provider (e.g. github) * cname: The CNAME used to map a website to the provider's content (e.g. github.io) * string: The error message returned for an unclaimed subdomain (e.g. "There isn't a GitHub Pages site here") * http: Whether to use http (not https, which is the default) to connect to the site (true/false) ### How is the output formatted? Domain,CNAME,Provider,IsVulnerable,Response * Domain: The domain checked * CNAME: The CNAME of the domain * Provider: The provider the domain was found to be using * IsVulnerable: Whether the domain was found to be vulnerable or not (true/false) * Response: The message that the subdomain was checked against If a dead DNS record is found, `Provider` is left empty. If a misbehaving nameserver is found, `Provider` and `CNAME` are left empty ### What is going on under the hood? This will iterate over all the domains (concurrently using GoRoutines) in the `subdomains.txt` file and: * See if they have a misbehaving authoritative nameserver; if they do, we mark that domain as vulnerable. * See if they have dangling CNAME records aka dead DNS records; if they do we mark that domain as vulnerable. * If a subdomain passes these two tests, it tries to curl them and get back a response and then try to see if that response matches any of the data provider strings mentioned in the [providers-data.csv](providers-data.csv) file. * If the response matches, we mark that domain as vulnerable. * And, that's it! ### Future Work * ~Take CMS name and regex from user or .env file and then automatically hook them into the tool to be able to find it.~ DONE * Add more CMS providers ### Credits * Thanks to Luke Young (@TheBoredEng) for helping me out with the go-github library. * Thanks to Frans Rosen (@fransrosen) for helping me understand the technical details that are required for some of the takeovers. * Thanks to Mohammed Diaa (@mhmdiaa) for taking time to implement the provider data functionality and getting the code going. * Thanks to high-stakes for a much needed code refresh. ### Changelog `8/4/18` * Added more services * Added CNAME recursion * Removed takeover functionality `5/27` * Added new Dockerfile reducing the size of the image * Added sample domains.txt file to test against * mhmdiaa added the logic for dead DNS takeovers. Updated documentation. Thanks a lot! `11/6` * high-stakes issues a PR with a bunch of new code that fixes a few bugs and makes the code cleaner `9/22` * Added an optional flag to check for single domain * Made it easier to install and run `6/25` * Made the code much more faster by implementing goroutines * Instead of checking using Golang's net packages' LookupCNAME function, made it to just use dig since that gives you dead DNS records as well. More attack surface!!
C++
UTF-8
669
3.546875
4
[]
no_license
#include <iostream> #include <math.h> using namespace std; //71. Починаючи з деякого моменту часу пройшло k повних секунд. Визначити, скільки пройшло повних діб, годин, хвилин та секунд.. int main() { int ksec; cout << "Enter count of seconds: "; cin >> ksec; int sut = ksec / 86400; int chas = (ksec % 86400) / 3600; int min = ((ksec % 86400) % 3600) / 60; int sec = ((ksec % 86400) % 3600) % 60; cout << "Time: " << sut << " дней:" << chas << " часов: " << min << " минут: " << sec << " секунд" << endl; }
Markdown
UTF-8
1,106
2.59375
3
[]
no_license
# README ## Thriftie ## Thriftie is a Ruby on Rails application, the goal of which is to enable users the ability to set and track financial goals. By its completion Thriftie should be able to account for deposits and withdrawals, and report various details about a user's financial plan (percentage complete, time to completion, average deposits, average withdrawals, and the like). **This README** This README is a living, breathing, digital document. Because this app is in development, this document can and will, change frequently as new functionality is added or removed. *****Gems****** Bootstrap-Sass (For styling) Devise (For User Authentication) More to be added ****Features**** ****Goals**** [X] Goals will have a financial endpoint [X] Goals will have a controller [X] Goals will be able to be viewed [X] Goals can be edited More Features will be added here when they are added. As always, thank you for reading. Any issues with Thriftie can be submitted via github as either "issues" or a "pull request". All forms of criticism welcomed and appreciated. ~~Apex-Code
Python
UTF-8
8,026
3.046875
3
[]
no_license
import struct import sys from functions import call_function SHOW_MESSAGES = False def debug(msg): if SHOW_MESSAGES: print msg class VirtualMachine: def __init__(self, input_file): with open(input_file, 'rb') as file: self.memory = file.read() self.cached_memory = {} self.reg = { 'addr': 0, 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0 } self.stack = [] def load_state(self, save_name='save'): with open(save_name + '/register', 'r') as file: inputs = file.read().rstrip().split('\n') for input in inputs: args = input.split() if args[0] == 'addr': self.reg['addr'] = int(args[1]) - 1 else: self.reg[int(args[0])] = int(args[1]) with open(save_name + '/stack', 'r') as file: inputs = file.read().rstrip().split('\n') for input in inputs: self.stack.append(int(input)) with open(save_name + '/memory', 'r') as file: inputs = file.read().rstrip().split('\n') for input in inputs: args = input.split() self.cached_memory[int(args[0])] = int(args[1]) def save_state(self): with open('register', 'w') as file: for key, value in self.reg.iteritems(): file.write("{} {}\n".format(key, value)) with open('stack', 'w') as file: for i in self.stack: file.write('{}\n'.format(i)) with open('memory', 'w') as file: for k, v in self.cached_memory.iteritems(): file.write('{} {}\n'.format(k, v)) def _read_next(self): val = self.read_address(self.reg['addr']) self.reg['addr'] += 1 return val def _parse_address(self): value = self._read_next() if value >= 32768 and value <= 32775: return value - 32768 else: raise Exception('Invalid address') def _parse_value(self): value = self._read_next() if value >= 0 and value <= 32767: return value if value >= 32768 and value <= 32775: debug("reading from register {} = {}".format( value - 32768, self.reg[value - 32768])) return self.reg[value - 32768] else: raise Exception('Invalid value') def read_address(self, address): if self.cached_memory.get(address) is None: return struct.unpack( '<H', self.memory[2*address:2*address+2])[0] return self.cached_memory[address] def run_next_instruction(self): addr = self.reg['addr'] inst = self._read_next() command = '' if inst == 0: command = 'stop' elif inst == 1: arg1 = self._parse_address() arg2 = self._parse_value() command = 'set R{} {}'.format(arg1, arg2) self.reg[arg1] = arg2 elif inst == 2: arg = self._parse_value() self.stack.append(arg) command = 'push {}'.format(arg) elif inst == 3: arg = self._parse_address() self.reg[arg] = self.stack.pop() command = 'pop R{} ({})'.format(arg, self.reg[arg]) elif inst == 4: arg1 = self._parse_address() arg2 = self._parse_value() arg3 = self._parse_value() if arg2 == arg3: self.reg[arg1] = 1 else: self.reg[arg1] = 0 command = 'eq R{} {} {}'.format(arg1, arg2, arg3) elif inst == 5: arg1 = self._parse_address() arg2 = self._parse_value() arg3 = self._parse_value() if arg2 > arg3: self.reg[arg1] = 1 else: self.reg[arg1] = 0 command = 'gt R{} {} {}'.format(arg1, arg2, arg3) elif inst == 6: arg = self._parse_value() self.reg['addr'] = arg command = 'jmp {}'.format(arg) elif inst == 7: arg1 = self._parse_value() arg2 = self._parse_value() if arg1 != 0: self.reg['addr'] = arg2 command = 'jt {} {}'.format(arg1, arg2) elif inst == 8: arg1 = self._parse_value() arg2 = self._parse_value() if arg1 == 0: self.reg['addr'] = arg2 command = 'jf {} {}'.format(arg1, arg2) elif inst == 9: arg1 = self._parse_address() arg2 = self._parse_value() arg3 = self._parse_value() self.reg[arg1] = (arg2 + arg3) % 32768 command = 'add R{} {} {}'.format(arg1, arg2, arg3) elif inst == 10: arg1 = self._parse_address() arg2 = self._parse_value() arg3 = self._parse_value() self.reg[arg1] = (arg2 * arg3) % 32768 command = 'mult R{} {} {}'.format(arg1, arg2, arg3) elif inst == 11: arg1 = self._parse_address() arg2 = self._parse_value() arg3 = self._parse_value() self.reg[arg1] = (arg2 % arg3) command = 'mod R{} {} {}'.format(arg1, arg2, arg3) elif inst == 12: arg1 = self._parse_address() arg2 = self._parse_value() arg3 = self._parse_value() self.reg[arg1] = arg2 & arg3 command = 'and R{} {} {}'.format(arg1, arg2, arg3) elif inst == 13: arg1 = self._parse_address() arg2 = self._parse_value() arg3 = self._parse_value() self.reg[arg1] = arg2 | arg3 command = 'or R{} {} {}'.format(arg1, arg2, arg3) elif inst == 14: arg1 = self._parse_address() arg2 = self._parse_value() self.reg[arg1] = 32768 + ~arg2 command = 'not R{} {}'.format(arg1, arg2) elif inst == 15: arg1 = self._parse_address() arg2 = self._parse_value() self.reg[arg1] = self.read_address(arg2) command = 'rmem R{} {}'.format(arg1, arg2) elif inst == 16: arg1 = self._parse_value() arg2 = self._parse_value() self.cached_memory[arg1] = arg2 command = 'wmem {} {}'.format(arg1, arg2) elif inst == 17: arg = self._parse_value() command = call_function(arg, self.reg, self) if command == False: self.stack.append(self.reg['addr']) self.reg['addr'] = arg command = 'call {}'.format(arg) elif inst == 18: if len(self.stack) > 0: self.reg['addr'] = self.stack.pop() command = 'ret ({})'.format(self.reg['addr']) else: command = 'stop' elif inst == 19: arg = self._parse_value() sys.stdout.write(chr(arg)) command = 'out {}'.format(arg) elif inst == 20: # write_register() arg = self._parse_address() self.reg[arg] = ord(sys.stdin.read(1)) command = 'in {} ({})'.format(arg, self.reg[arg]) elif inst == 21: command = 'noop' else: print 'invalid instruction {}'.format(inst) command = 'stop' return '- {}: {}'.format(addr, command) if __name__ == '__main__': machine = VirtualMachine('input/challenge.bin') machine.load_state('teleporter') while True: # Override the teleporter confirmation if machine.reg['addr'] == 5489: machine.reg['addr'] = 5498 # machine.reg['addr'] = 5579 output = machine.run_next_instruction() debug(output) if output == 'stop': break
Java
UTF-8
1,988
3.328125
3
[]
no_license
package question113; import java.util.ArrayList; import java.util.List; /** * Created by duncan on 17-11-21. */ class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } //判断路径上数之和,输出路径 public class Solution { public void pathSum(TreeNode root, int sum, List<List<Integer>> res,List<Integer> cur){ // path.push(root.val); // if(root.left == null && root.right == null) // if(sum == root.val) resultList.add(new ArrayList<Integer>(path)); // if(root.left!=null) pathSumInner(root.left, sum-root.val, path); // if(root.right!=null)pathSumInner(root.right, sum-root.val, path); // path.pop(); if(root == null) return; cur.add(root.val); if(root.left == null && root.right == null && root.val == sum){ res.add(new ArrayList(cur)); cur.remove(cur.size()-1); return; }else { pathSum(root.left, sum - root.val, res, cur); pathSum(root.right, sum - root.val, res, cur); } cur.remove(cur.size() - 1); } public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> res = new ArrayList<>(); List<Integer> cur = new ArrayList<>(); pathSum(root,sum,res,cur); return res; } public static void main(String[] args) { TreeNode root = new TreeNode(5); TreeNode node1 = new TreeNode(8); TreeNode node2 = new TreeNode(7); TreeNode node3 = new TreeNode(7); TreeNode node4 = new TreeNode(7); TreeNode node5 = new TreeNode(5); TreeNode node6 = new TreeNode(6); root.left = node1; root.right = node2; node1.left = node6; node1.right = node5; node2.left = node3; node2.right = node4; Solution method = new Solution(); System.out.println(method.pathSum(root,19)); } }
Markdown
UTF-8
5,674
2.78125
3
[]
no_license
# Notes from conversation with Paul more leaves fold better what features might be breaking levinthal's? the landscape must be funneled in order for these to fold how can we make these landscapes funnel better paul actually went to wales' group to make disconnectivity graphs wales code is really unwieldy-- would take much more time to make code efficient than it would be worth had some preliminary trees,but ultimately bailed because it was too complex disconnectivity should be its own paper with Wales, Morgan Sharon doesn't like Wales, he's kind of weird, Wales is really hands on, even with code development (Paul likes him) leaves were once called nucleation sites for folding in an earlier draft of Paul's paper Leaves are edges that are next to each other (local) that need to form-- so lots of leaves means a net seeded with lots of local, native bonds did some simulations seeding the net (icosahedra, which never folded on their own) one connection still wasn't enough, needed more interesting question-- how much do you need to add? specificity efficiency would be interesting critical bonds are related to the isostatic structure of the net-- fewest number of bonds that i need to make it rigid with triangle faces, look at the all the matches of the edges-- for it to be minimal and rigid you have to glue enough edges together so that no vertex has been glued twice, but sufficient that each vertex has been glued once cube and dodecahedra are trickier-- some cuts don't introduce degrees of freedom cutting trees / gluing trees -- probably a greedy algorithm that will do this faster than brute force understanding the rigidity of the structure is the key question what are the minimal bonds needed to make a structure rigid? some of the cubes have like, one bond that you can make and it will fold completely Information: Paul tried having an interaction matrix between all edges of a net edges aren't independent... so run into trouble maybe you can play a game of adding one bond at a time? binary symmetric channels (0 is folded, 1 is unfolded or something) could be a simplistic model of like, a protein signalling long-term view of molecular information and robotics enumeration algorithm already exists based on the two heuristics calculate the different paths you could take that kind of works this is how that last graph was calculated taking that-- could you like, seed with the first two folds for an icosahedra disconnectivity pluripotent materials -- no one really has a good way of doing this on a colloidal level how do we go from one sheet to another magnetic particles for reconfiguration might have been used diabolos, paul's presentation from august 8-15 # Notes from meeting with Sharon - High information pathway points - flesh out the nets, do totally systematically - Disconnectivity graph from john - Folding, with shapes Questions: - What does it mean for material to have information? - Can we determine if some starting points (structures, arrangements, etc) have more information than others - Can analyze with disconnectivity graph - Machine learning to high-likelihood initial configurations - Application: build "best" starting point for various end configurations # Brainstorming for prelim meeting with Sharon Three parts of venn diagram from before. Theme: Synthetic Intelligence/designed intelligence 1) Information: entropy, storage, retrieval 2) Biomimicry: pluripotency, complex signaling capabilities, CRISPR-like error correction 3) Non-equilibrium systems: agent-based models (minimal models), collection motion Information storage, retrieval, and action - Reconfigurability - How do we embed information in a material? - How can we embed reconfigurability in a material? - What information is already embedded in a material building block's properties? Shape memory materials have a dual-domain system, in which one is always elastic (the elastic domain), while the other (the transition domain) is able to change its stiffness remarkably if a right stimulus is presented. "The material is the machine": super cool, [here](http://science.sciencemag.org/content/307/5706/53/tab-pdf) This review addresses recent developments in actively moving materials based on stimuli-responsive polymers on the scale from single molecules to polymer networks. The examples of application of stimuli-responsive polymers for design of actuators, sensors, active elements in microfluidic devices, materials with switchable optical properties as well as biomaterials are discussed. [link](http://pubs.rsc.org/en/content/articlelanding/2010/jm/b922718k#!divAbstract) ### Older notes Sharon’s suggestion: reconfigurability   What world do I envision? Colloidal robotics:             Encode information in wet computing Leverage self-assembly trends to enable particles to run on their own accord—imagine that we could build engineer particles, not just materials, backwards—say that we want this behavior, what shape do we need to do this?   Previous work to build off of Lock and key binding (paper showing different kinetic pathways) Allophilic shaping—used to improve the self-assembly of desired phases without the use of functionalization external fields, or other types of intrinsic inter-particle interactions Digital colloids, wet computing The components of entropy generation in non-equilibrium systems is a fundamental hard problem Thoughts: - Block copolymers phase separate so that similar sides of the strand are in a band-- what would happen with anisotropic shapes where each side would typically have a very different behavior?
PHP
UTF-8
1,934
2.640625
3
[ "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-other-copyleft", "GPL-2.0-or-later", "LicenseRef-scancode-unknown-license-reference", "GPL-2.0-only", "Apache-2.0", "MIT" ]
permissive
<?php /** * @file * OG example selection handler. */ class OgExampleSelectionHandler extends OgSelectionHandler { /** * Overrides OgSelectionHandler::getInstance(). */ public static function getInstance($field, $instance = NULL, $entity_type = NULL, $entity = NULL) { return new OgExampleSelectionHandler($field, $instance, $entity_type, $entity); } /** * Overrides OgSelectionHandler::buildEntityFieldQuery(). * * This is an example of "subgroups" (but without getting into the logic of * sub-grouping). * The idea here is to show we can set "My groups" and "Other groups" to * reference different groups by different * logic. In this example, all group nodes below node ID 5, will appear under * "My groups", and the rest will appear under "Other groups", * for administrators. */ public function buildEntityFieldQuery($match = NULL, $match_operator = 'CONTAINS') { $group_type = $this->field['settings']['target_type']; if (empty($this->instance['field_mode']) || $group_type != 'node') { return parent::buildEntityFieldQuery($match, $match_operator); } $field_mode = $this->instance['field_mode']; $handler = EntityReference_SelectionHandler_Generic::getInstance($this->field, $this->instance, $this->entity_type, $this->entity); $query = $handler->buildEntityFieldQuery($match, $match_operator); // Show only the entities that are active groups. $query->fieldCondition(OG_GROUP_FIELD, 'value', 1, '='); if ($field_mode == 'default') { $query->propertyCondition('nid', '5', '<='); } else { $query->propertyCondition('nid', '5', '>'); } // FIXME: http://drupal.org/node/1325628 unset($query->tags['node_access']); // FIXME: drupal.org/node/1413108 unset($query->tags['entityreference']); $query->addTag('entity_field_access'); $query->addTag('og'); return $query; } }
Markdown
UTF-8
1,108
3.109375
3
[]
no_license
# PEC 2 ## Ejercicio 2 ### a. Observad que se han creado funciones handle en el fichero controlador (todo.controller.js), las cuales son pasadas como parámetro. Esto es debido al problema con el cambio de contexto (this) que existe en JavaScript. Ahora mismo si no tienes muy claro que está sucediendo, revisa qué hacen las “fat-arrow” de ES6 sobre el objeto this, y prueba a cambiar el código para comprender qué está sucediendo cuando se modifica la siguiente línea: this.view.bindAddTodo(this.handleAddTodo); Por esta: `code` this.view.bindAddTodo(this.service.addTodo); Responded, en un documento texto en el directorio de entrega a la siguiente pregunta: **¿Por qué es el valor de this es undefined?** En javascript, se pierde muy rapidaemnte el contexto de `this`. Esto va a depender mucho del ambito en que se ejecuta la función. Es decir, si queremos utilizar la función en otra clase o metodo, deberemos utilizar el operador "fat arrow" para poder realizar la llamada a la función de otra clase ya que el operador "captura" el this y lo hace apuntar a donde debe.
C#
UTF-8
582
3.453125
3
[]
no_license
using System; namespace lab9 { class Program { static void Main(string[] args) { string letters; Console.WriteLine("Enter letters"); letters = Console.ReadLine(); ReconstructingArray(letters); } static string ReconstructingArray(string letters) { string letters2 ; for (int i = 0; i < letters.Length; i++) { letters2[i] = letters[i]; } return letters2; } } }
C
UTF-8
1,224
3.1875
3
[]
no_license
/* * datagramUnixClient.c */ // This program connects to a datagram UNIX domain socket #include <sys/socket.h> #include <stdio.h> #include <stdlib.h> #include <sys/un.h> #include <string.h> #include <unistd.h> int main(int argc, char *argv[]) { char *socketPath = "named"; // create the socket int sockFd = socket(AF_UNIX, SOCK_DGRAM, 0); if (sockFd < 0) { perror("socket"); exit(1); } // set up the destination socket struct sockaddr_un addr; memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; strcpy(addr.sun_path, socketPath); struct sockaddr *ptr = (struct sockaddr *) &addr; int len = sizeof(addr); int bytesRead = 10; char buf[100]; int retVal; while (bytesRead > 0) { // read in from stdin and send bytesRead = read(0, buf, 100); if (bytesRead < 0) { perror("read"); exit(1); } retVal = sendto(sockFd, buf, bytesRead, 0, ptr, len); if (retVal < 0) { perror("sendto"); exit(1); } } int ret = close(sockFd); if (ret < 0) { perror("close"); exit(1); } }
Markdown
UTF-8
2,316
2.59375
3
[]
no_license
## Structure In this folder we keep multiple different models that we use for prototyping and classification. All models inherit from a base model that provides the interface for training, evaluation and prediction. ``` . ├── checkpoints/ # artifactories from training ├── base_model.py # base model that provides interface for all models ├── bigru_model_pytorch.py # model with BiGRU layers and Glove/BERT embeddings ├── bilstm_model_pytorch.py # model with BiLSTM layers and Glove/BERT embeddings ├── cil_pretrainingwithBERT # prototyping model with BERT and dense layers ├── custom_callback.py # callback that intercepts epochs and logs status ├── rnn_model.py # model with BILSTM and glove in rnn setting ├── san_model_pytorch.py # model with BILSTM and self attention Glove/BERT ├── saved_model.py # wrapper model for loading saved models ├── sep_cnn_model.py # model with Separable convolutions and glove └── README.md ``` ## Framework For the models we used mainly [TensorFlow](https://www.tensorflow.org/api_docs/python/tf?version=nightly) and [PyTorch](https://pytorch.org/docs/stable/index.html). For the embedding we used [Glove](https://nlp.stanford.edu/projects/glove/) and [BERT](https://github.com/google-research/bert) as language models. ## Interface All models implement the same base class and therefore can be used in a consistent way in the run scripts. The following base class with required functions is provided: ``` class BaseModel(ABC): @abstractmethod def build(self): pass @abstractmethod def fit(self, input): pass @abstractmethod def predict(self, input): pass ``` - `build()`: Build the model depending on provided parameters - `fit()`: Train the model depending on runtime parameters - `predict()`: Predict labels on input ## Models The following models were implemented: - [SepCNN](https://arxiv.org/abs/1610.02357) - [BiLSTM with self attention](https://www.aclweb.org/anthology/P16-2034.pdf) - [GRU with self attention](https://arxiv.org/pdf/2002.00735.pdf) - [BiLSTM](https://colah.github.io/posts/2015-08-Understanding-LSTMs/)
Python
UTF-8
356
3.109375
3
[]
no_license
from PIL import Image import numba left = int(input('pixels from left: ')) upper = int(input('pixels from upper: ')) right = int(input('pixels from right: ')) lower = int(input('pixels from down: ')) img_path = str(input('input path to the image: ')) open_img = Image.open(img_path) crop_image = open_img.crop((left,upper,right,lower)) crop_image.show()
Python
UTF-8
526
3.171875
3
[]
no_license
import main def test_add(): assert main.add(3, 4) == 7 assert main.add(3.5, 4) == 7 assert main.add(3.9, 4) == 7 assert main.add(3.9, 4.1) == 8 # def test_to_sentence(): # assert main.to_sentence('apple') == 'Apple.' # assert main.to_sentence('Apple trees') == 'Apple trees.' # assert main.to_sentence('Apple trees.') == 'Apple trees.' # def test_sub(): assert main.sub(3, 4) == -1 # assert main.sub(3.5, 4) == -1 # assert main.sub(3.9, 4) == -1 # assert main.sub(3.1, 3) == 0
Python
UTF-8
3,485
3.015625
3
[]
no_license
import numpy as np rng = np.random def clean_data(X, Y, flag=0): # convert party names into one-hot vectors one_hot_party = np.zeros((X.shape[0], 5)) for idx, party in enumerate(X[:, 0]): if party == 'Centaur': one_hot_party[idx, :] = [1, 0, 0, 0, 0] elif party == 'Odyssey': one_hot_party[idx, :] = [0, 1, 0, 0, 0] elif party == 'Cosmos': one_hot_party[idx, :] = [0, 0, 1, 0, 0] elif party == 'Tokugawa': one_hot_party[idx, :] = [0, 0, 0, 1, 0] elif party == 'Ebony': one_hot_party[idx, :] = [0, 0, 0, 0, 1] else: print 'No such party exists' # combine the first 25 features and make 5 features from them new_feature1 = [] new_feature2 = [] new_feature3 = [] new_feature4 = [] new_feature5 = [] for idx, var in enumerate(X[:, 1]): new_val = X[idx, 1] + X[idx, 6] + X[idx, 11] + X[idx, 16] + X[idx, 21] new_feature1.append(new_val) new_val = X[idx, 2] + X[idx, 7] + X[idx, 12] + X[idx, 17] + X[idx, 22] new_feature2.append(new_val) new_val = X[idx, 3] + X[idx, 8] + X[idx, 13] + X[idx, 18] + X[idx, 23] new_feature3.append(new_val) new_val = X[idx, 4] + X[idx, 9] + X[idx, 14] + X[idx, 19] + X[idx, 24] new_feature4.append(new_val) new_val = X[idx, 5] + X[idx, 10] + X[idx, 15] + X[idx, 20] + X[idx, 25] new_feature5.append(new_val) new_feature1 = np.reshape(np.array(new_feature1), (X.shape[0], 1)) new_feature2 = np.reshape(np.array(new_feature2), (X.shape[0], 1)) new_feature3 = np.reshape(np.array(new_feature3), (X.shape[0], 1)) new_feature4 = np.reshape(np.array(new_feature4), (X.shape[0], 1)) new_feature5 = np.reshape(np.array(new_feature5), (X.shape[0], 1)) # take the mean age for idx, age in enumerate(X[:, 27]): if len(list(X[idx, 27])) == 5: a1, a2, a3, a4, a5 = list(X[idx, 27]) mean_age = (int(a1)*10+int(a2) + int(a4)*10+int(a5))/2.0 elif len(list(X[idx, 27])) == 3: a1, a2, a3 = list(X[idx, 27]) mean_age = (int(a1)*10+int(a2) + 70.0)/2.0 else: mean_age = 25 print 'No such format exists' X[idx, 27] = mean_age # convert the degree into numeric value for idx, degree in enumerate(X[:, 30]): # print idx, degree if degree == 'Primary': X[idx, 30] = 1 elif degree == 'Diploma': X[idx, 30] = 2 elif degree == 'Degree': X[idx, 30] = 3 elif degree == 'Masters': X[idx, 30] = 4 # delete unnecesary features X = X[:, :-2] for idx in range(1, 26): X = np.delete(X, 1, axis=1) X = np.delete(X, 0, axis=1) # add the new features X = np.append(X, new_feature1, axis=1) X = np.append(X, new_feature2, axis=1) X = np.append(X, new_feature3, axis=1) X = np.append(X, new_feature4, axis=1) X = np.append(X, new_feature5, axis=1) X = np.append(X, one_hot_party, axis=1) # normalize the features for col in xrange(X.shape[1]): if not (col == 2 or col == 3 or col == 4): _max = X[:, col].max() _min = X[:, col].min() _mean = X[:, col].mean() X[:, col] = (X[:, col] - _mean)/(_max-_min) # convert Ys into one hot vectors if flag == 1: replace = np.zeros((Y.shape[0], 5)) for idx, row in enumerate(Y[:]): if row == 'Centaur': replace[idx, :] = [1, 0, 0, 0, 0] elif row == 'Odyssey': replace[idx, :] = [0, 1, 0, 0, 0] elif row == 'Cosmos': replace[idx, :] = [0, 0, 1, 0, 0] elif row == 'Tokugawa': replace[idx, :] = [0, 0, 0, 1, 0] elif row == 'Ebony': replace[idx, :] = [0, 0, 0, 0, 1] else: print 'No such party! at %dth row' % (idx,) Y = replace return X, Y else: return X
JavaScript
UTF-8
1,410
2.921875
3
[]
no_license
const Engine = Matter.Engine; const World = Matter.World; const Bodies = Matter.Bodies; const Body = Matter.Body; const Constraint= Matter.Constraint; var bobObject1, bobObject2, bobObject3, bobObject4, bobObject5; var roof1; var rope1, rope2, rope3, rope4, rope5; function preload() { } function setup() { createCanvas(800, 700); engine = Engine.create(); world = engine.world; //Create the Bodies Here. bobObject1= new Bob(300,350,50); bobObject2= new Bob(350,350,50); bobObject3= new Bob(400,350,50); bobObject4= new Bob(450,350,50); bobObject5= new Bob(500,350,50); roof1= new Roof(400,200,300,20); rope1= new Rope(bobObject1.body, roof1.body, -50*2,0); rope2= new Rope(bobObject2.body, roof1.body, -25*2,0); rope3= new Rope(bobObject3.body, roof1.body, -0*2,0); rope4= new Rope(bobObject4.body, roof1.body, 25*2,0); rope5= new Rope(bobObject5.body, roof1.body, 50*2,0); Engine.run(engine); } function draw() { rectMode(CENTER); background(230); bobObject1.display(); bobObject2.display(); bobObject3.display(); bobObject4.display(); bobObject5.display(); roof1.display(); rope1.display(); rope2.display(); rope3.display(); rope4.display(); rope5.display(); drawSprites(); } function keyPressed() { if (keyCode === UP_ARROW) { Matter.Body.applyForce(bobObject1.body, bobObject1.body.position,{x:-100, y:-100}); } }
C#
UTF-8
2,673
3.078125
3
[]
no_license
using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.InteropServices; using Xunit; namespace TDDKatas { public class WebshopTests { //[Theory] //[InlineData("Laptop", 5.33, "Laptop 5,33")] //[InlineData("Book", 100.55, "Book 100,55")] //public void TestCreateSimpleProduct(string name, decimal price, string expected) //{ // var product = new Product(name, price); // Assert.Equal(expected, product.ToString()); //} //[Theory] //[InlineData("Book", 100.55, 2, "2x Book 201,10")] //[InlineData("Laptop", 20.40, 10, "10x Laptop 204,0")] //public void TestCreateOrderItem(string productName, decimal price, int quantity, string expected) //{ // var product = new Product(productName, price); // var orderItem = new OrderItem(product, quantity); // Assert.Equal(expected, orderItem.ToString()); //} //[Fact] //public void TestCreateOrderItemNegativeQuantityThrowsException() //{ // var product = new Product("Tea", 123.22M); // Assert.Throws<ArgumentException>(() => new OrderItem(product, -1)); //} //[Fact] //public void TestCreateOrderItemZeroQuantityThrowsException() //{ // var product = new Product("Tea", 123.22M); // Assert.Throws<ArgumentException>(() => new OrderItem(product, 0)); //} //Currency formatting //Product equals //Order string presentation //Product with negative price? //Add Product to order //Remove product from order //Add same product twice adds together quantity } public class OrderItem { //public Product Product { get; } //public int Quantity { get; set; } //public decimal Subtotal => Product.Price * Quantity; //public OrderItem(Product product, int quantity) //{ // if (quantity <= 0) throw new ArgumentException(); // Product = product; // Quantity = quantity; //} //public override string ToString() //{ // return $"{Quantity}x {Product.Name} {Subtotal}"; //} } //public class Product //{ // public Product(string name, decimal price) // { // Name = name; // Price = price; // } // public string Name { get; } // public decimal Price { get; } // public override string ToString() // { // return $"{Name} {Price}"; // } //} }
C++
UTF-8
5,142
2.875
3
[]
no_license
#include "CommandManager.h" #include "PlayerManager.h" #include "GameManager.h" #include "IInteractable.h" #include "AnalyticsManager.h" #include <iostream> #include <sstream> #include <vector> #include <cctype> void CommandManager::initialize() { if (!mInitialzed) { mSingleCommands.emplace("HELP", &CommandManager::help); mSingleCommands.emplace("SAVE", &GameManager::saveGame); mSingleCommands.emplace("EXIT", &GameManager::endGame); mSingleCommands.emplace("INVENTORY", &GameManager::inventory); mSingleCommands.emplace("LOOK", &GameManager::look); mInteractableCommands.emplace("LOOK", &IInteractable::lookObject); mInteractableCommands.emplace("TELEPORT", &IInteractable::teleportRegion); mInteractableCommands.emplace("PICK", &IInteractable::pickObject); mInteractableCommands.emplace("GO", &IInteractable::goDirection); mInteractableCommands.emplace("BLOCK", &IInteractable::blockAttack); mInteractableCommands.emplace("WEAR", &IInteractable::wearObject); mInteractableCommands.emplace("PLAY", &IInteractable::playObject); mInteractableCommands.emplace("EAT", &IInteractable::eatObject); mInteractableCommands.emplace("MOVE", &IInteractable::moveObject); mInteractableCommands.emplace("ANSWER", &IInteractable::answerRiddle); mInteractableCommands.emplace("DROP", &IInteractable::dropObject); mTwoInteractionCommands.emplace("GIVE", &IInteractable::giveObject); mTwoInteractionCommands.emplace("ATTACK", &IInteractable::attackEnemy); mInitialzed = true; } } void CommandManager::help() { AnalyticsManager::instance().UpdateActionData("Help"); std::cout << "==============================" << std::endl; std::cout << "List of Commands" << std::endl; std::cout << "HELP" << std::endl; std::cout << "SAVE" << std::endl; std::cout << "EXIT" << std::endl; std::cout << "INVENTORY" << std::endl; std::cout << "LOOK" << std::endl; std::cout << "LOOK <Object Name>" << std::endl; std::cout << "TELEPORT <Portal Name>" << std::endl; std::cout << "PICK <Object Name>" << std::endl; std::cout << "GO <Direction> (Example: GO North)" << std::endl; std::cout << "ATTACK <Enemy Name> WITH <Weapon Name>" << std::endl; std::cout << "BLOCK <Enemy Name>" << std::endl; std::cout << "WEAR <Object Name>" << std::endl; std::cout << "PLAY <Object Name>" << std::endl; std::cout << "GIVE <Object Name> TO <Collector Name>" << std::endl; std::cout << "EAT <Object Name>" << std::endl; std::cout << "MOVE <Object Name>" << std::endl; std::cout << "ANSWER <Answer Name>" << std::endl; std::cout << "DROP <Object Name>" << std::endl; std::cout << "==============================" << std::endl; } std::vector<std::string> CommandManager::getCommandWords(std::string& pCommandStr) { std::vector<std::string> aCommandVector; std::istringstream aCommandStream(pCommandStr); std::string aWord(""); while (aCommandStream >> aWord) { aCommandVector.push_back(aWord); } return aCommandVector; } void CommandManager::convertToUpper(std::string& pString) { if (pString.size() > 0) { if (pString[0] == ' ') { pString = pString.substr(1); } } if (pString.size() > 0) { if (pString[pString.size() - 1] == ' ') { pString = pString.substr(0, pString.size() - 1); } } for (size_t aI = 0; aI < pString.size(); aI++) { if (std::islower(pString[aI])) { pString[aI] = std::toupper(pString[aI]); } } } bool CommandManager::runCommand(std::string& pCommandStr) { convertToUpper(pCommandStr); std::vector<std::string> aCommandWords = getCommandWords(pCommandStr); if (aCommandWords.size() <= 0) { return false; } if (mSingleCommands.count(pCommandStr) == 1) { mSingleCommands[pCommandStr](); return true; } bool aTwoInteraction = mTwoInteractionCommands.count(aCommandWords.at(0)) == 1; if (mInteractableCommands.count(aCommandWords.at(0)) == 0 && !aTwoInteraction) { return false; } std::string aObj1 = ""; std::string aObj2 = ""; bool aSInObj2 = false; bool aSwapObj1n2 = false; for (size_t aI = 1; aI < aCommandWords.size(); aI++) { if (aTwoInteraction && aCommandWords.at(aI) == "WITH") { aSInObj2 = true; continue; } else if (aTwoInteraction && aCommandWords.at(aI) == "TO") { aSInObj2 = true; aSwapObj1n2 = true; continue; } if (aSInObj2) { if (aObj2 != "") { aObj2 += " "; } aObj2 += aCommandWords.at(aI); } else { if (aObj1 != "") { aObj1 += " "; } aObj1 += aCommandWords.at(aI); } } if (aSwapObj1n2) //for implementation sake { std::string aObJ = aObj1; aObj1 = aObj2; aObj2 = aObJ; } IInteractable* aIObj1 = GameManager::instance().getInteractable(aObj1); if (aIObj1 == nullptr) { return false; } if (aSInObj2) { IInteractable* aIObj2 = GameManager::instance().getInteractable(aObj2); if (aIObj2 == nullptr) { return false; } mTwoInteractionCommands[aCommandWords.at(0)](aIObj1, aIObj2); } else if (aTwoInteraction) { return false; } else { mInteractableCommands[aCommandWords.at(0)](aIObj1); if (aCommandWords.at(0) == "LOOK") { AnalyticsManager::instance().UpdateActionData("Look"); } } return true; }
Markdown
UTF-8
1,810
4.40625
4
[ "Apache-2.0" ]
permissive
Tutorial -------- For loops in C are straightforward. They supply the ability to create a loop - a code block that runs multiple times. For loops require an iterator variable, usually notated as `i`. For loops give the following functionality: * Initialize the iterator variable using an initial value * Check if the iterator has reached its final value * Increases the iterator For example, if we wish to iterate on a block for 10 times, we write: int i; for (i = 0; i < 10; i++) { printf("%d\n", i); } This block will print the numbers 0 through 9 (10 numbers in total). For loops can iterate on array values. For example, if we would want to sum all the values of an array, we would use the iterator `i` as the array index: int array[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int sum = 0; int i; for (i = 0; i < 10; i++) { sum += array[i]; } /* sum now contains a[0] + a[1] + ... + a[9] */ printf("Sum of the array is %d\n", sum); Exercise -------- Calculate the factorial (multiplication of all items `array[0]` to `array[9]`, inclusive), of the variable `array`. Tutorial Code ------------- #include <stdio.h> int main() { int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int factorial = 1; int i; /* calculate the factorial using a for loop here*/ printf("10! is %d.\n", factorial); } Expected Output --------------- 10! is 3628800. Solution -------- #include <stdio.h> int main() { int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int factorial = 1; int i; for(i=0;i<10;i++){ factorial *= array[i]; } printf("10! is %d.\n", factorial); }
C
UTF-8
317
3.703125
4
[]
no_license
#include <stdio.h> int main (){ int n, i; int soma = 0; printf("\n\t Calculo dos n primeiros números naturais\n\n"); printf("Digite o valor de n: "); scanf("%d",&n); for (i = 0; i <= n; i++) { soma = soma + i; } printf("Soma dos %d primeiros números naturais é %d \n\n", n, soma); return 0; }
C++
UTF-8
2,908
2.65625
3
[]
no_license
#include <stdio.h> #include <conio.h> #include <math.h> #include <allegro.h> #include <list> #include "Vec2f.hpp" #include "Poly.hpp" #include "DrawVec2f.hpp" BITMAP* buffer; #define PIXEL(bmp, x, y) ((long*)(bmp)->line[(y)])[(x)] void init() { allegro_init(); install_mouse(); install_keyboard(); set_color_depth(32); set_gfx_mode(GFX_AUTODETECT_WINDOWED, 800, 600, 0, 0); buffer = create_bitmap(SCREEN_W, SCREEN_H); srand(time(NULL)); } void deinit() { destroy_bitmap(buffer); } struct Ray { Vec2f orig, dir; void init(Vec2f const& src, Vec2f const& dest) { orig = src; dir = (dest - src).unit(); } float dist(Vec2f const& p) const { if(fabs(dir.x) > 0.01) return (p.x - orig.x) / dir.x; else return (p.y - orig.y) / dir.y; } Vec2f point(float k) const { return orig + dir * k; } }; static bool clip(Vec2f& p, Vec2f const& v1, Vec2f const& v2, Ray const& ray) { Vec2f n = ray.dir.normal(); float d1 = (v1 - ray.orig).dot(n); float d2 = (v2 - ray.orig).dot(n); if((d1 < 0 && d2 >= 0) || (d2 < 0 && d1 >= 0)) { float k = fabs(d1) / (fabs(d1) + fabs(d2)); p = v1 + (v2 - v1) * k; return true; } return false; } bool clipPoly(Poly& dest1, Poly& dest2, Poly const& src, Ray const& ray) { Poly* curr = &dest1; Poly* other = &dest2; for(int i = 0; i < src.vertexVec.size(); i++) { int n = src.vertexVec.size(); Vec2f p; curr->vertexVec.push_back(src.vertexVec[i]); if(clip(p, src.vertexVec[i], src.vertexVec[(i + 1) % n], ray)) { curr->vertexVec.push_back(p); other->vertexVec.push_back(p); Poly* temp = curr; curr = other; other = temp; } } return dest2.vertexVec.size() != 0; } int main() { bool exit = false; init(); Poly poly; poly.init(400, 300, 100, 7); Vec2f a(100, 100), b(200, 200); while(!exit) { if(key[KEY_ESC]) exit = true; if(mouse_b == 1) a.init(mouse_x, mouse_y); if(mouse_b == 2) b.init(mouse_x, mouse_y); Ray ray; ray.init(a, b); clear_to_color(buffer, 0); Poly poly1, poly2; if(clipPoly(poly1, poly2, poly, ray)) { poly1.draw(buffer, makecol(255, 0, 0)); poly2.draw(buffer, makecol(0, 255, 0)); } else { poly1.draw(buffer, makecol(255, 0, 0)); } DrawVec2f::line(buffer, a, b, makecol(255, 255, 255)); DrawVec2f::circlefill(buffer, a, 4, makecol(0, 0, 255)); draw_sprite(buffer, mouse_sprite, mouse_x, mouse_y); blit(buffer, screen, 0, 0, 0, 0, SCREEN_W, SCREEN_H); } deinit(); return 0; }END_OF_MAIN()
JavaScript
UTF-8
801
2.515625
3
[ "MIT" ]
permissive
/* * pango-cairo.js */ const gi = require('../') const Gtk = gi.require('Gtk', '3.0') const Cairo = gi.require('cairo') const Pango = gi.require('Pango') const PangoCairo = gi.require('PangoCairo') gi.startLoop() Gtk.init() const surface = new Cairo.ImageSurface(Cairo.Format.RGB24, 300, 300) const cr = new Cairo.Context(surface) const fd = Pango.fontDescriptionFromString('Fantasque Sans Mono 16') const layout = PangoCairo.createLayout(cr) layout.setFontDescription(fd) layout.setAlignment(Pango.Alignment.LEFT) layout.setMarkup('<span font_weight="bold">A</span>') const [boldWidth, boldHeight] = layout.getSize() layout.setMarkup('<span>A</span>') const pixels = layout.getPixelSize() const [normalWidth, normalHeight] = layout.getSize() console.log({ fd, pixels, normalWidth, boldWidth })
Java
UTF-8
905
2.421875
2
[ "Apache-2.0" ]
permissive
package ch.hslu.swde.wda.service; import ch.hslu.swde.wda.domain.City; import ch.hslu.swde.wda.interfaces.CityService; import ch.hslu.swde.wda.repository.CityRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service public class CityServiceImpl implements CityService { @Autowired private CityRepository cityRepository; public City createCity(City city){ return cityRepository.save(city); } public List<City> getAllCities() { return cityRepository.findAll(); } public List<String> getAllCityNames() { List<City> cities = cityRepository.findAll(); List<String> cityNames = new ArrayList<>(); for (City city : cities) { cityNames.add(city.getName()); } return cityNames; } }
Markdown
UTF-8
2,266
4.59375
5
[]
no_license
# Java switch case 语句 switch case 语句判断一个变量与一系列值中某个值是否相等,每个值称为一个分支。 ### 语法 switch case 语句语法格式如下: ```java switch(expression){ case value : //语句 break; //可选 case value : //语句 break; //可选 //你可以有任意数量的case语句 default : //可选 //语句 } ``` switch case 语句有如下规则: - switch 语句中的变量类型可以是: byte、short、int 或者 char。从 Java SE 7 开始,switch 支持字符串 String 类型了,同时 case 标签必须为字符串常量或字面量。 - switch 语句可以拥有多个 case 语句。每个 case 后面跟一个要比较的值和冒号。 - case 语句中的值的数据类型必须与变量的数据类型相同,而且只能是常量或者字面常量。 - 当变量的值与 case 语句的值相等时,那么 case 语句之后的语句开始执行,直到 break 语句出现才会跳出 switch 语句。 - 当遇到 break 语句时,switch 语句终止。程序跳转到 switch 语句后面的语句执行。case 语句不必须要包含 break 语句。如果没有 break 语句出现,程序会继续执行下一条 case 语句,直到出现 break 语句。 - switch 语句可以包含一个 default 分支,该分支一般是 switch 语句的最后一个分支(可以在任何位置,但建议在最后一个)。default 在没有 case 语句的值和变量值相等的时候执行。default 分支不需要 break 语句。 **switch case 执行时,一定会先进行匹配,匹配成功返回当前 case 的值,==再根据是否有 break,判断是否继续输出,或是跳出判断。==** 如果匹配成功后没有break或者contiune,就会继续输出剩下的可能。 ```java public class Test { public static void main(String args[]){ int i = 1; switch(i){ case 0: System.out.println("0"); case 1: System.out.println("1"); case 2: System.out.println("2"); default: System.out.println("default"); } } } /* * 1 * 2 * default */ ```
Python
UTF-8
51
2.90625
3
[]
no_license
n = input("Enter number\n") print('Hello',n)
Java
UTF-8
1,205
2.9375
3
[ "Apache-2.0" ]
permissive
package platypus; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import org.junit.Test; public class DeloreanTest { public interface Car { String drive(); } public interface Aircraft { String fly(); } public interface Delorean extends Car, Aircraft { } public class CarImpl implements Car { @Override public String drive() { return "It can drive"; } } public class AircraftImpl implements Aircraft { @Override public String fly() { return "It can fly"; } } @Test public void testDelorean() { MixinClass<Delorean> deloreanMixinClass = MixinClasses.create(Delorean.class); Delorean delorean = deloreanMixinClass.newInstance(new AbstractMixinInitializer() { @Override protected void initialize() { implement(Car.class).with(new CarImpl()); implement(Aircraft.class).with(new AircraftImpl()); } }); assertThat(delorean.drive(), equalTo("It can drive")); assertThat(delorean.fly(), equalTo("It can fly")); } }
Python
UTF-8
826
3.375
3
[]
no_license
import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression dataset = pd.read_csv('mydata.csv') x=dataset.iloc[:,:-1] y=dataset.iloc[:,-1] x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=0) regressor=LinearRegression() regressor.fit(x_train,y_train) y_pred=regressor.predict(x_train) # Visualizing training data set plt.scatter(x_train,y_train,color="green") plt.plot(x_train,y_pred,color="red") plt.xlabel('Age') plt.ylabel('Height(cm)') plt.show() # Visualizing test data set plt.scatter(x_test,y_test,color="green") plt.plot(x_train,y_pred,color="red") plt.xlabel('Age') plt.ylabel('Height(cm)') plt.show() #This is my trial with my own datset, in the next one I have used an actual dataset.
Python
UTF-8
2,541
3.375
3
[]
no_license
''' Solves problem # 174 on https://projecteuler.net Sergey Lisitsin. Mar 2020 ''' # def generate_squares(limit): # squares = [ x**2 for x in range(1,limit+1)] # return squares # # # squares = generate_squares(100000) # evens = [x for x in squares if not (x%2) ] # odds = [x for x in squares if (x%2)] # # def distinct_laminae(tiles): # laminae = 0 # #print(mysquares) # for x in squares: # for y in squares: # #print (abs(x-y)) # if abs(x-y)==tiles: # laminae+=1 # return laminae//2 # def distinct_laminae(tiles): # tiles_used = 0 # starthole = 1 # laminae = 0 # while starthole <= (tiles//2) - 1: # side = starthole # while tiles_used <= tiles: # #print(starthole, tiles_used) # tiles_used = tiles_used + (side + 2) * 2 + side * 2 # if tiles_used == tiles: # laminae += 1 # #print(starthole,tiles_used) # side += 2 # starthole += 1 # tiles_used = 0 # #print(starthole) # return laminae def find_smaller_squares(num): return [x**2 for x in range(1,num//2) if x**2 < num] squares = find_smaller_squares(1000000) squares.pop(0) def find_distinct_laminae(num): result = 0 subsquares = [x for x in squares if x < num ] for x in range(len(subsquares)): multiplier = 2 while not(subsquares[x] * multiplier > num): if subsquares[x] * multiplier == num: result +=1 multiplier += 1 return (result) # def distinct_laminae(tiles): # start_side = (tiles//4)+1 # laminae = 0 # for x in range(start_side,1,-1): # for y in range((x-1),0,-1): # if x**2 - y**2 == tiles: # laminae += 1 # if laminae > 10: # return laminae # return laminae #print(distinct_laminae(100000)) counter = 0 for x in range(2,1000000): #print(x) p = find_distinct_laminae(x) #print(p) if p > 0 and p <=10: counter += 1 print(x) print(counter) # # squares = find_smaller_squares(1000000) # def find_distinct_laminae(num): # result = [] # subsquares = [x for x in squares if x < num ] # for x in range(len(subsquares)): # multiplier = 2 # while subsquares[x] * multiplier < num: # if subsquares[x] * multiplier == num: # result.append(1) # multiplier += 1 # return len(result)
Shell
UTF-8
922
3.703125
4
[]
no_license
#!/usr/bin/env bash # # Задать собственный поток ввода/вывода. У нас есть еще дескрипторы с 3 по 8 и мы можем задать их: # exec 3>>logfile echo "This should be displayed on screen" echo "This should be wrote in file" >&3 echo "And again this should be on screen" #Перенаправить ввод в скрипте можно точно так же, как и вывод. # Необходимо сохранить STDIN в другом дескрипторе, прежде чем перенаправлять ввод данных. exec 6<&0 exec 0<logfile while read LINE; do echo "$LINE" done exec 0<&6 read -p "Are you done now? " echo "Your answer is $REPLY" #Что бы закрыть дескриптор до завершения работы скрипта необходимо перенаправить его на &- exec 3>&-
TypeScript
UTF-8
1,322
2.75
3
[]
no_license
import { ADD_ACTORS, ADD_ACTORS_REQUEST, GET_ACTORS, GET_ACTORS_REQUEST, SEARCH_ACTORS, ActorListActionTypes, ACTOR_LOADING, GET_ACTOR, ActorItemActionTypes, } from '../types/actorTypes'; export const actorListReducer = ( state = { actors: [] }, action: ActorListActionTypes ) => { switch (action.type) { case GET_ACTORS_REQUEST: return { loading: true, actors: [] }; case GET_ACTORS: return { ...state, loading: false, actors: action.payload.actors, pages: action.payload.pages, results: action.payload.results, }; case ADD_ACTORS_REQUEST: return { ...state, nextLoading: true }; case ADD_ACTORS: return { ...state, nextLoading: false, actors: [...state.actors, ...action.payload], }; case SEARCH_ACTORS: { return { ...state, loading: false, actors: action.payload.actors, pages: action.payload.pages, results: action.payload.results, query: action.payload.query, }; } default: return state; } }; export const actorItemReducer = ( state = { actor: {} }, action: ActorItemActionTypes ) => { switch (action.type) { case ACTOR_LOADING: return { ...state, loading: true }; case GET_ACTOR: return { ...state, actor: action.payload, loading: false, }; default: return state; } };
Python
UTF-8
440
3.484375
3
[]
no_license
#!/usr/bin/python # -*- coding:utf-8 -*- #basic Judge sentences. a =10 b=5 if a>0 and b >0 and a >b: print "a is over b." else: print "a is below b." #循环判断 alist = [34,56.32,455,"tets",'a'] for tt in alist: print "get value is",tt for index,value in enumerate(alist): print "get index is:%d and value is: %s" %(index,str(value)) if True : pass print "pass code pass."
Markdown
UTF-8
5,219
2.796875
3
[]
no_license
# java-game-box-project-2-programandcontrolman java-game-box-project-2-programandcontrolman created by GitHub Classroom # Program & Control Man Developed in house, Program & Control Man is a clone of the apple II game TaxMan developed by Hals Labs, which is a clone of the arcade game PacMan developed Bandai Namco. ## Description In the land of Tanstaafl the citizens are in revolt, denying the government of its rightful venue, and rioting in the streets. You are the Taxman, self-appointed cham-pion of the government coffers. The silly citizens don't know what's good for them, and have developed rebellious tendencies. They are armed and dangerous. To help you, there are tax centers in each precinct. Passing through one gives you temporary power to 'pacify' the angry rebels. But, alas, they are soon back on the streets, causing more damage and destruction. Occasionally, government bonuses will appear. Quickly grab these to assure max-imum profits, before the feds take back what they offer. These 'fruit' taste de-licious, but be careful; the citizens resent this and will do their utmost to prevent your collecting these bonuses. ![alt text](https://github.com/uprm-ciic4010-s20/java-game-box-project-2-programandcontrolman/blob/master/taxman.png) ## Recursion used for the bullet pathfinding algorithm ```java public void checker ( int pixelX, int pixelY, int tpixelX, int tpixelY){ if (pixelX > 1) { if (nodos[pixelY][pixelX - 1] ) {//left if (1 + Queue[pixelY][pixelX][0] < Queue[pixelY][pixelX - 1][0]) { Queue[pixelY][pixelX - 1][0] = 1 + Queue[pixelY][pixelX][0]; Queue[pixelY][pixelX - 1][1] = pixelX; Queue[pixelY][pixelX - 1][2] = pixelY; Visited[pixelY][pixelX] = true; checker(pixelX - 1, pixelY, tpixelX, tpixelY); } } } if (pixelX < xmapsize - 1) {//right if (nodos[pixelY][pixelX + 1]) { if (1 + Queue[pixelY][pixelX][0] < Queue[pixelY][pixelX + 1][0]) { Queue[pixelY][pixelX + 1][0] = 1 + Queue[pixelY][pixelX][0]; Queue[pixelY][pixelX + 1][1] = pixelX; Queue[pixelY][pixelX + 1][2] = pixelY; Visited[pixelY][pixelX] = true; checker(pixelX + 1, pixelY, tpixelX, tpixelY); } } } if (pixelY > 1) {//up if (nodos[pixelY - 1][pixelX]) { if (1 + Queue[pixelY][pixelX][0] < Queue[pixelY - 1][pixelX][0]) { Queue[pixelY - 1][pixelX][0] = 1 + Queue[pixelY][pixelX][0]; Queue[pixelY - 1][pixelX][1] = pixelX; Queue[pixelY - 1][pixelX][2] = pixelY; Visited[pixelY][pixelX] = true; checker(pixelX, pixelY - 1, tpixelX, tpixelY); } } } if (pixelY < 30 && nodos[pixelY][pixelX]) {//dn if (nodos[pixelY + 1][pixelX]) { if (1 + Queue[pixelY][pixelX][0] < Queue[pixelY + 1][pixelX][0]) { Queue[pixelY + 1][pixelX][0] = 1 + Queue[pixelY][pixelX][0]; Queue[pixelY + 1][pixelX][1] = pixelX; Queue[pixelY + 1][pixelX][2] = pixelY; Visited[pixelY][pixelX] = true; checker(pixelX, pixelY + 1, tpixelX, tpixelY); } } } } public void Backtracker ( int pixlX, int pixlY, int startX, int startY){ int[] prevcoor = new int[2]; prevcoor[0] = Queue[pixlY][pixlX][1]; prevcoor[1] = Queue[pixlY][pixlX][2]; if (prevcoor[0] == startX && prevcoor[1] == startY) { prevX = pixlX; prevY = pixlY; } else { Backtracker(prevcoor[0], prevcoor[1], startX, startY); } } ``` ## Authors ✒️ _All the people that have helped to develop this game._ * **Josian Velez** - *Intitial work* - [Josian Velez](https://github.com/ElementalWizard) * **Edwin Vega** - *Final work* - [Edwin vega](https://github.com/heckio) * **Juan Fontanez** - *Final work & Documentation* - [Juan Fontanez](#fulanito-de-tal) You can also look at the list of contributors at [contributors](https://github.com/uprm-ciic4010-s20/java-game-box-project-2-programandcontrolman/graphs/contributors) . FAQ --- Q: The game launches but the map is bigger than my screen, is this intended behaviour? A: Yes, this is the intended behavior. the game is designed to be played on 1920x1080 or higher with windows scaling at 100%, changing the map multiplier will probably break the game. ## Contributing Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. Please make sure to update tests as appropriate. ## License [UPRM](https://www.uprm.edu/cti/usu/license-and-software-agreements/)
C++
UTF-8
1,203
2.875
3
[]
no_license
#define accelerometerPinX A1 // x-axis of the accelerometer float collisionThreshold = 1.35; ///////////////////////////////////////////////////////////////////////////////////////////////////////// // /////////////// // // END GLOBAL VARS // // /////////////// // ///////////////////////////////////////////////////////////////////////////////////////////////////////// bool checkForCollision() { if ((DRIVE_INSTRUCTION == "STOP") || (DRIVE_INSTRUCTION == "REVERSE")) { return false; // Ignore accelerometer when stopped/reversing. } int x = analogRead(accelerometerPinX); // read from accelerometerPinX if (((((float)x - 331.5) / 65) > collisionThreshold)) // collision detected! { playErrorSound(); return true; // indicate collision detected } return false; // DEBUG // Serial.print(((float)x - 331.5) / 65); //print x value on serial monitor // Serial.println("m/s²"); }
Java
UTF-8
286
2.71875
3
[]
no_license
package com.atn.kata.domain; public enum GameStatus { DEUCE("Deuce"),ADVANTAGE("Advantage"),WINNED("Winned"),START("Start"); private String value; GameStatus(String value){ this.value=value; } public String getValue(){ return this.value; } }