language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Markdown
UTF-8
35
2.546875
3
[]
no_license
# Aidan-Moore-ICS3U-Unit1-04-Python
Markdown
UTF-8
550
2.859375
3
[ "Unlicense" ]
permissive
# bbrot **bbrot** is a CLI [Buddhabrot](https://en.wikipedia.org/wiki/Buddhabrot) renderer. It's currently very basic; it has minimal options and only supports rendering to a png file. ### Sample output ![sample output](sample.png) That took about 10 seconds to render. ### Usage To build the executable, run the following command in this directory using Rust nightly ``` cargo build --release ``` The executable can then be found inside `target/release`. You can then run the executable with the `-h` flag for information on how to run it.
Python
UTF-8
1,353
2.8125
3
[]
no_license
#!/usr/bin/python # coding: utf-8 import sys import subprocess from pprint import pprint COMMANDS = ['help', 'ping', 'whoami', 'areyoualive', 'listsocketclients'] class Command(): Name = ['ping', '-c', '15', '-w', '5', '8.8.8.8'] output = '' def __init__(self, socket): self.socket = socket def run(self): p = subprocess.Popen(self.Name, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) while (True): retcode = p.poll() line = p.stdout.readline() self.output += line self.socket.send(self.print_line(line)) if (retcode is not None): # self.output = '' break def print_line(self, str): return '%s\n' % str def getOutput(self): return self.output class RunCommand(): def __init__(self, cmd, con): self.command = globals()[cmd](con) self.command.run() class whoami(Command): Name = ['whoami'] class ping(Command): Name = ['ping', '-c', '20', '-w', '20', '8.8.8.8'] class help(Command): Name = ['help'] def run(self): for command in COMMANDS: self.socket.send(self.print_line(command)) class areyoualive(Command): Name = ['areyoualive'] def run(self): self.socket.send(self.print_line('yes, I am ;)'))
Ruby
UTF-8
1,338
2.8125
3
[]
no_license
require 'test_helper' class CartItemTest < ActiveSupport::TestCase test "cart item can calculate price" do cart =Cart.new p1= Product.create(name:'ruby', price:100) p2= Product.create(name:'php', price:50) 5.times do cart.add_item(p1.id) end 3.times do cart.add_item(p2.id) end assert_equal 500, cart.items.first.price assert_equal 150, cart.items.second.price end test "cart can serialize to hash" do cart = Cart.new cart.add_item(1) cart.add_item(1) cart.add_item(2) cart.add_item(2) cart.add_item(2) assert_equal session_hash, cart.serialize end test "can build a cart from hash" do cart = Cart.build_from_hash(session_hash) assert_equal 1, cart.items.first.item_id assert_equal 2, cart.items.first.quantity assert_equal 2, cart.items.second.item_id assert_equal 3, cart.items.second.quantity end private def session_hash { "cart" => [ {"item_id" => 1, "quantity" => 2}, {"item_id" => 2, "quantity" => 3}, ] } end end #p1 = Product.create(name:'ruby',price:100) # p2 = Product.create(name:'php',price:100) # # 2.times do # cart.add_item(p1.id) # end # 3.times do # cart.add_item(p2.id) # end
C
UTF-8
870
3.046875
3
[]
no_license
#include <stdio.h> int main() { int k,n,m; scanf("%d %d %d",&k,&n,&m); int min = k; int best = 0; int adj[20][30]; int i,j,A,v; for(i=0; i<20; i++) for(j=0; j<30; j++) adj[i][j]=0; for(i=0; i<m; i++) { int start,end,cat; scanf("%d %d %d",&start,&end,&cat); adj[cat][start] |= (1<<end); adj[cat][end] |= (1<<start); } int lim = 2<<k; for(A=0; A<lim; A++) { int E[30]; for(i=0;i<30; i++) E[i]=0; int count=0; for(i=0; i<k; i++) { if( ((A>>i)&1)==0 ) continue; count++; for(j=0; j<n; j++) E[j] |= adj[i][j]; } int visited = 1; for(i=0; i<n; i++) { for(v=0; v<n; v++) { if( ((visited>>v)&1) ) visited |= E[v]; } } if( ((visited>>1)&1) == 1 && count<min) { min = count; best = A; } } printf("%d\n",min); for(i=0; i<k; i++) if( ((best>>i)&1)==1 ) printf("%d ",i); printf("\n"); }
Ruby
UTF-8
343
3.09375
3
[]
no_license
N = gets.to_i h = gets.split().map(&:to_i) inf = 1000000000 dp = [] 1000000.times do dp.push(inf) end dp[0] = 0 def chmin(a, b) if a > b return b end return a end (1..N-1).each do |i| dp[i] = chmin(dp[i], (h[i-1]-h[i]).abs + dp[i-1]) if i > 1 dp[i] = chmin(dp[i], (h[i-2]-h[i]).abs + dp[i-2]) end end puts dp[N-1]
Python
UTF-8
394
3.6875
4
[]
no_license
# coding: utf8 # 用一个栈实现另一个栈的排序 def sortStackByStack(stack): Help = [] while len(stack) > 0: cur = stack.pop() while len(Help) > 0 and Help[-1] < cur: stack.append(Help.pop()) Help.append(cur) while len(Help) > 0: stack.append(Help.pop()) return stack # # a = [2,7,4,8,3,7] # b = sortStackByStack(a) # print b
Java
UTF-8
846
2.453125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package app.domain.model; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; /** * * @author Gon�alo */ public class EmailNotification { public EmailNotification(){ //this is a constructor empty for this class } public static void sendEmailToClient(String message) throws IOException { File file = new File("emailAndSMSMessages.txt"); FileWriter arq = new FileWriter(file); PrintWriter gravarArq = new PrintWriter(arq); gravarArq.printf(message); gravarArq.close(); arq.close(); } }
Java
UTF-8
1,446
3.015625
3
[]
no_license
package com.nacorpio.nutilities.collection.natural; public class Leaf implements ILeaf { private String name; private IParental parent; private Object data; /** * Creates a new leaf. * @param par1 the name. * @param par2 the parent. * @param par3 the data. */ public Leaf(String par1, IParental par2, Object par3) { this.name = par1; this.parent = par2; this.data = par3; } /** * Creates a new leaf. * @param par1 the name. * @param par2 the parent. */ public Leaf(String par1, IParental par2) { this(par1, par2, null); } @Override public String getName() { return name; } @Override public String getId() { if (parent instanceof IRoot && parent instanceof NaturalTree) { return getIndex() + ":" + 0; } else if (parent instanceof IBranch) { return getIndex() + ":" + ((IBranch) parent).getId(); } return null; } @Override public int getIndex() { return 0; } @Override public IParental getParent() { return parent; } @Override public Object getData() { return data; } public final boolean equals(Object par1) { if (par1.equals(null)) { return false; } if (par1 instanceof ILeaf) { Leaf var1 = (Leaf) par1; return name.equals(var1.getName()) && parent.equals(var1.parent) && data.equals(var1.data); } return par1.equals(this); } public final Leaf clone() { return new Leaf(name, parent, data); } }
C++
UTF-8
2,914
2.65625
3
[]
no_license
// // Poll.cpp // marstcp // // Created by meryn on 2017/08/02. // Copyright © 2017 marsladder. All rights reserved. // #include "KQueuePoll.h" #include <sys/socket.h> #include "log/Log.h" #include "Channel.h" net::KQueuePoll::KQueuePoll(){ this->pollFd = kqueue(); } int net::KQueuePoll::AddChannel(std::shared_ptr<Channel>& chan){ if(this->channels.find(chan->GetFd()) != this->channels.end()){ ErrorLog << "fd is already in poll" << chan->GetFd(); return -1; } this->UpdateEvent(chan); this->channels[chan->GetFd()] = chan; return 0; } int net::KQueuePoll::UpdateEvent(std::shared_ptr<Channel>& chan){ bool is_modify = false; struct kevent ev[2]; int n = 0; int fd = chan->GetFd(); int event = chan->GetEvent(); int old_event = chan->GetOldEvent(); if(this->channels.find(fd) != this->channels.end()){ is_modify = true; } if(event & kReadEvent){ EV_SET(&ev[n++], fd, EVFILT_READ, EV_ADD|EV_ENABLE, 0, 0, (void*)(intptr_t)fd); }else if(is_modify && (old_event & kReadEvent)){ EV_SET(&ev[n++], fd, EVFILT_READ, EV_DELETE, 0, 0, (void*)(intptr_t)fd); } if(event & kWriteEvent){ EV_SET(&ev[n++], fd, EVFILT_WRITE, EV_ADD|EV_ENABLE, 0, 0, (void*)(intptr_t)fd); }else if(is_modify && (old_event & kWriteEvent)){ EV_SET(&ev[n++], fd, EVFILT_WRITE, EV_DELETE, 0, 0, (void*)(intptr_t)fd); } chan->SetOldEvent(event); int ret = kevent(this->pollFd, ev, n, NULL, 0, NULL); if(ret < 0){ FatalLog << std::strerror(errno) << "| update poll failed"; return -1; } return 0; } int net::KQueuePoll::Poll(int waitms){ struct timespec timeout; timeout.tv_sec = waitms / 1000; timeout.tv_nsec = (waitms % 1000) * 1e6; int n = kevent(this->pollFd, NULL, 0, this->ev, common::MAX_POLL_WAIT_EVENTS_NUM, &timeout); //InfoLog <<"has event num:"<<n; for(int ii = 0; ii < n; ii ++){ int fd = (int)(intptr_t)this->ev[ii].udata; int events = this->ev[ii].filter; auto iter = this->channels.find(fd); if(iter == this->channels.end()){ FatalLog << "chan is not exist"; continue; } if(events == EVFILT_READ){ iter->second->GetReadCallback()(iter->second); }else if (events == EVFILT_WRITE){ iter->second->GetWriteCallback()(iter->second); }else{ FatalLog << "unkown kqueue event, fd:"<<fd << " events:" <<events; } } return n; } int net::KQueuePoll::DelChannel(std::shared_ptr<Channel>& chan){ chan->ResetEvent(); UpdateEvent(chan); this->channels.erase(chan->GetFd()); return 0; }
Java
UTF-8
1,766
2.40625
2
[]
no_license
package fr.keuse.rightsalert.adapter; import java.util.ArrayList; import fr.keuse.rightsalert.entity.ApplicationEntity; import android.content.Context; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; public class ApplistAdapter extends BaseAdapter { private Context context; private ArrayList<ApplicationEntity> applications; public ApplistAdapter(Context context, ArrayList<ApplicationEntity> applications) { this.context = context; this.applications = applications; } public int getCount() { return applications.size(); } public ApplicationEntity getItem(int location) { return applications.get(location); } public long getItemId(int location) { return location; } public View getView(int location, View convertView, ViewGroup parent) { ApplicationEntity application = getItem(location); ImageView icon = new ImageView(context); TextView name = new TextView(context); TextView score = new TextView(context); LinearLayout view = new LinearLayout(context); icon.setImageDrawable(application.getIcon()); icon.setAdjustViewBounds(true); icon.setMaxHeight(40); icon.setMaxWidth(40); name.setText(application.getName()); score.setText(String.valueOf(application.getScore())); score.setGravity(Gravity.RIGHT); view.setOrientation(LinearLayout.HORIZONTAL); view.addView(icon); view.addView(name); view.addView(score, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); return view; } }
PHP
UTF-8
849
2.515625
3
[]
no_license
<!DOCTYPE html> <html> <head> <title>Menu Colaborador</title> </head> <body> <?php session_start(); $dbconn = pg_connect("host=localhost port=5432 dbname=bd user=postgres password=tarea") or die('<h1>No se ha podido conectar: </h1>' . pg_last_error()); $sql = 'SELECT "nombre" FROM "Alumno" WHERE "id_alumno"=\''.$_SESSION["id_alumno"].'\''; $result = pg_query($sql); $row = pg_fetch_array($result); echo "<h2>Bienvenido Colaborador ".$row[0]."</h2>"; pg_free_result($result); pg_close($dbconn); ?> <a href = "misdatos.php"><input type="submit" value="Ver mis datos"></a> <a href = "prevernoti.php"><input type="submit" value="Ver Noticias"></a> <a href = "index.php"><input type="submit" value="Salir"></a> </body> </html>
Markdown
UTF-8
1,205
3.171875
3
[ "MIT" ]
permissive
# typewriter.js typewriter.js is a Javascript module for emulating a type writer affect. [![Remix on Glitch](https://cdn.glitch.com/2703baf2-b643-4da7-ab91-7ee2a2d00b5b%2Fremix-button.svg)](https://glitch.com/edit/#!/join/b2ab7cab-7c58-49fa-bc8c-efa05a51500c) ## Example See demo [Glitch](https://typewriter-js.glitch.me/examples/index.html) or check [examples/](examples/index.html) ## Usage ```js // import module import { typeText, removeText } from "../js/typewriter.js"; ``` With animation ```js // define the target element let titleBlock = document.querySelector("#title-block"); // enable animated cursor titleBlock.classList.add("animated-cursor"); // begin typing typeText(titleBlock, "Hello World").then(() => { // remove text removeText(titleBlock, "World".length).then(() => { // disable animated cursor titleBlock.classList.remove("animated-cursor"); }); }); ``` Without animation ```js // define the target element let titleBlock = document.querySelector("#title-block"); // begin typing typeText(titleBlock, "Hello World").then(() => { // remove text removeText(titleBlock, "World".length); }); ``` ## License [MIT](https://choosealicense.com/licenses/mit/)
C
UTF-8
12,054
2.734375
3
[ "LicenseRef-scancode-public-domain", "BSD-2-Clause", "BSD-3-Clause" ]
permissive
/* This file records outlaw ratings * I have to warn you, don't try to understand it. * All other comments are meant for me, so my head doesn't explode.. * /Scarblac */ mapping ratings = ([ ]); /* ratings consists of: "name" : ({ rating, ... }) if rating = 0 (no rating yet) the '...' part is name1,evaldiff1,result, etc for logging to opponents he has had, evaldiff and kill(result 1) or death(result 0). if there IS a rating, the '...' part is kills, deaths, amount of events, date of last event, average rating of opponents */ string *namelist; string update_time; string update_name; #define SAVE "obj/o/ratings" #define RATING(x) (ratings[(x)]?ratings[(x)][0]:0) #define EVAL_RATING 30 /* Eval influence on pk rating */ #define FACTOR 75 /* Speed */ #define STD_RATING 2000 /* What people are supposed to start with */ #include <tune.h> query_rating(player) { return RATING(player); } query_rating_info(player) { return ratings[player]; } reset(whee) { if (!whee) restore_object(SAVE); } /* Call this to log a pk of name1 killing name2, evaldiff = eval of name1 - eval of name2. */ log_pk(name1,name2,evaldiff) { object ob; int q,i; int score,avg,ravg; if (find_player(name1)->query_test_char() || find_player(name2)->query_test_char()) return; if (!ratings[name1]) ratings[name1] = ({ 0 }); if (!ratings[name2]) ratings[name2] = ({ 0 }); if (!RATING(name1)) ratings[name1] += ({ name2, evaldiff, 1 }); else if (RATING(name2)) { i = RATING(name1); record_rating(name1,RATING(name2),evaldiff,1); record_rating(name2,i,-evaldiff,0); if (ob = find_player(name1)) tell_object(ob,"Your new pk rating is "+ratings[name1][0]+"!\n"); if (ob = find_player(name2)) tell_object(ob,"Your new pk rating is "+ratings[name2][0]+"!\n"); save_object(SAVE); return; } if (!RATING(name2)) ratings[name2] += ({ name1, -evaldiff, 0 }); /* Now, check if someone who didn't have a rating yet reached 3 events. */ if (!RATING(name1) && (sizeof(ratings[name1]) == 10)) { q = 1; /* Name1 is given rating now */ avg = 0; avg += (ratings[ratings[name1][1]][0] ? ratings[ratings[name1][1]][0] : STD_RATING) - EVAL_RATING*ratings[name1][2]; avg += (ratings[ratings[name1][4]][0] ? ratings[ratings[name1][4]][0] : STD_RATING) - EVAL_RATING*ratings[name1][5]; avg += (ratings[ratings[name1][7]][0] ? ratings[ratings[name1][7]][0] : STD_RATING) - EVAL_RATING*ratings[name1][8]; score = ratings[name1][3] + ratings[name1][6] + ratings[name1][9]; avg /= 3; ravg = avg; /* Average is now average rating of opponents */ switch (score) { case 0 : avg -= 300; break; case 1 : avg -= 100; break; case 2 : avg += 100; break; case 3 : avg += 300; break; } if (RATING(ratings[name1][1])) { record_rating(ratings[name1][1],avg,-ratings[name1][2],!ratings[name1][3]); if (ob = find_player(ratings[name1][1])) tell_object(ob,"Your pk rating is now "+ratings[ratings[name1][1]][0]+ ", because of "+(ratings[name1][3]?"your death to ":"your killing of ")+ capitalize(name1)+".\n"); } if (RATING(ratings[name1][4])) { record_rating(ratings[name1][4],avg,-ratings[name1][5],!ratings[name1][6]); if (ob = find_player(ratings[name1][4])) tell_object(ob,"Your pk rating is now "+ratings[ratings[name1][4]][0]+ ", because of "+(ratings[name1][6]?"your death to ":"your killing of ")+ capitalize(name1)+".\n"); } if (RATING(ratings[name1][7])) { record_rating(ratings[name1][7],avg,-ratings[name1][8],!ratings[name1][9]); if (ob = find_player(ratings[name1][7])) tell_object(ob,"Your pk rating is now "+ratings[ratings[name1][7]][0]+ ", because of "+(ratings[name1][9]?"your death to ":"your killing of ")+ capitalize(name1)+".\n"); } ratings[name1] = ({ avg, score, 3-score, 3, time(), ravg }); shout(capitalize(name1)+" now has an outlaw rating of "+avg+"!!\n"); } if (!RATING(name2) && (sizeof(ratings[name2]) == 10)) { avg = 0; avg += ((ratings[ratings[name2][1]][0] && !(q && ratings[name2][1] == name1)) ? ratings[ratings[name2][1]][0] : STD_RATING) - EVAL_RATING*ratings[name2][2]; avg += ((ratings[ratings[name2][4]][0] && !(q && ratings[name2][4] == name1)) ? ratings[ratings[name2][4]][0] : STD_RATING) - EVAL_RATING*ratings[name2][5]; avg += ((ratings[ratings[name2][7]][0] && !(q && ratings[name2][7] == name1)) ? ratings[ratings[name2][7]][0] : STD_RATING) - EVAL_RATING*ratings[name2][8]; score = ratings[name2][3] + ratings[name2][6] + ratings[name2][9]; avg /= 3; ravg = avg; /* Average is now average rating of opponents */ switch (score) { case 0 : avg -= 300; break; case 1 : avg -= 100; break; case 2 : avg += 100; break; case 3 : avg += 300; break; } if (RATING(ratings[name2][1]) && !(q && ratings[name2][1] == name1)) { record_rating(ratings[name2][1],avg,-ratings[name2][2],!ratings[name2][3]); if (ob = find_player(ratings[name2][1])) tell_object(ob,"Your pk rating is now "+ratings[ratings[name2][1]][0]+ ", because of "+(ratings[name2][3]?"your death to ":"your killing of ")+ capitalize(name2)+".\n"); } if (RATING(ratings[name2][4]) && !(q && ratings[name2][4] == name1)) { record_rating(ratings[name2][4],avg,-ratings[name2][5],!ratings[name2][6]); if (ob = find_player(ratings[name2][4])) tell_object(ob,"Your pk rating is now "+ratings[ratings[name2][4]][0]+ ", because of "+(ratings[name2][6]?"your death to ":"your killing of ")+ capitalize(name2)+".\n"); } if (RATING(ratings[name2][7]) && !(q && ratings[name2][7] == name1)) { record_rating(ratings[name2][7],avg,-ratings[name2][8],!ratings[name2][9]); if (ob = find_player(ratings[name2][7])) tell_object(ob,"Your pk rating is now "+ratings[ratings[name2][7]][0]+ ", because of "+(ratings[name2][9]?"your death to ":"your killing of ")+ capitalize(name2)+".\n"); } ratings[name2] = ({ avg, score, 3-score, 3, time(), ravg }); shout(capitalize(name2)+" now has an outlaw rating of "+avg+"!!\n"); } save_object(SAVE); } record_rating(player,opp_rating,evaldiff,result) { if (!ratings[player][0]) return; if (result) { ratings[player][0] += (get_probability(ratings[player][0],opp_rating- EVAL_RATING*evaldiff)*FACTOR)/100; ratings[player][1]++; } else { ratings[player][0] -= (get_probability(opp_rating-EVAL_RATING*evaldiff, ratings[player][0])*FACTOR)/100; ratings[player][2]++; } ratings[player][4] = time(); ratings[player][5] = (ratings[player][5]*ratings[player][3]+opp_rating- EVAL_RATING*evaldiff)/(++ratings[player][3]); } get_probability(rating1,rating2) { int i,j; i = (rating1-rating2); j = i >= 0; if (!j) i = -i; switch(i) { case 0..3 : return 50; case 4..10 : return j ? 49 : 51; case 11..17 : return j ? 48 : 52; case 18..25 : return j ? 47 : 53; case 26..32 : return j ? 46 : 54; case 33..39 : return j ? 45 : 55; case 40..46 : return j ? 44 : 56; case 47..53 : return j ? 43 : 57; case 54..61 : return j ? 42 : 58; case 62..68 : return j ? 41 : 59; case 69..76 : return j ? 40 : 60; case 77..83 : return j ? 39 : 61; case 84..91 : return j ? 38 : 62; case 92..98 : return j ? 37 : 63; case 99..106 : return j ? 36 : 64; case 107..113 : return j ? 35 : 65; case 114..121 : return j ? 34 : 66; case 122..129 : return j ? 33 : 67; case 130..137 : return j ? 32 : 68; case 138..145 : return j ? 31 : 69; case 146..153 : return j ? 30 : 70; case 154..162 : return j ? 29 : 71; case 163..170 : return j ? 28 : 72; case 171..179 : return j ? 27 : 73; case 180..188 : return j ? 26 : 74; case 189..197 : return j ? 25 : 75; case 198..206 : return j ? 24 : 76; case 207..215 : return j ? 23 : 77; case 216..225 : return j ? 22 : 78; case 226..235 : return j ? 21 : 79; case 236..245 : return j ? 20 : 80; case 246..256 : return j ? 19 : 81; case 257..267 : return j ? 18 : 82; case 268..278 : return j ? 17 : 83; case 279..290 : return j ? 16 : 84; case 291..302 : return j ? 15 : 85; case 303..315 : return j ? 14 : 86; case 316..328 : return j ? 13 : 87; case 329..341 : return j ? 12 : 88; case 342..357 : return j ? 11 : 89; case 358..374 : return j ? 10 : 90; case 375..391 : return j ? 9 : 91; case 392..411 : return j ? 8 : 92; case 412..432 : return j ? 7 : 93; case 433..456 : return j ? 6 : 94; case 457..481 : return j ? 5 : 95; case 482..517 : return j ? 4 : 96; case 518..559 : return j ? 3 : 97; case 560..619 : return j ? 2 : 98; case 920..735 : return j ? 1 : 99; default: return j ? 0 : 100; } } query_mapping() { return ratings; } write_mapping() { int i; string indices; write("The mapping:\n"); indices = m_indices(ratings); for (i=0; i < sizeof(indices); i++) printf("%15s %4d (%s)\n",indices[i],ratings[indices[i]][0], implode(ratings[indices[i]][1..sizeof(ratings[indices[i]])],",")); } update_toplist() { if (this_player()->query_exec() < SEC_EXEC) return write("Sorry, can't do.\n"); namelist = sort_array(filter_array(m_indices(ratings),"check_rating",this_object()), "on_rating",this_object()); update_time = ctime(time()); update_name = capitalize(this_player()->query_real_name()); save_object(SAVE); } check_rating(s) { if (!RATING(s)) return; if (file_size("/players/"+s+"/") == -2) return 0; if (file_size("/players/"+s+".o") == -1) return 0; return 1; } on_rating(a,b) { if (ratings[a][0] > ratings[b][0]) return -1; if (ratings[a][0] < ratings[b][0]) return 1; } show_list(s) { int n,i; if (sizeof(namelist) < 15) { for (i=0; i<sizeof(namelist); i++) printf("%2d. %-20s [%4d]\n",i+1, capitalize(namelist[i]),ratings[namelist[i]][0]); return; } if (s) if (sscanf(s,"%d",n)) n--; else n = member_array(s,namelist); if (n < 12) n = 12; if (n >= sizeof(namelist)-2) n = sizeof(namelist)-3; write("The PK rating toplist, last updated "+update_time+" by "+update_name+":\n"); for (i=0;i<10;i++) printf("%2d. %-20s [%4d]\n",i+1, capitalize(namelist[i]),ratings[namelist[i]][0]); for (i=n-2;i<n+3;i++) printf("%2d. %-20s [%4d]\n",i+1, capitalize(namelist[i]),ratings[namelist[i]][0]); } delete_rating(s) { if (this_player()->query_exec() < MIN_EXEC) return; ratings = m_delete(ratings,s); save_object(SAVE); }
C++
UTF-8
3,490
3.4375
3
[]
no_license
#include<iostream.h> #include<conio.h> #include<stdlib.h> #include<string.h> #include<fstream.h> class account { public : char name[20]; char type[15]; char branch[20]; float acc,amount; void add(); void show_all(); void search(); void edit(); }; fstream file; account obj; void account:: add() { cout<<"\n\n\t Enter Holder Name :"; cin>>name; cout<<"\n\t Enter Type of Account s or c :"; cin>>type; cout<<"\n\t Enter Branch :"; cin>>branch; cout<<"\n\t Enter Account number :"; cin>>acc; cout<<"\n\t Enter Initial Amount :"; cin>>amount; file.open("database.txt",ios::app) ; file.write((char*)&obj,sizeof(obj)); file.close(); } void account:: show_all() { file.open("database.txt",ios::in); file.read((char*)&obj,sizeof(obj)); while (file.eof()==0) { cout<<"\n--------------------------------------------------------"<<endl; cout<<"\t| Holder Name | "; cout<<" Type of Account |"; cout<<" Branch |" ; cout<<" Account Number |" ; cout<<"Balance|"<<endl; cout<<"----------------------------------------------------------"; cout<<"\n\t|"<<name<<"|"<<type<<"|"<<branch<<"|"<<acc<<"|"<<amount<<"|"<<endl; file.read((char*)&obj,sizeof(obj)); } file.close(); getch(); } void account::search() { float user; cout<<"\t Enter Account Number " ; cin>>user; file.open("database.txt",ios::in); file.read((char*)&obj,sizeof(obj)); while (file.eof()==0) { if (obj.acc==user) { cout<<"\t Holder Name : "<<name<<endl; cout<<"\t Type of Account :" <<type<<endl; cout<<"\t Branch " <<branch<<endl; cout<<"\t Account Number :" <<acc<<endl<<endl; cout<<"\tBalance :"<<amount<<endl; } file.read((char*)&obj,sizeof(obj)); } file.close(); getch(); } void account::edit() { float user; cout<<"\n\tEnter Account Number :"; cin>>user; file.open("database.txt",ios::in||ios::out); file.read((char*)&obj,sizeof(obj)); while (file.eof()==0) { if(obj.acc==user) { cout<<"\t Holder Name : "<<name<<endl; cout<<"\t Type of Account :" <<type<<endl; cout<<"\t Branch " <<branch<<endl; cout<<"\t Account Number :" <<acc<<endl<<endl; cout<<"\tBalance :"<<amount<<endl; cout<<"\nEnter New Name :"; cin>>name; file.seekp(file.tellg()-sizeof(obj)); file.write((char*)&obj,sizeof(obj)); cout<<"\n\n File Updated" ; break; } file.read((char*)&obj,sizeof(obj)); } file.close(); getch(); } void main() { int option; while (1) { cout<<"\n=================================="; cout<<"\n\t\t\tBank Management system"; cout<<"\n================================="; cout<<"\n\n\t1] New Account\n"; cout<<"\n\t2] Show all account\n"; cout<<"\n\t3] Search all account \n"; cout<<"\n\t4] Modify Account\n"; cout<<"\n\t5] Exit \n"; cout<<"\n\n\t Enter Option :"; cin>>option; switch (option) { case 1: cout<<"\n\t===========New Account========= "; obj.add(); cout<<"\n\n\t Recored enterd\n"; getch(); break; case 2: cout<<"\n\t===========All Account========= "; obj.show_all(); getch(); break; case 3: cout<<"\n\t===========New Account========= "; obj.search(); getch(); break; case 4: cout<<"\n\t===========New Account========= "; obj.edit(); getch(); break; case 5: exit(0); break; default: cout<<"\n\tINvalid keuy option"; } } getch(); }
Python
UTF-8
2,991
2.84375
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Fri Feb 5 17:56:44 2016 @author: Huang Hongye <[email protected]> This is a simulation program for acoustic signal tracking. Reference: [1] Zhong, X., Prekumar, A. B., and Madhukumar, A. S., "Particle filtering for acoustic source tracking in impulsive noise with alpha-stable process", IEEE Sensors Journal, Feb. 2013, Vol. 13 No. 2: 589-600. """ import time import numpy as np from numpy import pi import matplotlib.pyplot as plt from capon import doaSolver_Capon from pf import doaSolver_PF from salphas import salphas_cplx # Arguments sampling_rate = 44100 # Sampling rate total_time = 0.5 # Total time M = 3 # Number of array elements N = 90 # Number of samples in a time slice bf_resolution = 90 # Number of sample points of beamforming angle wavelength = 3. # Wavelength of the wave d = 1.414 # Sensor separation of ULA dt = 1. / sampling_rate # Interval of each time step t = np.arange(0., total_time, 1. / sampling_rate) # Time array t.resize((1, t.size)) # TODO: Randomize signal amplitude = 0.5 * np.ones(t.shape) # Amplitude in each time step phase = 2 * np.pi * np.random.rand(t.size) # Random phase in each time step signal = amplitude * np.exp(1j * phase) # Signal in each time step # TODO: Randomize DOA angle theta_t = pi / 2 / total_time * t + pi / 4 # Circular movement m = np.arange(M).reshape((M, 1)) steer = np.exp(-2j * pi * d / wavelength * m.dot(np.cos(theta_t))) # Steering vector y = np.zeros((M, t.size), dtype=np.complex) for i in range(t.size): y[:, i] = steer[:, i] * signal[0, i] # Randomize noise noise = salphas_cplx(1.23, 1.5, size=(M, t.size)) y += noise # Capon DOA estimation start_clock = time.clock() theta, estimated_Capon, Capon = doaSolver_Capon(y, wavelength, d, N, bf_resolution) stop_clock = time.clock() print('Time (Capon): %f s' % (stop_clock - start_clock)) """ # Plot the Capon beamformer result of the first slice plt.plot(180 / pi * theta[0], Capon[:, 0], 'o-') plt.grid(True) plt.title('Spatial Spectrum of Capon Estimator (DOA = 45 deg)') plt.xlabel('Direction (degree)') plt.ylabel('Power') plt.show() """ # PF-FLOM DOA estimation start_clock = time.clock() init_status = np.array([pi / 4, 0.]) estimated_PF = doaSolver_PF(y, dt, 5., 1.99, init_status, .8, 10000000, wavelength, d, 48, 42, N, bf_resolution) stop_clock = time.clock() print('Time (PF-FLOM): %f s' % (stop_clock - start_clock)) # Compare the difference of real and estimated plt.plot(t.ravel(), 180. / pi * theta_t.ravel(), 'k') time_slices = np.arange(t.size // N) * N / sampling_rate plt.plot(time_slices, estimated_Capon / pi * 180., 'o:r') plt.plot(time_slices, abs(estimated_PF) / pi * 180., '*-b') plt.legend(['Ground Truth', 'Capon', 'PF-FLOM'], loc='best') plt.title('DOA Tracking in S-alpha-S Noise Environment') plt.xlabel('Time (s)') plt.ylabel('DOA (deg)') plt.show()
Java
UTF-8
1,719
2.234375
2
[ "Apache-2.0" ]
permissive
/* * RegistrationEntryDaoHibernate.java * * Copyright © 2008-2009 City Golf League, LLC. All Rights Reserved * http://www.citygolfleague.com * * @author Steve Paquin - Sage Software Consulting, Inc. */ package com.sageconsulting.dao.hibernate; import java.util.List; import com.sageconsulting.dao.RegistrationEntryDao; import com.sageconsulting.model.RegistrationEntry; public class RegistrationEntryDaoHibernate extends BaseDaoHibernate implements RegistrationEntryDao { public RegistrationEntry getRegistrationEntry(Long id) { return (RegistrationEntry)getHibernateTemplate().get(RegistrationEntry.class, id); } @SuppressWarnings("unchecked") public List<RegistrationEntry> getRegistrationEntries() { return getHibernateTemplate().find("from RegistrationEntry"); //$NON-NLS-1$ } @SuppressWarnings("unchecked") public List<RegistrationEntry> getRegistrationEntriesForUser(Long userId) { return getHibernateTemplate().find("from RegistrationEntry r where r.user.id=?", userId); //$NON-NLS-1$ } @SuppressWarnings("unchecked") public List<RegistrationEntry> getRegistrationEntriesForRegistration(Long registrationId) { return getHibernateTemplate().find("from RegistrationEntry r where r.registration.id=?", registrationId); //$NON-NLS-1$ } public void saveRegistrationEntry(RegistrationEntry entry) { getHibernateTemplate().saveOrUpdate(entry); // flush() is necessary to generate DataIntegrityException getHibernateTemplate().flush(); } public void removeRegistrationEntry(Long id) { getHibernateTemplate().delete(getRegistrationEntry(id)); } }
Java
UTF-8
3,142
3.421875
3
[]
no_license
package code.day13; import code.day1to5_7.Customer; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class CustomerMain { static Scanner sc = new Scanner(System.in); static List<Customer>customersList=new ArrayList<Customer>(); public static void main(String[] args) { menu(); } public static void menu() { disPlayMenu(); int choice = sc.nextInt(); sc.nextLine(); while (choice!=0) { switch (choice) { case 1: addCustomer(); break; case 2: displayCustomer(); break; case 3: System.out.println("your choise is 3"); break; case 0: System.exit(0); break; default: System.out.println("No choice"); break; } disPlayMenu(); choice = sc.nextInt(); sc.nextLine(); } } public static void disPlayMenu() { System.out.println("MENU"); System.out.println("1.Add 1 khach hang"); System.out.println("2. Hien thi khach hang"); System.out.println("3.Hien thi cac villa va house"); System.out.println("0.exit"); } public static void addCustomer(){ Customer khachhang = new Customer(); System.out.println("Nhap thong tin 1 khach hang:"); System.out.println("Nhap ten khach hang"); khachhang.setName(sc.nextLine()); System.out.println("Nhap ma khach hang"); khachhang.setMSKH(sc.nextInt()); System.out.println("Nhap tuoi khach hang"); khachhang.setAge(sc.nextInt()); System.out.println("Nhap so villa khach hang muon thue"); khachhang.setNumberVilla(sc.nextInt()); System.out.println("Nhap so House khach hang muon thue"); khachhang.setNumberhouse(sc.nextInt()); System.out.println("Nhap so ngay khach hang o lai"); khachhang.setDayRent(sc.nextInt()); sc.nextLine(); customersList.add(khachhang); } public static void searchCustomer(){ System.out.println("nhap vao khach hang tim kiem"); String name=sc.nextLine(); for (int i = 0; i < customersList.size(); i++) { if(customersList.get(i).getName().equals(name)){ System.out.println(customersList.get(i)); } } } public static void displayCustomer(){ for (int i = 0; i < customersList.size(); i++) { System.out.println("Khach hang:"); System.out.println("Ten khach hang: "+customersList.get(i).getName()); System.out.println("Ma khach hang: "+customersList.get(i).getMSKH()); System.out.println("Tuoi khach hang: "+customersList.get(i).getAge()); System.out.println("So ngay khach hang o lai: "+customersList.get(i).getDayRent()); System.out.println("-----------------*********----------------"); } } }
TypeScript
UTF-8
524
2.5625
3
[]
no_license
export class Product { id?:string; usersummited?:string; serialnumber?:string; modelname?:string; custumername?:string; datesubmit?:Date; status?:string; waittingday?:string; constructor(data: any) { this.id = data.id; this.usersummited = data.usersummited; this.serialnumber = data.serialnumber; this.modelname = data.modelname; this.custumername = data.custumername; this.datesubmit = data.datesubmit; this.status = data.status; this.waittingday = data.waittingday } }
JavaScript
UTF-8
282
2.5625
3
[]
no_license
const reducer = (state={ text : '你好!访问者', name : '访问者' },action)=>{ switch (action.type){ case 'change': return { name:action.payload, text:'您好'+ action.payload } default: return state } } export default reducer
JavaScript
UTF-8
1,240
2.703125
3
[]
no_license
"use strict"; /** * @constructor * @param {string} label The label. */ var UIButton = function(label){ this.label = label; }; /** * @return {Element} The button element. */ UIButton.prototype.DOM = function(){ var button = document.createElement("button"); button.innerText = this.label; return button; }; /** * @constructor */ var UICheckbox = function(){}; /** * @return {Element} The button element. */ UICheckbox.prototype.DOM = function(){ var dom = document.createElement("input"); dom.type = "checkbox"; return dom; }; /** * @constructor * @param {string} label The label. */ var UICustomCheckbox = function(label){ this.label = label; }; /** * @return {Element} The button element. */ UICustomCheckbox.prototype.DOM = function(){ var dom = document.createElement("label"); var checkbox = (new UICheckbox).DOM(); dom.appendChild(checkbox); var span = document.createElement("span"); span.innerText = this.label; dom.appendChild(span); return dom; }; /** * @constructor */ var UIModal = function(){}; /** * @return {Element} The button element. */ UIModal.prototype.DOM = function(){ var dom = document.createElement("div"); return dom; };
C++
UTF-8
654
2.5625
3
[]
no_license
#include <iostream> #include <string> #include <algorithm> #include <cstring> #define MAX 1000 using namespace std; string str1, str2; int cache[MAX][MAX]; int getCnt(int idx1, int idx2) { if(idx1 == str1.size() || idx2 == str2.size()) return 0; int& ret = cache[idx1][idx2]; if(ret != -1) return ret; return ret = max(getCnt(idx1 + 1, idx2), max(getCnt(idx1, idx2 + 1), getCnt(idx1 + 1, idx2 + 1) + (str1[idx1] == str2[idx2]))); } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cin >> str1 >> str2; memset(cache, -1, sizeof(cache)); cout << getCnt(0, 0); return 0; }
Markdown
UTF-8
1,367
2.734375
3
[]
no_license
<img src = https://img.shields.io/badge/Team_Kosk-DID-yellow></a> # Decentalized id project of Team Kosk ## Ideas to leverage DID by Team Kosk We are a team of four South Korean blockchain developers - we are beginner-level blockchain programmers yet, but have worked hard to get our feet to next level. In this repository, we have documented our DID app/web project overview and source codes for Hackathon- & Demo day we participated(12th August, 2021, South Korea). Let's get our blocks chained :) ## What is a D.thiry app? Visit below link to see our business proposal 1. https://docs.google.com/presentation/d/1pbzxmRpCwv5Mb5Btukt3QCPSGZhsl-spTc8L8saVwSE/edit?usp=sharing (KR) 2. (Will be added) (ENG) ## Why is it needed? The biggest advantage of enabling SSI(Self Soverign Identity) is that it allows everyone to filter and subimit information only needed. This way, the previous centalized data process and strorage no longer interrupts or infringes user's privacy - but still able to address daily administrative tasks such as presenting a driver license for issuing a passport. D.thirty is a practical and user-freindly DID proejct, approaching to decentalized id with real life usage. Just like its slogan, it will let us to download and submit all kinds of certificates and, later, documents safely, quickly, and fast - with your thumb.
C++
WINDOWS-1251
1,602
2.84375
3
[]
no_license
using namespace std; class Array { int *a; int size_a; public: Array() { a = NULL; size_a = 0; } // Array(int *a1, int size_a1); // // size_a1, a1 void Print(); // int & a_i(int i); // i- Array(Array & ar); // ~Array(){ delete []a; } // Array Union(Array &ar); // Array operator +=(Array &ar); // int & operator [](int i); // int operator ==(Array &ar2); // Array operator ++(); // Array operator =(Array &ar); // Array operator +(Array &ar); // friend ostream & operator << (ostream & strm, Array &ar); // friend istream & operator >> (istream & strm, Array &ar); // friend void friend_Print(Array &ar); operator int(); operator int*(); Array (char * filename); // Array from_keyboard(int size); // Array random(int size); // Array anti (int size); // Array partly (int size); // void bubble(); void Shell(); };
Java
UTF-8
747
1.664063
2
[]
no_license
package com.sun.jmx.snmp.agent; import com.sun.jmx.snmp.SnmpOid; import com.sun.jmx.snmp.SnmpStatusException; import javax.management.ObjectName; public abstract interface SnmpTableCallbackHandler { public abstract void addEntryCb(int paramInt, SnmpOid paramSnmpOid, ObjectName paramObjectName, Object paramObject, SnmpMibTable paramSnmpMibTable) throws SnmpStatusException; public abstract void removeEntryCb(int paramInt, SnmpOid paramSnmpOid, ObjectName paramObjectName, Object paramObject, SnmpMibTable paramSnmpMibTable) throws SnmpStatusException; } /* Location: C:\Program Files\Java\jdk1.7.0_79\jre\lib\rt.jar * Qualified Name: com.sun.jmx.snmp.agent.SnmpTableCallbackHandler * JD-Core Version: 0.6.2 */
C#
UTF-8
16,758
2.546875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
//----------------------------------------------------------------------------- // // Copyright by the contributors to the Dafny Project // SPDX-License-Identifier: MIT // //----------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.IO; using JetBrains.Annotations; namespace Microsoft.Dafny; record FlowContext(SystemModuleManager SystemModuleManager, ErrorReporter Reporter, bool DebugPrint) { public TextWriter OutputWriter => SystemModuleManager.Options.OutputWriter; } /// <summary> /// A "Flow" is a puzzle piece in recomputing types. The "type adjustment" phase defines a set of flows and then /// recomputes types until it reaches a fix point. /// /// For example, the type adjustment phase will use a FlowIntoVariable to define a flow from the RHS of an assignment to /// the LHS. It will use a FlowBetweenExpressions to define a flow from the "then" branch of an "if-then-else" expression /// to the "if-then-else" expression itself, and will use another FlowBetweenExpressions to define the analogous flow from /// the "else" branch. /// /// For more information about type adjustments, flow, and the whole type inference process, see docs/dev/TypeSystemRefresh.md. /// </summary> abstract class Flow { private readonly IToken tok; private readonly string description; public bool HasError; protected string TokDescription() { return $"({tok.line},{tok.col}) {description}"; } /// <summary> /// Start flow from source to sink and return whether or not anything changed. /// </summary> public abstract bool Update(FlowContext context); protected Flow(IToken tok, string description) { this.tok = tok; this.description = description; } public abstract void DebugPrint(TextWriter output); protected bool UpdateAdjustableType(Type sink, Type sourceType, FlowContext context) { string previousLhs = null; string joinArguments = null; if (context.DebugPrint) { previousLhs = $"{AdjustableType.ToStringAsAdjustableType(sink)}"; joinArguments = $"{AdjustableType.ToStringAsBottom(sink)} \\/ {AdjustableType.ToStringAsBottom(sourceType)}"; } var previousSink = (AdjustableType.NormalizeSansAdjustableType(sink) as AdjustableType)?.T ?? sink; var join = JoinAndUpdate(sink, sourceType, context); if (join == null) { HasError = true; return false; } if (EqualTypes(previousSink, sink)) { return false; } if (context.DebugPrint) { context.OutputWriter.WriteLine($"DEBUG: updating {previousLhs} to {AdjustableType.ToStringAsBottom(sink)} ({joinArguments})"); } return true; } protected static bool EqualTypes(Type a, Type b) { if (AdjustableType.NormalizesToBottom(a) != AdjustableType.NormalizesToBottom(b)) { return false; } return a.Equals(b, true); } [CanBeNull] public static Type JoinAndUpdate(Type a, Type b, FlowContext context) { var adjustableA = AdjustableType.NormalizeSansAdjustableType(a) as AdjustableType; var join = Join(adjustableA?.T ?? a, b, context); if (join == null) { return null; } if (adjustableA == null) { return join; } join = AdjustableType.NormalizeSansAdjustableType(join); if (join is AdjustableType adjustableJoin) { join = adjustableJoin.T; } adjustableA.T = join; return adjustableA; } [CanBeNull] public static Type CopyAndUpdate(Type a, Type b, FlowContext context) { var adjustableA = AdjustableType.NormalizeSansAdjustableType(a) as AdjustableType; var aa = adjustableA?.T ?? a; // compute the "copy" of aa and b: Type copy; if (AdjustableType.NormalizesToBottom(a)) { copy = b; } else if (AdjustableType.NormalizesToBottom(b)) { copy = a; } else if (a.Equals(b, true)) { copy = a; } else { return null; } if (adjustableA == null) { return copy; } copy = AdjustableType.NormalizeSansAdjustableType(copy); if (copy is AdjustableType adjustableCopy) { copy = adjustableCopy.T; } adjustableA.T = copy; return adjustableA; } /// <summary> /// Does a best-effort to compute the join of "a" and "b", where the base types of "a" and "b" (or /// some parent type thereof) are the same. /// If there is no join (for example, if type parameters in a non-variant position are /// incompatible), then return null; /// </summary> [CanBeNull] public static Type Join(Type a, Type b, FlowContext context) { Contract.Requires(a != null); Contract.Requires(b != null); if (a is BottomTypePlaceholder) { return b; } else if (b is BottomTypePlaceholder) { return a; } // Before we do anything else, make a note of whether or not both "a" and "b" are non-null types. var abNonNullTypes = a.IsNonNullRefType && b.IsNonNullRefType; var towerA = Type.GetTowerOfSubsetTypes(a); var towerB = Type.GetTowerOfSubsetTypes(b); // We almost expect the base types of these towers to be the same, since the module has successfully gone through pre-resolution and the // pre-resolution underspecification checks. However, there are considerations. // - One is that the two given types may contain unused type parameters in type synonyms or subset types, and pre-resolution does not // fill those in or detect their absence. // - The other is traits. for (var n = System.Math.Min(towerA.Count, towerB.Count); 1 <= --n;) { a = towerA[n]; b = towerB[n]; var udtA = (UserDefinedType)a; var udtB = (UserDefinedType)b; if (udtA.ResolvedClass == udtB.ResolvedClass) { // We have two subset types with equal heads Contract.Assert(a.TypeArgs.Count == b.TypeArgs.Count); var typeArgs = Joins(TypeParameter.Variances(udtA.ResolvedClass.TypeArgs), a.TypeArgs, b.TypeArgs, context); if (typeArgs == null) { // there was an error in computing the joins, so propagate the error return null; } return new UserDefinedType(udtA.tok, udtA.Name, udtA.ResolvedClass, typeArgs); } } // We exhausted all possibilities of subset types being equal, so use the base-most types. a = towerA[0]; b = towerB[0]; if (a is BasicType) { Contract.Assert(b is BasicType); Contract.Assert(a.Equals(b, true)); return a; } else if (a is CollectionType) { var directions = a.TypeArgs.ConvertAll(_ => TypeParameter.TPVariance.Co); var typeArgs = Joins(directions, a.TypeArgs, b.TypeArgs, context); if (typeArgs == null) { return null; } Contract.Assert(typeArgs.Count == (a is MapType ? 2 : 1)); if (a is SetType aSetType) { var bSetType = (SetType)b; Contract.Assert(aSetType.Finite == bSetType.Finite); return new SetType(aSetType.Finite, typeArgs[0]); } else if (a is MultiSetType) { Contract.Assert(b is MultiSetType); return new MultiSetType(typeArgs[0]); } else if (a is SeqType) { Contract.Assert(b is SeqType); return new SeqType(typeArgs[0]); } else { var aMapType = (MapType)a; var bMapType = (MapType)b; Contract.Assert(aMapType.Finite == bMapType.Finite); return new MapType(aMapType.Finite, typeArgs[0], typeArgs[1]); } } else if (a.AsArrowType != null) { ArrowType aa = a.AsArrowType; var bb = b.AsArrowType; Contract.Assert(aa != null && bb != null && aa.Arity == bb.Arity); int arity = aa.Arity; Contract.Assert(a.TypeArgs.Count == arity + 1); Contract.Assert(b.TypeArgs.Count == arity + 1); Contract.Assert(aa.ResolvedClass == bb.ResolvedClass); var typeArgs = Joins(aa.Variances(), a.TypeArgs, b.TypeArgs, context); if (typeArgs == null) { return null; } return new ArrowType(aa.tok, (ArrowTypeDecl)aa.ResolvedClass, typeArgs); } // Convert a and b to their common supertype var aDecl = ((UserDefinedType)a).ResolvedClass; var bDecl = ((UserDefinedType)b).ResolvedClass; var commonSupertypeDecl = PreTypeConstraints.JoinHeads(aDecl, bDecl, context.SystemModuleManager); Contract.Assert(commonSupertypeDecl != null); var aTypeSubstMap = TypeParameter.SubstitutionMap(aDecl.TypeArgs, a.TypeArgs); (aDecl as TopLevelDeclWithMembers)?.AddParentTypeParameterSubstitutions(aTypeSubstMap); var bTypeSubstMap = TypeParameter.SubstitutionMap(bDecl.TypeArgs, b.TypeArgs); (bDecl as TopLevelDeclWithMembers)?.AddParentTypeParameterSubstitutions(bTypeSubstMap); a = UserDefinedType.FromTopLevelDecl(commonSupertypeDecl.tok, commonSupertypeDecl).Subst(aTypeSubstMap); b = UserDefinedType.FromTopLevelDecl(commonSupertypeDecl.tok, commonSupertypeDecl).Subst(bTypeSubstMap); var joinedTypeArgs = Joins(TypeParameter.Variances(commonSupertypeDecl.TypeArgs), a.TypeArgs, b.TypeArgs, context); if (joinedTypeArgs == null) { return null; } var udt = (UserDefinedType)a; var result = new UserDefinedType(udt.tok, udt.Name, commonSupertypeDecl, joinedTypeArgs); return abNonNullTypes && result.IsRefType ? UserDefinedType.CreateNonNullType(result) : result; } /// <summary> /// Does a best-effort to compute the meet of "a" and "b", where the base types of "a" and "b" (or /// some parent type thereof) are the same. /// If there is no meet (for example, if type parameters in a non-variant position are /// incompatible), then use a bottom type for the common base types of "a" and "b". /// </summary> public static Type Meet(Type a, Type b, FlowContext context) { Contract.Requires(a != null); Contract.Requires(b != null); // a crude implementation for now if (Type.IsSupertype(a, b)) { return b; } else if (Type.IsSupertype(b, a)) { return a; } else { // TODO: the following may not be correct in the face of traits return new BottomTypePlaceholder(a.NormalizeExpand()); } } /// <summary> /// For each i, compute some combination of a[i] and b[i], according to direction[i]. /// For a Co direction, use Join(a[i], b[i]). /// For a Contra direction (Co), use Meet(a[i], b[i]). /// For a Non direction, use a[i], provided a[i] and b[i] are equal, or otherwise use the base type of a[i]. /// </summary> [CanBeNull] public static List<Type> Joins(List<TypeParameter.TPVariance> directions, List<Type> a, List<Type> b, FlowContext context) { Contract.Requires(directions != null); Contract.Requires(a != null); Contract.Requires(b != null); Contract.Requires(directions.Count == a.Count); Contract.Requires(directions.Count == b.Count); var count = directions.Count; var extrema = new List<Type>(count); for (var i = 0; i < count; i++) { Type output; if (directions[i] == TypeParameter.TPVariance.Co) { output = JoinAndUpdate(a[i], b[i], context); } else if (directions[i] == TypeParameter.TPVariance.Contra) { output = Meet(a[i], b[i], context); } else { Contract.Assert(directions[i] == TypeParameter.TPVariance.Non); output = CopyAndUpdate(a[i], b[i], context); } if (output == null) { return null; } extrema.Add(output); } return extrema; } } class FlowIntoVariable : Flow { protected readonly Type sink; protected readonly Expression source; public FlowIntoVariable(IVariable variable, Expression source, IToken tok, string description = ":=") : base(tok, description) { this.sink = AdjustableType.NormalizeSansAdjustableType(variable.UnnormalizedType); this.source = source; } public override bool Update(FlowContext context) { return UpdateAdjustableType(sink, source.Type, context); } public override void DebugPrint(TextWriter output) { var lhs = AdjustableType.ToStringAsAdjustableType(sink); var rhs = AdjustableType.ToStringAsAdjustableType(source.UnnormalizedType); var bound = PreTypeConstraints.Pad($"{lhs} :> {rhs}", 27); var value = PreTypeConstraints.Pad(AdjustableType.ToStringAsBottom(sink), 20); output.WriteLine($" {bound} {value} {TokDescription()}"); } } class FlowIntoVariableFromComputedType : Flow { protected readonly Type sink; private readonly System.Func<Type> getType; public FlowIntoVariableFromComputedType(IVariable variable, System.Func<Type> getType, IToken tok, string description = ":=") : base(tok, description) { this.sink = AdjustableType.NormalizeSansAdjustableType(variable.UnnormalizedType); this.getType = getType; } public override bool Update(FlowContext context) { return UpdateAdjustableType(sink, getType(), context); } public override void DebugPrint(TextWriter output) { var sourceType = getType(); var bound = PreTypeConstraints.Pad($"{AdjustableType.ToStringAsAdjustableType(sink)} :> {AdjustableType.ToStringAsAdjustableType(sourceType)}", 27); var value = PreTypeConstraints.Pad(AdjustableType.ToStringAsBottom(sink), 20); output.WriteLine($" {bound} {value} {TokDescription()}"); } } class FlowBetweenComputedTypes : Flow { private readonly System.Func<(Type, Type)> getTypes; public FlowBetweenComputedTypes(System.Func<(Type, Type)> getTypes, IToken tok, string description) : base(tok, description) { this.getTypes = getTypes; } public override bool Update(FlowContext context) { var (sink, source) = getTypes(); return UpdateAdjustableType(sink, source, context); } public override void DebugPrint(TextWriter output) { var (sink, source) = getTypes(); var bound = PreTypeConstraints.Pad($"{AdjustableType.ToStringAsAdjustableType(sink)} :> {AdjustableType.ToStringAsAdjustableType(source)}", 27); var value = PreTypeConstraints.Pad(AdjustableType.ToStringAsBottom(sink), 20); output.WriteLine($" {bound} {value} {TokDescription()}"); } } abstract class FlowIntoExpr : Flow { private readonly Type sink; protected FlowIntoExpr(Type sink, IToken tok, string description = "") : base(tok, description) { this.sink = AdjustableType.NormalizeSansAdjustableType(sink); } protected FlowIntoExpr(Expression sink, IToken tok, string description = "") : base(sink.tok, description) { this.sink = sink.UnnormalizedType; } protected abstract Type GetSourceType(); public override bool Update(FlowContext context) { return UpdateAdjustableType(sink, GetSourceType(), context); } public override void DebugPrint(TextWriter output) { if (sink is AdjustableType adjustableType) { var sourceType = GetSourceType(); var bound = PreTypeConstraints.Pad($"{adjustableType.UniqueId} :> {AdjustableType.ToStringAsAdjustableType(sourceType)}", 27); var value = PreTypeConstraints.Pad(AdjustableType.ToStringAsBottom(adjustableType), 20); output.WriteLine($" {bound} {value} {TokDescription()}"); } } } class FlowFromType : FlowIntoExpr { private readonly Type source; public FlowFromType(Type sink, Type source, IToken tok, string description = "") : base(sink, tok, description) { this.source = source; } public FlowFromType(Expression sink, Type source, string description = "") : base(sink, sink.tok, description) { this.source = source; } protected override Type GetSourceType() { return source; } } class FlowFromTypeArgument : FlowIntoExpr { private readonly Type source; private readonly int argumentIndex; public FlowFromTypeArgument(Expression sink, Type source, int argumentIndex) : base(sink, sink.tok) { Contract.Requires(0 <= argumentIndex); this.source = source; this.argumentIndex = argumentIndex; } protected override Type GetSourceType() { var sourceType = source.NormalizeExpand(); Contract.Assert(argumentIndex < sourceType.TypeArgs.Count); return sourceType.TypeArgs[argumentIndex]; } } class FlowFromComputedType : FlowIntoExpr { private readonly System.Func<Type> getType; public FlowFromComputedType(Expression sink, System.Func<Type> getType, string description = "") : base(sink, sink.tok, description) { this.getType = getType; } protected override Type GetSourceType() { return getType(); } } class FlowBetweenExpressions : FlowIntoExpr { private readonly Expression source; public FlowBetweenExpressions(Expression sink, Expression source, string description = "") : base(sink, sink.tok, description) { this.source = source; } protected override Type GetSourceType() { return source.Type; } }
Java
UTF-8
517
2.3125
2
[]
no_license
package com.test.mytest.service.powermock; import com.test.mytest.dao.powermock.EmployeeDao; import com.test.mytest.model.powermock.Employee; public class EmployeeService { private EmployeeDao employeeDao; public EmployeeService(EmployeeDao employeeDao) { this.employeeDao = employeeDao; } /** * 获取所有员工的数量. * @return */ public int getTotalEmployee() { return employeeDao.getTotal(); } public void createEmployee(Employee employee) { employeeDao.addEmployee(employee); } }
Java
UTF-8
2,214
3.5625
4
[]
no_license
package com.lolo.juc.notifyWait; /** * 现在4个线程,可以操作初始值为零的一个变量, * 实现2个线程对该变量加1,2个线程对该变量减1 * * 编程思路: * 1. 线程 操作 资源类 * 2. 高内聚(空调资源制冷和制热) 低耦合(每个人使用空调资源) * * 3. 判断(while) * 4. 干活 * 5. 通知 * * Object: * hashCode() * equals() * toString() * notify() * wait() * getClass() */ public class NotifyWaitProblem { public static void main(String[] args) { // 共享资源对象 ShareDataProblem shareData = new ShareDataProblem(); // +1 线程 new Thread(() -> { for (int i = 1; i <= 10; i++) { try { Thread.sleep(100); shareData.increment(); } catch (InterruptedException e) { e.printStackTrace(); } } }, "A").start(); // -1 线程 new Thread(() -> { for (int i = 0; i < 10; i++) { try { Thread.sleep(200); shareData.decrement(); } catch (InterruptedException e) { e.printStackTrace(); } } }, "B").start(); // +1 线程 new Thread(() -> { for (int i = 0; i < 10; i++) { try { Thread.sleep(300); shareData.increment(); } catch (InterruptedException e) { e.printStackTrace(); } } }, "C").start(); // -1 线程 new Thread(() -> { for (int i = 0; i < 10; i++) { try { Thread.sleep(400); shareData.decrement(); } catch (InterruptedException e) { e.printStackTrace(); } } }, "D").start(); } } /* A 1 B 0 A 1 B 0 A 1 C 2 D 1 B 0 A 1 B 0 A 1 C 2 D 1 B 0 A 1 B 0 C 1 A 2 D 1 B 0 A 1 B 0 C 1 A 2 D 1 B 0 A 1 B 0 C 1 D 0 C 1 D 0 C 1 D 0 C 1 D 0 C 1 D 0 C 1 D 0 */
C++
UTF-8
1,218
3.359375
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> #include <functional> #include <numeric> using namespace std; class print{ public: print(): count(0){ } void operator()(int v){ count++; cout << v << endl; } int count; }; void test01(){ vector<int> v; for(int i=0; i< 10; i++){ v.push_back(i); } print p1; print p2 = for_each(v.begin(), v.end(), p1); cout << "count: " << p1.count << endl; cout << endl; cout << "count: " << p2.count << endl; } class myplus100{ public: int operator()(int v){ return v + 100; } }; class myminute{ public: int operator()(int v1, int v2){ return v2-v1; } }; void test02(){ // vector<int> v1, v2; // for(int i=0; i< 10; i++){ // v1.push_back(i); // } // v2.resize(v1.size()); // for_each(v2.begin(), v2.end(), p1); // transform(v1.begin(), v1.end(), v2.begin(), myplus100()); // print p1; // for_each(v2.begin(), v2.end(), p1); vector<int> v1, v2, v3; for(int i=0; i< 10; i++){ v1.push_back(i); v2.push_back(i+1); } v3.resize(v1.size()); for_each(v3.begin(), v3.end(), print()); cout << endl; transform(v1.begin(), v1.end(), v2.begin(), v3.begin(), myminute()); for_each(v3.begin(), v3.end(), print()); cout << endl; }
Java
UTF-8
9,028
2.40625
2
[]
no_license
/* * Copyright (C) 2016 Toby Scholz 2016 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package NepTune; import java.io.File; import java.security.NoSuchAlgorithmException; import java.util.List; import java.util.Map; import jcifs.smb.SmbException; import jcifs.smb.SmbFile; import java.util.ArrayList; import java.util.Date; import org.bson.Document; import static NepTune.DataParser.properties; /** * The Maintenance class has two purposes: * 1) It checks if the files available in the samba share match those in * the index, and adds / removes as appropriate. * 2) It clears out the Neptune temp directory. */ public class Maintenance implements Runnable { /** * The possible cases: * 1) File is deleted from SMB, still exists in datastore * 2) File was added to SMB, does not yet exist in datastore * 3) Existing file was modified */ SambaConnector samba = new SambaConnector( properties.getProperty("sambaUser"), properties.getProperty("sambaPassword"), properties.getProperty("sambaServer"), properties.getProperty("sambaPath")); DataStoreSingleton ds = DataStoreSingleton.getInstance(); MongoConnectorSingleton mongo = MongoConnectorSingleton.getInstance(); /** * Case 1). If removed from file share, also remove from live datastore, * and the database */ void checkIfDBEntryNoLongerExistsOnSamba() { Map<String,Document> existingEntries = ds.getMap(); List<String> docsToRemove = new ArrayList<>(); for ( Map.Entry<String, Document> entry : existingEntries.entrySet() ) { String file = (String) entry.getValue().get("fileName"); String path = (String) entry.getValue().get("filePath"); String type = (String) entry.getValue().get("fileType"); String filePath = path + file + "." + type; try { if (!samba.getFile(filePath).exists()) { mongo.removeEntry("files", file, path, type); docsToRemove.add(entry.getKey()); } } catch (SmbException ex) { LOG.ERROR("Exception while trying to access " + path + " (" + entry.getKey() + ")"); } } removeItemsFromDataStore(docsToRemove); } /** * Helper method to above, remove from live data store. * @param docs */ void removeItemsFromDataStore(List<String> docs) { for( String entry : docs) { ds.removeItem(entry); LOG.INFO("Maintenance removed id " + entry + " from document store"); } } /** * Cases 2) and 3). * If a new file was added to the samba share, also add it to the database * and live data store. * If an existing item was modified, remove it from the database and the * live datastore, and re-introduce as a new item. * @throws NoSuchAlgorithmException * @throws SmbException */ void addEntryIfWasAddedToSambaOrIfExistingEntryMatchesFile() throws NoSuchAlgorithmException, SmbException { Map<String,Document> existingEntries = ds.getMap(); for (String ii : samba.populatePathSet() ) { boolean found = false; String entryToRemove = null; String path = null; String file = null; String type = null; for ( Map.Entry<String, Document> entry : existingEntries.entrySet() ) { path = (String) entry.getValue().get("filePath"); file = (String) entry.getValue().get("fileName"); type = (String) entry.getValue().get("fileType"); String filePath = path + file + "." + type; if (ii.equals(filePath)) // we found the file in the db also in the datastore. Has it been modified? { try { found = compareFiles(entry.getValue().get("hash").toString(), ii); // if found is false, it has been modified. } catch (Exception e) { LOG.ERROR("Exception comparing file " + e.toString()); found = false; } entryToRemove = entry.getKey(); break; } } if (!found) /* Because mongodb creates the unique id of an entry, it is necessary to commit the new entry to db first, and then query the db to get the object id in order to add it to the live data store. */ { if (entryToRemove != null) // entry already exists, but has been modified. { ds.removeItem(entryToRemove); // remove from live data store mongo.removeEntry("files", file, path, type); // remove from db } DataParser dp = new DataParser(); Map<String, String> fileDetails = dp.splitPath(ii); Document doc = dp.parseSingleDoc(ii); // parse the new document mongo.addRecord(doc); // add it to db doc = mongo.getDocument("files", fileDetails.get("name"), fileDetails.get("path"), fileDetails.get("type")); // retrieve it from db String id = doc.get("_id").toString(); ds.addItem(id, doc); // add it tolive data store LOG.INFO("Maintenance added document " + doc.toString()); } } } /** * Compares two files based on a hash generated from its length and * last modified time. * * @param docHash Hash of existing entry * @param filePath Path to file for hashing * @return True if both hashes match * @throws SmbException */ private boolean compareFiles(String docHash, String filePath) throws SmbException { FileHasher fh = new FileHasher(); String fileHash = null; SmbFile file = null; try { file = new SmbFile(filePath); } catch(Exception e) { LOG.ERROR("Could not access file " + filePath); return false; } fileHash = fh.generateHash(file); return docHash.equals(fileHash); } /** * HLS creates stream file in the temp directory. We want to clear these * every now and then, as else, we will be running out of disk space. * Four hours seems a good time. */ void clearTempDirectory(int olderThan) { long date = new Date().getTime(); File tempFolder = new File(properties.getTempDirectory()); File[] files = tempFolder.listFiles(); for (File file : files) { if ((date - file.lastModified() > olderThan )) // older than four hours { file.delete(); } } } /** * Run all of the above methods in sequence, according to maintenanceInterval * specified in the config. */ @Override public void run() { while(true) { LOG.INFO("Starting Maintenance"); try { addEntryIfWasAddedToSambaOrIfExistingEntryMatchesFile(); } catch(Exception e) { LOG.ERROR("Error during file maintenance"); } checkIfDBEntryNoLongerExistsOnSamba(); // Must come after addEntry... clearTempDirectory((14400)*1000); // older than four hours LOG.INFO("Maintenance completed"); try { Thread.sleep(Integer.parseUnsignedInt(properties.getProperty("maintenanceInterval")) * 60 * 1000 ); } catch (InterruptedException ex) { LOG.ERROR("Error doing nothing in particular"); } } } } // end class
Java
UTF-8
2,070
2.328125
2
[]
no_license
package com.wuk.fastorm.bean; import com.wuk.fastorm.annontation.FastormColumn; import com.wuk.fastorm.annontation.FastormTable; import com.wuk.fastorm.proxy.DefaultLastOperateFeatureFactory; import com.wuk.fastorm.proxy.LastOperateFeature; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Function; public class FastormBeanStructure<T> extends BeanStructure<T> { private FastormTable table; private Map<String, FastormColumn> columnMap; public FastormBeanStructure(BeanStructure<T> beanStructure) { setClazz(beanStructure.getClazz()); setFieldNames(beanStructure.getFieldNames()); setFieldMap(beanStructure.getFieldMap()); setReadMethodMap(beanStructure.getReadMethodMap()); setWriteMethodMap(beanStructure.getWriteMethodMap()); } public FastormTable getTable() { return table; } public void setTable(FastormTable table) { this.table = table; } public Map<String, FastormColumn> getColumnMap() { return columnMap; } public void setColumnMap(Map<String, FastormColumn> columnMap) { this.columnMap = columnMap; } /** * 获取列名称 * @param fieldName * @return */ public String findColumnName(String fieldName) { return columnMap.get(fieldName).value(); } /** * 列是否是autoIncrement * @param fieldName * @return */ public boolean isAutoIncrement(String fieldName) { return columnMap.get(fieldName).autoIncrement(); } /** * 读取数据库结果 * @param resultSet * @return */ public List<T> readResultSet(ResultSet resultSet) throws SQLException { Map<String, String> columnMapping = new HashMap<>(); for (String fieldName : getFieldNames()) { columnMapping.put(columnMap.get(fieldName).value(), fieldName); } return super.readResultSet(resultSet, columnMapping); } }
Java
UTF-8
738
1.664063
2
[]
no_license
package com.viewnext.admin.servicio; import java.util.List; import com.viewnext.admin.bean.BusquedaLibro; import com.viewnext.admin.bean.Categoria; import com.viewnext.admin.bean.FiltroBusqueda; import com.viewnext.admin.bean.Libro; import com.viewnext.admin.bean.RespuestaBusqueda; public interface CatalogoServicio { List<Categoria> todasCategorias(); Categoria buscarCategoiraPorId(Long id); void actualizarCategoria(Categoria cat); void nuevaCategoria(Categoria cat); void eliminarCategoria(Long id); RespuestaBusqueda buscarPorCriterios(FiltroBusqueda filtro); Libro buscarLibroPorId(Long id); void actualizarLibro(Libro libro); void nuevoLibro(Libro libro); void eliminarLibro(Long id); }
Python
UTF-8
2,179
2.640625
3
[]
no_license
#!/usr/bin/env python import rospy import roslib from sensor_msgs.msg import Image from cv_bridge import CvBridge, CvBridgeError import cv2 import numpy as np import copy class Camera: def __init__(self): print('Camera Initialized') self.bridge_ros2cv = CvBridge() self.image = None while self.image is None: try: image_msg = rospy.wait_for_message("/camera/color/image_raw", Image) self.image = self.bridge_ros2cv.imgmsg_to_cv2(image_msg, desired_encoding="passthrough") #print type(self.image) #print self.image.shape print "check 1" except: pass #rospy.Subscriber("/camera/color/image_raw", Image, self.imageCallback, queue_size = 1) #rospy.Subscriber("/camera/color/image_raw", Image, self.getImage, queue_size = 1000) #rospy.Timer(rospy.Duration(1.0/5.0), self.getImage) def start(self): rospy.init_node('camera_show', anonymous=True) #while not rospy.is_shutdown(): # rospy.spin() def imageCallback(self, image_msg): print("Recieved Image") print "check 2" frame = self.bridge_ros2cv.imgmsg_to_cv2(image_msg, desired_encoding="passthrough") print type(frame) print frame.shape self.image = frame #self.getImage(self.image) #cv2.imshow("asdf", self.image[...,::-1]) #cv2.waitKey(1) def getImage2(self): try: image_msg = rospy.wait_for_message("/camera/color/image_raw", Image) self.image = self.bridge_ros2cv.imgmsg_to_cv2(image_msg, desired_encoding="passthrough") #print type(self.image) #print self.image.shape print "got something" except: pass return self.image def getImage(self, event): #return image print "check 3" print "returning latest image" #return self.image cv2.imshow("getimage", self.image[...,::-1]) cv2.waitKey(1) def __getitem__(self, item): #return image return self.image[item]
Java
UTF-8
8,739
2.5
2
[]
no_license
package Application; /** * @author jmalafronte * Controls all GUIs */ import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Arrays; import java.util.Comparator; import java.util.EventObject; import java.util.Observable; import java.util.Observer; import java.util.concurrent.TimeUnit; import javax.swing.*; import Data.*; import GUI.*; import SPI.*; import Utilities.*; public class runApp implements ActionListener, Observer { TPIGUI main; GUI_Monitor monitor = new GUI_Monitor(); GUIEndScreen endScreen = new GUIEndScreen(); MainLoop loop; TempData data; WriteFile file; long lStartTime, lEndTime; SpiConnector spi = new SpiConnector(); Double[][] tempArray; public runApp() { data = new TempData(); file = new WriteFile(data); main = new TPIGUI(); main.setVisible(true); // add actionlistener to main.startbutton object main.conNextButton.addActionListener(this); main.homeNextButton.addActionListener(this); main.conRefreshButton.addActionListener(this); main.checkRefreshButton.addActionListener(this); monitor.Pause_Button.addActionListener(this); endScreen.homeButton.addActionListener(this); } public void actionPerformed(ActionEvent e) { if(e.getSource() == endScreen.homeButton) { //set main to visible main.setVisible(true); monitor.setVisible(false); endScreen.setVisible(false); } if(e.getSource() == main.homeNextButton) { if (main.generalInfoText.getText().isEmpty()){ JOptionPane.showMessageDialog( main.tabbedPane, "Please Enter Test Info"); //setTitle("System Setup"); } else{ main.tabbedPane.setSelectedIndex(1); main.tabbedPane.setEnabledAt(1, true); } } // end homeNextButton // application start button if(e.getSource() == main.conNextButton) { // save all the data to temp data.setHiThreshold(Float.parseFloat(main.hiThresholdField.getText())); data.setLowThreshold(Float.parseFloat(main.lowThresholdField.getText())); data.setNumberOfCells(main.numberOfCells); data.setAbortVoltage(Float.parseFloat(main.abortVoltageField.getText())); data.setBatteryVoltage(Float.parseFloat(main.batteryVoltageField.getText())); data.setCellAlarmThreshold(Float.parseFloat(main.cellAlarmField.getText())); data.setGeneralTestInformation(main.generalInfoText.getText()); System.out.println(data.getGeneralTestInformation()); file.setCellData(spi.getSpiData(main.numberOfCells)); main.setVisible(false); monitor.setVisible(true); loop = new MainLoop(monitor, data, file); loop.thresholds.addObserver(this); loop.startLoop(); lStartTime = System.nanoTime(); } if(e.getSource() == main.checkRefreshButton || e.getSource() == main.conRefreshButton) { try{ //System.out.println("Number of Cells: " + main.numberOfCells); float[] spiArray = spi.getSpiData(main.numberOfCells); //main.printVoltage(spi.getSpiData(main.numberOfCells)); tempArray = new Double [main.numberOfCells] [2]; int tempCell = 1; for (int i= 0; i < spiArray.length; i++){ int j = 0; tempArray [i][j] = Double.valueOf(spiArray[i]); j++; tempArray [i][j] = Double.valueOf(tempCell); tempCell++; } if (main.sortLowRadioButton.isSelected()){ final Comparator<Double[]> arrayComparator = new Comparator<Double[]>() { @Override public int compare(Double[] o1, Double[] o2) { return ((o1[0]).compareTo(o2[0])); } }; Arrays.sort(tempArray, arrayComparator); main.voltArea.setText(""); for (int i= 0; i < tempArray.length; i++){ main.voltArea.append("Cell : " + Math.round(tempArray [i][1]) + " " + tempArray [i][0] + " "); //System.out.println("Cell : " + tempArray [i][1] + " " + tempArray [i][0] + " "); } } else if (main.sortHighRadioButton.isSelected()){ final Comparator<Double[]> arrayComparatorDes = new Comparator<Double[]>() { @Override public int compare(Double[] o1, Double[] o2) { return ((o2[0]).compareTo(o1[0])); } }; Arrays.sort(tempArray, arrayComparatorDes); main.voltArea.setText(""); for (int i= 0; i < tempArray.length; i++){ main.voltArea.append("Cell " + Math.round(tempArray [i][1]) + ": " + tempArray [i][0] + " "); //System.out.println("Cell " + tempArray [i][1] + ": " + tempArray [i][0] + " "); } } else if (main.sortCellRadioButton.isSelected()){ main.voltArea.setText(""); main.printVoltage(spiArray); } } catch (Exception e1) { main.voltArea.setText("No Data Available"); e1.printStackTrace(); } JOptionPane.showMessageDialog( null, "Activity Log is refreshed"); } // end refreshButton if (e.getSource() == monitor.Pause_Button) { monitor.Pause_Button.setText("Resume"); // loop.stopLoop(); int confirm = JOptionPane.showConfirmDialog(null, "Abort?", "Paused", JOptionPane.YES_NO_OPTION); if (confirm == JOptionPane.YES_OPTION) { loop.stopLoop(); monitor.Pause_Button.setText("Pause"); //create summary gui main.setVisible(false); monitor.setVisible(false); endScreen.setVisible(true); lEndTime = System.nanoTime(); long difference = lEndTime - lStartTime; // format the elapsed time and print to console System.out.println("Total execution time: " + String.format("%d min, %d sec", TimeUnit.NANOSECONDS.toHours(difference), TimeUnit.NANOSECONDS.toSeconds(difference) - TimeUnit.MINUTES.toSeconds(TimeUnit.NANOSECONDS.toMinutes(difference)))); System.out.println("Elapsed MilliSeconds: " + difference/1000000); // update test complete status endScreen.tComp.setText("Aborted"); // update total elapsed time endScreen.tDuration.setText( String.format("%d min, %d sec", TimeUnit.NANOSECONDS.toHours(difference), TimeUnit.NANOSECONDS.toSeconds(difference) - TimeUnit.MINUTES.toSeconds(TimeUnit.NANOSECONDS.toMinutes(difference)))); } else { //resume loop monitor.Pause_Button.setText("Pause"); loop.startLoop(); } } } public void update(Observable obs, Object obj) { // print out that it's out of threshold and at which cell System.out.println("out of threshold at " + obj); // pause the loop //loop.pauseLoop(); // alarm // abort? } }
SQL
UTF-8
424
3.859375
4
[]
no_license
SELECT AVG(cal) FROM (SELECT M.menu_id as menu_id, SUM(MR.amount / 100 * RM.amount / 100 * MA.cal) as cal FROM menus M INNER JOIN menu_recipe MR ON M.menu_id = MR.menu_id INNER JOIN recipe_material RM ON MR.recipe_id = RM.recipe_id INNER JOIN materials MA ON RM.material_id = MA.material_id GROUP BY M.menu_id) CAL;
Markdown
UTF-8
589
3.328125
3
[]
no_license
# 797. All Paths From Source to Target ## Solution 1 (time O(n*2^n), space O(n)) ```python class Solution(object): def allPathsSourceTarget(self, graph): """ :type graph: List[List[int]] :rtype: List[List[int]] """ self.ans = [] n = len(graph) def dfs(cur_node, cur_path): cur_path.append(cur_node) if cur_node == n - 1: self.ans.append(cur_path[:]) for new_node in graph[cur_node]: dfs(new_node, cur_path[:]) dfs(0, []) return self.ans ```
Markdown
UTF-8
3,013
2.734375
3
[]
no_license
# semantic-journal # Проект semantic-journal ## Сущности - Статья - Тайтл - Дата создания - Дата изменнения - Список тегов - Тег - Имя - Список тегов - Поиск - Запрос: Список тегов через запятую - Результат - Список статей которые роднятся с тегами (через граф метатегов) - Список тегов (которыми помечаны) ## Технологии ### База данных: Apache Jena jena сервер: https://hub.docker.com/r/stain/jena-fuseki/ jena командные утиля: https://hub.docker.com/r/stain/jena/ ``` docker run -p 3030:3030 stain/jena-fuseki docker run stain/jena riot http://www.w3.org/2013/TurtleTests/SPARQL_style_prefix.ttl ``` ## Стадии разработки 1. Локальное приложение 2. докеризированое приложение с возможностью развёртки через кубернетес (Это уже в дром репе) 3. ~~сервис типа lifejournal~~ # Поток сознания на тему концепции проекта Улучшенный дневник. Дневник в котором записи связаны не только хронологическим образом. Но и с помощью тегов. А также можно отвечать на другие статьи (получается диалог сам с самим собой). А так же есть возможность группировать статьи в группы с помощью тегов. Теги в свою очередь тоже можно помечать метатегами. Метатеги можно помечать метатегами. Можно селектить стать с помощью метатега. ## Какие юзкейсы? 1. Иногда хочется ответить на свою статью в дневнике. Потому что, например, какая-то ситуация развилась и появились новые данные. 2. Возникает нужда помечать теги метатегами, например есть набор мыслей о проектах. Эти мысли (описанные в статьях) помечены тегами- названиями проектов. И тут нужен список проектов. Для этого мы помечаем проекты метатегами - "проект", "опенсорс". Также интересно будет возможность делать богатый поисковый запрос, например "проекты", "идея". ## Терминология Метатег - тег которым помечен хотябы один другой тег ## Зачем? Прост)
Java
UTF-8
1,679
2.84375
3
[ "Apache-2.0" ]
permissive
package com.contentful.tea.java.markdown; import org.commonmark.node.AbstractVisitor; import org.commonmark.node.Block; import org.commonmark.node.Document; import org.commonmark.node.Node; import org.commonmark.node.Paragraph; import org.commonmark.parser.Parser; import org.commonmark.renderer.html.HtmlRenderer; import org.springframework.stereotype.Component; /** * Implementation of {@link MarkdownParser} using the commonsmark markdown parser. */ @Component @SuppressWarnings("unused") public class CommonmarkMarkdownParser implements MarkdownParser { private final Parser parser = Parser.builder().build(); private final AbstractVisitor simplifyInlineMarkdown = new AbstractVisitor() { @Override public void visit(Paragraph paragraph) { super.visit(paragraph); final Block parent = paragraph.getParent(); if (parent instanceof Document) { if (parent.getFirstChild() == paragraph && parent.getLastChild() == paragraph) { while (paragraph.getFirstChild() != null) { paragraph.insertBefore(paragraph.getFirstChild()); } paragraph.unlink(); } } } }; private final HtmlRenderer renderer = HtmlRenderer.builder().build(); /** * Parse a given simple text and return html notation of it. * * @param toParse the string containing Markdown markup. * @return a String containing html representation of input, or null on error. */ @Override public String parse(String toParse) { if (toParse == null) { return null; } final Node node = parser.parse(toParse); node.accept(simplifyInlineMarkdown); return renderer.render(node); } }
Shell
UTF-8
491
3.640625
4
[ "Apache-2.0" ]
permissive
#!/bin/bash set -x set -o nounset # -u FOO="FOO" #BAR="BAR" echo "FOO=$FOO" # this will fail when -u is set #echo "BAR=$BAR" # From: # http://stackoverflow.com/questions/874389/bash-test-for-a-variable-unset-using-a-function # test if a var is set or not when -u opt is set if [ ! ${!BAR[@]} ]; then echo "FALSE test with {!BAR[@]}" else echo "TRUE {!BAR[@]}" echo "BAR=$BAR" fi # if [ ${BAR-_} ]; then # echo "TRUE" # echo "BAR=$BAR" # else # echo "FALSE" # fi
PHP
UTF-8
1,302
2.875
3
[]
no_license
<?php class Database { public function dbConnect(){ try{ $database_conn = new PDO('mysql:host=localhost;dbname=jona;charset=utf8mb4','root',''); return $database_conn; }catch(PDOException $e){ return NULL; } } } /*$username = 'developer'; $password = 'Dri@2016';*/ //var_dump($db); /*class pdo{ private $conn; private $host; private $user; private $password; private $baseName; private $port; private $Debug; function __construct() { $this->conn = false; $this->host = 'localhost'; //hostname $this->user = 'developer'; //username $this->password = 'Dri@2016'; //password $this->baseName = 'jona'; //name of your database $this->connect(); } function connect(){ if($this->conn){ try { $this->conn = new PDO('mysql:host='.$this->host. ';dbname='.$this->baseName.'',$this->user,$this->password, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8mb4')); var_dump($this->conn); } catch(Exception $e){ die('Error:' . $e->getMessage()); } if (!$this->conn) { $this->status_fatal = true; echo 'Connection failed'; die(); } else{ $this->status_fatal = false; } } return $this->conn; } function disconnect(){ if($this->conn){ $this->conn =null; } } */ ?>
Rust
UTF-8
5,567
2.640625
3
[ "MIT", "Apache-2.0" ]
permissive
//! An instance represents an instance of Vulkan application. use std::{ ffi::{CStr, CString}, fmt::{Debug, Error, Formatter}, ops::Deref, os::raw::c_char }; use ash::{extensions::ext::DebugUtils, vk}; use crate::{entry::Entry, memory::host::HostMemoryAllocator, physical_device::PhysicalDevice, prelude::Vrc, util::fmt::VkVersion}; pub mod debug; pub mod error; #[cfg(test)] pub mod test; #[derive(Debug, Clone, Copy, Default)] pub struct ApplicationInfo<'a> { pub application_name: &'a str, pub engine_name: &'a str, pub application_version: VkVersion, pub engine_version: VkVersion, pub api_version: VkVersion } struct InstanceDebug { loader: DebugUtils, callback: vk::DebugUtilsMessengerEXT, host_memory_allocator: HostMemoryAllocator } impl Debug for InstanceDebug { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { f.debug_struct("InstanceDebug") .field("loader", &"<ash::_::DebugReport>") .field("callback", &self.callback) .field( "host_memory_allocator", &self.host_memory_allocator ) .finish() } } pub struct Instance { entry: Entry, instance: ash::Instance, // For the HasHandle trait instance_handle: vk::Instance, host_memory_allocator: HostMemoryAllocator, debug: Option<InstanceDebug> } impl Instance { /// Creates a new instance from an existing entry. pub fn new<'a>( entry: Entry, application_info: ApplicationInfo, layers: impl IntoIterator<Item = &'a CStr> + std::fmt::Debug, extensions: impl IntoIterator<Item = &'a CStr> + std::fmt::Debug, host_memory_allocator: HostMemoryAllocator, debug_callback: debug::DebugCallback ) -> Result<Vrc<Self>, error::InstanceError> { log::info!( "Vulkan instance version {}", entry.instance_version() ); let application_name_c = CString::new(application_info.application_name)?; let engine_name_c = CString::new(application_info.engine_name)?; let app_info = vk::ApplicationInfo::builder() .application_name(application_name_c.as_ref()) .engine_name(engine_name_c.as_ref()) .application_version(application_info.application_version.0) .engine_version(application_info.engine_version.0) .api_version(application_info.api_version.0); log::debug!( "Instance create info {:#?} {:#?} {:#?}", application_info, layers, extensions ); let ptr_layers: Vec<*const c_char> = layers.into_iter().map(CStr::as_ptr).collect(); let ptr_extensions: Vec<*const c_char> = extensions.into_iter().map(CStr::as_ptr).collect(); let create_info = vk::InstanceCreateInfo::builder() .application_info(&app_info) .enabled_layer_names(ptr_layers.as_slice()) .enabled_extension_names(ptr_extensions.as_slice()); unsafe { Instance::from_create_info( entry, create_info, host_memory_allocator, debug_callback ) } } /// Creates a new `Instance` from existing `InstanceCreateInfo`. /// /// ### Safety /// /// See <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/VkInstanceCreateInfo.html>. pub unsafe fn from_create_info( entry: Entry, create_info: impl Deref<Target = ash::vk::InstanceCreateInfo>, host_memory_allocator: HostMemoryAllocator, debug_callback: debug::DebugCallback ) -> Result<Vrc<Self>, error::InstanceError> { log_trace_common!( "Creating instance:", entry, create_info.deref(), host_memory_allocator, debug_callback ); let instance = entry.create_instance( &create_info, host_memory_allocator.as_ref() )?; // TODO: debug messenger, validation features, validation flags? let debug = match debug_callback.into() { None => None, Some(ref create_info) => { let loader = DebugUtils::new(entry.deref(), &instance); let callback = loader.create_debug_utils_messenger(create_info, None)?; Some(InstanceDebug { loader, callback, host_memory_allocator: HostMemoryAllocator::Unspecified() /* TODO: Allow callbacks */ }) } }; Ok(Vrc::new(Instance { entry, instance_handle: instance.handle(), instance, host_memory_allocator, debug })) } pub const fn entry(&self) -> &Entry { &self.entry } /// See <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/vkEnumeratePhysicalDevices.html>. pub fn physical_devices(self: &Vrc<Self>) -> Result<impl ExactSizeIterator<Item = PhysicalDevice>, error::PhysicalDeviceEnumerationError> { let elf = self.clone(); let enumerator = unsafe { self.enumerate_physical_devices()? .into_iter() .map(move |physical_device| PhysicalDevice::from_existing(elf.clone(), physical_device)) }; Ok(enumerator) } } impl_common_handle_traits! { impl HasHandle<vk::Instance>, Borrow, Eq, Hash, Ord for Instance { target = { instance_handle } } } impl Deref for Instance { type Target = ash::Instance; fn deref(&self) -> &Self::Target { &self.instance } } impl Drop for Instance { fn drop(&mut self) { log_trace_common!(info; "Dropping", self); unsafe { if let Some(debug) = self.debug.as_mut() { debug.loader.destroy_debug_utils_messenger( debug.callback, debug.host_memory_allocator.as_ref() ); } self.instance .destroy_instance(self.host_memory_allocator.as_ref()); } } } impl Debug for Instance { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { f.debug_struct("Instance") .field("entry", &self.entry) .field( "instance", &crate::util::fmt::format_handle(self.instance.handle()) ) .field( "host_memory_allocator", &self.host_memory_allocator ) .field("debug", &self.debug) .finish() } }
SQL
UTF-8
5,053
3.203125
3
[ "MIT" ]
permissive
-- -------------------------------------------------------- -- Host: 192.168.33.10 -- Server version: 5.5.52-MariaDB - MariaDB Server -- Server OS: Linux -- HeidiSQL Version: 9.4.0.5125 -- -------------------------------------------------------- /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET NAMES utf8 */; /*!50503 SET NAMES utf8mb4 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; -- Dumping database structure for ci CREATE DATABASE IF NOT EXISTS `ci` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `ci`; -- Dumping structure for table ci.adm_acl CREATE TABLE IF NOT EXISTS `adm_acl` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `parent_id` bigint(20) NOT NULL DEFAULT '0', `name` varchar(50) DEFAULT NULL, `controller` varchar(255) NOT NULL, `method` varchar(255) NOT NULL, `is_menu` tinyint(4) NOT NULL DEFAULT '1', `is_enabled` tinyint(4) DEFAULT '1', `sort` tinyint(4) NOT NULL DEFAULT '1', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8; -- Dumping data for table ci.adm_acl: ~14 rows (approximately) /*!40000 ALTER TABLE `adm_acl` DISABLE KEYS */; INSERT INTO `adm_acl` (`id`, `parent_id`, `name`, `controller`, `method`, `is_menu`, `is_enabled`, `sort`) VALUES (1, 0, 'admin', '', '', 1, 1, 1), (2, 1, 'user', 'user', 'lists', 1, 1, 1), (3, 2, 'add user', 'user', 'add', 0, 1, 1), (4, 2, 'edit user', 'user', 'edit', 0, 1, 2), (5, 1, 'group', 'group', 'lists', 1, 1, 2), (6, 2, 'add group', 'group', 'add', 0, 1, 1), (7, 2, 'edit group', 'group', 'edit', 0, 1, 2), (8, 0, 'demo1', '', '', 1, 1, 2), (9, 8, 'demo11', 'demo', 'demo11', 1, 1, 1), (10, 8, 'demo12', 'demo', 'demo12', 1, 1, 2), (11, 9, 'add demo11', 'demo', 'add11', 0, 1, 1), (12, 9, 'edit demo11', 'demo', 'edit11', 0, 1, 2), (13, 10, 'add demo12', 'demo', 'add12', 0, 1, 1), (14, 10, 'edit demo12', 'demo', 'demo12', 0, 1, 2); /*!40000 ALTER TABLE `adm_acl` ENABLE KEYS */; -- Dumping structure for table ci.adm_group CREATE TABLE IF NOT EXISTS `adm_group` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL, `is_enabled` tinyint(4) NOT NULL DEFAULT '1', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; -- Dumping data for table ci.adm_group: ~2 rows (approximately) /*!40000 ALTER TABLE `adm_group` DISABLE KEYS */; INSERT INTO `adm_group` (`id`, `name`, `is_enabled`) VALUES (1, 'admin', 1), (2, 'testg1', 1); /*!40000 ALTER TABLE `adm_group` ENABLE KEYS */; -- Dumping structure for table ci.adm_group_acl CREATE TABLE IF NOT EXISTS `adm_group_acl` ( `sn` bigint(20) NOT NULL AUTO_INCREMENT, `group_id` bigint(20) NOT NULL, `acl_id` bigint(20) NOT NULL, `is_enabled` tinyint(4) NOT NULL DEFAULT '1', PRIMARY KEY (`sn`), UNIQUE KEY `aclgroupid_aclid` (`group_id`,`acl_id`) ) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8; -- Dumping data for table ci.adm_group_acl: ~14 rows (approximately) /*!40000 ALTER TABLE `adm_group_acl` DISABLE KEYS */; INSERT INTO `adm_group_acl` (`sn`, `group_id`, `acl_id`, `is_enabled`) VALUES (1, 1, 1, 1), (2, 1, 2, 1), (3, 1, 3, 1), (4, 1, 4, 1), (5, 1, 5, 1), (6, 1, 6, 1), (7, 1, 7, 1), (8, 1, 8, 1), (9, 1, 9, 1), (10, 1, 10, 1), (11, 1, 11, 1), (12, 1, 12, 1), (13, 1, 13, 1), (14, 1, 14, 1); /*!40000 ALTER TABLE `adm_group_acl` ENABLE KEYS */; -- Dumping structure for table ci.adm_user CREATE TABLE IF NOT EXISTS `adm_user` ( `id` varchar(50) NOT NULL, `password` varchar(100) NOT NULL, `group_id` bigint(20) NOT NULL, `is_enabled` tinyint(4) NOT NULL DEFAULT '1', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Dumping data for table ci.adm_user: ~13 rows (approximately) /*!40000 ALTER TABLE `adm_user` DISABLE KEYS */; INSERT INTO `adm_user` (`id`, `password`, `group_id`, `is_enabled`) VALUES ('admin', '$2y$10$OvhGOJI/bje5N.Y5rni.VOsJV6LpNEUMhhcj/ujMh4aWp8eoXs/gu', 1, 1), ('test1', '', 0, 1), ('test10', '', 0, 1), ('test2', '', 0, 1), ('test3', '', 0, 1), ('test4', '', 0, 1), ('test5', '', 0, 1), ('test6', '', 0, 1), ('test7', '', 0, 1), ('test8', '', 0, 1), ('test9', '', 0, 1); /*!40000 ALTER TABLE `adm_user` ENABLE KEYS */; -- Dumping structure for table ci.adm_user_acl CREATE TABLE IF NOT EXISTS `adm_user_acl` ( `sn` bigint(20) NOT NULL AUTO_INCREMENT, `userid` varchar(50) NOT NULL, `acl_id` bigint(20) NOT NULL, `is_enabled` tinyint(4) NOT NULL DEFAULT '1', PRIMARY KEY (`sn`), UNIQUE KEY `userid_aclsn` (`userid`,`acl_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- Dumping data for table ci.adm_user_acl: ~0 rows (approximately) /*!40000 ALTER TABLE `adm_user_acl` DISABLE KEYS */; /*!40000 ALTER TABLE `adm_user_acl` ENABLE KEYS */; /*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */; /*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
Python
UTF-8
716
2.84375
3
[]
no_license
class Solution: def maximumMinimumPath(self, A: List[List[int]]) -> int: R, C = len(A), len(A[0]) heap = [(-A[0][0], 0, 0)] visited = [[0 for _ in range(C)] for _ in range(R)] visited[0][0] = 1 directions = [(0, 1), (1, 0), (-1, 0), (0, -1)] while heap: negScore, i, j = heapq.heappop(heap) if i == R - 1 and j == C - 1: return -negScore for x, y in directions: if i + x < 0 or i + x >= R or j + y < 0 or j + y >= C or visited[i+x][j+y] == 1: continue visited[i+x][j+y] = 1 heapq.heappush(heap, (max(negScore, -A[i+x][j+y]), i+x, j+y))
Java
UTF-8
65,537
1.992188
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package PeriodicTable; import java.awt.event.KeyEvent; /** * * @author MKS */ public class Silicon extends javax.swing.JFrame { /** * Creates new form Silicon */ public Silicon() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane8 = new javax.swing.JScrollPane(); jPanel22 = new javax.swing.JPanel(); jPanel23 = new javax.swing.JPanel(); jLabel869 = new javax.swing.JLabel(); jLabel872 = new javax.swing.JLabel(); jLabel873 = new javax.swing.JLabel(); jLabel893 = new javax.swing.JLabel(); jPanel24 = new javax.swing.JPanel(); jButton8 = new javax.swing.JButton(); jLabel980 = new javax.swing.JLabel(); jLabel981 = new javax.swing.JLabel(); jLabel982 = new javax.swing.JLabel(); jLabel983 = new javax.swing.JLabel(); jLabel984 = new javax.swing.JLabel(); jLabel985 = new javax.swing.JLabel(); jLabel986 = new javax.swing.JLabel(); jLabel987 = new javax.swing.JLabel(); jLabel988 = new javax.swing.JLabel(); jLabel989 = new javax.swing.JLabel(); jLabel990 = new javax.swing.JLabel(); jLabel991 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel21 = new javax.swing.JLabel(); jLabel933 = new javax.swing.JLabel(); jLabel936 = new javax.swing.JLabel(); jLabel870 = new javax.swing.JLabel(); jLabel911 = new javax.swing.JLabel(); jLabel943 = new javax.swing.JLabel(); jLabel944 = new javax.swing.JLabel(); jLabel941 = new javax.swing.JLabel(); jLabel942 = new javax.swing.JLabel(); jLabel939 = new javax.swing.JLabel(); jLabel940 = new javax.swing.JLabel(); jLabel947 = new javax.swing.JLabel(); jLabel992 = new javax.swing.JLabel(); jLabel993 = new javax.swing.JLabel(); jLabel976 = new javax.swing.JLabel(); jLabel1016 = new javax.swing.JLabel(); jLabel1060 = new javax.swing.JLabel(); jLabel1042 = new javax.swing.JLabel(); jLabel1047 = new javax.swing.JLabel(); jLabel978 = new javax.swing.JLabel(); jLabel958 = new javax.swing.JLabel(); jLabel994 = new javax.swing.JLabel(); jLabel997 = new javax.swing.JLabel(); jLabel999 = new javax.swing.JLabel(); jLabel995 = new javax.swing.JLabel(); jLabel962 = new javax.swing.JLabel(); jLabel934 = new javax.swing.JLabel(); jLabel935 = new javax.swing.JLabel(); jLabel961 = new javax.swing.JLabel(); jLabel960 = new javax.swing.JLabel(); jLabel932 = new javax.swing.JLabel(); jLabel929 = new javax.swing.JLabel(); jLabel931 = new javax.swing.JLabel(); jLabel930 = new javax.swing.JLabel(); jLabel938 = new javax.swing.JLabel(); jLabel949 = new javax.swing.JLabel(); jLabel912 = new javax.swing.JLabel(); jLabel918 = new javax.swing.JLabel(); jLabel917 = new javax.swing.JLabel(); jLabel920 = new javax.swing.JLabel(); jLabel915 = new javax.swing.JLabel(); jLabel922 = new javax.swing.JLabel(); jLabel923 = new javax.swing.JLabel(); jLabel924 = new javax.swing.JLabel(); jLabel925 = new javax.swing.JLabel(); jLabel926 = new javax.swing.JLabel(); jLabel927 = new javax.swing.JLabel(); jLabel921 = new javax.swing.JLabel(); jLabel919 = new javax.swing.JLabel(); jLabel948 = new javax.swing.JLabel(); jLabel913 = new javax.swing.JLabel(); jLabel914 = new javax.swing.JLabel(); jLabel909 = new javax.swing.JLabel(); jLabel910 = new javax.swing.JLabel(); jLabel908 = new javax.swing.JLabel(); jLabel904 = new javax.swing.JLabel(); jLabel903 = new javax.swing.JLabel(); jLabel907 = new javax.swing.JLabel(); jLabel901 = new javax.swing.JLabel(); jLabel902 = new javax.swing.JLabel(); jLabel899 = new javax.swing.JLabel(); jLabel900 = new javax.swing.JLabel(); jLabel946 = new javax.swing.JLabel(); jLabel964 = new javax.swing.JLabel(); jLabel965 = new javax.swing.JLabel(); jLabel966 = new javax.swing.JLabel(); jLabel945 = new javax.swing.JLabel(); jLabel950 = new javax.swing.JLabel(); jLabel951 = new javax.swing.JLabel(); jLabel952 = new javax.swing.JLabel(); jLabel996 = new javax.swing.JLabel(); jLabel998 = new javax.swing.JLabel(); jLabel895 = new javax.swing.JLabel(); jLabel896 = new javax.swing.JLabel(); jLabel894 = new javax.swing.JLabel(); jLabel928 = new javax.swing.JLabel(); jLabel916 = new javax.swing.JLabel(); jLabel906 = new javax.swing.JLabel(); jLabel905 = new javax.swing.JLabel(); jLabel937 = new javax.swing.JLabel(); jLabel953 = new javax.swing.JLabel(); jLabel954 = new javax.swing.JLabel(); jLabel955 = new javax.swing.JLabel(); jLabel967 = new javax.swing.JLabel(); jLabel977 = new javax.swing.JLabel(); jLabel1017 = new javax.swing.JLabel(); jLabel979 = new javax.swing.JLabel(); jLabel1018 = new javax.swing.JLabel(); jLabel1019 = new javax.swing.JLabel(); jLabel1000 = new javax.swing.JLabel(); jLabel1001 = new javax.swing.JLabel(); jLabel1020 = new javax.swing.JLabel(); jLabel1002 = new javax.swing.JLabel(); jLabel1003 = new javax.swing.JLabel(); jLabel1062 = new javax.swing.JLabel(); jLabel1044 = new javax.swing.JLabel(); jLabel1049 = new javax.swing.JLabel(); jLabel1063 = new javax.swing.JLabel(); jLabel1045 = new javax.swing.JLabel(); jLabel1050 = new javax.swing.JLabel(); jLabel959 = new javax.swing.JLabel(); jLabel1005 = new javax.swing.JLabel(); jLabel1006 = new javax.swing.JLabel(); jLabel1007 = new javax.swing.JLabel(); jLabel1008 = new javax.swing.JLabel(); jLabel1064 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Silicon"); setPreferredSize(new java.awt.Dimension(585, 720)); setResizable(false); jScrollPane8.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); jScrollPane8.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); jScrollPane8.setPreferredSize(new java.awt.Dimension(585, 720)); jPanel22.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel23.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel869.setBackground(new java.awt.Color(255, 255, 255)); jLabel869.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N jLabel869.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel869.setText("<html> <body> <center> <sub> 14</sub> Si</center> </body> </html>"); jLabel869.setOpaque(true); jPanel23.add(jLabel869, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 100, 550, 40)); jLabel872.setBackground(new java.awt.Color(242, 229, 220)); jLabel872.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel872.setIcon(new javax.swing.ImageIcon(getClass().getResource("/PeriodicTable/800px-SiliconCroda.jpg"))); // NOI18N jLabel872.setOpaque(true); jPanel23.add(jLabel872, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 220, 550, -1)); jLabel873.setBackground(new java.awt.Color(255, 255, 255)); jLabel873.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N jLabel873.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel873.setText("Crystalline, reflective with bluish-tinged faces"); jLabel873.setToolTipText(""); jLabel873.setOpaque(true); jPanel23.add(jLabel873, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 180, 550, 40)); jLabel893.setBackground(new java.awt.Color(204, 204, 0)); jLabel893.setFont(new java.awt.Font("Monotype Corsiva", 1, 24)); // NOI18N jLabel893.setForeground(new java.awt.Color(51, 51, 51)); jLabel893.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel893.setText("<html> <body> <center> History</center> </body> </html>"); jLabel893.setOpaque(true); jPanel23.add(jLabel893, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 840, 550, 40)); jPanel24.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)); jButton8.setFont(new java.awt.Font("Perpetua Titling MT", 0, 12)); // NOI18N jButton8.setText("Return To Table"); jButton8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton8ActionPerformed(evt); } }); jButton8.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jButton8KeyPressed(evt); } }); javax.swing.GroupLayout jPanel24Layout = new javax.swing.GroupLayout(jPanel24); jPanel24.setLayout(jPanel24Layout); jPanel24Layout.setHorizontalGroup( jPanel24Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel24Layout.createSequentialGroup() .addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 378, Short.MAX_VALUE)) ); jPanel24Layout.setVerticalGroup( jPanel24Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton8, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 56, Short.MAX_VALUE) ); jPanel23.add(jPanel24, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1)); jLabel980.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel980.setText("Element category"); jLabel980.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel23.add(jLabel980, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 560, 230, 40)); jLabel981.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel981.setText("Metalloid"); jLabel981.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel23.add(jLabel981, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 560, 320, 40)); jLabel982.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel982.setText("Pronunciation"); jLabel982.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel23.add(jLabel982, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 520, 230, 40)); jLabel983.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel983.setText(" \t/ˈsɪlɨkən/ SIL-ə-kən or /ˈsɪlɨkɒn/ SIL-ə-kon"); jLabel983.setToolTipText(""); jLabel983.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel23.add(jLabel983, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 520, 320, 40)); jLabel984.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel984.setText("Group, period, block"); jLabel984.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel23.add(jLabel984, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 600, 230, 40)); jLabel985.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel985.setText("14, 3, p"); jLabel985.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel23.add(jLabel985, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 600, 320, 40)); jLabel986.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel986.setText("Name, symbol, number"); jLabel986.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel23.add(jLabel986, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 480, 230, 40)); jLabel987.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel987.setText("Silicon, Si, 14"); jLabel987.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel23.add(jLabel987, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 480, 320, 40)); jLabel988.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel988.setText("Standard atomic weight"); jLabel988.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel23.add(jLabel988, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 640, 230, 40)); jLabel989.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel989.setText("28.0855(3)"); jLabel989.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel23.add(jLabel989, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 640, 320, 40)); jLabel990.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel990.setText("Electron configuration"); jLabel990.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel23.add(jLabel990, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 680, 230, 160)); jLabel991.setFont(new java.awt.Font("Times New Roman", 1, 12)); // NOI18N jLabel991.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); jLabel991.setIcon(new javax.swing.ImageIcon(getClass().getResource("/PeriodicTable/558px-Electron_shell_014_Silicon.svg.png"))); // NOI18N jLabel991.setText("14:Silicon 2, 8 ,4 "); jLabel991.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jLabel991.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT); jLabel991.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); jPanel23.add(jLabel991, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 680, 320, 160)); jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 12)); // NOI18N jLabel1.setText("<html>\n<body>\n[Ne] 3s<sup>2</sup> 3p<sup>2</sup>\n<br>2, 8, 4\n</body>\n</html>\n\n\n \t\n\n"); jPanel23.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 680, 130, 50)); jLabel4.setBackground(new java.awt.Color(204, 204, 0)); jLabel4.setFont(new java.awt.Font("Monotype Corsiva", 1, 24)); // NOI18N jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel4.setText("<html>\n<body>\n<center>\n\nSilicon\n\n</center>\n</body>\n</html>"); jLabel4.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jLabel4.setOpaque(true); jPanel23.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 60, 550, 40)); jLabel8.setBackground(new java.awt.Color(204, 204, 0)); jLabel8.setFont(new java.awt.Font("Monotype Corsiva", 1, 24)); // NOI18N jLabel8.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel8.setText("Appearance"); jLabel8.setOpaque(true); jPanel23.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 140, 550, 40)); jLabel21.setBackground(new java.awt.Color(204, 204, 0)); jLabel21.setFont(new java.awt.Font("Monotype Corsiva", 1, 24)); // NOI18N jLabel21.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel21.setText("<html> <body> <center> General Properties</center> </body> </html>"); jLabel21.setOpaque(true); jPanel23.add(jLabel21, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 440, 550, 40)); jLabel933.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel933.setText("A. Lavoisier (1787)"); jLabel933.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel23.add(jLabel933, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 880, 320, 40)); jLabel936.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel936.setText("Prediction"); jLabel936.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel23.add(jLabel936, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 880, 230, 40)); jPanel22.add(jPanel23, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1)); jLabel870.setBackground(new java.awt.Color(204, 204, 0)); jLabel870.setFont(new java.awt.Font("Monotype Corsiva", 1, 24)); // NOI18N jLabel870.setForeground(new java.awt.Color(51, 51, 51)); jLabel870.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel870.setText("<html> <body> <center> Most stable isotopes </center> </body> </html>"); jLabel870.setOpaque(true); jPanel22.add(jLabel870, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 2520, 550, 40)); jLabel911.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel911.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel911.setText("Main article: Isotopes of silicon"); jLabel911.setToolTipText(""); jLabel911.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel911, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 2560, 550, 40)); jLabel943.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel943.setText("Thermal conductivity"); jLabel943.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel943, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 2120, 230, 40)); jLabel944.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel944.setText("<html> <body> 149 W·m <sup>−1</sup>·K<sup>−1</sup> </body> </html>"); jLabel944.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel944, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 2120, 320, 40)); jLabel941.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel941.setText("Magnetic ordering"); jLabel941.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel941, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 2040, 230, 40)); jLabel942.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel942.setText("Diamagnetic"); jLabel942.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel942, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 2040, 320, 40)); jLabel939.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel939.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); jLabel939.setIcon(new javax.swing.ImageIcon(getClass().getResource("/PeriodicTable/Diamond.gif"))); // NOI18N jLabel939.setText("Diamond cubic "); jLabel939.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jLabel939.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT); jPanel22.add(jLabel939, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 1920, 320, 120)); jLabel940.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel940.setText("Crystal structure"); jLabel940.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel940, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 1920, 230, 120)); jLabel947.setBackground(new java.awt.Color(204, 204, 0)); jLabel947.setFont(new java.awt.Font("Monotype Corsiva", 1, 24)); // NOI18N jLabel947.setForeground(new java.awt.Color(51, 51, 51)); jLabel947.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel947.setText("<html> <body> <center> Miscellanea</center> </body> </html>"); jLabel947.setOpaque(true); jPanel22.add(jLabel947, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 1880, 550, 40)); jLabel992.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel992.setText("CAS registry number"); jLabel992.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel992, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 2440, 230, 40)); jLabel993.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel993.setText(" \t7440-21-3"); jLabel993.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel993, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 2440, 320, 40)); jLabel976.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel976.setText("Speed of sound (thin rod)"); jLabel976.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel976, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 2200, 230, 40)); jLabel1016.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel1016.setText("<html> <body> (20 °C) 8433 m·s <sup>−1</sup> </body> </html> \t"); jLabel1016.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel1016, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 2200, 320, 40)); jLabel1060.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel1060.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1060.setText("<html> <body> <sup>28</sup>Si</body> </html>"); jLabel1060.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel1060, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 2640, 70, 40)); jLabel1042.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel1042.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1042.setText("92.23%"); jLabel1042.setToolTipText(""); jLabel1042.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel1042, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 2640, 110, 40)); jLabel1047.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel1047.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1047.setText("<html>\n<body>\n<sup>28</sup>Si is stable with 14 neutrons\n</body>\n</html>28Si is stable with 14 neutrons"); jLabel1047.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel1047, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 2640, 370, 40)); jLabel978.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel978.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel978.setText("iso"); jLabel978.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel978, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 2600, 70, 40)); jLabel958.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel958.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel958.setText("NA"); jLabel958.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel958, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 2600, 110, 40)); jLabel994.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel994.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel994.setText("half-life"); jLabel994.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel994, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 2600, 90, 40)); jLabel997.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel997.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel997.setText("DM \t"); jLabel997.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel997, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 2600, 80, 40)); jLabel999.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel999.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel999.setText("DE (MeV)"); jLabel999.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel999, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 2600, 120, 40)); jLabel995.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel995.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel995.setText("DP"); jLabel995.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel995, new org.netbeans.lib.awtextra.AbsoluteConstraints(470, 2600, 80, 40)); jLabel962.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel962.setText("Covalent radius"); jLabel962.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel962, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 1800, 230, 40)); jLabel934.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel934.setText("Van der Waals radius"); jLabel934.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel934, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 1840, 230, 40)); jLabel935.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel935.setText("210 pm"); jLabel935.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel935, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 1840, 320, 40)); jLabel961.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel961.setText("<html> <body> 3rd: 3231.6 kJ·mol <sup>−1</sup> </body> </html>"); jLabel961.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel961, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 1720, 320, 40)); jLabel960.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel960.setText("<html> <body> 1st: 786.5 kJ·mol <sup>−1</sup> </body> </html> "); jLabel960.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel960, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 1640, 320, 40)); jLabel932.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel932.setText("Ionization energies (more)"); jLabel932.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel932, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 1640, 230, 120)); jLabel929.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel929.setText("Oxidation states"); jLabel929.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel929, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 1560, 230, 40)); jLabel931.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel931.setText("4, 3, 2, 1, -1, -2, -3, -4 (amphoteric oxide)"); jLabel931.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel931, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 1560, 320, 40)); jLabel930.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel930.setText("Electronegativity"); jLabel930.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel930, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 1600, 230, 40)); jLabel938.setBackground(new java.awt.Color(204, 204, 0)); jLabel938.setFont(new java.awt.Font("Monotype Corsiva", 1, 24)); // NOI18N jLabel938.setForeground(new java.awt.Color(51, 51, 51)); jLabel938.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel938.setText("<html> <body> <center> Atomic properties</center> </body> </html>"); jLabel938.setOpaque(true); jPanel22.add(jLabel938, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 1520, 550, 40)); jLabel949.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel949.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel949.setText("P (Pa)"); jLabel949.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel949, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 1440, 120, 40)); jLabel912.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel912.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel912.setText("at T (K)"); jLabel912.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel912, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 1480, 120, 40)); jLabel918.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel918.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel918.setText("1"); jLabel918.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel918, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 1440, 60, 40)); jLabel917.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel917.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel917.setText(" \t2102"); jLabel917.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel917, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 1480, 60, 40)); jLabel920.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel920.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel920.setText("10"); jLabel920.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel920, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 1440, 60, 40)); jLabel915.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel915.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel915.setText("1908"); jLabel915.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel915, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 1480, 60, 40)); jLabel922.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel922.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel922.setText("100"); jLabel922.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel922, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 1440, 60, 40)); jLabel923.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel923.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel923.setText("2339"); jLabel923.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel923, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 1480, 60, 40)); jLabel924.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel924.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel924.setText("1 k"); jLabel924.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel924, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 1440, 70, 40)); jLabel925.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel925.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel925.setText("2636 \t"); jLabel925.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel925, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 1480, 70, 40)); jLabel926.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel926.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel926.setText("10 k"); jLabel926.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel926, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 1440, 80, 40)); jLabel927.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel927.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel927.setText("3021"); jLabel927.setToolTipText(""); jLabel927.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel927, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 1480, 80, 40)); jLabel921.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel921.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel921.setText("100 k"); jLabel921.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel921, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 1440, 100, 40)); jLabel919.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel919.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel919.setText("3537"); jLabel919.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel919, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 1480, 100, 40)); jLabel948.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel948.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel948.setText("Vapor pressure "); jLabel948.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel948, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 1400, 550, 40)); jLabel913.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel913.setText("<html> <body> 19.789 J·mol <sup>−1</sup> ·K<sup>−1</sup> </body> </html> "); jLabel913.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel913, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 1360, 320, 40)); jLabel914.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel914.setText("Molar heat capacity"); jLabel914.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel914, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 1360, 230, 40)); jLabel909.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel909.setText("Heat of vaporization"); jLabel909.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel909, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 1320, 230, 40)); jLabel910.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel910.setText("<html> <body>359 kJ·mol <sup>−1</sup> </body> </html>"); jLabel910.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel910, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 1320, 320, 40)); jLabel908.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel908.setText("<html> <body> 50.21 kJ·mol <sup>−1</sup> </body> </html>"); jLabel908.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel908, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 1280, 320, 40)); jLabel904.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel904.setText(" \t3538 K, 3265 °C, 5909 °F"); jLabel904.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel904, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 1240, 320, 40)); jLabel903.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel903.setText("Boiling point"); jLabel903.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel903, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 1240, 230, 40)); jLabel907.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel907.setText("Heat of fusion"); jLabel907.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel907, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 1280, 230, 40)); jLabel901.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel901.setText("Melting point"); jLabel901.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel901, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 1200, 230, 40)); jLabel902.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel902.setText("1687 K, 1414 °C, 2577 °F"); jLabel902.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel902, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 1200, 320, 40)); jLabel899.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel899.setText("Liquid density at m.p."); jLabel899.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel899, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 1160, 230, 40)); jLabel900.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel900.setText("<html> <body>2.57 g·cm <sup>−3</sup> </body> </html>"); jLabel900.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel900, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 1160, 320, 40)); jLabel946.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel946.setText("1.90 (Pauling scale)"); jLabel946.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel946, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 1600, 320, 40)); jLabel964.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel964.setText("<html> <body> 2nd: 1577.1 kJ·mol <sup>−1</sup> </body> </html>"); jLabel964.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel964, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 1680, 320, 40)); jLabel965.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel965.setText("Atomic radius"); jLabel965.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel965, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 1760, 230, 40)); jLabel966.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel966.setText("111 pm"); jLabel966.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel966, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 1800, 320, 40)); jLabel945.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel945.setText("Electrical resistivity"); jLabel945.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel945, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 2080, 230, 40)); jLabel950.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel950.setText("<html> <body>(20 °C) 10 Ω·m </body> </html>"); jLabel950.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel950, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 2080, 320, 40)); jLabel951.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel951.setText("Thermal expansion"); jLabel951.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel951, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 2160, 230, 40)); jLabel952.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel952.setText("<html> <body>(25 °C) 2.6 µm.m <sup>−1</sup>·K<sup>−1</sup> </body> </html>"); jLabel952.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel952, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 2160, 320, 40)); jLabel996.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel996.setText("Mohs hardness"); jLabel996.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel996, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 2400, 230, 40)); jLabel998.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel998.setText(" \t7"); jLabel998.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel998, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 2400, 320, 40)); jLabel895.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel895.setText("Solid"); jLabel895.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel895, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 1080, 320, 40)); jLabel896.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel896.setText("Phase"); jLabel896.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel896, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 1080, 230, 40)); jLabel894.setBackground(new java.awt.Color(204, 204, 0)); jLabel894.setFont(new java.awt.Font("Monotype Corsiva", 1, 24)); // NOI18N jLabel894.setForeground(new java.awt.Color(51, 51, 51)); jLabel894.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel894.setText("<html> <body> <center> Physical Properties </center> </body> </html>"); jLabel894.setOpaque(true); jPanel22.add(jLabel894, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 1040, 550, 40)); jLabel928.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel928.setText("J. Berzelius (1824)"); jLabel928.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel928, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 960, 320, 40)); jLabel916.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel916.setText("First isolation"); jLabel916.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel916, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 960, 230, 40)); jLabel906.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel906.setText("J. Berzelius (1824)"); jLabel906.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel906, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 920, 320, 40)); jLabel905.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel905.setText("Discovery"); jLabel905.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel905, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 920, 230, 40)); jLabel937.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel937.setText("Named by"); jLabel937.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel937, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 1000, 230, 40)); jLabel953.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel953.setText(" \tT. Thomson (1831)"); jLabel953.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel953, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 1000, 320, 40)); jLabel954.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel954.setText("Density (near r.t.)"); jLabel954.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel954, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 1120, 230, 40)); jLabel955.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel955.setText("<html> <body>2.3290 g·cm <sup>−3</sup> </body> </html>"); jLabel955.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel955, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 1120, 320, 40)); jLabel967.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel967.setText("111 pm"); jLabel967.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel967, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 1760, 320, 40)); jLabel977.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel977.setText("Young's modulus"); jLabel977.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel977, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 2240, 230, 40)); jLabel1017.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel1017.setText("130-188 GPa"); jLabel1017.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel1017, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 2240, 320, 40)); jLabel979.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel979.setText("Shear modulus"); jLabel979.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel979, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 2280, 230, 40)); jLabel1018.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel1018.setText(" \t51-80 GPa"); jLabel1018.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel1018, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 2280, 320, 40)); jLabel1019.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel1019.setText(" \t97.6 GPa"); jLabel1019.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel1019, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 2320, 320, 40)); jLabel1000.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel1000.setText("Bulk modulus"); jLabel1000.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel1000, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 2320, 230, 40)); jLabel1001.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel1001.setText("Poisson ratio"); jLabel1001.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel1001, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 2360, 230, 40)); jLabel1020.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel1020.setText("0.064 - 0.28"); jLabel1020.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel1020, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 2360, 320, 40)); jLabel1002.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel1002.setText("1.12 eV"); jLabel1002.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel1002, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 2480, 320, 40)); jLabel1003.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel1003.setText("Band gap energy at 300 K"); jLabel1003.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel1003, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 2480, 230, 40)); jLabel1062.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel1062.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1062.setText("<html> <body> <sup>29</sup>Si</body> </html>"); jLabel1062.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel1062, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 2680, 70, 40)); jLabel1044.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel1044.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1044.setText("4.67%"); jLabel1044.setToolTipText(""); jLabel1044.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel1044, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 2680, 110, 40)); jLabel1049.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel1049.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1049.setText("<html> <body> <sup>29</sup>Si is stable with 15 neutrons </body> </html>28Si is stable with 14 neutrons"); jLabel1049.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel1049, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 2680, 370, 40)); jLabel1063.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel1063.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1063.setText("<html> <body> <sup>32</sup>Si</body> </html>"); jLabel1063.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel1063, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 2760, 70, 40)); jLabel1045.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel1045.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1045.setText("3.1%"); jLabel1045.setToolTipText(""); jLabel1045.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel1045, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 2720, 110, 40)); jLabel1050.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel1050.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1050.setText("<html> <body> <sup>30</sup>Si is stable with 16 neutrons </body> </html>28Si is stable with 14 neutrons"); jLabel1050.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel1050, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 2720, 370, 40)); jLabel959.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel959.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel959.setText("trace"); jLabel959.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel959, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 2760, 110, 40)); jLabel1005.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel1005.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1005.setText("170 y"); jLabel1005.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel1005, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 2760, 90, 40)); jLabel1006.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel1006.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1006.setText("<html>\n<body>\nβ<sup>−</sup>\n</body>\n</html>"); jLabel1006.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel1006, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 2760, 80, 40)); jLabel1007.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel1007.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1007.setText("13.020"); jLabel1007.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel1007, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 2760, 120, 40)); jLabel1008.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel1008.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1008.setText("<html> <body> <sup>32</sup>P</body> </html>"); jLabel1008.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel1008, new org.netbeans.lib.awtextra.AbsoluteConstraints(470, 2760, 80, 40)); jLabel1064.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel1064.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1064.setText("<html> <body> <sup>30</sup>Si</body> </html>"); jLabel1064.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jPanel22.add(jLabel1064, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 2720, 70, 40)); jScrollPane8.setViewportView(jPanel22); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane8, javax.swing.GroupLayout.DEFAULT_SIZE, 575, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed Periodic_TableNew Tab = new Periodic_TableNew(); Tab.setVisible(true); this.setVisible(false); }//GEN-LAST:event_jButton8ActionPerformed private void jButton8KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jButton8KeyPressed if (evt.getKeyCode() == KeyEvent.VK_BACK_SPACE) { Periodic_TableNew Tab = new Periodic_TableNew(); Tab.setVisible(true); this.setVisible(false); } }//GEN-LAST:event_jButton8KeyPressed /** * @param args the command line arguments */ public static void main(String args[]) { /* * Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* * If Nimbus (introduced in Java SE 6) is not available, stay with the * default look and feel. For details see * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Silicon.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Silicon.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Silicon.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Silicon.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* * Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Silicon().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton8; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel1000; private javax.swing.JLabel jLabel1001; private javax.swing.JLabel jLabel1002; private javax.swing.JLabel jLabel1003; private javax.swing.JLabel jLabel1005; private javax.swing.JLabel jLabel1006; private javax.swing.JLabel jLabel1007; private javax.swing.JLabel jLabel1008; private javax.swing.JLabel jLabel1016; private javax.swing.JLabel jLabel1017; private javax.swing.JLabel jLabel1018; private javax.swing.JLabel jLabel1019; private javax.swing.JLabel jLabel1020; private javax.swing.JLabel jLabel1042; private javax.swing.JLabel jLabel1044; private javax.swing.JLabel jLabel1045; private javax.swing.JLabel jLabel1047; private javax.swing.JLabel jLabel1049; private javax.swing.JLabel jLabel1050; private javax.swing.JLabel jLabel1060; private javax.swing.JLabel jLabel1062; private javax.swing.JLabel jLabel1063; private javax.swing.JLabel jLabel1064; private javax.swing.JLabel jLabel21; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel869; private javax.swing.JLabel jLabel870; private javax.swing.JLabel jLabel872; private javax.swing.JLabel jLabel873; private javax.swing.JLabel jLabel893; private javax.swing.JLabel jLabel894; private javax.swing.JLabel jLabel895; private javax.swing.JLabel jLabel896; private javax.swing.JLabel jLabel899; private javax.swing.JLabel jLabel900; private javax.swing.JLabel jLabel901; private javax.swing.JLabel jLabel902; private javax.swing.JLabel jLabel903; private javax.swing.JLabel jLabel904; private javax.swing.JLabel jLabel905; private javax.swing.JLabel jLabel906; private javax.swing.JLabel jLabel907; private javax.swing.JLabel jLabel908; private javax.swing.JLabel jLabel909; private javax.swing.JLabel jLabel910; private javax.swing.JLabel jLabel911; private javax.swing.JLabel jLabel912; private javax.swing.JLabel jLabel913; private javax.swing.JLabel jLabel914; private javax.swing.JLabel jLabel915; private javax.swing.JLabel jLabel916; private javax.swing.JLabel jLabel917; private javax.swing.JLabel jLabel918; private javax.swing.JLabel jLabel919; private javax.swing.JLabel jLabel920; private javax.swing.JLabel jLabel921; private javax.swing.JLabel jLabel922; private javax.swing.JLabel jLabel923; private javax.swing.JLabel jLabel924; private javax.swing.JLabel jLabel925; private javax.swing.JLabel jLabel926; private javax.swing.JLabel jLabel927; private javax.swing.JLabel jLabel928; private javax.swing.JLabel jLabel929; private javax.swing.JLabel jLabel930; private javax.swing.JLabel jLabel931; private javax.swing.JLabel jLabel932; private javax.swing.JLabel jLabel933; private javax.swing.JLabel jLabel934; private javax.swing.JLabel jLabel935; private javax.swing.JLabel jLabel936; private javax.swing.JLabel jLabel937; private javax.swing.JLabel jLabel938; private javax.swing.JLabel jLabel939; private javax.swing.JLabel jLabel940; private javax.swing.JLabel jLabel941; private javax.swing.JLabel jLabel942; private javax.swing.JLabel jLabel943; private javax.swing.JLabel jLabel944; private javax.swing.JLabel jLabel945; private javax.swing.JLabel jLabel946; private javax.swing.JLabel jLabel947; private javax.swing.JLabel jLabel948; private javax.swing.JLabel jLabel949; private javax.swing.JLabel jLabel950; private javax.swing.JLabel jLabel951; private javax.swing.JLabel jLabel952; private javax.swing.JLabel jLabel953; private javax.swing.JLabel jLabel954; private javax.swing.JLabel jLabel955; private javax.swing.JLabel jLabel958; private javax.swing.JLabel jLabel959; private javax.swing.JLabel jLabel960; private javax.swing.JLabel jLabel961; private javax.swing.JLabel jLabel962; private javax.swing.JLabel jLabel964; private javax.swing.JLabel jLabel965; private javax.swing.JLabel jLabel966; private javax.swing.JLabel jLabel967; private javax.swing.JLabel jLabel976; private javax.swing.JLabel jLabel977; private javax.swing.JLabel jLabel978; private javax.swing.JLabel jLabel979; private javax.swing.JLabel jLabel980; private javax.swing.JLabel jLabel981; private javax.swing.JLabel jLabel982; private javax.swing.JLabel jLabel983; private javax.swing.JLabel jLabel984; private javax.swing.JLabel jLabel985; private javax.swing.JLabel jLabel986; private javax.swing.JLabel jLabel987; private javax.swing.JLabel jLabel988; private javax.swing.JLabel jLabel989; private javax.swing.JLabel jLabel990; private javax.swing.JLabel jLabel991; private javax.swing.JLabel jLabel992; private javax.swing.JLabel jLabel993; private javax.swing.JLabel jLabel994; private javax.swing.JLabel jLabel995; private javax.swing.JLabel jLabel996; private javax.swing.JLabel jLabel997; private javax.swing.JLabel jLabel998; private javax.swing.JLabel jLabel999; private javax.swing.JPanel jPanel22; private javax.swing.JPanel jPanel23; private javax.swing.JPanel jPanel24; private javax.swing.JScrollPane jScrollPane8; // End of variables declaration//GEN-END:variables }
C++
UTF-8
909
3.25
3
[]
no_license
#include <iostream> #include <string> using namespace std; int len = 0; int insert = 0; int queue[10000]; int head = 0; int push(int x) { queue[insert] = x; insert++; len++; return 0; } void pop() { if (!len) { cout << -1 << endl; return; } cout << queue[head] << endl; head++; len--; return; } void front() { if (!len) cout << -1 << endl; else cout << queue[head] << endl; return; } void back() { if (!len) cout << -1 << endl; else cout << queue[insert-1] << endl; return; } int main() { int T; cin >> T; string text; int a; for (int i = 0; i < T; i++) { cin >> text; if (text == "push") { cin >> a; push(a); } else if (text == "pop") pop(); else if (text == "size") cout << len << endl; else if (text == "empty") { if (len) cout << 0 << endl; else cout << 1 << endl; } else if (text == "front") front(); else if (text == "back") back(); } }
Python
UTF-8
254
3.734375
4
[]
no_license
dict = {} array = [1, 7, 5, 9, 2, 12, 3] count = 0 for i in range(len(array)): for j in range(i+1, len(array)): if abs(array[i]-array[j]) == 2: dict[count] = f'{array[i]},{array[j]}' count += 1 print(len(dict))
Java
UTF-8
1,200
3.65625
4
[]
no_license
//Hassan M. Khan //Principles of Programming Languages //Lab 1 package Lab1; import java.util.*; import java.io.*; //This class will read the input file, and then return an Array of Strings, //with each element of the Array being one line of the input file. //The code for reading and writing to a file has been implemented from Stackoverflow. public final class InOut { public static ArrayList<String> readfile(String a) { ArrayList<String> data = new ArrayList<String>(); try (BufferedReader br = new BufferedReader(new FileReader(a))) { String line; while ((line = br.readLine()) != null) { //Processing the line data.add(line.trim()); } }catch (Exception e) { System.err.println(e.getMessage()); } return data; } public static void writetofile(ArrayList<String> b, String c) throws IOException { File fout = new File(c); FileOutputStream fos = new FileOutputStream(fout); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos)); for (int i = 0; i < b.size(); i++) { bw.write(b.get(i)); bw.newLine(); } bw.close(); } }
Java
UTF-8
4,924
3.09375
3
[]
no_license
package oldHomeWorkAssignment; import newHomeworkAssignment.people.*; import java.util.ArrayList; public class Prog { ArrayList<User> usersAndEmployees; // общий лист ArrayList<User> peopleWithMailGmailMail; // лист для почты @gmail и @mail ArrayList<User> mailEmployeesWomen; public Prog() { mailEmployeesWomen = new ArrayList<>(); peopleWithMailGmailMail = new ArrayList<>(); usersAndEmployees = new ArrayList<>(); usersAndEmployees.add(new User("Иван Иванов", 30, "мужчина", "[email protected]", "Украина")); usersAndEmployees.add(new User("Марта Мартынова", 28, "женщина", "[email protected]", "Украина")); usersAndEmployees.add(new User("Петя Петеньков", 17, "мужчина", "[email protected]", "Россия")); usersAndEmployees.add(new User("Васелиса Петенькова", 14, "женщина", "[email protected]", "Россия")); usersAndEmployees.add(new User("Фёдор Федорчиков", 42, "мужчина", "[email protected]", "Украина")); usersAndEmployees.add(new Employee("Лариса Ларькина", 26, "женщина", "[email protected]", "Россия", 1000, "менеджер", "отдел продаж")); usersAndEmployees.add(new Employee("Максим Максимов", 23, "мужчина", "[email protected]", "Украина", 800, "Тестировщик", "Отдел разработки ПО")); usersAndEmployees.add(new Employee("Карина Каривчановна", 22, "Женщина", "[email protected]", "Россия", 900, "Дизайнер", "3D-дизайнер")); usersAndEmployees.add(new Employee("Светлана Светланько", 31, "Женщина", "[email protected]", "Украина", 600, "Бугалтер", "Бугалтерия")); usersAndEmployees.add(new Employee("Виталий Переданков", 32, "Мужчина", "[email protected]", "Украина", 1500, "Android-Developer", "Отдел разработки ПО")); usersAndEmployees.add(new Employee("Ольга Олефандровна ", 28, "Женщина", "[email protected]", "Украина", 400, "Бугалтер", "Бугалтерия")); } public void run() { System.out.println("Общий средний возраст"); System.out.println(overallAverageAge() + " лет"); System.out.println(); System.out.println("Средний возраст до 18 лет"); System.out.println(averageAgeUnder18() + " лет"); System.out.println(); System.out.println(); java.lang.System.out.println("Люди у которых почта @gmail.com или @mail.ru"); System.out.println(); peopleWithMailGmailMail = email(); showAll(); System.out.println(); System.out.println(); System.out.println("Все почты, сотрудников, женщин до 30 лет"); System.out.println(); peopleWithMailGmailMail = mailEmployeesWomenUnder30(); showAll(); } // вывод на экран почту @gmail.com или @mail.ru public void showAll() { for (User user : peopleWithMailGmailMail) { System.out.println(user); } } // общий средний возраст public int overallAverageAge() { int num = 0; for (int i = 0; i < usersAndEmployees.size(); i++) { num += usersAndEmployees.get(i).getAGE(); } num /= usersAndEmployees.size(); return num; } // средний возраст среди не совершеннолетних public int averageAgeUnder18() { int val = 0; int count = 0; for (User ageUnder18 : usersAndEmployees) { if (ageUnder18.getAGE() < 18) { val += ageUnder18.getAGE(); count++; } } return val / count; } // почта @gmail.com или @mail.ru public ArrayList<User> email() { String[] mail; for (User people : usersAndEmployees) { mail = people.getMAIL().split("@"); if (mail[1].equalsIgnoreCase("gmail.com") || mail[1].equalsIgnoreCase("mail.ru")) { peopleWithMailGmailMail.add(people); } } return peopleWithMailGmailMail; } // почта женщин сотрудников до 30 лет public ArrayList<User> mailEmployeesWomenUnder30() { for (User people : usersAndEmployees) { if (people instanceof Employee && people.getGENDER().equalsIgnoreCase("женщина") && people.getAGE() < 30) { mailEmployeesWomen.add(people); } } return mailEmployeesWomen; } }
Java
UTF-8
2,379
2.359375
2
[]
no_license
package ru.netis.bird.develop.dialogfragment; import android.app.DialogFragment; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; public class MainActivity extends AppCompatActivity implements DialogCloseCallBack, LoginDialogFragment.OnLoginCallback { DialogFragment dlg1; DialogFragment dlg2; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); dlg1 = new Dialog1(this); dlg2 = new Dialog2(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_login) { LoginDialogFragment dialog = new LoginDialogFragment(); dialog.show(getSupportFragmentManager(), LoginDialogFragment.TAG); return true; } return super.onOptionsItemSelected(item); } public void onClick(View v) { switch (v.getId()) { case R.id.btnDlg1: dlg1.show(getFragmentManager(), "dlg1"); break; case R.id.btnDlg2: dlg2.show(getFragmentManager(), "dlg2"); break; case R.id.btnDlg3: Intent intent = new Intent(this, PaymentsActivity.class); startActivity(intent); break; default: break; } } @Override public void dialogCloseEvent(String result) { Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show(); } @Override public void onLogin(String SID) { Toast.makeText(MainActivity.this, SID, Toast.LENGTH_SHORT).show(); } }
C++
ISO-8859-1
698
2.8125
3
[]
no_license
#include <iostream> #include <locale.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char** argv) { setlocale(LC_ALL,""); int notas[3]; float media; printf("\t\t Programa de notas escolares 2021!"); for(int i = 1; i <= 4; i++){ printf("\n\n Entre com a nota do bimestre: %d\n", i); scanf("%d", &notas[i-1]); } media = (notas[0] + notas[1] + notas[2] + notas[3]) / 4; printf("%f", media); if(media < 6) printf("\n\n Voc no foi aprovado, envie um e-mail para a secretaria para refazer as matrias deste ano\n"); if(media >= 6) printf("\n\n Parabns!! Voc foi aprovado, at o ano que vem!!"); return 0; }
Python
UTF-8
186
2.796875
3
[]
no_license
import numpy as np m=np.zeros(10**3+1) for a in range(1,10**3): for b in range(1,a+1): h=(a**2+b**2)**0.5 if h%1==0 and a+b+h<=10**3: p=a+b+int(h) m[p]+=1 print(np.argmax(m))
C++
UTF-8
3,827
2.96875
3
[]
no_license
#include "catch.hpp" #include "Enum.h" #include "ItemQ1.h" #include "SaleQ1.h" #include "ItemQ2.h" #include "SaleQ2.h" #include "ItemQ3.h" #include "SaleQ3.h" #include "ItemQ4.h" #include "ItemQ5.h" #include "saleCreator.h" #include "SaleAbstractQ4.h" #include "SaleAbstractQ5.h" #include "saleCreatorQ5.h" using namespace std; TEST_CASE("Question 1", "[Q1]") { //creating item ItemQ1 test("test", 5.00, 2); SaleQ1 sale; //test item properties REQUIRE(test.getName() == "test"); REQUIRE(test.getQuantity() == 2); REQUIRE(test.getUnitPrice() == 5.00); REQUIRE(test.getItemTotal() == 10.00); sale.addItem(test); //test sale properties REQUIRE(sale.getDiscountRate() == .05); REQUIRE(sale.getSubTotal() == 10.00); REQUIRE(sale.getDiscount() == .50); REQUIRE(sale.getDiscountedSubtotal() == 9.50); } TEST_CASE("Question 2", "[Q2]") { //creating item ItemQ2 test("test", 5.00, 2); SaleQ2 sale; sale.addItem(test); //test various rates according to DiscountType REQUIRE(sale.getDiscountRate(senior) == .10); REQUIRE(sale.getDiscountRate(standard) == .05); REQUIRE(sale.getDiscountRate(preferred) == .15); REQUIRE(sale.getDiscount(senior) == 1.00); REQUIRE(sale.getDiscount(preferred) == 1.50); REQUIRE(sale.getDiscount(standard) == .50); } TEST_CASE("Question 3", "[Q3]") { //creating item ItemQ3 test("test", 5.00, 2); SaleQ3 sale; sale.addItem(test); sale.setWeekday(3); REQUIRE(sale.getWeekday() == 3); REQUIRE(sale.getDiscountRate(senior) == .10); sale.setWeekday(2); REQUIRE(sale.getDiscountRate(senior) != .10); REQUIRE(sale.getDiscountRate(senior) == .05); } TEST_CASE("Question 4", "[Q4]") { //creating item ItemQ4 test("test", 5.00, 2); // sale factory saleCreator creator; //make item SaleAbstractQ4* saleTest1 = creator.create(senior, 3); SaleAbstractQ4* saleTest2 = creator.create(senior, 2); SaleAbstractQ4* saleTest3 = creator.create(preferred, 3); SaleAbstractQ4* saleTest4 = creator.create(standard, 3); saleTest1->addItem(test); saleTest2->addItem(test); saleTest3->addItem(test);saleTest4->addItem(test); //test senior object creation REQUIRE(saleTest1->getDiscountRate() == .10); REQUIRE(saleTest2->getDiscountRate() == .05); REQUIRE(saleTest3->getDiscountRate() == .15); REQUIRE(saleTest4->getDiscountRate() == .05); //does the final discount work? REQUIRE(saleTest1->getDiscountedSubtotal() == 9.00); } TEST_CASE("Question 5", "[Q5]") { //create sales map of the day map<string, pair<int, double>> todaysDiscounts; todaysDiscounts.insert(make_pair("test",make_pair(2, .5))); //factory start saleCreatorQ5 creator; SaleAbstractQ5* saleTest = creator.create(senior, 3); saleTest->setItemsOnSale(todaysDiscounts); SECTION("item exists in discount map") { ItemQ5 test("test", 5.00, 3); saleTest->addItem(test); //the subtotal should now reflect the 3 initial items, and then the 1 discounted item. REQUIRE(saleTest->getSubTotal() == 12.50); //and the final total should be discounted by the senior discount REQUIRE(saleTest->getDiscountedSubtotal() == 11.25); } SECTION("item does not exist in discount map") { ItemQ5 test("noexist", 5.00, 3); saleTest->addItem(test); //the subtotal should now reflect the 3 initial items, and then the 1 discounted item. REQUIRE(saleTest->getSubTotal() == 15.00); } SECTION("item exists but quantity is exactly the threshold") { ItemQ5 test("test", 5.00, 2); saleTest->addItem(test); //the subtotal should now reflect the 3 initial items, and then the 1 discounted item. REQUIRE(saleTest->getSubTotal() == 10.00); } SECTION("item exists but quantity is below the threshold") { ItemQ5 test("test", 5.00, 1); saleTest->addItem(test); //the subtotal should now reflect the 3 initial items, and then the 1 discounted item. REQUIRE(saleTest->getSubTotal() == 5.00); } }
Python
UTF-8
2,156
2.953125
3
[ "Apache-2.0" ]
permissive
from elasticsearch_dsl import field def test_custom_field_car_wrap_other_field(): class MyField(field.CustomField): @property def builtin_type(self): return field.Text(**self._params) assert {'type': 'text', 'index': 'not_analyzed'} == MyField(index='not_analyzed').to_dict() def test_field_from_dict(): f = field.construct_field({'type': 'text', 'index': 'not_analyzed'}) assert isinstance(f, field.Text) assert {'type': 'text', 'index': 'not_analyzed'} == f.to_dict() def test_multi_fields_are_accepted_and_parsed(): f = field.construct_field( 'text', fields={ 'raw': {'type': 'keyword'}, 'eng': field.Text(analyzer='english'), } ) assert isinstance(f, field.Text) assert { 'type': 'text', 'fields': { 'raw': {'type': 'keyword'}, 'eng': {'type': 'text', 'analyzer': 'english'}, } } == f.to_dict() def test_modifying_nested(): f = field.Nested() f.field('name', 'text', index='not_analyzed') assert { 'type': 'nested', 'properties': { 'name': {'type': 'text', 'index': 'not_analyzed'} }, } == f.to_dict() def test_nested_provides_direct_access_to_its_fields(): f = field.Nested() f.field('name', 'text', index='not_analyzed') assert 'name' in f assert f['name'] == field.Text(index='not_analyzed') def test_field_supports_multiple_analyzers(): f = field.Text(analyzer='snowball', search_analyzer='keyword') assert {'analyzer': 'snowball', 'search_analyzer': 'keyword', 'type': 'text'} == f.to_dict() def test_multifield_supports_multiple_analyzers(): f = field.Text(fields={ 'f1': field.Text(search_analyzer='keyword', analyzer='snowball'), 'f2': field.Text(analyzer='keyword') }) assert { 'fields': { 'f1': {'analyzer': 'snowball', 'search_analyzer': 'keyword', 'type': 'text' }, 'f2': { 'analyzer': 'keyword', 'type': 'text'} }, 'type': 'text' } == f.to_dict()
PHP
UTF-8
1,947
2.765625
3
[ "MIT" ]
permissive
<?php namespace Tunacan\Bundle\Controller; use Tunacan\Bundle\Component\UIComponent\CardListNode; use Tunacan\Bundle\Service\UIComponentServiceInterface; use Tunacan\MVC\BaseController; use Tunacan\Bundle\Service\CardServiceInterface; use Tunacan\Bundle\DataObject\CardDTO; class ListController extends BaseController { /** * @Inject * @var CardServiceInterface */ private $cardService; /** * @Inject * @var UIComponentServiceInterface */ private $uiService; public function run(): string { try { $bbsUID = $this->request->getUriArguments('bbsUID'); $page = $this->request->getUriArguments('page'); $cardDTOList = $this->cardService->getCardListByBbsUID($bbsUID, $page); $previousBtn = ($page <= 1) ? 'hide' : ''; $nextBtn = (sizeof($cardDTOList) < 10) ? 'hide' : ''; $this->response->addAttribute('bbs_uid', $bbsUID); $this->response->addAttribute('card_list', $this->getCardList($cardDTOList)); $this->response->addAttribute('previous_btn', $previousBtn); $this->response->addAttribute('next_btn', $nextBtn); $this->response->addAttribute('previous_page', $page - 1); $this->response->addAttribute('next_page', $page + 1); return 'list'; } catch (\Exception $e) { $this->response->addHeader('HTTP/1.1 500 Internal Server Error'); $this->response->addAttribute('error_title', $e->getMessage()); return 'error'; } } /** * @param CardDTO[] $cardDTOList * @return string */ private function getCardList(array $cardDTOList) { return array_reduce( $this->uiService->drawCardList($cardDTOList), function (string $carry, CardListNode $cardListNode) { return $carry . $cardListNode; }, ''); } }
TypeScript
UTF-8
1,775
3.015625
3
[ "MIT" ]
permissive
import { State } from "state/state_system/State"; /** * This class extends the Map class to allow for state tracking * It notifies subscribers of key changes as if it where `stateProperties`. */ export class StateMap<K, V> extends State implements Map<K, V> { private map: Map<K, V> = new Map<K, V>(); public get size(): number { this.recordRead(); return this.map.size; } public clear(): void { this.dispatchStateEvent(); this.map.clear(); } public delete(key: K): boolean { this.dispatchStateEvent(key.toString()); return this.map.delete(key); } public forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: any): void { this.recordRead(); this.map.forEach(callbackfn, thisArg); } public get(key: K): V | undefined { this.recordRead(key.toString()); return this.map.get(key); } public has(key: K): boolean { this.recordRead(key.toString()); return this.map.has(key); } public set(key: K, value: V): this { this.map.set(key, value); this.dispatchStateEvent(key.toString()); return this; } public entries(): IterableIterator<[K, V]> { this.recordRead(); return this.map.entries(); } public keys(): IterableIterator<K> { this.recordRead(); return this.map.keys(); } public values(): IterableIterator<V> { this.recordRead(); return this.map.values(); } public [Symbol.iterator](): IterableIterator<[K, V]> { this.recordRead(); return this.map[Symbol.iterator](); } public get [Symbol.toStringTag](): string { return this.map[Symbol.toStringTag]; } }
Java
UTF-8
336
2.4375
2
[]
no_license
package ua.dp.mign.locale.format; import java.util.Date; import java.text.SimpleDateFormat; class PatternFormatDate { public static void main(String[] args) { String pattern = "dd-MM-yy"; SimpleDateFormat formatter = new SimpleDateFormat(pattern); System.out.println(formatter.format(new Date())); } }
Shell
UTF-8
1,043
4.03125
4
[]
no_license
#!/bin/bash # Tell the script to fail if an attempt is made to use an un-set (null) variable. # This helps prevent accidental breakages. set -u # Tell the script to exit if any statement returns a non-true return value. # The benefit of using -e is that it prevents errors snowballing into serious # issues when they could have been caught earlier. set -e FILE=$1 LOG_FILE=/tmp/image-uploader.log echo "$(date '+%a %d %b %Y %X') - Uploading picture file: $FILE" >> $LOG_FILE /opt/motion-uploader/uploader.py /opt/motion-uploader/uploader.cfg "$FILE" snap >> $LOG_FILE 2>&1 echo "$(date '+%a %d %b %Y %X') - Upload of picture file: $FILE completed" >> $LOG_FILE if [ -f "$FILE" ]; then echo "$(date '+%a %d %b %Y %X') - Deleting uploaded file $FILE from local storage..." >> $LOG_FILE rm $FILE >> $LOG_FILE 2>&1 echo "$(date '+%a %d %b %Y %X') - File $FILE successfully deleted." >> $LOG_FILE else echo "$(date '+%a %d %b %Y %X') - File $FILE has already been deleted from local storage..." >> $LOG_FILE fi
Java
UTF-8
1,245
3.765625
4
[ "Apache-2.0" ]
permissive
public class Solution { public int romanToInt(String s) { if (s.length() < 1) { return 0; } int current = 0;//当前位 int pre = singleRomanToInt(s.charAt(0));//前一位 int temp = pre;//临时值 int result = 0; for (int i = 1; i < s.length(); i++) { current = singleRomanToInt(s.charAt(i)); if (current == pre) { temp = temp + pre; } else if (current > pre) { temp = current - temp; } else { result += temp;//确定 current < pre 时,将结果加入 result 中 temp = current; } pre = current; } result += temp; return result; } /** * @param c sigle roman * @return int */ public int singleRomanToInt(char c) { switch (c) { case 'I': return 1; case 'V': return 5; case 'X': return 10; case 'L': return 50; case 'C': return 100; case 'D': return 500; case 'M': return 1000; default: return 0; } } }
Markdown
UTF-8
8,094
3.09375
3
[]
no_license
--- layout: post title: Ruby's other ternary operator type: post published: true status: publish categories: [] tags: - Ruby author: Dan Bernier date: 2007-06-11 23:02:27.000000000 -04:00 comments: - author: Reg Braithwaite content: "This is a well known Ruby trick, but it is not exactly the same thing as the ternary operator. Let's compare:\r\n\r\na ? b : c\r\n\r\nand\r\n\r\n(a &amp;&amp; b) || c\r\n\r\nThe former gives b whenever a is truthy and c otherwise, always. So if a == true, b == nil, and c == 'cee-threepio', (a ? b : c) =&gt; nil.\r\n\r\nBut (a &amp;&amp; b) || c =&gt; 'cee-threepio' for the same values.\r\n\r\nI prefer this form as well, but only when I know that the value of 'b' is guaranteed to be truthy." date: '2007-06-12 06:52:47' url: http://weblog.raganwald.com/ author_email: [email protected] - author: Simen content: "You don't need the parantheses around your third and fourth lines. It works anyway:\r\n\r\n<code>irb(main):001:0&gt; a = true ? \"a\" : \"b\"\r\n=&gt; \"a\"\r\nirb(main):002:0&gt; b = false ? \"a\" : \"b\"\r\n=&gt; \"b\"\r\nirb(main):003:0&gt; a = true &amp;&amp; \"a\" || b\r\n=&gt; \"a\"\r\nirb(main):004:0&gt; b = false &amp;&amp; \"a\" || b\r\n=&gt; \"b\"\r\n</code>\r\n\r\nHowever, if you change &amp;&amp; to \"and\", you start running into dark corners of operator precedence:\r\n\r\n<code>irb(main):001:0&gt; a = true ? \"a\" : \"b\"\r\n=&gt; \"a\"\r\nirb(main):002:0&gt; b = false ? \"a\" : \"b\"\r\n=&gt; \"b\"\r\nirb(main):003:0&gt; a = true and \"a\" || b\r\n=&gt; \"a\"\r\nirb(main):004:0&gt; b = false and \"a\" || b\r\n=&gt; false\r\n</code>\r\n\r\nAnd why do you put \"var\" before user_name? Ruby isn't javascript." date: '2007-06-12 07:04:04' url: http://metametamorfosen.wordpress.com/ author_email: [email protected] - author: Dan Bernier content: "Reg, you're right, I didn't think of that. I'll have to scan through the areas I've used this, and see whether that could happen...\r\n\r\nSimen,\r\n&gt; You don't need the parantheses around your third and fourth lines.\r\n\r\nYeah, I included them to emphasize the grouping, for clarity.\r\n\r\n&gt; And why do you put \"var\" before user_name? Ruby isn't javascript.\r\n\r\nYou're right...I think that 'var' snuck in from the javascript I've been doing, and the Scala I've been reading about." date: '2007-06-12 07:59:38' author_email: [email protected] - author: raichu content: i think that's how python programmers tried to get the convenience of the ternary operator into their programming language before they got their chainable syntax in version 2.5. back then, their version also failed when the variable wasn't "truthy-worthy". date: '2007-06-14 07:35:09' author_email: [email protected] - author: she content: "actually i think this is rather ugly\r\n\r\nand ternay operator is ugly too but at least used often enough to know it\r\nand sometimes it reduces a few lines of code" date: '2008-03-12 05:47:37' author_email: [email protected] - author: shawn content: "you cant do this if the action you want done is a binary opertor, ie only test if a test operator was given:\r\n(action ? params[:action] == action : true)" date: '2008-09-26 23:30:02' author_email: [email protected] - author: Otto content: I think the ternary operator sucks. Ok, it's fairly easy to understand a, b and c, but when that involves more complex expressions, it's a pain. And there are those who like to put a ternary operator inside another operator... date: '2009-06-23 21:47:04' author_email: [email protected] - author: Programmer content: Do you honestly think your expression is more readable than the ternary operator which is in use in many other languages? The point is to write re-usable code that can be read and understood clearly, not to make things harder to read because you want to show you are smarter. date: '2010-01-05 12:31:15' url: http://programmer.com author_email: [email protected] - author: Colin Bartlett content: "\"This is a lot like the a ||= 'a' trick,\r\n which expands to a = a || 'a', \r\n giving the variable a default value,\r\n if it's not already initialized.\"\r\n\r\nNot precisely correct - using (unnecessary) brackets to make things clear:\r\n whereas operators like x += y expand to x = (x + y)\r\n the operator x ||= y expands to x || (x = y)\r\n and the operator x &amp;&amp;= y expands to x &amp;&amp; (x = y)\r\n\r\nRick De Natale has a good post on this here:\r\nhttp://talklikeaduck.denhaven2.com/2008/04/26/x-y-redux" date: '2010-03-22 11:22:11' author_email: [email protected] - author: Dan Bernier content: "Colin, thanks for clarifying. So, when x has a value, it's basically a no-op?\r\n\r\nFunny, it expands to almost the opposite this JavaScript idiom:\r\n\r\n```javascript\nfunction foo(x) {\r\n x = x || \"default\";\r\n}\r\n```\n" date: '2010-03-22 13:06:24' author_email: [email protected] - author: Ruby Ternary Operations « OmegaDelta content: "[...] Ruby's other Ternary Operator [...]" date: '2010-12-17 00:46:17' url: http://omegadelta.net/2010/12/17/ruby-ternary-operations/ - author: wyderp content: these discussions should also include performance considerations. if you're like me and work on back end in a production environment you often have to use code that isn't pretty or easy to maintain but runs fast. date: '2011-10-27 07:52:54' author_email: [email protected] - author: Alfredo Amatriain content: "I confess I'm not too proficient with Ruby, but isn't your ternary example wrong? I think you're missing a couple \"=\" and they should be written like this:\r\n\r\na == true ? 'a' : 'b' #=&gt; \"a\"\r\nb == false ? 'a' : 'b' #=&gt; \"b\"\r\n\r\nOf course I fully expect to be told why I'm wrong and how much I still have to learn :)" date: '2012-11-07 14:09:01' author_email: [email protected] - author: Dan Bernier content: "No, I meant to use assignment (=), not equality testing (==). The effect I was after was to set a to \"a\", and b to \"b\".\r\n\r\nHere are some parentheses to clarify:\r\na = (true ? 'a' : 'b') #=&gt; \"a\"\r\nb = (false ? 'a' : 'b') \ #=&gt; \"b\"\r\n\r\nDoes that help?" date: '2012-11-07 14:14:59' author_email: [email protected] - author: Dan Bernier content: "...and hey, we've ALL got a lot to learn. :)" date: '2012-11-07 14:15:37' author_email: [email protected] - author: amatriain content: Ah, I see. I got the associativity wrong. Thanks. date: '2012-11-07 14:17:22' author_email: [email protected] - author: Programmer content: So, what is the code that runs the fastest? How was this tested out? date: '2012-11-13 14:44:35' author_email: [email protected] - author: Dan Bernier content: I don't know which is faster, but I doubt it's an order-of-magnitude difference. This was an article about language expressivity, not performance, so I didn't worry about it. date: '2012-11-13 14:48:38' author_email: [email protected] --- This may be a well-know Ruby trick, but I thought I'd share it anyway. Ruby has the ternary operator: {% highlight ruby linenos %} a = true ? 'a' : 'b' #=> "a" b = false ? 'a' : 'b' #=> "b"{% endhighlight %} But it also has something else... {% highlight ruby linenos %} a = (true && 'a') || b #=> "a" b = (false && 'a') || b #=> "b"{% endhighlight %} All statements in Ruby return the value of the last expression evaluated, so `true && 'a'` returns 'a', and the 'b' is ignored (via boolean short-circuiting). `false && 'a'` evaluates to `false`, so Ruby moves on, and returns 'b'. &nbsp; This is a lot like the `a ||= 'a'` trick, which expands to `a = a || 'a'`, giving the variable a default value, if it's not already initialized. If Ruby already has the ternary operator, why bother? Personally, I find this form more natural (which surprised me, after years of using the ternary operator in Java and C#). For some reason, it reads more like natural language to me. {% highlight ruby linenos %} user_name = (user.authenticated? && user.name) || 'guest'{% endhighlight %} Does anyone else see it? &nbsp;
PHP
UTF-8
521
2.65625
3
[]
no_license
<?php namespace EventoOriginal\Core\Persistence\Repositories; use EventoOriginal\Core\Entities\Customer; class CustomerRepository extends BaseRepository { public function save(Customer $customer, bool $flush = true) { $this->getEntityManager()->persist($customer); if ($flush) { $this->getEntityManager()->flush(); } } public function findOneByAffiliateCode(string $affiliateCode) { return $this->findOneBy(['affiliateCode' => $affiliateCode]); } }
Markdown
UTF-8
1,110
3.28125
3
[]
no_license
# HAVING-A-BEST-FRIEND A story tells that two Friends👬 were walking through the desert🏜️. During some point of the journey they had an argument,and one friend slapped the other one in the face. The one who got slapped was hurt💔,but without saying anything, wrote in the sand; "Today my best friend slapped me in the face". They kept on walking until they found oasis,where they decided to take a bath. The one who had been slapped got stuck in the mire and started drowning,but the friend saved him. After he recovered from the near drowning, he wrote on a stone; "Today my best friend saved my life". The friend who had slapped and save his best friend asked him; "After I hurt you,you wrote in the sand and now ,you write on a stone why?". The other friend replied; "When somebody hurts us we should write it down in the sand where winds of forgiveness can erase it away. But, when someone does something good for us, we must engrave it in stone where no wind can ever erase it". MORAL OF THE STORY: Don't value the things you have in your life. But value who you have in your life.
Java
UTF-8
2,148
2.5
2
[ "MIT" ]
permissive
package mage.cards.a; import java.util.UUID; import mage.abilities.effects.common.DamageTargetEffect; import mage.abilities.effects.common.DestroyTargetEffect; import mage.abilities.effects.common.search.SearchLibraryGraveyardPutInHandEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.filter.FilterCard; import mage.filter.predicate.mageobject.NamePredicate; import mage.target.common.TargetCreaturePermanent; import mage.target.common.TargetPlayerOrPlaneswalker; import mage.target.targetpointer.SecondTargetPointer; /** * * @author LevelX2 */ public final class AngrathsFury extends CardImpl { private static final FilterCard filter = new FilterCard("Angrath, Minotaur Pirate"); static { filter.add(new NamePredicate(filter.getMessage())); } public AngrathsFury(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{3}{B}{R}"); // Destroy target creature. this.getSpellAbility().addEffect(new DestroyTargetEffect()); this.getSpellAbility().addTarget(new TargetCreaturePermanent()); // Angrath's Fury deals 3 damage to target player. this.getSpellAbility().addEffect(new DamageTargetEffect(3).setTargetPointer(new SecondTargetPointer()) .setText("{this} deals 3 damage to target player or planeswalker")); this.getSpellAbility().addTarget(new TargetPlayerOrPlaneswalker()); // You may search your library and/or graveyard for a card named Angrath, Minotaur Pirate, reveal it, and put it into your hand. If you search your library this way, shuffle it. this.getSpellAbility().addEffect(new SearchLibraryGraveyardPutInHandEffect(filter) .setText("You may search your library and/or graveyard for a card named Angrath, Minotaur Pirate, reveal it, and put it into your hand. If you search your library this way, shuffle")); } private AngrathsFury(final AngrathsFury card) { super(card); } @Override public AngrathsFury copy() { return new AngrathsFury(this); } }
C++
UTF-8
3,640
3.140625
3
[ "MIT" ]
permissive
#pragma once #include <cstdint> #include <functional> #include <vector> #include "common.h" namespace pathplanner { struct PathAndCosts { Path path; float finalCosts; }; /** * @brief Weighted A* implementation */ class AStarPlanner { public: struct RoverModelConfig { /** * Signature: * auto dist = distFunc(ax, ay, bx, by); */ using DistFunc = std::function<float(int, int, int, int)>; /** * @param weight The rover's weight. Influences cost model for traveling up/downhill. * @param maxSpeed Rover's maximum speed, in normalized units. Rover's travelling speed in flat terrain is \a m_baseSpeed. * @param distFunc A user provided distance function between 2 points in the map, used by the heuristic. */ RoverModelConfig(float weight, float maxSpeed, DistFunc distFunc); /** * @brief Creates a config with a default euclidian distance */ RoverModelConfig(float weight, float maxSpeed); float m_weight; /** * Base speed is defaulted to 1.0 cell/<time unit>. Set directly for changing its value. */ float m_baseSpeed; float m_maxSpeed; DistFunc m_distance; protected: /** * @brief euclidean distance between two nodes */ static float euclideanDist(int ax, int ay, int bx, int by); }; /** * Constructs a new A* planner. * * @param width Width of the map. * @param height Height of the map. * @param elevation vector containing elevation (elevation == 0 marks impassable nodes). */ AStarPlanner(int width, int height, const std::vector<std::uint8_t>& elevation, const RoverModelConfig& modelConfig); /** * Plan a path from start to dest using currently set parameters (cf. constructor). * * @param start Position of the start node. * @param dest Position of the destination node. * @param relaxation The A* relaxation parameter. >= 1 * @return Found path and final costs for that path; path will be empty if none was found. */ PathAndCosts plan(const Pos& start, const Pos& dest, float relaxation); /** * Static convience function to create a single instance of the planner and call plan() on it. * * @param start Position of the start node. * @param dest Position of the destination node. * @param width Width of the map. * @param height Height of the map. * @param elevation vector containing elevation (elevation == 0 marks impassable nodes). * @return Found path and final costs for that path; path will be empty if none was found. */ static PathAndCosts plan(const Pos& start, const Pos& dest, int width, int height, const std::vector<std::uint8_t>& elevation, const RoverModelConfig& modelConfig, float relaxation); protected: // cost model related methods // Returns the cost of going from node a to b, also considering elevation. Works only properly // for neighboring nodes. float cost(int ax, int ay, int bx, int by) const; // A* heuristic: returns an upper bound for the cost for going from node to the target. float heuristic(int x, int y) const; uint8_t elevation(int x, int y) const; bool impassable(int x, int y) const; private: // methods int mkIdx(int x, int y) const; const int m_width; const int m_height; const std::vector<std::uint8_t>& m_elevation; const RoverModelConfig m_modelConfig; int m_dstX; int m_dstY; }; } // namespace
Java
UTF-8
20,432
2.171875
2
[ "Apache-2.0" ]
permissive
package controllers; import com.avaje.ebean.Ebean; import com.avaje.ebean.SqlQuery; import com.avaje.ebean.SqlRow; import models.*; import play.Logger; import play.data.*; import play.mvc.*; import views.html.*; import plugins.com.feth.play.module.pa.PlayAuthenticate; import java.lang.String; import java.util.*; import static play.libs.Json.toJson; import controllers.routes; public class ProjectData extends Controller { /** * This function render the page for a specific project * @param pid: project ID * @return Result */ public static Result project(Long pid) { session().put("callback", routes.ProjectData.project(pid).absoluteURL(request())); Person user = Person.findByAuthUserIdentity(PlayAuthenticate.getUser(session())); if(user != null) { Project p = Project.find.byId(pid); return ok(project.render("AssistU - Projects", user, p)); } else { session().put("callback", routes.ProjectData.project(pid).absoluteURL(request())); return Authentication.login(); } } static Form<Project> projectForm = Form.form(Project.class); /** * Renders the page for the creation of a new project * @return Result */ public static Result createProjectPage() { Person user = Person.findByAuthUserIdentity(PlayAuthenticate.getUser(session())); if(user != null) return ok(projectNew.render("Create a new Project", projectForm, false, "", "", user)); else { session().put("callback", routes.ProjectData.createProjectPage().absoluteURL(request())); return Authentication.login(); } } /** * Renders the page for editing a project * @param pid: project ID for the project to be edited * @return Result */ public static Result editProjectPage(Long pid) { Person user = Person.findByAuthUserIdentity(PlayAuthenticate.getUser(session())); Project p = Project.find.byId(pid); if(user != null) return ok(projectEdit.render("Edit Project " + p.name, p, projectForm.fill(p), false, "", "", user)); else { session().put("callback", routes.ProjectData.editProjectPage(pid).absoluteURL(request())); return Authentication.login(); } } /** * This function creates a new Project initiated by a user that automatically becomes its owner. * @return Result */ public static Result createProject() { Person user = Person.findByAuthUserIdentity(PlayAuthenticate.getUser(session())); Form<Project> filledProjectForm = projectForm.bindFromRequest(); if (user != null) { if (filledProjectForm.hasErrors()) { return badRequest(projectNew.render("Something went wrong", filledProjectForm, true, "danger", "The input did not fulfill the requirements, please review your information", user)); } else if (!(Application.allowedTitleRegex(filledProjectForm.get().folder) && Application.allowedTitleRegex(filledProjectForm.get().name))) { return badRequest(projectNew.render("Something went wrong", filledProjectForm, true, "danger", "The input did not have the allowed format, please review your information", user)); } else { Project projectData = filledProjectForm.get(); Project p = Project.create(projectData.folder, projectData.name, projectData.description, projectData.template); Project.inviteOwner(p.id, user.id); Role r = Role.find.where().eq("project", p).eq("person", user).findUnique(); r.accepted = true; r.dateJoined = new Date(); r.update(); if (!p.template.equals("None")) { Event.defaultPlanningArticle(user, p); p.planning = true; p.save(); } //Emailer.sendNotifyEmail("[assistU] New project "+p.name+ "Created",user,views.html.email.projectCreated.render(user,p)); return redirect(routes.ProjectData.project(p.id)); } } //User did not have a session session().put("callback", routes.ProjectData.createProject().absoluteURL(request())); return Authentication.login(); } /** * This function edits a project with values catched from a form. * @param pid: The Project ID of the Project that needs it details edited * @return Result */ public static Result editProject(Long pid) { Person user = Person.findByAuthUserIdentity(PlayAuthenticate.getUser(session())); if (user != null) { if (ProjectData.findAllOwners(pid).contains(user)) { Project p = Project.find.byId(pid); Form<Project> filledProjectForm = projectForm.bindFromRequest(); if (filledProjectForm.hasErrors()) { Logger.debug(filledProjectForm.errors().toString()); return badRequest(projectEdit.render("Something went wrong", p, filledProjectForm, true, "danger", "The input did not fulfill the requirements, please review your information", user)); } else if (!(Application.allowedTitleRegex(filledProjectForm.get().folder) && Application.allowedTitleRegex(filledProjectForm.get().name))) { return badRequest(projectNew.render("Something went wrong", filledProjectForm, true, "danger", "The input did not have the allowed format, please review your information", user)); } else { String template = filledProjectForm.get().template; if (!template.equals("None")) { Event.defaultPlanningArticle(user, p); p.planning = true; p.save(); } Project.edit(pid, filledProjectForm.get().folder, filledProjectForm.get().name, filledProjectForm.get().description,template); } } return redirect(routes.ProjectData.project(pid)); } else { //User did not have a session session().put("callback", routes.ProjectData.editProject(pid).absoluteURL(request())); return Authentication.login(); } } /** * This function refers to the model's archive function. The unused uid is to check whether the person is an * owner of the project at hand (future implementation) * @param uid: The User ID of the person requesting for archiving * @param pid: The Project ID of the project that is up for archiving * @return Result */ public static Result archiveProject(Long pid) { Person user = Person.findByAuthUserIdentity(PlayAuthenticate.getUser(session())); if(user != null) { if (ProjectData.findAllOwners(pid).contains(user) && ProjectData.findAllOwners(pid).size() == 1) { Project.archive(pid); } return redirect(routes.Application.project()); } else { //User did not have a session session().put("callback", routes.ProjectData.archiveProject(pid).absoluteURL(request())); return Authentication.login(); } } /** * This function catches the Dynamicform from the template with the ID of the User that needs to * be added to the project of which the Project ID has been passed * @param pid: The project to which the user in the form has to be assigned * @return Result */ public static Result inviteMemberToProjectAs(Long pid) { DynamicForm emailform = Form.form().bindFromRequest(); Person user = Person.findByAuthUserIdentity(PlayAuthenticate.getUser(session())); if (user != null){ //See if the user requesting to invite someone is an Owner if (ProjectData.findAllOwners(pid).contains(user)) { Person user_invited = Person.find.where().eq("email", emailform.get("email")).findUnique(); Project p = Project.find.byId(pid); //See if the user that needs to be invited exists in the system if (user_invited != null) { //There can not be a role relation between the invited user and the project, // as it would be the user is already a member if (Role.find.where().eq("project", p).eq("person", user_invited).findUnique() == null) { //Pattern match the correct role for invitation if (emailform.get("role").equals("Owner")) { Project.inviteOwner(p.id, user_invited.id); p.planning = true; p.save(); } else if (emailform.get("role").equals("Reviewer")) { Project.inviteReviewer(p.id, user_invited.id); } else { Project.inviteGuest(p.id, user_invited.id); } } } else { String email = emailform.get("email"); if(!email.equals("")){ //Emailer.sendInvitationEmail(user.name + " has invited you to join AssisTU", email, views.html.email.app_invitation.render(user,p)); return redirect(routes.Application.project()); }else{ flash("error", "You did not provide a valid email address"); return redirect(routes.Application.project()); } } } return redirect(routes.Application.project()); } else { //User did not have a session session().put("callback", routes.ProjectData.inviteMemberToProjectAs(pid).absoluteURL(request())); return Authentication.login(); } } /** * This function confirms the invitation to a project from the user currently logged in. * @param pid: project ID to be joined * @return Result */ public static Result hasAccepted(Long pid){ Project p = Project.find.byId(pid); Person user = Person.findByAuthUserIdentity(PlayAuthenticate.getUser(session())); if( user != null) { Role r = Role.find.where().eq("person", user).eq("project", p).findUnique(); //See if there actually exists a (pending) role between the accepting user and project if (r != null) { r.accepted = true; if(r.role.equals(Role.OWNER)) Event.defaultPlanningArticle(user, p); r.dateJoined = new Date(); r.save(); List<Person> owners=findAllOwners(p.id); owners.stream().forEach((u) -> { if(!u.equals(user)) // Emailer.sendNotifyEmail("[Assistu] "+ user.name + " has joined the project" , u ,views.html.email.project_joined.render(u,user,p) ); }); // Emailer.sendNotifyEmail("[Assistu] "+ user.name + " you have just joined the project" , user ,views.html.email.project_joined_2.render(user,p) ); } return redirect(routes.ProjectData.project(p.id)); } else { //User did not have a session session().put("callback", routes.ProjectData.hasAccepted(pid).absoluteURL(request())); return Authentication.login(); } } /** * This function declines the invitation to a project from the user currently logged in. * @param pid: project ID to be declined * @return Result */ public static Result hasDeclined(Long pid){ Project p = Project.find.byId(pid); Person user = Person.findByAuthUserIdentity(PlayAuthenticate.getUser(session())); if(user != null) { Role r = Role.find.where().eq("person", user).eq("project", p).findUnique(); if (r != null) { r.delete(); } List<Person> owners=findAllOwners(p.id); owners.stream().forEach((u) -> { if(!u.equals(user)) // Emailer.sendNotifyEmail("[Assistu] "+ user.name + " has declined to join the project" , u ,views.html.email.declined.render(u,user,p) ); }); return redirect(routes.Application.project()); } else { //User did not have a session session().put("callback", routes.ProjectData.hasDeclined(pid).absoluteURL(request())); return Authentication.login(); } } /** * This function removes a user from a project. This function doubles * as removing someone and leaving yourself. In the latter case your * own User ID is passed. * @param uid: The ID of the User that is being removed * @param pid: The ID of the Project in which the User had to be removed from * @return Result */ public static Result removeMemberFromProject(Long uid, Long pid){ Person user = Person.findByAuthUserIdentity(PlayAuthenticate.getUser(session())); Person other = Person.find.byId(uid); if(user != null) { if (ProjectData.findAllOwners(pid).contains(user) && !ProjectData.findAllOwners(pid).contains(other)) { Project.removeMemberFrom(pid, uid); } return redirect(routes.Application.project()); } else { //User did not have a session session().put("callback", routes.ProjectData.removeMemberFromProject(uid, pid).absoluteURL(request())); return Authentication.login(); } } /** * This function removes the user logged in from a project * @param pid: project ID of project the user wants to leave * @return Result */ public static Result leaveProject(Long pid){ Person user = Person.findByAuthUserIdentity(PlayAuthenticate.getUser(session())); if(user != null) { Project.removeMemberFrom(pid, user.id); return redirect(routes.Application.project()); } else { //User did not have a session session().put("callback", routes.ProjectData.leaveProject(pid).absoluteURL(request())); return Authentication.login(); } } /** * Returns the project name and ID pairs as JSON * @return Result */ public static Result getProjectIdsAsJson(){ List<Project> projects = PersonData.findActiveProjects(); List<TreeMap<String, String>> result = new ArrayList<TreeMap<String, String>>(); TreeMap<String, String> project; for(int i =0; i < projects.size(); i++){ project = new TreeMap<String, String>(); project.put("name", projects.get(i).name); project.put("projectID", "" + projects.get(i).id); result.add(project); } return ok(toJson(result)); } /** * Returns the owner projects IDs as JSON * @return Result */ public static Result getOwnerIdsAsJson(){ List<Project> projects = PersonData.findActiveProjects(); List<Long> result = new ArrayList<Long>(); for(int i =0 ; i < projects.size(); i++){ List<Person> projectowners = ProjectData.findAllOwners(projects.get(i).id); for(int j = 0; j < projectowners.size(); j++){ if(!result.contains(projectowners.get(j).id)){ result.add(projectowners.get(j).id); } } } return ok(toJson(result)); } /** * Returns the reviewer projects IDs as JSON * @return Result */ public static Result getReviewerIdsAsJson(){ List<Project> projects = PersonData.findActiveProjects(); List<Long> result = new ArrayList<Long>(); for(int i =0 ; i < projects.size(); i++){ List<Person> projectreviewers = ProjectData.findAllReviewers(projects.get(i).id); for(int j = 0; j < projectreviewers.size(); j++){ if(!result.contains(projectreviewers.get(j).id)){ result.add(projectreviewers.get(j).id); } } } return ok(toJson(result)); } /** * Returns the guest project IDs as JSON * @return Result */ public static Result getGuestIdsAsJson(){ List<Project> projects = PersonData.findActiveProjects(); List<Long> result = new ArrayList<Long>(); for(int i =0 ; i < projects.size(); i++){ List<Person> projectguests = ProjectData.findAllReviewers(projects.get(i).id); for(int j = 0; j < projectguests.size(); j++){ if(!result.contains(projectguests.get(j).id)){ result.add(projectguests.get(j).id); } } } return ok(toJson(result)); } /** * Return the name and ID of the last created project * @return Result */ public static Result getLastAccessedProjectIdAsJson(){ Project p = PersonData.getLastUsedProject(); HashMap<String, String> project = new HashMap<String, String>(); if(p != null) { project.put("name", p.name); project.put("projectID", "" + p.id); } return ok(toJson(project)); } /** * Finds all the users in a project * @param pid: the ID of the project * @return List<Person> */ public static List<Person> findAllAffiliatedUsers(Long pid){ Project p = Project.find.byId(pid); List<Role> roles = Role.find.where().eq("project", p).findList(); List<Person> persons = new ArrayList<Person>(); for(Role role: roles){ persons.add(role.person); } return persons; } /** * This function returns all the owners of a project * @param pid: project ID * @return List<Person> */ public static List<Person> findAllOwners(Long pid){ Project p = Project.find.byId(pid); List<Role> roles = Role.find.where().eq("project", p).eq("role", Role.OWNER).findList(); List<Person> persons = new ArrayList<Person>(); for(Role role: roles){ persons.add(role.person); } return persons; } /** * This function returns all the reviewers of a project * @param pid: project ID * @return List<Person> */ public static List<Person> findAllReviewers(Long pid){ Project p = Project.find.byId(pid); List<Role> roles = Role.find.where().eq("project", p).eq("role", Role.REVIEWER).findList(); List<Person> persons = new ArrayList<Person>(); for(Role role: roles){ persons.add(role.person); } return persons; } /** * This function returns all the guests of a project * @param pid: project ID * @return List<Person> */ public static List<Person> findAllGuests(Long pid){ Project p = Project.find.byId(pid); List<Role> roles = Role.find.where().eq("project", p).eq("role", Role.GUEST).findList(); List<Person> persons = new ArrayList<Person>(); for(Role role: roles){ persons.add(role.person); } return persons; } public static List<MendeleyDocument> findAllMendeleyDocuments(Long pid){ List<Person> members = ProjectData.findAllOwners(pid); List<MendeleyDocument> mendeley_docs = MendeleyDocument.find.where().in("person", members).orderBy("title").setDistinct(true).findList(); Map<String, MendeleyDocument> temp = new HashMap<String, MendeleyDocument>(); for(MendeleyDocument mendeley_doc : mendeley_docs){ temp.put(mendeley_doc.title, mendeley_doc); } List<MendeleyDocument> result = new ArrayList<MendeleyDocument>(); for(String title : temp.keySet()){ result.add(temp.get(title)); } return result; } }
C#
UTF-8
5,381
2.859375
3
[ "MIT" ]
permissive
using System.Collections.Generic; using System.Text.RegularExpressions; using TriggersTools.IO.Windows.Internal; namespace TriggersTools.IO.Windows { partial class FileFind { #region EnumeratePath /// <summary> /// Returns an enumerable collection of file paths that matches a specified search pattern /// and search subdirectory option. /// </summary> /// /// <param name="path"> /// The relative or absolute path to the directory to search. This string is not case-sensitive. /// </param> /// <param name="regex">The regex expression to match with.</param> /// <param name="searchOrder">How subdirectories should be searched, if at all.</param> /// <returns> /// An enumerable collection of files that matches searchPattern and searchOrder. /// </returns> public static IEnumerable<string> EnumerateFiles(string path, Regex regex, SearchOrder searchOrder = SearchOrder.TopDirectoryOnly) { return new FilePathEnumerable(path, regex, true, false, searchOrder); } /// <summary> /// Returns an enumerable collection of directory information that matches a specified search /// pattern and search subdirectory option. /// </summary> /// /// <param name="path"> /// The relative or absolute path to the directory to search. This string is not case-sensitive. /// </param> /// <param name="regex">The regex expression to match with.</param> /// <param name="searchOrder">How subdirectories should be searched, if at all.</param> /// <returns> /// An enumerable collection of directories that matches searchPattern and searchOrder. /// </returns> public static IEnumerable<string> EnumerateDirectories(string path, Regex regex, SearchOrder searchOrder = SearchOrder.TopDirectoryOnly) { return new FilePathEnumerable(path, regex, false, true, searchOrder); } /// <summary> /// Returns an enumerable collection of file system paths that matches a specified search /// pattern and search subdirectory option. /// </summary> /// /// <param name="path"> /// The relative or absolute path to the directory to search. This string is not case-sensitive. /// </param> /// <param name="regex">The regex expression to match with.</param> /// <param name="searchOrder">How subdirectories should be searched, if at all.</param> /// </param> /// <returns> /// An enumerable collection of file-system entries in the directory specified by path and that match /// the specified search pattern and option. /// </returns> public static IEnumerable<string> EnumerateFileSystemEntries(string path, Regex regex, SearchOrder searchOrder = SearchOrder.TopDirectoryOnly) { return new FilePathEnumerable(path, regex, true, true, searchOrder); } #endregion #region EnumerateInfo /// <summary> /// Returns an enumerable collection of file information that matches a specified search pattern /// and search subdirectory option. /// </summary> /// /// <param name="path"> /// The relative or absolute path to the directory to search. This string is not case-sensitive. /// </param> /// <param name="regex">The regex expression to match with.</param> /// <param name="searchOrder">How subdirectories should be searched, if at all.</param> /// <returns> /// An enumerable collection of files that matches searchPattern and searchOrder. /// </returns> public static IEnumerable<FileFindInfo> EnumerateFileInfos(string path, Regex regex, SearchOrder searchOrder = SearchOrder.TopDirectoryOnly) { return new FileInfoEnumerable(path, regex, true, false, searchOrder); } /// <summary> /// Returns an enumerable collection of directory information that matches a specified search /// pattern and search subdirectory option. /// </summary> /// /// <param name="path"> /// The relative or absolute path to the directory to search. This string is not case-sensitive. /// </param> /// <param name="regex">The regex expression to match with.</param> /// <param name="searchOrder">How subdirectories should be searched, if at all.</param> /// <returns> /// An enumerable collection of directories that matches searchPattern and searchOrder. /// </returns> public static IEnumerable<FileFindInfo> EnumerateDirectoryInfos(string path, Regex regex, SearchOrder searchOrder = SearchOrder.TopDirectoryOnly) { return new FileInfoEnumerable(path, regex, false, true, searchOrder); } /// <summary> /// Returns an enumerable collection of file system information that matches a specified search /// pattern and search subdirectory option. /// </summary> /// /// <param name="path"> /// The relative or absolute path to the directory to search. This string is not case-sensitive. /// </param> /// <param name="regex">The regex expression to match with.</param> /// <param name="searchOrder">How subdirectories should be searched, if at all.</param> /// </param> /// <returns> /// An enumerable collection of file-system entries in the directory specified by path and that match /// the specified search pattern and option. /// </returns> public static IEnumerable<FileFindInfo> EnumerateFileSystemInfos(string path, Regex regex, SearchOrder searchOrder = SearchOrder.TopDirectoryOnly) { return new FileInfoEnumerable(path, regex, true, true, searchOrder); } #endregion } }
C#
UTF-8
4,492
2.515625
3
[]
no_license
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using MVCELB1.Data; namespace MVCELB1.Controllers { public class HomeController : Controller { private SampleDBContext db = new SampleDBContext(); // GET: Home public ActionResult Index(string searchBy, string search) { if (searchBy == "FirstName") { return View(db.Customers.Where(x => x.FirstName == search).ToList()); } else { return View(db.Customers.Where(x => x.LastName.StartsWith(search)).ToList()); } } public ActionResult Show() { return View(db.Customers.ToList()); } public ActionResult Search(string searchBy, string search) { if (searchBy == "FirstName") { return View(db.Customers.Where(x => x.FirstName == search).ToList()); } else { return View(db.Customers.Where(x => x.LastName.StartsWith(search)).ToList()); } } // GET: Home/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Customer customer = db.Customers.Find(id); if (customer == null) { return HttpNotFound(); } return View(customer); } // GET: Home/Create public ActionResult Create() { return View(); } // POST: Home/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "CustomerID,FirstName,LastName,Phone,Address,City,State,Zip")] Customer customer) { if (ModelState.IsValid) { db.Customers.Add(customer); db.SaveChanges(); return RedirectToAction("Index"); } return View(customer); } // GET: Home/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Customer customer = db.Customers.Find(id); if (customer == null) { return HttpNotFound(); } return View(customer); } // POST: Home/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "CustomerID,FirstName,LastName,Phone,Address,City,State,Zip")] Customer customer) { if (ModelState.IsValid) { db.Entry(customer).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(customer); } // GET: Home/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Customer customer = db.Customers.Find(id); if (customer == null) { return HttpNotFound(); } return View(customer); } // POST: Home/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { Customer customer = db.Customers.Find(id); db.Customers.Remove(customer); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
C++
UTF-8
300
2.59375
3
[]
no_license
#include<iomanip> #include<iostream> #include<vector> #include<algorithm> #include<string> #include<map> #include<math.h> using namespace std; int summ(int a[],int pos) { if(size==1) return a[size-1]; return max(summ(a,pos),summ(a,pos+1)) } int main() { int a[5] = {}; summ(a,0); }
Shell
UTF-8
4,232
3.609375
4
[]
no_license
#!/bin/sh CAT="/bin/cat" CHMOD="/bin/chmod" MKDIR="/bin/mkdir" TOUCH="/usr/bin/touch" github_base='https://raw.githubusercontent.com/' repo_path='PeterDaveHello/Unitial/master/' os="$(uname)" if [ "$os" = "FreeBSD" ]; then ECHO="echo" ${ECHO} -e "\n\e[1;36;40mYour operating system is $os\n\e[0m" ${ECHO} -e "\n\e[1;36;40mSuppose you have 'fetch' to download files!\n\e[0m" download_o='fetch -o' else ECHO="/bin/echo" ${ECHO} -e "\n\e[1;36;40mYour operating system is $os\n\e[0m" if type "curl" > /dev/null 2>&1; then download_o='curl --compressed -#o' elif type "wget" > /dev/null 2>&1; then download_o='wget --no-timestamping --no-verbose -O ' else echo "Unitial needs 'wget' or 'curl' to download the assets." 1>&2 fi fi ${ECHO} -e "\n\e[1;36;40mUnitial is started to initial your Unix-like working environment\n\nPlease wait...\n\n\e[0m" ${ECHO} -e "\n\e[1;36;40mDownload and setup configs from server...\n\e[0m" for file in gitconfig tcshrc bashrc bash_profile inputrc vimrc zshrc gitignore_global tmux.conf xinputrc wgetrc curlrc tigrc editorconfig php_cs markdownlintrc lftprc; do ${download_o} - "${github_base}${repo_path}${file}" | ${CAT} >> ~/."$file" & done ${MKDIR} -p ~/.irssi/ ~/.git/contrib/ ~/.vim/colors/ ~/.vim/swp/ ~/.vim/bak/ ~/.vim/undo/ ~/.aria2/ ~/.w3m/ ${download_o} ~/.w3m/config "${github_base}${repo_path}w3mconfig" & ${download_o} ~/.irssi/config "${github_base}${repo_path}irssi_config" & ${download_o} ~/.aria2/aria2.conf "${github_base}${repo_path}aria2.conf" & ${download_o} ~/.colorEcho "${github_base}PeterDaveHello/ColorEchoForShell/master/dist/ColorEcho.bash" & ${MKDIR} -p ~/.gcin/ ${download_o} ~/.gcin/gtab.list "${github_base}${repo_path}gtab.list" & ${MKDIR} -p -m 700 ~/.ssh/.tmp_session/ ${CHMOD} 700 ~/.ssh/ ${download_o} - "${github_base}${repo_path}ssh_config" | ${CAT} >> ~/.ssh/config & ${TOUCH} ~/.ssh/authorized_keys ${CHMOD} 600 ~/.ssh/config ~/.ssh/authorized_keys wait ${ECHO} -e "\n\e[1;36;40mAdd some color setting which depends on your OS...\n\e[0m" if [ "$os" = "FreeBSD" ] || [ "$os" = "Darwin" ]; then ${ECHO} -e "\n#color setting\nalias ls='\ls -F'" >> ~/.zshrc ${ECHO} -e "\n#color setting\nalias ls '\ls -F'" >> ~/.tcshrc else ${ECHO} -e "\n#color setting\nalias ls='\ls -F --color=auto'" >> ~/.zshrc ${ECHO} -e "\n#color setting\nalias ls '\ls -F --color=auto'" >> ~/.tcshrc fi if [ "$os" = "FreeBSD" ]; then ${ECHO} -e "\n\e[1;36;40mAdd FreeBSD's package mirror setting...\n\e[0m" ${ECHO} -e "\n#package mirror setting\nexport PACKAGEROOT=http://ftp.tw.freebsd.org" >> ~/.bashrc ${ECHO} -e "\n#package mirror setting\nexport PACKAGEROOT=http://ftp.tw.freebsd.org" >> ~/.zshrc ${ECHO} -e "\n#package mirror setting\nsetenv PACKAGEROOT http://ftp.tw.freebsd.org" >> ~/.tcshrc fi if command -v git; then git_version="v$(git --version | awk '{print $3}')" else git_version="master" fi ${ECHO} -e "\n\e[1;36;40mDownload VIM color scheme - Kolor from server...\n\e[0m" ${download_o} ~/.vim/colors/kolor.vim "${github_base}zeis/vim-kolor/master/colors/kolor.vim" & ${ECHO} -e "\n\e[1;36;40mDownload git contrib - diff-highlight from server...\n\e[0m" ${download_o} ~/.git/contrib/diff-highlight "${github_base}git/git/v2.13.2/contrib/diff-highlight/diff-highlight" && ${CHMOD} +x ~/.git/contrib/diff-highlight & ${ECHO} -e "\n\e[1;36;40mDownload git's auto completion configs from server...\n\e[0m" git_auto_complete_path="${github_base}git/git/${git_version}/contrib/completion/git-completion." ${download_o} ~/.git-completion.bash "${git_auto_complete_path}bash" & ${download_o} ~/.git-completion.tcsh "${git_auto_complete_path}tcsh" & ${download_o} ~/.git-completion.zsh "${git_auto_complete_path}zsh" & wait if [ "$os" = "FreeBSD" ] && [ -r /usr/local/share/certs/ca-root-nss.crt ]; then ${ECHO} -e "\n\e[1;36;40mAdd ca-certificate path for FreeBSD's wget & aria2...\n\e[0m" ${ECHO} -e "\nca-certificate=/usr/local/share/certs/ca-root-nss.crt" >> ~/.wgetrc ${ECHO} -e "\nca-certificate=/usr/local/share/certs/ca-root-nss.crt" >> ~/.aria2/aria2.conf fi ${ECHO} -e "\n\e[1;36;40mUnitial installation was finished!\n\nPlease terminate all other works and restart your shell or re-login.\n\e[0m"
Markdown
UTF-8
1,058
2.875
3
[]
no_license
### Python dir(对象) , 遍历对象属性 对象.__dict__ 对象的字典键值对 vim : i 插入 :+W+Q 关闭当前文件 #coding:utf-8 告诉Python解释器 当前文件 编码格式 Python 创建类是 class Foo (object) 里面有object 说明是新式类, 否则是jiushilei cookie 以键值对的格式 存储在浏览器当中的一段文本信息 , 再次请求这个网站时这个cookie信息就会自动加到请求报文的头里面发送到服务器里面 ​ break/continue只能用在循环中,除此以外不能单独使用 break/continue在嵌套循环中,只对最近的一层循环起作用 continue的作用:用来结束本次循环,紧接着执行下一次的循环 切片是指对操作的对象截取其中一部分的操作。字符串、列表、元组都支持切片操作。 切片的语法:[起始:结束:步长] 注意:选取的区间属于左闭右开型,即从"起始"位开始,到"结束"位的前一位结束(不包含结束位本身)。 翻转字符串 : a="abvcy" a=a[4:0:-1]
Python
UTF-8
1,499
2.921875
3
[]
no_license
#!/usr/bin/env python3 from Model.loader import get_all_lm from Model.loader import load_fastai_lm from abc import abstractmethod, ABCMeta import logging class LanguageAdapter(metaclass=ABCMeta): """Base adapter for language model to enable using models trained in different frameworks""" def __init__(self): logging.debug("Initializing Language Model Adapter") self._lm = None self._name = None @property def name(self): return self._name @name.setter def name(self, name): self._name = name @property @abstractmethod def lm(self): ... @lm.setter @abstractmethod def lm(self, val): ... @abstractmethod def predict(self, text, n_words): ... class FastaiAdapter(LanguageAdapter): """Concrete language model trained in keras framework""" def __init__(self, name): super().__init__() self._lm = name @property def lm(self): return self._lm @lm.setter def lm(self, name): if name in get_all_lm(): self._lm = load_fastai_lm(name) def predict(self, text, n_words): """Return text with n_words that come after text""" if self.lm is not None: return self.lm.predict(text=text, n_words=n_words, temperature=0.75) else: logging.warning('Fastai adapter does not have model loaded') raise Exception('`Fastai language model` does not load model')
Shell
UTF-8
1,513
2.796875
3
[]
no_license
#!/bin/bash METHOD="Partition" EPSILON=10 PARTITIONS=1 CORES=1 CAPACITY=250 LEVELS=5 DEBUG="" while getopts "m:e:p:c:a:f:l:n:t:u:d" OPTION; do case $OPTION in m) METHOD=$OPTARG ;; e) EPSILON=$OPTARG ;; p) PARTITIONS=$OPTARG ;; c) CORES=$OPTARG ;; a) CAPACITY=$OPTARG ;; d) DEBUG="--debug" ;; *) echo "Incorrect options provided" exit 1 ;; esac done SPARK_JARS=$HOME/Spark/2.4/jars/ CLASS_JAR=$HOME/Research/Scripts/Scala/DistanceJoin/target/scala-2.11/geotester_2.11-0.1.jar CLASS_NAME=edu.ucr.dblab.djoin.DisksFinder_Control LOG_FILE=$HOME/Spark/2.4/conf/log4j.properties MASTER="local[$CORES]" #POINTS=file://$HOME/Datasets/Test/Points_N50K_E40.tsv POINTS=file://$HOME/Research/Datasets/Test/Points_N10K_E10.tsv #POINTS=file://$HOME/Research/Datasets/Test/Points_N1K_E20.tsv #POINTS=file://$HOME/Research/Datasets/Test/Points_N20_E1.tsv spark-submit \ --files "$LOG_FILE" --conf spark.driver.extraJavaOptions=-Dlog4j.configuration=file:"$LOG_FILE" \ --jars "${SPARK_JARS}"geospark-1.2.0.jar,"${SPARK_JARS}"geospark-sql_2.3-1.2.0.jar,"${SPARK_JARS}"geospark-viz_2.3-1.2.0.jar,"${SPARK_JARS}"scallop_2.11-3.1.5.jar,"${SPARK_JARS}"spark-measure_2.11-0.16.jar,"${SPARK_JARS}"utils_2.11.jar \ --master "$MASTER" \ --class "$CLASS_NAME" "$CLASS_JAR" $DEBUG \ --points "$POINTS" --method "$METHOD" --epsilon "$EPSILON" \ --partitions "$PARTITIONS" --capacity "$CAPACITY"
Markdown
UTF-8
1,219
2.59375
3
[]
no_license
# Employee-CRUD-Application-Using (REACT-js & SpringBoot) # Instructions to Run the application: # Softwares Needed are: 1. Spring Tool Suit 4 or Eclipse for running the JAVA SPRING MVC application(backend). 2. Postman for testing the server API. 3. Node js & React framework for the frontend. 4. Editor of your choice - *(VScode preferred) # Steps to Run : # Back-END 1. first Import the spring backend folder into your Spring Tool Suit. 2. Then the dependecies will automatically get downloaded from (Pom.xml) 3. Check the Application properties and make changes accordingly if any i.e (Ports etc) 4. I have used H2 Database for Query development. 5. Run the application as spring boot app. 6. Check the database on H2 console and Check the API Request on POSTMAN for CRUD ACTIONS - (GET,POST,PUT,DELETE) 7. Done with the backend part. # Front - End 1. Download the front-end folder into your personal location. 2. open the foler in VSCODE 3. start a New Terminal inside your directory. 4. run --> npm init 5. this will download all the required node modules. 6. then run--> npm start 7. Application will start on (localhost:3000) # HAPPY CODING.........>>
JavaScript
UTF-8
867
2.953125
3
[]
no_license
var heaDer = document.getElementById('header'); /* The first */ var sizeBrowser = window.innerWidth; var headerFix = document.getElementsByClassName('header__fix'); var checkClass = headerFix.length; if ((sizeBrowser < 1024) && (checkClass == 0)) { heaDer.classList.add('header__fix'); } if ((sizeBrowser >= 1024) && (checkClass == 1)) { heaDer.classList.remove('header__fix'); } /* When rotate screen */ document.getElementsByTagName("BODY")[0].onresize = function() {addClass()}; function addClass() { sizeBrowser = window.innerWidth; headerFix = document.getElementsByClassName('header__fix'); checkClass = headerFix.length; if ((sizeBrowser < 1024) && (checkClass == 0)) { heaDer.classList.add('header__fix'); } if ((sizeBrowser >= 1024) && (checkClass == 1)) { heaDer.classList.remove('header__fix'); } }
Markdown
UTF-8
643
2.8125
3
[ "MIT" ]
permissive
# Backbone-Weather-App Backbone.js Weather A Backbone.js app that grabs live weather data. This is an example of what I can make using Backbone.js and was created to get some more experience integrating it with a live API. It uses Backbone.js, Underscore.js, Open Weather Maps API, the Google Static Maps API, and Backbone.localStorage (https://github.com/jeromegn/Backbone.localStorage). This app will store the cities you've added in Local Storage in your browser, so the next time you visit the page the same cities will load again with fresh weather data. Try it out here - http://ijas.me/backbonejs/Backbone-Weather-App/index.html
C
UTF-8
1,784
3.609375
4
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <time.h> #include <assert.h> typedef struct { unsigned int n_rows; double* elements; } t_asm; //short for anti symmetric matrix //maping formula: col+row*n_rows - (row+1)(row+2)*0.5 double getElement(t_asm m, unsigned int r, unsigned int c){ double element; if(r==c){ element=0; }else if(r<c){ //right upper triangle unsigned int index= c + r*m.n_rows - ((r+1)*(r+2))/2; element= m.elements[index]; }else if(r>c){ //left lower triangle - invert col with row index unsigned int index= r + c*m.n_rows - ((c+1)*(c+2))/2; element= -m.elements[index]; } return element; } int main(int argc, char *argv[]){ int argok=0; t_asm m; if(argc==2){ unsigned int r; r=strtol(argv[1], NULL, 10); if(r>0){ if(r>UINT_MAX) r=UINT_MAX; //realistically, this program cannot handle more than r=0.5*(UINT_MAX)^0.5 m.n_rows=r; argok=1; } } if(!argok){ printf("USAGE: matrixgenantisym numrows\n"); exit(1); } //gauss formula to count the number of elements in the uptter triangular matrix (minus the diagunal); unsigned int n_upper = (m.n_rows*(m.n_rows-1))/2; m.elements=malloc(sizeof(double)*n_upper); srand((unsigned)time(NULL)); for(unsigned int i=0; i<n_upper; i++){ (m.elements)[i]=((double)rand()/(double)RAND_MAX)*2 -1; } size_t count = fwrite(&(m.n_rows), sizeof(unsigned int), 1, stdout); count += fwrite(&(m.n_rows), sizeof(unsigned int), 1, stdout); assert(count==2); count=0; for(unsigned int i=0; i<m.n_rows; ++i){ for (unsigned int j=0; j<m.n_rows; ++j){ double val=getElement(m, i, j); count+=fwrite(&val, sizeof(double), 1, stdout); } assert(count==m.n_rows); count=0; } free(m.elements); return 0; }
Java
UTF-8
1,351
2.609375
3
[]
no_license
package com.tienda.productos.testDominio; import com.tienda.productos.dominio.modelo.entidad.Categoria; import com.tienda.productos.dominio.modelo.entidad.Producto; public class ProductoDataBuilder { private static final Long ID=1l; private static final String NOMBRE="TENIS"; private static final String DESCRIPCION="deportivos"; private static final Double CANTIDAD=20.5; private static final Double PRECIO=200.5; private static final String ESTADO="CREADO"; private long id; private String nombre; private String descripcion; private Double cantidad; private Double precio; private String estado; private Categoria categoria; public ProductoDataBuilder() { this.id= ID; this.nombre=NOMBRE; this.descripcion=DESCRIPCION; this.cantidad=CANTIDAD; this.precio=PRECIO; this.estado=ESTADO; this.categoria=new CategoriaDataBuilder().build(); } public ProductoDataBuilder sinNombre(String nombre){ this.nombre=nombre; return this; } public ProductoDataBuilder sinCantidad(Double cantidad){ this.cantidad=cantidad; return this; } public Producto build(){ return new Producto(this.id,this.nombre,this.descripcion,this.cantidad,this.precio,this.estado,this.categoria); } }
Python
UTF-8
1,940
3.203125
3
[]
no_license
# **************************************************************************** # # # # ::: :::::::: # # operations.py :+: :+: :+: # # +:+ +:+ +:+ # # By: alpascal <[email protected]> +#+ +:+ +#+ # # +#+#+#+#+#+ +#+ # # Created: 2020/03/10 14:12:41 by alpascal #+# #+# # # Updated: 2020/03/10 14:44:00 by alpascal ### ########.fr # # # # **************************************************************************** # import sys def main(): if len(sys.argv) > 3: print ('InputError: too many arguments') return if len(sys.argv) < 3: print ('Usage: python operations.py <number1> <number2>') print ('Example:') print (' python operations.py 10 3') return for char in sys.argv[1]: if char.isdigit() != 1: print ('InputError: only numbers') return for char in sys.argv[2]: if char.isdigit() != 1: print ('InputError: only numbers') return print (f'Sum: ${int(sys.argv[1]) + int(sys.argv[2])}') print (f'Difference: ${int(sys.argv[1]) - int(sys.argv[2])}') print (f'Product: ${int(sys.argv[1]) * int(sys.argv[2])}') if int(int(sys.argv[2]) != 0): print (f'Quotient: ${int(sys.argv[1]) / int(sys.argv[2])}') print (f'Modulo: ${int(sys.argv[1]) % int(sys.argv[2])}') else: print (f'Quotient: Error (div by zero)') print (f'Modulo: Error (modulo by zero)') main()
Python
UTF-8
1,798
3.984375
4
[]
no_license
def checkPossibility(nums=[4,2,5,4]): ''' Because of the condition nums[i] <= nums[i+1], we iterate through array and have knowledge of two parts: 1.following Increasing order(Non decreasing) element (start from the left) 2. unknown ordering (start at the current i) On the left checked part, we have 0th, 1th ... i-1th elements are increasing order(Non decreasing), in order to be an increasing order, the next i element must be larger thani-1th element. Two cases: nums[i-1] > nums[i+1], [3,4,2,3] for example. if we are at 1th position, 0th's 3 > 2th's 2, since 3 is in the ordered part, the number after 3 must be larger than or equal to 3. Thus, we need to modify 2th's 2, which is nums[i+1] = nums[i]. nums[i-1] < nums[i+1], [1,4,2,3] for example. 1 is in the order, the number after 1 must be larger than or equal to 1. In this case, we modify ith element, which is nums[i] = nums[i+1]. :param nums: :return: ''' # O(n) time, O(1) space, iterate each element one by one check = False for i in range(len(nums) - 1): if nums[i] <= nums[i + 1]: continue else: # modify one time, make the modification as smaller as possible # case: first element if i == 0: nums[i] = nums[i + 1] check = True else: # nums[i-1] <= nums[i] since we pass condition from last check of nums[i] <= nums[i+1] if not check: if nums[i - 1] > nums[i + 1]: nums[i + 1] = nums[i] else: nums[i] = nums[i + 1] check = True else: return False return True print(checkPossibility())
C++
UTF-8
2,745
3.15625
3
[]
no_license
#pragma once #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> class Camera { glm::vec3 position; glm::vec3 target; glm::mat4 viewMatrix; void updateViewMatrix() { viewMatrix = glm::lookAt(position, target, glm::vec3(0.0f, 1.0f, 0.0f)); } public: Camera() {}; Camera(glm::vec3 position, glm::vec3 target) { this->position = position; this->target = target; updateViewMatrix(); } void setTarget(glm::vec3 target) { this->target = target; updateViewMatrix(); } void setPosition(glm::vec3 position) { this->position = position; updateViewMatrix(); } glm::mat4 getViewMatrix() { return viewMatrix; } glm::vec3 getPosition() { return position; } // rotates the target around the camera position void rotateYaw(float yaw) { target = position + glm::vec3(glm::rotate(glm::mat4(),yaw, glm::vec3(0,1,0)) * glm::vec4((target - position), 1.0f)); updateViewMatrix(); } // rotates the camera around the target void panYaw(float yaw) { position = target + glm::vec3(glm::rotate(glm::mat4(), yaw, glm::vec3(0, 1, 0)) * glm::vec4((position - target), 1.0f)); updateViewMatrix(); } void panPitch(float pitch) { glm::vec3 pitchDirection = glm::normalize(glm::cross(glm::vec3(0.0,1.0,0.0), target-position)); position = target + glm::vec3(glm::rotate(glm::mat4(), pitch, pitchDirection) * glm::vec4((position - target), 1.0f)); updateViewMatrix(); } void rotatePitch(float pitch) { glm::vec3 pitchDirection = glm::normalize(glm::cross(glm::vec3(0.0, 1.0, 0.0), target - position)); target = position + glm::vec3(glm::rotate(glm::mat4(), pitch, pitchDirection) * glm::vec4((target - position), 1.0f)); updateViewMatrix(); } void setPanPitch(float pitch) { float distance = glm::length(position - target); float dx = position.x - target.x; float dz = position.z - target.z; float newY = target.y + distance * glm::sin(pitch); float dy = newY - target.y; float scaleFactor = glm::sqrt((distance*distance-dy*dy)/(dx*dx + dz*dz)); float newX = target.x + dx * scaleFactor; float newZ = target.z + dz * scaleFactor; position = glm::vec3(newX, newY, newZ); updateViewMatrix(); } void setPanYaw(float yaw) { float dx = position.x - target.x; float dz = position.z - target.z; float r = glm::sqrt(dx*dx + dz*dz); auto tmp = position.y; position = glm::vec3(glm::rotate(glm::mat4(), yaw, glm::vec3(0, 1, 0)) * glm::vec4(0, 0, 1, 1)) * r; position.y = tmp; updateViewMatrix(); } void setCameraDistance(float distance) { position = target + glm::normalize(position - target) * distance; updateViewMatrix(); } void changeCameraDistance(float relativeChange) { position = target + (position - target) * relativeChange; updateViewMatrix(); } };
Python
UTF-8
5,683
2.828125
3
[]
no_license
import os import subprocess import codecs # codecs.open() handles unicode import datetime CURRDIR = os.getcwd() + '/' DEFCOLOR = 'COLOR_LIGHT_BLUE' C_N = '$none' C_LG = '$lgreen' C_G = '$green' C_B = '$blue' C_LB = '$lblue' C_R = '$red' C_GY = '$gray' C_P = '$purple' C_LP = '$lpurple' C_Y = '$yellow' #-------------- FORMATTING AND WRITING TO TERMINAL -------------------------# def pretty_string(s): # split camelCase, then make pretty lowers = [ 'a', 'an', 'and', 'da', 'du', 'is', 'in', 'on', 'of', 'the', 'to'] exceptions = [ ('I I I', 'III'), ('I I', 'II'), (' W ',' with '), (r'^[l|L]$',"l'"), (r'[i|I]m ',"I'm "),('O ',"O'"), (r'[w|W]hos ','Who\'s'),('D I A','DIA'), ('N Y C','NYC'),('N Y'),('NY'),('L A', 'LA'), ('freuds','freud\'s'), ('T N'),('TN'),('Didnt','Didn\'t'),('Dont','Don\'t'),('Lets','Let\'s'), ('Im','I\'m'),('Jaspers','Jasper\'s'),('Platos','Plato\s'), ('Sambos','Sambo\'s'),] title = re.sub(r'([a-z]*)([A-Z])', r'\1 \2', s) title = re.sub(r'([a-z]+)([0-9])', r'\1 \2', title) for l in lowers: l1 = ' ' + l.capitalize() + ' ' l2 = ' ' + l + ' ' title = re.sub(l1,l2,title) for e in exceptions: title = re.sub(e[0],e[1],title) title = title[0].upper() + title[1:] return title def pretty_file_name(l, artist = '', display = False): """Makes a human readable string from image file.""" file_name = list_to_dotstring(l) if artist == '': artist = pretty_string(l[0]) date = l[1] title = pretty_string(l[2]) if len(l) > 4: sub_title = '' for s in l[3:-1]: sub_title += pretty_string(s) title += ' (' + sub_title + ')' if display: s1 = s2 = ' ' if len(artist) < 12: s1 += (12 - len(artist)) * ' ' if len(date) < 8: s2 += (9 - len(date)) * ' ' cprint(C_Y,artist,s1,C_B,date,s2,C_P,title) return artist, date, title, file_name def color(s = ""): if s == '$none': c = '${COLOR_NC}\c' elif s == '$white': c = '${COLOR_WHITE}\c' elif s == '$black': c = '${COLOR_BLACK}\c' elif s == '$blue': c = '${COLOR_BLUE}\c' elif s == '$lblue': c = '${COLOR_LIGHT_BLUE}\c' elif s == '$green': c = '${COLOR_GREEN}\c' elif s == '$cyan': c = '${COLOR_CYAN}\c' elif s == '$lgreen': c = '${COLOR_LIGHT_GREEN}\c' elif s == '$lcyan': c = '${COLOR_LIGHT_CYAN}\c' elif s == '$red': c = '${COLOR_RED}\c' elif s == '$lred': c = '${COLOR_LIGHT_RED}\c' elif s == '$purple': c = '${COLOR_PURPLE}\c' elif s == '$lpurple': c = '${COLOR_LIGHT_PURPLE}\c' elif s == '$brown': c = '${COLOR_BROWN}\c' elif s == '$yellow': c = '${COLOR_YELLOW}\c' elif s == '$gray': c = '${COLOR_GRAY}\c' elif s == '$lgray': c = '${COLOR_LIGHT_GRAY}\c' else: c = '${' + DEFCOLOR + '}\c' call = 'echo "' + c + '"' subprocess.call(call, shell = True) def cprint(*print_list): """Take a list of strings, print them to terminal in color. Send a list of strings, if strings are color keywords, terminal color is changed. """ for s in print_list: s = str(s) if len(s) > 0 and s[0] == '$': color(s) else: call = 'echo "' + s + '\c"' subprocess.call(call, shell = True) color() print "" return def cprint_list(color,l,pretty=False): color(color) for item in l: if pretty: print pretty_string(item) else: print item color() def section(heading='*****'): cprint( '\n', C_Y,'***** ',C_B, heading.upper(), C_Y, ' *****') def menu(d,prompt='true'): """Take a dictionary, and turns it into a menu""" keys = [] try: title = d.pop('TITLE') section(title) except KeyError: section() sorted_d = sorted(d.items()) for key in sorted_d: row = [C_LB,' {0:10}'.format(key[0]),' : ',C_LG,'{}\n'.format(key[1])] keys.extend(row) cprint(*keys) if prompt: return raw_input('Enter Selection: ') #-------------- WRITING TO FILE --------------------------------------------# def write_list(l,f): """Writes list l, one item per line, to file f.""" count = 0 for item in l: try: f.write(item) except UnicodeDecodeError: cprint(C_R, 'error on {}'.format(item)) f.write('\n') count += 1 return count def write_dict(l,f): count = 0 for k, v in sorted(l.items()): item = k + ', ' + v f.write(item) f.write('\n') count += 1 return count def write_to_file(l,file_name,title,o_type='list', mode='w'): """Save a list to a file""" file_path = CURRDIR + file_name cprint(C_G, "file saving mode: ", mode) f = codecs.open(file_path, encoding='utf-8', mode=mode) count = 0 now = str(datetime.datetime.now()) now_stamp = '##### Generated: ' + now + '\n\n' hash_title = '# ' + title f.write(hash_title) f.write('\n') f.write(now_stamp) if o_type == 'list': count = write_list(l,f) elif o_type == 'dict': count = write_dict(l,f) end_title = """ ##### end generated log ##### total items = """ + str(count) + '\n\n' f.write(end_title) f.close() cprint (C_G, 'Saved ', C_P, title, C_G, ' to file ', C_LG, file_path) return
JavaScript
UTF-8
876
3.4375
3
[]
no_license
// BOX // Map is a type of composition. // Composition is good at unnesting expressions. // Box is not always better, use it as it fits. const Box = (x) => ({ map: fn => Box(fn(x)), fold: fn => fn(x), inspect: () => `Box(${x})` }) const moneyToFloat = (str) => Box(str) .map(s => s.replace(/\$/g, '')) .map(s => parseFloat(s)) const percentToFloat = (str) => Box(str.replace(/\$/g, '')) .map(s => parseFloat(s)) .map(number => number * 0.01) const composedApplyDiscount = (price, discount) => { // Encapsulate cost into a closure to be used by percentToFloat fold method. // There are two folds, since we are two level deep, 2 Boxes: moneyToFloat and percentToFloat. return moneyToFloat(price) .fold(cost => percentToFloat(discount) .fold(savings => cost - (cost * savings)) ) } module.exports = composedApplyDiscount
Python
UTF-8
1,039
3.0625
3
[]
no_license
class Solution(object): def rotatedDigits(self, N): """ :type N: int :rtype: int """ def isMagic(n): lstn = [int(i) for i in str(n) ] #print "isMagic lstn",lstn for i in range(len(lstn)): if lstn[i] == 3 or lstn[i] == 4 or lstn[i] == 7: return 0 if lstn[i] == 2: lstn[i] = 5 elif lstn[i] == 5: lstn[i] = 2 elif lstn[i] == 6: lstn[i] = 9 elif lstn[i] == 9: lstn[i] = 6 tmp = "" for i in lstn: tmp +=str(i) return int(tmp)!=n cnt = 0 for i in xrange(1,N+1): cnt += isMagic(i) return cnt sol = Solution() test_data = [857] for d in test_data: print sol.rotatedDigits(d)
Python
UTF-8
1,084
3.640625
4
[]
no_license
#.................................................. # OOP_magic_method : #.................................................. # Everything in python is an object # __init__ called automatically when instantiated class # self.__class__ the class to which class instance belong # __str__ gives a human readable output of the object # __len__ gives the length of the container # called when builtin len function used in the object #.................................................. class Skill : def __init__(self) : self.skills = ['Html','Css','Js'] def __str__(self) -> str: return f"This is my Skills : {self.skills}" def __len__(self) : return len(self.skills) profile = Skill() print(profile) # <__main__.Skill object at 0x0000020AAD29CB50> print(len(profile)) profile.skills.append("PHP") profile.skills.append("MySQL") print(len(profile)) print(profile.__class__) # to which class belong to(name of class) print('*'*50) string = 'osama' print(type(string)) # <class 'str'> # print(string.__class__) # <class 'str'> # print(dir(str))
Java
UTF-8
16,280
3.078125
3
[]
no_license
package edu.sapi.mestint; import java.util.Scanner; public class Amoba { public static int X; public static int O; public static int EMPTY; private int n; private int line; private int[][] table = new int[][] { new int[]{0, 0, 0, 0, 0, 0, 0, 0}, new int[]{0, 0, 0, 0, 0, 0, 0, 0}, new int[]{0, 0, 0, 0, 0, 0, 0, 0}, new int[]{0, 0, 0, 0, 0, 0, 0, 0}, new int[]{0, 0, 0, 0, 0, 0, 0, 0}, new int[]{0, 0, 0, 0, 0, 0, 0, 0}, new int[]{0, 0, 0, 0, 0, 0, 0, 0}, new int[]{0, 0, 0, 0, 0, 0, 0, 0}, }; public Amoba(int n, int line) { this.n = n; this.line = line; X = 2; EMPTY = 0; O = line * X + X; } public static void main(String[] args) { int depth = 3; Amoba amoba = new Amoba(8, 5); AmobaSolver solver = new AmobaSolver(amoba); Scanner scanner = new Scanner(System.in); int humanFigure; int computerFigure; int computerPlayerType = AmobaSolver.MAX; System.out.println("Choose figure X or O"); String resp = scanner.next(); while (!"x".equals(resp.toLowerCase()) && !"o".equals(resp.toLowerCase())) { System.out.println("Invalid figure choose X or O"); resp = scanner.next(); } if ("x".equals(resp.toLowerCase())) { humanFigure = AmobaSolver.X; computerFigure = AmobaSolver.O; } else { humanFigure = AmobaSolver.O; computerFigure = AmobaSolver.X; } System.out.println("Figure choosed: " + resp.toUpperCase()); System.out.println("Do you want to start? y/n"); resp = scanner.next(); while (!"y".equals(resp.toLowerCase()) && !"n".equals(resp.toLowerCase())) { System.out.println("Invalid response choose y or n"); resp = scanner.next(); } int player = "y".equals(resp.toLowerCase()) ? humanFigure : computerFigure; amoba.printOut(); boolean full = false; while (!full) { if (player == humanFigure) { humanStep(amoba, humanFigure, scanner); if (amoba.isSolved()) { System.out.println("You won!"); break; } player = computerFigure; } else { solver.putOnTable(player, computerPlayerType, 0, false, 4, true); if (amoba.isSolved()) { System.out.println("Computer wins!"); break; } player = humanFigure; } amoba.printOut(); full = amoba.isDrawn(); } if (full) { System.out.println("No winner!"); } amoba.printOut(); scanner.close(); } public static void humanStep(Amoba amoba, int figure, Scanner scanner) { System.out.println("Your step, enter coordinates"); int row = 0, column = 0; boolean ok = true; do { if (!ok) { System.out.println("That spot is already taken. Choose another one."); } System.out.println("Row"); row = scanner.nextInt(); while ((row < 1) || (row > 8)) { System.out.println("Invalid coordinate for row, value must be [1-8]"); row = scanner.nextInt(); } System.out.println("Column"); column = scanner.nextInt(); while ((column < 1) || (column > 8)) { System.out.println("Invalid coordinate for column, value must be [1-8]"); column = scanner.nextInt(); } ok = amoba.isEmpty(row - 1, column - 1); } while (!ok); amoba.placeElement(row - 1, column - 1, figure == 0 ? X : O); } public boolean isSolved() { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (table[i][j] != EMPTY) { if (isEastVestSolved(i, j)) { return true; } else if (isNordSouthSolved(i, j)) { return true; } else if (isEastSouthSolved(i, j)) { return true; } else if (isNorthEastSolved(i, j)) { return true; } } } } return false; } public boolean isDrawn() { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (table[i][j] == EMPTY) { return false; } } } return true; } private boolean isEastVestSolved(int i, int j) { if (j + line > n) { return false; } else { int sum = 0; for (int k = j; k < j + line; ++k) { sum += table[i][k]; } return sum == line * X || sum == line * O; } } private boolean isNordSouthSolved(int i, int j) { if (i - line < -1) { return false; } else { int sum = 0; for (int k = i; k > i - line; --k) { sum += table[k][j]; } return sum == line * X || sum == line * O; } } private boolean isEastSouthSolved(int i, int j) { if (i + line > n || j + line > n) { return false; } else { int sum = 0; for (int k = 0; k < line; ++k) { sum += table[i + k][j + k]; } return sum == line * X || sum == line * O; } } private boolean isNorthEastSolved(int i, int j) { if (i - line < -1 || j + line > n) { return false; } else { int sum = 0; for (int k = 0; k < line; ++k) { sum += table[i - k][j + k]; } return sum == line * X || sum == line * O; } } public void printOut() { System.out.print(" "); for (int i = 1; i <= n; i++) { System.out.print(i + " "); } System.out.println(); for (int i = 0; i < n; i++) { System.out.print((i + 1) + " "); for (int j = 0; j < n; j++) { if (table[i][j] == EMPTY) { System.out.print("_ "); } else if (table[i][j] == X) { System.out.print("X "); } else { System.out.print("O "); } } System.out.println(); } System.out.println(); } public int getDimension() { return n; } private int getOpposite(int type) { if (type == X) { return O; } return X; } public boolean isEmpty(int i, int j) { return table[i][j] == EMPTY; } public void placeElement(int i, int j, int element) { table[i][j] = element; } public double getEstimatedValue(int i, int j) { if (isSolved()) { return 1; } double value = 0; value += getEastValue(i, j, false); value += getVestValue(i, j, false); value += getNorthValue(i, j, false); value += getSouthValue(i, j, false); value += getNorthEastValue(i, j, false); value += getNorthVestValue(i, j, false); value += getSouthVestValue(i, j, false); value += getSouthEastValue(i, j, false); return value; } private double getEastValue(int i, int j, boolean opposite) { final int currentVal = table[i][j]; final int oppositeVal = getOpposite(table[i][j]); double numOfCurrent = 0; double numOfOpposite = 0; for (int k = 1; k < line; k++) { if (j + k < n) { if (table[i][j + k] == currentVal) { numOfCurrent += 1; } else { break; } } else { break; } } for (int k = 1; k < line; k++) { if (j + k < n) { if (table[i][j + k] == oppositeVal) { numOfOpposite += 1; } else { break; } } else { break; } } double currVal = 1 / (16 * Math.pow(2, (line - numOfCurrent))); double oppsVal = 1 / (16 * Math.pow(2, (line - numOfOpposite))); return currVal + oppsVal; } private double getVestValue(int i, int j, boolean opposite) { final int currentVal = table[i][j]; final int oppositeVal = getOpposite(table[i][j]); double numOfCurrent = 0; double numOfOpposite = 0; for (int k = 1; k < line; k++) { if (j - k >= 0) { if (table[i][j - k] == currentVal) { numOfCurrent += 1; } else { break; } } else { break; } } for (int k = 1; k < line; k++) { if (j - k >= 0) { if (table[i][j - k] == oppositeVal) { numOfOpposite += 1; } else { break; } } else { break; } } double currVal = 1 / (16 * Math.pow(2, (line - numOfCurrent))); double oppsVal = 1 / (16 * Math.pow(2, (line - numOfOpposite))); return currVal + oppsVal; } private double getNorthValue(int i, int j, boolean opposite) { final int currentVal = table[i][j]; final int oppositeVal = getOpposite(table[i][j]); double numOfCurrent = 0; double numOfOpposite = 0; for (int k = 1; k < line; k++) { if (i - k >= 0) { if (table[i - k][j] == currentVal) { numOfCurrent += 1; } else { break; } } else { break; } } for (int k = 1; k < line; k++) { if (i - k >= 0) { if (table[i - k][j] == oppositeVal) { numOfOpposite += 1; } else { break; } } else { break; } } double currVal = 1 / (16 * Math.pow(2, (line - numOfCurrent))); double oppsVal = 1 / (16 * Math.pow(2, (line - numOfOpposite))); return currVal + oppsVal; } private double getSouthValue(int i, int j, boolean opposite) { final int currentVal = table[i][j]; final int oppositeVal = getOpposite(table[i][j]); double numOfCurrent = 0; double numOfOpposite = 0; for (int k = 1; k < line; k++) { if (i + k < n) { if (table[i + k][j] == currentVal) { numOfCurrent += 1; } else { break; } } else { break; } } for (int k = 1; k < line; k++) { if (i + k < n) { if (table[i + k][j] == oppositeVal) { numOfOpposite += 1; } else { break; } } else { break; } } double currVal = 1 / (16 * Math.pow(2, (line - numOfCurrent))); double oppsVal = 1 / (16 * Math.pow(2, (line - numOfOpposite))); return currVal + oppsVal; } private double getNorthEastValue(int i, int j, boolean opposite) { final int currentVal = table[i][j]; final int oppositeVal = getOpposite(table[i][j]); double numOfCurrent = 0; double numOfOpposite = 0; for (int k = 1; k < line; k++) { if (i - k >= 0 && j + k < n) { if (table[i - k][j + k] == currentVal) { numOfCurrent += 1; } else { break; } } else { break; } } for (int k = 1; k < line; k++) { if (i - k >= 0 && j + k < n) { if (table[i - k][j + k] == oppositeVal) { numOfOpposite += 1; } else { break; } } else { break; } } double currVal = 1 / (16 * Math.pow(2, (line - numOfCurrent))); double oppsVal = 1 / (16 * Math.pow(2, (line - numOfOpposite))); return currVal + oppsVal; } private double getNorthVestValue(int i, int j, boolean opposite) { final int currentVal = table[i][j]; final int oppositeVal = getOpposite(table[i][j]); double numOfCurrent = 0; double numOfOpposite = 0; for (int k = 1; k < line; k++) { if (i - k >= 0 && j - k >= 0) { if (table[i - k][j - k] == currentVal) { numOfCurrent += 1; } else { break; } } else { break; } } for (int k = 1; k < line; k++) { if (i - k >= 0 && j - k >= 0) { if (table[i - k][j - k] == oppositeVal) { numOfOpposite += 1; } else { break; } } else { break; } } double currVal = 1 / (16 * Math.pow(2, (line - numOfCurrent))); double oppsVal = 1 / (16 * Math.pow(2, (line - numOfOpposite))); return currVal + oppsVal; } private double getSouthVestValue(int i, int j, boolean opposite) { final int currentVal = table[i][j]; final int oppositeVal = getOpposite(table[i][j]); double numOfCurrent = 0; double numOfOpposite = 0; for (int k = 1; k < line; k++) { if (i + k < n && j - k >= 0) { if (table[i + k][j - k] == currentVal) { numOfCurrent += 1; } else { break; } } else { break; } } for (int k = 1; k < line; k++) { if (i + k < n && j - k >= 0) { if (table[i + k][j - k] == oppositeVal) { numOfOpposite += 1; } else { break; } } else { break; } } double currVal = 1 / (16 * Math.pow(2, (line - numOfCurrent))); double oppsVal = 1 / (16 * Math.pow(2, (line - numOfOpposite))); return currVal + oppsVal; } private double getSouthEastValue(int i, int j, boolean opposite) { final int currentVal = table[i][j]; final int oppositeVal = getOpposite(table[i][j]); double numOfCurrent = 0; double numOfOpposite = 0; for (int k = 1; k < line; k++) { if (i + k < n && j + k < n) { if (table[i + k][j + k] == currentVal) { numOfCurrent += 1; } else { break; } } else { break; } } for (int k = 1; k < line; k++) { if (i + k < n && j + k < n) { if (table[i + k][j + k] == oppositeVal) { numOfOpposite += 1; } else { break; } } else { break; } } double currVal = 1 / (16 * Math.pow(2, (line - numOfCurrent))); double oppsVal = 1 / (16 * Math.pow(2, (line - numOfOpposite))); return currVal + oppsVal; } public int[][] getTable() { return table; } }
Java
UTF-8
610
2.171875
2
[]
no_license
package org.denis.wix.test.pageobject; import java.util.List; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; public class GoogleResults { @FindBy(css="div.g div.rc h3 > a") private List<WebElement> results; public GoogleResults(WebDriver driver) { PageFactory.initElements(driver, this); } public void clickResult(int num) { if (results != null && results.size()>= num) { results.get(num).click(); } } public List<WebElement> getResults(){ return results; } }
C++
UTF-8
263
2.578125
3
[]
no_license
#include <iostream> using namespace std; int main() { int nomor = 0; cout<<"contoh for\n"; cout<<"oleh ADE NEVIYANI\n\n"; cout<<"tampilkan perhitungan sampai : "; cin>>nomor; for(int i=1;i<=nomor;i++){ cout<<i<<endl; } return 0; }
Java
UTF-8
1,358
3.09375
3
[]
no_license
package lt_500_599; import java.util.HashSet; import java.util.Set; /** * [547] Friend Circles * union-find */ public class LC_547 { /** * union-find * @param friends * @param id * @return */ private int topFriends(int[] friends, int id) { if (friends[id] == id) { return id; } // 路径压缩 int top = topFriends(friends, friends[id]); friends[id] = top; return top; } public int findCircleNum(int[][] M) { int N = M.length; if (N <= 1) { return N; } int[] friends = new int[N]; for (int i = 0; i < N; ++i) { friends[i] = i; } for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) { if (M[i][j] == 1 && i!=j) { int top1 = topFriends(friends, i); int top2 = topFriends(friends, j); friends[top1] = top2; } } } Set<Integer> set = new HashSet<>(); for (int i = 0; i < N; ++i) { set.add(topFriends(friends, i)); } return set.size(); } public static void main(String ...args) { int[][] M = {{1,1,0}, {1,1,0},{0,0,1}}; System.out.println(new LC_547().findCircleNum(M)); } }
Java
UTF-8
779
2.28125
2
[]
no_license
package domain.mediator.patient; import java.io.IOException; import java.rmi.Remote; import java.rmi.RemoteException; import java.util.ArrayList; import domain.model.patient.Patient; public interface RemotePatientModel extends Remote { public void LoadFromDB(String name) throws IOException, RemoteException; public void addPatient(String[] patientData) throws RemoteException; public ArrayList<Patient> getPatientByName(String name) throws RemoteException; public void removePatientById(int id) throws RemoteException; public ArrayList<Patient> getAllPatientsFromTheList() throws RemoteException; public void updatePatient(Patient patient) throws RemoteException; public Patient getPatientByIdFromList(int id) throws RemoteException; }
Markdown
UTF-8
887
2.515625
3
[]
no_license
# CCI-Computational-Environments Unit 6 Exam Guided Frequencies is a virtual environment built with Three.js to help people relax, practice mindfulness and meditation. It uses PoseNet a machine learning model that uses real-time human pose estimation to allow the user to personalise their experience within the digital environment by controlling a Low-Frequency Oscillator blending and creating harmonies with audio in the scene. It also features Quotable API bringing in a random motivational quote into the space allowing for the user to help think positively on arrival to the digital environment. The environment helps bring ideas and mindfulness and meditation techniques and to people at home who may suffer social anxiety with going to physical classes as well as those who want a more personalised environment to practice their own mediative and mindfulness techniques.
C++
UTF-8
19,503
2.71875
3
[]
no_license
#include "chinesechesslogic.h" #include <QDebug> #define ROW 10 #define COL 9 #define NUL 0 #define RED 1 #define BLACK 2 //十行九列 // 小写黑 大写红 unsigned char arryChessBoard[ROW][COL]={ 'c','m','x','s','j','s','x','m','c', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,'p', 0, 0, 0, 0, 0,'p', 0, 'b', 0,'b', 0,'b', 0,'b', 0,'b', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'B', 0,'B', 0,'B', 0,'B', 0,'B', 0,'P', 0, 0, 0, 0, 0,'P', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 'C','M','X','S','J','S','X','M','C', }; ChineseChessLogic::ChineseChessLogic() { initChessBoard(); } void ChineseChessLogic::initChessBoard() { m_toJiangX = -1; m_toJiangY = -1; m_state = enState::BeFine; memcpy_s(m_arryChessBoard,sizeof(m_arryChessBoard),arryChessBoard,sizeof(arryChessBoard)); m_setInfo.clear(); } bool ChineseChessLogic::CanMove(int x, int y, int toX, int toY) { // x代表着列 y代表行 if(ROW<=x || COL<=y || (x == toX && y == toY))return false; //颜色相同则不符合规则(含0x00) if(judgmetColor(x,y) == judgmetColor(toX,toY)) { qDebug()<<"踩到自己人了"; return false; } //获取棋子类型 bool isOk = false; unsigned char piece = m_arryChessBoard[x][y]; //qDebug()<<"当前棋子:"<<piece <<" ->"<<m_arryChessBoard[toX][toY]; switch (piece) { case 'C': case 'c': // qDebug()<<"车的走法"; isOk = verifyChe(x,y,toX,toY); break; case 'M': case 'm': //qDebug()<<"马的走法"; isOk = verifyMa(x,y,toX,toY); break; case 'X': case 'x': //qDebug()<<"象的走法"; isOk = verifyXiang(x,y,toX,toY); break; case 'S': case 's': //qDebug()<<"士的走法"; isOk = verifyShi(x,y,toX,toY); break; case 'J': case 'j': //qDebug()<<"将军的走法"; isOk = verifyJiang(x,y,toX,toY); break; case 'P': case 'p': //qDebug()<<"大炮的走法"; isOk = verifyPao(x,y,toX,toY); break; case 'B': case 'b': //qDebug()<<"兵的走法"; isOk = verifyBing(x,y,toX,toY); break; default: break; } if(isOk) { //qDebug()<<"成功"; //qDebug()<<x<<"成功"<<y; //两位将军不能见面 int bX = 0, bY = 0; int rX = 0, rY = 0; getPos('j', bX, bY); getPos('J', rX, rY); if(bY == rY && ((toX != bX && toY != bY) ||(toX != rX && toY != rY) ) ) { // 两位将军之间是否存在棋子 bool isCan = false; for(int i=bX+1 ; i<rX; i++) { //假设棋子已经移动 if(i == x && y == rY) continue; if( (i == toX && rY == toY) || 0 < m_arryChessBoard[i][rY]) { isCan = true; break; } } qDebug()<<"黑方将军位置:"<<bX<<" "<<bY<<" 红方将军位置:"<<rX<<" "<<rY; if(!isCan) return false; } setInfo* info = new setInfo(); info->x = x; info->y = y; info->toX = toX; info->toY = toY; info->prePiece = m_arryChessBoard[x][y]; info->nowPiece = m_arryChessBoard[toX][toY]; qDebug()<<x<<"缓存前"<<y; m_setInfo.append(info); qDebug()<<toX<<"缓存后"<<toY; m_arryChessBoard[toX][toY] = m_arryChessBoard[x][y]; m_arryChessBoard[x][y] = 0; } return isOk; } void ChineseChessLogic::Rollback() { int nIndex = m_setInfo.size(); if( 0 < nIndex ) { setInfo* v = m_setInfo.at(nIndex-1); m_arryChessBoard[v->x][v->y] = v->prePiece; m_arryChessBoard[v->toX][v->toY] = v->nowPiece; qDebug()<<"回滚中..."<<v->x<<" -->" << v->y <<" 棋子-->"<< (int)v->prePiece <<" "<<(int)v->nowPiece; m_setInfo.removeAt(nIndex-1); delete v; v = nullptr; } } bool ChineseChessLogic::JiangJun(int x, int y, bool isSavePos) { m_state = enState::BeFine; if(0 == m_arryChessBoard[x][y]) return false; int toBX = 0; int toBY = 0; int toRX = 0; int toRY = 0; unsigned char piece = 0; unsigned char whichSide = judgmetColor(x,y); // 看下是哪一方. // 获取黑方将军的坐标 getPos('j', toBX, toBY); getPos('J', toRX, toRY); // qDebug()<<"黑方将军坐标:"<<toX<<" "<<toY; //校验当前的棋子是否可以到达将军的位置 for(int i=0; i<ROW; i++) { for(int j=0; j<COL; j++) { if('A'<m_arryChessBoard[i][j] && m_arryChessBoard[i][j]<'S') { piece = m_arryChessBoard[i][j]; if(CanMove(i,j, toBX, toBY)) {//还原坐标 m_arryChessBoard[toBX][toBY] = 'j'; m_arryChessBoard[i][j] = piece; if(BLACK == whichSide) { Rollback(); m_state = enState::BeBad; return false; } else { m_state = enState::BeBJiang; if(isSavePos) { m_toJiangX = i; m_toJiangY = j; } return true; } } } else if('a'<m_arryChessBoard[i][j] && m_arryChessBoard[i][j]<'s') { piece = m_arryChessBoard[i][j]; if(CanMove(i,j, toRX, toRY)) {//还原坐标 m_arryChessBoard[toRX][toRY] = 'J'; m_arryChessBoard[i][j] = piece; if(RED == whichSide) { Rollback(); m_state = enState::BeBad; return false; } else { m_state = enState::BeRJiang; if(isSavePos) { m_toJiangX = i; m_toJiangY = j; } return true; } } } } } m_state = enState::BeFine; return false; } ChineseChessLogic::enState ChineseChessLogic::JudgeWin() { //校验输赢 //将军的位置 int jiangX = 0, jiangY = 0; int minX = 0, maxX = 0; int nCount = 0; //四个方位 //黑方将军是否能移动 bool bJiang = false; enState nSate = m_state; if((enState::BeBJiang == nSate && getPos('j',jiangX,jiangY))) { //黑 移动范围 0 1 2行 3 4 5列 minX = 0; maxX = 3; bJiang = true; } else if(enState::BeRJiang == nSate && getPos('J',jiangX,jiangY)) { //红 移动范围 7 8 9行 3 4 5列 minX = 7; maxX = 10; bJiang = true; } if(bJiang) {//校验将军的可行走位置 if(minX <= jiangX-1)// { if(CanMove(jiangX, jiangY, jiangX-1, jiangY)) { JiangJun(jiangX-1, jiangY,false); if(enState::BeBad == m_state || nSate == m_state) nCount++; Rollback(); } else { nCount++; } }else { nCount++; } if(jiangX+1 < maxX)// { if(CanMove(jiangX, jiangY, jiangX+1, jiangY)) { JiangJun(jiangX+1,jiangY,false); if(enState::BeBad == m_state || nSate == m_state) nCount++; Rollback(); }else { nCount++; } } else { nCount++; } //----------------------// if(3 <= jiangY-1)// { if(CanMove(jiangX, jiangY, jiangX, jiangY-1)) { JiangJun(jiangX,jiangY-1,false); if(enState::BeBad == m_state || nSate == m_state) nCount++; Rollback(); } else { nCount++; } } else { nCount++; } if(jiangY+1 < 6)// { if(CanMove(jiangX, jiangY, jiangX, jiangY+1)) { JiangJun(jiangX, jiangY+1,false); if(enState::BeBad == m_state || nSate == m_state) nCount++; Rollback(); } else { nCount++; } } else { nCount++; } qDebug()<<"---->不能走的步数<----"<<nCount<<" X:"<<m_toJiangX<<" Y:"<<m_toJiangY<<" 棋子"<<(int)m_arryChessBoard[m_toJiangX][m_toJiangY]; if(4 == nCount) {//帅不能动弹,检测其他棋子能否救帅(帮帅挡枪,替帅去死) if('M' == m_arryChessBoard[m_toJiangX][m_toJiangY] || 'm' == m_arryChessBoard[m_toJiangX][m_toJiangY]) {//挡住马脚 return nSate; } else if('P' == m_arryChessBoard[m_toJiangX][m_toJiangY] || 'p' == m_arryChessBoard[m_toJiangX][m_toJiangY]\ ||'C' == m_arryChessBoard[m_toJiangX][m_toJiangY] || 'c' == m_arryChessBoard[m_toJiangX][m_toJiangY]) {//若是炮车 则挡在敌方的前面 return nSate; } nSate = (enState::BeRJiang == nSate) ? enState::RedWin : enState::BlackWin; } } m_state = nSate; return m_state; } bool ChineseChessLogic::verifyChe(int x, int y, int toX, int toY) { if ('C' == m_arryChessBoard[x][y] || 'c' == m_arryChessBoard[x][y]) {//确认 棋子 //车的走法 必须同一行 或者 同一列 if(x == toX) {//若同一行 则校验 直到toY列中是否包含其他棋子 int start = y; int end = toY; if(toY < y){ start = toY; end = y; } for(int i=start+1; i<end; i++){ if(0 < m_arryChessBoard[x][i]) { qDebug()<<"遇到障碍 "<<m_arryChessBoard[x][i]; return false; } } }else if(y == toY) {//若同一列 则校验 直到toX行中是否包含其他棋子 int start = x; int end = toX; if(toX < x){ start = toX; end = x; } for(int i=start+1; i<end; i++){ if(0 < m_arryChessBoard[i][y]) { qDebug()<<"遇到障碍 "<<m_arryChessBoard[i][y]; return false; } } }else{ return false; } return true; } qDebug()<<"不是车 "<<m_arryChessBoard[x][y]; return false; } bool ChineseChessLogic::verifyMa(int x, int y, int toX, int toY) { if (('M' == m_arryChessBoard[x][y] ||'m' == m_arryChessBoard[x][y] )&& x != toX && y != toY) { //马的走法 必须不在同一行 且 不在同一列 if(toX - x == 2 ) {//竖着走 校验马脚 if(0 < m_arryChessBoard[x+1][y]) { qDebug()<<"挡住马脚了"; return false; } return y == toY-1 || y == toY+1; } else if(toX - x == -2) { if(0 < m_arryChessBoard[x-1][y]) { qDebug()<<"挡住马脚了"; return false; } return y == toY-1 || y == toY+1; }else if(toY - y == 2) {//横着走 if(0 < m_arryChessBoard[x][y+1]) { qDebug()<<"挡住马脚了"; return false; } return x == toX-1 || x == toX+1; }else if(toY - y == -2) { if(0 < m_arryChessBoard[x][y-1]) { qDebug()<<"挡住马脚了"; return false; } return x == toX-1 || x == toX+1; } } return false; } bool ChineseChessLogic::verifyXiang(int x, int y, int toX, int toY) { if (('X' == m_arryChessBoard[x][y] || 'x' == m_arryChessBoard[x][y]) && x != toX && y != toY) {//象的走法 不能过河 走田字 //不能挡住象脚 if(0 < m_arryChessBoard[(x+toX)/2][(y+toY)/2]) { qDebug()<<"挡住像脚了"; return false; } unsigned char whichSide = judgmetColor(x,y); // 看下是哪一方的象. if(RED == whichSide) {//红 if(toX<5) { qDebug()<<"不能过河"; return false; } return (x == toX+2 || x == toX-2) && (y == toY+2 || y == toY-2); }else if(BLACK == whichSide) {//黑 if(4<toX) { qDebug()<<"不能过河"; return false; } return (x == toX+2 || x == toX-2) && (y == toY+2 || y == toY-2); } } return false; } bool ChineseChessLogic::verifyShi(int x, int y, int toX, int toY) { if (('S' == m_arryChessBoard[x][y] || 's' == m_arryChessBoard[x][y]) && x != toX && y != toY) {//仕的走法 必须不在同一行且不在同一列 只能是斜着走 unsigned char whichSide = judgmetColor(x,y); // 看下是哪一方的卫仕. if(RED == whichSide) {//红 移动范围 7 8 9行 3 4 5列 if(7<=toX && toX<10 && 3<=toY && toY<6) { return (x == toX+1 || x == toX-1) && (y == toY+1 || y == toY-1); } }else if(BLACK == whichSide) {//黑 移动范围 0 1 2行 3 4 5列 if(0<=toX && toX<3 && 3<=toY && toY<6) { return (x == toX+1 || x == toX-1) && (y == toY+1 || y == toY-1); } } } return false; } bool ChineseChessLogic::verifyJiang(int x, int y, int toX, int toY) { if ('J' == m_arryChessBoard[x][y] || 'j' == m_arryChessBoard[x][y]) { int startX = 0; int endX = 0; int rX = 0, rY = 0; if('j' == m_arryChessBoard[x][y]) { getPos('J', rX, rY); startX = toX; endX = rX; }else{ getPos('j', rX, rY); startX = rX; endX = toX; } //---------------- if(toY == rY) { // 两位将军之间是否存在棋子 bool isCan = false; for(int i=startX+1; i<endX; i++) { if(0 < m_arryChessBoard[i][rY]) { isCan = true; break; } } if(!isCan) return false; } unsigned char whichSide = judgmetColor(x,y); // 看下是哪一方的将军. if(RED == whichSide) {//红 移动范围 7 8 COL行 3 4 5列 if(7<=toX && toX<ROW && 3<=toY && toY<6) { return (x == toX && (y == toY+1||y==toY-1)) || (y == toY &&(x == toX+1||x==toX-1)); } }else if(BLACK == whichSide) {//黑 移动范围 0 1 2行 3 4 5列 if(0<=toX && toX<3 && 3<=toY && toY<6) { return (x == toX && (y == toY+1||y==toY-1)) || (y == toY &&(x == toX+1||x==toX-1)); } } } return false; } bool ChineseChessLogic::verifyPao(int x, int y, int toX, int toY) { if ('P' == m_arryChessBoard[x][y] || 'p' == m_arryChessBoard[x][y]) { //跑的走法 必须同一行 或者 同一列 if(x == toX) {//若同一行 则校验 直到toY列中是否包含其他棋子 int start = y; int end = toY; if(toY < y){ start = toY; end = y; } if(0 == m_arryChessBoard[toX][toY]) {//如果目标地 是空,校验是否有障碍物 for(int i=start+1; i<end; i++){ if(0 < m_arryChessBoard[x][i]) { qDebug()<<"遇到障碍 "<<m_arryChessBoard[x][i]; return false; } } }else {//如果是敌方棋子,校验是否前面有一个障碍 int nCount = 0; for(int i=start+1; i<end; i++){ if(0 < m_arryChessBoard[x][i]) nCount++; } if (1 != nCount) return false; } }else if(y == toY) {//若同一列 则校验 直到toX行中是否包含其他棋子 int start = x; int end = toX; if(toX < x){ start = toX; end = x; } if(0 == m_arryChessBoard[toX][toY]) {//如果目标地 是空,校验是否有障碍物 for(int i=start+1; i<end; i++){ if(0 < m_arryChessBoard[i][y]) { qDebug()<<"遇到障碍 "<<m_arryChessBoard[i][y]; return false; } } }else {//如果是敌方棋子,校验是否前面有一个障碍 int nCount = 0; for(int i=start+1; i<end; i++){ if(0 < m_arryChessBoard[i][y]) nCount++; } if (1 != nCount) return false; } }else{ return false; } return true; } return false; } bool ChineseChessLogic::verifyBing(int x, int y, int toX, int toY) { if ('B' == m_arryChessBoard[x][y] || 'b' == m_arryChessBoard[x][y]) { // 兵 不能往回走,且只能一步步走. 过河之后 才能左右走. unsigned char whichSide = judgmetColor(x,y); // 看下是哪一方的来兵. if(RED == whichSide) {//红方面军 任何时候向前一步都是可以 ->过河之后 同一行时,只能左右走 return (x == toX+1 && y == toY) || (x < 5 && (toX == x && (y == toY+1 || y == toY-1))); }else if(BLACK == whichSide) {//黑方面军 return (x == toX-1 && y == toY) || (4 < x && (toX == x && (y == toY+1 || y == toY-1))); } } return false; } bool ChineseChessLogic::getPos(unsigned char piece, int &x, int &y) { for(int i=0; i<ROW; i++) { for(int j=0; j<COL; j++) { if(piece == m_arryChessBoard[i][j]) { x = i; y = j; return true; } } } return false; } unsigned char ChineseChessLogic::judgmetColor(int x, int y) { if(0 == m_arryChessBoard[x][y]){//蓝 return NUL; } if(0x41 < m_arryChessBoard[x][y] && m_arryChessBoard[x][y] < 0x5A){//红 return RED; }else{//黑 return BLACK; } }
Java
UTF-8
3,544
1.929688
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package zw.co.hitrac.support.business.domain.Pysch; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import zw.co.hitrac.support.business.domain.Demo.Demographic; /** * * @author hitrac */ @Entity public class PyschSupport implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String trainingPsg; private String projectdone; // support group or social network joined private String supnetjoined; // are you affiliated to znnnp+ private Boolean znnnpaffil = Boolean.FALSE; private Boolean socialmedia = Boolean.FALSE; private Boolean internetacces = Boolean.FALSE; private String mobileOs; private String specifysocial; private Demographic demographic; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Demographic getDemographic() { return demographic; } public void setDemographic(Demographic demographic) { this.demographic = demographic; } public String getTrainingPsg() { return trainingPsg; } public void setTrainingPsg(String trainingPsg) { this.trainingPsg = trainingPsg; } public String getProjectdone() { return projectdone; } public void setProjectdone(String projectdone) { this.projectdone = projectdone; } public String getSupnetjoined() { return supnetjoined; } public void setSupnetjoined(String supnetjoined) { this.supnetjoined = supnetjoined; } public Boolean getZnnnpaffil() { return znnnpaffil; } public void setZnnnpaffil(Boolean znnnpaffil) { this.znnnpaffil = znnnpaffil; } public Boolean getSocialmedia() { return socialmedia; } public void setSocialmedia(Boolean socialmedia) { this.socialmedia = socialmedia; } public Boolean getInternetacces() { return internetacces; } public void setInternetacces(Boolean internetacces) { this.internetacces = internetacces; } public String getMobileOs() { return mobileOs; } public void setMobileOs(String mobileOs) { this.mobileOs = mobileOs; } public String getSpecifysocial() { return specifysocial; } public void setSpecifysocial(String specifysocial) { this.specifysocial = specifysocial; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof PyschSupport)) { return false; } PyschSupport other = (PyschSupport) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "zw.co.hitrac.support.business.domain.Pysch.PyschSupport[ id=" + id + " ]"; } }
C
UTF-8
1,377
2.671875
3
[]
no_license
/** * @file kernel/spinlock.c */ #include <kernel/spinlock.h> #include <kernel/sched.h> #include <kernel/proc.h> #include <arch/atomic.h> #include <arch/irq.h> #include <assert.h> /* TODO memory barriers */ static inline void __lock(struct spinlock *s) { int my_ticket; // FIXME: spinlock rely on overflow to correctly work my_ticket = atomic_inc(&s->ticket); /* * Spin until the ticket being served equals my ticket. Hopefully * gcc doesn't optimize any of this out... */ while (my_ticket != s->serving) { panic("SMP is not supported... You should not be here!"); continue; } } static inline void __unlock(struct spinlock *s) { s->serving++; } void __spin_lock(struct spinlock *s) { __lock(s); } void __spin_unlock(struct spinlock *s) { __unlock(s); } void __spin_lock_irq(struct spinlock *s, unsigned long *flags) { disable_save_irqs(flags); __spin_lock(s); } void __spin_unlock_irq(struct spinlock *s, unsigned long flags) { __spin_unlock(s); restore_irqs(flags); } void spin_lock(struct spinlock *s) { disable_save_preemption(); __lock(s); } void spin_unlock(struct spinlock *s) { __unlock(s); restore_preemption(); } void spin_lock_irq(struct spinlock *s, unsigned long *flags) { disable_save_irqs(flags); spin_lock(s); } void spin_unlock_irq(struct spinlock *s, unsigned long flags) { spin_unlock(s); restore_irqs(flags); }
Python
UTF-8
6,027
3
3
[]
no_license
#!/usr/bin/env python3 import re def split_line(line): return re.sub('"|\n', '', line).split(",") def get_func_indexes(schema, func): return [[schema.index(x) for x in func[y]] for y in range(2)] def FuncDep(filepath, func): schema, data = load_relation(filepath) indexes = get_func_indexes(schema, func) if len(data) == 0: return True for i in range(len(data) - 1): for j in range(i, len(data)): eq = True for k in range(len(indexes[0])): if data[i][indexes[0][k]] != data[j][indexes[0][k]]: eq = False break if not eq: continue for k in range(len(indexes[1])): if data[i][indexes[1][k]] != data[j][indexes[1][k]]: return False return True def KanonickyRozklad(filepath): schema, data = load_relation(filepath) schema_size = len(schema) data_size = len(data) result = [] for i in range(data_size): for j in range(i, data_size): tmp = [] for k in range(schema_size): if data[i][k] == data[j][k]: tmp.append(schema[k]) result.append(tmp) result.sort(key=lambda x: (len(x), x.__str__())) for i in result: while result.count(i) > 1: result.pop(result.index(i)) return result def is_subset(m1, m2): for i in m1: if not m2.__contains__(i): return False return True def set_equal(m1, m2): if is_subset(m1, m2) & is_subset(m2, m1): return True return False def is_edge_subset(m1, m2): if is_subset(m1, m2) & (len(m1) < len(m2)): return True return False def join_sets(s1, s2): tmp = s2.copy() for i in s1: if not tmp.__contains__(i): tmp.append(i) return tmp def unique_list(l): l = l.copy() for i in l: while l.count(i) > 1: l.pop(l.index(i)) return l def closure(t, m): stable = False while not stable: stable = True for ab in t: if is_subset(ab[0], m): m = join_sets(m, ab[1]) stable = False t.pop(t.index(ab)) return m def closure_test(): t = [[["a"], ["a", "b"]], [["a"], ["c"]], [["a", "c"], ["b"]]] m = ["a"] print(closure(t, m)) def dep_test(): tests = [[["a", "b"], ["b", "c"]], [["b"], ["c"]], [["a", "c"], ["b", "c"]], [["c"], ["a", "b", "c"]]] for item in tests: print(FuncDep("/home/kamil/Dropbox/UPOL/6semestr/DATA2/data.csv", item)) def roz_test(): foo = KanonickyRozklad("/home/kamil/Dropbox/UPOL/6semestr/DATA2/data2.csv") bar = KanonickyRozklad("/home/kamil/Dropbox/UPOL/6semestr/DATA2/data3.csv") print("%s\n%s" % (foo, bar)) def tuple_match_attr(t1, t2, attr, schema): for i in attr: pos = schema.index(i) return t1[pos] == t2[pos] return True def load_relation(filepath): f = open(filepath, 'r') schema = split_line(f.readline()) data = list(map(split_line, f.readlines())) return (schema, data) def Ed(schema, data, M): result = [] for i in [(t1,t2) for t1 in data for t2 in data]: if tuple_match_attr(i[0], i[1], M, schema): result.append(i) return unique_list(result) def Cd(schema, data, M): result = [] for i in schema: if is_subset(Ed(schema, data, M), Ed(schema, data, [i])): result.append(i) return result def make_powerset(lst): result = [[]] for x in lst: result.extend([subset + [x] for subset in result]) return result def Pd(schema, data): result = [] pows = make_powerset(schema) for i in pows: if i == Cd(schema, data, i): continue if not result: result.append(i) for j in result: if not is_edge_subset(j, i): continue if is_subset(Cd(schema, data, j), i): result.append(i) return result def Ed_test(): path = "/home/kamil/Dropbox/UPOL/6semestr/DATA2/data.csv" schema, data = load_relation(path) resEd = Ed(schema, data, []) print(resEd) print(len(resEd)) def Cd_test(): path = "/home/kamil/Dropbox/UPOL/6semestr/DATA2/data.csv" schema, data = load_relation(path) resCd = Cd(schema, data, ["a", "b"]) print(resCd) def Pd_test(): path = "/home/kamil/Dropbox/UPOL/6semestr/DATA2/real_data.csv" schema, data = load_relation(path) resPd = Pd(schema, data) print("Pd result: ") print(resPd) def clos_infty(M,T): M_next = M M = None while M != M_next: M = M_next tmp = [] for ab in T: if is_edge_subset(ab[0], M) and ab in T: tmp.extend(ab[1]) M_next = join_sets(tmp, M) return M def clos(t): return lambda M: clos_infty(M, t) def next_closure(cl, M, schema): n = len(schema) for i in range(n-1, -1, -1): if schema[i] not in M: M_less = [M[j] for j in range(len(M)) if M[j] in schema[:i]] new = cl(join_sets([schema[i]], M_less)) new_less = [new[j] for j in range(len(new)) if new[j] in schema[:i]] if set_equal(new_less, M_less): return new return None def minimum_base(path): schema, data = load_relation(path) M=[] T=[] while not set_equal(M, schema): if not set_equal(M, Cd(schema, data, M)): T.append([M, Cd(schema, data, M)]) M = next_closure(clos(T), M, schema) return T def minimum_base_test(): path = "/home/kamil/Dropbox/UPOL/6semestr/DATA2/real_data.csv" print(minimum_base(path)) dep_test() roz_test() print("Closure test") closure_test() print("Ed test") Ed_test() Cd_test() Pd_test() print("Minimum base test") minimum_base_test()
Markdown
UTF-8
2,088
2.671875
3
[]
no_license
> rdkafka.h rdkafka_partition.h 1. topic_partition_list 操作 ``` // 表示一个topic+partition typedef struct rd_kafka_topic_partition_s { char *topic; /* Topic name */ int32_t partition; /* Partition */ int64_t offset; /* Offset */ void *metadata; /* Metadata */ size_t metadata_size; /* Metadata size */ void *opaque; /* Application opaque */ rd_kafka_resp_err_t err; /* Error code, depending on use. */ void *_private; /* INTERNAL USE ONLY, * INITIALIZE TO ZERO, DO NOT TOUCH */ } rd_kafka_topic_partition_t; // 存放的list,一般是操作这个结构 typedef struct rd_kafka_topic_partition_list_s { int cnt; /* Current number of elements */ int size; /* Current allocated size */ rd_kafka_topic_partition_t *elems; /* Element array[] */ } rd_kafka_topic_partition_list_t; ``` ``` //1. 新建,销毁list rd_kafka_topic_partition_list_t *rd_kafka_topic_partition_list_new (int size); void rd_kafka_topic_partition_list_destroy (rd_kafka_topic_partition_list_t *rkparlist); // 2. 添加元素 // 添加1个元素,返回的element可用于填写其他field rd_kafka_topic_partition_t * rd_kafka_topic_partition_list_add ( rd_kafka_topic_partition_list_t *rktparlist, const char *topic, int32_t partition); // 添加多个元素 void rd_kafka_topic_partition_list_add_range ( rd_kafka_topic_partition_list_t *rktparlist, const char *topic, int32_t start, int32_t stop); // 3. 删除元素 // 根据topic+partition删除 int rd_kafka_topic_partition_list_del ( rd_kafka_topic_partition_list_t *rktparlist, const char *topic, int32_t partition); // 根据index删除 int rd_kafka_topic_partition_list_del_by_idx ( rd_kafka_topic_partition_list_t *rktparlist, int idx); // 4. 查找元素 rd_kafka_topic_partition_t * rd_kafka_topic_partition_list_find ( rd_kafka_topic_partition_list_t *rktparlist, const char *topic, int32_t partition); ```
Python
UTF-8
1,199
2.921875
3
[]
no_license
from copy import copy, deepcopy def check_constraints(a): l1 = [a[0],a[1],a[2],a[3]] l2 = [a[3],a[4],a[5],a[6]] l3 = [a[6],a[7],a[8],a[0]] l4 = [a[9],a[1],a[8],a[11]] l5 = [a[9],a[2],a[4],a[10]] l6 = [a[10],a[5],a[7],a[11]] l = [l1,l2,l3,l4,l5,l6] for line in l: if(sum(line)!=26 and (0 not in line)): return False if( sum(line)>=26 and (0 in line) ): return False return True def find_next(b): a = b[:] index = 0; for val in a: if(val != 0): index+=1; print a print index if(index == 12): return -1,-1 for i in range(1,13): if(i not in a): a = b[:] a[index] = i if(check_constraints(a) == True): return index,i def solve(a): index = 0 for val in a: if(val != 0): index+=1 else: break print a,index if(0 not in a): if(check_constraints(a)): return a else: #print "false" return False for i in range(1,13): if(i not in a): print i b = a[:] b[index]=i; if(check_constraints(b) == True): retval = solve(b) if(retval != False ): return retval return False a = [0]*12 a = solve(a) print a
Java
UTF-8
5,558
1.914063
2
[ "Apache-2.0" ]
permissive
package com.redhat.demo.optaplanner; import java.io.IOException; import java.util.Properties; import com.redhat.demo.optaplanner.model.Cache; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.RemoteCounterManagerFactory; import org.infinispan.client.hotrod.annotation.ClientCacheEntryCreated; import org.infinispan.client.hotrod.annotation.ClientCacheEntryExpired; import org.infinispan.client.hotrod.annotation.ClientCacheEntryModified; import org.infinispan.client.hotrod.annotation.ClientCacheEntryRemoved; import org.infinispan.client.hotrod.annotation.ClientListener; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.event.ClientEvent; import org.infinispan.commons.configuration.XMLStringConfiguration; import org.infinispan.counter.api.CounterEvent; import org.infinispan.counter.api.CounterListener; import org.infinispan.counter.api.CounterManager; import org.infinispan.counter.api.CounterState; import org.infinispan.counter.api.StrongCounter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.PropertySource; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class HelloController { @Autowired private SimpMessagingTemplate template; @Value("${infinispan.host}") private String infinispanHost; @Value("${infinispan.hotrod.port}") private int hotrodPort; @Bean private ClientConfiguration clientConfiguration() { return new ClientConfiguration(infinispanHost, hotrodPort); } @GetMapping("/") public String hello(Model model) { return "hello"; } @MessageMapping("/cacheSubscribe") public void handleCacheSubscribtion(Cache cache) { ClientConfiguration configuration = clientConfiguration(); System.out.println(configuration.getInfinispanHost() + ":" + configuration.getHotRodPort()); System.out.println(cache.getCacheName()); RemoteCacheManager remoteCacheManager = new RemoteCacheManager(configuration.getConfigurationBuilder().build()); // RemoteCache<String, String> remoteCache = remoteCacheManager.administration().getOrCreateCache(cache.getCacheName(), // new XMLStringConfiguration(String.format( // "<infinispan>" + // "<cache-container>" + // "<distributed-cache name=\"%1$s\">" + // "<memory>" + // "<object size=\"10\"/>" + // "</memory>" + // "<persistence passivation=\"false\">" + // "<file-store " + // "shared=\"false\" " + // "fetch-state=\"true\" " + // "path=\"${jboss.server.data.dir}/datagrid-infinispan/%1$s\"" + // "/>" + // "</persistence>" + // "</distributed-cache>" + // "</cache-container>" + // "</infinispan>", cache.getCacheName()) // )); // remoteCache.addClientListener(new RemoteListener()); String counterName; Properties props = new Properties(); try { props.load(HelloController.class.getClassLoader().getResourceAsStream("application.properties")); counterName = props.getProperty("health.counter.name"); } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException("Could not load application.properties file"); } System.out.println("HelloController.handleCacheSubscribtion: " + counterName); CounterManager counterManager = RemoteCounterManagerFactory.asCounterManager(remoteCacheManager); StrongCounter strongCounter = counterManager.getStrongCounter(counterName); strongCounter.addListener(new RemoteListener(strongCounter)); } @ClientListener() private class RemoteListener implements CounterListener { private StrongCounter strongCounter; public RemoteListener(StrongCounter strongCounter) { this.strongCounter = strongCounter; } @ClientCacheEntryCreated @ClientCacheEntryModified @ClientCacheEntryExpired @ClientCacheEntryRemoved public void handleRemoteEvent(ClientEvent event) { System.out.println("RemoteListener.handleRemoteEvent: " + event); template.convertAndSend("/topic/damageEvents", event); } @Override public void onUpdate(CounterEvent entry) { System.out.println("RemoteListener.onUpdate: " + entry); if (entry.getNewState().equals(CounterState.LOWER_BOUND_REACHED)) { strongCounter.sync().reset(); } } } }
Java
UTF-8
1,099
2.765625
3
[]
no_license
public class MSD { private static int R = 256; // private static String[] aux; public static String[] sort(String[] a){ return sort(a,0,a.length,0); } private static String[] sort(String[] a,int start,int end,int pos){ int N = end - start; if(N==0)return null; String[] aux = new String[N]; int[] count = new int[R+2]; int[] count_r = new int[R+2]; for(int i=start;i<end;i++){ count[charAt(a[i],pos)+2]++; count_r[charAt(a[i],pos)+2]++; } for(int r=0;r<R;r++){ count[r+1]+=count[r]; //count_r[r]=count[r]; } //count_r[R]=count[R]; for(int i=start;i<end;i++){ aux[count[charAt(a[i],pos)+1]]=a[i]; count[charAt(a[i],pos)+1]++; } for(int i=start;i<end;i++){ a[i]=aux[i-start]; } for(int r=2;r<R+2;r++){ if(count_r[r]==0)continue; int l = count_r[r]; char ch = (char)r; System.out.println(ch+":"+l); sort(a,start,start+l,pos+1); start+=l; } return a; } public static int charAt(String s ,int index){ try{ return s.charAt(index); } catch (IndexOutOfBoundsException e){ return -1; } } }
Java
UTF-8
1,162
3.640625
4
[]
no_license
package Shildt.Collection.ThreadCol.TreadEx; class MyRun implements Runnable { Thread t; public MyRun() { t = new Thread(this); t.start(); } @Override public void run() { try { for (int i = 1; i <= 10; i++){ System.err.println(i); Thread.sleep(250);} } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+" "); } } public class Ex8 extends Thread { public Ex8() { new Thread(this).start(); } @Override public void run() { try { for (int i = 1; i <= 10; i++){ System.out.println(i); Thread.sleep(250);} } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " "); } public static void main(String[] args) throws InterruptedException { Ex8 ex8 = new Ex8(); MyRun myRun = new MyRun(); ex8.join(); myRun.t.join(); System.out.println("Конец"); } }
C++
UTF-8
1,948
2.640625
3
[ "MIT" ]
permissive
/* Copyright 1995-2008 ibp (uk) Ltd. created: Mon Nov 18 12:05:02 GMT+0100 1996 Author: Lars Immisch <[email protected]> */ #ifndef _INTERFACE_H_ #define _INTERFACE_H_ #include <list> #include <map> #include <sstream> #include "text.h" #include "configuration.h" class Sequencer; class InterfaceConnection : public SocketStream { public: InterfaceConnection(int protocol = PF_INET, int s = -1) : SocketStream(protocol, s) {} virtual ~InterfaceConnection() {} void add(const std::string &name, Sequencer *sequencer) { omni_mutex_lock l(m_mutex); m_calls[name] = sequencer; } void remove(const std::string &name) { omni_mutex_lock l(m_mutex); m_calls.erase(name); } Sequencer *find(const std::string &name) { omni_mutex_lock l(m_mutex); std::map<std::string,Sequencer*>::const_iterator i = m_calls.find(name); if (i == m_calls.end()) return 0; return i->second; } int send(std::stringstream &data); void lost_connection(); omni_mutex& getMutex() { return m_mutex; } typedef std::map<std::string,Sequencer*> t_calls; const t_calls& get_calls() { return m_calls; } protected: t_calls m_calls; omni_mutex m_mutex; }; class Interface { public: Interface(SAP& local); virtual ~Interface() {} virtual void run(); // return false if connection should be closed bool data(InterfaceConnection *server); protected: Socket m_listener; omni_mutex m_mutex; std::list<InterfaceConnection*> m_connections; }; // helper class // contains all information about an outgoing call initiated by the client class ConnectCompletion { public: ConnectCompletion(InterfaceConnection *iface, const std::string &id, const SAP &local, const SAP &remote, unsigned timeout) : m_interface(iface), m_id(id), m_local(local), m_remote(remote), m_timeout(timeout) {} ~ConnectCompletion() {} InterfaceConnection *m_interface; std::string m_id; SAP m_local; SAP m_remote; unsigned m_timeout; }; #endif
PHP
UTF-8
1,034
2.828125
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace BEAR\Resource; use BEAR\Resource\Exception\UriException; final class Uri extends AbstractUri { /** * @throws \BEAR\Resource\Exception\UriException */ public function __construct(string $uri, array $query = []) { $this->validate($uri); if (count($query) !== 0) { $uri = uri_template($uri, $query); } $parsedUrl = parse_url($uri); list($this->scheme, $this->host, $this->path) = array_values($parsedUrl); if (isset($parsedUrl['query'])) { parse_str($parsedUrl['query'], $this->query); } if (count($query) !== 0) { $this->query = $query + $this->query; } } /** * @throws UriException */ private function validate(string $uri) { if (! filter_var($uri, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED)) { $msg = is_string($uri) ? $uri : gettype($uri); throw new UriException($msg, 500); } } }