language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Markdown
UTF-8
1,178
2.59375
3
[ "MIT" ]
permissive
# Apache Conf - Catch Suspecious Requests Apache server config for catching suspecious requests. Analyzes incoming request data (Request URI, User Agent, etc) for pre-defined patterns of suspecious activity. Requests deemed suspecious are stopped from being processed and a standard response is given (by default, a plain 404). ## Requirements - Apache server - Apache `mod_rewrite` module enabled ## Installation - Method 1: Global Installation - *Note: this method may not work with individual VirtualHosts. To use with VirtualHosts see Method 2 below.* - Place the `catch-suspecious-requests.conf` file inside your Apache's conf directory - `/etc/apache2/conf-available/`. - Enable the new conf with `a2enconf catch-suspecious-requests` and reload Apache with `service apache2 restart`. - Method 2: VirtualHost Installation - Place the `catch-suspecious-requests.conf` file inside your Apache's conf directory - `/etc/apache2/conf-available/`. - Include the new conf inside your VirtualHost by adding the line `Include conf-available/catch-suspecious-requests.conf`. - Enable the new conf by reloading Apache with `service apache2 reload`.
Python
UTF-8
1,471
2.90625
3
[]
no_license
from django import template import datetime register = template.Library() @register.filter def is_selected(value, page_name): """custom django filter to check and apply extra style if currently viewed page is selected from navigation Usage: {{ "link_on_navigation_name"|is_selected:current_page_name }}. """ s = '' if page_name == value: s = "class=selected" return s @register.filter def mod(value): """ simple modulus 2 custom tag. """ if value % 2 == 0: return True else: return False @register.filter def len(value): """ simple modulus 2 custom tag. """ return len(value) @register.filter def get(value, key): """ Get the value of a key from a dict """ try: return value[key] except KeyError: return None @register.filter def from_html(value): """ replaces <p></p> with a new line for display in textbox """ try: return value.replace('<br />', '\n') except Exception: return '' @register.filter def from_timestamp(value): """ Converts timestamp time to string date """ return datetime.datetime.fromtimestamp(float(value)) @register.filter def to_friendly_url(value): """ Converts string to a url friendly string. Replaces all spaces with hyphen and & xter with and """ _value = value.replace(" ", '-') _value = _value.replace('&', 'and') return _value
JavaScript
UTF-8
1,811
3.671875
4
[]
no_license
// { // firstname: 'Mollie' // lastname: 'Smith' // age: 27 // } // user1.age // var weddinglist = [ // 'old', // 'new', // 'borrowed', // 'blue', // ] // console.log(weddinglist[2]); // var userlist[ // user1 user2 // ] // console.log(userlist[1].firstname); var addressbook = [{ firstname: 'Mollie', lastname: 'Smith', phonenumber: '513-288-7093' }, { firstname: 'Nelson', lastname: 'Smith', phonenumber: '513-299-7843' }, { firstname: 'Laura', lastname: 'Wolfram', phonenumber: '513-277-6743' }, { firstname: 'Dennis', lastname: 'Smith', phonenumber: '513-244-3333' } ] function printFirstName(add) { console.log(add) } printFirstName(addressbook); function printAddressBook(add) { for (var i = 0; i < add.length; i++) { console.log(add[i].addressbook) } } printAddressBook(addressbook); var ourFunction = function (thing) { for (var i = 0; i < thing.length; i++) { console.log(thing[i].lastname); }; } // ourFunction(addressbook); function ourConsole(message1) { return function (message2) { console.log('This is our message out. ' + message1); console.log('This is our message out. ' + message2); } } var mgs = ourConsole('Hello'); mgs('Goodbye') for (var i = 0; i < addressbook.length; i++) { mgs(addressbook); } function forEach(arr1, func1) { for (var i = 0; i < arr1.length; i++) { func1(arr1); } } function printName(x) { console.log(x.firstname, x.lastname); } function printAddr(x) { console.log(x.address); } forEach(addressbook,printName); forEach(addressbook,printAddr); forEach(addressbook, function(x){ console.log(x.phonenumber) });
Java
UTF-8
81
1.789063
2
[]
no_license
package enums; public enum Status { TODO,PROGRESS,BLOCKED,IN_REVIEW,DONE }
SQL
UTF-8
650
2.71875
3
[]
no_license
-- create table SQL statements demo -- -- usage: -- $ ucasdb ./01_create.sql -- correct statement -- create table crtDemo (id int, name varchar); -- wrong statements -- -- 0. table existed -- create table crtDemo (id int, name varchar); -- 1. miss field name -- create table crtWrong1 (int, name varchar); -- 2. miss data type -- create table crtWrong2 (id, name varchar); -- 3. miss ',' -- create table crtWrong2 (id int name varchar); -- 4. miss ';' -- create table crtWrong2 (id int, name varchar) -- 5. wrong data type -- create table crtWrong3 (id float, name varchar);
Java
UTF-8
7,863
2.0625
2
[]
no_license
package com.cardmax.base.Chat; import android.app.ProgressDialog; import android.content.Intent; import android.graphics.Typeface; import android.os.Bundle; import android.os.Handler; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.cardmax.base.R; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.iid.FirebaseInstanceId; import com.cardmax.base.Muro.MuroMainActivity; // public class LoginActivity extends AppCompatActivity { // private FirebaseUser currentUser; private Button LoginButton, PhoneLoginButton; private EditText UserEmail, UserPassword; private Button NeedNewAccountLink, OlvideMiContraseña; private FirebaseAuth mAuth; private ProgressDialog loadingBar; private TextView titulo; //ANIMACION 1 LOGIN private RelativeLayout rellay1, rellay2; private ImageView imagen1; Handler handler = new Handler(); Runnable runnable = new Runnable() { @Override public void run() { rellay1.setVisibility(View.VISIBLE); rellay2.setVisibility(View.VISIBLE); imagen1.setVisibility(View.VISIBLE); } }; //FANAMICACION private DatabaseReference UserRef; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.chat_activity_login_animacion); //ANIMACION rellay1 = (RelativeLayout) findViewById(R.id.rellay1); rellay2 = (RelativeLayout) findViewById(R.id.rellay2); imagen1 = (ImageView) findViewById(R.id.login_image); handler.postDelayed(runnable, 2000); //2000 is the timeout for the splash imagen1.setAlpha(100); int opacity = 80; // from 0 to 255 imagen1.setBackgroundColor(opacity * 0x1000000); //FANIMACION titulo = (TextView) findViewById(R.id.tv_login); Typeface fuente =Typeface.createFromAsset(getAssets(),"fonts/MrDafoe-Regular.ttf"); titulo.setTypeface(fuente); mAuth = FirebaseAuth.getInstance(); UserRef = FirebaseDatabase.getInstance().getReference().child("Users"); // currentUser = mAuth.getCurrentUser(); intializeFileds(); NeedNewAccountLink.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SendUserToRegisterActivity(); } }); OlvideMiContraseña.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EnviarContraseñaActivity(); } }); LoginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AllowUserToLogin(); } }); /* PhoneLoginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent phoneLoginIntent=new Intent(LoginActivity.this,PhoneLoginActivity.class); startActivity(phoneLoginIntent); } });*/ } private void AllowUserToLogin() { String email = UserEmail.getText().toString(); String password = UserPassword.getText().toString(); if (TextUtils.isEmpty(email)) { Toast.makeText(this, "Porfavor digite el email", Toast.LENGTH_SHORT).show(); } if (TextUtils.isEmpty(password)) { Toast.makeText(this, "Porfavor digite el password", Toast.LENGTH_SHORT).show(); } else { loadingBar.setTitle("Cargando sesión"); loadingBar.setMessage("Porfavor espera mientras entras a tu cuenta"); loadingBar.setCanceledOnTouchOutside(true); loadingBar.show(); mAuth.signInWithEmailAndPassword(email, password). addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { //notificaciones por token String currentUserID = mAuth.getCurrentUser().getUid(); String deviceToken = FirebaseInstanceId.getInstance().getToken(); UserRef.child(currentUserID).child("token") .setValue(deviceToken) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { SendUserToInicioActivity(); // Toast.makeText(LoginActivity.this, "Inocio de sesión correcto", Toast.LENGTH_SHORT).show(); loadingBar.dismiss(); } } }); } else { String mensaje = task.getException().toString(); Toast.makeText(LoginActivity.this, "Error: " + mensaje, Toast.LENGTH_SHORT).show(); loadingBar.dismiss(); } } }); } } private void intializeFileds() { LoginButton = (Button) findViewById(R.id.login_button); // PhoneLoginButton = (Button) findViewById(R.id.phone_login_button); UserEmail = (EditText) findViewById(R.id.login_email); UserPassword = (EditText) findViewById(R.id.login_password); NeedNewAccountLink = (Button) findViewById(R.id.need_newaccount_link); OlvideMiContraseña = (Button) findViewById(R.id.forget_passowrd_link); loadingBar = new ProgressDialog(this); } /* @Override protected void onStart() { super.onStart(); if (currentUser != null) { SendUserToInicioActivity(); } }*/ private void SendUserToRegisterActivity() { Intent RegisterIntent = new Intent(LoginActivity.this, RegisterActivity.class); startActivity(RegisterIntent); } /* private void SendUserToInicioActivity() { Intent IncioIntent = new Intent(LoginActivity.this, InicioActivity.class); IncioIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(IncioIntent); finish(); }*/ private void SendUserToInicioActivity() { Intent IncioIntent = new Intent(LoginActivity.this, MuroMainActivity.class); IncioIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(IncioIntent); finish(); } private void EnviarContraseñaActivity() { Intent ContraseñaIntent = new Intent(LoginActivity.this, OlvidarPasswordActivity.class); startActivity(ContraseñaIntent); } }
Python
UTF-8
125
3.65625
4
[]
no_license
amount=int(input('Enter the price: ')) def price(amount): discount= 0.1*amount print (amount-discount) price(amount)
Java
UTF-8
6,636
2.15625
2
[]
no_license
package com.wmall.wechat.service; import com.alibaba.fastjson.JSON; import com.wmall.config.WechatInfoConfig; import com.wmall.utils.HttpUtil; import com.wmall.wechat.enums.WeChatConstant; import com.wmall.wechat.pojo.*; import lombok.extern.slf4j.Slf4j; import me.chanjar.weixin.common.util.http.URIUtil; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * 访问微信服务器服务 * create by niexx * 2017-11-14 22:42 */ @Slf4j @Service public class WechatAccessService { @Autowired private WechatInfoConfig wechatInfoConfig; /** * 获取用户信息 * * @param token * @param openid * @return */ public WechatUserInfo queryUserInfo(String openid, String token) { String userInfoUrl = String.format(genUserInfoUrl(token, openid)); String userInfoJson = HttpUtil.httpGetJs(userInfoUrl); WechatUserInfo wechatUserInfo = JSON.parseObject(userInfoJson, WechatUserInfo.class); return wechatUserInfo; } /** * 获取token信息 * * @param code * @return */ public AccessToken queryTokenInfo(String code) { String tokenUrl = String.format(genTokenUrl(code)); String tokenJson = HttpUtil.httpGetJs(tokenUrl); AccessToken accessToken = JSON.parseObject(tokenJson, AccessToken.class); return accessToken; } /** * 获取企业Token信息 * * @return */ public CorpTokenInfo queryCorpToken() { String corpTokenUrl = genCorpTokenUrl(wechatInfoConfig.getCorpId(), wechatInfoConfig.getCorpSecret()); String result = HttpUtil.httpGetJs(corpTokenUrl); CorpTokenInfo corpTokenInfo = JSON.parseObject(result, CorpTokenInfo.class); return corpTokenInfo; } /** * 主动推送消息 * * @param accessToken * @param msgData * @return */ public ActiveMsgResult activeSendMsg(String accessToken, String msgData) { String sendMsgUrl = genSendMsgUrl(accessToken); String result = HttpUtil.httpRequest(sendMsgUrl, HttpUtil.POST, msgData); ActiveMsgResult activeMsgResult = JSON.parseObject(result, ActiveMsgResult.class); return activeMsgResult; } /** * 创建菜单 * * @param agentId * @param menuObj * @return */ public CreateMenuResult createMenu(String agentId, String menuObj) { String menuUrl = genMenuUrl(agentId); String result = HttpUtil.httpRequest(menuUrl, HttpUtil.POST, menuObj); CreateMenuResult createMenuResult = JSON.parseObject(result, CreateMenuResult.class); return createMenuResult; } public String genMenuUrl(String agentId) { String menuUrl = wechatInfoConfig.getCreateMenu(); menuUrl = menuUrl.replace("ACCESS_TOKEN", WeChatConstant.corpToken).replace("AGENTID", agentId); return menuUrl; } public String genCodeUrl(String redirectUrl, String state) { String codeUrl = wechatInfoConfig.getCodeUrl(); codeUrl = codeUrl.replace("APPID", wechatInfoConfig.getAppId()) .replace("REDIRECT_URI", URIUtil.encodeURIComponent(redirectUrl)) .replace("SCOPE", wechatInfoConfig.getAuthScope()) .replace("STATE", StringUtils.trimToEmpty(state)); //log.info("genCodeUrl={}", codeUrl); return codeUrl; } public String genTokenUrl(String code) { String tokenUrl = wechatInfoConfig.getTokenUrl(); tokenUrl = tokenUrl.replace("APPID", wechatInfoConfig.getAppId()) .replace("SECRET", wechatInfoConfig.getAppSecret()) .replace("CODE", code); //log.info("genTokenUrl={}", tokenUrl); return tokenUrl; } public String genUserInfoUrl(String token, String openid) { String userInfoUrl = wechatInfoConfig.getUserInfoUrl(); userInfoUrl = userInfoUrl.replace("ACCESS_TOKEN", token) .replace("OPENID", openid); //log.info("genUserInfoUrl={}", userInfoUrl); return userInfoUrl; } public String genRefreshTokenUrl(String freshToken) { String refreshTokenUrl = wechatInfoConfig.getRefreshTokenUrl(); refreshTokenUrl = refreshTokenUrl.replace("APPID", wechatInfoConfig.getAppId()) .replace("REFRESH_TOKEN", freshToken); return refreshTokenUrl; } /** * 获取校验TOKEN URL * * @param accessToken * @param openid * @return */ public String genValidTokenUrl(String accessToken, String openid) { String validTokenUrl = wechatInfoConfig.getValidTokenUrl(); validTokenUrl = validTokenUrl.replace("ACCESS_TOKEN", accessToken) .replace("OPENID", openid); return validTokenUrl; } /** * 生成主动发送消息的URL * * @param accessToken * @return */ public String genSendMsgUrl(String accessToken) { String sendMsgUrl = wechatInfoConfig.getSendMsgUrl(); sendMsgUrl = sendMsgUrl.replace("ACCESS_TOKEN", accessToken); return sendMsgUrl; } public String genCorpTokenUrl(String corpId, String secret) { String corpTokenUrl = wechatInfoConfig.getCorpTokenUrl(); corpTokenUrl = corpTokenUrl.replace("ID", corpId) .replace("SECRECT", secret); return corpTokenUrl; } /** * 上传临时素材URL * * @param accessToken * @param fileType * @return */ public String genUploadUrl(String accessToken, String fileType) { String uploadUrl = wechatInfoConfig.getUploadUrl(); uploadUrl = uploadUrl.replace("ACCESS_TOKEN", accessToken) .replace("TYPE", fileType); return uploadUrl; } /** * 下载临时素材URL * * @param accessToken * @param mediaId * @return */ public String genDownLoadUrl(String accessToken, String mediaId) { String downLoadRrl = wechatInfoConfig.getDownLoadUrl(); downLoadRrl = downLoadRrl.replace("ACCESS_TOKEN", accessToken) .replace("MEDIA_ID", mediaId); return downLoadRrl; } public static void main(String[] args) { String corpTokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwae679b71d1986931&corpsecret=UrBeKxk06y20zGq2b4NpuXfnQg_7wiOGAgnT0dp0wfU"; corpTokenUrl = String.format(corpTokenUrl); String tokenInfo = HttpUtil.httpGetJs(corpTokenUrl); System.out.println("tokenInfo:" + tokenInfo); } }
JavaScript
UTF-8
1,125
2.515625
3
[ "MIT" ]
permissive
import React from 'react'; import axios from 'axios'; import StripeCheckout from 'react-stripe-checkout'; import STRIPE_PUBLISHABLE from './constants/stripe'; import PAYMENT_SERVER_URL from './constants/server'; // checkout component uses teh stripeCheckout that comes from the library installed. It receives personal props (name, description, amount ect.) const CURRENCY = 'USD'; const fromDollarsToCent = amount => amount * 100; const successPayment = data => { alert('Payment Successful!'); }; const errorPayment = data => { alert('Payment Unsuccessful!'); }; // change to async await trycatch const onToken = (amount, description) => token => axios .post(PAYMENT_SERVER_URL, { description, source: token.id, currency: CURRENCY, amount: fromDollarsToCent, }) .then(successPayment) .catch(errorPayment); const Checkout = ({ name, description, amount }) => ( <StripeCheckout name={name} description={description} amount={fromDollarsToCent(amount)} token={onToken(amount, description)} currency={CURRENCY} stripeKey={STRIPE_PUBLISHABLE} /> );
C
UTF-8
154
3.0625
3
[]
no_license
#include <stdio.h> #define PI 3.1415927 int main() { double a; while(scanf("%lf",&a)!=EOF) { printf("%.3f\n",4*PI*a*a*a/3); } return 0; }
Markdown
UTF-8
2,096
2.546875
3
[]
no_license
# Reinforcement Learning This is a repo containing explanations and implementations of the following Reinforcement Learning algorithms. Note that, if you want to see the notebooks clearly (with LaTeX and stuff) you need to clone the repo. * ```git clone git@github.com:ceteke/RL.git``` * ```cd RL``` * ```jupyter notebook``` ## [Tabular](https://github.com/ceteke/RL/tree/master/Tabular) The tabular methods are demonstrated on OpenAI Gym's FrozenLake environment. ### [Dynamic Programming](https://github.com/ceteke/RL/tree/master/Tabular/Dynamic%20Programming) * [Policy Iteration](https://github.com/ceteke/RL/blob/master/Tabular/Dynamic%20Programming/Policy%20Iteration.ipynb) * [Value Iteration](https://github.com/ceteke/RL/blob/master/Tabular/Dynamic%20Programming/Value%20Iteration.ipynb) ### Monte Carlo * On-Policy Control * Exploring Starts * Off-Policy Control ### [Temporal Difference](https://github.com/ceteke/RL/tree/master/Tabular/Temporal%20Difference) * [On-Policy TD (Sarsa)](https://github.com/ceteke/RL/blob/master/Tabular/Temporal%20Difference/SARSA.ipynb) * [Off-Policy TD (Q-Learning)](https://github.com/ceteke/RL/blob/master/Tabular/Temporal%20Difference/Q-Learning.ipynb) * [n-Step On-Policy TD (Sarsa)](https://github.com/ceteke/RL/blob/master/Tabular/Temporal%20Difference/n-step%20SARSA.ipynb) ## [Approximation](https://github.com/ceteke/RL/tree/master/Approximation) * [Linear Sarsa](https://github.com/ceteke/RL/blob/master/Approximation/Linear%20Sarsa.ipynb) * [Average Reward Linear Sarsa](https://github.com/ceteke/RL/blob/master/Approximation/Average%20Reward%20Semi-Gradient%20Sarsa.ipynb) * [n-Step Linear Sarsa](#) * [Actor-Critic Action Value Policy Gradient](https://github.com/ceteke/RL/blob/master/Approximation/Actor-Critic%20Policy%20Gradient.ipynb) ## [Policy Gradient](https://github.com/ceteke/RL/tree/master/Policy%20Gradient) * [REINFORCE (Monte Carlo Policy Gradient)](https://github.com/ceteke/RL/blob/master/Policy%20Gradient/reinforce.py) * [Hindsight Experience Replay](https://www.github.com/ceteke/her) ## Deep Reinforcement Learning
C++
UTF-8
11,694
2.625
3
[]
no_license
#include <map> #include <set> #include <list> #include <cmath> #include <ctime> #include <deque> #include <queue> #include <stack> #include <string> #include <bitset> #include <cstdio> #include <limits> #include <vector> #include <climits> #include <cstring> #include <cstdlib> #include <fstream> #include <numeric> #include <sstream> #include <iostream> #include <algorithm> #include <unordered_map> #include <map> using namespace std; map<string,long long>::iterator it; unordered_map<string,long long> multipleMap; unordered_map<long long,long long> contributionMap; // Long answer I came up with during the contest, basically // use DP to count the # of contributions long long threeDigitContribution(long long num, int pos) { return (num*contributionMap[pos]%1000000007); } long long threeDigitContributionEven(int i) { long long contribution = 0; contribution += threeDigitContribution(multipleMap["00"], i); contribution %= 1000000007; contribution += threeDigitContribution(multipleMap["08"], i); contribution %= 1000000007; contribution += threeDigitContribution(multipleMap["16"], i); contribution %= 1000000007; contribution += threeDigitContribution(multipleMap["24"], i); contribution %= 1000000007; contribution += threeDigitContribution(multipleMap["32"], i); contribution %= 1000000007; contribution += threeDigitContribution(multipleMap["40"], i); contribution %= 1000000007; contribution += threeDigitContribution(multipleMap["48"], i); contribution %= 1000000007; contribution += threeDigitContribution(multipleMap["56"], i); contribution %= 1000000007; contribution += threeDigitContribution(multipleMap["64"], i); contribution %= 1000000007; contribution += threeDigitContribution(multipleMap["72"], i); contribution %= 1000000007; contribution += threeDigitContribution(multipleMap["80"], i); contribution %= 1000000007; contribution += threeDigitContribution(multipleMap["88"], i); contribution %= 1000000007; contribution += threeDigitContribution(multipleMap["96"], i); contribution %= 1000000007; return contribution; } long long threeDigitContributionOdd(int i) { long long contribution = 0; contribution += threeDigitContribution(multipleMap["04"], i); contribution %= 1000000007; contribution += threeDigitContribution(multipleMap["12"], i); contribution %= 1000000007; contribution += threeDigitContribution(multipleMap["20"], i); contribution %= 1000000007; contribution += threeDigitContribution(multipleMap["28"], i); contribution %= 1000000007; contribution += threeDigitContribution(multipleMap["36"], i); contribution %= 1000000007; contribution += threeDigitContribution(multipleMap["44"], i); contribution %= 1000000007; contribution += threeDigitContribution(multipleMap["52"], i); contribution %= 1000000007; contribution += threeDigitContribution(multipleMap["60"], i); contribution %= 1000000007; contribution += threeDigitContribution(multipleMap["68"], i); contribution %= 1000000007; contribution += threeDigitContribution(multipleMap["76"], i); contribution %= 1000000007; contribution += threeDigitContribution(multipleMap["84"], i); contribution %= 1000000007; contribution += threeDigitContribution(multipleMap["92"], i); contribution %= 1000000007; return contribution; } int main(){ int n; cin >> n; string number; cin >> number; long long answer = 0; // Any of the following keys can be part of a multiple of 8 multipleMap["0"] = 0; multipleMap["1"] = 0; multipleMap["2"] = 0; multipleMap["3"] = 0; multipleMap["4"] = 0; multipleMap["5"] = 0; multipleMap["6"] = 0; multipleMap["7"] = 0; multipleMap["8"] = 0; multipleMap["9"] = 0; multipleMap["00"] = 0; multipleMap["04"] = 0; multipleMap["08"] = 0; multipleMap["12"] = 0; multipleMap["16"] = 0; multipleMap["20"] = 0; multipleMap["24"] = 0; multipleMap["28"] = 0; multipleMap["32"] = 0; multipleMap["36"] = 0; multipleMap["40"] = 0; multipleMap["44"] = 0; multipleMap["48"] = 0; multipleMap["52"] = 0; multipleMap["56"] = 0; multipleMap["60"] = 0; multipleMap["64"] = 0; multipleMap["68"] = 0; multipleMap["72"] = 0; multipleMap["76"] = 0; multipleMap["80"] = 0; multipleMap["84"] = 0; multipleMap["88"] = 0; multipleMap["92"] = 0; multipleMap["96"] = 0; // Calculate contribution of 3-digit pairs at different indices long long contribution = 1; for(int i = 0; i <= 220000; i++) { contributionMap[i] = contribution; contribution *= 2; contribution %= 1000000007; } // Count 2-digit and 3-digit multiples using DP for(int i = number.size()-1; i >= 0; i--) { if(number[i] == '0') { // First see what we can combine it with // 1-digit contributions answer++; // Since 0 is a multiple of 8 // 2-digit contributions answer += multipleMap["0"]; // Since 00 is a multiple of 8 answer %= 1000000007; answer += multipleMap["8"]; // Since 08 is a multiple of 8 answer %= 1000000007; // 3-digit contributions answer += threeDigitContributionEven(i); // Then update the maps multipleMap["00"] += multipleMap["0"]; multipleMap["00"] %= 1000000007; multipleMap["04"] += multipleMap["4"]; multipleMap["04"] %= 1000000007; multipleMap["08"] += multipleMap["8"]; multipleMap["08"] %= 1000000007; multipleMap["0"]++; } else if(number[i] == '1') { // First see what we can combine it with answer += multipleMap["6"]; answer %= 1000000007; answer += threeDigitContributionOdd(i); answer %= 1000000007; // Then update the maps multipleMap["12"] += multipleMap["2"]; multipleMap["12"] %= 1000000007; multipleMap["16"] += multipleMap["6"]; multipleMap["16"] %= 1000000007; multipleMap["1"]++; } else if(number[i] == '2') { // First see what we can combine it with answer += multipleMap["4"]; answer %= 1000000007; answer += threeDigitContributionEven(i); answer %= 1000000007; // Then update the maps multipleMap["20"] += multipleMap["0"]; multipleMap["20"] %= 1000000007; multipleMap["24"] += multipleMap["4"]; multipleMap["24"] %= 1000000007; multipleMap["28"] += multipleMap["8"]; multipleMap["28"] %= 1000000007; multipleMap["2"]++; } else if(number[i] == '3') { // First see what we can combine it with answer += multipleMap["2"]; answer %= 1000000007; answer += threeDigitContributionOdd(i); answer %= 1000000007; // Then update the maps multipleMap["32"] += multipleMap["2"]; multipleMap["32"] %= 1000000007; multipleMap["36"] += multipleMap["6"]; multipleMap["36"] %= 1000000007; multipleMap["3"]++; } else if(number[i] == '4') { // First see what we can combine it with answer += multipleMap["0"]; answer %= 1000000007; answer += multipleMap["8"]; answer %= 1000000007; answer += threeDigitContributionEven(i); answer %= 1000000007; // Then update the maps multipleMap["40"] += multipleMap["0"]; multipleMap["40"] %= 1000000007; multipleMap["44"] += multipleMap["4"]; multipleMap["44"] %= 1000000007; multipleMap["48"] += multipleMap["8"]; multipleMap["48"] %= 1000000007; multipleMap["4"]++; } else if(number[i] == '5') { // First see what we can combine it with answer += multipleMap["6"]; answer %= 1000000007; answer += threeDigitContributionOdd(i); answer %= 1000000007; // Then update the maps multipleMap["52"] += multipleMap["2"]; multipleMap["52"] %= 1000000007; multipleMap["56"] += multipleMap["6"]; multipleMap["56"] %= 1000000007; multipleMap["5"]++; } else if(number[i] == '6') { // First see what we can combine it with answer += multipleMap["4"]; answer %= 1000000007; answer += threeDigitContributionEven(i); answer %= 1000000007; // Then update the maps multipleMap["60"] += multipleMap["0"]; multipleMap["60"] %= 1000000007; multipleMap["64"] += multipleMap["4"]; multipleMap["64"] %= 1000000007; multipleMap["68"] += multipleMap["8"]; multipleMap["68"] %= 1000000007; multipleMap["6"]++; } else if(number[i] == '7') { // First see what we can combine it with answer += multipleMap["2"]; answer %= 1000000007; answer += threeDigitContributionOdd(i); answer %= 1000000007; // Then update the maps multipleMap["72"] += multipleMap["2"]; multipleMap["72"] %= 1000000007; multipleMap["76"] += multipleMap["6"]; multipleMap["76"] %= 1000000007; multipleMap["7"]++; } else if(number[i] == '8') { // First see what we can combine it with answer++; answer += multipleMap["0"]; answer %= 1000000007; answer += multipleMap["8"]; answer %= 1000000007; answer += threeDigitContributionEven(i); answer %= 1000000007; // Then update the maps multipleMap["80"] += multipleMap["0"]; multipleMap["80"] %= 1000000007; multipleMap["84"] += multipleMap["4"]; multipleMap["84"] %= 1000000007; multipleMap["88"] += multipleMap["8"]; multipleMap["88"] %= 1000000007; multipleMap["8"]++; } else if(number[i] == '9') { // First see what we can combine it with answer += multipleMap["6"]; answer %= 1000000007; answer += threeDigitContributionOdd(i); answer %= 1000000007; // Then update the maps multipleMap["92"] += multipleMap["2"]; multipleMap["92"] %= 1000000007; multipleMap["96"] += multipleMap["6"]; multipleMap["96"] %= 1000000007; multipleMap["9"]++; } } cout<<answer<<"\n"; return 0; } // Much cleaner trie solution (creds to tsite) // using namespace std; // #define m 1000000007 // #define pe(a,b){a+=b;a%=m;} // typedef unsigned int t; // constexpr t minv_t[]={0,4,3,4,2,4,1,4,0,4}; // int main(){ // int n; // cin >> n; // string number; // cin >> number; // t reg[5]={}; // t regp[2]={}; // t dcount=0; // t si=1; // for(int i=0;i<n;i++) { // number[i]-='0'; // if(number[i]%8==0)dcount++; // pe(dcount,reg[minv_t[number[i]]]); // pe(reg[number[i]%4],regp[0]+1); // pe(reg[(number[i]+2)%4],regp[1]); // pe(regp[number[i]%2],si); // pe(si,si); // } // cout << dcount; // return 0; // }
JavaScript
UTF-8
241
2.828125
3
[]
no_license
const document = { querySelectorAll: () => ['element1', 'element2', 'element3'] }; const cols = document.querySelectorAll('.column'); const col1 = cols[0]; const col3 = cols[2]; console.log("col1:", col1); console.log("col3:", col3);
Markdown
UTF-8
1,812
2.609375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# Bytestrings This is an implementation of a [pre-SRFI specification](https://bitbucket.org/cowan/r7rs-wg1-infra/src/default/BytestringsCowan.md) by John Cowan which provides bytestrings for Scheme. It should be portable to any R7RS-small implementation with [(scheme bytevector)](http://www.r6rs.org/final/html/r6rs-lib/r6rs-lib-Z-H-3.html#node_chap_2), [SRFI 1/(scheme list)](https://srfi.schemers.org/srfi-1), [SRFI 151/(scheme bitwise)](https://srfi.schemers.org/srfi-151), and one of Scheme's string libraries (one of SRFIs 152, 130, or 13). In addition, [SRFI 145](https://srfi.schemers.org/srfi-145) is an optional dependency. # Extensions This implementation provides the following additional procedures for inspecting error objects raised by some bytestring procedures; namely, those satisfying `bytestring-error?`: `(bytestring-error-message` *error-object*`)` Returns the message (string) encapsulated by *error-object*. `(bytestring-error-irritants` *error-object*`)` Returns a list of the irritants encapsulated by *error-object*. # Implementation Notes `(hex-string->bytevector s)` returns false if `s` cannot be interepreted as a base 16 number, in the sense of `string->number`. # Acknowledgements The implementation of hex-string and base64 encoding and decoding is from Alex Shinn's [chibi-scheme](http://synthcode.com/wiki/chibi-scheme). This code is found in the *hex.scm* and *base64.scm* files, along with the chibi-scheme license. The implementation of several functions is heavily inspired by Olin Shivers's [SRFI 13](https://srfi.schemers.org/srfi-13). Of course, any misuse of Alex's or Olin's code or ideas is purely my own. # Author Wolfgang Corcoran-Mathe Email: wcm at sigwinch dot xyzzy minus the zy # License This is free software released under the MIT/X license. See LICENSE for details.
Java
UTF-8
354
2.171875
2
[]
no_license
package test4.processor; import org.apache.camel.Exchange; import org.apache.camel.Processor; public class AdminUserProcessor implements Processor{ @Override public void process(Exchange exchange) throws Exception { System.out.println("Processing a ADMIN user..."); exchange.getIn().setHeader("cpf", "111.111.111-11"); } }
Java
UTF-8
1,941
2.171875
2
[]
no_license
package com.inn.project1.project1.dao; import java.math.BigInteger; import java.util.List; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.inn.project1.project1.models.Student; @Repository public interface IStudentDao extends CrudRepository<Student,Integer>{ public List<Object[]> getStudentGradesByGroup(); public BigInteger maxStudentIdentifier(String genderCode,String resultCode); //public Integer insertStudentIdentifier(String genderCode,String resultCode); //public void updateStudentIdentifier(String studentCode,String genderCode,String resultCode); /* @Query(value="select s.grades,count(*) from Student s group by s.grades") public List<Object[]> getStudentGradesByGroup(); @Query(value="select max(student_code)+1 from student_unique_code_generator where gender_code=:genderCode and result_code=:resultCode",nativeQuery=true) public BigInteger maxStudentIdentifier(@Param("genderCode") String genderCode,@Param("resultCode") String resultCode); */ @Modifying @Transactional @Query(value="insert into student_unique_code_generator(gender_code,result_code,student_code) value(:genderCode,:resultCode,1)",nativeQuery=true) public Integer insertStudentIdentifier(@Param("genderCode") String genderCode,@Param("resultCode") String resultCode); @Modifying @Transactional @Query(value="update student_unique_code_generator set student_code=:studentCode where gender_code=:genderCode and result_code=:resultCode",nativeQuery=true) public Integer updateStudentIdentifier(@Param("studentCode") String studentCode,@Param("genderCode") String genderCode,@Param("resultCode") String resultCode); }
Python
UTF-8
2,681
3.359375
3
[ "BSD-3-Clause" ]
permissive
#GUI BT program reference from tkinter import * import bluetooth # Look for all Bluetooth devices # the computer knows about. print("Searching for devices...") print("") nearby_devices = bluetooth.discover_devices()#array of devices # Run through all the devices found and list their name num = 0 print("Select your device by entering its coresponding number...") for i in nearby_devices: num += 1 print(num, ": ", bluetooth.lookup_name(i)) # Allow the user to select their Arduino # bluetooth module. They must have paired # it before hand. selection = int(input("> ")) - 1 print("You have selected", bluetooth.lookup_name(nearby_devices[selection])) bd_addr = nearby_devices[selection] print (type(bd_addr)) port = 1 # Create the GUI class Application(Frame): # Create a connection to the socket for Bluetooth # communication sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM) def disconnect(self): # Close socket connection to device self.sock.close() def on(self): # Send 'H' which the Arduino # detects as turning the light on data = "3" self.sock.send(data) def off(self): # Send 'L' to turn off the light # attached to the Arduino data = "1" self.sock.send(data) def createWidgets(self): # Form all the buttons. # Look at a Tkinter reference # for explanations. self.QUIT = Button(self) self.QUIT["text"] = "QUIT" self.QUIT["fg"] = "red" self.QUIT["command"] = self.quit self.QUIT.pack({"side": "left"}) self.disconnectFrom = Button(self) self.disconnectFrom["text"] = "Disconnect" self.disconnectFrom["fg"] = "darkgrey" self.disconnectFrom["command"] = self.disconnect self.disconnectFrom.pack({"side": "left"}) self.turnOn = Button(self) self.turnOn["text"] = "On", self.turnOn["fg"] = "green" self.turnOn["command"] = self.on self.turnOn.pack({"side": "left"}) self.turnOff = Button(self) self.turnOff["text"] = "Off" self.turnOff["fg"] = "red" self.turnOff["command"] = self.off self.turnOff.pack({"side": "left"}) def __init__(self, master=None): # Connect to the bluetooth device # and initialize the GUI self.sock.connect((bd_addr, port)) Frame.__init__(self, master) self.pack() self.createWidgets() # Begin the GUI processing root = Tk() app = Application(master=root) app.mainloop() root.destroy()
Markdown
UTF-8
1,239
3.140625
3
[ "Apache-2.0" ]
permissive
CSRFWork ========== A simple way of protecting forms regarding to CSRF Installation: ------------- * Place the csrf.php file into your application folder * Include it ```include_once 'csrf.php'; ``` * and initate it: ```CSRF::init();``` HowTo --------- There are 2 methods available for you to interact with your cache. * ```token()``` * ```check($token)``` TOKEN ----- token() This method will return the token for the current and next request. **Example usage:** <input type="hidden" value="<?php echo CSRF::token(); ?>" name="csrf_token" /> This will add a hidden input field to you form with the name ```csrf_token``` and the value is the token itself. How we can use we' ll see in the ```check()``` part. CHECK ----- check($token) This method will check if a string matches the token generated in the **previous** request. * ```$token```: string: the string to check **Example usage:** if (CSRF::check($_POST['csrf_token'])) { // Everything' s fine } else { // The post request was not submited by the form on your site. die('DIE STUPID ATTACKER'); //Take 'em down... } You can always have a look at the PHP doc for a brief explanation.
C#
UTF-8
3,034
2.640625
3
[]
no_license
using System; using System.Collections.Generic; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace CarouselDemo { public partial class App : Application { public static List<Models.Chapter> MainData { get; set; } public App() { InitializeComponent(); MainData = new List<Models.Chapter> { new Models.Chapter { Title = "Chapter 1", Pages = new List<Models.Page> { new Models.Page { Title = "Page 1 - 1", BackColor = Color.Red }, new Models.Page { Title = "Page 2 - 1", BackColor = Color.GhostWhite }, new Models.Page { Title = "Page 3 - 1", BackColor = Color.Gainsboro }, } }, new Models.Chapter { Title = "Chapter 2", Pages = new List<Models.Page> { new Models.Page { Title = "Page 1 - 2", BackColor = Color.YellowGreen }, new Models.Page { Title = "Page 2 - 2", BackColor = Color.AntiqueWhite }, new Models.Page { Title = "Page 3 - 2", BackColor = Color.Aqua }, } }, new Models.Chapter { Title = "Chapter 3", Pages = new List<Models.Page> { new Models.Page { Title = "Page 1 - 3", BackColor = Color.Blue }, new Models.Page { Title = "Page 2 - 3", BackColor = Color.Brown }, new Models.Page { Title = "Page 3 - 3", BackColor = Color.CadetBlue }, } } }; MainPage = new MainPage(); } protected override void OnStart() { } protected override void OnSleep() { } protected override void OnResume() { } } }
C++
UTF-8
30,321
3.03125
3
[]
no_license
#include <LiquidCrystal.h> int index = 0; // add all the letters and digits to the keyboard String keyboard[]={"SEND","A", "B","C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "SEND", "DEL", "SPACE"}; String text = ""; int numOptions = 40; int ledPort=8; int ledPort2=9; char letters; // initialize the library with the numbers of the interface pins LiquidCrystal lcd(12, 11, 7, 6, 5, 4); void setup() { // set up the LCD's number of columns and rows: Serial.begin(9600); lcd.begin(16,2); // Print a message to the LCD. attachInterrupt(0, changeLetter, RISING);//button A in port 2 attachInterrupt(1, selected, RISING);//button B in port 3 pinMode(ledPort, OUTPUT); pinMode(ledPort2, OUTPUT); } void loop() { // set the cursor to column 0, line 1 // (note: line 1 is the second row, since counting begins with 0): lcd.clear(); lcd.setCursor(0, 0); lcd.print(keyboard[index]); lcd.setCursor(0, 1); lcd.print(text); delay(100); digitalWrite(13, HIGH); } //This function changes the letter in the keyboard void changeLetter(){ static unsigned long last_interrupt_time = 0; unsigned long interrupt_time = millis(); if (interrupt_time - last_interrupt_time > 200) { last_interrupt_time = interrupt_time;// If interrupts come faster than 200ms, assum index++; //check for the max row number if(index==numOptions){ index=0; //loop back to first row } } } //this function adds the letter to the text or send the msg void selected(){ static unsigned long last_interrupt_time = 0; unsigned long interrupt_time = millis(); if (interrupt_time - last_interrupt_time > 200) { last_interrupt_time = interrupt_time;// If interrupts come faster than 200ms, assum String key = keyboard[index]; if (key == "DEL") { int len = text.length(); text.remove(len-1); } else if(key == "SEND") { convertbin(); text=""; } else if(key == "SPACE") { text += " "; }else{ text += key; } index = 0; //restart the index } } void convertbin(){ // if 2 lights ON = 1, if 1 light ON = 0 // if 2 lights OFF break // if 1 light ON 1s = 0, if 1 lights ON 2s = 00… // if 2 light ON 1s = 1, if 1 lights ON 2s = 11… String code; for(int i=0; i<text.length();i++){ letters = text[i]; Serial.print(letters); switch (letters) { case 'A': //code = "001010"; digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case 'B': //code = "001011"; digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case 'C': //code = "001100"; digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case 'D': //code = "001101"; digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case 'E': //code = "001110"; digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case 'F': //code = "001111"; digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case 'G': //code = "010000"; digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case 'H': //code = "010001"; digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case 'I': //code = "010010"; digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case 'J': //code = "010011"; digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case 'K': //code = "010100"; digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case 'L': //code = "010101"; digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case 'M': //code = "010110"; digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case 'N': //code = "010111"; digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case 'O': //code = "011000"; digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case 'P': //code = "011001"; digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case 'Q': //code = "011010"; digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case 'R': //code = "011011"; digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case 'S': //code = "011100"; digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case 'T': //code = "011101"; digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case 'U': //code = "011110"; digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case 'V': //code= "011111"; digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case 'W': //code = "100000"; digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case 'X': //code = "100001"; digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case 'Y': //code = "100010"; digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case 'Z': //code = "100011"; digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case '0': //code = "000000"; digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case '1': //code = "000001"; digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case '2': //code = "000010"; digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case '3': //code = "000011"; digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case '4': //code = "000100"; digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case '5': //code = "000101"; digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case '6': //code = "000110"; digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case '7': //code = "000111"; digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case '8': //code = "001000"; digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case '9': //code = "001001"; digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, HIGH); digitalWrite(ledPort2, HIGH); delay(200000); digitalWrite(ledPort, LOW); digitalWrite(ledPort2, LOW); delay(200000); break; case 'space': //code = 000000 digitalWrite(ledPort2, LOW); digitalWrite(ledPort2, LOW); delay(500000); } } }
SQL
UTF-8
12,783
3.515625
4
[]
no_license
CREATE PROCEDURE CH15_Calc_Bowler_Pins_Avg_Hcp AS UPDATE Bowlers SET Bowlers.BowlerTotalPins = DSum('RawScore','Bowler_Scores ','Bowler_Scores.BowlerID = ' & Bowlers.BowlerID), Bowlers.BowlerGamesBowled = DCount('RawScore','Bowler_Scores','Bowler_Scores.BowlerID = ' & Bowlers.BowlerID), Bowlers.BowlerCurrentAverage = NZ(Round(DAvg('Bowler_Scores.RawScore','Bowler_Scores','Bowler_Scores.BowlerID = ' & Bowlers.BowlerID),0),0), Bowlers.BowlerCurrentHcp = NZ(Round(0.9*(200-Round(DAvg('Bowler_Scores.RawScore','Bowler_Scores','Bowler_Scores.BowlerID = ' & Bowlers.BowlerID),0)),0),0); CREATE VIEW CH15_Calc_Bowler_Pins_Avg_Hcp_Query AS SELECT Bowlers.BowlerID, Bowlers.BowlerTotalPins, DSum('RawScore','Bowler_Scores ','Bowler_Scores.BowlerID = ' & Bowlers.BowlerID) AS NewBowlerTotalPins, Bowlers.BowlerGamesBowled, DCount('RawScore','Bowler_Scores','Bowler_Scores.BowlerID = ' & Bowlers.BowlerID) AS NewBowlerGamesBowled, Bowlers.BowlerCurrentAverage, Nz(Round(DAvg('Bowler_Scores.RawScore','Bowler_Scores','Bowler_Scores.BowlerID = ' & Bowlers.BowlerID),0),0) AS NewBowlerCurrentAverage, Bowlers.BowlerCurrentHcp, Nz(Round(0.9*(200-Round(DAvg('Bowler_Scores.RawScore','Bowler_Scores','Bowler_Scores.BowlerID = ' & Bowlers.BowlerID),0)),0),0) AS NewBowlerCurrentHcp FROM Bowlers; CREATE PROCEDURE CH15_Change_Huckleberry_Name AS UPDATE Teams SET Teams.TeamName = 'Manta Rays' WHERE Teams.TeamName = 'Huckleberrys'; CREATE VIEW CH15_Change_Huckleberry_Name_Query AS SELECT Teams.TeamName, 'Manta Rays' AS NewTeamName FROM Teams WHERE (((Teams.TeamName)='Huckleberrys')); CREATE PROCEDURE CH15_Change_Tourney_Location AS UPDATE Tournaments SET Tournaments.TourneyLocation = 'Oasis Lanes' WHERE Tournaments.TourneyLocation = 'Sports World Lanes'; CREATE VIEW CH15_Change_Tourney_Location_Query AS SELECT Tournaments.TourneyID, Tournaments.TourneyLocation, 'Oasis Lanes' AS NewTourneyLocation FROM Tournaments WHERE (((Tournaments.TourneyLocation)='Sports World Lanes')); CREATE PROCEDURE CH15_Update_Bowler_City_State AS UPDATE Bowlers SET BowlerCity = DLookup('City', 'WAZips', 'ZIP = '' & (BowlerZip) & '''), BowlerState = DLookup('State', 'WAZips', 'ZIP = '' & (BowlerZip) & ''') WHERE (BowlerCity <> (SELECT City FROM WAZips WHERE Bowlers.BowlerZip = WAZips.ZIP)) OR (BowlerState <> (SELECT State FROM WAZips WHERE Bowlers.BowlerZip = WAZips.ZIP)); CREATE VIEW CH15_Update_Bowler_City_State_Query AS SELECT Bowlers.BowlerCity, (SELECT City FROM WAZips WHERE Bowlers.BowlerZip = WAZips.ZIP) AS NewBowlerCity, Bowlers.BowlerState, (SELECT State FROM WAZips WHERE Bowlers.BowlerZip = WAZips.ZIP) AS NewBowlerState FROM Bowlers WHERE (((Bowlers.(BowlerCity))<>(SELECT City FROM WAZips WHERE Bowlers.BowlerZip = WAZips.ZIP))) OR (((Bowlers.(BowlerState))<>(SELECT State FROM WAZips WHERE Bowlers.BowlerZip = WAZips.ZIP))); CREATE PROCEDURE CH16_Add_Bowler AS INSERT INTO Bowlers ( BowlerLastName, BowlerFirstName, BowlerAddress, BowlerCity, BowlerState, BowlerZip, BowlerPhoneNumber, TeamID, BowlerTotalPins, BowlerGamesBowled, BowlerCurrentAverage, BowlerCurrentHcp ) SELECT Bowlers.BowlerLastName, 'Matthew' AS BowlerFirstName, Bowlers.BowlerAddress, Bowlers.BowlerCity, Bowlers.BowlerState, Bowlers.BowlerZip, Bowlers.BowlerPhoneNumber, Bowlers.TeamID, 0, 0, 0, 0 FROM Bowlers WHERE (Bowlers.BowlerLastName='Patterson') AND (Bowlers.BowlerFirstName='Neil'); CREATE VIEW CH16_Add_Bowler_Query AS SELECT Bowlers.BowlerLastName, 'Matthew' AS BowlerFirstName, Bowlers.BowlerAddress, Bowlers.BowlerCity, Bowlers.BowlerState, Bowlers.BowlerZip, Bowlers.BowlerPhoneNumber, Bowlers.TeamID, 0 AS Expr1, 0 AS Expr2, 0 AS Expr3, 0 AS Expr4 FROM Bowlers WHERE (((Bowlers.BowlerLastName)='Patterson') AND ((Bowlers.BowlerFirstName)='Neil')); CREATE PROCEDURE CH16_Add_Team AS INSERT INTO Teams ( TeamName, CaptainID ) VALUES ('Aardvarks', Null); CREATE VIEW CH16_Add_Team_Query AS SELECT 'Aardvarks' AS TeamName, Null AS CaptainID; CREATE PROCEDURE CH16_Archive_2017_Tournaments_1 AS INSERT INTO Tournaments_Archive SELECT Tournaments.TourneyID AS TourneyID, Tournaments.TourneyDate AS TourneyDate, Tournaments.TourneyLocation AS TourneyLocation FROM Tournaments WHERE (Tournaments.TourneyDate Between '1/1/2017' AND '12/31/2017'); CREATE VIEW CH16_Archive_2017_Tournaments_1_Query AS SELECT Tournaments.TourneyID AS TourneyID, Tournaments.TourneyDate AS TourneyDate, Tournaments.TourneyLocation AS TourneyLocation FROM Tournaments WHERE (((Tournaments.TourneyDate) Between '1/1/2017' AND '12/31/2017')); CREATE PROCEDURE CH16_Archive_2017_Tournaments_2 AS INSERT INTO Tourney_Matches_Archive SELECT Tourney_Matches.MatchID AS MatchID, Tourney_Matches.TourneyID AS TourneyID, Tourney_Matches.Lanes AS Lanes, Tourney_Matches.OddLaneTeamID AS OddLaneTeamID, Tourney_Matches.EvenLaneTeamID AS EvenLaneTeamID FROM Tourney_Matches WHERE (Tourney_Matches.TourneyID In (SELECT TourneyID FROM Tournaments WHERE TourneyDate BETWEEN '1/1/2017' AND '12/31/2017')); CREATE VIEW CH16_Archive_2017_Tournaments_2_Query AS SELECT Tourney_Matches.MatchID AS MatchID, Tourney_Matches.TourneyID AS TourneyID, Tourney_Matches.Lanes AS Lanes, Tourney_Matches.OddLaneTeamID AS OddLaneTeamID, Tourney_Matches.EvenLaneTeamID AS EvenLaneTeamID FROM Tourney_Matches WHERE (((Tourney_Matches.TourneyID) In (SELECT TourneyID FROM Tournaments WHERE TourneyDate BETWEEN '1/1/2017' AND '12/31/2017'))); CREATE PROCEDURE CH16_Archive_2017_Tournaments_3 AS INSERT INTO Match_Games_Archive SELECT Match_Games.MatchID AS MatchID, Match_Games.GameNumber AS GameNumber, Match_Games.WinningTeamID AS WinningTeamID FROM Match_Games WHERE Match_Games.MatchID IN (SELECT Tourney_Matches.MatchID FROM Tourney_Matches INNER JOIN Tournaments ON Tournaments.TourneyID = Tourney_Matches.TourneyID WHERE Tournaments.TourneyDate BETWEEN '1/1/2017' AND '12/31/2017'); CREATE VIEW CH16_Archive_2017_Tournaments_3_Query AS SELECT Match_Games.MatchID AS MatchID, Match_Games.GameNumber AS GameNumber, Match_Games.WinningTeamID AS WinningTeamID FROM Match_Games WHERE (((Match_Games.MatchID) In (SELECT Tourney_Matches.MatchID FROM Tourney_Matches INNER JOIN Tournaments ON Tournaments.TourneyID = Tourney_Matches.TourneyID WHERE Tournaments.TourneyDate BETWEEN '1/1/2017' AND '12/31/2017'))); CREATE PROCEDURE CH16_Archive_2017_Tournaments_4 AS INSERT INTO Bowler_Scores_Archive SELECT Bowler_Scores.MatchID AS MatchID, Bowler_Scores.GameNumber AS GameNumber, Bowler_Scores.BowlerID AS BowlerID, Bowler_Scores.RawScore AS RawScore, Bowler_Scores.HandiCapScore AS HandiCapScore, Bowler_Scores.WonGame AS WonGame FROM Bowler_Scores WHERE Bowler_Scores.MatchID In (SELECT Tourney_Matches.MatchID FROM Tourney_Matches INNER JOIN Tournaments ON Tournaments.TourneyID = Tourney_Matches.TourneyID WHERE Tournaments.TourneyDate BETWEEN '1/1/2017' AND '12/31/2017'); CREATE VIEW CH16_Archive_2017_Tournaments_4_Query AS SELECT Bowler_Scores.MatchID AS MatchID, Bowler_Scores.GameNumber AS GameNumber, Bowler_Scores.BowlerID AS BowlerID, Bowler_Scores.RawScore AS RawScore, Bowler_Scores.HandiCapScore AS HandiCapScore, Bowler_Scores.WonGame AS WonGame FROM Bowler_Scores WHERE (((Bowler_Scores.MatchID) In (SELECT Tourney_Matches.MatchID FROM Tourney_Matches INNER JOIN Tournaments ON Tournaments.TourneyID = Tourney_Matches.TourneyID WHERE Tournaments.TourneyDate BETWEEN '1/1/2017' AND '12/31/2017'))); CREATE PROCEDURE CH16_Copy_2017_Tournaments_1 AS INSERT INTO Tournaments ( TourneyID, TourneyDate, TourneyLocation ) SELECT Tournaments.TourneyID+25 AS TourneyID, Tournaments.TourneyDate+728 AS TourneyDate, Tournaments.TourneyLocation FROM Tournaments WHERE Tournaments.(TourneyDate) Between '1/1/2017' AND '12/31/2017'; CREATE VIEW CH16_Copy_2017_Tournaments_1_Query AS SELECT Tournaments.TourneyID+25 AS TourneyID, Tournaments.TourneyDate+728 AS TourneyDate, Tournaments.TourneyLocation FROM Tournaments WHERE (((Tournaments.TourneyDate) Between '1/1/2017' AND '12/31/2017')); CREATE PROCEDURE CH16_Copy_2017_Tournaments_2 AS INSERT INTO Tourney_Matches ( TourneyID, Lanes, OddLaneTeamID, EvenLaneTeamID ) SELECT Tourney_Matches.TourneyID+25 AS TourneyID, Tourney_Matches.Lanes, Tourney_Matches.OddLaneTeamID, Tourney_Matches.EvenLaneTeamID FROM Tourney_Matches WHERE Tourney_Matches.TourneyID IN (Select TourneyID FROM Tournaments WHERE Tournaments.(TourneyDate) Between '1/1/2017' AND '12/31/2017'); CREATE VIEW CH16_Copy_2017_Tournaments_2_Query AS SELECT Tourney_Matches.TourneyID+25 AS TourneyID, Tourney_Matches.Lanes, Tourney_Matches.OddLaneTeamID, Tourney_Matches.EvenLaneTeamID FROM Tourney_Matches WHERE Tourney_Matches.TourneyID IN (Select TourneyID FROM Tournaments WHERE Tournaments.(TourneyDate) Between '1/1/2017' AND '12/31/2017'); CREATE PROCEDURE CH17_Delete_Archived_2017_Tournaments_1 AS DELETE Bowler_Scores.* FROM Bowler_Scores WHERE Bowler_Scores.MatchID In (SELECT Tourney_Matches_Archive.MatchID FROM Tourney_Matches_Archive); CREATE VIEW CH17_Delete_Archived_2017_Tournaments_1_Query AS SELECT Bowler_Scores.* FROM Bowler_Scores WHERE (((Bowler_Scores.MatchID) In (SELECT Tourney_Matches_Archive.MatchID FROM Tourney_Matches_Archive))); CREATE PROCEDURE CH17_Delete_Archived_2017_Tournaments_1_WRONG AS DELETE Bowler_Scores.* FROM Bowler_Scores WHERE Bowler_Scores.MatchID In (SELECT Tourney_Matches.MatchID FROM Tourney_Matches INNER JOIN Tournaments ON Tournaments.TourneyID = Tourney_Matches.TourneyID WHERE Tournaments.TourneyDate BETWEEN '1/1/2017' AND '12/31/2017'); CREATE VIEW CH17_Delete_Archived_2017_Tournaments_1_WRONG_Query AS SELECT Bowler_Scores.* FROM Bowler_Scores WHERE (((Bowler_Scores.MatchID) In (SELECT Tourney_Matches.MatchID FROM Tourney_Matches INNER JOIN Tournaments ON Tournaments.TourneyID = Tourney_Matches.TourneyID WHERE Tournaments.TourneyDate BETWEEN '1/1/2017' AND '12/31/2017'))); CREATE PROCEDURE CH17_Delete_Archived_2017_Tournaments_2 AS DELETE Match_Games.* FROM Match_Games WHERE Match_Games.MatchID IN (SELECT Tourney_Matches_Archive.MatchID FROM Tourney_Matches_Archive); CREATE VIEW CH17_Delete_Archived_2017_Tournaments_2_Query AS SELECT Match_Games.* FROM Match_Games WHERE (((Match_Games.MatchID) In (SELECT Tourney_Matches_Archive.MatchID FROM Tourney_Matches_Archive))); CREATE PROCEDURE CH17_Delete_Archived_2017_Tournaments_3 AS DELETE Tourney_Matches.* FROM Tourney_Matches WHERE Tourney_Matches.MatchID In (SELECT MatchID FROM Tourney_Matches_Archive); CREATE VIEW CH17_Delete_Archived_2017_Tournaments_3_Query AS SELECT Tourney_Matches.* FROM Tourney_Matches WHERE (((Tourney_Matches.MatchID) In (SELECT MatchID FROM Tourney_Matches_Archive))); CREATE PROCEDURE CH17_Delete_Archived_2017_Tournaments_4 AS DELETE Tournaments.* FROM Tournaments WHERE (Tournaments.TourneyID IN (SELECT Tournaments_Archive.TourneyID FROM Tournaments_Archive)); CREATE VIEW CH17_Delete_Archived_2017_Tournaments_4_Query AS SELECT Tournaments.* FROM Tournaments WHERE (((Tournaments.TourneyID) In (SELECT Tournaments_Archive.TourneyID FROM Tournaments_Archive))); CREATE PROCEDURE CH17_Delete_Bowlers_No_Games AS DELETE Bowlers.* FROM Bowlers WHERE BowlerGamesBowled=0; CREATE VIEW CH17_Delete_Bowlers_No_Games_Query AS SELECT Bowlers.* FROM Bowlers WHERE (((Bowlers.(BowlerGamesBowled))=0)); CREATE PROCEDURE CH17_Delete_Bowlers_No_Games_Safe AS DELETE Bowlers.* FROM Bowlers WHERE Bowlers.BowlerID NOT IN (SELECT BowlerID FROM Bowler_Scores); CREATE VIEW CH17_Delete_Bowlers_No_Games_Safe_Query AS SELECT Bowlers.* FROM Bowlers WHERE (((Bowlers.BowlerID) Not In (SELECT BowlerID FROM Bowler_Scores))); CREATE PROCEDURE CH17_Delete_Matches_Not_Played AS DELETE Tourney_Matches.* FROM Tourney_Matches WHERE (Tourney_Matches.MatchID Not In (SELECT MatchID FROM Bowler_Scores)) AND (Tourney_Matches.MatchID Not In (SELECT MatchID FROM Match_Games)); CREATE VIEW CH17_Delete_Matches_Not_Played_Query AS SELECT Tourney_Matches.* FROM Tourney_Matches WHERE (Tourney_Matches.MatchID Not In (SELECT MatchID FROM Bowler_Scores)) AND (Tourney_Matches.MatchID Not In (SELECT MatchID FROM Match_Games));
Python
UTF-8
209
3.609375
4
[]
no_license
# Count the number of elements in a given array. def _count(nums: list[int | str]) -> int: N: int = len(nums) if N == 0 or N == 1: return N return 1 + _count(nums[1:]) assert _count([1, 2, 3, 4]) == 4
Java
UTF-8
337
1.53125
2
[]
no_license
package com.google.android.gms.internal.measurement; import java.util.Arrays; final class zzug implements zzui { zzug(zzue arg1) { this(); } private zzug() { super(); } public final byte[] zzc(byte[] arg1, int arg2, int arg3) { return Arrays.copyOfRange(arg1, arg2, arg3 + arg2); } }
Java
UTF-8
2,420
2.484375
2
[]
no_license
package com.devcat.watchdogruntime; import android.util.Log; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.Signature; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import java.util.concurrent.TimeUnit; /** * Created by xpchi on 2018/5/6. */ @Aspect public class WatchDog { /* @Pointcut("execution(@com.devcat.annotations.DebugLog * *(..))") public void method() {} @Around("method()") public Object watchMethod(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { Signature signature = proceedingJoinPoint.getSignature(); Class<?> clz = signature.getDeclaringType(); String methodName = signature.getName(); long startTime = System.nanoTime(); Object result = proceedingJoinPoint.proceed(); long endTime = System.nanoTime(); long time = TimeUnit.NANOSECONDS.toMillis(endTime - startTime); StringBuilder builder = new StringBuilder(); builder.append("Execute ") .append(methodName) .append(" [") .append(time) .append("ms]"); Log.v(asTag(clz), builder.toString()); return result; }*/ @Pointcut("execution(@com.devcat.annotations.DebugLog * *(..))") public void method() {} @Around("method()") public Object aroundMethod2(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { Signature signature = proceedingJoinPoint.getSignature(); Class<?> clz = signature.getDeclaringType(); String methodName = signature.getName(); long startTime = System.nanoTime(); Object result = proceedingJoinPoint.proceed(); long endTime = System.nanoTime(); long time = TimeUnit.NANOSECONDS.toMillis(endTime - startTime); StringBuilder builder = new StringBuilder(); builder.append("Execute ") .append(methodName) .append(" [") .append(time) .append("ms]"); Log.i(asTag(clz), builder.toString()); return result; } private String asTag(Class<?> clz) { if (clz.isAnonymousClass()) { // 该类是匿名内部类 asTag(clz.getEnclosingClass()); // 获取定义该成员内部类的类 } return clz.getSimpleName(); } }
Markdown
UTF-8
6,200
2.640625
3
[]
no_license
# Membership Plans AgileVentures helps teams of developers get together to work on open source charity IT projects. In the [free plan](/free) developers get the use of AgileVentures Slack. <div> <table class="tg" style=" border-collapse: collapse; border-spacing: 0; border-color: #aaa; width: 100%; " > <tbody> <tr style="background-color: #ee7335;"> <td style="width: 350px;"></td> <th style=" width: 65px; font-family: Arial, sans-serif; font-size: 14px; padding: 8px; " > <div style="text-align: center;"> <a href="/free" style="color: white;">Free Access</a> </div> </th> <th style=" width: 60px; font-family: Arial, sans-serif; font-size: 14px; padding: 8px; " > <div style="text-align: center;"> <a href="/associate" style="color: white;" >Associate Membership</a > </div> <div style="text-align: center;">(&#xa3; 5/month)</div> </th> </tr> <tr> <td style=" font-family: Arial, sans-serif; font-size: 14px; padding: 8px; " > <a href="/free">Access to AgileVentures Slack</a> </td> <td style=" text-align: center; padding: 8px; border-left: solid 1px #ddd; " > <img width="32" src="https://dl.dropbox.com/s/h3vg4hcvhkjc1ks/teal-circle-checkmark-128.png" alt="Circle checkmark icon" title="Circle checkmark" /> </td> <td style=" text-align: center; padding: 8px; border-left: solid 1px #ddd; border-right: solid 1px #ddd; " > <img width="32" src="https://dl.dropbox.com/s/h3vg4hcvhkjc1ks/teal-circle-checkmark-128.png" alt="Circle checkmark icon" title="Circle checkmark" /> </td> </tr> <tr> <td style=" font-family: Arial, sans-serif; font-size: 14px; background: #efefef; padding: 8px; " > <a href="/free">Access to AgileVentures Community events, workshops and training </a> </td> <td style=" text-align: center; background: #efefef; padding: 8px; border-left: solid 1px #ddd; " > <img width="32" src="https://dl.dropbox.com/s/h3vg4hcvhkjc1ks/teal-circle-checkmark-128.png" alt="Circle checkmark icon" title="Circle checkmark" /> </td> <td style=" text-align: center; background: #efefef; padding: 8px; border-left: solid 1px #ddd; border-right: solid 1px #ddd; " > <img width="32" src="https://dl.dropbox.com/s/h3vg4hcvhkjc1ks/teal-circle-checkmark-128.png" alt="Circle checkmark icon" title="Circle checkmark" /> </td> </tr> <tr> <td style=" font-family: Arial, sans-serif; font-size: 14px; padding: 8px; " > <a href="/associate">Access to <strong>AgileVentures Edge</strong> Training and Mob sessions.</a> </td> <td style=" text-align: center; padding: 8px; border-left: solid 1px #ddd; " > </td> <td style=" text-align: center; padding: 8px; border-left: solid 1px #ddd; border-right: solid 1px #ddd; " > <img width="32" src="https://dl.dropbox.com/s/h3vg4hcvhkjc1ks/teal-circle-checkmark-128.png" alt="Circle checkmark icon" title="Circle checkmark" /> </td> </tr> <tr> <td style=" font-family: Arial, sans-serif; font-size: 14px; padding: 8px; " > <a href="/free">Project logistics advice and support</a> </td> <td style=" text-align: center; padding: 8px; border-left: solid 1px #ddd; " > <img width="32" src="https://dl.dropbox.com/s/h3vg4hcvhkjc1ks/teal-circle-checkmark-128.png" alt="Circle checkmark icon" title="Circle checkmark" /> </td> <td style=" text-align: center; padding: 8px; border-left: solid 1px #ddd; border-right: solid 1px #ddd; " > <img width="32" src="https://dl.dropbox.com/s/h3vg4hcvhkjc1ks/teal-circle-checkmark-128.png" alt="Circle checkmark icon" title="Circle checkmark" /> </td> </tr> <tr> <td style=" font-family: Arial, sans-serif; font-size: 14px; background: #efefef; padding: 8px; " > <a href="/associate" >Financially support our mission</a> </td> <td style=" text-align: center; background: #efefef; padding: 8px; border-left: solid 1px #ddd; " ></td> <td style=" text-align: center; background: #efefef; padding: 8px; border-left: solid 1px #ddd; border-right: solid 1px #ddd; " > <img width="32" src="https://dl.dropbox.com/s/h3vg4hcvhkjc1ks/teal-circle-checkmark-128.png" alt="Circle checkmark icon" title="Circle checkmark" /> </td> </tr> <tr> <td style=" font-family: Arial, sans-serif; font-size: 14px; padding: 8px; " > <a href="/associate">Voting rights in AgileVentures general meetings </a ><br />(help decide AgileVentures Charity Policy and direction) </td> <td style=" text-align: center; padding: 8px; border-left: solid 1px #ddd; " ></td> <td style=" text-align: center; padding: 8px; border-left: solid 1px #ddd; border-right: solid 1px #ddd; " > <img width="32" src="https://dl.dropbox.com/s/h3vg4hcvhkjc1ks/teal-circle-checkmark-128.png" alt="Circle checkmark icon" title="Circle checkmark" /> </td> </tr> <tr> <td style=" font-family: Arial, sans-serif; font-size: 14px; padding: 8px; " > <a href="/opportunities">Hold an official position with Agile Ventures</a > </td> <td style=" text-align: center; padding: 8px; border-left: solid 1px #ddd; " ></td> <td style=" text-align: center; padding: 8px; border-left: solid 1px #ddd; border-right: solid 1px #ddd; " > <img width="32" src="https://dl.dropbox.com/s/h3vg4hcvhkjc1ks/teal-circle-checkmark-128.png" alt="Circle checkmark icon" title="Circle checkmark" /> </td> </tr> <tr> <td style=" font-family: Arial, sans-serif; font-size: 14px; padding: 8px; background: #efefef; " > <span class="btn btn-primary btn-block" style=" background-color: #ee7335; border-color: #ee7335; padding: 5px; width: 350px; " ><a href="/sponsorship"></a ></span> </td> <td style=" text-align: center; font-family: Arial, sans-serif; font-size: 14px; padding: 8px; background: #efefef; border-left: solid 1px #ddd; color: white; " > <span class="btn btn-primary btn-block" style=" background-color: #ee7335; border-color: #ee7335; padding: 5px; " ><a href="/users/sign_up" style="color: white;" ><b>Get Started</b></a ></span > </td> <td style=" text-align: center; font-family: Arial, sans-serif; font-size: 14px; padding: 8px; background: #efefef; border-left: solid 1px #ddd; border-right: solid 1px #ddd; " > <span class="btn btn-primary btn-block" style=" color: white; background-color: #ee7335; border-color: #ee7335; padding: 5px; " > <a href="/subscriptions/new?plan=associate" style="color: white;" ><b>Get Started</b></a ></span > </td> </tr> </tbody> </table> </div>
Python
UTF-8
2,123
3.03125
3
[]
no_license
import re batRegex = re.compile(r'Bat(wo)?man') mo=batRegex.search('The Adventures of Batman') print(mo.group()) mo=batRegex.search('The Adventures of Batwoman') print(mo.group()) mo=batRegex.search('The Adventures of Batwowowoman') print(mo==None) phoneRegex=re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') mo=phoneRegex.search('My phone number is 415-555-1234. Call me tomorrow.') print(mo.group()) mo=phoneRegex.search('My phone number is 555-1234. Call me tomorrow.') print(mo==None) phoneRegex=re.compile(r'(\d\d\d-)?\d\d\d-\d\d\d\d') mo=phoneRegex.search('My phone number is 555-1234. Call me tomorrow.') print(mo.group()) mo=phoneRegex.search('My phone number is 415-555-1234. Call me tomorrow.') print(mo.group()) batRegex=re.compile(r'Bat(wo)*man') mo=batRegex.search('The Adventures of Batman') print(mo.group()) mo=batRegex.search('The Adventures of Batwoman') print(mo.group()) mo=batRegex.search('The Adventures of Batwowowoman') print(mo.group()) batRegex=re.compile(r'Bat(wo)+man') mo=batRegex.search('The Adventures of Batman') print(mo==None) mo=batRegex.search('The Adventures of Batwoman') print(mo.group()) mo=batRegex.search('The Adventures of Batwowowoman') print(mo.group()) regex=re.compile(r'\+\*\?') mo=regex.search('O learned about +*? regex syntax') print(mo.group()) regex=re.compile(r'(\+\*\?)+') mo=regex.search('O learned about +*?+*?+*?+*? regex syntax') print(mo.group()) haRegex = re.compile(r'(Ha){3}') mo=haRegex.search('He said "HaHaHa"') print(mo.group()) haRegex = re.compile(r'HaHaHa') mo=haRegex.search('He said "HaHaHa"') print(mo.group()) phoneRegex=re.compile(r'((\d\d\d-)?\d\d\d-\d\d\d\d(,)?){3}') mo=phoneRegex.search('My numbers are 415-5555-1234,555-4242,212-555-0000') print(mo.group()) haRegex=re.compile(r'(Ha){3,5}') mo=haRegex.search('He said "HaHaHa"') print(mo.group()) mo=haRegex.search('He said "HaHaHaHa"') print(mo.group()) mo=haRegex.search('He said "HaHaHaHaHa"') print(mo.group()) digitRegex=re.compile(r'(\d){3,5}') mo=digitRegex.search('1234567890') print(mo.group()) digitRegex=re.compile(r'(\d){3,5}?') mo=digitRegex.search('1234567890') print(mo.group())
PHP
UTF-8
4,873
2.78125
3
[ "MIT" ]
permissive
<?php class TheBigDB { public $version = "0.2.0"; public $default_configuration = array( "api_key" => null, "use_ssl" => false, "verify_ssl_certificates" => false, # Not yet implemented "before_request_execution" => null, # Not yet implemented "after_request_execution" => null, # Not yet implemented "api_host" => "api.thebigdb.com", "api_port" => 80, "api_version" => "1", ); public $configuration = array(); public $client_user_agent = array(); public $user_agent = null; public $response = null; function __construct($options = array()){ # Set basic configuration $this->configuration = array_merge($this->default_configuration, $options); $this->configuration["api_port"] = ($this->configuration["use_ssl"] === true) ? 443 : 80; if(isset($options["api_port"])){ $this->configuration["api_port"] = $options["api_port"]; } # to be able to use shortcuts like $thebigdb->api_key = "foobar"; foreach($this->configuration as $key => $value){ $this->$key = $value; } # Prepare standard requests headers $this->user_agent = "TheBigDB PHPWrapper/{$this->version}"; $this->client_user_agent = json_encode(array( "publisher" => "thebigdb", "version" => $this->version, "language" => "php", "language_version" => PHP_VERSION )); } ############################## # Shortcuts to actions on Statements ############################## # GET function search($nodes, $other_params = array()){ $params = array_merge(array("nodes" => $nodes), $other_params); return $this->execute_request("get", "/statements/search", $params); } function show($id, $other_params = array()){ $params = array_merge(array("id" => $id), $other_params); return $this->execute_request("get", "/statements/show", $params); } # POST function create($nodes, $other_params = array()){ $params = array_merge(array("nodes" => $nodes), $other_params); return $this->execute_request("post", "/statements/create", $params); } function upvote($id, $other_params = array()){ $params = array_merge(array("id" => $id), $other_params); return $this->execute_request("post", "/statements/upvote", $params); } function downvote($id, $other_params = array()){ $params = array_merge(array("id" => $id), $other_params); return $this->execute_request("post", "/statements/downvote", $params); } ############################## # Other actions ############################## function user($action, $params){ return $this->execute_request("get", "/users/".$action, $params); } ############################## # Engine ############################## function execute_request($method, $path, $params = array()){ $method = strtolower($method); if($this->use_ssl){ $scheme = "https"; } else { $scheme = "http"; } $url = "{$scheme}://{$this->api_host}:{$this->api_port}"; $url = $url."/v{$this->api_version}"; if(substr($path, 0, 1) != "/"){ $path = "/{$path}"; } $url = $url.$path; if($this->api_key){ $params["api_key"] = $this->api_key; } if($method == "get"){ $url = $url."?".$this->serialize_query_params($params); } $curl = curl_init($url); if($method == "post"){ curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $params); } curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); if($this->use_ssl){ curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); } curl_setopt($curl, CURLOPT_HTTPHEADER, array("User-Agent: {$this->user_agent}", "X-TheBigDB-Client-User-Agent: {$this->client_user_agent}")); $json_response = curl_exec($curl); curl_close($curl); $this->response = json_decode($json_response); return $this->response; } # $this->serialize_query_params(array("house" => "brick and mortar", "animals" => array("cat", "dog"), "computers" => array("cool" => true, "drives" => array("hard", "flash")))) # => house=brick%20and%20mortar&animals%5B0%5D=cat&animals%5B1%5D=dog&computers%5Bcool%5D=1&computers%5Bdrives%5D%5B0%5D=hard&computers%5Bdrives%5D%5B1%5D=flash # which will be read by the server as: # => house=brick%20and%20mortar&animals[]=cat&animals[]=dog&computers[cool]=1&computers[drives][]=hard&computers[drives][]=flash function serialize_query_params($params, $prefix = null){ $ret = array(); foreach($params as $key => $value){ $param_key = $prefix ? $prefix."[".$key."]" : $key; if(is_array($value) || is_object($value)){ $ret[] = $this->serialize_query_params($value, $param_key); } else { $ret[] = urlencode($param_key)."=".str_replace("+", "%20", urlencode($value)); } } return implode("&", $ret); } } ?>
Markdown
UTF-8
510
3.3125
3
[ "MIT" ]
permissive
# Hashmap LEFT JOIN The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the right table. This means that if the ON clause matches 0 (zero) records in the right table; the join will still return a row in the result, but with NULL in each column from the right table. ## Challenge Write a function that LEFT JOINs two hashmaps into a single data structure. ## Approach & Efficiency Big O time => O(n) Big O space => O(n) ## Solution ![whiteboard](../../assets/leftJoin.jpg)
TypeScript
UTF-8
68
2.515625
3
[]
no_license
export type Item = { id: number; name:string; done: boolean; }
JavaScript
UTF-8
1,803
2.546875
3
[]
no_license
describe("App", function() { var app; beforeEach(function() { app = new App($); }); it("context can be initialized with context path", function () { expect(app.context).not.toBeDefined(); expect(app.context).toBeUndefined(); expect(app.context).toBeNothing(); expect(app.context).not.toBeSomething(); app.init('/jsstyle/'); expect(app.context).toEqual('/jsstyle/'); expect(app.context).toBeDefined(); expect(app.context).not.toBeUndefined(); expect(app.context).toBeSomething(); expect(app.context).not.toBeNothing(); expect(app.context).toBeSomething(); expect(app.context).not.toBeFunction(); }); it("context can be set many times", function () { app.init('/jsstyle/'); expect(app.context).toEqual('/jsstyle/'); app.init('/jsstyle-css/'); expect(app.context).toEqual('/jsstyle-css/'); }); describe("ajax calls returns", function() { var successFn, errorFn, ajax; beforeEach(function () { successFn = jasmine.createSpy("successFn"); errorFn = jasmine.createSpy("errorFn"); jQuery.ajax = spyOn(jQuery, "ajax").andCallFake( function (options) { if(/.*success.*/.test(options.url)) { options.success(); } else { options.error(); } } ); }); it("success", function () { app.ajax("success/url", successFn, errorFn); expect(successFn).toHaveBeenCalled(); }); it("error response", function () { app.ajax("error/url", successFn, errorFn); expect(errorFn).toHaveBeenCalled(); }); }); afterEach(function () { app = null; }); });
C++
UTF-8
1,018
3
3
[]
no_license
#include"tree.h" #include<vector> using namespace std; class Solution0113 { public: vector<vector<int>> pathSum(TreeNode* root, int targetSum) { vector<vector<int>> result; vector<int> partResult; if(root == nullptr) { return result; } dfs(root, targetSum, partResult, result); return result; } void dfs(TreeNode* root, int targetSum, vector<int>& partResult, vector<vector<int>>& result) { partResult.push_back(root->val); if(root->left == nullptr && root->right == nullptr) { if (root->val == targetSum) { result.push_back(partResult); } return; } if (root->left != nullptr) { dfs(root->left, targetSum - root->val, partResult, result); partResult.pop_back(); } if (root->right != nullptr) { dfs(root->right, targetSum - root->val, partResult, result); partResult.pop_back(); } } };
Shell
UTF-8
1,468
3.21875
3
[ "MIT" ]
permissive
#!/bin/bash #set -v # usage: perf_record_benchmark v1 export EXE_DIR=../build/threads/ export BENCHMARK_BINARY=queue_bench_v${1} export PERFTOOLS_DIR=../../FlameGraph function fecho { echo $1 >> perf_run.out } function run_with_threads { nice -n -20 ${EXE_DIR}/${BENCHMARK_BINARY} -m 1000000 -r 5000 -n $1 2>&1 >> perf_run.out & export PID=$(echo $!) echo "got PID=$PID" sleep 1 ps -leaf | egrep 'PID|queue_bench' | grep -v grep echo "perf stat CPU 1,2 for 10 seconds..." timeout -s 2 5 perf stat -d --cpu 1,2 -A echo "perf record for 10 seconds..." echo "writing cpu call graph to call_graph.out" perf record -s -F 99 -p $PID -g -- sleep 10 perf script | ${PERFTOOLS_DIR}/stackcollapse-perf.pl > out.perf-folded make_call_graph.py out.perf-folded > call_graph.out echo "stopping $PID" kill $PID perf report } COL_HEADER="|num threads| rate (msgs/sec)| total msg count | latency avg (ns) | latency stddev ns| latency sigma ns | latency 2sigma ns | latency 3sigma ns | hist 0123456789ABCDEFGHIJKLMNOPQRSTUV" SEPARATOR="|-----------|----------------|-----------------|------------------|------------------|------------------|-------------------|-------------------|--------------------------------------" fecho "" fecho "# Running Queue Latency Benchmark #1 (algorithm = std::queue with std::mutex)" fecho "" lscpu >> perf_run.out fecho $COL_HEADER fecho $SEPARATOR run_with_threads 2
Java
UTF-8
3,054
2.703125
3
[]
no_license
package ru.list.victor_90.study.myapplication.design; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import org.json.JSONException; import java.io.IOException; import java.util.ArrayList; import ru.list.victor_90.study.myapplication.R; import ru.list.victor_90.study.myapplication.logic.*; public class MainActivity extends Activity implements View.OnClickListener { MyJSONParser parser; EditText Id; TextView txtField; CheckBox checkBox; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); checkBox = (CheckBox) findViewById(R.id.checkBox); Id = (EditText) findViewById(R.id.edit_id); txtField = (TextView) findViewById(R.id.txt_main); findViewById(R.id.button).setOnClickListener(this); // listener for checkbox checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked){ Id.setEnabled(true); } else { Id.setEnabled(false); } } }); parseFromFile(); } private void parseFromFile() { try { parser = new MyJSONParser(new JSONFromFile().getJsonObject()); parser.parse(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } @Override public void onClick(View v) { if(parser == null){ Toast.makeText(MainActivity.this,"Не найден файл " + JSONFromFile.path, Toast.LENGTH_SHORT).show(); return; } int id = 0; txtField.setText(""); // берем данные из парселя String name = parser.getName(); ArrayList<People> people= parser.getPeople(); // если показывать одну запись, то и выводим одну запись if(checkBox.isChecked()) { id = Integer.parseInt(Id.getText().toString()); try { txtField.append(name + "\n"); txtField.append(people.get(id).toString()); } catch (IndexOutOfBoundsException e) { txtField.setText("Запись не найдена"); return; } } else { // иначе выводим все записи txtField.append(name + "\n"); for (People man : people){ txtField.append(man.toString()); txtField.append("--------------\n"); } } } }
C#
UTF-8
3,097
2.640625
3
[ "MIT" ]
permissive
using System; using QuickGraph.Unit; namespace QuickGraph.Algorithms.MaximumFlow { [TypeFixture(typeof(IMutableVertexAndEdgeListGraph<string, Edge<string>>))] [TypeFactory(typeof(AdjacencyGraphFactory))] [TypeFactory(typeof(BidirectionalGraphFactory))] public class AllVerticesGraphAugmentorAlgorithmTest { private AllVerticesGraphAugmentorAlgorithm<string, Edge<string>> augmentor; public void SetUp(IMutableVertexAndEdgeListGraph<string, Edge<string>> g) { this.augmentor = new AllVerticesGraphAugmentorAlgorithm<string, Edge<string>>( g, new StringVertexFactory(), new EdgeFactory<string>() ); } [TearDown] public void TearDown() { if (this.augmentor != null) { this.augmentor.Rollback(); this.augmentor = null; } } [Test] public void AddSuperSourceAndSink(IMutableVertexAndEdgeListGraph<string, Edge<string>> g) { SetUp(g); int vertexCount = g.VertexCount; this.augmentor.Compute(); Assert.AreEqual(vertexCount + 2, g.VertexCount); Assert.IsTrue(g.ContainsVertex(this.augmentor.SuperSource)); Assert.IsTrue(g.ContainsVertex(this.augmentor.SuperSink)); } [Test] public void AddAndRemove(IMutableVertexAndEdgeListGraph<string, Edge<string>> g) { SetUp(g); int vertexCount = g.VertexCount; int edgeCount = g.EdgeCount; this.augmentor.Compute(); this.augmentor.Rollback(); Assert.AreEqual(g.VertexCount, vertexCount); Assert.AreEqual(g.EdgeCount, edgeCount); } [Test] public void AddAndVerifySourceConnected(IMutableVertexAndEdgeListGraph<string, Edge<string>> g) { SetUp(g); this.augmentor.Compute(); foreach (string v in g.Vertices) { if (v == this.augmentor.SuperSource) continue; if (v == this.augmentor.SuperSink) continue; Assert.IsTrue(g.ContainsEdge(this.augmentor.SuperSource, v)); } } [Test] public void AddAndVerifySinkConnected(IMutableVertexAndEdgeListGraph<string, Edge<string>> g) { SetUp(g); this.augmentor.Compute(); foreach (string v in g.Vertices) { if (v == this.augmentor.SuperSink) continue; if (v == this.augmentor.SuperSink) continue; Assert.IsTrue(g.ContainsEdge(v, this.augmentor.SuperSink)); } } private sealed class StringVertexFactory : IVertexFactory<string> { private int id = 0; public string CreateVertex() { return "Super"+(++id).ToString(); } } } }
Python
UTF-8
498
3.203125
3
[ "Apache-2.0" ]
permissive
import glob for imageName in glob.glob('*.txt'): newList = [] f = open(imageName) for line in f.readlines(): tempList = line.split() newTempList = [tempList[0], tempList[5], tempList[1], tempList[2], tempList[3], tempList[4]] newList.append(newTempList) f.close w = open(imageName, 'w') for line in newList: newString = line[0] + ' ' + line[1] + ' ' + line[2] + ' ' + line[3] + ' ' + line[4] + ' ' + line[5] + '\n' w.write(newString)
JavaScript
UTF-8
3,487
2.96875
3
[]
no_license
var valueOne = ""; var valueTwo = ""; var runningTotal = ""; //var lastDigit = "0"; //var currentDigit = ""; function addValue(number) { var newNumber = number; if (runningTotal == "0") { valueTwo = ""; } //lastDigit = currentDigit; //console.log("lastDigit: " + lastDigit); switch (newNumber) { case "0": valueTwo += "0"; runningTotal = valueTwo; break; case "1": valueTwo += "1"; runningTotal = valueTwo; break; case "2": valueTwo += "2"; runningTotal = valueTwo; break; case "3": valueTwo += "3"; runningTotal = valueTwo; break; case "4": valueTwo += "4"; runningTotal = valueTwo; break; case "5": valueTwo += "5"; runningTotal = valueTwo; break; case "6": valueTwo += "6"; runningTotal = valueTwo; break; case "7": valueTwo += "7"; runningTotal = valueTwo; break; case "8": valueTwo += "8"; runningTotal = valueTwo; break; case "9": valueTwo += "9"; runningTotal = valueTwo; break; case "10": //stops multiple decimal points from being added to string if (valueTwo.indexOf('.') <= -1) { //adds zero before decimal if the starting value is 0 if ($("#valueTwoNumber").html() == "0") { valueTwo += "0."; } else { valueTwo += "."; } } else { valueTwo += "0"; } runningTotal = valueTwo; break; case "11": var removeValue = valueTwo.length; removeValue = removeValue -1; console.log(removeValue); valueTwo = valueTwo.substr(0,removeValue); if (removeValue < 1) { valueTwo = "0"; } runningTotal = valueTwo; break; case "12": valueTwo = "0"; runningTotal = valueTwo; break; case "13": if ($("#valueTwoNumber").html() == "0") { valueTwo = "0"; } break; case "14": if ($("#valueTwoNumber").html() == "0") { valueTwo = "0"; } break; default: break; } //console.log("currentDigit: " + currentDigit); console.log("runningTotal: " + runningTotal); $("#valueTwoNumber").html(valueTwo); } function copyValue() { } $(function () { //$("#11").css("background-color", "rgb(228, 193, 39)").css("color","rgb(236, 236, 236)"); //$("#12").css("background-color", "tomato").css("color", "rgb(236, 236, 236)"); var clickSound = new Audio(); clickSound.src = "./click.mp3"; $(".clickSound").mousedown(function(){ //clickSound.load(); //clickSound.play(); /* sound function needs to stop sound when another key is clicked */ }); $(".keyCap").on("click", function(){ addValue(this.id); }); }); //fixed
Java
UTF-8
1,872
2.609375
3
[ "MIT" ]
permissive
/** * Created by MomoLuaNative. * Copyright (c) 2020, Momo Group. All rights reserved. * * This source code is licensed under the MIT. * For the full copyright and license information,please view the LICENSE file in the root directory of this source tree. */ package com.xfy.shell; import java.io.*; /** * Created by Xiong.Fangyu on 2020-02-12 */ public class FileUtils { public static final int BUFFER_SIZE = 8 * 1024; //8k private static File currentJarPath; public static File getCurrentJarPath() { if (currentJarPath == null) { File jar = new File(FileUtils.class.getProtectionDomain().getCodeSource().getLocation().getPath()); currentJarPath = jar.getParentFile(); } return currentJarPath; } public static byte[] readBytes(File f) throws IOException { try (InputStream inputStream = new FileInputStream(f)) { return toBytes(inputStream); } } public static void closeQuietly(Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (Throwable t) {} } } public static byte[] toBytes(final InputStream input) { byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead; try (ByteArrayOutputStream output = new ByteArrayOutputStream()) { while ((bytesRead = input.read(buffer)) != -1) { output.write(buffer, 0, bytesRead); } return output.toByteArray(); } catch (Exception e) { return null; } } public static void writeFile(File file, byte[] data) throws Exception { try (BufferedOutputStream dest = new BufferedOutputStream(new FileOutputStream(file), BUFFER_SIZE)) { dest.write(data); dest.flush(); } } }
Java
UTF-8
3,043
2.203125
2
[]
no_license
package com.landasoft.demo.cloudfoundry.springcloudclient.controller; import com.landasoft.demo.cloudfoundry.springcloudclient.feign.ClientBackendFeign; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import java.util.Date; /** * @author 伍林云 * @date 2019/8/5 18:45 */ @RestController @Api(description = "客户端用户管理接口") public class HelloController { private static final Logger logger = LoggerFactory.getLogger(HelloController.class); @Value("${custom.restURL}") private String restURL; @Autowired @Qualifier("loadBalancedRestTemplate") private RestTemplate loadBalancedRestTemplate; @Autowired @Qualifier("originRestTemplate") private RestTemplate originRestTemplate; @Autowired private ClientBackendFeign springCloudClientBackendFeign; @GetMapping("/") @ApiOperation(value = "spring-cloud-client接口信息") public String call(){ logger.info("calling spring-cloud-client-backend"); return "hello spring-cloud-client-backend "+new Date().toString(); } /** * 直接调用接口地址 * @param id * @return */ @ApiOperation(value = "直接调用spring-cloud-client-backend接口地址") @GetMapping("/call/{id}") public String callHome(@PathVariable String id){ logger.info("calling from spring-cloud-client-backend"); String result= this.originRestTemplate.getForObject(restURL + id, String.class); return result+" world"; } /** * 通过feign调用接口地址 * @param id * @return */ @ApiOperation(value = "通过feign调用接口地址") @GetMapping("/call_f/{id}") public String callHomeF(@PathVariable String id){ logger.info("calling from spring-cloud-client-backend by feign"); String result = springCloudClientBackendFeign.call(id); return result+" world by feign "; } /** * 通过注册中心的服务名称调用接口 * @param id * @return */ @ApiOperation(value = "通过注册中心的服务名称调用接口") @GetMapping("/call_e/{id}") public String callHomeE(@PathVariable String id){ logger.info("calling from spring-cloud-client-backend by eureka"); //spring-cloud-client-backend的值为被调用服务中配置的spring.application.name的值 String result= this.loadBalancedRestTemplate.getForObject("http://spring-cloud-client-backend/call/" + id, String.class); return result+" world by eureka"; } }
Swift
UTF-8
3,619
3.015625
3
[]
no_license
// // DefaultAPI.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // import Foundation import Alamofire open class DefaultAPI { /** - parameter latOrg: (query) Latitude of origin location - parameter lngOrg: (query) Longitude of origin location - parameter seats: (query) Number of seats the user wishes to book - parameter walkingDistance: (query) Distance the user is willing to walk to and from the ride - parameter completion: completion handler to receive the data and the error objects */ open class func getvehiclesGet(latOrg: Double, lngOrg: Double, seats: Int, walkingDistance: Int, completion: @escaping ((_ data: [RideType]?,_ error: Error?) -> Void)) { getvehiclesGetWithRequestBuilder(latOrg: latOrg, lngOrg: lngOrg, seats: seats, walkingDistance: walkingDistance).execute { (response, error) -> Void in completion(response?.body, error) } } /** - GET /getvehicles - The getVehicles endpoint returns information about the available vehicles, that fulfils the users' requirements that they have inserted. The response includes the categories of vehicles avaialable, the price and other details about each vehicle, and lists the vehicles in the proper display order. - examples: [{contentType=application/json, example=[ { "ride_type" : "express", "displayName" : "Express", "price" : 3.08, "pickup" : 993, "eta" : 1000 }, { "ride_type" : "comfort", "displayName" : "Comfort", "price" : 5.35, "pickup" : 990, "eta" : 996 }, { "ride_type" : "luxury", "displayName" : "Luxury", "price" : 8.7, "pickup" : 991, "eta" : 996 }, { "ride_type" : "electric", "displayName" : "Electric", "price" : 3, "pickup" : 989, "eta" : 996 }, { "ride_type" : "suv_express", "displayName" : "SUV Express", "price" : 2.8, "pickup" : 990, "eta" : 1000 }, { "ride_type" : "suv_comfort", "displayName" : "SUV Comfort", "price" : 3.08, "pickup" : 991, "eta" : 998 }, { "ride_type" : "suv_luxury", "displayName" : "SUV Luxury", "price" : 4.5, "pickup" : 988, "eta" : 998 }, { "ride_type" : "suv_electric", "displayName" : "SUV Electric", "price" : 3.58, "pickup" : 989, "eta" : 998 }, { "ride_type" : "wav", "displayName" : "WAV", "price" : 5.6, "pickup" : 1000, "eta" : 1020 } ]}] - parameter latOrg: (query) Latitude of origin location - parameter lngOrg: (query) Longitude of origin location - parameter seats: (query) Number of seats the user wishes to book - parameter walkingDistance: (query) Distance the user is willing to walk to and from the ride - returns: RequestBuilder<[RideType]> */ open class func getvehiclesGetWithRequestBuilder(latOrg: Double, lngOrg: Double, seats: Int, walkingDistance: Int) -> RequestBuilder<[RideType]> { let path = "/getvehicles" let URLString = SwaggerClientAPI.basePath + path let parameters: [String:Any]? = nil var url = URLComponents(string: URLString) url?.queryItems = APIHelper.mapValuesToQueryItems([ "latOrg": latOrg, "lngOrg": lngOrg, "seats": seats.encodeToJSON(), "walkingDistance": walkingDistance.encodeToJSON() ]) let requestBuilder: RequestBuilder<[RideType]>.Type = SwaggerClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } }
JavaScript
UTF-8
218
2.625
3
[]
no_license
export function phoneReg(phone) { var reg = /^[1][3,4,5,7,8][0-9]{9}$/; return reg.test(phone) } export function passWordReg(psw){ var reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,21}$/; return reg.test(psw) }
PHP
UTF-8
1,158
2.515625
3
[ "MIT" ]
permissive
<?php namespace NottsDigital\Api\Tests; use PHPUnit\Framework\TestCase; class GroupConfigValidationTest extends TestCase { /** * @var array */ private $groupConfig; protected function setUp(): void { $groupsJson = \file_get_contents(dirname(__DIR__).'/groups.json'); $this->groupConfig = \json_decode($groupsJson, true); } /** * @test * @dataProvider serviceDataProvider * @param $service */ public function group_config_includes_supported_service($service): void { static::assertArrayHasKey($service, $this->groupConfig); } /** * @test */ public function group_config_supports_two_services(): void { static::assertCount(2, $this->groupConfig); } /** * @test */ public function meetup_groups_include_group_url_name(): void { foreach ($this->groupConfig['meetups'] as $meetup) { static::assertArrayHasKey('group_urlname', $meetup); } } public function serviceDataProvider(): array { return [ ['meetups'], ['ti.to'] ]; } }
Python
UTF-8
9,265
2.71875
3
[ "MIT" ]
permissive
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2021 Edward Higgins <ed.higgins@york.ac.uk> # # Distributed under terms of the MIT license. """ TRAJECTORIES - Trajectory construction and manipulation module Description: trajectories.py contains the Trajectory class containing information about spot trajectories across multiple frames, along with the routines involved in locating and extending the trajectories. Contains: class Trajectory function build_trajectories function read_trajectories function write_trajectories Author: Edward Higgins Version: 0.2.0 """ import csv import sys import os import numpy as np from spots import Spots class Trajectory: def __init__(self, id, spots, spot_id): self.id = id self.start_frame = spots.frame self.end_frame = spots.frame self.path = [spots.positions[spot_id, :]] self.intensity = [spots.spot_intensity[spot_id]] self.bg_intensity = [spots.bg_intensity[spot_id]] self.snr = [spots.snr[spot_id]] self.length = 1 self.stoichiometry = 0 self.converged = [spots.converged[spot_id]] self.linked_traj = None self.width = [spots.width[spot_id]] def extend(self, spots, spot_id): if spots.frame > self.end_frame + 1: sys.exit("ERROR: Cannot extend a spot over multiple frames") self.end_frame = spots.frame self.path.append(spots.positions[spot_id, :]) self.intensity.append(spots.spot_intensity[spot_id]) self.bg_intensity.append(spots.bg_intensity[spot_id]) self.converged.append(spots.converged[spot_id]) self.snr.append(spots.snr[spot_id]) self.length += 1 def build_trajectories(all_spots, params): trajectories = [] traj_num = 0 # Create a trajectory for all spots in the first frame for i in range(all_spots[0].num_spots): trajectories.append(Trajectory(traj_num, all_spots[0], i)) traj_num += 1 # Construct trajectories for the rest of the frames for frame in range(1, len(all_spots)): assigned_spots = [] for spot in range(all_spots[frame].num_spots): close_candidates = [] for candidate in trajectories: if candidate.end_frame != frame - 1: continue candidate_dist = np.linalg.norm( all_spots[frame].positions[spot, :] - candidate.path[-1] ) if candidate_dist < params.max_displacement: close_candidates.append(candidate) if len(close_candidates) == 0: trajectories.append(Trajectory(traj_num, all_spots[frame], spot)) traj_num += 1 elif len(close_candidates) == 1: close_candidates[0].extend(all_spots[frame], spot) else: trajectories.append(Trajectory(traj_num, all_spots[frame], spot)) traj_num += 1 filtered_trajectories = list(filter(lambda x: x.length >= params.min_traj_len, trajectories)) actual_traj_num = 0 for traj in filtered_trajectories: traj.id = actual_traj_num actual_traj_num += 1 return filtered_trajectories def write_trajectories(trajectories, filename): f = open(filename, "w") f.write(f"trajectory\tframe\tx\ty\tspot_intensity\tbg_intensity\tSNR\tconverged\twidthx\twidthy\n") for traj in trajectories: for frame in range(traj.start_frame, traj.end_frame + 1): i = frame - traj.start_frame f.write( f"{traj.id}\t{frame}\t{traj.path[i][0]}\t{traj.path[i][1]}\t{traj.intensity[i]}\t{traj.bg_intensity[i]}\t{traj.snr[i]}\t{traj.converged[i]}\t{traj.width[0][0]}\t{traj.width[0][1]}\n" ) f.close() def to_spots(trajs): all_spots = [] frame = 0 done_all_frames = False while not done_all_frames: done_all_frames = True # Get the spots from trajs for this frame positions = [] bg_intensity = [] spot_intensity = [] snr = [] converged = [] width = [] for traj in trajs: if traj.end_frame > frame: done_all_frames = False if traj.start_frame > frame or traj.end_frame < frame: continue i = frame-traj.start_frame positions.append(traj.path[i][:]) spot_intensity.append(traj.intensity[i]) bg_intensity.append(traj.bg_intensity[i]) snr.append(traj.snr[i]) converged.append(traj.converged[i]) width.append(traj.width) spots = Spots(len(positions), frame) spots.set_positions(np.array(positions)) spots.spot_intensity = np.array(spot_intensity) spots.bg_intensity = np.array(bg_intensity) spots.snr = np.array(snr) spots.converged = np.array(converged, dtype=np.int8) spots.width=np.array(width) all_spots.append(spots) frame += 1 return all_spots def read_trajectories(filename): trajectories = [] prev_traj_id = -1 if not os.path.isfile(filename): print(f"WARNING: No such file {filename}") return None with open(filename) as tsv_file: tsv_reader = csv.reader(tsv_file,delimiter="\t") for line in tsv_reader: if line[0] == "trajectory": continue spot = Spots(num_spots=1) traj_id = int(line[0]) spot.frame = int(line[1]) spot.positions[0, :] = [float(line[2]), float(line[3])] spot.spot_intensity[0] = float(line[4]) spot.bg_intensity[0] = float(line[5]) spot.snr[0] = float(line[6]) spot.converged[0] = int(line[7]) spot.width[0,:] = [float(line[8]),float(line[9])] if traj_id != prev_traj_id: trajectories.append(Trajectory(traj_id, spot, 0)) else: trajectories[-1].extend(spot, 0) prev_traj_id = traj_id return trajectories def compare_trajectories(params): all_target_spots = [] all_spots = [] trajs = read_trajectories(params.name + "_trajectories.tsv") target_trajs = read_trajectories(params.name + "_simulated.tsv") frame = 0 done_all_frames = False while not done_all_frames: done_all_frames = True # Get the spots from target_trajs for this frame frame_target_spots = [] for traj in target_trajs: if traj.end_frame > frame: done_all_frames = False if traj.start_frame > frame or traj.end_frame < frame: continue frame_target_spots.append(traj.path[frame-traj.start_frame][:]) target_spots = Spots(len(frame_target_spots), frame) target_spots.set_positions(np.array(frame_target_spots)) all_target_spots.append(target_spots) # Get the spots from trajs for this frame frame_spots = [] for traj in trajs: if traj.end_frame > frame: done_all_frames = False if traj.start_frame > frame or traj.end_frame < frame: continue frame_spots.append(traj.path[frame-traj.start_frame][:]) spots = Spots(len(frame_spots), frame) spots.set_positions(np.array(frame_spots)) all_spots.append(spots) frame += 1 num_frames = frame for frame in range(num_frames): false_positives = 0 false_negatives = 0 multiples = 0 matches = 0 errors = [] outside_frame = 0 assigned_spots = [] for spot in range(all_target_spots[frame].num_spots): if all_target_spots[frame].positions[spot,0] < 0 \ or all_target_spots[frame].positions[spot,1] < 0 \ or all_target_spots[frame].positions[spot,0] >= params.frame_size[0] \ or all_target_spots[frame].positions[spot,1] >= params.frame_size[1]: outside_frame += 1 continue close_candidates = [] for candidate in range(all_spots[frame].num_spots): candidate_dist = np.linalg.norm( all_target_spots[frame].positions[spot,:] - all_spots[frame].positions[candidate,:] ) if candidate_dist < 1: close_candidates.append(candidate_dist) if len(close_candidates) == 0: false_negatives += 1 elif len(close_candidates) == 1: matches += 1 errors.append(close_candidates[0]) else: false_negatives += 1 multiples += 1 false_positives = all_spots[frame].num_spots - matches print(f"Frame {frame:4d}:", f"Error = {np.mean(np.array(errors)):8f} pixels, ", f"Found = {all_spots[frame].num_spots:3d} ", f"Matches = {matches:3d} ", f"False negatives = {false_negatives:3d} ", f"False positives = {false_positives:3d} ", f"Outside = {outside_frame:3d} ")
Java
UTF-8
1,735
2.6875
3
[]
no_license
package org.igeek.common; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; /** * Created by Gyges on 2017/5/30. * 用于token缓存 guava 缓存 */ public class TokenCache { private static Logger logger = LoggerFactory.getLogger(TokenCache.class); public static String TOKEN_PROFIX = "token_"; private static LoadingCache<String,String> tokenCache = CacheBuilder.newBuilder() .maximumSize(10000) //最大存储大小 .initialCapacity(1000) //初始容量 .expireAfterAccess(12, TimeUnit.HOURS) //过期时间12小时 .build(new CacheLoader<String, String>() { // 调用时如果key没有对应值调用此方法 @Override public String load(String key) throws Exception { return "null"; } }); /** * 设置 key-value * @param key * @param value */ public static void setKey(String key,String value){ tokenCache.put(key,value); } /** * 获得value * @param key * @return */ public static String getValue(String key){ String value = null; try { value = tokenCache.get(key); if ("null".equals(value)){ return null; } return value; } catch (ExecutionException e) { logger.error("localCache get Error",e); e.printStackTrace(); } return null; } }
Python
UTF-8
3,665
2.875
3
[]
no_license
import numpy as np from sklearn.datasets import make_regression from matplotlib import pyplot def sse(X, Y, initial_w, X_transpose): max_iterations = 10000 t = 0 print("Training start for SSE") while t < max_iterations: error = list(map(lambda x: np.subtract(np.matmul(np.transpose(initial_w), x[0]), x[1]), zip(X, Y))) w_updates = list(map(lambda x: np.matmul(x, np.transpose(error)), X_transpose)) w_updates = np.multiply(w_updates, 2 * learning_rate) new_w = np.subtract(initial_w, w_updates) delta = np.linalg.norm(np.subtract(new_w, initial_w)) if delta <= min_delta: break # if t % 10 == 0: # print("Old Ws = {} and new Ws = {} and delta = {}".format(initial_w, new_w, delta)) initial_w = new_w t += 1 print("Training done: SSE") return new_w def r_squared(predictions, Y): mean_y = np.mean(Y) denom = np.sum(np.subtract(mean_y, Y) ** 2) num = np.sum(np.subtract(predictions, Y) ** 2) return 1 - (num / denom) def euclidean(X, Y, X_transpose): max_iterations = 100000 t = 0 initial_w = np.divide(W, 1.09) # learning_rate = 0.0002 print("Training start for Orthogonal Dist with initial weights {}".format(initial_w)) # initial_w = initial_w[1:] while t < max_iterations: initial_w0 = initial_w[0] w_squared = np.sum(initial_w[1:] ** 2) error = list(map(lambda x: np.subtract(np.matmul(np.transpose(initial_w), x[0]), x[1]), zip(X, Y))) error_square = list(map(lambda x: x ** 2, error)) sum_error_square = sum(error_square) sum_err_sq_w = list(map(lambda w: sum_error_square * w, initial_w)) error_Xi = list(map(lambda x: np.matmul(x, np.transpose(error)), X_transpose)) w_updates = np.multiply(2 / w_squared, np.subtract(error_Xi, np.divide(sum_err_sq_w, w_squared))) new_w = np.subtract(initial_w, np.multiply(w_updates, learning_rate)) new_w[0] = initial_w0 - ((2 * learning_rate / w_squared) * sum(error)) delta = np.linalg.norm(np.subtract(new_w, initial_w)) if delta <= min_delta: break if t % 1000 == 0: print("Old Ws = {} and new Ws = {} and delta = {}".format(initial_w, new_w, delta)) initial_w = new_w t += 1 print("Training done for Orthogonal Dist") return new_w n_samples = 500 features = 5 learning_rate = 0.0001 min_delta = 0.0001 bias = 1.5 for i in range(0, 5): X, Y, W = make_regression(n_samples, features - 1, noise=3, bias=bias, coef=True, random_state=i) X = np.insert(X, 0, 1, axis=1) W = np.insert(W, 0, bias) print("W used for generation {}".format(W)) initial_W = np.ones(features) X_T = np.transpose(X) sse_w = sse(X, Y, initial_W, X_T) sse_predictions = np.matmul(X, np.transpose(sse_w)) r_2_sse = r_squared(sse_predictions, Y) orthogonal_w = euclidean(X, Y, X_T) orthogonal_predictions = np.matmul(X, np.transpose(orthogonal_w)) r_2_orthogonal = r_squared(orthogonal_predictions, Y) X_T_X = np.matmul(X_T, X) inv_X_T_X = np.linalg.inv(X_T_X) X_inv_X_T_X = np.matmul(X, inv_X_T_X) X_inv_X_T_X_XT = np.matmul(X_inv_X_T_X, X_T) ML_predictions = np.matmul(X_inv_X_T_X_XT, Y) r_2_ml = r_squared(ML_predictions, Y) print("R squared for SSE {}".format(r_2_sse)) print("R squared for Orthogonal {}".format(r_2_orthogonal)) print("R squared for ML {}".format(r_2_ml)) print("Actual W ={}".format(W)) print("SSE W ={}".format(sse_w)) print("Ortho W={}".format(orthogonal_w))
Python
UTF-8
510
3.625
4
[]
no_license
### Print or breakpoint to debug def max(lst): #max_num = 0 max_num = -float('inf') for num in lst: print(num, max_num) if num > max_num: print('entered if statement') max_num = num return max_num print(max([-1, -2, -4])) ### Use pdb def max(lst): #max_num = 0 max_num = -float('inf') for num in lst: breakpoint() if num > max_num: max_num = num return max_num #press n to enter the next line of code
Python
UTF-8
189
2.5625
3
[]
no_license
N=int(input()) suc=0 mis=0 for i in range(N): #750 yukicoder _s=input().split() x,s=int(_s[0]),len(_s[1]) w=min(12*x//1000,s) suc=suc+w mis=mis+(s-w) print(suc,mis)
Java
UTF-8
1,475
2.1875
2
[]
no_license
package com.posidex.bean; public class LifeAsiaResponseMessageBean { private String policyNumber; private String mergeClientNumber; private String retainedClientNumber; private String flag; private String errorCode; private String errorDescription; public String getPolicyNumber() { return policyNumber; } public void setPolicyNumber(String policyNumber) { this.policyNumber = policyNumber; } public String getMergeClientNumber() { return mergeClientNumber; } public void setMergeClientNumber(String mergeClientNumber) { this.mergeClientNumber = mergeClientNumber; } public String getRetainedClientNumber() { return retainedClientNumber; } public void setRetainedClientNumber(String retainedClientNumber) { this.retainedClientNumber = retainedClientNumber; } public String getFlag() { return flag; } public void setFlag(String flag) { this.flag = flag; } public String getErrorCode() { return errorCode; } public void setErrorCode(String errorCode) { this.errorCode = errorCode; } public String getErrorDescription() { return errorDescription; } public void setErrorDescription(String errorDescription) { this.errorDescription = errorDescription; } @Override public String toString() { return "LifeAsiaResponseMessageBean [policyNumber=" + policyNumber + ", mergeClientNumber=" + mergeClientNumber + ", retainedClientNumber=" + retainedClientNumber + ", flag=" + flag + ", errorCode=" + errorCode + ", errorDescription=" + errorDescription + "]"; } }
C#
UTF-8
1,442
2.71875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using UnityEngine; public class HomeGenerator { List<RoomNode> allNodesCollection = new List<RoomNode>(); private int homeWidth; private int homeLength; public HomeGenerator(int homeWidth, int homeLength) { this.homeWidth = homeWidth; this.homeLength = homeLength; } public List<Node> CalculateHome(int maxIterations, int roomWidthMin, int roomLengthMin, float roomBottomCornerModifier, float roomTopCornerMidifier, int roomOffset, List<Room> roomsRequired) { // Creation of the binary space partitioner BinarySpacePartitioner bsp = new BinarySpacePartitioner(homeWidth, homeLength); allNodesCollection = bsp.PrepareNodesCollection(maxIterations, roomWidthMin, roomLengthMin); // Extraction of spaces rapresenting the room, all the children that are childern-less List<Node> roomSpaces = StructureHelper.TraverseGraphToExtractLowestLeafes(bsp.RootNode); RoomGenerator roomGenerator = new RoomGenerator(maxIterations, roomLengthMin, roomWidthMin); List<RoomNode> roomList = new List<RoomNode>(); roomList = roomGenerator.GenerateRoomsInGivenSpaces(roomSpaces, roomBottomCornerModifier, roomTopCornerMidifier, roomOffset, roomsRequired); return new List<Node>(roomList).ToList(); } }
Java
UTF-8
1,043
2.3125
2
[]
no_license
package ch.heig.pl.presentation; import ch.heig.pl.business.ContactService; import ch.heig.pl.model.Contact; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; @WebServlet("/liste") public class Liste extends HttpServlet { private ContactService service; @Override public void init(ServletConfig config) throws ServletException { super.init(config); service = (ContactService) getServletContext().getAttribute("service"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<Contact> contacts = service.getContacts(); request.setAttribute("contacts", contacts); request.getRequestDispatcher("/WEB-INF/pages/liste.jsp").forward(request, response); } }
Python
UTF-8
1,168
3.234375
3
[ "MIT" ]
permissive
import gudhi as gd import numpy as np import matplotlib.pyplot as plt def circle_sample(n, r): angles = np.random.uniform(0, 2*np.pi, n) return r*np.cos(angles), r*np.sin(angles) # First we sample 150 points from the unit circle and the radius 2 circle xs1, ys1 = circle_sample(150, 1.0) xs2, ys2 = circle_sample(150, 2.0) xs, ys = np.concatenate((xs1, xs2), axis=None), np.concatenate((ys1, ys2), axis=None) # Then we build a Vietoris-Rips complex (2 skeleton) pts = list(zip(xs, ys)) rc = gd.RipsComplex(points=pts, max_edge_length=4.1) # Then we build a simplex tree, which is a fast data structure encoding the simplex # This is just an intermediate step tr = rc.create_simplex_tree(max_dimension=2) # Finally we compute the persistence, which is a list of the form [(k, (b, d))] # where k is the homology level, b is the birth time and d is the death time. diag = tr.persistence() # Then we plot the persistence barcode and the original data side by side. plt.subplot(1, 3, 2) gd.plot_persistence_barcode(diag) plt.subplot(1, 3, 3) gd.plot_persistence_diagram(diag) plt.subplot(1, 3, 1) plt.title("Original data set") plt.plot(xs, ys, "ro") plt.show()
C#
UTF-8
1,480
2.609375
3
[]
no_license
// This is the blue dwarf // more information at https://github.com/picrap/BlueDwarf namespace BlueDwarf.ViewModel { using System; using System.Reflection; using ArxOne.MrAdvice.MVVM.Properties; using ArxOne.MrAdvice.MVVM.Threading; using Properties; /// <summary> /// View-model base (in case we write more than one). /// </summary> public class ViewModel : ArxOne.MrAdvice.MVVM.ViewModel.ViewModel { [NotifyPropertyChanged] public bool Loading { get; set; } [UISync] public override void OnPropertyChanged(PropertyInfo propertyInfo, NotifyPropertyChanged sender) { var categoryNotifyPropertyChanged = sender as CategoryNotifyPropertyChanged; var category = categoryNotifyPropertyChanged != null ? categoryNotifyPropertyChanged.Category : null; OnPropertyChanged(new CategoryPropertyChangedEventArgs(propertyInfo.Name, category)); } /// <summary> /// Asynchronously invokes the action and shows the wait overlay (assuming view handles it). /// </summary> /// <param name="action">The action.</param> [Async] protected void ShowAsyncLoad(Action action) { bool loading = Loading; try { Loading = true; action(); } finally { Loading = loading; } } } }
Java
UTF-8
4,064
2.296875
2
[]
no_license
package com.royken.teknik.entities; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import com.j256.ormlite.field.DataType; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; import java.io.Serializable; import java.util.Date; /** * Created by royken on 29/12/16. */ @DatabaseTable(tableName = "reponse") public class Reponse implements Serializable{ private static final long serialVersionUID = -22286413121475724L; @Expose(serialize = false, deserialize = false) @DatabaseField private int id; @DatabaseField @Expose(serialize = false, deserialize = false) private String code; @DatabaseField @Expose(serialize = false, deserialize = false) private String nom; @DatabaseField @Expose @SerializedName("valeur") private String valeur; @DatabaseField @Expose(serialize = false, deserialize = false) private int compteur; @DatabaseField @Expose @SerializedName("idElement") private int idElement; @DatabaseField(dataType = DataType.DATE_STRING, format = "yyyy-MM-dd HH:mm:ss") @Expose @SerializedName("date") private Date date; @DatabaseField private String user; @DatabaseField @Expose @SerializedName("idUser") private int idUser; @DatabaseField @Expose(serialize = false, deserialize = false) private String cahier; @DatabaseField @Expose(serialize = false, deserialize = false) private String organe; @DatabaseField @Expose(serialize = false, deserialize = false) private String sousOrgane; @DatabaseField @Expose @SerializedName("valeurCorrecte") private boolean valeurCorrecte; public Reponse() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getNom() { return nom; } public void setNom(String nom) { this.nom = nom; } public String getValeur() { return valeur; } public void setValeur(String valeur) { this.valeur = valeur; } public int getCompteur() { return compteur; } public void setCompteur(int compteur) { this.compteur = compteur; } public int getIdElement() { return idElement; } public void setIdElement(int idElement) { this.idElement = idElement; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getCahier() { return cahier; } public void setCahier(String cahier) { this.cahier = cahier; } public boolean isValeurCorrecte() { return valeurCorrecte; } public void setValeurCorrecte(boolean valeurCorrecte) { this.valeurCorrecte = valeurCorrecte; } public String getOrgane() { return organe; } public void setOrgane(String organe) { this.organe = organe; } public String getSousOrgane() { return sousOrgane; } public void setSousOrgane(String sousOrgane) { this.sousOrgane = sousOrgane; } public int getIdUser() { return idUser; } public void setIdUser(int idUser) { this.idUser = idUser; } @Override public String toString() { return "Reponse{" + "id=" + id + ", code='" + code + '\'' + ", nom='" + nom + '\'' + ", valeur='" + valeur + '\'' + ", compteur=" + compteur + ", idElement=" + idElement + ", date=" + date + ", user='" + user + '\'' + '}'; } }
Markdown
UTF-8
11,786
2.625
3
[ "Apache-2.0" ]
permissive
--- layout: post title: 基于SVM的人脸识别 categories: [blog ] tags: [SVM, Support Vector Machine] description: 通过SVM分类的方法,进行人脸识别 --- ## #数据说明 > LFW全称为Labeled Faces in the Wild, 是一个应用于人脸识别问题的数据库,更多内容查看官方网站:http://vis-www.cs.umass.edu/lfw LFW语料图片,每张图片都有人名Label标记。每个人可能有多张不同情况下情景下的图片。如George W Bush 有530张图片,而有一些人名对应的图片可能只有一张或者几张。我们将选取出现最多的人名作为人脸识别的类别,如本实验中选取出现频数超过70的人名为类别, 那么共计1288张图片。其中包括Ariel Sharon, Colin Powell, Donald Rumsfeld, George W Bush, Gerhard Schroeder, Hugo Chavez , Tony Blair等7个人名。 ![这里写图片描述](http://img.blog.csdn.net/20160829204914728) ## #问题描述 通过对7个人名的提取特征和标记,进行新输入的照片进行标记人名。这是一个多分类的问题,在本数据集合中类别数目为7. 这个问题的解决,不仅可以应用于像公司考勤一样少量人员的识别,也可以应用到新数据的标注中。语料库进一步标注,将进一步扩大训练数据集合数据量,从而进一步提高人脸识别的精确度。因此,对于图片的人名正确标注问题,或者这个多分类问题的研究和使用是有应用价值的。 ## #数据处理 训练与测试数据中样本数量为1288,对样本图片进行下采样后特征数为1850,所有人脸的Label数目为7。 首先将数据集划分为训练集合和测试集合,测试集合占25%(一般应该10%或者20%),训练数据进行训练过程中,将分为训练集合和验证集合。通过验证集合选择最优模型,使用测试结合测试模型性能。 其次,通过对训练集合PCA分解,提取特征脸,提高训练速度,防止过度拟合。图片 1是关于不同的特征所占的总方差的比率关系,从中可以看出,关键特征主要集中在前50个。图片 2 是关于图片 1的累计分布图。从曲线中可以看出,当特征脸数目为50时,约占85%的数据信息,特征脸数据为100时,约占总信息量的90%左右。经过测试,最佳分类结果时,特征脸数目为80 .此时约占88%的总体方差。 ```python print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model, decomposition, datasets from sklearn.pipeline import Pipeline from sklearn.grid_search import GridSearchCV logistic = linear_model.LogisticRegression() pca = decomposition.PCA() pipe = Pipeline(steps=[('pca', pca), ('logistic', logistic)]) digits = datasets.load_digits() X_digits = digits.data y_digits = digits.target ############################################################################### # Plot the PCA spectrum pca.fit(X_digits) plt.figure(1, figsize=(4, 3)) plt.clf() plt.axes([.2, .2, .7, .7]) plt.plot(pca.explained_variance_, linewidth=2) plt.axis('tight') plt.xlabel('n_components') plt.ylabel('explained_variance_') ############################################################################### # Prediction n_components = [10, 20, 25, 30, 35, 40, 50, 64]#[i for i in range(1,65)]# Cs = np.logspace(-4, 4, 3) estimator = GridSearchCV(pipe, dict(pca__n_components=n_components, logistic__C=Cs)) estimator.fit(X_digits, y_digits) plt.axvline(estimator.best_estimator_.named_steps['pca'].n_components, linestyle=':', label='n_components chosen') plt.legend(prop=dict(size=12)) plt.show() ``` ![图片 1 ](http://img.blog.csdn.net/20160829205312201) ***图片1: 不同特征选取数目的方差比率大小, 比率大小是按照从大到小的顺序排列的,从曲线中可以看出,最大的一维约占总体方差的18%*** ![图片2 ](http://img.blog.csdn.net/20160829205522096) ***图片 2: 不同特征选取数目的方差累计比率曲线,从曲线中可以看出,当特征脸数目为50时,约占85%的数据信息,特征脸数据为100时,约占总信息量的90%左右经过测试,最佳分类结果时,特征脸数目为80.此时约占88%的总体方差。*** 因为不同的人有多个不同角度的照片,如果提取特征脸过多,会导致过度拟合,从而测试结果不理想,如果使用特征脸过少,则会导致人脸多类过程区分度不高而使得部分结果分类错误。而在LFW数据集合中,使用特征脸数目为80时效果最佳是可以理解的。图片 3 显示了前16个特征脸。 ![PCA降维度后的16个特征脸](http://img.blog.csdn.net/20160829205644112) 图片 3:对PCA降维度结果中16个特征脸先行呈现效果图 当然,数字图像处理常用的特征降维中NMF分解前几年取得了很多成果,有机会可以使用NMF分级进行特征提取和降维。 ## **#模型训练与结果** 训练代码 ```python from __future__ import print_function from time import time import logging import matplotlib.pyplot as plt from sklearn.cross_validation import train_test_split from sklearn.datasets import fetch_lfw_people from sklearn.grid_search import GridSearchCV from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix from sklearn.decomposition import RandomizedPCA from sklearn.svm import SVC print(__doc__) # Display progress logs on stdout logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s') ############################################################################### # Download the data, if not already on disk and load it as numpy arrays lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4) # introspect the images arrays to find the shapes (for plotting) n_samples, h, w = lfw_people.images.shape # for machine learning we use the 2 data directly (as relative pixel # positions info is ignored by this model) X = lfw_people.data n_features = X.shape[1] # the label to predict is the id of the person y = lfw_people.target target_names = lfw_people.target_names n_classes = target_names.shape[0] print("Total dataset size:") print("n_samples: %d" % n_samples) print("n_features: %d" % n_features) print("n_classes: %d" % n_classes) ############################################################################### # Split into a training set and a test set using a stratified k fold # split into a training and testing set X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.25, random_state=42) ############################################################################### # Compute a PCA (eigenfaces) on the face dataset (treated as unlabeled # dataset): unsupervised feature extraction / dimensionality reduction n_components = 80 print("Extracting the top %d eigenfaces from %d faces" % (n_components, X_train.shape[0])) t0 = time() pca = RandomizedPCA(n_components=n_components, whiten=True).fit(X_train) print("done in %0.3fs" % (time() - t0)) eigenfaces = pca.components_.reshape((n_components, h, w)) print("Projecting the input data on the eigenfaces orthonormal basis") t0 = time() X_train_pca = pca.transform(X_train) X_test_pca = pca.transform(X_test) print("done in %0.3fs" % (time() - t0)) ############################################################################### # Train a SVM classification model print("Fitting the classifier to the training set") t0 = time() param_grid = {'C': [1,10, 100, 500, 1e3, 5e3, 1e4, 5e4, 1e5], 'gamma': [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.1], } clf = GridSearchCV(SVC(kernel='rbf', class_weight='balanced'), param_grid) clf = clf.fit(X_train_pca, y_train) print("done in %0.3fs" % (time() - t0)) print("Best estimator found by grid search:") print(clf.best_estimator_) print(clf.best_estimator_.n_support_) ############################################################################### # Quantitative evaluation of the model quality on the test set print("Predicting people's names on the test set") t0 = time() y_pred = clf.predict(X_test_pca) print("done in %0.3fs" % (time() - t0)) print(classification_report(y_test, y_pred, target_names=target_names)) print(confusion_matrix(y_test, y_pred, labels=range(n_classes))) ############################################################################### # Qualitative evaluation of the predictions using matplotlib def plot_gallery(images, titles, h, w, n_row=3, n_col=4): """Helper function to plot a gallery of portraits""" plt.figure(figsize=(1.8 * n_col, 2.4 * n_row)) plt.subplots_adjust(bottom=0, left=.01, right=.99, top=.90, hspace=.35) for i in range(n_row * n_col): plt.subplot(n_row, n_col, i + 1) # Show the feature face plt.imshow(images[i].reshape((h, w)), cmap=plt.cm.gray) plt.title(titles[i], size=12) plt.xticks(()) plt.yticks(()) # plot the result of the prediction on a portion of the test set def title(y_pred, y_test, target_names, i): pred_name = target_names[y_pred[i]].rsplit(' ', 1)[-1] true_name = target_names[y_test[i]].rsplit(' ', 1)[-1] return 'predicted: %s\ntrue: %s' % (pred_name, true_name) prediction_titles = [title(y_pred, y_test, target_names, i) for i in range(y_pred.shape[0])] plot_gallery(X_test, prediction_titles, h, w) # plot the gallery of the most significative eigenfaces eigenface_titles = ["eigenface %d" % i for i in range(eigenfaces.shape[0])] plot_gallery(eigenfaces, eigenface_titles, h, w) plt.show() ``` ![这里写图片描述](http://img.blog.csdn.net/20160829210951209) ***图片 4 实验数据在二维空间中分布情况,可以看出该数据集如果使用线性模型进行分类,效果将很差;我们将从非线性模型带核的SVM入手,解决该分类问题*** 分类模型将采用SVM分类器进行分类,其中核函数: $f = \exp(-\gamma || x - x'||^2)$ 我们将对核函数中的 γ 进行参数评估优化,此外对不同特征的权重进行优化,通过交叉验证和网格搜索方式,查找到最佳模型为γ=0.01, C = 10时,平均正确率达到90%,如表格 1所示。 **表格 1: 关于测试集合人名标记结果的正确率,召回率和F1** | # |Precision| Recall| F1| Support| | ------------- |:-------------:| -----:|------| |Ariel Sharon| 1.00 |0.85| 0.92| 13| |Colin Powell|0.86 |0.95| 0.90|60| |Donald Rumsfeld |0.88 |0.81| 0.85| 27| |George W Bush| 0.91 |0.98 |0.94 |146| |Gerhard Schroeder| 0.95 |0.72 |0.82| 25| |Hugo Chavez |1.00 |0.60| 0.75| 15| |Tony Blair |0.91 |0.86 |0.89 |36| |Avg/Total |0.91 |0.90 |0.90 |322| 这么高的准确率,是由于我们仅仅选取了每个标识人名数目> 70的人名,但是大量的仅仅出现1次的人名存在。如果考虑这种数据稀疏性,将大大降低结果的准确率。但是,真实应用中,数据稀疏性问题是不得不考虑的问题。 ![这里写图片描述](http://img.blog.csdn.net/20160829211022165) ***图片 5: 预测人名正确结果展示*** ## #未来工作 本文中使用PCA实现特征脸提取,也可以使用其他特征提取方式进行降维。比如NMF实现矩阵分解在数字图像处理中的应用,实现NMF在人脸识别中的特征分解。当前使用的训练数据集使用的最小标记数据为70,当标记训练数据比较稀疏的时候,能否利用未标记数据提供正确率。后面的研究中将注意这两个方面的问题。 ## #参考文章 1. [ sklearnPCA](http://scikit-learn.org/stable/modules/decomposition.html#principal-component-analysis-pca) 2. [The Elements of Statistical Learning Data Mining, Inference, and Prediction](http://link.springer.com/book/10.1007%2F978-0-387-84858-7)
C#
UTF-8
515
2.515625
3
[ "Apache-2.0" ]
permissive
using Favalon.Expressions; using System; namespace Favalon.Terms { #pragma warning disable CS0659 public abstract class Term : IEquatable<Term?> #pragma warning restore CS0659 { private protected Term() { } public abstract Term HigherOrder { get; } public abstract bool Equals(Term? other); public override bool Equals(object obj) => this.Equals(obj as Term); protected internal abstract Expression Visit(Environment environment); } }
Java
UTF-8
479
2.1875
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package cc104proj; /** * * @author Mark Gregor Miguel */ public class BuildingBlock { int row; int col; int distance; public BuildingBlock(int row, int col, int distance) { this.row = row; this.col = col; this.distance = distance; } }
Java
UTF-8
1,559
3.109375
3
[]
no_license
package helper.mapreduce; import com.google.common.collect.Lists; import java.util.Collections; import java.util.List; /** * An extremely basic and naive MapReduce framework. */ public final class MapReduceExecutor { /** * Executes the specified programs using the supplied input data. If more than one program is specified the output * from the previous program is fed into the next. */ public List<KeyValue> execute(Program program, List<KeyValue> inputData) { final List<KeyValue> mapOutput = Lists.newArrayList(); Collector mapCollector = (key, value) -> mapOutput.add(new KeyValue(key, value)); for (KeyValue keyValue : inputData) { program.map(keyValue.getKey(), keyValue.getValue(), mapCollector); } Collections.sort(mapOutput); final List<KeyValue> reduceOutput = Lists.newArrayList(); Collector reduceCollector = (key, value) -> reduceOutput.add(new KeyValue(key, value)); String previousKey = null; List<String> values = Lists.newArrayList(); for (KeyValue keyValue : mapOutput) { String key = keyValue.getKey(); String value = keyValue.getValue(); if (previousKey == null || previousKey.equals(keyValue.getKey())) { values.add(value); } else { program.reduce(previousKey, values.iterator(), reduceCollector); values.clear(); values.add(value); } previousKey = key; } if (!values.isEmpty()) { program.reduce(previousKey, values.iterator(), reduceCollector); } return reduceOutput; } }
C++
UTF-8
2,604
2.84375
3
[]
no_license
#pragma once #include "glbase.hpp" #include <string> #include <stb_image.h> namespace game::opengl { class texture { public: operator GLuint() { return _texture; } texture(std::string_view name) { int width, height, channels; stbi_uc *pixels = stbi_load(name.data(), &width, &height, &channels, STBI_rgb_alpha); if (!pixels) throw exception(except_e::GRAPHICS_BASE, "stbi_load"); glCreateTextures(GL_TEXTURE_2D, 1, &_texture); if (!_texture) throw exception(except_e::GRAPHICS_BASE, "glCreateTextures"); auto miplevels = static_cast<GLuint>(std::floor(std::log2(std::max(width, height)))) + 1; glTextureStorage2D(_texture, miplevels, GL_RGBA8, width, height); glTextureSubImage2D(_texture, 0, 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels); glTextureParameteri(_texture, GL_TEXTURE_WRAP_S, GL_REPEAT); glTextureParameteri(_texture, GL_TEXTURE_WRAP_T, GL_REPEAT); glTextureParameteri(_texture, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTextureParameteri(_texture, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glGenerateTextureMipmap(_texture); stbi_image_free(pixels); } // This function is only meant to be used for font rendering texture(const void *data, int width, int height) { glCreateTextures(GL_TEXTURE_2D, 1, &_texture); if (!_texture) throw exception(except_e::GRAPHICS_BASE, "glCreateTextures"); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTextureStorage2D(_texture, 1, GL_R8, width, height); glTextureSubImage2D(_texture, 0, 0, 0, width, height, GL_RED, GL_UNSIGNED_BYTE, data); glTextureParameteri(_texture, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTextureParameteri(_texture, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); glTextureParameteri(_texture, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTextureParameteri(_texture, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glPixelStorei(GL_UNPACK_ALIGNMENT, 4); } texture(const texture& rhs) = delete; texture(texture&& rhs) noexcept { _texture = rhs._texture; rhs._texture = 0; } ~texture() { if (_texture) glDeleteTextures(1, &_texture); } private: GLuint _texture = 0; }; }
Java
UTF-8
198
2.59375
3
[]
no_license
package ru.job4j.oop; public class Hare { public void tryEat(Ball ball){ System.out.println("Попытался заяц съесть колобка , а тот убежал"); } }
Python
UTF-8
4,388
2.625
3
[]
no_license
#!/usr/bin/python # Auteur : F.Lavaud # Carte : Raspberry Pi # ==================================== # Variable globale # ==================================== import VariableGlob as GLOB # ==================================== # liste des imports # ==================================== import sys import socket import os import time import def_func_LCD as LCD import threading # ===================================================== # Definition de la Class ThreadClient # ===================================================== class ThreadClient( threading.Thread ): '''derivation d'un objet thread pour gerer la connexion avec un client''' def __init__( self, conn, ecrlcd ) : threading.Thread.__init__(self) self.connexion = conn self.ecranlcd = ecrlcd def run(self) : # Dialogue avec le client : nom = self.getName() # nom du thread ip = GLOB.adresse[ nom ] # adresse ip while 1: msgClient = self.connexion.recv(1024) print "MSG IN \t %15s" %ip + ":%10s" %nom + " \t '%s" %msgClient + "'" # Faire suivre le message a tous les autres clients for cle in GLOB.conn_client: if cle != nom and msgClient != "FIN" : # ne pas le renvoyer a l emetteur ip2 = GLOB.adresse[ cle ] print "MSG OUT %15s:%10s -> %15s:%10s \t '%s'" % (ip, nom, ip2, cle, msgClient) GLOB.conn_client[cle].send( msgClient ) # Traite le message if ( ( msgClient == "FIN" ) or ( msgClient == "WEB_REBOOT" ) or ( msgClient == "WEB_SHUTDOWN" ) ) : break elif ( msgClient[0:3] == "LCD" ) : # Affiche sur l'ecran LCD le message recu self.ecranlcd = LCD.Init() self.ecranlcd.clear() #self.ecranlcd.message( 'Client say :\n' ) self.ecranlcd.message( msgClient[4:] + '\n' ) # Fermeture de la connexion self.connexion.close() # couper la connexion cote serveur del GLOB.conn_client[nom] # supprimer son entree dans le dictionnaire GLOB.NbrClient = GLOB.NbrClient - 1 print "\nCLT OUT\t %15s tracked by %10s\n" % (GLOB.adresse[nom], nom) if ( msgClient == "WEB_REBOOT" ) : print "Reboot du systeme demande." self.ecranlcd.clear() self.ecranlcd.message( 'Reboot...\n' ) os.system( "shutdown -r now" ) elif ( msgClient == "WEB_SHUTDOWN" ) : print "Arret du systeme demande." self.ecranlcd.clear() self.ecranlcd.message( 'Shutdown...\n' ) os.system( "shutdown -h now" ) # Le thread se termine ici # ==================================== # Initialisation du Serveur # Input : aucune # Output : socket # ==================================== def InitConnexion() : cmd = "ip addr show wlan0 | grep inet | awk '{print $2}' | cut -d/ -f1" GLOB.HOST = LCD.run_cmd( cmd ) print "Lancement du serveur sur IP=", GLOB.HOST # creation du socket mySocket = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) # liaison du socket a une adresse precise try: mySocket.bind( ( GLOB.HOST, GLOB.PORT ) ) except socket.error: print "La liaison du socket a l'adresse choisie a echoue." mySocket = 0 #sys.exit() return mySocket # ==================================== # Initialisation du serveur - Mise en place du socket # Input : socket # Output : it, connexion, adresse # ==================================== def WaitNewClient( mySocket, ecran ) : # Attente de la requete de connexion d un client ##print "SERVEUR : Pret, en attente d'un client ..." mySocket.listen( 5 ) # Etablissement de la connexion connexion, adresse = mySocket.accept() ##print "SERVEUR : Client connecte, adresse IP %s, port %s" % ( adresse[0], adresse[1] ) # Creer un nouvel objet thread pour gerer la connexion th = ThreadClient( connexion, ecran ) th.start() # Memoriser la connexion dans le dictionnaire it = th.getName() # identifiant du thread GLOB.NbrClient = GLOB.NbrClient + 1 GLOB.NameThread[ GLOB.NbrClient-1 ] = it GLOB.conn_client[it] = connexion GLOB.adresse[it] = adresse[0] GLOB.PThread[it] = th ##print "\n==> NEW CLIENT : %s connecte, %s:%s <==" %(it, adresse[0], adresse[1]) # Dialogue avec le client connexion.send("Vous etes connectes. Envoyez vos messages.") return it
Python
UTF-8
6,556
2.984375
3
[]
no_license
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # MAGIC WAND, MINECRABRACADABRA # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = # Auteurs: Albert et Ludovic # Affiliation: Gymnase du Bugnon # Annee: 2017-2018 # Classe: OC-Informatique # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = # =========================================================================== # # 1. Description du Fichier # # =========================================================================== # """ Creation d'un pont dans la direction nord depuis la position du joueur. Le pont peut etre en bois ou pierre. La longueur du pont est definie par le nombre de blocs vides, minimum 5, au nord du joueur. La fonction bridge appelle deux fonctions pour que le code soit plus lisible. """ # =========================================================================== # # 2. Code # # =========================================================================== # from mcpi import minecraft mc = minecraft.Minecraft.create() # =========================================================================== # # 2.1 Longueur du pont # # =========================================================================== # def isvoid(x, y, z): """Verifie si le bloc est de l'air ou de l'eau""" b = mc.getBlock(x, y, z) if b == 0 or b == 8 or b == 9: return True else: return False def lengthbridge(x, y, z): """Retourne la longueur du pont""" l = 0 # si l'un des deux blocs est vide le pont doit continuer # le bloc doit etre en-dessous du joueur if isvoid(x, y-1, z-1) is True or isvoid(x+1, y-1, z-1) is True: i = 1 while isvoid(x, y-1, z-i) is True or isvoid(x+1, y-1, z-i) is True: i += 1 # si les deux blocs sont pleins le pont se termine if isvoid(x, y-1, z-i) is False and isvoid(x+1, y-1, z-i) is False: # la longueur sous le pont l += i-1 return l else: # si le joueur ne se trouve pas a coté du vide # la fonction est appelée un bloc plus au nord return lengthbridge(x, y, z-1) # =========================================================================== # # 2.2 Construction du pont # # =========================================================================== # def first_stage(x, y, z, l, stairs, block): """Construit le premier étage du pont""" # deux escaliers décoratifs à l'avant du pont mc.setBlock(x-1, y+1, z+2, stairs, 3) mc.setBlock(x+2, y+1, z+2, stairs, 3) # escaliers sur lesquels le joueur marche mc.setBlocks(x, y+1, z+1, x+1, y+1, z+1, stairs, 3) # deux blocs décoratifs sur le coté du pont mc.setBlock(x-1, y+1, z+1, block) mc.setBlock(x+2, y+1, z+1, block) # escaliers à l'envers derrière les escaliers précédents mc.setBlocks(x-1, y+1, z, x+2, y+1, z, stairs, 6) # deux escaliers décoratifs à l'arrière du pont mc.setBlock(x-1, y+1, z-l-1, stairs, 2) mc.setBlock(x+2, y+1, z-l-1, stairs, 2) # escaliers sur lesquels le joueur marche mc.setBlocks(x, y+1, z-l, x+1, y+1, z-l, stairs, 2) # escaliers à l'envers devant les escaliers précédents mc.setBlocks(x-1, y+1, z-l+1, x+2, y+1, z-l+1, stairs, 7) # deux blocs décoratifs sur le coté du pont mc.setBlock(x-1, y+1, z-l, block) mc.setBlock(x+2, y+1, z-l, block) def second_stage(x, y, z, l, stairs, block): """Construit le deuxième étage du pont""" # deux escaliers décoratifs sur le coté du pont mc.setBlock(x-1, y+2, z+1, stairs, 3) mc.setBlock(x+2, y+2, z+1, stairs, 3) # escaliers sur lesquels le joueur marche mc.setBlocks(x, y+2, z, x+1, y+2, z, stairs, 3) # deux blocs décoratifs sur le coté du pont mc.setBlock(x-1, y+2, z, block) mc.setBlock(x+2, y+2, z, block) # deux escaliers décoratifs à l'envers sur le coté du pont mc.setBlock(x-1, y+2, z-1, stairs, 6) mc.setBlock(x+2, y+2, z-1, stairs, 6) # deux escaliers décoratifs sur le coté du pont mc.setBlock(x-1, y+2, z-l, stairs, 2) mc.setBlock(x+2, y+2, z-l, stairs, 2) # deux blocs décoratifs sur le coté du pont mc.setBlock(x-1, y+2, z-l+1, block) mc.setBlock(x+2, y+2, z-l+1, block) # deux escaliers décoratifs à l'envers sur le coté du pont mc.setBlock(x-1, y+2, z-l+2, stairs, 7) mc.setBlock(x+2, y+2, z-l+2, stairs, 7) # escaliers sur lesquels le joueur marche mc.setBlocks(x, y+2, z-l+1, x+1, y+2, z-l+1, stairs, 2) # partie principale du pont mc.setBlocks(x, y+2, z-1, x+1, y+2, z-l+2, block) # escaliers décoratifs à l'envers mc.setBlocks(x-1, y+2, z-2, x-1, y+2, z-l+3, stairs, 4) mc.setBlocks(x+2, y+2, z-2, x+2, y+2, z-l+3, stairs, 5) def bridge(x, y, z, blocktype): """Construit le pont""" l = lengthbridge(x, y, z) # minimum 2 escaliers, 1 bloc et 2 escaliers if l > 5: # attribue un id correspondant pour les escaliers et blocs # pour la pierre et le bois if blocktype is "COBBLESTONE": stairs = 67 block = 4 if blocktype is "WOOD": stairs = 53 block = 5 i = 1 while True: # Trouve le point de départ du pont # si le joueur est sur un terrain plat if isvoid(x, y-1, z-i) is True or isvoid(x+1, y-1, z-i) is True: xs, ys, zs = x, y-1, z-i break else: i += 1 # 1er étage first_stage(xs, ys, zs, l, stairs, block) # 2nd étage second_stage(xs, ys, zs, l, stairs, block) # 3eme étage # rembarde de blocs mc.setBlocks(xs-1, ys+3, zs, xs-1, ys+3, zs-l+1, block) mc.setBlocks(xs+2, ys+3, zs, xs+2, ys+3, zs-l+1, block) else: mc.postToChat("It is too small") xp,yp,zp = mc.player.getTilePos() bridge(xp,yp,zp,"WOOD")
C++
UTF-8
667
2.859375
3
[]
no_license
#include<iostream> using namespace std; int a[10001]; void qsort(int l,int r) { int i=l,j=r; double mid=a[(l+r)/2]; do{ while(a[i]<mid) i++; while(a[j]>mid) j--; if(i<=j) { swap(a[i],a[j]); i++,j--; } }while(i<=j); if(l<j) qsort(l,j); if(r>i) qsort(i,r); } int main() { int n,t,time; cin >> n; for (int i=1;i<=n;i++) { time = 0; cin >> t; for(int j=1;j<=t;j++) cin >> a[j]; qsort(1,t); while(t>3) { int x=a[1]*2+a[t-1]+a[t]; int y=a[1]+a[2]*2+a[t]; time+=min(x,y); t-=2; } if(t==1) time += a[1]; else if(t==2) time+=a[2]; else if(t==3) time+=(a[1]+a[2]+a[3]); cout << time << endl; } return 0; }
Java
UTF-8
1,136
2.078125
2
[]
no_license
package com.tt.jms.consumer; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import static org.junit.Assert.*; @RunWith(SpringRunner.class) @ContextConfiguration(value = "/consumer.xml") public class ConsumerMessageListenerTest { ApplicationContext context = null; @Before public void setUp() throws Exception { context = new ClassPathXmlApplicationContext("consumer.xml"); } @After public void tearDown() throws Exception { } @Test public void onMessage1() throws Exception { ConsumerMessageListener consumerMessageListener1 = (ConsumerMessageListener) context.getBean("consumerMessageListener"); ConsumerMessageListener consumerMessageListener2 = (ConsumerMessageListener) context.getBean("consumerMessageListener"); } }
PHP
UTF-8
3,451
2.578125
3
[]
no_license
<?php include "dp_conn.php"; $sinav_adi = $_POST["sinav_adi"]; $verisor=$pdo->prepare("SELECT * from quiz WHERE quizName = :sinav_adi"); $verisor->execute(array( 'sinav_adi' => $sinav_adi )); $vericek=$verisor->fetch(PDO::FETCH_ASSOC); $sinav_id = $vericek["quizId"]; $n= $vericek["sorusayisi"]; $soru = $_POST["soru"]; $A = $_POST["A"]; $B = $_POST["B"]; $C = $_POST["C"]; $D = $_POST["D"]; for ($i=0; $i < $n; $i++) { $stmt=$pdo->prepare("INSERT INTO questions (quizId, soru) VALUES (:quizId,:soru)"); $stmt->bindValue(':soru', $soru[$i], PDO::PARAM_STR); $stmt->bindValue(':quizId', $sinav_id, PDO::PARAM_STR); $result3=$stmt->execute(); } for ($i=0; $i < $n; $i++) { $verisor=$pdo->prepare("SELECT * from questions WHERE soru = :soru"); $verisor->execute(array( 'soru' => $soru[$i] )); $vericek=$verisor->fetch(PDO::FETCH_ASSOC); $soruId = $vericek["soruId"]; $stmt=$pdo->prepare("INSERT INTO options (soruId, ch1,quizId,ch2,ch3,ch4) VALUES (:soruId,:ch1,:quizId,:ch2,:ch3,:ch4)"); $stmt->bindValue(':soruId', $soruId , PDO::PARAM_STR); $stmt->bindValue(':ch1', $A[$i], PDO::PARAM_STR); $stmt->bindValue(':ch2', $B[$i], PDO::PARAM_STR); $stmt->bindValue(':ch3', $C[$i], PDO::PARAM_STR); $stmt->bindValue(':ch4', $D[$i], PDO::PARAM_STR); $stmt->bindValue(':quizId', $sinav_id, PDO::PARAM_STR); $result3=$stmt->execute(); $secenek = $_POST["cevap"]; switch ($secenek[$i]) { case 'A': $cp="ch1"; $stmt=$pdo->prepare("INSERT INTO answer (correctAnswer , soruId,quizId) VALUES (:correctAnswer,:soruId, :quizId)"); $stmt->bindValue(':soruId', $soruId, PDO::PARAM_STR); $stmt->bindValue(':correctAnswer',$cp, PDO::PARAM_STR); $stmt->bindValue(':quizId',$sinav_id, PDO::PARAM_STR); $result3=$stmt->execute(); break; case 'B': $cp="ch2"; $stmt=$pdo->prepare("INSERT INTO answer (correctAnswer , soruId, quizId) VALUES (:correctAnswer,:soruId,:quizId)"); $stmt->bindValue(':soruId', $soruId, PDO::PARAM_STR); $stmt->bindValue(':correctAnswer', $cp, PDO::PARAM_STR); $stmt->bindValue(':quizId',$sinav_id, PDO::PARAM_STR); $result3=$stmt->execute(); break; case 'C': $cp="ch3"; $stmt=$pdo->prepare("INSERT INTO answer (correctAnswer , soruId,quizId) VALUES (:correctAnswer,:soruId, :quizId)"); $stmt->bindValue(':soruId', $soruId, PDO::PARAM_STR); $stmt->bindValue(':correctAnswer', $cp, PDO::PARAM_STR); $stmt->bindValue(':quizId',$sinav_id, PDO::PARAM_STR); $result3=$stmt->execute(); break; case 'D': $cp="ch4"; $stmt=$pdo->prepare("INSERT INTO answer (correctAnswer , soruId,quizId) VALUES (:correctAnswer,:soruId,:quizId)"); $stmt->bindValue(':soruId', $soruId, PDO::PARAM_STR); $stmt->bindValue(':correctAnswer', $cp, PDO::PARAM_STR); $stmt->bindValue(':quizId',$sinav_id, PDO::PARAM_STR); $result3=$stmt->execute(); break; } } header("Location: admin.php"); ?>
Java
UTF-8
6,615
1.90625
2
[]
no_license
/** * */ package org.pssframework.model.system; import java.util.Date; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.OrderBy; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; import org.pssframework.base.BaseEntity; import org.springside.modules.utils.ReflectionUtils; import com.google.common.collect.Lists; /** * @author Administrator * */ @Entity @Table(name = "O_ROLE") @SequenceGenerator(sequenceName = "SEQ_O_ROLE", name = "SEQ_O_ROLE", allocationSize = 1, initialValue = 10) public class RoleInfo extends BaseEntity { public RoleInfo(Long roleId, String roleName) { this.roleId = roleId; this.roleName = roleName; } public RoleInfo(Long roleId) { this.roleId = roleId; } public RoleInfo() { } /** * */ private static final long serialVersionUID = -2306398962448879040L; /* * ROLE_ID NUMBER not null,is 'PK,有序列SEQ_ROLE生成';' */ @Column(nullable = false, unique = true, name = "ROLE_ID ") @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_O_ROLE") private Long roleId; // ROLE_NAME VARCHAR2(50) not null, @Column(nullable = false, unique = true, name = "ROLE_NAME") private String roleName; // ROLE_REMARK VARCHAR2(256), @Column(length = 256, name = "ROLE_REMARK") private String roleRemark; // ROLE_TYPE VARCHAR2(5), is '见编码ROLE_TYPE1 - 岗位角色(主要对应应用功能)2 - // 操作权限(如档案查询,档案维护) 3 - 系统对象(所能操作系统对象) @Column(length = 5, name = "ROLE_TYPE ") private String roleType; // CREATOR VARCHAR2(20),is '创建该角色的操作员编号(EMP_NO ) @Column(length = 20, name = "CREATOR ") private String creator; // CREATTIME DATE, @Column(name = "CREATTIME") @Temporal(TemporalType.TIMESTAMP) private Date creattime; @Column(name = "LASTTIME_STAMP") @Temporal(TemporalType.TIMESTAMP) // LASTTIME_STAMP DATE default SYSDATE is '最后表结构修改时间戳'; private Date lasttimeStamp; @ManyToMany() @JoinTable(name = "O_ROLE_AUTHORITY", joinColumns = { @JoinColumn(name = "ROLE_ID") }, inverseJoinColumns = { @JoinColumn(name = "AUTHORITY_ID") }) @Fetch(FetchMode.SUBSELECT) @OrderBy("authorityId") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) private List<AuthorityInfo> authorityInfoList = Lists.newArrayList(); @ManyToMany() @JoinTable(name = "O_ROLE_FUN", joinColumns = { @JoinColumn(name = "ROLE_ID") }, inverseJoinColumns = { @JoinColumn(name = "FUN_ID") }) @Fetch(FetchMode.SUBSELECT) @OrderBy("resourceId") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) private List<ResourceInfo> resourceInfoList = Lists.newArrayList(); @Transient @SuppressWarnings("unchecked") public List<Long> getAuthorityIds() { if (authorityIds == null) { authorityIds = ReflectionUtils.convertElementPropertyToList(authorityInfoList, "authorityId"); } return authorityIds; } /** * @param authorityIds the authorityIds to set */ public void setAuthorityIds(List<Long> authorityIds) { this.authorityIds = authorityIds; } @Transient private String resourceIds; @Transient private List<Long> authorityIds; /** * @return the resourceIds */ public String getResourceIds() { if (this.resourceIds == null) { this.resourceIds = ReflectionUtils.convertElementPropertyToString(resourceInfoList, "resourceId", ","); } return resourceIds; } /** * @param resourceIds the resourceIds to set */ public void setResourceIds(String resourceIds) { this.resourceIds = resourceIds; } @Transient public String getAuthNames() { return org.springside.modules.utils.ReflectionUtils.convertElementPropertyToString(authorityInfoList, "authorityName", ", "); } public List<AuthorityInfo> getAuthorityInfoList() { return authorityInfoList; } /** * @return the creator */ public String getCreator() { return creator; } /** * @return the creattime */ public Date getCreattime() { return creattime; } /** * @return the lasttimeStamp */ public Date getLasttimeStamp() { return lasttimeStamp; } public List<ResourceInfo> getResourceInfoList() { return this.resourceInfoList; } /** * @return the roleId */ public Long getRoleId() { return roleId; } /** * @return the roleName */ public String getRoleName() { return roleName; } public String getRoleRemark() { return roleRemark; } /** * @return the roleType */ public String getRoleType() { return roleType; } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } /** * @param authorityInfoList the authorityInfoList to set */ public void setAuthorityInfoList(List<AuthorityInfo> authorityInfoList) { this.authorityInfoList = authorityInfoList; } /** * @param creator the creator to set */ public void setCreator(String creator) { this.creator = creator; } /** * @param creattime the creattime to set */ public void setCreattime(Date creattime) { this.creattime = creattime; } /** * @param lasttimeStamp the lasttimeStamp to set */ public void setLasttimeStamp(Date lasttimeStamp) { this.lasttimeStamp = lasttimeStamp; } /** * @param resourceInfoList the resourceInfoList to set */ public void setResourceInfoList(List<ResourceInfo> resourceInfoList) { this.resourceInfoList = resourceInfoList; } /** * @param roleId the roleId to set */ public void setRoleId(Long roleId) { this.roleId = roleId; } /** * @param roleName the roleName to set */ public void setRoleName(String roleName) { this.roleName = roleName; } public void setRoleRemark(String roleRemark) { this.roleRemark = roleRemark; } /** * @param roleType the roleType to set */ public void setRoleType(String roleType) { this.roleType = roleType; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
C
UTF-8
1,424
2.84375
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* to_unsigned.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jgomes-c <jgomes-c@student.42sp.org.br> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/07/05 14:51:35 by jgomes-c #+# #+# */ /* Updated: 2021/07/09 21:15:49 by jgomes-c ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/ft_printf.h" #include "../libft/libft.h" void ft_to_unsigned(t_print *content) { int count; unsigned int u; int len; char *nbr; count = 0; u = va_arg(content->args, int); if (!u) //zero, 0 { ft_write_zero(content); return ; } nbr = ft_utoa(u); //transforma pra alphanumeric if (!nbr) return ; len = ft_numlen(u); ft_update_lenght(content, len); //confere tamanho q vai ser escrito wdt, prc ft_right(content); while (nbr[count]) content->tl += write (1, &nbr[count++], 1); ft_left(content); free(nbr); }
SQL
UTF-8
508
3.109375
3
[]
no_license
create table if not exists nodes( actions VARCHAR (255), displayDescription VARCHAR (255), displayName VARCHAR (255) not null, durationInMillis bigint, id varchar (255) not null, input VARCHAR (255), result VARCHAR (255), startTime TIMESTAMP, state VARCHAR (255), type VARCHAR (255), causeOfBlockage VARCHAR (255), edges UUID unique, firstParent VARCHAR (255), restartable bool, node_uuid UUID unique, run_uuid UUID not null, primary key (node_uuid), foreign key (run_uuid) references runs (run_uuid) )
C++
UTF-8
47,029
2.515625
3
[]
no_license
/*************************************************************************** init.cpp - description ------------------- begin : Thu Apr 11 2002 copyright : (C) 2002 by Mirela Andronescu email : andrones@cs.ubc.ca ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ // this file contains functions to read the thermodynamic parameters from files // into internal data structures #include <ctype.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "common.h" #include "constants.h" #include "globals.h" #include "structs.h" int ascii_to_int(char *string) // PRE: string is either in float format or it is a '.' // POST: convert in infinity (INF) if it is '.', in a float otherwise { char *ptr; double en; if (strcmp(string, ".") == 0) return INF; en = strtod(string, &ptr); if (en < 0) en -= EPSILON; else en += EPSILON; return (int)(en * 100); } double ascii_to_double(char *string) // PRE: string is either in float format or it is a '.' // POST: convert in infinity (INF) if it is '.', in a float otherwise { char *ptr; double en; if (strcmp(string, ".") == 0) return INF; en = strtod(string, &ptr); return en; // took out the *100.0 on Nov 20, 2007, because we don't want this for // misc.param_greater30 } PARAMTYPE ascii_to_param_type(char *string) { #ifdef DOUBLEPARAMS return 100.0 * ascii_to_double(string); // added the *100.0 on Nov 20, 2007. We don't want it inside ascii_to_double // because we don't want this for misc.param_greater30 #else return ascii_to_int(string); #endif } void read_configuration_file(char *filename) // PRE: None // POST: read the configuration file, which must be in the standard format // - see the documentation { char buffer[256], token1[50], token2[5], token3[50]; FILE *file; int i; if ((file = fopen(filename, "r")) == NULL) { giveup("Cannot open file", filename); } fgets(buffer, sizeof(buffer), file); while (!feof(file)) { if (buffer[0] == '#' || buffer[0] == '[' || buffer[0] == '\n') { fgets(buffer, sizeof(buffer), file); continue; } sscanf(buffer, "%s%s%s", token1, token2, token3); for (i = 0; i < nb_params; i++) { if (strcmp(token1, par_name[i]) == 0) { strcpy(par_value[i], token3); break; } } fgets(buffer, sizeof(buffer), file); } fclose(file); } void read_loop_file(char *filename, PARAMTYPE internal_penalty_by_size[], PARAMTYPE bulge_penalty_by_size[], PARAMTYPE hairpin_penalty_by_size[]) // PRE: None // POST: Read information from loop.dat file - internal, bulge, hairpin { char buffer[256]; FILE *file; int size; char internal[10], bulge[10], hairpin[10]; if ((file = fopen(filename, "r")) == NULL) { giveup("Cannot open file", filename); } fgets(buffer, sizeof(buffer), file); while (!feof(file)) { if (buffer[0] == '#' || buffer[0] == '\n') { fgets(buffer, sizeof(buffer), file); continue; } sscanf(buffer, "%d%s%s%s", &size, internal, bulge, hairpin); internal_penalty_by_size[size] = ascii_to_param_type(internal); bulge_penalty_by_size[size] = ascii_to_param_type(bulge); hairpin_penalty_by_size[size] = ascii_to_param_type(hairpin); fgets(buffer, sizeof(buffer), file); } fclose(file); } void read_tloop_file(char *filename, hairpin_tloop tloop[], int &nb_loops) // PRE: None // POST: Read information from tetra-loop file - hairpin { char buffer[256], energy[10]; FILE *file; int i, j; i = 0; if ((file = fopen(filename, "r")) == NULL) { giveup("Cannot open file", filename); } fgets(buffer, sizeof(buffer), file); while (!feof(file)) { if (buffer[0] == '#' || buffer[0] == '\n') { fgets(buffer, sizeof(buffer), file); continue; } sscanf(buffer, "%s%s", tloop[i].seq, energy); for (j = 0; j < strlen(tloop[i].seq); j++) tloop[i].seq[j] = toupper(tloop[i].seq[j]); tloop[i].energy = ascii_to_param_type(energy); fgets(buffer, sizeof(buffer), file); i++; // may be improved - hash-table?? } nb_loops = i; fclose(file); } void read_int11_file(char *filename, PARAMTYPE int11[][NUCL][NUCL][NUCL][NUCL][NUCL]) // PRE: filename is the file that contains the energy for 1-1 internal loops // POST: the values are stored in the 6-D array int11 { char buffer[256]; FILE *file; char v1[10], v2[10], v3[10], v4[10], v5[10], v6[10], v7[10], v8[10]; char v9[10], v10[10], v11[10], v12[10], v13[10], v14[10], v15[10], v16[10]; char v17[10], v18[10], v19[10], v20[10], v21[10], v22[10], v23[10], v24[10]; int ii, jj; // ii = i+1; jj = j-1 int oi[6] = {0, 1, 2, 3, 2, 3}, oii, oiip; // the order in which i and ip appear int oj[6] = {3, 2, 1, 0, 3, 2}, ojj, ojjp; // the order in which j and jp appear // In the following configuration: // X // A C // T G // Y // i = A; j = T; ii = X; jj = Y; ip = C; jp = G // int11[i][j][ii][jj][ip][jp] // initialize int11 ii = 0; jj = 0; // ii = i+1; jj = j-1 oii = 0; oiip = 0; // the order in which i and ip appear ojj = 0; ojjp = 0; // the order in which j and jp appear for (int i = 0; i < NUCL; i++) for (int j = 0; j < NUCL; j++) for (int ii = 0; ii < NUCL; ii++) for (int jj = 0; jj < NUCL; jj++) for (int ip = 0; ip < NUCL; ip++) for (int jp = 0; jp < NUCL; jp++) { int11[i][j][ii][jj][ip][jp] = INF; #if (MODEL == EXTENDED) int11_experimental_addition[i][j][ii][jj][ip][jp] = INF; #endif } if ((file = fopen(filename, "r")) == NULL) { giveup("Cannot open file", filename); } fgets(buffer, sizeof(buffer), file); while (!feof(file)) { if (buffer[0] == '#' || buffer[0] == '\n') { fgets(buffer, sizeof(buffer), file); continue; } sscanf(buffer, "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s", v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24); if (ii == NUCL) { ii = 0; oii++; ojj++; } // v1-v4 - jj changes // ip and jp are always in the following order: // AT, CG, GC, TA, GT, TG - that means // 03, 12, 21, 30, 23, 32 jj = 0; oiip = 0; ojjp = 0; int11[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]] = ascii_to_param_type(v1); int11[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]] = ascii_to_param_type(v2); int11[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]] = ascii_to_param_type(v3); int11[oi[oii]][oj[ojj]][ii][jj][oi[oiip]][oj[ojjp]] = ascii_to_param_type(v4); // j grows, jj starts again from 0 jj = 0; oiip++; ojjp++; int11[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]] = ascii_to_param_type(v5); int11[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]] = ascii_to_param_type(v6); int11[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]] = ascii_to_param_type(v7); int11[oi[oii]][oj[ojj]][ii][jj][oi[oiip]][oj[ojjp]] = ascii_to_param_type(v8); // j grows, jj starts again from 0 jj = 0; oiip++; ojjp++; int11[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]] = ascii_to_param_type(v9); int11[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]] = ascii_to_param_type(v10); int11[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]] = ascii_to_param_type(v11); int11[oi[oii]][oj[ojj]][ii][jj][oi[oiip]][oj[ojjp]] = ascii_to_param_type(v12); // j grows, jj starts again from 0 jj = 0; oiip++; ojjp++; int11[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]] = ascii_to_param_type(v13); int11[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]] = ascii_to_param_type(v14); int11[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]] = ascii_to_param_type(v15); int11[oi[oii]][oj[ojj]][ii][jj][oi[oiip]][oj[ojjp]] = ascii_to_param_type(v16); // j grows, jj starts again from 0 jj = 0; oiip++; ojjp++; int11[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]] = ascii_to_param_type(v17); int11[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]] = ascii_to_param_type(v18); int11[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]] = ascii_to_param_type(v19); int11[oi[oii]][oj[ojj]][ii][jj][oi[oiip]][oj[ojjp]] = ascii_to_param_type(v20); // j grows, jj starts again from 0 jj = 0; oiip++; ojjp++; int11[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]] = ascii_to_param_type(v21); int11[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]] = ascii_to_param_type(v22); int11[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]] = ascii_to_param_type(v23); int11[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]] = ascii_to_param_type(v24); // go to the next line: grow ii ii++; fgets(buffer, sizeof(buffer), file); } fclose(file); } void read_int21_file(char *filename, PARAMTYPE int21[][NUCL][NUCL][NUCL][NUCL][NUCL][NUCL]) // PRE: filename is the file that contains the energy for 2-1 internal loops // POST: the values are stored in the 7-D array int21 { char buffer[256]; FILE *file; char v1[10], v2[10], v3[10], v4[10], v5[10], v6[10], v7[10], v8[10]; char v9[10], v10[10], v11[10], v12[10], v13[10], v14[10], v15[10], v16[10]; char v17[10], v18[10], v19[10], v20[10], v21[10], v22[10], v23[10], v24[10]; int ii, jj, jjp; // ii = i+1; jj = j-1 int oi[6] = {0, 1, 2, 3, 2, 3}, oii, oiip; // the order in which i and ip appear int oj[6] = {3, 2, 1, 0, 3, 2}, ojj, ojjp; // the order in which j and jp appear // In the following configuration: // X // A C // T G // YZ // i = A; j = T; ii = X; jj = Y; ip = C; jp = G; jjp = Z // int21[i][j][ii][jj][ip][jp][jjp] ii = 0; jj = 0; jjp = 0; // ii = i+1; jj = j-1 oii = 0; oiip = 0; // the order in which i and ip appear ojj = 0; ojjp = 0; // initialize int21 for (int i = 0; i < NUCL; i++) for (int j = 0; j < NUCL; j++) for (int ii = 0; ii < NUCL; ii++) for (int jj = 0; jj < NUCL; jj++) for (int ip = 0; ip < NUCL; ip++) for (int jp = 0; jp < NUCL; jp++) for (int jjp = 0; jjp < NUCL; jjp++) { int21[i][j][ii][jj][ip][jp][jjp] = INF; #if (MODEL == EXTENDED) int21_experimental_addition[i][j][ii][jj][ip][jp][jjp] = INF; #endif } if ((file = fopen(filename, "r")) == NULL) { giveup("Cannot open file", filename); } fgets(buffer, sizeof(buffer), file); while (!feof(file)) { if (buffer[0] == '#' || buffer[0] == '\n') { fgets(buffer, sizeof(buffer), file); continue; } sscanf(buffer, "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s", v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24); if (ii == NUCL) { ii = 0; jjp++; } if (jjp == NUCL) { jjp = 0; oii++; ojj++; } // v1-v4 - jj changes // ip and jp are always in the following order: // AT, CG, GC, TA, GT, TG - that means // 03, 12, 21, 30, 23, 32 jj = 0; oiip = 0; ojjp = 0; int21[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]][jjp] = ascii_to_param_type(v1); int21[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]][jjp] = ascii_to_param_type(v2); int21[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]][jjp] = ascii_to_param_type(v3); int21[oi[oii]][oj[ojj]][ii][jj][oi[oiip]][oj[ojjp]][jjp] = ascii_to_param_type(v4); // j grows, jj starts again from 0 jj = 0; oiip++; ojjp++; int21[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]][jjp] = ascii_to_param_type(v5); int21[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]][jjp] = ascii_to_param_type(v6); int21[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]][jjp] = ascii_to_param_type(v7); int21[oi[oii]][oj[ojj]][ii][jj][oi[oiip]][oj[ojjp]][jjp] = ascii_to_param_type(v8); // j grows, jj starts again from 0 jj = 0; oiip++; ojjp++; int21[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]][jjp] = ascii_to_param_type(v9); int21[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]][jjp] = ascii_to_param_type(v10); int21[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]][jjp] = ascii_to_param_type(v11); int21[oi[oii]][oj[ojj]][ii][jj][oi[oiip]][oj[ojjp]][jjp] = ascii_to_param_type(v12); // j grows, jj starts again from 0 jj = 0; oiip++; ojjp++; int21[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]][jjp] = ascii_to_param_type(v13); int21[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]][jjp] = ascii_to_param_type(v14); int21[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]][jjp] = ascii_to_param_type(v15); int21[oi[oii]][oj[ojj]][ii][jj][oi[oiip]][oj[ojjp]][jjp] = ascii_to_param_type(v16); // j grows, jj starts again from 0 jj = 0; oiip++; ojjp++; int21[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]][jjp] = ascii_to_param_type(v17); int21[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]][jjp] = ascii_to_param_type(v18); int21[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]][jjp] = ascii_to_param_type(v19); int21[oi[oii]][oj[ojj]][ii][jj][oi[oiip]][oj[ojjp]][jjp] = ascii_to_param_type(v20); // j grows, jj starts again from 0 jj = 0; oiip++; ojjp++; int21[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]][jjp] = ascii_to_param_type(v21); int21[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]][jjp] = ascii_to_param_type(v22); int21[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]][jjp] = ascii_to_param_type(v23); int21[oi[oii]][oj[ojj]][ii][jj++][oi[oiip]][oj[ojjp]][jjp] = ascii_to_param_type(v24); // go to the next line: grow ii ii++; fgets(buffer, sizeof(buffer), file); } fclose(file); } void read_int22_file( char *filename, PARAMTYPE int22[][NUCL][NUCL][NUCL][NUCL][NUCL][NUCL][NUCL]) // PRE: filename is the file that contains the energy for 1-1 internal loops // POST: the values are stored in the 6-D array int11 { char buffer[256]; FILE *file; char v1[10], v2[10], v3[10], v4[10], v5[10], v6[10], v7[10], v8[10]; char v9[10], v10[10], v11[10], v12[10], v13[10], v14[10], v15[10], v16[10]; int ii, jj, iip, jjp; // ii = i+1; jj = j-1, iip=i'-1, jjp=j'+1 int oi[6] = {0, 1, 2, 3, 2, 3}; int i, ip; // the order in which i and ip appear int oj[6] = {3, 2, 1, 0, 3, 2}; ; int j, jp; // the order in which j and jp appear // In the following configuration: // XV // A C // T G // YZ // i = A; j = T; ii = X; jj = Y; ip = C; jp = G; iip = V; jjp = Z // int22[i][j][ii][jj][ip][jp][iip][jjp] ii = 0; jj = 0; iip = 0; jjp = 0; // ii = i+1; jj = j-1, iip=i'-1, jjp=j'+1 // initialize int22 for (i = 0; i < NUCL; i++) for (int j = 0; j < NUCL; j++) for (int ii = 0; ii < NUCL; ii++) for (int jj = 0; jj < NUCL; jj++) for (int ip = 0; ip < NUCL; ip++) for (int jp = 0; jp < NUCL; jp++) for (int iip = 0; iip < NUCL; iip++) for (int jjp = 0; jjp < NUCL; jjp++) int22[i][j][ii][jj][ip][jp][iip][jjp] = INF; if ((file = fopen(filename, "r")) == NULL) { giveup("Cannot open file", filename); } fgets(buffer, sizeof(buffer), file); i = 0; ip = 0; j = 0; jp = 0; while (!feof(file)) { if (buffer[0] == '#' || buffer[0] == '\n') { fgets(buffer, sizeof(buffer), file); continue; } sscanf(buffer, "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s", v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16); if (jj == NUCL) { jj = 0; ii++; } if (ii == NUCL) { ii = 0; ip++; jp++; } if (ip == 6) { ip = 0; jp = 0; i++; j++; } // v1-v4 - jj changes // ip and jp are always in the following order: // AT, CG, GC, TA, GT, TG - that means // 03, 12, 21, 30, 23, 32 iip = 0; jjp = 0; int22[oi[i]][oj[j]][ii][jj][oi[ip]][oj[jp]][iip][jjp++] = ascii_to_param_type(v1); int22[oi[i]][oj[j]][ii][jj][oi[ip]][oj[jp]][iip][jjp++] = ascii_to_param_type(v2); int22[oi[i]][oj[j]][ii][jj][oi[ip]][oj[jp]][iip][jjp++] = ascii_to_param_type(v3); int22[oi[i]][oj[j]][ii][jj][oi[ip]][oj[jp]][iip][jjp] = ascii_to_param_type(v4); // j grows, jj starts again from 0 iip++; jjp = 0; int22[oi[i]][oj[j]][ii][jj][oi[ip]][oj[jp]][iip][jjp++] = ascii_to_param_type(v5); int22[oi[i]][oj[j]][ii][jj][oi[ip]][oj[jp]][iip][jjp++] = ascii_to_param_type(v6); int22[oi[i]][oj[j]][ii][jj][oi[ip]][oj[jp]][iip][jjp++] = ascii_to_param_type(v7); int22[oi[i]][oj[j]][ii][jj][oi[ip]][oj[jp]][iip][jjp] = ascii_to_param_type(v8); // j grows, jj starts again from 0 iip++; jjp = 0; int22[oi[i]][oj[j]][ii][jj][oi[ip]][oj[jp]][iip][jjp++] = ascii_to_param_type(v9); int22[oi[i]][oj[j]][ii][jj][oi[ip]][oj[jp]][iip][jjp++] = ascii_to_param_type(v10); int22[oi[i]][oj[j]][ii][jj][oi[ip]][oj[jp]][iip][jjp++] = ascii_to_param_type(v11); int22[oi[i]][oj[j]][ii][jj][oi[ip]][oj[jp]][iip][jjp] = ascii_to_param_type(v12); // j grows, jj starts again from 0 iip++; jjp = 0; int22[oi[i]][oj[j]][ii][jj][oi[ip]][oj[jp]][iip][jjp++] = ascii_to_param_type(v13); int22[oi[i]][oj[j]][ii][jj][oi[ip]][oj[jp]][iip][jjp++] = ascii_to_param_type(v14); int22[oi[i]][oj[j]][ii][jj][oi[ip]][oj[jp]][iip][jjp++] = ascii_to_param_type(v15); int22[oi[i]][oj[j]][ii][jj][oi[ip]][oj[jp]][iip][jjp++] = ascii_to_param_type(v16); // go to the next line: grow jj jj++; fgets(buffer, sizeof(buffer), file); } fclose(file); } void read_stack_file(char *filename, PARAMTYPE stack[][NUCL][NUCL][NUCL]) // PRE: filename is the file that contains the stacked pairs energy data for // DNA POST: the values are stored in the 4-D array stack { char buffer[256]; FILE *file; char v1[10], v2[10], v3[10], v4[10], v5[10], v6[10], v7[10], v8[10]; char v9[10], v10[10], v11[10], v12[10], v13[10], v14[10], v15[10], v16[10]; int i, j, ii, jj; // ii = i+1; jj = j-1 i = 0; j = 0; ii = 0; jj = 0; if ((file = fopen(filename, "r")) == NULL) { giveup("Cannot open file", filename); } fgets(buffer, sizeof(buffer), file); while (!feof(file)) { if (buffer[0] == '#' || buffer[0] == '\n') { fgets(buffer, sizeof(buffer), file); continue; } sscanf(buffer, "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s", v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16); if (ii == NUCL) { ii = 0; i++; } // v1-v4 - jj changes jj = 0; j = 0; stack[i][j][ii][jj++] = ascii_to_param_type(v1); stack[i][j][ii][jj++] = ascii_to_param_type(v2); stack[i][j][ii][jj++] = ascii_to_param_type(v3); stack[i][j][ii][jj] = ascii_to_param_type(v4); // j grows, jj starts again from 0 jj = 0; j++; stack[i][j][ii][jj++] = ascii_to_param_type(v5); stack[i][j][ii][jj++] = ascii_to_param_type(v6); stack[i][j][ii][jj++] = ascii_to_param_type(v7); stack[i][j][ii][jj] = ascii_to_param_type(v8); // j grows, jj starts again from 0 jj = 0; j++; stack[i][j][ii][jj++] = ascii_to_param_type(v9); stack[i][j][ii][jj++] = ascii_to_param_type(v10); stack[i][j][ii][jj++] = ascii_to_param_type(v11); stack[i][j][ii][jj] = ascii_to_param_type(v12); // j grows, jj starts again from 0 jj = 0; j++; stack[i][j][ii][jj++] = ascii_to_param_type(v13); stack[i][j][ii][jj++] = ascii_to_param_type(v14); stack[i][j][ii][jj++] = ascii_to_param_type(v15); stack[i][j][ii][jj++] = ascii_to_param_type(v16); // go to the next line: grow ii ii++; fgets(buffer, sizeof(buffer), file); } fclose(file); } void read_dangle_file(char *filename, PARAMTYPE dangle_top[][NUCL][NUCL], PARAMTYPE dangle_bot[][NUCL][NUCL]) // PRE: filename is the file that contains the stacked pairs energy data for // DNA POST: the values are stored in the 4-D array stack { char buffer[256]; FILE *file; char v1[10], v2[10], v3[10], v4[10], v5[10], v6[10], v7[10], v8[10]; char v9[10], v10[10], v11[10], v12[10], v13[10], v14[10], v15[10], v16[10]; int i, j, ii, jj; // ii = i+1; jj = j-1 i = 0; j = 0; ii = 0; jj = 0; int counter; if ((file = fopen(filename, "r")) == NULL) { giveup("Cannot open file", filename); } fgets(buffer, sizeof(buffer), file); i = 0; counter = 0; // read the top dangling pairs while (counter < 4 && !feof(file)) { if (buffer[0] == '#' || buffer[0] == '\n') { fgets(buffer, sizeof(buffer), file); continue; } sscanf(buffer, "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s", v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16); ii = 0; j = 0; dangle_top[i][j][ii++] = ascii_to_param_type(v1); dangle_top[i][j][ii++] = ascii_to_param_type(v2); dangle_top[i][j][ii++] = ascii_to_param_type(v3); dangle_top[i][j][ii] = ascii_to_param_type(v4); // j grows, ii starts again from 0 ii = 0; j++; dangle_top[i][j][ii++] = ascii_to_param_type(v5); dangle_top[i][j][ii++] = ascii_to_param_type(v6); dangle_top[i][j][ii++] = ascii_to_param_type(v7); dangle_top[i][j][ii] = ascii_to_param_type(v8); // j grows, ii starts again from 0 ii = 0; j++; dangle_top[i][j][ii++] = ascii_to_param_type(v9); dangle_top[i][j][ii++] = ascii_to_param_type(v10); dangle_top[i][j][ii++] = ascii_to_param_type(v11); dangle_top[i][j][ii] = ascii_to_param_type(v12); // j grows, ii starts again from 0 ii = 0; j++; dangle_top[i][j][ii++] = ascii_to_param_type(v13); dangle_top[i][j][ii++] = ascii_to_param_type(v14); dangle_top[i][j][ii++] = ascii_to_param_type(v15); dangle_top[i][j][ii] = ascii_to_param_type(v16); fgets(buffer, sizeof(buffer), file); i++; counter++; } i = 0; counter = 0; // read the bottom dangling pairs while (counter < 4 && !feof(file)) { if (buffer[0] == '#' || buffer[0] == '\n') { fgets(buffer, sizeof(buffer), file); continue; } sscanf(buffer, "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s", v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16); jj = 0; j = 0; dangle_bot[i][j][jj++] = ascii_to_param_type(v1); dangle_bot[i][j][jj++] = ascii_to_param_type(v2); dangle_bot[i][j][jj++] = ascii_to_param_type(v3); dangle_bot[i][j][jj] = ascii_to_param_type(v4); // j grows, ii starts again from 0 jj = 0; j++; dangle_bot[i][j][jj++] = ascii_to_param_type(v5); dangle_bot[i][j][jj++] = ascii_to_param_type(v6); dangle_bot[i][j][jj++] = ascii_to_param_type(v7); dangle_bot[i][j][jj] = ascii_to_param_type(v8); // j grows, ii starts again from 0 jj = 0; j++; dangle_bot[i][j][jj++] = ascii_to_param_type(v9); dangle_bot[i][j][jj++] = ascii_to_param_type(v10); dangle_bot[i][j][jj++] = ascii_to_param_type(v11); dangle_bot[i][j][jj] = ascii_to_param_type(v12); // j grows, ii starts again from 0 jj = 0; j++; dangle_bot[i][j][jj++] = ascii_to_param_type(v13); dangle_bot[i][j][jj++] = ascii_to_param_type(v14); dangle_bot[i][j][jj++] = ascii_to_param_type(v15); dangle_bot[i][j][jj] = ascii_to_param_type(v16); fgets(buffer, sizeof(buffer), file); i++; counter++; } fclose(file); } void read_sequence_file(char *filename, char *sequence) // PRE: filename is the input file with the pool of input words // POST: Read data from file and put them in the global variable pool { char buffer[MAXSLEN]; FILE *file; // make sure the sequence is empty empty_string(sequence); if ((file = fopen(filename, "r")) == NULL) { giveup("Cannot open file", filename); } fgets(buffer, sizeof(buffer), file); while (!feof(file)) { if (buffer[0] == '#' || buffer[0] == '\n') { fgets(buffer, sizeof(buffer), file); continue; } if (buffer[strlen(buffer) - 1] == '\n') buffer[strlen(buffer) - 1] = '\0'; if (strcmp(sequence, "") == 0) strcpy(sequence, buffer); else strcat(sequence, buffer); fgets(buffer, sizeof(buffer), file); } fclose(file); } void read_miscloop_file(char *filename, miscinfo &misc) // read the information from the miscloop file { char buffer[256]; FILE *file; char v1[10], v2[10], v3[10], v4[10]; if ((file = fopen(filename, "r")) == NULL) { giveup("Cannot open file", filename); } fgets(buffer, sizeof(buffer), file); while (buffer[0] == '#' || buffer[0] == '\n') fgets(buffer, sizeof(buffer), file); sscanf(buffer, "%s", v1); misc.param_greater30 = ascii_to_double(v1); fgets(buffer, sizeof(buffer), file); while (buffer[0] == '#' || buffer[0] == '\n') fgets(buffer, sizeof(buffer), file); sscanf(buffer, "%s", v1); misc.asymmetry_penalty_max_correction = ascii_to_param_type(v1); fgets(buffer, sizeof(buffer), file); while (buffer[0] == '#' || buffer[0] == '\n') fgets(buffer, sizeof(buffer), file); sscanf(buffer, "%s%s%s%s", v1, v2, v3, v4); misc.asymmetry_penalty_array[0] = ascii_to_param_type(v1); misc.asymmetry_penalty_array[1] = ascii_to_param_type(v2); misc.asymmetry_penalty_array[2] = ascii_to_param_type(v3); misc.asymmetry_penalty_array[3] = ascii_to_param_type(v4); fgets(buffer, sizeof(buffer), file); while (buffer[0] == '#' || buffer[0] == '\n') fgets(buffer, sizeof(buffer), file); sscanf(buffer, "%s%s%s", v1, v2, v3); misc.multi_offset = ascii_to_param_type(v1); misc.multi_free_base_penalty = ascii_to_param_type(v2); misc.multi_helix_penalty = ascii_to_param_type(v3); fgets(buffer, sizeof(buffer), file); while (buffer[0] == '#' || buffer[0] == '\n') fgets(buffer, sizeof(buffer), file); // efn2 multibranched loops - not in use sscanf(buffer, "%s%s%s", v1, v2, v3); fgets(buffer, sizeof(buffer), file); while (buffer[0] == '#' || buffer[0] == '\n') fgets(buffer, sizeof(buffer), file); sscanf(buffer, "%s", v1); misc.terminal_AU_penalty = ascii_to_param_type(v1); fgets(buffer, sizeof(buffer), file); while (buffer[0] == '#' || buffer[0] == '\n') fgets(buffer, sizeof(buffer), file); sscanf(buffer, "%s", v1); misc.hairpin_GGG = ascii_to_param_type(v1); fgets(buffer, sizeof(buffer), file); while (buffer[0] == '#' || buffer[0] == '\n') fgets(buffer, sizeof(buffer), file); sscanf(buffer, "%s", v1); misc.hairpin_c1 = ascii_to_param_type(v1); fgets(buffer, sizeof(buffer), file); while (buffer[0] == '#' || buffer[0] == '\n') fgets(buffer, sizeof(buffer), file); sscanf(buffer, "%s", v1); misc.hairpin_c2 = ascii_to_param_type(v1); fgets(buffer, sizeof(buffer), file); while (buffer[0] == '#' || buffer[0] == '\n') fgets(buffer, sizeof(buffer), file); sscanf(buffer, "%s", v1); misc.hairpin_c3 = ascii_to_param_type(v1); fgets(buffer, sizeof(buffer), file); while (buffer[0] == '#' || buffer[0] == '\n') fgets(buffer, sizeof(buffer), file); sscanf(buffer, "%s", v1); misc.intermolecular_initiation = ascii_to_param_type(v1); fgets(buffer, sizeof(buffer), file); while (buffer[0] == '#' || buffer[0] == '\n') fgets(buffer, sizeof(buffer), file); sscanf(buffer, "%s", v1); misc.gail_rule = atoi(v1); } int round_double(double number) { int intrep = (int)number; if (number < 0) { if (number - intrep <= -0.5) return intrep - 1; else return intrep; } else { if (number - intrep >= 0.5) return intrep + 1; else return intrep; } } void formula(double temp, PARAMTYPE &energy, PARAMTYPE enthalpy) { if (energy < INF) { // TODO: this is used only for temperature != 37, so it's ok for now, but // maybe it shouldn't be converted to int energy = (int)(round_double( ((double)(enthalpy) - (temp + 273.15) * ((double)(enthalpy - energy)) / 310.15))); } } void calculate_energies(double temp) { int i, j, k, l, m, n, o, p; for (i = 0; i < NUCL; i++) for (j = 0; j < NUCL; j++) for (k = 0; k < NUCL; k++) { formula(temp, dangle_top[i][j][k], enthalpy_dangle_top[i][j][k]); formula(temp, dangle_bot[i][j][k], enthalpy_dangle_bot[i][j][k]); for (l = 0; l < NUCL; l++) { formula(temp, stack[i][j][k][l], enthalpy_stack[i][j][k][l]); formula(temp, tstackh[i][j][k][l], enthalpy_tstackh[i][j][k][l]); formula(temp, tstacki[i][j][k][l], enthalpy_tstacki[i][j][k][l]); for (m = 0; m < NUCL; m++) for (n = 0; n < NUCL; n++) { formula(temp, int11[i][j][k][l][m][n], enthalpy_int11[i][j][k][l][m][n]); for (o = 0; o < NUCL; o++) { formula(temp, int21[i][j][k][l][m][n][o], enthalpy_int21[i][j][k][l][m][n][o]); for (p = 0; p < NUCL; p++) formula(temp, int22[i][j][k][l][m][n][o][p], enthalpy_int22[i][j][k][l][m][n][o][p]); } } } } for (i = 0; i < MAXLOOP + 1; i++) { formula(temp, internal_penalty_by_size[i], enthalpy_internal_penalty_by_size[i]); formula(temp, bulge_penalty_by_size[i], enthalpy_bulge_penalty_by_size[i]); formula(temp, hairpin_penalty_by_size[i], enthalpy_hairpin_penalty_by_size[i]); } formula(temp, misc.terminal_AU_penalty, enthalpy_misc.terminal_AU_penalty); formula(temp, misc.hairpin_GGG, enthalpy_misc.hairpin_GGG); formula(temp, misc.hairpin_c1, enthalpy_misc.hairpin_c1); formula(temp, misc.hairpin_c2, enthalpy_misc.hairpin_c2); formula(temp, misc.hairpin_c3, enthalpy_misc.hairpin_c3); formula(temp, misc.asymmetry_penalty_max_correction, enthalpy_misc.asymmetry_penalty_max_correction); formula(temp, misc.asymmetry_penalty_array[0], enthalpy_misc.asymmetry_penalty_array[0]); formula(temp, misc.asymmetry_penalty_array[1], enthalpy_misc.asymmetry_penalty_array[1]); formula(temp, misc.asymmetry_penalty_array[2], enthalpy_misc.asymmetry_penalty_array[2]); formula(temp, misc.asymmetry_penalty_array[3], enthalpy_misc.asymmetry_penalty_array[3]); formula(temp, misc.multi_offset, enthalpy_misc.multi_offset); formula(temp, misc.multi_helix_penalty, enthalpy_misc.multi_helix_penalty); formula(temp, misc.multi_free_base_penalty, enthalpy_misc.multi_free_base_penalty); formula(temp, misc.intermolecular_initiation, enthalpy_misc.intermolecular_initiation); #if (MODEL == SIMPLE) // added enthalpy_nb_tloops on August 6th for (i = 0; i < enthalpy_nb_triloops; i++) formula(temp, triloop[i].energy, enthalpy_triloop[i].energy); for (i = 0; i < enthalpy_nb_tloops; i++) formula(temp, tloop[i].energy, enthalpy_tloop[i].energy); #endif } #include <iostream> // void init_data (char *config_file, int what, double temperature) void init_data(char *arg, char *config_file, int what, double temperature) // the function that must be called by the main program to read data files // PRE: None // POST: Read all data and configuration files { char stack_energy37_filename[200], loop_energy37_filename[200]; char tloop_energy37_filename[200], tstackh_energy37_filename[200]; char tstacki_energy37_filename[200], int11_energy37_filename[200]; char int21_energy37_filename[200], int22_energy37_filename[200]; char miscloop_energy37_filename[200], dangle_energy37_filename[200]; char triloop_energy37_filename[200]; char stack_enthalpy_filename[200], loop_enthalpy_filename[200]; char tloop_enthalpy_filename[200], tstackh_enthalpy_filename[200]; char tstacki_enthalpy_filename[200], int11_enthalpy_filename[200]; char int21_enthalpy_filename[200], int22_enthalpy_filename[200]; char miscloop_enthalpy_filename[200], dangle_enthalpy_filename[200]; char triloop_enthalpy_filename[200]; char conf[200]; // Added on Mar 19, 2008 char special_hl_energy37_filename[200]; // configuration file // first find the path to params int i; int len; int index; char path[200]; char separator; char config_dir[200]; len = strlen(arg); index = -1; separator = '/'; strcpy(path, ""); for (i = len; i >= 0; i--) { // make it work on Linux if (arg[i] == '/') { separator = '/'; index = i; break; } // make it work on Windows else if (arg[i] == '\\') { separator = '\\'; index = i; break; } } if (index > -1) { for (i = 0; i < index + 1; i++) path[i] = arg[i]; path[i] = '\0'; } strncpy(path, arg, index + 1); // get the path of the configuration directory strcpy(conf, config_file); sprintf(conf, "%s%s", path, conf); len = strlen(config_file); index = -1; separator = '/'; strcpy(config_dir, ""); for (i = len; i >= 0; i--) { // make it work on Linux if (config_file[i] == '/') { separator = '/'; index = i; break; } // make it work on Windows else if (config_file[i] == '\\') { separator = '\\'; index = i; break; } } if (index > -1) { for (i = 0; i < index + 1; i++) config_dir[i] = config_file[i]; config_dir[i] = '\0'; } // printf ("config_dir: %s\n", config_dir); // if (separator == '/') strcat(path, config_dir); // else if (separator == '\\') // strcat (path, "params\\"); if (what != RNA && what != DNA) { printf("Please specify what to fold: RNA or DNA\n"); exit(1); } if (temperature < 0 || temperature > 100) { printf("Temperature must be between 0 and 100 degrees Celsius\n"); exit(1); } read_configuration_file(config_file); strcpy(std_dir_par, config_dir); // if temperature is 37, there's no need to read the enthalpies if (what == RNA) { if (temperature == 37) { strcpy(stack_energy37_filename, std_dir_par); strcat(stack_energy37_filename, rna_stack_energy37_v31_par); strcpy(loop_energy37_filename, std_dir_par); strcat(loop_energy37_filename, rna_loop_energy37_v31_par); strcpy(triloop_energy37_filename, std_dir_par); strcat(triloop_energy37_filename, rna_triloop_energy37_v31_par); strcpy(tloop_energy37_filename, std_dir_par); strcat(tloop_energy37_filename, rna_tloop_energy37_v31_par); strcpy(tstackh_energy37_filename, std_dir_par); strcat(tstackh_energy37_filename, rna_tstackh_energy37_v31_par); strcpy(tstacki_energy37_filename, std_dir_par); strcat(tstacki_energy37_filename, rna_tstacki_energy37_v31_par); strcpy(int11_energy37_filename, std_dir_par); strcat(int11_energy37_filename, rna_int11_energy37_v31_par); strcpy(int21_energy37_filename, std_dir_par); strcat(int21_energy37_filename, rna_int21_energy37_v31_par); strcpy(int22_energy37_filename, std_dir_par); strcat(int22_energy37_filename, rna_int22_energy37_v31_par); strcpy(miscloop_energy37_filename, std_dir_par); strcat(miscloop_energy37_filename, rna_miscloop_energy37_v31_par); strcpy(dangle_energy37_filename, std_dir_par); strcat(dangle_energy37_filename, rna_dangle_energy37_v31_par); strcpy(special_hl_energy37_filename, std_dir_par); strcat(special_hl_energy37_filename, rna_special_hl_energy_par); } else { strcpy(stack_energy37_filename, std_dir_par); strcat(stack_energy37_filename, rna_stack_energy37_v23_par); strcpy(loop_energy37_filename, std_dir_par); strcat(loop_energy37_filename, rna_loop_energy37_v23_par); strcpy(triloop_energy37_filename, std_dir_par); strcat(triloop_energy37_filename, rna_triloop_energy37_v23_par); strcpy(tloop_energy37_filename, std_dir_par); strcat(tloop_energy37_filename, rna_tloop_energy37_v23_par); strcpy(tstackh_energy37_filename, std_dir_par); strcat(tstackh_energy37_filename, rna_tstackh_energy37_v23_par); strcpy(tstacki_energy37_filename, std_dir_par); strcat(tstacki_energy37_filename, rna_tstacki_energy37_v23_par); strcpy(int11_energy37_filename, std_dir_par); strcat(int11_energy37_filename, rna_int11_energy37_v23_par); strcpy(int21_energy37_filename, std_dir_par); strcat(int21_energy37_filename, rna_int21_energy37_v23_par); strcpy(int22_energy37_filename, std_dir_par); strcat(int22_energy37_filename, rna_int22_energy37_v23_par); strcpy(miscloop_energy37_filename, std_dir_par); strcat(miscloop_energy37_filename, rna_miscloop_energy37_v23_par); strcpy(dangle_energy37_filename, std_dir_par); strcat(dangle_energy37_filename, rna_dangle_energy37_v23_par); } strcpy(stack_enthalpy_filename, std_dir_par); strcat(stack_enthalpy_filename, rna_stack_enthalpy_par); strcpy(loop_enthalpy_filename, std_dir_par); strcat(loop_enthalpy_filename, rna_loop_enthalpy_par); strcpy(triloop_enthalpy_filename, std_dir_par); strcat(triloop_enthalpy_filename, rna_triloop_enthalpy_par); strcpy(tloop_enthalpy_filename, std_dir_par); strcat(tloop_enthalpy_filename, rna_tloop_enthalpy_par); strcpy(tstackh_enthalpy_filename, std_dir_par); strcat(tstackh_enthalpy_filename, rna_tstackh_enthalpy_par); strcpy(tstacki_enthalpy_filename, std_dir_par); strcat(tstacki_enthalpy_filename, rna_tstacki_enthalpy_par); strcpy(int11_enthalpy_filename, std_dir_par); strcat(int11_enthalpy_filename, rna_int11_enthalpy_par); strcpy(int21_enthalpy_filename, std_dir_par); strcat(int21_enthalpy_filename, rna_int21_enthalpy_par); strcpy(int22_enthalpy_filename, std_dir_par); strcat(int22_enthalpy_filename, rna_int22_enthalpy_par); strcpy(miscloop_enthalpy_filename, std_dir_par); strcat(miscloop_enthalpy_filename, rna_miscloop_enthalpy_par); strcpy(dangle_enthalpy_filename, std_dir_par); strcat(dangle_enthalpy_filename, rna_dangle_enthalpy_par); } else if (what == DNA) { strcpy(stack_energy37_filename, std_dir_par); strcat(stack_energy37_filename, dna_stack_energy37_par); strcpy(loop_energy37_filename, std_dir_par); strcat(loop_energy37_filename, dna_loop_energy37_par); strcpy(triloop_energy37_filename, std_dir_par); strcat(triloop_energy37_filename, dna_triloop_energy37_par); strcpy(tloop_energy37_filename, std_dir_par); strcat(tloop_energy37_filename, dna_tloop_energy37_par); strcpy(tstackh_energy37_filename, std_dir_par); strcat(tstackh_energy37_filename, dna_tstackh_energy37_par); strcpy(tstacki_energy37_filename, std_dir_par); strcat(tstacki_energy37_filename, dna_tstacki_energy37_par); strcpy(int11_energy37_filename, std_dir_par); strcat(int11_energy37_filename, dna_int11_energy37_par); strcpy(int21_energy37_filename, std_dir_par); strcat(int21_energy37_filename, dna_int21_energy37_par); strcpy(int22_energy37_filename, std_dir_par); strcat(int22_energy37_filename, dna_int22_energy37_par); strcpy(miscloop_energy37_filename, std_dir_par); strcat(miscloop_energy37_filename, dna_miscloop_energy37_par); strcpy(dangle_energy37_filename, std_dir_par); strcat(dangle_energy37_filename, dna_dangle_energy37_par); // write the enthalpy files strcpy(stack_enthalpy_filename, std_dir_par); strcat(stack_enthalpy_filename, dna_stack_enthalpy_par); strcpy(loop_enthalpy_filename, std_dir_par); strcat(loop_enthalpy_filename, dna_loop_enthalpy_par); strcpy(triloop_enthalpy_filename, std_dir_par); strcat(triloop_enthalpy_filename, dna_triloop_enthalpy_par); strcpy(tloop_enthalpy_filename, std_dir_par); strcat(tloop_enthalpy_filename, dna_tloop_enthalpy_par); strcpy(tstackh_enthalpy_filename, std_dir_par); strcat(tstackh_enthalpy_filename, dna_tstackh_enthalpy_par); strcpy(tstacki_enthalpy_filename, std_dir_par); strcat(tstacki_enthalpy_filename, dna_tstacki_enthalpy_par); strcpy(int11_enthalpy_filename, std_dir_par); strcat(int11_enthalpy_filename, dna_int11_enthalpy_par); strcpy(int21_enthalpy_filename, std_dir_par); strcat(int21_enthalpy_filename, dna_int21_enthalpy_par); strcpy(int22_enthalpy_filename, std_dir_par); strcat(int22_enthalpy_filename, dna_int22_enthalpy_par); strcpy(miscloop_enthalpy_filename, std_dir_par); strcat(miscloop_enthalpy_filename, dna_miscloop_enthalpy_par); strcpy(dangle_enthalpy_filename, std_dir_par); strcat(dangle_enthalpy_filename, dna_dangle_enthalpy_par); } read_stack_file(stack_energy37_filename, stack); read_loop_file(loop_energy37_filename, internal_penalty_by_size, bulge_penalty_by_size, hairpin_penalty_by_size); #if (MODEL == SIMPLE) read_tloop_file(triloop_energy37_filename, triloop, nb_triloops); read_tloop_file(tloop_energy37_filename, tloop, nb_tloops); #elif (MODEL == EXTENDED) read_tloop_file(special_hl_energy37_filename, special_hl, nb_special_hl); #endif read_stack_file(tstackh_energy37_filename, tstackh); read_stack_file(tstacki_energy37_filename, tstacki); read_miscloop_file(miscloop_energy37_filename, misc); // now fill the 3 misc.internal parameters, maybe we need them // this is a good place, because we have read tstacki and // misc.terminal_AU_penalty misc.internal_AU_closure = 65; // misc.internal_AU_closure = tstacki[A][U][A][A]; misc.internal_AG_mismatch = tstacki[C][G][A][G]; misc.internal_UU_mismatch = tstacki[C][G][U][U]; read_dangle_file(dangle_energy37_filename, dangle_top, dangle_bot); read_int11_file(int11_energy37_filename, int11); #if (MODEL == SIMPLE) misc.internal11_basic_mismatch = 40; misc.internal11_GG_mismatch = -170; #elif (MODEL == EXTENDED) misc.internal11_AU_closure = 120; misc.internal11_GU_closure = 120; misc.internal11_AG_mismatch = -40; misc.internal11_GG_mismatch = -210; misc.internal11_UU_mismatch = -30; misc.internal11_5YRR_5YRR = 70; misc.internal11_5RYY_5RYY = -50; misc.internal11_5YYR_5YYR = 40; misc.internal11_5YRY_5RYR = -40; misc.internal11_5RRY_5RYY = -100; #endif read_int21_file(int21_energy37_filename, int21); #if (MODEL == SIMPLE) misc.internal21_match = 400; misc.internal21_AU_closure = 75; #elif (MODEL == EXTENDED) misc.internal21_initiation = 220; misc.internal21_AU_closure = 70; misc.internal21_GU_closure = 70; misc.internal21_AG_mismatch = -110; misc.internal21_GG_mismatch = -110; misc.internal21_UU_mismatch - 100; #endif read_int22_file(int22_energy37_filename, int22); // fill the misc.internal22 parameters // misc.internal22_delta_same_size = int22[G][C][A][A][G][C][A][G] - // (int22[G][C][A][A][C][G][A][A] + int22[C][G][G][A][G][C][A][G])/2; // misc.internal22_delta_different_size = int22[G][C][G][U][G][C][A][G] - // (int22[G][C][G][U][C][G][U][G] + int22[C][G][G][A][G][C][A][G])/2; // the above don't give the right numbers, for some reason. Just use the // numbers from Mathews et al 1999 misc.internal22_delta_same_size = 0; misc.internal22_delta_different_size = 180; misc.internal22_delta_1stable_1unstable = 100; misc.internal22_delta_AC = 0; misc.internal22_match = 200; // read enthalpy files read_stack_file(stack_enthalpy_filename, enthalpy_stack); read_loop_file(loop_enthalpy_filename, enthalpy_internal_penalty_by_size, enthalpy_bulge_penalty_by_size, enthalpy_hairpin_penalty_by_size); read_tloop_file(triloop_enthalpy_filename, enthalpy_triloop, enthalpy_nb_triloops); read_tloop_file(tloop_enthalpy_filename, enthalpy_tloop, enthalpy_nb_tloops); read_stack_file(tstackh_enthalpy_filename, enthalpy_tstackh); read_stack_file(tstacki_enthalpy_filename, enthalpy_tstacki); read_miscloop_file(miscloop_enthalpy_filename, enthalpy_misc); read_dangle_file(dangle_enthalpy_filename, enthalpy_dangle_top, enthalpy_dangle_bot); read_int11_file(int11_enthalpy_filename, enthalpy_int11); read_int21_file(int21_enthalpy_filename, enthalpy_int21); read_int22_file(int22_enthalpy_filename, enthalpy_int22); // fill up the new 2D array for internal loop length #if (MODEL == EXTENDED) int j, k, ip, jp; // add bulge1 for (i = 0; i < NUCL; i++) for (j = 0; j < NUCL; j++) for (ip = 0; ip < NUCL; ip++) for (jp = 0; jp < NUCL; jp++) for (k = 0; k < NUCL; k++) bulge1[i][j][k][ip][jp] = INF; for (i = 0; i < NUCL; i++) for (j = 0; j < NUCL; j++) { if (!can_pair(i, j)) continue; for (ip = 0; ip < NUCL; ip++) for (jp = 0; jp < NUCL; jp++) { if (!can_pair(ip, jp)) continue; for (k = 0; k < NUCL; k++) bulge1[i][j][k][ip][jp] = stack[i][j][ip][jp] + bulge_penalty_by_size[1]; } } // add internal_penalty_by_size_2D for (i = 1; i < MAXLOOP_I; i++) { for (j = MAX(i, 3); j < MAXLOOP_I; j++) { internal_penalty_by_size_2D[i][j] = internal_penalty_by_size[i + j] + asymmetry_penalty(i, j); } } // in the simple model this was considered 0 // we start from 3 because we have full tables for int1x1 and int2x2 // for (i=3; i <= MAXLOOP_I/2; i++) // internal_symmetry[i] = 0; // we initialize with the Ninio values for the simple model // for (i=1; i <= 5; i++) // internal_asymmetry[i] = i*100.0/2.0; // for (i=6; i <= MAXLOOP_I-2; i++) // internal_asymmetry[i] = 300; #endif if (temperature != 37) { calculate_energies(temperature); } }
Python
UTF-8
2,100
2.984375
3
[]
no_license
from queue import Queue from collections import defaultdict from message import ChatMessage # simple in-memory database for this project. class SimpleDb(object): def __init__(self, user_cache_size=10): self.username_lookup = dict() self.username_cnt = 0 self.user_messages = defaultdict(lambda: Queue(maxsize=user_cache_size)) def get_user_id_from_username(self, username): for user_id, user_info in self.username_lookup.items(): if username == user_info.get('username'): return {'status': 'ok', 'value': user_id} return {'status': 'error', 'status_msg': 'User not found'} def register_user(self, username, ip_address): for user_id, user_info in self.username_lookup.items(): if username == user_info.get('username'): return {'status': 'error', 'status_msg': 'User already exists'} self.username_lookup[self.username_cnt] = {'username': username, 'ip': ip_address} self.username_cnt += 1 return {'status': 'ok', 'value': self.username_cnt - 1} def get_user_list(self): return [item.get('username') for item in self.username_lookup.values()] def assign_message_to_user_id(self, sending_user_id, user_id, message): if user_id not in self.username_lookup: return {'status': 'error', 'status_msg': 'User does not exist'} elif self.user_messages[user_id].full(): return {'status': 'error', 'status_msg': 'User message queue is full'} else: self.user_messages[user_id].put(ChatMessage(sending_user_id, user_id, message)) return {'status': 'ok', 'status_msg': 'assigned'} def get_message_for_user_id(self, user_id): if user_id not in self.username_lookup: return {'status': 'error', 'status_msg': 'User does not exist, please register'} elif self.user_messages[user_id].empty(): return {'status': 'ok', 'status_msg': 'no messages'} else: return {'status': 'ok', 'value': self.user_messages[user_id].get()}
Python
UTF-8
1,583
2.796875
3
[]
no_license
import datetime def test_schema_dump(peewee_obj, schema): dump_data = schema.dump(peewee_obj).data assert dump_data == {'id': 1, 'name': 'test_restaurant', 'opens_at': '08:30:00', 'closes_at': '00:00:00'} def test_schema_load(raw_obj_data, schema): clean_data, errors = schema.load(raw_obj_data) assert clean_data == {'name': 'test_restaurant2', 'opens_at': datetime.time(12, 30), 'closes_at': datetime.time(3, 0)} def test_schema_dump_many(peewee_obj_list, schema_many): dump_data = schema_many.dump(peewee_obj_list).data assert dump_data == [{'id': 1, 'name': 'test_restaurant3', 'opens_at': '09:30:00', 'closes_at': '01:00:00'}, {'id': 2, 'name': 'test_restaurant4', 'opens_at': '08:30:00', 'closes_at': '00:00:00'} ] def test_schema_load_many(raw_obj_list, schema_many): clean_data, errors = schema_many.load(raw_obj_list) assert clean_data == [{'name': 'test_restaurant5', 'opens_at': datetime.time(10, 30), 'closes_at': datetime.time(22, 0)}, {'name': 'test_restaurant6', 'opens_at': datetime.time(00, 00), 'closes_at': datetime.time(00, 0)} ]
SQL
UTF-8
1,151
2.625
3
[]
no_license
SET SERVEROUTPUT ON BEGIN -- ------------------------------------------------------- DBMS_AQADM.CREATE_QUEUE_TABLE ( queue_table => 'chirico.Q2_T' , queue_payload_type => 'chirico.message_type' ); -- ------------------------------------------------------- DBMS_AQADM.CREATE_QUEUE ( queue_name => 'Q2' , queue_table => 'chirico.Q2_T' , queue_type => DBMS_AQADM.NORMAL_QUEUE , max_retries => 0 , retry_delay => 0 , retention_time => 1209600 , dependency_tracking => FALSE , comment => 'Test Object Type Queue' , auto_commit => FALSE ); -- ------------------------------------------------------- DBMS_AQADM.START_QUEUE('chirico.Q2'); -- ------------------------------------------------------- DBMS_AQADM.GRANT_QUEUE_PRIVILEGE ( privilege => 'ALL' , queue_name => 'chirico.Q2' , grantee => 'chirico' , grant_option => FALSE ); -- ------------------------------------------------------- END; /
Java
GB18030
2,842
3.1875
3
[ "MIT" ]
permissive
package mars.meiwen; import mars.bigwork.R; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class txt013 extends Activity{ private TextView txt013; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.txt013); txt013=(TextView)findViewById(R.id.txt013); txt013.setText("1.Ready or not, some day it will all come to an end. There will be no more sunrises, no days, no hours or minutes. All the things you collected, whether treasured or forgotten, will pass no someone else.\nǷ׼һ죬һжʱճ¡СʱͷӵĸӵеһУֵϧĻӦģǽתˡ\n" + "2.Your wealth, fame and temporal power will shrivel to irrelevance. It will not matter what you owned or what you were owed.\nǷ׼һ죬һжʱճ¡СʱͷӵĸӵеһУֵϧĻӦģǽתˡ\n" + "3.Your grudges, resentments, frustrations, and jealousies will finally disappear. So, too, your hopes, ambitions, plans, and to-do lists will all expire. The wins and losses that once seemed so important will fade away.\nĶ⡢ߺޡܸкͼʶʧȻϣƻҪҲ޷ʵ֡ҪĵʧҲصĮˡ\n" + "4.It won't matter where you come from, or on what side of the tracks you lived. It won't matter whether you were beautiful or brilliant. Your gender, skin color, ethnicity will be irrelevant.\nʱԺηҪͬdzҲ塣Ա𡢷ɫҲ޹ء\n" + "5.So what will matter? How will the value of your days be measured?\nôʲôϧأָʲô׼ȥļֵأ\n" + "6.What will matter is not what you bought, but what you built; not what you got, but what you gave.\nҪϧģõijɹļֵ\n" + "7.What will matter is not your success, but your significance.\nҪϧģĶҲģõģġ\n" + "8.What will matter is not what you learned, but what you taught.\nҪϧģѧʲôʲô"); } }
Python
UTF-8
484
3.125
3
[]
no_license
# import os # import sys # import json # target = sys.argv[1] # with open(target, 'r') as reader: # json_str = reader.read() # json_lists = json.loads(json_str) # dict, read # with open(target, 'w+') as writer: # sorted_list = sorted(json_lists, key = lambda i: i["date"], reverse = True) # only work for list of dicts # json_sorted_str = json.dumps(sorted_list, indent=4) # write # writer.write(json_sorted_str) # print(f"Sort {target} by dates.")
Markdown
UTF-8
692
2.859375
3
[]
no_license
# Hackathon08 Desarrollo de la hackathon de la semana 8 • ¿Cuál es la importancia de usar un algoritmo? Un algortimo describe paso a paso las tareas que se debe desarrollar en un proceso dado, esto permite el control de cada paso mejorando asi cada proceso. • ¿Cómo un algoritmo mejora el proceso o servicio de una empresa? Un algoritmo mejora los procesos de la empresa al describir cada paso y asi poder ver donde podemos mejorar o corregir parte de este proceso. • ¿El algoritmo expuesto en este caso es el único con el que cuenta TuTienda? No, se puede tener diferentes algoritmos de acuerdo al alcance que se desea abarcar y segun lo que se quiera solucionar o presentar.
Java
UTF-8
772
3.25
3
[]
no_license
public class SpecialOffer { Product product; String description; String start; String end; double discount; SpecialOffer(Product p, String d, String s, String e, double dis){ product = p; description = d; start = s; end = e; discount = dis; } void showOffer(){ double priceAfterDiscount = product.price - product.price * discount; System.out.println("Special offer on: "+ product.name); System.out.println(description); System.out.println("Start offer: "+ start); System.out.println("End offer: " + end); System.out.println("Discount: "+ discount * 100 + "%"); System.out.println("Price after discount: "+ priceAfterDiscount + "zł"); } }
Java
UTF-8
1,111
2.078125
2
[]
no_license
package com.lagou.service; import com.lagou.domain.ResourceCategory; import com.lagou.domain.Role; import com.lagou.domain.RoleMenuVo; import com.lagou.domain.RoleResourceVo; import java.util.List; /** * @author liu * @description 角色查询Service层接口 * @date 2021/7/14 14:03 */ public interface RoleService { /* 按条件查询所有角色 */ List<Role> findAllRole(Role role); /* 更新角色关联菜单 */ void updateRoleContextMenu(RoleMenuVo roleMenuVo); /* 删除角色记录 */ void deleteRole(Integer roleId); /*------------作业部分---------------*/ /** * 根据角色id查询当前角色所拥有的资源信息 * 并按照资源分类-资源进行查询 * @param rid 角色id * @return 资源分类列表,其中包含了当前角色在该分类下拥有的资源 */ List<ResourceCategory> findResourceListByRoleId(Integer rid); /** * 更新角色资源关联信息 * @param roleResourceVo */ void roleContextResource(RoleResourceVo roleResourceVo); }
C++
UTF-8
945
3.203125
3
[]
no_license
#include "../lib/createTree.hpp" using namespace std; void morris(TreeNode *root, int k) { int count = 0; TreeNode *curr = root; while (curr != nullptr) { if (curr->left == nullptr) { count++; if (count == k) { cout << curr->val << endl; } curr = curr->right; } else { TreeNode *currLeft = curr->left; while (currLeft->right != curr && currLeft->right != nullptr) { currLeft = currLeft->right; } if (currLeft->right == nullptr) { currLeft->right = curr; curr = curr->left; } else { count++; if (count == k) { cout << curr->val << endl; } currLeft->right = nullptr; curr = curr->right; } } } } int main(int argc, char **argv) { string line; while (getline(cin, line)) { TreeNode *root = stringToTreeNode(line); int val; cin >> val; morris(root, val); } }
Java
UTF-8
987
2.8125
3
[]
no_license
package com.pineapple.java.redis.ch09; import redis.clients.jedis.Jedis; import redis.clients.jedis.Pipeline; public class ZipList { public static void testLongZiplistPerformance(Jedis conn) { System.out.println("\n----- testLongZiplistPerformance -----"); longZiplistPerformance(conn, Sharding.TEST, 5, 10, 10); assert conn.llen(Sharding.TEST) == 5; } public static double longZiplistPerformance(Jedis conn, String key, int length, int passes, int psize) { conn.del(key); for (int i = 0; i < length; i++) { conn.rpush(key, String.valueOf(i)); } Pipeline pipeline = conn.pipelined(); long time = System.currentTimeMillis(); for (int p = 0; p < passes; p++) { for (int pi = 0; pi < psize; pi++) { pipeline.rpoplpush(key, key); } pipeline.sync(); } return (passes * psize) / (System.currentTimeMillis() - time); } }
PHP
UTF-8
8,202
2.515625
3
[ "MIT" ]
permissive
<?php /** * 管理员服务 */ namespace Aizxin\Services\Admin; use Aizxin\Repositories\Eloquent\UserRepositoryEloquent; use Aizxin\Repositories\Eloquent\RoleRepositoryEloquent; use Aizxin\Tools\Result; use Aizxin\Validators\UserLoginValidator; use Aizxin\Validators\UserValidator; use Auth; use Cache; use Exception; use Prettus\Validator\Contracts\ValidatorInterface; use Prettus\Validator\Exceptions\ValidatorException; class UserService { protected $userRepo; protected $uValidator; protected $userValidator; protected $roleRepo; public function __construct( UserRepositoryEloquent $userRepo, UserLoginValidator $uValidator, UserValidator $userValidator, RoleRepositoryEloquent $roleRepo) { $this->roleRepo = $roleRepo; $this->userRepo = $userRepo; $this->uValidator = $uValidator; $this->userValidator = $userValidator; } /** * [postLogin 管理员登录] * 臭虫科技 * @author chouchong * @DateTime 2017-04-05T14:47:46+0800 * @param [type] $request [description] * @return [type] [description] */ public function postLogin($request) { $result = new Result(); $data = $request->only('username', 'password'); try { $this->uValidator->with($data)->passesOrFail(ValidatorInterface::RULE_UPDATE); try { Auth::guard('web')->attempt($data); $result->user = Auth::user()->toArray(); $result->message = trans('admin/alert.user.login_success'); } catch (Exception $e) { $result->code = 400; $result->message = trans('admin/alert.user.login_error'); $result->status = 'error'; } } catch (ValidatorException $e) { $result->code = 422; $result->message = $e->getMessageBag()->first(); $result->status = 'error'; } return $result->toJson(); } /** * [addUser 管理员添加] * 臭虫科技 * @author chouchong * @DateTime 2017-04-05T14:54:46+0800 * @param [type] $request [description] */ public function addUser($request) { $result = new Result(); $data = $request->only(['username', 'password', 'name']); try { $this->userValidator->with($data)->passesOrFail(ValidatorInterface::RULE_CREATE); $data['password'] = bcrypt($data['password']); try { $this->userRepo->create($data); $result->message = trans('admin/alert.user.create_success'); } catch (Exception $e) { $result->code = 400; $result->message = $e; $result->status = 'error'; } } catch (ValidatorException $e) { $result->code = 422; $result->message = $e->getMessageBag()->first(); $result->status = 'error'; } return $result->toJson(); } /** * [index 管理员列表] * chouchong.com * @author Sow * @DateTime 2017-04-15T23:26:15+0800 * @param [type] $request [description] * @return [type] [description] */ public function index($request) { $result = new Result(); try { $queryParams = request()->except(['s']); ksort($queryParams); $queryString = http_build_query($queryParams); $url = request()->url(); $fullUrl = "{$url}?{$queryString}"; $rememberKey = sha1($fullUrl); // 每页显示条数 $pageSize = request('pageSize', config('admin.global.pagination.pageSize')); // $role = Cache::remember($rememberKey, 2, function () use ($pageSize) { $user = $this->userRepo->orderBy('id', 'asc')->paginate($pageSize, ['id', 'name', 'username'])->toArray(); // }); $result->data = $user; } catch (Exception $e) { $result->code = 1001; $result->status = 500; $result->message = trans('admin/alert.user.index_error'); } return $result->toJson(); } /** * [destroy 管理员删除] * chouchong.com * @author Sow * @DateTime 2017-04-16T15:12:40+0800 * @param [type] $id [description] * @return [type] [description] */ public function destroy($id) { $result = new Result(); try { // 批量删除 if (!is_numeric($id)) { $isDestroy = $this->userRepo->multipleDestroy(explode(',', $id)); } else { $isDestroy = $this->userRepo->delete($id); } if ($isDestroy) { $result->message = trans('admin/alert.user.destroy_success'); } } catch (Exception $e) { $result->code = 400; $result->message = trans('admin/alert.user.destroy_error'); $result->status = 'error'; } return $result->toJson(); } /** * [show 管理员详情] * chouchong.com * @author Sow * @DateTime 2017-04-16T15:25:42+0800 * @param [type] $id [description] * @return [type] [description] */ public function show($id) { return $this->userRepo->find($id, ['id', 'name', 'username', 'password']); } /** * [update 管理员修改] * 臭虫科技 * @author chouchong * @DateTime 2017-04-13T19:36:06+0800 * @param [type] $request [description] * @param [type] $id [description] * @return [type] [description] */ public function update($request, $id) { $result = new Result(); $data = $request->except(['id']); try { $this->userValidator->with($data)->passesOrFail(ValidatorInterface::RULE_UPDATE); try { $data['password'] = bcrypt($data['password']); $isUpdate = $this->userRepo->update($data, $id); if ($isUpdate) { $result->message = trans('admin/alert.user.edit_success'); } } catch (Exception $e) { $result->code = 400; $result->message = trans('admin/alert.user.edit_error'); $result->status = 'error'; } } catch (ValidatorException $e) { $result->code = 422; $result->message = $e->getMessageBag()->first(); $result->status = 'error'; } return $result->toJson(); } /** * [role 获取角色列表] * chouchong.com * @author Sow * @DateTime 2017-04-16T21:06:52+0800 * @param string $value [description] * @return [type] [description] */ public function role() { if(Cache::has('role')){ return Cache::get('role'); } $role = $this->roleRepo->all(['id','name'])->toArray(); Cache::forever('role',$role); return $role; } /** * [getRole 管理员的角色] * chouchong.com * @author Sow * @DateTime 2017-04-16T21:17:17+0800 * @param [type] $id [description] * @return [type] [description] */ public function getRole($id) { $data = $this->userRepo->find($id)->getRoles()->toArray(); return count($data)?$data[0]:[]; } /** * [syncRoles 管理员的角色分配] * chouchong.com * @author Sow * @DateTime 2017-04-16T23:22:04+0800 * @param string $value [description] * @return [type] [description] */ public function syncRoles($request) { $result = new Result(); $id = $request->only(['id']); $role = $request->only(['role']); $roleIds = []; foreach ($role as $key => $v) { $roleIds[] = $v; } try { $this->userRepo->find($id['id'])->syncRoles($roleIds); $result->message = trans('admin/alert.user.role_succes'); } catch (Exception $e) { $result->code = 400; $result->message = trans('admin/alert.user.role_error'); $result->status = 'error'; } return $result->toJson(); } /** * [getPermissions 管理员的权限节点] * chouchong.com * @author Sow * @DateTime 2017-04-16T23:58:10+0800 * @return [type] [description] */ public function getPermissions() { $user = auth()->user(); if(Cache::has('userpermission'.$user->id)){ return Cache::get('userpermission'.$user->id); } $permission = $user->getPermissions()->toArray(); $data = sort_parent($permission); Cache::forever('userpermission'.$user->id,$data); return $data; } }
C
UTF-8
415
2.578125
3
[]
no_license
#include "libmfcrc.h" static uint8_t crc8_reduce(uint8_t idx) { uint8_t cnt = 8; do { uint8_t m = idx & 0x80; idx <<= 1; if (m) idx ^= 0x07; } while (--cnt); return idx; } uint8_t crc8_ccitt_byte(uint8_t crc, uint8_t c) { return crc8_reduce(crc ^ c); } uint8_t crc8_ccitt(const uint8_t *buf, uint8_t len, uint8_t init) { do { init = crc8_reduce(init ^ *buf++); } while (len--); return init; }
Java
UTF-8
826
1.757813
2
[]
no_license
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.paypal.android.sdk; import android.support.design.widget.al; import java.util.concurrent.CountDownLatch; public class fn { final al a; private final CountDownLatch b; private long c; private long d; void a() { if (c != -1L) { throw new IllegalStateException(); } else { c = System.nanoTime(); return; } } void b() { if (d != -1L || c == -1L) { throw new IllegalStateException(); } else { d = System.nanoTime(); b.countDown(); return; } } }
C#
UTF-8
832
2.609375
3
[]
no_license
using System; using System.Collections.Generic; using AlaskaAirlines.BL.Models; using AlaskaAirlines.DAL; namespace AlaskaAirlines.BL { public class AirportManager { private static AirportManager _instance; private const String AIRPORT_FILEPATH = "c:\\users\\paul\\documents\\visual studio 2017\\Projects\\AlaskaAirlines\\AlaskaAirlines\\airports.csv"; public static AirportManager Instance => _instance ?? (_instance = new AirportManager()); public List<Airport> airports { get; } private AirportManager() { airports = GetAirports(AIRPORT_FILEPATH); } private List<Airport> GetAirports(String absoluteFilePath) { return CSVParser.LoadCsv<Airport>(absoluteFilePath); } } }
PHP
UTF-8
4,802
2.96875
3
[]
no_license
<?php namespace MasterDmx\LaravelMedia\Images; use Intervention\Image\Image; use MasterDmx\LaravelMedia\Contexts\Context; use MasterDmx\LaravelMedia\Exceptions\ValidationException; class ImageValidator { /** * Минимальная ширина */ public const RULE_MIN_WIDTH = 'min_width'; /** * Максимальная ширина */ public const RULE_MAX_WIDTH = 'max_width'; /** * Минимальная высота */ public const RULE_MIN_HEIGHT = 'min_height'; /** * Максимальная высота */ public const RULE_MAX_HEIGHT = 'max_height'; private Context $context; private Image $image; /** * Массив ошибок * * @var array */ private array $errors; /** * ImageValidator constructor. * * @param Context $context * @param Image $image */ public function __construct(Context $context, Image $image) { $this->context = $context; $this->image = $image; } /** * Запуск валидации */ public function validate(): void { $rules = $this->context->rules(); if (!empty($rules)) { if (isset($rules[static::RULE_MAX_HEIGHT]) && !$this->checkMaxHeight($rules[static::RULE_MAX_HEIGHT])) { $message = $this->parseMessage( config('media.validation_messages.max_height', ''), static::RULE_MAX_HEIGHT, $rules[static::RULE_MAX_HEIGHT] ); $this->addError(static::RULE_MAX_HEIGHT, $message); } // Минимальная высота if (isset($rules[static::RULE_MIN_HEIGHT]) && !$this->checkMinHeight($rules[static::RULE_MIN_HEIGHT])) { $message = $this->parseMessage( config('media.validation_messages.min_height', ''), static::RULE_MIN_HEIGHT, $rules[static::RULE_MIN_HEIGHT] ); $this->addError(static::RULE_MIN_HEIGHT, $message); } // Минимальная ширина if (isset($rules[static::RULE_MIN_WIDTH]) && !$this->checkMinWidth($rules[static::RULE_MIN_WIDTH])) { $message = $this->parseMessage( config('media.validation_messages.min_width', ''), static::RULE_MIN_WIDTH, $rules[static::RULE_MIN_WIDTH] ); $this->addError(static::RULE_MIN_WIDTH, $message); } // Максимальная ширина if (isset($rules[static::RULE_MAX_WIDTH]) && !$this->checkMaxWidth($rules[static::RULE_MAX_WIDTH])) { $message = $this->parseMessage( config('media.validation_messages.max_width', ''), static::RULE_MAX_WIDTH, $rules[static::RULE_MAX_WIDTH] ); $this->addError(static::RULE_MAX_WIDTH, $message); } } if (!empty($this->errors)) { throw new ValidationException($this->errors); } } public static function start(Context $context, Image $image): self { $validator = new static($context, $image); $validator->validate(); return $validator; } protected function parseMessage(string $message, $ruleKey, $ruleValue) { if (mb_strpos($message, '{width}') !== false) { $message = str_replace('{width}', $this->image->width(), $message); } if (mb_strpos($message, '{height}') !== false) { $message = str_replace('{height}', $this->image->height(), $message); } if (mb_strpos($message, '{rule_' . $ruleKey . '}') !== false) { $message = str_replace('{rule_' . $ruleKey . '}', $ruleValue, $message); } return $message; } protected function addError(string $rule, string $message = '') { $this->errors[] = [ 'rule' => $rule, 'message' => $message, ]; } // ------------------------------------ // Обработка правил // ----------------------------------- protected function checkMinWidth(int $width): bool { return $this->image->width() >= $width; } protected function checkMaxWidth(int $width): bool { return $this->image->width() <= $width; } protected function checkMaxHeight(int $height): bool { return $this->image->height() <= $height; } protected function checkMinHeight(int $height): bool { return $this->image->height() >= $height; } }
Python
UTF-8
1,437
3.09375
3
[]
no_license
#!/usr/bin/python # coding: utf-8 import smbus import time bus = smbus.SMBus(1) # I2Cバス番号 address = 0x49 # ADS1015のI2Cアドレス # I2C data write (1byte) def write(reg, value): bus.write_byte_data(address, reg, value) # I2C data write (block) def blockwrite(reg, s): bus.write_i2c_block_data(address, reg, s[0:]) # I2C data read (1byte) def read(reg): value = bus.read_byte_data(address, reg) return value # I2C data write (block) def blockread(reg, value): value = bus.read_i2c_block_data(address, reg, value) return value while 1: # 初期設定(single,+/-4.096V range(GAIN=1),single-shot mode,1600 sample per sec) blockwrite(0x01, [0xC3, 0x83]) # CONFIGレジスタに0xC383を書き込む(AIN0) # blockwrite(0x01, [0xD3,0x83]) #CONFIGレジスタに0xD383を書き込む(AIN1) # blockwrite(0x01, [0xE3,0x83]) #CONFIGレジスタに0xE383を書き込む(AIN2) # blockwrite(0x01, [0xF3,0x83]) #CONFIGレジスタに0xF383を書き込む(AIN3) time.sleep(0.01) # 10ms(A/D変換処理待ちを少しいれる) # データ取得 ad_raw = blockread(0x00, 2) # データ整形 ad_val = ((ad_raw[0] & 0xFF) << 8) | (ad_raw[1] & 0xFF) ad_val = ad_val >> 4 # +/- 4.096Vで11bit分解能(GAIN=1設定) ad = ad_val * 4.096 / 2048 # 表示出力 print "ad = " + str(ad) + " V" time.sleep(1) # 1秒
C++
UTF-8
610
2.546875
3
[]
no_license
#pragma once /** * The following relevant macros are defined in the makefile: * CTH_SRATE * CTH_INTEGRAL * CTH_FLOATING * * When possible, use the corresponding constexpr bool values or types defined in this file. */ #define STRING(x) #x #define LITERAL(x) STRING(x) namespace cynth { /** Sample rate in kHz */ constexpr double sampleRate = CTH_SRATE; // kHz using Integral = CTH_INTEGRAL; using Floating = CTH_FLOATING; constexpr char const * integral = LITERAL(CTH_INTEGRAL); constexpr char const * floating = LITERAL(CTH_FLOATING); } #undef STRING #undef LITERAL
Java
UTF-8
11,857
1.84375
2
[]
no_license
package com.sipai.controller.process; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import net.sf.json.JSONArray; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.sipai.entity.process.Real; import com.sipai.entity.process.RealDetails; import com.sipai.entity.process.RealDetailsMaterial; import com.sipai.entity.process.TaskMaterial; import com.sipai.entity.user.User; import com.sipai.service.process.RealDetailsMaterialService; import com.sipai.service.process.RealDetailsService; import com.sipai.service.process.RealService; import com.sipai.service.process.TaskMaterialService; import com.sipai.tools.CommUtil; @Controller @RequestMapping("/process/realDetailsMaterial") public class RealDetailsMaterialController { @Resource private RealService realService; @Resource private RealDetailsMaterial realDetailsMaterial; @Resource private RealDetailsService realDetailsService; @Resource private RealDetailsMaterialService realDetailsMaterialService; @Resource private TaskMaterialService taskMaterialService; @RequestMapping("/showList.do") public String showList(HttpServletRequest request,Model model){ return "process/realDetailsMaterialList"; } @RequestMapping("/getlist.do") public ModelAndView getlist(HttpServletRequest request,Model model, @RequestParam(value = "page") Integer page, @RequestParam(value = "rows") Integer rows, @RequestParam(value = "sort", required=false) String sort, @RequestParam(value = "order", required=false) String order) { User cu=(User)request.getSession().getAttribute("cu"); if(sort==null){sort = " insdt ";} if(order==null){order = " asc ";} String orderstr=" order by "+sort+" "+order; String wherestr=CommUtil.getwherestr("insuser", "process/real/showlist.do", cu); if(request.getParameter("pid")!=null && !request.getParameter("pid").isEmpty()){ wherestr += " and pid = '"+request.getParameter("pid")+"' "; } if(request.getParameter("search_name")!=null && !request.getParameter("search_name").isEmpty()){ wherestr += " and name like '%"+request.getParameter("search_name")+"%' "; } PageHelper.startPage(page, rows); List<RealDetailsMaterial> list = this.realDetailsMaterialService.selectListByWhere(wherestr+orderstr); PageInfo<RealDetailsMaterial> pi = new PageInfo<RealDetailsMaterial>(list); JSONArray json=JSONArray.fromObject(list); String result="{\"total\":"+pi.getTotal()+",\"rows\":"+json+"}"; model.addAttribute("result",result); return new ModelAndView("result"); } @RequestMapping("/add.do") public String doadd(HttpServletRequest request,Model model){ String detailsId = request.getParameter("pid"); List<Real> realList = realService.getListByDetailsID(detailsId); if(realList!=null&&realList.size()>0){ model.addAttribute("productcode", realList.get(0).getProduct().getMaterialcode()); } return "process/realDetailsMaterialAdd"; } @RequestMapping("/edit.do") public String doedit(HttpServletRequest request,Model model, @RequestParam(value="id") String id){ realDetailsMaterial = this.realDetailsMaterialService.selectById(id); String detailsId = realDetailsMaterial.getPid(); List<Real> realList = realService.getListByDetailsID(detailsId); if(realList!=null&&realList.size()>0){ model.addAttribute("productcode", realList.get(0).getProduct().getMaterialcode()); } model.addAttribute("realDetailsMaterial", realDetailsMaterial); return "process/realDetailsMaterialEdit"; } // @RequestMapping("/save.do") // public String dosave(HttpServletRequest request,Model model, // @ModelAttribute RealDetailsMaterial realDetailsMaterial){ // User cu= (User)request.getSession().getAttribute("cu"); // // String id = CommUtil.getUUID(); // realDetailsMaterial.setId(id); // realDetailsMaterial.setInsuser(cu.getId()); // realDetailsMaterial.setInsdt(CommUtil.nowDate()); // // int result = this.realDetailsMaterialService.save(realDetailsMaterial); // String resstr="{\"res\":\""+result+"\",\"id\":\""+id+"\"}"; // model.addAttribute("result", resstr); // return "result"; // } @RequestMapping("/save.do") public String dosave(HttpServletRequest request,Model model, @ModelAttribute RealDetailsMaterial realDetailsMaterial){ User cu= (User)request.getSession().getAttribute("cu"); //清除所有旧数据 this.realDetailsMaterialService.deleteByWhere("where pid in ('"+request.getParameter("pid")+"')"); String resultstr=""; int result = 0; int suc = 0; int fal = 0; if(!request.getParameter("mids").equals("")){ String mids[]=request.getParameter("mids").split(","); if(mids.length>0){ for(int i=0;i<mids.length;i++){ String id = CommUtil.getUUID(); realDetailsMaterial.setId(id); realDetailsMaterial.setPid(request.getParameter("pid")); realDetailsMaterial.setMaterialid(mids[i]); realDetailsMaterial.setAmount(1.00); realDetailsMaterial.setInsuser(cu.getId()); realDetailsMaterial.setInsdt(CommUtil.nowDate()); result = this.realDetailsMaterialService.save(realDetailsMaterial); if(result==1){ suc++; }else{ fal++; } } } } if(request.getParameter("mids").equals("")){ resultstr += "已清除所有数据!"; } if(suc>0){ resultstr += "成功添加"+suc+"条数据!"; } if(fal>0){ resultstr += fal+"条数据添加失败!"; } model.addAttribute("result", resultstr); return "result"; } @RequestMapping("/update.do") public String doupdate(HttpServletRequest request,Model model, @ModelAttribute RealDetailsMaterial realDetailsMaterial){ User cu= (User)request.getSession().getAttribute("cu"); realDetailsMaterial.setUpduser(cu.getId()); realDetailsMaterial.setUpddt(CommUtil.nowDate()); int result = this.realDetailsMaterialService.update(realDetailsMaterial); String resstr="{\"res\":\""+result+"\",\"id\":\""+realDetailsMaterial.getId()+"\"}"; model.addAttribute("result", resstr); return "result"; } @RequestMapping("/updateamount.do") public String updateamount(HttpServletRequest request,Model model, @ModelAttribute RealDetailsMaterial realDetailsMaterial){ User cu= (User)request.getSession().getAttribute("cu"); String resultstr=""; int result = 0; int suc = 0; int fal = 0; if(!request.getParameter("ids").equals("")){ String ids[]=request.getParameter("ids").split(","); String amounts[] = request.getParameter("amounts").split(","); if(ids.length>0){ for(int i=0;i<ids.length;i++){ realDetailsMaterial = this.realDetailsMaterialService.selectById(ids[i]); if(amounts[i]!=null&&amounts[i]!=""){ Double amount = Double.valueOf(amounts[i]); realDetailsMaterial.setAmount(amount); }else{ realDetailsMaterial.setAmount(0.00); } realDetailsMaterial.setUpduser(cu.getId()); realDetailsMaterial.setUpddt(CommUtil.nowDate()); result = this.realDetailsMaterialService.update(realDetailsMaterial); if(result==1){ suc++; }else{ fal++; } } } } if(suc>0){ resultstr += "成功保存"+suc+"条数据!"; } if(fal>0){ resultstr += fal+"条数据保存失败!"; } model.addAttribute("result", resultstr); return "result"; } @RequestMapping("/saveamount.do") public String saveamount(HttpServletRequest request,Model model, @ModelAttribute RealDetailsMaterial realDetailsMaterial){ User cu= (User)request.getSession().getAttribute("cu"); String resultstr=""; int result = 0; if(!request.getParameter("id").equals("")){ String id=request.getParameter("id"); String amountStr = request.getParameter("amount"); realDetailsMaterial = this.realDetailsMaterialService.selectById(id); if(amountStr!=null&&amountStr!=""){ Double amount = Double.valueOf(amountStr); realDetailsMaterial.setAmount(amount); }else{ realDetailsMaterial.setAmount(0.00); } realDetailsMaterial.setUpduser(cu.getId()); realDetailsMaterial.setUpddt(CommUtil.nowDate()); result = this.realDetailsMaterialService.update(realDetailsMaterial); } if(result>0){ resultstr += "保存成功!"; }else{ resultstr += "保存失败!"; } model.addAttribute("result", resultstr); return "result"; } @RequestMapping("/delete.do") public String dodel(HttpServletRequest request,Model model, @RequestParam(value="id") String id){ int result = this.realDetailsMaterialService.deleteById(id); model.addAttribute("result", result); return "result"; } @RequestMapping("/deletes.do") public String dodels(HttpServletRequest request,Model model, @RequestParam(value="ids") String ids){ ids=ids.replace(",","','"); int result = this.realDetailsMaterialService.deleteByWhere("where id in ('"+ids+"')"); model.addAttribute("result", result); return "result"; } @RequestMapping("/getTaskMaterial.do") public ModelAndView getTaskMaterial(HttpServletRequest request,Model model, @RequestParam(value = "page") Integer page, @RequestParam(value = "rows") Integer rows, @RequestParam(value = "sort", required=false) String sort, @RequestParam(value = "order", required=false) String order) { if(sort==null){sort = " materialcode ";} if(order==null){order = " asc ";} String orderstr=" order by "+sort+" "+order; String wherestr="where 1=1 "; if(request.getParameter("pid")!=null && !request.getParameter("pid").isEmpty()){ wherestr += " and tb_process_real_details.id='"+request.getParameter("pid")+"'"; RealDetails realDetail= this.realDetailsService.selectById(request.getParameter("pid")); wherestr += " and tb_process_task_material.taskname = '"+realDetail.getTaskname()+"' "; } if(request.getParameter("search_name")!=null && !request.getParameter("search_name").isEmpty()){ wherestr += " and tb_material_info.materialname like '%"+request.getParameter("search_name")+"%' "; } if(request.getParameter("search_code")!=null && !request.getParameter("search_code").isEmpty()){ wherestr += " and tb_material_info.materialcode like '%"+request.getParameter("search_code")+"%' "; } PageHelper.startPage(page, rows); List<TaskMaterial> list = this.taskMaterialService.selectListByWhere1(wherestr+orderstr); PageInfo<TaskMaterial> pi = new PageInfo<TaskMaterial>(list); JSONArray json=JSONArray.fromObject(list); String result="{\"total\":"+pi.getTotal()+",\"rows\":"+json+"}"; model.addAttribute("result",result); return new ModelAndView("result"); } @RequestMapping("/getchecklist.do") public ModelAndView getchecklist(HttpServletRequest request,Model model) { String wherestr="where 1=1 "; if(request.getParameter("pid")!=null && !request.getParameter("pid").isEmpty()){ wherestr += " and pid = '"+request.getParameter("pid")+"' "; } List<RealDetailsMaterial> list = this.realDetailsMaterialService.selectListByWhere(wherestr); JSONArray json=JSONArray.fromObject(list); String result="{\"rows\":"+json+"}"; model.addAttribute("result",result); return new ModelAndView("result"); } }
Java
UTF-8
1,169
2.703125
3
[ "Apache-2.0" ]
permissive
package io.github.wanghuayao.jutils.serializer.converter.impl; import io.github.wanghuayao.jutils.serializer.converter.ByteConverter; import java.math.BigDecimal; import java.math.BigInteger; public class BigDecimalByteconverter implements ByteConverter<BigDecimal> { ByteConverter<Integer> intByteConverter = new IntByteconverter(); @Override public byte[] toBytes(BigDecimal val) { byte[] scaleBytes = intByteConverter.toBytes(val.scale()); byte[] intBytes = val.unscaledValue().toByteArray(); byte[] result = new byte[scaleBytes.length + intBytes.length]; System.arraycopy(scaleBytes, 0, result, 0, scaleBytes.length); System.arraycopy(intBytes, 0, result, scaleBytes.length, intBytes.length); return result; } @Override public BigDecimal fromBytes(byte[] bytes) { int scale = intByteConverter.fromBytes(bytes); byte[] intBytes = new byte[bytes.length - 4]; System.arraycopy(bytes, 4, intBytes, 0, intBytes.length); BigInteger bigInteger = new BigInteger(intBytes); return new BigDecimal(bigInteger, scale); } }
Java
UTF-8
1,294
2.328125
2
[]
no_license
package servlet; import com.google.gson.Gson; import com.google.gson.JsonObject; import dao.HotelDao; import entity.Hotel; import global.Utils; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet(name = "CustomerHotelChooseServlet",urlPatterns = {"/CustomerHotelChooseServlet"}) public class CustomerHotelChooseServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doGet(req, resp); } // Post: id, hotel_name // 返回hotel所有属性 @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { JsonObject json=Utils.req2json(req); String hotelName =json.get("hotel_name").getAsString(); // System.out.println(hotelName); Hotel hotel = HotelDao.findHotel(Integer.parseInt(hotelName)); if (hotel == null) { Utils.sendJsonFailure(resp, 0); return; } Utils.sendJsonResp(resp, new Gson().toJson(hotel)); } }
C++
UTF-8
447
2.609375
3
[]
no_license
#include <iostream> #include <math.h> #include "loading.h" using namespace std; int main(int argc, char const *argv[]) { const double pi =3.14; loading(); double a; cout<<"Xin moi nhap so can tinh: "; cin>>a; double t = (a*pi)/180; cout<<"\nsin:"<<sin(t); cout<<"\n"; cout<<"cos:"<<cos(t)<<" "; cout<<"\n"; cout<<"tan:"<<tan(t)<<" "; cout<<"\n"; cout<<"cotan:"<<1/tan(t)<<" "; return 0; }
Java
UTF-8
635
1.898438
2
[]
no_license
package com.tuojin.tvfilm.contract; import com.tuojin.tvfilm.base.BaseView; import com.tuojin.tvfilm.bean.CategoryInfo; import java.util.List; /** * 文 件 名: CategoryContract * 创 建 人: Administrator * 创建日期: 2016/9/21 13:50 * 文件描述: * 邮 箱: * 博 客: * 修改时间: * 修改备注: */ public class CategoryContract { public interface View extends BaseView { void setRecycleCategoryList(final List<CategoryInfo> datas); } public interface Presenter { void onResume(); } public interface Model { List<CategoryInfo> initCategory(); } }
Python
UTF-8
868
3.71875
4
[]
no_license
#!/usr/bin/python3 """ In this module it create a Class Rectangle""" BaseGeometry = __import__('7-base_geometry').BaseGeometry class Rectangle(BaseGeometry): """This a class Rectangle""" def __init__(self, width, height): """Initialize an instance of Rectangle Arguments: width: value for __width attribute height: value for __height attribute """ self.integer_validator("width", width) self.integer_validator("height", height) self.__width = width self.__height = height def area(self): """This method return value of area""" return self.__height * self.__width def __str__(self): """Return string representation of object Rectangle""" string_obj = "[Rectangle] {}/{}".format(self.__width, self.__height) return string_obj
Java
UTF-8
14,570
2.046875
2
[]
no_license
package cn.weli.svideo.module.video.component.widget.videoheart; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; import android.widget.RelativeLayout; import java.util.ArrayList; import java.util.List; import java.util.Random; import cn.weli.svideo.R; import cn.weli.svideo.WlVideoAppInfo; import cn.weli.svideo.baselib.helper.BitmapHelper; import cn.weli.svideo.baselib.helper.handler.WeakHandler; /** * 点击出现爱心的效果 * * @author Lei Jiang * @version [1.0.0] * @date 2019-11-19 * @see [class/method] * @since [1.0.0] */ public class HeartRelativeLayout extends RelativeLayout implements View.OnTouchListener { /** * 双击间格毫秒延时 */ private static final int TIME_OUT_DELAY = 400; /** * 双击点赞大小 */ private static final int DEFAULT_SCALE_SIZE = 4; /** * 透明度,默认为255,0为消失不可见 */ private static final int MAX_ALPHA = 255; /** * 存放多个心形图 */ private List<HeartBean> list = new ArrayList<>(); /** * true为开始动画,false为结束动画 */ private boolean START = true; /** * 动画刷新频率 */ private int refreshRate = 16; /** * 最小旋转角度 */ private int degreesMin = -30; /** * 最大旋转角度 */ private int degreesMax = 30; /** * 初始图片 */ private Bitmap bitmap; /** * 控制bitmap旋转角度和缩放的矩阵 */ private Matrix matrix = new Matrix(); /** * 记录第一次点击的时间 */ private long singleClickTime; /** * 是否需要抖动效果 默认抖动 */ private boolean isShake = true; /** * 是否是双击 */ private boolean isDoubleClick; private boolean enableDoubleClick; private OnHeartTouchListener mTouchListener; private GestureDetector mGestureDetector; public interface OnHeartTouchListener { void onSingleClick(); void onDoubleClick(); } public void setTouchListener(OnHeartTouchListener touchListener) { mTouchListener = touchListener; } public void setEnableDoubleClick(boolean enableDoubleClick) { this.enableDoubleClick = enableDoubleClick; } private WeakHandler handler = new WeakHandler(new Handler.Callback() { @Override public boolean handleMessage(Message msg) { switch (msg.what) { case 0: try { refresh(); invalidate(); if (list != null && list.size() > 0) { handler.sendEmptyMessageDelayed(0, refreshRate);// 延时 } } catch (Exception e) { e.printStackTrace(); } break; default: break; } return false; } }); public HeartRelativeLayout(Context context) { super(context); } public HeartRelativeLayout(Context context, AttributeSet attrs) { super(context, attrs); try { @SuppressLint("CustomViewStyleable") TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.HeartViewGroup); isShake = typedArray.getBoolean(R.styleable.HeartViewGroup_heart_shake, isShake); refreshRate = typedArray.getInt(R.styleable.HeartViewGroup_heart_refresh_rate, refreshRate); degreesMin = typedArray.getInt(R.styleable.HeartViewGroup_heart_degrees_interval_min, degreesMin); degreesMax = typedArray.getInt(R.styleable.HeartViewGroup_heart_degrees_interval_max, degreesMax); typedArray.recycle(); singleClickTime = System.currentTimeMillis(); GestureListener gestureListener = new GestureListener(); mGestureDetector = new GestureDetector(context, gestureListener); mGestureDetector.setOnDoubleTapListener(new DoubleGestureListener()); //为当前View设置触控 setOnTouchListener(this); setLongClickable(true); setClickable(true); setFocusable(true); } catch (Exception e) { } } @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); try { if (list == null || matrix == null || bitmap == null) { return; } for (int i = 0; i < list.size(); i++) { HeartBean heartBean = list.get(i); // 重置 matrix.reset(); // 缩放原图 matrix.postScale(heartBean.scanle * DEFAULT_SCALE_SIZE, heartBean.scanle * DEFAULT_SCALE_SIZE, heartBean.X + bitmap.getWidth() / 2, heartBean.Y + bitmap.getHeight() / 2); // 旋转 matrix.postRotate(heartBean.degrees, heartBean.X + bitmap.getWidth() / 2, heartBean.Y + bitmap.getHeight() / 2); canvas.save(); canvas.concat(matrix); canvas.drawBitmap(bitmap, heartBean.X - bitmap.getWidth() / 2, heartBean.Y - bitmap.getHeight() / 2, heartBean.paint); canvas.restore(); } } catch (Exception e) { e.printStackTrace(); } } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { try { return super.onInterceptTouchEvent(ev); } catch (Exception ex) { ex.printStackTrace(); } return false; } @Override public boolean onTouch(View view, MotionEvent event) { try { return mGestureDetector.onTouchEvent(event); } catch (Exception ex) { ex.printStackTrace(); } return false; } // @SuppressLint("ClickableViewAccessibility") // @Override // public boolean onTouchEvent(final MotionEvent event) { // switch (event.getAction()) { // case MotionEvent.ACTION_DOWN: // long newClickTime = System.currentTimeMillis(); // //双击以上事件都会调用心动动画 // if (newClickTime - singleClickTime < TIME_OUT_DELAY) { // //开始心动动画 // startSwipe(event); // } // singleClickTime = newClickTime; // break; // case MotionEvent.ACTION_MOVE: // Logger.e("onTouchEvent MotionEvent.ACTION_MOVE"); // break; // case MotionEvent.ACTION_UP: // Logger.e("onTouchEvent MotionEvent.ACTION_UP"); // break; // default: // break; // } // return mGestureDetector.onTouchEvent(event); // } /** * 初始化paint */ private Paint initPaint(int alpha) { Paint paint = new Paint(); paint.setAntiAlias(true); paint.setAlpha(alpha); return paint; } /** * 开始心动动画 * * @param event 点击事件 */ private void startSwipe(MotionEvent event) { try { if (list == null || handler == null) { return; } HeartBean bean = new HeartBean(); bean.scanle = 1; bean.alpha = MAX_ALPHA; bean.X = (int) event.getX(); bean.Y = (int) event.getY(); bean.paint = initPaint(bean.alpha); bean.degrees = degrees(degreesMin, degreesMax); if (list.size() == 0) { START = true; } list.add(bean); invalidate(); if (START) { handler.sendEmptyMessage(0); } } catch (Exception e) { e.printStackTrace(); } } /*** * 刷新 */ private void refresh() { try { if (list == null) { return; } List<HeartBean> removeList = new ArrayList<>(); for (int i = 0; i < list.size(); i++) { HeartBean bean = list.get(i); bean.count++; if (!START && bean.alpha == 0) { //透明度减为0后,从list里清除 removeList.add(bean); bean.paint = null; continue; } else if (START) { START = false; } if (bean.count <= 1 && isShake) { //初始为1.9倍大小 步骤A bean.scanle = 1.9f; } else if (bean.count <= 6 && isShake) { //每次缩小0.2,缩小5帧后为0.9 步骤B bean.scanle -= 0.2; } else if (bean.count <= 15 && isShake) { //恢复原图大小 步骤C ABC三个步骤主要实现一个初始跳动心心的效果 bean.scanle = 1; } else { //放大倍数 每次放大0.1 bean.scanle += 0.1; //透明度 bean.alpha -= 10; if (bean.alpha < 0) { bean.alpha = 0; } } bean.paint.setAlpha(bean.alpha); } if (!removeList.isEmpty()) { list.removeAll(removeList); } } catch (Exception e) { e.printStackTrace(); } } /** * 生成一个随机整数 * * @param min 最小值 * @param max 最大值 * @return 整数 */ private int degrees(int min, int max) { try { //若最小值大于最大值,则重新赋值正位 if (min > max) { int x = min; min = max; max = x; } Random random = new Random(); return random.nextInt((max - min) + 1) + min; } catch (Exception e) { e.printStackTrace(); } return min; } /** * 设置跳动的图片 * * @param id 图片资源id */ public void setSwipeImage(int id) { try { bitmap = BitmapFactory.decodeResource(getResources(), id); } catch (Exception e) { e.printStackTrace(); } } /** * 设置是否抖动一下 * 默认抖动 * * @param isShake true为抖动 */ public void setShake(boolean isShake) { this.isShake = isShake; } /** * 设置动画刷新频率 * 默认16ms * * @param refreshRate 刷新频率,单位:毫秒 */ public void setRefreshRate(int refreshRate) { this.refreshRate = refreshRate; } /** * 图片旋转角度区间 * 0-360 * * @param min 最小旋转角度 * @param max 最大旋转角度 */ public void setDegreesInterval(int min, int max) { degreesMin = min; degreesMax = max; } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); try { bitmap = BitmapHelper.readBitMap(WlVideoAppInfo.sAppCtx, R.drawable.home_icon_dianzan_selected, DEFAULT_SCALE_SIZE); matrix = new Matrix(); list = new ArrayList<>(); } catch (Exception e) { } } /** * viewGroup销毁时释放资源 */ @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); try { if (bitmap != null) { bitmap.recycle(); } bitmap = null; matrix = null; list = null; } catch (Exception e) { } } private class GestureListener implements GestureDetector.OnGestureListener { @Override public boolean onDown(MotionEvent motionEvent) { return false; } @Override public void onShowPress(MotionEvent motionEvent) { } @Override public boolean onSingleTapUp(MotionEvent motionEvent) { if (!enableDoubleClick) { if (mTouchListener != null) { mTouchListener.onSingleClick(); } return true; } handler.postDelayed(() -> { if (isDoubleClick) { isDoubleClick = false; } else { if (mTouchListener != null) { mTouchListener.onSingleClick(); } } }, TIME_OUT_DELAY); return false; } @Override public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) { return false; } @Override public void onLongPress(MotionEvent motionEvent) { } @Override public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) { return false; } } private class DoubleGestureListener implements GestureDetector.OnDoubleTapListener { @Override public boolean onSingleTapConfirmed(MotionEvent motionEvent) { return false; } @Override public boolean onDoubleTap(MotionEvent event) { if (!enableDoubleClick) { return true; } isDoubleClick = true; startSwipe(event); if (mTouchListener != null) { mTouchListener.onDoubleClick(); } return false; } @Override public boolean onDoubleTapEvent(MotionEvent motionEvent) { return false; } } }
Java
UTF-8
1,603
2.65625
3
[]
no_license
package sample; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import javafx.scene.control.TextArea; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Controller { public ComboBox choiceTimeZone; public TextArea result; public TextArea userTime; public Button btnCheck; public Button btnExit; public void choiceTimeZone(ActionEvent actionEvent) { String selValue = (String) choiceTimeZone.getValue(); selValue = processValue(selValue); showTime(selValue); } private void showTime(String selValue) { java.util.TimeZone timeZone = java.util.TimeZone.getTimeZone(selValue); java.util.Calendar calendar = java.util.Calendar.getInstance(timeZone); result.setText(calendar.get(java.util.Calendar.HOUR_OF_DAY)+":"+calendar.get(java.util.Calendar.MINUTE)+":"+calendar.get(java.util.Calendar.SECOND)); } private String processValue(String selValue) { Pattern pattern = Pattern.compile("([A-Z]+[\\-?+]?\\d+:\\d+)"); Matcher matcher = pattern.matcher(selValue); while (matcher.find()){ selValue = matcher.group(0); } return selValue; } public void userTimeZone(ActionEvent actionEvent) { String userZone = userTime.getText(); userZone = processValue(userZone); showTime(userZone); } public void exitProgram(ActionEvent actionEvent) { Platform.exit(); System.exit(0); } }
Shell
UTF-8
1,442
2.71875
3
[]
no_license
# save time! yum install -y /usr/bin/applydeltarpm # make sure we have compilers and such like yum groupinstall -y 'Development Tools' # go and get the SoftwareCollections.org wget https://www.softwarecollections.org/repos/rhscl/php55/epel-7-x86_64 # add Webtatic repo for PHP 5.5 packages rpm -Uvh https://mirror.webtatic.com/yum/el7/epel-release.rpm rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm # install Nginx yum install -y --skip-broken nginx # configure SSL support mkdir /etc/nginx/ssl chmod 700 /etc/nginx/ssl cp /tmp/storyplayer/ssl/nginx.crt /etc/nginx/ssl cp /tmp/storyplayer/ssl/nginx.key /etc/nginx/ssl cp /tmp/storyplayer/ssl/default.conf /etc/nginx/conf.d/ # install libzmq4 stable git clone https://github.com/zeromq/zeromq4-x.git ( cd zeromq4-x && ./autogen.sh && ./configure && make -j 4 install ) # install PHP 5.5 from Webtatic repo yum install -y php55w php55w-devel php55w-pear echo | pecl install zmq-1.1.2 cp /tmp/storyplayer/zmq/centos6-zmq.ini /etc/php.d/zmq.ini # install Supervisor yum install -y python-setuptools easy_install supervisor mkdir /etc/supervisor.d cp /tmp/storyplayer/supervisor/supervisord.conf /etc/supervisord.conf # install our ZMQ echo server cp /tmp/storyplayer/zmq/zmq-echo-server.php /usr/local/bin/zmq-echo-server.php cp /tmp/storyplayer/zmq/zmq-echo-server.conf /etc/supervisor.d/zmq-echo-server.conf # install other tools that we need yum install -y screen
Java
UTF-8
2,653
2.59375
3
[]
no_license
package rs.fon.miltek.models; import java.io.Serializable; import java.text.DecimalFormat; public class Product implements Serializable{ private int productID; private String title; private double price; private int brandID; private int categoryID; private String image; private String description; private int featured; private int quantity; DecimalFormat df = new DecimalFormat("#0.00"); public Product(int productID, String title, double price, int brandID, int categoryID, String image, String description, int featured, int quantity) { this.productID = productID; this.title = title; this.price = price; this.brandID = brandID; this.categoryID = categoryID; this.image = image; this.description = description; this.featured = featured; this.quantity = quantity; } public Product(String title, String image, String description, int quantity){ this.title = title; this.image = image; this.description = description; this.quantity = quantity; } public int getProductID() { return productID; } public void setProductID(int productID) { this.productID = productID; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public double getPrice() { return price; } public String getPriceS() { return df.format(price)+" RSD"; } public void setPrice(double price) { this.price = price; } public int getBrandID() { return brandID; } public void setBrandID(int brandID) { this.brandID = brandID; } public int getCategoryID() { return categoryID; } public void setCategoryID(int categoryID) { this.categoryID = categoryID; } public String getImage() { if(image.isEmpty()){ return ""; } return String.format("https://miltek.000webhostapp.com/img/products/%s", image); } public void setImage(String image) { this.image = image; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getFeatured() { return featured; } public void setFeatured(int featured) { this.featured = featured; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } }
Python
UTF-8
2,671
3.34375
3
[]
no_license
#!/usr/local/bin/python3 ''' Main program to show how to use this. See terms.txt for definitions and explanations. ''' if __name__ == "__main__": # pylint doesn't like the fact that my variables are lowercase here # pylint: disable=invalid-name from solvers import BFSSolver from puzzles import Expert39, Expert40, EXPERT40_TRANSLATOR, EXPERT40_SOLUTION from util import convert_to_rc_solution, SolutionStepper, invert_dictionary from framework import Board puzzle: Board = Expert39() solver = BFSSolver() solution = solver.solve(puzzle) print("Solution to Expert Puzzle #39: {}".format(solution)) puzzle = Expert40() solver = BFSSolver() # this takes around 10 seconds on my computer solution = solver.solve(puzzle) assert solution print("Solution to Expert Puzzle #40: {}".format(solution)) # solving the puzzle does not edit the puzzle, # ...so we can get the starting position from it. rc_solution = convert_to_rc_solution(solution, EXPERT40_TRANSLATOR, puzzle.person_position) # note that this solution differs slightly from the booklet solution, but it works # I believe this solution has less walk moves, which is why the BFS solver finds it first print("River Crossing solution to Expert Puzzle #40: {}".format(rc_solution)) my_stepper = SolutionStepper(Expert40, rc_solution, invert_dictionary(EXPERT40_TRANSLATOR)) # the puzzle after 26 RC moves my_puzzle_after_moves = my_stepper.get_puzzle_at_step(26) print("The board after 26 moves of my solution: {}".format(my_puzzle_after_moves)) real_stepper = SolutionStepper(Expert40, EXPERT40_SOLUTION, invert_dictionary(EXPERT40_TRANSLATOR)) real_puzzle_after_moves = real_stepper.get_puzzle_at_step(26) print("The board after 26 moves of the real solution: {}".format(real_puzzle_after_moves)) # the solutions are not equivalent assert my_puzzle_after_moves != real_puzzle_after_moves # determine at what step my solution and the real solution diverge # note that you can also determine this just by looking at the solution strings # ...but this provides more of a tutorial my_puzzle_after_moves, real_puzzle_after_moves = None, None # type: ignore diverge_step = -1 while my_puzzle_after_moves == real_puzzle_after_moves: diverge_step += 1 my_puzzle_after_moves = my_stepper.get_puzzle_at_step(diverge_step) real_puzzle_after_moves = real_stepper.get_puzzle_at_step(diverge_step) print("My solution and the real solution diverge at step {}".format(diverge_step))
Markdown
UTF-8
462
3.09375
3
[]
no_license
# ChordApp <strong>An app that displays all 7 chord/scale intervals for all 12 musical keys</strong> https://erichkopp.github.io/TheorumWheel ![Screenshot](screenshot.png) <ul> <li>Easily transpose a song from one key to another </li> <li>Roman numeral system (I,ii,iii,IV,V,vi,vii) denotes each chord/scale interval </li> <li>Reference to find all notes within a given scale </li> <li>Color-coded major/minor/diminished chords in every key</li> </ul
Java
UTF-8
4,182
2.578125
3
[ "Apache-2.0" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.maven.surefire.api.util; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; /** * A RunOrder specifies the order in which the tests will be run. * * @author Stefan Birkner */ public class RunOrder { public static final RunOrder ALPHABETICAL = new RunOrder("alphabetical"); public static final RunOrder FILESYSTEM = new RunOrder("filesystem"); public static final RunOrder HOURLY = new RunOrder("hourly"); public static final RunOrder RANDOM = new RunOrder("random"); public static final RunOrder REVERSE_ALPHABETICAL = new RunOrder("reversealphabetical"); public static final RunOrder BALANCED = new RunOrder("balanced"); public static final RunOrder FAILEDFIRST = new RunOrder("failedfirst"); public static final RunOrder[] DEFAULT = new RunOrder[] {FILESYSTEM}; /** * Returns the specified RunOrder * * @param values The runorder string value * @return An array of RunOrder objects, never null */ public static RunOrder[] valueOfMulti(String values) { List<RunOrder> result = new ArrayList<>(); if (values != null) { StringTokenizer stringTokenizer = new StringTokenizer(values, ","); while (stringTokenizer.hasMoreTokens()) { result.add(valueOf(stringTokenizer.nextToken())); } } return result.toArray(new RunOrder[result.size()]); } public static RunOrder valueOf(String name) { if (name == null) { return null; } else { RunOrder[] runOrders = values(); for (RunOrder runOrder : runOrders) { if (runOrder.matches(name)) { return runOrder; } } String errorMessage = createMessageForMissingRunOrder(name); throw new IllegalArgumentException(errorMessage); } } private static String createMessageForMissingRunOrder(String name) { RunOrder[] runOrders = values(); StringBuilder message = new StringBuilder("There's no RunOrder with the name "); message.append(name); message.append(". Please use one of the following RunOrders: "); for (int i = 0; i < runOrders.length; i++) { if (i != 0) { message.append(", "); } message.append(runOrders[i]); } message.append('.'); return message.toString(); } private static RunOrder[] values() { return new RunOrder[] {ALPHABETICAL, FILESYSTEM, HOURLY, RANDOM, REVERSE_ALPHABETICAL, BALANCED, FAILEDFIRST}; } public static String asString(RunOrder[] runOrder) { StringBuilder stringBuffer = new StringBuilder(); for (int i = 0; i < runOrder.length; i++) { stringBuffer.append(runOrder[i].name); if (i < (runOrder.length - 1)) { stringBuffer.append(","); } } return stringBuffer.toString(); } private final String name; private RunOrder(String name) { this.name = name; } private boolean matches(String anotherName) { return name.equalsIgnoreCase(anotherName); } public String name() { return name; } @Override public String toString() { return name; } }
C++
UTF-8
606
2.515625
3
[]
no_license
//------------------------------------------------------------------------------ // @file main.cpp // @author Matthew Hird // @date February 18, 2018 // // @brief Contains main function loop. Creates a ReservationSystem class // object called resSys. Calls resSys.menu() to access the // reservation system menu. When resSys.menu() returns, the program // exits. //------------------------------------------------------------------------------ #include "reservation_system.h" int main() { ReservationSystem resSys; resSys.menu(); return 0; }
Markdown
UTF-8
3,965
2.96875
3
[ "MIT" ]
permissive
--- layout: post title: "Documentary styles" categories: - culture date: 2004-07-12 00:00 comments: true --- <p>I've been watching quite a few documentaries recently, and it has made me think a bit about what makes them effective. In the style of the old 'compare and contrast' essays we all had to write at school, I was thinking about the differences between two programmes I've seen in the past few days: Time Machine and <a href="http://www.bbc.co.uk/bbcfour/documentaries/features/jim-white.shtml" title="A documentary about the Southern states with Jim White">Searching for the Wrong-Eyed Jesus</a>. Time Machine featured computer reconstructions of physical processes which happen over a very long time scale, like glaciation, plate tectonics and the formation of the Grand Canyon. The visuals were stunning<sup>1</sup>, but the narration was terrible. It was awash with terrible puns (when they showed a kangaroo, you just <strong>knew</strong> they were going to say, "we need to JUMP BACK in time...") and Every. Word. Was. Emphasised. It was so unnecessary; the graphics were mesmerising on their own, and the narration should have provided additional information rather than bludgeoning us with how amazing it all was. It was one of those occasions when I wished that I could selectively remove the narration from the audio, leaving the music and images.</p> <p>As a complete contrast, 'Searching for the Wrong-Eyed Jesus' was a perfect documentary as far as I'm concerned. The film maker (<a href="http://www.bbc.co.uk/bbcfour/documentaries/features/andrew-douglas.shtml" title="Interview with Andrew Douglas">Andrew Douglas</a>) kept out of the way, and we were guided around the hidden parts of the Deep South by Jim White (a really excellent musician). He told us about growing up in the South after his family moved there from California, and they let ordinary people talk about their beliefs and their stories as they drove around in an beaten-up old Caddy. This was interspersed with wonderful images of bayous wreathed in mist, moss-draped forests, trailer parks and truck stops, as well as performances &mdash; in situ &mdash; by other artists like <a href="http://www.16horsepower.net/index.php" title="16 Horsepower">16 Horsepower</a> and <a href="http://www.handsomefamily.com/" title="The Handsome Family">The Handsome Family</a>.</p><p>You really got the atmosphere of the place, and came away with the strong impression that The South is a place of extremes. Jim White said that you either turn to Jesus or end up in prison &mdash; there's nothing in between. In many ways it was a very sad film. There were some interviews at a prison, and one man told the story of how he was a roofer, earning $300 a week with a lot of back-breaking work. Then he slipped in to dealing in drugs and found that he could make $5,000 a week, without "bustin' his ass". He was sentenced to 120 years, while child molesters get 6 months. A writer called <a href="http://www.harrycrews.com/" title="Harry Crews' website">Harry Crews</a> also told some great stories about the superstitions that he grew up with. His mother taught him that when you kill an opossum to eat, and get rid of the guts and the eyes, you have to put the eyes face down in the hole when you bury them. That way, when the 'possum wakes up and comes to kill you in revenge ("and it will", he added menacingly), it will bury itself deeper and deeper, instead of digging to the surface.</p><p>In short, Time Machine made something that was intrinsically interesting dull and irritating, while Searching for the Wrong-Eyed Jesus made something I wouldn't have thought I would be interested in fascinating.</p><p><sup>1</sup> And more interesting than you might think; I loved seeing India breaking off from Pangea and hurtling northwards before crashing into Asia and forming the Himalayas from the crumple zone. You don't expect continents to hurtle anywhere, but they do if you have the right time frame.</p>
TypeScript
UTF-8
2,181
2.734375
3
[ "MIT" ]
permissive
import {FieldReference} from '../../../validation' import {RuleDef, ValidationBuilder} from '../../ruleBuilder' import {InitialValueProperty, SchemaValidationValue} from '../../types' import {IntrinsicDefinitions, TypeAliasDefinition, IntrinsicTypeName} from '../schemaDefinition' import {BaseSchemaDefinition, TitledListValue} from './common' /** @public */ export interface ArrayOptions<V = unknown> { list?: TitledListValue<V>[] | V[] /** * layout: 'tags' only works for string array * layout: 'grid' only works for arrays with objects */ // inferring the array.of value for ArrayDefinition cause too much code-noise and was removed. // Since we don't have the type-info needed here, we allow values layout?: 'tags' | 'grid' direction?: 'horizontal' | 'vertical' sortable?: boolean modal?: {type?: 'dialog' | 'popover'; width?: number | 'auto'} } /** @public */ export interface ArrayRule<Value> extends RuleDef<ArrayRule<Value>, Value> { min: (length: number | FieldReference) => ArrayRule<Value> max: (length: number | FieldReference) => ArrayRule<Value> length: (length: number | FieldReference) => ArrayRule<Value> unique: () => ArrayRule<Value> } /** @public */ export type ArrayOfEntry<T> = Omit<T, 'name' | 'hidden'> & {name?: string} /** @public */ export type IntrinsicArrayOfDefinition = { [K in keyof IntrinsicDefinitions]: Omit< ArrayOfEntry<IntrinsicDefinitions[K]>, 'validation' | 'initialValue' /* concession: without this "widening" these are considered unknown in array.of when not using defineArrayMember */ > & {validation?: SchemaValidationValue; initialValue?: InitialValueProperty<any, any>} } /** @public */ export type ArrayOfType< TType extends IntrinsicTypeName = IntrinsicTypeName, TAlias extends IntrinsicTypeName | undefined = undefined, > = IntrinsicArrayOfDefinition[TType] | ArrayOfEntry<TypeAliasDefinition<string, TAlias>> /** @public */ export interface ArrayDefinition extends BaseSchemaDefinition { type: 'array' of: ArrayOfType[] initialValue?: InitialValueProperty<any, unknown[]> validation?: ValidationBuilder<ArrayRule<unknown[]>, unknown[]> options?: ArrayOptions }