language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
C#
UTF-8
917
2.515625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace DayData.admin.core.controls { /// <summary> /// Summary description for File /// </summary> public class File : IHttpHandler { public void ProcessRequest(HttpContext context) { string filename = context.Request.QueryString["File"]; //Validate the file name and make sure it is one that the user may access context.Response.Buffer = true; context.Response.Clear(); context.Response.AddHeader("content-disposition", "attachment; filename=" + filename); context.Response.ContentType = "octet/stream"; context.Response.WriteFile("~/App_Data/" + filename); } public bool IsReusable { get { return false; } } } }
Java
UTF-8
2,248
2.0625
2
[]
no_license
package com.huamengtong.wms.main.mapper.service.impl; import com.huamengtong.wms.dto.TWmsCargoOwnerDTO; import com.huamengtong.wms.main.mapper.common.SpringTxTestCase; import com.huamengtong.wms.main.service.ICargoOwnerService; import org.apache.commons.lang3.StringUtils; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class CargoOwnerTest extends SpringTxTestCase { @Autowired ICargoOwnerService aOwnerService; @Test public void testCreateOwner(){ TWmsCargoOwnerDTO aTWmsCargoOwnerDTO = new TWmsCargoOwnerDTO(); aTWmsCargoOwnerDTO.setTypeCode("TypeCode"); aTWmsCargoOwnerDTO.setAddress("上海"); aTWmsCargoOwnerDTO.setTelephone("111111"); aTWmsCargoOwnerDTO.setCreateUser("master"); aTWmsCargoOwnerDTO.setArea("黄埔"); aTWmsCargoOwnerDTO.setCity("上海市"); aTWmsCargoOwnerDTO.setCountry("china"); aTWmsCargoOwnerDTO.setContact("Contact"); aTWmsCargoOwnerDTO.setEmail("aaa@email.com"); aTWmsCargoOwnerDTO.setCreateTime(1L); aTWmsCargoOwnerDTO.setZip("zip"); aTWmsCargoOwnerDTO.setFax("fax"); aTWmsCargoOwnerDTO.setIsActive((byte)1); aTWmsCargoOwnerDTO.setUpdateTime(2L); aTWmsCargoOwnerDTO.setProvince("shanghai"); aTWmsCargoOwnerDTO.setFullName("全名"); aTWmsCargoOwnerDTO.setShortName("简称"); aTWmsCargoOwnerDTO.setCargoOwnerNo("OwnerNo"); aOwnerService.createOwner(aTWmsCargoOwnerDTO); } @Test public void updatae(){ TWmsCargoOwnerDTO aTWmsCargoOwnerDTO = new TWmsCargoOwnerDTO(); aTWmsCargoOwnerDTO.setTypeCode("测试更新"); System.out.println(aOwnerService.updateOwner(aTWmsCargoOwnerDTO)); } @Test public void show(){ String str = "7766"; List<Long> ids = Arrays.stream(str.split(",")).filter(StringUtils::isNotBlank).map(Long::parseLong).collect(Collectors.toList()); System.out.println(ids.toString()); } }
PHP
UTF-8
467
2.90625
3
[]
no_license
<?php namespace Src\request\formvalidation\formRule; use FormRule; class RuleRequired extends FormRule{ private $data = ''; function __construct($data){ parent::__construct($data); $this->data = $data; } public function run($perameter = ''){ $value = preg_replace('/^[\pZ\pC]+|[\pZ\pC]+$/u', '', $this->data); if (empty($value) === false) { return true; } return false; } public function message(){ return '{field} is required.'; } }
Markdown
UTF-8
3,288
2.796875
3
[ "MIT" ]
permissive
--- title: "Ubuntu 13.04 Bandwidth Shaping and Traffic Control using HTB" tagline: "keepin' things fair" category: linux tags: [linux, ubuntu, qos] --- Problem ------- I don't want to allow a client on my network to consume all the available upload network bandwidth when doing something like online backups. Instead I want to have guarantees that each class of devices can consume a certain <code>rate</code>. After that certain amount they are welcome to share up to a defined <code>ceiling</code> with the other classes. Note that traffic shapping can only occur on the host that has control over the transmit queue. That is to say that my NAT router can only do QoS on outgoing traffic, not incoming traffic. The key to maintaining a responsive low-latecny connection when uploading large amounts of data is to keep the upload buffer under control with Linux instead of letting the cable modem or upstream router just blindly queue up all the packets. Solution -------- I threw together a quick hierarchical token bucket filter (htb or tc-htb for short) to solve this problem. It works by splitting traffic into 3 classes: my personal workstation that also doubles as the NAT router, Ethernet connected devices, and WiFi connected devices. Each class is guaranteed some bandwidth as described by the <code>rate</code> parameter and can borrow up to the <code>ceil</code> parameter. To actually classify the traffic so they fall in the right buckets, I use a simple iptables mangle rule. There are numerous guides around on the Internet describing how to set these up in a distribution independent way. I wanted to provide an example for others to correctly set up QoS in Ubuntu 13.04 (and likely old versions without any issues) so that it's automatically configured at start-up. My cable modem uplink is capped at 10 Mbit/s. I never want to exceed this rate as then that will move control queue to the cable modem instead of my NAT router. Implementation -------------- 1. Add the traffic control rules to the <code>/etc/network/interfaces</code> file: auto eth0 iface eth0 inet dhcp post-down tc qdisc del dev eth0 root post-up tc qdisc replace dev eth0 root handle 1: htb default 10 post-up tc class replace dev eth0 parent 1: classid 1:1 htb rate 10mbit # My workstation / server post-up tc class replace dev eth0 parent 1:1 classid 1:10 htb rate 5mbit ceil 8mbit prio 1 # LAN NAT routes post-up tc class replace dev eth0 parent 1:1 classid 1:20 htb rate 3mbit ceil 8mbit prio 2 # WLAN NAT routes post-up tc class replace dev eth0 parent 1:1 classid 1:30 htb rate 3mbit ceil 8mbit prio 2 2. If using ufw for firewall management, append the following to <code>/etc/ufw/before.rules</code>: *mangle :POSTROUTING ACCEPT [0:0] -A POSTROUTING -s 192.168.10.0/24 -o eth0 -j CLASSIFY --set-class 0001:0020 -A POSTROUTING -s 192.168.11.0/24 -o eth0 -j CLASSIFY --set-class 0001:0030 COMMIT 3. Reload the firewall and interface to apply the settings: $ sudo ufw reload $ sudo ifdown eth0 ; ifup eth0 4. Test it by uploading a huge file to a remote server somewhere while streaming a download somewhere else.
Python
UTF-8
1,501
3.03125
3
[]
no_license
import numpy as np import warnings from collections import Counter import pandas as pd import random def KNearestNeighbors(data,predict,k = 3): if len(data) >= k: warnings.warn('Hey you have choosen k value less then the length of the data dumbass') distances = [] for group in data: for features in data[group]: euclidean = np.linalg.norm(np.array(features)-np.array(predict)) distances.append([euclidean,group]) votes = [i[1] for i in sorted(distances)[:k]] global votes_count votes_count = Counter(votes).most_common(1)[0][0] #print(votes_count) return votes_count dataframe = pd.read_csv('cancer.csv') dataframe.replace('?',-99999,inplace = True) dataframe.drop(['id'],1,inplace = True) #print(dataframe.head()) #print(full_data[:10]) full_data = dataframe.astype(float).values.tolist() random.shuffle(full_data) # 2 is banign 4 is Malignant test_size = 0.2 train_set = {2:[],4:[]} test_set = {2:[],4:[]} train_data = full_data[:-int(test_size*len(full_data))] test_data = full_data[-int(test_size*len(full_data)):] for i in train_data: train_set[i[-1]].append(i[:-1]) for i in test_data: test_set[i[-1]].append(i[:-1]) correct = 0.0 total = 0.0 for group in test_set: for data in test_set[group]: vote = KNearestNeighbors(train_set,data,k = 5) if group == vote: correct +=1 total+=1 #print(correct) #print(total) Accuracy = correct/total print 'Accuracy: ', Accuracy pred = KNearestNeighbors(test_set,[5,1,1,1,2,1,3,1,1],k = 3) print(votes_count)
Java
UTF-8
3,624
2.109375
2
[]
no_license
package com.tqmall.legend.facade.discount.configuration.handler.init; import com.tqmall.common.exception.BizException; import com.tqmall.legend.biz.account.AccountInfoService; import com.tqmall.legend.biz.customer.CustomerService; import com.tqmall.legend.entity.account.AccountInfo; import com.tqmall.legend.entity.customer.Customer; import com.tqmall.legend.facade.discount.bo.AccountDiscountBo; import com.tqmall.legend.facade.discount.bo.DiscountContext; import com.tqmall.legend.facade.discount.configuration.handler.init.converter.AccountDiscountConverter; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import java.util.List; import static com.tqmall.wheel.lang.Langs.isNotBlank; import static com.tqmall.wheel.lang.Langs.isNotEmpty; import static com.tqmall.wheel.lang.Langs.isNotNull; /** * @Author 辉辉大侠 * @Date:2:05 PM 02/03/2017 */ @Slf4j public class GuestAccountInfoInitHandler extends AbstractAccountInfoInitHandler { @Autowired private CustomerService customerService; @Autowired private AccountInfoService accountInfoService; private Long customerId; @Override public void init(DiscountContext cxt) { this.initAccountInfo(cxt); initAccountCardsInfo(cxt.getShopId(), cxt.getGuestAccountDiscount()); initAccountComboInfo(cxt.getShopId(), cxt.getGuestAccountDiscount()); initAccountCouponInfo(cxt.getShopId(), cxt.getGuestAccountDiscount()); } private void initAccountInfo(DiscountContext cxt) { if (isNotBlank(cxt.getGuestMobile())) { checkMobile(cxt); List<Customer> customerList = customerService.getCustomerByMobile(cxt.getGuestMobile(), cxt.getShopId()); if (customerList.size() == 0) { log.error("根据手机号查不到他人车主信息,mobile:[{}]", cxt.getGuestMobile()); } else if (customerList.size() > 1) { log.error("根据手机号【{}】查找到{}个车主信息.", cxt.getGuestMobile(), customerList.size()); throw new BizException("根据手机号[" + cxt.getGuestMobile() + "]查找到" + customerList.size() + "个车主信息."); } else { customerId = customerList.get(0).getId(); AccountInfo accountInfo = this.accountInfoService.getAccountInfoByCustomerIdAndShopId(cxt.getShopId(), customerId); if (isNotNull(accountInfo)) { cxt.setGuestAccountDiscount(new AccountDiscountConverter().apply(accountInfo, new AccountDiscountBo())); } else { if (log.isErrorEnabled()) { log.error("根据客户id获取账户信息异常,customerId:{}", customerId); } throw new BizException("获取他人[" + cxt.getGuestMobile() + "]账户信息异常."); } } } } private void checkMobile(DiscountContext cxt) { if (isNotNull(cxt.getAccountDiscount())) { if (cxt.getGuestMobile().equals(cxt.getAccountDiscount().getCustomerMobile())) { throw new BizException("他人手机号为车辆账户下的手机号"); } } if (isNotEmpty(cxt.getBindAccountDiscountList())) { for (AccountDiscountBo account : cxt.getBindAccountDiscountList()) { if (cxt.getGuestMobile().equals(account.getCustomerMobile())) { throw new BizException("他人手机号为车辆绑定账户下的手机号"); } } } } }
Java
UTF-8
1,691
2.421875
2
[]
no_license
package com.courses.service.impl; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.courses.dao.CoursesDao; import com.courses.model.Course; import com.courses.service.CoursesService; @Service public class CoursesServiceImpl implements CoursesService { @Autowired CoursesDao coursesDao; @Transactional public List<Course> getCourses() { List<Course> courses = coursesDao.getCoursesDao(); return courses; } @Transactional public void saveCourses() { Course course = new Course(); course.setTitle("Java"); course.setType("programming"); course.setDescription("Course About Java"); Course course2 = new Course(); course2.setTitle("JavaScript"); course2.setType("programming"); course2.setDescription("Course About JavaScript"); Course course3 = new Course(); course3.setTitle("Python"); course3.setType("programming"); course3.setDescription("Course About Python"); Course course4 = new Course(); course4.setTitle("Design"); course4.setType("design"); course4.setDescription("Course About Design"); Course course5 = new Course(); course5.setTitle("Photoshop"); course5.setType("photo"); course5.setDescription("Course About Photoshop"); List<Course> courses = new ArrayList<Course>(); courses.add(course); courses.add(course2); courses.add(course3); courses.add(course4); courses.add(course5); coursesDao.saveCourses(courses); } @Transactional public void addCourse(Course course) { coursesDao.addCourseDB(course); } }
Java
UTF-8
12,968
2.578125
3
[]
no_license
package com.limegroup.gnutella.metadata; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.io.UnsupportedEncodingException; import java.util.Iterator; import java.util.Vector; import com.limegroup.gnutella.ByteOrder; import de.vdheide.mp3.ID3v2; import de.vdheide.mp3.ID3v2Exception; import de.vdheide.mp3.ID3v2Frame; import de.vdheide.mp3.NoID3v2TagException; /** * Provides a utility method to read ID3 Tag information from MP3 * files and creates XMLDocuments from them. * * @author Sumeet Thadani */ public class MP3MetaData extends AudioMetaData { public MP3MetaData(File f) throws IOException { super(f); } /** * Returns ID3Data for the file. * * LimeWire would prefer to use ID3V2 tags, so we try to parse the ID3V2 * tags first, and then v1 to get any missing tags. */ protected void parseFile(File file) throws IOException { parseID3v2Data(file); MP3Info mp3Info = new MP3Info(file.getCanonicalPath()); setBitrate(mp3Info.getBitRate()); setLength((int)mp3Info.getLengthInSeconds()); parseID3v1Data(file); } /** * Parses the file's id3 data. */ private void parseID3v1Data(File file) { // not long enough for id3v1 tag? if(file.length() < 128) return; RandomAccessFile randomAccessFile = null; try { randomAccessFile = new RandomAccessFile(file, "r"); long length = randomAccessFile.length(); randomAccessFile.seek(length - 128); byte[] buffer = new byte[30]; // If tag is wrong, no id3v1 data. randomAccessFile.readFully(buffer, 0, 3); String tag = new String(buffer, 0, 3); if(!tag.equals("TAG")) return; // We have an ID3 Tag, now get the parts randomAccessFile.readFully(buffer, 0, 30); if (getTitle() == null || getTitle().equals("")) setTitle(getString(buffer, 30)); randomAccessFile.readFully(buffer, 0, 30); if (getArtist() == null || getArtist().equals("")) setArtist(getString(buffer, 30)); randomAccessFile.readFully(buffer, 0, 30); if (getAlbum() == null || getAlbum().equals("")) setAlbum(getString(buffer, 30)); randomAccessFile.readFully(buffer, 0, 4); if (getYear() == null || getYear().equals("")) setYear(getString(buffer, 4)); randomAccessFile.readFully(buffer, 0, 30); int commentLength; if (getTrack()==0 || getTrack()==-1){ if(buffer[28] == 0) { setTrack((short)ByteOrder.ubyte2int(buffer[29])); commentLength = 28; } else { setTrack((short)0); commentLength = 3; } if (getComment()==null || getComment().equals("")) setComment(getString(buffer, commentLength)); } // Genre randomAccessFile.readFully(buffer, 0, 1); if (getGenre() ==null || getGenre().equals("")) setGenre( MP3MetaData.getGenreString((short)ByteOrder.ubyte2int(buffer[0]))); } catch(IOException ignored) { } finally { if( randomAccessFile != null ) try { randomAccessFile.close(); } catch(IOException ignored) {} } } /** * Helper method to generate a string from an id3v1 filled buffer. */ private String getString(byte[] buffer, int length) { try { return new String(buffer, 0, getTrimmedLength(buffer, length), ISO_LATIN_1); } catch (UnsupportedEncodingException err) { // should never happen return null; } } /** * Generates ID3Data from id3v2 data in the file. */ private void parseID3v2Data(File file) { ID3v2 id3v2Parser = null; try { id3v2Parser = new ID3v2(file); } catch (ID3v2Exception idvx) { //can't go on return ; } catch (IOException iox) { return ; } Vector frames = null; try { frames = id3v2Parser.getFrames(); } catch (NoID3v2TagException ntx) { return ; } //rather than getting each frame indvidually, we can get all the frames //and iterate, leaving the ones we are not concerned with for(Iterator iter=frames.iterator() ; iter.hasNext() ; ) { ID3v2Frame frame = (ID3v2Frame)iter.next(); String frameID = frame.getID(); byte[] contentBytes = frame.getContent(); String frameContent = null; if (contentBytes.length > 0) { try { String enc = (frame.isISOLatin1()) ? ISO_LATIN_1 : UNICODE; frameContent = new String(contentBytes, enc).trim(); } catch (UnsupportedEncodingException err) { // should never happen } } if(frameContent == null || frameContent.trim().equals("")) continue; //check which tag we are looking at if(MP3DataEditor.TITLE_ID.equals(frameID)) setTitle(frameContent); else if(MP3DataEditor.ARTIST_ID.equals(frameID)) setArtist(frameContent); else if(MP3DataEditor.ALBUM_ID.equals(frameID)) setAlbum(frameContent); else if(MP3DataEditor.YEAR_ID.equals(frameID)) setYear(frameContent); else if(MP3DataEditor.COMMENT_ID.equals(frameID)) { //ID3v2 comments field has null separators embedded to encode //language etc, the real content begins after the last null byte[] bytes = frame.getContent(); int startIndex = 0; for(int i=bytes.length-1; i>= 0; i--) { if(bytes[i] != (byte)0) continue; //OK we are the the last 0 startIndex = i; break; } frameContent = new String(bytes, startIndex, bytes.length-startIndex).trim(); setComment(frameContent); } else if(MP3DataEditor.TRACK_ID.equals(frameID)) { try { setTrack(Short.parseShort(frameContent)); } catch (NumberFormatException ignored) {} } else if(MP3DataEditor.GENRE_ID.equals(frameID)) { //ID3v2 frame for genre has the byte used in ID3v1 encoded //within it -- we need to parse that out int startIndex = frameContent.indexOf("("); int endIndex = frameContent.indexOf(")"); int genreCode = -1; //Note: It's possible that the user entered her own genre in //which case there could be spurious braces, the id3v2 braces //enclose values between 0 - 127 // Custom genres are just plain text and default genres (known // from id3v1) are referenced with values enclosed by braces and // with optional refinements which I didn't implement here. // http://www.id3.org/id3v2.3.0.html#TCON if(startIndex > -1 && endIndex > -1 && startIndex < frameContent.length()) { //we have braces check if it's valid String genreByte = frameContent.substring(startIndex+1, endIndex); try { genreCode = Integer.parseInt(genreByte); } catch (NumberFormatException nfx) { genreCode = -1; } } if(genreCode >= 0 && genreCode <= 127) setGenre(MP3MetaData.getGenreString((short)genreCode)); else setGenre(frameContent); } else if (MP3DataEditor.LICENSE_ID.equals(frameID)) { setLicense(frameContent); } } } /** * Takes a short and returns the corresponding genre string */ public static String getGenreString(short genre) { switch(genre) { case 0: return "Blues"; case 1: return "Classic Rock"; case 2: return "Country"; case 3: return "Dance"; case 4: return "Disco"; case 5: return "Funk"; case 6: return "Grunge"; case 7: return "Hip-Hop"; case 8: return "Jazz"; case 9: return "Metal"; case 10: return "New Age"; case 11: return "Oldies"; case 12: return "Other"; case 13: return "Pop"; case 14: return "R &amp; B"; case 15: return "Rap"; case 16: return "Reggae"; case 17: return "Rock"; case 18: return "Techno"; case 19: return "Industrial"; case 20: return "Alternative"; case 21: return "Ska"; case 22: return "Death Metal"; case 23: return "Pranks"; case 24: return "Soundtrack"; case 25: return "Euro-Techno"; case 26: return "Ambient"; case 27: return "Trip-Hop"; case 28: return "Vocal"; case 29: return "Jazz+Funk"; case 30: return "Fusion"; case 31: return "Trance"; case 32: return "Classical"; case 33: return "Instrumental"; case 34: return "Acid"; case 35: return "House"; case 36: return "Game"; case 37: return "Sound Clip"; case 38: return "Gospel"; case 39: return "Noise"; case 40: return "AlternRock"; case 41: return "Bass"; case 42: return "Soul"; case 43: return "Punk"; case 44: return "Space"; case 45: return "Meditative"; case 46: return "Instrumental Pop"; case 47: return "Instrumental Rock"; case 48: return "Ethnic"; case 49: return "Gothic"; case 50: return "Darkwave"; case 51: return "Techno-Industrial"; case 52: return "Electronic"; case 53: return "Pop-Folk"; case 54: return "Eurodance"; case 55: return "Dream"; case 56: return "Southern Rock"; case 57: return "Comedy"; case 58: return "Cult"; case 59: return "Gangsta"; case 60: return "Top 40"; case 61: return "Christian Rap"; case 62: return "Pop+Funk"; case 63: return "Jungle"; case 64: return "Native American"; case 65: return "Cabaret"; case 66: return "New Wave"; case 67: return "Psychadelic"; case 68: return "Rave"; case 69: return "Showtunes"; case 70: return "Trailer"; case 71: return "Lo-Fi"; case 72: return "Tribal"; case 73: return "Acid Punk"; case 74: return "Acid Jazz"; case 75: return "Polka"; case 76: return "Retro"; case 77: return "Musical"; case 78: return "Rock &amp; Roll"; case 79: return "Hard Rock"; case 80: return "Folk"; case 81: return "Folk-Rock"; case 82: return "National Folk"; case 83: return "Swing"; case 84: return "Fast Fusion"; case 85: return "Bebob"; case 86: return "Latin"; case 87: return "Revival"; case 88: return "Celtic"; case 89: return "Bluegrass"; case 90: return "Avantgarde"; case 91: return "Gothic Rock"; case 92: return "Progressive Rock"; case 93: return "Psychedelic Rock"; case 94: return "Symphonic Rock"; case 95: return "Slow Rock"; case 96: return "Big Band"; case 97: return "Chorus"; case 98: return "Easy Listening"; case 99: return "Acoustic"; case 100: return "Humour"; case 101: return "Speech"; case 102: return "Chanson"; case 103: return "Opera"; case 104: return "Chamber Music"; case 105: return "Sonata"; case 106: return "Symphony"; case 107: return "Booty Bass"; case 108: return "Primus"; case 109: return "Porn Groove"; case 110: return "Satire"; case 111: return "Slow Jam"; case 112: return "Club"; case 113: return "Tango"; case 114: return "Samba"; case 115: return "Folklore"; case 116: return "Ballad"; case 117: return "Power Ballad"; case 118: return "Rhythmic Soul"; case 119: return "Freestyle"; case 120: return "Duet"; case 121: return "Punk Rock"; case 122: return "Drum Solo"; case 123: return "A capella"; case 124: return "Euro-House"; case 125: return "Dance Hall"; default: return ""; } } }
Shell
UTF-8
1,562
4.28125
4
[ "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
#! /bin/bash function split() { if [ -n "$4" ]; then if [[ $4 == *","* ]]; then inner_counter=1 for i in ${4//,/ } do pdftk "$1" cat "$i" output "$2"/$(printf "%02d" $counter)_"$3$inner_counter.pdf" ((inner_counter+=1)) ((counter+=1)) done else pdftk "$1" cat "$4" output "$2"/$(printf "%02d" $counter)_"$3.pdf" ((counter+=1)) fi echo "$3 $4" >> "$2/.log" fi } help() { cat << EOF help: $0 options Split text book pdfs into sections. All options except file take lists that are comma seaparated. Examples: 1-2,3-4 (range) or 1,2-4,5 (single and range) or 1 (single) Requires pdftk OPTIONS: -h You know what this is obviously -f source file (a pdf) -t table of contents -c chapters -a appendices -i indices -g glossary EOF } while getopts “hf:t:c:a:i:g:o:” OPTION do case $OPTION in h) help exit 1 ;; f) src=$OPTARG ;; t) toc=$OPTARG ;; c) chapters=$OPTARG ;; a) appendices=$OPTARG ;; i) indices=$OPTARG ;; g) glossary=$OPTARG ;; *) break ;; esac done if [ ! -e "$src" ]; then echo "\"$src\" does not exist" exit 1 fi folder=$(basename "$src") folder=${src%\.pdf} mkdir "$folder" counter=0 split "$src" "$folder" "table_of_contents" "$toc" split "$src" "$folder" "chapter" "$chapters" split "$src" "$folder" "appendix" "$appendices" split "$src" "$folder" "index" "$indices" split "$src" "$folder" "glossary" "$glossary" # copy original cp "$src" "$folder/.original"
PHP
UTF-8
2,615
2.515625
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use App\Http\Requests\ResetPasswordRequest; use App\User; use Exception; use Illuminate\Auth\Events\PasswordReset; use Illuminate\Contracts\Auth\PasswordBroker; use Illuminate\Contracts\Auth\StatefulGuard; use Illuminate\Http\JsonResponse; use Illuminate\Http\RedirectResponse; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Password; use Illuminate\Support\Str; class ResetPasswordController extends Controller { /** * Reset the given user's password. * * @param ResetPasswordRequest $request * @return RedirectResponse|JsonResponse * @throws Exception */ public function reset(ResetPasswordRequest $request) { $response = $this->broker()->reset( $request->only([ 'email', 'password', 'token' ]), function ($user, $password) { $this->resetPassword($user, $password); } ); return $response == Password::PASSWORD_RESET ? $this->sendResetResponse($response) : $this->sendResetFailedResponse($response); } /** * Reset the given user's password. * * @param User $user * @param string $password * @return void */ protected function resetPassword(User $user, $password) { $user->password = $password; $user->setRememberToken(Str::random(60)); $user->save(); event(new PasswordReset($user)); } /** * Get the response for a successful password reset. * * @param string $response * @return RedirectResponse|JsonResponse */ protected function sendResetResponse($response) { return response()->json([ 'status' => trans($response), ]); } /** * Get the response for a failed password reset. * * @param string $response * @return RedirectResponse|JsonResponse * @throws Exception */ protected function sendResetFailedResponse($response) { return response()->json([ 'message' => trans($response), ])->setStatusCode(422); } /** * Get the broker to be used during password reset. * * @return PasswordBroker */ public function broker() { return Password::broker(); } /** * Get the guard to be used during password reset. * * @return StatefulGuard */ protected function guard() { return Auth::guard(); } }
Shell
UTF-8
1,468
3.171875
3
[]
no_license
#!/bin/bash OHDirectory="/cygdrive/e/temp/ONCOhabitats_GBM_analysis_modified_pipeline" OHANTsDirectory="/cygdrive/f/OneDrive/work/OUS/distortion_correction/ONCOhabitats_scripts/ANTs" inputFilePath="native/Segmentation.nii.gz" referencePath="native/Flair.nii.gz" transformations="transforms/transform_Flair_to_T1c_0GenericAffine.mat" outputFilePath="native/Segmentation_Flair_space.nii.gz" readarray results_dirs < <(ls -d $OHDirectory/*/results) #echo ${results_dirs[@]} applyInverseRegistrationDiscrete () { OHANTsDirectory=$1 results_dir=$2 inputFilePath=$3 referencePath=$4 transformations=$5 outputFilePath=$6 cd $results_dir #echo $(pwd) # Apply transform command_transform="$OHANTsDirectory/antsApplyTransforms.exe --dimensionality 3 --input $inputFilePath --reference-image $referencePath --output $outputFilePath --interpolation MultiLabel[0.3,0] --transform [$transformations, 1] --verbose 0" echo $command_transform eval $command_transform # Convert to uint8 command_convert="$OHANTsDirectory/ConvertImage.exe 3 $outputFilePath $outputFilePath 1" echo $command_convert eval $command_convert } #printf "%s\n" "${results_dirs[@]}" | xargs -I dir -n 1 -P $(nproc) bash -c 'echo $1' _ dir export -f applyInverseRegistrationDiscrete printf "%s\n" "${results_dirs[@]}" | xargs -I results_dir -n 1 -P $(nproc) bash -c 'applyInverseRegistrationDiscrete "$@"' _ $OHANTsDirectory results_dir $inputFilePath $referencePath $transformations $outputFilePath
Java
UTF-8
394
1.6875
2
[]
no_license
package com.zimokaka.uc.uac.role.repository; import com.zimokaka.uc.uac.role.po.UcRole; import org.springframework.data.repository.PagingAndSortingRepository; /** * Created by Nicky on 2017/7/30. */ public interface UcRolePageRepository extends PagingAndSortingRepository<UcRole, Integer> { // @Query("from Role r where r.roleId=:id") // Role findByRoleId(@Param("id") int id); }
Markdown
UTF-8
734
2.53125
3
[]
no_license
--- title: 'Ce que disent les grands' date: '2016-09-05' lang: fr type: post categories: - papa --- Ce soir, le grand a débarassé la table à la demande de sa mère, en ne se trompant pas. Il a d'abord empilé les couverts, puis les assiettes en mettant l'assiette remplie de couverts sur le dessus, comme cela se fait. Nous étions bouche bée. <!-- more --> > — C'est très bien chéri, tu peux être fier de toi. > — Mais j'ai fait ce que Papa et Maman ont dit. > — C'est encore mieux ! C'est bien, mon fils, tu iras loin ! <figure> <img src="{{ page.url }}wtf.gif" alt="Gary Coleman n'est pas sûr d'avoir compris."/> <figcaption>Là, j'ai vu le doute sur son visage.</figcaption> </figure> > Loin où, Papa ?
Java
UTF-8
487
2.046875
2
[]
no_license
package com.in28minutes.springboot.rest.example.gamestore.repository; import java.util.List; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.in28minutes.springboot.rest.example.gamestore.entity.Bank; @Repository public interface BankRepository extends JpaRepository<Bank, Integer> { Optional<Bank> findByBankName(String bankName); List<Bank> findAllByStatus(Boolean status); }
Python
UTF-8
725
3.359375
3
[]
no_license
# Uses python3 def edit_distance(word1, word2): word1 = '-' + word1 word2 = '-' + word2 n1 = len(word1) n2 = len(word2) d = [[0 for _ in range(n2)] for _ in range(n1)] for i in range(n1): d[i][0] = i for i in range(n2): d[0][i] = i for x in range(1, n1): for y in range(1, n2): if word1[x] == word2[y]: match_mismatch = d[x-1][y-1] else: match_mismatch = d[x-1][y-1] + 1 insertion = d[x - 1][y] + 1 deletion = d[x][y - 1] + 1 d[x][y] = min(insertion, deletion, match_mismatch) return d[-1][-1] if __name__ == "__main__": print(edit_distance(input(), input()))
Markdown
UTF-8
4,440
2.796875
3
[ "MIT" ]
permissive
# Command-line executables | file suffix | details | notes | |--------------------|-------------------------------------------------------------------------------------------|----------------| | [linux-amd64].elf | ELF 64-bit LSB executable: x86-64: version 1 (SYSV): statically linked: not stripped | | [linux-386].elf | ELF 32-bit LSB executable: Intel 80386: version 1 (SYSV): statically linked: not stripped | | [linux-arm64].elf | ELF 64-bit LSB executable: ARM aarch64: version 1 (SYSV): statically linked: not stripped | Cortex A | | [linux-arm-V5].elf | ELF 32-bit LSB executable: ARM: EABI5 version 1 (SYSV): statically linked: not stripped | no HW F-P | | [linux-arm-V6].elf | ELF 32-bit LSB executable: ARM: EABI5 version 1 (SYSV): statically linked: not stripped | | | [linux-arm-V7].elf | ELF 32-bit LSB executable: ARM: EABI5 version 1 (SYSV): statically linked: not stripped | | | [windows-amd64].exe | PE32+ executable (console) x86-64 (stripped to external PDB): for MS Windows | | | [windows-386].exe | PE32 executable (console) Intel 80386 (stripped to external PDB): for MS Windows | | | [darwin-amd64] | Mach-O 64-bit x86_64 executable | | | [darwin-386] | Mach-O i386 executable | | # Usage ``` Usage of ./hashing[linux-amd64].elf: -bits uint Number of leading bits being searched for. (default 1) -end duration search time limit. -h display help/usage. -hash string hash type. one of |SHA384|SHA512|SHA512_256|MD5|SHA256|SHA224|SHA512_224|MD4|SHA1| (default "SHA1") -help display help/usage. -i value input source bytes.(default:<Stdin>) -input value input source bytes.(default:<Stdin>) -interval duration time between log status reports. (default 1s) -log value progress log destination.(default:Stderr) -max Search for maximum number of matching bits. (until ctrl-c or end time). -o value output file, written with input file + nonce appended.(default:Stdout just written with nonce.) -output value output file, written with input file + nonce appended.(default:Stdout just written with nonce.) -q no progress logging. -quiet no progress logging. -set Leading bits set. -start uint Hash index to start search from.(default:#0) -stop uint Hash index to stop search at.(default:#0 = unlimited) ``` # Examples * append to 'test.bin' to make it have an MD5 starting with 24 zero bits. ``` hasher -bits=24 -hash=MD5 < test.bin >> test.bin ``` * with 'hasher.go', search for 24 leading zero bits in the SHA512 hash, output to 'out' file, give up after 2 minutes. ``` hasher -bits=24 -i hasher.go -o out -hash=SHA512 -end=2m ``` * 32bits leading zeros for a folder of files combined. then confirm the result. ``` cat * | hasher -bits=32 -hash=SHA512 -end=24h > nonce cat !(nonce) nonce | sha512sum # cat command here pipes files deterministically but with the nonce file last, as needed to get the right hash. ``` * the log produced from creating the file 'nonce32' in this folder (32 leading zero bits nonce for all exe's in this directory) using 2 threads and then checking it. ``` $ cat h* | ./hashing\[linux-amd64\].elf -bits=32 -interval=1m -hash=SHA512 -end=20h > nonce32 2019/05/13 18:55:30 Loading:"/dev/stdin" 2019/05/13 18:55:30 Starting thread @ #0 2019/05/13 18:55:30 Starting thread @ #1 2019/05/13 18:56:30 #83292160 @1m0s 1388203#/s Mean Match:51m32s 2019/05/13 18:57:30 #167384064 @2m0s 1401246#/s Mean Match:51m2s 2019/05/13 18:58:30 #253056000 @3m0s 1427866#/s Mean Match:50m6s 2019/05/13 18:59:30 #326335744 @4m0s 1221022#/s Mean Match:58m33s ... 2019/05/13 19:20:30 #2052461568 @25m0s 1458773#/s Mean Match:49m2s 2019/05/13 19:21:30 #2139917312 @26m0s 1457596#/s Mean Match:49m6s 2019/05/13 19:22:30 #2226361856 @27m0s 1440742#/s Mean Match:49m40s 2019/05/13 19:22:33 #2810513407 @1622.9s Match(32 bits):"/dev/stdin"+[FE 06 84 a6] Saving:"/dev/stdout" Hash(SHA512):[00 00 00 00 60 3c e1 3c 85 7f 30 83 8a 21 27 2d 01 39 9f 6c 5c f5 ca fa 67 1a a5 a9 ff 69 70 5b 0c 16 92 d0 57 15 c0 c8 18 a0 22 71 0a 8a 6d 95 d1 1e e2 6e 12 73 a5 b0 e6 95 8a 16 3b de 65 e5] $ cat h* nonce32 | sha512sum 00000000603ce13c857f30838a21272d01399f6c5cf5cafa671aa5a9ff69705b0c1692d05715c0c818a022710a8a6d95d11ee26e1273a5b0e6958a163bde65e5 - $ cat h* nonce32 | sha512sum | tr " " "\n" | head -n 1 | [[ `xargs echo $1` == 000000000* ]] $ echo $? 0 ```
Python
UTF-8
403
2.5625
3
[ "MIT" ]
permissive
#calss header class _DOCK(): def __init__(self,): self.name = "DOCK" self.definitions = [u'to remove part of something: ', u'If a ship docks, it arrives at a dock and if someone docks a ship, they bring it into a dock: '] self.parents = [] self.childen = [] self.properties = [] self.jsondata = {} self.specie = 'verbs' def run(self, obj1 = [], obj2 = []): return self.jsondata
Markdown
UTF-8
5,474
3.21875
3
[ "MIT" ]
permissive
--- title: "Key to Unlocking Creativity: Sleep" date: "2018-05-07" tags: ["Cognitive science", "Sleep", "Psychology"] --- #### What you should know about sleep to boost your creativity A couple of weeks ago Luova Aalto organized an event about the interplay of sleep and creativity, lead by the wonderful Anu-Katriina Pesonen, a professor of clinical and developmental psychology from the University of Helsinki. Here are the key takeaways of that highly informative workshop. ### First: What is Creativity? _“Come up with different usages for a brick”_ Everyone has some kind of an idea what creativity means, but how about the science of creativity? Psychologists have actually been studying creativity for a long time (although the interest in it has died a little in the recent years), and have for example drawn a separation between different types of thinking. First, we have **_convergent thinking_**, meaning the ability to give a “correct answer” to a question, like for example in tests! But creativity is defined by a completely different type of thinking, which scientists call **_divergent thinking_**. Divergent thinking is measurable too, by using tests that don’t have a single answer. In the workshop this was demonstrated by thinking of uses cases for a brick, e.g. using it as a hammer, breaking it and using it as paint, etc. Now in order to measure your creativity, you could just count the different use cases for a brick, that you came up with. That, however, tells you rather little. Instead, your best bet would be to use **[Torrence's test of creativity**](https://en.wikipedia.org/wiki/Torrance_Tests_of_Creative_Thinking), which measures four things: **fluency**, the total number of solutions generated; **flexibility**, number different categories of solutions; **originality**, the statistical rarity of the solutions; **elaboration**, amount of detail in solutions. As might you have already thought, measuring creativity is a bit of a wild goose chase because the subject is so fuzzy, and the mentioned measuring method is just one many. More important is to understand the process of studying creativity, for it helps to understand how something is considered to correlate with creativity. ### Things to Know About Sleep Then how about sleep? Turns out, maybe not so surprisingly, that it too has been extensively studied in psychology and a variety of other different fields. However, sleep is just one part of a larger subject called **_circadian rhythm,_** and [last year three scientists won Nobel prize for researching it](https://www.nobelprize.org/nobel_prizes/medicine/laureates/2017/press.html). Circadian rhythm is maybe one of the single most important factor to our health and wellbeing, affecting everything [from our cognition](http://www.cambridgecognition.com/blog/entry/how-your-body-clock-may-affect-cognition) to [how well we burn fat](https://www.sciencedaily.com/releases/2017/07/170718091542.htm). So in order to understand sleep you have to understand circadian rhythm and the circadian clock. Circadian rhythm is the inner clock of your body, adjusting your biological functions in accordance with solar time, meaning the in runs the same time as our 24-hour clock. A good example of how circadian rhythm adjusts your biology is, for example, the feeling of tiredness. If our circadian clock is running on time, our bodies should start releasing melatonin, a sleep hormone, an hour before we head to bed. However, if we have for example wake up earlier than we usually do for a period of days while still going to bed at the same time, our circadian clock will adjust the release the melatonin. This will, in turn, increase the chance of us going to bed earlier, and getting the amount of sleep our bodies require. ### Enough Sleep = Starting Point for Creative Thinking Now at this point you‘re’ thinking: cool know I know a lot more about sleep and also understand how creativity is measured, but how does that help me maximize my creativity? The thing is, sleep is so tightly connected to the development and upkeep of our brains, and that way also to creativity, that the answer becomes relatively simple: _get enough sleep and get it regularly_. Of course, easier said than done. But we can start with little things. As mentioned, the circadian rhythm is always adjusting itself according to what we do and what happens us to during the day. Therefore, small changes in our daily life can help adjust our circadian rhythm. For example, reducing the disparity in when you go to sleep during the weekends and when you go sleep during weekdays, called **_social jetlag_**, can help us fall asleep in the days following. Scheduling exercises more towards day time and eating lighter meals in the evening helps your body to start preparations for sleeping on time. And for morning sleepiness, getting rid of the snooze button and a cup of coffee might actually help your body to understand the time of the day when it should start feeling energized. ### Further Reading Interested in learning more about sleep? First, to help you better understand your circadian rhythm, Anu is currently developing a new service for that set to launch in early 2019. [More about that here](https://www.nyxo.fi/). Second, you might find a book by Matthew Walked, called _Why We Sleep: Unlocking the Power of Sleep and Dreams_ interesting. It covers the things mentioned here about sleep and more and is really easy to read.
C++
UTF-8
6,491
3.21875
3
[ "LicenseRef-scancode-nysl-0.9982", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
#pragma once //---------------------------------------------------------------------------// // // optional.hpp // 「値を持たないかもしれない」状態を表現するオブジェクト (in C++14) // Copyright (C) 2015-2016 tapetums // 2015.11.03 created by tapetums // //---------------------------------------------------------------------------// #include <cassert> #include <utility> //---------------------------------------------------------------------------// namespace tapetums { //---------------------------------------------------------------------------// // nullopt_t //---------------------------------------------------------------------------// struct nullopt_t { constexpr explicit nullopt_t(int) noexcept { } }; //---------------------------------------------------------------------------// constexpr nullopt_t nullopt { 0 }; //---------------------------------------------------------------------------// // optional //---------------------------------------------------------------------------// template<typename T> class optional { static_assert( !std::is_same<typename std::decay<T>::type, nullopt_t>::value, "bad T" ); private: bool engaged_; T value_; public: constexpr optional() noexcept : engaged_{ false }, value_{ } { } constexpr optional(const optional&) = default; constexpr optional(optional&&) noexcept = default; ~optional() = default; constexpr explicit optional(const T& v) : engaged_{ true }, value_{ v } { } constexpr explicit optional(T&& v) noexcept : engaged_{ true }, value_{ std::move(v) } { } constexpr explicit optional(nullopt_t) noexcept : optional() { } optional& operator =(const T& lhs) { if ( lhs.initialized() ) { value_ = lhs.value_; engaged_ = true; } else { engaged_ = false; } return *this; } optional& operator =(T&& rhs) noexcept { if ( rhs.initialized() ) { value_ = std::move(value); engaged_ = true; } else { engaged_ = false; } return *this; } optional& operator =(nullopt_t) noexcept { clear(); return *this; } public: constexpr void clear() noexcept { if ( initialized() ) { engaged_ = false; } } public: constexpr bool initialized() const noexcept { return engaged_; } constexpr explicit operator bool() const noexcept { return engaged_; } constexpr T const* operator ->() const { assert(initialized()); return std::addressof(value_); } constexpr T* operator ->() { assert(initialized()); return std::addressof(value_); } constexpr T const& operator *() const { assert(initialized()); return value_; } constexpr T& operator *() { assert(initialized()); return value_; } public: constexpr T const& value() const { assert(initialized()); return value_; } constexpr T& value() { assert(initialized()); return value_; } }; //---------------------------------------------------------------------------// template<typename T> class optional<T&> { static_assert( !std::is_same<T, nullopt_t>::value, "bad T" ); private: T* ref; public: constexpr optional() noexcept : ref { nullptr } { } constexpr optional(const optional& lhs) noexcept : ref { lhs.ref } { } constexpr optional(optional&& rhs) noexcept : ref { rhs.ref } { rhs.ref = nullptr; } ~optional() = default; optional(T&&) = delete; constexpr explicit optional(T& v) noexcept : ref { std::addressof(v) } { } constexpr explicit optional(nullopt_t) noexcept : ref { nullptr } { } optional& operator =(T& v) noexcept { ref = std::addressof(v); return *this; } optional& operator =(nullopt_t) noexcept { ref = nullptr; return *this; } public: constexpr explicit operator bool() const noexcept { return ref != nullptr; } constexpr T const* operator ->() const { assert(ref); return ref; } constexpr T const& operator *() const { assert(ref); return *ref; } constexpr T* operator ->() { assert(ref); return ref; } constexpr T& operator *() { assert(ref); return *ref; } public: constexpr T const& value() const { assert(ref); return *ref; } constexpr T& value() { assert(ref); return *ref; } }; //---------------------------------------------------------------------------// template<typename T> class optional<T&&> { static_assert(sizeof(T) == 0, "optional<T&&> is disallowed"); }; //---------------------------------------------------------------------------// // operators //---------------------------------------------------------------------------// template<typename T> constexpr bool operator ==(const optional<T>& x, const optional<T>& y) noexcept { return bool(x) != bool(y) ? false : bool(x) == false ? true : *x == *y; } //---------------------------------------------------------------------------// template<typename T> constexpr bool operator !=(const optional<T>& x, const optional<T>& y) noexcept { return !(x == y); } //---------------------------------------------------------------------------// template<typename T> constexpr bool operator ==(const optional<T>& x, nullopt_t) noexcept { return !bool(x); } //---------------------------------------------------------------------------// template<typename T> constexpr bool operator !=(const optional<T>& x, nullopt_t) noexcept { return bool(x); } //---------------------------------------------------------------------------// template<typename T> constexpr bool operator ==(nullopt_t, const optional<T>& x) noexcept { return !bool(x); } //---------------------------------------------------------------------------// template<typename T> constexpr bool operator !=(nullopt_t, const optional<T>& x) noexcept { return bool(x); } //---------------------------------------------------------------------------// } // namespace tapetums //---------------------------------------------------------------------------// // optional.hpp
Python
UTF-8
16,812
2.828125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#!/usr/bin/env python # vim: set fileencoding=utf-8 : # Copyright (c) 2015 Code for Karlsruhe (http://codefor.de/karlsruhe) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """ Scraper for Karlsruhe's drinking water quality indicators. This script scrapes the values of several drinking water quality indicators from the homepage of the Stadtwerke Karlsruhe. """ import cStringIO import contextlib import datetime import locale import urllib2 import PIL.Image # Homepage: # http://www.stadtwerke-karlsruhe.de/swka-de/inhalte/produkte/trinkwasser/online-wert-trinkwasser.php IMAGE_URL = "http://www.stadtwerke-karlsruhe.de/cgi-bin/gd?h=%d&w=%d&r=255&g=255&b=255&tr=0&tg=0&tb=0&wert=%s&tt=%%20%%20%%20&wnull=0&wmax=25" VALUES = { 'w1': ('temperature', '°C'), 'w2': ('ph', ''), 'w3': ('conductivity', 'µS/cm'), 'w4': ('turbidity', 'NTU'), 'w5': ('oxygen', 'mg/l'), 'w6': ('nitrate', 'mg/l'), } def get_image(key, width, height): """ Download one of the images/diagrams. ``key`` is the diagram key (``w1`` to ``w6`` for the indicators, ``w9`` for the date image). ``width`` and ``height`` specify the image dimensions. The return value is a ``PIL.Image.Image`` instance from which the black border has been cropped. """ buf = cStringIO.StringIO(urllib2.urlopen(IMAGE_URL % (height, width, key)).read()) img = PIL.Image.open(buf) return img.crop((1, 1, img.size[0] - 2, img.size[1] - 2)) # Cut 1 pixel border def count_black_pixels(img, left=None, top=None, right=None, bottom=None): """ Count black pixels in an image row- and column-wise. The black pixels in ``img`` are counted row- and column-wise and the result is returned as a 2-tuple. ``left``, ``top``, ``right`` and ``bottom`` specify the borders of the counting area. If not specified they default to the respective image border (e.g. ``top`` defaults to 0). ``left`` and ``top`` are inclusive, ``right`` and ``bottom`` are exclusive. """ columns = img.size[0] if left is None: left = 0 if top is None: top = 0 if right is None: right = columns if bottom is None: bottom = img.size[1] data = img.getdata() hcount = [0] * (bottom - top) vcount = [0] * (right - left) for x in range(left, right): for y in range(top, bottom): if not data[x + y * columns]: hcount[y - top] += 1 vcount[x - left] += 1 return hcount, vcount def get_block_signature(img, left, top, right, bottom): """ Get an image block's signature. The signature is a list of the running indices of the black pixels in the block. ``left``, ``top``, ``right`` and ``bottom`` specify the borders of the block. ``left`` and ``top`` are inclusive, ``right`` and ``bottom`` are exclusive. """ columns = img.size[0] data = img.getdata() sig = [] width = right - left for y in range(top, bottom): for x in range(left, right): index = x + y * columns if not data[index]: sig.append((x - left) + width * (y - top)) return tuple(sig) def split(seq): """ Split a sequence on zeros. The given sequence is split into chunks separated by one or more zeros. The start (inclusive) and end (exclusive) indices of the chunks are returned as a list of 2-tuples. """ indices = [] start = None for i, s in enumerate(seq): if start is None and s: start = i elif start is not None and not s: indices.append((start, i)) start = None if start is not None: indices.append((start, len(seq))) return indices def strip(seq): """ Strip zeros from the front and end of a sequence. Returns a tuple of the first and last non-zero items' indices. """ indices = split(seq) return indices[0][0], indices[-1][1] def get_char_signatures(img, space_width=6): """ Get character signatures for an image. The image is assumed to contain one row of characters, each of which is connected. The return value is a list of character signatures for these characters. If the gap between two characters is equal to or larger than ``space_width`` then a space signature (an empty tuple) is inserted between the characters' signatures. """ signatures = [] img = img.convert('L') vcount = count_black_pixels(img)[1] chars = [] last_right = float('Inf') for left, right in split(vcount): if left - last_right >= space_width: signatures.append(()) # Space hcount = count_black_pixels(img, left=left, right=right)[0] top, bottom = strip(hcount) signatures.append(get_block_signature(img, left, top, right, bottom)) last_right = right return signatures # This table was generated using ``create_classification_table.py``. CLASSES = { (): ' ', (0, 1, 2, 3, 4, 5, 6, 8, 9): '!', (2, 5, 8, 11, 14, 17, 18, 19, 20, 21, 22, 23, 25, 28, 31, 34, 36, 37, 38, 39, 40, 41, 42, 45, 48, 51, 54, 57): '#', (3, 8, 9, 10, 11, 12, 14, 17, 20, 21, 24, 29, 30, 31, 38, 39, 40, 45, 48, 49, 52, 55, 57, 58, 59, 60, 61, 66): '$', (1, 2, 6, 7, 10, 12, 14, 17, 19, 22, 23, 25, 31, 38, 44, 46, 47, 50, 52, 55, 57, 59, 62, 63, 67, 68): '%', (2, 3, 4, 8, 12, 15, 19, 22, 26, 30, 31, 32, 36, 37, 38, 41, 42, 46, 48, 49, 54, 56, 60, 61, 64, 65, 66, 69): '&', (2, 4, 7, 9, 12, 15, 18, 21, 24, 28, 31, 35): '(', (0, 4, 7, 11, 14, 17, 20, 23, 26, 28, 31, 33): ')', (3, 7, 10, 13, 15, 17, 19, 23, 24, 25, 29, 31, 33, 35, 38, 41, 45): '*', (3, 10, 17, 21, 22, 23, 24, 25, 26, 27, 31, 38, 45): '+', (0, 1, 3, 5, 6): ',', (0, 1, 2, 3, 4, 5): '-', (0, 1, 2, 3): '.', (5, 11, 16, 21, 27, 32, 38, 43, 48, 54): '/', (2, 3, 7, 10, 12, 17, 18, 23, 24, 29, 30, 35, 36, 41, 42, 47, 49, 52, 56, 57): '0', (2, 6, 7, 10, 12, 17, 22, 27, 32, 37, 42, 45, 46, 47, 48, 49): '1', (1, 2, 3, 4, 6, 11, 12, 17, 23, 27, 28, 32, 37, 42, 48, 54, 55, 56, 57, 58, 59): '2', (1, 2, 3, 4, 6, 11, 12, 17, 23, 26, 27, 28, 35, 41, 42, 47, 48, 53, 55, 56, 57, 58): '3', (4, 9, 10, 14, 16, 19, 22, 24, 28, 30, 34, 36, 37, 38, 39, 40, 41, 46, 52, 58): '4', (0, 1, 2, 3, 4, 5, 6, 12, 18, 24, 25, 26, 27, 28, 35, 41, 47, 48, 53, 55, 56, 57, 58): '5', (2, 3, 4, 7, 12, 18, 24, 25, 26, 27, 28, 30, 35, 36, 41, 42, 47, 48, 53, 55, 56, 57, 58): '6', (0, 1, 2, 3, 4, 5, 11, 17, 22, 28, 34, 39, 45, 51, 57): '7', (1, 2, 3, 4, 6, 11, 12, 17, 18, 23, 25, 26, 27, 28, 30, 35, 36, 41, 42, 47, 48, 53, 55, 56, 57, 58): '8', (1, 2, 3, 4, 6, 11, 12, 17, 18, 23, 25, 26, 27, 28, 29, 35, 41, 47, 52, 55, 56, 57): '9', (0, 1, 2, 3, 10, 11, 12, 13): ':', (0, 1, 2, 3, 10, 11, 13, 15, 16): ';', (4, 8, 12, 16, 20, 26, 32, 38, 44): '<', (0, 1, 2, 3, 4, 5, 24, 25, 26, 27, 28, 29): '=', (0, 6, 12, 18, 24, 28, 32, 36, 40): '>', (1, 2, 3, 4, 6, 11, 12, 17, 23, 28, 33, 39, 51, 57): '?', (2, 3, 4, 7, 11, 12, 15, 17, 18, 20, 22, 23, 24, 26, 29, 30, 32, 35, 36, 38, 41, 42, 45, 46, 47, 49, 56, 57, 58, 59): '@', (2, 3, 7, 10, 12, 17, 18, 23, 24, 29, 30, 31, 32, 33, 34, 35, 36, 41, 42, 47, 48, 53, 54, 59): 'A', (0, 1, 2, 3, 4, 6, 11, 12, 17, 18, 23, 24, 25, 26, 27, 28, 30, 35, 36, 41, 42, 47, 48, 53, 54, 55, 56, 57, 58): 'B', (1, 2, 3, 4, 6, 11, 12, 18, 24, 30, 36, 42, 48, 53, 55, 56, 57, 58): 'C', (0, 1, 2, 3, 6, 10, 12, 17, 18, 23, 24, 29, 30, 35, 36, 41, 42, 47, 48, 52, 54, 55, 56, 57): 'D', (0, 1, 2, 3, 4, 5, 6, 12, 18, 24, 25, 26, 27, 28, 30, 36, 42, 48, 54, 55, 56, 57, 58, 59): 'E', (0, 1, 2, 3, 4, 5, 6, 12, 18, 24, 25, 26, 27, 28, 30, 36, 42, 48, 54): 'F', (1, 2, 3, 4, 6, 11, 12, 18, 24, 30, 33, 34, 35, 36, 41, 42, 47, 48, 52, 53, 55, 56, 57, 59): 'G', (0, 5, 6, 11, 12, 17, 18, 23, 24, 25, 26, 27, 28, 29, 30, 35, 36, 41, 42, 47, 48, 53, 54, 59): 'H', (0, 1, 2, 3, 4, 7, 12, 17, 22, 27, 32, 37, 42, 45, 46, 47, 48, 49): 'I', (3, 4, 5, 10, 16, 22, 28, 34, 40, 42, 46, 48, 52, 55, 56, 57): 'J', (0, 5, 6, 10, 12, 15, 18, 20, 24, 25, 30, 31, 36, 38, 42, 45, 48, 52, 54, 59): 'K', (0, 6, 12, 18, 24, 30, 36, 42, 48, 54, 55, 56, 57, 58, 59): 'L', (0, 6, 7, 8, 12, 13, 14, 15, 19, 20, 21, 23, 25, 27, 28, 30, 32, 34, 35, 38, 41, 42, 45, 48, 49, 55, 56, 62, 63, 69): 'M', (0, 5, 6, 7, 11, 12, 13, 17, 18, 20, 23, 24, 26, 29, 30, 33, 35, 36, 39, 41, 42, 46, 47, 48, 52, 53, 54, 59): 'N', (1, 2, 3, 4, 6, 11, 12, 17, 18, 23, 24, 29, 30, 35, 36, 41, 42, 47, 48, 53, 55, 56, 57, 58): 'O', (0, 1, 2, 3, 4, 6, 11, 12, 17, 18, 23, 24, 25, 26, 27, 28, 30, 36, 42, 48, 54): 'P', (1, 2, 3, 4, 7, 12, 14, 19, 21, 26, 28, 33, 35, 40, 42, 47, 49, 51, 52, 54, 56, 57, 60, 61, 64, 65, 66, 67, 75, 76): 'Q', (0, 1, 2, 3, 4, 6, 11, 12, 17, 18, 23, 24, 25, 26, 27, 28, 30, 33, 36, 40, 42, 46, 48, 53, 54, 59): 'R', (1, 2, 3, 4, 6, 11, 12, 17, 18, 25, 26, 33, 34, 41, 42, 47, 48, 53, 55, 56, 57, 58): 'S', (0, 1, 2, 3, 4, 5, 6, 10, 17, 24, 31, 38, 45, 52, 59, 66): 'T', (0, 5, 6, 11, 12, 17, 18, 23, 24, 29, 30, 35, 36, 41, 42, 47, 48, 53, 55, 56, 57, 58): 'U', (0, 6, 7, 13, 14, 20, 22, 26, 29, 33, 36, 40, 44, 46, 51, 53, 59, 66): 'V', (0, 6, 7, 13, 14, 20, 21, 24, 27, 28, 31, 34, 35, 38, 41, 42, 45, 48, 49, 51, 53, 55, 56, 58, 60, 62, 64, 68): 'W', (0, 5, 6, 11, 13, 16, 19, 22, 26, 27, 32, 33, 37, 40, 43, 46, 48, 53, 54, 59): 'X', (0, 6, 7, 13, 15, 19, 22, 26, 30, 32, 38, 45, 52, 59, 66): 'Y', (0, 1, 2, 3, 4, 5, 11, 17, 22, 27, 32, 37, 42, 48, 54, 55, 56, 57, 58, 59): 'Z', (0, 1, 2, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 34, 35): '[', (0, 6, 13, 20, 26, 33, 39, 46, 53, 59): '\\', (0, 1, 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 33, 34, 35): ']', (2, 3, 7, 10, 12, 17): '^', (0, 1, 2, 3, 4, 5, 6): '_', (0, 1, 2, 4, 7): '`', (1, 2, 3, 4, 6, 11, 15, 16, 17, 19, 20, 23, 24, 29, 30, 34, 35, 37, 38, 39, 41): 'a', (0, 6, 12, 18, 20, 21, 22, 24, 25, 29, 30, 35, 36, 41, 42, 47, 48, 49, 53, 54, 56, 57, 58): 'b', (1, 2, 3, 4, 6, 11, 12, 18, 24, 30, 35, 37, 38, 39, 40): 'c', (5, 11, 17, 19, 20, 21, 23, 24, 28, 29, 30, 35, 36, 41, 42, 47, 48, 52, 53, 55, 56, 57, 59): 'd', (1, 2, 3, 4, 6, 11, 12, 17, 18, 19, 20, 21, 22, 23, 24, 30, 37, 38, 39, 40): 'e', (2, 3, 4, 7, 11, 13, 19, 24, 25, 26, 27, 28, 31, 37, 43, 49, 55): 'f', (5, 7, 8, 9, 11, 12, 16, 18, 22, 24, 28, 31, 32, 33, 37, 43, 44, 45, 46, 48, 53, 54, 59, 61, 62, 63, 64): 'g', (0, 6, 12, 18, 20, 21, 22, 24, 25, 29, 30, 35, 36, 41, 42, 47, 48, 53, 54, 59): 'h', (2, 7, 16, 17, 22, 27, 32, 37, 42, 45, 46, 47, 48, 49): 'i', (4, 9, 18, 19, 24, 29, 34, 39, 44, 49, 54, 55, 58, 61, 62): 'j', (0, 6, 12, 18, 22, 24, 27, 30, 32, 36, 37, 38, 42, 45, 48, 52, 54, 59): 'k', (1, 2, 7, 12, 17, 22, 27, 32, 37, 42, 45, 46, 47, 48, 49): 'l', (0, 1, 2, 4, 5, 7, 10, 13, 14, 17, 20, 21, 24, 27, 28, 31, 34, 35, 38, 41, 42, 45, 48): 'm', (0, 2, 3, 4, 6, 7, 11, 12, 17, 18, 23, 24, 29, 30, 35, 36, 41): 'n', (1, 2, 3, 4, 6, 11, 12, 17, 18, 23, 24, 29, 30, 35, 37, 38, 39, 40): 'o', (0, 2, 3, 4, 6, 7, 11, 12, 17, 18, 23, 24, 29, 30, 31, 35, 36, 38, 39, 40, 42, 48, 54): 'p', (1, 2, 3, 5, 6, 10, 11, 12, 17, 18, 23, 24, 29, 30, 34, 35, 37, 38, 39, 41, 47, 53, 59): 'q', (0, 2, 3, 4, 6, 7, 11, 12, 18, 24, 30, 36): 'r', (1, 2, 3, 4, 6, 11, 12, 19, 20, 21, 22, 29, 30, 35, 37, 38, 39, 40): 's', (2, 8, 12, 13, 14, 15, 16, 20, 26, 32, 38, 44, 50, 53, 57, 58): 't', (0, 5, 6, 11, 12, 17, 18, 23, 24, 29, 30, 34, 35, 37, 38, 39, 41): 'u', (0, 5, 6, 11, 12, 17, 19, 22, 25, 28, 32, 33, 38, 39): 'v', (0, 6, 7, 10, 13, 14, 17, 20, 21, 24, 27, 28, 31, 34, 35, 37, 39, 41, 43, 47): 'w', (0, 5, 6, 11, 13, 16, 20, 21, 25, 28, 30, 35, 36, 41): 'x', (0, 5, 6, 11, 12, 17, 18, 23, 24, 29, 31, 34, 35, 38, 39, 41, 47, 52, 55, 56, 57): 'y', (0, 1, 2, 3, 4, 5, 10, 15, 20, 25, 30, 36, 37, 38, 39, 40, 41): 'z', (1, 2, 3, 6, 10, 13, 15, 18, 22, 25, 27, 30, 34, 35): '{', (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13): '|', (0, 1, 5, 8, 10, 13, 17, 20, 22, 25, 29, 32, 33, 34): '}', (1, 2, 6, 7, 10, 13, 14, 18, 19): '~', } def get_text(img): """ Extract text from image. """ signatures = get_char_signatures(img) chars = [CLASSES[sig] for sig in signatures] return ''.join(chars) def get_value(key): """ Get diagram value. ``key`` is the diagram key (``w1`` to ``w6``). The diagram is downloaded, its text is extracted, converted to float and returned. """ img = get_image(key, 70, 50) return float(get_text(img)) @contextlib.contextmanager def local_locale(name): """ Context-manager to temporarily switch to a different locale. """ old = locale.getlocale(locale.LC_ALL) try: yield locale.setlocale(locale.LC_ALL, name) finally: locale.setlocale(locale.LC_ALL, old) def get_date(): """ Get time and date of the last update. The date image is downloaded, its text is extracted, converted to a ``datetime.datetime`` instance and returned. """ img = get_image('w9', 300, 20) label = get_text(img) with local_locale('C'): date = datetime.datetime.strptime(label.split(':', 1)[1].strip(), '%d %b %y %H:%M') return date def scrape(): """ Download and parse data. Returns a dictionary with the latest values. """ values = {} for key, (name, unit) in VALUES.iteritems(): values[name] = { 'unit': unit, 'value': get_value(key), } return values def symlink(target, filename): """ Create a symlink. An existing file of the same name is overwritten. """ try: os.remove(filename) except OSError as e: if e.errno != errno.ENOENT: raise os.symlink(target, filename) if __name__ == '__main__': import codecs import errno import json import logging import logging.handlers import os import os.path import sys HERE = os.path.abspath(os.path.dirname(__file__)) log = logging.getLogger('codeforka-trinkwasser') log.setLevel(logging.INFO) formatter = logging.Formatter('[%(asctime)s] <%(levelname)s> %(message)s') file_handler = logging.handlers.TimedRotatingFileHandler( os.path.join(HERE, 'scrape.log'), when='W0', backupCount=4, encoding='utf8') file_handler.setFormatter(formatter) log.addHandler(file_handler) log.info('Started') if len(sys.argv) != 2: log.error('Illegal number of arguments: Expected 1, got %d' % (len(sys.argv) - 1)) sys.exit(1) OUTPUT_DIR = os.path.abspath(sys.argv[1]) if not os.path.isdir(OUTPUT_DIR): log.error('Output directory "%s" does not exist' % OUTPUT_DIR) sys.exit(1) log.info('Output directory is "%s"' % OUTPUT_DIR) try: date = get_date().strftime('%Y-%m-%d-%H-%M-00') log.info('Date of last measurement: %s', date) basename = 'karlsruhe-drinking-water-' + date + '.json' filename = os.path.join(OUTPUT_DIR, basename) if not os.path.isfile(filename): log.info('Scraping data') values = scrape() with codecs.open(filename, 'w', encoding='utf8') as f: json.dump({'date': date, 'values': values}, f, separators=(',',':')) symlink(basename, os.path.join(OUTPUT_DIR, 'latest.json')) else: log.info('Data already scraped, nothing to do') except Exception as e: log.exception(e) log.info('Finished')
Java
UTF-8
68
2.0625
2
[]
no_license
package util; public interface ISorter { int[] sort(int[] arr); }
Go
UTF-8
867
3.046875
3
[ "MIT" ]
permissive
package db import ( "reflect" "testing" ) func TestNewManagerFromEngine(t *testing.T) { type args struct { name string connStr string } tests := []struct { name string args args want DatabaseManager wantErr bool }{ {"PostgresEngine", args{"postgres", "pg://postgres@localhost/apricot?sslmode=disable"}, &postgres{connectionString: "pg://postgres@localhost/apricot?sslmode=disable"}, false}, {"InvalidEngine", args{"invalid", ""}, nil, true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := NewManagerFromEngine(tt.args.name, tt.args.connStr) if (err != nil) != tt.wantErr { t.Errorf("NewManagerFromEngine() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(got, tt.want) { t.Errorf("NewManagerFromEngine() = %v, want %v", got, tt.want) } }) } }
Java
UTF-8
3,239
2.4375
2
[]
no_license
package com.capgemini.springmvc.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import com.capgemini.springmvc.beans.EmployeeInfoBean; import com.capgemini.springmvc.service.EmployeeService; @Controller public class EmployeeController { @Autowired private EmployeeService service; @GetMapping("/empLogin") public String displayLoginForm() { return "empLogin"; }// End of displayLoginForm() @PostMapping("/empLogin") public String empLogin(int empId, String password, ModelMap modelMap, HttpServletRequest req) { EmployeeInfoBean employeeInfoBean = service.authenticate(empId, password); if (employeeInfoBean != null) { // valid Credentials HttpSession session = req.getSession(true); session.setAttribute("employeeInfoBean", employeeInfoBean); return "empHomePage"; } else { // Invalid Credentials // modelMap.addAttribute("msg","Invalid Credentials"); return "empLogin"; } }// End of empLogin() @GetMapping("/addEmployeeForm") public String displayAddForm(HttpSession session, ModelMap modelMap) { if (session.isNew()) { modelMap.addAttribute("msg", "Please login first"); return "empLogin"; } else { return "addEmployeeForm"; } }// End of displayAddForm() @PostMapping("/addEmployeeForm") public String addEmployee(EmployeeInfoBean employeeInfoBean, HttpSession session, ModelMap modelMap) { if (session.isNew()) { // Invalid session modelMap.addAttribute("msg", "Please login first"); return "empLogin"; } else { // valid session if (service.addEmployee(employeeInfoBean)) { modelMap.addAttribute("msg", "Employee added successfully"); } else { modelMap.addAttribute("msg", "Unable to add Employee"); } return "addEmployeeForm"; } }// End of addEmployee @GetMapping("/logout") public String logout(HttpSession session, ModelMap modelMap) { session.invalidate(); modelMap.addAttribute("msg", "Logged out successfully"); return "empLogin"; }// End of logout() @GetMapping("/updateEmployeeForm") public String displayUpdateForm(HttpSession session, ModelMap modelMap) { if (session.isNew()) { // Invalid session modelMap.addAttribute("msg", "Please login first"); return "empLogin"; } else { // Valid session return "updateEmployeeForm"; } }// End of displayUpdateForm() @PostMapping("/updateEmployeeForm") public String updateEmployee(EmployeeInfoBean employeeInfoBean, HttpSession session, ModelMap modelMap) { if (session.isNew()) { // Invalid session modelMap.addAttribute("msg", "Please login first"); return "empLogin"; } else { // valid session if (service.updateEmployee(employeeInfoBean)) { modelMap.addAttribute("msg", "Employee details uodates successfully..."); } else { modelMap.addAttribute("msg", "Unable to update detils..."); } return "updateEmployeeForm"; } }// End of UpdateeEmployee()a }// End of class
SQL
UTF-8
582
2.96875
3
[]
no_license
create database apiDesafio; create table usuarios( id int auto_increment primary key, nome varchar(50), email varchar(150) unique, senha varchar(50), nascimento date, telefone varchar(20), cpf varchar(14), genero char(1) ); create table dadosProfissional( id int auto_increment primary key, profissao varchar(50), numero_registro varchar(14), especialidade varchar(50), localidade varchar(50), area_atendimento float(8, 2), usuario_id int, foreign key (usuario_id) references usuarios (id) on delete cascade on update cascade );
Java
UTF-8
211
1.585938
2
[]
no_license
package se.web.store.dao; import org.springframework.data.jpa.repository.JpaRepository; import se.web.store.entity.Product; public interface ProductDAO extends JpaRepository<Product, Integer> { //CRUD }
Java
UTF-8
694
3.296875
3
[]
no_license
package chainairport; /** * * @author Jack */ /** * This interface will create the methods that will be used in the chain design * pattern. The chainNumber method will be used when an object is passed into the chain * and it will determine which class will handle the object message. The setNextElement * method will add a new link onto the end of the chain and it will determine which class will * be used next in the chain * */ public interface helpDesk { public void chainNumber(int level); //This method is used to determin which class handles the object public void setNextElement(helpDesk next); //This method is used to set the next link of the chain }
JavaScript
UTF-8
159
3.59375
4
[]
no_license
const fn = () => { let sum = 0; for (let i = 1; i <= 155; i++ ) { sum = (i * (i+2)) * (i+3) } return sum; } console.log(fn());
Java
UTF-8
344
2.546875
3
[]
no_license
class Solution { public int countNegatives(int[][] grid) { int total = grid.length * grid[0].length; for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[0].length; j++) { if (grid[i][j] >= 0) total--; else break; } } return total; } }
SQL
UTF-8
17,018
2.921875
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 5.0.4 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Oct 21, 2021 at 06:31 PM -- Server version: 10.4.17-MariaDB -- PHP Version: 8.0.1 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `plvdocx_db` -- -- -------------------------------------------------------- -- -- Table structure for table `document_tbl` -- CREATE TABLE `document_tbl` ( `document_id` int(11) NOT NULL, `document_name` varchar(30) NOT NULL, `document_pricePerPageInPhp` int(11) NOT NULL, `document_pages` int(11) NOT NULL, `document_processDays` int(3) NOT NULL, `document_icon` varchar(100) NOT NULL, `isDeleted` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `document_tbl` -- INSERT INTO `document_tbl` (`document_id`, `document_name`, `document_pricePerPageInPhp`, `document_pages`, `document_processDays`, `document_icon`, `isDeleted`) VALUES (1, 'CAV', 150, 3, 2, 'image/cav.png', 0), (2, 'COR', 100, 1, 5, 'image/inc.png', 0), (3, 'LOA', 100, 1, 2, 'image/formsleaveofabsence.png', 0), (4, 'Transfer Credentials', 100, 1, 2, 'image/transfercreds.png', 0), (5, 'Diploma', 100, 1, 2, 'image/DIPLOMA.png', 0); -- -------------------------------------------------------- -- -- Table structure for table `employeetype_tbl` -- CREATE TABLE `employeetype_tbl` ( `employeeType_id` int(11) NOT NULL, `employeeType_name` varchar(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `employeetype_tbl` -- INSERT INTO `employeetype_tbl` (`employeeType_id`, `employeeType_name`) VALUES (1, 'admin'), (2, 'registrar'), (3, 'cashier'); -- -------------------------------------------------------- -- -- Table structure for table `employee_tbl` -- CREATE TABLE `employee_tbl` ( `employee_id` int(15) NOT NULL, `employee_fn` varchar(20) NOT NULL, `employee_mn` varchar(20) NOT NULL, `employee_ln` varchar(20) NOT NULL, `employee_type` int(20) NOT NULL, `employee_email` varchar(40) NOT NULL, `employee_username` varchar(20) NOT NULL, `employee_password` varchar(20) NOT NULL, `isActive` int(1) NOT NULL, `employee_isMale` int(1) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `employee_tbl` -- INSERT INTO `employee_tbl` (`employee_id`, `employee_fn`, `employee_mn`, `employee_ln`, `employee_type`, `employee_email`, `employee_username`, `employee_password`, `isActive`, `employee_isMale`) VALUES (0, 'Harvey', 'Sanchez', 'Resurreccion', 1, '', 'rezsolutions', 'admin', 1, 0), (1, 'Vince', '', 'Lucas', 2, '', 'irving', 'lucas', 1, 1), (2, 'Kier', '', 'Uychutin', 3, '', 'kier', 'admin', 0, 1), (3, 'Almiras', '', 'Pusing', 1, '', 'mira', 'admin', 1, 0); -- -------------------------------------------------------- -- -- Table structure for table `notificationstudent_tbl` -- CREATE TABLE `notificationstudent_tbl` ( `notificationStudent_id` int(11) NOT NULL, `student_id` int(11) NOT NULL, `notificationStudent_description` varchar(1000) NOT NULL, `notificationStudent_isSeen` int(1) NOT NULL, `notificationStudent_date` date NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `notificationstudent_tbl` -- INSERT INTO `notificationstudent_tbl` (`notificationStudent_id`, `student_id`, `notificationStudent_description`, `notificationStudent_isSeen`, `notificationStudent_date`) VALUES (1, 180227, 'TEST', 1, '2021-06-08'), (2, 0, 'The Registrar is now processing your request.', 0, '2021-06-09'), (3, 0, 'The Registrar is now processing your request.', 0, '2021-06-09'), (4, 180227, 'The Registrar is now processing your request.', 1, '2021-06-09'), (5, 180227, 'The Registrar is now processing your requestTOR', 1, '2021-06-09'), (6, 180227, 'The Registrar is now processing your document TOR', 1, '2021-06-09'), (7, 180227, 'Your requested document (TOR)is now being printed', 1, '2021-06-09'), (8, 180227, 'Your requested document (TOR) is now being signed', 1, '2021-06-09'), (9, 180227, 'Your requested document (TOR) is now being signed', 1, '2021-06-09'), (10, 180227, 'Your requested document (TOR) is now ready to be released.', 1, '2021-06-09'), (11, 180227, 'Your requested document (TOR) was released successfully.', 1, '2021-06-09'), (12, 180227, 'The Registrar is now processing your document CAV', 1, '2021-08-03'), (13, 180227, 'The Registrar is now processing your document CAV', 1, '2021-08-03'), (14, 180227, 'The Registrar is now processing your document COR', 1, '2021-08-03'), (15, 180227, 'Your requested document (CAV)is now being printed', 1, '2021-08-03'), (16, 180227, 'Your requested document (CAV)is now being printed', 1, '2021-08-03'), (17, 180227, 'Your requested document (CAV)is now being printed', 1, '2021-08-03'), (18, 180227, 'Your requested document (COR)is now being printed', 1, '2021-08-03'), (19, 180227, 'Your requested document (CAV) is now being stamped', 1, '2021-08-03'), (20, 180227, 'Your requested document (CAV) is now being stamped', 1, '2021-08-03'), (21, 180227, 'Your requested document (COR) is now being stamped', 1, '2021-08-03'), (22, 180227, 'Your requested document (CAV) is now being stamped', 1, '2021-08-03'), (23, 180227, 'Your requested document (CAV) is now being signed', 1, '2021-08-03'), (24, 180227, 'Your requested document (CAV) is now being signed', 1, '2021-08-03'), (25, 180227, 'Your requested document (COR) is now being signed', 1, '2021-08-03'), (26, 180227, 'Your requested document (CAV) is now being signed', 1, '2021-08-03'), (27, 180227, 'Your requested document (CAV) is now ready to be released.', 1, '2021-08-03'), (28, 180227, 'Your requested document (CAV) is now ready to be released.', 1, '2021-08-03'), (29, 180227, 'Your requested document (COR) is now ready to be released.', 1, '2021-08-03'), (30, 180227, 'Your requested document (CAV) is now ready to be released.', 1, '2021-08-03'), (31, 180227, 'Your requested document (CAV) was released successfully.', 1, '2021-08-03'), (32, 180227, 'Your requested document (CAV) was released successfully.', 1, '2021-08-03'), (33, 180227, 'Your requested document (COR) was released successfully.', 1, '2021-08-03'), (34, 180227, 'Your requested document (CAV) was released successfully.', 1, '2021-08-03'), (35, 180299, 'The Registrar is now processing your document CAV', 0, '2021-08-03'), (36, 180299, 'Your requested document (CAV)is now being printed', 0, '2021-08-03'), (37, 180299, 'Your requested document (CAV) is now being stamped', 0, '2021-08-03'), (38, 180299, 'Your requested document (CAV) is now being signed', 0, '2021-08-03'), (39, 180299, 'Your requested document (CAV) is now ready to be released.', 0, '2021-08-03'), (40, 180299, 'Your requested document (CAV) was released successfully.', 0, '2021-08-03'), (41, 180222, 'Your requested document (CAV)is now being printed', 0, '2021-10-10'), (42, 180222, 'Your requested document (CAV) is now being stamped', 0, '2021-10-10'), (43, 180222, 'Your requested document (CAV) is now being signed', 0, '2021-10-10'), (44, 180222, 'Your requested document (CAV) is now ready to be released.', 0, '2021-10-10'), (45, 180222, 'Your requested document (CAV) was released successfully.', 0, '2021-10-10'), (46, 180227, 'The Registrar is now processing your document CAV', 1, '2021-10-10'), (47, 180227, 'The Registrar is now processing your document CAV', 1, '2021-10-14'), (48, 180227, 'The Registrar is now processing your document CAV', 1, '2021-10-14'), (49, 180227, 'Your requested document (CAV)is now being printed', 1, '2021-10-14'), (50, 180227, 'Your requested document (CAV) is now being stamped', 1, '2021-10-14'), (51, 180227, 'Your requested document (CAV) is now being signed', 1, '2021-10-14'), (52, 180227, 'Your requested document (CAV) is now ready to be released.', 1, '2021-10-14'), (53, 180227, 'Your requested document (CAV) was released successfully.', 1, '2021-10-14'), (54, 180220, '', 1, '2021-10-20'), (55, 180220, '', 1, '2021-10-20'), (56, 180220, '', 1, '2021-10-20'), (57, 180220, '', 1, '2021-10-20'), (58, 180220, '', 1, '2021-10-20'), (59, 180220, '', 1, '2021-10-20'), (60, 180220, 'Document (CAV) was successfully requested, please proceed to the cashier to pay!', 1, '2021-10-20'), (61, 18, 'Document (CAV) was successfully requested, please proceed to the cashier to pay!', 0, '2021-10-21'); -- -------------------------------------------------------- -- -- Table structure for table `studentlevel_tbl` -- CREATE TABLE `studentlevel_tbl` ( `studentLevel_id` int(11) NOT NULL, `studentLevel_name` varchar(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `studentlevel_tbl` -- INSERT INTO `studentlevel_tbl` (`studentLevel_id`, `studentLevel_name`) VALUES (1, 'College'), (2, 'Senior High School'); -- -------------------------------------------------------- -- -- Table structure for table `studenttype_tbl` -- CREATE TABLE `studenttype_tbl` ( `studentType_id` int(11) NOT NULL, `studentType_name` varchar(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `studenttype_tbl` -- INSERT INTO `studenttype_tbl` (`studentType_id`, `studentType_name`) VALUES (1, 'Graduate'), (2, 'Undergraduate'), (3, 'Alumni'), (4, 'Drop Out/Transferred'); -- -------------------------------------------------------- -- -- Table structure for table `student_tbl` -- CREATE TABLE `student_tbl` ( `student_id` varchar(11) NOT NULL, `student_fn` varchar(20) NOT NULL, `student_mn` varchar(20) DEFAULT NULL, `student_ln` varchar(20) NOT NULL, `student_type` int(11) NOT NULL, `student_email` varchar(40) NOT NULL, `student_username` varchar(20) NOT NULL, `student_password` varchar(20) NOT NULL, `student_level` int(11) NOT NULL, `student_photo` varchar(100) NOT NULL, `isActive` int(11) NOT NULL, `student_isMale` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `student_tbl` -- INSERT INTO `student_tbl` (`student_id`, `student_fn`, `student_mn`, `student_ln`, `student_type`, `student_email`, `student_username`, `student_password`, `student_level`, `student_photo`, `isActive`, `student_isMale`) VALUES ('18-0229', 'Harvey Van', 'Sanchez', 'Resurreccion', 1, 'van.resurreccion@gmail.com', 'harves', '123123', 1, 'photos/61709c2538f516.49514734.jpg', 0, 1); -- -------------------------------------------------------- -- -- Table structure for table `transactiondetailed_tbl` -- CREATE TABLE `transactiondetailed_tbl` ( `transactionDetailed_id` int(11) NOT NULL, `transactionMaster_id` int(11) NOT NULL, `document_id` int(11) NOT NULL, `document_quantity` int(11) NOT NULL, `document_pages` int(11) NOT NULL, `document_pricePerPage` int(11) NOT NULL, `document_subtotal` int(11) NOT NULL, `transaction_status` int(10) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `transactiondetailed_tbl` -- INSERT INTO `transactiondetailed_tbl` (`transactionDetailed_id`, `transactionMaster_id`, `document_id`, `document_quantity`, `document_pages`, `document_pricePerPage`, `document_subtotal`, `transaction_status`) VALUES (29, 36, 1, 1, 3, 150, 150, 1); -- -------------------------------------------------------- -- -- Table structure for table `transactionmaster_tbl` -- CREATE TABLE `transactionmaster_tbl` ( `transaction_id` int(11) NOT NULL, `student_id` varchar(11) NOT NULL, `employee_id` int(11) NOT NULL, `amount_total` int(11) NOT NULL, `amount_payment` int(11) NOT NULL, `transaction_date` date NOT NULL, `transaction_dateFinished` date NOT NULL, `isFinished` int(1) NOT NULL, `isCancelled` int(2) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `transactionmaster_tbl` -- INSERT INTO `transactionmaster_tbl` (`transaction_id`, `student_id`, `employee_id`, `amount_total`, `amount_payment`, `transaction_date`, `transaction_dateFinished`, `isFinished`, `isCancelled`) VALUES (36, '18-0229', 0, 150, 0, '2021-10-21', '2021-10-25', 0, 0); -- -------------------------------------------------------- -- -- Table structure for table `transactionstatus_tbl` -- CREATE TABLE `transactionstatus_tbl` ( `transactionStatus_id` int(11) NOT NULL, `transactionStatus_name` varchar(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `transactionstatus_tbl` -- INSERT INTO `transactionstatus_tbl` (`transactionStatus_id`, `transactionStatus_name`) VALUES (1, 'toPay'), (2, 'processing'), (3, 'printing'), (4, 'stamping'), (5, 'signature'), (6, 'toRelease'), (7, 'released'), (8, 'unclaimed'), (9, 'cancelled'); -- -- Indexes for dumped tables -- -- -- Indexes for table `document_tbl` -- ALTER TABLE `document_tbl` ADD PRIMARY KEY (`document_id`); -- -- Indexes for table `employeetype_tbl` -- ALTER TABLE `employeetype_tbl` ADD PRIMARY KEY (`employeeType_id`); -- -- Indexes for table `employee_tbl` -- ALTER TABLE `employee_tbl` ADD PRIMARY KEY (`employee_id`), ADD KEY `admintype` (`employee_type`); -- -- Indexes for table `notificationstudent_tbl` -- ALTER TABLE `notificationstudent_tbl` ADD PRIMARY KEY (`notificationStudent_id`); -- -- Indexes for table `studentlevel_tbl` -- ALTER TABLE `studentlevel_tbl` ADD PRIMARY KEY (`studentLevel_id`); -- -- Indexes for table `studenttype_tbl` -- ALTER TABLE `studenttype_tbl` ADD PRIMARY KEY (`studentType_id`); -- -- Indexes for table `student_tbl` -- ALTER TABLE `student_tbl` ADD PRIMARY KEY (`student_id`), ADD KEY `studenttype` (`student_type`), ADD KEY `studentlevel` (`student_level`); -- -- Indexes for table `transactiondetailed_tbl` -- ALTER TABLE `transactiondetailed_tbl` ADD PRIMARY KEY (`transactionDetailed_id`), ADD KEY `transaction_id` (`transactionMaster_id`); -- -- Indexes for table `transactionmaster_tbl` -- ALTER TABLE `transactionmaster_tbl` ADD PRIMARY KEY (`transaction_id`), ADD KEY `studentId` (`student_id`), ADD KEY `employeeId` (`employee_id`); -- -- Indexes for table `transactionstatus_tbl` -- ALTER TABLE `transactionstatus_tbl` ADD PRIMARY KEY (`transactionStatus_id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `document_tbl` -- ALTER TABLE `document_tbl` MODIFY `document_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; -- -- AUTO_INCREMENT for table `employeetype_tbl` -- ALTER TABLE `employeetype_tbl` MODIFY `employeeType_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT for table `notificationstudent_tbl` -- ALTER TABLE `notificationstudent_tbl` MODIFY `notificationStudent_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=62; -- -- AUTO_INCREMENT for table `studentlevel_tbl` -- ALTER TABLE `studentlevel_tbl` MODIFY `studentLevel_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT for table `studenttype_tbl` -- ALTER TABLE `studenttype_tbl` MODIFY `studentType_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT for table `transactiondetailed_tbl` -- ALTER TABLE `transactiondetailed_tbl` MODIFY `transactionDetailed_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=30; -- -- AUTO_INCREMENT for table `transactionmaster_tbl` -- ALTER TABLE `transactionmaster_tbl` MODIFY `transaction_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=37; -- -- AUTO_INCREMENT for table `transactionstatus_tbl` -- ALTER TABLE `transactionstatus_tbl` MODIFY `transactionStatus_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10; -- -- Constraints for dumped tables -- -- -- Constraints for table `employee_tbl` -- ALTER TABLE `employee_tbl` ADD CONSTRAINT `admintype` FOREIGN KEY (`employee_type`) REFERENCES `employeetype_tbl` (`employeeType_id`); -- -- Constraints for table `student_tbl` -- ALTER TABLE `student_tbl` ADD CONSTRAINT `studentlevel` FOREIGN KEY (`student_level`) REFERENCES `studentlevel_tbl` (`studentLevel_id`), ADD CONSTRAINT `studenttype` FOREIGN KEY (`student_type`) REFERENCES `studenttype_tbl` (`studentType_id`); -- -- Constraints for table `transactiondetailed_tbl` -- ALTER TABLE `transactiondetailed_tbl` ADD CONSTRAINT `transaction_id` FOREIGN KEY (`transactionMaster_id`) REFERENCES `transactionmaster_tbl` (`transaction_id`); -- -- Constraints for table `transactionmaster_tbl` -- ALTER TABLE `transactionmaster_tbl` ADD CONSTRAINT `employeeId` FOREIGN KEY (`employee_id`) REFERENCES `employee_tbl` (`employee_id`), ADD CONSTRAINT `studentId` FOREIGN KEY (`student_id`) REFERENCES `student_tbl` (`student_id`); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Java
UTF-8
1,917
2.828125
3
[ "MIT" ]
permissive
package graphics.bar; import biuoop.DrawSurface; import geometry.invisible.Point; import geometry.visible.DrawableRectangle; import handlers.gameTrackers.Counter; import handlers.graphic.Sprite; import settings.GameStandarts; import java.awt.Color; /** * Bar. */ public class Bar implements Sprite { private DrawableRectangle rectangle; private LevelName levelName; private LivesIndicator livesIndicator; private ScoreIndicator scoreIndicator; /** * Constractor. * * @param levelN gameManger name * @param score highScores * @param lives lives */ public Bar(String levelN, Counter score, Counter lives) { createRectangleBar(); initialAll(levelN, score, lives); } /** * Create Rec. */ private void createRectangleBar() { Point zero = new Point(0, 0); rectangle = new DrawableRectangle(zero, GameStandarts.BAR_SIZE, GameStandarts.HEIGHT, new Color(217, 217, 217)); } /** * Initial. * * @param levelN gameManger name * @param score highScores * @param lives lives */ private void initialAll(String levelN, Counter score, Counter lives) { Point lN = new Point(10, 18); Point lI = new Point(GameStandarts.HEIGHT - 60, 18); Point sI = new Point(GameStandarts.HEIGHT / 2 - 45, 18); levelName = new LevelName(lN, levelN); livesIndicator = new LivesIndicator(lI, lives); scoreIndicator = new ScoreIndicator(sI, score); } /** * draw. * * @param d drawsurface. */ public void drawOn(DrawSurface d) { rectangle.drawOn(d); levelName.drawOn(d); livesIndicator.drawOn(d); scoreIndicator.drawOn(d); } /** * move one step, and check collisions. * * @param dt dt */ public void timePassed(double dt) { } }
C++
UTF-8
724
2.640625
3
[]
no_license
/// /// /// #ifndef ___STRING_TABLE_SET_H_ #define ___STRING_TABLE_SET_H_ #include <string> #include <map> namespace stable { class string_table; class string_table_set { public: typedef unsigned long id_type; struct config { string_table *st; typedef std::map<id_type, std::string> FileTableT; FileTableT ft; }; typedef std::map<id_type, config> TableSetT; public: ~string_table_set() { clear(); } bool load( const std::string &file ); bool save(); void clear(); string_table *get_st( id_type id ); string_table *get_key_st(); void update_key_st_ids(); private: TableSetT _tables; id_type _keyTable; }; } #endif
Java
UTF-8
2,126
2.96875
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package metodaszablonowa; /** * * @author lenovo */ public class Kremówka extends Przepis{ @Override protected String ilustracja() { return "obraz\\kremówka.jpg"; } @Override protected String tytul() { return "Kremówka"; } @Override protected String skladniki() { return "<html> 100 g mąki <br/>" + "3 kostki masła <br/>" + "400 g mąki </br>" + "2 jajka <br/>" + "0,5 szklanki wody <br/>" + "7 żółtek <br/>" + "1 l mleka <br/>" + "250 g mąki <br/>" + "250 g cukru <br/>" + "ocet</html>"; } @Override protected String ciasto() { return "<html> Do mąki dodajemy masło i urabiamy. Ciasto odstawiamy na 15 min <br/>" + "do lodówki. Do mąki dodajemy ocet, jajak i wodę i ugniatamy. Odstawiamy <br/>" + "na pół godziny.Na ciasto z octem kładziemy ciasto z masłem. Rozwałkowujemy i składamy ciasto <br/>" + "Następnie wkładamy je do lodówki na 15 min. Tą czynność powtarzamy 5 razy </html>"; } @Override protected String masa() { return " "; } @Override protected String pieczenie() { return "Pieczemy w piekarniku nagrzanym do 220 stopni przez 30 min"; } @Override protected String dodatki() { return "<html>Ucieramy żółtka z cukrem. Dodajemy mąki i powoli gorące mleko. Postawić nad <br/>" + "ciepłą wodą i mieszamy. Gdy wystygnie ucieramy masło i dodajemy krem. Kakładamy na </br>" + "ciasto. Na krem nałożyć bita śmietanę i ozdobić owocami.</html>"; } @Override protected String polewa() { return "Posypujemy cukrem pudrem"; } }
Markdown
UTF-8
16,701
3.828125
4
[ "Apache-2.0", "MIT" ]
permissive
# Quickstart tutorial If you are familiar with Python Numpy, do check out this [For Numpy User Doc](https://docs.rs/ndarray/0.13.0/ndarray/doc/ndarray_for_numpy_users/index.html) after you go through this tutorial. You can use [play.integer32.com](https://play.integer32.com/) to immediately try out the examples. ## The Basics You can create your first 2x3 floating-point ndarray as such: ```rust use ndarray::prelude::*; fn main() { let a = array![ [1.,2.,3.], [4.,5.,6.], ]; assert_eq!(a.ndim(), 2); // get the number of dimensions of array a assert_eq!(a.len(), 6); // get the number of elements in array a assert_eq!(a.shape(), [2, 3]); // get the shape of array a assert_eq!(a.is_empty(), false); // check if the array has zero elements println!("{:?}", a); } ``` This code will create a simple array, then print it to stdout as such: ``` [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], shape=[2, 3], strides=[3, 1], layout=C (0x1), const ndim=2 ``` ## Array Creation ### Element type and dimensionality Now let's create more arrays. A common operation on matrices is to create a matrix full of 0's of certain dimensions. Let's try to do that with dimensions (3, 2, 4) using the `Array::zeros` function: ```rust use ndarray::prelude::*; use ndarray::Array; fn main() { let a = Array::zeros((3, 2, 4).f()); println!("{:?}", a); } ``` Unfortunately, this code does not compile. ``` | let a = Array::zeros((3, 2, 4).f()); | - ^^^^^^^^^^^^ cannot infer type for type parameter `A` ``` Indeed, note that the compiler needs to infer the element type and dimensionality from context only. In this case the compiler does not have enough information. To fix the code, we can explicitly give the element type through turbofish syntax, and let it infer the dimensionality type: ```rust use ndarray::prelude::*; use ndarray::Array; fn main() { let a = Array::<f64, _>::zeros((3, 2, 4).f()); println!("{:?}", a); } ``` This code now compiles to what we wanted: ``` [[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]], [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]], [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]], shape=[3, 2, 4], strides=[1, 3, 6], layout=F (0x2), const ndim=3 ``` We could also specify its dimensionality explicitly `Array::<f64, Ix3>::zeros(...)`, with`Ix3` standing for 3D array type. Phew! We achieved type safety. If you tried changing the code above to `Array::<f64, Ix3>::zeros((3, 2, 4, 5).f());`, which is not of dimension 3 anymore, Rust's type system would gracefully prevent you from compiling the code. ### Creating arrays with different initial values and/or different types The [`from_elem`](http://docs.rs/ndarray/latest/ndarray/struct.ArrayBase.html#method.from_elem) method allows initializing an array of given dimension to a specific value of any type: ```rust use ndarray::{Array, Ix3}; fn main() { let a = Array::<bool, Ix3>::from_elem((3, 2, 4), false); println!("{:?}", a); } ``` ### Some common array initializing helper functions `linspace` - Create a 1-D array with 11 elements with values 0., …, 5. ```rust use ndarray::prelude::*; use ndarray::{Array, Ix3}; fn main() { let a = Array::<f64, _>::linspace(0., 5., 11); println!("{:?}", a); } ``` The output is: ``` [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0], shape=[11], strides=[1], layout=C | F (0x3), const ndim=1 ``` Common array initializing methods include [`range`](https://docs.rs/ndarray/0.13.0/ndarray/struct.ArrayBase.html#method.range), [`logspace`](https://docs.rs/ndarray/0.13.0/ndarray/struct.ArrayBase.html#method.logspace), [`eye`](https://docs.rs/ndarray/0.13.0/ndarray/struct.ArrayBase.html#method.eye), [`ones`](https://docs.rs/ndarray/0.13.0/ndarray/struct.ArrayBase.html#method.ones)... ## Basic operations Basic operations on arrays are all element-wise; you need to use specific methods for operations such as matrix multiplication (see later section). ```rust use ndarray::prelude::*; use ndarray::Array; use std::f64::INFINITY as inf; fn main() { let a = array![ [10.,20.,30., 40.,], ]; let b = Array::range(0., 4., 1.); // [0., 1., 2., 3, ] assert_eq!(&a + &b, array![[10., 21., 32., 43.,]]); // Allocates a new array. Note the explicit `&`. assert_eq!(&a - &b, array![[10., 19., 28., 37.,]]); assert_eq!(&a * &b, array![[0., 20., 60., 120.,]]); assert_eq!(&a / &b, array![[inf, 20., 15., 13.333333333333334,]]); } ``` Note that (for any binary operator `@`): * `&A @ &A` produces a new `Array` * `B @ A` consumes `B`, updates it with the result, and returns it * `B @ &A` consumes `B`, updates it with the result, and returns it * `C @= &A` performs an arithmetic operation in place Try removing all the `&` sign in front of `a` and `b` in the last example: it will not compile anymore because of those rules. For more info checkout https://docs.rs/ndarray/latest/ndarray/struct.ArrayBase.html#arithmetic-operations Some operations have `_axis` appended to the function name: they generally take in a parameter of type `Axis` as one of their inputs, such as `sum_axis`: ```rust use ndarray::{aview0, aview1, arr2, Axis}; fn main() { let a = arr2(&[[1., 2., 3.], [4., 5., 6.]]); assert!( a.sum_axis(Axis(0)) == aview1(&[5., 7., 9.]) && a.sum_axis(Axis(1)) == aview1(&[6., 15.]) && a.sum_axis(Axis(0)).sum_axis(Axis(0)) == aview0(&21.) && a.sum_axis(Axis(0)).sum_axis(Axis(0)) == aview0(&a.sum()) ); } ``` ### Matrix product ```rust use ndarray::prelude::*; use ndarray::Array; fn main() { let a = array![ [10.,20.,30., 40.,], ]; let b = Array::range(0., 4., 1.); // b = [0., 1., 2., 3, ] println!("a shape {:?}", &a.shape()); println!("b shape {:?}", &b.shape()); let b = b.into_shape((4,1)).unwrap(); // reshape b to shape [4, 1] println!("b shape {:?}", &b.shape()); println!("{}", a.dot(&b)); // [1, 4] x [4, 1] -> [1, 1] println!("{}", a.t().dot(&b.t())); // [4, 1] x [1, 4] -> [4, 4] } ``` The output is: ``` a shape [1, 4] b shape [4] b shape after reshape [4, 1] [[200]] [[0, 10, 20, 30], [0, 20, 40, 60], [0, 30, 60, 90], [0, 40, 80, 120]] ``` ## Indexing, Slicing and Iterating One-dimensional arrays can be indexed, sliced and iterated over, much like `numpy` arrays ```rust use ndarray::prelude::*; use ndarray::Array; fn main() { let a = Array::range(0., 10., 1.); let mut a = a.mapv(|a: f64| a.powi(3)); // numpy equivlant of `a ** 3`; https://doc.rust-lang.org/nightly/std/primitive.f64.html#method.powi println!("{}", a); println!("{}", a[[2]]); println!("{}", a.slice(s![2])); println!("{}", a.slice(s![2..5])); a.slice_mut(s![..6;2]).fill(1000.); // numpy equivlant of `a[:6:2] = 1000` println!("{}", a); for i in a.iter() { print!("{}, ", i.powf(1./3.)) } } ``` The output is: ``` [0, 1, 8, 27, 64, 125, 216, 343, 512, 729] 8 8 [8, 27, 64] [1000, 1, 1000, 27, 1000, 125, 216, 343, 512, 729] 9.999999999999998, 1, 9.999999999999998, 3, 9.999999999999998, 4.999999999999999, 5.999999999999999, 6.999999999999999, 7.999999999999999, 8.999999999999998, ``` For more info about iteration see [Loops, Producers, and Iterators](https://docs.rs/ndarray/0.13.0/ndarray/struct.ArrayBase.html#loops-producers-and-iterators) Let's try a iterating over a 3D array with elements of type `isize`. This is how you index it: ```rust use ndarray::prelude::*; fn main() { let a = array![ [[ 0, 1, 2], // a 3D array 2 x 2 x 3 [ 10, 12, 13]], [[100,101,102], [110,112,113]] ]; let a = a.mapv(|a: isize| a.pow(1)); // numpy equivalent of `a ** 1`; // This line does nothing except illustrating mapv with isize type println!("a -> \n{}\n", a); println!("`a.slice(s![1, .., ..])` -> \n{}\n", a.slice(s![1, .., ..])); println!("`a.slice(s![.., .., 2])` -> \n{}\n", a.slice(s![.., .., 2])); println!("`a.slice(s![.., 1, 0..2])` -> \n{}\n", a.slice(s![.., 1, 0..2])); println!("`a.iter()` ->"); for i in a.iter() { print!("{}, ", i) // flat out to every element } println!("\n\n`a.outer_iter()` ->"); for i in a.outer_iter() { print!("row: {}, \n", i) // iterate through first dimension } } ``` The output is: ``` a -> [[[0, 1, 2], [10, 12, 13]], [[100, 101, 102], [110, 112, 113]]] `a.slice(s![1, .., ..])` -> [[100, 101, 102], [110, 112, 113]] `a.slice(s![.., .., 2])` -> [[2, 13], [102, 113]] `a.slice(s![.., 1, 0..2])` -> [[10, 12], [110, 112]] `a.iter()` -> 0, 1, 2, 10, 12, 13, 100, 101, 102, 110, 112, 113, `a.outer_iter()` -> row: [[0, 1, 2], [10, 12, 13]], row: [[100, 101, 102], [110, 112, 113]], ``` ## Shape Manipulation ### Changing the shape of an array The shape of an array can be changed with `into_shape` method. ````rust use ndarray::prelude::*; use ndarray::Array; use std::iter::FromIterator; // use ndarray_rand::RandomExt; // use ndarray_rand::rand_distr::Uniform; fn main() { // Or you may use ndarray_rand crate to generate random arrays // let a = Array::random((2, 5), Uniform::new(0., 10.)); let a = array![ [3., 7., 3., 4.], [1., 4., 2., 2.], [7., 2., 4., 9.]]; println!("a = \n{:?}\n", a); // use trait FromIterator to flatten a matrix to a vector let b = Array::from_iter(a.iter()); println!("b = \n{:?}\n", b); let c = b.into_shape([6, 2]).unwrap(); // consume b and generate c with new shape println!("c = \n{:?}", c); } ```` The output is: ``` a = [[3.0, 7.0, 3.0, 4.0], [1.0, 4.0, 2.0, 2.0], [7.0, 2.0, 4.0, 9.0]], shape=[3, 4], strides=[4, 1], layout=C (0x1), const ndim=2 b = [3.0, 7.0, 3.0, 4.0, 1.0, 4.0, 2.0, 2.0, 7.0, 2.0, 4.0, 9.0], shape=[12], strides=[1], layout=C | F (0x3), const ndim=1 c = [[3.0, 7.0], [3.0, 4.0], [1.0, 4.0], [2.0, 2.0], [7.0, 2.0], [4.0, 9.0]], shape=[6, 2], strides=[2, 1], layout=C (0x1), const ndim=2 ``` ### Stacking/concatenating together different arrays The `stack!` and `concatenate!` macros are helpful for stacking/concatenating arrays. The `stack!` macro stacks arrays along a new axis, while the `concatenate!` macro concatenates arrays along an existing axis: ```rust use ndarray::prelude::*; use ndarray::{concatenate, stack, Axis}; fn main() { let a = array![ [3., 7., 8.], [5., 2., 4.], ]; let b = array![ [1., 9., 0.], [5., 4., 1.], ]; println!("stack, axis 0:\n{:?}\n", stack![Axis(0), a, b]); println!("stack, axis 1:\n{:?}\n", stack![Axis(1), a, b]); println!("stack, axis 2:\n{:?}\n", stack![Axis(2), a, b]); println!("concatenate, axis 0:\n{:?}\n", concatenate![Axis(0), a, b]); println!("concatenate, axis 1:\n{:?}\n", concatenate![Axis(1), a, b]); } ``` The output is: ``` stack, axis 0: [[[3.0, 7.0, 8.0], [5.0, 2.0, 4.0]], [[1.0, 9.0, 0.0], [5.0, 4.0, 1.0]]], shape=[2, 2, 3], strides=[6, 3, 1], layout=Cc (0x5), const ndim=3 stack, axis 1: [[[3.0, 7.0, 8.0], [1.0, 9.0, 0.0]], [[5.0, 2.0, 4.0], [5.0, 4.0, 1.0]]], shape=[2, 2, 3], strides=[3, 6, 1], layout=c (0x4), const ndim=3 stack, axis 2: [[[3.0, 1.0], [7.0, 9.0], [8.0, 0.0]], [[5.0, 5.0], [2.0, 4.0], [4.0, 1.0]]], shape=[2, 3, 2], strides=[1, 2, 6], layout=Ff (0xa), const ndim=3 concatenate, axis 0: [[3.0, 7.0, 8.0], [5.0, 2.0, 4.0], [1.0, 9.0, 0.0], [5.0, 4.0, 1.0]], shape=[4, 3], strides=[3, 1], layout=Cc (0x5), const ndim=2 concatenate, axis 1: [[3.0, 7.0, 8.0, 1.0, 9.0, 0.0], [5.0, 2.0, 4.0, 5.0, 4.0, 1.0]], shape=[2, 6], strides=[1, 2], layout=Ff (0xa), const ndim=2 ``` ### Splitting one array into several smaller ones More to see here [ArrayView::split_at](https://docs.rs/ndarray/latest/ndarray/type.ArrayView.html#method.split_at) ```rust use ndarray::prelude::*; use ndarray::Axis; fn main() { let a = array![ [6., 7., 6., 9., 0., 5., 4., 0., 6., 8., 5., 2.], [8., 5., 5., 7., 1., 8., 6., 7., 1., 8., 1., 0.]]; let (s1, s2) = a.view().split_at(Axis(0), 1); println!("Split a from Axis(0), at index 1:"); println!("s1 = \n{}", s1); println!("s2 = \n{}\n", s2); let (s1, s2) = a.view().split_at(Axis(1), 4); println!("Split a from Axis(1), at index 4:"); println!("s1 = \n{}", s1); println!("s2 = \n{}\n", s2); } ``` The output is: ``` Split a from Axis(0), at index 1: s1 = [[6, 7, 6, 9, 0, 5, 4, 0, 6, 8, 5, 2]] s2 = [[8, 5, 5, 7, 1, 8, 6, 7, 1, 8, 1, 0]] Split a from Axis(1), at index 4: s1 = [[6, 7, 6, 9], [8, 5, 5, 7]] s2 = [[0, 5, 4, 0, 6, 8, 5, 2], [1, 8, 6, 7, 1, 8, 1, 0]] ``` ## Copies and Views ### View, Ref or Shallow Copy Rust has ownership, so we cannot simply update an element of an array while we have a shared view of it. This brings guarantees & helps having more robust code. ```rust use ndarray::prelude::*; use ndarray::{Array, Axis}; fn main() { let mut a = Array::range(0., 12., 1.).into_shape([3 ,4]).unwrap(); println!("a = \n{}\n", a); { let (s1, s2) = a.view().split_at(Axis(1), 2); // with s as a view sharing the ref of a, we cannot update a here // a.slice_mut(s![1, 1]).fill(1234.); println!("Split a from Axis(0), at index 1:"); println!("s1 = \n{}", s1); println!("s2 = \n{}\n", s2); } // now we can update a again here, as views of s1, s2 are dropped already a.slice_mut(s![1, 1]).fill(1234.); let (s1, s2) = a.view().split_at(Axis(1), 2); println!("Split a from Axis(0), at index 1:"); println!("s1 = \n{}", s1); println!("s2 = \n{}\n", s2); } ``` The output is: ``` a = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]] Split a from Axis(0), at index 1: s1 = [[0, 1], [4, 5], [8, 9]] s2 = [[2, 3], [6, 7], [10, 11]] Split a from Axis(0), at index 1: s1 = [[0, 1], [4, 1234], [8, 9]] s2 = [[2, 3], [6, 7], [10, 11]] ``` ### Deep Copy As the usual way in Rust, a `clone()` call will make a copy of your array: ```rust use ndarray::prelude::*; use ndarray::Array; fn main() { let mut a = Array::range(0., 4., 1.).into_shape([2 ,2]).unwrap(); let b = a.clone(); println!("a = \n{}\n", a); println!("b clone of a = \n{}\n", a); a.slice_mut(s![1, 1]).fill(1234.); println!("a updated..."); println!("a = \n{}\n", a); println!("b clone of a = \n{}\n", b); } ``` The output is: ``` a = [[0, 1], [2, 3]] b clone of a = [[0, 1], [2, 3]] a updated... a = [[0, 1], [2, 1234]] b clone of a = [[0, 1], [2, 3]] ``` Notice that using `clone()` (or cloning) an `Array` type also copies the array's elements. It creates an independently owned array of the same type. Cloning an `ArrayView` does not clone or copy the underlying elements - it only clones the view reference (as it happens in Rust when cloning a `&` reference). ## Broadcasting Arrays support limited broadcasting, where arithmetic operations with array operands of different sizes can be carried out by repeating the elements of the smaller dimension array. ```rust use ndarray::prelude::*; fn main() { let a = array![ [1., 1.], [1., 2.], [0., 3.], [0., 4.]]; let b = array![[0., 1.]]; let c = array![ [1., 2.], [1., 3.], [0., 4.], [0., 5.]]; // We can add because the shapes are compatible even if not equal. // The `b` array is shape 1 × 2 but acts like a 4 × 2 array. assert!(c == a + b); } ``` See [.broadcast()](https://docs.rs/ndarray/latest/ndarray/struct.ArrayBase.html#method.broadcast) for a more detailed description. And here is a short example of it: ```rust use ndarray::prelude::*; fn main() { let a = array![ [1., 2.], [3., 4.], ]; let b = a.broadcast((3, 2, 2)).unwrap(); println!("shape of a is {:?}", a.shape()); println!("a is broadcased to 3x2x2 = \n{}", b); } ``` The output is: ``` shape of a is [2, 2] a is broadcased to 3x2x2 = [[[1, 2], [3, 4]], [[1, 2], [3, 4]], [[1, 2], [3, 4]]] ``` ## Want to learn more? Please checkout these docs for more information * [`ArrayBase` doc page](https://docs.rs/ndarray/latest/ndarray/struct.ArrayBase.html) * [`ndarray` for `numpy` user doc page](https://docs.rs/ndarray/latest/ndarray/doc/ndarray_for_numpy_users/index.html)
C
UTF-8
10,018
2.65625
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <time.h> #include <unistd.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/wait.h> #include "reduce.h" enum CLICOMMAND { MAP, REDUCE, EXIT, MARK, WRITE, WAIT, OTHER }; void splitFile(char* input, size_t nClusters); int parseCommand(const char* command); size_t runMappers(char **tableNames, size_t nTables, size_t nProcesses, pid_t* pidPool, size_t pidUsed, const char* processor, int operationId); size_t collectChildren(size_t nProcesses, size_t pidUsed, pid_t *childrenPids, size_t nTables, int operationId, char *output, size_t fromPid); typedef struct { size_t nTables, fromPid; char* outputTable; int operationId; } DelayedOperation; DelayedOperation* delayedOperations; int main(int argc, char** argv) { const int WORDSIZE = 256; char* tables[100]; for (int i = 0; i < 100; i++) tables[i] = malloc(WORDSIZE); char* processor = calloc(WORDSIZE, 1); int delayedQueueSize = 100; delayedOperations = calloc(sizeof(DelayedOperation) * delayedQueueSize, 1); size_t nDelayedOperation = 0; system("ls"); srand((unsigned int) time(0)); size_t nProcesses = 4; if (argc > 1) { int nProcessesArgument = atoi(argv[1]); assert(nProcessesArgument > 0); nProcesses = (size_t) nProcessesArgument; } size_t nClusters = nProcesses; fprintf(stderr, "\nnProcesses: %zu \n", nProcesses); char *line = 0; size_t lineLength = 0; char command[WORDSIZE] = ""; pid_t childrenPids[1000] = {}; size_t pidUsed = 0; while (printf("1-day-till-deadline> "), getline(&line, &lineLength, stdin) >= 0) { char *nextToken = strtok(line, " \t\r\n"); if (nextToken) strcpy(command, nextToken); else continue; int currentCommand = parseCommand(command); if (MAP == currentCommand || REDUCE == currentCommand) { if ((nextToken = strtok(NULL, " \t\r\n"))) { strcpy(processor, nextToken); } else { fprintf(stderr, "No processor found!\n"); continue; } size_t nTables = 0; while ((nextToken = strtok(NULL, " \t\r\n"))) strcpy(tables[nTables++], nextToken); if (!nTables) { fprintf(stderr, "No output file specified\n"); continue; } int asynchronous = 0; if (0 == strcmp(tables[nTables - 1], "&")) { asynchronous = 1; nTables--; } --nTables; char output[WORDSIZE]; strcpy(output, tables[nTables]); int operationId = rand(); size_t fromPid = pidUsed; if (REDUCE == currentCommand) pidUsed = runReducers(tables, nTables, nProcesses, childrenPids, pidUsed, processor, operationId); else pidUsed = runMappers(tables, nTables, nProcesses, childrenPids, pidUsed, processor, operationId); if (!asynchronous) { pidUsed = collectChildren(nProcesses, pidUsed, childrenPids, nTables, operationId, output, fromPid); } else { if (nDelayedOperation + 1 < delayedQueueSize) { printf("Operation %zu in background\n", nDelayedOperation); delayedOperations[nDelayedOperation].fromPid = fromPid; delayedOperations[nDelayedOperation].nTables = nTables; delayedOperations[nDelayedOperation].operationId = operationId; delayedOperations[nDelayedOperation].outputTable = strdup(output); nDelayedOperation++; } else { fprintf(stderr, "Can not run in background\n"); pidUsed = collectChildren(nProcesses, pidUsed, childrenPids, nTables, operationId, output, fromPid); } } } else if (EXIT == currentCommand) { break; } else if (MARK == currentCommand) { char input[1000] = ""; if ((nextToken = strtok(NULL, " \t\r\n"))) { strcpy(input, nextToken); } else { fprintf(stderr, "No filename given\n"); continue; } splitFile(input, nClusters); } else if (WAIT == currentCommand) { while (nDelayedOperation) { nDelayedOperation--; pidUsed = collectChildren(nProcesses, pidUsed, childrenPids, delayedOperations[nDelayedOperation].nTables, delayedOperations[nDelayedOperation].operationId, delayedOperations[nDelayedOperation].outputTable, delayedOperations[nDelayedOperation].fromPid); free(delayedOperations[nDelayedOperation].outputTable); } } else { printf("Only \"map\" and \"reduce\" commands available\n"); continue; } } free(delayedOperations); free(processor); for (int i = 0; i < 100; i++) free(tables[i]); free(line); return 0; } void splitFile(char* input, size_t nClusters) { strcat(input, ".tbl"); FILE* inputFile = fopen(input, "r"); if (!input) { fprintf(stderr, "Can not open file %s\n", input); return; } fseek(inputFile, 0, SEEK_END); size_t fileLength = (size_t) ftell(inputFile); char* fileAddr = (char*) mmap(0, fileLength, PROT_READ, MAP_SHARED, fileno(inputFile), 0); size_t labels[nClusters + 1]; memset(labels, 0, (nClusters + 1) * sizeof(labels[0])); size_t currCluster = 0; for (size_t k = 0, i = (fileLength / nClusters) * 0.9; k < nClusters - 1; k++) { for (size_t j = 0; i < fileLength && j < (fileLength / nClusters + 1); i++, j++) { if (fileAddr[i] == '\n') { labels[currCluster++] = i; i += 2 + fileLength / nClusters - j; // есть ли тут ошибка на один? Да наверняка break; } } } labels[currCluster++] = fileLength; // nClusters = currCluster; тут (мб) надо делать меньше блоков, если нужно. сейчас делаются нулевые. munmap(fileAddr, fileLength); fclose(inputFile); for (ssize_t i = 0, prevOffset = -1; i < (ssize_t) nClusters; prevOffset = (int64_t) labels[i], i++) { char cmd[1000] = ""; snprintf(cmd, sizeof(cmd) - 1, "dd bs=1 if=%s skip=%zi count=%zu of=marked_%s_%zi", input, prevOffset + 1, (ssize_t) labels[i] - prevOffset, input, i); system(cmd); } } int parseCommand(const char* command) { int currentCommand = OTHER; if (strcmp(command, "map") == 0) currentCommand = MAP; else if (strcmp(command, "reduce") == 0) currentCommand = REDUCE; else if (strcmp(command, "exit") == 0) currentCommand = EXIT; else if (strcmp(command, "mark") == 0) currentCommand = MARK; else if (strcmp(command, "wait") == 0) currentCommand = WAIT; else if (strcmp(command, "write") == 0) currentCommand = WRITE; return currentCommand; } size_t runMappers(char **tableNames, size_t nTables, size_t nProcesses, pid_t* pidPool, size_t pidUsed, const char* processor, int operationId) { char cmd[1000]; for (size_t currTable = 0, outputTableIdx = 0; currTable < nTables; currTable++) { for (size_t i = 0; i < nProcesses; i++, outputTableIdx++, pidUsed++) { pidPool[pidUsed] = fork(); if (0 == pidPool[pidUsed]) { snprintf(cmd, sizeof(cmd) - 1, "%s < marked_%s.tbl_%zu > temp_%i_%zu", processor, tableNames[currTable], i, operationId, outputTableIdx); execlp("bash", "bash", "-c", cmd, (char*)(NULL)); return 0; } } } return pidUsed; } size_t collectChildren(size_t nProcesses, size_t pidUsed, pid_t* childrenPids, size_t nTables, int operationId, char* output, size_t fromPid) { int status = 0; for (size_t i = fromPid; i < fromPid + nTables * nProcesses; i++) { waitpid(childrenPids[i], &status, 0); childrenPids[i] = 0; } if (fromPid + nTables * nProcesses == pidUsed) { pidUsed = fromPid; while (pidUsed > 0 && !childrenPids[pidUsed]) pidUsed--; } for (size_t i = 0; i < nProcesses; i++) { char cmd[1000] = "cat "; int from = (int) strlen(cmd); for (size_t j = 0; j < nTables; j++) { from += snprintf(cmd + from, sizeof(cmd) - 1, "temp_%i_%zu ", operationId, i + nProcesses*j); assert((size_t)from < sizeof(cmd)); } snprintf(cmd + from, sizeof(cmd) - 1, "> marked_%s.tbl_%zu", output, i); system(cmd); } char cmd[1000] = ""; snprintf(cmd, sizeof(cmd) - 1, "bash -c \"rm temp_%i_{0..%zu}\"", operationId, nProcesses * nTables - 1); system(cmd); return pidUsed; }
Python
UTF-8
4,846
2.65625
3
[]
no_license
import assembler import ksb_compiler class Compiler: def __init__(self, canvas, input, input_ksb): self.input = input self.input_ksb = input_ksb self.canvas = canvas self.commands = ["<ue1>", "<ue2>","<a>", "<titel>", "<ul>", "<gl>", "<tabelle>"] def scan(self): #seperate tags from value self.tags = [] self.values = [] self.posValues = [[]] #where a value starts and ends self.elements = [[]] #tags + values self.UL_values = [] # all of the values of all ULs self.OL_values = [] # all of the values of all OLs self.TAB_values = [] # all of the values of all tables iter = 0 self.x_scan_index=0 while self.x_scan_index < len(self.input): cnt = 0 # get mulitdimentional tags if self.input[self.x_scan_index:self.x_scan_index+4] == "<ul>": self.scan_multidim_elements("<ul>", "</ul>") elif self.input[self.x_scan_index:self.x_scan_index+4] == "<gl>": self.scan_multidim_elements("<gl>", "</gl>") elif self.input[self.x_scan_index:self.x_scan_index+9] == "<tabelle>": self.scan_multidim_elements("<tabelle>", "</tabelle>") #get normal tags elif self.input[self.x_scan_index] == '<': strTag = "" while self.input[self.x_scan_index+cnt-1] != '>': strTag+=self.input[self.x_scan_index+cnt] cnt+=1 self.tags.append(strTag) self.posValues.insert(iter, [self.x_scan_index, self.x_scan_index+cnt]) iter+=1 self.x_scan_index+=1 self.x_scan_index=0 print(self.tags) for x in range(len(self.posValues)-2): bor1 = self.posValues[x][1] bor2 = self.posValues[x+1][0] # get the end of the last and the beginning of the next if self.input[bor1:bor2] != "\n": self.values.append(self.input[bor1:bor2]) index=0 temp_ul_count = 0 #count of the values assigned to element of ul temp_ol_count = 0 #count of the values assigned to element of ol # division to body and head for x in range(len(self.tags)-1): for y in range(len(self.commands)): if self.tags[x] == self.commands[y]: if self.tags[x] == "<ul>": self.elements.insert(index, [self.tags[x], self.UL_values[temp_ul_count]]) temp_ul_count+=1 index+=1 elif self.tags[x] == "<gl>": self.elements.insert(index, [self.tags[x], self.OL_values[temp_ol_count]]) temp_ol_count+=1 index+=1 else: self.elements.insert(index, [self.tags[x], self.values[index]]) index+=1 # precheck if code is valid and run if len(self.tags) <=2: self.check_code() elif self.tags[0]!= "<!DOCTYPE htas>" or self.tags[1] != "<htas>" or self.tags[len(self.tags)-2] != "</koerper>" or self.tags[len(self.tags)-1] != "</htas>" or not "<koerper>" in self.tags: self.check_code() elif "<titel>" in self.tags: if "</kopf>" in self.tags and "<kopf>" in self.tags: if "<anknuepfen bez='Stilbogen' typ='text/ksb' hbez='index.ksb'>" in self.tags: htas = ksb_compiler.Compiler(self.canvas, self.input_ksb) assembler.Assembler(self.canvas, self.elements, htas.changes) else: assembler.Assembler(self.canvas, self.elements, self.input_ksb) else: self.check_code() else: assembler.Assembler(self.canvas, self.elements, self.input_ksb) def check_code(self): self.canvas.create_text(250, 350, text="!Überprüfe deine Kodierung!", font=(50), fill="#ff0000") def scan_multidim_elements(self, element, close_element): # to clean up the input temp = "" temptemp = "" k=0 temp_k=0 self.tags.append(element) while self.input[self.x_scan_index+k:self.x_scan_index+k+len(close_element)] != close_element: temp+=self.input[self.x_scan_index+k] k+=1 while temp_k < len(temp): temptemp+=temp[temp_k] temp_k+=1 temp = temptemp self.x_scan_index+=k if element == "<ul>": self.UL_values.append(temp) elif element == "<gl>": self.OL_values.append(temp) elif element == "<tabelle>": self.TAB_values.append(temp)
Python
UTF-8
1,111
4.125
4
[]
no_license
#when a variable is declared above a function , it become global variable. these variable are available to all the function which are written after it. the scope of global variable is the entire program body written below it. a=50 def show(): x=10 print(x) print(a) show() print("global variable:",a) #------------------------------------------------------------------------if global variable and local variable name are same,and we do not writw local variable , then it will generate error,ofr eg:- # i=0 # def myfun(): # i=i+1#here the second i which is in expression , should be a defined local variable # print(f"my function{i}") # myfun() #------------------------------------------------------------------------ # j=9 # def new(): # j=7 # j=j+1#here it is using local variable, be we supposed it that it would use global variable # print(j) # new() #------------------------------------------------------------------------ # so, to overcome this problem we use global keyword! #---------------------------------END------------------------------------
C#
UTF-8
1,137
2.671875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using Meow.Core.Entity; using MeowWorld.Core.DomainService; using Microsoft.EntityFrameworkCore; namespace MeowWorld.Infrastructure.data.Repositories { public class TodoItemRepo :IRepository<TodoItem> { private readonly MEOWcontext db; public TodoItemRepo(MEOWcontext context) { db = context; } public IEnumerable<TodoItem> GetAll() { return db.TodoItems.ToList(); } public TodoItem Get(long id) { return db.TodoItems.FirstOrDefault(b => b.Id == id); } public void Add(TodoItem entity) { db.TodoItems.Add(entity); db.SaveChanges(); } public void Edit(TodoItem entity) { db.Entry(entity).State = EntityState.Modified; db.SaveChanges(); } public void Remove(long id) { var item = db.TodoItems.FirstOrDefault(b => b.Id == id); db.TodoItems.Remove(item); db.SaveChanges(); } } }
C++
UTF-8
2,644
3.25
3
[]
no_license
#include <SDL/SDL.h> #include "boat.hpp" using namespace std; bool Boat::check_collision(pair<int,int> singleWall) { //The sides of the rectangles int leftA, leftB,rightA, rightB,topA, topB,bottomA, bottomB; //Calculate the sides of rect A printf("box(%d,%d)\n", box.x,box.y); leftA = box.x; rightA = box.x + box.w; topA = box.y; bottomA = box.y + box.h; // printf("leftA=%d\nrightA=%d\ntopA=%d\nbottomA=%d\n",leftA,rightA,topA,bottomA); leftB = singleWall.first; rightB = singleWall.first + SQUARE; topB = singleWall.second; bottomB = singleWall.second + SQUARE; //Calculate the sides of rect B if( bottomA <= topB ){ return false; } if( topA >= bottomB ){ return false; } if( rightA <= leftB ){ return false; } if( leftA >= rightB ){ return false; } //If none of the sides from A are outside B return true; } Boat::Boat() { //Inicializando a posição inicial box.x = 0; box.y = 0; //Inicializando a dimensão box.w = BOAT_WIDTH; box.h = BOAT_HEIGHT; //Inicializando a velocidade xVel = 0; yVel = 0; } void Boat::handle_input(SDL_Event event) { //If a key was pressed if( event.type == SDL_KEYDOWN ) { //Adjust the velocity switch( event.key.keysym.sym ) { case SDLK_UP: yVel -= 5; break; case SDLK_DOWN: yVel += 5; break; case SDLK_LEFT: xVel -= 5; break; case SDLK_RIGHT: xVel += 5; break; } } //If a key was released else if( event.type == SDL_KEYUP ) { //Adjust the velocity switch( event.key.keysym.sym ) { case SDLK_UP: yVel += 5; break; case SDLK_DOWN: yVel -= 5; break; case SDLK_LEFT: xVel += 5; break; case SDLK_RIGHT: xVel -= 5; break; } } } void Boat::move(SDL_Surface * image, Maze myMaze) { //Move the square left or right box.x += xVel; for(int i = 0;i<90;i++){ if(check_collision(myMaze.wall[i])) box.x -= xVel; } if( ( box.x < 0 ) || ( box.x + BOAT_WIDTH > SCREEN_WIDTH )) { for(int i = 0;i<90;i++){ if(check_collision(myMaze.wall[i])) box.x -= xVel; } //Move back box.x -= xVel; } //Move the square up or down box.y += yVel; //If the square went too far up or down or has collided with the wall if( ( box.y < 0 ) || ( box.y + BOAT_HEIGHT > SCREEN_HEIGHT ) ) { //Move back box.y -= yVel; } for(int i = 0;i<90;i++){ if(check_collision(myMaze.wall[i])) box.y -= yVel; } } void Boat::show(SDL_Surface * image,SDL_Surface * screen) { SDL_Rect dest; dest.x = box.x; dest.y = box.y; //Mostra o Barco SDL_BlitSurface(image, NULL, screen, &dest); }
Java
UTF-8
601
1.960938
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 ejb.sessions; import ejb.entities.SoTinTon; import java.util.List; import javax.ejb.Local; /** * * @author Winson Mac */ @Local public interface SoTinTonFacadeLocal { void create(SoTinTon soTinTon); void edit(SoTinTon soTinTon); void remove(SoTinTon soTinTon); SoTinTon find(Object id); List<SoTinTon> findAll(); List<SoTinTon> findRange(int[] range); int count(); }
Java
UTF-8
457
2.328125
2
[]
no_license
package com.tir38.android.blastermind.core; import java.util.List; import lombok.Data; import lombok.experimental.Accessors; @Data @Accessors(prefix = "m") public class Guess { private final List<Logic.TYPE> mTypes; public Guess(List<Logic.TYPE> types) { if (types.size() != Logic.guessWidth) { throw new IllegalArgumentException("types must be of size: " + Logic.guessWidth); } this.mTypes = types; } }
Java
UTF-8
4,374
1.859375
2
[ "Apache-2.0" ]
permissive
package com.zeroq6.blog.operate.web.controller; import com.zeroq6.blog.common.base.BaseController; import com.zeroq6.blog.common.base.BaseResponse; import com.zeroq6.blog.common.domain.CommentDomain; import com.zeroq6.blog.common.domain.PostDomain; import com.zeroq6.blog.common.domain.enums.field.EmPostPostType; import com.zeroq6.blog.operate.service.CommentService; import com.zeroq6.blog.operate.service.PostService; import com.zeroq6.blog.operate.service.captcha.CaptchaService; import com.zeroq6.common.utils.JsonUtils; import com.zeroq6.common.utils.MyWebUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; /** * Created by yuuki asuna on 2017/5/22. */ @Controller @RequestMapping("/comment") public class CommentController extends BaseController { private final String postUri = "/post/show/%s"; private final String guestBookUri = "/guestbook"; @Autowired private PostService postService; @Autowired private CommentService commentService; @Autowired private CaptchaService captchaService; @RequestMapping(value = "/post") public String post(CommentDomain commentDomain, HttpServletRequest request, Model view) { try { String userAgent = request.getHeader("user-agent"); if (StringUtils.isBlank(userAgent)) { return redirect(commentDomain); } String referer = request.getHeader("referer"); if (StringUtils.isBlank(referer)) { return redirect(commentDomain); } if (!lenLessEqualThan(commentDomain.getUsername(), 32) || !lenLessEqualThan(commentDomain.getEmail(), 32) || !lenLessEqualThan(commentDomain.getUrl(), 100) || !lenLessEqualThan(commentDomain.getContent(), 1000)) { return redirect(commentDomain); } boolean captchaSuccess = captchaService.validate(String.valueOf(commentDomain.get("captchaKey")), String.valueOf(commentDomain.get("captchaValue"))); if (!captchaSuccess) { return redirect(commentDomain); } // ip UA commentDomain.setIp(MyWebUtils.getClientIp(request)); commentDomain.setUserAgent(userAgent); // trim commentDomain.setUsername(StringUtils.trim(commentDomain.getUsername())); commentDomain.setEmail(StringUtils.trim(commentDomain.getEmail())); commentDomain.setUrl(StringUtils.trim(commentDomain.getUrl())); commentDomain.setContent(StringUtils.trim(commentDomain.getContent())); // BaseResponse<String> result = commentService.post(commentDomain); if (result.isSuccess()) { return redirect(commentDomain) + "#c" + commentDomain.getId(); } } catch (Exception e) { logger.error("发表评论异常: " + JsonUtils.toJSONString(commentDomain), e); } return redirect(commentDomain); } private boolean lenLessEqualThan(String string, int len) { return StringUtils.isNotBlank(string) && string.length() <= len; } private String redirect(CommentDomain commentDomain) { try { if (null == commentDomain || null == commentDomain.getPostId()) { return redirectIndex(); } PostDomain postDomain = postService.selectOne(new PostDomain().setId(commentDomain.getPostId()), true); if (null == postDomain) { return redirectIndex(); } if (postDomain.getPostType() == EmPostPostType.WENZHANG.value()) { return "redirect:" + String.format(postUri, postDomain.getId() + ""); } else if (postDomain.getPostType() == EmPostPostType.LIUYAN.value()) { return "redirect:" + guestBookUri; } else { return redirectIndex(); } } catch (Exception e) { logger.error("获取评论后重定向页面异常", e); return redirectIndex(); } } }
Java
UTF-8
1,070
3.8125
4
[]
no_license
package q6; import java.util.InputMismatchException; import java.util.Scanner; class InputException extends RuntimeException{ public InputException(int max) { super("Number can't be greater than " + max); } } public class CustomInputException { public static void main(String[] args) { try (Scanner sc = new Scanner(System.in)) { System.out.println("Enter max value of integer that can be taken: "); int max_val = sc.nextInt(); while(true) { try { System.out.println("Please enter a number or enter '-1' to quit the program"); int number = sc.nextInt(); if(number==-1) break; else if(number>100) throw new InputException(max_val); else if(number%2 != 0) System.out.println("You have entered an odd number"); else System.out.println("You have entered an even number"); } catch (InputMismatchException e) { System.out.println("You must enter an Integer"); sc.next(); } catch (Exception e) { System.out.println(e.getMessage()); } } } } }
Java
UTF-8
2,541
2.96875
3
[]
no_license
package cecs327.events; import cecs327.CustomFile; import cecs327.utils.DataReader; import cecs327.utils.DataWriter; import java.io.File; import java.io.IOException; public class RemoveFileEvent implements Event{ private int type; private String filePath; private String removedFileName; public byte[] createRemoveFileEventData(String fileDirPath, String fileName) throws IOException { this.type = EventType.REMOVE_FILE; this.filePath = fileDirPath; this.removedFileName = fileName; return packData(); } @Override public void unpackData(byte[] data) throws IOException { DataReader dr = new DataReader(data); // 1. Read the event type this.type = dr.readInt(); System.out.println("-------------------------------------------"); System.out.println("Event Type: " + type); // 2. Read the UUID of the file's owner int pathLen = dr.readInt(); byte[] removedFilePathBytes = new byte[pathLen]; dr.readFully(removedFilePathBytes); this.filePath = new String(removedFilePathBytes).replace("\\", "/"); // 3. Read the removed file name int fileNameLen = dr.readInt(); byte[] removedFileBytes = new byte[fileNameLen]; dr.readFully(removedFileBytes); this.removedFileName = new String(removedFileBytes); dr.close(); File removedFile = new File(filePath, removedFileName); removedFile.delete(); System.out.println("Remove the file " + removedFileName); } @Override public byte[] packData() throws IOException { byte[] data = null; DataWriter dw = new DataWriter(); // 1. Write the event type dw.writeInt(type); // 2. Write the path of the removed file byte[] filePathBytes = filePath.getBytes(); int pathLen = filePathBytes.length; dw.writeInt(pathLen); dw.write(filePathBytes); // 3. Write the removed file name byte[] removedFileNameBytes = removedFileName.getBytes(); int fileNameLen = removedFileNameBytes.length; dw.writeInt(fileNameLen); dw.write(removedFileNameBytes); dw.flush(); data = dw.toByteArray(); dw.close(); return data; } @Override public int getEventType() { return type; } @Override public String getNodeIP() { return null; } @Override public String getNodeUUID() { return null; } }
SQL
UTF-8
4,524
2.625
3
[]
no_license
insert into temperatures (geom, start_date, end_date, temperature) with dates as ( select min(i) as start_date, max(i) as end_date from generate_series('2018-01-01'::timestamp, '2018-02-01'::timestamp, '1 day'::interval) as i where i < '2018-02-01'::timestamp ) select geom, start_date, end_date, elev from dates cross join "wc2.0_30s_tavg_01.tif.translated.tif"; insert into temperatures (geom, start_date, end_date, temperature) with dates as ( select min(i) as start_date, max(i) as end_date from generate_series('2018-02-01'::timestamp, '2018-03-01'::timestamp, '1 day'::interval) as i where i < '2018-03-01'::timestamp ) select geom, start_date, end_date, elev from dates cross join "wc2.0_30s_tavg_02.tif.translated.tif"; insert into temperatures (geom, start_date, end_date, temperature) with dates as ( select min(i) as start_date, max(i) as end_date from generate_series('2018-03-01'::timestamp, '2018-04-01'::timestamp, '1 day'::interval) as i where i < '2018-04-01'::timestamp ) select geom, start_date, end_date, elev from dates cross join "wc2.0_30s_tavg_03.tif.translated.tif"; insert into temperatures (geom, start_date, end_date, temperature) with dates as ( select min(i) as start_date, max(i) as end_date from generate_series('2018-04-01'::timestamp, '2018-05-01'::timestamp, '1 day'::interval) as i where i < '2018-05-01'::timestamp ) select geom, start_date, end_date, elev from dates cross join "wc2.0_30s_tavg_04.tif.translated.tif"; insert into temperatures (geom, start_date, end_date, temperature) with dates as ( select min(i) as start_date, max(i) as end_date from generate_series('2018-05-01'::timestamp, '2018-06-01'::timestamp, '1 day'::interval) as i where i < '2018-06-01'::timestamp ) select geom, start_date, end_date, elev from dates cross join "wc2.0_30s_tavg_05.tif.translated.tif"; insert into temperatures (geom, start_date, end_date, temperature) with dates as ( select min(i) as start_date, max(i) as end_date from generate_series('2018-06-01'::timestamp, '2018-07-01'::timestamp, '1 day'::interval) as i where i < '2018-07-01'::timestamp ) select geom, start_date, end_date, elev from dates cross join "wc2.0_30s_tavg_06.tif.translated.tif"; insert into temperatures (geom, start_date, end_date, temperature) with dates as ( select min(i) as start_date, max(i) as end_date from generate_series('2018-07-01'::timestamp, '2018-08-01'::timestamp, '1 day'::interval) as i where i < '2018-08-01'::timestamp ) select geom, start_date, end_date, elev from dates cross join "wc2.0_30s_tavg_07.tif.translated.tif"; insert into temperatures (geom, start_date, end_date, temperature) with dates as ( select min(i) as start_date, max(i) as end_date from generate_series('2018-08-01'::timestamp, '2018-09-01'::timestamp, '1 day'::interval) as i where i < '2018-09-01'::timestamp ) select geom, start_date, end_date, elev from dates cross join "wc2.0_30s_tavg_08.tif.translated.tif"; insert into temperatures (geom, start_date, end_date, temperature) with dates as ( select min(i) as start_date, max(i) as end_date from generate_series('2018-09-01'::timestamp, '2018-10-01'::timestamp, '1 day'::interval) as i where i < '2018-10-01'::timestamp ) select geom, start_date, end_date, elev from dates cross join "wc2.0_30s_tavg_09.tif.translated.tif"; insert into temperatures (geom, start_date, end_date, temperature) with dates as ( select min(i) as start_date, max(i) as end_date from generate_series('2018-10-01'::timestamp, '2018-11-01'::timestamp, '1 day'::interval) as i where i < '2018-11-01'::timestamp ) select geom, start_date, end_date, elev from dates cross join "wc2.0_30s_tavg_10.tif.translated.tif"; insert into temperatures (geom, start_date, end_date, temperature) with dates as ( select min(i) as start_date, max(i) as end_date from generate_series('2018-11-01'::timestamp, '2018-12-01'::timestamp, '1 day'::interval) as i where i < '2018-12-01'::timestamp ) select geom, start_date, end_date, elev from dates cross join "wc2.0_30s_tavg_11.tif.translated.tif"; insert into temperatures (geom, start_date, end_date, temperature) with dates as ( select min(i) as start_date, max(i) as end_date from generate_series('2018-12-01'::timestamp, '2019-01-01'::timestamp, '1 day'::interval) as i where i < '2019-01-01'::timestamp ) select geom, start_date, end_date, elev from dates cross join "wc2.0_30s_tavg_12.tif.translated.tif";;
SQL
UTF-8
716
3.59375
4
[]
no_license
-- users table CREATE TABLE users ( users_id SERIAL PRIMARY KEY, name character varying(100), bio character varying(500), auth_id text, home_town character varying(100), img text, email character varying(200) ); -- events table CREATE TABLE events ( events_id SERIAL PRIMARY KEY, title character varying(100), host character varying(100), date date, time text, description character varying(500), img text, location text, users_id integer REFERENCES users(users_id) ); -- user_events table CREATE TABLE user_events ( id SERIAL PRIMARY KEY, users_id integer REFERENCES users(users_id), events_id integer REFERENCES events(events_id) );
Java
UTF-8
5,148
2.71875
3
[]
no_license
package DroneAutopilot.GUI; import java.awt.EventQueue; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.Color; import java.awt.Dimension; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JProgressBar; import javax.swing.JLabel; import javax.swing.JPanel; public class GUI { private final JProgressBar progressBar; public int maxValue; private JFrame frame; private boolean reached; private MissionType missionType; /** * Create the application. */ public GUI() { this.progressBar = new JProgressBar(); this.maxValue = 0; setMissionType(MissionType.HOVER); initialize(); } /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { GUI window = new GUI(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Initialize the contents of the frame. */ private void initialize() { this.frame = new JFrame(); this.getFrame().setTitle("AUTOPILOT GUI"); this.getFrame().setAlwaysOnTop(true); this.getFrame().setBounds(100, 100, 530, 80); this.getFrame().setMinimumSize(new Dimension(530,80)); this.getFrame().setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Font font = new Font("Tahoma", Font.PLAIN, 18); JPanel panel2 = new JPanel(new FlowLayout(FlowLayout.LEFT)); JPanel panel = new JPanel(new GridLayout(1,2)); JLabel select = new JLabel("Select mission: "); select.setFont(font); panel.add(select); String[] list = { " --- Select Mission --- ", "Fly to position",/*"Fly to multiple positions",*/ "Fly to single target", "Fly to multiple targets", "Scan object",/* "TEST"*/}; JComboBox menu = new JComboBox(list); menu.setPreferredSize(new Dimension(250,30)); panel.add(menu); menu.setFont(font); menu.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JComboBox menu = (JComboBox) e.getSource(); Object selected = menu.getSelectedItem(); if (selected.toString().equals("Fly to single target")){ setMissionType(MissionType.SINGLEOBJECT); }else if(selected.toString().equals("Scan object")) { setMissionType(MissionType.SCANOBJECT); }else if (selected.toString().equals("Fly to multiple targets")){ setMissionType(MissionType.FLYMULTIPLETAR); }else if (selected.toString().equals("TEST")){ setMissionType(MissionType.TEST); }else if (selected.toString().equals("Fly to position")){ setMissionType(MissionType.FLYTOPOSITION); }else if (selected.toString().equals("Fly to multiple positions")){ setMissionType(MissionType.FLYMULTIPLEPOS); }else { setMissionType(MissionType.HOVER); } } }); // JLabel progress = new JLabel("Progress to next sphere: "); // progress.setFont(font); // progress.setPreferredSize(new Dimension(80, 30)); // panel.add(progress); // // this.getProgressBar().setPreferredSize(new Dimension(250, 30)); // this.getProgressBar().setStringPainted(true); // this.getProgressBar().setString("0%"); // this.getProgressBar().setFont(font); // panel.add(this.getProgressBar()); panel2.add(panel); this.getFrame().getContentPane().add(panel2); this.getFrame().setVisible(true); } // public void update(float dist,int colorint) { // int distance = (int) (dist*100); // Color color = new Color(colorint); // if (color.getRGB() != this.getProgressBar().getForeground().getRGB()){ // this.setMaxValue(distance); // this.getProgressBar().setMaximum(distance); // this.setReached(false); // }; // this.getProgressBar().setForeground(color); // if(this.isReached()){ // this.getProgressBar().setString("100%"); // }else{ // if (distance > this.getMaxValue()) { // this.setMaxValue(distance); // this.getProgressBar().setMaximum(distance); // } else { // this.getProgressBar().setValue(this.getMaxValue() - distance); // } // if (this.getMaxValue() > 0){ // this.getProgressBar().setString((Math.round(((this.getMaxValue() - distance)*100) / (float)this.getMaxValue())) + "%"); // if((Math.round(((this.getMaxValue() - distance)*100) / (float)this.getMaxValue()))==100){ // this.setReached(true); // } // } else { // this.getProgressBar().setString("100%"); // this.setReached(true); // } // } // } //////////GETTERS & SETTERS////////// public boolean isReached() { return reached; } public void setReached(boolean reached) { this.reached = reached; } public JProgressBar getProgressBar() { return progressBar; } public int getMaxValue() { return maxValue; } public void setMaxValue(int maxValue) { this.maxValue = maxValue; } public JFrame getFrame() { return frame; } public void setFrame(JFrame frame) { this.frame = frame; } public MissionType getMissionType() { return missionType; } public void setMissionType(MissionType missionType) { this.missionType = missionType; } }
Markdown
UTF-8
8,891
2.71875
3
[ "MIT" ]
permissive
--- title: IoT enabled Jack-O-Lantern Flamethrower permalink: halloween-fire-pumpkin/ date: 2018-11-03 author: Markus description: A flame-throwing Jack-O-Lantern is a real Halloween highlight and definitely something to impress the trick-or-treaters and your neighbors. An internet controlled IoT flame throwing Jack-O-Lantern is even better. images: feature: /images/2018-11-03-halloween-fire-pumpkin/header.jpg category: project tags: - arduino - development - halloween --- ## Jack-O-Lantern Flamethrower A flame-throwing jack-o'-lantern is a real Halloween highlight and definitely something to impress the trick-or-treaters and your neighbors. An internet controlled IoT flame throwing jack-o'-lantern is even better. This Jack-O-Lantern is internet connected and can be controlled via MQTT protocol. That way the project can be integrated into a home automation solution like [OpenHab](https://www.openhab.org) or [Home Assistant](https://www.home-assistant.io) to control the flamethrower from there or via Alexa or Google Home. https://www.youtube.com/watch?v=jMbAKtgw04k You are "not so much" interested in Halloween? This is for you as well, a little fire will make even the most bold of people think twice about approaching your door. This is actually my second version of the flame-throwing jack-o'-lantern 😀 I already build one last year using a modified room spray (like [this project](https://www.hackster.io/Dlbates/iot-flaming-and-talking-pumpkin-using-aws-and-esp8266-49934f)). But these do not allow to control the flame directly so I decided I need to build a more pro version which allows controlling the duration of the flame. **Warning**: This pumpkin and playing with fire is extremely dangerous and you definitely should not make one of these. I do not endorse the manufacture or use of flamethrowers jack-o'-lanterns. The following project description is posted here are for research and entertainment purposes only. If you are going to rebuild this project you do it at your own risks. Read the warning above - twice! Also, make sure the place the pumpkin at a safe location to not harm anybody or burn down your own house! ### Hardware The following components are needed: - A big pumpkin - Penetrating fluid like WD-40 or cheaper replacement, it's just going to be burned anyway - A tea candle - Material for the flamethrower construction to hold the spray can - ESP8266 (Wemos D1 mini, Nodemcu) or ESP32 - 1-3 PIR motion sensors - Strong servo motor - SSD1306 display (optional) - Prototyping board - male & female pin headers - USB cable and power supply The display is not really needed for this project, it is just used for fun to display some little animation and information which of the motion sensors triggered the fire. As usual, I got the most parts from [Aliexpress](https://www.aliexpress.com) but all the parts should be available via other sources like ebay or amazon.com as well. ### Tools These are the tools needed: - A cutting knife - A marker - Soldering iron with solder - Tools to construct the flame-throwing mechanism ## The flamethrower Ok, again: only build this if you have read the warning and are sure what you are doing! The key element of this project is burning penetrating fluid which if sprayed directly into a candle burns like a small flamethrower. There are multiple ways to build the flamethrower. I used old wood pieces covered with aluminum foil to mount the spray can and candle. Maybe not the optimal solution but working, using metal parts would be a slightly better way. ![flamethrower mechanism](/assets/images/2018-11-03-halloween-fire-pumpkin/fire-1.jpg) Bend the thick wire like on the picture above. It should be a big lever as possible to make the most of the power of the servo motor. Hot glue or screw down the servo at the side of the construction and mount it with the wire. The lever will press down the spray nozzle when the servo is activated. ## The pumpkin The pumpkin is, of course, the most important part for a project like this 😉 First cut around the stem of the pumpkin at an angle. The top cover should be big enough, so you can later easily mount the flame thrower construction. After done cutting all the way around, remove the stem and the guts from the pumpkin. Depending on the size of the project you also need to cut out the bottom to fit in the flamethrower construction. If you have a very large pumpkin this might not be needed. Use the marker to mark jack-o'-lanterns face. The mouth should be at the position of the spray nozzle, so that the flame can flow out well. Make sure it is big enough so that there is no setback of the flame. I the pumpkin is not big enough the flame can also be fired through a bigger nose hole. Cut the face as marked. Place the flamethrower construction inside the pumpkin. Fix it with hot glue to stabilize it. Connect the electronics with the servo motor wires. If enough space the electronics can be placed inside the pumpkin and the PIR sensors can be inside jack-o'-lanterns eyes. Make sure you have a sufficient distance between the electronic parts and the flame. ![pumpkin](/assets/images/2018-11-03-halloween-fire-pumpkin/fire-2.jpg) If you have a smaller pumpkin, with not enough space inside the electronics can also be placed outside. I prefer this setup because it makes you more flexible when placing the PIR motion sensors. The PIR motions sensors got some protection cover and habe been places to recognize the movement of approaching trick-or-treaters. ![pumpkin](/assets/images/2018-11-03-halloween-fire-pumpkin/fire-4.jpg) ## The electronics The PIR motion sensors and the servo must be connected to the Wemos / ESP8266 board, you can use any of the Dx pins, expect D0 & D1. These two will be used by the OLED display. Connect power via USB adapter or battery pack. ![Fritzing Diagram](/assets/images/2018-11-03-halloween-fire-pumpkin/fritzing.png) ## The software The software project for the ESP8288 board can be found in my [GitHub](https://github.com/mhaack/halloween-pumpkin-fire) repository. <github-badge repo="mhaack/halloween-pumpkin-fire"></github-badge> After uploading the software to the board it has to be configured to connect to WiFi and MQTT. Homie provides multiple ways to do this, I prefer to create and upload a config file. Alternatively, the configuration UI can be used. My test setup looked like this: ![pumpkin](/assets/images/2018-11-03-halloween-fire-pumpkin/fire-3.jpg) The code is written in C++, `halloween.cpp` is the main class. The following software libraries are used. If using PlatformIO all dependencies are resolved automatically. - [Homie V2](https://github.com/marvinroger/homie-esp8266) including dependencies - [SSD1306 driver for ESP8266 platform](https://github.com/squix78/esp8266-oled-ssd1306) - [NTPClient to connect to a time server](https://github.com/arduino-libraries/NTPClient) - Optionally PlatformIO environment for building the code ## The IoT part I used [Homie](https://github.com/marvinroger/homie-esp8266) to better modularize the software parts into dedicated "nodes" to control the servo, the display and get the PIR motion sensor inputs. Homie provides the MQTT protocol support, see [Homie specification](https://git.io/homieiot) for details. ### MQTT commands and config The flamethrower supports one import command: switch on the fire 😀. It can be triggered via MQTT with `homie/<device id>/fire/on/set` with the value `true`. Command line example: ```bash mosquitto_pub -h <mqtt broker host> -t homie/<device id>/fire/on/set -m true ``` Where &lt;devie id&gt; is the name of the device assigned during configuration and &lt;mqtt broker host&gt; the hostname or ip address of your MQTT broker. This should make it easy to integrate it into home automation solution. I run OpenHab and integrated it there, just for the fun of controlling the fire via my mobile. ![Openhab](/assets/images/2018-11-03-halloween-fire-pumpkin/openhab.jpg) The following config parameters are available via config file or MQTT message (see Homie documentation how to use): | Parameter | Type | Usage | | ------------ | ---- | ----------------------------------------------------------------------------------------------- | | fireInterval | long | min. interval in sec between flame activations (if motion was detected) to avoid permanent fire | | fireDuration | long | duration of one flame shot in ms aka. time until servo moves back to initial position | | flipScreen | bool | flip the display screen vertically | ## The final result This is the Jack-O-Lantern on fire. ![Jack-O-Lantern](/assets/images/2018-11-03-halloween-fire-pumpkin/pumpkin-fire.jpg)
Java
UTF-8
51,467
1.710938
2
[]
no_license
package com.rc.buyermarket.activity; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.rc.buyermarket.R; import com.rc.buyermarket.adapter.CommonSpinnerAdapter; import com.rc.buyermarket.base.BaseActivity; import com.rc.buyermarket.enumeration.PropertyEnum; import com.rc.buyermarket.model.AddProperty; import com.rc.buyermarket.model.Bathroom; import com.rc.buyermarket.model.Bedroom; import com.rc.buyermarket.model.Country; import com.rc.buyermarket.model.Exterior; import com.rc.buyermarket.model.ParamsAddProperty; import com.rc.buyermarket.model.PropertyType; import com.rc.buyermarket.model.PurchaseType; import com.rc.buyermarket.model.SPModel; import com.rc.buyermarket.model.SessionBathroomList; import com.rc.buyermarket.model.SessionBedroomList; import com.rc.buyermarket.model.SessionCountryWithAreaList; import com.rc.buyermarket.model.SessionExteriorList; import com.rc.buyermarket.model.SessionPropertyTypeList; import com.rc.buyermarket.model.SessionPurchaseTypeList; import com.rc.buyermarket.model.SessionStyleList; import com.rc.buyermarket.model.States; import com.rc.buyermarket.model.Styles; import com.rc.buyermarket.network.NetworkManager; import com.rc.buyermarket.retrofit.APIClient; import com.rc.buyermarket.retrofit.APIInterface; import com.rc.buyermarket.retrofit.APIResponse; import com.rc.buyermarket.util.AllConstants; import com.rc.buyermarket.util.AppPref; import com.rc.buyermarket.util.AppUtil; import com.rc.buyermarket.util.DataUtil; import com.rc.buyermarket.view.CanaroTextView; import java.util.List; import retrofit2.Call; import retrofit2.Response; import static com.rc.buyermarket.util.AllConstants.INTENT_KEY_PROPERTY; import static com.rc.buyermarket.util.AllConstants.INTENT_KEY_PROPERTY_ENUM; public class ActivityAddProperty extends BaseActivity { //Toolbar private ImageView ivBack; private CanaroTextView tvTitle; private TextView txtPriceValue; private Spinner spPurchaseType, spPreapproved, spBuyPropertyType, spCountry, spState, spBuyBedrooms, spBuyBathroom, spBuyBasement, spBuyGarage, spBuyStyle, spBuyExterior; private EditText etFname, etLname, etEmail, etPhone, etCreditScore, etCity, etZipcode; private Button btnSubmit; private String preApproveType = "", purchaseType = "", bedroomType = "", bathroomType = "", basementType = "", garageType = "", propertyType = "", styleType = "", exteriorType = "", countryName = "", stateName = ""; private SeekBar seekBarPrice; private int priceMinimum = 10000; private int priceMaximum = 10000000; private CommonSpinnerAdapter preApprovedAdapter, purchaseTypeAdapter, bedroomAdapter, bathroomAdapter, basementAdapter, garageAdapter, countryTypeAdapter, stateTypeAdapter, propertyTypeAdapter, styleAdapter, exteriorAdapter; private APIInterface apiInterface; //Background task private GetCountryWithCityTask getCountryWithCityTask; private GetPropertyTypeTask getPropertyTypeTask; private GetExteriorTask getExteriorTask; private GetStyleTask getStyleTask; private GetAddPropertyTask getAddPropertyTask; private GetBathroomTask getBathroomTask; private GetBedroomTask getBedroomTask; private GetPurchaseTypeTask getPurchaseTypeTask; private AddProperty addPropertyEditData; private PropertyEnum propertyEnum; @Override public String initActivityTag() { return ActivityAddProperty.class.getSimpleName(); } @Override public int initActivityLayout() { return R.layout.activity_add_property; } @Override public void initStatusBarView() { } @Override public void initNavigationBarView() { } @Override public void initIntentData(Bundle savedInstanceState, Intent intent) { if (intent != null) { String propertyType = intent.getStringExtra(INTENT_KEY_PROPERTY_ENUM); if (!AppUtil.isNullOrEmpty(propertyType)) { propertyEnum = PropertyEnum.valueOf(propertyType); Log.d(TAG, TAG + ">>>" + " propertyEnum: " + propertyEnum); } AddProperty addProperty = intent.getParcelableExtra(INTENT_KEY_PROPERTY); if (addProperty != null) { addPropertyEditData = addProperty; Log.d(TAG, TAG + ">>>" + " addProperty: " + APIResponse.getResponseString(addProperty)); } } } @Override public void initActivityViews() { ivBack = (ImageView) findViewById(R.id.iv_back); tvTitle = (CanaroTextView) findViewById(R.id.tv_title); txtPriceValue = (TextView) findViewById(R.id.txt_price_value); etFname = (EditText) findViewById(R.id.et_fname); etLname = (EditText) findViewById(R.id.et_lname); etEmail = (EditText) findViewById(R.id.et_email); etPhone = (EditText) findViewById(R.id.et_phone); etCreditScore = (EditText) findViewById(R.id.et_credit_scroe); etCity = (EditText) findViewById(R.id.et_city); etZipcode = (EditText) findViewById(R.id.et_zipcode); spPurchaseType = (Spinner) findViewById(R.id.sp_purchase_type); spPreapproved = (Spinner) findViewById(R.id.sp_buy_preapproved); seekBarPrice = (SeekBar) findViewById(R.id.seekBar_price); spBuyPropertyType = (Spinner) findViewById(R.id.sp_buy_property_type); spCountry = (Spinner) findViewById(R.id.sp_country); spState = (Spinner) findViewById(R.id.sp_buy_state); spBuyBedrooms = (Spinner) findViewById(R.id.sp_buy_bedrooms); spBuyBathroom = (Spinner) findViewById(R.id.sp_buy_bathroom); spBuyBasement = (Spinner) findViewById(R.id.sp_buy_basement); spBuyGarage = (Spinner) findViewById(R.id.sp_buy_garage); spBuyStyle = (Spinner) findViewById(R.id.sp_buy_style); spBuyExterior = (Spinner) findViewById(R.id.sp_buy_exterior); btnSubmit = (Button) findViewById(R.id.btn_property_submit); } @Override public void initActivityViewsData(Bundle savedInstanceState) { apiInterface = APIClient.getClient(getActivity()).create(APIInterface.class); if (propertyEnum == PropertyEnum.PROPERTY_ADD) { tvTitle.setText(getString(R.string.add_property)); } else { tvTitle.setText(getString(R.string.property_details)); } purchaseTypeAdapter = new CommonSpinnerAdapter(ActivityAddProperty.this, CommonSpinnerAdapter.ADAPTER_TYPE.PURCHASE_TYPE); spPurchaseType.setAdapter(purchaseTypeAdapter); preApprovedAdapter = new CommonSpinnerAdapter(ActivityAddProperty.this, CommonSpinnerAdapter.ADAPTER_TYPE.PRE_APPROVED); spPreapproved.setAdapter(preApprovedAdapter); preApprovedAdapter.setData(DataUtil.getAllPreApproved()); propertyTypeAdapter = new CommonSpinnerAdapter(ActivityAddProperty.this, CommonSpinnerAdapter.ADAPTER_TYPE.PROPERTY_TYPE); spBuyPropertyType.setAdapter(propertyTypeAdapter); countryTypeAdapter = new CommonSpinnerAdapter(ActivityAddProperty.this, CommonSpinnerAdapter.ADAPTER_TYPE.COUNTRY); spCountry.setAdapter(countryTypeAdapter); spCountry.setEnabled(false); stateTypeAdapter = new CommonSpinnerAdapter(ActivityAddProperty.this, CommonSpinnerAdapter.ADAPTER_TYPE.STATE); spState.setAdapter(stateTypeAdapter); bedroomAdapter = new CommonSpinnerAdapter(ActivityAddProperty.this, CommonSpinnerAdapter.ADAPTER_TYPE.BEDROOM); spBuyBedrooms.setAdapter(bedroomAdapter); bathroomAdapter = new CommonSpinnerAdapter(ActivityAddProperty.this, CommonSpinnerAdapter.ADAPTER_TYPE.BATHROOM); spBuyBathroom.setAdapter(bathroomAdapter); basementAdapter = new CommonSpinnerAdapter(ActivityAddProperty.this, CommonSpinnerAdapter.ADAPTER_TYPE.BASEMANT); spBuyBasement.setAdapter(basementAdapter); basementAdapter.setData(DataUtil.getAllBasements()); garageAdapter = new CommonSpinnerAdapter(ActivityAddProperty.this, CommonSpinnerAdapter.ADAPTER_TYPE.GARAGE); spBuyGarage.setAdapter(garageAdapter); garageAdapter.setData(DataUtil.getAllGarages()); styleAdapter = new CommonSpinnerAdapter(ActivityAddProperty.this, CommonSpinnerAdapter.ADAPTER_TYPE.STYLE); spBuyStyle.setAdapter(styleAdapter); exteriorAdapter = new CommonSpinnerAdapter(ActivityAddProperty.this, CommonSpinnerAdapter.ADAPTER_TYPE.EXTERIOR); spBuyExterior.setAdapter(exteriorAdapter); if (NetworkManager.isInternetAvailable(getActivity())) { //Load spinner data getPropertyTypeTask = new GetPropertyTypeTask(getActivity(), apiInterface); getPropertyTypeTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); getStyleTask = new GetStyleTask(getActivity(), apiInterface); getStyleTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); getExteriorTask = new GetExteriorTask(getActivity(), apiInterface); getExteriorTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); getCountryWithCityTask = new GetCountryWithCityTask(getActivity(), apiInterface); getCountryWithCityTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); getBathroomTask = new GetBathroomTask(getActivity(), apiInterface); getBathroomTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); getBedroomTask = new GetBedroomTask(getActivity(), apiInterface); getBedroomTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); getPurchaseTypeTask = new GetPurchaseTypeTask(getActivity(), apiInterface); getPurchaseTypeTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); //Load edit property data if (addPropertyEditData != null) { etFname.setText(addPropertyEditData.getFirst_name()); etLname.setText(addPropertyEditData.getLast_name()); etEmail.setText(addPropertyEditData.getEmail()); etPhone.setText(addPropertyEditData.getContact()); if (AppUtil.isNullOrEmpty(addPropertyEditData.getPrice_min())) { seekBarPrice.setProgress(priceMinimum); txtPriceValue.setText("$" + priceMinimum + " - " + "$" + priceMaximum); } else { seekBarPrice.setProgress(Integer.parseInt(addPropertyEditData.getPrice_min())); txtPriceValue.setText("$" + addPropertyEditData.getPrice_min() + " - " + "$" + addPropertyEditData.getPrice_max()); } // spPurchaseType.setSelection(purchaseTypeAdapter.getItemPosition(addPropertyEditData.getPurchase_type())); spPreapproved.setSelection(preApprovedAdapter.getItemPosition(addPropertyEditData.getPrc_approved())); etCreditScore.setText(addPropertyEditData.getCredit_score()); // spBuyPropertyType.setSelection(propertyTypeAdapter.getItemPosition(addPropertyEditData.getProperty_type())); // spCountry.setSelection(countryTypeAdapter.getItemPosition(addPropertyEditData.getCountry())); // spState.setSelection(stateTypeAdapter.getItemPosition(addPropertyEditData.getState())); etCity.setText(addPropertyEditData.getCity()); etZipcode.setText(addPropertyEditData.getZipcode()); // spBuyBedrooms.setSelection(bedroomAdapter.getItemPosition(addPropertyEditData.getBedroom())); // spBuyBathroom.setSelection(bathroomAdapter.getItemPosition(addPropertyEditData.getBathroom())); spBuyBasement.setSelection(basementAdapter.getItemPosition(addPropertyEditData.getBasement())); spBuyGarage.setSelection(garageAdapter.getItemPosition(addPropertyEditData.getGarage())); // spBuyStyle.setSelection(styleAdapter.getItemPosition(addPropertyEditData.getStyle())); // spBuyExterior.setSelection(exteriorAdapter.getItemPosition(addPropertyEditData.getExterior())); } } else { loadOfflineData(); setPropertyData(); } } private void setPropertyData() { if (addPropertyEditData != null) { etFname.setText(addPropertyEditData.getFirst_name()); etLname.setText(addPropertyEditData.getLast_name()); etEmail.setText(addPropertyEditData.getEmail()); etPhone.setText(addPropertyEditData.getContact()); if (AppUtil.isNullOrEmpty(addPropertyEditData.getPrice_min())) { seekBarPrice.setProgress(priceMinimum); txtPriceValue.setText("$" + priceMinimum + " - " + "$" + priceMaximum); } else { seekBarPrice.setProgress(Integer.parseInt(addPropertyEditData.getPrice_min())); txtPriceValue.setText("$" + addPropertyEditData.getPrice_min() + " - " + "$" + addPropertyEditData.getPrice_max()); } spPurchaseType.setSelection(purchaseTypeAdapter.getItemPosition(addPropertyEditData.getPurchase_type())); spPreapproved.setSelection(preApprovedAdapter.getItemPosition(addPropertyEditData.getPrc_approved())); etCreditScore.setText(addPropertyEditData.getCredit_score()); spBuyPropertyType.setSelection(propertyTypeAdapter.getItemPosition(addPropertyEditData.getProperty_type())); spCountry.setSelection(countryTypeAdapter.getItemPosition(addPropertyEditData.getCountry())); spState.setSelection(stateTypeAdapter.getItemPosition(addPropertyEditData.getState())); etCity.setText(addPropertyEditData.getCity()); etZipcode.setText(addPropertyEditData.getZipcode()); spBuyBedrooms.setSelection(bedroomAdapter.getItemPosition(addPropertyEditData.getBedroom())); spBuyBathroom.setSelection(bathroomAdapter.getItemPosition(addPropertyEditData.getBathroom())); spBuyBasement.setSelection(basementAdapter.getItemPosition(addPropertyEditData.getBasement())); spBuyGarage.setSelection(garageAdapter.getItemPosition(addPropertyEditData.getGarage())); spBuyStyle.setSelection(styleAdapter.getItemPosition(addPropertyEditData.getStyle())); spBuyExterior.setSelection(exteriorAdapter.getItemPosition(addPropertyEditData.getExterior())); } } private void loadOfflineData() { purchaseTypeAdapter.setData(DataUtil.getAllPurchaseTypes(getActivity())); // preApprovedAdapter.setData(DataUtil.getAllPreApproved()); propertyTypeAdapter.setData(DataUtil.getAllPropertyTypes(getActivity())); countryTypeAdapter.setData(DataUtil.getAllCountryWithStates(getActivity())); stateTypeAdapter.setData(DataUtil.getAllCountryWithStates(getActivity()).get(0).getStates()); bedroomAdapter.setData(DataUtil.getAllBedrooms(getActivity())); bathroomAdapter.setData(DataUtil.getAllBathrooms(getActivity())); // basementAdapter.setData(DataUtil.getAllBasements()); // garageAdapter.setData(DataUtil.getAllGarages()); styleAdapter.setData(DataUtil.getAllStyles(getActivity())); exteriorAdapter.setData(DataUtil.getAllExteriors(getActivity())); } @Override public void initActivityActions(Bundle savedInstanceState) { btnSubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!NetworkManager.isInternetAvailable(getActivity())) { Toast.makeText(getActivity(), getResources().getString(R.string.toast_network_error), Toast.LENGTH_SHORT).show(); return; } String fName = etFname.getText().toString(); String lName = etLname.getText().toString(); String email = etEmail.getText().toString(); String phoneNumber = etPhone.getText().toString(); // String creditScore = etCreditScore.getText().toString(); String city = etCity.getText().toString(); String zipCode = etZipcode.getText().toString(); if (AppUtil.isNullOrEmpty(fName)) { Toast.makeText(getActivity(), getString(R.string.toast_please_input_your_fname), Toast.LENGTH_SHORT).show(); return; } if (AppUtil.isNullOrEmpty(lName)) { Toast.makeText(getActivity(), getString(R.string.toast_please_input_your_lname), Toast.LENGTH_SHORT).show(); return; } if (AppUtil.isNullOrEmpty(email)) { Toast.makeText(getActivity(), getString(R.string.toast_please_input_your_email), Toast.LENGTH_SHORT).show(); return; } if (AppUtil.isNullOrEmpty(phoneNumber)) { Toast.makeText(getActivity(), getString(R.string.toast_please_input_mobile_no), Toast.LENGTH_SHORT).show(); return; } // if (AppUtil.isNullOrEmpty(creditScore)) { // Toast.makeText(getActivity(), getString(R.string.toast_please_input_credit_score), Toast.LENGTH_SHORT).show(); // return; // } if (AppUtil.isNullOrEmpty(stateName)) { Toast.makeText(getActivity(), getString(R.string.toast_please_input_your_state), Toast.LENGTH_SHORT).show(); return; } if (AppUtil.isNullOrEmpty(city)) { Toast.makeText(getActivity(), getString(R.string.toast_please_input_your_city), Toast.LENGTH_SHORT).show(); return; } if (AppUtil.isNullOrEmpty(zipCode)) { Toast.makeText(getActivity(), getString(R.string.toast_please_input_your_zipcode), Toast.LENGTH_SHORT).show(); return; } getAddPropertyTask = new GetAddPropertyTask(getActivity(), apiInterface); getAddPropertyTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } }); ivBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { initActivityBackPress(); } }); seekBarPrice.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (seekBar.getProgress() < 10000) { seekBar.setProgress(10000); } priceMinimum = seekBar.getProgress(); Log.e("priceMinimum", priceMinimum + ">>"); txtPriceValue.setText("$" + priceMinimum + " - " + "$" + priceMaximum); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); spPurchaseType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { PurchaseType item = (PurchaseType) parent.getItemAtPosition(position); purchaseType = item.getPurchase_key(); Log.d(TAG, "purchaseType= " + purchaseType); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); spPreapproved.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { SPModel item = (SPModel) parent.getItemAtPosition(position); preApproveType = item.getId(); Log.d(TAG, "preApproveType= " + preApproveType); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); spCountry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { Country item = (Country) parent.getItemAtPosition(position); List<States> statesList = item.getStates(); countryName = item.getCountry_name(); if (statesList != null && statesList.size() > 0) { stateTypeAdapter.setData(item.getStates()); Log.d(TAG, "countryName= " + countryName); Log.d(TAG, "statesList= " + statesList.size()); spState.setSelection((addPropertyEditData != null) ? stateTypeAdapter.getItemPosition(addPropertyEditData.getState()) : 0); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); spState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { States item = (States) parent.getItemAtPosition(position); if (!item.getName().toLowerCase().equalsIgnoreCase(getString(R.string.txt_please_select).toLowerCase())) { stateName = item.getName(); } else { stateName = ""; } Log.d(TAG, "stateName= " + stateName); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); spBuyBedrooms.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { Bedroom item = (Bedroom) parent.getItemAtPosition(position); bedroomType = item.getBedroom_key(); Log.d(TAG, "bedroomType= " + bedroomType); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); spBuyBathroom.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { Bathroom item = (Bathroom) parent.getItemAtPosition(position); bathroomType = item.getBathroom_key(); Log.d(TAG, "bathroomType= " + bathroomType); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); spBuyBasement.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { SPModel item = (SPModel) parent.getItemAtPosition(position); basementType = item.getId(); Log.d(TAG, "basementType= " + basementType); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); spBuyGarage.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { SPModel item = (SPModel) parent.getItemAtPosition(position); garageType = item.getId(); // if (garageType.equalsIgnoreCase("")) { // garageType = "0"; // } else { // garageType = item.getId(); // } Log.d(TAG, "garageType= " + garageType); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); spBuyExterior.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { Exterior item = (Exterior) parent.getItemAtPosition(position); exteriorType = item.getExterior_key(); Log.d(TAG, "exteriorType= " + exteriorType); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); spBuyStyle.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { Styles item = (Styles) parent.getItemAtPosition(position); styleType = item.getStyle_key(); Log.d(TAG, "styleType= " + styleType); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); spBuyPropertyType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { PropertyType item = (PropertyType) parent.getItemAtPosition(position); propertyType = item.getProperty_key(); Log.d(TAG, "propertyType= " + propertyType); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } @Override public void initActivityOnResult(int requestCode, int resultCode, Intent data) { } @Override public void initActivityBackPress() { finish(); } @Override public void initActivityDestroyTasks() { dismissProgressDialog(); if (getCountryWithCityTask != null && getCountryWithCityTask.getStatus() == AsyncTask.Status.RUNNING) { getCountryWithCityTask.cancel(true); } if (getAddPropertyTask != null && getAddPropertyTask.getStatus() == AsyncTask.Status.RUNNING) { getAddPropertyTask.cancel(true); } if (getExteriorTask != null && getExteriorTask.getStatus() == AsyncTask.Status.RUNNING) { getExteriorTask.cancel(true); } if (getPropertyTypeTask != null && getPropertyTypeTask.getStatus() == AsyncTask.Status.RUNNING) { getPropertyTypeTask.cancel(true); } if (getStyleTask != null && getStyleTask.getStatus() == AsyncTask.Status.RUNNING) { getStyleTask.cancel(true); } if (getBathroomTask != null && getBathroomTask.getStatus() == AsyncTask.Status.RUNNING) { getBathroomTask.cancel(true); } if (getBedroomTask != null && getBedroomTask.getStatus() == AsyncTask.Status.RUNNING) { getBedroomTask.cancel(true); } if (getPurchaseTypeTask != null && getPurchaseTypeTask.getStatus() == AsyncTask.Status.RUNNING) { getPurchaseTypeTask.cancel(true); } } @Override public void initActivityPermissionResult(int requestCode, String[] permissions, int[] grantResults) { } /************************ * Server communication * ************************/ private class GetCountryWithCityTask extends AsyncTask<String, Integer, Response> { Context mContext; APIInterface mApiInterface; public GetCountryWithCityTask(Context context, APIInterface apiInterface) { mContext = context; mApiInterface = apiInterface; } @Override protected void onPreExecute() { showProgressDialog(); } @Override protected Response doInBackground(String... params) { try { Call<APIResponse<List<Country>>> call = apiInterface.doGetListCountryWithState(); Response response = call.execute(); if (response.isSuccessful()) { return response; } } catch (Exception ex) { ex.printStackTrace(); } return null; } @Override protected void onPostExecute(Response result) { try { dismissProgressDialog(); if (result != null && result.isSuccessful()) { Log.d(TAG, "APIResponse(GetCountryWithCityTask): onResponse-server = " + result.toString()); APIResponse<List<Country>> data = (APIResponse<List<Country>>) result.body(); Log.e("Country", data.toString() + ""); if (data != null && data.getStatus().equalsIgnoreCase("1")) { Log.d(TAG, "APIResponse(GetCountryWithCityTask()): onResponse-object = " + data.toString()); Log.d(TAG, "APIResponse(GetCountryWithCityTask()): onResponse-object = " + data.toString()); if (data.getData() != null && data.getData().size() > 0) { //Save data into the session AppPref.savePreferences(getActivity(), AllConstants.SESSION_CITY_WITH_AREA_LIST, SessionCountryWithAreaList.getResponseString(new SessionCountryWithAreaList(data.getData()))); countryTypeAdapter.setData(DataUtil.getAllCountryWithStates(mContext)); spCountry.setSelection((addPropertyEditData != null) ? countryTypeAdapter.getItemPosition(addPropertyEditData.getCountry()) : 0); stateTypeAdapter.setData(DataUtil.getAllCountryWithStates(getActivity()).get(0).getStates()); spState.setSelection((addPropertyEditData != null) ? stateTypeAdapter.getItemPosition(addPropertyEditData.getState()) : 0); } } else { Toast.makeText(getActivity(), getResources().getString(R.string.toast_no_info_found), Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(getActivity(), getResources().getString(R.string.toast_could_not_retrieve_info), Toast.LENGTH_SHORT).show(); } } catch (Exception exception) { exception.printStackTrace(); } } } private class GetPropertyTypeTask extends AsyncTask<String, Integer, Response> { Context mContext; APIInterface mApiInterface; public GetPropertyTypeTask(Context context, APIInterface apiInterface) { mContext = context; mApiInterface = apiInterface; } @Override protected void onPreExecute() { showProgressDialog(); } @Override protected Response doInBackground(String... params) { try { Call<APIResponse<List<PropertyType>>> call = apiInterface.doGetListPropertyType(); Response response = call.execute(); if (response.isSuccessful()) { return response; } } catch (Exception ex) { ex.printStackTrace(); } return null; } @Override protected void onPostExecute(Response result) { try { dismissProgressDialog(); if (result != null && result.isSuccessful()) { Log.d(TAG, "APIResponse(GetPropertyTypeTask): onResponse-server = " + result.toString()); APIResponse<List<PropertyType>> data = (APIResponse<List<PropertyType>>) result.body(); Log.e("PropertyType", data.toString() + ""); if (data != null && data.getStatus().equalsIgnoreCase("1")) { Log.d(TAG, "APIResponse(GetPropertyTypeTask()): onResponse-object = " + data.toString()); if (data.getData() != null && data.getData().size() > 0) { //Save data into the session AppPref.savePreferences(getActivity(), AllConstants.SESSION_PROPERTY_TYPE_LIST, SessionPropertyTypeList.getResponseString(new SessionPropertyTypeList(data.getData()))); propertyTypeAdapter.setData(DataUtil.getAllPropertyTypes(mContext)); //checked selection for both add/update property spBuyPropertyType.setSelection((addPropertyEditData != null) ? propertyTypeAdapter.getItemPosition(addPropertyEditData.getProperty_type()) : 0); } } else { Toast.makeText(getActivity(), getResources().getString(R.string.toast_no_info_found), Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(getActivity(), getResources().getString(R.string.toast_could_not_retrieve_info), Toast.LENGTH_SHORT).show(); } } catch (Exception exception) { exception.printStackTrace(); } } } private class GetStyleTask extends AsyncTask<String, Integer, Response> { Context mContext; APIInterface mApiInterface; public GetStyleTask(Context context, APIInterface apiInterface) { mContext = context; mApiInterface = apiInterface; } @Override protected void onPreExecute() { showProgressDialog(); } @Override protected Response doInBackground(String... params) { try { Call<APIResponse<List<Styles>>> call = apiInterface.doGetListStyles(); Response response = call.execute(); if (response.isSuccessful()) { return response; } } catch (Exception ex) { ex.printStackTrace(); } return null; } @Override protected void onPostExecute(Response result) { try { dismissProgressDialog(); if (result != null && result.isSuccessful()) { Log.d(TAG, "APIResponse(GetStyleTask): onResponse-server = " + result.toString()); APIResponse<List<Styles>> data = (APIResponse<List<Styles>>) result.body(); Log.e("Exterior", data.toString() + ""); if (data != null && data.getStatus().equalsIgnoreCase("1")) { Log.d(TAG, "APIResponse(GetStyleTask()): onResponse-object = " + data.toString()); if (data.getData() != null && data.getData().size() > 0) { //Save data into the session AppPref.savePreferences(getActivity(), AllConstants.SESSION_STYLE_LIST, SessionStyleList.getResponseString(new SessionStyleList(data.getData()))); styleAdapter.setData(DataUtil.getAllStyles(mContext)); spBuyStyle.setSelection((addPropertyEditData != null) ? styleAdapter.getItemPosition(addPropertyEditData.getStyle()) : 0); } } else { Toast.makeText(getActivity(), getResources().getString(R.string.toast_no_info_found), Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(getActivity(), getResources().getString(R.string.toast_could_not_retrieve_info), Toast.LENGTH_SHORT).show(); } } catch (Exception exception) { exception.printStackTrace(); } } } private class GetExteriorTask extends AsyncTask<String, Integer, Response> { Context mContext; APIInterface mApiInterface; public GetExteriorTask(Context context, APIInterface apiInterface) { mContext = context; mApiInterface = apiInterface; } @Override protected void onPreExecute() { showProgressDialog(); } @Override protected Response doInBackground(String... params) { try { Call<APIResponse<List<Exterior>>> call = apiInterface.doGetListExterior(); Response response = call.execute(); if (response.isSuccessful()) { return response; } } catch (Exception ex) { ex.printStackTrace(); } return null; } @Override protected void onPostExecute(Response result) { try { dismissProgressDialog(); if (result != null && result.isSuccessful()) { Log.d(TAG, "APIResponse(GetExteriorTask): onResponse-server = " + result.toString()); APIResponse<List<Exterior>> data = (APIResponse<List<Exterior>>) result.body(); Log.e("Exterior", data.toString() + ""); if (data != null && data.getStatus().equalsIgnoreCase("1")) { Log.d(TAG, "APIResponse(GetExteriorTask()): onResponse-object = " + data.toString()); if (data.getData() != null && data.getData().size() > 0) { //Save data into the session AppPref.savePreferences(getActivity(), AllConstants.SESSION_EXTERIOR_LIST, SessionExteriorList.getResponseString(new SessionExteriorList(data.getData()))); exteriorAdapter.setData(DataUtil.getAllExteriors(mContext)); spBuyExterior.setSelection((addPropertyEditData != null) ? exteriorAdapter.getItemPosition(addPropertyEditData.getExterior()) : 0); } } else { Toast.makeText(getActivity(), getResources().getString(R.string.toast_no_info_found), Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(getActivity(), getResources().getString(R.string.toast_could_not_retrieve_info), Toast.LENGTH_SHORT).show(); } } catch (Exception exception) { exception.printStackTrace(); } } } private class GetBathroomTask extends AsyncTask<String, Integer, Response> { Context mContext; APIInterface mApiInterface; public GetBathroomTask(Context context, APIInterface apiInterface) { mContext = context; mApiInterface = apiInterface; } @Override protected void onPreExecute() { showProgressDialog(); } @Override protected Response doInBackground(String... params) { try { Call<APIResponse<List<Bathroom>>> call = apiInterface.getAllBathroomTypes(); Response response = call.execute(); if (response.isSuccessful()) { return response; } } catch (Exception ex) { ex.printStackTrace(); } return null; } @Override protected void onPostExecute(Response result) { try { dismissProgressDialog(); if (result != null && result.isSuccessful()) { Log.d(TAG, "APIResponse(GetBathroomTask): onResponse-server = " + result.toString()); APIResponse<List<Bathroom>> data = (APIResponse<List<Bathroom>>) result.body(); Log.e("Bathroom", data.toString() + ""); if (data != null && data.getStatus().equalsIgnoreCase("1")) { Log.d(TAG, "APIResponse(GetBathroomTask()): onResponse-object = " + data.toString()); if (data.getData() != null && data.getData().size() > 0) { //Save data into the session AppPref.savePreferences(getActivity(), AllConstants.SESSION_BATHROOM_LIST, SessionBathroomList.getResponseString(new SessionBathroomList(data.getData()))); bathroomAdapter.setData(DataUtil.getAllBathrooms(mContext)); spBuyBathroom.setSelection((addPropertyEditData != null) ? bathroomAdapter.getItemPosition(addPropertyEditData.getBathroom()) : 0); } } else { Toast.makeText(getActivity(), getResources().getString(R.string.toast_no_info_found), Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(getActivity(), getResources().getString(R.string.toast_could_not_retrieve_info), Toast.LENGTH_SHORT).show(); } } catch (Exception exception) { exception.printStackTrace(); } } } private class GetBedroomTask extends AsyncTask<String, Integer, Response> { Context mContext; APIInterface mApiInterface; public GetBedroomTask(Context context, APIInterface apiInterface) { mContext = context; mApiInterface = apiInterface; } @Override protected void onPreExecute() { showProgressDialog(); } @Override protected Response doInBackground(String... params) { try { Call<APIResponse<List<Bedroom>>> call = apiInterface.getAllBedroomTypes(); Response response = call.execute(); if (response.isSuccessful()) { return response; } } catch (Exception ex) { ex.printStackTrace(); } return null; } @Override protected void onPostExecute(Response result) { try { dismissProgressDialog(); if (result != null && result.isSuccessful()) { Log.d(TAG, "APIResponse(GetBedroomTask): onResponse-server = " + result.toString()); APIResponse<List<Bedroom>> data = (APIResponse<List<Bedroom>>) result.body(); Log.e("Bedroom", data.toString() + ""); if (data != null && data.getStatus().equalsIgnoreCase("1")) { Log.d(TAG, "APIResponse(GetBedroomTask()): onResponse-object = " + data.toString()); if (data.getData() != null && data.getData().size() > 0) { //Save data into the session AppPref.savePreferences(getActivity(), AllConstants.SESSION_BEDROOM_LIST, SessionBedroomList.getResponseString(new SessionBedroomList(data.getData()))); bedroomAdapter.setData(DataUtil.getAllBedrooms(mContext)); spBuyBedrooms.setSelection((addPropertyEditData != null) ? bedroomAdapter.getItemPosition(addPropertyEditData.getBedroom()) : 0); } } else { Toast.makeText(getActivity(), getResources().getString(R.string.toast_no_info_found), Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(getActivity(), getResources().getString(R.string.toast_could_not_retrieve_info), Toast.LENGTH_SHORT).show(); } } catch (Exception exception) { exception.printStackTrace(); } } } private class GetPurchaseTypeTask extends AsyncTask<String, Integer, Response> { Context mContext; APIInterface mApiInterface; public GetPurchaseTypeTask(Context context, APIInterface apiInterface) { mContext = context; mApiInterface = apiInterface; } @Override protected void onPreExecute() { showProgressDialog(); } @Override protected Response doInBackground(String... params) { try { Call<APIResponse<List<PurchaseType>>> call = apiInterface.getAllPurchaseTypes(); Response response = call.execute(); if (response.isSuccessful()) { return response; } } catch (Exception ex) { ex.printStackTrace(); } return null; } @Override protected void onPostExecute(Response result) { try { dismissProgressDialog(); if (result != null && result.isSuccessful()) { Log.d(TAG, "APIResponse(GetPurchaseTypeTask): onResponse-server = " + result.toString()); APIResponse<List<PurchaseType>> data = (APIResponse<List<PurchaseType>>) result.body(); Log.e("Bedroom", data.toString() + ""); if (data != null && data.getStatus().equalsIgnoreCase("1")) { Log.d(TAG, "APIResponse(GetPurchaseTypeTask()): onResponse-object = " + data.toString()); if (data.getData() != null && data.getData().size() > 0) { //Save data into the session AppPref.savePreferences(getActivity(), AllConstants.SESSION_PURCHASE_TYPE_LIST, SessionPurchaseTypeList.getResponseString(new SessionPurchaseTypeList(data.getData()))); purchaseTypeAdapter.setData(DataUtil.getAllPurchaseTypes(mContext)); spPurchaseType.setSelection((addPropertyEditData != null) ? purchaseTypeAdapter.getItemPosition(addPropertyEditData.getPurchase_type()) : 0); } } else { Toast.makeText(getActivity(), getResources().getString(R.string.toast_no_info_found), Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(getActivity(), getResources().getString(R.string.toast_could_not_retrieve_info), Toast.LENGTH_SHORT).show(); } } catch (Exception exception) { exception.printStackTrace(); } } } private class GetAddPropertyTask extends AsyncTask<String, Integer, Response> { Context mContext; APIInterface mApiInterface; public GetAddPropertyTask(Context context, APIInterface apiInterface) { mContext = context; mApiInterface = apiInterface; } @Override protected void onPreExecute() { showProgressDialog(); } @Override protected Response doInBackground(String... params) { try { String buyerId = AppPref.getPreferences(getActivity(), AllConstants.SESSION_BUYER_ID); Call<APIResponse<List<AddProperty>>> call = null; switch (propertyEnum) { case PROPERTY_ADD: ParamsAddProperty pAddProperty = new ParamsAddProperty("0", etFname.getText().toString(), etLname.getText().toString(), etEmail.getText().toString(), etPhone.getText().toString(), purchaseType, preApproveType, etCreditScore.getText().toString(), propertyType, buyerId, countryName, etCity.getText().toString(), stateName, etZipcode.getText().toString(), bedroomType, bathroomType, basementType, garageType, styleType, exteriorType, priceMinimum + "", priceMaximum + ""); call = apiInterface.doAddPropety(pAddProperty); Log.d(TAG, "pAddProperty: onResponse-server = " + pAddProperty.toString()); Log.d(TAG,"pAddProperty: "+ pAddProperty.toString()); break; case PROPERTY_EDIT: if (addPropertyEditData != null) { ParamsAddProperty pUpdateProperty = new ParamsAddProperty(addPropertyEditData.getId(), etFname.getText().toString(), etLname.getText().toString(), etEmail.getText().toString(), etPhone.getText().toString(), purchaseType, preApproveType, etCreditScore.getText().toString(), propertyType, buyerId, countryName, etCity.getText().toString(), stateName, etZipcode.getText().toString(), bedroomType, bathroomType, basementType, garageType, styleType, exteriorType, priceMinimum + "", priceMaximum + ""); call = apiInterface.doAddPropety(pUpdateProperty); Log.d(TAG, "pAddProperty: onResponse-server = " + pUpdateProperty.toString()); Log.d(TAG,"pAddProperty: "+ pUpdateProperty.toString()); } break; } Response response = call.execute(); if (response.isSuccessful()) { return response; } } catch (Exception ex) { ex.printStackTrace(); } return null; } @Override protected void onPostExecute(Response result) { try { dismissProgressDialog(); if (result != null && result.isSuccessful()) { Log.d(TAG, "APIResponse(GetAddPropertyTask): onResponse-server = " + result.toString()); APIResponse<List<AddProperty>> data = (APIResponse<List<AddProperty>>) result.body(); if (data != null && data.getStatus().equalsIgnoreCase("1")) { Log.d(TAG, "APIResponse(GetAddPropertyTask()): onResponse-object = " + data.toString()); if (data.getData() != null && data.getData().size() == 1) { Intent intentEdit = new Intent(); intentEdit.putExtra(INTENT_KEY_PROPERTY, data.getData().get(0)); setResult(RESULT_OK, intentEdit); finish(); } } else { Toast.makeText(getActivity(), getResources().getString(R.string.toast_no_info_found), Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(getActivity(), getResources().getString(R.string.toast_could_not_retrieve_info), Toast.LENGTH_SHORT).show(); } } catch (Exception exception) { exception.printStackTrace(); } } } }
Python
UTF-8
3,157
2.953125
3
[]
no_license
#!/usr/bin/env python #Setup import files from the manifest file PKG = "see_n_tell" import roslib; roslib.load_manifest(PKG) import rospy #Import support libraries for buffer formatting and other generic functions import basic_header import numpy as np import cv2 #Import the necessary message formats needed from see_n_tell.msg import Int32Array class DepthViewer(object): def __init__(self, window_title="image"): #Create setup variables self._created = False self.depth_config=(640,480,30) self.title = window_title #Set start frame to a demo image :) Better than setting the start frame to all zeros self.frame = cv2.imread("pic_01.jpg") #Define this module as a rospy node rospy.init_node("orbbec_depth_viewer", anonymous=True) #Define a black gray scale image - To be used later to pad image self.zero_buffer = np.zeros( shape=(self.depth_config[1], self.depth_config[0], 1), dtype=np.uint8 ) def start(self): if not self._created: #Subscribe to DepthData_1 ros_topic rospy.Subscriber("DepthData_1", Int32Array, self.callback) #Create a window to display the image basic_header.createNormalWindow(self.title) #Update the created variable self._created = True def end(self): #Update the created variable self._created = False #Close Window basic_header.destroyWindows() #Exit program exit() def run(self): while not rospy.is_shutdown() and self._created: #Update the image in the window basic_header.showFrame(self.title, self.frame) #Get keyboard input key = cv2.waitKey(200) #Specify timeout. Used to regulate loop speed #If key == ESC end program if key == 27: self.end() def callback(self, data): #Retreive data and convert it to a numpy array self.frame = np.array(data.data, dtype=np.int32) #print "Below:: Min, Max",min(self.frame),max(self.frame) self.frame = basic_header.mapf( self.frame.astype(np.float32).ravel(), 0, 33559, 0, 255 ).astype(np.uint8) #print "After:: Min, Max",min(self.frame),max(self.frame) #Describe the shape of the data self.frame.shape = (self.depth_config[1], self.depth_config[0], 1) #Pad the data with two zero data ''' frame = 0 + data + 0 ==> (r,g,b) use the data for the green channel ''' self.frame = np.concatenate( (self.zero_buffer, self.frame, self.zero_buffer), axis = 2) def main(): #Create a viewer object with a window title <Depth Viewer> my_viewer = DepthViewer("Depth Viewer") #Start the viewer my_viewer.start() #Run the viewer my_viewer.run() #End the viewer my_viewer.end() #Run the main function if this program is running directly if __name__ == "__main__": main()
Go
UTF-8
2,644
2.5625
3
[]
no_license
package postgres import ( "context" "encoding/json" "github.com/cep21/circuit/v3" "github.com/jmoiron/sqlx" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" app "github.com/rislah/fakes/internal" "github.com/rislah/fakes/internal/errors" "github.com/rislah/fakes/internal/redis" ) var ( cacheHit = promauto.NewCounterVec(prometheus.CounterOpts{ Name: "cache_hit_total", }, []string{"method"}) cacheMiss = promauto.NewCounterVec(prometheus.CounterOpts{ Name: "cache_miss_total", }, []string{"method"}) ) func init() { prometheus.Register(cacheHit) prometheus.Register(cacheMiss) } type cacheKey string func (c cacheKey) String() string { return string(c) } const ( UsersKey cacheKey = "users" ) type postgresCachedUserDB struct { userDB *postgresUserDB redis redis.Client } var _ app.UserDB = &postgresCachedUserDB{} func NewCachedUserDB(pg *sqlx.DB, rd redis.Client, cc *circuit.Circuit) (*postgresCachedUserDB, error) { pgUserDB := &postgresUserDB{pg: pg, circuit: cc} cdb := &postgresCachedUserDB{ userDB: pgUserDB, redis: rd, } return cdb, nil } func (cdb *postgresCachedUserDB) CreateUser(ctx context.Context, user app.User) error { if err := cdb.userDB.CreateUser(ctx, user); err != nil { return errors.New(err) } if err := cdb.redis.Del(UsersKey.String()); err != nil { return errors.New(err) } return nil } func (cdb *postgresCachedUserDB) GetUsers(ctx context.Context) ([]app.User, error) { resp, err := cdb.redis.SMembers(ctx, UsersKey.String()) if err != nil { return nil, errors.New(err) } if len(resp) > 0 { users := []app.User{} for _, r := range resp { user := app.User{} err := json.Unmarshal([]byte(r), &user) if err != nil { return nil, errors.New(err) } users = append(users, user) } cacheHit.WithLabelValues("getUsers").Inc() return users, nil } users, err := cdb.userDB.GetUsers(ctx) if err != nil { return nil, errors.New(err) } if len(users) > 0 { marshalledUsers := []interface{}{} if err != nil { return nil, err } for _, usr := range users { b, err := json.Marshal(usr.Sanitize()) if err != nil { return nil, errors.New(err) } marshalledUsers = append(marshalledUsers, b) } if err := cdb.redis.SAdd(ctx, UsersKey.String(), marshalledUsers...); err != nil { return nil, errors.New(err) } } cacheMiss.WithLabelValues("getUsers").Inc() return users, nil } func (cdb *postgresCachedUserDB) GetUserByUsername(ctx context.Context, username string) (app.User, error) { return cdb.userDB.GetUserByUsername(ctx, username) }
Markdown
UTF-8
1,888
3.109375
3
[]
no_license
### Задача 21-1 — Монетка в git Создайте git–репозиторий с программой-монеткой `coin.rb.` ### Задача 21-2 — Коммит и отмена Практикуемся с git. В вашем репозитории `coin` поправьте программу так, чтобы монетка вставала на ребро немного чаще: 1 раз в 5 бросков. Сделайте коммит с этим изменением, а потом отмените этот коммит. ### Задача 21-3 — Вращение кубиков Ещё немного практики с git: Возьмите программу `roll_the_dice` (последнюю версию), надеюсь, Вы повторяли за нами и он а у вас в репозитории. Улучшите программу: пусть кубик «вращается» во время броска: сделайте так, чтобы перед тем, как вывести произвольное число от 1 до 6, программа бы быстро отображала несколько сменяющих друг друга произвольных чисел — «граней кубика». Привыкайте: сделали какое-то изменение, проверили, что всё работает — добавьте комит в репозиторий. ### Задача 21-4 — Сумма чисел на кубиках Добавьте ещё одно улучшение к программе `roll_some_dice`: подсчёт суммы выпавших на кубиках чисел. ``` Например: > ruby roll_some_dice.rb How many dice? 3 4 1 3 Sum of dice: 8 ``` Конечно по завершению работ сделайте комит.
Markdown
UTF-8
8,297
2.6875
3
[]
no_license
--- author: nwatson data: categories: - content: Cfengine domain: category nicename: cfengine - content: EFL domain: category nicename: efl post_type: post wp_menu_order: 0 wp_post_id: 723 wp_post_name: bulding-cfengine-classes-using-efl wp_post_parent: 0 wp_post_path: http://watson-wilson.ca/bulding-cfengine-classes-using-efl/ date: 2013-11-21 12:00:25 status: published tags: - cfengine - EFL title: Bulding CFEngine classes using EFL --- Recently my CFEngine colleague [Marco Marongiu](http://syslog.me/) wrote about [classifying CFEngine hosts via external means](http://syslog.me/2013/11/18/external-node-classification-the-cfengine-way/). His post inspired me to write about classifying hosts using [EFL](http://watson-wilson.ca/tag/efl/). --- EFL allows you classify your hosts using data separation and external modules. Let's look at the current bundles available to you and how you can expand EFL adding your own. All of these bundles take a CSV file as a parameter. You can call the bundles when, where, and as many times as you like using different parameter files. For the sake of readability I’m going to break long lines in these examples using ‘\’. You cannot do this in actual use because the CFEngine functions that read CSV files treat line breaks as record breaks. ### Classes from hostnames ### If you have an arbitrary list of hosts that you’d like to belong to the same class then you can use the bundle efl_class_hostname. In this example assume the desired class is web_servers. Create a file called efl_class_hostname-web_servers.txt and fill it with a list of unqualified hostnames, one per line, of all the hosts that belong to the class web_servers. $ cat efl_class_hostname-webservers.txt atlweb01 atlweb01 dmzatlweb01 dmzatlweb02 altdevweb01 atltestweb02 The bundle efl_class_hostname extracts the class name web_servers from the file name using ‘-’ and ‘.txt’ as anchors. The bundle then iterates through each line in the file. If any line in the file matches ${sys.uqhost} the class web_servers is set in the scope of namespace, which is less accurately called a global class. Call the bundle via method. "Set web_server class" usebundle => efl_class_hostname( "${sys.workdir}/inputs/efl_class_hostname-web_servers.txt" ); ### Classes from reading external command output ### The bundle efl_class_cmd_regcmp defines a class if the output of a command matches, or does not match, the provided regular expression. Consider the following parameter file. It has seven columns from zero to six. * Zero is the constraining class expression. The record is only promised if this class expression is true. * One is the class promiser that will be set. * Two is whether or not to negate the match. Meaning set a class if the expression is not matched. * Three is the command to run. * Four defines whether or not the command is run in a full shell. * Five is the regular expression that must match the entire output of the command in four. * Six is a free form promisee for documentation and searching. # Define global class if anchored regex matches command output. # context(0) ;; class promiser(1) ;; 'not' match?(2) ;; command(3) \ ;; useshell/noshell(4) ;; anchored regex(5) ;; promisee(6) debian ;; install_cfengine_apt_key ;; yes ;; /usr/bin/apt-key list \ ;; useshell ;; (?ims).*?CFEngine Community package repository.* ;; Neil Watson The above record runs the command 'apt-key list' on hosts of the debian class. If the given regular expression is not matched (see column two), then the class 'install_cfengine_apt_key' is set. Call the bundle using a method. "Class by shell and regcmp" usebundle => efl_class_cmd_regcmp "${sys.workdir}/efl_class_cmd_regcmp.txt" ); ### Classes from expressions ### The bundle efl_class_expression sets a class if the provided expression is true. Consider the following parameter file. It has three columns from zero to two. * Zero is the class promiser. * One is a class expression. If the expression is evaluated as true, then the class in column zero is defined. * Three is a free form promisee for documentation and searching. # promiser class(0) ;; class expression(1) ;; promisee(3) dmz_a ;; ipv4_10_10_10|ipv4_10_10_11 ;; dmz_a networks The class 'dmz_a' is defined if either of the given classes, which in this case are hard classes, are defined. Call the bundle using a method. "classify by expressions" usebundle => efl_class_expression( "${sys.workdir}/efl_class_expression.txt" ); ### Classes from the classmatch function ### The bundle efl_class_classmatch sets a class if the given regular expression matches any already defined classes. Consider the following parameter file. It has three columns from zero to two. * Zero is the class promiser. * One is a class regular expression. If the expression matches any defined class, then the class in column zero is defined. Note that the expression must match the entire class name and not a partial match. * Three is a free form promisee for documentation and searching. # promiser class(0) ;; class regular expression(1) ;; promisee(3) ipv4_host ;; ipv4_.* ;; Any ipv4 host Call the bundle using a method. "Class by classmatch function" usebundle => efl_class_classmatch( "${sys.workdir}/efl_class_classmatch.txt" ); ### Classes from the iprange function ### The bundle efl_class_iprange sets a class if any of the hosts IP addresses fall within the given range. Consider the following parameter file. It has three columns from zero to two. * Zero is the class promiser. * Two is the IP range to test against. If there is a match the class in zero is defined. * Three is a free form promisee for documentation and searching. # promiser class(0) ;; ip range(1) ;; promisee(3) dmz_a ;; 10.10.10.0/24 ;; dmz_a networks dmz_a ;; 10.10.11.0/24 ;; dmz_a networks dmz_b ;; 172.16.100.0/24 ;; dmz_b networks sandbox_hosts ;; 192.168.0.10-15 ;; CFEngine sandbox hosts Call the bundle using a method. "Class by iprange function" usebundle => efl_class_iprange( "${sys.workdir}/efl_class_iprange.txt" ); ### Classes from external modules ### The bundle efl_command (also discussed [here](http://watson-wilson.ca/make-cfengine-simple-using-the-evolve-free-library/).) promises to run given commands, constrained by a class expression. When the module options at column three is true then the promise attribute 'module' is set to true and cf-agent will treat the output of the command as module syntax. Consider the following parameter file. It has six columns from zero to five. * Zero is the constraining class expression. The record is only promised if this class expression is true. * One is the command promiser. * Two sets the shell containment (‘useshell’ or ‘noshell’). * Three defines if the command should be treated as a module (‘yes’ or ‘no’). * Four sets the ifelapsed number for the commands promise. * Five is the promisee for documentation and searching. # execute arbitrary commands. Great for cron replacement. # context(0) \ ;; command(1) \ ;; usehell(2) ;; module(3) ;; ifelapsed(4) ;; promisee(5) redhat \ ;; ${sys.workdir}/modules/graphics \ ;; yes ;; 1 ;; Set graphics hardware classes Call the bundle using a method. "Run commands or modules" usebundle => efl_command( "${sys.workdir}/inputs/efl_command.txt" ); ### Expanding EFL ### Most bundles in EFL are so similar that you can easily create your own bundles by copying existing ones. There is even a template called 'efl_skeleton' for this very purpose. A common change might be to duplicate a class bundle but change it to a common bundle. Such bundles would define classes that cf-serverd can use. If you do develop new bundles I hope you'll contribute them back to [EFL](https://github.com/neilhwatson/evolve_cfengine_freelib).
PHP
UTF-8
1,968
2.53125
3
[]
no_license
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Blog; use App\Category; class BlogController extends Controller { public function __construct() { $this->middleware('auth'); } public function Index(){ $blogs = Blog::orderBy('created_at', 'desc')->paginate(20); return view('blog.index', ['blogs' => $blogs]); } public function Create(){ $categories=Category::all(); return view("blog.create",['categories' => $categories]); } public function PostCreate(Request $request){ $this->validate($request, [ 'title' => 'required', 'description' => 'required', 'photourl'=>'required', 'category'=>'required' ]); $file = $request->file('photourl'); $filename= $file->getClientOriginalName(); $ext= pathinfo($filename,PATHINFO_EXTENSION); $newfilename= $this->GUID().'.'.$ext; $user=\Auth::user(); $ispublished=$request->has('ispublished')?true:false; $blog= new Blog([ 'title'=>$request->input('title'), 'description'=>$request->input('description'), 'photourl'=>$newfilename, 'category_id'=>$request->input('category'), 'user_id'=>$user->id, 'createdby_id'=>$user->id, 'modifyby_id'=>$user->id, 'IsPublished'=>$ispublished, ]); $file->move('uploads', $newfilename); $blog->save(); return redirect()->route('blog.index'); } public function GUID() { if (function_exists('com_create_guid') === true) { return trim(com_create_guid(), '{}'); } return sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535)); } }
Ruby
UTF-8
2,864
3.265625
3
[]
no_license
# encoding: utf-8 # # Подключим встроенный в руби класс Date для работы с датами require 'date' # Класс «Задача», разновидность базового класса «Запись» class Task < Post # Конструктор у класса «Задача» свой, но использует конструктор родителя. def initialize # Вызываем конструктор родителя super # Создаем специфичную для ссылки переменную экземпляра @due_date — время, к # которому задачу нужно выполнить @due_date = Time.now end # Напишем реализацию метода read_from_console для экземпляра задачи. Он # спрашивает у пользователя текст задачи (что нужно сделать) и дату, до # которой нужно успеть это сделать. def read_from_console # Спросим у пользователя, что нужно сделать и запишем его ответ (строку) в # переменную экземпляра класса Задача @text. puts 'Что надо сделать?' @text = STDIN.gets.chomp # Спросим у пользователя, до какого числа ему нужно выполнить задачу и # подскажем формат, в котором нужно вводить дату. А потом запишем его ответ # в локальную переменную input. puts 'К какому числу? Укажите дату в формате ДД.ММ.ГГГГ, ' \ 'например 12.05.2003' input = STDIN.gets.chomp # Для того, чтобы из строки получить объект класса Date, с которым очень # удобно работать (например, можно вычислить, сколько осталось дней до # нужной даты), мы получим этот объект из строки с помощью метода класса # Date (статического метода). @due_date = Date.parse(input) end # Метод to_string должен вернуть все строки, которые мы хотим записать в # файл при записи нашей задачи: строку с дедлайном, описание задачи и дату # создания задачи. def to_strings deadline = "Крайний срок: #{@due_date.strftime('%Y.%m.%d')}" time_string = "Создано: #{@created_at.strftime('%Y.%m.%d, %H:%M:%S')} \n\r" [deadline, @text, time_string] end end
Python
UTF-8
1,996
2.609375
3
[]
no_license
import numpy as np import glob import cv2 import os import json import sys class Annotator(): def __init__(self,folder,user_input,pics): self.folder = folder #'./windows/' self.user_input = user_input #{'d': 'discard', 'g': 'good'} self.files = glob.glob(self.folder + '/*.jpg') self.files.sort() def run(self): for fname in self.files: img = cv2.imread(fname) while True: cv2.imshow(fname, img) k = cv2.waitKey(0) if k == ord('q'): sys.exit('You pressed \'q\' - exiting!') if k == ord('s'): print(fname + ' - skipping!') cv2.destroyAllWindows() break annotation = None for key, value in self.user_input.items(): if k == ord(key): annotation = value break if annotation is None: print('Oops - did not recognize user input - try again!') else: print(fname + ' - annotation = ' + str(annotation)) cv2.destroyAllWindows() break data = {} data['imagePath'] = os.path.basename(fname) data['imageHeight'] = img.shape[0] data['imageWidth'] = img.shape[1] data['shapes'] = [] for key, value in self.user_input.items(): shape = {} shape['label'] = value shape['shape_type'] = 'point' # doesn't matter? if annotation == value: shape['points'] = [1] else: shape['points'] = [0] data['shapes'].append(shape) with open(self.folder + os.path.splitext(os.path.basename(fname))[0] + '.json', "w") as fout: json.dump(data, fout, indent=2)
Python
UTF-8
2,012
2.59375
3
[ "MIT" ]
permissive
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) 2015 Jérémie DECOCK (http://www.jdhp.org) # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # see http://doc.qt.io/qt-5/qtimer.html import sys from PyQt5.QtCore import QTimer from PyQt5.QtWidgets import QApplication app = QApplication(sys.argv) def update1(): print("Hi") def update2(): print("Hello") timer1 = QTimer() timer1.timeout.connect(update1) timer1.setSingleShot(True) # single shot = triggered only once #timer1.setInterval(500) # ms timer1.start(500) # ms timer2 = QTimer() timer2.timeout.connect(update2) #timer2.setInterval(1000) # ms timer2.start(1000) # ms # The mainloop of the application. The event handling starts from this point. # The exec_() method has an underscore. It is because the exec is a Python keyword. And thus, exec_() was used instead. exit_code = app.exec_() # The sys.exit() method ensures a clean exit. # The environment will be informed, how the application ended. sys.exit(exit_code)
Java
UTF-8
1,631
3.375
3
[]
no_license
package com.practice.google; import java.util.*; /* https://leetcode.com/problems/3sum/ Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not contain duplicate triplets. Example: Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ] */ public class ThreeSum { public List<List<Integer>> threeSum(int[] nums) { if(nums== null || nums.length == 0){ return new ArrayList<List<Integer>>(); } List<List<Integer>> list=new ArrayList<>(); Set<List<Integer>> set = new HashSet<>(); // [-1, 0, 1, 2, -1, -4] for(int i=0;i<nums.length;i++){ int target = 0- nums[i] ; Map<Integer,Integer> m = new HashMap<>(); for(int j=0;j<nums.length;j++){ if(i!=j){ if(m.containsKey(nums[j])){ List<Integer> l = new ArrayList<>(); l.add(nums[i]); l.add(nums[j]); l.add(nums[m.get(nums[j])]); Collections.sort(l); set.add(l); } else { m.put(target-nums[j],j); } } } } list.addAll(set); return list; } public static void main(String[] args) { ThreeSum ts= new ThreeSum(); System.out.println(ts.threeSum(new int[]{-1, 0, 1, 2, -1, -4})); } }
JavaScript
UTF-8
2,098
2.6875
3
[]
no_license
//Should be run locally for system related features var http = require("http"); var fs = require("fs"); var path = require("path"); var glob = require("glob"); var async = require("async"); var open = require('open'); var express = require('express'); var bodyParser = require('body-parser'); var stepsPattern = "w:/work/wexford/Acceptance-Tests/features/**/*.ts"; glob(stepsPattern, function (er, files) { var steps = []; async.each(files, (file, callback) => { fs.readFile(file, (err, fileContents) => { if (err) callback(err); fileContents = fileContents.toString(); extractSteps(file, fileContents, (matches) => { steps = steps.concat(matches); callback(); }); }) }, (err) => { if (err) return console.log(err); createServer(steps); open('http://localhost:1234'); }) }); function extractSteps(filePath, script, callback) { var regex = /\/\^.*\$\//g; var matches = []; var match; async.whilst( () => { return match !== null }, (done) => { match = regex.exec(script); if (!match) return done(); var fileName = path.basename(filePath); var lineNo = findLineNumberFromIndex(script, match.index); matches.push({lineNo: lineNo, filePath: filePath, fileName: fileName, index: match.index, match: match[0]}); done(); }, (err) => { callback(matches); }); } function createServer(steps) { var publicDir = path.join(__dirname, "public"); var app = express(); app.use(express.static('public')); app.use( bodyParser.json() ); app.get('/api/steps', function (req, res) { res.send(steps); }); app.post('/api/openFile', function(req, res) { if (req.body.filePath !== undefined) { console.log("Opening: " + req.body.filePath); open(req.body.filePath); } res.end(); }); app.listen(1234, function () { console.log('app listening on port 1324!'); }); } function findLineNumberFromIndex(text, index) { var newLineIndex = -1; var count = 0; while(newLineIndex === -1 || newLineIndex < index) { newLineIndex = text.indexOf("\n", newLineIndex+1); count++; } return count; }
JavaScript
UTF-8
6,729
2.75
3
[]
no_license
/** * Created by thanatv on 11/3/17. */ const Utils = require('./utils') class Antenna { constructor (antennaObject) { for (var field in antennaObject) { this[field] = antennaObject[field] } } // Calculate antenna gain from normal formula from given diameter (m) and frequency (GHz) gain (freq, path) { var eff = 0.6 // Assume antenna efficiency to be 60% // Check if this antenna already has the property tx_gain that user inputs when antenna is created // tx_gain is used when the gain value is from brochure (not use normal antenna gain formula) // Check if frequency is more than zero means there is a gain value for this antenna if (path && this[path + '_gain'] && this[path + '_gain'].freq > 0) { return this.gainAtFrequency(freq, path) } return 10 * Utils.log10(eff * Math.pow(Math.PI * this.size / Utils.lambda(freq), 2)); } gainAtFrequency(freq ,path) { // derives the equation to get this antenna efficiency let eff = Math.pow(10, this[path+'_gain'].value / 10) / Math.pow((this.size / Utils.lambda(this[path+'_gain'].freq) * Math.PI), 2); return 10 * Utils.log10(eff * Math.pow(Math.PI * this.size / Utils.lambda(freq), 2)); } rxGain(freq) { return this.gain(freq, 'rx') } txGain(freq) { return this.gain(freq, 'tx') } gainImprovment(deg_diff){ console.log('find gain improve of size = ' + this.size + ' diff = ' + deg_diff); var gain_improvement = 0; var gain_improvement_obj = this.gainImprovementValues().find(g => g.size === this.size); if(gain_improvement_obj){ var gain_data = gain_improvement_obj.data; console.log('Gain data = ' + JSON.stringify(gain_data)); // the object with minimum degrees which is more than our degree diff var min_data = _.min(_.filter(gain_data,function(item2){ return item2.degrees > deg_diff}), function(item){return item.degrees;}); console.log('Min data = ' + JSON.stringify(min_data)); // the object with maximum degrees which is less than our degree diff var max_data = _.max(_.filter(gain_data,function(item2){ return item2.degrees < deg_diff}), function(item){return item.degrees;}); console.log('Max data = ' + JSON.stringify(max_data)); if(deg_diff < max_data.degrees){ // do nothing } else if(deg_diff > min_data.degrees){ gain_improvement = min_data.value; } else{ gain_improvement = Utils.linearInterpolation(deg_diff,min_data.degrees, max_data.degrees, min_data.value, max_data.value); } } return gain_improvement; } gainImprovementValues () { return [ { "_id" : "LWvNmsYL8bPnPTaxc", "size" : 1, "data" : [ { "degrees" : 2.7, "value" : 3 }, { "degrees" : 3.5, "value" : 2.1 }, { "degrees" : 4.5, "value" : 2.1 } ] }, { "_id" : "NsnDHRvcWpBW2aMHm", "size" : 2.4, "data" : [ { "degrees" : 2.7, "value" : 1.9 }, { "degrees" : 3.5, "value" : 3.1 }, { "degrees" : 4.5, "value" : 2.4 } ] }, { "_id" : "hZ8XmPMRrWDpkJLsv", "size" : 1.2, "data" : [ { "degrees" : 2.7, "value" : 5.9 }, { "degrees" : 3.5, "value" : 7.6 }, { "degrees" : 4.5, "value" : 8.2 } ] }, { "_id" : "maLSFot3zL4m7v9MH", "size" : 1.8, "data" : [ { "degrees" : 2.7, "value" : 5.4 }, { "degrees" : 3.5, "value" : 7.1 }, { "degrees" : 4.5, "value" : 6.6 } ] }, { "_id": "qf72yXQRyiXrWxrEW", "size": 0.84, "data": [ { "degrees": 2.7, "value": 0 }, { "degrees": 3.5, "value": 6.4 }, { "degrees": 4.5, "value": 7.7 } ] } ] } // Return Gain rejection ratio from given frequency, antenna size and degree difference // (Return Positive value) gainRejectionRatio(freq, degree_diff) { return this.gain(freq) - this.offAxisGain(freq, degree_diff); } // Return off-axis gain offAxisGain(freq, offset) { var gain_max = this.gain(freq); var theta_r = 95 * Utils.lambda(freq) / this.size; var g1 = 29 - 25 * Utils.log10(theta_r); var theta_m = Utils.lambda(freq) / this.size * Math.sqrt((gain_max - g1) / 0.0025); var theta_b = Math.pow(10, 34.0 / 25); var result = 0; var abs_offset = Math.abs(offset); if (abs_offset < theta_m) { result = gain_max - 0.0025 * Math.pow((this.size / Utils.lambda(freq) * offset), 2); } else if (abs_offset < theta_r) { result = g1; } else if (abs_offset < theta_b) { result = 29 - 25 * Utils.log10(abs_offset); } else if (abs_offset < 70) { result = -5; } else { result = 0; } return result; } print() { console.log(`Antenna: ${this.name}`) } static calculateGain(diameter, freq) { var eff = 0.6 // Assume antenna efficiency to be 60% return 10 * Utils.log10(eff * Math.pow(Math.PI * diameter / lambda(freq), 2)); } static temp (attenuation, condition) { if(condition == "clear"){ return 30; } else if(condition == "rain"){ var tc = 2.7 // background sky noise due to cosmic radiation = 2.7K return 260 * (1 - Math.pow(10, -(attenuation / 10))) + tc * Math.pow(10, -(attenuation / 10)); } return 30; } } module.exports = Antenna
Java
UTF-8
565
2.671875
3
[]
no_license
package com.globbypotato.rockhounding_surface.enums; public enum EnumBogLogs implements BaseEnum { OAK, SPRUCE, KAURI, MOPHANE; //---------CUSTOM---------------- public static int size(){ return values().length; } public static String name(int index) { return values()[index].getName(); } //---------ENUM---------------- public static String[] getNames(){ String[] temp = new String[size()]; for(int i = 0; i < size(); i++){ temp[i] = getName(i); } return temp; } public static String getName(int index){ return name(index); } }
Python
UTF-8
10,582
2.671875
3
[]
no_license
import os import ast import time import datetime from time import gmtime, strftime import twitter import csv import pandas as pd def fetched_tweets_by_hashtags(_search_string, _count, _loc, _loc_range): try: _gecode = "%f,%f,%dkm" % (_loc[0], _loc[1], _loc_range) tweets_fetched = api.GetSearch(_search_string, count=_count, geocode=_gecode) print("Great! We fetched " + str(len(tweets_fetched)) + " tweets with the term " + _search_string + "!!") print("---") _tweets_fetched = [] for tweet in tweets_fetched: dict_tweet = {} # _SEARCH STRING try: dict_tweet["_search_string"] = _search_string except Exception as e: print("Sorry there was an error on the _search_string!") dict_tweet["_search_string"] = str(None) # _SEARCH LOC_LAT try: dict_tweet["_search_loc_lat"] = _loc[0] except Exception as e: print("Sorry there was an error on the _search_loc_lat!") dict_tweet["_search_loc_lat"] = str(None) # _SEARCH LOC_LON try: dict_tweet["_search_loc_lon"] = _loc[1] except Exception as e: print("Sorry there was an error on the _search_loc_lon!") dict_tweet["_search_loc_lon"] = str(None) # _SEARCH LOC_RANGE try: dict_tweet["_search_loc_range"] = _loc_range except Exception as e: print("Sorry there was an error on the _search_loc_range!") dict_tweet["_search_loc_range"] = str(None) # ID try: dict_tweet["id"] = tweet.id except Exception as e: print("Sorry there was an error on the tweet.id!") dict_tweet["id"] = str(None) # TEXT try: # Remove all newlines from inside a string _text = tweet.text.replace("\n", " - ") dict_tweet["text"] = _text except Exception as e: print("Sorry there was an error on the tweet.text!") dict_tweet["text"] = str(None) # USER ID try: dict_tweet["user_id"] = tweet.user.id except Exception as e: print("Sorry there was an error on the tweet.user_id!") dict_tweet["user_id"] = str(None) # CREATE_AT try: dict_tweet["created_at"] = tweet.created_at except Exception as e: print("Sorry there was an error on the tweet.created_at!") dict_tweet["created_at"] = str(None) # LANGUAGE try: dict_tweet["lang"] = tweet.lang except Exception as e: print("Sorry there was an error on the tweet.lang!") dict_tweet["lang"] = str(None) # COORDINATES - TYPE try: dict_tweet["coordinates_type"] = tweet.coordinates["type"] except Exception as e: print("Sorry there was an error on the tweet.coordinates.type!") dict_tweet["coordinates_type"] = str(None) # COORDINATES - LAT try: dict_tweet["coordinates_lat"] = tweet.coordinates["coordinates"][1] except Exception as e: print("Sorry there was an error on the tweet.coordinates.coordinates[1]!") dict_tweet["coordinates_lat"] = str(None) # COORDINATES - LON try: dict_tweet["coordinates_lon"] = tweet.coordinates["coordinates"][0] except Exception as e: print("Sorry there was an error on the tweet.coordinates.coordinates[0]!") dict_tweet["coordinates_lon"] = str(None) # PLACE - ID try: dict_tweet["place_id"] = tweet.place["id"] except Exception as e: print("Sorry there was an error on the tweet.place.id!") dict_tweet["place_id"] = str(None) # PLACE - TYPE try: dict_tweet["place_type"] = tweet.place["place_type"] except Exception as e: print("Sorry there was an error on the tweet.place.place_type!") dict_tweet["place_type"] = str(None) # PLACE - NAME try: dict_tweet["place_name"] = tweet.place["place_name"] except Exception as e: print("Sorry there was an error on the tweet.place.place_name!") dict_tweet["place_name"] = str(None) # PLACE - COUNTRY_CODE try: dict_tweet["place_country_code"] = tweet.place["country_code"] except Exception as e: print("Sorry there was an error on the tweet.place.country_code!") dict_tweet["place_country_code"] = str(None) # RETWEET COUNT try: dict_tweet["retweet_count"] = tweet.retweet_count except Exception as e: print("Sorry there was an error on the tweet.retweet_count!") dict_tweet["retweet_count"] = str(None) # FAVORITE COUNT try: dict_tweet["favorite_count"] = tweet.favorite_count except Exception as e: print("Sorry there was an error on the tweet.favorite_count!") dict_tweet["favorite_count"] = str(None) dict_tweet["label"] = str(None) _tweets_fetched.append(dict_tweet) return _tweets_fetched except Exception as e: print("==========================================================================") print("Sorry there was an error! %s" % (ast.literal_eval(str(e))[0]["message"])) return [int(ast.literal_eval(str(e))[0]["code"])] def create_data_base(path_db, _tweets_data, search_topic): csv_file_fetched_tweets = "%s/fetched_tweets_by_%s.%s" % (path_db, search_topic, "csv") with open(csv_file_fetched_tweets, 'a') as csv_file: line_writer = csv.writer(csv_file, delimiter=',', quotechar="\"") for tweet in _tweets_data: try: line_writer.writerow( [tweet["id"], tweet["created_at"], tweet["user_id"], tweet["text"], tweet["lang"], tweet["coordinates_type"], tweet["coordinates_lat"], tweet["coordinates_lon"], tweet["place_id"], tweet["place_name"], tweet["place_country_code"], tweet["retweet_count"], tweet["favorite_count"], tweet["_search_string"], tweet["_search_loc_lat"], tweet["_search_loc_lon"], tweet["_search_loc_range"], tweet["label"], ]) except Exception as e: print(e) return _tweets_data if __name__ == "__main__": api = twitter.Api(consumer_key='CaNf7S5GwXomvr9yJrAqSzLuw', consumer_secret='GG7g28L4r77c5Efw77KbgUaKgiLK32GT4yTfefGcAtyeTBoS7V', access_token_key='1057316422869757952-TvUn2pUMl4352lwxJPOJymNdIfkeN7', access_token_secret='V0XB9cGTBCQwLUOSnNzIbWltpClTrvQ0uJBkohJnSPfY3') db_folder = "%s/db/" % (os.getcwd()) trigger_times = [{"date": "2019-02-20", "hour": "18:46"}, {"date": "2019-02-20", "hour": "18:50"} ] interest_point = pd.read_csv("%s/db_input/Transports.csv" % (os.getcwd())) search_topics = ["bcn", "barcelona", "@policia", "#topmanta", "#lesglories", "#brocanters", "#TopManta", "@AdaColau", "@mossos", "@barcelona_GUB", "#seguridad ", "@sindicatomanter", "#TOPMANTA", "#Crowdfunding", "#Espaicontrabandand","robar", "#pickpocket", "#thieves","Lamine Bathily" "#DefendiendoAMaleno", "@openarms_fund", "#FreeOpenArms", "#MigrantesEnLucha","Venedors Ambulants" "#DefensemCasaAfrica", "#SobrevivirNoEsDelito", "#PerseguidBanquerosNoManteros","Sindicat Popular de Venedors Ambulants", "#DiaInternacionalDelMigrante ", "#JusticiaRacista","@AirportBCN_Info", "immigració","manta", "#EsRacismo", "@@esracismosos", "#PararÉsRacista","#RacismoInstitucional","#RacismeInstitucional","La Rambla.", "thieves " "@sindicatomanter", " les migracions", "Vendedores Ambulante", "@TrasLaManta", "#LamineBathily"] print("--------------------------------------------------------------------------") print("Twitter - DATABASE") print("--------------------------------------------------------------------------") is_stop = False counter = 0 current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M') current_time = current_time.split(" ") if current_time == current_time: try: print("Algorithm is trigger at %s %s" % (current_time[0], current_time[1])) print("--------------------------------------------------------------------------") for index, row in interest_point.iterrows(): # print(list(df_interest_point.columns.values)) _coordinates = [row['LATITUD'], row['LONGITUD']] _place = row['EQUIPAMENT'] data2search = _place.split(" ") if "FGC" not in data2search: _search_radius = 1 print("Algorithm is searching at " + _place + " with a radius of search of " + str( _search_radius) + " km") for topic in search_topics: tweets_data = fetched_tweets_by_hashtags(topic, 50, _coordinates, _search_radius) if tweets_data != [88]: create_data_base(db_folder, tweets_data, topic) else: print("Algorithm need to sleep for 15 min") print("==========================================================================") time.sleep(16 * 60) except Exception as e: print(e)
Java
UTF-8
3,409
3.3125
3
[]
no_license
import java.awt.Graphics; import java.awt.event.KeyListener; import java.awt.event.KeyEvent; import java.io.IOException; import java.awt.event.MouseListener; import java.awt.event.MouseEvent; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.Timer; import javax.swing.SwingUtilities; //class Controller that implements the interfaces //of MouseListener and KeyListener class Controller implements MouseListener, KeyListener { //declaring a Model object and a View object Model model; View view; //Controller constructor that throws exceptions Controller() throws IOException, Exception { //instantiating and creating new model and view objects //and also add a Key Listener model = new Model(); view = new View(this); view.addKeyListener(this); } //method that updates the model object public void update(Graphics g) { model.update(g); } //method that makes events associated with mouse presses public void mousePressed(MouseEvent e) { //if a left mouse button event is detected if (SwingUtilities.isLeftMouseButton(e)) { //gets the x & y location of the click //and calls the n_sprite constructor & repaints model.n_sprite(e.getX(),e.getY()); view.repaint(); } //else if a right mouse button event is detected else if (SwingUtilities.isRightMouseButton(e)) { //calls updateScene with the width and height & repaints model.updateScene(view.getWidth(), view.getHeight()); view.repaint(); } } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseClicked(MouseEvent e) { } public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { } //method that associates events with specific key presses public void keyTyped(KeyEvent e) { //getting the character that was pressed, //as was detected by the KeyListener char keyChar = e.getKeyChar(); //if the character was an h, print "hello world" if (keyChar == 'h') { System.out.println("hello world"); } //if the character was an n, print the //number of captured and escaped if(keyChar == 'n') { RobberCar.printCapture(); RobberCar.printEscape(); } //if the character was an r, reset //the window, reinitialize with default //values, and repaint the window if(keyChar == 'r') { model.initialize(); view.repaint(); } //if the character was an s, create //and start a new Thread if(keyChar == 's') { Thread thread = new Thread (new SpriteMover(model, view)); thread.start(); } } //main method that throws all exceptions and creates a new Controller object public static void main(String[] args) throws Exception { new Controller(); } }
Java
UTF-8
402
1.859375
2
[]
no_license
package com.oversea.task.mapper; import com.oversea.task.domain.OrderCreditCard; /** * @author: yangyan @Package: com.oversea.task.mapper @Description: * @time 2016年8月15日 下午6:16:38 */ public interface OrderCreditCardDAO { public OrderCreditCard getOrderCreditCardById(long creditId); public void updateOrderCreditCardNew(OrderCreditCard orderCreditCard); }
Python
UTF-8
2,433
3.59375
4
[]
no_license
import json import nltk from nltk.corpus import stopwords import emoji # A class that stores a word, and its frequency within the set of tweets class word: def __init__(self, word): self.word = word self.count = 1 # Get the index of a word within a list of words def getItem(list, word): for index, element in enumerate(list): if element.word == word: return index # Check if a word is already in the list def checkList(list, word): for i in list: if i.word == word: return True return False def isRetweet(tweet_text): words = tweet_text.split() if words[0] == 'RT': return True; return False; # Check that a word is: # - not an empty string # - not a url # - not a number # - is not representing a retweet (rt) # - is not a 'stopword' in the english language def check_validity(word): if word == '': return False if word.startswith("http"): return False if word.isnumeric(): return False if word == 'rt': return False if word == 'amp': return False if word in set(stopwords.words('english')): return False return True def contains_emoji(word): for char in word: if char in emoji.UNICODE_EMOJI: return True return False # Add the words from a tweet to the list of word objects def add_words_to_list(words, word_list): for i in words: i = i.lower() if checkList(word_list, i) == False: if check_validity(i): word_list.append( word(i)) else: index = getItem(word_list, i) count = word_list[index].count word_list[index].count = count+1 return word_list # Add the items (emojis, hashtags, mentions) from a tweet to the list of word objects def add_items_to_list(items, item_list): for i in items: i = i.lower() if checkList(item_list, i) == False: item_list.append( word(i)) else: index = getItem(item_list, i) count = item_list[index].count item_list[index].count = count+1 return item_list # Get the 'num' most frequently used words from the passed word list def get_n_most_frequent_items(list, num): list.sort(key=lambda x: x.count, reverse=True) return list[:num] def unique_word_count(word_list): return str(len(word_list))
PHP
UTF-8
673
3.015625
3
[]
no_license
<?php namespace Tdd\Cache; class MemcacheCacheStorage implements ICacheStorage { /** @var \Memcache */ private $memcache; /** * @param \Memcache $memcache */ public function __construct(\Memcache $memcache) { $this->memcache = $memcache; } /** * @param string $key * @param mixed $value * @param int $ttl * * @return bool */ public function set($key, $value, $ttl = 0) { return $this->memcache->set($key, $value, 0, $ttl); } /** * @param string $key * * @return mixed */ public function get($key) { // MemcachePool required argument, but we don't need it. $flags = 0; return $this->memcache->get($key, $flags); } }
Python
UTF-8
182
4.09375
4
[]
no_license
def somatorio(x): if x==1: return 1 else: return x + somatorio(x-1) while True: x = int(input("Somatorio de 1 até: ")) print("Soma: ",somatorio(x) )
C#
UTF-8
526
2.984375
3
[]
no_license
using System; public class Client : Personne { private string photo; //Constructeur d'un client en appelant le constructeur de le classe mere public Client(string nom, string prenom, DateTime dateNaissance, string adresse, string telephone, string adresseMail, string photo) : base(nom, prenom, dateNaissance, adresse, telephone, adresseMail) { this.photo = photo; } //getter et setter public string Photo { get { return photo; } set { photo = value; } } }
Java
UTF-8
475
2.078125
2
[]
no_license
package internet_store.core.domain; import lombok.Data; import javax.persistence.*; @Entity @Data @Table(name = "client", schema = "store") public class Client { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "name") private String name; @Column(name = "surname") private String surname; @Column(name = "phone") private String phoneNumber; @Column(name = "email") private String email; }
TypeScript
UTF-8
869
2.703125
3
[ "BSD-3-Clause" ]
permissive
import { Router } from './router'; import lightTheme from '!!raw-loader!@jupyterlab/theme-light-extension/style/index.css'; const LIGHT_THEME = lightTheme as string; /** * A class to handle requests to /api/themes */ export class Themes { /** * Construct a new Themes. */ constructor() { this._router.add( 'GET', '/api/themes/@jupyterlab/theme-light-extension/index.css', async (req: Request) => new Response(LIGHT_THEME) ); } /** * Dispatch a request to the local router. * * @param req The request to dispatch. */ dispatch(req: Request): Promise<Response> { return this._router.route(req); } private _router = new Router(); } /** * A namespace for Themes statics. */ export namespace Themes { /** * The url for the themes service. */ export const THEMES_SERVICE_URL = '/api/themes'; }
TypeScript
UTF-8
1,806
2.625
3
[]
no_license
import {ModelCtor, Sequelize} from "sequelize"; import userCreator,{UserInstance} from "./user"; import taskCreator,{TaskInstance} from "./task"; export interface SequelizeManagerProps { sequelize: Sequelize; User: ModelCtor<UserInstance>; Task: ModelCtor<TaskInstance>; } export class SequelizeManager implements SequelizeManagerProps { private static instance?: SequelizeManager sequelize: Sequelize; User: ModelCtor<UserInstance>; Task: ModelCtor<TaskInstance>; public static async getInstance(): Promise<SequelizeManager> { if(SequelizeManager.instance === undefined) { SequelizeManager.instance = await SequelizeManager.initialize(); } return SequelizeManager.instance; } private static async initialize(): Promise<SequelizeManager> { const sequelize = new Sequelize({ dialect: 'mysql', host: process.env.DB_HOST, database: process.env.DB_NAME, username: process.env.DB_USER, password: process.env.DB_PASSWORD, port: Number.parseInt(process.env.DB_PORT as string) }); await sequelize.authenticate(); const managerProps: SequelizeManagerProps = { sequelize, User: userCreator(sequelize), Task: taskCreator(sequelize) } SequelizeManager.associate(managerProps); await sequelize.sync(); return new SequelizeManager(managerProps); } private static associate(props: SequelizeManagerProps): void { props.User.hasMany(props.Task); props.Task.belongsTo(props.User) } private constructor(props: SequelizeManagerProps) { this.sequelize = props.sequelize; this.User = props.User; this.Task = props.Task; } }
JavaScript
UTF-8
2,078
2.625
3
[]
no_license
import * as actions from '../actions/ActionNames'; const initialState = { settings: { income: [], expense: [] } } export default function settings(state = initialState, action) { switch (action.type) { case actions.CATEGORY_ITEMS: return {...state, settings: action.payload} case actions.ADD_CATEGORY_ITEM: if(action.payload.category === "income") { return {...state, settings: {...state.settings, income: [...state.settings.income, action.payload.item]}} } else if(action.payload.category === "expense") { return {...state, settings: {...state.settings, expense: [...state.settings.expense, action.payload.item]}} } break; case actions.EDIT_CATEGORY_ITEM: let edited; if(action.payload.category === "income") { edited = state.settings.income; edited.splice(action.index, 1, action.payload.item); return {...state, settings: {...state.settings, income: edited}} } else if(action.payload.category === "expense") { edited = state.settings.expense; edited.splice(action.index, 1, action.payload.item); return {...state, settings: {...state.settings, expense: edited}} } break; case actions.REMOVE_CATEGORY_ITEM: let newState; if(action.category === "income") { newState = state.settings.income; newState.splice(action.payload, 1); return {...state, settings: {...state.settings, income: newState}} } else if(action.category === "expense") { newState = state.settings.expense; newState.splice(action.payload, 1); return {...state, settings: {...state.settings, expense: newState}} } // eslint-disable-next-line default: return state; } }
JavaScript
UTF-8
830
3.28125
3
[]
no_license
/** * @param {string} s * @return {number} */ var minOperations = function(s) { let zeroOne = ""; let oneZero = ""; for (let i = 0; i < s.length; i++) { if (i % 2 === 0) { zeroOne += '0'; oneZero += '1'; } else { zeroOne += '1'; oneZero += '0'; } } let diffChCountFromZeroOne = 0; for (let i = 0; i < s.length; i++) { if (s[i] !== zeroOne[i]) { diffChCountFromZeroOne++ } } let diffChCountFromOneZero = 0; for (let i = 0; i < s.length; i++) { if (s[i] !== oneZero[i]) { diffChCountFromOneZero++ } } return diffChCountFromZeroOne <= diffChCountFromOneZero ? diffChCountFromZeroOne : diffChCountFromOneZero; };
Shell
UTF-8
624
3.34375
3
[]
no_license
#! /bin/sh domain=$1 if [[ $domain != *"ip4"* && $domain != *"ip6"* ]] then spf="$(nslookup -type=txt $domain | grep v=spf)" OIFS=$IFS IFS=' ' read -r -a array <<< "$spf" for x in "${!array[@]}" do if [[ ${array[x]} == *"redirect"* ]] then looper="$(echo "${array[x]}" | cut -c10-)" echo "${looper::-1}" bash spflookup "${looper::-1}" fi if [[ ${array[x]} == *"include"* ]] then looper="$(echo "${array[x]}" | cut -c9-)" echo $looper bash spflookup $looper fi if [[ ${array[x]} == *"ip4"* || ${array[x]} == *"ip6"* ]] then echo Gyldig kilde: "${array[x]}" fi done IFS=$OIFS fi
PHP
UTF-8
4,305
2.515625
3
[]
no_license
<?php App::import('Controller', 'Jqgrid'); /** * 帐号管理 * @author jiangjun * @version 1.0 */ class AccountsController extends JqgridController { public function beforeFilter() { parent::beforeFilter(); parent::requireManager(); } /** * 院系主表 */ public function department() { if ($this->request->is('ajax') && $this->request->is('post')) { $this->autoRender = false; $this->loadModel('Department'); echo $this->show_results($this->Department); } } /** * 院系管理员表 */ public function admin() { if ($this->request->is('ajax') && $this->request->is('post')) { $dept_id = $this->request->query('dept_id'); if (empty($dept_id)) { exit(); } $this->autoRender = false; $where = array('department_id' => $dept_id); $this->loadModel('Manager'); echo $this->show_results($this->Manager, 'id,m_user,m_name,m_pwd', '', $where); } } /** * 院系管理员账号维护 */ public function adminOper() { if ($this->request->is('ajax') && $this->request->is('post')) { $dept_id = $this->request->query('dept_id'); if (empty($dept_id)) { exit(); } $this->autoRender = false; $oper = $this->request->data('oper'); $conditions = array(); if ($this->request->data('id')) $conditions = array('id' => $this->request->data('id')); $data = array(); $data['m_user'] = $this->request->data('m_user'); $data['m_name'] = $this->request->data('m_name'); $pwd = $this->request->data('m_pwd'); if (!empty($pwd)) { $data['m_pwd'] = md5($pwd); } $data['department_id'] = $dept_id; $this->loadModel('Manager'); $this->oper($oper, $this->Manager, $conditions, $data); } else { throw new ForbiddenException(); } } /** * 学生帐号管理 */ public function student() { if ($this->request->is('ajax') && $this->request->is('post')) { $this->autoRender = false; $this->loadModel('Student'); $joins = $this->Student->fullJoins(); $dept_id = $this->getInt($this->request->query('dept_id')); $major_id = $this->getInt($this->request->query('major_id')); $class_id = $this->getInt($this->request->query('class_id')); $where = array(); //直接查询条件 $fields = array('s_name', 's_num', 's_user'); $where = $this->defaultFilterToolbar($fields, $this->request->data); if ($class_id != -1) $where['Class.id'] = $class_id; else if ($major_id != -1) $where['Major.id'] = $major_id; else if ($dept_id != -1) $where['Department.id'] = $dept_id; echo $this->show_results($this->Student, 'Student.id as s_id,s_name,s_num,s_user,s_pwd,s_mail,s_date,s_role,s_phone, reg_date,last_login,Education.edu_name,Department.dept_name, Major.major_name,Class.class_name', '', $where, true, false, $joins); } } /** * 学生信息操作 */ public function studentOper() { $this->autoRender = false; $oper = $this->request->data('oper'); if ($this->request->is('ajax') && $this->request->is('post')) { $oper = $this->request->data('oper'); $conditions = array(); if ($this->request->data('id')) $conditions = array('id' => $this->request->data('id')); $data = array(); $data['s_name'] = $this->request->data('s_name'); $data['s_num'] = $this->request->data('s_num'); $pwd = $this->request->data('s_pwd'); if (!empty($pwd)) { $data['s_pwd'] = md5($pwd); } $this->loadModel('Student'); $this->oper($oper, $this->Student, $conditions, $data); } else { throw new ForbiddenException(); } } }
Markdown
UTF-8
3,965
3.59375
4
[]
no_license
--- title: this和super关键字 date: 2018-09-24 18:41:35 tags: - ES6 - JavaScript categories: ES6 cover_img: https://tva1.sinaimg.cn/large/006y8mN6ly1g77houkndbj30u0190qv6.jpg feature_img: https://tva1.sinaimg.cn/large/006y8mN6ly1g77hp1ssv2j30u01907wp.jpg --- # this 关键字 this 的指向: ## 作为普通对象的方法调用 作为普通对象的方法调用时,this 指向这个对象本身 <!-- more --> ```javascript var obj = { a: 1, getA: function() { console.log(this === obj); console.log(this.a); } }; //this指向obj对象 obj.getA(); ``` ## 作为普通函数调用 作为普通函数调用时,this 指向全局对象,在浏览器中全局对象是 window,在 NodeJs 中全局对象是 global。 ```javascript var obj = { a: 1, getA: function() { console.log(this === obj); console.log(this.a); } }; //this指向window对象 var getA = obj.getA; getA(); ``` 这里需要注意的一点是,直接调用并不是指在全局作用域下进行调用,在任何作用域下,直接通过 函数名(...) 来对函数进行调用的方式,都称为直接调用。 ## 构造器调用 构造器调用时,this 指向返回的对象。用 new 调用一个构造函数,会创建一个新对象,而其中的 this 就指向这个新对象。 ```javascript var a = 10; var b = 20; function Point(x, y) { this.x = x; this.y = y; } var a = new Point(1, 2); console.log(a.x); // 1 console.log(x); // 10 var b = new Point(1, 2); console.log(a === b); // false ``` ## call apply bind 当函数通过 call()和 apply()方法绑定时,this 指向两个方法的第一个参数对象上,若第一个参数不是对象,JS 内部会尝试将其转化为对象然后再指向它。 通过 bind 方法绑定后,无论其在什么情况下被调用,函数将被永远绑定在其第一个参数对象上,bind 绑定后返回的是一个函数。 ### call, apply 的用途 1. 改变 this 的指向 2. Function.prototype.bind ```javascript Function.prototype.bind = function() { var self = this; var context = [].shift.call(arguments); var args = [].slice.call(arguments); return function() { return self.apply(context, args.concat([].slice.call(arguments))); }; }; ``` ### 三者区别 call 只能一个一个传入参数 apply 可直接传入参数数组 bind 会返回一个新的函数 # super 关键字 关键字 super,指向当前对象的原型对象。 ```javascript const proto = { foo: "hello" }; const obj = { foo: "world", find() { return super.foo; } }; Object.setPrototypeOf(obj, proto); obj.find(); // "hello" ``` 上面代码中,对象 obj 的 find 方法之中,通过 super.foo 引用了原型对象 proto 的 foo 属性。 注意,super 关键字表示原型对象时,只能用在对象的方法之中,用在其他地方都会报错。 ```javascript // 报错 const obj = { foo: super.foo }; // 报错 const obj = { foo: () => super.foo }; // 报错 const obj = { foo: function() { return super.foo; } }; ``` 上面三种 super 的用法都会报错,因为对于 JavaScript 引擎来说,这里的 super 都没有用在对象的方法之中。第一种写法是 super 用在属性里面,第二种和第三种写法是 super 用在一个函数里面,然后赋值给 foo 属性。目前,只有对象方法的简写法可以让 JavaScript 引擎确认,定义的是对象的方法。 JavaScript 引擎内部,super.foo 等同于 Object.getPrototypeOf(this).foo(属性)或 Object.getPrototypeOf(this).foo.call(this)(方法)。 ```javascript const proto = { x: "hello", foo() { console.log(this.x); } }; const obj = { x: "world", foo() { super.foo(); } }; Object.setPrototypeOf(obj, proto); obj.foo(); // "world" ``` 上面代码中,super.foo 指向原型对象 proto 的 foo 方法,但是绑定的 this 却还是当前对象 obj,因此输出的就是 world。
Java
UTF-8
2,167
3.6875
4
[]
no_license
package minggu8; import java.util.Scanner; public class QueueMain { static void menu(){ System.out.println("Pilih operasi yang ingin dilakukan: "); System.out.println("1. Enqueue"); System.out.println("2. Dequeue"); System.out.println("3. Print"); System.out.println("4. Print data yang berada di depan"); System.out.println("5. Print data yang berada di belakang"); System.out.println("6. Cari posisi data yang anda input"); System.out.println("7. Cari data di posisi yang anda tentukan"); System.out.println("8. Keluar"); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int pil = 0; System.out.print("Masukkan berapa maksimal data antrian = "); int m = sc.nextInt(); Queue qobj = new Queue(m); do{ menu(); pil = sc.nextInt(); switch(pil){ case 1: System.out.print("Masukkan data baru: "); int dataIn = sc.nextInt(); qobj.enqueue(dataIn); break; case 2: int dataOut = qobj.dequeue(); if (dataOut != 0) { System.out.println("Data yang terambil: " + dataOut); } break; case 3: qobj.print(); break; case 4: qobj.printFront(); break; case 5: qobj.printRear(); break; case 6: System.out.print("Masukkan data yang dicari: "); int dataCari = sc.nextInt(); qobj.printPosition(dataCari); break; case 7: System.out.print("Masukkan posisi yang anda inginkan: "); int posCari = sc.nextInt(); qobj.printDataByPos(posCari); break; } }while (pil >= 1 && pil < 8); } }
PHP
UTF-8
734
2.703125
3
[ "MIT" ]
permissive
<?php namespace DTL\Freelancer\Model\Helper; class ClientHelper { const CLIENTS_DIR = 'clients'; private $baseDir; public function __construct($baseDir) { $this->baseDir = $baseDir; } public function getClientPath($code) { if (strlen($code) !== 6) { throw new \InvalidArgumentException(sprintf( 'Client codes must be 6 characters long. Got "%s"', $code )); } return implode('/', [ $this->baseDir, self::CLIENTS_DIR, $code, 'client.yml' ]); } public function getClientDir($code) { return dirname($this->getClientPath($code)); } }
Python
UTF-8
360
3.59375
4
[]
no_license
#----------------------------------- # try except 语句 # 添加大量的if else语句会降低代码可读性 # #----------------------------------- a = 12 b = 23 c = a + b try : d = '123' d / 3 except ZeroDivisionError : print('不能除以0') except TypeError : print('类型不正确') finally: del c print('清理一些变量')
TypeScript
UTF-8
1,799
2.859375
3
[]
no_license
import { Injectable } from '@angular/core'; import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpResponse } from '@angular/common/http'; import { Observable } from 'rxjs'; import { map, tap } from 'rxjs/operators'; @Injectable() export class CacheInterceptor implements HttpInterceptor { constructor() { } intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> { console.log('URL!!!!!' + request.url) console.log(request.method) if (request.method === 'GET') { //Comprobamos si en la caché (localStorage) están los datos de la petición que se ha realizado const datos = localStorage.getItem(request.url) if (!datos) { //Si no hay datos, hacemos la petición a la API y guardamos en la caché los datos que recibimos de la API return next.handle(request).pipe( map((resp: any) => { console.log({ resp }) localStorage.setItem(request.url, JSON.stringify(resp.body)) //almacenamos las tareas en el localStorage. //luego, si hay datos en el localStorage, los recuperamos de ahí, //en lugar de hacer de nuevo una petición return resp }) ) } else { //Si los datos ya están guardados, los obtenemos de la caché y devolvemos una respuesta. No se realiza la petición //El método intercept retorna un observable que contendrá la response console.log("recuperando datos de la caché") return new Observable((observer) => { observer.next(new HttpResponse({ body: JSON.parse(datos) })) }); } } //si no es un GET, se continúa normalmente con la petición return next.handle(request); } }
Python
UTF-8
1,102
3
3
[ "Apache-2.0", "LicenseRef-scancode-proprietary-license" ]
permissive
# -*- coding: utf-8 -*- from SciDataTool.Functions import NormError def convert(self, values, axes_list, unit, is_norm): """Returns the values of the field transformed or converted. Parameters ---------- self: Data a Data object values: ndarray array of the field axes_list: list a list of RequestedAxis objects unit: str Unit requested by the user ("SI" by default) is_norm: bool Boolean indicating if the field must be normalized (False by default) Returns ------- values: ndarray values of the field """ # Convert into right unit if unit == self.unit or unit == "SI": if is_norm: try: values = values / self.normalizations.get("ref") except: raise NormError( "ERROR: Reference value not specified for normalization" ) elif unit in self.normalizations: values = values / self.normalizations.get(unit) else: values = convert(values, self.unit, unit) return values
Java
UTF-8
2,110
2.140625
2
[]
no_license
package uz.bat.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import uz.bat.model.entity.Address; import uz.bat.model.entity.Person; import uz.bat.model.entity.Store; import uz.bat.model.entity.StoreType; import uz.bat.model.repository.AddressRepository; import uz.bat.model.repository.PersonRepository; import uz.bat.model.repository.StoreRepository; import uz.bat.model.repository.StoreTypeRepository; import java.util.List; @Service public class StoreService { public List<Store> all() { return storeRepository.findAll(); } public Store findOne(Long id) { return storeRepository.findOne(id); } @Transactional public void remove(Long id) { storeRepository.delete(id); } @Transactional public void create(Store store) { storeRepository.save(store); } @Transactional public void edit(Store store) { storeRepository.save(store); } public List<Store> criteria(Page page) { return storeRepository.findAll(page); } public List<Person> allPersons() { return personRepository.findAll(); } public List<StoreType> allStoreTypes() { return storeTypeRepository.findAll(); } public List<Address> allAddress() { return addressRepository.findAll(); } public Address findAddressById(Long addressId) { return addressRepository.findOne(addressId); } public Person findPersonById(Long personId) { return personRepository.findOne(personId); } public StoreType findStoreTypeById(Long storeTypeId) { return storeTypeRepository.findOne(storeTypeId); } @Autowired StoreRepository storeRepository; @Autowired PersonRepository personRepository; @Autowired StoreTypeRepository storeTypeRepository; @Autowired AddressRepository addressRepository; }
Java
UTF-8
1,681
2.4375
2
[]
no_license
package com.xzr.controller; import javax.servlet.http.HttpSession; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.xzr.service.SysUserService; import com.xzr.vo.BaseResponse; import com.xzr.vo.RestStatus; import com.xzr.vo.SysUser; @RestController @RequestMapping("user") public class UserController { @Autowired private SysUserService sysUserServicel; private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class); /** * @param username 用户名 * @param password 密码 * @return BaseResponse 统一返回vo */ @RequestMapping("login") public BaseResponse<String> login(HttpSession session, String username, String password) { LOGGER.info("请求参数:username:{},password:{}", username, password); BaseResponse<String> baseResponse = new BaseResponse<>(); if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) { LOGGER.info("必填请求参数为空,直接返回前端"); baseResponse.setRestStatus(RestStatus.PARAM_NULL); } else { if (sysUserServicel.login(username, password)) { LOGGER.info("用户名密码匹配成功;登录成功 username:{},password:{}", username, password); session.setAttribute("user", new SysUser(username, password)); } else { LOGGER.info("用户名密码匹配失败;登录失败 username:{},password:{}", username, password); baseResponse.setRestStatus(RestStatus.PWD_ERROR); } } return baseResponse; } }
PHP
UTF-8
543
2.546875
3
[ "MIT" ]
permissive
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Category extends Model { protected $fillable = ['name', 'is_active']; // Begin Subcategory Relationship public function subcategories() { return $this->hasMany('App\Subcategory'); } // End Subcategory Relationship public static function getCategoryName($categoryId) { $categoryName = static::where('id', $categoryId)->first(); $categoryName = ($categoryName['name']); return $categoryName; } }
Swift
UTF-8
472
2.828125
3
[]
no_license
// // dogImage.swift // dogPictures // // Created by Justin Knight on 3/19/19. // Copyright © 2019 JustinKnight. All rights reserved. // import Foundation // THis is to represent the data recieved from dog APIs which just contain a status message and an image URL // We need to specify that DogIMage conforms to the Codable protocol so we can decode JSON messages into an instance of our dogIMage struct DogImage: Codable{ let status: String let message: String }
Python
UTF-8
59
2.75
3
[]
no_license
scorelist = [64,100,78,80,72] for i in scorelist: print(i)
SQL
UTF-8
1,152
2.96875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
INSERT INTO series (title, author_id, subgenre_id) VALUES ("A Series of Unfortunate Events", 1, 1), ("Ender Saga", 2, 2); INSERT INTO authors (name) VALUES ("Lemony Snicket"), ("Orson Scott Card"); INSERT INTO subgenres (name) VALUES ("Bleak Children's Fiction"), ("Science Fiction"); INSERT INTO books (title, year, series_id) VALUES ("The Bad Beginning", 1999, 1), ("The Reptile Room", 1999, 1), ("The Wide Window", 2000, 1), ("Ender's Game", 1985, 2), ("Speaker for the Dead", 1986, 2), ("Children of the Mind", 1996, 2); INSERT INTO characters (name, motto, species, author_id, series_id) VALUES ("Klaus", "dracarys", "human", 1, 1), ("Violet", "a honeycomb...", "human", 1, 1), ("Sunny", NULL, "human", 1, 1), ("Count Olaf", "morality is relative", "human", 1, 1), ("Ender", "I dun wannit", "human", 2, 2), ("Bean", "mah queen", "human", 2, 2), ("Valentine", "those who do not study the past are doomed to repeat it", "human", 2, 2), ("Hive Queen", "buzz", "alien", 2, 2); INSERT INTO character_books (character_id, book_id) VALUES (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 2), (4, 2), (5, 1), (5, 2), (5, 3), (6, 1), (6, 2), (6, 3), (7, 2), (8, 2);
Java
GB18030
5,933
1.945313
2
[]
no_license
package com.android.mydiary.org; import java.util.ArrayList; import java.util.List; import com.android.mydiary.org.MainActivity.ListClickListener; import com.android.mydiary.org.MainActivity.ListLongPressListener; import com.android.mydiary.org.adapter.MyDiaryInfoAdapter; import com.android.mydiary.org.db.DataBaseOperate; import com.android.mydiary.org.model.MyDiaryInfoModel; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.TextView.OnEditorActionListener; public class SearchInfoActivity extends Activity{ private EditText searchText=null; private ListView listInfoView=null; private DataBaseOperate dbOperate=null; private List<MyDiaryInfoModel> listInfoModel=null; private ImageButton deleteButton=null; private CheckBox box=null; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.search_info); searchText=(EditText)findViewById(R.id.edit_search); listInfoView=(ListView)findViewById(R.id.diary_info_list_search); deleteButton=(ImageButton)findViewById(R.id.delete_info_search); listInfoModel=new ArrayList<MyDiaryInfoModel>(); dbOperate=new DataBaseOperate(this, listInfoModel); searchText.addTextChangedListener(new SearchInfoListener()); } class SearchInfoListener implements TextWatcher{ public void afterTextChanged(Editable s) { // TODO Auto-generated method stub //refreshDiaryInfo(listInfoView, "DIARY_INFO"); } public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub //refreshDiaryInfo(listInfoView, "DIARY_INFO"); } public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub if (!searchText.getText().toString().equals("")) { refreshDiaryInfo(listInfoView, "DIARY_INFO"); } else { listInfoModel.clear(); //Ϊر뷨 InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(SearchInfoActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } } } public void refreshDiaryInfo(ListView listView,String tableName){ dbOperate.dimSearch(searchText); MyDiaryInfoAdapter myDiaryInfoAdapter = new MyDiaryInfoAdapter(this, listInfoModel); listView.setAdapter(myDiaryInfoAdapter); listView.setVerticalScrollBarEnabled(true); listView.setOnItemClickListener(new ListClickListener()); listView.setOnItemLongClickListener(new ListLongPressListener()); listView.setSelection(0); } class ListClickListener implements OnItemClickListener{ public void onItemClick(AdapterView<?> parent, View v, final int position, long id) { Intent intent=new Intent(); intent.setClass(SearchInfoActivity.this, WriteDiaryActivity.class); intent.putExtra("date", listInfoModel.get(position).getDate()); intent.putExtra("week", listInfoModel.get(position).getWeek()); intent.putExtra("weather", listInfoModel.get(position).getWeather()); intent.putExtra("diaryinfo", listInfoModel.get(position).getDiaryInfo()); intent.putExtra("fontsize", listInfoModel.get(position).getFontSize()); intent.putExtra("id", listInfoModel.get(position).getId()); deleteButton.setVisibility(View.GONE); startActivity(intent); } } class ListLongPressListener implements OnItemLongClickListener{ @SuppressLint("NewApi") public boolean onItemLongClick(AdapterView<?> parent, View v, final int position, long id) { box=(CheckBox)v.findViewById(R.id.view_checkbox); deleteButton.setVisibility(View.VISIBLE); box.setChecked(true); deleteButton.setOnClickListener(new OnClickListener() { @SuppressLint("ParserError") public void onClick(View v) { AlertDialog.Builder builder=new AlertDialog.Builder(SearchInfoActivity.this) .setMessage(getString(R.string.con_delete_diary)) .setTitle(getString(R.string.attention)); builder.setIcon(getResources().getDrawable(android.R.drawable.ic_delete)); builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub if (listInfoModel.get(position).getChecked()) { dbOperate.delete(MyDiaryInfoAdapter.temp_id,SearchInfoActivity.this); refreshDiaryInfo(listInfoView, "DIARY_INFO"); deleteButton.setVisibility(View.GONE); dialog.dismiss(); }else { Toast.makeText(SearchInfoActivity.this, R.string.no_use_op, Toast.LENGTH_LONG).show(); dialog.dismiss(); } } }); builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub dialog.dismiss(); } }); builder.create().show(); } }); return true; } } }
PHP
UTF-8
11,734
2.859375
3
[ "MIT" ]
permissive
<?php namespace Application\Core; use Application\Objects\Router\Route; /** * The Router handles the routes */ class Router { /** @var xTend\Objects\Route Default route */ private static $_default; /** @var xTend\Objects\Route Home route */ private static $_home; /** @var array Contains the POST routes */ private static $_post=[]; /** @var array Contains the GET routes */ private static $_get=[]; /** @var array Contains the PUT routes */ private static $_put=[]; /** @var array Contains the DELETE routes */ private static $_delete=[]; /** @var array Contains the PATCH routes */ private static $_patch=[]; /** @var array Contains the OPTIONS routes */ private static $_options=[]; /** @var array Contains the any routes */ private static $_any=[]; /** @var array Contains the error routes */ private static $_error=[]; /** @var array Contains the aliases of the routes */ private static $_aliases=[]; /** * Returns all registered routes * * @return array */ public static function all() { return array_merge([self::$_home], self::$_post, self::$_get, self::$_delete, self::$_any, self::$_error); } /** * @param string $alias * * @return xTend\Objects\Route | boolean */ public static function alias($alias) { if(isset(self::$_aliases[$alias])) return self::$_aliases[$alias]; return false; } /** * Registers a new route * * @param array reference $routes * @param string|xTend\Objects\Route $handle * @param mixed $route * @param string|boolean $alias * * @return xTend\Objects\Route */ private static function add(&$routes, $handle, $route=false, $alias=false, $override=false) { //you can either pass an actual handle as the handle //or directly pass a route object as the handle //ignoring the route and alias parameters completely $h; if(is_string($handle)&&($route!==false)) { $h = new Route(App::location().'/'.$handle, $route, $alias); } elseif($handle instanceof Route) { $h=$handle; } if(($override===true)||(!isset($routes[$h->handle()]))) { //add route to the post $routes[$h->handle()]=$h; //add to aliases if there is any if($h->alias()!==false) { self::$_aliases[$h->alias()]=$h; } } elseif(isset($routes[$h->handle()])) { $h=$routes[$h->handle()]; } //return Route object return $h; } /** * Registers a new POST route * * @param string|xTend\Objects\Route * @param mixed $route * @param string|boolean $alias * * @return xTend\Objects\Route */ public static function post($handle, $route=false, $alias=false, $override=false) { return self::add(self::$_post, $handle, $route, $alias, $override); } /** * Registers a new GET route * * @param string|xTend\Objects\Route * @param mixed $route * @param string|boolean $alias * * @return xTend\Objects\Route */ public static function get($handle, $route=false, $alias=false, $override=false) { return self::add(self::$_get, $handle, $route, $alias, $override); } /** * Registers a new PUT route * * @param string|xTend\Objects\Route * @param mixed $route * @param string|boolean $alias * * @return xTend\Objects\Route */ public static function put($handle, $route=false, $alias=false, $override=false) { return self::add(self::$_put, $handle, $route, $alias, $override); } /** * Registers a new DELETE route * * @param string|xTend\Objects\Route * @param mixed $route * @param string|boolean $alias * * @return xTend\Objects\Route */ public static function delete($handle, $route=false, $alias=false, $override=false) { return self::add(self::$_delete, $handle, $route, $alias, $override); } /** * Registers a new PATCH route * * @param string|xTend\Objects\Route * @param mixed $route * @param string|boolean $alias * * @return xTend\Objects\Route */ public static function patch($handle, $route=false, $alias=false, $override=false) { return self::add(self::$_patch, $handle, $route, $alias, $override); } /** * Registers a new OPTIONS route * * @param string|xTend\Objects\Route * @param mixed $route * @param string|boolean $alias * * @return xTend\Objects\Route */ public static function options($handle, $route=false, $alias=false, $override=false) { return self::add(self::$_options, $handle, $route, $alias, $override); } /** * Registers a new any route * * @param string|xTend\Objects\Route * @param mixed $route * @param string|boolean $alias * * @return xTend\Objects\Route */ public static function any($handle, $route=false, $alias=false, $override=false) { return self::add(self::$_any, $handle, $route, $alias, $override); } /** * Registers new routes according to the methods * * @param array $methods * @param string|xTend\Objects\Route * @param mixed $route * @param string|boolean $alias */ public static function match($methods, $handle, $route=false, $alias=false, $override=false) { foreach ($methods as $method) { $method=strtolower($method); self::$method($handle, $route, $alias, $override); } } /** * Registers error routes * * @param string|xTend\Objects\Route * @param mixed $route * @param string|boolean $alias * * @return xTend\Objects\Route */ public static function error($handle, $route=false, $alias=false, $override=false) { //here the handler should be an errorcode //you can either pass an actual handle as the handle //or directly pass a route object as the handle //ignoring the route and alias parameters completely $h; if(is_numeric($handle)&&($route!==false)) { $h = new Route($handle, $route, $alias); } elseif($handle instanceof Route) { $h=$handle; } elseif(StatusCodeHandler::find($handle) instanceof StatusCode) { $h = new Route(StatusCodeHandler::find($handle)->code(), $route, $alias); } if(($override===true)||(!isset($routes[$h->handle()]))) { //add route to the error list self::$_error[$h->handle()]=$h; //add to aliases if there is any if($h->alias()!==false) { self::$_aliases[$h->alias()]=$h; } } elseif(isset($routes[$h->handle()])) { $h=$routes[$h->handle()]; } //return Route object return $h; } /** * Registers or returns the default route * * @param mixed $route * * @return xTend\Objects\Route */ public static function def($route=null) { //the default should always be a route, not a handle or route object if($route!==null) { self::$_default = new Route(false, $route, false); } return self::$_default; } /** * Sets a home route * * @param mixed $route * * @return xTend\Objects\Route */ public static function home($route=null) { if($route!==null) { //the home should always be a route not a handle or route object self::$_home = new Route(App::location(), $route, false); } return self::$_home; } /** * Adds route restrictions * * @param function $rest * @param function $routes * * @return boolean */ public static function restrict($rest, $routes) { if((is_callable($rest)&&is_callable($routes)&&($rest()==true))|| (($rest===true)&&(is_callable($routes)))) { $routes(); return true; } return false; } /** * Throws an error route * * @param integer|xTend\Core\StatusCode * * @return boolean */ public static function throw($error) { $code=$error; if($error instanceof StatusCode) { $code=$error->code(); } //find the error route if set if(isset(self::$_error[$code])) { self::$_error[$code]->execute(); return true; } return false; } /** * Executes the router * * @return boolean */ public static function start() { $request = Request::path(); //allow method spoofing $post=Request::$post; if(isset($post['_method'])) { Request::method($post['_method']); } //check home route if(isset(self::$_home)&&self::$_home->match($request)) { self::$_home->execute(); return true; } //check any routes foreach (self::$_any as $handle => $route_obj) { if($route_obj->match($request)) { $route_obj->execute(); return true; } } //check for method routes | POST or GET $relevant_requests; if(Request::method()=="POST") { $relevant_requests = self::$_post; } elseif(Request::method()=="GET") { $relevant_requests = self::$_get; } elseif(Request::method()=="PUT") { $relevant_requests = self::$_put; } elseif(Request::method()=="DELETE") { $relevant_requests = self::$_delete; } elseif(Request::method()=="PATCH") { $relevant_requests = self::$_patch; } elseif(Request::method()=="OPTIONS") { $relevant_requests = self::$_options; } //check the releavant requests foreach ($relevant_requests as $handle => $route_obj) { if($route_obj->match($request)) { $route_obj->execute(); return true; } } //no routes have been executed here //check for error page if(isset(self::$_default)) { self::$_default->execute(); return true; } App::throw(0x0194); return false; } }
JavaScript
UTF-8
457
3.03125
3
[ "MIT" ]
permissive
/** * */ var rIndexjL, tableJL = document.getElementById("janjiLuaran"); function addRow() { var newRow = tableJL.insertRow(tableJL.length); var cell = newRow.insertCell(0); cell.innerHTML = "Test"; selectedRow(); } function selectedRow() { for(var i = 0; i <tableJL.rows.length; i++) { tableJL.rows[i].onclick = function() { rIndexjL = this.rowIndex; console.log(rIndexjL); console.log(this.cells[0].innerHTML); } } } selectedRow();
C++
UTF-8
1,308
2.515625
3
[]
no_license
#pragma once #include "Cube.h" #include "Engine.h" #include "RandomGenerator.h" #include <stdint.h> class CGameBoardData { RandomGenerator generator; uint8_t boardBuffer[17][6]; double fpBuffer[17][6]; int bottomID; uint32_t seed; void genOneLine(int y); void genLine(int y); void genBegin(); int normalizeY(int y); bool isLineEmpty(int y); public: CGameBoardData(); ~CGameBoardData(); void reset(); void clearTop(); void newLine(); uint32_t getSeed(); void setSeed(uint32_t s); uint8_t getBlockID(const glm::ivec2 &block); BOX_COLOR getBlockColor(const glm::ivec2 &block); void swap(glm::ivec2 v1, glm::ivec2 v2) { int correctY = bottomID + 1; auto y = normalizeY(correctY + v1.y); auto temp = boardBuffer[y][v1.x]; boardBuffer[y][v1.x] = boardBuffer[y][v2.x]; boardBuffer[y][v2.x] = temp; } void set(const glm::ivec2 &block, uint8_t value); bool isBlockFalling(const glm::ivec2 &block); bool isSetToRemove(const glm::ivec2 &block); void setToRemove(const glm::ivec2 &block); double getBlink(const glm::ivec2 &block); double getFallOffset(const glm::ivec2 &block); void updateBlink(double dtime); void updateGravity(double dtime); };
Markdown
UTF-8
1,298
2.5625
3
[]
no_license
--- layout: post title: "2016 年终总结" date: 2017-02-10 10:30:20 +0800 categories: summary tags: summary --- ## 闲聊 我想东西的时候总是喜欢拽头发,这几天头发备受摧残啊。 这两天有段代码的逻辑不知道怎么写,就想找个人说说话,打开 QQ,关闭 QQ,打开微信,关闭微信,纠结了好长时间,大家都在忙吧... 说说 16 年总结和 17 年规划吧 ## 2016 年完成情况 1、上次也说过了学了很多东西可以感觉什么都不深入哈,完成一般 2、游戏也写完了,可以我感觉并不好,所以并没有上架哈,完成一般 3、小说还没开始写,这是欠下的债哈,没完成 4、健身没有预期的那么努力哈,完成较差 ## 2017 年目标 1、健身 2、游戏 3、深入学习 iOS 开发,网页开发,服务器开发 4、github 库的维护 5、开始准备弄副业和被动收入 ## 废话一箩筐 祝大家新年快乐,身体健康,新年发大财 能看到这里的都是真爱啊! 问个问题哈,在一个地方的时候怎么追女孩我大概是知道的,如果是异地呢?怎么追?怎么维持关系?怎么相处? 我感觉我对异地一直都有一直无力感哈,遇到根本不知道该怎么去做。
SQL
UTF-8
10,542
3.046875
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.7.3 -- https://www.phpmyadmin.net/ -- -- Servidor: localhost:8889 -- Tiempo de generación: 16-05-2018 a las 22:21:43 -- Versión del servidor: 5.6.35-log -- Versión de PHP: 7.1.8 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; -- -- Base de datos: `mydb` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `Compra` -- CREATE TABLE `Compra` ( `idCompra` int(11) NOT NULL, `FechaCompra` date DEFAULT NULL, `PrecioTotalCompra` float DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `Compra` -- INSERT INTO `Compra` (`idCompra`, `FechaCompra`, `PrecioTotalCompra`) VALUES (1, '2018-04-18', 0), (2, '2018-04-24', 0), (3, '2018-04-14', 0), (4, '2018-04-14', 0), (5, '2018-04-14', 0), (6, '2018-04-14', 0), (7, '2018-04-14', 0), (8, '2018-04-14', 0), (9, '2018-04-14', 0), (10, '2018-04-14', 0), (11, '2018-04-14', 0), (12, '2018-04-14', 0), (13, '2018-04-14', 36), (14, '2018-04-14', 0), (15, '2018-04-14', 0), (16, '2018-04-14', 0), (17, '2018-04-14', 0), (18, '2018-04-14', 40), (19, '2018-04-14', 0), (20, '2018-04-14', 57), (21, '2018-04-14', 30), (22, '2018-04-14', 500), (23, '2018-04-16', 54), (24, '2018-04-16', 200), (25, '2018-04-16', 0); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `Detalle_Compras` -- CREATE TABLE `Detalle_Compras` ( `idDetalle_Compras` int(11) NOT NULL, `Cantidad` float DEFAULT NULL, `Precio` varchar(45) DEFAULT NULL, `Producto_idProducto` int(11) NOT NULL, `Proveedor_idProveedor` int(11) NOT NULL, `Compra_idCompra` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `Detalle_Compras` -- INSERT INTO `Detalle_Compras` (`idDetalle_Compras`, `Cantidad`, `Precio`, `Producto_idProducto`, `Proveedor_idProveedor`, `Compra_idCompra`) VALUES (1, 5, '75', 1, 1, 1), (2, 3, '39', 2, 1, 1), (3, 4, '72', 3, 2, 2), (4, 3, '12.0', 19, 4, 13), (5, 2, '21.0', 19, 4, 17), (6, 2, '20.0', 19, 4, 18), (7, 2, '15.0', 19, 4, 20), (8, 3, '9.0', 16, 2, 20), (9, 2, '15.0', 19, 4, 21), (10, 10, '8.0', 16, 2, 22), (11, 10, '7.0', 17, 2, 22), (12, 10, '20.0', 18, 1, 22), (13, 10, '15.0', 19, 4, 22), (14, 2, '7.0', 17, 2, 23), (15, 2, '20.0', 18, 1, 23), (16, 10, '20.0', 21, 4, 24); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `Detalle_Ventas` -- CREATE TABLE `Detalle_Ventas` ( `idDetalle_Ventas` int(11) NOT NULL, `Cantidad` float DEFAULT NULL, `PrecioVenta` float DEFAULT NULL, `Producto_idProducto` int(11) NOT NULL, `Venta_idVenta` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `Detalle_Ventas` -- INSERT INTO `Detalle_Ventas` (`idDetalle_Ventas`, `Cantidad`, `PrecioVenta`, `Producto_idProducto`, `Venta_idVenta`) VALUES (1, 2, 30, 1, 1), (2, 3, 54, 3, 1), (3, 2, 26, 2, 1), (4, 2, 12, 16, 6), (5, 2, 12, 16, 7), (6, 3, 23, 18, 12), (7, 2, 22, 19, 14), (8, 3, 12, 16, 14), (9, 2, 12, 16, 15), (10, 2, 22, 19, 17), (11, 3, 23, 18, 18), (12, 2, 22, 19, 19), (13, 2, 22, 19, 20), (14, 2, 12, 16, 22), (15, 3, 22, 19, 22), (16, 2, 12, 16, 23), (17, 3, 22, 19, 23), (18, 1, 9, 17, 24), (19, 4, 23, 18, 24), (20, 2, 23, 18, 25), (21, 2, 9, 17, 25), (22, 3, 8, 20, 26), (23, 2, 22, 19, 26), (24, 8, 25, 21, 27); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `Producto` -- CREATE TABLE `Producto` ( `idProducto` int(11) NOT NULL, `Nombre` varchar(45) DEFAULT NULL, `Precio` float DEFAULT NULL, `PrecioVenta` float DEFAULT NULL, `FechaCaducidad` date DEFAULT NULL, `Proveedor_idProveedor` int(11) NOT NULL, `Cantidad` float DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `Producto` -- INSERT INTO `Producto` (`idProducto`, `Nombre`, `Precio`, `PrecioVenta`, `FechaCaducidad`, `Proveedor_idProveedor`, `Cantidad`) VALUES (1, 'Coca Cola 600ml', 15, NULL, '2018-04-28', 1, 10), (2, 'Delaware Punch 600ml', 13, NULL, '2018-05-26', 1, 10), (3, 'Cremax 322gr', 18, NULL, '2018-06-23', 2, 10), (9, 'Flipy 25gr', 8, NULL, '2018-12-12', 2, 20), (13, 'Emperador 30gr', 13, NULL, '2018-12-28', 2, 17), (16, 'Chokis 300gr', 8, 12, '2018-03-08', 2, 10), (17, 'Piruetas', 7, 9, '2018-01-01', 2, 10), (18, 'Sprite', 20, 23, '2018-01-01', 1, 10), (19, 'Tomates', 15, 22, '2018-01-01', 4, 8), (20, 'Jumex', 6, 8, '2018-01-01', 1, 7), (21, 'Star Fruit', 20, 25, '2018-12-01', 4, 2); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `Proveedor` -- CREATE TABLE `Proveedor` ( `idProveedor` int(11) NOT NULL, `NombreProveedor` varchar(45) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `Proveedor` -- INSERT INTO `Proveedor` (`idProveedor`, `NombreProveedor`) VALUES (1, 'Coca Cola Company'), (2, 'Gamesa'), (4, 'Ricardo'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `ReporteExistencia` -- CREATE TABLE `ReporteExistencia` ( `idReporteExistencia` int(11) NOT NULL, `Compra_idCompra` int(11) NOT NULL, `Venta_idVenta` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `Venta` -- CREATE TABLE `Venta` ( `idVenta` int(11) NOT NULL, `FechaVenta` date DEFAULT NULL, `PrecioTotalVenta` float DEFAULT NULL, `Ganancia` float DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `Venta` -- INSERT INTO `Venta` (`idVenta`, `FechaVenta`, `PrecioTotalVenta`, `Ganancia`) VALUES (1, '2018-04-30', 0, NULL), (2, '2018-04-13', 0, NULL), (3, '2018-04-13', 0, NULL), (4, '2018-04-13', 0, NULL), (5, '2018-04-13', 0, NULL), (6, '2018-04-13', 24, NULL), (7, '2018-04-13', 24, NULL), (8, '2018-04-14', 0, NULL), (9, '2018-04-14', 0, NULL), (10, '2018-04-14', 0, 0), (11, '2018-04-14', 0, 0), (12, '2018-04-14', 0, 0), (13, '2018-04-14', 0, 0), (14, '2018-04-14', 80, 0), (15, '2018-04-14', 24, 0), (16, '2018-04-14', 0, 0), (17, '2018-04-14', 44, 0), (18, '2018-04-14', 69, 0), (19, '2018-04-14', 44, 0), (20, '2018-04-14', 44, 0), (21, '2018-04-14', 0, 0), (22, '2018-04-14', 0, 0), (23, '2018-04-14', 90, 29), (24, '2018-04-14', 101, 14), (25, '2018-04-14', 64, 10), (26, '2018-04-16', 68, 20), (27, '2018-04-16', 200, 40); -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `Compra` -- ALTER TABLE `Compra` ADD PRIMARY KEY (`idCompra`); -- -- Indices de la tabla `Detalle_Compras` -- ALTER TABLE `Detalle_Compras` ADD PRIMARY KEY (`idDetalle_Compras`), ADD KEY `fk_Detalle_Compras_Producto1_idx` (`Producto_idProducto`), ADD KEY `fk_Detalle_Compras_Proveedor1_idx` (`Proveedor_idProveedor`), ADD KEY `fk_Detalle_Compras_Compra1_idx` (`Compra_idCompra`); -- -- Indices de la tabla `Detalle_Ventas` -- ALTER TABLE `Detalle_Ventas` ADD PRIMARY KEY (`idDetalle_Ventas`), ADD KEY `fk_Detalle_Ventas_Producto1_idx` (`Producto_idProducto`), ADD KEY `fk_Detalle_Ventas_Venta1_idx` (`Venta_idVenta`); -- -- Indices de la tabla `Producto` -- ALTER TABLE `Producto` ADD PRIMARY KEY (`idProducto`,`Proveedor_idProveedor`), ADD KEY `fk_Producto_Proveedor1_idx` (`Proveedor_idProveedor`); -- -- Indices de la tabla `Proveedor` -- ALTER TABLE `Proveedor` ADD PRIMARY KEY (`idProveedor`); -- -- Indices de la tabla `ReporteExistencia` -- ALTER TABLE `ReporteExistencia` ADD PRIMARY KEY (`idReporteExistencia`), ADD KEY `fk_ReporteExistencia_Compra1_idx` (`Compra_idCompra`), ADD KEY `fk_ReporteExistencia_Venta1_idx` (`Venta_idVenta`); -- -- Indices de la tabla `Venta` -- ALTER TABLE `Venta` ADD PRIMARY KEY (`idVenta`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `Compra` -- ALTER TABLE `Compra` MODIFY `idCompra` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=26; -- -- AUTO_INCREMENT de la tabla `Detalle_Compras` -- ALTER TABLE `Detalle_Compras` MODIFY `idDetalle_Compras` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=17; -- -- AUTO_INCREMENT de la tabla `Detalle_Ventas` -- ALTER TABLE `Detalle_Ventas` MODIFY `idDetalle_Ventas` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=25; -- -- AUTO_INCREMENT de la tabla `Producto` -- ALTER TABLE `Producto` MODIFY `idProducto` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22; -- -- AUTO_INCREMENT de la tabla `Proveedor` -- ALTER TABLE `Proveedor` MODIFY `idProveedor` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT de la tabla `ReporteExistencia` -- ALTER TABLE `ReporteExistencia` MODIFY `idReporteExistencia` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT de la tabla `Venta` -- ALTER TABLE `Venta` MODIFY `idVenta` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=28; -- -- Restricciones para tablas volcadas -- -- -- Filtros para la tabla `Detalle_Compras` -- ALTER TABLE `Detalle_Compras` ADD CONSTRAINT `fk_Detalle_Compras_Compra1` FOREIGN KEY (`Compra_idCompra`) REFERENCES `Compra` (`idCompra`) ON DELETE NO ACTION ON UPDATE NO ACTION, ADD CONSTRAINT `fk_Detalle_Compras_Producto1` FOREIGN KEY (`Producto_idProducto`) REFERENCES `Producto` (`idProducto`) ON DELETE NO ACTION ON UPDATE NO ACTION, ADD CONSTRAINT `fk_Detalle_Compras_Proveedor1` FOREIGN KEY (`Proveedor_idProveedor`) REFERENCES `Proveedor` (`idProveedor`) ON DELETE NO ACTION ON UPDATE NO ACTION; -- -- Filtros para la tabla `Detalle_Ventas` -- ALTER TABLE `Detalle_Ventas` ADD CONSTRAINT `fk_Detalle_Ventas_Producto1` FOREIGN KEY (`Producto_idProducto`) REFERENCES `Producto` (`idProducto`) ON DELETE NO ACTION ON UPDATE NO ACTION, ADD CONSTRAINT `fk_Detalle_Ventas_Venta1` FOREIGN KEY (`Venta_idVenta`) REFERENCES `Venta` (`idVenta`) ON DELETE NO ACTION ON UPDATE NO ACTION; -- -- Filtros para la tabla `Producto` -- ALTER TABLE `Producto` ADD CONSTRAINT `fk_Producto_Proveedor1` FOREIGN KEY (`Proveedor_idProveedor`) REFERENCES `Proveedor` (`idProveedor`) ON DELETE NO ACTION ON UPDATE NO ACTION; -- -- Filtros para la tabla `ReporteExistencia` -- ALTER TABLE `ReporteExistencia` ADD CONSTRAINT `fk_ReporteExistencia_Compra1` FOREIGN KEY (`Compra_idCompra`) REFERENCES `Compra` (`idCompra`) ON DELETE NO ACTION ON UPDATE NO ACTION, ADD CONSTRAINT `fk_ReporteExistencia_Venta1` FOREIGN KEY (`Venta_idVenta`) REFERENCES `Venta` (`idVenta`) ON DELETE NO ACTION ON UPDATE NO ACTION;
C#
UTF-8
942
3.0625
3
[]
no_license
SqlCommand command = new SqlConnection("[The connection String goes here]").CreateCommand(); try { command.Parameters.Add(new SqlParameter() { ParameterName = "ParameterA", Direction = ParameterDirection.Input, Value = "Some value" }); command.Parameters.Add(new SqlParameter() { ParameterName = "ReturnValue", Direction = ParameterDirection.ReturnValue }); command.CommandText = "[YourSchema].[YourProcedureName]"; command.CommandType = CommandType.StoredProcedure; command.Connection.Open(); command.ExecuteNonQuery(); } catch (Exception ex) { //TODO: Log the exception and return the relevant result. } finally { if (command.Connection.State != ConnectionState.Closed) command.Connection.Close(); SqlConnection.ClearPool(command.Connection); command.Connection.Dispose(); command.Dispose(); }
C
UTF-8
245
2.546875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { int receivedNumber; read(5, &receivedNumber, sizeof(int)); int nKup = receivedNumber * receivedNumber * receivedNumber; write(6, &nKup, sizeof(int)); return 0; }
Ruby
UTF-8
491
2.90625
3
[]
no_license
require 'open-uri' require 'nokogiri' # Let's scrape recipes from http://www.epicurious.com puts "What recipes are you looking for?" print ">" user_input = gets.chomp url = "https://www.bbcgoodfood.com/search/recipes?q=#{user_input}" html_file = URI.open(url).read html_doc = Nokogiri::HTML(html_file) html_doc.search('.standard-card-new__article-title').each do |element| # puts element.text puts element.attribute('href').value puts element.attribute('href').value.class end
Markdown
UTF-8
1,198
2.796875
3
[ "MIT" ]
permissive
# leetcodeJS Personal solution for leetcode problem using Javascript. ## Why? This is personal attempt for leetcode problems. Over period of time with web development, I felt I was more into that part of CS that involves understanding contracts(RFCs, HTML5, ES, etc) and specifications(WCAG, REST, etc) that revolves around Browser and Web. The motivation behind this is to get back to some problem solving aspect of CS and also get better command over JS language. ## Environment Chrome/Nodejs (depending on time taken, easy-small problems on browser) ## Problem Organisation Starting with two params - difficulty and most attempted problems. And subsequently increasing difficulty. Problems are organised in respective difficulty Folder -easy, medium, hard (As tagged on leetcode.com). There is also a seperate section as another solution for individual problems for solutions that are different/better/optimised/ideal. ## Problems Solutions Complete list of solved problems in order of Problem number can be seen [here](Problems.md) ## Contribution Suggestions and PRs are welcome for any algo/documentation improvement! Please create issue or open PR request for contribution. ---
Swift
UTF-8
2,042
3.046875
3
[]
no_license
// // GameLogic.swift // ParticleBlaster // // Created by Bohan Huang on 29/3/17. // Copyright © 2017 ParticleBlaster. All rights reserved. // /** * The `GameLogic` protocol defines the basic methods and properties of * To define the logic of a new game play * - Create a class conforming to this protocol * - Implement the basic methods and properties of the class * - Define any other methods in the class for unique game logic */ import SpriteKit protocol GameLogic { // Game Controller var gameViewController: GameViewController { get set } /* Start of game logic related properties */ var winningCondition: Bool { get } var losingCondition: Bool { get } /* End of game logic related properties */ /* Start of game object related properties */ // The number of players in the game var numberOfPlayers: Int { get set } // The player-controllers for each player var playerControllers: [PlayerController] { get set } // The obstacles in the game var obstaclePool: [Obstacle] { get set } // The map boundary of the game var map: Boundary { get set } /* End of game object related properties */ /* Start of Obstacles behavior related methods */ func obtainObstaclesHandler() -> [Obstacle] func updateObstaclesVelocityHandler() /* End of obstacles behavior related methods */ /* Start of collision related methods */ func bulletDidCollideWithObstacle(bullet: SKSpriteNode, obstacle: SKSpriteNode) func bulletDidCollideWithPlayer(bullet: SKSpriteNode, player: SKSpriteNode) func grenadeDidCollideWithObstacle(obstacle: SKSpriteNode, grenade: SKSpriteNode) func obstacleDidCollideWithPlayer(obs: SKSpriteNode, player: SKSpriteNode) func obstaclesDidCollideWithEachOther(obs1: SKSpriteNode, obs2: SKSpriteNode) func objectDidCollideWithMap(object: SKSpriteNode) func upgradePackDidCollideWithPlayer(upgrade: SKSpriteNode, player: SKSpriteNode) /* End of collision related methods */ }
Java
UTF-8
302
1.820313
2
[ "Apache-2.0", "GPL-1.0-or-later" ]
permissive
package com.github.netty.core.util; /** * @author wangzihao * 2018/8/25/025 */ public class LoggerFactoryX { public static LoggerX getLogger(Class clazz) { return new LoggerX(clazz); } public static LoggerX getLogger(String clazz) { return new LoggerX(clazz); } }
Java
UTF-8
352
2.40625
2
[]
no_license
package backEnd; import lombok.Builder; import lombok.RequiredArgsConstructor; /** * Collects money for the current player */ @RequiredArgsConstructor @Builder public class CollectMoney implements Action { private final int amount; @Override public void resolve() { GameManager.getCurrentPlayer().addFunds(amount); } }
Java
UTF-8
3,452
2.03125
2
[ "Apache-2.0" ]
permissive
package com.amazon.dataprepper.plugins.source.oteltrace; import com.amazon.dataprepper.model.configuration.PluginSetting; public class OTelTraceSourceConfig { private static final String REQUEST_TIMEOUT = "request_timeout"; private static final String PORT = "port"; private static final String SSL = "ssl"; private static final String HEALTH_CHECK_SERVICE = "health_check_service"; private static final String PROTO_REFLECTION_SERVICE = "proto_reflection_service"; private static final String SSL_KEY_CERT_FILE = "sslKeyCertChainFile"; private static final String SSL_KEY_FILE = "sslKeyFile"; private static final int DEFAULT_REQUEST_TIMEOUT = 10_000; private static final int DEFAULT_PORT = 21890; private static final boolean DEFAULT_SSL = false; private final int requestTimeoutInMillis; private final int port; private final boolean healthCheck; private final boolean protoReflectionService; private final boolean ssl; private final String sslKeyCertChainFile; private final String sslKeyFile; private OTelTraceSourceConfig(final int requestTimeoutInMillis, final int port, final boolean healthCheck, final boolean protoReflectionService, final boolean isSSL, final String sslKeyCertChainFile, final String sslKeyFile) { this.requestTimeoutInMillis = requestTimeoutInMillis; this.port = port; this.healthCheck = healthCheck; this.protoReflectionService = protoReflectionService; this.ssl = isSSL; this.sslKeyCertChainFile = sslKeyCertChainFile; this.sslKeyFile = sslKeyFile; if (ssl && (sslKeyCertChainFile == null || sslKeyCertChainFile.isEmpty())) { throw new IllegalArgumentException(String.format("%s is enable, %s can not be empty or null", SSL, SSL_KEY_CERT_FILE)); } if (ssl && (sslKeyFile == null || sslKeyFile.isEmpty())) { throw new IllegalArgumentException(String.format("%s is enable, %s can not be empty or null", SSL, SSL_KEY_CERT_FILE)); } } public static OTelTraceSourceConfig buildConfig(final PluginSetting pluginSetting) { return new OTelTraceSourceConfig(pluginSetting.getIntegerOrDefault(REQUEST_TIMEOUT, DEFAULT_REQUEST_TIMEOUT), pluginSetting.getIntegerOrDefault(PORT, DEFAULT_PORT), pluginSetting.getBooleanOrDefault(HEALTH_CHECK_SERVICE, false), pluginSetting.getBooleanOrDefault(PROTO_REFLECTION_SERVICE, false), pluginSetting.getBooleanOrDefault(SSL, DEFAULT_SSL), pluginSetting.getStringOrDefault(SSL_KEY_CERT_FILE, null), pluginSetting.getStringOrDefault(SSL_KEY_FILE, null)); } public int getRequestTimeoutInMillis() { return requestTimeoutInMillis; } public int getPort() { return port; } public boolean hasHealthCheck() { return healthCheck; } public boolean hasProtoReflectionService() { return protoReflectionService; } public boolean isSsl() { return ssl; } public String getSslKeyCertChainFile() { return sslKeyCertChainFile; } public String getSslKeyFile() { return sslKeyFile; } }