language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Python
UTF-8
81
3.140625
3
[]
no_license
# -*- coding: utf-8 -*- A = int(input('请输入十进制数字:')) print(hex(A))
Python
UTF-8
2,249
4.28125
4
[]
no_license
def menu(): print("---------\nMAIN MENU\n---------\n" "1. Isi List\n" "2. Lihat List\n" "3. Sort List Ascending\n" "4. Sort List Descending\n" "5. Nilai Tertinggi dan Terendah\n" "6. Jumlah Ganjil dan Genap\n" "7. Ulang\n" "8. Keluar\n") # # # storage = [] def isi_list(): n = int(input("Mau masukkan berapa angka? ")) for _ in range(n): storage.append(int(input("Masukkan angka: "))) def lihat_list(): print(storage) def sort_ascending(): for i in range(len(storage)): for j in range(i+1, len(storage)): if storage[i] > storage[j]: storage[i], storage[j] = storage[j], storage[i] print(storage) def sort_descending(): for i in range(len(storage)): for j in range(i + 1, len(storage)): if storage[j] > storage[i]: storage[i], storage[j] = storage[j], storage[i] print(storage) def min_max(): for i in range(len(storage)): for j in range(i+1, len(storage)): if storage[i] > storage[j]: storage[i], storage[j] = storage[j], storage[i] min_value = storage[0] max_value = storage[-1] print("Nilai terendah adalah {} dan nilai tertinggi adalah {}".format(min_value, max_value)) def ganjil_genap(): n_ganjil, n_genap = 0, 0 for i in range(len(storage)): if storage[i] % 2 == 1: n_ganjil += 1 else: n_genap += 1 print("Ada {} bilangan ganjil dan {} bilangan genap".format(n_ganjil, n_genap)) def reset(): storage.clear() print("Silahkan isi list lagi..") # # # loop = True while loop: menu() pilihan = int(input("Pilih menu: ")) if pilihan == 1: isi_list() elif pilihan == 2: lihat_list() elif pilihan == 3: sort_ascending() elif pilihan == 4: sort_descending() elif pilihan == 5: min_max() elif pilihan == 6: ganjil_genap() elif pilihan == 7: reset() elif pilihan == 8: loop = False print("Terima kasih!") else: print("Salah input, masukkan 1-8 :)")
PHP
UTF-8
823
2.546875
3
[]
no_license
<?php /** * Created by PhpStorm. * User: p2 * Date: 6/10/14 * Time: 1:46 AM */ namespace Main\Entity\View; /** * @Entity * @Table(name="q_dru") */ class QDru extends BaseEntity { /** * @Id * @Column(type="integer") */ protected $vn_id; /** * @Column(type="string") */ protected $timedru; /** * @param mixed $vn_id */ public function setVnId($vn_id) { $this->vn_id = $vn_id; } /** * @return mixed */ public function getVnId() { return $this->vn_id; } /** * @param mixed $timedru */ public function setTimedru($timedru) { $this->timedru = $timedru; } /** * @return mixed */ public function getTimedru() { return $this->timedru; } }
Python
UTF-8
1,362
2.625
3
[]
no_license
#!/usr/bin/env python # # Print the label volumes from all labels a folder # # label_vols <dir> [<dir> ...] # import sys import os import os.path import glob import subprocess import StringIO def execute(command, input = "", dry_run = False, stdout = 2): """Spins off a subprocess to run the cgiven command""" if not dry_run: proc = subprocess.Popen(command.split(), stdin = subprocess.PIPE, stdout = stdout, stderr = 2) out, err = proc.communicate(input) if proc.returncode != 0: raise Exception("Returns %i :: %s" %( proc.returncode, command )) return (out, err) if __name__ == '__main__': filenames = sys.argv[1:] if len(sys.argv) == 1: filenames = sys.stdin labels = None for f in filenames: f = f.strip() try: if labels is None: o, e = execute("print_all_labels %s" % f, stdout = subprocess.PIPE) labels = [ line.split(" ")[1] for line in o.strip().split("\n") ] print ",".join(["file"] + labels) o, e = execute("mincstats -quiet -binvalue %s -volume %s" % \ (",".join(labels), f), stdout = subprocess.PIPE) volumes = o.split("\n") print ",".join([f] + volumes) except: pass
Markdown
UTF-8
1,068
2.96875
3
[ "MIT" ]
permissive
--- title: Mushroom (picture) hunting in loblolly forest in Gainesville. description: perfect weather. date: 2020-11-17 tags: - mushroom hunting layout: layouts/post.njk --- This was my first real walk in the woods since taking the auto train down to Florida. I don't know exactly what I was expecting--but despite the woods being very different, the mushrooms were mostly pretty familiar and similar to Maryland. That said I did spot a couple of new and intersting things. A new polyphore, mostly notable for the fact that it's a near perfect semi-circle. ![semi-circle polyphore](/img/2020_11_18_semi_circle.jpg) I also saw the fairly common oyster look-alike called that is usually called angel wings. Much more delicate than oystes and growing on hemlock or maybe cedar. ![angel wings](/img/2020_11_18_angel_wings.jpg) The woods itself were beautiful and surprisingly not lush or jungly. The pines needles must be somewhat allelopathic because the number of species growing below them was pretty limited. But, lots of beautiful palmettos do flourish.
Markdown
UTF-8
2,740
3.109375
3
[]
no_license
# Channel your inner Jason Bay: How to be productive on a new Team # ## by Ashish Dixit ## ### Abstract ### You've landed a great opportunity to work with some of the smartest people in the industry. You can barely contain the enthusiasm to learn and contribute to the team. You may not have all the required technical skills on day one, but you are confident that you will get there with the support from your team. It's exciting & stressful at the same time because you need to start contributing right away. A lot of developers find themselves in these shoes, just as I did in not-too-distant past. This talk offers specific strategies developers of all skill levels can use to start making an immediate impact. These strategies have enabled me to contribute quickly on a new team and I want to share it with you so that they can help you on each new project or team you work with. I also want to share specific gotchas and share some tips on how to adapt and continue to improve once you have become productive member of the team. The talk will primarily focus on: * Techniques for quickly learning a new codebase * Finding ways to have a significant impact quickly * Ways in which you can continue to be more awesome ### Additional Notes ### Anything in addition to the abstract the choosing committee should take into consideration. #### Intended Audience While this talk is from the perspective of someone new to the team, I am confident that it will help experienced developers better understand the mindset and needs of new team members necessary to help them onboard new developers quickly and effectively. In fact, anyone who is starting on a new team or on a new codebase can learn a few things from this talk. Furthermore, this talk will explain the mindset of new developers to their more experienced counterparts who are interested in creating a nurturing environment within their company, their city or the greater Ruby Community. #### Why I want to give this talk? In response to the scarcity of technical talent, there have been numerous initiatives to train people with limited or no programming experience so that they can be employed as an entry-level developer. However, there is very little conversation going on about what challenges these people feel when they find themselves on a new team. I hope that by talking about my experiences on boarding on a new team and lessons I learned since, I can start a conversation with others who are going through the same thing as well as members of technical community who find themselves mentoring new hires with limited experience. ## Social ## * [Blog](http://tundal45.github.com) * [@tundal45](http://twitter.com/tundal45) * [GitHub](https://github.com/tundal45)
Java
UTF-8
3,271
2.4375
2
[]
no_license
package domain; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; /** * * @author JONATAN */ @Entity @NamedQueries({ @NamedQuery(name="Cliente.findAll", query="SELECT c FROM Cliente c"), @NamedQuery(name="Cliente.findByIdCliente", query="SELECT c FROM Cliente c WHERE c.idCliente=:idCliente"), @NamedQuery(name="Cliente.findByNombre", query="SELECT c FROM Cliente c WHERE c.nombre=:nombre"), @NamedQuery(name="Cliente.findByApellido", query="SELECT c FROM Cliente c WHERE c.apellido=:apellido"), @NamedQuery(name="Cliente.findByEmail", query="SELECT c FROM Cliente c WHERE c.email=:email"), @NamedQuery(name="Cliente.findByTelefono", query="SELECT c FROM Cliente c WHERE c.telefono=:telefono"), @NamedQuery(name="Cliente.findBySaldo", query="SELECT c FROM Cliente c WHERE c.saldo=:saldo")}) @Table(name="cliente") public class Cliente implements Serializable { private static final long serialVersionUID=1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id_cliente") private int idCliente; private String nombre; private String apellido; private String email; private String telefono; private double saldo; public Cliente(){ } public Cliente(int idCliente){ this.idCliente=idCliente; } public Cliente(String nombre,String apellido,String email,String telefono,double saldo){ this.nombre=nombre; this.apellido=apellido; this.email=email; this.telefono=telefono; this.saldo=saldo; } public Cliente(int idCliente, String nombre, String apellido, String email, String telefono, double saldo) { this.idCliente = idCliente; this.nombre = nombre; this.apellido = apellido; this.email = email; this.telefono = telefono; this.saldo = saldo; } public int getIdCliente() { return idCliente; } public void setIdCliente(int idCliente) { this.idCliente = idCliente; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getApellido() { return apellido; } public void setApellido(String apellido) { this.apellido = apellido; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getTelefono() { return telefono; } public void setTelefono(String telefono) { this.telefono = telefono; } public double getSaldo() { return saldo; } public void setSaldo(double saldo) { this.saldo = saldo; } @Override public String toString() { return "Cliente{" + "idCliente=" + idCliente + ", nombre=" + nombre + ", apellido=" + apellido + ", email=" + email + ", telefono=" + telefono + ", saldo=" + saldo + '}'; } }
Java
UTF-8
2,936
2.015625
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 com.parentabc.service.impl; import com.parentabc.dto.BasePageQueryReq; import com.parentabc.dto.BasePaginationResult; import com.parentabc.entity.Question; import com.parentabc.service.IQuestionService; import java.util.Date; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * * @author youguilin */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:spring/spring-context.xml"}) public class QuestionServiceImplTest { @Autowired private IQuestionService instance; public QuestionServiceImplTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testAskQuestion() { System.out.println("askQuestion"); Question question = new Question(); question.setType(1); question.setStatus(1); question.setCreateDate(new Date()); question.setCreatorId(0); question.setQtitle("aaaa"); question.setQcontent("bbbbbb"); instance.askQuestion(question); } @Test public void testGetQuestions() { System.out.println("getQuestions"); BasePageQueryReq pageQueryReq = null; QuestionServiceImpl instance = new QuestionServiceImpl(); BasePaginationResult<Question> expResult = null; BasePaginationResult<Question> result = instance.getQuestions(pageQueryReq); } @Test public void testGetQuesDetail() { System.out.println("getQuesDetail"); int qId = 0; QuestionServiceImpl instance = new QuestionServiceImpl(); Question expResult = null; Question result = instance.getQuesDetail(qId); } @Test public void testGetQuesSimple() { System.out.println("getQuesSimple"); int qId = 0; QuestionServiceImpl instance = new QuestionServiceImpl(); Question expResult = null; Question result = instance.getQuesSimple(qId); } @Test public void testUpdateQuestion() { System.out.println("updateQuestion"); Question question = null; QuestionServiceImpl instance = new QuestionServiceImpl(); instance.updateQuestion(question); } }
Markdown
UTF-8
5,870
2.65625
3
[]
no_license
# Alokai ## Summary: * A young apprentice engineer discovers an artifact that grants him magical abilities and journeys to the center of the Empire to deliver a warning about impending magical armageddon. ## Motivation: * wants to find his place within greater whole * admires well-constructed things (buildings, crafted items, stories) * feels justice in trading individual happiness for collective happiness ## Goal: * travel to the capital of the Empire (Dalga Mak) to warn the Emperor of the magical armageddon ## Conflict: * **External**:   * magic events slow his progress   * politics/wars slow his progress   * antagonist steals his part of the artifact * **Internal**:   * fear of loneliness ## Epiphany: * the magic in the world is imbalanced and must be balanced * leadership through sacrifice can change hearts and minds and is key to restoring balance to the world ## Map travel path: Galube'i > Talnu Va'nua > On ship > Papak port > Ship crash at Imis > Atere > Donzul > Tehmus > Sanci > Dalga Mak > Shortcut to eastern shore and board ship > Hehtaa > Ihnis ## Character Synopsis Alokai is coming of age in a relatively quiet island village on the border of the Empire. He was adopted by the island's Master Builder as an orphaned child and learned the trade of drafting and planning the larger buildings and settlements of the island. His father is respected amongst the people (and also a valuable/rare trade) and is given some latitude in engaging in eccentric hobbies like mechanical engineering. While during the day Alokai assists in what he feels is boring drafts of alehouses, inns, town squares, travel road infrastructure, during the evenings he indulges in building mechanical contraptions and sketching conceptual ideas. He discovers a piece of a mysterious artifact in a remote job site, and soon after begins feeling connections to magic. He is sometimes able to perceive the roads by which magic travels - lines of connection between living and non-living things. He gains a companion - a magical creature called a featherhound. It can speak only to Alokai. Alokai is scared and confused of his magical affinities at first, but begins to explore and experiment with his new abilities with the help and encouragement of the featherhound. Around this time, tremors and earthquakes nearly destroy the island. Alokai is the only one who can perceive the source of the destruction as magical and against his village's wishes he sets out to inform the Empire of the coming magical destruction (of which only he can see and sense). He determines the fastest journey to Dalga Mak is a ship to Donzul.  After evading disaster through piracy and gaining a congenial scoundrel companion he gets to the small port of Papak for resupply. Antagonistic magical creatures spawn, inhibiting their progress. The ship crashes as it rounds the bottom of the continent and they go on foot to Imis.  He aids Imis by using his engineering skills to solve a big problem.  Additionally, small confrontations between rebellion idealogies and Empire supporters interrupt their journey and require clever handling to escape. Along the way, he begins to sense Runa's growing power from a distance. He can also sense her journey's trajectory paralleling his own. They begin to interact with each other through their magical ability, and they develop a relationship. In the great city of Dalga Mak, Runa and Alokai meet in person as forces of the Empire and Rebellion clash in a large confrontation. Here he chooses to aid the city of Dalga Mak with defenses to protect the innocent, but Runa interprets this as working for the enemy. He is betrayed by Runa and she steals his artifact which dampens his magical powers. She reforges the two pieces into one, and the magical chaos in the land increases.  However, during his time in Dalga Mak he gains a third companion - a cosmopolitan scribe. After the battle, as Alokai continues in his weakend state to the Temple at Ihnis he learns with the help of his companions that he has done this quest before in a different time, as an older version of himself, and that he did it with Runa and that they failed in their quest because their power imbalance with the world was unsustainable. This is also the reason for the pending armageddon: the imbalance. He resolves to prevent Runa from succeeding in her quest, as her power would grow and destroy the world. He confronts her in the Temple at Ihnis as she is taking power, but he fails to stop her, but she is struggling against executing him and so imprisons him instead. She takes rulership of the Empire. He realizes that the only way to achieve balance is to destroy the artifact and sacrifice himself so that only Runa remains. His companions who escaped capture find a way to free him from prison, but he doubles back and confronts Runa a second time. This time he uses the last of his power to empty himself into her mind, losing his life in the process. He succeeds, the magic balance is restored.
Java
UTF-8
5,367
2.015625
2
[]
no_license
package com.wk.platform.batch; import com.wk.bean.Batch; import com.wk.bean.BatchItem; import com.wk.common.constant.Const; import com.wk.common.util.TimeUtil; import com.wk.common.vo.PageList; import com.wk.common.vo.Result; import com.wk.commonservice.service.CommonService; import com.wk.commonservice.service.SeqService; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.HashMap; import java.util.List; import java.util.Map; @Service public class BatchServiceImpl implements BatchService { @Autowired private BatchRepo batchRepo; @Autowired private CommonService commonService; @Autowired private SeqService seqService; @Autowired private BatchItemRepo batchItemRepo; @Transactional @Override public Result<Batch> addBatch(Batch batch, String operateUserId) { Batch b = batchRepo.findFirstByBatchNameAndCustomerId(batch.getBatchName(), batch.getCustomerId()); if(b != null){ return Result.error("批次名称已存在"); } String batchId = seqService.getNextBusinessId(Const.BZ_BATCH, batch.getCustomerId(), 2); batch.setBatchId(batchId); int currentInSecond = TimeUtil.getCurrentInSecond(); batch.setCreateTime(currentInSecond); batch.setUpdateTime(currentInSecond); Batch newBatch = batchRepo.saveAndFlush(batch); return Result.success(newBatch); } @Override public Result updateBatch(Batch batch, String operateUserId) { Batch b = batchRepo.findFirstByBatchNameAndCustomerIdAndBatchIdNot(batch.getBatchName(), batch.getCustomerId(), batch.getBatchId()); if(b != null){ return Result.error("批次名称已存在"); } int currentInSecond = TimeUtil.getCurrentInSecond(); batch.setUpdateTime(currentInSecond); batchRepo.saveAndFlush(batch); return Result.success(); } @Override public Result deleteBatch(String batchId, String operateUserId) { return null; } @Override public Result<List<Batch>> getBatchList(String keyword, String customerId, String operateUserId) { List<Batch> batches = batchRepo.findAllByCustomerId(customerId); return Result.success(batches); } @Override public Result<BatchItem> addBatchItem(BatchItem batchItem, String operateUserId) { String batchId = batchItem.getBatchId(); BatchItem b =batchItemRepo.findFirstByBatchIdAndItemId(batchId,batchItem.getItemId()); if(b != null){ return Result.error("自定义编号已存在"); } b = batchItemRepo.getByTime(batchId, batchItem.getBeginTime(),batchItem.getEndTime()); if(b != null){ return Result.error("所选时间已存在自定义批次"); } BatchItem newItem = batchItemRepo.saveAndFlush(batchItem); return Result.success(newItem); } @Transactional @Override public Result updateBatchItem(BatchItem batchItem, String operateUserId) { String batchId = batchItem.getBatchId(); BatchItem b =batchItemRepo.findFirstByBatchIdAndItemIdAndIdNot(batchId,batchItem.getItemId(),batchItem.getId()); if(b != null){ return Result.error("自定义编号已存在"); } int id = batchItem.getId(); b = batchItemRepo.getByTimeNotId(batchId, batchItem.getBeginTime(),batchItem.getEndTime(),id); if(b != null){ return Result.error("所选时间已存在自定义批次"); } batchItemRepo.saveAndFlush(batchItem); return Result.success(); } @Transactional @Override public Result deleteBatchItem(String itemId, String operateUserId) { batchItemRepo.deleteByItemId(itemId); return Result.success(); } @Override public Result<PageList<BatchItem>> getBatchItemPageList(String keyword, String batchId, int page, int size, String operateUserId) { String sql = "SELECT * FROM batch_item WHERE batch_id=:batchId"; Map<String,Object> param = new HashMap<>(); param.put("batchId",batchId); if(StringUtils.isNotBlank(keyword)){ sql += " AND (id LIKE :keyword)"; param.put("keyword","%"+keyword+"%"); } Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "beginTime"); Page<BatchItem> list = commonService.pageBySql(sql,param,pageable,BatchItem.class); return Result.success(new PageList<>(list.getContent(),list.getTotalElements(),page,size)); } @Override public Result<List<BatchItem>> getBatchItemList(String customerId, String operateUserId) { String sql = "SELECT * FROM batch_item WHERE batch_id like :k"; Map<String,Object> param = new HashMap<>(); param.put("k", customerId+"%"); List<BatchItem> batchItems = commonService.listBySql(sql, param, BatchItem.class); return Result.success(batchItems); } }
TypeScript
UTF-8
1,590
2.8125
3
[]
no_license
import { Option, WeightedValue } from "./index"; import { getGroups } from "./utils"; import path from "path"; interface TableEntry { w: number, options: Option[] } interface Tables { [name: string]: TableEntry } const tables = {} as Tables; function importAll(r: any) { r.keys().forEach((key: string) => { const name = path.basename(key, ".json"); const table: WeightedValue[] = r(key); let totalWeight = 0; const options = table.map(row => { const w = row.w > 0 ? row.w : 0; totalWeight += w; return { ...row, w, v: getGroups(row.v) || [], original: row.v } }); var convertedTable = { w: totalWeight, options }; tables[name] = convertedTable; }); } importAll((require as any).context('./tables/', false, /\.json$/)); export default tables; export interface NamedOption extends Option { name?: string; } export interface TableReferenceOption extends NamedOption { table: string; } export function getNamedTableOptions(tablename: string): NamedOption[] { const options = tables[tablename].options; return options as NamedOption[]; } export function getTableReferenceOptions(tablename: keyof Tables): TableReferenceOption[] { const options = tables[tablename].options as any; for (const opt of options) { if (!("table" in opt)) { throw new Error(`Missing "table" property in table ${tablename} option ${opt.original}`); } } return options as TableReferenceOption[]; } export function getTableOptions(tablename: string) { return tables[tablename].options; }
Java
UTF-8
1,312
2.078125
2
[]
no_license
package com.cabletech.troublemanage.beans; import com.cabletech.commons.base.*; public class AccidentDetailBean extends BaseBean{ private String id; private String accidentid; private String corecode; private String tempfixedtime; private String fixedtime; private String diachronic; public AccidentDetailBean(){ } public void setId( String id ){ this.id = id; } public void setAccidentid( String accidentid ){ this.accidentid = accidentid; } public void setCorecode( String corecode ){ this.corecode = corecode; } public void setTempfixedtime( String tempfixedtime ){ this.tempfixedtime = tempfixedtime; } public void setFixedtime( String fixedtime ){ this.fixedtime = fixedtime; } public void setDiachronic( String diachronic ){ this.diachronic = diachronic; } public String getId(){ return id; } public String getAccidentid(){ return accidentid; } public String getCorecode(){ return corecode; } public String getTempfixedtime(){ return tempfixedtime; } public String getFixedtime(){ return fixedtime; } public String getDiachronic(){ return diachronic; } }
C++
UTF-8
946
2.796875
3
[]
no_license
#include <iostream> #include <algorithm> #include <math.h> #define MAXN 30 using namespace std; int n; int rs[MAXN]; int arr[MAXN]; bool vis[MAXN]; bool is_ss(int x) { if(0==x || 1==x) return false; int t = sqrt(x); for(int i=2; i<=t; i++) { if(x%i == 0) return false; } return true; } void dfs(int x) { if(x == n+1) { int t = arr[rs[n]] + arr[rs[1]]; if(is_ss(t)) { for(int i=1, c=0; i<=n; i++) { if(c++) printf(" "); printf("%d", arr[rs[i]]); } printf("\n"); } return ; } for(int i=1; i<=n; i++) { if(!vis[i]) { int t = arr[rs[x-1]] + arr[i]; if(!is_ss(t)) continue ; rs[x] = i; vis[i] = true; dfs(x+1); vis[i] = false; } } } int main() { freopen("test", "r", stdin); int count = 1; for( ; EOF != scanf("%d", &n); ) { printf("Case %d:\n", count++); for(int i=1; i<=n; i++) arr[i] = i; vis[1] = true; rs[1] = 1; dfs(2); printf("\n"); } return 0; }
C#
UTF-8
1,227
2.71875
3
[ "MIT" ]
permissive
#region Usings using System; using System.Globalization; using NUnit.Framework; #endregion namespace Extend.Testing { [TestFixture] public partial class DateTimeExTest { [Test] public void ToLongDateStringTest() { var dateTime = DateTime.Now; var expected = dateTime.ToString( "D" ); var actual = DateTimeEx.ToLongDateString( dateTime ); Assert.AreEqual( expected, actual ); } [Test] public void ToLongDateStringTest1() { var dateTime = DateTime.Now; var expected = dateTime.ToString( "D", DateTimeFormatInfo.CurrentInfo ); // ReSharper disable once AssignNullToNotNullAttribute var actual = dateTime.ToLongDateString( DateTimeFormatInfo.CurrentInfo ); Assert.AreEqual( expected, actual ); } [Test] public void ToLongDateStringTest2() { var dateTime = DateTime.Now; var expected = dateTime.ToString( "D", CultureInfo.InvariantCulture ); var actual = dateTime.ToLongDateString( CultureInfo.InvariantCulture ); Assert.AreEqual( expected, actual ); } } }
Ruby
UTF-8
554
3.390625
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# My Code here.... def map_to_negativize(source_array) source_array.map {|s| s * -1 } end def map_to_no_change(source_array) source_array end def map_to_double(source_array) source_array.map {|s| s * 2} end def map_to_square(source_array) source_array.map {|s| s * s} end def reduce_to_total(source_array, starting_point = 0) source_array.reduce(starting_point) {|sa , sp| sa + sp} end def reduce_to_all_true(source_array) source_array.all? end def reduce_to_any_true(source_array) source_array.any? end
Java
UTF-8
4,151
2.359375
2
[]
no_license
package repository; import com.auth0.jwt.JWT; import com.auth0.jwt.algorithms.Algorithm; import model.UserViewModel; import org.hibernate.Session; import org.hibernate.Transaction; import utils.Hibernate; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Date; public class User { public model.User create(String name, String email, String password) throws NoSuchAlgorithmException { Session session = Hibernate.getSessionFactory().openSession(); model.User user = new model.User(name, email, password); session.save(user); Hibernate.shutdown(); return user; } public static String login(String email, String password) throws NoSuchAlgorithmException { Session session = Hibernate.getSessionFactory().openSession(); CriteriaBuilder cb = session.getCriteriaBuilder(); CriteriaQuery<model.User> cq = cb.createQuery(model.User.class); Root<model.User> pod = cq.from(model.User.class); CriteriaQuery<model.User> like = cq.select(pod); MessageDigest md = MessageDigest.getInstance("SHA-512"); byte[] hashedPassword = md.digest(password.getBytes(StandardCharsets.UTF_8)); StringBuilder sb = new StringBuilder(); for (byte b : hashedPassword) { sb.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1)); } password = sb.toString(); TypedQuery<model.User> result = session.createQuery(like.where(cb.equal(pod.<String>get("email"), email), cb.equal(pod.<String>get("password"), password))).setMaxResults(5); model.User resUser = result.getSingleResult(); Algorithm algorithm = Algorithm.HMAC256("ap0ll0s3cret"); return JWT.create() .withSubject(resUser.getId().toString()) .withIssuer("Apollo") .withIssuedAt(new Date()) .sign(algorithm); } public static String signup(model.User user) throws NoSuchAlgorithmException { Session session = Hibernate.getSessionFactory().openSession(); MessageDigest md = MessageDigest.getInstance("SHA-512"); byte[] hashedPassword = md.digest(user.getPassword().getBytes(StandardCharsets.UTF_8)); StringBuilder sb = new StringBuilder(); for (byte b : hashedPassword) { sb.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1)); } user.setPassword(sb.toString()); session.save(user); session.persist(user); session.close(); Algorithm algorithm = Algorithm.HMAC256("ap0ll0s3cret"); return JWT.create() .withSubject(user.getId().toString()) .withIssuer("Apollo") .withIssuedAt(new Date()) .sign(algorithm); } public static model.User update(model.User user) throws NoSuchAlgorithmException { Session session = Hibernate.getSessionFactory().openSession(); MessageDigest md = MessageDigest.getInstance("SHA-512"); byte[] hashedPassword = md.digest(user.getPassword().getBytes(StandardCharsets.UTF_8)); StringBuilder sb = new StringBuilder(); for (byte b : hashedPassword) { sb.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1)); } user.setPassword(sb.toString()); model.User userInDB = session.get(model.User.class, user.getId()); userInDB.updateUser(user); Transaction tx = session.beginTransaction(); session.saveOrUpdate(userInDB); tx.commit(); session.close(); return user; } public static model.User byId(Integer id){ Session session = Hibernate.getSessionFactory().openSession(); return session.get(model.User.class, id); } }
Java
UTF-8
1,635
2.25
2
[]
no_license
package com.rocket.sivico.Adapters; import android.graphics.Color; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.rocket.sivico.Data.Report; import com.rocket.sivico.R; import com.rocket.sivico.Utils; import com.squareup.picasso.Picasso; /** * Created by JuanCamilo on 7/10/2017. */ public class ReportHolder extends RecyclerView.ViewHolder { public CardView cv; TextView title; TextView date; TextView hour; ImageView image; public ReportHolder(View itemView) { super(itemView); cv = itemView.findViewById(R.id.card_view_report); title = itemView.findViewById(R.id.report_title); date = itemView.findViewById(R.id.report_date); hour = itemView.findViewById(R.id.report_hour); image = itemView.findViewById(R.id.report_image); } public void bind(Report report) { this.title.setText(Utils.formatString(report.getDescription())); this.date.setText(Utils.getFormatDate(Long.parseLong(report.getDate()))); this.hour.setText(Utils.getHour(Long.parseLong(report.getDate()))); this.image.setBackgroundColor(Color.parseColor(report.getColor())); Log.e("bind holder", report.getEvidence().get("img1").toString()); Picasso.with(this.cv.getContext()) .load(report.getEvidence().get("img1").toString()) .fit() .placeholder(R.drawable.ic_file_upload) .into(this.image); } }
Shell
UTF-8
317
2.578125
3
[]
no_license
#!/bin/bash source functions.sh build_project start_server $1 $2 wait_till_started $1 simulate_network_partition $2 sleep 10s printf "\nInvoking /health endpoint after N/W partition...\n" curl http://localhost:$1/actuator/health kill -9 $pid_java >> $log_file fix_simulated_network_partition printf "\nDONE!\n"
Python
UTF-8
506
3.125
3
[]
no_license
import random quantity = int(input('Сколько сгенерировать файлов: ')) for i in range(quantity): width = random.randint(1, 15) height = random.randint(1, 15) _list = [] for h in range(height): output_string = '' for w in range(width): output_string += str(random.randint(0, 1)) + ' ' _list.append(output_string) with open('moon_' + str(i) + '.txt', 'w') as f: for _str in _list: f.write(_str + '\n')
C#
UTF-8
952
2.6875
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController:MonoBehaviour { [SerializeField] private GameObject uno; [SerializeField] private GameObject dos; [SerializeField] private GameObject tres; [SerializeField] private GameObject cuarto; [SerializeField] private GameObject quinto; void Start() { string monster = PlayerPrefs.GetString("player"); GameObject monsterGO = new GameObject(); if(monster == "1" ){ monsterGO = uno; } if(monster == "2"){ monsterGO = dos; } if(monster == "3"){ monsterGO = tres; } if(monster == "4"){ monsterGO = cuarto; } if (monster == "5") { monsterGO = quinto; } Instantiate(monsterGO,transform.position, Quaternion.identity); } }
Python
UTF-8
1,217
2.78125
3
[]
no_license
import turtle as tu door = [ ['set', (20,0)], ['rt', -90], ['fd', 40], ['rt', 90], ['fd', 40], ['rt', 90], ['fd', 40], ] wall = [ ['set', (20,0)], ['sh', 180], ['fd', 20], ['rt', 90], ['fd', 80], ['rt', 90], ['fd', 80], ['rt', 90], ['fd', 80], ['rt', 90], ['fd', 60], ] roof = [ ['set', (0,80)], ['sh', 0], ['rt', -60], ['fd', 80], ['rt', -(360 - 120)], ['fd', 80], ] zones = { 'door': {'color': 'red', 'layout': door}, 'wall': {'color': 'black', 'layout': wall}, 'roof': {'color': 'green', 'layout': roof}, } for zone,details in zones.items(): tu.color(details['color']) tu.end_fill() for step in details['layout']: if step[0] == 'fd': tu.fd(step[1]) elif step[0] == 'rt': tu.rt(step[1]) elif step[0] == 'fl': if step[1] == True: tu.begin_fill() else: tu.end_fill() elif step[0] == 'set': tu.up() tu.setx(step[1][0]) tu.sety(step[1][1]) tu.down() elif step[0] == 'sh': tu.setheading(step[1]) tu.up() tu.done()
Markdown
UTF-8
1,762
3.109375
3
[]
no_license
Q: ![](./Figure/200(1).JPG) 나의 솔루션: ```python class Solution: def numIslands(self, grid: List[List[str]]) -> int: def is_valid(x, y): if 0 <= x < len(grid) and 0 <= y < len(grid[i]): return True else: return False def recursive_dfs_search(vertex_x_y): for coord in coordinate: temp_x = vertex_x_y[0] + coord[0] temp_y = vertex_x_y[1] + coord[1] if (is_valid(temp_x, temp_y)) and ((temp_x, temp_y) not in discovered) and (grid[temp_x][temp_y] == "1"): discovered.add((temp_x, temp_y)) recursive_dfs_search((temp_x, temp_y)) coordinate = [(-1, 0), (0, 1), (1, 0), (0, -1)] #up, right, down, left island_count = 0 discovered = set() for i in range(len(grid)): for j in range(len(grid[i])): if (i, j) not in discovered and grid[i][j] == "1": discovered.add((i, j)) recursive_dfs_search((i, j)) island_count += 1 return island_count ``` 재귀적 dfs로 풀었다. 재귀적으로 좌표를 탐색하는 Inner function을 만들고 탐색할때마다 유효한 좌표를 찾았다고 표시한다. 탐색을 끝내고 나면 카운트를 1한다. 그렇게 모든 그리드에 대해서 좌표를 확인하면 카운트를 리턴하고 종료. ![](./Figure/200(2).JPG) 책의 솔루션: 비슷한 접근법이되, 공간 복잡도를 줄이기 위해서 discorved를 따로 생성하지 않고 발견한 1을 그냥 0으로 만들어 버린다.
Python
UTF-8
1,823
2.6875
3
[ "MIT" ]
permissive
import numpy as np node_name_to_index = dict() node_index_to_att = dict() node_index_to_class = dict() label_to_class = dict() index = 0 class_label = 0 content_file = open('./citeseer.content', "r").readlines() for line in content_file: vector = [x for x in line.strip('\n').split('\t')] if not label_to_class.__contains__(vector[3704]): label_to_class[vector[3704]] = class_label class_label += 1 node_name_to_index[vector[0]] = index node_index_to_att[index] = vector[1:3704] node_index_to_class[index] = label_to_class[vector[3704]] index += 1 nodN = len(node_name_to_index) dim = len(node_index_to_att[0]) edge_num=0 adj = np.zeros((nodN, nodN)) cite_file = open('./citeseer.cites', "r").readlines() for line in cite_file: vector = [x for x in line.strip('\n').split('\t')] if not node_name_to_index.__contains__(vector[0]) \ or not node_name_to_index.__contains__(vector[1])\ or vector[0]==vector[1]: continue start = node_name_to_index[vector[0]] end = node_name_to_index[vector[1]] # if start==end: # print(str(vector[0])+'->'+str(vector[1])) # #print(str(start) + '->' + str(end)) adj[start][end] = 1 adj[end][start] = 1 edge_num+=2 print('edge_num:',edge_num) with open('./citeseer_adj.txt', 'w') as adj_file: for i in range(nodN): for j in range(nodN): adj_file.write(str(adj[i][j]) + ',') adj_file.write('\n') with open('./node_features.txt', 'w') as feature_file: for i in range(nodN): for j in range(dim): feature_file.write(node_index_to_att[i][j] + ',') feature_file.write('\n') with open('./node_labels.txt', 'w') as label_file: for i in range(nodN): label_file.write(str(node_index_to_class[i]) + '\n')
C++
UTF-8
1,523
3.1875
3
[]
no_license
#include <iostream> #include <stdint.h> #include <vector> #include <deque> #include <sstream> #include <cstdlib> #include <string> #include <math.h> std::string PrimeCalculate(uint64_t input); uint64_t StrToUint64_t(std::string input); int main(){ std::string a = "90090"; std::string b = "56473"; std::cout<<"a="<<a<<std::endl; std::cout<<"b="<<b<<std::endl; uint64_t a_value = StrToUint64_t(a); uint64_t b_value = StrToUint64_t(b); std::string result_a = PrimeCalculate(a_value); std::string result_b = PrimeCalculate(b_value); std::cout<<"a="<<result_a<<std::endl; std::cout<<"b="<<result_b<<std::endl; } uint64_t StrToUint64_t(std::string input){ std::stringstream stream(input); uint64_t result; stream>>result; return result; }; std::string PrimeCalculate(uint64_t input){ std::vector<uint64_t> vector_prime; int i =2; while(i!=input){ int re = input%i; if(re==0){ vector_prime.push_back(i); input /= i; } else{ i++; } } vector_prime.push_back(input); std::string primelist=""; for(int j=0;j<vector_prime.size();j++) { if(j!=0) primelist += "x"; std::stringstream a; a<<vector_prime[j]; std::string prime = a.str(); primelist += prime; } return primelist; }
C++
UTF-8
1,232
2.84375
3
[]
no_license
/* * ADC.cpp * * Created on: 17 Aug 2019 * Author: Connor */ #include "ADC.h"; void ADC_Init() { //Set all analogue ports to inputs DDRC = 0x00; //ADC Enable ADCSRA |= (1 << ADEN); //ADC Frequency ADCSRA |= (1 << ADPS0); ADCSRA |= (1 << ADPS1); ADCSRA |= (1 << ADPS2); // AREF = AVcc ADMUX |= (1 << REFS0); //Do first read so as to reduce future conversion time ADCSRA |= (1 << ADSC); } int ADC_Read() { //Start conversion ADCSRA |= (1 << ADSC); //Wait for conversion to complete while (ADCSRA & (1 << ADSC)); return (ADC); } char ADC_Button() { //Change to A0 ADMUX &= ~(1 << MUX0 | 1 << MUX1 | 1 << MUX2 | 1 << MUX3); //Set the frequency to 128 ADCSRA |= (1 << ADPS0); ADCSRA |= (1 << ADPS1); ADCSRA |= (1 << ADPS2); int adcValue = ADC_Read(); if (adcValue <= 40) { //Real value 0 return 'R'; //Right } if (adcValue <= 110) { //Real value 99 return 'U'; //Up } if (adcValue <= 270) { //Real value 256 return 'D'; //Down } if (adcValue <= 420) { //Real value 410 return 'L'; //Left } if (adcValue <= 650) { //Real value 640 return 'S'; //Select } return 0; //Nothing selected (NULL) }
C++
UTF-8
9,680
3.140625
3
[]
no_license
/*! Chris Miller (cmiller@fsdev.net), CS116 *! Copyright (C) 2009 FSDEV. Aw richts pitten by. *! Academic endorsement. This code is not licensed for commercial use. *! 20091003, Ch. 10 Asgn */ #include <iostream> #include <fstream> #include <vector> #include <exception> #include <stdexcept> #include <string> #include <algorithm> const int not_a_reading= -7777; const int not_a_month = -1; const int implausible_min = -200; const int implausible_max = 200; std::vector<std::string> month_input_tbl; std::vector<std::string> month_print_tbl; struct Day { std::vector<double> hour; Day(); double mean(); std::vector<double>& populate_reading_vector(); }; struct Month { int month; std::vector<Day> day; Month() :month(not_a_month), day(32) { } double mean(); std::vector<double>& populate_reading_vector(); }; struct Year { int year; std::vector<Month> month; Year() :month(12) { } double mean(); std::vector<double>& populate_reading_vector(); }; struct Reading { int day; int hour; double temperature; }; bool is_valid(const Reading& r); void end_of_loop(std::istream& ist, char term, const std::string& message); void init_input_tbl(std::vector<std::string>& tbl); void init_print_tbl(std::vector<std::string>& tbl); int month_to_int(std::string s); std::string int_to_month(int i); bool all_blank(const Month& m); std::istream& operator >> (std::istream& is, Reading& r); std::istream& operator >> (std::istream& is, Month& m); std::istream& operator >> (std::istream& is, Year& y); std::ostream& operator << (std::ostream& os, Reading& r); std::ostream& operator << (std::ostream& os, Month& m); std::ostream& operator << (std::ostream& os, Year& y); int main (int argc, char * const argv[]) { /* Write a program that creates a file of data in the form of the temperature Reading type defined in §10.11. Fill the file with at least 50 temperature readings. DONE Call this program store_temps.cpp and the file it creates raw_temps.txt. Write a program that reads the data from raw_temps.txt into a vector and then calculates the mean and median temperatures in your data set. Call this program temp_stats.cpp. Modify the store_temps.cpp program to include a temperature suffix c for Celsius or f for Fahrenheit temperatures. Then modify the temp_stats.cpp program to test each temperature; converting the Celsius readings to Fahrenheit before putting them into the vector. */ std::cout << argv[0] << std::endl; init_print_tbl(month_print_tbl); init_input_tbl(month_input_tbl); std::vector<Year> y_input= std::vector<Year>(); std::vector<double> all_readings= std::vector<double>(); std::ifstream ifs("../../raw_temps.txt"); if(!ifs) { std::cerr << "cannot open file!" << std::endl; throw std::runtime_error("cannot open file!"); } std::cout << "Program: " << std::endl; Year y; while(ifs >> y) { std::cout << y; std::cout << "Year "<< y.year << " mean reading: " << y.mean() << std::endl; all_readings = y.populate_reading_vector(); std::sort(all_readings.begin(), all_readings.end()); std::cout << "Mean reading for " << y.year << " " << all_readings[all_readings.size()/2] << std::endl; y_input.push_back(y); } std::cout << std::endl << "File: " << std::endl; ifs.close(); ifs.open("../../raw_temps.txt"); std::string in; while(ifs >> in) std::cout << in << ' '; // for(size_t i=0; i < y_input.size(); ++i) { // std::cout << "Year " << y_input[i].year << " mean reading: " << y_input[i].mean() << std::endl; // } // std::cout << "Program: " << std::endl; // for(size_t i=0; i<y_input.size(); ++i) { // std::cout << y_input[i]; // } return 0; } Day::Day() : hour(24) { for (size_t i = 0; i<hour.size(); ++i) hour[i]=not_a_reading; } double Day::mean() { double sum=0.0; int r=0; for(size_t i=0; i < hour.size(); ++i) { sum += (hour[i]==not_a_reading)?0.0:hour[i]; r+=(hour[i]==not_a_reading)?0:1; } return sum/r; } double Month::mean() { double sum=0.0; for(size_t i=0; i < day.size(); ++i) { sum += day[i].mean(); } return sum/day.size(); } double Year::mean() { double sum=0.0; for(size_t i=0; i < month.size(); ++i) sum+=month[i].mean(); return sum/month.size(); } std::vector<double>& Year::populate_reading_vector() { std::vector<double> toReturn= std::vector<double>(); for(size_t i = 0; i < month.size(); ++i) { std::vector<double> tmp=month[i].populate_reading_vector(); toReturn.insert(toReturn.end(), tmp.begin(), tmp.end()); } return *(new std::vector<double>(toReturn.begin(), toReturn.end())); } std::vector<double>& Month::populate_reading_vector() { std::vector<double> toReturn= std::vector<double>(); for(size_t i=0; i < day.size(); ++i) { std::vector<double> tmp=day[i].populate_reading_vector(); toReturn.insert(toReturn.end(), tmp.begin(), tmp.end()); } return *(new std::vector<double>(toReturn.begin(), toReturn.end())); } std::vector<double>& Day::populate_reading_vector() { std::vector<double> toReturn= std::vector<double>(); for(size_t i=0; i < hour.size(); ++i) { if(hour[i]!=not_a_reading) toReturn.push_back(hour[i]); } return *(new std::vector<double>(toReturn.begin(), toReturn.end())); } bool is_valid(const Reading& r) { if(r.day<1||31<r.day) return false; if(r.hour<0||23<r.hour) return false; if(r.temperature<implausible_min||implausible_max<r.temperature) return false; return true; } void end_of_loop(std::istream& ist, char term, const std::string& message) { if(ist.fail()) { ist.clear(); char ch; if(ist>>ch && ch==term) return; std::cerr << message << std::endl; throw std::runtime_error(message); } } void init_input_tbl(std::vector<std::string>& tbl) { tbl.push_back("jan"); tbl.push_back("feb"); tbl.push_back("mar"); tbl.push_back("apr"); tbl.push_back("may"); tbl.push_back("jun"); tbl.push_back("jul"); tbl.push_back("aug"); tbl.push_back("sep"); tbl.push_back("oct"); tbl.push_back("nov"); tbl.push_back("dec"); } void init_print_tbl(std::vector<std::string>& tbl) { tbl.push_back("January"); tbl.push_back("February"); tbl.push_back("March"); tbl.push_back("April"); tbl.push_back("May"); tbl.push_back("June"); tbl.push_back("July"); tbl.push_back("August"); tbl.push_back("September"); tbl.push_back("October"); tbl.push_back("November"); tbl.push_back("December"); } int month_to_int(std::string s) { for(int i=0; i<12; ++i) if (month_input_tbl[i]==s) return i; return -1; } std::string int_to_month(int i) { if(i<0||12<=i) { std::cerr << "bad month index" << std::endl; throw std::runtime_error("bad month index"); } return month_print_tbl[i]; } bool all_blank(const Month& m) { bool all_blank=true; for(size_t i=0; i < m.day.size(); ++i) { for(size_t j=0; j < m.day[i].hour.size(); ++j) if(m.day[i].hour[j]!=not_a_reading) { all_blank=false; break; } if(all_blank==false) break; } return all_blank; } std::istream& operator >> (std::istream& is, Reading& r) { char ch1; if(is>>ch1 &&ch1!='(') { is.unget(); is.clear(std::ios_base::failbit); return is; } char ch2; int d; int h; double t; is >> d >> h >> t >> ch2; if(!is || ch2!=')') { std::cerr << "Error: messed up reading!" << std::endl; throw std::runtime_error("messed up reading!"); } r.day = d; r.hour = h; r.temperature = t; return is; } std::istream& operator >> (std::istream& is, Month& m) { char ch=0; if(is >> ch && ch!='{') { is.unget(); is.clear(std::ios_base::failbit); return is; } std::string month_marker; std::string mm; is >> month_marker >> mm; if(!is || month_marker!="month") { std::cerr << "Error: bad start of month!" << std::endl; throw std::runtime_error("messed up month marker!"); } m.month = month_to_int(mm); Reading r; int duplicates = 0; int invalids = 0; while(is>>r) { if(is_valid(r)) { if(m.day[r.day].hour[r.hour] != not_a_reading) ++duplicates; m.day[r.day].hour[r.hour] = r.temperature; } else { ++invalids; } } if(invalids) { std::cerr << "invalid readings in month " << invalids << std::endl; throw std::runtime_error("invalid readings in month"); } if(duplicates) { std::cerr << "duplicate readings in month " << duplicates << std::endl; throw std::runtime_error("duplicate readings in month"); } end_of_loop(is,'}',"bad end of month"); return is; } std::istream& operator >> (std::istream& is, Year& y) { char ch; is >> ch; if(ch!='{') { is.unget(); is.clear(std::ios_base::failbit); return is; } std::string year_marker; int yy; is >> year_marker >> yy; if(!is || year_marker!="year") { std::cerr << "bad start of year" << std::endl; throw std::runtime_error("bad start of year"); } y.year = yy; while(true) { Month m; if(!(is >> m)) break; y.month[m.month] = m; } end_of_loop(is,'}',"bad end of year"); return is; } std::ostream& operator << (std::ostream& os, Reading& r) { os << "( " << r.day << ' ' << r.hour << ' ' << r.temperature << " )"; return os; } std::ostream& operator << (std::ostream& os, Month& m) { if(all_blank(m)) return os; os << "{ month " << month_input_tbl[(m.month>-1&&m.month<12)?m.month:0] << ' '; Reading r; for(size_t i=0; i < m.day.size(); ++i) { Day d = m.day[i]; for(size_t j=0; j<d.hour.size(); ++j) { if(d.hour[j]==not_a_reading) continue; r.day = i; r.hour = j; r.temperature = d.hour[j]; os << r << ' '; } } os << '}'; return os; } std::ostream& operator << (std::ostream& os, Year& y) { os << "{ year " << y.year << ' '; for(size_t i=0; i<y.month.size(); ++i) { if(all_blank(y.month[i])) continue; os << y.month[i] << " "; } os << '}'; return os; }
Python
UTF-8
6,222
3.234375
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Fri May 18 11:50:26 2018 @author: Chloe """ def getPoints(bboxes): """ Gets the points of the bounding boxes for detected instances Parameters ---------- bboxes : numpy array array containing points corresponding to bounding box Returns ------- [] : numpy array [instances,2] (u,v) coordinates for the centre and boundary box corners """ # Get centre topLeft = [] topRight = [] botLeft = [] botRight = [] centre = [] for i in range(bboxes.shape[0]): # Put into arrays for easier post-processing topLeft.append([bboxes[i, 1], bboxes[i, 0]]) botLeft.append([bboxes[i, 1], bboxes[i, 2]]) topRight.append([bboxes[i, 3], bboxes[i, 0]]) botRight.append([bboxes[i, 3], bboxes[i, 2]]) # Calculate horizontal and vertical radius (centre to bounding box) centre.append([0.5*(topLeft[i][1]+botLeft[i][1]), 0.5*(topRight[i][0]+topLeft[i][0])]) return(topLeft, botLeft, topRight, botRight, centre) def vectorAngle(v1, v2): """ Returns the angle in radians between vectors 'v1' and 'v2' Note ----- Using atan2 instead of cos to improve robustness w/ small angles Parameters ---------- v1 : numpy array vector 1 v2 : numpy array vector 2 Returns ------- ang : scalar angle Angle between v1 and v2 in radians. """ import numpy as np import numpy.linalg as la cosAng = np.dot(v1, v2) sinAng = la.norm(np.cross(v1, v2)) ang = np.arctan2(sinAng, cosAng) return(ang) def displayDetections(image, boxes, masks, ids, names, scores, angDiameter, distance): """ Take Mask-RCNN output and annotate image with details Parameters ---------- image : RGB image [height, width, 3] boxes : numpy array Array containing points corresponding to bounding box masks : image segmentation mask [height, width, instance num] Masks corresponding to pixels predicted to belong to object class. ids : numpy array [instances] Array of values corresponding to the detected class ID for each detected instance. For duckieDetection: 0 = background (ignored) 1 = Duckie names : numpy array [num classes] Array of class names for Mask-RCNN For duckieDetection, this is ['BG','Duckie'] scores : numpy array [1,instances] Array of values from 0-1, corresponding to the prediction confidence. 0 = no confidence, 1 = full confidence angDiameter : numpy array [instances] Predicted angular diameter distance : numpy array [instances] Predicted distance to the object, based on object size and angWidth Returns ------- image : RGB image [height, width, 3] Image with annotations """ import cv2 import numpy as np n_instances = boxes.shape[0] colors = randomColours(n_instances) if not n_instances: print('Detected: Nothing') else: assert boxes.shape[0] == masks.shape[-1] == ids.shape[0] print('Detected: ' + names[ids[0]]) for i, color in enumerate(colors): if not np.any(boxes[i]): continue y1, x1, y2, x2 = boxes[i] if (angDiameter[i] <= 0): caption = "C:'{}' L:{:.2f}%".format(names[ids[i]], float(scores[i]*100)) else: caption = "C:'{}' L:{:.2f}% W:{:.2f}rad D:{:.2f}mm".format(names[ids[i]], float(scores[i]*100), float(angDiameter[i]), float(distance[i])) mask = masks[:, :, i] image = applyMask(image, mask, color) image = cv2.rectangle(image, (x1, y1), (x2, y2), color, 2) image = cv2.putText(image, caption, (x1, y1), cv2.FONT_HERSHEY_COMPLEX, 0.7, color, 2) return image def colourRegion(image, mask): """Apply color effect on regions of detected objects in image. Parameters ---------- image : RGB image [height, width, 3] The image/frame upon which to put the colour effect. Passed from detect_and_colour() mask : image segmentation mask [height, width, instance num] Mask corresponding to pixels predicted to belong to object class. Returns from model.detect(). Used to determine which pixels to colour. Returns ------- detectFlag : boolean Indicates whether colour effect was implemented in frame. True == colour effect implemented False == colour effect not implemented img : The edited image, either in grayscale or with the colour effect. """ from skimage.color import rgb2gray, gray2rgb import numpy as np # Make a grayscale copy of the image gray = gray2rgb(rgb2gray(image))*255 # Collapse masks into a single layer mask = (np.sum(mask, -1, keepdims=True) >= 1) # Copy colour pixels in the masked region from the original colour image # Replace these pixels in the grayscale image if mask.shape[0] > 0: img = np.where(mask, image, gray).astype(np.uint8) detectFlag = True else: img = gray detectFlag = False return detectFlag, img def randomColours(N): import numpy as np # Random seed - VR46 #MotoGP np.random.seed(46) # Generate 3 random numbers randArray = np.random.rand(3) # Generate N number of colours colours = [tuple(255*randArray) for throwawayVar in range(N)] return(colours) def applyMask(image, mask, colour, alpha=0.5): """ Apply mask to image """ import numpy as np for n, c in enumerate(colour): image[:, :, n] = np.where(mask == 1, image[:, :, n] * (1 - alpha) + alpha * c, image[:, :, n]) return(image)
Markdown
UTF-8
1,777
2.796875
3
[ "MIT" ]
permissive
# Digitial_Adders This repository contains the project done on Parameterized Carry Look-ahead/Ripple Adders as a part of the CAD for VLSI Systems(CS6230) course at IIT Madras. This Repo contains code to Generate CLA &amp; CRA in verilog from HLL # How to run the code? * run the follow command to generate the N-bit CLA circuit in verilog. * Code will ask to input the value of N when you will run ./a.out enter any value in power of 2. g++ CLA_gen.cpp ./a.out 64 * After running the above command the CLA.v file will be generated in you current directory which is the verilog file for N-bit adder (N is 64 in this case) - run the follow command to generate the N-bit CRA circuit in verilog. - Code will ask to input the value of N when you will run ./a.out enter any value in power of 2. g++ RCA_gen.cpp ./a.out 64 - After running the above command the RCA.v file will be generated in you current directory which is the verilog file for N-bit adder (N is 64 in this case) # Comparative Analysis ![alt text](https://github.com/Jash-Khatri/Digitial_Adders/blob/main/index.png) ![alt text](https://github.com/Jash-Khatri/Digitial_Adders/blob/main/index1.png) * Green line shows the result of CLA and Red line shows the result of CRA. * We can see that time taken for CLA is much lesser than CRA as value of N increases as curve for CLA is almost flat which shows that CLA is much faster than CRA. * Number of NAND gates required to realize CLA are more than that for CRA. This shows that CLA is much costlier to than CRA. * For this experiment we can conclude that if we consider cost then CRA is better than CLA and if we consider the execution time then CLA ( O(log_2 n) ) is better then CRA ( O(n) ). Hence we need to look for trade-of between both of them.
Ruby
UTF-8
224
3
3
[]
no_license
old_syntax_hash = {:name => "Bob"} new_hash = {name: "Bob"} person = {height: "6 ft.", weight: "165 lbs."} person = {hair: "Brown"} person = {age: 62} person.delete(:age) person [:weight] person.merge!(new_hash)
Python
UTF-8
362
3.640625
4
[]
no_license
from itertools import repeat from operator import index def task_3(str_, list_index): return list(map(get_char, repeat(str_), list_index)) # to do operator index and list comprehension def get_char(str_, index): return str_[index] if __name__ == '__main__': string_ = "Всем привет" list_ = [1, 3, 5] print("".join(task_3(string_, list_)))
Java
UTF-8
712
3.984375
4
[]
no_license
import java.util.Scanner; public class SwitchEx { public static void main(String[] args) { Scanner scnr = new Scanner(System.in); System.out.println("Please enter a number between 1 and 7: "); int userNum = scnr.nextInt(); switch (userNum) { case 1: System.out.println("You entered 1."); break; case 2: case 4: case 6: System.out.println("The number you entered is even."); break; case 3: case 5: System.out.println("The number you entered is odd."); break; case 7: System.out.println("You entered lucky number seven."); break; default: System.out.println("I don't understand you. Please follow the instructions."); break; } scnr.close(); } }
TypeScript
UTF-8
1,314
2.890625
3
[]
no_license
import { FieldLabel } from "./FieldLabel"; import { FieldType } from "./EFieldType"; import { Field } from "./IField"; export class EmailField implements Field { name: string; label: FieldLabel; type: FieldType.inputEmail; value: string; id: number = new Date().getTime(); constructor(name: string, label: string, value?: string) { this.name = name; this.label = new FieldLabel(label); this.value = value ? value : ""; } setValue(value: string): boolean { this.value = value; if(this.getValue() === value){ return true; }else{ return false; } } addDefaultEvents(): void { throw new Error("Method not implemented."); } getValue(): string { return this.value; } render(): HTMLDivElement { const element = document.createElement("div"); element.classList.add("form-group"); element.classList.add("input-group"); const input = <HTMLInputElement>document.createElement("input"); input.id = this.id.toString() + this.name; input.type = "email"; input.name = this.name; input.value = this.value; element.append(this.label.render()); element.append(input); return element; } }
TypeScript
UTF-8
2,161
3.265625
3
[ "MIT" ]
permissive
import { NamedParameterizedQuery } from "./NamedParameterizedQuery"; import { SQLParam } from "./SQLParam"; /** * Parse a prepared statement to a query that is supported by node/mysql. */ export class BakedQuery { private _sql: string; private _dictionary: Map<number, string> = new Map<number, string>(); private _values: Map<number, SQLParam> = new Map<number, SQLParam>(); /** * @param npq query that should be converted */ public constructor(npq: NamedParameterizedQuery) { this._sql = npq.getSql(); this.buildDictionary(npq.getParameters()); } /** * Retrieves the values of the parameters that should be replaced as a list. * Get the values that are later injected into the query. */ public fillParameters(): any[] { const returnArr: any[] = []; this._values.forEach((value: SQLParam) => { returnArr.push(value.value); }); return returnArr; } /** * Returns the sql, where parameters the parameters are replaced with questionmarks. */ public getBakedSQL(): string { return this._sql; } /** * Adds the names of the parameters and the values of the parameters to the map. * Adds the values of the parameters to the _values map. * * @param params values for the params */ private buildDictionary(params: SQLParam[]): void { let count = 1; const regexp: RegExp = new RegExp("::(.*?)::", "g"); const array: RegExpMatchArray = this._sql.match(regexp); if (array !== null) { for (let item of array) { item = item.replace(new RegExp("::", "g"), ""); this._dictionary.set(count, item); this._sql = this._sql.replace("::" + item + "::", "?"); let value: SQLParam = null; for (const currParam of params) { if (currParam.name === item) { value = currParam; } } this._values.set(count, value); count++; } } } }
Java
UTF-8
1,677
2.28125
2
[]
no_license
package janjagruti.learning.com.janjagruti.entity; import com.google.gson.annotations.SerializedName; import java.util.Date; public class UserPackage { private int id; private User user; @SerializedName("package") private Package aPackage; private Date validityStart; private Date validityEnd; private boolean isActive; @SerializedName("created_at") private Date createdAt; @SerializedName("updated_at") private Date updatedAt; public int getId() { return id; } public void setId(int id) { this.id = id; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Package getaPackage() { return aPackage; } public void setaPackage(Package aPackage) { this.aPackage = aPackage; } public Date getValidityStart() { return validityStart; } public void setValidityStart(Date validityStart) { this.validityStart = validityStart; } public Date getValidityEnd() { return validityEnd; } public void setValidityEnd(Date validityEnd) { this.validityEnd = validityEnd; } public boolean isActive() { return isActive; } public void setActive(boolean active) { isActive = active; } public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } public Date getUpdatedAt() { return updatedAt; } public void setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; } }
Java
UTF-8
376
1.703125
2
[]
no_license
package antlr.debug; import java.util.EventListener; public abstract interface ListenerBase extends EventListener { public abstract void doneParsing(TraceEvent paramTraceEvent); public abstract void refresh(); } /* Location: C:\Users\ESa10969\Desktop\PDFComparer\ * Qualified Name: antlr.debug.ListenerBase * JD-Core Version: 0.6.2 */
Java
UTF-8
884
2.25
2
[]
no_license
package com.techburg.autospring.service.abstr; import java.util.List; import com.techburg.autospring.model.business.Workspace; import com.techburg.autospring.model.query.WorkspacePersistenceQuery; public interface IWorkspacePersistenceService { /** * Store the workspace * * @param workspace * @param isSyncMode * @return */ public int persistWorkspace(Workspace workspace, boolean isSyncMode); /** * Update the workspace * * @param workspace * @return */ public int updateWorkspace(Workspace workspace); /** * Retrieve the workspaces matching the specified query * * @param buildInfoList * @param query * @return */ public int loadWorkspace(List<Workspace> buildInfoList, WorkspacePersistenceQuery query); /** * Remove the workspace with Id specified * * @param id * @return */ public int removeWorkspaceByID(long id); }
Markdown
UTF-8
2,615
2.546875
3
[]
no_license
# linux 网络相关 ### 命令总览 - 网络配置: ifconfig、 ip - 连通性探测: ping、 traceroute、 telnet、 mtr - 网络连接: netstat、 ss、 nc、 lsof - 流量统计: ifstat、 sar、 iftop - 交换与路由: arp、 arping、 vconfig、 route - 防火墙: iptables、 ipset - 域名: host、 nslookup、 dig、 whois - 抓包: tcpdump - 虚拟设备: tunctl、 brctl、 ovs #### ifconfig ```bash ifconfig eth0 # 查看网卡信息 ifconfig eth0 192.168.1.10 # 给网卡配置 ip ifconfig eth0 192.168.1.10 netmask 255.255.255.0 ifconfig eth0 down/up # 关闭/开启网卡 ``` #### ip ```bash ip route # 查看路由 ``` #### ping / telnet - ping用来查看网络连通性,如 `ping www.baidu.com` - telnet 确定远程服务是否能访问,如 `telent localhost 22` ### curl ```bash curl url # 发出 get 请求 curl -[ilvK] url # -i打印响应头和内容;-l响应头;-v打印全部;-K跳过 ssl 检查 curl -A "xx" url # 设置 户代理标头(User-Agent) curl -b "a=b" url # 设置 cookie curl -b a.txt url # 读取文件 a.txt 作为 cookie curl -c a.txt url # 将服务器设置的 Cookie 写入一个文件,文件格式见 ./shell/cookes.txt curl -d "login=emma&password=123" -X POST url # 发送 post 请求 和 数据,请求会自动加上: application/x-www-form-urlencoded curl -d '@data.txt' https://google.com/login # 读取文件 curl --data-urlencode "login=emma&password=123" -X POST url # 与 -d 一样,但会对参数进行 url 编码 curl -D filename url # 将响应头写入文件里 curl -e 'https://google.com?q=example' url # 设置 referer curl -F "file=@a.png" url # 上传 二进制 文件 curl -H "a: 1" -H "b: 2" url # 设置请求头 curl -o example.html url # 等于 wget,保存为 example.html ``` #### 利用 curl 测试 ```bash curl -o /dev/null -s -w time_namelookup:"\t"%{time_namelookup}"\n"time_connect:"\t\t"%{time_connect}"\n"time_pretransfer:"\t"%{time_pretransfer}"\n"time_starttransfer:"\t"%{time_starttransfer}"\n"time_total:"\t\t"%{time_total}"\n"time_redirect:"\t\t"%{time_redirect}"\n" URL # or curl -o /dev/null -s -w "@curl-time" URL # @curl-time 为一个文件,格式 \n http: \t\t%{http_code}\n dns: \t\t\t%{time_namelookup}s\n redirect: \t\t%{time_redirect}s\n time_connect: \t%{time_connect}s\n time_appconnect: \t%{time_appconnect}s\n time_pretransfer: \t%{time_pretransfer}s\n time_starttransfer: \t%{time_starttransfer}s\n size_download: \t%{size_download}bytes\n speed_download: \t%{speed_download}B/s\n ----------\n time_total: %{time_total}s\n \n ```
C++
UTF-8
2,104
3.21875
3
[]
no_license
#include <cmath> #include "space_object.h" SpaceObject::SpaceObject(Vector2 pos, Vector2 vel, float scale, float rot) : m_pos(pos), m_vel(vel), m_scale(scale), m_rot(rot) {} void SpaceObject::drawObject(Display &display) { int width = display.getWidth(); int height = display.getHeight(); int half_width = width / 2; int half_height = height / 2; float ratio = (float)height / width; // For each line that makes up the object graphic for (size_t i = 0; i < m_lines.size(); i+=2) { // Apply rotation float x1 = m_lines[i].x * std::cos(m_rot) - m_lines[i].y * std::sin(m_rot); float y1 = m_lines[i].x * std::sin(m_rot) + m_lines[i].y * std::cos(m_rot); float x2 = m_lines[i + 1].x * std::cos(m_rot) - m_lines[i + 1].y * std::sin(m_rot); float y2 = m_lines[i + 1].x * std::sin(m_rot) + m_lines[i + 1].y * std::cos(m_rot); // Convert normalised coordinates to pixel coordinates x1 = (ratio * m_scale * x1 + m_pos.x) * half_width + half_width; y1 = (m_scale * y1 + m_pos.y) * half_height + half_height; x2 = (ratio * m_scale * x2 + m_pos.x) * half_width + half_width; y2 = (m_scale * y2 + m_pos.y) * half_height + half_height; display.drawLine(std::ceil(x1), std::ceil(y1), std::ceil(x2), std::ceil(y2), 0xFFFFFFFF); } } void SpaceObject::updatePosition(float timeDelta) { Vector2 pos = m_pos + m_vel * timeDelta; // Wrap-around screen if (pos.x < -1) pos.x = pos.x + 2; if (pos.x >= 1) pos.x = pos.x - 2; if (pos.y < -1) pos.y = pos.y + 2; if (pos.y >= 1) pos.y = pos.y - 2; m_pos = pos; } void SpaceObject::setPos(Vector2 pos) { m_pos = pos; } Vector2 SpaceObject::getPos() { return m_pos; } void SpaceObject::setVel(Vector2 vel) { m_vel = vel; } Vector2 SpaceObject::getVel() { return m_vel; } void SpaceObject::setScale(float scale) { m_scale = scale; } float SpaceObject::getScale() { return m_scale; } void SpaceObject::setRot(float rot) { m_rot = rot; } float SpaceObject::getRot() { return m_rot; } SpaceObject::~SpaceObject() {}
Python
UTF-8
2,169
2.765625
3
[]
no_license
""" ============================ Author:小白31 Time:2020/8/12 23:10 E-mail:1359239107@qq.com ============================ """ # 2、选做题:尝试(请求头使用X-Lemonban-Media-Type":"lemonban.v2), # 去请求需要鉴权的充值接口(提示:要先登录,提取token,按接口文档要求加上token才能通过鉴权) import requests from jsonpath import jsonpath class test_api2(): # 域名 url = 'http://api.lemonban.com/futureloan' # 请求头 def headers_v2(self): headers_v2 = {"X-Lemonban-Media-Type": "lemonban.v2", "content-type": "application/json" } return headers_v2 # 登录接口 def login(self): login_url = self.url + "/member/login" data = {"mobile_phone": "13012341230", "pwd": "lemon123456"} res = requests.post(url=login_url, json=data, headers=self.headers_v2()) return res # return jsonpath(res.json(), "$..token") # return res.json()["data"]["token_info"]["token"] # 充值接口 def recharge(self): recharge_url = self.url + "/member/recharge" # 获取登录后的id也就是member_id id = jsonpath(self.login().json(),"$..id") # 测试数据 data = {"member_id": id[0], "amount": "50000.00"} # token token = jsonpath(self.login().json(),"$..token") auth = {"Authorization": "Bearer {}".format(token[0])} header = self.headers_v2() header.update(auth) # 添加一个字典auth res = requests.post(url=recharge_url, json=data, headers=header) return res.json() t = test_api2() # print(t.login().json()) print(t.recharge()) # print(t.recharge()) # {'code': 0, 'msg': 'OK', # 'data': {'id': 2074984, 'leave_amount': 1580.0, 'mobile_phone': '13012341230', 'reg_name': '小白', # 'reg_time': '2020-08-12 22:28:00.0', 'type': 1, # 'token_info': {'token_type': 'Bearer', 'expires_in': '2020-08-12 23:21:10', # 'token': 'eyJhbGciOiJIUzUxMiJ9.eyJtZW1iZXJfaWQiOjIwNzQ5ODQsImV4cCI6MTU5NzI0NTY3MH0.Cs2qobmeH9A1fBo2OXOelbuJGgz1Askgx47-xUg3mOugCJ3KW8cG4MXoAydyDMEveU-Ha8_x0GluijZUuIrTWQ'}}, # 'copyright': 'Copyright 柠檬班 © 2017-2020 湖南省零檬信息技术有限公司 All Rights Reserved'}
Java
UTF-8
1,665
2.203125
2
[]
no_license
package com.liangchen.myutil; import com.liangchen.POJO.Notify; import com.liangchen.POJO.NotifyList; import com.liangchen.Service.CommentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; @Component public class NotifyUtill { private CommentService commentService; private CommentUtil commentUtil; private NotifyList notifyList; @Autowired public NotifyUtill(CommentService commentService, CommentUtil commentUtil, NotifyList notifyList) { this.commentService = commentService; this.commentUtil = commentUtil; this.notifyList = notifyList; } private List<Notify> notifies=new CopyOnWriteArrayList<>(); //生成Notify对象 public void notifyFactory(int cid, String replayTile, String replayer, String replayTo, String replayConte){ Notify notify=new Notify(cid, replayTile,replayer,replayTo,replayConte); notifies.add(notify); notifyList.setNotifies(notifies); } public int ignore(int cid){ for (Notify n:notifies){ if (n.getCommentID()==cid){ notifies.remove(n); notifyList.setNotifies(notifies); } } return commentService.updataRead(cid); } public int delete(int cid){ //删除逻辑 //忽略通知 int res1=ignore(cid); //删除评论 String res2=commentUtil.deleteCommentByID(cid); return res1; } public void clearAll(){ notifies=new CopyOnWriteArrayList<>(); } }
Python
UTF-8
2,889
2.890625
3
[]
no_license
''' Two methods to determine some exoplanet properties using radial velocity measurements. ''' import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit # number of steps n_fit = 10000 t = np.array([3791.7441, 3793.6623, 3793.7635, 3794.7132, 3794.8735, 3853.5400, 3853.5753, 3854.4999, 3856.6192, 3858.6166, 3859.7276, 4143.7804, 4144.7438, 4144.7730, 4145.7741, 4148.6511, 4149.7774, 4150.7396, 4203.5920, 4204.5496, 4205.5464, 4207.6555, 4208.5372, 4209.6534]) u = np.array([22.433, 22.297, 22.209, 22.325, 22.293, 22.161, 22.238, 22.374, 22.500, 22.430, 22.488, 22.191, 22.325, 22.256, 22.504, 22.330, 22.454, 22.452, 22.368, 22.259, 22.407, 22.229, 22.260, 22.457]) u_sd = np.array([0.056, 0.118, 0.067, 0.056, 0.058, 0.062, 0.057, 0.056, 0.060, 0.057, 0.070, 0.062, 0.061, 0.057, 0.082, 0.060, 0.064, 0.057, 0.046, 0.070, 0.070, 0.043, 0.050, 0.054]) # Determine radial velocity amplitude through variance of radial velocity. n = u.shape[0] u_sd_norm = np.sum(1 / u_sd**2) w = np.sum(u / u_sd**2) / u_sd_norm w_var = n / (n - 1) * np.sum(((u - w) / u_sd)**2) / u_sd_norm w_sd = np.sqrt(w_var) w_var_var = n / (n - 2) * np.sum((((u - w)**2 - w_var) / u_sd)**2) / u_sd_norm w_var_sd = np.sqrt(w_var_var) print('variance method') print(f'drift\t{w:.1f} km/s') print(f'amplitude sin(inclination)\t{w_sd:.3f}±{w_var_sd:.3f} km/s') print() # Determine radial velocity properties through direct fitting to sinusoidal model. P = 3.97910 # in days, pm 0.00001 P_s = 3600 * 24 * P # in seconds inc = 85.7 * np.pi / 180 # pm 0.3 def f(t, w, b, t_0): return w + 2 * np.pi * b / P_s * np.sin(2 * np.pi / P * (t - t_0)) * np.sin(inc) fit, fit_cov = curve_fit(f, t, u, p0 = [22.35, 6750, 3]) fit_sd = np.sqrt(fit_cov.diagonal()) print('fit method') print(f'drift\t{fit[0]:.1f}±{fit_sd[0]:.1f} km/s') print(f'semi-major radius\t{fit[1]:.0f}±{fit_sd[1]:.0f} km') print(f'amplitude sin(inclination)\t {2 * np.pi * fit[1] / P_s * np.sin(inc):.3f}±{2 * np.pi * fit_sd[1] / P_s * np.sin(inc):.3f} km/s') print(f't_0\t{fit[2]:.2f}±{fit_sd[2]:.2f} days') t_fit = np.linspace(np.min(t), np.max(t), n_fit) u_fit = np.empty(n_fit) for i in range(0, n_fit): u_fit[i] = f(t_fit[i], fit[0], fit[1], fit[2]) fig = plt.figure(figsize = (5, 8)) axs = [fig.add_subplot(411), fig.add_subplot(412), fig.add_subplot(413), fig.add_subplot(414)] for ax in axs: ax.plot(t_fit, u_fit, color = 'red') ax.errorbar(t, u, yerr = u_sd, fmt = 'o', color = 'black') ax.set_xlabel('time [BJD]', size = 10) ax.set_ylabel('radial velocity [km/s]', size = 10) ax.grid() axs[0].set_xlim([3791, 3796]) axs[1].set_xlim([3851, 3862]) axs[2].set_xlim([4142, 4153]) axs[3].set_xlim([4201, 4211]) plt.tight_layout() plt.show()
Markdown
UTF-8
3,191
2.5625
3
[ "MIT" ]
permissive
# Energy Budget Constraints on the Time History of Aerosol Forcing and Climate Sensitivity This code demonstrates how we can use constraints of observed surface warming from 1850-2019 and ocean heat update from 1971-2018 to constrain historical aerosol forcing, equilibrium climate sensitivity and transient climate response. ![Comparison of constrained aerosol forcing and CMIP6 models from 1850 to 2019](figures/models_v_constrained.png?raw=true) Comparison of the energy-budget constrained aerosol forcing best estimate (thick grey line) and 5-95% range (grey shaded band) with CMIP6 model aerosol forcing results (coloured). CMIP6 individual years are coloured points and a 11-year Savitzy-Golay smoothing filter is applied to these model results to produce smoothed model time series estimates (coloured lines). Note this plot is using an 1850 baseline for direct comparison with CMIP6 models, whereas all results in the paper use a 1750 baseline for "pre-industrial" conditions. ## Reference and citation The paper describing this method is published in Journal of Geophysical Research Atmospheres and available as an open-access paper at https://agupubs.onlinelibrary.wiley.com/doi/10.1029/2020JD033622. Please cite as: Smith, C. J., Harris, G. R., Palmer, M. D., Bellouin, N., Collins, W., Myhre, G., Schulz, M., Golaz, J.-C., Ringer, M., Storelvmo, T., Forster, P. M., (2021). Energy Budget Constraints on the Time History of Aerosol Forcing and Climate Sensitivity. Journal of Geophysical Research: Atmospheres, 126, e2020JD033622. https://doi.org/10.1029/2020JD033622 ## Reproduction As always, the best way to avoid disaster is to use a virtual environment. My weapon of choice is miniconda3 (https://docs.conda.io/en/latest/miniconda.html). For this code more than ever it is a good idea to use `conda`, as code makes heavy use of `iris` which is difficult(/impossible?) to install through `pip`. Therefore, create a new environment, activate it, and use `conda` to grab `iris`: conda install -c conda-forge iris When this is done, grab the repo-specific dependencies: pip install -r requirements.txt Once set up, run the notebooks in the `notebooks` directory in order. Some notebooks take a while, e.g. the two-layer model calculations for 13 models (notebook 30) and the internal variability calculation (notebook 10). In the `scripts` directory is the code that runs the APRP decomposition for the 11 climate models used in the paper. However, these scripts won't run because they require the CMIP6 and E3SM data (the file names point to my local paths, and they are not supplied here due to file sizes, but all are available either from the ESGF portal or https://esgf-node.llnl.gov/projects/e3sm/). The important data that is required to reproduce the results is shipped in the directories `input_data` (if it is a raw input) or `output_data` (if somewhere along the process, the code calculates it). The only figure in the whole paper and supplement not reproduced by this repository is Figure S3, by Glen Harris. The two-layer results (red curves in fig. S3) can be reproduced by plugging the parameters from each CMIP6 model (`input_data/scmpy2L_calib_n=44_eps=fit_v20200702.txt`) into the two-layer model.
Java
UTF-8
1,435
3.3125
3
[]
no_license
package j2eebp.security; import java.security.*; /** * Principals represent Subject identities. They implement the * java.security.Principal interface (which predates JAAS) and * java.io.Serializable. A Subject's most important method is getName(), which * returns an identity's string name. Since a Subject instance contains an array * of Principals, it can thus have multiple names. * * Because a social security number, login ID, email address, and so on, can all * represent one user, multiple identities prove common in the real world. * * @version 1.0 2004-09-14 * @author Cay Horstmann */ public class J2eebpPrincipal implements Principal { private String descr; private String value; /** * Construye un Principal para guardar un valor y una descripcion * * @param roleName * the role name */ public J2eebpPrincipal(String descr, String value) { this.descr = descr; this.value = value; } /** * Devuelve el rol del principal * * @return the role name */ public String getName() { return descr + "=" + value; } public boolean equals(Object otherObject) { if (this == otherObject) return true; if (otherObject == null) return false; if (getClass() != otherObject.getClass()) return false; J2eebpPrincipal other = (J2eebpPrincipal) otherObject; return getName().equals(other.getName()); } public int hashCode() { return getName().hashCode(); } }
C
UTF-8
1,145
3.609375
4
[]
no_license
#include<stdio.h> #include<stdlib.h> void linear(int[],int,int); void binary(int a[],int k,int n); void sort(int a[],int n); void main() { int a[30],n,k,c; printf("enter the limit:"); scanf("%d",&n); printf("enter the elements"); for(int i=0;i<n;i++) { scanf("%d",&a[i]); } printf("enter the element to be searched:"); scanf("%d",&k); printf("enter 1 for linear and 2 for binary search"); scanf("%d",&c); switch(c) { case 1:linear(a,k,n);break; case 2:binary(a,k,n);break; default:printf("invalid choice"); } } void linear(int a[],int k,int n) { int f=0; for(int i=0;i<n;i++) { if(a[i]==k) { f=i+1; } } if(f>0) { printf("element is present in the %dth position",f); } else { printf("element not found"); } } void sort(int a[],int n) { int temp; for(int i=0;i<n;i++) for(int j=0;j<n-i-1;j++) if(a[i]>a[j+1]) { temp=a[i]; a[i]=a[j+1]; a[j+1]=temp; } } void binary(int a[],int k,int n) { int first,last,mid; sort(a,n); first=0; last=n-1; mid=(first+last)/2; while(first<last) { if(a[mid]<k) first=mid+1; else if (a[mid]==k) { printf("element is found at %d",mid); exit(0); } else last=mid-1; mid=(first+last)/2; } printf("element not found"); }
Swift
UTF-8
1,358
2.765625
3
[]
no_license
// // AppointmentCategory.swift // appointment // // Created by Raluca Mesterca on 19/03/2020. // Copyright © 2020 DTT. All rights reserved. // import Foundation import UIKit enum AppointmentCategory: String, Codable { case business case standard case group case memo = "MEMO" case unknown enum CodingKeys: String, CodingKey { case standard, group, business case memo = "MEMO" } var image: UIImage? { switch self { case .memo: return R.image.memo_Icon_Yellow() case .standard: return R.image.popUp_invitation_incoming_appointment() case .group: return R.image.popUp_dateConfirmation() case .business: return R.image.menu_Business() case .unknown: return nil } } /// Defines the priority with which an appointment is shown in home sceen /// in case of multiple appointments static func > (lhs: AppointmentCategory, rhs: AppointmentCategory) -> Bool { switch (lhs, rhs) { case (.business, _), (.standard, .standard), (.standard, .group), (.standard, .memo), (.group, .group), (.group, .memo), (.memo, .memo): return true default: return false } } }
C++
UTF-8
1,275
2.625
3
[]
no_license
#ifndef ACTIONJUDGETTSANDVIEWPARALLEL_H #define ACTIONJUDGETTSANDVIEWPARALLEL_H #include <thread> #include "Action.h" class ActionJudgeTTSAndViewParallel : public Action { public: ActionJudgeTTSAndViewParallel(std::string audioType , std::string audioFilePath, int audioTimeout , std::string picFilePath, int picTimeout) :Action(audioTimeout) ,_audioType(audioType) ,_audioFilePath(audioFilePath) ,_audioTimeout(audioTimeout) ,_picFilePath(picFilePath) ,_picTimeout(picTimeout) ,_audioResult(false) ,_picResult(false) {} virtual ~ActionJudgeTTSAndViewParallel() {} virtual bool run(std::string casename, int seq) override; private: void audioThread(); void picThread(); void setAudioResult(bool result) { _audioResult = result; } bool getAudioResult() { return _audioResult; } void setPicResult(bool result) { _picResult = result; } bool getPicResult() { return _picResult; } const std::string _audioType; const std::string _audioFilePath; const int _audioTimeout; const std::string _picFilePath; const int _picTimeout; bool _audioResult; bool _picResult; }; #endif /* ACTIONJUDGETTSANDVIEWPARALLEL_H */
Markdown
UTF-8
3,413
3.453125
3
[ "MIT" ]
permissive
# Docker Images - Each docker image is made of multiple layers and each layer is just another docker image. - The very first layer is called the *base layer*. - The layers in an image can be viewed using ```docker history imagename:tag``` command. - When we create a container from an image we create a new *writable layer* where all the read/write or modify actions happen in this *writable layer* . - When the container is stopped this *writable layer* is discarded. ![image-20200316162150359](/home/shekar-android/Documents/0_My_Projects/docker-blitz/images/10_docker_image_layers.png) ## Building docker images There are two ways to build docker images. 1. Commit changes made to a container to create new image 2. Create an image using *Dockerfile* ### Create using commit To create an image using ```docker commit``` command we first run the base container for out image and then make the required changes and commit those changes using ```docker commit``` command to create the new image. Steps involved: 1. Run the base container using the ```-it``` flags in order to be able to modify the *writable layer* 2. Now We add required applications or files to the image and close the container. 3. Use ```docker ps -a``` command to list all the containers. 4. Copy the container ID of our modified container. 5. Use command ```docker commit container_ID repository_name:tag``` to create the image ### Creating images using Dockerfile - A *Dockerfile* is a text document that contains all the instructions user provides to assemble the image. - Each instruction will create a new image layer to the image. - Instructions specify what to do when building the image. **Note**: A *Dockerfile* is a file named *Dockerfile* with no extensions. Steps to create a *docker image* using a *Dockerfile*: 1. Create a dockerfile Sample *Dockerfile*: ```dockerfile FROM debian:jessie RUN apt-get update RUN apt-get install vim -y RUN apt-get install git -y ``` 2. Use ``` docker build -t your_tag . ``` to build the image. #### Understanding docker build Docker build command takes the path to build contxt as an argumnent. Which is ```.``` in this case. When build starts, docker client would pack all the files in the build context into a tarball and then transfers the tarball file to the daemon. By default docker would search for the Dockerfile in the build context path. When the above mentioned dockerfile is used to build a new image - first docker creates a new container from the base image *debian/jessie*. - Then runs the command ```RUN apt-get update``` on the base image, modifying the *writable layer*. - once this instruction is executed, a new container is created with the previous changes intact and the previous container is discarded. - In this new container the second instruction ```RUN apt-get install vim -y``` is executed. - creation of containers -> execution of commands -> commit changes and create new container -> discatding old container -> executing commands, this cycle is continued till all the instructions are completed and final image is created. Only the instructions `RUN`, `COPY`, `ADD` create layers. Other instructions create temporary intermediate images, and do not increase the size of the build. A complete list of instructions can be found [here](https://docs.docker.com/engine/reference/builder/).
C#
UTF-8
695
2.640625
3
[]
no_license
using System; using UnityEngine; namespace AreaOfAres.UI.DataTypes { [Serializable] public class UIBool { [SerializeField] private string _text; [SerializeField] private bool _flag; public string Text { get { return _text; } private set { _text = value; } } public bool Flag { get { return _flag; } private set { _flag = value; } } public event Action<bool> OnFlagChanged = delegate { }; public UIBool(string text, bool flag) { Text = text; Flag = flag; } public void SetFlag(bool flag) { Flag = flag; OnFlagChanged?.Invoke(Flag); } } }
Java
UTF-8
271
2.234375
2
[ "MIT" ]
permissive
package com.hz.design.facade; /** * 内存 * * Created by hezhao on 2018-08-09 15:32 */ public class Memory { public void start() { System.out.println("启动内存"); } public void stop() { System.out.println("关闭内存"); } }
Swift
UTF-8
2,192
2.859375
3
[]
no_license
// // SignUPViewController.swift // LetsWork // // Created by Isaac Kim on 27/10/2018. // Copyright © 2018 Isaac Kim. All rights reserved. // import UIKit struct UserInfo { var id: String var pw: String var email: String let firstName : String let lastName: String } class SignUPViewController: UIViewController { @IBOutlet weak var firstName: UITextField! @IBOutlet weak var lastName: UITextField! @IBOutlet weak var userID: UITextField! @IBOutlet weak var initialPassword: UITextField! @IBOutlet weak var retypePassword: UITextField! @IBOutlet weak var userEmail: UITextField! let message = "Please retype the password" let segueIdentifierForSignUp = "signup" override func viewDidLoad() { super.viewDidLoad() } @IBAction func signUpTapped(_ sender: UIButton) { guard let savedFirstName = firstName.text, let savedLastName = lastName.text, let savedUserID = userID.text, let savedInitialPW = initialPassword.text, let savedretypePW = retypePassword.text, let savedUserEmail = userEmail.text else {return} let newUser = UserInfo(id: savedUserID, pw: savedInitialPW, email: savedUserEmail, firstName: savedFirstName, lastName: savedLastName) // Mark: make the data that put into a dictionary. // let userData [String:[:]] = [] if newUser.pw != savedretypePW { // mark: make a alertView when the password does not match let alertController = UIAlertController(title: "Password Does not Match", message: message, preferredStyle: .alert) let dismiss = UIAlertAction(title: "Ok", style: .default, handler: nil) print(savedInitialPW) print(savedretypePW) alertController.addAction(dismiss) present(alertController, animated: true) } else { performSegue(withIdentifier: segueIdentifierForSignUp, sender: sender) } } }
Go
UTF-8
10,189
3.125
3
[ "MIT" ]
permissive
package gorefactor import ( "fmt" "github.com/dave/dst" "github.com/stretchr/testify/assert" "go/token" "testing" ) func TestHasStmtInsideFuncBody(t *testing.T) { t.Run("basic", func(t *testing.T) { var src = ` package main import "fmt" func B() { c := 1 } func main() { a := 1 b := 1 fmt.Println(a+b) } ` cases := []struct { stmt dst.Stmt expected bool }{ {&dst.AssignStmt{ Lhs: []dst.Expr{dst.NewIdent("a")}, Tok: token.DEFINE, Rhs: []dst.Expr{&dst.BasicLit{ Kind: token.INT, Value: "1", }}, }, true}, {&dst.AssignStmt{ Lhs: []dst.Expr{dst.NewIdent("b")}, Tok: token.DEFINE, Rhs: []dst.Expr{&dst.BasicLit{ Kind: token.INT, Value: "1", }}, }, true}, {&dst.ExprStmt{ X: &dst.CallExpr{ Fun: &dst.Ident{ Name: "Println", Path: "fmt", }, Args: []dst.Expr{&dst.BinaryExpr{ X: dst.NewIdent("a"), Op: token.ADD, Y: dst.NewIdent("b"), Decs: dst.BinaryExprDecorations{}, }}, }, }, true}, {&dst.AssignStmt{ Lhs: []dst.Expr{dst.NewIdent("a")}, Tok: token.DEFINE, Rhs: []dst.Expr{&dst.BasicLit{ Kind: token.INT, Value: "2", }}, }, false}, { &dst.AssignStmt{ Lhs: []dst.Expr{dst.NewIdent("c")}, Tok: token.DEFINE, Rhs: []dst.Expr{&dst.BasicLit{ Kind: token.INT, Value: "1", }}, Decs: dst.AssignStmtDecorations{}, }, false, }, } df, _ := ParseSrcFileFromBytes([]byte(src)) for _, c := range cases { assert.Equal(t, c.expected, HasStmtInsideFuncBody(df, "main", c.stmt)) } }) t.Run("nested", func(t *testing.T) { var src = ` package main import "fmt" func main() { a := 1 b := 1 defer func() { c := 3 fmt.Println(c) }() } ` df, _ := ParseSrcFileFromBytes([]byte(src)) stmt := &dst.AssignStmt{ Lhs: []dst.Expr{dst.NewIdent("c")}, Tok: token.DEFINE, Rhs: []dst.Expr{&dst.BasicLit{ Kind: token.INT, Value: "3", }}, Decs: dst.AssignStmtDecorations{}, } assert.Equal(t, true, HasStmtInsideFuncBody(df, "main", stmt)) }) } func TestDeleteStmtFromFuncBody(t *testing.T) { t.Run("basic", func(t *testing.T) { var src = ` package main import ( "fmt" ) func main() { a := 1 b := 1 fmt.Println(a+b) } ` var expectedTemplate = ` package main func main() { %s } ` cases := []struct { stmt dst.Stmt expectedModified bool expectedBody string }{ {&dst.ExprStmt{ X: &dst.CallExpr{ Fun: &dst.Ident{ Name: "Println", Path: "fmt", }, Args: []dst.Expr{&dst.BinaryExpr{ X: dst.NewIdent("a"), Op: token.ADD, Y: dst.NewIdent("b"), Decs: dst.BinaryExprDecorations{}, }}, }, }, true, "a := 1 \n b := 1"}, {&dst.AssignStmt{ Lhs: []dst.Expr{dst.NewIdent("b")}, Tok: token.DEFINE, Rhs: []dst.Expr{&dst.BasicLit{ Kind: token.INT, Value: "1", }}, }, true, "a := 1"}, {&dst.AssignStmt{ Lhs: []dst.Expr{dst.NewIdent("a")}, Tok: token.DEFINE, Rhs: []dst.Expr{&dst.BasicLit{ Kind: token.INT, Value: "1", }}, }, true, ""}, } df, _ := ParseSrcFileFromBytes([]byte(src)) for _, c := range cases { assert.Equal(t, c.expectedModified, DeleteStmtFromFuncBody(df, "main", c.stmt)) buf := printToBuf(df) assertCodesEqual(t, fmt.Sprintf(expectedTemplate, c.expectedBody), buf.String()) } }) t.Run("nested", func(t *testing.T) { var src = ` package main import ( "fmt" ) func main() { a := 1 b := 1 defer func() { c := 1 fmt.Println("hello world") }() } ` var expected = ` package main import ( "fmt" ) func main() { a := 1 b := 1 defer func() { fmt.Println("hello world") }() } ` df, _ := ParseSrcFileFromBytes([]byte(src)) stmt := &dst.AssignStmt{ Lhs: []dst.Expr{dst.NewIdent("c")}, Tok: token.DEFINE, Rhs: []dst.Expr{&dst.BasicLit{ Kind: token.INT, Value: "1", }}, Decs: dst.AssignStmtDecorations{}, } assert.Equal(t, true, DeleteStmtFromFuncBody(df, "main", stmt)) buf := printToBuf(df) assertCodesEqual(t, expected, buf.String()) }) t.Run("multiple", func(t *testing.T) { var src = ` package main import ( "fmt" ) func main() { fmt.Println() fmt.Println() } ` var expected = ` package main func main() { } ` printStmt := &dst.ExprStmt{ X: &dst.CallExpr{ Fun: &dst.Ident{ Name: "Println", Path: "fmt", }, }, } df, _ := ParseSrcFileFromBytes([]byte(src)) assert.Equal(t, true, DeleteStmtFromFuncBody(df, "main", printStmt)) buf := printToBuf(df) assertCodesEqual(t, expected, buf.String()) }) } func TestDeleteSelectorExprFromFuncBody(t *testing.T) { t.Run("basic", func(t *testing.T) { var src = ` package main func A() { fmt.Printf("%s", "foo") } func main() { fmt.Println() fmt.Printf("%s", "bar") fmt.Printf("%s", "baz") fmt.Println() } ` var expected = ` package main func A() { fmt.Printf("%s", "foo") } func main() { fmt.Println() fmt.Println() } ` printSelector := &dst.SelectorExpr{ X: dst.NewIdent("fmt"), Sel: dst.NewIdent("Printf"), } df, _ := ParseSrcFileFromBytes([]byte(src)) assert.Equal(t, true, DeleteSelectorExprFromFuncBody(df, "main", printSelector)) buf := printToBuf(df) assertCodesEqual(t, expected, buf.String()) }) t.Run("complex", func(t *testing.T) { var src = ` package main func (m *TestServiceImpl) Hello(req *HelloReq) (r *HelloRes, err error) { fun := "TestServiceImpl.Hello -->" st := stime.NewTimeStat() defer func() { dur := st.Duration() log.Infof("%s req:%v tm:%d", fun, req, dur) monitor.Stat("RPC-Hello", dur) }() return logic.HandleTest.Hello(req), nil } ` var expected = ` package main func (m *TestServiceImpl) Hello(req *HelloReq) (r *HelloRes, err error) { fun := "TestServiceImpl.Hello -->" st := stime.NewTimeStat() defer func() { dur := st.Duration() monitor.Stat("RPC-Hello", dur) }() return logic.HandleTest.Hello(req), nil } ` printSelector := &dst.SelectorExpr{ X: dst.NewIdent("log"), Sel: dst.NewIdent("Infof"), } df, _ := ParseSrcFileFromBytes([]byte(src)) assert.Equal(t, true, DeleteSelectorExprFromFuncBody(df, "Hello", printSelector)) buf := printToBuf(df) assertCodesEqual(t, expected, buf.String()) }) } func TestAddStmtToFuncBody(t *testing.T) { t.Run("basic", func(t *testing.T) { var src = ` package main func main() { a := 1 b := 2 } ` var expectedTemplate = ` package main func main() { %s } ` cstmt := &dst.AssignStmt{ Lhs: []dst.Expr{dst.NewIdent("c")}, Tok: token.DEFINE, Rhs: []dst.Expr{&dst.BasicLit{ Kind: token.INT, Value: "3", }}, } cases := []struct { pos int expectedBody string }{ {0, "c := 3\na := 1\nb := 2"}, {1, "a := 1\nc := 3\nb := 2"}, {2, "a := 1\nb := 2\nc := 3"}, {-1, "a := 1\nb := 2\nc := 3"}, } for _, c := range cases { df, _ := ParseSrcFileFromBytes([]byte(src)) assert.True(t, AddStmtToFuncBody(df, "main", cstmt, c.pos)) buf := printToBuf(df) assertCodesEqual(t, fmt.Sprintf(expectedTemplate, c.expectedBody), buf.String()) } }) } func TestAddStmtToFuncBodyRelativeTo(t *testing.T) { t.Run("basic", func(t *testing.T) { var src = ` package main func main() { a := 1 b := 2 } ` var expectedTemplate = ` package main func main() { %s } ` astmt := &dst.AssignStmt{ Lhs: []dst.Expr{dst.NewIdent("a")}, Tok: token.DEFINE, Rhs: []dst.Expr{&dst.BasicLit{ Kind: token.INT, Value: "1", }}, } bstmt := &dst.AssignStmt{ Lhs: []dst.Expr{dst.NewIdent("b")}, Tok: token.DEFINE, Rhs: []dst.Expr{&dst.BasicLit{ Kind: token.INT, Value: "2", }}, } cstmt := &dst.AssignStmt{ Lhs: []dst.Expr{dst.NewIdent("c")}, Tok: token.DEFINE, Rhs: []dst.Expr{&dst.BasicLit{ Kind: token.INT, Value: "3", }}, } cases := []struct { direction int refStmt dst.Stmt expectedBody string }{ {relativeDirectionBefore, astmt, "c := 3\na := 1\nb := 2"}, {relativeDirectionAfter, astmt, "a := 1\nc := 3\nb := 2"}, {relativeDirectionBefore, bstmt, "a := 1\nc := 3\nb := 2"}, {relativeDirectionAfter, bstmt, "a := 1\nb := 2\nc := 3"}, } for _, c := range cases { df, _ := ParseSrcFileFromBytes([]byte(src)) assert.True(t, addStmtToFuncBodyRelativeTo(df, "main", cstmt, c.refStmt, c.direction)) buf := printToBuf(df) assertCodesEqual(t, fmt.Sprintf(expectedTemplate, c.expectedBody), buf.String()) } }) t.Run("nested", func(t *testing.T) { var src = ` package main func main() { a := 1 b := 2 defer func() { d := 4 }() } ` var expectedTemplate = ` package main func main() { a := 1 b := 2 defer func() { %s }() } ` cstmt := &dst.AssignStmt{ Lhs: []dst.Expr{dst.NewIdent("c")}, Tok: token.DEFINE, Rhs: []dst.Expr{&dst.BasicLit{ Kind: token.INT, Value: "3", }}, } dstmt := &dst.AssignStmt{ Lhs: []dst.Expr{dst.NewIdent("d")}, Tok: token.DEFINE, Rhs: []dst.Expr{&dst.BasicLit{ Kind: token.INT, Value: "4", }}, } estmt := &dst.AssignStmt{ Lhs: []dst.Expr{dst.NewIdent("e")}, Tok: token.DEFINE, Rhs: []dst.Expr{&dst.BasicLit{ Kind: token.INT, Value: "5", }}, } cases := []struct { direction int stmt dst.Stmt refStmt dst.Stmt expectedBody string }{ {relativeDirectionBefore, cstmt, dstmt, "c := 3\nd := 4"}, {relativeDirectionAfter, estmt, dstmt, "d := 4\ne := 5"}, } for _, c := range cases { df, _ := ParseSrcFileFromBytes([]byte(src)) assert.True(t, addStmtToFuncBodyRelativeTo(df, "main", c.stmt, c.refStmt, c.direction)) buf := printToBuf(df) assertCodesEqual(t, fmt.Sprintf(expectedTemplate, c.expectedBody), buf.String()) } }) }
Markdown
UTF-8
6,996
2.59375
3
[ "MIT" ]
permissive
--- layout: post title: Speech by Senior Minister of State for Trade & Industry and Education S Iswaran at the 6th LNGA 2011 Conference, 1 March 2011 subtitle: 1 Mar 2011 permalink: /media/speeches/speech-by-senior-minister-of-state-for-trade-industry-and-education-s-iswaran-at-the-6th-lnga-2011-conference-1-march-2011 --- ### SPEECH BY SENIOR MINISTER OF STATE FOR TRADE & INDUSTRY AND EDUCATION S ISWARAN AT THE 6TH LNGA 2011 CONFERENCE, 1 MARCH 2011 Distinguished Guests, Ladies and Gentlemen, I am pleased to join you this morning at the “LNG Supplies for Asian Markets 2011” Conference. Amidst political upheavals, volatile energy markets and rising prices, the theme for this year’s conference – *“Current and Future LNG Markets: Surplus, Deficit or Balance, and When?”* – will challenge the best of experts and pundits. Much has transpired over recent months that has had a direct impact on global energy markets. The political uncertainty in Egypt, Tunisia and other parts of the Middle East has pushed crude oil prices well past the US$100 per barrel mark. These developments have a significant impact on the Asian LNG market, where the price of LNG is typically linked to oil prices. Apart from geopolitical events, gas markets and prices are also being driven by longer-term demand and supply dynamics. **Developments in Global Gas Markets** In general, the three distinct geographical regions of the global natural gas market - North America, Europe and Asia – have their own market dynamics. Consequently, gas prices in these markets move somewhat independently of each other. They are determined by each region’s unique systems of pipelines and LNG transportation routes that link gas supplies to their demand centres. Asia imports a substantial proportion of its gas over long distances and Asian LNG, therefore, generally commands a price premium of US$4 to US$10 per mmBtu over the other markets. However, global gas markets are fast evolving. The rise of unconventional gas in the US market has introduced a new and significant supply source. So much so that current US shale gas production, at about 10 billion cubic feet per day, accounts for 20 per cent of total US natural gas production. With such volumes, far from needing to import natural gas as was previously expected, the US may well become an exporter to the rest of the world. Energy companies are also beginning to develop unconventional gas operations in Australia, Europe and China. If this current rate of development is extrapolated, unconventional gas could be a game-changer for the global LNG industry. Meanwhile, the global LNG trade continues to expand rapidly. Qatar, the world’s largest LNG producer, announced in early February this year that its supply capacity has reached 77 Mtpa. Investments by both the BG Group and Santos in their Australian coal seam gas-based LNG projects will raise Australia’s LNG exports by about 16 Mtpa. With the US out of the import equation for now, LNG suppliers will focus on European and Asian markets. If the US were to emerge as a significant LNG exporter, there would be significant scope for arbitrage across the three regions, leading to more active trading in the LNG market. Fortunately, at least from a suppliers’ perspective, gas demand in Asia is rising in tandem with economic growth. China and India have emerged as significant new demand centres, along with new Southeast Asian buyers like Singapore and Thailand. In Southeast Asia, traditional LNG exporters like Malaysia and Indonesia are also building LNG re-gasification facilities to import LNG. Give the uncertainties and wider range of supply options, we can expect Asian importers to adopt variegated buying strategies, and to focus on securing better terms for their LNG. Indeed, buyers are beginning to negotiate for more competitive terms such as index diversification, shorter terms and better price. As the Asian market continues to develop, we may see more buyers adopt a portfolio of spot, short-term and long-term contracts. **Singapore’s LNG Commitments** Though a new player in this business, Singapore is committed to developing our own LNG industry. In 2008, we awarded BG Group an exclusive franchise to import and sell up to 3 Mtpa of LNG. Back then, we had estimated that demand would reach 3 Mtpa in 2018. However, our local power generation companies have already signed up for about 2 Mtpa of LNG and EMA expects the remaining volume to be taken up by other industry players who have expressed a keen interest to purchase LNG. Besides buying long-term LNG from BG, there are provisions within BG’s franchise for Singapore gas buyers to gain access to the spot LNG market. This means that once the terminal is in operation, gas users can take advantage of movements in spot prices, should these move in their favour. To ensure that there is sufficient terminal capacity to harness spot cargoes, Singapore LNG Corporation (SLNG) has commenced work on a third LNG storage tank in the LNG terminal. The terminal is on track to commence commercial operations by mid-2013. The third tank is scheduled to come on stream about a year later. The additional LNG storage capacity will encourage the trading of LNG in Singapore, allowing LNG traders to store and arbitrage LNG cargoes. Singapore’s first LNG terminal could also present new business opportunities in areas such as LNG bunkering. The Maritime Port Authority of Singapore (MPA) is partnering DNV of Norway to conduct a feasibility study on the use of LNG as a fuel for ships. As the maritime industry responds to calls to adopt environmentally-friendly solutions for fuel, LNG has the potential to be a cleaner alternative to marine diesel. The LNG terminal could also offer low-cost and low-carbon integrated services for industries located on Jurong Island. Cold energy from the LNG terminal could be used for air separation or as a coolant for plant operations. In addition, the terminal could also be used to import liquefied petroleum gas (LPG) as feedstock for petrochemical companies. Mr Neil McGregor, CEO of Singapore LNG, will share more details on this later today. **Conclusion** Like many other countries, Singapore continues to keep a keen eye on global energy market trends. Governments and businesses alike are mindful of the need to tack our sails according to the prevailing political and economic winds that buffet energy prices. Policy makers and business leaders have to synthesise a gamut of information on the market and global developments before charting a course. This conference is a good platform for public and private sector participants to network, keep abreast of recent trends and glean key insights on the evolving LNG market. I wish you all a fruitful conference and a pleasant stay in Singapore. Thank you. <br><br><br> *Source*: [<a href="https://www.mti.gov.sg/" target="_blank">Ministry of Trade and Industry</a>](https://www.mti.gov.sg/)
PHP
UTF-8
1,444
2.578125
3
[ "MIT" ]
permissive
<?php namespace Task; /* * This file is part of sample Task command package. * * (c) Piotr Plenik <piotr.plenik@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * Configuration class * * @author Piotr Plenik <piotr.plenik@gmail.com> */ class Configuration { private static $instance; private $config; public static function getInstance() { if (self::$instance === null) { self::$instance = new Configuration(); } return self::$instance; } public function __construct() { $iniFile = getcwd().'/config/app.ini'; $this->config = parse_ini_file($iniFile); } public function getLogFilename() { return getcwd().$this->config["logFilename"]; } public function getEmailFrom() { return $this->config['emailFrom']; } public function getEmailTo() { return $this->config['emailTo']; } public function getSmtpHost() { return $this->config['smtpHost']; } public function getSmtpPort() { return $this->config['smtpPort']; } public function getSmtpUsername() { return $this->config['smtpUsername']; } public function getSmtpPassword() { return $this->config['smtpPassword']; } public function getSmsTo() { return $this->config['smsTo']; } }
Java
UTF-8
257
1.851563
2
[]
no_license
package com.example.filip.gpstracker.ui.login.view; /** * Created by Filip on 08/03/2016. */ public interface LoginView { void onSuccessfulLogin(String username); void onFailedLogin(); void showProgressBar(); void hideProgressBar(); }
TypeScript
UTF-8
1,072
2.53125
3
[]
no_license
import { Component, OnInit } from '@angular/core'; import { RegisterModel } from '../models/register.model'; import { AuthenticationService } from '../auth.service'; @Component({ selector: 'app-register-form', templateUrl: './register-form.component.html', styleUrls: ['./register-form.component.css'] }) export class RegisterFormComponent { public model : RegisterModel; public registeredUser : string; public registerSuccess : boolean; public registerFail : boolean; constructor( private authService : AuthenticationService ) { this.model = new RegisterModel("", "", "", ""); } register() : void { this.authService.register(this.model) .subscribe( data => { this.successfulRegister(data); }, err => { this.registerFail = true; } ) } get diagnostics() : string { return JSON.stringify(this.model); } successfulRegister(data) : void { this.registerSuccess = true; this.registeredUser = data['username']; console.log(this.registeredUser) } }
C++
UTF-8
4,129
2.59375
3
[]
no_license
/* Copyright (c) 2016-2020, Elias Aebi All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <cstdint> #include <vector> namespace nitro { template <class T> class Property { void* object; using Getter = T (*)(void*); using Setter = void (*)(void*, T); Getter getter; Setter setter; public: Property(void* object, Getter getter, Setter setter): object(object), getter(getter), setter(setter) {} T get() const { return getter(object); } void set(T value) const { setter(object, value); } }; // create properties from getter and setter methods template <class T, class C, T (C::*Get)() const, void (C::*Set)(T)> Property<T> create_property(C* object) { return Property<T>(object, [](void* object) -> T { return (static_cast<C*>(object)->*Get)(); }, [](void* object, T value) { (static_cast<C*>(object)->*Set)(value); }); } template <class T, class C, const T& (C::*Get)() const, void (C::*Set)(const T&)> Property<T> create_property(C* object) { return Property<T>(object, [](void* object) -> T { return (static_cast<C*>(object)->*Get)(); }, [](void* object, T value) { (static_cast<C*>(object)->*Set)(value); }); } template <class T> constexpr T linear(const T& v1, const T& v2, float x) { return v1 * (1.f - x) + v2 * x; } class AnimationType { public: float (*get_y)(float x); AnimationType() {} constexpr AnimationType(float (*get_y)(float)): get_y(get_y) {} static const AnimationType LINEAR; static const AnimationType ACCELERATING; static const AnimationType DECELERATING; static const AnimationType OSCILLATING; static const AnimationType SWAY; }; class Animation { static std::vector<Animation*> animations; static std::uint64_t time; public: virtual ~Animation() {} virtual bool apply() = 0; static void add_animation(Animation* animation); static std::uint64_t get_time(); static bool apply_all(float advance_seconds); }; template <class T> class Animator: public Animation { T start_value, end_value; std::uint64_t start_time, duration; Property<T> property; AnimationType type; bool running; public: Animator(const Property<T>& property): property(property), running(false) {} void animate(T to, float duration, AnimationType type = AnimationType::SWAY) { start_value = property.get(); end_value = to; start_time = get_time(); this->duration = duration * 1000000.f + .5f; this->type = type; if (!running) { running = true; Animation::add_animation(this); } } bool apply() override { const float x = static_cast<float>(get_time() - start_time) / duration; if (x >= 1.f) { property.set(end_value); running = false; return true; } property.set(linear(start_value, end_value, type.get_y(x))); return false; } }; }
Markdown
UTF-8
3,727
3.1875
3
[]
no_license
--- layout: post title: "The spiral of refinement" date: 2023-08-26 12:00:00 -0400 description: "Like a spiral, drawing closer but never reaching the center, creative work involves iteration and refinement." tags: [Craft] maturity: scribble reading_time: 2 min --- <p class="dropCap">I repeat myself a lot. For instance, when exploring the research on peak aesthetic experiences, I wrote about <a href="{% post_url 2022-05-09-pae-content-2 %}">optimal difference</a>, the idea that there's an ideal point between too familiar and too strange at which our reward systems are maximally engaged. Then, when writing about <a href="{% post_url 2023-07-04-rule-of-three %}">the rule of three</a>, I stumbled back into the same discussion and <a href="{% post_url 2023-08-24-optimal-difference %}">wrote about optimal difference again</a>.</p> I worry about being too repetitive in these notes. Will it be boring or off-putting to you, dear reader? On the other hand, I feel that there's an unavoidable element of repetition that happens in any creative process. Musicians sometimes circle around melodic themes across multiple songs or even albums (sometimes knowingly, sometimes unknowingly). Fiction authors can end up using similar character archetypes and tropes. (I found in my own writing that the romantic interest subplots for two unpublished novels had some striking similarities.) Where does this repetition come from? I think it emerges naturally from the process of iterating and refining. In my work as a designer, I often need to iterate through multiple attempts at a solution. We develop a concept about the problem we are trying to solve or a solution to a problem that we've identified and then we test it out. Like a carpenter building a bench, we observe it from different angles, "sit in it" to see if it's comfortable. Inevitably, the first few attemtps will have obvious things wrong with them. But they weren't obvious until we made the attempt. Only in making the thing and observing it — in taking it out of our heads and putting it in the world — are we able to see the holes in our concept. We must go back, fix the problems, and try again. I see this sort of like a "creative spiral of refinement" in which we are circling around a solution, gradually getting closer, but never quite reaching the perfect center. In my writing, I see this process play out all the time. I often have an idea in my mind that I want to express. But before I write: - I don't know all of the implications of the idea. - I don't know the right structure and metaphors to best express the idea. - And — which feel I struggle with the most right now — I don't know what is the best _context_ into which to embed the idea. How best to "approach" the idea and show how it relates to other ideas. Discovering all that takes iteration and refinement. I must build several "benches" before I get one that's comfortable. I'm committed to ["working with the garage door up"](https://notes.andymatuschak.org/zCMhncA1iSE74MKKYQS5PBZ) in these notes. Fortunately or unfortunately, part of what that means is that this repetition will be on display. You, dear reader, will be invited to sit on many benches that aren't yet comfortable, many ideas that aren't yet perfectly clear. One benefit that does provide is that _you_ can have input into my writing. Ideas are more malleable when they aren't fully formed. So if something strikes you, let me know. (<a href="mailto:hello@natelistrom.com">hello@natelistrom.com</a>) Let's build some benches together. --- #### Read this next **[Shinichi Suzuki and the three domains of mastery]({% post_url 2015-01-23-suzuki %})** An exploration of the interaction between talent, education, and skill.
C#
UTF-8
1,145
2.53125
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(fileName = "New Inventory", menuName = "Inventory System/Inventory")] public class InventoryObject : ScriptableObject { public List<InventorySlot> inventorySlots = new List<InventorySlot>(); public void AddItem(ItemObject _item, int _quantity) { bool hasItem = false; for(int i = 0; i < inventorySlots.Count; i++) { if(inventorySlots[i].item == _item) { inventorySlots[i].IncreaseQuantity(_quantity); hasItem = true; break; } } if (!hasItem) { inventorySlots.Add(new InventorySlot(_item, _quantity)); } } } [System.Serializable] public class InventorySlot { public int quantity; public ItemObject item; public InventorySlot(ItemObject _item, int _quantity) { item = _item; quantity = _quantity; } public void IncreaseQuantity(int _quantity) { quantity += _quantity; } }
Markdown
UTF-8
1,593
3.203125
3
[]
no_license
## git配置 ### git配置文件位置 1. ```/etc/gitconfig```文件. 包含系统上每一个用户及他们仓库的通用配置. 如果在执行 git config 时带上 ```--system``` 选项,那么它就会读写该文件中的配置变量 2. ```~/.gitconfig``` 或 ```~/.config/git/config``` 文件. 只针对当前用户。 你可以传递 ```--global``` 选项让 Git 读写此文件,这会对你系统上 所有 的仓库生效 3. 当前使用仓库的 Git 目录中的 config 文件(即 .git/config). 针对该仓库。 你可以传递 --local 选项让 Git 强制读写此文件, 虽然默认情况下用的就是它. (当然, 你需要进入某个 Git 仓库中才能让该选项生效) 每一个级别会覆盖上一级别的配置,所以 .git/config 的配置变量会覆盖 /etc/gitconfig 中的配置变量 ### git配置常用命令 1. 可以通过以下命令查看所有的配置以及它们所在的文件 ``` git config --list --show-origin ``` 2. 通过 git config [key] 查看某一项配置 ``` git config user.name ``` 3. 通过 git config [key] [value]配置 ``` git config --global user.name "Joy" git config --global user.email joy@example.com ``` ## git帮助 ``` git help <verb> git <verb> --help man git-<verb> ``` 如果你不需要全面的手册,只需要可用选项的快速参考,那么可以用 -h 选项获得更简明的 “help” 输出 ``` git add -h git push --help ``` 1. 关联远程分支:git push --set-upstream origin xxx 2. 删除远程分支:git push origin --delete xxx 3. 从远程分分支co:git checkout -b xxx origin/xxx
C++
UTF-8
2,217
2.75
3
[]
no_license
#ifndef LIBDL_HELPER_H #define LIBDL_HELPER_H #include <iostream> #include "../src/Tensor.h" using namespace Catch::literals; template<std::int64_t N> auto makeTensor(const std::int64_t (&dimensions)[N], bool requiresGrad = true) { std::array<std::int64_t, N> d; std::copy_n(std::begin(dimensions), N, std::begin(d)); auto ret = std::make_shared<Tensor<std::float_t, N>>(d, requiresGrad); if (requiresGrad) ret->setGradFn(std::make_shared<Leaf<std::float_t, N>>(ret)); return ret; } template<std::int64_t N> auto trange(const std::int64_t (&dimensions)[N], bool requiresGrad = true, std::int64_t mod = 1000) { auto ret = makeTensor(dimensions, requiresGrad); for (std::int64_t i = 0; i < ret->data->size(); i++) ret->data->data()[i] = static_cast<std::float_t>((i % mod) + 1); return ret; } template<std::int64_t N> auto constant(const std::int64_t (&dimensions)[N], std::float_t value, bool requiresGrad = true) { auto ret = makeTensor(dimensions, requiresGrad); ret->data->setConstant(value); return ret; } template<std::int64_t N> auto random(const std::int64_t (&dimensions)[N], bool requiresGrad = true) { auto ret = makeTensor(dimensions, requiresGrad); *ret->data = ret->data->random() * ret->data->constant(2.) - ret->data->constant(1.); return ret; } template<std::int64_t N> auto setGradAndBackward(const std::shared_ptr<Tensor<std::float_t, N>> &t, std::int64_t mod = 1000) { Eigen::Tensor<std::float_t, N> grad(t->data->dimensions()); for (std::int64_t i = 0; i < grad.size(); i++) grad.data()[i] = static_cast<std::float_t>((i % mod) + 1); t->gradFn.value()->addGrad(grad); t->backward(0); return grad; } template<std::int64_t R> bool tensorEqual(const Eigen::Tensor<std::float_t, R> &a, const Eigen::Tensor<std::float_t, R> &b, std::float_t atol = 1e-6) { if (a.size() != b.size()) return false; for (std::int64_t i = 0; i < R; i++) if (a.dimension(i) != b.dimension(i)) return false; for (std::int64_t i = 0; i < a.size(); i++) if (abs(a.data()[i] - b.data()[i]) > atol) return false; return true; } #endif //LIBDL_HELPER_H
C
UTF-8
2,244
3.703125
4
[]
no_license
/*Yugraj Singh *Shuffle.c *Main program that performs the permutations */ #include<stdio.h> #include<stdlib.h> #include<string.h> #include "List.h" #define MAX_LEN 300 /*shuffle *Pre: takes to ListRef *Pos: shuffles the list L by the permutations listed in List P */ void shuffle(ListRef L, ListRef P){ int index = 2; int holdIndex; moveTo(P,0); while( offEnd(P) != 1){ holdIndex = getLength(L) + getCurrent(P)-index; moveTo(L,holdIndex); insertAfterCurrent(L,getFront(L)); deleteFront(L); index++; moveNext(P); } } int main(int argc, char* argv[]){ FILE* in; FILE* out; char line[MAX_LEN]; char* token; int order, size; if (argc !=3){ printf("Usage: %s infile outfile\n",argv[0]); exit(EXIT_FAILURE); } /*opens the input and output files*/ in = fopen(argv[1], "r"); out = fopen(argv[2], "w"); /* check to make sure the input and output files are functioning*/ if ( in == NULL){ printf("Unable to open file %s for reading\n",argv[1]); exit(EXIT_FAILURE); } if ( out == NULL){ printf("Unable to open file %s for writing\n",argv[2]); exit(EXIT_FAILURE); } /*reads the first line in file and assigns the value to size*/ if( fgets(line,MAX_LEN,in) != NULL){ token = strtok(line," \n"); while(token!= NULL){ size = atoi(token); token = strtok(NULL, " \n"); } } /* main loop*/ int i; for( i=0; i< size; i++){ fgets(line,MAX_LEN,in); token = strtok(line," \n"); ListRef P = newList(); ListRef L = newList(); /*inserts the data values from input file*/ while(token!=NULL){ insertBack(P,atoi(token)); token = strtok(NULL," \n"); } /* creates a List to perform the permutations on*/ int j = 0; while( j<getLength(P)){ insertBack(L,j+1); j++; } /*copys the list*/ ListRef listCopy = copyList(L); shuffle(L,P); printList(out,L); order = 1; /*counts the number of permutations being performed*/ while( !equals(listCopy,L)){ shuffle(L,P); order++; } /*print the order, and frees the Heap memory from the list*/ fprintf(out," order = %d\n", order); freeList(&listCopy); freeList(&L); freeList(&P); } /* closes the input and output files*/ fclose(in); fclose(out); return(0); }
Python
UTF-8
2,382
3.484375
3
[]
no_license
from typing import List from collections import deque # 투포인터 문제 class Solution: def trap(self, height: List[int]) -> int: if not height: return 0 volume = 0 left, right = 0, len(height) - 1 left_max, right_max = height[left], height[right] while left < right: left_max, right_max = max(height[left], left_max), max( height[right], right_max ) if left_max <= right_max: volume += left_max - height[left] left += 1 else: volume += right_max - height[right] right -= 1 return volume # def trap(self, height: List[int]) -> int: # left, right, result = 0, 1, 0 # blocks = [] # while len(height) > right + 1: # if height[left] <= height[right]: # result += self.calculate(blocks, min(height[left], height[right])) # left = right # right = left + 1 # blocks = [] # elif height[left] > height[right]: # blocks.append(height[right]) # right += 1 # right = len(blocks) # left = 0 # if len(blocks) != 0 : # result += self.trap_calculcate(height[::-1],0, 1) # return result # def trap_calculcate(self,height, left, right ): # blocks=[] # result = 0 # while len(height) > right + 1: # if height[left] <= height[right]: # result += self.calculate(blocks, min(height[left], height[right])) # print(blocks) # left = right # right = left + 1 # blocks = [] # elif height[left] > height[right]: # blocks.append(height[right]) # right += 1 # return result # # print(result) # def calculate(self, blocks, pillar): # sum_of_water = 0 # for block in blocks: # if pillar - block > 0: # sum_of_water += pillar - block # return sum_of_water # height = [4,2,0,3,2,4,3,4] height = [4, 2, 0, 3, 2, 5] # height = [4, 2, 3] # height = [0,1,0,2,1,0,1,3,2,1,2,1] s = Solution() # s.trap(height) # height = [1000,999,998,997,996,996,996,996,996] print(s.trap(height))
Java
UTF-8
6,906
2.875
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 com.sg.dvdlibrary.ui; import com.sg.dvdlibrary.dto.DVD; import java.util.ArrayList; import java.util.List; /** * * @author patty */ public class DVDLibraryView { private UserIO io; public DVDLibraryView(UserIO io) { this.io = io; } public int printMenuAndGetSelection() { io.print("DVD Library Main Menu"); io.print("1) List All DVDs"); io.print("2) Add a new DVD"); io.print("3) View a DVD"); io.print("4) Remove a DVD"); io.print("5) Edit a DVD"); io.print("6) Search for a DVD by Title"); io.print("7) Exit"); return io.readInt("Please select from the above choices.", 1, 7); } public DVD getNewDVDInfo(String dvdId) { // in case user does not provide info, or just hits enter String substituteInfo = "No data on file"; String title = io.readString("Please enter title:"); String releaseDate = io.readString("Please enter release date (as yyyy-mm-dd):"); String ratingMPAA = io.readString("Please enter the MPAA rating:"); String directorName = io.readString("Please enter director's name:"); String studio = io.readString("Please enter studio name:"); String note = io.readString("Please enter any notes:"); DVD currentDVD = new DVD(dvdId); currentDVD.setTitle(title); currentDVD.setReleaseDate(releaseDate); currentDVD.setRatingMPAA(ratingMPAA); currentDVD.setDirectorName(directorName); currentDVD.setStudio(studio); if (!note.equals("")) { currentDVD.setNote(note); } else { currentDVD.setNote(substituteInfo); } // check to see if any info was entered // otherwise indicate that the field was not provided by the user // if (!title.equals("")) { // currentDVD.setTitle(title); // } else { // currentDVD.setTitle(substituteInfo); // } // //// if (!releaseDate.equals("")) { //// //// } // // if (!releaseDate.equals("")) { // currentDVD.setReleaseDate(releaseDate); // } else { // currentDVD.setReleaseDate(substituteInfo); // } // if (!ratingMPAA.equals("")) { // currentDVD.setRatingMPAA(ratingMPAA); // } else { // currentDVD.setRatingMPAA(substituteInfo); // } // if (!directorName.equals("")) { // currentDVD.setDirectorName(directorName); // } else { // currentDVD.setDirectorName(substituteInfo); // } // if (!studio.equals("")) { // currentDVD.setStudio(studio); // } else { // currentDVD.setStudio(substituteInfo); // } // if (!note.equals("")) { // currentDVD.setNote(note); // } else { // currentDVD.setNote(substituteInfo); // } return currentDVD; } public void displayCreateDVDBanner() { io.print("=== Create DVD ==="); } public void displayCreateSuccessBanner() { io.readString("DVD successfully created. Please hit enter to continue."); } public void displayDVDList(List<DVD> dvdList) { for (DVD currentDVD : dvdList) { io.print(currentDVD.getDVDId() + ": " + currentDVD.getTitle()); } io.readString("Please hit enter to continue."); } public void displayDisplayAllBanner() { io.print("=== Display All DVDs ==="); } public void displayDisplayDVDBanner() { io.print("=== Display DVD ==="); } public String getDVDIdChoice() { return io.readString("Please enter the DVD ID."); } public void displayDVD(DVD dvd) { if (dvd != null) { io.print(" DVD ID: " + dvd.getDVDId()); io.print(" Title: " + dvd.getTitle()); io.print(" Release Date: " + dvd.getReleaseDate().toString()); io.print(" MPAA Rating: " + dvd.getRatingMPAA()); io.print("Director's Name: " + dvd.getDirectorName()); io.print(" Studio: " + dvd.getStudio()); io.print(" Movie Notes: " + dvd.getNote()); } else { io.print("No such DVD."); } io.readString("Please hit enter to continue."); } public void displayRemoveDVDBanner() { io.print("=== Remove DVD ==="); } public void displayRemoveSuccessBanner() { io.print("If such a DVD existed, it is now gone. Please hit enter to continue."); } public void displayExitBanner() { io.print("Good bye!"); } public void displayUnknownCommandBanner() { io.print("Unknown Command..."); } public void displayErrorMessage(String errorMsg) { io.print("=== ERROR ==="); io.print(errorMsg); } public void displayEditDVDBanner() { io.print("=== Edit DVD ==="); } public void displaySearchTitleBanner() { io.print("=== Search for DVD by Title ==="); } public String getSearchString() { String search = io.readString("Enter a title or part of one to search for a DVD:"); return search; } public DVD getEditDVDInfo(DVD dvd) { String title = io.readString("Please enter NEW title, otherwise hit enter:"); String releaseDate = io.readString("Please enter NEW release date, otherwise hit enter:"); String ratingMPAA = io.readString("Please enter the NEW MPAA rating, otherwise hit enter:"); String directorName = io.readString("Please enter NEW director's name, otherwise hit enter:"); String studio = io.readString("Please enter NEW studio name, otherwise hit enter:"); String note = io.readString("Please enter NEW notes, otherwise hit enter:"); // checks to see if any info was entered, if not, previous info left unchanged if (!title.equals("")) { dvd.setTitle(title); } if (!releaseDate.equals("")) { dvd.setReleaseDate(releaseDate); } if (!ratingMPAA.equals("")) { dvd.setRatingMPAA(ratingMPAA); } if (!directorName.equals("")) { dvd.setDirectorName(directorName); } if (!studio.equals("")) { dvd.setStudio(studio); } if (!note.equals("")) { dvd.setNote(note); } return dvd; } public void displayPreviousDVDInfo() { io.print("=== EXISTING DVD INFO ==="); } public void displayEditDVDSuccessBanner() { io.print("=== DVD Successfully Edited ==="); } }
Python
UTF-8
2,817
2.734375
3
[]
no_license
from django import template # 导入包 # 创建注册器 变量名必须为register register = template.Library() @register.inclusion_tag('page.html') def page(total_num, current_num, url_prefix, page_max_num=9): ''' total_num 总页数 current_num 当前页数 url_prefix 链接前缀 page_max_num 展示页数(默认展示9页) ''' # 用于标签拼接 page_list = [] # 判断总页数和固定页数大小关系,如果总页数小于固定展示页数,固定页复制为总页数 page_max_num = page_max_num if page_max_num < total_num else total_num # 定义一个中间变量用于当前页居中 half_num = page_max_num // 2 # 计算开始页 start_num = current_num - half_num # 计算结束页 end_num = current_num + half_num # 异常赋值,如url手动把page值改为0.5等负数情况 if start_num < 1: start_num = 1 end_num = page_max_num if end_num > total_num: end_num = total_num start_num = total_num - page_max_num + 1 # 生成页面 if current_num == 1: page_list.append( '<li class="disabled"><span aria-label="Previous">首页</span></li>' ) page_list.append( '<li class="disabled"><span aria-label="Previous">&laquo;</span></li>' ) else: page_list.append( '<li><a href="{}?page={}" aria-label="Previous"><span aria-hidden="true">首页</span></a></li>'.format( url_prefix, 1) ) page_list.append( '<li><a href="{}?page={}" aria-label="Previous"><span aria-hidden="true">&laquo;</span></a></li>'.format( url_prefix, current_num - 1) ) for i in range(start_num, end_num + 1): if i == current_num: page_list.append( ' <li class="active"><a href="#">{}</a></li>'.format(i) ) else: page_list.append( ' <li><a href="{}?page={}">{}</a></li>'.format(url_prefix, i, i) ) if current_num == total_num: page_list.append( '<li class="disabled"><span aria-label="Next">&raquo;</span></li>' ) page_list.append( '<li class="disabled"><span aria-label="Next">尾页</span></li>' ) else: page_list.append( '<li><a href="{}?page={}" aria-label="Next"><span aria-hidden="true">&raquo;</span></a></li>'.format( url_prefix, total_num) ) page_list.append( '<li ><a href="{}?page={}" aria-label="Previous"><span aria-hidden="true">尾页</span></a></li>'.format( url_prefix, total_num) ) page_list_str = "".join(page_list) return {'page_list': page_list_str}
PHP
UTF-8
846
2.890625
3
[]
no_license
<?php /** * Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details. */ namespace MagentoDevBox\Library; /** * Class for communication with database */ class Db { /** * @var \PDO[] */ private static $connections; /** * Get connection to database * * @param string $host * @param string $user * @param string $password * @param string $dbName * @return \PDO */ public static function getConnection($host, $user, $password, $dbName) { $key = sprintf('%s/%s/%s/%s', $host, $user, $password, $dbName); if (empty(static::$connections[$key])) { static::$connections[$key] = new \PDO(sprintf('mysql:dbname=%s;host=%s', $dbName, $host), $user, $password); } return static::$connections[$key]; } }
Java
UTF-8
1,652
2.359375
2
[]
no_license
package com.anmis.anmis.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.anmis.anmis.activity.ClickEnentManager; import com.anmis.anmis.util.Utils; /** * Created by niushuowen on 2016/4/28. */ public class MyRecyclerViewAdaptes extends RecyclerView.Adapter { private Context context; private String[]datas; public MyRecyclerViewAdaptes(Context context,String[]datas){ this.context = context; this.datas = datas; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { Button button = new Button(context); RecyclerView.LayoutParams params = new RecyclerView.LayoutParams(Utils.getScreenWidth(context)/3,Utils.getScreenWidth(context)/3); button.setLayoutParams(params); RecyclerView.ViewHolder viewHolder = new ViewHoler(button); return viewHolder; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { ((Button)holder.itemView).setText(datas[position]); ((Button)holder.itemView).setAllCaps(false); ClickEnentManager.registerButton((Button)holder.itemView,position); } @Override public int getItemCount() { return datas.length; } @Override public int getItemViewType(int position) { return super.getItemViewType(position); } class ViewHoler extends RecyclerView.ViewHolder { public ViewHoler(View itemView) { super(itemView); } } }
Markdown
UTF-8
3,503
2.984375
3
[ "CC-BY-4.0", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
[^1]: Patent text contain patent, [**NPL**](./vocabulary#non-patent-literature-npl), software, database, product, etc citations and NPL citations contain bibliographical references, office actions, search reports, patents, webpages, norms & standards, product documentations, databases and litigations. [^2]: Bibliographical reference, office action, search report, patent, webpage, norm & standard, product documentation, database and litigation [^nvy]: <span style="color:red">Not validated yet</span> # <small>Welcome to</small> PatCit *Making Patent Citations Uncool Again* Patents are at the crossroads of many innovation nodes: science, industry, products, competition, etc. Such interactions can be identified through citations *in a broad sense*. It is now common to use patent-to-patent citations to study some aspects of the innovation system. However, **there is much more buried in the [**Non Patent Literature (NPL)**](./vocabulary#non-patent-literature-npl) citations and in the patent text itself**.[^1] Good news, Natural Language Processing (NLP) tools now enable social scientists to excavate and structure this long hidden information. **That's the purpose of this project**. ## Achievements So far, we have: 1. **classified** the 40 million NPL citations reported in the [**DOCDB**](./vocabulary#epo-worldwide-bibliographic-data-docdb) database in 9 distinct research oriented classes[^2] with a 90% accuracy rate. 2. [**parsed**](./vocabulary#parse) and [**consolidated**](./vocabulary#consolidate) the 27 million [**NPL**](./vocabulary#non-patent-literature-npl) citations classified as bibliographical references. !!! more From the 27 million bibliographical references: 1. 11 million (40%) were matched with a [**DOI**](./vocabulary#digital-object-identifier-doi) with a 99% [**precision**](./vocabulary#precision) rate 2. the main bibliographic attributes were parsed with [**accuracy**](./vocabulary#accuracy) rates ranging between 71% and 92% for the remaining 16 million (60%) 3. [**extracted**](./vocabulary#extract), [**parsed**](./vocabulary#parse) and [**consolidated**](./vocabulary#consolidate) in-text bibliographical references and patent citations from the body of all time USPTO patents.[^nvy] !!! more From the 16 million USPTO patents, we have: 1. [**extracted**](./vocabulary#extract) and [**parsed**](./vocabulary#parse) 70 million in-text bibliographical references and 80 million patent citations[^nvy]. 2. found a [**DOI**](./vocabulary#digital-object-identifier-doi) for 13+ million in-text bibliographical references (18%)[^nvy]. ## Features #### Open - The code is licensed under MIT-2 and the dataset is licensed under CC4. Two highly permissive licenses. - The project is thought to be *dynamically improved by and for the community*. Anyone should feel free to open discussions, raise issues, request features and contribute to the project. #### Comprehensive - We address *worldwide patents*, as long as the data is available. - We address *all classes of citations*[^2], not only bibliographical references. - We address front-page and in-text citations. #### Highest standards - We use and implement state-of-the art machine learning solutions. - We take great care to implement only the most efficient solutions. We believe that computational resources should be used sparsely, for both environmental sustainability and long term financial sustainability of the project.
Python
UTF-8
169
2.53125
3
[ "MIT" ]
permissive
class ConditionalFormatting(object): def __init__(self): self.ranges = {} self.priority = 0 def add(self, range_string, rule): pass
Go
UTF-8
1,514
2.546875
3
[]
no_license
package callbacks import ( "strings" f "../functions" utils "../utils" "github.com/bwmarrin/discordgo" ) var ( commChan = make(chan string) recording = false ) // OnMessage will be executed every time the discord session will receive a message func OnMessage(s *discordgo.Session, m *discordgo.MessageCreate) { if m.Author.ID == s.State.User.ID || m.Author.Bot { return } if m.ChannelID == "276583899088289793" { s.MessageReactionAdd(m.ChannelID, m.Message.ID, "🐀") } f.Shitpost(s, m) if utils.ArrayContainsUser(m.Mentions, s.State.User) { c, err := s.State.Channel(m.ChannelID) utils.CheckError(err, "Couldn't get the Channel with the ID: ", m.ChannelID) _, err = s.State.Guild(c.GuildID) utils.CheckError(err, "Couldn't get the Server with the ID: ", c.GuildID) split := strings.SplitN(m.ContentWithMentionsReplaced(), " ", 3) command, line := split[1], "" if len(split) == 3 { line = split[2] } switch command { case "echo": f.Echo(s, m, line) case "record": if !recording && (m.Author.Username == "Endmonaut" || m.Author.Username == "Liikt") { go f.Record(s, m, line, commChan) recording = true } else { s.ChannelMessageSend(m.ChannelID, "I CURRENTLY AM RECORDING YOU FUCK") } case "pause": commChan <- "pause" case "resume": commChan <- "resume" case "stop": commChan <- "stop" recording = false case "debug": f.Debug(s, m) default: go s.ChannelMessageSend(m.ChannelID, "I AM LIVING CANCER") } } }
Markdown
UTF-8
922
2.8125
3
[]
no_license
# PrepHoops Backend Challenge ## Overview This exercise will have the candidate build a simple API which will generate JSON data used to populate the nav of the PrepHoops Frontend Challenge. ## Deliverables - A forked version of this repo with an attached MySQL database file with the database structure and contents so we are able to recreate your system on our local environments ## Guidelines - Laravel is the preferred framework, but if you'd like to use another PHP framework, go for it. - Auth is not required as this will be a public endpoint ## Version 0.1.0 ## Get Started ``` git clone https://github.com/JeanHules/prephoops-backend-challenge.git cd prephoops-backend-challenge composer install php artisan key:generate php artisan serve ``` ### Requested Endpoints Create an endpoint that replicates the data found in the nav.json file at the root of this project. - **localhost:8000/nav**
Python
UTF-8
1,009
2.6875
3
[]
no_license
#!/usr/bin/python import os.path import re import argparse from subprocess import Popen, PIPE, STDOUT if __name__ == '__main__': parser = argparse.ArgumentParser(description="") parser.add_argument('-f', '--file', help="File to parse") args = parser.parse_args() if (args.file != None): firstLine = re.compile(r"\d*:(?P<length>\d+):\w+") secondline = re.compile(r"(\(\s){2}-(?P<mfe>\d+)*") L = open(args.file,"r").read().splitlines() length = 0 mfe = 0 new = 0 for l in L: m1 = firstLine.match(l) if (m1 != None): if (new): print "%s\t0" % (m1.group("length"),) new = 1 length = m1.group("length") if (new): m2 = secondline.match(l) if (m2 != None): mfe = int(m2.group('mfe'))/100 new = 0 print "%s\t%d" % (length,mfe)
Python
UTF-8
1,774
2.578125
3
[ "MIT" ]
permissive
from gensim.models.doc2vec import Doc2Vec, TaggedDocument import pandas as pd from nltk.tokenize import word_tokenize import random random.seed(42) true_dataset = pd.read_csv("../dataset/preprocessed_true.csv") true_dataset.dropna(axis=0, how='any', inplace=True) fake_dataset = pd.read_csv("../dataset/preprocessed_fake.csv") fake_dataset.dropna(axis=0, how='any', inplace=True) true_corpus = list(true_dataset["text"]) fake_corpus = list(fake_dataset["text"]) sentences_true = [_.split() for _ in true_corpus] sentences_fake = [_.split() for _ in fake_corpus] sentences_true_fake = sentences_true + sentences_fake true_uniq = list(set(true_corpus).difference(set(fake_corpus))) fake_uniq = list(set(fake_corpus).difference(set(true_corpus))) random.shuffle(true_uniq) random.shuffle(fake_uniq) model = Doc2Vec.load('../model_doc2vec/true_fake_doc2vec.bin') true_sentence = true_uniq[0] fake_sentence = fake_uniq[0] print(true_sentence) print(fake_sentence) true_test_doc = word_tokenize(true_sentence.lower()) fake_test_doc = word_tokenize(fake_sentence.lower()) true_test_doc_vector = model.infer_vector(true_test_doc) fake_test_doc_vector = model.infer_vector(fake_test_doc) true_result = model.docvecs.most_similar(positive = [true_test_doc_vector], topn=3) fake_result = model.docvecs.most_similar(positive = [fake_test_doc_vector], topn=3) print("="*20, "Real", "="*20) for i,j in true_result: print("Sentence: {} - Similarity score: {}".format(' '.join(i.strip() for i in sentences_true_fake[i]),j)) print("="*20, "Fake", "="*20) for i,j in fake_result: print("Sentence: {} - Similarity score: {}".format(' '.join(i.strip() for i in sentences_true_fake[i]),j)) print("="*20, "End", "="*20)
Java
UTF-8
926
2.515625
3
[]
no_license
package SeleniumAssignments; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import io.github.bonigarcia.wdm.WebDriverManager; public class LinkTextAssi { public static void main(String[] args) { WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); driver.get("https://www.freshworks.com/"); List <WebElement> linklist = driver.findElements(By.tagName("a")); //System.out.println("Total links : " + linklist.size()); List <WebElement> llist = driver.findElement(By.className("footer-main")).findElements(By.tagName("a")); System.out.println("Footer link text :"); for (int k = 0 ; k < llist.size(); k++) { String txt = llist.get(k).getText(); if(! txt.isEmpty()) { System.out.println(k + " ------->" + txt); } } } }
Java
UTF-8
346
1.65625
2
[]
no_license
package cl.bennu.plcbus.core.persistence.iface; import cl.bennu.plcbus.common.domain.MovementActionDetail; /** * Created with IntelliJ IDEA. * User: _Camilo * Date: 08-07-13 * Time: 08:49 AM */ public interface IMovementActionDetailDAO extends IBaseDAO<MovementActionDetail> { void deleteByMovementActionId(Long movementActionId); }
C++
UTF-8
607
2.703125
3
[]
no_license
#pragma once class Moon : public Renderer { public: Moon(Shader* shader); ~Moon(); void Update(); void Render(float theta); Texture* GetMoonTexture(){ return moon; } Texture* GetMoonGlowTexture() { return moonGlow; } float& GetDistance() { return distance; } float& GetGlowDistance () { return glowDistance; } private: float GetAlpha(float theta); Matrix GetTransform(float theta); Matrix GetGlowTransform(float theta); private: float distance, glowDistance; ID3DX11EffectScalarVariable* sAlpha; Texture* moon; Texture* moonGlow; ID3DX11EffectShaderResourceVariable* sMoon; };
Java
UTF-8
2,947
2.15625
2
[]
no_license
package com.sbsa.benchmark.solaceclient; import java.util.concurrent.ConcurrentHashMap; import com.sbsa.benchmark.Consumer; import com.sbsa.benchmark.DeliveryMode; import com.sbsa.benchmark.EndPointType; import com.sbsa.benchmark.Endpoint; import com.sbsa.benchmark.Factory; import com.sbsa.benchmark.Monitor; import com.sbsa.benchmark.Producer; import com.solacesystems.jcsmp.EndpointProperties; import com.solacesystems.jcsmp.JCSMPException; import com.solacesystems.jcsmp.JCSMPFactory; import com.solacesystems.jcsmp.JCSMPProperties; import com.solacesystems.jcsmp.JCSMPSession; import com.solacesystems.jcsmp.Queue; public class SolClientFactory extends Factory { JCSMPFactory jcsmp = JCSMPFactory.onlyInstance(); final JCSMPProperties properties = new JCSMPProperties(); public SolClientFactory(ConcurrentHashMap<String, Object> runtimeParamaters) throws Exception { super(runtimeParamaters); initialize(); } private void initialize() throws Exception { properties.setProperty(JCSMPProperties.HOST, (String) runtimeParamaters.get("BrokerIP")); properties.setProperty(JCSMPProperties.VPN_NAME, "default"); properties.setProperty(JCSMPProperties.USERNAME, "clientUsername"); properties.setProperty(JCSMPProperties.MESSAGE_CALLBACK_ON_REACTOR, true); } private JCSMPSession createSession() throws JCSMPException { final JCSMPSession session = jcsmp.createSession(properties); session.connect(); return session; } @Override public Producer createProducer(Monitor monitor, Endpoint endpoint) throws Exception { Producer producer = new SolClientProducer(monitor, endpoint); return producer; } @Override public Consumer createConsumer(Monitor monitor, Endpoint endpoint) throws Exception { Consumer consumer = new SolClientConsumer(monitor, endpoint); return consumer; } @Override public Endpoint createEndPoint(String destination) throws Exception { Endpoint endpoint = new Endpoint(); EndPointType endPointType = (EndPointType) runtimeParamaters.get("EndpointType"); DeliveryMode deliveryMode = (DeliveryMode) runtimeParamaters.get("DeliveryMode"); JCSMPSession session = createSession(); switch (endPointType) { case Topic: { endpoint.setEndpoint(endPointType, deliveryMode, null, session, jcsmp.createTopic(destination)); } break; case Queue: { final Queue queue = jcsmp.createQueue(destination); final EndpointProperties endpointProps = new EndpointProperties(); endpointProps.setPermission(EndpointProperties.PERMISSION_CONSUME); endpointProps.setAccessType(EndpointProperties.ACCESSTYPE_NONEXCLUSIVE); session.provision(queue, endpointProps, JCSMPSession.FLAG_IGNORE_ALREADY_EXISTS); endpoint.setEndpoint(endPointType, deliveryMode, null, session, queue); } break; default: throw new RuntimeException("No Endpoint defined"); } return endpoint; } }
C++
UTF-8
2,162
2.59375
3
[]
no_license
#include "stdafx.h" #include <stdio.h> #include <stdlib.h> #include <Windows.h> #include<io.h> #include<iostream> #include<vector> #include <fstream> #include <sstream> #include <iterator> #include <string> #include "EnumFiles.h" #include <cassert> using namespace std; #define MAX_PATH 1024 vector<string> CEnumFiles::listdir(const string &path) { string dir = path; vector<string> s; _finddata_t fileDir; long lfDir; if ((lfDir = _findfirst(dir.c_str(), &fileDir)) == -1l){ //printf("No file is found\n"); } else { do { string str(fileDir.name); if (str.find('.') == -1) s.push_back(str); } while (_findnext(lfDir, &fileDir) == 0); } _findclose(lfDir); return s; } void CEnumFiles::findfile(const string &str) { string s = str; vector<string> tmp = listdir(s + "\\*"); for (int i = 0; i<tmp.size(); i++) { string temp = s + "\\" + tmp[i]; res.push_back(temp); findfile(temp); } } //************************************ // Method: countColumnRowNumber // @date : 2018/4/10 16:50 // @author : Ruidong Xue //************************************ bool CEnumFiles::countColumnRowNumber(const string& file_name) { //bool getFileStream(const string& file_name, T(&mg_input_data)[ROW][COLUMN]) { //T* mp_pointer = *mg_input_data; /*T* mp_pointer = &mg_input_data[0][0];*/ string fs_row_string; string fs_row_number; /*for (int i = 0; i < ROW; i++) { for (int j = 0; j <= COLUMN; j++) { mg_input_data[i][j] = NULL; } }*/ ifstream file_stream = ifstream(file_name); assert(file_stream); /*if (!file_stream) { cout << "Can't open file " << file_name << " !!!!"; return false; }*/ int row_count = 0; int column_count = 0; int column_number = 0; while (!file_stream.eof()) { row_count++; file_stream >> fs_row_string; stringstream sstr(fs_row_string); while (getline(sstr, fs_row_number, ',')) { stod(fs_row_number); if (column_number == 0) { column_count++; } } column_number = column_count; } file_stream.close(); cout << row_count << ", " << column_number << endl; return true; }
Java
UTF-8
1,876
3.140625
3
[]
no_license
package com.tanmay.calculator; import java.util.HashSet; import java.util.Set; public class CalculatorContext { private String text; private boolean isCustom = false; private String effectiveString; private String delimiter; public CalculatorContext(String text) { this.text = text; init(); } private void init() { String[] chunks = text.split("\n"); if (text.startsWith("//")) { isCustom = true; effectiveString = chunks[1]; } else { effectiveString = text; } delimiter = getCustomDelimiter(chunks[0]); } public String getDelimiter() { return delimiter; } public String getText() { return text; } public boolean isCustom() { return isCustom; } public String getEffectiveString() { return effectiveString; } @Override public String toString() { return "{" + "text='" + text + ", isCustom=" + isCustom + ", effectiveString=" + effectiveString + ", delimiter=" + delimiter + '}'; } public String[] getNumbers() { return effectiveString.split(delimiter); } private String getCustomDelimiter(String line) { Set<Character> charSet = new HashSet<>(); if (isCustom) { line = line.substring(2); StringBuilder multilineDelimiter = new StringBuilder(); for (Character delimiter : line.toCharArray()) { multilineDelimiter.append("["); multilineDelimiter.append(delimiter); multilineDelimiter.append("]"); charSet.add(delimiter); } if (charSet.size() == 1) { return multilineDelimiter.toString(); } return "[" + line + "]"; } return "[\n,]"; } }
Java
UTF-8
20,161
2.703125
3
[]
no_license
package gapp.ulg.game.util; import gapp.ulg.game.GameFactory; import gapp.ulg.game.PlayerFactory; import gapp.ulg.game.board.GameRuler; import gapp.ulg.game.board.Move; import gapp.ulg.game.board.Player; import gapp.ulg.games.GameFactories; import gapp.ulg.play.PlayerFactories; import static gapp.ulg.game.util.PlayerGUI.MoveChooser; import java.nio.file.Path; import java.util.concurrent.ExecutorService; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinTask; import java.util.function.Consumer; /** * Un {@code PlayGUI} è un oggetto che facilita la gestione di partite in una * applicazione controllata da GUI. Un {@code PlayGUI} segue lo svolgimento di una * partita dalla scelta della {@link GameFactory} e dei {@link PlayerFactory} e di * tutte le mosse fino alla fine naturale della partita o alla sua interruzione. * Inoltre, un {@code PlayGUI} aiuta sia a mantenere la reattività della GUI che a * garantire la thread-safeness usando un thread di confinamento per le invocazioni * di tutti i metodi e costruttori degli oggetti coinvolti in una partita. * * @param <P> tipo del modello dei pezzi */ public class PlayGUI<P> { /** * Un {@code Observer} è un oggetto che osserva lo svolgimento di una o più * partite. Lo scopo principale è di aggiornare la GUI che visualizza la board * ed eventuali altre informazioni a seguito dell'inizio di una nuova partita e * di ogni mossa eseguita. * * @param <P> tipo del modello dei pezzi */ public interface Observer<P> { /** * Comunica allo {@code Observer} il gioco (la partita) che sta iniziando. * Può essere nello stato iniziale o in uno stato diverso, ad es. se la * partita era stata sospesa ed ora viene ripresa. L'oggetto {@code g} è * una copia del {@link GameRuler} ufficiale del gioco. Lo {@code Observer} * può usare e modificare {@code g} a piacimento senza che questo abbia * effetto sul {@link GameRuler} ufficiale. In particolare lo {@code Observer} * può usare {@code g} per mantenersi sincronizzato con lo stato del gioco * riportando in {@code g} le mosse dei giocatori, vedi * {@link Observer#moved(int, Move)}. L'uso di {@code g} dovrebbe avvenire * solamente nel thread in cui il metodo è invocato. * <br> * <b>Il metodo non blocca, non usa altri thread e ritorna velocemente.</b> * * @param g un gioco, cioè una partita * @throws NullPointerException se {@code g} è null */ void setGame(GameRuler<P> g); /** * Comunica allo {@code Observer} la mossa eseguita da un giocatore. Lo * {@code Observer} dovrebbe usare tale informazione per aggiornare la sua * copia del {@link GameRuler}. L'uso del GameRuler dovrebbe avvenire * solamente nel thread in cui il metodo è invocato. * <br> * <b>Il metodo non blocca, non usa altri thread e ritorna velocemente.</b> * * @param i indice di turnazione di un giocatore * @param m la mossa eseguita dal giocatore * @throws IllegalStateException se non c'è un gioco impostato o c'è ma è * terminato. * @throws NullPointerException se {@code m} è null * @throws IllegalArgumentException se {@code i} non è l'indice di turnazione * di un giocatore o {@code m} non è una mossa valida nell'attuale situazione * di gioco */ void moved(int i, Move<P> m); /** * Comunica allo {@code Observer} che il giocatore con indice di turnazione * {@code i} ha violato un vincolo sull'esecuzione (ad es. il tempo concesso * per una mossa). Dopo questa invocazione il giocatore {@code i} è * squalificato e ciò produce gli stessi effetti che si avrebbero se tale * giocatore si fosse arreso. Quindi lo {@code Observer} per sincronizzare * la sua copia con la partita esegue un {@link Move.Kind#RESIGN} per il * giocatore {@code i}. L'uso del GameRuler dovrebbe avvenire solamente nel * thread in cui il metodo è invocato. * * @param i indice di turnazione di un giocatore * @param msg un messaggio che descrive il tipo di violazione * @throws NullPointerException se {@code msg} è null * @throws IllegalArgumentException se {@code i} non è l'indice di turnazione * di un giocatore */ void limitBreak(int i, String msg); /** * Comunica allo {@code Observer} che la partita è stata interrotta. Ad es. * è stato invocato il metodo {@link PlayGUI#stop()}. * * @param msg una stringa con una descrizione dell'interruzione */ void interrupted(String msg); } /** * Crea un oggetto {@link PlayGUI} per partite controllate da GUI. L'oggetto * {@code PlayGUI} può essere usato per giocare più partite anche con giochi e * giocatori diversi. Per garantire che tutti gli oggetti coinvolti * {@link GameFactory}, {@link PlayerFactory}, {@link GameRuler} e {@link Player} * possano essere usati tranquillamente anche se non sono thread-safe, crea un * thread che chiamiamo <i>thread di confinamento</i>, in cui invoca tutti i * metodi e costruttori di tali oggetti. Il thread di confinamento può cambiare * solo se tutti gli oggetti coinvolti in una partita sono creati ex novo. Se * durante una partita un'invocazione (ad es. a {@link Player#getMove()}) blocca * il thread di confinamento per un tempo superiore a {@code maxBlockTime}, la * partita è interrotta. * <br> * All'inizio e durante una partita invoca i metodi di {@code obs}, rispettando * le specifiche di {@link Observer}, sempre nel thread di confinamento. * <br> * <b>Tutti i thread usati sono daemon thread</b> * * @param obs un osservatore del gioco * @param maxBlockTime tempo massimo in millisecondi di attesa per un blocco * del thread di confinamento, se < 0, significa nessun * limite di tempo * @throws NullPointerException se {@code obs} è null */ public PlayGUI(Observer<P> obs, long maxBlockTime) { throw new UnsupportedOperationException("PROGETTO: DA IMPLEMENTARE"); } /** * Imposta la {@link GameFactory} con il nome dato. Usa {@link GameFactories} * per creare la GameFactory nel thread di confinamento. Se già c'era una * GameFactory impostata, la sostituisce con la nuova e se c'erano anche * PlayerFactory impostate le cancella. Però se c'è una partita in corso, * fallisce. * * @param name nome di una GameFactory * @throws NullPointerException se {@code name} è null * @throws IllegalArgumentException se {@code name} non è il nome di una * GameFactory * @throws IllegalStateException se la creazione della GameFactory fallisce o se * c'è una partita in corso. */ public void setGameFactory(String name) { throw new UnsupportedOperationException("PROGETTO: DA IMPLEMENTARE"); } /** * Ritorna i nomi dei parametri della {@link GameFactory} impostata. Se la * GameFactory non ha parametri, ritorna un array vuoto. * * @return i nomi dei parametri della GameFactory impostata * @throws IllegalStateException se non c'è una GameFactory impostata */ public String[] getGameFactoryParams() { throw new UnsupportedOperationException("PROGETTO: DA IMPLEMENTARE"); } /** * Ritorna il prompt del parametro con il nome specificato della * {@link GameFactory} impostata. * * @param paramName nome del parametro * @return il prompt del parametro con il nome specificato della GameFactory * impostata. * @throws NullPointerException se {@code paramName} è null * @throws IllegalArgumentException se la GameFactory impostata non ha un * parametro di nome {@code paramName} * @throws IllegalStateException se non c'è una GameFactory impostata */ public String getGameFactoryParamPrompt(String paramName) { throw new UnsupportedOperationException("PROGETTO: DA IMPLEMENTARE"); } /** * Ritorna i valori ammissibili per il parametro con nome dato della * {@link GameFactory} impostata. * * @param paramName nome del parametro * @return i valori ammissibili per il parametro della GameFactory impostata * @throws NullPointerException se {@code paramName} è null * @throws IllegalArgumentException se la GameFactory impostata non ha un * parametro di nome {@code paramName} * @throws IllegalStateException se non c'è una GameFactory impostata */ public Object[] getGameFactoryParamValues(String paramName) { throw new UnsupportedOperationException("PROGETTO: DA IMPLEMENTARE"); } /** * Ritorna il valore del parametro di nome dato della {@link GameFactory} * impostata. * * @param paramName nome del parametro * @return il valore del parametro della GameFactory impostata * @throws NullPointerException se {@code paramName} è null * @throws IllegalArgumentException se la GameFactory impostata non ha un * parametro di nome {@code paramName} * @throws IllegalStateException se non c'è una GameFactory impostata */ public Object getGameFactoryParamValue(String paramName) { throw new UnsupportedOperationException("PROGETTO: DA IMPLEMENTARE"); } /** * Imposta il valore del parametro di nome dato della {@link GameFactory} * impostata. * * @param paramName nome del parametro * @param value un valore ammissibile per il parametro * @throws NullPointerException se {@code paramName} o {@code value} è null * @throws IllegalArgumentException se la GameFactory impostata non ha un * parametro di nome {@code paramName} o {@code value} non è un valore * ammissibile per il parametro * @throws IllegalStateException se non c'è una GameFactory impostata o è già * stato impostata la PlayerFactory di un giocatore */ public void setGameFactoryParamValue(String paramName, Object value) { throw new UnsupportedOperationException("PROGETTO: DA IMPLEMENTARE"); } /** * Imposta un {@link PlayerGUI} con il nome e il master dati per il giocatore * di indice {@code pIndex}. Se c'era già un giocatore impostato per quell'indice, * lo sostituisce. * * @param pIndex indice di un giocatore * @param pName nome del giocatore * @param master il master * @throws NullPointerException se {@code pName} o {@code master} è null * @throws IllegalArgumentException se {@code pIndex} non è un indice di giocatore * valido per la GameFactory impostata * @throws IllegalStateException se non c'è una GameFactory impostata o se c'è * una partita in corso. */ public void setPlayerGUI(int pIndex, String pName, Consumer<MoveChooser<P>> master) { throw new UnsupportedOperationException("PROGETTO: DA IMPLEMENTARE"); } /** * Imposta la {@link PlayerFactory} con nome dato per il giocatore di indice * {@code pIndex}. Usa {@link PlayerFactories} per creare la PlayerFactory nel * thread di confinamento. La PlayerFactory è impostata solamente se il metodo * ritorna {@link PlayerFactory.Play#YES}. Se c'era già un giocatore impostato * per quell'indice, lo sostituisce. * * @param pIndex indice di un giocatore * @param fName nome di una PlayerFactory * @param pName nome del giocatore * @param dir la directory della PlayerFactory o null * @return un valore (vedi {@link PlayerFactory.Play}) che informa sulle * capacità dei giocatori di questa fabbrica di giocare al gioco specificato. * @throws NullPointerException se {@code fName} o {@code pName} è null * @throws IllegalArgumentException se {@code pIndex} non è un indice di giocatore * valido per la GameFactory impostata o se non esiste una PlayerFactory di nome * {@code fName} * @throws IllegalStateException se la creazione della PlayerFactory fallisce o * se non c'è una GameFactory impostata o se c'è una partita in corso. */ public PlayerFactory.Play setPlayerFactory(int pIndex, String fName, String pName, Path dir) { throw new UnsupportedOperationException("PROGETTO: DA IMPLEMENTARE"); } /** * Ritorna i nomi dei parametri della {@link PlayerFactory} di indice * {@code pIndex}. Se la PlayerFactory non ha parametri, ritorna un array vuoto. * * @param pIndex indice di un giocatore * @return i nomi dei parametri della PlayerFactory di indice dato * @throws IllegalArgumentException se non c'è una PlayerFactory di indice * {@code pIndex} */ public String[] getPlayerFactoryParams(int pIndex) { throw new UnsupportedOperationException("PROGETTO: DA IMPLEMENTARE"); } /** * Ritorna il prompt del parametro con il nome specificato della * {@link PlayerFactory} di indice {@code pIndex}. * * @param pIndex indice di un giocatore * @param paramName nome del parametro * @return il prompt del parametro con il nome specificato della PlayerFactory * di indice dato * @throws NullPointerException se {@code paramName} è null * @throws IllegalArgumentException se la PlayerFactory non ha un parametro di * nome {@code paramName} o non c'è una PlayerFactory di indice {@code pIndex} */ public String getPlayerFactoryParamPrompt(int pIndex, String paramName) { throw new UnsupportedOperationException("PROGETTO: DA IMPLEMENTARE"); } /** * Ritorna i valori ammissibili per il parametro di nome dato della * {@link PlayerFactory} di indice {@code pIndex}. * * @param pIndex indice di un giocatore * @param paramName nome del parametro * @return i valori ammissibili per il parametro di nome dato della PlayerFactory * di indice dato. * @throws NullPointerException se {@code paramName} è null * @throws IllegalArgumentException se la PlayerFactory non ha un parametro di * nome {@code paramName} o non c'è una PlayerFactory di indice {@code pIndex} */ public Object[] getPlayerFactoryParamValues(int pIndex, String paramName) { throw new UnsupportedOperationException("PROGETTO: DA IMPLEMENTARE"); } /** * Ritorna il valore del parametro di nome dato della {@link PlayerFactory} di * indice {@code pIndex}. * * @param pIndex indice di un giocatore * @param paramName nome del parametro * @return il valore del parametro di nome dato della PlayerFactory di indice * dato * @throws NullPointerException se {@code paramName} è null * @throws IllegalArgumentException se la PlayerFactory non ha un parametro di * nome {@code paramName} o non c'è una PlayerFactory di indice {@code pIndex} */ public Object getPlayerFactoryParamValue(int pIndex, String paramName) { throw new UnsupportedOperationException("PROGETTO: DA IMPLEMENTARE"); } /** * Imposta il valore del parametro di nome dato della {@link PlayerFactory} * di indice {@code pIndex}. * * @param pIndex indice di un giocatore * @param paramName nome del parametro * @param value un valore ammissibile per il parametro * @throws NullPointerException se {@code paramName} o {@code value} è null * @throws IllegalArgumentException se la PlayerFactory non ha un parametro di * nome {@code paramName} o {@code value} non è un valore ammissibile per il * parametro o non c'è una PlayerFactory di indice {@code pIndex} * @throws IllegalStateException se c'è una partita in corso */ public void setPlayerFactoryParamValue(int pIndex, String paramName, Object value) { throw new UnsupportedOperationException("PROGETTO: DA IMPLEMENTARE"); } /** * Inizia una partita con un gioco fabbricato dalla GameFactory impostata e i * giocatori forniti da {@link PlayerGUI} impostati o fabbricati dalle * PlayerFactory impostate. Se non c'è una GameFactory impostata o non ci sono * sufficienti giocatori impostati o c'è già una partita in corso, fallisce. Se * sono impostati dei vincoli sui thread per le invocazioni di * {@link Player#getMove}, allora prima di iniziare la partita invoca i metodi * {@link Player#threads(int, ForkJoinPool, ExecutorService)} di tutti i giocatori, * ovviamente nel thread di confinamento. * <br> * Il metodo ritorna immediatamente, non attende che la partita termini. Quindi * usa un thread per gestire la partita oltre al thread di confinamento usato * per l'invocazione di tutti i metodi del GameRuler e dei Player. * * @param tol massimo numero di millisecondi di tolleranza per le mosse, cioè se * il gioco ha un tempo limite <i>T</i> per le mosse, allora il tempo di * attesa sarà <i>T</i> + {@code tol}; se {@code tol} <= 0, allora * nessuna tolleranza * @param timeout massimo numero di millisecondi per le invocazioni dei metodi * dei giocatori escluso {@link Player#getMove()}, se <= 0, * allora nessun limite * @param minTime minimo numero di millisecondi tra una mossa e quella successiva, * se <= 0, allora nessuna pausa * @param maxTh massimo numero di thread addizionali permessi per * {@link Player#getMove()}, se < 0, nessun limite è imposto * @param fjpSize numero di thread per il {@link ForkJoinTask ForkJoin} pool, * se == 0, non è permesso alcun pool, se invece è < 0, non c'è * alcun vincolo e possono usare anche * {@link ForkJoinPool#commonPool() Common Pool} * @param bgExecSize numero di thread permessi per esecuzioni in background, se * == 0, non sono permessi, se invece è < 0, non c'è alcun * vincolo * @throws IllegalStateException se non c'è una GameFactory impostata o non ci * sono sufficienti PlayerFactory impostate o la creazione del GameRuler o quella * di qualche giocatore fallisce o se già c'è una partita in corso. */ public void play(long tol, long timeout, long minTime, int maxTh, int fjpSize, int bgExecSize) { throw new UnsupportedOperationException("PROGETTO: DA IMPLEMENTARE"); } /** * Se c'è una partita in corso la termina immediatamente e ritorna true, * altrimenti non fa nulla e ritorna false. * * @return true se termina la partita in corso, false altrimenti */ public boolean stop() { throw new UnsupportedOperationException("PROGETTO: DA IMPLEMENTARE"); } }
Ruby
UTF-8
2,585
2.8125
3
[ "MIT" ]
permissive
require "money" require File.expand_path(File.join(File.dirname(__FILE__), 'has_money', 'validators')) # Helper methods for ActiveRecord models which can be used to easily define money and # currency attributes using +money+ library. # #--- # TODO DRY it up #+++ module HasMoney def has_currency(attr, options = {}) define_method attr do c = read_attribute(attr) || options[:default] if c.present? Money::Currency.new(c) else Money.default_currency end end define_method "#{attr}=" do |c| c = Money::Currency.new(c.to_s) unless c.is_a? Money::Currency if options[:for].present? money_attrs = Array(options[:for]).flatten money_attrs.each do |money_attr| m = send("#{money_attr}") write_attribute(money_attr, m.exchange_to(c).cents) unless m.nil? end end write_attribute(attr, c.iso_code) end end def has_money(attr, options = {}) currency_attribute = options[:with_currency] || "#{attr}_currency" unless options[:with_currency].present? define_method currency_attribute do c = read_attribute("#{attr}_currency") || options[:default_currency] if c.present? Money::Currency.new(c) else Money.default_currency end end define_method "#{currency_attribute}=" do |c| c = Money::Currency.new(c.to_s) unless c.is_a? Money::Currency m = send("#{attr}") write_attribute(attr, m.exchange_to(c).cents) unless m.nil? write_attribute("#{attr}_currency", c.iso_code) end end define_method attr do cents = read_attribute(attr) Money.new(cents, send(currency_attribute).iso_code) unless cents.nil? end define_method "#{attr}=" do |value| currency = send(currency_attribute) unless value.is_a? Money value = Money.new(value.to_f * currency.subunit_to_unit, currency.iso_code) end cents = value.exchange_to(currency.iso_code).cents write_attribute(attr, cents) end end def validates_currency(attr, options = {}) validate do |instance| HasMoney::Validators::CurrencyValidator.new(instance, attr, options).validate end end def validates_money(attr, options = {}) validate do |instance| unless options[:currency] == false HasMoney::Validators::CurrencyValidator.new(instance, "#{attr}_currency", options[:currency]).validate end HasMoney::Validators::MoneyValidator.new(instance, attr, options).validate end end end
C#
UTF-8
1,724
2.71875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DRMFSS.BLL.Services { public class HubService : IHubService { private readonly IUnitOfWork _unitOfWork; public HubService(IUnitOfWork unitOfWork) { this._unitOfWork = unitOfWork; } #region Default Service Implementation public bool AddHub(Hub hub) { _unitOfWork.HubRepository.Add(hub); _unitOfWork.Save(); return true; } public bool DeleteHub(Hub hub) { if (hub == null) return false; _unitOfWork.HubRepository.Delete(hub); _unitOfWork.Save(); return true; } public bool DeleteById(int id) { var entity = _unitOfWork.HubRepository.FindById(id); if (entity == null) return false; _unitOfWork.HubRepository.Delete(entity); _unitOfWork.Save(); return true; } public bool EditHub(Hub hub) { _unitOfWork.HubRepository.Edit(hub); _unitOfWork.Save(); return true; } public Hub FindById(int id) { return _unitOfWork.HubRepository.FindById(id); } public List<Hub> GetAllHub() { return _unitOfWork.HubRepository.GetAll(); } public List<Hub> FindBy(System.Linq.Expressions.Expression<Func<Hub, bool>> predicate) { return _unitOfWork.HubRepository.FindBy(predicate); } #endregion public void Dispose() { _unitOfWork.Dispose(); } } }
C#
UTF-8
1,226
3.125
3
[]
no_license
using System; using System.Collections.Generic; using Fsd.Kamil.Cs.Ex2.Animals; using Fsd.Kamil.Cs.Ex2.Views; namespace Fsd.Kamil.Cs.Ex2 { public class AnimalsProvider { private IAnimalReader _reader; public AnimalsProvider(IAnimalReader reader) { _reader = reader; } public IEnumerable<ISound> GenerateAnimals() { var animals = new List<ISound>(); animals.AddRange(GenerateAnimalForSpecies<Cat>("cat")); animals.AddRange(GenerateAnimalForSpecies<Dog>("dog")); animals.AddRange(GenerateAnimalForSpecies<Cow>("cow")); animals.AddRange(GenerateAnimalForSpecies<Sheep>("sheep")); return animals; } private IEnumerable<ISound> GenerateAnimalForSpecies<TAnimal>(string speciesName) where TAnimal : ISound { var animalNumber = _reader.GetAnimalCount(speciesName); var animals = new List<ISound>(); for (var i = 0; i < animalNumber; i++) animals.Add((TAnimal)Activator.CreateInstance(typeof(TAnimal), _reader.GetAnimalName(speciesName))); return animals; } } }
Java
UTF-8
1,153
2.4375
2
[]
no_license
package com.salavizadeh.notepad.data; import android.provider.BaseColumns; import static com.salavizadeh.notepad.data.NotesContract.NoteTable.CREATED_AT; import static com.salavizadeh.notepad.data.NotesContract.NoteTable._TABLE_NAME; public final class NotesContract { private NotesContract() {} public static final String SQL_CREATE_ENTRIES = "CREATE TABLE " + _TABLE_NAME + " (" + NoteTable._ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " + NoteTable.TEXT + " TEXT, " + NoteTable.IS_PINNED + " INTEGER, " + CREATED_AT + " INTEGER, " + NoteTable.UPDATED_AT + " INTEGER" + ")"; public static final String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + _TABLE_NAME; public static final String SQL_QUERY_ALL = "SELECT * FROM NOTE ORDER BY " + CREATED_AT + " DESC"; public interface NoteTable extends BaseColumns { String _TABLE_NAME = "notes"; String TEXT = "text"; String IS_PINNED = "is_pinned"; String CREATED_AT = "created_at"; String UPDATED_AT = "updated_at"; } }
C#
UTF-8
632
2.515625
3
[ "MIT" ]
permissive
using UnityEngine; using System.Collections; namespace SimpleSceneDescription { public class SSDDomeLight : SSDLight { private Texture2D texture; public SSDDomeLight(Light light) : base(light) { LightAdapter adapter = light.GetComponent<LightAdapter>(); if (adapter) this.texture = adapter.texture; } protected override LightType LightType { get { return LightType.Dome; } } public override void OnToJSON(Hashtable ht) { base.OnToJSON(ht); ht["textureId"] = texture; } } }
SQL
UTF-8
270
2.734375
3
[]
no_license
-- Create the database burgers_db and specified it for use. CREATE DATABASE burgers_db; USE burgers_db; -- Create the table plans. CREATE TABLE burgers ( id int NOT NULL AUTO_INCREMENT, burger_name varchar(200) NOT NULL, devoured BOOL DEFAULT false, PRIMARY KEY (id) );
Python
UTF-8
5,456
3.046875
3
[]
no_license
#Python 2.7 #psutil is an external package, install it before running the program import copy as cp import time import os import psutil import sys ''' Uncomment if want the script to install psutil package try: import psutil # for computing memory usage except ImportError: # try to install requests module if not present print ("Trying to Install required module: psutil\n") os.system('sudo python -m pip install psutil') import psutil ''' def iterative_deepening_depth_search(iInitialState, iFinalState): ''' :param iInitialState: initial state of the puzzle :param iFinalState: goal state of the puzzle :return: solution path if any (action) ''' node = str(iInitialState) final = str(iFinalState) if node == final: return node actionPath = [] for i in xrange(sys.maxint): #the cutoff value theoretically is as good as infinity #Memory sanity check process = psutil.Process(os.getpid()) memory = process.memory_info().rss / 1000000 if memory > 200: print ("Memory limit exceeded") return None solutionPath = depth_limited_search([node], final, i, actionPath) if solutionPath: return solutionPath if i == sys.maxint: #If i reaches final cutoff value and no solution exists return none return None def depth_limited_search(iCurrentPath, iFinalState, iDepth, oActionPath): ''' :param iCurrentPath: The current path of the search tree :param iFinalState: Goal state :param iDepth: cutoff depth of the limited depth tree :param oActionPath: action path of the puzzle :return: action path of the puzzle ''' depth = iDepth currentPath = iCurrentPath currentActionPath = oActionPath lastNode = currentPath[len(currentPath)-1] if(lastNode == iFinalState): return currentActionPath for currentState, actionMove in possibleStates(lastNode).iteritems(): if currentState in currentPath: #Repeated states check continue if depth == 0: #depth limit for this iteration is over return None #recursively check in the depth limited tree solutionPath = depth_limited_search(currentPath + [currentState], iFinalState, depth - 1, currentActionPath + [actionMove]) if solutionPath is not None: return solutionPath # find possible states def possibleStates(iCurrentState): ''' :definition: returns the possible states from current state :param iInterState: the row or column in which the movement is to be done :return: return all possible states after tile is moved ''' oPossibleStates = {} state = eval(iCurrentState) zeroIndex = [(ix, iy) for ix, row in enumerate(state) for iy, i in enumerate(row) if i == 0] iX = zeroIndex[0][0] iY = zeroIndex[0][1] minIndex = 0 maxIndex = 3 if iX > minIndex: # move pieces up and append to possible states state[iX][iY], state[iX - 1][iY] = state[iX - 1][iY], state[iX][iY] tmp = cp.deepcopy(state) sequenceActionPair = {repr(tmp):"UP"} oPossibleStates.update(sequenceActionPair) # revert back to original state state[iX][iY], state[iX - 1][iY] = state[iX - 1][iY], state[iX][iY] if iX < maxIndex: # move pieces down and append to possible states state[iX][iY], state[iX + 1][iY] = state[iX + 1][iY], state[iX][iY] tmp = cp.deepcopy(state) sequenceActionPair = {repr(tmp): "DOWN"} oPossibleStates.update(sequenceActionPair) # revert back to original state state[iX][iY], state[iX + 1][iY] = state[iX + 1][iY], state[iX][iY] if iY > minIndex: # move pieces left and append to possible states state[iX][iY], state[iX][iY - 1] = state[iX][iY - 1], state[iX][iY] tmp = cp.deepcopy(state) sequenceActionPair = {repr(tmp): "LEFT"} oPossibleStates.update(sequenceActionPair) # revert back to original state state[iX][iY], state[iX][iY - 1] = state[iX][iY - 1], state[iX][iY] if iY < maxIndex: # move pieces right and append to possible states state[iX][iY], state[iX][iY + 1] = state[iX][iY + 1], state[iX][iY] tmp = cp.deepcopy(state) sequenceActionPair = {repr(tmp): "RIGHT"} oPossibleStates.update(sequenceActionPair) # revert back to original state state[iX][iY], state[iX][iY + 1] = state[iX][iY + 1], state[iX][iY] return oPossibleStates #main if __name__ == '__main__': startTime = time.time() initialState = [[1, 2, 0, 4], [5, 6, 3, 12], [13, 9, 8, 7], [14, 11, 10, 15]] # End state is the final solved state of the puzzle endState = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 0]] path = iterative_deepening_depth_search(initialState, endState) if path == None: print "Solution does not exist" else: print "Action path of the solution is (in terms of 0 tile)- " for i in path: print i time = time.time() - startTime print ("Depth of Solution is: ", len(path)) print ("Number of seconds to solve: ", time) process = psutil.Process(os.getpid()) memory = process.memory_info().rss print ("Memory used:(in MB)", memory / 1000000)
Markdown
UTF-8
3,357
2.515625
3
[]
no_license
+++ title = "[방구석 영화제]캐쉬백 Cashback" date = "2007-09-30T14:04:00+0900" categories = ["일상사"] tags = ["캐쉬백","cashback"] description = "" +++ <span class="copyright_entry" style="display:block;" title="[방구석 영화제]캐쉬백 Cashback@@**@@http://shed.egloos.com/1636062"></span>영국영화 Cashback 입니다. <br> <br>네. 'OK 캐시백'이 떠오르네요. <br> <br>굳이 번역하자면 '돈으로 돌려주기' 혹은 '돈 다시 돌려주기' 정도일거 같은데요. <br> <br>제목과 영화내용은 별 상관이 없습니다. <br> <br>영화가 대형 할인매장을 배경으로 하고 있기 때문에 의미적 연관이 전혀 없다고는 할 수 없겠습니다만... <br> <br> <br>어쨌건, 줄거리는, <br> <br> <br>미대생 벤은 몇년간 사귀던 애인에게 자신의 무능으로 인해 그녀를 행복하게 해 줄 수 없다는 이유로 결별을 선언합니다. <br> <br>참 어이없는 이유죠(나중에는 자신도 어이없는 생각이었다는 것을 깨닫게 됩니다). <br> <br> <br>그런데 막상 헤어지게 되고 옛애인이 금방 새 남자를 만나는 것을 보고는 배신감/상실감/그리움으로 인해 그만 불면증에 걸리게 됩니다. <br> <br>불면증에 걸릴정도로 정신적 충격이 심하다면 술이라도 진탕먹고 사고치고 다녀야 정상일것 같은데 <br> <br>이성적으로 대처 하는 모습이 상당히 인상적입니다. 신사의 나라 국민이라서 그런걸까요? ㅡ.ㅡ <br> <br> <br>어쨌건 어차피 남는 시간, 주인공은 남는 8시간을 노동을 통해 금전적으로 보상을 받고자(Cashback) 대형마트에 야간 점원으로 취직합니다. <br> <br>그런데 실연으로 인해 생긴 또 하나의 놀라운 능력이 있었으니. 바로 '시간 멈추기' 입니다. <br> <br>불면증으로 하루에 8시간이 덤으로 주어졌는데 시간을 멈추는 능력까지 생겼으니 사실상 무한대의 시간을 쓸 수 있게 된겁니다. <br> <br>줄거리는 이쯤 하구요. <br> <br> <br>본 영화는 영국작품으로 2004년에 단편영화로 만들어져서 호평을 받았었고 2006년 장편으로 다시 만들었다고 합니다. <br> <br>감독 숀 엘리스(Sean Ellis)는 패션사진작가로 경력을 시작해서 CF감독을 거쳐 단편영화작업으로 호평을 받은 후 본격적으로 장편영화에 입문하게 된 독특한 경력을 가지고 있습니다. <br> <br>'캐시백'은 기발한 영상과 재미있는 에피소드들이 영화 시작에서 부터 끝까지 눈을 땔 수 없게 만드는, 가볍지 않은 메시지를 전달하면서도 유쾌함을 잃지 않는 기분좋은 영화입니다. <br> <br> <img style="width: 458px; height: 307px;" src="http://imgmovie.naver.com/mdi/mi/0638/F3879-14.jpg"> <!-- <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/"> <rdf:Description rdf:about="http://shed.egloos.com/1636062" dc:identifier="http://shed.egloos.com/1636062" dc:title="[방구석 영화제]캐쉬백 Cashback" trackback:ping="http://shed.egloos.com/tb/1636062"/> </rdf:RDF> --> <ul></ul>
C#
UTF-8
5,306
2.765625
3
[]
no_license
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using IxMilia.Dxf; using IxMilia.Dxf.Entities; namespace DxfLib { public class DxfToJsonConverter { private DxfFile _dxfFile; public NumberFormatInfo Format { get; } = new NumberFormatInfo {NumberDecimalSeparator = "."}; public string EntitiesToJson(IList<DxfEntity> dxfEntities) { var json = string.Join(", ", dxfEntities.Select(EntityToJson)); return json; } public string EntityToJson(DxfEntity dxfEntity) { if (dxfEntity is DxfPolyline dxfPolyline) return EntityToJson(dxfPolyline); if (dxfEntity is DxfLine dxfLine) return EntityToJson(dxfLine); if (dxfEntity is DxfSpline dxfSpline) return EntityToJson(dxfSpline); if (dxfEntity is DxfCircle dxfCircle) { if (dxfCircle is DxfArc dxfArc) return EntityToJson(dxfArc); return EntityToJson(dxfCircle); } if (dxfEntity is DxfLwPolyline dxfLwPolyline) return EntityToJson(dxfLwPolyline); if (dxfEntity is DxfInsert dxfInsert) return EntityToJson(dxfInsert); throw new ArgumentException($"Unknown DxfEntity {dxfEntity}"); } public string EntityToJson(DxfPolyline dxfPolyline) { var dxfPolylineVertices = dxfPolyline.Vertices; var json = ""; using (var enumerator = dxfPolylineVertices.GetEnumerator()) { if (!enumerator.MoveNext()) return "{}"; var last = enumerator.Current; enumerator.MoveNext(); while (true) { var current = enumerator.Current; json += string.Format(Format, "[\"line\",{0:F},{1:F},{2:F},{3:F}]", last.Location.X, last.Location.Y, current.Location.X, current.Location.Y); last = current; if (enumerator.MoveNext()) json += ", "; else break; } } return json; } public string EntityToJson(DxfLwPolyline dxfLwPolyline) { // TODO! var dxfLwPolylineVertices = dxfLwPolyline.Vertices; var json = string.Join(", ", dxfLwPolylineVertices.Select(cp => string.Format(Format, "[{0:F},{1:F}]", cp.X, cp.Y))); return string.Format("[\"lwpolyline\",{0}]", json); } public string EntityToJson(DxfLine dxfLine) { return string.Format(Format, "[\"line\",{0:F},{1:F},{2:F},{3:F}]", dxfLine.P1.X, dxfLine.P1.Y, dxfLine.P2.X, dxfLine.P2.Y); } public string EntityToJson(DxfSpline dxfSpline) { // TODO! var dxfSplineControlPoints = dxfSpline.ControlPoints; var json = string.Join(", ", dxfSplineControlPoints.Select(cp => string.Format(Format, "[{0:F},{1:F}]", cp.Point.X, cp.Point.Y))); return string.Format("[\"spline\",{0}]", json); } public string EntityToJson(DxfArc dxfArc) { // float startAngle = (float)dxfArc.StartAngle; // float endAngle = (float)dxfArc.EndAngle; // startAngle *= -1; // endAngle *= -1; // // float sweep = (endAngle - startAngle - 360) % 360; return string.Format(Format, "[\"arc\",{0:F},{1:F},{2:F},{3:F},{4:F}]", dxfArc.Center.X, dxfArc.Center.Y, dxfArc.Radius, dxfArc.StartAngle, dxfArc.EndAngle); } public string EntityToJson(DxfCircle dxfCircle) { // We dont care about center return string.Format(Format, "[\"circle\",{0:F},{1:F},{2:F}]", dxfCircle.Center.X, dxfCircle.Center.Y, dxfCircle.Radius); } public string EntityToJson(DxfInsert dxfInsert) { var dxfBlock = _dxfFile.Blocks.FirstOrDefault(t => t.Name == dxfInsert.Name); var json = EntitiesToJson(dxfBlock.Entities); return json; } public string EncodeFileJson(DxfFile dxfFile) { // var entitiesCount = CollectStats(dxfFile.Entities); // var typesString = string.Join("\n", // entitiesCount.Keys.Where(k => entitiesCount[k] != 0).Select(k => k + ":" + entitiesCount[k])); // labelStats.Text = "\n\tFILE:\n" + typesString + "\n"; _dxfFile = dxfFile; var result = string.Format(Format, "{{\"cost\":{0:F}, \"entities\":[{1}]}}", new Mather().GetFileTotalLength(dxfFile), EntitiesToJson(dxfFile.Entities)); _dxfFile = null; return result; } } }
Markdown
UTF-8
3,395
2.625
3
[]
no_license
I'm very happy to announce a new release of the [Yesod Web Framework](http://hackage.haskell.org/package/yesod). This release is accompanied by version bumps in [Persistent](http://hackage.haskell.org/package/persistent) and [yesod-auth](http://hackage.haskell.org/package/yesod-auth), as well as a massive reorganization of the content in the [Yesod book](/book/), hopefully making the material easier to follow and more comprehensive. The main goal in this release has been pushing forward the stability of the Yesod API, paving the way for a 1.0 release in the near future. Some notable changes in this release are: * Changes to the session are visible immediately, instead of needing to wait until the next request. This has been a source of confusion for a few people, and it turns out the new implementation is simpler. I just [wrote an email about it.](http://www.haskell.org/pipermail/web-devel/2010/000508.html) * CSRF protection for forms. A bit more information on that in [another email I wrote](http://www.haskell.org/pipermail/web-devel/2010/000507.html). * A major renaming of the widget functions for simplification. You can [read the email I wrote about it](http://www.haskell.org/pipermail/web-devel/2010/000501.html). * Completely replaced MonadCatchIO with MonadInvertIO. The former had a flaw in its implementation of finally which allowed database connections to be leaked. The latter has a full test suite associated with it, and should be safe. * The Auth helper has been moved into the yesod-auth package (version 0.2 just released). This slims down the dependencies in Yesod while allowing us to have more freedom in changing the API. yesod-auth deviates from the previous Auth helper by providing a plugin interface, allowing anyone to add new backends. * Moved the Yesod.Mail module to the new mime-mail package, allowing its use outside of Yesod. * Added support for free-forms. In addition to the formlet-inspired, Applicative form API, we now have a second datatype (GFormMonad) which makes it easier to write custom-styled forms. I [wrote a blog post about this](http://docs.yesodweb.com/blog/custom-forms/) already. * The jQuery date picker can now be configured through a Haskell datatype. * The Widget type alias has been removed; now the site template defines this. * mkToForm can be applied to a single datatype instead of all of your entities. * Added fiRequired to FieldInfo, making it easier to style your forms differently for required and optional fields. We also have a fieldsToDivs function for those who hate tables. * By default, sessions are tied to a specific IP address to prevent session hijacking. Under certain circumstances, such as proxied requests, this can cause a problem. There is now a sessionIpAddress method in the Yesod typeclass to disable this. I'm very encouraged by the fact that most of these changes were incremental enhancements on features already present, and that even those often did not require breaking changes. My goal for the near future is to continue focusing on the [Yesod book](/book/). I'm hoping to have the majority of the book written by the time we have a 1.0 release. The code should be pretty stable: it's already running [haskellers.com](http://www.haskellers.com/), so it's getting a fair amount of stress testing. If you find any bugs, let me know. And if you have any questions, ask away!
Java
UTF-8
1,117
1.625
2
[]
no_license
package com.cn.smart.baselib.share.core.error; public class CarSmartShareStatusCode { public static final int ST_CODE_SUCCESSED = 200; public static final int ST_CODE_ERROR_CANCEL = 201; public static final int ST_CODE_ERROR = 202; public static final int ST_CODE_SHARE_ERROR_NOT_CONFIG = -233;//没有配置appkey, appId public static final int ST_CODE_SHARE_ERROR_NOT_INSTALL = -234;//第三方软件未安装 public static final int ST_CODE_SHARE_ERROR_PARAM_INVALID = -235;//ShareParam参数不正确 public static final int ST_CODE_SHARE_ERROR_EXCEPTION = -236;//异常 public static final int ST_CODE_SHARE_ERROR_UNEXPLAINED = -237; public static final int ST_CODE_SHARE_ERROR_SHARE_FAILED = -238; public static final int ST_CODE_SHARE_ERROR_AUTH_FAILED = -239;//认证失败 public static final int ST_CODE_SHARE_ERROR_CONTEXT_TYPE = -240;//上下文类型和需求不负 public static final int ST_CODE_SHARE_ERROR_PARAM_UNSUPPORTED = -241;//上下文类型和需求不负 public static final int ST_CODE_SHARE_ERROR_IMAGE = -242;//图片处理失败 }
Java
UTF-8
951
2.90625
3
[]
no_license
package BSTfromPreIn; public class BSTfromPreIn { public TreeNode buildTree(int[] preorder, int[] inorder) { int preStart=0; int preEnd=preorder.length-1; int inStart=0; int inEnd=inorder.length-1; return buildTree(preorder,preStart,preEnd,inorder,inStart,inEnd); } public TreeNode buildTree(int[] preorder,int preStart,int preEnd,int[] inorder,int inStart,int inEnd){ if(preStart>preEnd || inStart>inEnd){ return null; } TreeNode root=new TreeNode(preorder[preStart]); int k=0; for(int i=0;i<inorder.length;i++){ if(inorder[i]==preorder[preStart]){ k=i; break; } } int len=k-inStart; root.left=buildTree(preorder,preStart+1,preStart+len,inorder,inStart,k-1); root.right=buildTree(preorder,preStart+len+1,preEnd,inorder,k+1,inEnd); return root; } }
JavaScript
UTF-8
14,572
3
3
[ "MIT" ]
permissive
console.log("hi"); const connect4 = { // |--> connect4.row7[0].pos // | |--> connect4.row7[0].piece row7: [{pos:'7a', piece: null}, {pos:'7b', piece: null}, {pos:'7c', piece: null}, {pos:'7d', piece: null}, {pos:'7e', piece: null}, {pos:'7f', piece: null}], row6: [{pos:'6a', piece: null}, {pos:'6b', piece: null}, {pos:'6c', piece: null}, {pos:'6d', piece: null}, {pos:'6e', piece: null}, {pos:'6f', piece: null}], row5: [{pos:'5a', piece: null}, {pos:'5b', piece: null}, {pos:'5c', piece: null}, {pos:'5d', piece: null}, {pos:'5e', piece: null}, {pos:'5f', piece: null}], row4: [{pos:'4a', piece: null}, {pos:'4b', piece: null}, {pos:'4c', piece: null}, {pos:'4d', piece: null}, {pos:'4e', piece: null}, {pos:'4f', piece: null}], row3: [{pos:'3a', piece: null}, {pos:'3b', piece: null}, {pos:'3c', piece: null}, {pos:'3d', piece: null}, {pos:'3e', piece: null}, {pos:'3f', piece: null}], row2: [{pos:'2a', piece: null}, {pos:'2b', piece: null}, {pos:'2c', piece: null}, {pos:'2d', piece: null}, {pos:'2e', piece: null}, {pos:'2f', piece: null}], row1: [{pos:'1a', piece: null}, {pos:'1b', piece: null}, {pos:'1c', piece: null}, {pos:'1d', piece: null}, {pos:'1e', piece: null}, {pos:'1f', piece: null}], } // red = +1 // blue = -1 //null = empty space let playerBlue = false; let playerRed= true; let currentPlayer = playerBlue ? 'playerBlue' : 'playerRed'; // red goes first easy to change this with a button that changes this to false. //token is "dropped" into array row, // could use the return function here to feed info into the win checker const switchPlayer = function() { if (!playerBlue) { playerBlue = true; playerRed = false; } else { playerBlue = false; playerRed = true; } } const row1Move = function() { for (let i = 0; i < 7; i++) { if (connect4.row1[i].piece === null && playerRed === true) { connect4.row1[i].piece = 1 // winTest(); switchPlayer(); return connect4.row1[i].pos } if (connect4.row1[i].piece === null && playerBlue === true) { connect4.row1[i].piece = -1 // winTest(); switchPlayer(); return connect4.row1[i].pos } } } const row2Move = function() { for (let i = 0; i < 7; i++) { if (connect4.row2[i].piece === null && playerRed === true) { connect4.row2[i].piece = 1 // winTest(); switchPlayer(); return connect4.row2[i].pos } if (connect4.row2[i].piece === null && playerBlue === true) { connect4.row2[i].piece = -1 // winTest(); switchPlayer(); return connect4.row2[i].pos } } } const row3Move = function() { for (let i = 0; i < 7; i++) { if (connect4.row3[i].piece === null && playerRed === true) { connect4.row3[i].piece = 1 // winTest(); switchPlayer(); return connect4.row3[i].pos } if (connect4.row3[i].piece === null && playerBlue === true) { connect4.row3[i].piece = -1 // winTest(); switchPlayer(); return connect4.row3[i].pos } } } const row4Move = function() { for (let i = 0; i < 7; i++) { if (connect4.row4[i].piece === null && playerRed === true) { connect4.row4[i].piece = 1 // winTest(); switchPlayer(); return connect4.row4[i].pos } if (connect4.row4[i].piece === null && playerBlue === true) { connect4.row4[i].piece = -1 // winTest(); switchPlayer(); return connect4.row4[i].pos } } } const row5Move = function() { for (let i = 0; i < 7; i++) { if (connect4.row5[i].piece === null && playerRed === true) { connect4.row5[i].piece = 1 // winTest(); switchPlayer(); return connect4.row5[i].pos } if (connect4.row5[i].piece === null && playerBlue === true) { connect4.row5[i].piece = -1 // winTest(); switchPlayer(); return connect4.row5[i].pos } } } const row6Move = function() { for (let i = 0; i < 7; i++) { if (connect4.row6[i].piece === null && playerRed === true) { connect4.row6[i].piece = 1 // winTest(); switchPlayer(); return connect4.row6[i].pos } if (connect4.row6[i].piece === null && playerBlue === true) { connect4.row6[i].piece = -1 // winTest(); switchPlayer(); return connect4.row6[i].pos } } } const row7Move = function() { for (let i = 0; i < 7; i++) { if (connect4.row7[i].piece === null && playerRed === true) { connect4.row7[i].piece = 1 // winTest(); switchPlayer(); return connect4.row7[i].pos } if (connect4.row7[i].piece === null && playerBlue === true) { connect4.row7[i].piece = -1 // winTest(); switchPlayer(); return connect4.row7[i].pos } } } const iterate = function() { for (var key in connect4) { //this loops through the rows (connect4) console.log(key, connect4[key]); for (let i = 0; i < connect4[key].length; i++) { // this loops through each row // if (i) { // the i represents one of these: {pos:'7a', piece: 1} console.log(connect4[key][i].pos) // to get pos or piece you simple write .pos or .piece } // console.log(connect4[key][0].pos) // } } } const resetGame = function() { for (var key in connect4) { //this loops through the rows (connect4) console.log(key, connect4[key]); for (let i = 0; i < connect4[key].length; i++) { // this loops through each row connect4[key][i].piece = null; } } } // // //stuck on this, the score is updating appropriately now but i can get the jloop going through the rows, ie row 1-7 // //win contions // //row 1 - 7, abcd, bcde, cdef const winTest = function() { for (var key in connect4) { //connect4 rows console.log(key); for (let i = 0; i < connect4[key].length; i++) { //connect4.row score = 0; for (let j = 0; j < 4 ; j++) { console.log(score); score += connect4[key][i].piece; if (score === 4){ console.log(`Red win at ${connect4[key][j].pos}`); } if (score === -4){ console.log(`Blue win at ${connect4[key][j].pos}`) } } //score reset here score = 0; for (let j = 1; j < 5 ; j++) { score += connect4[key][j].piece; if (score === 4){ console.log(`Red win at ${connect4[key][j].pos}`); } if (score === -4){ console.log(`Blue win at ${connect4[key][j].pos}`) } } //score reset score = 0; for (let j = 2; j < 6 ; j++) { score += connect4[key][j].piece; if (score === 4){ console.log(`Red win at ${connect4[key][j].pos}`); } if (score === -4){ console.log(`Blue win at ${connect4[key][j].pos}`) } } //score reset score = 0; //vertical check starts here for (let j = 0; j < 7; j++) { //score += connect4[key][0].piece; console.log(connect4[key][0].piece); if (score === 4){ console.log(`Red win at ${connect4[key][0].pos}`); } if (score === -4){ console.log(`Blue win ${connect4[key][0].pos}`) } } score = 0 for (let j = 0; j < 7; j++) { //vertical check starts here score += connect4[key][1].piece; if (score === 4){ console.log(`Red win at ${connect4[key][1].pos}`); } if (score === -4){ console.log(`Blue win at ${connect4[key][1].pos}`) } } score = 0; for (let j = 0; j < 7; j++) { //vertical check starts here score += connect4[key][2].piece; if (score === 4){ console.log(`Red win at ${connect4[key][2].pos}`); } if (score === -4){ console.log(`Blue win at ${connect4[key][2].pos}`) } } score = 0; for (let j = 0; j < 7; j++) { //vertical check starts here score += connect4[key][3].piece; if (score === 4){ console.log(`Red win at ${connect4[key][3].pos}`); } if (score === -4){ console.log(`Blue win at ${connect4[key][3].pos}`) } } score = 0; for (let j = 0; j < 7; j++) { //vertical check starts here score += connect4[key][4].piece; if (score === 4){ console.log(`Red win at ${connect4[key][4].pos}`); } if (score === -4){ console.log(`Blue win at ${connect4[key][4].pos}`) } } score = 0; for (let j = 0; j < 7; j++) { //vertical check starts here score += connect4[key][5].piece; if (score === 4){ console.log(`Red win at ${connect4[key][5].pos}`); } if (score === -4){ console.log(`Blue win at ${connect4[key][5].pos}`) } } } } // left to right diaganal// //1c , 2d, 3e, 4f, let oneC = 0 oneC += connect4.row1[2].piece oneC += connect4.row2[3].piece oneC += connect4.row3[4].piece oneC += connect4.row4[5].piece if (oneC === 4){ return console.log(`Red win`); } if (oneC === -4){ return console.log(`Blue win`) } //1b, 2c, 3d, 4e, 5f let oneB = 0 oneB += connect4.row1[1].piece oneB += connect4.row2[2].piece oneB += connect4.row3[3].piece oneB += connect4.row4[4].piece oneB += connect4.row5[5].piece if (oneB === 4){ return console.log(`Red win`); } if (oneB === -4){ return console.log(`Blue win`) } //1a 2b, 3c, 4d, 5e, 6f let oneA = 0 oneA += connect4.row1[0].piece oneA += connect4.row2[1].piece oneA += connect4.row3[2].piece oneA += connect4.row4[3].piece oneA += connect4.row5[4].piece oneA += connect4.row6[5].piece if (oneA === 4){ return console.log(`Red win`); } if (oneA === -4){ return console.log(`Blue win`) } //2a, 3b, 4c, 5d, 6e, 7f let twoA = 0 twoA += connect4.row2[0].piece twoA += connect4.row3[1].piece twoA += connect4.row4[2].piece twoA += connect4.row5[3].piece twoA += connect4.row6[4].piece twoA += connect4.row7[5].piece if (twoA === 4){ return console.log(`Red win`); } if (twoA === -4){ return console.log(`Blue win`) } //3a, 4b, 5c, 6d, 7f let threeA = 0 threeA += connect4.row3[0].piece threeA += connect4.row4[1].piece threeA += connect4.row5[2].piece threeA += connect4.row6[3].piece threeA += connect4.row7[4].piece if (threeA === 4){ return console.log(`Red win`); } if (threeA === -4){ return console.log(`Blue win`) } //4a, 5b, 6c, 7d let fourA = 0 fourA += connect4.row4[0].piece fourA += connect4.row4[1].piece fourA += connect4.row4[2].piece fourA += connect4.row4[3].piece if (fourA === 4){ return console.log(`Red win`); } if (fourA === -4){ return console.log(`Blue win`) } // right to left // //7c, 6d, 5e, 4f let sevenC = 0 sevenC += connect4.row7[2].piece sevenC += connect4.row6[3].piece sevenC += connect4.row5[4].piece sevenC += connect4.row4[5].piece if (sevenC === 4){ return console.log(`Red win`); } if (sevenC === -4){ return console.log(`Blue win`) } //7b, 6c, 5d, 4e, 3f let sevenB = 0 sevenB += connect4.row7[1].piece sevenB += connect4.row6[2].piece sevenB += connect4.row5[3].piece sevenB += connect4.row4[4].piece sevenB += connect4.row3[5].piece if (sevenB === 4){ return console.log(`Red win`); } if (sevenB === -4){ return console.log(`Blue win`) } //7a, 6b, 5c, 4d, 3e, 2f let sevenA = 0 sevenA += connect4.row7[0].piece sevenA += connect4.row6[1].piece sevenA += connect4.row5[2].piece sevenA += connect4.row4[3].piece sevenA += connect4.row3[4].piece sevenA += connect4.row2[5].piece if (sevenA === 4){ return console.log(`Red win`); } if (sevenA === -4){ return console.log(`Blue win`) } //6a, 5b, 4c, 3d, 2e, 1f let sixA = 0 sixA += connect4.row6[0].piece sixA += connect4.row5[1].piece sixA += connect4.row4[2].piece sixA += connect4.row3[3].piece sixA += connect4.row2[4].piece sixA += connect4.row1[5].piece if (sixA === 4){ return console.log(`Red win`); } if (sixA === -4){ return console.log(`Blue win`) } //5a, 4b, 3c, 2d, 1e, let fiveA = 0 fiveA += connect4.row5[0].piece fiveA += connect4.row4[1].piece fiveA += connect4.row3[2].piece fiveA += connect4.row2[3].piece fiveA += connect4.row1[4].piece if (fiveA === 4){ return console.log(`Red win`); } if (fiveA === -4){ return console.log(`Blue win`) } //4a, 3b, 2c, 1d let fourAl = 0 fourAl += connect4.row4[0].piece fourAl += connect4.row3[1].piece fourAl += connect4.row2[2].piece fourAl += connect4.row1[3].piece if (fourAl === 4){ return console.log(`Red win`); } if (fourAl === -4){ return console.log(`Blue win`) } } // console.log(`j loop ${[j]}`); // for (let i = 0; i < 4 ; i++) { // score += connect4.row6[i].piece; // i need J variable working here instead of 6, to check the whole board // if (score === 4){ // return console.log('Red win'); // } if (score === -4){ // return console.log('Blue win') // } // } // // for (let i = 1; i < 5 ; i++) { // // console.log('1-5'); // } // // for (let i = 2; i < 6 ; i++) { // // console.log(connect4.row7[i].pos); // // console.log(connect4.row7[i].piece); // console.log('2-6'); // } // // for (let i = 3; i < 7 ; i++) { // // console.log(connect4.row7[i].pos); // // console.log(connect4.row7[i].piece); // console.log('3-7'); // } // } // } // const winTest = function() { // for (let j = 1; j < 7; j++) { // console.log(`j loop ${[j]}`); // for (let i = 0; i < 4 ; i++) { // score += connect4.row6[i].piece; // i need J variable working here instead of 6, to check the whole board // if (score === 4){ // return console.log('Red win'); // } if (score === -4){ // return console.log('Blue win') // } // } // // for (let i = 1; i < 5 ; i++) { // // console.log('1-5'); // } // // for (let i = 2; i < 6 ; i++) { // // console.log(connect4.row7[i].pos); // // console.log(connect4.row7[i].piece); // console.log('2-6'); // } // // for (let i = 3; i < 7 ; i++) { // // console.log(connect4.row7[i].pos); // // console.log(connect4.row7[i].piece); // console.log('3-7'); // } // } // } //index 0 - 6 of arrays - 1234, 2345, 3456, 4567 -- only 4 posibilities per row // |---> this 1 needs to be the variable, // |--> index location, //connect4.row1[0].piece //diaganal wins both values accending // 1a, 2b, 3c, 4d //max height is c -> f
PHP
UTF-8
8,285
2.59375
3
[]
no_license
<?php //valido a sessão do usuário include_once '../estrutura/controle/validarSessao.php'; include_once '../funcaoPHP/function_letraMaiscula.php'; include_once '../funcaoPHP/funcaoData.php'; //verifico se a página está sendo chamada pelo méthod POST // Se sim executa escript // Senao dispara Erro if ($_SERVER['REQUEST_METHOD'] === 'POST') { // VARIAVEIS //ARRAY PARA ARMAZENAR ERROS $array_erros = array(); if (!fun_aplica_validacao_campo($_POST['txt_num_inscricao'], 6, 6)) { $array_erros['txt_inscricao'] = 'POR FAVOR ENTRE COM INSCRICÃO VÁLIDA \n'; } if (!fun_aplica_validacao_campo($_POST['txt_proprietario_imovel'], 3, 50)) { $array_erros['txt_proprietario_imovel'] = 'POR FAVOR ENTRE COM PROPRIETARIO VÁLIDO \n'; } if (!fun_aplica_validacao_campo($_POST['txt_logradouro_imovel'], 1, 50)) { $array_erros['txt_logradouro_imovel'] = 'POR FAVOR ENTRE COM LOGRADOURO VÁLIDO \n'; } if (!fun_aplica_validacao_campo($_POST['txt_nome_completo_requerente'], 3, 50)) { $array_erros['txt_nome_completo_requerente'] = 'POR FAVOR ENTRE COM REQUERENTE VÁLIDO \n'; } if (!fun_aplica_validacao_campo($_POST['txt_tipo_pessoa_requerente'], 5, 9)) { $array_erros['txt_tipo_pessoa_requerente'] = 'POR FAVOR ENTRE COM TIPO PESSOA VÁLIDO \n'; } if (!fun_aplica_validacao_campo($_POST['txt_cep_requerente'], 5, 9)) { $array_erros['txt_cep_requerente'] = 'POR FAVOR ENTRE COM CEP VÁLIDO \n'; } if (!fun_aplica_validacao_campo($_POST['txt_identidade_requerente'], 3, 20)) { $array_erros['txt_identidade_requerente'] = 'POR FAVOR ENTRE COM IDENTIDADE VÁLIDA \n'; } // verifico se tem erro na validação if (empty($array_erros)) { try { include_once '../estrutura/conexao/conexao.php'; $pdo->beginTransaction(); func_executa_sql($pdo); $pdo->commit(); header("Location: relatorio_certidao_regularidade_fiscal.php"); // $pdo->commit(); } catch (Exception $ex) { echo '<script>window.alert("' . $ex->getMessage() . '"); location.href = "../../../RelCertidaoRegularidadeFiscal.php"; </script>'; } } else { $msg_erro = ''; foreach ($array_erros as $msg) { $msg_erro = $msg_erro . $msg; } echo '<script>window.alert("' . $msg_erro . '"); location.href = "../../../RelCertidaoRegularidadeFiscal.php"; </script>'; } // if($_SERVER['REQUEST_METHOD'] === 'POST'){ } else { die(header("Location: ../../../logout.php")); } function func_buscar_proximo_numero_certidao($pdo) { $sql = "SELECT * FROM SisParametros"; $query = $pdo->prepare($sql); $query->execute(); if ($dados = $query->fetch()) { return $dados['Num_Certidao']; } else { return "0"; } } function func_executa_sql($pdo) { //nome da estação que esta acessando o sistema $hostname = $_SERVER['REMOTE_ADDR']; // Nome do usuário logado $usuario_logado = $_SESSION["usuario"]; //pegando o numero da certidao $numero_certidao = str_pad(func_buscar_proximo_numero_certidao($pdo), 6, "0", STR_PAD_LEFT); $ano_certidao = date('Y'); $inscricao = letraMaiuscula($_POST['txt_num_inscricao']); $cadastro = 1; $cod_divida = '01'; $requerente = $_POST['txt_nome_completo_requerente']; $obs = $_POST['txt_obs']; $data_emissao = dataAmericano(date('d/m/Y')); $tipo_certidao = '03'; $sql_insert = "INSERT INTO Certidao (Num_Certidao, Ano_Certidao, Inscricao, Cadastro, Cod_Divida, Requerente, Obs, Data_Emissao, Tipo_Certidao, USUARIO, ESTACAO)"; $sql_insert = $sql_insert . " VALUES "; $sql_insert = $sql_insert . " (:numero_certidao, :ano_certidao, :inscricao, :cadastro, :cod_divida, :requerente,:obs, :data_emissao, :tipo_certidao, :usuario, :estacao)"; $executa_insert = $pdo->prepare($sql_insert); $executa_insert->bindParam(':numero_certidao', $numero_certidao); $executa_insert->bindParam(':ano_certidao', $ano_certidao); $executa_insert->bindParam(':inscricao', $inscricao); $executa_insert->bindParam(':cadastro', $cadastro); $executa_insert->bindParam(':cod_divida', $cod_divida); $executa_insert->bindParam(':requerente', $requerente); $executa_insert->bindParam(':obs', $obs); $executa_insert->bindParam(':data_emissao', $data_emissao); $executa_insert->bindParam(':tipo_certidao', $tipo_certidao); $executa_insert->bindParam(':usuario', $usuario_logado); $executa_insert->bindParam(':estacao', $hostname); $executa_insert->execute(); func_carreagar_variaveis($numero_certidao); fun_alterar_numero_certidao($pdo, $numero_certidao + 1); } function fun_alterar_numero_certidao($pdo, $proximo){ $sql_update = "UPDATE SisParametros SET Num_Certidao = ?"; $executa_update = $pdo->prepare($sql_update); $executa_update->bindParam(1, $proximo); $executa_update->execute(); } function func_carreagar_variaveis($numero_certidao){ //VARIAVEIS DE SESSAO $_SESSION['PASSOU_CONTROLE'] = "OK"; $_SESSION['REL_NUMERO_CERTIDAO'] = $numero_certidao; $_SESSION['REL_ANO_CERTIDAO'] = date('Y'); $_SESSION['REL_INSCRICAO'] = letraMaiuscula($_POST['txt_num_inscricao']); $_SESSION['REL_CONTRIBUINTE'] = letraMaiuscula($_POST['txt_proprietario_imovel']); $_SESSION['REL_ENDERECO'] = letraMaiuscula($_POST['txt_logradouro_imovel']) . letraMaiuscula($_POST['txt_quadra_endereco_imovel']). letraMaiuscula($_POST['txt_lote_endereco_imovel']) ; $_SESSION['REL_CIDADE'] = 'JAPERI'; $_SESSION['REL_BAIRRO'] = letraMaiuscula($_POST['txt_bairro_imovel']); $_SESSION['REL_ESTADO'] = 'RJ'; $_SESSION['REL_AREA_CONSTRUIDA'] = letraMaiuscula($_POST['txt_area_construida']); $_SESSION['REL_AREA_TERRENO'] = letraMaiuscula($_POST['txt_area_terreno']); $_SESSION['REL_AVERBADO_EM'] = '21/01/2017'; $_SESSION['REL_VALOR_VENAL'] = letraMaiuscula($_POST['txt_valor_venal']); $_SESSION['REL_UTILIZACAO'] = letraMaiuscula($_POST['txt_utilizacao']); $_SESSION['REL_REQUERENTE'] = letraMaiuscula($_POST['txt_nome_completo_requerente']); $_SESSION['REL_REQUERENTE_CPF'] = letraMaiuscula($_POST['txt_cpf_cnpj_requerente']); $_SESSION['REL_REQUERENTE_IDENTIDADE'] = letraMaiuscula($_POST['txt_identidade_requerente']); $_SESSION['REL_REQUERENTE_ENDERECO'] =letraMaiuscula($_POST['txt_cep_requerente']) . " - " .letraMaiuscula($_POST['txt_rua_requerente']) . " - " . letraMaiuscula($_POST['txt_bairro_requerente']) . " - ". letraMaiuscula($_POST['txt_cidade_requerente']) ; $_SESSION['REL_REQUERENTE_ENDERECO'] = $_SESSION['REL_REQUERENTE_ENDERECO'] . letraMaiuscula($_POST['txt_uf_requerente']). " - " . letraMaiuscula($_POST['txt_numero_endereco_requerente']). " - " . letraMaiuscula($_POST['txt_complemento_endereco_requerente']) ; $_SESSION['NUMERO_PROCESSO'] = letraMaiuscula($_POST['txt_numero_processo']); $_SESSION['ANO_PROCESSO']= letraMaiuscula($_POST['txt_ano_processo']); $_SESSION['REL_AVERBADO_EM']= letraMaiuscula($_POST['txt_data_averbacao']); $_SESSION['REL_CARTA'] = ' CERTIFICO, conforme despacho exarado no processo administrativo número '. $_SESSION['NUMERO_PROCESSO'] .'/' . $_SESSION['ANO_PROCESSO'] .', em que o requerente Sr(a) : '; $_SESSION['REL_CARTA'] = $_SESSION['REL_CARTA'] . $_SESSION['REL_REQUERENTE']; $_SESSION['REL_CARTA'] = $_SESSION['REL_CARTA'] . ", CPF = ". $_SESSION['REL_REQUERENTE_CPF']; $_SESSION['REL_CARTA'] = $_SESSION['REL_CARTA'] . ", IDENTIDADE ". $_SESSION['REL_REQUERENTE_IDENTIDADE']; $_SESSION['REL_CARTA'] = $_SESSION['REL_CARTA'] . ", situado ". $_SESSION['REL_REQUERENTE_ENDERECO']; $_SESSION['REL_CARTA'] = $_SESSION['REL_CARTA'] . ", de acordo com as informações constantes em nossa base de dados, que o imóvel acima "; $_SESSION['REL_CARTA'] = $_SESSION['REL_CARTA'] . " descrito encontra-se EM DÉBITO com o Imposto respectivos"; $_SESSION['REL_OBSERVACAO'] = letraMaiuscula($_POST['txt_obs']); } ?>
Java
UTF-8
237
1.585938
2
[]
no_license
package com.test720.grasshoppercollege.module.userData.geRenZiLiao; /** * Created by 水东流 on 2018/4/9. */ public class HeaderFragment extends BaseHeaderFragment { @Override public int type() { return 1; } }
Java
UTF-8
1,284
1.96875
2
[]
no_license
package powercraft.core.item; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.inventory.GuiCrafting; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import powercraft.api.item.PC_Item; import powercraft.api.registry.PC_GresRegistry; import powercraft.core.container.PCco_ContainerCraftingTool2; public class PCco_ItemCraftingTool extends PC_Item { public PCco_ItemCraftingTool(int ids) { super("craftingtool"); setMaxDamage(0); setMaxStackSize(1); setCreativeTab(CreativeTabs.tabTools); } @Override public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer player) { if (player.isSneaking()) { if (!world.isRemote) { player.openContainer = new PCco_ContainerCraftingTool2(player.inventory, player.worldObj, (int) player.posX, (int) player.posY, (int) player.posZ); } else Minecraft.getMinecraft().displayGuiScreen(new GuiCrafting(player.inventory, player.worldObj, (int) player.posX, (int) player.posY, (int) player.posZ)); } else if (!world.isRemote) PC_GresRegistry.openGres("CraftingTool", player, null); return itemstack; } }
Markdown
UTF-8
733
3.34375
3
[ "Apache-2.0" ]
permissive
# backlog.txt _backlog.txt_ is a format (and an associated command-line tool) to store a project backlog in a text file. * It's **simple**: you can mantain a _backlog.txt_ with a tool, but you can also use a plain old text editor. * It's **powerful**: _backlog.txt_ is a [Markdown](http://daringfireball.net/projects/markdown/syntax) dialect, so it can format your backlog any way that Markdown can. * It's **flexible**: _backlog.txt_ makes very few assumptions about the way you work, or how you should structure your backlog. _backlog.txt_ is inspired by _[todo.txt](http://todotxt.com/)_. We're still writing the first version of the tool. Meanwhile, look at the [wiki](https://github.com/nusco/backlog.txt/wiki) for the specs.
Java
UTF-8
489
2.765625
3
[]
no_license
import java.util.Set; public class word_break { public boolean wordBreak(String s, Set<String> dict) { int len = s.length(); boolean[] arrays = new boolean[len+1]; arrays[0] = true; for(int i=1;i<=len;i++){ for(int j=0;j<i;j++){ if(arrays[j] && dict.contains(s.substring(j,i))){ arrays[i] = true; break; } } } return arrays[len]; } }
Java
UTF-8
2,824
2.765625
3
[]
no_license
import java.io.IOException; import java.util.Iterator; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.util.GenericOptionsParser; public class FibTask { private static int fibonacci(int n) { if (n < 0) { System.out.println("Incorrect input"); return 0; } else if (n == 1) { return 0; } else if (n == 2) { return 1; } else { return fibonacci(n - 1) + fibonacci(n - 2); } } public static class FibonacciMapper extends Mapper<Object, Text, Text, IntWritable> { private IntWritable durationKey = new IntWritable(); public void map(Object key, Text value, Context context) throws IOException, InterruptedException { String data = value.toString(); String[] fields = data.split(",", -1); int duration = Integer.parseInt(fields[8]); durationKey.set(fibonacci(duration + 6)); Text srcIpValue = new Text(fields[0]); context.write(srcIpValue, durationKey); } } public static class FibonacciReducer extends Reducer<Text, IntWritable, Text, IntWritable> { public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { Iterator<IntWritable> iterator = values.iterator(); int durationSum = 0; while (iterator.hasNext()) { durationSum += iterator.next().get(); } int magicNumber = fibonacci((durationSum % 10) + 5); IntWritable output = new IntWritable(magicNumber); context.write(key, output); } } public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException { Configuration conf = new Configuration(); String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs(); if (otherArgs.length != 2) { System.err.println("Usage: Fibonacci <input_file> <output_dir>"); System.exit(2); } Job job = Job.getInstance(conf, "Fibonacci Task"); job.setJarByClass(FibTask.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); job.setMapperClass(FibonacciMapper.class); job.setReducerClass(FibonacciReducer.class); FileInputFormat.addInputPath(job, new Path(otherArgs[0])); FileOutputFormat.setOutputPath(job, new Path(otherArgs[1])); boolean status = job.waitForCompletion(true); int statusCode = status? 0 : 1; System.exit(statusCode); } }
Java
ISO-8859-2
5,334
2.6875
3
[]
no_license
/** * */ package Server; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.net.Socket; import java.nio.ByteBuffer; import javax.imageio.ImageIO; /** * @author Sebastien and Valentin * */ public class Worker implements Runnable { private SingleServer server; private Socket socket; private Thread th; private ListWorker listWorker; private DataOutputStream out; private OutputStream outputStream; private String clientLogin; private int clientId; Worker(SingleServer server, Socket socket) { this.server = server; this.socket = socket; th = new Thread(this); th.start(); } @Override public void run() { System.out.println("[+] Worker created"); //Creating a Listener for each client listWorker = new ListWorker(this, socket); //Creating an output data stream to send the responses try { out = new DataOutputStream(socket.getOutputStream()); outputStream = socket.getOutputStream(); } catch (IOException e1) { e1.printStackTrace(); } } public void analyzeReq(int req, String data) { switch(req) { case 0: System.out.println("Request 0"); deconnection(); break; case 1: System.out.println("Request 1"); // Creating a new account boolean crea; crea = server.creaCompte(data); if(crea) { // Creation accepted sendResponse(11,""); } else { // Creation refused sendResponse(10,""); } //deconnection(); break; case 2: System.out.println("Request 2"); //Connecting to an account int conn; // The server return the id of the connected user. If he's not connected, return 0. conn = server.conCompte(data); if(conn != 0) { // Connection accepted sendResponse(21,""); clientId = conn; String[] parts = data.split("\t"); clientLogin = parts[0]; } else { // Connection refused sendResponse(20,""); deconnection(); } break; case 3: System.out.println(data); // The user is looking for information about the food int nbLines = server.searchFoodLines(data); String info = ""; if(nbLines==0) { // Nothing found sendResponse(30,""); } else { // Send the infos for(int i = 0; i<nbLines;i++) { info = server.searchFoodInfos(data, nbLines-i); // The line number is sent so that the client knows when to stop // Format: numLine, code, type_de_produit, nom, marque, categorie, score, valeur_energetique, acides_gras_satures, sucres, proteines, fibres, sel_ou_sodium, teneur_fruits_legumes sendResponse(31,String.valueOf(nbLines-i)+"\t"+info); } } break; case 4: System.out.println("Request 4"); //Modify infos about the account boolean modif; modif = server.modifCompte(data); if(modif) { // Modifications accepted sendResponse(41,""); } else { // Modifications refused sendResponse(40,""); } break; case 5: System.out.println("Request 5"); // Refresh the wall // Send the last 10 descriptions/images stored on the server boolean loop = true; int i=0; String text = ""; while(loop && i<10) { // Get the 10 last lines stored on the server // Return a line with: "username,title,description,imageName,date,nbAliments,aliment1,aliment2,...,scoreNutri" text = server.sendPostText(i+1); if(text == "") loop = false; else { sendResponse(8,text); } i++; } break; case 7: // The food doesn't exist. The user wants to add it in the database boolean added = server.addNewFood(data); if(added) { sendResponse(71,""); } else { sendResponse(70,""); } break; default: System.out.println("Request default"); //The id of the request is unknown, just skip the request } } public void storeInfos(String data,BufferedImage img, String date) { System.out.println("Request 6"); // Client uploading Text boolean upload = false; upload = server.upload(data, img, clientLogin, clientId, date); if(upload) { // Data uploaded accepted sendResponse(61,""); } else { // Data uploaded refused sendResponse(60,""); } } public void sendResponse(int req, String data) { try { out.writeInt(req); out.writeUTF(data); if(req == 8) { String[] parts = data.split("\t"); String imageName = parts[3]; // Sending the image to the client BufferedImage image = ImageIO.read(new File("C:\\Users\\Sbastien\\Desktop\\Cours\\3A\\Java\\JavaProject\\Java_Project\\images\\"+imageName+".png")); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ImageIO.write(image, "jpg", byteArrayOutputStream); byte[] size = ByteBuffer.allocate(4).putInt(byteArrayOutputStream.size()).array(); out.write(size); out.write(byteArrayOutputStream.toByteArray()); out.flush(); } } catch (IOException e) { e.printStackTrace(); } } public void deconnection() { listWorker.stop(); server.delWorker(this); try { out.close(); outputStream.close(); socket.close(); } catch (IOException e) { System.out.println("[x] Worker aborted"); } System.out.println("[-] Worker deleted"); th = null; } }
JavaScript
UTF-8
2,079
2.734375
3
[ "MIT" ]
permissive
function showLoginForm(){ $('#loginModal .registerBox').fadeOut('fast',function(){ $('.loginBox').fadeIn('fast'); $('.register-footer').fadeOut('fast',function(){ $('.login-footer').fadeIn('fast'); }); $('.modal-title').html('Login with'); }); $('.error').removeClass('alert alert-danger').html(''); } function openLoginModal(){ showLoginForm(); setTimeout(function(){ $('#loginModal').modal('show'); }, 230); } if (window.location.href.indexOf('login.html') > -1) { var input = document.getElementById("password"); input.addEventListener("keyup", function (event) { if (event.keyCode === 13) { event.preventDefault(); document.getElementById("login").click(); } }); } function shakeModal(){ $('#loginModal .modal-dialog').addClass('shake'); $('.error').addClass('alert alert-danger').html("Invalid email/password combination"); $('input[type="password"]').val(''); setTimeout( function(){ $('#loginModal .modal-dialog').removeClass('shake'); }, 1000 ); } function loginSuccess() { var email = document.getElementById('email').value; var password = document.getElementById('password').value; if (email === '' || password === '') //alert("Login credentials cannot be Empty!") $('#loginErrModal').modal('show') else if (email === '10seconds' && password === 'test@123') { // sessionStorage.setItem("authState", "authenticated"); $('#loginModalSuccess').modal('show') //alert("hello") } else { // //alert("Incorrect username or password! ") $('#detailModal').modal('show'); } } // function validateEmail(emailField){ // var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/; // if (reg.test(emailField.value) == false) // { // $('#emailModal').modal('show'); // return false; // } // return true; // }