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
C++
GB18030
1,119
2.765625
3
[]
no_license
#include "EventLoopThread.h" #include "EventLoop.h" using namespace kimgbo; using namespace kimgbo::net; EventLoopThread::EventLoopThread(const ThreadInitCallback& cb) : m_loop(NULL), m_exiting(false), m_thread(std::bind(&EventLoopThread::threadFunc, this)), m_mutex(), m_cond(m_mutex), m_callback(cb) { } EventLoopThread::~EventLoopThread() { m_exiting = true; m_loop->quit(); //ֹI/O߳ m_thread.join(); } EventLoop* EventLoopThread::startLoop() { assert(!m_thread.started()); m_thread.start(); { MutexLockGuard lock(m_mutex); while (m_loop == NULL) { //ȴstartеthreadfuncEventLoopɹŻ᷵ m_cond.wait(); } } return m_loop; } void EventLoopThread::threadFunc() { //ջ󣬵˺˳ζŴI/O̵ֹ߳ EventLoop loop; if (m_callback) { m_callback(&loop); //ں̱߳ش洢ݽϣ߷˵IJ } { MutexLockGuard lock(m_mutex); m_loop = &loop; m_cond.notify(); } loop.loop(); //assert(exiting_); }
Java
UTF-8
1,560
2.84375
3
[]
no_license
package clientlib; public enum Elements { NONE(' '), BATTLE_WALL('☼'), BANG('Ѡ'), CONSTRUCTION('╬'), CONSTRUCTION_DESTROYED_DOWN('╩'), CONSTRUCTION_DESTROYED_UP('╦'), CONSTRUCTION_DESTROYED_LEFT('╠'), CONSTRUCTION_DESTROYED_RIGHT('╣'), CONSTRUCTION_DESTROYED_DOWN_TWICE('╨'), CONSTRUCTION_DESTROYED_UP_TWICE('╥'), CONSTRUCTION_DESTROYED_LEFT_TWICE('╞'), CONSTRUCTION_DESTROYED_RIGHT_TWICE('╡'), CONSTRUCTION_DESTROYED_LEFT_RIGHT('│'), CONSTRUCTION_DESTROYED_UP_DOWN('─'), CONSTRUCTION_DESTROYED_UP_LEFT('┌'), CONSTRUCTION_DESTROYED_RIGHT_UP('┐'), CONSTRUCTION_DESTROYED_DOWN_LEFT('└'), CONSTRUCTION_DESTROYED_DOWN_RIGHT('┘'), CONSTRUCTION_DESTROYED(' '), BULLET('•'), TANK_UP('▲'), TANK_RIGHT('►'), TANK_DOWN('▼'), TANK_LEFT('◄'), OTHER_TANK_UP('˄'), OTHER_TANK_RIGHT('˃'), OTHER_TANK_DOWN('˅'), OTHER_TANK_LEFT('˂'), AI_TANK_UP('?'), AI_TANK_RIGHT('»'), AI_TANK_DOWN('¿'), AI_TANK_LEFT('«'); public final char ch; Elements(char ch) { this.ch = ch; } public static Elements valueOf(char ch) { for (Elements el : Elements.values()) { if (el.ch == ch) { return el; } } throw new IllegalArgumentException("No such element for " + ch); } public char ch() { return ch; } @Override public String toString() { return String.valueOf(ch); } }
Python
UTF-8
1,182
2.828125
3
[ "LicenseRef-scancode-public-domain", "BSD-3-Clause" ]
permissive
import os from subprocess import run, PIPE, STDOUT import time def wait_for_job(status_ticker_queue): while True: p = run(["hetero", "jobs"], stdout=PIPE, stderr=STDOUT) if p.stdout.decode('ascii').rstrip() == "": for key in status_ticker_queue.keys(): if status_ticker_queue[key] == "failed": print("ERROR: status is 'failed' for '"+key+"'") break time.sleep(1) def check_file_exists(filename): if not os.path.isfile(filename): print("ERROR: "+filename+" is missing") return False return True def count_lines_with_word(filename, word, rightanswer): if not check_file_exists(filename): return count = 0 with open(filename,'r') as fid: for line in fid: if word in line: count += 1 if count != rightanswer: print("ERROR: "+filename+" has "+str(count)+" "+word+" when it should have "+str(rightanswer)) def count_lines(filename, rightanswer): if not check_file_exists(filename): return count = 0 with open(filename,'r') as fid: for line in fid: count += 1 if count != rightanswer: print("ERROR: "+filename+" has "+str(count)+" lines when it should have "+str(rightanswer))
Markdown
UTF-8
3,944
2.6875
3
[]
no_license
--- description: "Simple Way to Make Perfect Peanut Butter Cheesecake Brownies" title: "Simple Way to Make Perfect Peanut Butter Cheesecake Brownies" slug: 878-simple-way-to-make-perfect-peanut-butter-cheesecake-brownies date: 2021-02-15T22:59:15.775Z image: https://img-global.cpcdn.com/recipes/6585483939807232/680x482cq70/peanut-butter-cheesecake-brownies-recipe-main-photo.jpg thumbnail: https://img-global.cpcdn.com/recipes/6585483939807232/680x482cq70/peanut-butter-cheesecake-brownies-recipe-main-photo.jpg cover: https://img-global.cpcdn.com/recipes/6585483939807232/680x482cq70/peanut-butter-cheesecake-brownies-recipe-main-photo.jpg author: Lucy Romero ratingvalue: 4.6 reviewcount: 10389 recipeingredient: - "1 packages Chewy Brownie Mix 13x9 in pan size" - "1 packages Cream cheese 8oz size softened" - "1/3 cup Sugar" - "1 Egg" - "1/4 cup Creamy Peanut Butter" - "1/2 tsp Vanilla Extract" - "1 Cool Whip topping" - "1 Cherries" recipeinstructions: - "Pre heat oven to 350" - "Mix brownie batter as directed on package" - "In a bowl, mix cream cheese, sugar, egg, peanut butter, and vanilla until well blended" - "Line mini muffin pans with paper liners, makes about 40" - "Spoon in brownie mix to muffin pans, filling to about 3/4 full" - "Spoon peanut butter mixture onto brownie mixture, pressing into batter slightly" - "Bake for about 20 to 30 minutes, until a toothpick comes out clean" - "Let cool, then add cool whip and cherries. Enjoy!" categories: - Recipe tags: - peanut - butter - cheesecake katakunci: peanut butter cheesecake nutrition: 148 calories recipecuisine: American preptime: "PT40M" cooktime: "PT40M" recipeyield: "2" recipecategory: Lunch --- ![Peanut Butter Cheesecake Brownies](https://img-global.cpcdn.com/recipes/6585483939807232/680x482cq70/peanut-butter-cheesecake-brownies-recipe-main-photo.jpg) Hello everybody, it is Brad, welcome to our recipe page. Today, I will show you a way to prepare a distinctive dish, peanut butter cheesecake brownies. It is one of my favorites food recipes. This time, I will make it a little bit tasty. This will be really delicious. Peanut Butter Cheesecake Brownies is one of the most well liked of current trending foods on earth. It is appreciated by millions every day. It's easy, it's quick, it tastes yummy. They're fine and they look fantastic. Peanut Butter Cheesecake Brownies is something that I've loved my entire life. To get started with this particular recipe, we have to first prepare a few components. You can have peanut butter cheesecake brownies using 8 ingredients and 8 steps. Here is how you cook that. <!--inarticleads1--> ##### The ingredients needed to make Peanut Butter Cheesecake Brownies: 1. Make ready 1 packages Chewy Brownie Mix, 13x9 in. pan size 1. Make ready 1 packages Cream cheese 8oz. size, softened 1. Take 1/3 cup Sugar 1. Prepare 1 Egg 1. Make ready 1/4 cup Creamy Peanut Butter 1. Get 1/2 tsp Vanilla Extract 1. Take 1 Cool Whip topping 1. Make ready 1 Cherries <!--inarticleads2--> ##### Steps to make Peanut Butter Cheesecake Brownies: 1. Pre heat oven to 350 1. Mix brownie batter as directed on package 1. In a bowl, mix cream cheese, sugar, egg, peanut butter, and vanilla until well blended 1. Line mini muffin pans with paper liners, makes about 40 1. Spoon in brownie mix to muffin pans, filling to about 3/4 full 1. Spoon peanut butter mixture onto brownie mixture, pressing into batter slightly 1. Bake for about 20 to 30 minutes, until a toothpick comes out clean 1. Let cool, then add cool whip and cherries. Enjoy! So that is going to wrap this up for this special food peanut butter cheesecake brownies recipe. Thanks so much for reading. I am confident that you can make this at home. There's gonna be interesting food at home recipes coming up. Don't forget to bookmark this page on your browser, and share it to your family, colleague and friends. Thank you for reading. Go on get cooking!
SQL
WINDOWS-1250
1,169
3.625
4
[]
no_license
/* Fecha: 24 SETIEMBRE 2018 Autor: Mariela Barrantes Descripcion: TABLA CATALOGO OCUPACION */ create table OCUPACION ( id_Ocupacion number(6), nombre varchar2(30) CONSTRAINT Ocupacion_nombre_NN NOT NULL, --Atributos Auditoria Fecha_creacion DATE, Usuario_creacion VARCHAR2(10), Fecha_ultima_modificacion DATE, Usuario_ultima_modificacion VARCHAR2(10) ); ALTER table OCUPACION add constraint pk_Ocupacion primary key (id_Ocupacion) using index tablespace ce_ind pctfree 20 storage (initial 10k next 10k pctincrease 0); --------------------------------------------------------------- --Comentarios de la tabla y atributos COMMENT ON TABLE OCUPACION IS 'CATALOGO OCUPACION'; COMMENT ON COLUMN CE.OCUPACION.id_Ocupacion IS 'IDENTIFICADOR NICO DE LA TABLA'; COMMENT ON COLUMN CE.OCUPACION.nombre IS 'ATRIBUTO CON EL NOMBRE DE LA OCUPACION'; COMMENT ON COLUMN CE.OCUPACION.Fecha_creacion IS 'ATRIBUTO AUDITORIA'; COMMENT ON COLUMN CE.OCUPACION.Usuario_creacion IS 'ATRIBUTO AUDITORIA'; COMMENT ON COLUMN CE.OCUPACION.Fecha_ultima_modificacion IS 'ATRIBUTO AUDITORIA'; COMMENT ON COLUMN CE.OCUPACION.Usuario_ultima_modificacion IS 'ATRIBUTO AUDITORIA';
Java
UTF-8
2,204
2.046875
2
[ "Apache-2.0", "CC-BY-3.0" ]
permissive
/* * Copyright (C) 2012 CONIT Co., Ltd. * * 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 jp.co.conit.sss.sp.ex1.fragment; import jp.co.conit.sss.sp.ex1.R; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; /** * 設定機能(リストア)を提供するFragmentです。 * * @author conit */ public class SettingsFragment extends Fragment { private OnRestoreLisntener mOnRestoreLisntener; /** * リストア処理のリスナーです。 * * @author conit */ public interface OnRestoreLisntener { void onRestore(); } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mOnRestoreLisntener = (OnRestoreLisntener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnRestoreLisntener"); } }; public static SettingsFragment newInstance() { SettingsFragment fragment = new SettingsFragment(); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_settings, null); view.findViewById(R.id.btn_restore).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mOnRestoreLisntener.onRestore(); } }); return view; } }
Python
UTF-8
150
3.140625
3
[]
no_license
class Solution: def mySqrt(self, x: int) -> int: return int(x**0.5) if __name__ == "__main__": s = Solution() print(s.mySqrt(8))
Markdown
UTF-8
784
3.171875
3
[]
no_license
# Celebrate Success If the project finishes a phase successfully \(e.g. first successful production release\) this should be celebrated. This is important because: * **Motivation** Celebrating success is a kind of appreciation to the people who did a good job in the past days. Appreciation is an important booster for motivation which could lead to even better performance in the following iterations. * **Make success visible to others** The idea of making success visible is not to show off but to raise awareness about the things that go well. A sponsor might be willing to invest more in the project if he sees that his investments pay off. * **Learn and adapt** To celebrate success helps to recognize what's working well. So basically you can do more of it.
JavaScript
UTF-8
6,186
2.8125
3
[]
no_license
/* WebWorkerController.js Contains logic that is used to control the web worker processes that compute the values to color each pixel on the canvas. */ // jslint directive /*jslint browser: true, white: true*/ /*global Form, drawingFunctions, Progress, alert, Worker*/ (function () { 'use strict'; var configuration, minR, maxR, minI, maxI, graphingMethod, limit, max, tolerance, maxPeriod, plotSize, rowResults, workers; // Cancel any currently running drawing. function cancelDrawing() { var i; // In order to cancel the drawing, terminate all of the web-worker processes. if (workers) { for (i = 0; i < workers.length; i += 1) { workers[i].terminate(); } } // Close any previously opened Progress dialog. Progress.hideProgress(); } // Draw the image. function startDrawing() { var nextRowNumber, width, height, farmSize, i, rowsComputed, times = []; function setupWorker(thisWorker) { thisWorker.postMessage({ mode: 'setup', code: configuration.code, canvasWidth: width, canvasHeight: height }); } // Post a message to a particular worker to compute the next row of escape values. function computeNextRowAsync(thisWorker) { thisWorker.postMessage({ mode: 'computeResult', canvasWidth: width, canvasHeight: height, graphingMethod: graphingMethod, limit: limit, max: max, tolerance: tolerance, maxPeriod: maxPeriod, rowNumber: nextRowNumber, minR: minR, maxR: maxR, minI: minI, maxI: maxI }); } // Before doing anything, stop any previous drawing operation. cancelDrawing(); // Starts at -1 because it gets incremented at the beginning of a loop and should be 0 at the first run. nextRowNumber = -1; rowsComputed = 0; workers = []; configuration = Form.getConfiguration(); if (configuration.textFunction === '') { alert('There is no iterating function specified.'); return; } plotSize = configuration.plotSize; limit = configuration.numEscape; max = configuration.numMaxIterations; farmSize = configuration.numWorkers; minR = configuration.minR; maxR = configuration.maxR; minI = configuration.minI; maxI = configuration.maxI; graphingMethod = configuration.graphingMethod; // Parameters to the "Perodicity Time" graphing method tolerance = configuration.tolerance; maxPeriod = configuration.maxPeriod; // Now that the plot new co-ordinates have been read from the "Proposed New Plot location", // update the form to display the new co-ordinates in the "Plot Location" Form.setPlotCoordinates(minR, maxR, minI, maxI); // Set the canvas size to what the user specified. width = height = plotSize; drawingFunctions.setPlotDimensions(width, height); rowResults = new Array(height); // Show the progress dialog with a [Cancel] button that will stop the drawing. Progress.showProgress('Drawing Image...', null, true, cancelDrawing); for (i = 0; i < farmSize; i += 1) { (function () { var worker; worker = new Worker('Scripts/computer.js'); nextRowNumber += 1; // When we get a message back from the web worker, we expect that it contains the howManyToEscape values // for a row of pixels in the canvas. // In the event listener that listens to these messages, we read and display this data. // Once that's done, check and see if this was the last row, and if it's not, go process the new row. worker.addEventListener('message', function (e) { var computedRowNumber, result; times.push(e.data.time); computedRowNumber = e.data.rowNumber; result = e.data.result; rowResults[computedRowNumber] = result; // nextRowNumber and rowsComputed must be trackes separately because some rows // take longer to draw than others. nextRowNumber += 1; rowsComputed += 1; if (nextRowNumber < height) { // If there is another row to compute, compute it! computeNextRowAsync(worker); } else { // If there are no more rows to compute, this worker is done. // If all workers are done, then it's time to color the pixels to draw the image. farmSize -= 1; if (farmSize === 0) { drawingFunctions.colorPixels(rowResults, configuration.numMaxIterations, configuration.colors); Progress.hideProgress(); } } // Update the progress bar with the current progress as a result of the computation being done. Progress.setProgress(rowsComputed, height); }, false); // Setup the worker with the code specified by the user. setupWorker(worker); // Start the worker on the next row. computeNextRowAsync(worker); // Put the worker into an array that allows us to easily stop the operation if the user clicks [Cancel]. workers.push(worker); } ()); } } // end startDrawing Form.setPlotSizeByWindowSize(); Form.setupForm(startDrawing); } ());
C++
UTF-8
2,376
3.375
3
[]
no_license
/// main.cpp - Bubble Sort #include <iostream> #include <stdlib.h> #include <time.h> using namespace std; void ASMBubbleSort(long*, long); int main() { /// Fill an array with pseudorandom integers. const unsigned ARRAY_SIZE = 100000; long array[ARRAY_SIZE]; for(unsigned i = 0; i < ARRAY_SIZE; i++) array[i] = rand(); time_t startTime; time_t endTime; /// Test the C++ function: cout << "Running C++ version of bubble sort...." << endl; time( &startTime ); for(int i = 0; i < ARRAY_SIZE; i++) { for(int j = i + 1; j < ARRAY_SIZE; j++) { if(array[i] > array[j]) { long temp = array[i]; array[i] = array[j]; array[j] = temp; } } } time( &endTime ); cout << "Elapsed CPP time: " << long(endTime - startTime) << " seconds" << endl; /// Test the Assembly language version: cout << endl << endl; cout << "Running ASM version of bubble sort...." << endl; time( &startTime ); long* arrayPtr = array; ASMBubbleSort(arrayPtr, ARRAY_SIZE); time( &endTime ); cout << "Elapsed ASM time: " << long(endTime - startTime) << " seconds" << endl; cout << endl << "Press enter to end" << endl; cin.ignore(); } void ASMBubbleSort(long* arrayPtr, long arraySize) { __asm { MOV ESI, arrayPtr MOV EBX, arraySize MOV EAX, ESI ; set EAX=ESI MOV ECX, EBX ; set ECX=EBX DEC ECX ; set ECX=CX-1 OUTER_LOOP: ; loop label MOV EBX, ECX ; set EBX=ECX MOV ESI, EAX ; set ESI=EAX MOV EDI, EAX ; set EDI=EAX INC EDI ; set EDI=EDI+1 INNER_LOOP: ; loop label MOV EDX, [ESI] ; set EDX=[ESI] CMP EDX, [EDI] ; compare EDX with [EDI] JNG SKIP_EXCHANGE ; jump to label @SKIP_EXCHANGE if EDX<[EDI] XCHG EDX, [EDI] ; set EDX=[EDI], [EDI]=EDX MOV [ESI], EDX ; set [ESI]=EDX SKIP_EXCHANGE: ; jump label INC ESI ; set ESI=ESI+1 INC EDI ; set EDI=EDI+1 DEC EBX ; set EBX=EBX-1 JNZ INNER_LOOP ; jump to label @INNER_LOOP if EBX!=0 LOOP OUTER_LOOP ; jump to label @OUTER_LOOP while ECX!=0 }; }
C#
UTF-8
3,271
3.671875
4
[]
no_license
using System; using System.Collections; using System.Linq; namespace EN_Lab_09 { public interface ISequenceDecorator { public string Description(); public IEnumerable Decorate(IEnumerable enumerable); } public class SequenceSum : ISequenceDecorator { public IEnumerable Decorate(IEnumerable enumerable) { int sum = 0; foreach (int elem in enumerable) { sum += elem; yield return sum; } } public string Description() { return $"SequenceSum()"; } } public class LessThanFilter : ISequenceDecorator { private int limit; private bool memory; public LessThanFilter(int Limit, bool Memory = false) { limit = Limit; memory = Memory; } public IEnumerable Decorate(IEnumerable enumerable) { bool last_flag = false; int last = 0; foreach (int elem in enumerable) { if (!memory) { if (elem < limit) yield return elem; } else { if (elem < limit) { last = elem; last_flag = true; yield return elem; } else if (last_flag) { yield return last; } } } } public string Description() { return $"LessThanFilter({limit}, {memory})"; } } public class MedianFilter : ISequenceDecorator { private int filtersize; public MedianFilter(int FilterSize) { filtersize = FilterSize; } public IEnumerable Decorate(IEnumerable enumerable) { IEnumerator pos = enumerable.GetEnumerator(); int[] tab = new int[filtersize]; int count = 0; while(pos.MoveNext()) { count++; tab[count - 1] = (int)pos.Current; // copy elements to array if(count == filtersize) // when filtersize many elements are in array { Array.Sort(tab); // sort the array yield return tab[filtersize / 2]; // return the median count = 0; // reset counter } } if (count != 0) // if sequence ended and there are elements in array { int[] tab2 = tab[0..count]; // only use the last copied elements ("count"-many) Array.Sort(tab2); // sort the array yield return tab2[count / 2]; // return median of "count"-many elements } } public string Description() { return $"MedianFilter({filtersize})"; } } }
Java
UTF-8
180
1.5625
2
[]
no_license
package challenges.strategy; public class PlusCameraApp extends PhoneCameraApp { public void edit() { } public void share() { shareStrategy.share(); } }
Python
UTF-8
1,791
4.03125
4
[]
no_license
#Mark Price #Learning Python #Fall 2011 """ This script prompts the user for an integer, and draws a grid the size (nxn) specified by the user """ def isEven (n): #Returns true if even false if odd if n%2 == 0 : return True else : return False def printLineAGrid (size): line = '+' if isEven(size) : modifier=(size/2)-2 line = line + '-'*modifier + '++' + '-'*modifier + '+' else : modifier=(size/2)-1 line = line + '-'*modifier + '+' + '-'*modifier + '+' return line def printLineBGrid (size): line = '+' if isEven(size) : modifier=(size/2)-2 line = line + ' '*modifier + '++' + ' '*modifier + '+' else : modifier=(size/2)-1 line = line + ' '*modifier + '+' + ' '*modifier + '+' return line def printGrid (size): #special case 1x1 and 2x2 grids if size == 1 : print '+' return if size == 2 : print "++\n++" return print printLineAGrid (size) #if even, draw use two lines/columns for "grid" if isEven(size) : for x in range((size/2)-2) : print printLineBGrid (size) print printLineAGrid (size) print printLineAGrid (size) for x in range((size/2)-2) : print printLineBGrid (size) #if odd, use "normal" looking grid else : for x in range((size/2)-1) : print printLineBGrid (size) print printLineAGrid (size) for x in range((size/2)-1) : print printLineBGrid (size) print printLineAGrid (size) gridSize = -1 while gridSize != 0 : while gridSize < 1 : print "Enter Grid Size, 0 to exit : \n" gridSize = int(raw_input()) printGrid (gridSize) gridSize = -1
Go
UTF-8
9,619
2.59375
3
[ "MIT" ]
permissive
package models import ( "errors" "regexp" "time" ) // Shipment wraps all the Fedex API fields needed for creating a shipment type Shipment struct { FromAndTo NotificationEmail string References []string Service string // MethodServiceLevel preserves the original shipping method service level, as Service is overwritten. MethodServiceLevel string Dimensions Dimensions InvoiceNumber string RMANumber string TotalWeight Weight // Only used for international ground shipments OriginatorName string Commodities Commodities LetterheadImageID string } var ( nonAlphanumericRegex *regexp.Regexp ) func init() { nonAlphanumericRegex = regexp.MustCompile("[^a-zA-Z0-9]+") } func (s *Shipment) ServiceType() string { return ServiceType(s.FromAndTo, s.Service) } func (s *Shipment) Broker() string { switch s.ServiceType() { case ServiceTypeInternationalEconomy: return "FedEx Express" default: return "FedEx Logistics" } } func (s *Shipment) ShipTime() time.Time { t := time.Now() if s.IsInternational() { t = t.Add(9 * 24 * time.Hour) } return t } func (s *Shipment) ShippingDocumentSpecification() *ShippingDocumentSpecification { if s.ServiceType() == ServiceTypeSmartPost || !s.IsInternational() { return nil } letterheadImageID := s.LetterheadImageID if s.LetterheadImageID == "" { letterheadImageID = "IMAGE_1" } return &ShippingDocumentSpecification{ ShippingDocumentTypes: []string{DocumentTypeCommercialInvoice}, CommercialInvoiceDetail: []CommercialInvoiceDetail{ { Format: Format{ ImageType: ImageTypePDF, StockType: StockTypePaperLetter, }, CustomerImageUsages: []CustomerImageUsage{ { Type: CustomerImageUsageTypeLetterHead, ID: letterheadImageID, }, { Type: CustomerImageUsageTypeSignature, ID: "IMAGE_2", }, }, }, }, } } func (s *Shipment) LabelSpecification() *LabelSpecification { if s.IsInternational() { stockType := StockTypePaper4x6 return &LabelSpecification{ LabelFormatType: LabelFormatTypeCommon2D, ImageType: ImageTypePDF, LabelStockType: &stockType, } } return &LabelSpecification{ LabelFormatType: LabelFormatTypeCommon2D, ImageType: ImageTypePNG, } } func (s *Shipment) DropoffType() string { if s.IsInternational() { return "BUSINESS_SERVICE_CENTER" } return "REGULAR_PICKUP" } func (s *Shipment) Weight() Weight { if !s.TotalWeight.IsZero() { return s.TotalWeight } commoditiesWeight := s.Commodities.Weight() if !commoditiesWeight.IsZero() && s.IsInternational() { // Add a little extra weight to the entire shipment weight, since adding floats // in golang sometimes results in a float that is a little less than the actual // sum, and then the FedEx API will return an error commoditiesWeight.Value += 0.5 return commoditiesWeight } switch s.ServiceType() { case ServiceTypeSmartPost: return Weight{Units: WeightUnitsLB, Value: 0.99} default: value := 2.0 if !commoditiesWeight.IsZero() { value = commoditiesWeight.Value } return Weight{Units: WeightUnitsLB, Value: value} } } func (s *Shipment) ValidatedDimensions() Dimensions { if s.Dimensions.IsValid() { return s.Dimensions } switch s.ServiceType() { case ServiceTypeSmartPost: return Dimensions{Length: 6, Width: 5, Height: 5, Units: DimensionsUnitsIn} default: return Dimensions{Length: 10, Width: 5, Height: 5, Units: DimensionsUnitsIn} } } func (s *Shipment) SpecialServicesRequested() *SpecialServicesRequested { var ( specialServiceTypes []string etdDetail *EtdDetail eventNotificationDetail *EventNotificationDetail returnShipmentDetail *ReturnShipmentDetail ) if s.ServiceType() == ServiceTypeSmartPost || s.MethodServiceLevel == "fedex_ground_return" { specialServiceTypes = append(specialServiceTypes, SpecialServiceTypeReturnShipment) returnShipmentDetail = &ReturnShipmentDetail{ ReturnType: ReturnTypePrintReturnLabel, } } if s.IsInternational() { specialServiceTypes = append(specialServiceTypes, SpecialServiceTypeElectronicTradeDocuments) etdDetail = &EtdDetail{ RequestedDocumentCopies: DocumentTypeCommercialInvoice, } } if s.NotificationEmail != "" { specialServiceTypes = append(specialServiceTypes, "EVENT_NOTIFICATION") eventNotificationDetail = defaultEventNotificationDetail(s.NotificationEmail) } if len(specialServiceTypes) == 0 { return nil } return &SpecialServicesRequested{ SpecialServiceTypes: specialServiceTypes, EtdDetail: etdDetail, EventNotificationDetail: eventNotificationDetail, ReturnShipmentDetail: returnShipmentDetail, } } func (s *Shipment) CustomerReferences() []CustomerReference { customerReferences := make([]CustomerReference, 0, 4) // HR-4683 Bug Fix // The references passed in through the ShipmentRequest to the shipping // service that eventually make it through to this function included // two values, the "retailerName", and "orderNumber". The duplicated // keys for the CustomerReferenceTypeCustomerReference type were causing // billing issues because there were two values (likely causing the WSDL // validation to fail), and this will now always access the first reference // passed in as the customer reference, and the second reference passed in as // the PO number. This is not elegant as it requires explicit indexed values, // but this is somewhat regulated by the ShippingServiceReferencesFromHRReturn // function in the shipping repo's conv package which will always provide the // two references when called when building the shipping service client requests. // // TODO: Tech Debt: This should be revisited at a later time to have a more // elegant solution as this is only a workaround for the present bug. for idx, reference := range s.References { switch idx { case 0: // first index would always be the retailer name customerReferences = append(customerReferences, CustomerReference{ CustomerReferenceType: CustomerReferenceTypeCustomerReference, Value: sanitizeReferenceForFedexAPI(reference), }) case 1: // second index would always be the order number customerReferences = append(customerReferences, CustomerReference{ CustomerReferenceType: CustomerReferenceTypePurchaseOrder, Value: sanitizeReferenceForFedexAPI(reference), }) } } if s.InvoiceNumber != "" { customerReferences = append(customerReferences, CustomerReference{ CustomerReferenceType: CustomerReferenceTypeInvoice, Value: s.InvoiceNumber, }) } if s.RMANumber != "" { customerReferences = append(customerReferences, CustomerReference{ CustomerReferenceType: CustomerReferenceTypeRMAAssociation, Value: sanitizeReferenceForFedexAPI(s.RMANumber), }) } return customerReferences } func sanitizeReferenceForFedexAPI(reference string) string { // Remove non-alphanumeric chars validatedReference := nonAlphanumericRegex.ReplaceAllString(reference, "") // Trim length if len(validatedReference) > 20 { validatedReference = validatedReference[0:20] } return validatedReference } func defaultEventNotificationDetail(notificationEmail string) *EventNotificationDetail { return &EventNotificationDetail{ AggregationType: AggregationTypePerShipment, EventNotifications: []EventNotification{{ Role: RoleShipper, Events: []string{ "ON_DELIVERY", "ON_ESTIMATED_DELIVERY", "ON_EXCEPTION", "ON_SHIPMENT", "ON_TENDER", }, NotificationDetail: NotificationDetail{ NotificationType: "EMAIL", EmailDetail: EmailDetail{ EmailAddress: notificationEmail, Name: "Happy Returns dev team", }, Localization: Localization{ LanguageCode: "en", }, }, FormatSpecification: FormatSpecification{ Type: "HTML", }, }}, } } func (s *Shipment) RequestedPackageLineItems() []RequestedPackageLineItem { return []RequestedPackageLineItem{{ SequenceNumber: 1, PhysicalPackaging: PackagingBag, ItemDescription: "ItemDescription", CustomerReferences: s.CustomerReferences(), Weight: s.Weight(), Dimensions: s.ValidatedDimensions(), }} } type ProcessShipmentBody struct { ProcessShipmentRequest ProcessShipmentRequest `xml:"q0:ProcessShipmentRequest"` } type ProcessShipmentRequest struct { Request RequestedShipment RequestedShipment `xml:"q0:RequestedShipment"` } type ShipResponseEnvelope struct { Reply ProcessShipmentReply `xml:"Body>ProcessShipmentReply"` } func (s *ShipResponseEnvelope) Error() error { return s.Reply.Error() } // ProcessShipReply : Process shipment reply root (`xml:"Body>ProcessShipmentReply"`) type ProcessShipmentReply struct { Reply TransactionDetail TransactionDetail CompletedShipmentDetail CompletedShipmentDetail Events []Event } func (p *ProcessShipmentReply) LabelDataAndImageType() ([]byte, string, error) { if label := p.CompletedShipmentDetail.CompletedPackageDetails.Label; len(label.Parts) > 0 { return []byte(label.Parts[0].Image), label.ImageType, nil } return nil, "", errors.New("no label") } func (p *ProcessShipmentReply) CommercialInvoiceDataAndImageType() ([]byte, string, error) { for _, document := range p.CompletedShipmentDetail.ShipmentDocuments { if document.Type == DocumentTypeCommercialInvoice && len(document.Parts) > 0 { return []byte(document.Parts[0].Image), document.ImageType, nil } } return nil, "", errors.New("no commercial invoice") }
PHP
UTF-8
5,244
2.625
3
[]
no_license
<?php namespace Drupal\iish_conference_lostpassword\Form; use Drupal\Core\Form\FormBase; use Drupal\Core\Form\FormStateInterface; use Drupal\iish_conference\EasyProtection; use Drupal\iish_conference_lostpassword\API\ConfirmLostPasswordApi; /** * The confirm lost password form. */ class ConfirmLostPasswordForm extends FormBase { /** * Returns a unique string identifying the form. * * @return string * The unique string identifying the form. */ public function getFormId() { return 'conference_confirm_lost_password'; } /** * Form constructor. * * @param array $form * An associative array containing the structure of the form. * @param \Drupal\Core\Form\FormStateInterface $form_state * The current state of the form. * * @return array * The form structure. */ public function buildForm(array $form, FormStateInterface $form_state) { $queryParameters = \Drupal::request()->query; $default_id = $queryParameters->get('id') ? EasyProtection::easyIntegerProtection($queryParameters->get('id')) : NULL; $default_code = $queryParameters->get('code') ? EasyProtection::easyStringProtection($queryParameters->get('code')) : NULL; $codeCheckOkay = FALSE; // Auto submit if (($default_id !== NULL) && ($default_id !== '') && ($default_code !== NULL) && ($default_code !== '')) { if (strtolower($_SERVER['REQUEST_METHOD']) === 'get') { $codeCheckOkay = $this->setMessage($default_id, $default_code); } } if (!$codeCheckOkay) { $form['info'] = array( '#markup' => '<div class="bottommargin">' . iish_t('Please enter the ID and CODE we have sent you via e-mail and click on Confirm.') . '<br />' . iish_t('After the CODE is confirmed we will send you a new password.') . '</div>', ); $form['id'] = array( '#type' => 'textfield', '#title' => iish_t('ID'), '#size' => 30, '#maxlength' => 50, '#required' => TRUE, '#prefix' => '<div class="container-inline bottommargin">', '#suffix' => '</div>', '#default_value' => $default_id, ); $form['code'] = array( '#type' => 'textfield', '#title' => iish_t('CODE'), '#size' => 30, '#maxlength' => 50, '#required' => TRUE, '#prefix' => '<div class="container-inline bottommargin">', '#suffix' => '</div>', '#default_value' => $default_code, ); $form['submit'] = array( '#type' => 'submit', '#value' => 'Confirm' ); } return $form; } /** * Form validation handler. * * @param array $form * An associative array containing the structure of the form. * @param \Drupal\Core\Form\FormStateInterface $form_state * The current state of the form. */ public function validateForm(array &$form, FormStateInterface $form_state) { // RegExp only integers if (EasyProtection::easyIntegerProtection($form_state->getValue('id')) === NULL) { $form_state->setErrorByName('id', iish_t('The ID appears to be invalid.')); } // RegExp only digits and characters if (EasyProtection::easyStringProtection($form_state->getValue('code')) === '') { $form_state->setErrorByName('code', iish_t('The CODE appears to be invalid.')); } } /** * Form submission handler. * * @param array $form * An associative array containing the structure of the form. * @param \Drupal\Core\Form\FormStateInterface $form_state * The current state of the form. */ public function submitForm(array &$form, FormStateInterface $form_state) { $form_state->setRebuild(); $id = EasyProtection::easyIntegerProtection($form_state->getValue('id')); $code = EasyProtection::easyStringProtection($form_state->getValue('code')); $this->setMessage($id, $code); } /** * Sets the message for lost password code checking. * * @param int $id The id of the user. * @param string $code The code to check for this id. * * @return bool Whether to return. */ private function setMessage($id, $code) { $confirmLostPasswordApi = new ConfirmLostPasswordApi(); $status = $confirmLostPasswordApi->confirmLostPassword($id, $code); switch ($status) { case ConfirmLostPasswordApi::ACCEPT: drupal_set_message(iish_t('We have sent you an e-mail with your new password.'), 'status'); return TRUE; case ConfirmLostPasswordApi::PASSWORD_ALREADY_SENT: drupal_set_message(iish_t('We already sent you an email with your new password. Please check your email!'), 'warning'); return TRUE; case ConfirmLostPasswordApi::CODE_EXPIRED: drupal_set_message(iish_t('The CODE has been expired. Please request a new CODE.'), 'error'); break; case ConfirmLostPasswordApi::ERROR: drupal_set_message(iish_t('We failed to send you an email with your new password. ' . 'Please try again later. We are sorry for the inconvenience.'), 'error'); break; default: drupal_set_message(iish_t('ID / CODE combination not found.'), 'error'); } return FALSE; } }
C
UTF-8
1,317
3.71875
4
[]
no_license
//FIFO #include<stdio.h> #include<stdlib.h> struct node { int data; struct node* next; }; struct node* head = NULL; struct node* currNode = NULL; struct node* old = NULL; void enqueue(int num){ struct node* newNode = (struct node*)malloc(sizeof(struct node)); if(head == NULL){ newNode->data = num; newNode->next = NULL; head = newNode; currNode=newNode; } else{ currNode->next =newNode; newNode->data = num; newNode->next=NULL; old =currNode; currNode=newNode; } } void dequeue(){ if(head==NULL){ printf("Cannot do dequeue"); }else{ printf("DEqueued %d", head->data); head=head->next; } } void printLinkList() { struct node* printNode = head; while(printNode != NULL) { printf(" %d",printNode->data); printNode = printNode->next; } } int main(){ enqueue(5); enqueue(10); enqueue(15); printLinkList(); printf("\n"); dequeue(); printf("\n"); printLinkList(); printf("\n"); dequeue(); printf("\n"); printLinkList(); printf("\n"); enqueue(15); printLinkList(); printf("\n"); printf("\n"); dequeue();dequeue();dequeue();dequeue(); return 0; }
PHP
UTF-8
10,905
2.578125
3
[ "MIT" ]
permissive
<?php namespace Conv\Factory; use Conv\Structure\Attribute; use Conv\Structure\ColumnStructure; use Conv\Structure\IndexStructure; use Conv\Structure\PartitionLongStructure; use Conv\Structure\PartitionPartStructure; use Conv\Structure\PartitionShortStructure; use Conv\Structure\TableStructure; use Conv\Util\Config; use Conv\Util\Evaluator; use Conv\Util\PartitionType; use Conv\Util\SchemaKey; use Conv\Util\SchemaValidator; use Symfony\Component\Yaml\Yaml; class TableStructureFactory { /** * @param string $tableName * @param array $spec * @return TableStructure */ public static function fromSpec(string $tableName, array $spec): TableStructure { $columnStructureList = []; foreach ($spec[SchemaKey::TABLE_COLUMN] as $field => $column) { $properties = array_diff_key($column, array_flip(SchemaKey::COLUMN_KEYS)); $columnStructureList[] = new ColumnStructure( $field, $column[SchemaKey::COLUMN_TYPE], array_key_exists(SchemaKey::COLUMN_DEFAULT, $column) ? $column[SchemaKey::COLUMN_DEFAULT] : null, $column[SchemaKey::COLUMN_COMMENT], array_key_exists(SchemaKey::COLUMN_ATTRIBUTE, $column) ? $column[SchemaKey::COLUMN_ATTRIBUTE] : [], null, null, $properties ); } $indexStructureList = []; if (true === array_key_exists(SchemaKey::TABLE_PRIMARY_KEY, $spec)) { $indexStructureList[] = new IndexStructure( 'PRIMARY', true, 'BTREE', $spec[SchemaKey::TABLE_PRIMARY_KEY] ); } if (true === array_key_exists(SchemaKey::TABLE_INDEX, $spec)) { foreach ($spec[SchemaKey::TABLE_INDEX] as $keyName => $value) { $indexStructureList[] = new IndexStructure( $keyName, $value[SchemaKey::INDEX_TYPE], 'BTREE', $value[SchemaKey::INDEX_COLUMN] ); } } if (array_key_exists(SchemaKey::TABLE_ENGINE, $spec)) { $engine = $spec[SchemaKey::TABLE_ENGINE]; } else { $engine = Config::default('engine'); } if (array_key_exists(SchemaKey::TABLE_DEFAULT_CHARSET, $spec)) { $defaultCharset = $spec[SchemaKey::TABLE_DEFAULT_CHARSET]; } else { $defaultCharset = Config::default('charset'); } if (array_key_exists(SchemaKey::TABLE_COLLATE, $spec)) { $collate = $spec[SchemaKey::TABLE_COLLATE]; } else { $collate = Config::default('collate'); } $partition = null; if (array_key_exists(SchemaKey::TABLE_PARTITION, $spec)) { $partitionSpec = $spec[SchemaKey::TABLE_PARTITION]; $by = $partitionSpec['by']; $method = array_flip(PartitionType::METHOD)[$by]; $type = PartitionType::METHOD_TYPE[$method]; $value = $partitionSpec['value']; switch ($type) { case PartitionType::SHORT: $partition = new PartitionShortStructure( $method, $value, $partitionSpec['num'] ); break; case PartitionType::LONG: $parts = []; $i = 1; foreach ($partitionSpec['list'] as $name => $array) { $operator = PartitionType::METHOD_OPERATOR[$method]; $parts[$i] = new PartitionPartStructure( $name, $operator, $array[strtolower($operator)], isset($array['comment']) ? $array['comment'] : '' ); $i++; } $partition = new PartitionLongStructure( $method, $value, $parts ); break; } } $properties = array_diff_key($spec, array_flip(SchemaKey::TABLE_KEYS)); $tableStructure = new TableStructure( $tableName, $spec[SchemaKey::TABLE_COMMENT], $engine, $defaultCharset, $collate, $columnStructureList, $indexStructureList, $partition, $properties ); return $tableStructure; } /** * @param \PDO $pdo * @param string $dbName * @param string $tableName * @return TableStructure */ public static function fromTable(\PDO $pdo, string $dbName, string $tableName): TableStructure { $pdo->exec('USE ' . $dbName); $rawStatus = $pdo->query("SHOW TABLE STATUS LIKE '$tableName'")->fetch(); $rawColumnList = $pdo->query( sprintf( "SELECT * FROM information_schema.COLUMNS WHERE table_schema = '%s' AND table_name = '%s' ORDER BY ORDINAL_POSITION ASC", $dbName, $tableName ) )->fetchAll(); $rawPartitionList = $pdo->query( sprintf( "SELECT * FROM information_schema.PARTITIONS WHERE table_schema = '%s' AND table_name = '%s' ORDER BY PARTITION_ORDINAL_POSITION ASC", $dbName, $tableName ) )->fetchAll(); $partitionGroups = []; if (count($rawPartitionList) !== 1 and !is_null(reset($rawPartitionList)['PARTITION_METHOD'])) { $methods = array_fill_keys(array_column($rawPartitionList, 'PARTITION_METHOD'), []); foreach ($rawPartitionList as $item) { $methods[$item['PARTITION_METHOD']][] = $item; } foreach ($methods as $method => $methodValue) { $expressions = array_fill_keys(array_column($methodValue, 'PARTITION_EXPRESSION'), []); foreach ($methodValue as $value) { $expressions[$value['PARTITION_EXPRESSION']][$value['PARTITION_ORDINAL_POSITION']] = [ 'PARTITION_NAME' => $value['PARTITION_NAME'], 'PARTITION_DESCRIPTION' => $value['PARTITION_DESCRIPTION'], 'PARTITION_COMMENT' => $value['PARTITION_COMMENT'], ]; } $partitionGroups[$method] = $expressions; } } $partition = null; foreach ($partitionGroups as $method => $group) { $type = PartitionType::METHOD_TYPE[$method]; switch ($type) { case PartitionType::SHORT: foreach ($group as $value => $raw) { $partition = new PartitionShortStructure( $method, $value, count($raw) ); } break; case PartitionType::LONG: foreach ($group as $value => $raw) { $parts = []; foreach ($raw as $order => $array) { $parts[$order] = new PartitionPartStructure( $array['PARTITION_NAME'], PartitionType::METHOD_OPERATOR[$method], $array['PARTITION_DESCRIPTION'], $array['PARTITION_COMMENT'] ); } $partition = new PartitionLongStructure( $method, $value, $parts ); } break; } } $columnStructureList = []; foreach ($rawColumnList as $column) { $attribute = []; if ((bool) preg_match('/auto_increment/', $column['EXTRA'])) { $attribute[] = Attribute::AUTO_INCREMENT; } if ('YES' === $column['IS_NULLABLE']) { $attribute[] = Attribute::NULLABLE; } if ((bool) preg_match('/unsigned/', $column['COLUMN_TYPE'])) { $attribute[] = Attribute::UNSIGNED; } if ((bool) preg_match('/STORED/', $column['EXTRA'])) { $attribute[] = Attribute::STORED; } $collationName = $column['COLLATION_NAME']; $generationExpression = empty($column['GENERATION_EXPRESSION']) ? null : $column['GENERATION_EXPRESSION']; $columnStructureList[] = new ColumnStructure( $column['COLUMN_NAME'], str_replace(' unsigned', '', $column['COLUMN_TYPE']), $column['COLUMN_DEFAULT'], $column['COLUMN_COMMENT'], $attribute, $collationName, $generationExpression, [] ); } $rawIndexList = $pdo->query("SHOW INDEX FROM $tableName")->fetchAll(); $keyList = []; foreach ($rawIndexList as $index) { $columnName = $index['Column_name']; if (!is_null($index['Sub_part'])) { $subPart = $index['Sub_part']; $columnName = "$columnName($subPart)"; } $keyList[$index['Key_name']][] = [ 'Non_unique' => $index['Non_unique'], 'Column_name' => $columnName, 'Index_type' => $index['Index_type'] ]; } $indexStructureList = []; foreach ($keyList as $keyName => $indexList) { $indexStructureList[] = new IndexStructure( $keyName, '0' == $indexList[0]['Non_unique'], $indexList[0]['Index_type'], array_column($indexList, 'Column_name') ); } $createQuery = $pdo->query("SHOW CREATE TABLE $tableName")->fetch()[1]; $defaultCharsetSearch = mb_strstr($createQuery, 'DEFAULT CHARSET='); if (false !== $defaultCharsetSearch) { $defaultCharsetSearch = str_replace('DEFAULT CHARSET=', '', $defaultCharsetSearch); $defaultCharset = explode(' ', $defaultCharsetSearch)[0]; } else { $defaultCharset = null; } $tableStructure = new TableStructure( $tableName, $rawStatus['Comment'], $rawStatus['Engine'], $defaultCharset, $rawStatus['Collation'], $columnStructureList, $indexStructureList, $partition, [] ); return $tableStructure; } }
C++
UTF-8
1,042
2.625
3
[]
no_license
//#include <stdio.h> //#include <string.h> //#include <algorithm> // //using namespace std; //int Tree[1000]; //struct Edge{ // int a; // int b; // int lowCost; // int status; // bool operator < (const Edge &e) const{ // return lowCost < e.lowCost; // } // //}edge[1000]; // //int findRoot(int x) { // if(Tree[x] == -1) return x; // else // return findRoot(Tree[x]); //} // // //int main() { // int n,ans; // while(scanf("%d",&n) != EOF) { // ans = 0; // if(n == 0) break; // for(int i=1;i<=n;++i) { // Tree[i]=-1; // } // for(int i=0;i<n*(n-1)/2; ++i) { // scanf("%d%d%d%d",&edge[i].a,&edge[i].b,&edge[i].lowCost,&edge[i].status); // if(edge[i].status == 1) { // edge[i].lowCost =0; // } // } // sort(edge,edge+n*(n-1)/2); // for(int i=0;i<n*(n-1)/2;++i) { // int aa = findRoot(edge[i].a); // int bb = findRoot(edge[i].b); // if( aa != bb) { // Tree[aa] = bb; // ans += edge[i].lowCost; // } // // } // // printf("%d\n",ans); // } // return 0; // //}
Java
UTF-8
1,075
2.140625
2
[]
no_license
package br.com.vehicle.delivery.configuration; import org.springframework.context.annotation.Configuration; import org.springframework.format.FormatterRegistry; import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar; import org.springframework.http.MediaType; import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * Configuração da camada Web (Endpoints da Aplicação) * * @author Caio * @since 09/07/2018 * @version 1.0 */ @Configuration public class WebConfiguration implements WebMvcConfigurer{ @Override public void addFormatters(FormatterRegistry registry) { DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar(); registrar.setUseIsoFormat(true); registrar.registerFormatters(registry); } @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer.defaultContentType(MediaType.APPLICATION_JSON); } }
JavaScript
UTF-8
380
2.890625
3
[ "MIT" ]
permissive
"use strict"; const swapi = function(num){ let url = "https://swapi.dev/api/people/"; fetch(url+num+"/").then(data => data.json()) .then(obj => { console.log(obj); return fetch(obj.homeworld) }) .then(hwdata => hwdata.json()) .then(hwObject => console.log(hwObject)); }; swapi(1); console.log("Check other commands!");
C++
UTF-8
1,819
2.890625
3
[]
no_license
// Runtime: 4 ms, faster than 96.56% of C++ // Memory Usage: 8.9 MB, less than 100.00% of C++ class Solution { public: string mostCommonWord(string paragraph, vector<string>& banned) { vector<string> v; vector<int> freq; string s = ""; int i, j, max = 0; bool isBanned = false, isSave = false; for(i=0;i<paragraph.size();i++){ if(paragraph[i] >= 'A' && paragraph[i] <= 'Z') s.push_back(paragraph[i]-'A'+'a'); else if(paragraph[i] >= 'a' && paragraph[i] <= 'z') s.push_back(paragraph[i]); else if(s.size() != 0){ // check if banned for(j=0;j<banned.size();j++){ if(s == banned[j]) isBanned = true; } if(!isBanned){ for(j=0;j<v.size();j++){ if(s == v[j]){ isSave = true; freq[j] ++; if(freq[j] > max) max = freq[j]; } } if(!isSave){ v.push_back(s); freq.push_back(1); } } s = ""; isBanned = false; isSave = false; } } for(j=0;j<banned.size();j++){ if(s == banned[j]) isBanned = true; } if(!isBanned){ for(j=0;j<v.size();j++){ if(s == v[j]){ isSave = true; freq[j] ++; if(freq[j] > max) max = freq[j]; } } if(!isSave){ v.push_back(s); freq.push_back(1); if(1 > max) max = 1; } } for(i=0;i<freq.size();i++){ if(freq[i] == max){ return v[i]; } } return ""; } };
Python
UTF-8
547
3.15625
3
[]
no_license
import notas.nota as modelo class Acciones: def crear(self, usuario): print(f'\nOk {usuario[1]}!! vamos a crear una nota... ') titulo = input("Ingresa el titulo de la nota: ") descripcion = input("Ingresa la nota: ") nota = modelo.Nota(usuario[0], titulo, descripcion) guardar = nota.guardar() if guardar[0] >= 1: print(f'Perfecto la nota {nota.titulo} se ah guardado') else: print(f'La nota no se ah guardado, lo siento {usuario[1]}') return guardar
JavaScript
UTF-8
2,446
3.15625
3
[]
no_license
'use strict' var gKeyWords = createArrOfKeys(); var gKeysCount = { happy: 4, asking: 46, sad: 15, amazed: 9, pink: 1, wonder: 18, complete: 3, mad: 19, smart: 30, man: 12, cat: 10, child: 2, victory: 15, suprised: 30, unsatisfied: 3, grass: 34, grumpy: 7, laugh: 20, sarcastic: 7 }; function filterByKeyWord(key) { var imgsWithKey = gImgs.filter(function (img) { return (img.keyWords.includes(key)); }); return imgsWithKey; } function createArrOfKeys() { var keyWords = []; gImgs.forEach(function (img) { keyWords = keyWords.concat(img.keyWords); }); keyWords = keyWords.filter(function (key, index) { return keyWords.indexOf(key) === index; }); return keyWords; } function countKeysSearch(key) { if (gKeysCount[key]) gKeysCount[key]++; else gKeysCount[key] = 1; } function calculatePercents(key) { return (gKeysCount[key] / calculateSumSearched()) * 100; } function calculateSumSearched() { var sum = 0; for (var key in gKeysCount) { if (gKeysCount.hasOwnProperty(key)) { sum += parseFloat(gKeysCount[key]); } } return sum; } function createFontSize(percents) { var className = 'least-popular'; if (percents > 30) className = 'most-popular'; else if (percents > 20) className = 'very-popular'; else if (percents > 15) className = 'regular'; else if (percents > 10) className = 'popular'; else if (percents > 5) className = 'not-very-popular'; return className; } function search() { var elGallery = document.querySelector('.gallery'); var inputSearch = document.getElementById("search"); var key = inputSearch.value; countKeysSearch(key); saveToStorage('keyCount', gKeysCount) renderKeys(); var filteredImgs = filterByKeyWord(key); if (filteredImgs.length === 0) { elGallery.innerHTML = "Soory, not matching results" } else { renderGallery(filteredImgs); } inputSearch.value = ""; } function renderKeys() { var keysDiv = document.querySelector('.search-tags'); keysDiv.innerHTML = ''; var strHtml = ''; for (var key in gKeysCount) { var className = createFontSize(calculatePercents(key)); strHtml += `<span class="${className}" onclick="renderGallery(filterByKeyWord('${key}'))"> ${key} </span>\n`; } keysDiv.innerHTML = strHtml; }
Python
UTF-8
16,379
2.515625
3
[]
no_license
__author__ = "Shourya S. Roy Burman" __email__ = "ssrburman@gmail.com" import os import argparse import numpy as np import pandas as pd import time from pymol import cmd, util """ The first two functions were borrowed from the PyMOL wiki: https://pymolwiki.org/index.php/FindSurfaceResidues """ def findSurfaceAtoms(selection="all", cutoff=2.5, quiet=1): """ DESCRIPTION Finds those atoms on the surface of a protein that have at least 'cutoff' exposed A**2 surface area. USAGE findSurfaceAtoms [ selection, [ cutoff ]] SEE ALSO findSurfaceResidues """ cutoff, quiet = float(cutoff), int(quiet) tmpObj = cmd.get_unused_name("_tmp") cmd.create(tmpObj, "(" + selection + ") and polymer", zoom=0) cmd.set("dot_solvent", 1, tmpObj) cmd.get_area(selection=tmpObj, load_b=1) # threshold on what one considers an "exposed" atom (in A**2): cmd.remove(tmpObj + " and b < " + str(cutoff)) selName = cmd.get_unused_name("exposed_atm_") cmd.select(selName, "(" + selection + ") in " + tmpObj) cmd.delete(tmpObj) if not quiet: print("Exposed atoms are selected in: " + selName) return selName def findSurfaceResidues(selection="all", cutoff=2.5, doShow=0, quiet=1): """ DESCRIPTION Finds those residues on the surface of a protein that have at least 'cutoff' exposed A**2 surface area. USAGE findSurfaceResidues [ selection, [ cutoff, [ doShow ]]] ARGUMENTS selection = string: object or selection in which to find exposed residues {default: all} cutoff = float: cutoff of what is exposed or not {default: 2.5 Ang**2} RETURNS (list: (chain, resv ) ) A Python list of residue numbers corresponding to those residues w/more exposure than the cutoff. """ cutoff, doShow, quiet = float(cutoff), int(doShow), int(quiet) selName = findSurfaceAtoms(selection, cutoff, quiet) exposed = set() cmd.iterate(selName, "exposed.add((chain,resv))", space=locals()) selNameRes = cmd.get_unused_name("exposed_res_") cmd.select(selNameRes, "byres " + selName) if not quiet: print("Exposed residues are selected in: " + selNameRes) if doShow: cmd.show_as("spheres", "(" + selection + ") and polymer") cmd.color("white", selection) cmd.color("yellow", selNameRes) cmd.color("red", selName) return sorted(exposed) def get_all_surface_lysines(model): # Running this script gives the findSurfaceResidues command exposed_res = [n[1] for n in findSurfaceResidues("{} and chain B".format(model), cutoff=17)] resi_num = {"resis": []} cmd.iterate("{} and chain B and resn LYS and name CA".format(model), "resis.append(resi)", space=resi_num) lysine_res = [int(ii) for ii in resi_num["resis"]] exposed_lys = set(lysine_res).intersection(exposed_res) return sorted(exposed_lys) def align_ref(model, rad): """ Return distance between CRBN-LVY N3 and aligned reference 2PU C26 :param model: Name of pymol selection :param rad: Radius within which free path has to be calculated :return: True if alignment works, False otherwise """ cmd.super("ref and resi 1-149", "{} and chain B".format(model)) dist = cmd.distance("{} and chain A and resn LVY and name N4".format(model), "ref and resn GUI and name N01") num_bb = has_free_path(model, rad) return dist, num_bb def is_in_cylinder(a, b, rad, p): """ Returns True if point p is in cylinder of radius rad joining points a and b Math from https://bit.ly/3oRNAdN :param a: numpy array coordinates of a :param b: numpy array coordinates of b :param rad: radius of cylinder :param p: numpy array coordinates of p :return: Boolean """ e = b - a m = np.cross(a, b) d = np.linalg.norm(m + np.cross(e, p)) / np.linalg.norm(e) # distance of p from line joining a and b if d >= rad: return False else: q = p + (np.cross(e, m + np.cross(e, p))) / (np.linalg.norm(e)) ** 2 # q is closest point to p on line # calculating barycentric coordinates of q wa = np.linalg.norm(np.cross(q, b)) / np.linalg.norm(m) wb = np.linalg.norm(np.cross(q, a)) / np.linalg.norm(m) # is q between a and b? if 0 <= wa <= 1 and 0 <= wb <= 1: return True else: return False def has_free_path(model, rad): """ Determine if there is a free path between the two points. Only protein backbone atoms and cmpd non-neighbours are considered :param model: Name of pymol selection :param rad: Radius if the cylinder within which to calculate clashes :return: Number of clashing atoms in cylinder """ a = cmd.get_coords("{} and chain A and resn LVY and name N4".format(model), 1)[0] b = cmd.get_coords("ref and resn GUI and name N01", 1)[0] bb_coords = cmd.get_coords("{} and name CA+C+N".format(model), 1) lvy_coords = cmd.get_coords("{} and resn LVY and !(name N4+C4+C3+C5)".format(model)) # LVY except neighboring atoms gui_coords = cmd.get_coords("ref and resn GUI and !(name N01+C18+C20)") # GUI except neighboring atoms num_bb = 0 for bb in np.concatenate([bb_coords, lvy_coords, gui_coords]): if is_in_cylinder(a, b, rad, bb): num_bb += 1 return num_bb def get_plane_coeffs(model): """ Calculate vertical plane passing through 1/2 dist between COM_target and CRBN, and hortizontal plane passing through COM_target :param model: Name of pymol selection :return: A pair of 4-tupples for the coefficients for each plane """ # Vertical: Getting coordinates for C-alpha of CRBN R130, Y151, and I333 ver_a = np.array(cmd.get_coords(selection="{} and chain A and resi 130 and name CA".format(model))[0]) ver_b = np.array(cmd.get_coords(selection="{} and chain A and resi 151 and name CA".format(model))[0]) ver_c = np.array(cmd.get_coords(selection="{} and chain A and resi 333 and name CA".format(model))[0]) # Pass planes through centre of mass of kinase com_kinase = np.array(cmd.centerofmass("{} and chain B".format(model))) # These two vectors are in the plane v1 = ver_c - ver_a v2 = ver_b - ver_a # the cross product is a vector normal to the plane ver_cp = np.cross(v1, v2) a, b, c = ver_cp # This evaluates a * x_c + b * y_c + c * z_c which equals d # d_on_plane = np.dot(ver_cp, ver_c) # Taking projection of COM on vertical plane passing through CRBN t = (np.dot(ver_cp, ver_c) - np.dot(ver_cp, com_kinase)) / np.linalg.norm(ver_cp) ** 2 com_proj = np.array([com_kinase[0] + t * a, com_kinase[1] + t * b, com_kinase[2] + t * c]) com_half_dist = np.mean(np.array([com_kinase, com_proj]), axis=0) d = np.dot(ver_cp, com_half_dist) # Taking plane through half distance between CRBN and COM ver_plane_coeffs = np.array([a, b, c, -d]) # print("The vertical plane is {}x + {}y + {}z + {} = 0".format(*ver_plane_coeffs)) # Horizontal: Getting coordinates for C-alpha of CRBN D64, 208, 409 hor_a = np.array(cmd.get_coords(selection="{} and chain A and resi 64 and name CA".format(model))[0]) hor_b = np.array(cmd.get_coords(selection="{} and chain A and resi 208 and name CA".format(model))[0]) hor_c = np.array(cmd.get_coords(selection="{} and chain A and resi 409 and name CA".format(model))[0]) # These two vectors are in the plane v3 = hor_c - hor_a v4 = hor_b - hor_a # the cross product is a vector normal to the plane hor_cp = np.cross(v3, v4) p, q, r = hor_cp # This evaluates p * x_c + q * y_c + r * z_c which equals s s = np.dot(hor_cp, com_kinase) hor_plane_coeffs = np.array([p, q, r, -s]) # print("The horizontal plane is {}x + {}y + {}z + {} = 0".format(*hor_plane_coeffs)) return ver_plane_coeffs, hor_plane_coeffs def is_e2_accessible(p1, ver_plane_coeffs, hor_plane_coeffs, lvy_n4): """ Is a point e2 acccessible? :param p1: 3-D coordinats of point for which the calculations are being made :param ver_plane_coeffs: Coefficients of vertical plane :param hor_plane_coeffs:Coefficients of horizontal plane :param lvy_n4: 3-D coordinates of N4 atom of LVY :return: Boolean """ if round(np.dot(ver_plane_coeffs, np.append(p1, 1))) <= 0 <= round(np.dot(hor_plane_coeffs, np.append(p1, 1))) and \ np.linalg.norm(lvy_n4 - p1) <= 60: # Rounding to take care of numerical errors return True else: return False def lys_ca_cb_orientation(p0, p1, ver_plane_coeffs, hor_plane_coeffs): """ Is the lysine Ca->Cb vector pointing in the completely wrong direction? :param p0: 3-D coordinates of C-alpha :param p1: 3-D coordinates of C-beta :param ver_plane_coeffs: Coefficients of vertical plane :param hor_plane_coeffs: Coefficients of horizontal plane :return: """ ver_orient = np.dot(ver_plane_coeffs[:3], p1 - p0) hor_orient = np.dot(hor_plane_coeffs[:3], p1 - p0) if hor_orient < 0 < ver_orient: # Both orientations are wrong return False else: return True def get_ub_sites(src_dir, dst): """ Writes file with fraction of E2 accessibility of every exposed lysine. Also, writes .pse files highlighting which Ub sites are considered accessible, what which ones are not. :param src_dir: Directory where all files are kept :param dst: Directory where """ ub_sites = {} pdb_with_offsets = set() with open(os.path.join(src_dir, "e2_accessible_surface_lysines.csv"), "w") as f: f.write("Uniprot_AC,Lys_res,E2_accessibility,E2_accessible_orientation\n") for pdb in sorted(os.listdir(src_dir)): if not pdb.startswith("."): start = time.time() ac = pdb.split("_")[0] if not os.path.exists(os.path.join(src_dir, pdb, dst)): os.mkdir(os.path.join(src_dir, pdb, dst)) # Get a list of surface lysines cmd.load(os.path.join(src_dir, pdb, "{}.pdb".format(pdb)), pdb) ub_sites[ac] = get_all_surface_lysines(pdb) cmd.delete(pdb) # Count accessible site e2_accessible_site_count = dict.fromkeys(ub_sites[ac], None) # blank dictionary with Ub sites e2_accessible_site_orient_count = dict.fromkeys(ub_sites[ac], None) # blank dictionary with Ub sites model_count = 0 # PROTAC feasible model count for model in os.listdir(os.path.join(src_dir, pdb, "top_models")): cmd.load(os.path.join(src_dir, pdb, "top_models", model), model[:-7]) util.cbc(model[:-7]) # Is there a free path from LVY? Max dist: 14 Ang, max number of atoms in cylinder:2, radius: 1 Ang dist, num_bb = align_ref(model[:-7], 1) if dist <= 14 and num_bb <= 2: # PROTAC feasible model_count += 1 ver_plane_coeffs, hor_plane_coeffs = get_plane_coeffs(model[:-7]) lvy_n4 = np.array(cmd.get_coords( selection="{} and chain A and resn LVY and name N4".format(model[:-7]))[0]) # Check that they are indeed lysine for site in ub_sites[ac]: resi_names = {"resi_name": []} cmd.iterate("{} and chain B and resi {} and name CA".format(model[:-7], site), "resi_name.append(resn)", space=resi_names) if len(resi_names["resi_name"]) > 0: # residue might not exist in structure if resi_names["resi_name"][0] != "LYS": print("In {}, at {}, residue in {}.".format(pdb, site, resi_names["resi_name"][0])) pdb_with_offsets.add(pdb) else: # If they are lysine p0 = np.array( cmd.get_coords(selection="{} and chain B and resi {} and name CA".format( model[:-7], site))[0]) p1 = np.array( cmd.get_coords(selection="{} and chain B and resi {} and name CB".format( model[:-7], site))[0]) # Color ub sites by E2 accessibility if is_e2_accessible(p1, ver_plane_coeffs, hor_plane_coeffs, lvy_n4): cmd.show("sticks", "{} and chain B and resi {}".format(model[:-7], site)) cmd.color("blue", "{} and chain B and resi {}".format(model[:-7], site)) if e2_accessible_site_count[site] is None: e2_accessible_site_count[site] = 1 else: e2_accessible_site_count[site] += 1 if lys_ca_cb_orientation(p0, p1, ver_plane_coeffs, hor_plane_coeffs): if e2_accessible_site_orient_count[site] is None: e2_accessible_site_orient_count[site] = 1 else: e2_accessible_site_orient_count[site] += 1 else: cmd.show("sticks", "{} and chain B and resi {}".format(model[:-7], site)) cmd.color("firebrick", "{} and chain B and resi {}".format(model[:-7], site)) if e2_accessible_site_count[site] is None: e2_accessible_site_count[site] = 0 e2_accessible_site_orient_count[site] = 0 util.cnc(model[:-7]) cmd.save(os.path.join(src_dir, pdb, dst, "{}_e2_accessible_exposed_lys.pse".format(model[:-7])), "{} + ref".format(model[:-7])) cmd.delete(model[:-7]) end = time.time() print("It took {} seconds to finish {}.".format(end - start, pdb)) for site, count in e2_accessible_site_count.items(): if count is not None and model_count > 0: if e2_accessible_site_orient_count[site] is not None: f.write("{},{},{},{}\n".format(pdb.split("_")[0], site, (count / model_count), (e2_accessible_site_orient_count[site] / model_count))) else: f.write("{},{},{},{}\n".format(pdb.split("_")[0], site, (count / model_count), e2_accessible_site_orient_count[site])) else: f.write("{},{},{},{}\n".format(pdb.split("_")[0], site, count, e2_accessible_site_orient_count[site])) f.flush() def main(): # Parsing all arguments parser = argparse.ArgumentParser() parser.add_argument("-s", "--src_dir", help="Super directory with clustered decoys", default="../07_local_docking_all_kinases/01_CRBN_Len") parser.add_argument("-d", "--dst", help="Where the pymol sessions will be stored", default="e2_accessible_lysines") parser.add_argument("-r", "--ref_struct", help="Name of reference kinase to align", default="../07_local_docking_all_kinases/aux_files/CDK2_TAE.pdb") args = parser.parse_args() src_dir = args.src_dir dst = args.dst # Loading fixed reference cmd.load(os.path.join(args.ref_struct), "ref") cmd.color("gray90", "ref") cmd.set("cartoon_transparency", 0.4, "ref") util.cnc("ref") get_ub_sites(src_dir, dst) main()
Java
UTF-8
30,437
2.5625
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 havabol.util; import havabol.builtins.types.*; import havabol.common.type.*; import havabol.classify.*; import havabol.eval.*; import static havabol.eval.Evaluator.reportEvalError; import static havabol.util.Numerics.*; import static havabol.util.Text.*; /** * * @author fish */ public class Operators { public static TypeInterface add(TypeInterface first, TypeInterface second) { switch (first.getFormalType()) { case FLOAT: PFloat floatB, floatRes; switch (second.getFormalType()) { case INTEGER: floatB = floatPrim((PInteger) second); break; case FLOAT: floatB = (PFloat) second; break; case STRING: floatB = floatPrim((PString) second); break; default: // XXX - EXPLODE! return null; } floatRes = floatPrim(((PFloat) first).getValue() + floatB.getValue()); return floatRes; case INTEGER: PInteger intB, intRes; switch (second.getFormalType()) { case INTEGER: intB = (PInteger) second; break; case FLOAT: intB = intPrim((PFloat) second); break; case STRING: intB = intPrim((PString) second); break; default: // XXX - EXPLODE! return null; } intRes = intPrim(((PInteger) first).getValue() + intB.getValue()); return intRes; default: // XXX - We need a narrow exception class for this. return null; } } public static TypeInterface sub(TypeInterface first, TypeInterface second) { switch (first.getFormalType()) { case FLOAT: PFloat floatB, floatRes; switch (second.getFormalType()) { case INTEGER: floatB = floatPrim((PInteger) second); break; case FLOAT: floatB = (PFloat) second; break; case STRING: floatB = floatPrim((PString) second); break; default: // XXX - EXPLODE! return null; } floatRes = floatPrim(((PFloat) first).getValue() - floatB.getValue()); return floatRes; case INTEGER: PInteger intB, intRes; switch (second.getFormalType()) { case INTEGER: intB = (PInteger) second; break; case FLOAT: intB = intPrim((PFloat) second); break; case STRING: intB = intPrim((PString) second); break; default: // XXX - EXPLODE! return null; } intRes = intPrim(((PInteger) first).getValue() - intB.getValue()); return intRes; default: // XXX - We need a narrow exception class for this. return null; } } public static TypeInterface mult(TypeInterface first, TypeInterface second) { switch (first.getFormalType()) { case FLOAT: PFloat floatB, floatRes; switch (second.getFormalType()) { case INTEGER: floatB = floatPrim((PInteger) second); break; case FLOAT: floatB = (PFloat) second; break; case STRING: floatB = floatPrim((PString) second); break; default: // XXX - EXPLODE! return null; } floatRes = floatPrim(((PFloat) first).getValue() * floatB.getValue()); return floatRes; case INTEGER: PInteger intB, intRes; switch (second.getFormalType()) { case INTEGER: intB = (PInteger) second; break; case FLOAT: intB = intPrim((PFloat) second); break; case STRING: intB = intPrim((PString) second); break; default: // XXX - EXPLODE! return null; } intRes = intPrim(((PInteger) first).getValue() * intB.getValue()); return intRes; default: // XXX - We need a narrow exception class for this. return null; } } public static TypeInterface div(TypeInterface first, TypeInterface second) throws EvalException { switch (first.getFormalType()) { case FLOAT: PFloat floatB, floatRes; switch (second.getFormalType()) { case INTEGER: floatB = floatPrim((PInteger) second); break; case FLOAT: floatB = (PFloat) second; break; case STRING: floatB = floatPrim((PString) second); break; default: // XXX - EXPLODE! return null; } if ( floatB.getValue() == 0.0 ) { // Throw DivZero Error reportEvalError( String.format( "Can not perform assignment - divide by zero error would occur (given %s)", floatB.getValue() ), second ); return null; } floatRes = floatPrim(((PFloat) first).getValue() / floatB.getValue()); return floatRes; case INTEGER: PInteger intB, intRes; switch (second.getFormalType()) { case INTEGER: intB = (PInteger) second; break; case FLOAT: intB = intPrim((PFloat) second); break; case STRING: intB = intPrim((PString) second); break; default: // XXX - EXPLODE! return null; } if ( intB.getValue() == 0 ) { // Throw DivZero Error reportEvalError( String.format( "Can not perform assignment - divide by zero error would occur (given %s)", intB.getValue() ), second ); return null; } intRes = intPrim(((PInteger) first).getValue() / intB.getValue()); return intRes; default: // XXX - We need a narrow exception class for this. return null; } } public static TypeInterface concat(TypeInterface first, TypeInterface second) { PString stringA, stringB, stringRes; stringA = strPrim(first.getRepr()); stringB = strPrim(second.getRepr()); stringRes = strPrim(stringA.getValue() + stringB.getValue()); return stringRes; } public static TypeInterface equal(TypeInterface first, TypeInterface second) { PBoolean res = new PBoolean(); switch (first.getFormalType()) { case FLOAT: PFloat floatB = (PFloat) second.coerceTo(ReturnType.FLOAT); if ( Double.compare(((PFloat) first).getValue(), floatB.getValue()) == 0 ) { res.setValue(Boolean.TRUE); }else{ res.setValue(Boolean.FALSE); } return res; case INTEGER: PInteger intB = (PInteger) second.coerceTo(ReturnType.INTEGER); if( ((PInteger) first).getValue() == intB.getValue()){ res.setValue(Boolean.TRUE); }else{ res.setValue(Boolean.FALSE); } return res; case BOOLEAN: PBoolean boolB = (PBoolean) second.coerceTo(ReturnType.BOOLEAN); if ( ((PBoolean) first).getValue() == boolB.getValue() ) { res.setValue(Boolean.TRUE); } else { res.setValue(Boolean.FALSE); } return res; case STRING: PString strB = (PString) second.coerceTo(ReturnType.STRING); String a = ((PString) first).getValue(); String b = strB.getValue(); if ( a.compareTo(b) == 0 ) { res.setValue(Boolean.TRUE); } else { res.setValue(Boolean.FALSE); } return res; default: return null; } } public static TypeInterface notEqual(TypeInterface first, TypeInterface second) throws EvalException { PBoolean res = new PBoolean(); switch (first.getFormalType()) { case FLOAT: PFloat floatB = (PFloat) second.coerceTo(ReturnType.FLOAT); if ( Double.compare(((PFloat) first).getValue(), floatB.getValue()) != 0 ) { res.setValue(Boolean.TRUE); }else{ res.setValue(Boolean.FALSE); } return res; case INTEGER: PInteger intB = (PInteger) second.coerceTo(ReturnType.INTEGER); if( ((PInteger) first).getValue() != intB.getValue()){ res.setValue(Boolean.TRUE); }else{ res.setValue(Boolean.FALSE); } return res; case BOOLEAN: PBoolean boolB = (PBoolean) second.coerceTo(ReturnType.BOOLEAN); if ( ((PBoolean) first).getValue() != boolB.getValue() ) { res.setValue(Boolean.TRUE); } else { res.setValue(Boolean.FALSE); } return res; case STRING: PString strB = (PString) second.coerceTo(ReturnType.STRING); String a = ((PString) first).getValue(); String b = strB.getValue(); if ( a.compareTo(b) != 0 ) { res.setValue(Boolean.TRUE); } else { res.setValue(Boolean.FALSE); } return res; default: return null; } } public static TypeInterface greaterThan(TypeInterface first, TypeInterface second) throws EvalException { PBoolean res = new PBoolean(); switch (first.getFormalType()) { case FLOAT: PFloat floatB = (PFloat) second.coerceTo(ReturnType.FLOAT); if ( Double.compare(((PFloat) first).getValue(), floatB.getValue()) > 0 ) { res.setValue(Boolean.TRUE); }else{ res.setValue(Boolean.FALSE); } return res; case INTEGER: PInteger intB = (PInteger) second.coerceTo(ReturnType.INTEGER); if( ((PInteger) first).getValue() > intB.getValue()){ res.setValue(Boolean.TRUE); }else{ res.setValue(Boolean.FALSE); } return res; case BOOLEAN: reportEvalError("Error can not do greater-than comparision of booleans"); return null; case STRING: PString strB = (PString) second.coerceTo(ReturnType.STRING); String a = ((PString) first).getValue(); String b = strB.getValue(); if ( a.compareTo(b) > 0 ) { res.setValue(Boolean.TRUE); } else { res.setValue(Boolean.FALSE); } return res; default: return null; } } public static TypeInterface lessThan(TypeInterface first, TypeInterface second) throws EvalException { PBoolean res = new PBoolean(); switch (first.getFormalType()) { case FLOAT: PFloat floatB = (PFloat) second.coerceTo(ReturnType.FLOAT); if ( Double.compare(((PFloat) first).getValue(), floatB.getValue()) < 0 ) { res.setValue(Boolean.TRUE); }else{ res.setValue(Boolean.FALSE); } return res; case INTEGER: PInteger intB = (PInteger) second.coerceTo(ReturnType.INTEGER); if( ((PInteger) first).getValue() < intB.getValue()){ res.setValue(Boolean.TRUE); }else{ res.setValue(Boolean.FALSE); } return res; case BOOLEAN: reportEvalError("Error can not do less-than comparision of booleans"); return null; case STRING: PString strB = (PString) second.coerceTo(ReturnType.STRING); String a = ((PString) first).getValue(); String b = strB.getValue(); if ( a.compareTo(b) < 0 ) { res.setValue(Boolean.TRUE); } else { res.setValue(Boolean.FALSE); } return res; default: return null; } } public static TypeInterface lessThanEqual(TypeInterface first, TypeInterface second) throws EvalException { PBoolean res = new PBoolean(); switch (first.getFormalType()) { case FLOAT: PFloat floatB = (PFloat) second.coerceTo(ReturnType.FLOAT); if ( Double.compare(((PFloat) first).getValue(), floatB.getValue()) <= 0 ) { res.setValue(Boolean.TRUE); }else{ res.setValue(Boolean.FALSE); } return res; case INTEGER: PInteger intB = (PInteger) second.coerceTo(ReturnType.INTEGER); if( ((PInteger) first).getValue() <= intB.getValue()){ res.setValue(Boolean.TRUE); }else{ res.setValue(Boolean.FALSE); } return res; case BOOLEAN: reportEvalError("Error can not do less-than-equal comparision of booleans"); return null; case STRING: PString strB = (PString) second.coerceTo(ReturnType.STRING); String a = ((PString) first).getValue(); String b = strB.getValue(); if ( a.compareTo(b) <= 0 ) { res.setValue(Boolean.TRUE); } else { res.setValue(Boolean.FALSE); } return res; default: return null; } } public static TypeInterface greaterThanEqual(TypeInterface first, TypeInterface second) throws EvalException { PBoolean res = new PBoolean(); switch (first.getFormalType()) { case FLOAT: PFloat floatB = (PFloat) second.coerceTo(ReturnType.FLOAT); if ( Double.compare(((PFloat) first).getValue(), floatB.getValue()) >= 0 ) { res.setValue(Boolean.TRUE); }else{ res.setValue(Boolean.FALSE); } return res; case INTEGER: PInteger intB = (PInteger) second.coerceTo(ReturnType.INTEGER); if( ((PInteger) first).getValue() >= intB.getValue()){ res.setValue(Boolean.TRUE); }else{ res.setValue(Boolean.FALSE); } return res; case BOOLEAN: reportEvalError("Error can not do greater-than-equal comparision of booleans"); return null; case STRING: PString strB = (PString) second.coerceTo(ReturnType.STRING); String a = ((PString) first).getValue(); String b = strB.getValue(); if ( a.compareTo(b) >= 0 ) { res.setValue(Boolean.TRUE); } else { res.setValue(Boolean.FALSE); } return res; default: return null; } } public static TypeInterface modulo(TypeInterface first, TypeInterface second) { switch (first.getFormalType()) { case FLOAT: PFloat floatB, floatRes; switch (second.getFormalType()) { case INTEGER: floatB = floatPrim((PInteger) second); break; case FLOAT: floatB = (PFloat) second; break; case STRING: floatB = floatPrim((PString) second); break; default: // XXX - EXPLODE! return null; } floatRes = floatPrim(((PFloat) first).getValue() % floatB.getValue()); return floatRes; case INTEGER: PInteger intB, intRes; switch (second.getFormalType()) { case INTEGER: intB = (PInteger) second; break; case FLOAT: intB = intPrim((PFloat) second); break; case STRING: intB = intPrim((PString) second); break; default: // XXX - EXPLODE! return null; } intRes = intPrim(((PInteger) first).getValue() % intB.getValue()); return intRes; default: // XXX - We need a narrow exception class for this. return null; } } public static TypeInterface power(TypeInterface first, TypeInterface second) { switch (first.getFormalType()) { case FLOAT: PFloat floatB, floatRes; switch (second.getFormalType()) { case INTEGER: floatB = floatPrim((PInteger) second); break; case FLOAT: floatB = (PFloat) second; break; case STRING: floatB = floatPrim((PString) second); break; default: // XXX - EXPLODE! return null; } floatRes = floatPrim(Math.pow(((PFloat) first).getValue(), floatB.getValue())); return floatRes; case INTEGER: PInteger intB, intRes; switch (second.getFormalType()) { case INTEGER: intB = (PInteger) second; break; case FLOAT: intB = intPrim((PFloat) second); break; case STRING: intB = intPrim((PString) second); break; default: // XXX - EXPLODE! return null; } intRes = intPrim(Math.pow(((PInteger) first).getValue(), intB.getValue())); return intRes; default: // XXX - We need a narrow exception class for this. return null; } } public static TypeInterface contains(TypeInterface item, TypeInterface container) throws EvalException { ArrayType ary = null; ReturnType typeBound; PString str = null; if ( container.getFormalType() == ReturnType.ARRAY ) { ary = (ArrayType) container; typeBound = ary.getBoundType(); } else if ( container.getFormalType() == ReturnType.STRING ) { str = (PString) container; typeBound = ReturnType.STRING; } else { reportEvalError( String.format( "Cannot check membership of type `%s`", container.getFormalType().name() ), container, item ); return null; } if ( item.getFormalType() != typeBound ) { if ( item.coercibleTo(typeBound) ) { item = item.coerceTo(typeBound); } else { return boolPrim(false); } } switch (container.getFormalType()) { case STRING: String s = ((PString) container).getValue(); return boolPrim(s.contains(((PString) item).getValue())); case ARRAY: for (TypeInterface elem : ary.getValue()) { if ( elem.isEqual(item.getValue()) ) { return boolPrim(true); } } break; } return boolPrim(false); } public static TypeInterface notContains(TypeInterface item, TypeInterface container) throws EvalException { return boolPrim(! ((PBoolean) contains(item, container)).getValue()); } public static TypeInterface and(TypeInterface a, TypeInterface b) throws EvalException { boolean left; boolean right; if ( a.getFormalType() == ReturnType.BOOLEAN ) { // get the bool value left = ((PBoolean) a).getValue(); } else { reportEvalError( String.format( "a is not a bool `%s`", a.getFormalType().name() ), a ); return null; } if ( b.getFormalType() == ReturnType.BOOLEAN ) { right = ((PBoolean) b).getValue(); } else { reportEvalError( String.format( "b is not a bool `%s`", b.getFormalType().name() ), b ); return null; } return boolPrim(left && right); } public static TypeInterface or(TypeInterface a, TypeInterface b) throws EvalException { boolean left; boolean right; if ( a.getFormalType() == ReturnType.BOOLEAN) { // get the bool value left = ((PBoolean) a).getValue(); } else { reportEvalError( String.format( "a is not a bool `%s`", a.getFormalType().name() ), a ); return null; } if( b.getFormalType() == ReturnType.BOOLEAN ){ right = ((PBoolean) b).getValue(); } else { reportEvalError( String.format( "b is not a bool `%s`", b.getFormalType().name() ), b ); return null; } return boolPrim(left || right); } /** * Negates a singular number! */ public static TypeInterface arithNegate(TypeInterface operand) throws EvalException { switch (operand.getFormalType()) { case FLOAT: PFloat floatVal = (PFloat) operand; return floatPrim(-(floatVal.getValue())); case INTEGER: PInteger intVal = (PInteger) operand; return intPrim(-(intVal.getValue())); default: reportEvalError( String.format( "unary arithmetic negation `-` expected numeric type, not `%s`", operand.getFormalType().name() ), operand ); } return null; } /** * Negates a boolean value! */ public static TypeInterface logicNegate(TypeInterface operand) throws EvalException { switch (operand.getFormalType()) { case BOOLEAN: PBoolean boolVal = (PBoolean) operand; return boolPrim(!(boolVal.getValue())); default: reportEvalError( String.format( "unary logical negation `not` expected boolean type, not `%s`", operand.getFormalType().name() ), operand ); } return null; } public static TypeInterface addset(TypeInterface first, TypeInterface second) { TypeInterface value; switch (first.getFormalType()) { case FLOAT: PFloat floatB, floatRes; switch (second.getFormalType()) { case INTEGER: floatB = floatPrim((PInteger) second); break; case FLOAT: floatB = (PFloat) second; break; case STRING: floatB = floatPrim((PString) second); break; default: // XXX - EXPLODE! return null; } value = floatPrim(((PFloat) first).getValue() + floatB.getValue()); ((PFloat) first).setValue(((PFloat) value).getValue()); return first; case INTEGER: PInteger intB, intRes; switch (second.getFormalType()) { case INTEGER: intB = (PInteger) second; break; case FLOAT: intB = intPrim((PFloat) second); break; case STRING: intB = intPrim((PString) second); break; default: // XXX - EXPLODE! return null; } value = intPrim(((PInteger) first).getValue() + intB.getValue()); ((PInteger) first).setValue(((PInteger) value).getValue()); return first; default: // XXX - We need a narrow exception class for this. return null; } } public static TypeInterface subset(TypeInterface first, TypeInterface second) { TypeInterface value; switch (first.getFormalType()) { case FLOAT: PFloat floatB, floatRes; switch (second.getFormalType()) { case INTEGER: floatB = floatPrim((PInteger) second); break; case FLOAT: floatB = (PFloat) second; break; case STRING: floatB = floatPrim((PString) second); break; default: // XXX - EXPLODE! return null; } value = floatPrim(((PFloat) first).getValue() - floatB.getValue()); ((PFloat) first).setValue(((PFloat) value).getValue()); return first; case INTEGER: PInteger intB, intRes; switch (second.getFormalType()) { case INTEGER: intB = (PInteger) second; break; case FLOAT: intB = intPrim((PFloat) second); break; case STRING: intB = intPrim((PString) second); break; default: // XXX - EXPLODE! return null; } value = intPrim(((PInteger) first).getValue() - intB.getValue()); ((PInteger) first).setValue(((PInteger) value).getValue()); return first; default: // XXX - We need a narrow exception class for this. return null; } } }
Python
UTF-8
998
2.859375
3
[]
no_license
import phonenumbers import folium # from test import number from phonenumbers import geocoder from phonenumbers import carrier from opencage.geocoder import OpenCageGeocode import random import pyautogui number = pyautogui.prompt("Enter a Phone Number (eg.+254712345678) : ") key = 'f0daa136d83f48f29e85601b69d9baa3' # getting the country someNumber = phonenumbers.parse(number) yourLocation = geocoder.description_for_number(someNumber, "en") print(yourLocation) # getting the service provider service_provider = phonenumbers.parse(number) print(carrier.name_for_number(service_provider, "en")) # getting the location geocoder = OpenCageGeocode(key) query = str(yourLocation) results = geocoder.geocode(query) # print(results) lat = results[0]['geometry']['lat'] lng = results[0]['geometry']['lng'] print(lat,lng) myMap = folium.Map(location=[lat, lng], zoom_start = 9) folium.Marker([lat, lng],popup= yourLocation).add_to((myMap)) # save map in html file myMap.save('myLocation.html')
Shell
UTF-8
3,644
4.40625
4
[ "MIT" ]
permissive
#!/bin/bash ## Install, uninstall and update .dotfiles ## https://github.com/bymathias/dotfiles set -e DOT_SYS=`uname -s` DOT_BAK=$(date +"%Y-%m-%d").bak DOT_DEP=(git curl vim) DOT_DIR=~/.dotfiles DOT_FLS=(.bashrc .bash_profile .gitconfig .vim .vimrc .tmux.conf .inputrc) echo_notice() { echo -e "\n\033[4;37m$1\033[0m"; } dep_check() { type -p $1 &> /dev/null local INS_DEP=$? [[ $INS_DEP -eq 0 ]] && echo -e "$1 OK" || echo -e "$1 is required" return $INS_DEP } bak_files() { if [[ -h ~/$1 ]] then rm -v ~/$1 elif [[ -f ~/$1 || -d ~/$1 ]] then mv -v ~/$1 ~/$1.$DOT_BAK fi } get_files() { [[ -f $1 ]] && rm -v $1 curl -fL -o $1 -s $2 } bin_scripts() { get_files $DOT_DIR/bin/wp https://raw.github.com/wp-cli/builds/gh-pages/phar/wp-cli.phar get_files $DOT_DIR/bin/speedtest https://raw.github.com/sivel/speedtest-cli/master/speedtest_cli.py get_files $DOT_DIR/bin/timebackup https://github.com/laurent22/rsync-time-backup/raw/master/rsync_tmbackup.sh get_files $DOT_DIR/bin/cloudapp https://raw.github.com/bonifaido/cloudapp-cli/master/cloudapp for file in wp speedtest timebackup cloudapp do chmod +x $DOT_DIR/bin/$file done } bootstrap() { if [ $# -ne 1 ] then bootstrap help return fi case "$1" in "help") echo "-----------------------------------------------" echo " Usage:" echo " ./bootstrap.sh install" echo " ./bootstrap.sh uninstall" echo " ./bootstrap.sh update" echo " " echo " Doc: github.com/bymathias/dotfiles" echo "-----------------------------------------------" ;; "install") ## Create all symlinks for file in "${DOT_FLS[@]}" do bak_files $file if [[ $file == ".gitconfig" ]] then ln -sv $DOT_DIR/git/$file ~/$file elif [[ $file == ".vim" ]] then ln -sv $DOT_DIR/vim ~/$file else ln -sv $DOT_DIR/$file ~/$file fi done ## Get bin scripts bin_scripts ## Get Vim Vundle and install plugins git clone https://github.com/gmarik/vundle.git vim/bundle/vundle vim +BundleInstall +qall 2>/dev/null ## Set Vim config for root user if [[ $DOT_SYS == "Linux" ]]; then sudo ln -siv $DOT_DIR/.vimrc /root/.vimrc sudo ln -siv $DOT_DIR/vim /root/.vim fi ;; "uninstall") ## Remove all symlinks for file in "${DOT_FLS[@]}" do rm -v ~/$file done ## Remove Vim config for root user if [[ $DOT_SYS == "Linux" ]]; then sudo rm -iv --preserve-root /root/.vimrc sudo rm -Riv --preserve-root /root/.vim fi ## Backup .dotfiles folder mv -v $DOT_DIR $DOT_DIR.$DOT_BAK ;; "update") ## Update bin scripts bin_scripts ## Update Vim plugins using Vundle vim +BundleInstall +qall 2>/dev/null ;; *) bootstrap help ;; esac } echo_notice "Checking dependencies..." for i in "${DOT_DEP[@]}" do dep_check $i done echo_notice "Dotfiles $1..." bootstrap "$@" echo_notice "Dotfiles $1 done."
C#
UTF-8
1,077
2.59375
3
[]
no_license
using System; using System.Collections.Generic; using System.Web; /// <summary> /// 意见反馈 /// </summary> public class Feedback { /// <summary> /// 返回所有意见 /// </summary> public static IEnumerable<dynamic> GetAllFeedbacks() { var db = MyDB.Open(); var sql = @"Select * From Feedback a Inner Join Users b On a.UserID = b.UserID Order By a.ID Desc"; return db.Query(sql); } /// <summary> /// 新增意见 /// </summary> public static void Add(int UserID, string Suggestion) { var db = MyDB.Open(); var sql = "Insert Into Feedback (UserID, Suggestion, PostTime) Values (@0, @1, GetDate())"; db.Execute(sql, UserID, Suggestion); } /// <summary> /// 删除意见 /// </summary> public static void Delete(int ID) { var db = MyDB.Open(); var sql = "Delete From Feedback Where ID = @0"; db.Execute(sql, ID); } }
C#
UTF-8
1,264
3.578125
4
[]
no_license
// Problem 2. Print Company Information // A company has name, address, phone number, fax number, web site and manager. // The manager has first name, last name, age and a phone number. // Write a program that reads the information about a company and its manager and prints it back on the console. using System; class PrintCompanyInformation { static void Main() { Console.WriteLine("This program prints company information."); Console.WriteLine(); string companyName = "Company: Fantastico"; string companyAddress = "Address: 14A Momina salza, Sofia"; string phoneNumber = "Tel. +359 2 969 25 00"; string faxNumber = "Fax: (no fax)"; string webSite = "Web site: http://ff-bg.net/"; string managerFirstName = "Ivan"; string managerLastName = "Ivanov"; byte managerAge = 33; string managerPhone = "Tel. +359 888 080 080"; Console.WriteLine(companyName); Console.WriteLine(companyAddress); Console.WriteLine(phoneNumber); Console.WriteLine(faxNumber); Console.WriteLine(webSite); Console.WriteLine("Manager: " + managerFirstName + " " + managerLastName + " " + "(Age: {0}, {1})", managerAge, managerPhone); } }
C
UTF-8
2,551
2.625
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_display.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: fleger <fleger@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/12/20 08:05:58 by fleger #+# #+# */ /* Updated: 2019/12/21 07:42:35 by fleger ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" int ft_display_formatsize(t_def *tab_pars, int ret, char *temp) { if (tab_pars->is_less) ft_putstr(temp = ft_add_char_b(tab_pars->str, ' ', tab_pars->f_size)); else if (tab_pars->is_zero) { if (tab_pars->str[0] == '-') { ft_putchar('-'); ret++; temp = ft_itoa(-ft_atoi(tab_pars->str)); ft_putstr(temp = ft_add_char_f(temp, '0', tab_pars->f_size - 1)); free(tab_pars->str); } else ft_putstr(temp = ft_add_char_f(tab_pars->str, '0', tab_pars->f_size)); } else if (tab_pars->is_less) ft_putstr(temp = ft_add_char_b(tab_pars->str, ' ', tab_pars->f_size)); else ft_putstr(temp = ft_add_char_f(tab_pars->str, ' ', tab_pars->f_size)); ret += ft_strlen(temp); free(temp); return (ret); } int ft_display(t_def *tab_pars, int ret) { char *temp; int size; size = 0; temp = NULL; if (tab_pars->is_dot == 1) ret += ft_dot(tab_pars, size); else if (tab_pars->is_mult == 1) ret += ft_mult(tab_pars); else if (tab_pars->f_size) ret = ft_display_formatsize(tab_pars, ret, temp); else { if (tab_pars->str[0] != '\0') ret += ft_strlen(tab_pars->str); else if (tab_pars->chara == 'c') { ft_putchar('\0'); ret++; } ft_putstr(tab_pars->str); free(tab_pars->str); } return (ret); } int ft_choose(t_def *tab_pars, const char *str, va_list *start) { int i; int ret; int j; j = 0; i = -1; ret = 0; while (str[++i]) { if (str[i] == '%') { ft_init_null(tab_pars); ft_parsing(str + i++, tab_pars, &*start); ret = ft_display(tab_pars, ret); j++; while (!is_format(str[i])) i++; } else { ft_putchar(str[i]); ret++; } } return (ret); }
JavaScript
UTF-8
1,163
2.5625
3
[]
no_license
function DebugValidate() { var output = ValidateServerActive( {"WorldName":"blah", "ServerIP":"174.216.19.195", "Port":7777} ); Logger.log( "DebugValidate: "+output ); } function ValidateServerActive( server_data ) { /*var data = { "WorldName": server_data["WorldName"], "ServerIP": server_data["ServerIP"], "Port": server_data["Port"] }; var options = { "method" : "post", "contentType": "application/json", "payload": JSON.stringify( data ) }; var resp, resp_str; try { var resp = UrlFetchApp.fetch( "http://hamstar.pw/hamstarhelpers/validate_server/", options ); } catch( err ) { console.warn( "ValidateServerActive connection failed - "+err ); return false; } try { var resp_str = resp.getContentText(); var resp_json = JSON.parse( resp_str ); if( "Success" in resp_json && resp_json["Success"] ) { return true; } if( "Msg" in resp_json ) { console.log( "ValidateServerActive connection unsuccessful - "+resp_json.Msg ); } } catch( err ) { console.warn( "ValidateServerActive failed - "+err ); return false; }*/ return true; }
Markdown
UTF-8
2,030
3.6875
4
[]
no_license
2000 #Magic Squares <!--- tags: cpp --> A magic square here is a square matrix made of subsequent natural numbers, whose sums for each row, column, and the two main diagonals are equal. Magic squares such as those defined above are called 'perfect squares'. Example of magic square of n=3: |||| |-|-|-| |8|1|6 |3|5|7 |4|9|2 The square shown above is the base perfect square, where the numbers from 1 to 'N', where 'N' is the number of elements in the matrix (N = n^2 e.g., 3x3 = 9), are used only once. Adding the same number to every square element, or multiplying it by the same number, produces other magic squares of the same family. ##MagicSQ MagicSQ implements a simple algorithm (Simon de la Loubère's) for creating squares of the same type as shown above. It can create base perfect squares of any size and is limited only by the memory in your system and by your time. It is a polynomial time algorithm of O(n^2) and has a n^2 space complexity. The above tables were generated by this program. The n-odd magic square algorithm is easy to learn by heart and could be great for impressing kids. For an explanation of the algorithm used in the MagicSQ generator see: http://forum.swarthmore.edu/alejandre/magic.square/adler/adler.5x5math.html. Surprisingly, a generic algorithm exists for generating also n-even magic squares by [Kwon Young Shin](http://user.chollian.net/~brainstm/MagicSquare.htm). The original program is modified, here, to make use of dynamic memory allocation, in order to allow the creation of squares with a big number of elements. It uses 's_matrix.h' and 's_matrix.c' files. Replace 'magicsq.c' by the 'kwon.c' file when compiling. I am not a mathematician, do not ask me on this. I was taught the n-odd algorithm on paper when I was very young by my grandfather, before I could learn to program, and found it very fascinating. Later on (when my grandfather was no more there), I became aware what he had taught to me was what they call an algorithm. I implemented it in C to test it for some bigger numbers.
Java
UTF-8
1,671
2
2
[]
no_license
package com.example.android.stickshiftdraft; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import static android.R.attr.button; public class MenuActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_menu); //Go to resources screen Button buttonResources= (Button) findViewById(R.id.resources_button); buttonResources.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent resourceIntent = new Intent(v.getContext(), ResourcesActivity.class); startActivity(resourceIntent); } }); //Go to question list screen Button buttonQuestionList= (Button) findViewById(R.id.question_list_button); buttonQuestionList.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent resourceIntent = new Intent(v.getContext(), QuestionListActivity.class); startActivity(resourceIntent); } }); //Go to question list screen Button buttonMenuStart= (Button) findViewById(R.id.menu_start_button); buttonMenuStart.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent resourceIntent = new Intent(v.getContext(), FlashcardActivity.class); startActivity(resourceIntent); } }); } }
C
UTF-8
197
3.015625
3
[]
no_license
#include <stdio.h> #include<conio.h> #include <string.h> void main() { char a[15]; int b=0; clrscr(); printf("Enter a String: \n"); scanf("%s",a); b=strlen(a); printf("Length= %d\n",b); getch(); }
C#
UTF-8
264
2.765625
3
[]
no_license
namespace AoC2015.Solutions.Day01 { using System.Linq; public class Part01 : ISolution { public string Solve(string input) { return (input.Count(x => x == '(') - input.Count(x => x == ')')).ToString(); } } }
Java
UTF-8
8,208
2.453125
2
[]
no_license
package game; import javafx.application.Platform; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.input.KeyCode; import javafx.scene.layout.Pane; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import util.*; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.util.Arrays; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; /** * Created by Hans on 26/10/2015. */ //FRONT END DEVELOPMENT REQUIRES NO CODE QUALITY // (Only CSS) public class ClientMain { static Player player; static Engine rmiServer; static int[][] visibleBoard; static final Logger LOGGER = LoggerFactory.getLogger(ClientMain.class); static String name = ""; public static String score = "0"; public static Label scoreLabel; public static Stage stage; public static int port; public static void changeScore(String score) { Platform.runLater(() -> scoreLabel.setText(score)); } private static String ip; public static void setup(String[] args, Stage primaryStage) throws Exception { LOGGER.info("args length is: {}", args.length); if (args.length == 1) { LOGGER.info("First argument is: {}", args[0]); ip = args[0]; } else if (args.length == 2) { LOGGER.info("First argument is: {}, second argument is: {}", args[0], args[1]); ip = args[0]; port = new Scanner(args[1]).hasNextInt() ? new Integer(args[1]) : 8080; name = "default"; } else if(args.length > 2) { ip = args[0]; port = Integer.parseInt(args[1]); name = args[2]; } else { ip = "localhost"; name = "default"; } new Thread(() -> { try { mainLoop(); } catch (Exception ignore) { LOGGER.info("Ignoring exception" , ignore); Platform.runLater(() -> { try { ServerSelect.start(primaryStage); } catch (Exception e) { e.printStackTrace(); } }); } }).start(); Platform.runLater(() -> { try { ClientMain.start(primaryStage); } catch (Exception e) { e.printStackTrace(); } }); } private static void mainLoop() throws Exception { Registry registry = LocateRegistry.getRegistry(ip, port); rmiServer = (Engine) registry.lookup("EngineImpl"); player = new PlayerImpl(PlayerType.SPECTATOR); player = rmiServer.registerPlayer(player); visibleBoard = rmiServer.getMaskedBoard(player); //This time active game loop is here while (true) { //We fps block in frontend, because we are a modern game and build on game tick //Read this as a rant Thread.sleep(500); //Poll if player died LOGGER.info("Player type is {}", player.getType()); if (player.getType() != PlayerType.NULL && player.getType() != PlayerType.SPECTATOR) { player = rmiServer.getPlayer(player.getX(), player.getY()); } if (player.getType() == PlayerType.NULL) { //You are dead System.out.println("Holy crap, you died :("); throw new IllegalStateException("Player is dead"); //System.exit(0); } if (player.getType() == PlayerType.SPECTATOR) { visibleBoard = rmiServer.getMaskedBoard(player); GameFieldElements.updateGameField(visibleBoard, EventCache.rects); continue; } LOGGER.info("Making move: {}", EventCache.previousEvent); player = rmiServer.makeMove(player, EventCache.previousEvent); EventCache.previousEvent = Move.NULL; visibleBoard = rmiServer.getMaskedBoard(player); LOGGER.info("Current player has coordinates ({}, {})", player.getX(), player.getY()); LOGGER.info("Current player has ID {}", player.getId()); try { GameFieldElements.updateGameField(visibleBoard, EventCache.rects); changeScore(player.getScore() + ""); } catch (NullPointerException e) { LOGGER.warn("Game not initialized"); } } } public static void start(Stage primaryStage) throws Exception { LOGGER.info("Client working!"); Label nameLabel = new Label(name); scoreLabel = new Label("0"); scoreLabel.setLayoutX(650); scoreLabel.setLayoutY(100); nameLabel.setLayoutX(650); nameLabel.setLayoutY(200); Pane root = new Pane(); EventCache.rects = GameFieldElements.initializeGameField(8, 8); List<Rectangle> rectangleList = Arrays.stream(EventCache.rects).flatMap(Arrays::stream).collect(Collectors.toList()); Rectangle[] rectangles = rectangleList.toArray(new Rectangle[rectangleList.size()]); LOGGER.debug("Get root children: {}", root.getChildren()); Scene scene = new Scene(root, 800, 600); Button fly = GameFieldElements.chooseFly(scene, primaryStage); fly.setLayoutX(700); fly.setLayoutY(100); root.getChildren().add(fly); Button frog = GameFieldElements.chooseFrog(scene, primaryStage); frog.setLayoutX(700); frog.setLayoutY(200); //Hack, don't remove. This triggers an instant nullpointer when there is no server //player.getId(); root.getChildren().add(frog); root.getChildren().addAll(rectangles); primaryStage.setScene(scene); primaryStage.show(); primaryStage.setOnCloseRequest(event -> System.exit(0)); fly.setOnAction(event -> { root.getChildren().removeAll(fly, frog); root.getChildren().addAll(scoreLabel, nameLabel); //EventCache.previousEvent = Move.FLY; try { LOGGER.info("Registering Fly, {}", player); player.setType(PlayerType.FLY); // player = rmiServer.registerPlayer(player); player = rmiServer.putPlayerOnBoard(player); visibleBoard = rmiServer.getMaskedBoard(player); GameFieldElements.updateGameField(visibleBoard, EventCache.rects); } catch (RemoteException e) { LOGGER.error("Failed to register fly position!", e); System.exit(1); } primaryStage.setScene(scene); primaryStage.show(); } ); frog.setOnAction(event -> { root.getChildren().removeAll(fly, frog); root.getChildren().addAll(scoreLabel, nameLabel); //EventCache.previousEvent = Move.FROG; try { player.setType(PlayerType.FROG); LOGGER.info("Registering Frog, {}", player); //player = rmiServer.registerPlayer(player); player = rmiServer.putPlayerOnBoard(player); visibleBoard = rmiServer.getMaskedBoard(player); GameFieldElements.updateGameField(visibleBoard, EventCache.rects); } catch (RemoteException e) { LOGGER.error("Failed to register Frog!", e); System.exit(1); } primaryStage.setScene(scene); primaryStage.show(); } ); scene.setOnKeyPressed(event -> { Move tmp = Move.NULL; if (EventCache.previousEvent != Move.NULL && player.getType() == PlayerType.FROG) { LOGGER.info("Temporary event is: {}", EventCache.previousEvent); tmp = EventCache.previousEvent; } if (event.getCode() == KeyCode.UP) { if (tmp == Move.UP) { EventCache.previousEvent = Move.DOUBLEUP; } else { EventCache.previousEvent = Move.UP; } } else if (event.getCode() == KeyCode.DOWN) { if (tmp == Move.DOWN) { EventCache.previousEvent = Move.DOUBLEDOWN; } else { EventCache.previousEvent = Move.DOWN; } } else if (event.getCode() == KeyCode.LEFT) { if (tmp == Move.LEFT) { EventCache.previousEvent = Move.DOUBLELEFT; } else { EventCache.previousEvent = Move.LEFT; } } else if (event.getCode() == KeyCode.RIGHT) { if (tmp == Move.RIGHT) { EventCache.previousEvent = Move.DOUBLERIGHT; } else { EventCache.previousEvent = Move.RIGHT; } } }); } }
Java
UTF-8
371
1.65625
2
[]
no_license
package com.example.tjdwp.planiot; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; /** * Created by tjdwp on 2017-08-08. */ public class Dic_info extends AppCompatActivity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.dic_info); } }
Java
UTF-8
1,364
3.03125
3
[]
no_license
package TCP_IP_in_Java; import java.io.IOException; import java.net.InetAddress; import java.util.List; /** * Created by tonytan on 10/8/15. * * */ public class LookupThread extends Thread{ private List entries; PooledWebLog log; public LookupThread(List entries, PooledWebLog log){ this.entries = entries; this.log = log; } @Override public void run() { String entry; while (true){ synchronized (entries){ while (entries.size() == 0){ if (log.isFinished()) return; try { entries.wait(); }catch (InterruptedException e){ // } } entry = (String) entries.remove(entries.size()-1); } int index = entry.indexOf(' ', 0); String remoteHost = entry.substring(0, index); String theRest = entry.substring(index, entry.length()); try { remoteHost = InetAddress.getByName(remoteHost).getHostName(); }catch (Exception e){ // } try { log.log(remoteHost+theRest); }catch (IOException e){ // } this.yield(); } } }
Java
UTF-8
192
1.671875
2
[]
no_license
package io.vilya.eurus.core.manager; /** * @author iamaprin * @time 2017年6月9日 下午10:11:52 */ public interface IManager { void startup(); void shutdown(); }
Markdown
UTF-8
4,803
2.96875
3
[]
no_license
``` package com.ksxing.util; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.List; /** * 200:表示成功 * 500:表示错误,错误信息在msg字段中 * 501:bean验证错误,不管多少个错误都以map形式返回 * 502:拦截器拦截到用户token出错 * 555:异常抛出信息 */ public class ResultJson { // 定义jackson对象 private static final ObjectMapper MAPPER = new ObjectMapper(); // 响应业务状态 private Integer status; // 响应消息 private String msg; // 响应中的数据 private Object data; private String ok;// 不使用 public static ResultJson build(Integer status, String msg, Object data) { return new ResultJson(status, msg, data); } public static ResultJson ok(Object data) { return new ResultJson(data); } public static ResultJson ok() { return new ResultJson(null); } public static ResultJson errorMsg(String msg) { return new ResultJson(500, msg, null); } public static ResultJson errorMap(Object data) { return new ResultJson(501, "error", data); } public static ResultJson errorTokenMsg(String msg) { return new ResultJson(502, msg, null); } public static ResultJson errorException(String msg) { return new ResultJson(555, msg, null); } public ResultJson() { } //public static LeeJSONResult build(Integer status, String msg) { //return new LeeJSONResult(status, msg, null); //} public ResultJson(Integer status, String msg, Object data) { this.status = status; this.msg = msg; this.data = data; } public ResultJson(Object data) { this.status = 200; this.msg = "OK"; this.data = data; } public Boolean isOK() { return this.status == 200; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } /** * * * * @Description: 将json结果集转化为LeeJSONResult对象 * * 需要转换的对象是一个类 * * @param jsonData * * @param clazz * * @return * */ public static ResultJson formatToPojo(String jsonData, Class<?> clazz) { try { if (clazz == null) { return MAPPER.readValue(jsonData, ResultJson.class); } JsonNode jsonNode = MAPPER.readTree(jsonData); JsonNode data = jsonNode.get("data"); Object obj = null; if (clazz != null) { if (data.isObject()) { obj = MAPPER.readValue(data.traverse(), clazz); } else if (data.isTextual()) { obj = MAPPER.readValue(data.asText(), clazz); } } return build(jsonNode.get("status").intValue(), jsonNode.get("msg").asText(), obj); } catch (Exception e) { return null; } } /** * * * * @Description: 没有object对象的转化 * * @param json * * @return * */ public static ResultJson format(String json) { try { return MAPPER.readValue(json, ResultJson.class); } catch (Exception e) { e.printStackTrace(); } return null; } /** * * * * @Description: Object是集合转化 * * 需要转换的对象是一个list * * @param jsonData * * @param clazz * * @return * * * */ public static ResultJson formatToList(String jsonData, Class<?> clazz) { try { JsonNode jsonNode = MAPPER.readTree(jsonData); JsonNode data = jsonNode.get("data"); Object obj = null; if (data.isArray() && data.size() > 0) { obj = MAPPER.readValue(data.traverse(), MAPPER.getTypeFactory().constructCollectionType(List.class, clazz)); } return build(jsonNode.get("status").intValue(), jsonNode.get("msg").asText(), obj); } catch (Exception e) { return null; } } public String getOk() { return ok; } public void setOk(String ok) { this.ok = ok; } } ```
Java
UTF-8
8,337
1.976563
2
[]
no_license
package br.com.joncmuniz.microservices.api.web.hateoas; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import br.com.joncmuniz.microservices.api.client.persitence.model.Customer; import br.com.joncmuniz.microservices.api.client.util.ApiMappings; import br.com.joncmuniz.microservices.api.service.ICustomerService; import br.com.joncmuniz.microservices.common.util.QueryConstants; import br.com.joncmuniz.microservices.common.web.controller.AbstractHateoasController; @Controller @RequestMapping(value = ApiMappings.Hateoas.CUSTOMER) public class CustomerHateoasController extends AbstractHateoasController<CustomerResource, Customer> { @Autowired private ICustomerService service; public CustomerHateoasController() { super(); } @RequestMapping(params = { QueryConstants.PAGE, QueryConstants.SIZE, QueryConstants.SORT_BY }, method = RequestMethod.GET) @ResponseBody @SwaggerExposeApi public HttpEntity<CustomerListResource> findAllPaginatedAndSorted(final HttpServletRequest request, @RequestParam(value = QueryConstants.PAGE) final int page, @RequestParam(value = QueryConstants.SIZE) final int size, @RequestParam(value = QueryConstants.SORT_BY) final String sortBy, @RequestParam(value = QueryConstants.SORT_ORDER) final String sortOrder) { CustomerListResource customerListResource = new CustomerListResource(); List<CustomerResource> customersResource = findPaginatedAndSortedInternal(page, size, sortBy, sortOrder); for (CustomerResource customerResource : customersResource) { customerResource.add(linkTo(methodOn(CustomerHateoasController.class).update(request, customerResource.getCustomer().getId(), customerResource.getCustomer())).withSelfRel()); } customerListResource.setCustomers(customersResource); customerListResource.add(linkTo(CustomerHateoasController.class).withRel("customers")); ResponseEntity<CustomerListResource> responseEntity = new ResponseEntity<CustomerListResource>( customerListResource, HttpStatus.OK); return responseEntity; } @RequestMapping(params = { QueryConstants.PAGE, QueryConstants.SIZE }, method = RequestMethod.GET) @ResponseBody @SwaggerExposeApi public HttpEntity<CustomerListResource> findAllPaginated(final HttpServletRequest request,@RequestParam(value = QueryConstants.PAGE) final int page, @RequestParam(value = QueryConstants.SIZE) final int size) { CustomerListResource customerListResource = new CustomerListResource(); List<CustomerResource> customersResource = findPaginatedInternal(page, size); for (CustomerResource customerResource : customersResource) { customerResource.add(linkTo(methodOn(CustomerHateoasController.class).update(request, customerResource.getCustomer().getId(), customerResource.getCustomer())).withSelfRel()); } customerListResource.setCustomers(customersResource); customerListResource.add(linkTo(CustomerHateoasController.class).withRel("customers")); ResponseEntity<CustomerListResource> responseEntity = new ResponseEntity<CustomerListResource>( customerListResource, HttpStatus.OK); return responseEntity; } @RequestMapping(params = { QueryConstants.SORT_BY }, method = RequestMethod.GET) @ResponseBody @SwaggerExposeApi public HttpEntity<CustomerListResource> findAllSorted(final HttpServletRequest request,@RequestParam(value = QueryConstants.SORT_BY) final String sortBy, @RequestParam(value = QueryConstants.SORT_ORDER) final String sortOrder) { CustomerListResource customerListResource = new CustomerListResource(); List<CustomerResource> customersResource = findAllSortedInternal(sortBy, sortOrder); for (CustomerResource customerResource : customersResource) { customerResource.add(linkTo(methodOn(CustomerHateoasController.class).update(request, customerResource.getCustomer().getId(), customerResource.getCustomer())).withSelfRel()); } customerListResource.setCustomers(customersResource); customerListResource.add(linkTo(CustomerHateoasController.class).withRel("customers")); ResponseEntity<CustomerListResource> responseEntity = new ResponseEntity<CustomerListResource>( customerListResource, HttpStatus.OK); return responseEntity; } @RequestMapping(produces = "application/json; charset=UTF-8", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) @SwaggerExposeApi public HttpEntity<CustomerListResource> findAll(final HttpServletRequest request) { CustomerListResource customerListResource = new CustomerListResource(); List<CustomerResource> customersResource = findAllInternal(request); for (CustomerResource customerResource : customersResource) { customerResource.add(linkTo(methodOn(CustomerHateoasController.class).update(request, customerResource.getCustomer().getId(), customerResource.getCustomer())).withSelfRel()); } customerListResource.setCustomers(customersResource); customerListResource.add(linkTo(CustomerHateoasController.class).withRel("customers")); ResponseEntity<CustomerListResource> responseEntity = new ResponseEntity<CustomerListResource>( customerListResource, HttpStatus.OK); return responseEntity; } @Override public long count() { // TODO Auto-generated method stub return super.count(); } @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public CustomerResource findOne(final HttpServletRequest request, @PathVariable("id") final Long id) { CustomerResource customerResource = findOneInternal(id); customerResource.add(linkTo(methodOn(CustomerHateoasController.class).findAll(request)).withSelfRel()); return customerResource; } @PostMapping(produces = "application/json; charset=UTF-8") @ResponseStatus(HttpStatus.CREATED) @SwaggerExposeApi public HttpEntity<CustomerResource> create(final HttpServletRequest request, @RequestBody @Valid final Customer resource) { createInternal(resource); CustomerResource customerResource = new CustomerResource(resource, request); customerResource.add(linkTo(methodOn(CustomerHateoasController.class).findAll(request)).withSelfRel()); customerResource.add(linkTo(methodOn(CustomerHateoasController.class).update(request, resource.getId(), resource)).withSelfRel()); return new ResponseEntity<CustomerResource>(customerResource, HttpStatus.CREATED); } @RequestMapping(produces = "application/json; charset=UTF-8", value = "/{id}", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) @SwaggerExposeApi public HttpEntity<CustomerResource> update(final HttpServletRequest request, @PathVariable("id") final Long id, @RequestBody @Valid final Customer resource) { resource.setId(id); updateInternal(id, resource); CustomerResource customerResource = new CustomerResource(resource, request); customerResource.add(linkTo(methodOn(CustomerHateoasController.class).findAll(request)).withSelfRel()); return new ResponseEntity<CustomerResource>(customerResource, HttpStatus.CREATED); } @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.NO_CONTENT) @SwaggerExposeApi public void delete(@PathVariable("id") final Long id) { deleteByIdInternal(id); } @Override protected final ICustomerService getService() { return service; } @Override protected final CustomerResource convert(final Customer entity) { return new CustomerResource(entity); } }
PHP
UTF-8
1,245
2.59375
3
[ "MIT" ]
permissive
<?php use Illuminate\Auth\UserTrait; use Illuminate\Auth\UserInterface; use Illuminate\Auth\Reminders\RemindableTrait; use Illuminate\Auth\Reminders\RemindableInterface; use LaravelBook\Ardent\Ardent; class User extends Ardent implements UserInterface, RemindableInterface { use UserTrait, RemindableTrait; public static $passwordAttributes = array('password', 'password_confirmation'); public $autoHashPasswordAttributes = true; public $autoPurgeRedundantAttributes = true; /** * The database table used by the model. * * @var string */ protected $table = 'users'; /** * The attributes excluded from the model's JSON form. * * @var array */ protected $hidden = array('password', 'remember_token'); /** * Mass Assignment protection * * @var array */ protected $fillable = array( 'email', 'name', 'password', 'password_confirmation' ); /** * Ardent validation rules * * @var array */ public static $rules = array( 'email' => 'required|email|unique:users', 'name' => 'required', 'password' => 'required|confirmed', 'password_confirmation' => 'required', ); /** * Blog relationship * */ public function blogs() { return $this->hasMany('BlogPost', 'user_id'); } }
Java
UTF-8
1,620
2.40625
2
[]
no_license
package it.cilea.osd.jdyna.validator; import it.cilea.osd.jdyna.model.Soggettario; import it.cilea.osd.jdyna.service.IValidatorClassificationService; import it.cilea.osd.jdyna.service.IValidatorSubjectService; import it.cilea.osd.jdyna.service.ValidatorService.ValidationResult; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; public class SoggettarioValidator extends JDynaBaseValidator { protected final Log log = LogFactory.getLog(getClass()); private IValidatorSubjectService validatorService; public SoggettarioValidator(IValidatorSubjectService validatorService) { super(validatorService); this.validatorService = validatorService; } public boolean supports(Class clazz) { return Soggettario.class.isAssignableFrom(clazz); } public void validate(Object object, Errors errors) { log.debug("SoggettoValidator.java-----validate"); Soggettario soggetto = (Soggettario) object; ValidationUtils.rejectIfEmptyOrWhitespace(errors, "nome", "error.message.fallita.campo.obbligatorio"); validateVoce(soggetto,errors); } /** Verifica se la voce e' stata inserita ed e' unica sul soggettario. */ public void validateVoce(Soggettario soggettario,Errors errors) { ValidationResult result = validatorService.controllaNomeSuSoggettario(soggettario, soggettario.getNome()); if (!result.isSuccess()) { errors.rejectValue("nome",result.getMessage()); } } }
PHP
UTF-8
4,740
2.71875
3
[ "Apache-2.0" ]
permissive
<?php namespace FrontCore\ViewHelpers; use Zend\View\Helper\AbstractHelper; class FrontRenderSimpleHtmlTable extends AbstractHelper { /** * Default settings for table params * @var various */ protected $id = "dataTable1"; protected $class = "data-table mj3-table table table-striped dataTable no-footer"; protected $width = "100%"; protected $cellpadding = "0"; protected $cellspacing = "0"; protected $border = "0"; protected $data_options = FALSE; protected $rownumbers = FALSE; protected $pagination = FALSE; protected $data_mode = "columntoggle"; protected $data_role = "table"; /** * Collection of headers for the table * @var array */ private $_arr_headings; /** * Data to be populated within the table * @var array */ private $_arr_data; /** * Data to be added to the footer * @var array */ private $_arr_footer; /** * Container for generated html * @var string */ private $_html; public function __invoke($arr_data = array(), $arr_headings = array(), $arr_options = "", $arr_footer = "") { //assign settings received if (is_array($arr_options)) { foreach ($arr_options as $key => $value) { $this->$key = $value; }//end foreach }//end if $this->_arr_headings = $arr_headings; $this->_arr_data = $arr_data; $this->_arr_footer = $arr_footer; return self::_buildTable(); }//end function public function generate($arr_options = "", $arr_headings = array(), $arr_data = array(), $arr_footer = "") { return self::__invoke($arr_data, $arr_headings, $arr_options, $arr_footer); }//end function /** * Create the table structure * @return string */ private function _buildTable() { //open the table //set table params $arr_params = array( "id", "class", "cellspacing", "cellpadding", "width", "border", "data_options", "rownumbers", "pagination", "data_mode", "data_role", ); $table_options = ""; foreach ($arr_params as $k => $v) { if ($this->$v !== FALSE) { $value = $this->$v; switch ($v) { case "data_options": $v = "data-options"; break; case "data_mode": $v = "data-mode"; break; case "data_role": $v = "data-role"; break; }//end switch $table_options .= str_replace("_", "", $v) . "=\"$value\" "; }//end if }//end foreach $this->_html = "<table $table_options>"; //set headers $this->_html .= self::_setHeaders(); //set table body $this->_html .= self::_setData(); //set table footer if (is_array($this->_arr_footer)) { $this->_html .= self::_setFooter(); }//end if //close the table $this->_html .= "</table>"; return $this->_html; }//end function /** * Set headers * @return string */ private function _setHeaders() { $html = "<thead>"; $html .= "<tr>"; if (is_array($this->_arr_headings)) { foreach ($this->_arr_headings as $key => $value) { if (is_array($value)) { $th_options = ""; foreach($value as $e => $ev) { if ($e != "value") { $th_options .= "$e=\"$ev\" "; } else { $ev_value = $ev; }//end if }//end foreach if (array_key_exists("disable-data-priority", $value)) { $html .= "<th $th_options>$ev_value</th>"; } else { $html .= "<th $th_options data-priority=\"" . ($key + 1) . "\">$ev_value</th>"; }//end if } else { $html .= "<th data-priority=\"" . ($key + 1) . "\">$value</th>"; }//end if }//end foreach }//end if $html .= "</tr>"; $html .= "</thead>"; return $html; }//end function /** * Populate the table with data * @return string */ private function _setData() { $html = "<tbody>"; if (is_array($this->_arr_data)) { foreach ($this->_arr_data as $key => $arr_value) { if (is_array($arr_value)) { $html .= "<tr id=\"tr_$key\">"; foreach ($arr_value as $k => $v) { if (is_array($v)) { $td_options = ""; foreach ($v as $e => $ev) { if ($e != "value") { $td_options .= "$e=\"$ev\" "; } else { $ev_value = $ev; }//end if }//end foreach $html .= "<td $td_options>$ev_value</td>"; } else { $html .= "<td>$v</td>"; }//end if }//end foreach $html .= "</tr>"; }//end if }//end foreach }//end if $html .= "</tbody>"; return $html; }//end function /** * Create HTML table footer * @return string */ private function _setFooter() { $html = "<tfoot>"; $html .= "</tfoot>"; return $html; }//end function }//end function
Markdown
UTF-8
5,454
2.609375
3
[]
no_license
--- author: name: jshen picture: 113709 body: "[img:sites/default/files/old-images/TypeAmericana2_500pix_6520.jpg]\r\n\r\n\r\n<strong>First, A full day of talking about American type history<strong>\r\n\t\r\nFriday, May 4, 10am\u20135pm\r\n\r\nWe\u2018ve invited noted historians and practitioners of American typography to share their research and personal experience\u2014information you won't find assembled anywhere else. \r\n\r\nPaul Shaw | <em>Oswald Cooper: Attacked by an itch to work with type<em>\r\n\r\nDr. Cathleen Baker | <em>Roycrofters to Renaissance: The progression of Dard Hunter\u2018s letterforms from arts and crafts to classical<em>\r\n\r\nPaul F. Gehl | <em>Ludlow\u2018s Mutt and Jeff: Douglas McMurtrie and R. Hunter Middleton<em>\r\n\r\nNancy Sharon Collins | <em>Engraving: The curiously shy stepchild in American type genealogy<em>\r\n\r\nThomas Phinney, Steve Matteson, and Richard Kegler | <em>A second life for vintage American typefaces<em>\r\n\r\nFrank Brannon | <em>Print Your Own Language: The role of letterpress in Cherokee language revitalization<em>\r\n\r\n<strong>On the weekend, a choice of two workshops<strong>\r\n\r\nSumner Stone | <strong>1-day Workshop | <em>Rome in a Day: Designing Capital Letters<em><strong>\r\n\r\nSaturday, May 5, 9am\u20134pm\r\n\r\nThis workshop led by Sumner Stone combines history and the drawing and digitizing of an alphabet of sans serif roman capital letters based on examples from the second century BCE. Stone will show different approaches to designing letters that will reveal their underlying structures and how they relate to modern sans serif forms. \r\n\r\nCarl Montford | <strong>2-day Workshop | <em>Plants and Platen<em><strong>\r\n\r\nSaturday and Sunday, May 5 & 6, 9am\u20134pm\r\n\r\nTake home three treasures from this workshop. First, you\u2018ll have a floral wood engraving that you carved, based on 15th century herbal books. You\u2018ll also have a print of your illustration with its accompanying handset-type description, made on a vintage Reliance iron handpress. Finally, we\u2018ll give you an illustrated booklet about the restoration of the Reliance, showing how design ingenuity and a passion for making beautiful things created a gem of a refurbished press.\r\n\r\nMore information and registration: http://typeamericana.svcseattle.com/\r\n\r\n<em>Register for single or multiple events. Spaces are limited!\r\nDiscount for multiple registration. Student and AIGA discounts. \r\nDiscount on hotel reservations until April 12.<em>" comments: - author: name: princeruben-spammer body: 'The <a href="http://www.ashwatches.net">replica watch</a> can extremely effortlessly select lots of around 100 dollars. <a href="http://www.ashwatches.net/replica-panerai-watches.html">replica panerai watches</a> hold a substantial share from the marketplace and are probably the most helpful retailers. Fake Rolex watches have the same appearance and sense of the innovative items,they are influential and create an impression at job and at parties as well. ' created: '2012-11-07 07:48:27' - author: name: princeruben-spammer body: 'There are some important functions that make <a href="http://www.ashwatches.net">watches replica</a> so attractive and eye-catching. And due to these features, <a href="http://www.ashwatches.net/replica-omega-watches.html">replica omega watches</a> have grow to be a need to have trend accessory for several of us. Be it any age group or gender, the followers of watches are just about every in which giving a soaring substantial restrict to the Reputation of these points. ' created: '2012-11-07 07:48:51' - author: name: princeruben-spammer body: Welcome to Ashwatches <a href="http://www.ashwatches.net">replica watches</a>, China's large online shop for top brands copy watches, which offers a huge selection of <a href="http://www.ashwatches.net/replica-panerai-watches.html">replica panerai watches</a>, and other well-known brands fake watches. created: '2012-11-07 07:49:19' - author: name: princeruben-spammer body: 'Find the your perfect <a href="http://www.ashwatches.net">replica watch</a> online store for example ROLEX, <a href="http://www.ashwatches.net/replica-patek-philippe-watches.html">replica patek philippe watches</a>, TAG HEUER, CARTIER, PANERAI, CITIZEN, HUBLOT and IWC and convince yourself of our low prices for men''s watches, and women''s watches. The mission of us is to provide you with the hottest replica watches at best price. ' created: '2012-11-07 07:49:30' - author: name: princeruben-spammer body: 'Therefore leather men <a href="http://www.ashwatches.net">watches replica</a> watch concerning find the style and beauty, these people looking for legitimate Hublot Major Boom <a href="http://www.ashwatches.net/replica-montblanc-watches.html">replica montblanc watches</a> using constrained finances opt for the replications. If you wear this one, you will be the leader of the fashion trends. ' created: '2012-11-07 07:49:50' - author: name: evanmacdonald picture: 115105 body: "I went in 2010 and it was really great. The design workshop with Sumner Stone was fabulous, only it was too short. This year, tho, it will be a full day.\r\n\r\ncheers!" created: '2012-02-22 18:28:10' date: '2012-02-22 00:25:23' node_type: forum title: 'Type Americana 2: May 4-6, Seattle Washington' ---
JavaScript
UTF-8
651
3.640625
4
[]
no_license
var fs = require('fs'); async function myReadFile() { try { console.log('Starting read'); let result = await fs.readFile('input.txt',function(err,data){ if (err) { return console.log(err); } console.log('Async read: '+ data.toString()); }) } catch (error) { console.log('there was an error - not callback'); } console.log('Call made'); /* let promise = new Promise((resolve, reject) => { setTimeout(() => resolve("done!"), 1000) }); let result = await promise; // wait till the promise resolves (*) console.log(result); // "done!" */ } myReadFile();
Markdown
UTF-8
4,055
2.703125
3
[]
no_license
--- title: "Créer votre première application web PHP dans Azure en 5 minutes | Microsoft Docs" description: "Découvrez la facilité avec laquelle vous pouvez exécuter des applications web dans App Service en déployant un exemple d’application PHP." services: app-service\web documentationcenter: author: cephalin manager: wpickett editor: ms.assetid: 6feac128-c728-4491-8b79-962da9a40788 ms.service: app-service-web ms.workload: web ms.tgt_pltfrm: na ms.devlang: na ms.topic: hero-article ms.date: 03/17/2017 ms.author: cephalin translationtype: Human Translation ms.sourcegitcommit: 0d8472cb3b0d891d2b184621d62830d1ccd5e2e7 ms.openlocfilehash: afecc8997631bf507c797e56a9e3fc0d1df27614 ms.lasthandoff: 03/21/2017 --- # <a name="create-your-first-php-web-app-in-azure-in-five-minutes"></a>Créer votre première application web PHP dans Azure en 5 minutes [!INCLUDE [app-service-web-selector-get-started](../../includes/app-service-web-selector-get-started.md)] Ce démarrage rapide vous permet de déployer votre première application web PHP dans [Azure App Service](../app-service/app-service-value-prop-what-is.md) en quelques minutes. Avant de commencer, assurez-vous que l’interface de ligne de commande Azure est installée. Pour plus d’informations, consultez le [Guide d’installation de l’interface de ligne de commande Azure](https://docs.microsoft.com/cli/azure/install-azure-cli). ## <a name="log-in-to-azure"></a>Connexion à Azure Connectez-vous à Azure en exécutant `az login` et en suivant les instructions à l’écran. ```azurecli az login ``` ## <a name="create-a-resource-group"></a>Créer un groupe de ressources Créez un [groupe de ressources](../azure-resource-manager/resource-group-overview.md). C’est ici que vous placez toutes les ressources Azure que vous souhaitez gérer ensemble, telles que l’application web et son serveur principal SQL Database. ```azurecli az group create --location "West Europe" --name myResourceGroup ``` Pour connaître les valeurs que vous pouvez utiliser pour `---location`, utilisez la commande d’interface de ligne de commande Azure `az appservice list-locations`. ## <a name="create-an-app-service-plan"></a>Créer un plan App Service Créez un [plan App Service](../app-service/azure-web-sites-web-hosting-plans-in-depth-overview.md) « Standard » qui exécute un conteneur Linux. ```azurecli az appservice plan create --name my-free-appservice-plan --resource-group myResourceGroup --is-linux --sku S1 ``` ## <a name="create-a-web-app"></a>Créer une application web Créez une application web avec un nom unique dans `<app_name>`. ```azurecli az appservice web create --name <app_name> --resource-group myResourceGroup --plan my-free-appservice-plan ``` ## <a name="configure-the-linux-container"></a>Configurer le conteneur Linux Configurez le conteneur Linux pour utiliser l’image de PHP 7.0.6 par défaut. ```azurecli az appservice web config update --php-version 7.0.6 --name <app_name> --resource-group myResourceGroup ``` ## <a name="deploy-sample-application"></a>Déployer un exemple d’application Déployez un exemple d’application PHP à partir de GitHub. ```azurecli az appservice web source-control config --name <app_name> --resource-group myResourceGroup \ --repo-url "https://github.com/Azure-Samples/app-service-web-php-get-started.git" --branch master --manual-integration ``` ## <a name="browse-to-web-app"></a>Accéder à l’application web Pour exécuter votre application en temps réel dans Azure, exécutez la commande qui suit. ```azurecli az appservice web browse --name <app_name> --resource-group myResourceGroup ``` Félicitations, votre première application web PHP s’exécute en temps réel dans Azure App Service. [!INCLUDE [cli-samples-clean-up](../../includes/cli-samples-clean-up.md)] ## <a name="next-steps"></a>Étapes suivantes Explorez les [scripts d’interface de ligne de commande des applications web](app-service-cli-samples.md) créés au préalable.
Markdown
UTF-8
4,587
3.09375
3
[ "0BSD" ]
permissive
--- title: JDSB Newsletter - Landing the Software Dev interview description: My thoughts on how to get called in date: 2020-11-12T18:52:51.159Z tags: - JDSB - Career published: true favorite: false --- I've a few conversations with community member recently about the frustration and distress of applying for positions and not being asked to interview. I wanted to share my thoughts on how to best handle this phase of the job hunting process. This is aimed at junior software developers looking to break into the industry, but I'm sure a lot of this could be applied to any job hunting situation. Intro - Focus on the Process 1. Identify your Audience and Message 2. Publish and Get Feedback 3. Polish ### Focus on the Process - We're going to talk philosophical before we talk concrete. Just how you went from knowing nothing about software development to a place where you're applying for professional software development roles, there's a lot you can learn and tweak to more easily land a first round interview. You won't learn it all by reading this blog post, but recognize that focusing your energy on the *process* of applying for jobs instead of on the end goal of landing a job, you will land interviews faster and have a better time doing it. The below section will outline individual parts of process. Note: Don't stop your job hunting as you apply this knowledge. Don't use this as an excuse to procrastinate on applying for positions. Apply this knowledge while continuing to send applications. ### Identify Your Audience and Message - At a recent meetup, there was a brief conversation regarding the frustration with rejection. A few people threw around the term "HR Gatekeepers", and expressed with great conviction that they'd be a great hire if they could only speak to an engineer. To this I say, HR reps who screen resumes are looking for the best candidates with whom to grow the company. There's no personal vendetta, but they have skin in the game. There is liability in passing on someone to the engineering team who doesn't meet a minimum requirement, since the HR rep would be pulling engineers away from their product work. So - you need to tailor your message to speak to the HR reps. Present yourself as excited and hungry to learn/build. My message was more or less "**I have no professional industry experience, but I'm very excited about software development, I'm an effective builder and a quick learner.**" My message wasn't "I know what I need to know", but "I'll learn it quickly and bring a fresh perspective." Feel free to use my message as yours, if you can back it up. Once you've identified your message, tailor everything all of your outward facing communication (resume, [website](https://natespilman.com/blog/all-junior-web-developers-should-have-personal-websites/), LinkedIn posts, etc) to deliver and confirm that message. If you just graduated from a bootcamp, you're not going to convince anyone that you're an industry worn developer. "This person is hungry to learn." is a liability-free reason for an HR rep to pass on to the dev team. ### Publish and Get Feedback One way to show HR that you're a safer bet is a steady history of published work. Published work can include blogposts, projects, code samples, etc. As I stated in my previous post, [all apply for dev jobs should have their own website](https://natespilman.com/blog/all-junior-web-developers-should-have-personal-websites/). At least, it's a major leg up. This site can then be used to publish your projects, writings, etc, for an HR rep/dev manager to easily find. Get feedback as often as you can on your published work. JDSB meetups are the perfect forum for this. Ask for feedback on your website. As for feedback on your resume. Ask for feedback on your projects. Feedback is your friend. Feedback on your resume doesn't reflect on who you are as a person. In a way, constructive feedback is a form of love and care. Receive it as such. ### Polish Take that feedback and bake it back into your work. Take feedback from the process and bake it back into the process. Publish and get feedback. Rinse, repeat. Make those small but meaningful refactors to better tell your audience that you're hungry and competent. This feedback loop should always give you something to work on, so you won't be too hung up on each individual application. Each individual application is far less important then your consistent focus on the process of applying. \----------- Thanks for reading. That's all for now. Happy applying - Nate
C
UTF-8
518
3.859375
4
[]
no_license
#include <stdio.h> #include "fonction7.h" #include <stdbool.h> void fonction7() { int nb; printf("Veuillez saisir un nombre: "); scanf("%d", &nb); entier(nb); multiple(nb); divisible(nb); } void entier(int nb) { if(nb % 2 == 0) { printf("Il est pair \n"); } } void multiple(int nb) { if(nb % 3 == 0) { printf("Il est multiple de 3 \n"); } } void divisible( int nb) { if(nb % 6 == 0) { printf("Il est divisible par 6 \n"); } }
Java
UTF-8
2,385
2.078125
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2016 The Simple File Server Authors * * 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 org.sfs.nodes.all.segment; import io.vertx.core.logging.Logger; import org.sfs.vo.TransientBlobReference; import org.sfs.vo.TransientSegment; import rx.functions.Func1; import java.util.Iterator; import static io.vertx.core.logging.LoggerFactory.getLogger; public class PruneDeletedBlobs implements Func1<TransientSegment, Boolean> { private static final Logger LOGGER = getLogger(PruneDeletedBlobs.class); @Override public Boolean call(TransientSegment transientSegment) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("begin prunedeletedblobs object=" + transientSegment.getParent().getParent().getId() + ", version=" + transientSegment.getParent().getId() + ", segment=" + transientSegment.getId()); } Iterator<TransientBlobReference> blobIterator = transientSegment.getBlobs().iterator(); boolean modified = false; while (blobIterator.hasNext()) { TransientBlobReference blob = blobIterator.next(); if (blob.isDeleted()) { blobIterator.remove(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("removed prunedeletedblobs object=" + blob.getSegment().getParent().getParent().getId() + ", version=" + blob.getSegment().getParent().getId() + ", segment=" + blob.getSegment().getId() + ", volume=" + blob.getVolumeId() + ", position=" + blob.getPosition()); } modified |= true; } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("end prunedeletedblobs object=" + transientSegment.getParent().getParent().getId() + ", version=" + transientSegment.getParent().getId() + ", segment=" + transientSegment.getId()); } return modified; } }
Markdown
UTF-8
678
2.59375
3
[]
no_license
# what data should you be using to calculate the encodings based on stats These encodings are all based on statistics calculated from the dataset like counts and means. Considering this, what data should you be using to calculate the encodings? - Count Encoding - Target Encoding - Leave-one-out Encoding - CatBoost Encoding - Feature embedding with SVD You should calculate the encodings **from the training set only**. If you include data from the validation and test sets into the encodings, you'll overestimate the model's performance. You should in general be vigilant to avoid leakage, that is, including any information from the validation and test sets into the model.
Java
UTF-8
2,330
2.03125
2
[]
no_license
package com.icts.shortfilmfestival.tabgroup; import java.util.ArrayList; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.GridView; import com.icts.shortfilmfestival.adapter.AppsAdapter; import com.icts.shortfilmfestival.entity.AppsEntity; import com.icts.shortfilmfestival.inf.ISettings; import com.icts.shortfilmfestival_en.MainTabActivity; import com.vnp.shortfilmfestival.R; public class AppsTab extends Activity implements OnItemClickListener{ private GridView mGridView; private ArrayList<AppsEntity> mAppsArrayList; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.list_apps); mGridView = (GridView) findViewById(R.id.gridview); mGridView.setOnItemClickListener(this); mAppsArrayList = new ArrayList<AppsEntity>(); for (int i = 0; i < ISettings.LIST_APPS.length; i++) { String strItem =ISettings.LIST_APPS[i]; String[] arrayItem = strItem.split("_"); AppsEntity mAppsEntity = new AppsEntity(); mAppsEntity.setmName(arrayItem[0]); mAppsEntity.setmImage(ISettings.LIST_LOGO_APP[i]); if (ISettings.LANGUAGE.equals("ja")) { mAppsEntity.setmDesc(arrayItem[2]); } else if (ISettings.LANGUAGE.equals("en")) { mAppsEntity.setmDesc(arrayItem[3]); } Log.d("Apps",mAppsEntity.getmDesc()); mAppsEntity.setmPrice(arrayItem[4]); mAppsEntity.setUrl(arrayItem[5]); mAppsArrayList.add(mAppsEntity); } AppsAdapter mAppsAdapter = new AppsAdapter(this, mAppsArrayList); mGridView.setAdapter(mAppsAdapter); } public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { final Intent intent = new Intent(Intent.ACTION_VIEW).setData(Uri.parse(mAppsArrayList.get(position).getUrl())); startActivity(intent); } protected void onResume() { // TODO Auto-generated method stub super.onResume(); MainTabActivity.isFromApps = false; } protected void onDestroy() { // TODO Auto-generated method stub System.gc(); super.onDestroy(); } }
C++
UTF-8
745
2.640625
3
[]
no_license
#include "DialogBox.h" #include <gtkmm/stock.h> #include <gtkmm/entry.h> #include <iostream> using namespace std; DialogBox::DialogBox(Gtk::Window & parentWindow, string title, string message) : Dialog( title, parentWindow, true, true ) { Gtk::Label messageLabel(message); // Obtain the dialog box's vertical alignment box. Gtk::VBox* contentArea = this->get_vbox(); contentArea->pack_start( messageLabel, Gtk::PACK_SHRINK, true, false ); // Add a standard "ok" buttons_ with the appropriate responses when clicked. Gtk::Button * okButton = add_button( Gtk::Stock::OK, Gtk::RESPONSE_OK); show_all_children(); // Wait for a response from the dialog box. int result = run(); switch (result) { case Gtk::RESPONSE_OK: break; } }
PHP
UTF-8
1,390
3.40625
3
[]
no_license
<?php class Aluno { public $matricula; public $nome; private $n1; private $n2; private $t1; public $media; public function getN1() { return $this->n1; } public function getN2() { return $this->n2; } public function getT1() { return $this->t1; } public function setN1($n1) { $this->n1 = $n1; } public function setN2($n2) { $this->n2 = $n2; } public function setT1($t1) { $this->t1 = $t1; } public function Media() { $n1 = $this->n1; $n2 = $this->n2; $t1 = $this->t1; $notafinal = (($n1 * 3.5) + ($n2 * 3.5) + ($t1 * 3)); $this->media = $notafinal; if ($notafinal >= 70) { return "Situação: Aprovado"; } if ($notafinal >= 0 && $notafinal < 70) { return "Situação: Reprovado"; } } public function imprime(){ echo "<br>"; echo "Matrícula: " . $this->matricula . "<br>"; echo "Nome: " . $this->nome . "<br>"; echo "Primeira prova: " . $this->n1 . "<br>"; echo "Segunda Prova: " . $this->n2 . "<br>"; echo "Trabalho: " . $this->t1 . "<br>"; echo "Nota Final: " . $this->media . "<br>"; echo $this->Media() . "<br><br>"; echo "<hr>"; } } ?>
Python
UTF-8
3,229
2.953125
3
[]
no_license
import codecs import re import numpy as np from config import BATCH_SIZE as batch_size from config import TIME_STEPS as time_steps from sklearn.preprocessing import OneHotEncoder # =============== 读取文本内容 =============== f = codecs.open('./data/new.txt', 'r', encoding='utf-8') data = f.readlines() # data = ''.join(data) #=============== 简单的预处理 =============== # 替换括号里的内容 pattern = re.compile(r'\(.*?\)') data = [pattern.sub('', line) for line in data] # 删除\n, \r,' ' data = [word.replace('.', '。') for word in data] data = [word.replace('\r', '') for word in data] # data = [word.replace(' ', '') for word in data] # 删除章节名称 pattern = re.compile(r'.*?第.*?章.*') def isNotChapterName(text): if pattern.search(text): return False else: return True data = [word for word in data if isNotChapterName(word)] # 省略号 => . data = [line.replace('……', '。') for line in data if len(line) > 1] # ==============判断char是否是乱码=================== def is_uchar(uchar): """判断一个unicode是否是汉字""" if uchar >= u'\u4e00' and uchar<=u'\u9fa5': return True """判断一个unicode是否是数字""" if uchar >= u'\u0030' and uchar<=u'\u0039': return True """判断一个unicode是否是英文字母""" if (uchar >= u'\u0041' and uchar<=u'\u005a') or (uchar >= u'\u0061' and uchar<=u'\u007a'): return True if uchar in (',','。',':','?','“','”','!',';','、','《','》','——'): return True return False # 将每行的list合成一个长字符串 data = ''.join(data) data = [char for char in data if is_uchar(char)] data = ''.join(data) # ==============生成字典=============== vocab = set(data) id2char = {i:c for i,c in enumerate(vocab)} char2id = {c:i for i,c in enumerate(vocab)} # 总数 VOCAB_NUM = len(id2char) # =====转换数据为数字格式====== numdata = [char2id[char] for char in data] numdata = np.array(numdata) batch_num = len(numdata) // (batch_size * time_steps) # print(numdata.shape) # print('数字数据信息:\n', numdata[:100]) # print('\n文本数据信息:\n', ''.join([id2char[i] for i in numdata[:100]])) # print(len(numdata)) # ============= 定义 dataloader ============= def yield_data( batch_size, time_step, data= numdata): encoder = OneHotEncoder(categories= [range(VOCAB_NUM)]) start = [i * time_step for i in range(batch_size)] end = [(i+1) * time_step for i in range(batch_size)] data_num = batch_size * time_step batch_num = len(data) // data_num arr = data[:data_num * batch_num] arr_y = np.roll(arr,-1) arr = arr.reshape((batch_size, -1)) arr_y = arr_y.reshape((batch_size, -1)) for i in range(0,arr.shape[1], time_step): x = arr[:,i:i + time_step].reshape((batch_size, -1)) x = encoder.fit_transform(x.reshape(-1,1)).toarray().reshape(x.shape[0], x.shape[1], -1) y = arr_y[:,i:i + time_step].reshape((batch_size, -1)) yield (np.array(x, dtype= np.float),y) if __name__ == '__main__': data = yield_data(128,100) for x,y in data: break print(x.shape) print(y.shape)
Markdown
UTF-8
1,154
2.875
3
[]
no_license
--- layout: post title: "MySQL Integer Spickzettel" date: 2008-06-26 11:19:06 comments: true categories: MySQL --- So damit ich es mir endlich mal merke und nicht jedes mal nach schauen muss habe ich hier mal die 5 Integer Felder der MySQL Datenbank in einer Kurzzusammenfassung zusammengestellt mit Namen, dem Wertebereich für Vorzeichen behaftet (signed) und ohne Vorzeichen (unsigned). #### TINYINT Größe: 8 Bit signed: von -128 bis 127 unsigned: von 0 bis 255 #### SMALLINT Größe: 16 Bit signed: von -32768 bis 32767 unsigned: von 0 bis 65535 #### MEDIUMINT Größe: 24 Bit signed: von -8388608 bis 8388607 unsigned: von 0 bis 16777215 #### INT oder INTEGER Größe: 32 Bit signed: von -2147483648 bis 2147483647 unsigned: von 0 bis 4294967295 #### BIGINT Größe: 64 Bit signed: von -9223372036854775808 bis 9223372036854775807 unsigned: von 0 bis 18446744073709551615 Arithmetische Funktionen sollte nicht auf BIGINTs die selbst größer 63 Bit (9223372036854775807) sind oder deren Ergebnisse größer der besagten 63 Bit sind angewendet werden, da sonst Rundungsfehler auftreten können ,da MySQL dann mit DOUBLE werten arbeitet
C++
UTF-8
735
2.53125
3
[]
no_license
#include "../include.h" void facade_setup(); void facade_run(); void facade_clean(); // demo codes for facade design pattern // the child system has a lot of module and different APIs class screen{ public: void screen_on(); void screen_off(); }; class mainboard{ public: void mainboard_on(); void mainboard_off(); }; class fan{ public: void fan_on(); void fan_off(); }; class otherDevices{ public: void otherDevices_on(); void otherDevices_off(); }; // the facade to hold all the child system part and support the main APIs class computer{ public: void computer_on(); void computer_off(); computer(); ~computer(); private: screen* m_screen; mainboard* m_mainboard; fan* m_fan; otherDevices* m_otherDevices; };
C++
UTF-8
4,151
2.625
3
[]
no_license
#include <string> #include <bits/stdc++.h> #include <Eigenvalues> #include <cstring> #include "PCAHeaders.cpp" #include <time.h> using namespace Eigen; using namespace std; std::vector< std::vector<double> > A,MCD; int main(int argc, char const *argv[]) { //==============taking input from file and feeding it to matrix===============================// // if(argc == 1){ // cout<<"\n=========== ENTER DATA FILE NAME ==============\n\n"; // cout<<" <<<<<< FORMAT >>>> : ./EXE FILENAME.TXT"<<endl<<endl; // return 0; // } // A = extractData(argv[1]); int cap = 1024*1024; for (int i = 0; i <1024 ; ++i) { std::vector<double> temp; for (int j = 0; j < 1024; ++j) { /* code */ temp.push_back(i*1024+j); } A.push_back(temp); } int rows = A.size(); int cols = A[0].size(); //=================Now finding mean of given matrix taking each column as one sample=============// vector<std::vector<double> >mean; clock_t meanStart = clock(); cout<<"making data mean centred..."<<endl; mean = calculateMean(A, rows, cols); // for (int i = 0; i < mean.size(); ++i) // { // /* code */ // cout<<mean[i][0]<<" "; // } //=================mean centering data=============================================================// MCD = subtractMean(A,mean,A.size(),A[0].size()); printf("time taken for making data mean centred: %.2fs\n", (double)(clock() - meanStart)/CLOCKS_PER_SEC); //testing(MCD,MCD.size(),MCD[0].size()); //=========computing covariance matrix multiplying rowwise without taking transpose================// clock_t covStart = clock(); cout<<"making co-variance matrix..."<<endl; std::vector<std::vector<double> > covMatrix(rows,std::vector<double>(rows,0.0)); for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols ; ++j) { double temp =0; for (int k = 0; k < rows; ++k) { temp+=MCD[k][i]*MCD[k][j]; } covMatrix[i][j] = double(temp)/(rows-1); } } printf("time taken for making co-variance matrix: %.2fs\n", (double)(clock() - covStart)/CLOCKS_PER_SEC); //========putting data to matrix to find eigen values using eigen package===========================// int r = covMatrix.size(); int c = covMatrix[0].size(); MatrixXd Data(r,c); // for (int i = 0; i < r; ++i) // { // for (int j = 0; j < c; ++j) // { // Data(i,j) = covMatrix[i][j]; // } // } //============computing eigen values and eigen vectors=============================================// clock_t eigStart = clock(); cout<<"finding eigen values and vectors of co-variance matrix..."<<endl; EigenSolver<MatrixXd> es(Data); es.compute(Data,true); MatrixXd eigenvalues = es.pseudoEigenvalueMatrix(); MatrixXd eigenvectors = es.pseudoEigenvectors(); printf("time taken for finding eigen values & eigen vectors: %.2fs\n", (double)(clock() - eigStart)/CLOCKS_PER_SEC); std::vector<double> ev,eigvalues; std::vector<int> eigPos; std::vector<double>::iterator it; //===============separating eigen values from matrix=========================// for (int i = 0; i < r; ++i) { ev.push_back(eigenvalues(i,i)); eigvalues.push_back(eigenvalues(i,i)); } sort(ev.begin(),ev.end(),std::greater<double>()); //======finding eigen positions===========================// for (int i = 0; i < r; ++i) { it = find(eigvalues.begin(),eigvalues.end(),ev[i]); eigPos.push_back(it-eigvalues.begin()); } std::vector<std::vector<double> > pca(r,std::vector<double>(c,0.0)),Y; for (int i = 0; i < eigenvectors.cols(); ++i) { for (int j = 0; j < eigenvectors.rows() ; ++j) { pca[j][i] = eigenvectors.col(eigPos[i])[j]; } } cout<<"\n\n===================TRANSPOSED PCA Running=================\n"<<endl; //testing(pca,pca.size(),1); clock_t mm2Start = clock(); cout<<"projecting data..."<<endl; Y = matMul(MCD,pca,MCD[0].size(),pca[0].size(),pca.size()); //cout<<"\n\n====================PROJECTED DATA================\n"<<endl; printf("time taken for projecting: %.2fs\n", (double)(clock() - mm2Start)/CLOCKS_PER_SEC); //testing(Y,Y.size(),1); cout<<endl; cout<<"\n\n===================================================\n"<<endl; return 0; }
Java
UTF-8
1,038
3.46875
3
[]
no_license
package ru.downwine._2_SecondLab.Ex3; import java.util.Scanner; public class Main { public static void main(String[] args) { System.out.println("Введите цвет книги, автора книги, название книги, " + "количество страниц, высоту книги, ширину книги"); Scanner in = new Scanner(System.in); String bookColor = in.next(), bookAuthor = in.next(), bookTitle = in.next(); int bookPages = in.nextInt(), bookHeight = in.nextInt(), bookWidth = in.nextInt(); Book book = new Book(bookAuthor, bookColor, bookTitle, bookWidth, bookHeight, bookPages); System.out.println(book); System.out.println("Введите нового автора: "); bookAuthor = in.next(); book.setAuthor(bookAuthor); System.out.println("Введите новое название: "); bookTitle = in.next(); book.setTitle(bookTitle); System.out.println(book); } }
Python
UTF-8
1,975
2.625
3
[ "Apache-2.0" ]
permissive
"""Models for statistics in the Recorder.""" from __future__ import annotations from datetime import datetime, timedelta from typing import Literal, TypedDict class StatisticResult(TypedDict): """Statistic result data class. Allows multiple datapoints for the same statistic_id. """ meta: StatisticMetaData stat: StatisticData class StatisticDataTimestampBase(TypedDict): """Mandatory fields for statistic data class with a timestamp.""" start_ts: float class StatisticDataBase(TypedDict): """Mandatory fields for statistic data class.""" start: datetime class StatisticMixIn(TypedDict, total=False): """Mandatory fields for statistic data class.""" state: float sum: float min: float max: float mean: float class StatisticData(StatisticDataBase, StatisticMixIn, total=False): """Statistic data class.""" last_reset: datetime | None class StatisticDataTimestamp(StatisticDataTimestampBase, StatisticMixIn, total=False): """Statistic data class with a timestamp.""" last_reset_ts: float | None class StatisticMetaData(TypedDict): """Statistic meta data class.""" has_mean: bool has_sum: bool name: str | None source: str statistic_id: str unit_of_measurement: str | None class CalendarStatisticPeriod(TypedDict, total=False): """Statistic period definition.""" period: Literal["hour", "day", "week", "month", "year"] offset: int class FixedStatisticPeriod(TypedDict, total=False): """Statistic period definition.""" end_time: datetime start_time: datetime class RollingWindowStatisticPeriod(TypedDict, total=False): """Statistic period definition.""" duration: timedelta offset: timedelta class StatisticPeriod(TypedDict, total=False): """Statistic period definition.""" calendar: CalendarStatisticPeriod fixed_period: FixedStatisticPeriod rolling_window: RollingWindowStatisticPeriod
PHP
UTF-8
2,630
2.703125
3
[ "MIT" ]
permissive
<?php /** * Created by Noman Tufail. * User: waqas * Date: 3/21/2016 * Time: 9:22 AM */ namespace App\Http\Validators\Validators\UserValidators; use App\Http\Requests\Requests\Auth\RegistrationRequest; use App\Http\Validators\Interfaces\ValidatorsInterface; class AddUserValidator extends UserValidator implements ValidatorsInterface { /** * @param RegistrationRequest $request */ public function __construct(RegistrationRequest $request){ parent::__construct($request); $this->request = $request; } public function CustomValidationMessages(){ $termsConditionsMessage ='Dear user you must agree our terms and conditions'; return [ 'required.required' => ':attribute is required', 'fName.required' => 'First name is required', 'lName.required' => 'Last name is required', 'passwordAgain.required' => 'Password Again is required', 'phone.required' => 'Phone is required', 'userRoles.required' => 'User roles is required', 'securityCode.required' => 'Security code is required', 'termsConditions.required' => $termsConditionsMessage, 'termsConditions.equals' => $termsConditionsMessage, /* Agency messages */ 'agencyName.required' => 'Agency name is required', 'companyPhone.required' => 'Company phone is required', 'companyAddress.required' => 'Company address is required', 'companyEmail.required' => 'Company email is required' ]; } public function userRules() { return [ 'fName' => 'required', 'lName' => 'required', 'email' => 'required|email|unique:users,email|max:255', 'password' => 'required', 'passwordAgain' => 'required', 'phone' => 'required', 'userRoles' => 'required', 'securityCode' => 'required', 'termsConditions' => 'required|equals:1' ]; } public function agencyRules() { return [ 'agencyName' => 'required|unique:agencies,agency|max:255', 'companyPhone' => 'required|max:15', 'companyAddress' => 'required|max:225', 'companyEmail' => 'required|email|unique:agencies,email|max:255', ]; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return ($this->request->userIsAgent())?array_merge($this->userRules(),$this->agencyRules()):$this->userRules(); } }
Java
UTF-8
1,073
2.3125
2
[]
no_license
package cn.xlink.data.query.builder.json; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** * Created by Ghold on 2017/7/21. */ public class OrDimFilter implements DimFilter, Comparable{ @JsonProperty("type") private String type = "or"; @JsonProperty("fields") private List<DimFilter> fields; public OrDimFilter(List<DimFilter> fields) { this.fields = fields; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; OrDimFilter that = (OrDimFilter) o; if (!type.equals(that.type)) return false; return fields.equals(that.fields); } @Override public int hashCode() { int result = type.hashCode(); result = 31 * result + fields.hashCode(); return result; } @Override public int compareTo(Object o) { if (this.hashCode() >= o.hashCode()) { return 1; } else { return -1; } } }
Java
UTF-8
653
3
3
[]
no_license
package mentoring.JUNITTEST.J; public class main { public char lastCharacter(String str){ return str.charAt( str.length()-1); } //ARRAYIN MAX ELEMANININ BULMAK public int maxNumberArray (int []arr){ int max=0; for (int i = 0; i <arr.length ; i++) { if (max<arr[i]){ max=arr[i]; } } return max; } // faktoriyel bulma metodu yazalim ve test edelim; public int factorial(int num) { int faktoriyel=1; while(num>0){ faktoriyel=faktoriyel*num; num--; } return faktoriyel; } }
Java
UTF-8
4,376
2.203125
2
[]
no_license
package com.example.volunteer_matching; import android.annotation.SuppressLint; import android.graphics.Point; import android.support.v4.app.FragmentActivity; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.Toast; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.MapsInitializer; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; public class PositionActivity extends FragmentActivity implements GoogleMap.OnMapClickListener, OnMapReadyCallback { private GoogleMap mGoogleMap; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Toast.makeText(getApplicationContext(), "k",Toast.LENGTH_SHORT).show(); setContentView(R.layout.activity_position); Toast.makeText(getApplicationContext(), "a",Toast.LENGTH_SHORT).show(); // BitmapDescriptorFactory 생성하기 위한 소스 MapsInitializer.initialize(getApplicationContext()); Toast.makeText(getApplicationContext(), "b",Toast.LENGTH_SHORT).show(); MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map); Toast.makeText(getApplicationContext(), "c",Toast.LENGTH_SHORT).show(); mapFragment.getMapAsync(this); Toast.makeText(getApplicationContext(), "d",Toast.LENGTH_SHORT).show(); init(); Toast.makeText(getApplicationContext(), "e",Toast.LENGTH_SHORT).show(); } /** Map 클릭시 터치 이벤트 */ public void onMapClick(LatLng point) { // 현재 위도와 경도에서 화면 포인트를 알려준다 Point screenPt = mGoogleMap.getProjection().toScreenLocation(point); // 현재 화면에 찍힌 포인트로 부터 위도와 경도를 알려준다. LatLng latLng = mGoogleMap.getProjection().fromScreenLocation(screenPt); Log.d("맵좌표", "좌표: 위도(" + String.valueOf(point.latitude) + "), 경도(" + String.valueOf(point.longitude) + ")"); Log.d("화면좌표", "화면좌표: X(" + String.valueOf(screenPt.x) + "), Y(" + String.valueOf(screenPt.y) + ")"); } /** * 초기화 * @author */ private void init() { GooglePlayServicesUtil.isGooglePlayServicesAvailable(PositionActivity.this); // 맵의 이동 //mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 15)); GpsInfo gps = new GpsInfo(PositionActivity.this); // GPS 사용유무 가져오기 if (gps.isGetLocation()) { double latitude = gps.getLatitude(); double longitude = gps.getLongitude(); // Creating a LatLng object for the current location LatLng latLng = new LatLng(latitude, longitude); // Showing the current location in Google Map mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); // Map 을 zoom 합니다. mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(13)); // 마커 설정. MarkerOptions optFirst = new MarkerOptions(); optFirst.position(latLng);// 위도 • 경도 optFirst.title("Current Position");// 제목 미리보기 optFirst.snippet("Snippet"); optFirst.icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher)); mGoogleMap.addMarker(optFirst).showInfoWindow(); } } @SuppressLint("MissingPermission") @Override public void onMapReady(GoogleMap googleMap) { mGoogleMap = googleMap; googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); googleMap.setMyLocationEnabled(true); googleMap.setTrafficEnabled(true); googleMap.setIndoorEnabled(true); googleMap.setBuildingsEnabled(true); googleMap.getUiSettings().setZoomControlsEnabled(true); } }
Python
UTF-8
552
3.25
3
[]
no_license
# -*- coding: utf-8 -*- # @Author: Xia Hanyu (Humprey Chou) # @Date: 2021-01-19 10:48:47 # @Last Modified by: Xia Hanyu (Humprey Chou) # @Last Modified time: 2021-01-25 21:52:49 def Extend_Euclid(x, y): """ Args: x ([type]): [description] y ([type]): [description] Returns: [type]: [description] >>> Extend_Euclid(11, 6) (1, -1, 2) """ assert isinstance(x, int) assert x >= 0 if y == 0: return (x, 1, 0) else: (d, a, b) = Extend_Euclid(y, x % y) return (d, b, a - (x // y) * b)
Java
UTF-8
1,207
1.640625
2
[]
no_license
package app.component.cus.feign; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import app.component.cus.entity.MfCusReputationInfo; import app.util.toolkit.Ipage; /** * Title: MfCusReputationInfoBo.java * Description: * @author:kaifa@dhcc.com.cn * @Fri Aug 18 10:27:55 CST 2017 **/ @FeignClient("mftcc-platform-factor") public interface MfCusReputationInfoFeign { @RequestMapping("/mfCusReputationInfo/insert") public void insert(@RequestBody MfCusReputationInfo mfCusReputationInfo) throws Exception; @RequestMapping("/mfCusReputationInfo/delete") public void delete(@RequestBody MfCusReputationInfo mfCusReputationInfo) throws Exception; @RequestMapping("/mfCusReputationInfo/update") public void update(@RequestBody MfCusReputationInfo mfCusReputationInfo) throws Exception; @RequestMapping("/mfCusReputationInfo/getById") public MfCusReputationInfo getById(@RequestBody MfCusReputationInfo mfCusReputationInfo) throws Exception; @RequestMapping("/mfCusReputationInfo/findByPage") public Ipage findByPage(@RequestBody Ipage ipage) throws Exception; }
C#
UTF-8
471
3
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MSPractice { class ExcelSheetName { public string ConvertToTitle(int n) { string result = ""; while (n > 0) { n--; result = Convert.ToChar('A' + n % 26)+result; n = n / 26; } return result; } } }
Ruby
UTF-8
1,345
2.625
3
[]
no_license
# frozen_string_literal: true class Seed def self.begin seed = Seed.new User.delete_all Project.destroy_all ProjectsUser.destroy_all Post.destroy_all seed.generate_users seed.generate_projects seed.add_users_to_projects seed.add_project_owners seed.add_posts_to_projects end def generate_projects 20.times do @project = Project.create!(title: Faker::Commerce.department, description: Faker::Lorem.sentence(25)) end end def generate_users 40.times do @name = Faker::Name.unique.name User.create!(name: @name, email: Faker::Internet.free_email(@name), password: 'password') end end def add_users_to_projects 100.times do @project = Project.all.sample @user = User.all.sample if @user.projects.include?(@project) else @user.projects << @project end end end def add_project_owners for project in Project.all do @assigned_user = User.all.sample project.update(owner: @assigned_user.id) end end def add_posts_to_projects for user in User.all do for project in user.projects do 2.times do Post.create(title: Faker::Hipster.sentence(5), comment: Faker::Lorem.paragraph(5), user: user, project: project) end end end end end Seed.begin
JavaScript
UTF-8
741
2.625
3
[]
no_license
import axios from "../../../axios"; import { FETCH_USER_DETAILS } from '../../Types'; export const storeUserDetails = userDetails => { return { type: FETCH_USER_DETAILS, userDetails }; }; export const fetchUserDetails = id => (dispatch, getState) => { const token = getState().userReducer.currentUser.token; const userID = id const myConfig = { headers: { Authorization: `Bearer ${token}` } }; return axios.get(`api/users/${userID}`, myConfig) .then(response => { const userDetails = response.data; dispatch(storeUserDetails(userDetails)); }) .catch(error => { console.log('ERROR', error); }); };
Java
UTF-8
1,282
3.203125
3
[ "MIT" ]
permissive
package file; import java.awt.Color; import java.awt.Graphics; import java.awt.image.BufferedImage; public class Image_Layer extends Layer{ public BufferedImage image; public Image_Layer(int width, int height, int imageType, String nameT, Img mother_image) { super(width, height, imageType, nameT, mother_image); image=new BufferedImage(width,height, BufferedImage.TYPE_INT_ARGB); Graphics g=image.getGraphics(); g.setColor(Color.white); g.fillRect(0, 0, width, height); } @Override public void setTransparency(int t) { super.setTransparency(t); int alpha = t; for (int cx=0;cx<image.getWidth();cx++) { for (int cy=0;cy<image.getHeight();cy++) { int rgb = image.getRGB(cx, cy); Color color = new Color(rgb); color = new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha); image.setRGB(cx, cy, color.getRGB()); } } } @Override public void set_image(BufferedImage new_image) { super.set_image(new_image); image=new_image; } @Override public BufferedImage get_image() { return image; } @Override public void draw(Graphics g, int x, int y, int w, int h) { g.drawImage(image, x, y, w, h, null); } }
JavaScript
UTF-8
181
2.578125
3
[]
no_license
"use strict"; const doShortly = function(callback, delay, data) { setTimeout(() => { callback(data); }, delay); }; // Don't change below: module.exports = { doShortly };
Swift
UTF-8
2,444
2.65625
3
[ "MIT", "Apache-2.0" ]
permissive
// // AddToLibraryViewController.swift // AAPhotoLibrary // // Created by Armen Abrahamyan on 5/8/16. // Copyright © 2016 Armen Abrahamyan. All rights reserved. // import UIKit import Photos class AddToLibraryViewController: UIViewController { var currentCell: NewAssetImageCell? var currentPage:Int = 0 @IBOutlet weak var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func saveImage(_ sender: AnyObject) { if currentCell == nil { currentCell = collectionView.cellForItem(at: IndexPath(row: 0, section: 0)) as? NewAssetImageCell } if let cell = currentCell { PHPhotoLibrary.addNewImage("AAPhotoLibrary", image: cell.imageView.image!, completion: { (success, error) in if error != nil { print("Success = \(success)") } }) } } } extension AddToLibraryViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 5 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "newAssetCell", for: indexPath) as! NewAssetImageCell cell.imageView.image = UIImage(named: "\((indexPath as NSIndexPath).row)") return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width) } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { let pageWidth = collectionView.frame.size.width currentPage = Int(collectionView.contentOffset.x / pageWidth) currentCell = collectionView.cellForItem(at: IndexPath(row: currentPage, section: 0)) as? NewAssetImageCell } }
Swift
UTF-8
2,672
2.65625
3
[]
no_license
// // CustomNavigationAnimationController.swift // TransitionsTutorial // // Created by admin on 9/4/18. // Copyright © 2018 cuongnv. All rights reserved. // import UIKit class CustomNavigationAnimationController: NSObject, UIViewControllerAnimatedTransitioning { var reverse: Bool = false func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 1.5 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView let toViewControler = transitionContext.viewController(forKey: .to)! let fromViewControler = transitionContext.viewController(forKey: .from)! let toView = toViewControler.view let fromView = fromViewControler.view let dicrection: CGFloat = reverse ? -1 : 1 let const: CGFloat = -0.005 toView?.layer.anchorPoint = CGPoint(x: dicrection == 1 ? 0 : 1, y: 0.5) fromView?.layer.anchorPoint = CGPoint(x: dicrection == 1 ? 1 : 0, y: 0.5) var viewFromTransform: CATransform3D = CATransform3DMakeRotation(dicrection*CGFloat(Double.pi / 2), 0.0, 1.0, 0.0) var viewToTransform: CATransform3D = CATransform3DMakeRotation(-dicrection*CGFloat(Double.pi / 2), 0.0, 1.0, 0.0) viewFromTransform.m34 = const viewToTransform.m34 = const containerView.transform = CGAffineTransform(translationX: dicrection * containerView.frame.size.width / 2.0, y: 0) toView?.layer.transform = viewToTransform containerView.addSubview(toView!) UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { containerView.transform = CGAffineTransform(translationX: -dicrection * containerView.frame.size.height / 2, y: 0.0) fromView?.layer.transform = viewFromTransform toView?.layer.transform = CATransform3DIdentity }) { (finished) in containerView.transform = CGAffineTransform.identity fromView?.layer.transform = CATransform3DIdentity toView?.layer.transform = CATransform3DIdentity fromView?.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5) toView?.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5) if (transitionContext.transitionWasCancelled) { toView?.removeFromSuperview() }else{ fromView?.removeFromSuperview() } transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } } }
JavaScript
UTF-8
2,011
3.90625
4
[ "MIT" ]
permissive
/** * Partition logic work in following way. It takes low and high value from array * Then take first element as the pivoted element. Then iterating through * the array to check i-th value is greater than pivot then it get stopped. * The same way decrement j from the right side to check any values less than * pivot value. If this two get stoped then interchanged the elements(i-th and j-th), Untill j value * crosses i value. Once this happen j-th position replaced with pivot value and jth * value move to pivot indexs. Now the pivot value in sorted position. All from left * is less than pivot value and all element from right are greater than pivot but not * guarentee than its sorted. The some process get repeated recursevely to sort the array */ class QuickSort { constructor(dataArr) { this.arrData = dataArr; this.low = 0; this.high = dataArr.length; this.doSort(this.low, this.high); } // To perform sorting based on divide and conquer approch doSort(low, high) { if(low < high) { let sortedPos = this.partition(low, high); low < sortedPos -1 ? this.doSort(low , sortedPos) : ''; high > sortedPos ? this.doSort(sortedPos + 1, high) : ''; } else { //console.log(this.arrData); } } // To perform recursive partition partition(low, high) { let arrData = this.arrData, pivotVal = arrData[low], i = low, j = high, pivotPos = low; //console.log('pivot value::'+ pivotVal); while( i<j ) { // i loop stops when an element less than pivot value do { i++; } while(arrData[i] < pivotVal) // j loop stops when an element greater than pivot value do { j--; } while(arrData[j] > pivotVal) if(i < j) { //console.log('Value interchanged::i val '+ arrData[i] + ' j val '+arrData[j]); let temp = arrData[j]; arrData[j] = arrData[i]; arrData[i] = temp; } } let temp = arrData[j]; arrData[j] = pivotVal; arrData[pivotPos] = temp; //console.log('After change::'+ arrData) return j; } }
Rust
UTF-8
366
3.296875
3
[ "Apache-2.0", "LLVM-exception", "NCSA", "BSD-2-Clause", "LicenseRef-scancode-unicode", "MIT", "LicenseRef-scancode-other-permissive" ]
permissive
use std::fmt::Debug; // Test to suggest boxing the return type, and the closure branch of the `if` fn print_on_or_the_other<'a>(a: i32, b: &'a String) -> dyn Fn() + 'a { //~^ ERROR return type cannot have an unboxed trait object if a % 2 == 0 { move || println!("{a}") } else { Box::new(move || println!("{}", b)) } } fn main() {}
Markdown
UTF-8
1,847
4.15625
4
[]
no_license
### Destructuring: unpacking elements from an array or properties from an object and assigning to new variables 1. array destructuring 2. object destructuring if variables are in same count as values ``` const [a, b] = [1, 2]; console.log(a) // 1 console.log(b) // 2 ``` if variables are more than values ``` const [a, b] = [1]; console.log(a) // 1 console.log(b) // undefined ``` if variables are less than values ``` const [a, b] = [1, 2, 3]; console.log(a) // 1 console.log(b) // 2 ``` assigning after decleration ``` let a = 1, b = 2; [a, b] = [10, 20, 30]; console.log(a); // 10 console.log(b); // 20 ``` with default values ``` const [a = 1, b = 2] = [10, 20, 30]; console.log(a); // 10 console.log(b); // 20 ``` ``` const [a = 1, b = 2] = [10]; console.log(a); // 10 console.log(b); // 2 ``` with rest operator: ``` const [a, ...b] = [1, 2, 3, 4, 5]; console.log(a) // 1 console.log(b) // [2, 3, 4, 5] ``` ignoring elements: ``` const [a, , c] = [1, 2, 3]; console.log(a); // 1 console.log(c); // 3 ``` ### Object destructuring: ``` let emp = { name: 'Gopal', age: 20, }; const { name, age } = emp; console.log(name); // Gopal console.log(age); // 20 console.log(email); // Error: email is not defined ``` with spread operator: ``` let emp = { name: 'Gopal', age: 20, email: 'g@gmail.com', }; const { name, ...otherDetails } = emp; console.log(name); // Gopal console.log(otherDetails); // {age: 20, email: "g@gmail.com"} ``` ### combined (array + object destructing) ``` let employees = [ { name: 'Gopal', age: 20, email: 'g@gmail.com', }, { name: 'Ram', age: 10, email: 'r@gmail.com', }, { name: 'Siva', age: 20, email: 's@gmail.com', }, ]; const [gopal, , { name }] = employees; console.log(gopal); // {name: "Gopal", age: 20, email: "g@gmail.com"} console.log(name); // Siva ```
Java
UTF-8
4,852
1.976563
2
[]
no_license
package com.example.mysensorsapplication; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.Manifest; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.database.Cursor; import android.net.wifi.ScanResult; import android.net.wifi.WifiManager; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.OutputStreamWriter; import java.io.Serializable; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Date; import java.util.List; public class WifiActivity extends AppCompatActivity implements Serializable{ WifiManager wifiManager; WifiReceiver wifiReceiver; Button exportButton; List<ScanResult> myWifiList; List<String> list; TextView textView; DBManager manager; ListView listView; public transient Context context; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_wifi); // textView = (TextView)findViewById(R.id.wifiList); listView = (ListView) findViewById(R.id.wifilist); exportButton = (Button) findViewById(R.id.export); wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); wifiReceiver = new WifiReceiver(); registerReceiver(wifiReceiver,new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); if(ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},0); } else { scanWifiList(); } list = getPreviousWifiData(); exportButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { exportDataToFile(list); } }); } public void exportDataToFile(List<String> list) { FileOutputStream fos = null; try { fos = openFileOutput("WifiList.txt", Context.MODE_PRIVATE); ObjectOutputStream os = new ObjectOutputStream(fos); os.writeObject(list); os.close(); } catch (IOException e) { Log.e("Exception", "File write failed: " + e.toString()); } System.out.println(getFilesDir()+"/WifiList.txt"); Toast.makeText(this,"saved to"+getFilesDir()+"/WifiList.txt",Toast.LENGTH_SHORT).show(); } public List<String> getPreviousWifiData() { List<String> list = new ArrayList<String>(); manager = new DBManager(this); Cursor cursor = manager.getWifiData(); if(cursor.getCount() == 0) { Toast.makeText(this,"NO DATA",Toast.LENGTH_SHORT).show(); } else { while (cursor.moveToNext()) { String str = cursor.getString(0) +" "+ cursor.getString(1) +" " +cursor.getString(2); // Toast.makeText(this,str,Toast.LENGTH_SHORT).show(); list.add(str); } } ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.wifi_list_item, list); ListView listView = (ListView) findViewById(R.id.wifilist); listView.setAdapter(adapter); return list; } private void scanWifiList() { wifiManager.startScan(); String names = ""; long timestamp = 0; myWifiList = wifiManager.getScanResults(); System.out.println(myWifiList.get(0).SSID); for (int i=0; i<myWifiList.size(); i++) { names+=myWifiList.get(i).SSID+"\n"; } timestamp = myWifiList.get(0).timestamp; Date date = new Date(timestamp); insertIntoDB(names,date.toString()); } public void insertIntoDB(String names , String timestamp) { DBManager dbManager = new DBManager(this); String res = dbManager.addWifiRecord(names,timestamp); // Toast.makeText(this,res,Toast.LENGTH_LONG).show(); } class WifiReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { } } }
Python
UTF-8
1,236
3.296875
3
[]
no_license
# Flip stack from 0 to l as group def flip(stack, l): temp = stack[:l+1] temp.reverse() for i in xrange(l+1): stack[i] = 1 - temp[i] # flip def solve(stack): count = 0 n = len(stack) last_negative = n - 1 print 'start' print stack while last_negative >= 0: # update last_negative while last_negative >= 0 and stack[last_negative] == 1: last_negative -= 1 # if all set if last_negative < 0: return count # find first_negative first_negative = 0 while first_negative < n and stack[first_negative] == 1: first_negative += 1 # if all set (impossible) if first_negative >= n: return count if first_negative > 0: flip(stack, first_negative - 1) count += 1 flip(stack, last_negative) count += 1 print stack return count with open('pancake.in', 'r') as fin: with open('pancake.out', 'w') as fout: T = int(fin.readline()) for i in xrange(1, T+1): t = fin.readline() a = [0 if c == '-' else 1 for c in t[:-1]] fout.write('Case #{0}: {1}\n'.format(i, solve(a)))
PHP
UTF-8
10,155
2.640625
3
[]
no_license
<?php /*********************************************************************** * Author : Philippe Ku * School / Class : CFPT Informatique / I.FA-P3B * Date : 15.06.2016 * Programm : Event gestion website * File : controller.php * Description : This file is the controller that checks all the datas of my website * Version : 1.10 * ****************************************************************** */ session_start(); // Sets the errors to null. $signin_error = ""; $passwordcheck_error = ""; $passwordlength_error = ""; $date_error = ""; $editdate_error = ""; $comment_error = ""; $banconnect_error = ""; // Checks if the insert event button is pressed. if (isset($_POST['insert_event'])) { // Getting the datas with security check from the form field. $datas['event_title'] = filter_var($_POST['event_title'], FILTER_SANITIZE_SPECIAL_CHARS); $datas['event_street'] = filter_var($_POST['event_street'], FILTER_SANITIZE_SPECIAL_CHARS); $datas['event_city'] = filter_var($_POST['event_city'], FILTER_SANITIZE_SPECIAL_CHARS); $datas['event_country'] = filter_var($_POST['event_country'], FILTER_SANITIZE_SPECIAL_CHARS); $datas['event_datestart'] = filter_var($_POST['event_datestart'], FILTER_SANITIZE_SPECIAL_CHARS); $datas['event_dateend'] = filter_var($_POST['event_dateend'], FILTER_SANITIZE_SPECIAL_CHARS); $datas['event_desc'] = $_POST['event_desc']; // The TinyMCE script handles the security check. $datas['user_id'] = getUserId(); // Get the user_id from the sessions. if ($_POST['event_datestart'] <= $_POST['event_dateend']) { // Upload the image in the correct folder. uploadEventImage(); // Getting the datas from the image. $datas['event_image'] = $_SESSION['imageevent_name']; // Add the event into the database. insertNewEvent($datas); // Redirect to the index page. header('location: index.php'); } else { $date_error = '<div class="alert alert-warning"><strong>ATTENTION !</strong>La date de fin doit être supérieur ou égale à celle de début !</div>'; } } // Checks if the insert user button is pressed. if (isset($_POST['insert_user'])) { // Getting the datas with security check from the form field. $datas['user_email'] = filter_var($_POST['user_email'], FILTER_SANITIZE_SPECIAL_CHARS); $datas['user_nickname'] = filter_var($_POST['user_nickname'], FILTER_SANITIZE_SPECIAL_CHARS); // Checks if the two passwords are matching. if ($_POST['user_password'] == $_POST['user_checkpassword']) { if (strlen($_POST['user_password']) >= 3) { $datas['user_password'] = sha1($_POST['user_password']); // Add the new user in the database. insertNewUser($datas); // Shows a succes message. echo '<script type="text/javascript"> alert("Votre compte à été crée !"); document.location.href = "index.php"; </script>'; } else { $passwordlength_error = '<div class="alert alert-warning"><strong>ATTENTION !</strong> Le mot de passe doit faire au minimum 3 caractères !</div>'; } } else { $passwordcheck_error = '<div class="alert alert-warning"><strong>ATTENTION !</strong> Les mots de passe ne correspondent pas !</div>'; } } // Checks if the connect button is pressed. if (isset($_POST['connect_user'])) { // Getting the datas from the form field. $datas['user_email'] = (isset($_POST['user_email']) ? $_POST['user_email'] : ""); $datas['user_password'] = (isset($_POST['user_password']) ? $_POST['user_password'] : ""); // Connect the user with the datas he gave us. If all the datas are true then log him. if (checkuser($datas)) { $results = getUserInfo(); if ($results[0]['status'] == 1) { // Sets the logged status to true. setLoggedIn(true); // Set his group. setUserGroup(getUserGroupFromDatabase($datas)); } else { $banconnect_error = '<div class="alert alert-warning"><strong>ATTENTION !</strong> Votre compte a été banni veuillez contacter l\'administrateur !</div>'; } } else { $signin_error = '<div class="alert alert-warning"><strong>ATTENTION !</strong> La combinaison email / mot de passe est incorrecte!</div>'; } } // Checks if the comment button is pressed. if (isset($_POST['insert_comment'])) { // Getting the datas from the form field. $datas['comment_time'] = date('Y-m-d H:i:s'); $datas['comment_text'] = $_POST['comment_text']; $datas['user_id'] = getUserId(); $datas['event_id'] = $_REQUEST['event_id']; if ($_POST['comment_text'] != "") { // Add the new comment into the database. insertNewComment($datas); // Redirect to the event detail page. header('Location: event_details.php?event_id=' . $_REQUEST['event_id']); } else { $comment_error = '<div class="alert alert-warning"><strong>ATTENTION !</strong> Le texte du commentaire ne doit pas être vide !</div>'; } } // Checks if the logout button is pressed. if (isset($_REQUEST['logout'])) { logOutUser(); header('Location: index.php'); } // Change the menubar depending if it's a visitor, member or admin that signin. switch (getUserGroup()) { case -1: require '/menu/default_menu.php'; break; case 0: require '/menu/user_menu.php'; break; case 1: require '/menu/admin_menu.php'; break; default :require '/menu/default_menu.php'; break; } // Checks if the edit profile button is pressed. if (isset($_POST['edit_profile'])) { // Getting the datas (secured!) from the form fields. $datas['user_name'] = filter_var($_POST['edit_name'], FILTER_SANITIZE_SPECIAL_CHARS); $datas['user_firstname'] = filter_var($_POST['edit_firstname'], FILTER_SANITIZE_SPECIAL_CHARS); $datas['user_organisation'] = filter_var($_POST['edit_organisation'], FILTER_SANITIZE_SPECIAL_CHARS); $datas['user_adress'] = filter_var($_POST['edit_adress'], FILTER_SANITIZE_SPECIAL_CHARS); $datas['user_desc'] = $_POST['edit_desc']; $datas['user_id'] = getUserId(); // Upload the image in the correct file. uploadAvatarImage(); // Getting the datas for the image. $datas['user_avatar'] = $_SESSION['imageavatar_name']; // Edit the new profile in the database. editUserData($datas); // Redirect to the index page. header('Location: myaccount.php'); } // Checks if the edit event button is pressed. if (isset($_POST['edit_event'])) { // Getting the datas (secured!) from the form fields. $datas['event_title'] = filter_var($_POST['editevent_title'], FILTER_SANITIZE_SPECIAL_CHARS); $datas['event_street'] = filter_var($_POST['editevent_street'], FILTER_SANITIZE_SPECIAL_CHARS); $datas['event_city'] = filter_var($_POST['editevent_city'], FILTER_SANITIZE_SPECIAL_CHARS); $datas['event_country'] = filter_var($_POST['editevent_country'], FILTER_SANITIZE_SPECIAL_CHARS); $datas['event_datestart'] = filter_var($_POST['editevent_datestart'], FILTER_SANITIZE_SPECIAL_CHARS); $datas['event_dateend'] = filter_var($_POST['editevent_dateend'], FILTER_SANITIZE_SPECIAL_CHARS); $datas['event_desc'] = $_POST['editevent_desc']; $datas['event_id'] = $_GET['event_id']; if ($_POST['editevent_datestart'] <= $_POST['editevent_dateend']) { // Upload the image in the correct folder. uploadEventImage(); // Getting the datas for the image. $datas['event_image'] = $_SESSION['imageevent_name']; // Edit the new profile in the database. editUserEvent($datas); // Redirect to the index page. header('Location: myaccount.php'); } else { $editdate_error = '<div class="alert alert-warning"><strong>ATTENTION !</strong>La date de fin doit être supérieur ou égale à celle de début !</div>'; } } // Checks if the searchbox is not empty and displays the results of the search. if (isset($_GET['search'])) { $search_query = filter_var($_GET['user_query'], FILTER_SANITIZE_SPECIAL_CHARS); if ($search_query != "") { searchAnEvent($search_query); } else { echo '<div class="row col-md-offset-0"><h1>Veuillez entrer un élément de recherche...</h1><br/>'; } } // Checks if the delete user event button is pressed. if (isset($_POST['delete_userevent'])) { $datas['event_id'] = $_POST['hidden_idevent']; deleteEvent($datas); } // Checks if the ban admin event button is pressed. if (isset($_POST['ban_adminevent'])) { $datas['event_id'] = $_POST['hidden_ideventadmin']; banEvent($datas); } // Checks if the unban event admin button is pressed. if (isset($_POST['unban_adminevent'])) { $datas['event_id'] = $_POST['hidden_ideventadmin']; unbanEvent($datas); } // Checks if the delete admin event button is pressed if (isset($_POST['delete_adminevent'])) { $datas['event_id'] = $_POST['hidden_ideventadmin']; deleteEvent($datas); } // Checks if the ban comment button is pressed. if (isset($_POST['ban_comment'])) { $datas['comment_id'] = $_POST['hidden_idcommentadmin']; banComment($datas); } // Checks if the unban comment button is pressed. if (isset($_POST['unban_comment'])) { $datas['comment_id'] = $_POST['hidden_idcommentadmin']; unbanComment($datas); } // Checks if the delete comment button is pressed. if (isset($_POST['delete_comment'])) { $datas['comment_id'] = $_POST['hidden_idcommentadmin']; deleteComment($datas); } // Checks if the ban admin user button is pressed. if (isset($_POST['ban_adminuser'])) { $datas['user_id'] = $_POST['hidden_iduseradmin']; banUser($datas); } // Checks if the unban admin user button is pressed. if (isset($_POST['unban_adminuser'])) { $datas['user_id'] = $_POST['hidden_iduseradmin']; unbanUser($datas); } // Checks if the delete admin user button is pressed if (isset($_POST['delete_adminuser'])) { $datas['user_id'] = $_POST['hidden_iduseradmin']; deleteUser($datas); }
C++
UTF-8
1,253
3.046875
3
[ "Apache-2.0" ]
permissive
#pragma once #include <Functions/IFunction.h> #include <Interpreters/Context_fwd.h> namespace DB { /// Creates an array, multiplying the column (the first argument) by the number of elements in the array (the second argument). /// Function may accept more then two arguments. If so, the first array with non-empty offsets is chosen. class FunctionReplicate : public IFunction { public: static constexpr auto name = "replicate"; static FunctionPtr create(ContextPtr) { return std::make_shared<FunctionReplicate>(); } String getName() const override { return name; } size_t getNumberOfArguments() const override { return 0; } bool isVariadic() const override { return true; } bool isSuitableForShortCircuitArgumentsExecution(const DataTypesWithConstInfo & /*arguments*/) const override { return true; } bool useDefaultImplementationForNulls() const override { return false; } bool useDefaultImplementationForLowCardinalityColumns() const override { return false; } DataTypePtr getReturnTypeImpl(const DataTypes & arguments) const override; ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr &, size_t) const override; }; }
JavaScript
UTF-8
2,331
2.640625
3
[]
no_license
import React, { useEffect, useState } from 'react'; import axios from 'axios'; import { Redirect } from 'react-router-dom'; const REACT_APP_SERVER_URL = process.env.REACT_APP_SERVER_URL; const AllUsers = (props) => { const [allUsers, setAllUsers] = useState('') const [follows, setFollows] = useState([]) const [redirect, setRedirect] = useState('') //get route for all users const users = axios.get(`${REACT_APP_SERVER_URL}/api/users/all`) useEffect(() => { users.then(res=>{ setAllUsers(res.data) }) },[]) console.log(allUsers); console.log(allUsers[0]) const handleFollowerChange = (e) => { setFollows(e.target.value) } const handleFollow = (id) => { //e.preventDefault(); // console.log('your follows array',props.user.follows) // const id = props.user.id; // console.log(id) // const followersUpdate = { // follows // }; axios.put(`${REACT_APP_SERVER_URL}/api/users/follows/add/${id}`) .then((response)=>{ console.log(response, 'followe r has been added') console.log(response, 'follow has been added') setRedirect(true) }) .catch((error) => { console.log(error); }) } console.log(allUsers); if (redirect) return <Redirect to='/home' /> if (allUsers){ return( <div> <h2>All users</h2> {allUsers.map((user, idx)=>( <div key={idx} className ='post-container'> <img className='post-image' src={user.picture} alt=""/> <h5><a href={`/user/${user._id}`}>{user.name}</a> </h5> {/* <h6>followers: {user.followers.length} </h6> */} <p>follows: {user.follows.length}</p> <p>Recent Post: {user.posts.slice(-1)} </p> <button className="btn btn-primary" onChange={handleFollowerChange} onClick={ ()=>handleFollow(user._id)}> Follow </button> </div> ))} </div> ) }else{ return( <div> <h1> no users available</h1> </div> ) } } export default AllUsers
TypeScript
UTF-8
569
2.8125
3
[ "MIT" ]
permissive
let deprecationsSeen: { [key: string]: boolean } = {}; export const resetDeprecationsSeen = (): void => { deprecationsSeen = {}; }; const consoleWarn = (typeof console === 'object' && typeof console.warn === 'function') ? (...args: any[]) => console.warn(...args) : () => { }; export const deprecate = (msg: string): void => { if (!deprecationsSeen[msg]) { deprecationsSeen[msg] = true; consoleWarn(`redux-observable | DEPRECATION: ${msg}`); } }; export const warn = (msg: string): void => { consoleWarn(`redux-observable | WARNING: ${msg}`); };
Python
UTF-8
1,411
3.796875
4
[]
no_license
def w_convert(): kg_lb = 2.2046228 st_lb = 14 st_kg = 6.3502927 conv_choice = input( "Choose from one of the following weight conversions:\n" "1. Pound (lb) <-> Kilogram (kg)\n" "2. Stone (st) <-> Pound (lb)\n" "3. Stone (st) <-> Kilogram (kg)\n\n" "Choice: ") if conv_choice == '1': entry = input( "\n" "Enter a value, followed by a unit. (e.g.: 15lbs or 1lb or 23kg)\n\n" "Value: ") def lbconvert(): output = entry/kg_lb if entry > 1 or entry < 1: unit = 'lbs' elif entry == 1: unit = 'lb' print( str(entry) + unit + " equal to " + str(output) + "kg." ) def kgconvert(): output = entry*kg_lb print( str(entry) + "kg equal to " + str(output) + "lbs." ) if entry[-3:] == 'lbs': unit = 'lbs' entry = float(entry[:-3]) lbconvert() elif entry[-2:] == 'lb': unit = 'lb' entry = float(entry[:-2]) lbconvert() elif entry[-2:] == 'kg': entry = float(entry[:-2]) kgconvert() w_convert()
Java
UTF-8
3,643
1.765625
2
[]
no_license
package com.dvc.mybilibili.mvp.model.api.service.comment; import com.alibaba.fastjson.JSONObject; import com.dvc.mybilibili.app.retrofit2.BaseUrl; import com.dvc.mybilibili.mvp.model.api.response.GeneralResponse; import com.dvc.mybilibili.mvp.model.api.service.comment.entity.*; import java.util.Map; import io.reactivex.Observable; import retrofit2.http.Field; import retrofit2.http.FieldMap; import retrofit2.http.FormUrlEncoded; import retrofit2.http.GET; import retrofit2.http.POST; import retrofit2.http.Query; import retrofit2.http.QueryMap; @BaseUrl("http://api.bilibili.com") /* compiled from: BL */ public interface BiliCommentApiService { @FormUrlEncoded @POST("/x/v2/reply/del") Observable<GeneralResponse<Void>> delete(@Field("access_key") String access_key, @Field("oid") long j, @Field("type") int i, @Field("rpid") long j2); @FormUrlEncoded @POST("/x/v2/reply/del/combo") Observable<GeneralResponse<JSONObject>> deleteAndBlacken(@Field("access_key") String access_key, @Field("oid") long j, @Field("type") int i, @Field("rpid") long j2); @FormUrlEncoded @POST("/x/v2/reply/hate") Observable<GeneralResponse<Void>> dislike(@Field("access_key") String access_key, @Field("oid") long j, @Field("type") int i, @Field("rpid") long j2, @Field("action") int i2); //评论:更多回复内容 @GET("/x/v2/reply/reply/cursor") Observable<GeneralResponse<BiliCommentDetail>> getCommentDetail(@QueryMap Map<String, String> map); //评论:查看对话 @GET("/x/v2/reply/dialog/cursor") Observable<GeneralResponse<BiliCommentDialogue>> getCommentDialogue(@QueryMap Map<String, String> map); @GET("/x/v2/reply/folded") Observable<GeneralResponse<BiliCommentCursorList>> getCommentFoldedList(@QueryMap Map<String, String> map); @GET("/x/v2/reply") Observable<GeneralResponse<BiliCommentList>> getCommentList(@QueryMap Map<String, String> map); @GET("/x/v2/reply/cursor") Observable<GeneralResponse<BiliCommentCursorList>> getCommentListByCursor(@QueryMap Map<String, String> map); //评论列表 @GET("/x/v2/reply/main") Observable<GeneralResponse<BiliCommentCursorList>> getCommentListByCursorV2(@QueryMap Map<String, String> map); @GET("/x/v2/reply/log") Observable<GeneralResponse<BiliCommentDeleteHistory>> getDeleteLog(@Query("oid") long j, @Query("type") int i, @Query("pn") int i2, @Query("ps") int i3); @GET("/x/v2/reply/reply/folded") Observable<GeneralResponse<BiliCommentCursorList>> getReplyFoldedList(@QueryMap Map<String, String> map); @GET("/x/v2/reply/topics") Observable<GeneralResponse<BiliCommentTopic>> getTopic(@Query("oid") long j, @Query("type") int i, @Query("mid") long j2, @Query("message") String str); @FormUrlEncoded @POST("/x/v2/reply/action") Observable<GeneralResponse<Void>> like(@Field("access_key") String access_key, @Field("oid") long j, @Field("type") int i, @Field("rpid") long j2, @Field("action") int i2); @FormUrlEncoded @POST("/x/v2/reply/add") Observable<GeneralResponse<BiliCommentAddResult>> postComment(@FieldMap Map<String, String> map); @FormUrlEncoded @POST("/x/v2/reply/report") Observable<GeneralResponse<Void>> report(@Field("access_key") String access_key, @Field("oid") long j, @Field("type") int i, @Field("rpid") long j2, @Field("reason") int i2, @Field("content") String str2); @FormUrlEncoded @POST("/x/v2/reply/top") Observable<GeneralResponse<Void>> stick(@Field("access_key") String access_key, @Field("oid") long j, @Field("type") int i, @Field("rpid") long j2, @Field("action") int i2); }
Java
UTF-8
388
1.632813
2
[]
no_license
package com.pathfinder.anup.todolist; import android.content.Context; /** * Created by Anup on 2/8/2017. */ public interface TodoMainViewPresenter { void onResume(Context context); void onItemClicked(int position); void onDestroy(); void onSuccess(); void addWishTodoInDB(Context context, int id, String todoItem, String desc); //void onAddTodoEntryErr(); }
Java
UTF-8
991
2.8125
3
[]
no_license
package com.dengzi.eventbus; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * @Title: 异步执行线程池 * @Author: djk * @Time: 2017/11/20 * @Version:1.0.0 */ public class AsyncPoster implements Runnable { Subscription subscription; Object event; private final static ExecutorService executorService = Executors.newCachedThreadPool(); public AsyncPoster(Subscription subscription, Object event) { this.subscription = subscription; this.event = event; } public static void enqueue(Subscription subscription, Object event) { AsyncPoster asyncPoster = new AsyncPoster(subscription, event); // 用线程池 executorService.execute(asyncPoster); } @Override public void run() { try { subscription.subscriberMethod.method.invoke(subscription.subscriber, event); } catch (Exception e) { e.printStackTrace(); } } }
JavaScript
UTF-8
5,324
2.546875
3
[]
no_license
import React, { useState } from 'react'; import { View, ScrollView, KeyboardAvoidingView, TouchableOpacity } from 'react-native'; import { SafeAreaView } from 'react-native-safe-area-context'; import { Text } from 'react-native-elements'; import ModalComponent from '../components/Modal' import InputComponent from '../components/InputComponent'; //Initialisation de Redux import { connect } from 'react-redux'; import urlLocal from '../../urlDevs' const URL_BE = process.env.REACT_APP_URL_BE function SignUpScreen(props) { const [signUpUserFirstname, setSignUpUserFirstname] = useState('') const [signUpEmail, setSignUpEmail] = useState('') const [signUpPassword, setSignUpPassword] = useState('') const [confPassword, setConfUpPassword] = useState('') const [toModal, setToModal]= useState({}) const [modal, setModal] = useState(false) const modalOn = (type, message)=>{ setToModal( {type, message, setModal, modal} ) setModal(true) } var handleSubmitSignup = async () => { let errors = [] if (signUpUserFirstname === ""){ errors.push('name is empty') } if (signUpEmail === ""){ errors.push('email is incompete') } if (signUpPassword === "" || signUpPassword !== confPassword){ errors.push('passwords are wrongs') } if ( errors.length === 0 ){ const body = `prenom=${signUpUserFirstname}&email=${signUpEmail}&password=${signUpPassword}` console.log("body=", body) const data = await fetch(`${urlLocal}/users/sign-up`, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body : body, }) const response = await data.json() console.log('reponse Backend=', response) if (response.status) { //si l'utilisateur a bien été enregistré en BDD (le sign-up a fonctionné), // on appelle la fonction 'addToken' comme propriété de Redux et // on ajoute dans Redux l'user reçu du backend props.newUser(response.user); console.log('user est enregistré'); modalOn ("succes", 'Profil is created') } else { modalOn ("error", response.error) } }else{ console.log('errors=', errors) modalOn ("error", errors.toLocaleString()) } } return ( <View > <ModalComponent type={toModal.type} message={toModal.message} setModal={setModal} modal={modal} /> <ScrollView contentContainerStyle={{ flexDirection: 'column'}}> <KeyboardAvoidingView behavior="padding" style={{width: "90%", justifyContent: 'center' }}> <SafeAreaView> <InputComponent label="Name" placeholder="your name" secureTextEntry={false} setState = { setSignUpUserFirstname} /> <InputComponent label="e-mail" placeholder="enter your address e-mail" secureTextEntry={false} setState = { setSignUpEmail} /> <InputComponent label="Password" placeholder="enter your password" secureTextEntry={true} setState = { setSignUpPassword} /> <InputComponent label="Password" placeholder="repeat your password" secureTextEntry={true} setState = { setConfUpPassword} /> </SafeAreaView> </KeyboardAvoidingView> <View style={{ alignItems: 'center' }}> <TouchableOpacity onPress={() => handleSubmitSignup()} style={{ width: '40%', height: 40, backgroundColor: '#FF8200', alignItems: 'center', justifyContent: 'center', borderRadius: 15 }} > <Text style={{ color: 'white', fontSize: 16, fontWeight: 'bold' }}>Inscription</Text> </TouchableOpacity> </View> </ScrollView> </View> ); } //Mise en place du composant conteneur qui va “englober” SignUpScreen function mapDispatchToProps(dispatch) { return { // création de la fonction qui va devoir recevoir une info afin de déclencher une action nommée addToken qui enverra cette information auprès de Redux comme propriété newUser: function (user) { dispatch({ type: 'user', user }) }, } } // function mapStateToProps(state) { // return { SignUpScreen: state.city } // } //export modifié pour l’appliquer au composant conteneur export default connect( null, mapDispatchToProps )(SignUpScreen);
C++
UTF-8
928
2.59375
3
[]
no_license
#include<stdio.h> #include<iostream> #include<ctype.h> #include<string.h> #include<stdlib.h> #include<math.h> #include<string> #include<algorithm> #include<vector> #include<sstream> #include<stack> #include<queue> #include<map> #include<set> using namespace std; int n,i,gcd,lcm,arr[100]; int GCD(int a,int b){ while(b){ a=a%b; swap(a,b); } return a; } int LCM(int i,int j){ int lcm=(i/GCD(i,j))*j; return lcm; } int main() { //freopen("input.txt","r",stdin); //freopen("output.txt","w",stdout); while(scanf("%d",&n)==1){ for(i=0;i<n;i++) scanf("%d",&arr[i]); gcd=GCD(arr[0],arr[1]) ; lcm=(arr[0]*arr[1])/gcd; for(i=2;i<n;i++){ gcd=GCD(gcd,arr[i]); lcm=LCM(lcm,arr[i]); } printf("GCD %d\n",gcd); printf("LCM %d\n",lcm); } return 0 ; }
JavaScript
UTF-8
4,981
2.765625
3
[]
no_license
// user와 관계된 라우터 // JWT 웹 토큰 방식 - JSON 토큰 안에 일정한 정보를 담아 로그인, 글 작성 할 때 오직 인증된 사람만 글을 쓸 수 있도록 하기 // 웹에서 토큰을 보내주면 서버에서 인증을 해서 만약 성공 시 글을 쓸 수 있거나 로그인을 하도록 함 //서버 측에서 유저가 로그인 했는지 보관하고 있을 필요 없고 단지 요청이 있을 때 토큰 값이 유효한지만 판단해 접근 여부 결정 // npm i bcryptjs jsonwebtoken import express from 'express' import bcrypt from 'bcryptjs' import jwt from 'jsonwebtoken' import config from '../../config/index'; const {JWT_SECRET} = config; import User from '../../models/user' const router = express.Router(); // @routes GET api/user // @desc GET all user // @access public // 유저 검색 router.get('/', async(req, res) => { try{ // 유저 검색 const users = await User.find(); // 유저가 존재하지 않으면 if(!users) throw Error("No users"); // 유저가 존재하면 성공 코드 보내고 유저 정보 json으로 넘기기 res.status(200).json(users); }catch(e) { console.log(e); res.status(400).json({msg: e.message}); //400 상태 코드를 json 형태로 보내 실패를 알림 } }); // 회원가입 - 유저 작성 - POST // @routes POST api/user // @desc Register user // @access public router.post('/', (req, res) => { // express 서버에선 대부분의 정보가 req.body에 담겨있다. const {name, email,password} = req.body; //Simple validation if(!name || !email || !password) { return res.status(400).json({msg: "모든 필드를 채워주세요"}); }; // Check for existing user 이미 존재하는 이메일이 있는지 확인 User.findOne({email}).then(user => { if(user) return res.status(400).json({msg: "이미 가입된 유저가 존재합니다."}); // newUser 정보 인스턴스화 const newUser = new User({ name, email, password }); // bcrypt 작성 bcrypt.genSalt(10, (err, salt) => { //salt 값 생성 bcrypt.hash(newUser.password, salt, (err, hash) => { // newUser의 password와 salt값 합쳐 해시값 생성 if(err) throw err; newUser.password = hash; // 해시값 생성 완료 시 newUser password에 hash 값으로 갱신 newUser.save().then((user) => { // newUser을 save하기 jwt.sign( //jwt 웹 토큰 생성 및 등록 {id: user.id}, JWT_SECRET, //JWT_SECRET {expiresIn: 3600}, //jwt 만기일 (err, token) => { // 생성된 token 가지고 if(err) throw err; res.json({ // res에 json 형태로 token과 user 정보 내보내기 token, user: { id: user.id, name: user.name, email: user.email } }) } ) }); }); }); }); }); // 프로필 페이지 (비밀번호 수정 기능만) //@route POST api/user/:username/profile //@desc POST Edit Password //@access Private router.post('/:username/profile', async(req, res) => { try { const {previousPassword, password, rePassword, userId} = req.body; // 구조 분해 const result = await User.findById(userId, 'password'); // userId로 찾은 계정의 password를 가져옴 bcrypt.compare(previousPassword, result.password) // bcrypt 를 통해 이전 패스워드와 계정에 있던 패스워드 일치 여부 확인 .then((isMatch) => { if(!isMatch) { //일치 하지 않음 console.log('비밀번호 불일치'); return res.status(400).json({ match_msg: "기존 비밀 번호와 일치하지 않습니다." }) } else { // 새 비밀번호 등록 if(password === rePassword) { console.log('비밀번호 확인됨'); bcrypt.genSalt(10, (err, salt) => { // salt 생성 (2의 10승번 계산해서 salt 제작) bcrypt.hash(password, salt, (err, hash) => { // hash 값 만들기 (새 비밀번호에 salt를 넣어서 새 비밀번호를 해쉬값(임의의 값)으로 만들어준다) if(err) throw err; // 만약 에러가 나면 에러 던져버림 result.password = hash; // result의 password 값을 hash로 교체하고 result.save();// result 저장 }) }) res.status(200).json({ success_msg: "비밀번호가 업데이트 되었습니다." }) } else { console.log('비밀번호 비교 확인 틀림'); res.status(400).json({ fail_msg: "입력한 값이 새 비밀번호와 동일하지 않습니다" }) } } }) } catch (e) { console.log(e); } }) export default router;
JavaScript
UTF-8
1,172
2.53125
3
[]
no_license
// add React import React, { Component } from 'react'; import ReactDOM from 'react-dom'; // add components import Header from './components/header'; import LinkCreate from './components/link_create'; import { Links } from '../imports/collections/links'; import LinkList from './components/link_list'; // create App component (similar to a class / constructor function) class App extends Component { // render the view // the console.log is run as many times as this component gets rendered... currently 2x: // 1. once for constructor function's initialization of the "images" prop // 2. then once when state of "images" prop gets updated with images from Imgur API // pass "images" prop into ImageList child component render() { return( <div> <Header /> <LinkCreate /> <LinkList /> </div> ); } }; // wait for DOM to load before rendering components // render component to the screen // ReactDOM.render(); takes 2 arguments // 1. which component to render // 2. where to render it in the HTML structure // add an instance of App component Meteor.startup( () => { ReactDOM.render(<App />, document.querySelector(".react-target")); });
C
UTF-8
530
3.8125
4
[]
no_license
/* 19. Faça um algoritmo que verifique a validade de uma senha fornecida pelo usuário. A senha correta é o número: 12345. O algoritmo deve imprimir mensagem de permissão ou negação de acesso. */ #include <stdio.h> int main(){ int senha; //Entrada de Dados printf("\nDigite a senha: "); scanf("%i", &senha); //Processamento e Saida de Dados if (senha == 12345) { //Definição da senha printf("Acesso Permitido!\n"); } else { printf("Acesso Negado!\n"); } }
Java
UTF-8
623
3.859375
4
[]
no_license
package com.jerry.linkedlist; import java.util.ArrayList; /** * * 描述 * 输入一个链表的头节点,按链表从尾到头的顺序返回每个节点的值(用数组返回)。 * * 如输入{1,2,3}的链表如下图: * * 返回一个数组为[3,2,1] * * 0 <= 链表长度 <= 1000 * */ public class RverseList { public ArrayList<Integer> printListFromTailToHead(ListNode listNode){ ArrayList<Integer> list = new ArrayList<>(); ListNode tmp = listNode; while (tmp != null){ list.add(0,tmp.val); tmp = tmp.next; } return list; } }
Python
UTF-8
699
2.78125
3
[ "LicenseRef-scancode-generic-cla", "MIT" ]
permissive
import sys def sub(filename,out, size): qids = {} with open(filename,'r') as f: for l in f: l = l.strip().split('\t')[0] qids[l]= 0 sample = list(qids)[:size] with open(filename,'r') as f: with open(out,'w') as w: for l in f: qid = l.strip().split('\t')[0] if qid in sample: w.write(l) if __name__ == "__main__": if len(sys.argv) != 4: print("Usage: subsample.py <input filename> <output filenane> <sample size>") exit(-1) else: sub(sys.argv[1],sys.argv[2],int(sys.argv[3]))
Java
UTF-8
5,226
2.15625
2
[ "BSD-3-Clause", "MPL-2.0", "Apache-2.0" ]
permissive
// *** WARNING: this file was generated by pulumi-java-gen. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** package com.pulumi.azure.monitoring.inputs; import com.pulumi.core.Output; import com.pulumi.core.annotations.Import; import java.lang.Integer; import java.lang.String; import java.util.List; import java.util.Objects; import java.util.Optional; import javax.annotation.Nullable; public final class AlertProcessingRuleSuppressionScheduleRecurrenceMonthlyArgs extends com.pulumi.resources.ResourceArgs { public static final AlertProcessingRuleSuppressionScheduleRecurrenceMonthlyArgs Empty = new AlertProcessingRuleSuppressionScheduleRecurrenceMonthlyArgs(); /** * Specifies a list of dayOfMonth to recurrence. Possible values are integers between `1` - `31`. * */ @Import(name="daysOfMonths", required=true) private Output<List<Integer>> daysOfMonths; /** * @return Specifies a list of dayOfMonth to recurrence. Possible values are integers between `1` - `31`. * */ public Output<List<Integer>> daysOfMonths() { return this.daysOfMonths; } /** * Specifies the recurrence end time (H:M:S). * */ @Import(name="endTime") private @Nullable Output<String> endTime; /** * @return Specifies the recurrence end time (H:M:S). * */ public Optional<Output<String>> endTime() { return Optional.ofNullable(this.endTime); } /** * Specifies the recurrence start time (H:M:S). * */ @Import(name="startTime") private @Nullable Output<String> startTime; /** * @return Specifies the recurrence start time (H:M:S). * */ public Optional<Output<String>> startTime() { return Optional.ofNullable(this.startTime); } private AlertProcessingRuleSuppressionScheduleRecurrenceMonthlyArgs() {} private AlertProcessingRuleSuppressionScheduleRecurrenceMonthlyArgs(AlertProcessingRuleSuppressionScheduleRecurrenceMonthlyArgs $) { this.daysOfMonths = $.daysOfMonths; this.endTime = $.endTime; this.startTime = $.startTime; } public static Builder builder() { return new Builder(); } public static Builder builder(AlertProcessingRuleSuppressionScheduleRecurrenceMonthlyArgs defaults) { return new Builder(defaults); } public static final class Builder { private AlertProcessingRuleSuppressionScheduleRecurrenceMonthlyArgs $; public Builder() { $ = new AlertProcessingRuleSuppressionScheduleRecurrenceMonthlyArgs(); } public Builder(AlertProcessingRuleSuppressionScheduleRecurrenceMonthlyArgs defaults) { $ = new AlertProcessingRuleSuppressionScheduleRecurrenceMonthlyArgs(Objects.requireNonNull(defaults)); } /** * @param daysOfMonths Specifies a list of dayOfMonth to recurrence. Possible values are integers between `1` - `31`. * * @return builder * */ public Builder daysOfMonths(Output<List<Integer>> daysOfMonths) { $.daysOfMonths = daysOfMonths; return this; } /** * @param daysOfMonths Specifies a list of dayOfMonth to recurrence. Possible values are integers between `1` - `31`. * * @return builder * */ public Builder daysOfMonths(List<Integer> daysOfMonths) { return daysOfMonths(Output.of(daysOfMonths)); } /** * @param daysOfMonths Specifies a list of dayOfMonth to recurrence. Possible values are integers between `1` - `31`. * * @return builder * */ public Builder daysOfMonths(Integer... daysOfMonths) { return daysOfMonths(List.of(daysOfMonths)); } /** * @param endTime Specifies the recurrence end time (H:M:S). * * @return builder * */ public Builder endTime(@Nullable Output<String> endTime) { $.endTime = endTime; return this; } /** * @param endTime Specifies the recurrence end time (H:M:S). * * @return builder * */ public Builder endTime(String endTime) { return endTime(Output.of(endTime)); } /** * @param startTime Specifies the recurrence start time (H:M:S). * * @return builder * */ public Builder startTime(@Nullable Output<String> startTime) { $.startTime = startTime; return this; } /** * @param startTime Specifies the recurrence start time (H:M:S). * * @return builder * */ public Builder startTime(String startTime) { return startTime(Output.of(startTime)); } public AlertProcessingRuleSuppressionScheduleRecurrenceMonthlyArgs build() { $.daysOfMonths = Objects.requireNonNull($.daysOfMonths, "expected parameter 'daysOfMonths' to be non-null"); return $; } } }
Python
UTF-8
1,527
3.265625
3
[]
no_license
#encoding:utf-8 #@Time : 2017/7/30 14:28 #@Author : JackNiu import re from sklearn.feature_extraction.text import CountVectorizer from sklearn.model_selection import train_test_split from sklearn.naive_bayes import MultinomialNB class LanguageDetector(): def __init__(self, classifier=MultinomialNB()): self.classifier = classifier self.vectorizer = CountVectorizer(ngram_range=(1,2), max_features=100, preprocessor=self._remove_noise) def _remove_noise(self, document): noise_pattern = re.compile("|".join(["http\S+", "\@\w+", "\#\w+"])) clean_text = re.sub(noise_pattern, "", document) return clean_text def features(self, X): return self.vectorizer.transform(X) def fit(self, X, y): self.vectorizer.fit(X) self.classifier.fit(self.features(X), y) print(self.classifier.feature_log_prob_[0]) print(self.classifier.class_log_prior_) def predict(self, x): return self.classifier.predict(self.features([x])) def score(self, X, y): return self.classifier.score(self.features(X), y) in_f = open('data.csv') lines = in_f.readlines() in_f.close() dataset = [(line.strip()[:-3], line.strip()[-2:]) for line in lines] x, y = zip(*dataset) x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=1) language_detector = LanguageDetector() language_detector.fit(x_train, y_train) print(language_detector.predict('This is an English sentence')) print(language_detector.score(x_test, y_test))
C#
UTF-8
1,371
2.703125
3
[]
no_license
using System.Threading.Tasks; using Supermarket.Core.Models; using Microsoft.EntityFrameworkCore; namespace Supermarket.Core.Helpers { public static class SeedHelper { public static async Task SeedCategories(DataContext context) { if (await context.Categories.AnyAsync()) { return; } await context.Categories.AddAsync(new Category { Name = "Phone" }); await context.Categories.AddAsync(new Category { Name = "Tivi" }); await context.SaveChangesAsync(); } public static async Task SeedProducts(DataContext context) { if (await context.Products.AnyAsync()) { return; } await context.Products.AddAsync(new Product { Name = "Tomato", CategoryId = 1, Description = "A very good fruit", Price = 5, ImageUrl = "This a image" }); await context.Products.AddAsync(new Product { Name = "Onion", CategoryId = 2, Description = "A very good fruit", Price = 5, ImageUrl = "This a image" }); await context.SaveChangesAsync(); } } }
C++
UTF-8
1,834
2.90625
3
[]
no_license
#include "height_map.h" #include "SDL_image.h" HeightMap::~HeightMap() { } Uint32 HeightMap::GetPixel(int x, int y) { int bpp = surface->format->BytesPerPixel; /* Here p is the address to the pixel we want to retrieve */ Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * bpp; switch(bpp) { case 1: return *p; case 2: return *(Uint16 *)p; case 3: if(SDL_BYTEORDER == SDL_BIG_ENDIAN) return p[0] << 16 | p[1] << 8 | p[2]; else return p[0] | p[1] << 8 | p[2] << 16; case 4: return *(Uint32 *)p; default: return 0; /* shouldn't happen, but avoids warnings */ } } // (w-1)*(h-1)*2 triangles void HeightMap::load(char *filename) { surface = IMG_Load(filename); glEnable(GL_TEXTURE_2D); glGenTextures(1, &id); glBindTexture(GL_TEXTURE_2D, id); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, surface->w, surface->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, surface->pixels); map = (GLfloat *)malloc(surface->w * surface->h * sizeof(GLfloat)); Uint8 r1, g1, b1, a1; height = surface->h; width = surface->w; for (int i = 0; i < surface->h; i++) { for (int j = 0; j < surface->w; j++) { SDL_GetRGBA(GetPixel(j, i), surface->format, &r1, &g1, &b1, &a1); map[i * surface->w + j] = float(r1) / 256.0; } } SDL_FreeSurface(surface); } void HeightMap::render() { //glActiveTexture(GL_TEXTURE0); //glBindTexture(GL_TEXTURE_2D, id); for(int z = 0; z < height-1; z++) { glBegin(GL_TRIANGLE_STRIP); for (int x = 0; x < width; x++) { //glTexCoord2d(GLfloat(x) / width, GLfloat(z) / height); glVertex3f(x, map[(z+1) * width + x], z+1); glVertex3f(x, map[z * width + x], z); } glEnd(); } }
C
UTF-8
583
2.984375
3
[]
no_license
#include "shell-header.h" /** * check_builtin - checks if the user has called one of our built-ins. * @token: the string we are checking * * Return: The function that was matched, or NULL. */ void (*check_builtin(char *token))(prm_t *) { sh_t bltin[] = { {"exit", exit_blt}, {"env", env_blt}, {"setenv", setenv_blt}, {"unsetenv", unsetenv_blt}, {"cd", cd_blt}, {"help", help_blt}, {NULL, NULL} }; int ite = 0; while ((bltin + ite)->data) { if (_strcmp(token, (bltin + ite)->data) == 0) { return ((bltin + ite)->f); } ite++; } return (NULL); }
Python
UTF-8
630
3.421875
3
[]
no_license
# Enter your code here. Read input from STDIN. Print output to STDOUT from collections import Counter if __name__ == '__main__': N = int(input()) shoeSize = list(map(int, input().split())) shoeSize = Counter(shoeSize) customers = [] earned = 0 while 1: try: val = list(map(int,input().split())) if len(val) > 1: customers.append(val) except EOFError: break for size, price in customers: if size in shoeSize and shoeSize[size] != 0: earned += price shoeSize[size] -= 1 print(earned)
Python
UTF-8
1,836
2.65625
3
[ "MIT" ]
permissive
import itertools from typing import Dict, List import numpy as np import pretrainedmodels import torch def freeze(model: torch.nn.Module): """Freeze all model parameters.""" for param in model.parameters(): param.requires_grad = False def unfreeze(model: torch.nn.Module): """Unfreeze all model parameters.""" for param in model.parameters(): param.requires_grad = True def get_group_params(groups: List[List[torch.nn.Module]], lrs: np.ndarray) -> List[Dict]: """Create dicts defining parameter groups for an optimizer.""" group_params = [] for group, lr in zip(groups, lrs): params = {'params': list(itertools.chain(*[layer.parameters() for layer in group])), 'lr': lr} group_params.append(params) return group_params def get_norm(model: torch.nn.Module, norm_type: int = 2) -> float: total_norm = 0 for p in model.parameters(): if p.grad is not None: param_norm = p.grad.data.norm(norm_type) total_norm += param_norm.item() ** norm_type total_norm = total_norm ** (1. / norm_type) return total_norm def load_model(model_name: str, num_classes: int, pretrained: str): return pretrainedmodels.__dict__[model_name](num_classes=num_classes, pretrained=pretrained) def save_checkpoint(epoch: int, model: torch.nn.Module, optimizer: torch.optim.Optimizer, path: str): state = { 'epoch': epoch, 'state_dict': model.module.state_dict() if isinstance(model, torch.nn.DataParallel) else model.state_dict(), 'optimizer': optimizer.state_dict() } torch.save(state, path) def load_checkpoint(model: torch.nn.Module, path: str): checkpoint = torch.load(path) model.load_state_dict(checkpoint['state_dict'])