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
4,126
2.921875
3
[ "MIT" ]
permissive
import re import sys from bs4 import BeautifulSoup import requests from epub import Epub from global_variable import HAS_QT, SENDER, HEADERS SINGLE_THREAD = False def get_urls(): """ Get urls from input or sys.argv Return: A string contains urls """ for i in sys.argv[1:]: if i.startswith('-u'): return i[2:] else: urls = input('Please input urls(separate with ","):') return urls def is_single_thread(): for i in sys.argv[1:]: if i.startswith('-s'): return True else: single = input("Single Thread(Y/N)?:") return True if single in ['Y', 'y'] else False def check_url(url): """ check input url Args: url: A string represent the url which was input by user Returns: return 'vollist' if the url represent a vollist return 'book' if the url represent a book return False if the url is neither vollist nor booklist """ vollist = re.compile(r'http://lknovel.lightnovel.cn/main/vollist/(\d+).html') book = re.compile(r'http://lknovel.lightnovel.cn/main/book/(\d+).html') if vollist.search(url): return 'vollist' elif book.search(url): return 'book' else: return False def print_info(info): print(info) if HAS_QT: SENDER.sigChangeStatus.emit(info) def grab_volume(url, epub_file_path, cover_path): """ grab volume Args: url: A string represent the url which was input by user epub_file_path: A string represent the path of the output EPUB file cover_file: A string represent the path of the EPUB cover """ try: print_info('Getting:' + url) epub = Epub(url=url, epub_file_path=epub_file_path, cover_path=cover_path, single_thread=SINGLE_THREAD) epub.generate_epub() except Exception as e: if HAS_QT: SENDER.sigWarningMessage.emit('错误', str(e) + '\nat:' + url) SENDER.sigButton.emit() print(url) raise e def parse_page(url): """ parse page with BeautifulSoup Args: url: A string represent the url to be parsed Return: A BeatifulSoup element """ r = requests.get(url, headers=HEADERS) r.encoding = 'utf-8' return BeautifulSoup(r.text) def grab_booklist(url, epub_file_path, cover_path): """ grab each volume in the booklist Args: url: A string represent the booklist epub_file_path: A string represent the path of the output EPUB file cover_file: A string represent the path of the EPUB cover """ soup = parse_page(url) temp_volume_link = soup.select('body div.content div.container dl dd.row div.inline h2.ft-24 strong a') find_lolume_link = re.compile(r'<a href="(.*)">') for i in temp_volume_link: volume_link = find_lolume_link.search(str(i)).group(1) grab_volume(volume_link, epub_file_path, cover_path) def start(urls, epub_file_path=None, cover_path=None): """ start the job using url Args: urls: A string represent the urls which was input by user epub_file_path: A string represent the path of the output EPUB file cover_file: A string represent the path of the EPUB cover """ for url in urls.split(','): check_result = check_url(url) if check_result == 'book': grab_volume(url, epub_file_path, cover_path) elif check_result == 'vollist': grab_booklist(url, epub_file_path, cover_path) else: print( '请输入正确的网址,例如:\nhttp://lknovel.lightnovel.cn/main/vollist/726.html' + '\nhttp://lknovel.lightnovel.cn/main/book/2664.html') def main(): urls = get_urls() if is_single_thread(): global SINGLE_THREAD SINGLE_THREAD = True start(urls) if __name__ == '__main__': main()
PHP
UTF-8
239
3.140625
3
[]
no_license
<?php function simplecall() { for ($i = 0; $i < 1000000; $i++) strlen("hallo"); } //////// $time_before = microtime(true); simplecall(); $time_after = microtime(true); printf('%.7f', $time_after - $time_before); echo "\n"; ?>
Python
UTF-8
72
3.546875
4
[]
no_license
total = 0 for number in range(1, 101): total += number print(total)
C#
UTF-8
2,153
2.84375
3
[]
no_license
using System; using System.IO; using System.Linq; using EF6Demo.CodeFirst.Entities; namespace EF6Demo.CodeFirst { class Program { static void Main(string[] args) { //http://blogs.msdn.com/b/dataaccess/archive/2005/10/28/486273.aspx AppDomain.CurrentDomain.SetData("DataDirectory", Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data")); using (var db = new DemoDbContext()) { if (!db.Database.Exists()) { var group = new Group { GroupName = "管理员组" }; var user = new User { UserId = "ylhyh", Password = "123456", Nickname = "Alan Hu", Email = "ylhuyh@163.com", MobilePhone = "13926581626", UserGroup = group }; /* * Make sure the folder exists of the data file, otherwise, the Add method will not create db automatically and throw error below: * 其他信息: Directory lookup for the file "E:\TestPrj\Dotnet\EF6Demo\EF6Demo\bin\Debug\App_Data\VDatabase.mdf" failed with the operating system error 2(系统找不到指定的文件。). * CREATE DATABASE failed. Some file names listed could not be created. Check related errors. */ db.Set<Group>().Add(group); db.Set<User>().Add(user); //db.Groups.Add(group); //db.Users.Add(user); var recordCount = db.SaveChanges(); } else { var users = from u in db.Users orderby u.Id select u; foreach (var user in users) { Console.WriteLine(user.Nickname); } } Console.ReadLine(); } } } }
Java
UTF-8
1,129
2.453125
2
[]
no_license
package erik.study.net.netty.doc.demo.time.server.handler; import erik.study.net.netty.doc.demo.time.pojo.UnixTime; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import lombok.extern.slf4j.Slf4j; /** * @author erik.wang * @Date 2019-10-02 */ @Slf4j public class TimeServerHandlerWithEncoder extends ChannelInboundHandlerAdapter { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ChannelFuture future = ctx.writeAndFlush(new UnixTime()); log.info("应该是先写write,然后才挨着outBoundHandler来处理"); // 一个future就代表这个动作 ,这个动作之后,就close该连接 // TODO: 2021/2/18 改一改实时 future.addListener(new ChannelFutureListener(){ @Override public void operationComplete(ChannelFuture future) throws Exception { log.info("写出去时间了。但是我就不关闭链接,哈哈"); } }); } }
JavaScript
UTF-8
201
2.9375
3
[]
no_license
function Mostrar() { var num=prompt() var primo=true for (i=2; i<num; i++) { if (num%i==0) { primo=false break } } if (primo) { alert ("Es primo") } }//FIN DE LA FUNCIÓN
Markdown
UTF-8
2,817
3.453125
3
[]
no_license
+++ date = "2015-10-14T15:05:14-07:00" title = "Type, *Type, Receivers & Interfaces" published=true categories = ["go"] keywords = ["go"] tags = ["go"] image = "images/typewriter-exploded.jpg" +++ I've recently seen a bit of confusion around types, pointers to types, receivers for the two and interfaces. I'm going to try to clarify that confusion a bit with some examples. Given a simple interface named **Fooer**, a struct type (**Bar**) that implements it and a simple function (**DoFoo()**) that accepts a **Fooer** and calls the interface function like so: {{< goplayground QDpxG41xqK >}} When you run the code above you get `Fooer: 5` for output. ## What's happening? **Bar** implements **Foo() int** so instances of it match the **Fooer** interface. If you change **Bar{}** to **&Bar{}** to create a pointer to a **Bar**, the [program](https://play.golang.org/p/M54OuYH9CU) runs and still works. This is because, as per the [GoSpec](https://golang.org/ref/spec#Method_sets): *pointer type \*T is the set of all methods declared with receiver \*T or T (that is, it also contains the method set of T)*. Since **Foo()** is declared on **Bar**, both an instance of **Bar** (**Bar{}**) and a pointer to an instance of **Bar** (**&Bar{}**) have the method **Foo() int**. Right now **Foo()** isn't doing anything interesting though, just returning the integer **5**. ## More interesting Let's modify the program a little so that **Foo()** actually does something: increment and return the value of a struct member. {{< goplayground yq9ImtGT0j >}} Run the program. It may not output what you expected. You may have expected the second call to **DoFoo** to output `Fooer: 2`, but instead `Fooer: 1` was output both times. This happened because **Foo()** is declared on **Bar** (the non pointer version) and **Foo()**'s receiver is a copy of the **Bar** that was passed to **DoFoo**. All parameters, including receivers, are pass by value and are copies of the original (this includes pointers btw, they are just copies of the pointer itself). Since it's a copy, we always start out with the initial value of **val**, which is **0**. So would changing **Bar{}** to **&Bar{}** fix the problem? No, because even though **\*Bar** contains all of the methods defined on **Bar**, they're still called with a copy of the **Bar** instance since they are declared as being *on* **Bar**. {{< goplayground NzGEH0om_u >}} To fix, we need to declare both **Foo()** on **\*Bar** *AND* pass a **\*Bar** to **DoFoo**. With this change an instance of **Bar** no longer matches the **Fooer** interface, but a pointer to **Bar** (**\*Bar**) does and works like so: {{< goplayground gOT_oyV327 >}} ## Fin I hope these examples help clear up confusion and show the relationships between T, *T, receivers and interfaces.
Java
UTF-8
1,966
2.078125
2
[]
no_license
package br.com.ilha.bean; import java.util.List; import javax.faces.bean.ManagedBean; import javax.faces.view.ViewScoped; import br.com.ilha.model.Produto; import br.com.ilha.resources.ProdutoResource; @ManagedBean @ViewScoped public class ProdutoBean { private ProdutoResource produtoResource; private Produto novoProduto; private int qtdP; private int qtdM; private int qtdG; private List<Produto> listaProdutos; public ProdutoResource getProdutoResource() { return produtoResource; } public void setProdutoResource(ProdutoResource produtoResource) { this.produtoResource = produtoResource; } public Produto getNovoProduto() { return novoProduto; } public void setNovoProduto(Produto novoProduto) { this.novoProduto = novoProduto; } public int getQtdP() { return qtdP; } public void setQtdP(int qtdP) { this.qtdP = qtdP; } public int getQtdM() { return qtdM; } public void setQtdM(int qtdM) { this.qtdM = qtdM; } public int getQtdG() { return qtdG; } public void setQtdG(int qtdG) { this.qtdG = qtdG; } public List<Produto> getListaProdutos() { this.produtoResource = new ProdutoResource(); return produtoResource.listarTodos(); } public void setListaProdutos(List<Produto> listaProdutos) { this.listaProdutos = listaProdutos; } public void gravar(){ try{ this.produtoResource = new ProdutoResource(); produtoResource.gravar(novoProduto, qtdP, qtdM, qtdG); }catch(Exception e){ } } public int produtoQtdP(Produto prodt){ this.produtoResource = new ProdutoResource(); return produtoResource.qtdP(prodt); } public int produtoQtdM(Produto prodt){ this.produtoResource = new ProdutoResource(); return produtoResource.qtdM(prodt); } public int produtoQtdG(Produto prodt){ this.produtoResource = new ProdutoResource(); return produtoResource.qtdG(prodt); } }
TypeScript
UTF-8
862
2.765625
3
[]
no_license
import { Request, Response } from 'express'; import { addGenre, allGenres } from '../services/genreServices'; async function newGenre(req:Request, res: Response) { const { name } : {name: string}= req.body; if(!name ) return res.sendStatus(400); if(typeof name !== 'string') return res.sendStatus(404); try{ const existGenre = await addGenre(name); if(existGenre) return res.sendStatus(409); else return res.sendStatus(200); } catch(e){ console.error(e); res.sendStatus(500); } } async function genreList(req: Request, res: Response) { const {id} = req.params; if(id){ if(!parseInt(id)) return res.sendStatus(400); res.send(id); } else{ const alphabeticList = await allGenres(); res.send(alphabeticList) } } export { newGenre, genreList };
Java
UTF-8
229
2.453125
2
[]
no_license
import static java.lang.Math.*; public class CalcMethod2 implements ICalcMethod { public double calc(double a, double b, double c, double d) { return (6 * pow(sin(abs(2*a)), log10(b))) + (sqrt(c*cosh(-d))); } }
Java
UTF-8
2,105
3
3
[]
no_license
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.Hashtable; import java.util.Scanner; public class Calculator { public static HashSet<String> setClassName=new HashSet<String>(); public static void main(String[] args) throws IOException { ArrayList<ArrayList<String>> records = new ArrayList<>(); Hashtable<String, Integer> hash=new Hashtable<String, Integer>(); Scanner input=new Scanner(System.in); //"D:\\Measurement-Project\\Reports\\PITest\\commons-codec\\mutations.csv" String inputPath=input.nextLine(); String outputPath=input.nextLine(); Scanner scan=new Scanner(new FileInputStream(inputPath)); while(scan.hasNextLine()) { records.add(getRecordFromLine(scan.nextLine())); } int size=0; double killed=0; int mutation=0; for (String item : setClassName) { size=0; killed=0; for (ArrayList<String> arrayList : records) { if (item.equalsIgnoreCase(arrayList.get(0))) { size++; if(arrayList.get(5).equals("KILLED")|| arrayList.get(5).equals("TIMED_OUT") ) { killed++; } } } mutation=(int) (Math.round(killed/size*100)); hash.put(item, mutation); } FileWriter csvWriter = new FileWriter(outputPath); hash.entrySet().forEach( entry -> { try { csvWriter.append(entry.getKey()+","+entry.getValue()); } catch (IOException e) { e.printStackTrace(); } try { csvWriter.append("\n"); } catch (IOException e) { e.printStackTrace(); } }); csvWriter.flush(); csvWriter.close(); } public static ArrayList<String> getRecordFromLine(String line) { ArrayList<String> values = new ArrayList<String>(); Hashtable<String,Integer> hash=new Hashtable<String,Integer>(); try (Scanner rowScanner = new Scanner(line)) { rowScanner.useDelimiter(","); while (rowScanner.hasNext()) { values.add(rowScanner.next()); } } setClassName.add(values.get(0)); return values; } }
Java
UTF-8
629
3.578125
4
[]
no_license
package es2; import java.util.ArrayList; import java.util.List; import java.util.Random; public class Shuffle { public static <E> void swap(List<E> a, int i, int j) { E tmp = a.get(i); a.set(i, a.get(j)); a.set(j, tmp); } public static void shuffle(List<Integer> list, Random rnd) { for (int i = list.size(); i > 1; i--) swap(list, i - 1, rnd.nextInt(i)); } public static void main(String[] args){ List<Integer> list = new ArrayList(); for (int i = 0; i < 10; i++){ list.add(i); } System.out.println(list); shuffle(list, new Random()); System.out.println(list); } }
Python
UTF-8
2,085
2.671875
3
[ "MIT", "BSD-3-Clause" ]
permissive
""" file: unmarshallers.py (pysiss.vocabulary.gml) author: Jess Robertson CSIRO Mineral Resources Flagship date: Monday 25 August, 2014 description: Unmarshalling functions for GeoSciML/GML objects """ from shapely.geometry import Polygon, LineString from ..namespaces import NamespaceRegistry NAMESPACES = NamespaceRegistry() def position(elem): """ Unmarshal a gml:posList, gml:pos or gml:coordinates element """ if elem.text: token_pairs = elem.text.split('\n')[1:-1] return [map(float, p.split()) for p in token_pairs] else: return None def polygon(elem): """ Unmarshal a gml:Polygon element """ # Get the projection projection = elem.xpath('.//@srsName', namespaces=NAMESPACES)[0] # Get outer boundary first, we always have this outer = position( elem.xpath('.//gml:outerBoundaryIs//gml:posList', namespaces=NAMESPACES)[0]) # We may have 0, 1 or more inner boundaries inners = elem.xpath('.//gml:innerBoundaryIs//gml:posList', namespaces=NAMESPACES) if not inners: inners = None else: inners = map(position, inners) return {'projection': projection, 'shape': Polygon(outer, inners)} def linestring(elem): """ Unmarshal a gml:LineString element """ # Get the projection projection = elem.xpath('.//@srsName', namespaces=NAMESPACES)[0] # Get the LineString text string = position( elem.xpath('./gml:posList', namespaces=NAMESPACES)[0]) return {'projection': projection, 'shape': LineString(string)} def description(elem): """ Unmarshal a gml:description element """ return elem.text UNMARSHALLERS = { 'gml:posList': position, 'gml:pos': position, 'gml:coordinates': position, 'gml:Polygon': polygon, 'gml:LineString': linestring, 'gml:description': description, } __all__ = (position, polygon, linestring, UNMARSHALLERS)
Python
UTF-8
1,709
3.296875
3
[]
no_license
import tensorflow as tf """ https://danijar.com/structuring-models/ """ class DnCNN(tf.keras.Model): def __init__(self,depth = 5,grayscale=True): super(DnCNN,self).__init__() # Network params self.channels = 1 if grayscale else 3 self.depth = depth def call(self,input_tensor,training=True): # First Convolution Layer with Conv and ReLU x = tf.keras.layers.Conv2D(64,(3,3),padding="same",kernel_initializer='Orthogonal')(input_tensor) x = tf.keras.activations.relu(x) # Add Conv+Batch_Norm+ReLU for layers 2 to (depth-1) for _ in range(self.depth - 1): x = tf.keras.layers.Conv2D(64,(3,3),padding="same",kernel_initializer='Orthogonal')(x) x = tf.keras.layers.BatchNormalization(epsilon=0.0001)(x,training=training) x = tf.keras.activations.relu(x) # The final conv layer will use only 1 filter to recontruct the original image x = tf.keras.layers.Conv2D(1,(3,3),padding="same",kernel_initializer='Orthogonal')(x) # Subtract the predicted noise from the noisy input image x = tf.keras.layers.Subtract()([input_tensor,x]) #input - noise return x def model(self): # Funtion to build the model x = tf.keras.Input(shape=(None,None,self.channels)) return tf.keras.Model(inputs=[x],outputs= self.call(x) ) # Simple code to instantiate , compile and print the summary of the model architecture # if __name__ == "__main__": # model = DnCNN(depth=5).model() # model.compile(optimizer='Adam',loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True),metrics=["accuracy"]) # print(model.summary())
Python
UTF-8
368
2.953125
3
[]
no_license
for t in range(int(input())): N = int(input()) arr = list(map(int, input().split())) for i in range(0, N - 1): if i % 2 == 0: if arr[i] > arr[i + 1]: arr[i], arr[i + 1] = arr[i + 1], arr[i] if i % 2 == 1: if arr[i] < arr[i + 1]: arr[i], arr[i + 1] = arr[i + 1], arr[i] print(*arr)
Python
UTF-8
2,500
2.8125
3
[]
no_license
import subprocess import cv2 import os import argparse import json def split_video_to_parts(video_path, out_dir, segment_len_frames, overlap_percent, index_from=0): filename = os.path.basename(video_path)[:-4] dir_path = os.path.join(out_dir, filename) if not os.path.exists(dir_path): os.makedirs(dir_path) else: return 0 v = cv2.VideoCapture(video_path) v.set(cv2.CAP_PROP_POS_AVI_RATIO,1) duration = v.get(cv2.CAP_PROP_POS_MSEC) frame_count = v.get(cv2.CAP_PROP_FRAME_COUNT) fps = v.get(cv2.CAP_PROP_FPS) time_len = round(segment_len_frames / fps, 2) frame_from = 0 frame_to = frame_from + segment_len_frames num_video_parts = index_from while frame_to <= frame_count: start_time = round(frame_from / fps, 2) p = subprocess.call(f'ffmpeg -i {video_path} -ss {start_time} -t {time_len} -strict -2 {dir_path}/part_{num_video_parts}.mp4', shell=True) num_video_parts += 1 frame_from += int((1 - overlap_percent) * segment_len_frames) frame_to = frame_from + segment_len_frames # print("frame from: ", frame_from) return num_video_parts - index_from if __name__ == "__main__": parser = argparse.ArgumentParser(description='Process arguments') parser.add_argument('--video_dir', type=str, help='Directory containing mp4 files.') parser.add_argument('--output_dir', type=str, help='Directory where to save video parts.') parser.add_argument('--segment_len', type=int, help='Segment length in frames.') parser.add_argument('--overlap', type=float, default=0.3, help='Overlap between segments.') args = parser.parse_args() if not os.path.exists(args.output_dir): os.makedirs(args.output_dir) config = dict() config['segment_len'] = args.segment_len config['overlap'] = args.overlap with open(os.path.join(args.output_dir, 'config.json'), "w") as write_file: json.dump(config, write_file) filepaths = [os.path.join(args.video_dir, f) for f in os.listdir(args.video_dir) if (os.path.isfile(os.path.join(args.video_dir, f)) and f.endswith('.mp4'))] print(filepaths) index_from = 0 for filepath in filepaths: print("Filepath: ", filepath) num_parts = split_video_to_parts(filepath, args.output_dir, args.segment_len, args.overlap, index_from) index_from += num_parts + 1
Java
UTF-8
7,818
2.34375
2
[ "Apache-2.0" ]
permissive
package at.salzburgresearch.nodekeeper.tests.ruleEngineTests; import at.salzburgresearch.nodekeeper.eca.*; import at.salzburgresearch.nodekeeper.eca.function.CurrentNodeData; import at.salzburgresearch.nodekeeper.eca.function.CurrentNodeLabel; import at.salzburgresearch.nodekeeper.exception.NodeKeeperException; import at.salzburgresearch.nodekeeper.model.Node; import at.salzburgresearch.nodekeeper.tests.NodeKeeperTest; import org.junit.Assert; import org.junit.Test; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; /** * ... * <p/> * Author: Thomas Kurz (tkurz@apache.org) */ public class SimpleRuleTests extends NodeKeeperTest { @Test public void createNodeWithRuleTest() throws InterruptedException, IOException, NodeKeeperException, TransformerException, ParserConfigurationException { RuleHandler ruleHandler = new RuleHandler(nodeKeeper); Rule rule = new Rule(); rule.event = new Event(Event.Type.nodeCreated,"/my/event/.+"); rule.bindings.add(new Binding("name",new CurrentNodeLabel(),false)); rule.bindings.add(new Binding("data",new CurrentNodeData(),false)); rule.actions.add(new Action(Action.Type.createUpdateNode,"/my/action/{name}","Hallo {data}")); ruleHandler.addRule(rule); nodeKeeper.writeNode(new Node<String>("/my/event/node1","Testwelt"),String.class); Thread.sleep(2000); Node<String> node = nodeKeeper.readNode("/my/action/node1",String.class); nodeKeeper.writeNode(new Node<String>("/my/event/node2","World2"),String.class); nodeKeeper.writeNode(new Node<String>("/my/event/node3","World3"),String.class); Thread.sleep(2000); Node<String> node2 = nodeKeeper.readNode("/my/action/node2",String.class); Node<String> node3 = nodeKeeper.readNode("/my/action/node3",String.class); Assert.assertNotNull(node); Assert.assertNotNull(node2); Assert.assertNotNull(node3); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ruleHandler.writeRules(baos); //System.out.println(baos.toString()); } @Test public void checkConditions() throws InterruptedException, IOException, NodeKeeperException, TransformerException, ParserConfigurationException { RuleHandler ruleHandler = new RuleHandler(nodeKeeper); Rule rule = new Rule(); rule.event = new Event(Event.Type.nodeCreated,"/my/event/.+"); rule.bindings.add(new Binding("name",new CurrentNodeLabel(),false)); rule.bindings.add(new Binding("data",new CurrentNodeData(),false)); rule.conditions.add(new Condition(Condition.Type.equals,"{name}","node1")); rule.actions.add(new Action(Action.Type.createUpdateNode,"/my/action/{name}","Hallo {data}")); ruleHandler.addRule(rule); nodeKeeper.writeNode(new Node<String>("/my/event/node1","Testwelt"),String.class); Thread.sleep(2000); Node<String> node = nodeKeeper.readNode("/my/action/node1",String.class); nodeKeeper.writeNode(new Node<String>("/my/event/node2","World2"),String.class); nodeKeeper.writeNode(new Node<String>("/my/event/node3","World3"),String.class); Thread.sleep(2000); Node<String> node2 = nodeKeeper.readNode("/my/action/node2",String.class); Node<String> node3 = nodeKeeper.readNode("/my/action/node3",String.class); Assert.assertNotNull(node); Assert.assertNull(node2); Assert.assertNull(node3); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ruleHandler.writeRules(baos); System.out.println(baos.toString()); } @Test public void deleteNodeWithRuleTest() throws InterruptedException, IOException, NodeKeeperException { nodeKeeper.writeNode(new Node<String>("/my/event/node1","One"),String.class); nodeKeeper.writeNode(new Node<String>("/my/action/node1","Two"),String.class); Node<String> node1 = nodeKeeper.readNode("/my/action/node1",String.class); RuleHandler ruleHandler = new RuleHandler(nodeKeeper); Rule rule = new Rule(); rule.event = new Event(Event.Type.nodeDeleted,"/my/event/.+"); rule.bindings.add(new Binding("$name",new CurrentNodeLabel(),false)); rule.actions.add(new Action(Action.Type.deleteNode,"/my/action/$name")); ruleHandler.addRule(rule); nodeKeeper.deleteNode(new Node<String>("/my/event/node1")); Thread.sleep(2000); Node<String> node2 = nodeKeeper.readNode("/my/action/node1",String.class); } @Test public void parseRulesTest() throws InterruptedException, IOException, NodeKeeperException { InputStream in = new FileInputStream("src/test/resources/rules.xml"); RuleHandler handler = new RuleHandler(nodeKeeper); handler.readRules(in); nodeKeeper.writeNode(new Node<String>("/my/event/node","World"),String.class); Thread.sleep(2000); Assert.assertEquals("Hello World: Test",nodeKeeper.readNode("/my/action/NODE",String.class).getData()); InputStream in2 = new FileInputStream("src/test/resources/rules2.xml"); handler.readRules(in2); nodeKeeper.writeNode(new Node<String>("/my/event/node","Update"),String.class); Thread.sleep(2000); Assert.assertNotNull(nodeKeeper.readNode("/my/action/NODE",String.class)); System.out.println(handler.getDescription()); } @Test public void testOrFunction() throws IOException, InterruptedException, NodeKeeperException { InputStream in = new FileInputStream("src/test/resources/rules3.xml"); RuleHandler handler = new RuleHandler(nodeKeeper); handler.readRules(in); nodeKeeper.writeNode(new Node<String>("/parent/instance","instance123"),String.class); nodeKeeper.writeNode(new Node<String>("/parent/node1","node1"),String.class); Thread.sleep(2000); Assert.assertEquals("/data/stanbol/indexes/instance123",nodeKeeper.readNode("/result/node1",String.class).getData()); nodeKeeper.writeNode(new Node<String>("/indexdir","/standard"),String.class); nodeKeeper.writeNode(new Node<String>("/parent/node2","node2"),String.class); Thread.sleep(2000); Assert.assertEquals("/standard",nodeKeeper.readNode("/result/node2",String.class).getData()); } @Test public void testBindingStrictMode() throws IOException, InterruptedException, NodeKeeperException { InputStream in = new FileInputStream("src/test/resources/rules2.xml"); RuleHandler handler = new RuleHandler(nodeKeeper); handler.readRules(in); Thread.sleep(2000); nodeKeeper.writeNode(new Node<String>("/my/demo/test/set/version","0"),String.class); Thread.sleep(2000); Node<String> n = nodeKeeper.readNode("/stanbol/instances/sites/test/set_kiwi_yard", String.class); Assert.assertNotNull(n); Assert.assertEquals(Binding.DEFAULT_BINDING,n.getData()); in.close(); } @Test public void testBindingStrictModeTrue() throws IOException, InterruptedException, NodeKeeperException { InputStream in = new FileInputStream("src/test/resources/rules4.xml"); RuleHandler handler = new RuleHandler(nodeKeeper); handler.readRules(in); nodeKeeper.writeNode(new Node<String>("/my/demo/test/set/version","0"),String.class); Thread.sleep(2000); Node<String> n = nodeKeeper.readNode("/stanbol/instances/sites/test/set_kiwi_yard", String.class); Assert.assertNull(n); in.close(); } }
Java
UTF-8
1,316
2.15625
2
[]
no_license
package org.apache.log4j.jmx; import com.sun.jdmk.comm.CommunicatorServer; import com.sun.jdmk.comm.HtmlAdaptorServer; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.ObjectName; import org.apache.log4j.Category; import org.apache.log4j.Logger; public class Agent { static Logger log = Logger.getLogger(Agent.class); public void start() { MBeanServer localMBeanServer = MBeanServerFactory.createMBeanServer(); HtmlAdaptorServer localHtmlAdaptorServer = new HtmlAdaptorServer(); try { log.info("Registering HtmlAdaptorServer instance."); localMBeanServer.registerMBean(localHtmlAdaptorServer, new ObjectName("Adaptor:name=html,port=8082")); log.info("Registering HierarchyDynamicMBean instance."); HierarchyDynamicMBean localHierarchyDynamicMBean = new HierarchyDynamicMBean(); localMBeanServer.registerMBean(localHierarchyDynamicMBean, new ObjectName("log4j:hiearchy=default")); } catch (Exception localException) { log.error("Problem while regitering MBeans instances.", localException); return; } localHtmlAdaptorServer.start(); } } /* Location: D:\test\Fusion Installer.jar * Qualified Name: org.apache.log4j.jmx.Agent * JD-Core Version: 0.6.0 */
Java
UTF-8
1,414
2.828125
3
[]
no_license
package events; import game.Die; import game.GameData; public class Nepotism extends Card { public static int roll; public static final int[] results = {0, 4, 4, 3, 3, 1, 1}; @Override public void onEvent(int sp, String[] args) { roll = new Die().roll(); GameData.dec = new Decision(1, 80); GameData.txtcom.sendMessage(GameData.rolecom.getAsMention() + ", you rolled a " + roll + ". You may place " + results[roll] + " support among worker spaces in the Balkans.").complete(); } @Override public boolean isPlayable(int sp) { return true; } @Override public String getId() { return "080"; } @Override public String getName() { return "Nepotism"; } @Override public int getOps() { return 3; } @Override public int getEra() { return 1; } @Override public int getAssociation() { return 1; } @Override public boolean isRemoved() { return true; } @Override public boolean isFormatted(int sp, String[] args) { return true; } @Override public String getDescription() { return "A die is rolled.\n" + "1-2: Place a total of 4 Communist Support in Worker spaces in the Balkans.\n" + "3-4: Place a total of 3 Communist Support in Worker spaces in the Balkans.\n" + "5-6: Place 1 Communist Support in a Worker space in the Balkans.\n"; } @Override public String getArguments() { return "Event: None.\n" + "Decision: Influence."; } }
C++
UTF-8
993
2.578125
3
[]
no_license
#include<SoftwareSerial.h> #include <Servo.h> SoftwareSerial BTSerial(10,11); //RX,TX Servo hand1; Servo hand2; // twelve servo objects can be created on most boards int pos = 0; // variable to store the servo position String dataIn; int handposR; void setup() { pinMode(4, OUTPUT); digitalWrite(4, LOW); hand1.attach(5); hand2.attach(6); BTSerial.begin(9600); Serial.begin(9600); } void loop() { // Keep reading from HC-05 and send to Arduino Serial Monitor if (BTSerial.available()){ dataIn = BTSerial.readString(); Serial.println(dataIn); if (dataIn.startsWith("arm")){ digitalWrite(4, HIGH); delay(2000); digitalWrite(4, LOW); }else if(dataIn.startsWith("hn")){ String dataInS = dataIn.substring(2, dataIn.length()); Serial.println(dataInS); handposR = dataInS.toInt(); hand1.write(handposR); hand2.write(180-handposR); } } if (Serial.available()){ BTSerial.write(Serial.read()); } }
Java
UTF-8
1,738
3.40625
3
[]
no_license
public class Main { //Sorting by counting:Comparison counting public static void main(String[] args) { int N = 16; int[] keys = new int[17]; int[] COUNT = new int[17]; //Prepare the data keys[1] = 503; keys[2] = 87; keys[3] = 512; keys[4] = 61; keys[5] = 908; keys[6] = 170; keys[7] = 897; keys[8] = 275; keys[9] = 653; keys[10] = 426; keys[11] = 154; keys[12] = 509; keys[13] = 612; keys[14] = 677; keys[15] = 765; keys[16] = 703; //Output unsorted keys System.out.println("Unsorted keys:"); for(int i=1; i<=N; i++){ System.out.println(i+":"+keys[i]); } System.out.println(); //Clear COUNTs for(int i=1; i<=N; i++){ COUNT[i] = 0; } //Kernel of the Algorithm for(int i=N; i>1; i--){ for(int j=i-1; j>=1; j--){ if(keys[i] < keys[j]){ COUNT[j]++; }else{ COUNT[i]++; } } } //Output final COUNTs System.out.println("COUNT values:"); for(int i=1; i<=N; i++){ System.out.println("COUNT["+i+"]="+COUNT[i]); } System.out.println(); //Output sorted keys System.out.println("Sorted keys:"); for(int i=0; i<=N-1; i++){ for(int j=1; j<=N; j++){ if(COUNT[j] == i){ System.out.println((COUNT[j]+1)+":"+keys[j]); } } } } }
PHP
UTF-8
2,612
2.90625
3
[]
no_license
<?php declare(strict_types=1); use PaulDawson\ContainerTest\Container; use PaulDawson\ContainerTest\Dummy\Baz; use PaulDawson\ContainerTest\Dummy\CustomFoo; use PaulDawson\ContainerTest\Dummy\Foo; use PaulDawson\ContainerTest\Dummy\Bar; use PaulDawson\ContainerTest\Dummy\NestedBar; use PaulDawson\ContainerTest\Dummy\NestedBaz; require_once 'vendor/autoload.php'; // // Create a new instance of the container // $container = Container::instance(); // // Register container bindings // $container[Foo::class] = static fn () => new Foo('test'); $container->singleton( Bar::class, static fn () => new Bar() ); $container->register( NestedBar::class, static fn (Container $container) => new NestedBar($container->get(Bar::class)) ); $container->register( CustomFoo::class, static fn (Container $container, array $arguments) => new CustomFoo(...$arguments) ); // Note: We do not nest Baz here, this can be auto-wired from the container // // Testing the container // Could use PHP unit, but this is simpler for explanation. // /** @var Foo $foo */ $foo = $container[Foo::class]; assert($foo instanceof Foo); assert($foo->getProperty() === 'test'); /** @var Bar $bar */ $bar = $container->get(Bar::class); assert($bar instanceof Bar); assert($bar->helloWorld() === 'hello, world!'); assert($bar === $container->get(Bar::class)); assert($bar === $container[Bar::class]); /** @var Baz $baz */ $baz = $container->get(Baz::class); assert($baz instanceof Baz); assert($baz->helloWorld() === 'no, goodbye!'); /** @var NestedBar $nestedBar */ $nestedBar = $container->get(NestedBar::class); assert($nestedBar instanceof NestedBar); assert($nestedBar->getBar() instanceof Bar); // This one is registered as a singleton; we would expect the instances to be // exactly the same, so we can compare them strictly. assert($nestedBar->getBar() === $container->get(Bar::class)); assert($nestedBar->getBar() === $container[Bar::class]); // // We can also auto-wire the nested classes! // $nestedBaz = $container->get(NestedBaz::class); assert($nestedBaz instanceof NestedBaz); assert($nestedBaz->getBaz() instanceof Baz); assert($nestedBaz->getBaz() !== $baz); $customFoo = $container->make(CustomFoo::class, ['A custom parameter']); assert($customFoo instanceof CustomFoo); assert($customFoo->getProperty() === 'A custom parameter'); $anotherCustomFoo = $container->make(CustomFoo::class, ['Another instance']); assert($anotherCustomFoo instanceof CustomFoo); assert($anotherCustomFoo !== $customFoo); assert($anotherCustomFoo->getProperty() === 'Another instance');
Java
UTF-8
127,374
1.757813
2
[]
no_license
package com.cloudweb.oa.controller; import cn.js.fan.db.ListResult; import cn.js.fan.db.ResultIterator; import cn.js.fan.db.ResultRecord; import cn.js.fan.util.DateUtil; import cn.js.fan.util.ErrMsgException; import cn.js.fan.util.ParamUtil; import cn.js.fan.util.StrUtil; import com.cloudweb.oa.api.IModuleFieldSelectCtl; import com.cloudweb.oa.api.INestSheetCtl; import com.cloudweb.oa.service.MacroCtlService; import com.cloudweb.oa.utils.SpringUtil; import com.cloudwebsoft.framework.db.JdbcTemplate; import com.cloudwebsoft.framework.util.LogUtil; import com.redmoon.oa.android.Privilege; import com.redmoon.oa.base.IFormMacroCtl; import com.redmoon.oa.flow.*; import com.redmoon.oa.flow.macroctl.MacroCtlMgr; import com.redmoon.oa.flow.macroctl.MacroCtlUnit; import com.redmoon.oa.person.UserDb; import com.redmoon.oa.person.UserMgr; import com.redmoon.oa.util.RequestUtil; import com.redmoon.oa.visual.*; import com.redmoon.oa.visual.FormDAO; import lombok.extern.slf4j.Slf4j; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import java.io.UnsupportedEncodingException; import java.util.*; @Slf4j @RestController @RequestMapping("/public/android") public class ModularController { public static final int RETURNCODE_SUCCESS = 0; //登录成功 public static final String RES = "res"; public static final int RESULT_TIME_OUT = -2;//时间过期 public static final String RETURNCODE = "returnCode"; public static final int RESULT_FORMCODE_ERROR = -3;//未传formcode public static final int RESULT_MODULE_ERROR = -8;//未传moduleCode public static final int RESULT_NO_DATA = -1;//列表无数据 public static final int RESULT_SUCCESS = 0;//请求成功 public static final String RESULT = "result"; public static final String DATAS = "datas"; @Autowired HttpServletRequest request; @ResponseBody @RequestMapping(value = "/module/list", produces = {"application/json;charset=UTF-8;"}) public String list(@RequestParam(defaultValue = "", required = true) String skey, String moduleCode, String op, String orderBy, String sort, Integer pageNum, Integer pageSize) throws JSONException { JSONObject jReturn = new JSONObject(); JSONObject jResult = new JSONObject(); if ("".equals(moduleCode)) { jReturn.put(RES, RESULT_MODULE_ERROR); //请求成功 return jReturn.toString(); } ModuleSetupDb msd = new ModuleSetupDb(); msd = msd.getModuleSetupDb(moduleCode); if (orderBy == null) { orderBy = ParamUtil.get(request, "orderBy"); } if (sort == null) { sort = ParamUtil.get(request, "sort"); } if ("".equals(orderBy)) { String filter = StrUtil.getNullStr(msd.getString("filter")).trim(); boolean isComb = filter.startsWith("<items>") || filter.equals(""); // 如果是组合条件,则赋予后台设置的排序字段 if (isComb) { orderBy = StrUtil.getNullStr(msd.getString("orderby")); sort = StrUtil.getNullStr(msd.getString("sort")); } if ("".equals(orderBy)) { orderBy = "id"; } } if ("".equals(sort)) { sort = "desc"; } String formCode = msd.getString("form_code"); try { UserMgr um = new UserMgr(); Privilege privilege = new Privilege(); boolean re = privilege.Auth(skey); String userName = privilege.getUserName(skey); jReturn.put(RES, RETURNCODE_SUCCESS); //请求成功 if (re) { jResult.put(RETURNCODE, RESULT_TIME_OUT); //登录超时 } else { privilege.doLogin(request, skey); if (formCode == null || formCode.trim().equals("")) { jResult.put(RETURNCODE, RESULT_FORMCODE_ERROR); //表单为空 } else { FormDb fd = new FormDb(); fd = fd.getFormDb(formCode); if (!fd.isLoaded()) { //表单不存在 jResult.put(RETURNCODE, RESULT_FORMCODE_ERROR);//表单不存在 return jResult.toString(); } else { MacroCtlUnit mu; MacroCtlMgr mm = new MacroCtlMgr(); FormDAO fdao = new FormDAO(); if (msd == null) { jResult.put(RETURNCODE, RESULT_MODULE_ERROR);//表单不存在 return jResult.toString(); } String btnName = StrUtil.getNullStr(msd.getString("btn_name")); String[] btnNames = StrUtil.split(btnName, ","); String btnScript = StrUtil.getNullStr(msd.getString("btn_script")); String[] btnScripts = StrUtil.split(btnScript, "#"); // 取得条件 JSONArray conditions = new JSONArray(); int len = 0; if (btnNames != null) { len = btnNames.length; for (int i = 0; i < len; i++) { if (btnScripts[i].startsWith("{")) { JSONObject jsonBtn = new JSONObject(btnScripts[i]); if (((String) jsonBtn.get("btnType")).equals("queryFields")) { String condFields = (String) jsonBtn.get("fields"); String[] fieldAry = StrUtil.split(condFields, ","); for (int j = 0; j < fieldAry.length; j++) { String fieldName = fieldAry[j]; FormField ff = fd.getFormField(fieldName); if (ff == null) { continue; } String condType = (String) jsonBtn.get(fieldName); String queryValue = ParamUtil.get(request, fieldName); queryValue = new String(queryValue.getBytes("ISO-8859-1"), "UTF-8"); JSONObject jo = new JSONObject(); jo.put("type", ff.getType()); jo.put("fieldName", ff.getName()); jo.put("fieldTitle", ff.getTitle()); jo.put("fieldType", ff.getFieldType()); jo.put("fieldCond", condType); // 点时间、时间段或模糊、准确查询 jo.put("fieldOptions", ""); if (ff.getType().equals(FormField.TYPE_MACRO)) { mu = mm.getMacroCtlUnit(ff.getMacroType()); if (mu != null) { IFormMacroCtl ifm = mu.getIFormMacroCtl(); if (ifm.getControlType().equals(FormField.TYPE_SELECT)) { jo.put("controlType", FormField.TYPE_SELECT); jo.put("fieldOptions", ifm.getControlOptions(userName, ff)); } } } jo.put("fieldValue", queryValue); if (ff.getType().equals(FormField.TYPE_DATE) || ff.getType().equals(FormField.TYPE_DATE_TIME)) { if (condType.equals("0")) { String fDate = ParamUtil.get(request, ff.getName() + "FromDate"); String tDate = ParamUtil.get(request, ff.getName() + "ToDate"); jo.put("fromDate", fDate); jo.put("toDate", tDate); } } conditions.put(jo); } } } } } jResult.put("conditions", conditions); String[] ary = null; request.setAttribute(ModuleUtil.MODULE_SETUP, msd); ary = SQLBuilder.getModuleListSqlAndUrlStr(request, fd, op, orderBy, sort); String sql = ary[0]; // 增加权限控制 ModulePrivDb mpd = new ModulePrivDb(moduleCode); boolean canAdd = mpd.canUserAppend(userName); boolean canEdit = mpd.canUserModify(userName); boolean canDel = mpd.canUserManage(userName); jResult.put("canAdd", canAdd); jResult.put("canEdit", canEdit); jResult.put("canDel", canDel); // 列名 JSONArray cols = new JSONArray(); jResult.put("cols", cols); int i = 0; // String listField = StrUtil.getNullStr(msd.getString("list_field")); String[] formFieldArr = msd.getColAry(false, "list_field"); if (formFieldArr != null && formFieldArr.length > 0) { ListResult lr = fdao.listResult(formCode, sql, pageNum, pageSize); long total = lr.getTotal(); if (total == 0) { jResult.put("total", total); //总页数 jResult.put(RETURNCODE, RESULT_NO_DATA); //没有数据 } else { jResult.put("total", total); //总页数 jResult.put(RETURNCODE, RESULT_SUCCESS); //请求成功 Iterator ir = null; Vector v = lr.getResult(); JSONArray dataArr = new JSONArray(); if (v != null) { ir = v.iterator(); } // 将不显示的字段加入fieldHide String fieldHide = ""; Iterator irField = fd.getFields().iterator(); while (irField.hasNext()) { FormField ff = (FormField) irField.next(); if (ff.getHide() == FormField.HIDE_ALWAYS) { if ("".equals(fieldHide)) { fieldHide = ff.getName(); } else { fieldHide += "," + ff.getName(); } } } String[] fdsHide = StrUtil.split(fieldHide, ","); List<String> listHide = null; if (fdsHide != null) { listHide = Arrays.asList(ary); } WorkflowDb wf = new WorkflowDb(); HashMap<String, FormField> map = getFormFieldsByFromCode(formCode); while (ir != null && ir.hasNext()) { fdao = (FormDAO) ir.next(); RequestUtil.setFormDAO(request, fdao); long id = fdao.getId(); JSONObject rowObj = new JSONObject(); rowObj.put("id", id); rowObj.put("creator", um.getUserDb(fdao.getCreator()).getRealName()); JSONArray fieldArr = new JSONArray(); rowObj.put("fields", fieldArr); for (String fieldName : formFieldArr) { // 不需要显示操作列 if (fieldName.equals("colOperate")) { continue; } JSONObject formFieldObj = new JSONObject(); //Form表单对象 // System.out.println(ListAction.class.getName() + " fieldName=" + fieldName); String title = ""; if (fieldName.startsWith("main:")) { String[] subFields = StrUtil.split(fieldName, ":"); if (subFields.length == 3) { FormDb subfd = new FormDb(subFields[1]); title = subfd.getFieldTitle(subFields[2]); } } else if (fieldName.startsWith("other:")) { String[] otherFields = StrUtil.split(fieldName, ":"); if (otherFields.length == 5) { FormDb otherFormDb = new FormDb(otherFields[2]); title = otherFormDb.getFieldTitle(otherFields[4]); } } else if (fieldName.equals("cws_creator")) { title = "创建者"; } else if (fieldName.equals("ID")) { title = "ID"; } else if (fieldName.equals("cws_progress")) { title = "进度"; } else if (fieldName.equals("flowId")) { title = "流程号"; } else if (fieldName.equals("cws_status")) { title = "状态"; } else if (fieldName.equals("cws_flag")) { title = "冲抵状态"; } else if (fieldName.equals("cws_create_date")) { title = "创建时间"; } else if (fieldName.equals("flow_begin_date")) { title = "流程开始时间"; } else if (fieldName.equals("flow_end_date")) { title = "流程结束时间"; } else { title = fd.getFieldTitle(fieldName); } formFieldObj.put("name", fieldName); formFieldObj.put("title", title); if (i == 0) { JSONObject jo = new JSONObject(); jo.put("name", fieldName); jo.put("title", title); cols.put(jo); } if (map.containsKey(fieldName)) { FormField ff = map.get(fieldName); String value = fdao.getFieldValue(fieldName); //表单值 formFieldObj.put("value", value); String type = ff.getType();// 类型描述 formFieldObj.put("type", type); } String controlText = ""; if (fieldName.startsWith("main:")) { String[] subFields = fieldName.split(":"); if (subFields.length == 3) { FormDb subfd = new FormDb(subFields[1]); com.redmoon.oa.visual.FormDAO subfdao = new com.redmoon.oa.visual.FormDAO(subfd); FormField subff = subfd.getFormField(subFields[2]); String subsql = "select id from " + subfdao.getTableName() + " where cws_id=" + id + " order by cws_order"; JdbcTemplate jt = new JdbcTemplate(); StringBuilder sb = new StringBuilder(); try { ResultIterator ri = jt.executeQuery(subsql); while (ri.hasNext()) { ResultRecord rr = (ResultRecord) ri.next(); int subid = rr.getInt(1); subfdao = new com.redmoon.oa.visual.FormDAO(subid, subfd); String subFieldValue = subfdao.getFieldValue(subFields[2]); if (subff != null && subff.getType().equals(FormField.TYPE_MACRO)) { mu = mm.getMacroCtlUnit(subff.getMacroType()); if (mu != null) { subFieldValue = mu.getIFormMacroCtl().converToHtml(request, subff, subFieldValue); } } sb.append("<span>").append(subFieldValue).append("</span>").append(ri.hasNext() ? "</br>" : ""); } } catch (Exception e) { e.printStackTrace(); } controlText = sb.toString(); } } else if (fieldName.startsWith("other:")) { controlText = com.redmoon.oa.visual.FormDAOMgr.getFieldValueOfOther(request, fdao, fieldName); } else if (fieldName.equals("ID")) { controlText = String.valueOf(fdao.getId()); } else if (fieldName.equals("cws_progress")) { controlText = String.valueOf(fdao.getCwsProgress()); } else if (fieldName.equals("cws_creator")) { String realName = ""; if (fdao.getCreator() != null) { UserDb user = um.getUserDb(fdao.getCreator()); if (user != null) { realName = user.getRealName(); } } controlText = realName; } else if (fieldName.equals("flowId")) { controlText = String.valueOf(fdao.getFlowId()); } else if (fieldName.equals("cws_status")) { controlText = com.redmoon.oa.flow.FormDAO.getStatusDesc(fdao.getCwsStatus()); } else if (fieldName.equals("cws_flag")) { controlText = com.redmoon.oa.flow.FormDAO.getCwsFlagDesc(fdao.getCwsFlag()); } else if (fieldName.equals("cws_create_date")) { controlText = DateUtil.format(fdao.getCwsCreateDate(), "yyyy-MM-dd HH:mm:ss"); } else if (fieldName.equals("flow_begin_date")) { int flowId = fdao.getFlowId(); if (flowId != -1) { wf = wf.getWorkflowDb(flowId); controlText = DateUtil.format(wf.getBeginDate(), "yyyy-MM-dd HH:mm:ss"); } } else if (fieldName.equals("flow_end_date")) { int flowId = fdao.getFlowId(); if (flowId != -1) { wf = wf.getWorkflowDb(flowId); controlText = DateUtil.format(wf.getEndDate(), "yyyy-MM-dd HH:mm:ss"); } } else { FormField ff = fdao.getFormField(fieldName); if (ff == null) { controlText = fieldName + " 已不存在!"; } else { // 隐藏 if (listHide != null && listHide.contains(ff.getName())) { continue; } if (ff.getType().equals(FormField.TYPE_MACRO)) { mu = mm.getMacroCtlUnit(ff.getMacroType()); if (mu != null) { controlText = mu.getIFormMacroCtl().converToHtml(request, ff, fdao.getFieldValue(fieldName)); } } else { controlText = FuncUtil.renderFieldValue(fdao, ff); } } } formFieldObj.put("text", controlText); fieldArr.put(formFieldObj); } dataArr.put(rowObj);//组装json数组 i++; } jResult.put(DATAS, dataArr); } } } } } jReturn.put(RESULT, jResult); } catch (JSONException e) { log.error(e.getMessage()); e.printStackTrace(); } catch (ErrMsgException e) { log.error(e.getMessage()); e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return jReturn.toString(); } /** * 获得所有字段信息 * * @return */ public HashMap<String, FormField> getFormFieldsByFromCode(String formCode) { HashMap<String, FormField> map = new HashMap<String, FormField>(); FormDb fd = new FormDb(); fd = fd.getFormDb(formCode); FormDAO fdao = new FormDAO(fd);//获得所有表单元素 Iterator fdaoIr = fdao.getFields().iterator(); while (fdaoIr != null && fdaoIr.hasNext()) { FormField ff = (FormField) fdaoIr.next(); map.put(ff.getName(), ff); } return map; } @ResponseBody @RequestMapping(value = "/module/add", produces = {"application/json;charset=UTF-8;"}) public String add(@RequestParam(defaultValue = "", required = true) String skey, String moduleCode) { // 手机客户端 —— 新增 判断 需要显示的列 JSONObject json = new JSONObject(); Privilege privilege = new Privilege(); try { boolean re = privilege.Auth(skey); if (re) { json.put("res", "-2"); json.put("msg", "时间过期"); return json.toString(); } privilege.doLogin(request, skey); if (moduleCode != null && !moduleCode.trim().equals("")) { ModuleSetupDb msd = new ModuleSetupDb(); msd = msd.getModuleSetupDb(moduleCode); String formCode = msd.getString("form_code"); FormDb fd = new FormDb(); fd = fd.getFormDb(formCode); Vector v = fd.getFields(); Vector vWritable = new Vector(); // 可写表单域(去除了隐藏字段) // 置可写表单域 String userName = privilege.getUserName(skey); ModulePrivDb mpd = new ModulePrivDb(formCode); String fieldWrite = mpd.getUserFieldsHasPriv(userName, "write"); String fieldHide = mpd.getUserFieldsHasPriv(userName, "hide"); // 将不显示的字段加入fieldHide Iterator ir = v.iterator(); while (ir.hasNext()) { FormField ff = (FormField) ir.next(); if (ff.getHide() == FormField.HIDE_EDIT || ff.getHide() == FormField.HIDE_ALWAYS) { if ("".equals(fieldHide)) { fieldHide = ff.getName(); } else { fieldHide += "," + ff.getName(); } } } String[] fdsHide = StrUtil.split(fieldHide, ","); if (!"".equals(fieldWrite)) { String[] fds = StrUtil.split(fieldWrite, ","); if (fds != null) { int len = fds.length; // 将不可写的域筛选出 ir = v.iterator(); while (ir.hasNext()) { FormField ff = (FormField) ir.next(); boolean finded = false; for (int i = 0; i < len; i++) { if (ff.getName().equals(fds[i])) { finded = true; break; } } if (finded) { vWritable.addElement(ff); // 置为不能编辑,以使得CKEditorCtl初始化时,不转变为编辑器 ff.setEditable(false); } } } // 从可写字段中去掉隐藏字段 if (fdsHide != null) { ir = vWritable.iterator(); while (ir.hasNext()) { FormField ff = (FormField) ir.next(); for (int k = 0; k < fdsHide.length; k++) { if (ff.getName().equals(fdsHide[k])) { ir.remove(); } } } } } else { // 全部可写 vWritable = v; } JSONArray fields = new JSONArray(); MacroCtlUnit mu; MacroCtlMgr mm = new MacroCtlMgr(); ir = vWritable.iterator(); json.put("res", "0"); // 遍历表单字段------------------------------------------------- while (ir.hasNext()) { FormField ff = (FormField) ir.next(); if (!ff.isMobileDisplay()) { continue; } JSONObject field = new JSONObject(); String desc = StrUtil.getNullStr(ff.getDescription()); field.put("title", ff.getTitle()); field.put("code", ff.getName()); field.put("desc", desc); // 如果是计算控件,则取出精度和四舍五入属性 if (ff.getType().equals(FormField.TYPE_CALCULATOR)) { FormParser fp = new FormParser(); String isroundto5 = fp.getFieldAttribute(fd, ff, "isroundto5"); String digit = fp.getFieldAttribute(fd, ff, "digit"); field.put("formula", ff.getDefaultValueRaw()); field.put("isroundto5", isroundto5); field.put("digit", digit); } String options = ""; String macroType = ""; String controlText = ""; String controlValue = ""; JSONArray opinionArr = null; JSONObject opinionVal = null; String macroCode = ""; String metaData = ""; JSONArray js = new JSONArray(); if (ff.getType().equals("macro")) { mu = mm.getMacroCtlUnit(ff.getMacroType()); if (mu == null) { LogUtil.getLog(getClass()).error( "MactoCtl " + ff.getTitle() + ":" + ff.getMacroType() + " is not exist."); continue; } metaData = mu.getIFormMacroCtl().getMetaData(ff); macroCode = mu.getCode(); macroType = mu.getIFormMacroCtl().getControlType(); controlText = mu.getIFormMacroCtl().getControlText( privilege.getUserName(skey), ff); controlValue = mu.getIFormMacroCtl().getControlValue( privilege.getUserName(skey), ff); options = mu.getIFormMacroCtl().getControlOptions( privilege.getUserName(skey), ff); // options = options.replaceAll("\\\"", ""); if (options != null && !options.equals("")) { // options = options.replaceAll("\\\"", ""); js = new JSONArray(options); } } else { String type = ff.getType(); if (type != null && !type.equals("")) { if (type.equals("DATE") || type.equals("DATE_TIME")) { controlValue = ff.getDefaultValueRaw(); } else { controlValue = ff.getDefaultValue(); } } else { controlValue = ff.getDefaultValue(); } } // 判断是否为意见输入框 if (macroCode != null && !macroCode.equals("")) { if (macroCode.equals("macro_opinion") || macroCode.equals("macro_opinionex")) { if (controlText != null && !controlText.trim().equals("")) { opinionArr = new JSONArray(controlText); } if (controlValue != null && !controlValue.trim().equals("")) { opinionVal = new JSONObject(controlValue); } } if (macroCode.equals("nest_sheet") || macroCode.equals("nest_table") || macroCode.equals("macro_detaillist_ctl")) { MacroCtlService macroCtlService = SpringUtil.getBean(MacroCtlService.class); INestSheetCtl nestSheetCtl = macroCtlService.getNestSheetCtl(); JSONObject jsonObj = nestSheetCtl.getCtlDescription(ff); if (jsonObj != null) { field.put("desc", jsonObj); } } else if (macroCode.equals("module_field_select")) { MacroCtlService macroCtlService = SpringUtil.getBean(MacroCtlService.class); IModuleFieldSelectCtl moduleFieldSelectCtl = macroCtlService.getModuleFieldSelectCtl(); JSONObject jsonObj = moduleFieldSelectCtl.getCtlDescription(ff); if (jsonObj != null) { field.put("desc", jsonObj); } } } field.put("type", ff.getType()); if (ff.getType().equals("select")) { // options = fp.getOptionsOfSelect(fd, ff); String[][] optionsArray = FormParser .getOptionsArrayOfSelect(fd, ff); for (int i = 0; i < optionsArray.length; i++) { String[] optionsItem = optionsArray[i]; JSONObject option = new JSONObject(); try { option.put("value", optionsItem[0]); option.put("name", optionsItem[1]); } catch (Exception e) { e.printStackTrace(); } js.put(option); } } else if (ff.getType().equals("radio")) { // options = fp.getOptionsOfSelect(fd, ff); String[] optionsArray = FormParser.getValuesOfInput(fd, ff); for (int i = 0; i < optionsArray.length; i++) { JSONObject option = new JSONObject(); option.put("value", optionsArray[i]); option.put("name", optionsArray[i]); js.put(option); } } field.put("options", js); field.put("text", controlText); String level = ""; if (ff.getType().equals("checkbox")) { // level = "个人兴趣"; level = ff.getTitle(); } field.put("level", level); field.put("macroType", macroType); field.put("editable", String.valueOf(ff.isEditable())); field.put("isNull", String.valueOf(ff.isCanNull())); field.put("fieldType", ff.getFieldTypeDesc()); if (opinionVal != null) { field.put("value", opinionVal); } else { field.put("value", controlValue); } if (opinionArr != null && opinionArr.length() > 0) { field.put("text", opinionArr); } else { field.put("text", controlText); } field.put("macroCode", macroCode); // 可传SQL控件条件中的字段 field.put("metaData", metaData); field.put("isReadonly", ff.isReadonly()); fields.put(field); } json.put("fields", fields); // 是否允许上传附件 json.put("hasAttach", fd.isHasAttachment()); return json.toString(); } else { json.put("res", "-1"); json.put("msg", "表单编码为空!"); return json.toString(); } } catch (JSONException e) { log.error(e.getMessage()); } return json.toString(); } @ResponseBody @RequestMapping(value = "/module/del", produces = {"application/json;charset=UTF-8;"}) public String del(@RequestParam(defaultValue = "", required = true) String skey, @RequestParam(required = true) String moduleCode, @RequestParam(required = true) long id) { JSONObject json = new JSONObject(); Privilege privilege = new Privilege(); boolean re = privilege.Auth(skey); if (re) { try { json.put("res", "-2"); json.put("msg", "时间过期"); return json.toString(); } catch (JSONException e) { e.printStackTrace(); } } try { FormDb fd = new FormDb(); ModuleSetupDb msd = new ModuleSetupDb(); msd = msd.getModuleSetupDb(moduleCode); String formCode = msd.getString("form_code"); fd = fd.getFormDb(formCode); FormDAO fdao = new FormDAO(fd); fdao = fdao.getFormDAO(id, fd); re = fdao.del(); if (re) { json.put("res", "0"); json.put("msg", "操作成功"); } else { json.put("res", "-1"); json.put("msg", "删除失败"); } } catch (JSONException e) { log.error(e.getMessage()); } return json.toString(); } @ResponseBody @RequestMapping(value = "/module/edit", produces = {"application/json;charset=UTF-8;"}) public String edit(@RequestParam(defaultValue = "", required = true) String skey, @RequestParam(required = true) String moduleCode, @RequestParam(required = true) long id) { JSONObject json = new JSONObject(); Privilege privilege = new Privilege(); boolean re = privilege.Auth(skey); if (re) { try { json.put("res", "-2"); json.put("msg", "时间过期"); return json.toString(); } catch (JSONException e) { e.printStackTrace(); } } privilege.doLogin(request, skey); if (moduleCode != null && !moduleCode.trim().equals("")) { JSONArray fields = new JSONArray(); MacroCtlUnit mu; MacroCtlMgr mm = new MacroCtlMgr(); try { json.put("res", "0"); ModuleSetupDb msd = new ModuleSetupDb(); msd = msd.getModuleSetupDb(moduleCode); String formCode = msd.getString("form_code"); FormDb fd = new FormDb(); fd = fd.getFormDb(formCode); Vector v = fd.getFields(); // 置可写表单域 String userName = privilege.getUserName(skey); ModulePrivDb mpd = new ModulePrivDb(formCode); String fieldWrite = mpd.getUserFieldsHasPriv(userName, "write"); if (!"".equals(fieldWrite)) { String[] fds = StrUtil.split(fieldWrite, ","); if (fds != null) { int len = fds.length; // 将不可写的域筛选出 Iterator ir = v.iterator(); while (ir.hasNext()) { FormField ff = (FormField) ir.next(); boolean finded = false; for (int i = 0; i < len; i++) { if (ff.getName().equals(fds[i])) { finded = true; break; } } if (finded) { // 置为不能编辑,以使得CKEditorCtl初始化时,不转变为编辑器 ff.setEditable(false); } } } // 去掉隐藏字段 String fieldHide = mpd.getUserFieldsHasPriv(userName, "hide"); // 将不显示的字段加入fieldHide Iterator ir = v.iterator(); while (ir.hasNext()) { FormField ff = (FormField) ir.next(); if (ff.getHide() == FormField.HIDE_EDIT || ff.getHide() == FormField.HIDE_ALWAYS) { if ("".equals(fieldHide)) { fieldHide = ff.getName(); } else { fieldHide += "," + ff.getName(); } } } String[] fdsHide = StrUtil.split(fieldHide, ","); if (fdsHide != null) { ir = v.iterator(); while (ir.hasNext()) { FormField ff = (FormField) ir.next(); for (int k = 0; k < fdsHide.length; k++) { if (ff.getName().equals(fdsHide[k])) { ir.remove(); } } } } } FormDAO fdao = new FormDAO(); fdao = fdao.getFormDAO(id, fd); Iterator ir = fdao.getFields().iterator(); while (ir.hasNext()) { FormField ff = (FormField) ir.next(); if (!ff.isMobileDisplay()) { continue; } String val = fdao.getFieldValue(ff.getName()); JSONObject field = new JSONObject(); field.put("title", ff.getTitle()); field.put("code", ff.getName()); field.put("desc", StrUtil.getNullStr(ff.getDescription())); // 如果是计算控件,则取出精度和四舍五入属性 if (ff.getType().equals(FormField.TYPE_CALCULATOR)) { FormParser fp = new FormParser(); String isroundto5 = fp.getFieldAttribute(fd, ff, "isroundto5"); String digit = fp.getFieldAttribute(fd, ff, "digit"); field.put("formula", ff.getDefaultValueRaw()); field.put("isroundto5", isroundto5); field.put("digit", digit); } String options = ""; String macroType = ""; String controlText = ""; String macroCode = ""; JSONArray js = new JSONArray(); JSONArray opinionArr = null; JSONObject opinionVal = null; String metaData = ""; if (ff.getType().equals("macro")) { mu = mm.getMacroCtlUnit(ff.getMacroType()); if (mu == null) { LogUtil.getLog(getClass()).error( "MactoCtl " + ff.getTitle() + ":" + ff.getMacroType() + " is not exist."); continue; } IFormMacroCtl ifmc = mu.getIFormMacroCtl(); ifmc.setIFormDAO(fdao); macroType = mu.getIFormMacroCtl().getControlType(); metaData = mu.getIFormMacroCtl().getMetaData(ff); macroCode = mu.getCode(); // 如果值为null,则在json中put的时候,是无效的,不会被记录至json中 controlText = StrUtil.getNullStr(mu.getIFormMacroCtl() .getControlText(privilege.getUserName(skey), ff)); val = StrUtil.getNullStr(mu.getIFormMacroCtl() .getControlValue(privilege.getUserName(skey), ff)); options = mu.getIFormMacroCtl().getControlOptions( privilege.getUserName(skey), ff); if (options != null && !"".equals(options)) { // options = options.replaceAll("\\\"", ""); js = new JSONArray(options); } } // 判断是否为意见输入框 if (macroCode != null && !"".equals(macroCode)) { if ("macro_opinion".equals(macroCode) || "macro_opinionex".equals(macroCode)) { if (controlText != null && !controlText.trim().equals("")) { opinionArr = new JSONArray(controlText); } if (val != null && !val.trim().equals("")) { opinionVal = new JSONObject(val); } } if (macroCode.equals("nest_sheet") || macroCode.equals("nest_table") || macroCode.equals("macro_detaillist_ctl")) { MacroCtlService macroCtlService = SpringUtil.getBean(MacroCtlService.class); INestSheetCtl nestSheetCtl = macroCtlService.getNestSheetCtl(); JSONObject jsonObj = nestSheetCtl.getCtlDescription(ff); if (jsonObj != null) { field.put("desc", jsonObj); } } else if (macroCode.equals("module_field_select")) { MacroCtlService macroCtlService = SpringUtil.getBean(MacroCtlService.class); IModuleFieldSelectCtl moduleFieldSelectCtl = macroCtlService.getModuleFieldSelectCtl(); JSONObject jsonObj = moduleFieldSelectCtl.getCtlDescription(ff); if (jsonObj != null) { field.put("desc", jsonObj); } } } field.put("type", ff.getType()); if ("select".equals(ff.getType())) { String[][] optionsArray = FormParser.getOptionsArrayOfSelect(fd, ff); for (int i = 0; i < optionsArray.length; i++) { String[] optionsItem = optionsArray[i]; if (optionsItem != null && optionsItem.length == 2) { JSONObject option = new JSONObject(); option.put("value", optionsItem[0]); option.put("name", optionsItem[1]); js.put(option); } } } else if (ff.getType().equals("radio")) { FormParser fp = new FormParser(); // options = fp.getOptionsOfSelect(fd, ff); String[] optionsArray = FormParser.getValuesOfInput(fd, ff); for (int i = 0; i < optionsArray.length; i++) { JSONObject option = new JSONObject(); option.put("value", optionsArray[i]); option.put("name", optionsArray[i]); js.put(option); } } String level = ""; if (ff.getType().equals("checkbox")) { // level = "个人兴趣"; level = ff.getTitle(); } field.put("options", js); if (opinionVal != null) { field.put("value", opinionVal); } else { field.put("value", val); } if (opinionArr != null && opinionArr.length() > 0) { field.put("text", opinionArr); } else { field.put("text", controlText); } // LogUtil.getLog(getClass()).info(ff.getTitle() + // " controlText=" + controlText); field.put("level", level); field.put("macroType", macroType); field.put("editable", String.valueOf(ff.isEditable())); // field.put("isHidden", String.valueOf(ff.isHidden())); // 之前已被去除 field.put("isNull", String.valueOf(ff.isCanNull())); field.put("fieldType", ff.getFieldTypeDesc()); field.put("macroCode", macroCode); // 传SQL控件条件中的字段 field.put("metaData", metaData); field.put("isReadonly", ff.isReadonly()); fields.put(field); } json.put("fields", fields); Iterator itFiles = fdao.getAttachments().iterator(); JSONArray filesArr = new JSONArray(); while (itFiles.hasNext()) { com.redmoon.oa.visual.Attachment am = (com.redmoon.oa.visual.Attachment) itFiles .next(); JSONObject fileObj = new JSONObject(); String name = am.getName(); fileObj.put("name", name); String url = "/public/visual/visual_getfile.jsp?attachId=" + am.getId(); fileObj.put("url", url); fileObj.put("id", am.getId()); fileObj.put("size", String.valueOf(am.getFileSize())); filesArr.put(fileObj); } json.put("files", filesArr); // 是否允许上传附件 json.put("hasAttach", fd.isHasAttachment()); } catch (JSONException e) { e.printStackTrace(); } } return json.toString(); } @ResponseBody @RequestMapping(value = "/module/show", produces = {"application/json;charset=UTF-8;"}) public String show(@RequestParam(defaultValue = "", required = true) String skey, @RequestParam(required = true) String moduleCode, @RequestParam(required = true) long id) { JSONObject json = new JSONObject(); Privilege privilege = new Privilege(); boolean re = privilege.Auth(skey); if (re) { try { json.put("res", "-2"); json.put("msg", "时间过期"); return json.toString(); } catch (JSONException e) { e.printStackTrace(); } } String userName = privilege.getUserName(skey); if (userName == null || "".equals(userName)) { com.redmoon.oa.pvg.Privilege pvg = new com.redmoon.oa.pvg.Privilege(); userName = pvg.getUser(request); } MacroCtlUnit mu; MacroCtlMgr mm = new MacroCtlMgr(); try { ModuleSetupDb msd = new ModuleSetupDb(); msd = msd.getModuleSetupDb(moduleCode); String formCode = msd.getString("form_code"); FormDb fd = new FormDb(); fd = fd.getFormDb(formCode); FormDAO fdao = new FormDAO(); fdao = fdao.getFormDAO(id, fd); mm = new MacroCtlMgr(); json.put("res", "0"); json.put("id", id); JSONArray fields = new JSONArray(); ModulePrivDb mpd = new ModulePrivDb(formCode); boolean isHideField = true; String fieldHide = mpd.getUserFieldsHasPriv(userName, "hide"); // 将不显示的字段加入fieldHide Iterator ir = fd.getFields().iterator(); while (ir.hasNext()) { FormField ff = (FormField) ir.next(); if (ff.getHide() == FormField.HIDE_ALWAYS) { if ("".equals(fieldHide)) { fieldHide = ff.getName(); } else { fieldHide += "," + ff.getName(); } } } String[] fdsHide = StrUtil.split(fieldHide, ","); Vector v = fdao.getFields(); ir = v.iterator(); while (ir.hasNext()) { FormField ff = (FormField) ir.next(); // 跳过隐藏域 if (isHideField) { boolean isShow = true; if (fdsHide != null) { for (int i = 0; i < fdsHide.length; i++) { if (!fdsHide[i].startsWith("nest.")) { if (fdsHide[i].equals(ff.getName())) { isShow = false; break; } } else { isShow = false; break; } } if (!isShow) { continue; } } } String val = StrUtil.getNullStr(ff.getValue()); JSONObject field = new JSONObject(); String macroCode = ""; JSONArray jsonArr = null; if (ff.getType().equals(FormField.TYPE_MACRO)) { mu = mm.getMacroCtlUnit(ff.getMacroType()); if (mu != null) { val = mu.getIFormMacroCtl().getControlText(privilege.getUserName(skey), ff); macroCode = mu.getCode(); if (macroCode != null && !macroCode.equals("")) { if (macroCode.equals("macro_opinion") || macroCode.equals("macro_opinionex")) { if (!val.equals("")) { jsonArr = new JSONArray(val); } else { jsonArr = new JSONArray(); } } if (macroCode.equals("nest_sheet") || macroCode.equals("nest_table") || macroCode.equals("macro_detaillist_ctl")) { MacroCtlService macroCtlService = SpringUtil.getBean(MacroCtlService.class); INestSheetCtl nestSheetCtl = macroCtlService.getNestSheetCtl(); JSONObject jsonObj = nestSheetCtl.getCtlDescription(ff); if (jsonObj != null) { field.put("desc", jsonObj); } else { field.put("desc", ff.getDescription()); } } else if (macroCode.equals("module_field_select")) { MacroCtlService macroCtlService = SpringUtil.getBean(MacroCtlService.class); IModuleFieldSelectCtl moduleFieldSelectCtl = macroCtlService.getModuleFieldSelectCtl(); JSONObject jsonObj = moduleFieldSelectCtl.getCtlDescription(ff); if (jsonObj != null) { field.put("desc", jsonObj); } else { field.put("desc", ff.getDescription()); } } } } } field.put("title", ff.getTitle()); field.put("code", ff.getName()); if (jsonArr != null) { field.put("value", jsonArr); } else { field.put("value", val); } field.put("type", ff.getType()); String level = ""; if (ff.getType().equals("checkbox")) { level = ff.getTitle(); } field.put("level", level); field.put("macroCode", macroCode); fields.put(field); } json.put("fields", fields); Iterator itFiles = fdao.getAttachments().iterator(); JSONArray filesArr = new JSONArray(); while (itFiles.hasNext()) { com.redmoon.oa.visual.Attachment am = (com.redmoon.oa.visual.Attachment) itFiles .next(); JSONObject fileObj = new JSONObject(); String name = am.getName(); fileObj.put("name", name); String url = "/public/visual/visual_getfile.jsp?attachId=" + am.getId(); fileObj.put("url", url); fileObj.put("id", am.getId()); fileObj.put("size", String.valueOf(am.getFileSize())); filesArr.put(fileObj); } json.put("files", filesArr); // 关联模块 FormDb fdRelated = new FormDb(); JSONArray arrRelated = new JSONArray(); ModuleRelateDb mrdTop = new ModuleRelateDb(); java.util.Iterator irTop = mrdTop.getModulesRelated(formCode).iterator(); while (irTop.hasNext()) { mrdTop = (ModuleRelateDb) irTop.next(); // 有查看权限才能看到从模块选项卡 ModulePrivDb mpdTop = new ModulePrivDb(mrdTop.getString("relate_code")); if (mpdTop.canUserSee(userName)) { String name = fdRelated.getFormDb(mrdTop.getString("relate_code")).getName(); JSONObject jsonRelated = new JSONObject(); jsonRelated.put("name", name); jsonRelated.put("formCodeRelated", mrdTop.getString("relate_code")); arrRelated.put(jsonRelated); } } json.put("formRelated", arrRelated); // 其它标签 String[] subTags = StrUtil.split(StrUtil.getNullStr(msd.getString("sub_nav_tag_name")), "\\|"); String[] subTagUrls = StrUtil.split(StrUtil.getNullStr(msd.getString("sub_nav_tag_url")), "\\|"); int subLen = 0; if (subTags != null) { subLen = subTags.length; } JSONArray subArr = new JSONArray(); for (int i = 0; i < subLen; i++) { // String uri = ModuleUtil.filterViewEditTagUrl(request, codeTop, subTagsTop[i]); String tagUrl = ModuleUtil.getModuleSubTagUrl(moduleCode, subTags[i]); if (tagUrl.startsWith("{")) { JSONObject jsonTag = new JSONObject(tagUrl); if (!jsonTag.isNull("fieldSource")) { JSONObject jsonRelated = new JSONObject(); jsonRelated.put("tagName", subTags[i]); jsonRelated.put("subTagIndex", i); // 因为传tagName用于得到配置信息时,从RelateListAction取出来时乱码(因为是中文),所以用该键值来传递信息 subArr.put(jsonRelated); continue; } } } json.put("subTags", subArr); } catch (JSONException e) { e.printStackTrace(); } return json.toString(); } @ResponseBody @RequestMapping(value = "/module/attDel", produces = {"application/json;charset=UTF-8;"}) public String attDel(@RequestParam(defaultValue = "", required = true) String skey, @RequestParam(required = true) boolean isFlow, @RequestParam(required = true) int id) { JSONObject json = new JSONObject(); Privilege privilege = new Privilege(); boolean re = privilege.Auth(skey); if (re) { try { json.put("res", "-2"); json.put("msg", "时间过期"); return json.toString(); } catch (JSONException e) { e.printStackTrace(); } } try { if (isFlow) { com.redmoon.oa.flow.Attachment att = new com.redmoon.oa.flow.Attachment(id); re = att.del(); } else { com.redmoon.oa.visual.Attachment att = new com.redmoon.oa.visual.Attachment(id); re = att.del(); } if (re) { json.put("res", "0"); json.put("msg", "操作成功"); } else { json.put("res", "-1"); json.put("msg", "删除失败"); } } catch (JSONException e) { log.error(e.getMessage()); } return json.toString(); } @ResponseBody @RequestMapping(value = "/module/listRelate", produces = {"application/json;charset=UTF-8;"}) public String listRelate(@RequestParam(defaultValue = "", required = true) String skey, @RequestParam(required = true) String moduleCode, Long parentId, String formCodeRelated, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "15") Integer pageSize, @RequestParam(defaultValue = "") String op, @RequestParam(defaultValue = "id") String orderBy, @RequestParam(defaultValue = "desc") String sort) throws JSONException { JSONObject jReturn = new JSONObject(); JSONObject jResult = new JSONObject(); if ("".equals(moduleCode)) { jResult.put(RETURNCODE, RESULT_MODULE_ERROR); return jResult.toString(); } try { ModuleSetupDb msd = new ModuleSetupDb(); msd = msd.getModuleSetupDb(moduleCode); if (msd == null) { jResult.put(RETURNCODE, RESULT_MODULE_ERROR); return jResult.toString(); } String formCode = msd.getString("form_code"); UserMgr um = new UserMgr(); Privilege privilege = new Privilege(); boolean re = privilege.Auth(skey); jReturn.put(RES, RETURNCODE_SUCCESS); //请求成功 if (re) { jResult.put(RETURNCODE, RESULT_TIME_OUT); //登录超时 } else { String userName = privilege.getUserName(skey); if (userName == null || "".equals(userName)) { com.redmoon.oa.pvg.Privilege pvg = new com.redmoon.oa.pvg.Privilege(); userName = pvg.getUser(request); } if (formCode == null || formCode.trim().equals("")) { jResult.put(RETURNCODE, RESULT_FORMCODE_ERROR); //表单为空 } else { FormDb fdMain = new FormDb(); fdMain = fdMain.getFormDb(formCode); if (!fdMain.isLoaded()) { //表单不存在 jResult.put(RETURNCODE, RESULT_FORMCODE_ERROR);//表单不存在 return jResult.toString(); } else { FormDb fdRelated = new FormDb(); try { request.setCharacterEncoding("utf-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } // 按选项卡设置中的顺序排列,从0开始 int subTagIndex = ParamUtil.getInt(request, "subTagIndex", -1); if (subTagIndex != -1) { String[] subTags = StrUtil.split(StrUtil.getNullStr(msd.getString("sub_nav_tag_name")), "\\|"); int subLen = 0; if (subTags != null) { subLen = subTags.length; } String tagName = ""; for (int i = 0; i < subLen; i++) { if (i == subTagIndex) { tagName = subTags[i]; break; } } String tagUrl = ModuleUtil.getModuleSubTagUrl(moduleCode, tagName); if (tagUrl.equals("")) { com.cloudwebsoft.framework.util.LogUtil.getLog(getClass()).error(tagName + " 不存在!"); } else { if (tagUrl.startsWith("{")) { JSONObject json = new JSONObject(tagUrl); if (!json.isNull("formRelated")) { // formCodeRelated = json.getString("formRelated"); msd = msd.getModuleSetupDb(json.getString("formRelated")); // 用于SQLBuilder中调用ModuleUtil.parseFilter时 request.setAttribute("MODULE_SETUP", msd); formCodeRelated = msd.getString("form_code"); } } } } fdRelated = fdRelated.getFormDb(formCodeRelated); MacroCtlUnit mu; MacroCtlMgr mm = new MacroCtlMgr(); FormDAO fdao = new FormDAO(); com.redmoon.oa.visual.FormDAOMgr fdm = new com.redmoon.oa.visual.FormDAOMgr(formCode); String relateFieldValue = fdm.getRelateFieldValue(parentId, formCodeRelated); if (relateFieldValue == null) { relateFieldValue = SQLBuilder.IS_NOT_RELATED; /* jReturn.put(RES,-3); jReturn.put("msg", "请检查模块是否相关联!"); setResult(jReturn.toString()); return; */ } jReturn.put(RES, 0); jReturn.put("parentId", parentId); jReturn.put("moduleCode", moduleCode); jReturn.put("formCodeRelated", formCodeRelated); // 关联模块 JSONArray arrRelated = new JSONArray(); ModuleRelateDb mrdTop = new ModuleRelateDb(); java.util.Iterator irTop = mrdTop.getModulesRelated(formCode).iterator(); while (irTop.hasNext()) { mrdTop = (ModuleRelateDb) irTop.next(); // 有查看权限才能看到从模块选项卡 ModulePrivDb mpdTop = new ModulePrivDb(mrdTop.getString("relate_code")); if (mpdTop.canUserSee(userName)) { String name = fdRelated.getFormDb(mrdTop.getString("relate_code")).getName(); JSONObject jsonRelated = new JSONObject(); jsonRelated.put("name", name); jsonRelated.put("formCodeRelated", mrdTop.getString("relate_code")); arrRelated.put(jsonRelated); } } jReturn.put("formRelated", arrRelated); ModuleSetupDb msdRelated = new ModuleSetupDb(); msdRelated = msdRelated.getModuleSetupDb(formCodeRelated); String btnName = StrUtil.getNullStr(msdRelated.getString("btn_name")); String[] btnNames = StrUtil.split(btnName, ","); String btnScript = StrUtil.getNullStr(msdRelated.getString("btn_script")); String[] btnScripts = StrUtil.split(btnScript, "#"); // 取得条件 JSONArray conditions = new JSONArray(); int len = 0; if (btnNames != null) { len = btnNames.length; for (int i = 0; i < len; i++) { if (btnScripts[i].startsWith("{")) { // System.out.println(getClass() + " " + btnScripts[i]); JSONObject jsonBtn = new JSONObject(btnScripts[i]); if (((String) jsonBtn.get("btnType")).equals("queryFields")) { String condFields = (String) jsonBtn.get("fields"); String[] fieldAry = StrUtil.split(condFields, ","); for (int j = 0; j < fieldAry.length; j++) { String fieldName = fieldAry[j]; FormField ff = fdRelated.getFormField(fieldName); if (ff == null) { continue; } String condType = (String) jsonBtn.get(fieldName); String queryValue = ParamUtil.get(request, fieldName); JSONObject jo = new JSONObject(); jo.put("fieldName", ff.getName()); jo.put("fieldTitle", ff.getTitle()); jo.put("fieldType", ff.getFieldType()); jo.put("fieldCond", condType); // 点时间、时间段或模糊、准确查询 jo.put("fieldOptions", ""); jo.put("fieldValue", queryValue); if (ff.getType().equals(FormField.TYPE_DATE) || ff.getType().equals(FormField.TYPE_DATE_TIME)) { if (condType.equals("0")) { String fDate = ParamUtil.get(request, ff.getName() + "FromDate"); String tDate = ParamUtil.get(request, ff.getName() + "ToDate"); jo.put("fromDate", fDate); jo.put("toDate", tDate); } } conditions.put(jo); } } } } } jResult.put("conditions", conditions); request.setAttribute("cwsId", String.valueOf(parentId)); // String[] ary = SQLBuilder.getModuleListSqlAndUrlStr(request, fd, op, orderBy, sort); String[] ary = SQLBuilder.getModuleListRelateSqlAndUrlStr(request, fdRelated, op, orderBy, sort, relateFieldValue); String sql = ary[0]; String listField = StrUtil.getNullStr(msdRelated.getString("list_field")); String[] formFieldArr = StrUtil.split(listField, ","); if (formFieldArr != null && formFieldArr.length > 0) { ListResult lr = fdao.listResult(formCodeRelated, sql, pageNum, pageSize); long total = lr.getTotal(); if (total == 0) { jResult.put(RETURNCODE, RESULT_NO_DATA); //没有数据 } else { jResult.put("total", total); //总页数 jResult.put(RETURNCODE, RESULT_SUCCESS); //请求成功 Iterator ir = null; Vector v = lr.getResult(); JSONArray dataArr = new JSONArray(); if (v != null) { ir = v.iterator(); } // 增加权限控制 ModulePrivDb mpd = new ModulePrivDb(formCodeRelated); boolean canAdd = mpd.canUserAppend(userName); boolean canEdit = mpd.canUserModify(userName); boolean canDel = mpd.canUserManage(userName); jResult.put("canAdd", canAdd); jResult.put("canEdit", canEdit); jResult.put("canDel", canDel); // 列名 JSONArray cols = new JSONArray(); jResult.put("cols", cols); int i = 0; HashMap<String, FormField> map = getFormFieldsByFromCode(formCode); while (ir != null && ir.hasNext()) { fdao = (FormDAO) ir.next(); long id = fdao.getId(); JSONObject rowObj = new JSONObject(); rowObj.put("id", id); rowObj.put("creator", um.getUserDb(fdao.getCreator()).getRealName()); JSONArray fieldArr = new JSONArray(); rowObj.put("fields", fieldArr); for (String fieldName : formFieldArr) { JSONObject formFieldObj = new JSONObject(); //Form表单对象 // System.out.println(ListAction.class.getName() + " fieldName=" + fieldName); String title = ""; if (fieldName.startsWith("main:")) { String[] subFields = StrUtil.split(fieldName, ":"); if (subFields.length == 3) { FormDb subfd = new FormDb(subFields[1]); title = subfd.getFieldTitle(subFields[2]); } } else if (fieldName.startsWith("other:")) { String[] otherFields = StrUtil.split(fieldName, ":"); if (otherFields.length == 5) { FormDb otherFormDb = new FormDb(otherFields[2]); title = otherFormDb.getFieldTitle(otherFields[4]); } } else if (fieldName.equals("cws_creator")) { title = "创建者"; } else if (fieldName.equals("ID")) { title = "ID"; } else if (fieldName.equals("cws_progress")) { title = "进度"; } else { title = fdRelated.getFieldTitle(fieldName); } formFieldObj.put("name", fieldName); formFieldObj.put("title", title); if (i == 0) { JSONObject jo = new JSONObject(); jo.put("name", fieldName); jo.put("title", title); cols.put(jo); } if (map.containsKey(fieldName)) { FormField ff = map.get(fieldName); String value = fdao.getFieldValue(fieldName); //表单值 formFieldObj.put("value", value); String type = ff.getType();// 类型描述 formFieldObj.put("type", type); } String controlText = ""; if (fieldName.startsWith("main:")) { String[] subFields = fieldName.split(":"); if (subFields.length == 3) { FormDb subfd = new FormDb(subFields[1]); com.redmoon.oa.visual.FormDAO subfdao = new com.redmoon.oa.visual.FormDAO(subfd); FormField subff = subfd.getFormField(subFields[2]); String subsql = "select id from " + subfdao.getTableName() + " where cws_id=" + id + " order by cws_order"; JdbcTemplate jt = new JdbcTemplate(); StringBuilder sb = new StringBuilder(); try { ResultIterator ri = jt.executeQuery(subsql); while (ri.hasNext()) { ResultRecord rr = (ResultRecord) ri.next(); int subid = rr.getInt(1); subfdao = new com.redmoon.oa.visual.FormDAO(subid, subfd); String subFieldValue = subfdao.getFieldValue(subFields[2]); if (subff != null && subff.getType().equals(FormField.TYPE_MACRO)) { mu = mm.getMacroCtlUnit(subff.getMacroType()); if (mu != null) { subFieldValue = mu.getIFormMacroCtl().converToHtml(request, subff, subFieldValue); } } sb.append("<span>").append(subFieldValue).append("</span>").append(ri.hasNext() ? "</br>" : ""); } } catch (Exception e) { e.printStackTrace(); } controlText = sb.toString(); } } else if (fieldName.startsWith("other:")) { controlText = com.redmoon.oa.visual.FormDAOMgr.getFieldValueOfOther(request, fdao, fieldName); } else if (fieldName.equals("ID")) { controlText = String.valueOf(fdao.getId()); } else if (fieldName.equals("cws_progress")) { controlText = String.valueOf(fdao.getCwsProgress()); } else if (fieldName.equals("cws_creator")) { String realName = ""; if (fdao.getCreator() != null) { UserDb user = um.getUserDb(fdao.getCreator()); if (user != null) realName = user.getRealName(); } controlText = realName; } else { FormField ff = fdao.getFormField(fieldName); if (ff == null) { controlText = fieldName + " 已不存在!"; } else { if (ff.getType().equals(FormField.TYPE_MACRO)) { mu = mm.getMacroCtlUnit(ff.getMacroType()); if (mu != null) { controlText = mu.getIFormMacroCtl().converToHtml(request, ff, fdao.getFieldValue(fieldName)); } } else { controlText = FuncUtil.renderFieldValue(fdao, ff); } } } formFieldObj.put("text", controlText); fieldArr.put(formFieldObj); } dataArr.put(rowObj);//组装json数组 i++; } jResult.put(DATAS, dataArr); } } } } } jReturn.put(RESULT, jResult); } catch (JSONException e) { log.error(e.getMessage()); } catch (ErrMsgException e) { log.error(e.getMessage()); } return jReturn.toString(); } @ResponseBody @RequestMapping(value = "/module/addRelate", produces = {"application/json;charset=UTF-8;"}) public String addRelate(@RequestParam(defaultValue = "", required = true) String skey, @RequestParam(required = true) String moduleCode, String formCodeRelated, long parentId) { // 手机客户端 —— 新增 判断 需要显示的列 JSONObject json = new JSONObject(); Privilege privilege = new Privilege(); try { boolean re = privilege.Auth(skey); if (re) { json.put("res", "-2"); json.put("msg", "时间过期"); return json.toString(); } privilege.doLogin(request, skey); if (moduleCode != null && !moduleCode.trim().equals("")) { ModuleSetupDb msd = new ModuleSetupDb(); msd = msd.getModuleSetupDb(moduleCode); String formCode = msd.getString("form_code"); FormDb fdMain = new FormDb(); fdMain = fdMain.getFormDb(formCode); com.redmoon.oa.visual.FormDAOMgr fdmMain = new com.redmoon.oa.visual.FormDAOMgr(formCode); String relateFieldValue = fdmMain.getRelateFieldValue(parentId, formCodeRelated); if (relateFieldValue == null) { json.put("res", "-3"); json.put("msg", "请检查模块是否相关联!"); return json.toString(); } json.put("res", "0"); json.put("cws_id", relateFieldValue); // 关联值 json.put("formCode", formCode); // 主表单编码 FormDb fd = new FormDb(); fd = fd.getFormDb(formCodeRelated); Vector v = fd.getFields(); Vector vWritable = new Vector(); // 可写表单域(去除了隐藏字段) // 置可写表单域 String userName = privilege.getUserName(skey); ModulePrivDb mpd = new ModulePrivDb(formCodeRelated); String fieldWrite = mpd.getUserFieldsHasPriv(userName, "write"); String fieldHide = mpd.getUserFieldsHasPriv(userName, "hide"); String[] fdsHide = StrUtil.split(fieldHide, ","); if (!"".equals(fieldWrite)) { String[] fds = StrUtil.split(fieldWrite, ","); if (fds != null) { int len = fds.length; // 将不可写的域筛选出 Iterator ir = v.iterator(); while (ir.hasNext()) { FormField ff = (FormField) ir.next(); boolean finded = false; for (int i = 0; i < len; i++) { if (ff.getName().equals(fds[i])) { finded = true; break; } } if (finded) { vWritable.addElement(ff); // 置为不能编辑,以使得CKEditorCtl初始化时,不转变为编辑器 ff.setEditable(false); } } } // 从可写字段中去掉隐藏字段 if (fdsHide != null) { Iterator ir = vWritable.iterator(); while (ir.hasNext()) { FormField ff = (FormField) ir.next(); for (int k = 0; k < fdsHide.length; k++) { if (ff.getName().equals(fdsHide[k])) { ir.remove(); } } } } } else { // 全部可写 vWritable = v; } JSONArray fields = new JSONArray(); MacroCtlUnit mu; MacroCtlMgr mm = new MacroCtlMgr(); Iterator ir = vWritable.iterator(); json.put("res", "0"); // 遍历表单字段------------------------------------------------- while (ir.hasNext()) { FormField ff = (FormField) ir.next(); if (!ff.isMobileDisplay()) { continue; } JSONObject field = new JSONObject(); String desc = StrUtil.getNullStr(ff.getDescription()); field.put("title", ff.getTitle()); field.put("code", ff.getName()); field.put("desc", desc); // 如果是计算控件,则取出精度和四舍五入属性 if (ff.getType().equals(FormField.TYPE_CALCULATOR)) { FormParser fp = new FormParser(); String isroundto5 = fp.getFieldAttribute(fd, ff, "isroundto5"); String digit = fp.getFieldAttribute(fd, ff, "digit"); field.put("formula", ff.getDefaultValueRaw()); field.put("isroundto5", isroundto5); field.put("digit", digit); } String options = ""; String macroType = ""; String controlText = ""; String controlValue = ""; JSONArray opinionArr = null; JSONObject opinionVal = null; String macroCode = ""; String metaData = ""; JSONArray js = new JSONArray(); if (ff.getType().equals("macro")) { mu = mm.getMacroCtlUnit(ff.getMacroType()); if (mu == null) { LogUtil.getLog(getClass()).error( "MactoCtl " + ff.getTitle() + ":" + ff.getMacroType() + " is not exist."); continue; } metaData = mu.getIFormMacroCtl().getMetaData(ff); macroCode = mu.getCode(); macroType = mu.getIFormMacroCtl().getControlType(); controlText = mu.getIFormMacroCtl().getControlText( privilege.getUserName(skey), ff); controlValue = mu.getIFormMacroCtl().getControlValue( privilege.getUserName(skey), ff); options = mu.getIFormMacroCtl().getControlOptions( privilege.getUserName(skey), ff); // options = options.replaceAll("\\\"", ""); if (options != null && !options.equals("")) { // options = options.replaceAll("\\\"", ""); js = new JSONArray(options); } } else { String type = ff.getType(); if (type != null && !type.equals("")) { if (type.equals("DATE") || type.equals("DATE_TIME")) { controlValue = ff.getDefaultValueRaw(); } else { controlValue = ff.getDefaultValue(); } } else { controlValue = ff.getDefaultValue(); } } // 判断是否为意见输入框 if (macroCode != null && !macroCode.equals("")) { if (macroCode.equals("macro_opinion") || macroCode.equals("macro_opinionex")) { if (controlText != null && !controlText.trim().equals("")) { opinionArr = new JSONArray(controlText); } if (controlValue != null && !controlValue.trim().equals("")) { opinionVal = new JSONObject(controlValue); } } if (macroCode.equals("nest_sheet") || macroCode.equals("nest_table") || macroCode.equals("macro_detaillist_ctl")) { MacroCtlService macroCtlService = SpringUtil.getBean(MacroCtlService.class); INestSheetCtl nestSheetCtl = macroCtlService.getNestSheetCtl(); JSONObject jsonObj = nestSheetCtl.getCtlDescription(ff); if (jsonObj != null) { field.put("desc", jsonObj); } } else if (macroCode.equals("module_field_select")) { MacroCtlService macroCtlService = SpringUtil.getBean(MacroCtlService.class); IModuleFieldSelectCtl moduleFieldSelectCtl = macroCtlService.getModuleFieldSelectCtl(); JSONObject jsonObj = moduleFieldSelectCtl.getCtlDescription(ff); if (jsonObj != null) { field.put("desc", jsonObj); } } } field.put("type", ff.getType()); if (ff.getType().equals("select")) { // options = fp.getOptionsOfSelect(fd, ff); String[][] optionsArray = FormParser .getOptionsArrayOfSelect(fd, ff); for (int i = 0; i < optionsArray.length; i++) { String[] optionsItem = optionsArray[i]; JSONObject option = new JSONObject(); try { option.put("value", optionsItem[0]); option.put("name", optionsItem[1]); } catch (Exception e) { e.printStackTrace(); } js.put(option); } } else if (ff.getType().equals("radio")) { // options = fp.getOptionsOfSelect(fd, ff); String[] optionsArray = FormParser.getValuesOfInput(fd, ff); for (int i = 0; i < optionsArray.length; i++) { JSONObject option = new JSONObject(); option.put("value", optionsArray[i]); option.put("name", optionsArray[i]); js.put(option); } } field.put("options", js); field.put("text", controlText); String level = ""; if (ff.getType().equals("checkbox")) { // level = "个人兴趣"; level = ff.getTitle(); } field.put("level", level); field.put("macroType", macroType); field.put("isNull", String.valueOf(ff.isCanNull())); field.put("fieldType", ff.getFieldTypeDesc()); if (opinionVal != null) { field.put("value", opinionVal); } else { field.put("value", controlValue); } if (opinionArr != null && opinionArr.length() > 0) { field.put("text", opinionArr); } else { field.put("text", controlText); } field.put("macroCode", macroCode); // 可传SQL控件条件中的字段 field.put("metaData", metaData); fields.put(field); } json.put("fields", fields); // 判断 是否允许上传附件 json.put("hasAttach", fd.isHasAttachment()); return json.toString(); } else { json.put("res", "-1"); json.put("msg", "表单编码为空!"); return json.toString(); } } catch (JSONException e) { log.error(e.getMessage()); } return json.toString(); } @ResponseBody @RequestMapping(value = "/module/editRelate", produces = {"application/json;charset=UTF-8;"}) public String editRelate(@RequestParam(defaultValue = "", required = true) String skey, @RequestParam(required = true) String moduleCode, String formCodeRelated, Long parentId, Long id) { JSONObject json = new JSONObject(); Privilege privilege = new Privilege(); boolean re = privilege.Auth(skey); if (re) { try { json.put("res", "-2"); json.put("msg", "时间过期"); return json.toString(); } catch (JSONException e) { e.printStackTrace(); } } String userName = privilege.getUserName(skey); if (userName == null || "".equals(userName)) { com.redmoon.oa.pvg.Privilege pvg = new com.redmoon.oa.pvg.Privilege(); userName = pvg.getUser(request); } else { privilege.doLogin(request, skey); } if (moduleCode != null && !moduleCode.trim().equals("")) { JSONArray fields = new JSONArray(); MacroCtlUnit mu; MacroCtlMgr mm = new MacroCtlMgr(); try { ModuleSetupDb msd = new ModuleSetupDb(); msd = msd.getModuleSetupDb(moduleCode); FormDb fd = new FormDb(); fd = fd.getFormDb(formCodeRelated); ModulePrivDb mpd = new ModulePrivDb(formCodeRelated); if (!mpd.canUserModify(userName)) { json.put("res", "-3"); json.put("msg", "权限非法!"); return json.toString(); } json.put("res", "0"); json.put("id", id); json.put("parentId", parentId); Vector v = fd.getFields(); // 置可写表单域 String fieldWrite = mpd.getUserFieldsHasPriv(userName, "write"); if (!"".equals(fieldWrite)) { String[] fds = StrUtil.split(fieldWrite, ","); if (fds != null) { int len = fds.length; // 将不可写的域筛选出 Iterator ir = v.iterator(); while (ir.hasNext()) { FormField ff = (FormField) ir.next(); boolean finded = false; for (int i = 0; i < len; i++) { if (ff.getName().equals(fds[i])) { finded = true; break; } } if (finded) { // 置为不能编辑,以使得CKEditorCtl初始化时,不转变为编辑器 ff.setEditable(false); } } } // 去掉隐藏字段 String fieldHide = mpd.getUserFieldsHasPriv(userName, "hide"); String[] fdsHide = StrUtil.split(fieldHide, ","); if (fdsHide != null) { Iterator ir = v.iterator(); while (ir.hasNext()) { FormField ff = (FormField) ir.next(); for (int k = 0; k < fdsHide.length; k++) { if (ff.getName().equals(fdsHide[k])) { ir.remove(); } } } } } FormDAO fdao = new FormDAO(); fdao = fdao.getFormDAO(id, fd); Iterator ir = v.iterator(); while (ir.hasNext()) { FormField ff = (FormField) ir.next(); if (!ff.isMobileDisplay()) { continue; } String val = fdao.getFieldValue(ff.getName()); JSONObject field = new JSONObject(); field.put("title", ff.getTitle()); field.put("code", ff.getName()); field.put("desc", StrUtil.getNullStr(ff.getDescription())); // 如果是计算控件,则取出精度和四舍五入属性 if (ff.getType().equals(FormField.TYPE_CALCULATOR)) { FormParser fp = new FormParser(); String isroundto5 = fp.getFieldAttribute(fd, ff, "isroundto5"); String digit = fp.getFieldAttribute(fd, ff, "digit"); field.put("formula", ff.getDefaultValueRaw()); field.put("isroundto5", isroundto5); field.put("digit", digit); } String options = ""; String macroType = ""; String controlText = ""; String macroCode = ""; JSONArray js = new JSONArray(); JSONArray opinionArr = null; JSONObject opinionVal = null; String metaData = ""; if (ff.getType().equals("macro")) { mu = mm.getMacroCtlUnit(ff.getMacroType()); if (mu == null) { LogUtil.getLog(getClass()).error( "MactoCtl " + ff.getTitle() + ":" + ff.getMacroType() + " is not exist."); continue; } macroType = mu.getIFormMacroCtl().getControlType(); metaData = mu.getIFormMacroCtl().getMetaData(ff); macroCode = mu.getCode(); // 如果值为null,则在json中put的时候,是无效的,不会被记录至json中 controlText = StrUtil.getNullStr(mu.getIFormMacroCtl() .getControlText(privilege.getUserName(skey), ff)); val = StrUtil.getNullStr(mu.getIFormMacroCtl() .getControlValue(privilege.getUserName(skey), ff)); options = mu.getIFormMacroCtl().getControlOptions( privilege.getUserName(skey), ff); if (options != null && !options.equals("")) { // options = options.replaceAll("\\\"", ""); js = new JSONArray(options); } } // 判断是否为意见输入框 if (macroCode != null && !macroCode.equals("")) { if (macroCode.equals("macro_opinion") || macroCode.equals("macro_opinionex")) { if (controlText != null && !controlText.trim().equals("")) { opinionArr = new JSONArray(controlText); } if (val != null && !val.trim().equals("")) { opinionVal = new JSONObject(val); } } if (macroCode.equals("nest_sheet") || macroCode.equals("nest_table") || macroCode.equals("macro_detaillist_ctl")) { MacroCtlService macroCtlService = SpringUtil.getBean(MacroCtlService.class); INestSheetCtl nestSheetCtl = macroCtlService.getNestSheetCtl(); JSONObject jsonObj = nestSheetCtl.getCtlDescription(ff); if (jsonObj != null) { field.put("desc", jsonObj); } } else if (macroCode.equals("module_field_select")) { MacroCtlService macroCtlService = SpringUtil.getBean(MacroCtlService.class); IModuleFieldSelectCtl moduleFieldSelectCtl = macroCtlService.getModuleFieldSelectCtl(); JSONObject jsonObj = moduleFieldSelectCtl.getCtlDescription(ff); if (jsonObj != null) { field.put("desc", jsonObj); } } } field.put("type", ff.getType()); if (ff.getType().equals("select")) { String[][] optionsArray = FormParser .getOptionsArrayOfSelect(fd, ff); for (int i = 0; i < optionsArray.length; i++) { String[] optionsItem = optionsArray[i]; if (optionsItem != null && optionsItem.length == 2) { JSONObject option = new JSONObject(); option.put("value", optionsItem[0]); option.put("name", optionsItem[1]); js.put(option); } } } else if (ff.getType().equals("radio")) { FormParser fp = new FormParser(); // options = fp.getOptionsOfSelect(fd, ff); String[] optionsArray = FormParser.getValuesOfInput(fd, ff); for (int i = 0; i < optionsArray.length; i++) { JSONObject option = new JSONObject(); option.put("value", optionsArray[i]); option.put("name", optionsArray[i]); js.put(option); } } String level = ""; if (ff.getType().equals("checkbox")) { // level = "个人兴趣"; level = ff.getTitle(); } field.put("options", js); if (opinionVal != null) { field.put("value", opinionVal); } else { field.put("value", val); } if (opinionArr != null && opinionArr.length() > 0) { field.put("text", opinionArr); } else { field.put("text", controlText); } // LogUtil.getLog(getClass()).info(ff.getTitle() + // " controlText=" + controlText); field.put("level", level); field.put("macroType", macroType); field.put("editable", String.valueOf(ff.isEditable())); field.put("isHidden", String.valueOf(ff.isHidden())); field.put("isNull", String.valueOf(ff.isCanNull())); field.put("fieldType", ff.getFieldTypeDesc()); field.put("macroCode", macroCode); // 传SQL控件条件中的字段 field.put("metaData", metaData); fields.put(field); } json.put("fields", fields); Iterator itFiles = fdao.getAttachments().iterator(); JSONArray filesArr = new JSONArray(); while (itFiles.hasNext()) { com.redmoon.oa.visual.Attachment am = (com.redmoon.oa.visual.Attachment) itFiles .next(); JSONObject fileObj = new JSONObject(); String name = am.getName(); fileObj.put("name", name); String url = "/public/visual/visual_getfile.jsp?attachId=" + am.getId(); fileObj.put("url", url); fileObj.put("id", am.getId()); fileObj.put("size", String.valueOf(am.getFileSize())); filesArr.put(fileObj); } json.put("files", filesArr); } catch (JSONException e) { e.printStackTrace(); } } return json.toString(); } @ResponseBody @RequestMapping(value = "/module/initNestSheet", produces = {"application/json;charset=UTF-8;"}) public String initNestSheet(@RequestParam(defaultValue = "", required = true) String skey, @RequestParam(required = true) String formCode, String parentFormCode, Long parentId, Integer flowId, Integer actionId, Long id) { // 手机客户端 —— 新增 判断 需要显示的列 JSONObject json = new JSONObject(); Privilege privilege = new Privilege(); try { boolean re = privilege.Auth(skey); if (re) { json.put("res", "-2"); json.put("msg", "时间过期"); return json.toString(); } ModuleSetupDb msd = new ModuleSetupDb(); msd = msd.getModuleSetupDb(formCode); if (msd == null || !msd.isLoaded()) { json.put("res", "-1"); json.put("msg", "模块不存在!"); return json.toString(); } else { formCode = msd.getString("form_code"); } privilege.doLogin(request, skey); FormDb formDb = new FormDb(formCode); if (formCode != null && !formCode.trim().equals("")) { FormDAO formDao = null; if (id != 0) { formDao = new FormDAO(id, formDb); } else { formDao = new FormDAO(formDb); } if (flowId != -1) { WorkflowActionDb wfa = new WorkflowActionDb(); wfa = wfa.getWorkflowActionDb(actionId); String fieldWrite = StrUtil.getNullString(wfa.getFieldWrite()).trim(); String[] fds = fieldWrite.split(","); int len = fds.length; int nestLen = "nest.".length(); // 将嵌套表中不可写的域筛选出 Iterator ir = formDao.getFields().iterator(); while (ir.hasNext()) { FormField ff = (FormField) ir.next(); boolean finded = false; for (int i = 0; i < len; i++) { // 如果不是嵌套表格2的可写表单域 if (!fds[i].startsWith("nest.")) { continue; } String fName = fds[i].substring(nestLen); if (ff.getName().equals(fName)) { finded = true; break; } } if (!finded) { // 置为不能编辑,以使得CKEditorCtl初始化时,不转变为编辑器 ff.setEditable(false); } } } else { Vector v = formDb.getFields(); // 置可写表单域 String userName = privilege.getUserName(skey); ModulePrivDb mpd = new ModulePrivDb(formCode); String fieldWrite = mpd.getUserFieldsHasPriv(userName, "write"); if (!"".equals(fieldWrite)) { String[] fds = StrUtil.split(fieldWrite, ","); if (fds != null) { int len = fds.length; // 将不可写的域筛选出 Iterator ir = v.iterator(); while (ir.hasNext()) { FormField ff = (FormField) ir.next(); boolean finded = false; for (int i = 0; i < len; i++) { if (ff.getName().equals(fds[i])) { finded = true; break; } } if (finded) { // 置为不能编辑,以使得CKEditorCtl初始化时,不转变为编辑器 ff.setEditable(false); } } } } } MacroCtlMgr macroCtrlMgr = new MacroCtlMgr(); MacroCtlUnit macroCtrlUnit = null; Iterator it = formDao.getFields().iterator(); JSONArray fieldsArr = new JSONArray(); while (it.hasNext()) { FormField ff = (FormField) it.next(); JSONObject field = new JSONObject();// json field if (ff.isMobileDisplay() && ff.getHide() == FormField.HIDE_NONE) { field.put("title", ff.getTitle());// 标题 field.put("isCanNull", ff.isCanNull());// 标题 field.put("code", ff.getName());// 名称 field.put("desc", ff.getDefaultValueRaw()); // field.put("editable",true);//控件是否显示 // field.put("isHidden",false);//是否隐藏 String type = ff.getType();// 类型描述 field.put("type", type); // 如果是计算控件,则取出精度和四舍五入属性 if (ff.getType().equals(FormField.TYPE_CALCULATOR)) { FormParser fp = new FormParser(); String isroundto5 = fp.getFieldAttribute(formDao.getFormDb(), ff, "isroundto5"); String digit = fp.getFieldAttribute(formDao.getFormDb(), ff, "digit"); field.put("formula", ff.getDefaultValueRaw()); field.put("isroundto5", isroundto5); field.put("digit", digit); } String metaData = ""; // 判断是否是宏控件类型 if (type.equals("macro")) { String macroCode = ff.getMacroType(); field.put("macroCode", macroCode);// 宏控件的code macroCtrlUnit = macroCtrlMgr .getMacroCtlUnit(macroCode); metaData = macroCtrlUnit.getIFormMacroCtl().getMetaData(ff); String macroType = macroCtrlUnit.getIFormMacroCtl() .getControlType(); field.put("macroType", macroType);// 宏控件类型 String controlText = StrUtil .getNullStr(macroCtrlUnit .getIFormMacroCtl() .getControlText( privilege .getUserName(skey), ff)); String controlValue = StrUtil .getNullStr(macroCtrlUnit .getIFormMacroCtl() .getControlValue( privilege .getUserName(skey), ff)); field.put("text", controlText);// 文本 field.put("value", controlValue);// 显示的值 if (macroType.equals("select") || macroType.equals("buttonSelect")) { // 一般options只有在拉框中显示 String options = StrUtil .getNullStr(macroCtrlUnit .getIFormMacroCtl() .getControlOptions( privilege .getUserName(skey), ff)); if (options != null && !options.trim().equals("")) { JSONArray opinionArr = new JSONArray( options); field.put("options", opinionArr); } } else { JSONArray opinionArr = new JSONArray(); field.put("options", opinionArr); } } else { String value = StrUtil.getNullStr(ff.getValue()); if (value.equals("")) { value = ff.getDefaultValue(); } if (type.equals("DATE") || type.equals("DATE_TIME")) { if (id != 0) { field.put("value", ff.getValue()); } else { field.put("value", ff.getDefaultValueRaw()); } } else if (type.equals("select")) {// 解析普通控件中 // select控件 String[][] optionsArray = FormParser .getOptionsArrayOfSelect(formDb, ff); if (optionsArray != null && optionsArray.length > 0) { JSONArray options = new JSONArray(); for (String[] option : optionsArray) { JSONObject optionObj = new JSONObject(); if (value.equals(option[0])) { field.put("text", option[1]); field.put("value", value); } optionObj.put("value", option[0]); optionObj.put("name", option[1]); options.put(optionObj); } field.put("options", options); } } else { field.put("value", value); } } // 可传SQL控件条件中的字段 field.put("metaData", metaData); } field.put("isEditable", ff.isEditable()); fieldsArr.put(field); } json.put("fields", fieldsArr); json.put("formCode", formCode); json.put("res", "0"); json.put("msg", "操作成功"); if (flowId != -1) { FormDb flowFd = new FormDb(); flowFd = flowFd.getFormDb(parentFormCode); com.redmoon.oa.flow.FormDAO fdaoFlow = new com.redmoon.oa.flow.FormDAO(); fdaoFlow = fdaoFlow.getFormDAO(flowId, flowFd); parentId = fdaoFlow.getId(); com.redmoon.oa.visual.FormDAOMgr fdm = new com.redmoon.oa.visual.FormDAOMgr(parentFormCode); String relateFieldValue = fdm.getRelateFieldValue(parentId, formCode); json.put("cws_id", relateFieldValue); } else { json.put("cws_id", String.valueOf(parentId)); } return json.toString(); } else { json.put("res", "-1"); json.put("msg", "表单编码为空!"); return json.toString(); } } catch (JSONException e) { e.printStackTrace(); log.error(e.getMessage()); } return json.toString(); } @ResponseBody @RequestMapping(value = "/module/delNestSheet", produces = {"application/json;charset=UTF-8;"}) public String delNestSheet(@RequestParam(defaultValue = "", required = true) String skey, @RequestParam(required = true) String formCode, String formCodeRelated, @RequestParam(required = true) Long id) { JSONObject json = new JSONObject(); Privilege privilege = new Privilege(); boolean re = privilege.Auth(skey); if (re) { try { json.put("res", "-2"); json.put("msg", "时间过期"); return json.toString(); } catch (JSONException e) { e.printStackTrace(); } } privilege.doLogin(request, skey); try { if (id == -1) { json.put("res", "-1"); json.put("msg", "缺少ID!"); return json.toString(); } FormMgr fm = new FormMgr(); FormDb fdRelated = fm.getFormDb(formCodeRelated); com.redmoon.oa.visual.FormDAOMgr fdm = new com.redmoon.oa.visual.FormDAOMgr(fdRelated); String cwsId = ""; boolean isNestSheet = true; try { FormDAO fdao = new FormDAO(); fdao = fdao.getFormDAO(id, fdRelated); cwsId = fdao.getCwsId(); re = fdm.del(request, isNestSheet, formCodeRelated); } catch (ErrMsgException e) { // TODO Auto-generated catch block e.printStackTrace(); json.put("res", "-1"); json.put("msg", e.getMessage()); return json.toString(); } if (re) { json.put("res", "0"); json.put("msg", "操作成功!"); FormDb pfd = new FormDb(); pfd = pfd.getFormDb(formCode); json.put("sums", FormUtil.getSums(fdRelated, pfd, cwsId)); } else { json.put("res", "-1"); json.put("msg", "操作失败!"); } } catch (JSONException e) { log.error(e.getMessage()); } return json.toString(); } }
Python
UTF-8
27,967
2.828125
3
[ "MIT" ]
permissive
import numpy as np from el_geometry import get_extrema_2loops,get_length_c, three_points_to_circle, define_perpendicular_bisector, get_distance_from_line_to_point, get_line_point_nearest2point, two_points_to_line from math import sin, cos ,sqrt, fabs, atan, tan import imagetools import aplpy from scipy.optimize import fmin import itertools as it import time def filamentation(image, method="medium",alpha=1,near_distance=(sqrt(2)/2), max_level=1000, use_extremes=True): """ Function to perform the mediatrix decomposition method on a given object. Input: - image_name <str> : the image file name. - image_dir <str> : the image directory. If it is on the same directory, directory=''. - method <string> : possible values are 'medium' or 'brightest'. - alpha <float> : the factor alpha=l_i/w to stop the bisection. - near_distance <float> : the distance to consider a point near to the perpendicular bisector. Output: - <dic> : Dictionary structure. Each list item is a dictionary with information of corresponding to a mediatrix vector. The keys are 'theta' for the angle with x axis, 'linear_coefficient' for the linear coefficient from the line in the vector direction, 'origin' the point (x,y) of the vector origin, 'end' the point (x,y) of the vector, 'modulus' for vector modulus. The first item from the list has two extra keys 'id' wich contains the image_name and 'center' that keeps the objet center defined by the first mediatrix point in the first mediatrix level. """ #image,hdr = getdata(image_dir+image_name, header = True ) pixels=np.where(image>0) E1,E2=get_extrema_2loops(pixels[0], pixels[1], 0 ) Area=len(pixels[1]) p1=pixels[0][E1]+pixels[1][E1]*1j # the extreme points p_1 and p_2 p2=pixels[0][E2]+pixels[1][E2]*1j keydots=[p1,p2] key_center=[p1,p2] key_center=find_keydots_c(p1,p2,pixels,image,key_center,Area, method=method,alpha=0,near_distance=near_distance,max_level=1,level=0) keydots=find_keydots_c(p1,p2,pixels,image,keydots,Area, method=method,alpha=alpha,near_distance=near_distance,max_level=max_level,level=0) L=get_length_c(keydots) if use_extremes==False: if len(keydots)>3: keydots.remove(p1) keydots.remove(p2) else: print "Impossible to reject extremes, too few points" mediatrix_vectors=find_mediatrix_vectors_c(keydots) if len(key_center)>2: mediatrix_vectors['center']=key_center[1] else: medium=int(float(len(keydots))/2) mediatrix_vectors['center']=keydots[medium] W=(len(pixels[0]))/(atan(1)*L) mediatrix_vectors['L/W']=L/W mediatrix_vectors['L']=L p1_vec=[pixels[0][E1],pixels[1][E1]] # the extreme points p_1 and p_2 p2_vec=[pixels[0][E2],pixels[1][E2]] p3_vec=[mediatrix_vectors['center'].real,mediatrix_vectors['center'].imag] x_c,y_c,r=three_points_to_circle(p1_vec,p3_vec,p2_vec) circle_center=x_c+y_c*1j mediatrix_vectors['circle_params']=[circle_center,p1,p2] return mediatrix_vectors def find_keydots_c(p1,p2,image_pixels,image,keydots,area, method="medium",alpha=1,near_distance=(sqrt(2)/2),max_level=1000,level=0): """ Function to calculate the keydots Points in Mediatrix Decomposition. Input: - p1 <array> : coordinates (x,y) of the first extreme point. - p2 <array> : coordinates (x,y) of the second extreme point. - image_pixels <list> : list of points coordidates fitting the object. - image <array> : the image matrix. - keydots <array> : list with the two p_i extreme points and p_i=[p_i_x,p_i_y]. - area <array> : the object area. - method <string> : possible values are 'medium' or 'brightest'. - alpha <float> : the factor alpha=l_i/w. - near_distance <float> : the distance to consider a point near to the perpendicular bisector. Output: - <array> : list with the keydots points. """ level=level+1 if (p1 in keydots) and (p2 in keydots): index1=keydots.index(p1) index2=keydots.index(p2) if index1>index2: indexNext=index1 else: indexNext=index2 elif (p1 in keydots): indexNext=keydots.index(p1) elif (p1 in keydots): indexNext=keydots.index(p2) else: return keydots dl=abs(p1-p2) L=get_length_c(keydots) W=width_ellipse(L,area) if dl>(alpha*W) and len(keydots)<100 and level<=max_level: p1_r=[p1.real,p1.imag] p2_r=[p2.real,p2.imag] coefficients=define_perpendicular_bisector(p1_r,p2_r) p3,p3Flag=choose_near_point_c_vec(coefficients[0],coefficients[1],image_pixels,image,method,near_distance) if (p3Flag==0): if level==1: px=p3.real py=p3.imag test_points2=np.array([[px-1,py+1],[px,py+1],[px+1,py+1],[px-1,py],[px,py],[px+1,py],[px-1,py-1],[px,py-1],[px+1,py-1]]) Ds=np.apply_along_axis(get_distance_from_line_to_point,1,test_points2,theta=coefficients[0],c=coefficients[1]) Ds=np.array(Ds) if (not(p3 in keydots)): keydots.insert(indexNext,p3) keydots=find_keydots_c(p1,p3,image_pixels,image,keydots,area, method,alpha,near_distance,max_level,level) keydots=find_keydots_c(p3,p2,image_pixels,image,keydots,area, method,alpha,near_distance,max_level,level) else: pmed=(p1+p2)/2. if p1 in keydots: keydots=find_keydots_c(p1,pmed,image_pixels,image,keydots,area, method,alpha,near_distance,max_level,level) if p2 in keydots: keydots=find_keydots_c(pmed,p2,image_pixels,image,keydots,area, method,alpha,near_distance, max_level,level) return keydots def find_mediatrix_vectors_c(points): """ From a given set of points, this function returns the mediatrix decomposition vector between those points. Input: - points <list> : list of p_i points where p_i=(x_i,y_i). Output: - <list> : a list of dictionary structure. Each list item is a dictionary with information of corresponding to a mediatrix vector. The keys are 'theta' for the angle with x axis, 'linear_coefficient' for the linear coefficient from the line in the vector direction, 'origin' the point (x,y) of the vector origin, 'end' the point (x,y) of the vector, 'modulus' for vector modulus. """ mediatrix_vectors= {'origin': [] , 'end': [], } vectors=[] p1_r=[points[0].real,points[0].imag] p2_r=[points[len(points)-1].real,points[len(points)-1].imag] theta_ext,c_ext=two_points_to_line(p1_r,p2_r) for t in range(0,len(points)-1): p1_r=[points[t].real,points[t].imag] p2_r=[points[t+1].real,points[t+1].imag] coefficients=define_perpendicular_bisector(p1_r,p2_r) origin=(points[t]+points[t+1])/2. modulus=abs(points[t]-points[t+1]) if(coefficients[0]!=2*atan(1)): end1=origin + modulus*(cos(coefficients[0]))+modulus*(sin(coefficients[0]))*1j end2=origin - modulus*(cos(coefficients[0]))-modulus*(sin(coefficients[0]))*1j else: end1=origin+modulus*1j end2=origin-modulus*1j end1_r=[end1.real,end1.imag] end2_r=[end2.real,end2.imag] Dend1=get_distance_from_line_to_point(end1_r,theta_ext,c_ext) Dend2=get_distance_from_line_to_point(end2_r,theta_ext,c_ext) if Dend1<Dend2: end=end1 else: end=end2 mediatrix_vectors['origin'].append(origin) mediatrix_vectors['end'].append(end) return mediatrix_vectors def choose_near_point_c_vec(theta,c,object_pixels,image,method,near_distance): FlagErr=0 chosenX=0 chosenY=0 test_points=np.array(np.transpose(object_pixels)) Ds=np.apply_along_axis(get_distance_from_line_to_point,1,test_points,theta=theta,c=c) Ds=np.array(Ds) near_index=np.where(Ds<=near_distance) if len(near_index[0])==0: FlagErr=1 else: Ds=Ds[near_index] near_points=test_points[near_index] near_points=np.transpose(near_points) object_pixels_near=tuple((near_points[0],near_points[1])) if method=='brightest' and FlagErr==0: brights=image[object_pixels_near] index_chosen_arr=np.where(brights==np.max(brights)) index_chosen=index_chosen_arr[0][0] chosenX=float(object_pixels_near[0][index_chosen]) chosenY=float(object_pixels_near[1][index_chosen]) elif method=='brightestinline' and FlagErr==0: brights=image[object_pixels_near] index_chosen_arr=np.where(brights==np.max(brights)) index_chosen=index_chosen_arr[0][0] X_aux=float(object_pixels_near[0][index_chosen]) Y_aux=float(object_pixels_near[1][index_chosen]) chosenX,chosenY=get_line_point_nearest2point([X_aux,Y_aux],theta=theta,c=c) elif method=='medium' and FlagErr==0: i,j=get_extrema_2loops( near_points[0], near_points[1], 0 ) chosenX=float(near_points[0][i]+near_points[0][j])/2. chosenY=float(near_points[1][i]+near_points[1][j])/2. else: FlagErr=1 return chosenX+chosenY*1j,FlagErr def eval_med_stats(mediatrix_data,obj_stamp, sigma_out=True,sigma=1,sigma_pre=0.5,Area_out=True): """ Function to calculate the S estatistic measurements. Input: - mediatrix_data <list> : a list of dictionary structure. Each list item is a dictionary with information corresponding to a mediatrix vector. The keys are 'theta' for the angle with x axis, 'linear_coefficient' for the linear coefficient from the line in the vector direction, 'origin' the point (x,y) of the vector origin, 'end' the point (x,y) of the vector, 'modulus' for vector modulus. The first item from the list has an extra key 'id' wich contains the image file name. It is the output from Mediatrix_Decomposition. Output: - <dic> : dictionary with the S statistic measurements. The keys are """ guess=[mediatrix_data['center'].real,mediatrix_data['center'].imag] L=0 theta=[] linear=[] L=mediatrix_data['L'] for i in range(0,len(mediatrix_data['origin'])): origin=mediatrix_data['origin'][i] end=mediatrix_data['end'][i] delta=end-origin if delta.real!=0: a=float((delta.imag ))/delta.real theta.append(atan(a)) b=end.imag-a*(end.real) linear.append(b) else: theta.append(2*atan(1)) linear.append(end.imag-origin.imag) minM_r=fmin(M_function,guess,args=(theta,linear),maxiter=1000, disp=0) minM_val=M_function(minM_r,theta,linear) minM=minM_r[0]+minM_r[1]*1j S_output={'center_MinM': minM} R=abs(mediatrix_data['center']-minM) circle_center=mediatrix_data['circle_params'][0] center_comparison=abs(circle_center-minM) alpha=Find_angle_from_circle_section_c(mediatrix_data['circle_params'][0],mediatrix_data['circle_params'][1],mediatrix_data['circle_params'][2]) try: S_output['MinM_norm']=minM_val/(L*L) except: print " Impossible to define a lenght "#for "+str(mediatrix_data['id']) S_output['MinM_norm']=-1 if R!=0: S_output['L/R']=L/R else: print "Impossible to define a radius and curvature"# for "+str(mediatrix_data['id']) S_output['L/R']=-1 if R!=0 and alpha!=0: S_output['curvature_comparison']=(L/R)/alpha else: print "Impossible to compare curvature from circle section and mediatrix S"# for "+str(mediatrix_data['id']) S_output['curvature_comparison']=-1 try: S_output['center_comparison']=center_comparison/L except: print "Impossible to compare center from circle method and mediatrix S"# for "+str(mediatrix_data['id']) S_output['curvature_comparison']=-1 if sigma_out==True: search=np.array([]) rc_center=minM sigma_points=[] step=sigma_pre lim=step sigma_points=find_rc_region_c(sigma_points,rc_center,step,lim=lim,theta=theta,linear=linear,minM=minM_val,sigma=sigma) sigma_points=np.array(sigma_points) sigma_points=np.unique(np.round(sigma_points.real,0)+np.round(sigma_points.imag,0)*1j) E1,E2=get_extrema_2loops(sigma_points.real, sigma_points.imag, 0 ) Extreme=[sigma_points[E1],sigma_points[E2]] sigma_lenght=get_length_c(Extreme) try: S_output['sigma_lenght']=(sigma_lenght)/L except: print "Impossible to define sigma_lenght for "+str(mediatrix_data['id']) sigma_minor_axis=len(sigma_points)/(4*atan(1)*sigma_lenght) try: S_output['sigma_exc']=(sigma_lenght)/sigma_minor_axis except: print "Impossible to define sigma_exc for "+str(mediatrix_data['id']) if Area_out==True: pixels=np.where(obj_stamp>0) pixels_c=np.array(pixels[0]+pixels[1]*1j) intersection_points=np.intersect1d(pixels_c,sigma_points) S_output['intersection']=len(intersection_points) return S_output def M_function(p,theta,b): M=0 for i in range(0,len(theta)): aux=get_distance_from_line_to_point(p,theta[i],b[i]) M=M+(aux*aux) M=M/float(len(theta)) return M def M_function_c(p,theta,b): M=0 for i in range(0,len(theta)): D=0 if(theta[i]!=2*atan(1)) and (theta[i]!=0.): a=tan(theta[i]) m=-1./a c=p.imag-m*p.real x=(b[i]-c)/(m-a) y=a*x+b[i] p_line=x+y*1j D=abs(p-p_line) elif (theta[i]==2*atan(1)): # case of the perpendicular bisector is a vertical line a-->inf. D=abs(p.real-b[i]) elif theta[i]==0.: # case of the perpendicular bisector is a horizontal line a-->0 D=abs(p.imag-b[i]) #print D M+=(D*D) M=M/float(len(theta)) return M def Find_angle_from_circle_section_c(circle_center,circle_point1,circle_point2): m_point=(circle_point1+circle_point2)/2 delta_adjacent=abs(m_point-circle_center) delta_opposite=abs(circle_point1-circle_center) alpha=atan(delta_opposite/delta_adjacent) alpha=2*alpha return alpha def find_rc_region_c(region,center,step,lim,theta,linear,minM,sigma): nex_level=0 ini_region=len(region) X_search=np.arange(round(center.real,2)-lim, round(center.real,2)+lim,step) Y_search=np.arange(round(center.imag,2)-lim, round(center.imag,2)+lim,step) search=np.array([]) len_search=0 piece=np.repeat(X_search[0],len(Y_search))+Y_search*1j search=np.concatenate((piece,search),axis=0) len_search+=len(piece) piece=np.repeat(X_search[-1],len(Y_search))+Y_search*1j search=np.concatenate((piece,search),axis=0) len_search+=len(piece) piece=X_search+np.repeat(Y_search[0],len(X_search))*1j search=np.concatenate((piece,search),axis=0) len_search+=len(piece) piece=X_search+np.repeat(Y_search[-1],len(X_search))*1j search=np.concatenate((piece,search),axis=0) len_search+=len(piece) search=np.reshape(search,len_search) m_values_c=np.apply_along_axis(M_function_c,0,search,theta,linear) m_values_c=m_values_c- np.repeat(minM,len(search)) for i in range(0,len(search)): if m_values_c[i]<=sigma: region.append(search[i]) if len(region)>ini_region and len(region) < 2000: region=find_rc_region_c(region,center,step,lim+step,theta,linear,minM,sigma) return region def plot_med_stats_apl(image_name,_id='',keydots=False,circle=False,rc=True, save=True,out_image='', args={},use_extremes=True): # FIXME to work in world coord==true """ Function to make plot of S estatistic interesting measurements. Input: - mediatrix_data <dic> : the output from mediatrix decomposition. Output: - <bool> : """ opt={'increase': 2, 'relative_increase': True,'connected': False,'object_centered':True, 'out_type':'cutout', 'pmin':0.25 , 'pmax':99.75 , 'invert':True ,'out_title': 'Mediatrix Method', 'keys_color': "r" ,'alpha': 1 ,'max_level': 1000, 'near_distance': sqrt(2)/2, 'max_level': 1000, 'method':"brightest",'sigma':1,'sigma_pre':0.5, 'rc_color': 'm', 'world_coord': 'False'} opt.update(args) if out_image=='' and type(image_name)==type('str'): out_image=image_name.replace(".fits","")+"_mediatrixS_plot.png" else: out_image="mediatrixS_plot.png" mediatrix_plot,mediatrix_data,image_ps=plot_mediatrixapl(image_name,_id=_id, keydots=keydots,circle=circle, save=False, args=opt,use_extremes=use_extremes) guess=[mediatrix_data['center'].real,mediatrix_data['center'].imag] Length=0 theta=[] linear=[] for i in range(0,len(mediatrix_data['origin'])): origin_x=mediatrix_data['origin'][i].real origin_y=mediatrix_data['origin'][i].imag end_x=mediatrix_data['end'][i].real end_y=mediatrix_data['end'][i].imag Length_aux=(origin_x - end_x)**2 + (origin_y - end_y)**2 Length=Length+ sqrt(Length_aux) delta_x=float((end_x-origin_x )) if delta_x!=0: a=float((end_y-origin_y ))/delta_x theta.append(atan(a)) b=end_y-a*(end_x) linear.append(b) else: theta.append(2*atan(1)) linear.append(end_y-origin_y) MinM=fmin(M_function,guess,args=(theta,linear),maxiter=1000, disp=0) MinM_val=M_function(MinM,theta,linear) MinM_plot_X=[MinM[0],MinM[0]] MinM_plot_Y=[MinM[1],MinM[1]] mediatrix_plot.show_markers(MinM_plot_Y,MinM_plot_X,c='red',marker='.',zorder=2000) lim=round((float(Length)/2.)+5,2) sigma_X=[] sigma_Y=[] ps=[] Ms=[] pixels=np.where(image_ps>0) if rc==True: X_search=arange(round(MinM[0],2)-lim, round(MinM[0],2)+lim,opt['sigma_pre']*1) Y_search=arange(round(MinM[1],2)-lim, round(MinM[1],2)+lim,opt['sigma_pre']*1) search_aux=[X_search,Y_search] test_points=np.array(list(it.product(*search_aux))) sigma=np.apply_along_axis(M_function,1,test_points, theta=theta,b=linear) sigma=np.array(sigma) sigma=sigma-MinM_val cr_index=np.where(sigma<1) sigma=sigma[cr_index] cr_points=test_points[cr_index] for k in range(0,len(cr_points)): p=cr_points[k] mediatrix_plot.show_markers(p[1],p[0],c=opt['rc_color'],marker=".",linewidths='0', zorder=999) if save==True: savefig(out_image) return True else: size0=abs(max(pixels[0])-min(pixels[0])) size1=abs(max(pixels[1])-min(pixels[1])) return mediatrix_plot, [mediatrix_data['center'].real,mediatrix_data['center'].imag], [MinM[0],MinM[1]],[size0,size1] def plot_mediatrixapl(image_name,_id='', keydots=False,circle=True, save=True, out_image='', args={},use_extremes=True): """ Make a plot presenting the object, keydots and mediatrix vectors. If the input image name is not a postage stamp the code will read from the sextractor segmentation image the object position with given id and pixels intensity from sextractor objects image. The function assumes that the segmentation and objects images names are *original_image_name*_seg.fits and *original_image_name*_obj.fits respectively. Input: - mediatrix_data <list> : the output from mediatrix_decomposition_on_matrix. - image_dir <str> : the image directory. If it is on the same directory, directory=''. - keydots <bool> : 'True' if you want to display the keydots and 'False' if you do not. - colors <dic> : set the plot colors. The possible keys are 'object', 'vector' and 'keydots'. - type <str> : cutout or object Output: <bool> """ opt={'increase': 2, 'relative_increase': True,'connected': False,'object_centered':True, 'out_type':'cutout', 'vmin':0 , 'invert':True ,'out_title': 'Mediatrix Decomposition', 'keys_color': "r" ,'alpha': 1 ,'max_level': 1000, 'near_distance': sqrt(2)/2, 'max_level': 1000, 'method':"brightest", 'world_coord': 'False', 'circle_radius': False, 'bkg_img': ''} opt.update(args) if opt['out_type']=='cutout': opt['object_centered']=False type_arg=type(image_name) is str if type_arg: if out_image=='': out_image=image_name.replace(".fits","")+"_mediatrix_plot.png" if _id=='': image_ps,hdr=fits.getdata(image_name, header = True ) else: test_string=image_name.rstrip(".jpg") test_string=test_string.rstrip(".png") test_string=test_string.rstrip(".jpeg") test_string=test_string.rstrip(".tiff") test_string=test_string.rstrip(".gif") if test_string== image_file: image_segname=image_name.replace(".fits","")+"_seg.fits" image_objname=image_name.replace(".fits","")+"_obj.fits" image_seg,hdr = fits.getdata(image_segname, header = True ) image_obj = fits.getdata(image_objname, header = False ) image_ps,hdr=imagetools.segstamp(segimg=image_seg, objID=_id, objimg=image_obj, hdr=hdr, increase=opt['increase'], relative_increase=opt['relative_increase'], connected=opt['connected'], obj_centered=opt['object_centered']) del image_seg del image_obj gc.collect() image_name_ps=image_name.replace(".fits","")+"_ps.fits" if opt['world_coord']=='True': fits.writeto(image_name_ps,image_ps.astype(float),header=hdr) else: original_img=cv2.imread('testimg.jpg')[:,:,0] hdr=None else: image_ps=image_name.copy() if out_image=='': time_id=time.time() out_image=str(time_id)+"_mediatrix_plot.png" mediatrix_data=filamentation(image_ps, method=opt['method'],alpha=opt['alpha'],near_distance=opt['near_distance'],max_level=opt['max_level'], use_extremes=use_extremes) if opt['bkg_img']!='': img,hdr=fits.getdata(opt['bkg_img'], header = True ) else: img=image_ps.copy() IDtime=str(time.time()) pixels=np.where(image_ps>0) if opt['world_coord']=='True': if opt['out_type']=='cutout': FitsPlot = aplpy.FITSFigure(image_name) else: FitsPlot = aplpy.FITSFigure(image_name_ps) #FIXME os.system(" rm "+image_name_ps) else: FitsPlot = aplpy.FITSFigure(img) smallest = np.amin(img) biggest = np.amax(img) if 'vmax' in opt.keys(): if opt['vmax']=='Max': opt['vmax']=biggest if opt['vmin']=='Min': opt['vmin']=smallest FitsPlot.show_grayscale(vmin=opt['vmin'], vmax=opt['vmax'],invert=opt['invert']) else: if ('pmax' in opt.keys()) and ('pmin' in opt.keys()): FitsPlot.show_grayscale(pmin=opt['pmin'], pmax=opt['pmax'],invert=opt['invert']) else: FitsPlot.show_grayscale(invert=opt['invert']) Length=0 if keydots==True: pixels=np.array(pixels) E1,E2=get_extrema_2loops(pixels[0], pixels[1], 0 ) Area=len(pixels[1]) p1=pixels[0][E1]+ pixels[1][E1]*1j # the extreme points p_1 and p_2 p2=pixels[0][E2]+ pixels[1][E2]*1j keydots=[p1,p2] keydots=find_keydots_c(p1,p2,pixels,image_ps,keydots,Area, method=opt['method'],alpha=opt['alpha'],near_distance=opt['near_distance'],max_level=opt['max_level']) if use_extremes==False: if len(keydots)>3: keydots.remove(p1) keydots.remove(p2) else: print "Impossible to reject extremes, too few points" keyX=[] keyY=[] if opt['world_coord']=='True': for j in range(0,len(keydots)): keyX_aux,keyY_aux=FitsPlot.pixel2world(keydots[j].real,keydots[j].imag) keyX.append(keyX_aux) keyY.append(keyY_aux) else: for j in range(0,len(keydots)): keyX.append(keydots[j].real+1) #due to the image origin is at 1,1 not 0,0 like the matrix coordinates keyY.append(keydots[j].imag+1) FitsPlot.show_markers(keyY,keyX,c=opt['keys_color'],marker='.',zorder=500) if circle==True: if keydots==False: E1,E2=get_extrema_2loops(pixels[0], pixels[1], 0 ) x_circ=[pixels[0][E1]+1,mediatrix_data['center'].real+1,pixels[0][E2]+1] #due to the image origin is at 1,1 not 0,0 like the matrix coordinates y_circ=[pixels[1][E1]+1,mediatrix_data['center'].imag+1,pixels[1][E2]+1] #due to the image origin is at 1,1 not 0,0 like the matrix coordinates FitsPlot.show_markers(y_circ,x_circ,c='g',marker='D',zorder=500) p1_vec=[pixels[0][E1],pixels[1][E1]] # the extreme points p_1 and p_2 p2_vec=[pixels[0][E2],pixels[1][E2]] p3_vec=[mediatrix_data['center'].real+1,mediatrix_data['center'].imag+1] #due to the image origin is at 1,1 not 0,0 like the matrix coordinates x_c,y_c,r=three_points_to_circle(p1_vec,p3_vec,p2_vec) if r>0: FitsPlot.show_markers(np.array([p3_vec[1], y_c]), np.array([p3_vec[0], x_c]), layer=False, zorder=499,c='g',marker='.') else: print "impossible to define a circle " for i in range(0,len(mediatrix_data['origin'])): origin_x=mediatrix_data['origin'][i].real+1 #due to the image origin is at 1,1 not 0,0 like the matrix coordinates origin_y=mediatrix_data['origin'][i].imag+1 #due to the image origin is at 1,1 not 0,0 like the matrix coordinates end_x=mediatrix_data['end'][i].real+1 #due to the image origin is at 1,1 not 0,0 like the matrix coordinates end_y=mediatrix_data['end'][i].imag+1 #due to the image origin is at 1,1 not 0,0 like the matrix coordinates if opt['world_coord']==True: origin_x,origin_y=FitsPlot.pixel2world(origin_x,origin_y) end_x,end_y=FitsPlot.pixel2world(end_x,end_y) Length_aux=(origin_x - end_x)**2 + (origin_y - end_y)**2 Length=Length+sqrt(Length_aux) d_x= end_x - origin_x d_y= end_y - origin_y FitsPlot.show_arrows(origin_y, origin_x, d_y, d_x,zorder=502 ) if save==True: FitsPlot.save(out_image) del FitsPlot del mediatrix_data del image_ps del img gc.collect return True else: return FitsPlot, mediatrix_data, image_ps.copy() def width_ellipse(L,Area): W=Area/(atan(1)*L) return W
Rust
UTF-8
3,660
2.953125
3
[]
no_license
use crate::pokemon::{ReadRequest, ReadResponse, WriteRequest, WriteResponse, p2p_server::P2p}; use tonic::{Request, Response, Status}; use tokio::sync::mpsc::UnboundedSender; use std::sync::mpsc::channel; use crate::model::{Commands, Responses}; //use crate::node::*; //use libp2p::request_response::channel; //use hello_rust::reqchan::{channel, RequestSender, ResponseReceiver}; //use crate::reqchan::RequestSender; pub struct PokemonP2p { //pub sender : RequestSender<Commands, Result<Responses, Errors>>, pub sender: UnboundedSender<Commands>, //pub sender: Sender<Commands>, //pub receiver: UnboundedReceiver<Responses>, } /* impl PokemonP2p { pub fn getResponse(&mut self) -> Responses { match self.receiver.blocking_recv() { None => Responses::Error(), Some(res) => res } } } */ // implementing rpc for service defined in .proto #[tonic::async_trait] impl P2p for PokemonP2p { // our rpc impelemented as function async fn get_by_key(&self, request:Request<ReadRequest>) ->Result<Response<ReadResponse>,Status>{ let req_key = request.get_ref().key.clone(); //let pokemon_content = String::from("test content"); let (response_sender, response_receiver) = channel(); match self.sender.send(Commands::GetPokemon(req_key, response_sender)) { Ok(_) => { let pokemon_content = match response_receiver.recv() { Ok(res) => { match res { Responses::GotPokemon(content) => content, Responses::Success() => String::from("{}"), Responses::Error() => String::from("{}") } } Err(_) => String::from("{}") }; Ok(Response::new(ReadResponse { // reading data from request which is awrapper around our SayRequest message defined in .proto key: format!("received: {}", request.get_ref().key), value: pokemon_content })) } Err(_) => { Ok(Response::new(ReadResponse { // reading data from request which is awrapper around our SayRequest message defined in .proto key: format!("received: {}", request.get_ref().key), value: String::from("Error") })) } } } async fn put_value(&self,request:Request<WriteRequest>)->Result<Response<WriteResponse>,Status>{ let ref_key = request.get_ref().key.clone(); match self.sender.send(Commands::PutPokemon(ref_key, request.get_ref().value.clone())) { Ok(_) => { Ok(Response::new(WriteResponse { // reading data from request which is awrapper around our SayRequest message defined in .proto key: format!("put pokemon: {}, {}",request.get_ref().key, request.get_ref().value), result : 0, message:String::from("Successful") })) } Err(_) => { Ok(Response::new(WriteResponse { // reading data from request which is awrapper around our SayRequest message defined in .proto key: format!("put pokemon: {}, {}",request.get_ref().key, request.get_ref().value), result : 0, message:String::from("Error") })) } } } }
C++
UTF-8
1,085
2.859375
3
[]
no_license
#include "SDL.h" #include "Game.h" Game* game = nullptr; int main(int argc, char* argv[]) { /* // Draw a green window for 3 seconds SDL_Init(SDL_INIT_EVERYTHING); SDL_Window* window = SDL_CreateWindow("title", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 600, 400, SDL_WINDOW_SHOWN); SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, 0); SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255); SDL_RenderClear(renderer); SDL_RenderPresent(renderer); SDL_Delay(3000); */ // Game Loop // while game running // handle user input // update all objects // render changes to display const int FPS = 60; const int frameDelay = 1000 / FPS; Uint32 frameStart; int frameTime; game = new Game(); game->init("Block Ball", 800, 640, false); while (game->running()) { // ms since initialized SDL frameStart = SDL_GetTicks(); game->handleEvents(); game->update(); game->render(); frameTime = SDL_GetTicks() - frameStart; // Delay FPS if (frameDelay > frameTime) { SDL_Delay(frameDelay - frameTime); } } game->clean(); return 0; }
PHP
UTF-8
769
2.546875
3
[]
no_license
<?php session_start(); mysql_connect("localhost","root",""); mysql_select_db("tg"); if(isset($_REQUEST["enrollment_no"])) { $enrollment_no=$_REQUEST["enrollment_no"]; echo $enrollment_no; } if(isset($_REQUEST["submit"])) { $entrance=$_REQUEST["entrance"]; //$admissionbase=$_REQUEST["admissionbase"]; //$school_no=$_REQUEST["school_no"]; //$branch=$_REQUEST["branch"]; //$semester=$_REQUEST["semester"]; $query= mysql_query("insert into studentadmission(entrance)values('$entrance')"); if ($query){ echo "success"; } else{ echo "not succes"; } } ?> <form method="post" enctype="multipart/form-data"> Entrance<input type="text" name="entrance" required><br><br> <input type="submit" value="submit" name="submit"> </form>
Python
UTF-8
965
3.421875
3
[]
no_license
class Game(object): """ This class controls a game and takes the logic to decide who wins """ def __init__(self, id_, player1, player2): self.id = id_ self.player1 = player1 self.player2 = player2 self.is_done = False self.winner = None def set_winner(self): self.set_is_done() if self.is_done: total_score_player_1 = sum([getattr(self.player1, "score_" + str(i)) for i in range(1, 4)]) total_score_player_2 = sum([getattr(self.player2, "score_" + str(i)) for i in range(1, 4)]) results = {total_score_player_1: self.player1.name, total_score_player_2: self.player2.name, } self.winner = results[max(results.keys())] else: print('the game is not done') def set_is_done(self): self.in_done = self.player1.score_3 is not None and self.player2.score_3 is not None
C++
UTF-8
710
2.875
3
[]
no_license
#include "Menor.h" #include "ingreso.h" string Menor::getMenor() { return menor; } void Menor::setMenor(string newMenor) { this->menor = newMenor; } void Menor::calcularMenor(int num_palabras) { string menor = ""; char primeraLetra; string primeraPalabra; string palabra; string* palabras = new string[num_palabras]; for (int i = 0; i < num_palabras; i++) { *(palabras + i) = ingresarPalabra("Ingrese palabra: "); } primeraPalabra = *(palabras + 0); primeraLetra = primeraPalabra.at(0); for (int i = 0; i < num_palabras; i++) { palabra = *(palabras + i); if (primeraLetra > palabra.at(0)) { primeraLetra = palabra.at(0); menor = palabra; } } setMenor(menor); delete[] palabras; }
JavaScript
UTF-8
2,406
2.515625
3
[]
no_license
const width = 400; const height = 400; const dirName = "temp"; const { spawn } = require("child_process"); const chrome = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"; const WebSocket = require("ws"); const args = [ "--no-first-run", //ようこそみたいなのが表示されるのを防止 "--disable-default-apps", "--remote-debugging-port=9222", "--user-data-dir=/" + dirName, //これがないとDevToolの接続受け付けてくれない "--app=https://deno.land/", "--disable-sync", `--window-size=${width},${height}` ]; function SEND(ws, command) { ws.send(JSON.stringify(command)); return new Promise(resolve => { ws.on("message", function(text) { const response = JSON.parse(text); if (response.id === command.id) { ws.removeListener("message", arguments.callee); resolve(response); } }); }); } const bat = spawn(chrome, args); bat.stderr.on("data", data => { const dev = data .toString() .split("\r\n") .find(i => i.indexOf("DevTools listening on ") >= 0); if (dev) { const wsUrl = dev.replace("DevTools listening on ", ""); console.log(wsUrl); const ws = new WebSocket(wsUrl); let sessionId = ""; ws.on("open", async function open() { const targetsResponse = await SEND(ws, { id: 1, method: "Target.getTargets" }); const pageTarget = targetsResponse.result.targetInfos.find( info => info.type === "page" ); const sessionId = (await SEND(ws, { id: 2, method: "Target.attachToTarget", params: { targetId: pageTarget.targetId, flatten: true } })).result.sessionId; // Navigate the page using the session. await SEND(ws, { sessionId, id: 1, // Note that IDs are independent between sessions. method: "Page.navigate", params: { url: "https://pptr.dev" } }); await SEND(ws, { sessionId, id: 1, // Note that IDs are independent between sessions. method: "Runtime.addBinding", params: { name: "hello" } }); console.log("Startup") ws.on("message", function incoming(data) { console.log(data); }); }); } });
Java
UTF-8
747
3.375
3
[]
no_license
public class Vector { float x; float y; float z; public Vector(float x, float y, float z){ this.x = x; this.y = y; this.z = z; } public Vector difference(Vector aVec){ float x = this.x - aVec.x; float y = this.y - aVec.y; float z = this.z - aVec.z; return new Vector(x, y, z); } public Vector sum(Vector aVec){ return new Vector(this.x + aVec.x, this.y + aVec.y, this.z + aVec.z); } public float distanceMagnitude(Vector aVec){ float x = this.x - aVec.x; float y = this.y - aVec.y; float z = this.z - aVec.z; return (float) Math.sqrt(x*x + y*y + z*z); } public Vector dotProduct(float factor){ return new Vector(this.x * factor, this.y * factor, this.z * factor); } }
Python
UTF-8
1,677
3.609375
4
[]
no_license
# The socket Lib basically allows us establish # A connection over the internet import socket # Install IPy using pip3 install IPy # Use apt install python3-pip to install pip3 from IPy import IP def scan(target): converted_ip = check_ip(target) print('\n' + '^_^ Scanning Target ^_^ ' + str(target)) for port in range(1, 500): scan_port(converted_ip, port) def check_ip(ip): try: IP(ip) return ip except ValueError: return socket.gethostbyname(ip) def get_banner(sock): # The socket.recv function receives data from an open port # s.recv(1024) is the amount of data we receive from the port in # bytes as we don't need more in order to get and print the banner return sock.recv(1024) # We Try to connect to the target using socket in a try and except rule # Read more on socket to understand the Lib def scan_port(ipaddress, port): try: sock = socket.socket() # We set timeout because it takes longer to connect to certain # Ports than other ports # Note: the lower the timeout the lower the accuracy sock.settimeout(0.5) sock.connect((ipaddress, port)) try: banner = get_banner(sock) print('[+] Open Port ' + str(port) + ' : ' + str(banner.decode().strip('\n'))) except: print('[+] Port ' + str(port) + ' is Open') except: pass if __name__ == "__main__": targets = input('[+] Enter Target/s IP/Domain To Scan(Split multiple targets with ,): ') if ',' in targets: for ip_add in targets.split(','): scan(ip_add.strip(' ')) else: scan(targets)
C#
UTF-8
1,532
2.953125
3
[]
no_license
using System; using System.Collections.Generic; using UnityEngine; /// <summary> /// Check Property is used to validate field using other filds. /// </summary> [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = true)] public class vCheckPropertyAttribute : PropertyAttribute { [Serializable] public struct CheckValue { public string property; public object value; public bool isValid => value != null; public CheckValue(string property, object value) { this.property = property; this.value = value; } } public List<CheckValue> checkValues = new List<CheckValue>(); public bool hideInInspector; /// <summary> /// Check Property is used to validate field using other filds. /// </summary> /// <param name="propertyNames"> Properties names separated by "," (comma) Exemple "PropertyA,PropertyB". Only Enum and Boolean is accepted.</param> /// <param name="values">The values to compare, you need to set all values to compare with all properties</param> public vCheckPropertyAttribute(string propertyNames, params object[] values) { checkValues.Clear(); var _props = propertyNames.Split(','); for (int i = 0; i < _props.Length; i++) { try { checkValues.Add(new CheckValue(_props[i], values[i])); } catch { break; } } } }
Java
UTF-8
971
2.078125
2
[]
no_license
package com.pk.et.infra.util; public class JSONRequest { private boolean search; private int page; private int rows; private String sortField; private String sortOrder; private SearchFilter searchFilter; public boolean isSearch() { return search; } public void setSearch(boolean search) { this.search = search; } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public int getRows() { return rows; } public void setRows(int rows) { this.rows = rows; } public String getSortField() { return sortField; } public void setSortField(String sortField) { this.sortField = sortField; } public String getSortOrder() { return sortOrder; } public void setSortOrder(String sortOrder) { this.sortOrder = sortOrder; } public SearchFilter getSearchFilter() { return searchFilter; } public void setSearchFilter(SearchFilter searchFilter) { this.searchFilter = searchFilter; } }
Java
UTF-8
1,888
2.546875
3
[]
no_license
package com.example.aet.data; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.UUID; import com.example.aet.R; /** * @author swordy * @email mryangjian@live.com * @since Jan 20, 2014 * @version 1.0 */ public class SimulateData extends BaseInfo{ public static final String TAG = "SimulateData"; public static ArrayList<AddressInfo> getAddresses() { ArrayList<AddressInfo> data = new ArrayList<AddressInfo>(); String[] addrs = { "浙江", "江苏", "上海", "北京" }; for (int i = 0; i != addrs.length; i++) { AddressInfo addr = new AddressInfo(); addr.id = UUID.randomUUID().toString(); addr.name = addrs[i]; data.add(addr); } Collections.sort(data, new Comparator<AddressInfo>() { @Override public int compare(AddressInfo arg1, AddressInfo arg2) { return arg1.name.compareTo(arg2.name); } }); return data; } public static ArrayList<AtelierShortInfo> getAtelierShortInfos() { ArrayList<AtelierShortInfo> data = new ArrayList<AtelierShortInfo>(); int[] thumbIds = { R.drawable.atelier_logo_laoying, R.drawable.atelier_logo_xiaoji, R.drawable.atelier_logo_laoshu, R.drawable.atelier_logo_xiaomao }; for (int i = 0; i != thumbIds.length * 4; i++) { AtelierShortInfo info = new AtelierShortInfo(); info.name = "小画室" + i; info.number = 100 + i; info.isHonesty = (i % 2 == 0); info.logoId = thumbIds[i % thumbIds.length]; info.isFocused = (i % 3 != 0); data.add(info); } Collections.sort(data, new Comparator<AtelierShortInfo>() { @Override public int compare(AtelierShortInfo arg1, AtelierShortInfo arg2) { int result = 0; if (arg1.isHonesty == arg2.isHonesty) { result = arg1.name.compareTo(arg2.name); } else { result = arg1.isHonesty ? -1 : 1; } return result; } }); return data; } }
C#
UTF-8
909
2.90625
3
[ "MS-PL" ]
permissive
using System; namespace Microsoft.Msagl.Drawing { /// <summary> /// Size structure /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes"), Serializable] public struct Size { double width; /// <summary> /// width /// </summary> public double Width { get { return width; } set { width = value; } } double height; /// <summary> /// Height /// </summary> public double Height { get { return height; } set { height = value; } } /// <summary> /// constructor /// </summary> /// <param name="width"></param> /// <param name="height"></param> public Size(double width, double height) { this.width = width; this.height = height; } } }
Python
UTF-8
249
3.21875
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # https://leetcode.com/problems/find-the-difference/ # 1. get the length of s, and return the t[len+1:] # s = "abcd" # t = "abcde" s = "ymbgaraibkfmvocpizdydugvalagaivdbfsfbepeyccqfepzvtpyxtbadkhmwmoswrcxnargtlswqemafandgkmydtimuzvjwxvlfwlhvkrgcsithaqlcvrihrwqkpjdhgfgreqoxzfvhjzojhghfwbvpfzectwwhexthbsndovxejsntmjihchaotbgcysfdaojkjldprwyrnischrgmtvjcorypvopfmegizfkvudubnejzfqffvgdoxohuinkyygbdzmshvyqyhsozwvlhevfepdvafgkqpkmcsikfyxczcovrmwqxxbnhfzcjjcpgzjjfateajnnvlbwhyppdleahgaypxidkpwmfqwqyofwdqgxhjaxvyrzupfwesmxbjszolgwqvfiozofncbohduqgiswuiyddmwlwubetyaummenkdfptjczxemryuotrrymrfdxtrebpbjtpnuhsbnovhectpjhfhahbqrfbyxggobsweefcwxpqsspyssrmdhuelkkvyjxswjwofngpwfxvknkjviiavorwyfzlnktmfwxkvwkrwdcxjfzikdyswsuxegmhtnxjraqrdchaauazfhtklxsksbhwgjphgbasfnlwqwukprgvihntsyymdrfovaszjywuqygpvjtvlsvvqbvzsmgweiayhlubnbsitvfxawhfmfiatxvqrcwjshvovxknnxnyyfexqycrlyksderlqarqhkxyaqwlwoqcribumrqjtelhwdvaiysgjlvksrfvjlcaiwrirtkkxbwgicyhvakxgdjwnwmubkiazdjkfmotglclqndqjxethoutvjchjbkoasnnfbgrnycucfpeovruguzumgmgddqwjgdvaujhyqsqtoexmnfuluaqbxoofvotvfoiexbnprrxptchmlctzgqtkivsilwgwgvpidpvasurraqfkcmxhdapjrlrnkbklwkrvoaziznlpor" t = "qhxepbshlrhoecdaodgpousbzfcqjxulatciapuftffahhlmxbufgjuxstfjvljybfxnenlacmjqoymvamphpxnolwijwcecgwbcjhgdybfffwoygikvoecdggplfohemfypxfsvdrseyhmvkoovxhdvoavsqqbrsqrkqhbtmgwaurgisloqjixfwfvwtszcxwktkwesaxsmhsvlitegrlzkvfqoiiwxbzskzoewbkxtphapavbyvhzvgrrfriddnsrftfowhdanvhjvurhljmpxvpddxmzfgwwpkjrfgqptrmumoemhfpojnxzwlrxkcafvbhlwrapubhveattfifsmiounhqusvhywnxhwrgamgnesxmzliyzisqrwvkiyderyotxhwspqrrkeczjysfujvovsfcfouykcqyjoobfdgnlswfzjmyucaxuaslzwfnetekymrwbvponiaojdqnbmboldvvitamntwnyaeppjaohwkrisrlrgwcjqqgxeqerjrbapfzurcwxhcwzugcgnirkkrxdthtbmdqgvqxilllrsbwjhwqszrjtzyetwubdrlyakzxcveufvhqugyawvkivwonvmrgnchkzdysngqdibhkyboyftxcvvjoggecjsajbuqkjjxfvynrjsnvtfvgpgveycxidhhfauvjovmnbqgoxsafknluyimkczykwdgvqwlvvgdmufxdypwnajkncoynqticfetcdafvtqszuwfmrdggifokwmkgzuxnhncmnsstffqpqbplypapctctfhqpihavligbrutxmmygiyaklqtakdidvnvrjfteazeqmbgklrgrorudayokxptswwkcircwuhcavhdparjfkjypkyxhbgwxbkvpvrtzjaetahmxevmkhdfyidhrdeejapfbafwmdqjqszwnwzgclitdhlnkaiyldwkwwzvhyorgbysyjbxsspnjdewjxbhpsvj" print len(s), len(t) # s = "" # t = "abcde"
Java
UTF-8
2,666
2.25
2
[]
no_license
package com.test.demo.test.apiDemo.fragments; import android.content.Context; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; /** * Created by DEV002 on 2018/5/31. */ public class MyListFragment extends ListFragment{ public static final String TAG = "MyListFragment"; private OnContentClick onContentClick; String[] classes = { "计算机网络", "操作系统", "C语言", "Java", "数据库原理", "移动开发", }; @Override public void onAttach(Context context) { super.onAttach(context); onContentClick = (OnContentClick) getActivity(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.i(TAG,"=============onCreateView=============="); return super.onCreateView(inflater, container, savedInstanceState); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); Log.i(TAG,"=============onViewCreated=============="); this.setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, classes)); } @Override public void onStart() { super.onStart(); Log.i(TAG,"=============onStart=============="); } @Override public void onResume() { super.onResume(); Log.i(TAG,"=============onResume=============="); } @Override public void onPause() { super.onPause(); Log.i(TAG,"=============onPause=============="); } @Override public void onStop() { super.onStop(); Log.i(TAG,"=============onStop=============="); } @Override public void onDestroy() { super.onDestroy(); Log.i(TAG,"=============onDestroy=============="); } @Override public void onDestroyView() { super.onDestroyView(); Log.i(TAG,"=============onDestroyView=============="); } @Override public void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); onContentClick.onContentClick(position); } public interface OnContentClick{ public void onContentClick(int position); } }
Java
UTF-8
1,528
2.359375
2
[]
no_license
package com.example.murodjonrahimov.hackathon.model; /** * Created by c4q on 3/3/18. */ public class TennisCourt { private String Name; private String Location; private int image; private String Phone; private String Courts; private String Indoor_Outdoor; private String Tennis_Type; private boolean isFavorite; public boolean isFavorite() { return isFavorite; } public void setFavorite(boolean favorite) { isFavorite = favorite; } public String getName() { return Name; } public void setName(String name) { Name = name; } public String getLocation() { return Location; } public void setLocation(String location) { Location = location; } public String getPhone() { return Phone; } public void setPhone(String phone) { Phone = phone; } public String getCourts() { return Courts; } public void setCourts(String courts) { Courts = courts; } public String getIndoor_Outdoor() { return Indoor_Outdoor; } public void setIndoor_Outdoor(String indoor_Outdoor) { Indoor_Outdoor = indoor_Outdoor; } public String getTennis_Type() { return Tennis_Type; } public void setTennis_Type(String tennis_Type) { Tennis_Type = tennis_Type; } public int getImage() { return image; } public void setImage(int image) { this.image = image; } }
C++
UTF-8
572
3.28125
3
[]
no_license
/** * https://leetcode.com/problems/find-all-duplicates-in-an-array/description/ * 2017/02 * 129 ms */ class Solution { public: vector<int> findDuplicates(vector<int> & nums) { int n = nums.size(); vector<int> dups; for(int idx = 0; idx < n; idx ++) { int counter = abs(nums[idx]) - 1; if(nums[counter] < 0) { dups.push_back(counter + 1); } else { nums[counter] *= -1; } } return dups; } };
Python
UTF-8
3,204
2.78125
3
[]
no_license
from . import (particle_dist, particle_is_compatible, particle_merge, particle_evolve_up_to, contract, np, aer_particle) class ParticleTracker(): """ A class that tracks a set of particles for one frequency. """ @contract(max_vel='>0', max_bound='>0') def __init__(self, max_vel, max_bound): self.max_vel = max_vel self.max_bound = max_bound self.particles = [] def evolve_up_to(self, timestamp): e = lambda p: particle_evolve_up_to(p, self.max_vel, timestamp) self.particles = map(e, self.particles) @contract(tracks='tracks_array') def add_observations(self, tracks): timestamp = tracks[0]['timestamp'] self.evolve_up_to(timestamp) self.merge_observations(tracks) self.remove_too_large() self.merge_particles() score_sum = np.sum([x['score'] for x in self.particles]) for p in self.particles: p['score'] /= score_sum # also add new particles self.particles.extend(map(track2particle, tracks)) self.last = tracks.copy() def remove_too_large(self): new_particles = [] for p in self.particles: if p['bound'] <= self.max_bound: new_particles.append(p) self.particles = new_particles def merge_particles(self): new_particles = [] # sort particles by bound, smallest to big self.particles.sort(key=lambda x: x['bound']) for p_big in self.particles: for p_small in new_particles: # if p_small is included into p_big, # then let's say they merge dist = particle_dist(p_small, p_big) merge = dist < p_big['bound'] if merge: p_small['score'] += p_big['score'] break else: new_particles.append(p_big) self.particles = new_particles def merge_observations(self, tracks): new_particles = [] for p in self.particles: # add one without merging # with the lowest probability q = p.copy() min_quality = np.min(tracks['quality']) q['score'] *= min_quality new_particles.append(q) # add the ones that merged for t in tracks: coords = np.array([t['i'], t['j']]) if particle_is_compatible(p, coords): p1 = particle_merge(p, coords, coords_score=t['quality']) new_particles.append(p1) self.particles = new_particles def get_all_particles(self): self.particles.sort(key=lambda x: (-x['score'])) return list(self.particles) @contract(t='track_dtype', returns='is_particle_dtype') def track2particle(t): p = aer_particle(timestamp=t['timestamp'], id_track=t['id_track'], coords=[t['i'], t['j']], score=t['quality'], bound=2) # XXX return p
Python
UTF-8
413
3.421875
3
[]
no_license
# -*- coding: utf-8 -*- from __future__ import division a=int(input('insira o valor de a:')) b=int(input('insira o valor de b:')) c=int(input('insira o valor de c:')) cont=0 p=0 while p<=c: q=1 while q<=c: if c==((p*a)+(q*b)): m=p n=q cont=cont+1 break q=q+1 p=p+1 if cont==0: print ('N') else: print (m) print (n)
C++
UTF-8
2,857
2.9375
3
[]
no_license
/* * Console.cpp * * Created on: 18 de ago de 2016 * Author: doreis */ #include <cstdio> #include <cstdlib> #include <iostream> #include <string> // std::string #include <iostream> // std::cout #include <sstream> #include <iomanip> #include <algorithm> #include <Service/Convert.h> #include "Console.h" #include "Commands/ShowASCII.h" Console::Console() { commandMap["sa"] = new ShowASCII("sa"); commandMap["exit"] = nullptr; } bool Console::ProcessCommand(std::string cmd) { CommandBase* cmdHandler; std::string result; bool found; std::map<std::string, CommandBase*>::iterator it; std::vector<std::string> paramList; found = false; cmdHandler = nullptr; paramList.clear(); splitString(cmd,' ', paramList); if(paramList.size() > 0) { cmd = paramList[0]; std::transform(cmd.begin(), cmd.end(), cmd.begin(), toupper); for (auto it : this->commandMap) { std::string cmdName = it.first; std::transform(cmdName.begin(), cmdName.end(), cmdName.begin(), toupper); if(cmdName == cmd) { cmdHandler = it.second; found = true; break; } } if(cmdHandler == nullptr) { if(!found) { std::cout << "Command invalid!" << std::endl; return true; } else { std::cout << "Closing Terminal!" << std::endl; return false; } } paramList.erase(paramList.begin()); if(cmdHandler->ParseParameters(paramList)) { if (cmdHandler->Execute(result)) { } } else { std::cout << "Invalid parameters Dumb!" << std::endl; } } else { std::cout << "Invalid command Dumb!" << std::endl; } return true; } void Console::Execute() { std::string cmd, result; do { Help(); std::cout << "Type a command: "; std::cout << std::endl; std::getline(std::cin, cmd); }while(ProcessCommand(cmd)); } void Console::Help() { std::cout << std::endl << "+" << std::setw(80) << std::right << std::setfill('-') << "-" << "+" << std::endl; std::cout << "|" << std::setw(80) << std::left << std::setfill(' ') << " Commands" << "|" << std::endl; for (auto it : this->commandMap) { std::string help = "Close"; if(it.second) { it.second->Help(help); } std::cout << "|" << std::setw(80) << std::left << std::setfill(' ') << it.first + ": " + help << "|" << std::endl; } std::cout << "+"<< std::setw(80) << std::right << std::setfill('-') << "-" << "+" << std::endl << std::endl; }
Go
UTF-8
3,221
3.015625
3
[]
no_license
package main import ( "fmt" "log" "sync" "time" "github.com/google/uuid" pb "github.com/MarcGrol/go-training/examples/grpc/streaming/flightinfoapi" ) const ( maxOutstandingCount = 100 ) type session struct { uid string internalChannel chan pb.Flight externalChannel chan pb.Acknowledgement quitChannel chan bool stream pb.FlightInfoAsync_KeepSynchronizingServer outstanding map[string]bool maxOutstandingCount int sync.Mutex } func newSession(stream pb.FlightInfoAsync_KeepSynchronizingServer) (*session, func()) { sess := &session{ uid: uuid.New().String(), internalChannel: make(chan pb.Flight, maxOutstandingCount), externalChannel: make(chan pb.Acknowledgement, maxOutstandingCount), quitChannel: make(chan bool), stream: stream, outstanding: map[string]bool{}, maxOutstandingCount: maxOutstandingCount, } cleanup := func() { log.Printf("Cleanup session: %s", sess.uid) close(sess.quitChannel) close(sess.internalChannel) close(sess.externalChannel) } log.Printf("Created session: %s", sess.uid) return sess, cleanup } func (s *session) getOutstandingCount() int { s.Lock() defer s.Unlock() return len(s.outstanding) } func (s *session) addOutstanding(uid string) { s.Lock() defer s.Unlock() s.outstanding[uid] = true } func (s *session) removeOutstanding(uid string) { s.Lock() defer s.Unlock() _, ok := s.outstanding[uid] if !ok { log.Printf("Remove non-existing event: %s", uid) return } delete(s.outstanding, uid) } func (s *session) process() error { go s.readExternal() return s.waitforEvents() } func (s *session) waitforEvents() error { log.Printf("Start processing events on session %s", s.uid) defer log.Printf("Done processing events on session %s", s.uid) heartbeatChannel := time.Tick(10 * time.Second) for { select { case <-heartbeatChannel: log.Printf("*** Send heartbeat on session %s\n", s.uid) err := s.stream.Send(&pb.FlightPdu{ Payload: &pb.FlightPdu_Heartbeat{ Heartbeat: &pb.Heartbeat{}, }, }) if err != nil { log.Printf("*** Error writing heartbeat event: %s\n", err) return err } case <-s.quitChannel: log.Printf("*** Got quit signal\n") return nil case f := <-s.internalChannel: s.addOutstanding(f.FlightUid) err := s.stream.Send(&pb.FlightPdu{ Payload: &pb.FlightPdu_Flight{ Flight: &f, }, }) if err != nil { log.Printf("*** Error writing outbound event: %s\n", err) return err } fmt.Printf("\nWrote flight-event to remote client: %+v\n", f.FlightUid) case fc := <-s.externalChannel: s.removeOutstanding(fc.FlightUid) fmt.Printf("\nReceived confirmation from remote client: %+v\n", fc.FlightUid) } } return nil } func (s *session) readExternal() error { defer func() { s.quitChannel <- true }() log.Printf("Start reading external for session %s", s.uid) defer log.Printf("Done reading external for session %s", s.uid) for { fc, err := s.stream.Recv() if err != nil { log.Printf("*** Error reading from external: %s\n", err) return err } s.externalChannel <- *fc } return nil }
Python
UTF-8
1,517
3.59375
4
[]
no_license
# This file communicates with the load Arduino. # The format for this is: # setup by sending "L C R;" # reset by sending "<char>" import time import serial class LoadControl: def __init__(self, device): """Open a specific device as a load controller. Device is a tuple with the first element being the com port on Windows or file name on Linux and the second element is the baud rate.""" try: self.device = device self.comlink = serial.Serial(*device) except: print "Could not open ",device raise def __del__(self): self.comlink.close() def setLCR(self, l, c, r): # Format is L C R; command = b"{0} {1} {2};".format(l,c,r) self.comlink.write(command) self.comlink.flush() def reset(self): # Format is <char> self.comlink.write(b"#") self.comlink.flush() if __name__ == '__main__': print("Testing LoadControl!") f = raw_input("Enter the device descriptor: ") b = int(raw_input("Enter the baud rate: ")) load = LoadControl((f,b)) L = int(raw_input("Enter a load: ")) C = int(raw_input("Enter a capacatence: ")) R = int(raw_input("Enter a resistance: ")) load.setLCR(L,C,R) time.sleep(5) load.reset()
Python
UTF-8
123
3.4375
3
[]
no_license
x=input("enter some value:") if x/2==0: print("enterd value is zero") else: print("the enterd value is non-zero")
PHP
UTF-8
1,788
2.53125
3
[]
no_license
<?php namespace Test\ItemTest; use App\Controller\GildedRose; use App\Model\Item\Item; use App\Model\Item\ItemTypes\ItemNormal; use App\Model\ItemManager; use PHPUnit\Framework\TestCase; class ItemNormalTest extends TestCase { private $itemManager; private $gildedRose; public function setUp() { $this->itemManager = new ItemManager(); $this->itemManager->insertItems( [ new Item("Normal item", 10, 10), new Item("Even more normal item", 0, 10), new Item("Even even more more normal item", 10, 0), new Item("Even even even more more more normal item", 0, -10), new Item("Even even even even more more more more normal item", -10, -10) ] ); $this->gildedRose = new GildedRose( $this->itemManager ); parent::setUp(); } public function testNormalItemBehaviour() { $this->gildedRose->loopUpdateQuality(3); $this->assertEquals($this->itemManager->getItem(0), new Item('Normal item', 7, 7)); $this->assertEquals($this->itemManager->getItem(1), new Item('Even more normal item', -3, 5)); $this->assertEquals($this->itemManager->getItem(2), new Item('Even even more more normal item', 7, 0)); $this->assertEquals($this->itemManager->getItem(3), new Item('Even even even more more more normal item', -3, 0)); $this->assertEquals($this->itemManager->getItem(4), new Item('Even even even even more more more more normal item', -13, 0)); } public function testOneNormalItemBehaviour() { $this->gildedRose->loopUpdateQuality(10); $this->assertEquals($this->itemManager->getItem(0), new Item('Normal item', 0, 0)); } }
JavaScript
UTF-8
5,178
2.578125
3
[]
no_license
import { createSlice } from '@reduxjs/toolkit' import { api } from 'api/index' import { getLoggedInUserInfo } from 'utils/index'; const imagesSlice = createSlice({ name: 'images', initialState: { images: [], isImagesLoading: false, error: false }, reducers: { startLoadingImages: state => { state.isImagesLoading = true; }, hasImagesLoadingError: (state, action) => { state.error = action.payload; state.isImagesLoading = false; }, imagesLoadedSuccessfully: (state, action) => { state.images = action.payload; state.isImagesLoading = false; }, }, }); export default imagesSlice.reducer; const { startLoadingImages, imagesLoadedSuccessfully, hasImagesLoadingError } = imagesSlice.actions // any random number between min (included) and max (not included): const getRandomIndex = (max) => { return Math.floor(Math.random() * max); }; const width = 237; const heightArray = [239, 429, 355, 249, 237, 505, 740, 315, 354, 583, 330, 255]; const getCurrentUserId = () => { const currentUser = getLoggedInUserInfo(); if(currentUser) return currentUser.userId; return null; } const getUserImagesUrl = `/pin/users/${getCurrentUserId()}/images`; const getImagesUrl = `/pin/images`; export const fetchImages = () => async dispatch => { dispatch(startLoadingImages()); try { await api.get(getUserImagesUrl) .then((response) => { const allImages = response.data.data.map(image=> { return { ...image, width: width, height: heightArray[getRandomIndex(heightArray.length)] }; }); console.info('allImages: ', allImages); dispatch(imagesLoadedSuccessfully(allImages)) }) } catch (e) { // return console.error(e.message); dispatch(hasImagesLoadingError(e.message)) } } export const fetchImagesAuthWise = (authStatus) => async dispatch => { let imageUrl = `/pin/images`; dispatch(startLoadingImages()); if(authStatus) imageUrl = `/pin/users/${getCurrentUserId()}/images`; try { await api.get(imageUrl) .then((response) => { const allImages = response.data.data.map(image=> { return { ...image, width: width, height: heightArray[getRandomIndex(0, heightArray.length)] }; }); console.info('allImages: ', allImages); dispatch(imagesLoadedSuccessfully(allImages)) }) } catch (e) { // return console.error(e.message); dispatch(hasImagesLoadingError(e.message)) } } export const fetchImagesByUserId = (userId) => async dispatch => { let imageUrl = `/pin/images`; dispatch(startLoadingImages()); if(userId) imageUrl = `/pin/users/${userId}/images`; try { await api.get(imageUrl) .then((response) => { const allImages = response.data.data.map(image=> { const randomIndex = getRandomIndex(heightArray.length); return { ...image, width: width, height: heightArray[randomIndex] }; }); console.info('allImages: ', allImages); dispatch(imagesLoadedSuccessfully(allImages)) }) } catch (e) { // return console.error(e.message); dispatch(hasImagesLoadingError(e.message)) } } export const fetchAllImages = () => async dispatch => { dispatch(startLoadingImages()); try { await api.get(getImagesUrl) .then((response) => { const allImages = response.data.data.map(image=> { return { ...image, width: width, height: heightArray[getRandomIndex(0, heightArray.length)] }; }); console.info('allImages: ', allImages); dispatch(imagesLoadedSuccessfully(allImages)) }) } catch (e) { // return console.error(e.message); dispatch(hasImagesLoadingError(e.message)) } } export const deleteUserImageById = (userId, imageId) => async dispatch => { console.info('delete userId, imageId: ', userId, imageId); const url = `/pin/users/${userId}/images/${imageId}`; try { await api.delete(url) .then((response) => { console.info(`${imageId} is deleted`); console.info(response); if(response.data.data !== null){ dispatch(fetchImagesByUserId(userId)); } else { console.info('image not deleted'); } }) } catch (e) { console.error(e.message); } };
Markdown
UTF-8
1,662
3.484375
3
[]
no_license
--- title: Algorithmique -- MergeSort author: Romain Gille date: 30/03/2016 geometry: margin=1in ... \newpage # Dernier tri de tableau : MergeSort (tri fusion) * Tri optimal (non stochastique) : $\Theta(n \log n)$ * Copie du tableau (ne trie pas "sur place") * Approche "Diviser pour régner" (idem QuickSort) ```java void mergeSort(int[] T){ int n = T.length; ms(T, 0, n); } void ms(int[] T, i, j){ int n = j - i; if(n >= 2){ int[] T1 = Arrays.copyOfRange(T, i, n/2), T2 = Arrays.copyOfRange(T, n/2, j); mergeSort(T1); mergeSort(T2); merge(T1, T2, T, i, j); } } ``` $I(k, k1, k2) : T[i:k] \text{ suivi de } T[k1:n1] \text{ fusionné avec } T2[k2:n2] = T1[0:n1] \text{ fusionné avec } T2[0:n2]$ **Initialisation :** $k1 = 0, k2 = 0, k = i$ **Arrêt :** $k1 = n1 \text{ ou } k2 = n2$ *il reste à faire après ça* **Progression :** $I(k, k1, k2)$ et $\overline{\text{arrêt}}$ et $T1[k1] \leq T2[k2]$ et $T[k] = T1[k1] \Rightarrow I(k + 1, k1 + 1, k2)$ $I(k, k1, k2)$ et $\underline{\text{arrêt}}$ et $T1[k1] \leq T2[k2]$ et $T[k] = T2[k2] \Rightarrow I(k + 1, k1, k2 + 1)$ ```java void merge(int[] T1, int[] T2, T, i, j){ int n1 = T1.length, n2 = T2.length, k1 = 0, k2 = 0, k = i; // I(k, k1, k2) while(k1 != n1 && k2 != n2){ if(T1[k1] <= T2[k2]){ T[k] = T1[k1]; k ++; k1 ++; } else{ T[k] = T2[k2]; k ++; k2 ++; } } while(k1 != n1){ T[k] = T1[k1]; k ++; k1 ++; } while(k2 != n2){ T[k] = T2[k2]; k ++; k2 ++; } } ``` `merge()` est de complexité $\Theta(n)$.
Python
UTF-8
599
2.78125
3
[]
no_license
import sys from heapq import heappush, heappushpop X, Y, Z = map(int, input().split()) xyz = sorted([list(map(int,l.split()))for l in sys.stdin],key=lambda x:x[0]-x[1]) uq = [] cy = 0 for x, y, z in xyz[:Y]: heappush(uq, y - z) cy += y Ly = [cy] for x, y, z in xyz[Y:Y+Z]: cy += y - heappushpop(uq, y - z) Ly += [cy] lq = [] cx = 0 for _ in [0] * X: x, y, z = xyz.pop() heappush(lq, x - z) cx += x Lx = [cx] for _ in [0] * Z: x, y, z = xyz.pop() cx += x - heappushpop(lq, x - z) Lx += [cx] print(max(map(sum, zip(Lx, Ly[::-1]))))
JavaScript
UTF-8
853
2.796875
3
[ "MIT" ]
permissive
'use strict'; function json(data, type) { if ('application/json' !== type) { throw new Error('Unsupported Content-Type: ' + type); } return JSON.parse(data); } function form(data, type) { if ('application/form-data' !== type) { throw new Error('Unsupported Content-Type: ' + type); } var payload = {}; var params = data.split('&'); var len = params.length; var i, param; for (i = 0; i < len; i = i + 1) { param = params[i].split('=', 2); payload[decodeURIComponent(param[0])] = decodeURIComponent(param[1]); } return payload; } function decode(fn, data, type) { return data.then(function(text) { switch (fn) { case 'json': return json(text, type); case 'form': return form(text, type); default: return fn(text, type); } }); } module.exports = decode;
C#
UTF-8
592
2.96875
3
[]
no_license
using System; using System.Collections.Generic; using System.Text; namespace day18 { public struct Edge { public string Name; public char[] Doors; public int Cost; public Edge(string name, RetraceData retraceData) { Name = name; Doors = retraceData.Doors.ToArray(); Cost = retraceData.Length; } public static string EdgeName(Node a, Node b) { if (a.Name > b.Name) return $"{a.Name}{b.Name}"; return $"{b.Name}{a.Name}"; } } }
Markdown
UTF-8
2,850
3.125
3
[]
no_license
--- layout: post title: "Spark-Streaming day 5 (spark streaming window)" date: 2018-06-15 08:44:17 +0800 categories: Spark-Streaming --- #### 目標 算出每個時間區間的總數 #### StreamingWindowTest.scala spark-streaming 每 5 秒觸發一次, 使用 reduceByWindow 這 function 會給 2 個參數,第一個是 window length,第二個是 sliding interval. 這邊的例子就是每 5 秒計算一次 10 秒內出現的數字加總起來. ```scala package com.streaming.test import org.apache.spark.streaming.{Seconds, StreamingContext} import org.apache.spark.{SparkConf, SparkContext} object StreamingWindowTest { def main(args: Array[String]): Unit = { val conf = new SparkConf().setMaster("local[2]").setAppName("NetworkWordCount") val ssc = new StreamingContext(conf, Seconds(5)) val lines = ssc.socketTextStream("localhost", 9988) val wordspair = lines.map(row => { if(row !=null && row != "") { val num = row.split(" ")(1); num.toInt } else { 0 } }) val windowsRdds = wordspair.reduceByWindow((x:Int , y:Int) => { println(x + " + " + y + " = " + (x+y)); (x + y) }, Seconds(10), Seconds(5)).print() ssc.start() ssc.awaitTermination() } } ``` #### spark streaming checkpoint 使用 StreamingContext.getOrCreate 這方法,如果沒有 checkpoint file 則重新 new 一個 StreamingContext, 有的話直接讀取 checkpoint file 產生 StreamingContext. #### StreamingWindowTest.scala 改寫 ```scala package com.streaming.test import org.apache.spark.streaming.{Seconds, StreamingContext} import org.apache.spark.SparkConf object StreamingWindowTest { def main(args: Array[String]): Unit = { val ssc = StreamingContext.getOrCreate("/Users/daniel/test/checkpointfile" , functionToCreateContext) ssc.start() ssc.awaitTermination() } def functionToCreateContext(): StreamingContext = { val conf = new SparkConf().setMaster("local[2]").setAppName("NetworkWordCount") val ssc = new StreamingContext(conf, Seconds(5)) ssc.checkpoint("/Users/daniel/test/checkpointfile") val lines = ssc.socketTextStream("localhost", 9988) val wordspair = lines.map(row => { if(row !=null && row != "") { val num = row.split(" ")(1); num.toInt } else { 0 } }) val windowsRdds = wordspair.reduceByWindow((x:Int , y:Int) => { println(x + " + " + y + " = " + (x+y)); (x + y) }, Seconds(10), Seconds(5)).print() ssc } } ``` 先 run 起來一次產生幾筆資料後,然後關掉從 run 可以看到下列訊息 : ![spark-streaming_day5_1.jpg]({{ "/assets/spark-streaming/day5/spark-streaming_day5_1.jpg" | absolute_url }}) > 參考資料 > [check point](https://blog.csdn.net/qq_36330643/article/details/74451402)
PHP
UTF-8
3,029
2.921875
3
[]
no_license
<?php /** * Contact.php * * Copyright (c) 2009 Fraise, Inc. * All rights reserved. */ /** * ユーザー側問い合わせクラス * 問い合わせを管理するクラス * * @copyright 2009 Fraise, Inc. * @author mitsuhiro nakamura */ class Contact extends ComCommon { const SEND_MAIL_ADDRESS_ACCOUNT = "info@"; /** @var string エラーメッセージ */ protected $_errorMsg = null; /** @var object インスタンスを保持するstatic変数 */ protected static $_instance = null; /** * コンストラクタ。 */ function __construct() { parent::__construct(); } /** * getInstanceメソッド * * このクラスのオブジェクトを生成する。 * 既に生成されていたら、前回と同じものを返す。 * * @return object $instance */ public static function getInstance() { if (!self::$_instance) { self::$_instance = new self(); } return self::$_instance; } /** * 問い合わせの登録。 * * @param array $insertArray 挿入データ配列 * @return boolean */ public function insertContactData($insertArray) { if (!is_array($insertArray)) { return false; } if (!$dbResultOBJ = $this->insert("contact", $insertArray)) { $this->_errorMsg[] = "データ登録できませんでした。"; return false; } return $dbResultOBJ; } /** * * selectbox用問い合わせ種別リストの取得 * * @return array $dataArray データ配列 */ public function getContactTypeAryForSelect() { $columnArray[] = "*"; $whereArray[] = "is_display = 1"; $whereArray[] = "disable = 0"; $otherArray[] = "ORDER BY sort_seq DESC"; $sql = $this->makeSelectQuery("contact_type", $columnArray, $whereArray, $otherArray); if (!$dbResultOBJ = $this->executeQuery($sql)) { return FALSE; } while ($data = $this->fetch($dbResultOBJ)) { $dataArray[$data["id"]] = $data["name"]; } return $dataArray; } /** * mailToメソッド * * メール送信実行 * * @param string $mailAddress 送信するメアド * @param array $$mailElements 送信する要素 * [from_address]:メール送信元アドレス * [from_name] :メール送信元名(任意) * [return_path] :リターンアドレス(任意) * [subject] :メールタイトル * [text_body] :メール本文(テキスト) * [html_body] :メール本文(HTML)(任意) * @return 送信成功:True 送信失敗:False */ public function mailTo ($mailElements, $sec = 0, $imageData = null, $imageType = null) { $SendMailOBJ = SendMail::getInstance(); return $SendMailOBJ->mailTo($mailElements, $sec, $imageData, $imageType); } } ?>
Java
UTF-8
431
2.234375
2
[]
no_license
//@author A0080415N //Name : Steven Kester Yuwono //Matric No. : A0080415N //com.licensetokil.atypistcalendar.parser package com.licensetokil.atypistcalendar.parser; public class SyncGoogleAction extends GoogleAction{ public SyncGoogleAction(){ type = GoogleActionType.GOOGLE_SYNC; } public String toString(){ return ("Type : " + type + "\n"); } public GoogleActionType getType(){ return type; } }
Rust
UTF-8
5,825
3.375
3
[ "Apache-2.0", "MIT" ]
permissive
use {crate::ui::layout, reclutch::display as gfx}; /// A 2D position based on a relative offset and an absolute offset. /// The `relative` offset is expressed as a fraction of the corresponding parent dimension for each component in `(x, y)`. /// The `post_relative` offset is expressed as a fraction of the result of the `relative`, `post_relative` and `real` calculated size from `FractionSize`. /// The `real` offset is a concrete size in DPI pixels which is added onto the offset calculated from `relative`. /// /// For example, `FractionalPosition { relative: (0.3, 0.1), post_relative: (-0.5, 0.0), real: Vector::new(5, 30) }` for a child with a computed size of `50 x 50` /// placed within a parent of size `100 x 100` positioned at `(50, 50)` will result in an absolute position of `(60, 90)` (or relatively; `(10, 40)`). /// Following the calculation; `100 * 0.3 = 30, + 50 = 80, + 5 = 85, - 0.5 * 50 = 60` and `100 * 0.1 = 10, + 50 = 60, + 30 = 90`. #[derive(Debug, Default, Clone, Copy, PartialEq)] pub struct FractionalPosition { pub relative: (f32, f32), pub post_relative: (f32, f32), pub real: gfx::Vector, } /// A 2D size based on a relative size and an absolute size. /// The `relative` size is expressed as a fraction of the corresponding parent dimension for each component in `(width, height)`. /// The `post_relative` size is expressed as a fraction of the result of the `relative` and `real` calculated size. /// The `real` size is a concrete size in DPI pixels which is added onto the size calculated from `relative`. /// /// For example, `FractionalSize { relative: (0.5, 0.75), post_relative: (0.6, -0.2), real: Size::new(15, 10) }` placed within a parent /// of size `100 x 100` will result in a size of `120 x 68`, because `100 * 0.5 = 50, + 15 = 75, + 0.6 * 75 = 120` and `100 * 0.75 = 75, + 10 = 85, - 0.2 * 85 = 68`. #[derive(Debug, Default, Clone, Copy, PartialEq)] pub struct FractionalSize { pub relative: (f32, f32), pub post_relative: (f32, f32), pub real: gfx::Size, } /// Configuration for `RelativeBox`. /// /// If `size` is left as `None`, then the size of the child will be used. #[derive(Debug, Default, Clone, Copy, PartialEq)] pub struct RelativeBoxConfig { pub position: FractionalPosition, pub size: Option<FractionalSize>, } impl RelativeBoxConfig { /// Returns a `RelativeBoxConfig` which will result in the item being centered in the parent. pub fn center() -> Self { RelativeBoxConfig { position: FractionalPosition { relative: (0.5, 0.5), post_relative: (-0.5, -0.5), ..Default::default() }, ..Default::default() } } } /// Powerful layout based on quantities relative to the parent. /// This only supports a single child. /// /// This layout is very useful for any of the following scenarios; /// - Centering an item. /// - Aligning an item to a corner or side with an arbitrary offset. /// - Filling a fraction of the parent (e.g. filling the bottom-half of the parent). /// /// These are all scenarios which can be expressed as screen-space fractions. pub struct RelativeBox { item: Option<layout::Item>, config: RelativeBoxConfig, } impl RelativeBox { pub fn new(config: RelativeBoxConfig) -> Self { RelativeBox { item: None, config } } } impl layout::Layout for RelativeBox { type Config = (); type Id = (); #[inline] fn push(&mut self, item: impl Into<layout::Item>, _: ()) { self.item = Some(item.into()); } #[inline] fn remove(&mut self, _: &()) -> Option<layout::Item> { self.item.take() } #[inline] fn get(&self, _: &()) -> Option<&layout::Item> { self.item.as_ref() } #[inline] fn get_mut(&mut self, _: &()) -> Option<&mut layout::Item> { self.item.as_mut() } #[inline] fn len(&self) -> usize { self.item.is_some() as _ } fn items(&self) -> Vec<(&layout::Item, &Self::Id)> { if let Some(item) = &self.item { vec![(item, &())] } else { Vec::new() } } fn min_size(&self) -> gfx::Size { if let Some(item) = &self.item { if !layout::should_layout(item) { Default::default() } else { item.rect().size } } else { Default::default() } } fn update(&mut self, bounds: gfx::Rect) { if let Some(item) = &mut self.item { if !layout::should_layout(item) { return; } let mut rect = item.rect(); let position = self.config.position; rect.size = if let Some(size) = self.config.size { let mut new_size = gfx::Size::new( bounds.size.width * size.relative.0, bounds.size.height * size.relative.1, ); new_size.width += size.real.width; new_size.height += size.real.height; new_size.width += new_size.width * size.post_relative.0; new_size.height += new_size.height * size.post_relative.1; new_size } else { rect.size }; let mut new_position = gfx::Point::new( bounds.size.width * position.relative.0, bounds.size.height * position.relative.1, ); new_position.x += position.real.x; new_position.y += position.real.y; new_position.x += rect.size.width * position.post_relative.0; new_position.y += rect.size.height * position.post_relative.1; rect.origin = new_position; item.set_rect(rect); } } }
Java
UTF-8
866
3.0625
3
[]
no_license
package teel; import java.util.Arrays; public class NumberOfLongestIncreasingSubsequences { public int findNumberOfLIS(int[] nums) { if (nums.length == 0) return 0; if (nums.length == 1) return 1; int []counts = new int [nums.length]; int []lengths = new int [nums.length]; Arrays.fill(counts, 1); for (int i = 0; i < nums.length; i++) { for (int j = 0; j < i; j++) { if (nums[j] < nums[i]) { if (lengths[i] <= lengths[j]) { lengths[i] = lengths[j] + 1; counts[i] = counts[j]; } else if (lengths[i] == lengths[j]+1) { counts[i] += counts[j]; } } } } int longest = 0, ans = 0; for (int i = 0; i < lengths.length; i++) { longest = Math.max(longest, lengths[i]); } for (int i = 0; i < counts.length; i++) { if (counts[i] == longest) { ans += counts[i]; } } return ans; } }
Java
UTF-8
1,971
4
4
[]
no_license
package hu.bp.concurrency.visibility; /** * The following class demonstrates the visibility issue in multi-threaded Java * programs. * * The main thread starts a new thread and then changes the stopperFlag variable * to false. The other thread monitors this flag and if it becomes false, then * it exits the while loop finishing its run() method. * * Actually making a Thread and starting it is quite slow. So in reality if we * don't call Thread.sleep() the flag will already be set to false by the time * the new Thread is started. (I think it is a race condition of some kind.) * * The best explanation I have found so far why this is happening can be found * here: http://jeremymanson.blogspot.com/2007/08/atomicity-visibility-and-ordering.html * * According to this article, what happens is that the compiler (the JVM) * doesn't let the second thread see the variable stopperFlag, because it * detects that no writes are performed to that variable from that thread. * * When you uncomment the stopperBlock this theory is fallen. :( * * The strangest thing is that the compiler makes the variable visible to the * second thread when you uncomment the code in the while loop: * "System.out.println("Running...");" * * @author Ádám T. Nagy * */ public class NoVisibility implements Runnable{ private static boolean stopperFlag = false; @Override public void run() { System.out.println("run() method started."); /*stopperBlock: { stopperFlag = true; stopperFlag = false; }*/ while (!stopperFlag) { // When the next line is commented out the issue will be triggered. //System.out.println("Running..."); } System.out.println("Finished run() method."); stopperFlag = true; } public static void main(String[] args) throws InterruptedException { Thread t = new Thread(new NoVisibility()); t.start(); Thread.sleep(1000); stopperFlag = true; System.out.println("stopperFlag is: " + stopperFlag); } }
Java
UTF-8
1,094
2.03125
2
[]
no_license
package spartons.com.frisbee.di.modules; import dagger.Module; import dagger.Provides; import spartons.com.frisbee.collections.DriverCollection; import spartons.com.frisbee.collections.MarkerCollection; import spartons.com.frisbee.di.scopes.CustomApplicationScope; import spartons.com.frisbee.repo.DriverRepo; import spartons.com.frisbee.repo.MarkerRepo; import spartons.com.frisbee.util.AppRxSchedulers; @Module(includes = {UtilModule.class}) public class RepositoryModule { @Provides @CustomApplicationScope public DriverCollection driverCollection(AppRxSchedulers appRxSchedulers) { return new DriverCollection(appRxSchedulers); } @Provides @CustomApplicationScope public MarkerCollection markerCollection() { return new MarkerCollection(); } @Provides @CustomApplicationScope public DriverRepo driverRepo(DriverCollection driverCollection) { return new DriverRepo(driverCollection); } public MarkerRepo markerRepo(MarkerCollection markerCollection) { return new MarkerRepo(markerCollection); } }
Rust
UTF-8
704
2.96875
3
[]
no_license
use std::fmt::{self, Display}; pub type Result<T> = std::result::Result<T, Error>; #[derive(Debug)] pub enum Error { BadIdentity, #[cfg(feature = "json")] Serialisation(serde_json::Error), } impl Display for Error { fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result { use Error::*; write!(w, "{}", match self { BadIdentity => String::from("bad identity"), #[cfg(feature = "json")] Serialisation(e) => e.to_string(), }) } } impl std::error::Error for Error {} #[cfg(feature = "json")] impl From<serde_json::Error> for Error { fn from(e: serde_json::Error) -> Self { Self::Serialisation(e) } }
Markdown
UTF-8
1,963
2.828125
3
[]
no_license
#jQuery.RSlide A simple, auto slide animation jQuery plugin for Desktop and Mobile ####Include ```javascript <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <script type="text/javascript" src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script> ``` ####Installation Include js and css after the jQuery library ```javascript <script type="text/javascript" src="js/jquery.RSlide-1.0.1.js"></script> <link type="text/css" rel="stylesheet" href="css/RSlide.css" /> ``` ####Usage Create Markup Structure : ```html <!-- s : contents --> <div id="fluid-slide" class="scroll-wrap"> <!-- list --> <div class="scroll"> <ul class="list"> <li class="item"> <div class="photo"><img src="images/img01.jpg" alt="" /></div> <div class="desc">Gallery 01</div> </li> <li class="item"> <div class="photo"><img src="images/img02.jpg" alt="" /></div> <div class="desc">Gallery 02</div> </li> <li class="item"> <div class="photo"><img src="images/img03.jpg" alt="" /></div> <div class="desc">Gallery 03</div> </li> <li class="item"> <div class="photo"><img src="images/img03.jpg" alt="" /></div> <div class="desc">Gallery 04</div> </li> </ul> </div> <!-- paging --> <div class="paging"> <a href="#nowhere" class="on"><span class="blind">1</span></a> <a href="#nowhere" class="reservation"></a> <a href="#nowhere"><span class="blind">2</span></a> <a href="#nowhere"><span class="blind">3</span></a> <a href="#nowhere"><span class="blind">4</span></a> </div> <!-- button left , right --> <div class="btn-wrap"> <button type="button" class="btn btn-prev"><span class="blind">prev</span></button> <button type="button" class="btn btn-next"><span class="blind">next</span></button> </div> </div> <!-- e : contents --> ``` Create new Constructor : ```javascript var mySlide = new FluidSlide($(".className") , speed , interval); ```
C
UTF-8
20,492
2.953125
3
[]
no_license
#include <stdlib.h> #include <stdio.h> #include <dirent.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <string.h> #include <time.h> #include <fcntl.h> typedef struct{ char color[100]; }colores; typedef struct{ char numero[100]; }numeros; void crearArchivo(int jugador,char nombreArchivo[]){ char dirJ1[]="jugador1/"; char dirJ2[]="jugador2/"; char dirJ3[]="jugador3/"; char dirJ4[]="jugador4/"; char final[100]; if(jugador==1){ sprintf(final,"%s%s",dirJ1,nombreArchivo); FILE *archivo=fopen(final,"w"); fclose(archivo); } if(jugador==2){ sprintf(final,"%s%s",dirJ2,nombreArchivo); FILE *archivo=fopen(final,"w"); fclose(archivo); } if(jugador==3){ sprintf(final,"%s%s",dirJ3,nombreArchivo); FILE *archivo=fopen(final,"w"); fclose(archivo); } if(jugador==4){ sprintf(final,"%s%s",dirJ4,nombreArchivo); FILE *archivo=fopen(final,"w"); fclose(archivo); } } void removerDeMazo(char nombreArchivo[]){ char final[100]; char dirMazo[]="mazo/"; sprintf(final,"%s%s",dirMazo,nombreArchivo); remove(final); } void removerDeMano(char nombreArchivo[],int jugador){ char dirJ1[]="jugador1/"; char dirJ2[]="jugador2/"; char dirJ3[]="jugador3/"; char dirJ4[]="jugador4/"; char final[100]; if(jugador==1){ char final[100]; sprintf(final,"%s%s",dirJ1,nombreArchivo); remove(final); } if(jugador==2){ char final[100]; sprintf(final,"%s%s",dirJ2,nombreArchivo); remove(final); } if(jugador==3){ char final[100]; sprintf(final,"%s%s",dirJ3,nombreArchivo); remove(final); } if(jugador==4){ char final[100]; sprintf(final,"%s%s",dirJ4,nombreArchivo); remove(final); } } void crearCartas(){ char dirMazo[]="mazo/"; //creando las cartas del 0 al 9 colores *arreglo=(colores *)malloc(sizeof(colores *)*4); strcpy(arreglo[0].color,"Azul"); strcpy(arreglo[1].color,"Rojo"); strcpy(arreglo[2].color,"Amarillo"); strcpy(arreglo[3].color,"Verde"); //printf("mi color es %s\n",arreglo[2].color); numeros *arregloDos=(numeros *)malloc(sizeof(numeros)*10); strcpy(arregloDos[0].numero,"Cero"); strcpy(arregloDos[1].numero,"Uno"); strcpy(arregloDos[2].numero,"Dos"); strcpy(arregloDos[3].numero,"Tres"); strcpy(arregloDos[4].numero,"Cuatro"); strcpy(arregloDos[5].numero,"Cinco"); strcpy(arregloDos[6].numero,"Seis"); strcpy(arregloDos[7].numero,"Siete"); strcpy(arregloDos[8].numero,"Ocho"); strcpy(arregloDos[9].numero,"Nueve"); int i; int j; for (i = 0; i < 10; ++i) { for (j = 0; j < 4; j++) { if(i==0){ char nombreArchivo[100]; strcpy(nombreArchivo,arregloDos[i].numero); strcat(nombreArchivo,arreglo[j].color); strcat(nombreArchivo,".txt"); //puts(nombreArchivo); char final[100]; sprintf(final,"%s%s",dirMazo,nombreArchivo); FILE* archivo=fopen(final,"w"); fclose(archivo); }else{ //printf("i es %d\n",i); //printf("mi numero es %s\n",arregloDos[i].numero); char nombreArchivo[100]; char nombreArchivo2[100]; strcpy(nombreArchivo,arregloDos[i].numero); strcat(nombreArchivo,arreglo[j].color); strcpy(nombreArchivo2,nombreArchivo); strcat(nombreArchivo,".txt"); //puts(nombreArchivo); char final[100]; sprintf(final,"%s%s",dirMazo,nombreArchivo); FILE* archivo=fopen(final,"w"); fclose(archivo); strcat(nombreArchivo2,"2"); strcat(nombreArchivo2,".txt"); //puts(nombreArchivo2); char final2[100]; sprintf(final2,"%s%s",dirMazo,nombreArchivo2); FILE* archivo2=fopen(final2,"w"); fclose(archivo2); } } } //creamos los +2 de cada color for (i = 0; i < 4; i++) { char nombreArchivo[100]; char nombreArchivo2[100]; strcpy(nombreArchivo,"+2"); strcpy(nombreArchivo2,"+2"); strcat(nombreArchivo,arreglo[i].color); strcat(nombreArchivo2,arreglo[i].color); strcat(nombreArchivo2,"2"); strcat(nombreArchivo2,".txt"); strcat(nombreArchivo,".txt"); char final[100]; sprintf(final,"%s%s",dirMazo,nombreArchivo); FILE* archivo=fopen(final,"w"); fclose(archivo); char final2[100]; sprintf(final2,"%s%s",dirMazo,nombreArchivo2); FILE* archivo2=fopen(final2,"w"); fclose(archivo2); } //creamos los reversas for (i = 0; i < 4; i++) { char nombreArchivo[100]; char nombreArchivo2[100]; strcpy(nombreArchivo,"Reversa"); strcpy(nombreArchivo2,"Reversa"); strcat(nombreArchivo,arreglo[i].color); strcat(nombreArchivo2,arreglo[i].color); strcat(nombreArchivo2,"2"); strcat(nombreArchivo2,".txt"); strcat(nombreArchivo,".txt"); char final[100]; char final2[100]; sprintf(final,"%s%s",dirMazo,nombreArchivo); sprintf(final2,"%s%s",dirMazo,nombreArchivo2); FILE* archivo=fopen(final,"w"); FILE* archivo2=fopen(final2,"w"); fclose(archivo); fclose(archivo2); } //creamos las cartas de salto for (i = 0; i < 4; i++) { char nombreArchivo[100]; char nombreArchivo2[100]; strcpy(nombreArchivo,"Salto"); strcpy(nombreArchivo2,"Salto"); strcat(nombreArchivo,arreglo[i].color); strcat(nombreArchivo2,arreglo[i].color); strcat(nombreArchivo2,"2"); strcat(nombreArchivo2,".txt"); strcat(nombreArchivo,".txt"); char final[100]; char final2[100]; sprintf(final,"%s%s",dirMazo,nombreArchivo); sprintf(final2,"%s%s",dirMazo,nombreArchivo2); FILE* archivo=fopen(final,"w"); FILE* archivo2=fopen(final2,"w"); fclose(archivo); fclose(archivo2); } //creamos las cartas Colores negras FILE* archivo4=fopen("mazo/ColoresNegro1.txt","w"); FILE* archivo3=fopen("mazo/ColoresNegro2.txt","w"); FILE* archivo2=fopen("mazo/ColoresNegro3.txt","w"); FILE* archivo1=fopen("mazo/ColoresNegro4.txt","w"); fclose(archivo1); fclose(archivo2); fclose(archivo3); fclose(archivo4); //creamos las cartas +4 negras FILE* archivo5=fopen("mazo/+4Negra1.txt","w"); FILE* archivo6=fopen("mazo/+4Negra2.txt","w"); FILE* archivo7=fopen("mazo/+4Negra3.txt","w"); FILE* archivo8=fopen("mazo/+4Negra4.txt","w"); fclose(archivo5); fclose(archivo6); fclose(archivo7); fclose(archivo8); } char *Wild(){ int opcionWild; printf("Escoge el color\n\n"); printf("(0) Rojo\n"); printf("(1) Azul\n"); printf("(2) Amarillo\n"); printf("(3) Verde\n"); scanf("%d", &opcionWild); if(opcionWild==0){ printf("Se ha cambiado el color a: Rojo\n"); return "CartaRojo"; } if(opcionWild==1){ printf("Se ha cambiado el color a: Azul\n"); return "CartaAzul"; } if(opcionWild==2){ printf("Se ha cambiado el color a: Amarillo\n"); return "CartaAmarillo"; } if(opcionWild==3){ printf("Se ha cambiado el color a: Verde\n"); return "CartaVerde"; } } void Reverse(){ printf("Alteraste el orden mundial, turno del jugador anterior.\n"); } void Mas4(int jugador){ int cont, i, r; int min=2; int cantMazo = 0; DIR *d =opendir("mazo"); if (d == NULL){ printf("ERROR FATAL: No se pudo abrir el directorio.\n"); exit(1); } struct dirent *sd; while((sd = readdir(d)) != NULL){ cantMazo ++; } while(cont < 4){ r = (rand() % (cantMazo + 1 - min)) + min; i = 0; while((sd = readdir(d)) != NULL){ if(r == i){ crearArchivo(jugador, sd-> d_name); removerDeMazo(sd->d_name); cantMazo -= 1; } i++; } cont++; } printf("Sacas 4 cartas y tu turno se ha saltado al del siguiente jugador.\n"); } void Skip(){ printf("El siguiente jugador no juega\n"); } void Mas2(int jugador){ int cont, i, r; int min = 2; int cantMazo = 0; DIR *d; d =opendir("mazo"); if (d == NULL){ printf("No se pudo abrir el directorio.\n"); exit(1); } struct dirent *sd; while((sd = readdir(d)) != NULL){ cantMazo ++; } while(cont < 2){ r = (rand() % (cantMazo + 1 - min)) + min; i = 0; while( (sd = readdir(d)) != NULL){ if(r == i){ crearArchivo(jugador, sd-> d_name); removerDeMazo(sd->d_name); cantMazo -= 1; } i++; } cont++; } printf("El jugador que sigue saca 2 cartas y su turno se ha saltado al del siguiente jugador.\n"); } //Tira la carta escogida por el jugador y realiza una accion si es que es una carta especial. char *tirarCarta(char carta[], char cartaJuego[]){ //carta: la que queri tirar y cartaJuego: la que esta en mesa char primerosDosChar[3]; for (int i = 0; i < 2; i++) { primerosDosChar[i]=carta[i]; } primerosDosChar[2]='\0'; if(strcmp(primerosDosChar,"+2") == 0){ Mas2(1); return strcpy(cartaJuego, carta); } else if( strcmp(primerosDosChar,"+4") == 0){ Mas4(1); return strcpy(cartaJuego, carta); } else if(strcmp(primerosDosChar,"Co")==0){ return strcpy(cartaJuego,Wild()); } else if(strcmp(primerosDosChar, "Re")==0){ Reverse(); } else if(strcmp(primerosDosChar, "Sa")==0){ Skip(); return strcpy(cartaJuego, carta); } else{ return strcpy(cartaJuego, carta); } } int ValidarJugada(char carta[], char elegida[]){ //elegida es la carta que tiras //siempre: +4, cambio color. char primerosDosChar[3]; for (int i = 0; i < 2; i++) { primerosDosChar[i]=elegida[i]; } primerosDosChar[2]='\0'; if (strcmp(primerosDosChar,"+4")==0) { //caso carta +4 return 1; } if (strcmp(primerosDosChar,"Co")==0) { //caso carta Colores return 1; } if( (strcmp(primerosDosChar,"Un")==0) || (strcmp(primerosDosChar,"Do")==0) ){ char color[5]; int j=0; for (int i = 3; i <7; i++) { color[j]=elegida[i]; j+=1; } int M = strlen(color); int N = strlen(carta); for (int i = 0; i <= N - M; i++) { int j; for (j = 0; j < M; j++) if (carta[i + j] != color[j]) break; if (j == M) return 1; } } if( (strcmp(primerosDosChar,"Tr")==0) || (strcmp(primerosDosChar,"Se")==0) || (strcmp(primerosDosChar,"Oc")==0) || (strcmp(primerosDosChar,"Ce")==0) ){ char color[5]; int j=0; for (int i = 4; i <8; i++) { color[j]=elegida[i]; j+=1; } int M = strlen(color); int N = strlen(carta); for (int i = 0; i <= N - M; i++) { int j; for (j = 0; j < M; j++) if (carta[i + j] != color[j]) break; if (j == M) return 1; } } if( (strcmp(primerosDosChar,"Si")==0) || (strcmp(primerosDosChar,"Ci")==0) || (strcmp(primerosDosChar,"Nu")==0) || (strcmp(primerosDosChar,"Sa")==0) || (strcmp(primerosDosChar,"Ca")==0)){ char color[5]; int j=0; for (int i = 5; i <9; i++) { color[j]=elegida[i]; j+=1; } int M = strlen(color); int N = strlen(carta); for (int i = 0; i <= N - M; i++) { int j; for (j = 0; j < M; j++) if (carta[i + j] != color[j]) break; if (j == M) return 1; } } if (strcmp(primerosDosChar,"Cu")==0) { char color[5]; int j=0; for (int i = 6; i <10; i++) { color[j]=elegida[i]; j+=1; } int M = strlen(color); int N = strlen(carta); for (int i = 0; i <= N - M; i++) { int j; for (j = 0; j < M; j++) if (carta[i + j] != color[j]) break; if (j == M) return 1; } } if ((strcmp(primerosDosChar,"Re")==0)) { char color[5]; int j=0; for (int i = 7; i <11; i++) { color[j]=elegida[i]; j+=1; } int M = strlen(color); int N = strlen(carta); for (int i = 0; i <= N - M; i++) { int j; for (j = 0; j < M; j++) if (carta[i + j] != color[j]) break; if (j == M) return 1; } } if ((strcmp(primerosDosChar,"+2")==0)) { char color[5]; int j=0; for (int i = 2; i <6; i++) { color[j]=elegida[i]; j+=1; } int M = strlen(color); int N = strlen(carta); for (int i = 0; i <= N - M; i++) { int j; for (j = 0; j < M; j++) if (carta[i + j] != color[j]) break; if (j == M) return 1; } } if(strcmp(primerosDosChar,"+2")==0){ //caso +2 == +2 for (int i = 0; i < 2; i++) { primerosDosChar[i]=carta[i]; } primerosDosChar[2]='\0'; if (strcmp(carta,"+2")==0) { return 1; } } if(strcmp(primerosDosChar, "Re")==0){ for (int i = 0; i < 2; i++) { primerosDosChar[i]=carta[i]; } primerosDosChar[2]='\0'; if (strcmp(carta,"Re")==0) { return 1; } } if(strcmp(primerosDosChar, "Sa") == 0){ for (int i = 0; i < 2; i++) { primerosDosChar[i]=carta[i]; } primerosDosChar[2]='\0'; if (strcmp(carta,"Sa")==0) { return 1; } } return 0; } int main(int argc, char const *argv[]) { printf(" BIENVENIDOS A UNO\n\n"); struct stat verificar = {0}; int i, j,r,cantJ, opcion; int turno =1; DIR *d; DIR *j1, *j2, *j3, *j4; struct dirent *sd; struct dirent *cartas; char carta[100]; char cartaJugador[100]; char elegida[100]; int cont=0; int max=109; int min=2; srand (time(NULL)); //aqui verificamos si existe la carpeta mencionada, si no existe, se crea if (stat("mazo", &verificar) == -1) { mkdir("mazo", 0777); } if (stat("jugador1", &verificar) == -1) { mkdir("jugador1", 0777); } if (stat("jugador2", &verificar) == -1) { mkdir("jugador2", 0777); } if (stat("jugador3", &verificar) == -1) { mkdir("jugador3", 0777); } if (stat("jugador4", &verificar) == -1) { mkdir("jugador4", 0777); } //se crean las cartas dentro de la carpeta mazo crearCartas(); //repartir cartas while(cont<4){ j=0; while(j<7){ i=0; r = (rand() % (max + 1 - min)) + min; //random entre min y max incluidos d=opendir("mazo");//abrimos el directorio en el que nos encontramos (en este caso Mazo) if(d==NULL){ printf("ERROR FATAL: No se pudo abrir el directorio\n"); exit(1); } //iteramos sobre los archivos del directorio que abrimos while( (sd=readdir(d)) != NULL ){ if(r==i){ //movemos el archivo random al jugador correspondiente if (cont==0) { crearArchivo(1,sd->d_name); removerDeMazo(sd->d_name); } if (cont==1) { crearArchivo(2,sd->d_name); removerDeMazo(sd->d_name); } if (cont==2) { crearArchivo(3,sd->d_name); removerDeMazo(sd->d_name); } if (cont==3) { crearArchivo(4,sd->d_name); removerDeMazo(sd->d_name); } } i+=1; } j+=1; max=max-1; } cont+=1; } printf("Cartas repartidas: A jugar\n" ); while(max > 0){//para que el juego siga mientras hayan cartas en el mazo printf("TURNO: %d\n",turno); //sacar la carta inicial para empezar el juego if(turno == 1){ i=0; r = (rand() % (max + 1 - min)) + min; d=opendir("mazo"); while((cartas = readdir(d)) != NULL){ if(r ==i){ strcpy(carta,cartas->d_name); removerDeMazo(cartas->d_name); max=max-1; } i++; } printf("Carta en mesa: %s\n", carta); printf("Es tu turno!, que carta quieres jugar?\n"); j1=opendir("jugador1"); cantJ = 1; while((cartas=readdir(j1)) != NULL){ strcpy(cartaJugador,cartas->d_name); if(strcmp(cartaJugador,".") != 0 && strcmp(cartaJugador,"..") != 0){ printf("(%d) %s\n",cantJ,cartaJugador); cantJ++; } } printf("(0) Sacar carta del mazo.\n"); printf("(432) Salir del juego.\n"); //este print muestra la carta superior que esta en la seccion de juego printf("Elige la opcion que deseas jugar:"); scanf("%d", &opcion); if (opcion == 432){ exit(1); } if (opcion == 0){ //IF PARA SACAR UNA CARTA DEL MAZO i=0; r = (rand() % (max + 1 - min)) + min; //random entre min y max incluidos d=opendir("mazo");//abrimos el directorio en el que nos encontramos (en este caso Mazo) if(d==NULL){ printf("ERROR FATAL: No se pudo abrir el directorio\n"); exit(1); } //iteramos sobre los archivos del directorio que abrimos while( (sd=readdir(d)) != NULL ){ if(r==i){ //movemos el archivo random al jugador correspondiente crearArchivo(1,sd->d_name); removerDeMazo(sd->d_name); } i+=1; } max=max-1; } else{ i=0; j1=opendir("jugador1"); while((cartas = readdir(j1)) != NULL){ if((opcion +1) == i){ strcpy(elegida,cartas->d_name); } i++; } printf("Has decidido jugar la carta: %s\n",elegida); int SePuedeOno=ValidarJugada(carta, elegida); //carta es la que está encima en juego, y elegida es la carta que quiere tirar el jugador if (SePuedeOno==1){ tirarCarta(elegida,carta); removerDeMano(elegida,1); } else{ printf("No puedes jugar esa carta, por favor escoge otra o saca una del mazo.\n"); } } turno+=1; }else{ printf("Carta en mesa: %s\n", carta); printf("Es tu turno!, que carta quieres jugar?\n"); j1=opendir("jugador1"); cantJ = 1; while((cartas=readdir(j1)) != NULL){ strcpy(cartaJugador,cartas->d_name); if(strcmp(cartaJugador,".") != 0 && strcmp(cartaJugador,"..") != 0){ printf("(%d) %s\n",cantJ,cartaJugador); cantJ++; } } printf("(0) Sacar carta del mazo.\n"); printf("(432) Salir del juego.\n"); //este print muestra la carta superior que esta en la seccion de juego printf("Elige la opcion que deseas jugar:"); scanf("%d", &opcion); if (opcion == 432){ exit(1); } if (opcion == 0){ //IF PARA SACAR UNA CARTA DEL MAZO i=0; r = (rand() % (max + 1 - min)) + min; //random entre min y max incluidos d=opendir("mazo");//abrimos el directorio en el que nos encontramos (en este caso Mazo) if(d==NULL){ printf("ERROR FATAL: No se pudo abrir el directorio\n"); exit(1); } //iteramos sobre los archivos del directorio que abrimos while( (sd=readdir(d)) != NULL ){ if(r==i){ //movemos el archivo random al jugador correspondiente crearArchivo(1,sd->d_name); removerDeMazo(sd->d_name); } i+=1; } max=max-1; } else{ j1=opendir("jugador1"); i=0; while((cartas = readdir(j1)) != NULL){ if((opcion +1) == i){ strcpy(elegida,cartas->d_name); } i++; } printf("Has decidido jugar la carta: %s\n",elegida); int SePuedeOno=ValidarJugada(carta, elegida); //carta es la que está encima en juego, y elegida es la carta que quiere tirar el jugador if (SePuedeOno==1){ tirarCarta(elegida,carta); removerDeMano(elegida,1); } else{ printf("No puedes jugar esa carta, por favor escoge otra o saca una del mazo.\n"); } } turno+=1; } } return 0; }
C#
UTF-8
1,022
3.15625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Configuration; // Adding a System.Configuration namespace and reference allows us to connect to the Northwind database. namespace Northwind.DataLayer.Config { public static class Settings { private static string _connectionString; public static string ConnectionString { get { if (string.IsNullOrEmpty(_connectionString)) { //Settings.cs is connecting to App.config using the conectionstring and name we assigned it. "NorthWind". //Settings.cs says to "get" our connectionstring much in the same way that a model class has fields that are assigned "{get;}" _connectionString = ConfigurationManager.ConnectionStrings["Northwind"].ConnectionString; } return _connectionString; } } } }
Markdown
UTF-8
881
2.671875
3
[]
no_license
## Setting up the virtual environemnt Run the following commands in terminal ``` pipenv --three pipenv install pipenv shell cd ./server ``` This will set-up the virtual environment for the file. ## Running the code 1. To start the database run the following command in terminal: ```npm run database``` 2. Open another terminal and run the following code: ```pipenv shell python new_parser.py -i [files in test_html] ``` ## Flow of the code #### Working of the Parser 1. Parsing of the _HTML_ files into _plain text_ file. 2. Formatting the data to feed into the model with appropriate responses. 3. The formatted data is further sent to the gpt to extract the information from the data in JSON file format. 4. The information is further processed to the server. ```python python3 new_parser.py -i [Files in parser/test_html] #Example python3 new_parser.py -i invite.html ```
Markdown
UTF-8
1,825
2.671875
3
[]
no_license
--- title: 5 questions from kendokamel author: Matt Stratton layout: post date: 2004-02-05T18:04:00+00:00 url: /life-in-general/5-questions-from-kendokamel dsq_thread_id: - 28239508 categories: - Personal --- As asked by : _1. How did you first get involved in filmmaking?_ I studied theatre at <a href="https://www.millikin.edu" title="Millikin University" target="_blank">Millikin University</a>, but did nothing with it. Until a few years ago, when Dallas and I decided it would be &#8220;fun&#8221; to make a mock-doc about the swing dancing scene. That was what start <a href="https://www.dancingwithgaia.com" title="Dancing With Gaia" target="_blank"><em>Dancing With Gaia</em></a>. I think that my love of film really came from the Cinema class I took in high school though, taught by <a href="https://www.depauw.edu/sfs/reviews_pages/r22.htm#Amelio" title="Ralph Amelio" target="_blank">Ralph J. Amelio</a>. _2. How did you first get involved in LiveJournal?_ I don&#8217;t recall how I came across it at first&#8230;I posted a couple things when I created my account, mostly about breaking up with my girlfriend at the time. Then I saw that had a link to her LJ in her AIM profile, and I said &#8220;hey, I&#8217;ve got one of those&#8221;, and started journaling again. _3. What is your favorite thing to do in your spare time?_ I&#8217;m embarassed to say that it&#8217;s watching TV. Especially stuff on **Adult Swim** on Cartoon Network. _4. What was the most daring thing you&#8217;ve ever done?_ I think it was when I went rock climbing in New Mexico when I was 16. _5. What is the airspeed velocity of an unlaiden swallow?_ According to my <a href="https://www.style.org/unladenswallow/" title="one swallow doesn't make a spring" target="_blank">research</a>, it is roughly 11 meters per second, or 24 miles an hour.
Java
UTF-8
623
3.5625
4
[]
no_license
public class RotateLeft { public static void main(String[] args) { rotateLeft(5, 4, new int[]{1, 2, 3, 4, 5}); } static void rotateLeft(int n, int k, int[] arr) { if (arr.length == 1) System.out.print(arr[0]); else if (arr.length > 1) { int amountToRotate = k % n; int[] temp = new int[n*2]; for(int i=0; i<arr.length; i++) { temp[i] = arr[i]; temp[i+n] = arr[i]; } for(int i=amountToRotate; i<amountToRotate+n; i++) System.out.print(temp[i]+" "); } } }
Markdown
UTF-8
1,227
2.953125
3
[]
no_license
# Progressive-Budget # by Merdad Karkudi # project repository link : https://github.com/mkarkuody/Progressive-Budget # Screenshots <img src="Screenshot.jpg"> # demo video link : # as a user; I want to be able to track my expenses to make sure I don't go over my budget also to be able to track my withdrawals and deposits. Objective Giving users a fast and easy way to track their money is important, but allowing them to access that information anytime is even more important.we as user sometimes do not have acces to internet and want to see our interaction without having internet. Technologies Used Javascript Node.js Express MongoDB Mongoose IndexedDB # Credits: Got help Online from : • https://www.google.com/ • www.YouTube.com • Bootstrap • MongoDB • Mangoose • Heroku Thanks to John Young my class instructor and Ben Vaagen my TA. special Thanks to Abdul Aziz my TA and Amanda Crawford My Tutor for helping me to understand the class and homework contents. # To create a Progressive-Budget using this app; Clone repository. In the directory run npm install and then type npm start. as soon as you see the Message,(App listening on PORT: 3000) you can work on your localhost and type on the save and retrieve the data.
Java
UTF-8
163
1.914063
2
[]
no_license
package com.example.jose.week1daydemo; public class SampleClass { public static void main(String[] args){ System.out.println("Hello There!"); } }
Shell
UTF-8
911
3.359375
3
[]
no_license
#!/bin/bash /bin/mkdir -p /mnt/aws-codecommit-keys while read username; do random_pass=`openssl rand -base64 10` echo $random_pass ssh-keygen -t rsa -N "${random_pass}" -C "codecommit-${username}" -f /mnt/aws-codecommit-keys/${username}-key pub_key=`cat /mnt/aws-codecommit-keys/${username}-key.pub` IFS="" key_id=`cd /mnt/aws-codecommit-keys/${username}-key;aws iam upload-ssh-public-key --user-name ${username} --ssh-public-key-body ${pub_key} --region us-east-1` ssh_key_id=`echo $key_id | awk '{print $6}'` echo $ssh_key_id echo "Username: ${username} Password: ${random_pass}" | tee -a /mnt/aws-codecommit-keys/user-pwd-credentials.txt cat > /mnt/aws-codecommit-keys/${username}-config << EOF Host git-codecommit.*.amazonaws.com User $ssh_key_id IdentityFile ~/.ssh/${username}-key EOF done < userlist.txt;
Java
UTF-8
2,608
2.734375
3
[]
no_license
package cn.lunzn.util; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import cn.lunzn.common.constant.Constant; import cn.lunzn.common.enums.CommonResultCode; import cn.lunzn.common.exception.MyRuntimeException; import cn.lunzn.model.user.Employee; /** * @author clark * 员工登录/注销处理类 */ public class StaffUtil { /** * 管理员 */ public static final Integer ROLE_ADMIN_1 = 1; /** * HR-人事 */ public static final Integer ROLE_HR_2 = 2; /** * 受保护的构造函数,静态类无需共有构造函数 */ protected StaffUtil() { } /** * 登录 * @param request HTTP请求 * @param em 员工 */ public static void seesionLogin(HttpServletRequest request, Employee em) { HttpSession httpSession = request.getSession(true); httpSession.setAttribute(Constant.SESSION_STAFF_KEY, em); } /** * 获取会话员工,如果员工未登录则会抛出异常 * @param request HTTP请求 * * @return Employee */ public static Employee seesionStaff(HttpServletRequest request) { HttpSession httpSession = request.getSession(); if (null != httpSession && null != httpSession.getAttribute(Constant.SESSION_STAFF_KEY)) { return (Employee)httpSession.getAttribute(Constant.SESSION_STAFF_KEY); } // 抛出请登录运行异常 throw new MyRuntimeException(CommonResultCode.SERVICE_BUSINESS_6011000.getCode(), CommonResultCode.SERVICE_BUSINESS_6011000.getMsg()); } /** * 获取会话员工,不抛异常 * @param request HTTP请求 * * @return Employee */ public static Employee seesionStaffNoThrow(HttpServletRequest request) { HttpSession httpSession = request.getSession(); if (null != httpSession && null != httpSession.getAttribute(Constant.SESSION_STAFF_KEY)) { return (Employee)httpSession.getAttribute(Constant.SESSION_STAFF_KEY); } return null; } /** * 注销 * @param request HTTP请求 */ public static void seesionLoginOut(HttpServletRequest request) { HttpSession httpSession = request.getSession(); if (null != httpSession) { httpSession.removeAttribute(Constant.SESSION_STAFF_KEY); } } }
C
UTF-8
147
2.796875
3
[]
no_license
#include <stdio.h> int main() { int a,b,c; scanf("%d %d %d",&a,&b,&c); printf("%d",(int)(a * 0.2 + b * 0.3 + c * 0.5)); return 0; }
JavaScript
UTF-8
338
3.21875
3
[]
no_license
char firstNotRepeatingCharacter(String s) { int[] ascii = new int[256]; for(int i = 0; i < s.length(); ++i){ int numAsc = (int) s.charAt(i); ascii[numAsc]++; } for(int x = 0; x < s.length(); ++x){ if(ascii[(int) s.charAt(x)] == 1){ return s.charAt(x); } } return '_'; }
Java
UTF-8
638
2.0625
2
[]
no_license
package com.fluidpay.sdk.models.customers; import com.fasterxml.jackson.annotation.JsonProperty; /** * response from getting all of the customer's address tokens */ public class CustomerAddressesResponse { private String status; private String msg; private CustomerAddressResponseData[] data; @JsonProperty("total_count") private int totalCount; public String getStatus() { return status; } public String getMsg() { return msg; } public CustomerAddressResponseData[] getData() { return data; } public int getTotalCount() { return totalCount; } }
Ruby
UTF-8
3,671
3.984375
4
[]
no_license
require 'active_support/all' require './human.rb' require './computer.rb' class Game attr_accessor :board, :side def initialize puts "Let's play Tic Tac Toe!" set_up_game end def set_up_game create_board get_players play_game end def get_players puts "Would you like to play against a human or the computer? (Type h or c.)" opponent = gets.downcase[0] case opponent when "h" @player1 = Human.new(self) @player2 = Human.new(self) when "c" chose_starter else puts "That is not a valid choice. Please try again" get_players end end def chose_starter puts "Would you like to go first? Type y for yes, n for no, c for computer's choice." choice = gets.downcase[0] case choice when "y" @player1 = Human.new(self) @player2 = Computer.new(self) when "n" @player1 = Computer.new(self) @player2 = Human.new(self) when "c" randomize = rand(2) if randomize == 0 @player1 = Computer.new(self) @player2 = Human.new(self) else @player1 = Human.new(self) @player2 = Computer.new(self) end else puts "That is not a valid choice. Please try again" chose_starter end end def play_game @turn = 0 @winner = false while @winner == false && @turn < @side**2 print_board if @turn == (@side**2)-1 puts "It's a tie!" play_again else get_moves end @turn += 1 end end def get_moves puts "Player #{(@turn%2)+1}" if @turn % 2 == 0 @player1.move("X") else @player2.move("O") end check_for_winner end def check_for_winner board = @board.in_groups_of(side) @tally = 1 if vertical_win?(board) || horizontal_win?(board) || diagonal_win?(board) @winner = true print_board puts "Player #{(@turn%2)+1} wins!" play_again end end def vertical_win?(board) (0...@side).each do |x| (0...(@side-1)).each do |y| @tally += 1 if board[y][x] == board[y+1][x] end if check_tally == true return true end end false end def horizontal_win?(board) (0...@side).each do |y| (0...(@side-1)).each do |x| @tally += 1 if board[y][x] == board[y][x+1] end if check_tally == true return true end end false end def diagonal_win?(board) (0...(@side-1)).each do |i| @tally += 1 if board[i][i] == board[i+1][i+1] end if check_tally == true return true end (0...(@side-1)).each do |i| @tally += 1 if board[@side-(i+1)][i] == board[@side-(i+2)][i+1] end check_tally == true ? true : false end def check_tally if @tally == @side true else @tally = 1 end end def create_board puts "How big would you like the board to be? (Type 3 for 3x3, 4 for 4x4, etc. up to 9)" @side = gets.to_i if @side <= 0 || @side > 9 puts "That is not a valid board size. Please try again.\n\n" create_board end @board = (1..@side**2).to_a end def print_board board = @board.in_groups_of(side) printed_board = "\n" board.each_with_index do |row, i| row.each do |char| printed_board += char.to_s.rjust(@side**2.to_s.length, " ") end printed_board += "\n\n" end puts printed_board end def play_again puts "Play again? y/n" again = gets.downcase[0] again == "y" ? set_up_game : exit end def exit puts "Thanks for playing!" end end new_game = Game.new
JavaScript
UTF-8
897
2.65625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* * * HomePage reducer * */ import { fromJS } from 'immutable'; import { DEFAULT_ACTION, GET_PHOTOS_ERROR, GET_PHOTOS_SUCCESS, GET_PHOTOS_REQUEST, SET_PHOTOS } from './constants'; const initialState = fromJS({ loading: false, error: null, photos: [] }); function homePageReducer(state = initialState, action) { switch (action.type) { case DEFAULT_ACTION: return state; case GET_PHOTOS_REQUEST: return state.set('loading', true) .set('error', null); case GET_PHOTOS_SUCCESS: return state.set('loading', false) .set('photos', action.photos) .set('error', null); case GET_PHOTOS_ERROR: return state.set('loading', false) .set('error', action.error); case SET_PHOTOS: return state .set('photos', action.photos) default: return state; } } export default homePageReducer;
Java
UTF-8
2,258
2.140625
2
[]
no_license
package com.cyztc.app.views.knowledge.adapter; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.cyztc.app.R; import com.cyztc.app.adapter.BaseDataAdapter; import com.cyztc.app.bean.BaseBean; import com.cyztc.app.bean.VideoBean; import com.zhy.autolayout.utils.AutoUtils; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by ywl on 2016/11/9. */ public class VideoDetailAdapter extends BaseDataAdapter{ private int type; public VideoDetailAdapter(Context context, List<? extends BaseBean> mDatas) { super(context, mDatas); } public void setType(int type) { this.type = type; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder = null; VideoBean videoBean = (VideoBean) mDatas.get(position); if(convertView == null) { convertView = mlayoutInflate.inflate(R.layout.item_video_layout, parent, false); AutoUtils.auto(convertView); viewHolder = new ViewHolder(convertView); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } viewHolder.tvName.setText(videoBean.getTitle()); viewHolder.tvRemark.setText(videoBean.getRemark()); viewHolder.tvPlayCount.setText(videoBean.getReadCount() + "播放"); if(type == 2) { viewHolder.ivImgTop.setImageResource(R.mipmap.icon_video_item_img); } else if(type == 3) { viewHolder.ivImgTop.setImageResource(R.mipmap.icon_audio_item_img); } return convertView; } public class ViewHolder { @BindView(R.id.iv_img_top) ImageView ivImgTop; @BindView(R.id.iv_img) ImageView ivImg; @BindView(R.id.tv_name) TextView tvName; @BindView(R.id.tv_remark) TextView tvRemark; @BindView(R.id.tv_playcount) TextView tvPlayCount; ViewHolder(View view) { ButterKnife.bind(this, view); } } }
Java
UTF-8
1,299
1.84375
2
[]
no_license
package com.kayak.qa.pages; import com.kayak.qa.util.TestBase; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; public class SearchPage extends TestBase { @FindBy(xpath="//div[@class='js-selection _iaf _idA _idj _iai _ia4 _iiM _ibc _ia2 _ia- _ia7 _im4 _kaF _iac _idf _idG _iej _ixV _ixW _irF _iVK _ic2 _ibH _igO _kaG _kaH _ia3 _Hl _ia6 _j0 _ibb _jT _jU _ia9 _jZ _jY']//div[@class='js-selection-display _id7 _ii0 _iir _iQe _kaM _ic2 _ic3'][contains(text(),'San Francisco (SFO)')]") static WebElement origin; @FindBy(xpath="//div[@class='js-selection _iaf _idA _idj _iai _ia4 _iiM _ibc _ia2 _ia- _ia7 _im4 _kaF _iac _idf _idG _iej _ixV _ixW _irF _iVK _ic2 _ibH _igO _kaG _kaH _ia3 _Hl _ia6 _j0 _ibb _jT _jU _ia9 _jZ _jY']//div[@class='js-selection-display _id7 _ii0 _iir _iQe _kaM _ic2 _ic3'][contains(text(),'New York (JFK)')]") static WebElement destination; //Initializing the Page Objects: public SearchPage() { PageFactory.initElements(driver, this); } //Actions public String validateLoginPageTitle() { return driver.getTitle(); } public static boolean verifyOrigin() { return origin.isDisplayed(); } public static boolean verifyDestination() { return destination.isDisplayed(); } }
Java
UTF-8
110
1.75
2
[]
no_license
package com.xworkz.equals.object_method; public enum BagColor { BLUE,BROWN,BLACK,GREEN,RED,YELLOW; }
Java
UTF-8
15,338
1.6875
2
[ "MIT" ]
permissive
package com.sciome.bmdexpress2.service; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.commons.math3.util.Precision; import com.sciome.bmdexpress2.mvp.model.DoseResponseExperiment; import com.sciome.bmdexpress2.mvp.model.IStatModelProcessable; import com.sciome.bmdexpress2.mvp.model.info.AnalysisInfo; import com.sciome.bmdexpress2.mvp.model.prefilter.PrefilterResults; import com.sciome.bmdexpress2.mvp.model.probe.ProbeResponse; import com.sciome.bmdexpress2.mvp.model.probe.Treatment; import com.sciome.bmdexpress2.mvp.model.stat.BMDResult; import com.sciome.bmdexpress2.mvp.model.stat.ExponentialResult; import com.sciome.bmdexpress2.mvp.model.stat.GCurvePResult; import com.sciome.bmdexpress2.mvp.model.stat.HillResult; import com.sciome.bmdexpress2.mvp.model.stat.PolyResult; import com.sciome.bmdexpress2.mvp.model.stat.PowerResult; import com.sciome.bmdexpress2.mvp.model.stat.ProbeStatResult; import com.sciome.bmdexpress2.mvp.model.stat.StatResult; import com.sciome.bmdexpress2.serviceInterface.IBMDAnalysisService; import com.sciome.bmdexpress2.shared.BMDExpressProperties; import com.sciome.bmdexpress2.util.bmds.BMDSTool; import com.sciome.bmdexpress2.util.bmds.IBMDSToolProgress; import com.sciome.bmdexpress2.util.bmds.ModelInputParameters; import com.sciome.bmdexpress2.util.bmds.ModelSelectionParameters; import com.sciome.bmdexpress2.util.bmds.shared.StatModel; import com.sciome.bmdexpress2.util.curvep.CurvePProcessor; import com.sciome.bmdexpress2.util.curvep.GCurvePInputParameters; public class BMDAnalysisService implements IBMDAnalysisService { BMDSTool bMDSTool; boolean cancel = false; /* * Run parametric bmd analylsis via epa models on processable data */ @Override public BMDResult bmdAnalysis(IStatModelProcessable processableData, ModelInputParameters inputParameters, ModelSelectionParameters modelSelectionParameters, List<StatModel> modelsToRun, String tmpFolder, IBMDSToolProgress progressUpdater) { inputParameters.setObservations( processableData.getProcessableDoseResponseExperiment().getTreatments().size()); bMDSTool = new BMDSTool(processableData.getProcessableProbeResponses(), processableData.getProcessableDoseResponseExperiment().getTreatments(), inputParameters, modelSelectionParameters, modelsToRun, progressUpdater, processableData, tmpFolder); BMDResult bMDResults = bMDSTool.bmdAnalyses(); // someone canceled this. so just uncancel it before returning. if (cancel) cancel = false; if (bMDResults == null) return null; DoseResponseExperiment doseResponseExperiment = processableData .getProcessableDoseResponseExperiment(); bMDResults.setDoseResponseExperiment(doseResponseExperiment); if (processableData instanceof PrefilterResults) bMDResults.setPrefilterResults((PrefilterResults) processableData); List<ProbeResponse> responses = processableData.getProcessableProbeResponses(); List<Treatment> treatments = doseResponseExperiment.getTreatments(); List<ArrayList<Float>> numericMatrix = new ArrayList<ArrayList<Float>>(); List<Float> doseVector = new ArrayList<Float>(); // Fill numeric matrix for (int i = 0; i < responses.size(); i++) { numericMatrix.add((ArrayList<Float>) responses.get(i).getResponses()); } // Fill doseVector for (int i = 0; i < treatments.size(); i++) { doseVector.add(treatments.get(i).getDose()); } Set<String> doseGroups = new HashSet<>(); for (Float dose : doseVector) doseGroups.add(dose.toString()); // Calculate and set wAUC values if (doseGroups.size() > 2) { // float currBMR = (float) inputParameters.getBmrLevel(); List<Float> wAUCList = new ArrayList<Float>(); for (int i = 0; i < responses.size(); i++) { StatResult stat = bMDResults.getProbeStatResults().get(i).getBestStatResult(); if (stat == null) { wAUCList.add(0.0f); continue; } // below, wAUC metric is calculated based on parametric curves, as such, values will differ // from gcurvep-based estimates List<Float> udoses = CurvePProcessor.CollapseDoses(doseVector); List<Float> logudoses = new ArrayList<Float>(); try { logudoses = CurvePProcessor.logBaseDoses(udoses, -24); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } /* * String CurrID = doseResponseExperiment.getProbeResponses().get(1).getProbe().getId(); if * (CurrID.equals("1367733_at")) { List<Float> uu = CurvePProcessor.CollapseDoses( doseVector * ); int ll = uu.size(); CurrID = Integer.toString(ll); } */ int type = -1; // unknown parametric curve type if (stat instanceof PolyResult) type = 0; // if(stat instanceof LogarithmicResult) type = 10; //reserved for future if (stat instanceof PowerResult) type = 20; if (stat instanceof HillResult) type = 30; if (stat instanceof ExponentialResult) type = 40 + ((ExponentialResult) stat).getOption(); List<Float> coffs = new ArrayList<Float>(); double[] dcoffs = stat.getCurveParameters(); for (int nn = 0; nn < dcoffs.length; nn++) { coffs.add((float) dcoffs[nn]); } float aucv = CurvePProcessor.intg_log_AUC(udoses, stat, type, -24, 1000); // better implement // and use // getResponseAt() // inside // StatResult // class instead // of exporting & // re0importing // model pars // */ // float aucv = CurvePProcessor.calc_AUC( logudoses, // CurvePProcessor.calc_WgtAvResponses(doseVector, numericMatrix.get(i)) ); float ww = CurvePProcessor.calc_wAUC(aucv, (float) Math.log10(stat.getBMD()), logudoses); wAUCList.add(ww); } bMDResults.setwAUC(wAUCList); // Calculate and set log 2 wAUC values List<Float> logwAUCList = CurvePProcessor.logwAUC(wAUCList); bMDResults.setLogwAUC(logwAUCList); } // clean up any leftovers from this process bMDSTool.cleanUp(); return bMDResults; } @Override public boolean cancel() { cancel = true; if (bMDSTool != null) { bMDSTool.cancel(); return true; } return false; } /* * Run GcurveP on the proccessable data given * */ @Override public BMDResult bmdAnalysisGCurveP(IStatModelProcessable processableData, GCurvePInputParameters inputParameters, IBMDSToolProgress me) { BMDResult bMDResults = new BMDResult(); DoseResponseExperiment doseResponseExperiment = processableData .getProcessableDoseResponseExperiment(); bMDResults.setDoseResponseExperiment(doseResponseExperiment); if (processableData instanceof PrefilterResults) bMDResults.setPrefilterResults((PrefilterResults) processableData); List<ProbeResponse> responses = processableData.getProcessableProbeResponses(); List<Treatment> treatments = doseResponseExperiment.getTreatments(); List<ArrayList<Float>> numericMatrix = new ArrayList<ArrayList<Float>>(); List<Float> doseVector = new ArrayList<Float>(); // Fill numeric matrix for (int i = 0; i < responses.size(); i++) numericMatrix.add((ArrayList<Float>) responses.get(i).getResponses()); // Fill doseVector for (int i = 0; i < treatments.size(); i++) doseVector.add(treatments.get(i).getDose()); /* do the gcurvep processing here! */ /* * String CurrID = doseResponseExperiment.getProbeResponses().get(1).getProbe().getId(); if * (CurrID.equals("1370387_at")) { //dbg int dd = 0; CurrID = Integer.toString(dd); }// */ List<ProbeStatResult> probeStatResults = new ArrayList<>(); for (int i = 0; i < responses.size(); i++) { // someone canceled the process if (cancel) { cancel = false; return null; } List<Float> correctedPointsMinus = new ArrayList<>(); List<Float> correctedPointsPlus = new ArrayList<>(); // List<Float> correctedPointsNeutral = new ArrayList<>(); /* * Supply BMR directly into CurveP calls! 07.16.2019 */ List<Float> collapsedDoses = CurvePProcessor.CollapseDoses(doseVector); Float firstNonControlDose = collapsedDoses.get(1); if (inputParameters.getControlDoseAdjustment() != null) firstNonControlDose *= inputParameters.getControlDoseAdjustment().floatValue(); else firstNonControlDose *= collapsedDoses.get(1) / collapsedDoses.get(2); Float firstNonControlDoseLogged10 = new Float(Math.log10(firstNonControlDose.doubleValue())); List<Float> weightedAvgs = CurvePProcessor.calc_WgtAvResponses(doseVector, numericMatrix.get(i)); List<Float> weightedStdDeviations = CurvePProcessor.calc_WgtSdResponses(doseVector, numericMatrix.get(i)); float BMR_neg = CurvePProcessor.calc_PODR_bySD(weightedAvgs.get(0), weightedStdDeviations.get(0), -inputParameters.getBMR()); float BMR_poz = CurvePProcessor.calc_PODR_bySD(weightedAvgs.get(0), weightedStdDeviations.get(0), inputParameters.getBMR()); List<Float> valuesMinus = CurvePProcessor.curvePcorr(doseVector, numericMatrix.get(i), correctedPointsMinus, BMR_neg, -1, inputParameters.getBootStraps(), inputParameters.getpValueCutoff(), firstNonControlDoseLogged10); List<Float> valuesPlus = CurvePProcessor.curvePcorr(doseVector, numericMatrix.get(i), correctedPointsPlus, BMR_poz, 1, inputParameters.getBootStraps(), inputParameters.getpValueCutoff(), firstNonControlDoseLogged10); List<Float> values = valuesPlus; List<Float> correctedPoints = correctedPointsPlus; int mono = 1; boolean allgoodminus = Double.isFinite(valuesMinus.get(5).doubleValue()) && Double.isFinite(valuesMinus.get(4).doubleValue()) && Double.isFinite(valuesMinus.get(6).doubleValue()) && !Double.isNaN(valuesMinus.get(5).doubleValue()) && !Double.isNaN(valuesMinus.get(4).doubleValue()) && !Double.isNaN(valuesMinus.get(6).doubleValue()); boolean allgoodplus = Double.isFinite(valuesPlus.get(5).doubleValue()) && Double.isFinite(valuesPlus.get(4).doubleValue()) && Double.isFinite(valuesPlus.get(6).doubleValue()) && !Double.isNaN(valuesPlus.get(5).doubleValue()) && !Double.isNaN(valuesPlus.get(4).doubleValue()) && !Double.isNaN(valuesPlus.get(6).doubleValue()); // first choose the direction where fitpvalue is not 0.0 if (valuesMinus.get(0).doubleValue() == 0.0 && valuesPlus.get(0).doubleValue() != 0.0) { values = valuesPlus; correctedPoints = correctedPointsPlus; mono = 1; } else if (valuesPlus.get(0).doubleValue() == 0.0 && valuesMinus.get(0).doubleValue() != 0.0) { mono = -1; values = valuesMinus; correctedPoints = correctedPointsMinus; } // then after fit pvalue choose the one with convergence on bmdl/bmd/bmdu else if (allgoodminus && !allgoodplus) { mono = -1; values = valuesMinus; correctedPoints = correctedPointsMinus; } else if (!allgoodminus && allgoodplus) { values = valuesPlus; correctedPoints = correctedPointsPlus; mono = 1; } // if all converge, and there is a pvalue != 0.0, pick best fit (fraction of saved signal), as the // direction else if (valuesPlus.get(0).doubleValue() < valuesMinus.get(0).doubleValue()) {// ..choose mono = -1; values = valuesMinus; correctedPoints = correctedPointsMinus; } List<Float> correctedPointsOffsets = new ArrayList<>(); for (int j = 0; j < numericMatrix.get(i).size(); j++) correctedPointsOffsets.add(numericMatrix.get(i).get(j) - correctedPoints.get(j)); ProbeStatResult psR = new ProbeStatResult(); GCurvePResult gResult = new GCurvePResult(); gResult.setFitPValue(values.get(0).doubleValue()); gResult.setAIC(Double.NaN); gResult.setCorrectedDoseResponseOffsetValues(correctedPointsOffsets); gResult.setCurveParameters(null); gResult.setFitLogLikelihood(Double.NaN); gResult.setSuccess("true"); gResult.setBMDL(Math.pow(10.0, values.get(4).doubleValue())); gResult.setBMD(Math.pow(10.0, values.get(5).doubleValue())); gResult.setBMDU(Math.pow(10.0, values.get(6).doubleValue())); gResult.setBMDLauc(values.get(1).doubleValue()); gResult.setBMDauc(values.get(2).doubleValue()); gResult.setBMDUauc(values.get(3).doubleValue()); gResult.setBMDLwAuc(values.get(7).doubleValue()); gResult.setBMDwAuc(values.get(8).doubleValue()); gResult.setBMDUwAuc(values.get(9).doubleValue()); gResult.setAdjustedControlDoseValue(firstNonControlDose.doubleValue()); if (mono > 0) gResult.setBmr(BMR_poz); else gResult.setBmr(BMR_neg); gResult.setWeightedAverages(weightedAvgs); gResult.setWeightedStdDeviations(weightedStdDeviations); gResult.setAdverseDirection((short) mono); psR.setBestPolyStatResult(null); psR.setBestPolyStatResult(null); psR.setBestStatResult(gResult); psR.setChiSquaredResults(null); psR.setProbeResponse(responses.get(i)); psR.setStatResults(new ArrayList<>(Arrays.asList(gResult))); probeStatResults.add(psR); float percentComplete = (float) i / (float) processableData.getProcessableProbeResponses().size(); me.updateProgress("Progress: " + Precision.round(100 * percentComplete, 2) + "% complete for " + processableData.getDataSetName(), percentComplete); } bMDResults.setName(processableData.toString() + "_SciomeGCurveP"); bMDResults.setProbeStatResults(probeStatResults); if (processableData instanceof PrefilterResults) bMDResults.setPrefilterResults((PrefilterResults) processableData); bMDResults.setDoseResponseExperiment(processableData.getProcessableDoseResponseExperiment()); bMDResults.setwAUC(null); bMDResults.setLogwAUC(null); AnalysisInfo analysisInfo = new AnalysisInfo(); analysisInfo.setNotes(new ArrayList<>()); analysisInfo.getNotes().add("Benchmark Dose Analyses With Sciome GCurveP"); analysisInfo.getNotes().add("Data Source: " + processableData.getParentDataSetName()); analysisInfo.getNotes().add("Work Source: " + processableData.toString()); analysisInfo.getNotes() .add("BMDExpress2 Version: " + BMDExpressProperties.getInstance().getVersion()); analysisInfo.getNotes() .add("Timestamp (Start Time): " + BMDExpressProperties.getInstance().getTimeStamp()); analysisInfo.getNotes().add("Operating System: " + System.getProperty("os.name")); analysisInfo.getNotes().add("Number of bootstraps: " + inputParameters.getBootStraps()); analysisInfo.getNotes().add("BMR: " + inputParameters.getBMR()); analysisInfo.getNotes().add("pValue for intervals: " + inputParameters.getpValueCutoff()); if (inputParameters.getControlDoseAdjustment() != null) analysisInfo.getNotes() .add("Control Dose Adjustment: " + inputParameters.getControlDoseAdjustment()); bMDResults.setAnalysisInfo(analysisInfo); return bMDResults; } }
SQL
UTF-8
6,113
2.859375
3
[]
no_license
-- MySQL dump 10.13 Distrib 5.7.17, for Win64 (x86_64) -- -- Host: 127.0.0.1 Database: ezeebizdb -- ------------------------------------------------------ -- Server version 5.5.59 /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `orderitem` -- DROP TABLE IF EXISTS `orderitem`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `orderitem` ( `OrderItemID` int(5) unsigned NOT NULL AUTO_INCREMENT, `PurchaseOrder_PONumber` int(10) unsigned NOT NULL, `PurchaseOrder_Customer_CustomerID` int(10) unsigned NOT NULL, `Product_ProductID` int(5) unsigned NOT NULL, `OrderedQty` int(2) unsigned NOT NULL, PRIMARY KEY (`OrderItemID`,`PurchaseOrder_PONumber`,`PurchaseOrder_Customer_CustomerID`), KEY `fk_OrderItem_PurchaseOrder1_idx` (`PurchaseOrder_PONumber`,`PurchaseOrder_Customer_CustomerID`), KEY `fk_OrderItem_Product1_idx` (`Product_ProductID`), CONSTRAINT `fk_OrderItem_Product1` FOREIGN KEY (`Product_ProductID`) REFERENCES `product` (`ProductID`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_OrderItem_PurchaseOrder1` FOREIGN KEY (`PurchaseOrder_PONumber`, `PurchaseOrder_Customer_CustomerID`) REFERENCES `purchaseorder` (`PONumber`, `Customer_CustomerID`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `orderitem` -- LOCK TABLES `orderitem` WRITE; /*!40000 ALTER TABLE `orderitem` DISABLE KEYS */; INSERT INTO `orderitem` VALUES (1,1,1,1,10),(2,1,1,2,7),(3,2,1,1,1),(4,2,1,2,1),(5,3,1,1,3),(6,4,1,1,3),(7,5,1,1,4),(8,6,1,1,6),(9,6,1,2,6),(10,7,2,2,1); /*!40000 ALTER TABLE `orderitem` ENABLE KEYS */; UNLOCK TABLES; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; /*!50003 SET character_set_client = utf8 */ ; /*!50003 SET character_set_results = utf8 */ ; /*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = '' */ ; DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER trg_validate_orderitem_quantity BEFORE INSERT ON orderitem FOR EACH ROW BEGIN -- get available product quantity from product table SELECT product.AvailProductQty INTO @availprodqty FROM product WHERE product.ProductID = NEW.Product_ProductID; -- if order item quantity is less than 0 or greater than prod qty --> error IF (NEW.orderedqty < 0) OR (NEW.orderedqty > @availprodqty) THEN SIGNAL SQLSTATE VALUE '45000' SET MESSAGE_TEXT = 'Order item quantity is invalid'; END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; /*!50003 SET character_set_client = utf8 */ ; /*!50003 SET character_set_results = utf8 */ ; /*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = '' */ ; DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER trg_reduce_product_qty AFTER INSERT ON orderitem FOR EACH ROW BEGIN UPDATE Product SET AvailProductQty = AvailProductQty - NEW.OrderedQty WHERE Product.ProductID = NEW.Product_ProductID; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; /*!50003 SET character_set_client = utf8 */ ; /*!50003 SET character_set_results = utf8 */ ; /*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = '' */ ; DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER trg_increase_product_qty AFTER DELETE ON orderitem FOR EACH ROW BEGIN UPDATE Product SET AvailProductQty = AvailProductQty + OLD.OrderedQty WHERE Product.ProductID = OLD.Product_ProductID; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2018-04-22 16:21:39
Python
UTF-8
90
2.640625
3
[]
no_license
def average_mark(*args): average = sum(args) / len(args) return round(average, 1)
JavaScript
UTF-8
2,138
3.5
4
[]
no_license
let correct = Math.round(Math.random() * 10); let retry = 3; function loadEventListeners(){ const submit = document.querySelector("#submit"); submit.addEventListener("click", handleSubmit); } const handleSubmit = ()=>{ const input = document.querySelector("#input"); if(retry > 0) { if(correct.toString() === input.value) { console.log("correct!"); input.style.cssText = 'border: 2px solid #279327;'; const result = document.querySelector(".result"); result.innerHTML = `${correct} is correct, YOU WIN!`; result.style.cssText = "color : #279327; font-weight : bold; font-size : 20px;" const submit = document.querySelector("#submit"); submit.value = "PLAY AGAIN"; retry = 0; } else{ retry--; console.log("Fail! : " + correct + " " + input.value ); input.style.cssText = 'border: 2px solid #ff1212;'; if(retry === 0){ const result = document.querySelector(".result"); result.innerHTML = `Game Over, you lost. The Correct number was ${correct}.`; result.style.cssText = "color : #ff1212; font-weight : bold; font-size : 20px;" const submit = document.querySelector("#submit"); submit.value = "PLAY AGAIN"; } else{ const result = document.querySelector(".result"); result.innerHTML = `${input.value} is not correct, ${retry} guesses left`; result.style.cssText = "color : #ff1212; font-weight : bold; font-size : 20px;" } } } else{ const submit = document.querySelector("#submit"); submit.value = "SUBMIT"; correct = Math.round(Math.random() * 10); retry = 3; input.value = ""; input.style.cssText = 'border: 1px #aaa solid'; const result = document.querySelector(".result"); result.innerHTML = ``; } } function init(){ loadEventListeners(); } init();
JavaScript
UTF-8
1,962
3.21875
3
[]
no_license
function add(a, b) { return a + b; } function sub(a, b) { return a - b; } function mul(a, b) { return a * b; } function div(a, b) { return a / b; } function operator(x, y, op) { switch (op) { case "+": return add(x, y); break; case "-": return sub(x, y); break; case "*": return mul(x, y); break; case "%": return div(x, y); break; } } function convertnum(str) { let num, firstnum, secondnum, exp; for (let i = 0; i < str.length; i++) { if (str[i] == "+") { num = i; if (num == 0) { continue; } exp = str[num]; break; } else if (str[i] == "-") { num = i; if (num == 0) { continue; } exp = str[num]; break; } else if (str[i] == "*") { num = i; if (num == 0) { continue; } exp = str[num]; break; } else if (str[i] == "%") { num = i; if (num == 0) { continue; } exp = str[num]; break; } } firstnum = parseInt(str.substr(0, num)); secondnum = parseInt(str.substr(num + 1, str.length - 1)); text.textContent = operator(firstnum, secondnum, exp); } let text = document.querySelector(".dispzero"); let btn = document.querySelectorAll(".num,.operator"); let equal = document.querySelector(".equal"); let clear = document.querySelector(".clear"); btn.forEach((element) => { element.addEventListener("click", function () { if (text.textContent == "0") { text.textContent = ""; } text.textContent += `${element.textContent}`; }); }); equal.addEventListener("click", function () { convertnum(text.textContent); }); clear.addEventListener("click", function () { text.textContent = "0"; });
Java
UTF-8
4,998
2
2
[]
no_license
package com.example.ole.oleandroid.controller; import android.content.Intent; import android.graphics.drawable.Drawable; import android.support.design.widget.TextInputEditText; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.ole.oleandroid.R; import com.example.ole.oleandroid.controller.DAO.LoginDAO; import com.example.ole.oleandroid.controller.DAO.UserDAO; import com.example.ole.oleandroid.controller.PublicLeague.SpecialList; public class ForgotPassword extends AppCompatActivity { EditText email; TextInputEditText changePassword, confirmChangePassword; Button confirmPassword; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_forgot_password); final Drawable tickDone = getResources().getDrawable(R.drawable.ic_done_black_24dp); final String from = getIntent().getStringExtra("from"); email = findViewById(R.id.email); changePassword = findViewById(R.id.changePassword); confirmChangePassword = findViewById(R.id.confirmChangePassword); confirmPassword = findViewById(R.id.confirmPassword); if (from != null) { email.setText(UserDAO.getLoginUser().getEmail()); } changePassword.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(final Editable s) { if (isStrong(s.toString())) { changePassword.setError("Good", tickDone); } else { changePassword.setError("8 or more characters \n" + "Min 1 Upper Case\n" + "Min 1 numeral (0-9)\n" + "Min 1 letter in Lower Case"); } } }); confirmChangePassword.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(final Editable s) { //System.out.println(confirmChangePassword.getText().toString() + " matches " + changePassword.getText().toString()); if (confirmChangePassword.getText().toString().equals(changePassword.getText().toString())) { confirmChangePassword.setError("Good", tickDone); } else { confirmChangePassword.setError("Does not match above password"); } } }); confirmPassword.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String inputEmail = email.getText().toString(); String password = confirmChangePassword.getText().toString(); Boolean status = LoginDAO.changePassword(inputEmail, password); if (status) { Toast.makeText(getBaseContext(), "Password change successful", Toast.LENGTH_LONG).show(); Intent intent = new Intent(ForgotPassword.this, Login.class); if (from != null) { intent = new Intent(ForgotPassword.this, Profile.class); } startActivity(intent); } else { Toast.makeText(getBaseContext(), "Password change failed", Toast.LENGTH_LONG).show(); } } }); } private boolean isStrong(String password) { return password.matches("^(?=.*[A-Z])(?=.*[0-9])(?=.*[a-z]).{8,20}$"); //return password.matches("^(?=.*[A-Z].*[A-Z])(?=.*[!@#$&*])(?=.*[0-9].*[0-9])(?=.*[a-z].*[a-z].*[a-z]).{8,20}$"); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.changepasswordtoolbar, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.close: finish(); break; } return super.onOptionsItemSelected(item); } }
JavaScript
UTF-8
1,998
3.03125
3
[]
no_license
function bin2ascii(array) { var result = []; for (var i = 0; i < array.length; ++i) { result.push(String.fromCharCode( // hex2ascii part parseInt( ('0' + (array[i] & 0xFF).toString(16)).slice(-2), // binary2hex part 16 ) )); } return result.join(''); } function bin2hex(array, length) { var result = ""; length = length || array.length; for (var i = 0; i < length; ++i) { result += ('0' + (array[i] & 0xFF).toString(16)).slice(-2); } return result; } function Where(stack){ var at = "" for(var i = 0; i < stack.length; ++i){ at += stack[i].toString() + "\n" } return at } Java.perform(function() { var ThreadDef = Java.use('java.lang.Thread') var threadinstance = ThreadDef.$new() Java.use('javax.crypto.spec.SecretKeySpec').$init.overload('[B', 'java.lang.String').implementation = function(key, spec) { send("KEY: " + bin2hex(key) + " | " + bin2ascii(key)); var stack = threadinstance.currentThread().getStackTrace() var full_call_stack = Where(stack) console.log("\r\nFull call stack:\r\n" + full_call_stack) return this.$init(key, spec); }; Java.use('javax.crypto.Cipher')['getInstance'].overload('java.lang.String').implementation = function(spec) { send("CIPHER: " + spec); var stack = threadinstance.currentThread().getStackTrace() var full_call_stack = Where(stack) console.log("\r\nFull call stack:\r\n" + full_call_stack) return this.getInstance(spec); }; Java.use('javax.crypto.Cipher')['doFinal'].overload('[B').implementation = function(data) { send("doFinal!"); send(bin2ascii(data)); var stack = threadinstance.currentThread().getStackTrace() var full_call_stack = Where(stack) console.log("\r\nFull call stack:\r\n" + full_call_stack) return this.doFinal(data); }; });
Java
UTF-8
1,370
1.898438
2
[]
no_license
package com.sabrewinginfotech.reesguru.fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.sabrewinginfotech.reesguru.MainActivity; import com.sabrewinginfotech.reesguru.R; import com.sabrewinginfotech.reesguru.constant.UrlConstant; public class SuppliersFragment extends Fragment { public SuppliersFragment() { // Required empty public constructor } public static SuppliersFragment newInstance(String param1, String param2) { SuppliersFragment fragment = new SuppliersFragment(); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment UrlConstant.fragmenttag = 5; MainActivity.ivfilter.setVisibility(View.GONE); return inflater.inflate(R.layout.fragment_suppliers, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } }
Java
UTF-8
2,682
4
4
[]
no_license
package _09_loops.java; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class _02_for { public static void main(String[] args) { // //TODO: If you've never done for loops, you will need a lot of practice. We recommend you study these // until you can do one without looking. Take a break, and then do some more. //// // for (int j = 10; j>0; j--){ // System.out.println("The value of j is: " + j + "\n"); // } // // //// // Bronze: //// Create a loop that counts from 0 to 10 and prints even for even numbers // for (int k = 0; k<=10; k++){ // if (k%2 == 0){ // System.out.println("The value of the even number is: " + k); // } else { // System.out.println("The value of the odd number is: " + k); // } // } //// // Silver: //// Create a for loop that counts the amount of vowels in a string // String vowels = "Aloha kiddee".toLowerCase(); // int vowelCount = 0; // for (int i = 0; i<vowels.length(); i++){ // switch(vowels.charAt(i)) { // case 'a': // case 'e': // case 'i': // case 'o': // case 'u': // vowelCount++; // break; // default: // } // // } // System.out.println("The string has " + vowelCount + " vowels."); // // Gold: // Create a for loop that counts the amount of vowels in a string given by a user req. input. // Scanner scan = new Scanner(System.in); // System.out.println("Please type the phrase you would like to count the vowels in"); // String vowelString = scan.nextLine(); // vowelString = vowelString.toLowerCase(); // int vowelsCount = 0; // for (int m = 0; m<vowelString.length(); m++){ // switch(vowelString.charAt(m)) { // case 'a': // case 'e': // case 'i': // case 'o': // case 'u': // vowelsCount++; // break; // default: // } // // } // System.out.println("The string has " + vowelsCount + " vowels."); // double balance = 5000; // double rate = 1.02; // for(int i=0; i<=10; i++){ // balance *= rate; // System.out.println(balance); // } String spaces = "there are some spaces in this string"; int spaceCount = 0; for(int i = 0; i < spaces.length(); i++) { if (Character.toString(spaces.charAt(i)).matches("[ ]")) { spaceCount++; } } System.out.println(spaceCount); String[] comedians = { "Bill Hader", "Dane Cook", "George Carlin", "Louis CK"}; for(String comedian : comedians){ System.out.println(comedian); } String[] greatestBossesOfAllTime = {"Jenn Aikins", "Bob Alcorn", "Robin Holer", "Aaron"}; for(String boss : greatestBossesOfAllTime){ System.out.println(boss); } String s = "hello"; for(char ch : s.toCharArray()){ System.out.println(ch); } } }
PHP
UTF-8
4,419
2.828125
3
[]
no_license
<?php defined('SYSPATH') or die('No direct script access.'); /** * Class Widget * Базовый класс виджета * Фабрика виджетов * */ class Widget { protected $_controllers_folder = 'widgets'; // Название папки с контроллерами виджетов protected $_config_filename = 'widgets'; // Название файла конфигураций виджетов protected $_route_name = 'widgets'; // Название файла конфигураций виджетов по умолчанию protected $_params = array(); // Массив передаваемых параметров protected $_widget_name; // Название виждета (контроллер) protected $_cachetime = 0; // Время кеширования (0 - без кеширования) public function __construct($widget_name, array $params = array(), $route_name = NULL) { $this->_widget_name = $widget_name; if ($params != NULL) { $this->_params = $params; } if ($route_name != NULL) { $this->_route_name = $route_name; } } /* * Вызов виджета Widget::factory('widget_name')->render(); * @param string Название виджета * @param array Массив передаваемых параметров * @param string Название роута данного виджета */ public static function factory($widget_name, array $params = array()) { return new Widget($widget_name, $params); } /* * Вызов виджета Widget::load('widget_name', array('param' => 'val'), 'route_name'); * @param string Название виджета * @param array Массив передаваемых параметров * @param string Название роута данного виджета */ public static function load($widget_name, array $params = array()) { $widget = new Widget($widget_name, $params); return $widget->render(); } /** * Кештровать вывод виджета * @param int $time - время кеширования (0 - без кеширования) * @return $this */ public function cached($time = 0){ $this->_cachetime = $time; return $this; } /** * Имя кеша для виджета * @return string */ protected function _widgetCacheName(){ return "widgetCache". $this->_widget_name; } /** * Рендер виджета * @return null|Response */ public function render() { if($this->_cachetime && ($content = Cache::instance()->get( $this->_widgetCacheName() ))){ return $content; } // Получаем текущий контроллер и экшен $controller = Request::current()->controller(); $action = Request::current()->action(); // $directory = Request::current()->directory(); // Загружаем файл конфигураций $widget_config = Kohana::$config->load("$this->_config_filename.$this->_widget_name.$controller"); // Запрещаем вывод виджета в экшенах, указанных в конфигах if ($widget_config != NULL) { if (in_array($action, $widget_config) ||in_array('all_actions', $widget_config) ) { return NULL; } } $this->_params['controller'] = $this->_widget_name; $url = Route::get($this->_route_name)->uri($this->_params); $content = Request::factory($url)->post($this->_params)->execute(); if($this->_cachetime){ Cache::instance()->set( $this->_widgetCacheName(), $content, $this->_cachetime ); } return $content; } /** * Widget parameter getter * @param $name * @return null */ public function __get($name){ if(isset($this->_params[$name])) return $this->_params[$name]; return NULL; } /** * @return string */ public function __toString(){ return (string) $this->render(); } }
C++
UTF-8
2,779
2.6875
3
[]
no_license
#ifndef __UITEXTTEST_H #define __UITEXTTEST_H #include <cxxtest/TestSuite.h> #include <UI/UIText.h> #include <ResourceManager/ResourceManager.h> #include <Renderer/SDLRenderer.h> // // A generated test suite: Just write tests! // class UITextTest : public CxxTest::TestSuite { private: // any variables that could be shared between tests UIText* testText; UIUnitTestHelp* mUIUnitTester; // Unit Tests: public: // Called before all unit tests in this suite, remove if not needed void setUp() { // Header for all UI Testing Elements Logger::GetInstance( "unitTestLog.txt" ); Logger::GetInstance()->Initialize(); SDLRenderer::GetInstance()->Initialize( 480, 320, 32 ); ResourceManager::GetInstance()->Initialize(); } // Called after all unit tests in this suite, remove if note needed void tearDown() { ResourceManager::GetInstance()->Shutdown(); SDLRenderer::GetInstance()->Shutdown(); Logger::GetInstance()->Shutdown(); } void testRenderSelf() { // Initializing Elements for test UIText* storage; UIImage* backdrop = new UIImage("testButton.png"); SDLRenderer::GetInstance()->AddToRenderQueue(backdrop); testText = new UIText(); mUIUnitTester = new UIUnitTestHelp( testText , "UIText" ); // Basic Test mUIUnitTester->RunBasicTest(); // Test default constructor storage = testText; testText = NULL; testText = new UIText("BASIC TEXT"); mUIUnitTester->SetNewElement(testText); delete storage; storage = NULL; mUIUnitTester->RunBasicTest(); SDLRenderer::GetInstance()->RemoveFromRenderQueue(backdrop); // Test 3rd constructor storage = testText; testText = NULL; testText = new UIText("DIFFERENT TEXT", 36, 0, 0, 255); mUIUnitTester->SetNewElement(testText); delete storage; storage = NULL; mUIUnitTester->RunNewTest("DIFF TEXT"); // Test operators //========= // Text testText->ChangeText("MORE TEXT"); mUIUnitTester->RunNewTest("MORE TEXT"); // Colour testText->SetColour(255, 255, 255); mUIUnitTester->RunNewTest("White"); // Size testText->SetSize(12); mUIUnitTester->RunNewTest("Small"); // Everything testText->ChangeText("New Text!!", 16, 0, 255, 0); mUIUnitTester->RunNewTest("All New Text!!"); delete mUIUnitTester; delete testText; delete backdrop; } }; #endif // __UITEXTTEST_H
C#
UTF-8
1,463
2.984375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Newton.Data { /// <summary> /// Class representing a structure key pair logger /// </summary> public abstract class StructuredLogger<T> : ILogger<T> where T : class { #region Properties private LogStructure<T> logStructure = new LogStructure<T>(); /// <summary> /// The structure of the data to be added to the log /// </summary> public LogStructure<T> LogStructure { get { return logStructure; } set { logStructure = value; } } #endregion #region Constructors /// <summary> /// Class representing a structure key pair logger /// </summary> public StructuredLogger() { LogStructure.Items.AddRange(CreateLogStructure()); } #endregion #region Methods /// <summary> /// Defines the structue of the log entries /// </summary> public virtual IEnumerable<LogStructureItem<T>> CreateLogStructure() { return new List<LogStructureItem<T>>(); } /// <summary> /// Logs an exception using an ExceptionContext on an MVC application /// </summary> public abstract void Log(T logObject); #endregion } }
Markdown
UTF-8
7,198
3.0625
3
[]
no_license
--- layout: post title: 《小狗钱钱》读书笔记 date: 2018-07-01 17:34:11.000000000 +09:00 category: Finance tags: Notes --- ## 童话与理财 如果你想富有,请把自己变成一个小孩,因为小孩子的框框最少,他们诚实、快乐、乐于学习。 ## 前言 1. 我们常常会过于迅速地得出结论:“这我已经知道了。”似乎认识几个关键词就足够了。这种想法很可能是一个陷阱,因为当我们发现对要学的东西早已熟悉时,可能就不会继续学习下去。因为我们觉得自己已经知道了,所以就对这些信息不再感兴趣。 2. 忽视财务问题,就是放弃成功的机会。财务自由是今天每个人都可能实现的目标,当然这需要我们拥有追求自己真正想要的生活的勇气。 3. 并非困难使我们放弃,而是因为我们放弃,才显得如此困难。 ## 第二章 梦想储蓄罐和梦想相册 1. 从现在开始,你必须每天把这张写着自己的愿望的单子从头到尾看一遍,它会不断地提醒你自己想要得到什么,那么你就会密切关注一切可以帮助你实现这些愿望的机遇了。 2. 好奇是好的,但是绝不能让好奇阻碍你做事。太多的人做事犹豫不决,就是因为他们觉得没有完全弄懂这件事。真正付出实践要比纯粹的思考有用多了。 3. 如果你只是抱着试试看的心态,那么你只会以失败告终,你会一事无成。“尝试”纯粹是一种借口,你还没有做,就已经给自己想好了退路。不能试验,你只有两个选择——做或者不做。 4. 要把梦想“视觉化”。成功的人之所以成功,就是因为他们一直梦想着自己成功的那一天,不停地想象着自己实现了理想时的情形。 5. 学习就是认识新观念和新想法的过程。加入人们始终以同一种思维方式来考虑问题的话,那么始终只会得到同样的结果。 ## 第三章 达瑞,一个很会挣钱的男孩 1. 你的自信程度决定了你是否相信自己的能力,是否相信你自己。加入你根本不相信你能做到的话,那么你就根本不会动手去做,而假如你不会开始去做,那么你就什么也得不到。 ## 第四章 堂兄的挣钱之道 无论在什么时候都不能把希望只寄托在一份工作上,它持续的时间不会像你设想的那么长,所以你要立即寻找另一份替代的工作。 ## 第五章 钱钱以前的主人 1. 这正是许多没有钱的人爱犯的错误。他们总是有那么多紧急的事情要做,以至于没有时间来关注重要的事情。 ## 第七章 在金先生家 1. 有的时候,疯狂的念头确实比普通的小目标更容易实现。当你定下大目标的时候,就意味着你必须付出比别人多得多的努力。 ## 第十一章 爸爸妈妈不明白 1. 勇敢的人也会害怕,一个人虽然害怕却依然敢于前进,这才叫勇敢。 ## 第十六章 俱乐部的投资行动 挑选基金时的注意事项: 1. 基金应该至少有10年历史。假如它在这么长时间内一直有丰厚的利润,那我们可以认为,未来它也会运作良好。 2. 应该选择大型的跨国股票基金。这种基金在世界各地购买股票,以此分散风险,所以十分安全。 3. 对基金的走势图进行比较。我们应该观察在过去10年间哪些基金的年终利润最好。 ## 自力更生 写给成年人的后记 1. 应该给孩子们提供机会,让他们能够多接触一下成年人的工作领域。 2. 赚钱不是一件坏事,它可以为自己和他人带来好处。从小开始赚钱的人拥有对依赖思想的抵抗力,不会乐意让别人来养活自己。而且自己赚钱的人不会成为不断膨胀的消费欲望的奴隶。从事商业活动有助于人们以理智的态度珍惜和使用有限的资源。 3. 对于孩子们层出不穷的愿望,大人们把迅速满足他们的需要当作一剂速效镇定剂。于是孩子们失去了在发展心理学中被称作进取心和承受力的能力。被宠坏的孩子缺乏应对艰难时刻的心理准备。 ## 总结 ### Step 1 梦想清单: 1. 写出十个你想变得富有的原因。 2. 把最重要的3项圈出来。 3. 每天把这张写着自己的愿望的单子从头到尾看一遍。 ### Step 2 做三件事: 1. 拿一本相册作为梦想相册。收集一些与自己的愿望有关的照片,把它们贴在相册里。我们要通过图片来思考。 2. 每天看几遍相册,然后想象着这3项目标已经实现了,还要想象达成目标(比如给爸爸妈妈买房子)后自豪的神情。 3. 准备一个梦想储蓄罐。随便拿一个罐子,然后在这个罐子上协商你的梦想,把它作为你的储蓄罐。但是要为自己的每一个梦想各准备一个储蓄罐。一旦储蓄罐准备好,就应当把剩下的每一分钱放进去。 ### Step 3 成功日记: 准备一个本子,叫“成功日记”,然后把所有做成功的事情记录进去,每天都要记录。每次至少写5条你的个人成果,任何小事都可以。开始的时候也许你觉得不太容易,可能会问自己,这件或那件事情是否真的可以算作成果。在这种情况下,你的回答应该是肯定的。过于自信比不够自信要好很多。 ### Step 4 三件重要的事情: 1. 在遇到困难的时候,仍然要坚持自己的想法。一切正常的时候,每个人都能做到这一点。只有当真正的困难出现时才能见分晓。只有少数人能坚定不移地贯彻自己的计划。那些非常成功的人,甚至有能力在他们最困难的时候作出最杰出的表现。困难总在不断地出现。尽管如此,你每天还是要不间断地去做对你的未来意义重大的事情。你为此花费的时间不会超过10分钟(比如记成功日记),但是就是这10分钟会让一切变得不同。大多数人总是在现有的水平上停滞不前,就是因为他们没有拿出这10分钟。他们总是期望情况能向有利于自己的方向转变,但是他们忽视了一点,那就是他们首先必须改变自己。 2. 在一切进展非常顺利的时候,你也应该做这些事情。 3. 72小时规定:当你决定做一件事的时候,必须在72小时内完成,否则你很可能永远不会做了。 ## 其他 ### “金钱魔术师”的理念 1. 确定自己希望获得财务上的成功。 2. 自信,有想法,做自己喜欢做的事。 3. 把钱分成日常开销、梦想目标和金鹅账户三部分。 4. 进行明智的投资。 5. 享受生活。 ### 分配收入的方式 50%收入变成 “鹅”,等待收益(投资) 40%放入梦想储蓄罐 10%用来花 ### Tips 1. 为别人解决一个难题,那么你就能赚到许多钱 2. 把精力集中在你知道的、能做的和拥有的东西上 3. 72公式:1. 计算通货膨胀:通货膨胀率约3%,按 72/3,得到24,也就是24年后,你的钱只值现在的一半;2. 计算收益:72/投资的年利率百分比,得到的数字就是这笔钱翻一倍所需要的年数。
C
UTF-8
3,716
2.65625
3
[ "Apache-2.0", "MIT" ]
permissive
#include <sightglass.h> #include <assert.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define SLOTS_LEN 100000 #define PERIOD 1000 #define PEAK 10 #define ITERATIONS 1000000 typedef struct RateLimiter_ { unsigned int *slots; uint64_t v0, v1; size_t slots_mask; size_t period; size_t pos; } RateLimiter; static int ratelimiter_init(RateLimiter *rate_limiter, size_t slots_len, size_t period, const uint8_t key[16]) { if ((rate_limiter->slots = calloc(slots_len, sizeof *rate_limiter->slots)) == NULL) { return -1; } if (period < slots_len) { period = slots_len; } rate_limiter->slots_mask = slots_len - (uint64_t)1U; rate_limiter->period = period; rate_limiter->pos = (size_t)0U; memcpy(&rate_limiter->v0, &key[0], 8); memcpy(&rate_limiter->v1, &key[8], 8); return 0; } static void ratelimiter_free(RateLimiter *rate_limiter) { free(rate_limiter->slots); memset(rate_limiter, 0, sizeof *rate_limiter); rate_limiter->slots = NULL; } #define ROTL64(X, B) rotl64((X), (B)) static inline uint64_t rotl64(const uint64_t x, const int b) { return (x << b) | (x >> (64 - b)); } #define SIPROUND \ do \ { \ v0 += v1; \ v1 = ROTL64(v1, 13); \ v1 ^= v0; \ v0 = ROTL64(v0, 32); \ v2 += v3; \ v3 = ROTL64(v3, 16); \ v3 ^= v2; \ v0 += v3; \ v3 = ROTL64(v3, 21); \ v3 ^= v0; \ v2 += v1; \ v1 = ROTL64(v1, 17); \ v1 ^= v2; \ v2 = ROTL64(v2, 32); \ } while (0) static void ratelimiter_hashes(uint64_t *i, uint64_t *j, const uint8_t ip[16], uint64_t v0, uint64_t v1) { uint64_t v2 = 0x736f6d6570736575ULL ^ 0x6c7967656e657261ULL ^ v0; uint64_t v3 = 0x646f72616e646f6dULL ^ 0x7465646279746573ULL ^ v1; uint64_t m; memcpy(&m, &ip[0], 8); v3 ^= m; SIPROUND; v0 ^= m; memcpy(&m, &ip[8], 8); v3 ^= m; SIPROUND; v0 ^= m; v2 ^= 0xff; SIPROUND; SIPROUND; SIPROUND; *i = v0 ^ v1 ^ v2 ^ v3; SIPROUND; *j = v0 ^ v1 ^ v2 ^ v3; } static int ratelimiter_hit(RateLimiter *rate_limiter, const uint8_t ip[16], uint64_t peak) { uint64_t slot_i, slot_j; int ret; if (rate_limiter->pos <= rate_limiter->slots_mask) { rate_limiter->slots[rate_limiter->pos] /= 2U; } rate_limiter->pos++; if (rate_limiter->pos >= rate_limiter->period) { rate_limiter->pos = 0U; } ratelimiter_hashes(&slot_i, &slot_j, ip, rate_limiter->v0, rate_limiter->v1); slot_i &= rate_limiter->slots_mask; slot_j &= rate_limiter->slots_mask; if (rate_limiter->slots[slot_i] < peak) { rate_limiter->slots[slot_i]++; ret = 0; } else { ret = 1; } if (rate_limiter->slots[slot_j] < peak) { rate_limiter->slots[slot_j]++; ret = 0; } return ret; } int main() { RateLimiter *limiter = malloc(sizeof(RateLimiter)); static uint8_t key[16] = {0}; int ret = ratelimiter_init(limiter, SLOTS_LEN, PERIOD, key); assert(ret == 0); uint8_t ip[16] = {0xff}; uint64_t i; int hits = 0; printf("[ratelimit] start limiting\n"); bench_start(); for (i = (uint64_t)0U; i < ITERATIONS; i++) { memcpy(ip, &i, sizeof i); BLACK_BOX(ip); hits += ratelimiter_hit(limiter, ip, PEAK); } bench_end(); BLACK_BOX(hits); printf("[ratelimit] found %d hits\n", hits); ratelimiter_free(limiter); }
Java
UTF-8
410
2.25
2
[]
no_license
package org.cougaar.tools.techspecs.qos; /** * Similar to a delay measurement point, but useful for "tagging" individual elements. * This is the same as the DelayMeasurementPoint, just plotted differently (e.g. a single bar * per event.) */ public class EventDurationMeasurementPoint extends DelayMeasurementPoint { public EventDurationMeasurementPoint(String name) { super(name); } }
Markdown
UTF-8
2,953
2.765625
3
[ "MIT" ]
permissive
--- layout: post title: "The AppDevs are idiots" date: 2013-12-20 23:28 comments: true categories: --- In my many years of Enterprise DBA servitude, there would be many instances of blanket 'the devs are idiots' statements. Sometimes by me, sometimes by others and from the perspective of the database it was usually justifiable. In these enviornments, this is acceptable. I have no idea what busy work task they have come up with and why should I even care about anything out side of my database? These AppsDevs are disgusting dirty creatures that just sling filth everywhere as they stomp their hooves on the keyboard. Worthless. #### Inner Joined at the Hip What I enjoy most about the above mindset is the expectation of the AppDev to know their job and be equally proficient at my own. They must be fluent in the language of Stored Procedures else everything collapses from the data hate speech that comes from their object-pooriented programs. I've often wondered where this one sidedness originated from. For a bit I thought it was just something that happened at places I worked. It's not just there though. Check out your local communities and you'll see the imbalance there as well. I attend both database user groups and developer based user groups. I often see a fair amount of AppDevs at sql events... I pretty much never see DBAs at developer events. #### Cross Apply What You Know A few years back, I got involved in with a few open source .NET ORMs. It goes without saying that ORMs are the [Vietnam of the software world][1] and I was pretty much blown away at how desperate these projects were for feedback. It was so easy and fun to help out and it totally changed my opinion of ORMs. It also changed my opinion of the curmudgeoned DBA. If you want some contrast/perspective, I've also helped out a few 'open source' database projects by their prefered method - email. #### Refactor the Query The more time you spend with AppDevs the more you realize just how many of them are stuck with really bad DBAs. Now when I hear DBAs complain I ask the following of them: What open source work do you do? What dev conferences do you attend with the team? What have you personally built? What source control do you use so that the team can see your scripts and ask about them? You don't have to be Nostradamus to know how the people I'm talking about answer the above questions. Like so many things with humans, the loud ones with the most generic argument are typically doing the least to fix the problem. If you are an Oracle/SQL Server DBA, don't just hide behind our industry specific firewalls - get out there. Engage the AppDevs, review their code, help some project, make your scripts public for them to see. We've sat in our foxholes long enough and the AppDevs are not our enemy. It's our turn to build the bridge. [1]: http://www.codinghorror.com/blog/2006/06/object-relational-mapping-is-the-vietnam-of-computer-science.html
Markdown
UTF-8
8,920
2.96875
3
[]
no_license
# Fun with Socket.io ## Step 1: Create app using express generator: ```bash npx express-generator -v ejs socket-io ``` <br> ## Step 2: Rename app.js to server.js and adjust the bin/www file. <br> ## Step 3: Install the socket.io node module: ```bash npm i socket.io ``` <br> ## Step 4: Create a chat.js file that will be responsible for client-side chat functionality. Stub it up with the following: ```bash touch public/javascripts/chat.js ``` <br> ```js // Creating a socket connection via functionality provided by a CDN link in the HTML <head> let socket = io() ``` ## Step 5: Add the socket.io CDN to the HTML <head> along with the JavaScript file we just created: ```html <script src="https://cdn.socket.io/socket.io-3.0.1.min.js"></script> <script defer src="/javascripts/chat.js"></script> ``` ## Step 6: Create a module to export all socket.io functionality. This is done to keep the code organized. Rather than putting ALL of this code in our bin/www file, we're going to export it from io.js. ```bash touch io.js ``` <br> ## Step 7: Stub up the io.js module with the following: ```js const io = require('socket.io')() io.on('connection', (socket) => { // This is where all of our server-side socket.io functionality will exist. console.log("The server is running.") }) module.exports = io ``` ## Step 8: Require the io.js module in the bin/www file, then attach it to the http server ```js const http = require('http'); // Require the io.js module here: const io = require("../io") . . . const server = http.createServer(app); // Attach io to the https server here: io.attach(server) ``` <br> ## Step 9: In the index.ejs, create a button with an `id` of 'messageButton' ```html <button id="messageButton">Message Button<button> ``` <br> ## Step 10: In `chat.js`, add a cached element reference and an event listener for a `click` on our new button Click the button and verify that the message appears in the browser console. ```js const messageButton = document.getElementById("messageButton") messageButton.addEventListener("click", () => { console.log("message button clicked") }) ``` <br> ## Step 11: Let's tweak the function and emit 'message' to the server ```js messageButton.addEventListener("click", () => { // Emit 'message' to the server (optionally passing data) socket.emit('message', {message: "message data"}) }) ``` <br> ## Step 12: Now that the client is emitting, we need to listen server-side (in io.js) for 'message' When 'message' is heard, we'll execute a callback function: ```js io.on('connection', (socket) => { console.log("The server is running.") // Listening for 'message' to be emitted by a client, then displaying the optional data passed along. Notice that the data must be passed as an argument to the callback function! socket.on('message', (messageData) => { console.log(messageData, 'data sent via message') }) }) ``` <br> ## Step 13: Add an `<input>` in `index.ejs` with an `id` of "messageInput" (above the button) ```html <input type="text" id="messageInput" placeholder="Type a message!"> ``` <br> ## Step 14: Add a cached element reference for the message input ```js const messageInput = document.getElementById("messageInput") ``` <br> ## Step 15: Refactor the callback function in `chat.js` to pass the `<input>`'s value instead as the message data ```js messageButton.addEventListener("click", () => { console.log("message button clicked") // Emit 'banana' to the server (optionally passing data) socket.emit('message', {message: messageInput.value}) }) ``` ## Step 16: Allow users to attach their name to the message ```html <input type="text" id="userName" placeholder="Enter name:"><br><br><br> ``` <br> ## Step 17: Add a cached element reference in `chat.js` for the `<input>` and refactor the emit to send the user's name as well. Let's also make it user-friendly by allowing the user to hit "Enter" instead of clicking the button. We'll also clean up the UI by resetting the message after it is sent. ```js const messageButton = document.getElementById("messageButton") const messageInput = document.getElementById("messageInput") const userName = document.getElementById("userName") messageButton.addEventListener("click", sendMessage) messageInput.addEventListener("keydown", sendMessage) function sendMessage(e) { if(e.key === "Enter" || e.type === "click") { // Emit 'message' to the server (optionally passing data) socket.emit('message', {message: messageInput.value, user: userName.value}) messageInput.value = "" } } ``` <br> ## Step 18: Add a `<div>` to the `index.ejs` that we can append the messages to after they are sent. Don't forget to add the cached element reference to `chat.js`! ```html <div id="messages"></div> ``` ```js const messagesDiv = document.getElementById("messages") ``` <br> ## Step 19: Create an empty `messages` array to store the chat data. Also, adjust the server-side listener for `message` to push the incoming data into the `messages` array. ```js messages = [] . . . // Listening for 'message' to be emitted by a client socket.on('message', (messageData) => { messages.push(messageData) io.sockets.emit('new-message', {messages}) }) ``` <br> ## Step 20: Add a listener in `chat.js` for the 'new-message' event The callback function should clear the contents of `messagesDiv` then loop over each of the incoming messages and creating/appending a `<p>` with the user's name and message. ```js socket.on('new-message', (data) => { messagesDiv.innerHTML = "" data.messages.reverse().forEach(m => { const newMessage = document.createElement("div") newMessage.innerHTML = `<p><strong>${m.user}</strong>: ${m.message}</p>` messagesDiv.appendChild(newMessage) }); }) ``` <br> ## Step 21: Add events for detecting when a client connects or disconnects from the server. Use these to push a message indicating the current number of clients connected to the server. ```js // Initialize the number of clients connected const userCount = 0 . . . // Client has connected (This must go OUTSIDE of the io.on('connection') function!) io.sockets.on('connect', () => { userCount ++ messages.push({user: "System", message: `${userCount} users are connected`}) io.sockets.emit('new-message', {messages}) }) . . . io.on('connection', (socket) => { // Client has disconnected (This must go INSIDE of the io.on('connection) function!) socket.on('disconnect', () => { userCount -- messages.push({user: "System", message: `${userCount} users are connected`}) io.sockets.emit('new-message', {messages}) }) . . . } ``` <br> ## Step 22: Display a message showing when a user is typing a message. Add a `<div>` with an id of 'isTyping' below the message button in `index.ejs`. Add a cached element reference for it in `chat.js`. ```html <div id="isTyping"></div> ``` ```js const isTyping = document.getElementById("isTyping") ``` <br> ## Step 23: Expand the event listener for the `messageInput` element to include an else statement to handle emitting an event while someone is typing in the `<input>`. ```js function sendMessage(e) { if(e.key === "Enter" || e.type === "click") { // Emit 'message' to the server (optionally passing data) socket.emit('message', {message: messageInput.value, user: userName.value}) messageInput.value = "" // Add this code to handle '... is typing' } else { socket.emit('typing', {user: userName.value}) } } ``` <br> ## Step 24: Add a listener on the server (`io.js`) for the 'typing' event. When detected, it should emit an event to all sockets except for the one that triggered the event. `socket.broadcast.emit`, to the rescue!!! ```js socket.on('typing', (userName) => { socket.broadcast.emit("user-typing", {user: userName.user}) }) ``` <br> ## Step 25: Add a listener to the client-side `chat.js` to handle displaying a message whenever the 'user-typing' event is detected. ```js socket.on('user-typing', (userName) => { isTyping.innerText = `${userName.user} is typing...` }) ``` ## Step 26: Add one line of code to clear the '... is typing...' message whenever a message is sent. ```js socket.on('new-message', (data) => { messagesDiv.innerHTML = "" data.messages.reverse().forEach(m => { const newMessage = document.createElement("div") newMessage.innerHTML = `<p><strong>${m.user}</strong>: ${m.message}</p>` messagesDiv.appendChild(newMessage) }); // Add this line of code to reset the '... is typing ...' message isTyping.innerText = "" }) ``` ## Stretch goals: - oAuth instead of chat name `<input>` - list current client user names - handle message for multiple users typing simultaneously - drawing with colors - sounds on entry/exit/message - namespaces - database connection (display message timestamps also) - deployment - styling (anything...)
Java
UTF-8
5,705
1.921875
2
[ "Apache-2.0" ]
permissive
package com.vaadin.server; /* * Copyright 2000-2014 Vaadin Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ import java.lang.reflect.Type; import java.util.Collection; import java.util.HashMap; import java.util.Map; import junit.framework.AssertionFailedError; import junit.framework.TestCase; import com.vaadin.server.JsonCodec.BeanProperty; import com.vaadin.shared.communication.UidlValue; import com.vaadin.shared.ui.splitpanel.AbstractSplitPanelState; import elemental.json.Json; import elemental.json.JsonArray; import elemental.json.JsonException; import elemental.json.JsonValue; /** * Tests for {@link JsonCodec} * * @author Vaadin Ltd * @since 7.0 * */ public class JSONSerializerTest extends TestCase { HashMap<String, AbstractSplitPanelState> stringToStateMap; HashMap<AbstractSplitPanelState, String> stateToStringMap; public void testStringToBeanMapSerialization() throws Exception { Type mapType = getClass().getDeclaredField("stringToStateMap") .getGenericType(); stringToStateMap = new HashMap<String, AbstractSplitPanelState>(); AbstractSplitPanelState s = new AbstractSplitPanelState(); AbstractSplitPanelState s2 = new AbstractSplitPanelState(); s.caption = "State 1"; s.id = "foo"; s2.caption = "State 2"; s2.id = "bar"; stringToStateMap.put("string - state 1", s); stringToStateMap.put("String - state 2", s2); JsonValue encodedMap = JsonCodec.encode(stringToStateMap, null, mapType, null).getEncodedValue(); ensureDecodedCorrectly(stringToStateMap, encodedMap, mapType); } public void testBeanToStringMapSerialization() throws Exception { Type mapType = getClass().getDeclaredField("stateToStringMap") .getGenericType(); stateToStringMap = new HashMap<AbstractSplitPanelState, String>(); AbstractSplitPanelState s = new AbstractSplitPanelState(); AbstractSplitPanelState s2 = new AbstractSplitPanelState(); s.caption = "State 1"; s2.caption = "State 2"; stateToStringMap.put(s, "string - state 1"); stateToStringMap.put(s2, "String - state 2"); JsonValue encodedMap = JsonCodec.encode(stateToStringMap, null, mapType, null).getEncodedValue(); ensureDecodedCorrectly(stateToStringMap, encodedMap, mapType); } public void testNullLegacyValue() throws JsonException { JsonArray inputArray = Json.createArray(); inputArray.set(0, "n"); inputArray.set(1, Json.createNull()); UidlValue decodedObject = (UidlValue) JsonCodec.decodeInternalType( UidlValue.class, true, inputArray, null); assertNull(decodedObject.getValue()); } public void testNullTypeOtherValue() { try { JsonArray inputArray = Json.createArray(); inputArray.set(0, "n"); inputArray.set(1, "a"); UidlValue decodedObject = (UidlValue) JsonCodec.decodeInternalType( UidlValue.class, true, inputArray, null); throw new AssertionFailedError("No JsonException thrown"); } catch (JsonException e) { // Should throw exception } } private void ensureDecodedCorrectly(Object original, JsonValue encoded, Type type) throws Exception { Object serverSideDecoded = JsonCodec.decodeInternalOrCustomType(type, encoded, null); assertTrue("Server decoded", equals(original, serverSideDecoded)); } private boolean equals(Object o1, Object o2) throws Exception { if (o1 == null) { return (o2 == null); } if (o2 == null) { return false; } if (o1 instanceof Map) { if (!(o2 instanceof Map)) { return false; } return equalsMap((Map) o1, (Map) o2); } if (o1.getClass() != o2.getClass()) { return false; } if (o1 instanceof Collection || o1 instanceof Number || o1 instanceof String) { return o1.equals(o2); } return equalsBean(o1, o2); } private boolean equalsBean(Object o1, Object o2) throws Exception { for (BeanProperty property : JsonCodec.getProperties(o1.getClass())) { Object c1 = property.getValue(o1); Object c2 = property.getValue(o2); if (!equals(c1, c2)) { return false; } } return true; } private boolean equalsMap(Map o1, Map o2) throws Exception { for (Object key1 : o1.keySet()) { Object key2 = key1; if (!(o2.containsKey(key2))) { // Try to fins a key that is equal for (Object k2 : o2.keySet()) { if (equals(key1, k2)) { key2 = k2; break; } } } if (!equals(o1.get(key1), o2.get(key2))) { return false; } } return true; } }
PHP
UTF-8
469
2.640625
3
[]
no_license
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Support\Collection; /** * @method static self find(int $id) * @property string $name * @property Collection|Item[] $items */ class Category extends Model { use HasFactory; public function items(): HasMany { return $this->hasMany(Item::class); } }
Java
UTF-8
4,489
2.9375
3
[ "MIT" ]
permissive
package com.innovationchef.strategy; import com.innovationchef.constant.Direction; import com.innovationchef.gameplay.TrackVisit; import com.innovationchef.model.Coordinate; import com.innovationchef.model.Grid; import lombok.ToString; import java.util.Comparator; import java.util.stream.Stream; /** * If the player forms a square formation on the grid, he wins * Eg: If two players are X and M, in the following grid, X wins * O O O O O O O * O O O O O O O * O O O O X O O * O O O O X O O * O M O O X O O * M M M O X O O * * O O O O O O O * O O O O O O O * O X O O O O O * O O X O O O O * O M O X O O O * M M M O X O O * */ public class ArrayMatchStrategy implements GameStrategy { public final Grid grid; public final TrackVisit trackVisit; public ArrayMatchStrategy(final Grid grid, final TrackVisit trackVisit) { this.grid = grid; this.trackVisit = trackVisit; } @Override public void verifyBoard(final Coordinate c) { MatchPerDirection matchPerDirection = new MatchPerDirection(); visit(this.grid, this.trackVisit, c, Direction.CENTER, matchPerDirection); int max = Stream.of(matchPerDirection.L + matchPerDirection.R, matchPerDirection.U + matchPerDirection.D, matchPerDirection.LU + matchPerDirection.RD, matchPerDirection.RU + matchPerDirection.LD).max(Comparator.naturalOrder()).get(); if (max + 1 >= this.trackVisit.getConnectMax()) { this.trackVisit.championFound(true); } } public void visit(Grid grid, TrackVisit trackVisit, Coordinate c, Direction dir, MatchPerDirection matchPerDirection) { if (dir != Direction.CENTER) { matchPerDirection.add(dir); } if (trackVisit.fwd()) { trackVisit.bwd(); return; } trackVisit.visit(c); if (c.isUpLeftPossible() && trackVisit.shouldVisit(c.moveUp(), grid) && dir.isCU()) { visit(grid, trackVisit, c.moveUp(), Direction.U, matchPerDirection); } if (c.isDownPossible() && trackVisit.shouldVisit(c.moveDown(), grid) && dir.isCD()) { visit(grid, trackVisit, c.moveDown(), Direction.D, matchPerDirection); } if (c.isLeftPossible() && trackVisit.shouldVisit(c.moveLeft(), grid) && dir.isCL()) { visit(grid, trackVisit, c.moveLeft(), Direction.L, matchPerDirection); } if (c.isRightPossible() && trackVisit.shouldVisit(c.moveRight(), grid) && dir.isCR()) { visit(grid, trackVisit, c.moveRight(), Direction.R, matchPerDirection); } if (c.isUpLeftPossible() && trackVisit.shouldVisit(c.moveUpLeft(), grid) && dir.isCLU()) { visit(grid, trackVisit, c.moveUpLeft(), Direction.LU, matchPerDirection); } if (c.isDownRightPossible() && trackVisit.shouldVisit(c.moveDownRight(), grid) && dir.isCRD()) { visit(grid, trackVisit, c.moveDownRight(), Direction.RD, matchPerDirection); } if (c.isDownLeftPossible() && trackVisit.shouldVisit(c.moveDownLeft(), grid) && dir.isCLD()) { visit(grid, trackVisit, c.moveDownLeft(), Direction.LD, matchPerDirection); } if (c.isUpRightPossible() && trackVisit.shouldVisit(c.moveUpRight(), grid) && dir.isCRU()) { visit(grid, trackVisit, c.moveUpRight(), Direction.RU, matchPerDirection); } trackVisit.bwd(); } @ToString private class MatchPerDirection { public int L; public int R; public int U; public int D; public int LU; public int LD; public int RU; public int RD; public void add(Direction d) { switch (d) { case L: this.L++; return; case R: this.R++; return; case U: this.U++; return; case D: this.D++; return; case LU: this.LU++; return; case LD: this.LD++; return; case RU: this.RU++; return; case RD: this.RD++; } } } }
Java
UTF-8
2,454
2.515625
3
[]
no_license
package sfs; import dfsexceptions.DataBaseDfsException; import sfs.storage.StorageManagerException; import sfs.storage.Storage; import sfs.stream.RemoteInFile; import java.io.IOException; import manager.dbmanager.DBManager; import org.junit.Test; import sfs.storage.StorageManager; import static org.junit.Assert.*; /** * * @author an */ public class RemoteInFileTest { private final sfs.RemoteFileDescr remotefiledescr = new sfs.RemoteFileDescr(); public RemoteInFileTest() throws StorageManagerException, DataBaseDfsException, InterruptedException { DBManager.Init("dfs-test.db"); sfs.storage.StorageManager.Init(6000000); StorageManager storageManager = sfs.storage.StorageManager.GetInstance(); remotefiledescr.size = 67; remotefiledescr.id = 12; remotefiledescr.storage = storageManager.getStorageById(1); Thread.sleep(1000); } /** * Test of read method, of class RemoteInFile. */ @Test public void testRead() throws Exception { // run storage agent //remotefiledescr.storagePort = 9000; pseudoremot.Agent agent = new pseudoremot.Agent(remotefiledescr.storage.port); new Thread(agent).start(); Thread.yield(); System.out.println("read"); RemoteInFile instance = new RemoteInFile(remotefiledescr); // checks first readed byte int b = instance.read(); // checks the request parametrs assertEquals(agent.fileId, remotefiledescr.id); assertEquals(agent.requestType, "download"); assertEquals(agent.offset, 0); assertEquals(b, 'I'); b = instance.read(); assertEquals(b, ' '); // checks avaliable reading all file byte [] bytes = new byte[remotefiledescr.size -2]; int readed = instance.read(bytes); assertEquals(readed, remotefiledescr.size -2); // checks next after last byte assertEquals(instance.read(), -1); instance.close(); instance.close(); System.err.println("end read"); } /** * Test of close method, of class RemoteInFile. * Test genereate exception on read from closes stream. */ @Test (expected=IOException.class) public void testClose() throws Exception { // run storage agent //remotefiledescr.storagePort = 9000; pseudoremot.Agent agent = new pseudoremot.Agent(remotefiledescr.storage.port); new Thread(agent).start(); Thread.yield(); System.out.println("read"); RemoteInFile instance = new RemoteInFile(remotefiledescr); instance.read(); instance.close(); // try read from closed stream instance.read(); } }
C++
UTF-8
11,052
2.671875
3
[]
no_license
// The Screen class is a derivative of Window that writes the resulting // data onto the physical screen #include <sys/ioctl.h> #include <unistd.h> #include <fcntl.h> #include <sys/uio.h> #include <sys/socket.h> // Some libc/linux versions seem to have iovec there :( #include "mcl.h" #include "cui.h" #include "Buffer.h" #include "Curses.h" #include "Session.h" // This isn't too pretty int get_screen_size_x() { // Screen dimensions struct winsize size; if (ioctl(STDIN_FILENO, TIOCGWINSZ, (char *) &size) < 0) error ("get_screen_size:ioctl:%m"); return size.ws_col; } int get_screen_size_y() { // Screen dimensions struct winsize size; if (ioctl(STDIN_FILENO, TIOCGWINSZ, (char *) &size) < 0) error ("get_screen_size:ioctl:%m"); return size.ws_row; } // Initialization. Figure out what dimensions we have here Screen::Screen() : Window(NULL, get_screen_size_x(), get_screen_size_y()), fd(0) { // Open our fd char *tty = ttyname(STDIN_FILENO); int ttyno; char buf[256]; usingVirtual = true; // pre 2.4 if (1 == (sscanf(tty, "/dev/tty%d", &ttyno))) sprintf (buf, "/dev/vcsa%d", ttyno); // 2.4 with devs (noted by moon@deathmoon.com else if (1 == (sscanf(tty, "/dev/vc/%d", &ttyno))) sprintf (buf, "/dev/vcc/a%d", ttyno); else { usingVirtual = false; scr_x = scr_y = scr_w = scr_h = 0; last_screen = new attrib[width * height]; memcpy(last_screen, canvas, width * height * sizeof(attrib)); write(STDOUT_FILENO, CLEAR_SCREEN, strlen(CLEAR_SCREEN)); out = new Buffer(32000); } if (usingVirtual) { if ((fd = open (buf, O_WRONLY)) < 0) { fprintf (stderr, "\nFailed to open %s: %m. \nPerhaps your permissions are wrong?\n\n", buf); exit (EXIT_FAILURE); } } init_curses(usingVirtual); } // Refresh the screen bool Screen::refreshVirtual() { unsigned char cursor_pos[2]; struct iovec write_struct[2] = { {(void*) &cursor_pos, 2}, {(void*) canvas, width*height*sizeof(*canvas)} }; if (dirty) clear(); if (Window::refresh()) { lseek(fd,2,SEEK_SET); // Go to beginning of the vcsa, but not the first // 2 bytes which are selection pos or somethign // Write cursor position, then canvas data to the device cursor_pos[0] = cursor_x; cursor_pos[1] = cursor_y; while (writev (fd, write_struct, 2) < 0) if (errno != EINTR && errno != EAGAIN) error ("Screen::refresh():writev"); return true; } else return false; } bool Screen::refresh() { if (usingVirtual) return refreshVirtual(); else return refreshTTY(); } // Why this? // ANSI colors and the colors used by /dev/vcsa do not fit together // Internally we use the /dev/vcsa colors so we must translate here static int reverse_color_conv_table[8] = { 0,4,2,6,1,5,3,7 }; // 8-bit CSI - use this if your terminal supports it! // #define CSI "\x9B" // 7-bit CSI #define CSI "\e[" // TODO: split it up so we can change fg and bg seperately const char* Screen::getColorCode (int color, bool setBackground) const { int fg_color = 30 + reverse_color_conv_table[color & 0x07]; int bold = color & fg_bold; int bg_color = 40 + reverse_color_conv_table[color >> 4]; static char buf[64]; // Xterm doesn't like fg_white|bg_black ?! if (fg_color == 37 && bg_color == 40 && !bold) sprintf(buf, CSI "0m"); else { char bg[8]; if (setBackground) sprintf(bg, "%d;", bg_color); else bg[0] = NUL; if (bold) sprintf(buf, CSI "1;%s%dm", bg, fg_color); else sprintf(buf, CSI "0;%s%dm", bg, fg_color); } return buf; } void Screen::setTTYColor(int color, bool setBackground) { const char *code = getColorCode(color, setBackground); globalStats.ctrl_chars += out->strcat(code); } // Print a single character. If it's a graphical character, and ACS is not yet enabled it, enable it void Screen::printCharacter(int c, bool& acs_enabled) { if (c >= SC_BASE && c < SC_END && smacs) { if (!acs_enabled) out->strcat(smacs); out->chrcat(real_special_chars[c-SC_BASE]); acs_enabled = true; } else { if (acs_enabled && rmacs) { out->strcat(rmacs); acs_enabled = false; } out->chrcat(c); } } // This is Y,X, both starting at 1 #define VT_GOTO CSI "%d;%dH" // goes to 1,1 #define VT_HOME CSI "H" #define MAX_SCROLL_TRY 5 // some more optimization could be useful here! // Checksum rows? (could error) // do a memcp before running through it? // probably not worth it, it's the output that's most important bool Screen::refreshTTY() { int x,y; bool acs_enabled = false; if (Window::refresh()) { // let's go with a very raw refresh for now out->clear(); // how many lines are different? int diff = 0; for (y = 0; y < height; y++) if (memcmp(last_screen+y*width, canvas+y*width, width * sizeof(attrib)) != 0) diff++; // Figure out whether we can scroll the scrolling region // Note that it isn't always a win.. when e.g. the alt-o window is open for example, how to evaluate? if (scr_h && diff > width/2) { int scrreg_bottom = scr_y + scr_h - 1; // the last line of the scrolling region int scrreg_test_start = scr_y + 5; // Where do we start looking to determine scroll happened? int scrreg_test_end = scrreg_test_start + MAX_SCROLL_TRY; // find out where the saved line at the bottom of the scrreg has went to for (y = scrreg_test_start; y <= scrreg_test_end ; y++) if (memcmp(last_screen + scrreg_test_end*width, canvas + y*width, width * sizeof(attrib)) == 0) { int lines = scrreg_test_end - y; if (lines > 0) { // adjust to what we think the screen looks like memmove(last_screen + scr_y*width, last_screen+ ((scr_y+lines)*width), (scr_h - lines) * width * sizeof(attrib)); // mark the black that should now appear at the bottom there for (y = scrreg_bottom - lines; y <= scrreg_bottom; y++) memcpy(last_screen + y*width, clearLine, width * sizeof(attrib)); setTTYColor(bg_black|fg_white, true); // we want to scroll up black space globalStats.ctrl_chars += out->printf(CSI "%d;%dr", scr_y+1, scr_y+scr_h); globalStats.ctrl_chars += out->printf(VT_GOTO, scr_y+scr_h, 1); while (lines-- > 0) out->strcat("\n"); globalStats.ctrl_chars += out->printf(CSI "%d;%dr", 1, height); } break; } } out->printf(VT_HOME); // top left corner int saved_color = -1; int last_y = 0, last_x = 0; for (y = 0; y < height ; y++) { for (x = 0; x < width; x++) { // don't write in that very last cell if (y == height-1 && x == width-1) continue; int offset = x + y * width; if (canvas[offset] != last_screen[offset]) { int color = canvas[offset] >> 8; int c = canvas[offset] & 0xFF; if (color != saved_color) { // XTerm seems to have problems with this?! #if 0 setTTYColor(color, color >> 4 != saved_color >> 4); #endif setTTYColor(color, true); saved_color = color; } // Are we there yet? if (x != last_x || y != last_y) { // It is more efficient to just print the actual skipped character in some // cases rather than goto (especially when it's e.g. a space in our current color) if (last_y == y && last_x == x-1 && (canvas[offset-1] >> 8) == saved_color) printCharacter(canvas[offset-1] & 0xFF, acs_enabled); else { // just on the line above? then we can just send a newline to go down #if 0 if (x == 0 && last_y == y-1) out->printf("\r\n"); else #endif globalStats.ctrl_chars += out->printf(VT_GOTO, y+1, x+1); } } last_y = y; last_x = x+1; if (last_x == width) { last_x = 0; last_y++; } if (c >= 32) printCharacter(c, acs_enabled); else out->chrcat(' '); } } } globalStats.ctrl_chars += out->printf(VT_GOTO, cursor_y+1, cursor_x+1); // top left corner if (rmacs && acs_enabled) // Always reset JIC globalStats.ctrl_chars += out->strcat(rmacs); int n = write(STDIN_FILENO, ~*out, out->count()); if (n != out->count()) abort(); memcpy(last_screen, canvas, width*height*sizeof(attrib)); globalStats.tty_chars += out->count(); return true; } else return false; } Screen::~Screen() { if (usingVirtual) close (fd); done_curses(); } void Screen::set_cursor(int _x, int _y) { cursor_x = _x; cursor_y = _y; } void Screen::setScrollingRegion(int x, int y, int w, int h) { scr_x = x; scr_y = y; scr_w = w; scr_h = h; } void Screen::flash() { if (config->getOption(opt_beep)) write (STDIN_FILENO, "\a",1); } bool Screen::keypress(int key) { // Check for alt-X if (key >= key_alt_1 && key < key_alt_9) { Window *w = Numbered::find(key-key_alt_1+1); if (w) { w->show(true); w->popUp(); return true; } } else if (key == key_ctrl_l) { // redraw if (!usingVirtual) memset(last_screen, 0, width*height*sizeof(attrib)); return true; } if (!Window::keypress(key)) if (!currentSession || !currentSession->expand_macros(key)) status->setf ("Keycode %d (%s) was not handled by any object", key, key_name(key)); return true; }