language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Markdown
UTF-8
452
3.5625
4
[ "MIT" ]
permissive
# 191. 位 1 的个数 ## 题目 编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中数字位数为 '1' 的个数(也被称为汉明重量)。 ## 题解 ### 转换二进制 ```js /** * @param {number} n - a positive integer * @return {number} */ var hammingWeight = function(n) { let c = 0; while (n) { if (n % 2) c++; n = Math.floor(n / 2); } return c; }; ```
C++
UTF-8
608
3.265625
3
[]
no_license
#include <iostream> #include "vector.h" #include "strlib.h" #include "console.h" using namespace std; char* copyCString(char* str); unsigned long strlen(char* str); int main() { char* str = "hello world"; cout << "Copy of " << str << " is " << copyCString(str) << endl; return 0; } char* copyCString(char* str) { unsigned long len = strlen(str) + 1; char* dst = new char[len]; for (int i = 0; i < len; i++) { *(dst + i) = *(str + i); } return dst; } unsigned long strlen(char* str) { char *cp; for (cp = str; *cp != '\0'; cp++); return cp - str; }
C#
UTF-8
787
2.578125
3
[]
no_license
<Query Kind="Expression"> <Connection> <ID>9f536fc5-abf6-4d0d-a44e-9b36870cd229</ID> <Persist>true</Persist> <Server>.</Server> <Database>eRestaurant</Database> </Connection> </Query> //Order Clause from X in Items orderby X.Description select X // also available ascending and descending from food in Items orderby food.CurrentPrice descending, food.Calories ascending select food // you can use where and orderby together // orderby and where can change its order. from food in Items orderby food.CurrentPrice descending, food.Calories ascending where food .MenuCategory.Description.Equals("Entree") select food from food in Items where food .MenuCategory.Description.Equals("Entree") orderby food.CurrentPrice descending, food.Calories ascending select food
JavaScript
UTF-8
1,861
2.796875
3
[]
no_license
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function createDefaultGhost(target) { return new Proxy(target, { get: function (obj, prop) { return function () { let args = arguments; return function (defaultData) { let fn = obj[prop]; if (fn) { return fn.apply(obj, args); } else { return defaultData; } }; }; } }); } exports.createDefaultGhost = createDefaultGhost; function createDynamicGhost(targetCb) { return new Proxy({}, { get: function (obj, prop) { return function () { let args = arguments; return function (defaultData) { let target = targetCb() || obj; let fn = target[prop]; if (fn) { return fn.apply(target, args); } else { return defaultData; } }; }; } }); } exports.createDynamicGhost = createDynamicGhost; /** * Get the value at path of object. * If the resolved values is undefined, the defaultValue is returnted in its place. * * @param {any} value The object to query. * @param {string} path The path of the property to get. * @param {T} defaultValue The value returned for undefined resolved values. */ function get(value, path, defaultValue) { return path .replace(/\[(\w+)\]/g, '.$1') .split('.') .reduce((p, k) => { if (p && typeof p[k] !== 'undefined') { return p[k]; } return defaultValue; }, value); } exports.get = get;
C++
UTF-8
1,036
2.71875
3
[]
no_license
// https://www.urionlinejudge.com.br/judge/en/problems/view/1911 #include <bits/stdc++.h> using namespace std; bool false_signature(string const &original, string const &checked) { size_t i, diffs = 0; for (i = 0; diffs <= 1 && i < original.size(); ++i) { if (original[i] != checked[i]) ++diffs; } return diffs > 1; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); while (true) { int N, M, i, count; string name, sign; map<string, string> signatures; map<string, string>::iterator it; cin >> N; if (!N) break; for (i = 0; i < N; ++i) { cin >> name >> sign; signatures[name] = sign; } cin >> M; for (count = 0, i = 0; i < M; ++i) { cin >> name >> sign; it = signatures.find(name); if (false_signature(it->second, sign)) ++count; } cout << count << "\n"; } return 0; }
PHP
UTF-8
462
2.6875
3
[ "MIT" ]
permissive
<?php declare(strict_types = 1); namespace Korobovn\CloudPayments\Message\Traits\ModelField; trait PeriodInt { /** @var int */ protected $period; /** * @return int */ public function getPeriod(): int { return $this->period; } /** * @param int $period * * @return $this */ public function setPeriod(int $period): self { $this->period = $period; return $this; } }
Markdown
UTF-8
1,472
2.984375
3
[]
no_license
## Live Version https://ktran031.github.io/udacity-fend-restaurant-review-app/ # Project Overview: Stage 1 For this Restaurant Reviews app, I converted a static webpage to a mobile-ready web application. In Stage One, I took a static design that lacks accessibility and converted the design to be responsive on different sized displays and accessible for screen reader use. I also added a service worker to begin the process of creating a seamless offline experience for users. ## Leaflet.js and Mapbox: This repository uses [leafletjs](https://leafletjs.com/) with [Mapbox](https://www.mapbox.com/). You need to replace `<your MAPBOX API KEY HERE>` with a token from [Mapbox](https://www.mapbox.com/). Mapbox is free to use, and does not require any payment information. ### Note about ES6 Most of the code in this project has been written to the ES6 JavaScript specification for compatibility with modern web browsers and future proofing JavaScript code. As much as possible, try to maintain use of ES6 in any additional JavaScript you write. ## How to install this project Perform a git clone: $git clone https://github.com/ktran031/udacity-fend-restaurant-review-app.github.io.git Get into the cloned folder and start the server for the app: $python -m SimpleHTTPServer Start the Restaurant Review App: Open a web browser and enter "http://localhost:8000" *** If you get errors while installing on a MAC OS device, simply add "sudo" in front of each command.
Python
UTF-8
1,092
2.90625
3
[]
no_license
import torch import torch.nn.functional as F import torch.nn as nn class QNetwork(nn.Module): def __init__(self, state_size, action_size, seed, fc1_units=64, fc2_units=32): super(QNetwork, self).__init__() self.seed = torch.manual_seed(seed) ''' self.fc1 = nn.Linear(state_size, fc1_units) self.fc2 = nn.Linear(fc1_units, fc2_units) self.fc3 = nn.Linear(fc2_units, action_size) ''' #Dualing DQN self.advantage1 = nn.Linear(state_size, 16) self.advantage2 = nn.Linear(16, action_size) self.value1 = nn.Linear(state_size, 16) self.value2 = nn.Linear(16, 1) def forward(self, x): '''' x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) return F.relu(self.fc3(x)) ''' x= x.float() x_adv = F.relu(self.advantage1(x)) x_adv = F.relu(self.advantage2(x_adv)) x_val = self.value1(x) x_val = self.value2(x_val) mean_adv = x_adv.mean(1).unsqueeze(1).expand_as(x_adv) return x_val+x_adv-mean_adv
C#
UTF-8
721
2.859375
3
[]
no_license
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace RecipeSystem { public class XmlSaveLoad { public static void SaveFile( object obj, string fullPath) { using (StreamWriter writer = new StreamWriter(fullPath)) { XmlSerializer serializer = new XmlSerializer(obj.GetType()); serializer.Serialize(writer, obj); } } public static void LoadFile(ref object obj, string fullPath) { using (StreamReader reader = new StreamReader(fullPath)) { XmlSerializer serializer = new XmlSerializer(obj.GetType()); obj = serializer.Deserialize(reader); } } } }
Java
UTF-8
2,418
2.59375
3
[]
no_license
/** * @Title: HttpClientUtil.java * @Package com.sunyuki.ec.group.base.util * @Description: TODO(用一句话描述该文件做什么) * @author liuchun * @date 2015年12月25日 下午5:03:21 * @version V1.0 */ package com.ec.facilitator.base.util; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.lang.StringUtils; /** * @author liuchun * @date 2015年12月25日 下午5:03:21 */ public class HttpClientUtil { private static final String DEFAULT_CHARSET = "utf-8"; private static final String URL_SUFFIX = "api/sykapi/print"; public static final String IS_FAIL = "IsFaile"; public static final String MESSAGE = "Message"; public static Map<String, Object> requestByGet(String url, Map<String, Object> params) { Map<String, Object> map = new HashMap<String, Object>(); HttpClient httpClient = new HttpClient(); Iterator<String> it = params.keySet().iterator(); String param = ""; while (it.hasNext()) { String paramName = it.next(); Object value = params.get(paramName); param += paramName + "=" + value + "&"; } param = param.substring(0, param.length() - 1); GetMethod getMethod = new GetMethod(url + URL_SUFFIX); getMethod.setQueryString(param); getMethod.getParams().setCredentialCharset(DEFAULT_CHARSET); try { int status = httpClient.executeMethod(getMethod); if (status == HttpStatus.SC_OK) { String result = getMethod.getResponseBodyAsString(); map = parseResult(result); } } catch (Exception e) { e.printStackTrace(); } finally { getMethod.releaseConnection(); } return map; } private static Map<String, Object> parseResult(String response) { Map<String, Object> map = new HashMap<String, Object>(); String formatResult = response.replaceFirst("\\{", "").replaceFirst("\\}", "").replaceAll("\"", ""); String[] results = formatResult.split(","); for (String str : results) { if (str.contains(IS_FAIL) || str.contains(MESSAGE)) { String[] temp = str.split(":"); if (StringUtils.isNotBlank(temp[1]) && !"null".equals(temp[1])) { map.put(temp[0], temp[1]); } } } return map; } }
Python
UTF-8
11,980
3.484375
3
[]
no_license
#!/usr/bin/env python """ Author ====== Nicolas Poilvert Date ==== October 2010 This function reads a Wannier90 output file that stores a lead matrix (files ending in "_htB.dat", "_htL.dat" and "_htR.dat") and computes the band structure of the lead. For this, sub-blocks of the H00 and H01 matrices are extracted and used to diagonalize a k-dependent matrix whose eigenvalues are exactly the band energies at this k point. This way of computing the band structure is similar to the "cut" mode implemented in Wannier90 but here no other knowledge than the lead matrix is required. :Inputs: a string corresponding to the full path to the file containing the lead matrix an integer giving the number of unit cells per principal layer an integer giving the total number of points in the k space grid for sampling the band energies :Outputs: a file containing the band energies in XY for- mat if matplotlib is present on the user's comput- er, the plot is directly shown on screen. """ import os import sys import time try: import numpy as np except: print "" print " Error in compute_band_structure.py :" print " Needed package 'Numpy' could not be found." print " Exiting the program..." print "" sys.exit(1) import optparse #---------------------------------------------------# # Main program which parses the user's command line # #---------------------------------------------------# def main(): # # command-line options parser = optparse.OptionParser() parser.add_option('-m', '--matrix', dest="lead_matrix", help="full path to the file containing the lead matrix") parser.add_option('-c', '--cells', dest="cell_number", type="int", help="number of lead unit cell(s) in one principal layer") parser.add_option('-n', '--pointnumber', dest="point_number", type="int", default=314, help="number of points in the interval [-pi/a,pi/a] for band structure") options, remainder = parser.parse_args() # # if the program is called without options it prints the help menu if len(sys.argv[1:])==0: parser.print_help() sys.exit(0) # # loading the H00 and H01 matrices from the given file (H00,H01) = read_lead(options.lead_matrix) # # calling the routine that computes the band structure t_start = time.time() (grid,eigs) = compute_band_structure(H00,H01,options.cell_number,options.point_number) t_stop = time.time() # # dumping the eigenvalues in an XY formatted file print_to_file(grid,eigs) # # plotting the band structure if matplotlib is installed try: import matplotlib.pyplot as plt plot_bands(grid,eigs) except: print "" print " Warning in compute_band_structure.py :" print " Module 'matplotlib' could not be found on this" print " computer. Dropping the bands plot." print "" # # timing information print "" elapsed_time = t_stop - t_start if elapsed_time < 1.0: print " Time to compute band structure : %6.2f ms" %(elapsed_time*1000) else: print " Time to compute band structure : %6.2f s " %(elapsed_time) print "" return #------------------------------------------------------# # Here is the routine that computes the band structure # # from the knowledge of H00 and H01 # #------------------------------------------------------# def compute_band_structure(H00,H01,cell_num,pt_num): """ This routine computes the band structure from the knowledge of H00, H01 and the number of lead unit cells inside ONE principal layer :Inputs: a 2D numpy array representing H00 a 2D numpy array representing H01 an integer giving the number of cells per PL an integer giving the number of points in the k-space grid :Outputs: a 1D numpy array corresponding to the k space grid a 2D numpy array corresponding to the band energies for each grid value (the rows of that array represent the bands) """ # # making sure that the number of unit cells is compatible # with the size of H00 and H01 if H00.shape!=H01.shape: print "" print " Error in compute_band_structure :" print " H00 and H01 have different shapes" print " H00 is a (%i,%i) matrix" %(H00.shape[0],H00.shape[1]) print " H01 is a (%i,%i) matrix" %(H01.shape[0],H01.shape[1]) print " Those matrices should have similar dimensions" print " Exiting the program..." print "" sys.exit(1) wf_num = H00.shape[0]/cell_num if wf_num*cell_num!=H00.shape[0]: print "" print " Error in compute_band_structure :" print " The dimension of H00 is not divisible by" print " the number of cells provided." print " Exiting the program..." print "" sys.exit(1) # # setting up the grid in k space (we only go from # 0 to pi/a because of time reversal symmetry) from math import pi, cos, sin grid = np.linspace(0.0,pi,pt_num,endpoint=True) # # extracting the fundamental blocks corresponding to the # "on-site" , "nearest neighbours", etc... (between unit # cells), see matrices H_0i below block = [] for i in xrange(cell_num): block.append( H00[:wf_num,i*wf_num:(i+1)*wf_num].astype(complex) ) block.append( H01[:wf_num,:wf_num].astype(complex) ) # # computing the band structure from the following formula : # # H_k = H_00 + (H_01 * exp(i.k.R_1) + H_01^+ * exp(-i.k.R_1)) # + (H_02 * exp(i.k.R_2) + H_02^+ * exp(-i.k.R_2)) # + (H_03 * exp(i.k.R_3) + H_03^+ * exp(-i.k.R_3)) # + ... # where : # - H_0i is the i-th (wf_num*wf_num) block of matrix # elements between cell 0 and cell i (to the right) # - H_0i^+ means taking the hermitian conjugate of # matrix H_0i # - R_i is nothing else than i*ka where k is the k # vector and a the length of a UNIT CELL of lead # (not the PL length) eigs = np.zeros((block[0].shape[0],grid.shape[0]),dtype="float") for k in xrange(grid.shape[0]): k_hamiltonian = np.zeros((block[0].shape[0],block[0].shape[1]),dtype="complex") k_hamiltonian += block[0] for j in xrange(1,len(block)): k_hamiltonian += block[j]*complex(cos(j*grid[k]),sin(j*grid[k])) + \ np.conjugate(block[j].transpose())*complex(cos(j*grid[k]),-sin(j*grid[k])) k_eigenvalues = np.zeros(k_hamiltonian.shape[0],dtype="float") k_eigenvalues = np.real( np.linalg.eigvalsh( k_hamiltonian ) ) eigs[:,k] = k_eigenvalues return (grid,eigs) #-------------------------------------------# # Utility routines used in the main program # #-------------------------------------------# def read_lead(path): """ This function extracts the H00 and H01 matrices from a `*_htL.dat`, `*_htR.dat` or `*_htB.dat` Wannier90 formatted file. The H00 and H01 matrices correspond respectively to the **on-site** and **off-diagonal** matrix sub-blocks of a lead principal layer. :Input(s): a string corresponding to the name (full path) of the file containing the principal layer matrices :Output(s): a tuple with two rank-2 numpy arrays in the following order (H00,H01) """ # # tests whether the path is actually existing and # if there is a file to read if not os.path.exists(path): print "" print " Error in read_lead :" print " It seems that '%s' does not exist" %(path) print " Exiting the program..." print "" sys.exit(1) elif not os.path.isfile(path): print "" print " Error in read_lead :" print " It seems that '%s' is not a file" %(path) print " Exiting the program..." print "" sys.exit(1) temp_file = open(path,'r') lines = temp_file.readlines() temp_file.close() starting_line_for_H00 = 1 starting_line_for_H01 = int( (len(lines)+1)/2 ) # # extracting the size of H00 try: H00_size = int(lines[starting_line_for_H00].split()[0]) except: print "" print " Error in read_lead :" print " could not extract the size of H00 on line 1" print " in file %s" %(path) print " Exiting the program..." print "" sys.exit(1) # # extracting the size of H01 try: H01_size = int(lines[starting_line_for_H01].split()[0]) except: print "" print " Error in read_lead :" print " could not extract the size of H01 on line %i" %(starting_line_for_H01) print " in file %s" %(path) print " Exiting the program..." print "" sys.exit(1) H00 = np.zeros((H00_size,H00_size),dtype='float') H01 = np.zeros((H01_size,H01_size),dtype='float') # # extracting the H00 matrix iterator = 0 line_number = starting_line_for_H00+1 try: for i in xrange(starting_line_for_H00+1,starting_line_for_H01): line = lines[i].split() for item in line: col = iterator/H00_size row = iterator%H00_size H00[row,col] = float(item) iterator += 1 line_number += 1 except: print "" print " Error in read_lead :" print " could not extract matrix H00 on line %i" %(line_number) print " in file %s" %(path) print " Exiting the program..." print "" sys.exit(1) # # extracting the H01 matrix iterator = 0 line_number = starting_line_for_H01+1 try: for i in xrange(starting_line_for_H01+1,len(lines)): line = lines[i].split() for item in line: col = iterator/H01_size row = iterator%H01_size H01[row,col] = float(item) iterator += 1 line_number += 1 except: print "" print " Error in read_lead :" print " could not extract matrix H01 on line %i" %(line_number) print " in file %s" %(path) print " Exiting the program..." print "" sys.exit(1) return (H00,H01) def print_to_file(grid,eigs): """ This function takes a grid of k points between -pi/a and pi/a and the band energies on that grid and dumps those in a file in XY format :Inputs: a 1D numpy array of floats (the grid) a 2D numpy array whose rows contain the band energies given at the grid points :Output: a file containing the grid as X axis and the band energies as Y values. The file is in XY format """ # # checking for dimension match between grid and eigs if grid.shape[0]!=eigs.shape[1]: print "" print " Error in compute_band_structure.py :" print " There was a mismatch between the size of the grid" print " of points in k space and the size of the band energy" print " arrays." print " Cannot print band energies to file" print "" sys.exit(1) # # if no dimension problems, the band energies are printed to file outfile = open('./band_energies.dat','w') for i in xrange(grid.shape[0]): outfile.write(' %10.7f ' %(grid[i])) for j in xrange(eigs.shape[0]): outfile.write('%10.7f ' %(eigs[j,i])) outfile.write('\n') outfile.close() return def plot_bands(grid,eigs): """ This function uses matplotlib to plot the band energies on screen :Inputs: a 1D numpy array corresponding to the 'x' values 'grid' a 2D numpy array corresponding to the bands 'eigs' :Output: a matplotlib graph on screen """ import matplotlib.pyplot as plt # # building the plot plt.figure() plt.xticks(np.array([grid.min(),grid.max()]), ('0', r'$\frac{\pi}{a}$'), fontsize=20) plt.ylabel(r'Band Energies (eV)', fontsize=18) for i in xrange(eigs.shape[0]): plt.plot(grid,eigs[i,:],color=(float(i)/eigs.shape[0],0.5,0.5),label='band %i' %(i)) plt.legend() plt.show() return if __name__=="__main__": main()
Markdown
UTF-8
52,915
3.109375
3
[]
no_license
Self-refinement =============== At this stage the following three acts should be performed: A. Refinement of self from all sort of false beliefs, evil thoughts, and superstitions. B. Refinement of self from vices and moral indecencies. C. Quitting all kind of sins and transgressions. False beliefs and superstitions are ignorance and deviations that result in self's darkness and deviation from following the straight path of perfection and God's Nearness. Because, the believers in false beliefs never recognize the straight path of human perfection and wander aimlessly and confused in the darkest valleys of deviations and vices never reaching to their undefined final destination. How come the heart which is full of intense darkness can witness the ever shining sacred Divine illumination? Also, moral indecencies strengthen the animalistic habits gradually silencing the light within the celestial human soul. Such a deviated person will never succeed in accomplishing the most exalted human objective of reaching the nearness of the supreme source of beauty and absolute perfection, i.e. God-Almighty. Similarly, sinning and transgressions makes the human self dark and contaminated, thus, causing him further to deviate from the exalted path of human perfection and God's Nearness. Naturally, such a person will never reach to its ultimate cherished goal. Therefore, self-refinement determines our final destination and should be considered as an extremely important matter. We must, therefore, first identify the moral indecencies and sins and then must take remedial actions for cleansing and purifying our self from these impurities. Fortunately, in the first part we do not have any problem because the physicians of the self or God’s assigned human specialists -Prophet's and Infallible Imams have thoroughly defined moral indecencies, and even have given the prescription for their treatment; have counted various kinds of sins and taught us how to relinquish them. We all recognize moral indecencies and understand their ugliness. We know that hypocrisy, arrogance, jealously, revenge, anger, slander, treason, egotism, malevolence, backbiting accusation, ill-speaking, wrath, oppression, fear, stinginess, greed, fault-finding, lying, love of the world, ambitiousness, deceit, cheating, suspicion, cruelty, snobbery, self-weakness, and other such habits are bad and undesirable. Apart from the fact that by features we understand and realize their ugliness, hundreds of Qur’anic verses and traditions also confirms their ugliness and indecencies. Our traditions in this field are extremely vast, rich and comprehensive that there does not exist the least shortage. Also, all forbidden acts and sins and their relevant punishments have been explained explicitly and comprehensively in the Holy Qur’an and traditions, and we do know about all of them. Therefore, as for as the identification of minor and major sins are concerned, we do not have any problem at all. But at the same time it must be frankly admitted that we all are captive of Satan and imperious self (*nafse- ammarah*), and unfortunately do not find the grace for purification of self from sins and moral indecencies. This is our real problem for which a solution must be found. In my opinion these are two important factors relevant to the above problem: First: We don't understand our moral diseases and do not have the courage to admit this sickness within ourselves. Secondly: We regards them a minor thing and are negligent about the severe painful and catastrophic consequences arising thereof, and because of this reason are not concerned for their treatment. These are the two factors responsible for our negligence towards self-refinement. Therefore, these should be discussed in detail and the method of treatment should be discovered. 1. Negligence from the Disease ------------------------------ We probably understand the moral sicknesses and do appreciate heir ugliness but only in others, and not within ourselves. If we encounter impoliteness and moral indecencies in others we are quick to observe them immediately. While it is quite possible that the same moral indecency or may be worst than that might exist within ourselves, but we do not pay the east attention and ignore it completely. For example, we may regard transgression of others rights as something bad and might hate the transgressor, but at the same time it is possible that we ourselves might be transgressor, and may not realize it at all. We do not consider our own act as a transgression, and on the contrary it is quite possible, that we might present it something as a glorious or virtuous act before ourselves, thus, by this means making it justified. Similar might be the case with other moral shameful deeds, and in this manner we never think about our own improvement. Because, if a sick person does not consider himself sick naturally he will never worry about his treatment. Since, we do not consider ourselves as sick, we are not concerned about our treatments either, and this happens to be our biggest problem. Therefore, if we care about our happiness and prosperity we must think for the remedy of this problem and by all possible means must endeavor to identity for internal psychological diseases. 2. Diagnosis of Self-sickness ----------------------------- Here it would be appropriate to describe the ways and means which could be useful for identifying the self-sickness. ### 2.1. Strengthening of Reason The most exalted, celestial distinction of human beings, and the most perfect parameter of his existence distinguishing him over all other creatures, which in the terminology of the Holy Qur’an and traditions has been called by different names such as: spirit, self, heart, and intelligence, all are manifestations of one single reality, but because of different considerations have been given different names. But the fountainhead and origin of all thinking, rationalization, and intelligence have been named as reason. [^1] In the books of tradition the reason (*aql*) has been treated with special distinction, and special chapters have been assigned for its detailed explanation. Reason in traditions have been titled as the most noble existence which is the source of all obligations, rewards, and punishments. For example: Imam al-Baqir (a.s.) has said: <blockquote dir="rtl"> <p> عن ابي جعفر عليه السلام قال: لما خلق الله العقل استنطقه. ثم قال له: اقبل, فاقبل. ثم قال له: ادبر. فادبر ثم قال: قعزتى وجلالى! ما خلقت خلقا احب الى منك ولا اكملتك الا فيمن احب. اما انى اياك آمر واياك انهى واياك اثيب. </p> </blockquote> *“When God Almighty created the reason, it was blessed with the power of speech. Then it was ordered by Him to come and it obeyed; then it was commanded by him to return and again it obeyed. Than God-Almighty said:* *“By the oath of My Honor and Glory ! I have not created any existence which is superior and dearer than you. You will not be perfected in anyone except the one who is dearer to me. Be aware!* *That obedience and transgression of My Commands depends upon you, and you will receive the rewards and punishment accordingly.”*[^2] Also the Holy Qur’an said: <blockquote dir="rtl"> <p> لَكُمْ آيَاتِهِ لَعَلَّكُمْ تَعْقِلُونَ كَذَٰلِكَ يُبَيِّنُ اللَّهُ </p> </blockquote> ***“Thus, God expoundeth unto you His revelations so that ye may understand. (2:242)*** <blockquote dir="rtl"> <p> أَفَلَمْ يَسِيرُوا فِي الْأَرْضِ فَتَكُونَ لَهُمْ قُلُوبٌ يَعْقِلُونَ بِهَا </p> </blockquote> ***“Have they not traveled in the land, and have they hearts wherewith to feel and ears wherewith to hear.”the Holy- Qur’an (22:46)*** And said: <blockquote dir="rtl"> <p> يَعْقِلُونَ إِنَّ شَرَّ الدَّوَابِّ عِندَ اللَّهِ الصُّمُّ الْبُكْمُ الَّذِينَ لَا </p> </blockquote> ***“Lo! The worst of beasts in God's Sight are the deaf, the dumb, who have no sense. (8: 22)*** Those who possess ears, tongue, and reason, but do not utilize them in discovering the realities are introduced by God-Almighty in the Holy Qur’an in the category of beasts and even worst than them, be cause they have not used their minds. God-Almighty said: <blockquote dir="rtl"> <p> وَيَجْعَلُ الرِّجْسَ عَلَى الَّذِينَ لَا يَعْقِلُونَ </p> </blockquote> ***“…He hath set uncleanness upon those who have no sense. (10:100)*** Whatever goodness is possessed by a human being it is due to his reason; he recognizes God-Almighty by means of reason and worships him; accepts the Day of Resurrection and makes him readied for it; accepts the prophets and obeys them; understand the good moral conduct and trains him accordingly; identity the vices and evil and therefore, avoids them. It is because of this reason that the reason has been praised in the Holy Qur’an and traditions e.g. Imam al-Sadiq (a.s.) replying to a beggar said: <blockquote dir="rtl"> <p> بعض اصحابنا رفعه الى ابي عبدالله عليه السلام قال: قلت له ما العقل؟ قال: ما عبد به الرحمان واكتسب به الجنان. </p> </blockquote> *“It is because of the existence of reason that God-Almighty gets worshipped, and one makes his entry into Paradise.”*[^3] He also said: <blockquote dir="rtl"> <p> قال ابو عبدالله عليه السلام: من كان عاقلا كان له دين ومن كان له دين دخل الجنة. </p> </blockquote> *“Whoever is wise and intelligent possesses religion, and whoever has religion will enter into the Paradise.”*[^4] Imam al-Kadhim (a.s.) said to Hasham: <blockquote dir="rtl"> <p> قال ابوالحسن موسى بن جعفر عليه السلام (في حديث): يا هشام! ان الله على الناس حجتين: حجة ظاهرة وحجة باطنة فاما الظاهرة فالرسل والانبيا والايمه. واما الباطنة بالعقول. </p> </blockquote> *“God-Almighty has blessed the human beings with two proofs:* *One is apparent and the other one is hidden. The apparent proofs are Prophets and Imams, and the hidden proof is the reason and intelligence within our existence.”*[^5] Imam al-Sadiq (a.s.) said: <blockquote dir="rtl"> <p> قال ابوعبدالله عليه السلام: اكمل الناس عقلا احسنهم خلقا </p> </blockquote> *“The most perfect human beings from the point of view of reason are those who are the best in moral conduct.”*[^6] <blockquote dir="rtl"> <p> قال ابوعبدالله عليه السلام: العقل دليل المؤمن </p> </blockquote> *“The reason is the guide of a believer.”*[^7] Imam al-Ridha’ [^8] (a.s.) said: <blockquote dir="rtl"> <p> قال الرضا عليه السلام: صديق كل امر عقلة وعدوه جهله. </p> </blockquote> *“The reason is the friend of everyone and the ignorance is his enemy.”*[^9] The Commander of the Faithful Imam ‘Ali (a.s.) has said: <blockquote dir="rtl"> <p> قال امير المؤمنين (ع): اعجاب المر بنفسه دليل على ضعف عقله </p> </blockquote> *“Egotism of a person is the indication of his wisdom's weakness.”*[^10] Imam al-Kadhim (a.s.) said to Hasham: <blockquote dir="rtl"> <p> قال موسى بن جعفرعليه السلام: يا هشام! من اراد الغنى بالامل وراحة القلب من الحسد السلامة في الدين فليتضرع الى الله في مسالته بان يكمل عقلة. فمن عقل قنع بما يكفيه ومن قنع بما يكفيه استغنى ومن لم يقنع بما يكقيه لم يدرك الغنى ابدا.م. </p> </blockquote> *“Whoever desires to become contented without possessing health, a tranquil heart free from jealousy and soundness in religion must cry before God-Almighty and should ask for perfection of his reason. Therefore, whoever becomes wise will be contented with modest means of livelihood, and thus, will become free from wants, and whoever is not contented with modest means of livelihood will never become free from wants.”*[^11] Imam al Kadhim (a.s.) [^12]said: <blockquote dir="rtl"> <p> قال موسى بن جعفر عليه السلام: يا هشام! ان العقلا تركوا فضول الدنيا, فكيف الذنوب, وترك الدنيا من الفضل وترك الذنوب من الفرض. </p> </blockquote> *“A wise person avoids even extra worldly-affairs what to say about sins, while quitting extra worldly-affairs is optional and avoiding of sins is mandatory.”*[^13] And said: <blockquote dir="rtl"> <p> قال موسى بن جعفر (ع): يا هشام! ان العقال لا يكذب وان كان فيه هواه. </p> </blockquote> *“A wise person will never tell a lie, even if his self is tempted to do so.”*[^14] And said: <blockquote dir="rtl"> <p> قال موسى بن جعفر عليه السلام: يا هشام! لا دين لمن لامروة له ولامروة لمن لا عقل له وان اعطهم الناس قدر الذى لا يرى الدنيا لنفسه خطرا. اما ان ابدانكم ليس لها ثمن الا الجنة فلا تبيعوها بغيرها. </p> </blockquote> *“Whoever lacks compassion does not have religion; whoever lacks wisdom does not have compassion; the most valuable person is the one who does not consider the entire world worthy of his self Know that: your bodies could not be traded with anything except Paradise. Therefore, be careful never to trade yourselves for a price other than Paradise.”*[^15] From the above tradition the preciousness of the reason, its important role in acquiring higher learning and sciences, accepting faith , worshipping God, recognizing and utilizing good morals, and quitting sins and other vices, could be understood well. Here, it should be emphasized that simply the existence of reason is not sufficient as for as the accomplishment of the above objectives are concerned, rather it is the commissioning and efficient utilization of the faculty of reason within human body which produce the cherished results. Within human body the presence of reason could be compared to like a righteous judge or expert, but he could only issue the correct judgment if, the required safe and peaceful environment has been provided in which the verdict issued by him will be accepted. Or in other words we may compare reason with an intelligent, competent, sincere and resourceful governor of a region, but he could succeed only if his governance is officially certified and backed up by the ruling administration. The reason could be like a wise, trusted, and sincere adviser but only if it is being allowed to advice and if the attention is paid to its words. If the reason becomes the ruling authority within a human body and could control the whims and passions of the self- it will govern it in an excellent manner; will achieve an equilibrium between the supply and demands; will arrange everything in a proper order, so that they may achieve perfection by ascending towards God-Almighty. But are the whims and passions of the self going to surrender themselves so easily and accept the governance of reason? No! They won't, on the contrary they will engaged themselves into sabotage and other destructive work against it till the reason is forced out of the field of confrontation. There is no choice except that the reason should be strengthened, because, the stronger it is the better it recognizes the internal enemies and will be able to subdue and control them easily. Therefore, it is our utmost duty to endeavor and struggle for strengthening the faculty of reason. ### 2.2. Thinking before Action In order to strengthen the reason we must seriously decide that before undertaking each action its over all worldly and eternal results and ultimate consequences must be thoroughly reviewed. This should be practiced till gradually it becomes a habit. It is because of this consideration that Islam encourages us to think about the ultimate consequences of our actions. e.g.: Commander of the Faithful Imam ‘Ali (a.s.) said: <blockquote dir="rtl"> <p> كان امير المؤمنين عليه السلام يقول: نبه بالتفكر قلبك. </p> </blockquote> *“By means of pondering deeply, make your heart aware and knowledgeable.”*[^16] Also said: <blockquote dir="rtl"> <p> قال امير المؤمنين عليه السلام: ان التفكر يدعو الى البر والعمل به. </p> </blockquote> *“Pondering invites a person towards good works and actions.”*[^17] And said: <blockquote dir="rtl"> <p> قال امير المؤمنين عليه السلام: التدبير قبل العمل يؤمنك من الندم. </p> </blockquote> *“Thinking about the ultimate consequences before action makes you safe against feeling sorry later on.”*[^18] A man approached the Holy Prophet (S) and asked him: <blockquote dir="rtl"> <p> ان رجلا اتى رسول الله صلى الله عليه وآله فقال: يا رسول الله اوصنى. فقال له: فهل انت مستوص ان اوصيتك؟ حتى قال ذالك ثالثا في كلها يقول الرجل: نعم يا رسول الله, فقال له رسول الله: فانى اوصيك اذا هممت بامر, فتدبر عاقبته, فان يك رشدا فامضه وان يك غيا فانته عنه. </p> </blockquote> *“Oh Messenger of God! Please advise me.* *The Holy Prophet (S) replied:* *“Will you follow my recommendation?” 'Yes! I will', Replied the man. This question and answer was repeated three times. Then the Holy Prophet (S) said: “My recommendation is that whenever you wanted to decide to undertake an action, then firstly you must ponder well about its ultimate* *consequences. In case you found it good then go ahead and do it, but in case you realized that it is not good, then don't do it.”*[^19] Also, he said: <blockquote dir="rtl"> <p> قال رسول الله صلى الله عليه وآله: انما اهلك الناس العجلة ولو ان الناس تشبتوا لم يهلك احد. </p> </blockquote> *“People were ruined because of being hasty. If they would have pondered about their actions none of them would have been ruined.”*[^20] And said: <blockquote dir="rtl"> <p> قال رسول الله صلى الله عليه وآله: الاناة من الله العجلة من الشيطان. </p> </blockquote> *“Delay and thinking about the consequences are blessings from God-Almighty while haste is from Shaitan.”*[^21] The following has been quoted from a tradition by the Infallible Imams (a.s.). <blockquote dir="rtl"> <p> واروى: التكفر مرآتك ترايك سيأتك وحسناتك </p> </blockquote> *“Pondering is like a mirror which shows your goodness and evilness.”*[^22] The animals in their actions follow the passions of their instincts and do not have the power of thinking and reasoning, but since a human being possesses reason, he must ponder and review the ultimate consequences before undertaking any action. Nevertheless, a man also possesses the same desires and animalistic passions, therefore, immediately reacts, gets stimulated, and absorbed as soon as he is faced with a desirable animal object of opposite sex from his own species. In this situation animal passions do not allow him to resort to thinking, because, once reason enters the scene it will prevent the action taken in accordance with animalistic passions. Therefore, if we become habitual of practicing thinking and rationalizing before undertaking each action, then in that case, we will be opening a gateway for the reason so that it could be present at the scene. Once it enters at the scene, it immediately diagnoses our interest and benefits by subduing the animalistic passions, and will guide us towards the straight path of human perfection if it is strengthened and becomes ruler of the country (i.e. human body). It could diagnose the internal enemies and psychic diseases within his inner self, and accordingly may take the preventive measures and necessary treatments for their cure. It is because of these considerations that thinking pondering, and reasoning have been assigned special emphasis in Qur’anic verses and traditions. ### 2.3. Being Pessimistic towards the Self If a human being takes a correct and in-depth review of his inner-self and investigate his psychic characteristics, most probably he would be able to discover his psychic diseases, because, after all, one is more knowledgeable about his ownself as compared to others. God-Almighty has said: <blockquote dir="rtl"> <p> بَلِ الْإِنسَانُ عَلَىٰ نَفْسِهِ بَصِيرَةٌ وَلَوْ أَلْقَىٰ مَعَاذِيرَهُ </p> </blockquote> ***“Oh! But man is telling witness against himself, although he tenders his excuses. (75:14-15)*** But our problem is that while judging we cannot remain impartial, because, we are optimistic about our souls; consider ourselves, our characteristics, our actions, and our opinions as faultless. The imperious-self (*nafse-ammarah*) makes the animalistic passions so charming, attractive, and appealing before our eyes that the evil deeds committed by us appears as virtuous acts. The Holy Qur’an said: <blockquote dir="rtl"> <p> أَفَمَن زُيِّنَ لَهُ سُوءُ عَمَلِهِ فَرَآهُ حَسَنًا ۖ فَإِنَّ اللَّهَ يُضِلُّ مَن يَشَاءُ وَيَهْدِي مَن يَشَاءُ </p> </blockquote> ***“Is he, the evil of whose deeds is made fair-seeming unto him so that he deemeth it good, (other than Satan's dupe)” God verily sendeth whom He will astray and guideth whom He will. (35:8)*** It is because of this reason that we do not realize our defects and faults so that we could take remedial measures. Therefore, the solution of the problem consists that we must continuously be pessimistic and suspicious about the self; should presume or even must be assured that we possess vices, plenty of diseases, and with this reality should investigate the self. The Commander of the Faithful Imam ‘Ali (a.s.) has said: <blockquote dir="rtl"> <p> قال على عليه السلام: ان المؤمن لايصبح ولايمسى الا ونفسه ظنون عنده فلا يزال زاريا عليها ومستزيدا لها. </p> </blockquote> *“A believer is continuously pessimistic about his self, always criticizes, and demands better deeds from him.”*[^23] In praising the characteristics of the pious, he said: <blockquote dir="rtl"> <p> قال على (ع): فهم لانفسهم متهمون ومن اعمالهم مشفقون واذاذكى احد منهم خال مما يقال له فيقول: انا اعلم بنفسى من غيرى وربـى اعلم منى بنفسى. </p> </blockquote> *“Their souls before them are always blamed' and criticized and they are always afraid of their deeds. While one of them is being praised, he is afraid of such praise and says: 'I am more aware about my own self; and God-Almighty is more knowledgeable as compared to me.”*[^24] One of the biggest obstacle which never permits us to discover our psychic diseases and to seek treatment is our being optimistic and having a favorable opinion about our souls. Therefore, if this obstacle could be removed and the self is reviewed honestly, it would be possible to diagnose the disease and seek its treatment accordingly. ### 2.4. Consulting Spiritual Physicians In order to diagnose our hidden internal faults and defects we may seek the assistance of a learned scholar of ethics who after having perfected his self has achieved a praiseworthy moral conduct. We must explain in detail the characteristics and internal behavior to him, and should request him to remind us about our psychic faults and moral indecencies. A spiritual physician who Is a psychiatrist as well as a scholar of ethics, whose belief and action coincides, and is a true manifestation of higher moral excellence is extremely useful and influential for achieving self-perfection and undertaking a spiritual journey towards God-Almighty. If, one could succeed in finding such a person one must be thankful to God-Almighty for this blessing. Unfortunately, such persons are not available easily and are in shortage. Also, this point needs to be emphasized that the correct diagnosis of the self's disease is extremely difficult. Therefore, it is patient's duty to describe in detail his deeds and internal characteristics without reservation before such a spiritual physician to enable him to diagnose his sickness correctly. If the patience did not cooperate and concealed the realities about him, then in that case, he will not obtain the desired results. ### 2.5. Consulting a Wise Friend A good friend who is wise, intelligent, and well wisher is a great blessing of God-Almighty, and could be helpful in our efforts for achieving self-refinement and identification of moral indecencies, subjected to his being competent to identify our good and bad characteristics. Also, he should be a confident and well wisher. Because, if he could not diagnose the good and bad characteristics not only he can not help us, but on the contrary he may regard our weaknesses as virtues and visa versa. In case, if he is not a trusted well wisher, it is quite possible that for the continuation of friendship and not to hurt our sentiments, might conceal our faults and defects, and even for flattering and appeasement will mislead us by branding our moral indecencies as our virtues. If, luckily we succeeded in finding such an ideal friend then we must demand him to feel free in frankly pointing out to us all our defects and faults observed by him. We must appreciate his reminders, should utilize them for improvement of the self, should make him understand that his criticism is sincerely appreciated and that not only we are not unhappy of his reminder on the contrary are grateful and pleased. On the other hand, the person who has been trusted for this task is obliged to prove his honesty and sincerity through his practical actions. He must review the characteristics of his friend honestly without any reservations, and should let him know about his observations in a friendly and well-wishing manner in strict confidence. Also, pointing out defects and faults in the presence of others should be strictly prohibited. His aim should be to present out the facts and exaggeration should be strictly avoided, because, a believer is supposed to be like a mirror for another believer reflecting the later's beauty and ugliness the way they are without making any addition or subtraction. Of course, such a friend who for the sake of reform reminds a person about his faults and defects are in shortages, but if one luckily y finds such an ideal friend, he indeed has received one of the greatest blessing. He must appreciate it, should be pleased for his comments, must thanks him, and must realize that a friend who criticizes for the sake of his improvement is one of the best and most valuable friend. God forbids! If instead, a person feels offended with his positive criticism and for the sake of self defense starts thinking about taking revenge against him. If, someone reminded you that there are some poisonous scorpions upon your dress. Will you then feel offended with such a reminder and will take revenge or will you be pleased and thanks him? Yes! The undesirable characteristics are like scorpions and even worst that this, because they sting and continuously strive their entries inside the soul. Some one who helps us to against them has indeed done the greatest services for us. Imam al-Sadiq (a.s.) said: <blockquote dir="rtl"> <p> قال الصادق عليه السلام: احب اخوانى الى عيوبى. </p> </blockquote> *“The one who points out my faults to me is my best brother.”*[^25] ### 2.6. Learning from Other's Faults Most probably a human being is unaware of his own defects but sees them in others clearly and feels their ugliness very well. According to a famous proverb: “They see a tiny piece of straw in the eyes of others and makes it big like a mountain, but can not see the mountain of their own eyes.” Therefore, one of the method for identifying our psychic defects is to detect these faults within other people. Once, a human being sees a defect of others, instead of paying attention towards it or criticizing, he should investigate his own inner-self for being contaminated with the same faults, and in case he finds it, should try for its remedial. In this manner he could learn a lesson from the faults of other people, in continuation of his efforts for achieving self-refinement. The Holy Prophet (S) said: <blockquote dir="rtl"> <p> قال رسول الله صلى الله عليه وآله: السعيد من وعظ بغيره. </p> </blockquote> *“Fortunate is the one who learns a lesson from the faults of others.”*[^26] ### 2.7. Learning from Criticism Generally friends decline to point out the defects of a human being but opposite to that his enemies are quite eager to criticize. Of course, they are not sincere in their criticism and are motivated with their feelings of jealousy, enmity, and revengefulness but any way one might utilize their criticism to his best advantage. When being criticized by his enemies a man has two options: **Firstly:** He may take a defending position by taking the excuse that since the criticism is uttered by his enemies who are not his well wishers, therefore, he will defend himself by every possible means, thus, silencing their voices. Such a person had not only corrected his defects but on the contrary he might contaminate himself by committing further mistakes. **Secondly:** He might pay good attention to his enemy's criticism, then with the aim of truth finding may refer to his own-self by reviewing him honestly. If, he found out that the enemy was right and his own-self was at fault, he should resort immediately to his own reform. In case, if it is feasible, he should even thank his enemy whose criticism be-came a means of his self-refinement- an enemy who is far better than those protecting friends who did not point out his defects, and with their flattering and appeasement kept him in the darkness of ignorance. But if after referring to his self and reviewing, if he finds out that the defect does not exist within his self, then must thanks God-Almighty and be careful in guarding his self, lest it become contaminated with this defect later on. In this manner he could be benefited from the criticism of his enemies. Of course, this method of encounter will not be an obstacle as for as his utilization of other logical and legal means for dissipating the treacherous enemy plans are concerned. ### 2.8. Symptoms of Heart's Sickness One of the best methods for diagnosing a disease is to recognize its symptoms. The bodily sickness in generally identified by means of two indications i.e. either by feeling pain or by means of weakness of a particular part of the body in dischargement of its assigned function. Every part of the body is supposed to perform a special function, which in case of being fit performs it very well. Therefore, if a part of the body is not performing its assigned function well it means that the part is sick. For example, the human eye in sound health under particular conditions sees the object, and therefore, if in spite of having suitable conditions does not see well, indicates that it is sick. Similarly, other organs of the body like ears, tongue, hands, feet, heart, liver, kidney, and others, each one of them is supposed to perform a particular function, which is performed by them in their being fit, and their failure to perform their relevant functions indicate their sickness. Similar is the case with human self or heart which in accordance to his primordial nature is assigned to perform a special function. He has arrived from the Celestial Kingdom with knowledge, blessing, power , mercy, justice, love, enlightenment, illumination, and other moral virtues. By nature he is curious to discover the reasons and realities and desires God. Belief, attention, love, attachment, and worship towards God-Almighty all are symptoms of soundness of self and heart. Likewise, attachment shown towards knowledge and wisdom, benevolence and service for the God's Creatures for the sake of God-Almighty, sacrifice, generosity, seeking justice, and other moral virtues also are indicative of soundness of the self. If, a person discovers such characteristics within him, it means that he possesses a sound heart, but on the contrary if he realized that he does not pay attention towards God; does not enjoy prayer, supplication, and worshipping; does not like God; is ambitious for power, wealth, wife, and children; prefers sexual and carnal pleasures over God's consent; does not have any other goal in life except to safeguard his own interests; does not enjoy sacrifice, generosity, kindness, and service towards others human beings, and does not feel upset while seeing other people inflicted with calamities. Such a person must know that he is certainly sick, and if he is interested in his prosperity must resort to his reform and treatment as soon as possible. 3. Decision for Treatment ------------------------- After the psychic sickness is diagnosed correctly, once we become sure that we are sick then its treatment must be started immediately, and the most important thing which matters at this stage -is to be able to take the firm decision. If, we really want and seriously decide that we must refine ourselves from the moral indecencies -it could be done. But if we treat. it something as insignificant, and do not decide, then in that case getting cured and achieving sound health would become impossible. It is at this stage that Satan and imperious-self enter into action and by means of playing dirty tricks prevent us from taking the right decision. But we must be careful and should not become victim of their treacherous deceit. It is possible that he may justify the self's ugliness by pointing out: Don't you want to live with the people? Others do possess the same characteristics, look at Mr. so and so, they all possess the some characteristics even greater than yours. Do you alone want to be good? <blockquote dir="rtl"> <p> خواهي نشوی رسوا همرنگ جماعت باش. </p> </blockquote> *“If you don't want to be insulted then better join the crowd.”* But we must take a decisive and firm stand against their treacherous deceits and must say: The argument that the others are also contaminated has nothing do with me; there being contaminated does not give mean excuse or justification; in any case this defect and sickness exist within me; if I die in this condition; will be inflicted with eternal doom, and therefore, must endeavor for treatment and attaining self-refinement. Sometimes it is possible that the Satan will enter the field with time killing and delaying tricks, thus, preventing us from taking the right decision at the right time. He might tell us: True! This defeat exists within you and must be reminded .But it is not late. Why hurry up? Take it easy and let the other important works first be completed and then with complete ease you may engage yourself in self-refinement. Right now! You are too young. This is the time for fun and enjoyment. Wait till you become old. Then you may repent. God does accept repentance any way. Then you may get yourself busy in self-perfection. We must, therefore, be intelligent enough to understand that these are Satanic tricks. Who knows that we will be alive till our old age? Perhaps, the death might arrive before old age and we might leave this world contaminated with the psychic diseases. In that case what will be our destiny? Any way even if we lived till that time but will the Satan and imperious self quit their treacherous filthy tricks and leave us free to pay attention towards the self-refinement? Even at that time by means of some other tricks they will prevent us from taking the right decision. Therefore, why not right now, we should take the action to subdue the rebellious imperious-self. Sometimes, it is possible that imperious-self would tell us: You have become addicted to sinning and quitting this addiction is impossible for you. You are a prisoner of the whims and passions of your self. How could you free yourself from this imprisonment? Your self has become totally darkened by means of sins, and therefore, you do not have any chance for return. But we must better understand that the above argument is nothing but another treacherous trick of imperious-self. In response we must tell him: quitting habit is not only impossible but on the contrary is quite possible. Of course, it is difficult but any how I must take action and must endeavor for self-refinement. If, quitting sins and bad characteristics would really have been impossible then in that case all these moral instructions, about their quitting, from the Prophet (S) and Infallible Imams (a.s.) would not have been issued. The path of repentance is never closed and is always open and therefore, we must decide and must get involved in achieving self-refinement. Also, it is possible that the imperious-self may reflect their psychic diseases and moral indecencies as insignificant and unimportant by saying: you are committed for the performance of mandatory obligations as well as also perform such and such recommended obligations. Certainly you will receive the pardon of Merciful and Beneficent God and will be sent to Paradise. The moral indecencies which you possess are not so important to be concerned, and anyhow they will be compensated with your performance of recommended obligations (*Mustahabbat*). Here, too it is important to be careful and to understand that such justifications are nothing but deludings of Satan and imperious-self. We must tell them: righteous deeds are accepted only from pious people, and achieving piety without self-refinement is impossible. If, the self is not cleansed thoroughly from evilness it could never be a place for goodness. Unless Satan is forced out the angels will never enter. If, by means of committing sins and other carnal desires the heart becomes contaminated and dark, it will remain without illumination and radiance in the Next World. Serious attention should always be paid about the dangerous consequences of the psychic diseases which have already been summarized earlier. Apart from that, by referring to literature of moral ethics and traditions, the dangerous effects and eternal punishments of each psychic disease must be studied thoroughly; through these means the treacherous Satanic plans must be resisted by taking a definite and firm decision for starting a program of self-refinement. If we succeed passing through the decision stage we will become closer to the stage of action. 4. Control and Domination of Self --------------------------------- Human-self is the origin and source of all actions, deeds, sayings, virtues, and vices. If he is reformed one's success in both worlds is assured, but if becomes contaminated, will turn into a source of vices and will bring a catastrophe for this as well as the Next World. If, he started walking on the righteous path, might even surpass the God's most favorite angels; but if showed indifference towards the precious “Jewel-of- Humanity” (*Gowhar al-Insaniyat*), and selected the animalistic way of life would become even lower then them, falling into the darkest valleys of ignorance. The ways and means for following either one of these two paths have been incorporated within human existence. He has reason and wisdom, and in accordance with his primordial nature is inclined towards higher moral human characteristics, but at the same time he is also a biological animal possessing animalistic passions, desires, and energies. But it is not so that all of these animalistic characteristics are evil and damaging responsible for his eventual doom; on the contrary, their existence is necessary for the continuation of his human life; if utilized properly they even might be helpful in his journey towards attaining self-perfection and ascent towards God-Almighty. But the problem is that animalistic passions and desires do not limit or stop themselves at certain predetermined level, and do not least care about the interests of others. Neither they offer any explanation for human requirements nor care about other desires, and do not follow any other goal except to achieve a saturation point. The sexual passions strive to achieve their own absolute climax and pursue this single goal without pursuing any other objective. Other animalistic passion such as; pleasure of edible and drinks; ambitions for position, power, and fame; attachment to wealth, property, and other luxuries; power of revenge and wrath; and all other characteristics which arise from them do not stop themselves at a certain desired limit, rather each one of them demands its own absolute domination. It is because of this reason that the human-self becomes a battlefield where various passions wage war against each other continuously. This battlefield is never silent until one of them gains victory thus, taking the self into its absolute imprisonment. But among them, reason possesses the most important position and power. By utilizing the religious guidelines might exert control over the passions and desires of self, thus, preventing their tendencies towards excessiveness or dissipation, may take control of the power center, maintain an equilibrium between the desire and passions and in this manner might rescue self's country from anarchy, disturbances and extremism, by guiding him towards the straight path of humanity and ascension towards God-Almighty. However, taking over center of power by the reason is not an easy task, because, it is opposed by a most powerful deceitful enemy called the imperious-self, who is not alone and is supported by many of his friends and partisans. God-Almighty has said: <blockquote dir="rtl"> <p> إِنَّ النَّفْسَ لَأَمَّارَةٌ بِالسُّوءِ إِلَّا مَا رَحِمَ رَبِّي </p> </blockquote> ***“The (human) soul is certainly prone to evil, unless my Lord do bestow His Mercy. (12:53)*** The Commander of the Faithful Imam ‘Ali (a.s.) said: <blockquote dir="rtl"> <p> قال على عليه السلام: العقل والشهوة ضدان, ومؤيد العقل العلم ومؤيد والشهوة الهوى, والنفس متنازعة بينهما. فايهما قهر كانت في جانبه. </p> </blockquote> *“The reason and lust are opposite to each other; knowledge supports reason while the lust is supported by the passions and inordinate desires, self is a battlefield where a war is waged between the reason and lust; whoever becomes victorious in this fight takes control of the self.”*[^27] And, he said: <blockquote dir="rtl"> <p> قال على عليه السلام: الشر كامن في طبيعة كل احد فان غلبه صاحبه بطن وان لم يغلبه ظهر. </p> </blockquote> *“Evil and mischief are hidden inside every self; in case the master of self takes over his control, they remain hidden, but when opposite happens, they make themselves manifested.”*[^28] Therefore, reason is a good ruler but requires support and cooperation. If, we support reason in this confrontation by attacking the forces of passions and lusts, and handover the ruling of the body to reason then we indeed had accomplished a great victory. This is what have been de sired by all the religious pioneers, Divine Messengers, guides, leaders, and seekers of truth through out the ages, and it was to accomplish this objective that they had issued plenty of instructions to mankind. e.g.: The Commander of the Faithful Imam ' ‘Ali (a.s.) had said: <blockquote dir="rtl"> <p> قال على عليه السلام: اياكم وغلبة الشهوات على قلوبكم فان بدايتها ملكة ونهايتها هلكة. </p> </blockquote> *“Be careful! Passions do not take over control of your hearts; because in the beginning they will take you as their possessions, and will ruin you eventually.”*[^29] And said: <blockquote dir="rtl"> <p> قال على عليه السلام: من لم يملك شهوته لم يملك عقله. </p> </blockquote> *“Whoever does not take possession of his passions and desires will not be the master of his reason either.”*[^30] And said: <blockquote dir="rtl"> <p> قال على (ع): غلبة الشهوة اعظم هلك وملكها اشرف ملك. </p> </blockquote> *“The domination of passions is the -worst kind of catastrophe, and triumph over them is -one of the most precious possessions.”*[^31] Imam al-Sadiq (a.s.) said: <blockquote dir="rtl"> <p> قال الصادق عليه السلام: من ملك نفسه اذا رغب واذا رهب واذا اشتهى واذا غضب واذا رضى حرم الله جسده على النار. </p> </blockquote> *“Whoever at the time of seduction, fear, lust, wrath, and consent, is in control of his self; God-Almighty will make the Hell' s fire forbidden for his body.”*[^32] The Commander of the Faithful Imam ' ‘Ali (a.s.) said: <blockquote dir="rtl"> <p> قال على عليه السلام: غالبوا انفسكم على ترك المعاصى يسهل عليكم مقادتها الى الطاعات. </p> </blockquote> *“Take control of your self and do not allow him to indulge in sins, so that it is easier to guide him towards worships.”*[^33] Therefore, domination over the self and controlling his whims and passions is a matter of utmost importance and pre-requisite for achieving self-refinement. Human self is like a mulish horse; if by means of hard training he becomes disciplined, you have the control of his straps in your hands, and is mounted upon his back, then in that case you may be benefited from his commissioning. But if he is not disciplined and wants to run away freely here and there without any control, then there is absolutely no doubt that you will have a crash. Of course, to discipline the rebellious self is an extremely difficult task; although, in the beginning he will offer resistance against you, but if you persisted patiently, he will be subdued eventually. The Commander of the Faithful Imam ‘Ali (a.s.) said: <blockquote dir="rtl"> <p> قال على عليه السلام: اذا صعب عليك نفسك فاصعب لها تذل لك وخادع نفسك عن نفسك تنقد لك. </p> </blockquote> *“lf self showed stubbornness and did not surrender against you, then deal harshly till be becomes tame. Act deceitfully against him until becomes obedient.”*[^34] And said: <blockquote dir="rtl"> <p> قال على عليه السلام: الشهوات اعلال قاتلات افضل دوائها اقتنا الصبر عنها. </p> </blockquote> *“Lusts and passions of self are most fatal diseases, and the best medicines are patience and perseverance against them.”*[^35] [^1]: “For God's-worship there is nothings superior than the reason. A believer is not wise until and unless he possesses the following ten characteristics: 1.The people should expect goodness from him. 2. They should feel immune from his wickedness. 3. He must evaluate the good deeds of others as too much even if they are small. 4. Should regard his good deeds as insignificant even if they re too much. 5. Should never be tired from acquiring knowledge through out his life. 6. Should never be annoyed while people approach him demanding fulfillment of their wants. 7. Should prefer seclusion and obscurity more than outwardly fame and popularity. 8. Poverty in his sight should be more dearer than the richness. 9. He must rely upon on only one single power in the world. 10. The tenth characteristic which is more important than all is -that while seeing others he must say: 'He is more better and pious than me. ' Because, the people belong to two categories: Either they are better or re worst than him. “While encountering the better ones he must show humility and be courteous so that he could be associated with him. Regarding the latter who outwardly does not appear good, he must say: 'May his inner self is better than my own inner self or may be he will become ashamed from his devotion and may return towards God-Almighty through repentance and thus, might attain a prosperous end. “If some one pays need to these dimensions he has indeed discovered his dignity and exaltedness and will be successful over his contemporaries.”-Nasayeh, Ayatullah Mishkini, p-301. [^2]: al-Kafi, vol. 1, p-10. [^3]: al-Kafi, vol. 1, p-11. [^4]: al-Kafi, vol. 1, p-11. [^5]: al Kafi, vol. 1, p-16. [^6]: al-Kafi, vol. 1, p-23. [^7]: al-Kafi, vol. 1, p-25. [^8]: Imam ‘Ali ibn Musa al-Ridha’ (a.s.): was born in Medina on Thursday, 11th Dhu'l-qi'dah 148 A.H. He lived in a period hen the Abbasids were faced with increasing difficulties because of Shi'ite revolts. After al-Mam'un the seventh Abbasid caliph and a contemporary of Imam al-Ridha’ (a.s.) murdered his brother Amin and assumed office, he thought he would solve the problems by naming Imam as his own successor hoping thus, to insure him in worldly affairs and turn the devotion of his followers away from him. After encouragement, urging and finally threats, Imam accepted on condition that he be excused from dismissals, appointments, and other involvement in matters of state. Making the most of this circumstance, the Imam extended guidance to the people, imparting priceless elucidation of Islamic culture and spiritual truths, which have survived in numbers roughly equal to those reaching us from the Commander of the Faithful Imam ‘Ali (a.s.), and in greater number than those of any other Imam. Finally after al-Ma'mun realized his mistake, for Shi'ism began to spread even more rapidly he is said to have poisoned him; he died at the age of 55 in Mashhad Khurasan on Tuesday, 17th Safar 203 A.H.. He is buried in Mashhad Iran. [^9]: al-Kafi, vol. 1, p-11 [^10]: al-Kafi, vol. 1, p-27. [^11]: al-Kafi, vol. 1, p-18. [^12]: Imam Musa al-Kadhim (a.s.): The son of sixth Imam J'afar al-Sadiq was born in Abwa' (between Mecca and Medina) on Sunday 7th Safar 128 A.H. He was contemporary with four Abbasid Caliphs as al-Mansur, Hadi, Mahdi, and Harun. Because of the sever oppression, the necessity of taqiyya grew more stringent, and since he was under close surveillance, he admitted only a few elect Shi'ites. Finally he was martyred -poisoned by owner of the second Abbasid Caliph al-Mansur on 25th Rajab 183 A.H. He is buried in Kadhimayn in Iraq. Despite of most stringent need for caution and taqiyya, he enjoyed in promulgating the religious sciences and made many prophetic sayings available to the Shi'ites, to the extent that he left more teaching on Jurisprudence than any other Imam with the exceptions of Imam al-Baqir (a.s.) and al-Sadiq (a.s.) [Tr]. [^13]: al-Kafi, vol. l, p-17. [^14]: al-Kafi, vol. 1, p-19. [^15]: al-Kafi, vol. 1, p-19. [^16]: al-Kafi, vol. 2, p-54. [^17]: al-Kafi, vol. 2, p-55. [^18]: Bihar al-Anwar, vol. 71, p-338 [^19]: Bihar al-Anwar, vol. 71, p-339. [^20]: Bihar al-Anwar, vol. 71, p-340. [^21]: Bihar al-Anwar, vol. 71, p-340. [^22]: Bihar al-Anwar, vol. 71, p-325. [^23]: Nahjul Balagha, sermon 176. [^24]: Nahjul al-Balagha, sermon 193. [^25]: Tohof al-Aqool, p-385. [^26]: Bihar al-Anwar, vol. 71, p-324. [^27]: Ghirar al-Hukm, vol. 1, p-96. [^28]: Ghirar al-Hukm, vol. 1, p-105. [^29]: Ghirar al-Hukm, p-16. [^30]: Ghirar al-Hukm, vol. 2, p-702. [^31]: Ghirar al-Hukm, vol. 2, p-507. [^32]: Wasail al-Shi'a, vol. 6, p-123. [^33]: Ghirar al-Hukm, vol. 2, p-5-8. [^34]: Ghirar al-Hukm, vol. 1, p-319. [^35]: Ghirar al-Hukm, vol. 1, p-72.
C#
UTF-8
1,321
2.71875
3
[]
no_license
using UnityEngine; using System.Collections; public class Grid : MonoBehaviour { public static int height=20; public static int width=10; public static Transform[,] grid = new Transform[width, height]; public static Vector2 roundVector(Vector2 v) { return new Vector2 (Mathf.Round (v.x), Mathf.Round (v.y)); } public static bool InsideBorder(Vector2 pos) { return((int)pos.x >= 0 && (int)pos.x < width && (int)pos.y >= 0); } public static void deleteRow(int y) { for (int x = 0; x <= width; x++) { Destroy(grid[x,y].gameObject); grid [x, y] = null; } } public static void decreaseRow(int y) { for(int x=0;x<width;x++) { if (grid [x, y] != null) { //moves row towards bottom grid[x,y-1]=grid[x,y]; grid [x, y] = null; //Updates block position grid[x,y-1].position+=new Vector3(0,-1,0); } } } public static void decreaseRowAbove(int y) { for (int i = y; i < height; i++) { decreaseRow (i); } } public static bool isRowFull(int y) { for (int x = 0; x < width; ++x) { if (grid [x, y] == null) return false; } return true; } public static void deleteFullRows() { for (int y = 0; y < height; ++y) { if (isRowFull(y)) { deleteRow(y); decreaseRowAbove(y+1); --y; } } } }
C++
UTF-8
1,257
2.890625
3
[]
no_license
#include "../stdafx.h" #include "CityManager.h" CityManager::CityManager() { } CityManager* CityManager::GetInstance() { if (!s_sharedCityManager) { s_sharedCityManager = new CityManager(); s_sharedCityManager->init(); } return s_sharedCityManager; } void CityManager::DestroyInstace() { if (s_sharedCityManager) { delete s_sharedCityManager; } s_sharedCityManager = nullptr; } void CityManager::init() { } void CityManager::update(time_t dt) { for each (auto& headQuarter in _citys) { headQuarter->update(dt); } } void CityManager::destroy() { for each (auto& headQuarter in _citys) { delete headQuarter; } _citys.clear(); } HeadQuarter* CityManager::createHeadQuarter(Camp camp, unsigned int cityID, unsigned int tragetCityID) { auto headQuarter = new HeadQuarter(camp,cityID,tragetCityID); _citys.emplace_back(headQuarter); return headQuarter; } City* CityManager::createCity(Camp camp, unsigned int cityID) { auto pCity = new City(camp, cityID); _citys.emplace_back(pCity); return pCity; } bool CityManager::isHeadQuarter(unsigned int cityID) const { if (cityID == 0 || cityID == _citys.size() - 1) { return true; } else { return false; } } CityManager* CityManager::s_sharedCityManager = nullptr;
Java
UTF-8
3,048
2.546875
3
[]
no_license
package nl.edm_programming.voodoo; import org.bukkit.entity.EntityType; import java.util.Random; public class Util { public static EntityType generateRandomMobs(){ Random random = new Random(); int i = random.nextInt(31); EntityType mob; switch (i) { case 1: mob = EntityType.ZOMBIE; break; case 2: mob = EntityType.SKELETON; break; case 3: mob = EntityType.CREEPER; break; case 4: mob = EntityType.WITCH; break; case 5: mob = EntityType.WITHER_SKELETON; break; case 6: mob = EntityType.CHICKEN; break; case 7: mob = EntityType.PIG; break; case 8: mob = EntityType.COW; break; case 9: mob = EntityType.MUSHROOM_COW; break; case 10: mob = EntityType.COD; break; case 11: mob = EntityType.BEE; break; case 12: mob = EntityType.BAT; break; case 13: mob = EntityType.CAVE_SPIDER; break; case 14: mob = EntityType.DOLPHIN; break; case 15: mob = EntityType.DROWNED; break; case 16: mob = EntityType.GUARDIAN; break; case 17: mob = EntityType.ELDER_GUARDIAN; break; case 18: mob = EntityType.ENDERMAN; break; case 19: mob = EntityType.ENDERMITE; break; case 20: mob = EntityType.DOLPHIN; break; case 21: mob = EntityType.BLAZE; break; case 22: mob = EntityType.GHAST; break; case 23: mob = EntityType.ILLUSIONER; break; case 24: mob = EntityType.WOLF; break; case 25: mob = EntityType.SLIME; break; case 26: mob = EntityType.PILLAGER; break; case 27: mob = EntityType.RAVAGER; break; case 28: mob = EntityType.VEX; break; case 29: mob = EntityType.SQUID; break; case 30: mob = EntityType.POLAR_BEAR; break; case 31: mob = EntityType.PANDA; break; default: mob = EntityType.ZOMBIE; } return mob; } }
PHP
UTF-8
943
3.0625
3
[]
no_license
<?php namespace Controllers; use Exception; use mysqli; use Services\Service; class BaseController extends Mysqli{ private string $host='localhost'; private string $user='root'; private string $password=''; private string $database = 'test'; private ?string $port = NULL; private ?string $socket = NULL; public function __construct() { parent::__construct($this->host, $this->user, $this->password, $this->database, $this->port, $this->socket); $this->throwConnectionExceptionOnConnectionError(); } private function throwConnectionExceptionOnConnectionError() { try { if (!$this->connect_error) return; $message = sprintf('(%s) %s', $this->connect_errno, $this->connect_error); throw new Exception($message); }catch (Exception $ex){ Service::endResponse(data:$ex,message:$ex->getMessage(),status: 0); } } }
JavaScript
UTF-8
1,847
2.65625
3
[]
no_license
'use strict' const axios = require('axios') const fromThousandsNumberToKString = (number = 0) => number > 999 ? `${(number / 1000).toFixed(0)}K` : number.toString() /** * * @param {string} subreddit - Subreddit name * @param {string} time - Posts date timeframe ('day') * @param {number} limit - Limit posts amount */ async function getSubredditTopPosts ({ subreddit, limit = 3, time = 'day' } = {}) { try { const topPostsApiResponse = await axios.get( `https://www.reddit.com/r/${subreddit}/top.json?limit=${limit}&time=${time}` ) if ( topPostsApiResponse.data && topPostsApiResponse.data.data && topPostsApiResponse.data.data.children && topPostsApiResponse.data.data.children.length > 0 ) { const { children: topPosts } = topPostsApiResponse.data.data const mappedPosts = topPosts.map((post) => { const { title, // eslint-disable-next-line camelcase subreddit_name_prefixed, ups, url, permalink, thumbnail, preview } = post.data return { title, subredditUrl: `https://www.reddit.com/${subreddit_name_prefixed}/top`, ups, upsFormatted: fromThousandsNumberToKString(ups), externalUrl: url, permalink: `https://www.reddit.com${permalink}`, thumbnail, previewImage: preview && preview.images && preview.images[0] && preview.images[0].source.url.replace(/&amp;/g, '&') } }) return mappedPosts } } catch (err) { console.error('Error getting top posts from reddit API:', err.message) throw new Error('Error getting top posts from reddit API:', err.message) } } module.exports = { getSubredditTopPosts }
C
UTF-8
229
2.78125
3
[]
no_license
#include<stdio.h> int main() { int n,i,a,s,d,c=0; scanf("%d",&n); a=n; while(n!=0) { s=1; d=n%10; for(i=1;i<=d;i++) s*=i; c+=s; n=n/10; } if(a==c) printf("true"); else printf("false"); }
C++
UTF-8
260
3.15625
3
[]
no_license
#include <iostream> using namespace std; int main() { int test_arr[6] = {10, 22, 13, 99, 4, 5}; int i, sum = 0; for(i = 0; i < 6; i++) { cout << test_arr[i] << endl; sum = sum + test_arr[i]; } cout << "The sum is: " << sum; return 0; }
SQL
UTF-8
3,780
4.125
4
[]
no_license
SET SERVEROUTPUT ON; DECLARE counter NUMBER; total NUMBER; --Sales cursor for monthly income from rentals CURSOR Sales_Cursor IS SELECT RENTAL.PAYMENTMETHOD, EXTRACT (MONTH FROM RENTAL.RENTDATE)AS MONF, SUM(RENTITEM.RENTFEE)AS ALLRENTS FROM ALLPOWDER.RENTAL INNER JOIN ALLPOWDER.RENTITEM ON ALLPOWDER.RENTAL.RENTID=ALLPOWDER.RENTITEM.RENTID GROUP BY RENTAL.PAYMENTMETHOD, EXTRACT(MONTH FROM RENTAL.RENTDATE) ORDER BY EXTRACT(MONTH FROM RENTAL.RENTDATE); SALE_REC Sales_Cursor%ROWTYPE; --Customer cursor for discounts above a skill level of 5 CURSOR Cust_Cursor IS SELECT CUSTOMER.LASTNAME, CUSTOMER.FIRSTNAME, CUSTOMER.EMAIL, CUSTOMERSKILL.SKILLLEVEL FROM ALLPOWDER.CUSTOMER INNER JOIN ALLPOWDER.CUSTOMERSKILL ON ALLPOWDER.CUSTOMER.CUSTOMERID=ALLPOWDER.CUSTOMERSKILL.CUSTOMERID WHERE ALLPOWDER.CUSTOMERSKILL.SKILLLEVEL >= 6 ORDER BY ALLPOWDER.CUSTOMERSKILL.SKILLLEVEL, ALLPOWDER.CUSTOMER.LASTNAME, ALLPOWDER.CUSTOMER.FIRSTNAME ASC; CUST_REC Cust_Cursor%ROWTYPE; BEGIN /* INFORMATION ABOUT CUSTOMERS */ OPEN Cust_Cursor; LOOP FETCH Cust_Cursor INTO CUST_REC; EXIT WHEN Cust_Cursor%NOTFOUND; DBMS_OUTPUT.PUT_LINE('Name: ' || CUST_REC.LASTNAME || ', ' || CUST_REC.FIRSTNAME); DBMS_OUTPUT.PUT_LINE('Email: ' || CUST_REC.EMAIL); IF CUST_REC.SKILLLEVEL = 10 THEN DBMS_OUTPUT.PUT_LINE('Half-Pipe Rating: **********'); ELSIF CUST_REC.SKILLLEVEL = 9 THEN DBMS_OUTPUT.PUT_LINE('Half-Pipe Rating: *********'); ELSIF CUST_REC.SKILLLEVEL = 8 THEN DBMS_OUTPUT.PUT_LINE('Half-Pipe Rating: ********'); ELSIF CUST_REC.SKILLLEVEL = 7 THEN DBMS_OUTPUT.PUT_LINE('Half-Pipe Rating: *******'); ELSIF CUST_REC.SKILLLEVEL = 6 THEN DBMS_OUTPUT.PUT_LINE('Half-Pipe Rating: ******'); ELSE DBMS_OUTPUT.PUT_LINE(''); END IF; DBMS_OUTPUT.PUT_LINE(' '); END LOOP; CLOSE Cust_Cursor; /* SALES OUTPUT FOR EACH MONTH AND TOTALS */ OPEN Sales_Cursor; counter := 0; FETCH Sales_Cursor INTO SALE_REC; WHILE counter < 5 LOOP total := 0; CASE WHEN SALE_REC.MONF = 1 THEN DBMS_OUTPUT.PUT_LINE('January Rentals----------'); WHEN SALE_REC.MONF = 2 THEN DBMS_OUTPUT.PUT_LINE('February Rentals----------'); WHEN SALE_REC.MONF = 3 THEN DBMS_OUTPUT.PUT_LINE('March Rentals----------'); WHEN SALE_REC.MONF = 11 THEN DBMS_OUTPUT.PUT_LINE('November Rentals----------'); WHEN SALE_REC.MONF = 12 THEN DBMS_OUTPUT.PUT_LINE('December Rentals----------'); ELSE EXIT; END CASE; FOR i in 0..6 LOOP DBMS_OUTPUT.PUT_LINE(SALE_REC.PAYMENTMETHOD || ': ' || to_char(SALE_REC.ALLRENTS,'$9,999')); total := total + SALE_REC.ALLRENTS; FETCH Sales_Cursor INTO SALE_REC; END LOOP; DBMS_OUTPUT.PUT_LINE('______________________'); DBMS_OUTPUT.PUT_LINE('Total Rentals: ' || to_char(total,'$99,999')); DBMS_OUTPUT.PUT_LINE(' '); counter := counter +1; END LOOP; END; /
Shell
UTF-8
553
3.5
4
[]
no_license
#!/usr/bin/env bash # YOUTRACK_HOME is defined in the dockerfile SETUP_FILE=$YOUTRACK_HOME/initial-setup-done EXECUTABLE=$YOUTRACK_HOME/bin/youtrack.sh # Check if there are any java options, and there are no setup file if [ -n "$JETBRAINS_YOUTRACK_JVM_OPTIONS" ] && [ ! -f $SETUP_FILE ]; then echo Setting JVM Options ... i=0 for opt in ${JETBRAINS_YOUTRACK_JVM_OPTIONS[@]}; do clOptions[$i]=-J$opt i=$(($i+1)) done $EXECUTABLE configure ${clOptions[@]} touch $SETUP_FILE fi exec $EXECUTABLE run --no-browser
Markdown
UTF-8
2,979
3.203125
3
[]
no_license
--- layout: post title: "Elasticsearch HTTP Queries with Jest" date: 2015-04-03 12:35:00 -0600 comments: true categories: [programming] tags: [elasticsearch, solr, java, jest, http] --- Elasticsearch has a robust and expansive java api with one large issue - you cannot use the Elasticsearch HTTP Rest protocol to talk to your cluster. Thankfully, HTTP elasticsearch clients exist to work around this issue. [Jest](https://github.com/searchbox-io/Jest) acts as an HTTP wrapper on top of the native elasticsearch api. This is fantastic, because it makes using POJOs and marshalling fairly simple when you cannot use the native api. There are a plethora of elasticsearch features, and by stepping through the official docs and perusing the Jest examples and unit tests, you can more or less figure out how to accomplish what you need. One issue I came across deals with dates: the bane of every programmer's existence. Elasticsearch by default uses Joda date formats while Jest by default uses Java.util Dates (it uses Gson to parse). When marshalling out of a document, Jest is able to see the class (Date) and the field (long - date timestamp). Marshalling this will give parsing errors, as the Date class has no long constructor. Custom parsing to the rescue! Jest supports using a custom Gson parser to marshall out of Elasticsearch, but it is not exactly straightforward to setup. There are 2 steps: 1- Create a new class to implement JsonDeserializer (JsonSerializer if you want to index). All that is required is implementing the deserialize function, which takes in a JsonElement that you can convert to a long and create a Date from. See below: {% highlight java %} class DateTimeTypeConverter implements JsonSerializer<Date>, JsonDeserializer<Date> { // No need for an InstanceCreator since DateTime provides a no-args constructor @Override public JsonElement serialize(Date src, Type srcType, JsonSerializationContext context) { return new JsonPrimitive(src.toString()) } @Override public Date deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { return new DateTime(json.getAsLong()).toDate() } } {% endhighlight %} 2- Register this type adapter with Gson, and give this parser to Jest: {% highlight java %} JestClientFactory factory = new JestClientFactory() Gson gson = new GsonBuilder() .registerTypeAdapter(Date.class, new DateTimeTypeConverter()).create() factory.setHttpClientConfig(new HttpClientConfig .Builder(endpoint) .gson(gson) .multiThreaded(true) .build()) client = factory.getObject() {% endhighlight %} Now, you can parse your Pojo containing Dates directly out of Elasticsearch! This should work now (at least without Date errors): {% highlight java %} SearchResult result = client.execute(search) List<SearchResult.Hit<Article, Void>> hits = searchResult.getHits(Article.class) {% endhighlight %}
Java
UTF-8
487
2.359375
2
[]
no_license
package com.gdufe.kevany.chapter14_type_information.registered_factories.filters; /** * @author: kevanyzeng * @date: 2018/12/3 23:14 * @description: */ public class CabinAirFilter extends Filter { public static class Factory implements com.gdufe.kevany.chapter14_type_information.registered_factories.factory.Factory<CabinAirFilter> { @Override public CabinAirFilter create() { return new CabinAirFilter(); } } }
C#
UTF-8
428
2.9375
3
[]
no_license
public static string MyJoin(this IEnumerable<IEnumerable<IEnumerable<string>>> items) { return items.SelectMany(x => x.MyJoin()); } public static string MyJoin(this IEnumerable<IEnumerable<string>> items) { return items.SelectMany(x => x.MyJoin(()); } public static string MyJoin(this IEnumerable<string> strings) { return string.Join(Environment.NewLine, strings); }
Java
UTF-8
428
1.921875
2
[]
no_license
package com.example.jpademo.entity; import lombok.Data; import javax.persistence.*; /** * Created by Dangdang on 2017/12/21. */ @Entity @Data @Table(name = "book", schema = "transactiondemo") public class BookEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", nullable = false) private Integer id; @Column(name = "name", nullable = false) private String name; }
Shell
UTF-8
287
2.78125
3
[]
no_license
#Get line of touchpad ID=$(xinput | grep Touchpad) #Get id of touchpad ID=`echo ${ID#*id=} | awk '{print $1}'` #Set l0 to turn off the touchpad alias l0="xinput set-prop ${ID} \"Device Enabled\" 0" #Set l1 to turn on the touchpad alias l1="xinput set-prop ${ID} \"Device Enabled\" 1"
C++
UTF-8
1,679
3.296875
3
[]
no_license
#include <stdio.h> #include <vector> using namespace std; char array_info[10][10]; struct pos { unsigned int x; unsigned int y; }; struct pos_pair { pos pos1; pos pos2; }; void print_array(unsigned int row,unsigned int column) { for(unsigned int i=0;i<row;++i) { for(unsigned int j=0;j<column;++j) { printf("%c",array_info[i][j]); if(j==column-1) break; printf(" "); } printf("\n"); } } int main() { unsigned int num; while(scanf("%u",&num)!=EOF) { getchar(); for(unsigned int i=0;i<2*num;++i) for(unsigned int j=0;j<2*num;++j) { char temp; scanf("%c",&temp); array_info[i][j]=temp; getchar(); } unsigned int operation; scanf("%u",&operation); vector<pos_pair> pos_array(operation); for(unsigned int i=0;i<operation;++i) scanf("%u %u %u %u",&pos_array[i].pos1.x,&pos_array[i].pos1.y, &pos_array[i].pos2.x,&pos_array[i].pos2.y); unsigned int count=0; unsigned int success=0; for(unsigned int i=0;i<operation;++i) { if(array_info[pos_array[i].pos1.x-1][pos_array[i].pos1.y-1]==array_info[pos_array[i].pos2.x-1][pos_array[i].pos2.y-1] &&array_info[pos_array[i].pos1.x-1][pos_array[i].pos1.y-1]!='*') { array_info[pos_array[i].pos1.x-1][pos_array[i].pos1.y-1]=array_info[pos_array[i].pos2.x-1][pos_array[i].pos2.y-1]='*'; if(++success==2*num*num) { printf("Congratulations!\n"); break; } else print_array(2*num,2*num); } else { ++count; printf("Uh-oh\n"); } if(count==3) break; } if(count==3) printf("Game Over\n"); } return 0; }
Python
UTF-8
1,607
3.453125
3
[]
no_license
# 打开文件 f = open("C:\\Users\\14259\Desktop\\temporary\\test.txt") # 定义一下根目录 dirname = "C:\\Users\\14259\Desktop\\temporary\\" # 然后使用两个列表分别存储分割之后的内容 boy = [] kefu = [] #需要一个count来给文件命名 count = 1 for each_line in f: if each_line[0:6] != "======": # print(each_line.split(":")) # print(each_line[:6]) # 如果没有遇到分割符 ===,就直接分割程两部分,以冒号来分割 (role,line_spoken) = each_line.split(":") if role == "小甲鱼": boy.append(line_spoken) if role == "小客服": kefu.append(line_spoken) else: # 分别命名文件 file_name_boy = "boy_"+str(count)+".txt" file_name_kefu = "kefu_"+str(count)+".txt" #打开文件 boy_file = open(dirname+file_name_boy,"w") #以写入的形式打开 kefu_file = open(dirname+file_name_kefu,'w') # print(boy,kefu) #写入文件 boy_file.writelines(boy) kefu_file.writelines(kefu) boy_file.close() kefu_file.close() boy = [] kefu = [] count +=1 # 分别命名文件 file_name_boy = "boy_"+str(count)+".txt" file_name_kefu = "kefu_"+str(count)+".txt" #打开文件 boy_file = open(dirname+file_name_boy,"w") #以写入的形式打开 kefu_file = open(dirname+file_name_kefu,'w') # print(boy,kefu) #写入文件 boy_file.writelines(boy) kefu_file.writelines(kefu) boy_file.close() kefu_file.close() f.close() # 代码冗余,需要优化,使用函数
Markdown
UTF-8
1,479
2.984375
3
[]
no_license
# Weather-Application Node.js command line application built for giving the temperature of the location which you input. ### Prerequisites To get this project on your local machine, you need to have [Node.js](https://nodejs.org). ### Installing Install the project by navigating to the weather-application directory( which will contain all the project files) in bash and running ```bash npm install ``` This will install all the necessary dependencies. ### How To Main functionality of the application will be shown here. To see the help, run: ```bash node app.js --help ``` ### To find the temperature in the location input You can see the temperature in your location by running the following command: ```bash node app.js -a “Your Address here ” ``` 'a’ is alias for address so you alternatively write like this too: ```bash node app.js --address “Your address here.” ``` Note that you don’t have to write your full address but your district along with state and country. For ex – -a ‘Mayur Vihar phase-1 Delhi 110091 India’ ## Built With * [Node.JS](http://nodejs.org) - Platform * [Yargs](http://yargs.js.org/) - Parsing command line arguments * [Axios](https://github.com/axios/axios) – Promise based HTTP client for the browser and node.js ## Author * **Eklavya Chopra** ## ## * Thanks to Andrew Mead for creating the course [The Complete Node.js Developer Course 2.0](https://www.udemy.com/the-complete-nodejs-developer-course-2/)
JavaScript
UTF-8
1,502
3.046875
3
[]
no_license
$(document).ready(function() { var position_1 = 1; var position_2 = 1; var winner = 0; var player1_id = $("tr#player1_strip").attr("player-id"); var player2_id = $("tr#player2_strip").attr("player-id"); var start_time = new Date().getTime(); $(document).on('keyup', function(event) { var move = function(player, position) { $("table tr:nth-child(" + player + ") td").removeClass("active") $("table tr:nth-child(" + player + ") td:nth-child(" + position + ")").addClass("active") } if (event.keyCode == 32) { position_1 +=1 move(1, position_1); } if (event.keyCode == 39) { position_2 += 1 move(2, position_2); } if (position_1 === 10) { winner = 1 alert("Player 1 won!") $(document).off('keyup'); } if (position_2 === 10) { winner = 2 alert("Player 2 won!") $(document).off('keyup'); } if (winner) { console.log("There is a winner!") game_id_str = window.location.pathname.split('/').pop(); game_id = parseInt(game_id_str) winning_time = new Date().getTime() - start_time; var game_stats = { game_id: game_id, winner_id: (winner == 1 ? player1_id : player2_id), winning_time: winning_time } $.ajax({ type: "POST", url: '/games/stats', dataType: "json", data: game_stats }).done(function(data) { $('#stats').show(); }) } }); });
Python
UTF-8
6,202
3.5625
4
[ "MIT" ]
permissive
import unittest from typing import List from data_test_search_in_rotated_sorted_array import long_list class Solution(): def search(self, nums: List[int], target: int) -> int: if not nums: return -1 index_left = 0 index_right = len(nums)-1 if nums[index_left] < nums[index_right]: return self.binary_search(nums, target, index_left, index_right) while index_left <= index_right: index_middle = int((index_left + index_right) / 2) val_left = nums[index_left] val_middle = nums[index_middle] val_right = nums[index_right] if val_left == target: return index_left elif val_right == target: return index_right elif val_middle == target: return index_middle # linke seite stetig? if val_left < val_middle: # und target im stetigen Bereich? if val_left <= target and target < val_middle: return self.binary_search(nums, target, index_left, index_middle) # Lösung in rechte Seite? elif ((val_middle > target and val_right > target) or (val_middle < target and val_right < target)): index_left = index_middle + 1 continue else: return -1 # rechte seite stetig? if val_middle < val_right: # und target im stetigen bereich? if val_middle < target and target <= val_right: return self.binary_search(nums, target, index_middle, index_right) # Lösung in linker Seite? elif ((val_left > target and val_middle > target) or (val_left < target and val_middle < target)): index_right = index_middle - 1 continue else: return -1 else: return -1 return -1 def binary_search(self, nums: List[int], target: int, left_index: int, right_index: int) -> int: if not nums: return -1 while left_index <= right_index: middle_index = int((left_index + right_index) / 2) if nums[middle_index] < target: left_index = middle_index + 1 elif nums[middle_index] > target: right_index = middle_index - 1 elif nums[middle_index] == target: return middle_index else: return -1 return -1 def print_for_debugging(self, nums: List[int], index: int, size_per_int: int = 6): str_per_int = '{:^' + str(size_per_int) + '}' for i in range(len(nums)): print(str_per_int.format(i), end='') print() for num in nums: print(str_per_int.format(num), end='') print() for _ in range(index): print(str_per_int.format('---'), end='') print(str_per_int.format('-/\\-')) print('index: ' + str(index)) class TestSearch(unittest.TestCase): def setUp(self): self.sol = Solution() def test_search_nums(self): nums = [4, 5, 6, 7, 8, 0, 1, 2] target = 0 index = self.sol.search(nums, target) self.assertEqual(index, 5) def test_search_nums_zero(self): nums = [4, 5, 6, 7, 0, 1, 2] target = -0 index = self.sol.search(nums, target) self.assertEqual(index, 4) def test_search_target_not_in_nums(self): nums = [4, 5, 6, 7, 0, 1, 2] target = 10 index = self.sol.search(nums, target) self.assertEqual(index, -1) def test_search_target_orderd_nums(self): nums = [-5, -4, -3, 5, 6, 7, 10, 200] target = 10 index = self.sol.search(nums, target) self.assertEqual(index, 6) def test_search_nums_negative(self): nums = [4, 5, 6, 7, 0, 1, 2] target = -30 index = self.sol.search(nums, target) self.assertEqual(index, -1) def test_search_target_empty_list(self): nums = [] target = 10 index = self.sol.search(nums, target) self.assertEqual(index, -1) def test_search_nums_first_num(self): nums = [4, 5, 6, 7, 0, 1, 2] target = 4 index = self.sol.search(nums, target) self.assertEqual(index, 0) def test_search_nums_last_num(self): nums = [4, 5, 6, 7, 0, 1, 2] target = 2 index = self.sol.search(nums, target) self.assertEqual(index, 6) def test_search_nums_last_middle(self): nums = [4, 5, 6, 7, 0, 1, 2] target = 7 index = self.sol.search(nums, target) self.assertEqual(index, 3) def test_search_nums_last_middle_left(self): nums = [4, 5, 6, 7, 0, 1, 2] target = 6 index = self.sol.search(nums, target) self.assertEqual(index, 2) def test_search_nums_last_middle_right(self): nums = [4, 5, 6, 7, 0, 1, 2] target = 0 index = self.sol.search(nums, target) self.assertEqual(index, 4) def test_search_nums_long_list(self): nums = long_list target = 0 index = self.sol.search(nums, target) self.assertEqual(index, 6667) def test_search_nums_long_list_last_elem(self): nums = long_list target = 3332 index = self.sol.search(nums, target) self.assertEqual(index, 9999) def test_search_nums_two_elem_list(self): nums = [1, 3] target = 2 index = self.sol.search(nums, target) self.assertEqual(index, -1) def test_search_nums_three_elem_list(self): nums = [5, 1, 3] target = 4 index = self.sol.search(nums, target) self.assertEqual(index, -1) test = TestSearch() test.setUp() test.test_search_nums_three_elem_list()
PHP
UTF-8
435
2.625
3
[]
no_license
<?php // exercice 1 30/03/2020 // ma première action function test_hook(){ echo '<p class="hello"> Moi comprendre !!</p>'; } add_action( 'test', 'test_hook'); add_filter( 'the_content', 'display_time_ago' ); // Hook time ago function display_time_ago ( $content ) { $content .= " " . __( '<br>Posté il y a ', 'wpcandy' ) . human_time_diff( get_the_time('U'), current_time('timestamp') ); return $content; }
PHP
UTF-8
338
2.65625
3
[]
no_license
<? class SigCheck { private $tool = ''; public function __construct() { } public function init($params) { if(isset($params['home_dir'])) { $this->tool = '"'.$params['home_dir'].DIRECTORY_SEPARATOR.'sigcheck.exe"'; } else { $this->tool = 'sigcheck.exe'; } } public function check($file_in) { } }
Java
UTF-8
334
1.664063
2
[]
no_license
package com.kirg.referencelinksystem.data.notUsedCurrently; import com.kirg.referencelinksystem.entity.notUsedCurrently.Customer; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface CustomerRepository extends JpaRepository <Customer,Long> { }
Python
UTF-8
3,754
3.078125
3
[]
no_license
# Simple reading and writing to a small EEPROM using the MPSSE library and a FT232 in Python # # The EEPROM is a 256 byte device located at 0x50 on the bus. It is # AT24C02 – 2-Wire Bus Serial EEPROM (Atmel) # 256 bytes / 2 kilobit – 8 bytes / page # http://www.atmel.com/devices/AT24C02.aspx # # Project started from: http://buildingelectronics.blogspot.com/2017/09/talking-i2c-via-ftdi-ft2232h-with-python.html # # Note that the libMPSSE.dll file must be in the project directory and must match your Python implementation. # # Don Russ 7/29/2019 import struct import ctypes import time class ChannelConfig(ctypes.Structure): _fields_ = [("ClockRate", ctypes.c_int), ("LatencyTimer",ctypes.c_ubyte), ("Options", ctypes.c_int)] class I2C_TRANSFER_OPTION(object): START_BIT = 0x01 STOP_BIT = 0x02 BREAK_ON_NACK = 0x04 NACK_LAST_BYTE = 0x08 FAST_TRANSFER_BYTES = 0x10 FAST_TRANSFER_BITS = 0x20 FAST_TRANSFER = 0x30 NO_ADDRESS = 0x40 #Create the Python wrapper around the MPSSE library using CTYPES libMPSSE = ctypes.cdll.LoadLibrary("libMPSSE.dll") # This is one way to create the byte string variable values = [0x03, 0x00] raw = struct.pack("%dB"%len(values),*values) #Initialize some of the variables that are used when the MPSSE Library is called chn_count = ctypes.c_int() chn_conf = ChannelConfig(400000,5,0) # 400kHz chn_no = 0 #Assume only one device handle = ctypes.c_void_p() bytes_transfered = ctypes.c_int() buf = ctypes.create_string_buffer(raw,len(raw)) mode = I2C_TRANSFER_OPTION.START_BIT|I2C_TRANSFER_OPTION.STOP_BIT|I2C_TRANSFER_OPTION.FAST_TRANSFER_BYTES|I2C_TRANSFER_OPTION.BREAK_ON_NACK # We use fast transfer when we can and break on NACK # Note that with Break on NAK the ctypes.byref(bytes_transfered) may return a number smaller than the number of bytes sent but the transfer may not hang and timeout. ret = libMPSSE.I2C_GetNumChannels(ctypes.byref(chn_count)) # Used as an example. We assume only one device in the code. print("Interface status:",ret," Number of channels:",chn_count) ret = libMPSSE.I2C_OpenChannel(chn_no, ctypes.byref(handle)) # Here we open the channel and get the handel for that channel print("I2C_OpenChannel status:",ret," Interface Handle:",hex(ctypes.c_void_p.from_buffer(handle).value) ) # Print the status and the memory location of the libMPSSE routine in HEX ret = libMPSSE.I2C_InitChannel(handle,ctypes.byref(chn_conf)) # Configure the FT232 to be I2C at 400kHz print("I2C_InitChannel status:",ret) I2Caddress = 0x50 # Base address of the EEPROM on the I2C bus byte_buf=b'\x00'*16 # Create a byte buffer that is one page long # libMPSSE.I2C_DeviceWrite(handle, I2Caddress, Number of Bytes to transfer, Byte String, Number of Bytes Written returned, mode) ret = libMPSSE.I2C_DeviceWrite(handle, I2Caddress, 5, b'\x00\xDE\xAD\xBE\xEF', ctypes.byref(bytes_transfered), mode) # Write some dead cow to the EEPROM at page 0 ret = libMPSSE.I2C_DeviceWrite(handle, I2Caddress, 1, b'\x00', ctypes.byref(bytes_transfered), mode) # Write the page address to the EEPROM ret = libMPSSE.I2C_DeviceRead(handle, I2Caddress, 16, byte_buf, ctypes.byref(bytes_transfered), mode) # Read back the page from the EEPROM hex_out = "" for b in byte_buf: hex_out += "%02X " % b print("\n") print ("\n 00: ", hex_out,"\n") print("I2C_DeviceWrite status:",ret, "Number of Bytes Transfered:",bytes_transfered) # Display the status of the transfer ret = libMPSSE.I2C_CloseChannel(handle) print("I2C_CloseChannel status:",ret) print("\n")
Markdown
UTF-8
3,106
3.109375
3
[ "MIT" ]
permissive
--- title: المسيح في سفر الرؤيا (الجزء الثاني) date: 19/04/2018 --- `اقرأ رؤيا ١: ١٠-١٨. ماذا يقول المسيح عن نفسه في هذه الفقرة الكتابية؟` يظهر المسيح في هذه الآيات واقفاً في القسم الأول من المقدس السماوي. وقد كان ظُهُور المسيح في هذا الدور هائلاً للغاية لدرجة أن يوحنا سقط عند قدميه بخوف. والمسيح، الذي يعزي ويطمئن دائماً، طلب من يوحنا أن لا يخاف، وأشار المسيح إلى نفسه على أنه الألف والياء، الأول والآخر- وذلك إشارة إلى وجوده الأزلي بوصفه الله. وفي وقت لاحق يتحدث المسيح عن موته وقيامته، وعن الرجاء الذي تجلبه قيامته. فالمسيح لديه «مفاتيح الموت والهاوية.» وبعبارة أخرى، يقول المسيح هنا ما دوَّنه يوحنا أيضاً « ‹أَنَا هُوَ الْقِيَامَةُ وَالْحَيَاةُ. مَنْ آمَنَ بِي وَلَوْ مَاتَ فَسَيَحْيَا، ٢٦ وَكُلُّ مَنْ كَانَ حَيًّا وَآمَنَ بِي فَلَنْ يَمُوتَ إِلَى الأَبَدِ. أَتُؤْمِنِينَ بِهذَا؟› » (يوحنا ١١: ٢٥، ٢٦). وكما فعل مع مرثا ومع يوحنا، يوجهنا المسيح إلى رجاء القيامة الذي هو تتويج وذروة الإيمان المسيحي. وبدون هذا الرجاء، هل سيكون هناك من رجاء؟ `اقرأ رؤيا ٢٢: ٧، ١٢، ١٣. ما الذي تعلنه هذه الآيات أيضاً عن المسيح؟` «يسوع المسيح هو الألف والياء، هو التكوين في العهد القديم والرؤيا في العهد الجديد. وكلاهما يلتقيان معاً في المسيح. إن آدم والله قد تصالحا بواسطة طاعة آدم الثاني الذي أنجز العمل المتمثل في التغلب على تجارب الشيطان والتعويض عن فشل آدم وسقوطه المخزيين» (تعليقات إلن ج. هوايت، موسوعة الأدفنتست لتفسير الكتاب المُقَدَّس، مجلد ٦، صفحة ١٠٩٢). نعم، المسيح هو البداية والنهاية. لقد خلقنا في البداية، وهو سوف يعيد خلقنا في النهاية. إن سفر الرؤيا، من البداية وحتى النهاية، رغم أنه يعلمنا عن التاريخ وأحداث زمن النهاية، هو إعلان يسوع المسيح. ومرة أخرى، أياً كانت الأمور الأخرى التي قد ندرسها عن أحداث زمن النهاية، يجب أن يكون يسوع المسيح هو محور كل شيء. `ما هي الطرق التي يمكننا من خلالها أن نبقي المسيح محور حياتنا في كل يوم؟`
Java
UTF-8
23,909
1.96875
2
[]
no_license
package com.mark.manager.pojo; import java.util.ArrayList; import java.util.List; public class VproCoursesCoverExample { /** * This field was generated by MyBatis Generator. * This field corresponds to the database table vpro_courses_cover * * @mbg.generated Thu Jan 10 23:05:16 CST 2019 */ protected String orderByClause; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table vpro_courses_cover * * @mbg.generated Thu Jan 10 23:05:16 CST 2019 */ protected boolean distinct; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table vpro_courses_cover * * @mbg.generated Thu Jan 10 23:05:16 CST 2019 */ protected List<Criteria> oredCriteria; /** * This method was generated by MyBatis Generator. * This method corresponds to the database table vpro_courses_cover * * @mbg.generated Thu Jan 10 23:05:16 CST 2019 */ public VproCoursesCoverExample() { oredCriteria = new ArrayList<Criteria>(); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table vpro_courses_cover * * @mbg.generated Thu Jan 10 23:05:16 CST 2019 */ public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table vpro_courses_cover * * @mbg.generated Thu Jan 10 23:05:16 CST 2019 */ public String getOrderByClause() { return orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table vpro_courses_cover * * @mbg.generated Thu Jan 10 23:05:16 CST 2019 */ public void setDistinct(boolean distinct) { this.distinct = distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table vpro_courses_cover * * @mbg.generated Thu Jan 10 23:05:16 CST 2019 */ public boolean isDistinct() { return distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table vpro_courses_cover * * @mbg.generated Thu Jan 10 23:05:16 CST 2019 */ public List<Criteria> getOredCriteria() { return oredCriteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table vpro_courses_cover * * @mbg.generated Thu Jan 10 23:05:16 CST 2019 */ public void or(Criteria criteria) { oredCriteria.add(criteria); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table vpro_courses_cover * * @mbg.generated Thu Jan 10 23:05:16 CST 2019 */ public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table vpro_courses_cover * * @mbg.generated Thu Jan 10 23:05:16 CST 2019 */ public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table vpro_courses_cover * * @mbg.generated Thu Jan 10 23:05:16 CST 2019 */ protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table vpro_courses_cover * * @mbg.generated Thu Jan 10 23:05:16 CST 2019 */ public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table vpro_courses_cover * * @mbg.generated Thu Jan 10 23:05:16 CST 2019 */ protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andCourseCoverIdIsNull() { addCriterion("course_cover_id is null"); return (Criteria) this; } public Criteria andCourseCoverIdIsNotNull() { addCriterion("course_cover_id is not null"); return (Criteria) this; } public Criteria andCourseCoverIdEqualTo(Integer value) { addCriterion("course_cover_id =", value, "courseCoverId"); return (Criteria) this; } public Criteria andCourseCoverIdNotEqualTo(Integer value) { addCriterion("course_cover_id <>", value, "courseCoverId"); return (Criteria) this; } public Criteria andCourseCoverIdGreaterThan(Integer value) { addCriterion("course_cover_id >", value, "courseCoverId"); return (Criteria) this; } public Criteria andCourseCoverIdGreaterThanOrEqualTo(Integer value) { addCriterion("course_cover_id >=", value, "courseCoverId"); return (Criteria) this; } public Criteria andCourseCoverIdLessThan(Integer value) { addCriterion("course_cover_id <", value, "courseCoverId"); return (Criteria) this; } public Criteria andCourseCoverIdLessThanOrEqualTo(Integer value) { addCriterion("course_cover_id <=", value, "courseCoverId"); return (Criteria) this; } public Criteria andCourseCoverIdIn(List<Integer> values) { addCriterion("course_cover_id in", values, "courseCoverId"); return (Criteria) this; } public Criteria andCourseCoverIdNotIn(List<Integer> values) { addCriterion("course_cover_id not in", values, "courseCoverId"); return (Criteria) this; } public Criteria andCourseCoverIdBetween(Integer value1, Integer value2) { addCriterion("course_cover_id between", value1, value2, "courseCoverId"); return (Criteria) this; } public Criteria andCourseCoverIdNotBetween(Integer value1, Integer value2) { addCriterion("course_cover_id not between", value1, value2, "courseCoverId"); return (Criteria) this; } public Criteria andCourseCoverKeyIsNull() { addCriterion("course_cover_key is null"); return (Criteria) this; } public Criteria andCourseCoverKeyIsNotNull() { addCriterion("course_cover_key is not null"); return (Criteria) this; } public Criteria andCourseCoverKeyEqualTo(String value) { addCriterion("course_cover_key =", value, "courseCoverKey"); return (Criteria) this; } public Criteria andCourseCoverKeyNotEqualTo(String value) { addCriterion("course_cover_key <>", value, "courseCoverKey"); return (Criteria) this; } public Criteria andCourseCoverKeyGreaterThan(String value) { addCriterion("course_cover_key >", value, "courseCoverKey"); return (Criteria) this; } public Criteria andCourseCoverKeyGreaterThanOrEqualTo(String value) { addCriterion("course_cover_key >=", value, "courseCoverKey"); return (Criteria) this; } public Criteria andCourseCoverKeyLessThan(String value) { addCriterion("course_cover_key <", value, "courseCoverKey"); return (Criteria) this; } public Criteria andCourseCoverKeyLessThanOrEqualTo(String value) { addCriterion("course_cover_key <=", value, "courseCoverKey"); return (Criteria) this; } public Criteria andCourseCoverKeyLike(String value) { addCriterion("course_cover_key like", value, "courseCoverKey"); return (Criteria) this; } public Criteria andCourseCoverKeyNotLike(String value) { addCriterion("course_cover_key not like", value, "courseCoverKey"); return (Criteria) this; } public Criteria andCourseCoverKeyIn(List<String> values) { addCriterion("course_cover_key in", values, "courseCoverKey"); return (Criteria) this; } public Criteria andCourseCoverKeyNotIn(List<String> values) { addCriterion("course_cover_key not in", values, "courseCoverKey"); return (Criteria) this; } public Criteria andCourseCoverKeyBetween(String value1, String value2) { addCriterion("course_cover_key between", value1, value2, "courseCoverKey"); return (Criteria) this; } public Criteria andCourseCoverKeyNotBetween(String value1, String value2) { addCriterion("course_cover_key not between", value1, value2, "courseCoverKey"); return (Criteria) this; } public Criteria andCourseCoverAddressIsNull() { addCriterion("course_cover_address is null"); return (Criteria) this; } public Criteria andCourseCoverAddressIsNotNull() { addCriterion("course_cover_address is not null"); return (Criteria) this; } public Criteria andCourseCoverAddressEqualTo(String value) { addCriterion("course_cover_address =", value, "courseCoverAddress"); return (Criteria) this; } public Criteria andCourseCoverAddressNotEqualTo(String value) { addCriterion("course_cover_address <>", value, "courseCoverAddress"); return (Criteria) this; } public Criteria andCourseCoverAddressGreaterThan(String value) { addCriterion("course_cover_address >", value, "courseCoverAddress"); return (Criteria) this; } public Criteria andCourseCoverAddressGreaterThanOrEqualTo(String value) { addCriterion("course_cover_address >=", value, "courseCoverAddress"); return (Criteria) this; } public Criteria andCourseCoverAddressLessThan(String value) { addCriterion("course_cover_address <", value, "courseCoverAddress"); return (Criteria) this; } public Criteria andCourseCoverAddressLessThanOrEqualTo(String value) { addCriterion("course_cover_address <=", value, "courseCoverAddress"); return (Criteria) this; } public Criteria andCourseCoverAddressLike(String value) { addCriterion("course_cover_address like", value, "courseCoverAddress"); return (Criteria) this; } public Criteria andCourseCoverAddressNotLike(String value) { addCriterion("course_cover_address not like", value, "courseCoverAddress"); return (Criteria) this; } public Criteria andCourseCoverAddressIn(List<String> values) { addCriterion("course_cover_address in", values, "courseCoverAddress"); return (Criteria) this; } public Criteria andCourseCoverAddressNotIn(List<String> values) { addCriterion("course_cover_address not in", values, "courseCoverAddress"); return (Criteria) this; } public Criteria andCourseCoverAddressBetween(String value1, String value2) { addCriterion("course_cover_address between", value1, value2, "courseCoverAddress"); return (Criteria) this; } public Criteria andCourseCoverAddressNotBetween(String value1, String value2) { addCriterion("course_cover_address not between", value1, value2, "courseCoverAddress"); return (Criteria) this; } public Criteria andCourseCoverUptimeIsNull() { addCriterion("course_cover_uptime is null"); return (Criteria) this; } public Criteria andCourseCoverUptimeIsNotNull() { addCriterion("course_cover_uptime is not null"); return (Criteria) this; } public Criteria andCourseCoverUptimeEqualTo(String value) { addCriterion("course_cover_uptime =", value, "courseCoverUptime"); return (Criteria) this; } public Criteria andCourseCoverUptimeNotEqualTo(String value) { addCriterion("course_cover_uptime <>", value, "courseCoverUptime"); return (Criteria) this; } public Criteria andCourseCoverUptimeGreaterThan(String value) { addCriterion("course_cover_uptime >", value, "courseCoverUptime"); return (Criteria) this; } public Criteria andCourseCoverUptimeGreaterThanOrEqualTo(String value) { addCriterion("course_cover_uptime >=", value, "courseCoverUptime"); return (Criteria) this; } public Criteria andCourseCoverUptimeLessThan(String value) { addCriterion("course_cover_uptime <", value, "courseCoverUptime"); return (Criteria) this; } public Criteria andCourseCoverUptimeLessThanOrEqualTo(String value) { addCriterion("course_cover_uptime <=", value, "courseCoverUptime"); return (Criteria) this; } public Criteria andCourseCoverUptimeLike(String value) { addCriterion("course_cover_uptime like", value, "courseCoverUptime"); return (Criteria) this; } public Criteria andCourseCoverUptimeNotLike(String value) { addCriterion("course_cover_uptime not like", value, "courseCoverUptime"); return (Criteria) this; } public Criteria andCourseCoverUptimeIn(List<String> values) { addCriterion("course_cover_uptime in", values, "courseCoverUptime"); return (Criteria) this; } public Criteria andCourseCoverUptimeNotIn(List<String> values) { addCriterion("course_cover_uptime not in", values, "courseCoverUptime"); return (Criteria) this; } public Criteria andCourseCoverUptimeBetween(String value1, String value2) { addCriterion("course_cover_uptime between", value1, value2, "courseCoverUptime"); return (Criteria) this; } public Criteria andCourseCoverUptimeNotBetween(String value1, String value2) { addCriterion("course_cover_uptime not between", value1, value2, "courseCoverUptime"); return (Criteria) this; } public Criteria andCourseCoverIsuploadedIsNull() { addCriterion("course_cover_isuploaded is null"); return (Criteria) this; } public Criteria andCourseCoverIsuploadedIsNotNull() { addCriterion("course_cover_isuploaded is not null"); return (Criteria) this; } public Criteria andCourseCoverIsuploadedEqualTo(Byte value) { addCriterion("course_cover_isuploaded =", value, "courseCoverIsuploaded"); return (Criteria) this; } public Criteria andCourseCoverIsuploadedNotEqualTo(Byte value) { addCriterion("course_cover_isuploaded <>", value, "courseCoverIsuploaded"); return (Criteria) this; } public Criteria andCourseCoverIsuploadedGreaterThan(Byte value) { addCriterion("course_cover_isuploaded >", value, "courseCoverIsuploaded"); return (Criteria) this; } public Criteria andCourseCoverIsuploadedGreaterThanOrEqualTo(Byte value) { addCriterion("course_cover_isuploaded >=", value, "courseCoverIsuploaded"); return (Criteria) this; } public Criteria andCourseCoverIsuploadedLessThan(Byte value) { addCriterion("course_cover_isuploaded <", value, "courseCoverIsuploaded"); return (Criteria) this; } public Criteria andCourseCoverIsuploadedLessThanOrEqualTo(Byte value) { addCriterion("course_cover_isuploaded <=", value, "courseCoverIsuploaded"); return (Criteria) this; } public Criteria andCourseCoverIsuploadedIn(List<Byte> values) { addCriterion("course_cover_isuploaded in", values, "courseCoverIsuploaded"); return (Criteria) this; } public Criteria andCourseCoverIsuploadedNotIn(List<Byte> values) { addCriterion("course_cover_isuploaded not in", values, "courseCoverIsuploaded"); return (Criteria) this; } public Criteria andCourseCoverIsuploadedBetween(Byte value1, Byte value2) { addCriterion("course_cover_isuploaded between", value1, value2, "courseCoverIsuploaded"); return (Criteria) this; } public Criteria andCourseCoverIsuploadedNotBetween(Byte value1, Byte value2) { addCriterion("course_cover_isuploaded not between", value1, value2, "courseCoverIsuploaded"); return (Criteria) this; } public Criteria andCourseCoverIsusedIsNull() { addCriterion("course_cover_isused is null"); return (Criteria) this; } public Criteria andCourseCoverIsusedIsNotNull() { addCriterion("course_cover_isused is not null"); return (Criteria) this; } public Criteria andCourseCoverIsusedEqualTo(Byte value) { addCriterion("course_cover_isused =", value, "courseCoverIsused"); return (Criteria) this; } public Criteria andCourseCoverIsusedNotEqualTo(Byte value) { addCriterion("course_cover_isused <>", value, "courseCoverIsused"); return (Criteria) this; } public Criteria andCourseCoverIsusedGreaterThan(Byte value) { addCriterion("course_cover_isused >", value, "courseCoverIsused"); return (Criteria) this; } public Criteria andCourseCoverIsusedGreaterThanOrEqualTo(Byte value) { addCriterion("course_cover_isused >=", value, "courseCoverIsused"); return (Criteria) this; } public Criteria andCourseCoverIsusedLessThan(Byte value) { addCriterion("course_cover_isused <", value, "courseCoverIsused"); return (Criteria) this; } public Criteria andCourseCoverIsusedLessThanOrEqualTo(Byte value) { addCriterion("course_cover_isused <=", value, "courseCoverIsused"); return (Criteria) this; } public Criteria andCourseCoverIsusedIn(List<Byte> values) { addCriterion("course_cover_isused in", values, "courseCoverIsused"); return (Criteria) this; } public Criteria andCourseCoverIsusedNotIn(List<Byte> values) { addCriterion("course_cover_isused not in", values, "courseCoverIsused"); return (Criteria) this; } public Criteria andCourseCoverIsusedBetween(Byte value1, Byte value2) { addCriterion("course_cover_isused between", value1, value2, "courseCoverIsused"); return (Criteria) this; } public Criteria andCourseCoverIsusedNotBetween(Byte value1, Byte value2) { addCriterion("course_cover_isused not between", value1, value2, "courseCoverIsused"); return (Criteria) this; } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table vpro_courses_cover * * @mbg.generated do_not_delete_during_merge Thu Jan 10 23:05:16 CST 2019 */ public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table vpro_courses_cover * * @mbg.generated Thu Jan 10 23:05:16 CST 2019 */ public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
C++
UTF-8
784
2.5625
3
[]
no_license
#include "visualizeritem.h" cuteGraphLib::VisualizerItem::VisualizerItem(std::string name, QGraphicsScene* scene, QObject *parent) : QObject(parent) { this->name = name; this->scene = scene; scene->setParent(this); } cuteGraphLib::VisualizerItem::~VisualizerItem() { delete scene; } std::string cuteGraphLib::VisualizerItem::getName() const { return this->name; } QGraphicsScene *cuteGraphLib::VisualizerItem::getScene() const { return this->scene; } cuteGraphLib::EdgeGraphicItem* cuteGraphLib::VisualizerItem::getEdgeForKey(std::string key) { return edges.find(key)->second; } void cuteGraphLib::VisualizerItem::insertEdgeWithKey(EdgeGraphicItem* item, std::string key) { edges.insert(std::pair<std::string, EdgeGraphicItem*>(key, item)); }
Python
UTF-8
5,322
2.59375
3
[]
no_license
#!/usr/bin/env python import tornado.ioloop import tornado.web # шаблонизатор loader = tornado.template.Loader(".") # утилита перегрузки сервера при изменениях кода from tornado import autoreload # обработчик вебсокетов from tornado.websocket import WebSocketHandler import json import datetime import time import hashlib import tornadoredis # Создаем клиента Redis в глобальной переменной # для посылки сообщений напрямую в канал import redis redis_client = redis.Redis(host='localhost', port=6379, db=0) # отдает главную страницу class MainHandler(tornado.web.RequestHandler): def get(self): self.render("index.html") # глобальный словарь для хранения текущих соединений ws_clients = {} def send_cliens_to_all(): clnts = [] # сформируем список соединений for key, value in ws_clients.items(): clnts.append({ 'id': key, 'username': value['username'] }) # отправим список в каждое соединение for key, value in ws_clients.items(): ws_clients[key]['connection'].write_message(\ {\ 'action': 'update_clients',\ 'message': json.dumps(clnts)\ }\ ) class WebsocketHandler(tornado.websocket.WebSocketHandler): # сама подписка на канал (асинхронно) @tornado.gen.coroutine def listen_redis(self,channel_id): self.client = tornadoredis.Client() self.client.connect() yield tornado.gen.Task(self.client.subscribe, self.client_id) self.client.listen(self.redis_message) # обработчик поступления сообщений из редиса def redis_message(self,message): if(message.kind != 'subscribe'): data = message.body self.write_message(data) # обработчик открытия соединения def open(self): print('Open connection') # генерируем уникальный идентификатор клиента из таймстампа sign = hashlib.md5(str(datetime.datetime.now()).encode('utf-8')).hexdigest() self.client_id = sign # добавление соединения в глобальный словарь ws_clients[sign] = {} ws_clients[sign]['connection'] = self ws_clients[sign]['username'] = 'undefined' self.listen_redis(self.client_id) # обработчик поступления сообщения из клиента по вебсокету def on_message(self, message): message = json.loads(message) print('got message "%s"' % message['action']) if message['action'] == 'login': print('Login with name %s' % message['message']) ws_clients[self.client_id]['username'] = message['message'] # отправляем клиенту его идентификатор соединения на сервере self.write_message(\ {\ 'action': 'set_connection_id',\ 'message': self.client_id\ }\ ) send_cliens_to_all() if message['action'] == 'offer': print("Sending offer to: %s" % message['destination']) message['initiator_id'] = self.client_id redis_client.publish(\ message['destination'],\ json.dumps(message)\ ) if message['action'] == 'answer': print("Sending answer to: %s" % message['destination']) redis_client.publish(\ message['destination'],\ json.dumps(message)\ ) if message['action'] == 'candidate': print("Sending ICE candidate to: %s" % message['destination']) redis_client.publish(\ message['destination'],\ json.dumps(message)\ ) if message['action'] == 'leave': print("Leaving chat") # обработчик закрытия соединения клиентом def on_close(self): print('close connection') # удаление соединения из глобального словаря del ws_clients[self.client_id] send_cliens_to_all() # конфигурируем приложение роутингом def make_app(): return tornado.web.Application([ # главная страница (r"/", MainHandler), # отдача статики (r'/static/(.*)', tornado.web.StaticFileHandler, {'path': 'static'}), # запросы по веб-сокету (r"/websocket", WebsocketHandler), ]) if __name__ == "__main__": print('Starting server on 8888 port') autoreload.start() autoreload.watch('.') autoreload.watch('index.html') app = make_app() app.listen(8888) tornado.ioloop.IOLoop.current().start()
Python
UTF-8
566
2.875
3
[ "Apache-2.0", "LLVM-exception", "NCSA" ]
permissive
""" Test that IntLiteral.p_denoted_value properly decodes all valid Ada integer literals. Also exercise several erroneous cases that are still accepted by Libadalang's lexer. """ import libadalang as lal c = lal.AnalysisContext('utf-8') u = c.get_from_file('foo.ads') for decl in u.root.findall(lal.NumberDecl): name = decl.f_ids.text expr = decl.f_expr assert isinstance(expr, lal.IntLiteral) try: v = expr.p_denoted_value except lal.PropertyError: v = '<PropertyError>' print('{} ({}) -> {}'.format(name, expr.text, v))
Python
UTF-8
391
3.53125
4
[]
no_license
def DecimalToBinary(num): decimal =0 for i in num: decimal = decimal*2 + int(digit) print(decimal) DecimalToBinary(101) def BinaryConcatenation(x,y): binX = str(bin(x)) binX = binX[2:] binY = str(bin(y)) binY = binY[2:] binXplusY = binX+binY binYplusX = binY+binX print(binX,binY,binXplusY) BinaryConcatenation(5,9)
Python
UTF-8
576
2.640625
3
[]
no_license
import re import sys import os.path import hashlib PATH = sys.argv[1] filemd5 = {} f = open("duplicate_list", "w") def visit(arg, dirname, filenames): for filename in filenames: sys.stdout.write('.') if not(os.path.isdir(dirname + "\\" + filename)): md5 = hashlib.md5(open(dirname + "\\" + filename,'rb').read()).hexdigest() if md5 in filemd5: f.write(filemd5[md5] + ";" + dirname + "\\" + filename + "\n") else: # sys.stdout.write(".") filemd5[md5] = dirname + "\\" + filename os.path.walk(PATH, visit, None) f.close()
C#
UTF-8
4,205
2.546875
3
[]
no_license
using Backend.Models; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; namespace Backend.ViewModels { public class ViewModel1 : BaseNotificationClass { private string _mo; private string _di; private string _mi; private string _do; private string _fr; public string Montag { get { return _mo; } set { _mo = value; OnPropertyChanged(nameof(Montag)); } } public string Dienstag { get { return _di; } set { _di = value; OnPropertyChanged(nameof(Dienstag)); } } public User CurrentUser { get; set; } public string Mittwoch { get { return _mi; } set { _mi = value; OnPropertyChanged(nameof(Mittwoch)); } } public string Donnerstag { get { return _do; } set { _do = value; OnPropertyChanged(nameof(Donnerstag)); } } public string Freitag { get { return _fr; } set { _fr = value; OnPropertyChanged(nameof(Freitag)); } } public ObservableCollection<Fach> Fächer { get; set; } //Liste von allen Fächern public ObservableCollection<Fach> Other { get; set; } //Liste mit selbsterstellten Fächern public ObservableCollection<Fach> Übungen { get; set; } // Liste von allen Übungen public ObservableCollection<Fach> Alle { get; set; } //gemeinsame Liste von Fächern und Übungen public ObservableCollection<User> DeineFreunde { get; set; } //User die du hinzugefügt hast public ObservableCollection<User> AlleUser { get; set; } //Alle verfügbaren User public ObservableCollection<String> Studiengänge { get; set; } public INFaecher Inf { get; set; } public MCFaecher Mcf { get; set; } public ViewModel1() { Inf = new INFaecher(); Mcf = new MCFaecher(); //Initialisierung aller Collections Fächer = new ObservableCollection<Fach>(); //Automatisch in Mainwindow.cs Übungen = new ObservableCollection<Fach>(); //Automatisch in MainWindow.cs Other = new ObservableCollection<Fach>();//Wird aus Datenbank gefüllt Alle = new ObservableCollection<Fach>(); //Automatisch in EditFach AlleUser = new ObservableCollection<User>();//wird aus Datenbank gefüllt Studiengänge = new ObservableCollection<string> { "B-IN", "B-MC", "other" }; //Dein Stundenplan du bistauch ein User DeineFreunde = new ObservableCollection<User> { new User { Name = "Du" } }; //Datumsberechnung DateTime startOfWeek = DateTime.Today.AddDays( (int)CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek - (int)DateTime.Today.DayOfWeek); Montag = "Montag, " + string.Join("", Enumerable.Range(0, 1).Select(i => startOfWeek.AddDays(0).ToString("dd.MM"))); Dienstag = "Dienstag, " + string.Join("", Enumerable.Range(0, 1).Select(i => startOfWeek.AddDays(1).ToString("dd.MM"))); Mittwoch = "Mittwoch, " + string.Join("", Enumerable.Range(0, 1).Select(i => startOfWeek.AddDays(2).ToString("dd.MM"))); Donnerstag = "Donnerstag, " + string.Join("", Enumerable.Range(0, 1).Select(i => startOfWeek.AddDays(3).ToString("dd.MM"))); Freitag = "Freitag, " + string.Join("", Enumerable.Range(0, 1).Select(i => startOfWeek.AddDays(4).ToString("dd.MM"))); CurrentUser = DeineFreunde[0]; } } }
Markdown
UTF-8
2,580
2.515625
3
[]
no_license
--- short_name: "li:jneurophys_2009" title: "What response properties do individual neurons need to underlie position and clutter 'invariant' object recognition?" authors: [Nuo Li, David D. Cox, Davide F. Zoccolan, James J. DiCarlo] type: journal venue: "Journal of Neurophysiology" volume: 102 issue: 1 pages: 360-376 issn: 0022-3077 year: 2009 tags: ['neuroscience', 'primates', 'physiology', 'simulation'] link: "http://jn.physiology.org/cgi/content/abstract/102/1/360" pdf: "J_Neurophysiol-2009-Li-360-76.pdf" PMID: 19439676 --- Primates can easily identify visual objects over large changes in retinal position--a property commonly referred to as position "invariance." This ability is widely assumed to depend on neurons in inferior temporal cortex (IT) that can respond selectively to isolated visual objects over similarly large ranges of retinal position. However, in the real world, objects rarely appear in isolation, and the interplay between position invariance and the representation of multiple objects (i.e., clutter) remains unresolved. At the heart of this issue is the intuition that the representations of nearby objects can interfere with one another and that the large receptive fields needed for position invariance can exacerbate this problem by increasing the range over which interference acts. Indeed, most IT neurons' responses are strongly affected by the presence of clutter. While external mechanisms (such as attention) are often invoked as a way out of the problem, we show (using recorded neuronal data and simulations) that the intrinsic properties of IT population responses, by themselves, can support object recognition in the face of limited clutter. Furthermore, we carried out extensive simulations of hypothetical neuronal populations to identify the essential individual-neuron ingredients of a good population representation. These simulations show that the crucial neuronal property to support recognition in clutter is not preservation of response magnitude, but preservation of each neuron's rank-order object preference under identity-preserving image transformations (e.g., clutter). Because IT neuronal responses often exhibit that response property, while neurons in earlier visual areas (e.g., V1) do not, we suggest that preserving the rank-order object preference regardless of clutter, rather than the response magnitude, more precisely describes the goal of individual neurons at the top of the ventral visual stream.
C#
UTF-8
2,390
2.671875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using AuthenticationWebApi.Entities; using AuthenticationWebApi.Interfaces; using AuthenticationWebApi.Helpers; using Microsoft.Extensions.Options; using AuthenticationWebApi.Models; namespace AuthenticationWebApi.Services { public class UserService : IUserService { private readonly AppSettings _appSettings; private readonly UsersContext _usersContext; public UserService(IOptions<AppSettings> appSettings, UsersContext usersContext) { _appSettings = appSettings.Value; _usersContext = usersContext; } public User Authenticate(AuthenticateModel authenticateModel) { User user = getUser(authenticateModel, _usersContext); if (user == null) { return null; } TokenHandler tokenHandler = new TokenHandler(_appSettings); user.Token = tokenHandler.CreateToken(user); return user.WithoutPassword(); } public IEnumerable<User> getAll() { var users = (from user in _usersContext.users select user).WithoutPasswords(); return users; } private static User getUser(AuthenticateModel authenticateModel, UsersContext usersContext) { var user = usersContext.users.FirstOrDefault(u => u.UserName == authenticateModel.UserName && u.Password == authenticateModel.Password); if (user == null) { return null; } else { return user.WithoutPassword(); } } public bool delete(string userName) { try { User user = _usersContext.users.FirstOrDefault(u => u.UserName == userName); if (user != null) { _usersContext.users.Remove(user); _usersContext.SaveChanges(); return true; } else { return false; } } catch (Exception ex) { return false; } } } }
Java
UTF-8
12,240
2.265625
2
[]
no_license
package com.projects.bookpdf.ui.category; import android.content.Context; import android.util.Log; import android.widget.AbsListView; import android.widget.GridView; import androidx.fragment.app.FragmentActivity; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import androidx.recyclerview.widget.RecyclerView; import com.projects.bookpdf.activity.MainActivity; import com.projects.bookpdf.adapter.ListAdapterBooks; import com.projects.bookpdf.adapter.RecyclerAdapterCategory; import com.projects.bookpdf.adapter.RecyclerAdapterSubCategory; import com.projects.bookpdf.data.Book; import com.projects.bookpdf.data.ObjectCollection; import java.util.ArrayList; import java.util.Objects; import java.util.Observable; import java.util.Observer; public class CategoryViewModel extends ViewModel implements Observer { private Context context; private GridView gridBooks; private RecyclerView recyclerCategory; private RecyclerView recyclerSubCategory; private RecyclerAdapterCategory recyclerAdapterCategory; private RecyclerAdapterSubCategory recyclerAdapterSubCategory; private ListAdapterBooks listAdapterBooks; private MutableLiveData<Boolean> toggleSubCategoryVisibility; private String selectedCategory; private String selectedSubCategory=null; private static final String tag="CategoryVM"; FragmentActivity activity; CategoryViewModel(Context context) { this.context = context; recyclerAdapterCategory=new RecyclerAdapterCategory(context); toggleSubCategoryVisibility=new MutableLiveData<>(); recyclerAdapterCategory.getCategorySelectedNotifier().addObserver(CategoryViewModel.this); ObjectCollection.subCategoryNamesNotifier.addObserver(CategoryViewModel.this); ObjectCollection.booksForCategoryNotifier.addObserver(CategoryViewModel.this); ObjectCollection.booksForSubCategoryNotifier.addObserver(CategoryViewModel.this); ObjectCollection.subCategoryDataNotifier.addObserver(CategoryViewModel.this); ObjectCollection.generalCategoryLoadedNotifier.addObserver(CategoryViewModel.this); ObjectCollection.loadMorePagesForCategoryNotifer.addObserver(CategoryViewModel.this); } void setViews(GridView books, RecyclerView category, RecyclerView subCategory, FragmentActivity activity) { MainActivity.showProgressDialog(); gridBooks=books; recyclerCategory=category; recyclerSubCategory=subCategory; this.activity=activity; //TODO: assigning adapter to category list recyclerCategory.setAdapter(recyclerAdapterCategory); if(ObjectCollection.category.size()>0) MainActivity.stopProgressDialog(); } @Override public void update(Observable o, Object arg) { MainActivity.stopProgressDialog(); if(o instanceof ObjectCollection.LoadMorePagesForCategoryNotifier) { Log.e(tag,"notifier of load more pages"); String[] x=(String[])arg; if(x[1]==null&&selectedSubCategory==null&&x[0].equalsIgnoreCase(selectedCategory)) listAdapterBooks.setMorePages(); else if(x[1] != null && x[0].equalsIgnoreCase(selectedCategory) && x[1].equalsIgnoreCase(selectedSubCategory)) listAdapterBooks.setMorePages(); } if(o instanceof ObjectCollection.GeneralCategoryLoadedNotifier) { recyclerAdapterCategory.notifyDataSetChanged(); } if(o instanceof RecyclerAdapterCategory.CategorySelectedNotifier) { selectedCategory=(String) arg; selectedSubCategory=null; Log.e(tag,"Selected Category : "+selectedCategory); if(ObjectCollection.category.get(selectedCategory).getSubCategoryName()==null) { Log.e(tag,"Selected Category : getSubCategoryName==null "); //TODO : Initialize subCategoryNames LinkedHashMap of Category class object ObjectCollection.getSubCategoryNamesForCategory(selectedCategory,activity); } else if(ObjectCollection.category.get(selectedCategory).getSubCategoryName().size()>0) { Log.e(tag,"Selected Category : getSubCategoryName.size()>0"); toggleSubCategoryVisibility.setValue(true); //TODO: set recyclerSubCategory adapter setRecyclerSubCategoryToAdapter(); } else if(ObjectCollection.category.get(selectedCategory).getSubCategoryName().size()<=0) { Log.e(tag,"Selected Category : getSubCategoryName.size()<=0"); toggleSubCategoryVisibility.setValue(false); } if(ObjectCollection.category.get(selectedCategory).getBooks().size()<=0) { //TODO: load books for selected category Log.e(tag,"Selected Category :getBooks.size<=0"); ObjectCollection.getBooksForCategory(selectedCategory,activity); } else { //TODO : set recyclerBook adapter Log.e(tag,"Selected Category :getBooks.size>0"); setRecyclerBooksToAdapter(Objects.requireNonNull(ObjectCollection.category.get(selectedCategory)).getBooks()); } } if(o instanceof ObjectCollection.SubCategoryNamesNotifier) { Log.e(tag,"inside subCategoryNameNptifier: selected cat : "+selectedCategory); Log.e(tag,"inside subCategoryNameNptifier: arg : "+arg.toString()); Log.e(tag,"inside subCategoryNameNptifier: subCAtegoryName.size() : "+ObjectCollection.category.get(selectedCategory).getSubCategoryName().size()); if(ObjectCollection.category.get(selectedCategory).getSubCategoryName().size()>0) { Log.e(tag,"inside if of subcategoryname notifier : getSubCategoryName.size()>0"); toggleSubCategoryVisibility.setValue(true); //TODO: set recyclerSubCategory adapter setRecyclerSubCategoryToAdapter(); } else { toggleSubCategoryVisibility.setValue(false); } } if(o instanceof ObjectCollection.BooksForCategoryNotifier) { Log.e(tag,"inside BooksForCategoryNotifier : arg ="+arg.toString()); Log.e(tag,"inside BooksForCategoryNotifier : selectedCategory ="+selectedCategory); if(((String) arg).equalsIgnoreCase(selectedCategory)) { //TODO : set recyclerBook adapter setRecyclerBooksToAdapter(Objects.requireNonNull(ObjectCollection.category.get(selectedCategory)).getBooks()); } } //TODO: notifier for selected sub category if(o instanceof RecyclerAdapterSubCategory.SubCategorySelectedNotifier) { selectedSubCategory= (String) arg; if(ObjectCollection.category.get(selectedCategory).getSubCategory().containsKey(selectedSubCategory)) { setBooksForSubCategory(); } else { //TODO: load the selected sub category data ObjectCollection.getSubCategoryData(selectedCategory,selectedSubCategory,activity); } } if(o instanceof ObjectCollection.SubCategoryDataNotifier) { String[] x=(String[]) arg; if(x[0].equalsIgnoreCase(selectedCategory)&&x[1].equalsIgnoreCase(selectedSubCategory)) { if(ObjectCollection.category.get(selectedCategory).getSubCategory().containsKey(selectedSubCategory)) { setBooksForSubCategory(); } } } if(o instanceof ObjectCollection.BooksForSubCategoryNotifier) { String[] x=(String[]) arg; if(x[0].equalsIgnoreCase(selectedCategory)&&x[1].equalsIgnoreCase(selectedSubCategory)) { //TODO : set recyclerBook adapter setRecyclerBooksToAdapter(ObjectCollection.category.get(selectedCategory).getSubCategory().get(selectedSubCategory).getBooks()); } } } private void setRecyclerBooksToAdapter(ArrayList<Book> books) { Log.e(tag,"inside setRecyclerBooksToAdapter : books : "+books.size()); listAdapterBooks = new ListAdapterBooks(books,context,selectedCategory,selectedSubCategory); gridBooks.setAdapter(listAdapterBooks); gridBooks.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if(ListAdapterBooks.morePagesLoaded&&firstVisibleItem+visibleItemCount>=totalItemCount) { if (selectedSubCategory == null) { Log.e(tag,"for category : toalLoadedPages : "+ObjectCollection.category.get(selectedCategory).getTotalLoadedPage()); Log.e(tag,"for category : toalPages : "+ObjectCollection.category.get(selectedCategory).getTotalPage()); if (ObjectCollection.category.get(selectedCategory).getTotalLoadedPage() + 1 <= ObjectCollection.category.get(selectedCategory).getTotalPage()) { ListAdapterBooks.morePagesLoaded = false; ObjectCollection.loadMorePagesForCategory(ObjectCollection.category.get(selectedCategory).getTotalLoadedPage() + 1, selectedCategory, activity); } } else { Log.e(tag,"for category : toalLoadedPages : "+ObjectCollection.category.get(selectedCategory).getSubCategory().get(selectedSubCategory).getTotalLoadedPage()); Log.e(tag,"for category : toalPages : "+ObjectCollection.category.get(selectedCategory).getSubCategory().get(selectedSubCategory).getTotalPage()); if (ObjectCollection.category.get(selectedCategory).getSubCategory().get(selectedSubCategory).getTotalLoadedPage() + 1 <= ObjectCollection.category.get(selectedCategory).getSubCategory().get(selectedSubCategory).getTotalPage()) { ListAdapterBooks.morePagesLoaded = false; ObjectCollection.loadMorePagesForCategory(ObjectCollection.category.get(selectedCategory).getSubCategory().get(selectedSubCategory).getTotalLoadedPage() + 1, selectedCategory, selectedSubCategory, activity); } } } } }); } private void setBooksForSubCategory() { if(ObjectCollection.category.get(selectedCategory).getSubCategory().get(selectedSubCategory).getBooks().size()<=0) { //TODO : load books for selected sub category ObjectCollection.getBooksForSubCategory(selectedCategory,selectedSubCategory,activity); } else { //TODO : set recyclerBook adapter setRecyclerBooksToAdapter(ObjectCollection.category.get(selectedCategory).getSubCategory().get(selectedSubCategory).getBooks()); } } private void setRecyclerSubCategoryToAdapter() { Log.e(tag,"Settign subCAtegoruy to adapter : "+ObjectCollection.category.get(selectedCategory).getSubCategoryName().toString()); recyclerAdapterSubCategory=new RecyclerAdapterSubCategory(context ,ObjectCollection.category.get(selectedCategory).getSubCategoryName()); recyclerAdapterSubCategory.getSubCategorySelectedNotifier().addObserver(CategoryViewModel.this); recyclerSubCategory.setAdapter(recyclerAdapterSubCategory); } public MutableLiveData<Boolean> getToggleSubCategoryVisibility() { return toggleSubCategoryVisibility; } }
Markdown
UTF-8
721
2.875
3
[]
no_license
# Simple Portfolio ******************************************* ## Overview This project was designed as a way to showcase the projects I have created over the course of the University of Oregon Coding Bootcamp. There are three menu items at the top: the home page, a list of the pages I have created, and the contact information page. ## Information Contained On each item in my portfolio, there is listed a brief description of the project, as well as a link to the respective GitHub and Hosted Website for each. On the Contact tab, I have my contact email, phone number, as well as links to my LinkedIn and Github pages. ## Coding Practices This website was created with HTML, CSS, jQuery, and vanilla Javascript.
PHP
UTF-8
2,233
2.53125
3
[ "BSD-3-Clause" ]
permissive
<?php namespace frontend\modules\user\controllers; use common\models\UserProfile; use yii\web\NotFoundHttpException; use frontend\controllers\BehaviorsController; /** * ProfileController implements the CRUD actions for UserProfile model. */ class ProfileController extends BehaviorsController { /** * Lists all UserProfile models. * @return mixed */ public function actionIndex() { $newUser = \Yii::$app->redis->executeCommand('GET', ['users:signup:'.\Yii::$app->user->id]); if($newUser) { \Yii::$app->redis->executeCommand('DEL', ['users:signup:'.\Yii::$app->user->id]); \Yii::$app->session->setFlash('0', [ 'type' => 'info', 'icon' => 'fa fa-smile-o', 'title' => '<strong>'.\Yii::t('app', 'Hello').':</strong><br>', 'message' => \Yii::t('app', 'Welcome to {name} app!', ['name' => \Yii::$app->name]), ] ); } return $this->render('view', [ 'model' => $this->findModel(), ]); } /** * Updates an existing UserProfile model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ public function actionUpdate() { $model = $this->findModel(); if ($model->load(\Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->user_id]); } else { return $this->render('update', [ 'model' => $model, ]); } } /** * Finds the UserProfile model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return UserProfile the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel() { if (($model = UserProfile::findOne(\Yii::$app->user->id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } } }
TypeScript
UTF-8
323
2.609375
3
[ "MIT" ]
permissive
export const defer = <P, E>() => { let internalResolve: (payload: P) => void let internalReject: (error: E) => void const promise = new Promise((resolve, reject) => { internalResolve = resolve internalReject = reject }) return { promise, resolve: internalResolve, reject: internalReject } }
C++
GB18030
2,083
2.765625
3
[]
no_license
#ifndef _CELL_BUFFER_HPP_ #define _CELL_BUFFER_HPP_ #include "Cell.hpp" class CELLBuffer { public: CELLBuffer(int nSize = 8192) { _nSize = nSize; _pBuff = new char[nSize]; } ~CELLBuffer(){ if (_pBuff) { delete[] _pBuff; _pBuff = nullptr; } } bool push(const char* pData,int nLen) { //if (_nLast + nLen > _nSize) { // //дݴڿÿռ Ҳдݿߴ // int n = _nLast + nLen - _nSize; // if (n < 8192) // n = 8192; // char* buff = new char[_nSize + n]; // memcpy(buff, _pBuff, _nLast); // delete[] _pBuff; // _pBuff = buff; //} if (_nLast + nLen <= _nSize) { memcpy(_pBuff + _nLast, pData, nLen); _nLast += nLen; if (_nLast == SEND_BUFF_SIZE) { _BuffFullCount++; } return true; } else { _BuffFullCount++; } return false; } void pop(int nLen) { int n = _nLast - nLen; if (n > 0) { memcpy(_pBuff, _pBuff + nLen, n); } _nLast = n; if (_BuffFullCount > 0) --_BuffFullCount; } int write2socket(SOCKET sockfd) { int ret = 0; if (_nLast > 0 && INVALID_SOCKET != sockfd) { ret = send(sockfd, _pBuff, _nLast, 0); _nLast = 0; _BuffFullCount = 0; } return ret; } char* data() { return _pBuff; } int read4socket(SOCKET sockfd) { if (_nSize - _nLast > 0) { char* szRecv = _pBuff + _nLast; int nLen = (int)recv(sockfd, szRecv, _nSize - _nLast, 0); if (nLen <= 0) { //CELLLog::Info("socket-%d client exit\n", pClient->sockfd()); return nLen; } _nLast += nLen; return nLen; } return 0; } bool hasMsg() { //Ϣβλú if (_nLast >= sizeof(netmsg_DataHeader)) { netmsg_DataHeader *header = (netmsg_DataHeader*)_pBuff; return _nLast >= header->dataLength; } return false; } bool needWrite() { return _nLast >0; } private: //ͻ char* _pBuff = nullptr; //βλãݳ int _nLast = 0; //ܵĿռС int _nSize; //д int _BuffFullCount = 0; }; #endif // !_CELL_BUFFER_HPP_
Python
UTF-8
1,569
3.03125
3
[ "MIT" ]
permissive
#!/usr/bin/env python3 import click import decimal import drawSvg as draw import math def drange(x, y, jump): while x < y: yield float(x) x += decimal.Decimal(jump) @click.command(context_settings={"help_option_names": ["-h", "--help"]}) @click.option( "--diameter", "-d", help="Outer diameter (in inches)", type=click.FLOAT, required=True, ) @click.option( "--with-dots/--without-dots", help="Include light-scattering dots.", default=False ) def main(diameter, with_dots): """Generate laser-cuttable lenses for edge-lit LED lights.""" MARGIN_IN = 0.1 DIMPLE_SPACING_IN = "0.08" # suggest using "0.04" DIMPLE_RADIUS_IN = 0.02 # suggest using 0.01 d = draw.Drawing(diameter, diameter, origin="center", displayInline=False) # Draw a circle d.append( draw.Circle( 0, 0, (diameter / 2), fill="none", stroke_width=0.005, stroke="blue" ) ) if with_dots: for x in drange(-math.ceil(diameter), math.ceil(diameter), DIMPLE_SPACING_IN): for y in drange( -math.ceil(diameter), math.ceil(diameter), DIMPLE_SPACING_IN ): if (x ** 2 + y ** 2) < (((diameter / 2) - MARGIN_IN) ** 2): # point is inside circle d.append( draw.Circle(x, y, DIMPLE_RADIUS_IN, fill="black", stroke="none") ) d.setPixelScale(72) # Set number of pixels per geometry unit d.saveSvg("output.svg") if __name__ == "__main__": main()
Python
UTF-8
378
3.640625
4
[]
no_license
def main (): print ("Enter temperature") a = input (); try: a = float (a) except ValueError: print ("Not a number") return if a >= -273: kel = a + 273 print ("Kel", kel) far = a * (9 / 5) + 32 print ("Faren" , far) else: print ("Min temperature -273") if __name__=='__main__': main()
SQL
UTF-8
343
3.8125
4
[]
no_license
select start_date, min(end_date) from (select start_date from projects where start_date not in (select end_date from projects)) as t1, (select end_date from projects where end_date not in (select start_date from projects)) as t2 where start_date < end_date group by start_date order by datediff(min(end_date), start_date), start_date;
Python
UTF-8
2,087
2.703125
3
[]
no_license
import inline as inline import matplotlib import numpy import pandas from sklearn.ensemble import RandomForestRegressor from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt import constants import spark_interface import seaborn as sns import matplotlib.pyplot as plt sns.set_style("whitegrid") sns.set(rc = {'figure.figsize':(15, 10)}) # udfs ---- # function for creating a feature importance dataframe def imp_df(column_names, importances): df = pandas.DataFrame({'Feature': column_names, 'Information_Gain': importances}) \ .sort_values('Information_Gain', ascending = False) \ .reset_index(drop = True) return df # plotting a feature importance dataframe (horizontal barchart) def var_imp_plot(imp_df, title): imp_df.columns = ['Feature', 'Information_Gain'] sns.barplot(x = 'Information_Gain', y = 'feature', data = imp_df, orient = 'h', color = 'royalblue') \ .set_title(title, fontsize = 20) spark = spark_interface.get_spark_session() end_table = spark_interface.get_table(spark, 'v2_union_repository') cols = constants.items_columns + constants.abilities_columns cols = cols + ['player_slot', 'matchId'] end_table = end_table.drop(*cols) end_table.show() pandas_df = end_table.toPandas() hero_dummies = pandas.get_dummies(pandas_df.hero_name) pandas_df = pandas.concat([pandas_df, hero_dummies], axis=1) pandas_df = pandas_df.drop(['hero_name'], axis=1) X = pandas_df[pandas_df.columns.difference(['win'])] y = pandas_df[['win']] X_train, X_valid, y_train, y_valid = train_test_split(X, y, test_size = 0.8, random_state = 42) rf = RandomForestRegressor(n_estimators = 100, n_jobs = -1, oob_score = True, bootstrap = True, random_state = 42) rf.fit(X_train, y_train) base_imp = imp_df(X_train.columns, rf.Information_Gain) print(base_imp) var_imp_plot(base_imp, 'Default feature importance (scikit-learn)') plt.rcParams["figure.figsize"] = (20,20) plt.show()
PHP
UTF-8
6,118
2.953125
3
[]
no_license
<?php //------------------------------------------------------------------------------ // General.Functions.Inc v2.0 // // (c) Andrew Collington - amnuts@talker.com // (c) Michael Doig - michael@mike250.com //------------------------------------------------------------------------------ // general functions function sqldate_to_string($t="",$short=0) { if ($t=="") return ""; if (!$short) $months = array( "Jan","Feb","Mar","Apr","May","Jun","Jul", "Aug","Sep","Oct","Nov","Dec" ); else $months = array( "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" ); if (preg_match("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})^",$t,$args)) return sprintf("%s %d, %s",$months[$args[2]-1],$args[3],$args[1]); else if (preg_match("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})^",$t,$args)) return sprintf("%s %d, %s",$months[$args[2]-1],$args[3],$args[1]); else return $t; } function ordinal_text($num=1) { $ords = array("th","st","nd","rd"); if ((($num%=100)>9 && $num<20) || ($num%=10)>3) $num=0; return $ords[$num]; } function show_short_story($num=1,$ctry="us",$div="R",$len=210) { global $pathcfg; $sroot = sprintf($pathcfg["sroot"],$ctry,$pathcfg[$div]); if (!file_exists("$sroot/story.$num")) return ""; $contents = file("$sroot/story.$num"); $header = split("\|",trim($contents[0])); $story = ""; // get the line from 1-n and put it into a string for ($i=1; $i<count($contents); $i++) { $story .= $contents[$i]; } // get the default size $story = substr($story,0,$len); // backtrack incase we have hit in the middle of a word while($story[strlen($story)-1] != " ") { $story = substr($story,0,-1); } // add the ... to the string $story = substr($story,0,-1); $story .= "..."; // now build up for html output $story = preg_replace("[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\\.[a-z]{2,3}", "<a href=\"mailto:\\0\">\\0</a>",nl2br(htmlentities($story))); $story = "<p><span class=\"story$num\">$header[0]</span></p><div class=\"stdtext\">" . $story . "</div>"; $story .= "<p><a href=\"stories.php?num=$num&div=$div&ctry=$ctry\">click here for full story</a></p>"; return $story; } function show_full_story($num=1,$ctry="us",$div="R") { global $pathcfg; $sroot = sprintf($pathcfg["sroot"],$ctry,$pathcfg[$div]); if (!file_exists("$sroot/story.$num")) return ""; $contents = file("$sroot/story.$num"); $header = split("\|",trim($contents[0])); $story = ""; // get the line from 1-n and put it into a string for ($i=1; $i<count($contents); $i++) { $story .= $contents[$i]; } // now build up for html output $story = preg_replace("[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\\.[a-z]{2,3}", "<a href=\"mailto:\\0\">\\0</a>",nl2br(htmlentities($story))); // process any special tags $story = preg_replace("/\[link=(\S+?)\](.*?)\[\/link\]/Uis", "<a href=\"\\1\" class=\"12px\">\\2</a>",$story); $story = preg_replace("/\[img=(\S+?)\](.*?)\[\/img\]/Uis", "<img src=\"\\1\" align=\"left\">",$story); $story = preg_replace("/\[i\](.*?)\[\/i\]/Uis", "<i>\\1</i>",$story); $story = preg_replace("/\[b\](.*?)\[\/b\]/Uis", "<b>\\1</b>",$story); $story = preg_replace("/\[u\](.*?)\[\/u\]/Uis", "<u>\\1</u>",$story); $story = preg_replace("/\[pre\](.*?)\[\/pre\]/Uis", "<pre>\\1</pre>",$story); if ($num == 1) { if (file_exists("$sroot/$header[1]")) { $size = GetImageSize("$sroot/$header[1]"); $img = "<img src=\"stories/$header[1]\" $size[3] border=\"0\" alt=\"" . htmlentities($header[0]) . "\" align=\"right\">"; } else { $img = ""; } $story = "<p><span class=\"story$num\">" . htmlentities($header[0]) . "</span></p><div class=\"stdtext\">$img" . $story . "</div>"; } else { $story = "<p><span class=\"story$num\">" . htmlentities($header[0]) . "</span></p><div class=\"stdtext\">" . $story . "</div>"; } return $story; } function show_story_picture($num=1,$ctry="us",$div="R") { global $pathcfg; $sroot = sprintf($pathcfg["sroot"],$ctry,$pathcfg[$div]); $contents = file("$sroot/story.$num"); $header = split("\|",trim($contents[0])); if (file_exists("$sroot/$header[1]")) { $size = GetImageSize ("$sroot/$header[1]"); $img = "<img src=\"stories/$header[1]\" $size[3] border=\"0\" alt=\"" . htmlentities($header[0]) . "\">"; } else { $img = ""; } return $img; } function extcal_12to24hour($hour,$mode) { // converts 12hours format to 24hours if($mode == 'am') return $hour%12; else return $hour%12 + 12; } function extcal_24to12hour($hour) { // converts 24hours format to 12hours with am/pm flag $new_time[0] = ($hour%12)?$hour%12:12; $new_time[1] = ($hour>12)?false:true; // AM (true) / PM (false) return $new_time; } function datestoduration ($start_date, $end_date, $periods = null) { $seconds = strtotime($end_date) - strtotime($start_date); // Force the seconds to be numeric $seconds = (int)$seconds; // Define our periods if (!is_array($periods)) { $periods = array ( //'years' => 31556926, //'months' => 2629743, //'weeks' => 604800, 'days' => 86400, 'hours' => 3600, 'minutes' => 60, //'seconds' => 1 ); } // Loop through foreach ($periods as $period => $value) { $count = floor($seconds / $value); $values[$period] = $count; if ($count == 0) { continue; } $seconds = $seconds % $value; } // Return array if (empty($values)) { $values = null; } // fix the all day value if(date("G:i",strtotime($end_date)) == "23:59") { $values['days']++; $values['hours'] = 0; $values['minutes'] = 0; } return $values; } ?>
Python
UTF-8
3,647
3.390625
3
[]
no_license
import random from binascii import unhexlify from sys import exit from Crypto.Cipher import AES ''' pads message to be a multiple of blocksize. message is a byte array. ''' def pad(message, blockSize): if (message is None) or (len(message) == 0): raise ValueError('message cannot be null or empty') if type(message) is not bytes: raise ValueError('message must be bytes') message = bytearray(message) paddingNeeded = blockSize - (len(message) % blockSize) paddedMessage = message[:] for i in range(paddingNeeded): paddedMessage.append(paddingNeeded) return bytes(paddedMessage) ''' Unpads a message padded by calling pad(). message must be a byte array. ''' def unpad(message): if type(message) is not bytes: raise ValueError('message must be a bytes') message = bytearray(message) numPadding = message[-1] return bytes(message[:-numPadding]) ''' Generates n pseudorandom bytes. ''' def generateIV(n): if n < 1: raise ValueError('n must be greater than 0') return bytes(random.getrandbits(8) for _ in range(n)) ''' Divides message into chunks of size n. The last message may be shorter than n. ''' def chunkMessage(message, n): return [message[i:i+n] for i in range(0, len(message), n)] ''' bitwise XORs m1 and m2. ''' def XOR(m1, m2): return bytes(a ^ b for a, b in zip(m1, m2)) ''' Fk is a pseudorandom function keyed on <key>. It takes message as input and outputs its encrypted ciphertext if <encrypt> is true. Otherwise it pushes the ciphertext back through the pseudorandom function and outputs the plaintext. ''' def Fk(input, key, encrypt = True): cipher = AES.AESCipher(key[:32], AES.MODE_ECB) if encrypt: return bytes(cipher.encrypt(input)) else: return bytes(cipher.decrypt(input)) ''' Creates n CTRs starting at IV and incrementing by one each time. ''' def getCtrs(IV, n): if type(IV) is not bytes: raise ValueError('IV must be bytes') IVasInt = int.from_bytes(IV, 'big') return [i.to_bytes(len(IV), 'big') for i in range(IVasInt, IVasInt + n)] ''' Reads from the input, key, the IV file (if it is provided), and whether to decrypt or encrypt File order is <e|d> input output key [IV] Returns the file contents as bytes converted from utf8. Return order (encrypt, input, key, IV). IV is none if not provided. encrypt is boolean. ''' def readFiles(argv): if len(argv) < 5: print('All parameters not specified') exit(1) if len(argv) > 6: print('Too many parameters specified') exit(1) if argv[1] == 'e': encrypt = True elif argv[1] == 'd': encrypt = False else: print('first argument must be e for encrypt or d for decrypt') exit(1) inputFileName = argv[2] keyFileName = argv[4] if len(argv) == 6: IVFileName = argv[5] with open(IVFileName, 'r') as f: iv = unhexlify(f.read()) else: iv = None with open(inputFileName, 'rb') as f: input = f.read() with open(keyFileName, 'r') as f: key = unhexlify(f.read()) return encrypt, input, key, iv ''' Writes message to the output file specified in argv. Output file must be at argv[2]. ''' def writeFile(message, argv): if type(message) is not bytes: raise ValueError('message must be bytes') outputFileName = argv[3] with open(outputFileName, 'wb') as f: f.write(message) ''' Test that unpad correctly reverses pad. ''' def paddingTest(): m = bytes('abcde', 'utf8') for i in range(1, 11): assert m == (unpad(pad(m, i)))
C
UTF-8
356
2.96875
3
[ "Apache-2.0" ]
permissive
#include<stdio.h> #include<stdlib.h> #include<stdarg.h> void name(int count,...){ va_list ap; va_start(ap,count); int a = va_arg(ap,int); printf("%d ",a); a = va_arg(ap,int); printf("%d ",a); double d = va_arg(ap,double); printf("%f ",d); a = va_arg(ap,int); printf("%d \n",a); } int main() { name(4,1,2,3.1415926,4); return EXIT_SUCCESS; }
Java
UTF-8
2,437
2.71875
3
[]
no_license
package com.example.poetryapp; import android.content.Context; import android.content.res.AssetManager; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class DBFile { //数据库文件名 private final String DB_NAME = "test21.db"; private Context context; public DBFile(Context context){ this.context = context; } // 复制和加载区域数据库中的数据 public String CopyDBFile() throws IOException{ // 第一次运行程序时,加载数据库到data/data/当前的包的名称/databases/<db_name> // 获取准确的路径,context.getPackageName()得到包名 File dir = context.getExternalFilesDir("databases"); System.out.println(dir.toString()); // 如果文件夹不存在就创建文件 if (!dir.exists() || !dir.isDirectory()){ dir.mkdir(); } // 声明文件 File file = new File(dir, DB_NAME); // 输入流 InputStream inputStream = null; // 输出流 OutputStream outputStream = null; // 如果不存在,通过IO流的方式,将assets目录下的数据库文件,写入手机中 if (!file.exists()){ try { // 创建文件 file.createNewFile(); // 通过路径加载文件 inputStream = context.getClass().getClassLoader().getResourceAsStream("assets/" + DB_NAME); // 输出到文件 outputStream = new FileOutputStream(file); byte[] buffer = new byte[1024]; int len; // 按字节写入 while ((len = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } System.out.println("success"); }catch (IOException e){ e.printStackTrace(); }finally { // 关闭资源 if (outputStream != null){ outputStream.flush(); outputStream.close(); } if (inputStream != null){ inputStream.close(); } } } return file.getPath(); } }
Python
UTF-8
2,010
2.671875
3
[]
no_license
import unittest from selenium_tests.pop_tests.pages.main import MainPage from selenium_tests.pop_tests.pages.search import SearchPage from selenium_tests.pop_tests.pages.basket import BasketPage from selenium_tests.pop_tests.pages.login import LoginPage from selenium_tests.pop_tests.pages.address import AddressPage from selenium import webdriver from hamcrest import * import HtmlTestRunner import logging class CartTests(unittest.TestCase): url = "http://automationpractice.com/index.php" def setUp(self) -> None: options = webdriver.ChromeOptions() #options.add_argument("--headless") options.add_argument("--start-maximized") self.driver = webdriver.Chrome(options=options) self.driver.get(url=self.url) self.main_page, self.search_page, self.basket_page, self.login_page, self.address_page \ = MainPage(self.driver), SearchPage(self.driver), BasketPage(self.driver), LoginPage(self.driver), AddressPage(self.driver) self.search_page = SearchPage(self.driver) self.basket_page = BasketPage(self.driver) self.login_page = LoginPage(self.driver) self.address_page = AddressPage(self.driver) def test_adding_to_cart(self): self.login_page.login("aaatest@gmail.com", "test1") self.main_page.make_search("Printed Summer") self.search_page.add_all_elements_to_cart() self.basket_page.navigate_to_cart() total_price = self.basket_page.get_total_price() delivery_price = self.basket_page.get_delivery_price() assert_that(total_price, less_than_or_equal_to(100)) assert_that(delivery_price, equal_to(2)) self.basket_page.proceed_to_ceckout() self.address_page.proceed_to_ceckout() def tearDown(self) -> None: self.driver.save_screenshot("reports\\cart_screenshot.png") self.driver.quit() if __name__ == '__main__': unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(report_name="last_report.html"))
Swift
UTF-8
766
3.140625
3
[ "Unlicense" ]
permissive
// // TextArea.swift // SelabInventoryHelper // // Created by 詹昆宬 on 2021/6/8. // import Foundation import SwiftUI struct TextArea: View { private let placeholder: String @Binding var text: String init(_ placeholder: String, text: Binding<String>) { self.placeholder = placeholder self._text = text } var body: some View { ZStack(alignment: .topLeading) { if text.isEmpty || text.isBlank { Text(placeholder) .foregroundColor(Color.primary.opacity(0.25)) .padding(5) } TextEditor(text: $text) } } } extension String { var isBlank: Bool { return allSatisfy({ $0.isWhitespace }) } }
Go
UTF-8
2,052
3.078125
3
[]
no_license
package main import ( "testing" "reflect" ) func TestNext(t *testing.T) { input := "azzzzzzz" want := "baaaaaaa" if got := NextInput(input); want != got { t.Errorf("NextInput(%q) %q, want %q",input,got,want) } } func TestNextValid(t *testing.T) { inputs := []string{"abcdefgh","ghijklmn"} wants := []string{"abcdffaa","ghjaabcc"} gots := make([]string,0) for _, input := range inputs { got, ok := NextValid(input) if ok { gots = append(gots,got) } } if !reflect.DeepEqual(wants,gots) { t.Errorf("NextValid(%q)",inputs) t.Error(gots," want ",wants) } } func TestIncreasing(t *testing.T) { inputs := []string{"hijklmmn","abbceffg","abbcegjk","abcdffaa","ghjaabcc"} wants := []bool{true,false,false,true,true} gots := make([]bool,0) for _, input := range inputs { gots = append(gots,CheckIncreasing(input)) } if !reflect.DeepEqual(wants,gots) { t.Errorf("CheckIncreasing(%q)",inputs) t.Error(gots," want ",wants) } } func TestForbidden(t *testing.T) { inputs := []string{"hijklmmn","abbceffg","abbcegjk","abcdffaa","ghjaabcc"} wants := []bool{false,true,true,true,true} gots := make([]bool,0) for _, input := range inputs { gots = append(gots,CheckForbidden(input)) } if !reflect.DeepEqual(wants,gots) { t.Errorf("CheckForbiden(%q)",inputs) t.Error(gots," want ",wants) } } func TestPairs(t *testing.T) { inputs := []string{"hijklmmn","abbceffg","abbcegjk","abcdffaa","ghjaabcc"} wants := []bool{false,true,false,true,true} gots := make([]bool,0) for _, input := range inputs { gots = append(gots,CheckPairs(input)) } if !reflect.DeepEqual(wants,gots) { t.Errorf("CheckPairs(%q)",inputs) t.Error(gots," want ",wants) } } func TestInput(t *testing.T) { inputs := []string{"hijklmmn","abbceffg","abbcegjk","abcdffaa","ghjaabcc"} wants := []bool{false,false,false,true,true} gots := make([]bool,0) for _, input := range inputs { gots = append(gots,CheckInput(input)) } if !reflect.DeepEqual(wants,gots) { t.Errorf("CheckInput(%q)",inputs) t.Error(gots," want ",wants) } }
Markdown
UTF-8
2,414
3.203125
3
[]
no_license
--- date: '2012-06-02 13:10:59' layout: post slug: performing-the-refactoring-kata-pairing-with-josh-and-the-pairing-tour status: publish title: Performing the Refactoring Kata, pairing with Josh and the pairing tour wordpress_id: '736' categories: - 8th Light - Apprentice --- **Preforming the Refactoring Kata** At the [8th Light University](http://university.8thlight.com/) on Friday I presented the Refactoring kata that Doug (my mentor) has been working on and thinking about for some time. The material comes from the beginning of the Refactoring book by Martin Fowler and other authors. The example code to be refactored is a simple video rental system with three classes: Movie, Rental and Customer. The focus is on a statement method in the Customer class that creates a billing statement for a customer. It was a lot of fun to present although it was tricky to keep focused on both the refactoring and the dialog. It was a good experience to present again in front of everyone as I will have to do this when I present my apprenticeship challenge(s) on July 6th. **Pairing with Josh** On Friday I also chose my apprenticeship review committee via random selection. Over the next three weeks I will tour among the craftsmen on my committee. Josh is on the committee and while I was scheduling the tour he suggested pairing during Waza or free afternoons on Fridays to work on open source projects. Josh is working on a readme code sample validator. Say you have a project in Ruby with a readme in markdown and it has code samples. How can you ensure that your samples work particularly as your project changes over time? Well that is what Josh is aiming to solve and it was a fun project to work on. **The pairing tour** As mentioned above, the next three weeks will be spent touring with the craftsmen on my apprenticeship review committee. Then I will have two weeks to work on my apprentice challenges that culminates with a presentation on July 6th. The details of the challenges are very sketchy -- I won't know what they are until the Friday before those two weeks. In talking with other apprentices, it's clear that starting as soon as possible is a very good idea as sometimes things take longer than expected. To be clear, everyone has been careful to follow the spirit of the challenges and not reveal any details. I'm looking forward to the challenges but I'm happy the pairing touring is next!
Markdown
UTF-8
26,243
2.984375
3
[]
no_license
--- title: "Display" nodateline: true weight: 1 --- The *display* module is available on platforms which have the *framebuffer* driver enabled. It allows for controlling the display of your device. **Available on:** &nbsp;&nbsp; ✅ [CampZone 2020](/docs/badges/campzone-2020/) &nbsp;&nbsp; ✅ [Disobey 2020](/docs/badges/disobey-2020/) &nbsp;&nbsp; ✅ [CampZone 2019](/docs/badges/campzone-2019/) &nbsp;&nbsp; ✅ [HackerHotel 2019](/docs/badges/hackerhotel-2019/) <br> ✅ [Disobey 2019](/docs/badges/disobey-2019/) &nbsp;&nbsp; ✅ [SHA2017](/docs/badges/sha2017/) # Reference | Command | Parameters | Description | | ---------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | flush | \[flags\] | Flush the contents of the framebuffer to the display. Optionally you may provide flags (see the table down below) | | size | \[window\] | Get the size (width, height) of the framebuffer or a window as a tuple | | width | \[window\] | Get the width of the framebuffer or a window as an integer | | height | \[window\] | Get the height of the framebuffer or a window as an integer | | orientation | \[window\], \[angle\] | Get or set the orientation of the framebuffer or a window | | getPixel | \[window\], x, y | Get the color of a pixel in the framebuffer or a window | | drawRaw | \[window\], x, y, width, height, data | Copy a raw bytes buffer directly to the framebuffer or the current frame of a window. The length of the bytes buffer must match the formula width\*height\*(bitsPerPixel//8). This is a direct copy: color format (bitsPerPixel) must match the specific display of the badge this command is used on. | | drawPixel | \[window\], x, y, color | Draw a pixel in the framebuffer or a window | | drawFill | \[window\], color | Fill the framebuffer or a window | | drawLine | \[window\], x0, y0, x1, y1, color | Draw a line from (x0, y0) to (x1, y1) | | drawTri(angle) | \[window\], x0, y0, x1, y1, x2, y2, color | Draws a filled triangle | | drawRect | \[window\], x, y, width, height, filled, color | Draw a rectangle at (x, y) with size (width, height). Set the filled parameter to False to draw only the border, or set it to True to draw a filled rectangle. | | drawQuad* | \[window\], x0, y0, x1, y1, x2, y2, x3, y3, color | Draws a four-pointed shape between (x0, y0), (x1, y1), (x2, y2) and (x3, y3), always filled | | drawCircle | \[window\], x0, y0, radius, a0, a1, fill, color | Draw a circle with center point (x0, y0) with the provided radius from angle a0 to angle a1, optionally filled (boolean) | | drawText | \[window\], x, y, text, \[color\], \[font\], \[x-scale\], \[y-scale\] | Draw text at (x, y) with a certain color and font. Can be scaled (drawn with rects instead of pixels) in both the x and y direction | | drawPng | \[window\], x, y, \[data or filename\] | Draw a PNG image at (x, y) from either a bytes buffer or a file | | getTextWidth | text, \[font\] | Get the width a string would take if drawn with a certain font | | getTextHeight | text, \[font\] | Get the height a string would take if drawn with a certain font | | pngInfo | \[data or filename\] | Get information about a PNG image | | windowCreate | name, width, height | | | windowRemove | name | | | windowMove | name, x, y | | | windowResize | name, width, height | | | windowVisibility | name, \[visible\] | | | windowShow | name | | | windowHide | name | | | windowFocus | name | | | windowList | \- | | | translate* | \[window\], x, y | Move the canvas of the window by (x, y) | | rotate* | \[window\], angle | Rotate the canvas of the window by an angle (in randians) | | scale* | \[window\], x, y | Scale the canvas of the window by (x, y) | | pushMatrix* | \[window\] | Save the current transformation for later, may be more than one | | popMatrix* | \[window\] | Restore the transformation pushed earlier, may be more than one | | clearMatrix* | \[window\], \[keep-stack\] | Clears the current matrix, and also the matrix stack unless keep-stack is true | | getMatrix* | \[window\] | Returns an array representing the current matrix for the window | | setMatrix* | \[window\], \[matrix\] | Sets the current matrix to the array representing it | | matrixSize* | \[window\] | Returns the current size of the matrix stack for the window | \* This command is only available if you run a firmware with graphics acceleration, and the respective part enabled in the component config under Driver: framebuffer. Currently, badges have these features disabled by default. | flag | platform | description | | ------------------ | ----------------------------- | --------------------------------------------- | | FLAG_FORCE | All | Force flushing the entire screen. | | FLAG_FULL | All | Force flushing the entire screen. | | FLAG_LUT_GREYSCALE | All with greyscale: SHA2017 | Simulate greyscale. | | FLAG_LUT_NORMAL | All with e-ink | Normal speed flush. | | FLAG_LUT_FAST | All with e-ink | Faster flush. | | FLAG_LUT_FASTEST | All with e-ink | Much faster flush. | # Color representation Colors are always represented in 24-bit from within Python, in the 0xRRGGBB format. This matches HTML/CSS colors which are #RRGGBB as well. Devices with a smaller colorspace will not actually store the exact color information provided. For displays with a color depth of less than 24-bit the display driver will automatically mix down the colors to the available color depth. This means that even if you have a black and white display 0x000000 is black and 0xFFFFFF is white. # Examples ## Setting one pixel ``` import display x = 2 y = 3 display.drawPixel(x, y, 0x00FF00) # Set one pixel to 100% green display.flush() # Write the contents of the buffer to the display ``` ## Drawing a line ``` import display display.drawFill(0x000000) # Fill the screen with black display.drawLine(10, 10, 20, 20, 0xFFFFFF) # Draw a white line from (10,10) to (20,20) display.flush() # Write the contents of the buffer to the display ``` ## Drawing a line using pixels: ``` import display, time display.drawFill(display.BLACK) # Fill the screen with black before drawing the line displau.flush() # Write the color to the screen before drawing the line for i in range(80): # Loop for the X axis display.drawPixel(i, 1, 0x00FF00) # Set 1 pixel on the X axis i, and the Y axis 1 to 100% green display.flush() # Write the pixel output to the screen time.sleep(0.050) # Sleep for 50 milliseconds as to show the line being drawn ``` ## Drawing text ``` import display display.drawFill(0x000000) # Fill the screen with black display.drawText(10, 10, "Hello world!", 0xFFFFFF, "permanentmarker22") # Draw the text "Hello world!" at (10,10) in white with the PermanentMarker font with size 22 display.flush() # Write the contents of the buffer to the display ``` ## Drawing a rectangle ``` import display display.drawFill(0x000000) # Fill the screen with black display.drawRect(10, 10, 10, 10, False, 0xFFFFFF) # Draw the border of a 10x10 rectangle at (10,10) in white display.drawRect(30, 30, 10, 10, True, 0xFFFFFF) # Draw a filled 10x10 rectangle at (30,30) in white display.flush() # Write the contents of the buffer to the display ``` ## Spinning a box Note: as described earlier, matrix transformations are not enabled in the firmware by default ``` import display, math # Note: radians are an angle unit where PI (math.pi) is half a rotation display.clearMatrix() # Clear the matrix stack, just in case it wasn't already display.translate(display.width() / 2, display.height() / 2) # Go to the middle of the screen # Everything is now offset as if the middle of the screen is X/Y (0, 0) while True: display.drawFill(0xffffff) # Fill the screen with white display.rotate(math.pi * 0.1) # This will continually rotate the screen by a small amount display.drawRect(-20, -20, 40, 40, True, 0x000000) # Simply draw a rectangle, which will then spin display.flush() # Flush, show everything ``` ## Spinning text Note: as described earlier, matrix transformations are not enabled in the firmware by default Similarly to spinning a box, you can also spin text this way. ``` import display, math # Note: radians are an angle unit where PI (math.pi) is half a rotation text = "Well hello there!" # Whatever you want to show font = "7x5" # Pick a font scale = 2 # You can scale text, too! display.clearMatrix() # Clear the matrix stack, just in case it wasn't already display.translate(display.width() / 2, display.height() / 2) # Go to the middle of the screen # Everything is now offset as if the middle of the screen is X/Y (0, 0) while True: display.drawFill(0xffffff) # Fill the screen with white display.rotate(math.pi * 0.1) # This will continually rotate the screen by a small amount textWidth = display.getTextWidth(text, font) # Get the size so we can center the text textHeight = display.getTextHeight(text, font) display.pushMatrix() # Save the transformation for later display.scale(scale, scale) # Scale the text display.translate(-textWidth / 2, -textHeight / 2) # Move the canvas so the text is centered # It is important you scale first, then translate display.drawText(0, 0, text, 0x000000, font) # Spinny texts display.popMatrix() # Restore the transformation display.flush() # Flush, show everything ``` ## More complex graphics Note: as described earlier, matrix transformations are not enabled in the firmware by default Now you've spun a box and some text, what about something more complicated?<br> Let's say we draw a boat on a wave! First, we draw the boat using some shapes: ``` import display, math def drawBoat(): display.pushMatrix() drawBoatBottom(0x000000) display.translate(-4, 0) # Move just a little so the mast lines up nicely drawBoatMast(0x000000, 0x000000) display.popMatrix() def drawBoatMast(mastColor, flagColor): # The points drawn, by place: # 0--1 # | | # | 6 # | |\ # | 5-4 # | | # 3--2 x0, y0 = 0, -23 x1, y1 = 3, -23 x2, y2 = 3, 0 x3, y3 = 0, 0 x4, y4 = 12, -10 x5, y5 = 3, -10 x6, y6 = 3, -20 display.drawQuad(x0, y0, x1, y1, x2, y2, x3, y3, mastColor) # This is the mast: points 0, 1, 2, 3 display.drawTri(x4, y4, x5, y5, x6, y6, flagColor) # This is the flag: points 4, 5, 6 def drawBoatBottom(color): # The points drawn, by place: # 0--------1 # \ / # 3----2 x0, y0 = -20, 0 x1, y1 = 20, 0 x2, y2 = 16, 8 x3, y3 = -16, 8 display.drawQuad(x0, y0, x1, y1, x2, y2, x3, y3, color) ``` Now, to test your boat drawing action: ``` import display, math # Put the boat drawing functions here display.clearMatrix() # Don't forget display.translate(30, 30) # Move to where you want to draw the boat display.drawFill(0xffffff) # Clear the screen once more drawBoat() # Draw the boat of course display.flush() # Flush display; boat is now visible ``` Then, we'll draw a wave and a sun: ``` import display, math def drawSun(color): # Draws the sun with a circle and some lines display.pushMatrix() display.translate(-3, -3 - display.height()) # This is where the sun will orbit around # We do - display.height() here because we set the origin to be at the bottom of the screen earlier display.drawCircle(0, 0, 30, 0, 360, True, color) # The sun display.rotate(sunOffset) for i in range(20): # Draw lines as the sun's rays display.rotate(math.pi / 10) display.drawLine(0, 35, 0, 45, color) display.popMatrix() # For good measure. display.clearMatrix() display.translate(0, display.height()) sunOffset = 0 offset = 0 boatX = display.width() / 6 boatAngle = 0 boatY = 0 while True: display.drawFill(0xffffff) drawSun(0x000000) # Draw the sun for i in range(display.width()): # Draw the waves by plotting points wave = math.sin((i + offset) * math.pi / 35) * 8 - 35 display.drawPixel(i, wave, 0x000000) if i & 1: for j in range(round(wave - 1) | 1, 0, 2): display.drawPixel(i, j + ((i >> 1) & 1) + 1, 0x000000) offset += 8 # Move the waves over by a bit sunOffset += math.pi * 0.025 # Spin the sun by a bit display.flush() ``` Finally, you can draw the boat on the wave, by adding some code: ``` while True: display.drawFill(0xffffff) drawSun(0x000000) for i in range(display.width()): wave = math.sin((i + offset) * math.pi / 35) * 8 - 35 display.drawPixel(i, wave, 0x000000) if i & 1: for j in range(round(wave - 1) | 1, 0, 2): display.drawPixel(i, j + ((i >> 1) & 1) + 1, 0x000000) # vvvv HERE vvvv display.pushMatrix() # Save the transformation, we're going to mess with it waterLevelBeforeBoat = math.sin((boatX + 2 + offset) * math.pi / 35) * 8 - 35 boatY = math.sin((boatX + offset) * math.pi / 35) * 8 - 35 # Calculate the two water levels, one at and one before the boat # By doing this, we know how and where to position the boat boatAngle = math.atan2(waterLevelBeforeBoat - boatY, 2) # Using atan2 to find the angle required to rock the boat with the wave display.translate(boatX, boatY - 6) # Now, position the boat display.rotate(boatAngle) drawBoat() # And draw the boat display.popMatrix() # Undo our changes to the transformation # ^^^^ HERE ^^^^ offset += 8 sunOffset += math.pi * 0.025 display.flush() ``` The source code for the boat can be found here: [gist: boat.py](https://gist.github.com/robotman2412/121ebe82a74dbca13d3c5f3d1eddb1d7) ## Available fonts: The fonts in the latest firmware can be obtained from the [sourcecode](https://github.com/badgeteam/badgePython/blob/master/components/driver_framebuffer/driver_framebuffer_text.cpp#L50). # Known problems - Rotation of the contents of windows does not work correctly in combination with rotation of the screen itself - There is no method available to list the fonts available on your platform - There is no method for providing a custom font - There is no anti-aliassing support
Java
UTF-8
1,051
3.796875
4
[]
no_license
/* * @author Ariyana Ramos */ package org.howard.edu.lsp.exam.question40; /* * This is an abstract class defining a hierarchy that can represent Animals. The methods * define the 2 behaviors: the ability to speak and the ability to move. */ public abstract class Animal { String name; String phrase; /* * This methods takes in the name of the animal as the parameter * @param name - name of the animal */ public Animal (String name) { this.name = name; } /* * This method returns that the specified animal can speak. * @return "This animal can speak." */ public void speak() { phrase = "This " + name + " speaks."; return; } /* * This method returns that the specified animal can move. * @return "This animal moves forward." */ public void move() { phrase = "This " + name + " moves forward."; return; } /* * This method returns the string representation of the respective called method. * @return String representation of the defined behavior. */ public String toString() { return phrase; } }
C#
UTF-8
3,620
2.609375
3
[]
no_license
using System; using System.Collections.Generic; using System.Text; namespace UniTimetable { partial class Solver { public class Preset { string Name_; List<Criteria> Criteria_; List<Filter> Filters_; #region Constructors public Preset(string name) { Name_ = name; Criteria_ = new List<Criteria>(); Filters_ = new List<Filter>(); } public Preset(string name, IEnumerable<Criteria> criteria, IEnumerable<Filter> filters) { Name_ = name; // criteria list if (criteria == null) Criteria_ = new List<Criteria>(); else Criteria_ = new List<Criteria>(criteria); // filter list if (filters == null) Filters_ = new List<Filter>(); else Filters_ = new List<Filter>(filters); } #endregion #region Accessors public List<Criteria> Criteria { get { return Criteria_; } } public List<Filter> Filters { get { return Filters_; } } #endregion public override string ToString() { return Name_; } } public static readonly Preset[] Presets = new Preset[] { /*new Preset( "Test", new Criteria[] { new Criteria(FieldIndex.Days, Preference.Minimise), new Criteria(FieldIndex.LongBreak, Preference.Minimise), new Criteria(FieldIndex.EarlyStart, Preference.Maximise), new Criteria(FieldIndex.TimeAtUni, Preference.None), new Criteria(FieldIndex.AverageStart, Preference.Maximise), new Criteria(FieldIndex.MaxDayLength, Preference.Minimise) }, new Filter[] { new Filter(false, FieldIndex.AverageStart, new TimeOfDay(10, 30), FilterTest.GreaterThan), new Filter(true, FieldIndex.LongBreak, new TimeLength(3, 00), FilterTest.EqualTo) }),*/ new Preset( "Default", new Criteria[] { new Criteria(FieldIndex.Days, Preference.Minimise), new Criteria(FieldIndex.EarlyStart, Preference.Maximise), new Criteria(FieldIndex.TimeAtUni, Preference.Minimise), new Criteria(FieldIndex.LongBreak, Preference.Minimise), new Criteria(FieldIndex.AverageStart, Preference.Maximise), new Criteria(FieldIndex.MaxDayLength, Preference.Minimise) }, new Filter[] {}), new Preset( "No Early Mornings!", new Criteria[] { new Criteria(FieldIndex.EarlyStart, Preference.Maximise), new Criteria(FieldIndex.AverageStart, Preference.Maximise), new Criteria(FieldIndex.Days, Preference.Minimise) }, new Filter[] {}) }; } }
Python
UTF-8
2,204
3.515625
4
[]
no_license
# fit to y(x) = a_1 exp(a2 x) using a nonlinear fitting technique that # reduces to a multivariate root finding problem # # This is very sensitive to our initial guess # # M. Zingale (2013-03-10) import numpy import numpy.linalg import pylab tol = 1.e-5 def fun(a, x, y): """ the derivatives of our fitting function wrt each parameter: Q = sum_{i=1}^N (y_i = a0 exp(a1 x_i) )**2 -- these are what we zero """ # dQ/da0 f0 = numpy.sum(numpy.exp(a[1]*x)*(a[0]*numpy.exp(a[1]*x) - y)) # dQ/da1 f1 = numpy.sum(x*numpy.exp(a[1]*x)*(a[0]*numpy.exp(a[1]*x) - y)) return numpy.array([f0, f1]) def jac(a, x, y): """ return the Jacobian of fun """ # df0/da0 df0da0 = numpy.sum(numpy.exp(2.0*a[1]*x)) # df0/da1 df0da1 = numpy.sum(x*numpy.exp(a[1]*x)*(2.0*a[0]*numpy.exp(a[1]*x) - y)) # df1/da0 df1da0 = numpy.sum(x*numpy.exp(2.0*a[1]*x)) # df1/da1 df1da1 = numpy.sum(x**2*numpy.exp(a[1]*x)*(2.0*a[0]*numpy.exp(a[1]*x) - y)) return numpy.array([ [df0da0, df0da1], [df1da0, df1da1] ]) def fRoots(aguess, x, y): """ aguess is the initial guess to our fit parameters. x and y are the vector of points that we are fitting to """ avec = aguess.copy() err = 1.e100 while err > tol: # get the jacobian J = jac(avec, x, y) print "condition number of J: ", numpy.linalg.cond(J) # get the current function values f = fun(avec, x, y) # solve for the correction: J dx = -f da = numpy.linalg.solve(J, -f) avec += da err = numpy.max(numpy.abs(da)) return avec # make up some experimental data a0 = 2.5 a1 = 2./3. sigma = 2.0 x = numpy.linspace(0.0, 4.0, 25) y = a0*numpy.exp(a1*x) + sigma*numpy.random.randn(len(x)) pylab.scatter(x,y) pylab.errorbar(x, y, yerr=sigma, fmt=None, label="_nolegend_") # initial guesses aguess = numpy.ones(2) # fit afit = fRoots(aguess, x, y) print afit p = pylab.plot(x, afit[0]*numpy.exp(afit[1]*x), label=r"$a_0 = $ %f; $a_1 = $ %f" % (afit[0], afit[1])) pylab.legend(numpoints=1, frameon=False) pylab.savefig("nonlinear-fit.png")
Swift
UTF-8
763
2.578125
3
[ "Apache-2.0" ]
permissive
import UIKit class ViewController2: UIViewController { var textV2: String! @IBOutlet weak var historyText: UITextView! override func viewDidLoad() { super.viewDidLoad() historyText.editable = false historyText.scrollEnabled = true historyText.text = textV2 // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { let controller = segue.destinationViewController as! ViewController controller.historyText = textV2 } }
C++
UTF-8
1,942
3.28125
3
[ "Apache-2.0" ]
permissive
#include <bits/stdc++.h> using namespace std; // Complete the morganAndString function below. bool compare(string s1, int i,string s2, int j) { while(i<s1.size() && j<s2.size()) { if(s1[i] < s2[j]) return true; else if(s1[i]> s2[j]) return false; i++; j++; } if(i == s1.size()) return false; else return true; } string morganAndString(string s1, string s2) { int a=0,b=0; string s = ""; while(a<s1.size() && b<s2.size()) { if(s1[a] > s2[b]) { s+=s2[b]; b++; } else if(s1[a] < s2[b]) { s+=s1[a]; a++; } else { if(compare(s1,a+1,s2,b+1)) { s+=s1[a]; a++; while(a<s1.size() && s1[a] == s1[a-1]) { s+=s1[a]; a++; } } else{ // cout << s << "\n"; s +=s2[b]; b++; while(b<s2.size() && s2[b] == s2[b-1]) { s+=s2[b]; b++; } } } } // cout << endl; // // cout << b << " " << s2.size()-b; // cout << "\n" << a << " " << s1.size(); if(a==s1.size()) { s += s2.substr(b,s2.size()-b); } else { s += s1.substr(a,s1.size()-a); } return s; } int main() { ofstream fout(getenv("OUTPUT_PATH")); int t; cin >> t; cin.ignore(numeric_limits<streamsize>::max(), '\n'); for (int t_itr = 0; t_itr < t; t_itr++) { string a; getline(cin, a); string b; getline(cin, b); string result = morganAndString(a, b); fout << result << "\n"; } fout.close(); return 0; }
Java
UTF-8
1,106
2.46875
2
[]
no_license
package br.com.concretesolutions.animationdojo; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class Cena1Fragment extends Fragment implements AnimationFragment{ ViewGroup root; View view; public static Cena1Fragment newInstance() { Cena1Fragment fragment = new Cena1Fragment(); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View layout = inflater.inflate(R.layout.fragment_cena1, container, false); root = (ViewGroup) layout.findViewById(R.id.cena1_view_root); view = layout.findViewById(R.id.cena1_view1); return layout; } @Override public void playAnimation() { view.setVisibility(view.getVisibility() == View.VISIBLE? View.GONE : View.VISIBLE); } }
C
UTF-8
3,668
3.09375
3
[]
no_license
/* Generic */ #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <pthread.h> #include <semaphore.h> #include <sched.h> /* Network */ #include <netdb.h> #include <sys/socket.h> #define BUF_SIZE 100 struct arg_struct { char* host; char* portnum; char* files[2]; int hasSecondFile; }; pthread_barrier_t myBarrier; int FIFO = 0; void *getThread(void * input); sem_t mutex; // Get host information (used to establishConnection) struct addrinfo *getHostInfo(char* host, char* port) { int r; struct addrinfo hints, *getaddrinfo_res; // Setup hints memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; if ((r = getaddrinfo(host, port, &hints, &getaddrinfo_res))) { fprintf(stderr, "[getHostInfo:21:getaddrinfo] %s\n", gai_strerror(r)); return NULL; } return getaddrinfo_res; } // Establish connection with host int establishConnection(struct addrinfo *info) { if (info == NULL) return -1; int clientfd; for (;info != NULL; info = info->ai_next) { if ((clientfd = socket(info->ai_family, info->ai_socktype, info->ai_protocol)) < 0) { perror("[establishConnection:35:socket]"); continue; } if (connect(clientfd, info->ai_addr, info->ai_addrlen) < 0) { close(clientfd); perror("[establishConnection:42:connect]"); continue; } freeaddrinfo(info); return clientfd; } freeaddrinfo(info); return -1; } // Send GET request void GET(int clientfd, char *path) { char req[1000] = {0}; sprintf(req, "GET %s HTTP/1.0\r\n\r\n", path); send(clientfd, req, strlen(req), 0); } void * getThread(void * input){ struct arg_struct *args = input; int clientfd; char* filename; int fileupto = 0; while(1) { if (FIFO) sem_wait(&mutex); filename = args->files[fileupto]; if (args->hasSecondFile) { fileupto = !fileupto; } // Establish connection with <hostname>:<port> clientfd = establishConnection(getHostInfo(args->host, args->portnum)); if (clientfd == -1) { fprintf(stderr, "[main:73] Failed to connect to: %s:%s%s \n", args->host, args->portnum, filename); return NULL; } GET(clientfd, filename); if (FIFO) sem_post(&mutex); pthread_barrier_wait(&myBarrier); char buf[BUF_SIZE]; while (recv(clientfd, buf, BUF_SIZE, 0) > 0) { fputs(buf, stdout); fflush(stdout); memset(buf, 0, BUF_SIZE); } close(clientfd); } return NULL; } int main(int argc, char **argv) { if (argc < 6) { fprintf(stderr, "USAGE: client [host] [portnum] [threads] [schedalg] [filename1] [filename2]\n"); return 1; } int numberOfThreads = atoi(argv[3]); if(numberOfThreads < 1){ printf("Invalid number of threads"); exit(1); } pthread_t threads[numberOfThreads]; if(!strcmp(argv[4], "FIFO")) FIFO = 1; pthread_barrier_init(&myBarrier, NULL, numberOfThreads); if (FIFO) sem_init(&mutex, 0, 1); struct arg_struct args; args.host = argv[1]; args.portnum = argv[2]; args.files[0] = argv[5]; args.hasSecondFile = 0; //Probs not needed. if (argc > 6) { args.hasSecondFile = 1; args.files[1] = argv[6]; } for (int i = 0; i < numberOfThreads; i++) { pthread_create(&threads[i], NULL, getThread, (void*) &args); } while (1) sched_yield(); return 0; }
Go
UTF-8
1,177
3.03125
3
[ "MIT" ]
permissive
package wire import ( "bytes" "testing" "time" "github.com/stretchr/testify/assert" ) func TestNewEventBus(t *testing.T) { eb := NewEventBus() assert.NotNil(t, eb) } func TestSubscribe(t *testing.T) { eb := NewEventBus() myChan := make(chan *bytes.Buffer, 10) assert.NotNil(t, eb.Subscribe("whateverTopic", myChan)) } func TestPublish(t *testing.T) { newEB(t) } func TestUnsubscribe(t *testing.T) { eb, myChan, id := newEB(t) eb.Unsubscribe("whateverTopic", id) eb.Publish("whateverTopic", bytes.NewBufferString("whatever2")) select { case <-myChan: assert.FailNow(t, "We should have not received message") case <-time.After(50 * time.Millisecond): // success } } func newEB(t *testing.T) (*EventBus, chan *bytes.Buffer, uint32) { eb := NewEventBus() myChan := make(chan *bytes.Buffer, 10) id := eb.Subscribe("whateverTopic", myChan) assert.NotNil(t, id) eb.Publish("whateverTopic", bytes.NewBufferString("whatever")) select { case received := <-myChan: assert.Equal(t, "whatever", received.String()) case <-time.After(50 * time.Millisecond): assert.FailNow(t, "We should have received a message by now") } return eb, myChan, id }
Java
UTF-8
587
2.234375
2
[]
no_license
package com.quarkus.repo; import com.quarkus.model.User; import io.quarkus.hibernate.orm.panache.PanacheRepositoryBase; import javax.enterprise.context.ApplicationScoped; import javax.transaction.Transactional; @ApplicationScoped public class UserRepo implements PanacheRepositoryBase<User,Long> { public User findByName(String name) { return find("name", name).firstResult(); } public User findByEmail(String email) { return find("email", email).firstResult(); } @Transactional public void save(User user){ user.persist(); } }
Java
UTF-8
3,249
4.28125
4
[]
no_license
package com.example.sort.selection; import java.util.Arrays; /** * @author hzq * @date 2019/6/22 18:10 * @desc 从第一个元素开始,扫描整个待排数组,找到最小的元素放之后再与第一个元素交换位置, * 然后再从第二个元素开始,继续寻找最小的元素与第二个元素交换位置,依次类推。 */ public class SelectionSort { public static void main(String[] args) { int[] arr = {20,40,30,10,60,50}; test2(arr); System.out.println(Arrays.toString(arr)); } public static void test1(int[] arr){ int temp; int min; int counter = 1; for(int i = 0; i < arr.length - 1; i++){ min = i; for(int j = i + 1; j < arr.length - 1; j++){ //每完成一轮排序,就确定了一个相对最小元素,下一轮排序只对后面的元素排序 if(arr[min] > arr[j]){ //如果待排数组中的某个元素比当前元素小,minPoint指向该元素的下标 min = j; } } if(i != min){ //如果发现了更小的元素,交换位置 temp = arr[i]; arr[i] = arr[min]; arr[min] = temp; } System.out.println("第" + (counter++) + "轮排序结果: " + Arrays.toString(arr)); } } public static void test2(int[] arr){ int min; int max; int temp; int len = arr.length; int counter = 1; for(int i = 0; i < len / 2; i++){ min = i; max = i; for(int j = i + 1; j <= len - 1 - i; j++){ //每完成一轮排序,就确定了两个最值,下一轮排序时比较范围减少两个元素 if(arr[min] > arr[j]){ //如果待排数组中的某个元素比当前元素小,minPoint指向该元素的下标 min = j; continue; }else if(arr[max] < arr[j]){ //如果待排数组中的某个元素比当前元素大,maxPoint指向该元素的下标 max = j; } } if(min != i){ //如果发现了更小的元素,与第一个元素交换位置 temp = arr[i]; arr[i] = arr[min]; arr[min] = temp; //原来的第一个元素已经与下标为minPoint的元素交换了位置 //如果之前maxPoint指向的是第一个元素,那么需要将maxPoint重新指向array[minPoint] //因为现在array[minPoint]存放的才是之前第一个元素中的数据 if(max == i){ max = min; } } if(max != len - 1 - i){ //如果发现了更大的元素,与最后一个元素交换位置 temp = arr[len - 1 - i]; arr[len - 1 - i] = arr[max]; arr[max] = temp; } System.out.println("第" + (counter++) + "轮排序结果: " + Arrays.toString(arr)); } } }
SQL
UTF-8
233
2.828125
3
[]
no_license
-- Retrieves the roles -- Suitable for Firebird 3.0 and higher select trim(trailing from ROLE_NAME) as ROLE_NAME, COMMENTS from ( select RDB$ROLE_NAME as ROLE_NAME, RDB$DESCRIPTION as COMMENTS from RDB$ROLES ) roles
Java
UTF-8
223
2.828125
3
[]
no_license
package edu.java.intermediate.exercise1.creation.structural.decorator; public class Triangulo implements Forma{ @Override public void mostrar() { System.out.println("Se ha mostrado un triangulo"); } }
Java
UTF-8
1,259
3.921875
4
[]
no_license
package com.object; //부모 클래스, Super, base, Parent 클래스 class Parent{ String name="Taek"; String addr="here"; //생성자 Parent(){ System.out.println("Parent 생성자"); } String getName() { return name; } String getAddr() { return addr; } } //자식 클래스, sub, derived, child 클래스 public class Child extends Parent{ String email="wosl0205@daum.net"; //생성자 Child(){ System.out.println("Child 생성자"); } //Method Overriding : 상속받은 메소드 중 자식 클래스에 맞게 재정의 하는일 //리턴타입, 메소드 이름, 파라미터가 동일해야함 String getName() { return "택진"; } void callSuper() { System.out.println(super.getName()); } @Override String getAddr() { // TODO Auto-generated method stub return "요기"; } public static void main(String[] args) { Parent c=new Child(); System.out.println(c.getName()); System.out.println(c.getAddr()); //static 안에서는 this, super 키워드 사용불가 //형변환 Child c2 = (Child)c; c2.callSuper(); } }
Java
UTF-8
4,071
2.140625
2
[]
no_license
package com.smartschool.bean; import java.util.Date; public class ContactInfoBean { private long contactInfoId; private long studentId; private String firstContactNo; private String streetNoName1; private String city; private String state; private String country; private String zipCode; private String secondContactNo; private String streetNoName2; private String city2; private String state2; private String country2; private String zipCode2; private Date recCreatedDate; private long recCreatedById; private String recCreatedByName; private Date recUpdatedDate; private long recUpdatedById; private String recUpdatedByName; private boolean activeFlag; public ContactInfoBean() { } public ContactInfoBean(long contactInfoId) { this.contactInfoId = contactInfoId; } public long getContactInfoId() { return contactInfoId; } public void setContactInfoId(long contactInfoId) { this.contactInfoId = contactInfoId; } public long getStudentId() { return studentId; } public void setStudentId(long studentId) { this.studentId = studentId; } public String getFirstContactNo() { return firstContactNo; } public void setFirstContactNo(String firstContactNo) { this.firstContactNo = firstContactNo; } public String getStreetNoName1() { return streetNoName1; } public void setStreetNoName1(String streetNoName1) { this.streetNoName1 = streetNoName1; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getSecondContactNo() { return secondContactNo; } public void setSecondContactNo(String secondContactNo) { this.secondContactNo = secondContactNo; } public String getStreetNoName2() { return streetNoName2; } public void setStreetNoName2(String streetNoName2) { this.streetNoName2 = streetNoName2; } public String getCity2() { return city2; } public void setCity2(String city2) { this.city2 = city2; } public String getState2() { return state2; } public void setState2(String state2) { this.state2 = state2; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getZipCode() { return zipCode; } public void setZipCode(String zipCode) { this.zipCode = zipCode; } public String getCountry2() { return country2; } public void setCountry2(String country2) { this.country2 = country2; } public String getZipCode2() { return zipCode2; } public void setZipCode2(String zipCode2) { this.zipCode2 = zipCode2; } public Date getRecCreatedDate() { return recCreatedDate; } public void setRecCreatedDate(Date recCreatedDate) { this.recCreatedDate = recCreatedDate; } public long getRecCreatedById() { return recCreatedById; } public void setRecCreatedById(long recCreatedById) { this.recCreatedById = recCreatedById; } public String getRecCreatedByName() { return recCreatedByName; } public void setRecCreatedByName(String recCreatedByName) { this.recCreatedByName = recCreatedByName; } public Date getRecUpdatedDate() { return recUpdatedDate; } public void setRecUpdatedDate(Date recUpdatedDate) { this.recUpdatedDate = recUpdatedDate; } public long getRecUpdatedById() { return recUpdatedById; } public void setRecUpdatedById(long recUpdatedById) { this.recUpdatedById = recUpdatedById; } public String getRecUpdatedByName() { return recUpdatedByName; } public void setRecUpdatedByName(String recUpdatedByName) { this.recUpdatedByName = recUpdatedByName; } public boolean isActiveFlag() { return activeFlag; } public void setActiveFlag(boolean activeFlag) { this.activeFlag = activeFlag; } }
Java
UTF-8
549
1.992188
2
[]
no_license
package test.com.epam.create; import com.epam.geometry.create.PointCreator; import com.epam.geometry.exception.PointCreateException; import com.epam.geometry.util.Tags; import org.json.simple.JSONObject; import org.junit.Test; public class PointCreatorTest { @Test(expected = PointCreateException.class) public void createTest() throws PointCreateException{ JSONObject jsonObject = new JSONObject(); jsonObject.put(Tags.X,"1.2"); jsonObject.put(Tags.Y,"aj"); new PointCreator().create(jsonObject); } }
Markdown
UTF-8
1,502
2.921875
3
[ "MIT" ]
permissive
# Focal Length Analyzer Simple and quick project to get the focal length of images in a directory and it's subdirectories. Background was to check which focal length I most commonly work with and use this data point in finding a good suited lens for my travels. ## Usage ### IDE Set values in `CliConfig` and execute the `ApplicationRunner`-class. ### Compilation You can use a compiled version of this project via command line by executing: ``` java -jar focal-length-analyzer-1.0.jar -d DIRECTORY_TO_SCAN [-o OUTPUT_FILE] ``` #### -d Path to directory which should be scanned. All sub-directories will be scanned as well. - Example: `/usr/tmp/pictures` - Default value: *none* #### -o (optional) Output file. If no output file is defined the result will be written to the console - Example: `result.csv` - Default value: *none* #### -s (optional) Boolean flag if the focal lengths should be split by cameras. This option is useful if you're using multiple cameras but you're only interested in the files of one of them or want to compare the usage of the different cameras. - Example: `true` - Default value: `false` #### -ff (optional) Boolean flag to define if the focal lengths should be in 35mm film equivalent, by default they are not and therefor ignore the crop factor of your camera. This option is useful in case you want to compare focal lengths at a camera with a crop factor (e.g. APS-C) with the focal lengths of a full-frame one. - Example: `true` - Default value: `false`
Java
UTF-8
722
2.234375
2
[]
no_license
package com.wt.bean.table; /** * 地区表对应 island_package * @author sl * */ public class IslandPackageBean { private Integer id; private Integer areaId;//地区id private Integer islandId;//岛屿id private String title;//套餐名称 public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getAreaId() { return areaId; } public void setAreaId(Integer areaId) { this.areaId = areaId; } public Integer getIslandId() { return islandId; } public void setIslandId(Integer islandId) { this.islandId = islandId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
C++
UTF-8
1,150
3.1875
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> #include <queue> #include <string> using namespace std; int main() { // 행렬 입력받기 int n, m, i, j, p, q; scanf_s("%d %d", &n, &m); string temp; int before[51][51]; int after[51][51]; for (i = 0; i < n; i++) { cin >> temp; for (j = 0; j < m; j++) before[i][j] = temp[j] - '0'; } for (i = 0; i < n; i++) { cin >> temp; for (j = 0; j < m; j++) after[i][j] = temp[j] - '0'; } // 연산 -> 가지고 있는 행렬과 바꿔야하는 행렬을 비교했을 때 int res = 0; for (i = 0; i < n-2; i++) { for (j = 0; j < m-2; j++) { // 중심점을 기준으로 좌상단 값이 다르다면 행렬 뒤집기 if (before[i][j] != after[i][j]) { res++; for (p = 0; p < 3; p++) { for (q = 0; q < 3; q++) { before[i + p][j + q] = 1 - before[i + p][j + q]; } } } } } // 모든 연산이 끝났을 때 before과 after이 일치하지 않으면 -1 출력 for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { if (before[i][j] != after[i][j]) { printf("-1"); return 0; } } } printf("%d", res); return 0; }
C++
UTF-8
589
2.796875
3
[]
no_license
/********************************************************************* ** Author: Kendal Droddy ** Date: 9/13/18 *********************************************************************/ #ifndef STUDENT_HPP #define STUDENT_HPP #include <string> /********************************************************************* ** Box Class Declaration *********************************************************************/ class Student { private: std::string name; double score; public: Student(std::string, double); std::string getName(); double getScore(); }; #endif
C
UTF-8
8,690
2.78125
3
[]
no_license
//Projet de RP S5-2016 Nathan URBAIN , Marek Felsöci //Code source client #include "../include/q12_client.h" int main(int argc , char **argv) { int sockfd; socklen_t addrlgn; struct sockaddr_in6 dest; //Création du socket if((sockfd = socket(AF_INET6,SOCK_DGRAM,IPPROTO_UDP)) == -1) { perror("socket fail \n"); exit(EXIT_FAILURE); } //creation adresse destination dest.sin6_family = AF_INET6; dest.sin6_port = htons(atoi(argv[2])); addrlgn = sizeof(struct sockaddr_in6); if(inet_pton(AF_INET6, argv[1], &dest.sin6_addr) != 1) { perror("inet fail \n"); close(sockfd); exit(EXIT_FAILURE); } //Fichier unsigned char hash_type = 50; short int hash_lgn = strlen(argv[5])+1; char hash[strlen(argv[5])+1]; strcpy(hash , argv[5]); //client address unsigned char client_type=55; short int client_lgn = sizeof(dest.sin6_addr)+2; short int client_port =atoi(argv[2]); struct in6_addr client_addr = dest.sin6_addr; //Recupration du type de message cf figure 2 du sujet unsigned char msg_type; if(strcmp(argv[4], "put" ) ==0) { msg_type = 110; //type put } if (strcmp(argv[4] , "get") == 0) { msg_type = 112; // type get } //Creation de la longeur du buffeur acceuillant le message short int msg_lgn = 1+2+hash_lgn+1+2+client_lgn; int total_lgn = 1+2+msg_lgn; void* buf = malloc(total_lgn); //placement des différentes valeurs dans le buffeur memcpy(buf, &msg_type, sizeof(msg_type)); //type du message memcpy(buf+sizeof(msg_type), &msg_lgn , sizeof(msg_lgn)); // taille du message memcpy(buf+sizeof(msg_type)+sizeof(msg_lgn), &hash_type , sizeof(hash_type)); //type de hash memcpy(buf+sizeof(msg_type)+sizeof(msg_lgn)+sizeof(hash_type) , &hash_lgn , sizeof(hash_lgn)); // taille de hash memcpy(buf+sizeof(msg_type)+sizeof(msg_lgn)+sizeof(hash_type)+sizeof(hash_lgn), hash , sizeof(hash)); //hash memcpy(buf+sizeof(msg_type)+sizeof(msg_lgn)+sizeof(hash_type)+sizeof(hash_lgn)+sizeof(hash), &client_type , sizeof(client_type)); // type de client memcpy(buf+sizeof(msg_type)+sizeof(msg_lgn)+sizeof(hash_type)+sizeof(hash_lgn)+sizeof(hash)+sizeof(client_type), &client_lgn , sizeof(client_lgn)); // taille de client memcpy(buf+sizeof(msg_type)+sizeof(msg_lgn)+sizeof(hash_type)+sizeof(hash_lgn)+sizeof(hash)+sizeof(client_type)+sizeof(client_lgn), &client_port , sizeof(client_port)); //port du client memcpy(buf+sizeof(msg_type)+sizeof(msg_lgn)+sizeof(hash_type)+sizeof(hash_lgn)+sizeof(hash)+sizeof(client_type)+sizeof(client_lgn)+sizeof(client_port), & client_addr , sizeof(client_addr)); //adresse du client //Permet les testes pour a vérification de la bonne mise en place char pmsg_type; short int pmsg_lgn; char phash_type; short int phash_lgn; char phash[65]; char pclient_type; short int pclient_lgn; short int pclient_port; char * client = (char*)malloc(50); struct in6_addr pclient_addr; memcpy(&pmsg_type , buf , sizeof(pmsg_type)); //type message memcpy(&pmsg_lgn , buf+sizeof(msg_type),sizeof(pmsg_lgn)); //taille message memcpy(&phash_type , buf+sizeof(msg_type)+sizeof(msg_lgn), sizeof(phash_type)); //type hash memcpy(&phash_lgn , buf+sizeof(msg_type)+sizeof(msg_lgn)+sizeof(hash_type), sizeof(phash_lgn)); //taille hash memcpy(phash , buf+sizeof(msg_type)+sizeof(msg_lgn)+sizeof(hash_type)+sizeof(hash_lgn), sizeof(phash)); // hash memcpy(&pclient_type , buf+sizeof(msg_type)+sizeof(msg_lgn)+sizeof(hash_type)+sizeof(hash_lgn)+sizeof(hash) , sizeof(pclient_type)); // type client memcpy(&pclient_lgn , buf+sizeof(msg_type)+sizeof(msg_lgn)+sizeof(hash_type)+sizeof(hash_lgn)+sizeof(hash)+sizeof(client_type),sizeof(pclient_lgn)); // taille client memcpy(&pclient_port , buf+sizeof(msg_type)+sizeof(msg_lgn)+sizeof(hash_type)+sizeof(hash_lgn)+sizeof(hash)+sizeof(client_type)+sizeof(client_lgn), sizeof(pclient_port)); //port du client memcpy(&pclient_addr , buf+sizeof(msg_type)+sizeof(msg_lgn)+sizeof(hash_type)+sizeof(hash_lgn)+sizeof(hash)+sizeof(client_type)+sizeof(client_lgn)+sizeof(pclient_port), sizeof(pclient_addr)); //adresse du client //Affichage des différentes données pour verification printf("\nMessage à envoyer : \n"); printf("type msg : %u \n",pmsg_type); printf("longeur msg : %d \n",pmsg_lgn); printf("type hash : %u \n ", phash_type); printf("longeur hash : %d \n", phash_lgn); printf("hash : %s \n", phash); printf("type client : %u \n",pclient_type); printf("longuer client : %d \n",pclient_lgn); printf("port client : %d \n", pclient_port); printf("client : %s \n" , inet_ntop(AF_INET6 , &pclient_addr,client,sizeof(pclient_addr))); //envoi du message if (sendto(sockfd,buf, total_lgn, 0 , (struct sockaddr * ) &dest , addrlgn ) == -1 ) { perror("socket fail \n"); close(sockfd); exit(EXIT_FAILURE); } //descripteur int sockfd2; socklen_t addrlgn2; struct sockaddr_in6 my_addr; // adresse ipv4 //socket a creer if((sockfd2 = socket(AF_INET6,SOCK_DGRAM,IPPROTO_UDP)) == -1) { perror("socket fail \n"); exit(EXIT_FAILURE); } //initialisation de l'adresse local my_addr.sin6_family = AF_INET6; // domaine d'adresse my_addr.sin6_port = htons(atoi(argv[3])); //port my_addr.sin6_addr = in6addr_any; //on ecoute sur une adresse quelconque addrlgn2 = sizeof(struct sockaddr_in6); //association socket a l'adresse if (bind(sockfd2, (struct sockaddr *) &my_addr, addrlgn2)== -1) { perror("bind fail \n"); close(sockfd2); exit(EXIT_FAILURE); } if (!strcmp(argv[4],"put") || !strcmp(argv[4],"get")) { void* ack = malloc(total_lgn+1000); //recuperation de la chaine de caractère if(recvfrom(sockfd2,ack,total_lgn+1000 ,0 , (struct sockaddr *) &my_addr , &addrlgn2 ) == -1) { perror("recois fail \n"); close(sockfd2); exit(EXIT_FAILURE); } char rmsg_type; short int rmsg_lgn; char rhash_type ; short int rhash_lgn; char rhash[65]; char rclient_type; short int rclient_lgn; short int rclient_port ; struct in6_addr rclient_addr; memcpy(&rmsg_type, ack , sizeof(pmsg_type)); //type message memcpy(&rmsg_lgn , ack+sizeof(msg_type), sizeof(pmsg_lgn)); //taille message memcpy(&rhash_type, ack+sizeof(msg_type)+sizeof(msg_lgn), sizeof(phash_type)); //type hash memcpy(&rhash_lgn, ack+sizeof(msg_type)+sizeof(msg_lgn)+sizeof(hash_type),sizeof(phash_lgn)); //taille hash memcpy(rhash, ack+sizeof(msg_type)+sizeof(msg_lgn)+sizeof(hash_type)+sizeof(hash_lgn), sizeof(phash)); //hash memcpy(&rclient_type, ack+sizeof(msg_type)+sizeof(msg_lgn)+sizeof(hash_type)+sizeof(hash_lgn)+ sizeof(hash), sizeof(pclient_type)); //type client memcpy(&rclient_lgn,ack+sizeof(msg_type)+sizeof(msg_lgn)+sizeof(hash_type)+sizeof(hash_lgn)+ sizeof(hash) + sizeof(client_type), sizeof(pclient_lgn)); //taille client memcpy(&rclient_port,ack+sizeof(msg_type)+sizeof(msg_lgn)+sizeof(hash_type)+sizeof(hash_lgn)+ sizeof(hash) + sizeof(client_type)+sizeof(client_lgn) ,sizeof(pclient_port)); memcpy(&rclient_addr,ack+sizeof(msg_type)+sizeof(msg_lgn)+sizeof(hash_type)+sizeof(hash_lgn)+ sizeof(hash) + sizeof(client_type)+sizeof(client_lgn)+sizeof(client_port), sizeof(pclient_addr)); //Affichage des différentes données pour verification printf("\nReponse : \n"); printf("type msg : %u \n",rmsg_type); printf("longeur msg : %d \n",rmsg_lgn); printf("type hash : %u \n ", rhash_type); printf("longeur hash : %d \n", rhash_lgn); printf("hash : %s \n", rhash); printf("type client : %u \n",rclient_type); printf("longuer client : %d \n",rclient_lgn); printf("port client : %d \n", rclient_port); printf("client : %s \n" , inet_ntop(AF_INET6 , &rclient_addr,client,sizeof(rclient_addr))); int s = 21; while (rmsg_lgn > 89) { memcpy(&rclient_type , s+ack+sizeof(msg_type)+sizeof(msg_lgn)+sizeof(hash_type)+sizeof(hash_lgn)+sizeof(hash) , sizeof(pclient_type)); //type client memcpy(&rclient_lgn , s+ack+sizeof(msg_type)+sizeof(msg_lgn)+sizeof(hash_type)+sizeof(hash_lgn)+sizeof(hash)+sizeof(client_type), sizeof(pclient_lgn)); //taille client memcpy(&rclient_port, s+ack+sizeof(msg_type)+sizeof(msg_lgn)+sizeof(hash_type)+sizeof(hash_lgn)+sizeof(hash)+sizeof(client_type)+sizeof(client_lgn), sizeof(pclient_port)); //port client memcpy(&rclient_addr,s+ack+sizeof(msg_type)+sizeof(msg_lgn)+sizeof(hash_type)+sizeof(hash_lgn)+sizeof(hash)+sizeof(client_type)+sizeof(client_lgn)+sizeof(client_port),sizeof(pclient_addr)); //adresse client s+=21; rmsg_lgn-=21; printf("\n type client : %u \n" , rclient_type); printf("longeur client : %d \n" , rclient_lgn); printf("port client : %d \n " , rclient_port); printf("client : %s \n" , inet_ntop(AF_INET6 , &rclient_addr,client,sizeof(rclient_addr))); } } return 0; }
C#
UTF-8
1,491
2.9375
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using Shared.Contracts; namespace Shared.Domains { public static class DefaultEvent { public static IEvent<T> Create<T>(T result = null, IEnumerable<T> results = null) where T : class { return new DefaultEvent<T>(result, results); } public static IEvent<T> Create<T>(bool isSuccessful, Exception exception = null, T result = null, IEnumerable<T> results = null) where T : class { return new DefaultEvent<T>(isSuccessful, exception, result, results); } } public class DefaultEvent<T> : IEvent<T> where T : class { public DefaultEvent(T result = null, IEnumerable<T> results = null) { Result = result; Results = results; IsSuccessful = true; } public DefaultEvent(bool isSuccessful, Exception exception = null, T result = null, IEnumerable<T> results = null) { Results = results; Result = result; IsSuccessful = isSuccessful; Exception = exception; } public IEnumerable<T> Results { get; } public T Result { get; } public bool IsSuccessful { get; } public Exception Exception { get; } object IEvent.Result { get => Result; } IEnumerable<object> IEvent.Results => Results.Select(result => (object)result); } }
Markdown
UTF-8
698
2.65625
3
[ "MIT" ]
permissive
--- title: "Users administration" permalink: /en/admin-users excerpt: "Users administration" redirect_from: - /theme-setup/ --- {% include base_path %} Click on the users menu on the left side to open the users administration section Then click on "New" button |![](/en/admin-users/menu.png)| |:--:| |*Users menu*| Enter the username (the user for login) The password The name, this will be showed in the call status and left panel And select the profile from: * ROLE_STUDIO, Studio users can make calls * ROLE_JOURNALIST, Journalists users can receive calls from Studio * ROLE_ADMIN, only has access to administration section. |![](/en/admin-users/new.png)| |:--:| |*Create a new user*|
Java
UTF-8
5,789
2.84375
3
[]
no_license
package mps.redundant.dispatcher; import mps.redundant.Config; import mps.redundant.gui.MonitorGUI; import mps.redundant.monitor.Monitor; import mps.redundant.server.IMpsServer; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import java.util.ArrayList; import java.util.HashMap; import javax.swing.JFrame; /** * Der Dispatcher verteilt die Anfragen des Clients Round Robin an die * MPSServerprozesse. */ public class Dispatcher implements IDispatcher { public Registry dispatcherRegistry; public HashMap<String, IMpsServer> serverList; // Hilfsvariable fuer die Round Robin Aufgabenverteilung public int roundRobinCounter = 0; private static Dispatcher dispatcher; /** * @param dispatcherPort * @throws RemoteException * Konstruktor des Dispatchers, welcher eine neue Registry * erzeugt sowie eine HashMap fuer die MpsServer */ public Dispatcher(int dispatcherPort) throws RemoteException { dispatcherRegistry = LocateRegistry .createRegistry(dispatcherPort); this.serverList = new HashMap<String, IMpsServer>(); } /** * @param dispatcherPort * @return * @throws RemoteException * * Erzeugt ein Dispatcher Objekt und exportiert es nach außen um * eingehende Aufrufe wahrnehmen zu koennen. Außerdem wird es an * die in der Config festgelegte Referenz gebunden. */ public static Dispatcher create(int dispatcherPort) throws RemoteException { dispatcher = new Dispatcher(dispatcherPort); IDispatcher stub = (IDispatcher) UnicastRemoteObject.exportObject( dispatcher, 0); dispatcher.dispatcherRegistry.rebind(Config.DISPATCHER_NAME, stub); return dispatcher; } /** * @return * @throws RemoteException * | InterruptedException * * Gibt einen Server zurueck, indem er getNextActiveServer() * aufruft. Falls alle Server deaktiviert sind, wartet er und * versucht es im 5 Sekunden Takt immer wieder einen * erreichbaren Server zu bekommen. */ @Override public synchronized IMpsServer getRemoteServerInstance() throws RemoteException { IMpsServer server = null; try { server = getNextActiveServer(); System.out.println("Server: " + server.getName() + " uebernimmt die Anfrage."); while (server == null) { Thread.sleep(5000); server = getNextActiveServer(); } } catch (RemoteException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } return server; } /** * @return * @throws RemoteException * Holt sich mit Round Robin den jeweils anderen Server wenn * beide aktiv sind sonst immer den selben. Erhoeht die * jeweilige Anfragenanzahl in der GUI. */ private IMpsServer getNextActiveServer() throws RemoteException { roundRobinCounter %= serverList.size(); IMpsServer server; while (roundRobinCounter < serverList.size()) { ArrayList<IMpsServer> servers = new ArrayList<IMpsServer>( serverList.values()); server = servers.get(roundRobinCounter); if (!server.isDeaktiviert()) { if (server.getName().equals(Config.HAWMPS1_NAME)) { MonitorGUI.getInstance().erhoeheAnfragenVonMPS1(); } if (server.getName().equals(Config.HAWMPS2_NAME)) { MonitorGUI.getInstance().erhoeheAnfragenVonMPS2(); } roundRobinCounter++; return server; } roundRobinCounter++; if (roundRobinCounter == serverList.size()) roundRobinCounter = 0; } return null; } /** * @param serverInstance * @throws RemoteException * * Fuegt den lebendigen Server unter seinem Namen der HashMap * hinzu falls noch nicht enthalten. */ public synchronized void alive(IMpsServer serverInstance) throws RemoteException { if (!serverList.values().contains(serverInstance)) { serverList.put(serverInstance.getName(), serverInstance); } } /** * @param serverName * * Entfernt den "toten" Server aus der HashMap */ public synchronized void notAlive(String serverName) { if (serverList.containsKey(serverName)) { serverList.remove(serverName); } } /** * @param servername * @param b * * Deaktiviert den Server in der HashMap (setzt Boolean auf true) */ public void deaktiviereServerInstanz(String servername, boolean b) { try { if (serverList.containsKey(servername)) { serverList.get(servername).setisDeaktiviert(b); } } catch (RemoteException e) { e.printStackTrace(); } } /** * @param servername * @return * * Prueft ob ein Server in der HashMap ist, also ob dieser nicht * offline ist. */ public boolean isServerOnline(String servername) { if (serverList.containsKey(servername)) { return true; } return false; } public static void main(String[] args) throws RemoteException, InterruptedException, NotBoundException { // if (System.getSecurityManager() == null) { // System.setSecurityManager(new SecurityManager()); // } // try { if (args.length == 1) { Dispatcher dispatcher = Dispatcher .create(Integer.parseInt(args[0])); Monitor.create(dispatcher); JFrame frame = new JFrame("MonitorGUI"); MonitorGUI x = new MonitorGUI(frame, dispatcher); frame.setContentPane(x.monitorGUI); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setResizable(false); frame.setVisible(true); } else System.err.println("please specify your port as parameters"); // } catch (Exception e) { // System.err.println("Dispatcher exception:"); // e.printStackTrace(); // } } }
JavaScript
UTF-8
2,659
3.5
4
[]
no_license
$(document).ready(function() { makePlot(); }); function makePlot() { d3.csv("data.csv").then(function(data) { console.log(data); // make the plot // STEP 1: set up the chart var svgWidth = 960; var svgHeight = 500; var margin = { top: 20, right: 40, bottom: 60, left: 50 }; // get the area for the viz itself var chart_width = svgWidth - margin.left - margin.right; var chart_height = svgHeight - margin.top - margin.bottom; // STEP 2: CREATE THE SVG (if it doesn't exist already) var svg = d3.select("#scatter") .append("svg") .attr("width", svgWidth) .attr("height", svgHeight); var chartGroup = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); // STEP 3: PREPARE THE DATA var timeParser = d3.timeParse("%d-%b"); data.forEach(function(row) { row.date = timeParser(row.date); //cast the date string to a datetime object data type }); // STEP 4: CREATE SCALES var col1_max = d3.max(data, d => d.morning); var col2_max = d3.max(data, d => d.evening); var total_max = d3.max([col1_max, col2_max]); var xScale = d3.scaleTime() .domain(d3.extent(data, d => d.date)) .range([0, chart_width]); var yScale = d3.scaleLinear() .domain([0, total_max]) .range([chart_height, 0]); // STEP 5: CREATE THE AXES var leftAxis = d3.axisLeft(yScale); var bottomAxis = d3.axisBottom(xScale).tickFormat(d3.timeFormat("%d-%b")); // cast the datetime back to a string for display (only for time series) chartGroup.append("g") .attr("transform", `translate(0, ${chart_height})`) .call(bottomAxis); chartGroup.append("g") .call(leftAxis); // STEP 6: CREATE THE GRAPH // for line graphs - create line generator and then draw the line var line_gen1 = d3.line() .x(d => xScale(d.date)) .y(d => yScale(d.morning)); var line_gen2 = d3.line() .x(d => xScale(d.date)) .y(d => yScale(d.evening)); chartGroup.append("path") .attr("d", line_gen1(data)) .classed("line green", true); chartGroup.append("path") .attr("d", line_gen2(data)) .classed("line orange", true); }).catch(function(error) { alert("YOU BROKE SOMETHING. JK. It was Aakash."); console.log(error); }); }
Java
UTF-8
893
3.40625
3
[]
no_license
package LinkedCollection; /** * Created by Alexander on 14.12.2014. */ public class App { public static void main( String[] args ) { LinkedList linkedList = new LinkedList(); linkedList.add("first something"); linkedList.add("second something"); linkedList.add("i don't know something"); linkedList.add("whatever something"); linkedList.add("maybe last something"); linkedList.remove("first something"); System.out.println("linked list size is : " + linkedList.size()); //System.out.println("linked list contains 'whatever': " + linkedList.contains("whatever")); for(int i =0; i < linkedList.size(); i++ ){ System.out.println(linkedList.get(i)); } //for(Object element : linkedList.toArray()) { // System.out.println("to array : " + element); //} } }
Swift
UTF-8
5,153
3.625
4
[]
no_license
// // Question Set.swift // TrueFalseStarter // // Created by Siddharth Doshi on 22/12/16. // Copyright © 2016 Treehouse. All rights reserved. // //--------------------------------------------------------------------- ///////////////////////// // Question Set Format // ///////////////////////// /* // Question <Question Number> // --------------- class Que<Question Number>: Question { override init() { super.init() que = "" op1 = "" op2 = "" op3 = "" op4 = "" ans = <Answer Variable> } } */ // ## Parent Class for all Question Set ## class Question { var que = "" var op1 = "" var op2 = "" var op3 = "" var op4 = "" var ans = "" } // ** Previous Questions ** // Previous Question 1 // --------------- class OldQue1: Question { override init() { super.init() que = "Only female koalas can whistle" op1 = "True" op2 = "False" op3 = "" op4 = "" ans = op2 } } // Previous Question 2 // --------------- class OldQue2: Question { override init() { super.init() que = "Blue whales are technically whales" op1 = "True" op2 = "False" op3 = "" op4 = "" ans = op1 } } // Previous Question 3 // --------------- class OldQue3: Question { override init() { super.init() que = "Camels are cannibalistic" op1 = "True" op2 = "False" op3 = "" op4 = "" ans = op2 } } // Previous Question 4 // --------------- class OldQue4: Question { override init() { super.init() que = "All ducks are birds" op1 = "True" op2 = "False" op3 = "" op4 = "" ans = op1 } } // Question 1 // --------------- class Que1: Question { override init() { super.init() que = "This was the only US President to serve more than two consecutive terms." op1 = "George Washington" op2 = "Franklin D. Roosevelt" op3 = "Woodrow Wilson" op4 = "Andrew Jackson" ans = op2 } } // Question 2 // --------------- class Que2: Question { override init() { super.init() que = "Which of the following countries has the most residents?" op1 = "Nigeria" op2 = "Russia" op3 = "Iran" op4 = "Vietnam" ans = op1 } } // Question 3 // --------------- class Que3: Question { override init() { super.init() que = "In what year was the United Nations founded?" op1 = "1918" op2 = "1919" op3 = "1945" op4 = "1954" ans = op3 } } // Question 4 // --------------- class Que4: Question { override init() { super.init() que = "The Titanic departed from the United Kingdom, where was it supposed to arrive?" op1 = "Paris" op2 = "Washington D.C." op3 = "New York City" op4 = "Boston" ans = op3 } } // Question 5 // --------------- class Que5: Question { override init() { super.init() que = "Which nation produces the most oil?" op1 = "Iran" op2 = "Iraq" op3 = "Brazil" op4 = "Canada" ans = op4 } } // Question 6 // --------------- class Que6: Question { override init() { super.init() que = "Which country has most recently won consecutive World Cups in Soccer?" op1 = "Italy" op2 = "Brazil" op3 = "Argetina" op4 = "Spain" ans = op2 } } // Question 7 // --------------- class Que7: Question { override init() { super.init() que = "Which of the following rivers is longest?" op1 = "Yangtze" op2 = "Mississippi" op3 = "Congo" op4 = "Mekong" ans = op2 } } // Question 8 // --------------- class Que8: Question { override init() { super.init() que = "Which city is the oldest?" op1 = "Mexico City" op2 = "Cape Town" op3 = "San Juan" op4 = "Sydney" ans = op1 } } // Question 9 // --------------- class Que9: Question { override init() { super.init() que = "Which country was the first to allow women to vote in national elections?" op1 = "Poland" op2 = "United States" op3 = "Sweden" op4 = "Senegal" ans = op1 } } // Question 10 // --------------- class Que10: Question { override init() { super.init() que = "Which of these countries won the most medals in the 2012 Summer Games?" op1 = "France" op2 = "Germany" op3 = "Japan" op4 = "Great Britian" ans = op4 } }
Python
UTF-8
245
3.734375
4
[]
no_license
#capitalize the string str='python', 'datascience', 'amazon web services' s3='|' s4=s3.join(str) print(s4) #string slicing x='COMPUTER' x1=x[0:4] print(x1) x2=x[0: :2] print(x2) x3=x[3:] print(x3) x4=x[:-2] print(x4) x5=x[-5:-7:-1] print(x5)
Java
UTF-8
2,600
2.234375
2
[]
no_license
package br.com.isalvati.sistemaacademico.services; import br.com.isalvati.sistemaacademico.PostgresqlContainer; import br.com.isalvati.sistemaacademico.UtilTest; import br.com.isalvati.sistemaacademico.entities.SystemUserEntity; import br.com.isalvati.sistemaacademico.exception.SistemaAcademicoException; import org.junit.Assert; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import org.testcontainers.containers.PostgreSQLContainer; import javax.transaction.Transactional; @RunWith(SpringRunner.class) @SpringBootTest @ContextConfiguration(initializers = {PostgresqlContainer.Initializer.class}) public class SystemUserEntityServiceTest { @ClassRule public static PostgreSQLContainer postgreSQLContainer = PostgresqlContainer.getInstance(); @Autowired private SystemUserService systemUserService; private SystemUserEntity systemUser; @Before public void setUp() { systemUser = UtilTest.createSystemUser(); } @Test @Transactional public void findByUsername() throws SistemaAcademicoException { systemUserService.save(systemUser); SystemUserEntity user = systemUserService.findByUsername("SA-ADMIN"); Assert.assertNotNull(user); } @Test @Transactional public void create() throws SistemaAcademicoException { SystemUserEntity usr = systemUserService.save(systemUser); Assert.assertNotNull(usr); System.out.println(" INSERT INTO academico.system_user (username, password, app_key, description, environment)\n" + "VALUES ('" + usr.getUsername() + "', " + " decode('" + bytesToHex(usr.getPassword()) + "', 'hex'),\n" + " decode('" + bytesToHex(usr.getAppKey()) + "', 'hex'),\n" + " '" + usr.getDescription() + "', '" + usr.getEnvironment().name() + "');\n"); } private final static char[] hexArray = "0123456789ABCDEF".toCharArray(); private static String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for (int j = 0; j < bytes.length; j++) { int v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } }
JavaScript
UTF-8
796
3.9375
4
[]
no_license
//high order array methods const todos = [ { id: 1, text: "Take out trash", isCompleted: true, }, { id: 2, text: "Do laundry", isCompleted: true, }, { id: 3, text: "Load dishwasher", isCompleted: false, }, ] // forEach //todos.forEach(function (todo) { // console.log(todo.text) //}) // map //const todoText = todos.map(function (todo) { // return todo.text // }) //console.log(todoText) // filter //const todoCompleted = todos.filter(function (todo) { // return todo.isCompleted === true //}) //console.log(todoCompleted) // filter and map const todoCompleted = todos .filter(function (todo) { return todo.isCompleted === true }) .map(function (todo) { return todo.text }) console.log(todoCompleted)
C#
UTF-8
791
3.328125
3
[ "MIT" ]
permissive
namespace TaskEmployee { class Employee { public string Name; public int Id; public string Position; public double Salary; public Employee() { Name = "Joe Doe"; Id = 1; Position = "Boss"; Salary = 100; } public Employee(string name, int id, string position, double salary) { Name = name; Id = id; Position = position; Salary = salary; } // Copy constructor public Employee(Employee employee) { Name = employee.Name; Id = employee.Id; Position = employee.Position; Salary = employee.Salary; } // Methods } }
Java
UTF-8
2,681
3.0625
3
[]
no_license
/* Name: Beier (Benjamin) Liu Date: 5/17/2018 Remark: */ package Percolation; import edu.princeton.cs.algs4.StdRandom; import edu.princeton.cs.algs4.StdStats; import edu.princeton.cs.algs4.WeightedQuickUnionUF; import java.util.logging.Logger; import java.util.logging.Level; import java.text.MessageFormat; /*=================================================================================================== File content: A PercolationStats Class ===================================================================================================*/ public class PercolationStats { private static final Logger LOGGER = Logger.getLogger(PercolationStats.class.getName()); private double[] threshold; // perform trials independent experiments on an n-by-n grid public PercolationStats(int n, int trials) { // Preparation Phrase int openCount, row, col; if(n<=0||trials<=0){ LOGGER.severe("Arguement out of bound"); throw new IllegalArgumentException("Arguement out of bound"); } threshold=new double[trials]; openCount=0; // Handling Phrase for (int i=0; i<trials; i++){ Percolation pc = new Percolation(n); do{ row=StdRandom.uniform(1, n+1); col=StdRandom.uniform(1, n+1); if (pc.isOpen(row, col)){ continue; } pc.open(row, col); openCount++; } while (!pc.percolates()); threshold[i]=(double) openCount/(n*n); openCount=0; LOGGER.finest(MessageFormat.format("threshold[{}]={}\n", i, threshold[i])); } // Checking Phrase } // sample mean of percolation threshold public double mean() { // Handling Phrase return StdStats.mean(threshold); } // sample standard deviation of percolation threshold public double stddev() { // Handling Phrase return StdStats.stddev(threshold); } // low endpoint of 95% confidence interval public double confidenceLo(){ // Handling Phrase return mean()-1.96*stddev()/Math.sqrt(threshold.length); } // high endpoint of 95% confidence interval public double confidenceHi(){ // Handling Phrase return mean()+1.96*stddev()/Math.sqrt(threshold.length); } // test client (described below) public static void main(String[] args){ // Preparation phrase PercolationStats pcs=new PercolationStats(Integer.parseInt(args[0]), Integer.parseInt(args[1])); // Handling Phrase LOGGER.setLevel(Level.INFO); LOGGER.info(MessageFormat.format("mean: ={}\n", pcs.mean())); LOGGER.info(MessageFormat.format("stddev: ={}\n", pcs.stddev())); LOGGER.info(MessageFormat.format("95%% confidence inteval: ({}, {})", pcs.confidenceLo(), pcs.confidenceHi())); } }
C++
UTF-8
403
3.71875
4
[]
no_license
/* Un número es divible entre otro numero */ #include <iostream> using namespace std; int main() { int a,b; cout<<"Ingrese un numero "<<endl; cin>>a; cout<<"Ingrese un numero "<<endl; cin>>b; if (a%b==0) { cout<<"Su numero es divisible entre otro numero"; } else { cout<<"Su numero no es divisible entre otro numero"; } return 0; }
Python
UTF-8
1,111
3.34375
3
[]
no_license
class Container: def __init__(self): self.content = [] def add(self, value): self.content.append(value) def items(self, identifier=None, content=None, priority=None): if identifier: return [value for value in self.content if value.identifier == identifier] elif content: return [value for value in self.content if value.content == content] elif priority: return [value for value in self.content if value.priority == priority] else: return [value for value in self.content] def values(self, identifier=None): return [value.content for value in self.items(identifier)] def count(self, identifier): return len([value for value in self.content if value.identifier == identifier]) def get_identifier(self, content): return str(*self.items(content=content)) def get_lexeme(self, content): return self.items(content=content)[0] def get_content(self, identifier): return [value.content for value in self.content if str(value) == identifier][0]
C++
UTF-8
1,155
3.15625
3
[]
no_license
// =============== BEGIN ASSESSMENT HEADER ================ /// @file User.h /// @brief assn4 /// /// @author Samuel Rufer [srufe001@ucr.edu] /// @date November 12, 2014 /// /// @par Plagiarism Section /// I hereby certify that I have not received assistance on this assignment, /// or used code, from ANY outside source other than the instruction team. // ================== END ASSESSMENT HEADER =============== #ifndef __USER_H__ #define __USER_H__ #include<string> using namespace std; class User { private: string username; string password; public: //creates a user with empty name and password. User(); //creates a user with given username and password. User(const string& uname, const string& pass); //returns the username string get_username() const; //returns true if the stored username/password matches with the parameters. //Otherwise, return false //Returns false if uname parameter is an empty string, because a User //object with empty username/password can exist bool check(const string& uname, const string& pass) const; //sets a nwe password void set_password(const string& newpass); }; #endif
JavaScript
UTF-8
5,580
3.171875
3
[]
no_license
var map; var toronto = new google.maps.LatLng(43.6532, -79.3832); var userLocation; var browserSupportFlag = new Boolean(); function initialize() { // Creating an infoWindow var; var marker; var infoWindow; // Creating an instance of a Google Map map = new google.maps.Map(document.getElementById('map'), { zoom: 12, center:userLocation }); //Checking in the device support gelocation using the reco HTML 5 version if(navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { var pos = { lat: position.coords.latitude, lng: position.coords.longitude }; // set the map center to user's position and add a red marker map.setCenter(pos); addMarker(pos, map); }); } else { handleNoGeolocation(flase, infoWindow, map.getCenter(), map); } function handleNoGeolocation(browserHasGeolocation, infoWindow, pos, map) { // Assigning the infoWindow var and letting the user knwo that their browser // doesn't support this service, and add a red marker infoWindow = new google.maps.InfoWindow({map: map}); infoWindow.setPosition(pos); infoWindow.setContent(browserHasGeolocation ? 'Error: The Geolocation service failed.' : 'Error: Your browser doesn\'t support geolocation.'); addMarker(pos, map); } // Add marker function function addMarker(location, map) { console.log(location) marker = new google.maps.Marker({ position: location, animation: google.maps.Animation.BOUNCE, map: map, draggable: true, icon: 'http://maps.google.com/mapfiles/ms/icons/red-dot.png' }); updateLatLngOnForm(marker); } // Add the event listener to mvoe the red marker google.maps.event.addListener(map, 'click', function(event) { // Setting the current marker, which is scoped to this function, to null marker.setMap(null); // Adding a new marker at the location where the click occured addMarker(event.latLng, map); // Pan to the new marker to the new marker map.panTo(event.latLng); }); // Function to locate the lat and long on the form function updateLatLngOnForm(currentMarker){ $("#lat").val(currentMarker.position.lat().toPrecision(5)); $("#long").val(currentMarker.position.lng().toPrecision(5)); } function initAutocomplete() { var searchInput = document.getElementsByClassName("search-input")[1]; var searchBox = new google.maps.places.SearchBox(searchInput); var newTrail = document.getElementsByClassName("search-input")[0]; var newTrailSearch = new google.maps.places.SearchBox(newTrail); function placeFind(places, location) { places.forEach(function(place) { location = {lat:place.geometry.location.lat() , lng:place.geometry.location.lng() } }); if (places.length == 0) { return; } // remove red marker, so that there is only one on the page marker.setMap(null); // Move marker addMarker(location, map); // Pan to the new marker to the new marker map.panTo(location); } map.addListener('bounds_changed', function() { newTrailSearch.setBounds(map.getBounds()); searchBox.setBounds(map.getBounds()); }); newTrailSearch.addListener('places_changed', function() { var places = newTrailSearch.getPlaces(); var location; placeFind(places, location); }); searchBox.addListener('places_changed', function() { var places = searchBox.getPlaces(); var location; placeFind(places, location); }); } initAutocomplete(location, map); } function createTrailMaker(trails){ //Turning the JSON object from the model to an array var trailArray = $(trails).toArray(); // This function adds a yellow marker and the infoWindow for each trail var addBlueMarker = function(trail, map) { var latLng = {lat: trail.lat, lng: trail.long} var marker = new google.maps.Marker({ position: latLng, map: map, draggable: false, title: trail.trail_name, icon: 'http://maps.google.com/mapfiles/ms/icons/yellow-dot.png' }); var infoWindow = new google.maps.InfoWindow({ content: "<h3 class='-window-title'>" + trail.trail_name + "</h3><br/>" + trail.description + "<h3 class='-window-subheads'>Review:</h3> " + trail.review + "<h3 class='-window-subheads'>Reviewed by user:</h3> " + trail.username }); // adds an event listener to open the infoWindow on click marker.addListener('mouseover', function() { infoWindow.open(map, marker); }); // adds a listener to close the infoWindow when the mouse moves off of it marker.addListener('mouseout', function() { infoWindow.close(map, marker); }); } // clearing out div $("#trails-near-you").html(""); // Loop through the array and call addBlueMaker function for each trail in the array for(var i = 0; i < trailArray.length; i++){ addBlueMarker(trailArray[i], map); $('<li><a href="/trails/'+trailArray[i].id+'">'+trails[i].trail_name+'</a></li>').appendTo("#trails-near-you"); } } // Event listeners to load the map and markers google.maps.event.addDomListener(window, 'load', function() { initialize(); // initAutocomplete(); // using AXAJ to grab the data from the router and pass it to createTrailMaker function $.getJSON("/trails", function(data) { createTrailMaker(data); }); });
Java
UTF-8
480
2.109375
2
[ "Apache-2.0" ]
permissive
package com.hs.mail.imap; import org.springframework.dao.DataAccessException; public class UnsupportedRightException extends DataAccessException { private static final long serialVersionUID = 1079894029366919256L; private char unsupportedRight; public UnsupportedRightException(char right) { super("Unsupported right flag '"+ right +"'."); this.unsupportedRight = right; } public char getUnsupportedRight() { return unsupportedRight; } }
SQL
UTF-8
1,427
3.5625
4
[]
no_license
-- auto gen by george 2017-12-06 15:25:17 DROP VIEW IF EXISTS v_player_online; CREATE OR REPLACE VIEW "v_player_online" AS SELECT s.id, s.username, s.real_name, s.login_time, s.login_ip, s.login_ip_dict_code, s.last_active_time, s.use_line, s.last_login_time, s.last_login_ip, s.last_login_ip_dict_code, s.total_online_time, string_agg(((pgl.game_id)::character varying)::text, ','::text) AS gameids, string_agg(((pgl.api_id)::character varying)::text, ','::text) AS apiids, s.session_key, u.wallet_balance, u.freezing_funds_balance, u.rank_id, u.channel_terminal, s.terminal, u.user_agent_id FROM ((user_player u JOIN sys_user s ON ((s.id = u.id))) LEFT JOIN player_game_log pgl ON (((pgl.user_id = s.id) AND ((pgl.session_key)::text = (s.session_key)::text)))) WHERE ((s.session_key IS NOT NULL) AND ((s.login_time > s.last_logout_time) OR (s.last_logout_time IS NULL)) AND (s.last_active_time > (now() - '00:30:00'::interval))) GROUP BY s.id, s.username, s.real_name, s.login_time, s.login_ip, s.login_ip_dict_code, s.last_active_time, s.use_line, s.last_login_time, s.last_login_ip, s.last_login_ip_dict_code, s.total_online_time, s.session_key, u.wallet_balance, u.freezing_funds_balance, u.rank_id, u.channel_terminal, s.terminal,u.user_agent_id; COMMENT ON VIEW "v_player_online" IS '在线玩家视图 edit by linsen';