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
1,401
3.1875
3
[ "MIT" ]
permissive
""""Loader class that coordinates loading of data samples and converting them to XY array""" import os, fnmatch import numpy as np from preprocessor import DataPreprocessor from data.paths import Paths from data.features import Features class Loader: def load_data(self): warming_file_names = fnmatch.filter(os.listdir(Paths.raw_data), '*A.wav') boiling_file_names = fnmatch.filter(os.listdir(Paths.raw_data), '*B.wav') pp = DataPreprocessor() warming_data = self.load_samples(warming_file_names) boiling_data = self.load_samples(boiling_file_names) data = [] data.extend(warming_data) data.extend(boiling_data) target = np.zeros(len(warming_data) + len(boiling_data)) # set zero for feature of class 1 (warming water) for index in range(len(warming_data),len(warming_data) + len(boiling_data)): target[index] = 1 # set one for feature of class 2 (boiling water) X = np.array(data) Y = target return X, Y def load_samples(self, files): samples = [] pp = DataPreprocessor() for file in files: samples.extend(pp.preprocess(file)) return samples if __name__ == '__main__': l = Loader(); X, Y = l.load_data(); print "Loader selftest..." print "X: " print X print "Y: " + str(Y) print "Done!"
C#
UTF-8
5,076
2.921875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using OpenQA.Selenium; using OpenQA.Selenium.Support.Extensions; using OpenQA.Selenium.Support.UI; using Digital.Settings; using System.Drawing.Imaging; namespace Digital.ComponentHelper { public class GenericHelper { public static WebDriverWait genericHelperWait = new WebDriverWait(ObjectRepository.Driver, TimeSpan.FromSeconds(30)); public static string GetFirstFewChars(string inputString, int noOfChars) { string returnString = inputString.Substring(0,noOfChars); return returnString; } //Used for situations such as needing to return the numeric valuefrom a string like "£1.25" public static string GetValueAfterPoundSymbol(string inputString) { int stringLength = inputString.Length; string returnString=null; if (inputString.Substring(0,1)=="£") { returnString = inputString.Substring(1,stringLength-1 ); } else { returnString = inputString; } return returnString; } //Use this to check for presence of element when you have the locator rather than the element public static bool IsElementDisplayed(By locator) { try { genericHelperWait.Until(ExpectedConditions.ElementIsVisible(locator)); return ObjectRepository.Driver.FindElement(locator).Displayed; } catch (OpenQA.Selenium.WebDriverTimeoutException) { return false; } } //Use this to check for presence of element when you have the element rather than the locator public static bool IsElementClickable(IWebElement element) { try { genericHelperWait.Until(ExpectedConditions.ElementToBeClickable(element)); return true; } catch (OpenQA.Selenium.WebDriverTimeoutException) { return false; } } public static bool IsElementEnabled(By locator) { if (IsElementDisplayed(locator)) { return ObjectRepository.Driver.FindElement(locator).Enabled; } else { return false; } } //Overloaded method. This version takes the locator as paramenter public static string GetElementText(By locator) { var element = GenericHelper.GetElement(locator); if (element.GetAttribute("value") == null) return String.Empty; return element.GetAttribute("value"); } //Overloaded method. This version takes the element as paramenter public static string GetElementText(IWebElement element) { if (IsElementClickable(element)) { if (element.GetAttribute("value") == null) return String.Empty; return element.GetAttribute("value"); } else { TimeoutException t = new TimeoutException("Could not get element text because wait timed out"); throw t; } } //This method returns number within a string public static int getNumberFromString(string input) { var getNumbers = (from t in input where char.IsDigit(t) select t).ToArray(); try { return int.Parse(new string(getNumbers)); }catch(FormatException e){ ObjectRepository.writer.WriteToLog(e.Message); ObjectRepository.writer.WriteToLog(e.StackTrace); throw new FormatException("There is no number in the string passed to this method"); } } //Used to get the element referred to by given locator. public static IWebElement GetElement(By locator) { if (IsElementDisplayed(locator)) return ObjectRepository.Driver.FindElement(locator); else throw new NoSuchElementException("Element Not Found : " + locator.ToString()); } //Useful if you need screenshots as evidence public static void TakeScreenShot(string filename) { var camera = ObjectRepository.Driver.TakeScreenshot(); filename = filename + DateTime.UtcNow.ToString("yyyy-MM-dd-mm-ss") + ".jpeg"; camera.SaveAsFile(filename, ScreenshotImageFormat.Jpeg); return; } } }
Markdown
UTF-8
977
2.6875
3
[]
no_license
# mvmoproject ## google oauth2 authorization using java This project used docker for contanerising Wildfly application server and postgreSQL database. I use google oauth 2 API and create new user into database if the user sign in with gmail for the first time. In addition,I configure dockerised wildfly with ssl certificate. This project has a lot more cool thing to do but it is more for testing different technologies. for running the application you need go to docker folder run the docker and a ```bash docker container run -d --name=pg -p 5432:5432 -e POSTGRES_PASSWORD=1234 -e PGDATA=/pgdata -v /pgdata:/pgdata postgres:12 ``` Alternatively you can run both database and application from my dockerhub account use these command seperatly. ``` docker run -p 8080:8080 -p 8443:8443 hadiroudsari/maro:2 ``` and ``` docker container run -d --name=pg -p 5432:5432 -e POSTGRES_PASSWORD=1234 -e PGDATA=/pgdata -v $(pwd)/pgdata:/pgdata hadiroudsari/pg:1 ```
C#
UTF-8
5,228
2.5625
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Net; using System.IO; using System.Diagnostics; using System.Text.RegularExpressions; namespace NaverTTS { public partial class Form1 : Form { const int KOREAN = 0; const int ENGLISH = 1; const int JAPANESE = 2; const int CHINESE = 3; const int ESPANOL = 4; const int GIRL = 0; const int MAN = 1; string[,] sex = { { "Mijin", "Jinho" }, { "Clara", "Matt" }, { "Yuri", "Shinji" }, { "Meimei", "Liangliang" }, { "Carmen", "Jose" }, }; int nLanguage = KOREAN; int nSex = GIRL; public Form1() { InitializeComponent(); } private void ttsBtn_Click(object sender, EventArgs e) { string text = textBox.Text; // 음성합성할 문자값 string url = "https://openapi.naver.com/v1/voice/tts.bin"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Headers.Add("X-Naver-Client-Id", clientIDTxt.Text); request.Headers.Add("X-Naver-Client-Secret", clientKeyTxt.Text); try{ request.Method = "POST"; float voiceSpeed = (float)voiceSpeedTrack.Value / 2; string parm = "speaker=" + sex[nLanguage, nSex].ToLower() + "&speed=" + voiceSpeed.ToString() + "&text=" + text; byte[] byteDataParams = Encoding.UTF8.GetBytes(parm); request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = byteDataParams.Length; Stream st = request.GetRequestStream(); st.Write(byteDataParams, 0, byteDataParams.Length); st.Close(); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { try { string status = response.StatusCode.ToString(); Console.WriteLine("status=" + status); string Name = Regex.Replace(text, @"[^a-zA-Z0-9가-힣_]", "", RegexOptions.Singleline); string fileName = @".\" + Name + "_" + sex[nLanguage, nSex].ToLower() + "_" + voiceSpeed.ToString() + ".mp3"; using (Stream output = File.OpenWrite(fileName)) using (Stream input = response.GetResponseStream()) { input.CopyTo(output); MessageBox.Show(Name + ".mp3" + " 생성!\n성공!"); } } catch { } } } catch (WebException ex) { MessageBox.Show(ex.Message); if (ex.Status == WebExceptionStatus.Timeout) { // Handle timeout exception } } finally { } } private void rKorean_CheckedChanged(object sender, EventArgs e) { nLanguage = KOREAN; refresh_sexModel(); } private void rEnglish_CheckedChanged(object sender, EventArgs e) { nLanguage = ENGLISH; refresh_sexModel(); } private void rChinese_CheckedChanged(object sender, EventArgs e) { nLanguage = CHINESE; refresh_sexModel(); } private void rJapanese_CheckedChanged(object sender, EventArgs e) { nLanguage = JAPANESE; refresh_sexModel(); } private void rEspanol_CheckedChanged(object sender, EventArgs e) { nLanguage = ESPANOL; refresh_sexModel(); } void refresh_sexModel() { rGirl.Text = sex[nLanguage,0] + "(여성)"; rMan.Text = sex[nLanguage, 1] + "(남성)"; } private void Form1_Load(object sender, EventArgs e) { refresh_sexModel(); } private void voiceSpeedTrack_ValueChanged(object sender, EventArgs e) { float f = (float)voiceSpeedTrack.Value / 2; speedVal.Text = f.ToString(); } private void OpenFolderBtn_Click(object sender, EventArgs e) { Process.Start(@".\"); } private void rGirl_CheckedChanged(object sender, EventArgs e) { nSex = GIRL; } private void rMan_CheckedChanged(object sender, EventArgs e) { nSex = MAN; } } }
Java
UTF-8
777
2.015625
2
[]
no_license
package com.zhanhong.wcs.entity.sys; import org.apache.ibatis.type.Alias; import com.zhanhong.wcs.entity.base.BaseWcs; /** * 菜单角色实体类 * @author Arvin_Li * */ @Alias(value="menuRole") public class WcsSysMenuRole extends BaseWcs{ private Integer mrId;//关系ID private Integer menuId;//菜单ID private Integer roleId;//角色ID public WcsSysMenuRole() { super(); } public Integer getMrId() { return mrId; } public void setMrId(Integer mrId) { this.mrId = mrId; } public Integer getMenuId() { return menuId; } public void setMenuId(Integer menuId) { this.menuId = menuId; } public Integer getRoleId() { return roleId; } public void setRoleId(Integer roleId) { this.roleId = roleId; } }
PHP
UTF-8
1,189
2.875
3
[]
no_license
<?php namespace App\Service; use App\Repository\GameModeRepository; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; /** * Service permettant de retourner des valeurs aléatoires */ class RandomService extends AbstractController { private $gameModeRepo; public function __construct(GameModeRepository $gameModeRepo) { $this->gameModeRepo = $gameModeRepo; } // Permet de nettoyer les données envoyées en post /** * Retourne une Couleur aléatoire * * @return string */ public function getRandomColor() { $result = array('rgb' => '', 'hex' => ''); foreach (array('r', 'b', 'g') as $col) { $rand = mt_rand(0, 255); // $result['rgb'][$col] = $rand; $dechex = dechex($rand); if (strlen($dechex) < 2) { $dechex = '0' . $dechex; } $result['hex'] .= $dechex; } $rgbColor = "#". $result['hex']; return $rgbColor; } public function timesUpGameMode() { $timesUpCameMode = $this->gameModeRepo->findOneBy(['tag' => 'Times-Up']); return $timesUpCameMode; } }
C#
UTF-8
3,394
3.875
4
[]
no_license
using System; namespace Sort { public class Sort { public static void SelectionSort(IComparable[] a) { Action<IComparable[], int, int> Switch = (arr, i, j) => { IComparable t = arr[i]; arr[i] = arr[j]; arr[j] = t; }; int n = a.Length; for (int i = 0; i < n; i++) { int min = i; for (int j = i; j < n; j++) if (a[min].CompareTo(a[j]) > 0) min = j; Switch(a, i, min); } } public static void InsertionSort(IComparable[] a) { Action<IComparable[], int, int> Switch = (arr, i, j) => { IComparable t = arr[i]; arr[i] = arr[j]; arr[j] = t; }; int n = a.Length; for (int i = 1; i < n; i++) for (int j = i; j > 0 && a[j].CompareTo(a[j - 1]) < 0; j--) Switch(a, j, j - 1); } public static void Merge(IComparable[] a, int l, int r) { IComparable[] t = new IComparable[a.Length]; for (int k = l; k <= r; k++) t[k] = a[k]; int i = l; int mid = (l + r) / 2; int j = mid + 1; for (int k = l; k <= r; k++) { if (i > mid) a[k] = t[j++]; else if (j > r) a[k] = t[i++]; else if (t[i].CompareTo(t[j]) > 0) a[k] = t[j++]; else a[k] = t[i++]; } } public static void MergeSort(IComparable[] a,int l,int r) { if (l >= r) return; int mid = (l + r) / 2; MergeSort(a, l, mid); MergeSort(a, mid + 1, r); Merge(a, l, r); } public static void QuickSort(IComparable[] a,int l,int r) { if (l >= r) return; int p = Partition(a, l, r); QuickSort(a, l, p - 1); QuickSort(a, p + 1, r); } public static int Partition(IComparable[] a,int l,int r) { Action<IComparable[], int, int> Switch = (arr, i2, j2) => { IComparable t = arr[i2]; arr[i2] = arr[j2]; arr[j2] = t; }; IComparable mid = a[l]; int i = l; int j = r + 1; while(true) { while(mid.CompareTo(a[++i])>0) if (i == r) break; while (mid.CompareTo(a[--j]) < 0) if (j == l) break; if (i >= j) break; Switch(a, i, j); } Switch(a,l,j); return j; } public static void Main(string[] args) { IComparable[] a = new IComparable[] { 1, 3, 2, 5, 4, 8, 7, 6, 9 }; //SelectionSort(a); //InsertionSort(a); //MergeSort(a, 0, 8); QuickSort(a, 0, 8); foreach (IComparable element in a) { Console.WriteLine($"{element}"); } } } }
Java
UTF-8
948
1.601563
2
[]
no_license
package com.facebook.graphql.model; import com.facebook.common.json.FbSerializerProvider; import com.facebook.graphql.deserializers.GraphQLStickerDeserializer; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; /* compiled from: Unexpected HTTP code */ public final class GraphQLSticker$Serializer extends JsonSerializer<GraphQLSticker> { public final void m21833a(Object obj, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) { GraphQLSticker graphQLSticker = (GraphQLSticker) obj; GraphQLStickerDeserializer.m5947a(graphQLSticker.w_(), graphQLSticker.u_(), jsonGenerator, serializerProvider); } static { FbSerializerProvider.a(GraphQLSticker.class, new GraphQLSticker$Serializer()); FbSerializerProvider.a(GraphQLSticker.class, new GraphQLSticker$Serializer()); } }
Go
UTF-8
1,434
2.515625
3
[]
no_license
package main import ( "context" "fmt" "github.com/INEFFABLE-games/Birds/config" "github.com/INEFFABLE-games/Birds/protocol" "github.com/INEFFABLE-games/Birds/repository" "github.com/INEFFABLE-games/Birds/server" "github.com/INEFFABLE-games/Birds/service" log "github.com/sirupsen/logrus" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "google.golang.org/grpc" "net" ) func getMongoConnection(connString string) (*mongo.Client, error) { clientOptions := options.Client().ApplyURI(connString) conn, err := mongo.Connect(context.Background(), clientOptions) return conn, err } func main() { cfg := config.NewConfig() conn, err := getMongoConnection(cfg.MongoConnString) if err != nil { log.WithFields(log.Fields{ "handler": "main", "action": "ping mongo connection", }).Errorf("unable connect to mongo %v", err.Error()) } lis, err := net.Listen("tcp", fmt.Sprintf("localhost:%s", cfg.Port)) if err != nil { log.WithFields(log.Fields{ "handler": "main", "action": "create listener", }).Errorf("unable to create listener %v", err.Error()) } birdRepo := repository.NewBirdRepository(conn) birdService := service.NewBirdService(birdRepo) birdHandler := server.NewBirdHandler(birdService) grpcServer := grpc.NewServer() protocol.RegisterBirdServiceServer(grpcServer, birdHandler) err = grpcServer.Serve(lis) if err != nil { log.Fatal(err) } }
Java
UTF-8
1,867
2.484375
2
[]
no_license
package cn.wx.MyData; import java.nio.charset.Charset; import cn.wx.Utils.GetAccessToken; public class MyData { /** 用户自定TOKEN*/ public final static String TOKEN = "pppa20180608"; /** 管理员ID*/ public final static String AppID = "wxe127d9b9fe06cf6d"; /** 管理员密码*/ public final static String AppSecret = "f8593e6cdd6a11ec4519a7cbd8b9f7d2"; /** * access_token获取地址 * https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET */ public static String AccessToken = null; public static int Timeout=0; /** * 微信公众平台开发者设置的EncodingAESKey */ public final static String EncodingAESKey = "7CSZu9Gxp4plMy7iUI63WvfIlToUhkl93urJCYdMOMW"; /** * 定义字符集为UTF-8 */ public final static Charset charset = Charset.forName("utf-8"); public static int MsgID=0; /** * 定义一个flag用于判断当前公众平台消息加密模式,若为true则公众平台消息加密模式为密文或兼容模式 ,此时发送加密XML数据包,若为 false * 公众平台消息加密模式为明文模式 ,此时发送不加密的XML数据包 */ public static boolean encryptFlag = true; public static String getAccessToken() { return AccessToken; } public static void setAccessToken() { String []result=GetAccessToken.GetAT(); AccessToken = result[0]; Timeout=Integer.parseInt(result[1]); System.out.println(AccessToken); } public static String bytetoStr(byte[] bb) { String strDigest = ""; for (int i = 0; i < bb.length; i++) { strDigest += byteToHexStr(bb[i]); } return strDigest; } public static String byteToHexStr(byte b) { char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; char[] tempArr = new char[2]; tempArr[0] = Digit[(b >>> 4) & 0X0F]; tempArr[1] = Digit[b & 0X0F]; String s = new String(tempArr); return s; } }
C++
UTF-8
1,510
2.578125
3
[]
no_license
#include "Sprite2D.hpp" #include "../../../Ascii_Render_System/AsciiRenderer.hpp" Sprite2D::Sprite2D() { ascii_sprite=NULL; } Sprite2D::Sprite2D(std::string* asc) { setSprite(asc); } Sprite2D::~Sprite2D() { } void Sprite2D::setSprite(std::string* asc) { ascii_sprite=asc; } std::string* Sprite2D::getSprite() { return ascii_sprite; } void Sprite2D::_draw() { int tx=(int)getPos()[0]; int ty=(int)getPos()[1]; // AsciiRenderer::getInstance().render(std::vector<int> {tx,ty}, *ascii_sprite, COLOR_PAIR(1)); unsigned int ctr = 0; int i=tx;//X coord int j=ty;//Y coord char c = (*ascii_sprite)[ctr]; while (j<0 && ctr<(*ascii_sprite).length()) { while (c!='\n') { c=(*ascii_sprite)[++ctr]; } c=(*ascii_sprite)[++ctr]; j = j + 1; } while(ctr<(*ascii_sprite).length() and j<25) { if (i>=0 && i<100) { if (c!=' ' && c!='$') { AsciiRenderer::getInstance().putSym(std::vector<int>{i,j},c,COLOR_PAIR(1)); } else if (c=='$') { AsciiRenderer::getInstance().putSym(std::vector<int>{i,j},' ',COLOR_PAIR(1)); } } c=(*ascii_sprite)[++ctr]; if (c=='\n') { if (i<100) { // frame[j][i]=' '; } i=tx; j++; c=(*ascii_sprite)[++ctr]; } else i++; } }
C++
UTF-8
1,091
3.25
3
[]
no_license
//Author: Xujia Ji //Data: 03/28/2018 //Reference: https://www.geeksforgeeks.org/evaluation-of-expression-tree/ #include <iostream> #include <fstream> using namespace std; class node { private:; public: string info; node *left = nullptr, *right = nullptr; node(string x) { info = x; } }; int toInt(string s) { int num = 0; for (int i = 0; i < s.length(); i++) { num = num * 10 + (int(s[i]) - 48); } return num; } int eval(node* root){ if(!root)return 0; if(!root->left&&!root->right)return toInt(root->info); int l_val = eval(root->left); int r_val = eval(root->right); if(root->info == "+")return l_val+r_val; if(root->info == "-")return l_val-r_val; if(root->info == "-")return l_val-r_val; return l_val/r_val; } int main() { ifstream in; in.open("hw8inp.dat",ios::in); string line; node *q; if(in.is_open()){ while(!in.eof()){ getline(in,line); q = new node(line); cout<<line<<" is equal to "<<eval(q)<<endl; } } return 0; }
Java
UTF-8
3,403
1.96875
2
[]
no_license
package com.yl.online.model.bean; import java.io.Serializable; import java.util.Date; import javax.validation.constraints.NotNull; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import com.yl.online.model.enums.BusinessType; import com.yl.online.model.enums.PartnerRole; import com.yl.online.model.enums.PayType; /** * 创建交易订单Bean * * @author 聚合支付有限公司 * @since 2016年7月13日 * @version V1.0.0 */ public class CreateOrderBean implements Serializable { private static final long serialVersionUID = -8328696273847710291L; /** 业务类型 */ @NotNull private BusinessType businessType; /** 付款方角色 */ @NotNull private PartnerRole payerRole; /** 付款方 */ @NotNull private String payer; /** 收款方角色 */ @NotNull private PartnerRole receiverRole; /** 收款方 */ @NotNull private String receiver; /** 合作方唯一订单号 */ @NotNull private String outOrderId; /** 币种 */ private String currency; /** 金额 */ private Double amount; /** 接口编号 */ private String interfaceCode; /** 后台通知URL */ private String notifyURL; /** 超时时间 */ private Date timeout; /** 业务扩展参数 */ private String extParam; /** 客户端IP */ private String clientIP; /** 支付类型 */ private PayType payType; public BusinessType getBusinessType() { return businessType; } public void setBusinessType(BusinessType businessType) { this.businessType = businessType; } public PartnerRole getPayerRole() { return payerRole; } public void setPayerRole(PartnerRole payerRole) { this.payerRole = payerRole; } public String getPayer() { return payer; } public void setPayer(String payer) { this.payer = payer; } public PartnerRole getReceiverRole() { return receiverRole; } public void setReceiverRole(PartnerRole receiverRole) { this.receiverRole = receiverRole; } public String getReceiver() { return receiver; } public void setReceiver(String receiver) { this.receiver = receiver; } public String getOutOrderId() { return outOrderId; } public void setOutOrderId(String outOrderId) { this.outOrderId = outOrderId; } public String getCurrency() { return currency; } public void setCurrency(String currency) { this.currency = currency; } public Double getAmount() { return amount; } public void setAmount(Double amount) { this.amount = amount; } public String getInterfaceCode() { return interfaceCode; } public void setInterfaceCode(String interfaceCode) { this.interfaceCode = interfaceCode; } public String getNotifyURL() { return notifyURL; } public void setNotifyURL(String notifyURL) { this.notifyURL = notifyURL; } public Date getTimeout() { return timeout; } public void setTimeout(Date timeout) { this.timeout = timeout; } public String getExtParam() { return extParam; } public void setExtParam(String extParam) { this.extParam = extParam; } public String getClientIP() { return clientIP; } public void setClientIP(String clientIP) { this.clientIP = clientIP; } public PayType getPayType() { return payType; } public void setPayType(PayType payType) { this.payType = payType; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } }
Java
UTF-8
708
2.453125
2
[]
no_license
package backup.model; public class Arquivo { private long id; private String nome; private String diretorio; private String diretorioCompleto; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getDiretorio() { return diretorio; } public void setDiretorio(String diretorio) { this.diretorio = diretorio; } public String getDiretorioCompleto() { return diretorioCompleto; } public void setDiretorioCompleto(String diretorioCompleto) { this.diretorioCompleto = diretorioCompleto; } }
Python
UTF-8
7,495
2.578125
3
[ "MIT" ]
permissive
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np def concat_x_c(x, c): # Replicate spatially and concatenate domain information. c = c.view(c.size(0), c.size(1), 1, 1) c = c.repeat(1, 1, x.size(2), x.size(3)) x = torch.cat([x, c], dim=1) return x class GatedBlock(nn.Module): """Residual Block with instance normalization.""" def __init__(self, dim_in, dim_out, kernel_size, stride, padding=0, deconv=False): super(GatedBlock, self).__init__() conv = nn.ConvTranspose2d if deconv else nn.Conv2d self.conv = conv(dim_in, dim_out, kernel_size=kernel_size, stride=stride, padding=padding, bias=True) self.bn_conv = nn.BatchNorm2d(dim_out) self.gate = conv(dim_in, dim_out, kernel_size=kernel_size, stride=stride, padding=padding, bias=True) self.bn_gate = nn.BatchNorm2d(dim_out) def forward(self, x): x1 = self.bn_conv(self.conv(x)) x2 = F.sigmoid(self.bn_gate(self.gate(x))) out = x1 * x2 return out class NoCompressGenerator16(nn.Module): """Generator network. Latent size (8, 64, 16)""" def __init__(self, c_dim): super(NoCompressGenerator16, self).__init__() encoder = [] # my dims (reduces length dim by 2, keeps features dim until last conv, like in StarGAN-VC) encoder.append(GatedBlock(1, 32, kernel_size=(9,3), stride=(1,1), padding=(4,1))) encoder.append(GatedBlock(32, 64, kernel_size=(8,4), stride=(2,2), padding=(3,1))) encoder.append(GatedBlock(64, 128, kernel_size=(8,4), stride=(2,2), padding=(3,1))) encoder.append(GatedBlock(128, 8, kernel_size=(5,3), stride=(1,1), padding=(2,1))) self.l1 = GatedBlock(8 + c_dim, 128, kernel_size=(5,3), stride=(1,1), padding=(2,1), deconv=True) self.l2 = GatedBlock(128, 64, kernel_size=(8,4), stride=(2,2), padding=(3,1), deconv=True) self.l3 = GatedBlock(64, 32, kernel_size=(8,4), stride=(2,2), padding=(3,1), deconv=True) self.l4 = nn.ConvTranspose2d(32, 1, kernel_size=(9,3), stride=(1,1), padding=(4,1)) self.encoder = nn.Sequential(*encoder) def forward(self, x, c): x = self.encoder(x) x = concat_x_c(x, c) x = self.l1(x) x = concat_x_c(x, c) x = self.l2(x) x = concat_x_c(x, c) x = self.l3(x) x = concat_x_c(x, c) x = self.l4(x) return x class NoCompressGenerator32(nn.Module): """Generator network. Latent size (8, 64, 32)""" def __init__(self, c_dim): super(NoCompressGenerator32, self).__init__() encoder = [] # my dims (reduces length dim by 2, keeps features dim until last conv, like in StarGAN-VC) encoder.append(GatedBlock(1, 32, kernel_size=(9,3), stride=(1,1), padding=(4,1))) encoder.append(GatedBlock(32, 64, kernel_size=(8,4), stride=(2,2), padding=(3,1))) encoder.append(GatedBlock(64, 128, kernel_size=(8,3), stride=(2,1), padding=(3,1))) encoder.append(GatedBlock(128, 8, kernel_size=(5,3), stride=(1,1), padding=(2,1))) self.l1 = GatedBlock(8 + c_dim, 128, kernel_size=(5,3), stride=(1,1), padding=(2,1), deconv=True) self.l2 = GatedBlock(128 + c_dim, 64, kernel_size=(8,3), stride=(2,1), padding=(3,1), deconv=True) self.l3 = GatedBlock(64 + c_dim, 32, kernel_size=(8,4), stride=(2,2), padding=(3,1), deconv=True) self.l4 = nn.ConvTranspose2d(32 + c_dim, 1, kernel_size=(9,3), stride=(1,1), padding=(4,1)) self.encoder = nn.Sequential(*encoder) def forward(self, x, c): x = self.encoder(x) x = concat_x_c(x, c) x = self.l1(x) x = concat_x_c(x, c) x = self.l2(x) x = concat_x_c(x, c) x = self.l3(x) x = concat_x_c(x, c) x = self.l4(x) return x class Generator(nn.Module): """Generator network.""" def __init__(self, c_dim): super(Generator, self).__init__() encoder = [] decoder = [] # my dims (reduces length dim by 2, keeps features dim until last conv, like in StarGAN-VC) encoder.append(GatedBlock(1, 32, kernel_size=(9,3), stride=(1,1), padding=(4,1))) encoder.append(GatedBlock(32, 64, kernel_size=(8,4), stride=(2,2), padding=(3,1))) encoder.append(GatedBlock(64, 128, kernel_size=(8,4), stride=(2,2), padding=(3,1))) encoder.append(GatedBlock(128, 64, kernel_size=(5,3), stride=(1,1), padding=(2,1))) encoder.append(GatedBlock(64, 5, kernel_size=(5,16), stride=(1,16), padding=(2,1))) decoder.append(GatedBlock(5 + c_dim, 64, kernel_size=(5,16), stride=(1,16), padding=(2,0), deconv=True)) decoder.append(GatedBlock(64, 128, kernel_size=(5,3), stride=(1,1), padding=(2,1), deconv=True)) decoder.append(GatedBlock(128, 64, kernel_size=(8,4), stride=(2,2), padding=(3,1), deconv=True)) decoder.append(GatedBlock(64, 32, kernel_size=(8,4), stride=(2,2), padding=(3,1), deconv=True)) decoder.append(nn.ConvTranspose2d(32, 1, kernel_size=(9,3), stride=(1,1), padding=(4,1))) self.encoder = nn.Sequential(*encoder) self.decoder = nn.Sequential(*decoder) def forward(self, x, c): x = self.encoder(x) x = concat_x_c(x, c) x = self.decoder(x) return x class Discriminator(nn.Module): def __init__(self, c_dim): super(Discriminator, self).__init__() # my dims (reduces length dim by 2, keeps features dim until last conv, like in StarGAN-VC) self.l1 = GatedBlock(1 + c_dim, 32, kernel_size=(9,3), stride=(1,1), padding=(4,1)) self.l2 = GatedBlock(32 + c_dim, 32, kernel_size=(8,3), stride=(2,1), padding=(3,1)) self.l3 = GatedBlock(32 + c_dim, 32, kernel_size=(8,3), stride=(2,1), padding=(3,1)) self.l4 = GatedBlock(32 + c_dim, 32, kernel_size=(6,3), stride=(2,1), padding=(2,1)) self.l5 = nn.Conv2d(32 + c_dim, 1, kernel_size=(5,40), stride=(1,40), padding=(2,0), bias=False) def forward(self, x, c): x = concat_x_c(x, c) x = self.l1(x) x = concat_x_c(x, c) x = self.l2(x) x = concat_x_c(x, c) x = self.l3(x) x = concat_x_c(x, c) x = self.l4(x) x = concat_x_c(x, c) x = self.l5(x) x = F.sigmoid(x) x = x.mean(2) x = x.squeeze(2) return x class Classifier(nn.Module): def __init__(self, c_dim, dropout=0.5): super(Classifier, self).__init__() layers = [] layers.append(GatedBlock(1, 8, kernel_size=(4,6), stride=(2,4), padding=(1,1))) layers.append(nn.Dropout2d(dropout)) layers.append(GatedBlock(8, 8, kernel_size=(4,6), stride=(2,2), padding=(1,1))) layers.append(nn.Dropout2d(dropout)) layers.append(nn.Conv2d(8, c_dim, kernel_size=(3,5), stride=(2,5), padding=(1,1), bias=False)) self.layers = nn.Sequential(*layers) def forward(self, x): # now x of size (B, 1, SEQ_LEN, N_FEATS) x = self.layers(x) # now x is of size (B, #CLASSES, 8, 1) x = F.log_softmax(x, dim=1) x = x.mean(2) x = x.squeeze(2) return x class UnifiedDiscriminator(nn.Module): def __init__(self, c_dim, c_do): super(UnifiedDiscriminator, self).__init__() self.D = Discriminator(c_dim) self.C = Classifier(c_dim, c_do) def forward(self, x, c): return self.D(x, c), self.C(x)
SQL
UTF-8
1,625
2.8125
3
[]
no_license
/* Tactical play */ UPDATE Units SET Range = 10 WHERE Range > 0 AND (CombatClass = 'UNITCOMBAT_SIEGE' OR CombatClass = 'UNITCOMBAT_NAVAL' OR CombatClass = 'UNITCOMBAT_ARCHER'); UPDATE Units SET Range = 50 WHERE Range > 0 AND (CombatClass = 'UNITCOMBAT_NAVAL') AND NOT (Class LIKE '%SUBMARINE%'); UPDATE Units SET Range = 3 WHERE (Class LIKE '%SUBMARINE%'); UPDATE Defines SET Value = 15 WHERE Name = 'SUPPORT_FIRE_MAX_REQUEST_RANGE'; UPDATE Defines SET Value = 33 WHERE Name = 'SUPPORT_FIRE_MIN_HEALTH_PERCENT_LEFT'; UPDATE Defines SET Value = 1 WHERE Name = 'SUPPORT_FIRE_CHANCE_BY_HEALTH'; UPDATE Defines SET Value = 66 WHERE Name = 'SUPPORT_FIRE_BASE_CHANCE_PERCENT'; UPDATE Defines SET Value = 0 WHERE Name = 'SUPPORT_FIRE_NO_COUNTER'; UPDATE Units SET BaseSightRange = BaseSightRange + 2 WHERE BaseSightRange > 0 AND NOT (CombatClass = 'UNITCOMBAT_SIEGE'); /* Unit Scale */ UPDATE ArtDefine_UnitMemberInfos SET Scale = Scale*3 WHERE Domain = 'Sea' AND NOT Type = 'ART_DEF_UNIT_MEMBER_TRANSPORT'; UPDATE ArtDefine_UnitMemberInfos SET Scale = Scale*2 WHERE Domain = 'Air'; UPDATE ArtDefine_UnitInfoMemberInfos SET NumMembers = 1 WHERE UnitMemberInfoType LIKE '%ART_DEF_UNIT_MEMBER_DESTROYER%'; UPDATE ArtDefine_UnitInfoMemberInfos SET NumMembers = 1 WHERE UnitMemberInfoType LIKE '%ART_DEF_UNIT_MEMBER_SUBMARINE%'; /* Aircraft Speed */ UPDATE ArtDefine_UnitMemberCombats SET MoveRate = 2*MoveRate; UPDATE ArtDefine_UnitMemberCombats SET TurnRateMin = 1.5*TurnRateMin WHERE MoveRate > 0; UPDATE ArtDefine_UnitMemberCombats SET TurnRateMax = 1.5*TurnRateMax WHERE MoveRate > 0;
Swift
UTF-8
1,050
2.890625
3
[ "MIT" ]
permissive
// // UIExtensions.swift // PFactors_Example // // Created by Stephan Jancar on 23.10.17. // Copyright © 2017 CocoaPods. All rights reserved. // import Foundation import UIKit extension UIView { var x : CGFloat { get { return self.frame.origin.x} } var y : CGFloat { get { return self.frame.origin.y} } var w : CGFloat { get { return self.frame.width} } var h : CGFloat { get { return self.frame.height} } } class CalcButton : UIButton { private (set) var type : CalcType = .Undefined var shiftbutton : CalcButton? = nil //If there is a second action when Shift ist pressed convenience init (type : CalcType) { self.init() self.type = type switch type { case .Plus,.Minus,.Divide,.Prod: break //Fontsize keeps default default: self.titleLabel?.font = self.titleLabel?.font.withSize(14) } } init() { super.init(frame : .zero) setTitleColor(.white, for: .normal) self.setTitleColor(.blue, for: .highlighted) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
C++
UTF-8
611
3.5625
4
[]
no_license
#include<iostream> #include<fstream> using namespace std; void perumtation(string a, int l, int r); int main() { string str = "ABC"; int n = str.length(); perumtation(str,0,n-1); return 0; } void perumtation(string a, int l, int r) { if(l == r) { cout<<a<<endl; } else { for (int i = l; i <= r; i++) { //cout<<"l: "<<l<<endl; swap(a[l],a[i]); //cout<<"swap1: "<<a<<endl; perumtation(a,l+1,r); swap(a[l],a[i]); //cout<<"swap2: "<<a<<endl; } } }
Java
UTF-8
142
1.726563
2
[ "Apache-2.0" ]
permissive
package com.airbnb.lottie; public interface LottieOnCompositionLoadedListener { void onCompositionLoaded(LottieComposition composition); }
Python
UTF-8
838
2.703125
3
[]
no_license
#!/usr/bin/python import socket import sys import os FILEPATH = sys.argv[1] SERVER_PORT = int(sys.argv[2]) def process_request(s): if not os.path.isfile(FILEPATH): send_not_exist(s) elif os.path.getsize(FILEPATH) == 0: send_empty(s) else: send_lines(s) def send_not_exist(s): send_line(s, '{"err": "FILE ON SERVER DOES NOT EXIST"}') def send_empty(s): send_line(s, '{"err": "FILE ON SERVER IS EMPTY"}') def send_lines(s): with open(FILEPATH) as fp: for line in fp: send_line(s, '{"line": "'+line.strip().upper()+'"}') def send_line(s, line): c, addr = s.accept() request = c.recv(16000).decode() if request == 'LINE': c.sendall(line.encode()) c.close() s = socket.socket() host = socket.gethostname() s.bind((host, SERVER_PORT)) s.listen(5) while True: process_request(s)
Swift
UTF-8
1,937
3.0625
3
[]
no_license
// // ViewController.swift // tic tac toe // // Created by Kevin Naik on 14/07/18. // Copyright © 2018 Kevin Naik. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var button: UIButton! @IBOutlet weak var output: UILabel! @IBAction func reset(_ sender: Any) { gamestate = [0,0,0,0,0,0,0,0,0] activegame = true player = 1 output.text = "" for var i in 1..<10 { let button = view.viewWithTag(i) as? UIButton button?.setImage(nil, for: []) i += 1 } } var activegame = true var player = 1 var gamestate = [0,0,0,0,0,0,0,0,0] var winner = [[0,1,2],[0,3,6],[3,4,5],[2,5,8],[6,7,8],[0,4,8],[2,4,6],[1,4,7]] @IBAction func buttonclicked(_ sender: Any) { print((sender as AnyObject).tag!) if gamestate[(sender as AnyObject).tag! - 1] == 0 && activegame { if player == 1 { gamestate[(sender as AnyObject).tag! - 1] = player (sender as AnyObject).setImage(UIImage (named: "zero.png"), for: []) player = 2 } else { gamestate[(sender as AnyObject).tag! - 1] = player (sender as AnyObject).setImage(UIImage (named: "cross.jpeg"), for: []) player = 1 } } for var check in winner { if gamestate[check[0]] != 0 && gamestate[check[0]] == gamestate[check[1]] && gamestate[check[1]] == gamestate[check[2]] { activegame = false output.text = " The winner is player \(gamestate[check[0]])" } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } }
C
UTF-8
5,359
2.828125
3
[ "LicenseRef-scancode-free-unknown", "Apache-2.0", "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later" ]
permissive
/* Integer base 2 logarithm calculation * * Copyright (C) 2006 Red Hat, Inc. All Rights Reserved. * Written by David Howells (dhowells@redhat.com) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _LINUX_LOG2_H #define _LINUX_LOG2_H #include <linux/types.h> #include <linux/bitops.h> /* * deal with unrepresentable constant logarithms */ extern __attribute__((const, noreturn)) int ____ilog2_NaN(void); /* * non-constant log of base 2 calculators * - the arch may override these in asm/bitops.h if they can be implemented * more efficiently than using fls() and fls64() * - the arch is not required to handle n==0 if implementing the fallback */ #ifndef CONFIG_ARCH_HAS_ILOG2_U32 static inline __attribute__((const)) int __ilog2_u32(u32 n) { return fls(n) - 1; } #endif #ifndef CONFIG_ARCH_HAS_ILOG2_U64 static inline __attribute__((const)) int __ilog2_u64(u64 n) { return fls64(n) - 1; } #endif /* * Determine whether some value is a power of two, where zero is * *not* considered a power of two. */ static inline __attribute__((const)) bool is_power_of_2(unsigned long n) { return (n != 0 && ((n & (n - 1)) == 0)); } /* * round up to nearest power of two */ static inline __attribute__((const)) unsigned long __roundup_pow_of_two(unsigned long n) { return 1UL << fls_long(n - 1); } /* * round down to nearest power of two */ static inline __attribute__((const)) unsigned long __rounddown_pow_of_two(unsigned long n) { return 1UL << (fls_long(n) - 1); } /** * ilog2 - log of base 2 of 32-bit or a 64-bit unsigned value * @n - parameter * * constant-capable log of base 2 calculation * - this can be used to initialise global variables from constant data, hence * the massive ternary operator construction * * selects the appropriately-sized optimised version depending on sizeof(n) */ #define ilog2(n) \ ( \ __builtin_constant_p(n) ? ( \ (n) < 1 ? ____ilog2_NaN() : \ (n) & (1ULL << 63) ? 63 : \ (n) & (1ULL << 62) ? 62 : \ (n) & (1ULL << 61) ? 61 : \ (n) & (1ULL << 60) ? 60 : \ (n) & (1ULL << 59) ? 59 : \ (n) & (1ULL << 58) ? 58 : \ (n) & (1ULL << 57) ? 57 : \ (n) & (1ULL << 56) ? 56 : \ (n) & (1ULL << 55) ? 55 : \ (n) & (1ULL << 54) ? 54 : \ (n) & (1ULL << 53) ? 53 : \ (n) & (1ULL << 52) ? 52 : \ (n) & (1ULL << 51) ? 51 : \ (n) & (1ULL << 50) ? 50 : \ (n) & (1ULL << 49) ? 49 : \ (n) & (1ULL << 48) ? 48 : \ (n) & (1ULL << 47) ? 47 : \ (n) & (1ULL << 46) ? 46 : \ (n) & (1ULL << 45) ? 45 : \ (n) & (1ULL << 44) ? 44 : \ (n) & (1ULL << 43) ? 43 : \ (n) & (1ULL << 42) ? 42 : \ (n) & (1ULL << 41) ? 41 : \ (n) & (1ULL << 40) ? 40 : \ (n) & (1ULL << 39) ? 39 : \ (n) & (1ULL << 38) ? 38 : \ (n) & (1ULL << 37) ? 37 : \ (n) & (1ULL << 36) ? 36 : \ (n) & (1ULL << 35) ? 35 : \ (n) & (1ULL << 34) ? 34 : \ (n) & (1ULL << 33) ? 33 : \ (n) & (1ULL << 32) ? 32 : \ (n) & (1ULL << 31) ? 31 : \ (n) & (1ULL << 30) ? 30 : \ (n) & (1ULL << 29) ? 29 : \ (n) & (1ULL << 28) ? 28 : \ (n) & (1ULL << 27) ? 27 : \ (n) & (1ULL << 26) ? 26 : \ (n) & (1ULL << 25) ? 25 : \ (n) & (1ULL << 24) ? 24 : \ (n) & (1ULL << 23) ? 23 : \ (n) & (1ULL << 22) ? 22 : \ (n) & (1ULL << 21) ? 21 : \ (n) & (1ULL << 20) ? 20 : \ (n) & (1ULL << 19) ? 19 : \ (n) & (1ULL << 18) ? 18 : \ (n) & (1ULL << 17) ? 17 : \ (n) & (1ULL << 16) ? 16 : \ (n) & (1ULL << 15) ? 15 : \ (n) & (1ULL << 14) ? 14 : \ (n) & (1ULL << 13) ? 13 : \ (n) & (1ULL << 12) ? 12 : \ (n) & (1ULL << 11) ? 11 : \ (n) & (1ULL << 10) ? 10 : \ (n) & (1ULL << 9) ? 9 : \ (n) & (1ULL << 8) ? 8 : \ (n) & (1ULL << 7) ? 7 : \ (n) & (1ULL << 6) ? 6 : \ (n) & (1ULL << 5) ? 5 : \ (n) & (1ULL << 4) ? 4 : \ (n) & (1ULL << 3) ? 3 : \ (n) & (1ULL << 2) ? 2 : \ (n) & (1ULL << 1) ? 1 : \ (n) & (1ULL << 0) ? 0 : \ ____ilog2_NaN() \ ) : \ (sizeof(n) <= 4) ? \ __ilog2_u32(n) : \ __ilog2_u64(n) \ ) /** * roundup_pow_of_two - round the given value up to nearest power of two * @n - parameter * * round the given value up to the nearest power of two * - the result is undefined when n == 0 * - this can be used to initialise global variables from constant data */ #define roundup_pow_of_two(n) \ ( \ __builtin_constant_p(n) ? ( \ (n == 1) ? 1 : \ (1UL << (ilog2((n) - 1) + 1)) \ ) : \ __roundup_pow_of_two(n) \ ) /** * rounddown_pow_of_two - round the given value down to nearest power of two * @n - parameter * * round the given value down to the nearest power of two * - the result is undefined when n == 0 * - this can be used to initialise global variables from constant data */ #define rounddown_pow_of_two(n) \ ( \ __builtin_constant_p(n) ? ( \ (1UL << ilog2(n))) : \ __rounddown_pow_of_two(n) \ ) /** * order_base_2 - calculate the (rounded up) base 2 order of the argument * @n: parameter * * The first few values calculated by this routine: * ob2(0) = 0 * ob2(1) = 0 * ob2(2) = 1 * ob2(3) = 2 * ob2(4) = 2 * ob2(5) = 3 * ... and so on. */ #define order_base_2(n) ilog2(roundup_pow_of_two(n)) #endif /* _LINUX_LOG2_H */
Python
UTF-8
2,351
3.015625
3
[]
no_license
import os from tqdm.notebook import tqdm as tqdm_notebook from tqdm import tqdm import requests def download_file_with_progress_bar(url, filename=None, download_dir=os.curdir, mkdir=True, redownload=False): # From https://stackoverflow.com/a/37573701/4228052 # Use the filename from the end of the URL by default if filename is None: filename = os.path.basename(url) # Make sure the download directory exists if not os.path.exists(download_dir): if mkdir: os.makedirs(download_dir) else: raise FileNotFoundError("Download directory '{}' does not exist, and `mkdir` option is disabled.".format(download_dir)) elif not os.path.isdir(download_dir): raise NotADirectoryError("Download directory '{}' exists, but is not actually a directory!".format(download_dir)) download_path = os.path.join(download_dir, filename) None if os.path.exists(download_path) and not redownload: print("File '{}' already exists - not re-downloading {}".format(download_path, url)) return # Streaming, so we can iterate over the response. response = requests.get(url, stream=True) # Quit early if there's an error try: response.raise_for_status() except requests.exceptions.HTTPError as e: raise requests.exceptions.HTTPError("Failed to download {} to {}".format(url, download_path)) from e # Create the progress bar total_size_in_bytes = int(response.headers.get('content-length', 0)) block_size = 1024 #1 Kibibyte try: progress_bar = tqdm_notebook(total=total_size_in_bytes, unit='iB', unit_scale=True, desc=download_path) except ImportError: progress_bar = tqdm(total=total_size_in_bytes, unit='iB', unit_scale=True, desc=download_path, mininterval=5) # Write the file with open(download_path, 'wb') as file: for data in response.iter_content(block_size): progress_bar.update(len(data)) file.write(data) # Make sure the download completed if total_size_in_bytes != 0 and progress_bar.n != total_size_in_bytes: progress_bar.clear() raise ValueError("Unexpected error: failed to completely download {}".format(url)) progress_bar.close() return response
Python
UTF-8
11,202
2.890625
3
[]
no_license
''' The HeightSelector module only contains the HeighSelector class. It is intended to create a dialog that gives suggestions to the user for collimation. I would highly suggest going to the tkdocs website (google it) for tutorials on widgets in ttk/tkinter. @author: Collin ''' from Tkinter import * import ttk from tkSimpleDialog import Dialog import tkMessageBox class HeightSelector(Dialog): ''' HeightSelector is a Dialog that provides suggestions to user for the height of the collimtor and dimension of the aperature based on the dimensions of treatment size on the target. ''' #constant defines for shape selection CIRCLE="CIRCLE" SQUARE="SQUARE" RECTANGLE="RECTANGLE" def __init__(self,mainGuiWindow,title="move"): ''' Constructor ''' Toplevel.__init__(self, mainGuiWindow) self.withdraw() # remain invisible for now # If the master is not viewable, don't # make the child transient, or else it # would be opened withdrawn if mainGuiWindow.winfo_viewable(): self.transient(mainGuiWindow) if title: self.title(title) self.mainGuiWindow = mainGuiWindow self.result = None body = Frame(self) self.initial_focus = self.body(body) body.grid(column=0,row=0,padx=5, pady=5) self.buttonbox() #self.updateText([1,2,3,4]) if not self.initial_focus: self.initial_focus = self self.protocol("WM_DELETE_WINDOW", self.cancel) if self.mainGuiWindow is not None: self.geometry("+%d+%d" % (mainGuiWindow.winfo_rootx() + 50, mainGuiWindow.winfo_rooty() + 50)) #self.updateText([32.1,12.7,5,13.4]) self.deiconify() # become visibile now self.initial_focus.focus_set() # wait for window to appear on screen before calling grab_set self.wait_visibility() self.grab_set() self.lift() self.wait_window(self) def destroy(self): '''Destroy the window''' self.initial_focus = None Toplevel.destroy(self) def body(self, master): '''create dialog body. return widget that should have initial focus. This method should be overridden, and is called by the __init__ method. ''' pass def buttonbox(self): ''' Initializes most of the GUI components. Called by the constructor. ''' self.title("Collimator") self.box = Frame(self) self.box.grid(column=0,row=0) self.plateHeight = 0.0 self.collimatorBlank = 0.0 self.collimatorBlankShape = "Circle" shapeSelectFrame=ttk.Labelframe(self.box,text="Select apperature shape") shapeSelectFrame.grid(row=0,column=0,padx=5,pady=5,columnspan=3) self.shape = StringVar() self.shape.set(HeightSelector.CIRCLE) circle = ttk.Radiobutton(shapeSelectFrame, text='Circle', variable=self.shape, value=HeightSelector.CIRCLE,command=self.selection) square = ttk.Radiobutton(shapeSelectFrame, text='Square', variable=self.shape, value=HeightSelector.SQUARE,command=self.selection) rectangle = ttk.Radiobutton(shapeSelectFrame, text='Rectangle', variable=self.shape, value=HeightSelector.RECTANGLE,command=self.selection) circle.grid(row=0,column=0) square.grid(row=0,column=1) rectangle.grid(row=0,column=2) self.dimensionLabel=ttk.Label(self.box,text="Diameter: ") self.dimensionLabel.grid(row=1,column=0) self.dimensionVariable=StringVar() self.dimensionEntry=Entry(self.box,textvariable=self.dimensionVariable) self.dimensionEntry.config(highlightcolor="GOLD", bd=2, highlightthickness=1, relief=GROOVE) self.dimensionEntry.grid(column=1,row=1) dimensionUnits=ttk.Label(self.box,text="mm") dimensionUnits.grid(row=1,column=2) self.circleImg=PhotoImage(file="circle.gif") self.rectangleImg=PhotoImage(file="rectangle.gif") self.squareImg=PhotoImage(file="square.gif") self.imageLabel=ttk.Label(self.box,image=self.circleImg) self.imageLabel.grid(row=2,column=0,columnspan=3,pady=5) buttonFrame=ttk.Frame(self.box) buttonFrame.grid(column=0,row=3,columnspan=3) w = ttk.Button(buttonFrame, text="OK", width=10, command=self.ok, default=ACTIVE) w.grid(column=0,row=0, padx=5, pady=5,sticky=(E)) w = ttk.Button(buttonFrame, text="cancel", width=10, command=self.cancel) w.grid(column=1,row=0, padx=5, pady=5,sticky=(W)) self.bind("<Return>", self.ok) self.bind("<Escape>", self.cancel) self.height = 564.5 self.bottomLimit = 423.0 self.topLimit = 203.7 self.topRatio = self.height/self.topLimit self.bottomRatio = self.height/self.bottomLimit self.squareSizes = [24.0,14.0,9.0,5.0,3.0] #size of the square blanks in descending size self.circleSizes = [8.0,4.0,2.0,1.6,1.0,0.5] #size of the circle blanks in descending size self.rectangleSizes = [6.0,3.0] #side of the rectangle blanks in descending size self.message = "" def ok(self, event=None): ''' Proceeds to give suggestion for collimation if validation is ok. Call back function for the "ok" button on the GUI. ''' if not self.validate(): self.initial_focus.focus_set() # put focus back return self.calculateHeight() self.withdraw() self.update_idletasks() try: self.apply() finally: self.cancel() def cancel(self, event=None): ''' Called to destroy the dialog and set focus back to the main GUI. Can be called as a call back function for the "cancel" button or at the last step after pressing the "ok" button. ''' # put focus back to the parent window if self.mainGuiWindow is not None: self.mainGuiWindow.focus_set() self.destroy() def validate(self): ''' Validates that the user entered a number. This method is called automatically to validate the data before the dialog is destroyed. ''' try: float(self.dimensionVariable.get()) return 1 except: return 0 def apply(self): ''' Displays an information dialog to the user giving them the suggested parameters for collimation. ''' tkMessageBox.showinfo("Suggestion", "%s" % self.message) def selection(self): ''' Handles the users selection for aperature shape. Call back function for the three radiobuttons (circle, square, and rectangle). ''' if(self.shape.get()==HeightSelector.CIRCLE): self.dimensionLabel['text']="Diameter: " self.imageLabel['image']=self.circleImg if(self.shape.get()==HeightSelector.SQUARE): self.dimensionLabel['text']="Length: " self.imageLabel['image']=self.squareImg if(self.shape.get()==HeightSelector.RECTANGLE): self.dimensionLabel['text']="Height: " self.imageLabel['image']=self.rectangleImg def calculateHeight(self): ''' Based on the users entered shape and size, calculateHeight figures out the suggested settings for collimation. Stores the suggestion in self.message. ''' desiredSize = float(self.dimensionVariable.get()) if(self.shape.get()==HeightSelector.CIRCLE): '''calculate the height using the circle array''' self.collimatorBlankShape="diameter circle" if desiredSize/self.circleSizes[0] > self.topRatio: self.plateHeight = 0.00 self.collimatorBlank = 0.00 else: i = 0 ratio = desiredSize/self.circleSizes[i] while (ratio < self.bottomRatio or ratio > self.topRatio) and i < len(self.circleSizes)-1: i = i + 1 ratio = desiredSize/self.circleSizes[i] if i >= len(self.circleSizes)-1 and ratio < self.bottomRatio: self.collimatorBlank = 1.0 self.plateHeight = 1.0 else: self.collimatorBlank = self.circleSizes[i] self.plateHeight = (self.bottomRatio/ratio)*self.bottomLimit if(self.shape.get()==HeightSelector.SQUARE): '''calculate the height using the square array''' self.collimatorBlankShape="length square" if desiredSize/self.squareSizes[0] > self.topRatio: self.plateHeight = 0.00 self.collimatorBlank = 0.00 else: i = 0 ratio = desiredSize/self.squareSizes[i] while (ratio < self.bottomRatio or ratio > self.topRatio) and i < len(self.squareSizes)-1: i = i + 1 ratio = desiredSize/self.squareSizes[i] if i >= len(self.squareSizes)-1 and ratio < self.bottomRatio: self.collimatorBlank = 1.0 self.plateHeight = 1.0 else: self.collimatorBlank = self.squareSizes[i] self.plateHeight = (self.bottomRatio/ratio)*self.bottomLimit if(self.shape.get()==HeightSelector.RECTANGLE): '''calculate the height using the rectangle array''' self.collimatorBlankShape="height rectangle" if desiredSize/self.rectangleSizes[0] > self.topRatio: self.plateHeight = 0.00 self.collimatorBlank = 0.00 else: i = 0 ratio = desiredSize/self.rectangleSizes[i] while (ratio < self.bottomRatio or ratio > self.topRatio) and i < len(self.rectangleSizes)-1: i = i + 1 ratio = desiredSize/self.rectangleSizes[i] if i >= len(self.rectangleSizes)-1 and ratio < self.bottomRatio: self.collimatorBlank = 1.0 self.plateHeight = 1.0 else: self.collimatorBlank = self.rectangleSizes[i] self.plateHeight = (self.bottomRatio/ratio)*self.bottomLimit if self.plateHeight == 1.00: self.message = "The requested hole size is too small for the current collimator blanks." elif self.plateHeight == 0.00: self.message = "The requested hole size is too large for the current collimator blanks." else: self.message = "Collimator Distance: %.2f cm\nCollimator Blank: %.2f mm %s." % ( self.plateHeight/10.0, self.collimatorBlank, self.collimatorBlankShape)
C++
UTF-8
531
3.109375
3
[ "MIT" ]
permissive
#pragma once #include <SFML/Graphics.hpp> namespace overmon { /// The variable type signifying unique sprites. typedef uint8_t AreaId; /// Loads and stores area metadata. template<typename T> class BaseAreaManager { public: /// Sets and loads the indicated area. void areaSet(AreaId id) { static_cast<T*>(this)->areaSet(id); } /// Draws the current area. void draw(sf::RenderTarget &target, const sf::RenderStates& states = sf::RenderStates::Default) const { static_cast<T*>(this)->draw(target, states); } }; }
Java
UTF-8
2,172
2.265625
2
[ "BSD-3-Clause" ]
permissive
package org.ndexbio.cxio.aspects.readers; import java.io.IOException; import org.ndexbio.cxio.aspects.datamodels.ATTRIBUTE_DATA_TYPE; import org.ndexbio.cxio.aspects.datamodels.AbstractAttributesAspectElement; import org.ndexbio.cxio.aspects.datamodels.AttributesAspectUtils; import org.ndexbio.cxio.aspects.datamodels.HiddenAttributesElement; import org.ndexbio.cxio.core.interfaces.AspectElement; import com.fasterxml.jackson.databind.node.ObjectNode; public class HiddenAttributesFragmentReader extends AbstractFragmentReader { public static HiddenAttributesFragmentReader createInstance() { return new HiddenAttributesFragmentReader(); } private HiddenAttributesFragmentReader() { super(); } @Override public String getAspectName() { return HiddenAttributesElement.ASPECT_NAME; } @Override public AspectElement readElement(final ObjectNode o) throws IOException { ATTRIBUTE_DATA_TYPE type = ATTRIBUTE_DATA_TYPE.STRING; if (o.has(AbstractAttributesAspectElement.ATTR_DATA_TYPE)) { type = AttributesAspectUtils.toDataType(ParserUtils.getTextValueRequired(o, AbstractAttributesAspectElement.ATTR_DATA_TYPE)); } if (ParserUtils.isArray(o, AbstractAttributesAspectElement.ATTR_VALUES)) { return new HiddenAttributesElement(ParserUtils.getTextValueAsLong(o, AbstractAttributesAspectElement.ATTR_SUBNETWORK), ParserUtils.getTextValueRequired(o, AbstractAttributesAspectElement.ATTR_NAME), ParserUtils.getAsStringList(o, AbstractAttributesAspectElement.ATTR_VALUES), type); } return new HiddenAttributesElement(ParserUtils.getTextValueAsLong(o, AbstractAttributesAspectElement.ATTR_SUBNETWORK), ParserUtils.getTextValueRequired(o, AbstractAttributesAspectElement.ATTR_NAME), ParserUtils.getTextValue(o, AbstractAttributesAspectElement.ATTR_VALUES), type); } }
Python
UTF-8
3,964
3.375
3
[]
no_license
""" Sample script to parse xr and ct radiology notes. """ import re import numpy as np import pandas as pd import glob, os import timeit # Start timer start_time = timeit.default_timer() # Specify notes directory and columns to parse notes_dir = input("What is the path to the notes?") # feel free to replace with the path to avoid being prompted every execution notes = glob.glob(os.path.join(notes_dir, "*.txt")) note_cols = ['ScanType', 'ScanDate', 'ClinInfo', 'Technique', 'Comparison', 'Findings', 'Impressions', 'ElecSig', 'RawText'] # Helper functions for parsing def between(value, a, b): """ Parse a substring between two other substrings. """ # Find and validate before substring. pos_a = value.find(a) if pos_a == -1: return "" # Find and validate after substring. pos_b = value.rfind(b) if pos_b == -1: return "" # Return between substring. adjusted_pos_a = pos_a + len(a) if adjusted_pos_a >= pos_b: return "" return value[adjusted_pos_a:pos_b] def before(value, a): """ Parse a substring before (the first instance of) another substring. """ # Find value string and return substring before it. pos_a = value.find(a) if pos_a == -1: return "" return value[0:pos_a] def after(value, a): """ Parse a substring after (the first instance of) another substring. """ # Find and validate first part. pos_a = value.find(a) if pos_a == -1: return "" # Returns chars after the found string. adjusted_pos_a = pos_a + len(a) if adjusted_pos_a >= len(value): return "" return value[adjusted_pos_a:] def parse_note(text): """ Parse note and return array including each element. """ scan_type = before(text, '**DATE<[').strip() scan_date = between(text, '**DATE<[**', 'CLINICAL INFORMATION: ').strip() clininfo = between(text, 'CLINICAL INFORMATION: ', ' TECHNIQUE: ').strip() technique = between(text, 'TECHNIQUE: ', ' COMPARISON: ').strip() comparison = between(text, 'COMPARISON: ', '\n\nFINDINGS:\n\n').strip() findings = between(text, '\n\nFINDINGS:\n\n', '\n\nIMPRESSION:\n\n').strip() impression = between(text, '\n\nIMPRESSION:\n\n', 'Report Electronically Signed:').strip() elec_sig = after(text, 'Report Electronically Signed: ').strip() raw_text = text return [scan_type, scan_date, clininfo, technique, comparison, findings, impression, elec_sig, raw_text] def parsed_note_to_df(parsed_note_array): """ Converts an array of note elements into a dataframe """ temp_dict = dict(zip(note_cols, parsed_note_array)) return pd.DataFrame(temp_dict, index = [0]) def main(): """ Parse notes and write to csv. """ notes_str = [] for note in notes: with open(note, 'r') as file: notes_str.append(file.read()) df_each_note = (parsed_note_to_df(parse_note(note)) for note in notes_str) df = pd.concat(df_each_note, ignore_index=True) df = df[note_cols] df.to_csv('notes_df.csv') # Parse main() execution_time = timeit.default_timer() - start_time print('Completed in ', str(format(execution_time, '.2f')), ' seconds.') """ Regex below works but might be slower. Can try with larger data set. Substitute this stuff into parse_note. scan_type = text.partition('**DATE<[')[0].strip() scan_date = re.search('DATE(.*) CLINICAL INFORMATION: ', text).group(1).strip() clininfo = re.search('CLINICAL INFORMATION: (.*) TECHNIQUE: ', text).group(1).strip() technique = re.search('TECHNIQUE: (.*) COMPARISON: ', text).group(1).strip() comparison = re.search('COMPARISON: (.*)\n\nFINDINGS:\n\n', text).group(1).strip() findings = re.search('\n\nFINDINGS:\n\n(.*)\n\nIMPRESSION:\n\n', text).group(1).strip() impression = re.search('\n\nIMPRESSION:\n\n(.*)Report Electronically Signed:', text).group(1).strip() elec_sig2 = text.partition('Report Electronically Signed: ')[2].strip() # try catch if no match """
Python
UTF-8
7,808
3
3
[]
no_license
# # File: Contour_Detect_Drive # # Author: Jacob Gerecht and Austin Smith # # Created: 11-09-2018 # # Purpose: This code locates the orange circle that makes up our beacon and indicates # it with a bright green circle on the displayed image. The detected blob is also printed # to the console to provide feedback information. The code also estimates the distance and angle # the target is located at. The key change here is using contours to define the detected blob, # then using a minimal enclosing circle to estimate the size. This is to deal with the issue # of viewing the beacon like an elipse # # Use: Ensure that the pi is running on the cv environment. Make sure the picamera # is properly attached and installed with the pip install "picamra[array]" command. # Make sure cv2.so file is in the same directory as the script # #Setup I2C libraries and LCD import smbus import Adafruit_CharLCD as LCD import subprocess #Setting up all relevent libraries from picamera import PiCamera from time import sleep import numpy as np import cv2 #setup I2C bus = smbus.SMBus(1) address = 0x04 #flags for beacon detection beacon_flag = False arduinoReady = False #LCD Setup ##while(True): ## try: ## lcd = LCD.Adafruit_CharLCDPlate() ## break ## except IOError as e: ## subprocess.call(['i2cdetect', '-y', '1']) ## print("Error connecting to LCD, retrying") #function for sending data to Arduino def sendData(signal1, signal2, signal3): print("sending data: ", signal1, signal2, signal3) try: bus.write_i2c_block_data(address, 2, [signal1, signal2, signal3]) except IOError as e: subprocess.call(['i2cdetect', '-y', '1']) print("Trying to send data again") sendData(signal1, signal2, signal3) return #function for receiving data from Arduino def ReceiveData(): print("Receiving data") try: temp = bus.read_byte(address) print("readyflag variable from arduino =", temp) return temp except IOError as e: subprocess.call(['i2cdetect', '-y', '1']) print("reasking for data") ReceiveData() return def LCDSend(message, var): print("Sending: ", message, " to LCD") print("Sending: ", var, " to LCD") try: #sending Message and Variable to LCD lcd.clear() lcd.message(message + " \n") lcd.message(str(var)) except IOError as e: subprocess.call(['i2cdetect', '-y', '1']) LCDSend(message, var) return def LCDSend1(message): print("Sending: ", message, " to LCD") try: #sending Message and Variable to LCD lcd.clear() lcd.message(message + " \n") except IOError as e: subprocess.call(['i2cdetect', '-y', '1']) LCDSend1(message) return print("I2C ready") #variables for sending to arduino desiredDistance = 0 desiredAngle = 0 camera = PiCamera() camera.resolution = (640, 640) lower_g = np.array([55, 70, 60]) upper_g = np.array([80, 200, 155]) #1 is to the left, -1 is to the right, 0 is straight on direction = 0; while (1): #creates an empty numpy array to store the image in image = np.empty((640*640*3,), dtype=np.uint8) #captures the image and stores in numpy array camera.capture(image, 'bgr') #Organizes array into 320 X 320 X 3 arrangements for x, y, and brg placement image = image.reshape((640, 640, 3)) #Converts to HSV color scheme hsv_img = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) #Green Filter green_final = cv2.inRange(hsv_img, lower_g, upper_g) #Removes noise from the color isolated images kernel_erode = np.ones((15,15),np.uint8) kernel_dilate = np.ones((10,10),np.uint8) green_final = cv2.morphologyEx(green_final, cv2.MORPH_OPEN, kernel_erode) green_final = cv2.morphologyEx(green_final, cv2.MORPH_DILATE, kernel_dilate) #locates the contours green_final, contours, hierarchy = cv2.findContours(green_final, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE) #for each found contour, filter for both size and circularity beacons = [] for contour in contours: #approximation for how cirular the contour is approx = cv2.approxPolyDP(contour, 0.01*cv2.arcLength(contour, True),True) area = cv2.contourArea(contour) #print len(approx) if ((len(approx) > 4) and (len(approx) < 23) and (area > 30)): beacons.append(contour) #if it fits, add it to our list if(len(beacons) >= 1): beacon_flag = True else: beacon_flag = False if(beacon_flag == False): desiredAngle = 45 print("beacon not found, angle set to 45") for beacon in beacons: #incribe an enclosing circle around the found beacon (x,y),radius = cv2.minEnclosingCircle(beacon) center = (int(x),int(y)) radius = int(radius) if (y < 200) : continue #also draw a rectangle, we will use the width and height to find aspect ratio (how much like an elipse) r1,r2,w,h = cv2.boundingRect(beacon) aspect_ratio = float(w)/h if (aspect_ratio > 1): aspect_ratio = 1 corrected = radius + (1 - aspect_ratio)*10 pix_from_center = 320 - int(x) if pix_from_center < -20 : direction = -1 elif pix_from_center > 20: direction = 1 else : direction = 0 #print abs(pix_from_center) #print float(pix_from_center)/320 angle = float(abs(pix_from_center))/320*25 print("angle:",angle) #Use the radius from drawn circle as a reference #Have to apply a corrrective factor of (1 - aspect_ratio)*10 in order to account for possible elipse #Use the equasion dist = 8839.2*(corrected)^-1.064 to estimate the distance #print "Green Radius: %.01f, Ratio: %0.01f Correction: %0.01f" % (radius, aspect_ratio, corrected) #create distance for sending to arduino desiredDistance = int(float(10021)*float(corrected)**-1.089) #print "Green Distance: %0.01f cm" % (10021*(corrected)**-1.089) #print "Angle: %0.01f degrees, %0.01f direction" % (angle, direction) image = cv2.circle(image, center, radius, (70, 255, 1), 3) green_final = cv2.circle(green_final, center, radius, (70, 255, 1), 3) #create desiredAngle and send to arduino desiredAngle = int(angle) arduinoReady = ReceiveData() if(arduinoReady == False): print("Arduino Ready for data",arduinoReady) elif(arduinoReady == True): print("Arduino not ready for data",arduinoReady) if(direction != 0 and arduinoReady == False): print("Direction = ",direction," desiredAngle: %0.01f" % desiredAngle) sendData(0,desiredDistance,direction) if(direction == 0 and arduinoReady == False): print("Direction = 0, %0.01f" % desiredDistance) sendData(0,desiredDistance,direction) if(beacon_flag == False and arduinoReady == False): print("Beacon not detected rotating by ",desiredAngle) sendData(desiredAngle, 0, direction) sleep(1) #saves the image cv2.imwrite("green.jpg", green_final) cv2.imwrite("Robo-View.jpg", image) cv2.namedWindow("Robo-View") cv2.namedWindow("Green Filter") #shows the image, and wait key takes the keyboard input cv2.imshow("Robo-View", image) cv2.imshow("Green Filter", green_final) ## if(beacon_flag): ## LCDSend1("Beacon Detected") ## else: ## lcd.clear() k = cv2.waitKey(1) #27 == ESC key if k == 27: break #closes all display windows cv2.destroyAllWindows()
Java
UTF-8
302
1.765625
2
[]
no_license
package com.tortoise.control; import com.tortoise.bean.ResultBean; /** * @author pengli * @create 2021-08-05 17:30 * * 控制类 核心基类 */ public class BaseControl { public ResultBean getResultBean(){ ResultBean result= ResultBean.builder().build(); return result; } }
Shell
UTF-8
1,018
2.59375
3
[ "MIT" ]
permissive
#!/bin/sh echo "Download bundable opendjk" wget -c https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk11u-2019-10-16-10-43/OpenJDK11U-jdk_x64_linux_hotspot_2019-10-16-10-43.tar.gz tar xf OpenJDK11U-jdk_x64_linux_hotspot_2019-10-16-10-43.tar.gz echo "Download and build Newton Adventure" git clone https://github.com/devnewton/newton_adventure.git newton_adventure (cd newton_adventure; mvn package) cp newton_adventure/game/lwjgl/target/newton-adventure.jar NewtonAdventure.AppDir/ echo "Build custom jdk" NEWTON_ADVENTURE_DEPS=`./jdk-11.0.5+9/bin/jdeps --print-module-deps newton_adventure/game/lwjgl/target/newton-adventure.jar` ./jdk-11.0.5+9/bin/jlink --no-header-files --no-man-pages --compress=2 --strip-debug --add-modules $NEWTON_ADVENTURE_DEPS --output NewtonAdventure.AppDir/usr wget -c https://github.com/AppImage/AppImageKit/releases/download/12/appimagetool-x86_64.AppImage chmod +x appimagetool-x86_64.AppImage ARCH=x86_64 ./appimagetool-x86_64.AppImage NewtonAdventure.AppDir/
C++
UTF-8
251
2.609375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main(){ long long a, b; cin >> a >> b; if(a > 0 && b > 0){ cout << "I"; } else if(a > 0 && b < 0){ cout << "IV"; } else if(a < 0 && b > 0){ cout << "II"; } else cout << "III"; }
C++
UTF-8
3,023
3.015625
3
[]
no_license
#include <iostream> #include <fstream> #include <vector> #include <cstdlib> #include <sstream> using namespace std; void readData(const string &, vector<double> &, vector<double> &); double interpolation(double, const vector<double> &, const vector<double> &); bool isOrdered(const vector<double> &); void reorder(vector<double> &, vector<double> &); int main(int argc, char *argv[]) { string fileName = argv[1]; vector<double> fPath; vector<double> coLift; double fAngle; readData(fileName, fPath, coLift); for(unsigned int i = 0; i < fPath.size(); i++) { cout << fPath.at(i) << ' '; } cout << endl; if (!isOrdered(fPath)) { reorder(fPath, coLift); } for(unsigned int i = 0; i < fPath.size(); i++) { cout << fPath.at(i) << ' '; } string response = "Yes"; while (response != "No" && response == "Yes") { cout << "Choose a flight path angle: "; cin >> fAngle; cout << interpolation(fAngle, fPath, coLift); cout << endl; cout << endl; cout << "Choose another flight path angle? "; cin >> response; cout << endl; } return 0; } void readData(const string& fileName, vector<double>& fpath, vector<double>& coLift) { string line; ifstream nFile; nFile.open(fileName.c_str()); double f; double c; if(!nFile.is_open()){ cout << "Error opening " << fileName << endl; exit(1); } while (getline(nFile, line)) { stringstream temp(line); temp >> f >> c; fpath.push_back(f); coLift.push_back(c); } } double interpolation(double pAngle, const vector<double>&fpath, const vector<double>&coLift) { double interpol; for (unsigned int i = 0; i < fpath.size(); i++) { if (fpath.at(i) == pAngle) { return coLift.at(i); } else if (fpath.at(i) < pAngle && fpath.at(i+1) > pAngle && i+1 != fpath.size()) { interpol = coLift.at(i) + (pAngle - fpath.at(i))/(fpath.at(i+1) - fpath.at(i)) * (coLift.at(i+1) - coLift.at(i)); } } return interpol; } bool isOrdered(const vector<double>& fpath) { bool isOrder = true; for (unsigned int i = 0; i + 1 < fpath.size(); i++) { if (fpath.at(i) > fpath.at(i+1)) { isOrder = false; } } return isOrder; } void reorder(vector<double>& fpath, vector<double>& coLift) { int indexH; double swap; double min; for(unsigned int i = 0; i < fpath.size(); i++) { min = fpath.at(i); indexH = i; for(unsigned int j = i; j < fpath.size(); j++) { if (fpath.at(j) < min) { min = fpath.at(j); indexH = j; } } swap = fpath.at(i); fpath.at(i) = fpath.at(indexH); fpath.at(indexH) = swap; swap = coLift.at(i); coLift.at(i) = coLift.at(indexH); coLift.at(indexH) = swap; } }
Markdown
UTF-8
2,398
2.84375
3
[]
no_license
#### Event loop https://github.com/nodejs/node/blob/master/lib/fs.js #### Signals A signal is a limited form of inter-process communication used in Unix, Unix-like and other POSIX-compliant operating systems. It is an asynchronous notification sent to a process, or to a specific thread, within the same process in order to notify it of an event that occurred. #### Child processes A fundamenetal part of Node's design is to create or fork processes when parallelizing execution or scaling a system, as opposed to creating a thread pool ```javascript let cp = require('child_process'); let child = cp.fork(__dirname + '/lovechild.js'); ``` #### File events Node allows developers to register for notifications on the file events through the `fs.watch` method. The watch method broadcasts changed events on both files and directories. ```javascript fs.watch('file or directory', {}, callback) ``` ### Deferred execution `process.nextTick` delays execution of its callback function until some point in the future. The primary use of `nextTick` in a function is to postpone the broadcast of result events to listeners on the current execution stack until the caller has had an opportunity to register event listeners, giving the current executing program a chance to bind callbacks to `EventEmitter.emit` events. `setImmediate`: Node will actually run the function you give to nextTick before the one you pass to setImmediate. ### Building Twitter feeds using file events The goal is to create a server taht a client can connect to and receive updates from Twitter. We will first create a process to query Twitter for any messages with the hashtag #nodejs, and write any found messages to a tweets.txt file in 140-byte chunks. We will then create a network server that broadcasts these messages to a single client. Those broadcasts will be triggered by write events on the tweets.txt file Whenever a write occurs, 140-bytes chunk are asynchronously read from the last-known client read pointer. Finally we will create a simple client.html page, which asks for, receives and displays these messages. This demonstrates: - Listening to filesystem for changes, and responding to those events - Using data streams events for reading and writing files - Responding to network events - Using timeouts for polling state - Using a node server itself as a network event broadcaster
Ruby
UTF-8
864
3.0625
3
[]
no_license
class UnionFind def initialize(nodes) @leaders = Hash.new @leaders = nodes @changes = @leaders # array.each do |edge| # @leaders[edge[1]] = [edge[1]] unless @leaders.has_key?(edge[1]) # @leaders[edge[2]] = [edge[2]] unless @leaders.has_key?(edge[2]) # end # @changes = @leaders end def same?(id1,id2) @leaders[id1] == @leaders[id2] end def union(id1,id2) @leaders[id1] = @leaders[id1].concat(@leaders[id2]) @changes[id2].each do |id| @leaders[id] = @leaders[id1] @leaders[id].sort!.uniq! end @changes[id1] = @changes[id1].concat([id2]) end def values @leaders.values.uniq end def all_values @leaders.values end end def test a = UnionFind.new([1,2,3,4,5]) a.union(1,4) a.union(4,5) puts a.connected?(1,5) puts a.connected?(1,2) == false end test
PHP
UTF-8
165
2.921875
3
[]
no_license
<?php // 自分の得意な言語で // Let's チャレンジ!! $N = trim(fgets(STDIN)); for($i=$N;$i>0;$i--){ echo $i ."\n"; } ?>
Java
UTF-8
7,574
1.84375
2
[]
no_license
package com.example.tony.finalproject_plants; import android.Manifest; import android.app.Activity; import android.app.FragmentTransaction; import android.content.Context; import android.content.pm.PackageManager; import android.database.sqlite.SQLiteDatabase; import android.graphics.Bitmap; import android.graphics.Typeface; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.Window; import android.widget.TextView; import android.widget.Toast; import com.baidu.mapapi.SDKInitializer; import org.litepal.crud.DataSupport; import org.litepal.tablemanager.Connector; import java.io.IOException; import java.io.InputStream; import java.util.List; public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private TextView tabNote; private TextView tabMap; private TextView tabAdd; private TextView tabFind; private noteclass noteFragment; private mapclass mapFragmet; private findclass findFragmet; private addClass addFragmet; private String[] permissions = {Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_WIFI_STATE,Manifest.permission.CHANGE_WIFI_STATE,Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.INTERNET,Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, Manifest.permission.CAMERA}; Typeface mtypeface; @RequiresApi(api = Build.VERSION_CODES.KITKAT) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SDKInitializer.initialize(getApplicationContext()); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){ for(int i=0;i<permissions.length;i++){ int j=ContextCompat.checkSelfPermission(this,permissions[i]); if (j!=PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this,permissions,666); }; } Toast.makeText(this, "Success of access to permissions", Toast.LENGTH_SHORT).show(); } setDefaultFragment(); mtypeface=Typeface.createFromAsset(getAssets(),"hey.ttf"); bindView(); createSQL(); testMap(); } private void testMap(){ List<Plant> plantList = Plant.getAllPlants(); for (Plant p : plantList){ Log.d("map", "testMap: "+ p.getName()+ "" + p.getLat() + "||" + p.getLng()); } } @Override public void onClick(View view) { FragmentTransaction transaction = getFragmentManager().beginTransaction(); hideAllFragment(transaction); selected(); switch(view.getId()){ case R.id.txt_note: tabNote.setSelected(true); noteFragment = new noteclass(); transaction.replace(R.id.fragment_container,noteFragment); break; case R.id.txt_map: tabMap.setSelected(true); mapFragmet = new mapclass(); transaction.replace(R.id.fragment_container,mapFragmet); break; case R.id.txt_find: tabFind.setSelected(true); findFragmet = new findclass(); transaction.replace(R.id.fragment_container,findFragmet); break; case R.id.txt_add: tabAdd.setSelected(true); addFragmet = new addClass(); transaction.replace(R.id.fragment_container,addFragmet); break; } transaction.commit(); } //数据库 @RequiresApi(api = Build.VERSION_CODES.KITKAT) //创建数据库 private void createSQL(){ SharedHelper helper = new SharedHelper(getApplicationContext()); if (helper.readStartStatus()) { SQLiteDatabase db = Connector.getDatabase(); try { InputStream xmlFile = MainActivity.this.getAssets().open("plants.xml"); List<Plant> plantList = XmlHelper.getPalntList(xmlFile); DataSupport.saveAll(plantList); helper.saveStartStatus(false); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } @RequiresApi(api = Build.VERSION_CODES.KITKAT) private void testDatabase(){ //找出所有植物 List<Plant> plantList = Plant.getAllPlants(); Log.d("mainactivity", "testDatabase: " + plantList.size()); for (Plant p : plantList){ Log.d("mainactivity", "testDatabase: " + p.getDescriptionPath()); } //根据名称查找数据 Plant plant = Plant.getPlantByName("example plant1"); //通过文件处理工具加载对应的描述文字及图片 FileUtils fu = new FileUtils(getApplicationContext()); String des = fu.getPlantDescription(plant);//描述 Bitmap img = fu.getPlantBitmap(plant);//图片 Log.d("mainactivity", "testDatabase: " + des); } /*获得植物名称、图片、描述 *描述文件文字存在main/assets/plant_descriptions * 图片存在main/assets/plant_photos * *assets/plants.xml文件记录名称、图片、描述文字的对应关系,添加图片文字需要在plant.xml文件了添加内容 *1.获得Plant对象:Plant.getAllPalnts() 或者 Plant.getPlantByName(String name) *2. FileUtils fileUtils = new FileUtils(getApplicationContext()); *3.String description = fileUtils.getPlantDescription(plant); *4.Bitmap img = fileUtils.getPlantBitmap(plant); */ //数据库结束 //设置初始默认fragment private void setDefaultFragment(){ mapFragmet = new mapclass(); FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.add(R.id.fragment_container,mapFragmet); transaction.show(mapFragmet); transaction.commit(); } //UI组件初始化与事件绑定 private void bindView() { tabNote = this.findViewById(R.id.txt_note); tabMap = this.findViewById(R.id.txt_map); tabFind = this.findViewById(R.id.txt_find); tabAdd = this.findViewById(R.id.txt_add); tabNote.setOnClickListener(this); tabAdd.setOnClickListener(this); tabFind.setOnClickListener(this); tabMap.setOnClickListener(this); } //重置所有文本的选中状态 public void selected(){ tabNote.setSelected(false); tabAdd.setSelected(false); tabMap.setSelected(false); tabFind.setSelected(false); } //隐藏所有Fragment private void hideAllFragment(FragmentTransaction transaction){ if(noteFragment!=null){ transaction.hide(noteFragment); } if(mapFragmet!=null) { transaction.hide(mapFragmet); } if(findFragmet!=null){ transaction.hide(findFragmet); } if(addFragmet!=null){ transaction.hide(addFragmet); } } }
Python
UTF-8
3,151
2.796875
3
[]
no_license
#!/usr/bin/python # -*- coding: iso-8859-1 -*- # zululand/actor :: rev 21 :: MAY2014 :: msarch@free.fr ##---IMPORTS------------------------------------------------------------------- import os import sys from glob import glob from imp import load_source import pyglet.gl from debug import db_print ##---CLASS ACTOR--------------------------------------------------------------- class Actor(object): "Stores the position, orientation, shape, rule of an actor" def __init__(self, shape=None, ruleset=[], anchorx=0.0, anchory=0.0, angle=0.0, drawable=True, layer=0, **kwargs): self.shape = shape self.anchorx = anchorx self.anchory = anchory self.angle = angle if self.shape: self.drawable = drawable else: self.drawable= False self.layer = layer self.ruleset = ruleset Field.add_actor(self) def tick(self, dt): # TODO for rules in self.rules for rule in self.ruleset: rule(self,dt) def paint(self): if self.shape: if self.drawable: pyglet.gl.glPushMatrix() pyglet.gl.glTranslatef(self.anchorx, self.anchory, 0) pyglet.gl.glRotatef(self.angle, 0, 0, 1) batch = self.shape.get_batch() batch.draw() pyglet.gl.glPopMatrix() else: print 'actor', self, 'not drawn' else: print 'actor', self, 'has no shape' ##---ACTORS FOLDER PARSING----------------------------------------------------- class Field(): @staticmethod def init(): Field.registry=[] scene_folder=Field.get_scene_folder() Field.parse_folder(scene_folder) @staticmethod def get_scene_folder(): ''' returns the folder specified by the user ''' fn = sys.argv[1] # TODO : use getopt? db_print ('user folder is :',fn) if os.path.exists(fn): db_print (os.path.basename(fn),'exists') # file exists return(fn) else: exit() @staticmethod def parse_folder(scene_folder): ''' Loads al module inside scene_folder ''' db_print('getting modules from :',scene_folder) sys.path.insert(0,scene_folder) # include scene folder for path in glob(scene_folder+'/[!_]*.py'): db_print('trying to load :',path) name, ext = os.path.splitext(os.path.basename(path)) mdl = load_source(name, path) db_print (name, 'is loaded') db_print (mdl) @staticmethod def tick(dt): # TODO for rules in self.rules for actor in Field.registry: for rule in actor.ruleset: rule(actor,dt) @staticmethod def paint(): print Field.registry for actor in Field.registry: actor.paint() @staticmethod def add_actor(actor): Field.registry.append(actor) db_print( 'actor #',actor,'added to Field') db_print('ruleset is :', actor.ruleset,'shape is:', actor.shape)
Java
UTF-8
649
2.4375
2
[]
no_license
package org.openjfx.model.vo; import java.io.Serializable; public class KontaktInformasjon implements Serializable { private String epost; private String telefonNr; public KontaktInformasjon(String epost, String telefonNr) { this.epost = epost; this.telefonNr = telefonNr; } public String getEpost() { return epost; } public String getTelefonNr() { return telefonNr; } @Override public String toString() { return "KontaktInformasjon{" + "epost='" + epost + '\'' + ", telefonNr='" + telefonNr + '\'' + '}'; } }
PHP
UTF-8
5,793
2.53125
3
[]
no_license
<?php require_once(dirname(__FILE__) . "/../VidiunClientBase.php"); require_once(dirname(__FILE__) . "/../VidiunEnums.php"); require_once(dirname(__FILE__) . "/../VidiunTypes.php"); class VidiunAnnotationOrderBy { const CREATED_AT_ASC = "+createdAt"; const CREATED_AT_DESC = "-createdAt"; const UPDATED_AT_ASC = "+updatedAt"; const UPDATED_AT_DESC = "-updatedAt"; } abstract class VidiunAnnotationBaseFilter extends VidiunFilter { /** * * * @var string */ public $idEqual = null; /** * * * @var string */ public $entryIdEqual = null; /** * * * @var string */ public $parentIdEqual = null; /** * * * @var string */ public $parentIdIn = null; /** * * * @var int */ public $createdAtGreaterThanOrEqual = null; /** * * * @var int */ public $createdAtLessThanOrEqual = null; /** * * * @var int */ public $updatedAtGreaterThanOrEqual = null; /** * * * @var int */ public $updatedAtLessThanOrEqual = null; /** * * * @var string */ public $userIdEqual = null; /** * * * @var string */ public $userIdIn = null; } class VidiunAnnotationFilter extends VidiunAnnotationBaseFilter { } class VidiunAnnotation extends VidiunObjectBase { /** * * * @var string * @readonly */ public $id = null; /** * * * @var string */ public $entryId = null; /** * * * @var int * @readonly */ public $partnerId = null; /** * * * @var string */ public $parentId = null; /** * * * @var int * @readonly */ public $createdAt = null; /** * * * @var int * @readonly */ public $updatedAt = null; /** * * * @var string */ public $text = null; /** * * * @var string */ public $tags = null; /** * * * @var int */ public $startTime = null; /** * * * @var int */ public $endTime = null; /** * * * @var string * @readonly */ public $userId = null; /** * * * @var string */ public $partnerData = null; } class VidiunAnnotationListResponse extends VidiunObjectBase { /** * * * @var array of VidiunAnnotation * @readonly */ public $objects; /** * * * @var int * @readonly */ public $totalCount = null; } class VidiunAnnotationService extends VidiunServiceBase { function __construct(VidiunClient $client = null) { parent::__construct($client); } function listAction(VidiunAnnotationFilter $filter = null, VidiunFilterPager $pager = null) { $vparams = array(); if ($filter !== null) $this->client->addParam($vparams, "filter", $filter->toParams()); if ($pager !== null) $this->client->addParam($vparams, "pager", $pager->toParams()); $this->client->queueServiceActionCall("annotation_annotation", "list", $vparams); if ($this->client->isMultiRequest()) return null; $resultObject = $this->client->doQueue(); $this->client->throwExceptionIfError($resultObject); $this->client->validateObjectType($resultObject, "VidiunAnnotationListResponse"); return $resultObject; } function add(VidiunAnnotation $annotation) { $vparams = array(); $this->client->addParam($vparams, "annotation", $annotation->toParams()); $this->client->queueServiceActionCall("annotation_annotation", "add", $vparams); if ($this->client->isMultiRequest()) return null; $resultObject = $this->client->doQueue(); $this->client->throwExceptionIfError($resultObject); $this->client->validateObjectType($resultObject, "VidiunAnnotation"); return $resultObject; } function get($id) { $vparams = array(); $this->client->addParam($vparams, "id", $id); $this->client->queueServiceActionCall("annotation_annotation", "get", $vparams); if ($this->client->isMultiRequest()) return null; $resultObject = $this->client->doQueue(); $this->client->throwExceptionIfError($resultObject); $this->client->validateObjectType($resultObject, "VidiunAnnotation"); return $resultObject; } function delete($id) { $vparams = array(); $this->client->addParam($vparams, "id", $id); $this->client->queueServiceActionCall("annotation_annotation", "delete", $vparams); if ($this->client->isMultiRequest()) return null; $resultObject = $this->client->doQueue(); $this->client->throwExceptionIfError($resultObject); $this->client->validateObjectType($resultObject, "null"); return $resultObject; } function update($id, VidiunAnnotation $annotation) { $vparams = array(); $this->client->addParam($vparams, "id", $id); $this->client->addParam($vparams, "annotation", $annotation->toParams()); $this->client->queueServiceActionCall("annotation_annotation", "update", $vparams); if ($this->client->isMultiRequest()) return null; $resultObject = $this->client->doQueue(); $this->client->throwExceptionIfError($resultObject); $this->client->validateObjectType($resultObject, "VidiunAnnotation"); return $resultObject; } } class VidiunAnnotationClientPlugin extends VidiunClientPlugin { /** * @var VidiunAnnotationClientPlugin */ protected static $instance; /** * @var VidiunAnnotationService */ public $annotation = null; protected function __construct(VidiunClient $client) { parent::__construct($client); $this->annotation = new VidiunAnnotationService($client); } /** * @return VidiunAnnotationClientPlugin */ public static function get(VidiunClient $client) { if(!self::$instance) self::$instance = new VidiunAnnotationClientPlugin($client); return self::$instance; } /** * @return array<VidiunServiceBase> */ public function getServices() { $services = array( 'annotation' => $this->annotation, ); return $services; } /** * @return string */ public function getName() { return 'annotation'; } }
Java
UTF-8
641
2.84375
3
[]
no_license
package com.example; import java.util.Arrays; import java.util.HashMap; import java.util.List; public class MemberService { //HashMap<String,List<String>> details; //by using book object class; HashMap<String,List<Book>> details; public MemberService() { details=new HashMap<>(); details.put("anil",Arrays.asList(new Book(101,"Java programming","Cathy Caeser"),new Book(201,"python programming","Thomas Brute"))); details.put("rahul",Arrays.asList(new Book(102,"Springs in summer","Arunitha reddy"),new Book(202,"java for beginners","Robert T"))); } public List<Book> findByName(String memberName){ return details.get(memberName); } }
Markdown
UTF-8
1,218
3.953125
4
[]
no_license
**Problem:** Given an integer array `nums` of **unique** elements, return *all possible subsets (the power set)*. The solution set **must not** contain duplicate subsets. Return the solution in **any order**. **Example 1:** ``` Input: nums = [1,2,3] Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] ``` **Example 2:** ``` Input: nums = [0] Output: [[],[0]] ``` **Constraints:** - `1 <= nums.length <= 10` - `-10 <= nums[i] <= 10` - All the numbers of `nums` are **unique**. **My Solution:** ``` void bfs(vector<vector<int>> &results, vector<int> &result, vector<int> nums, int index) { for (int i = index; i < nums.size(); i++) { result.emplace_back(nums[i]); vector<int> tmp(result); results.emplace_back(tmp); bfs(results, result, nums, i + 1); result.pop_back(); } } vector<vector<int>> subsets(vector<int>& nums) { vector<vector<int>> results = {{}}; vector<int> result; bfs(results, result, nums, 0); return results; } ``` Correctness: It's a simple recursion problem. We just have to check each element but pay attention to duplicate. Complexity: Time: O($2^n$) Space: O(n)
Markdown
UTF-8
11,458
2.75
3
[ "MIT" ]
permissive
<!-- Titel på rapporten --> Färgval och typografi på kommunala webbplatser ======================= Introduktion ----------------------- <!-- Skriv en eller två rader om vad uppgiften handlar om. --> Anpassning av webbplats genom färgval och typografi är en viktig punkt för att locka besökare. Om färgvalen appliceras helt vilt utan tanke, brukar det resultera i en ansträngande sida att läsa/tolk för användaren. Ansträngning kan också minskas genom att följa beprövade riktlinjer inom typografi (Pamental 2014). I denna rapport kommer det ske en granskning av färgscheman och typografi. Undersökning utförs på tre kommuners webbsidor: Tyresö, Enköping och Karlstad. Urval ----------------------- <!-- Berätta vilka webbplatser du valt att undersöka och varför eller hur du gick tillväga när du gjorde ditt urval. --> De tre webbplatser som blivit utvalda har blivit framtagna från IDG.se (2019) &#45; "fem bästa kommunerna på nätet 2019". Kommunerna som granskas är Tyresö, Enköping och Karlstad. Anledningen till valet av granskningområde gjordes då webbplatser hos kommuner brukar ha en tendens att inte följa med i webbutvecklingen. Relateras till de två kommuner som forskaren bott i under sitt liv, samt med stöd från IDG.se (2019). Begränsning har gjorts till att granska en nyhetsartikel hos respektive webbplats. Då fokus ligger på att granska färgschema och typografi känns det som ett naturligt val. Metod ----------------------- <!-- Berätta kort om din "metod", hur du gör för att utföra undersökningen. Berätta om du använder något speciellt verktyg. --> Undersökningen använder sig av diverse verktyg för att kunna bedöma webbsidorna. * För att granska om färgerna följer ett färgschema, används en kombination av verktygen: - [ColorZilla](https://www.colorzilla.com/firefox/) &#45; Addon i webbläsaren som tar fram färg hos ett element. - [Adobe Color CC](https://color.adobe.com/sv/create) &#45; Ett "red-greenish" komplement färghjul som kan generera färgpaletter. * För att granska typsnitt används: - Dev-tool i webbläsaren &#45; för att verifiera diverse styling. * För att beräkna tecken radlängden - i olika resolutioner: - [Counter](https://www.lettercount.com/) &#45; Räknare av antal tecken. Resultat ----------------------- <!-- Dokumentera dina resultat från din studie. Berätta vad du kom fram till, vilka resultat du hittade och observerade. --> ### Tyresö kommun ### Webbsidan som användes från Tyresö kommun (2019) illustrerars i bilden. ![Tyresö](img/tyreso.jpg "Tyresö kommun") <table style="border-spacing: 4px; border-collapse: separate"> <tr> <td style="height: 50px; width: 50px; background-color: #BEE8F5"> <td style="height: 50px; width: 50px; background-color: #6ECDE9"> <td style="height: 50px; width: 50px; background-color: #204560"> <!-- <td style="height: 50px; width: 50px; background-color: #FBC900"> <td style="height: 50px; width: 50px; background-color: #E11F14"> --> </tr> </table> Frånsett färg på sin kommun-sköld använder sig Tyresö av tre blå nyanser, samt vit bakgrund och svart text. Där bakgrundsfärgen är blå - är texten vit. Tyresö använder ett egenskapat färgschema som är i närliggande färgharmoni av analog. Accent-färgen som används är #6ECDE9, den återfinns som underlinje för länkar eller för att färglägga logotyper hos social media. Typsnittet på brödtexten är i en sans-serif stil med en lätt fontvikt. H1, H2 har samma typsnitt som brödtexten men med tyngre fontvikt. Tecken radlängd ligger någonstans mellan 35 &#45; 85 tecken, där det lägre uppfylls på mobil (iPhone 6) resolution och det högre nås på tablet (iPad) eller dator med högre resolution. ### Enköpings kommun ### Webbsidan som användes från Enköpings kommun (2019) illustrerars i bilden. ![Enköping](img/enkoping.jpg "Enköpings kommun") <table style="border-spacing: 4px; border-collapse: separate"> <tr> <td style="height: 50px; width: 50px; background-color: #F2C800"> <td style="height: 50px; width: 50px; background-color: #5D9ACF"> <td style="height: 50px; width: 50px; background-color: #003366"> <!-- <td style="height: 50px; width: 50px; background-color: #EBBC00"> <td style="height: 50px; width: 50px; background-color: #003F78"> --> </tr> </table> Frånsett färg på sin kommun-sköld använder sig Enköping av två blå nyanser och en gul färg, samt vit bakgrund och svart text. Där bakgrundsfärgen är blå - är texten vit och där bakgrundsfärgen är gul - är texten svart. Enköping använder ett sammansatt färgschema, då färgerna inte ligger i linje med varandra för att uppfylla ett komplementärt färgschema. Accent-färgen som används är #5D9ACF, den återfinns vid hoverande över länkarna i slut på artikeln. Typsnittet på brödtexten är i en sans-serif stil med en normal fontvikt. H1, H2 använder sans-serif men en annan variant än brödtexten, samt med en fontvikt på 500. Tecken radlängd ligger någonstans mellan 45 &#45; 102 tecken, där det lägre uppfylls på mobil (iPhone 6) resolution och det högre nås på en resolutions-bredd av 716px, när resolutions-bredd når 717px+ är radlängden max 53 tecken. ### Karlstads kommun ### Webbsidan som användes från Karlstads kommun (2019) illustrerars i bilden. ![Karlstad](img/karlstad.jpg "Karlstads kommun") <table style="border-spacing: 4px; border-collapse: separate"> <tr> <td style="height: 50px; width: 50px; background-color: #FED13E"> <td style="height: 50px; width: 50px; background-color: #FEC933"> <td style="height: 50px; width: 50px; background-color: #FEC126"> <td style="height: 50px; width: 50px; background-color: #F6A800"> <td style="height: 50px; width: 50px; background-color: #F29301"> <td style="height: 50px; width: 50px; background-color: #F36E07"> <td style="height: 50px; width: 50px; background-color: #E75114"> <td style="height: 50px; width: 50px; background-color: #C50E20"> <!-- <td style="height: 50px; width: 50px; background-color: #FFE400"> <td style="height: 50px; width: 50px; background-color: #ED6C07"> --> </tr> </table> Karlstad använder sig av olika nyanser av orange samt närliggande färger i form av gul och röd. Bakgrund är vit med svart text. Där bakgrundsfärgen är orange-röd gradientfärgad har texten vit färg och länkarna i footer-delen är orange. Karlstad använder sig av ett analogt färgschema, då färgerna ligger i närhet av varandra på färghjulet. Accent-färgen som används är en gradientfärg mellan #FED13E och #FEC126, den återfinns vid knappen "Kontakt". Typsnittet på brödtexten är i en sans-serif stil med en normal fontvikt. H1, H2, H3 använder sans-serif men en annan variant än brödtexten, med en normal fontvikt. Tecken radlängd ligger någonstans mellan 52 &#45; 86 tecken, där det lägre uppfylls på mobil (iPhone 6) resolution och det högre nås på en resolutions-bredd av 600px, när resolutions-bredd når omkring 980px+ är radlängden max 76 tecken. Analys ----------------------- <!-- Diskutera och analysera de resultaten du fann. --> Samtliga webbplatser verkar ha valt sina färgschema för att skapa harmoni. Då alla använts sig av antingen närliggande färger, eller komplement färger. Färgtonerna hos basfärgen har varit stark och accentfärg har för det mesta varit ljusare (visst undantag hos Karlstad). Blått färgval förekommer hos två av tre kommuner. Både Enköping och Karlstad använder sig av färger som relaterar mot deras kommunsköld. Tyresö är ensamma om att inte använda sin "kommuns-färg", de kör på olika blåa nyaser istället. Antingen är det på grund av kombinationen gult och rött, skulle tvinga på en orange färg som ligger mellan gul och rött (likt Karlstad) och de inte känner att det förmedlar rätt budskap. En annan möjlighet är att de valde blått för att kommunskölden ska få funktionen av en accentfärg och webbsidan samtidigt ska framställa ett lugn, vilket är en tolkning av blått enligt Beaird, J. och George, J. (2014). Typografin utifrån responsivitet ligger inom en tecken radlängd på 35-102 tecken. Det var Enköping som hade den lite opassande längden på 102 tecken vid en specifik resolution, annars var max hos de andra två kommunerna max 85 tecken. Så att det finns någon tanke med typografi när det kommer till radlängd kan konstateras. Typsnitt är gemensamt för samtliga kommuner, det är sans-serif som gäller. Med kanske en "touch" tyngre font-vikt hos h1-h3 rubriker jämfört med brödtexten. Kontrast mellan bakgrundfärg och textfärg är skapad med känsla. Det är svart eller vit textfärg som gäller, beroende på om bakgrundsfärg har en ljusare eller mörkare karaktär. I sin helhet kan det konstateras att webbsidorna varit rätt neutrala i färgvalen. Det är en standard vit bakgrundfärg och färginslag finns hos header, footer och länkar eller knappar. Då undersökningen inkluderat enbart tre webbplatser ger det inte en rättvis bild på hur ett genomsnitt av liknande webbplatser utför sina färgval eller typografi. Utan detta resultat grundar sig i de webbplatser som ligger i framkant av Sveriges kommuner enligt den topplista som blivit framtagen av IDG.se (2019). Reservation för att bedömning som utförts inte speglar ett samtycke hos alla läsare. De slutsater som tagits har blivit baserat på färgteorier och typografiska riktlinjer som i stor utsträckning anses vara passande. Enligt de referenser/verktyg som använts och den kunskap som forskaren besitter. Referenser ----------------------- <!-- Ange de eventuella referenser du använder dig av, om några. --> Beaird, J. & George, J. (2014). *The Principles of Beautiful Web Design* (3rd ed.). &nbsp;&nbsp;&nbsp;&nbsp;Accessad 2019-12-07 från &nbsp;&nbsp;&nbsp;&nbsp;<https://learning.oreilly.com/library/view/the-principles-of/9781457174353/Text/ch02.html> Enköpings kommun. (2019). *Fjärdhundraland vinner Stora Turismpriset*. &nbsp;&nbsp;&nbsp;&nbsp;[Elektronisk resurs] accessad 2019-12-07 från &nbsp;&nbsp;&nbsp;&nbsp;<https://enkoping.se/fritid-och-kultur/nyheter/lista/2019-12-05-fjardhundraland-vinner-stora-turismpriset.html> IDG.se. (2019). *Topp100 2019: Här är de 5 bästa kommunerna på nätet*. &nbsp;&nbsp;&nbsp;&nbsp;[Elektronisk resurs] accessad 2019-12-07 från &nbsp;&nbsp;&nbsp;&nbsp;<https://topp100.idg.se/2.39772/1.715015/topp100-2019-kommuner> Karlstads kommun. (2019). *Nu ska Fredricelundsskolan rivas*. &nbsp;&nbsp;&nbsp;&nbsp;[Elektronisk resurs] accessad 2019-12-07 från &nbsp;&nbsp;&nbsp;&nbsp;<https://karlstad.se/Nyheter/2019/november/nu-ska-fredricelundsskolan-rivas/> Pamental, J. (2014). *A more Modern Scale for Web Typography*. &nbsp;&nbsp;&nbsp;&nbsp;[Elektronisk resurs] accessad 2019-12-07 från &nbsp;&nbsp;&nbsp;&nbsp;<https://typecast.com/blog/a-more-modern-scale-for-web-typography> Tyresö kommun. (2019). *Tyresöbornas konst fyller julsalongen*. &nbsp;&nbsp;&nbsp;&nbsp;[Elektronisk resurs] accessad 2019-12-07 från &nbsp;&nbsp;&nbsp;&nbsp;<https://www.tyreso.se/arkiv/nyheter/nyheter-uppleva--gora/uppleva--gora/2019-12-04-tyresobornas-konst-fyller-julsalongen.html> Övrigt ----------------------- <!-- Skriv ditt eget namn samt vilka gruppmedlemmar som deltog i att författa rapporten. --> Anton Rönnberg
Python
UTF-8
4,726
3.09375
3
[]
no_license
import numpy as np import sys sys.setrecursionlimit(1500) def read_input(filename, scoring_file): try: input_file = open(filename, "r") genome1 = input_file.readline().rstrip('\n') genome2 = input_file.readline().rstrip('\n') genome3 = input_file.readline().rstrip('\n') input_file.close() except: print("Exception caught, file probably doesnt exist") return genome1, genome2, genome3 # Edge weights are defined by the scoring matrix and penalties def MultipleLCS(g1, g2, g3): n1 = len(g1) n2 = len(g2) n3 = len(g3) longest_path = np.zeros((n1+1, n2+1, n3+1), dtype=int) backtrack = np.zeros((n1+1, n2+1, n3+1), dtype='object') # Traffic control for i in range(1, n1+1): backtrack[i][0][0] = 'D' for j in range(1, n2+1): backtrack[0][j][0] = 'R' for k in range(1, n3+1): backtrack[0][0][k] = 'I' for i in range(1, n1+1): for j in range(1, n2+1): backtrack[i][j][0] = 'DR' for i in range(1, n1+1): for k in range(1, n3+1): backtrack[i][0][k] = 'DI' for j in range(1, n2+1): for k in range(1, n3+1): backtrack[0][j][k] = 'RI' for i in range(1, n1+1): for j in range(1, n2+1): for k in range(1, n3+1): match = 0 if g1[i-1] == g2[j-1] and g1[i-1] == g3[k-1]: match = 1 longest_path[i][j][k] = max(longest_path[i-1][j][k], longest_path[i][j-1][k], \ longest_path[i][j][k-1], \ longest_path[i-1][j-1][k], \ longest_path[i-1][j][k-1], \ longest_path[i][j-1][k-1], \ longest_path[i-1][j-1][k-1] + match \ ) if longest_path[i][j][k] == longest_path[i-1][j][k]: backtrack[i][j][k] = 'D' elif longest_path[i][j][k] == longest_path[i][j-1][k]: backtrack[i][j][k] = 'R' elif longest_path[i][j][k] == longest_path[i][j][k-1]: backtrack[i][j][k] = 'I' elif longest_path[i][j][k] == longest_path[i-1][j-1][k]: backtrack[i][j][k] = 'DR' elif longest_path[i][j][k] == longest_path[i-1][j][k-1]: backtrack[i][j][k] = 'DI' elif longest_path[i][j][k] == longest_path[i][j-1][k-1]: backtrack[i][j][k] = 'RI' elif longest_path[i][j][k] == (longest_path[i-1][j-1][k-1] + match): backtrack[i][j][k] = 'M' return backtrack, n1, n2, n3, longest_path[n1][n2][n3] def OutputMultipleLCS(backtrack, g1, g2, g3, i, j, k): # Base case if backtrack[i][j][k] == 0: return '', '', '' # Recursive part if backtrack[i][j][k] == 'D': s1, s2, s3 = OutputMultipleLCS(backtrack, g1, g2, g3, i-1, j, k) s1 += g1[i-1] s2 += '-' s3 += '-' return s1, s2, s3 elif backtrack[i][j][k] == 'R': s1, s2, s3 = OutputMultipleLCS(backtrack, g1, g2, g3, i, j-1, k) s1 += '-' s2 += g2[j-1] s3 += '-' return s1, s2, s3 elif backtrack[i][j][k] == 'I': s1, s2, s3 = OutputMultipleLCS(backtrack, g1, g2, g3, i, j, k-1) s1 += '-' s2 += '-' s3 += g3[k-1] return s1, s2, s3 elif backtrack[i][j][k] == 'DR': s1, s2, s3 = OutputMultipleLCS(backtrack, g1, g2, g3, i-1, j-1, k) s1 += g1[i-1] s2 += g2[j-1] s3 += '-' return s1, s2, s3 elif backtrack[i][j][k] == 'DI': s1, s2, s3 = OutputMultipleLCS(backtrack, g1, g2, g3, i-1, j, k-1) s1 += g1[i-1] s2 += '-' s3 += g3[k-1] return s1, s2, s3 elif backtrack[i][j][k] == 'RI': s1, s2, s3 = OutputMultipleLCS(backtrack, g1, g2, g3, i, j-1, k-1) s1 += '-' s2 += g2[j-1] s3 += g3[k-1] return s1, s2, s3 else: # match s1, s2, s3 = OutputMultipleLCS(backtrack, g1, g2, g3, i-1, j-1, k-1) s1 += g1[i-1] s2 += g2[j-1] s3 += g3[k-1] return s1, s2, s3 def start(): genome1, genome2, genome3 = read_input("dataset.txt", "BLOSUM62.txt") backtrack, n1, n2, n3, score = MultipleLCS(genome1, genome2, genome3) s1, s2, s3 = OutputMultipleLCS(backtrack, genome1, genome2, genome3, n1, n2, n3) print(score) print(s1) print(s2) print(s3) if __name__ == '__main__': start()
C++
UTF-8
3,775
2.546875
3
[]
no_license
#include "hades/game_api.hpp" #include <type_traits> #include "hades/data.hpp" #include "hades/level_interface.hpp" namespace hades { namespace detail { template<typename T, typename GameSystem> T& get_level_local_ref_imp(unique_id id, extra_state<GameSystem>& extras) { auto val = extras.level_locals.try_get<T>(id); if (val) return *val; static_assert(std::is_default_constructible_v<T>); return extras.level_locals.set<T>(id, {}); } template<typename T, typename GameSystem> void set_level_local_value_imp(unique_id id, T value, extra_state<GameSystem>& extras) { extras.level_locals.set(id, std::move(value)); return; } } namespace game { namespace detail = hades::detail; template<typename T> T& get_system_data() { auto ptr = detail::get_game_data_ptr(); assert(ptr->system_data->has_value()); auto ret = std::any_cast<T>(ptr->system_data); assert(ret); return *ret; } template<typename T> void set_system_data(T value) { auto ptr = detail::get_game_data_ptr(); ptr->system_data->emplace<std::decay_t<T>>(std::move(value)); } } namespace game::mission { } namespace game::level { template<typename T> T& get_level_local_ref(unique_id id) { auto ptr = detail::get_game_level_ptr(); return detail::get_level_local_ref_imp<T>(id, ptr->get_extras()); } template<typename T> void set_level_local_value(unique_id id, T value) { auto ptr = detail::get_game_level_ptr(); detail::set_level_local_value_imp<T>(id, std::move(value), ptr->get_extras()); return; } } namespace game::level::object { template<template<typename> typename CurveType, typename T> CurveType<T>& get_property_ref(object_ref& o, variable_id v) { static_assert(curve_types::is_curve_type_v<T>); const auto g_ptr = detail::get_game_level_ptr(); auto& obj = state_api::get_object(o, g_ptr->get_extras()); return state_api::get_object_property_ref<CurveType, T>(obj, v); } } namespace render { namespace detail = hades::detail; template<typename T> T &get_system_data() noexcept { auto ptr = detail::get_render_data_ptr(); assert(ptr->system_data->has_value()); auto ret = std::any_cast<T>(ptr->system_data); assert(ret); return *ret; } template<typename T> void set_system_data(T value) { auto ptr = detail::get_render_data_ptr(); ptr->system_data->emplace<std::decay_t<T>>(std::move(value)); } } namespace render::drawable { template<typename DrawableObject> id_t create(DrawableObject&& d, layer_t l) { auto ptr = detail::get_render_data_ptr(); assert(ptr); assert(ptr->render_output); return ptr->render_output->create_drawable_copy(std::forward<DrawableObject>(d), l); } template<typename DrawableObject> void update(id_t id, DrawableObject&& d, layer_t l) { auto ptr = detail::get_render_data_ptr(); assert(ptr); assert(ptr->render_output); ptr->render_output->update_drawable_copy(id, std::forward<DrawableObject>(d), l); } } namespace render::level { template<typename T> T& get_level_local_ref(unique_id id) { return detail::get_level_local_ref_imp<T>(id, *detail::get_render_extra_ptr()); } template<typename T> void set_level_local_value(unique_id id, T value) { return detail::set_level_local_value_imp(id, std::move(value), *detail::get_render_extra_ptr()); } namespace object { template<template<typename> typename CurveType, typename T> const CurveType<T>& get_property_ref(object_ref& o, variable_id v) { static_assert(curve_types::is_curve_type_v<T>); auto& obj = state_api::get_object(o, *detail::get_render_extra_ptr()); return state_api::get_object_property_ref<CurveType, T>(obj, v); } } } }
TypeScript
UTF-8
730
2.859375
3
[ "MIT" ]
permissive
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne } from 'typeorm'; import TrackedAccount from '../tracked-account/trackedAccount.entity'; /** * Database representation of a ban */ @Entity() export default class Ban { /** * Primary key */ @PrimaryGeneratedColumn() id: number; /** * When was the ban detected */ @Column() detectedAt: Date; /** * Type of ban * VAC, game, economy, faceit, ... */ @Column() type: string; // TODO Placeholder, needs an interface for types of bans /** * Link bans to trackedAccount */ @ManyToOne(type => TrackedAccount, trackedAccount => trackedAccount.bans) trackedAccount: TrackedAccount; }
Python
UTF-8
940
2.59375
3
[ "MIT" ]
permissive
# # Copyright (C) 2019-2020 UAVCAN Development Team <info@zubax.com>. # Author: Pavel Kirienko <pavel.kirienko@zubax.com> # import os import glob import typing from .. import app _ADOPTERS_DIRECTORY_PATH = os.path.join(app.root_path, '..', 'adopters') class Adopter: def __init__(self, name: str, logo_file_name: str, website: str): self.name = str(name) self.logo_file_name = str(logo_file_name) website = str(website) if '://' in website: self.website_url = website else: self.website_url = 'http://' + website def get_list() -> typing.Iterable[Adopter]: entries = list(sorted(map(os.path.basename, glob.glob(_ADOPTERS_DIRECTORY_PATH + '/*.png')))) for e in entries: name, website = e.rsplit('.', 1)[0].rsplit(' ', 1) yield Adopter(name, e, website) def get_logo_file_path(logo_file_name: str) -> str: return os.path.join(_ADOPTERS_DIRECTORY_PATH, logo_file_name)
Java
UTF-8
2,515
2.390625
2
[]
no_license
package com.esprit.mycitymystory.Adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.esprit.mycitymystory.R; import com.esprit.mycitymystory.model.NewsModel; import com.squareup.picasso.Picasso; import java.util.ArrayList; public class NewsListAdapter extends BaseAdapter { private ArrayList<NewsModel> newsModels; private LayoutInflater mInflater; private Context context; public NewsListAdapter(ArrayList<NewsModel> newsModels, Context context) { this.newsModels = newsModels; this.context = context; this.mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return newsModels.size(); } @Override public Object getItem(int position) { return newsModels.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { final View view; ViewHolder viewHolder; NewsModel newsModel = (NewsModel) getItem(position); if (convertView==null) { view = mInflater.inflate(R.layout.news_item, parent, false); setViewHolder(view); }else { view = convertView; } viewHolder = (ViewHolder)view.getTag(); Picasso.with(context).load(newsModel.getLogoIcon()).into(viewHolder.logoIcon); viewHolder.newsTitle.setText(newsModel.getTitle()); viewHolder.newsText.setText(newsModel.getText()); if (newsModel.getImage() != null) { Picasso.with(context).load(newsModel.getImage()).into(viewHolder.newsImage); } return view; } public static class ViewHolder { ImageView logoIcon, newsImage; TextView newsTitle, newsText; } public static void setViewHolder(View view) { ViewHolder viewHolder = new ViewHolder(); viewHolder.logoIcon = (ImageView) view.findViewById(R.id.logo_icon); viewHolder.newsImage = (ImageView) view.findViewById(R.id.news_image); viewHolder.newsTitle = (TextView) view.findViewById(R.id.news_title); viewHolder.newsText = (TextView) view.findViewById(R.id.news_text); view.setTag(viewHolder); } }
Python
UTF-8
127
3.09375
3
[]
no_license
mylist=[10,2,3,4,4,4,3,3,3,56,7] mylist2=[] for i in mylist: if i not in mylist2: mylist2.append(i) print(mylist2)
TypeScript
UTF-8
1,807
2.65625
3
[ "MIT" ]
permissive
import { code as script } from 'code ./browser/dynamicImportWrapper.ts' import { relative } from 'path' import slash from 'slash' export function setupLoaderScript({ eventDelay = false, wakeEvents = [] as string[], }: { eventDelay?: number | false wakeEvents?: string[] noWakeEvents?: boolean }) { // FEATURE: add static code analysis for wake events // - Use code comments? // - This will be slower... // WAKE_EVENT: chrome.runtime.onMessage const replaceDelay = (match: string, tag: string) => { if (typeof eventDelay === 'number') { return match.replace(tag, eventDelay.toString()) } else if (eventDelay === false) { return '' } else { throw new TypeError( 'dynamicImportEventDelay must be false or a number', ) } } const replaceSwitchCase = (index: number) => { const events = wakeEvents.map((e) => e.split('.')[index]) return (match: string, tag: string) => { return events.length ? events.map((e) => match.replace(tag, e)).join('') : '' } } return (scriptPath: string) => { return ( script // Delay events by ms .replace( /[\n\s]+.then\(delay\(('%DELAY%')\)\)([\n\s]+)/, replaceDelay, ) // Chrome namespace (ie, runtime, tabs, etc...) .replace( /[\n\s]+case '(%NAME%)':[\n\s]+return true/, replaceSwitchCase(1), ) // Chrome event (ie, onMessage, onUpdated, etc...) .replace( /[\n\s]+case '(%EVENT%)':[\n\s]+return true/, replaceSwitchCase(2), ) // Path to module being loaded .replace( '%PATH%', // Fix path slashes to support Windows slash(relative('assets', scriptPath)), ) ) } }
Python
UTF-8
286
4.21875
4
[]
no_license
#x = 0 #while x <= 5: #print(x) #x = x + 1 # Import the datetime class from the datetime module. import datetime # Use the now() attribute on the datetime class to get the present time. now = datetime.datetime.now() # Print the present time. print("The time right now is ", now)
C++
UTF-8
3,139
2.53125
3
[ "Apache-2.0" ]
permissive
#include <chrono> #include <iostream> #include <memory> #include <string.h> #include "WiringPiLcdDisplay.h" #include "../src2/HealthStatus.h" using namespace std; using namespace std::chrono; static inline void truncateName(string& name) { size_t length = name.length(); if(length > 8) { name.resize(8); name.replace(7, 1, 1, '.'); } } int main() { unique_ptr<WiringPiLcdDisplay> lcd(WiringPiLcdDisplay::getLcdDisplayInstance()); lcd->init(); StatusInformation status; beacon_info beacon; memset(&beacon, 0, sizeof(beacon)); status.setScannerID("LCDScanner"); // Add some events sprintf(beacon.uuid, "UUID-%.10d", 66); beacon.minor = 66; beacon.major = 1; beacon.manufacturer = 0xdead; beacon.code = 0xbeef; beacon.count = 3; beacon.rssi = -68; milliseconds now = duration_cast<milliseconds >(system_clock::now().time_since_epoch()); beacon.time = now.count(); status.addEvent(beacon, false); beacon.isHeartbeat = true; beacon.minor = 206; beacon.time += 10; status.addEvent(beacon, true); beacon.isHeartbeat = false; beacon.minor = 56; beacon.time += 10; status.addEvent(beacon, false); beacon.isHeartbeat = true; beacon.minor = 206; beacon.time += 10; status.addEvent(beacon, true); HealthStatus healthStatus; healthStatus.calculateStatus(status); shared_ptr<Properties> statusProps = status.getLastStatus(); printf("StatusProps dump:\n"); for(Properties::const_iterator iter = statusProps->begin(); iter != statusProps->end(); iter ++) { printf("%s = %s\n", iter->first.c_str(), iter->second.c_str()); } printf("+++ End dump\n\n"); char tmp[21]; snprintf(tmp, sizeof(tmp), "01234567890123456789"); lcd->displayText(tmp, 0, 0); cout << "\nEnter any key to test local layout: "; std::string line; std::getline(std::cin, line); lcd->clear(); string name(status.getScannerID()); truncateName(name); snprintf(tmp, sizeof(tmp), "%s:%.7d;%d", name.c_str(), status.getHeartbeatCount(), status.getHeartbeatRSSI()); lcd->displayText(tmp, 0, 0); string uptime = (*statusProps)["Uptime"]; const char *uptimeStr = uptime.c_str(); printf("%s; length=%ld\n", uptimeStr, uptime.size()); int days=0, hrs=0, mins=0; int count = sscanf (uptimeStr, "uptime: %*d, days:%d, hrs:%d, min:%d", &days, &hrs, &mins); printf("matched:%d, UP D:%d H:%d M:%d\n", count, days, hrs, mins); snprintf(tmp, sizeof(tmp), "UP D:%d H:%d M:%d", days, hrs, mins); lcd->displayText(tmp, 0, 1); const char *load = (*statusProps)["LoadAverage"].c_str(); printf("Load: %s\n", load); lcd->displayText(load, 0, 2); snprintf(tmp, sizeof(tmp), "Events: %d; Msgs: %d", status.getRawEventCount(), status.getPublishEventCount()); lcd->displayText(tmp, 0, 3); cout << "\nEnter any key to call displayStatus: "; std::getline(std::cin, line); lcd->clear(); lcd->displayStatus(status); cout << "\nEnter any key to call exit: "; std::getline(std::cin, line); lcd->clear(); }
Java
UTF-8
64,947
1.59375
2
[]
no_license
package com.jshx.ajxx.web; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import net.sf.json.JsonConfig; import net.sf.json.util.PropertyFilter; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import com.jshx.ajxx.entity.CaseCl; import com.jshx.ajxx.entity.CaseInfo; import com.jshx.ajxx.entity.CaseZj; import com.jshx.ajxx.service.CaseInfoService; import com.jshx.ajxx.util.FileDocUtil; import com.jshx.core.base.action.BaseAction; import com.jshx.core.base.vo.Pagination; import com.jshx.core.json.CodeJsonValueProcessor; import com.jshx.core.json.DateJsonValueProcessor; import com.jshx.core.utils.Struts2Util; import com.jshx.core.utils.SysPropertiesUtil; import com.jshx.module.admin.entity.User; import com.jshx.module.admin.entity.UserRight; import com.jshx.module.admin.service.CodeService; import com.jshx.module.admin.service.UserService; import com.jshx.photoPic.entity.PhotoPic; import com.jshx.photoPic.service.PhotoPicService; import com.jshx.qyjbxx.entity.EntBaseInfo; import com.jshx.qyjbxx.service.EntBaseInfoService; import com.jshx.shjl.entity.CheckRecord; import com.jshx.shjl.service.CheckRecordService; import com.jshx.wsgl.entity.InstrumentsInfo; import com.jshx.wsgl.service.InstrumentsInfoService; public class CaseInfoAction extends BaseAction { /** * 主键ID列表,用于接收页面提交的多条主键ID信息 */ private String ids; /** * 实体类 */ private CaseInfo caseInfo = new CaseInfo(); private InstrumentsInfo instrumentsInfo = new InstrumentsInfo(); /** * 业务类 */ @Autowired private CaseInfoService caseInfoService; @Autowired private CodeService codeService; @Autowired private UserService userService; @Autowired private CheckRecordService checkRecordService; @Autowired private EntBaseInfoService entBaseInfoService; @Autowired private InstrumentsInfoService instrumentsInfoService; @Autowired private PhotoPicService photoPicService; /** * 修改新增标记,add为新增、mod为修改 */ private String flag; /** * 分页信息 */ private Pagination pagination; private Date queryCaseTimeStart; private Date queryCaseTimeEnd; private List<CheckRecord> checkRecords = new ArrayList<CheckRecord>(); private List<InstrumentsInfo> wsList = new ArrayList<InstrumentsInfo>(); private String type; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); private List<User> userList = new ArrayList<User>(); private List<PhotoPic> picList = new ArrayList<PhotoPic>(); @Autowired() @Qualifier("sessionFactory") private SessionFactory sessionFactory; private String loginUserId; public String getLoginUserId() { return loginUserId; } public void setLoginUserId(String loginUserId) { this.loginUserId = loginUserId; } private CaseCl caseCl = new CaseCl(); private CaseZj caseZj = new CaseZj(); private List<CaseCl> clList = new ArrayList<CaseCl>(); private List<CaseZj> zjList = new ArrayList<CaseZj>(); private int pageNo; private int pageSize; private String searchLike; /** * 查询登录人角色 * @author luting * 2015-10-21 * @return */ public String init() { loginUserId = this.getLoginUser().getId(); List<UserRight> list = (List<UserRight>) this.getLoginUser().getUserRoles(); flag = ""; for(UserRight ur:list) { flag += ur.getRole().getRoleCode()+ ","; } return SUCCESS; } /** * 执行查询的方法,返回json数据 */ public void list() throws Exception{ Map<String, Object> paraMap = new HashMap<String, Object>(); if(pagination==null) pagination = new Pagination(this.getRequest()); if(null != caseInfo){ //设置查询条件,开发人员可以在此增加过滤条件 if ((null != caseInfo.getAreaId()) && (0 < caseInfo.getAreaId().trim().length())){ paraMap.put("areaId", caseInfo.getAreaId().trim() ); } if ((null != caseInfo.getCompanyName()) && (0 < caseInfo.getCompanyName().trim().length())){ paraMap.put("companyName", "%" + caseInfo.getCompanyName().trim() + "%"); } if ((null != caseInfo.getCaseName()) && (0 < caseInfo.getCaseName().trim().length())){ paraMap.put("caseName", "%" + caseInfo.getCaseName().trim() + "%"); } if ((null != caseInfo.getCaseSource()) && (0 < caseInfo.getCaseSource().trim().length())){ paraMap.put("caseSource", caseInfo.getCaseSource().trim()); } if ((null != caseInfo.getCaseStatus()) && (0 < caseInfo.getCaseStatus().trim().length())){ List<String> ll = new ArrayList<String>(); if("0".equals(caseInfo.getCaseStatus())) { flag = ""; List<UserRight> list = (List<UserRight>) this.getLoginUser().getUserRoles(); for(UserRight ur:list) { flag += ur.getRole().getRoleCode()+ ","; } String level = ""; //登录人为安监局领导 if(flag.contains("A02")) { level += "1"; } else { level += "0"; } //登录人为监察大队队长 if(flag.contains("A09")) { level += "1"; } else { level += "0"; } //登录人为大队队员 if(flag.contains("A10")) { level += "1"; } else { level += "0"; } //登录人为法务 if(flag.contains("A30")) { level += "1"; } else { level += "0"; } paraMap.put("level", level); paraMap.put("undertakerId", this.getLoginUser().getId()); } else { paraMap.put("caseStatus", caseInfo.getCaseStatus().trim()); } } if (null != queryCaseTimeStart){ paraMap.put("startCaseTime", queryCaseTimeStart); } if (null != queryCaseTimeEnd){ paraMap.put("endCaseTime", queryCaseTimeEnd); } } if(type != null && "1".equals(type)) { paraMap.put("userId", this.getLoginUser().getId()); } if(this.getLoginUser().getDeptCode().equals("009")) { Map map = new HashMap(); map.put("loginId", this.getLoginUser().getLoginId()); EntBaseInfo entBaseInfo = entBaseInfoService.findEntBaseInfoByMap(map); paraMap.put("companyId", entBaseInfo.getId()); } JsonConfig config = new JsonConfig(); config.registerJsonValueProcessor(java.util.Date.class,new DateJsonValueProcessor()); Map<String, String> codeMap = new HashMap<String, String>(); //此处添加需要转换的一维代码,key是一维代码在数据对象中的属性名,value是一维代码的codeId codeMap.put("caseSource", "402880fe506f9d9801506fa93b2e0008"); config.registerJsonValueProcessor(String.class,new CodeJsonValueProcessor(codeMap)); final String filter = "id|areaName|companyName|caseTime|caseName|caseSource|caseStatus|createUserID|undertakerId|ifNr|wszt|undertakerName|"; if (filter != null && filter.length() > 1) { config.setJsonPropertyFilter(new PropertyFilter() { public boolean apply(Object source, String name, Object value) { if (filter.indexOf(name + "|") != -1) return false; else return true; } }); } pagination = caseInfoService.findByPage(pagination, paraMap); convObjectToJson(pagination, config); } /** * 查看详细信息 */ public String view() throws Exception{ try { if((null != caseInfo)&&(null != caseInfo.getId())) { caseInfo = caseInfoService.getById(caseInfo.getId()); Map<String, Object> paraMap = new HashMap<String, Object>(); paraMap.put("infoId", caseInfo.getId()); checkRecords=checkRecordService.findCheckRecord(paraMap); paraMap.put("caseId", caseInfo.getId()); paraMap.put("notin", "35"); paraMap.put("ifPrint", "1"); wsList = instrumentsInfoService.findInstrumentsInfos(paraMap); clList = caseInfoService.getCaseClList(paraMap); for(CaseCl cl:clList) { Map map = new HashMap(); map.put("linkId",cl.getLinkId()); map.put("mkType", "ajxx"); map.put("picType","ajclfj"); cl.setPicList(photoPicService.findPicPath(map));//获取执法文书材料 } zjList = caseInfoService.getCaseZjList(paraMap); } else { caseInfo.setUndertakerName1(this.getLoginUser().getDisplayName()); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return VIEW; } /** * 初始化修改信息 */ public String initEdit() throws Exception{ view(); Map map = new HashMap(); map.put("userId", this.getLoginUser().getId()); userList = caseInfoService.queryCaseUserList(map); return EDIT; } /** * 保存信息(包括新增和修改) */ public String save() throws Exception{ FileInputStream in = null; try { //设置Blob字段 setBlobField(in); } finally { if (null != in) { try { in.close(); } catch (Exception ex) { } } } Map m = new HashMap(); m.put("codeName", "企业属地"); m.put("itemValue", caseInfo.getAreaId()); caseInfo.setAreaName(codeService.findCodeValueByMap(m).getItemText()); String undertakerName = caseInfo.getUndertakerName1(); if(caseInfo.getUndertakerId() != null) { User user = userService.findUserById(caseInfo.getUndertakerId().trim()); undertakerName += "," + user.getDisplayName(); } caseInfo.setUndertakerName(undertakerName); if ("add".equalsIgnoreCase(this.flag)){ String day[] = sdf.format(caseInfo.getLaTime()).split("-"); caseInfo.setGlh(day[0]); caseInfo.setDeptId(this.getLoginUserDepartmentId()); caseInfo.setDelFlag(0); caseInfo.setCaseStatus("8"); caseInfoService.save(caseInfo); }else{ if(caseInfo.getCaseStatus() != null && "5".equals(caseInfo.getCaseStatus())) { caseInfo.setCaseStatus("8"); } caseInfoService.update(caseInfo); if(type != null && "1".equals(type) )//超级管理员修改,重新生成文书 { m.put("caseId", caseInfo.getId()); m.put("instrumentType", "100");//立案审批表 List<InstrumentsInfo> list1 = instrumentsInfoService.findInstrumentsInfoss(m); if(list1.size() != 0) { InstrumentsInfo ins = list1.get(0); String root = this.getRequest().getRealPath("/"); root = root.replaceAll("\\\\", "/"); Map<String, Object> map=new HashMap<String, Object>(); String lsname = ins.getLastFile(); String filename = ins.getFileName(); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmssSSS"); String destName = sdf1.format(new Date()); String newfilename = "立案审批表"+destName+".docx"; ins.setFileName(newfilename); ins.setLastFile(lsname + "," + filename); ins.setCaseId(caseInfo.getId()); ins.setCaseName(caseInfo.getCaseName()); ins.setTime(caseInfo.getCaseTime()); map.put("ajbz", NullToString(ins.getAjbz())); map.put("glh", NullToString(ins.getAjh())); map.put("glhNum", NullToString(ins.getAjhNum())); map.put("caseCause", NullToString(caseInfo.getCaseCause())); m.put("codeName", "案件来源"); m.put("itemValue", caseInfo.getCaseSource()); map.put("caseSource", codeService.findCodeValueByMap(m).getItemText()); if(caseInfo.getCaseTime() != null) { map.put("caseTime", sdf.format(caseInfo.getCaseTime())); } else { map.put("caseTime", ""); } map.put("caseName", NullToString(caseInfo.getCaseName())); if(caseInfo.getPersonType().equals("1")) { map.put("person", NullToString(caseInfo.getPerson())); } else { map.put("person", NullToString(caseInfo.getCompanyName())); } map.put("tele", NullToString(caseInfo.getTele())); map.put("personCondition", NullToString(caseInfo.getPersonCondition())); map.put("personAddress", NullToString(caseInfo.getCompanyAddress())); map.put("personCode", NullToString(caseInfo.getZipCode())); map.put("caseCondition", NullToString(caseInfo.getCaseCondition())); map.put("cbr2zh", ""); // map.put("cbr2qm", ""); User uu = userService.findUserById(caseInfo.getCreateUserID()); map.put("cbr1zh", NullToString(uu.getZfzh())); // Map<String,Object> cbr1qm = new HashMap<String, Object>(); // if(uu.getFilePath() != null && !"".equals(uu.getFilePath())) // { // URL url1 = new URL(uu.getFilePath()); // HttpURLConnection conn1 = (HttpURLConnection)url1.openConnection(); // cbr1qm.put("content", FileDocUtil.inputStream2ByteArray(conn1.getInputStream(), true)); // } // map.put("cbr1qm", cbr1qm); // Map<String,Object> cbr2qm = new HashMap<String, Object>(); // if(caseInfo.getUndertakerId() != null && !"".equals(caseInfo.getUndertakerId())) // { // User user = userService.findUserById(caseInfo.getUndertakerId()); // map.put("cbr2zh", NullToString(user.getZfzh())); // // if(user.getFilePath() != null && !"".equals(user.getFilePath())) // { // URL url2 = new URL(user.getFilePath()); // HttpURLConnection conn2 = (HttpURLConnection)url2.openConnection(); // cbr2qm.put("content", FileDocUtil.inputStream2ByteArray(conn2.getInputStream(), true)); // } // } // map.put("cbr2qm", cbr2qm); map.put("undertakerComment", NullToString(caseInfo.getUndertakerComment())); map.put("underTime",changeTimeToZw(caseInfo.getUnderTime())); map.put("checkComment", NullToString(caseInfo.getCheckComment())); map.put("checkTime", changeTimeToZw(caseInfo.getCheckTime())); // Map<String,Object> checkQm = new HashMap<String, Object>(); // if(caseInfo.getCheckPersonId() != null && !"".equals(caseInfo.getCheckPersonId())) // { // User user = userService.findUserById(caseInfo.getCheckPersonId()); // if(user.getFilePath() != null && !"".equals(user.getFilePath())) // { // URL url2 = new URL(user.getFilePath()); // HttpURLConnection conn2 = (HttpURLConnection)url2.openConnection(); // checkQm.put("content", FileDocUtil.inputStream2ByteArray(conn2.getInputStream(), true)); // } // } // map.put("checkQm", checkQm); map.put("approvalComment", NullToString(caseInfo.getApprovalComment())); map.put("approvalTime", changeTimeToZw(caseInfo.getApprovalTime())); // Map<String,Object> approvalQm = new HashMap<String, Object>(); // if(caseInfo.getApprovalId() != null && !"".equals(caseInfo.getApprovalId())) // { // User user = userService.findUserById(caseInfo.getApprovalId()); // if(user.getFilePath() != null && !"".equals(user.getFilePath())) // { // URL url2 = new URL(user.getFilePath()); // HttpURLConnection conn2 = (HttpURLConnection)url2.openConnection(); // approvalQm.put("content", FileDocUtil.inputStream2ByteArray(conn2.getInputStream(), true)); // } // } // map.put("approvalQm", approvalQm); FileDocUtil fileDocUtil = new FileDocUtil(); String[] s = fileDocUtil.createDocFile(root + "立案审批表.docx", ins.getFileName(),root+"../../virtualdir/file/"+caseInfo.getCaseName(), map).split(","); ins.setFileSize(s[0]); ins.setPageSize(s[1]); instrumentsInfoService.update(ins); } } } //将案件相关文书案件名称更新 Map mmm = new HashMap(); mmm.put("caseId", caseInfo.getId()); mmm.put("caseName", caseInfo.getCaseName()); instrumentsInfoService.updateAllWsInfoByMap(mmm); return RELOAD; } /** * 将File对象转换为Blob对象,并设置到实体类中 * 如果没有File对象,可删除此方法,并一并删除save方法中调用此方法的代码 */ private void setBlobField(FileInputStream in) { if (null != caseInfo) { try { //此处将File对象转换成blob对象,并设置到caseInfo中去 } catch (Exception ex) { ex.printStackTrace(); } } } /** * 删除信息 */ public String delete() throws Exception{ try{ caseInfoService.deleteWithFlag(ids); this.getResponse().getWriter().println("{\"result\":true}"); }catch(Exception e){ this.getResponse().getWriter().println("{\"result\":false}"); } return null; } /** * 调转至审核 * @author luting * 2015-10-20 * @return * @throws Exception */ public String shenhe() throws Exception { view(); caseInfo.setUnderTime(caseInfo.getLaTime()); if(caseInfo.getCaseStatus() != null && "8".equals(caseInfo.getCaseStatus())) { Map map = new HashMap(); String day[] = sdf.format(caseInfo.getLaTime()).split("-"); map.put("fineType", caseInfo.getFineType()); map.put("glh", day[0]); flag = caseInfoService.getGlhNumListByMap(map); int glhNum = caseInfoService.getMaxGlhNumByMap(map)+1; String ss = glhNum + ""; if(ss.length() == 1) { ss = "00" + ss; } else if(ss.length() == 2) { ss = "0" + ss; } caseInfo.setGlhNum(ss); } return SUCCESS; } /** * 保存审核信息 * @author luting * 2015-10-20 * @return * @throws Exception */ public String shenheSave() throws Exception { try { CaseInfo ca = caseInfoService.getById(caseInfo.getId()); String result = caseInfo.getResult(); String status = caseInfo.getCaseStatus(); String remark = caseInfo.getUndertakerComment(); Date checkTime = caseInfo.getUnderTime(); CheckRecord checkrecord = new CheckRecord(); checkrecord.setInfoId(caseInfo.getId()); checkrecord.setCheckRemark(remark); checkrecord.setCheckTime(checkTime); if(status.equals("8")) { if(result.equals("0")) { ca.setCaseStatus("7"); checkrecord.setCheckResult("审核通过"); ca.setFwcheck("1"); String ss = caseInfo.getGlhNum(); if(ss.length() == 1) { ss = "00" + ss; } else if(ss.length() == 2) { ss = "0" + ss; } ca.setGlhNum(ss); if(ca.getFineType().equals("0")) { ca.setCaseId("苏园安监违立字〔" + ca.getGlh() + "〕" + ca.getGlhNum() + "号"); } else { ca.setCaseId("苏园安监立字〔" + ca.getGlh() + "〕" + ca.getGlhNum() + "号"); } } else { ca.setCaseStatus("5"); checkrecord.setCheckResult("审核不通过"); } } else if(status.equals("7")) { ca.setUnderTime(checkTime); if(result.equals("0")) { ca.setCaseStatus("0"); checkrecord.setCheckResult("审核通过"); ca.setDzqmcheck("1"); } else { ca.setCaseStatus("5"); checkrecord.setCheckResult("审核不通过"); } } else if(status.equals("0")) { ca.setCheckTime(checkTime); ca.setCheckComment(remark); ca.setCheckPersonId(this.getLoginUser().getId()); ca.setCheckPersonName(this.getLoginUser().getDisplayName()); if(result.equals("0")) { ca.setCaseStatus("1"); checkrecord.setCheckResult("审核通过"); ca.setDzcheck("1"); } else { ca.setCaseStatus("5"); checkrecord.setCheckResult("审核不通过"); } } else { ca.setApprovalTime(checkTime); ca.setApprovalComment(remark); ca.setApprovalId(this.getLoginUser().getId()); ca.setApprovalName(this.getLoginUser().getDisplayName()); if(result.equals("0")) { ca.setCaseStatus("2"); ca.setJzcheck("1"); checkrecord.setCheckResult("审批通过"); String root = this.getRequest().getRealPath("/"); root = root.replaceAll("\\\\", "/"); Map<String, Object> map=new HashMap<String, Object>(); InstrumentsInfo ins = new InstrumentsInfo(); ins.setCaseId(ca.getId()); ins.setCaseName(ca.getCaseName()); ins.setHttpurl(SysPropertiesUtil.getProperty("httpurl")); ins.setNwurl(SysPropertiesUtil.getProperty("nwurl")); ins.setInstrumentType("100"); ins.setTime(ca.getCaseTime()); String fileName = "立案审批表"; SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmssSSS"); String destName = sdf1.format(new Date()); ins.setIfCheck("0"); ins.setIfPrint("1"); ins.setDeptId(this.getLoginUserDepartmentId()); ins.setFileName(fileName+destName+".docx"); SimpleDateFormat sdf11 = new SimpleDateFormat("yyyyMMdd"); String instrumentsName = fileName + sdf11.format(ins.getTime()); ins.setInstrumentName(instrumentsName); //获取文书号 luting 2015-10-25 if(ca.getFineType().equals("0")) { ins.setAjbz("苏园安监违立字"); } else { ins.setAjbz("苏园安监立字"); } ins.setAjh(ca.getGlh()); ins.setAjhNum(ca.getGlhNum()); ins.setCompanyName(ca.getCompanyName()); String wsh = ins.getAjbz() + "〔" + ins.getAjh() + "〕" + ins.getAjhNum() + "号"; ins.setWsh(wsh); map.put("ajbz", NullToString(ins.getAjbz())); map.put("glh", NullToString(ins.getAjh())); map.put("glhNum", NullToString(ins.getAjhNum())); map.put("caseCause", NullToString(ca.getCaseCause())); Map m = new HashMap(); m.put("codeName", "案件来源"); m.put("itemValue", ca.getCaseSource()); map.put("caseSource", codeService.findCodeValueByMap(m).getItemText()); if(ca.getCaseTime() != null) { map.put("caseTime", sdf.format(ca.getCaseTime())); } else { map.put("caseTime", ""); } map.put("caseName", NullToString(ca.getCaseName())); if(ca.getPersonType().equals("1")) { map.put("person", NullToString(ca.getPerson())); } else { map.put("person", NullToString(ca.getCompanyName())); } map.put("tele", NullToString(ca.getTele())); map.put("personCondition", NullToString(ca.getPersonCondition())); map.put("personAddress", NullToString(ca.getCompanyAddress())); map.put("personCode", NullToString(ca.getZipCode())); map.put("caseCondition", NullToString(ca.getCaseCondition())); map.put("cbr2zh", ""); // map.put("cbr2qm", ""); User uu = userService.findUserById(ca.getCreateUserID()); map.put("cbr1zh", NullToString(uu.getZfzh())); // Map<String,Object> cbr1qm = new HashMap<String, Object>(); // if(uu.getFilePath() != null && !"".equals(uu.getFilePath())) // { // URL url1 = new URL(uu.getFilePath()); // HttpURLConnection conn1 = (HttpURLConnection)url1.openConnection(); // cbr1qm.put("content", FileDocUtil.inputStream2ByteArray(conn1.getInputStream(), true)); // } // map.put("cbr1qm", cbr1qm); // Map<String,Object> cbr2qm = new HashMap<String, Object>(); // if(ca.getUndertakerId() != null && !"".equals(ca.getUndertakerId())) // { // User user = userService.findUserById(ca.getUndertakerId()); // map.put("cbr2zh", NullToString(user.getZfzh())); // // if(user.getFilePath() != null && !"".equals(user.getFilePath())) // { // URL url2 = new URL(user.getFilePath()); // HttpURLConnection conn2 = (HttpURLConnection)url2.openConnection(); // cbr2qm.put("content", FileDocUtil.inputStream2ByteArray(conn2.getInputStream(), true)); // } // } // map.put("cbr2qm", cbr2qm); map.put("undertakerComment", NullToString(ca.getUndertakerComment())); map.put("underTime",changeTimeToZw(ca.getUnderTime())); map.put("checkComment", NullToString(ca.getCheckComment())); map.put("checkTime", changeTimeToZw(ca.getCheckTime())); // Map<String,Object> checkQm = new HashMap<String, Object>(); // if(ca.getCheckPersonId() != null && !"".equals(ca.getCheckPersonId())) // { // User user = userService.findUserById(ca.getCheckPersonId()); // if(user.getFilePath() != null && !"".equals(user.getFilePath())) // { // URL url2 = new URL(user.getFilePath()); // HttpURLConnection conn2 = (HttpURLConnection)url2.openConnection(); // checkQm.put("content", FileDocUtil.inputStream2ByteArray(conn2.getInputStream(), true)); // } // } // map.put("checkQm", checkQm); map.put("approvalComment", NullToString(ca.getApprovalComment())); map.put("approvalTime", changeTimeToZw(ca.getApprovalTime())); // Map<String,Object> approvalQm = new HashMap<String, Object>(); // if(ca.getApprovalId() != null && !"".equals(ca.getApprovalId())) // { // User user = userService.findUserById(ca.getApprovalId()); // if(user.getFilePath() != null && !"".equals(user.getFilePath())) // { // URL url2 = new URL(user.getFilePath()); // HttpURLConnection conn2 = (HttpURLConnection)url2.openConnection(); // approvalQm.put("content", FileDocUtil.inputStream2ByteArray(conn2.getInputStream(), true)); // } // } // map.put("approvalQm", approvalQm); FileDocUtil fileDocUtil = new FileDocUtil(); String[] s = fileDocUtil.createDocFile(root + "立案审批表.docx", ins.getFileName(),root+"../../virtualdir/file/"+ca.getCaseName(), map).split(","); ins.setNeedCheck("2"); ins.setDzqmCheck("2"); ins.setDzCheck("2"); ins.setJzCheck("2"); ins.setDelFlag(0); ins.setFileSize(s[0]); ins.setPageSize(s[1]); String linkId = java.util.UUID.randomUUID().toString().replace("-", ""); ins.setLinkId(linkId); instrumentsInfoService.save(ins); } else { ca.setCaseStatus("5"); checkrecord.setCheckResult("审批不通过"); } } caseInfoService.update(ca); checkrecord.setCheckUserid(this.getLoginUser().getId()); checkrecord.setCheckUsername(this.getLoginUser().getDisplayName()); checkrecord.setDelFlag(0); checkRecordService.save(checkrecord); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return RELOAD; } /** * 将null值转换为空字符串 * @author luting * 2015-10-27 * @param object * @param i * @return */ public String NullToString(String object) { String s = ""; if(object != null) { s = object; } return s; } /** * 跳转至归档页面 * @author luting * 2015-10-27 * @param object * @param i * @return * @throws IOException */ public String guidnag() throws IOException { if(caseInfo != null && caseInfo.getId() != null && !"".equals(caseInfo.getId())) { Map<String, Object> paraMap = new HashMap<String, Object>(); paraMap.put("caseId", caseInfo.getId()); paraMap.put("notin", "35"); wsList = instrumentsInfoService.findInstrumentsInfos(paraMap); } caseInfo.setBcqx("永久"); return SUCCESS; } /*** * <b>function:</b> 将数字转化为大写 * @author luting * 2015-10-30 * @param num 数字 * @return 转换后的大写数字 */ public static String numToUpper(int num) { String[] str = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九" }; String ss[] = new String[] { "", "十", "百", "千", "万", "十", "百", "千", "亿" }; String s = String.valueOf(num); StringBuffer sb = new StringBuffer(); for (int i = 0; i < s.length(); i++) { String index = String.valueOf(s.charAt(i)); sb = sb.append(str[Integer.parseInt(index)]); } String sss = String.valueOf(sb); int i = 0; for (int j = sss.length(); j > 0; j--) { sb = sb.insert(j, ss[i++]); } return sb.toString(); } /** * 保存归档信息 * @author luting * 2015-10-27 * @param object * @param i * @return */ public String guidnagSave() throws Exception { try { CaseInfo ca = caseInfoService.getById(caseInfo.getId()); ca.setCaseStatus("4"); String bcqx = caseInfo.getBcqx(); Date gdTime = caseInfo.getGdTime(); ca.setGdNum(new SimpleDateFormat("yyyyMMddHHmmss").format(gdTime)); ca.setBcqx(bcqx); ca.setGdTime(gdTime); ca.setGdhttpurl(SysPropertiesUtil.getProperty("httpurl")); ca.setGdnwurl(SysPropertiesUtil.getProperty("nwurl")); if(ca.getFineType().equals("0")) { ca.setGajbz("苏园安监违案字"); } else { ca.setGajbz("苏园安监案字"); } Map m = new HashMap(); String root = this.getRequest().getRealPath("/"); root = root.replaceAll("\\\\", "/"); FileDocUtil fileDocUtil = new FileDocUtil(); //生成证据列表 SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmssSSS"); String destName = sdf1.format(new Date()); Map map1 = new HashMap(); Map mmm = new HashMap(); mmm.put("caseId", ca.getId()); //生成证据列表 List<Map<String, Object>> newList = new ArrayList<Map<String, Object>>(); zjList = caseInfoService.getCaseZjList(mmm); for(int i=0;i<zjList.size();i++) { CaseZj zjlb = zjList.get(i); Map<String, Object> mm = new HashMap<String, Object>(); int index = i+1; mm.put("wpmc", index+"."+NullToString(zjlb.getZjContent())); newList.add(mm); } map1.put("zjList", newList); if(ca.getPersonType().equals("1")) { map1.put("companyName", NullToString(ca.getPerson())+"行政处罚案(个人)证据清单及证明内容"); } else { map1.put("companyName", NullToString(ca.getCompanyName())+"行政处罚案(单位)证据清单及证明内容"); } map1.put("time", changeTimeToZw(gdTime)); fileDocUtil.createDocFile(root+"证据清单及证明内容.docx", "证据清单及证明内容"+destName+".docx", root+"../../virtualdir/file/"+ca.getCaseName(), map1).split(","); //生成照片 Map map3 = new HashMap(); List<Map<String, Object>> picList = new ArrayList<Map<String, Object>>(); mmm.put("zjType", "1"); clList = caseInfoService.getCaseClList(mmm); int num=1; for(CaseCl cl:clList) { Map ss = new HashMap(); ss.put("linkId",cl.getLinkId()); ss.put("mkType", "ajxx"); ss.put("picType","ajclfj"); List<PhotoPic> list = photoPicService.findPicPath(ss); Map<String, Object> mm = new HashMap<String, Object>(); mm.put("picName", "照片" + numToUpper(num)); mm.put("picTime", changeTimeToZw(cl.getPicTime())); mm.put("picAdd", NullToString(cl.getPicAdd())); mm.put("picContent", NullToString(cl.getPicContent())); for(PhotoPic photo:list) { Map<String,Object> header = new HashMap<String, Object>(); int idx = photo.getPicName().lastIndexOf('.'); header.put("type", photo.getPicName().substring(idx)); URL url = new URL(photo.getNwUrl()+"/upload/photo/"+photo.getPicName()); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(6000); InputStream in = conn.getInputStream(); byte[] buf = new byte[1024]; int size = 0; File file = new File(root+"../../virtualdir/upload/photo/xz"); if(!file.exists()) { file.mkdir(); } FileOutputStream out = new FileOutputStream(root+"../../virtualdir/upload/photo/xz/"+photo.getPicName()); while ((size = in.read(buf)) != -1) { out.write(buf, 0, size); } out.flush(); out.close(); in.close(); header.put("content", FileDocUtil.inputStream2ByteArray(new FileInputStream(root+"../../virtualdir/upload/photo/xz/"+photo.getPicName()), true)); mm.put("pic",header); picList.add(mm); num ++; } } map3.put("picList", picList); fileDocUtil.createDocFile(root+"照片.docx", "照片"+destName+".docx", root+"../../virtualdir/file/"+ca.getCaseName(), map3).split(","); //生成案卷(首页) Map<String, Object> map=new HashMap<String, Object>(); map.put("ajbz", NullToString(ca.getGajbz())); map.put("gah", NullToString(ca.getGlh())); map.put("gahNum", NullToString(ca.getGlhNum())); map.put("caseName", NullToString(ca.getCaseName())); map.put("caseCause", NullToString(ca.getCaseCause())); map.put("approvalResult", NullToString(ca.getApprovalResult())); map.put("laTime", changeTimeToZw(ca.getLaTime())); map.put("jaTime", changeTimeToZw(ca.getJaTime())); map.put("zfry1", ""); map.put("zfry2", ""); map.put("zfry1", NullToString(userService.findUserById(ca.getCreateUserID()).getDisplayName())); if(ca.getUndertakerId() != null && !"".equals(ca.getUndertakerId())) { User user = userService.findUserById(ca.getUndertakerId()); map.put("zfry2", NullToString(user.getDisplayName())); } map.put("gdTime", changeTimeToZw(ca.getGdTime())); map.put("gdNum", NullToString(ca.getGdNum())); map.put("bcqx", NullToString(ca.getBcqx())); String[] s = fileDocUtil.createDocFile(root+"案卷(首页).docx","案卷(首页).docx", root+"../../virtualdir/file/"+ca.getCaseName(), map).split(","); ca.setSySize(s[0]); //生成封面 fileDocUtil.createDocFile(root+"封面.docx","封面.docx", root+"../../virtualdir/file/"+ca.getCaseName(), map).split(","); if(instrumentsInfo.getId() != null && !"".equals(instrumentsInfo.getId())) { String[] wsids = instrumentsInfo.getId().replaceAll(" ", "").split(","); for(int i=0;i<wsids.length;i++) { InstrumentsInfo ins = instrumentsInfoService.getById(wsids[i].trim()); String sort = i + ""; if(sort.length() == 1) { sort = "00" + sort; } else if(sort.length() == 2) { sort = "0" + sort; } ins.setSort(sort); instrumentsInfoService.update(ins); } } //生成卷内目录 Map<String, Object> map2=new HashMap<String, Object>(); m.put("caseId", ca.getId()); List<InstrumentsInfo> wslist = instrumentsInfoService.findInstrumentsInfos(m); List<Map<String, Object>> newList2 = new ArrayList<Map<String, Object>>(); int page = 1; for(int i=0;i<wslist.size();i++) { InstrumentsInfo in = wslist.get(i); if(in.getPageSize() != null && !"".equals(in.getPageSize())) { Map<String, Object> mm2 = new HashMap<String, Object>(); m.put("codeName", "文书类型"); m.put("itemValue", in.getInstrumentType()); String fileName = codeService.findCodeValueByMap(m).getItemText(); int index = i+1; mm2.put("xh", index + ""); if(in.getWsh() != null && !"".equals(in.getWsh())) { mm2.put("wjmc",fileName+ "(" + in.getWsh() + ")" ); } else { mm2.put("wjmc",fileName); } mm2.put("ys", page); page += Integer.parseInt(in.getPageSize()); mm2.put("time", changeTimeToZw(in.getTime())); newList2.add(mm2); } } map2.put("mlList", newList2); String[] sss = fileDocUtil.createDocFile(root+"卷内目录.docx","卷内目录.docx", root+"../../virtualdir/file/"+ca.getCaseName(), map2).split(","); ca.setJnmuSize(sss[0]); caseInfoService.update(ca); //将案件相关文书置为不可回执 mmm.put("ifCheck", "7"); instrumentsInfoService.updateAllWsInfoByMap(mmm); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return RELOAD; } /** * 下载文书 * @author luting * 2015-10-27 * @param object * @param i * @return */ public void downloadAllFile() { try { CaseInfo ca = caseInfoService.getById(caseInfo.getId()); String urls = ""; String fileName = ""; if(flag.equals("1"))//案卷(首页) { urls = ca.getGdnwurl() +"/file/" + URLEncoder.encode(ca.getCaseName(), "utf-8")+"/"+URLEncoder.encode("案卷(首页).docx", "utf-8"); fileName = "案卷(首页).docx"; } else if(flag.equals("2"))//卷内目录 { urls = ca.getGdnwurl() +"/file/" + URLEncoder.encode(ca.getCaseName(), "utf-8")+"/"+URLEncoder.encode("卷内目录.docx", "utf-8"); fileName = "卷内目录.docx"; } else if(flag.equals("3"))//封面 { urls = ca.getGdnwurl() +"/file/" + URLEncoder.encode(ca.getCaseName(), "utf-8")+"/"+URLEncoder.encode("封面.docx", "utf-8"); fileName = "封面.docx"; } else if(flag.equals("4"))//照片 { urls = ca.getGdnwurl() +"/file/" + URLEncoder.encode(ca.getCaseName(), "utf-8")+"/"+URLEncoder.encode("照片.docx", "utf-8"); fileName = "照片.docx"; } else if(flag.equals("5"))//证据清单及证明内容 { urls = ca.getGdnwurl() +"/file/" + URLEncoder.encode(ca.getCaseName(), "utf-8")+"/"+URLEncoder.encode("证据清单及证明内容.docx", "utf-8"); fileName = "证据清单及证明内容.docx"; } URL url = new URL(urls); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); InputStream in = conn.getInputStream(); String browName = new String(); browName = URLEncoder.encode(fileName, "UTF-8"); String clientInfo = getRequest().getHeader("User-agent"); if ((clientInfo != null) && (clientInfo.indexOf("MSIE") > 0)) { if ((clientInfo.indexOf("MSIE 6") > 0) || (clientInfo.indexOf("MSIE 5") > 0)) browName = new String(fileName.getBytes("GBK"), "ISO-8859-1"); } Struts2Util.getResponse() .addHeader( "Content-Disposition", "attachment;filename=" + browName); OutputStream out = Struts2Util.getResponse().getOutputStream(); try { byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) != -1) { out.write(buf, 0, len); } } catch (Exception e) { e.printStackTrace(); } finally { in.close(); out.close(); } } catch (Exception e) { e.printStackTrace(); } } /** * 调转至审核 * @author luting * 2015-10-20 * @return * @throws Exception */ public String shenheAll() throws Exception { return SUCCESS; } /** * 保存审核信息 * @author luting * 2015-10-20 * @return * @throws Exception */ public String shenheAllSave() throws Exception { String result = caseInfo.getResult(); String remark = caseInfo.getUndertakerComment(); String[] idArray = ids.split("\\|"); if(null != idArray) { for(String id : idArray) { if(id!=null && !id.trim().equals("")) { CaseInfo ca = caseInfoService.getById(id); Date time = ca.getCaseTime(); String status = ca.getCaseStatus(); CheckRecord checkrecord = new CheckRecord(); checkrecord.setInfoId(caseInfo.getId()); checkrecord.setCheckRemark(remark); if(status.equals("8")) { if(result.equals("0")) { ca.setCaseStatus("7"); checkrecord.setCheckResult("审核通过"); ca.setFwcheck("1"); } else { ca.setCaseStatus("5"); checkrecord.setCheckResult("审核不通过"); } } else if(status.equals("7")) { ca.setUnderTime(time); if(result.equals("0")) { ca.setCaseStatus("0"); checkrecord.setCheckResult("审核通过"); ca.setDzqmcheck("1"); } else { ca.setCaseStatus("5"); checkrecord.setCheckResult("审核不通过"); } } else if(status.equals("0")) { ca.setCheckComment(remark); ca.setCheckPersonId(this.getLoginUser().getId()); ca.setCheckPersonName(this.getLoginUser().getDisplayName()); ca.setCheckTime(time); if(result.equals("0")) { ca.setCaseStatus("1"); checkrecord.setCheckResult("审核通过"); ca.setDzcheck("1"); } else { ca.setCaseStatus("5"); checkrecord.setCheckResult("审核不通过"); } } else { ca.setApprovalComment(remark); ca.setApprovalId(this.getLoginUser().getId()); ca.setApprovalName(this.getLoginUser().getDisplayName()); ca.setApprovalTime(time); if(result.equals("0")) { Map m = new HashMap(); ca.setCaseStatus("2"); ca.setJzcheck("1"); checkrecord.setCheckResult("审批通过"); String root = this.getRequest().getRealPath("/"); root = root.replaceAll("\\\\", "/"); Map<String, Object> map=new HashMap<String, Object>(); InstrumentsInfo ins = new InstrumentsInfo(); ins.setCaseId(ca.getId()); ins.setCaseName(ca.getCaseName()); ins.setHttpurl(SysPropertiesUtil.getProperty("httpurl")); ins.setNwurl(SysPropertiesUtil.getProperty("nwurl")); ins.setInstrumentType("100"); ins.setTime(ca.getCaseTime()); String fileName = "立案审批表"; SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmssSSS"); String destName = sdf1.format(new Date()); ins.setIfCheck("0"); ins.setIfPrint("1"); ins.setDeptId(this.getLoginUserDepartmentId()); ins.setFileName(fileName+destName+".docx"); SimpleDateFormat sdf11 = new SimpleDateFormat("yyyyMMdd"); String instrumentsName = fileName + sdf11.format(ins.getTime()); ins.setInstrumentName(instrumentsName); //获取文书号 luting 2015-10-25 if(ca.getFineType().equals("0")) { ins.setAjbz("苏园安监违立字"); } else { ins.setAjbz("苏园安监立字"); } ins.setAjh(ca.getGlh()); ins.setAjhNum(ca.getGlhNum()); ins.setCompanyName(ca.getCompanyName()); String wsh = ins.getAjbz() + "〔" + ins.getAjh() + "〕" + ins.getAjhNum() + "号"; ins.setWsh(wsh); map.put("ajbz", NullToString(ins.getAjbz())); map.put("glh", NullToString(ins.getAjh())); map.put("glhNum", NullToString(ins.getAjhNum())); map.put("caseCause", NullToString(ca.getCaseCause())); m.put("codeName", "案件来源"); m.put("itemValue", ca.getCaseSource()); map.put("caseSource", codeService.findCodeValueByMap(m).getItemText()); if(ca.getCaseTime() != null) { map.put("caseTime", sdf.format(ca.getCaseTime())); } else { map.put("caseTime", ""); } map.put("caseName", NullToString(ca.getCaseName())); if(ca.getPersonType().equals("1")) { map.put("person", NullToString(ca.getPerson())); } else { map.put("person", NullToString(ca.getCompanyName())); } map.put("tele", NullToString(ca.getTele())); map.put("personCondition", NullToString(ca.getPersonCondition())); map.put("personAddress", NullToString(ca.getCompanyAddress())); map.put("personCode", NullToString(ca.getZipCode())); map.put("caseCondition", NullToString(ca.getCaseCondition())); map.put("cbr2zh", ""); // map.put("cbr2qm", ""); User uu = userService.findUserById(ca.getCreateUserID()); map.put("cbr1zh", NullToString(uu.getZfzh())); // Map<String,Object> cbr1qm = new HashMap<String, Object>(); // if(uu.getFilePath() != null && !"".equals(uu.getFilePath())) // { // URL url1 = new URL(uu.getFilePath()); // HttpURLConnection conn1 = (HttpURLConnection)url1.openConnection(); // cbr1qm.put("content", FileDocUtil.inputStream2ByteArray(conn1.getInputStream(), true)); // } // map.put("cbr1qm", cbr1qm); // Map<String,Object> cbr2qm = new HashMap<String, Object>(); // if(ca.getUndertakerId() != null && !"".equals(ca.getUndertakerId())) // { // User user = userService.findUserById(ca.getUndertakerId()); // map.put("cbr2zh", NullToString(user.getZfzh())); // // if(user.getFilePath() != null && !"".equals(user.getFilePath())) // { // URL url2 = new URL(user.getFilePath()); // HttpURLConnection conn2 = (HttpURLConnection)url2.openConnection(); // cbr2qm.put("content", FileDocUtil.inputStream2ByteArray(conn2.getInputStream(), true)); // } // } // map.put("cbr2qm", cbr2qm); map.put("undertakerComment", NullToString(ca.getUndertakerComment())); map.put("underTime",changeTimeToZw(ca.getUnderTime())); map.put("checkComment", NullToString(ca.getCheckComment())); map.put("checkTime", changeTimeToZw(ca.getCheckTime())); // Map<String,Object> checkQm = new HashMap<String, Object>(); // if(ca.getCheckPersonId() != null && !"".equals(ca.getCheckPersonId())) // { // User user = userService.findUserById(ca.getCheckPersonId()); // if(user.getFilePath() != null && !"".equals(user.getFilePath())) // { // URL url2 = new URL(user.getFilePath()); // HttpURLConnection conn2 = (HttpURLConnection)url2.openConnection(); // checkQm.put("content", FileDocUtil.inputStream2ByteArray(conn2.getInputStream(), true)); // } // } // map.put("checkQm", checkQm); map.put("approvalComment", NullToString(ca.getApprovalComment())); map.put("approvalTime", changeTimeToZw(ca.getApprovalTime())); // Map<String,Object> approvalQm = new HashMap<String, Object>(); // if(ca.getApprovalId() != null && !"".equals(ca.getApprovalId())) // { // User user = userService.findUserById(ca.getApprovalId()); // if(user.getFilePath() != null && !"".equals(user.getFilePath())) // { // URL url2 = new URL(user.getFilePath()); // HttpURLConnection conn2 = (HttpURLConnection)url2.openConnection(); // approvalQm.put("content", FileDocUtil.inputStream2ByteArray(conn2.getInputStream(), true)); // } // } // map.put("approvalQm", approvalQm); FileDocUtil fileDocUtil = new FileDocUtil(); String[] s = fileDocUtil.createDocFile(root + "立案审批表.docx", ins.getFileName(),root+"../../virtualdir/file/"+ca.getCaseName(), map).split(","); ins.setNeedCheck("2"); ins.setDzqmCheck("2"); ins.setDzCheck("2"); ins.setJzCheck("2"); ins.setDelFlag(0); ins.setFileSize(s[0]); ins.setPageSize(s[1]); String linkId = java.util.UUID.randomUUID().toString().replace("-", ""); ins.setLinkId(linkId); instrumentsInfoService.save(ins); } else { ca.setCaseStatus("5"); checkrecord.setCheckResult("审批不通过"); } } checkrecord.setCheckUserid(this.getLoginUser().getId()); checkrecord.setCheckUsername(this.getLoginUser().getDisplayName()); checkrecord.setCheckTime(time); checkrecord.setDelFlag(0); caseInfoService.update(ca); checkRecordService.save(checkrecord); } } } return RELOAD; } public String initUploadFile() { caseCl.setCaseId(caseInfo.getId()); loginUserId = this.getLoginUser().getId(); return SUCCESS; } public void uploadFileList() { Map<String, Object> paraMap = new HashMap<String, Object>(); if(pagination==null) pagination = new Pagination(this.getRequest()); if(null != caseCl){ //设置查询条件,开发人员可以在此增加过滤条件 if ((null != caseCl.getCaseId()) && (0 < caseCl.getCaseId().trim().length())){ paraMap.put("caseId", caseCl.getCaseId().trim() ); } if ((null != caseCl.getZjType()) && (0 < caseCl.getZjType().trim().length())){ paraMap.put("zjType", caseCl.getZjType().trim() ); } } JsonConfig config = new JsonConfig(); config.registerJsonValueProcessor(java.util.Date.class,new DateJsonValueProcessor()); Map<String, String> codeMap = new HashMap<String, String>(); //此处添加需要转换的一维代码,key是一维代码在数据对象中的属性名,value是一维代码的codeId config.registerJsonValueProcessor(String.class,new CodeJsonValueProcessor(codeMap)); final String filter = "id|zjType|createUserID|"; if (filter != null && filter.length() > 1) { config.setJsonPropertyFilter(new PropertyFilter() { public boolean apply(Object source, String name, Object value) { if (filter.indexOf(name + "|") != -1) return false; else return true; } }); } pagination = caseInfoService.findCaseClByPage(pagination, paraMap); convObjectToJson(pagination, config); } public void zwtfilelist() { Map<String, Object> paraMap = new HashMap<String, Object>(); if(pagination==null) pagination = new Pagination(this.getRequest()); if(null != caseCl){ //设置查询条件,开发人员可以在此增加过滤条件 if ((null != caseCl.getCaseId()) && (0 < caseCl.getCaseId().trim().length())){ paraMap.put("caseId", caseCl.getCaseId().trim() ); } if ((null != caseCl.getZjType()) && (0 < caseCl.getZjType().trim().length())){ paraMap.put("zjType", caseCl.getZjType().trim() ); } } JsonConfig config = new JsonConfig(); config.registerJsonValueProcessor(java.util.Date.class,new DateJsonValueProcessor()); Map<String, String> codeMap = new HashMap<String, String>(); //此处添加需要转换的一维代码,key是一维代码在数据对象中的属性名,value是一维代码的codeId config.registerJsonValueProcessor(String.class,new CodeJsonValueProcessor(codeMap)); final String filter = "id|zjType|createUserID|"; if (filter != null && filter.length() > 1) { config.setJsonPropertyFilter(new PropertyFilter() { public boolean apply(Object source, String name, Object value) { if (filter.indexOf(name + "|") != -1) return false; else return true; } }); } pagination.setPageNumber(pageNo); pagination.setPageSize(pageSize); pagination = caseInfoService.findCaseClByPage(pagination, paraMap); JSONObject json=new JSONObject(); JSONArray ja = JSONArray.fromObject(pagination.getListOfObject(), config); json.put("result", ja); json.put("count", pagination.getTotalCount()); int totalPage; totalPage = (pagination.getTotalCount()%pageSize==0?pagination.getTotalCount()/pageSize:(pagination.getTotalCount()/pageSize+1)); json.put("totalPage", totalPage); json.put("pageNo", pageNo); try { this.getResponse().getWriter().println(json.toString()); } catch (IOException e) { e.printStackTrace(); } } /** * 查看详细信息 */ public String uploadFileView() throws Exception{ try { if((null != caseCl)&&(null != caseCl.getId())) { caseCl = caseInfoService.getCaseClById(caseCl.getId()); if(caseCl.getLinkId() != null && !"".equals(caseCl.getLinkId())) { Map map = new HashMap(); map.put("linkId",caseCl.getLinkId()); map.put("mkType", "ajxx"); map.put("picType","ajclfj"); picList = photoPicService.findPicPath(map);//获取执法文书材料 } else { String linkId = java.util.UUID.randomUUID().toString().replace("-", ""); caseCl.setLinkId(linkId); } } else { String linkId = java.util.UUID.randomUUID().toString().replace("-", ""); caseCl.setLinkId(linkId); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return VIEW; } /** * 初始化修改信息 */ public String uploadFileInitEdit() throws Exception{ uploadFileView(); return EDIT; } /** * 保存信息(包括新增和修改) */ public String saveUploadFile() throws Exception{ FileInputStream in = null; try { //设置Blob字段 setBlobField(in); } finally { if (null != in) { try { in.close(); } catch (Exception ex) { } } } if ("add".equalsIgnoreCase(this.flag)){ caseCl.setDeptId(this.getLoginUserDepartmentId()); caseCl.setDelFlag(0); caseInfoService.saveCaseCl(caseCl); }else{ caseInfoService.updateCaseCl(caseCl); } return RELOAD; } /** * 删除信息 */ public String deleteUploadFile() throws Exception{ try{ caseInfoService.deleteCaseClWithFlag(ids); this.getResponse().getWriter().println("{\"result\":true}"); }catch(Exception e){ this.getResponse().getWriter().println("{\"result\":false}"); } return null; } public String initUploadZjlb() { caseZj.setCaseId(caseInfo.getId()); loginUserId = this.getLoginUser().getId(); return SUCCESS; } public void uploadZjlbList() { Map<String, Object> paraMap = new HashMap<String, Object>(); if(pagination==null) pagination = new Pagination(this.getRequest()); if(null != caseZj){ //设置查询条件,开发人员可以在此增加过滤条件 if ((null != caseZj.getCaseId()) && (0 < caseZj.getCaseId().trim().length())){ paraMap.put("caseId", caseZj.getCaseId().trim() ); } if ((null != caseZj.getZjContent()) && (0 < caseZj.getZjContent().trim().length())){ paraMap.put("zjContent", "%" + caseZj.getZjContent().trim()+ "%" ); } } JsonConfig config = new JsonConfig(); config.registerJsonValueProcessor(java.util.Date.class,new DateJsonValueProcessor()); Map<String, String> codeMap = new HashMap<String, String>(); //此处添加需要转换的一维代码,key是一维代码在数据对象中的属性名,value是一维代码的codeId config.registerJsonValueProcessor(String.class,new CodeJsonValueProcessor(codeMap)); final String filter = "id|zjContent|createUserID|"; if (filter != null && filter.length() > 1) { config.setJsonPropertyFilter(new PropertyFilter() { public boolean apply(Object source, String name, Object value) { if (filter.indexOf(name + "|") != -1) return false; else return true; } }); } pagination = caseInfoService.findCaseZjByPage(pagination, paraMap); convObjectToJson(pagination, config); } public void zwtzjlblist() { Map<String, Object> paraMap = new HashMap<String, Object>(); if(pagination==null) pagination = new Pagination(this.getRequest()); if(null != caseZj){ //设置查询条件,开发人员可以在此增加过滤条件 if ((null != caseZj.getCaseId()) && (0 < caseZj.getCaseId().trim().length())){ paraMap.put("caseId", caseZj.getCaseId().trim() ); } if ((null != caseZj.getZjContent()) && (0 < caseZj.getZjContent().trim().length())){ paraMap.put("zjContent", "%" + caseZj.getZjContent().trim()+ "%" ); } } JsonConfig config = new JsonConfig(); config.registerJsonValueProcessor(java.util.Date.class,new DateJsonValueProcessor()); Map<String, String> codeMap = new HashMap<String, String>(); //此处添加需要转换的一维代码,key是一维代码在数据对象中的属性名,value是一维代码的codeId config.registerJsonValueProcessor(String.class,new CodeJsonValueProcessor(codeMap)); final String filter = "id|zjContent|createUserID|"; if (filter != null && filter.length() > 1) { config.setJsonPropertyFilter(new PropertyFilter() { public boolean apply(Object source, String name, Object value) { if (filter.indexOf(name + "|") != -1) return false; else return true; } }); } pagination.setPageNumber(pageNo); pagination.setPageSize(pageSize); pagination = caseInfoService.findCaseZjByPage(pagination, paraMap); JSONObject json=new JSONObject(); JSONArray ja = JSONArray.fromObject(pagination.getListOfObject(), config); json.put("result", ja); json.put("count", pagination.getTotalCount()); int totalPage; totalPage = (pagination.getTotalCount()%pageSize==0?pagination.getTotalCount()/pageSize:(pagination.getTotalCount()/pageSize+1)); json.put("totalPage", totalPage); json.put("pageNo", pageNo); try { this.getResponse().getWriter().println(json.toString()); } catch (IOException e) { e.printStackTrace(); } } /** * 查看详细信息 */ public String uploadZjlbView() throws Exception{ try { if((null != caseZj)&&(null != caseZj.getId())) { caseZj = caseInfoService.getCaseZjById(caseZj.getId()); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return VIEW; } /** * 初始化修改信息 */ public String uploadZjlbInitEdit() throws Exception{ uploadZjlbView(); return EDIT; } /** * 保存信息(包括新增和修改) */ public String saveUploadZjlb() throws Exception{ FileInputStream in = null; try { //设置Blob字段 setBlobField(in); } finally { if (null != in) { try { in.close(); } catch (Exception ex) { } } } if ("add".equalsIgnoreCase(this.flag)){ caseZj.setDeptId(this.getLoginUserDepartmentId()); caseZj.setDelFlag(0); caseInfoService.saveCaseZj(caseZj); }else{ caseInfoService.updateCaseZj(caseZj); } return RELOAD; } /** * 删除信息 */ public String deleteUploadZjlb() throws Exception{ try{ caseInfoService.deleteCaseZjWithFlag(ids); this.getResponse().getWriter().println("{\"result\":true}"); }catch(Exception e){ this.getResponse().getWriter().println("{\"result\":false}"); } return null; } public String ajgl() { loginUserId = this.getLoginUser().getId(); List<UserRight> list = (List<UserRight>) this.getLoginUser().getUserRoles(); flag = ""; for(UserRight ur:list) { flag += ur.getRole().getRoleCode()+ ","; } return SUCCESS; } public void zwtList() throws Exception{ Map<String, Object> paraMap = new HashMap<String, Object>(); if(pagination==null) pagination = new Pagination(this.getRequest()); if(null != caseInfo){ //设置查询条件,开发人员可以在此增加过滤条件 if ((null != caseInfo.getAreaId()) && (0 < caseInfo.getAreaId().trim().length())){ paraMap.put("areaId", caseInfo.getAreaId().trim() ); } if ((null != caseInfo.getCompanyName()) && (0 < caseInfo.getCompanyName().trim().length())){ paraMap.put("companyName", "%" + caseInfo.getCompanyName().trim() + "%"); } if ((null != caseInfo.getCaseName()) && (0 < caseInfo.getCaseName().trim().length())){ paraMap.put("caseName", "%" + caseInfo.getCaseName().trim() + "%"); } if ((null != caseInfo.getCaseSource()) && (0 < caseInfo.getCaseSource().trim().length())){ paraMap.put("caseSource", caseInfo.getCaseSource().trim()); } if ((null != caseInfo.getCaseStatus()) && (0 < caseInfo.getCaseStatus().trim().length())){ List<String> ll = new ArrayList<String>(); if("0".equals(caseInfo.getCaseStatus())) { flag = ""; List<UserRight> list = (List<UserRight>) this.getLoginUser().getUserRoles(); for(UserRight ur:list) { flag += ur.getRole().getRoleCode()+ ","; } String level = ""; //登录人为安监局领导 if(flag.contains("A02")) { level += "1"; } else { level += "0"; } //登录人为监察大队队长 if(flag.contains("A09")) { level += "1"; } else { level += "0"; } //登录人为大队队员 if(flag.contains("A10")) { level += "1"; } else { level += "0"; } //登录人为法务 if(flag.contains("A30")) { level += "1"; } else { level += "0"; } paraMap.put("level", level); paraMap.put("undertakerId", this.getLoginUser().getId()); } else { paraMap.put("caseStatus", caseInfo.getCaseStatus().trim()); } } if (null != queryCaseTimeStart){ paraMap.put("startCaseTime", queryCaseTimeStart); } if (null != queryCaseTimeEnd){ paraMap.put("endCaseTime", queryCaseTimeEnd); } } if(type != null && "1".equals(type)) { paraMap.put("userId", this.getLoginUser().getId()); } if(this.getLoginUser().getDeptCode().equals("009")) { Map map = new HashMap(); map.put("loginId", this.getLoginUser().getLoginId()); EntBaseInfo entBaseInfo = entBaseInfoService.findEntBaseInfoByMap(map); paraMap.put("companyId", entBaseInfo.getId()); } JsonConfig config = new JsonConfig(); config.registerJsonValueProcessor(java.util.Date.class,new DateJsonValueProcessor()); Map<String, String> codeMap = new HashMap<String, String>(); //此处添加需要转换的一维代码,key是一维代码在数据对象中的属性名,value是一维代码的codeId codeMap.put("caseSource", "402880fe506f9d9801506fa93b2e0008"); config.registerJsonValueProcessor(String.class,new CodeJsonValueProcessor(codeMap)); final String filter = "id|areaName|companyName|caseTime|caseName|caseSource|caseStatus|createUserID|undertakerId|ifNr|wszt|undertakerName|"; if (filter != null && filter.length() > 1) { config.setJsonPropertyFilter(new PropertyFilter() { public boolean apply(Object source, String name, Object value) { if (filter.indexOf(name + "|") != -1) return false; else return true; } }); } if(null!=searchLike&&!"".equals(searchLike)&&!"搜索企业名称或案件名称".equals(searchLike)){ paraMap.put("searchLike", "%" + searchLike.trim() + "%"); } pagination.setPageNumber(pageNo); pagination.setPageSize(pageSize); pagination = caseInfoService.findByPage(pagination, paraMap); JSONObject json=new JSONObject(); JSONArray ja = JSONArray.fromObject(pagination.getListOfObject(), config); json.put("result", ja); json.put("count", pagination.getTotalCount()); int totalPage; totalPage = (pagination.getTotalCount()%pageSize==0?pagination.getTotalCount()/pageSize:(pagination.getTotalCount()/pageSize+1)); json.put("totalPage", totalPage); json.put("pageNo", pageNo); try { this.getResponse().getWriter().println(json.toString()); } catch (IOException e) { e.printStackTrace(); } } public String getIds(){ return ids; } public void setIds(String ids){ this.ids = ids; } public Pagination getPagination(){ return pagination; } public void setPagination(Pagination pagination){ this.pagination = pagination; } public CaseInfo getCaseInfo(){ return this.caseInfo; } public void setCaseInfo(CaseInfo caseInfo){ this.caseInfo = caseInfo; } public String getFlag(){ return flag; } public void setFlag(String flag){ this.flag = flag; } public Date getQueryCaseTimeStart(){ return this.queryCaseTimeStart; } public void setQueryCaseTimeStart(Date queryCaseTimeStart){ this.queryCaseTimeStart = queryCaseTimeStart; } public Date getQueryCaseTimeEnd(){ return this.queryCaseTimeEnd; } public void setQueryCaseTimeEnd(Date queryCaseTimeEnd){ this.queryCaseTimeEnd = queryCaseTimeEnd; } public List<CheckRecord> getCheckRecords() { return checkRecords; } public void setCheckRecords(List<CheckRecord> checkRecords) { this.checkRecords = checkRecords; } public String getType() { return type; } public void setType(String type) { this.type = type; } public List<InstrumentsInfo> getWsList() { return wsList; } public void setWsList(List<InstrumentsInfo> wsList) { this.wsList = wsList; } public InstrumentsInfo getInstrumentsInfo() { return instrumentsInfo; } public void setInstrumentsInfo(InstrumentsInfo instrumentsInfo) { this.instrumentsInfo = instrumentsInfo; } public List<PhotoPic> getPicList() { return picList; } public void setPicList(List<PhotoPic> picList) { this.picList = picList; } public String changeTimeToZw(Date d) { String time = ""; if(d != null) { String day[] = sdf.format(d).split("-"); time = day[0] + "年" + day[1] + "月" + day[2] + "日"; } return time; } public List<User> getUserList() { return userList; } public void setUserList(List<User> userList) { this.userList = userList; } public CaseCl getCaseCl() { return caseCl; } public void setCaseCl(CaseCl caseCl) { this.caseCl = caseCl; } public CaseZj getCaseZj() { return caseZj; } public void setCaseZj(CaseZj caseZj) { this.caseZj = caseZj; } public List<CaseCl> getClList() { return clList; } public void setClList(List<CaseCl> clList) { this.clList = clList; } public List<CaseZj> getZjList() { return zjList; } public void setZjList(List<CaseZj> zjList) { this.zjList = zjList; } public int getPageNo() { return pageNo; } public void setPageNo(int pageNo) { this.pageNo = pageNo; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public String getSearchLike() { return searchLike; } public void setSearchLike(String searchLike) { this.searchLike = searchLike; } }
TypeScript
UTF-8
573
2.515625
3
[]
no_license
import validator from 'validator'; import { EmailValidatorAdapter } from './email-validator-adapter'; jest.mock('validator', () => ({ isEmail(): boolean { return true; } })); const makeSut = (): EmailValidatorAdapter => { return new EmailValidatorAdapter(); }; describe('EmailValidatorAdapter', () => { test('Should not validate if validator returns false', () => { const { isValid } = makeSut(); jest.spyOn(validator, 'isEmail').mockReturnValueOnce(false); const sutResponse = isValid('any_invalid_email@mail.com'); expect(sutResponse).toBe(false); }); });
TypeScript
UTF-8
1,374
2.765625
3
[]
no_license
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { length=0; password=""; isUseLetters=false; isUseNumbers=false; isUseSymbols=false; onChangeLength(event: Event){ console.log("EVENT =>",event) if(event){ const targetElement: HTMLInputElement = <HTMLInputElement> event.target; const value: number = parseInt(targetElement.value); if (!isNaN(value)) this.length=value; } } onChangeUseLetters(){ this.isUseLetters = !this.isUseLetters; } onChangeUseNumbers(){ this.isUseNumbers = !this.isUseNumbers; } onChangeUseSymbols(){ this.isUseSymbols = !this.isUseSymbols; } onButtonClick(){ const numbers ='1234567890'; const letters = 'abcdefghijklmopqrstuvwxyz'; const symbols= '!@#$%^&*()'; let validChars=""; if(this.isUseLetters){ validChars += letters; } if(this.isUseNumbers){ validChars +=numbers ; } if(this.isUseSymbols){ validChars += symbols; } let generatedPassword = ""; for (let i=0; i<=this.length;i++) { let index= Math.floor(Math.random()* validChars.length); generatedPassword += validChars[index]; } this.password=generatedPassword; } }
Python
UTF-8
2,795
3.828125
4
[]
no_license
import pytest class game: def __init__(self): self.board = [[None]*3 for i in range(3)] self.X_won = None self.O_won = None def show_state(self): for x in self.board: print(x) print("========") def place_x(self, x, y): if self.board[x][y] == None: self.board[x][y] = "X" else: raise ValueError if self.check_victory(x, y): self.x_won = True #print("X won the game") def place_o(self, x, y): if self.board[x][y] == None: self.board[x][y] = "O" else: raise ValueError if self.check_victory(x, y): self.O_won = True #print("O won the game") def check_victory(self, x, y): # check if previous move caused a win on vertical line if self.board[0][y] == self.board[1][y] == self.board[2][y]: return True # check if previous move caused a win on horizontal line if self.board[x][0] == self.board[x][1] == self.board[x][2]: return True # check if previous move was on the main diagonal and caused a win if x == y and self.board[0][0] == self.board[1][1] == self.board[2][2]: return True # check if previous move was on the secondary diagonal and caused a win if x + y == 2 and self.board[0][2] == self.board[1][1] == self.board[2][0]: return True return False def reset(self): self.__init__() game = game() def test_tictac_vertical(): global game game.reset() game.place_o(2, 2) game.place_o(1, 2) game.place_o(0, 2) assert game.O_won == True game.show_state() def test_tictac_horizontal(): global game game.reset() game.place_o(1, 0) game.place_o(1, 1) game.place_o(1, 2) assert game.O_won == True game.show_state() def test_tictac_diagonal(): global game game.reset() #test o game.place_o(0,0) game.place_o(1,1) game.place_o(2,2) assert game.O_won == True game.show_state() game.reset() #test x game.place_x(0,0) game.place_x(1,1) game.place_x(2,2) assert game.x_won == True game.show_state() game.reset() #test x game.place_x(2,0) game.place_x(1,1) game.place_x(0,2) assert game.x_won == True game.show_state() def test_same_move(): global game #repeated o with pytest.raises(ValueError): game.place_o(0,0) game.place_o(0,0) #repeated x with pytest.raises(ValueError): game.place_x(0,0) game.place_x(0,0) pass if __name__ == "__main__": test_tictac_diagonal() test_tictac_horizontal() test_tictac_vertical() pass
Python
UTF-8
421
2.640625
3
[]
no_license
import requests from bs4 import BeautifulSoup url='https://www.jumia.co.ke/apple-iphone-11-pro-max-with-facetime-256gb-midnight-green-25698946.html' headers={"User Agent":'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36'} page= requests.get( url, headers= headers) soup =BeautifulSoup(page.content,'html.parser') print(soup.prettify())
Python
UTF-8
146
2.78125
3
[ "WTFPL" ]
permissive
class User: def __init__(self, username, email, token): self.username = username self.email = email self.token = token
Python
UTF-8
615
3.09375
3
[ "MIT" ]
permissive
def insert_shift_array(lst, val): midpoint = len(lst) // 2 if len(lst) % 2 == 0: # I'm trying to get it to not change the midpoint here. Not sure if I would just be able to leave this if statement blank or not midpoint = midpoint # This section varies slightly from my whiteboarding solution because I while I was whiteboarding I didn't factor in for a list that was too short to have a midpoint. elif len(lst) % 2 != 0: midpoint += 1 first_half = lst[:midpoint:] second_half = lst[midpoint::] first_half.append(val) return first_half + second_half
Markdown
UTF-8
4,583
3.046875
3
[]
no_license
# 데이터 모델의 이해 ## 데이터 모델의 이해 ### 모델링의 정의 현실 세계를 데이터로 단순화, 명확하, 추상화 하는것 ### 모델리의 특의 1. 추상화 2. 단순화 3. 명확하 ### 모델링의 세 가지 관점 - 데이터 관점 : 업무과 어떤 데이터와 관련 있는지 - 프로세스 관점 : 업무가 실제하고 있는 일은 무엇인지 또는 무엇을 해야 하는지 - 상관 과점 (데이터 + 프로세스 ) : 일의 방법에 따라 데이터는 어떻게 영향을 받고 있는지 ### 데이터 모델이 제공하는 기능 - 가시화 - 명세화 - 구조화된 틀을 제공 - 문서화 - 다양한 관점을 제공 - 구체화 ### 진행 순서 현실세계 -> (개념 데이터 모델링 (추상적)) -> 개념적 구조 -> (논리 데이터 모델링) -> 논리적 구조 -> (물리 데이터 모델링 ( 구체적)) -> 물리 구조 ### 데이터 독립성의 필요성 지속적으로 증가하는 유지보수 비용을 절감하고 복잡도를 낮추며 중복된 데이터를 줄이기 위한 목적이 있다. 요구사항에 대한 화면과 데이터베이스 간에 독립성을 유지하기 위한 목적이 있다. ### 데이터 베이스 3단계 구조 - 외부 스키마 (사용자 관점) - 개념 스키마 (통합 관점) - 내부 스키마 (물리적 관점) ### 데이터 독립성 논리적 독립성 : 개념 스키마가 변경되어도 외부 스키마에는 영향을 미치지 않도록 지원하는 것 물리적 독립성 : 내부 스키마가 변경되어도 외부 / 개념 스키마는 영향을 받지 않도록 지원하는 것 ### 데이터 모델링 용어 - 엔티티 (Entity) : 어떤것 - 관계 (Relationship) : 어떤 것 간의 관계 - 속성 (Attribute) : 어떤 것의 성격 ### 모델리 작업 순서 1. 엔티티를 그린다. 2. 엔티티를 적절하게 배치한다. 3. 관계를 설정한다. 4. 관계명을 기술한다. 5. 관계의 참여도를 기술한다. 6. 관계의 필수 여부를 기술한다. ### 데이터 모델리의 이해관계자 데이터 모델을 사용하는 개발자들에게 중요하다. ## 엔터티 (Entity) ### 개념 업무상 필요한 어떤 것으로 주로 명사에 해당한다. 예를들어 고객을 관리한다 했을때 고객이 엔터티가 될 수 있다. ### 인스턴스 인스턴스는 데이터 하나라고 생각할 수 있다 따라서 인스턴스의 집합으로 엔터티를 나타낼 수 있다. ### 특징 - 엔터티는 식별 가능해야 한다. - 인스턴스의 집합이여야 한다.(한개만 있어서는 엔터티가 아니다) - 속성을 포함해야 한다. - 관계가 최소한 한계이상 존재해야 한다. ### 분류 유무에 따라서 - 유형 - 개념 - 사건 발생시점에 따라서 - 기본 - 중심 - 행위 명확하게 나눌 수는 없고애매한게 존재한다. ### 명명 현업 엄무에서 사용하는 용어를 사용해야 하고, 생성한 의미를 잘 포함하고 있어야 한다. 약어를 사용하지 말도록 하고 유일한 단수 명사를 사용한다. ## 속성 (Attribute) 속성은 업무에 필요한 정보로서 더이상 분리되지 않는 것이다. ### 엔터티와의 관계 - 엔터티는 여러개의 인스턴스를 갖는다. - 인스턴스는 여러개의 속성을 갖는다. - 속성은 하나의 속성값을 갖는다. ### 분류 속성은 여러 가지 기준으로 분류 될 수 있다. 특성에 따른 분류 : 1. 기본 속성 업무 분석을 통해서 얻는다. 2. 설계 속성 : 업무상의 존재하지 않지만 필요에 의해서 만든다. 3. 파생 속성 : 다른 속성으로 파생된 속성 엔터티 구성방식에 따른 분류 - PK 속성 - FK 속성 - 일반 속성 ### 도메인 각 속성이 가질 수 있는 값의 범위를 도메인이라고 한다. ## 관계 엔티티 간의 상호 연관성이라고 할 수 있다. ### 관계의 페어링 인스턴스 각각은 자신의 연관성을 가지고 있을 수 있다. 이것을 집합하여 관계를 도출하는데 인스턴스가 개별적으로 관계를 가지는 것을 페어링이라고 한다. ### 관계 읽기 1. 기준 엔터티를 한개 또는 각 으로 읽는다. 2. 대상 엔티티의 관계 참여도 즉 개수 를 읽는다. 3. 관계 선택사항과 관계명을 읽는다. ex : - 각각의 고객은 여러개의 주문을 때때로 가진다. -> 1:N 고객은 점선 - 각각의 주문은 한명의 곡객을 반드시 가진다. -> 주문 입장 N:1 실선
Swift
UTF-8
3,141
3.328125
3
[]
no_license
// // Assignment2ViewController.swift // app-practice // // Created by Felicia Hou on 7/11/18. // Copyright © 2018 Felicia Hou. All rights reserved. // import UIKit class ViewController2: UIViewController { //MARK: Properties @IBOutlet weak var noRepeatLabel: UILabel! @IBOutlet weak var noRepeatTextField: UITextField! @IBOutlet weak var removeLabel: UILabel! @IBOutlet weak var removeCharacterLabel: UILabel! @IBOutlet weak var removeCharacterTextField: UITextField! @IBOutlet weak var removeStringLabel: UILabel! @IBOutlet weak var removeStringTextField: UITextField! @IBOutlet weak var reverseLabel: UILabel! @IBOutlet weak var reverseTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func noRepeats(text :String) -> Character { let string = text var letters: [Character] = [] for x in string { letters.append(Character(String(x).lowercased())) } let countedSet = NSCountedSet(array: letters) var uniques = letters.filter {countedSet.count(for: $0) == 1} return (uniques[0]) } func removeCharacter(letter: String, text :String) -> String { let character = letter let word = text let newString = word.replacingOccurrences(of: character, with: "") let newString2 = newString.replacingOccurrences(of: character.uppercased(), with: "") let newString3 = newString2.replacingOccurrences(of: character.lowercased(), with: "" ) return (newString3) } func reverse(text :String) -> String { let normal = text var reverse = "" for character in normal { let char = "\(character)" reverse = char + reverse } return(reverse) } //MARK: Actions @IBAction func noRepeatButton(_ sender: UIButton) { if noRepeatTextField.text == "" { noRepeatLabel.text = "Please enter a valid string!" } else { let letter = noRepeats(text: noRepeatTextField.text!) noRepeatLabel.text = String(letter) } } @IBAction func removeButton(_ sender: UIButton) { if removeCharacterTextField.text! == "" || removeStringTextField.text! == "" || (removeCharacterTextField.text?.count)! > 1 { removeLabel.text = "Please enter a valid character(only one) and string!" } else { let removedWord = removeCharacter(letter: removeCharacterTextField.text!, text: removeStringTextField.text!) removeLabel.text = String(removedWord) } } @IBAction func reverseButton(_ sender: UIButton) { if reverseTextField.text == "" { reverseLabel.text = "Please enter a valid string!" } else { let reverseWord = reverse(text: reverseTextField.text!) reverseLabel.text = String(reverseWord) } } }
Java
UTF-8
5,652
1.945313
2
[]
no_license
package com.example.llh_pc.it_support.utils.Events; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.support.v7.app.AlertDialog; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.example.llh_pc.it_support.R; import com.example.llh_pc.it_support.activities.frmDK_DN; import com.example.llh_pc.it_support.activities.frmTaoMoiMK; import com.example.llh_pc.it_support.activities.frmTaoMoiMatKhau; import com.example.llh_pc.it_support.models.Account; import com.example.llh_pc.it_support.models.JsonParses.LoginParse; import com.example.llh_pc.it_support.restclients.RequestMethod; import com.example.llh_pc.it_support.restclients.Response; import com.example.llh_pc.it_support.restclients.RestClient; import com.example.llh_pc.it_support.utils.CommonFunction; import com.example.llh_pc.it_support.utils.Interfaces.Def; import com.google.gson.Gson; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by LLH-PC on 9/13/2015. */ public class eventForgotPass implements View.OnClickListener { private String url_forgotpass = Def.API_BASE_LINK + Def.API_ForgotPass + Def.API_FORMAT_JSON; private Context context; private ArrayList<View> views; public eventForgotPass(Context current, ArrayList<View> viewArrayList) { this.context = current; this.views = viewArrayList; } @Override public void onClick(View v) { try { EditText edtMai = (EditText) views.get(0); String mail = edtMai.getText().toString(); RestClient restClient = new RestClient(url_forgotpass); restClient.addBasicAuthentication(Def.API_USERNAME_VALUE, Def.API_PASSWORD_VALUE); restClient.addParam(Account.EMAIL, mail); restClient.execute(RequestMethod.POST); if(!emailValidator(edtMai.getText().toString())) { LayoutInflater li = LayoutInflater.from(context); View promptsView = li.inflate(R.layout.popup_validation, null); android.support.v7.app.AlertDialog.Builder alertDialogBuilder = new android.support.v7.app.AlertDialog.Builder(context); alertDialogBuilder.setView(promptsView); final TextView textView = (TextView) promptsView.findViewById(R.id.tvValidation); // set dialog message alertDialogBuilder.setView(promptsView); // set dialog message alertDialogBuilder.setCancelable(false); final android.support.v7.app.AlertDialog show = alertDialogBuilder.show(); Button okpopup= (Button) promptsView.findViewById(R.id.okpopup); TextView tv = (TextView)promptsView.findViewById(R.id.tvValidation); tv.setText("Email không đúng định dạng."); okpopup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { show.dismiss(); } }); }else if (restClient.getResponseCode() == Def.RESPONSE_CODE_SUCCESS) { String jsonObject = restClient.getResponse(); Gson gson = new Gson(); LoginParse getLoginJson = gson.fromJson(jsonObject, LoginParse.class); //if result from response success if (getLoginJson.getStatus().equalsIgnoreCase(Response.STATUS_SUCCESS)) { Intent intent = new Intent(context, frmTaoMoiMatKhau.class); intent.putExtra("mail",mail); context.startActivity(intent); }else { LayoutInflater li = LayoutInflater.from(context); View promptsView = li.inflate(R.layout.popup_validation, null); android.support.v7.app.AlertDialog.Builder alertDialogBuilder = new android.support.v7.app.AlertDialog.Builder(context); alertDialogBuilder.setView(promptsView); final TextView textView = (TextView) promptsView.findViewById(R.id.tvValidation); // set dialog message alertDialogBuilder.setView(promptsView); // set dialog message alertDialogBuilder.setCancelable(false); final android.support.v7.app.AlertDialog show = alertDialogBuilder.show(); Button okpopup= (Button) promptsView.findViewById(R.id.okpopup); TextView tv = (TextView)promptsView.findViewById(R.id.tvValidation); tv.setText("Email không hợp lệ hoặc chưa đăng ký."); okpopup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { show.dismiss(); } }); } } }catch (Exception ex) { } } public static boolean emailValidator(final String mailAddress) { Pattern pattern; Matcher matcher; final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; pattern = Pattern.compile(EMAIL_PATTERN); matcher = pattern.matcher(mailAddress); return matcher.matches(); } }
Java
UTF-8
447
1.976563
2
[]
no_license
package com.test.promanage.po; public class TableRate { private Integer rateid; private String ratename; public Integer getRateid() { return rateid; } public void setRateid(Integer rateid) { this.rateid = rateid; } public String getRatename() { return ratename; } public void setRatename(String ratename) { this.ratename = ratename == null ? null : ratename.trim(); } }
Python
UTF-8
7,653
3.140625
3
[]
no_license
import random from abc import ABCMeta from pathlib import Path from typing import List import matplotlib.image as mpimg import numpy as np from prrt.helper import INT_MAX from prrt.primitive import PoseR2S2, PointR2 class KDPair(object): """ K (PTG index) <=> Distance Pair """ def __init__(self, k: int, d: float): self.k = k self.d = d class Grid(metaclass=ABCMeta): """ An ixj cells grid, each cell contains a list of zero or more (k,d_min) pairs """ def __init__(self, size: float, resolution: float): self._resolution = resolution self._size = size self._half_cell_count_x = int(size / resolution) self._half_cell_count_y = self._half_cell_count_x self._cell_count_x = 2 * self._half_cell_count_x + 1 self._cell_count_y = self._cell_count_x self.cells = np.empty((self._cell_count_x, self._cell_count_y), dtype=object) def x_to_ix(self, x: float) -> int: """ Maps x position to column index in dmap :param x: x position in WS :return: column index of cell in dmap """ return int(np.floor(x / self._resolution) + self._half_cell_count_x) def y_to_iy(self, y: float) -> int: """ Maps y position to row index in dmap :param y: x position in WS :return: row index of cell in dmap """ return int(np.floor(y / self._resolution) + self._half_cell_count_y) def idx_to_x(self, idx: int) -> float: """ Map grid cell index to x position :param idx: column index in dmap :return: x position in WS """ return idx * self._resolution - self._size def idx_to_y(self, idy: int) -> float: """ Map grid cell index to x position :param idy: column index in dmap :return: y position in WS """ return idy * self._resolution - self._size def cell_by_pos(self, pos: PointR2) -> List[KDPair]: ix = self.x_to_ix(pos.x) iy = self.y_to_iy(pos.y) if ix >= self._cell_count_x or iy >= self._cell_count_y: return None if ix < 0 or iy < 0: return None return self.cells[ix][iy] @property def cell_count_x(self): return self._cell_count_x @property def cell_count_y(self): return self._cell_count_y class ObstacleGrid(Grid): def update_cell(self, ix: int, iy: int, k: int, d: float): # if this is the first entry create a new pair and return if self.cells[ix][iy] is None: self.cells[ix][iy] = [KDPair(k, d)] return # Cell already has an entry or more. # check if one exist for the same k for k_d_pair in self.cells[ix][iy]: if k_d_pair.k == k: k_d_pair.d = min(k_d_pair.d, d) return # The entry is new for the given k self.cells[ix][iy].append(KDPair(k, d)) class CPointsGrid(Grid): ''' CPointsGrid is a data structure used to speed up the retrieval of cpoint at a given location. It holds information about the max and min alpha that causes the vehicle to reach this point. Similarly, it keeps track of the max abd min index of cpoint in a given trajectory. The data will be later used to narrow down search operation for collision detection. ''' def update_cell(self, ix: int, iy: int, k: int, n: int): if ix < 0 or ix >= self.cell_count_x or iy < 0 or iy >= self.cell_count_y: return if self.cells[ix][iy] is None: self.cells[ix][iy] = (INT_MAX, INT_MAX, 0, 0) k_min, n_min, k_max, n_max = self.cells[ix][iy] k_min = min(k_min, k) n_min = min(n_min, n) k_max = max(k_max, k) n_max = max(n_max, n) self.cells[ix][iy] = (k_min, n_min, k_max, n_max) def cell_by_idx(self, ix: int, iy: int): if 0 <= ix < self.cell_count_x and 0 <= iy < self.cell_count_y: return self.cells[ix][iy] return None class WorldGrid(object): """ Holds obstacle data for world environment """ def __init__(self, map_file: str, width: float, height: float): file_path = Path(map_file) assert file_path.exists(), FileExistsError self.map_32bit = mpimg.imread(map_file) self.min_ix = 0 self.min_iy = 0 self.max_ix = self.map_32bit.shape[1] - 1 self.max_iy = self.map_32bit.shape[0] - 1 self.iwidth = self.max_ix - self.min_ix + 1 self.iheight = self.max_iy - self.min_iy + 1 self.width = width self.height = height self.x_resolution = self.width / self.iwidth self.y_resolution = self.height / self.iheight map8bit = (np.dot(self.map_32bit[..., :3], [1, 1, 1])) self.omap = (map8bit < 1.5) self._obstacle_buffer = [] # type: List[PointR2] def x_to_ix(self, x: float) -> int: """ Maps x position to column index in dmap :param x: x position in WS :return: column index of cell in dmap """ return int(np.floor(x / self.x_resolution)) def y_to_iy(self, y: float) -> int: """ Maps y position to row index in dmap :param y: x position in WS :return: row index of cell in dmap """ return int(np.floor(y / self.y_resolution)) def idx_to_x(self, idx: int) -> float: """ Map grid cell index to x position :param idx: column index in dmap :return: x position in WS """ return idx * self.x_resolution def idx_to_y(self, idy: int) -> float: """ Map grid cell index to x position :param idy: column index in dmap :return: y position in WS """ return idy * self.y_resolution def get_random_pose(self, bias_pose: PoseR2S2 = None, bias=0.05): if bias_pose is not None: rand = random.uniform(0, 1) if rand <= bias: return bias_pose.copy() x = random.uniform(0, self.width) y = random.uniform(0, self.height) theta = random.uniform(-np.pi, np.pi) return PoseR2S2(x, y, theta) def build_obstacle_buffer(self): obstacles = [] for ix in range(self.iwidth): for iy in range(self.iheight): if self.omap[iy][ix]: x = self.idx_to_x(ix) y = self.idx_to_y(iy) # self._obstacle_buffer.append(PointR2(x, y)) obstacles.extend([x, y]) self._obstacle_buffer = np.reshape(obstacles, newshape=(len(obstacles) // 2, 2)).T def transform_point_cloud(self, ref_pose: PoseR2S2, max_dist): inv_pose_x = -ref_pose.x * np.cos(ref_pose.theta) - ref_pose.y * np.sin(ref_pose.theta) inv_pose_y = ref_pose.x * np.sin(ref_pose.theta) - ref_pose.y * np.cos(ref_pose.theta) inv_pose_theta = - ref_pose.theta inv_pose = np.array([[inv_pose_x], [inv_pose_y], [inv_pose_theta]]) # First get a list of obstacles within range obstacles_diff = self._obstacle_buffer - np.array([[ref_pose.x], [ref_pose.y]]) obstacles_in_range = self._obstacle_buffer[:, (np.absolute(obstacles_diff[0, :]) < max_dist) & ( np.absolute(obstacles_diff[1, :]) < max_dist)] R = np.array( [[np.cos(inv_pose_theta), -np.sin(inv_pose_theta)], [np.sin(inv_pose_theta), np.cos(inv_pose_theta)]]) obstacles_rel = inv_pose[0:2] + R.dot(obstacles_in_range) return obstacles_rel
PHP
UTF-8
3,467
2.625
3
[]
no_license
<?php use Silk\Post\PostTypeBuilder; class PostTypeBuilderTest extends WP_UnitTestCase { use PostTypeAssertions; /** * @test */ function it_can_be_constructed_with_a_slug() { new PostTypeBuilder('some-type'); } /** * @test */ function it_has_a_named_constructor_for_creating_a_new_instance() { $this->assertInstanceOf(PostTypeBuilder::class, PostTypeBuilder::make('new-type')); } /** * @test */ function it_can_register_the_post_type() { $this->assertPostTypeNotExists('some-post-type'); $object = PostTypeBuilder::make('some-post-type')->register()->object(); $this->assertSame($object, get_post_type_object('some-post-type')); $this->assertPostTypeExists('some-post-type'); } /** * @test * @expectedException Silk\Post\Exception\InvalidPostTypeNameException */ function it_blows_up_if_the_post_type_slug_is_too_long() { PostTypeBuilder::make('twenty-character-limit'); } /** * @test * @expectedException Silk\Post\Exception\InvalidPostTypeNameException */ function it_blows_up_if_the_post_type_slug_is_too_short() { PostTypeBuilder::make(''); } /** * @test */ function it_accepts_an_array_or_parameters_for_supported_features() { PostTypeBuilder::make('bread')->supports(['flour', 'water'])->register(); $this->assertTrue(post_type_supports('bread', 'flour')); $this->assertTrue(post_type_supports('bread', 'water')); PostTypeBuilder::make('butter')->supports('bread', 'spreading')->register(); $this->assertTrue(post_type_supports('butter', 'bread')); $this->assertTrue(post_type_supports('butter', 'spreading')); } /** * @test */ function it_can_get_and_set_arbitrary_values_for_the_registration_arguments() { $type = PostTypeBuilder::make('stuff') ->set('mood', 'happy') ->register(); $object = get_post_type_object('stuff'); $this->assertSame('happy', $object->mood); } /** * @test */ function it_has_dedicated_methods_for_public_visibility() { $public = PostTypeBuilder::make('a-public-type')->open(); $this->assertTrue($public->get('public')); $private = PostTypeBuilder::make('a-private-type')->closed(); $this->assertFalse($private->get('public')); } /** * @test */ function it_has_dedicated_methods_for_user_interface() { $ui = PostTypeBuilder::make('ui-having')->withUI(); $this->assertTrue($ui->get('show_ui')); $no_ui = PostTypeBuilder::make('no-ui')->noUI(); $this->assertFalse($no_ui->get('show_ui')); } /** * @test */ function it_has_methods_for_setting_the_labels() { $book = PostTypeBuilder::make('book') ->oneIs('Book') ->manyAre('Books'); $this->assertSame('Book', $book->one); $this->assertSame('Books', $book->many); } /** * @test */ function it_makes_the_slug_available_as_a_read_only_property() { $this->assertSame('book', PostTypeBuilder::make('book')->slug); } /** * @test */ function it_returns_null_for_non_existent_properties() { $this->assertNull(PostTypeBuilder::make('book')->nonExistentProperty); } }
PHP
UTF-8
14,827
2.671875
3
[]
no_license
<?php require_once('Connections/unique.php'); ?> <?php $i=0; $error=array(); $message=''; ?> <?php if (!isset($_SESSION)) { session_start(); } $MM_authorizedUsers = "3"; $MM_donotCheckaccess = "false"; // *** Restrict Access To Page: Grant or deny access to this page function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { // For security, start by assuming the visitor is NOT authorized. $isValid = False; // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. // Therefore, we know that a user is NOT logged in if that Session variable is blank. if (!empty($UserName)) { // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. // Parse the strings into arrays. $arrUsers = Explode(",", $strUsers); $arrGroups = Explode(",", $strGroups); if (in_array($UserName, $arrUsers)) { $isValid = true; } // Or, you may restrict access to only certain users based on their username. if (in_array($UserGroup, $arrGroups)) { $isValid = true; } if (($strUsers == "") && false) { $isValid = true; } } return $isValid; } $MM_restrictGoTo = "admin.php"; if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { $MM_qsChar = "?"; $MM_referrer = $_SERVER['PHP_SELF']; if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&"; if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) $MM_referrer .= "?" . $QUERY_STRING; $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer); header("Location: ". $MM_restrictGoTo); exit; } ?> <?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $currentPage = $_SERVER["PHP_SELF"]; $maxRows_students = 30; $pageNum_students = 0; if (isset($_GET['pageNum_students'])) { $pageNum_students = $_GET['pageNum_students']; } $startRow_students = $pageNum_students * $maxRows_students; mysql_select_db($database_unique, $unique); $query_students = "SELECT student_info.student_id,CONCAT_WS(' ', student_info.student_Lname, student_info.student_Fname) AS name, `class`.class_name, student_info.sex FROM student_info, `class` WHERE student_info.`class` = `class`.class_id ORDER BY `class`.class_name, student_info.student_Lname"; $query_limit_students = sprintf("%s LIMIT %d, %d", $query_students, $startRow_students, $maxRows_students); $students = mysql_query($query_limit_students, $unique) or die(mysql_error()); $row_students = mysql_fetch_assoc($students); if (isset($_GET['totalRows_students'])) { $totalRows_students = $_GET['totalRows_students']; } else { $all_students = mysql_query($query_students); $totalRows_students = mysql_num_rows($all_students); } $totalPages_students = ceil($totalRows_students/$maxRows_students)-1; $queryString_students = ""; if (!empty($_SERVER['QUERY_STRING'])) { $params = explode("&", $_SERVER['QUERY_STRING']); $newParams = array(); foreach ($params as $param) { if (stristr($param, "pageNum_students") == false && stristr($param, "totalRows_students") == false) { array_push($newParams, $param); } } if (count($newParams) != 0) { $queryString_students = "&" . htmlentities(implode("&", $newParams)); } } $queryString_students = sprintf("&totalRows_students=%d%s", $totalRows_students, $queryString_students); if(isset($_POST['Add'])){ foreach ($_POST as $item){ $item=trim($item); } } if (empty($_POST['fname'])){ array_push($error,'fname'); } if (empty($_POST['lname'])){ array_push($error,'lname'); } if(empty($error)){ if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "assign_subject")) { $insertSQL = sprintf("INSERT INTO parent (parent_id, parent_fname, parent_lname, profession, office_address, home_address, office_phone, home_phone, mobile_phone, sex, origin, religion) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", GetSQLValueString($_POST['id'], "text"), GetSQLValueString($_POST['fname'], "text"), GetSQLValueString($_POST['lname'], "text"), GetSQLValueString($_POST['profession'], "text"), GetSQLValueString($_POST['o_address'], "text"), GetSQLValueString($_POST['h_address'], "text"), GetSQLValueString($_POST['o_number'], "text"), GetSQLValueString($_POST['h_number'], "text"), GetSQLValueString($_POST['m_number'], "text"), GetSQLValueString($_POST['sex'], "text"), GetSQLValueString($_POST['origin'], "text"), GetSQLValueString($_POST['religion'], "text")); mysql_select_db($database_unique, $unique); $Result1 = mysql_query($insertSQL, $unique); } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Welcome to Unique Blossom Schools, Abuja</title> <!-- Slider script --> <link rel="stylesheet" href="nivo-slider.css" type="text/css" media="screen" /> <!-- <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.nin.js" type="text/javascript"></script> --> <script type="text/javascript" src="demo/scripts/jquery-1.6.1.min.js"></script> <script src="jquery.nivo.slider.pack.js" type="text/javascript"> </script> <link rel="stylesheet" href="themes/default/default.css" type="text/css" media="screen" /> <link rel="stylesheet" href="themes/pascal/pascal.css" type="text/css" media="screen" /> <link rel="stylesheet" href="themes/orman/orman.css" type="text/css" media="screen" /> <link rel="stylesheet" href="nivo-slider.css" type="text/css" media="screen" /> <!-- end of slider script --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta name="description" content="Unique Blossom Schools, Abuja; Creche, Prenursery, Nursery, Primary" /> <meta name="keywords" content="creche, Nursery, prenursery, reception, primary, schoool, school in abuja, primary school in abuja, nursery school, students, unique blossom" /> <link rel="stylesheet" href="style.css" type="text/css" /> <script src="SpryAssets/SpryMenuBar.js" type="text/javascript"></script> <link href="SpryAssets/SpryMenuBarHorizontal.css" rel="stylesheet" type="text/css" /> <link rel="shortcut icon" href="favicon.ico" /> </head> <body> <div id="content"> <?php include("includes/header.php"); ?> <div class="clearnav" > <?php include("includes/nav.php"); ?> </div> <?php include('includes/side_admin.php'); ?> <div id="right"> <div id="long_txt_pix"> <h1>Students Data </h1> <table width="95%" border="1"> <tr> <td align="right"><form id="form1" method="get" action="search_result_student.php"> <input name="name" type="text" class="searchfield" id="name" /> <input name="submit" type="submit" class="searchbutton" id="submit" value="Search Student" /> </form></td> </tr> </table> <p>&nbsp;</p> <form name="assign_subject" id="parent_data" method="POST"> <table width="95%" border="0" cellpadding="6"> <tr> <td colspan="5" align="left"><table width="100%" border="0"> <tr> <td width="83%"><table width="99%" border="0" cellpadding="6"> <tr> <td height="32" colspan="4" align="center"><p> <?php if(isset($_GET['message'])){ switch ($_GET['message']){ case "update": ?> <span class='success'>Data Successfully Update</span> <?php break; case "insert": ?> <span class='success'>Data Successfully Inserted</span>. <strong><a href="enter_students.php">Add Another</a></strong> <?php break; } }?> </p></td> <td height="32" align="center"><a href="reports/report_student.php" target="_blank">Print List</a></td> </tr> <tr> <td colspan="5" align="left">&nbsp;<strong>Showing Records <?php echo ($startRow_students + 1) ?> to <?php echo min($startRow_students + $maxRows_students, $totalRows_students) ?> of <?php echo $totalRows_students ?></strong></td> </tr> <tr> <td colspan="5" align="left"><table width="100%" border="0"> <tr> <td width="6%"><?php if ($pageNum_students > 0) { // Show if not first page ?> <a href="<?php printf("%s?pageNum_students=%d%s", $currentPage, 0, $queryString_students); ?>">First</a> <?php } // Show if not first page ?></td> <td width="83%"><?php if ($pageNum_students > 0) { // Show if not first page ?> <a href="<?php printf("%s?pageNum_students=%d%s", $currentPage, max(0, $pageNum_students - 1), $queryString_students); ?>">Previous</a> <?php } // Show if not first page ?></td> <td width="6%"><?php if ($pageNum_students < $totalPages_students) { // Show if not last page ?> <a href="<?php printf("%s?pageNum_students=%d%s", $currentPage, min($totalPages_students, $pageNum_students + 1), $queryString_students); ?>">Next</a> <?php } // Show if not last page ?></td> <td width="5%"><?php if ($pageNum_students < $totalPages_students) { // Show if not last page ?> <a href="<?php printf("%s?pageNum_students=%d%s", $currentPage, $totalPages_students, $queryString_students); ?>">Last</a> <?php } // Show if not last page ?></td> </tr> </table></td> </tr> <tr class="hlite"> <td width="23%" align="left"><h2>Student's ID</h2></td> <td width="25%" align="left"><h2>Student's Names</h2></td> <td width="23%" align="left"><h2>CLASS</h2></td> <td width="15%" align="left"><h2>SEX</h2></td> <td width="14%" align="left"><h2>ACTION</h2></td> </tr> <?php $count=0; ?> <?php do { ?> <tr <?php if ($count++ %2) echo 'class="hlite"'; ?>> <td><p><?php echo $row_students['student_id']; ?></p></td> <td><p><?php echo $row_students['name']; ?></p></td> <td><?php echo $row_students['class_name']; ?></td> <td><?php echo ucwords($row_students['sex']); ?></td> <td><p><a href="view_details.php?id=<?php echo $row_students['student_id']; ?>&amp;cat=student">Details</a>|<a href="edit_student_details.php?id=<?php echo $row_students['student_id']; ?>&amp;cat=student">Edit</a>|<a href="delete_student.php?cat=student&amp;id=<?php echo $row_students['student_id']; ?>">Delete</a>|</p></td> </tr> <?php } while ($row_students = mysql_fetch_assoc($students)); ?> <tr> <td height="73" colspan="5"><table width="100%" border="0"> <tr> <td width="6%"><?php if ($pageNum_students > 0) { // Show if not first page ?> <a href="<?php printf("%s?pageNum_students=%d%s", $currentPage, 0, $queryString_students); ?>">First</a> <?php } // Show if not first page ?></td> <td width="83%"><?php if ($pageNum_students > 0) { // Show if not first page ?> <a href="<?php printf("%s?pageNum_students=%d%s", $currentPage, max(0, $pageNum_students - 1), $queryString_students); ?>">Previous</a> <?php } // Show if not first page ?></td> <td width="6%"><?php if ($pageNum_students < $totalPages_students) { // Show if not last page ?> <a href="<?php printf("%s?pageNum_students=%d%s", $currentPage, min($totalPages_students, $pageNum_students + 1), $queryString_students); ?>">Next</a> <?php } // Show if not last page ?></td> <td width="5%"><?php if ($pageNum_students < $totalPages_students) { // Show if not last page ?> <a href="<?php printf("%s?pageNum_students=%d%s", $currentPage, $totalPages_students, $queryString_students); ?>">Last</a> <?php } // Show if not last page ?></td> </tr> </table></td> </tr> </table></td> </tr> </table></td> </tr> </table> <p>&nbsp;</p> </form> <p>&nbsp;</p> </div> </div> <?php include("includes/footer.php"); ?> </div> <script type="text/javascript"> $(window).load(function() { $('#slider').nivoSlider(); }); </script> </body> </html> <?php mysql_free_result($students); ?>
Java
UTF-8
1,155
1.875
2
[]
no_license
package awd.cloud.suppers.interfaces.service.kss.imp; import awd.cloud.suppers.interfaces.api.KssBaseServersApi; import awd.cloud.suppers.interfaces.service.kss.SwqrService; import awd.cloud.suppers.interfaces.utils.PagerResult; import awd.cloud.suppers.interfaces.utils.QueryParam; import awd.cloud.suppers.interfaces.utils.ResponseMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Map; @Service("swqrService") public class SimpleSwqrService implements SwqrService { @Autowired private KssBaseServersApi kssBaseServersApi; @Override public ResponseMessage<PagerResult<Map<String, Object>>> getSwqr(Map<String, Object> map) { QueryParam queryParam = new QueryParam(); return kssBaseServersApi.getSwqr(queryParam); } @Override public ResponseMessage<String> saveSwqr(Map<String, Object> map) { return kssBaseServersApi.saveSwqr(map); } @Override public ResponseMessage<String> updateSwqrById(String id, Map<String, Object> map) { return kssBaseServersApi.updateSwqrById(id,map); } }
C++
UTF-8
1,570
3.390625
3
[]
no_license
/** * @file 24_ReverseList.cpp * @brief Sample project head file * @detils The header file details * @auther Auther * @version 1.0.0.1 * @date 2018年08月08日 星期三 09时51分20秒 */ #include <iostream> #include <cstdio> #include "ListNode.h" using namespace std; void ReverseList_Error_Gai(ListNode **head) { if (head == NULL || *head == NULL || (*head) -> next == NULL) return ; int index = 0; ListNode *pNode = *head; ListNode *pTemp = (*head) -> next; ListNode *pNext = (*head) -> next -> next; while (pNext) { pTemp -> next = pNode; if (pNode == *head) pNode -> next = NULL; pNode = pTemp; pTemp = pNext; pNext = pTemp -> next; } pTemp -> next = pNode; if (pNode == *head) pNode -> next = NULL; *head = pTemp; return ; } ListNode * ReverseList(ListNode *head) { ListNode *pReHead = NULL; ListNode *pNode = head; ListNode *pPre = NULL; while (pNode) { ListNode *pNext = pNode -> next; if (pNext == NULL) pReHead = pNode; pNode -> next = pPre; pPre = pNode; pNode = pNext; } return pReHead; } void output(ListNode *head) { ListNode *pNode = head; printf("["); while (pNode) { printf("%d ", pNode -> val); pNode = pNode -> next; } printf("]\n"); } int main() { ListNode *head = NULL, *p; int num[10] = {1, 1, 1, 3, 5, 6, 9, 9, 9, 9}; for (int i = 0; i < 10; i++) { ListNode *pNode = new ListNode(num[i]); if (head == NULL) head = pNode, p = pNode; else p->next = pNode, p = pNode; } output(head); // ListNode *pNode = ReverseList(head); ReverseList_Error_Gai(&head); output(head); }
C++
UTF-8
1,746
2.578125
3
[]
no_license
/*------------------------------------------------------------------------------ * Copyright © Portal Instruments – All Rights Reserved * Proprietary and Confidential * Copying of this file or use of code contained in this file via any * medium is strictly prohibited unless prior written permission is obtained * from Portal Instruments, Inc. * Created by Joseph McLaughlin 2017 ------------------------------------------------------------------------------*/ #ifndef INCLUDE_RTOS_TASK_INTERFACE_H_ #define INCLUDE_RTOS_TASK_INTERFACE_H_ #include <system_error> // NOLINT(build/c++11) //----------------------------------------------------------------------------- enum class RTOSTaskError { RTOSTASK_NOT_STARTED = 1, RTOSTASK_NOT_RUNNING = 2, RTOSTASK_TIMED_OUT = 3, RTOSTASK_INVALID_EVENT_BIT = 4, RTOSTASK_EXIT = 5, }; namespace std { template <> struct is_error_code_enum<RTOSTaskError> : public true_type {}; } std::error_code make_error_code(RTOSTaskError error); std::error_condition make_error_condition(RTOSTaskError error); //----------------------------------------------------------------------------- class IRTOSTask { public: virtual ~IRTOSTask() {} virtual std::error_code Start() const = 0; virtual std::error_code Suspend() const = 0; virtual std::error_code Resume() const = 0; }; class IRTOSRunningTask { public: virtual std::error_code Delay(float seconds) const = 0; virtual std::error_code WaitForNotification(float timeout_seconds) const = 0; virtual bool IsEventBitPending(uint32_t event_bit) const = 0; }; class IRTOSNotifyTask { public: virtual std::error_code SendNotification(uint32_t event_bit) const = 0; }; #endif // INCLUDE_RTOS_TASK_INTERFACE_H_
Python
UTF-8
3,960
3.84375
4
[]
no_license
import random from pokemon import * NOMES = ["João", "José", "Pedro", "Maria", "Mathes", "Matias", "Morais", "Mauro", "Marcio", "Beto", "Breno", "Brenda"] POKEMONS = [ PokemonFogo("Charmander"), PokemonFogo("Charmilion"), PokemonFogo("Charizard"), PokemonEletrico("Pikachu"), PokemonEletrico("Raichu"), PokemonAgua("Squirtle"), PokemonAgua("Wartotle"), ] class Pessoa: def __init__(self, nome=None, pokemons=[], dinheiro=100): if nome: self.nome = nome else: self.nome = random.choice(NOMES) self.pokemons = pokemons self.dinheiro = dinheiro def __str__(self): return self.nome def mostrar_pokemons(self): if self.pokemons: print("Pokemons de {}!".format(self)) for index, pokemon in enumerate(self.pokemons): print(f"{index} - {pokemon}") else: print("{} não tem pokemons". format(self)) def escolher_pokemon(self): if self.pokemons: pokemon_escolhido = random.choice(self.pokemons) print(f"{self} escolheu {pokemon_escolhido}!") return pokemon_escolhido else: print("Esse player não tem Pokemons.") def mostrar_dinheiro(self): print(f"Você tem ${self.dinheiro}!") def ganhar_dinheiro(self, quantidade): self.dinheiro = self.dinheiro + quantidade print(f"Você ganhou {quantidade}!") self.mostrar_dinheiro() def batalhar(self, pessoa): print(f"{self} Iniciou uma batalha com {pessoa}!") pessoa.mostrar_pokemons() pokemon_inimigo = pessoa.escolher_pokemon() pokemon = self.escolher_pokemon() if pokemon and pokemon_inimigo: while True: vitoria = pokemon.atacar(pokemon_inimigo) if vitoria: print(f"{self} Ganhou a batalha!") self.ganhar_dinheiro(pokemon_inimigo.level * 100) break vitoria_inimiga = pokemon_inimigo.atacar(pokemon) if vitoria_inimiga: print(f"{pessoa} Ganhou a batalha!") break else: print("Falha inesperada:(") class Player(Pessoa): tipo = "player" def capturar(self, pokemon): self.pokemons.append(pokemon) print("{} Capturou {}".format(self, pokemon)) def escolher_pokemon(self): self.mostrar_pokemons() if self.pokemons: while True: escolha = input("Escolha seu Pokemon: ") try: escolha = int(escolha) pokemon_escolhido = self.pokemons[escolha] print(f"{pokemon_escolhido} Eu escolho você!!!") return pokemon_escolhido except: print("Escolha invalida") else: print("Você não tem Pokemons.") def explorar(self): if random.random() <= 0.3: pokemon = random.choice(POKEMONS) print(f"Um {pokemon} selvagem apareceu!") escolha = input(f"Deseja tentar capturar {pokemon}? (s/n): ") if escolha == 's': if random.random() >= 0.5: self.capturar(pokemon) else: print(f"O {pokemon} escapou.") else: print(f"...") else: print("Nenhum Pokemon selvagem foi encontrado :(") class Inimigo(Pessoa): tipo = "inimigo" def __init__(self, nome=None, pokemons=None): if not pokemons: pokemons_aleatorios = [] for i in range(random.randint(1, 6)): pokemons_aleatorios.append(random.choice(POKEMONS)) super().__init__(nome=nome, pokemons=pokemons_aleatorios) else: super().__init__(nome=nome, pokemons=pokemons)
Markdown
UTF-8
885
3.125
3
[]
no_license
**线程封闭**:仅在单先内部访问数据,就不需要同步,即使被封闭对象不是线程安全的。如局部变量、ThreadLocal类 线程封闭技术:栈封闭、ThreadLocal类 **栈封闭** 基本类型局部变量:由于任何方法都无法或者对基本类型的引用,因此基本类型的局部变量始终封闭在线程内; 如果没有发生逸出,那么引用对象也在线程内部 **ThreadLocal** 使线程中某个值与保持值的对象关联起来。提供get\set方法,为每个使用该变量的线程都存有一份独立的副本。 通常用于放置对可变的单实例变量或全局变量进行共享。例如jdbc连接池; 使用场景“当某个频繁执行的操作需要一个临时对象,而同时又希望避免在每次执行时都会重新分配该临时对象。 可以将ThreadLocal<T> 视为Map<Thread,T>
C#
UTF-8
1,098
2.75
3
[]
no_license
namespace Tinyweather { using System; using System.Collections.Generic; using System.Linq; using System.Text; public class ForecastDay { private String _day; private String _date; private Int16 _low; private Int16 _high; private String _description; private Int16 _code; public String Day { get { return _day; } set { _day = value; } } public String Date { get { return _date; } set { _date = value; } } public Int16 Low { get { return _low; } set { _low = value; } } public Int16 High { get { return _high; } set { _high = value; } } public String Description { get { return _description; } set { _description = value; } } public Int16 Code { get { return _code; } set { _code = value; } } public ForecastDay() { } } }
PHP
UTF-8
2,295
2.71875
3
[]
no_license
<?php namespace App\Converter; use App\Repository\NewsRepository; use App\Repository\TagRepository; use App\Repository\UserRepository; use App\ValueObject\Filter; class FilterConverter implements Converter { /** @var NewsRepository */ protected $newsRepository; /** @var TagRepository */ protected $tagRepository; /** @var UserRepository */ private $userRepository; /** * FilterConverter constructor. * @param NewsRepository $newsRepository * @param TagRepository $tagRepository * @param UserRepository $userRepository */ public function __construct(NewsRepository $newsRepository, TagRepository $tagRepository, UserRepository $userRepository) { $this->newsRepository = $newsRepository; $this->tagRepository = $tagRepository; $this->userRepository = $userRepository; } /** * @param array $entity * * @return Filter * * @throws \Exception */ public function convert($entity) { [ 'id' => $id, 'dates' => $dates, 'author' => $author, 'tags' => $tags ] = array_merge( ['id' => null, 'dates' => [], 'author' => null, 'tags' => []], json_decode($entity, true) ?? [] ); $news = null; if (null !== $id) { $news = $this->newsRepository->find($id); } $dateObject[0] = null; $dateObject[1] = null; if (isset($dates[0]) && isset($dates[1])) { $dateObject = [ new \DateTime($dates[0]), new \DateTime($dates[1]), ]; usort($dateObject, function(\DateTime $date1, \DateTime $date2) { return ($date1->format('U') - $date2->format('U')) > 0; }); } $authorEntity = null; if (null !== $author) { $authorEntity = $this->userRepository->findOneByUsername($author); } $tagsEntity = []; if (!empty($tags)) { $tagsEntity = array_map(function($tag) { return $this->tagRepository->findOneBySlug($tag); }, $tags); } return new Filter($news, $dateObject[0], $dateObject[1], $authorEntity, $tagsEntity); } }
Java
UTF-8
575
2.171875
2
[]
no_license
package ru.majestic.bashimreader.utils; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.text.Html; import ru.majestic.bashimreader.data.Quote; public class BufferSaver { public static final void saveInBuffer(final Context context, final Quote quote) { ClipboardManager man = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); ClipData data = ClipData.newPlainText("Quote", Html.fromHtml(quote.getContent()).toString()); man.setPrimaryClip(data); } }
Java
UTF-8
4,399
2.234375
2
[]
no_license
import java.io.IOException; import java.io.PrintWriter; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class compose extends HttpServlet { Connection con; PreparedStatement ps,ps1; ResultSet rs1; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext sc=request.getServletContext(); PrintWriter out=response.getWriter(); con=(Connection)sc.getAttribute("con"); String too=request.getParameter("to"); HttpSession session=request.getSession(); String frm=(String)session.getAttribute("na"); String s=request.getParameter("sub"); String m=request.getParameter("msg"); String b=request.getParameter("but"); RequestDispatcher rd=request.getRequestDispatcher("compose.html"); rd.include(request,response); try { if(b.equals("SAVE")) { ps1=con.prepareStatement("insert into draft(too,frm,sub,msg) values(?,?,?,?)"); ps1.setString(1,too); ps1.setString(2,frm); ps1.setString(3,s); ps1.setString(4,m); int j=ps1.executeUpdate(); if(j>0) { out.println("Mail Saved as Draft"); } else { out.println("database error"); } } else { ps1=con.prepareStatement("select uname from users where uname=?"); ps1.setString(1,too); rs1=ps1.executeQuery(); int c=0; while(rs1.next()) { c++; } if(c==0) { out.println("invalid emailid...sending failed"); } else { ps=con.prepareStatement("insert into sent(too,frm,sub,msg) values(?,?,?,?)"); ps.setString(1,too); ps.setString(2,frm); ps.setString(3,s); ps.setString(4,m); int i=ps.executeUpdate(); if(i>0) { out.println("Mail Sent"); } else { out.println("database error"); } } } }//try catch(Exception r) { System.out.println(r); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
Markdown
UTF-8
3,942
3.234375
3
[]
no_license
As I was driving to work and reflecting on my work experience thus far, I realized that I was still utilizing a problem-solving approach which I picked up during CS70, which actually revolutionized my CS70 career. I'm writing this advice from the perspective of both the student and the teacher, but also the employee and coworker. Hopefully, this will enable you to learn FROM being stuck and ask meaningful questions which don't make you feel bad for asking. (Will help at work) I'm working on a full stack web/database project in C#, Javascript, and SQL, none of which I've really worked with before. By learning to ask questions the right way, I've managed to independently solve and create different approaches to problems. # How to Learn From Being Stuck and Not Feel Bad About Asking Questions Every time someone starts solving problems in new area or concept of study, there will almost certainly come a time when he or she gets stuck. Sometimes, the student will have absolutely no idea what the proof or solution should even look like. There will seem to be an insurmountable challenge and a vaguely distant, possibly possible solution with clear way forward. (The first thing to try would be to look at solutions to similar problems and mimic them, but this is not always possible or thorough) Well, good news! That's ok, and actually one of the best learning opportunities you can experience, if responded to properly! (If you already knew how to solve the problems, why would you be in the class?) **The first thing to avoid, and the option that most humans tend towards, is the response of "I don't know what to do", or "What should I do here?".** Unfortunately, this stuck-feeling won't go away when you get a job or when you finish this class, and this type of question will, frankly, make you feel stupid for asking repeatedly. From a teacher's persective, this is also difficult to address, because we don't know exactly where you're stuck, or how to guide you in the right direction without planting the idea in your head. # TL;DR solution: Ask a Proposal Make an educated guess on a solution or a path forward, and ask "Should I try to show that ______?" or "Would ______ be a wise approach?". Ideally, your question should be 1-3 sentences, explaining a couple possible options and the reason why each one doesn't quite work. Your guess will very rarely be on point at first, but that's ok! As you formulate your answer, you'll get to mull over different approaches and issues, and possibly stumble upon the soultion! A well-thought-out questiopn will highlight what you don't understand or why your approach won't work, and eventually it will boil down to a specific issue or explanation on a specific concept. This will be enough for your teacher or boss to guide you in the right direction using YOUR problem solving abilities! So the next time you're stuck on a hypercube proof or a complex recursive problem, (*~cough towers of hanoi*), present your best guess as your question, and use that to get started in the right direction. <br /> <br /> <br /> **If you're already using this approach, good job!** Keep developing that intution! With practice, your guesses should help you get closer and closer to the solution, if you don't solve the problem along the way. This same practice of thinking it out and guessing towards a solution will help you on exams and future projects where you may have less guidance available. (Debugging is a whole new game, but similar) Fun fact: This tends to be distinguishing feature between those who enjoy studying CS and those who opt for a different path of study. Frankly, the questions "Is this right?" or "What should I do here?" are lazy; the question itself is not meaningful and conveys a sense of defeat, regardless of the effort put in. XD Good luck! Love you guys! I pray for you all every day! :D I'll see you guys soon! -Emmett Ling
Python
UTF-8
2,043
2.8125
3
[ "BSD-3-Clause" ]
permissive
import numpy as np from fnmatch import fnmatch from astropy.table import Column, Table def scale_by_distance(_grid_name, _outputs, _models, scaling_factor, distance): """Scale external model fluxes and normalization value. Parameters ---------- _grid_name : str name of grid specified _outputs : astropy table grid outputs. _models : astropy table grid models. scaling_factor : float Scaling factor to scale grids to distance. distance : distance in kpc Returns ------- _outputs : astropy table Updated astropy table with scaled vexp, and mdot. scaled_models : astropy table astropy table with sclaed fluxes """ print("Scaling model grid by distance (" + str(len(_models)) + " models)") if fnmatch(_grid_name, "grams*"): # Norm is the log normalization for plotting GRAMS _outputs["norm"] = np.log10( _outputs["norm"] * np.square(50) / np.square(distance) ) scaled_models = _models["flux_wm2"] * np.power(10, _outputs["norm"][0]) if (distance < 20) | (distance > 150): print( "\n" + "=" * 75 + "\nWARNING:\n" + "\nThis is beyond the suggested range (20-150 kpc) " + "for using the GRAMS grids.\n" + "This may result in unrealistic geometries.\n\n" + "=" * 75 ) else: # Norm is the log normalization for plotting Nanni et al. models _outputs["norm"] = np.log10(_outputs["norm"] / scaling_factor * _outputs["lum"]) scaled_models = [] for i, lum_val in enumerate(_outputs["lum"]): scaled_flux_array = np.multiply( _models["flux_wm2"][i], lum_val / scaling_factor ) scaled_models.append(scaled_flux_array) full_models = Table( (_models["wavelength_um"], Column(scaled_models, name="flux_wm2")) ) return _outputs, full_models
Java
UTF-8
375
1.632813
2
[]
no_license
package com.myke.common; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Configuration; import javax.annotation.PostConstruct; /** * user: zhangjianbin <br/> * date: 2018/2/13 11:34 */ @Slf4j @Configuration public class CommonConfig { @PostConstruct public void run() { log.info("加载 service-common依赖"); } }
C#
UTF-8
2,183
2.53125
3
[]
no_license
using UnityEngine; using UnityEngine.UI; public class ProfilePage : MonoBehaviour { public Text summaryText; public Text detailedText; Savefile playerData = SaveManager.currentSavefile; void OnEnable() { try { ShowInfo(); } catch { } } void ShowInfo() { string major1Name = playerData.major; string major2Name = playerData.secondaryMajor; string summaryStr = "요약: "; string major1Str = "전공: "; string major2Str = ""; string libArtStr = "\n교양: "; string normalStr = "\n일반선택: "; int major1Unit = 0; int major2Unit = 0; int libArtUnit = 0; int totalUnit = 0; bool is2Majored = string.IsNullOrEmpty(playerData.secondaryMajor); foreach (Subject item in playerData.succeededSubjects) { int category = (int)item.category; if (category < 2 && item.department.Equals(major1Name)) { major1Str += item.name + ", "; major1Unit += item.units; } else if (is2Majored && category < 2 && item.department.Equals(major2Name)) { major2Str += item.name + ", "; major2Unit += item.units; } else if (category > 2) { libArtStr += item.name + ", "; libArtUnit += item.units; } else { normalStr += item.name + ", "; totalUnit += item.units; } } summaryStr += "전공 - " + major1Unit.ToString() + "학점, "; if (is2Majored) summaryStr += "제2전공 - " + major2Unit.ToString() + "학점, "; summaryStr += "교양 - " + libArtUnit.ToString() + "학점, "; summaryStr += "총 " + totalUnit.ToString() + "학점"; string detailedStr = major1Str + major2Str + libArtStr + normalStr; summaryText.text = summaryStr; detailedText.text = detailedStr; } }
Shell
UTF-8
458
3.421875
3
[ "Apache-2.0" ]
permissive
#!/bin/bash . /etc/sysconfig/heat-params DOCKER_DEV=/dev/disk/by-id/virtio-${DOCKER_VOLUME:0:20} attempts=60 while [[ ! -b $DOCKER_DEV && $attempts != 0 ]]; do echo "waiting for disk $DOCKER_DEV" sleep 0.5 udevadm trigger let attempts-- done if ! [ -b $DOCKER_DEV ]; then echo "ERROR: device $DOCKER_DEV does not exist" >&2 exit 1 fi pvcreate $DOCKER_DEV vgcreate docker $DOCKER_DEV cat > /etc/sysconfig/docker-storage-setup <<EOF VG=docker EOF
Markdown
UTF-8
1,939
3.671875
4
[]
no_license
# Styling Links and Lists ## 1. Anchor Links * Links can take on all of the usual style as well as <font color="orange">_text-decoration_</font> ``` a { display: block; font-weight: bold; color: #FFFFFF; background-color: #0006CC; width: 200px; # Only works with inline and inline-block text-align: center; padding: 4px; text-decoration: none; # Removes the underline } ``` ## 2. Buttons * Many designers try to make their links look like buttons. * Be semantic, if you want a button use the `<button>` element instead `<button>Click Me!</button>`: <button>Click Me!</button> ## 3. States * Some links are blue, some are purple, etc. Why??? * a:link - a normal, unvisited link * a:visited - has been visited * a:hover - activated by mouse (touchscreens...?, not necessarily) * a:focus - activated with the keyboard * a:active - is being clicked * Hands-on * [HTML](../../codes/html/links.html) * [CSS](../../codes/css/links.css) ## 4. Precedence of Rules * a:hover MUST come after a:link and a:visited * a:active MUST come after a:hover ## 5. Styling Lists * Number of properties beyond font, margin, etc. * list-style-type * list-style-image * list-style-position * list-style ### 01. list-style-type * list-style-type * ordered lists: _lower-roman, upper-roman, decimal, decimal-leading-zero, upper-alpha, lower-alpha, hebrew, armenian, ..._ * unordered list: _Override the default marker with cirlces, discs, or squares_ * list-style-image * Use a custom image instead of traditional marker ``` ul { list-style-image: square url('icon.gif') } ``` ## Review * At this point you have learned how to write rules for the _tags_. * Embrace the many tools that are available to help you design your site. * https://chrispederick.com/work/web-developer/ * https://css3generator.com/ * Do web search for "Developer Tools"
Java
UTF-8
3,224
2.484375
2
[]
no_license
package app.localization; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import app.utilities.CommonUtilities; import app.utilities.CustomDialog; import app.utilities.RestClient; /** * Merchant list. Pulls subscribed or nearby merchant information from the * database. Need service-oriented architecture and needs three elements: * external database, web-service, mobile web-service client. * * @author Chihiro */ public class Merchants extends Activity { TextView username; TextView result; String dbResult; static int TIMEOUT_MILLISEC = 3000; List<String> listContents; ListView myListView; ArrayAdapter<String> adapter; Merchants currentThis = this; Intent intent; Bundle b; /** * Initializes the page when it is first called. */ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.merchant); listContents = new ArrayList<String>(); myListView = (ListView) findViewById(R.id.merchantList); // Save merchant information to be used in the Merchant Map page intent = new Intent(Merchants.this, MerchantMap.class); b = new Bundle(); // Get list of merchants from database getMerchants(); // Display map button Button mapButton = (Button) findViewById(R.id.mapButton); // Listening to button event mapButton.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { startActivity(intent); } }); } /** * Retrieve a list of subscribed merchants from the database. */ public void getMerchants() { String username = CommonUtilities.getUsername(Merchants.this); JSONObject jsonIn = new JSONObject(); try { jsonIn.put("userName", username); } catch (Exception e) { Log.v("Merchants", "JSON Exception"); } final JSONArray jsonArray = RestClient.connectToDatabase( CommonUtilities.NEARBYMERCHANTS_URL, jsonIn); if (jsonArray != null) { runOnUiThread(new Runnable() { @Override public void run() { try { listContents = new ArrayList<String>(jsonArray.length()); for (int i = 0; i < jsonArray.length(); i++) { listContents.add(jsonArray.getJSONObject(i) .getString("merchantUserName")); } // Save this information to be used in the Merchant Map // page b.putString("merchantInfo", jsonArray.toString()); intent.putExtras(b); } catch (JSONException e) { CustomDialog cd = new CustomDialog(Merchants.this); cd.showNotificationDialog(e.getMessage()); } adapter = new ArrayAdapter<String>(currentThis, android.R.layout.simple_list_item_1, listContents); adapter.setNotifyOnChange(true); myListView.setAdapter(adapter); } }); } else { CustomDialog cd = new CustomDialog(Merchants.this); cd.showNotificationDialog("Merchant list is empty."); } } }
Shell
UTF-8
3,085
3.921875
4
[]
no_license
#!/bin/bash RED='\033[0;31m' GRN='\033[0;32m' NC='\033[0m' check_one () { if [ "$#" -ne 4 -a "$#" -ne 5 ]; then echo "Illegal number of parameters" echo "Usage : sh checker.sh [lines] [characters per line] [with (1) or without new line] [from file(1) or stdin(0)] [verbose]" exit fi S0="$(sh rungen.sh $1 $2 $3 > file)" S=$(cat file) if [ "$4" -eq 1 ]; then R0="$(./main.out file > ret)" elif [ "$4" -eq 0 ] then R0="$(cat file | ./main.out | cat > ret)" fi R="$(cat ret)" if [ "$5" == "-v" ];then echo "Input :" cat -e file echo "\nOutput :" cat -e ret fi if [ "$3" -eq 1 ];then T="with" elif [ "$3" -eq 0 ] then T="without" fi if [[ "$R" != "$S" ]]; then echo "${RED}Main Test $1 line(s) ${2} characters $T \\\n : [KO] Difference between ${NC}$R${RED} and ${NC}$S" #return 1 else echo "${GRN}Main Test $1 line(s) $2 characters $T \\\n : [OK]${NC}" #return 0 fi } ran= lines=(1 2 $(( ( RANDOM % 20 ) + 1 ))) chars=(8 16 4) stdfile=(0 1) for i in ${chars[*]} do for j in ${stdfile[*]} do for k in ${lines[*]} do check_one $k $i 1 $j $1 done echo "\n" done done echo "--------------------------------------------------------------\n" echo "${RED}!You may Have to check manually for empty files, or files with no newline! (Change the main)\nAs you should see, the main adds a new line at each line so you should see in the output a \$ and none in the input.\nFor the empty files you might check yourself with a ${NC}./main.out empty_file${NC}\n" for j in 4 8 16 do check_one 1 $i 0 1 $1 done check_one 0 0 0 1 $1 check_one 0 0 0 0 $1 #Check for the return of get_next_line with testerror.out ? check_ret () { if [ "$#" -ne 5 -a "$#" -ne 6 ]; then echo "Illegal number of parameters" echo "Usage : sh checker.sh [lines] [characters per line] [with (1) or without new line] [expected return 0/1/-1] [number of reads] [verbose]" exit fi S0="$(sh rungen.sh $1 $2 $3 > file)" S=$(cat file) R0="$(./ret.out file $5 | cat > ret)" R="$(cat ret)" if [ "$6" == "-v" ];then echo "Input :" cat -e file echo "\nOutput :" cat ret fi if [ "$3" -eq 1 ];then T="with" elif [ "$3" -eq 0 ] then T="without" fi if [[ "$R" != $4 ]]; then echo "${RED}Return test $1 line(s) $2 characters, read $5 time(s) : [KO] Returned ${NC}$R${RED} when expecting ${NC}$4" else echo "${GRN}Return test $1 line(s) $2 characters, read $5 time(s) : [OK] Returned $R when expecting $4${NC}" fi } echo "\n--------------------------------------------------------------\n" check_ret 1 16 1 1 1 $1 check_ret 1 16 1 0 2 $1 check_ret 3 8 1 1 2 $1 check_ret 3 8 1 0 4 $1 echo "\nTesting errors, invalid fd and no rights on file :\n" chmod 000 file echo "Should display permission denied :" check_ret 1 8 1 -1 1 $1 #echo "Testing with a illegal file descriptor : (should return -1)" R=$(./error.out) if [ "$R" != -1 ];then echo "${RED}Return test : [KO] Returned ${NC}$R${RED} when expecting ${NC}-1" else echo "${GRN}Return test : [OK] Returned $R when expecting -1${NC}" fi chmod 777 file rm -f file ret
C#
UTF-8
1,592
3.25
3
[]
no_license
using System; namespace Books { public class Book : BaseEntity { private Genre Genre { get; set; } private string Author { get; set; } private string Title { get; set; } private string Description { get; set; } private int Year { get; set; } private bool Deleted { get; set; } public Book(int id, string author, Genre genre, string title, string description, int year) { this.Id = id; this.Title = title; this.Author = author; this.Year = year; this.Genre = genre; this.Description = description; this.Deleted = false; } public override string ToString() { string bookInfoMsg = ""; bookInfoMsg += "Genre: " + this.Genre + Environment.NewLine; bookInfoMsg += "Title: " + this.Title + Environment.NewLine; bookInfoMsg += "Author: " + this.Author + Environment.NewLine; bookInfoMsg += "Year: " + this.Year + Environment.NewLine; bookInfoMsg += "Description: " + this.Description + Environment.NewLine; bookInfoMsg += "Deleted: " + this.Deleted; return bookInfoMsg; } public string GetTitle() { return this.Title; } public int GetId() { return this.Id; } public bool GetDeleted() { return this.Deleted; } public void DeleteBook() { this.Deleted = true; } } }
Swift
UTF-8
4,803
2.75
3
[]
no_license
// // TwitchAPI.swift // TopGames // // Created by Eduardo Domene Junior on 27/06/18. // Copyright © 2018 Eduardo Domene Junior. All rights reserved. // import Foundation class TwitchAPI: NetworkAPIProtocol { let baseURL = "https://api.twitch.tv" let headers = ["Client-ID": "xzqsdxt247xi72kder6l57r0aksbsh"] let provider: RequestProtocol? enum Endpoint: String { case games = "/helix/games" case topGames = "/helix/games/top" case streams = "/helix/streams" } public init(provider: RequestProtocol) { self.provider = provider } func getGameBy(id: String, completion: @escaping CompletionWithGame) { let url = baseURL + Endpoint.topGames.rawValue let params = ["id": id] provider?.request(url: url, method: .get, params: params, headers: headers, completion: { (response) in switch response.result { case .success: let code = response.response?.statusCode if code != 200 && code != 201 { completion(false, nil) return } if let json = response.result.value as? [String: Any] { let games = NetworkGamesModel(object: json) if let game = games.data?.first { completion(true, game) return } completion(false, nil) } else { completion(false, nil) } case .failure: completion(false, nil) } }) } func getTopGames(_ fetchNextFromCursor: String?, completion: @escaping CompletionWithGames) { let url = baseURL + Endpoint.topGames.rawValue let params = ["after": fetchNextFromCursor ?? ""] provider?.request(url: url, method: .get, params: params, headers: headers, completion: { (response) in switch response.result { case .success: let code = response.response?.statusCode if code != 200 && code != 201 { completion(false, nil) return } if let json = response.result.value as? [String: Any] { let games = NetworkGamesModel(object: json) completion(true, games) } else { completion(false, nil) } case .failure: completion(false, nil) } }) } func getGameStreams(first: Int, gameId: String, completion: @escaping CompletionWithStreams) { let first = String(describing: first) let url = baseURL + Endpoint.streams.rawValue let params = ["first": first, "gameId": gameId] provider?.request(url: url, method: .get, params: params, headers: headers, completion: { (response) in switch response.result { case .success: let code = response.response?.statusCode if code != 200 && code != 201 { completion(false, nil) return } if let json = response.result.value as? [String: Any] { let games = NetworkStreamsModel(object: json) completion(true, games) } else { completion(false, nil) } case .failure: completion(false, nil) } }) } }
Python
UTF-8
839
4.40625
4
[]
no_license
name = 'python' age = 22 # 打印 "我是python,今年27岁" # 第一个不建议使用,因为格式转换比较麻烦 new_str = '我是' + name + ',' + '今年' + str(age) + '岁了'; print(new_str) # python 2 里面这样转换,特别注意前面的%s和%d要和后面传入的数据类型一致 new_str1 = "我是%s,今年%d岁了" % (name , age) print(new_str1) # python 3格式转化 与2相比format不需要在意数据类型 还可以增加标识 new_str2 = "我是{name},今年{age}岁了".format(name='python',age= 22) print(new_str2) # 这种方法可以直接引用变量 name1 = 'asd' age1 = 22 new_str3 = f"我是{name1},今年{age1}岁了" print(new_str3) # bool就是 True or false条件语句会用到 # None空值就是没有值 a = '' (空字符串)or a = 0 (值是0)都不叫空。a = None叫空
C#
UTF-8
1,452
2.546875
3
[]
no_license
using System; using System.ComponentModel; using System.Runtime.InteropServices; using System.Threading; using Microsoft.Win32.SafeHandles; namespace TrainCommuteCheckService { public class WakeyWakey { [DllImport("kernel32.dll")] public static extern SafeWaitHandle CreateWaitableTimer(IntPtr lpTimerAttributes, bool bManualReset, string lpTimerName); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetWaitableTimer(SafeWaitHandle hTimer, [In] ref long pDueTime, int lPeriod, IntPtr pfnCompletionRoutine, IntPtr lpArgToCompletionRoutine, bool fResume); public static void WakeUpAt(DateTime utc) { long duetime = utc.ToFileTime(); using (SafeWaitHandle handle = CreateWaitableTimer(IntPtr.Zero, true, "MyWaitabletimer")) { if (SetWaitableTimer(handle, ref duetime, 0, IntPtr.Zero, IntPtr.Zero, true)) { using (EventWaitHandle wh = new EventWaitHandle(false, EventResetMode.AutoReset)) { wh.SafeWaitHandle = handle; wh.WaitOne(); } } else { throw new Win32Exception(Marshal.GetLastWin32Error()); } } } } }
Markdown
UTF-8
3,164
2.9375
3
[]
no_license
⚠️ **Note: This project is a hobby, and is still in early development. It should probably not be used by anyone, for anything, yet.** --- A typeahead is a text input that displays suggestions as you type. It can be used for search, navigation, entity selection, and countless other things, and has become a ubiquitous part of modern user interfaces. I've spent a bunch of time throughout my career working on various implementations of this component and have developed some strong opinions about how they should work. This project aims to provide a simple reference typeahead implementation which codifies the following opinions: 1. One reflow per keystroke The contents of the results list should only ever be changed once after every keystroke. It might be okay to perform multiple paints, meaning you show a placeholder while an image downloads, or insert a line of expensive-to-fetch metadata after an initial render, but it's important to _never change the layout of the result list_, including modifying the height of the rendered items, more than once per keystroke. User interfaces that change shape asynchronously are infuriating. Note that there is one exception to this rule [1], but "one reflow per keystroke" is easy enough to remember, so let's run with it. 2. No result reordering As a corollary to one reflow per keystroke, regardless of what new information you gain from the server or elsewhere after the results are rendered, you should _never, ever reorder results after they are initially rendered_. You get one shot per keystroke to get the ordering of results right. If for some reason you get it wrong, you must simply swallow sadness and try to do better on future keystrokes. That being said: 3. Reverse waterfall filtering Once an item is displayed it should continue to be displayed for as long as it continues to be a prefix match. As the user types, previous results that continue to match should _flow upwards_ causing what I call a "reverse waterfall" effect. Even if you know a result is no longer relevant, the only time it should be removed from the result list is if it stops matching the typed query. Items that no longer match simply disappear, and items from the bottom of the list should flow upwards until they no longer match. 4. Backspace should be instant If you've generated the results for a query in a particular typeahead session, you should never need to go to the server or even do expensive work on the client to generate them again. This means that as the user hits backspace, the exact same results they saw a keystroke ago show up again instantly. This typeahead implementation offers prefix token matching only (no mid-string matching), and abides by the rules above through some pre-processing when new entries are added to the DataSource. It is generally able to filter a couple hundred thousand entries in less than a single frame (16ms) on a low end device. [1] The exception to the "one reflow per keystroke" is appending more results to the end of the list. It's okay to append more results to the end as long as you don't cause a reflow in anything that's already been rendered.
Java
UTF-8
3,066
2.21875
2
[]
no_license
/******************************************************************************* * * Project : Mirage V2 * * Package : * * Date : September 19, 2007, 8:27 PM * * Author : RangaRao Panda<rpanda@miraclesoft.com> * Rajasekhar Yenduva<ryenduva@miraclesoft.com> * * File : HibernateServiceLocator.java * * Copyright 2007 Miracle Software Systems, Inc. All rights reserved. * MIRACLE SOFTWARE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * ***************************************************************************** */ package com.mss.mirage.util; import java.sql.Connection; import java.sql.SQLException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; /** * * @author Rajasekhar Yenduva<ryenduva@miraclesoft.com> * @author RangaRao Panda<rpanda@miraclesoft.com> * * This Class.... ENTER THE DESCRIPTION HERE */ public class HibernateServiceLocator { // Instance for this class private static HibernateServiceLocator _instance; // java.sql.Connection object private Connection connection; // Hibernate Session Varible private Session session; // Hibernate SessionFactory Varible private SessionFactory sessionFactory; // ThreadLocal variable with early Instantiation private ThreadLocal sessionThreadLocal = new ThreadLocal(); /** Creates a new instance of HibernateServiceLocator */ private HibernateServiceLocator() throws ServiceLocatorException{ } /** * @return An instance of the HibernateServiceLocator class * @throws ServiceLocatorException */ public static HibernateServiceLocator getInstance() throws ServiceLocatorException { try { if(_instance==null) { _instance = new HibernateServiceLocator(); } } catch (Exception ex) { throw new ServiceLocatorException(ex); } return _instance; } /* * This method is used to store the session in thread * @return Hibernate Session instance */ public Session getSession() throws ServiceLocatorException { try { if (CacheManager.getCache().containsKey(ApplicationConstants.HIBERNATE_SESSION_FACTORY_KEY)) { sessionFactory = (SessionFactory) CacheManager.getCache().get(ApplicationConstants.HIBERNATE_SESSION_FACTORY_KEY); } else { sessionFactory = new Configuration().configure().buildSessionFactory(); CacheManager.getCache().put(ApplicationConstants.HIBERNATE_SESSION_FACTORY_KEY, sessionFactory); } session = sessionFactory.openSession(); } catch (HibernateException ex) { throw new ServiceLocatorException(ErrorMessages.CANNOT_GET_SESSIONFACTORY + ex.getMessage(),ex); } return session; } }
C++
UTF-8
4,082
2.578125
3
[]
no_license
#ifndef MAIN_CYCLE_H #define MAIN_CYCLE_H #include <cmath> #include "functions.h" class GA { public: GA(const double& Pc, const int& numIt, const int& maxItReq) : record(new IndividualType), fitnessRecord(-1), Pc(Pc), // max or min maxNumItWithoutChanges(numIt), maxNumItForRequirements(maxItReq), numItWithoutChanges(0) {} IndividualType* getResult(IPopulation* population, IMutation* mutation, ISelection* selection, ICrossover* crossover, IFitness* F) { updateRecord(population); const int pop_size = population->size(); int ids[pop_size]; // for check repeat parents in new generation int was_added[pop_size]; // for check repeat parents in new generation while (numItWithoutChanges < maxNumItWithoutChanges) { for (int i = 0; i < pop_size; ++i) was_added[i] = 0; IPopulation* parents = selection->getParents(population, F, ids); delete population; IPopulation* newGeneration = parents->weakCopy(); int rand2parent; for (int i = 0; i < pop_size; i += 2) { int rand1parent = arc4random_uniform(pop_size); // get rand2parent for (rand2parent = (rand1parent + 1) % pop_size; rand2parent != rand1parent and ids[rand1parent] == ids[rand2parent]; rand2parent = (rand2parent + 1) % pop_size); ////////////////// newGeneration->addIndividual(parents->getIndividual(rand1parent)); newGeneration->addIndividual(parents->getIndividual(rand2parent)); if (getRandomReal() < Pc or was_added[ids[rand1parent]] or was_added[ids[rand2parent]]) { crossover->crossing(&newGeneration->getIndividual(i), &newGeneration->getIndividual(i + 1)); } else { was_added[ids[rand1parent]] = was_added[ids[rand2parent]] = 1; } } delete parents; for (int i = 0; i < pop_size; ++i) { int numItForRequirements = 0; do { mutation->mutate(&newGeneration->getIndividual(i)); newGeneration->getFitness()[i].value = F->fitness(newGeneration->getIndividual(i)); newGeneration->getFitness()[i].state = F->checkRequirement(); } while (F->checkRequirement() and numItForRequirements++ < maxNumItForRequirements); if (newGeneration->getFitness()[i].state) newGeneration->getFitness()[i].value *= F->getFine(); } population = newGeneration; updateRecord(population); } delete population; return record; } void updateRecord(IPopulation* population) { // std::cout << __PRETTY_FUNCTION__ << std::endl; int size = population->size(); int max = fitnessRecord, it_max = 0; for (int i = 0; i < size; ++i) { int curr_fit = population->getFitness()[i].value; bool stationary = population->getFitness()[i].state; if (curr_fit > max and not stationary) { // max or min max = curr_fit; it_max = i; } } if (max > fitnessRecord) { // max or min fitnessRecord = max; delete record; record = new IndividualType(population->getIndividual(it_max)); numItWithoutChanges = 0; } else { ++numItWithoutChanges; } // std::cout << __PRETTY_FUNCTION__ << std::endl; } int getFitnessRecord() const { return fitnessRecord; } private: IndividualType* record; int fitnessRecord; double Pc; int maxNumItWithoutChanges; int maxNumItForRequirements; int numItWithoutChanges; }; #endif // MAIN_CYCLE_H
Python
UTF-8
3,081
2.546875
3
[ "MIT" ]
permissive
''' - login and get token - process 2FA if 2FA is setup for this account - in case the login is authorized as a partner_admin then also list the users that partner_admin has access to ''' import requests import json get_token_url = "https://api.canopy.cloud:443/api/v1/sessions/" validate_otp_url = "https://api.canopy.cloud:443/api/v1/sessions/otp/validate.json" #calling the production server for OTP authentication get_partner_users_url = "https://api.canopy.cloud:443/api/v1/admin/users.json" get_token_url = 'https://api.canopy.cloud:443/api/v1/sessions.json' validate_otp_url = "https://api.canopy.cloud:443/api/v1/sessions/otp/validate.json" #calling the production server for OTP authentication #please replace below with your username and password over here username = 'userxxx' password = 'passxxx' #please enter the OTP token in case it is enabled otp_code = '259060' #first call for a fresh token payload = "user%5Busername%5D=" + username + "&user%5Bpassword%5D=" + password headers = { 'accept': "application/json", 'content-type':"application/x-www-form-urlencoded" } response = requests.request("POST", get_token_url, data=payload, headers=headers) print json.dumps(response.json(), indent=4, sort_keys = True) token = response.json()['token'] login_flow = response.json()['login_flow'] #in case 2FA is enabled use the OTP code to get the second level of authentication if login_flow == '2fa_verification': headers['Authorization'] = token payload = 'otp_code=' + otp_code response = requests.request("POST", validate_otp_url, data=payload, headers=headers) print json.dumps(response.json(), indent=4, sort_keys = True) #print response.text # token = response.json()['token'] login_role = response.json()['role'] ''' you should get an ouput in the following format (in case a regular customer) { "base_currency": "USD", "days_to_password_expiry": 53, "display_name": "canopy_demo", "email": "admin@mesitis.com", "id": 291, "is_new": false, "login_flow": "logged_in", "registered_on": "03-06-2015", "role": "Customer", "status": "ok", "timeouts": { "IDLE_TIMEOUT": 30, "TOTAL_TIMEOUT": 240 }, "token": "816VvjP_3vdj85AHyasL", "username": "canopy_demo" } and in case of a partner_admin { "base_currency": "USD", "days_to_password_expiry": 53, "display_name": "demo_rm", "email": "abcd@1234.com", "id": 1674, "is_new": false, "login_flow": "logged_in", "registered_on": "24-08-2016", "role": "Partneradmin", "status": "ok", "timeouts": { "IDLE_TIMEOUT": 30, "TOTAL_TIMEOUT": 240 }, "token": "D9qoCakjxm1bNw8zFUyu", "username": "demo_rm" } ''' if login_role == 'Partneradmin': print "============== partner's users ===========" headers = { 'authorization': token, 'content-type': "application/x-www-form-urlencoded; charset=UTF-8" } partner_users = [] response = requests.request("GET", get_partner_users_url, headers=headers) print json.dumps(response.json(), indent=4, sort_keys = True)
Java
UTF-8
3,020
2.265625
2
[]
no_license
package com.ydw.myphone; import android.content.Context; import android.databinding.DataBindingUtil; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.ydw.myphone.databinding.ListContentBinding; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; /** * Created by Administrator on 2017/7/28. */ public class ContactsListAdapter extends RecyclerView.Adapter<ContactsListAdapter.ViewHolder> { private MyItemClickListener mItemClickListener; private ArrayList<ContactsInfo> contactsInfos = new ArrayList<>(); private ListContentBinding binding; private Context context; public ContactsListAdapter(Context context, ArrayList<ContactsInfo> list) { this.contactsInfos = list; this.context = context; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { binding = DataBindingUtil.inflate(LayoutInflater .from(context), R.layout.list_content, parent, false); ViewHolder holder = new ViewHolder(binding.getRoot(), mItemClickListener); holder.setBinding(binding); return holder; } @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.getBinding().setVariable(BR.contactsInfo, contactsInfos.get(position)); holder.getBinding().setContactsInfo(contactsInfos.get(position)); holder.getBinding().executePendingBindings(); } @Override public int getItemCount() { return contactsInfos.size(); } public void setContactList(ArrayList<ContactsInfo> mCMD) { this.contactsInfos = mCMD; notifyDataSetChanged(); } /** * 在activity里面adapter就是调用的这个方法,将点击事件监听传递过来,并赋值给全局的监听 * * @param myItemClickListener */ public void setItemClickListener(MyItemClickListener myItemClickListener) { this.mItemClickListener = myItemClickListener; } class ViewHolder extends RecyclerView.ViewHolder { private MyItemClickListener mListener; private ListContentBinding binding; public ViewHolder(View itemView, MyItemClickListener listener) { super(itemView); ButterKnife.bind(this, itemView); this.mListener = listener; } public void setBinding(ListContentBinding binding) { this.binding = binding; } public ListContentBinding getBinding() { return this.binding; } @OnClick(R.id.left) public void left_onClick(){ mListener.onItemClick(itemView, getPosition(), Edge.left); } @OnClick(R.id.right) public void right_onClick(){ mListener.onItemClick(itemView, getPosition(), Edge.right); } } }
PHP
UTF-8
362
2.8125
3
[]
no_license
<?php require_once("conexion.php"); class Usuario extends Conexion{ public function alta($nombre,$tipo,$password){ $this->sentencia = "INSERT INTO usuario VALUES (null,'$nombre','$tipo','$password')"; $this->ejecutarSentencia(); } public function consulta(){ $this->sentencia = "SELECT * FROM usuario"; return $this->obtenerSentencia(); } } ?>
C++
UTF-8
13,016
2.765625
3
[ "BSD-2-Clause" ]
permissive
#pragma once //------------------------------------------------------------------------------ /// \file /// \ingroup math /// \copyright (C) Copyright Aquaveo 2018. Distributed under FreeBSD License /// (See accompanying file LICENSE or https://aqaveo.com/bsd/license.txt) //------------------------------------------------------------------------------ #define XMSCORE_MATH_H #include <cmath> // for std::abs namespace xms { //------------------------------------------------------------------------------ /// \brief Rounds /// \param a: The value. /// \return int //------------------------------------------------------------------------------ template <class _T> int Round(_T a) { return (((a) > 0.0) ? ((int)((a) + 0.5)) : (((a) < 0.0) ? ((int)((a)-0.5)) : 0)); } ///< macro //------------------------------------------------------------------------------ /// \brief Integer absolute value /// \param a: The value. /// \return non-negative value //------------------------------------------------------------------------------ template <class _T> _T Miabs(_T a) { return (((a) >= 0) ? (a) : (-(a))); } ///< macro //------------------------------------------------------------------------------ /// \brief Float absolute value /// \param a: The value. /// \return non-negative value //------------------------------------------------------------------------------ template <class _T> _T Mfabs(_T a) { return (((a) >= 0.) ? (a) : (-(a))); } ///< macro //------------------------------------------------------------------------------ /// \brief Max of two values. /// \param a: The first value. /// \param b: The second value. /// \return Max value //------------------------------------------------------------------------------ template <class _T, class _U> _T Mmax(_T a, _U b) { return (((a) >= (b)) ? (a) : (b)); } ///< macro //------------------------------------------------------------------------------ /// \brief Min of two values. /// \param a: The first value. /// \param b: The second value. /// \return Min value //------------------------------------------------------------------------------ template <class _T, class _U> _T Mmin(_T a, _U b) { return (((a) >= (_T)(b)) ? (b) : (a)); } ///< macro //------------------------------------------------------------------------------ /// \brief Max of three values. /// \param a: The first value. /// \param b: The second value. /// \param c: The third value. /// \return Max value //------------------------------------------------------------------------------ template <class _T, class _U, class _V> _T Mmax3(_T a, _U b, _V c) { return (((a) >= (b)) ? (((a) >= (c)) ? (a) : (c)) : (((b) >= (c)) ? (b) : (c))); } ///< macro //------------------------------------------------------------------------------ /// \brief Min of three values. /// \param a: The first value. /// \param b: The second value. /// \param c: The third value. /// \return Min value //------------------------------------------------------------------------------ template <class _T, class _U, class _V> _T Mmin3(_T a, _U b, _V c) { return (((a) <= (b)) ? (((a) <= (c)) ? (a) : (c)) : (((b) <= (c)) ? (b) : (c))); } ///< macro //------------------------------------------------------------------------------ /// \brief Square /// \param x: The value to square. /// \return The value squared //------------------------------------------------------------------------------ template <typename _T> inline _T sqr(const _T x) { return x * x; } ///< macro //------------------------------------------------------------------------------ /// \brief XY distance. /// \param x1: X coordinate of first point. /// \param y1: Y coordinate of first point. /// \param x2: X coordinate of second point. /// \param y2: Y coordinate of second point. /// \return XY distance. //------------------------------------------------------------------------------ template <class _T, class _U, class _V, class _W> double Mdist(_T x1, _U y1, _V x2, _W y2) { return sqrt((double)(sqr(x1 - x2) + sqr(y1 - y2))); } ///< macro //------------------------------------------------------------------------------ /// \brief XY distance squared. /// \param x1: X coordinate of first point. /// \param y1: Y coordinate of first point. /// \param x2: X coordinate of second point. /// \param y2: Y coordinate of second point. /// \return XY distance squared. //------------------------------------------------------------------------------ template <class _T, class _U, class _V, class _W> double MdistSq(_T x1, _U y1, _V x2, _W y2) { return (double)(sqr(x1 - x2) + sqr(y1 - y2)); } ///< macro //------------------------------------------------------------------------------ /// \brief XYZ distance. /// \param x1: X coordinate of first point. /// \param y1: Y coordinate of first point. /// \param z1: Z coordinate of first point. /// \param x2: X coordinate of second point. /// \param y2: Y coordinate of second point. /// \param z2: Z coordinate of second point. /// \return XYZ distance. //------------------------------------------------------------------------------ template <typename X1, typename Y1, typename Z1, typename X2, typename Y2, typename Z2> double Mdist(X1 x1, Y1 y1, Z1 z1, X2 x2, Y2 y2, Z2 z2) { return sqrt((double)(sqr(x1 - x2) + sqr(y1 - y2) + sqr(z1 - z2))); } ///< macro //------------------------------------------------------------------------------ /// \brief Magnituded squared (x*x + y*y + z*z + w*w) /// \param x: Value in x. /// \param y: Value in y. /// \param z: Value in z. /// \param w: Value in x. /// \return Magnitude squared. //------------------------------------------------------------------------------ template <typename _T> double MagSquared(_T const x, _T const y, _T const z = 0, _T const w = 0) { return (double)(x * x + y * y + z * z + w * w); } ///< macro //------------------------------------------------------------------------------ /// \brief Magnituded sqrt(x*x + y*y + z*z + w*w) /// \param x: Value in x. /// \param y: Value in y. /// \param z: Value in z. /// \param w: Value in x. /// \return Magnitude. //------------------------------------------------------------------------------ template <typename _T> double Mag(_T const x, _T const y, _T const z = 0, _T const w = 0) { return sqrt(MagSquared(x, y, z, w)); } ///< macro //------------------------------------------------------------------------------ /// \brief Returns a value between a_min and a_max. /// \param a_in: Value to be clamped. /// \param a_min: Minimum value. /// \param a_max: Maximum value. /// \return Clamped value. //------------------------------------------------------------------------------ template <typename _T> _T Clamp(_T a_in, _T a_min, _T a_max) { return Mmin(Mmax(a_in, a_min), a_max); } ///< macro // The following 3 macros ending with EPS should have an epsilon // value passed to them. This should be something like FLT_EPSILON or // DBL_EPS or 1e-6 etc. The epsilon value is multiplied by the // sum of the two floats to compute a tolerance //------------------------------------------------------------------------------ /// \brief Returns true if A == B within an epsilon (DBL EPS). /// \param A: left hand side. /// \param B: right hand side. /// \param epsilon: The epsilon. /// \return true or false. //------------------------------------------------------------------------------ template <class _T, class _U, class _V> bool EQ_EPS(_T A, _U B, _V epsilon) { return (std::abs((A) - (B)) <= std::abs(((A) + (B)) * (epsilon))); } ///< macro //------------------------------------------------------------------------------ /// \brief Returns true if A < B equal within an epsilon (DBL EPS). /// \param A: left hand side. /// \param B: right hand side. /// \param epsilon: The epsilon. /// \return true or false. //------------------------------------------------------------------------------ template <class _T, class _U, class _V> bool LT_EPS(_T A, _U B, _V epsilon) { return (((B) - (A)) > std::abs(((A) + (B)) * (epsilon))); } ///< macro //------------------------------------------------------------------------------ /// \brief Returns true if A > B equal within an epsilon (DBL EPS). /// \param A: left hand side. /// \param B: right hand side. /// \param epsilon: The epsilon. /// \return true or false. //------------------------------------------------------------------------------ template <class _T, class _U, class _V> bool GT_EPS(_T A, _U B, _V epsilon) { return (((A) - (B)) > std::abs(((A) + (B)) * (epsilon))); } ///< macro //------------------------------------------------------------------------------ /// \brief Returns true if A <= B equal within an epsilon (DBL EPS). /// \param A: left hand side. /// \param B: right hand side. /// \param epsilon: The epsilon. /// \return true or false. //------------------------------------------------------------------------------ template <class _T, class _U, class _V> bool LTEQ_EPS(_T A, _U B, _V epsilon) { return (LT_EPS((A), (B), (epsilon)) || EQ_EPS((A), (B), (epsilon))); } ///< macro //------------------------------------------------------------------------------ /// \brief Returns true if A >= B equal within an epsilon (DBL EPS). /// \param A: left hand side. /// \param B: right hand side. /// \param epsilon: The epsilon. /// \return true or false. //------------------------------------------------------------------------------ template <class _T, class _U, class _V> bool GTEQ_EPS(_T A, _U B, _V epsilon) { return (GT_EPS((A), (B), (epsilon)) || EQ_EPS((A), (B), (epsilon))); } ///< macro // The following 3 macros ending with TOL should have a tolerance // passed to them. This tolerance should be something like // g_triangletolerancexy, or a tolerance that has been computed // from the range of the numbers involved. The numbers are compared // against the tolerance // Equal-with-tolerance EQ_TOL is needed, otherwise double values would not be // equal when, for all practical purposes, they are equal. Given that a number // is equal-with-tolerance to another number, then it cannot also be either // less-than or greater-than that other number. Therefore, LT_TOL and GT_TOL // give non-overlapping results rather than the result given by < and >. //------------------------------------------------------------------------------ /// \brief Returns true if A == B equal within a tolerance. /// \param A: left hand side. /// \param B: right hand side. /// \param tolerance: The tolerance. /// \return true or false. //------------------------------------------------------------------------------ template <class _T, class _U, class _V> bool EQ_TOL(const _T& A, const _U& B, const _V& tolerance) { return (std::abs((A) - (B)) <= (tolerance)); } //------------------------------------------------------------------------------ /// \brief Returns true if A < B equal within a tolerance. /// \param A: left hand side. /// \param B: right hand side. /// \param tolerance: The tolerance. /// \return true or false. //------------------------------------------------------------------------------ template <class _T, class _U, class _V> bool LT_TOL(_T A, _U B, _V tolerance) { return (((B) - (A)) > (tolerance)); } ///< macro //------------------------------------------------------------------------------ /// \brief Returns true if A > B equal within a tolerance. /// \param A: left hand side. /// \param B: right hand side. /// \param tolerance: The tolerance. /// \return true or false. //------------------------------------------------------------------------------ template <class _T, class _U, class _V> bool GT_TOL(_T A, _U B, _V tolerance) { return (((A) - (B)) > (tolerance)); } ///< macro //------------------------------------------------------------------------------ /// \brief Returns true if A <= B equal within a tolerance. /// \param A: left hand side. /// \param B: right hand side. /// \param tol: The tolerance. /// \return true or false. //------------------------------------------------------------------------------ template <class _T, class _U, class _V> bool LTEQ_TOL(_T A, _U B, _V tol) { return (LT_TOL((A), (B), (tol)) || EQ_TOL((A), (B), (tol))); } ///< macro //------------------------------------------------------------------------------ /// \brief Returns true if A >= B equal within a tolerance. /// \param A: left hand side. /// \param B: right hand side. /// \param tol: The tolerance. /// \return true or false. //------------------------------------------------------------------------------ template <class _T, class _U, class _V> bool GTEQ_TOL(_T A, _U B, _V tol) { return (GT_TOL((A), (B), (tol)) || EQ_TOL((A), (B), (tol))); } ///< macro } // namespace xms {
Python
UTF-8
3,563
2.71875
3
[ "MIT" ]
permissive
import time import socket import struct import random import threading import traceback from endpoint import Endpoint class IcmpClient: def __init__(self): self.sourceIp = socket.gethostbyname(socket.getfqdn()) self.sourcePort = 0 self.protocol = "icmp" def __checksum(self, packet) -> int: try: sumBytes = 0 if len(packet) & 1 == 1: packet += bytes([0]) for i in range(0, len(packet), 2): sumBytes += ((packet[i + 1] << 8) + packet[i]) while sumBytes > 65535: sumBytes = (sumBytes & 0xffff) + (sumBytes >> 16) return sumBytes ^ 0xffff except Exception as e: raise e def sendEchoRequest(self, destIp, destPort=7, times=0, size=64, interval=1) -> bool: ''' Create packe, send echo request, count success reply then if all request is fine, return True. Parameters ---------- destIp : string IP address to send packet. times : int times of sending packets. size : int size of messages within a packet. ''' endpoint = "" try: # Create endpoints. if destIp == "localhost" or destIp.split(".")[0] == "127": self.sourceIp = destIp endpoint = Endpoint(self.sourceIp, \ self.sourcePort, \ destIp, \ destPort, \ self.protocol) endpoint.daemon = True endpoint.start() inboundQueue = endpoint.getInboundQueue() outboundQueue = endpoint.getOutboundQueue() # RFC 792: https://tools.ietf.org/html/rfc792 type = 8 code = 0 checksum = 0 # Use for checking wheather receive packet is correct or not. idTable = dict() # Define source and destination IP address to pass to Endpoint Class. destIp = socket.gethostbyname(destIp) sourceIp = destIp for sequence in range(times): startTime = time.time() identifier = random.randint(0, 65355) idTable[str(identifier)] = sequence # Create each packet. header = struct.pack("bbHHh", type, code, 0, identifier, sequence) body = b"\xff" * size message = header + body checksum = self.__checksum(message) header = struct.pack("bbHHh", type, code, checksum, identifier, sequence) message = header + body # Ask to send packet to destination. outboundQueue.put(message) # Ask to get packet from destination. recvPacket = inboundQueue.get() # Check received packet is valid or not. header = recvPacket[0][20:28] recvType, recvCode, recvChecksum, recvId, recvSequence = struct.unpack("bbHHh", header) if recvType != 0: return False if idTable[str(recvId)] != recvSequence: return False time.sleep(interval - (time.time() - startTime)) endpoint.closeAllEndpoints() return True except KeyboardInterrupt: endpoint.closeAllEndpoints() except KeyError as e: return False except Exception as e: raise e
C++
UTF-8
660
3.40625
3
[]
no_license
/** * baekjoon online judge * No. 11650 좌표 정렬하기 * @date 2018.04.27 */ #include <iostream> #include <algorithm> using namespace std; // 좌표 구조체 struct xy { int x, y; }; // 배열 xy arr[100001]; // 비교 함수 bool compare(xy a, xy b) { if (a.x == b.x) return a.y < b.y; return a.x < b.x; } // main int main() { ios::sync_with_stdio(false); cin.tie(NULL); // 점의 개수 입력 int N; cin >> N; // 좌표 입력 for (int i = 0; i < N; i++) cin >> arr[i].x >> arr[i].y; // 정렬 sort(arr, arr + N, compare); // 출력 for (int i = 0; i < N; i++) cout << arr[i].x << " " << arr[i].y << "\n"; return 0; }
Java
UTF-8
6,404
2.265625
2
[ "Apache-2.0" ]
permissive
/** * Copyright 2015 Expedia, Inc. All rights reserved. * EXPEDIA PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package com.expedia.echox3.internal.transport.request.source; import com.expedia.echox3.basics.configuration.ConfigurationManager; import com.expedia.echox3.basics.tools.pubsub.Publisher; import com.expedia.echox3.basics.tools.pubsub.PublisherManager; import com.expedia.echox3.internal.transport.request.AbstractRequest; import com.expedia.echox3.internal.transport.request.MessageType; public abstract class AbstractSourceRequest extends AbstractRequest { private static final TimeoutManager TIMEOUT_MANAGER = new TimeoutManager(); private long m_clientContext; // Because the TransmitMessage is stolen before the response arrives private long m_timeoutMS; // timeout private long m_timeSubmittedMS; // WallClock time when the request is submitted. private long m_timeResponseMS; // WallClock time when the response is ready private long m_timeTimeoutMS; // WallClock time when the request will timeout. private IRequestCompleteListener m_objectToNotify = null; protected AbstractSourceRequest(MessageType messageType) { super(messageType); } @Override public void release() { m_objectToNotify = null; super.release(); } public IRequestCompleteListener getObjectToNotify() { return m_objectToNotify; } public void setObjectToNotify(IRequestCompleteListener objectToNotify) { m_objectToNotify = objectToNotify; m_timeoutMS = calculateTimeout(); m_timeSubmittedMS = System.currentTimeMillis(); m_timeResponseMS = 0; m_timeTimeoutMS = m_timeSubmittedMS + m_timeoutMS; } protected long calculateTimeout() { return TIMEOUT_MANAGER.getTimeout(this, getMessageType(), 1); } @Override public void initTransmitMessage(int size) { super.initTransmitMessage(size); setClientContext(getTransmitMessage().getClientContext()); } public long getClientContext() { return m_clientContext; } public void setClientContext(long clientContext) { m_clientContext = clientContext; } public long getTimeoutMS() { return m_timeoutMS; } public long getTimeSubmittedMS() { return m_timeSubmittedMS; } public long getTimeResponseMS() { return m_timeResponseMS; } public long getTimeTimeoutMS() { return m_timeTimeoutMS; } public long getDurationMS() { return getTimeResponseMS() - getTimeSubmittedMS(); } @Override protected void markResponseReady() { m_timeResponseMS = System.currentTimeMillis(); super.markResponseReady(); if (null != getObjectToNotify()) { getObjectToNotify().processCompletedRequest(this); } } @Override public void runInternal() { markResponseReady(); } /** * Returns a string representation of the object. In general, the * {@code toString} method returns a string that * "textually represents" this object. The result should * be a concise but informative representation that is easy for a * person to read. * It is recommended that all subclasses override this method. * <p> * The {@code toString} method for class {@code Object} * returns a string consisting of the name of the class of which the * object is an instance, the at-sign character `{@code @}', and * the unsigned hexadecimal representation of the hash code of the * object. In other words, this method returns a string equal to the * value of: * <blockquote> * <pre> * getClass().getName() + '@' + Integer.toHexString(hashCode()) * </pre></blockquote> * * @return a string representation of the object. */ @Override public String toString() { return String.format("%s: Context %,d", getClass().getSimpleName(), getClientContext()); } public interface IRequestCompleteListener { void processCompletedRequest(AbstractSourceRequest clientRequest); } /** * Manages the raw data from which the timeout of individual requests are calculated. * The data comes from configuration. * The setting names are <RequestClassName>.[Timeout|Increment][Number|Units], with full inheritance. * * A timeout is : CalculatedTimeout = timeout + (count * increment) * * The data is stored in arrays indexed by the message number for fast retrieval. * The data is kept by the singleton TimeoutManager to keep only one copy, read from configuration once, ... * */ private static class TimeoutManager { private static final ConfigurationManager CONFIGURATION_MANAGER = ConfigurationManager.getInstance(); private static final String FORMAT_BASE = "%s.Timeout"; private static final String FORMAT_INCREMENT = "%s.Increment"; private static final String DEFAULT_BASE = "2000"; private static final String DEFAULT_INCREMENT = "20"; private String[] m_classNameList = new String[MessageType.MESSAGE_COUNT_MAX]; private long[] m_timeoutList = new long[MessageType.MESSAGE_COUNT_MAX]; private long[] m_incrementList = new long[MessageType.MESSAGE_COUNT_MAX]; public TimeoutManager() { Publisher.getPublisher(ConfigurationManager.PUBLISHER_NAME).register(this::updateConfiguration); } public void updateConfiguration(String publisherName, long timeMS, Object event) { // Update the timeout list... for (int i = 0; i < MessageType.MESSAGE_COUNT_MAX; i++) { if (null != m_classNameList[i]) { updateConfiguration(i); } } } private void updateConfiguration(int messageNumber) { String baseName = String.format(FORMAT_BASE, m_classNameList[messageNumber]); String incrementName = String.format(FORMAT_INCREMENT, m_classNameList[messageNumber]); //CHECKSTYLE:OFF m_timeoutList[messageNumber] = CONFIGURATION_MANAGER.getTimeInterval(baseName, DEFAULT_BASE, "ms"); m_incrementList[messageNumber] = CONFIGURATION_MANAGER.getTimeInterval(incrementName, DEFAULT_INCREMENT, "ms"); //CHECKSTYLE:ON } public long getTimeout(AbstractSourceRequest request, MessageType messageType, int count) { int messageNumber = messageType.getNumber(); if (null == m_classNameList[messageNumber]) { // As of yet unknown message, register it... m_classNameList[messageNumber] = request.getClass().getName(); updateConfiguration(messageNumber); } return m_timeoutList[messageNumber] + (count * m_incrementList[messageNumber]); } } }
Java
UTF-8
3,661
2.109375
2
[ "MIT" ]
permissive
package com.maryanto.dimas.example.controller; import com.maryanto.dimas.example.entity.Kecamatan; import com.maryanto.dimas.example.entity.Kelurahan; import com.maryanto.dimas.example.entity.KotaKabupaten; import com.maryanto.dimas.example.entity.Provinsi; import com.maryanto.dimas.example.repository.KecamatanRepository; import com.maryanto.dimas.example.repository.KelurahanRepository; import com.maryanto.dimas.example.repository.KotaKabupatenRepository; import com.maryanto.dimas.example.repository.ProvinsiRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.Optional; import static org.springframework.http.ResponseEntity.noContent; import static org.springframework.http.ResponseEntity.ok; @RestController @RequestMapping("/api/v2") public class WilayahIndonesiaApi { @Autowired private ProvinsiRepository provinsiRepository; @Autowired private KotaKabupatenRepository kotaRepository; @Autowired private KecamatanRepository kecamatanRepository; @Autowired private KelurahanRepository kelurahanRepository; @GetMapping({"/provinsi", "/provinsi/list"}) public ResponseEntity<?> provinsiAll() { List<Provinsi> list = provinsiRepository.findAll(); if (list.isEmpty()) return noContent().build(); return ok(list); } @GetMapping("/provinsi/{id}") public ResponseEntity<?> provinsiById(@PathVariable("id") Long provinsiId) { Optional<Provinsi> provinsi = provinsiRepository.findById(provinsiId); if (!provinsi.isPresent()) return noContent().build(); return ok(provinsi.get()); } @GetMapping("/kota/{id}") public ResponseEntity<?> kotaByProvinsiId(@PathVariable("id") Long provinsiId) { Optional<KotaKabupaten> kota = kotaRepository.findById(provinsiId); if (!kota.isPresent()) return noContent().build(); return ok(kota.get()); } @GetMapping("/kota/{id}/list") public ResponseEntity<?> kotaAllByProvinsiId(@PathVariable("id") Long id) { List<KotaKabupaten> list = kotaRepository.findByProvinsiId(id); if (list.isEmpty()) return noContent().build(); return ok(list); } @GetMapping("/kecamatan/{id}/list") public ResponseEntity<?> kecamatanByKotaId(@PathVariable("id") Long id) { List<Kecamatan> list = kecamatanRepository.findByKotaId(id); if (list.isEmpty()) return noContent().build(); return ok(list); } @GetMapping("/kecamatan/{id}") public ResponseEntity<?> kecamatanById(@PathVariable("id") Long id) { Optional<Kecamatan> kecamatan = kecamatanRepository.findById(id); if (!kecamatan.isPresent()) return noContent().build(); return ok(kecamatan.get()); } @GetMapping("/kelurahan/{id}/list") public ResponseEntity<?> kelurahanByKecamatanId(@PathVariable("id") Long id) { List<Kelurahan> list = kelurahanRepository.findByKecamatanId(id); if (list.isEmpty()) return noContent().build(); return ok(list); } @GetMapping("/kelurahan/{id}") public ResponseEntity<?> kelurahanById(@PathVariable("id") Long id) { Optional<Kelurahan> kelurahan = kelurahanRepository.findById(id); if (!kelurahan.isPresent()) return noContent().build(); return ok(kelurahan.get()); } }
Python
UTF-8
1,444
3
3
[]
no_license
from sys import argv script, input_file = argv open_file = open(input_file) directions = open_file.read() houses = [(0,0)] robot_houses = [(0,0)] i = 0 for d in directions: if i%2 == 0: if d == '^': houses.append([houses[len(houses) - 1][0]+1, houses[len(houses) - 1][1]]) elif d == 'v': houses.append([houses[len(houses) - 1][0]-1, houses[len(houses) - 1][1]]) elif d == '>': houses.append([houses[len(houses) - 1][0], houses[len(houses) - 1][1]+1]) elif d == '<': houses.append([houses[len(houses) - 1][0], houses[len(houses) - 1][1]-1]) else: if d == '^': robot_houses.append([robot_houses[len(robot_houses) - 1][0]+1, robot_houses[len(robot_houses) - 1][1]]) elif d == 'v': robot_houses.append([robot_houses[len(robot_houses) - 1][0]-1, robot_houses[len(robot_houses) - 1][1]]) elif d == '>': robot_houses.append([robot_houses[len(robot_houses) - 1][0], robot_houses[len(robot_houses) - 1][1]+1]) elif d == '<': robot_houses.append([robot_houses[len(robot_houses) - 1][0], robot_houses[len(robot_houses) - 1][1]-1]) i += 1 unique_house = [] for house in robot_houses: if house not in unique_house: unique_house.append(house) for house in houses: if house not in unique_house: unique_house.append(house) print("part 2:", len(unique_house))
Python
UTF-8
144
2.6875
3
[]
no_license
import math def calcula_norma(n): s=0 i=0 while i <= len(n): s+=n[i]**2 i+=1 norma=math.sqrt(s) return norma
C++
UTF-8
315
2.9375
3
[]
no_license
#include <cassert> #include <iostream> #include "intcode.h" using namespace std; int main(int argc, char *argv[]) { assert(argc == 2); Intcode ic(argv[1]); for (auto &x : {1, 2}) { ic.push_input({x}); ic.run_program(); cout << "Part " << x << ": " << ic.get_output() << endl; } return 0; }