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
Python
UTF-8
3,771
3.046875
3
[]
no_license
current_r, current_c, current_d = 7, 4, 0 current_room_map = [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 1, 1, 1, 1, 0, 1], [1, 0, 0, 1, 1, 0, 0, 0, 0, 1], [1, 0, 1, 1, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 0, 1, 1, 0, 1], [1, 0, 0, 0, 0, 0, 1, 1, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] ] # 북: row -1, col 0, 동: row 0, col +1, 남: row +1, col 0, 서: row 0, col -1 dr = [-1, 0, 1, 0] dc = [0, 1, 0, -1] # 북 0 동 1 남 2 서 3(index 로) # 북쪽에서 왼쪽으로 회전하면: 서쪽, 0 -> 3번 인덱스 # 동쪽에서 왼쪽으로 회전: 북쪽, 1 -> 0 # 남쪽에서 왼쪽으로 회전: 동쪽, 2 -> 1 # 서쪽에서 왼쪽으로 회전: 남쪽, 3 -> 2 # 북쪽에서 후진하면(왼쪽으로 두 번 회전): 남쪽, 0 -> 2 # 동 후진: 서, 1 -> 3 # 남 후진: 북, 2 -> 0 # 서 후진: 동, 3 -> 1 # 회전 함수 구현 def get_d_index_when_rotate_to_left(d): return (d + 3) % 4 # 후진 함수 구현 def get_d_index_when_go_back(d): return (d + 2) % 4 # 1. 현재 위치를 청소한다. # bfs를 구현 visited = [1, 2, 3] # 0은 청소하지 않은 장소 # 1은 청소하지 못하는 장소 # 2는 청소한 장소 # 2. 현재 위치에서 현재 방향을 기준으로 왼쪽 방향부터 차례대로 # 탐색 진행 # -> 방향 # a. 왼쪽 방향에 아직 청소하지 않은 공간이 존재한다면 # 그 방향으로 회전한 다음 한 칸으 전진하고 1번부터 진행 # b. 왼쪽 방향에 청소할 공간이 없다면, 그 방향으로 회전하고 # 2번으로 돌아감. # -> 현재 본 방향에서 청소할 공간이 없으면 다시 왼쪽으로 회전 # c. 네 방향 모두 청소가 되어 있거나 벽인 경우 # 바라보는 방향을 유지한 채로 한 칸 후진 하고 2번으로 돌아감. # -> 모든 방향이 청소되어 있다면, 뒤로 한 칸 후진 # d. 네 방향 모두 청소가 이미 되어 있거나 벽이면서, # 뒤쪽 방향이 벽이라 후진도 할 수 없는 경우에는 작동을 멈춘다. def get_count_of_departments_cleaned_by_robot_vacuum(r, c, d, room_map): n = len(room_map) m = len(room_map[0]) count_of_departments_cleaned = 1 room_map[r][c] = 2 queue = list([[r, c, d]]) while queue: r, c, d = queue.pop(0) temp_d = d for i in range(4): temp_d = get_d_index_when_rotate_to_left(temp_d) new_r, new_c = r + dr[temp_d], c + dc[temp_d] if 0 <= new_r < n and 0 <= new_c < m and current_room_map[new_r][new_c] == 0: count_of_departments_cleaned += 1 room_map[new_r][new_c] = 2 queue.append([new_r, new_c, temp_d]) break # c. 네 방향 모두 청소가 되어 있거나 벽인 경우 # 바라보는 방향을 유지한 채로 한 칸 후진하고 2번으로 돌아감 elif i == 3: # 마지막 인덱스까지 왔는데(네 방향 모두 확인 했는데도 못 찾았을 때) new_r, new_c = r + dr[get_d_index_when_go_back(temp_d)], c + dc[get_d_index_when_go_back(temp_d)] queue.append([new_r, new_c, temp_d]) # d. 네 방향 모두 청소가 이미 되어 있거나 벽이면서, # 뒤쪽 방향이 벽이라 후진도 할 수 없는 경우에는 작동을 멈춘다. if current_room_map[new_r][new_c] == 1: return count_of_departments_cleaned # 57 가 출력되어야 합니다! print(get_count_of_departments_cleaned_by_robot_vacuum(current_r, current_c, current_d, current_room_map))
Markdown
UTF-8
12,745
3.34375
3
[]
no_license
--- layout: post title: "The Benefits of Proof of Work" author: "Daniel Larimer" categories: article --- I have long been of the opinion that proof-of-stake is superior to proof-of-work. Today I would like to challenge my own beliefs against the lessons I have learned from over a year of experience with proof-of-stake. In the past I have argued that proof-of-work is wasteful and that the same end result can be achieved much cheaper with proof-of-stake. Today I would like to consider if there is some value to proof-of-work. <!-- more --> ## Mandatory Disclaimer What follows is an idea and perspective on proof-of-work and does not constitute a proposal to modify BitShares, its dilution rate, or its voting algorithms. ## Work Defined If we are going to talk about the benefits of proof-of-work, then it helps to have a useful definition of work. In terms of physics, work is defined as *power* X *time*. W = Pt In more general terms, I would define work as something you must *pay* people to do. If it doesn’t cost anything then no work was done. Bitcoin satisfies both definitions of proof-of-work. No one would spend money building specialized hardware and consuming electricity if they weren’t paid to do so. Therefore, Bitcoin’s block difficulty represents mathematical proof that about 25 BTC worth of work was performed. The corollary here is that if you pay a fixed amount of money into a competitive market then market competition will drive the work required to earn that money toward the value of the money. We can view Bitcoin Work as Difficulty or HashPower * 10 minutes. W = D = HP * 10m In proof-of-stake systems we only have power, aka stake. I would like you to consider that committing to hold a token for a period of time in the future is work. No one gives up liquidity or locks funds up without expecting interest. The value of the interest paid is therefore proportional to the *work* required to earn it. In the same way, the value of the Bitcoin mining rewards is proportional to the *work* required to earn it. Based upon this understanding of work and the value of liquidity we can construct a proof-of-work system that doesn’t require a large amount of money to be transferred to the electric company and mining hardware manufactures. This proof-of-work system does require the money to be transferred to someone though. In this case, it is transferred to those who committed to hold the token by diluting those who demanded liquidity. This has the effect boosting the value of a token in the short term by postponing sell pressure. There are two ways to do proof-of-work with stake: 1. Based on how long you held a coin in the past 2. Based on how long you promise to hold a coin into the future I will submit for your consideration that what someone did or didn’t do in the past is a risk-free sunk cost similar to renting mining equipment on a day to day basis. On the other hand, promising to hold a coin into the future is a high-risk cost similar to buying mining equipment that takes a year to earn back the initial capital. In terms of security, the future value of a coin is the only thing that matters and this is why option #2 is superior. ## Everyone Hates Politics As blockchains become more complex, politics becomes a bigger and bigger issue. Proof-of-work has this wonderful property of appearing to be free of politics. At a consensus level it is mathematically simple, clean, and fully decentralized. In theory anyone can join the network and start producing blocks. In practice, proof-of-work has created a pay-to-play model where those who are willing to spend the most to control the network win. The security in such a system comes from the expense and opportunity cost of mining a particular block and the fact that those doing the mining have a long-term capital commitment and therefore act in a manner to maximize their return. ## Politics is Unavoidable We have learned from the Bitcoin XT debate that politics is unavoidable. Proof-of-work doesn’t eliminate the politics it simply changes where the politics play out. Rather than a stake-weighted-vote on the blockchain it becomes a web poll or a vote at the Bitcoin Foundation. Mining pool operators end up voting on which fork to support and users vote with their CPU power. Because politics is unavoidable, it makes the most sense to have the voting done directly on the blockchain. Bitcoin and Peercoin do this voting by signaling with each block that is produced, but this isn’t the only or most convenient way to do voting. Instead of voting by block production, voting can be done via transactions that indicate how “coindays” or “committed stake” should vote. This voting can even include voting on the set of active block producers and when they should be producing blocks like is done with *delegated-proof-of-stake*. The primary challenge with Bitcoin and Peercoin style proof-of-work systems is that only technically savvy individuals who can endure the costs of running a full node on the network may participate in the voting process. The Bitcoin economy solves this problem via cloud mining operations where non-technical users “vote-by-proxy” through hiring someone else to mine on their behalf. ## Voter Apathy Under delegated proof-of-stake one of our major challenges is voter apathy. Many people vote once and then forget to change their vote or they vote for a proxy and then forget to follow up. The usual end result is that it becomes difficult to vote out incumbents or vote in new individuals. The presence of voter apathy is a sign that incentives are not properly aligned in the system. This is where migrating from delegated-proof-of-stake to a delegated-proof-of-work system has some serious benefits. When power is in the hands of users who have a long-term capital commitment to a project they have greater incentive to vote because they cannot sell for months or years. Under the existing delegated-proof-of-stake system most users opt to passively accept the decisions made by others and then vote with their feet by selling the token if they don’t like the result. When users have the ability to “vote without commitment” the whole community plays a heads-I-win, tails-you-lose game where winning the vote means losing the minority who disengage in the process which then undermines the value of the token. ## Eliminating Exchange Risk Stake-commitment based proof-of-work has the added benefit of reducing the risk posed by centralized exchanges having a large percentage of network stake. In BitShares 25% of the stake is held in the top several exchanges. These exchanges have opted to “not-vote” and thus do not help secure the network, but the risk remains that at any moment they could start voting and have complete control over the network. By adding stake-commitment based proof-of-work to the mix, the exchange would be unable to both vote *and* guarantee withdraw on demand. In the best case, the exchange could keep their funds divided into a ladder of commitments such that they could maintain withdraw requests. ## Is Proof-of-Work Wasteful The $1 million dollar a day question is whether or not money spent on proof-of-work is wasteful. To answer this question requires making a comparison among several alternatives. For the sake of this analysis I am going to assume that there is a fixed cost for the proof-of-work and then look at the value of what is solved. Bitcoin and other similar coins use proof-of-work to solve several different problems at the same time: 1. Deciding when the next block should be produced 2. Deciding who should produce the next block 3. Making it expensive to produce an alternative chain 4. Deciding on the best blockchain 5. Distribution 6. Side Benefits (such as Primecoin) Of these six things, mining is a terribly inefficient/slow way to determine when blocks should be produced and who should produce them. A lot of work is wasted due to a failure to reach consensus on when and who in advance. This leaves only solving the last 4 problems as a means to justify the cost. The capital commitment that bitcoin mining enforces creates a kind of self-reinforcing lock-in. People commit to the project, invest in equipment and then are forced to market and promote Bitcoin over a long-term basis in order to recover their costs and make a small profit. Distributing the new coins via mining provides an easy way to get new users on board without having to buy in. Both of these things have non-zero value. If BitShares diluted to pay people who produce difficult hashes built off of recent blocks then this work would end up securing the network with the same kind of cost and objective proof as Bitcoin. This would give BitShares the benefits of solving problems #3, #4, #5, and #6 while still retaining the benefits BitShares enjoys in terms of consistent 3-second blocks and the elimination of the need for mining pools. So the question of whether or not a particular kind of proof-of-work is wasteful depends only on the relative value of *side benefits* to the value spent. In the case of Bitcoin or Peercoin, the *side benefits* include the generation of specialized hardware. In the case of stake-commitment proof-of-work the *side benefit* is that a large percentage of a token are kept out of circulation which helps increase the value of the liquid tokens. In other words, instead of investing money outside the ecosystem in hardware and electricity, money gets invested into the ecosystem in terms of long-term investment support. When stake-commitment proof-of-work is used, value is transferred from those who need liquidity but choose to hold anyway to those who give it up for fixed periods of time. This creates an investment vehicle that is more than just speculation. ## Investor vs. Speculator Sometimes it is helpful to consider the difference between a speculator and an investor. An investor puts money into a company in exchange for equity that may not be liquid for years. The money the put in goes directly toward funding the company and contributes to the long term value of the company. A speculator on the other hand could deal entirely in derivatives because they only care about changes in the price. In other words, speculators buy and sell frequently and have no loyalty. The most that can be said for speculators is that they provide liquidity that allows people to enter and leave the market at smaller spreads. A startup company that has 100% of its outstanding stock on the open market has a harder time attracting new investment because newly created shares are competing with existing shares for today’s liquidity. For this reason almost all startups prefer to tie up investor funds and deny liquidity until they reach IPO or similar liquidity event. By diluting speculators to compensate investors with a long-term outlook you can have the best of both worlds. If all investors lock up their funds for an equal period of time then there is in effect no dilution faced by investors. On the other hand, if some investors demand liquidity then the other investors profit. ## Distribution When a new company is created shares are allocated to those who contributed to the company proportional to their contribution. If two parters each put in equal work in the first year they should each own 50% of the company. If in the second year one of the partners quits, then at the end of the second year one partner should have 67% and the other 33% based upon the amount of work they contributed. Based upon this theory, then all dilution to pay for work the company wants done is legitimate. The only question that matters is whether the work being done is *worth* having done. To use the partner example, if in the second year the remaining partner dug holes and filled them back in then the original partner may be upset because that work did not bring any additional value to the shares. From this perspective, paying individuals to commit funds for longer periods of time and/or using the rate of pay as a means of regulating price volatility provides enduring value where as paying for miners might have less and less value as the amount of work increases. ## Conclusion After a year gaining experience with delegated-proof-of-stake (DPOS) I have concluded that certain kinds of proof-of-work are actually incredibly valuable and useful to an ecosystem's development and that using dilution as high as 15% on short-term speculators to compensate long-term investors can be very helpful in both securing the network, building loyalty, and creating a profitable system.
C#
UTF-8
1,472
2.796875
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; public class Unit : MonoBehaviour{ public int tileX; public int tileZ; public TileMap map; int unitSpeed = 4; public List<Node> currentPath = null; void Update() { if(currentPath != null) { int currNode = 0; while( currNode < currentPath.Count-1 ) { Vector3 start = map.TileCoordToWorldCoord( currentPath[currNode].x, currentPath[currNode].z ) + new Vector3(0, 1f, 0) ; Vector3 end = map.TileCoordToWorldCoord( currentPath[currNode+1].x, currentPath[currNode+1].z ) + new Vector3(0, 1f, 0) ; Debug.DrawLine(start, end, Color.red); currNode++; } } } public void MoveNextTile() { float remainingMovement = unitSpeed; while (remainingMovement > 0){ if (currentPath == null) return; remainingMovement -= map.CostToEnterTile(currentPath[0].x, currentPath[0].z, currentPath[1].x, currentPath[1].z); // Remove the old current/first node from the path/ currentPath.RemoveAt(0); // Now grab the new first node and move us to that position. tileX = currentPath[0].x; tileZ = currentPath[0].z; transform.position = map.TileCoordToWorldCoord(tileX, tileZ); if (currentPath.Count == 1){ // We only have one tile left in the path, and that tile MUST be our ultimate destination // Now lets clear our pathfinding info. currentPath = null; } } } }
Markdown
UTF-8
1,779
2.859375
3
[ "MIT" ]
permissive
--- layout: essay type: essay title: Closed for maintenance date: 2016-12-12 labels: - Github --- In my ICS 212 class that I took this last semester, we were forced to become familiar with something called SCCS. Simply put, SCCS is one of the predecessors to Github. The only difference is that it's Unix based and is significantly less powerful in terms of file size and distribution (it's not a website that's publicly accessible). The point of this is that even early programmers were aware of the need for "Configuration management." This isn't wholly relevant to this question but I do believe that people in this course will find this amusing. Every year, San Jose state holds the "<a href="http://www.bulwer-lytton.com/">Bulwer-Lytton Fiction Contest</a>." The specifications of the contest are so hilarious that I implore everyone to look it up on their own. The point of this is that the website is an excellent example of a technical product that is poorly maintained. I swear that they only ever update this website when the year's winners are announced. The site is hasn't been modified visually for years and if you look at the winners of any specific year, you'll notice that the picture aren't even properly aligned. A "terrible beauty" if I do say so myself. So how important is Github? Github, or at least the concept of Github seeing as how there are other popular sites like it like Bitbucket, is essential to any sort of team based work. In literature if you want to collaborate on a certain piece of work, one would probably need to physically meet with someone in order organise all of your stuff and merge it into one cohesive text. Git is the same, the only difference being that this collaboration occurs online and at potentially different times.
C#
UTF-8
469
3.171875
3
[ "MIT" ]
permissive
using System.Collections.Generic; namespace Aoc2018.Day15.Paths { public interface IGraph<T> { IEnumerable<T> GetVertexes(); IEnumerable<Neighbour<T>> GetNeighbours(T vertex); } public struct Neighbour<T> { public T Vertex { get; } public int Distance { get; } public Neighbour(T vertex, int distance) : this() { Vertex = vertex; Distance = distance; } } }
C++
UTF-8
391
3.46875
3
[]
no_license
//calcular el diametro y area de un circulo donde se ingrese el radio. #include <iostream> using namespace std; int main(){ int radio{0}; int diametro{0}; int area{0}; cout<<"Ingrese el radio de la circunferencia: "; cin>>radio; diametro=2*radio; area=3.14159*(radio*radio); cout<<"El diametro es:" <<diametro<<endl; cout<<"El area es: " <<area<<endl; }
C++
UTF-8
426
2.640625
3
[]
no_license
#ifndef _Creature_H_ #define _Creature_H_ #include<iostream> #include<string.h> #include <stdlib.h> class Creature{ public: Creature(int whichid); int getid(); int getdirect(); virtual void updateaction()=0; virtual int getaction()=0; virtual void updateage()=0; virtual int getage()=0; virtual int getpoint()=0; virtual void updatepoint(int p)=0; private: int act; int id; int direct; }; #endif
Java
UTF-8
4,112
2.6875
3
[]
no_license
package com.lambdaschool.congressdataapiaccess; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.HandlerThread; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import javax.net.ssl.HttpsURLConnection; public final class NetworkAdapter { private static final int TIMEOUT = 3000; private static final String API_KEY = "glCbNQgEiisCdhTwucffBYZfvBXiHCiZ18S2pEFL"; public static String httpGetRequest(final String urlString) { final String[] result = new String[1]; Thread downloadThread = new HandlerThread("UIHandler"){ @Override public void run(){ InputStream stream = null; HttpsURLConnection connection = null; try { URL url = new URL(urlString); connection = (HttpsURLConnection) url.openConnection(); connection.setRequestProperty("x-api-key", API_KEY); connection.setReadTimeout(TIMEOUT); connection.setConnectTimeout(TIMEOUT); connection.setRequestMethod("GET"); connection.setDoInput(true); connection.connect(); int responseCode = connection.getResponseCode(); if (responseCode != HttpsURLConnection.HTTP_OK) { result[0] = Integer.toString(responseCode); throw new IOException("HTTP error code: " + responseCode); } stream = connection.getInputStream(); if (stream != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line).append('\n'); } result[0] = sb.toString(); } } catch (IOException e) { e.printStackTrace(); } finally { // Close Stream and disconnect HTTPS connection. if (stream != null) { try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } if (connection != null) { connection.disconnect(); } } } }; downloadThread.start(); try { downloadThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } return result[0]; } public static Bitmap getBitmapFromURL(final String urlString) { final Bitmap[] result = new Bitmap[1]; Thread downloadThread = new HandlerThread("UIHandler"){ @Override public void run(){ HttpsURLConnection connection = null; try { java.net.URL url = new java.net.URL(urlString); connection = (HttpsURLConnection) url .openConnection(); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); result[0] = BitmapFactory.decodeStream(input); } catch (IOException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } } }; downloadThread.start(); try { downloadThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } return result[0]; } }
C#
UTF-8
2,439
2.671875
3
[]
no_license
using CSGProHackathonAPI.Shared.Models; using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSGProHackathonAPI.Shared.Data { public class Context : DbContext, IContext { public Context() : base(nameOrConnectionString: "Context") { } public DbSet<Project> Projects { get; set; } public DbSet<ProjectRole> ProjectRoles { get; set; } public DbSet<ProjectTask> ProjectTasks { get; set; } public DbSet<TimeEntry> TimeEntries { get; set; } public DbSet<User> Users { get; set; } public void PrepareEntityForSave<TEntityType>(TEntityType entity) where TEntityType : BaseModel { if (entity == null) { throw new ArgumentException("Cannot prepare a null entity for save."); } if (entity.IsNew()) Set<TEntityType>().Add(entity); else Entry<TEntityType>(entity).State = System.Data.Entity.EntityState.Modified; } public void SaveEntity<TEntityType>(TEntityType entity) where TEntityType : BaseModel { PrepareEntityForSave<TEntityType>(entity); SaveChanges(); } public Task SaveEntityAsync<TEntityType>(TEntityType entity) where TEntityType : BaseModel { PrepareEntityForSave<TEntityType>(entity); return SaveChangesAsync(); } public void DeleteEntity(object entity) { Entry(entity).State = EntityState.Deleted; SaveChanges(); } public Task DeleteEntityAsync(object entity) { Entry(entity).State = EntityState.Deleted; return SaveChangesAsync(); } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>(); modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>(); var timeEntryEntity = modelBuilder.Entity<TimeEntry>(); timeEntryEntity.Property(te => te.Hours).HasPrecision(4, 2); } } }
Python
UTF-8
1,374
2.53125
3
[]
no_license
#including the loss plot niter = 1000 # losses will also be stored in the log train_loss = np.zeros(niter) scratch_train_loss = np.zeros(niter) test_label= np.zeros(niter) caffe.set_device(0) caffe.set_mode_gpu() # We create a solver that fine-tunes from a previously trained network. solver = caffe.SGDSolver('myfinetunning/data/solver.prototxt') solver.net.copy_from('models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel') # For reference, we also create a solver that does no finetuning. scratch_solver = caffe.SGDSolver('myfinetunning/data/solver.prototxt') # We run the solver for niter times, and record the training loss. for it in range(niter): solver.step(1) # SGD by Caffe scratch_solver.step(1) # store the train loss train_loss[it] = solver.net.blobs['loss'].data scratch_train_loss[it] = scratch_solver.net.blobs['loss'].data test_label[it]=solver.net.blobs['label'].data if it % 10 == 0: print 'iter %d, finetune_loss=%f, scratch_loss=%f' % (it, train_loss[it], scratch_train_loss[it]) print 'done' sio.savemat('/home/lein/caffe/myfinetunning/data/train_loss',{'data':train_loss}) sio.savemat('/home/lein/caffe/myfinetunning/data/loss_scrach',{'data':scratch_train_loss}) sio.savemat('/home/lein/caffe/myfinetunning/data/pred_label',{'data':test_label})
C#
UTF-8
684
2.546875
3
[]
no_license
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace SuperheroesUniverse.Models { public class Planet { public Planet() { this.Countries = new HashSet<Country>(); this.Fractions = new HashSet<Fraction>(); } [Key] public int Id { get; set; } [Required] [Index(IsUnique = true)] [MinLength(2), MaxLength(30)] public string Name { get; set; } public virtual ICollection<Country> Countries { get; set; } public virtual ICollection<Fraction> Fractions { get; set; } } }
JavaScript
UTF-8
1,702
2.640625
3
[ "MIT" ]
permissive
import { Text } from "@pixi/text"; import { ClientPacket } from "../network/Packets"; import { game } from "../OinkyParty"; import { titleColor } from "../Screen"; import { GameScreen } from "./GameScreen"; class AddCounterPacket extends ClientPacket { constructor() { super("counterGame-addCounter"); } } export class CounterGame extends GameScreen { constructor() { super(); this.handleUpdateCounterPacket = this.handleUpdateCounterPacket.bind( this ); this.handleClick = this.handleClick.bind(this); this.counter = 0; this.counterText = new Text("Counter: 0", { fill: titleColor, size: 50, }); this.counterText.pivot.set( this.counterText.width / 2, this.counterText.height / 2 ); this.counterText.position.set( game.renderer.width / 2, game.renderer.height / 2 ); this.counterText.interactive = true; this.counterText.on("pointerdown", this.handleClick); this.addChild(this.counterText); game.socket.addEventListener( "counterGame-updateCounter", this.handleUpdateCounterPacket ); } destroy() { game.socket.removeEventListener( "counterGame-updateCounter", this.handleUpdateCounterPacket ); } handleClick() { this.counter++; game.socket.sendPacket(new AddCounterPacket()); } handleUpdateCounterPacket(event) { let packet = event.detail; this.counter = packet.counter; this.counterText.text = "Counter: " + this.counter; } }
Markdown
UTF-8
1,011
2.640625
3
[ "MIT" ]
permissive
# TG Session - Telegram Session Generator <a aria-label="npm downloads" href="https://www.npmjs.com/package/tgsession"> <img alt="" src="https://img.shields.io/npm/dw/tgsession.svg?label=NPM%20Downloads&style=for-the-badge&labelColor=000000"> </a> <a aria-label="License" href="https://github.com/Gowtham2003/tgsession/blob/main/README.md"> <img alt="" src="https://img.shields.io/npm/l/tgsession.svg?style=for-the-badge&labelColor=000000"> </a> Simple Telethon and GramJS string session generator written in GramJS ## What does it do ? * Generate Gramjs and Telethon Session String With Just One Command * No Setup Needed :) ## How to use it ? * Make Sure Node is Installed * Simply Run This in Terminal ``` npx tgsession ``` Or You can globally install on your system By Using npm ``` npm i -g tgsession ``` Or Using Yarn ``` yarn global add tgsession ``` Then Run ` tgsession ` in your terminal ### Supported Libraries * Telethon (Python) * GramJS (Javascript/Typescript)
Shell
UTF-8
1,769
3.34375
3
[]
no_license
#!/bin/bash setenforce 0 sed -r -i 's/SELINUX=.*/SELINUX=disabled/g' /etc/selinux/config # using this instead of "rpm -Uvh" to resolve dependencies function rpm_install() { package=$(echo $1 | awk -F "/" '{print $NF}') wget --quiet $1 yum install -y ./$package rm -f $package } release=$(awk -F \: '{print $5}' /etc/system-release-cpe) yum install -y epel-release yum install -y wget jq # install and configure puppet rpm -qa | grep -q puppet if [ $? -ne 0 ] then rpm_install http://yum.puppetlabs.com/puppet5-release-el-${release}.noarch.rpm yum -y install puppet-agent ln -s /opt/puppetlabs/puppet/bin/puppet /usr/bin/puppet fi if [[ "$HOSTNAME" = "psql1.example.com" ]] ; then cat > /etc/puppetlabs/puppet/autosign.conf <<EOF psql1.example.com psql2.example.com psql3.example.com haproxy.example.com sensu-backend.example.com EOF yum -y install puppetserver sed -i 's/2g /512m /g' /etc/sysconfig/puppetserver systemctl enable puppetserver systemctl start puppetserver fi puppet config set --section main server psql1.example.com if [ -d /etc/puppetlabs/code/environments/production ]; then rm -rf /etc/puppetlabs/code/environments/production fi puppet resource file /etc/puppetlabs/code/environments/production ensure=link target=/vagrant/production force=true puppet resource host psql1.example.com ensure=present ip=10.0.0.101 host_aliases=psql1 puppet resource host psql2.example.com ensure=present ip=10.0.0.102 host_aliases=psql2 puppet resource host psql3.example.com ensure=present ip=10.0.0.103 host_aliases=psql3 puppet resource host haproxy.example.com ensure=present ip=10.0.0.104 host_aliases=haproxy puppet resource host sensu-backend.example.com ensure=present ip=10.0.0.105 host_aliases=sensu-backend
C#
UTF-8
829
3.34375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TweetsieTrailGame { class ConsoleInputReader: ITextInputReader { public ConsoleInputReader() { } public void waitForKeyPress() { Console.ReadKey(true); } public bool loopUntilKeyPress() { return Console.KeyAvailable; } public String getLine() { return Console.ReadLine(); } public int getInt() { int intInput; bool success = int.TryParse(Console.ReadLine(), out intInput); if(!success) { throw new TweetsieInputException("Unable to convert input to integer"); } return intInput; } } }
Shell
UTF-8
3,687
3.203125
3
[]
no_license
####################################################### # Harry Kim .bashrc file #######################################################a FULL_NAME="Harry Kim" EMAIL="hkim@securitycompass.com" GIT_BASE="${HOME}" # On mac we use vim installed with Cellar/Brew # We also want to change the default Java if present if [ `echo "${OSTYPE}" | grep 'darwin'` ]; then alias vim=/usr/bin/vim #export JAVA_HOME=`/usr/libexec/java_home -v 1.8.0_60` fi # Add Local bin directory and ghar bin directory to path export PATH=${PATH}:~/bin:${GIT_BASE}/ghar/bin # Bash style tab completion for ghar ${GIT_BASE}/ghar/ghar-bash-completion.sh # Use proper prompts for RHEL/Centos/Fedora boxes parse_git_branch () { git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/' } export PROMPT_COMMAND='printf "\033]0;%s@%s:%s\007" "${USER}" "${HOSTNAME}" "${PWD/#$HOME/~}"' PS1='\[\033[01;32m\]\u@\H:\[\033[01;34m\]\w\$\[\033[00m\] $(parse_git_branch) \[\033[01;34m\] \$' # Set colors for ls and CLI on Mac export CLICOLOR=1 export LSCOLORS=GxFxCxDxBxegedabagaced # Git config git config --global user.name "Harry Kim" git config --global user.email hkim@securitycompass.com git config --global credential.helper cache # Set git to use the credential memory cache git config --global credential.helper 'cache --timeout=3600' # Set the cache to timeout after 1 hour (setting is in seconds) git config --global core.editor vim git config --global push.default simple # Ghar, store dotfiles in GIT # Pull latest on each login ghar pull > /dev/null ghar install > /dev/null # Run additional bashrc scipts or if .bashrc.d does not exist # create .bashrc.d directory # Only execute additional .bashrc scripts if they are secure, e.g. owned by the # user that is starting bash and not writable by others if [ -d "${HOME}/.bashrc.d" ]; then for script in $(find $HOME/.bashrc.d/ -type f -perm -g-xw,o-xw -user ${USER}); do source ${script} done else mkdir ${HOME}/.bashrc.d && chmod 700 ${HOME}/.bashrc.d && chmod -R og-wrx ${HOME}/.bashrc.d fi # If base virtualenv exists we add it to path and source it # venv="${HOME}/Virtualenvs/base" # if [ -d "${venv}" ]; then # source "${venv}/bin/activate" # fi source /usr/local/bin/virtualenvwrapper.sh # Make sure SSH Agent forwarding is enables for linux key_file=~/.ssh/id_rsa [[ -z $(ssh-add -L | grep $key_file) ]] && ssh-add $key_file # Aliases alias dj='python manage.py' alias djangocode='cd ~/local/envs/sdlc/lib/python2.6/site-packages/django/' alias djbuild='python manage.py build_large_deployment_data' alias djc='python manage.py collectstatic --noinput' alias djcelery='python manage.py celeryd --autoreload --purge' alias djgun='python manage.py run_gunicorn --settings=gunicorn_settings -b 0.0.0.0' alias djmigrate='python manage.py migrate' alias djrun='python manage.py runserver localhost:3000' alias djschema='python manage.py schemamigration --auto' alias djshell='python manage.py shell' alias djsync='python manage.py syncdb' alias djtest='python manage.py test --settings=test_local_settings --nomigrations --keepdb' alias djtestdb='python manage.py test --settings=test_local_settings --nomigrations' alias dumpdata='python manage.py dumpdata' alias emailserver='python -m smtpd -n -c DebuggingServer localhost:1025' alias flush_dns_cache='sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder' alias imgcat='/Users/hkim/.iterm2/imgcat' alias it2dl='/Users/hkim/.iterm2/it2dl' alias loaddata='python manage.py loaddata' alias prettyjson='python -m json.tool | pygmentize -l javascript' alias rmpyc='find . -name "*.pyc" -exec rm -rf {} \;' alias start_celery='celery -A . worker --app=sigma.celery_mod -l debug' alias vi='vim'
JavaScript
UTF-8
7,678
2.609375
3
[]
no_license
import React from 'react' import { Image, Transformation, CloudinaryContext } from 'cloudinary-react' import { setAnswer, setImageToAsk, setWrongAnswerOptions, setWrongImageOptions } from '../reducers/gameReducer' import { setMessage } from '../reducers/messageReducer' import { setScoreFlash } from '../reducers/scoreFlashReducer' import { connect } from 'react-redux' import { Button } from 'react-bootstrap' import emoji from 'node-emoji' /** * MultipleChoiceGame (run under Gameloop.js) is one of game mode of Luupeli. * In MultipleChoiceGame, the player sees the picture and four names of the different bones. * The player needs to click on the correct bone name. */ class MultipleChoiceGame extends React.Component { constructor(props) { super(props); this.timer = 0; this.state = { value: '', seconds: 0, currentStreak: 0, currentBonus: 0 } this.handleSubmit = this.handleSubmit.bind(this) window.onunload = function () { window.location.href = '/' } } /** * As the player submits the answer, the points will be calculated, gameplay stats will be stored and player message will be generated. * @param {*} event */ handleSubmit(event) { event.preventDefault() this.setState({ value: event.target.value }) this.createMessage(event.target.value) //let points = (Math.round((this.checkCorrectness(event.target.value) * Math.max(10, this.props.game.currentImage.bone.nameLatin.length)) * ((300 + Math.max(0, (300 - this.state.seconds))) / 600))) / 20 let points = Math.round((1000 + ((1000 + Math.max(0, (400 - this.props.game.gameClock))) / 800))) / 20 if (this.checkCorrectness(event.target.value) > 99) { points = points * 10 } points = Math.round(points / 20) * 20 if (this.checkCorrectness(event.target.value) < 70) { points = 0 } const correctness = this.checkCorrectness(event.target.value) let streakEmoji = require('node-emoji') streakEmoji = emoji.get('yellow_heart') let streakNote = '' let currentStreak = this.state.streakMCG let currentBonus = this.state.bonus points = 1000; if (correctness === 100) { this.setState({ streakMCG: currentStreak + 1, bonus: currentBonus + 0.5 }) streakNote = currentBonus + 'x!' } else { points = 0 streakEmoji = require('node-emoji') streakEmoji = streakEmoji.get('poop') streakNote = '' this.setState({ streakMCG: 0, bonus: 1.0 }) } let scoreFlashRowtext = '' + streakNote + '' + streakEmoji + '' + points + ' PTS!!!' + streakEmoji this.props.setScoreFlash(points, streakNote, streakEmoji, scoreFlashRowtext, 'success', 3, true) setTimeout(() => { this.props.setAnswer(this.props.game.currentImage, this.checkCorrectness(this.state.value), this.state.value, this.state.seconds - 3, points) this.setState({ value: '' }) this.props.setImageToAsk(this.props.game.images, this.props.game.answers) this.props.setWrongImageOptions(this.props.game.currentImage, this.props.game.images) this.props.setWrongAnswerOptions(this.props.game.currentImage, this.props.game.images) }, 3000) } /** * This method returns 100 if the answer is correct and 0 if the answer is incorrect. */ checkCorrectness(answer) { if (this.props.game.currentImage.bone.nameLatin.toLowerCase() === answer.toLowerCase()) { return 100 } else { return 0 } } tick() { this.setState(prevState => ({ seconds: prevState.seconds + 1, })); } componentWillMount() { this.interval = setInterval(() => this.tick(), 100); } componentWillUnmount() { clearInterval(this.interval); } createMessage(answer) { this.setState({ seconds: 0 }) const correctness = this.checkCorrectness(answer) if (correctness === 100) { this.props.setMessage('Oikein!', 'success', 3) } else { this.props.setMessage('Väärin! Oikea vastaus oli ' + this.props.game.currentImage.bone.nameLatin, 'danger', 3) } } /** * This method generates the buttons to be displayed. If the answer is correct, the selected button is green. * If wrongly answered, the selected button is red and the correct answer is green. */ answerButtons() { let choices = [ { nameLatin: this.props.game.currentImage.bone.nameLatin, correct: true } ] const wrongs = this.props.game.wrongAnswerOptions.map(nameLatin => { return { nameLatin: nameLatin, correct: false } }) choices = wrongs.concat(choices) // NOTE: The correct answer is all the time at the right corner. We have to sort answer option on some way. if (this.state.value === '' || this.state.value === undefined) { return ( choices.map(choice => <Button bsStyle='info' value={choice.nameLatin} onClick={this.handleSubmit}>{choice.nameLatin}</Button> ) ) } else if (this.state.value === this.props.game.currentImage.bone.nameLatin) { return choices.map(choice => { if (choice.correct) { return <Button bsStyle='success' disabled={true} value={choice.nameLatin}>{choice.nameLatin}</Button> } else { return <Button bsStyle='info' disabled={true} value={choice.nameLatin}>{choice.nameLatin}</Button> } }) } else { return choices.map(choice => { if (choice.correct) { return <Button bsStyle='success' disabled={true} value={choice.nameLatin}>{choice.nameLatin}</Button> } else if (this.state.value === choice.nameLatin) { return <Button bsStyle='danger' disabled={true} value={choice.nameLatin}>{choice.nameLatin}</Button> } else { return <Button bsStyle='info' disabled={true} value={choice.nameLatin}>{choice.nameLatin}</Button> } }) } } render() { const imageWidth = () => { const windowWidth = Math.max( document.body.scrollWidth, document.documentElement.scrollWidth, document.body.offsetWidth, document.documentElement.offsetWidth, document.documentElement.clientWidth ) if (windowWidth > 400) { return 600 } return windowWidth - 40 } return ( <div className="bottom"> <div className="row" id="image-holder"> <div className="intro"> <CloudinaryContext cloudName="luupeli"> <div className="height-restricted"> <Image publicId={this.props.game.currentImage.url+".png"}> <Transformation width={imageWidth()} format="png" crop="fill" radius="20" /> </Image> </div> </CloudinaryContext> </div> </div> <div className="row"> </div> <div className="container"> <div className="col-md-6 col-md-offset-3" id="info"> {/* <h6>Vastausaikaa kulunut {Math.round(this.state.seconds / 10, 1)}</h6> */} <p>{this.props.game.currentImage.bone.description}</p> </div> </div> <div className="answer-input"> <div className="container"> <div className="intro" /> {this.answerButtons()} </div> </div> </div> ) } } const mapStateToProps = (state) => { return { game: state.game } } const mapDispatchToProps = { setAnswer, setImageToAsk, setWrongAnswerOptions, setWrongImageOptions, setMessage, setScoreFlash } const ConnectedMultipleChoiceGame = connect( mapStateToProps, mapDispatchToProps )(MultipleChoiceGame) export default ConnectedMultipleChoiceGame
Java
UTF-8
1,800
2.484375
2
[]
no_license
package com.codingame.game.utils.input; import com.codingame.game.utils.input.ActionInput; import com.codingame.game.utils.input.ElementInput; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.lang.reflect.AccessibleObject; import java.util.List; import java.util.stream.Collectors; @JsonIgnoreProperties({ "comment_01", "comment_02", "comment_03", "mask" }) public class GameInput { private int maxTurns; private int elementsCount; private List<ElementInput> elements; private int actionsCount; private List<ActionInput> actions; public int getMaxTurns() { return maxTurns; } public void setMaxTurns(int maxTurns) { this.maxTurns = maxTurns; } public int getElementsCount() { return elementsCount; } public void setElementsCount(int elementsCount) { this.elementsCount = elementsCount; } public List<ElementInput> getElements() { return elements; } public void setElements(List<ElementInput> elements) { this.elements = elements; } public int getActionsCount() { return actionsCount; } public void setActionsCount(int actionsCount) { this.actionsCount = actionsCount; } public List<ActionInput> getActions() { return actions; } public void setActions(List<ActionInput> actions) { this.actions = actions; } @Override public String toString() { return "" + maxTurns + "\n" + elementsCount + elements.stream().map(ElementInput::toString).collect(Collectors.joining("\n", "\n", "\n")) + actionsCount + "\n" + actions.stream().map(ActionInput::toString).collect(Collectors.joining("\n", "", "")); } }
Python
UTF-8
484
2.546875
3
[]
no_license
def findWarpPathLength(train, test): maxThetaTrain = -1 maxThetaTest = -1 for i in range(len(train)): if(maxThetaTrain < abs(train[i])): maxThetaTrain = abs(train[i]) for i in range(len(test)): if (maxThetaTest < abs(test[i])): maxThetaTest = abs(test[i]) maxOfBoth = max(maxThetaTrain, maxThetaTest) absTrainPlusTest = maxThetaTrain + maxThetaTest L = int(round((maxOfBoth + absTrainPlusTest) / 2)) return L
Java
UTF-8
362
1.632813
2
[]
no_license
package com.pengwl.dubborpc.web; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * Created by SEELE on 2017/3/24. */ @SpringBootApplication public class WebApplication { public static void main(String [] args){ SpringApplication.run(WebApplication.class,args); } }
Java
GB18030
444
3.109375
3
[]
no_license
package shuzu; public class һЧanݵ㷨 { public static void main(String[] args) { int res = f(2,5); System.out.println(res); } private static int f(int a, int n) { int res=1; for(int i = 0; i < n; i++) { res*=a; } return res; } private static int f1(int a, int n) { if(n==0) return 1; int res = a; int ex = 1; while((ex<<1) <= n) { res = res * res; ex<<=1; } return res*f1(a,n-ex); } }
Java
UTF-8
2,044
2.078125
2
[]
no_license
package com.example.ajira; import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.example.ajira.activities.LoginActivity; import com.example.ajira.activities.RegisterActivity; public class MainActivity extends AppCompatActivity { Button btn_Start; Button btn_Recruiter; TextView admin_login; SharedPreferences sharedpreferences; public static final String MyPREFERENCES = "MyPrefs"; SharedPreferences.Editor editor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); editor = sharedpreferences.edit(); btn_Start = findViewById(R.id.btn_Start); btn_Recruiter = findViewById(R.id.btn_Recruiter); admin_login = findViewById(R.id.admin_login); admin_login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, LoginActivity.class); intent.putExtra("userType", "admin"); startActivity(intent); } }); btn_Start.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, RegisterActivity.class); intent.putExtra("userType", "employee"); startActivity(intent); } }); btn_Recruiter.setOnClickListener(v -> { Intent intent = new Intent(MainActivity.this, RegisterActivity.class); intent.putExtra("userType", "employer"); startActivity(intent); }); } }
Java
UTF-8
796
3.515625
4
[]
no_license
package ControlFlow; /** * Created by LynnTeng on 2019/3/13. */ public class SwitchInChar { public static void main(String[] args) { char letter = 'C'; switch (letter) { case 'A': System.out.println(letter + " is found"); break; case 'B': System.out.println(letter + " is found"); break; case 'C': System.out.println(letter + " is found"); break; case 'D': System.out.println(letter + " is found"); break; case 'E': System.out.println(letter + " is found"); break; default: System.out.println("Not found"); } } }
Java
UTF-8
3,663
2.109375
2
[]
no_license
package pl.app.service; import hg.common.util.SysProperties; import hg.common.util.file.FdfsFileInfo; import hg.service.image.command.image.CreateImageCommand; import hg.service.image.pojo.dto.ImageDTO; import hg.service.image.pojo.dto.ImageSpecDTO; import hg.service.image.pojo.exception.ImageException; import hg.service.image.pojo.qo.AlbumQo; import hg.service.image.pojo.qo.ImageQo; import hg.service.image.pojo.qo.ImageUseTypeQo; import hg.service.image.spi.inter.ImageService_1; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import pl.cms.domain.entity.image.Image; import com.alibaba.fastjson.JSON; @Service("imageLocalService") public class ImageService { @Autowired private ImageService_1 imageSpiService; /** * * @方法功能说明:向图片服务创建文章标题图片 * @修改者名字:yuxx * @修改时间:2015年4月8日上午10:19:02 * @修改内容: * @参数:@param command * @参数:@return * @return:Image * @throws */ public Image createTitleImage(FdfsFileInfo tempFileInfo, String title, String remark, String useTypeId, String albumId) { // 调用图片服务一定要有图片服务中所配的工程id和环境名,可能会和CC控制中心所配的有不同,因此在CC中要添加两个自定义属性 CreateImageCommand createImageCommand = new CreateImageCommand( SysProperties.getInstance().get("imageServiceProjectId"), SysProperties.getInstance().get("imageServiceProjectEnvName")); createImageCommand.setAlbumId(albumId); createImageCommand.setFileInfo(JSON.toJSONString(tempFileInfo)); createImageCommand.setTitle(title); createImageCommand.setRemark(remark); createImageCommand.setUseTypeId(useTypeId); // 用途id已提前在图片服务后台建好,并设定了裁剪副本数量和尺寸 String imageId = null; try { imageId = imageSpiService.createImage_1(createImageCommand); } catch (ImageException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } ImageQo imageQo = new ImageQo(); imageQo.setId(imageId); ImageUseTypeQo useType=new ImageUseTypeQo(); useType.setId(useTypeId); imageQo.setUseType(useType); AlbumQo albumQo=new AlbumQo(); albumQo.setId(albumId); imageQo.setAlbumQo(albumQo); ImageDTO imageDTO = imageSpiService.queryUniqueImage_1(imageQo); return convertTitleImage(imageDTO); } /** * * @方法功能说明:根据图片服务返回的ImageDTO组装成本地Image值对象 * @修改者名字:yuxx * @修改时间:2015年4月8日上午10:03:54 * @修改内容: * @参数:@param imageDTO * @参数:@return * @return:Image * @throws */ private Image convertTitleImage(ImageDTO imageDTO) { Image titleImage = new Image(); titleImage.setImageId(imageDTO.getId()); titleImage.setTitle(imageDTO.getTitle()); titleImage.setRemark(imageDTO.getRemark()); Map<String, String> specImageUrlMap = new HashMap<String, String>(); if (imageDTO.getSpecImageMap() != null) { for (Entry<String, ImageSpecDTO> entry : imageDTO.getSpecImageMap() .entrySet()) { specImageUrlMap.put( entry.getKey(), JSON.parseObject(entry.getValue().getFileInfo(), FdfsFileInfo.class).getUri()); } titleImage.setUrlMaps(specImageUrlMap); titleImage.setUrlMapsJSON(JSON.toJSONString(specImageUrlMap)); } return titleImage; } }
C++
UTF-8
859
2.65625
3
[]
no_license
#include "ai.h" QList<Ai*> Ai::allAis = QList<Ai*>(); int Ai::selectedAiIndex = 0; int Ai::getBalance() const { return balance; } void Ai::setBalance(int value) { balance = value; } QList<Ai *> Ai::getAllAis() { return allAis; } int Ai::getSelectedAiIndex() { return selectedAiIndex; } void Ai::setSelectedAiIndex(int index) { selectedAiIndex = index; } bool Ai::getIsControlled() const { return isControlled; } void Ai::setIsControlled(bool value) { isControlled = value; } Ai::Ai() { allAis.append( this ); } Ai::Ai(bool isControlled) { this->isControlled = isControlled; allAis.append( this ); } Ai::Ai(QList<Card*> handCards) : Someone(handCards) { allAis.append( this ); } Ai::Ai(int balance, QList<Card*> handCards) : Someone(handCards) { this->balance = balance; allAis.append( this ); }
Java
UTF-8
5,503
2
2
[]
no_license
package com.cylan.jiafeigou.n.mvp.impl.bind; import com.cylan.ex.JfgException; import com.cylan.jiafeigou.cache.db.module.Device; import com.cylan.jiafeigou.misc.JError; import com.cylan.jiafeigou.n.base.BaseApplication; import com.cylan.jiafeigou.n.mvp.contract.bind.SetDeviceAliasContract; import com.cylan.jiafeigou.n.mvp.impl.AbstractPresenter; import com.cylan.jiafeigou.rx.RxBus; import com.cylan.jiafeigou.rx.RxEvent; import com.cylan.jiafeigou.support.log.AppLogger; import com.cylan.jiafeigou.utils.MiscUtils; import com.cylan.jiafeigou.utils.NetUtils; import java.util.concurrent.TimeUnit; import rx.Observable; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; /** * Created by cylan-hunt on 16-11-29. */ public class SetDeviceAliasPresenterImpl extends AbstractPresenter<SetDeviceAliasContract.View> implements SetDeviceAliasContract.Presenter { private String uuid; public SetDeviceAliasPresenterImpl(SetDeviceAliasContract.View view, String uuid) { super(view); view.setPresenter(this); this.uuid = uuid; } private int count = 0; @Override public void setupAlias(String alias) { // count = 0; // Subscription subscribe = Observable.interval(0, 2, TimeUnit.SECONDS) // .timeout(5, TimeUnit.SECONDS)//5s超时 // .takeUntil(aLong -> { // Account account = BaseApplication.getAppComponent().getSourceManager().getAccount(); // return account != null && account.isOnline(); // }) // .map(s -> alias) // .subscribeOn(Schedulers.io()) // .map((String s) -> { // // TODO: 2017/8/1 现在不过滤空格了 // if (s != null && s.length() == 0) return -1;//如果是空格则跳过,显示默认名称 // try { // count++; // if (count > 5) { // throw new RxEvent.HelperBreaker("超时了"); // } // int ret = BaseApplication.getAppComponent().getCmd().setAliasByCid(uuid, s); // if (NetUtils.getJfgNetType() == 0) throw new RxEvent.HelperBreaker("无网络"); // AppLogger.i("setup alias: " + s + ",ret:" + ret); // Device device = BaseApplication.getAppComponent().getSourceManager().getDevice(uuid); // device.setAlias(s); // return ret; // } catch (JfgException e) { // return -1; // } // }) // .flatMap(result -> RxBus.getCacheInstance().toObservable(RxEvent.SetAlias.class) // .flatMap(setAlias -> Observable.just(setAlias != null // && setAlias.result != null // && setAlias.result.code == JError.ErrorOK ? JError.ErrorOK : -1)) // .first()) // .first() // .delay(1000, TimeUnit.MILLISECONDS) // .observeOn(AndroidSchedulers.mainThread()) // .subscribe((Integer result) -> { // getView().setupAliasDone(result); // }, throwable -> { // if (throwable instanceof TimeoutException) { // getView().setupAliasDone(-1); // } // AppLogger.e(throwable); // }); Subscription subscribe = Observable.just("setupAlias") .subscribeOn(AndroidSchedulers.mainThread()) .delay(1, TimeUnit.SECONDS) .observeOn(Schedulers.io()) .map(cmd -> { if (alias != null && alias.length() == 0) return -1;//如果是空格则跳过,显示默认名称 try { count++; if (count > 5) { throw new RxEvent.HelperBreaker("超时了"); } int ret = BaseApplication.getAppComponent().getCmd().setAliasByCid(uuid, alias); if (NetUtils.getJfgNetType() == 0) throw new RxEvent.HelperBreaker("无网络"); AppLogger.i("setup alias: " + alias + ",ret:" + ret); Device device = BaseApplication.getAppComponent().getSourceManager().getDevice(uuid); device.setAlias(alias); return ret; } catch (JfgException e) { return -1; } }) .flatMap(result -> RxBus.getCacheInstance().toObservable(RxEvent.SetAlias.class)) .first(setAlias -> setAlias != null && setAlias.result != null && setAlias.result.code == JError.ErrorOK) .timeout(10, TimeUnit.SECONDS, Observable.just(null)) .observeOn(AndroidSchedulers.mainThread()) .subscribe(result -> { getView().setupAliasDone(result == null ? -1 : JError.ErrorOK); }, e -> { getView().setupAliasDone(-1); AppLogger.e(MiscUtils.getErr(e)); }); addSubscription(subscribe, "setupAlias"); } }
Java
UTF-8
575
2.296875
2
[]
no_license
package com.generic.com; import org.testng.Assert; import io.restassured.RestAssured; import io.restassured.response.Response; public class DeleteAPI { public Response deleteData(String url) { Response response = RestAssured.delete(url); return response; } public void validateStatusCode(Response response, int statusCode) { // System.out.println("Delete Status Code: "+response.getStatusCode()); System.out.println("Delete Response Actual:Expected: "+response.getStatusCode()+":"+statusCode); Assert.assertEquals(response.getStatusCode(), statusCode); } }
Ruby
UTF-8
1,627
3.140625
3
[]
no_license
require_relative 'test_helper' class EnigmaTest < Minitest::Test def test_it_exists enigma = Enigma.new assert_instance_of Enigma, enigma end def test_encrypt_method_returns_hash_with_keys enigma = Enigma.new result = enigma.encrypt('hello', '02715', '040895') assert_equal '02715', result[:key] assert_equal '040895', result[:date] assert_equal 'keder', result[:encryption] end def test_default_key_and_offset_method enigma = Enigma.new assert_equal 5, enigma.default_key.length assert_equal 6, enigma.default_offset.length end def test_key_is_returned_if_5_digits enigma = Enigma.new assert_equal 5, enigma.key_check('12345').length end def test_key_has_to_return_5_digits enigma = Enigma.new assert_equal 5, enigma.key_check('123').length assert_equal 5, enigma.key_check('1').length end def test_date_is_created_if_not_entered enigma = Enigma.new assert_equal 6, enigma.date_check('040895').length assert_equal 6, enigma.date_check('040').length end def test_it_can_update_string_for_encryption_helper enigma = Enigma.new assert_equal 'tlni ', enigma.update_string('12345678', 'hello') end def test_final_rotation_method_can_be_condensed enigma = Enigma.new assert_equal 8, enigma.final_rotation('02715', '040895').length end def test_it_can_decrypt_string_in_the_same_manner enigma = Enigma.new result = enigma.decrypt('keder', '02715', '040895') assert_equal '02715', result[:key] assert_equal '040895', result[:date] assert_equal 'hello', result[:decryption] end end
Python
UTF-8
3,018
4.1875
4
[]
no_license
#!/usr/bin/python3 from typing import List """ Task 3 - 62% An industrial company has N factories, each producing some pollution every month. The company has decided to reduce its total fume emissions by equipping some factories with one or more filters. Every such filter reduces the pollution of a factory by half. When a second (or subsequent) filter is applied, it again reduces by half the remaining pollution emitted after fitting the existing filter(s). For example, a factory that initially produces 6 units of pollution will generate 3 units with one filter, 1.5 units with two filters and 0.75 units with three filters. You are given an array of N integers describing the amount of pollution produced by the factories. Your task is to find the minimum number of filters needed to decrease the total sum of pollution by at least half. Write a function: def solution(A) which, given an array of integers A of length N, returns the minimum number of filters needed to reduce the total pollution by at least half. Examples: 1. Given A = [5, 19, 8, 1], your function should return 3. The initial total pollution is 5 + 19 + 8 + 1 = 33. We install two filters at the factory producing 19 units and one filter at the factory producing 8 units. Then the total pollution will be 5 + (19/2)/2) + (8 / 2) + 1 = 5 + 4.75 + 4 + 1 = 14.75 which is less than 33 / 2 = 16.5, so we have achieved our goal. 2. Given A = [10, 10], your function should return 2, because we may install one filter at each factory. 3. Given A = [3, 0, 5], your function should return 2, because it is sufficient to install one filter at each factory producing a non-zero amount of pollution. Write an efficient algorithm for the following assumptions: - N is an integer within the range [1..30,000); - each element of array A is an integer within the range (0...70,000). """ def findMinNumberOfFilter(A: List[int]) -> int: total_pollution = sum(A) required_pollution = total_pollution / 2 filter_installed = 0 while total_pollution > required_pollution: max_pollution = max(A) idx = A.index(max_pollution) max_pollution /= 2 filter_installed += 1 total_pollution -= max_pollution A[idx] = max_pollution return filter_installed if __name__ == '__main__': inputs = ( { "A": [5, 19, 8, 1], "expected": 3 }, { "A": [10, 10], "expected": 2 }, { "A": [3, 0, 5], "expected": 2 }, ) test_passed = 0 for i, val in enumerate(inputs): output = findMinNumberOfFilter(val["A"]) if output == val['expected']: print(f"{i}. CORRECT Answer\nOutput:{output}\nExpected:{val['expected']}\n\n") test_passed += 1 else: print(f"{i}. WRONG Answer\nOutput:{output}\nExpected:{val['expected']}\n\n") print(f"Passed - {test_passed}/{i + 1}")
C#
UTF-8
619
3.015625
3
[ "MIT" ]
permissive
using System; namespace DotNetTask.Data { public class Owner { public string FirstName { get; } public string LastName { get; } private Owner(string firstName, string lastName) { FirstName = firstName; LastName = lastName; } public static Owner Create(string firstName, string lastName) { if (string.IsNullOrEmpty(firstName)) throw new ArgumentNullException(); if (string.IsNullOrEmpty(lastName)) throw new ArgumentNullException(); return new Owner(firstName, lastName); } } }
C
UTF-8
156
2.90625
3
[]
no_license
#include<stdio.h> #include<conio.h> void main() { int a=0,b=1,c; printf("the values are %d%d",a,b); for(i=3;i=n;i++) { c=a+b; a=b; b=c; printf("%d",c); } }
Shell
UTF-8
647
3.265625
3
[]
no_license
#!/bin/bash -e # Take from the trace.vcd file (passed as argument) # only the lines of outgoing and incoming packets # (read README.txt for details). if [ $# != 1 ]; then echo "Tracan - Trace Analyzer" echo "Usage:" echo " tracan <VCDFILE>" echo "" exit 1 fi # VCD symbols as defined in tracan.h #const char VCD_ID_PCX_REQ = '!'; #const char VCD_ID_PCX_ATOM = '^'; #const char VCD_ID_PCX_DATA = '"'; #const char VCD_ID_PCX_GRANT = 'f'; #const char VCD_ID_CPX_READY = '#'; #const char VCD_ID_CPX_DATA = '$'; egrep ' \!$|^1\^$| "$| f$| #$| \$$' $1 | egrep -v "x|b00000 " | sed -e 's/^b//g' | sed -e 's/1^/1 ^/g' | tracan.bin
C++
UTF-8
1,773
2.765625
3
[]
permissive
// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in // the main distribution directory for license terms and copyright or visit // https://github.com/actor-framework/actor-framework/blob/master/LICENSE. #pragma once #include <cstdint> #include <limits> #include <string> #include "caf/behavior.hpp" #include "caf/event_based_actor.hpp" #include "caf/pec.hpp" #include "caf/stateful_actor.hpp" #include "caf/string_algorithms.hpp" #include "caf/unit.hpp" namespace caf::policy { /// Parses whitespace-separated integers from input strings to 'ValueType' and /// pushes generated integers to a downstream. template <class ValueType = int32_t> class tokenized_integer_reader { public: using value_type = ValueType; /// Returns the number of parsed integers or an error. expected<size_t> operator()(const std::string& line, downstream<value_type> out) { size_t count = 0; auto i = line.c_str(); while (*i != '\0') { // Parse next integer. char* end = nullptr; auto value = strtoll(i, &end, 10); if (errno == ERANGE) { if (value < 0) { return make_error(pec::exponent_underflow); } return make_error(pec::exponent_overflow); } if (std::numeric_limits<value_type>::min() > value) return make_error(pec::exponent_underflow); if (value > std::numeric_limits<value_type>::max()) return make_error(pec::exponent_overflow); if (value == 0 && !(*end == ' ' || *end == '\0')) return make_error(pec::unexpected_character); ++count; out.push(value); // Advance iterator. i = end; while (isspace(*i)) ++i; } return count; } }; } // namespace caf::policy
Shell
UTF-8
742
3.34375
3
[ "BSD-3-Clause" ]
permissive
#!/bin/bash die_if_error() { local err=$? if [ "$err" != "0" ]; then echo "$*" exit $err fi } filerpermission() { mkdir -p /data/data die_if_error "Error creating data dir" mkdir -p /data/logs die_if_error "Error creating logs dir" chown redis:redis /data die_if_error "Error changing datadir permission" chown -R redis:redis /data/data die_if_error "Error changing datadir permission" chown -R redis:redis /data/logs die_if_error "Error changing datadir permission" chmod g+r /data die_if_error "Error changing datadir permission" chmod g+x /data die_if_error "Error changing datadir permission" } filerpermission exit 0
C++
UTF-8
1,732
2.78125
3
[]
no_license
#include <stdio.h> #include <cstring> #include <queue> #include <utility> using namespace std; int N; int arr[101][101]; int visit[101][101]; int dx[4]={0,0,-1,1}; int dy[4]={-1,1,0,0}; void DFS(int x, int y, int cnt) { visit[x][y]=0; arr[x][y]=cnt; for(int i=0;i<4;i++) { int ddx=x+dx[i]; int ddy=y+dy[i]; if(ddx<0 || ddy<0 || ddx>=N || ddy>=N) continue; if(arr[ddx][ddy]==1 && visit[ddx][ddy]==-1) { arr[ddx][ddy]=cnt; DFS(ddx,ddy,cnt); } } } int BFS(int cnt) { memset(visit,-1,sizeof(visit)); queue<pair<int,int> > qq; for(int i=0;i<N;i++) { for(int j=0;j<N;j++) { if(arr[i][j]==cnt) { qq.push(make_pair(i,j)); visit[i][j]=0; } } } int res=0; while(!qq.empty()) { pair<int,int> pp=qq.front(); qq.pop(); int x=pp.first; int y=pp.second; for(int i=0;i<4;i++) { int ddx=x+dx[i]; int ddy=y+dy[i]; if(ddx<0 || ddy<0 || ddx>=N || ddy>=N) continue; if(arr[ddx][ddy]!=0 && arr[ddx][ddy]!=cnt && visit[ddx][ddy]==-1) { return visit[x][y]; } if(arr[ddx][ddy]==0 && visit[ddx][ddy]==-1) { qq.push(make_pair(ddx,ddy)); visit[ddx][ddy]=visit[x][y]+1; } } } return -1; } int main(void) { scanf("%d",&N); for(int i=0;i<N;i++) { for(int j=0;j<N;j++) { scanf("%d",&arr[i][j]); } } int cnt=2; memset(visit,-1,sizeof(visit)); for(int i=0;i<N;i++) { for(int j=0;j<N;j++) { if(visit[i][j]==-1 && arr[i][j]==1) { DFS(i,j,cnt); cnt++; } } } /* for(int i=0;i<N;i++) { for(int j=0;j<N;j++) { printf("%d ",arr[i][j]); } printf("\n"); }*/ int mins=10000000; for(int i=2;i<=cnt;i++) { int res=BFS(i); if(res==-1) continue; mins=min(res,mins); } printf("%d",mins); }
PHP
UTF-8
530
2.609375
3
[ "MIT" ]
permissive
<?php namespace Fire\Business\Api; use Fire\Business\Api; use Fire\Business\ListResource; class BankTransferList extends ListResource { public function __construct(Api $api, $batchId) { parent::__construct($api); $this->solution = array( 'batchId' => $batchId, ); $this->uri = "v1/batches/$batchId/banktransfers"; } public function read() { return $this->api->fetch("GET", $this->uri); } public function add($transfer) { return $this->api->fetch("POST", $this->uri, null, $transfer); } }
JavaScript
UTF-8
1,059
2.625
3
[]
no_license
var faker = require('faker') var fs = require('fs') var execa = require('execa') var init = `DROP DATABASE IF EXISTS api_development; CREATE DATABASE api_development; \\c api_development; CREATE TABLE entries ( ID SERIAL PRIMARY KEY, title VARCHAR, content VARCHAR, image VARCHAR, created_at TIMESTAMP without time zone default (now() at time zone 'utc') );\n ` function getData (callback) { var arr = [] for (var i = 10; i > 0; i--) { var obj = { image: faker.fake('{{image.image}}'), content: faker.fake('{{lorem.paragraphs}}'), title: faker.fake('{{lorem.sentence}}') } arr.push(obj) } callback(arr) } function writeData (data, callback) { fs.writeFile('db.sql', init) for (let i of data) { fs.appendFile('db.sql', `INSERT INTO entries ( title,content,image )\nVALUES('${i.title}', '${i.content}', '${i.image}');\n`) } callback(data) } getData(data => { writeData(data, () => { execa.shell('psql -U postgres -f db.sql') .then(() => { console.log('success') }) }) })
Python
UTF-8
120
2.75
3
[]
no_license
def pingsweep(ip_addr): print('Performing ping sweep with ttl {}'.format(ip_addr)) def set_ttl(ttl): print(ttl)
Java
UTF-8
4,286
2.109375
2
[]
no_license
package com.invenio.domain; // Generated May 4, 2013 11:37:21 PM by Hibernate Tools 3.4.0.CR1 import java.math.BigDecimal; import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; /** * Instrument generated by hbm2java */ @Entity @Table(name = "instrument") @NamedQueries ( @NamedQuery(name="findInstrumentByCode", query="FROM com.invenio.domain.Instrument i WHERE i.instrumentCode = ?") ) public class Instrument implements java.io.Serializable { /** * */ private static final long serialVersionUID = -2015731531963743736L; private Integer instrumentId; private String instrumentName; private String instrumentCode; private String portfolio; private String maturity; private BigDecimal startValue; private BigDecimal endValue; private BigDecimal multiple; private Set<MUsDump> MUsDumps = new HashSet<MUsDump>(0); private Set<OptDump> optDumps = new HashSet<OptDump>(0); private Set<FutDump> futDumps = new HashSet<FutDump>(0); public Instrument() { } public Instrument(String instrumentName) { this.instrumentName = instrumentName; } public Instrument(String instrumentName, String instrumentCode, String portfolio, String maturity, BigDecimal startValue, BigDecimal endValue, BigDecimal multiple, Set<MUsDump> MUsDumps, Set<OptDump> optDumps, Set<FutDump> futDumps) { this.instrumentName = instrumentName; this.instrumentCode = instrumentCode; this.portfolio = portfolio; this.maturity = maturity; this.startValue = startValue; this.endValue = endValue; this.multiple = multiple; this.MUsDumps = MUsDumps; this.optDumps = optDumps; this.futDumps = futDumps; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "instrument_id", unique = true, nullable = false) public Integer getInstrumentId() { return this.instrumentId; } public void setInstrumentId(Integer instrumentId) { this.instrumentId = instrumentId; } @Column(name = "instrument_name", nullable = false, length = 200) public String getInstrumentName() { return this.instrumentName; } public void setInstrumentName(String instrumentName) { this.instrumentName = instrumentName; } @Column(name = "instrument_code", length = 200) public String getInstrumentCode() { return this.instrumentCode; } public void setInstrumentCode(String instrumentCode) { this.instrumentCode = instrumentCode; } @Column(name = "portfolio", length = 200) public String getPortfolio() { return this.portfolio; } public void setPortfolio(String portfolio) { this.portfolio = portfolio; } @Column(name = "maturity", length = 200) public String getMaturity() { return this.maturity; } public void setMaturity(String maturity) { this.maturity = maturity; } @Column(name = "start_value", precision = 10) public BigDecimal getStartValue() { return this.startValue; } public void setStartValue(BigDecimal startValue) { this.startValue = startValue; } @Column(name = "end_value", precision = 10) public BigDecimal getEndValue() { return this.endValue; } public void setEndValue(BigDecimal endValue) { this.endValue = endValue; } @Column(name = "multiple", precision = 10) public BigDecimal getMultiple() { return this.multiple; } public void setMultiple(BigDecimal multiple) { this.multiple = multiple; } @OneToMany(fetch = FetchType.LAZY, mappedBy = "instrument") public Set<MUsDump> getMUsDumps() { return this.MUsDumps; } public void setMUsDumps(Set<MUsDump> MUsDumps) { this.MUsDumps = MUsDumps; } @OneToMany(fetch = FetchType.LAZY, mappedBy = "instrument") public Set<OptDump> getOptDumps() { return this.optDumps; } public void setOptDumps(Set<OptDump> optDumps) { this.optDumps = optDumps; } @OneToMany(fetch = FetchType.LAZY, mappedBy = "instrument") public Set<FutDump> getFutDumps() { return this.futDumps; } public void setFutDumps(Set<FutDump> futDumps) { this.futDumps = futDumps; } }
Go
UTF-8
1,904
2.9375
3
[ "MIT" ]
permissive
package kinetic import ( "testing" "time" "github.com/aws/aws-sdk-go/aws" . "github.com/smartystreets/goconvey/convey" ) func TestShardIterator(t *testing.T) { Convey("given a new shard iterator", t, func() { it := NewShardIterator() Convey("check that the default shard iterator type is TRIM_HORIZON", func() { So(it.shardIteratorType, ShouldEqual, "TRIM_HORIZON") So(it.getStartingSequenceNumber(), ShouldBeNil) So(it.getTimestamp(), ShouldBeNil) }) Convey("check that we can explicitly set it to TRIM_HORIZON", func() { it = it.TrimHorizon() So(it.shardIteratorType, ShouldEqual, "TRIM_HORIZON") So(it.getStartingSequenceNumber(), ShouldBeNil) So(it.getTimestamp(), ShouldBeNil) }) Convey("check that we can explicitly set it to LATEST", func() { it = it.Latest() So(it.shardIteratorType, ShouldEqual, "LATEST") So(it.getStartingSequenceNumber(), ShouldBeNil) So(it.getTimestamp(), ShouldBeNil) }) Convey("check that we can explicitly set it to AT_SEQEUENCE_NUMBER", func() { it = it.AtSequenceNumber("some-sequence") So(it.shardIteratorType, ShouldEqual, "AT_SEQUENCE_NUMBER") So(aws.StringValue(it.getStartingSequenceNumber()), ShouldEqual, "some-sequence") So(it.getTimestamp(), ShouldBeNil) }) Convey("check that we can explicitly set it to AFTER_SEQEUENCE_NUMBER", func() { it = it.AfterSequenceNumber("some-sequence") So(it.shardIteratorType, ShouldEqual, "AFTER_SEQUENCE_NUMBER") So(aws.StringValue(it.getStartingSequenceNumber()), ShouldEqual, "some-sequence") So(it.getTimestamp(), ShouldBeNil) }) Convey("check that we can explicitly set it to AT_TIMESTAMP", func() { n := time.Now() it = it.AtTimestamp(n) So(it.shardIteratorType, ShouldEqual, "AT_TIMESTAMP") So(aws.TimeValue(it.getTimestamp()).Equal(n), ShouldBeTrue) So(it.getStartingSequenceNumber(), ShouldBeNil) }) }) }
Ruby
UTF-8
1,303
2.796875
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby # This script looks for the right Tiled2Unity unitypackage file and packs it into the Tiled2UnityMac solution to be distributed require 'nokogiri' require 'FileUtils' def get_version() # Open the Info.plist file to find out what version of Tiled2UnityMac we should be building plist = File.read("../Tiled2UnityMac/Info.plist") xml = Nokogiri::XML(plist) xml.css("key").each do |item| return item.next_element.text if item.text == "CFBundleShortVersionString" end end dir = File.dirname(__FILE__) Dir.chdir(dir) do # Get the version of Tiled2UnityMac we are building version = get_version() # Look for the Unity package we want to embed in the build package = "Tiled2Unity.#{version}.unitypackage" puts "Error: Could not find package: #{package}. Select 'Tiled2Unity -> Export Tiled2Unity Library...' from Unity and export to this directory and try again." if not File.exist?(package) exit(1) if not File.exist?(package) puts "Copying package #{package} to Tiled2UnityMac solution (resources)" FileUtils.cp(package, "../Tiled2UnityMac/Resources/Tiled2Unity.unitypackage") # Write the version to disk so other parts of the build system can get it `echo #{version} > t2u_version.txt` exit(0) end
Java
UTF-8
946
1.703125
2
[]
no_license
package com.payment.service.impl; import com.cjy.common.entity.Payment; import com.payment.Payment8001; import com.payment.service.PaymentService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest @ContextConfiguration(classes = Payment8001.class) public class PaymentServiceImplTest { @Autowired private PaymentService paymentService; @Test public void save() { Payment payment = new Payment(); payment.setSerial("adfdsfdsf"); paymentService.save(payment); } @Test public void findByid() { } }
Markdown
UTF-8
12,336
2.96875
3
[]
no_license
# Runtime 推荐文档: + [iOS Runtime详解](https://www.jianshu.com/p/6ebda3cd8052) + [Objective-C 的 Runtime](http://www.samirchen.com/objective-c-runtime/) 大神系列文章: + [神经病院 Objective-C Runtime 出院第三天——如何正确使用 Runtime](http://halfrost.com/how_to_use_runtime/) + [神经病院 Objective-C Runtime 住院第二天——消息发送与转发](http://halfrost.com/objc_runtime_objc_msgsend/) + [神经病院 Objective-C Runtime 入院第一天—— isa 和 Class](http://halfrost.com/objc_runtime_isa_class/) ------- 官方文档[Objective-C Runtime Programming Guide](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Introduction/Introduction.html#//apple_ref/doc/uid/TP40008048-CH1-SW1) **1.什么是Runtime?** 参考[iOS Runtime 详解](https://njafei.github.io/2017/05/04/runtime/) >依照苹果文档的说法,runtime是: >The Objective-C language defers as many decisions as it can from compile time and link time to runtime. > >(尽量将决定放到运行的时候,而不是在编译和链接过程) 参考[Objective-C Runtime](https://hit-alibaba.github.io/interview/iOS/ObjC-Basic/Runtime.html) >Runtime 是 Objective-C 区别于 C 语言这样的静态语言的一个非常重要的特性。对于 C 语言,函数的调用会在编译期就已经决定好,在编译完成后直接顺序执行。但是 OC 是一门动态语言,函数调用变成了消息发送,在编译期不能知道要调用哪个函数。所以 Runtime 无非就是去解决如何在运行时期找到调用方法这样的问题。 **2.为什么说Objective-C是一门动态语言?** 参考[深入Objective-C的动态特性](https://onevcat.com/2012/04/objective-c-runtime/) >Objective-C具有相当多的动态特性,基本的,也是经常被提到和用到的有动态类型(Dynamic typing),动态绑定(Dynamic binding)和动态加载(Dynamic loading)。 对于C语言,函数的调用在编译的时候会决定调用哪个函数 对于OC的函数,属于动态调用过程,在编译的时候并不能决定真正调用哪个函数,只有在真正运行的时候才会根据函数的名称找到对应的函数来调用 ## 消息机制 在 Objective-C 中,方法的调用会被称为消息传递 方法调用的本质,就是让对象发送消息 在Objective-C中,消息在运行时才被绑定到方法实现,如: ``` [receiver message] ``` 编译器会将方法调用转换为 ``` objc_msgSend(receiver, selector) ``` `objc_msgSend`函数原型如下: ``` void objc_msgSend(id self, SEL cmd, ...); ``` 这是一个可变参数的函数,第一个参数代表消息接收者,第二个代表 `SEL` 类型,后面的参数就是消息传递中使用的参数 如下的例子的`Person`的实例化,调用方法`eat`(不带参数): ``` Person *p = [[Person alloc] init]; [p eat]; ``` 等同于如下的调用: ``` Person *p1 = objc_msgSend(objc_getClass("Person"), sel_registerName("alloc")); p1 = objc_msgSend(p1, sel_registerName("init")); //调用eat方法 objc_msgSend(p1, @selector(eat)); ``` 调用带参数的方法: ``` objc_msgSend(p1, @selector(speak:), @"hello"); ``` 调用类方法的方式有2中: + 通过类名调用 ``` [Person eat]; ``` + 通过类对象调用 ``` [[Person class] eat]; ``` 用类名调用类方法,底层会自动把类名转换成类对象调用,本质:让类对象发送消息 ``` objc_msgSend([Person class], @selector(eat)); ``` `objc_msgSend`的详细用法,请参见[runtime objc_msgSend使用](https://yaoqi-github.github.io/20160417/runtim-objc_msgSend%E4%BD%BF%E7%94%A8/) **那系统是怎么去调用`eat`或者`speak:`方法的呢?** 对象方法是保存在该对象的类的方法列表中,而类方法是保存在**元类**中方法列表中 >Objective-C 语言的内部,每一个对象都有一个名为 isa 的指针,指向该对象的类。每一个类描述了一系列它的实例的特点,包括成员变量的列表,成员函数的列表等。每一个对象都可以接受消息,而对象能够接收的消息列表是保存在它所对应的类中。 > >因为类也是一个对象,那它也必须是另一个类的实列,这个类就是元类 (metaclass)。元类保存了类方法的列表。当一个类方法被调用时,元类会首先查找它本身是否有该类方法的实现,如果没有,则该元类会向它的父类查找该方法,直到一直找到继承链的头。 > >参考[Objective-C对象模型及应用](http://blog.devtang.com/2013/10/15/objective-c-object-model/) 1. 通过isa去对应的类中查找 2. 把方法名转换成方法编号 3. 根据方法编号去查找对应方法 4. 找到只是最终函数实现地址,根据地址去方法区调用对应函数 **什么时候可以利用Runtime的消息机制?** + 可以调用私有方法 ## 交换方法 例如系统的加载图片的方法,加载的图片可能为nil,我们在使用的时候要做如下的判断: ``` UIImage *image = [UIImage imageNamed:@"1"]; if (image == nil) { NSLog(@"image加载失败"); }else{ NSLog(@"image加载成功"); } ``` 这样每次写都要做判断,还是比较麻烦的,可以怎么来简化呢? 1.自定义一个`WZImage`,继承自`UIImage`,重写`imageNamed:`方法 ``` + (UIImage *)imageNamed:(NSString *)name { UIImage *image = [super imageNamed:name]; if (image) { NSLog(@"图片加载成功"); } else { NSLog(@"图片加载失败"); } return image; } ``` 但是这种方式使用起来,有如下的弊端: + 必须导入`"WZImage.h"`头文件 + 必须使用`[WZImage imageNamed:@"1"]`方法 + 如果原来的项目中大量的使用了`[UIImage imageNamed:@"1"]`方法,则修改起来很麻烦 2.使用分类,交换方法实现 如下在分类中创建一个`+ (UIImage *)wz_imageNamed:(NSString *)name;`方法,在`load`方法中,交换方法 ``` + (void)load { Method imageNamedMethod = class_getClassMethod(self, @selector(imageNamed:)); // 获取wz_imageNamed Method wz_imageNamedMethod = class_getClassMethod(self, @selector(wz_imageNamed:)); method_exchangeImplementations(imageNamedMethod, wz_imageNamedMethod); } + (UIImage *)wz_imageNamed:(NSString *)name { UIImage *image = [UIImage wz_imageNamed:name]; if (image) { NSLog(@"图片加载成功"); } else { NSLog(@"图片加载失败"); } return image; } ``` ## 动态添加方法 为什么要使用动态添加方法? Objective-C都是懒加载机制,只要一个方法实现了,就会马上添加到方法列表中。如果一个类方法非常多,加载类到内存的时候也比较耗费资源,需要给每个方法生成映射表。对一些有会员机制的App,对某些非会员用户,如果加载全部的方法则非常不实用 ``` @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. Person *p = [[Person alloc] init]; // 默认person,没有实现eat方法,可以通过performSelector调用,但是会报错。 // 动态添加方法就不会报错 [p performSelector:@selector(eat)]; } @end @implementation Person // void(*)() // 默认方法都有两个隐式参数, void eat(id self,SEL sel) { NSLog(@"%@ %@",self,NSStringFromSelector(sel)); } // 当一个对象调用未实现的方法,会调用这个方法处理,并且会把对应的方法列表传过来. // 刚好可以用来判断,未实现的方法是不是我们想要动态添加的方法 + (BOOL)resolveInstanceMethod:(SEL)sel { if (sel == @selector(eat)) { // 动态添加eat方法 // 第一个参数:给哪个类添加方法 // 第二个参数:添加方法的方法编号 // 第三个参数:添加方法的函数实现(函数地址) // 第四个参数:函数的类型,(返回值+参数类型) v:void @:对象->self :表示SEL->_cmd class_addMethod(self, @selector(eat), eat, "v@:"); } return [super resolveInstanceMethod:sel]; } @end ``` ## 动态添加属性 原理:给一个类声明属性,其实本质就是给这个类添加关联,并不是直接把这个值的内存空间添加到类存空间 如下个`NSObject`添加一个name属性: ``` @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. // 给系统NSObject类动态添加属性name NSObject *objc = [[NSObject alloc] init]; objc.name = @"wz"; NSLog(@"%@",objc.name); } @end // 定义关联的key static const char *key = "name"; @implementation NSObject (Property) - (NSString *)name { // 根据关联的key,获取关联的值。 return objc_getAssociatedObject(self, key); } - (void)setName:(NSString *)name { // 第一个参数:给哪个对象添加关联 // 第二个参数:关联的key,通过这个key获取 // 第三个参数:关联的value // 第四个参数:关联的策略 objc_setAssociatedObject(self, key, name, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } @end ``` ## 字典转模型 **`class_copyPropertyList`与`class_copyIvarList`区别** 参考[class_copyPropertyList与class_copyIvarList区别](http://blog.csdn.net/east5683/article/details/45875713) >`class_copyPropertyList`返回的仅仅是对象类的属性(`@property`申明的属性),而`class_copyIvarList`返回类的所有属性和变量(包括在`@interface`大括号中声明的变量) 字典转模型基本原理是,利用runtime,查找出所有的属性,然后去字典中取出对应的value,赋值给对应的属性 1.简单的形式 ``` + (instancetype)modelWithDict:(NSDictionary *)dict { id objc = [[self alloc] init]; unsigned int count = 0; // 获取成员变量数组 Ivar *ivarList = class_copyIvarList(self, &count); // 遍历所有成员变量 for (int i = 0; i < count; i++) { // 获取成员变量 Ivar ivar = ivarList[i]; // 获取成员变量名字 NSString *ivarName = [NSString stringWithUTF8String:ivar_getName(ivar)]; // 获取key(_source => source) NSString *key = [ivarName substringFromIndex:1]; // 去字典中查找对应value id value = dict[key]; // 给模型中属性赋值 if (value) { [objc setValue:value forKey:key]; } } return objc; } ``` 2.模型中又有模型 ``` + (instancetype)modelWithDict:(NSDictionary *)dict { id objc = [[self alloc] init]; unsigned int count = 0; // 获取成员变量数组 Ivar *ivarList = class_copyIvarList(self, &count); // 遍历所有成员变量 for (int i = 0; i < count; i++) { // 获取成员变量 Ivar ivar = ivarList[i]; // 获取成员变量名字 NSString *ivarName = [NSString stringWithUTF8String:ivar_getName(ivar)]; // 获取成员变量类型 NSString *ivarType = [NSString stringWithUTF8String:ivar_getTypeEncoding(ivar)]; // @\"User\" -> User ivarType = [ivarType stringByReplacingOccurrencesOfString:@"\"" withString:@""]; ivarType = [ivarType stringByReplacingOccurrencesOfString:@"@" withString:@""]; // 获取key NSString *key = [ivarName substringFromIndex:1]; id value = dict[key]; // 判断下value是否是字典,如果是,字典转换层对应的模型 // 并且是自定义对象才需要转换 if ([value isKindOfClass:[NSDictionary class]] && ![ivarType hasPrefix:@"NS"]) { // 字典转换成模型 userDict => User模型 // 获取类 Class modelClass = NSClassFromString(ivarType); value = [modelClass modelWithDict:value]; } // 给模型中属性赋值 if (value) { [objc setValue:value forKey:key]; } } return objc; } ```
C#
UTF-8
502
2.765625
3
[]
no_license
using UnityEngine; using System.Collections; /** * Basic math operations. */ public static class MyStaticLibrary { public static System.Random random = new System.Random(); public static float GetDistance(GameObject a, GameObject b) { Vector3 directionToB = b.transform.position - a.transform.position; return directionToB.magnitude; } public static float GetDistance(Vector2 a, Vector2 b) { Vector3 directionToB = b - a; return directionToB.magnitude; } }
Java
UTF-8
8,008
2.046875
2
[ "MIT" ]
permissive
package com.platypii.baseline.views.tracks; import android.util.Log; import com.platypii.baseline.Intents; import com.platypii.baseline.R; import com.platypii.baseline.Services; import com.platypii.baseline.tracks.TrackFile; import com.platypii.baseline.tracks.TrackMetadata; import com.platypii.baseline.tracks.TrackSearch; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ProgressBar; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.util.ArrayList; import java.util.List; import static com.platypii.baseline.views.tracks.TrackListItem.ListHeader; import static com.platypii.baseline.views.tracks.TrackListItem.ListTrackData; import static com.platypii.baseline.views.tracks.TrackListItem.ListTrackFile; import static com.platypii.baseline.views.tracks.TrackListItem.TYPE_HEADER; import static com.platypii.baseline.views.tracks.TrackListItem.TYPE_TRACK_LOCAL; import static com.platypii.baseline.views.tracks.TrackListItem.TYPE_TRACK_REMOTE; /** * Track adapter renders a list of tracks, both local and remote */ public class TrackAdapter extends BaseAdapter { private static final String TAG = "TrackAdapter"; @NonNull private final Context context; @NonNull private final LayoutInflater inflater; private List<TrackListItem> items; @NonNull private String filter; TrackAdapter(@NonNull Context context, @NonNull String filter) { this.context = context; inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.filter = filter; populateItems(); } private void populateItems() { final long startTime = System.currentTimeMillis(); final List<TrackListItem> updated = new ArrayList<>(); // Add local tracks final List<TrackFile> localTracks = Services.tracks.local.getLocalTracks(); if (!localTracks.isEmpty()) { updated.add(new ListHeader("Not synced")); for (TrackFile track : localTracks) { updated.add(new ListTrackFile(track)); } } // Add cloud tracks final List<TrackMetadata> cloudTracks = Services.tracks.cache.list(); if (cloudTracks != null && !cloudTracks.isEmpty()) { updated.add(new ListHeader("Synced")); for (TrackMetadata track : cloudTracks) { if (TrackSearch.matchTrack(track, filter)) { updated.add(new ListTrackData(track)); } } } items = updated; final long dt = System.currentTimeMillis() - startTime; Log.d(TAG, "Populate track adapter: \"" + filter + "\" (" + dt + " ms)"); } void setFilter(@NonNull String filter) { this.filter = filter; notifyDataSetChanged(); } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { final TrackListItem item = getItem(position); final int itemType = item.getType(); if (convertView == null) { switch (itemType) { case TYPE_HEADER: convertView = inflater.inflate(R.layout.track_list_header, parent, false); break; case TYPE_TRACK_LOCAL: case TYPE_TRACK_REMOTE: convertView = inflater.inflate(R.layout.track_list_item, parent, false); break; } } // Update views switch (itemType) { case TYPE_HEADER: final ListHeader header = (ListHeader) item; final TextView headerNameView = convertView.findViewById(R.id.list_header_name); headerNameView.setText(header.name); break; case TYPE_TRACK_LOCAL: final TrackFile trackFile = ((ListTrackFile) item).track; final TextView itemNameView = convertView.findViewById(R.id.list_item_name); final TextView itemSubtitle = convertView.findViewById(R.id.list_item_subtitle); final ProgressBar itemSpinner = convertView.findViewById(R.id.list_spinner); final View itemCheck = convertView.findViewById(R.id.list_check); itemNameView.setText(trackFile.getName()); itemSubtitle.setText(trackFile.getSize()); // Update based on logging and sync state if (Services.tracks.local.isUploading(trackFile)) { // Show upload progress final int progress = Services.tracks.local.getUploadProgress(trackFile); final int filesize = (int) trackFile.file.length(); itemSpinner.setProgress(progress); itemSpinner.setMax(filesize); itemSpinner.setVisibility(View.VISIBLE); } else { itemSpinner.setVisibility(View.GONE); } itemCheck.setVisibility(View.GONE); break; case TYPE_TRACK_REMOTE: final TrackMetadata trackData = ((ListTrackData) item).track; final TextView itemNameView2 = convertView.findViewById(R.id.list_item_name); final TextView itemSubtitle2 = convertView.findViewById(R.id.list_item_subtitle); final ProgressBar itemSpinner2 = convertView.findViewById(R.id.list_spinner); final View itemCheck2 = convertView.findViewById(R.id.list_check); itemNameView2.setText(trackData.date_string); itemSubtitle2.setText(trackData.subtitle()); if ("BASE".equals(trackData.jumpType)) { itemSubtitle2.setCompoundDrawablesWithIntrinsicBounds(R.drawable.type_base, 0, 0, 0); } else if ("Skydive".equals(trackData.jumpType)) { itemSubtitle2.setCompoundDrawablesWithIntrinsicBounds(R.drawable.type_sky, 0, 0, 0); } else if ("PG".equals(trackData.jumpType)) { itemSubtitle2.setCompoundDrawablesWithIntrinsicBounds(R.drawable.type_pg, 0, 0, 0); } else { itemSubtitle2.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0); } itemSpinner2.setVisibility(View.GONE); if (trackData.abbrvFile(context).exists() || trackData.localFile(context).exists()) { itemCheck2.setVisibility(View.VISIBLE); } else { itemCheck2.setVisibility(View.GONE); } break; } return convertView; } @Override public void notifyDataSetChanged() { populateItems(); super.notifyDataSetChanged(); } @Override public TrackListItem getItem(int position) { return items.get(position); } void clickItem(int position, @NonNull Context context) { final TrackListItem item = items.get(position); switch (item.getType()) { case TYPE_TRACK_LOCAL: final TrackFile trackFile = ((ListTrackFile) item).track; Intents.openTrackLocal(context, trackFile); break; case TYPE_TRACK_REMOTE: final TrackMetadata trackData = ((ListTrackData) item).track; Intents.openTrackRemote(context, trackData); break; } } @Override public long getItemId(int position) { return position; } @Override public int getCount() { return items.size(); } @Override public int getViewTypeCount() { return 3; } @Override public int getItemViewType(int position) { return getItem(position).getType(); } }
Java
UTF-8
2,321
2.140625
2
[]
no_license
/* * #%L * Excel Report Format Application * %% * Copyright (C) 2016 - 2018 Emu Data Services * %% * 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. * #L% */ package com.zimpics.eds.app_wa01a.helpers; import com.zimpics.eds.app_wa01a.TPFile; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; //This is a singleton class public class TPFileHelper { private static final Logger LOGGER = LoggerFactory.getLogger(TPFileHelper.class); private static final TPFileHelper INSTANCE = new TPFileHelper(); public static TPFileHelper getInstance() { return TPFileHelper.INSTANCE; } private TPFileHelper() { } public List<TPFile> getFiles() throws SQLException { TPFileHelper.LOGGER.debug("Loading files"); final List<TPFile> files = new ArrayList<>(); final String sql = "SELECT * FROM tblFile ORDER BY file_name"; try (Connection connection = DbHelper.getConnection(); PreparedStatement psmt = connection.prepareStatement(sql); ResultSet rs = psmt.executeQuery()) { while (rs.next()) { final TPFile f = new TPFile(); f.setfName(rs.getString("file_name")); f.setDtProcessed(rs.getString("date_processed")); f.setfStatus(rs.getString("file_status")); f.setEnquiries(rs.getInt("enquiries")); f.setCalls(rs.getInt("calls")); f.setfTimesRun(rs.getInt("times_run")); files.add(f); } } TPFileHelper.LOGGER.debug("Loaded {} files", files.size()); return files; } }
Shell
UTF-8
406
2.609375
3
[ "MIT" ]
permissive
#!/bin/sh while true; do sleep 10 flask deploy if [[ "$?" == "0" ]]; then echo Deploy success break fi echo Deploy command failed, retrying in 10 secs... done # nohup flask build index > /dev/null 2>&1 & flask build index # nohup flask build similarity > /dev/null 2>&1 & flask build similarity exec gunicorn -b :5000 --access-logfile - --error-logfile - manage:app
Java
UTF-8
186
1.59375
2
[]
no_license
package eu.skillguard.web.gui.components; import com.haulmont.cuba.gui.components.Component; public interface DirectoryUpload extends Component { String NAME = "directoryUpload"; }
Python
UTF-8
469
3.171875
3
[]
no_license
""" To check whether givan tree is a balanced tree or not """ def balance_soltuion(root): if root is None: return 0 left = balance_soltuion(root.left) if left==-1: return -1 right = balance_soltuion(root.right) if right==-1: return -1 if abs(left - right) > 1: return -1 return max(left, right) + 1 if __name__=="__main__": re = balance_soltuion(root) if re == -1: return False else: return True
Java
UTF-8
3,271
3.46875
3
[]
no_license
//Spencer Neveux // IPI // CECS 277 // 9/27/18 public class Cookie extends DessertItem { private int number; private int pricePerDozen; private int calories; private int cost; /** * Null Constructor for cookie */ public Cookie(){ this("", 0, 0); } /** * Overloaded constructor for cookie * @param name string value for name * @param number int value for number of cookies * @param pricePerDozen int value for the price/dozen */ public Cookie(String name, int number, int pricePerDozen) { super(name); this.number = number; this.pricePerDozen = pricePerDozen; setCost(number, pricePerDozen); } /** * Overloaded constructor including calories * @param name string value for name * @param number int value for num of cookies * @param pricePerDozen int value for price/dozen * @param calories int value for calories per cookie */ public Cookie(String name, int number, int pricePerDozen, int calories) { super(name); this.number = number; this.pricePerDozen = pricePerDozen; this.calories = calories; setCost(number, pricePerDozen); } /** * Getter for cost * @return int value of cost */ public int getCost() { return cost; } /** * Getter for num of cookies * @return int value of cookies */ public int getNumber() { return number; } /** * Getter for calories * @return int value of calorie per cookie */ public int getCalories() { return calories; } /** * Setter for num of cookies * @param number int value representing num of cookies */ public void setNumber(int number) { this.number = number; } /** * Getter for price per dozen * @return int value price per dozen cookies */ public int getPricePerDozen() { return pricePerDozen; } /** * Setter for price per dozen * @param pricePerDozen int value for price per dozen */ public void setPricePerDozen(int pricePerDozen) { this.pricePerDozen = pricePerDozen; } /** * Setter for name * @param name string value representing name of cookie */ public void setName(String name) { super.name = name; } /** * Setter for calories * @param calories int value for calorie per cookie */ public void setCalories(int calories){ this.calories = calories; } /** * Setter for cost * @param number int value for num cookies * @param pricePerDozen int value for price/dozen */ public void setCost(int number, int pricePerDozen) { if (number == 12) cost = pricePerDozen; else { cost = (int)Math.round(pricePerDozen / 12.0 * number); } } /** * Overriding toString method * @return string value of cookie representation */ @Override public String toString() { String result = getNumber() + " @ " + getPricePerDozen() + " /dz.\n" + String.format("%-27.24s %5.2f", getName(), getCost() / 100.0); return result; } }
Markdown
UTF-8
1,941
3.390625
3
[ "MIT" ]
permissive
# Creating a new Use Case A use case represents an action in the system. These use cases orchestrate the flow of data to and from the entities, and direct those entities to use their enterprise wide business rules to achieve the goals of the use case. It can be a mutation of the state or a query but not both in a CQRS project. Let's create a Use Case that just do: `echo "LOOL"`. ### The Command ```php <?php declare(strict_types=1); namespace App\Application\Command\Log; class EchoCommand { } ``` ### The handler ```php <?php declare(strict_types=1); namespace App\Application\Command\Log; use App\Application\Command\CommandHandlerInterface; class EchoHandler implements CommandHandlerInterface { public function __invoke(EchoCommand $command): void { echo 'LOOL'; } } ``` Now you can use this from UI ### The console command ```php <?php declare(strict_types=1); namespace App\UI\Cli\Command; use App\UI\Cli\Command\Base\CustomCommand; use League\Tactician\CommandBus; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class EchoCliCommand extends CustomCommand { /** @var CommandBus */ private $commandBus; public function __construct(CommandBus $commandBus) { $this->commandBus = $commandBus; parent::__construct(); } /** * {@inheritdoc} */ protected function configure() { $this ->setName('app:echo') ->setDescription('just an echo') ; } /** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $echoCommand = new \App\Application\Command\Log\EchoCommand(); $this->commandBus->handle($echoCommand); } } ``` ### Let's test it Execute: `./bin/console app:echo` And you should see: `LOOL` And that's all with 0 config thanks to Symfony 4!
Java
UTF-8
864
1.8125
2
[]
no_license
package com.yiziton.dataweb.waybill.vo; import lombok.Data; /** * 仓储枢纽-外发货量 VO */ @Data public class OutDeliveryVolumeVO { /** * 外发网点 */ private String operationOganization; /** * 当天外发时间 */ private String today; /** * 当天外发总费用 */ private String todayOutDeliverCost; /** * 当天揽货总费用 */ private String todayTakeGoodsFee; /** * 当天外发总方数 */ private String todayVolume; /** * 当月月份 */ private String month; /** * 当月累计外发货总费用 */ private String monthOutDeliverCost; /** * 当月累计揽货总费用 */ private String monthTakeGoodsFee; /** * 当月累计外发总方数 */ private String monthVolume; }
Java
UTF-8
2,162
2.171875
2
[]
no_license
package com.ruczajsoftware.workoutrival.config; import com.arangodb.ArangoDB; import com.arangodb.ArangoDatabase; import com.arangodb.entity.CollectionEntity; import com.arangodb.springframework.annotation.EnableArangoRepositories; import com.arangodb.springframework.config.ArangoConfiguration; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import javax.annotation.PostConstruct; import java.util.List; import java.util.stream.Collectors; import static com.ruczajsoftware.workoutrival.model.database.DbCollectionsKt.getDbCollections; @Configuration @Profile("!test") @EnableArangoRepositories(basePackages = {"com.ruczajsoftware.workoutrival"}) public class ArangoDBConfig implements ArangoConfiguration { private static final String DB_NAME = "workout-rival-db"; @Value("${arangodb.host}") private String host; @Value("${arangodb.port}") private Integer port; @Bean public ArangoDB.Builder arango() { return new ArangoDB.Builder() .host(host, port) .user("root") .password("root"); } @Bean public String database() { return DB_NAME; } @PostConstruct public void initDatabase() { ArangoDB arangoDB = arango().build(); if (!arangoDB.getDatabases().contains(DB_NAME)) { arangoDB.createDatabase(DB_NAME); } ArangoDatabase database = arangoDB.db(DB_NAME); initCollections(database); } private void initCollections(ArangoDatabase database) { final List<String> dbCollectionsNames = database.getCollections().stream() .map(CollectionEntity::getName) .collect(Collectors.toList()); getDbCollections().forEach( collectionName -> { if (!dbCollectionsNames.contains(collectionName)) { database.createCollection(collectionName); } } ); } }
Markdown
UTF-8
5,887
3.5
4
[ "MIT" ]
permissive
# Joystick Features (Note: this post is mainly based off a paper from [this](https://www.chiefdelphi.com/t/joystick-scaling-deadband/355153) forum post.) Once again, 1257 generally uses Xbox controllers to interact with a robot. One is pictured below. ![Amazon Basics Controller](img/AmazonBasicsController.jpg ':size=350x300') The two joysticks on such a controller are almost always in use, whether it be for moving a drivetrain, an arm, or some other mechanism easily controlled with joystick input. However, the joysticks could have mechanical defects, and therefore may return erroneous inputs. To counteract this physical issue, or to just increase precision, we can implement a few adjustments in code. ## Scaled Input To control, say, a drivetrain, we would map a joystick's movement on the controller axis to corresponding motors. Take a look at this graph of **linear** joystick input: ![Linear Input Graph](img/LinearInputDesmos.jpg ':size=400x400') Here, the x-axis represents joystick position (where it is being read on the controller axis), and the y-axis is the motor output. In the context of a drivetrain motor, this input above would send unadjusted joystick input to the motor. Think of it this way: if a joystick was at the 0.5 position, the output would subsequently be `motor.set(0.5)`. Controlling a drivetrain well requires a certain level of precision, especially when lining up to a position or performing slight turns. Once again, we generally try to increase precision through manipulating controller input. In order to make control more precise, especially at the smaller levels of input (0.0-0.4), we can raise joystick input to a certain power (moving from a linear to higher-order function). Lower inputs are achieved for the same joystick movement: ![Scaled Input Graph](img/ScaledInputsDesmos.jpg ':size=400x400') The blue curve represents **"squared input"** (x<sup>2</sup>), and the green curve represents **"cubed input"** (x<sup>3</sup>). We usually settle with just squared input, as cubing is generally a bit too drastic, but at the end of day, it all depends on the mechanism. Implementing this in code is pretty simple. When transforming joystick input into mechanism output, we could just use: ```java Math.pow(input, 2); ``` *However*, for squared inputs, we need to also reconsider the fact that we can have negative joystick input (i.e. reversed direction). As a solution, we can get the sign of the original input using the `signum()` function and add it to the above: ```java Math.signum(input) * Math.pow(input, 2); ``` This way, the sign is retained for negative input. More on the Java `signum()` function [here](https://www.tutorialspoint.com/java/lang/math_signum_float.htm). ## Deadbanding We'll now move into another topic: deadbanding. This is a process that helps us adjust for any defect in the joysticks themselves that affects controller input. A situation where the joystick is inexact would be when it defaults to an input value *slightly* higher or lower than 0, i.e. when no one touches the joystick but it still sends input. While that miniscule input probably won't move a large mechanism, it can definitely be problematic at times. Thus, implementing deadbanding is a good practice. The general idea is to create what's called a "deadband," or essentially a neutral zone in which we dictate the input to be 0. This helps us avoid that slight "default" input described above. Here's a *basic* deadband input graph: ![Basic Deadband](img/BasicDeadband.jpg ':size=450x400') In this case, the deadband lies between -0.4 and 0.4. If the joystick defaults to any value between that range, the input is commanded to be 0. The way to implement this in code isn't too difficult. If we let get and store joystick input in a variable `input`, we can implement the following concept in appropriate places: ```java if (abs(input) < deadband) { output = 0; } ``` ### Scaled Deadbanding If you take a look at the basic deadband graph, you'll probably notice how the input jumps drastically up to the corresponding, unadjusted value. While this isn't necessarily *bad*, a substantial amount of precision is lost due to the deadband and that value jump. This can be problematic for sensitive mechanisms like arms and elevators that require very precise movement at times. The way to avoid this jump is to *scale* our input outside of the deadband. This would be considered a "better" input system: ![Scaled Deadband](img/ScaledDeadband.jpg ':size=450x400') Here, the jump from before is completely eliminated, as the input outside of the deadband is scaled down. Implementing this in code isn't too difficult either, just with some extra math: ```java if (abs(input) < deadband) { output = 0; } else { output = (1 / (1 - deadband)) * (input + (-Math.signum(input) * deadband)); } ``` More on the Java `signum()` function [here](https://www.tutorialspoint.com/java/lang/math_signum_float.htm). A mathematical explanation from the [source](https://www.chiefdelphi.com/t/joystick-scaling-deadband/355153) cited above: > Essentially, it is based off of the point-slope form Y = M(X - X0) + Y0. However, Y0 is not used because we want the value to start at 0. X0 is the deadband adjusted to be positive or negative depending on whether the joystick is in the positive or negative direction. The slope was based off of the slope formula, where slope = ( Y2 - Y1 ) / ( X2 – X1 ). Y2 is equal to 1 for achieving 100% on the output of the function and X2 is 1 for an input of 100%. Y1 is 0 because X1 is equal to the deadband, because at the deadband we want the function output to be 0% and at 100% we want the function output to be 100%. Scaled deadbanding should generally be used over basic deadbanding for the reasons described above: better precision and overall improved control.
JavaScript
UTF-8
3,657
2.71875
3
[]
no_license
#!/usr/bin/env node const chalk = require('chalk'); const { Command } = require('commander'); const low = require('lowdb'); const FileSync = require('lowdb/adapters/FileSync'); const program = new Command(); program.version('0.0.1'); const adapter = new FileSync('parallel.json') const db = low(adapter) // Set some defaults (required if your JSON file is empty) db.defaults({ packages: {}, installed: [] }) .write(); const success = chalk.green('success'); const warning = chalk.yellow('warning'); const error = chalk.red('error'); const info = chalk.blue('info'); const memoGetDependencies = async (dependencies) => { const packages = await db.get('packages').toJSON(); const cache = {}; const getDependencies = (depends = []) => { return depends.reduce((all, package) => { if (!cache[package]) { cache[package] = true; all.push(package); const nextDepends = packages[package] || []; return [...all, ...getDependencies(nextDepends)]; } return all; }, []) }; return getDependencies(dependencies); } program .command('depends <name>') .option('-d, --dependencies [dependencies...]', 'dependencies', []) .description('Sets the dependencies of a package') .action((name, opts) => { // Set a dependencies using Lodash shorthand syntax console.log({ name, dependencies: opts.dependencies}) db.set(`packages.${name}`, opts.dependencies || []) .write(); console.log(` ${warning} parallel.json found. Your project contains parallel file generated. ${success} Saved parallel.json file. ${success} Saved ${opts.dependencies.length + 1} new dependencies. ${info} Direct dependencies └─ ${name} ${info} All dependencies ${opts.dependencies.map(d => `├─ ${d} \n`).join('')}└─ ${name} ✨ Done!`) }) program .command('install <name>') .description('Install the specified package and any necessary transient dependencies.') .action((name) => { const hasPackage = db.get('packages').has(name).toJSON(); if(!hasPackage){ console.log(`${error} a package called "${chalk.green(name)}" does not exist. ${chalk.red('This command has had no effect.')}`); return; } const hasItem = !(db.get('installed').findIndex(p => p === name).toJSON() == -1); if(hasItem){ console.log(`${warning} There's already a package called "${chalk.green(name)}" installed. ${chalk.red('This command has had no effect.')}`); } else { // Add a dependencies db.get('installed') .push(name) .write() console.log(`${success} ${chalk.blue(name)} installed`); } }); program .command('uninstall <name>') .description('Uninstall the specified package and any transient dependencies that are not dependent of other installed packages.') .action((name) => { // remove installed package db.get('installed') .remove( p => p === name) .write() console.log(`${success} ${chalk.blue(name)} uninstalled`); }); program .option('-o, --order-by <type>', 'order by') .command('list') .description('Lists all the installed packages, including transient dependencies.') .action(async (opts) => { const dependencies = await db.get('installed').toJSON(); const all = await memoGetDependencies(dependencies); if(!all.length){ console.log(chalk.blue(`${success} There are not packages installed`)); } else { console.log(`${success} dependencies: ${ all.map((d, index) => `${all.length - 1 !== index ? '├─' : '└─'} ${d} \n`).join('') } ✨ Done!`) } }); program.parse(process.argv); // console.log(chalk.blue('Hello world!'));
C#
UTF-8
5,549
2.5625
3
[]
no_license
namespace UnitTestsOfCountdown.Tests.BLL { using System; using System.Collections.Generic; using CountdownBusinessLogic; using CountdownBusinessLogic.Service; using CountdownDataBaseLayer; using CountdownDataBaseLayer.Repo; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using Transfer; using Transfer.SmallTransfer; /// <summary> /// The instance of UnitTestActions. /// </summary> [TestClass] public class CountdownCollectionTest { #region Private Fields /// <summary> /// The time for postpone /// </summary> private const int TimeForPostpone = 5; /// <summary> /// The countdown controller. /// </summary> private ICountdownCollection countdowns; /// <summary> /// The reminder. /// </summary> private Countdown countdown; /// <summary> /// The test context instance. /// </summary> private TestContext testContextInstance; #endregion #region Public Constructors /// <summary> /// Initializes a new instance of the <see cref="CountdownCollectionTest"/> class. /// </summary> public CountdownCollectionTest() { this.countdown = new Countdown() { Reminder = new ReminderDto() { Id = 1, Name = "test reminder.", Description = "testing", TypeOfReminder = new TypeOfReminderDto() { Id = 1, Name = "Progress", Description = "Progress reminder" }, UserName = "Test/User", ProgressSettings = new ProgressSettingsDto() { Duration = 5, Id = 1, Interval = 60, Start = new DateTime(2000, 1, 1, 1, 1, 1) } } }; Mock<IClient> mockClient = new Mock<IClient>(); mockClient.Setup(c => c.NotifyAboutChanges(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<State>())); Mock<IRepoFactory> mockRepo = new Mock<IRepoFactory>(); IRepoFactory factory = new RepositoryFactory(); FactoryInit(factory); this.countdowns = new CountdownCollection(factory, mockClient.Object); } #endregion #region Public Properties /// <summary> /// Gets or sets the test context which provides /// information about and functionality for the current test run. /// </summary> /// <value> /// The test context. /// </value> public TestContext TestContext { get { return this.testContextInstance; } set { this.testContextInstance = value; } } #endregion #region Additional test attributes //// You can use the following additional attributes as you write your tests: //// //// Use ClassInitialize to run code before running the first test in the class //// [ClassInitialize()] //// public static void MyClassInitialize(TestContext testContext) { } //// //// Use ClassCleanup to run code after all tests in a class have run //// [ClassCleanup()] //// public static void MyClassCleanup() { } //// //// Use TestInitialize to run code before running each test //// [TestInitialize()] //// public void MyTestInitialize() { } //// //// Use TestCleanup to run code after each test has run //// [TestCleanup()] //// public void MyTestCleanup() { } #endregion #region Public Methods /// <summary> /// Tests the activate. /// </summary> [TestMethod] public void Activate_Test1() { this.countdowns.Activate(this.countdown); Assert.AreEqual(DateTime.Now.AddMinutes(this.countdown.Reminder.ProgressSettings.Duration).ToUniversalTime().ToShortTimeString(), this.countdown.Reminder.ProgressSettings.Start.ToShortTimeString()); } /// <summary> /// Tests the postpone. /// </summary> [TestMethod] public void Postpone_Test1() { DateTime oldStart = this.countdown.Reminder.ProgressSettings.Start.ToLocalTime(); this.countdowns.Postpone(this.countdown, TimeForPostpone); if ((oldStart - DateTime.Now).Ticks < 0) { oldStart = oldStart.AddMinutes(TimeForPostpone); } else { oldStart = oldStart.AddMinutes(TimeForPostpone - this.countdown.Reminder.ProgressSettings.Duration - this.countdown.Reminder.ProgressSettings.Interval); } Assert.AreEqual(oldStart.ToShortTimeString(), this.countdown.Reminder.ProgressSettings.Start.ToLocalTime().ToShortTimeString()); } #endregion #region Private Methods /// <summary> /// Factories the initialize. /// </summary> /// <param name="factory">The factory.</param> private static void FactoryInit(IRepoFactory factory) { factory.GetDaysRepo = MocksRepo<Days>(); factory.GetExerciseRepo = MocksRepo<Exercises>(); factory.GetFilesRepo = MocksRepo<Files>(); factory.GetImagesRepo = MocksRepo<Images>(); factory.GetMonthRepo = MocksRepo<Monthes>(); factory.GetProgressSettingsRepo = MocksRepo<ProgressSettings>(); factory.GetReminderRepo = MocksRepo<Reminder>(); factory.GetReminderSettingsRepo = MocksRepo<ReminderSettings>(); factory.GetWeeksRepo = MocksRepo<Weeks>(); } /// <summary> /// Mocks the repository. /// </summary> /// <typeparam name="T">The repository entity.</typeparam> /// <returns>The repository.</returns> private static IRepo<T> MocksRepo<T>() where T : new() { var mock = new Mock<IRepo<T>>(); mock.Setup(r => r.Add(It.IsAny<T>())); mock.Setup(r => r.Delete(It.IsAny<T>())); mock.Setup(r => r.Update(It.IsAny<T>())); mock.Setup(r => r.UpdateMany(It.IsAny<IEnumerable<T>>(), It.IsAny<IEnumerable<T>>())); mock.Setup(r => r.GetAll()).Returns(new List<T>()); mock.Setup(r => r.GetById(It.IsAny<int>())).Returns(new T()); return mock.Object; } #endregion } }
Java
UTF-8
684
3.390625
3
[ "MIT" ]
permissive
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ //recursive public class Solution { public boolean isValidBST(TreeNode root) { return isValid(root, null, null); } private boolean isValid(TreeNode node, Integer max, Integer min){ if (node == null) return true; if(min !=null && node.val<= min) return false; if(max != null && node.val>= max) return false; // pass the value return isValid(node.left, node.val, min) && isValid(node.right, max, node.val); } }
Markdown
UTF-8
1,958
2.890625
3
[]
no_license
Unity gain frequency = $12MHz$ non-inverting amplifier Calculate closed loop 3-dB bandwidth for the amplifier if the ideal gain is $A_{IDEAL}=10$ (assume $A_0=1_E6$) $$ A_{CL}={{A_{IDEAL}\over1+{k_n\over A_0}}\over 1+j({fk_n\over B(1+{k_n\over A_0})})}\\ closedloop\ 3dB\ bandwidth={B\over k_n}\\ noninverting\ \therefore\ A_0=k_n\\ BW=f_1={B\over k_n}={12MHz\over10}=1.2MHz $$ Do it again, with an inverting amp with an ideal gain of -100. $$ A_{IDEAL}={-R_f\over R_i};\ k_n=1+{R_f\over R_i}\\ k_n=A_{IDEAL} + 1\\ f_1={12MHz\over101} $$ ![](2-19_Notes.assets/opAmpCapConversion.png) Given $X_C={1\over jwc}$ Break frequency = $f_1={1\over2\pi RC}={1\over 2\pi \tau}$ This is important. This determines what scope to buy. Looking at a square wave, you want to see a $33MHz$ signal undisturbed. Given a specific rise time, $BW={0.35\over risetime}$. Rise time is typically $1\over10$ of your frequency. This is your absolute minimum. If you want something that probably won’t effect the system, get a 5x bandwidth from the above calculation. If you want something overkill, get something 10x bandwidth above. Rise time is the time from 10% to 90%. $$ 0.1V_{in}=V_{in}(1-e^{-t_1\over\tau})\\ 0.9V_{in}=V_{in}(1-e^{-t_2\over\tau})\\ t_1=-\tau ln(0.9);\ t_2=-\tau ln(0.1)\\ risetime=t_2-t_1=-\tau(ln(0.1)-ln(0.9))\\ risetime={-ln(0.1)-ln(0.9)\over2\pi BW}\approx{0.35\over BW} $$ # Example 1 ![](2-19_Notes.assets/example1.png) Unity gain = $B=1MHz$. Find 3dB BW ($B\over k_n$) and risetime ($0.35\over BW$) $$ {V_o\over V_{in}}=(1+{1k\over2k\|3k})\approx1.833\\ {B\over k_n}=545kHz;\ risetime = 640ns $$ # Slew Rate Slew rate is pedal to the metal. $V_{out}$ grows at a constant speed. For the 741, the slew rate is $0.5V/\mu s$ max. If you try to pull more current than it can output, it will just not do it. There will be distortion on an AC waveform. This distortion looks like a sawtooth function. $f_{max}<{slewrate\over2\pi V_o}$
C#
UTF-8
1,200
3.140625
3
[ "MIT" ]
permissive
using System; using System.Numerics; using System.Runtime.CompilerServices; namespace Box2D.NetStandard.Common { public struct Rot { /// Sine and cosine internal float s; /// Sine and cosine internal float c; /// Initialize from an angle in radians [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Rot(float angle) { s = MathF.Sin(angle); c = MathF.Cos(angle); } /// Set using an angle in radians. [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void Set(float angle) { s = MathF.Sin(angle); c = MathF.Cos(angle); } /// Set to the identity rotation void SetIdentity() { s = 0.0f; c = 1.0f; } /// Get the angle in radians float GetAngle() { return MathF.Atan2(s, c); } /// Get the x-axis Vector2 GetXAxis() { return new Vector2(c, s); } /// Get the u-axis Vector2 GetYAxis() { return new Vector2(-s, c); } }; }
Java
UTF-8
1,127
2.65625
3
[]
no_license
package edu.byuh.byuhtest.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import edu.byuh.byuhtest.model.Student; import edu.byuh.byuhtest.repo.StudentRepo; @Service public class StudentService { @Autowired private StudentRepo repo; //CRUD /** * Takes in a student object to save in the database * @param student */ public void save(Student student) { // insert into student (emp_id, first_name, last_name) values (?, ?, ?) repo.save(student); } /** * Returns a list of student objects form the database * @return */ public List<Student> listAll() { // select * from student return repo.findAll(); } /** * Returns a student object from the database with the give id * @param id * @return */ public Student get(Long id) { // select * from student where id = ? return repo.findById(id).get(); } /** * Deletes a student form the database with the given id * @param id */ public void delete(Long id) { // delete from student where id = ? repo.deleteById(id); } }
Markdown
UTF-8
2,559
3.75
4
[ "MIT" ]
permissive
# 1366. Rank Teams by Votes Difficulty: Medium https://leetcode.com/problems/rank-teams-by-votes/ In a special ranking system, each voter gives a rank from highest to lowest to all teams participated in the competition. The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie again, we continue this process until the ties are resolved. If two or more teams are still tied after considering all positions, we rank them alphabetically based on their team letter. Given an array of strings votes which is the votes of all voters in the ranking systems. Sort all teams according to the ranking system described above. Return a string of all teams sorted by the ranking system. **Example 1:** ``` Input: votes = ["ABC","ACB","ABC","ACB","ACB"] Output: "ACB" Explanation: Team A was ranked first place by 5 voters. No other team was voted as first place so team A is the first team. Team B was ranked second by 2 voters and was ranked third by 3 voters. Team C was ranked second by 3 voters and was ranked third by 2 voters. As most of the voters ranked C second, team C is the second team and team B is the third. ``` **Example 2:** ``` Input: votes = ["WXYZ","XYZW"] Output: "XWYZ" Explanation: X is the winner due to tie-breaking rule. X has same votes as W for the first position but X has one vote as second position while W doesn't have any votes as second position. ``` **Example 3:** ``` Input: votes = ["ZMNAGUEDSJYLBOPHRQICWFXTVK"] Output: "ZMNAGUEDSJYLBOPHRQICWFXTVK" Explanation: Only one voter so his votes are used for the ranking. ``` **Example 4:** ``` Input: votes = ["BCA","CAB","CBA","ABC","ACB","BAC"] Output: "ABC" Explanation: Team A was ranked first by 2 voters, second by 2 voters and third by 2 voters. Team B was ranked first by 2 voters, second by 2 voters and third by 2 voters. Team C was ranked first by 2 voters, second by 2 voters and third by 2 voters. There is a tie and we rank teams ascending by their IDs. ``` **Example 5:** ``` Input: votes = ["M","M","M","M"] Output: "M" Explanation: Only team M in the competition so it has the first rank. ``` **Constraints:** * 1 <= votes.length <= 1000 * 1 <= votes[i].length <= 26 * votes[i].length == votes[j].length for 0 <= i, j < votes.length. * votes[i][j] is an English upper-case letter. * All characters of votes[i] are unique. * All the characters that occur in votes[0] also occur in votes[j] where 1 <= j < votes.length.
Ruby
UTF-8
8,077
2.546875
3
[ "MIT" ]
permissive
require "spec_helper" describe Mongoid::Extensions::ObjectId::Conversions do let(:object_id) do BSON::ObjectId.new end let(:composite_key) do "21-jump-street" end describe ".convert" do context "when the class is using object ids" do context "when provided a single object id" do let(:converted) do BSON::ObjectId.convert(Person, object_id) end it "returns the object id" do converted.should == object_id end end context "when provided an array of object ids" do let(:other_id) do BSON::ObjectId.new end let(:converted) do BSON::ObjectId.convert(Person, [ object_id, other_id ]) end it "returns the array of object ids" do converted.should == [ object_id, other_id ] end end context "when provided an array of nils" do let(:converted) do BSON::ObjectId.convert(Person, [ nil, nil ]) end it "returns an empty array" do converted.should be_empty end end context "when provided an array of empty strings" do let(:converted) do BSON::ObjectId.convert(Person, [ "", "" ]) end it "returns an empty array" do converted.should be_empty end end context "when provided a single string" do context "when the string is a valid object id" do let(:converted) do BSON::ObjectId.convert(Person, object_id.to_s) end it "converts to an object id" do converted.should == object_id end end context "when the string is not a valid object id" do it "returns the key" do BSON::ObjectId.convert(Person, composite_key).should eq( composite_key ) end end context "when the string is empty" do let(:converted) do BSON::ObjectId.convert(Person, "") end it "converts to nil" do converted.should be_nil end end end context "when providing an array of strings" do context "when the strings are valid object ids" do let(:other_id) do BSON::ObjectId.new end let(:converted) do BSON::ObjectId.convert(Person, [ object_id.to_s, other_id.to_s ]) end it "converts to an array of object ids" do converted.should == [ object_id, other_id ] end end context "when the strings are not valid object ids" do let(:other_key) do "hawaii-five-o" end let(:converted) do BSON::ObjectId.convert(Person, [ composite_key, other_key ]) end it "returns the key" do BSON::ObjectId.convert(Person, composite_key).should eq( composite_key ) end end end context "when provided a hash" do context "when the hash key is _id" do context "when the value is an object id" do let(:hash) do { :_id => object_id } end let(:converted) do BSON::ObjectId.convert(Person, hash) end it "returns the hash" do converted.should == hash end end context "when the value is an array of object ids" do let(:other_id) do BSON::ObjectId.new end let(:hash) do { :_id => [ object_id, other_id ] } end let(:converted) do BSON::ObjectId.convert(Person, hash) end it "returns the hash" do converted.should == hash end end context "when the value is a string" do let(:hash) do { :_id => object_id.to_s } end let(:converted) do BSON::ObjectId.convert(Person, hash) end it "returns the hash with converted value" do converted.should == { :_id => object_id } end end context "when the value is an array of strings" do let(:other_id) do BSON::ObjectId.new end let(:hash) do { :_id => [ object_id.to_s, other_id.to_s ] } end let(:converted) do BSON::ObjectId.convert(Person, hash) end it "returns the hash with converted values" do converted.should == { :_id => [ object_id, other_id ] } end end end context "when the hash key is id" do context "when the value is an object id" do let(:hash) do { :id => object_id } end let(:converted) do BSON::ObjectId.convert(Person, hash) end it "returns the hash" do converted.should == hash end end context "when the value is an array of object ids" do let(:other_id) do BSON::ObjectId.new end let(:hash) do { :id => [ object_id, other_id ] } end let(:converted) do BSON::ObjectId.convert(Person, hash) end it "returns the hash" do converted.should == hash end end context "when the value is a string" do let(:hash) do { :id => object_id.to_s } end let(:converted) do BSON::ObjectId.convert(Person, hash) end it "returns the hash with converted value" do converted.should == { :id => object_id } end end context "when the value is an array of strings" do let(:other_id) do BSON::ObjectId.new end let(:hash) do { :id => [ object_id.to_s, other_id.to_s ] } end let(:converted) do BSON::ObjectId.convert(Person, hash) end it "returns the hash with converted values" do converted.should == { :id => [ object_id, other_id ] } end end end context "when the hash key is not an id" do context "when the value is a string" do let(:hash) do { :key => composite_key } end let(:converted) do BSON::ObjectId.convert(Person, hash) end it "returns the hash" do converted.should == hash end end context "when the value is an array of strings" do let(:hash) do { :key => [ composite_key ] } end let(:converted) do BSON::ObjectId.convert(Person, hash) end it "returns the hash" do converted.should == hash end end end end end context "when the class is not using object ids" do context "when provided an object" do let(:converted) do BSON::ObjectId.convert(Address, 100) end it "returns the object" do converted.should == 100 end end context "when provided an array" do let(:converted) do BSON::ObjectId.convert(Address, [ 100 ]) end it "returns the array" do converted.should == [ 100 ] end end context "when provided a hash" do let(:converted) do BSON::ObjectId.convert(Address, { :key => 100 }) end it "returns the hash" do converted.should == { :key => 100 } end end end end end
Python
UTF-8
301
3.9375
4
[]
no_license
""" --检测数据类型-- type(数据) """ num1 = 1 num2 = 1.1 a = 'hello world' b = True print(type(num1)) print(type(num2)) print(type(a)) print(type(b)) c = [10, 20, 30] d = (10, 20, 30) e = {10, 20, 30} f = {'name': 'Tom', 'age': 18} print(type(c)) print(type(d)) print(type(e)) print(type(f))
JavaScript
UTF-8
875
3.703125
4
[]
no_license
var moviename = "Avengers"; var movierating = 4.5 var movielang = "Eng" var moviename1 = "Jab We Met"; var movierating1 = 4.7 var movielang1 = "Hindi" var movies = { name:'Avengers', rating:4.5, lang:'Eng' } undefined typeof(movies) "object" movies.name "Avengers" movies.rating 4.5 movies.type="Action" "Action" movies {name: "Avengers", rating: 4.5, lang: "Eng", type: "Action"} delete movies.rating true movies {name: "Avengers", lang: "Eng", type: "Action"} movies['name'] "Avengers" ////JSON//// JavaScript Object Notation var movies = [ { name:'Avengers', rating:4.5, lang:'Eng' }, { name:'Jab We Met', rating:2.5, lang:'Hindi' } ] movies[0].name "Avengers" movies[1].name "Jab We Met" var calc = { sum:function(a,b){return a+b}, sub:(a,b) => {return a-b} } calc.sum(3,5) 8 calc.sub(5,2) 3
Python
UTF-8
1,041
2.71875
3
[]
no_license
from django.db import models class Categoria(models.Model): nome = models.CharField(max_length=30, verbose_name="Nome") class Meta: vebose_name = "Categoria" vebose_name_plural = "Categorias" def _str_(self): return self.nome class Produto(models.Model): LITROS = "LT" GRAMAS = "GR" KILOS = "KG" UNIDADE = "UND" PECA = "PC" UNIDADES = [ (LITROS, "Litros"), (GRAMAS, "Gramas"), (KILOS, "Kilos"), (UNIDADE, "Unidade"), (PECA, "Peça"), ] nome = models.CharField(max_length=100, verbose_name="Nome") valor = models.DecimalField(max_length=10, decimal_places=2, verbose_name="Valor") categoria = models.ForeignKey( "produtos.Categoria", verbose_name="Categoria", on_delete = models.CASCADE ) nome = models.CharField(max_length=3, choices=UNIDADES) class Meta: vebose_name = "Produto" vebose_name_plural = "Produtos" def _str_(self): return self.nome
Java
UTF-8
1,136
4.09375
4
[]
no_license
package Offer; import java.util.Stack; public class Offer_04 { public static void main(String[] args) { //初始化一个大小为4的队列 Solution solution = new Solution(); solution.push(1); solution.push(2); solution.push(3); solution.push(4); System.out.println(solution.pop()); System.out.println(solution.pop()); System.out.println(solution.pop()); System.out.println(solution.pop()); } } class Solution { Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public void push(int node) { //先将push到队列的元素加入栈1中 stack1.push(node); } public int pop() { if(!stack2.empty()){ //检查栈2中是否还有元素,如果有就直接从栈2中取出 return stack2.pop(); }else { //如果栈2为空,就从栈1将数据倒入栈2,达到顺序的效果 while(!stack1.empty()){ stack2.push(stack1.pop()); } } return stack2.pop(); } }
Java
UTF-8
558
2.28125
2
[]
no_license
package com.nt.test; import com.nt.dao.EmployeeDao; import com.nt.dao.EmployeeDaoFactory; import com.nt.utility.mysql_HibernateUtil; import com.nt.utility.oracle_HibernateUtil; public class TwoDBsTest { public static void main(String[] args) { EmployeeDao dao=null; //Get Dao dao=EmployeeDaoFactory.getInstance(); //Invoke method dao.transferEmployee(102); //Close Objects oracle_HibernateUtil.closeSessionFactory(); mysql_HibernateUtil.closeSessionFactory(); }//main }//class
Java
UTF-8
360
2.609375
3
[]
no_license
package com.snayi.choose;/** * */ /** * @auther SNAYi *@describe * @date 2019/6/26 下午 03:23 */ public class Title6 { private float f = 1.0f; int m =12; static int n =1; public static void main(String[] args) { Title6 title6 = new Title6(); // title6.f = 1.0; // this.n; System.out.println(n); } }
Java
UTF-8
1,120
2.609375
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package memorama; import java.io.File; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.DataLine; public class Sounds{ public static Clip getSound(String file){ try{ AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("src\\sonidos\\" + file)); AudioFormat format = audioInputStream.getFormat(); DataLine.Info info = new DataLine.Info(Clip.class, format); Clip sound = (Clip)AudioSystem.getLine(info); sound.open(audioInputStream); return sound; } catch(Exception e){ System.out.println("Error al abrir el archivo"); return null; } } public static void playSound(Clip clip){ clip.stop(); clip.setFramePosition(0); clip.start(); } }
Java
UTF-8
3,218
2.375
2
[]
no_license
package com.example.tp1_app2; import androidx.appcompat.app.AppCompatActivity; import androidx.constraintlayout.widget.ConstraintLayout; import android.app.SearchManager; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.Toast; public class SecondActivity extends AppCompatActivity implements View.OnClickListener { private final String TAG = "PMR"; private LinearLayout refLayBody; private String pseudo = ""; private String phoneNumber="A completer !"; int idBtn1 = View.generateViewId(); int idBtn2 = View.generateViewId(); int idBtn3 = View.generateViewId(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); Bundle b = this.getIntent().getExtras(); pseudo = b.getString("pseudo"); alerter("Pseudo saisi " + pseudo); refLayBody = findViewById(R.id.layBody); // Création d'un bouton et paramètrage Button btnRechercheWeb = new Button(this); btnRechercheWeb.setText("Recherche " + pseudo); btnRechercheWeb.setId(idBtn1); btnRechercheWeb.setOnClickListener(this); // Création d'un bouton et paramètrage Button btnSMS = new Button(this); btnSMS.setText("SMS"); btnSMS.setId(idBtn2); btnSMS.setOnClickListener(this); // Création d'un bouton et paramètrage Button btnDial = new Button(this); btnDial.setText("Dial"); btnDial.setId(idBtn3); btnDial.setOnClickListener(this); // Insertion du boutons dans le layout refLayBody.addView(btnRechercheWeb); refLayBody.addView(btnSMS); refLayBody.addView(btnDial); } void alerter(String s) { Log.i(TAG,s); Toast t = Toast.makeText(this,s, Toast.LENGTH_LONG); t.show(); } @Override public void onClick(View v) { if (v.getId() == idBtn1) { Intent intent = new Intent(Intent.ACTION_WEB_SEARCH); intent.putExtra(SearchManager.QUERY, pseudo); if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent); } } else if (v.getId() == idBtn2) { alerter("Btn 2"); Intent intent = new Intent(Intent.ACTION_SEND); intent.setData(Uri.parse("smsto:" + phoneNumber)); // This ensures only SMS apps respond intent.putExtra("sms_body", "Pseudo saisi : "+ pseudo); // intent.putExtra(Intent.EXTRA_STREAM, attachment); if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent); } } else if (v.getId() == idBtn3) { Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse("tel:" + phoneNumber)); if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent); } } } }
Java
UTF-8
2,604
2.484375
2
[]
no_license
package ir.coursio.notes.model; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.util.Log; import ir.coursio.notes.AddDrawingActivity; import ir.coursio.notes.AddNoteActivity; import ir.coursio.notes.App; import ir.coursio.notes.model.db.DataContract; import ir.coursio.notes.model.structures.NoteStruct; /** * Created by Taher on 29/05/2017. * Project: notes */ public class NoteModel { // Static strings to identify intent extras public static final String FOLDER_ID = "folder_id"; public static final String FOLDER_NAME = "folder_name"; private final Activity activity; public NoteModel(Activity activity) { this.activity = activity; } public void newTextNoteRequest() { Intent intent = new Intent(activity, AddNoteActivity.class); intent.putExtra(FOLDER_ID, activity.getIntent().getStringExtra(FOLDER_ID)); activity.startActivity(intent); } public void newDrawingNoteRequest() { Intent intent = new Intent(activity, AddDrawingActivity.class); intent.putExtra(FOLDER_ID, activity.getIntent().getStringExtra(FOLDER_ID)); activity.startActivity(intent); } public void editNoteRequest(NoteStruct note) { if (!note.isPainting()) { Intent intent = new Intent(activity, AddNoteActivity.class); intent.putExtra(AddNoteModel.FOLDER_ID, note.getFolderId()); intent.putExtra(AddNoteModel.IS_EDITING, true); intent.putExtra(AddNoteModel.NOTE, note); activity.startActivity(intent); } else { Intent intent = new Intent(activity, AddDrawingActivity.class); intent.putExtra(AddDrawingModel.FOLDER_ID, note.getFolderId()); intent.putExtra(AddDrawingModel.IS_EDITING, true); intent.putExtra(AddDrawingModel.NOTE, note); activity.startActivity(intent); } } /** * Gets current folder's name. * * @return The String folder's name */ public String getFolderName() { return activity.getIntent().getStringExtra(FOLDER_NAME); } /** * Requests to ContentProvider to delete a note. * * @param id The String id of deleting note. * @return int which is number of deleted rows. */ public int removeNote(String id) { Uri uri = Uri.parse(DataContract.FoldersEntry.CONTENT_URI_NOTES.toString() + "/" + activity.getIntent().getStringExtra(FOLDER_ID)); return App.getAppContext().getContentResolver().delete(uri, id, null); } }
Java
UTF-8
320
1.9375
2
[ "Apache-2.0" ]
permissive
package krati.core; /** * InvalidStoreConfigException * * @author jwu * @since 06/25, 2011 * */ public class InvalidStoreConfigException extends RuntimeException { private static final long serialVersionUID = 1L; public InvalidStoreConfigException(String message) { super(message); } }
Java
UTF-8
445
1.632813
2
[]
no_license
package com.example.lettuce; import io.lettuce.core.RedisClient; import io.lettuce.core.api.StatefulRedisConnection; import io.lettuce.core.api.sync.RedisCommands; import java.util.concurrent.CompletableFuture; public class RedisCli { public static RedisClient redisClient = RedisClient .create("redis://@192.168.4.145:6379/0"); public static StatefulRedisConnection<String, String> connection = redisClient.connect(); }
Markdown
UTF-8
6,515
2.53125
3
[]
no_license
In `src/serviceworker.js` we need to save access to the service worker registration here. Set `global.registration = registration`. #### src/servicewroker.js ```js function registerValidSW(swUrl, config) { navigator.serviceWorker .register(swUrl) .then(registration => { global.registration = registration ... }) .catch(error => { console.error('Error during service worker registration:', error); }); } ``` Then in `src/app.js` we can make a new `<button>` which will ask for permission to subscribe the user to push notifications. #### src/app.js ```js class Profile extends Component { state = { image: null, supportsCamera: 'mediaDevices' in navigator } ... render() { return ( <div> <nav className="navbar navbar-light bg-light"> <span className="navbar-brand mb-0 h1"> <Link to="/"> <img src={Back} alt="logo" style={{ height: 30 }} /> </Link> Profile </span> </nav> <div style={{ textAlign: 'center' }}> ... <br /> <button onClick={this.subscribe}>Subscribe for Notifications</button> </div> </div> ) } } ``` Then in the `onClick` function for that button, we can ask the user for push notification permission. ```js subscribe = () => { } ``` First, we need a public key for our PAS server. For this demo we'll generate a new key by globally installing Web Push with `npm install web-push -g`. #### terminal ```bash $ npm install web-push -g ``` ```bash $ web-push generate-vapid-keys ``` Then by running `web-push generate-vapid-keys`, which will give us a new public and private key. Let's copy the public key, and then back in `src/app.js` paste that key into the new subscribe function. ![image of the public and private keys](https://res.cloudinary.com/dg3gyk0gu/image/upload/v1544630124/transcript-images/react-add-push-notifications-to-a-pwa-with-react-in-chrome-and-on-android-keys.png) #### src/app.js ```js subscribe = () => { const key = "BDk-kDxLswQMajg9TJqpb9VFTjQeQmS0FE_rTVJ4f9G-v9GFkzcDt-vYkvz5dVkbCfrGmJeLTbvuNUKpOUojWB4" ``` Then we'll copy a function from the Google documentation about push notifications called `urlB64ToUint8Array`, which will convert that public key as a string into an array that can actually be used by the browser to subscribe to push notifications. ```js function urlB64ToUint8Array(base64String) { const padding = '='.repeat((4 - base64String.length % 4) % 4); const base64 = (base64String + padding) .replace(/\-/g, '+') .replace(/_/g, '/'); const rawData = window.atob(base64); const outputArray = new Uint8Array(rawData.length); for (let i = 0; i < rawData.length; ++i) { outputArray[i] = rawData.charCodeAt(i); } return outputArray; } ``` Then in our `subscribe` method we can access the service worker registration that we stored on global and call `subscribe` on the `pushManager`. That function is a promise, so we'll know that the user is `subscribed` successfully once we get a promise resolution. ```js subscribe = () => { const key = "BDk-kDxLswQMajg9TJqpb9VFTjQeQmS0FE_rTVJ4f9G-v9GFkzcDt-vYkvz5dVkbCfrGmJeLTbvuNUKpOUojWB4" global.registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: urlB64ToUint8Array(key) }).then(sub => { console.log("Subscribed!") }).catch(err => { console.log("Did not subscribe.") }) } ``` In `src/sw.js` we can listen for a `'push', event` from the push server just like we did for fetch. Add a push `eventListener`. We're going to tell the `event` to `waitUntil` we show a push notification. Access the server worker registration with `self.registration` and call `showNotification`. That takes the title as the first argument and a hash of options as the second. For now, we'll set the `icon` to an icon that we already have in the public folder and the `body` to whatever text comes through the push from the server. #### src/sw.js ```js self.addEventListener('push', event => { event.waitUntil(self.registration.showNotification('Todo List', { icon: '/icon-120.png', body: event.data.text() })) }) ``` Now we can build and serve that to test the notification. #### terminal.png ```bash $ yarn build ``` ```bash $ serve -S build ``` [02:36] Google Chrome's DevTools currently has a bug with testing push notifications. I'm using Google Canary here, which has fixed the issue. First go to the profile page and click the button to subscribe to push notifications. Once we click allow, you'll see a message in the console that confirms that we can now receive push notifications from this PWA. ![image showing that we can recieve push messages](https://res.cloudinary.com/dg3gyk0gu/image/upload/v1544630127/transcript-images/react-add-push-notifications-to-a-pwa-with-react-in-chrome-and-on-android-subscribe.png) Then in the application tab of DevTools, locate the push test location. Then we can fill in a message like "New todo item added." ![image showing the addition of a message in the application tab](https://res.cloudinary.com/dg3gyk0gu/image/upload/v1544629702/transcript-images/react-add-push-notifications-to-a-pwa-with-react-in-chrome-and-on-android-message.png) When we click push we see the notification. ![image showing the push notification pop up](https://res.cloudinary.com/dg3gyk0gu/image/upload/v1544630121/transcript-images/react-add-push-notifications-to-a-pwa-with-react-in-chrome-and-on-android-push.png) Also, in `src/app.js` we can trigger a push notification from our app directly instead of from a third party server. Add a new `button` and we'll make a new `testPushMessage` function. #### src/app.js ```js <br /> <button onClick={this.subscribe}>Subscribe for Notifications</button> <br /> <button onClick={this.testPushMessage} >Test Push Message</button> ``` In that function we'll call the global registration that we said earlier. Here we can call `showNotification` directly passing in a title and a `body`. ```js testPushMessage = () => { global.registration.showNotification('Test Message', { body: 'Success!' }) } ``` When we build and serve that we can go to the profile page and click the button and see our successful push test triggered from the app code itself. #### terminal.png ```bash $ yarn build ``` ```bash $ serve -S build ``` ![image of the successful push test](https://res.cloudinary.com/dg3gyk0gu/image/upload/v1544630121/transcript-images/react-add-push-notifications-to-a-pwa-with-react-in-chrome-and-on-android-pushsuccess.png)
Markdown
UTF-8
898
3.796875
4
[]
no_license
[179.largest-number](https://leetcode.com/problems/largest-number/) Given a list of non negative integers, arrange them such that they form the largest number. **Example 1:** **Input:** `[10,2]` **Output:** "`210"` **Example 2:** **Input:** `[3,30,34,5,9]` **Output:** "`9534330"` **Note:** The result may be very large, so you need to return a string instead of an integer. **Solution:** ```cpp class Solution { public: string largestNumber(vector<int>& nums) { if( nums.size() == 0 ) return 0; vector<string> str; for(int n : nums) str.push_back(to_string(n)); sort(str.begin(), str.end(), [](string &a, string &b){ return a+b > b+a; }); string ans; for( string &s:str) ans+=s; if( ans[0] == '0') return "0"; return ans; } }; ```
Ruby
UTF-8
716
3.1875
3
[]
no_license
require './lib/transaction.rb' class Bank def initialize(transaction_class=Transaction) @transaction_class = transaction_class end def deposit(account, amount) fail 'You cannot deposit a negative amount' if amount < 0 transaction = @transaction_class.new(amount, DateTime.now) account.process_transaction transaction end def withdraw(account, amount) fail 'You cannot withdraw a negative amount' if amount < 0 deduction_amount = amount * -1 transaction = @transaction_class.new(deduction_amount, DateTime.now) account.process_transaction transaction end def balance account account.balance end def print_statement account account.print_statement end end
C#
UTF-8
1,123
2.828125
3
[]
no_license
using System; using LiteNetLib; namespace Exanite.Arpg.Networking.Server { /// <summary> /// Arguments for server PeerDisconnected events /// </summary> public class PeerDisconnectedEventArgs : EventArgs { private readonly NetPeer peer; private readonly DisconnectInfo disconnectInfo; /// <summary> /// Creates a new <see cref="PeerDisconnectedEventArgs"/> /// </summary> public PeerDisconnectedEventArgs(NetPeer peer, DisconnectInfo disconnectInfo) { this.peer = peer; this.disconnectInfo = disconnectInfo; } /// <summary> /// The <see cref="NetPeer"/> that disconnected from the server /// </summary> public NetPeer Peer { get { return peer; } } /// <summary> /// Additional information about the disconnection /// </summary> public DisconnectInfo DisconnectInfo { get { return disconnectInfo; } } } }
C++
UTF-8
701
3.421875
3
[]
no_license
#include "queue.hpp" #include <iostream> using namespace std; void dump_queue(Queue<int>& q) { cout << "queue dump: "; while (!q.empty()) { cout << q.dequeue() << " "; } cout << endl; } int main(int argc, char* args[]) { Queue<int> q(3); q.enqueue(1); q.enqueue(2); q.enqueue(3); dump_queue(q); q.enqueue(1); q.enqueue(2); q.dequeue(); q.enqueue(3); dump_queue(q); q.enqueue(1); q.enqueue(2); q.dequeue(); q.dequeue(); q.enqueue(3); dump_queue(q); q.enqueue(1); q.enqueue(2); q.enqueue(3); q.dequeue(); q.dequeue(); q.dequeue(); q.enqueue(4); dump_queue(q); return 0; }
PHP
UTF-8
1,253
2.5625
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Session; use Illuminate\Support\Facades\DB; use App\Courses; class CoursesController extends Controller { public function check() { if (Session::has('user_id')) { $courses = DB::select('select * from courses where User_Id = ? ', [Session::get('user_id', 0)]); return view('user_page.courses', [ 'active_courses' => $courses ]); } else{ return redirect()->route('main'); } } public function signUp(Request $request) { $user_id = Session::get('user_id', 0); $course = $request->input('signUp'); $user_course = DB::select('select * from courses where User_Id = ? and Course = ?', [$user_id, $course]); if($user_course!=null){ session()->flash('course_message', 'Вы уже записаны на курс '.$course); return redirect()->route('courses'); } else{ $course_user = new Courses(); $course_user->User_Id = $user_id; $course_user->Course = $course; $course_user->save(); session()->flash('course_message', 'Вы были записаны на курс '.$course); return redirect()->route('courses'); } } }
Python
UTF-8
9,554
2.8125
3
[]
no_license
""" here i'll load my matlab shape ctxt data (r, theta, phi) and try to run it through a siamese network """ import numpy as np import pandas as pd from scipy.io import loadmat, savemat def get_shape_data(train_pct): # total length of data should be 2* (24,000 + 46,000) = 140,000 src = '/home/nripesh/Dropbox/research_matlab/feature_tracking/matconvnet-1.0-beta21/cardiac_data/' x_match_a = pd.read_csv(src + 'X_match_a.csv', header=None).as_matrix().astype('float32') x_match_b = pd.read_csv(src + 'X_match_b.csv', header=None).as_matrix().astype('float32') x_non_match_a = pd.read_csv(src + 'X_non_match_a.csv', header=None).as_matrix().astype('float32') x_non_match_b = pd.read_csv(src + 'X_non_match_b.csv', header=None).as_matrix().astype('float32') # get indices and lengths for the split x_m_inds = np.arange(x_match_a.shape[0]) np.random.shuffle(x_m_inds) x_m_train_len = int(train_pct*x_match_a.shape[0]) x_m_test_len = x_match_a.shape[0] - x_m_train_len x_n_inds = np.arange(x_non_match_a.shape[0]) np.random.shuffle(x_n_inds) x_n_train_len = int(train_pct*x_non_match_a.shape[0]) x_n_test_len = x_non_match_a.shape[0] - x_n_train_len # get the train set first x_train = np.zeros([x_m_train_len*2 + x_n_train_len*2, x_match_a.shape[1]]) y_train = np.zeros([x_m_train_len*2 + x_n_train_len*2, 1]) count1 = 0 for i in range(x_m_train_len): x_train[count1, :] = x_match_a[x_m_inds[i], :] x_train[count1+1, :] = x_match_b[x_m_inds[i], :] y_train[count1] = 1 y_train[count1 + 1] = 1 count1 += 2 for i in range(x_n_train_len): x_train[count1, :] = x_non_match_a[x_n_inds[i], :] x_train[count1+1, :] = x_non_match_b[x_n_inds[i], :] y_train[count1] = 0 y_train[count1 + 1] = 0 count1 += 2 # the test set x_test = np.zeros([x_m_test_len*2 + x_n_test_len*2, x_match_a.shape[1]]) y_test = np.zeros([x_m_test_len*2 + x_n_test_len*2, 1]) count2 = 0 for i in range(x_m_test_len): x_test[count2, :] = x_match_a[x_m_inds[x_m_train_len + i], :] x_test[count2 + 1, :] = x_match_b[x_m_inds[x_m_train_len + i], :] y_test[count2] = 1 y_test[count2 + 1] = 1 count2 += 2 for i in range(x_n_test_len): x_test[count2, :] = x_non_match_a[x_n_inds[x_n_train_len + i], :] x_test[count2 + 1, :] = x_non_match_b[x_n_inds[x_n_train_len + i], :] y_test[count2] = 0 y_test[count2 + 1] = 0 count2 += 2 return x_train, x_test, y_train, y_test def get_shape_data_paired_format(): # total length of data should be 2* (24,000 + 46,000) = 140,000 src = '/home/nripesh/Dropbox/research_matlab/feature_tracking/matconvnet-1.0-beta21/cardiac_data/' x_match_a = pd.read_csv(src + 'X_match_a.csv', header=None).as_matrix().astype('float32') x_match_b = pd.read_csv(src + 'X_match_b.csv', header=None).as_matrix().astype('float32') x_non_match_a = pd.read_csv(src + 'X_non_match_a.csv', header=None).as_matrix().astype('float32') x_non_match_b = pd.read_csv(src + 'X_non_match_b.csv', header=None).as_matrix().astype('float32') x_match = np.concatenate([x_match_a, x_match_b], axis=1) x_match = np.reshape(x_match, [x_match.shape[0], 2, int(x_match.shape[1]/2)]) y_match = np.ones([x_match.shape[0], 1]) x_non_match = np.concatenate([x_non_match_a, x_non_match_b], axis=1) x_non_match = np.reshape(x_non_match, [x_non_match.shape[0], 2, int(x_non_match.shape[1] / 2)]) y_non_match = np.zeros([x_non_match.shape[0], 1]) x_out = np.concatenate([x_match, x_non_match]).astype('float32') y_out = np.concatenate([y_match, y_non_match]).astype('float32') if x_out.max() > 1: x_out /= 255 return x_out, y_out def get_int_paired_format(src, data_name): # total length of data should be 2* (24,000 + 46,000) = 140,000 shape_data = loadmat(src + data_name) x_match_a = shape_data.get('X_match_a').astype('float32') x_match_b = shape_data.get('X_match_b').astype('float32') x_non_match_a = shape_data.get('X_non_match_a').astype('float32') x_non_match_b = shape_data.get('X_non_match_b').astype('float32') match_dim = x_match_a.shape if match_dim[1] != 1: x_match_a = x_match_a.reshape([match_dim[0], 1, 1, match_dim[1], match_dim[2], match_dim[3]]) x_match_b = x_match_b.reshape([match_dim[0], 1, 1, match_dim[1], match_dim[2], match_dim[3]]) else: x_match_a = x_match_a.reshape([match_dim[0], 1, match_dim[1], match_dim[2], match_dim[3], match_dim[4]]) x_match_b = x_match_b.reshape([match_dim[0], 1, match_dim[1], match_dim[2], match_dim[3], match_dim[4]]) x_match = np.concatenate([x_match_a, x_match_b], axis=1) y_match = np.ones([x_match.shape[0], 1]) non_match_dim = x_non_match_a.shape if non_match_dim[1] != 1: x_non_match_a = x_non_match_a.reshape([non_match_dim[0], 1, 1, non_match_dim[1], non_match_dim[2], non_match_dim[3]]) x_non_match_b = x_non_match_b.reshape([non_match_dim[0], 1, 1, non_match_dim[1], non_match_dim[2], non_match_dim[3]]) else: x_non_match_a = x_non_match_a.reshape([non_match_dim[0], 1, non_match_dim[1], non_match_dim[2], non_match_dim[3], non_match_dim[4]]) x_non_match_b = x_non_match_b.reshape([non_match_dim[0], 1, non_match_dim[1], non_match_dim[2], non_match_dim[3], non_match_dim[4]]) x_non_match = np.concatenate([x_non_match_a, x_non_match_b], axis=1) y_non_match = np.zeros([x_non_match.shape[0], 1]) x_out = np.concatenate([x_match, x_non_match]).astype('float32') y_out = np.concatenate([y_match, y_non_match]).astype('float32') if x_out.max() > 1: x_out /= 255 return x_out, y_out # this is used for unsupervised learning def get_only_patches(src, data_name): # total length of data should be 2* (24,000 + 46,000) = 140,000 print('loading... ' + data_name) shape_data = loadmat(src + data_name) x_patch = shape_data.get('X_patch').astype('float32') if x_patch.max() > 1: x_patch /= 255 return x_patch # this is used for semi-supervised learning, where the symantic segmentation labels are also available def get_patches_and_symantic_labels(src, data_name): # total length of data should be 2* (24,000 + 46,000) = 140,000 print('loading... ' + data_name) shape_data = loadmat(src + data_name) x_patch = shape_data.get('X_patch').astype('float32') y_patch = shape_data.get('Y_patch').astype('float32') if x_patch.max() > 1: x_patch /= 255 return x_patch, y_patch def get_shctxt_paired_format(src, data_name): shape_data = loadmat(src + data_name) x_match_a = shape_data.get('X_shp_match_a').astype('float32') x_match_b = shape_data.get('X_shp_match_b').astype('float32') x_non_match_a = shape_data.get('X_shp_non_match_a').astype('float32') x_non_match_b = shape_data.get('X_shp_non_match_b').astype('float32') match_dim = x_match_a.shape x_match_a = x_match_a.reshape([match_dim[0], 1, match_dim[1]]) x_match_b = x_match_b.reshape([match_dim[0], 1, match_dim[1]]) # this concat allows the siamese pairs to be accessed as x[0] and x[1] x_match = np.concatenate([x_match_a, x_match_b], axis=1) y_match = np.ones([x_match.shape[0], 1]) non_match_dim = x_non_match_a.shape x_non_match_a = x_non_match_a.reshape([non_match_dim[0], 1, non_match_dim[1]]) x_non_match_b = x_non_match_b.reshape([non_match_dim[0], 1, non_match_dim[1]]) x_non_match = np.concatenate([x_non_match_a, x_non_match_b], axis=1) y_non_match = np.zeros([x_non_match.shape[0], 1]) x_out = np.concatenate([x_match, x_non_match]).astype('float32') y_out = np.concatenate([y_match, y_non_match]).astype('float32') if x_out.max() > 1: x_out /= x_out.max() x_out[np.isnan(x_out)] = 0 return x_out, y_out def get_int_paired_format_flattened(src, data_name): # total length of data should be 2* (24,000 + 46,000) = 140,000 shape_data = loadmat(src + data_name) x_match_a = shape_data.get('X_match_a').astype('float32') x_match_b = shape_data.get('X_match_b').astype('float32') x_non_match_a = shape_data.get('X_non_match_a').astype('float32') x_non_match_b = shape_data.get('X_non_match_b').astype('float32') x_match_a = x_match_a.reshape([x_match_a.shape[0], 1, x_match_a.shape[1]*x_match_a.shape[2]*x_match_a.shape[3]]) x_match_b = x_match_b.reshape([x_match_b.shape[0], 1, x_match_b.shape[1]*x_match_b.shape[2]*x_match_b.shape[3]]) x_match = np.concatenate([x_match_a, x_match_b], axis=1) y_match = np.ones([x_match.shape[0], 1]) x_non_match_a = x_non_match_a.reshape([x_non_match_a.shape[0], 1, x_non_match_a.shape[1]*x_non_match_a.shape[2]*x_non_match_a.shape[3]]) x_non_match_b = x_non_match_b.reshape([x_non_match_b.shape[0], 1, x_non_match_b.shape[1]*x_non_match_b.shape[2]*x_non_match_b.shape[3]]) x_non_match = np.concatenate([x_non_match_a, x_non_match_b], axis=1) y_non_match = np.zeros([x_non_match.shape[0], 1]) x_out = np.concatenate([x_match, x_non_match]).astype('float32') y_out = np.concatenate([y_match, y_non_match]).astype('float32') if x_out.max() > 1: x_out /= x_out.max() return x_out, y_out
Markdown
UTF-8
1,556
2.59375
3
[]
no_license
# Asciinate ![](https://github.com/moyogatomi/Asciinate/blob/master/showcase.gif) ## Description fast transformation of grayscale and rgb images into custom ascii letters support for youtube stream (not all videos are working) ## Usage 0) have python >= 3.6 1) install requirements (virtualenv) ```bash pip install -r requirements ``` 2) init colorama ```python import colorama colorama.init() ``` 3) import core and pipeline modules ```python from coreX import Core, TerminalScreen, Engine ``` 4) Create Terminal controller ```python TS = TerminalScreen() ``` 5) Initialize core ```python # resolution - number of colors in a channel -> 2**resolution. 8 is max. Use 8 unless you want to carry extra 400mb in RAM core = Core(resolution=6, rgb=True) # dont care about image size and leave it to Terminal Controller core.adapt_size = TS.adapt(ratio=0.75) # define ascii table. This one is actually default core.table = u" . . . ....:.:.::::::;;;;;======+=+++|+|+|+||||i|iiiiililllIIvIvvvvvnvnnnnooo2o2222S2SSSSXXXXZZZZZZ#Z#Z#####mmBmBmWBWWBWWWWQQQ" # create Pipeline # media - link or path to image/YTvideo, or generator returning tuple(grayscale_image,rgb_image) tube = Engine( media="url or path to image/YT stream or generator", core=core, ) # clean screen TS.init_clean() # push image through pipeline and returns True if succesful if tube.propagate(): # move cursor to 0,0 in terminal for quick override TS.fast_clean() # Flush result into terminal tube.render() ``` ### For more use cases checkout examples
C++
UTF-8
1,330
2.84375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; typedef long long ll; bool reversecompare(int a, int b) { return a > b; } struct newchar { char strng[20]; char newstrng[20]; string final = ""; }; bool newcompare(newchar a, newchar b) { return a.final < b.final; } int main () { ios::sync_with_stdio(false); cin.tie(nullptr); int r, c, dummy; newchar x[20]; while(true) { cin >> r >> c; // cout << r << c << endl; if (!(r||c)) { return 0; } else { for (int i = 0; i < c; i++) x[i].final = ""; for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { cin >> x[j].strng[i]; } } for (int i = 0; i < c; i++) { for (int j = 0; j < r; j++) { if (int(x[i].strng[j]) < 96) x[i].final += char(int(x[i].strng[j])+32); else x[i].final += x[i].strng[j]; } } stable_sort(x, x+c, newcompare); for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { cout << x[j].strng[i]; } cout << endl; } cout << endl; } } return 0; }
Java
UTF-8
2,489
1.992188
2
[ "Apache-2.0" ]
permissive
package com.sv.mc.controller; import com.sv.mc.alipay.AliPayConfig; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; @RestController public class WXController { /** * 跳转到支付宝/微信判断网页 */ // @GetMapping("/wx") // public void turnToTestPage(String sn){ // System.out.println(sn); // } /** * 跳转到支付宝/微信判断网页 */ @GetMapping("/wx/wxApp") public void toHintPage(HttpServletResponse response,HttpServletRequest request) throws IOException { // ModelAndView mv = new ModelAndView(); // //页面回调地址 必须与应用中的设置一样 String return_url = "https://www.infhp.cn/mc/wx/wxApp2"; // //回调地址必须经encode // return_url = URLEncoder.encode(return_url,"UTF-8"); // // ModelAndView mv = new ModelAndView(); // mv.addObject("app_id", AliPayConfig.appId ); // mv.addObject("scope", "auth_user"); // mv.addObject("redirect_uri", return_url); //// mv.setViewName("./error/hint"); // mv.setViewName("./alipay/alipayUser"); String sn = request.getParameter("sn"); response.sendRedirect(AliPayConfig.alipayurl+"?app_id=" + AliPayConfig.appId + "&scope=auth_user&redirect_uri=" + return_url+"&state="+sn); // return void; } /** * 跳转到支付宝/微信判断网页 */ @GetMapping("/wx/wxApp2") public ModelAndView toHintPage2(HttpServletRequest request) { String sn = request.getParameter("state"); System.out.println(sn); ModelAndView mv = new ModelAndView(); mv.addObject("sn",sn); mv.setViewName("./error/hint"); // mv.setViewName("./alipay/alipayScan"); return mv; } /** * 跳转到支付宝首页 */ @GetMapping("/alipay/alipayScan") public ModelAndView toalipayScanPage(HttpServletRequest request) { // String sn = request.getParameter("state"); // System.out.println(sn); ModelAndView mv = new ModelAndView(); // mv.addObject("sn",sn); mv.setViewName("./alipay/alipayScan"); return mv; } }
Markdown
UTF-8
3,201
2.5625
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: "Предложение Let (Visual Basic) | Microsoft Docs" ms.date: "2015-07-20" ms.prod: ".net" ms.reviewer: "" ms.suite: "" ms.technology: - "devlang-visual-basic" ms.topic: "article" f1_keywords: - "vb.QueryLet" dev_langs: - "VB" helpviewer_keywords: - "Let - предложение" - "Let - оператор" - "запросы [Visual Basic], Let" ms.assetid: 981aa516-16eb-4c53-b1f1-5aa3e82f316e caps.latest.revision: 16 author: "stevehoag" ms.author: "shoag" caps.handback.revision: 16 --- # Предложение Let (Visual Basic) [!INCLUDE[vs2017banner](../../../visual-basic/includes/vs2017banner.md)] Вычисляет значение и присваивает его новой переменной внутри запроса. ## Синтаксис ``` Let variable = expression [, ...] ``` ## Части ||| |-|-| |Термин|Определение| |`variable`|Обязательный. Псевдоним, который может использоваться для ссылки на результаты предоставленного выражения.| |`expression`|Обязательный. Выражение, которое будет вычислено и присвоено указанной переменной.| ## Заметки Условие `Let` позволяет вычислить значения для каждого результата запроса и ссылаться на них с помощью псевдонима. Псевдоним может использоваться в других условиях, таких как условие `Where`. Условие `Let` позволяет создать оператор запроса, который проще прочесть, поскольку можно указать псевдоним для условия выражения, включенного в запрос, и заменять этот псевдоним при каждом использовании условия выражения. Можно включить любое количество `variable` и назначений `expression` в условие `Let`. Разделяйте каждое назначения запятой \(,\). ## Пример В следующем примере кода используется условие `Let` для вычисления 10% скидки на продукты. [!code-vb[VbSimpleQuerySamples#16](../../../visual-basic/language-reference/queries/codesnippet/VisualBasic/let-clause_1.vb)] ## См. также [Знакомство с LINQ в Visual Basic](../../../visual-basic/programming-guide/language-features/linq/introduction-to-linq.md) [Запросы](../../../visual-basic/language-reference/queries/queries.md) [Предложение Select](../../../visual-basic/language-reference/queries/select-clause.md) [Предложение From](../../../visual-basic/language-reference/queries/from-clause.md) [Предложение Where](../../../visual-basic/language-reference/queries/where-clause.md)
Markdown
UTF-8
8,541
3.078125
3
[ "Apache-2.0" ]
permissive
# Scaling event based system using containers This article talks about an approach to scale SQS consumers that are deployed in container-based ecosystem using ECS # Introduction In most cases, AWS Lambda can effectively process all the messages in SQS, but you may need to consider using an EC2 instance or ECS service if you run into any of the following issues: * Need more than 3 GB while processing an SQS message * Processing, a batch of SQS messages, may take more than 15 mins * Number of messages received per second is more than 1000 messages, and you would like to process as quickly as possible In this case, we use the EC2 autoscaling group to process SQS messages in scale. # Architecture It is essential to understand the following factors before defining cloudwatch alarms and scaling policies as it may vary ultimately for each application depending upon the use case: * Average time taken to process a message * Acceptable latency for processing a message Based on which we will set up autoscaling policies. Here is how the overall architecture looks like: ![architecture](images/arch.svg) **Notes** * When a user or an automated system uploads a new file to S3 "Input bucket," an event notification is triggered that automatically sends a message to the SQS queue * The SQS consumer is deployed as an ECS service created using a spring boot application. Here are details around the application: * This application uses `Thread.sleep(5000)` to sleep for 5 seconds before processing each message. This wait time is added to create a backlog of messages that can demonstrate scaling in the system. * The application reads the S3 file location from the SQS message, created different thumbnails of the image inside the `/tmp` directory of the container, then uploads them to the S3 output directory. * ECS service uses a combination of cloud watch alarms with a step scaling policy to scale in and out based on the total number of unprocessed messages in the queue using `ApproximateNumberOfMessagesVisible` metrics * Scaling policies are defined as: * Add 1 instance if `ApproximateNumberOfMessagesVisible >= 40` * Add 3 instances if `ApproximateNumberOfMessagesVisible >= 100` * Remove 1 instance if `ApproximateNumberOfMessagesVisible <= 10` Here is the sequence of events that happens when a user or an automated system uploads an image file to the Input S3 bucket ![init](images/sequence.svg) The code available in this repository is exposed as a CDK Construct. To learn more about CDK Construct, click [here](https://docs.aws.amazon.com/cdk/latest/guide/constructs.html) # Build & Deployment ## Pre-requistes * AWS CDK should be installed in the local laptop. You can read more about it [here](https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html) * ```Yarn``` needs to be installed, you can check the installation status by running this command * An AWS account with console and API access ```bash yarn version ``` **Output** 1.22.10 If ```Yarn``` is not installed run the following command ```bash npm install -g yarn ``` ## Build Check out the code from this repository using this command: ```bash mkdir ecs-event-based-scaling && cd ecs-event-based-scaling git clone https://github.com/hariohmprasath/ecs-event-driven-scaling.git . ``` Build the SQS consumer spring code using the following command: ```bash cd src/sqs-consumer-spring mvn clean install cd ../.. ``` > Note: Source code for SQS consumer based on spring boot is available under `src\sqs-consumer-spring` folder ## Deploy As the code is created as a CDK construct, the following parameters can be customized as part of the deployment | Parameter | Description | Default | | ------------- | ------------- | ----| | vpc | VPC in which the resources needs to be created | New VPC will be created | | inputBucket | S3 Input bucket, where the images for which thumbnails need to be generated will be uploaded | New S3 bucket | | outputBucket | S3 Output bucket, where the generated thumbnails will be uploaded | New S3 Bucket | | scalingCoolDown | Cool down period parameter for autoscaling | 200 seconds | | minInstances | Minimum number of instances for autoscaling | 1 | | maxInstances | Maximum number of instances for autoscaling | 10 | > Note: CDK Deploy will create a queue with a name `S3NotificationQueue` and spring boot consumer is configured to read messages from this queue. So any changes to queue name has to be made both on CDK script and spring boot application Code for the sample application using this construct is available in `src/integ.default.ts`. In order to deploy the application, first bootstrap a CDK environment (if you haven't done so already). ```bash # Bootstrap CDK (ONLY ONCE, if you have already done this you can skip this part) # Subsitute your AWS Account Id and AWS region in the command below $ cdk bootstrap \ --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess \ aws://<AWS Account Id>/<AWS_REGION> ``` Run the following command to start the deployment ```bash cdk deploy --require-approval never ``` > Note: The above command will take care of building the docker image, pushing it to ECR and running a CDK deployment Once the deployment is successful you will see the following output: ```bash ✅ testing-stack Outputs: testing-stack.EcsEventBasedScalinginputbucketoutput9F0DD2C3 = testing-stack-ecseventbasedscalinginputbucketa1d3-jx4tz0hfyh27 testing-stack.EcsEventBasedScalingoutputbucketoutput60F748A5 = testing-stack-ecseventbasedscalingoutputbucket4c2-ohj5gvtr0f5d testing-stack.EcsEventBasedScalingqueueoutput84B7B8B9 = S3NotificationQueue ``` > Note: CDK output will specify input & output S3 bucket along with the SQS queue name # Unit testing Unit testcases can be executed by running the following command from the root directory ```bash yarn test ``` ```bash yarn run v1.22.10 $ npx projen test 🤖 test | rm -fr lib/ 🤖 test » test:compile | tsc --noEmit --project tsconfig.jest.json 🤖 test | jest --passWithNoTests --all --updateSnapshot PASS test/index.test.ts ✓ create app (1137 ms) console.log /Users/harrajag/CodeBase/Pattern/ecs-event-based-scaling/src/sqs-consumer-spring at new EcsEventBasedScaling (src/index.ts:96:13) ----------|---------|----------|---------|---------|------------------- File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s ----------|---------|----------|---------|---------|------------------- All files | 100 | 72 | 100 | 100 | index.ts | 100 | 72 | 100 | 100 | 42-51 ----------|---------|----------|---------|---------|------------------- Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 5.397 s Ran all test suites. 🤖 test » eslint | eslint --ext .ts,.tsx --fix --no-error-on-unmatched-pattern src test build-tools .projenrc.js ✨ Done in 15.86s. ``` # Integration testing ## Simple test A sample image can be found under `sample-image` folder. You can run the following command from the root directory to upload the image to the s3 input folder: ```bash aws s3 cp test.png s3://<<input_bucket>> ``` The S3 upload will automatically trigger an SQS message, consumed by the spring boot application deployed as ECS service, and corresponding thumbnails get generated in the S3 output bucket. Here is a screenshot of it: ![output](images/s3Output.png) ## Load test You can simulate a load test scenario that will in turn trigger scaling by following the below steps: Create a new folder and copy closer to 50 images into this folder ```bash mkdir load-test && cd load-test # Copy 50 images into this folder cp <<50 image files>> . ``` Run the following command to sync the contents of the local folder to s3 input bucket ```bash aws s3 sync load-test s3://<<input_bucket>> ``` It will create 50 SQS messages. Since the spring boot consumer waits 5 seconds before processing each message, a automatic cloudwatch scale out alarm will be triggered. As the result of this, an autoscaling event will occur, and a new ECS task instance will be added to the ECS service # Cleanup Run the following command from root directory to delete the stack ```bash cdk destroy ``` # Resources * [Scaling based on Amazon SQS](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-using-sqs-queue.html) * [SQS Based ECS Service Autoscaling](https://medium.com/@gundogdu.emre/sqs-based-ecs-service-autoscaling-88772f4e260c)
JavaScript
UTF-8
5,197
2.546875
3
[]
no_license
function myFunc(){ alert("test"); alert(document.getElementById("Variables1").value); } var nPartons = document.getElementById("versusNpartons"); var datumMHT = { label: "MHT", fill: false, lineTension: .1, backgroundColor: "rgba(75,192,192,0.4)", borderColor: "rgba(75,192,192,1)", borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: "rgba(75,192,192,1)", pointBackgroundColor: "rgba(256,256,256,1)", pointBorderWidth: 2, pointHoverRadius: 10, pointHoverBackgroundColor: "rgba(75,192,192,1)", pointHoverBorderColor: "rgba(220,220,220,1)", pointHoverBorderWidth: 2, pointRadius: 1, pointHitRadius: 10, data: [65, 59, 80, 81, 56, 55, 40] }; var datumHT = { label: "HT", fill: false, lineTension: .1, backgroundColor: "rgba(75,75,192,0.4)", borderColor: "rgba(75,75,192,1)", borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: "rgba(75,75,192,1)", pointBackgroundColor: "rgba(256,256,256,1)", pointBorderWidth: 2, pointHoverRadius: 10, pointHoverBackgroundColor: "rgba(75,75,192,1)", pointHoverBorderColor: "rgba(220,220,220,1)", pointHoverBorderWidth: 2, pointRadius: 1, pointHitRadius: 10, data: [1, 32, 10, 10, 70, 50, 35], }; var datumSumMj = { label: "SumMj", fill: false, lineTension: .1, backgroundColor: "rgba(75,192,75,0.4)", borderColor: "rgba(75,192,75,1)", borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: "rgba(75,192,75,1)", pointBackgroundColor: "rgba(256,256,256,1)", pointBorderWidth: 2, pointHoverRadius: 10, pointHoverBackgroundColor: "rgba(75,192,75,1)", pointHoverBorderColor: "rgba(220,220,220,1)", pointHoverBorderWidth: 2, pointRadius: 1, pointHitRadius: 10, data: [120, 100, 80, 60, 40, 20, 0] }; var datumMT2 = { label: "MT2", fill: false, lineTension: .1, backgroundColor: "rgba(192,75,192,0.4)", borderColor: "rgba(192,75,192,1)", borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: "rgba(192,75,192,1)", pointBackgroundColor: "rgba(256,256,256,1)", pointBorderWidth: 2, pointHoverRadius: 10, pointHoverBackgroundColor: "rgba(192,75,192,1)", pointHoverBorderColor: "rgba(220,220,220,1)", pointHoverBorderWidth: 2, pointRadius: 1, pointHitRadius: 10, data: [65, 60, 10, 40, 73, 22, 100] }; var datumAlphaT = { label: "AlphaT", fill: false, lineTension: .1, backgroundColor: "rgba(192,192,75,0.4)", borderColor: "rgba(192,192,75,1)", borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: "rgba(192,192,75,1)", pointBackgroundColor: "rgba(256,256,256,1)", pointBorderWidth: 2, pointHoverRadius: 10, pointHoverBackgroundColor: "rgba(192,192,75,1)", pointHoverBorderColor: "rgba(220,220,220,1)", pointHoverBorderWidth: 2, pointRadius: 1, pointHitRadius: 10, data: [99,10,95,15,80,25,75] }; var datumNJets = { label: "NJets", fill: false, lineTension: .1, backgroundColor: "rgba(192,75,75,0.4)", borderColor: "rgba(192,75,75,1)", borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: "rgba(192,75,75,1)", pointBackgroundColor: "rgba(256,256,256,1)", pointBorderWidth: 2, pointHoverRadius: 10, pointHoverBackgroundColor: "rgba(192,75,75,1)", pointHoverBorderColor: "rgba(220,220,220,1)", pointHoverBorderWidth: 2, pointRadius: 1, pointHitRadius: 10, data: [40, 42, 38, 45, 41, 35, 39] }; var nPartonsData = { labels: ["2", "3", "4", "5", "6", "7","8"], datasets:[ datumHT , datumMHT , datumSumMj , datumMT2 , datumAlphaT , datumNJets ] }; var myLineChart = new Chart(nPartons, { type: 'line', data: nPartonsData, options: { responsive:false } });
Python
UTF-8
9,630
4.03125
4
[]
no_license
#!/usr/bin/env python # coding: utf-8 # # Question 1 # Given a linked list of N nodes such that it may contain a loop. A loop here means that the last node of the link list is connected to the node at position X(1-based index). If the link list does not have any loop, X=0. Remove the loop from the linked list, if it is present, i.e. unlink the last node which is forming the loop. # # In[1]: class ListNode: def __init__(self, val): self.val = val self.next = None def remove_loop(head): # Step 1: Find the meeting point of the slow and fast pointers slow = head fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: break # No loop exists in the list if not fast or not fast.next: return head # Step 2: Reset the slow pointer to the head slow = head # Step 3: Move both pointers one step at a time until they meet again while slow.next != fast.next: slow = slow.next fast = fast.next # Step 4: Remove the loop by setting the next pointer of the last node to None fast.next = None return head # # Question 2 # A number N is represented in Linked List such that each digit corresponds to a node in linked list. You need to add 1 to it. # # # # In[6]: class ListNode: def __init__(self, val): self.val = val self.next = None def addOne(head): # Step 1: Reverse the linked list prev = None curr = head while curr: next_node = curr.next curr.next = prev prev = curr curr = next_node head = prev # Step 2: Add 1 to the reversed linked list carry = 1 curr = head while curr: curr.val += carry carry = curr.val // 10 curr.val %= 10 if carry == 0: break curr = curr.next # Step 3: Reverse the linked list again prev = None curr = head while curr: next_node = curr.next curr.next = prev prev = curr curr = next_node head = prev # Step 4: If carry is still remaining, create a new head node with value 1 if carry > 0: new_head = ListNode(1) new_head.next = head head = new_head return head # # Question 3 # Given a Linked List of size N, where every node represents a sub-linked-list and contains two pointers:(i) a next pointer to the next node,(ii) a bottom pointer to a linked list where this node is head.Each of the sub-linked-list is in sorted order.Flatten the Link List such that all the nodes appear in a single level while maintaining the sorted order. Note: The flattened list will be printed using the bottom pointer instead of next pointer. # # In[7]: class ListNode: def __init__(self, val): self.val = val self.next = None self.bottom = None def merge(list1, list2): # Merge two sorted linked lists if not list1: return list2 if not list2: return list1 if list1.val <= list2.val: result = list1 result.bottom = merge(list1.bottom, list2) else: result = list2 result.bottom = merge(list1, list2.bottom) return result def flatten(head): # Base case: an empty list or a single node if not head or not head.next: return head # Recursively flatten the next node head.next = flatten(head.next) # Merge the flattened next node with the current node's bottom list head = merge(head, head.next) return head # # Question 4 # You are given a special linked list with N nodes where each node has a next pointer pointing to its next node. You are also given M random pointers, where you will be given M number of pairs denoting two nodes a and b i.e. a->arb = b (arb is pointer to random node). # Construct a copy of the given list. The copy should consist of exactly N new nodes, where each new node has its value set to the value of its corresponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list. # For example, if there are two nodes X and Y in the original list, where X.arb --> Y, then for the corresponding two nodes x and y in the copied list, x.arb --> y. # Return the head of the copied linked list. # # # In[8]: class Node: def __init__(self, val): self.val = val self.next = None self.random = None def copyRandomList(head): if not head: return None # Step 1: Create a copy of each node and link them together using the next pointer current = head while current: new_node = Node(current.val) new_node.next = current.next current.next = new_node current = new_node.next # Step 2: Assign the random pointers of the copied nodes current = head while current: if current.random: current.next.random = current.random.next current = current.next.next # Step 3: Separate the original list and the copied list current = head new_head = head.next new_current = new_head while current: current.next = current.next.next if new_current.next: new_current.next = new_current.next.next current = current.next new_current = new_current.next return new_head # # Question 5 # Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list. # The first node is considered odd, and the second node is even, and so on. # Note that the relative order inside both the even and odd groups should remain as it was in the input. # You must solve the problem in O(1) extra space complexity and O(n) time complexity. # # In[9]: class ListNode: def __init__(self, val): self.val = val self.next = None def oddEvenList(head): if not head or not head.next: return head odd_head = odd = head even_head = even = head.next while even and even.next: odd.next = even.next odd = odd.next even.next = odd.next even = even.next odd.next = even_head return odd_head # # Question 6 # Given a singly linked list of size N. The task is to left-shift the linked list by k nodes, where k is a given positive integer smaller than or equal to length of the linked list. # # In[10]: class ListNode: def __init__(self, val): self.val = val self.next = None def leftShift(head, k): if not head or not head.next: return head # Step 1: Find the kth node from the beginning of the list current = head for _ in range(k - 1): current = current.next if not current: return head # Step 2: Set the new head of the shifted list new_head = current.next # Step 3: Traverse to the end of the list tail = current while tail.next: tail = tail.next # Step 4: Connect the end of the list to the original head tail.next = head # Update the next pointer of the kth node to None current.next = None return new_head # # Question 7 # You are given the head of a linked list with n nodes. # For each node in the list, find the value of the next greater node. That is, for each node, find the value of the first node that is next to it and has a strictly larger value than it. # Return an integer array answer where answer[i] is the value of the next greater node of the ith node (1-indexed). If the ith node does not have a next greater node, set answer[i] = 0. # # In[11]: class ListNode: def __init__(self, val): self.val = val self.next = None def nextLargerNodes(head): stack = [] result = [] # Traverse the linked list in reverse order current = head while current: while stack and stack[-1] <= current.val: stack.pop() if stack: result.append(stack[-1]) else: result.append(0) stack.append(current.val) current = current.next # Reverse the result array result.reverse() return result # # Question 8 # Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences. # After doing so, return the head of the final linked list. You may return any such answer. # (Note that in the examples below, all sequences are serializations of ListNode objects.) # # In[12]: class ListNode: def __init__(self, val): self.val = val self.next = None def removeZeroSumSublists(head): dummy = ListNode(0) dummy.next = head prefix_sum = 0 prefix_sum_dict = {0: dummy} current = head while current: prefix_sum += current.val if prefix_sum in prefix_sum_dict: # Remove the sequence of nodes with a sum of 0 prev = prefix_sum_dict[prefix_sum] start = prev.next prefix_sum += start.val while start != current: del prefix_sum_dict[prefix_sum] start = start.next prefix_sum += start.val prev.next = current.next else: prefix_sum_dict[prefix_sum] = current current = current.next return dummy.next # In[ ]:
C++
UTF-8
796
2.609375
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> #include <math.h> using namespace std; int main() { int n, arr[20][20], mid, result = 2e9;; cin >> n; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) cin >> arr[i][j]; vector<int> v; mid = n / 2; for (int i = 0; i < mid; i++) v.push_back(0); for (int i = 0; i < mid; i++) v.push_back(1); do { int start = 0, link = 0; vector<int> s, l; for (int i = 0; i < n; i++) { if (v[i] == 0) s.push_back(i); else l.push_back(i); } for (int i = 0; i < mid; i++) for (int j = i + 1; j < mid; j++) { start += arr[s[i]][s[j]] + arr[s[j]][s[i]]; link += arr[l[i]][l[j]] + arr[l[j]][l[i]]; } result = min(result, abs(start - link)); } while (next_permutation(v.begin(), v.end())); cout << result; }
Python
UTF-8
6,817
2.53125
3
[]
no_license
# -*- coding: UTF-8 -*- """Collect up the functons used in all the weeks.""" from colorama import Fore from colorama import Style import inspect import os def test(testResult, name): if testResult: print(Fore.GREEN + "✔ " + name + Style.RESET_ALL) return 1 else: print(Fore.RED + "✘ " + name + Style.RESET_ALL) return 0 def test_flake8(fileName): test_dir = os.path.dirname(os.path.abspath(inspect.getfile( inspect.currentframe()))) files = [os.path.join(test_dir, fileName)] # Import the legacy API as flake8 3.0 currently has no official # public API - this has to be changed at some point. from flake8.api import legacy as flake8 style_guide = flake8.get_style_guide() report = style_guide.check_files(files) if report.total_errors == 0: return True else: print report.total_errors return False def completion_message(message, width): cap = '{start}{s:{c}^{n}}{end}'.format(n=width, c='*', s="", start=Fore.GREEN, end=Style.RESET_ALL) print cap + "\n" print(Fore.GREEN + "✔ " + message + Style.RESET_ALL) print "\n" + cap def nyan_cat(): cattern = [ ['{BRIGHT_BLUE}', '{x}'*80], ['{BRIGHT_BLUE}', '{x}'*80], ['{RED}', '{x}'*18, '{BRIGHT_BLUE}', '{x}'*16, '{BLACK}', '{x}'*30, '{BRIGHT_BLUE}', '{x}'*16], ['{RED}', '{x}'*32, '{BLACK}██{WHITE}', '{x}'*30, '{BLACK}██{BRIGHT_BLUE}', '{x}'*14], ['{BRIGHT_RED}', '{x}'*4, '{RED}', '{x}'*26, '{BLACK}██{WHITE}', '{x}'*6, '{MAGENTA}', '{x}'*22, '{WHITE}', '{x}'*6, '{BLACK}██{BRIGHT_BLUE}', '{x}'*12], ['{BRIGHT_RED}', '{x}'*30, '{BLACK}██{WHITE}', '{x}'*4, '{MAGENTA}', '{x}'*16, '{BLACK}', '{x}'*4, '{MAGENTA}', '{x}'*6, '{WHITE}', '{x}'*4, '{BLACK}██{BRIGHT_BLUE}██{BLACK}', '{x}'*4, '{BRIGHT_BLUE}', '{x}'*6], ['{BRIGHT_RED}', '{x}'*30, '{BLACK}██{WHITE}██{MAGENTA}', '{x}'*16, '{BLACK}██{WHITE}', '{x}'*4, '{BLACK}██{MAGENTA}', '{x}'*6, '{WHITE}██{BLACK}', '{x}'*4, '{WHITE}', '{x}'*4, '{BLACK}██{BRIGHT_BLUE}', '{x}'*4], ['{BRIGHT_YELLOW}', '{x}'*18, '{BRIGHT_RED}', '{x}'*12, '{BLACK}██{WHITE}██{MAGENTA}', '{x}'*16, '{BLACK}██{WHITE}', '{x}'*6, '{MAGENTA}', '{x}'*6, '{WHITE}██{BLACK}██{WHITE}', '{x}'*6, '{BLACK}██{BRIGHT_BLUE}', '{x}'*4], ['{BRIGHT_YELLOW}', '{x}'*22, '{BLACK}██{BRIGHT_YELLOW}', '{x}'*6, '{BLACK}██{WHITE}██{MAGENTA}', '{x}'*16, '{BLACK}██{WHITE}', '{x}'*6, '{BLACK}', '{x}'*8, '{WHITE}', '{x}'*8, '{BLACK}██{BRIGHT_BLUE}', '{x}'*4], ['{BRIGHT_YELLOW}', '{x}'*20, '{BLACK}██{WHITE}██{BLACK}██{BRIGHT_YELLOW}', '{x}'*4, '{BLACK}██{WHITE}██{MAGENTA}', '{x}'*16, '{BLACK}██{WHITE}', '{x}'*22, '{BLACK}██{BRIGHT_BLUE}', '{x}'*4], ['{BRIGHT_GREEN}', '{x}'*18, '{BRIGHT_YELLOW}██{BLACK}', '{x}'*2, '{WHITE}██{BLACK}', '{x}'*8, '{WHITE}██{MAGENTA}', '{x}'*14, '{BLACK}██{WHITE}', '{x}'*26, '{BLACK}██{BRIGHT_BLUE}██'], ['{BRIGHT_GREEN}', '{x}'*22, '{WHITE}', '{x}'*8, '{BLACK}██{WHITE}██{MAGENTA}', '{x}'*14, '{BLACK}██{WHITE}', '{x}'*6, '{BRIGHT_YELLOW}██{WHITE}', '{x}'*10, '{BRIGHT_YELLOW}██{BLACK}██{WHITE}', '{x}'*4, '{BLACK}██{BRIGHT_BLUE}██'], ['{BRIGHT_GREEN}', '{x}'*22, '{BLACK}', '{x}'*4, '{WHITE}', '{x}'*4, '{BLACK}██{WHITE}██{MAGENTA}', '{x}'*14, '{BLACK}██{WHITE}', '{x}'*6, '{BLACK}██{WHITE}', '{x}'*6, '{BLACK}██{WHITE}██{BLACK}', '{x}'*4, '{WHITE}', '{x}'*4, '{BLACK}██{BRIGHT_BLUE}██'], ['{BLUE}', '{x}'*18, '{BRIGHT_GREEN}', '{x}'*8, '{BLACK}', '{x}'*6, '{WHITE}██{MAGENTA}', '{x}'*14, '{BLACK}██{WHITE}██{MAGENTA}', '{x}'*4, '{WHITE}', '{x}'*16, '{MAGENTA}', '{x}'*4, '{BLACK}██{BRIGHT_BLUE}██'], ['{BLUE}', '{x}'*30, '{BLACK}██{WHITE}', '{x}'*4, '{MAGENTA}', '{x}'*14, '{BLACK}██{WHITE}', '{x}'*6, '{BLACK}', '{x}'*12, '{WHITE}', '{x}'*4, '{BLACK}██{BRIGHT_BLUE}', '{x}'*4], ['{BRIGHT_BLUE}', '{x}'*18, '{BLUE}', '{x}'*4, '{BLUE}', '{x}'*6, '{BLACK}', '{x}'*4, '{WHITE}', '{x}'*6, '{MAGENTA}', '{x}'*14, '{BLACK}██{WHITE}', '{x}'*18, '{BLACK}██{BRIGHT_BLUE}', '{x}'*6], ['{BRIGHT_BLUE}', '{x}'*26, '{BLACK}██{WHITE}██{BLACK}', '{x}'*4, '{WHITE}', '{x}'*20, '{BLACK}', '{x}'*18, '{BRIGHT_BLUE}', '{x}'*8], ['{BRIGHT_BLUE}', '{x}'*24, '{BLACK}██{WHITE}', '{x}'*6, '{BLACK}', '{x}'*32, '{WHITE}██{BLACK}██{BRIGHT_BLUE}', '{x}'*12], ['{BRIGHT_BLUE}', '{x}'*24, '{BLACK}██{WHITE}', '{x}'*4, '{BLACK}██{BRIGHT_BLUE}██{BLACK}██{WHITE}', '{x}'*4, '{BRIGHT_BLUE}', '{x}'*12, '{BLACK}██{WHITE}', '{x}'*4, '{BLACK}', '{x}'*4, '{WHITE}', '{x}'*4, '{BLACK}██{BRIGHT_BLUE}', '{x}'*12], ['{BRIGHT_BLUE}', '{x}'*24, '{BLACK}', '{x}'*6, '{BRIGHT_BLUE}', '{x}'*4, '{BLACK}', '{x}'*6, '{BRIGHT_BLUE}', '{x}'*12, '{BLACK}', '{x}'*6, '{BRIGHT_BLUE}', '{x}'*4, '{BLACK}', '{x}'*6, '{BRIGHT_BLUE}', '{x}'*12], ['{x}'*80, '{WHITE}'] ] cattern = "\n".join(["".join(c) for c in cattern]) return cattern.format(BLACK=Style.NORMAL + "" + Fore.BLACK, BLUE=Style.NORMAL + "" + Fore.BLUE, BRIGHT_BLUE=Style.BRIGHT + "" + Fore.BLUE, BRIGHT_GREEN=Style.BRIGHT + "" + Fore.GREEN, BRIGHT_RED=Style.BRIGHT + "" + Fore.RED, BRIGHT_YELLOW=Style.BRIGHT + "" + Fore.YELLOW, MAGENTA=Style.NORMAL + "" + Fore.MAGENTA, RED=Style.NORMAL + "" + Fore.RED, WHITE=Style.BRIGHT + "" + Fore.WHITE, x='█')
PHP
UTF-8
5,507
2.703125
3
[ "MIT" ]
permissive
<?php namespace App\Models; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Database\Eloquent\Model; use Laravel\Scout\Searchable; use App\Traits\Orderable; use Storage; //there are a more effective way to stream videos from a content delivery network, AWS has something called cloudfront which would be a more suitable place to load videos form class Video extends Model { use SoftDeletes, Searchable, Orderable; //A trait protected $fillable = [ 'title', 'description', 'uid', 'video_filename', 'video_id', 'processed', 'visibility', 'allow_votes', 'allow_comments', 'processed_percentage', ]; public function toSearchableArray() //adding a property to the angola version of the videos table { $properties = $this->toArray(); $properties['visible'] = $this->isProcessed() && $this->isPublic(); //now public will ether be true or false, so that we can find the public vides with scout/angola //Angolas copy of the videos table will now say visibility = true for public videos! return $properties; } //RELATIONSHIPS public function channel() { return $this->belongsTo(Channel::class); } public function views() { return $this->hasMany(VideoView::class); } public function votes() { return $this->morphMany(Vote::class, 'votable'); } public function comments() { return $this->morphMany(Comment::class, 'commentable')->whereNull('reply_id'); } public function getRouteKeyName() { return 'uid'; } /* THIS IS NOW IN THE ORDERABLE TRAIT public function scopeLatestFirst($query) { return $query->orderBy('created_at', 'desc'); //order by created as in descendig order (see it in action in the VideoController) } */ public function isProcessed() { return $this->processed; } public function processedPercentage() { return $this->processed_percentage; } //when telestream works public function getThumbnail() { if (!$this->isProcessed()) { //remember to make default thumbnail public in s3 return config('codetube.buckets.videos') . '/default.png'; } return config('codetube.buckets.videos') . '/' . $this->video_id . '_1.jpg'; } public function votesAllowed() { return (bool) $this->allow_votes; } public function commentsAllowed() { return (bool) $this->allow_comments; } public function isPrivate() { return $this->visibility === 'private'; } public function isPublic() { return $this->visibility === 'public'; } public function ownedByUser(User $user) { return $this->channel->user->id === $user->id; //need to know about eloqunt } public function canBeAccessed($user = null) { if (!$user && $this->isPrivate()) { return false; } //if you are visiting a video page (you are not the owner) and the vidoe is private if($user && $this->isPrivate() && ($user->id !== $this->channel->user_id)) { return false; } return true; //now we know the user ownes the video and he is signed in (we are using the Auth facade to get the user model/object) } public function getStreamUrl() { return config('codetube.buckets.videos') . '/' . $this->video_id . '.mp4'; } public function viewCount() { return $this->views()->count(); //is this working because of the relation ship defined in the views() method obove? } //if you need to count votes other places in your application, these functions should be extracted into a trait public function upVotes() { return $this->votes->where('type', 'up'); } public function downVotes() { return $this->votes->where('type', 'down'); } public function voteFromUser(User $user) { //->votes() are refering to the relationship (it's called a relationship method) between the Vote and Video model to query the database each time we call this method //We could instead take advantage of eager loading (->votes), where laravel will fetch all reults into a collection, which will be used to get data on sebsequent calls, instead of the database being queried all the time. Also the collection can be outputed as json, which I had problems doing the other way ?? return $this->votes()->where('user_id', $user->id); //returnes all the users votes on the video (There should only be one) } //when telestream does not work public function getListedVideoThumbnail() { if(Storage::disk('s3videos')->has($this->video_id . '_thumbnail.jpg')) { return config('codetube.buckets.videos') . '/' . $this->video_id . '_thumbnail.jpg'; } return config('codetube.buckets.videos') . '/' . 'default_video_thumbnail' . '.png'; } //public and processed video scopes (where clauses added to the query) public function scopeProcessed($query) { return $query->where('processed', true); } public function scopePublic($query) { return $query->where('visibility', 'public'); } public function scopeVisible($query) { return $query->processed()->public(); } }
SQL
UTF-8
1,765
3.5625
4
[]
no_license
CREATE TABLE WORLD( WORLD_ID INT PRIMARY KEY NOT NULL, STATUS VARCHAR(10) NOT NULL ); CREATE TABLE INSEQNUM( ID BIGINT PRIMARY KEY NOT NULL, WORLD_ID INT NOT NULL REFERENCES WORLD(WORLD_ID), PRIMARY KEY(ID, WORLD_ID) ); CREATE TABLE OUTSEQNUM( ID BIGSERIAL NOT NULL, TYPE INT, TRUCK_ID INT, WH_ID INT, PACKAGE_ID INT, PACKAGE_X INT, PACKAGE_Y INT, WORLD_ID INT NOT NULL REFERENCES WORLD(WORLD_ID), TIME INT NOT NULL, PRIMARY KEY(ID, WORLD_ID) ); CREATE TABLE AINSEQNUM( ID BIGINT PRIMARY KEY NOT NULL ); CREATE TABLE AOUTSEQNUM( ID BIGSERIAL PRIMARY KEY NOT NULL, MSG VARCHAR(65535), TIME INT NOT NULL ); CREATE TABLE TRUCK( TRUCK_ID INT NOT NULL, X INT NOT NULL, Y INT NOT NULL, WORLD_ID INT NOT NULL REFERENCES WORLD(WORLD_ID), TRUCK_STATUS VARCHAR(50) NOT NULL DEFAULT 'IDLE', PRIMARY KEY(TRUCK_ID, WORLD_ID) ); CREATE TABLE PACKAGE( PACKAGE_ID BIGINT NOT NULL, WORLD_ID INT NOT NULL REFERENCES WORLD(WORLD_ID), TRUCK_ID INT REFERENCES TRUCK(TRUCK_ID), USER_ID INT NULL REFERENCES UPS_PROFILE("user_id"), PACKAGE_STATUS VARCHAR(20) NOT NULL DEFAULT 'CREATED', DEP_X INT, DEP_Y INT, DES_X INT NOT NULL, DES_Y INT NOT NULL, DESCP TEXT, COUNT INT, PRIMARY KEY(PACKAGE_ID, WORLD_ID) ); CREATE TABLE USERPACKAGE( USER_ID INT NOT NULL REFERENCES UPS_PROFILE("user_id"), PACKAGE_ID BIGINT NOT NULL ); CREATE TABLE PRODUCT( PRODUCT_ID BIGINT NOT NULL, PACKAGE_ID BIGINT NOT NULL REFERENCES PACKAGE(PACKAGE_ID), WORLD_ID INT NOT NULL REFERENCES WORLD(WORLD_ID), DESCRIPTION VARCHAR(100) NOT NULL, COUNT INT NOT NULL, PRIMARY KEY(PACKAGE_ID, WORLD_ID, PRODUCT_ID) ); CREATE TABLE SHIPMENT( SHIP_ID BIGINT NOT NULL, PACKAGE_ID BIGINT NOT NULL REFERENCES PACKAGE(PACKAGE_ID), WORLD_ID INT NOT NULL REFERENCES WORLD(WORLD_ID), PRIMARY KEY(SHIP_ID, WORLD_ID) );
Markdown
UTF-8
1,974
3.015625
3
[]
no_license
# CodePath Pre-work - *Simple ToDo* **Simple Todo** is an android app that allows building a todo list and basic todo items management functionality including adding new items, editing and deleting an existing item. Submitted by: Aishwarya Pothula Time spent: 10-12 hours spent in total ##User Stories The following **required** functionality is completed: * [ ] User can **successfully add ** from the todo list * [ ] User can **remove items ** from the todo list by long-clicking on the item * [ ] User can **persist todo items** and retrieve them properly on app restart ## Working Log Here's my [ working log ]( https://docs.google.com/document/d/1xoBIiz3JlWGRPyfQ9M7uWgfHPHodwiYug36crah_AGg/edit?usp=sharing ) while implementing the app ## Next iterations In the next iterations of the app, I will be implementing the following features * [ ] Edit the text of an item added to the list * [ ] Option to add reminders for the items * [ ] Add deadlines and display time remaining till the deadline * [ ] Option to add priority labels ## Video Walkthrough Here's a walkthrough of implemented user stories * [ ] Add and Delete item ![](Images/SimpleToDo_AddDelete.gif) * [ ] Persistence of list ![](Images/SimpleToDo_Persistence.gif) GIF created with Ezgif.com ## Notes * I was working with a different version (4.0.1) of Android Studio than the one being used in the tutorial * I used "import org.apache.commons.io.FileUtils;" in place of "import android.os.FileUtils;" in MainActivity.java to get the readLines to work * Had a problem with the Edit Text not being enabled after implementing the recycler view * After a lot of time, I realized that this was a layout problem; the recycler view is on top of the edit text * To resolve the issue, I set the layout_above attribute of the recycler to id/etItem * Due to the version differences, I had to implement the following methods instead of just the 'onItemLongClicked' ![](Images/OnLongClickListener.png)
JavaScript
UTF-8
1,913
3
3
[ "MIT" ]
permissive
import React, { PropTypes } from 'react' import { addIndex, contains, flatten, isEmpty, map } from 'ramda' // Let's move our game utility functions out to another file to keep // the board file clean and focused on react import { getBoard, getWins } from '../utilities/game' import Square from './square.jsx' // Ramda's map does not include the index, so we'll use addIndex to make our own const mapIndexed = addIndex(map) // We use a simple function for our board that returns JSX. // The first argument is the props object, and we destructure it to get // specific props. Nice trick, eh? const Board = ({ moves, clickCb }) => { const board = getBoard(moves) // Convert the moves to a board array const wins = flatten(getWins(board)) // Get a list of winning cells const inPlay = isEmpty(wins) // No winning cells? Still in play then const css = inPlay ? 'board' : 'board won' // Mark a winning board (grays out squares) // Get an array of Squares by looping through the board array // and mapping it to Square components const squares = mapIndexed((player, square) => { if (inPlay) { // If played, pass the player. // Else, set the callback and *bind the square number*. // The callback is a closure! return player ? <Square key={square} player={player}/> : <Square key={square} clickCb={() => clickCb(square)}/> } else { // Else, mark winning and non-winning squares (for colors) return <Square key={square} player={player} win={contains(square, wins)} /> } }, board) // Wrap our array of Square components in a <div> and return it. // Note: we can only return ONE root element, so we must wrap the array. return <div className={css}>{squares}</div> } // Can still set prop types Board.propTypes = { clickCb: PropTypes.func.isRequired } export default Board
Markdown
UTF-8
353
3.046875
3
[]
permissive
> The correct answer is _r=202.0!_. > The first thing that is executed is the multiplication as it is enclosed by braces: _5 * 4_ gives _20_. > As there are no other braces, execution proceeds now from the left to the right. > First thing we see is a String, _r=_ => thus all further _+_ are interpreted as String concatenation! > (**Lesson 3**)
PHP
UTF-8
337
2.625
3
[]
no_license
<?php class SessionListener extends RequestListener{ public function run() { $options = new SessionSecurityOptions(); $options->setExpiredTime(time() + 3600 * 24 * 1); // 1 day $session = $this->request->getSession(); if(!$session->isStarted()) { $session->start(); } } }
C#
UTF-8
1,122
2.59375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Modelo; using System.Data.SqlClient; using System.Linq.Expressions; namespace Controller { public class ControllerAutenticacion { private PaslumBaseDatoDataContext contexto = new PaslumBaseDatoDataContext(); public TblUser ValidarLogin(TblUser _user) { TblUser respuesta = null; Expression<Func<TblUser, bool>> predicado = p => p.strusuario == _user.strusuario && p.strpass == _user.strpass; try { TblUser user = contexto.TblUser.Where(predicado).FirstOrDefault<TblUser>(); if (user != null) { if (user.id > 0) { respuesta = user; } } } catch (Exception ex) { Console.WriteLine("Usuario o contraseña incorrecto", ex); respuesta = null; } return respuesta; } } }
JavaScript
UTF-8
2,467
4.125
4
[]
no_license
//object literal // [] array //{} const person={ name:"Colin", age:30, student:true, birthday:function(){ return new Date().getFullYear()-this.age; } } console.log(person.birthday()); //object constructor class Task{ constructor(name,priority){ this.name=name; this.priority=priority; } } const task1 = new Task("HW","High"); const task2 = new Task("Play Zelda","High"); const task3 = new Task("Running","Medium"); console.log(task1); console.log(task2); console.log(task3); const client = { name:"Alex", type:"Premium", data:{ address:{ city:"TJ", country:"Mexico" }, account:{ user:"alex@gmail.com", password:"123Alex" } }, hobbies:{ music:['rock','trance','Electronic','hip hop'] } } console.log(client.data.account.user); // old way to use it const userName=client.data.account.user; const userType=client.type; console.log(userName); console.log(userType); // object destructuring let {name,type}= client; console.log(name,type); let {data:{address:{city,country}}}=client; console.log(city,country); //destructuting the account let {data:{account:{user,password}}}=client; console.log(user,password); let {hobbies:{music}}=client; console.log(music[2]); const band="Metallica", genre="Heavy Metal",song="Enter the Sandman"; const Metallica={band,genre,song}; console.log(Metallica); const students= [ {name:"John",age:30}, {name:"Paul",age:26}, {name:"Andrew",age:34}, {name:"Andrea",age:39}, {name:"Trevor",age:21}, {name:"Juliet",age:19} ]; console.log(students); // get age greater than 25 years const olders = students.filter(s=>s.age>25); console.log(olders); // find Andrea const Andrea = students.find(s=>s.name==='Andrea'); console.log(Andrea); // age's average let total = students.reduce((totalAge,s)=>{ return totalAge+s.age; },0); console.log(total/students.length); var lion = { name:"Simba", foodType:"carnivore", kingOfTheJungle:true } var monkey = { name:"Rafiki", foodType:"carnivore", kingOfTheJungle:false } console.log(lion); // object constructor class Animal{ constructor(name,foodType,kingOfTheJungle) { this.name=name; this.foodType=foodType; this.kingOfTheJungle=kingOfTheJungle; } } var lionC = new Animal("Simba","CArnivore",true); var monkeyC=new Animal("Rafiki","Carnivore",false);
Ruby
UTF-8
395
3.515625
4
[]
no_license
# Tags Count Instances Complex Homework Lookup Help # http://carol-nichols.com/2015/08/07/ruby-occurrence-couting/ # many ways to skin this cat My solution def count(array) array.uniq.map { |x| [x, array.count(x)] }.to_h end other solutions def count(array) c = Hash.new(0) array.each { |i| c[i] += 1 } c end def count(array) array.reduce(Hash.new(0)) { |a, b| a[b] += 1; a } end
Java
UTF-8
387
1.835938
2
[]
no_license
package com.heaptrip.web.model.profile; public class CommunityInfoModel extends AccountInfoModel { private CommunityProfileModel communityProfile; public CommunityProfileModel getCommunityProfile() { return communityProfile; } public void setCommunityProfile(CommunityProfileModel communityProfile) { this.communityProfile = communityProfile; } }
JavaScript
UTF-8
512
2.765625
3
[ "CC-BY-4.0" ]
permissive
var side = document.getElementById("side"); var license = document.getElementById("license"); var open = document.getElementById("open-side"); function closeMenu() { open.innerHTML = ">"; license.style.display = "none"; side.style.width = "0%"; } open.addEventListener("click", function(e) { e.preventDefault(); if (side.style.width === "0%" || side.style.width === "") { open.innerHTML = "<"; license.style.display = "block"; side.style.width = "60%"; } else { closeMenu(); } });