language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Markdown
UTF-8
865
2.640625
3
[]
no_license
--- title: Erik Štrumbelj firstName: Erik lastName: Štrumbelj date: 2019-04-19T00:00:00.000Z bgImage: /uploads/c75t9175.jpg image: uploads/team_erik_strumbelj.jpg phone: +386 1 479 8235 email: erik.strumbelj@fri.uni-lj.si redirect: '' --- Dr. Erik Štrumbelj je izredni profesor na Fakulteti za računalništvo in informatiko Univerze v Ljubljani ter član [Laboratorija za kognitivno modeliranje](https://www.fri.uni-lj.si/sl/laboratorij/lkm). Raziskovalno deluje na področju uporabne statistike in strojnega učenja s poudarkom na bayesovskih metodah. Ima preko 10 let praktičnih izkušenj iz analize podatkov, že več kot 5 let pa poučuje Bayesovo statistiko na magistrskem in doktorskem študiju. Skupaj s člani skupine za Bayesovo statistiko in računanje je aktiven pri promociji Bayesove statistike in razvoju programskih orodij, vključno s prispevki k razvoju programskega jezika Stan.
C
UTF-8
693
3.921875
4
[]
no_license
// // dist.c // ECS 30 Work // // Created by Jennifer Salas on 9/28/16. // Copyright © 2016 Jennifer Salas. All rights reserved. // #include <stdio.h> #include <math.h> int main() { // user defined variables double x1, y1, x2, y2; // calculated variables double distance; printf("Enter the first point in the form x,y: "); scanf(" %lf , %lf", &x1, &y1); printf("Enter the second point in the form x,y: "); scanf(" %lf , %lf", &x2, &y2); distance = sqrt( pow(x1 - x2, 2) + pow( y2 - y1, 2)); printf("The distance between (%.2lf, %.2lf) and (%.2lf, %.2lf) is %.2lf.\n", x1, y1, x2, y2, distance); return 0; }
JavaScript
UTF-8
1,600
2.671875
3
[]
no_license
const { API_URL, API_VERSION } = require('../constants/Endpoints'); const APIRequest = require('./APIRequest'); const HTTPError = require('./HTTPError'); const DiscordAPIError = require('./DiscordAPIError'); const routeBuilder = require('./routeBuilder'); class RequestHandler { /** * @param {object} [options] * @param {string} [options.apiURL] * @param {number} [options.apiVersion] */ constructor(options = {}) { const baseURL = options.apiURL || API_URL; const version = options.apiVersion || API_VERSION; this.baseURL = `${baseURL}/v${version}`; } /** * @returns {api} */ get api() { return routeBuilder(this); } async request(method, path, options = {}) { const request = new APIRequest(this, method, path, options); const res = await request.send(); if (res.ok) { return this.parseResponse(res); } // Handle 4xx responses if (res.status >= 400 && res.status < 500) { let data; try { data = await this.parseResponse(res); } catch (err) { throw new HTTPError(err.message, err.constructor.name, err.status, request.method, request.path); } throw new DiscordAPIError(request.path, data, request.method, res.status); } // Throw an error for other status codes throw new HTTPError(res.statusText, res.constructor.name, res.status, request.method, request.path); } parseResponse(res) { if (res.headers.get('content-type').includes('application/json')) { return res.json(); } return null; } } module.exports = RequestHandler;
C++
UTF-8
324
2.859375
3
[]
no_license
#include <iostream> #include <string> #include <algorithm> using namespace std; int main() { for (int i = 1000; i < 10000; i++) { string a = to_string(i), b = to_string(i * 9); reverse(b.begin(), b.end()); if (a == b) { cout << i << endl; } } return 0; }
Ruby
UTF-8
1,479
3.796875
4
[]
no_license
require "byebug" require_relative "intcode_computer" class Hull BLACK = 0 WHITE = 1 def initialize @hull = {} end def set_color(x,y,color) key = "#{x}_#{y}" @hull[key] = color end def get_color(x,y) key = "#{x}_#{y}" @hull[key] || BLACK end def painted_count @hull.keys.count end end class HullPaintingRobot attr_reader :hull module Orientations UP = 0 RIGHT = 1 DOWN = 2 LEFT = 3 end def initialize @x = 0 @y = 0 @orientation = Orientations::UP @hull = Hull.new @computer = IntcodeComputer::Computer.new data = File.read("input.txt").gsub(/\n/,"").split(",").map {|d| d.to_i } @computer.load(data, [@hull.get_color(@x,@y)]) end def run count = 0 @computer.process do |output| if count.even? @hull.set_color(@x,@y, output) else output == 0 ? rotate_left : rotate_right move_robot @computer.inputs = [@hull.get_color(@x,@y)] end count += 1 end end def move_robot case @orientation when Orientations::UP @y += 1 when Orientations::DOWN @y -= 1 when Orientations::LEFT @x -= 1 when Orientations::RIGHT @x += 1 end end def rotate_right @orientation += 1 @orientation = 0 if @orientation > 3 end def rotate_left @orientation -= 1 @orientation = 3 if @orientation < 0 end end h = HullPaintingRobot.new h.run puts h.hull.painted_count
Java
UTF-8
1,082
3.546875
4
[]
no_license
package com.myself.searching.bitonic; import java.util.Arrays; public class BitonicSearch { public int positionOfMax = -2; public int[] tab; public BitonicSearch(int[] tab) {this.tab = tab;} public void findMax() { int left = 0; int right = tab.length - 1; if (right < 0){ positionOfMax = -1; return; } if(right == 0){ positionOfMax = 0; return; } while(left < right) { int mid = (left + right) / 2; if (tab[mid] > tab[mid + 1]){ positionOfMax = mid; return; } if(tab[left] <= tab[mid]){ left = mid + 1; } else { right = mid; } } if(tab[right] >= tab[right - 1]) { positionOfMax = right; return; } // positionOfMax = left; } @Override public String toString() { return "Max at: " + positionOfMax + " in: " + Arrays.toString(tab); } }
Java
UTF-8
1,318
3.234375
3
[]
no_license
package ua.nure.kramarenko.SummaryTask3.entity.plane; /** * This class describes ammo characteristics of the plane * * @author Vlad Kramarenko * */ public class Ammo { /** * Boolean value describes has plane ammo or not */ private Boolean value; /** * Describes how many rockets has the plane */ private Byte rocket; /** * Empty class constructor */ public Ammo() { } /** * Class constructor * * @param value * Boolean ammo describes has plane ammo or not * @param rocket * Rockets count */ public Ammo(Boolean value, byte rocket) { this.value = value; this.rocket = rocket; } /** * Class constructor * * @param value * Boolean ammo describes has plane ammo or not */ public Ammo(Boolean value) { this.value = value; } public Boolean getValue() { return value; } public void setValue(Boolean value) { this.value = value; } public Byte getRocket() { return rocket; } public void setRocket(Byte value) { this.rocket = value; } /** * Override toString() method to determine text output of the ammo */ @Override public String toString() { if (value != null) { if (value) { return "Ammo:\t" + rocket + "(rocket)"; } else { return "Ammo:\tno ammo"; } } else { return ""; } } }
Java
UTF-8
1,863
2.328125
2
[]
no_license
package com.example.two.controller; import com.example.two.entity.Result; import com.example.two.entity.SysUser; import com.example.two.service.UserServiceI; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.naming.AuthenticationException; @Api(value = "用户登录管理") @RestController public class AuthController { private static Logger logger = LoggerFactory.getLogger(AuthController.class); @Autowired private UserServiceI userService; @ApiOperation(value = "登录") @RequestMapping(value = "/auth/login", method = RequestMethod.POST) public Result<?> createAuthenticationToken(String username,String password) throws AuthenticationException { logger.info("登陆:" +username); SysUser user = userService.login(username,password); return Result.success(user); } @ApiOperation(value = "注册") @RequestMapping(value = "auth/register", method = RequestMethod.POST) public Result<SysUser> register(@RequestBody SysUser addedUser) throws AuthenticationException{ logger.info("注册:" +addedUser.getUserName()); return Result.success(userService.register(addedUser)); } @ApiOperation(value = "是否登录") @RequestMapping(value = "auth/isLogin", method = RequestMethod.POST) public Boolean isLogin() throws AuthenticationException{ return true; } @ApiOperation(value = "获取用户名") @RequestMapping(value="/auth/getUserName", method = RequestMethod.GET) @ResponseBody public String login() { SysUser user = userService.selectById(1); return user.getUserName(); } }
Java
UTF-8
1,703
1.5
2
[ "Apache-2.0" ]
permissive
/******************************************************************************* * Copyright 2017 HuaWei Tld * * 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.openstack4j.openstack.loadbalance.internal; import org.openstack4j.api.loadbalance.ELBQuotaService; import org.openstack4j.model.loadbalance.Quotas; import org.openstack4j.openstack.loadbalance.domain.ELBQuotas; public class ELBQuotaServiceImpl extends BaseELBServices implements ELBQuotaService { @Override public Quotas list() { return get(ELBQuotas.class, uri("/elbaas/quotas")).execute(); } }
Python
UTF-8
641
4.375
4
[]
no_license
# IF ELSE IN PYTHON var1 = 223 var2 = 223 if var1>var2 : print("greater") elif var1==var2: print("equal") else: print("lesser") list = [2,3,4,5,6] if 15 in list: print("Yes present in list") # FOR LOOP IN PYTHON list1 = [["mohan",2],["kumarf",2],["rathore",4],["tanisha",5],["surabhi",7]] dict1 =dict(list1) print(dict1) for item,lollypop in dict1.items(): print(item,lollypop) # WHILE LOOP IN PYTHON i=0 while i<45: print(1) i+=10 # BREAK AND CONTINUE STATMENT IN PYTHON # shorthand if else a = int(input("enter a number \n")) b = int(input("enter b number \n")) print("mohan") if a<b else print("kumar")
Python
UTF-8
2,325
3.625
4
[]
no_license
import random import colored from colored import stylize Optionen = ["Schere", "Stein", "Papier"] Zettel = input ("Wie viele Runden möchtest du spielen ?") Spielerpunkte = 0 Computerpunkte = 0 for Runde in range (int( Zettel )): Computerwahl = random.choice(Optionen) Spielerwahl = input (stylize("Was willst du wählen: Schere , Stein oder Papier ? ", colored.fg("purple_1b"))) if Computerwahl == "Schere": if Spielerwahl == "Schere": print (stylize("Der Computer hat Schere gewählt. Unentschieden!",colored.fg("dark_orange_3b"))) if Spielerwahl == "Stein": print (stylize("Der Computer hat Schere gewählt. Gewonnen!",colored.fg("chartreuse_2a"))) Spielerpunkte = Spielerpunkte+1 if Spielerwahl == "Papier": print (stylize("Der Computer hat Schere gewählt. Verloren!",colored.fg("red_3a"))) Computerpunkte = Computerpunkte+1 if Computerwahl == "Stein": if Spielerwahl == "Stein": print (stylize("Der Computer hat Stein gewählt. Unentschieden!",colored.fg("dark_orange_3b"))) if Spielerwahl == "Papier": print (stylize("Der Computer hat Stein gewählt. Gewonnen!",colored.fg("chartreuse_2a"))) Spielerpunkte = Spielerpunkte+1 if Spielerwahl == "Schere": print (stylize("Der Computer hat Stein gewählt. Verloren!",colored.fg("red_3a"))) Computerpunkte = Computerpunkte+1 if Computerwahl == "Papier": if Spielerwahl == "Papier": print (stylize("Der Computer hat Papier gewählt. Unentschieden!",colored.fg("dark_orange_3b"))) if Spielerwahl == "Schere": print (stylize("Der Computer hat Papier gewählt. Gewwonnen!",colored.fg("chartreuse_2a"))) Spielerpunkte = Spielerpunkte+1 if Spielerwahl == "Stein": print (stylize("Der Computer hat Papier gewählt. Verloren!",colored.fg("red_3a"))) Computerpunkte = Computerpunkte+1 if Spielerpunkte == Computerpunkte: print ("Unentschieden") if Spielerpunkte > Computerpunkte: print ("Gewonnen") if Spielerpunkte < Computerpunkte: print ("Verloren")
Java
UTF-8
776
1.546875
2
[]
no_license
package com.scarlatti.ws.client; import java.io.Closeable; import java.util.concurrent.TimeUnit; /** * ______ __ __ ____ __ __ __ _ * ___/ _ | / /__ ___ ___ ___ ____ ___/ /______ / __/______ _____/ /__ _/ /_/ /_(_) * __/ __ |/ / -_|_-<(_-</ _ `/ _ \/ _ / __/ _ \ _\ \/ __/ _ `/ __/ / _ `/ __/ __/ / * /_/ |_/_/\__/___/___/\_,_/_//_/\_,_/_/ \___/ /___/\__/\_,_/_/ /_/\_,_/\__/\__/_/ * Saturday, 8/4/2018 */ public interface WsRpcSyncManager extends Closeable { void notifyReady(); void notifyKilled(); void notifyComplete(); void awaitReady(long timeout, TimeUnit timeUnit); void awaitKilled(long timeout, TimeUnit timeUnit); void awaitComplete(long timeout, TimeUnit timeUnit); }
C++
UTF-8
485
2.71875
3
[]
no_license
#ifndef LCD_DEVICE_HPP #define LCD_DEVICE_HPP #include <string> #include "point.hpp" #include "pixels_rect.hpp" namespace Lcd { class LcdDevice { private: int dev_fd; static const int LCD_WIDTH = 200; static const int LCD_HEIGHT = 8; ssize_t write_pixels(const Point &begin, const PixelsRect &rect) const; public: LcdDevice(const std::string &dev_name); ~LcdDevice(); ssize_t write_all_pixels(const PixelsRect &rect) const; bool is_opened() const; }; } #endif
Java
UTF-8
2,825
2.0625
2
[]
no_license
package com.example.weatherapp; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.Handler; import android.view.Window; import android.view.WindowManager; import android.widget.Toast; public class SplashActivity extends AppCompatActivity implements LocationListener { Handler handler; LocationManager locationManager; public static String lat; public static String lon; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_splash); getSupportActionBar().hide(); if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 101); } getLocation(); handler=new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { Intent intent=new Intent(SplashActivity.this,MainActivity.class); startActivity(intent); finish(); } },3000); } void getLocation() { try { locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 5, this); } catch(SecurityException e) { e.printStackTrace(); } } @Override public void onLocationChanged(Location location) { lat=String.valueOf(location.getLatitude()); lon=String.valueOf(location.getLongitude()); } @Override public void onProviderDisabled(String provider) { Toast.makeText(SplashActivity.this, "Please Enable GPS and Internet", Toast.LENGTH_SHORT).show(); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } }
C
UTF-8
4,074
2.90625
3
[]
no_license
/* * T E R M I N A L I N D E P E N D E N T G R A P H I C S * * by: George E. Toth * May 15, 1980 * * These routines produce the Terminal Independent Graphics * Intermediate language designed by Michael J. Muuss. * * (C) Copyright, 1980 All Rights Reserved * * R E V I S I O N H I S T O R Y * =================================================== * 05/15/80 GET Wrote subroutine. * */ #include <stdio.h> #include <math.h> #include "tig.h" double c1 = { 0.70710678118654752440084 }; /* SQRT(2)/2 */ double c2 = { 0.29289321881345247559916 }; /* 1 - SQRT(2)/2 */ #define SINCR 4096 /* 2 ^ 10; starting increment (arbitrary) */ #define abs(a) ((a<0)? -(a) : (a)) #define VECDIF(x,y) (abs(x.Xpos-y.Xpos)+abs(x.Ypos-y.Ypos)+abs(x.Zpos-y.Zpos)) /* * PLOTF( <start position>, <stop position>, <scale fact>, &<func> ) * * Calls: move(6T) * * Method: * * This routine will plot an arbitrary function on the plotter. * The function must be parametrized in such a way that as its * argument varies from 0 to 1, it returns single values throughout * its maximal range. * The function must return a pointer to a TIG vector. * * This subroutine is NOT GUARANTEED OF PLOTTING ALL FUNCTIONS!!! * It does a modest job of well behaved global behaviour functions. * It will fall apart on highly localized disordered functions, * for example a real delta function is unlikely to work, but * Bessel functions will. All in all it is the next best thing * to doing it without doing it. */ plotf( start, stop, scale, pfct ) /* Plot the function `pfct' */ double start, stop; register int scale; register struct TIGvec *(*pfct)(); { register int flag = {0}; double incr; struct TIGvec vecref, vecnew, vectry, vecdif, vecj; if( start > stop ) { /* accross 0-1 boundary, i.e. opposite dir */ plotf( start, 1.0, scale, pfct ); plotf( 0.0, stop, scale, pfct ); return; } incr = (stop - start) / SINCR; vecref = *(*pfct)(start,scale); /* Initialize reference */ move2pt( vecref.Xpos, vecref.Ypos, vecref.Zpos ); /* Move to it */ while( start < stop ) { vecnew = *(*pfct)( start+incr, scale ); vecj = vecnew; vecdif = vecnew; vecdif.Xpos -= vecref.Xpos; vecdif.Ypos -= vecref.Ypos; vecdif.Zpos -= vecref.Zpos; /* See if it can be made larger */ if( !flag && start+incr+incr <= stop ) { vectry = *(*pfct)( start+incr+incr, scale ); /* Real value */ vecj.Xpos += vecdif.Xpos; vecj.Ypos += vecdif.Ypos; vecj.Zpos += vecdif.Zpos; if( VECDIF( vectry, vecj ) <= 1 ) { /* It worked... */ incr *= 2; /* so make it bigger */ continue; } } /* * Check curve in between points. This is where it fails * to detect things like delta functions. It checks only * three points, which for most functions will be good * enough since they are in rather strange places: * 1-sqrt(2)/2, 0.5, sqrt(2)/2 * Why there? Why not? * * Flag is set once the LARGER test is passed so if it * fails any of the smaller ones, it doesn't get enlarged * again. */ flag = 1; vectry = *(*pfct)( start+incr/2, scale ); vecj = vecref; vecj.Xpos += vecdif.Xpos>>1; vecj.Ypos += vecdif.Ypos>>1; vecj.Zpos += vecdif.Zpos>>1; if( VECDIF( vectry, vecj ) > 1 ) { incr /= 2; continue; } vectry = *(*pfct)( start+incr*c1, scale ); vecj = vecref; vecj.Xpos += vecdif.Xpos*c1; vecj.Ypos += vecdif.Ypos*c1; vecj.Zpos += vecdif.Zpos*c1; if( VECDIF( vectry, vecj ) > 1 ) { incr /= 2; continue; } vectry = *(*pfct)( start+incr*c2, scale ); vecj = vecref; vecj.Xpos += vecdif.Xpos*c2; vecj.Ypos += vecdif.Ypos*c2; vecj.Zpos += vecdif.Zpos*c2; if( VECDIF( vectry, vecj ) > 1 ) { incr /= 2; continue; } if( vecdif.Xpos | vecdif.Ypos | vecdif.Zpos ) /* If motion resulted */ move( vecdif.Xpos, vecdif.Ypos, vecdif.Zpos ); start += incr; /* Went through an interation */ vecref = vecnew; /* Move forward */ flag = 0; /* Reset */ } vecref = *(*pfct)(stop,scale); /* Goto to stop point */ move2pt( vecref.Xpos, vecref.Ypos, vecref.Zpos ); }
Java
UTF-8
1,311
2.15625
2
[]
no_license
package com.gymbuddy.backgymbuddy.admin.order.domain; import com.gymbuddy.backgymbuddy.admin.base.BaseDomain; import com.gymbuddy.backgymbuddy.admin.enums.status.CsStatus; import com.gymbuddy.backgymbuddy.admin.enums.status.ProgramStatus; import com.gymbuddy.backgymbuddy.admin.enums.status.ShipmentStatus; import com.gymbuddy.backgymbuddy.admin.user.domain.User; import lombok.Data; import javax.persistence.*; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; @Entity @Table(name = "orders") @Data public class Orders extends BaseDomain { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "orders_id") private Long id; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "user_id") private User user; @OneToMany(mappedBy = "orders", cascade = CascadeType.ALL) private List<OrderProgram> orderPrograms = new ArrayList<>(); @OneToMany(mappedBy = "orders", cascade = CascadeType.ALL) private List<OrderGoods> orderGoods = new ArrayList<>(); @Enumerated(EnumType.STRING) private CsStatus csStatus; @Enumerated(EnumType.STRING) private ShipmentStatus shipmentStatus; @Enumerated(EnumType.STRING) private ProgramStatus programStatus; @Column private BigDecimal totalPrice; }
Ruby
UTF-8
607
2.953125
3
[ "MIT" ]
permissive
require "csv" module Transformer class Csv DEFAULT_PATH = File.expand_path("../../../test/data.csv", __FILE__) #def name(file = '') # file ||= '' # output = [] # output << file.strip # output.join(',') #end def self.csv2hash(file = nil) file ||= DEFAULT_PATH array = CSV.read(file).map do |row| [ row[0].to_i, [ row[1].strip, row[2].to_f ] ] end data = ::Hash[array] puts "csv to hash finish!!" data end end end
Markdown
UTF-8
1,361
3.765625
4
[]
no_license
### 基础数论概念 #### 公约数 > 性质1:$d \mid a \text { 且 } d \mid b \text { 蕴涵着 } d \mid(a+b) \text { 且 } d \mid(a-b)$ > 性质2:对于任意的$x$和$y$,$d \mid a \text { 且 } d \mid b \text { 蕴涵着 } d \mid(a x+b y)$ #### 最大公约数 ${ 两个不同时为 0 的整数 a 与 b 的公约数中最大的称为其最大公约数, 记作 gcd( } a, b \text { ) }$ 最大公约数有如下几个性质: $$ \begin{aligned} &\begin{array}{l} \operatorname{gcd}(a, b)=\operatorname{gcd}(b, a) \\ \operatorname{gcd}(a, b)=\operatorname{gcd}(-a, b) \\ \operatorname{gcd}(a, b)=\operatorname{gcd}(|a|,|b|) \\ \operatorname{gcd}(a, 0)=|a| \end{array}\\ &\operatorname{gcd}(a, k a)=|a| \quad \text { 对任 意 } k \in \mathbf{Z} \end{aligned} $$ > 推论1:$ \text { 对任意整数 } a \text { 与 } b, \text { 如果 } d \mid a \text { 且 } d \mid b, \text { 则 } d \mid \operatorname{gcd}(a, b) $ #### 唯一因子分解定理 $ \text { 对所有素数 p 和所有整数 a, b, 如果 } p \mid a b, \text { 则 } p \mid a \text { 或 } p \mid b(\text { 或两者都成立) } $ (唯一因子分解定理) 合数a仅能以一种方式写成如下乘积形式: $$ a=p_{1}^{e_{1}} p_{z}^{e_{2}} \cdots p_{r}^{e_{r}} $$ 其中 $p_{i}$ 为素数, $p_{1}<p_{2}<\cdots<p_{r},$ 且 $e_{i}$ 为 正整数。 ### 常见算法
Java
UTF-8
3,901
2.1875
2
[]
no_license
package br.com.fiap.challenge.controller; import java.util.List; import java.util.Optional; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; 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.RequestMapping; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import br.com.fiap.challenge.exception.ComercianteNotFoundException; import br.com.fiap.challenge.model.Comerciante; import br.com.fiap.challenge.model.User; import br.com.fiap.challenge.repository.ComercianteRepository; @Controller @RequestMapping("/comerciante") public class ComercianteController { @Autowired private ComercianteRepository repository; @Autowired private MessageSource message; @GetMapping public ModelAndView index() { ModelAndView modelAndView = new ModelAndView("comerciantes"); List<Comerciante> comerciantes = repository.findAll(); modelAndView.addObject("comerciantes", comerciantes); return modelAndView; } @PostMapping public String save(@Valid Comerciante comerciante, BindingResult result, RedirectAttributes redirect) { if (result.hasErrors()) return "comerciante-form"; repository.save(comerciante); redirect.addFlashAttribute("message", message.getMessage("comerciante.new.success", null, LocaleContextHolder.getLocale())); return "redirect:/comerciante"; } @RequestMapping("new") public String create(Comerciante comerciante) { return "comerciante-form"; } @GetMapping("/hold/{id}") public String hold(@PathVariable Long id, Authentication auth) { Optional<Comerciante> optional = repository.findById(id); if(optional.isEmpty()) throw new ComercianteNotFoundException("Comerciante não encontrada"); Comerciante comerciante = optional.get(); if(comerciante.getUser() != null) throw new NotAllowedException("Comerciante já atribuído no sistema"); User user = (User) auth.getPrincipal(); comerciante.setUser(user); repository.save(comerciante); return "redirect:/comerciante"; } @GetMapping("/release/{id}") public String release(@PathVariable Long id, Authentication auth) { Optional<Comerciante> optional = repository.findById(id); if(optional.isEmpty()) throw new ComercianteNotFoundException("Comerciante não encontrada"); Comerciante comerciante = optional.get(); User user = (User) auth.getPrincipal(); if(!comerciante.getUser().equals(user)) throw new NotAllowedException("Comerciante está com outro usuário"); comerciante.setUser(null); repository.save(comerciante); return "redirect:/comerciante"; } @RequestMapping("/delete/{id}") public String deleteComerciante(@PathVariable String id) { repository.deleteById(Long.parseLong(id)); return "redirect:/comerciante"; } @RequestMapping("/update/{id}") public String update(@PathVariable Long id, @Valid Comerciante comerciante, BindingResult result, Model model) { Comerciante teste = repository.findById(id).orElse(null); if (result.hasErrors()) { comerciante.setId(id); comerciante.setTitle(teste.getTitle()); comerciante.setDescription(teste.getDescription()); comerciante.setUser(teste.getUser()); return "comerciante-update-form"; } repository.save(comerciante); return "redirect:/comerciante"; } }
Markdown
UTF-8
1,294
2.6875
3
[ "MIT" ]
permissive
--- title: "South Florida's Codecamp 2020" --- These are the notes on my **Improve your AWS security** presentation ## [Slides](https://docs.google.com/presentation/d/1OZl445nzbtDBh3EtsFWAsJTA22cKxsh8WJHScEwaLQA/edit?usp=sharing) ## [Source Code](https://github.com/cshtdd/aws-security-presentation) ## Presentation Outline Cloud adoption has rapidly increased with the years. The cloud empowers companies to change faster. However, speed comes with its own set of risks: accidental data leaks, internal services publicly accessible, compromised account credentials. AWS offers several services to help secure and monitor your account. Wouldn't it be great to automatically validate S3 buckets are not publicly available? Would you like to know who destroyed the test EC2 instance without your consent? Would you like to get an alert when your account is under attack? This presentation will cover how to use three powerful AWS services to answer these and other questions. We will walk through AWS Config, AWS Cloudtrail and AWS Guarduty. What do they do. And what problems they solve. This is an introductory talk. Participants with any level of AWS knowledge are welcomed. This is an AWS only talk. The comparable Azure services will be explained in a future presentation.
PHP
UTF-8
2,989
2.546875
3
[]
no_license
<?php namespace App\Entity; use App\Repository\TransactionRepository; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass=TransactionRepository::class) */ class Transaction { const STATUS_SUCCESS = 1; const STATUS_FAILURE = 2; /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private $id; /** * @ORM\ManyToOne(targetEntity=User::class, inversedBy="transactions") * @ORM\JoinColumn(nullable=false) */ private $user; /** * @ORM\ManyToOne(targetEntity=Subscription::class, inversedBy="transactions") * @ORM\JoinColumn(nullable=false) */ private $subscription; /** * @ORM\Column(type="string", length=255) */ private $externalId; /** * @ORM\Column(type="string", length=255) */ private $provider; /** * @ORM\Column(type="integer") */ private $quantity; /** * @ORM\Column(type="integer") */ private $amount; /** * @ORM\Column(type="datetime") */ private $purchasedAt; /** * @ORM\Column(type="integer") */ private $status; public function getId(): ?int { return $this->id; } public function getUser(): ?User { return $this->user; } public function setUser(?User $user): self { $this->user = $user; return $this; } public function getSubscription(): ?Subscription { return $this->subscription; } public function setSubscription(?Subscription $subscription): self { $this->subscription = $subscription; return $this; } public function getExternalId(): ?string { return $this->externalId; } public function setExternalId(string $externalId): self { $this->externalId = $externalId; return $this; } public function getProvider(): ?string { return $this->provider; } public function setProvider(string $provider): self { $this->provider = $provider; return $this; } public function getQuantity(): ?int { return $this->quantity; } public function setQuantity(int $quantity): self { $this->quantity = $quantity; return $this; } public function getAmount(): ?int { return $this->amount; } public function setAmount(int $amount): self { $this->amount = $amount; return $this; } public function getPurchasedAt(): ?\DateTimeInterface { return $this->purchasedAt; } public function setPurchasedAt(\DateTimeInterface $purchasedAt): self { $this->purchasedAt = $purchasedAt; return $this; } public function getStatus(): ?int { return $this->status; } public function setStatus(int $status): self { $this->status = $status; return $this; } }
PHP
UTF-8
12,777
2.875
3
[]
no_license
<?php class database{ protected $server = "localhost"; protected $username = "root"; protected $password; protected $database = "startravel"; protected $link; public function __construct() { try { $this->link = new mysqli($this->server, $this->username, $this->password, $this->database); } catch (Exception $e) { echo "connection failed" . $e->getMessage(); } } public function fetch($query) { $row = null; if ($sql = $this->link->query($query)) { while ($data = mysqli_fetch_assoc($sql)) { $row[] = $data; } } return $row; } } class tourHot extends database { public function create() { ini_set('display_errors', 0); $name = $_POST['name_hot']; $anh = $_POST['img_hot']; $price = $_POST['price_hot']; $fromto = $_POST['fromto_hot']; $detail = $_POST['detail_hot']; $anh = $_FILES['img_hot']['name']; if ($anh != null) { $path = "images/"; $tmp_name = $_FILES['img_hot']['tmp_name']; $anh = $_FILES['img_hot']['name']; move_uploaded_file($tmp_name, $path . $anh); } $query = "insert into tour_hot(name_hot,img_hot,price_hot,detail_hot,from_to_hot) value ('$name','$anh',$price,'$detail','$fromto')"; if ($sql = $this->link->query($query)) { echo "<script>alert('SUCCESS')</script>"; header("location: admin.php"); } } public function edit($id) { ini_set('display_errors', 0); $name = $_POST['name_hot2']; $anh = $_POST['img_hot2']; $price = $_POST['price_hot2']; $fromto = $_POST['fromto_hot2']; $detail = $_POST['detail_hot2']; $anh = $_FILES['img_hot2']['name']; if ($anh != null) { $path = "images/"; $tmp_name = $_FILES['img_hot2']['tmp_name']; $anh = $_FILES['img_hot2']['name']; move_uploaded_file($tmp_name, $path . $anh); } $query = "update tour_hot set name_hot='$name',img_hot='$anh',price_hot='$price',detail_hot='$detail',from_to_hot='$fromto' where id_hot='$id'"; if ($sql = $this->link->query($query)) { echo "<script>alert('SUCCESS')</script>"; } } public function delete($id) { $query = "delete from tour_hot where id_hot='$id'"; if ($sql = $this->link->query($query)) { return true; } else return false; } } class tourOffer extends database { public function create() { ini_set('display_errors', 0); $name = $_POST['name_offer']; $anh = $_POST['img_offer']; $price = $_POST['price_offer']; $fromto = $_POST['fromto_offer']; $detail = $_POST['detail_offer']; $anh = $_FILES['img_offer']['name']; if ($anh != null) { $path = "images/"; $tmp_name = $_FILES['img_offer']['tmp_name']; $anh = $_FILES['img_offer']['name']; move_uploaded_file($tmp_name, $path . $anh); } $query = "insert into tour_offer(name_offer,img_offer,price_offer,detail_offer,from_to_offer) value ('$name','$anh',$price,'$detail','$fromto')"; if ($sql = $this->link->query($query)) { echo "<script>alert('SUCCESS')</script>"; header("location: admin.php"); } } public function edit($id) { ini_set('display_errors', 0); $name = $_POST['name_offer2']; $anh = $_POST['img_offer2']; $price = $_POST['price_offer2']; $fromto = $_POST['fromto_offer2']; $detail = $_POST['detail_offer2']; $anh = $_FILES['img_offer2']['name']; if ($anh != null) { $path = "images/"; $tmp_name = $_FILES['img_offer2']['tmp_name']; $anh = $_FILES['img_offer2']['name']; move_uploaded_file($tmp_name, $path . $anh); } $query = "update tour_offer set name_offer='$name',img_offer='$anh',price_offer='$price',detail_offer='$detail',from_to_offer='$fromto' where id_offer='$id'"; if ($sql = $this->link->query($query)) { echo "<script>alert('SUCCESS')</script>"; } } public function delete($id) { $query = "delete from tour_offer where id_offer='$id'"; if ($sql = $this->link->query($query)) { return true; } else return false; } } class tourCruise extends database { public function __construct() { try { $this->link = new mysqli($this->server, $this->username, $this->password, $this->database); } catch (Exception $e) { echo "connection failed" . $e->getMessage(); } } public function create() { ini_set('display_errors', 0); $name = $_POST['name_cruise']; $anh = $_POST['img_cruise']; $price = $_POST['price_cruise']; $fromto = $_POST['fromto_cruise']; $detail = $_POST['detail_cruise']; $anh = $_FILES['img_cruise']['name']; if ($anh != null) { $path = "images/"; $tmp_name = $_FILES['img_cruise']['tmp_name']; $anh = $_FILES['img_cruise']['name']; move_uploaded_file($tmp_name, $path . $anh); } $query = "insert into tour_cruise(name_cruise,img_cruise,price_cruise,detail_cruise,from_to_cruise) value ('$name','$anh',$price,'$detail','$fromto')"; if ($sql = $this->link->query($query)) { echo "<script>alert('SUCCESS')</script>"; header("location: admin.php"); } } public function edit($id) { ini_set('display_errors', 0); $name = $_POST['name_cruise2']; $anh = $_POST['img_cruise2']; $price = $_POST['price_cruise2']; $fromto = $_POST['fromto_cruise2']; $detail = $_POST['detail_cruise2']; $anh = $_FILES['img_cruise2']['name']; if ($anh != null) { $path = "images/"; $tmp_name = $_FILES['img_cruise2']['tmp_name']; $anh = $_FILES['img_cruise2']['name']; move_uploaded_file($tmp_name, $path . $anh); } $query = "update tour_cruise set name_cruise='$name',img_cruise='$anh',price_cruise='$price',detail_cruise='$detail',from_to_cruise='$fromto' where id_cruise='$id'"; if ($sql = $this->link->query($query)) { echo "<script>alert('SUCCESS')</script>"; } } public function delete($id) { $query = "delete from tour_cruise where id_cruise='$id'"; if ($sql = $this->link->query($query)) { return true; } else return false; } } class tourSport extends database { public function create() { ini_set('display_errors', 0); $name = $_POST['name_sport']; $anh = $_POST['img_sport']; $price = $_POST['price_sport']; $fromto = $_POST['fromto_sport']; $detail = $_POST['detail_sport']; $anh = $_FILES['img_sport']['name']; if ($anh != null) { $path = "images/"; $tmp_name = $_FILES['img_sport']['tmp_name']; $anh = $_FILES['img_sport']['name']; move_uploaded_file($tmp_name, $path . $anh); } $query = "insert into tour_sport(name_sport,img_sport,price_sport,detail_sport,from_to_sport) value ('$name','$anh',$price,'$detail','$fromto')"; if ($sql = $this->link->query($query)) { echo "<script>alert('SUCCESS')</script>"; header("location: admin.php"); } } public function edit($id) { ini_set('display_errors', 0); $name = $_POST['name_sport2']; $anh = $_POST['img_sport2']; $price = $_POST['price_sport2']; $fromto = $_POST['fromto_sport2']; $detail = $_POST['detail_sport2']; $anh = $_FILES['img_sport2']['name']; if ($anh != null) { $path = "images/"; $tmp_name = $_FILES['img_sport2']['tmp_name']; $anh = $_FILES['img_sport2']['name']; move_uploaded_file($tmp_name, $path . $anh); } $query = "update tour_sport set name_sport='$name',img_sport='$anh',price_sport='$price',detail_sport='$detail',from_to_sport='$fromto' where id_sport='$id'"; if ($sql = $this->link->query($query)) { echo "<script>alert('SUCCESS')</script>"; } } public function delete($id) { $query = "delete from tour_sport where id_sport='$id'"; if ($sql = $this->link->query($query)) { return true; } else return false; } } class tourCapital extends database { public function create() { ini_set('display_errors', 0); $name = $_POST['name_capital']; $anh = $_POST['img_capital']; $price = $_POST['price_capital']; $fromto = $_POST['fromto_capital']; $detail = $_POST['detail_capital']; $anh = $_FILES['img_capital']['name']; if ($anh != null) { $path = "images/"; $tmp_name = $_FILES['img_capital']['tmp_name']; $anh = $_FILES['img_capital']['name']; move_uploaded_file($tmp_name, $path . $anh); } $query = "insert into tour_capital(name_capital,img_capital,price_capital,detail_capital,from_to_capital) value ('$name','$anh',$price,'$detail','$fromto')"; if ($sql = $this->link->query($query)) { echo "<script>alert('SUCCESS')</script>"; header("location: admin.php"); } } public function edit($id) { ini_set('display_errors', 0); $name = $_POST['name_capital2']; $anh = $_POST['img_capital2']; $price = $_POST['price_capital2']; $fromto = $_POST['fromto_capital2']; $detail = $_POST['detail_capital2']; $anh = $_FILES['img_capital2']['name']; if ($anh != null) { $path = "images/"; $tmp_name = $_FILES['img_capital2']['tmp_name']; $anh = $_FILES['img_capital2']['name']; move_uploaded_file($tmp_name, $path . $anh); } $query = "update tour_capital set name_capital='$name',img_capital='$anh',price_capital='$price',detail_capital='$detail',from_to_capital='$fromto' where id_capital='$id'"; if ($sql = $this->link->query($query)) { echo "<script>alert('SUCCESS')</script>"; } } public function delete($id) { $query = "delete from tour_capital where id_capital='$id'"; if ($sql = $this->link->query($query)) { return true; } else return false; } } class blog extends database { public function create() { ini_set('display_errors', 0); $author_blog = $_POST['author_blog']; $anh = $_POST['img_blog']; $time_blog = $_POST['time_blog']; $title_blog = $_POST['title_blog']; $content_blog = $_POST['content_blog']; $anh = $_FILES['img_blog']['name']; if ($anh != null) { $path = "images/"; $tmp_name = $_FILES['img_blog']['tmp_name']; $anh = $_FILES['img_blog']['name']; move_uploaded_file($tmp_name, $path . $anh); } $query = "insert into blog(author_blog,img_blog,time_blog,title_blog,content_blog) value ('$author_blog','$anh','$time_blog','$title_blog','$content_blog')"; if ($sql = $this->link->query($query)) { echo "<script>alert('SUCCESS')</script>"; header("location: admin.php"); } } public function edit($id) { ini_set('display_errors', 0); $author_blog = $_POST['author_blog2']; $anh = $_POST['img_blog2']; $time_blog = $_POST['time_blog2']; $title_blog = $_POST['title_blog2']; $content_blog = $_POST['content_blog2']; $anh = $_FILES['img_blog2']['name']; if ($anh != null) { $path = "images/"; $tmp_name = $_FILES['img_blog2']['tmp_name']; $anh = $_FILES['img_blog2']['name']; move_uploaded_file($tmp_name, $path . $anh); } $query = "update blog set author_blog='$author_blog',img_blog='$anh',time_blog='$time_blog',title_blog='$title_blog',content_blog='$content_blog' where id_blog='$id'"; if ($sql = $this->link->query($query)) { echo "<script>alert('SUCCESS')</script>"; } } public function delete($id) { $query = "delete from blog where id_blog='$id'"; if ($sql = $this->link->query($query)) { return true; } else return false; } }
JavaScript
UTF-8
3,386
3.265625
3
[]
no_license
/** * Created by changliang on 6/22/19. */ /** * 个位数补0 * @param {(number|string)} */ exports.to0 = n => { return n * 1 < 10 ? "0" + n : n; }; /** * 时间戳或GMT转时间转换 * @param {(string | dateGMT),string} * timeStamp 时间戳或GMT格式日期 * format = YMD => 年-月-日 , Y=> 年 , M=>月 , D=>日 , YM => 年-月 , hms=> 时:分:秒 , YMDhms=> 年-月-日 时:分:秒 , YMDhm=> 年-月-日 时:分 */ exports.stampToTime = (date, format = "YMDhms") => { let getDate = null; let to0 = n => (n * 1 < 10 ? "0" + n : n); if (Object.prototype.toString.call(date) == "[object Date]") { //GMT getDate = date; } else { //时间戳 getDate = date / 100000000000 < 1 ? date * 1000 : date; } let oDate = new Date(getDate); let Y = oDate.getFullYear(); let M = to0(oDate.getMonth() + 1); let D = to0(oDate.getDate()); let h = to0(oDate.getHours()); let m = to0(oDate.getMinutes()); let s = to0(oDate.getSeconds()); let oMap = new Map([ ["Y", Y], ["M", M], ["D", D], ["h", h], ["hm", `${h}:${m}`], ["hms", `${h}:${m}:${s}`], ["YM", `${Y}-${M}`], ["YMD", `${Y}-${M}-${D}`], ["YMDhms", `${Y}-${M}-${D} ${h}:${m}:${s}`], ["YMDhm", `${Y}-${M}-${D} ${h}:${m}`] ]); return oMap.get(format); }; /** * 时间转时间戳 */ exports.timeToStamp = time => { let newTime = time.replace(/-/g, "/"); return new Date(newTime).getTime(); }; /** * 数组里对象删除相同元素 * @param {array ,string, [object|string]} * arr需要去重的数组 key对象里需要对比的 键 名 obj要对比的对象或者字符串 */ exports.rmSameObj = (arr, key, obj) => { let _obj = obj[key] ? obj[key] : obj; let _del = ""; arr.forEach((v, i) => { if (v[key] == _obj) { _del = arr.splice(i, 1); } }); return _del; }; /** * 两点间计算距离(经纬坐标) * @param {String, String, String, String} */ exports.getDistance = (lat1, lng1, lat2, lng2) => { let getRad = d => { var PI = Math.PI; return (d * PI) / 180.0; }; let f = getRad((lat1 * 1 + lat2 * 1) / 2); let g = getRad((lat1 * 1 - lat2 * 1) / 2); let l = getRad((lng1 * 1 - lng2 * 1) / 2); let sg = Math.sin(g); let sl = Math.sin(l); let sf = Math.sin(f); let s, c, w, r, d, h1, h2; let a = 6378137.0; //The Radius of eath in meter. let fl = 1 / 298.257; sg = sg * sg; sl = sl * sl; sf = sf * sf; s = sg * (1 - sl) + (1 - sf) * sl; c = (1 - sg) * (1 - sl) + sf * sl; w = Math.atan(Math.sqrt(s / c)); r = Math.sqrt(s * c) / w; d = 2 * w * a; h1 = (3 * r - 1) / 2 / c; h2 = (3 * r + 1) / 2 / s; s = d * (1 + fl * (h1 * sf * (1 - sg) - h2 * (1 - sf) * sg)); s = Math.round(s); //指定小数点后的位数。 return s; }; /** * 首字母大写 * @param { String } 英文单词 */ exports.capitalize = ([first, ...r]) => first.toUpperCase() + r.join(''); /** * 时间戳转日期格式 */ exports.timestamp2Date = (ts, format = '{Y}-{M}-{D}') => { let oDate = new Date(ts * 1000); let to0 = n => (n * 1 < 10 ? "0" + n : n); let setDate = { Y:oDate.getFullYear(), M:to0(oDate.getMonth() + 1), D:to0(oDate.getDate()), h:to0(oDate.getHours()), m:to0(oDate.getMinutes()), s:to0(oDate.getSeconds()) } return format.replace(/{(Y|M|D|h|m|s)+}/g,(v,k)=>{ return setDate[k] }) }
JavaScript
UTF-8
1,467
2.765625
3
[]
no_license
function validate(){ var regex = /^(([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+([;.](([a-zA-Z0-9_\-\.]+)@{[a-zA-Z0-9_\-\.]+0\.([a-zA-Z]{2,5}){1,25})+)*$/; if(!regex.test(formName.email.value)){ // alert("Congrats! This is a valid Email email"); alert("This is not a valid email address"); //return false; } var reg=/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,15}$/; if(reg.test(formName.password.value)){ alert("correct password"); // document.getElementById("error_msg").innerHTML ="correct password" ; //return true } else{ alert("incorrect password"); // return false; } var regexx=/^[a-zA-Z]/; if(regexx.test(formName.first_name.value)){ alert("correct name" ); //return true; } else{ alert("incorrect name"); // return false; } var regexx=/^[a-zA-Z]/; if(regexx.test(formName.first_name.value)){ alert("correct name" ); //return true; } else{ alert("incorrect name"); // return false; } }
PHP
UTF-8
2,234
2.671875
3
[]
no_license
<?php /** * Inheritance Campaign Model * For every inheritance model, allowed to have only $type, fillable, rules, and available function */ namespace App\Models; // use App\Models\Observers\ReferralObserver; class Referral extends Campaign { /** * The public variable that assigned type of inheritance model * * @var string */ public $type = 'referral'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'user_id' , 'type' , 'code' , 'value' , 'started_at' , 'expired_at' , ]; /** * Basic rule of database * * @var array */ protected $rules = [ 'user_id' => 'exists:users,id', 'code' => 'max:255|min:8', 'value' => 'numeric', 'type' => 'in:referral', // 'started_at' => 'date_format:"Y-m-d H:i:s"|after:now', // 'expired_at' => 'date_format:"Y-m-d H:i:s"|after:now', ]; /* ---------------------------------------------------------------------------- RELATIONSHIP ----------------------------------------------------------------------------*/ /* ---------------------------------------------------------------------------- QUERY BUILDER ----------------------------------------------------------------------------*/ /* ---------------------------------------------------------------------------- MUTATOR ----------------------------------------------------------------------------*/ /* ---------------------------------------------------------------------------- ACCESSOR ----------------------------------------------------------------------------*/ /* ---------------------------------------------------------------------------- FUNCTIONS ----------------------------------------------------------------------------*/ public static function boot() { parent::boot(); // Referral::observe(new ReferralObserver()); } /* ---------------------------------------------------------------------------- SCOPES ----------------------------------------------------------------------------*/ }
C++
UTF-8
506
2.953125
3
[]
no_license
#include <iostream> using namespace std; int sum(int a) { int sum_cif = 0; while (a != 0) { int last = a % 10; sum_cif = sum_cif + last; a = a / 10; } return sum_cif; } int main() { int n; cin >> n; int x[n]; int y[n]; for (int i = 1; i <= n; i++) { cin >> x[i]; } for (int i = 1; i <= n; i++) { y[i] = x[i] % sum(x[i]); } for (int i = 1; i <= n; i++) { cout << y[i] << " "; } }
JavaScript
UTF-8
4,362
2.625
3
[]
no_license
/*jshint node: true*/ /*jshint esversion: 6 */ "use strict"; const mongoose = require('mongoose'); const uniqueValidator = require('mongoose-unique-validator'); const bcrypt = require('bcrypt'); const jwt = require('jsonwebtoken'); const config = require('../config/config'); const UserSchema = new mongoose.Schema({ username: { type: String, lowercase: true, unique: true, required: [true, `'can't be blank'`], match: [/^[a-zA-Z0-9]+$/, 'is invalid'], index: true }, email: { type: String, lowercase: true, unique: true, required: [true, "can't be blank"], match: [/\S+@\S+\.\S+/, 'is invalid'], index: true }, name: { type: String, lowercase: true, required: [true, "can't be blank"], match: [/^[a-zA-Z]+$/, 'is invalid'], index: true }, surname: { type: String, lowercase: true, required: [true, "can't be blank"], match: [/^[a-zA-Z]+$/, 'is invalid'], index: true }, isAdmin: { type: Boolean, default: false }, isValidated: { type: Boolean, default: false }, image: String, hash: String, validationCode: String, created: { type: Date, default: Date.now() }, participations: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Games' }], preferences: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Sports' }], friends: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }] }, {timestamps: true}); UserSchema.plugin(uniqueValidator, {message: 'is already taken.'}); UserSchema.methods.validatePassword = (password) => { return bcrypt.compareSync(password, this.hash); }; UserSchema.methods.setPassword = function (password) { let salt = bcrypt.genSaltSync(config.saltRounds); this.hash = bcrypt.hashSync(password, salt); return this.save(); }; UserSchema.methods.generateJWT = function () { const today = new Date(); const exp = new Date(today); exp.setDate(today.getDate() + 60); return jwt.sign({ id: this._id, username: this.username, isAdmin: this.isAdmin, exp: parseInt(exp.getTime() / 1000), }, config.loginSecret); }; UserSchema.methods.generateCode = function () { let code = ''; let possibleChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; for (let i = 0; i < 6; i++) { code += possibleChars.charAt(Math.floor(Math.random() * possibleChars.length)); } this.validationCode = code; return this.save(); }; UserSchema.methods.authData = () => { return { username: this.username, email: this.email, token: this.generateJWT(), image: this.image || this.getDefaultProfilePicture(), preferences: this.preferences, friends: this.friends, mathces: this.mathces }; }; UserSchema.methods.getDefaultProfilePicture = () => { return `${config.serverURL}images/defaults/${this.name[0]}.jpg`; }; UserSchema.methods.userData = (user) => { return { username: this.username, bio: this.bio, image: this.image || this.getDefaultProfilePicture(), following: user ? user.isFollowing(this._id) : false }; }; UserSchema.methods.saveImage = (image) => { this.image = image; return this.save(); }; UserSchema.methods.addFavorite = (id) => { if(!this.friends.includes(id)) { throw Error('Already favorite.'); } this.friends.push(id); return this.save(); }; UserSchema.methods.unFavorite = (id) => { this.favorites.remove(id); return this.save(); }; UserSchema.methods.isFavorite = (id) => { return this.favorites.some((favoriteId) => { return favoriteId.toString() === id.toString(); }); }; UserSchema.methods.addFriend = (id) => { if(this.friends.includes(id)){ this.following.push(id); } return this.save(); }; UserSchema.methods.unFriend = (id) => { this.following.remove(id); return this.save(); }; UserSchema.methods.isFriend = (id) => { return this.following.some(function(followId){ return followId.toString() === id.toString(); }); }; mongoose.model('User', UserSchema);
JavaScript
UTF-8
597
2.59375
3
[]
no_license
const loader = new THREE.TextureLoader(); let cobblestone = 'textures/cobblestone.jpeg'; let cobblestoneTexture = loader.load(cobblestone); let beigeCobblestone = 'textures/beige_cobblestone.jpeg'; let beigeCobblestoneTexture = loader.load(beigeCobblestone); cobblestoneTexture.wrapS = THREE.RepeatWrapping; cobblestoneTexture.wrapT = THREE.RepeatWrapping; beigeCobblestone.wrapS = THREE.RepeatWrapping; beigeCobblestone.wrapT = THREE.RepeatWrapping; cobblestoneTexture.repeat.x = 1; cobblestoneTexture.repeat.y = 1; beigeCobblestoneTexture.repeat.x = 1; beigeCobblestoneTexture.repeat.y = 1;
PHP
UTF-8
2,260
2.671875
3
[]
no_license
<?php namespace App\Presenters; use Nette; use Model; use Nette\Application\UI\Form; class UserPresenter extends BasePresenter { /** @var Model\User */ private $userRepository; /** @var Model\Authenticator */ private $authenticator; public function inject(Model\User $userRepository, Model\Authenticator $authenticator) { $this->userRepository = $userRepository; $this->authenticator = $authenticator; } protected function startup() { parent::startup(); if (!$this->getUser()->isLoggedIn()) { $this->redirect('Sign:in'); } } protected function createComponentPasswordForm() { $form = new Form(); $form->addPassword('oldPassword', 'Staré heslo:', 30) ->setAttribute('class', 'form-control') ->addRule(Form::FILLED, 'Je nutné zadat staré heslo.'); $form->addPassword('newPassword', 'Nové heslo:', 30) ->setAttribute('class', 'form-control') ->addRule(Form::MIN_LENGTH, 'Nové heslo musí mít alespoň %d znaků.', 6); $form->addPassword('confirmPassword', 'Potvrzení hesla:', 30) ->setAttribute('class', 'form-control') ->addRule(Form::FILLED, 'Nové heslo je nutné zadat ještě jednou pro potvrzení.') ->addRule(Form::EQUAL, 'Zadná hesla se musejí shodovat.', $form['newPassword']); $form->addSubmit('set', 'Změnit heslo')->setAttribute('class', 'btn btn-primary btn-flat'); $form->onSuccess[] = $this->passwordFormSubmitted; return $form; } public function passwordFormSubmitted(Form $form) { $values = $form->getValues(); $user = $this->getUser(); try { $this->authenticator->authenticate(array( $user->getIdentity()->username, $values->oldPassword )); $this->authenticator->setPassword($user->getId(), $values->newPassword); $this->flashMessage('Heslo bylo změněno.', 'success'); $this->redirect('Homepage:'); } catch (Nette\Security\AuthenticationException $e) { $form->addError('Zadané heslo není správné.'); } } }
Java
UTF-8
198
2.40625
2
[]
no_license
package Utilisateurs; public class User extends Member{ public User() { super(); } public User(String pseudo, String pwd, String mail, String role) { super(pseudo, pwd, mail, role); } }
JavaScript
UTF-8
2,194
2.5625
3
[]
no_license
/* jshint esversion : 6 */ // @root/api/tshirts.js const compte_associeAPi = function compte_associeAPi(connection) { const router = require("express").Router(); const compte_associeModel = require("../model/compte_associe")(connection); router.post('/compte_associe', (req, res) => { compte_associeModel.create((err, dataset) => { res.send(dataset); }, req.body); // post datas ici ... }); const solver = function solver(comptes) { const axios = require("axios"); return new Promise((resolve, reject) => { var finished = 0; comptes.forEach(compte => { axios.post('http://localhost:8888/fortnite', { pseudo: compte.name, platform: compte.platform }) .then(function(response) { console.log("ajax fortnite ok") compte.score = response.data.lifeTimeStats[6].value compte.wins = response.data.lifeTimeStats[8].value finished++; if (finished === comptes.length) resolve(comptes) }) }); }) }; router.get('/compte_associe', (req, res) => { console.log("ca get compte associe"); compte_associeModel.get( (err, comptes) => { solver(comptes).then(finalComptes => { console.log("finito") res.send(finalComptes) console.log(finalComptes) }) console.log("compte avec les stats", comptes); }, null); }); router.delete('/compte_associe', (req, res) => { compte_associeModel.remove((err, dataset) => { if (err) return res.status(500).send(err); return res.status(200).send(dataset); }, req.body.id); // tableau d'ids ici ... }); router.patch('/compte_associe', (req, res) => { compte_associeModel.update((err, dataset) => { if (err) return res.status(500).send(err); else return res.status(200).send(dataset); }, req.body); // un tableau d'ids ici ... }); return router; }; module.exports = compte_associeAPi;
C
UTF-8
774
3.703125
4
[]
no_license
/* Matt Fleetwood 3/4/2019 Portland, OR Assignment 5 for ECE 362 Makes 4 threads and prints their IDs out. Feel inspired. */ #include <stdio.h> #include <stdlib.h> #include <pthread.h> //Number of threads we are having for dinner #define NUM_THREADS 4 //Function to print the thread ID void *print_thread_ID(void *vargp) { long thread_ID = (long)vargp; printf("My thread ID is %u\n", thread_ID); return; } int main() { int loop_counter = 0; pthread_t some_threads[NUM_THREADS]; for(loop_counter = 0; loop_counter < NUM_THREADS; ++loop_counter) { pthread_create(&(some_threads[loop_counter]), NULL, print_thread_ID, &(some_threads[loop_counter])); pthread_join(some_threads[loop_counter], NULL); } return 1; }
Java
UTF-8
1,660
2.140625
2
[]
no_license
package ftn.uns.ac.rs.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import ftn.uns.ac.rs.model.KategorijaSmestaja; import ftn.uns.ac.rs.service.KategorijaSmestajaService; @RestController @RequestMapping("/kategorija-smestaja") public class KategorijaSmestajaController { @Autowired private KategorijaSmestajaService kategorijaSmestajaService; @GetMapping public ResponseEntity<List<KategorijaSmestaja>> getAll(){ if(kategorijaSmestajaService.getAll() == null) { return new ResponseEntity<List<KategorijaSmestaja>>(HttpStatus.NO_CONTENT); } return new ResponseEntity<List<KategorijaSmestaja>>(kategorijaSmestajaService.getAll(), HttpStatus.OK); } @GetMapping(value = "getAllSync") public ResponseEntity<List<KategorijaSmestaja>> getAllSync(){ return new ResponseEntity<List<KategorijaSmestaja>>(kategorijaSmestajaService.getAllSync(), HttpStatus.OK); } @GetMapping(value = "/{id}") public ResponseEntity<KategorijaSmestaja> getById(@PathVariable Long id){ if(kategorijaSmestajaService.getById(id) == null) { return new ResponseEntity<KategorijaSmestaja>(HttpStatus.NO_CONTENT); } return new ResponseEntity<KategorijaSmestaja>(kategorijaSmestajaService.getById(id), HttpStatus.OK); } }
C
UTF-8
325
3.6875
4
[]
no_license
#include <stdio.h> #include <math.h> double sum_powers_from(double x, double y, int n){ double res = 0; while(n>0)res += pow(x+((double)(--n)), y); return res; } int main(){ double x = 0; double y = 0; int n = 0; while(scanf("%lf%lf%i", &x, &y, &n) != EOF) printf("%f\n", sum_powers_from(x, y, n)); return 0; }
TypeScript
UTF-8
1,492
3.015625
3
[ "MIT" ]
permissive
import {add, collection, Doc, get, Ref, subcollection, update} from "typesaurus"; export class Game { countdownTime: number = 60 remainingTime: number = -1 score: Score[] = [] teams: Ref<Team>[] words: string[] = [] wordsDone: string[] = [] } export function getGame(gameRef: Ref<Game>): Promise<Doc<Game>> { return get(gameRef) } class Score { team: Ref<Team>; value: number = 0; constructor(team: Ref<Team>) { this.team = team } } class Team { name: string = "" members: string[] = []; teamRef: Ref<Team> constructor(name) { this.name = name this.members.push("Spieler 1") this.members.push("Spieler 2") } } export function createGame(): Promise<Ref<Game>> { const games = collection<Game>('games') const teams = subcollection<Team, Game>("teams", games) let game = new Game() return add(games, game).then(gameRef => { let team1 = new Team("team1") return add(teams(gameRef), team1).then(team1Ref => { let team2 = new Team("team2") return add(teams(gameRef), team2).then(team2Ref => { let score1 = new Score(team1Ref) let score2 = new Score(team2Ref) game.score.push(score1) game.score.push(score2) return update(gameRef, game).then(() => { return new Promise<Ref<Game>>(() => game) }); }) }); }) }
Java
UTF-8
707
2.625
3
[]
no_license
package com.homework.epam.service.impl; import com.homework.epam.annotation.Timed; import com.homework.epam.aspect.Logging; import com.homework.epam.service.Notebook; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; public class RandomNotebook implements Notebook { private static final Logger LOG = LogManager.getLogger(Logging.class.getName()); private String message = "Hello"; //random amount of repeating. From 1 to 9; private int repeat = (int) (1 + (Math.random() * 9)); public RandomNotebook() { } @Timed public void notateSomething() { for (int i = 0; i < repeat; i++) { LOG.info("Note = " + message); } } }
Python
UTF-8
182
2.859375
3
[]
no_license
# A program to test importing the calculateAreaofCircle function and using it with the integer 20 from reynLibrary import calculateAreaOfCircle print(calculateAreaOfCircle(20))
Java
UTF-8
582
1.976563
2
[]
no_license
package view.lcc.wyzsb.mvp.param; import java.io.Serializable; /** * Author: 梁铖城 * Email: 1038127753@qq.com * Date: 2017年04月25日20:55:10 * Description: 要发送的评论 */ public class SendComments implements Serializable{ private String content; private String oid; public String getOid() { return oid; } public void setOid(String oid) { this.oid = oid; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
TypeScript
UTF-8
263
2.765625
3
[]
no_license
export class ServerModel { public type: string; public name: string; public content: string; constructor(type : string, name: string, content: string){ type = this.type; name = this.name; content = this.content; } }
Java
UTF-8
200
1.671875
2
[]
no_license
package net.es.oscars.pss.enums; /** * Created by haniotak on 1/13/16. */ public enum ReviewStatus { REV_CONFIGURED, REV_CLEANED, REV_PARTIALLY_CONFIGURED, REV_PARTIALLY_CLEANED }
PHP
UTF-8
299
2.734375
3
[]
no_license
<?php require_once(dirname(__FILE__)."/../helpers/CModel.php"); class Country extends CModel { /** * **/ public static function getNames() { $allUsers = self::getAll(); $result = array(); foreach ($allUsers as $key => $value) { $result[] = (array) $value; } return $result; } }
Python
UTF-8
380
2.8125
3
[]
no_license
import pyodbc import dbpackage def update_data(): with dbpackage.connectdb() as con: sql_cmd = """ UPDATE person SET fullname='Johny', weight='70' WHERE id='2' """ try: con.execute(sql_cmd) print('update data success') except pyodbc.ProgrammingError: print('update data fail!') update_data()
Java
UTF-8
1,243
3.171875
3
[]
no_license
class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { int len1 = nums1.length; int len2 = nums2.length; int total = len1 + len2; boolean isOdd = total % 2 == 1; int idx = isOdd ? total / 2 + 1 : total / 2; int c1 = 0, c2 = 0; for (int i = 1; i <= total; i++) { int value; if (c1 >= nums1.length) { value = nums2[c2++]; } else if (c2 >= nums2.length) { value = nums1[c1++]; } else { value = nums1[c1] <= nums2[c2] ? nums1[c1++] : nums2[c2++]; } if (idx == i) { if (isOdd) { return (double) value; } else { int next; if (c1 >= nums1.length) { next = nums2[c2]; } else if (c2 >= nums2.length) { next = nums1[c1]; } else { next = nums1[c1] <= nums2[c2] ? nums1[c1] : nums2[c2]; } return ((double) value + (double) next) / 2; } } } return 0.0; } }
Java
UTF-8
488
2.90625
3
[]
no_license
package com.lrf.day001; public class SomeThread extends Thread { @Override public void run() { super.run(); try { while (true) { this.sleep(1000); System.out.println("========>"); } } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) { SomeThread oneThread = new SomeThread(); oneThread.start(); } }
Java
UTF-8
8,000
1.882813
2
[]
no_license
package com.example.musicok.service; import android.app.Notification; import android.content.Intent; import android.os.Bundle; import android.support.v4.media.MediaBrowserCompat; import android.support.v4.media.MediaDescriptionCompat; import android.support.v4.media.MediaMetadataCompat; import android.support.v4.media.RatingCompat; import android.support.v4.media.session.MediaSessionCompat; import android.support.v4.media.session.PlaybackStateCompat; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.content.ContextCompat; import androidx.media.MediaBrowserServiceCompat; import com.example.musicok.notification.MediaNotificationManager; import com.example.musicok.player.MediaPlayerAdapter; import com.example.musicok.player.PlaybackInfoListener; import com.example.musicok.util.MediaLibrary; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; /** * 音乐播放服务 */ public class MusicService extends MediaBrowserServiceCompat { private static final String TAG = "MusicService"; private MediaSessionCompat mSession; private MediaSessionCallback mSessionCallback; private MediaNotificationManager mNotificationManager; private MediaPlayerAdapter mPlayerAdapter; private boolean mServiceInStartedState; private List<MediaBrowserCompat.MediaItem> mMediaItemList = new ArrayList<>(); @Override public void onCreate() { super.onCreate(); Log.d(TAG, "onCreate: "); //创建MediaSession(会话) mSession = new MediaSessionCompat(this, "MusicService"); //创建MediaSessionCallback(会话回调) mSessionCallback = new MediaSessionCallback(); //绑定MediaSessionCallback(会话 绑定 会话回调) mSession.setCallback(mSessionCallback); //设置MediaSession Flag(会话 Flag) mSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_QUEUE_COMMANDS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS); //设置MediaSession Token(会话 Token) setSessionToken(mSession.getSessionToken()); //创建通知管理器(通知) mNotificationManager = new MediaNotificationManager(this); //创建播放器Adapter(实际播放音乐) mPlayerAdapter = new MediaPlayerAdapter(this, new MediaPlayerListener()); } @Override public void onDestroy() { Log.d(TAG, "onDestroy: "); //停止播放 mPlayerAdapter.stop(); //释放会话 mSession.release(); } @Nullable @Override public BrowserRoot onGetRoot(@NonNull String clientPackageName, int clientUid, @Nullable Bundle rootHints) { return new BrowserRoot("root", null); } @Override public void onLoadChildren(@NonNull String parentId, @NonNull Result<List<MediaBrowserCompat.MediaItem>> result) { Log.d(TAG, "onLoadChildren: "); result.sendResult(mMediaItemList); } //按钮UI控制播放器Player private class MediaSessionCallback extends MediaSessionCompat.Callback { private List<MediaMetadataCompat> mPlaylist = MediaLibrary.getInstance().getmMediaList(); private int mQueueIndex = 0; private MediaMetadataCompat mPreparedMedia; @Override public void onAddQueueItem(MediaDescriptionCompat description) { } @Override public void onRemoveQueueItem(MediaDescriptionCompat description) { } @Override public void onSkipToQueueItem(long id) { super.onSkipToQueueItem(id); if (id < 0) { id = 0; } mQueueIndex = id >= mPlaylist.size() ? mPlaylist.size() - 1 : (int) id; mPreparedMedia = null; onPlay(); } @Override public void onPrepare() { Log.d(TAG, "onPrepare: "); if (mPlaylist.isEmpty()) { // Nothing to play. return; } //TODO 通过binder获取需要播放音乐的地址 mPreparedMedia = mPlaylist.get(mQueueIndex); mSession.setMetadata(mPreparedMedia); if (!mSession.isActive()) { mSession.setActive(true); } } @Override public void onPlay() { Log.d(TAG, "onPlay: "); if (mPlaylist.isEmpty()) { return; } if (mPreparedMedia == null) { onPrepare(); } mPlayerAdapter.playFromUrl(mPreparedMedia); } @Override public void onPause() { Log.d(TAG, "onPause: "); mPlayerAdapter.pause(); } @Override public void onSetRating(RatingCompat rating) { float speed = rating.getPercentRating(); mPlayerAdapter.setSpeed(speed); } @Override public void onStop() { Log.d(TAG, "onStop: "); mPlayerAdapter.stop(); mSession.setActive(false); } @Override public void onSkipToPrevious() { mQueueIndex = mQueueIndex > 0 ? mQueueIndex - 1 : mPlaylist.size() - 1; mPreparedMedia = null; onPlay(); } @Override public void onSkipToNext() { mQueueIndex = (++mQueueIndex % mPlaylist.size()); mPreparedMedia = null; onPlay(); } @Override public void onFastForward() { mPlayerAdapter.syncState(); } @Override public void onSeekTo(long pos) { Log.d(TAG, "onSeekTo: "); mPlayerAdapter.seekTo(pos); } } public class MediaPlayerListener extends PlaybackInfoListener { private ServiceManager mServiceManager; public MediaPlayerListener() { mServiceManager = new ServiceManager(); } @Override public void onPlaybackStateChange(PlaybackStateCompat state) { //更改session状态 mSession.setPlaybackState(state); switch (state.getState()) { case PlaybackStateCompat.STATE_PLAYING: mServiceManager.moveServiceToStartedState(state); break; case PlaybackStateCompat.STATE_PAUSED: mServiceManager.updateNotificationForPause(state); break; case PlaybackStateCompat.STATE_STOPPED: mServiceManager.moveServiceOutOfStartedState(state); break; } } private class ServiceManager { public void moveServiceToStartedState(PlaybackStateCompat state) { Notification notification = mNotificationManager.getNotification(mPlayerAdapter.getCurrentMedia(), state, getSessionToken()); if (!mServiceInStartedState) { ContextCompat.startForegroundService(MusicService.this, new Intent(MusicService.this, MusicService.class)); mServiceInStartedState = true; } startForeground(MediaNotificationManager.NOTIFICATION_ID, notification); } public void updateNotificationForPause(PlaybackStateCompat state) { // stopForeground(false); Notification notification = mNotificationManager.getNotification(mPlayerAdapter.getCurrentMedia(), state, getSessionToken()); mNotificationManager.getNotifiManager().notify(MediaNotificationManager.NOTIFICATION_ID, notification); } public void moveServiceOutOfStartedState(PlaybackStateCompat state) { // stopForeground(true); stopSelf(); mServiceInStartedState = false; } } } }
Python
UTF-8
1,513
4
4
[]
no_license
# Hangman # https://knightlab.northwestern.edu/2014/06/05/five-mini-programming-projects-for-the-python-beginner/ import random guessLimit = 7 wordList = ("bowdoin", "bear", "graduate") secretWord = wordList[random.randint(0, len(wordList) - 1)] guesses = [] matchedCount = 0; # https://stackoverflow.com/questions/6142689/initialising-an-array-of-fixed-size-in-python secretWordRevealed = ['*'] * len(secretWord) print("The word I'm thinking of is " + str(len(secretWord)) + " characters long (lowercase).") while True: guess = input() if guess == 'quit': break if guess in guesses: print("You already guessed that letter.") elif len(guesses) >= guessLimit: print("You lose. The secret word was: " + secretWord) break else: index = 0 # https://stackoverflow.com/questions/3873361/finding-multiple-occurrences-of-a-string-within-a-string-in-python while index < len(secretWord): index = secretWord.find(guess, index) if index == -1: break else: secretWordRevealed[index] = guess matchedCount += 1 index += 1 if matchedCount == len(secretWord): print("You win! The secret word is " + secretWord + "!") break guesses.append(guess) print("Guesses: " + str(guesses)) print("Progress: " + str(secretWordRevealed))
Python
UTF-8
8,451
2.890625
3
[]
no_license
import logging from cassandra import ConsistencyLevel from cassandra.cluster import Cluster, BatchStatement from cassandra.query import SimpleStatement import collections import json import flask from flask import request, jsonify, abort class PythonCassandraExample: def __init__(self): self.cluster = None self.session = None self.keyspace = None self.log = None def __del__(self): self.cluster.shutdown() def createsession(self): self.cluster = Cluster(['localhost']) self.session = self.cluster.connect(self.keyspace) self.session.set_keyspace('ikea') def getsession(self): return self.session # How about Adding some log info to see what went wrong def setlogger(self): log = logging.getLogger() log.setLevel('INFO') handler = logging.StreamHandler() handler.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s")) log.addHandler(handler) self.log = log def create_tables(self): c_sql1 = """ CREATE TABLE IF NOT EXISTS INVENTORY (art_id int, name varchar, stock int, primary key(name,art_id)); """ c_sql2 = """ CREATE TABLE IF NOT EXISTS PRODUCTS (name varchar,art_id int,amount_of int, primary key(name,art_id)); """ self.session.execute(c_sql1) self.session.execute(c_sql2) self.log.info("Tables are Created !!!") # lets do some batch insert def insert_data(self): insert_sql = self.session.prepare("INSERT INTO employee (emp_id, ename , sal,city) VALUES (?,?,?,?)") batch = BatchStatement() batch.add(insert_sql, (5, 'Rajani', 2500, 'AMS')) batch.add(insert_sql, (6, 'RK', 3000, 'nld')) self.session.execute(batch) self.log.info('Batch Insert Completed') def select_data(self): rows = self.session.execute('select * from employee limit 10;') for row in rows: print(row.ename, row.sal) def update_data(self): self.session.execute('update employee set sal=4000 where emp_id=5;') def delete_data(self): self.session.execute('delete * from employee where emp_id=6;') app = flask.Flask(__name__) app.config["DEBUG"] = True #### This is shown in home screen @app.route('/', methods=['GET']) def home(): return '''<h1>API assingment from IKEA </h1> <p>A prototype API for Inventory demonstration.</p>''' #### Returns all the inventory in JSON format @app.route('/api/v1/resources/inventory/all', methods=['GET']) def inventory_all(): example1 = PythonCassandraExample() example1.createsession() rows = example1.session.execute('select * from inventory;') # Convert query to objects of key-value pairs objects_list = [] for row in rows: d = collections.OrderedDict() d["name"] = row[0] d["art_id"] = row[1] d["stock"] = row[2] objects_list.append(d) j = json.dumps(objects_list) print(j) return jsonify(j) #### Returns all the products in JSON format @app.route('/api/v1/resources/products/all', methods=['GET']) def products_all(): example1 = PythonCassandraExample() example1.createsession() rows = example1.session.execute('select * from products;') # Convert query to objects of key-value pairs objects_list = [] for row in rows: d = collections.OrderedDict() d["name"] = row[0] d["art_id"] = row[1] d["amount_of"] = row[2] objects_list.append(d) j = json.dumps(objects_list) print(j) return jsonify(j) #### Page not found handling for Exceptional cases @app.errorhandler(404) def page_not_found(e): return "<h1>404</h1><p>The resource could not be found.</p>", 404 @app.route('/api/v1/resources/products/create', methods=['PUT']) def create_products(): record = json.loads(request.data) print(record) example1 = PythonCassandraExample() example1.createsession() prd_ins_sql = example1.session.prepare("INSERT INTO products(name, art_id, amount_of ) VALUES (?,?,?)") batch = BatchStatement() for i in record['products']: name = i['name'] print(name) for a in i['contain_articles']: art_id = a['art_id'] amount_of = a['amount_of'] print(art_id) print(amount_of) batch.add(prd_ins_sql, (name,int(art_id), int(amount_of))) example1.session.execute(batch) return jsonify(record) @app.route('/api/v1/resources/products/update', methods=['POST']) def update_products(): record = json.loads(request.data) print(record) example1 = PythonCassandraExample() example1.createsession() update_sql = example1.session.prepare("UPDATE PRODUCTS SET AMOUNT_OF = ? WHERE NAME = ? AND ART_ID = ?") batch = BatchStatement() for i in record['products']: name = i['name'] print(name) for a in i['contain_articles']: art_id = a['art_id'] amount_of = a['amount_of'] print(art_id) print(amount_of) batch.add(update_sql, (int(amount_of), name, int(art_id))) example1.session.execute(batch) return jsonify(record) @app.route('/api/v1/resources/products/delete', methods=['DELETE']) def delte_products(): record = json.loads(request.data) print(record) example1 = PythonCassandraExample() example1.createsession() del_sql = example1.session.prepare("DELETE FROM PRODUCTS WHERE NAME = ? AND ART_ID = ?") batch = BatchStatement() for i in record['products']: name = i['name'] print(name) for a in i['contain_articles']: art_id = a['art_id'] amount_of = a['amount_of'] print(art_id) print(amount_of) batch.add(del_sql, (name, int(art_id))) example1.session.execute(batch) return jsonify(record) @app.route('/api/v1/resources/inventory/create', methods=['PUT']) def create_inventory(): record = json.loads(request.data) print(record) example1 = PythonCassandraExample() example1.createsession() prd_ins_sql = example1.session.prepare("INSERT INTO inventory(art_id, name, stock ) VALUES (?,?,?)") batch = BatchStatement() for i in record['inventory']: art_id = i['art_id'] name = i['name'] stock = i['stock'] print(art_id) print(name) print(stock) batch.add(prd_ins_sql, (int(art_id), name, int(stock))) example1.session.execute(batch) return jsonify(record) @app.route('/api/v1/resources/inventory/update', methods=['POST']) def update_inventory(): record = json.loads(request.data) print(record) example1 = PythonCassandraExample() example1.createsession() update_sql = example1.session.prepare("UPDATE INVENTORY SET STOCK = ? WHERE NAME = ? AND ART_ID = ?") batch = BatchStatement() for i in record['inventory']: art_id = i['art_id'] name = i['name'] stock = i['stock'] print(art_id) print(name) print(stock) batch.add(update_sql, (int(stock), name, int(art_id))) example1.session.execute(batch) return jsonify(record) @app.route('/api/v1/resources/inventory/delete', methods=['DELETE']) def delte_inventory(): record = json.loads(request.data) print(record) example1 = PythonCassandraExample() example1.createsession() del_sql = example1.session.prepare("DELETE FROM INVENTORY WHERE NAME = ? AND ART_ID = ?") batch = BatchStatement() for i in record['inventory']: art_id = i['art_id'] name = i['name'] stock = i['stock'] print(art_id) print(name) print(stock) batch.add(del_sql, (name, int(art_id))) example1.session.execute(batch) return jsonify(record) if __name__ == '__main__': example1 = PythonCassandraExample() example1.createsession() example1.setlogger() example1.create_tables() app.run()
C#
UTF-8
765
2.671875
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BindDataToWindows { class DataPoint : INotifyPropertyChanged { private string _value; public string Value { get { return _value; } set { _value = value; OnPropertyChanged("Value"); } } #region INotifyPropertyChanged Members protected virtual void OnPropertyChanged(string propertyName) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged = delegate { }; #endregion } }
Java
UTF-8
2,003
2.046875
2
[]
no_license
package com.paulotec.virtualize.services; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; @Configuration @EnableWebSecurity @Order(1) public class SecurityCliente extends WebSecurityConfigurerAdapter { @Autowired private DataSource dataSource; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception{ auth.jdbcAuthentication().dataSource(dataSource) .usersByUsernameQuery( "select username as username, password as password, 1 as enable from table_Cliente where username=?") .authoritiesByUsernameQuery( "select username as username, 'cliente' as authority from table_Cliente where username=?") .passwordEncoder(new BCryptPasswordEncoder()); } @Override protected void configure(HttpSecurity http) throws Exception{ http.antMatcher("/finalizarCompra/**").authorizeRequests().anyRequest().hasAnyAuthority("cliente") .and().csrf().disable().formLogin().loginPage("/loginCliente").permitAll() .failureUrl("/loginCliente").loginProcessingUrl("/finalizarCompra/login") .defaultSuccessUrl("/finalizarCompra").usernameParameter("username").passwordParameter("password") .and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")) .logoutSuccessUrl("/").permitAll().and().exceptionHandling().accessDeniedPage("/negado"); } }
Java
UTF-8
3,292
1.726563
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Licensed under the Zeebe Community License 1.1. You may not use this file * except in compliance with the Zeebe Community License 1.1. */ package io.camunda.zeebe.exporter; import static org.assertj.core.api.Assertions.assertThatThrownBy; import io.camunda.zeebe.exporter.api.ExporterException; import io.camunda.zeebe.protocol.record.Record; import io.camunda.zeebe.test.util.TestUtil; import io.camunda.zeebe.test.util.record.RecordingExporter; import org.junit.Test; public class ElasticsearchExporterConfigurationIT extends AbstractElasticsearchExporterIntegrationTestCase { @Test public void shouldPropagateNumberOfShardsAndReplicas() { // given elastic.start(); configuration = getDefaultConfiguration(); // change number of shards and replicas configuration.index.setNumberOfShards(5); configuration.index.setNumberOfReplicas(4); esClient = createElasticsearchClient(configuration); // when exporterBrokerRule.configure("es", ElasticsearchExporter.class, configuration); exporterBrokerRule.start(); exporterBrokerRule.publishMessage("message", "123"); // then RecordingExporter.messageRecords() .withCorrelationKey("123") .withName("message") .forEach(r -> TestUtil.waitUntil(() -> wasExported(r))); assertIndexSettings(); } @Test public void shouldFailWhenNumberOfShardsIsLessOne() { // given elastic.start(); configuration = getDefaultConfiguration(); // change number of shards configuration.index.setNumberOfShards(-1); esClient = createElasticsearchClient(configuration); // when exporterBrokerRule.configure("es", ElasticsearchExporter.class, configuration); // then assertThatThrownBy(() -> exporterBrokerRule.start()) .isInstanceOf(IllegalStateException.class) .getRootCause() .isInstanceOf(ExporterException.class) .hasMessageContaining("numberOfShards must be >= 1. Current value: -1"); } @Test public void shouldFailWhenNumberOfReplicasIsLessZero() { // given elastic.start(); configuration = getDefaultConfiguration(); // change number replicas configuration.index.setNumberOfReplicas(-1); esClient = createElasticsearchClient(configuration); // when exporterBrokerRule.configure("es", ElasticsearchExporter.class, configuration); // then assertThatThrownBy(() -> exporterBrokerRule.start()) .isInstanceOf(IllegalStateException.class) .getRootCause() .isInstanceOf(ExporterException.class) .hasMessageContaining("numberOfReplicas must be >= 0. Current value: -1"); } private boolean wasExported(final Record<?> record) { try { return esClient.getDocument(record) != null; } catch (final Exception e) { // suppress exception in order to retry and see if it was exported yet or not // the exception can occur since elastic may not be ready yet, or maybe the index hasn't been // created yet, etc. } return false; } }
C#
UTF-8
3,974
2.625
3
[]
no_license
using Client; using DAL; using DAL.Entity; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace Server { class Program { private const int port = 2020; private static IPAddress ip; private static TcpListener server; static void Main(string[] args) { StartService(); Console.Title = "Server" + server.Server.LocalEndPoint; } private static void StartService() { int index = 0; var dbHelper = new DBHelper(); ip = (Dns.GetHostEntry(Dns.GetHostName()).AddressList[0]); server = new TcpListener(ip, port); server.Start(); string res; while (true) { try { Console.WriteLine("Waiting for connecting..."); var client = server.AcceptTcpClient(); Console.WriteLine("Connected"); using (var stream = client.GetStream()) { var serializer1 = new XmlSerializer(typeof(string)); res = (string)serializer1.Deserialize(stream); Console.WriteLine(res); } client = server.AcceptTcpClient(); using (var stream = client.GetStream()) { if (res == "Add") { var serializer2 = new XmlSerializer(typeof(ContactDTO)); var contact = (ContactDTO)serializer2.Deserialize(stream); Contact c = new Contact { Email = contact.Email, Name = contact.Name, Phone = contact.Phone }; dbHelper.AddContact(c); } else if (res == "Load") { var serializer = new XmlSerializer(typeof(List<string>)); var res2 = dbHelper.GetName(); serializer.Serialize(stream, res2); } else if (res == "Delete") { var serializer2 = new XmlSerializer(typeof(int)); index = (int)serializer2.Deserialize(stream); Contact c = dbHelper.GetContact(index); dbHelper.DeleteContact(c); } else if (res == "SelectionIndex") { var serializer2 = new XmlSerializer(typeof(int)); index = (int)serializer2.Deserialize(stream); } else { Contact c = dbHelper.GetContact(index); ContactDTO cD = new ContactDTO() { Email = c.Email, Name = c.Name, Phone = c.Phone }; var serializer = new XmlSerializer(typeof(ContactDTO)); serializer.Serialize(stream, cD); } } } catch (SocketException ex) { Console.WriteLine(ex.Message); } } } } }
Python
UTF-8
1,661
3.421875
3
[ "BSD-3-Clause" ]
permissive
"""Showcases *Lightness* computations.""" import numpy as np import colour from colour.utilities import message_box message_box('"Lightness" Computations') xyY = np.array([0.4316, 0.3777, 0.1008]) message_box( f'Computing "Lightness" "CIE L*a*b*" reference value for given "CIE xyY" ' f"colourspace values:\n\n\t{xyY}" ) print(np.ravel(colour.XYZ_to_Lab(colour.xyY_to_XYZ(xyY)))[0]) print("\n") Y = 12.19722535 message_box( f'Computing "Lightness" using ' f'"Glasser, Mckinney, Reilly and Schnelle (1958)" method for given ' f'"luminance" value:\n\n\t{Y}' ) print(colour.lightness(Y, method="Glasser 1958")) print(colour.colorimetry.lightness_Glasser1958(Y)) print("\n") message_box( f'Computing "Lightness" using "Wyszecki (1963)" method for given ' f'"luminance" value:\n\n\t{Y}' ) print(colour.lightness(Y, method="Wyszecki 1963")) print(colour.colorimetry.lightness_Wyszecki1963(Y)) print("\n") message_box( f'Computing "Lightness" using "Fairchild and Wyble (2010)" method for ' f'given "luminance" value:\n\n\t{Y}' ) print(colour.lightness(Y, method="Fairchild 2010")) print(colour.colorimetry.lightness_Fairchild2010(Y / 100.0)) print("\n") message_box( f'Computing "Lightness" using "Fairchild and Chen (2011)" method for ' f'given "luminance" value:\n\n\t{Y}' ) print(colour.lightness(Y, method="Fairchild 2011")) print(colour.colorimetry.lightness_Fairchild2011(Y / 100.0)) print("\n") message_box( f'Computing "Lightness" using "CIE 1976" method for given "luminance" ' f"value:\n\n\t{Y}" ) print(colour.lightness(Y, method="CIE 1976")) print(colour.colorimetry.lightness_CIE1976(Y))
C#
UTF-8
1,183
3.40625
3
[ "WTFPL", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
using System; using System.Collections.Generic; using System.Text; namespace GetFingerprintExample { class Program { static void Main(string[] args) { Console.WriteLine("Get X.509 certidicate fingerprint example"); Console.WriteLine(); if (args.Length < 2) { Console.WriteLine("Use:"); Console.WriteLine("getfingerprintexample.exe <certificate_file> <hash_algorithm>"); Console.WriteLine("Algorithms: MD5, SHA1, SHA256, SHA384, SHA512"); Console.WriteLine(); Console.WriteLine("Press ENTER"); Console.ReadLine(); return; } string FileName = args[0]; string Algorithm = args[1]; string result = Fingerpint.GetCertFingerprint(FileName, Algorithm); Console.WriteLine("File: " + FileName); Console.WriteLine("Algorithm: " + Algorithm); Console.WriteLine("Fingerprint: " + result); Console.WriteLine(); Console.WriteLine("Press ENTER"); Console.ReadLine(); } } }
Go
UTF-8
3,596
2.6875
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package handlers_test import ( "errors" "net/http" "time" "code.cloudfoundry.org/lager" "code.cloudfoundry.org/rep" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("State", func() { var ( repState rep.CellState requestLatency time.Duration ) BeforeEach(func() { repState = rep.CellState{ RootFSProviders: rep.RootFSProviders{"docker": rep.ArbitraryRootFSProvider{}}, } requestLatency = 50 * time.Millisecond fakeLocalRep.StateStub = func(logger lager.Logger) (rep.CellState, bool, error) { time.Sleep(requestLatency) return repState, true, nil } }) It("it returns whatever the state call returns", func() { status, body := Request(rep.StateRoute, nil, nil) Expect(status).To(Equal(http.StatusOK)) Expect(body).To(MatchJSON(JSONFor(repState))) Expect(fakeLocalRep.StateCallCount()).To(Equal(1)) }) It("emits the request metrics", func() { Request(rep.StateRoute, nil, nil) Expect(fakeRequestMetrics.IncrementRequestsStartedCounterCallCount()).To(Equal(1)) calledRequestType, delta := fakeRequestMetrics.IncrementRequestsStartedCounterArgsForCall(0) Expect(delta).To(Equal(1)) Expect(calledRequestType).To(Equal("State")) Expect(fakeRequestMetrics.IncrementRequestsInFlightCounterCallCount()).To(Equal(1)) calledRequestType, delta = fakeRequestMetrics.IncrementRequestsInFlightCounterArgsForCall(0) Expect(delta).To(Equal(1)) Expect(calledRequestType).To(Equal("State")) Expect(fakeRequestMetrics.DecrementRequestsInFlightCounterCallCount()).To(Equal(1)) calledRequestType, delta = fakeRequestMetrics.DecrementRequestsInFlightCounterArgsForCall(0) Expect(delta).To(Equal(1)) Expect(calledRequestType).To(Equal("State")) Expect(fakeRequestMetrics.UpdateLatencyCallCount()).To(Equal(1)) calledRequestType, calledLatency := fakeRequestMetrics.UpdateLatencyArgsForCall(0) Expect(calledRequestType).To(Equal("State")) Expect(calledLatency).To(BeNumerically("~", requestLatency, 5*time.Millisecond)) Expect(fakeRequestMetrics.IncrementRequestsSucceededCounterCallCount()).To(Equal(1)) calledRequestType, delta = fakeRequestMetrics.IncrementRequestsSucceededCounterArgsForCall(0) Expect(delta).To(Equal(1)) Expect(calledRequestType).To(Equal("State")) Expect(fakeRequestMetrics.IncrementRequestsFailedCounterCallCount()).To(Equal(0)) }) Context("when the state call is not healthy", func() { BeforeEach(func() { fakeLocalRep.StateReturns(repState, false, nil) }) It("returns a StatusServiceUnavailable", func() { status, body := Request(rep.StateRoute, nil, nil) Expect(status).To(Equal(http.StatusServiceUnavailable)) Expect(body).To(MatchJSON(JSONFor(repState))) Expect(fakeLocalRep.StateCallCount()).To(Equal(1)) }) }) Context("when the state call fails", func() { BeforeEach(func() { fakeLocalRep.StateReturns(rep.CellState{}, false, errors.New("boom")) }) It("fails", func() { status, body := Request(rep.StateRoute, nil, nil) Expect(status).To(Equal(http.StatusInternalServerError)) Expect(body).To(BeEmpty()) Expect(fakeLocalRep.StateCallCount()).To(Equal(1)) }) It("emits the failed request metrics", func() { Request(rep.StateRoute, nil, nil) Expect(fakeRequestMetrics.IncrementRequestsSucceededCounterCallCount()).To(Equal(0)) Expect(fakeRequestMetrics.IncrementRequestsFailedCounterCallCount()).To(Equal(1)) calledRequestType, delta := fakeRequestMetrics.IncrementRequestsFailedCounterArgsForCall(0) Expect(delta).To(Equal(1)) Expect(calledRequestType).To(Equal("State")) }) }) })
Python
UTF-8
780
2.75
3
[]
no_license
# coding: utf-8 import torch import os, json def analyze(ckpt_path, out_path, data, args): model = torch.load(ckpt_path) # Load model from checkpoint. weight = model.linear.weight # Weights of words. if not os.path.exists(out_path): os.mkdir(out_path) f = open(os.path.join(out_path, "word_weight.json"), "w") for wid in range(len(weight[0])): # Word id. word = data.idx2word[wid] # Word. words_js = {"word": word} # Output for a word. for label_id in data.idx2label: label = data.idx2label[label_id] # Label. word_w = weight[label_id][wid].item() # Word weight. words_js[label] = word_w f.write(json.dumps(words_js) + "\n") f.close()
Swift
UTF-8
958
2.6875
3
[]
no_license
// // SUSView.swift // Questionaire-tool // // Created by Celina on 05.08.19. // Copyright © 2019 CelinaLandgraf. All rights reserved. // import SwiftUI struct SUSView: View { @ObservedObject var model: Model let susIndex: Int var body: some View { ScrollView { VStack { Text("Wie sehr treffen folgende Aussagen bezüglich der gerade genutzten App zu? ") .font(.headline) Spacer().padding(.top) ForEach(0...9, id: \.self) { index in Group { LikertScale(model: self.model, id: index, typeId: "SUS_\(self.susIndex)") Spacer().padding(.top) } } } } } } #if DEBUG struct SUSView_Previews: PreviewProvider { static var previews: some View { SUSView(model: Model(), susIndex: 1) } } #endif
Java
UTF-8
561
1.976563
2
[]
no_license
package com.lxl.interfaceevent.dagger; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.lxl.interfaceevent.R; public class DaggerTestSecondActivity extends AppCompatActivity { private TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dagger_test_second); tv = (TextView) findViewById(R.id.tv); // tv.setText("注解值:"+menu.toString()); } }
Python
UTF-8
70
2.796875
3
[]
no_license
letters=["a","b","c","d","e"] for letter in letters: print letter
Java
GB18030
1,518
3.78125
4
[]
no_license
package api; /* * ȼڣ *javac: public class Student extends Object * *ͨǰഴ equalshashCode,toString ֤ StudentĸObject * */ public class Student { private int id;//ѧ private String name;// private int age;// public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Student() { super(); } public Student(int id, String name, int age) { super(); this.id = id; this.name = name; this.age = age; } /* * д֮equals Ƚ϶ * 1.Ƚĵַ * 2.ȽΨһʶǷ ôҲͬһ * * **/ @Override public boolean equals(Object obj) { //ȽĵַǷͬ ַͬĶضͬһ if (this == obj) return true; if(obj instanceof Student){ Student stu =(Student)obj; return stu.id == this.id; //Ƚѧѧ } return false; } public int hashCode(){ return this.id; //ѧѧΪhash } public String toString(){ return ""+id+","+name; } }
Java
WINDOWS-1252
679
3.265625
3
[]
no_license
package th.part_15_Generic.chapter_08_ErasedCompnesate._02; public class GenericArray<T> { private T[] t; @SuppressWarnings("unchecked")//עjavac -Xlint:unchecked GenericArray.java public GenericArray(int size){ t=(T[]) new Object[size]; } public void put(int index,T item){ t[index]=item; } public T get(int index){ return t[index]; } public T[] rep(){ return t; } public static void main(String[] args) { GenericArray<Integer> gia=new GenericArray<Integer>(10); //ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer // Integer[] ia=gia.rep(); Object[] obj=gia.rep(); } }
C++
UTF-8
910
3.046875
3
[ "MIT" ]
permissive
#include <iostream> #include <vector> #include <algorithm> #include <ctime> #include <cmath> int main(void) { unsigned long long number; std::cin >> number; std::vector<unsigned long long> answer(number + 1); clock_t t; t = clock(); for(size_t i = 2; i <= number; i++) { if (i % 3 == 0 && answer[i] > answer[i / 3]) { answer[i] = answer[i / 3]; } if (i % 2 == 0 && answer[i] > answer[i / 2]) { answer[i] = answer[i / 2]; } answer[i] += i; } std::cout << "time for DP is " << (float)t/CLOCKS_PER_SEC << '\n'; t = clock(); std::vector<unsigned long long> lolz(number); size_t sizes = lolz.size(); for (size_t i = 1; i < sizes; i++) { lolz[i] = (i + 2 * 3) + 2; lolz[i] += lolz[(size_t)clock() % (i + 3)]; } std::cout << "time for naive is " << (float)t/CLOCKS_PER_SEC / number * std::pow(2, number)<< '\n'; return 0; }
Markdown
UTF-8
18,949
2.578125
3
[]
no_license
--- title: Azure Key Vault logging | Microsoft Docs description: Use this tutorial to help you get started with Azure Key Vault logging. services: key-vault documentationcenter: '' author: barclayn manager: barbkess tags: azure-resource-manager ms.assetid: 43f96a2b-3af8-4adc-9344-bc6041fface8 ms.service: key-vault ms.workload: identity ms.tgt_pltfrm: na ms.topic: conceptual ms.date: 01/18/2019 ms.author: barclayn #Customer intent: As an Azure Key Vault administrator, I want to enable logging so I can monitor how my key vaults are accessed. --- # Azure Key Vault logging [!INCLUDE [updated-for-az](../../includes/updated-for-az.md)] After you create one or more key vaults, you'll likely want to monitor how and when your key vaults are accessed, and by whom. You can do this by enabling logging for Azure Key Vault, which saves information in an Azure storage account that you provide. A new container named **insights-logs-auditevent** is automatically created for your specified storage account. You can use this same storage account for collecting logs for multiple key vaults. You can access your logging information 10 minutes (at most) after the key vault operation. In most cases, it will be quicker than this. It's up to you to manage your logs in your storage account: * Use standard Azure access control methods to secure your logs by restricting who can access them. * Delete logs that you no longer want to keep in your storage account. Use this tutorial to help you get started with Azure Key Vault logging. You'll create a storage account, enable logging, and interpret the collected log information. > [!NOTE] > This tutorial does not include instructions for how to create key vaults, keys, or secrets. For this information, see [What is Azure Key Vault?](key-vault-overview.md). Or, for cross-platform Azure CLI instructions, see [this equivalent tutorial](key-vault-manage-with-cli2.md). > > This article provides Azure PowerShell instructions for updating diagnostic logging. You can also update diagnostic logging by using Azure Monitor in the **Diagnostic logs** section of the Azure portal. > For overview information about Key Vault, see [What is Azure Key Vault?](key-vault-whatis.md). For information about where Key Vault is available, see the [pricing page](https://azure.microsoft.com/pricing/details/key-vault/). ## Prerequisites To complete this tutorial, you must have the following: * An existing key vault that you have been using. * Azure PowerShell, minimum version of 1.0.0. To install Azure PowerShell and associate it with your Azure subscription, see [How to install and configure Azure PowerShell](/powershell/azure/overview). If you have already installed Azure PowerShell and don't know the version, from the Azure PowerShell console, enter `$PSVersionTable.PSVersion`. * Sufficient storage on Azure for your Key Vault logs. ## <a id="connect"></a>Connect to your key vault subscription The first step in setting up key logging is to point Azure PowerShell to the key vault that you want to log. Start an Azure PowerShell session and sign in to your Azure account by using the following command: ```PowerShell Connect-AzAccount ``` In the pop-up browser window, enter your Azure account user name and password. Azure PowerShell gets all the subscriptions that are associated with this account. By default, PowerShell uses the first one. You might have to specify the subscription that you used to create your key vault. Enter the following command to see the subscriptions for your account: ```PowerShell Get-AzSubscription ``` Then, to specify the subscription that's associated with the key vault you'll be logging, enter: ```PowerShell Set-AzContext -SubscriptionId <subscription ID> ``` Pointing PowerShell to the right subscription is an important step, especially if you have multiple subscriptions associated with your account. For more information about configuring Azure PowerShell, see [How to install and configure Azure PowerShell](/powershell/azure/overview). ## <a id="storage"></a>Create a storage account for your logs Although you can use an existing storage account for your logs, we'll create a storage account that will be dedicated to Key Vault logs. For convenience for when we have to specify this later, we'll store the details in a variable named **sa**. For additional ease of management, we'll also use the same resource group as the one that contains the key vault. From the [getting-started tutorial](key-vault-get-started.md), this resource group is named **ContosoResourceGroup**, and we'll continue to use the East Asia location. Replace these values with your own, as applicable: ```PowerShell $sa = New-AzStorageAccount -ResourceGroupName ContosoResourceGroup -Name contosokeyvaultlogs -Type Standard_LRS -Location 'East Asia' ``` > [!NOTE] > If you decide to use an existing storage account, it must use the same subscription as your key vault. And it must use the Azure Resource Manager deployment model, rather than the classic deployment model. > > ## <a id="identify"></a>Identify the key vault for your logs In the [getting-started tutorial](key-vault-get-started.md), the key vault name was **ContosoKeyVault**. We'll continue to use that name and store the details in a variable named **kv**: ```PowerShell $kv = Get-AzKeyVault -VaultName 'ContosoKeyVault' ``` ## <a id="enable"></a>Enable logging To enable logging for Key Vault, we'll use the **Set-AzDiagnosticSetting** cmdlet, together with the variables that we created for the new storage account and the key vault. We'll also set the **-Enabled** flag to **$true** and set the category to **AuditEvent** (the only category for Key Vault logging): ```PowerShell Set-AzDiagnosticSetting -ResourceId $kv.ResourceId -StorageAccountId $sa.Id -Enabled $true -Category AuditEvent ``` The output looks like this: StorageAccountId : /subscriptions/<subscription-GUID>/resourceGroups/ContosoResourceGroup/providers/Microsoft.Storage/storageAccounts/ContosoKeyVaultLogs ServiceBusRuleId : StorageAccountName : Logs Enabled : True Category : AuditEvent RetentionPolicy Enabled : False Days : 0 This output confirms that logging is now enabled for your key vault, and it will save information to your storage account. Optionally, you can set a retention policy for your logs such that older logs are automatically deleted. For example, set retention policy by setting the **-RetentionEnabled** flag to **$true**, and set the **-RetentionInDays** parameter to **90** so that logs older than 90 days are automatically deleted. ```PowerShell Set-AzDiagnosticSetting -ResourceId $kv.ResourceId -StorageAccountId $sa.Id -Enabled $true -Category AuditEvent -RetentionEnabled $true -RetentionInDays 90 ``` What's logged: * All authenticated REST API requests, including failed requests as a result of access permissions, system errors, or bad requests. * Operations on the key vault itself, including creation, deletion, setting key vault access policies, and updating key vault attributes such as tags. * Operations on keys and secrets in the key vault, including: * Creating, modifying, or deleting these keys or secrets. * Signing, verifying, encrypting, decrypting, wrapping and unwrapping keys, getting secrets, and listing keys and secrets (and their versions). * Unauthenticated requests that result in a 401 response. Examples are requests that don't have a bearer token, that are malformed or expired, or that have an invalid token. ## <a id="access"></a>Access your logs Key Vault logs are stored in the **insights-logs-auditevent** container in the storage account that you provided. To view the logs, you have to download blobs. First, create a variable for the container name. You'll use this variable throughout the rest of the walkthrough. ```PowerShell $container = 'insights-logs-auditevent' ``` To list all the blobs in this container, enter: ```PowerShell Get-AzStorageBlob -Container $container -Context $sa.Context ``` The output looks similar to this: ``` Container Uri: https://contosokeyvaultlogs.blob.core.windows.net/insights-logs-auditevent Name - - - resourceId=/SUBSCRIPTIONS/361DA5D4-A47A-4C79-AFDD-XXXXXXXXXXXX/RESOURCEGROUPS/CONTOSORESOURCEGROUP/PROVIDERS/MICROSOFT.KEYVAULT/VAULTS/CONTOSOKEYVAULT/y=2016/m=01/d=05/h=01/m=00/PT1H.json resourceId=/SUBSCRIPTIONS/361DA5D4-A47A-4C79-AFDD-XXXXXXXXXXXX/RESOURCEGROUPS/CONTOSORESOURCEGROUP/PROVIDERS/MICROSOFT.KEYVAULT/VAULTS/CONTOSOKEYVAULT/y=2016/m=01/d=04/h=02/m=00/PT1H.json resourceId=/SUBSCRIPTIONS/361DA5D4-A47A-4C79-AFDD-XXXXXXXXXXXX/RESOURCEGROUPS/CONTOSORESOURCEGROUP/PROVIDERS/MICROSOFT.KEYVAULT/VAULTS/CONTOSOKEYVAULT/y=2016/m=01/d=04/h=18/m=00/PT1H.json ``` As you can see from this output, the blobs follow a naming convention: `resourceId=<ARM resource ID>/y=<year>/m=<month>/d=<day of month>/h=<hour>/m=<minute>/filename.json` The date and time values use UTC. Because you can use the same storage account to collect logs for multiple resources, the full resource ID in the blob name is useful to access or download just the blobs that you need. But before we do that, we'll first cover how to download all the blobs. Create a folder to download the blobs. For example: ```PowerShell New-Item -Path 'C:\Users\username\ContosoKeyVaultLogs' -ItemType Directory -Force ``` Then get a list of all blobs: ```PowerShell $blobs = Get-AzStorageBlob -Container $container -Context $sa.Context ``` Pipe this list through **Get-AzStorageBlobContent** to download the blobs to the destination folder: ```PowerShell $blobs | Get-AzStorageBlobContent -Destination C:\Users\username\ContosoKeyVaultLogs' ``` When you run this second command, the **/** delimiter in the blob names creates a full folder structure under the destination folder. You'll use this structure to download and store the blobs as files. To selectively download blobs, use wildcards. For example: * If you have multiple key vaults and want to download logs for just one key vault, named CONTOSOKEYVAULT3: ```PowerShell Get-AzStorageBlob -Container $container -Context $sa.Context -Blob '*/VAULTS/CONTOSOKEYVAULT3 ``` * If you have multiple resource groups and want to download logs for just one resource group, use `-Blob '*/RESOURCEGROUPS/<resource group name>/*'`: ```PowerShell Get-AzStorageBlob -Container $container -Context $sa.Context -Blob '*/RESOURCEGROUPS/CONTOSORESOURCEGROUP3/*' ``` * If you want to download all the logs for the month of January 2019, use `-Blob '*/year=2019/m=01/*'`: ```PowerShell Get-AzStorageBlob -Container $container -Context $sa.Context -Blob '*/year=2016/m=01/*' ``` You're now ready to start looking at what's in the logs. But before we move on to that, you should know two more commands: * To query the status of diagnostic settings for your key vault resource: `Get-AzDiagnosticSetting -ResourceId $kv.ResourceId` * To disable logging for your key vault resource: `Set-AzDiagnosticSetting -ResourceId $kv.ResourceId -StorageAccountId $sa.Id -Enabled $false -Category AuditEvent` ## <a id="interpret"></a>Interpret your Key Vault logs Individual blobs are stored as text, formatted as a JSON blob. Let's look at an example log entry. Run this command: ```PowerShell Get-AzKeyVault -VaultName 'contosokeyvault'` ``` It returns a log entry similar to this one: ```json { "records": [ { "time": "2016-01-05T01:32:01.2691226Z", "resourceId": "/SUBSCRIPTIONS/361DA5D4-A47A-4C79-AFDD-XXXXXXXXXXXX/RESOURCEGROUPS/CONTOSOGROUP/PROVIDERS/MICROSOFT.KEYVAULT/VAULTS/CONTOSOKEYVAULT", "operationName": "VaultGet", "operationVersion": "2015-06-01", "category": "AuditEvent", "resultType": "Success", "resultSignature": "OK", "resultDescription": "", "durationMs": "78", "callerIpAddress": "104.40.82.76", "correlationId": "", "identity": {"claim":{"http://schemas.microsoft.com/identity/claims/objectidentifier":"d9da5048-2737-4770-bd64-XXXXXXXXXXXX","http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn":"live.com#username@outlook.com","appid":"1950a258-227b-4e31-a9cf-XXXXXXXXXXXX"}}, "properties": {"clientInfo":"azure-resource-manager/2.0","requestUri":"https://control-prod-wus.vaultcore.azure.net/subscriptions/361da5d4-a47a-4c79-afdd-XXXXXXXXXXXX/resourcegroups/contosoresourcegroup/providers/Microsoft.KeyVault/vaults/contosokeyvault?api-version=2015-06-01","id":"https://contosokeyvault.vault.azure.net/","httpStatusCode":200} } ] } ``` The following table lists the field names and descriptions: | Field name | Description | | --- | --- | | **time** |Date and time in UTC. | | **resourceId** |Azure Resource Manager resource ID. For Key Vault logs, this is always the Key Vault resource ID. | | **operationName** |Name of the operation, as documented in the next table. | | **operationVersion** |REST API version requested by the client. | | **category** |Type of result. For Key Vault logs, **AuditEvent** is the single, available value. | | **resultType** |Result of the REST API request. | | **resultSignature** |HTTP status. | | **resultDescription** |Additional description about the result, when available. | | **durationMs** |Time it took to service the REST API request, in milliseconds. This does not include the network latency, so the time you measure on the client side might not match this time. | | **callerIpAddress** |IP address of the client that made the request. | | **correlationId** |An optional GUID that the client can pass to correlate client-side logs with service-side (Key Vault) logs. | | **identity** |Identity from the token that was presented in the REST API request. This is usually a "user," a "service principal," or the combination "user+appId," as in the case of a request that results from an Azure PowerShell cmdlet. | | **properties** |Information that varies based on the operation (**operationName**). In most cases, this field contains client information (the user agent string passed by the client), the exact REST API request URI, and the HTTP status code. In addition, when an object is returned as a result of a request (for example, **KeyCreate** or **VaultGet**), it also contains the key URI (as "id"), vault URI, or secret URI. | The **operationName** field values are in *ObjectVerb* format. For example: * All key vault operations have the `Vault<action>` format, such as `VaultGet` and `VaultCreate`. * All key operations have the `Key<action>` format, such as `KeySign` and `KeyList`. * All secret operations have the `Secret<action>` format, such as `SecretGet` and `SecretListVersions`. The following table lists the **operationName** values and corresponding REST API commands: | operationName | REST API command | | --- | --- | | **Authentication** |Authenticate via Azure Active Directory endpoint | | **VaultGet** |[Get information about a key vault](https://msdn.microsoft.com/library/azure/mt620026.aspx) | | **VaultPut** |[Create or update a key vault](https://msdn.microsoft.com/library/azure/mt620025.aspx) | | **VaultDelete** |[Delete a key vault](https://msdn.microsoft.com/library/azure/mt620022.aspx) | | **VaultPatch** |[Update a key vault](https://msdn.microsoft.com/library/azure/mt620025.aspx) | | **VaultList** |[List all key vaults in a resource group](https://msdn.microsoft.com/library/azure/mt620027.aspx) | | **KeyCreate** |[Create a key](https://msdn.microsoft.com/library/azure/dn903634.aspx) | | **KeyGet** |[Get information about a key](https://msdn.microsoft.com/library/azure/dn878080.aspx) | | **KeyImport** |[Import a key into a vault](https://msdn.microsoft.com/library/azure/dn903626.aspx) | | **KeyBackup** |[Back up a key](https://msdn.microsoft.com/library/azure/dn878058.aspx) | | **KeyDelete** |[Delete a key](https://msdn.microsoft.com/library/azure/dn903611.aspx) | | **KeyRestore** |[Restore a key](https://msdn.microsoft.com/library/azure/dn878106.aspx) | | **KeySign** |[Sign with a key](https://msdn.microsoft.com/library/azure/dn878096.aspx) | | **KeyVerify** |[Verify with a key](https://msdn.microsoft.com/library/azure/dn878082.aspx) | | **KeyWrap** |[Wrap a key](https://msdn.microsoft.com/library/azure/dn878066.aspx) | | **KeyUnwrap** |[Unwrap a key](https://msdn.microsoft.com/library/azure/dn878079.aspx) | | **KeyEncrypt** |[Encrypt with a key](https://msdn.microsoft.com/library/azure/dn878060.aspx) | | **KeyDecrypt** |[Decrypt with a key](https://msdn.microsoft.com/library/azure/dn878097.aspx) | | **KeyUpdate** |[Update a key](https://msdn.microsoft.com/library/azure/dn903616.aspx) | | **KeyList** |[List the keys in a vault](https://msdn.microsoft.com/library/azure/dn903629.aspx) | | **KeyListVersions** |[List the versions of a key](https://msdn.microsoft.com/library/azure/dn986822.aspx) | | **SecretSet** |[Create a secret](https://msdn.microsoft.com/library/azure/dn903618.aspx) | | **SecretGet** |[Get a secret](https://msdn.microsoft.com/library/azure/dn903633.aspx) | | **SecretUpdate** |[Update a secret](https://msdn.microsoft.com/library/azure/dn986818.aspx) | | **SecretDelete** |[Delete a secret](https://msdn.microsoft.com/library/azure/dn903613.aspx) | | **SecretList** |[List secrets in a vault](https://msdn.microsoft.com/library/azure/dn903614.aspx) | | **SecretListVersions** |[List versions of a secret](https://msdn.microsoft.com/library/azure/dn986824.aspx) | ## <a id="loganalytics"></a>Use Log Analytics You can use the Key Vault solution in Azure Log Analytics to review Key Vault **AuditEvent** logs. In Log Analytics, you use log queries to analyze data and get the information you need. For more information, including how to set this up, see [Azure Key Vault solution in Log Analytics](../azure-monitor/insights/azure-key-vault.md). This article also contains instructions if you need to migrate from the old Key Vault solution that was offered during the Log Analytics preview, where you first routed your logs to an Azure storage account and configured Log Analytics to read from there. ## <a id="next"></a>Next steps For a tutorial that uses Azure Key Vault in a .NET web application, see [Use Azure Key Vault from a web application](tutorial-net-create-vault-azure-web-app.md). For programming references, see [the Azure Key Vault developer's guide](key-vault-developers-guide.md). For a list of Azure PowerShell 1.0 cmdlets for Azure Key Vault, see [Azure Key Vault cmdlets](/powershell/module/az.keyvault/?view=azps-1.2.0#key_vault). For a tutorial on key rotation and log auditing with Azure Key Vault, see [Set up Key Vault with end-to-end key rotation and auditing](key-vault-key-rotation-log-monitoring.md).
C#
UTF-8
1,214
3.09375
3
[]
no_license
using Microsoft.Xna.Framework; namespace SuperTutoriel.Classes.Managers { /// <summary> /// Gére le screenshake. /// </summary> public static class ScreenShakeManager { #region Propriétés /// <summary> /// La valeur du tremblement d'écran actuel. /// </summary> public static Vector2 ScreenShake { get; set; } #endregion Propriétés #region Méthodes /// <summary> /// Permet d'initialiser le manager. /// </summary> public static void Initialize() { ScreenShake = Vector2.Zero; } /// <summary> /// Met à jour la logique de l'objet. /// </summary> /// <param name="gameTime">Représente le temps à l'instant T.</param> public static void Update(GameTime gameTime) { ScreenShake /= 2; } /// <summary> /// Permet d'augmenter le tremblement d'écran. /// </summary> public static void AddScreenShake(int value) { ScreenShake += new Vector2(value); } #endregion Méthodes } }
Java
UTF-8
257
1.859375
2
[]
no_license
package br.com.limpacity.producer.dto; import lombok.Getter; import lombok.experimental.SuperBuilder; import java.util.Date; @Getter @SuperBuilder public abstract class MessageDTO { private final String messageType; private final Date currentDate; }
PHP
UTF-8
905
2.75
3
[ "MIT" ]
permissive
<?php /** * For the full copyright and license information, please view the LICENSE.md * file that was distributed with this source code. */ namespace Notamedia\ConsoleJedi\Module\Command; use Notamedia\ConsoleJedi\Module\Module; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * The command to remove a module * * @author Marat Shamshutdinov <m.shamshutdinov@gmail.com> */ class UnregisterCommand extends ModuleCommand { /** * {@inheritdoc} */ protected function configure() { parent::configure(); $this->setName('module:unregister') ->setDescription('Uninstall module'); } /** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $module = new Module($input->getArgument('module')); $module->unRegister(); $output->writeln(sprintf('unregistered <info>%s</info>', $module->getName())); } }
PHP
UTF-8
1,793
2.546875
3
[]
no_license
<?php $num_of_articles = $_REQUEST['num_of_articles']; function getnews($nofarticle) { $appkey = "c2633a3d944ea8e2372ba7d40389d8a80b0bae86"; $hv_api = 'https://api-ssl.bitly.com/v3/highvalue?access_token='.$appkey.'&limit='.$nofarticle; $hv = file_get_contents($hv_api); $data = json_decode($hv, TRUE); $response = "{ \"data\" : [ "; foreach($data['data']['values'] as $item) { $content_api = 'https://api-ssl.bitly.com/v3/link/content?access_token='.$appkey.'&link='.urlencode($item); $c = file_get_contents($content_api); $content = json_decode($c, TRUE); //print_r($content); if( strcmp( $content['status_txt'], 'OK' ) == 0 ){ $response = $response."{ \"bitly_link\" : \"".$item."\", "; $info_api = 'https://api-ssl.bitly.com/v3/link/info?access_token='.$appkey.'&link='.urlencode($item); $i = file_get_contents($info_api); $info = json_decode($i, TRUE); $response = $response."\"title\" : \"".$info['data']['html_title']."\", "; //print $content['data']['content']."<br>"; $notag = strip_tags($content['data']['content']); $s = preg_replace("/\s+/", " ", $notag); //Remove duplicate newlines //$s = preg_replace("/[\n]*/", "\n", $notag); //Preserves newlines while replacing the other whitspaces with single space //$s = preg_replace("/[\t]*/", " ", $s); $s = str_replace('"', '\"', $s); $response = $response."\"content\" : \"".$s."\""; //echo $info_api; //echo $content_api; //print_r( $info); //print_r( $content); //print "<br>_______________________________________________________<br>"; $response = $response." },"; } } $response = substr($response, 0, -1); $response = $response." ] }"; return $response; } echo getnews($num_of_articles); ?>
Java
UTF-8
238
2.71875
3
[]
no_license
package Facade; public class Bank { public boolean hasSufficientSavings(Customer customer, int loanAmount) { if(customer.getSavingAmount() > loanAmount) { return true; } else return false; } }
Ruby
UTF-8
524
3.984375
4
[]
no_license
my_arr = [34, 57, 82, 20345, 23] def my_max(array) if array[0] > array[1] && array[0] > array[2] && array[0] > array[3] && array[0] > array[4] && array[0] > array[5] puts array[0] elsif array[1] > array[2] && array[1] > array[3] && array[1] > array[4] && array[1] > array[5] puts array[1] elsif array[2] > array[3] && array[2] > array[4] && array[2] > array[5] puts array[2] elsif array[3] > array[4] puts array[3] else puts array[4] end end puts my_max(my_arr)
Java
UTF-8
1,429
2.671875
3
[]
no_license
package core.components; import java.awt.Polygon; import java.awt.Shape; import java.awt.image.AffineTransformOp; import core.Component; import rendering.ColorFill; import rendering.FillOptions; import rendering.ShapeRenderRequest; import rendering.StrokeOptions; /** * A component that renders a polygon on screen */ public class PolygonRenderer extends Component { /** * The shape to render */ public Shape shape = null; /** * FillOptions of this shape: how will the shape be filled */ public FillOptions fill = null; /** * Are coordinates of the spatial relative to the world or to screenspace (=~ world object or GUI ?) */ public boolean screenSpace = false; /** * Spatial belonging to this component's GameObject */ private Spatial2D spatial; @Override public void start() { super.start(); spatial = getOwner().getOrCreateComponent(Spatial2D.class); } @Override public void update(double delta) { sendRenderRequest(); } /** * Sends a render request to the render manager */ private void sendRenderRequest() { Shape transformedShape = this.shape; if(spatial != null) { transformedShape = spatial.getTransform().createTransformedShape(transformedShape); } ShapeRenderRequest request = new ShapeRenderRequest(transformedShape, new StrokeOptions(), this.fill, screenSpace); this.getOwner().getWorld().getRenderManager().addRequest(request); } }
C#
UTF-8
6,704
2.59375
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Calculator { public partial class Form1 : Form { StringBuilder intxt = new StringBuilder(10); StringBuilder outtxt = new StringBuilder(10); StringBuilder inputText = new StringBuilder(10); [DllImport("fb3-3.tab.dll", EntryPoint = "Calculation", CallingConvention = CallingConvention.Cdecl)] public static extern int Calculation(StringBuilder xintxt, StringBuilder xouttxt); public Form1() { InitializeComponent(); intxt.Append(".\\in.txt"); outtxt.Append(".\\out.txt"); } private void textBox2_TextChanged(object sender, EventArgs e) { } private void IN_Click(object sender, EventArgs e) { } private void button17_Click(object sender, EventArgs e) { //删除一个字符 if (inputText.Length>0) { inputText.Remove((inputText.Length - 1), 1); INPUT.Text = inputText.ToString(); } } private void button19_Click(object sender, EventArgs e) { //写字符串 if (!File.Exists(".\\in.txt")) { FileStream fs1 = new FileStream(".\\in.txt", FileMode.Create, FileAccess.Write);//创建写入文件 inputText.Append("\r\n"); StreamWriter sw = new StreamWriter(fs1); sw.Write(inputText); sw.Close(); fs1.Close(); } else { FileStream fs = new FileStream(".\\in.txt", FileMode.Open); inputText.Append("\r\n"); StreamWriter sw = new StreamWriter(fs); sw.Write(inputText); sw.Close(); fs.Close(); } //计算 Calculation(intxt, outtxt); //显示 string outstr = File.ReadAllText(".\\out.txt"); OUT.Text = outstr; } private void 历史记录ToolStripMenuItem_Click(object sender, EventArgs e) { } private void 帮助ToolStripMenuItem_Click(object sender, EventArgs e) { } private void INPUT_TextChanged(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { inputText.Append("1"); INPUT.Text = inputText.ToString(); } private void button2_Click(object sender, EventArgs e) { inputText.Append("2"); INPUT.Text = inputText.ToString(); } private void button3_Click(object sender, EventArgs e) { inputText.Append("3"); INPUT.Text = inputText.ToString(); } private void button4_Click(object sender, EventArgs e) { inputText.Append("4"); INPUT.Text = inputText.ToString(); } private void button5_Click(object sender, EventArgs e) { inputText.Append("5"); INPUT.Text = inputText.ToString(); } private void button6_Click(object sender, EventArgs e) { inputText.Append("6"); INPUT.Text = inputText.ToString(); } private void button7_Click(object sender, EventArgs e) { inputText.Append("7"); INPUT.Text = inputText.ToString(); } private void button8_Click(object sender, EventArgs e) { inputText.Append("8"); INPUT.Text = inputText.ToString(); } private void button9_Click(object sender, EventArgs e) { inputText.Append("9"); INPUT.Text = inputText.ToString(); } private void button11_Click(object sender, EventArgs e) { inputText.Append("0"); INPUT.Text = inputText.ToString(); } private void button14_Click(object sender, EventArgs e) { inputText.Append("+"); INPUT.Text = inputText.ToString(); } private void button13_Click(object sender, EventArgs e) { inputText.Append("-"); INPUT.Text = inputText.ToString(); } private void button15_Click(object sender, EventArgs e) { inputText.Append("*"); INPUT.Text = inputText.ToString(); } private void button16_Click(object sender, EventArgs e) { inputText.Append("/"); INPUT.Text = inputText.ToString(); } private void button12_Click(object sender, EventArgs e) { inputText.Append("."); INPUT.Text = inputText.ToString(); } private void button10_Click(object sender, EventArgs e) { inputText.Append(";"); INPUT.Text = inputText.ToString(); } private void button20_Click(object sender, EventArgs e) { inputText.Append("("); INPUT.Text = inputText.ToString(); } private void button21_Click(object sender, EventArgs e) { inputText.Append(")"); INPUT.Text = inputText.ToString(); } private void button22_Click(object sender, EventArgs e) { inputText.Append("{"); INPUT.Text = inputText.ToString(); } private void button23_Click(object sender, EventArgs e) { inputText.Append("}"); INPUT.Text = inputText.ToString(); } private void button24_Click(object sender, EventArgs e) { inputText.Append("\r\n"); INPUT.Text = inputText.ToString(); } private void button25_Click(object sender, EventArgs e) { //导入当前显示文字 inputText.Clear(); inputText.Append(INPUT.Text); } private void button18_Click(object sender, EventArgs e) { FileStream fs = new FileStream(".\\in.txt", FileMode.Open); fs.SetLength(0); inputText.Clear(); INPUT.Text = ""; fs.Close(); } private void 计算器_Load(object sender, EventArgs e) { } } }
Java
UTF-8
1,375
2.78125
3
[]
no_license
/* * GrindStack.java * by bluedart * * A useful implementation of IGrindRecipe. Pass this into FTAAPI.addGrind() to add the * recipe to FTA's list of grindables. */ package pa.api.recipe; import net.minecraft.item.ItemStack; import pa.api.inventory.ItemInventoryUtils; public class GrindStack implements IGrindRecipe { public ItemStack input, output, bonus; public float chance; public GrindStack(ItemStack input, ItemStack output) { this(input, output, 0.0f, null); } public GrindStack(ItemStack input, ItemStack output, float chance, ItemStack bonus) { this.input = input; this.output = output; this.chance = chance; this.bonus = bonus; } public void setBonusAndChance(ItemStack bonus, float chance) { this.bonus = bonus; this.chance = chance; } @Override public boolean matches(ItemStack stack) { return ItemInventoryUtils.areStacksSame(input, stack); } @Override public ItemStack getInput() { return (input != null) ? input.copy() : null; } @Override public ItemStack getOutput() { return (output != null) ? output.copy() : null; } @Override public ItemStack getOutput(ItemStack input) { return (output != null) ? output.copy() : null; } @Override public ItemStack getBonus() { return (bonus != null) ? bonus.copy() : null; } @Override public float getChance() { return chance; } }
C++
UTF-8
2,989
3.046875
3
[]
no_license
#include "Instruction.hpp" #include "Error.hpp" #include "Token.hpp" #include <stdexcept> #include <regex> const std::map< std::string, std::tuple< unsigned int, unsigned int > > Instruction::instMap = { {"ADD", {1, 2} }, {"SUB", {2, 2} }, {"MULT", {3, 2} } , {"DIV", {4, 2} }, {"JMP", {5, 2} }, {"JMPN", {6, 2} } , {"JMPP", {7, 2} }, {"JMPZ", {8, 2} }, {"COPY", {9, 3} } , {"LOAD", {10, 2} }, {"STORE", {11, 2} }, {"INPUT", {12, 2} } , {"OUTPUT", {13, 2} }, {"STOP", {14, 1} } }; int Instruction::GetOpcode( std::string key ) { try { unsigned int opcode = std::get<0>( instMap.at( key ) ); return int(opcode); } catch(std::out_of_range &e) { return -1; } } int Instruction::GetOpsize( std::string key ) { try { unsigned int opcode = std::get<1>( instMap.at( key ) ); return int(opcode); } catch(std::out_of_range &e) { return -1; } } bool Instruction::Validate( Expression exp ) { int opcode = GetOpcode( exp.GetOperation() ); switch( opcode ) { case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 10: case 11: case 12: case 13: { return ValidateSingleArg( exp ); break; } case 9: { return ValidateTwoArg( exp ); break; } case 14: { return ValidateNoArg( exp ); break; } } return -1 != opcode; } bool Instruction::ValidateNoArg( Expression exp ) { if( 0 < exp.GetOperands()[0].size() || 0 < exp.GetOperands()[1].size() ) { int column = exp.GetLabel().size(); column += 2*(column>0) + 1; Error::Semantico( "Essa instrucao nao aceita argumentos.", exp, column, std::string( exp ).size() ); exp.Invalidate(); } return true; } bool Instruction::ValidateSingleArg( Expression exp ) { if( 0 < exp.GetOperands()[1].size() ) { int column = exp.GetLabel().size(); column += 2*(column>0) + 1; Error::Semantico( "Essa instrucao nao aceita dois argumentos.", exp, column, std::string( exp ).size() ); exp.Invalidate(); } if( std::regex_match( exp.GetOperands()[0], Token::Number ) ) { int column = exp.GetLabel().size(); column += 2*(column>0) + 1; Error::Semantico( "Essa instrucao nao aceita argumento numerico.", exp, column, std::string( exp ).size() ); exp.Invalidate(); } return true; } bool Instruction::ValidateTwoArg( Expression exp ) { if( 0 == exp.GetOperands()[0].size() || 0 == exp.GetOperands()[1].size() ) { int column = exp.GetLabel().size(); column += 2*(column>0) + 1; Error::Semantico( "Essa instrucao requisita dois argumentos.", exp, column, std::string( exp ).size() ); exp.Invalidate(); } if( std::regex_match( exp.GetOperands()[0], Token::Number ) || std::regex_match( exp.GetOperands()[1], Token::Number ) ) { int column = exp.GetLabel().size(); column += 2*(column>0) + 1; Error::Semantico( "Essa instrucao nao aceita argumento numerico.", exp, column, std::string( exp ).size() ); exp.Invalidate(); } return true; }
Markdown
UTF-8
7,039
2.671875
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
# Schematic of current state of the amplifier I will try to update this to be as current as possible to how the amp is actually wired up. > Refer to the original schematic PDF when needed. Where possible component reference numbers were reused. ## Preamp ![preamp](preamp.png) Notable changes: * The input stage is no longer two parallel channels, but only one channel. * You now have your choise of first stage preamp * A 12AX7 based on the original schematic. I added a plate bypass cap to help make it warmer (less high frequencies). * An EF86. This has a bit more gain and is a lot brighter sound to it. * The second gain stage is a cathode clipper type configuration. The adjustable position lets me change the bias on the tube to allow it to distort more. I currently have this at about 2K * Stock 2M pots for volume were changed to be 1M, mostly because this is all I could find. But also the old values seemed to do cause the amp to do oscillating or squealing when turned up. * Added 1M grid stop resistor to be right before the input to the tube, instead of before the 68K resistors from the input jack. * Using RG-178 coaxial wire for sensitive signal paths. The power supply now supplies 4 additional tubes than the amp originally had. It seems way over sized for what it was designed to handle. ## Tone Stack ![tone stack](tonestack.png) This is the most part the original tone stack. I just like how it sounds. * The powr to V2 has been moved to go through a 10K resistor and a 10uF capacitor. I discovered by measuring with the scope there was a to 300mV 120Hz ripple on the power supply. This is as far as I can tell how the amplifier always was. It always had a small AC hum to it. I found I could swap out different tubes in this socket and make it get a bit better. But really what made the hum go away was the extra power supply filtering I added. * The tube socket had pins 2 and 6 soldered together at the socket, under the filament wires. I was thinking this was picking up some of the noise from the AC filament wire that was right there. Sure enough, just rewiring this socket makes a little bit of improvement on not hearing hum on the speaker. This was another original assembly artifact or bug that I fixed with thea mp. * There is now an effects send/return jacks. This amplifier did not have his. I like to use it a lot to add a noise gate, or digital delay effects after the preamp. * The output of the tone stack (effects loop jacks) now goes to the reverb unit instead of the phase inverter. ## Reverb ![reverb](reverb.png) This is an entirely new component. The amp originally did not have reverb effect. I ordered a mod reverb tank from NextGenGuitars. They are right here in Ottawa, great service for having stuff shipped. It's almost as fast as DigiKey. This circuit is based on a reverb circuit schematic I found on the internet. I think from "Tube Town Reverb Kit". They specify to use an EL844. I tried an EL84 for fun. I can't really notice a difference. But it kind of feels like the EL84 can overdrive the reverb output transformer, so you can get some intereting sounds with that. For now I will stick with the EL844. The power transformer in this amp seems to be way over sized and does not even blink when I add 3 more tubes. Which is convenient. I took some time to wire up the discrete components on its own circuit board module, like the other parts of the amplifier. It is now a hairy wires mess inside. But it works. After some preliminary testing and tracing all the component connections before powering it on, it worked for me right out the door. I am amused by the complexity. To add reverb, you basically build a mini amplifier, inside your amplifier. I can see why the modern amps use digital modelling circuits. Though I really appreciate having a tube driven real spring reverb effect. It is so much better to me than a reverb effect pedal anyway. * using RG-178 shielded wire for the sensitive audio paths, like return from the reverb tank to the regeneration triode. ## Output ![output](output.png) * Replaced the "long tail pair" tube based phase inverter with a solid state op-amp phase inverter. * This required a +/-15V DC power supply. I achieved this using a small DC-DC converter and diode rectitifer attached to the filament supply. I was having some of that terrible buzz that means the phase splitter is not tracking opposite phases like it should. The values are all the right ones and it appears to be working. But It is likely stray capacatance, or magic that is letting it not operate properly. I am tired of the magic of this too. The op-amp phase inverter is a lot more precise than the long tail pair circuit. * The annoying buzz or background hum that was always there is now gone. * Fixed the squealing when gain knobs or tone knobs are up. > I was chasing several high frequency oscillations since adding the reverb circuit. Having the gain up a bit past mid point, or having the tone control for the reverb on would cause screeching or loud hum and buzzing. Like the phase inverter was not working properly from being loaded. > I have a feeling some of the noise is coming from stray capacitance from the terribly arranged and too long unshielded wires everywhere. It is a side quest to make the wires as short as possible. > It would appear the op-amp phase inverter has helped a lot of these demonic problems now as well! One thing I do worry about, is if the audio signal is ever hundreds of volts like it may have been in the tube amplifier, that would be ok for the tube phase inverter. But the op amp would get roasted. I measured the input voltages, and it seems to be the order of a couple volts. So this is likely ok for the levels I plan on using the amplifer. ## Power Supply ![power supply](powersupply.png) * Removed the "death capacitor" * Now having the V1 voltage to the output transformer switched. Before it was not switched by the bypass switch. * I built a convenient custom circuit board, so these high voltage parts are safely tucked off to the side. This was among the first enhancements. The old turret board and chassis mounted capacitors had high voltage wires spread everywhere. * Added a new module to use the [Recom RS-0505D](https://www.digikey.com/product-detail/en/recom-power/RS-0515D/945-1543-5-ND/2321270) to provide the +/-15V DC for the op amp in the phase inverter, by using the filament supply. * Moved all the power entry chassis components to one corner. Before they were kind of sprawled over the back of the chassis. * Added an IEC outlet after the power switch. This will allow me to switch the power to my pedal board from the amp switch now. ## Tremolo ![tremolo](tremolo.png) This circuit has not changed much from the original. I replaced all the parts with new parts of the same value. Except for * Changed C18 and C19 from 0.01uF to 0.02uF. This has the effect of making the oscillator operate a bit slower. I found before it was entirely too fast to be usable.
Markdown
UTF-8
4,895
2.578125
3
[ "MIT" ]
permissive
CAGR Explorer (CAGRex) ====================== Installation ------------ ```bash pip install cagrex ``` Usage ----- ```python >>> from cagrex import CAGR >>> from pprint import pprint >>> cagr = CAGR() >>> pprint(cagr.course('INE5417', '20172')) {'ementa': 'Análise de requisitos: requisitos funcionais e requisitos ' 'não-funcionais; técnicas para levantamento e representação de ' 'requisitos, incluindo casos de uso. Modelagem OO: classe, ' 'atributo, associação, agregação e herança. Projeto OO: técnicas ' 'para projeto; padrões de projeto, componentes e frameworks; ' 'projeto de arquitetura; mapeamento objeto-relacional. Linguagem de ' 'especificação orientada a objetos. Métodos de análise e projeto ' 'orientados a objetos. Desenvolvimento de um software OO.', 'horas_aula': 90, 'id': 'INE5417', 'nome': 'Engenharia de Software I', 'semestre': 20181, 'turmas': {'04208A': {'horarios': [{'dia_da_semana': 2, 'duracao': 3, 'horario': '1330', 'sala': 'CTC-CTC108'}, {'dia_da_semana': 3, 'duracao': 2, 'horario': '0820', 'sala': 'CTC-CTC107'}], 'pedidos_sem_vaga': 0, 'professores': ['Ricardo Pereira e Silva'], 'vagas_disponiveis': 10, 'vagas_ofertadas': 25}, '04208B': {'horarios': [{'dia_da_semana': 2, 'duracao': 3, 'horario': '1330', 'sala': 'AUX-ALOCAR'}, {'dia_da_semana': 3, 'duracao': 2, 'horario': '0820', 'sala': 'AUX-ALOCAR'}], 'pedidos_sem_vaga': 0, 'professores': ['Patricia Vilain'], 'vagas_disponiveis': 9, 'vagas_ofertadas': 25}}} >>> cagr.login('id.ufsc', 'password') >>> pprint(cagr.student(16100719)) {'id': 16100719, 'nome': 'Cauê Baasch de Souza', 'curso': 'Ciências Da Computação', 'disciplinas': [{'id': 'INE5413', 'nome': 'Grafos', 'semestre': '20172', 'turma': '04208'}, {'id': 'INE5414', 'nome': 'Redes de Computadores I', 'semestre': '20172', 'turma': '04208'}, {'id': 'INE5415', 'nome': 'Teoria da Computação', 'semestre': '20172', 'turma': '04208'}, {'id': 'INE5416', 'nome': 'Paradigmas de Programação', 'semestre': '20172', 'turma': '04208'}, {'id': 'INE5417', 'nome': 'Engenharia de Software I', 'semestre': '20172', 'turma': '04208B'}]} >>> pprint(cagr.students_per_semester(cagr.program_id())) {'alunos_por_semestre': [('19.2', 54), ('20.1', 52), ('20.2', 52), ('19.1', 50), ('18.2', 40), ('17.2', 37), ('18.1', 37), ('17.1', 31), ('16.2', 27), ('16.1', 26), ('15.2', 18), ('15.1', 14), ('14.2', 14), ('13.2', 11), ('14.1', 6), ('13.1', 6), ('12.2', 5), ('12.1', 5), ('11.1', 2), ('10.2', 1), ('11.2', 1)], 'curso': 'CIÊNCIAS DA COMPUTAÇÃO'} >>> pprint(cagr.students_from_course(cagr.program_id())) [{'id': 16100719, 'name': 'Cauê Baasch de Souza'}, ... {'id': 12345678, 'name': 'John Doe'}] >>> pprint(cagr.total_students(cagr.program_id())) {'curso': 'CIÊNCIAS DA COMPUTAÇÃO', 'estudantes': 497} >>> pprint(cagr.suspended_students(cagr.program_id())) {'curso': 'CIÊNCIAS DA COMPUTAÇÃO', 'estudantes': 497, 'alunos_trancados': 35, 'porcentagem': 7.042253521126761} ``` Running tests ------------- Run tests without network access with: ```bash $ poetry run pytest ``` To enable network access: ```bash $ NETWORK_TESTS=1 poetry run pytest ``` To enable tests that required authentication, you must provide a `tests/credentials.json` file. ``` file: tests/credentials.json { "username": "", "password": "" } ```
C++
UTF-8
1,992
3.28125
3
[]
no_license
#include "01 Creating a buffer.h" #include "02 Allocating and binding memory object to a buffer.h" #include "04 Creating a buffer view.h" #include "06 Creating a storage texel buffer.h" namespace VulkanLibrary { bool CreateStorageTexelBuffer( VkPhysicalDevice physical_device, VkDevice logical_device, VkFormat format, VkDeviceSize size, VkBufferUsageFlags usage, bool atomic_operations, VkBuffer & storage_texel_buffer, VkDeviceMemory & memory_object, VkBufferView & storage_texel_buffer_view ) { VkFormatProperties format_properties; vkGetPhysicalDeviceFormatProperties( physical_device, format, &format_properties ); if( !(format_properties.bufferFeatures & VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_BIT) ) { std::cout << "Provided format is not supported for a uniform texel buffer." << std::endl; return false; } if( atomic_operations && !(format_properties.bufferFeatures & VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_ATOMIC_BIT) ) { std::cout << "Provided format is not supported for atomic operations on storage texel buffers." << std::endl; return false; } if( !CreateBuffer( logical_device, size, usage | VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT, storage_texel_buffer ) ) { return false; } if( !AllocateAndBindMemoryObjectToBuffer( physical_device, logical_device, storage_texel_buffer, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, memory_object ) ) { return false; } if( !CreateBufferView( logical_device, storage_texel_buffer, format, 0, VK_WHOLE_SIZE, storage_texel_buffer_view ) ) { return false; } return true; } } // namespace VulkanLibrary
Markdown
UTF-8
1,819
2.515625
3
[]
no_license
# 🚧 under construction 🚧 My first application is being developed; at this point, I have learned the Spring concepts, and I am at least ready to put them into practice. the Spring dependencies to create a web application, and I will learn how to put up my first Spring application on IDE (IntelliJ IDEA community) and command line, expose my first endpoint, understand how this works under the hood, and get to know the main annotations of Spring REST support. I will figure out how to create a service layer for the CMS (Content Management System) application and understand how Dependency Injection works in a Spring container. the Spring stereotypes will be met and implement my first Spring bean. At the end of before finishing project, and how to create a view layer and integrate that with Angular or React or Vue or whatever. The following the list will be worked: - Creating the project structure - Running the first Spring application - Introducing the REST support - Understanding the Dependency Injection in Spring ## install and run `mvn clean install spring-boot:run` navigate to the url: {get, post, put, delete} http://localhost:8080/api/category {get, post, put, delete} http://localhost:8080/api/user {get, post, put, delete} http://localhost:8080/api/news ## Swagger api `http://localhost:8080/swagger-ui.html` ## setup database under running docker environment `docker pull postgres:9.6.6:alpine` `docker pull mongo:latest` `docker network create cms-application` `docker run -d --name mongodb --net cms-application --port 27017:27017 mongo:latest` `docker run -d --name postgres --net cms-application --port 27017:27017 postgres:9.6.6:alpine` ## connect mongo express (admin app for database) `docker run -d --link mongodb:mongo --net cms-application -p 8081:8081 mongo-express`
Markdown
UTF-8
1,591
2.6875
3
[]
no_license
Create an ecosystem that fulfills basic needs (warmth, human interaction, etc.). Scarcity in location and availability, but not in resources, which are abundantly available and transportable by vehicles that exist 1. Overcapacity as a Service; use resources in current system efficitevely, right location right time. Connect ecosystems (mobility, transport, energy). Sky Scanner owned by us all. "Search gets inverted: instead of people searching for products, people search and compete for people". Connecting the dots, effectively connect to We use AI to sift through personal data. Ramping up to DAO, DO OR DIE the fllippening must happen. Crowdfund through ICO to setup for development phase, with a fixed amount of coins. The intrinsic value of the is directly linked to Metcalfe's law. 2. Paradigm Shift; in the first phase we have developed a platform that can effectively connect capacity to availability through optimal deployment of existing resources. At some point the flippening happens: overcapacity turns into undercapacity and decisions need to be made on which assets/resources are needed to fill the gap. The platform moves to a DAO. Everyone's money on one big pile, able to invest in the required units. 3. The DAO has found optimal allocation for resources now and as the system grows. The system will grow, the value of the underlying coin grows. At some point there is enough value and the DAO will cover most of the system (let's say the world). At that point we have replaced overcapacity with overvalue. This overvalue can be released a form of basic income.
C++
UTF-8
563
2.8125
3
[]
no_license
#ifndef USERS_H #define USERES_H #pragma once #include "Course.h" #include "ResearchGroup.h" #include "Staff.h" #include <vector> /** Users class is responsible for simlation of users in supercomputer environment. We can recognize different types of user: students in course, researcher in research group, IT member in staff. Not all class of users have been implemented. **/ class Users { public: vector<Course> course; vector<ResearchGroup> researcherGroup; vector<Staff> staff; public: Users(); Users(int amount, int budget); ~Users(); }; #endif
Python
UTF-8
372
3.1875
3
[]
no_license
n = int(input()) while n: n -= 1 value = input().split() a = value[0] b = value[1] lenA = len(a) lenB = len(b) if lenA >= lenB: if a[lenA - lenB:lenA] == b: res = a[lenA - lenB:lenA] # print(res) print("encaixa") else: print("nao encaixa") else: print("nao encaixa")
JavaScript
UTF-8
965
3.78125
4
[]
no_license
//Given a string of numbers the adder method should be able to add pairs of numbers together. //Example Input: "1 1 2 2 3 3" //Example Output: "2 4 6" //Example Input: "1 2 3 4 5 6" //Example Output: "3 7 11" //Note: If there is an odd number of numbers the last number in the string is not added with a number. //Example Input: "1 1 2 2 3 3 3" //Example Output: "2 4 6 3" //Remember: Please implement by test driving the code. //Extra Credit: //Given that a string of numbers contains special characters you should be able to add the pair of numbers together //stripping any extra whitespace. //Example Input: "[1 2] (5 5) {6 6}" //Example Output: "[3] (10) {12}" var example_inputs = [ "1 1 2 2 3 3", "9 10 77 5", "1 2 3", "[1 2] [3 4] [5 6] 7 8", "{1 1} [2 2] 5" ]; var example_outputs = [ "2 4 6", "19 82", "3 3", "[3] [7] [11] 15", "{2} [4] 5" ]; module.exports = function adder(input) { };
Java
UTF-8
4,948
2.59375
3
[]
no_license
package com.simpleplus.telegram.bots.services.impl; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.simpleplus.telegram.bots.components.BotBean; import com.simpleplus.telegram.bots.datamodel.Coordinates; import com.simpleplus.telegram.bots.datamodel.SunsetSunriseTimes; import com.simpleplus.telegram.bots.exceptions.ServiceException; import com.simpleplus.telegram.bots.services.SunsetSunriseService; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Locale; import java.util.Map; public class SunsetSunriseRemoteAPI implements SunsetSunriseService, BotBean { private static final Logger LOG = LogManager.getLogger(SunsetSunriseRemoteAPI.class); private static final String BASE_URL = "http://127.0.0.1:8500/json/%f/%f/%s"; @Override public SunsetSunriseTimes getSunsetSunriseTimes(Coordinates coordinates, LocalDate localDate) throws ServiceException { String result = callRemoteService(coordinates, localDate); LOG.debug(result); return parseResult(result); } @Override public SunsetSunriseTimes getSunsetSunriseTimes(Coordinates coordinates) throws ServiceException { return getSunsetSunriseTimes(coordinates, LocalDate.now()); } private SunsetSunriseTimes parseResult(String result) throws ServiceException { SunsetSunriseTimes times = new SunsetSunriseTimes(); try { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new JavaTimeModule()); APIResponse response = objectMapper.readValue(result, APIResponse.class); if (!"OK".equals(response.status)) { throw new ServiceException("Remote service error: " + response.message); } for (Map.Entry<String, LocalDateTime> entry : response.results.entrySet()) { times.putTime(entry.getKey(), entry.getValue()); } } catch (IOException e) { throw new ServiceException("Internal service error (" + e.getMessage() + ")", e); } return times; } /** * Calls the remote API and returns the response string. * * @param localDate the date which will be passed to the service. Please note that since it is a non-zoned date, * prior to passing it to the API, it will be converted to a zoned one with system-default time * zone (assuming start of day as time). */ private String callRemoteService(Coordinates coordinates, LocalDate localDate) throws ServiceException { StringBuilder result = new StringBuilder(); try { URL url = new URL(String.format(Locale.ROOT, BASE_URL, coordinates.getLatitude(), coordinates.getLongitude(), localDate.atStartOfDay(ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")))); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { throw new ServiceException("HTTP Error " + conn.getResponseCode()); } try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()))) { String output; while ((output = br.readLine()) != null) { result = result.append(output); } } conn.disconnect(); } catch (MalformedURLException e) { LOG.error("MalformedURLException", e); } catch (IOException e) { throw new ServiceException("IO Error"); } return result.toString(); } public static class APIResponse { private String status; private String message; private Map<String, LocalDateTime> results; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Map<String, LocalDateTime> getResults() { return results; } public void setResults(Map<String, LocalDateTime> results) { this.results = results; } } }
C++
BIG5
278
3.25
3
[]
no_license
#include<iostream> using namespace std; int main() { cout << "10iƪ10O" << 10 << "C\n"; cout << "8iƪ10O" << 010 << "C\n"; cout << "16iƪ10O" << 0x10 << "C\n"; cout << "16iƪFO" << 0xF << "C\n"; return 0; }
Ruby
UTF-8
3,600
3.25
3
[]
no_license
require 'rspec' require_relative 'spechelper' require_relative '../lib/enigma' RSpec.describe Enigma do before :each do @enigma = Enigma.new end it 'exists' do expect(@enigma).to be_an(Enigma) end it 'initializes with attributes' do expect(@enigma.set).to eq(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ' ']) expect(@enigma.set.length).to eq(27) end it 'can split a message into an arary of characters' do expected = ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] expect(@enigma.char_array('hello world')).to eq(expected) end it 'can return the positions of the message characters in the set' do char_array = ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] expected = [7, 4, 11, 11, 14, 26, 22, 14, 17, 11, 3] expect(@enigma.positions_in_set(char_array)).to eq(expected) end it 'can return message character with index' do char_array = ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] expected = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] expect(@enigma.char_index(char_array)).to eq(expected) end it 'can return a nested array of the char, index, and position in set' do char_index = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] pos_in_set = [7, 4, 11, 11, 14, 26, 22, 14, 17, 11, 3] expected = [['h', 0, 7], ['e', 1, 4], ['l', 2, 11], ['l', 3, 11], ['o', 4, 14], [' ', 5, 26], ['w', 6, 22], ['o', 7, 14], ['r', 8, 17], ['l', 9, 11], ['d', 10, 3]] expect(@enigma.char_index_and_pos('hello world')).to eq(expected) end it 'can encrypt a message with a key and date' do expected = { encryption: 'keder ohulw!', key: '02715', date: '040895' } expect(@enigma.encrypt('hello world!', '02715', '040895')).to eq(expected) end it 'can decrypt a message with a key and date' do expected = { decryption: 'hello world', key: '02715', date: '040895' } expect(@enigma.decrypt('keder ohulw', '02715', '040895')). to eq(expected) end it "can encrypt a message with a key (uses today's date)" do expected = { encryption: 'okfavfqdyry', key: '02715', date: '130621' } allow(@enigma).to receive(:encrypt).and_return(expected) expect(@enigma.encrypt('hello world', '02715')). to eq(expected) end it "can decrypt a message with a key (uses today's date)" do encrypted = @enigma.encrypt('hello world', '02715') expected = { date: '130621', decryption: 'hello world', key: '02715' } allow(@enigma).to receive(:decrypt).and_return(expected) expect(@enigma.decrypt(encrypted[:encryption], '02715')).to eq(expected) expected = { decryption: 'chicky-chicky parm-parm', key: '02715', date: '130621' } allow(@enigma).to receive(:decrypt).and_return(expected) expect(@enigma.decrypt('jncsrd-soox efjqys-ehxg', '02715')). to eq(expected) end it "can encrypt a message (generates random key and uses today's date)" do expected = { encryption: 'rsmaynxdaze', key: '86242', date: '130621' } allow(@enigma).to receive(:encrypt).and_return(expected) expect(@enigma.encrypt('hello world')).to eq(expected) end end
Go
UTF-8
579
2.765625
3
[]
no_license
package clause import ( "orm/ormlog" "reflect" "testing" ) func TestClause_BuildSQL(t *testing.T) { var clause Clause clause.Set(WHERE, "Name = ?", "foo") clause.Set(ORDERBY, "Age DESC") clause.Set(LIMIT, 3) clause.Set(SELECT, "User", []string{"Name", "Age"}) sql, sqlVars := clause.BuildSQL(SELECT, WHERE, LIMIT, ORDERBY) if sql != `SELECT Name,Age FROM User WHERE Name = ? LIMIT ? ORDER BY Age DESC` { ormlog.Debug("sql build error") t.FailNow() } if !reflect.DeepEqual(sqlVars, []interface{}{"foo", 3}) { ormlog.Debug("sqlVars error") t.FailNow() } }
Swift
UTF-8
2,614
2.609375
3
[]
no_license
// // ViewController.swift // GEO // // Created by YANGSHENG ZOU on 2016-05-25. // Copyright © 2016 YANGSHENG ZOU. All rights reserved. // import UIKit import CoreLocation import MapKit class ViewController: UIViewController { @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var locationLabel: UILabel! @IBOutlet weak var pinImageView: UIImageView! var geoCoder:CLGeocoder = CLGeocoder.init() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func locationOnMapView() ->CLLocationCoordinate2D { let pinCenter = CGPoint(x: CGRectGetMidX(pinImageView.bounds), y: CGRectGetMidY(pinImageView.bounds)) return mapView.convertPoint(pinCenter, toCoordinateFromView: pinImageView) } func showLoacation(){ let coordinateInMapView = locationOnMapView() let location = CLLocation(latitude: coordinateInMapView.latitude, longitude: coordinateInMapView.longitude) geoCoder.reverseGeocodeLocation(location, completionHandler: { placemark,error in if error == nil { var locationInfo = "" print(locationInfo) for p:CLPlacemark in placemark!{ if(p.country != nil){ locationInfo = locationInfo+p.country!+" " } if(p.administrativeArea != nil){ locationInfo = locationInfo+p.administrativeArea!+" " } if(p.name != nil){ locationInfo = locationInfo+p.name!+" " } if(p.postalCode != nil){ locationInfo = locationInfo+p.postalCode!+" " } print(locationInfo) self.locationLabel.text = locationInfo } } else{ print(error!) } }) } func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool){ mapView.userInteractionEnabled = false showLoacation() mapView.userInteractionEnabled = true } @IBAction func showLocation(sender: AnyObject) { } }
PHP
UTF-8
577
2.59375
3
[]
no_license
<?php // Fetch all drivers header("Access-Control-Allow-Origin: *"); // Connect to db require_once('connect.php'); // Get data $response = []; // Insert dispatcher $sql = "SELECT * FROM drivers"; $result = $conn->query($sql); if($result->num_rows > 0){ while($row = $result->fetch_assoc()){ $array = array("ID"=>$row["ID"], "name"=>$row["name"], "email"=>$row["email"], "password"=>$row["password"] ); array_push($response, $array); } } else { $response = '0 results'; } echo json_encode($response); $conn->close(); ?>
Java
UTF-8
3,658
2.53125
3
[ "Apache-2.0" ]
permissive
package org.deltaecore.feature.validation; import java.util.List; import org.deltaecore.feature.DECardinalityBasedElement; import org.deltaecore.feature.DEFeature; import org.deltaecore.feature.DEGroup; import org.deltaecore.feature.DEVersion; import org.eclipse.core.runtime.IStatus; import de.christophseidl.util.ecore.validation.AbstractConstraint; public class DEStructuralWellformednessConstraint extends AbstractConstraint<DECardinalityBasedElement> { @Override protected IStatus doValidate(DECardinalityBasedElement cardinalityBasedElement) { if (cardinalityBasedElement instanceof DEFeature) { DEFeature feature = (DEFeature) cardinalityBasedElement; List<DEVersion> versions = feature.getVersions(); //At least one version if (versions.isEmpty()) { String message = "A feature has to declare at least one version."; return createErrorStatus(message, feature); } if (!hasTreeStructuredVersions(feature)) { String message = "The versions of a feature have to be arranged as a tree (exactly one initial version, no cycles, all superseded/superseding versions belong to the same feature)."; return createErrorStatus(message, feature); } } if (cardinalityBasedElement instanceof DEGroup) { //At least one child feature DEGroup group = (DEGroup) cardinalityBasedElement; List<DEFeature> features = group.getFeatures(); if (features.isEmpty()) { String message = "A group has to contain at least one feature."; return createErrorStatus(message, group); } } return createSuccessStatus(); } private static boolean hasTreeStructuredVersions(DEFeature feature) { //Versions have to form a tree //- Only one initial version //- No cycles //- all referenced versions belong to same feature boolean hasValidInitialVersion = hasValidInitialVersion(feature); boolean isFreeOfVersionCycles = isFreeOfVersionCycles(feature); boolean allReferencedVersionsBelongToSameFeature = allReferencedVersionsBelongToSameFeature(feature); return hasValidInitialVersion && isFreeOfVersionCycles && allReferencedVersionsBelongToSameFeature; } private static boolean hasValidInitialVersion(DEFeature feature) { List<DEVersion> versions = feature.getVersions(); boolean hasInitial = false; for (DEVersion version : versions) { boolean isInitial = (version.getSupersededVersion() == null); if (isInitial) { if (hasInitial) { //Second initial version return false; } else { hasInitial = true; } } } return hasInitial; } private static boolean isFreeOfVersionCycles(DEFeature feature) { List<DEVersion> versions = feature.getVersions(); for (DEVersion version : versions) { DEVersion currentVersion = version.getSupersededVersion(); while(currentVersion != null) { //Version has itself as superseded version -> cycle. if (currentVersion == version) { return false; } currentVersion = currentVersion.getSupersededVersion(); } } return true; } private static boolean allReferencedVersionsBelongToSameFeature(DEFeature feature) { List<DEVersion> versions = feature.getVersions(); for (DEVersion version : versions) { DEVersion supersededVersion = version.getSupersededVersion(); if (supersededVersion != null && supersededVersion.getFeature() != feature) { return false; } List<DEVersion> supersedingVersions = version.getSupersedingVersions(); for (DEVersion supersedingVersion : supersedingVersions) { if (supersedingVersion.getFeature() != feature) { return false; } } } return true; } }
C#
UTF-8
2,849
3.4375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LessonNewCar { public class Car { #region Variables bool IsDirty; bool IsWork; int id; static int count=1; double lenght; #endregion public Car() { IsDirty = false; IsWork = true; lenght = 0; id = count++; } /// <summary> /// Свойство машины Как Выглядит /// Возврвщвет IsDirty</summary> public bool Look { get { return IsDirty; } set { IsDirty = value; } } /// <summary> /// Свойство работоспособности машины /// Возвращает IsWorking</summary> public bool StateIsWorking { get { return IsWork; } set { IsWork = value; } } public double Mealage { get { return lenght; } private set { } } public void Travel(double path) { double pred; pred = path + Mealage; if (path<0) { throw new Exception("Значение не может быть меньше нуля"); } else if ((path>=1000)||(pred>=1000)) { lenght = 1000; StateIsWorking = false; Look = true; } else if ((path<=2000)||(pred>=2000)) { lenght = 2000; StateIsWorking = false; Look = true; } else if ((path >= 5000) || (pred >= 5000)) { lenght = 5000; StateIsWorking = false; Look = true; } else { lenght = lenght + path; Look = true; } } /// <summary> /// Перезагрузка метода ToString /// </summary> /// <returns></returns> public override string ToString() { string Look = this.IsDirty ? "грязная" : "чистая"; string StateIsWorking = this.IsWork ? "рабочая" : "сломанная"; return string.Format ("Машина N {0} пробег: {1} Состояние: {2} , {3}",id,Mealage,Look,StateIsWorking ); } } }
Markdown
UTF-8
1,218
2.65625
3
[ "MIT" ]
permissive
# realtime-react-datatable realtime react datagrid using [Hamoni Sync](https://www.hamoni.tech/) and [react-table](https://react-table.js.org/) ![React app running](https://cdn.filestackcontent.com/O6PAXFmSCeYHhTn8BfRA) # Setup * Clone or download this repository * Run `npm install` to install its dependencies * Copy your Account and Application ID from your [dashboard](https://dashboard.hamoni.tech) if you're already logged in. If you don't have an account, [Register and Login](https://dashboard.hamoni.tech) to Hamoni Sync dashboard * Open **server.js** and replace the sring placeholder for account and application ID with values you see on your dashboard. * Open **App.js** in src folder. Replace the sring placeholder for account and application ID with values you see on your dashboard. * Open the terminal and run `node server.js` to create the initial data to be rendered in the datagrid. * Run `npm start` to start the React app. Now you can change and add new data. This [blog post](https://dev.to/pmbanugo/real-time-editable-datagrid-in-react-56ad) describes more details on how this app was built. For more on Hamoni Sync, see the doccumentation at [docs.hamoni.tech](https://docs.hamoni.tech)
Java
UTF-8
840
2.4375
2
[ "MIT" ]
permissive
package tn.imed.jaberi.hospitalmanagement.error; import java.util.Date; import com.fasterxml.jackson.annotation.JsonFormat; public class ErrorDetails { private String message; private String uri; @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss" ) private Date timesamp; public ErrorDetails () { this.timesamp = new Date(); } public ErrorDetails (String message, String uri) { this(); this.message = message; this.uri = uri; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public Date getTimesamp() { return timesamp; } public void setTimesamp(Date timesamp) { this.timesamp = timesamp; } }
Java
UTF-8
3,433
2.546875
3
[]
no_license
package com.example.hp.iFindYou.DAO; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.DatabaseUtils; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.util.ArrayList; /** * Created by HP on 11/1/2016. */ public class CaregiverDAO extends SQLiteOpenHelper { public static final String DATABASE_NAME = "iFindYou.db"; public static final String CAREGIVER_COLUMN_ID = "id"; public static final String CAREGIVER_COLUMN_NAME = "name"; public static final String CAREGIVER_COLUMN_PHONE = "contactNo"; public static final String TABLE_NAME = "caregiver"; public CaregiverDAO(Context context) { super(context, DATABASE_NAME , null, 1); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL( "create table "+ TABLE_NAME + " (id integer primary key, name text,contactNo text)" ); } @Override public void onUpgrade(SQLiteDatabase db, int oldVer, int newVer) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); onCreate(db); } public boolean insertCaregiver (String name, String contactNo) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("name", name); contentValues.put("contactNo", contactNo); db.insert(TABLE_NAME, null, contentValues); return true; } public Cursor getData(int id){ SQLiteDatabase db = this.getReadableDatabase(); Cursor res = db.rawQuery( "select * from " + TABLE_NAME + " where id=" + id + "", null ); return res; } public int numberOfRows(){ SQLiteDatabase db = this.getReadableDatabase(); int numRows = (int) DatabaseUtils.queryNumEntries(db, TABLE_NAME); return numRows; } public boolean updateCaregiverInfo (Integer id, String name, String contactNo) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("name", name); contentValues.put("phone", contactNo); db.update(TABLE_NAME, contentValues, "id = ? ", new String[] { Integer.toString(id) } ); return true; } public Integer deleteCaregiver (Integer id) { SQLiteDatabase db = this.getWritableDatabase(); return db.delete(TABLE_NAME, "id = ? ", new String[] { Integer.toString(id) }); } public ArrayList<String> getAllCaregivers() { ArrayList<String> array_list = new ArrayList<String>(); SQLiteDatabase db = this.getReadableDatabase(); Cursor res = db.rawQuery( "select * from " + TABLE_NAME, null ); res.moveToFirst(); while(res.isAfterLast() == false){ array_list.add(res.getString(res.getColumnIndex(TABLE_NAME))); res.moveToNext(); } return array_list; } // public boolean assignClient (Caregiver caregiver, Client client) { // SQLiteDatabase db = this.getWritableDatabase(); // ContentValues contentValues = new ContentValues(); // contentValues.put("name", name); // contentValues.put("contactNo", contactNo); // db.insert(TABLE_NAME, null, contentValues); // return true; // } }
PHP
UTF-8
3,234
2.53125
3
[]
no_license
<?php App::uses('AppController', 'Controller'); /** * Seasons Controller * * @property Season $Season */ class SeasonsController extends AppController { public function beforeRender() { parent::beforeRender(); $this->layout = 'admin'; $this->isAdmin(); } /** * admin_index method * * @return void */ public function admin_index() { $this->Season->recursive = 0; $this->set('seasons', $this->paginate()); } /** * admin_add method * * @return void */ public function admin_add() { if ($this->request->is('post')) { $this->Season->create(); if($this->request->data['Season']['slug'] == ''){ $this->request->data['Season']['slug'] = Inflector::slug(trim($this->request->data['Season']['name']), '-'); } else{ $this->request->data['Season']['slug'] = Inflector::slug(trim($this->request->data['Season']['slug']), '-'); } if ($result = $this->Season->save($this->request->data)) { $this->Session->setFlash(__('The season has been saved'), 'flash'); $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The season could not be saved. Please, try again'), 'flash'); } } } /** * admin_edit method * * @throws NotFoundException * @param string $id * @return void */ public function admin_edit($id = null) { if (!$this->Season->exists($id)) { throw new NotFoundException(__('Invalid Season')); } if ($this->request->is('post') || $this->request->is('put')) { $this->request->data['Season']['slug'] = Inflector::slug(trim($this->request->data['Season']['slug']), '-'); if ($this->Season->save($this->request->data)) { $this->Session->setFlash(__('The season has been saved'), 'flash'); $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The season could not be saved. Please, try again'), 'flash'); } } else { $options = array('conditions' => array('Season.' . $this->Season->primaryKey => $id)); $this->request->data = $this->Season->find('first', $options); } } /** * admin_delete method * * @throws NotFoundException * @param string $id * @return void */ public function admin_delete($id = null) { $this->Season->id = $id; if (!$this->Season->exists()) { throw new NotFoundException(__('Invalid Season')); } $this->request->onlyAllow('post', 'delete'); if ($this->Season->delete()) { //$this->Category->reorder(); $this->Session->setFlash(__('Season deleted'), 'flash'); $this->redirect(array('action' => 'index')); } $this->Session->setFlash(__('Season was not deleted. Please, try again'), 'flash'); $this->redirect(array('action' => 'index')); } }
PHP
UTF-8
804
2.875
3
[]
no_license
<?php namespace HarmSmits\BolComClient\Models; /** * @method null|int getWeeksAhead() * @method self setWeeksAhead(int $weeksAhead) * @method null|Total getTotal() * @method self setTotal(Total $total) * @method Countries[] getCountries() */ final class SalesForecastPeriod extends AModel { /** * The number of weeks into the future, starting from today. * @var int */ protected int $weeksAhead = 0; protected Total $total; /** @var Countries[] */ protected array $countries = []; /** * @param Countries[] $countries * * @return $this */ public function setCountries(array $countries): self { $this->_checkIfPureArray($countries, Countries::class); $this->countries = $countries; return $this; } }
Markdown
UTF-8
11,504
2.671875
3
[]
no_license
[点击](https://github.com/neroneroffy/react-source-code-debug)进入React源码调试仓库。 本文是在[React中的高优先级任务插队机制](https://github.com/neroneroffy/react-source-code-debug/blob/master/docs/Concurrent%E6%A8%A1%E5%BC%8F%E4%B8%8BReact%E7%9A%84%E6%9B%B4%E6%96%B0%E8%A1%8C%E4%B8%BA/%E9%AB%98%E4%BC%98%E5%85%88%E7%BA%A7%E4%BB%BB%E5%8A%A1%E6%8F%92%E9%98%9F.md) 基础上的后续延伸,先通过阅读这篇文章了解任务调度执行的整体流程,有助于更快地理解本文所讲的内容。 饥饿问题说到底就是高优先级任务不能毫无底线地打断低优先级任务,一旦低优先级任务过期了,那么他就会被提升到同步优先级去立即执行。如下面的例子: 我点击左面的开始按钮,开始渲染大量DOM节点,完成一次正常的高优先级插队任务: ![](http://neroht.com/unstraved.gif) 而一旦左侧更新的时候去拖动右侧的元素,并在拖动事件中调用setState记录坐标,介入更高优先级的任务,这个时候,左侧的DOM更新过程会被暂停,不过当我拖动到一定时间的时候,左侧的任务过期了,那它就会提升到同步优先级去立即调度,完成DOM的更新(低优先级任务的lane优先级并没有变,只是任务优先级提高了)。 ![](http://neroht.com/straved.gif) 要做到这样,React就必须用一个数据结构去存储pendingLanes中有效的lane它对应的过期时间。另外,还要不断地检查这个lane是否过期。 这就涉及到了**任务过期时间的记录** 以及 **过期任务的检查**。 # lane模型过期时间的数据结构 完整的pendingLanes有31个二进制位,为了方便举例,我们缩减位数,但道理一样。 例如现在有一个lanes: ``` 0 b 0 0 1 1 0 0 0 ``` 那么它对应的过期时间的数据结构就是这样一个数组: ``` [ -1, -1, 4395.2254, 3586.2245, -1, -1, -1 ] ``` > 在React过期时间的机制中,-1 为 NoTimestamp 即pendingLanes中每一个1的位对应过期时间数组中一个有意义的时间,过期时间数组会被存到root.expirationTimes字段。这个计算和存取以及判断是否过期的逻辑 是在`markStarvedLanesAsExpired`函数中,每次有任务要被调度的时候都会调用一次。 # 记录并检查任务过期时间 在[React中的高优先级任务插队机制](https://github.com/neroneroffy/react-source-code-debug/blob/master/docs/%E5%89%8D%E7%BD%AE%E7%9F%A5%E8%AF%86/React%E4%B8%AD%E7%9A%84%E4%BC%98%E5%85%88%E7%BA%A7.md) 那篇文章中提到过,`ensureRootIsScheduled`函数作为统一协调任务调度的角色,它会调用`markStarvedLanesAsExpired`函数,目的是把当前进来的这个任务的过期时间记录到root.expirationTimes,并检查这个任务是否已经过期,若过期则将它的lane放到root.expiredLanes中。 ```javascript function ensureRootIsScheduled(root: FiberRoot, currentTime: number) { // 获取旧任务 const existingCallbackNode = root.callbackNode; // 记录任务的过期时间,检查是否有过期任务,有则立即将它放到root.expiredLanes, // 便于接下来将这个任务以同步模式立即调度 markStarvedLanesAsExpired(root, currentTime); ... } ``` `markStarvedLanesAsExpired`函数的实现如下: *暂时不需要关注suspendedLanes和pingedLanes* ```javascript export function markStarvedLanesAsExpired( root: FiberRoot, currentTime: number, ): void { // 获取root.pendingLanes const pendingLanes = root.pendingLanes; // suspense相关 const suspendedLanes = root.suspendedLanes; // suspense的任务被恢复的lanes const pingedLanes = root.pingedLanes; // 获取root上已有的过期时间 const expirationTimes = root.expirationTimes; // 遍历待处理的lanes,检查是否到了过期时间,如果过期, // 这个更新被视为饥饿状态,并把它的lane放到expiredLanes let lanes = pendingLanes; while (lanes > 0) { /* pickArbitraryLaneIndex是找到lanes中最靠左的那个1在lanes中的index 也就是获取到当前这个lane在expirationTimes中对应的index 比如 0b0010,得出的index就是2,就可以去expirationTimes中获取index为2 位置上的过期时间 */ const index = pickArbitraryLaneIndex(lanes); const lane = 1 << index; // 上边两行的计算过程举例如下: // lanes = 0b0000000000000000000000000011100 // index = 4 // 1 = 0b0000000000000000000000000000001 // 1 << 4 = 0b0000000000000000000000000001000 // lane = 0b0000000000000000000000000001000 const expirationTime = expirationTimes[index]; if (expirationTime === NoTimestamp) { // Found a pending lane with no expiration time. If it's not suspended, or // if it's pinged, assume it's CPU-bound. Compute a new expiration time // using the current time. // 发现一个没有过期时间并且待处理的lane,如果它没被挂起, // 或者被触发了,那么去计算过期时间 if ( (lane & suspendedLanes) === NoLanes || (lane & pingedLanes) !== NoLanes ) { expirationTimes[index] = computeExpirationTime(lane, currentTime); } } else if (expirationTime <= currentTime) { // This lane expired // 已经过期,将lane并入到expiredLanes中,实现了将lanes标记为过期 root.expiredLanes |= lane; } // 将lane从lanes中删除,每循环一次删除一个,直到lanes清空成0,结束循环 lanes &= ~lane; } } ``` 通过`markStarvedLanesAsExpired`的标记,过期任务得以被放到root.expiredLanes中在随后获取任务优先级时,会优先从root.expiredLanes中取值去计算优先级,这时得出的优先级是同步级别,因此走到下面会以同步优先级调度。实现过期任务被立即执行。 ```javascript function ensureRootIsScheduled(root: FiberRoot, currentTime: number) { // 获取旧任务 const existingCallbackNode = root.callbackNode; // 记录任务的过期时间,检查是否有过期任务,有则立即将它放到root.expiredLanes, // 便于接下来将这个任务以同步模式立即调度 markStarvedLanesAsExpired(root, currentTime); ... // 若有任务过期,这里获取到的会是同步优先级 const newCallbackPriority = returnNextLanesPriority(); ... // 调度一个新任务 let newCallbackNode; if (newCallbackPriority === SyncLanePriority) { // 过期任务以同步优先级被调度 newCallbackNode = scheduleSyncCallback( performSyncWorkOnRoot.bind(null, root), ); } } ``` # 何时记录并检查任务是否过期 concurrent模式下的任务执行会有时间片的体现,检查并记录任务是否过期就发生在每个时间片结束交还主线程的时候。可以理解成在整个(高优先级)任务的执行期间, 持续调用`ensureRootIsScheduled`去做这件事,这样一旦发现有过期任务,可以立马调度。 执行任务的函数是`performConcurrentWorkOnRoot`,一旦因为时间片中断了任务,就会调用`ensureRootIsScheduled`。 ```javascript function performConcurrentWorkOnRoot(root) { ... // 去执行更新任务的工作循环,一旦超出时间片,则会退出renderRootConcurrent // 去执行下面的逻辑 let exitStatus = renderRootConcurrent(root, lanes); ... // 调用ensureRootIsScheduled去检查有无过期任务,是否需要调度过期任务 ensureRootIsScheduled(root, now()); // 更新任务未完成,return自己,方便Scheduler判断任务完成状态 if (root.callbackNode === originalCallbackNode) { return performConcurrentWorkOnRoot.bind(null, root); } // 否则retutn null,表示任务已经完成,通知Scheduler停止调度 return null; } ``` > performConcurrentWorkOnRoot是被Scheduler持续执行的,这与Scheduler的原理相关,可以移步到我写的 [一篇文章搞懂React的任务调度机制](https://github.com/neroneroffy/react-source-code-debug/blob/master/docs/%E8%B0%83%E5%BA%A6%E6%9C%BA%E5%88%B6/Scheduler.md) 这篇文章中去了解一下,如果暂时不了解也没关系,你只需要知道它会被Scheduler在每一个时间片内都调用一次即可。 一旦时间片中断了任务,那么就会走到下面调用`ensureRootIsScheduled`。我们可以追问一下时间片下的fiber树构建机制,更深入的理解`ensureRootIsScheduled` 为什么会在时间片结束的时候调用。 这一切都要从`renderRootConcurrent`函数说起: ```javascript function renderRootConcurrent(root: FiberRoot, lanes: Lanes) { // workLoopConcurrent中判断超出时间片了, // 那workLoopConcurrent就会从调用栈弹出, // 走到下面的break,终止循环 // 然后走到循环下面的代码 // 就说明是被时间片打断任务了,或者fiber树直接构建完了 // 依据情况return不同的status do { try { workLoopConcurrent(); break; } catch (thrownValue) { handleError(root, thrownValue); } } while (true); if (workInProgress !== null) { // workInProgress 不为null,说明是被时间片打断的 // return RootIncomplete说明还没完成任务 return RootIncomplete; } else { // 否则说明任务完成了 // return最终的status return workInProgressRootExitStatus; } } ``` renderRootConcurrent中写了一个do...while(true)的循环,目的是如果任务执行的时间未超出时间片限制(一般未5ms),那就一直执行, 直到`workLoopConcurrent`调用完成出栈,brake掉循环。 `workLoopConcurrent`中依据时间片去深度优先构建fiber树 ```javascript function workLoopConcurrent() { // 调用shouldYield判断如果超出时间片限制,那么结束循环 while (workInProgress !== null && !shouldYield()) { performUnitOfWork(workInProgress); } } ``` 所以整个持续检查过期任务过程是:一个更新任务被调度,Scheduler调用`performConcurrentWorkOnRoot`去执行任务,后面的步骤: 1. `performConcurrentWorkOnRoot`调用`renderRootConcurrent`,`renderRootConcurrent`去调用`workLoopConcurrent`执行fiber的构建任务,也就是update引起的更新任务。 2. 当执行时间超出时间片限制之后,首先`workLoopConcurrent`会弹出调用栈,然后`renderRootConcurrent`中的do...while(true)被break掉,使得它也弹出调用栈,因此回到`performConcurrentWorkOnRoot`中。 3. `performConcurrentWorkOnRoot`继续往下执行,调用`ensureRootIsScheduled`检查有无过期任务需要被调度。 4. 本次时间片跳出后的逻辑完成,Scheduler会再次调用`performConcurrentWorkOnRoot`执行任务,重复1到3的过程,也就实现了持续检查过期任务。 # 总结 低优先级任务的饥饿问题其实本质上还是高优先级任务插队,但是低优先级任务在被长时间的打断之后,它的优先级并没有提高,提高的根本原因是`markStarvedLanesAsExpired`将过期任务的优先级放入root.expiredLanes,之后优先从expiredLanes获取任务优先级以及渲染优先级,即使pendingLanes中有更高优先级的任务,但也无法从pendingLanes中 获取到高优任务对应的任务优先级。 欢迎扫码关注公众号,发现更多技术文章 ![](https://neroht.com/qrcode-small.jpg)
C#
UTF-8
442
2.78125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Padroes.Patterns.Behavioral.Mediator { public class ClienteLocal : Cliente { public ClienteLocal(IMediator mediator) : base(mediator) { } public override void Receber(string msg) { Console.WriteLine($"Client local recebeu: {msg}."); } } }
Java
UTF-8
1,326
2.75
3
[]
no_license
import io.github.bonigarcia.wdm.WebDriverManager; import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import java.io.IOException; import java.util.concurrent.TimeUnit; public class GetRectangle { public static void main(String[] args) { WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.get("https://www.gmail.com/"); WebElement emailId = driver.findElement(By.id("identifierId")); //getting Element Dimension in Selenium 3: Dimension emailIdDim = emailId.getSize(); System.out.println(emailIdDim.getHeight()); System.out.println(emailIdDim.getWidth()); Point p = emailId.getLocation(); System.out.println(p.getX()); System.out.println(p.getY()); System.out.println("#############################"); //getting Element Dimension in Selenium 4: Rectangle emailIdRect = emailId.getRect(); System.out.println(emailIdRect.getHeight()); System.out.println(emailIdRect.getWidth()); System.out.println(emailIdRect.getX()); System.out.println(emailIdRect.getY()); driver.close(); } }
C++
UTF-8
765
3.03125
3
[]
no_license
#ifndef PLAYER_H #define PLAYER_H #include <SFML/System.hpp> #include <SFML/Graphics.hpp> #include <string> /* Player states: -1: Forfeit 0: Playing 1: Finished */ class Player { private: sf::Vector2f coord; sf::RectangleShape rect; std::string name; // int wins, losses; int pos, state, win_pos; public: void init(std::string, int); void move(int); void render(sf::RenderWindow& window); void update(); void set_position(float, float); void set_state(int s){state = s;} void set_win_pos(int p){win_pos = p;} sf::RectangleShape get_rect() {return rect;} int get_pos(){return pos;} int get_state(){return state;} // int get_wins(){return wins;} // int get_losses(){return losses;} std::string get_name(){return name;} }; #endif // PLAYER_H
Markdown
UTF-8
1,054
2.734375
3
[]
no_license
Geo_decoder ========== synopsis for getting address -------- ```javascript var geo = require('geo_decoder'); geo.getAddress(latitude, longitude, function(err, result) { if (err) { console.log(err); } else { console.log(result); } // response { address: 'A-4, NH 64, Green Enclave, Lohgarh, Zirakpur, Punjab 140603, India', postal_code: '140603', country_code: 'PB', country: 'Punjab' } ``` synopsis for getting longitude and latitude -------- ```javascript var geo = require('geo_decoder'); geo.getLatLong("Enter Your Address Here",function(err,result){ // console.log('err===',err,result); if(err){ console.log(err); }else{ console.log(result); } }); // response { latitude: 30.7112416, longitude: 76.7927981 } ``` synopsis for getting distance between longitude and latitude -------- ```javascript var geo = require('geo_decoder'); var point1 = { x1: 1, y1: 1 }; var point2 = { x2: 4, y2: 5 }; var distace = geo.distance(point1, point2); console.log("Distance between: ", point1, " and ", point2, " is:", distace); ```
Java
UTF-8
2,247
2.546875
3
[]
no_license
package com.qriyo.android.data; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; /** * Created by DELL on 1/29/2016. */ public class StoredData { Context context; SharedPreferences preferences; SharedPreferences.Editor preferenceEditor; public StoredData(Context context) { super(); this.context = context; preferences= PreferenceManager.getDefaultSharedPreferences(context); preferenceEditor=preferences.edit(); } /* * Login Module data begins * isUserLoggedin() * setUserLoggedin(boolean isLoggedin) * getuserData() * saveUserData(String userData) * logout() */ //----if user is logged in used for navigation from the splash activity public boolean isUserLoggedin() { return preferences.getBoolean("isLoggedin", false); } //-----isUserLoggedin() body ends here--------------------------------------- //--Set the login value------------------------------------------------------ public void setUserLoggedin(boolean isLoggedin) { preferenceEditor.putBoolean("isLoggedin", isLoggedin); preferenceEditor.commit(); } //---------setUserLoggedin body ends here------------------------------------- //-----returns the JSON response saved after login for logged in user //-----Can be parsed to retrieve the user information---------------- public String getuserData() { return preferences.getString("saveduserdata", ""); } //-------getuserData() body ends here--------------------------------- //------Saves the user data after login------------------------------- public void saveUserData(String userData) { preferenceEditor.putString("saveduserdata", userData); preferenceEditor.commit(); } //---------saveUserData body ends here--------------------------------- //----Cleans the stored data------------------------------------------- public void logout() { preferenceEditor.clear(); preferenceEditor.commit(); } //-----Logout body ends here-------------------------------------------- /* * User Login Module related functions ends here */ }
Markdown
UTF-8
335
2.828125
3
[]
no_license
# gitme A command line tool to see your git commits across multiple projects ## Installation npm install -g gitme ## Usage View commits for multiple repos: gitme Add some repos: gitme add [repo-location] Remove a repo: gitme rm [repo-location] List all repos: gitme ls View help: gitme --help