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
Markdown
UTF-8
3,442
3.109375
3
[]
no_license
### v-model 原理 看下面代码 通过给 input 元素监听 input 事件 使 $event.target.value 等于绑定值 ### with 语法 ```js // 如果想要改变 obj 中每一项的值,一般写法可能会是这样: // 重复写了 3 次的“obj” obj.a = 2; obj.b = 3; obj.c = 4; // 而用了 with 的写法,会有一个简单的快捷方式 with (obj) { a = 3; //a=obj.a b = 4; c = 5; } ``` ### 模板编译(vue-template-compiler) 模板会编译为 render 函数,执行 render 函数会返回 vnode 基础 vnode 执行 patch(补丁) 和 diff(对比)(渲染和更新) 集成 webpack vue-loader,会在开发环境下编译模板 引入 vue 得话会再运行时才编译 这样性能就不行 都是再开发环境下打包编译好再发布的 ```js //模板编译 const compiler = require('vue-template-compiler') // 插值 const template = `<p>{{message}}</p>` with(this){return createElement('p',[createTextVNode(toString(message))])} // h -> vnode // createElement -> vnode // 表达式 // const template = `<p>{{flag ? message : 'no message found'}}</p>` // with(this){return _c('p',[_v(_s(flag ? message : 'no message found'))])} // 属性和动态属性 // const template = ` // <div id="div1" class="container"> // <img :src="imgUrl"/> // </div> // ` // with(this){return _c('div', // {staticClass:"container",attrs:{"id":"div1"}}, // [ // _c('img',{attrs:{"src":imgUrl}})])} // // 条件 // const template = ` // <div> // <p v-if="flag === 'a'">A</p> // <p v-else>B</p> // </div> // ` // with(this){return _c('div',[(flag === 'a')?_c('p',[_v("A")]):_c('p',[_v("B")])])} // 循环 // const template = ` // <ul> // <li v-for="item in list" :key="item.id">{{item.title}}</li> // </ul> // ` // with(this){return _c('ul',_l((list),function(item){return _c('li',{key:item.id},[_v(_s(item.title))])}),0)} // 事件 // const template = ` // <button @click="clickHandler">submit</button> // ` // with(this){return _c('button',{on:{"click":clickHandler}},[_v("submit")])} // v-model !!! const template = `<input type="text" v-model="name">` // 主要看 input 事件 with(this){return _c('input',{directives:[{name:"model",rawName:"v-model",value:(name),expression:"name"}],attrs:{"type":"text"},domProps:{"value":(name)},on:{"input":function($event){if($event.target.composing)return;name=$event.target.value}}})} // 以上编译过后的都是render 函数 // 它们返回 vnode // patch(补丁) // 编译 const res = compiler.compile(template) console.log(res.render) // ---------------分割线-------------- // // 从 vue 源码中找到缩写函数的含义 // function installRenderHelpers (target) { // target._o = markOnce; // target._n = toNumber; // target._s = toString; // target._l = renderList; // target._t = renderSlot; // target._q = looseEqual; // target._i = looseIndexOf; // target._m = renderStatic; // target._f = resolveFilter; // target._k = checkKeyCodes; // target._b = bindObjectProps; // target._v = createTextVNode; // target._e = createEmptyVNode; // target._u = resolveScopedSlots; // target._g = bindObjectListeners; // target._d = bindDynamicKeys; // target._p = prependModifier; // } ```
Java
UTF-8
595
2.859375
3
[]
no_license
package AbstractClasses_Schugeschaeft; public abstract class Adidas extends AbstractClasses_Schugeschaeft.Shoe { private String brand = "Adidas"; private int guaranteeInDays = 29; public Adidas(String sole, String material, String color, boolean waterproof) { super(sole, material, color, waterproof); } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public int getGuaranteeInDays() { return guaranteeInDays; } public void setGuaranteeInDays(int guaranteeInDays) { this.guaranteeInDays = guaranteeInDays; } }
Python
UTF-8
641
3.625
4
[]
no_license
#!/bin/python # 9-1 exercise # @author strong # @email 1025155365@qq.com class Restaurant: def __init__(self, restaurant_name, cuisine_type): self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type def describe_restaurant(self): print(self.restaurant_name + ':' + self.cuisine_type) def open_restaurant(self): print("on sale!") res = Restaurant("strong", "goods") res.describe_restaurant() res.open_restaurant() res = Restaurant("strong1", "goods1") res.describe_restaurant() res.open_restaurant() res = Restaurant("strong2", "goods2") res.describe_restaurant() res.open_restaurant()
Java
UTF-8
319
2.671875
3
[]
no_license
import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class TaskSecond { public static boolean checkArray(Integer[] array){ Set<Integer> set = new HashSet<Integer>(Arrays.asList(array)); return (set.size() == 2) && (set.contains(1)) &&(set.contains(4)); } }
C++
UTF-8
11,450
2.578125
3
[ "MIT" ]
permissive
/* * dbtype_DocumentProperty.cpp */ #include "dbtypes/dbtype_DocumentProperty.h" #include "dbtypes/dbtype_PropertyData.h" #include <string> #include <vector> #include <iostream> #include <sstream> #include <stddef.h> #include "osinterface/osinterface_OsTypes.h" #include "utilities/mutgos_config.h" #include "text/text_Utf8Tools.h" #include <boost/tokenizer.hpp> #include "text/text_StringConversion.h" #define SHORT_STRING_LENGTH 60 namespace { const std::string EMPTY_STRING; } namespace mutgos { namespace dbtype { // ---------------------------------------------------------------------- DocumentProperty::DocumentProperty() : PropertyData(PROPERTYDATATYPE_document), max_lines(config::db::limits_property_document_lines()) { } // ---------------------------------------------------------------------- DocumentProperty::DocumentProperty(const DocumentProperty &data) : PropertyData(PROPERTYDATATYPE_document), max_lines(data.max_lines) { set(data.document_data); } // ---------------------------------------------------------------------- DocumentProperty::~DocumentProperty() { clear(); } // ---------------------------------------------------------------------- bool DocumentProperty::operator==(const PropertyData *rhs) const { if (not rhs) { return false; } else if (rhs == this) { return true; } else if (PropertyData::operator==(rhs)) { const DocumentProperty *rhs_casted = dynamic_cast<const DocumentProperty *>(rhs); if (rhs_casted and (document_data.size() == rhs_casted->document_data.size())) { bool result = true; for (DocumentData::const_iterator iter = document_data.begin(), iter_rhs = rhs_casted->document_data.begin(); (iter != document_data.end()) and (iter_rhs != rhs_casted->document_data.end()); ++iter, ++iter_rhs) { if (*iter and *iter_rhs) { if (**iter != **iter_rhs) { result = false; break; } } else { // One or both of them is null, which should never // happen. Not equal. result = false; break; } } return result; } } return false; } // ---------------------------------------------------------------------- bool DocumentProperty::operator<(const PropertyData *rhs) const { if (not rhs) { return false; } else if (rhs == this) { return false; } else if (not PropertyData::operator<(rhs)) { const DocumentProperty *rhs_casted = dynamic_cast<const DocumentProperty *>(rhs); if (rhs_casted) { bool result = false; for (DocumentData::const_iterator iter = document_data.begin(), iter_rhs = rhs_casted->document_data.begin(); (iter != document_data.end()) and (iter_rhs != rhs_casted->document_data.end()); ++iter, ++iter_rhs) { if (*iter and *iter_rhs) { if ((**iter).compare(**iter_rhs) < 0) { result = true; break; } } else { // One of the documents has a bad pointer. Should // NEVER happen. // result = true; break; } } if (not result) { // A tie. See if one document is longer than the other result = document_data.size() < rhs_casted->document_data.size(); } return result; } return false; } return true; } // ---------------------------------------------------------------------- void DocumentProperty::set_max_lines( const osinterface::OsTypes::UnsignedInt max) { if (max > 0) { max_lines = max; } } // ------------------------------------------------------------------ PropertyData *DocumentProperty::clone(void) const { return new DocumentProperty(*this); } // ---------------------------------------------------------------------- bool DocumentProperty::append_line(const std::string &data) { if (is_full()) { return false; } else if (text::utf8_size(data) > config::db::limits_string_size()) { // Too long a line. return false; } else { document_data.push_back(new std::string(data)); return true; } } // ---------------------------------------------------------------------- bool DocumentProperty::insert_line( const std::string &data, const MG_UnsignedInt line) { bool success = true; if (is_full()) { success = false; } else if (text::utf8_size(data) > config::db::limits_string_size()) { // Too long a line. success = false; } else { if (line >= get_number_lines()) { // If out of range, then just append. document_data.push_back(new std::string(data)); } else { document_data.insert( document_data.begin() + line, new std::string(data)); } } return success; } // ---------------------------------------------------------------------- bool DocumentProperty::delete_line(const MG_UnsignedInt line) { bool success = true; if (get_number_lines() <= line) { // Trying to delete past the end success = false; } else { delete document_data[line]; document_data.erase(document_data.begin() + line); } return success; } // ---------------------------------------------------------------------- MG_UnsignedInt DocumentProperty::get_number_lines(void) const { return document_data.size(); } // ---------------------------------------------------------------------- bool DocumentProperty::is_full(void) const { return document_data.size() > max_lines; } // ---------------------------------------------------------------------- const std::string &DocumentProperty::get_line( const MG_UnsignedInt line) const { if (line < get_number_lines()) { return *(document_data[line]); } else { // Out of range. return EMPTY_STRING; } } // ---------------------------------------------------------------------- void DocumentProperty::clear(void) { // Need to clean up memory! // for (DocumentData::iterator iter = document_data.begin(); iter != document_data.end(); ++iter) { delete *iter; } document_data.clear(); } // ---------------------------------------------------------------------- std::string DocumentProperty::get_as_short_string(void) const { if (document_data.empty()) { return EMPTY_STRING; } else { return (*(document_data[0])).substr(0, SHORT_STRING_LENGTH); } } // ---------------------------------------------------------------------- std::string DocumentProperty::get_as_string(void) const { std::ostringstream stream; for (MG_UnsignedInt index = 0; index < document_data.size(); ++index) { stream << *(document_data[index]) << std::endl; } return stream.str(); } // ---------------------------------------------------------------------- bool DocumentProperty::set_from_string(const std::string &str) { bool success = true; clear(); // Split it out by newlines, and put them one at a time into the // document. // boost::char_separator<char> sep(MG_NewLine); boost::tokenizer<boost::char_separator<char> > tokens(str, sep); for (boost::tokenizer<boost::char_separator<char> >::iterator tok_iter = tokens.begin(); tok_iter != tokens.end(); ++tok_iter) { if (not append_line(*tok_iter)) { success = false; break; } } if (not success) { clear(); } return success; } // ---------------------------------------------------------------------- bool DocumentProperty::set(const std::vector<std::string> &data) { bool success = true; clear(); for (MG_UnsignedInt index = 0; index < data.size(); ++index) { if (not append_line(data[index])) { success = false; break; } } if (not success) { clear(); } return success; } // ---------------------------------------------------------------------- bool DocumentProperty::set(const DocumentData &data) { if (&data == &document_data) { // This is us! return true; } clear(); for (DocumentData::const_iterator iter = data.begin(); iter != data.end(); ++iter) { std::string * const string_ptr = new std::string(**iter); document_data.push_back(string_ptr); } return true; } // ---------------------------------------------------------------------- const DocumentProperty::DocumentData &DocumentProperty::get(void) const { return document_data; } // ------------------------------------------------------------------ size_t DocumentProperty::mem_used(void) const { size_t string_mem = PropertyData::mem_used(); for (DocumentData::const_iterator iter = document_data.begin(); iter != document_data.end(); ++iter) { string_mem += (*iter)->capacity() + sizeof(void *) + sizeof(max_lines); } return string_mem; } } /* namespace dbtype */ } /* namespace mutgos */
Python
UTF-8
1,011
3.390625
3
[]
no_license
class Solution: def intToRoman(self, num): """ :type num: int :rtype: str """ rule = { 1000: 'M', 500: 'D', 100: 'C', 50: 'L', 10: 'X', 5: 'V', 1: 'I' } # rule_pattern = [1000, 500, 100, 50, 10, 5, 1] rest = num div = 1000 result = "" while div >= 1: div = int(div) if div > rest: div /= 10 continue dresult, rest = rest // div, rest % div if dresult == 9: result += rule[div] + rule[div*10] elif dresult > 4: result += rule[div * 5] + (rule[div] * (dresult - 5)) elif dresult == 4: result += rule[div] + rule[div*5] else: result += rule[div] * dresult div /= 10 return result s = Solution() r = s.intToRoman(9) print(r)
C++
UTF-8
2,719
2.765625
3
[]
no_license
#include "events/gestureeventfilter_p.h" #include <algorithm> GestureEventFilter::GestureEventFilter() { } GestureEventFilter::~GestureEventFilter() { } GestureMoveEventFilter::GestureMoveEventFilter() : GestureEventFilter() , m_moveThreshold(0) , m_trackMovement(true) { } void GestureMoveEventFilter::filter(GestureTouchEvent *ev) { if (!ev) return; if (m_moveThreshold <= 0) return; if (ev->type == GestureTouchEvent::TouchStart) { if (ev->numTouchPoints == 1) m_trackMovement = true; updateHistory(ev); } else if (ev->type == GestureTouchEvent::TouchMove && m_trackMovement) { bool aboveThreshold = false; unsigned int a = 0, b = 0; while (!aboveThreshold && a < m_numTouchPoints && b < ev->numTouchPoints) { // Compare the correct finger ids while (m_touchPoints[a].id < ev->touchPoints[b].id) a++; while (m_touchPoints[a].id > ev->touchPoints[b].id) b++; int diff = abs(m_touchPoints[a].x - ev->touchPoints[b].x) + abs(m_touchPoints[a].y - ev->touchPoints[b].y); if (diff > m_moveThreshold) aboveThreshold = true; a++; b++; } if (aboveThreshold) { ev->flags &= ~GestureTouchEvent::GESTURE_EVENT_TINY_MOVE; m_trackMovement = false; } else { ev->flags |= GestureTouchEvent::GESTURE_EVENT_TINY_MOVE; } } } void GestureMoveEventFilter::updateHistory(GestureTouchEvent *ev) { m_numTouchPoints = ev->numTouchPoints; for (unsigned int i = 0; i < ev->numTouchPoints; ++i) { if (ev->touchPoints[i].state == GestureTouchPoint::TouchPressed) m_touchPoints[i] = ev->touchPoints[i]; } } PinchEventFilter::PinchEventFilter() { } void PinchEventFilter::filter(GestureTouchEvent *ev) { if (!ev) return; if (ev->numTouchPoints != 2) { reset(); return; } Vector2D p0(ev->touchPoints[0].x, ev->touchPoints[0].y); Vector2D p1(ev->touchPoints[1].x, ev->touchPoints[1].y); if (m_p0.isNull() && m_p1.isNull()) { m_p0 = p0; m_p1 = p1; } Vector2D diffA = (m_p0 - p0); Vector2D diffB = (m_p1 - p1); if (diffA.lengthSquared() > MIN_MOVEMENT_LENGTH_SQUARED && diffB.lengthSquared() > MIN_MOVEMENT_LENGTH_SQUARED) ev->flags |= GestureTouchEvent::GESTURE_EVENT_CAN_RECOGNIZE_DIRECTION; else ev->flags &= ~GestureTouchEvent::GESTURE_EVENT_CAN_RECOGNIZE_DIRECTION; } void PinchEventFilter::reset() { m_p0 = Vector2D(); m_p1 = Vector2D(); }
Java
UTF-8
3,233
2.71875
3
[]
no_license
package com.bignerdranch.android.client; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import java.util.List; public class SearchActivity extends AppCompatActivity { private List<String> people; private List<String> events; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent intent; switch(item.getItemId()) { case android.R.id.home: this.finish(); return true; default: } return true; } // public class MyAdapter extends RecyclerView.Adapter<MyAdapter.SearchViewHolder> { // // // Provide a reference to the views for each data item // // Complex data items may need more than one view per item, and // // you provide access to all the views for a data item in a view holder // public class SearchViewHolder extends RecyclerView.ViewHolder { // // each data item is just a string in this case // public TextView mTextView; // public SearchViewHolder(TextView v) { // super(v); // mTextView = (TextView)v.findViewById(R.id.textLine); // } // } // // // Provide a suitable constructor (depends on the kind of dataset) // public MyAdapter(List<String> lines) { // this.lines = lines; // } // // // Create new views (invoked by the layout manager) // @Override // public SearchViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // // create a new view // View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_text_view, parent, false); // // set the view's size, margins, paddings and layout parameters // //... // SearchViewHolder vh = new SearchViewHolder((TextView) v); // return vh; // } // // // Replace the contents of a view (invoked by the layout manager). What actaully displays the views. // @Override // public void onBindViewHolder(SearchViewHolder holder, int position) { // // - get element from your dataset at this position // // - replace the contents of the view with that element // holder.mTextView.setText(lines.get(position)); // } // // // Return the size of your dataset (invoked by the layout manager) // @Override // public int getItemCount() { // return lines.size(); // } // // // @Override // public void onAttachedToRecyclerView(RecyclerView recyclerView) { // super.onAttachedToRecyclerView(recyclerView); // } // // public void addLine(String line) { // lines.add(line); // notifyDataSetChanged(); // } // // public void removeLine(int lineNumber) { // lines.remove(lineNumber); // } }
Markdown
UTF-8
2,992
2.984375
3
[]
no_license
# Uge 19 Jeg har lavet to videoserier til jer. Den første videoserie introducerer Loggeren i en normal java applikation. Den anden serie viser loggeren brugt i Kaspers projektskabelon. Udover at vise loggeren i to forskellige miljøer, så bruger jeg de to serier til at se på fejl generelt. Hvilke informationer skal en bruger have, og hvilke ting skal gemmes i en logfil. Der er jo tale om forskelligt publikum i forskellige situationer. Men de handler også om hvordan man behandler en fejl, og endelig hvad en fornuftig strategi for en videre afvikling af programmet kan være. Jeg regner med at det hele nok tager halvanden time. Det er måske ikke lige overvejelser, I sidder og føler I kan tillade jer, hvis I er meget pressede. Hvis I har det sådan, og det ved jeg der er nogen af jer der har, så har I følgende muligheder. 1) I kan enten springe den første videoserie over og gå direkte til serien, der viser hvordan loggeren anvendes i projektskabelonen. Det er selvfølgelig lidt ærgeligt da jeg så har spildt noget tid, men jeg har fuld forståelse for det. 2) I kan også helt droppe logningen og koncentrere jer om alle de andre ting. Også det, har jeg forståelse for, men der er altså ikke så meget arbejde i det, og I bliver klogere af det. ### introduktion af loggeren i demo app. demologger som er det java projekt jeg tager udgangspunkt i kan hentes på git [demologger](https://github.com/raakostOnCph/loggerDemo) | Emne | Resource | | ------- | ---------------------------------------- | | Introduktion af loggeren og java projektet| [1.1](https://www.youtube.com/watch?v=WPWl0gYL6i0) | | Udvidelse af loggeren| [1.2](https://www.youtube.com/watch?v=1ykyND0ymiM) | lege med forskellige fejl | [1.3](https://www.youtube.com/watch?v=BTJvVrLLTuI) | lege med forskellige fejl| [1.4](https://www.youtube.com/watch?v=JL8C34te5Jw) | Tail og avk| [1.5](https://www.youtube.com/watch?v=ldl0eiD7--U) for at lave et filter af linjer som I skriver til en fil: `awk '/SEVERE/{print}' nik.log >> resultat.txt` Den færdige logger kan findes på gist så du kan gå igang med loggeren i kaspers skabelon.[færdig logger](https://gist.github.com/raakostOnCph/ac10585301af665941fd123e90d463f6) Loggeren i Kaspers projektskabelon. [projektskabelonen](https://github.com/raakostOnCph/Projektskabelon) | Emne | Resource | | ------- | ---------------------------------------- | | Eks. på hvordan loggeren kan brues i Login | [Login](https://www.youtube.com/watch?v=nPS5-aFj7vM) | | Eks. på hvordan loggeren kan bruges til create user| [Create user](https://www.youtube.com/watch?v=vq15yyXnkg0) | Loggeren på dropletten | [Dropletten](https://www.youtube.com/watch?v=dVvf_v5syDY) Hvis du oplever problemer med tiden ift. din connector så [se her](https://gist.github.com/9ef811f59481d56cd04cc37aef79d270)
C++
UTF-8
1,232
2.546875
3
[]
no_license
#include "Main.h" using namespace std; const int SCREEN_WIDTH = 640; const int SCREEN_HEIGHT = 480; void graphMain() { vector<string> vtrStrEquation = createVtrStrEquation((inputStrEQN())); Equation equation; equation = evalVtrStrEquation(vtrStrEquation); if(validateEquation(equation) == false) { cout << "Invalid Equation, returning to menu:"; return; } int* range = inputRange(); // deleteNodes(equation); ExpressionTree eqnTree; eqnTree.createTree(equation); // cout << eqnTree.value(); vector<VarNode*> indVar = inputConstantValues(equation); SDL_Init(SDL_INIT_EVERYTHING); SDL_Window * window = SDL_CreateWindow("Graphed Equation", 100, 100, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); SDL_Renderer * renderer = window ? SDL_CreateRenderer(window, -1, 0) : NULL; if (!window || !renderer) { std::cerr << SDL_GetError() << "\n"; SDL_Quit(); } SDL_Event event; bool quit = false; while (!quit) { while ( SDL_PollEvent(&event) ) { if (event.type == SDL_QUIT) quit = true; } renderExpressionTree(renderer, SCREEN_WIDTH, SCREEN_HEIGHT, eqnTree, indVar, range); SDL_RenderPresent(renderer); SDL_Delay(1); } SDL_DestroyRenderer(renderer); SDL_Quit(); }
C#
UTF-8
826
3.34375
3
[]
no_license
using System; namespace expr13 { class Program {//Khaibullin Bulat (goat and hay Square) static void Main(string[] args) { var a = Convert.ToInt32(Console.ReadLine()); var r = Convert.ToInt32(Console.ReadLine()); double sum = 0; if (r<=0.5*a) { sum = Math.PI * r * r; } if (r>=Math.Sqrt(2)/2*a) { sum = a * a; } if (r>0.5*a && r< Math.Sqrt(2) / 2 * a) { sum = (Math.PI * r * r )- 4 * (((((Math.PI * r * r) / 360) * 2 * Math.Acos((double)a / (2 * r)) * 180 / Math.PI)) - (Math.Sqrt(r * r - ((a * a) / 4)) * a / 2)); } Console.WriteLine(Math.Round(sum,3)); Console.ReadKey(); } } }
Java
UTF-8
552
1.898438
2
[]
no_license
package com.amine; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Merkez { public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext context = new ClassPathXmlApplicationContext("SpringBeanConfig.xml"); Ogrenci ogrenci = (Ogrenci) context.getBean("beanOgrenci", Ogrenci.class); ogrenci.getOgrenciListesi(); ogrenci.getOgrenciSet(); ogrenci.getOgrenciMap(); ogrenci.getOgrenciProperties(); } }
JavaScript
UTF-8
9,185
2.78125
3
[ "MIT" ]
permissive
var bigEndianPlatform = null; /** * Check if the endianness of the platform is big-endian (most significant bit first) * @returns {boolean} True if big-endian, false if little-endian */ function isBigEndianPlatform() { if ( bigEndianPlatform === null ) { var buffer = new ArrayBuffer( 2 ), uint8Array = new Uint8Array( buffer ), uint16Array = new Uint16Array( buffer ); uint8Array[ 0 ] = 0xAA; // set first byte uint8Array[ 1 ] = 0xBB; // set second byte bigEndianPlatform = ( uint16Array[ 0 ] === 0xAABB ); } return bigEndianPlatform; } // match the values defined in the spec to the TypedArray types var InvertedEncodingTypes = [ null, Float32Array, null, Int8Array, Int16Array, null, Int32Array, Uint8Array, Uint16Array, null, Uint32Array ]; // define the method to use on a DataView, corresponding the TypedArray type var getMethods = { Uint16Array: 'getUint16', Uint32Array: 'getUint32', Int16Array: 'getInt16', Int32Array: 'getInt32', Float32Array: 'getFloat32', Float64Array: 'getFloat64' }; function copyFromBuffer( sourceArrayBuffer, viewType, position, length, fromBigEndian ) { var bytesPerElement = viewType.BYTES_PER_ELEMENT, result; if ( fromBigEndian === isBigEndianPlatform() || bytesPerElement === 1 ) { result = new viewType( sourceArrayBuffer, position, length ); } else { var readView = new DataView( sourceArrayBuffer, position, length * bytesPerElement ), getMethod = getMethods[ viewType.name ], littleEndian = ! fromBigEndian, i = 0; result = new viewType( length ); for ( ; i < length; i ++ ) { result[ i ] = readView[ getMethod ]( i * bytesPerElement, littleEndian ); } } return result; } function decodePrwm( buffer ) { var array = new Uint8Array( buffer ), version = array[ 0 ], flags = array[ 1 ], indexedGeometry = !! ( flags >> 7 & 0x01 ), indicesType = flags >> 6 & 0x01, bigEndian = ( flags >> 5 & 0x01 ) === 1, attributesNumber = flags & 0x1F, valuesNumber = 0, indicesNumber = 0; if ( bigEndian ) { valuesNumber = ( array[ 2 ] << 16 ) + ( array[ 3 ] << 8 ) + array[ 4 ]; indicesNumber = ( array[ 5 ] << 16 ) + ( array[ 6 ] << 8 ) + array[ 7 ]; } else { valuesNumber = array[ 2 ] + ( array[ 3 ] << 8 ) + ( array[ 4 ] << 16 ); indicesNumber = array[ 5 ] + ( array[ 6 ] << 8 ) + ( array[ 7 ] << 16 ); } /** PRELIMINARY CHECKS **/ if ( version === 0 ) { throw new Error( 'PRWM decoder: Invalid format version: 0' ); } else if ( version !== 1 ) { throw new Error( 'PRWM decoder: Unsupported format version: ' + version ); } if ( ! indexedGeometry ) { if ( indicesType !== 0 ) { throw new Error( 'PRWM decoder: Indices type must be set to 0 for non-indexed geometries' ); } else if ( indicesNumber !== 0 ) { throw new Error( 'PRWM decoder: Number of indices must be set to 0 for non-indexed geometries' ); } } /** PARSING **/ var pos = 8; var attributes = {}, attributeName, char, attributeType, cardinality, encodingType, arrayType, values, indices, i; for ( i = 0; i < attributesNumber; i ++ ) { attributeName = ''; while ( pos < array.length ) { char = array[ pos ]; pos ++; if ( char === 0 ) { break; } else { attributeName += String.fromCharCode( char ); } } flags = array[ pos ]; attributeType = flags >> 7 & 0x01; cardinality = ( flags >> 4 & 0x03 ) + 1; encodingType = flags & 0x0F; arrayType = InvertedEncodingTypes[ encodingType ]; pos ++; // padding to next multiple of 4 pos = Math.ceil( pos / 4 ) * 4; values = copyFromBuffer( buffer, arrayType, pos, cardinality * valuesNumber, bigEndian ); pos += arrayType.BYTES_PER_ELEMENT * cardinality * valuesNumber; attributes[ attributeName ] = { type: attributeType, cardinality: cardinality, values: values }; } pos = Math.ceil( pos / 4 ) * 4; indices = null; if ( indexedGeometry ) { indices = copyFromBuffer( buffer, indicesType === 1 ? Uint32Array : Uint16Array, pos, indicesNumber, bigEndian ); } return { version: version, attributes: attributes, indices: indices }; } // match the TypedArray type with the value defined in the spec var EncodingTypes = { Float32Array: 1, Int8Array: 3, Int16Array: 4, Int32Array: 6, Uint8Array: 7, Uint16Array: 8, Uint32Array: 10 }; // define the method to use on a DataView, corresponding the TypedArray type var setMethods = { Uint16Array: 'setUint16', Uint32Array: 'setUint32', Int16Array: 'setInt16', Int32Array: 'setInt32', Float32Array: 'setFloat32' }; function copyToBuffer (sourceTypedArray, destinationArrayBuffer, position, bigEndian) { var length = sourceTypedArray.length, bytesPerElement = sourceTypedArray.BYTES_PER_ELEMENT; var writeArray = new sourceTypedArray.constructor(destinationArrayBuffer, position, length); if (bigEndian === isBigEndianPlatform() || bytesPerElement === 1) { // desired endianness is the same as the platform, or the endianness doesn't matter (1 byte) writeArray.set(sourceTypedArray.subarray(0, length)); } else { var writeView = new DataView(destinationArrayBuffer, position, length * bytesPerElement), setMethod = setMethods[sourceTypedArray.constructor.name], littleEndian = !bigEndian, i = 0; for (i = 0; i < length; i++) { writeView[setMethod](i * bytesPerElement, sourceTypedArray[i], littleEndian); } } return writeArray; } function encodePrwm (attributes, indices, bigEndian) { var attributeKeys = attributes ? Object.keys(attributes) : [], indexedGeometry = !!indices, i, j; /** PRELIMINARY CHECKS **/ // this is not supposed to catch all the possible errors, only some of the gotchas if (attributeKeys.length === 0) { throw new Error('PRWM encoder: The model must have at least one attribute'); } if (attributeKeys.length > 31) { throw new Error('PRWM encoder: The model can have at most 31 attributes'); } for (i = 0; i < attributeKeys.length; i++) { if (!EncodingTypes.hasOwnProperty(attributes[attributeKeys[i]].values.constructor.name)) { throw new Error('PRWM encoder: Unsupported attribute values type: ' + attributes[attributeKeys[i]].values.constructor.name); } } if (indexedGeometry && indices.constructor.name !== 'Uint16Array' && indices.constructor.name !== 'Uint32Array') { throw new Error('PRWM encoder: The indices must be represented as an Uint16Array or an Uint32Array'); } /** GET THE TYPE OF INDICES AS WELL AS THE NUMBER OF INDICES AND ATTRIBUTE VALUES **/ var valuesNumber = attributes[attributeKeys[0]].values.length / attributes[attributeKeys[0]].cardinality | 0, indicesNumber = indexedGeometry ? indices.length : 0, indicesType = indexedGeometry && indices.constructor.name === 'Uint32Array' ? 1 : 0; /** GET THE FILE LENGTH **/ var totalLength = 8, attributeKey, attribute, attributeType, attributeNormalized; for (i = 0; i < attributeKeys.length; i++) { attributeKey = attributeKeys[i]; attribute = attributes[attributeKey]; totalLength += attributeKey.length + 2; // NUL byte + flag byte + padding totalLength = Math.ceil(totalLength / 4) * 4; // padding totalLength += attribute.values.byteLength; } if (indexedGeometry) { totalLength = Math.ceil(totalLength / 4) * 4; totalLength += indices.byteLength; } /** INITIALIZE THE BUFFER */ var buffer = new ArrayBuffer(totalLength), array = new Uint8Array(buffer); /** HEADER **/ array[0] = 1; array[1] = ( indexedGeometry << 7 | indicesType << 6 | (bigEndian ? 1 : 0) << 5 | attributeKeys.length & 0x1F ); if (bigEndian) { array[2] = valuesNumber >> 16 & 0xFF; array[3] = valuesNumber >> 8 & 0xFF; array[4] = valuesNumber & 0xFF; array[5] = indicesNumber >> 16 & 0xFF; array[6] = indicesNumber >> 8 & 0xFF; array[7] = indicesNumber & 0xFF; } else { array[2] = valuesNumber & 0xFF; array[3] = valuesNumber >> 8 & 0xFF; array[4] = valuesNumber >> 16 & 0xFF; array[5] = indicesNumber & 0xFF; array[6] = indicesNumber >> 8 & 0xFF; array[7] = indicesNumber >> 16 & 0xFF; } var pos = 8; /** ATTRIBUTES **/ for (i = 0; i < attributeKeys.length; i++) { attributeKey = attributeKeys[i]; attribute = attributes[attributeKey]; attributeType = typeof attribute.type === 'undefined' ? attributeTypes.Float : attribute.type; attributeNormalized = (!!attribute.normalized ? 1 : 0); /*** WRITE ATTRIBUTE HEADER ***/ for (j = 0; j < attributeKey.length; j++, pos++) { array[pos] = (attributeKey.charCodeAt(j) & 0x7F) || 0x5F; // default to underscore } pos++; array[pos] = ( attributeType << 7 | attributeNormalized << 6 | ((attribute.cardinality - 1) & 0x03) << 4 | EncodingTypes[attribute.values.constructor.name] & 0x0F ); pos++; // padding to next multiple of 4 pos = Math.ceil(pos / 4) * 4; /*** WRITE ATTRIBUTE VALUES ***/ var attributesWriteArray = copyToBuffer(attribute.values, buffer, pos, bigEndian); pos += attributesWriteArray.byteLength; } /*** WRITE INDICES VALUES ***/ if (indexedGeometry) { pos = Math.ceil(pos / 4) * 4; copyToBuffer(indices, buffer, pos, bigEndian); } return buffer; }
Markdown
UTF-8
12,771
3.375
3
[ "MIT" ]
permissive
--- title: Get the most out of Community Bridge Program date: "2020-08-25" description: "I am fortunate enough to have them as mentors as they not only guided me technically but also showed how to become a good software engineer and human being." tags: ["open-source", "internships", "cncf", "linux-foundation"] disqus: true --- ![Thanos Project](./program.png) <center><sub>CNCF 😻</sub></center><br/> Hello everyone, my name is Sonia 👱‍♀️, and currently, am pursuing my Bachelor's in Information Technology from Panjab University, Chandigarh, India. I have successfully graduated from Linux Foundation's [Community Bridge program](https://communitybridge.org/) with [Thanos](https://thanos.io/) community. In this blog post, I am going to write about my experience and suggestions for future Community Bridge interns to help you get the most out of your internship 😻 ###Every person has their own journey, this is mine👩🏻‍💻 ##Application Process: 1. [Start Early 🕓](#1-start-early) 2. [Project Selection 🤔](#2-project-selection) 3. [Set Goals/Objectives 🎯](#3-set-goals) 4. [Community Engagement 🤝](#4-community-engagement) 5. [Ask for feedback 🙌🏻](#5-ask-for-feedback) Applying for the [Community Bridge program](https://communitybridge.org/) is a very engaging process. It requires you to make many decisions and to commit the effort of making contributions as part of the requirements to be accepted. <b>1. Start Early 🕓:</b> It is advisable to start the process early so that you can interact with the project mentors, maintainers, and the other community members. This ensures the understanding of the working style of the organization and adapts to it in a better manner when the internship period actually starts.<br><br> If the mentors get to know you early and longer, then their decisions to choose you will be more informed than if you come in days before the deadline. <b>2. Project Selection 🤔:</b> [Community Bridge program](https://communitybridge.org/) has a list of different organizations and most of them have interesting projects you would love to work on. Always try to focus on 2–3 projects rather than everywhere. Choose your project wisely. It will help you to concentrate on being a great candidate for that project. You will need to put effort into completing the tasks. It's a good point to make sure you really want to learn and work on a particular idea. <b>3. Set Goals/Objectives 🎯:</b> Once you have narrowed down your project choices, reach out to the mentors for guidance, potential tasks, and good first issues to work on. Set some goals for what you want to work on and start contributing. Don't stop at one contribution. Making multiple contributions makes your profile stand out from the rest.<br><br> Also, the most important thing, this should not be a competition with other applicants. With your set goals, focus on yourself and compete with your own goals. <b>4. Community Engagement 🤝:</b> To know more about the organization culture, contribution workflow/communication channels, and Initial discussions about the project, it is important to communicate with the community. The project mentor is going to be one of the biggest factors that will affect your experience during the internship. Thus, you should make sure you get along! Ask them questions about what they look for when picking interns. If there are some weekly/monthly community meetings, try to join them and keep yourself updated with the latest feed, and ask questions if you have any.<br><br> If you are working on a new feature or pull request, it is preferred to ask in the channel and explain the changes in detail to make the review process fast and easy. <b>5. Feedback 🙌🏻:</b> Ask for feedback on the proposal or application form before the deadline. Asking for feedback can be a difficult thing, but it's a very important part of the application process. If you want to know what you're doing well, or what points you need to improve on, you'll need to be prepared to ask your mentor for feedback on your work.<br><br> The application process is mandatory and everyone must make an effort to try it out. Whether you are accepted or not, it will serve as a win. The contributions and connections you made during the application process may act as your project reference for the next opportunity, who knows? 😉<br><br> If you are a beginner in the open-source world, do not feel disheartened. At least you have started with open-source through this process and learned a lot of new things. The FOSS mentors are the kindest people in the world, they are always willing to guide and help you to continue with the contributions. <p align="center"> <img src="./save.gif"> </p> <center><sub>Work Together 🤗</sub></center><br/> <b><i>Note: You can always apply to the next round if you are not accepted. Learn from your mistakes and improve them in the next rounds.</i></b> ##Internship Guide: 1. [Sync up with Mentors 👾]() 2. [Communication 👋🏻]() 3. [Be Honest 😇]() 4. [Be Curious & Challenge yourself 💪🏻]() 5. [Having Mentors 👤]() 6. [Managing Project 👩🏻‍💻]() 7. [Join a group of co-interns 👥]() 8. [Have fun on the way 😉]() 9. [Thank You ❤️]() ![Thanos Project](./Thanos-logo_full.svg) <center><sub>Thanos 👾</sub></center><br/> I completed my internship with [Thanos](https://thanos.io/) project under the guidance of [Bartek Plotka](https://www.bwplotka.dev/) and [Povilas Versockas](https://povilasv.me/) where I worked on the project [Complete Katacoda tutorials](https://github.com/thanos-io/thanos/issues/2041). ##Thanos:Introduction [Thanos](https://github.com/thanos-io/thanos) is a project that turns your [Prometheus](https://prometheus.io/docs/prometheus/latest/installation/) installation into a highly available metric system with unlimited storage capacity. From a very high-level view, it does this by deploying a sidecar to Prometheus, which uploads the data blocks to any object storage. A store component downloads the blocks again and makes them accessible to a query component, which has the same API as Prometheus itself. This works nicely with [Grafana](https://grafana.com/) because its the same API. So without much effort, you can view your nice dashboard graphs beyond the configured retention time of your Prometheus monitoring stack. and get an almost unlimited timeline , only restricted by object storage capacities. [Thanos](https://github.com/thanos-io/thanos) also provides downsampling of stored metrics, deduplication of data points and some more. Since I had no prior knowledge of Golang, I decided to learn more about Golang and simultaneously, started working on good first issues to know more about the different components of Thanos. <b>Here is my list of online tutorials I found to be really helpful<i>(Many thanks to Khyati)</i></b>: 1. https://www.youtube.com/watch?v=YS4e4q9oBaU 2. https://play.golang.org/ 3. https://gobyexample.com/ <b>List of the blogs, tutorials, and videos that are really helpful in order to understand Thanos project:</b> 1. https://katacoda.com/thanos/courses/thanos/1-globalview 2. https://thanos.io/getting-started.md/ 3. [Thanos Introduction, PromCon 2018](https://www.youtube.com/watch?v=Fb_lYX01IX4) 4. [Thanos - Transforming Prometheus to a Global Scale in a Seven Simple Steps, GrafanaCon LA 2019](https://youtu.be/Iuo1EjCN5i4) ![Thanos Project](./Q.png) <center><sub>Make sure to sign the agreement</sub></center><br/> <b>1. Sync up with Mentors 👾:</b> I had weekly hangouts meeting with my mentor where we kept a proper meeting agenda ready to discuss the blockers, update pull requests, discuss the project proposal, and it's implementation. Ask for feedback from the mentors, maybe weekly? Be transparent if something is not clear and it is advisable to share the transparent status of what you are doing with the mentors as it will help you in a long way. <b>2. Communication 👋🏻:</b> As I mentioned above, making regular communication with the mentors, co-mentees and other members of the community is one of the most important things. This ensures you understand the working style of the organization and adapt to it in a better manner when the internship period actually starts.<br><br> We, Thanos mentees, took an initiative to gather all the mentees and invite a speaker to our weekly calls to make the discussion more open, inclusive, and interactive. Here's the [GitHub repo](https://github.com/soniasingla/thanos-mentees-meeting-notes) which contains all the notes and useful material. <b>3. Be Honest 😇:</b> Please be honest about your previous experiences, what you have built or created, contributed, and accomplished. As a developer, it's exciting and challenging to stay up to speed with the latest trends in technology.<br><br> Every day, new languages, frameworks, and devices capture our attention and spur conversations in meetups, forums, and chats. However, our developer community is made of people, not tools, and it's fascinating to explore its sociopolitical aspects. Software engineers are never done learning as our field is always changing. We are always beginners at some things and experts at others. <b>4. Be curious & challenge yourself 💪🏻:</b> You're going to make mistakes, make sure to ask tons of questions. But you're definitely going to learn a lot, that's how we learn, isn't it? When I started with Thanos, I didn't have prior experience with Golang, and was not much comfortable with Docker, but I know I can learn along with it. Make sure to do proper research and homework, before asking questions. <b>5. Having Mentors 👤:</b> My mentors, Bartek and Povilas, taught me patiently how to write readable code, automate things, be clear and transparent with whatever you are writing, use tools and make things easier for others, through the strict code review. Isn't it great?<br><br> I am fortunate enough to have them as mentors as they not only guided me technically but also showed how to become a good software engineer and human being. <b>6. Managing Project 👩🏻‍💻:</b> Yes, you heard me absolutely right! We can keep contributing towards our project even after the internship as it's open-source. The internship project becomes part of an even bigger project and thus, the last day of an internship isn't the end of your learning. <b>7. Join a group of co-interns 👥:</b> Interact with your co-interns & other folks in the community. It makes the journey more interesting and easy for you. Thanos Mentees team took an initiative to organize a hangout meeting every Friday to discuss weekly goals, review blog posts, hear funny stories, learn, and interact with each other. All these meetings were open to everyone. Along with the time, some of the interns from the other CNCF projects and past interns also joined the meets and we really had a great time.<br><br> There are many ways to collaborate with people and organizations. Encouraging communication between companies with a shared experience (Thanos) can be really helpful for the larger goal of continuing to ensure there is a strong base of support for future interns. <b>8. Have Fun 😉:</b> It is so important to have fun at work. Create your own sense of happiness as there will be times of happiness and frustration, both. With patience and practice, you are definitely going to be better at your work, so make it something you look forward to rather than just a responsibility. <b>9. Thank You ❤️:</b> Before I sign off for this post, I would like to take a moment to thank my mentors, [Bartek Plotka](https://www.bwplotka.dev/) and [Povilas Versockas](https://povilasv.me/). I really appreciate you all. Giving time despite the busy schedule to advise and guide someone is no easy feat! This program would never have finished without the hard work of [Ihor Dvoretskyi](https://github.com/idvoretskyi) and [CNCF community members](https://github.com/cncf/mentoring), thank you so much for everything. I would also like to acknowledge some of the people who helped me along the way: [Ben Ye](https://github.com/yeya24), [Harshitha Chowdary Thota](https://twitter.com/ThotaHarshitha), [Uche Obasi](https://twitter.com/Thisisobate), [Yash Sharma](https://twitter.com/yashrsharma44) ,and [Prem Kumar](https://twitter.com/prmsrswt). Congratulations to them for completing the program successfully. Thank you so much for helping when you could, providing support and guidance along the way. I have enjoyed working with you all so much over the internship. Thank you. If I missed an important detail or you wish to add anything to this blog post, please feel free to ping me. I look forward to hearing feedback. That's how we learn 🤗
C
UTF-8
5,205
2.9375
3
[]
no_license
/* * Filename: ql.c * * Purpose: doubly-linked queue manager * * Copyright Sierra Wireless Inc., 2008 All rights reserved * * Notes: The user of the queue is required to provide its own concurrent * control in the way of locks and such. */ #include "aa/aaglobal.h" #include "ql/qludefs.h" /* * Name: qlinitlnk * * Purpose: To initialize a queue link * * Param: linkp - pointer to a queue link * userp - pointer to user data to be linked * * Returns: Nothing * * Abort: None * * Notes: None */ global void qlinitlnk( struct qllink *linkp, void *userp ) { /* initialize queue link pointer to point as itself */ linkp->qlnextp = linkp; linkp->qlprevp = linkp; /* set the user data pointer in the queue link */ linkp->qluserp = userp; } /* * Name: qladdnext * * Purpose: To add a new queue link "next" to the current link in the queue * * Param: curlinkp - pointer to the current queue link * newlinkp - pointer to the new queue link to be added next to * the current one * Returns: Nothing * * Abort: None * * Notes: qlinit() must be called to initialize a link before it can * be added to the queue */ global void qladdnext(struct qllink *curlinkp, struct qllink *newlinkp) { /* add new link to queue */ newlinkp->qlnextp = curlinkp->qlnextp; newlinkp->qlprevp = curlinkp; newlinkp->qlnextp->qlprevp = newlinkp; curlinkp->qlnextp = newlinkp; } /* * Name: qladdprev * * Purpose: To add a new queue link previous to the current link in * the queue * * Param: curlinkp - pointer to the current queue link * newlinkp - pointer to the new queue link to be added * next to the current one * Returns: Nothing * * Abort: None * * Notes: qlinit() must be called to initialize a link before it can * be added to the queue */ global void qladdprev(struct qllink *curlinkp, struct qllink *newlinkp) { /* add new link to queue */ newlinkp->qlprevp = curlinkp->qlprevp; newlinkp->qlnextp = curlinkp; newlinkp->qlprevp->qlnextp = newlinkp; curlinkp->qlprevp = newlinkp; } /* * Name: qlgetnext * * Purpose: To retrieve the pointer to the next user data in the queue * * Param: curlinkp - pointer to the current queue link * * Returns: the next user data pointer in the queue * * Abort: None * * Notes: None * */ global void *qlgetnext( struct qllink *curlinkp) { /* return pointer to the next user data */ return(curlinkp->qlnextp->qluserp); } /* * Name: qlgetprev * * Purpose: To retrieve the pointer to the previous user * data in the queue * * Param: curlinkp * * Returns: the previous user data pointer in the queue * * Abort: None * * Notes: None * */ global void *qlgetprev( struct qllink *curlinkp) { /* return pointer to the previous user data */ return(curlinkp->qlprevp->qluserp); } /* * Name: qlremnext * * Purpose: To remove a queue link next to the current one * * Param: curlinkp - pointer to current queue link * * Returns: the user data pointer of the removed queue link * * Abort: None * * Notes: None */ global void *qlremnext( struct qllink *curlinkp) { struct qllink *remlinkp; /* pointer to the queue link to be removed */ /* get pointer to the queue link to be removed */ remlinkp = curlinkp->qlnextp; /* remove queue link from queue */ curlinkp->qlnextp = remlinkp->qlnextp; remlinkp->qlnextp->qlprevp = curlinkp; /* return user data pointer */ return(remlinkp->qluserp); } /* * Name: qlremprev * * Purpose: To remove the queue link previous to the current one * * Param: curlinkp - pointer to current queue link * * Returns: the user data pointer of the removed queue link * * Abort: None * * Notes: None */ global void *qlremprev( struct qllink *curlinkp) { struct qllink *remlinkp; /* pointer to the queue link to be removed */ /* get pointer to the queue link to be removed */ remlinkp = curlinkp->qlprevp; /* remove queue link */ curlinkp->qlprevp = remlinkp->qlprevp; remlinkp->qlprevp->qlnextp = curlinkp; /* return user data pointer of the removed queue link */ return( remlinkp->qluserp); } /* * Name: qlremcur * * Purpose: To remove the current queue link * * Param: curlinkp - pointer to current queue link * * Returns: the user data pointer of the removed queue link * * Abort: None * * Notes: None * */ global void *qlremcur( struct qllink *curlinkp) { struct qllink *nextlinkp; /* Ptr to the Q link next to current link */ /* get a pointer to queue link next to the one to be removed */ nextlinkp = curlinkp->qlnextp; /* remove the queue from the list */ curlinkp->qlprevp->qlnextp = nextlinkp; nextlinkp->qlprevp = curlinkp->qlprevp; /* return user data pointer of the removed queue link */ return( curlinkp->qluserp); }
JavaScript
UTF-8
1,104
2.8125
3
[]
no_license
/* eslint-disable radix */ /* eslint-disable no-prototype-builtins */ /* eslint-disable react/jsx-filename-extension */ /* eslint-disable react/prop-types */ /* eslint-disable no-unused-vars */ import React from 'react'; function MathComponent(props) { let result = ''; let finalResult = ''; const operators = { '+': (a, b) => a + b, '-': (a, b) => a - b, '*': (a, b) => a * b, '/': (a, b) => a / b, }; const { first, second, operator, childrens, } = props; if (second === 0) { result = 'Infinity'; } const checkOperatorExists = operators.hasOwnProperty(operator); if (!checkOperatorExists) { result = 'Invalid Operator'; } const checkChildernsExists = Object.keys(childrens); if (checkChildernsExists.length === 0 && !result) { const getOperator = operators[operator]; const calculateFinalVal = getOperator(first, second); finalResult = `${first}${operator}${second}=${calculateFinalVal}`; } else { finalResult = `${first}${operator}${second}=${result}`; } return ( <>{finalResult}</> ); } export default MathComponent;
C
WINDOWS-1250
192
2.640625
3
[]
no_license
#include <stdio.h> #include <conio.h> int anubis(void) { int i;//varivel de controle do loop for (i = 1; i <= 3; i++) { printf("Aprendendo Linguagem C\n"); } getch(); return(0); }
Python
UTF-8
515
2.734375
3
[]
no_license
import pygame black = pygame.Color(0, 0, 0) white = pygame.Color(255, 255, 255) blue = pygame.Color(0, 0, 255) light_blue = pygame.Color(0, 0, 170) yellow = pygame.Color(255, 255, 0) red = pygame.Color(255, 0, 0) light_red = pygame.Color(255, 160, 160) green = pygame.Color(0, 255, 0) light_green = pygame.Color(0, 170, 0) college_green = pygame.Color(0, 98, 51) orange = pygame.Color(255, 145, 0) light_orange = pygame.Color(255, 210, 160) gray = pygame.Color(128, 128, 128) brown = pygame.Color(150, 75, 0)
Python
UTF-8
715
3.65625
4
[]
no_license
distance=float(input("Enter the Total kilometers driven per day:")) cost_petrol=float(input("Enter the Cost per litre of petrol:")) mileage=float(input("Enter the Average kms per litre (mileage):")) fee_parking=float(input("Enter the Parking fee per day:")) toll=float(input("Enter the Toll tax per day:")) if (distance>=0 and cost_petrol>=0 and mileage>0 and fee_parking>=0 and toll>=0): quantity_petrol=(distance/mileage) total_petrol=(quantity_petrol*cost_petrol) total_cost=toll+fee_parking+total_petrol print("The Total Cost of driving per day is ₹",total_cost) if (distance<0 or cost_petrol<0 or mileage<=0 or fee_parking<0 or toll<0): print("INVALID input")
JavaScript
UTF-8
373
3.3125
3
[]
no_license
// this is local as it hasnt be declared for exports var local = 'bjcdkhd'; // whereas this is can be used in other files var shouldWeHaveCake = function() { // return true; console.log('yes lets eat the fucker'); } // module.exports = shouldWeHaveCake; // we can also make this a library by turning it into an object module.exports = { haveCake: shouldWeHaveCake} ;
Markdown
UTF-8
3,080
3.265625
3
[]
no_license
# [Swift] Stored Property Property는 값을 Class, Struct, Enum과 연결한다. Swift의 Property에는 크게 세가지가 있다. - Stored Property - Computed Property - Type Property Stored Property는 Class와 Struct에서 constant와 variable 값을 instance의 일부로 저장한다. ```swift struct FixedLengthRange { var firstValue: Int let length: Int } let rangeOfThreeItems = FixedLengthRange(firstValue: 0, length: 3) // 초깃값을 주지 않았기 때문에 rangeOfThreeItems.firstValue = 6 //error! rangeOfThreeItems.length = 10 //error! ``` firstValue가 var임에도 불구하고 에러가 나는 이유; Struct는 Value type이기 떄문에! Struct의 Instance가 var로 선언되면 해당 구조체의 property들은 변경할 수 있지만, let으로 선언되면 모든 property가 let으로 선언된 것 같이 된다. ```swift class FixedLengthRange { var firstValue: Int let length: Int init(firstValue : Int, length:Int) { self.firstValue = firstValue self.length = length } } let rangeOfThreeItems = FixedLengthRange(firstValue: 0, length: 3) rangeOfThreeItems.firstValue = 3 rangeOfThreeItems.length = 10//error! ``` Struct와 달리 Class는 Reference Type이기 때문에 우너본에 바로 접근하기 떄문에, 에러가 발생하지 않는다. ```swift class DataImporter { //DataImporter클래스는 외부파일에서 데이터를 가져오는 클래스! var filename = "data.txt" //데이터를 가져올 외부파일이름은 "data.txt"인가봐요 :) } class DataManager { lazy var importer = DataImporter() var data = [String]() //DataManager클래스는 데이터 관리하는 클래스에요. importer가 위에서 선언한 DataImporter의 인스턴스이며, lazy로 선언되었네요. } let manager = DataManager()//DataManager의 인스턴스를 만듭니다. 참고로, DataManager의 저장프로퍼티들은 초기값이 있으므로 init이 없어도 됩니다. manager.data.append("Some data")//DataManager의 저장프로퍼티 data라는 배열에 어떤 데이터를 집어넣고, manager.data.append("Some more data")//또 집어넣어요. //하지만 아직까지 DataImporter의 인스턴스인 importer프로퍼티는 생성되지 않았습니다. lazy 저장프로퍼티이기 때문이죠. ``` importer 프로퍼티에 처음 액세스 할 때 만들어지게 된다. 그 전까지는 생생되지 않는다. lazy stored property를 잘만 사용하면 성능도 올가가고, 공간낭비도 줄일 수 있다. lazy property 같은 경우, 항상 변수로서 선언해야 한다. 왜냐하면 초기값이 검색되지 않을 수 있기 때문에. 그리고 lazy property가 여러 쓰레드가 동싱에 엑세스 된다면, 단 한 번만 초기화 된다는 보장이 없기 떄문에. ## References [<The Swift Programming Language (Swift 4) - Properties>](https://docs.swift.org/swift-book/LanguageGuide/Properties.html) [Zedd - Properties - Stored Property(저장 프로퍼티)](https://zeddios.tistory.com/243)
Markdown
UTF-8
19,613
2.78125
3
[]
no_license
# swagger_client.PhoneSharedLineGroupsApi All URIs are relative to *https://api.zoom.us/v2* Method | HTTP request | Description ------------- | ------------- | ------------- [**add_members_to_shared_line_group**](PhoneSharedLineGroupsApi.md#add_members_to_shared_line_group) | **POST** /phone/shared_line_groups/{sharedLineGroupId}/members | Add Members to a Shared Line Group [**assign_phone_numbers_slg**](PhoneSharedLineGroupsApi.md#assign_phone_numbers_slg) | **POST** /phone/shared_line_groups/{sharedLineGroupId}/phone_numbers | Assign Phone Numbers [**delete_a_member_slg**](PhoneSharedLineGroupsApi.md#delete_a_member_slg) | **DELETE** /phone/shared_line_groups/{sharedLineGroupId}/members/{memberId} | Unassign a Member From a Shared Line Group [**delete_a_phone_number_slg**](PhoneSharedLineGroupsApi.md#delete_a_phone_number_slg) | **DELETE** /phone/shared_line_groups/{sharedLineGroupId}/phone_numbers/{phoneNumberId} | Unassign a Phone Number [**delete_a_shared_line_group**](PhoneSharedLineGroupsApi.md#delete_a_shared_line_group) | **DELETE** /phone/shared_line_groups/{sharedLineGroupId} | Delete a Shared Line Group [**delete_members_of_slg**](PhoneSharedLineGroupsApi.md#delete_members_of_slg) | **DELETE** /phone/shared_line_groups/{sharedLineGroupId}/members | Unassign Members of a Shared Line Group [**get_a_shared_line_group**](PhoneSharedLineGroupsApi.md#get_a_shared_line_group) | **GET** /phone/shared_line_groups/{sharedLineGroupId} | Get a Shared Line Group [**update_a_shared_line_group**](PhoneSharedLineGroupsApi.md#update_a_shared_line_group) | **PATCH** /phone/shared_line_groups/{sharedLineGroupId} | Update a Shared Line Group # **add_members_to_shared_line_group** > object add_members_to_shared_line_group(shared_line_group_id, body=body) Add Members to a Shared Line Group A [shared line group](https://support.zoom.us/hc/en-us/articles/360038850792) allows Zoom Phone admins to share a phone number and extension with a group of phone users or common area phones. This gives members of the shared line group access to the group's direct phone number and voicemail. Use this API to [add members](https://support.zoom.us/hc/en-us/articles/360038850792-Setting-up-shared-line-groups#h_7cb42370-48f6-4a8f-84f4-c6eee4d9f0ca) to a Shared Line Group. Note that a member can only be added to one shared line group. **Prerequisties:** <br> * Pro or higher account with Zoom Phone license. * A valid Shared Line Group * Account owner or admin privileges **Scopes:** `phone:write:admin` **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Light` ### Example ```python from __future__ import print_function import time import swagger_client from swagger_client.rest import ApiException from pprint import pprint # Configure OAuth2 access token for authorization: OAuth configuration = swagger_client.Configuration() configuration.access_token = 'YOUR_ACCESS_TOKEN' # create an instance of the API class api_instance = swagger_client.PhoneSharedLineGroupsApi(swagger_client.ApiClient(configuration)) shared_line_group_id = 'shared_line_group_id_example' # str | Unique Identifier of the shared line group. body = swagger_client.Body186() # Body186 | (optional) try: # Add Members to a Shared Line Group api_response = api_instance.add_members_to_shared_line_group(shared_line_group_id, body=body) pprint(api_response) except ApiException as e: print("Exception when calling PhoneSharedLineGroupsApi->add_members_to_shared_line_group: %s\n" % e) ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **shared_line_group_id** | **str**| Unique Identifier of the shared line group. | **body** | [**Body186**](Body186.md)| | [optional] ### Return type **object** ### Authorization [OAuth](../README.md#OAuth) ### HTTP request headers - **Content-Type**: application/json, multipart/form-data - **Accept**: application/json, application/xml [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **assign_phone_numbers_slg** > assign_phone_numbers_slg(shared_line_group_id, body=body) Assign Phone Numbers Use this API to assign phone numbers to a shared line groups. These direct phone numbers will be shared among members of the [shared line group](https://support.zoom.us/hc/en-us/articles/360038850792-Setting-up-shared-line-groups). **Prerequisties:** <br> * Pro or higher account with Zoom Phone license. * A valid Shared Line Group * Account owner or admin privileges **Scopes:** `phone:write:admin` **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Light` ### Example ```python from __future__ import print_function import time import swagger_client from swagger_client.rest import ApiException from pprint import pprint # Configure OAuth2 access token for authorization: OAuth configuration = swagger_client.Configuration() configuration.access_token = 'YOUR_ACCESS_TOKEN' # create an instance of the API class api_instance = swagger_client.PhoneSharedLineGroupsApi(swagger_client.ApiClient(configuration)) shared_line_group_id = 'shared_line_group_id_example' # str | Unique Identifier of the Shared Line Group. body = swagger_client.Body188() # Body188 | (optional) try: # Assign Phone Numbers api_instance.assign_phone_numbers_slg(shared_line_group_id, body=body) except ApiException as e: print("Exception when calling PhoneSharedLineGroupsApi->assign_phone_numbers_slg: %s\n" % e) ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **shared_line_group_id** | **str**| Unique Identifier of the Shared Line Group. | **body** | [**Body188**](Body188.md)| | [optional] ### Return type void (empty response body) ### Authorization [OAuth](../README.md#OAuth) ### HTTP request headers - **Content-Type**: application/json, multipart/form-data - **Accept**: Not defined [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **delete_a_member_slg** > delete_a_member_slg(shared_line_group_id, member_id) Unassign a Member From a Shared Line Group Members of the [shared line group](https://support.zoom.us/hc/en-us/articles/360038850792) have access to the group's phone number and voicemail. Use this API to unassign **a specific member** from a Shared Line Group. **Prerequisties:** <br> * Pro or higher account with Zoom Phone license. * A valid Shared Line Group * Account owner or admin privileges **Scopes:** `phone:write:admin` **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Light` ### Example ```python from __future__ import print_function import time import swagger_client from swagger_client.rest import ApiException from pprint import pprint # Configure OAuth2 access token for authorization: OAuth configuration = swagger_client.Configuration() configuration.access_token = 'YOUR_ACCESS_TOKEN' # create an instance of the API class api_instance = swagger_client.PhoneSharedLineGroupsApi(swagger_client.ApiClient(configuration)) shared_line_group_id = 'shared_line_group_id_example' # str | Unique Identifier of the shared line group from which you would like to remove a member. member_id = 'member_id_example' # str | Unique identifier of the member who is to be removed. try: # Unassign a Member From a Shared Line Group api_instance.delete_a_member_slg(shared_line_group_id, member_id) except ApiException as e: print("Exception when calling PhoneSharedLineGroupsApi->delete_a_member_slg: %s\n" % e) ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **shared_line_group_id** | **str**| Unique Identifier of the shared line group from which you would like to remove a member. | **member_id** | **str**| Unique identifier of the member who is to be removed. | ### Return type void (empty response body) ### Authorization [OAuth](../README.md#OAuth) ### HTTP request headers - **Content-Type**: Not defined - **Accept**: Not defined [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **delete_a_phone_number_slg** > delete_a_phone_number_slg(shared_line_group_id, phone_number_id) Unassign a Phone Number Use this API to unassign a specific phone number that was assigned to the [shared line group](https://support.zoom.us/hc/en-us/articles/360038850792-Setting-up-shared-line-groups). **Prerequisties:** <br> * Pro or higher account with Zoom Phone license. * A valid Shared Line Group * Account owner or admin privileges **Scopes:** `phone:write:admin` **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Light` ### Example ```python from __future__ import print_function import time import swagger_client from swagger_client.rest import ApiException from pprint import pprint # Configure OAuth2 access token for authorization: OAuth configuration = swagger_client.Configuration() configuration.access_token = 'YOUR_ACCESS_TOKEN' # create an instance of the API class api_instance = swagger_client.PhoneSharedLineGroupsApi(swagger_client.ApiClient(configuration)) shared_line_group_id = 'shared_line_group_id_example' # str | Unique identifier of the shared line group from which you would like to unassign a phone number. phone_number_id = 'phone_number_id_example' # str | Unique identifier of the phone number which is to be unassigned. This can be retrieved from Get a Shared Line Group API. try: # Unassign a Phone Number api_instance.delete_a_phone_number_slg(shared_line_group_id, phone_number_id) except ApiException as e: print("Exception when calling PhoneSharedLineGroupsApi->delete_a_phone_number_slg: %s\n" % e) ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **shared_line_group_id** | **str**| Unique identifier of the shared line group from which you would like to unassign a phone number. | **phone_number_id** | **str**| Unique identifier of the phone number which is to be unassigned. This can be retrieved from Get a Shared Line Group API. | ### Return type void (empty response body) ### Authorization [OAuth](../README.md#OAuth) ### HTTP request headers - **Content-Type**: Not defined - **Accept**: Not defined [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **delete_a_shared_line_group** > object delete_a_shared_line_group(shared_line_group_id) Delete a Shared Line Group A [shared line group](https://support.zoom.us/hc/en-us/articles/360038850792) allows Zoom Phone admins to share a phone number and extension with a group of phone users or common area phones. Use this API to delete a Shared Line Group. **Prerequisties:** <br> * Pro or higher account with Zoom Phone license. * Account owner or admin privileges **Scopes:** `phone:write:admin` **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Light` ### Example ```python from __future__ import print_function import time import swagger_client from swagger_client.rest import ApiException from pprint import pprint # Configure OAuth2 access token for authorization: OAuth configuration = swagger_client.Configuration() configuration.access_token = 'YOUR_ACCESS_TOKEN' # create an instance of the API class api_instance = swagger_client.PhoneSharedLineGroupsApi(swagger_client.ApiClient(configuration)) shared_line_group_id = 'shared_line_group_id_example' # str | Unique Identifier of the shared line group that you would like to delete. try: # Delete a Shared Line Group api_response = api_instance.delete_a_shared_line_group(shared_line_group_id) pprint(api_response) except ApiException as e: print("Exception when calling PhoneSharedLineGroupsApi->delete_a_shared_line_group: %s\n" % e) ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **shared_line_group_id** | **str**| Unique Identifier of the shared line group that you would like to delete. | ### Return type **object** ### Authorization [OAuth](../README.md#OAuth) ### HTTP request headers - **Content-Type**: Not defined - **Accept**: application/json, application/xml [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **delete_members_of_slg** > object delete_members_of_slg(shared_line_group_id) Unassign Members of a Shared Line Group Members of the [shared line group](https://support.zoom.us/hc/en-us/articles/360038850792) have access to the group's phone number and voicemail. Use this API to unassign **all** the existing members from a Shared Line Group. **Prerequisties:** <br> * Pro or higher account with Zoom Phone license. * A valid Shared Line Group * Account owner or admin privileges **Scopes:** `phone:write:admin` **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Light` ### Example ```python from __future__ import print_function import time import swagger_client from swagger_client.rest import ApiException from pprint import pprint # Configure OAuth2 access token for authorization: OAuth configuration = swagger_client.Configuration() configuration.access_token = 'YOUR_ACCESS_TOKEN' # create an instance of the API class api_instance = swagger_client.PhoneSharedLineGroupsApi(swagger_client.ApiClient(configuration)) shared_line_group_id = 'shared_line_group_id_example' # str | Unique identifier of the Shared Line Group that you would like to delete. try: # Unassign Members of a Shared Line Group api_response = api_instance.delete_members_of_slg(shared_line_group_id) pprint(api_response) except ApiException as e: print("Exception when calling PhoneSharedLineGroupsApi->delete_members_of_slg: %s\n" % e) ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **shared_line_group_id** | **str**| Unique identifier of the Shared Line Group that you would like to delete. | ### Return type **object** ### Authorization [OAuth](../README.md#OAuth) ### HTTP request headers - **Content-Type**: Not defined - **Accept**: application/json, application/xml [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **get_a_shared_line_group** > InlineResponse20099 get_a_shared_line_group(shared_line_group_id) Get a Shared Line Group A [shared line group](https://support.zoom.us/hc/en-us/articles/360038850792) allows Zoom Phone admins to share a phone number and extension with a group of phone users or common area phones. This gives members of the shared line group access to the group's direct phone number and voicemail. Use this API to list all the Shared Line Groups. **Prerequisties:** <br> * Pro or higher account with Zoom Phone license. * Account owner or admin privileges **Scopes:** `phone:read:admin` or `phone:write:admin` **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Light` ### Example ```python from __future__ import print_function import time import swagger_client from swagger_client.rest import ApiException from pprint import pprint # Configure OAuth2 access token for authorization: OAuth configuration = swagger_client.Configuration() configuration.access_token = 'YOUR_ACCESS_TOKEN' # create an instance of the API class api_instance = swagger_client.PhoneSharedLineGroupsApi(swagger_client.ApiClient(configuration)) shared_line_group_id = 'shared_line_group_id_example' # str | Unique Identifier of the Shared Line Group. try: # Get a Shared Line Group api_response = api_instance.get_a_shared_line_group(shared_line_group_id) pprint(api_response) except ApiException as e: print("Exception when calling PhoneSharedLineGroupsApi->get_a_shared_line_group: %s\n" % e) ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **shared_line_group_id** | **str**| Unique Identifier of the Shared Line Group. | ### Return type [**InlineResponse20099**](InlineResponse20099.md) ### Authorization [OAuth](../README.md#OAuth) ### HTTP request headers - **Content-Type**: Not defined - **Accept**: application/json, application/xml [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **update_a_shared_line_group** > object update_a_shared_line_group(shared_line_group_id, body=body) Update a Shared Line Group A [shared line group](https://support.zoom.us/hc/en-us/articles/360038850792) allows Zoom Phone admins to share a phone number and extension with a group of phone users or common area phones. This gives members of the shared line group access to the group's direct phone number and voicemail. Use this API to update information of a Shared Line Group. **Prerequisties:** <br> * Pro or higher account with Zoom Phone license. * Account owner or admin privileges **Scopes:** `phone:write:admin` **[Rate Limit Label](https://marketplace.zoom.us/docs/api-reference/rate-limits#rate-limits):** `Light` ### Example ```python from __future__ import print_function import time import swagger_client from swagger_client.rest import ApiException from pprint import pprint # Configure OAuth2 access token for authorization: OAuth configuration = swagger_client.Configuration() configuration.access_token = 'YOUR_ACCESS_TOKEN' # create an instance of the API class api_instance = swagger_client.PhoneSharedLineGroupsApi(swagger_client.ApiClient(configuration)) shared_line_group_id = 'shared_line_group_id_example' # str | Unique identifier of the shared line group that is to be updated. body = swagger_client.Body184() # Body184 | (optional) try: # Update a Shared Line Group api_response = api_instance.update_a_shared_line_group(shared_line_group_id, body=body) pprint(api_response) except ApiException as e: print("Exception when calling PhoneSharedLineGroupsApi->update_a_shared_line_group: %s\n" % e) ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **shared_line_group_id** | **str**| Unique identifier of the shared line group that is to be updated. | **body** | [**Body184**](Body184.md)| | [optional] ### Return type **object** ### Authorization [OAuth](../README.md#OAuth) ### HTTP request headers - **Content-Type**: application/json, multipart/form-data - **Accept**: application/json, application/xml [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
Java
UTF-8
2,079
2.078125
2
[]
no_license
package ru.st.selenium.elements; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.NoAlertPresentException; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class Homework2 { FirefoxDriver wd; @BeforeMethod public void setUp() throws Exception { DesiredCapabilities caps = DesiredCapabilities.firefox(); caps.setCapability("nativeEvents", false); wd = new FirefoxDriver(caps); } @Test public void homework2() { String url = "http://demos.telerik.com/aspnet-ajax/webmail/default.aspx"; wd.get(url); PageFactory.initElements(wd, this); List <WebElement> folders = wd.findElements(By.xpath("/html/body/form/div[4]/div/table/tbody/tr[2]/td/div/div/div/table/tbody/tr/td/div/div/div/table/tbody/tr/td/div/div[3]/ul/li/ul/li[3]/ul/li/div/span[2]")); for (WebElement folder : folders){ new WebDriverWait (wd,30).until(ExpectedConditions.presenceOfElementLocated(By.id("subject"))); folder.click(); new WebDriverWait (wd,30).until(ExpectedConditions.stalenessOf(wd.findElement(By.id("ctl00_ContentPlaceHolder2_RadGrid1_ctl00")))); new WebDriverWait (wd,30).until(ExpectedConditions.presenceOfElementLocated(By.id("ctl00_ContentPlaceHolder2_RadGrid1_ctl00"))); } } @AfterMethod public void tearDown() { wd.close(); } public static boolean isAlertPresent(FirefoxDriver wd) { try { wd.switchTo().alert(); return true; } catch (NoAlertPresentException e) { return false; } } }
Java
UTF-8
1,693
2.96875
3
[]
no_license
package javacollections.maintask.electricalAppliances; import javacollections.maintask.specifications.EnergyConsumptionClass; import javacollections.maintask.specifications.Execution; public class CookingFoodAppliances extends Appliance { private EnergyConsumptionClass energyConsumptionClass; private Execution execution; public CookingFoodAppliances(String model, String brand, long weight, int powerConsumption, EnergyConsumptionClass energyConsumptionClass, Execution execution) { super(model, brand, weight, powerConsumption); this.energyConsumptionClass = energyConsumptionClass; this.execution = execution; } public EnergyConsumptionClass getEnergyConsumptionClass() { return energyConsumptionClass; } public Execution getExecution() { return execution; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CookingFoodAppliances that = (CookingFoodAppliances) o; if (energyConsumptionClass != that.energyConsumptionClass) return false; return execution == that.execution; } @Override public int hashCode() { int result = energyConsumptionClass != null ? energyConsumptionClass.hashCode() : 0; result = 31 * result + (execution != null ? execution.hashCode() : 0); return result; } @Override public String toString() { return super.toString().replaceAll("}", ", energyConsumptionClass=" + energyConsumptionClass + ", execution=" + execution + '}'); } }
Markdown
UTF-8
2,874
2.828125
3
[ "MIT" ]
permissive
--- title: Classroom Audio author: 'kurtis' date: '2015-06-08' slug: classroom-audio categories: - Research tags: - dissertation draft: no summary: image: caption: '' focal_point: '' --- The research team recorded an entire week's worth of class meetings of three courses at four times during the course of the semester. These class meetings were recorded in video from four different angles. This resulted in a very large amount of data (approximately 200 hours of raw video) requiring about 1 Terabyte (1,000 Gigabytes) of storage space. The audio portion of the video was also rendered out and compressed into MP3 format files for ease of use and analysis when research questions can be answered without video. ## Cleaning Classroom Audio The resulting MP3 files were much easier to process and store, but audio quality, which was lacking in the original raw video, still needed to be improved. In order to make the recording process unobtrusive, the cameras and microphones were installed at the ceiling in a large classroom. As a result, classroom audio recordings included a large amount of mid-frequency noise from building electrical and mechanical systems. This noise made it difficult to discern what individuals were saying on the recording. In order to improve the quality of the classroom audio, I first equalized audio to remove reduce the volume of sounds at frequencies above and below those typical of speech. Frequencies below 1,000 Hz and above 7,000 Hz were reduced by 20 dB. Frequencies between 1,000 Hz and 7,000 Hz were reduced according to a generally bell-shaped curve centered near 2,800 Hz. Once audio had been equalized to focus on speech, the next priority was to reduce hissing, humming, and other constant noises which helped to mask speech. I used a noise removal tool integrated into the [Audacity] software package (v. 2.0.6). After selecting a noise profile for each track, I reduced noise by 48 dB on each recording (with a sensitivity of -1.00 dB and attack/decay of 0.20 seconds, utilizing a frequency smoothing window of 250 Hz). Finally, I converted each recording from a stereo recording to a mono recording and combined the recording for each camera – four total – into a single file, synchronized and balanced the audio sources, and exported the audio into a cleaned MP3 format audio file. This effort resulted in a noticeable increase in intelligibility and reduction in recording artifacts, especially loud, high- and low-frequency pops and bangs which had limited the listening volume of the recordings. ## Selecting Classroom Audio The classroom audio used for this dissertation come from the first week of classes because this is the time period where the highest amount of socialization of new organizational members (the students) typically occurs. <!-- References --> [Audacity]: web.audacityteam.org
Java
UTF-8
506
1.921875
2
[]
no_license
package com.aaa.dao;/* */ import com.aaa.entity.SysMenuPath; import java.util.List; public interface SysMenuPathDao { //查询资源详情,路径对应的操作 List<SysMenuPath> findSysMenu(); //添加资源路径 Integer addPath(SysMenuPath sysMenuPath); //删除资源路径 Integer deletePath(Integer id); //查询资源是否重复 SysMenuPath findMenuPathByUrl(Integer id,String pathurl); //修改资源 Integer updPath(SysMenuPath sysMenuPath); }
C++
UTF-8
1,729
3.15625
3
[ "Apache-2.0" ]
permissive
class Solution { public: int canCompleteCircuit(vector<int>& gas, vector<int>& cost) { int curGas = 0; for (int i = 0, j = -1; i < gas.size(); i++){ if (gas[i] < cost[i]) continue; curGas = gas[i] - cost[i]; for (j = i + 1; j != i; j++){ if (j == gas.size()){ j = 0; if (j == i) return i; } curGas = curGas + gas[j] - cost[j]; if (curGas < 0) break; } if (j == i) return i; } return -1; } }; // more compact version class Solution { public: int canCompleteCircuit(vector<int>& gas, vector<int>& cost) { int curGas = 0; for (int i = 0, j = -1; i < gas.size(); i++){ if (gas[i] < cost[i]) continue; curGas = gas[i] - cost[i]; for (j = (i + 1) % gas.size(); j != i; j = ++j % gas.size()){ // Use % as it is a circle curGas = curGas + gas[j] - cost[j]; if (curGas < 0) break; } if (j == i) return i; } return -1; } }; Class Solution { public: int canCompleteCircuit(vector<int>& gas, vector<int>& cost) { int tankGas = 0, totalGas = 0, start = 0; for (int i = 0; i < gas.size(); i++) { tankGas += gas[i] - cost[i]; totalGas += gas[i] - cost[i]; if (tankGas < 0) { start = i + 1; tankGas = 0; } } return totalGas < 0 ? -1 : start; } }
C
UTF-8
457
3.9375
4
[]
no_license
#include <unistd.h> #include <stdio.h> void ft_ultimate_div_mod(int *a, int *b); int main(void) { int a; int b; a = 10; b = 5; ft_ultimate_div_mod(&a, &b); printf("a, divided: %i\n", a); printf("b, modulated: %i\n", b); return (0); } void ft_ultimate_div_mod(int *a, int *b) { int divided; int modulated; divided = *a / *b; modulated = *a % *b; *a = divided; *b = modulated; return ; }
C++
UTF-8
3,253
3.0625
3
[]
no_license
// // Created by user on 03.12.18. // #include <fstream> #include "MatrixMultiplier2.h" MatrixMultiplier2::MatrixMultiplier2( char *filenameA, char *filenameB, int num_threads_, char *filenameC_) : num_threads(num_threads_), filenameC(filenameC_) { try { read_MatrixA(filenameA); read_MatrixB(filenameB); MatrixC = new double*[nA]; for (int i = 0; i < nA; i++) { MatrixC[i] = new double[kB]; } } catch (std::bad_alloc &error) { throw; } } void MatrixMultiplier2::delete_matrix(double ***Matrix, int n) { try{ for (int i = 0; i < n; i++) { delete[] (*Matrix)[i]; } delete[] (*Matrix); } catch (...) { throw ; } } void MatrixMultiplier2::read_MatrixA( char *fileName) { std::ifstream myfile; myfile.open(fileName, std::ifstream::binary); myfile.read(const_cast<char *>(reinterpret_cast<const char*>(&nA)), sizeof(nA)); myfile.read(const_cast<char *>(reinterpret_cast<const char*>(&kA)), sizeof(kA)); MatrixA = new double*[nA]; for(int i = 0; i < nA; i++) { MatrixA[i] = new double[kA]; } for (size_t i = 0; i < nA; i++) { for (size_t j = 0; j < kA; j++) { double a = 0; myfile.read(const_cast<char *>(reinterpret_cast<const char*>(&a)), sizeof(double)); MatrixA[i][j] = a; } } myfile.close(); } void MatrixMultiplier2::read_MatrixB( char *fileName) { std::ifstream myfile; myfile.open(fileName, std::ifstream::binary); myfile.read(const_cast<char *>(reinterpret_cast<const char*>(&nB)), sizeof(nB)); myfile.read(const_cast<char *>(reinterpret_cast<const char*>(&kB)), sizeof(kB)); MatrixB = new double*[nB]; for(int i = 0; i < nB; i++) { MatrixB[i] = new double[kB]; } for (size_t i = 0; i < nB; i++) { for (size_t j = 0; j < kB; j++) { double a = 0; myfile.read(const_cast<char *>(reinterpret_cast<const char*>(&a)), sizeof(double)); MatrixB[i][j] = a; } } myfile.close(); } void MatrixMultiplier2::write_matrix( char *filename, double **Matrix, int n, int k) { std::ofstream file; file.open(filename); file << n << " " << k << "\n"; for (int i = 0; i < n; i++) { for (int j = 0; j < k; j++) { file << Matrix[i][j] << " "; } file << std::endl; } file.close(); } void MatrixMultiplier2::multiply() { //#pragma omp parallel for collapse(2) num_threads(num_threads) for (int i = 0; i < nA; i++) { for (int j = 0; j < kB; j++) { MatrixC[i][j] = 0; for (int k = 0; k < kA; k++) { MatrixC[i][j] += MatrixA[i][k] * MatrixB[k][j]; } } } } MatrixMultiplier2::~MatrixMultiplier2() { delete_matrix(&MatrixA, nA); delete_matrix(&MatrixB, nB); delete_matrix(&MatrixC, nA); } void MatrixMultiplier2::show() { write_matrix(filenameC, MatrixC, nA, kB); } void MatrixMultiplier2::writeTo(double **Matrix) { for (int i = 0; i < nA; i++) { for (int j = 0; j < kB; j++) { Matrix[i][j] = MatrixC[i][j]; } } }
Java
UTF-8
3,301
2.625
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Controle; import GUI.Desenvolvedor.JanelaTexto; import java.awt.Component; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.ArrayList; import javax.swing.JOptionPane; /** * * @author Bruno */ public class ControladoraAjuda { ControladoraIdioma idioma; public ControladoraAjuda() { idioma = ControladoraIdioma.getInstancia(); } public void ExibirAjuda(Component source, String arquivoAjuda) { try { String idiomaAtual = idioma.getIdiomaAtual(); File arquivo = new File("Arquivos/Ajuda/" + idiomaAtual + "/" + arquivoAjuda + ".txt"); FileReader fileReader = new FileReader(arquivo); BufferedReader bufferedReader = new BufferedReader(fileReader); ArrayList<String> conteudoArquivo = new ArrayList<>(); String linha = ""; while ((linha = bufferedReader.readLine()) != null) { conteudoArquivo.add(linha); } fileReader.close(); bufferedReader.close(); JanelaTexto jt = new JanelaTexto(conteudoArquivo); jt.setLocationRelativeTo(source); jt.setVisible(true); } catch (Exception e) { String mensagem = idioma.Valor("msgErroAoAbrirArquivo") + ": " + e.getMessage(); JOptionPane.showMessageDialog(null, mensagem, idioma.Valor("aviso"), JOptionPane.OK_OPTION); e.printStackTrace(); } } public void ManualUtilizacao(Component source) { try { String idiomaAtual = idioma.getIdiomaAtual(); ArrayList<String> conteudoDosArquivos = new ArrayList<>(); File file = new File("Arquivos/Ajuda/" + idiomaAtual); File arquivos[] = file.listFiles(); for (File arquivoAjuda : arquivos) { FileReader fileReader = new FileReader(arquivoAjuda); BufferedReader bufferedReader = new BufferedReader(fileReader); String linha = ""; while ((linha = bufferedReader.readLine()) != null) { conteudoDosArquivos.add(linha); } fileReader.close(); bufferedReader.close(); conteudoDosArquivos.add(""); conteudoDosArquivos.add(""); } conteudoDosArquivos.add(""); conteudoDosArquivos.add(""); conteudoDosArquivos.add(idioma.Valor("mensagemManualParte1")); conteudoDosArquivos.add(""); conteudoDosArquivos.add(idioma.Valor("mensagemManualParte2")); conteudoDosArquivos.add(""); JanelaTexto jt = new JanelaTexto(conteudoDosArquivos); jt.setLocationRelativeTo(source); jt.setVisible(true); } catch (Exception e) { String mensagem = idioma.Valor("msgErroAoAbrirArquivo") + ": " + e.getMessage(); JOptionPane.showMessageDialog(null, mensagem, idioma.Valor("aviso"), JOptionPane.OK_OPTION); e.printStackTrace(); } } }
JavaScript
UTF-8
326
3.859375
4
[]
no_license
var num = Math.floor(Math.random() * 101); function guessnum(){ var guess = document.forms['form1'].num.value; if (guess == num) { alert("Great you Guessed! How did you know that?"); } if (guess < num) { alert("No your number is too low!"); } if (guess > num) { alert("No your number is too high"); } }
Markdown
UTF-8
1,196
2.515625
3
[]
no_license
## space2vec: Model Code Check our the posts here: [space2vec.com](http://space2vec.com) The project behind the code is talked about in detail throughout the blog posts. But this is where the cool code stuff happens! ## Data You can find the feature engineered CSV from the autoscan project (under the "Features" heading) site here: [http://portal.nersc.gov/project/dessn/autoscan/](http://portal.nersc.gov/project/dessn/autoscan/) ## Environment We have supplied requirements.txt file which you can use to setup the right environment. This was made for Python 3.6, so if you are getting errors about missing versions or something similar try removing anything after the "==" for that library in the requirements.txt and run again. ## Posts ### Week 2: building a baseline model See [/xgboost-baseline](https://github.com/pippinlee/space2vec-ml-code/tree/master/building-baseline-model) for code We pickled the feature engineered data for our above model, you can find the data here: [https://drive.google.com/open?id=1Pa4-imVbK7yfZuCX3mfF-mMae1eyhQqo](https://drive.google.com/open?id=1Pa4-imVbK7yfZuCX3mfF-mMae1eyhQqo) ###### Maintained by Pippin Lee (p.lee@dessa.com) and Cole Clifford (c.clifford@dessa.com)
Java
UTF-8
2,389
2.34375
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.infineon.infohub.sap.excel.model; import java.io.Serializable; /** * * @author Raaj */ public class SapTechnincal implements Serializable { private String messageType; private String messageCode; private String partnerNo; private Direction type; public SapTechnincal(SapExcelType type) { if(type == SapExcelType.Invalid || type == SapExcelType.Customer) throw new IllegalArgumentException("This sap excel is not tecnical file"); if (type == SapExcelType.PC1In || type == SapExcelType.PIFin) { this.type = Direction.Inbound; }else{ this.type = Direction.Outbound; } } public String getMessageType() { return messageType; } public void setMessageType(String messageType) { this.messageType = messageType; } public String getMessageCode() { return messageCode; } public void setMessageCode(String messageCode) { if (messageCode.length() < 3) { this.messageCode = ("000" + messageCode).substring(messageCode.length()); } else { this.messageCode = messageCode; } } public String getPartnerNo() { return partnerNo; } public void setPartnerNo(String partnerNo) { if (partnerNo.length() < 10) { this.partnerNo = ("0000000000" + partnerNo).substring(partnerNo.length()); } else { this.partnerNo = partnerNo; } } public Direction getType() { return type; } public void setType(Direction type) { this.type = type; } @Override public String toString() { return "SapTechnincal{" + " partnerNo=" + partnerNo + ", messageType=" + messageType + ", messageCode=" + messageCode + ", type=" + type + '}'; } public String getPartnerTechical() { return this.type + "IDOC-" + this.messageType + (this.messageCode == null ? "" : "-"+messageCode); } public String getTechTerms() { return "IDOC-" + this.messageType +(this.messageCode == null ? "" : "-"+messageCode); } }
Java
UTF-8
5,280
1.867188
2
[]
no_license
package com.accessorydm.filetransfer.action; import com.accessorydm.XDMDmUtils; import com.accessorydm.adapter.XDMInitAdapter; import com.accessorydm.agent.fota.XFOTADl; import com.accessorydm.db.file.XDB; import com.accessorydm.db.file.XDBFumoAdp; import com.accessorydm.eng.core.XDMEvent; import com.accessorydm.eng.core.XDMMsg; import com.accessorydm.interfaces.XDMAccessoryInterface; import com.accessorydm.interfaces.XFOTAInterface; import com.accessorydm.interfaces.XUIEventInterface; import com.accessorydm.postpone.PostponeManager; import com.accessorydm.ui.progress.XUIProgressModel; import com.samsung.accessory.fotaprovider.AccessoryController; import com.samsung.accessory.fotaprovider.controller.ConsumerInfo; import com.samsung.accessory.fotaprovider.controller.RequestController; import com.samsung.accessory.fotaprovider.controller.RequestError; import com.samsung.android.fotaprovider.log.Log; import java.io.File; import java.util.Locale; public final class CopyDelta extends FileTransferAction { /* access modifiers changed from: package-private */ public boolean checkPrecondition() { XDMDmUtils.getInstance().xdmSetWaitWifiConnectMode(0); PostponeManager.cancelPostpone(); XFOTADl.xfotaCopySetDrawingPercentage(true); XDBFumoAdp.xdbSetFUMOStatus(250); XDMMsg.xdmSendUIMessage(XUIEventInterface.DL_UIEVENT.XUI_DL_COPY_IN_PROGRESS, Long.valueOf(XDBFumoAdp.xdbGetObjectSizeFUMO()), (Object) null); if (!AccessoryController.getInstance().getConnectionController().isConnected()) { Log.W("Device connection is not ready"); failedCopyProcess(); return false; } else if (!AccessoryController.getInstance().getRequestController().isInProgress()) { return true; } else { Log.W("Accessory is in progress"); return false; } } /* access modifiers changed from: package-private */ public void controlAccessory() { Log.I(""); File file = new File(XDB.xdbFileGetNameFromCallerID(XDB.xdbGetFileIdFirmwareData())); Log.I(file.getName()); if (!file.exists()) { Log.W("file is not existed"); failedCopyProcess(); return; } AccessoryController.getInstance().getRequestController().sendPackage(file.getPath(), new RequestController.RequestCallback.Result() { public void onSuccessAction(ConsumerInfo consumerInfo) { Log.I("copyDelta succeeded"); CopyDelta.this.completeCopyProcess(); } public void onFailure(RequestError requestError) { Log.W("copyDelta failed"); if (requestError != null) { Log.W("error: " + requestError); if (requestError == RequestError.ERROR_LOW_MEMORY) { Log.W("Low Memory by Socket"); FileTransferFailure.handleLowMemory(XDMAccessoryInterface.XDMAccessoryCheckState.XDM_ACCESSORY_CHECK_COPY); return; } } CopyDelta.this.failedCopyProcess(); } }, new RequestController.RequestCallback.FileTransfer() { public void onFileTransferStart() { Log.I("Copying Progress Reset"); CopyDelta.this.updateCopyProgress(0); } public void onFileProgress(int i) { Log.I(String.format(Locale.US, "Copying Percentage:%d%%", new Object[]{Integer.valueOf(i)})); CopyDelta.this.updateCopyProgress(i); } }); Log.I("Start to transfer delta package!"); } /* access modifiers changed from: private */ public void updateCopyProgress(int i) { XUIProgressModel.getInstance().updateProgressInfoForCopy(i); } /* access modifiers changed from: private */ public void completeCopyProcess() { XFOTADl.xfotaCopySetDrawingPercentage(false); XDBFumoAdp.xdbSetFUMOCopyRetryCount(0); XDB.xdbAdpDeltaAllClear(); XDBFumoAdp.xdbSetFUMOStatus(251); XUIProgressModel.getInstance().initializeProgress(); XDMEvent.XDMSetEvent((Object) null, XUIEventInterface.DL_UIEVENT.XUI_DL_UPDATE_CONFIRM); } /* access modifiers changed from: private */ public void failedCopyProcess() { Log.I(""); int xdbGetFUMOCopyRetryCount = XDBFumoAdp.xdbGetFUMOCopyRetryCount() + 1; XFOTADl.xfotaCopySetDrawingPercentage(false); if (xdbGetFUMOCopyRetryCount >= 3) { XUIProgressModel.getInstance().initializeProgress(); XDBFumoAdp.xdbSetFUMOCopyRetryCount(0); XDMInitAdapter.xdmAccessoryUpdateResultSetAndReport(XFOTAInterface.XFOTA_GENERIC_SAP_COPY_FAILED); XDB.xdbAdpDeltaAllClear(); XDMEvent.XDMSetEvent((Object) null, XUIEventInterface.ACCESSORY_UIEVENT.XUI_DM_ACCESSORY_COPY_FAILED); return; } XUIProgressModel.getInstance().initializeProgress(); XDBFumoAdp.xdbSetFUMOCopyRetryCount(xdbGetFUMOCopyRetryCount); XDMEvent.XDMSetEvent((Object) null, XUIEventInterface.ACCESSORY_UIEVENT.XUI_DM_ACCESSORY_COPY_RETRY_LATER); } }
Markdown
UTF-8
2,012
3.375
3
[]
no_license
### 题目描述 SORT 公司是一个专门为人们提供排序服务的公司,该公司的宗旨是「顺序是最美丽的」。 为了把工厂中高低不等的物品按从低到高排好序,工程师发明了一种排序机械臂。 它遵循一个简单的排序规则,第一次操作找到高度最低的物品的位置P<sub>1</sub>,并把左起第一个物品至P<sub>1</sub>间的物品(即区间[1,P<sub>1</sub>]间的物品)反序;第二次找到第二低的物品的位置P<sub>2</sub>,并把左起第二个至P<sub>2</sub>间的物品(即区间[2,P<sub>2</sub>]间的物品)反序……最终所有的物品都会被排好序。 <p align=""> <img src="http://mooctest-code.oss-cn-shanghai.aliyuncs.com/static/media/%E6%8E%92%E5%BA%8F%E6%9C%BA%E6%A2%B0%E8%87%82.png" alt="Sample" width="500" height="120"> </p> 上图给出有六个物品的示例,第一次操作前,高度最低的物品在位置4,于是把第一至第四的物品反序;第二次操作前,第二低的物品在位罝六,于是把第二至六的物品反序…… 你的任务便是编写一个程序,确定一个操作序列,即每次操作前第i低的物品所在位置P<sub>i</sub>,以便机械臂工作。需要注意的是,如果有高度相同的物品,必须保证排序后它们的相对位置关系与初始时相同。 ### 输入描述 ``` 输入共两行,第一行为一个整数N,N表示物品的个数。 第二行为N个用空格隔开的正整数,表示N个物品最初排列的编号 ``` ### 输出描述 输出共一行,N个用空格隔开的正整数P<sub>1</sub>,P<sub>2</sub>,...,P<sub>n</sub>,P<sub>i</sub>表示第i次操作前第i小的物品所在的位置。 注意:如果第i次操作前,第i小的物品己经在正确的位置P<sub>i</sub>上,我们将区间[P<sub>i</sub>,P<sub>i</sub>]反转 (单个物品)。 ### 测试样例 #### 样例1:输入-输出-解释 ``` 6 3 4 5 1 6 2 ``` ``` 4 6 4 5 6 6 ``` ### 题目来源 `CQOI`
Markdown
UTF-8
1,521
3.453125
3
[ "MIT" ]
permissive
--- layout: page title: Ruby Exception category: 技术 tags: Ruby --- {% include JB/setup %} ## C时代的异常处理 由于C没有异常处理机制,所以只能通过返回值来判断是否存在异常。 这种方式有两个弊端: - 遗漏会出现异常的点 - 如果面面俱到,则错误处理代码可能会淹没正常的业务代码 ## Ruby的异常处理 在Ruby中,我们用raise方法来创建一个表示异常的对象。 raise有四种使用方法: - raise 产生一个错误信息为空的RuntimeError(default for raise) - raise "Exception" 产生一个错误信息为"Exception"的RuntimeError - raise TypeError, "Exception" 产生一个错误信息为"Exception"的TypeError - raise TypeError, "Exception", arr 产生一个错误信息为"Exception"的TypeError,arr保存backtrace信息 通过rescue可以捕获Exception 如果rescue后面没有跟参数,则默认捕获StandardError.(所以,如果想自定义Exception,一般继承StandardError比较合适) 在block中raise的最近一次的error会保存在$!全局变量中。在rescue中,通过比较parameter === $!(===除了表示通常的==的含义,也表示当后面的参数为前面参数或其子类的实例..., 则判断为true;或者说,前面的参数为后面的类或者父类..., 则判断为true) 来判断是否应该捕获此异常(如果没有parameter则默认为StandardError) 如果rescue后面的parameter是raised exception的class或者superclass,则匹配成功。
Java
UTF-8
1,642
2.15625
2
[]
no_license
package com.ecolemultimedia.sabermostaf.projet2.cells; import android.content.Context; import android.graphics.Typeface; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.ecolemultimedia.sabermostaf.projet2.R; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; public class CellDrawerChild extends RelativeLayout { private TextView ui_tx_title_sub_cat = null; private LayoutInflater layoutInflater = null; private Context m_context = null; public CellDrawerChild(Context context) { super(context); m_context = context; layoutInflater = LayoutInflater.from(context); } public View init() { View convertView = layoutInflater.inflate(R.layout.cell_drawer_child, this); ui_tx_title_sub_cat = (TextView) convertView .findViewById(R.id.ui_tx_title_sub_cat); Typeface style = Typeface.createFromAsset(m_context.getAssets(), "corbel.otf"); ui_tx_title_sub_cat.setTypeface(style); return this; } public void reuse(String info) { cleanView(); if (info != null) { String parse=null; try { parse= URLDecoder.decode(info, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } ui_tx_title_sub_cat.setText(parse); } } public void cleanView() { ui_tx_title_sub_cat.setText(""); } }
PHP
UTF-8
4,162
2.53125
3
[]
no_license
<?php use Illuminate\Support\MessageBag; class AuthController extends Controller { public function __construct() { $this->beforeFilter('csrf', array('on' => 'post')); } public function login() { return View::make('homepage', array('title' => 'Login', 'main' => 'homepage', 'mostra_login' => true)); } public function loginHandler() { // Retrieve input $email = Input::get('email'); $senha = Input::get('senha'); $auth = new Business\Login; // Verify credentials and perform login if (!$auth->login($email, $senha)) { // If failed, redirect informing the error return Redirect::to(URL::previous()) ->with('errors', $auth->loginErrors) ->with('mostra_login', true) ->withInput(); } // If successful, redirect to intended page or dashboard return Redirect::intended('/' . (Larauth::user()->type() == 'Franquia' ? 'franquia' : 'minha-conta') . '/admin'); } public function logout() { $user = App::make('user'); if ($user) { Log::info('Logout de ' . Config::get('larauth::user_class') . ' bem-sucedido: ' . $user->email); } Larauth::logout(); return Redirect::route('home'); } public function signup() { return View::make('assine', array('title' => 'Assine', 'main' => 'assine')); } public function signupHandler() { $signup = new Business\Assinante\SignUp; // Validate and register a new user if (!$signup->register(Input::all())) { // If failed, return HTTP error code 500 return App::abort(500); } // If successful, send mail, do login and redirect to dashboard with(new Business\Email)->send('verify_email', $signup->assinante); Larauth::loginUser($signup->assinante->email); Session::flash('success', 'Bem-vindo! Enviamos um e-mail para você com um link para confirmar seu cadastro. Por favor, acesse o link para habilitar sua conta. Obrigado.'); return array('success' => true); } public function verify($code) { if (!Business\Security::checkUserSecretCode($code, $user, 'verify_email')) { return Redirect::route('home')->with('danger', 'Link de confirmação expirado ou inválido.'); } Business\Security::userSuccessfullyVerified($user); Larauth::loginUser($user->email); return Redirect::action('AssinanteController@getAdmin') ->with('success', 'O seu endereço de e-mail foi confirmado com sucesso. Obrigado.'); } public function forgotPassword() { return View::make('auth.esqueci-senha'); } public function forgotPasswordHandler() { $email = strtolower(trim(Input::get('email'))); $assinante = Assinante::whereEmail($email)->first(); if (!$assinante) { return Redirect::action('AuthController@forgotPassword') ->with('danger', 'Assinante não encontrado.') ->withInput(); } with(new Business\Email)->send('forgot_password', $assinante); $expires = Config::get('business.forgot_password_expires'); return Redirect::action('AuthController@forgotPassword') ->with('success', 'Enviamos um e-mail com um link para redefinir sua senha. <strong>Ele vale por ' . $expires . ' minutos.</strong> Por favor, utilize-o antes de expirar. Obrigado.'); } public function resetPassword($code) { if (!Business\Security::checkUserSecretCode($code, $user, 'forgot_password')) { return Redirect::route('home')->with('danger', 'Link de recuperação de senha expirado ou inválido.'); } if (Request::getMethod() == 'POST') { $input = array_filled(Input::all(), array('token', 'senha', 'confirma-senha')); $token = Session::get('rp_token'); Session::forget('rp_token'); $result = Business\Security::changePassword($user, $token, $input); if ($result === true) { Larauth::loginUser($user->email); return Redirect::action('AssinanteController@getAdmin') ->with('success', 'Sua nova senha foi salva. Você já está logado.'); } return Redirect::to(Request::fullURL())->with('danger', $result)->withInput(); } $token = Larauth::randomPassword(64, false); Session::put('rp_token', $token); return View::make('auth.recuperar-senha', array( 'title' => 'Recuperar Senha', 'token' => $token, )); } }
PHP
UTF-8
824
2.71875
3
[ "MIT" ]
permissive
<?php namespace App\Sharp\Filters; use Carbon\Carbon; use Code16\Sharp\EntityList\EntityListDateRangeRequiredFilter; class PassengerBirthdateFilter implements EntityListDateRangeRequiredFilter { public function label() { return "Born between"; } /** * @return array * * awaited format: * * [ * "start" => Carbon::yesterday(), * "end" => Carbon::today(), * ] * * @throws \Exception */ public function defaultValue() { return [ "start" => (new Carbon())->setDate(2014,1,1), "end" => (new Carbon())->setDate(2014,12,31), ]; } public function dateFormat() { return "YYYY-MM-DD"; } public function isMondayFirst() { return false; } }
Python
UTF-8
11,297
3.078125
3
[]
no_license
#!/usr/bin/python # -*- coding: utf-8 -*- import random from spacegeo import * from pylab import * class Cortex(object): def __init__(self,cell_width=3.,cell_length=15.): self.width = cell_width self.length = cell_length def isinside(self,particle): ''' returns true if the particle (a 3D array) is in the cell ''' width = self.width length = self.length right = (length - width)/2 left = - right proj = sqrt(particle[1]**2 + particle[2]**2) if proj <= width/2 and abs(particle[0]) <= right: return True elif right < abs(particle[0]) <= length/2: p = S.array([abs(particle[0]),particle[1],particle[2]]) r = S.array([right,0,0]) c = CartezPos(p-r) rho = c.norme() if rho <= width/2: return True else: return False else: return False def shape(self,scale): ''' scale is per pixel ''' width = self.width length = self.length l = int(length*1.2/scale) m = int(width*1.2/scale) n = m grid = S.zeros((l,m,n),dtype = int) for i in range(l): for j in range(m): for k in range(n): x = float((i - l/2) * scale) y = float((j - m/2) * scale) z = float((k - n/2) * scale) voxel = S.array([x,y,z]) if self.isinside(voxel): grid[i][j][k] = 1 else: grid[i][j][k] = 0 return grid def shape2D(self, scale): width = self.width length = self.length xmin = -length/2 xmax = length/2 + scale right = (length - width)/2 left = -right xaxis = S.arange(xmin, xmax, scale) yval1 = [] for x in xaxis: if abs(x) <= right: y1 = width/2 elif xmin <= x < left : y1 = sqrt((width / 2)**2 - (x - left)**2) elif right < x <= xmax : y1 = sqrt((width / 2)**2 - (x - right)**2) yval1.append(y1) yval1 = S.array(yval1) yval2 = -yval1 return (xaxis, yval1, yval2) class Nucleus(object): def __init__(self,radius = 1.5): self.radius = radius def isinside(self,particle): radius = self.radius p = CartezPos(particle) rho = p.norme() if rho < radius: return True else: return False class Fuseau(CartezPos): c = S.array([0, 1.2, 0]) def __init__(self,length=0.4,center=c, theta=0,phi=pi/2): ''' The spindle is defined by its length, the position of its center and the angles of the SPBs ''' self.length = length self.center = center self.theta = theta self.phi = phi def pos_spbs(self): ''' returns a tuple of 2 3D arrays giving the absolute positions of the SPBs ''' center = CartezPos(self.center) length = self.length theta = self.theta phi = self.phi spb1_rel = S.array([length/2,theta,phi]) spb1_rel = SpherPos(spb1_rel).cartez() spb1 = center.pos + spb1_rel spb2 = center.pos - spb1_rel return (spb1, spb2) def projection(self): pos_spbs = self.pos_spbs() spb1 = pos_spbs[0] spb2 = pos_spbs[1] spin = [spb1[0] - spb2[0], spb1[1] - spb2[1], 0] length_proj = CartezPos(spin).norme() return length_proj ## Random motion for a free spindle (no membrane) def shake(self, dt, pos_noise = 0.1): tmp = Fuseau() tmp.length = self.length ang_noise = 20 * asin(pos_noise / tmp.length) tmp.theta = self.theta + dt * random.gauss(0,ang_noise) tmp.phi = self.phi + dt * random.gauss(0,ang_noise) tmp.center[0] = self.center[0] + dt * random.gauss(0,pos_noise) tmp.center[1] = self.center[1] + dt * random.gauss(0,pos_noise) tmp.center[2] = self.center[2] + dt * random.gauss(0,pos_noise) return tmp def move(self, txelong, dt, len_noise = 0.2): tries = 0 cortex = Cortex() if self.length >= cortex.length : return 0 self.length += dt * random.gauss(txelong,len_noise) if self.length >= cortex.length : return 0 tmp = self.shake(dt = dt) inside = map(cortex.isinside,tmp.pos_spbs()) while not S.all(inside) : tmp = self.shake(dt = dt) tries += 1 inside = map(cortex.isinside,tmp.pos_spbs()) if tries > 1000: return 0 self.theta = tmp.theta self.phi = tmp.phi self.center = tmp.center return 1 ## Random motion for a rigid emi-spherical membrane def shake_fixnuc(self, dt, pos_noise = 0.1): tmp = Fuseau() tmp.length = self.length nuc = Nucleus() radius = nuc.radius ang_noise = 20 * asin(pos_noise / tmp.length) tmp.theta = self.theta + dt * random.gauss(0,ang_noise) tmp.phi = self.phi + dt * random.gauss(0,ang_noise) tmp.center = CartezPos(self.center).spherical() if tmp.length/2 > radius: radius = tmp.length / 2 rho_c = 0 theta_c = 0 phi_c = 0 else: rho_c = sqrt(nuc.radius**2 - (tmp.length**2) / 4) ang_noise_center = ( pi / 10 )* pos_noise theta_c = tmp.center[1] + dt * random.gauss(0,ang_noise_center) a = cos(self.theta - theta_c) * tan(self.phi) if abs(a) <= 1E-6: phi_c = tmp.phi + pi/2 print "a nul!!" else: phi_c = atan2(1,a) tmp.center = array([rho_c, theta_c, phi_c]) tmp.center = SpherPos(tmp.center).cartez() return tmp def move_fixnuc(self, txelong, dt, len_noise = 0.2): tries = 0 cortex = Cortex() if self.length >= cortex.length : return 0 self.length += dt * random.gauss(txelong,len_noise) if self.length >= cortex.length : return 0 tmp = self.shake_fixnuc(dt = dt) inside = map(cortex.isinside,tmp.pos_spbs()) while not S.all(inside) : tmp = self.shake_fixnuc(dt = dt) tries += 1 inside = map(cortex.isinside,tmp.pos_spbs()) if tries > 1000: print 'out!' return 0 self.theta = tmp.theta self.phi = tmp.phi self.center = tmp.center return 1 ## Random motion class CellCycle(Fuseau,Nucleus,Cortex): f = Fuseau() c = Cortex() n = Nucleus() def __init__(self,fuso = f, nuc = n, cortex = c): self.fuso = Fuseau() self.nuc = Nucleus() self.cortex = Cortex() self.trajs_spbs = [fuso.pos_spbs()] self.trajs_theta = [fuso.theta] def phase(self,tstart,tstop,dt,txelong, fixnuc = 0): cortex = self.cortex stt = int(round(tstart / dt)) stp = int(round(tstop / dt)) for i in range(stt, stp): if not fixnuc: move = self.fuso.move(txelong, dt) else: move = self.fuso.move_fixnuc(txelong, dt) if not move: break self.trajs_spbs.append(self.fuso.pos_spbs()) self.trajs_theta.append(self.fuso.theta) def cycle(self,dt, fixnuc = 0): ## taux d'élongation moyen self.txelong1 = random.gauss(0.4,0.01) #um/min self.txelong2 = random.gauss(0.2,0.01) self.txelong3 = random.gauss(0.8,0.15) ## timing des phases self.temps_1 = abs(2 + random.gauss(0,0.1)) self.temps_2 = self.temps_1 + 6 + abs(random.gauss(3,3)) self.temps_3 = self.temps_2 + 8 + random.gammavariate(3,1) ## initialisation l0 = 0.4 + random.gauss(0.4,0.01) # longueur initiale du fuseau [xc,yc,zc] = [random.gauss(0,0.1),random.gauss(1.2,0.05), random.gauss(0,0.1)] center=S.array([xc,yc,zc]) theta= random.gauss(0,pi/10) # angle initial phi = random.gauss(pi/2,pi/10) self.fuso = Fuseau(l0,center,theta,phi) self.trajs_spbs = [self.fuso.pos_spbs()] self.trajs_theta = [self.fuso.theta] tps1 = self.temps_1 tx1 = self.txelong1 tps2 = self.temps_2 tx2 = self.txelong2 tps3 = self.temps_3 tx3 = self.txelong3 self.phase(0,tps1,dt,tx1, fixnuc) self.phase(tps1,tps2,dt,tx2, fixnuc) self.phase(tps2,tps3,dt,tx3, fixnuc) trajs_spbs = S.array(self.trajs_spbs) self.spb1 = trajs_spbs[:,0,:] self.spb2 = trajs_spbs[:,1,:] p_spb1 = self.spb1[:,0:2] p_spb2 = self.spb2[:,0:2] self.length_proj = map(distance, p_spb1, p_spb2) def display(self,dt): cortex = self.cortex.shape2D(0.02) trajs_spbs = S.array(self.trajs_spbs) trajs_theta = S.array(self.trajs_theta) length_proj = S.array(self.length_proj) p_spb1 = self.spb1[:,0:2] p_spb2 = self.spb2[:,0:2] nb_frames = len(length_proj) timelapse = [] for i in range(nb_frames) : timelapse.append(i*dt) timelapse = S.array(timelapse) timelapse -= self.temps_2 figure(1) subplot(211) plot(timelapse,length_proj,'-') subplot(212) plot(timelapse,trajs_theta,'-') axis([-15,15,-1,1]) figure(2) plot(self.spb1[:,0],self.spb1[:,1],'bo-',self.spb2[:,0],self.spb2[:,1],'ro-', cortex[0], cortex[1], 'k-', cortex[0], cortex[2], 'k-') ## axis([-8,8,-2,2]) def logging(self, fname, dt): ''' Écrit dans le fichier nommé fname.txt les trajectroires des SPBs, etc. ''' tmp = "data.txt" name= fname+".txt" length_proj = S.array(self.length_proj) spindle_angle = S.array(self.trajs_theta) posSPB1 = self.spb1[:,0:2] posSPB2 = self.spb2[:,0:2] nb_frames = len(length_proj) timelapse = [] for i in range(nb_frames) : timelapse.append(i*dt) timelapse = S.array(timelapse) timelapse -= self.temps_2 data = S.column_stack((length_proj, spindle_angle, posSPB1[:,0], posSPB1[:,1], posSPB2[:,0], posSPB2[:,1], timelapse)) S.io.write_array(tmp, data, separator=' ', linesep='\n') f = open(name,'w+') g = open(tmp,'r+') f.write("spindle_length spindle_angle xspb1 yspb1 xspb2 yspb2 timelapse\n") for line in g: f.write(line) f.close() g.close()
Java
UTF-8
3,677
2.28125
2
[]
no_license
package com.example.matheus.projeto_final; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.text.SimpleDateFormat; import entidades.Patrimony; import entidades.Storage; import webService.ServiceCallback; import webService.WebService; public class EditActivity extends AppCompatActivity implements ServiceCallback{ public final static String ID_PATRIMONY = "ID_PATRIMONY"; private int id; private Patrimony patrimony; private ProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); id = (int) getIntent().getExtras().get(ID_PATRIMONY); progressDialog = ProgressDialog.show(this, "", "Consultando dados no servidor..."); progressDialog.show(); WebService.getInstance().searchByID(id, this); } public void editPatrimony(){ patrimony.setName(((EditText)findViewById(R.id.etNameEdit)).getText().toString()); patrimony.setResponsible(((EditText)findViewById(R.id.etReponsibleEdit)).getText().toString()); patrimony.setLocation((((EditText)findViewById(R.id.etLocationEdit)).getText().toString())); patrimony.setDescription(((EditText)findViewById(R.id.etDescriptEdit)).getText().toString()); patrimony.setLastUpdater(Storage.getInstance().getLoggedUser()); } public void btEditPatrimonyClick(View view){ editPatrimony(); progressDialog = ProgressDialog.show(this, "", "Enviando dados para o servidor..."); WebService.getInstance().edit(patrimony, this); } public void setFieldsValues(Patrimony patrimony){ ((EditText)findViewById(R.id.etNameEdit)).setText(patrimony.getName()); ((EditText)findViewById(R.id.etReponsibleEdit)).setText(patrimony.getResponsible()); ((EditText)findViewById(R.id.etLocationEdit)).setText(patrimony.getLocation()); ((EditText)findViewById(R.id.etDescriptEdit)).setText(patrimony.getDescription()); ((EditText)findViewById(R.id.etIdEdit)).setText(""+patrimony.getId()); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm"); ((TextView)findViewById(R.id.tvRegisterDate)).setText("Cadastrado por " + patrimony.getRegisteredBy().getName() + " na data " + sdf.format(patrimony.getRegisterDate())); if(patrimony.getLastUpdate() != null){ ((TextView)findViewById(R.id.tvEditDate)).setText("Alterado pela última vez por " + patrimony.getLastUpdater().getName() + " na data " + sdf.format(patrimony.getLastUpdate())); } } @Override public void serviceCallback(String result, int code) { if(code == WebService.SEARCH_PATRIMONY){ patrimony = Storage.getInstance().getPatrimonyById(id); if(patrimony != null){ setFieldsValues(patrimony); }else{ Toast.makeText(this, "Não foi possível carregar os dados do patrimônio", Toast.LENGTH_SHORT).show(); } }else if(code == WebService.EDIT_PATRIMONY){ Toast.makeText(this, "O patrimônio foi editado com sucesso", Toast.LENGTH_SHORT).show(); finish(); } progressDialog.dismiss(); } }
SQL
UTF-8
817
3.8125
4
[]
no_license
CREATE TABLE AuthConsumer ( ConsumerId varchar(255) PRIMARY KEY NOT NULL, CreatedAt datetime NOT NULL, UpdatedAt datetime NOT NULL, ClientId varchar(255), ClientSecret varchar(255), Username varchar(255) ); CREATE UNIQUE INDEX PK__AuthConsumer_ConsumerId ON AuthConsumer(ConsumerId); CREATE UNIQUE INDEX UK_AuthConsumer_Username ON AuthConsumer(Username); CREATE TABLE AuthCompany ( id bigint identity PRIMARY KEY NOT NULL, CreatedAt datetime NOT NULL, UpdatedAt datetime NOT NULL, CompanyId varchar(255), CompanyType varchar(255) NOT NULL, ConsumerId varchar(255) NOT NULL ); ALTER TABLE AuthCompany ADD CONSTRAINT FK_Consumer_Company_On_ConsumerId FOREIGN KEY (ConsumerId) REFERENCES AuthConsumer(ConsumerId); CREATE UNIQUE INDEX PK__AuthCompany_Id ON AuthCompany(id);
Java
UTF-8
5,350
3.015625
3
[ "MIT" ]
permissive
package net.bolbat.utils.lang; import net.bolbat.utils.annotation.Audience; import net.bolbat.utils.annotation.Stability; /** * Useful validations. * * @author Alexandr Bolbat */ @Audience.Public @Stability.Evolving public final class Validations { /** * Default constructor with preventing instantiations of this class. */ private Validations() { throw new IllegalAccessError("Shouldn't be instantiated."); } /** * Ensures the truth of an expression.<br> * Throws {@link IllegalArgumentException} if {@code expression} is <code>false</code>. * * @param expression * a boolean expression */ public static void checkArgument(final boolean expression) { if (!expression) throw new IllegalArgumentException(); } /** * Ensures the truth of an expression.<br> * Throws {@link IllegalArgumentException} if {@code expression} is <code>false</code>. * * @param expression * a boolean expression * @param message * the exception message to use if the check fails, will be converted to a string using {@link String#valueOf(Object)} */ public static void checkArgument(final boolean expression, final Object message) { if (!expression) throw new IllegalArgumentException(String.valueOf(message)); } /** * Ensures the truth of an expression.<br> * Throws {@link IllegalArgumentException} if {@code expression} is <code>false</code>. * * @param expression * a boolean expression * @param template * a template for the exception message to use if the check fails, will be processed using {@link String#valueOf(Object)} * @param args * the arguments to be substituted into the message template using {@link String#format(String, Object[])} */ public static void checkArgument(final boolean expression, final String template, final Object... args) { if (!expression) throw new IllegalArgumentException(String.format(String.valueOf(template), args)); } /** * Ensures the truth of an expression.<br> * Throws {@link IllegalStateException} if {@code expression} is <code>false</code>. * * @param expression * a boolean expression */ public static void checkState(final boolean expression) { if (!expression) throw new IllegalStateException(); } /** * Ensures the truth of an expression.<br> * Throws {@link IllegalStateException} if {@code expression} is <code>false</code>. * * @param expression * a boolean expression * @param message * the exception message to use if the check fails, will be converted to a string using {@link String#valueOf(Object)} */ public static void checkState(final boolean expression, final Object message) { if (!expression) throw new IllegalStateException(String.valueOf(message)); } /** * Ensures the truth of an expression.<br> * Throws {@link IllegalStateException} if {@code expression} is <code>false</code>. * * @param expression * a boolean expression * @param template * a template for the exception message to use if the check fails, will be processed using {@link String#valueOf(Object)} * @param args * the arguments to be substituted into the message template using {@link String#format(String, Object[])} */ public static void checkState(final boolean expression, final String template, final Object... args) { if (!expression) throw new IllegalStateException(String.format(String.valueOf(template), args)); } /** * Ensures the {@code reference} in not <code>null</code>.<br> * Throws {@link NullPointerException} if {@code reference} is <code>null</code>. * * @param reference * an object reference * @return the non-null reference that was validated */ public static <T> T checkNotNull(final T reference) { if (reference == null) throw new NullPointerException(); return reference; } /** * Ensures the {@code reference} in not <code>null</code>.<br> * Throws {@link NullPointerException} if {@code reference} is <code>null</code>. * * @param reference * an object reference * @param message * the exception message to use if the check fails, will be converted to a string using {@link String#valueOf(Object)} * @return the non-null reference that was validated */ public static <T> T checkNotNull(final T reference, final Object message) { if (reference == null) throw new NullPointerException(String.valueOf(message)); return reference; } /** * Ensures the {@code reference} in not <code>null</code>.<br> * Throws {@link NullPointerException} if {@code reference} is <code>null</code>. * * @param reference * an object reference * @param template * a template for the exception message to use if the check fails, will be processed using {@link String#valueOf(Object)} * @param args * the arguments to be substituted into the message template using {@link String#format(String, Object[])} * @return the non-null reference that was validated */ public static <T> T checkNotNull(final T reference, final String template, final Object... args) { if (reference == null) throw new NullPointerException(String.format(String.valueOf(template), args)); return reference; } }
C++
UTF-8
1,337
2.796875
3
[]
no_license
//*************************************************************************************** // A collection of mathmaticly constants and functions // Autors: Kay Goossen // Date: 29 September 2015 // Version: 1.01 //*************************************************************************************** #include "Line.h" #include "VisionOperators.h" #define PI 3.14159265359 #define Infinity 9999999 namespace math { using cv::Mat; using cv::Point; using cv::Line; int sign(int val); float length(const Point& vector); float length(const vision::Point& vector); float cross(cv::Point v1, cv::Point v2); float cross(vision::Point v1, vision::Point v2); void rotatePoint(const Mat& src, const Point& srcPoint, Point& dstPoint, float angle); void rotatePoint(const vision::Mat& src, const vision::Point& srcPoint, vision::Point& dstPoint, float angle); void rotateLine(const Mat& src, Line& srcLine, Line& dstLine, float angle); void rotateLine(const vision::Mat& src, vision::Line& srcLine, vision::Line& dstLine, float angle); std::vector<Point> horizontalLineObjectIntersection(const Mat& src, int height); std::vector<vision::Point> horizontalLineObjectIntersection(const vision::Mat& src, int height); Point lineLineIntersection(Line l1, Line l2); vision::Point lineLineIntersection(vision::Line l1, vision::Line l2); }
C#
UTF-8
5,010
2.53125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using CatsAndDogs_project.Data; using CatsAndDogs_project.Models; using Microsoft.AspNetCore.Authorization; namespace CatsAndDogs_project.Controllers { [Authorize(Roles = "Admin , Editor")] public class BreedCat_2Controller : Controller { private readonly CatsAndDogs_projectContext _context; public BreedCat_2Controller(CatsAndDogs_projectContext context) { _context = context; } // GET: BreedCat_2 public async Task<IActionResult> Index() { var q = from b in _context.BreedCat_2.OrderBy(x => x.Name) select b; return View(await q.ToListAsync()); } public async Task<IActionResult> Search(string queryName) // add search { var q = from b in _context.BreedCat_2 where (b.Name.Contains(queryName)) || (queryName == null) orderby b.Name select b; return View("Index", await q.ToListAsync()); } // GET: BreedCat_2/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var breedCat_2 = await _context.BreedCat_2 .FirstOrDefaultAsync(m => m.Id == id); if (breedCat_2 == null) { return NotFound(); } return View(breedCat_2); } // GET: BreedCat_2/Create public IActionResult Create() { return View(); } // POST: BreedCat_2/Create // To protect from overposting attacks, enable the specific properties you want to bind to. // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("Id,Name")] BreedCat_2 breedCat_2) { if (ModelState.IsValid) { _context.Add(breedCat_2); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } return View(breedCat_2); } // GET: BreedCat_2/Edit/5 public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var breedCat_2 = await _context.BreedCat_2.FindAsync(id); if (breedCat_2 == null) { return NotFound(); } return View(breedCat_2); } // POST: BreedCat_2/Edit/5 // To protect from overposting attacks, enable the specific properties you want to bind to. // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("Id,Name")] BreedCat_2 breedCat_2) { if (id != breedCat_2.Id) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(breedCat_2); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!BreedCat_2Exists(breedCat_2.Id)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } return View(breedCat_2); } // GET: BreedCat_2/Delete/5 public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var breedCat_2 = await _context.BreedCat_2 .FirstOrDefaultAsync(m => m.Id == id); if (breedCat_2 == null) { return NotFound(); } return View(breedCat_2); } // POST: BreedCat_2/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var breedCat_2 = await _context.BreedCat_2.FindAsync(id); _context.BreedCat_2.Remove(breedCat_2); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } private bool BreedCat_2Exists(int id) { return _context.BreedCat_2.Any(e => e.Id == id); } } }
PHP
UTF-8
770
2.78125
3
[]
no_license
<?php namespace App\Data\Blog; use Validator; class Stock extends BaseModel { // Database table used by the model protected $table = 'stocks'; protected $guarded = ['id']; /** * Validate input data for stock * * @return Validator */ public static function validateStock($inputData = []) { // Rules for validation of data $rules = [ 'user_id' => 'required', 'stock_id' => 'required', ]; $validator = Validator::make($inputData, $rules); return $validator; } public function user() { return $this->belongsTo('App\Data\System\User'); } public function post() { return $this->belongsTo('App\Data\Blog\Post'); } }
Java
UTF-8
2,964
4.1875
4
[]
no_license
/* File Name: Nim.java //******PROPERTY OF ALICIA RODRIGUEZ******** Nim class which depends only on the Player interface and Pile class. It does not depend on any of the other classes that implement the Player Interface. */ package nimgame; //******PROPERTY OF ALICIA RODRIGUEZ******** public class Nim { //Instance Variables: private Pile marblePile; //the pile of marbles /** * Constructs a pile. */ public Nim() { marblePile = new Pile(); //******PROPERTY OF ALICIA RODRIGUEZ******** } /** * Conductor of the game. Nim knows how many marbles are in the pile. * Must call the move() method polymorphically. * * @param player1 Player 1: either human, smart comp, or dumb comp. * @param player2 Player 2: either human, smart comp, or dumb comp. */ public void play(Player player1, Player player2) { System.out.println("***Game has started***\n"); //******PROPERTY OF ALICIA RODRIGUEZ******** System.out.println(player1 + " VS " + player2 + "\n\n"); //polymorphically calling the corresponding toString methods int play; System.out.println("There are " + marblePile.getMarbles() + " marbles in the pile."); //******PROPERTY OF ALICIA RODRIGUEZ******** do { //start conducting the game atleast once play = player1.move(marblePile.getMarbles()); //polymorphism marblePile.removeMarbles(play); //remove the number of marbles //the player chooses in "move" if(marblePile.getMarbles() == 1) { //if the number of marbles is equal to 1 then... System.out.println(player1 + " is the winner!"); System.out.println(player2 + " pick up the last marble!"); break; //no need to continue } //******PROPERTY OF ALICIA RODRIGUEZ******** play = player2.move(marblePile.getMarbles()); //polymorphism marblePile.removeMarbles(play); //remove the number of marbles //the player chooses in "move" if(marblePile.getMarbles() == 1) { System.out.println(player2 + " is the winner!"); System.out.println(player1 + " pick up the last marble!"); //no break needed because it's already the end of the loop } } while(marblePile.getMarbles() > 0); //is #of marbles greater than 0? //continue loop, if it's not then //game has finished. }//******PROPERTY OF ALICIA RODRIGUEZ******** }//end of Nim class definition
Java
UTF-8
4,924
2.875
3
[]
no_license
package lab2; import com.fasterxml.jackson.annotation.JsonIgnore; import javax.xml.bind.annotation.XmlTransient; import java.time.LocalDate; import java.time.Month; import java.util.regex.*; public class Bus { private int capacity; private String indentificationNumber; private LocalDate dataConstruction; private Model model; @XmlTransient @JsonIgnore private int id; private final static String CAPACITY_PATTERN = "capacity=(\\d{1,})"; private final static String DATA_CONSTRUCTION_PATTERN = "dataConstruction=(\\d{4}\\-\\d{2}\\-\\d{2})"; private final static String MODEL_PATTERN = "model=([A-Z]{1,})"; private final static String NUMBER_PATTERN = "indentificationNumber=([A-Z]{2}\\d{4}[A-Z]{2})"; private final static String NUMBER_PATTERN1 = "[A-Z]{2}\\d{4}[A-Z]{2}"; public enum Model{ VOLKSWAGEN, FORD, RENAULT, TOYOTA, ICARUS, NISSAN, LADA, GEELY, DAEWOO, AUDI } public Bus(){ this.capacity = 5; this.indentificationNumber = "AH2718AC"; this.dataConstruction = LocalDate.of(2010, Month.OCTOBER, 11); this.model = Model.LADA; } public Bus(int capacity, String indentificationNumber, LocalDate dataConstruction, Model model){ this.capacity = capacity; this.indentificationNumber = indentificationNumber; this.dataConstruction = dataConstruction; this.model = model; } /** * @param number - amount of passengers * This method checks the capacity of the bus. * If there is enough place for passengers it will return true, * and will return false if there are to many people for this type of the bus. * @return */ public boolean checkOfTheSize(int number){ return number <= this.capacity; } /** * @param indentificationNumber * This method checks whether the identification number is correct. * @return */ public boolean regularExpIdentificationNumber(String indentificationNumber){ Pattern pattern = Pattern.compile(NUMBER_PATTERN1); Matcher match = pattern.matcher(indentificationNumber); return match.matches(); } public Model getModel() { return model; } public void setModel(Model model) { this.model = model; } public int getCapacity() { return capacity; } public void setCapacity(int capacity) { this.capacity = capacity; } public String getIndentificationNumber() { return indentificationNumber; } public void setIndentificationNumber(String indentificationNumber) { this.indentificationNumber = indentificationNumber; } public LocalDate getDataConstruction() { return dataConstruction; } public void setDataConstruction(LocalDate dataConstruction) { this.dataConstruction = dataConstruction; } public int getId() { return id; } public void setId(int id) { this.id = id; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((indentificationNumber == null) ? 0 : indentificationNumber.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Bus other = (Bus) obj; return ((other.dataConstruction.equals(this.dataConstruction)) && (other.capacity == this.capacity) && (other.indentificationNumber.equals(this.indentificationNumber))); } public Bus fromString(String[] str){ Pattern pattern1 = Pattern.compile(NUMBER_PATTERN); Pattern pattern2 = Pattern.compile(MODEL_PATTERN); Pattern pattern3 = Pattern.compile(CAPACITY_PATTERN); Pattern pattern4 = Pattern.compile(DATA_CONSTRUCTION_PATTERN); Matcher match; for(int i = 0; i < 4; i++) { if((match = pattern1.matcher(str[i])).matches() == true){ this.indentificationNumber = match.group(1); } if((match = pattern2.matcher(str[i])).matches() == true){ this.model = Model.valueOf(match.group(1)); } if((match = pattern3.matcher(str[i])).matches() == true){ this.capacity = Integer.parseInt(match.group(1)); } if((match = pattern4.matcher(str[i])).matches()){ this.dataConstruction = LocalDate.parse(match.group(1)); } } return this; } @Override public String toString() { return "capacity=" + capacity + "\nindentificationNumber=" + indentificationNumber + "\ndataConstruction=" + dataConstruction + "\nmodel=" + model; } }
Python
UTF-8
387
3
3
[]
no_license
# https://leetcode.com/problems/ransom-note/ # Solved Date: 20.05.03. def can_construct(ransomNote, magazine): from collections import Counter magazine_counter = Counter(magazine) ransomNote_counter = Counter(ransomNote) for letter in ransomNote_counter.keys(): if magazine_counter[letter] < ransomNote_counter[letter]: return False return True
Python
UTF-8
573
2.8125
3
[]
no_license
def do(f): fabric = [[''] * 1000 for _ in range(1000)] for line in f: id, _, xy, size = line.split() id = int(id[1:]) x, y = map(int, xy.strip(':').split(',')) w, h = map(int, size.split('x')) for i in range(x, x + w): for j in range(y, y + h): if not fabric[i][j]: fabric[i][j] = '.' else: fabric[i][j] = '#' print(sum(row.count('#') for row in fabric)) if __name__ == "__main__": #do(open("small.txt")) do(open("input.txt"))
Python
UTF-8
791
3.59375
4
[]
no_license
"""class person(object): def __init__(self,name): self.name=name def getname(self): return self.name def isemployee(self): return False class employee(person): def isemployee(self): return True emp=person("geeks") print(emp.getname(),emp.isemployee()) emp=employee("geeks1") print(emp.getname,emp.isemployee()) class base(object): pass class derived(base): pass print(issubclass(base,derived)) print(issubclass(derived,base)) b=base() d=derived() print(isinstance(b,derived)) print(isinstance(d,base)) class base(object): def __init__(self,x): self.x=x class derived(base): def __init__(self,x,y): base.x=x self.y=y def printxy(self): print(base.x,self.y) d=derived(10,20) d.printxy()"""
Markdown
UTF-8
428
2.8125
3
[]
no_license
# Instance of my Menu class **Class** class: KidsHolidayMenu **Attributes** ```ruby menu_name = "Kid's Holiday Specials" material = "paper" color = "Green" food_items = { "Mac 'n Cheese": 2.50, "Smiling Pancakes": 3.50} is_open = false ``` **Methods** * change_name: `menu_name = "Kid's Happy Holiday Specials"` * change_material: `material = "plastic"` * change_color: `color = "Red"` * open_close_menu: `is_open = true`
PHP
UTF-8
5,926
2.9375
3
[]
no_license
<?php if (isset($_POST['short'])) { $short = $_POST['short']; } if (isset($_POST['comment'])) { $comment = $_POST['comment']; } if (isset($_POST['expire'])) { deleteFiles(); deleteFromDB(); header('Location: http://local-dev.chooseshort.com/'); } if (isset($_POST['submit'])) { createShort($short, $comment); insertShort($short, $comment); header('Location: http://local-dev.chooseshort.com/'); } form(); displayInfo(); /*************Present Form************/ function form() { ?> <html> <head> <title> Customize a Short URL for grata.co/ </title> </head> <body> <!-- Display Form --> <fieldset> <legend> Add Analytics to a Short URL </legend> <br \> <strong> This form generates a php file with google analytics that redirects based on user agent </strong> <br \> <br \> Example: <br \> 1. Submit a custom short url "iluvbjs" <br \> 2. [Backend] Adds the file iluvbjs.php to the production server at /var/www/html/grata.co/ <br \> 3. Access the file via http://grata.co/iluvbjs <br \> <br \> <form action = "" method = "post"> <input type = "text" size = "30" name = "short" value = "submit custom short" /> <input type = "text" size = "50" name = "comment" value = "submit comment with short" /> <br \> <input type = "submit" name = "submit" value = "submit" /> </form> </fieldset> </body> </html> <? } /************ Display table "display" in database "shorts" **************/ function displayInfo() { $link = mysqli_connect("local-dev.chooseshort.com", "root", "s3ns89ui","shorts") or die(mysqli_error()); $sql = "SELECT * FROM display ORDER BY timestamp DESC LIMIT 10"; $result = mysqli_query ($link, $sql) or die (mysql_error()); $path = "http://local-dev.chooseshort.com/"; ?> <!-- Display info --> <html> <head></head> <body> <fieldset> <legend> Selected URLs </legend> <table> <tr> <th> Timestamp </th> <td> &nbsp; </td> <td> &nbsp; </td> <th> Short URL </th> <td> &nbsp; </td> <td> &nbsp; </td> <th> QR Code </th> <td> &nbsp; </td> <td> &nbsp; </td> <th> Comment </th> </tr> <?php while ($row = mysqli_fetch_array($result)) :?> <tr> <td> <?php echo $row['timestamp']; ?> </td> <td> &nbsp; </td> <td> &nbsp; </td> <td> <?php echo preg_replace('/\.[^.]*$/', '', $row['short_url']); ?> </td> <td> &nbsp; </td> <td> &nbsp; </td> <td> <img src = "<?php echo $path.$row['qrcode']; ?>"> <?php $path.$row['qrcode']; ?> </td> <td> &nbsp; </td> <td> &nbsp; </td> <td> <?php echo $row['comment']; ?> </td> <td> <form action = "" method = "post"> <input type = "hidden" name = "expire" value = "<?php echo $row['short_url']; ?>" /> <input type = "submit" value = "delete" /> </form> </td> </tr> <?php endwhile; ?> </table> </fieldset> </body> </html> <? } /********* The following two functions process Form Data ***********/ function createShort($short, $comment) { $text = "<?php\n include('/var/www/html/grata.co/php-ga-1.1.1/src/autoload.php');\n use UnitedPrototype\GoogleAnalytics;\n // Initialize GA Tracker\n \$tracker = new GoogleAnalytics\\Tracker('UA-41229393-4', 'www.grata.co');\n // Assemble Visitor information\n \$visitor = new GoogleAnalytics\\Visitor();\n \$visitor->setIpAddress(\$_SERVER['REMOTE_ADDR']); \$visitor->setUserAgent(\$_SERVER['HTTP_USER_AGENT']); // Assemble Session information\n \$session = new GoogleAnalytics\Session();\n // Assemble Page information\n \$page = new GoogleAnalytics\Page(\"/$short\");\n \$page->setTitle(\"$comment\");\n // Track page view\n \$tracker->trackPageview(\$page, \$session, \$visitor);\n include('/var/www/html/grata.co/download.php');\n detectAgent();"; $fname = "/Users/iZhang/Desktop/Development/grata_co/chooseShort/".$short.".php"; $fp = fopen($fname, 'w+') or die("Can't open file"); $fwrite = fwrite($fp, $text); chmod($fname, 0775); } function insertShort($short, $comment) { $link = mysqli_connect("local-dev.chooseshort.com", "root", "s3ns89ui","shorts") or die(mysqli_error()); $root = "http://local-dev.chooseshort.com"; //generate qr code and save to filename shorturl.png include('/Users/iZhang/Desktop/Development/grata_co/admin/phpqrcode/phpqrcode.php'); $fname = "/Users/iZhang/Desktop/Development/grata_co/chooseShort/".$short.".png"; QRcode::png($root."/".$short.".php", $fname); chmod($fname, 0775); $qrcode = $short.'.png'; $timestamp = date("m/d/y : H:i:s", time()); $short = $short.".php"; //insert values into table. $sql = "INSERT INTO display (timestamp, short_url, qrcode, comment) VALUES ('$timestamp', '$short', '$qrcode', '$comment')"; mysqli_query($link, $sql) or die(mysqli_error()); mysqli_close($link); } /***************** Delete a given url (and associated shit) in the database and in the table *******************/ function deleteFiles() { $link = mysqli_connect("local-dev.chooseshort.com", "root", "s3ns89ui", "shorts") or die(mysqli_error()); $id = $_POST['expire']; $sql = "select * from display where short_url = '$id'"; $result = mysqli_query($link, $sql) or die(mysqli_error()); $row = mysqli_fetch_array($result); $fPhp = $row['short_url']; $fPng = $row['qrcode']; $path = "/Users/iZhang/Desktop/Development/grata_co/chooseShort/"; unlink($path.$fPhp); unlink($path.$fPng); mysqli_close($link); } function deleteFromDB() { $link = mysqli_connect("local-dev.chooseshort.com", "root", "s3ns89ui", "shorts") or die(mysqli_error()); $id = $_POST['expire']; $sql = "delete from display where short_url = '$id'"; mysqli_query($link, $sql) or die(mysqli_error()); mysqli_close($link); }
Java
GB18030
2,845
2.578125
3
[]
no_license
package spring_app14_jdbc; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import javax.swing.tree.TreePath; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; public class EmpDAO implements Dao{ private JdbcTemplate jdbcTemplate; StringBuffer sb = new StringBuffer(); PreparedStatement pstmt = null; ResultSet rs = null; public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Override public List<EmpDTO> selectAll() { // TODO Auto-generated method stub sb.setLength(0); sb.append("select * from emp"); RowMapper<EmpDTO> rm = new RowMapper<EmpDTO>() { @Override public EmpDTO mapRow(ResultSet rs, int rowNum) throws SQLException { return new EmpDTO(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getInt(4), rs.getString(5), rs.getDouble(6), rs.getDouble(7), rs.getInt(8)); } }; jdbcTemplate.query(sb.toString(), rm); return null; } @Override public EmpDTO selectOne(int no) { // TODO Auto-generated method stub sb.setLength(0); sb.append("select * from emp "); sb.append("where empno = ? "); RowMapper<EmpDTO> rm = new RowMapper<EmpDTO>() { @Override public EmpDTO mapRow(ResultSet rs, int rowNum) throws SQLException { // TODO Auto-generated method stub return new EmpDTO(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getInt(4), rs.getString(5), rs.getDouble(6), rs.getDouble(7), rs.getInt(8)); } }; EmpDTO dto = jdbcTemplate.queryForObject(sb.toString(), rm,no); return dto; } @Override public void insertOne(EmpDTO dto) { // TODO Auto-generated method stub sb.setLength(0); sb.append("insert into emp "); sb.append("values (?, ?, ?, ?, curdate(), ?, ?, ?) "); int result = jdbcTemplate.update(sb.toString(), dto.getEmpno(), dto.getEname(), dto.getJob(), dto.getMgr(), dto.getSal(), dto.getComm(), dto.getDeptno()); System.out.println("insert ó : " + result); } @Override public void updateOne(EmpDTO dto) { // TODO Auto-generated method stub sb.setLength(0); sb.append("update emp "); sb.append("set ename = ? , sal = ?, deptno = ? "); sb.append("where empno = ? "); int result = jdbcTemplate.update(sb.toString(), dto.getEname(), dto.getSal(), dto.getDeptno(), dto.getEmpno()); System.out.println("update ó " + result); } @Override public void deleteOne(int no) { // TODO Auto-generated method stub sb.setLength(0); sb.append("delete from emp "); sb.append("where empno = ? "); int result = jdbcTemplate.update(sb.toString(), no); System.out.println("delete ó : " + result); } }
Java
UTF-8
788
2.546875
3
[]
no_license
package stud; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Iterator; import java.util.NavigableSet; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import javax.xml.ws.handler.MessageContext.Scope; public class cc8 { public static void main(String[] args) { String skill = "CBD"; String[] skill_trees = {"BACDE", "CBADF", "AECB", "BDA"}; int answer= 0; ArrayList<String> list = new ArrayList<String>(Arrays.asList(skill_trees)); Iterator<String> it = list.iterator(); while(it.hasNext()) { String s = it.next(); String b = s.replace("[^"+skill+"]", ""); if(skill.indexOf(b) != 0) it.remove(); } answer = list.size(); System.out.println(answer); } }
Python
UTF-8
419
3.03125
3
[]
no_license
__author__ = 'Merlo' import string def checkio(text): text = text.lower() remove = string.digits + string.punctuation + ' ' for char in text: if char in remove: text = text.replace(char, '') text = sorted(text) result = "" count = 0 for item in text: if text.count(item) > count: count = text.count(item) result = item return result
C#
UTF-8
490
2.75
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LabirintEPAM2019 { public class Ground : BaseConsoleCell { public override ConsoleColor ForegroundColor { get; protected set; } = ConsoleColor.Green; public override char Symbol { get; set; } = '.'; public override bool TryToStep { get; protected set; } = true; public Ground(int _x, int _y) : base(_x, _y) { } } }
Java
UTF-8
19,866
2.640625
3
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package exchangerateprediction; import java.io.FileWriter; import java.io.IOException; import java.util.Random; import java.util.Arrays; import java.util.Formatter; //***this package is based on byte array, I may be able to write a bitwise version public class GeneticAlgorithm { int dynamicCounter; //evaluate fitness of each population member,, this function have to be overwritten private double evaluate(byte[] solution) throws IOException { int t = arrtoi(solution); for(int i = 0; i < checkedNumber; i++) if(t == checkedPoints[i]) { System.out.println("$$$ " + dynamicCounter++); return checkedFitness[i]; } Trainer trainer = new Trainer(trainFile); double res = trainer.run(solution)[0]; //TODO: add SCC affect also, find classification result checkedPoints[checkedNumber++] = arrtoi(solution); checkedFitness[checkedNumber] = res; return res; } //--------------------variables------------------------------------ private int populationSize; //size of choromosome numbers private int chromosomeLength; //size of each chormosome private double mutuationProbability; private double crossOverProbability; private int eliteNumber; //number of elite answers that have to remain private int maxGeneration; //int mode; //operate in byte mode or bit mode //Different methods of Selection, Cross Over and Mutation //***use enum later private int selectionMethod; private int crossOverMethod; private int mutuationMethod; //population byte[][] population; //int[] bitPopulation; double[] fitness; byte[][] elites; int[] selectedParents; int[] checkedPoints; double[] checkedFitness; int checkedNumber; //process time calculation variables long runTime; long initializationTime; long selectionTime; long crossOverTime; long mutuationTime; long elitismTime; long evaluateTime; long sortTime; long otherTime; //---------------------------end of variable------------------------- public String trainFile; //-------------------------constructors------------------------------ public GeneticAlgorithm(int chromosomeLength) { this.chromosomeLength = chromosomeLength; //default values this.populationSize = 10; //***defualt population size I put 20, may change later this.mutuationProbability = (double)1/chromosomeLength; //L*Pm = 1: expecting one mutuation in each chromosome this.selectionMethod = 1; //simplest selection method, choosing best parents this.crossOverMethod = 1; //simplest cross over method, one point cross over from half this.crossOverProbability = 0.8; //cross over happens in any case (all offspring created sexually) this.eliteNumber = 1; //default number of elite members that have to remain for next generation this.maxGeneration = 50; //***default maximum number of generations, may change later //create population population = new byte[populationSize][chromosomeLength]; fitness = new double[populationSize]; elites = new byte[eliteNumber][chromosomeLength]; } public GeneticAlgorithm(int chromosomeSize, int populationSize) { this(chromosomeSize); this.populationSize = populationSize; //create population population = new byte[populationSize][chromosomeLength]; fitness = new double[populationSize]; } public GeneticAlgorithm(int chromosomeSize, int populationSize, double mutuationProbability) { this(chromosomeSize, populationSize); this.mutuationProbability = mutuationProbability; //create population population = new byte[populationSize][chromosomeLength]; fitness = new double[populationSize]; elites = new byte[eliteNumber][chromosomeLength]; } public GeneticAlgorithm(int chromosomeSize, int populationSize, double mutuationProbability, int selectionMethod, int crossOverMethod) { this(chromosomeSize, populationSize, mutuationProbability); this.selectionMethod = selectionMethod; this.crossOverMethod = crossOverMethod; //create population population = new byte[populationSize][chromosomeLength]; fitness = new double[populationSize]; elites = new byte[eliteNumber][chromosomeLength]; } public GeneticAlgorithm(int chromosomeSize, int populationSize, double mutuationProbability, int selectionMethod, int crossOverMethod, double crossOverProbability) { this(chromosomeSize, populationSize, mutuationProbability, selectionMethod, crossOverMethod); this.crossOverProbability = crossOverProbability; //create population population = new byte[populationSize][chromosomeLength]; fitness = new double[populationSize]; elites = new byte[eliteNumber][chromosomeLength]; } public GeneticAlgorithm(int chromosomeSize, int populationSize, double mutuationProbability, int selectionMethod, int crossOverMethod, double crossOverProbability, int eliteNumber) { this(chromosomeSize, populationSize, mutuationProbability, selectionMethod, crossOverMethod, crossOverProbability); this.eliteNumber = eliteNumber; //create population population = new byte[populationSize][chromosomeLength]; fitness = new double[populationSize]; elites = new byte[eliteNumber][chromosomeLength]; } //---------------------public functions-------------------------------- //main function to run genetic algorithm for default numbers of iteration public byte[] run() throws IOException { //***max Generation is 1000 for default return run(maxGeneration); } public byte[] run(int maxGeneration) throws IOException { //main function to run genetic algorithm long startTime, t; //for process time calculation startTime = System.currentTimeMillis(); t = System.currentTimeMillis(); initialize(); //initialize first gereneration, sort and select elites initializationTime = System.currentTimeMillis() - t; for(int i = 0; i < maxGeneration; i++) { System.out.println("\n#GENERATION: " + (i+1)); t = System.currentTimeMillis(); selection(); selectionTime += System.currentTimeMillis() - t; t = System.currentTimeMillis(); crossOver(); crossOverTime += System.currentTimeMillis() - t; t = System.currentTimeMillis(); mutuation(); mutuationTime += System.currentTimeMillis() - t; t = System.currentTimeMillis(); elitism(); elitismTime += System.currentTimeMillis() - t; if(stoppingCriteria()) break; } runTime = System.currentTimeMillis() - startTime; return population[0]; //return the best of population, that is after sorting the first one in population } public String printResults() { elitismTime -= (evaluateTime + sortTime); String res = "Best Result with fitness of " + fitness[1] + "\n created in: " + maxGeneration + " Generations and " + (double)runTime/1000 + " seconds, \n In details: \n" + " Initialization: " + (double)initializationTime/1000 + " seconds (" + (100 * initializationTime / runTime) + "%) \n" + " Selection: " + (double)selectionTime/1000 + " seconds (" + (100 * selectionTime / runTime) + "%) \n" + " Cross Over: " + (double)crossOverTime/1000 + " seconds (" + (100 * crossOverTime / runTime) + "%) \n" + " Mutuation: " + (double)mutuationTime/1000 + " seconds (" + (100 * mutuationTime / runTime) + "%) \n" + " Evaluation: " + (double)evaluateTime/1000 + " seconds (" + (100 * evaluateTime / runTime) + "%) \n" + " Sort: " + (double)sortTime/1000 + " seconds (" + (100 * sortTime / runTime) + "%) \n" + " Elitism: " + (double)elitismTime/1000 + " seconds (" + (100 * elitismTime / runTime) + "%) \n"; return res; } //-------------------------Initilization------------------------- private void initialize() throws IOException { checkedPoints = new int[maxGeneration * populationSize]; checkedFitness = new double[maxGeneration * populationSize]; checkedNumber = 0; System.out.println("\n#GENERATYION:" + 0); //initilize first population and sort them and select Random rand = new Random(System.currentTimeMillis()); //*** enhance it by faster better random creation methods for(int j = 0; j < chromosomeLength; j++) population[0][j] = 0; System.out.println("#population:" + 0); fitness[0] = evaluate(population[0]); for(int j = 0; j < chromosomeLength; j++) population[1][j] = 1; System.out.println("\n#population:" + 1); fitness[1] = evaluate(population[1]); //create random solutions for(int i = 2; i < populationSize; i++) //*** enhance it by checking repeated solutions { System.out.println("\n#population:" + i); for(int j = 0; j < chromosomeLength; j++) population[i][j] = (byte)rand.nextInt(2); //*** make it faster by random creation methods //finding fitness of each random solution fitness[i] = evaluate(population[i]); } sort(); //sort popultation members for easier selection and elitism selectElites(); //select the elite members and keep them for next generation } //-----------------------Selections------------------------------ private void selection() { //selection function that call different selection methods switch(selectionMethod) { case 0: selectBest(); break; case 1: //***** tournament size tournamentSelection(2); break; default: tournamentSelection(2); break; } } private void selectBest() { //simplest, naive selection method, it select the best parents selectedParents = new int[populationSize]; //*** check for odd population for(int i = 0, j = populationSize/2-1; i < populationSize/2; i++, j--) { selectedParents[i*2] = i; selectedParents[i*2+1] = j; } } private void tournamentSelection(int tournamentSize) { selectedParents = new int[populationSize]; Random rand = new Random(System.currentTimeMillis()); for(int i = 0; i < populationSize; i++) { int best = rand.nextInt(populationSize); for(int j = 1; j < tournamentSize; j++) { int t = rand.nextInt(populationSize); if(fitness[best] > fitness[t]) best = t; } selectedParents[i] = best; } } //------------------Cross Over---------------------------- private void crossOver() { switch(crossOverMethod) { case 0: simpleOnePointCrossOver(); break; case 1: onePointCrossOver(); break; case 2: twoPointCrossOver(); break; default: twoPointCrossOver(); break; } } //simplest cross over possible, one point from middle of each answer private void simpleOnePointCrossOver() { byte[][] offSprings = new byte[populationSize][chromosomeLength]; //****check of odd chromosomeLength for(int i = 0; i < populationSize; i = i+2) { int j; for(j = 0; j < chromosomeLength/2; j++) { offSprings[i][j] = population[selectedParents[i]][j]; offSprings[i+1][j] = population[selectedParents[i+1]][j]; } for(;j < chromosomeLength; j++) { offSprings[i][j] = population[selectedParents[i+1]][j]; offSprings[i+1][j] = population[selectedParents[i]][j]; } } } //one point cross over, find cross over point by random private void onePointCrossOver() { byte[][] offSprings = new byte[populationSize][chromosomeLength]; //****check of odd chromosomeLength for(int i = 0; i < populationSize; i = i+2) { int j; Random rand = new Random(System.currentTimeMillis()); int x = rand.nextInt(chromosomeLength); for(j = 0; j < x; j++) { offSprings[i][j] = population[selectedParents[i]][j]; offSprings[i+1][j] = population[selectedParents[i+1]][j]; } for(;j < chromosomeLength; j++) { offSprings[i][j] = population[selectedParents[i+1]][j]; offSprings[i+1][j] = population[selectedParents[i]][j]; } } } private void twoPointCrossOver() { byte[][] offSprings = new byte[populationSize][chromosomeLength]; Random rand = new Random(System.currentTimeMillis()); for(int i = 0; i < populationSize; i = i+2) { int j; if(rand.nextDouble() > crossOverProbability) { for(j = 0; j < chromosomeLength; j++) { offSprings[i][j] = population[selectedParents[i]][j]; offSprings[i+1][j] = population[selectedParents[i+1]][j]; } continue; } int x = rand.nextInt(chromosomeLength); int y = rand.nextInt(chromosomeLength); //swap x and y if(x > y) { int t = x; x = y; y = t; } for(j = 0; j < x; j++) { offSprings[i][j] = population[selectedParents[i]][j]; offSprings[i+1][j] = population[selectedParents[i+1]][j]; } for(;j < y; j++) { offSprings[i][j] = population[selectedParents[i+1]][j]; offSprings[i+1][j] = population[selectedParents[i]][j]; } for(;j < chromosomeLength; j++) { offSprings[i][j] = population[selectedParents[i]][j]; offSprings[i+1][j] = population[selectedParents[i+1]][j]; } } } //--------------------Mutuation---------------------- private void mutuation() { //*** too much random needs to be created Random rand = new Random(System.currentTimeMillis()); for(int i = 0; i < populationSize; i++) for(int j = 0; j < chromosomeLength; j++) { double t = rand.nextDouble(); if(t < mutuationProbability) population[i][j] = (byte)((byte)(population[i][j] + 1) % 2); } } private void elitism() throws IOException { //XXX ***check elitism if it is working fine or not*** insertElites(); double t = System.currentTimeMillis(); evaluateAll(); evaluateTime += System.currentTimeMillis() - t; t = System.currentTimeMillis(); sort(); sortTime += System.currentTimeMillis() - t; try (Formatter log = new Formatter(new FileWriter("generation_bests", true))) { log.format("%f ", fitness[0]); } selectElites(); } //*** later enhance private boolean stoppingCriteria() { return false; } //evaluate all current population fitness private void evaluateAll() throws IOException { for(int i = 0; i < populationSize; i++) { System.out.println("\n#population: " + i); fitness[i] = evaluate(population[i]); } } //sort population Descendary private void sort() throws IOException { double[] tempFitness = new double[populationSize]; System.arraycopy( fitness, 0, tempFitness, 0, populationSize ); byte[][] tempPopulation = new byte[populationSize][chromosomeLength]; //System.arraycopy( population, 0, tempPopulation, 0, population.length ); //Arrays.sort(tempFitness); //place population in order in tempPopulation /*for(int i = populationSize-1; i >= 0; i--) for(int j = 0; j < populationSize; j++) if(tempFitness[i] == fitness[j]) { fitness[j] = -1; System.arraycopy(population[j], 0, tempPopulation[populationSize - i - 1], 0, chromosomeLength); break; }*/ for(int i = 0; i < populationSize; i++) for(int j = 0; j < populationSize-1; j++) { if(fitness[j] > fitness[j+1]) { fitness[j+1] = fitness[j]; System.arraycopy(population[j], 0, population[j+1], 0, chromosomeLength); } } population = tempPopulation; //evaluateAll(); } //select select "eliteNum" best members of population private void selectElites() { elites = new byte[eliteNumber][chromosomeLength]; ///System.arraycopy(population, 0, elites, 0, eliteNumber); for(int i = 0; i < eliteNumber; i++) for(int j = 0; j < chromosomeLength; j++) elites[i][j] = population[i][j]; } //insert "eliteNum" of previous generations best members instead of worst members of current population private void insertElites() { for(int i = 0; i < eliteNumber; i++) for(int j = 0; j < chromosomeLength; j++) population[populationSize - eliteNumber + i][j] = elites[i][j]; //System.arraycopy(elites, 0, population, populationSize - eliteNumber, eliteNumber); } int arrtoi(byte[] input) { int res = 0; for(int i = input.length-1, j = 0; i >= 0; i--, j++) res += Math.pow(j, input[i]); return res; } }
C++
UHC
453
3.203125
3
[]
no_license
// Լ ƴ ʼ Դϴ. // ü ( data) Լ(getXXXX) ݵ // Լ Ǿ մϴ. class Rect { int x, y, w, h; public: int getArea() const { return w *h; } }; void foo(const Rect& r) { int n = r.getArea(); // ? } int main() { Rect r; // ʱȭ ߴٰ ϰ int n = r.getArea(); foo(r); }
JavaScript
UTF-8
7,601
2.59375
3
[]
no_license
"use strict"; function Dom(storage) { var self = this; self.find = find; self.batchFind = batchFind; self.modal = new modal(self); self.addUser = addUser; self.createConversation = createConversation; self.createConversationLink = createConversationLink; self.showConversation = showConversation; self.toggleFriendConvList = toggleFriendConvList; self.updateConversation = updateConversationMessages self.addMessage = addMessage; self.logout = logout; self.clearBody = clearBody; function find(id) { if (typeof self[id] === "undefined") { return build(id); } else { return self[id]; } } function batchFind(list){ for (var i in list) { self.find(list[i]); } } function build(id) { if (document.getElementById(id) !== null) { self[id] = document.getElementById(id); } else if (document.getElementsByClassName(id).length > 0 ) { self[id] = document.getElementsByClassName(id)[0]; } else { return false; } self[id].tmp = {}; self[id].on = on; self[id].hide = hide; self[id].show = show; self[id].toggle = toggle; self[id].clear = clear; function toggle() { if (self[id].style.display == "none") { self[id].show(); } else { self[id].hide(); } } function hide() { self[id].tmp.display = window.getComputedStyle(self[id]).getPropertyValue("display"); self[id].style.display = "none"; } function show() { self[id].style.display = self[id].tmp.display || "initial"; } function on(event, fn) { self[id].addEventListener(event, fn); }'' function clear() { self[id].innerHTML = ''; } return self[id]; } function modal() { var mdl = this; mdl.current = "loginModal"; mdl.init = function() { self.find("Modal"); mdl.close(); self.find("modal-close").on("click", mdl.close); self.find("modal-close-X").on("click", mdl.close); }; mdl.close = function() { self["Modal"].hide(); }; mdl.open = function() { self["Modal"].show(); }; mdl.switch = function(id) { self[mdl.current].hide(); self[id].show(); mdl.current = id; self["modal-title"].innerText = mdl.modals[mdl.current].title; }; mdl.modals = { "loginModal": { "title": "Login or Register" }, "findFriendsModal": { "title": "Find your friends" }, }; return mdl; } function addUser(userData, sendTo, type, where) { let li = document.createElement("li"); li.setAttribute("data-userId", userData.id); if(type == "checkbox") { li.innerHTML = '<input type="checkbox" name="addFriend" value="'+userData.id+'">' + userData.email + '</a>'; } else if (type == "link") { li.innerHTML = '<a href="#">' + userData.email + '</a>'; } li.addEventListener("click", sendTo); self[where].appendChild(li); } function addMessage(message) { console.log("message received", message); if(message.from == storage.getUserData("id")) { message.fromEmail = storage.getUserData("email"); } else { message.fromEmail = storage.getUserFriends()[message.from].email; } let li = document.createElement("li"); li.setAttribute("id", message.id); li.innerHTML = '<<a href="#" data-userId="'+message.from+'">' + message.fromEmail + '</a>> ' + message.text; try { self["conv_"+message.conversationId].appendChild(li); } catch (TypeError) { // create the conversation for the message console.log('no conversation for message'); } } function createConversationLink(conv, callback) { let li = document.createElement("li"); li.setAttribute("id", "link_" + conv.id); li.setAttribute("class", "convLink"); li.innerHTML = conv.name; li.addEventListener("click", callback); self.conversationList.appendChild(li); } function createConversation(conv, callback) { createConversationLink(conv, callback); let ul = document.createElement("ul"); ul.setAttribute("id", "conv_"+conv.id); ul.setAttribute("class", "convMessages"); for(var i in conv.messages) { let li = document.createElement("li"); li.setAttribute("id", conv.messages[i].id); li.setAttribute("class", "convMessage"); li.innerHTML = '<a href="#" data-userId="'+conv.messages[i].from+'"><' + storage.getUserData("friends")[conv.messages[i].from] + '></a> ' + conv.messages[i].text; ul.appendChild(li); } self.conversationMessages.appendChild(ul); self.find("conv_"+conv.id); } function showConversation(conv) { self["body-title"].innerHTML = "<h4>"+conv.name+"</h4>"; let members = []; let friends = storage.getUserFriends(); for (let i in conv.members) { if(conv.members[i] != storage.getUserData("id")) { members.push('<a href="#" data-userId="' + conv.members[i] + '">' + friends[conv.members[i]].email + "</a>"); } else { members.push('<a href="#">You</a>'); } } self["body-text"].innerHTML = "Members: " + members.join(", "); let convs = self.conversationMessages.children; for(var i = 0; i < convs.length; i++) { self[convs[i].id].hide(); } updateConversationMessages(conv); self["conv_"+conv.id].show(); } function updateConversationMessages(conv) { console.log("clearing conversation..."); let messageList = self["conv_"+conv.id]; messageList.clear(); for(var i in conv.messages) { let li = document.createElement("li"); li.setAttribute("id", conv.messages[i].id); li.setAttribute("class", "convMessage"); li.innerHTML = '<a href="#" data-userId="'+conv.messages[i].from+'"><' + storage.getUserData("friends")[conv.messages[i].from] + '></a> ' + conv.messages[i].text; messageList.appendChild(li); } } function toggleFriendConvList() { self.friends.classList.toggle("min"); self.friends.classList.toggle("full"); self.friendList.toggle(); self.addFriendsLink.toggle(); self.conversations.classList.toggle("min"); self.conversations.classList.toggle("full"); self.conversationList.toggle(); self.newConvButton.toggle(); } return self; function clearBody() { self["body-title"].innerHTML = "<h4> Please Login to TW1LL-MSG </h4>"; self["body-text"].innerHTML = ''; } function logout() { self.userInfoLink.innerText = "Login / Register"; self.conversationList.innerHTML = ''; self.conversationMessages.innerHTML = ''; self.friendList.innerHTML = ''; self.clearBody(); self.sidepane.hide(); self.userInfoDropdown.hide(); self.modal.switch("loginModal"); } }
Java
UTF-8
14,085
2.6875
3
[]
no_license
package com.example.sourcecodeview; import android.accessibilityservice.AccessibilityService; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.util.Log; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import java.util.List; import java.util.Objects; /** * Create by chenlei on 2019/12/21 * * 使用Android无障碍功能,完成模拟点击。 * 自动发送消息。 * 使用时在无障碍界面开启该应用的服务。然后打开soul聊天界面即可 */ public class SimulatedClickService extends AccessibilityService { private final static String TAG = "SimulatedClickService"; private long count = 0L; //接收到系统发送AccessibilityEvent时的回调 @RequiresApi(api = Build.VERSION_CODES.O) @Override public void onAccessibilityEvent(AccessibilityEvent event) { Log.e(TAG, "onAccessibilityEvent event: " + event); int eventType = event.getEventType(); switch (eventType) { case AccessibilityEvent.TYPE_VIEW_CLICKED: //界面点击 break; case AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED: //界面文字改动 break; case AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED: if (event.getSource() != null) { //遍历节点找到文本框,并输入消息 AccessibilityNodeInfo nodeInfo = event.getSource(); if (nodeInfo != null) { recycleFindEditTexts(nodeInfo); } //找到发送按钮发送消息 List<AccessibilityNodeInfo> list = Objects.requireNonNull(event.getSource()).findAccessibilityNodeInfosByText("发送"); if (null != list) { for (AccessibilityNodeInfo info : list) { if (info.getText().toString().equals("发送")) { // 找到你的节点以后就直接点击他就行了 info.performAction(AccessibilityNodeInfo.ACTION_FOCUS); info.performAction(AccessibilityNodeInfo.ACTION_CLICK); } } } } break; } } /** * 遍历node节点找到文本框,并输入文字 * @param node */ @RequiresApi(api = Build.VERSION_CODES.O) public void recycleFindEditTexts(AccessibilityNodeInfo node) { //edittext下面必定没有子元素,所以放在此时判断 if (node.getChildCount() == 0) { if ("android.widget.EditText".contentEquals(node.getClassName())) { count ++; String inputStr = count + "-" + getContent(); Log.e(TAG, inputStr); node.performAction(AccessibilityNodeInfo.ACTION_FOCUS); Bundle arguments = new Bundle(); arguments.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, inputStr.trim()); node.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, arguments); } } else { for (int i = 0; i < node.getChildCount(); i++) { if (node.getChild(i) != null) { recycleFindEditTexts(node.getChild(i)); } } } } //服务中断时的回调 @Override public void onInterrupt() { Log.e(TAG, "onInterrupt"); } /** * 得到随机文字 * @return */ private String getContent() { int index = 0; String[] contentArray = content.split("-"); index = (int) (Math.random() * contentArray.length); if (index < 0) { index = 0; } if (index > contentArray.length) { index = contentArray.length; } return contentArray[index]; } @Override public void onCreate() { super.onCreate(); } private String content = "我喜欢的样子,你都有。-“我愿意”,说时来不及思索,但思索之后还是这样说\n" + "-我的故事,都是关于你啊!\n" + "-今夜我不关心人类,我只想你。\n" + "-从爱上你的那天起,甜蜜得很轻易\n" + "-你笑起来真像好天气。\n" + "-初次见面的时候,没想到会这样爱你。\n" + "-我转头,看见你走来,在阳光里,于是笑容从我心里溢出。\n" + "-听闻小姐治家有方,鄙人余生愿闻其详。\n" + "-你来的话,日子会甜一点。\n" + "-我的勇气和你的勇气加起来,对付这个世界总够了吧?去向世界发出我们的声音,我一个人是不敢的,有了你,我就敢 。\n" + "-在有你的选择里,我都选择你。\n" + "-你是我温暖的手套,冰冷的啤酒,带着阳光味道的衬衫,日复一日的梦想。\n" + "-在所有物是人非的风景里,我最喜欢你。\n" + "-夏天总想你。夏天不听话。\n" + "-你对我说的每一句话,都是沙漠里下过的雨。\n" + "-春日宴,绿酒一杯歌一遍。再拜陈三愿:一愿郎君千岁,二愿妾身常健,三愿如同梁上燕,岁岁长相见。\n" + "-你是年少的欢喜 这句话反过来也是你\n" + "-你是我这一生等了半世未拆的礼物。\n" + "-因为你太美好了,我等你等了这么久,才能跟你在一起,我害怕得不得了,生怕自己搞砸了。\n" + "-佛渡众生。你渡我。\n" + "-这个世界一点都不温柔,还好有你。\n" + "-我看过很多书,但都没有你好看。\n" + "-我想念你身体里波光万倾的海。\n" + "-要带着温度见你,哪怕是在梦里。\n" + "-在我贫瘠的土地上,你是最后的玫瑰。\n" + "-与君初相识,犹如故人归。天涯明月新,朝暮最相思。\n" + "-最近睡得很坏,最好你搬过来。\n" + "-我想要在茅亭里看雨,假山边看蚂蚁,看蝴蝶恋爱,看蜘蛛结网,看山,看船,看云,看瀑布,看宋清如甜甜地睡觉。\n" + "-想来想去,还是想你。\n" + "-你陪着我的时候,我从未羡慕过任何人。\n" + "-写了五行关于火的诗,两行烧茶,两行留到冬天取暖,剩下的一行,留给你在停电的晚上读我。\n" + "-我像铁一样拒绝不了你这般的磁石。\n" + "-你这种人,我除了恋爱跟你也没什么好谈的。\n" + "-其实我并不习惯晚睡,只是睡前想着你,然后想了很久。\n" + "-我其实只想和你在一起一次。哪怕只有61秒,25小时,13个月。\n" + "-“来者何人?”“你的人。”\n" + "-你是非常可爱的人,真应该遇到最好的人,我也真希望我就是。\n" + "-“我有个好小好小的梦想,才四个字。”,“嗯,是什么?”,“沿途有你。”\n" + "-我曾踏月而来,只因你在山中。\n" + "-我想作诗,写雨,写夜的相思,写你,写不出。\n" + "-皎皎白驹,在彼空谷。生刍一束,其人如玉。毋金玉尔音,而有遐心。\n" + "-南有乔木,不可休思,汉有游女,不可求思。\n" + "-明明早已百无禁忌,偏偏你是一百零一。\n" + "-绸缪束薪,三星在天。今夕何夕,见此良人。子兮子兮,如此良人何。\n" + "-偷偷在草稿纸上写你名字的人是我,下雪时偷偷在雪地里写你名字的是我,对反光镜哈气写你名字的是我,为了和你偶遇不惜绕路的是我,想为你瘦下来的是我,可是不知道的是你。\n" + "-我从不喜欢迁就,却用最干净的真心为你妥协了很久。\n" + "-未来我的生活只有简单十二个字“睡前吻你,半夜抱你,醒来有你”。\n" + "-我渴望与你打架,也渴望抱抱你。\n" + "-喜欢就去表白,大不了连朋友都做不成,做朋友又有什么用,我又不缺朋友,我缺你。\n" + "-醒来觉得甚是爱你。\n" + "-“春天的原野里,你一个人正走着,对面走来一只可爱的小熊,浑身的毛活像天鹅绒,眼睛圆鼓鼓的。它这么对你说到:‘你好,小姐,和我一块打滚玩好么?’接着,你就和小熊抱在一起,顺着长满三叶草的山坡咕噜咕噜滚下去,整整玩了一大天。你说棒不棒?” \n" + "-“太棒了。” \n" + "-“我就这么喜欢你。”\n" + "-我只有两个心愿:你在身边,在你身边。\n" + "-海底月是天上月,眼前人是心上人。\n" + "-你的眉目笑语使我病了一场,热势退尽,还我寂寞的健康。\n" + "-清晨的微笑给你,深夜的晚安给你,情话给你,钥匙给你,一腔孤勇和余生几十年,全都给你。\n" + "-跟我走吧,我真的想要一个家了。\n" + "-理想归理想,现实归现实,你归我!\n" + "-你知道吗,我不想做你的路人,我想做你余生故事里的人。\n" + "-自从遇见你,人生苦短,甜长。\n" + "-我的每一支笔都知道你的名字。\n" + "-我爱宇宙,爱星星尘埃,爱孤单际遇。我爱山河湖海,爱叽喳鸟鸣,爱茵茵绿芽。我爱四季更迭,爱化冰后的叮咚小溪,爱一树簌簌下落的飘雪,然后停在你这里。\n" + "-假如你愿意,就去恋爱吧,爱我。\n" + "-我发觉我是一个坏小子,你爸爸说的一点也不错。可是我现在不坏了,我有了良心。我的良心就是你。\n" + "-我羡慕那些和你在同一座城市的人,可以和你擦肩而过,乘坐同一辆地铁,走同一条路,看同一处风景,他们甚至还可能在汹涌的人潮中不小心踩了你一脚说对不起,再听你温柔道声没关系,他们那么幸运,而我只能从心里对你说:我想你。\n" + "-跟你在一起的时光都很耀眼,因为天气好,因为天气不好,因为天气刚刚好,每一天,都很美好。\n" + "-月亮照回湖心,野鹤奔向闲云,我步入你。\n" + "-你要是愿意,我就永远爱你 。你要是不愿意,我就永远相思。\n" + "-我遇见你,我记得你,这座城市天生就适合恋爱,你天生就适合我的灵魂。\n" + "-你辛苦归辛苦,什么时候有空嫁给我。\n" + "-一个人不孤单,想一个人才孤单。\n" + "-任她们多漂亮,未及你矜贵。\n" + "-纵然世上有三千个你,每个我都要娶\n" + "-我喜欢你总是藏不住,捂住了嘴巴会从眼睛里跑出来。\n" + "-过去有人曾对我说,“一个人爱上小溪,是因为没有见过大海。” 而如今我终于可以说,“我已见过银河,但我仍只爱你这一颗星。”\n" + "-我嫉妒你身边每一个无关紧要的人。他们就那样轻而易举,见到我朝思暮想的你。\n" + "-为你,千千万万遍。\n" + "-滔滔不绝很容易,可我只想和你在一个慢下来的世界里交谈。\n" + "-我把我整个灵魂都给你,连同它的怪癖,耍小脾气,忽明忽暗,一千八百种坏毛病。它真讨厌,只有一点好,爱你。\n" + "-你的过去我来不及参与,你的未来我奉陪到底。\n" + "-我觉得你是精灵。谵语及诗句,最后我都会念给你听。\n" + "-我等你扑来\n" + "-像莽撞的幼兽猛然跃起\n" + "-一路撞碎了几迎春风\n" + "-乌糟糟的衣服襟子里卷带了马兰头的新鲜叶子。\n" + "-若逢新雪初霁,满月当空,下面平铺着皓影,上面流转着亮银,而你带笑地向我走来 月色与雪色之间,你是第三种绝色。\n" + "-你说出来 就存在,你造出来 就崇拜,你说存在 就存在,你叫我爱 我就爱\n" + "-我在世界上有三种爱的东西,太阳 月亮 和你,太阳是为了早晨,月亮是为了夜晚,而你 是为了永远\n" + "-我想和你过漫无目地的日子,把世人的烦恼当作久远而荒唐的故事\n" + "-原谅我和你找不到那么多的话题,背后却满嘴都是你。\n" + "-有一个大晴天我睡了午觉起来,看到阳台上晒着你的衬衫和我的裙子,他们投射到地板上的影子,让我联想到了一生一世之类的词语。\n" + "-你眼中有春与秋,胜过我见过爱过的一切山川与河流。\n" + "-就让我笨拙地喜欢你,从须臾到不朽,从一叶到知秋,然后,骑一匹白马,到人海里安家。\n" + "-原谅我太贪心,陪了你情窦初开,还想陪你两鬓斑白。\n" + "-不知为何,明明想和你说话。却骗你说,风雨正好,该去写点诗句。\n" + "-我见过千万人,像你的发,像你的眼,却都不是你的脸。\n" + "-我与命运做的数十笔交易中,遇见你这单,最划算。\n" + "-如果天天都能看到你,已经是今世最好的福气了。"; }
Java
UTF-8
4,255
2.09375
2
[]
no_license
package pojo.annotations; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; @Entity @Table(name = "cierrecaja", schema = "public") public class Cierrecaja implements java.io.Serializable { /** * */ private static final long serialVersionUID = -7065372722815220910L; private int idcierrecaja; private Usuario usuariocaja; private float saldoinicial; private float saldofinal; private Date fechacierre; private Date fechadesde; private Date fechahasta; private Estado estado; private Empresa empresa; private Usuario usuario; private Date fecha; private String iplog; public Cierrecaja() { } public Cierrecaja(int idcierrecaja,Usuario usuariocaja,float saldoinicial,float saldofinal, Date fechacierre,Date fechadesde,Date fechahasta,Estado estado,Empresa empresa, Usuario usuario,Date fecha,String iplog) { this.idcierrecaja = idcierrecaja; this.usuariocaja = usuariocaja; this.saldoinicial = saldoinicial; this.saldofinal = saldofinal; this.fechacierre = fechacierre; this.fechadesde = fechadesde; this.fechahasta = fechahasta; this.estado = estado; this.empresa = empresa; this.usuario = usuario; this.fecha = fecha; this.iplog = iplog; } @Id @Column(name = "idcierrecaja", unique = true, nullable = false) public int getIdcierrecaja() { return idcierrecaja; } public void setIdcierrecaja(int idcierrecaja) { this.idcierrecaja = idcierrecaja; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "idusuariocaja", nullable = false) public Usuario getUsuariocaja() { return usuariocaja; } public void setUsuariocaja(Usuario usuariocaja) { this.usuariocaja = usuariocaja; } @Column(name = "saldoinicial", nullable = false, precision = 8, scale = 8) public float getSaldoinicial() { return saldoinicial; } public void setSaldoinicial(float saldoinicial) { this.saldoinicial = saldoinicial; } @Column(name = "saldofinal", nullable = false, precision = 8, scale = 8) public float getSaldofinal() { return saldofinal; } public void setSaldofinal(float saldofinal) { this.saldofinal = saldofinal; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "fechacierre", nullable = false, length = 29) public Date getFechacierre() { return fechacierre; } public void setFechacierre(Date fechacierre) { this.fechacierre = fechacierre; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "fechadesde", nullable = false, length = 29) public Date getFechadesde() { return fechadesde; } public void setFechadesde(Date fechadesde) { this.fechadesde = fechadesde; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "fechahasta", nullable = false, length = 29) public Date getFechahasta() { return fechahasta; } public void setFechahasta(Date fechahasta) { this.fechahasta = fechahasta; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "idestado", nullable = false) public Estado getEstado() { return estado; } public void setEstado(Estado estado) { this.estado = estado; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "idempresa", nullable = false) public Empresa getEmpresa() { return empresa; } public void setEmpresa(Empresa empresa) { this.empresa = empresa; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "idusuario", nullable = false) public Usuario getUsuario() { return usuario; } public void setUsuario(Usuario usuario) { this.usuario = usuario; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "fecha", nullable = false, length = 29) public Date getFecha() { return fecha; } public void setFecha(Date fecha) { this.fecha = fecha; } @Column(name = "iplog", length = 20) public String getIplog() { return iplog; } public void setIplog(String iplog) { this.iplog = iplog; } }
Markdown
UTF-8
2,098
3.046875
3
[ "Apache-2.0" ]
permissive
--- title: "Managing Dagster Cloud deployments | Dagster Docs" --- # Managing Dagster Cloud deployments Learn how to deploy your code to Dagster Cloud, use command line tools, set up CI/CD, and define environment variables. <ArticleList> <ArticleListItem title="Managing full deployments" href="/dagster-cloud/managing-deployments/managing-deployments" ></ArticleListItem> <ArticleListItem title="Deployment settings reference" href="/dagster-cloud/managing-deployments/deployment-settings-reference" ></ArticleListItem> <ArticleListItem title="Setting up alerts" href="dagster-cloud/managing-deployments/setting-up-alerts" ></ArticleListItem> <ArticleListItem title="Adding and managing code locations" href="/dagster-cloud/managing-deployments/code-locations" ></ArticleListItem> <ArticleListItem title="Using the dagster-cloud CLI" href="/dagster-cloud/managing-deployments/dagster-cloud-cli" ></ArticleListItem> </ArticleList> --- ## Environment variables and secrets <ArticleList> <ArticleListItem title="Using environment variables and secrets" href="/dagster-cloud/managing-deployments/environment-variables-and-secrets" ></ArticleListItem> <ArticleListItem title="Setting up environment variables using Hybrid agent configuration" href="/dagster-cloud/managing-deployments/setting-environment-variables-dagster-cloud-agents" ></ArticleListItem> </ArticleList> --- ## Branch deployments <ArticleList> <ArticleListItem title="Using Branch Deployments for Continous Integration (CI)" href="/dagster-cloud/managing-deployments/branch-deployments" ></ArticleListItem> <ArticleListItem title="Setting up Branch Deployments with GitHub Actions" href="/dagster-cloud/managing-deployments/branch-deployments/using-branch-deployments-with-github" ></ArticleListItem> <ArticleListItem title="Setting up Branch Deployments with the dagster-cloud CLI" href="/dagster-cloud/managing-deployments/branch-deployments/using-branch-deployments" ></ArticleListItem> </ArticleList>
Java
UTF-8
18,541
1.8125
2
[]
no_license
/* * Copyright (C) 2014 Le Ngoc Anh <greendream.ait@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * */ package com.phatam.activities; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONObject; import android.content.Intent; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.view.LayoutInflater; import android.view.View; import android.view.animation.AnimationUtils; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.actionbarsherlock.widget.SearchView; import com.actionbarsherlock.widget.SearchView.OnQueryTextListener; import com.google.analytics.tracking.android.EasyTracker; import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu; import com.phatam.R; import com.phatam.adapters.SlidingMenuAdapter; import com.phatam.config.GlobalData; import com.phatam.fragment.FArtist; import com.phatam.fragment.FCategory; import com.phatam.fragment.FDonate; import com.phatam.fragment.FFavoriteVideosListView; import com.phatam.fragment.FHistoryVideosListView; import com.phatam.fragment.FHome; import com.phatam.fragment.FIntroduce; import com.phatam.fragment.FLoadmoreListVideo; import com.phatam.fragment.FSetting; import com.phatam.interfaces.OnConnectionStatusChangeListener; import com.phatam.interfaces.OnSlidingMenuItemClickedListener; import com.phatam.model.MSlidingMenuListItem; import com.phatam.playback.PhatAmConnectionStatusReceiver; import com.phatam.util.UtilConnection; import com.phatam.websevice.ApiUrl; import com.phatam.websevice.OnGetJsonListener; import com.phatam.websevice.ServiceGetRandomVideo; public class MainActivity extends SherlockFragmentActivity implements OnQueryTextListener, OnItemClickListener, OnConnectionStatusChangeListener { // Main menu on the left hand SlidingMenu mLeftSlidingMenu; ListView mListViewInLeftSlidingMenu; ArrayList<MSlidingMenuListItem> mSlidingMenuListItems; SlidingMenuAdapter mSlidingMenuAdapter; // Favorite on the right hand SlidingMenu mFavoriteVideo; FragmentManager mFragmentManager; FArtist mAuthorsFragment; FCategory mCategoryFragment; MenuItem mSearchMenuItem; @Override public void onCreate(Bundle savedInstanceState) { PhatAmConnectionStatusReceiver.addConnectionObserver(this); super.onCreate(savedInstanceState); GlobalData.context = getApplicationContext(); /** * Initial the activity */ setContentView(R.layout.activity_main); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setBackgroundDrawable( new ColorDrawable(getResources().getColor(R.color.blue))); /** * Setting Sliding Menu */ LayoutInflater inflater = getLayoutInflater(); View menu_frame = inflater.inflate(R.layout.layout_sliding_menu, null); // Initial list view for menu_frame mSlidingMenuAdapter = new SlidingMenuAdapter(this,createSlidingMenuListItems()); mListViewInLeftSlidingMenu = (ListView) menu_frame.findViewById(R.id.list_view_in_sliding_menu); mListViewInLeftSlidingMenu.setAdapter(mSlidingMenuAdapter); mListViewInLeftSlidingMenu.setDivider(null); mListViewInLeftSlidingMenu.setOnItemClickListener(this); mLeftSlidingMenu = new SlidingMenu(this); mLeftSlidingMenu.setMode(SlidingMenu.LEFT); mLeftSlidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN); mLeftSlidingMenu.setShadowWidthRes(R.dimen.shadow_width); mLeftSlidingMenu.setShadowDrawable(R.drawable.shadow); mLeftSlidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset); mLeftSlidingMenu.setFadeDegree(0.35f); mLeftSlidingMenu.attachToActivity(this, SlidingMenu.SLIDING_WINDOW); mLeftSlidingMenu.setMenu(menu_frame); /** * Show the home fragment for start-up * */ FHome homeFragment = new FHome(); homeFragment.setMainActivity(this); mFragmentManager = getSupportFragmentManager(); mFragmentManager.beginTransaction().replace(R.id.content_frame, homeFragment).commit(); onConnectionStatusChange(); } public ArrayList<MSlidingMenuListItem> createSlidingMenuListItems() { mSlidingMenuListItems = new ArrayList<MSlidingMenuListItem>(); // Create & Add Items "Top menu group" mSlidingMenuListItems.add(new MSlidingMenuListItem( MSlidingMenuListItem.ITEM_TYPE_TOP_MENU_GROUP, new OnSlidingMenuItemClickedListener() { // Action for Home button @Override public void doAction() { // Create a new fragment and specify the planet to show // based on position FHome fragment = new FHome(); // Insert the fragment by replacing any existing // fragment mFragmentManager.beginTransaction().replace(R.id.content_frame, fragment).addToBackStack(null).commit(); // Rename the action bar getSupportActionBar().setTitle(R.string.app_name); // close the sliding menu mLeftSlidingMenu.toggle(); } }, new OnSlidingMenuItemClickedListener() { // Action for Favorite button @Override public void doAction() { // Create a new fragment and specify the planet to show // based on position FFavoriteVideosListView fragment = new FFavoriteVideosListView(); // Insert the fragment by replacing any existing // fragment mFragmentManager.beginTransaction().replace(R.id.content_frame, fragment).addToBackStack(null).commit(); // Rename the action bar getSupportActionBar().setTitle(R.string.str_favorite); // close the sliding menu mLeftSlidingMenu.toggle(); } }, new OnSlidingMenuItemClickedListener() { // Action for History button @Override public void doAction() { // Create a new fragment and specify the planet to show // based on position FHistoryVideosListView fragment = new FHistoryVideosListView(); // Insert the fragment by replacing any existing // fragment mFragmentManager.beginTransaction().replace(R.id.content_frame, fragment).addToBackStack(null).commit(); // Rename the action bar getSupportActionBar().setTitle(R.string.str_history); // close the sliding menu mLeftSlidingMenu.toggle(); } }) ); // Create & Add Items CATEGORY "PHẬT ÂM" mSlidingMenuListItems.add(new MSlidingMenuListItem( MSlidingMenuListItem.ITEM_TYPE_CATEGORY_NAME, 0, this.getString(R.string.sliding_menu_category_phatam), "", null) ); // Create & Add Items "Chuyên mục" mSlidingMenuListItems.add(new MSlidingMenuListItem( MSlidingMenuListItem.ITEM_TYPE_SCREEN_IN_CATEGORY, R.drawable.ic_menu_category, this.getString(R.string.sliding_menu_lable_category), "", new OnSlidingMenuItemClickedListener() { @Override public void doAction() { // Create a new fragment and specify the planet to show // based on position FCategory fragment = new FCategory(); // Insert the fragment by replacing any existing // fragment mFragmentManager.beginTransaction().replace(R.id.content_frame, fragment).addToBackStack(null).commit(); // Rename the action bar getSupportActionBar().setTitle(R.string.sliding_menu_lable_category); // close the sliding menu mLeftSlidingMenu.toggle(); } }) ); // Create & Add Items "Tác giả" mSlidingMenuListItems.add(new MSlidingMenuListItem( MSlidingMenuListItem.ITEM_TYPE_SCREEN_IN_CATEGORY, R.drawable.ic_menu_artist, this.getString(R.string.sliding_menu_lable_artist), "", new OnSlidingMenuItemClickedListener() { @Override public void doAction() { // Create a new fragment and specify the planet to show // based on position FArtist fragment = new FArtist(); fragment.setUrl(ApiUrl.getAllArtistNameUrl(ApiUrl.ORDER_BY_ARTIST_VIDEO_COUNT, -1)); // Insert the fragment by replacing any existing // fragment mFragmentManager.beginTransaction().replace(R.id.content_frame, fragment).addToBackStack(null).commit(); // Rename the action bar getSupportActionBar().setTitle(R.string.sliding_menu_lable_artist); // close the sliding menu mLeftSlidingMenu.toggle(); } }) ); // Create & Add Items "Video mới" mSlidingMenuListItems.add(new MSlidingMenuListItem( MSlidingMenuListItem.ITEM_TYPE_SCREEN_IN_CATEGORY, R.drawable.ic_menu_new, this.getString(R.string.sliding_menu_lable_new_videos), "", new OnSlidingMenuItemClickedListener() { @Override public void doAction() { // Create a new fragment and specify the planet to show // based on position FLoadmoreListVideo fragment = new FLoadmoreListVideo(); fragment.setUrl(ApiUrl.getNewVideosUrl(-1)); // Insert the fragment by replacing any existing // fragment mFragmentManager.beginTransaction().replace(R.id.content_frame, fragment).addToBackStack(null).commit(); // Rename the action bar getSupportActionBar().setTitle(R.string.sliding_menu_lable_new_videos); // close the sliding menu mLeftSlidingMenu.toggle(); } }) ); // Create & Add Items "Video nổi bật" mSlidingMenuListItems.add(new MSlidingMenuListItem( MSlidingMenuListItem.ITEM_TYPE_SCREEN_IN_CATEGORY, R.drawable.ic_menu_top, this.getString(R.string.sliding_menu_lable_top_videos), "", new OnSlidingMenuItemClickedListener() { @Override public void doAction() { // Create a new fragment and specify the planet to show // based on position FLoadmoreListVideo fragment = new FLoadmoreListVideo(); fragment.setUrl(ApiUrl.getTopVideoUrl(-1)); // Insert the fragment by replacing any existing // fragment mFragmentManager.beginTransaction().replace(R.id.content_frame, fragment).addToBackStack(null).commit(); // Rename the action bar getSupportActionBar().setTitle(R.string.sliding_menu_lable_top_videos); // close the sliding menu mLeftSlidingMenu.toggle(); } }) ); // Create & Add Items "Video Ngẫu nhiên" mSlidingMenuListItems.add(new MSlidingMenuListItem( MSlidingMenuListItem.ITEM_TYPE_SCREEN_IN_CATEGORY, R.drawable.ic_menu_random, this.getString(R.string.sliding_menu_lable_random_videos), "", new OnSlidingMenuItemClickedListener() { @Override public void doAction() { // close the sliding menu mLeftSlidingMenu.toggle(); ServiceGetRandomVideo service = new ServiceGetRandomVideo(); service.addOnGetJsonListener(new OnGetJsonListener() { @Override public void onGetJsonFail(String response) { // TODO Auto-generated method stub } @Override public void onGetJsonCompleted(String response) { try { JSONObject json = new JSONObject(response); JSONArray array = json.getJSONArray("videos"); JSONObject videoJsonObject = array.getJSONObject(0); String uniq_id = videoJsonObject.getString("uniq_id"); // Start activity Intent i = new Intent(MainActivity.this, FullVideoInfoActivity.class); i.putExtra(FullVideoInfoActivity.INFO_VIDEO_UNIQUE_ID, uniq_id); startActivity(i); } catch (Exception e) { } } }); service.getRandomVideo(); } }) ); // Create & Add Items CATEGORY "ỨNG DỤNG" mSlidingMenuListItems.add(new MSlidingMenuListItem( MSlidingMenuListItem.ITEM_TYPE_CATEGORY_NAME, 0, this.getString(R.string.sliding_menu_category_aplication), "", null) ); // Create & Add Items "Cài đặt" mSlidingMenuListItems.add(new MSlidingMenuListItem( MSlidingMenuListItem.ITEM_TYPE_SCREEN_IN_CATEGORY, R.drawable.ic_menu_setting, this.getString(R.string.sliding_menu_lable_setting), "", new OnSlidingMenuItemClickedListener() { @Override public void doAction() { // Create a new fragment and specify the planet to show // based on position FSetting fragment = new FSetting(); // Insert the fragment by replacing any existing // fragment mFragmentManager.beginTransaction().replace(R.id.content_frame, fragment).addToBackStack(null).commit(); // Rename the action bar getSupportActionBar().setTitle(R.string.sliding_menu_lable_setting); // close the sliding menu mLeftSlidingMenu.toggle(); } }) ); // Create & Add Items "Giới thiệu" mSlidingMenuListItems.add(new MSlidingMenuListItem( MSlidingMenuListItem.ITEM_TYPE_SCREEN_IN_CATEGORY, R.drawable.ic_menu_introduce, this.getString(R.string.sliding_menu_lable_introduce), "", new OnSlidingMenuItemClickedListener() { @Override public void doAction() { // Create a new fragment and specify the planet to show // based on position FIntroduce fragment = new FIntroduce(); // Insert the fragment by replacing any existing // fragment mFragmentManager.beginTransaction().replace(R.id.content_frame, fragment).addToBackStack(null).commit(); // Rename the action bar getSupportActionBar().setTitle(R.string.sliding_menu_lable_introduce); // close the sliding menu mLeftSlidingMenu.toggle(); } }) ); // Create & Add Items "Ủng hộ" mSlidingMenuListItems.add(new MSlidingMenuListItem( MSlidingMenuListItem.ITEM_TYPE_SCREEN_IN_CATEGORY, R.drawable.ic_menu_donate, this.getString(R.string.sliding_menu_lable_donate), "", new OnSlidingMenuItemClickedListener() { @Override public void doAction() { // Create a new fragment and specify the planet to show // based on position FDonate fragment = new FDonate(); // Insert the fragment by replacing any existing // fragment mFragmentManager.beginTransaction().replace(R.id.content_frame, fragment).addToBackStack(null).commit(); // Rename the action bar getSupportActionBar().setTitle(R.string.sliding_menu_lable_donate); // close the sliding menu mLeftSlidingMenu.toggle(); } }) ); // Create & Add Items "Đóng ứng dụng" mSlidingMenuListItems.add(new MSlidingMenuListItem( MSlidingMenuListItem.ITEM_TYPE_SCREEN_IN_CATEGORY, R.drawable.ic_menu_shoutdown, this.getString(R.string.sliding_menu_lable_shoutdown), "", new OnSlidingMenuItemClickedListener() { @Override public void doAction() { MainActivity.this.finish(); } }) ); return mSlidingMenuListItems; } @Override protected void onPostResume() { // TODO Auto-generated method stub super.onPostResume(); } @Override public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { try { mSlidingMenuListItems.get(position).getOnItemClickHandler() .doAction(); } catch (NullPointerException e) { } } @Override public void onBackPressed() { if (mLeftSlidingMenu.isMenuShowing()) { mLeftSlidingMenu.toggle(); } else { super.onBackPressed(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: mLeftSlidingMenu.toggle(); return true; } return super.onOptionsItemSelected(item); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Create the search view SearchView searchView = new SearchView(getSupportActionBar() .getThemedContext()); searchView.setQueryHint(getString(R.string.search_hint)); searchView.setOnQueryTextListener(this); menu.add(getString(R.string.action_search)) .setIcon(R.drawable.ic_action_search) .setActionView(searchView) .setShowAsAction( MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW); mSearchMenuItem = menu.getItem(0); return super.onCreateOptionsMenu(menu); } @Override public boolean onQueryTextSubmit(String query) { if (mSearchMenuItem != null) { mSearchMenuItem.collapseActionView(); } Intent iKeyWord = new Intent(this, SearchResultsActivity.class); iKeyWord.putExtra("KEY_WORD", query); if (getSupportActionBar().getTitle().equals( getString(R.string.sliding_menu_lable_artist))) { iKeyWord.putExtra("PREFER_RESULT", SearchResultsActivity.PREFER_RESULT_ARTIST); } else if (getSupportActionBar().getTitle().equals( getString(R.string.sliding_menu_lable_category))) { iKeyWord.putExtra("PREFER_RESULT", SearchResultsActivity.PREFER_RESULT_VIDEO); } startActivity(iKeyWord); return false; } @Override public boolean onQueryTextChange(String newText) { return false; } @Override public void onStart() { super.onStart(); // The rest of your onStart() code. EasyTracker.getInstance(this).activityStart(this); // Add this method. } @Override public void onStop() { super.onStop(); // The rest of your onStop() code. EasyTracker.getInstance(this).activityStop(this); // Add this method. } @Override public void onConnectionStatusChange() { // TODO Auto-generated method stub if (UtilConnection.getConnectivityStatus(this) == UtilConnection.TYPE_NOT_CONNECTED) { this.findViewById(R.id.layoutConnectionError).setVisibility(View.VISIBLE); this.findViewById(R.id.layoutConnectionError).startAnimation(AnimationUtils.loadAnimation(this, R.animator.appear)); } else { this.findViewById(R.id.layoutConnectionError).setVisibility(View.GONE); this.findViewById(R.id.layoutConnectionError).startAnimation(AnimationUtils.loadAnimation(this, R.animator.disappear)); } } }
Shell
UTF-8
984
3.484375
3
[]
no_license
#!/bin/bash downloadDir="/var/www/nextcloud/data/" downloadList="${downloadDir}" userDir="" links=$(sudo cat ${downloadList}) if [ ! -z $links ]; then # Connect to VPN windscribe connect DE tempLinks=$links for link in $links do tempLinks=${tempLinks/$link/""} # Download file sudo wget -P "${downloadDir}${userDir}" "${link//[$'\t\r\n']}" truncate -s 0 "${downloadList}" for tempLink in ${tempLinks} do echo $tempLink >> ${downloadList} done done # Assign downloaded file to user + group www-data sudo chown www-data:www-data -R "${downloadDir}${userDir}" # Disconnect from VPN windscribe disconnect # Rescan uploaded files sudo -u www-data php /var/www/nextcloud/occ files:scan --path="${userDir}" fi
PHP
UTF-8
424
2.90625
3
[]
no_license
<?php class user{ private $email; private $name; private $birthday; private $gender; private $sdt; public function __construct($email, $name, $birthday,$gender,$sdt) { $this->email = $email; $this->name = $name; $this->birthday = $birthday; $this->gender = $gender; $this->sdt = $sdt; } } ?>
Java
UTF-8
1,936
3.328125
3
[]
no_license
package animation; import biuoop.DrawSurface; import biuoop.Sleeper; import running.Counter; import inerfaces.Animation; import running.SpriteCollection; import java.awt.Color; /** * This func will countdown each game start's. * It will implement animation, so it can be drawn on given surface. */ public class CountdownAnimation implements Animation { private double numOfSeconds; private int countFrom; private SpriteCollection gameScreen; private Counter countdown; /** * @param numOfSeconds seconds each digit will appear on screen. * @param countFrom second we countdown from. * @param gameScreen all the objects drew before. * This func will countdown before each game start's. */ public CountdownAnimation(double numOfSeconds, int countFrom, SpriteCollection gameScreen) { this.numOfSeconds = numOfSeconds; this.countFrom = countFrom; this.gameScreen = gameScreen; this.countdown = new Counter(countFrom); } /** * @param d the surface upon we draw. * @param dt frame speed. * draw on the surface. */ public void doOneFrame(DrawSurface d, double dt) { this.gameScreen.drawAllOn(d); d.setColor(Color.white.darker()); d.drawText(400, 400, this.countdown.toString(), 50); long pauseTime = (long) ((this.numOfSeconds / this.countFrom) * 1000); Sleeper sleep = new Sleeper(); if (this.countdown.getValue() < 3) { sleep.sleepFor(pauseTime); } this.countdown.decrease(1); } /** * @return boolean val. * This func will check all the conditions to stop drawing frames. */ public boolean shouldStop() { if (this.countdown.getValue() == 0) { return true; } return false; } }
Markdown
UTF-8
3,942
2.828125
3
[]
no_license
# Article 5 I. - Le montant de l'aide prévue au VI de l'article 3 de la loi du 13 juin 1998 susvisée, ainsi que celui de chacune des majorations, est forfaitaire et fixé, par salarié, pour chaque année d'exécution de la convention. La majoration prévue au troisième alinéa du VI du même article est attribuée au plus pendant trois ans. Un barème annexé au présent décret fixe les montants de l'aide et de chacune des majorations. Les montants de l'aide et de la majoration prévue au troisième alinéa du VI de l'article 3 de la loi du 13 juin 1998 susvisée varient conformément à ce barème. Le barème de l'aide dont bénéficie l'entreprise est celui applicable à la date de la signature de l'accord d'entreprise servant de base à la convention signée ou, à défaut, dans le cas de l'application d'une convention ou d'un accord de branche étendus ou agréés, la date de dépôt de la demande de convention. Toutefois si la demande de convention est déposée en application d'une convention collective ou d'un accord de branche étendus ou agréés conclus antérieurement au 1er juillet 1999, le barème applicable est celui en vigueur à la date de la conclusion dudit accord sous réserve que la demande de convention soit déposée avant l'expiration d'un délai de trois mois courant à compter de la publication au Journal officiel de l'arrêté d'extension. En tout état de cause, si la réduction du temps de travail n'est pas effective dans les trois mois suivant la signature de la convention entre l'Etat et l'entreprise, le barème applicable est celui en vigueur à la date de la réduction du temps de travail, sauf circonstances exceptionnelles appréciées par l'autorité administrative. II. - Lorsque, en application du troisième alinéa du IV de l'article 3 de la loi du 13 juin 1998 susvisée, l'entreprise opère une nouvelle réduction du temps de travail, celle-ci doit être organisée par un avenant à l'accord d'entreprise. Celui-ci précise notamment l'ampleur de la nouvelle réduction du temps de travail ainsi que le nombre d'embauches auxquelles l'employeur s'engage à procéder et la durée pendant laquelle l'employeur s'engage à maintenir l'emploi. La majoration du montant de l'aide prévue au troisième alinéa du IV de l'article 3 de la loi du 13 juin 1998 susvisée peut être accordée par avenant à la convention liant l'Etat et l'entreprise. Le délai dont dispose l'employeur pour réaliser les embauches est identique à celui fixé au quatrième alinéa du IV de l'article 3 de la loi du 13 juin 1998 susvisée. A compter de la dernière embauche, l'employeur doit maintenir l'effectif moyen annuel de l'entreprise ou de l'établissement mentionné dans la convention initiale augmenté de la totalité des embauches auxquelles l'employeur s'est engagé dans la convention conclue avec le représentant de l'Etat ainsi que dans l'avenant à cette convention. La majoration du montant de l'aide prend effet à la date de l'entrée en vigueur de la nouvelle réduction du temps de travail. III. - La majoration spécifique prévue au troisième alinéa du VI de l'article 3 de la loi du 13 juin 1998 susvisée est ouverte aux entreprises dont l'effectif est constitué d'au moins 60 % d'ouvriers au sens des conventions collectives et d'au moins 70 % de salariés dont les gains et rémunérations mensuels sont inférieurs ou égaux à 169 fois le salaire minimum de croissance majoré de 50 %. Pour l'application de l'alinéa précédent, sont pris en compte les gains et rémunérations tels que définis à l'article L. 242-1 du code de la sécurité sociale. IV. - La prolongation de la durée de l'aide prévue au V de l'article 3 de la loi du 13 juin 1998 susvisée est accordée notamment au vu des conditions d'exécution des mesures de prévention et d'accompagnement des licenciements qui ont permis le bénéfice de la convention initiale.
Python
UTF-8
3,137
2.546875
3
[]
no_license
from collections import namedtuple import argparse import torch import numpy as np import torch.nn as nn import torch.nn.functional as F from os.path import realpath, join, dirname import time CNNModel = namedtuple("CNNModel", "input_x input_y keep_prob output loss train_op") SCRIPT_DIR = dirname(realpath(__file__)) DATA_DIR = join(dirname(SCRIPT_DIR), "data") def pad_same(in_dim, ks, stride, dilation=1): """ Refernces: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/framework/common_shape_fns.h https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/framework/common_shape_fns.cc#L21 """ assert stride > 0 assert dilation >= 1 effective_ks = (ks - 1) * dilation + 1 out_dim = (in_dim + stride - 1) // stride p = max(0, (out_dim - 1) * stride + effective_ks - in_dim) padding_before = p // 2 padding_after = p - padding_before return padding_before, padding_after class Conv2dPaddingSame(nn.Module): def __init__(self, input_size, filters, kernel_size): self.W = nn.Parameter([filters, input_size, kernel_size, kernel_size]) self.b = nn.Parameter([filters]) class Model(nn.Module): def __init__(self): super().__init__() self.layer1 = nn.Conv2d(1, 64, 5, padding=pad_same(28, 5, 1)) self.layer2 = nn.Conv2d(64, 64, 5, padding=pad_same(14, 5, 1)) self.fc1 = nn.Linear(7 * 7 * 64, 1024) self.fc2 = nn.Linear(1024, 10) self.dropout = nn.Dropout(0.5) self.cross_ent_loss = nn.CrossEntropyLoss() def forward(self, x, y): out = x.reshape([x.shape[0], 1, 28, 28]) out = torch.relu(self.layer1(out)) out = F.max_pool2d(out, 2) out = torch.relu(self.layer2(out)) out = F.max_pool2d(out, 2) out = torch.relu(torch.reshape(out, [out.shape[0], 7 * 7 * 64])) out = torch.relu(self.fc1(out)) out = self.dropout(out) out = self.fc2(out) return self.cross_ent_loss(out, y) def main(): parser = argparse.ArgumentParser() parser.add_argument("--batch_size", default=256, type=int) parser.add_argument("--epochs", default=10, type=int) args = parser.parse_args() model = Model() if torch.cuda.is_available(): model.cuda() X = np.load(join(DATA_DIR, "mnist", "train_x.npy")) Y = np.load(join(DATA_DIR, "mnist", "train_y.npy")) batch_size = args.batch_size print(len(X)) optimizer = torch.optim.SGD(model.parameters(), lr=0.01) for iteration in range(args.epochs): t0 = time.time() for i in range(0, len(X), batch_size): batch_x = torch.FloatTensor(X[i:i + batch_size]) batch_y = torch.LongTensor(Y[i:i + batch_size]) if torch.cuda.is_available(): batch_x = batch_x.cuda() batch_y = batch_y.cuda() batch_loss = model(batch_x, batch_y) model.zero_grad() batch_loss.backward() optimizer.step() t1 = time.time() print("%.3f" % (t1 - t0)) if __name__ == "__main__": main()
Swift
UTF-8
2,184
3
3
[ "MIT" ]
permissive
// // SMEvent.swift // StateMachine // // Created by coderyi on 2020/11/29. // import UIKit open class SMEvent: NSObject, NSCoding, NSCopying { var shouldFireEventBlock: ((_ event: SMEvent, _ transition: SMTransition?) -> Bool)? var willFireEventBlock: ((_ event: SMEvent, _ transition: SMTransition?) -> Bool)? var didFireEventBlock: ((_ event: SMEvent, _ transition: SMTransition?) -> Bool)? public let name: String public let destinationState: SMState public let sourceStates: [SMState] public init(_ name: String, sourceStates: [SMState], destinationState: SMState) { self.sourceStates = sourceStates self.name = name self.destinationState = destinationState } public func setShouldFireEventBlock(_ block: @escaping(_ event: SMEvent, _ transition: SMTransition?) -> Bool) { shouldFireEventBlock = block } public func setWillFireEventBlock(_ block: @escaping(_ event: SMEvent, _ transition: SMTransition?) -> Bool) { willFireEventBlock = block } public func setDidFireEventBlock(_ block: @escaping(_ event: SMEvent, _ transition: SMTransition?) -> Bool) { didFireEventBlock = block } public func encode(with aCoder: NSCoder) { aCoder.encode(self.name, forKey: "name") aCoder.encode(self.sourceStates, forKey: "sourceStates") aCoder.encode(self.destinationState, forKey: "destinationState") } public required init?(coder aDecoder: NSCoder) { self.name = aDecoder.decodeObject(forKey: "name") as? String ?? "" self.sourceStates = aDecoder.decodeObject(forKey: "sourceStates") as? [SMState] ?? [] self.destinationState = aDecoder.decodeObject(forKey: "destinationState") as? SMState ?? SMState("") } open func copy(with zone: NSZone? = nil) -> Any { let copy = SMEvent(name, sourceStates: sourceStates, destinationState: destinationState) copy.shouldFireEventBlock = shouldFireEventBlock copy.willFireEventBlock = willFireEventBlock copy.didFireEventBlock = didFireEventBlock return copy } }
Java
UTF-8
19,670
2.09375
2
[]
no_license
/* * 创建日期 2005-7-14 * * 要更改此生成的文件的模板,请转至 * 窗口 - 首选项 - Java - 代码样式 - 代码模板 */ package cn.com.infosec.netseal.common.util.p10; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.Method; import java.math.BigInteger; import java.security.KeyFactory; import java.security.PublicKey; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.security.interfaces.RSAPublicKey; import java.security.spec.RSAPublicKeySpec; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import cn.com.infosec.asn1.DERInputStream; import cn.com.infosec.asn1.DERObject; import cn.com.infosec.asn1.DEROctetString; import cn.com.infosec.asn1.DEROutputStream; import cn.com.infosec.crypto.CryptoException; import cn.com.infosec.util.Base64; /** * @author hyoffice * * 要更改此生成的类型注释的模板,请转至 窗口 - 首选项 - Java - 代码样式 - 代码模板 */ public class CryptoUtil { public static boolean debug = false; static byte JNI_RSA_KEY_NAME = 0x10; static byte JNI_RSA_PLAIN_DATA = 0x20; static byte JNI_RSA_SIGNATURE = 0x40; static byte JNI_RSA_KEY_PARM_N = 0x01; static byte JNI_RSA_KEY_PARM_KE = 0x02; static byte JNI_RSA_ENCHASH = 0x41; static byte JNI_RSA_DECHASH = 0x42; static byte JNI_SYM_ENCSECKEY = 0x43; static byte JNI_SYM_ENC_DATA = 0x44; static byte JNI_SYM_ALG_IV = 0x45; final static String cn = "2.5.4.3"; private static final String BEGIN_CERT_REQ = "-----BEGIN CERTIFICATE REQUEST-----"; /** End certificate signing request */ private static final String END_CERT_REQ = "-----END CERTIFICATE REQUEST-----"; /** The maximum length of lines in certificate signing requests */ private static final int CERT_REQ_LINE_LENGTH = 76; private static final long DATE_2050 = 2524579200000l; public static final byte[] DERNULL = new byte[] { (byte) 05, (byte) 00 }; public static final byte[] DERTRUE = new byte[] { (byte) 01, (byte) 01, (byte) 0xff }; /** * */ public CryptoUtil() { super(); // 自动生成构造函数存根 } public static String getExtern(byte[] a) throws Exception { String externvalue = null; try { ByteArrayInputStream bint = new ByteArrayInputStream(a); DERInputStream dint = new DERInputStream(bint); DEROctetString doct = (DEROctetString) dint.readObject(); byte[] tmp = doct.getOctets(); bint = new ByteArrayInputStream(tmp); dint = new DERInputStream(bint); DERObject dobj = dint.readObject(); Class dc = dobj.getClass(); Class c1 = dc.forName(dc.getName()); Method m = c1.getMethod("getString", null); String tmp1 = (String) m.invoke(dobj, null); externvalue = tmp1; } catch (Exception ex) { throw new Exception(ex); } return externvalue; } private static byte[] cnid = new byte[] { 0x55, 0x04, 0x03 }; public static ArrayList getcrldp(byte[] a) throws IOException { ArrayList cnlist = new ArrayList(); if ((a != null) && (a.length > 0)) { for (int i = 0, ilength = a.length; i < ilength; i++) { boolean match = false; for (int j = 0, jlength = cnid.length; j < jlength; j++) { if ((i + j) < ilength) { if (a[i + j] == cnid[j]) { match = true; } else { match = false; i += j; break; } } } if (match) { i += 4; int clength = 0xff & a[i]; i += 1; byte[] cnbs = new byte[clength]; System.arraycopy(a, i, cnbs, 0, clength); String cnstr = new String(cnbs); // System.out.println( cnstr ); cnlist.add(cnstr); i += clength; } } } return cnlist; } /* * public static String getcrldp( byte[] a ) throws IOException { if( a == null ) return null; String crldp = null; ByteArrayInputStream bint = new ByteArrayInputStream( a ); DERInputStream dint = * new DERInputStream( bint ); DEROctetString doct = ( DEROctetString ) dint.readObject(); byte[] tmp = doct.getOctets(); bint = new ByteArrayInputStream( tmp ); dint = new DERInputStream( bint ); * // CRLDistPoint crl=CRLDistPoint.getInstance(dint); DERConstructedSequence dconstr = ( DERConstructedSequence ) ( dint .readObject() ); //System.out.print( "de=" + dconstr.size() ); for( int i * = 0 ; i < dconstr.size() ; i++ ) { DERConstructedSequence dconstr0 = ( DERConstructedSequence ) ( dconstr .getObjectAt( 0 ) ); * * DERTaggedObject dert = ( DERTaggedObject ) dconstr0.getObjectAt( 0 ); DERTaggedObject dert1 = ( DERTaggedObject ) dert.getObject(); * * DERTaggedObject dert2 = ( DERTaggedObject ) dert1.getObject(); if( dert2.getTagNo() == 4 ) { DERConstructedSequence dconstr2 = ( DERConstructedSequence ) dert2 .getObject(); DERConstructedSet * dconsettmp; DERConstructedSequence dconsequencetmp; for( int j = 0 ; j < dconstr2.size() ; j++ ) { dconsettmp = ( DERConstructedSet ) dconstr2.getObjectAt( j ); dconsequencetmp = ( * DERConstructedSequence ) dconsettmp .getObjectAt( 0 ); if( cn.equals( ( ( DERObjectIdentifier ) dconsequencetmp .getObjectAt( 0 ) ).getId() ) ) { crldp = ( ( DERString ) * dconsequencetmp.getObjectAt( 1 ) ) .getString().toLowerCase(); } } } // else // { // System.out.println("crl dp type is url"); // // System.out.println(new String( // * ((DEROctetString)dert2.getObject()).getOctets())); // // System.out.println( dert2.getObject()); // } } return crldp; * * } */ public static boolean compereDN(String DN1, String JKSDN) { if ((DN1 == null) || (JKSDN == null)) return false; if (DN1.equals(JKSDN)) return true; else { String[] temp = JKSDN.split(","); String turnDN = temp[temp.length - 1].trim(); for (int i = (temp.length - 2); i >= 0; i--) { turnDN = turnDN + "," + temp[i].trim(); } if (DN1.equals(turnDN)) return true; } return false; } public static boolean compereBytes(byte[] bytes1, byte[] bytes2) { if (bytes1 == bytes2) return true; else { if ((bytes1 == null) || (bytes2 == null)) return false; else if (bytes1.length != bytes2.length) return false; else { for (int i = 0, length = bytes1.length; i < length; i++) { if (bytes1[i] != bytes2[i]) return false; } return true; } } } public static String trimDN(String dn) { String[] temp = dn.split(","); StringBuffer buffer = new StringBuffer(); for (int i = 0; i < temp.length; i++) { buffer.append(temp[i].trim() + ","); } String value = buffer.toString(); return value.substring(0, value.length() - 1); } public static String turnDN(String DN) { String[] temp = DN.split(","); String turnDN = temp[temp.length - 1].trim(); for (int i = (temp.length - 2); i >= 0; i--) { turnDN = turnDN + "," + temp[i].trim(); } return turnDN; } public static String createbase64csr(PKCS10CertificationRequest csr) throws Exception { // Get Base 64 encoding of CSR ByteArrayOutputStream baos = new ByteArrayOutputStream(); DEROutputStream deros = new DEROutputStream(baos); deros.writeObject(csr.getDERObject()); String sTmp = new String(Base64.encode(baos.toByteArray())); // CSR is bounded by a header and footer String sCsr = BEGIN_CERT_REQ + "\n"; // Limit line lengths between header and footer for (int iCnt = 0; iCnt < sTmp.length(); iCnt += CERT_REQ_LINE_LENGTH) { int iLineLength; if ((iCnt + CERT_REQ_LINE_LENGTH) > sTmp.length()) { iLineLength = (sTmp.length() - iCnt); } else { iLineLength = CERT_REQ_LINE_LENGTH; } sCsr += sTmp.substring(iCnt, (iCnt + iLineLength)) + "\n"; } // Footer sCsr += END_CERT_REQ + "\n"; return sCsr; } public static byte[] constructHardData(byte tag, byte[] sourcedata) { int intLen = sourcedata.length; byte[] bytelen = getDataLength(intLen); byte[] result = new byte[5 + intLen]; result[0] = tag; result[1] = bytelen[0]; result[2] = bytelen[1]; result[3] = bytelen[2]; result[4] = bytelen[3]; for (int i = 0; i < intLen; i++) result[5 + i] = sourcedata[i]; return result; } public static byte[] getDataLength(int intLen) { byte[] result = new byte[4]; result[0] = (byte) (0xff & (intLen >> 24)); result[1] = (byte) (0xff & (intLen >> 16)); result[2] = (byte) (0xff & (intLen >> 8)); result[3] = (byte) (0xff & (intLen >> 0)); return result; } public static PublicKey getPublicKey(byte[] pubkeyN, byte[] pubkeyE) throws Exception { try { // 根据PKCS1标准,N和E必须为正数, BigInteger biN = new BigInteger(1, pubkeyN); BigInteger biE = new BigInteger(1, pubkeyE); RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(biN, biE); KeyFactory fact; fact = KeyFactory.getInstance("RSA", "INFOSEC"); PublicKey pubKey = fact.generatePublic(pubKeySpec); return pubKey; } catch (Exception ex) { String msg = "Can not convert PublicKey( N & E) bytearray to PublicKey object"; throw new Exception(msg, ex); } } public static byte[] clearHardData(byte[] sourcedata) { byte[] byteLen = { sourcedata[1], sourcedata[2], sourcedata[3], sourcedata[4] }; int intLen = getDataLength(byteLen); byte[] result = new byte[intLen]; for (int i = 0; i < intLen; i++) result[i] = sourcedata[5 + i]; return result; } public static byte[] constructHardPublicKey(PublicKey pk) throws CryptoException { // 将N , E 两个部分分离开 // 格式:0x01 + length(4) + dataN + 0x02 + length(4) + dataE // PublicKey pk = CryptoUtil.getPublicKey("RSA", pubkey); RSAPublicKey rpk = (RSAPublicKey) pk; byte[] pk_n = rpk.getModulus().toByteArray(); byte[] pk_e = rpk.getPublicExponent().toByteArray(); int intLen_N = pk_n.length; int intLen_E = pk_e.length; byte[] bytePkn = getDataLength(intLen_N); byte[] bytePke = getDataLength(intLen_E); /** * 长度 N的tag(1位) + N的长度描述(4位) + N的长度 + E的tag(1位) + E的长度描述(4位) + E的长度 */ int totallen = 1 + 4 + intLen_N + 1 + 4 + intLen_E; byte[] resultPubkey = new byte[totallen]; resultPubkey[0] = JNI_RSA_KEY_PARM_N; resultPubkey[1] = bytePkn[0]; resultPubkey[2] = bytePkn[1]; resultPubkey[3] = bytePkn[2]; resultPubkey[4] = bytePkn[3]; for (int i = 0; i < intLen_N; i++) resultPubkey[5 + i] = pk_n[i]; /** * JNI_RSA_KEY_PARM_KE N的tag下标(1位)+长度描述(4位)+ N长度 + E的tag描述(1位) */ int Pos_E = 0 + 4 + intLen_N + 1; resultPubkey[Pos_E] = JNI_RSA_KEY_PARM_KE; resultPubkey[Pos_E + 1] = bytePke[0]; resultPubkey[Pos_E + 2] = bytePke[1]; resultPubkey[Pos_E + 3] = bytePke[2]; resultPubkey[Pos_E + 4] = bytePke[3]; int curPos_E = Pos_E + 5; for (int i = 0; i < intLen_E; i++) resultPubkey[curPos_E + i] = pk_e[i]; return resultPubkey; } public static int getDataLength(byte[] len) { BigInteger bi = new BigInteger(len); String result = bi.toString(10); return Integer.valueOf(result).intValue(); } public static byte[][] splitHardPublicKey(byte[] hardpubkey) { byte[] byteLen_N = { hardpubkey[1], hardpubkey[2], hardpubkey[3], hardpubkey[4] }; int intLen_N = getDataLength(byteLen_N); // System.out.println("pubkey_N length :" + intLen_N); // N的tag下标(1位)+长度描述(4位)+N + E的tag描述(1位) int Pos = 0 + 4 + intLen_N + 1; byte[] byteLen_E = { hardpubkey[Pos + 1], hardpubkey[Pos + 2], hardpubkey[Pos + 3], hardpubkey[Pos + 4] }; int intLen_E = getDataLength(byteLen_E); // System.out.println("pubkey_E length :" + intLen_E); byte[] pubkey_N = new byte[intLen_N]; byte[] pubkey_E = new byte[intLen_E]; System.arraycopy(hardpubkey, 5, pubkey_N, 0, intLen_N); System.arraycopy(hardpubkey, Pos + 5, pubkey_E, 0, intLen_E); // try{ // System.out.println("pubkey byte length =" + pubkey_N.length ) ; // FileOutputStream fo = new FileOutputStream("d:\\temp\\pubkey_N.dat"); // fo.write(pubkey_N) ; // fo.close() ; // }catch(Exception e){} // return new byte[][] { pubkey_N, pubkey_E }; } public static void debug(byte[] bs) { if (!debug || (bs == null)) return; for (int i = 0, length = bs.length; i < length; i++) { int x = ((int) bs[i]) & 0xff; if (x > 15) System.out.print(Integer.toString(x, 16) + " "); else System.out.print("0" + Integer.toString(x, 16) + " "); if ((i + 1) % 16 == 0) System.out.print("\n"); } System.out.print("\n"); } public static void debug(String title, byte[] bs) { debug(title + ":"); debug(bs); } public static void debug(byte[] bs, String file) { if (!debug) return; FileOutputStream out = null; try { out = new FileOutputStream(file); out.write(bs); out.flush(); } catch (Exception e) { }finally{ if(out!=null){ try { out.close(); } catch (IOException e) { } } } } public static void debug(String msg) { if (!debug) return; System.out.println(msg); } public static int bytes2Int(byte[] bytes, boolean desc) { if (bytes == null) return 0; if (bytes.length < 4) { byte[] tmp = new byte[] { 0, 0, 0, 0 }; if (!desc) System.arraycopy(bytes, 0, tmp, 4 - bytes.length, bytes.length); else System.arraycopy(bytes, 0, tmp, 0, bytes.length); bytes = tmp; } if (!desc) return ((bytes[0] << 24) | ((bytes[1] << 16) & 0xff0000) | ((bytes[2] << 8) & 0xff00) | (bytes[3] & 0xff)); else return ((bytes[3] << 24) | ((bytes[2] << 16) & 0xff0000) | ((bytes[1] << 8) & 0xff00) | (bytes[0] & 0xff)); } public static byte[] getDERInnerData(byte[] der) { int ab = der[1] & 0xff; int length = 0; int dataIndex = 0; if (ab >= 0x80) { int lengthOfLength = ab - 0x80; byte[] lengthBytes = new byte[lengthOfLength]; System.arraycopy(der, 2, lengthBytes, 0, lengthOfLength); length = generateInt(lengthBytes); dataIndex = 2 + lengthOfLength; } else { length = (int) ab; dataIndex = 2; } byte[] data = new byte[length]; System.arraycopy(der, dataIndex, data, 0, length); return data; } public static byte[] getDERInnerData(byte[] der, int index) { int derStart = 0; int length = 0; int headLength = 2; for (int i = 0; i < index; i++) { int ab = der[derStart + 1] & 0xff; if (ab > 0x79) { int lengthOfLength = ab - 0x80; headLength = 2 + lengthOfLength; byte[] lengthBytes = new byte[lengthOfLength]; System.arraycopy(der, derStart + 2, lengthBytes, 0, lengthOfLength); length = generateInt(lengthBytes); } else length = (int) ab; if (i != (index - 1)) derStart = derStart + length + headLength; } byte[] bs = new byte[length]; System.arraycopy(der, derStart + headLength, bs, 0, length); return bs; } public static int generateInt(byte[] bytes) { int tr = 0; for (int i = bytes.length - 1; i > -1; i--) { int x = ((int) bytes[bytes.length - 1 - i] & 0xff) << (i * 8); tr += x; } return tr; } public static byte[] generateDERCode(int type, byte[] content) { int length = content.length; byte[] lengthBs = null; if (length >= 0x80) { byte[] intBs = int2Bytes(length); lengthBs = new byte[1 + intBs.length]; lengthBs[0] = (byte) (0x80 + intBs.length); System.arraycopy(intBs, 0, lengthBs, 1, intBs.length); } else { lengthBs = new byte[1]; lengthBs[0] = (byte) length; } byte[] all = new byte[1 + lengthBs.length + content.length]; all[0] = (byte) type; System.arraycopy(lengthBs, 0, all, 1, lengthBs.length); System.arraycopy(content, 0, all, 1 + lengthBs.length, content.length); return all; } public static byte[] int2Bytes(int i) { int l = 0; if (i <= 0xff) l = 1; else if (i <= 0xffff) l = 2; else if (i <= 0xffffff) l = 3; else l = 4; byte[] bs = new byte[l]; for (int x = 0; x < l; x++) { bs[x] = (byte) (i >> ((l - 1 - x) * 8)); } return bs; } public static byte[] connect(byte[] a, byte[] b) { byte[] tmp = new byte[a.length + b.length]; System.arraycopy(a, 0, tmp, 0, a.length); System.arraycopy(b, 0, tmp, a.length, b.length); return tmp; } public static byte[] date2ASN1(Date date) { if (date.getTime() < DATE_2050) { SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmmss"); String time = format.format(date) + "Z"; return generateDERCode(0x17, time.getBytes()); } else { SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); String time = format.format(date) + "Z"; return generateDERCode(0x18, time.getBytes()); } } public static byte[] oid2ASN1(String oid) { String[] pieces = oid.split("\\."); byte[] oidbs = null; byte b = (byte) (Integer.parseInt(pieces[0]) * 40 + Integer.parseInt(pieces[1])); oidbs = new byte[1]; oidbs[0] = b; for (int i = 2; i < pieces.length; i++) { int num = Integer.parseInt(pieces[i]); int pow = maxPow128(num, 0); byte[] id = new byte[pow + 1]; genid(pow, num, id); byte[] tmp = new byte[oidbs.length + id.length]; System.arraycopy(oidbs, 0, tmp, 0, oidbs.length); System.arraycopy(id, 0, tmp, oidbs.length, id.length); oidbs = tmp; } return oidbs; } private static int maxPow128(int num, int pow) { if (num % (Math.pow(128, pow)) > Math.pow(128, ((pow - 1) > 0) ? (pow - 1) : 1)) return maxPow128(num, pow + 1); else { if ((pow == 0) && (num / 128 > 0)) return 1; return pow; } } private static void genid(int pow, int num, byte[] id) { if (pow == 0) id[id.length - 1] = (byte) num; else id[id.length - 1 - pow] = (byte) (0x80 + num / Math.pow(128, pow)); if ((pow - 1) >= 0) genid(pow - 1, (int) (num % Math.pow(128, pow)), id); } public static X509Certificate generateCertificate(byte[] cert) throws Exception { ByteArrayInputStream in = null; // 判断是否为der编码证书 if (cert[0] == 0x30) { int tl = ((int) (cert[1] & 0xff)) - 128; if (tl > 0) { byte[] ltmp = new byte[tl]; System.arraycopy(cert, 2, ltmp, 0, tl); int length = new BigInteger(ltmp).intValue(); if ((length > 0) && (length == (cert.length - 2 - tl))) { in = new ByteArrayInputStream(cert); } else throw new CertificateException("Illegal length: " + length); } else throw new CertificateException("Illegal code: 30 " + ((cert[1] & 0xff))); } else { String head = "-----BEGIN CERTIFICATE-----"; String tail = "-----END CERTIFICATE-----"; String b64Cert = new String(cert); if (b64Cert.indexOf(head) > -1) { b64Cert = b64Cert.replaceFirst(head, "").replaceFirst(tail, ""); } byte[] certTmp = Base64.decode(b64Cert.trim()); in = new ByteArrayInputStream(certTmp); } CertificateFactory cf = CertificateFactory.getInstance("X.509FX", "INFOSEC"); return (X509Certificate) cf.generateCertificate(in); } public static void main(String[] args) throws Exception { String DN1 = "c=cn,ou=infosec,ou=randd,cn=hy"; String DN2 = "cn=hy,ou=randd,ou=infosec,c=cn"; System.out.println(turnDN(DN1)); compereDN(DN1, DN2); } }
Java
UTF-8
11,857
2.28125
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package microcreditbanking.classes; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import javax.swing.JOptionPane; /** * * @author Ricky Islam */ public class logIn extends javax.swing.JFrame { /** * Creates new form logIn */ public logIn() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jButton2 = new javax.swing.JButton(); jButton1 = new javax.swing.JButton(); jPasswordField1 = new javax.swing.JPasswordField(); jTextField1 = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setLayout(null); jButton2.setFont(new java.awt.Font("Arabic Typesetting", 1, 24)); // NOI18N jButton2.setText("Exit"); jPanel1.add(jButton2); jButton2.setBounds(730, 560, 110, 40); jButton1.setFont(new java.awt.Font("Arabic Typesetting", 1, 24)); // NOI18N jButton1.setText("Log In"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jPanel1.add(jButton1); jButton1.setBounds(590, 560, 120, 40); jPanel1.add(jPasswordField1); jPasswordField1.setBounds(590, 510, 250, 30); jPanel1.add(jTextField1); jTextField1.setBounds(590, 460, 250, 30); jLabel3.setFont(new java.awt.Font("Arabic Typesetting", 1, 36)); // NOI18N jLabel3.setText("Admin Password: "); jPanel1.add(jLabel3); jLabel3.setBounds(340, 510, 260, 42); jLabel2.setFont(new java.awt.Font("Arabic Typesetting", 1, 36)); // NOI18N jLabel2.setText("Enter Admin Name: "); jPanel1.add(jLabel2); jLabel2.setBounds(340, 450, 360, 42); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/microcreditbanking/image/white_keyboard-wallpaper-1366x768.jpg"))); // NOI18N jPanel1.add(jLabel1); jLabel1.setBounds(0, 0, 1350, 720); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 1350, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 680, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: String id = jTextField1.getText(); String pass = jPasswordField1.getText(); if (id.length() == 0 || pass.length() == 0) { JOptionPane.showMessageDialog(null, "Please Fill Up The Fields Correctly !!! "); } else { try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "shunno"); Statement stmt = con.createStatement(); ResultSet rs = null; rs = stmt.executeQuery("SELECT * FROM ADMINPANEL WHERE USERNAME like '" + id + "' and PASSWORD like '" + pass + "' "); if (rs.next()) { dispose(); home homeObject = new home () ; homeObject.homeFunction () ; } else { JOptionPane.showMessageDialog(null, "Incorrect User Name Or Password !!! "); } con.close(); } catch (Exception e) { JOptionPane.showMessageDialog(null, " Error: " + e); } } }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(logIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(logIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(logIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(logIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","shunno"); Statement stmt=con.createStatement(); stmt.executeQuery ("CREATE table \"ADMINPANEL\" (\n" + " \"USERNAME\" VARCHAR2(4000),\n" + " \"PASSWORD\" VARCHAR2(4000)\n" + ")"); con.close(); //JOptionPane.showMessageDialog(null, "Database Created Successfully !!! "); } catch(Exception e){ // JOptionPane.showMessageDialog(null, " Database Ready To Run !!!! "); } // ----------------------------------------------------------------------------------------------------------------------------------------------- try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","shunno"); Statement stmt=con.createStatement(); stmt.executeQuery ("CREATE table \"CUSTOMER\" (\n" + " \"CUR_DATE\" VARCHAR2(4000),\n" + " \"ACCOUNT\" VARCHAR2(4000),\n" + " \"NAME\" VARCHAR2(4000),\n" + " \"B_DAY\" VARCHAR2(4000),\n" + " \"PHONE\" VARCHAR2(4000),\n" + " \"OCCUPATION\" VARCHAR2(4000),\n" + " \"NID\" VARCHAR2(4000),\n" + " \"ADDRESS\" VARCHAR2(4000),\n" + " \"SEX\" VARCHAR2(4000),\n" + " \"ACCOUNT_TYPE\" VARCHAR2(4000),\n" + " \"ACCOUNT_KEY\" VARCHAR2(4000),\n" + " \"INCOME\" VARCHAR2(4000),\n" + " \"NOMINEE\" VARCHAR2(4000),\n" + " \"BALANCE\" VARCHAR2(4000),\n" + " \"LOAN\" VARCHAR2(4000)\n" + ")"); con.close(); //JOptionPane.showMessageDialog(null, "Database Created Successfully !!! "); } catch(Exception e){ // JOptionPane.showMessageDialog(null, " Database Ready To Run !!!! "); } // ------------------------------------------------------------------------------------------------------------------------------------------------------- try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","shunno"); Statement stmt=con.createStatement(); stmt.executeQuery ("CREATE table \"HISTORY\" (\n" + " \"CUSTOMER_ID\" VARCHAR2(4000),\n" + " \"CUSTOMER_NAME\" VARCHAR2(4000),\n" + " \"TRANSACTION_DATE\" VARCHAR2(4000),\n" + " \"TRANSACTION_TYPE\" VARCHAR2(4000),\n" + " \"TRANSACTION_MODE\" VARCHAR2(4000),\n" + " \"TRANSACTION_AMOUNT\" VARCHAR2(4000),\n" + " \"OLD_BALANCE\" VARCHAR2(4000),\n" + " \"FINAL_BALANCE\" VARCHAR2(4000)\n" + ")"); con.close(); //JOptionPane.showMessageDialog(null, "Database Created Successfully !!! "); } catch(Exception e){ // JOptionPane.showMessageDialog(null, " Database Ready To Run !!!! "); } // ------------------------------------------------------------------------------------------------------------------------------------------------------- try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","shunno"); Statement stmt=con.createStatement(); stmt.executeQuery ("CREATE table \"LOAN\" (\n" + " \"CUS_ACCOUNT_NO\" VARCHAR2(4000),\n" + " \"CUS_NAME\" VARCHAR2(4000),\n" + " \"BORROW_DATE\" VARCHAR2(4000),\n" + " \"AMOUNT\" VARCHAR2(4000),\n" + " \"INTEREST\" VARCHAR2(4000),\n" + " \"FINAL_AMOUNT\" VARCHAR2(4000),\n" + " \"PAY_DATE\" VARCHAR2(4000)\n" + ")"); con.close(); //JOptionPane.showMessageDialog(null, "Database Created Successfully !!! "); } catch(Exception e){ // JOptionPane.showMessageDialog(null, " Database Ready To Run !!!! "); } // ------------------------------------------------------------------------------------------------------------------------------------------------------- try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","shunno"); Statement stmt=con.createStatement(); stmt.executeQuery ("CREATE table \"PAYMENT\" (\n" + " \"P_ACCOUNT_NO\" VARCHAR2(4000),\n" + " \"P_CUS_NAME\" VARCHAR2(4000),\n" + " \"P_BORROW_DATE\" VARCHAR2(4000),\n" + " \"P_LOAN_AMOUNT\" VARCHAR2(4000),\n" + " \"P_DEADLINE\" VARCHAR2(4000),\n" + " \"P_AMOUNT\" VARCHAR2(4000)\n" + ")"); con.close(); //JOptionPane.showMessageDialog(null, "Database Created Successfully !!! "); } catch(Exception e){ // JOptionPane.showMessageDialog(null, " Database Ready To Run !!!! "); } /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new logIn().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPanel jPanel1; private javax.swing.JPasswordField jPasswordField1; private javax.swing.JTextField jTextField1; // End of variables declaration//GEN-END:variables }
Java
UTF-8
1,859
2.484375
2
[]
no_license
package com.example.demo.entity; import java.io.Serializable; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSeeAlso; /** * @author 作者 zuoruibo: * @date 创建时间:2020年12月1日 下午3:20:57 * @version 1.0 * @parameter * @since 统一的返回类 * @return */ @XmlAccessorType(value = XmlAccessType.FIELD) @XmlRootElement(name ="response") @XmlSeeAlso(User.class) public class Response implements Serializable{ private String resultCode; private String resultDesc; private List<User> result; public static Response SUCCESS(List<User> list) { return new Response("0","success",list); } public static Response SUCCESS(String msg,List<User> list) { return new Response("0",msg,list); } public static Response ERROR() { return new Response("-1","操作失败",null); } public static Response ERROR(String code,String msg) { return new Response(code,msg,null); } public static Response ERROR(String msg) { return new Response("-1",msg,null); } public String getResultCode() { return resultCode; } public void setResultCode(String resultCode) { this.resultCode = resultCode; } public String getReslutDesc() { return resultDesc; } public void setReslutDesc(String resultDesc) { this.resultDesc = resultDesc; } public List<User> getResult() { return result; } public void setResult(List<User> result) { this.result = result; } public Response() { } public Response(String resultCode, String resultDesc,List<User> result) { this.resultCode = resultCode; this.resultDesc = resultDesc; this.result= result; } }
C
UTF-8
1,495
3.859375
4
[]
no_license
#include<stdio.h> #include<stdlib.h> #include "BiTree.h" #define N 10 void CreateBiTree(BiTree *T, char ch) { /* If the very tree is empty, then malloc space for it and initialize the children NULL and evaluate the data as ch */ if(!*T) { *T = (BiTNode*)malloc(sizeof(BiTNode)); (*T)->data = ch; (*T)->lchild = NULL; (*T)->rchild = NULL; return; } /* If the tree is not empty, then compare the tree node value with the very value, if the node is bigger, then initalize the left child, the other with the right child */ else { if((*T)->data == ch) return; if((*T)->data > ch) CreateBiTree(&((*T)->lchild), ch); else CreateBiTree(&((*T)->rchild), ch); } } /* Print the value according with Previous Order is to print the value first, then left child, and last the right child */ void MidOrder(BiTree T) { if(T) { MidOrder(T->lchild); printf("%c ", T->data); MidOrder(T->rchild); } return; } /* Initalize the Root with NULL, and there using the array to provide the values, and this can also get from an extern file and even get by inputing */ /* int main() { BiTree T = NULL; char a[N] = {'5','2', '3','6', '8', '7', '4', '1', '0', '9'}; int i = 0; for(; i < N; i++) { CreateBiTree(&T, a[i]); } MidOrder(T); printf("\n"); system("PAUSE"); return 0; } */
Markdown
UTF-8
2,118
2.78125
3
[]
no_license
--- layout: post title: ツリー構造の情報を作りたい date: 2018-03-06 10:08:24 categories: c# --- <p><a href="https://i.stack.imgur.com/iBzmC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iBzmC.png" alt="画像の説明をここに入力"></a></p> <p>あるデータをツリー構造のデータを作ろうとしているのですが、<br> うまくロジックをくめずにおります。<br> イメージとしては<br> 画像のようなA~Fのデータをツリーで持ちたく考えており、</p> <p>データとしてA~Fをもつデータ配列と<br> 矢印線のデータ配列があります。<br> A~Fのデータはそれぞれ、つながる線のデータをもち、<br> 矢印線のデータは矢印の先にどのデータA~Fにつながっているかの情報を持っています。</p> <p>図のように矢印のデータにIN、OUTがわかるようであれば若干楽になるのですが<br> それがない状態です。<br> A~FのデータはAがトップのデータであるということのみがわかるようなものになっています。</p> ``` List&lt;Item&gt; items; A~Fのリスト情報 List&lt;Arrow&gt; arrows; 矢印線のリスト情報 public class Element { public int Id; public int Parent; public IList Children; } ``` <p>~~</p> ``` ObservableCollection&lt;Element&gt; tree = new ObservableCollection&lt;Element&gt;(); Element element = new Element(); element.Id = items[0].Id; itemsからA(トップ)の情報を取得し、つながるアイテムデータのリストを取得する element.Childrenに取得したリストを設定 // ツリー情報にエレメントを追加 tree.Add(element); ``` <p>つながるアイテムデータのリスト分、同じような処理をループして行うことになると思うのですが、どのようにメソッドを分けていいのかが整理できずにおります。</p> <p>説明が下手で申し訳ないのですが、アドバイスいただけると助かります。</p>
Java
UTF-8
1,102
2.046875
2
[]
no_license
package com.jayden.testandroid.lollipop.animation; import android.annotation.TargetApi; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.widget.ImageView; import com.jayden.testandroid.R; /** * Created by Jayden on 2016/5/12. * Email : 1570713698@qq.com */ public class ShareElementActivity extends AppCompatActivity { private int pos; private int drawableId; @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_share_detail); Intent intent = getIntent(); if (intent != null) { pos = intent.getExtras().getInt("pos"); drawableId = intent.getExtras().getInt("drawableId"); } ImageView imageView = (ImageView) findViewById(R.id.image); imageView.setTransitionName(pos+"pic"); imageView.setImageResource(drawableId); } }
C++
UTF-8
4,035
3.171875
3
[]
no_license
#include <iostream> #include <stack> #include <string> #include <vector> #include <utility> #include <math.h> #include <algorithm> const int SMALLCONST = -1000000001; void readInput(int* n, int* m, std::vector<std::vector<int>>* grid, std::istream &in_stream = std::cin) { in_stream >> *n; in_stream >> *m; grid->assign(*n, std::vector<int> (*m, 0)); for (int i = 0; i < *n; ++i) { for (int j = 0; j < *m; ++j) { in_stream >> (*grid)[i][j]; } } } void writeOutput(const std::vector<int>& sequence, std::ostream &out_stream = std::cout) { for (size_t i = 0; i < sequence.size(); ++i) { out_stream << sequence[i] << " "; } } void printVector(const std::vector<int>& some_vector) { for (size_t i = 0; i < some_vector.size(); ++i) { std::cerr << some_vector[i] << " "; } std::cerr << std::endl; } void printBoolVector (const std::vector<bool>& some_vector) { std::cerr << "true indexes are:\n"; for (int i = 0; i < some_vector.size(); ++i) { if (some_vector[i]) { std::cerr << i << " "; } } std::cerr << std::endl; } void printPairVector(const std::vector<std::pair<int, int>>& some_vector) { for (size_t i = 0; i < some_vector.size(); ++i) { std::cerr << "{ " << some_vector[i].first << ", " << some_vector[i].second << "} "; } std::cerr << std::endl; } template<typename T> class Heap { private: int size_; std::vector<T> elements_; bool heapify(int index) { if (2 * index + 1 >= size_) { return false; } if (2 * index + 2 >= size_) { if (elements_[index] > elements_[2 * index + 1]) { std::swap(elements_[index], elements_[2 * index + 1]); return true; } return false; } if (elements_[index] <= elements_[2 * index+1] && elements_[index] <= elements_[2 * index + 2]) { return false; } if (elements_[2 * index + 1] < elements_[2 * index + 2]) { std::swap(elements_[index], elements_[2 * index + 1]); return heapify(2 * index + 1); } else { std::swap(elements_[index], elements_[2 * index + 2]); return heapify(2 * index + 2); } } public: Heap() { size_ = 0; } void add(T element) { ++size_; elements_.push_back(element); if (size_ == 1) { return; } bool flag = true; int current_index = (size_ - 2) / 2; while(flag) { flag = heapify(current_index); current_index = (current_index - 1) / 2; } //printVector(elements_); } T getMin() { //printVector(elements_); return elements_[0]; } void pop() { std::swap(elements_[0], elements_[size_ - 1]); elements_.pop_back(); --size_; heapify(0); } int getSize() { return size_; } bool isEmpty() { return elements_.empty(); } }; std::vector<int> solve(const int n, const int m, const std::vector<std::vector<int>>& grid) { Heap<std::pair<int, std::pair<int, int>>> heap; for (int i = 0; i < n; ++i) { heap.add(std::make_pair(grid[i][0], std::make_pair(i, 0))); } std::vector<int> sorted; while (!heap.isEmpty()) { auto minimalPair = heap.getMin(); heap.pop(); sorted.push_back(minimalPair.first); auto coordinates = minimalPair.second; int x = coordinates.first; int y = coordinates.second; if (coordinates.second + 1 < m) { heap.add(std::make_pair(grid[x][y + 1], std::make_pair(x, y + 1))); } } return sorted; } int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(0); int n, m; std::vector<std::vector<int>> grid; readInput(&n, &m, &grid); std::vector<int> sorted = solve(n, m, grid); writeOutput(sorted); }
Python
UTF-8
1,299
3.046875
3
[]
no_license
import numpy import scipy.special # nueral network class nueralNetwork: def __init__(self,inputnodes,hiddennodes,outputnodes,learningrate): # nodes self.inodes = inputnodes self.hnodes = hiddennodes self.unodes = outputnodes # weight self.wih = numpy.random.normal(0.0, pow(self.hnodes, -0.5),(self.hnodes, self.inodes)) # between input and hidden self.who = numpy.random.normal(0.0, pow(self.onodes, -0.5),(self.onodes, self.hnodes)) # between hidden and output # learning rate self.lr = learningrate # activation function self.activation_function = lambda x : scipy.special.expit(x) pass def train(): pass def query(self,inputs_list): # 入力リストを行列に変換 inputs = numpy.array(inputs_list,ndmin=2).T hidden_inputs = numpy.dot(self.wih, inputs) hidden_outputs = self.activation_function(hidden_inputs) final_inputs = numpy.dot(self.who, hidden_outputs) final_outputs = self.activation_function(final_inputs) return final_outputs input_nodes = 3 hidden_nodes = 3 output_nodes = 3 learning_rate = 0.3 n = nueralNetwork(input_nodes,hidden_nodes,output_nodes,learning_rate)
Markdown
UTF-8
1,504
3.03125
3
[]
no_license
# SVN-DIFF 文件解析工具 ## 简介 svn-diff 是一个对svn diff文件解析的模块,用于解析SVN diff返回的结果。 ## 使用说明 ### 模块接入 * svn-diff 是一个对svn diff文件解析的模块,所以需要先将svn diff返回的结果输出到一个文件中(建议使用.diff作为后缀名,方便使用TortoiseSVN打开查看)。然后再使用svn_diff去解析该文件: ```python import svn_diff diff = svn_diff.Diff(diff_file) # diff_file为diff文件路径 ``` * Diff包含一个字典files,key为file_name,value为OneFile类。 * OneFile类表示一个文件的更改情况,包含三个字典add_list、del_list和upd_list。key都为line_num,value为相应的行(upd_list则保存前后行)。 ### 暂时提供接口 #### Diff类 * ```check_change(patten)```:这个接口用于检查一个diff文件中是否有相应的改变,pattern为一个正则表达式。 * 未完待续~ ### OneFile 类 * ```check_change(pattern)```:这个接口用于检查修改了的文件中是否有相应的改变,pattern为一个正则表达式。 * ```check_del(pattern)```:这个接口用于检测修改文件张是否删除了包含某种串的行,pattern为一个正则表达式。 * 未完待续~ ## 设计说明 ### Diff 类 ```python files:{} file_name -> OneFile ``` ### OneFile 类 ```python file_name: string add_list:{} line_num -> line del_list:{} line_num -> line upd_list:{} line_num -> [old_line, new_line] ```
JavaScript
UTF-8
14,083
2.578125
3
[]
no_license
 function DatePicker(imgUrl) { Element.prototype.append = function (elements) { for (var a = 0; a < elements.length; a++) { this.appendChild(elements[a]); } } Element.prototype.setStyles = function (styleObj) { for (var style in styleObj) { this.style[style] = styleObj[style]; } } var div = document.createElement('div'), monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], weekDaysNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], yy = new Date().getFullYear(), mm = new Date().getMonth(), dd = new Date().getDate(), currentYY = yy, currentMM = mm, currentDD = dd; div.setStyles({ float: 'left', display: 'inline-block', fontFamily: 'Calibri', color: '#eeeeee', boxSizing: 'border-box', border: '1px solid transparent' }); function DatePicker() { //this.yy = new Date().getFullYear(); //this.mm = new Date().getMonth(); //this.dd = new Date().getDate(); this.mainContainer = this.createMainContainer(); this.navigationRow = this.createNavigationRow(); this.dateOptionsBox = this.createDateOptionsBox(); this.mainContainer.append([this.navigationRow, this.dateOptionsBox]); document.body.appendChild(this.mainContainer); }; DatePicker.prototype = { createMainContainer: function () { var mainContainer = div.cloneNode(true); mainContainer.setStyles({ position: 'absolute', width: '250px', textAlign: 'center', display: 'none', border: '10px solid #333333', backgroundColor: '#333333', fontSize: '13px', padding: '0px' }); return mainContainer; }, createNavigationRow: function () { var self = this, navigationRow = div.cloneNode(true), header = div.cloneNode(true), arrowBtn = div.cloneNode(true); arrowBtn.setStyles({ cursor: 'pointer', width: '15%' }); var leftArrow = arrowBtn.cloneNode(true), rightArrow = arrowBtn.cloneNode(true); leftArrow.innerHTML = '&#9664;'; rightArrow.innerHTML = '&#9654;'; leftArrow.onclick = function (ev) { self.arrowEvent('backward'); }; rightArrow.onclick = function (ev) { self.arrowEvent('forward'); }; header.innerHTML = monthNames[mm] + ' - ' + yy; header.setStyles({ cursor: 'pointer', width: '70%' }); header.setAttribute('header-type', 'days'); header.onclick = function () { self.headerEvent(header); } navigationRow.setStyles({ width: '100%', borderBottom: '1px solid #ffffff' }); navigationRow.append([leftArrow, header, rightArrow]); return navigationRow; }, createDateOptionsBox: function () { var self = this, dateOptionsBox = div.cloneNode(true); dateOptionsBox.innerHTML = this.generateDaysOfMonth(); dateOptionsBox.id = 'date-options-box'; dateOptionsBox.onclick = function (ev) { if (ev.target.getAttribute('cell-type') != 'active') { return; } self.dateOptionsEvent(ev.target, self); } return dateOptionsBox; }, attachTo: function (element) { var self = this, relativeParent = this.findRelativeParent(element), imgSize = element.offsetHeight - 5, imgPosition = element.offsetWidth - (imgSize + 7), imgStartX = imgPosition + element.offsetLeft + relativeParent.left, imgEndX = imgStartX + imgSize, imgStartY = element.offsetTop + relativeParent.top, imgEndY = imgStartY + element.offsetHeight; element.style.background = 'url(' + (imgUrl ? imgUrl : 'calendar.png') + ') no-repeat ' + imgPosition + 'px 0px'; element.style.backgroundSize = imgSize + 'px ' + imgSize + 'px'; element.onfocus = function (ev) { self.activeInput = this; } element.onclick = function (ev) { if (ev.pageX > imgStartX && ev.pageX < (imgEndX + 3) && ev.pageY > imgStartY && ev.pageY < imgEndY) { if (self.mainContainer.style.display == 'none') { var left = element.offsetLeft + relativeParent.left, top = (element.offsetTop + element.offsetHeight) + relativeParent.top; self.mainContainer.setStyles({ display: 'inline-block', left: left + 'px', top: top + 'px' }); var activeDate = self.activeInput.value.split('-').filter(Boolean); if (activeDate.length) { self.setInputDate(activeDate); } else { self.resetDate(); } self.setCurrentDate(); self.dateOptionsBox.innerHTML = self.generateDaysOfMonth(); self.navigationRow.children[1].innerHTML = monthNames[mm] + ' - ' + yy; } else { self.mainContainer.style.display = 'none'; } } } element.onmousemove = function (ev) { if (ev.pageX > imgStartX && ev.pageX < (imgEndX + 3) && ev.pageY > imgStartY && ev.pageY < imgEndY) { this.style.cursor = 'pointer'; } else { this.style.cursor = 'initial'; } } }, arrowEvent: function (timeDirection) { var header = this.navigationRow.children[1], headerType = header.getAttribute('header-type'), direction = (timeDirection == 'backward') ? -1 : 1; if (headerType == 'days') { mm += direction; if (mm > 11) { mm = 0; yy += 1; } else if (mm < 0) { mm = 11; yy -= 1; } this.dateOptionsBox.innerHTML = this.generateDaysOfMonth(); header.innerHTML = monthNames[mm] + ' - ' + yy; } else if (headerType == 'months') { yy += direction; header.innerHTML = yy; this.dateOptionsBox.innerHTML = this.generateMonths(); } else { var years = header.innerHTML.split(' - '), startYear = (timeDirection == 'backward') ? Number(years[0]) - 15 : Number(years[1]); header.innerHTML = startYear + ' - ' + (startYear + 15); this.dateOptionsBox.innerHTML = this.generateYears(startYear, startYear + 15); } }, headerEvent: function (header) { var headerType = header.getAttribute('header-type'); if (headerType == 'days') { header.innerHTML = yy; header.setAttribute('header-type', 'months'); this.dateOptionsBox.innerHTML = this.generateMonths(); } else if (headerType == 'months') { var startYear = (yy - 8); header.innerHTML = startYear + ' - ' + (startYear + 15); header.setAttribute('header-type', 'years'); this.dateOptionsBox.innerHTML = this.generateYears(startYear, (startYear + 15)); } else { header.innerHTML = yy; header.setAttribute('header-type', 'months'); this.dateOptionsBox.innerHTML = this.generateMonths(); } }, dateOptionsEvent: function (element, mainContainer) { var header = this.navigationRow.children[1], headerType = header.getAttribute('header-type'); if (headerType == 'days') { dd = Number(element.innerHTML); this.activeInput.value = dd + '-' + (mm + 1) + '-' + yy; this.mainContainer.style.display = 'none'; } else if (headerType == 'months') { mm = monthNames.indexOf(element.innerHTML); header.innerHTML = monthNames[mm] + '-' + yy; header.setAttribute('header-type', 'days'); this.dateOptionsBox.innerHTML = this.generateDaysOfMonth(); } else { yy = Number(element.innerHTML); header.innerHTML = yy; header.setAttribute('header-type', 'months'); this.dateOptionsBox.innerHTML = this.generateMonths(); } }, generateDaysOfMonth: function () { var daysOfMonth = new Date(yy, mm + 1, 0).getDate(), firstDayOfMonth = new Date(yy, mm, 1).getDay() - 1, lastDayOfMonth = new Date(yy, mm + 1, 0).getDay(), previousMonthDays = new Date(yy, mm, 0).getDate() - firstDayOfMonth, nextMonthStart = 1, daysWrapper = div.cloneNode(true), day = div.cloneNode(true); day.setStyles({ width: (100 / 7) + '%', padding: '1.5%' }); for (var b = 0; b < 7; b++) { var weekDay = day.cloneNode(true); weekDay.innerHTML = weekDaysNames[b]; daysWrapper.appendChild(weekDay); } for (var a = 0, len = firstDayOfMonth + daysOfMonth + (7 - lastDayOfMonth) ; a < len; a++) { var singleDay = day.cloneNode(true); if (a <= firstDayOfMonth || (a - firstDayOfMonth) > daysOfMonth) { singleDay.innerHTML = a <= firstDayOfMonth ? previousMonthDays++ : nextMonthStart++; singleDay.setStyles({ color: '#888888' }); } else { singleDay.innerHTML = a - firstDayOfMonth; singleDay.setAttribute('cell-type', 'active'); singleDay.setStyles({ cursor: 'pointer' }); if (a - firstDayOfMonth == currentDD && mm == currentMM && currentYY == yy) { singleDay.setStyles({ border: '1px solid #8FBF20', color: '#8FBF20' }); } } daysWrapper.appendChild(singleDay); } return daysWrapper.innerHTML; }, generateMonths: function () { var wrapper = div.cloneNode(true), month = div.cloneNode(true); month.setStyles({ width: '25%', padding: '2%', cursor: 'pointer' }); for (var a = 0; a < monthNames.length; a++) { var newMonth = month.cloneNode(true); newMonth.innerHTML = monthNames[a]; newMonth.setAttribute('cell-type', 'active'); if (a == currentMM && currentYY == yy) { newMonth.setStyles({ border: '1px solid #8FBF20', color: '#8FBF20' }); } wrapper.appendChild(newMonth); } return wrapper.innerHTML; }, generateYears: function (startYear, endYear) { var wrapper = div.cloneNode(true), year = div.cloneNode(true); year.setStyles({ width: '25%', padding: '2%', cursor: 'pointer' }); for (var a = startYear; a <= endYear; a++) { var singleYear = year.cloneNode(true); singleYear.innerHTML = a; singleYear.setAttribute('cell-type', 'active'); if (a == currentYY) { singleYear.setStyles({ border: '1px solid #8FBF20', color: '#8FBF20' }); } wrapper.appendChild(singleYear); } return wrapper.innerHTML; }, setInputDate: function (activeDate) { yy = Number(activeDate[2]); mm = Number(activeDate[1] - 1); dd = Number(activeDate[0]); }, resetDate: function () { yy = new Date().getFullYear(); mm = new Date().getMonth(); dd = new Date().getDate(); }, setCurrentDate: function () { currentYY = yy; currentMM = mm; currentDD = dd; }, holdReleaseEffect: function (element) { element.onmousedown = function () { var currentLineHeight = Number(this.style.lineHeight.slice(0, -2)); this.style.lineHeight = (currentLineHeight + 2) + 'px'; } element.onmouseup = function () { var currentLineHeight = Number(this.style.lineHeight.slice(0, -2)); this.style.lineHeight = (currentLineHeight - 2) + 'px'; } }, findRelativeParent: function (element) { var parent = element.parentNode; while (parent.style.position != 'relative' && parent.tagName != 'BODY') { parent = parent.parentNode; } return { top: parent.offsetTop, left: parent.offsetLeft } } } return new DatePicker(); }; var datePicker = new DatePicker(); var inputs = document.querySelectorAll('input'); for (var a = 0; a < inputs.length; a++) { inputs[a].readOnly = 'true'; datePicker.attachTo(inputs[a]); }
C#
UTF-8
2,569
2.828125
3
[]
no_license
using System; namespace Beam { // // tree node // public class AABBTreeNode { static int version = 1; public int escapeNodeOffset; public AABBExternalNode externalNode; // user data public AABBBox extents; // bounding box public AABBTreeNode(AABBBox extents, int escapeNodeOffset, AABBExternalNode externalNode) { this.escapeNodeOffset = escapeNodeOffset; this.externalNode = externalNode; this.extents = extents; } public bool isLeaf() { return this.externalNode != null; } public void reset(double minX, double minY, double minZ, double maxX, double maxY, double maxZ, int escapeNodeOffset, AABBExternalNode externalNode = null) { this.escapeNodeOffset = escapeNodeOffset; this.externalNode = externalNode; var oldExtents = this.extents; oldExtents[0] = minX; oldExtents[1] = minY; oldExtents[2] = minZ; oldExtents[3] = maxX; oldExtents[4] = maxY; oldExtents[5] = maxZ; } public void clear() { this.escapeNodeOffset = 1; this.externalNode = null; var oldExtents = this.extents; var maxNumber = double.MaxValue; oldExtents[0] = maxNumber; oldExtents[1] = maxNumber; oldExtents[2] = maxNumber; oldExtents[3] = -maxNumber; oldExtents[4] = -maxNumber; oldExtents[5] = -maxNumber; } } public class AABBExternalNode { public int spatialIndex { get; set; } public object Data { get; set; } public void Print() { Console.WriteLine($"Node: {Data}"); } } public class AABBBox { private double[] box = new double[6]; public double this[int index] { get { return box[index]; } set { box[index] = value; } } public AABBBox() { for (int i = 0; i < 6; i++) { box[i] = 0; } } public AABBBox(Point3 min, Point3 max) { box[0] = min.X; box[1] = min.Y; box[2] = min.Z; box[3] = max.X; box[4] = max.Y; box[5] = max.Z; } } }
JavaScript
UTF-8
966
2.75
3
[]
no_license
var UserItems = {}; var count = 0; Diary = require('../models/diary.js'); function User(user){ this.name = user.name; this.password = user.password; this.avatar = user.avatar; }; module.exports = User; User.prototype.save = function(){ var user = { name: this.name, password: this.password, avatar: this.avatar, }; UserItems[count] = user; count++; }; User.prototype.get = function(name){ var i = 0; while(i < count){ if(UserItems[i].name == name){ var user = UserItems[i]; return user; } i++; } }; User.prototype.adddiary = function(name,title,post,image,type,location,price,liquidateDamages=100, startAt="20171101", endAt="20171103"){ var newdiary = new Diary(name,title,post,image,type,location,price,liquidateDamages, startAt, endAt); newdiary.save(); }; User.prototype.getdiary = function(name){ var result = Diary.get(name); return result; }; User.prototype.deletediary = function(name,title){ return Diary.delete(name,title); };
C++
ISO-8859-1
1,737
3.546875
4
[]
no_license
// PROG - 19/02/2020 - TPC1 // Ficha1 - Exerccio 5 // up201806629 #include "pch.h" #include <iostream> #include <string> using namespace std; int ex_1_5_a() { int hour1, hour2, minute1, minute2, second1, second2, second_sum, minute_sum, hour_sum, days, minute, second, hour; cout << "Time1 (hour minutes seconds)? "; cin >> hour1 >> minute1 >> second1; cout << "Time2 (hour minutes seconds)? "; cin >> hour2 >> minute2 >> second2; second_sum = second1 + second2; minute_sum = minute1 + minute2 + (second_sum / 60); hour_sum = hour1 + hour2 + (minute_sum / 60); days = hour_sum / 24; minute = minute_sum % 60; second = second_sum % 60; hour = hour_sum % 24; cout << "\n Time1 + Time2 = " << days << " day, " << hour << " hours, " << minute << " minutes and " << second << " seconds \n"; return 0; } int ex_1_5_b() { string time1, time2; int second_sum, minute_sum, hour_sum, days, minute, second, hour, hour1, hour2, minute1, minute2, second1, second2; cout << "Time1 (HH:MM:SS)? "; cin >> time1; cout << "Time2 (hour minutes seconds)? "; cin >> time2; hour1 = stoi(time1.substr(0, 3)); hour2 = stoi(time2.substr(0, 3)); minute1 = stoi(time1.substr(3, 6)); minute2 = stoi(time2.substr(3, 6)); second1 = stoi(time1.substr(6)); second2 = stoi(time2.substr(6)); second_sum = second1 + second2; minute_sum = minute1 + minute2 + (second_sum / 60); hour_sum = hour1 + hour2 + (minute_sum / 60); days = hour_sum / 24; minute = minute_sum % 60; second = second_sum % 60; hour = hour_sum % 24; cout << "\n Time1 + Time2 = " << days << " day, " << hour << " hours, " << minute << " minutes and " << second << " seconds \n"; return 0; } int main() { //ex_1_5_a(); ex_1_5_b(); return 0; }
C#
UTF-8
1,387
3.5
4
[]
no_license
using System; using System.Collections; using System.Collections.Generic; namespace InOne.Task.Structure.IMPL { public class ArrayStack<T> : IStack<T>, IEnumerable<T> { private T[] _arr; private int _top; private int _size; public ArrayStack(int size) { _size = size; _arr = new T[_size]; _top = -1; } public int Count() => _arr.Length; public bool IsEmpty() => _arr.Length == 0; public T Peek() => _arr[0]; public T Pop() => _arr[_top--]; public void Push(T data) { if (_top != (_size - 1)) _arr[++_top] = data; else throw new IndexOutOfRangeException(); } public void Reverse() { int mid = (_arr.Length - 1) / 2; int max = _arr.Length - 1; for (int i = 0; i < mid; i++) { T temp = _arr[i]; _arr[i] = _arr[max]; _arr[max] = temp; max--; } } #region IEnumerator IMPL public IEnumerator<T> GetEnumerator() { foreach (var item in _arr) yield return item; } IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable)this).GetEnumerator(); #endregion } }
Java
UTF-8
1,271
2.3125
2
[]
no_license
package com.example.freightmanagement.model; /** * Created by songdechuan on 2020/8/6. */ public class TrainingListBean { /** * id : 1 * type : 1 * content : 1+2 * createTime : 1596350485000 * updateTime : 1596350485000 */ private int id; private int type; private String content; private long createTime; private long updateTime; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public long getCreateTime() { return createTime; } public void setCreateTime(long createTime) { this.createTime = createTime; } public long getUpdateTime() { return updateTime; } public void setUpdateTime(long updateTime) { this.updateTime = updateTime; } }
Java
UTF-8
3,123
2.421875
2
[]
no_license
package com.my.myapplication; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; import org.opencv.core.Mat; import org.opencv.core.MatOfRect; import org.opencv.core.Size; import org.opencv.objdetect.CascadeClassifier; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.logging.Logger; public class Detector { private static final Logger logger = Logger.getLogger(Detector.class.getName()); Integer minSize1; Integer maxSize1; Integer minSize2, maxSize2; SharedPreferences sp; private Activity activity; private CascadeClassifier cascadeClassifier1; private CascadeClassifier cascadeClassifier2; public Detector(Activity activity){ this.activity = activity; loadCascadeFile(1); loadCascadeFile(2); sp = PreferenceManager.getDefaultSharedPreferences(activity); minSize1 = Integer.parseInt(sp.getString("minSize1", "30")); maxSize1 = Integer.parseInt(sp.getString("maxSize1", "70")); minSize2 = Integer.parseInt(sp.getString("minSize2", "30")); maxSize2 = Integer.parseInt(sp.getString("maxSize2", "70")); } public void Detect(Mat mGray,MatOfRect signs,int type){ //loadCascadeFile(type, cascadeClassifier); // loadCascadeFile(type); switch (type) { case 1: if (cascadeClassifier1 != null && !cascadeClassifier1.empty()) { cascadeClassifier1.detectMultiScale(mGray, signs, 1.1, 3, 0 , new Size(minSize1, minSize1), new Size(maxSize1, maxSize1)); } else { Log.e("s", "cascade"); } break; case 2: default: if (cascadeClassifier2 != null && !cascadeClassifier2.empty()) { cascadeClassifier2.detectMultiScale(mGray, signs, 1.1, 5, 0 , new Size(minSize2, minSize2), new Size(maxSize2, maxSize2)); } else { Log.e("s", "cascade"); } } } private void loadCascadeFile(int type){ try { InputStream is; File cascadeDir = activity.getDir("cascade", Context.MODE_PRIVATE); File cascadeFile; switch (type) { case 1: is = activity.getResources().openRawResource(R.raw.circle); cascadeFile = new File(cascadeDir, "circle.xml"); break; case 2: default: is = activity.getResources().openRawResource(R.raw.triangle); cascadeFile = new File(cascadeDir, "triangle.xml"); break; } FileOutputStream os = new FileOutputStream(cascadeFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = is.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } is.close(); os.close(); // Load the cascade classifier switch (type) { case 1: cascadeClassifier1 = new CascadeClassifier(cascadeFile.getAbsolutePath()); break; case 2: default: cascadeClassifier2 = new CascadeClassifier(cascadeFile.getAbsolutePath()); break; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Java
UTF-8
1,323
2.78125
3
[]
no_license
import phases.UploadDayLiftRidesPhases; import java.io.IOException; import java.util.Scanner; public class Main { public static void main(String[] args) throws InterruptedException, IOException { try (Scanner scanner = new Scanner(System.in)) { System.out.println("Please enter the details to start the SKI application client program"); System.out.println("Maximum number of threads to run (max 256) : "); int numThreads = scanner.nextInt(); System.out.println("Number of skier to generate lift rides for (max 50000): "); int numSkiers = scanner.nextInt(); System.out.println("Number of ski lifts (range 5-60 and hit enter) : "); int numLifts = scanner.nextInt(); System.out.println("Mean number of ski lifts each skier rides each day"); int numRuns = scanner.nextInt(); System.out.println("IP/Port address of the server"); // "http://ec2-54-186-128-171.us-west-2.compute.amazonaws.com:8080/SkierAssignment_war" String serverAddress = scanner.next(); UploadDayLiftRidesPhases uploadDayLiftRides = new UploadDayLiftRidesPhases(numThreads, numSkiers, numLifts, numRuns, serverAddress); uploadDayLiftRides.initiate(); } } }
Java
UTF-8
1,542
2.703125
3
[]
no_license
package com.icode.library.tools.utils; import android.app.Activity; import android.util.DisplayMetrics; /** * 和系统屏幕相关的操作 * */ public class IScreenUtils { //屏幕宽度 private static int screenWidth = 0; //屏幕高度 private static int screenHeight = 0; //每英寸有多少个显示点 private static float density = 0; //Standard quantized DPI for screens. private static int densityDIP = 0; public static int getScreenWidth(Activity activity) { if(screenWidth==0) initScreen(activity); return screenWidth; } public static int getScreenHeight(Activity activity) { if(screenHeight==0) initScreen(activity); return screenHeight; } private static void initScreen(Activity activity){ DisplayMetrics displayMetrics = new DisplayMetrics(); activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); screenWidth = displayMetrics.widthPixels; screenHeight = displayMetrics.heightPixels; density = displayMetrics.density; densityDIP = displayMetrics.densityDpi; } public static DisplayMetrics getDisplayMetrics(Activity activity){ DisplayMetrics displayMetrics = new DisplayMetrics(); activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); return displayMetrics; } public static float getDensity(Activity activity) { if(density==0) initScreen(activity); return density; } public static int getDensityDIP(Activity activity) { if(densityDIP==0) initScreen(activity); return densityDIP; } }
PHP
UTF-8
3,890
2.8125
3
[]
no_license
<?php session_start(); if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){ header("Location: index.php"); exit; } // Include config file require_once "config.php"; // Define variables and initialize with empty values $username = $password = $err = ""; // Processing form data when form is submitted if($_SERVER["REQUEST_METHOD"] == "POST"){ // Check if username is empty if(empty(trim($_POST["username"]))){ $err = "Please enter username."; } else{ $username = trim($_POST["username"]); } if (empty($err)) { if(empty(trim($_POST["password"]))){ $err = "Please enter your password."; } else{ $password = trim($_POST["password"]); } } if (empty($err)) { $param_username = $username; $stmt = $conn->prepare('SELECT name, password FROM users WHERE username = ?' ); $stmt->bind_param('s', $param_username); $stmt->execute(); $result = $stmt->get_result(); if($result->num_rows == 1) { $row = $result->fetch_assoc(); $name =$row["name"]; $hashed_password=$row["password"]; //echo '<br> hashed_password',$hashed_password; //echo "<br> Name: ". $row["username"]. " " . $row["surname"] . "<br>"; if(password_verify ($password, $hashed_password) ){ session_start(); $_SESSION["loggedin"] = true; $_SESSION["name"] = $name; $_SESSION["username"] = $username; header("Location: index.php"); } else { // Username doesn't exist, display a generic error message $err = "Invalid username or password."; } } else { // Username doesn't exist, display a generic error message $err = "Invalid username or password."; } } } ?> <!DOCTYPE html> <html lang="en"> <head> <title> COVID-CT: Login</title> <meta charset="UTF-8"> <script src="map.js"></script> <link rel="stylesheet" href='covid_track.css'> <script> function clearForm(){ document.getElementById("form").reset(); }; </script> </head> <body> <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> <div class="covid19_title">COVID - 19 Contact Tracing</div> <div class="grid-container"> <div class="grid-title"> </div> <div class="grid-item">&nbsp; </div> <div class="grid-item"> <div class="login-container"> <div class="login-psw"> <input type="text" placeholder="username" name="username" class="form-control"> </div> <div class="login-psw"> <input type="password" name="password" placeholder="Password" class="form-control"> </div> <div class="login-item"> <input type="submit" class="btn" value="Login"> </div> <div class="login-item"> &nbsp;</div> <div class="login-item"> <input class="btn" type="reset" value="Cancel"> </div> <div class="login-register"> <a href="register.php"> <button type="button" class="btn">Register</button> </a> </div> <?php if(!empty($err)){ echo ' <div class="login-err" > '. $err.' </div> '; } ?> </div> </div> <div class="grid-item">&nbsp;</div> </div> </form> </body> </html>
C#
UTF-8
6,024
2.53125
3
[ "MIT", "Apache-2.0" ]
permissive
using System; using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Condensate_API.Models; using SteamKit2; using Condensate_API.Services; using System.Net.Http; using Microsoft.Extensions.Logging; using System.Text.RegularExpressions; namespace Condensate_API.Controllers { [Route("api/[controller]")] [ApiController] public class UsersController : ControllerBase { private readonly GameService _gameService; private readonly ILogger _logger; private readonly GameCacheService _gameCacheService; public UsersController(GameService gameService, GameCacheService gameCacheService, IHttpClientFactory clientFactory, ILogger<UsersController> logger) { _gameService = gameService; _gameCacheService = gameCacheService; _logger = logger; } // GET: api/users //[HttpGet] //public ActionResult<IEnumerable<Game>> Get() //{ // return null; //} private static string GetSteamID(string input) { string digit_pattern = @"^\d+$"; string user_homePattern = @"steamcommunity.com/id/([A-Za-z0-9\-]+)"; string user_nestedPattern = @"steamcommunity.com/id/([A-Za-z0-9\-]+)/.*"; string id_homePattern = @"steamcommunity.com/profiles/(\d+)"; string id_nestedPattern = @"steamcommunity.com/profiles/(\d+)/.*"; // see if the input is just the id Match digitMatch = Regex.Match(input.ToString().Replace("'", ""), digit_pattern); if (digitMatch.Success) return digitMatch.Value; Match id_homeMatch = Regex.Match(input, id_homePattern, RegexOptions.IgnoreCase); Match id_nestedMatch = Regex.Match(input, id_nestedPattern, RegexOptions.IgnoreCase); if (id_homeMatch.Success || id_nestedMatch.Success) return id_homeMatch.Success ? id_homeMatch.Groups[1].Value : id_nestedMatch.Groups[1].Value; Match user_homeMatch = Regex.Match(input, user_homePattern, RegexOptions.IgnoreCase); Match user_nestedMatch = Regex.Match(input, user_nestedPattern, RegexOptions.IgnoreCase); if (user_homeMatch.Success || user_nestedMatch.Success) { using (dynamic steam = WebAPI.GetInterface("ISteamUser", Environment.GetEnvironmentVariable("STEAM_API_KEY"))) { string user_name = user_homeMatch.Success ? user_homeMatch.Groups[1].Value : user_nestedMatch.Groups[1].Value; var res = steam.ResolveVanityURL(vanityurl: user_name); if (res["success"].AsUnsignedInteger() == 1) { return res["steamid"].AsString(); } } } return null; } private static User GetSteamProfile(string id) { using (dynamic steam = WebAPI.GetInterface("ISteamUser", Environment.GetEnvironmentVariable("STEAM_API_KEY"))) { KeyValue res = steam.GetPlayerSummaries(steamids: id); if (res["players"] != null) { User user = new User(); user.user_id = id; user.personaname = res["players"]["player"].Children[0]["personaname"].AsString(); user.IconURL = res["players"]["player"].Children[0]["avatarfull"].AsString(); return user; } } return null; } // GET: api/users/GetUserGamesById?id=5 [HttpGet("GetUserGamesById")] public ActionResult<UserGPs> GetUserGamesById(string id) { UserGPs ugps = new UserGPs(); ugps.gamePlaytimes = new HashSet<GamePlaytime>(); using (dynamic steam = WebAPI.GetInterface("IPlayerService", Environment.GetEnvironmentVariable("STEAM_API_KEY"))) { // note the usage of c#'s dynamic feature, which can be used // to make the api a breeze to use try { string user_id = GetSteamID(id); KeyValue res = steam.GetOwnedGames(steamid: user_id); // check if we can get games; maybe profile is private or bad id if (res.Children.Find(kv => kv.Name == "games") == null) // same as returning null return NoContent(); ugps.user = GetSteamProfile(user_id); // get hashset of known games to compare to HashSet<Game> games; // use the cached games to save on time games = new HashSet<Game>(_gameCacheService.Get(), new GameEqualityComparer()); foreach (KeyValue game in res["games"].Children) { uint appid = game["appid"].AsUnsignedInteger(); Game g = new Game(); g.name = "unknown"; g.appid = appid; g.store_link = Game.STORE_GAME_LINK_PREFIX + appid; g.header_image = Game.STEAM_LOGO_URL; // since it's stored in minutes double playtime = game["playtime_forever"].AsUnsignedInteger() / 60.0; if (games.TryGetValue(g, out Game f)) ugps.gamePlaytimes.Add(new GamePlaytime(f, playtime)); else ugps.gamePlaytimes.Add(new GamePlaytime(g, playtime)); } } catch (Exception e) { _logger.LogError(e, "Failed to get owned games"); return NotFound(); } } return ugps; } } }
Java
UTF-8
707
3.875
4
[]
no_license
import java.util.Scanner; public class Proyecto711 { public static void main(String[] zzz) { Scanner teclado= new Scanner(System.in); float p; float s; System.out.print("Ingrese el primer numero"); p = teclado.nextFloat(); System.out.print("Ingrese el segundo numero"); s = teclado.nextFloat(); if (p > s) { System.out.println("Pues el primero es mas grande:" ); System.out.println(p + s); System.out.println(p - s); } if (p < s) { System.out.println("Pues el segundo es mas grande:" ); System.out.println(p * s); System.out.println(p / s); } if (p==s) { System.out.println("Los numeros son iguales y no voy hacer nada"); } } }
JavaScript
UTF-8
2,406
2.5625
3
[]
no_license
import * as actionTypes from '../actions/actionTypes'; import { updateObject } from '../utility'; const initialState = { Movielist : [], initialMovieList : [], page : null, ModalStatus : false, activeMovie : null, pageNumber : 0, totalPages : null, scrolling : false, ratingFilter : ['RATED', 'HIGHEST RATED' , 'LOWEST RATED' ], selectedFilter : "RATED", trailerId : null } const getMoreMovieInfo = (state , action) => { let newModalStatus = !(state.ModalStatus); return updateObject( state , { ModalStatus : newModalStatus, activeMovie : action.id, trailerId : null } ) } const addMovieList = (state , action) => { const newMovieList = [...state.Movielist , ...action.movielist.results]; return updateObject( state, { Movielist: newMovieList, pageNumber: state.pageNumber + 1, page : action.movielist.page } ); } const getMoreMovieCards = (state , action) => { return state; } const filterMovieData = (state, action) => { let newMovieList = [...state.Movielist]; if(action.filterType === "LOWEST RATED"){ newMovieList.sort(function(a , b){ return (a.popularity - b.popularity) }) } else if (action.filterType === "HIGHEST RATED"){ newMovieList.sort(function(a , b){ return (b.popularity - a.popularity) }) } else { newMovieList = [...state.initialMovieList] } return updateObject( state, { Movielist: newMovieList, selectedFilter : action.filterType } ); } const getTrailerData = (state, action ) => { return updateObject( state, { trailerId : action.trailerId } ); } const reducer = ( state = initialState, action ) => { switch ( action.type ) { case actionTypes.SET_MOVIE_LIST: return addMovieList( state, action ); case actionTypes.GET_MORE_MOVIE_INFO : return getMoreMovieInfo(state , action); case actionTypes.GET_MORE_MOVIE_CARDS : return getMoreMovieCards(state , action); case actionTypes.FILTER_MOVIE_DATA : return filterMovieData(state , action); case actionTypes.GET_TRAILER : return getTrailerData(state , action); default: return state; } }; export default reducer;
Java
UTF-8
2,740
2.28125
2
[]
no_license
package cn.huaxunchina.cloud.location.app.lbs; import java.util.ArrayList; import java.util.List; import cn.huaxunchina.cloud.app.R; import com.baidu.mapapi.map.BitmapDescriptor; import com.baidu.mapapi.map.BitmapDescriptorFactory; import com.baidu.mapapi.map.MapView; import com.baidu.mapapi.map.Marker; import com.baidu.mapapi.map.MarkerOptions; import com.baidu.mapapi.map.OverlayOptions; import com.baidu.mapapi.model.LatLng; public class MarkerManager extends MapManager { private List<MarkerInfo> markers = new ArrayList<MarkerInfo>(); //构建Marker图标 private BitmapDescriptor markIcon = BitmapDescriptorFactory.fromResource(R.drawable.loc_zx_mark); public MarkerManager(MapView mMapView) { super(mMapView); // TODO Auto-generated constructor stub } public void addLatLng(MarkerInfo latLng){ this.markers.add(latLng); } public MarkerInfo getMarker(int index){ return markers.get(index); } public MarkerInfo getMarkerInfo(int index){ return markers.get(index); } public void setLatLngs(List<MarkerInfo> latLngs){ this.markers=latLngs; } protected List<MarkerInfo> getMarkerInfo(){ return this.markers; } public void drawMarker(MarkerInfo info){ //构建MarkerOption,用于在地图上添加Marker OverlayOptions option = new MarkerOptions().position(info.latlng).icon(markIcon); //在地图上添加Marker,并显示 Marker m =(Marker)getBaiduMap().addOverlay(option); m.setAnchor(0.5f, 0.5f); info.marker=m; markers.add(info); } public Marker drawMarker(LatLng point,BitmapDescriptor icon){ //构建MarkerOption,用于在地图上添加Marker OverlayOptions option = new MarkerOptions().position(point).icon(icon); //在地图上添加Marker,并显示 Marker m =(Marker)getBaiduMap().addOverlay(option); return m; } public void drawAddMarker(){ int size = markers.size(); for(int i=0;i<size;i++){ drawMarker(markers.get(i)); } } public void setMarkIcon(BitmapDescriptor bitamap){ this.markIcon = bitamap; } public void clearMarkers(){ int size = markers.size(); for(int i=0;i<size;i++){ Marker m= markers.get(i).marker; if(m!=null){ m.remove(); } } markers.clear(); } /** * TODO(描述) * @param m 小于负一表示没有找到 * @return */ public int getIndexes(Marker m){ int indexes = -1; int size = markers.size(); for(int i=0;i<size;i++){ if(m==markers.get(i).marker){ indexes=markers.get(i).tag; } } return indexes; } public MarkerInfo getMarkerInfo(Marker m){ MarkerInfo info = null; int size = markers.size(); for(int i=0;i<size;i++){ if(m==markers.get(i).marker){ info=markers.get(i); } } return info; } }
Python
UTF-8
1,625
2.859375
3
[]
no_license
import simpy import random SIM_TIME = 1000 RANDOM_SEED = 42 MEAN = 1.8 VAR = 0.2 NUM_MACHINES = 10 REPOSITORY = 3 NUM_REPAIRMEN = 3 MAX_EXPERIENCE = 1.65 MIN_EXPERIENCE = 0.55 # Constante que calcula la experiencia del operario EXPERIENCE_PER_HOUR = (MAX_EXPERIENCE-MIN_EXPERIENCE)/SIM_TIME class SystemMachine(object): def __init__(self, env): self.env = env self.machines = simpy.Resource(env, NUM_MACHINES) self.repairmen = simpy.Resource(env, NUM_REPAIRMEN) def machine(env, name, system): # Espera hasta que ocupa un recurso cuando esta disponible # y lo libera cuando lo deja (automaticamente) print('%s arrives to the system at %.2f.' % (name, env.now)) while True: with system.machines.request() as request: yield request print('%s working at %.2f.' % (name, env.now)) yield env.timeout(random.normalvariate(MEAN, VAR)) print('%s has failed at %.2f.' % (name, env.now)) with system.repairmen.request() as request: yield request paramExponential = (EXPERIENCE_PER_HOUR*env.now)+MIN_EXPERIENCE yield env.timeout(random.expovariate(paramExponential)) print('%s repaired at %.2f.' % (name, env.now)) # Create an environment and start the setup process random.seed(RANDOM_SEED) env = simpy.Environment() system = SystemMachine(env) # Create 13 machines total_machines = NUM_MACHINES + REPOSITORY for i in range(total_machines): env.process(machine(env, 'Machine %d' % i, system)) # Execute! env.run(until=SIM_TIME)
Java
UTF-8
303
1.640625
2
[]
no_license
package android.com.mobilechat.model.notification.body; import lombok.Builder; import lombok.Data; @Data @Builder public class BecameRoomMemberBody { private final Long roomId; private final String roomName; private final String roomDescription; private final int roomMembersCount; }
Java
UTF-8
5,429
2.390625
2
[]
no_license
package math.nyx.framework.square; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import math.nyx.framework.square.SquareDecimationStrategy; import math.nyx.utils.TestUtils; import org.apache.commons.math.linear.Array2DRowRealMatrix; import org.apache.commons.math.linear.RealMatrix; import org.apache.commons.math.linear.SparseRealMatrix; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"file:src/main/resources/applicationContext.xml"}) public class SquareDecimationStrategyTest { @Autowired private SquareDecimationStrategyFactory sdStrategyFactory; private SquareDecimationStrategy getDecimator(int rangeDimension, int domainDimension) { return sdStrategyFactory.getDecimator(rangeDimension, domainDimension); } private SparseRealMatrix getDecimationOperator(int rangeDimension, int domainDimension) { return getDecimator(rangeDimension, domainDimension).getDecimationOperator(); } @Test public void checkOffset() { // 3x3 -> 2x2 SquareDecimationStrategy sdStrategy = getDecimator(4, 9); assertEquals(0, sdStrategy.getOffset(0)); assertEquals(1, sdStrategy.getOffset(1)); assertEquals(3, sdStrategy.getOffset(2)); assertEquals(4, sdStrategy.getOffset(3)); // 16x16 -> 8x8 sdStrategy = getDecimator(64, 256); assertEquals(0, sdStrategy.getOffset(0)); assertEquals(2, sdStrategy.getOffset(1)); assertEquals(4, sdStrategy.getOffset(2)); assertEquals(6, sdStrategy.getOffset(3)); // ... assertEquals(32, sdStrategy.getOffset(8)); } @Test public void checkIndex() { // 3x3 -> 2x2 SquareDecimationStrategy sdStrategy = getDecimator(4, 9); assertEquals(0, sdStrategy.getIndex(0)); assertEquals(1, sdStrategy.getIndex(1)); assertEquals(3, sdStrategy.getIndex(2)); assertEquals(4, sdStrategy.getIndex(3)); // 16x16 -> 8x8 sdStrategy = getDecimator(64, 256); assertEquals(0, sdStrategy.getIndex(0)); assertEquals(1, sdStrategy.getIndex(1)); assertEquals(16, sdStrategy.getIndex(2)); assertEquals(17, sdStrategy.getIndex(3)); } @Test public void decimateSmall() throws InterruptedException { // Generate RealMatrix signal = TestUtils.generateSignal(9); // Decimate SparseRealMatrix decimator = getDecimationOperator(4, 9); RealMatrix decimated = decimator.multiply(signal); // Verify assertArrayEquals(new double[]{3, 4, 6, 7}, decimated.getColumn(0), TestUtils.DELTA); } @Test public void decimateLarge() { double domainVector[] = new double[] { 51.0, 43.0, 54.0, 59.0, 56.0, 56.0, 52.0, 56.0, 55.0, 55.0, 55.0, 59.0, 60.0, 29.0, 16.0, 33.0, 43.0, 50.0, 56.0, 57.0, 54.0, 53.0, 54.0, 57.0, 58.0, 55.0, 57.0, 62.0, 55.0, 24.0, 16.0, 31.0, 51.0, 60.0, 57.0, 51.0, 50.0, 52.0, 53.0, 55.0, 56.0, 58.0, 60.0, 56.0, 47.0, 23.0, 15.0, 25.0, 52.0, 54.0, 54.0, 51.0, 49.0, 48.0, 53.0, 51.0, 53.0, 58.0, 59.0, 54.0, 44.0, 22.0, 14.0, 19.0, 51.0, 50.0, 48.0, 49.0, 48.0, 46.0, 48.0, 51.0, 54.0, 56.0, 52.0, 46.0, 41.0, 21.0, 13.0, 14.0, 54.0, 48.0, 47.0, 46.0, 47.0, 44.0, 46.0, 51.0, 48.0, 49.0, 47.0, 42.0, 31.0, 16.0, 11.0, 10.0, 48.0, 44.0, 41.0, 38.0, 39.0, 38.0, 40.0, 43.0, 44.0, 40.0, 38.0, 33.0, 25.0, 14.0, 12.0, 8.0, 27.0, 25.0, 27.0, 28.0, 28.0, 32.0, 32.0, 30.0, 32.0, 30.0, 27.0, 25.0, 22.0, 15.0, 12.0, 9.0, 16.0, 19.0, 23.0, 23.0, 23.0, 21.0, 21.0, 23.0, 24.0, 26.0, 24.0, 24.0, 22.0, 21.0, 15.0, 10.0, 8.0, 9.0, 11.0, 12.0, 12.0, 13.0, 13.0, 17.0, 17.0, 21.0, 20.0, 19.0, 20.0, 25.0, 20.0, 14.0, 10.0, 8.0, 9.0, 11.0, 10.0, 9.0, 9.0, 9.0, 10.0, 12.0, 12.0, 13.0, 16.0, 17.0, 19.0, 20.0, 20.0, 14.0, 11.0, 10.0, 11.0, 11.0, 10.0, 10.0, 10.0, 9.0, 10.0, 9.0, 11.0, 13.0, 17.0, 19.0, 39.0, 34.0, 23.0, 15.0, 13.0, 12.0, 11.0, 11.0, 11.0, 11.0, 10.0, 9.0, 10.0, 11.0, 11.0, 13.0, 35.0, 32.0, 28.0, 24.0, 21.0, 16.0, 13.0, 12.0, 11.0, 11.0, 10.0, 10.0, 12.0, 12.0, 11.0, 10.0, 21.0, 20.0, 17.0, 15.0, 16.0, 18.0, 17.0, 13.0, 13.0, 12.0, 13.0, 12.0, 12.0, 14.0, 14.0, 13.0, 14.0, 14.0, 15.0, 14.0, 12.0, 14.0, 13.0, 12.0, 12.0, 12.0, 12.0, 13.0, 12.0, 14.0, 15.0, 13.0 }; double decimatedDomainVector[] = new double[] { 46.75, 56.5, 54.75, 54.75, 55.75, 58.25, 42.0, 24.0, 54.25, 53.25, 49.75, 53.0, 56.25, 57.25, 34.0, 18.25, 50.75, 47.5, 46.25, 49.0, 51.75, 46.75, 27.25, 12.0, 36.0, 33.5, 34.25, 36.25, 36.5, 30.75, 19.0, 10.25, 13.0, 17.25, 17.25, 18.5, 22.0, 21.75, 22.0, 14.75, 13.0, 10.25, 10.25, 9.5, 10.25, 11.0, 14.25, 18.75, 35.0, 22.5, 15.5, 11.75, 11.0, 9.75, 11.25, 11.25, 17.25, 15.25, 15.0, 13.75, 12.25, 12.5, 13.0, 13.75 }; RealMatrix domain = new Array2DRowRealMatrix(domainVector.length, 1); domain.setColumn(0, domainVector); RealMatrix expectedDecimatedDomain = new Array2DRowRealMatrix(decimatedDomainVector.length, 1); expectedDecimatedDomain.setColumn(0, decimatedDomainVector); // Decimate SparseRealMatrix decimator = getDecimationOperator(decimatedDomainVector.length, domainVector.length); RealMatrix decimatedDomain = decimator.multiply(domain); // Verify assertArrayEquals(expectedDecimatedDomain.getColumn(0), decimatedDomain.getColumn(0), TestUtils.DELTA); } }
PHP
UTF-8
1,727
2.625
3
[]
no_license
<?php namespace ProjectesWeb\Controller; use ProjectesWeb\Model\Repository\TasksRepository; use ProjectesWeb\View\ViewHelper; use Zend\Diactoros\Response; use ProjectesWeb\Model\Entity\Task; /** * Class TaskController * @package ProjectesWeb\lib\Controller */ class TaskController { private $request; /** * @var TasksRepository */ private $repository; /** * @var ViewHelper */ private $viewHelper; /** * TaskController constructor. * @param $request * @param ViewHelper $viewHelper * @param TasksRepository $repository */ public function __construct($request, TasksRepository $repository, ViewHelper $viewHelper) { $this->request = $request; $this->viewHelper = $viewHelper; $this->repository = $repository; } public function indexAction() { $tasks = $this->repository->getAll(); $responseBody = $this->viewHelper->render('home', ['tasks' => $tasks]); $response = new Response(); $response->getBody()->write($responseBody); return $response; } public function getAddTaskAction(){ $responseBody = $this->viewHelper->renderAdd(); $response = new Response(); $response->getBody()->write($responseBody); return $response; } public function postAddTaskAction($dada){ $last = $this->repository->getLastInsertedId(); $num = $last +1; $task = $this->repository->createTask($num, $dada); $this->repository->save($task); header('Location: /'); } public function removeTaskAction($id){ $this->repository->delete($id); header('Location: /'); } }
Java
UTF-8
2,538
2.109375
2
[]
no_license
package com.spoid; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; public class SplashActivity extends AppCompatActivity { Handler handler; Intent intent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); handler = new Handler(); // // new Thread(new Runnable() { // @Override // public void run() { // try { // Thread.sleep(2500); // handler.post(new Runnable() { // @Override // public void run() { // Animation fade_out = AnimationUtils.loadAnimation(getApplicationContext(), android.R.anim.fade_out); // } // }); // // Thread.sleep(500); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // intent = new Intent(SplashActivity.this, CameraActivity.class); // handler.post(new Runnable() { // @Override // public void run() { // startActivity(intent); // overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out); // finish(); // } // }); // // } // }).start(); final Button button = (Button) findViewById(R.id.button); final TextView resister = (TextView) findViewById(R.id.textView4); View.OnClickListener listener1 = new View.OnClickListener() { //로그인페이지 @Override public void onClick(View v) { // TODO Auto-generated method stub startActivity(new Intent(SplashActivity.this, LoginActivity.class)); } }; View.OnClickListener listener2 = new View.OnClickListener() { //회원가입 @Override public void onClick(View v) { // TODO Auto-generated method stub startActivity(new Intent(SplashActivity.this, JoinActivity.class)); } }; resister.setOnClickListener(listener2); button.setOnClickListener(listener1); } }
Java
UTF-8
849
2.765625
3
[]
no_license
package irvine.oeis.a014; import irvine.factor.factor.Cheetah; import irvine.math.group.IntegerField; import irvine.math.group.PolynomialRingField; import irvine.math.polynomial.Polynomial; import irvine.math.z.Z; import irvine.oeis.Sequence; /** * A014651 Number of partitions of n into its nonprime divisors with at least one part of size 1. * @author Sean A. Irvine */ public class A014651 implements Sequence { private static final PolynomialRingField<Z> RING = new PolynomialRingField<>(IntegerField.SINGLETON); private int mN = 0; @Override public Z next() { Polynomial<Z> prod = RING.one(); for (final Z d : Cheetah.factor(++mN).divisors()) { if (!d.isProbablePrime()) { prod = RING.multiply(prod, RING.oneMinusXToTheN(d.intValueExact()), mN); } } return RING.coeff(RING.one(), prod, mN - 1); } }
Java
UTF-8
1,004
3.078125
3
[]
no_license
import java.util.Scanner; // codeforces.com/problemset/problem/828/A public class RestaurantTables { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int a = s.nextInt(); int b = s.nextInt(); int[] customers = new int[n]; for(int i = 0; i < n; i++) customers[i] = s.nextInt(); int res = 0, alone = 0; for(int i = 0; i < n; i++) { if(customers[i] == 1) { if(a > 0) { a--; } else if(b > 0) { alone++; b--; } else if(b == 0 && alone > 0) { alone--; } else res++; } else if(customers[i] == 2) { if(b > 0) { b--; } else res += 2; } } System.out.println(res); } }