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
SQL
UTF-8
265
3.890625
4
[]
no_license
SELECT * FROM (SELECT EmployeeID, FirstName, LastName, Salary, (DENSE_RANK() OVER(PARTITION BY Salary ORDER BY EmployeeID)) AS [Rank] FROM Employees WHERE Salary >= 10000 AND Salary <= 50000 ) AS temp WHERE [Rank] = 2 ORDER By Salary DESC
Python
UTF-8
2,034
3.5625
4
[]
no_license
from typing import Iterator, List def first(puzzle_input: Iterator[str]) -> int: counts = find_jolt_diff_counts(int(n.strip()) for n in puzzle_input) return counts[0] * counts[2] def second(puzzle_input: Iterator[str]) -> int: return count_arrangements(int(n.strip()) for n in puzzle_input) def find_jolt_diff_counts(adapters: List[int]) -> List[int]: """Get the count of jolt differences (1, 2, 3) when using all the adapters.""" nums = sorted(adapters) counts = [0, 0, 0] curr_j = 0 for n in nums: diff = n - curr_j if diff > 3: raise ValueError(f"No valid adapter found for joltage {curr_j}") counts[diff - 1] += 1 curr_j = n # The device's joltage is 3j more than the last adapter counts[2] += 1 return counts def count_arrangements(adapters: List[int]) -> int: """ Count all the arrangements This is a dynamic programming solution, as the count of possible arrangements for an adapter of value n, is the sum of the counts for the values: n-1, n-2, n-3. """ nums = sorted(adapters) # We could keep an array of counts for all the possible values so far, but this is more # memory efficient as we only ever need to keep the values for the previous three joltages count1 = 0 count2 = 0 count3 = 0 # n is the joltage for count3, there are count3 ways to arrange adapters to have a joltage of n n = 0 for curr in nums: # Some adapter values are missing, so we shift the counts until our shifted values # are right before our desired joltage while n < curr - 1: n += 1 # shift to the left count1 = count2 count2 = count3 count3 = 0 tmp = count1 + count2 + count3 count1 = count2 count2 = count3 count3 = tmp # For joltages under 3, you can use the adapter directly if curr <= 3: count3 += 1 n = curr return count3
Java
UTF-8
7,762
1.914063
2
[]
no_license
package uk.ac.tees.aad.W9299136; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.google.firebase.storage.FirebaseStorage; import org.jetbrains.annotations.NotNull; import java.sql.Ref; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import de.hdodenhof.circleimageview.CircleImageView; import uk.ac.tees.aad.W9299136.Utills.Common; import uk.ac.tees.aad.W9299136.Utills.Message; import uk.ac.tees.aad.W9299136.Utills.RecyclerViewDiscussionAdapter; import uk.ac.tees.aad.W9299136.Utills.User; public class DiscussionActivity extends AppCompatActivity { FirebaseAuth mAuth; FirebaseUser mUSer; RecyclerView recyclerView; EditText edSms; ImageView imageViewSend; DatabaseReference mRef; FirebaseUser mUser; DatabaseReference mUserRef, notification; CircleImageView profileImage; User user; List<Message> messageList; RecyclerViewDiscussionAdapter adapter; ImageView back; List<User> userList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_discussion); InitVariable(); imageViewSend.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { sendMessage(); } }); back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); LoadMessages(); LoadMyProfile(); LoadAllUserForNotification(); } private void InitVariable() { mAuth = FirebaseAuth.getInstance(); mUSer = mAuth.getCurrentUser(); recyclerView = findViewById(R.id.recyclerView); recyclerView.setLayoutManager(new LinearLayoutManager(this)); messageList = new ArrayList<>(); edSms = findViewById(R.id.edSms); back = findViewById(R.id.imageView); imageViewSend = findViewById(R.id.ImageViewSend); mRef = FirebaseDatabase.getInstance().getReference().child("Discussion"); mAuth = FirebaseAuth.getInstance(); mUser = mAuth.getCurrentUser(); mUserRef = FirebaseDatabase.getInstance().getReference().child("Users"); notification = FirebaseDatabase.getInstance().getReference().child("Notification"); userList = new ArrayList<>(); } private void LoadMyProfile() { mUserRef.child(mUser.getUid()).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull @NotNull DataSnapshot snapshot) { if (snapshot.exists()) { user = snapshot.getValue(User.class); Common.user = user; } } @Override public void onCancelled(@NonNull @NotNull DatabaseError error) { } }); } private void LoadAllUserForNotification() { mRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull @NotNull DataSnapshot snapshot) { userList = new ArrayList<>(); for (DataSnapshot snapshot1 : snapshot.getChildren()) { User u = snapshot1.getValue(User.class); userList.add(u); } } @Override public void onCancelled(@NonNull @NotNull DatabaseError error) { } }); } private void LoadMessages() { mRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull @NotNull DataSnapshot snapshot) { messageList = new ArrayList<>(); if (snapshot.exists()) { for (DataSnapshot snapshot1 : snapshot.getChildren()) { Message message = snapshot1.getValue(Message.class); messageList.add(message); } adapter = new RecyclerViewDiscussionAdapter(messageList, DiscussionActivity.this); recyclerView.setAdapter(adapter); } } @Override public void onCancelled(@NonNull @NotNull DatabaseError error) { } }); } private void sendMessage() { String message = edSms.getText().toString(); if (message.isEmpty()) { Toast.makeText(this, "Select Message", Toast.LENGTH_SHORT).show(); } else { if (user != null) { Date date = Calendar.getInstance().getTime(); DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); String today = formatter.format(date); String key = mRef.push().getKey().toString(); HashMap hashMap = new HashMap(); hashMap.put("message", message); hashMap.put("key", key); hashMap.put("userID", mUSer.getUid()); hashMap.put("date", today); hashMap.put("username", user.getUsername()); mRef.child(key).updateChildren(hashMap).addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull @NotNull Task task) { if (task.isSuccessful()) { edSms.setText(null); sendNotification(key, message); Toast.makeText(DiscussionActivity.this, "Sent", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(DiscussionActivity.this, "" + task.getException(), Toast.LENGTH_SHORT).show(); } } }); } else { Toast.makeText(this, "Update Profile", Toast.LENGTH_SHORT).show(); } } } private void sendNotification(String key, String message) { for (int i = 0; i < userList.size(); i++) { if (!userList.get(i).getUserID().equals(mUSer.getUid())) { HashMap hashMap = new HashMap(); hashMap.put("key", key); hashMap.put("message", message); hashMap.put("status", "unseen"); hashMap.put("userID", userList.get(i).getUserID()); notification.child(userList.get(i).getUserID()).child(key).updateChildren(hashMap).addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull @NotNull Task task) { } }); } } } }
Python
UTF-8
512
2.890625
3
[ "MIT" ]
permissive
import numpy as np import cv2 img = cv2.imread('obstacle_scene_5.jpg') dst = cv2.fastNlMeansDenoisingColored(img,None,10,10,7,21) lower = np.array([40,40,40]) #-- Lower range -- upper = np.array([110,110,110]) #-- Upper range -- mask = cv2.inRange(dst, lower, upper) #cv2.imshow('Mask',mask) mask = 255 - mask res = cv2.bitwise_and(dst, dst, mask = mask) #-- Contains pixels having the gray color-- cv2.imshow('Original, Denoised, Masked',np.hstack([img,dst,res])) cv2.waitKey(0) cv2.destroyAllWindows()
Python
UTF-8
448
3.65625
4
[]
no_license
print('Nhap chuoi co dang: A=B. ex: 120=111') s = input('Input:') index = s.find('=') A = s[:index] B = s[index+1:] n = len(A) m = len(B) count = 0 for i in range(1, n): for j in range(1, m): aL = A[:i] aR = A[i:] bL = B[:j] bR = B[j:] if int(aL) + int(aR) == int(bL) + int(bR): count += 1 print(aL, '+', aR, '=', bL, '+', bR) if count == 0: print('Khong co cach dat.')
Shell
UTF-8
2,845
4.21875
4
[]
no_license
#!/bin/bash # # DESCRIPTION: # # Set the bash prompt according to: # * the active virtualenv # * the branch/status of the current git repository # * the return value of the previous command # # USAGE: # # 1. Save this file as ~/.bash_prompt # 2. Add the following line to the end of your ~/.bashrc or ~/.bash_profile: # . ~/.bash_prompt # # LINEAGE: # # Based on work by woods # # https://gist.github.com/31967 # The various escape codes that we can use to color our prompt. # TODO: change pallete and remove duplicates (RED == LIGHT_RED) RED="\[\033[0;31m\]" YELLOW="\[\033[1;33m\]" GREEN="\[\033[0;32m\]" BLUE="\[\033[1;34m\]" LIGHT_RED="\[\033[1;31m\]" LIGHT_GREEN="\[\033[1;32m\]" WHITE="\[\033[1;37m\]" LIGHT_PURPLE="\[\033[1;35m\]" LIGHT_GRAY="\[\033[0;37m\]" COLOR_NONE="\[\e[0m\]" # Detect whether the current directory is a git repository. function is_git_repository { git branch > /dev/null 2>&1 } # Determine the branch/state information for this git repository. function set_git_branch { # Capture the output of the "git status" command. git_status="$(git status 3> /dev/null)" # Set color based on clean/staged/dirty. if [[ ${git_status} =~ "working directory clean" ]]; then state="${GREEN}" elif [[ ${git_status} =~ "Changes to be committed" ]]; then state="${YELLOW}" else state="${LIGHT_RED}" fi # Set arrow icon based on status against remote. remote_pattern="Your branch is (.*) of" if [[ ${git_status} =~ ${remote_pattern} ]]; then if [[ ${BASH_REMATCH[1]} == "ahead" ]]; then remote="↑" else remote="↓" fi else remote="" fi diverge_pattern="Your branch and (.*) have diverged" if [[ ${git_status} =~ ${diverge_pattern} ]]; then remote="↕" fi # Get the name of the branch. branch=$(git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/') # Set the final branch string. BRANCH="${state}(${branch}) ${remote}${COLOR_NONE}" } # TODO: verify if current version matches .nvmrc when present function set_nodeenv () { if test "$node -v" ; then NODE_VERSION="${LIGHT_GREEN}[nodejs $(node -v)]${COLOR_NONE}" else NODE_VERSION="${RED}[NODE NOT INSTALLED]${COLOR_NONE}" fi } # Set the full bash prompt. # TODO: keep empty [] and maybe add something? # TODO: make it work with python, java, c, etc. function set_bash_prompt () { # set_virtualenv if test -e ".nvmrc" || test "$node -v"; then set_nodeenv fi # Set the BRANCH variable. if is_git_repository ; then set_git_branch else BRANCH='' fi # Set the bash prompt variable. PS1="${LIGHT_PURPLE}\u${COLOR_NONE}:${BLUE}\W${COLOR_NONE} ${NODE_VERSION} ${BRANCH} \$ " } # Tell bash to execute this function just before displaying its prompt. PROMPT_COMMAND=set_bash_prompt
Java
UTF-8
1,767
2.859375
3
[]
no_license
package com.ticket.management.data; import java.util.HashMap; import java.util.Map; public class Level { private int id; private String name; private int totalRows; private float pricePerSeat; private int totalSeatsPerRow; private Map<Character,Row> rows; private int totalAvailableSeats; public Level(int id,String name,int totalRows,float price,int totalSeatsPerRow){ this.id=id; this.name = name; this.totalRows =totalRows; this.pricePerSeat =price; this.totalSeatsPerRow = totalSeatsPerRow; this.rows = new HashMap<Character,Row>(); this.totalAvailableSeats = totalRows*totalSeatsPerRow; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getTotalRows() { return totalRows; } public void setTotalRows(int totalRows) { this.totalRows = totalRows; } public float getPricePerSeat() { return pricePerSeat; } public void setPricePerSeat(float pricePerSeat) { this.pricePerSeat = pricePerSeat; } public int getTotalSeatsPerRow() { return totalSeatsPerRow; } public void setTotalSeatsPerRow(int totalSeatsPerRow) { this.totalSeatsPerRow = totalSeatsPerRow; } public Map<Character, Row> getRows() { return rows; } public void setRows(Map<Character, Row> rows) { this.rows = rows; } public int getTotalAvailableSeats() { return totalAvailableSeats; } public void setTotalAvailableSeats(int totalAvailableSeats) { this.totalAvailableSeats = totalAvailableSeats; } public void incrementNumberOfVacantSeats() { this.totalAvailableSeats ++; } public void decrementNumberOfVacantSeats() { this.totalAvailableSeats --; } }
Java
UTF-8
216
2.171875
2
[]
no_license
package com.codewars; //public class KataTests { // @Test // public void exampleTests() { // assertEquals(8, Kata.dontGiveMeFive(1,9)); // assertEquals(12, Kata.dontGiveMeFive(4,17)); // } //}
C#
UTF-8
1,132
2.578125
3
[]
no_license
using InvoicingSystem.Data.Repositories; using InvoicingSystem.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InvoicingSystem.Data.Mocks { class AddressMock { AppDbContext context = new AppDbContext(); AddressRepository rep; public AddressMock() { rep = new AddressRepository(context); Seed(); } private void Seed() { /*rep.CreateAddress(new Address() { Street = "Karlovarská", BuildingNumber = "71", City = "Kyšice", ZipCode = 27351 }); rep.CreateAddress(new Address() { Street = "Londýnská", BuildingNumber = "290/3a", City = "Praha", ZipCode = 29000 }); rep.CreateAddress(new Address() { Street = "Malé náměstí", BuildingNumber = "459/13", City = "Praha", ZipCode = 23001 });*/ } } }
Markdown
UTF-8
6,476
2.90625
3
[]
no_license
# Image镜像 * 介绍 * 父镜像 * 基础镜像 * 镜像ID * 获列出本地镜像取镜像 * 创建镜像 * 修改已有镜像 * 利用 Dockerfile 来创建镜像 * 从本地文件系统导入 * 上传镜像 * 存出和载入镜像 * 存出镜像 * 载入镜像 * 移除本地镜像 * 镜像的实现原理 --- # 介绍 ![mark](http://p7whtc26y.bkt.clouddn.com/blog/180513/CK6mEi4G0m.png?imageslim) 在 Docker 的术语里,一个只读层被称为镜像,一个镜像是永久不会变的。 ![mark](http://p7whtc26y.bkt.clouddn.com/blog/180513/Bm3I3mA6Lg.png?imageslim) 所有的变更都发生顶层的可写层,而下层的原始的只读镜像文件并未变化 ## 父镜像 ![mark](http://p7whtc26y.bkt.clouddn.com/blog/180513/CHiFkE6jb8.png?imageslim) 每一个镜像都可能依赖于由一个或多个下层的组成的另一个镜像。我们有时说,下层那个 镜像是上层镜像的父镜像。 ## 基础镜像 一个没有任何父镜像的镜像,谓之基础镜像。也就是最下面那个兄弟 ## 镜像ID 所有镜像都是通过一个 64 位十六进制字符串 (内部是一个 256 bit 的值)来标识的。 为简化使用,前 12 个字符可以组成一个短ID,可以在命令行中使用。短ID还是有一定的 碰撞机率,所以服务器总是返回长ID。 # 获列出本地镜像取镜像 可以使用 ```docker pull``` 命令来从仓库获取所需要的镜像。 下面的例子将从 Docker Hub 仓库下载一个 Ubuntu 12.04 操作系统的镜像。 ``` root@iZj6ccz5qk5jv5b33n6fhnZ:~# docker pull ubuntu:12.04 12.04: Pulling from library/ubuntu d8868e50ac4c: Pull complete 83251ac64627: Pull complete 589bba2f1b36: Pull complete d62ecaceda39: Pull complete 6d93b41cfc6b: Pull complete Digest: sha256:18305429afa14ea462f810146ba44d4363ae76e4c8dfc38288cf73aa07485005 Status: Downloaded newer image for ubuntu:12.04 ``` Digest就是 镜像ID ## 列出本地镜像 使用 ```docker images``` 显示本地已有的镜像。 ``` root@iZj6ccz5qk5jv5b33n6fhnZ:~# docker images REPOSITORY TAG IMAGE ID CREATED SIZE ghost 0.11-alpine 840279d7ae80 8 days ago 174MB hello-world latest e38bc07ac18e 4 weeks ago 1.85kB ubuntu 12.04 5b117edd0b76 13 months ago 104MB training/webapp latest 6fae60ef3446 2 years ago 349MB ``` 在列出信息中,可以看到几个字段信息 * 来自于哪个仓库,比如 ubuntu * 镜像的标记,比如 14.04 * 它的 ID 号(唯一) * 创建时间 * 镜像大小 其中镜像的 ID 唯一标识了镜像 # 创建镜像 创建镜像有很多方法,用户可以从 Docker Hub 获取已有镜像并更新,也可以利用本地文件系统创建一个 ## 修改已有镜像 先使用下载的镜像启动容器。 注意:记住容器的 ID,稍后还会用到。 在容器中添加 json 和 gem 两个应用。 当结束后,我们使用 exit 来退出,现在我们的容器已经被我们改变了, 使用 ``` docker commit``` 命令来提交更新后的副本。 其中,-m 来指定提交的说明信息,跟我们使用的版本控制工具一样; -a 可以指定更新的用户信息;之后是用来创建镜像的容器的 ID; 最后指定目标镜像的仓库名和 tag 信息。 创建成功后会返回这个镜像的 ID 信息。 使用 docker images 来查看新创建的镜像。 之后,可以使用新的镜像来启动容器 ``` root@iZj6ccz5qk5jv5b33n6fhnZ:~# docker run -t -i training/sinatra /bin/bash root@0b2616b0e5a8:/# gem install json root@563523cc99fa:/# exit exit root@iZj6ccz5qk5jv5b33n6fhnZ:~# docker commit -m "add json into image " 897ed0ec8cef my-images:v1 sha256:7a9cfc4a88db791e2d5d1cc63642a74413b1ec6b17ddc3b046fb333843b3220f root@iZj6ccz5qk5jv5b33n6fhnZ:~# docker images REPOSITORY TAG IMAGE ID CREATED SIZE my-images v1 7a9cfc4a88db 24 seconds ago 453MB docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES b4bbc46c306d my-images:v1 "/bin/bash" 2 seconds ago Up 2 seconds happy_joliot ``` ## 利用 Dockerfile 来创建镜像 新建一个目录和一个 Dockerfile Dockerfile 中每一条指令都创建镜像的一层, Dockerfile 中每一条指令都创建镜像的一层, 编写完成 Dockerfile 后可以使用 docker build 来生成镜像。 * 注意一个镜像不能超过 127 层 此外,还可以利用 ADD 命令复制本地文件到镜像; 用 EXPOSE 命令来向外部开放端口; 用 CMD 命令来描述容器启动后运行的程序等。 现在可以利用新创建的镜像来启动一个容器。 ``` root@iZj6ccz5qk5jv5b33n6fhnZ:~# mkdir lmt root@iZj6ccz5qk5jv5b33n6fhnZ:~# cd lmt root@iZj6ccz5qk5jv5b33n6fhnZ:~/lmt# touch Dockerfile root@iZj6ccz5qk5jv5b33n6fhnZ:~/lmt# ls Dockerfile root@iZj6ccz5qk5jv5b33n6fhnZ:~/lmt# vi Dockerfile ``` ![mark](http://p7whtc26y.bkt.clouddn.com/blog/180513/CLEIdDlIjm.png?imageslim) ~~~ root@iZj6ccz5qk5jv5b33n6fhnZ:~/lmt# docker images REPOSITORY TAG IMAGE ID CREATED SIZE lmt/node v1 2b1e755445b1 31 seconds ago 248MB ~~~ ## 上传镜像 login first 在hub.docker.com注册账户 ~~~ root@iZj6ccz5qk5jv5b33n6fhnZ:~/lmt# docker login Login with your Docker ID to push and pull images from Docker Hub. If you don't have a Docker ID, head over to https://hub.docker.com to create one. Username: lazytai Password: WARNING! Your password will be stored unencrypted in /root/.docker/config.json. Configure a credential helper to remove this warning. See https://docs.docker.com/engine/reference/commandline/login/#credentials-store Login Succeeded ~~~ push之前要tag ~~~ root@iZj6ccz5qk5jv5b33n6fhnZ:~/lmt# docker tag lazytai/node lazytai/node root@iZj6ccz5qk5jv5b33n6fhnZ:~/lmt# docker push lazytai/node ~~~ 记得YOUR_DOCKERHUB_NAME/firstimage ```YOUR_DOCKERHUB_NAME``` 这个必须准确 ``` root@iZj6ccz5qk5jv5b33n6fhnZ:~/lmt# docker pull lazytai/node ```
Java
UTF-8
978
2.078125
2
[]
no_license
/** * */ package ec.com.taxinet.webapp.dto; import java.io.Serializable; import ec.com.taxinet.webapp.model.paymentManagement; /** * @author Juan Campos * */ public class paymentManagementDTO extends BaseDTO implements Serializable{ /** * */ private static final long serialVersionUID = 1L; private paymentManagement responseData; /** * */ public paymentManagementDTO() { // TODO Auto-generated constructor stub } public paymentManagement getResponseData() { return responseData; } public void setResponseData(paymentManagement responseData) { this.responseData = responseData; } @Override public String toString() { return "paymentManagementDTO [responseData=" + responseData + ", getResponseCode()=" + getResponseCode() + ", getResponseMessage()=" + getResponseMessage() + ", getMethodName()=" + getMethodName() + ", toString()=" + super.toString() + ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + "]"; } }
TypeScript
UTF-8
1,629
3
3
[ "MIT" ]
permissive
import { getImageUrl } from '../../../../utils/get-image'; import cardType from '../../../internal/SecuredFields/lib/utilities/cardType'; export const getCardImageUrl = (brand: string, loadingContext: string): string => { const imageOptions = { type: brand === 'card' ? 'nocard' : brand || 'nocard', extension: 'svg', loadingContext }; return getImageUrl(imageOptions)(brand); }; /** * Creates an object used for setting state - that will trigger the rendering of a select element to allow a choice between 2 different card variants * @param types - array containing 2 card brands or types * @param switcherType - type of switcher ('brandSwitcher' or 'cardTypeSwitcher' - the latter would switch between 'debit' & 'credit' varieties) */ export const createCardVariantSwitcher = (types: string[], switcherType: string) => { const leadType = types[0]; let displayName = cardType.getDisplayName(leadType); // Works for when types are card brands e.g. 'visa', 'mc' NOT when types are 'credit'/'debit' const leadDisplayName = displayName || leadType; const subType = types[1]; displayName = cardType.getDisplayName(subType); const subDisplayName = displayName || subType; return { stateObject: { additionalSelectElements: [ { id: leadType, name: leadDisplayName }, { id: subType, name: subDisplayName } ], // additionalSelectValue: leadType, // comment out line if no initial selection is to be made additionalSelectType: switcherType }, leadType }; };
Markdown
UTF-8
1,762
3.109375
3
[]
no_license
# 0x08. Python - More classes and objects ## Learning Objectives - Why Python programming is awesome - What is OOP - "first-class everything" - What is a class - What is an object and an instance - What is the difference between an class and an object or instance - What is an attribute - What are and how to use public, protected, and private attributes - What is `self` - What is a method - What is the special `__init__` method and how to use it - What is Data Abstraction, Data Encapsulation, and Information Hiding - What is a property - What is the difference between an attribute and a property in Python - What is the Pythonic way to write getters and setters - What are the special `__str__` and `__repr__` methods and how to use them - What is the difference between `__str__` and `__repr__` - What is a class attribute - What is the diffrence between a class attribute and an object attribute - What is a class method - What is a static method - How to dynamically create arbitarary new attributes for existing instances of a class - How to bind attributes to objects and classes - What is the `__dict__` of a class or instance of a class and what does it contain - How does Python find the attributes fo an object or class - How to use the `getattr` function ## Requirements - Allowed editors: vi, vim, emacs - All of your files will be interpreted/compiled on Ubuntu 14.04 LTS using `python3` (version 3.4.3) - All your files should end with a new line - The first line of all your files should be `#!/usr/bin/python3` exactly - A `README.md` at the root of the project directory is mandatory - Your code should use the `PEP8` style (version 1.7.*) - All your files must be executable - The length of your files will be tested using `wc` ## Files
Python
UTF-8
288
3.46875
3
[]
no_license
#program to insert in a dictionary a={} a.setdefault('key','value') a.setdefault('key1','value1') a.setdefault('key2',[]).append('value2_1') #appending as a list a.setdefault('key2',[]).append('value2_2') a.setdefault('key2',[]).append('value2_3') a.setdefault('key3','value3') print a
C++
UTF-8
4,720
3.1875
3
[]
no_license
// // Created by rnetuka on 22.12.19. // #include <algorithm> #include <deque> #include <functional> #include <numeric> #include <set> #include <sstream> #include <string> #include <vector> #include "../utils.h" using namespace std; using deck = deque<long>; constexpr long oversized_deck_size = 119'315'717'514'047; deck create_deck() { deck cards(10'007); iota(cards.begin(), cards.end(), 0); return cards; } long index_of(const deck& cards, long card) { auto it = find(cards.begin(), cards.end(), card); return distance(cards.begin(), it); } void deal_into_new_stack(deck& cards) { deck new_stack { cards }; reverse(new_stack.begin(), new_stack.end()); cards = new_stack; } void cut(deck& cards, int n) { deck result; if (n > 0) { result.insert(result.begin(), cards.begin() + n, cards.end()); result.insert(result.end(), cards.begin(), cards.begin() + n); } else if (n < 0) { result.insert(result.begin(), cards.end() - abs(n), cards.end()); result.insert(result.end(), cards.begin(), cards.end() - abs(n)); } cards = result; } void deal_with_increment(deck& cards, int n) { int size = cards.size(); deck dealed_cards(size); int i = 0; while (! cards.empty()) { int card = cards.front(); cards.pop_front(); dealed_cards[i % size] = card; i += n; } cards = dealed_cards; } int position_of_2019() { deck cards = create_deck(); vector<string> lines = read_lines<string>("day22/res/input.txt"); for (const string& line : lines) { stringstream stream { line }; string order; int n = 0; if (line.find("deal with increment ") == 0) { stream >> order >> order >> order; stream >> n; deal_with_increment(cards, n); } else if (line == "deal into new stack") deal_into_new_stack(cards); else if (line.find("cut ") == 0) { stream >> order; stream >> n; cut(cards, n); } } return (int) index_of(cards, 2019); } long deal_into_new_stack(long position, long deck_size) { return deck_size - position - 1; } long deal_with_increment(long position, int n, long deck_size) { return (n * position) % deck_size; } long cut(long position, int n, long deck_size) { /*if (n < 0) { if (position >= deck_size - abs(n)) return position + abs(n) - deck_size; } else { // n > 0 return position + (deck_size - abs(n)) % deck_size; } return position;*/ //return position + (deck_size - abs(n)) % deck_size; long offset = n < 0 ? abs(n) : deck_size - n; return (position + offset) % deck_size; } long position_of_2020() { long deck_size = 10'007; long card = 2019; //long deck_size = 119'315'717'514'047; //long card = 2020; long position = card; vector<string> lines = read_lines<string>("day22/res/input.txt"); vector<function<long(long)>> operations; for (const string& line : lines) { stringstream stream { line }; string order; int n = 0; if (line.find("deal with increment ") == 0) { stream >> order >> order >> order; stream >> n; operations.emplace_back([n, deck_size](long position) { return deal_with_increment(position, n, deck_size); }); } else if (line == "deal into new stack") { operations.emplace_back([deck_size](long position) { return deal_into_new_stack(position, deck_size); }); } else if (line.find("cut ") == 0) { stream >> order; stream >> n; operations.emplace_back([n, deck_size](long position) { return cut(position, n, deck_size); }); } } for (auto& operation : operations) { position = (2 * operation(position)) % deck_size; } return position; position %= deck_size; /*long max_i = 101'741'582'076'661 + 1; set<long> part_results; for (long i = 0; i < 170'000; i++) { for (auto& operation : operations) { position = operation(position); if (position == 108'705'724'129'205) { return -i; } if (part_results.find(position) != part_results.end()) { return position; } part_results.insert(position); } }*/ // position of 2020 repeats: // after 137'070 steps = 108'705'724'129'205 // after 165'855 steps = 108'705'724'129'205 return position; }
C
UTF-8
3,514
2.953125
3
[]
no_license
#include <stdlib.h> #include <unistd.h> #include <SDL.h> #include <SDL_audio.h> #include <stdint.h> #include <math.h> typedef float sample_t; typedef int samplecount_t; typedef float freq_t; typedef float msec_t; samplecount_t samplerate; static freq_t basefreq=55; static freq_t freq; // Converts a sample count into a time in milliseconds static msec_t time(samplecount_t samples){ return (1000.0/samplerate)*samples; } // Convert time in milliseconds to a sample count static samplecount_t samples(msec_t time){ return (time/1000.0)*samplerate; } // Fast fixed point sine approximation int32_t isin_S3(int32_t x){ int qN=13; // Q-pos for quarter circle int qA=29; // Q-pos for output int qP=15; // Q-pos for parentheses intermediate int qR=2*qN-qP; int qS=qN+qP+1-qA; x=x<<(30-qN); // shift to full s32 range (Q13->Q30) if((x^(x<<1))<0) // test for quadrant 1 or 2 x=(1<<31)-x; x=x>>(30-qN); return x*((3<<qP)-(x*x>>qR))>>qS; } #define f2Q(x) ( (x) * (1.0/(2*M_PI)) * pow(2,15) ) #define Q2f(x) ( (int32_t)(x) * (1.0/(float)(1<<29)) ) static sample_t sinQ(sample_t in){ //static float max=0.0; int32_t out=isin_S3(f2Q(in)); //float error=fabs(sin(in)-Q2f(out)); //if(error>max){ // max=error; // printf("%f\n",max); //} // printf("%f\n",error); return Q2f(out); } // Sine oscillator with FM. void sin_osc(sample_t* in, sample_t* out, int len, freq_t freq, samplecount_t samplepos){ int i; float pos; for(i=0;i<len;i++){ pos=samplepos/(samplerate/freq); out[i]=sinQ(2*M_PI*(pos+in[i])); samplepos++; } } // Linear AR envelope generator void ar_env(sample_t* restrict in, sample_t* restrict out, int len, samplecount_t samplepos, samplecount_t envstart, sample_t mod, msec_t attack, msec_t release){ int i; float envpos; sample_t s; for(i=0;i<len;i++){ envpos=time(samplepos-envstart); if(envpos<attack){ s=envpos*(mod/attack); }else{ s=mod-(envpos-attack)/release; } if(s<0.0){ s=0.0; } out[i]=in[i]*s; samplepos++; } } // Two operator FM patch static samplecount_t synth(sample_t* buf, int len, freq_t freq, samplecount_t samplepos, samplecount_t envstart){ int i; for(i=0;i<len;i++){ buf[i]=0.0; } sin_osc(buf,buf,len,freq*1.2,samplepos); ar_env(buf,buf,len,samplepos,envstart,time(samplepos)/50000,0,750); sin_osc(buf,buf,len,freq,samplepos); ar_env(buf,buf,len,samplepos,envstart,1,4,100); return samplepos+len; } void synthcall(SDL_AudioSpec* fmt, int16_t* stream, int len){ static int envstart=0; static int samplepos=0; static float nexttime=0; static sample_t* buf=NULL; int i; len=len/sizeof(int16_t); if(buf==NULL){ buf=calloc(len,sizeof(sample_t)); } if(time(samplepos)>=nexttime){ envstart=samplepos; nexttime=time(samplepos)+100; freq=freq*2; if(freq>440){ basefreq=basefreq-(basefreq/4); if(basefreq<50){ basefreq=220; } freq=basefreq; } } samplepos=synth(buf,len,freq,samplepos,envstart); for(i=0;i<len;i++){ stream[i]=(int16_t)(buf[i]*INT16_MAX); } } int main(void){ SDL_AudioSpec desiredfmt,actualfmt; desiredfmt.freq = 48000; desiredfmt.format = AUDIO_S16SYS; desiredfmt.channels = 1; desiredfmt.samples = 512; desiredfmt.callback = synthcall; desiredfmt.userdata = NULL; if(SDL_OpenAudio(&desiredfmt,&actualfmt)<0){ fprintf(stderr, "Unable to open audio: %s\n",SDL_GetError()); exit(1); } samplerate=actualfmt.freq; freq=basefreq; SDL_PauseAudio(0); while(1){ sleep(5); } SDL_CloseAudio(); return 0; }
C++
UTF-8
7,955
3.34375
3
[]
no_license
#include "myBlock.h" #include <stddef.h> #include <memory> #include <iostream> # define myEpsilon 100 using namespace std; //default constructor myBlock::myBlock(){ theObject = nullptr; cout<<"default constructor called"<<endl; } myBlock::myBlock(int lengthOfString){ //check for space //create 3 blocks just once if(initlized == false) { CallmeOnce();//initlize the three blocks } if(Allocate(lengthOfString)){ //length of the object plus the number of its bytes this->sizeOfMyObj = lengthOfString; //subtract from the overall size allocated //class ptr theObject = new char[this->sizeOfMyObj]; }//if this is true will allocate a block else{ cout<<"nothing was allocated, not enough space"<<endl; } }//end of my Block //sizes int myBlock:: getNumberOfUsedBlocks(){ return this->myBlocks; }//end get number of blocks allocated int myBlock::sizeofBlock(){ //allocatedNode* q = (allocatedNode)theObject; return (sizeof this->theObject);//return the size of the object }//end size //sizes for object memory pool void myBlock::decrementSize(int bytes){//used when allocating space in the overall pool this->overallAlocation -=(sizeof(bytes)); cout<<"Succesfully added to the memory pool"<<endl; } void myBlock::restoreSize(int bytes){//used when deallocating memory and returns memory to the overall object pool this->overallAlocation += (sizeof(bytes)); cout<<"returned "<<sizeof(bytes)<<" bytes, to overall memory."<<endl; } int myBlock::currentSizeOfObjectPool(){//gives the overall size of the memory pool return this->overallAlocation; } //links 3 blocks together void myBlock::CallmeOnce(){ //first node points to the begining of the list //empty //points to the front of the list FirstNode = static_cast<myHead *> (myMemoryAddress); FirstNode->tag = 0; FirstNode->size = 0; //left and rught FirstNode->LLink = (myHead*)((char*) myMemoryAddress + (overallAlocation) - sizeof(myTail*) - sizeof(myHead*)); FirstNode->RLink = (myHead*) ((char*) myMemoryAddress + (sizeof(myHead) - sizeof(myTail))); //tail myFirstTail = (myTail*)((char*)myMemoryAddress + sizeof(myHead*)); myFirstTail->size = 0; myFirstTail->upLink = FirstNode;//connect the first node //body block points to the tail BodyNode = (myHead*)((char*) myFirstTail - sizeof(myTail*) - sizeof(myHead*)); BodyNode ->size = 0; BodyNode ->tag = 0; BodyNode->RLink = (myHead*)((char*) myMemoryAddress + (overallAlocation) - sizeof(myTail*) - sizeof(myHead*)); BodyNode->LLink = (myHead*) ((char*) myMemoryAddress + (sizeof(myHead) - sizeof(myTail))); //tail of the middle block points to the head of the first block myBodyTail = (myTail*)((char*)BodyNode + sizeof(myHead*)); myBodyTail->size = 0; myBodyTail->upLink = BodyNode;//connect the first node //final Block points to tain LastNode = (myHead*)((char*) BodyNode - sizeof(myTail*) - sizeof(myHead*)); LastNode->tag = 0; LastNode->size = 0; BodyNode->RLink = (myHead*)((char*) myMemoryAddress + (overallAlocation) - sizeof(myTail*) - sizeof(myHead*)); BodyNode->LLink = (myHead*) ((char*) myMemoryAddress + (sizeof(myHead) - sizeof(myTail))); //last node tail myLasttTail = (myTail*)((char*)myMemoryAddress + sizeof(myHead*)); myLasttTail->size = 0; myLasttTail->upLink = LastNode;//connect the first node initlized = true;//set true once }//end call me once //allocate recives (n) - which is the length of the object bool myBlock::Allocate(int lengthOfN){ int diff; myHead *p; //top of the block myTail* tail;//bottom of the block int epsilon = myEpsilon; bool checkMe = (sizeof(p)>= lengthOfN) ? true : false; // algorithm //first p is set to the right link of av p = av->RLink; do{ //----->check size //want to make sure the size of the object is not bigger than //the memory means in the pool so check first if(checkMe) { //check if the next block is big enough //diff<--size(p) - n diff = (sizeof(p) - lengthOfN); //diff<epsilon if(diff<epsilon){//------------>first case //[Rlink(Llink(p)) <-- Rlink(p)] p->RLink->LLink = p->RLink; //Llink(Rlink(p))<--Llink(p) p->LLink->RLink = p->LLink; p->tag = 1;//upper tag at the top of the block //to be moved around //tail = (myTail*)((char*)p + p->size + sizeof(myHead)); av = p->LLink;//set av to point to the nexly allocatted block, which is the //new starting point return true; }//end first case else{//------------->second case --lower case //diff will now equal the size of p + its tail diff = sizeof(p)+sizeof(tail) + lengthOfN; //and size of the tail? + sizeof(tail) p->size = diff; //set uplink to point to p tail->upLink = (myHead*)(((char*)p) + diff - 1); //postion of p p->tag = 0;// p tag is 0 - top block isnt allocated p->size = lengthOfN; tail->tag = 1; return true; }//end second case //move the ptr forward to check other blocks } p = p->RLink; }while(p!= av->RLink); //stop if we have reached av //end Allocate p = nullptr;tail = nullptr; return false; }//end allocate void myBlock::Free(myHead *p){ int onTheLeft, onTheRight; int n = p->size; myHead *q; myTail *k; //case1 if both adjacent tags are in use q = ((myHead*)((char*)p + n )); //p+n k = ((myTail*)((char*)p - n ));//p-1 //p-1 p+n if(q->tag == 1 && k->tag == 1){ //set the tag to free p->tag = 0; //upLink p->LLink = av; p->RLink = av->RLink; p->LLink->RLink = p; av->RLink= p; } //p+n p-1 if( k->tag == 1 && q->tag == 0 ){ //case 2 //start of left block k->upLink = (myHead*)(((char*)p) - 1); q->size = (sizeof(q) + n); k->upLink = (myHead*)(((char*)p) + n - 1); p->tag = 0;//set the tag to zed } if( k->tag == 0 && q->tag == 1 ){ //case 3 p->RLink->LLink->((myHead*)sizeof((char*)p) + n) = p; p->LLink->RLink->(sizeof((char*)p) + n) = p; p->RLink = p->RLink->((myHead*)((char*)p) + n); p->size = n + sizeof(p) + n; k->upLink->(sizeof(p) + sizeof(p) - 1); p->tag = 0; }//end if if( av = p ) av = p; else {//case 4 //both adjacent blocks are free p->RLink = p->LLink->(sizeof((char*)p) + n); p->LLink->RLink->(sizeof((char*)p) + n) = p->LLink->(sizeof((char*)p) + n); q = k->upLink->(sizeof(p) - 1); if(av = (myHead*)(sizeof(p) + n)) av = p->LLink->(sizeof(p)+ n); }//end else }//end free //deallocate the ptr myBlock::~myBlock(){ cout<<"Deleting class ptr"<<endl; delete [] theObject; } void* myBlock::operator new(size_t size){ cout<<"size of allocation: "<<size<<endl; void *p = malloc(size);//creates the size of the object //keeping track of the number of free blocks cout<<"size of allocation: "<<size<<" bytes"<<endl; //when the algo is implemented ill keep track of the amount of space inside //of each block myBlocks++; cout<<"\n Successfully allocated a block!! number of blocks allocated: "<<myBlocks<<endl; return p; // return new char [size]; }//end operator new void myBlock::operator delete(void* myMemory){ myBlocks--; cout<<"Freed up memory bytes"<<endl; free(myMemory);//delete the ptr }//end operator Delete
C
UTF-8
614
3.921875
4
[]
no_license
// Counts digits in a given number #include <stdio.h> #include <stdlib.h> void repetedDigits(int n){ int *p = (int *) malloc(1 * sizeof(int)); int digit, i=0, j, index = 0; int arr[10] = {0}; while(n/10 != 0){ digit = n % 10; n /= 10; p[i] = digit; realloc(p, 1 * sizeof(int)); i++; } realloc(p, 1 * sizeof(int)); p[i] = n%10; for(j=0; j<=i; j++) { arr[p[j]]++; } for(j=0; j<10; j++) { printf("Posizione %d%: %d\n", j, arr[j]); } } int main() { int n, i; printf("Enter a number: "); scanf("%d", &n); repetedDigits(n); return 0; }
Go
UTF-8
1,107
3.28125
3
[ "MIT" ]
permissive
package perftest import ( "bytes" "encoding/json" "fmt" "net/http" "sync" "testing" "time" ) func hitURLShortner() (interface{}, interface{}) { requestBody, _ := json.Marshal(map[string]string{ "url": "https://youtu.be/dQw4w9WgXcQ?t=43", "request_id": "asdlfjhlaksdjffsajkflkjghjasfflkg", }) resp, err := http.Post("http://0.0.0.0:8080/shorten", "application/json", bytes.NewBuffer(requestBody)) return resp, err } func serially(wg *sync.WaitGroup, n int) { defer wg.Done() for i := 0; i < n; i++ { hitURLShortner() } } func PerfTest() { t1 := time.Now() numGoRoutines := 5 // Number of go routines maxQueriesPerGoRoutine := 200 //Number of request each go Routine is going to make Serially var wg sync.WaitGroup wg.Add(numGoRoutines) for i := 0; i < numGoRoutines; i++ { go serially(&wg, maxQueriesPerGoRoutine) //Fan Out } wg.Wait() //Fan In t2 := time.Now() fmt.Printf("Time taken to add %v records %v\n", numGoRoutines*maxQueriesPerGoRoutine, t2.Sub(t1)) return } //Perf Testing func TestAddingRecordsConcurrently(t *testing.T) { PerfTest() }
C++
UTF-8
1,161
3.015625
3
[]
no_license
class Solution { public: vector<vector<int>> ans; void dfs(vector<int>& nums, vector<int>& path, int start) { if (path.size() >= 2) ans.push_back(path); if (start >= nums.size()) return; unordered_set<int> s; // 如果set里已经记录了当前的值,则跳过;因为之前唤起的dfs里会把之后所有的同样的值都选中; // 只需要考虑从之后开始选中的重复的值即可 for (int i = start; i < nums.size(); i++) { if (s.find(nums[i]) != s.end()) continue; if (path.size() == 0) { s.insert(nums[i]); path.push_back(nums[i]); dfs(nums, path, i+1); path.pop_back(); } else { if (nums[i] >= path.back()) { s.insert(nums[i]); path.push_back(nums[i]); dfs(nums, path, i+1); path.pop_back(); } } } } vector<vector<int>> findSubsequences(vector<int>& nums) { vector<int> path; dfs(nums, path, 0); return ans; } };
C++
UTF-8
6,276
2.53125
3
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* * ******** merced: calculate the transfer matrix ******** * $Revision: 601 $ * $Date: 2017-12-12 $ * $Author: hedstrom $ * $Id: quad_methods.hpp 601 2017-12-12Z hedstrom $ * ******** merced: calculate the transfer matrix ********* * * # <<BEGIN-copyright>> * # <<END-copyright>> */ // Classes for Gaussian quadrature #ifndef QUAD_METHODS #define QUAD_METHODS #include "param_base.hpp" #include "coef_vector.hpp" namespace Qmeth { // ------------------------ Quadrature_Method --------------- //! Specifies the quadrature rule. The options are //! GAUSS1: the midpoint rule //! GAUSS2: 2nd-order Gaussian quadrature //! GAUSS3: 3nd-order Gaussian quadrature //! GAUSS4: 4th-order Gaussian quadrature //! GAUSS6: 6th-order Gaussian quadrature //! GAUSS10: 10th-order Gaussian quadrature //! WEIGHT_L1: 1st-order Gaussian quadrature with $sqrt{x}$ singularity enum Quadrature_Method{ GAUSS1, GAUSS2, GAUSS3, GAUSS4, GAUSS6, GAUSS10, WEIGHT_L1 }; //! Class to specify the quadrature rule // ------------------------ Quadrature_Rule --------------- class Quadrature_Rule { private: public: Quadrature_Method quad_method; //! Do we use adaptive quadrature? bool adaptive; //! Is this rule set at input? bool input_set; Quadrature_Rule( ): adaptive( true ), input_set( false ) {} ~Quadrature_Rule( ) { } //! to copy //! \param to_copy, the data to copy Quadrature_Rule& operator=( const Quadrature_Rule &to_copy ); }; // ********** basic Gaussian quadrature routines ************** // ------------- midpoint_rule ------------------------------- //! The midpoint rule on the interval $(A, B)$. //! Returns true if there were no problems //! \param F the vector function to integrate: $\int_A^B F$ //! \param A lower limit of integration //! \param B upper limit of integration //! \param params parameters for the function, F //! \param value vector of approximate integrals: $\int_A^B F$ bool midpoint_rule( bool (*F)( double x, Qparam::QuadParamBase *params, Coef::coef_vector *Value ), double A, double B, Qparam::QuadParamBase *params, Coef::coef_vector *value ); // ------------- Gauss_2 ------------------------------- //! Second-order Gaussian quadrature on the interval $(A, B)$. //! Returns true if there were no problems //! This is used because it is exact for polynomials of degree 3. //! \param F the vector function to integrate: $\int_A^B F$ //! \param A lower limit of integration //! \param B upper limit of integration //! \param params parameters for the function, F //! \param value vector of approximate integrals: $\int_A^B F$ bool Gauss_2( bool (*F)( double x, Qparam::QuadParamBase *params, Coef::coef_vector *Value ), double A, double B, Qparam::QuadParamBase *params, Coef::coef_vector *value ); // ------------- Gauss_3 ------------------------------- //! Third-order Gaussian quadrature on the interval $(A, B)$. //! Returns true if there were no problems //! This is used because it is exact for polynomials of degree 3. //! \param F the vector function to integrate: $\int_A^B F$ //! \param A lower limit of integration //! \param B upper limit of integration //! \param params parameters for the function, F //! \param value vector of approximate integrals: $\int_A^B F$ bool Gauss_3( bool (*F)( double x, Qparam::QuadParamBase *params, Coef::coef_vector *Value ), double A, double B, Qparam::QuadParamBase *params, Coef::coef_vector *value ); // ------------- Gauss_4 ------------------------------- //! Fourth-order Gaussian quadrature on the interval $(A, B)$. //! Returns true if there were no problems //! This is used because it is exact for polynomials of degree 7. //! \param F the vector function to integrate: $\int_A^B F$ //! \param A lower limit of integration //! \param B upper limit of integration //! \param params parameters for the function, F //! \param value vector of approximate integrals: $\int_A^B F$ bool Gauss_4( bool (*F)( double x, Qparam::QuadParamBase *params, Coef::coef_vector *Value ), double A, double B, Qparam::QuadParamBase *params, Coef::coef_vector *value ); // ------------- Gauss_6 ------------------------------- //! Sixth-order Gaussian quadrature on the interval $(A, B)$. //! Returns true if there were no problems //! This is used because it is exact for polynomials of degree 11. //! \param F the vector function to integrate: $\int_A^B F$ //! \param A lower limit of integration //! \param B upper limit of integration //! \param params parameters for the function, F //! \param value vector of approximate integrals: $\int_A^B F$ bool Gauss_6( bool (*F)( double x, Qparam::QuadParamBase *params, Coef::coef_vector *Value ), double A, double B, Qparam::QuadParamBase *params, Coef::coef_vector *value ); // ------------- Gauss_10 ------------------------------- //! Tenth-order Gaussian quadrature on the interval $(A, B)$. //! Returns true if there were no problems //! This is used because it is exact for polynomials of degree 19. //! \param F the vector function to integrate: $\int_A^B F$ //! \param A lower limit of integration //! \param B upper limit of integration //! \param params parameters for the function, F //! \param value vector of approximate integrals: $\int_A^B F$ bool Gauss_10( bool (*F)( double x, Qparam::QuadParamBase *params, Coef::coef_vector *Value ), double A, double B, Qparam::QuadParamBase *params, Coef::coef_vector *value ); // ------------- weight_L1 ------------------------------- //! First-order Gaussian quadrature on the interval $(A, B)$ //! with $sqrt{x}$ singularity. //! Returns true if there were no problems //! \param F the vector function to integrate: $\int_A^B F$ //! \param A lower limit of integration //! \param B upper limit of integration //! \param params parameters for the function, F //! \param value vector of approximate integrals: $\int_A^B F$ bool weight_L1( bool (*F)( double x, Qparam::QuadParamBase *params, Coef::coef_vector *Value ), double A, double B, Qparam::QuadParamBase *params, Coef::coef_vector *value ); } // end of namespace Qmeth #endif
Java
UTF-8
3,293
2.8125
3
[ "MIT" ]
permissive
package goliathoufx.panes; import javafx.event.Event; import javafx.event.EventHandler; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; public class AppTabPane extends TabPane { public static boolean POWER_ONLY = false; public static boolean BLOCK_TAB_CREATION; private final TabHandler handler; private final Tab[] tabs; private final PasswordPane passwordPane; private final PerformancePane performancePane; public AppTabPane() { super(); super.setTabClosingPolicy(TabClosingPolicy.ALL_TABS); ConsolePane pane = new ConsolePane(); ConsolePane.init(pane.getList()); BLOCK_TAB_CREATION = false; passwordPane = new PasswordPane(this); performancePane = new PerformancePane(this); handler = new TabHandler(this); tabs = new Tab[5]; tabs[0] = new Tab("Information"); tabs[0].setContent(new InformationPane()); tabs[1] = new Tab("PowerMizer & Overclocking"); tabs[1].setContent(performancePane); tabs[2] = new Tab("Fan Control"); tabs[2].setContent(new FanProfilePane()); tabs[3] = new Tab("App Console"); tabs[3].setContent(pane); tabs[4] = new Tab("About"); tabs[4].setContent(new AboutPane()); for(int i = 0; i < tabs.length; i++) tabs[i].setOnCloseRequest(handler); super.getTabs().addAll(tabs); } public void promptPassword() { BLOCK_TAB_CREATION = true; Tab pswPane = new Tab("Root Access Required"); pswPane.setContent(passwordPane); pswPane.setClosable(false); this.getTabs().removeAll(this.getTabs()); this.getTabs().add(pswPane); this.getSelectionModel().select(pswPane); } public void cancelPassword() { BLOCK_TAB_CREATION = false; this.getTabs().removeAll(this.getTabs()); for(int i = 0; i < tabs.length; i++) this.getTabs().add(tabs[i]); this.getSelectionModel().select(1); } public void gotPassword() { BLOCK_TAB_CREATION = false; this.getTabs().removeAll(this.getTabs()); for(int i = 0; i < tabs.length; i++) this.getTabs().add(tabs[i]); this.getSelectionModel().select(1); if(POWER_ONLY) performancePane.applyPowerLimit(passwordPane.getPassword()); else performancePane.applyOCAll(passwordPane.getPassword()); } public Tab getInformationTab() { return tabs[0]; } public Tab getPowerMizerTab() { return tabs[1]; } public Tab getFanControlTab() { return tabs[2]; } // Generic EventHandler class for taking care of special tab closing behavior private class TabHandler implements EventHandler { private final TabPane pane; public TabHandler(TabPane tabPane) { pane = tabPane; } @Override public void handle(Event event) { pane.getTabs().remove(((Tab)event.getSource())); } } }
Go
UTF-8
1,300
2.59375
3
[]
no_license
package services import "testing" func TestCreateMerchantInvalidRateN(t *testing.T) { actual := MS.CreateMerchant([]string{"merchantTest", "abc"}) if actual { t.Errorf("Merchant Created despite invalid rate of interest") } } func TestCreateMerchantInvalidArgsN(t *testing.T) { actual := MS.CreateMerchant([]string{"merchantTest", "10", "some random param"}) if actual { t.Errorf("Merchant created despite invalid args") } } func TestCreateMerchantInvalidInterestN(t *testing.T) { actual := MS.CreateMerchant([]string{"merchantTest", "-10", "some random param"}) if actual { t.Errorf("Merchant created despite invalid interest rate") } } func TestGetMerchantDiscountInvalidArgsN(t *testing.T) { actual := MS.GetMerchantDiscount([]string{"merchantTest"}) if actual { t.Errorf("GetMerchantDiscount passed despite InvalidArgs") } } func TestGetMerchantDiscountInvalidMerchantN(t *testing.T) { actual := MS.GetMerchantDiscount([]string{"discount", "merchantTest123"}) if actual { t.Errorf("GetMerchantDiscount passed despite Invalid Merchant") } } func TestChangeMerchantInterest110N(t *testing.T) { actual := MS.ChangeMerchantInterest([]string{"merchantTest", "110"}) if actual { t.Errorf("TestChangeMerchantInterest110N passed despite Invalid Rate of interest") } }
Go
UTF-8
34,509
3.109375
3
[ "MIT" ]
permissive
package container type ArrayList_int struct { items []int } type ArrayList_int8 struct { items []int8 } type ArrayList_int16 struct { items []int16 } type ArrayList_int32 struct { items []int32 } type ArrayList_int64 struct { items []int64 } type ArrayList_uint struct { items []uint } type ArrayList_uint8 struct { items []uint8 } type ArrayList_uint16 struct { items []uint16 } type ArrayList_uint32 struct { items []uint32 } type ArrayList_uint64 struct { items []uint64 } type ArrayList_float32 struct { items []float32 } type ArrayList_float64 struct { items []float64 } type ArrayList_complex64 struct { items []complex64 } type ArrayList_complex128 struct { items []complex128 } type ArrayList_string struct { items []string } // NewArrayList_int creates a new ArrayList func NewArrayList_int() *ArrayList_int { return new(ArrayList_int) } // NewArrayList_int8 creates a new ArrayList func NewArrayList_int8() *ArrayList_int8 { return new(ArrayList_int8) } // NewArrayList_int16 creates a new ArrayList func NewArrayList_int16() *ArrayList_int16 { return new(ArrayList_int16) } // NewArrayList_int32 creates a new ArrayList func NewArrayList_int32() *ArrayList_int32 { return new(ArrayList_int32) } // NewArrayList_int64 creates a new ArrayList func NewArrayList_int64() *ArrayList_int64 { return new(ArrayList_int64) } // NewArrayList_uint creates a new ArrayList func NewArrayList_uint() *ArrayList_uint { return new(ArrayList_uint) } // NewArrayList_uint8 creates a new ArrayList func NewArrayList_uint8() *ArrayList_uint8 { return new(ArrayList_uint8) } // NewArrayList_uint16 creates a new ArrayList func NewArrayList_uint16() *ArrayList_uint16 { return new(ArrayList_uint16) } // NewArrayList_uint32 creates a new ArrayList func NewArrayList_uint32() *ArrayList_uint32 { return new(ArrayList_uint32) } // NewArrayList_uint64 creates a new ArrayList func NewArrayList_uint64() *ArrayList_uint64 { return new(ArrayList_uint64) } // NewArrayList_float32 creates a new ArrayList func NewArrayList_float32() *ArrayList_float32 { return new(ArrayList_float32) } // NewArrayList_float64 creates a new ArrayList func NewArrayList_float64() *ArrayList_float64 { return new(ArrayList_float64) } // NewArrayList_complex64 creates a new ArrayList func NewArrayList_complex64() *ArrayList_complex64 { return new(ArrayList_complex64) } // NewArrayList_complex128 creates a new ArrayList func NewArrayList_complex128() *ArrayList_complex128 { return new(ArrayList_complex128) } // NewArrayList_string creates a new ArrayList func NewArrayList_string() *ArrayList_string { return new(ArrayList_string) } // Add adds an item to the end of the list func (list *ArrayList_int) Add(item int) { list.items = append(list.items, item) } // Add adds an item to the end of the list func (list *ArrayList_int8) Add(item int8) { list.items = append(list.items, item) } // Add adds an item to the end of the list func (list *ArrayList_int16) Add(item int16) { list.items = append(list.items, item) } // Add adds an item to the end of the list func (list *ArrayList_int32) Add(item int32) { list.items = append(list.items, item) } // Add adds an item to the end of the list func (list *ArrayList_int64) Add(item int64) { list.items = append(list.items, item) } // Add adds an item to the end of the list func (list *ArrayList_uint) Add(item uint) { list.items = append(list.items, item) } // Add adds an item to the end of the list func (list *ArrayList_uint8) Add(item uint8) { list.items = append(list.items, item) } // Add adds an item to the end of the list func (list *ArrayList_uint16) Add(item uint16) { list.items = append(list.items, item) } // Add adds an item to the end of the list func (list *ArrayList_uint32) Add(item uint32) { list.items = append(list.items, item) } // Add adds an item to the end of the list func (list *ArrayList_uint64) Add(item uint64) { list.items = append(list.items, item) } // Add adds an item to the end of the list func (list *ArrayList_float32) Add(item float32) { list.items = append(list.items, item) } // Add adds an item to the end of the list func (list *ArrayList_float64) Add(item float64) { list.items = append(list.items, item) } // Add adds an item to the end of the list func (list *ArrayList_complex64) Add(item complex64) { list.items = append(list.items, item) } // Add adds an item to the end of the list func (list *ArrayList_complex128) Add(item complex128) { list.items = append(list.items, item) } // Add adds an item to the end of the list func (list *ArrayList_string) Add(item string) { list.items = append(list.items, item) } // Clear removes all items from the list func (list *ArrayList_int) Clear() { list.items = nil } // Clear removes all items from the list func (list *ArrayList_int8) Clear() { list.items = nil } // Clear removes all items from the list func (list *ArrayList_int16) Clear() { list.items = nil } // Clear removes all items from the list func (list *ArrayList_int32) Clear() { list.items = nil } // Clear removes all items from the list func (list *ArrayList_int64) Clear() { list.items = nil } // Clear removes all items from the list func (list *ArrayList_uint) Clear() { list.items = nil } // Clear removes all items from the list func (list *ArrayList_uint8) Clear() { list.items = nil } // Clear removes all items from the list func (list *ArrayList_uint16) Clear() { list.items = nil } // Clear removes all items from the list func (list *ArrayList_uint32) Clear() { list.items = nil } // Clear removes all items from the list func (list *ArrayList_uint64) Clear() { list.items = nil } // Clear removes all items from the list func (list *ArrayList_float32) Clear() { list.items = nil } // Clear removes all items from the list func (list *ArrayList_float64) Clear() { list.items = nil } // Clear removes all items from the list func (list *ArrayList_complex64) Clear() { list.items = nil } // Clear removes all items from the list func (list *ArrayList_complex128) Clear() { list.items = nil } // Clear removes all items from the list func (list *ArrayList_string) Clear() { list.items = nil } // Contains determines whether an element is in the list func (list *ArrayList_int) Contains(item int) bool { return list.IndexOf(item) >= 0 } // Contains determines whether an element is in the list func (list *ArrayList_int8) Contains(item int8) bool { return list.IndexOf(item) >= 0 } // Contains determines whether an element is in the list func (list *ArrayList_int16) Contains(item int16) bool { return list.IndexOf(item) >= 0 } // Contains determines whether an element is in the list func (list *ArrayList_int32) Contains(item int32) bool { return list.IndexOf(item) >= 0 } // Contains determines whether an element is in the list func (list *ArrayList_int64) Contains(item int64) bool { return list.IndexOf(item) >= 0 } // Contains determines whether an element is in the list func (list *ArrayList_uint) Contains(item uint) bool { return list.IndexOf(item) >= 0 } // Contains determines whether an element is in the list func (list *ArrayList_uint8) Contains(item uint8) bool { return list.IndexOf(item) >= 0 } // Contains determines whether an element is in the list func (list *ArrayList_uint16) Contains(item uint16) bool { return list.IndexOf(item) >= 0 } // Contains determines whether an element is in the list func (list *ArrayList_uint32) Contains(item uint32) bool { return list.IndexOf(item) >= 0 } // Contains determines whether an element is in the list func (list *ArrayList_uint64) Contains(item uint64) bool { return list.IndexOf(item) >= 0 } // Contains determines whether an element is in the list func (list *ArrayList_float32) Contains(item float32) bool { return list.IndexOf(item) >= 0 } // Contains determines whether an element is in the list func (list *ArrayList_float64) Contains(item float64) bool { return list.IndexOf(item) >= 0 } // Contains determines whether an element is in the list func (list *ArrayList_complex64) Contains(item complex64) bool { return list.IndexOf(item) >= 0 } // Contains determines whether an element is in the list func (list *ArrayList_complex128) Contains(item complex128) bool { return list.IndexOf(item) >= 0 } // Contains determines whether an element is in the list func (list *ArrayList_string) Contains(item string) bool { return list.IndexOf(item) >= 0 } // Fill adds all the items to the end of the list func (list *ArrayList_int) Fill(items []int) { list.items = append(list.items, items...) } // Fill adds all the items to the end of the list func (list *ArrayList_int8) Fill(items []int8) { list.items = append(list.items, items...) } // Fill adds all the items to the end of the list func (list *ArrayList_int16) Fill(items []int16) { list.items = append(list.items, items...) } // Fill adds all the items to the end of the list func (list *ArrayList_int32) Fill(items []int32) { list.items = append(list.items, items...) } // Fill adds all the items to the end of the list func (list *ArrayList_int64) Fill(items []int64) { list.items = append(list.items, items...) } // Fill adds all the items to the end of the list func (list *ArrayList_uint) Fill(items []uint) { list.items = append(list.items, items...) } // Fill adds all the items to the end of the list func (list *ArrayList_uint8) Fill(items []uint8) { list.items = append(list.items, items...) } // Fill adds all the items to the end of the list func (list *ArrayList_uint16) Fill(items []uint16) { list.items = append(list.items, items...) } // Fill adds all the items to the end of the list func (list *ArrayList_uint32) Fill(items []uint32) { list.items = append(list.items, items...) } // Fill adds all the items to the end of the list func (list *ArrayList_uint64) Fill(items []uint64) { list.items = append(list.items, items...) } // Fill adds all the items to the end of the list func (list *ArrayList_float32) Fill(items []float32) { list.items = append(list.items, items...) } // Fill adds all the items to the end of the list func (list *ArrayList_float64) Fill(items []float64) { list.items = append(list.items, items...) } // Fill adds all the items to the end of the list func (list *ArrayList_complex64) Fill(items []complex64) { list.items = append(list.items, items...) } // Fill adds all the items to the end of the list func (list *ArrayList_complex128) Fill(items []complex128) { list.items = append(list.items, items...) } // Fill adds all the items to the end of the list func (list *ArrayList_string) Fill(items []string) { list.items = append(list.items, items...) } // Get returns the item at the index in the list func (list *ArrayList_int) Get(idx int) int { return list.items[idx] } // Get returns the item at the index in the list func (list *ArrayList_int8) Get(idx int) int8 { return list.items[idx] } // Get returns the item at the index in the list func (list *ArrayList_int16) Get(idx int) int16 { return list.items[idx] } // Get returns the item at the index in the list func (list *ArrayList_int32) Get(idx int) int32 { return list.items[idx] } // Get returns the item at the index in the list func (list *ArrayList_int64) Get(idx int) int64 { return list.items[idx] } // Get returns the item at the index in the list func (list *ArrayList_uint) Get(idx int) uint { return list.items[idx] } // Get returns the item at the index in the list func (list *ArrayList_uint8) Get(idx int) uint8 { return list.items[idx] } // Get returns the item at the index in the list func (list *ArrayList_uint16) Get(idx int) uint16 { return list.items[idx] } // Get returns the item at the index in the list func (list *ArrayList_uint32) Get(idx int) uint32 { return list.items[idx] } // Get returns the item at the index in the list func (list *ArrayList_uint64) Get(idx int) uint64 { return list.items[idx] } // Get returns the item at the index in the list func (list *ArrayList_float32) Get(idx int) float32 { return list.items[idx] } // Get returns the item at the index in the list func (list *ArrayList_float64) Get(idx int) float64 { return list.items[idx] } // Get returns the item at the index in the list func (list *ArrayList_complex64) Get(idx int) complex64 { return list.items[idx] } // Get returns the item at the index in the list func (list *ArrayList_complex128) Get(idx int) complex128 { return list.items[idx] } // Get returns the item at the index in the list func (list *ArrayList_string) Get(idx int) string { return list.items[idx] } // IndexOf searches for the specified item and returns the // index of the first occurence, or -1 if not found func (list *ArrayList_int) IndexOf(item int) int { for i, t := range list.items { if t == item { return i } } return -1 } // IndexOf searches for the specified item and returns the // index of the first occurence, or -1 if not found func (list *ArrayList_int8) IndexOf(item int8) int { for i, t := range list.items { if t == item { return i } } return -1 } // IndexOf searches for the specified item and returns the // index of the first occurence, or -1 if not found func (list *ArrayList_int16) IndexOf(item int16) int { for i, t := range list.items { if t == item { return i } } return -1 } // IndexOf searches for the specified item and returns the // index of the first occurence, or -1 if not found func (list *ArrayList_int32) IndexOf(item int32) int { for i, t := range list.items { if t == item { return i } } return -1 } // IndexOf searches for the specified item and returns the // index of the first occurence, or -1 if not found func (list *ArrayList_int64) IndexOf(item int64) int { for i, t := range list.items { if t == item { return i } } return -1 } // IndexOf searches for the specified item and returns the // index of the first occurence, or -1 if not found func (list *ArrayList_uint) IndexOf(item uint) int { for i, t := range list.items { if t == item { return i } } return -1 } // IndexOf searches for the specified item and returns the // index of the first occurence, or -1 if not found func (list *ArrayList_uint8) IndexOf(item uint8) int { for i, t := range list.items { if t == item { return i } } return -1 } // IndexOf searches for the specified item and returns the // index of the first occurence, or -1 if not found func (list *ArrayList_uint16) IndexOf(item uint16) int { for i, t := range list.items { if t == item { return i } } return -1 } // IndexOf searches for the specified item and returns the // index of the first occurence, or -1 if not found func (list *ArrayList_uint32) IndexOf(item uint32) int { for i, t := range list.items { if t == item { return i } } return -1 } // IndexOf searches for the specified item and returns the // index of the first occurence, or -1 if not found func (list *ArrayList_uint64) IndexOf(item uint64) int { for i, t := range list.items { if t == item { return i } } return -1 } // IndexOf searches for the specified item and returns the // index of the first occurence, or -1 if not found func (list *ArrayList_float32) IndexOf(item float32) int { for i, t := range list.items { if t == item { return i } } return -1 } // IndexOf searches for the specified item and returns the // index of the first occurence, or -1 if not found func (list *ArrayList_float64) IndexOf(item float64) int { for i, t := range list.items { if t == item { return i } } return -1 } // IndexOf searches for the specified item and returns the // index of the first occurence, or -1 if not found func (list *ArrayList_complex64) IndexOf(item complex64) int { for i, t := range list.items { if t == item { return i } } return -1 } // IndexOf searches for the specified item and returns the // index of the first occurence, or -1 if not found func (list *ArrayList_complex128) IndexOf(item complex128) int { for i, t := range list.items { if t == item { return i } } return -1 } // IndexOf searches for the specified item and returns the // index of the first occurence, or -1 if not found func (list *ArrayList_string) IndexOf(item string) int { for i, t := range list.items { if t == item { return i } } return -1 } // Insert inserts the item into the list at the specified index func (list *ArrayList_int) Insert(idx int, item int) { if idx > len(list.items) { list.Truncate(idx + 1) } list.items[idx] = item } // Insert inserts the item into the list at the specified index func (list *ArrayList_int8) Insert(idx int, item int8) { if idx > len(list.items) { list.Truncate(idx + 1) } list.items[idx] = item } // Insert inserts the item into the list at the specified index func (list *ArrayList_int16) Insert(idx int, item int16) { if idx > len(list.items) { list.Truncate(idx + 1) } list.items[idx] = item } // Insert inserts the item into the list at the specified index func (list *ArrayList_int32) Insert(idx int, item int32) { if idx > len(list.items) { list.Truncate(idx + 1) } list.items[idx] = item } // Insert inserts the item into the list at the specified index func (list *ArrayList_int64) Insert(idx int, item int64) { if idx > len(list.items) { list.Truncate(idx + 1) } list.items[idx] = item } // Insert inserts the item into the list at the specified index func (list *ArrayList_uint) Insert(idx int, item uint) { if idx > len(list.items) { list.Truncate(idx + 1) } list.items[idx] = item } // Insert inserts the item into the list at the specified index func (list *ArrayList_uint8) Insert(idx int, item uint8) { if idx > len(list.items) { list.Truncate(idx + 1) } list.items[idx] = item } // Insert inserts the item into the list at the specified index func (list *ArrayList_uint16) Insert(idx int, item uint16) { if idx > len(list.items) { list.Truncate(idx + 1) } list.items[idx] = item } // Insert inserts the item into the list at the specified index func (list *ArrayList_uint32) Insert(idx int, item uint32) { if idx > len(list.items) { list.Truncate(idx + 1) } list.items[idx] = item } // Insert inserts the item into the list at the specified index func (list *ArrayList_uint64) Insert(idx int, item uint64) { if idx > len(list.items) { list.Truncate(idx + 1) } list.items[idx] = item } // Insert inserts the item into the list at the specified index func (list *ArrayList_float32) Insert(idx int, item float32) { if idx > len(list.items) { list.Truncate(idx + 1) } list.items[idx] = item } // Insert inserts the item into the list at the specified index func (list *ArrayList_float64) Insert(idx int, item float64) { if idx > len(list.items) { list.Truncate(idx + 1) } list.items[idx] = item } // Insert inserts the item into the list at the specified index func (list *ArrayList_complex64) Insert(idx int, item complex64) { if idx > len(list.items) { list.Truncate(idx + 1) } list.items[idx] = item } // Insert inserts the item into the list at the specified index func (list *ArrayList_complex128) Insert(idx int, item complex128) { if idx > len(list.items) { list.Truncate(idx + 1) } list.items[idx] = item } // Insert inserts the item into the list at the specified index func (list *ArrayList_string) Insert(idx int, item string) { if idx > len(list.items) { list.Truncate(idx + 1) } list.items[idx] = item } // Len returns the number of items in the list func (list *ArrayList_int) Len() int { return len(list.items) } // Len returns the number of items in the list func (list *ArrayList_int8) Len() int { return len(list.items) } // Len returns the number of items in the list func (list *ArrayList_int16) Len() int { return len(list.items) } // Len returns the number of items in the list func (list *ArrayList_int32) Len() int { return len(list.items) } // Len returns the number of items in the list func (list *ArrayList_int64) Len() int { return len(list.items) } // Len returns the number of items in the list func (list *ArrayList_uint) Len() int { return len(list.items) } // Len returns the number of items in the list func (list *ArrayList_uint8) Len() int { return len(list.items) } // Len returns the number of items in the list func (list *ArrayList_uint16) Len() int { return len(list.items) } // Len returns the number of items in the list func (list *ArrayList_uint32) Len() int { return len(list.items) } // Len returns the number of items in the list func (list *ArrayList_uint64) Len() int { return len(list.items) } // Len returns the number of items in the list func (list *ArrayList_float32) Len() int { return len(list.items) } // Len returns the number of items in the list func (list *ArrayList_float64) Len() int { return len(list.items) } // Len returns the number of items in the list func (list *ArrayList_complex64) Len() int { return len(list.items) } // Len returns the number of items in the list func (list *ArrayList_complex128) Len() int { return len(list.items) } // Len returns the number of items in the list func (list *ArrayList_string) Len() int { return len(list.items) } // Remove removes the first occurence of the item from the list func (list *ArrayList_int) Remove(item int) { idx := list.IndexOf(item) if idx < 0 { return } list.RemoveAt(idx) } // Remove removes the first occurence of the item from the list func (list *ArrayList_int8) Remove(item int8) { idx := list.IndexOf(item) if idx < 0 { return } list.RemoveAt(idx) } // Remove removes the first occurence of the item from the list func (list *ArrayList_int16) Remove(item int16) { idx := list.IndexOf(item) if idx < 0 { return } list.RemoveAt(idx) } // Remove removes the first occurence of the item from the list func (list *ArrayList_int32) Remove(item int32) { idx := list.IndexOf(item) if idx < 0 { return } list.RemoveAt(idx) } // Remove removes the first occurence of the item from the list func (list *ArrayList_int64) Remove(item int64) { idx := list.IndexOf(item) if idx < 0 { return } list.RemoveAt(idx) } // Remove removes the first occurence of the item from the list func (list *ArrayList_uint) Remove(item uint) { idx := list.IndexOf(item) if idx < 0 { return } list.RemoveAt(idx) } // Remove removes the first occurence of the item from the list func (list *ArrayList_uint8) Remove(item uint8) { idx := list.IndexOf(item) if idx < 0 { return } list.RemoveAt(idx) } // Remove removes the first occurence of the item from the list func (list *ArrayList_uint16) Remove(item uint16) { idx := list.IndexOf(item) if idx < 0 { return } list.RemoveAt(idx) } // Remove removes the first occurence of the item from the list func (list *ArrayList_uint32) Remove(item uint32) { idx := list.IndexOf(item) if idx < 0 { return } list.RemoveAt(idx) } // Remove removes the first occurence of the item from the list func (list *ArrayList_uint64) Remove(item uint64) { idx := list.IndexOf(item) if idx < 0 { return } list.RemoveAt(idx) } // Remove removes the first occurence of the item from the list func (list *ArrayList_float32) Remove(item float32) { idx := list.IndexOf(item) if idx < 0 { return } list.RemoveAt(idx) } // Remove removes the first occurence of the item from the list func (list *ArrayList_float64) Remove(item float64) { idx := list.IndexOf(item) if idx < 0 { return } list.RemoveAt(idx) } // Remove removes the first occurence of the item from the list func (list *ArrayList_complex64) Remove(item complex64) { idx := list.IndexOf(item) if idx < 0 { return } list.RemoveAt(idx) } // Remove removes the first occurence of the item from the list func (list *ArrayList_complex128) Remove(item complex128) { idx := list.IndexOf(item) if idx < 0 { return } list.RemoveAt(idx) } // Remove removes the first occurence of the item from the list func (list *ArrayList_string) Remove(item string) { idx := list.IndexOf(item) if idx < 0 { return } list.RemoveAt(idx) } // RemoveAt removes the element at the specified index of the list func (list *ArrayList_int) RemoveAt(idx int) { list.items = append(list.items[:idx], list.items[idx+1:]...) if cap(list.items) > 2*len(list.items) { list.Truncate(len(list.items)) } } // RemoveAt removes the element at the specified index of the list func (list *ArrayList_int8) RemoveAt(idx int) { list.items = append(list.items[:idx], list.items[idx+1:]...) if cap(list.items) > 2*len(list.items) { list.Truncate(len(list.items)) } } // RemoveAt removes the element at the specified index of the list func (list *ArrayList_int16) RemoveAt(idx int) { list.items = append(list.items[:idx], list.items[idx+1:]...) if cap(list.items) > 2*len(list.items) { list.Truncate(len(list.items)) } } // RemoveAt removes the element at the specified index of the list func (list *ArrayList_int32) RemoveAt(idx int) { list.items = append(list.items[:idx], list.items[idx+1:]...) if cap(list.items) > 2*len(list.items) { list.Truncate(len(list.items)) } } // RemoveAt removes the element at the specified index of the list func (list *ArrayList_int64) RemoveAt(idx int) { list.items = append(list.items[:idx], list.items[idx+1:]...) if cap(list.items) > 2*len(list.items) { list.Truncate(len(list.items)) } } // RemoveAt removes the element at the specified index of the list func (list *ArrayList_uint) RemoveAt(idx int) { list.items = append(list.items[:idx], list.items[idx+1:]...) if cap(list.items) > 2*len(list.items) { list.Truncate(len(list.items)) } } // RemoveAt removes the element at the specified index of the list func (list *ArrayList_uint8) RemoveAt(idx int) { list.items = append(list.items[:idx], list.items[idx+1:]...) if cap(list.items) > 2*len(list.items) { list.Truncate(len(list.items)) } } // RemoveAt removes the element at the specified index of the list func (list *ArrayList_uint16) RemoveAt(idx int) { list.items = append(list.items[:idx], list.items[idx+1:]...) if cap(list.items) > 2*len(list.items) { list.Truncate(len(list.items)) } } // RemoveAt removes the element at the specified index of the list func (list *ArrayList_uint32) RemoveAt(idx int) { list.items = append(list.items[:idx], list.items[idx+1:]...) if cap(list.items) > 2*len(list.items) { list.Truncate(len(list.items)) } } // RemoveAt removes the element at the specified index of the list func (list *ArrayList_uint64) RemoveAt(idx int) { list.items = append(list.items[:idx], list.items[idx+1:]...) if cap(list.items) > 2*len(list.items) { list.Truncate(len(list.items)) } } // RemoveAt removes the element at the specified index of the list func (list *ArrayList_float32) RemoveAt(idx int) { list.items = append(list.items[:idx], list.items[idx+1:]...) if cap(list.items) > 2*len(list.items) { list.Truncate(len(list.items)) } } // RemoveAt removes the element at the specified index of the list func (list *ArrayList_float64) RemoveAt(idx int) { list.items = append(list.items[:idx], list.items[idx+1:]...) if cap(list.items) > 2*len(list.items) { list.Truncate(len(list.items)) } } // RemoveAt removes the element at the specified index of the list func (list *ArrayList_complex64) RemoveAt(idx int) { list.items = append(list.items[:idx], list.items[idx+1:]...) if cap(list.items) > 2*len(list.items) { list.Truncate(len(list.items)) } } // RemoveAt removes the element at the specified index of the list func (list *ArrayList_complex128) RemoveAt(idx int) { list.items = append(list.items[:idx], list.items[idx+1:]...) if cap(list.items) > 2*len(list.items) { list.Truncate(len(list.items)) } } // RemoveAt removes the element at the specified index of the list func (list *ArrayList_string) RemoveAt(idx int) { list.items = append(list.items[:idx], list.items[idx+1:]...) if cap(list.items) > 2*len(list.items) { list.Truncate(len(list.items)) } } // Reverse reverses the list func (list *ArrayList_int) Reverse() { Reverse(list) } // Reverse reverses the list func (list *ArrayList_int8) Reverse() { Reverse(list) } // Reverse reverses the list func (list *ArrayList_int16) Reverse() { Reverse(list) } // Reverse reverses the list func (list *ArrayList_int32) Reverse() { Reverse(list) } // Reverse reverses the list func (list *ArrayList_int64) Reverse() { Reverse(list) } // Reverse reverses the list func (list *ArrayList_uint) Reverse() { Reverse(list) } // Reverse reverses the list func (list *ArrayList_uint8) Reverse() { Reverse(list) } // Reverse reverses the list func (list *ArrayList_uint16) Reverse() { Reverse(list) } // Reverse reverses the list func (list *ArrayList_uint32) Reverse() { Reverse(list) } // Reverse reverses the list func (list *ArrayList_uint64) Reverse() { Reverse(list) } // Reverse reverses the list func (list *ArrayList_float32) Reverse() { Reverse(list) } // Reverse reverses the list func (list *ArrayList_float64) Reverse() { Reverse(list) } // Reverse reverses the list func (list *ArrayList_complex64) Reverse() { Reverse(list) } // Reverse reverses the list func (list *ArrayList_complex128) Reverse() { Reverse(list) } // Reverse reverses the list func (list *ArrayList_string) Reverse() { Reverse(list) } // Swap swaps items in the list func (list *ArrayList_int) Swap(i, j int) { list.items[i], list.items[j] = list.items[j], list.items[i] } // Swap swaps items in the list func (list *ArrayList_int8) Swap(i, j int) { list.items[i], list.items[j] = list.items[j], list.items[i] } // Swap swaps items in the list func (list *ArrayList_int16) Swap(i, j int) { list.items[i], list.items[j] = list.items[j], list.items[i] } // Swap swaps items in the list func (list *ArrayList_int32) Swap(i, j int) { list.items[i], list.items[j] = list.items[j], list.items[i] } // Swap swaps items in the list func (list *ArrayList_int64) Swap(i, j int) { list.items[i], list.items[j] = list.items[j], list.items[i] } // Swap swaps items in the list func (list *ArrayList_uint) Swap(i, j int) { list.items[i], list.items[j] = list.items[j], list.items[i] } // Swap swaps items in the list func (list *ArrayList_uint8) Swap(i, j int) { list.items[i], list.items[j] = list.items[j], list.items[i] } // Swap swaps items in the list func (list *ArrayList_uint16) Swap(i, j int) { list.items[i], list.items[j] = list.items[j], list.items[i] } // Swap swaps items in the list func (list *ArrayList_uint32) Swap(i, j int) { list.items[i], list.items[j] = list.items[j], list.items[i] } // Swap swaps items in the list func (list *ArrayList_uint64) Swap(i, j int) { list.items[i], list.items[j] = list.items[j], list.items[i] } // Swap swaps items in the list func (list *ArrayList_float32) Swap(i, j int) { list.items[i], list.items[j] = list.items[j], list.items[i] } // Swap swaps items in the list func (list *ArrayList_float64) Swap(i, j int) { list.items[i], list.items[j] = list.items[j], list.items[i] } // Swap swaps items in the list func (list *ArrayList_complex64) Swap(i, j int) { list.items[i], list.items[j] = list.items[j], list.items[i] } // Swap swaps items in the list func (list *ArrayList_complex128) Swap(i, j int) { list.items[i], list.items[j] = list.items[j], list.items[i] } // Swap swaps items in the list func (list *ArrayList_string) Swap(i, j int) { list.items[i], list.items[j] = list.items[j], list.items[i] } // Truncate changes the size of the list to sz, any excess items are removed func (list *ArrayList_int) Truncate(sz int) { items := make([]int, sz) copy(items, list.items) list.items = items } // Truncate changes the size of the list to sz, any excess items are removed func (list *ArrayList_int8) Truncate(sz int) { items := make([]int8, sz) copy(items, list.items) list.items = items } // Truncate changes the size of the list to sz, any excess items are removed func (list *ArrayList_int16) Truncate(sz int) { items := make([]int16, sz) copy(items, list.items) list.items = items } // Truncate changes the size of the list to sz, any excess items are removed func (list *ArrayList_int32) Truncate(sz int) { items := make([]int32, sz) copy(items, list.items) list.items = items } // Truncate changes the size of the list to sz, any excess items are removed func (list *ArrayList_int64) Truncate(sz int) { items := make([]int64, sz) copy(items, list.items) list.items = items } // Truncate changes the size of the list to sz, any excess items are removed func (list *ArrayList_uint) Truncate(sz int) { items := make([]uint, sz) copy(items, list.items) list.items = items } // Truncate changes the size of the list to sz, any excess items are removed func (list *ArrayList_uint8) Truncate(sz int) { items := make([]uint8, sz) copy(items, list.items) list.items = items } // Truncate changes the size of the list to sz, any excess items are removed func (list *ArrayList_uint16) Truncate(sz int) { items := make([]uint16, sz) copy(items, list.items) list.items = items } // Truncate changes the size of the list to sz, any excess items are removed func (list *ArrayList_uint32) Truncate(sz int) { items := make([]uint32, sz) copy(items, list.items) list.items = items } // Truncate changes the size of the list to sz, any excess items are removed func (list *ArrayList_uint64) Truncate(sz int) { items := make([]uint64, sz) copy(items, list.items) list.items = items } // Truncate changes the size of the list to sz, any excess items are removed func (list *ArrayList_float32) Truncate(sz int) { items := make([]float32, sz) copy(items, list.items) list.items = items } // Truncate changes the size of the list to sz, any excess items are removed func (list *ArrayList_float64) Truncate(sz int) { items := make([]float64, sz) copy(items, list.items) list.items = items } // Truncate changes the size of the list to sz, any excess items are removed func (list *ArrayList_complex64) Truncate(sz int) { items := make([]complex64, sz) copy(items, list.items) list.items = items } // Truncate changes the size of the list to sz, any excess items are removed func (list *ArrayList_complex128) Truncate(sz int) { items := make([]complex128, sz) copy(items, list.items) list.items = items } // Truncate changes the size of the list to sz, any excess items are removed func (list *ArrayList_string) Truncate(sz int) { items := make([]string, sz) copy(items, list.items) list.items = items }
JavaScript
UTF-8
424
3.1875
3
[]
no_license
var x=document.getElementById("text"); console.log(x.innerHTML); var tag=document.getElementsByTagName("h1")[1]; console.log(tag.innerHTML); var input=document.getElementsByName("my name")[0] console.log(input.type); var span = document.getElementsByClassName("clas")[0] console.log(span.innerHTML) var button=document.getElementById("btn") button.onclick=function(){ span.style.background="red" console.log(input.value) }
Go
UTF-8
237
2.9375
3
[]
no_license
package main import "net/http" // http.ListenAndServe() じゃなくて http.Server を直接使う場合 func main() { server := http.Server{Addr: "", Handler: nil} err := server.ListenAndServe() if err != nil { panic(err) } }
Markdown
UTF-8
1,604
3.8125
4
[]
no_license
#### 0598.范围求和 II [题目链接](https://leetcode-cn.com/problems/range-addition-ii) > 给定一个初始元素全部为 **0**,大小为 m*n 的矩阵 **M** 以及在 **M** 上的一系列更新操作。 > > 操作用二维数组表示,其中的每个操作用一个含有两个**正整数 a** 和 **b** 的数组表示,含义是将所有符合 **0 <= i < a** 以及 **0 <= j < b** 的元素 **M[i][j]** 的值都**增加 1**。 > > 在执行给定的一系列操作后,你需要返回矩阵中含有最大整数的元素个数。 > > **示例 1:** > > ` > 输入: > m = 3, n = 3 > operations = [[2,2],[3,3]] > 输出: 4 > 解释: > 初始状态, M = > [[0, 0, 0], > [0, 0, 0], > [0, 0, 0]] > > 执行完操作 [2,2] 后, M = > [[1, 1, 0], > [1, 1, 0], > [0, 0, 0]] > > 执行完操作 [3,3] 后, M = > [[2, 2, 1], > [2, 2, 1], > [1, 1, 1]] > > M 中最大的整数是 2, 而且 M 中有4个值为2的元素。因此返回 4。 > ` > > **注意:** > > 1. m 和 n 的范围是 [1,40000]。 > 2. a 的范围是 [1,m],b 的范围是 [1,n]。 > 3. 操作数目不超过 10000。 **简单思路** 每次都是从左上角开始不停取交,所以找出`ops`中最小的行和最小的列,其乘积即为答案。时间复杂度$O(n)$,这里$n$为操作次数,空间复杂度为$O(1)$,执行时间60ms ```python class Solution: def maxCount(self, m: int, n: int, ops: List[List[int]]) -> int: min_a, min_b = m, n for a, b in ops: min_a = min(min_a, a) min_b = min(min_b, b) return min_a * min_b ```
Java
UTF-8
504
2.578125
3
[]
no_license
package resume; import java.util.ArrayList; import java.util.Scanner; public class Main { public static void main(String[] args) { ArrayList<PersonData> myArrayList = new ArrayList<PersonData>(); PersonData personData = new PersonData(); personData.setName("Genzeb"); personData.setEmail("genzeb@gmail.com"); System.out.printf("%s, \n%s", personData.getName(), personData.getEmail()); ArrayList<Education> myEducations = new ArrayList<>(); } }
SQL
UTF-8
1,780
4.03125
4
[]
no_license
create table Department( ID int primary key, DEPT_NAME varchar(50) not null, LOCATION varchar(50) not null, SUPERVISOR varchar(50) ); insert into Department values (801,'CSE','Rajshahi','Nur E Alam'); insert into Department values(802,'EEE','Dhaka','Faisal Imran'); insert into Department values(803,'CIVIL','Khulna','Meraj Ali'); insert into Department values(804,'MECHANICAL','Chittagong','Sanjir Shishir'); select * from Department; create table Student2( ID int primary key, NAME varchar(50) not null, GENDER varchar(50) not null, EXPECTED_SALARY int not null, DEPT_ID int, foreign key (DEPT_ID) references Department (ID) ); insert into Student2 values (101,'Tamim','Male',44000,801); insert into Student2 values(102,'Rupom','Male',43000,803); insert into Student2 values(103,'Mijan','Male',45000,801); insert into student2 values(104,'Tareq','Male',42000,802); insert into Student2 values(105,'Saudia','Female',48000,802); insert into Student2 values(106,'Rima','Female',47000,801); insert into Student2 values(107,'Naima','Female',45500,803); insert into Student2 values(108,'Sanjida','Female',43500,801); insert into Student2 values(109,'Khushi','Female',48500,null); insert into Student2 values(110,'Pronob','Male',48000,null); select * from Student2; select DEPT_NAME,max (EXPECTED_SALARY) from Student2 group by DEPT_NAME having max(EXPECTED_SALARY); update Student2 set EXPECTED_SALARY=EXPECTED_SALARY*1.05 where EXPECTED_SALARY>(select avg(EXPECTED_SALARY) from Student2); select * from Department inner join Student2 on DEPARTMENT.ID=STUDENT2.DEPT_ID; select * from Department left outer join Student2 on DEPARTMENT.ID=STUDENT2.DEPT_ID; select Student2.NAME,Department.SUPERVISOR from Student2 where Department.DEPT_NAME='CSE' and Student2.EXPECTED_SALARY>43000;
PHP
UTF-8
2,139
2.609375
3
[ "BSD-3-Clause" ]
permissive
<?php namespace common\models; use Yii; use yii\data\ActiveDataProvider; /** * This is the model class for table "favorite". * * @property int $user_id * @property int $post_id * @property int $add_time * @property int $type */ class Favorite extends \yii\db\ActiveRecord { const TYPE_LAUD=1; const TYPE_FAVORITE=2; /** * {@inheritdoc} */ public static function tableName() { return 'favorite'; } /** * {@inheritdoc} */ public function rules() { return [ [['user_id', 'post_id', 'add_time', 'type'], 'integer'], ]; } /** * {@inheritdoc} */ public function attributeLabels() { return [ 'user_id' => '用户ID', 'post_id' => '文章ID', 'add_time' => '添加时间', 'type' => '类型', ]; } public function beforeSave($insert) { if(parent::beforeSave($insert)) { if($insert) { $this->add_time = time(); } return true; } else { return false; } } public function getPost() { return $this->hasOne(Post::className(), ['id' => 'post_id']); } public function favoritePost() { $uid = Yii::$app->user->id; $type = Favorite::TYPE_FAVORITE; $query = Favorite::find()->where("type={$type} and user_id={$uid}"); $dataProvider = new ActiveDataProvider([ 'query' => $query, 'pagination'=>['pageSize'=>5], 'sort'=>[ 'defaultOrder'=>[ 'add_time'=>SORT_DESC, ], ] ]); return $dataProvider; } static public function getFavStatus($type = Favorite::TYPE_FAVORITE,$post_id = 0) { $uid = Yii::$app->user->id; $data = Favorite::find()->where("type={$type} and user_id={$uid} and post_id = {$post_id}")->one(); if (empty($data)){ return false; }else{ return true; } } }
Shell
UTF-8
4,219
2.625
3
[]
no_license
#!/bin/bash cat <<-EOF > /tmp/mcdata/mapcache-source.xml <?xml version="1.0" encoding="UTF-8"?> <mapcache> EOF cat <<-EOF > /var/www/html/mapcache-sandbox-browser/mapcache-source.js var mapcache_source = new ol.layer.Group({ title: 'Sources externes', fold: 'open' }); layers.unshift(mapcache_source) EOF for source in \ "HeiGIT&OSM&https://maps.heigit.org/osm-wms/service?&osm_auto:all" \ "Mundialis&OSM&http://ows.mundialis.de/services/service?&OSM-WMS" \ "Terrestris&OSM&http://ows.terrestris.de/osm/service?&OSM-WMS" \ "Stamen&Terrain&http://tile.stamen.com/terrain/{z}/{x}/{inv_y}.png&<rest>" \ "Stamen&Watercolor&http://tile.stamen.com/watercolor/{z}/{x}/{inv_y}.jpg&<rest>" \ "GIBS&Blue Marble - Relief&https://gibs.earthdata.nasa.gov/wms/epsg3857/best/wms.cgi?&BlueMarble_ShadedRelief_Bathymetry" \ "ESRI&World Imagery&https://clarity.maptiles.arcgis.com/arcgis/rest/services/World_Imagery/MapServer/tile/{z}/{inv_y}/{x}&<rest>" \ "NOAA&Dark Gray&https://server.arcgisonline.com/arcgis/rest/services/Canvas/World_Dark_Gray_Base/MapServer/tile/{z}/{inv_y}/{x}&<rest>" \ "AJAston&Pirate Map&http://d.tiles.mapbox.com/v3/aj.Sketchy2/{z}/{x}/{inv_y}.png&<rest maxzoom=\"6\">" \ "MakinaCorpus&Toulouse Pencil&https://d-tiles-vuduciel2.makina-corpus.net/toulouse-hand-drawn/{z}/{x}/{inv_y}.png&<rest minzoom=\"13\" maxzoom=\"18\" minx=\"136229\" miny=\"5386020\" maxx=\"182550\" maxy=\"5419347\">" do IFS='&' read provider name url layer <<< "${source}" lprovider=$(tr [:upper:] [:lower:] <<< ${provider}) mclayer=$(tr [:upper:] [:lower:] <<< "${provider}-${name}" | sed 's/ //g') jslayer=$(tr '-' '_' <<< ${mclayer}) if grep -q -v ${provider} <<< ${providers} then providers=${providers}:${provider} cat <<-EOF >> /var/www/html/mapcache-sandbox-browser/mapcache-source.js var mapcache_source_${lprovider} = new ol.layer.Group({ title: '${provider}', fold: 'close' }); mapcache_source.getLayers().array_.unshift(mapcache_source_${lprovider}); EOF fi cat <<-EOF >> /var/www/html/mapcache-sandbox-browser/mapcache-source.js var ${jslayer} = new ol.layer.Tile({ title: '${name}', type: 'base', visible: false, source: new ol.source.TileWMS({ url: 'http://'+location.host+'/mapcache-source?', params: {'LAYERS': '${mclayer}', 'VERSION': '1.1.1'} }) }); mapcache_source_${lprovider}.getLayers().array_.unshift(${jslayer}); EOF if grep -q -v "<rest" <<< "${layer}" then cat <<-EOF >> /tmp/mcdata/mapcache-source.xml <!-- ${mclayer} --> <source name="${mclayer}" type="wms"> <http><url>${url}</url></http> <getmap><params> <format>image/png</format> <layers>${layer}</layers> </params></getmap> </source> EOF else gridopt=$(sed 's/^.*<rest\(.*\)>$/\1/' <<< "${layer}") cat <<-EOF >> /tmp/mcdata/mapcache-source.xml <!-- ${mclayer} --> <cache name="remote-${mclayer}" type="rest"> <url>${url}</url> </cache> <tileset name="remote-${mclayer}"> <cache>remote-${mclayer}</cache> <grid>GoogleMapsCompatible</grid> </tileset> <source name="${mclayer}" type="wms"> <http><url>http://localhost:80/mapcache-source?</url></http> <getmap><params> <format>image/png</format> <layers>remote-${mclayer}</layers> </params></getmap> </source> EOF fi cat <<-EOF >> /tmp/mcdata/mapcache-source.xml <cache name="${mclayer}" type="sqlite3"> <dbfile>/share/caches/source/${mclayer}.sqlite3</dbfile> </cache> <tileset name="${mclayer}"> <source>${mclayer}</source> <format>PNG</format> <cache>${mclayer}</cache> <grid${gridopt}>GoogleMapsCompatible</grid> </tileset> EOF done cat <<-EOF >> /tmp/mcdata/mapcache-source.xml <service type="wmts" enabled="true"/> <service type="wms" enabled="true"> <maxsize>4096</maxsize> </service> <log_level>debug</log_level> <threaded_fetching>true</threaded_fetching> </mapcache> EOF cat <<-EOF > /etc/apache2/conf-enabled/mapcache-source.conf <IfModule mapcache_module> MapCacheAlias "/mapcache-source" "/tmp/mcdata/mapcache-source.xml" </IfModule> EOF gawk -i inplace '/anchor/&&c==0{print l};{print}' \ l='<script src="mapcache-source.js"></script>' \ /var/www/html/mapcache-sandbox-browser/index.html
Markdown
UTF-8
590
3.53125
4
[ "MIT" ]
permissive
## Problem 389 of Euler Project https://www.projecteuler.net/problem=389 An unbiased single 4-sided die is thrown and its value, T, is noted.T unbiased 6-sided dice are thrown and their scores are added together. The sum, C, is noted.C unbiased 8-sided dice are thrown and their scores are added together. The sum, O, is noted.O unbiased 12-sided dice are thrown and their scores are added together. The sum, D, is noted.D unbiased 20-sided dice are thrown and their scores are added together. The sum, I, is noted. Find the variance of I, and give your answer rounded to 4 decimal places.
C++
UTF-8
4,144
3.53125
4
[ "MIT" ]
permissive
/* ============================================================================== Interpolator.h Created: 1 Aug 2018 6:34:02pm Author: stefa ============================================================================== */ #pragma once #include <vector> #include <cassert> namespace Interpolation { template<typename T = double> class Interpolator { public: virtual ~Interpolator() {} // Requires only the last sample, but assumes that previous samples are constantly updated virtual const T& ShiftInterpolate(const T& alpha, const T& sample) = 0; // Requires the entire array of samples to be interpolated virtual const T& Interpolate(const T& alpha, const std::vector<T>& samples) = 0; protected: Interpolator(const int& numSamples) : mSamples(std::vector<T>(numSamples, 0)) {} void ShiftSamples(const T& newSample) { // Shift old samples one position to the left std::rotate(mSamples.begin(), mSamples.begin() + 1, mSamples.end()); // Add newSample in the last (rightmost) position mSamples.back() = newSample; } std::vector<T> mSamples; // Array of samples around the interpolation point private: Interpolator() {}; }; template<typename T = double> class LinearInterpolator : public Interpolator<> { public: LinearInterpolator() : Interpolator(mSamplesSize) {} ~LinearInterpolator() override {} const T& ShiftInterpolate(const T& alpha, const T& sample) override { this->ShiftSamples(sample); return this->mSamples[0] + alpha*(this->mSamples[1] - this->mSamples[0]); } const T& Interpolate(const T& alpha, const std::vector<T>& samples) override { assert(samples.size() == mSamplesSize); this->mSamples = samples; return this->mSamples[0] + alpha*(this->mSamples[1] - this->mSamples[0]); } private: static const int mSamplesSize = 2; }; template<typename T = double> class QuadraticInterpolator : public Interpolator<T> { public: QuadraticInterpolator() : Interpolator(mSamplesSize) {} ~QuadraticInterpolator() override {} const T& ShiftInterpolate(const T& alpha, const T& sample) override { ShiftSamples(sample); return this->mSamples[1] + 0.5*alpha*(this->mSamples[2] - this->mSamples[0] + alpha*(this->mSamples[2] - 2 * this->mSamples[1] + this->mSamples[0])); } const T& Interpolate(const T& alpha, const std::vector<T>& samples) override { assert(samples.size() == mSamplesSize); this->mSamples = samples; return this->mSamples[1] + 0.5*alpha*(this->mSamples[2] - this->mSamples[0] + alpha*(this->mSamples[2] - 2 * this->mSamples[1] + this->mSamples[0])); } private: static const int mSamplesSize = 3; }; template<typename T = double> class CubicInterpolator : public Interpolator<T> { public: CubicInterpolator() : Interpolator(mSamplesSize) {} ~CubicInterpolator() override {} const T& ShiftInterpolate(const T& alpha, const T& sample) override { ShiftSamples(sample); return this->mSamples[1] + 0.5*alpha*(this->mSamples[2] - this->mSamples[0] + alpha*(2.0*this->mSamples[0] - 5.0*this->mSamples[1] + 4.0*this->mSamples[2] - this->mSamples[3] + alpha*(3.0*(this->mSamples[1] - this->mSamples[2]) + this->mSamples[3] - this->mSamples[0]))); } const T& Interpolate(const T& alpha, const std::vector<T>& samples) override { assert(samples.size() == mSamplesSize); this->mSamples = samples; return this->mSamples[1] + 0.5*alpha*(this->mSamples[2] - this->mSamples[0] + alpha*(2.0*this->mSamples[0] - 5.0*this->mSamples[1] + 4.0*this->mSamples[2] - this->mSamples[3] + alpha*(3.0*(this->mSamples[1] - this->mSamples[2]) + this->mSamples[3] - this->mSamples[0]))); } private: static const int mSamplesSize = 4; }; // Linear // y = p[0] + a*(p[1] - p[0]); // Quadratic // y = p[1] + 0.5*a*(p[2] - p[0] + a*(p[2] - 2 * p[1] + p[0])); // Cubic // y = p[1] + 0.5*a*(p[2] - p[0] + a*(2.0*p[0] - 5.0*p[1] + 4.0*p[2] - p[3] + a*(3.0*(p[1] - p[2]) + p[3] - p[0]))); }
C#
UTF-8
494
2.609375
3
[]
no_license
using UnityEngine; public class SimpleBullet : MonoBehaviour { float speed = 10, lifeTime = 0.5f, dist = 10000, spawnTime = 0; private Transform tr; void OnEnable() { tr = transform; spawnTime = Time.time; } void Update() { tr.position += tr.forward * speed * Time.deltaTime; dist -= speed * Time.deltaTime; if (Time.time > spawnTime + lifeTime || dist < 0) { Destroy(gameObject); } } }
C++
UTF-8
1,142
3.09375
3
[]
no_license
#include <iostream> using namespace std; template <typename T> struct TypeTrait { enum { typeid_ = -1 }; }; #define DEFINE_TRAIT(type, id) \ template <> \ struct TypeTrait<type> { \ enum { typeid_ = id}; \ }; DEFINE_TRAIT(int, 1); DEFINE_TRAIT(float, 2); DEFINE_TRAIT(double, 3); // prevent compiler warning because variable unused template <typename X> void no_unused_warning(X x) {} template <typename T> void foo(const T& v) { //// Compile-time type filtering //char Invalid_Argument_DataType_To_foo[TypeTrait<T>::typeid_]; //no_unused_warning(Invalid_Argument_DataType_To_foo); // Runtime type identification switch (TypeTrait<T>::typeid_) { case TypeTrait<int>::typeid_: cout << "Receive integer" << endl; break; case TypeTrait<float>::typeid_: cout << "Receive float" << endl; break; case TypeTrait<double>::typeid_: cout << "Receive double" << endl; break; default: cout << "Receive unknown type" << endl; } // ... } int main(int argc, char *argv[]) { foo(1); foo(1.0f); foo(1.0); foo(static_cast<short>(1)); return 0; }
Markdown
UTF-8
1,359
4
4
[]
no_license
### [1.Two Sum](https://github.com/MorrisLee000/Practice/blob/master/Leetcode/1%23_Two%20Sum_06170243.py) * 在寫Two Sum 我先設置一個空list,因為在最後還傳出來的東西會是一個list裡面包含兩個答案,然後設迴圈去尋找答案。 ### [7.Reverse Interger](https://github.com/MorrisLee000/Practice/blob/master/Leetcode/7%23_Reverse%20Interger_06170243.py) * 先把數字取絕對值再轉換成str去倒著排回來,python取值的範圍是-2**31 ~ 2**31-1,然後比較她是大於0還是小於0,去決定要不要加上負號。 ### [9.Palindrome Number](https://github.com/MorrisLee000/Practice/blob/master/Leetcode/9%23_Palindrome%20Number_06170243.py) * 這題跟7.一樣,但是這題回傳的是判斷使否倒過來相同。 ### [3.Roman to Integer](https://github.com/MorrisLee000/Practice/blob/master/Leetcode/13%23_Roman%20to%20Integer_06170243.py) * 先設一個東西來把表示該符號代表的數字,然後用迴圈去判斷那應該要減還是加,需要先設一個變數,最後回傳加減過的數字。 ### [27.Remove Element](https://github.com/MorrisLee000/Practice/blob/master/Leetcode/27%23_Remove%20Element_06170243.py) * 用while count去判斷是否有要刪除的數字,有的話進入list裡面找,找到後刪除,再重新跑一次,因為不知道有沒有重複。
C#
UTF-8
2,218
3.765625
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Verk_1 { class Program { public static int duplicatesLetters(string input) { SortedDictionary<char, int> repeats = new SortedDictionary<char, int>(); for (int i = 0; i < input.Length; i++) { if (repeats.ContainsKey(input[i])) { repeats[input[i]]++; } else { repeats.Add(input[i], 1); } } Console.WriteLine("Letter amount"); for (int i = 0; i < repeats.Count; i++) { //Console.WriteLine("{0} {1}", i, repeats[i]); } foreach (var key in repeats.Keys) { Console.WriteLine("{0,-12}{1,-12}", key, repeats[key]); } return repeats.Count; } public static int duplicatesWords(string input) { SortedDictionary<string, int> repeats = new SortedDictionary<string, int>(); string[] words = input.Split(' '); int numRepeats = 0;//counts the number of repeats for (int i = 0; i < words.Length; i++) { if (repeats.ContainsKey(words[i])) { repeats[words[i]]++; } else { repeats.Add(words[i], 0); } } foreach (var amount in repeats.Values) { numRepeats =numRepeats + amount; } return numRepeats; } static void Main(string[] args) { Console.WriteLine("Please enter a sentence"); string input = Console.ReadLine().ToLower(); Console.WriteLine("There are {0} repeats in your text", duplicatesWords(input)); Console.WriteLine(); Console.WriteLine("counting the occurance of each letter"); duplicatesLetters(input); Console.ReadLine(); } } }
Java
UTF-8
749
1.726563
2
[]
no_license
package code.expressionlanguage.exec.opers; import code.expressionlanguage.Argument; import code.expressionlanguage.ContextEl; import code.expressionlanguage.exec.StackCall; import code.expressionlanguage.exec.variables.ArgumentsPair; import code.expressionlanguage.fwd.opers.ExecOperationContent; import code.util.IdMap; public final class ExecArgumentListInstancing extends ExecMethodOperation implements AtomicExecCalculableOperation { public ExecArgumentListInstancing(ExecOperationContent _m) { super(_m); } @Override public void calculate(IdMap<ExecOperationNode, ArgumentsPair> _nodes, ContextEl _conf, StackCall _stack) { setQuickNoConvertSimpleArgument(Argument.createVoid(),_conf,_nodes,_stack); } }
C#
UTF-8
418
2.90625
3
[]
no_license
using System; namespace BehaviorTree { [Serializable] public class BlackboardKey<T> { private T param; public BlackboardKey(T value) { param = value; } public void SetValue(T value) { param = value; } public T GetValue() { return param; } public void Nullify() { param = default(T); } public bool IsSet() { return !param.Equals(default(T)); } } }
Java
UTF-8
3,125
2.4375
2
[]
no_license
package services; import dao.EventPointDAO; import dao.EventPointDAOImpl; import models.EventPoint; import models.User; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import util.DBHelper; import java.util.List; public class EventPoinServiceImpl implements EventPoinService { private final EventPointDAO eventPointDAO; private static volatile EventPoinServiceImpl instance; private EventPoinServiceImpl() { this.eventPointDAO = new EventPointDAOImpl(createSessionFactory(DBHelper.getConfiguration())); } public static EventPoinServiceImpl getInstance() { if (instance == null) { synchronized (EventPoinServiceImpl.class) { if (instance == null) { instance = new EventPoinServiceImpl(); } } } return instance; } @Override public EventPoint getById(long id) { return eventPointDAO.getById(id); } @Override public EventPoint getByName(String name) { return eventPointDAO.getByName(name); } @Override public Long add(EventPoint eventPoint) { Long eventPointID = eventPointDAO.add(eventPoint); if (eventPointID == null) { System.out.println("HotPoint " + eventPoint.getName() + " is allready exist!"); return getByName(eventPoint.getName()).getId(); } return eventPointID; } @Override public void update(EventPoint eventPoint) { eventPointDAO.update(eventPoint); } @Override public void remove(long id) { eventPointDAO.remove(id); } @Override public List<EventPoint> getAllList() { return eventPointDAO.getAllList(); } @Override public List<EventPoint> getAllByFestival (long id) { return eventPointDAO.getAllByFestival(id); } @Override public List<EventPoint> getAllEventPointByFestivalId(long festivalId) { return eventPointDAO.getAllEventPointByFestivalId(festivalId); } public List<User> getUsersByEventId(long id){ EventPoint event= eventPointDAO.getById(id); return event.getUsersFromEvent(); } @Override public void addUsersToEventId(long id, List<User> users){ EventPoint event= eventPointDAO.getById(id); event.setUsersToEvent(users); } @Override public void addUserToEventId(long id, User user){ EventPoint event= eventPointDAO.getById(id); event.addUserToEvent(user); } public void clearCash() { eventPointDAO.clearCash(); } private static SessionFactory createSessionFactory(Configuration configuration) { StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder(); builder.applySettings(configuration.getProperties()); ServiceRegistry serviceRegistry = builder.build(); return configuration.buildSessionFactory(serviceRegistry); } }
C++
UTF-8
1,788
2.78125
3
[]
no_license
#ifndef IpWidget_H #define IpWidget_H /** * IP地址输入框控件 作者:feiyangqingyun(QQ:517216493) 2017-8-11 * 1. 可设置IP地址,自动填入框 * 2. 可清空IP地址 * 3. 支持按下小圆点自动切换 * 4. 支持退格键自动切换 * 5. 支持IP地址过滤 * 6. 可设置背景色/边框颜色/边框圆角角度 */ #include <QWidget> class QLabel; class QLineEdit; #ifdef quc class Q_DECL_EXPORT IpWidget : public QWidget #else class IpWidget : public QWidget #endif { Q_OBJECT Q_PROPERTY(QString ip READ getIP WRITE setIP) public: explicit IpWidget(QWidget *parent = 0); protected: bool eventFilter(QObject *watched, QEvent *event); private: QLabel *m_labDot1; //第一个小圆点 QLabel *m_labDot2; //第二个小圆点 QLabel *m_labDot3; //第三个小圆点 QLineEdit *m_txtIP1; //IP地址网段输入框1 QLineEdit *m_txtIP2; //IP地址网段输入框2 QLineEdit *m_txtIP3; //IP地址网段输入框3 QLineEdit *m_txtIP4; //IP地址网段输入框4 QString m_ip; //IP地址 QString m_bgColor; //背景颜色 QString m_borderColor;//边框颜色 int m_borderRadius; //边框圆角角度 private slots: void textChanged(const QString &text); public: //获取IP地址 QString getIP() const; QSize sizeHint() const; QSize minimumSizeHint() const; public Q_SLOTS: //设置IP地址 void setIP(const QString &ip); //清空 void clear(); //设置背景颜色 void setBgColor(const QString &bgColor); //设置边框颜色 void setBorderColor(const QString &borderColor); //设置边框圆角角度 void setBorderRadius(int borderRadius); }; #endif // IpWidget_H
JavaScript
UTF-8
1,650
2.75
3
[ "MIT" ]
permissive
'use strict' /** * @fileoverview Discourage repeating parts of CSS selectors * @author Alexander Afanasyev */ var isCSSLocator = require('../find-css-locator') module.exports = { meta: { schema: [] }, create: function (context) { // keeping the processed CSS selectors to check the next one against var selectors = [] return { 'CallExpression': function (node) { if (node.arguments && node.arguments.length && node.arguments[0].hasOwnProperty('value')) { if (isCSSLocator(node)) { // we don't want to report the same repeated part multiple times var alreadyReported = [] var currentSelector = node.arguments[0].value var currentSelectorParts = currentSelector.split(' ') selectors.forEach(function (selectorParts) { // match the parts until a different part is found var sameParts = [] for (var i = 0; i < selectorParts.length; i++) { if (selectorParts[i] === currentSelectorParts[i]) { sameParts.push(selectorParts[i]) } else { break } } var samePart = sameParts.join(' ').trim() if (samePart && alreadyReported.indexOf(samePart) < 0) { context.report({ node: node, message: 'Repetitive part of a selector detected: "' + samePart + '"' }) alreadyReported.push(samePart) } }) selectors.push(currentSelectorParts) } } } } } }
C++
UTF-8
846
3.171875
3
[]
no_license
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: int pairSum(ListNode* head) { int n = 0; ListNode* p1 = head; ListNode* p2 = head; while(p2!=NULL){ p1=p1->next; p2=p2->next->next; n++; } vector<int> sum(n, 0); p2 = head; int i=0, j=n-1; while(p1!=NULL){ sum[i++]+=p2->val; sum[j--]+=p1->val; p1=p1->next; p2=p2->next; } int ans = 0; for(int i=0;i<sum.size();i++) ans = max(ans, sum[i]); return ans; } };
PHP
ISO-8859-1
21,149
3.265625
3
[]
no_license
<?php /** * @copyright (C) 2005 Hugo Ferreira da Silva. All rights reserved * @license http://www.gnu.org/copyleft/lesser.html LGPL License * @author Hugo Ferreira da Silva <eu@hufersil.com.br> * @link http://www.hufersil.com.br/lumine/ Lumine Project * Lumine is Free Software **/ /** * Utility class, just for hold the common methods * @author Hugo Ferreira da Silva * @access public * @package Lumine */ class Util { /** * Formats the date to a given format * * <code> * $my_iso_date = Util::FormatDate('20/10/2005', '%Y-%m-%d'); // or * $my_iso_date = Util::FormatDate('10/20/2005', '%Y-%m-%d'); // or * $my_iso_date = Util::FormatDate(time(), '%Y-%m-%d'); // or * $my_formated_date = Util::FormatDate("2005-10-20", "%d/%m/%Y"); * </code> * @author Hugo Ferreira da Silva * @return string The formated date * @access public * @param mixed $date Or in date format or unix timestamp * @param string $format The desired format */ function FormatDate($date, $format = "%d/%m/%Y") { $v = $date; if(is_numeric($date)) { return strftime($format, $date); } $formats = array("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", "/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/"); //$replaces = array( if(preg_match($formats[0], $date, $d)) { $v = $date; } if(preg_match($formats[1], $date, $d)) { if(checkdate($d[2], $d[1], $d[3])) { $v = "$d[3]-$d[2]-$d[1]"; } else { $v = "$d[3]-$d[1]-$d[2]"; } } $s = strtotime($v); if($s > -1) { return strftime($format, $s); } return $v; } /** * Formats the time to a given format * * @author Hugo Ferreira da Silva * @return string The formated time * @access public * @param mixed $time Or in time format or unix timestamp * @param string $format The desired format */ function FormatTime($time, $format = "%H:%M:%S") { if(is_numeric($time)) { return strftime($time, $format); } $v = $time; $t = strtotime($v); if($t > -1) { $v = strftime($format, $t); } return $v; } /** * Formats the datetime to a given format * * <code> * $my_iso_date = Util::FormatDateTime('20/10/2005 22:33', '%Y-%m-%d %H:%M'); // or * $my_iso_date = Util::FormatDateTime('10/20/2005 01:04:07', '%Y-%m-%d :%H:%M:%S'); // or * $my_iso_date = Util::FormatDateTime(time(), '%Y-%m-%d %H:%M:%S'); // or * $my_formated_date = Util::FormatDate("2005-10-20 10:30", "%d/%m/%Y %H:%M"); * </code> * @author Hugo Ferreira da Silva * @return string The formated datetime * @access public * @param mixed $time Or in date format or unix timestamp * @param string $format The desired format */ function FormatDateTime($time, $format = "%Y-%m-%d %H:%M:%S") { if(is_numeric($time)) { return strftime($format, $time); } // 2005-10-15 12:29:32 if(preg_match("/^([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})$/", $time, $reg)) { return strftime($format, strtotime($time)); } // 2005-10-15 12:29 if(preg_match("/^([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2})$/", $time, $reg)) { return strftime($format, strtotime($time)); } // 2005-10-15 12 if(preg_match("/^([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2})$/", $time, $reg)) { return strftime($format, strtotime($time)); } // 2005-10-15 if(preg_match("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $time, $reg)) { return Util::FormatDate($time, $format); } // 15/10/2005 12:29:32 if(preg_match("/^([0-9]{2})\/([0-9]{2})\/([0-9]{4}) ([0-9]{2}):([0-9]{2}):([0-9]{2})$/", $time, $reg)) { $isodate = Util::FormatDate("$reg[1]/$reg[2]/$reg[3]", "%Y-%m-%d"); return strftime($format, strtotime("$isodate $reg[4]:$reg[5]:$reg[6]")); } // 15/10/2005 12:29 if(preg_match("/^([0-9]{2})\/([0-9]{2})\/([0-9]{4}) ([0-9]{2}):([0-9]{2})$/", $time, $reg)) { $isodate = Util::FormatDate("$reg[1]/$reg[2]/$reg[3]", "%Y-%m-%d"); return strftime($format, strtotime("$isodate $reg[4]:$reg[5]:00")); } // 15/10/2005 12 if(preg_match("/^([0-9]{2})\/([0-9]{2})\/([0-9]{4}) ([0-9]{2})$/", $time, $reg)) { $isodate = Util::FormatDate("$reg[1]/$reg[2]/$reg[3]", "%Y-%m-%d"); return strftime($format, strtotime("$isodate $reg[4]")); } // 15/10/2005 if(preg_match("/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/", $time, $reg)) { return Util::FormatDate($time, $format); } return $time; } /** * Import a class from the current class-path and return a new instance of it * * @author Hugo Ferreira da Silva * @return mixed A new instance of class or false on failure * @access public * @param string $class A class to import (like my.package.Classname) */ function Import($class) { $listConf = &$GLOBALS['__LumineConf']; // primeiro, vemos se uma entidade foreach($listConf as $conf) { for($j=0; $j<count($conf->tables); $j++) { // achamos a entidade relacionada if($conf->tables[$j]->class == $class) { $file = $conf->config['class-path'] . "/" . str_replace(".","/",$class) . ".php"; if(file_exists($file)) { require_once $file; $className = array_pop(explode(".", $class)); $x = new $className; return $x; } else { LumineLog::logger(3, 'O arquivo no existe', __FILE__, __LINE__); return false; } } } } // ok, no uma entidade, ento vamos procurar simplesmente por uma classe dentro de todas as // class-paths definidas e usaremos a primeira que encontrar reset($listConf); foreach($listConf as $conf) { $file = $conf->config['class-path'] . "/" . str_replace(".","/",$class) . ".php"; // se existir if(file_exists($file)) { // importa a classe require_once $file; $className = array_pop(explode(".", $class)); $x = new $className; return $x; } } return false; } /** * Create directory recusively * @author Hugo Ferreira da Silva * @return boolean True on success, false on failure * @param strin $dir the directory */ function mkdir($dir, $dono = false) { if(file_exists($dir) && is_dir($dir)) { return true; } $dir = str_replace("\\","/", $dir); $pieces = explode("/", $dir); for($i=0; $i<count($pieces); $i++) { $mdir = ''; for($j=0; $j<=$i; $j++) { $mdir .= $pieces[$j] != '' ? $pieces[$j] . "/" : ''; } $mdir = substr($mdir, 0, strlen($mdir)-1); if(!file_exists($mdir) && $mdir != '') { mkdir($mdir, 0777) or die("Falha ao criar o diretrio <strong>$mdir</strong>"); @chmod($mdir, 0777); if($dono !== false) { chown($mdir, $dono); } } } return true; } /** * Write a file with the given content * @author Hugo Ferreira da Silva * @return void * @param string $filename The filename to write * @param string $contents The contents of file * @access public */ function write($filename, $contents) { $fp = fopen($filename, "wb"); fwrite($fp, $contents); fclose($fp); } /** * Validate emali address * @author Hugo Ferreira da Silva * @return boolean * @param string $email The email to validate * @access public */ function validateEmail ($email ) { if($email == '') { return false; } return ereg("^([0-9,a-z,A-Z]+)([.,_,-]([0-9,a-z,A-Z]+))*[@]([0-9,a-z,A-Z]+)([.,_,-]([0-9,a-z,A-Z]+))*[.]([0-9,a-z,A-Z]){2}([0-9,a-z,A-Z])?$", $email); } /** * Cria as options de uma select HTML */ function buildOptions($class, $value, $label, $selected='', $where=false) { if(is_string($class)) { $o=Util::Import($class); if($o) { if($where != false) { $o->whereAdd($where); } $o->orderby("$label asc"); $o->find(); } } else if(is_a($class, 'luminebase')) { $o = &$class; } else { return false; } $str=''; while($o->fetch()) { $str .= '<option value="'.$o->$value.'"'; if($o->$value == $selected) { $str .= ' selected="selected"'; } $str .= '>'.$o->$label.'</option>'; } return $str; } /** * Cria um formulrio simples de cadastro de itens com a classe passada * como parametro */ function createForm( $className, $options=array() ) { $nl = "\r\n"; $ref = Util::Import( $className ); if($ref === false) { die('Classe '. $className.' no encontrada'); } $list = $ref->table(); $mtm = $ref->oTable->getForeignKeys(); foreach($mtm as $name => $prop) { if($prop['type'] == 'many-to-many') { $list[$name] = $prop; } } $str = '<form action="'.$_SERVER['PHP_SELF'].'" method="post" enctype="multipart/form-data" id="form1" name="form1">' . $nl; $str .= '<table>' . $nl; $formats = "/\b("; $formats .= "int|integer|float|float4|float8|double|double precision|real"; $formats .= "|bpchar|text|char|varchar|blob|longblob|tinyblob|longtext|tinytext|mediumtext|mediumblob"; $formats .= "|date|time|datetime|timestamp"; $formats .= "|bool|boolean|tinyint"; $formats .= "|bytea"; $formats .= "|many-to-one|many-to-many"; $formats .= ")\b/i"; $labels = array('nome','name','label','descricao','description','login'); foreach($list as $name => $prop) { $reg=array(); if(!isset($ref->oTable->sequence_key) || (isset($ref->oTable->sequence_key) && $name != $ref->oTable->sequence_key)) { if(isset($prop['type']) && preg_match($formats, $prop['type'], $reg)) { $default = ''; if(isset($_POST[$name])) $default = $_POST[$name]; else if(isset($prop['default'])) $default = $prop['default']; $str .= '<tr><td>' . ucfirst($name) . '</td>'.$nl; $len = str_replace($reg[1], '', preg_replace("'[\(\)]'","",$prop['type'])); switch($reg[1]) { case "longblob": case 'bytea': $str .= '<td><input type="file" name="'.$name.'" />'; $str .= '(<input type="checkbox" name="'.$name.'_remove_file" /> - Remover)</td></tr>'; break; case "blob": case "tinyblob": case "longtext": case "tinytext": case "text": $str .= '<td><textarea rows="4" cols="30" name="'.$name.'">'; $str .= $default; $str .= '</textarea></td></tr>'.$nl; break; case "mediumtext": case "varchar": case "char": case "bpchar": $str .= '<td><input type="text" '; if(is_numeric($len)) { $str .= 'maxlength="'.$len.'" '; if($len < 50) { $str .= 'size="'.$len.'" '; } } $str .= 'name="'.$name.'" value="'.$default.'" /></td></tr>'.$nl; break; case "integer": case "int": case "float": case "float4": case "float8": case "double": case "double precision": case "real": case "date": case "time": case "timestamp": case "datetime": $str .= '<td><input type="text" '; $str .= 'name="'.$name.'" value="'.$default.'" /></td></tr>'.$nl; break; case "many-to-one": $o = Util::Import($prop['class']); $list = $o->table(); $label = $prop['linkOn']; foreach($list as $n => $p) { if(in_array($n, $labels)) { $label = $p['column']; break; } } $str .= '<td><select name="'.$name.'"><option value=""></option>'.Util::buildOptions($prop['class'], $prop['linkOn'], $label, @$_POST[$name]); $str .= '</td></tr>'; break; case 'many-to-many': $itens_list = Util::Import($prop['class']); $itens_list->find(); $pks = $itens_list->oTable->getPrimaryKeys(); $entity_fields = $itens_list->table(); $label_field = key($pks); foreach($entity_fields as $n => $p) { if(in_array($n, $labels)) { $label_field = $p['column']; break; } } $key = key($pks); $str .= ' <td>(many-to-many)</td></tr><tr><td colspan="2">'; while($itens_list->fetch()) { $ck = isset($_POST[ $name ]) && in_array($itens_list->$key, $_POST[$name]) ? ' checked="checked"' : ''; $str .= '<input id="'.$name.$itens_list->$key.'" type="checkbox" name="'.$name.'[]" value="'.$itens_list->$key.'"'.$ck.' /> '; $str .= '<label for="'.$name.$itens_list->$key.'">'.$itens_list->$label_field . '</label><br />'; } $str .= '</td></tr>'; break; case "boolean": case "bool": case "tinyint": $str .= '<td><input type="checkbox" name="'.$name.'" value="1"'; if(@$_POST[$name] == 1) { $str .= ' checked="checked"'; } $str .= ' /></td></tr>'; break; } } } } $value = ''; if(isset($ref->oTable->sequence_key)) { $key = $ref->oTable->sequence_key; if($key == '') { $keys = $ref->oTable->getPrimaryKeys(); if(count($keys) > 0) { list($key) = each($keys); } } $value = @$_POST[$key]; $str .= '<input type="hidden" name="_old_'.$key.'" value="'.$value.'" />' . $nl; } $str .= '<tr><td colspan="2"><input type="submit" name="lumineAction" value="Save" /> <input type="button" value="Cancel" onclick="window.location=\''.$_SERVER['PHP_SELF'].'\'" />'. ($value != '' ? '<input type="submit" name="lumineAction" value="Remove" /><input type="hidden" name="id" value="'.$value.'" />' : ''). '</td></tr>' . $nl; $str .= '</table></form>' . $nl; return $str; } /** * Cria uma lista para editar */ function createEditList($className, $where=false, $max = 20, $offset = 0) { $nl = "\r\n"; $ref = Util::Import($className); if($where != false) { $ref->whereAdd($where); } $total = $ref->count(); $ref->limit($offset, $max); $list = $ref->table(); $ref->selectAs(); $i = 1; /* LumineLog::setLevel(3); LumineLog::setOutput(); */ foreach($list as $name => $prop) { if(isset($prop['type']) && $prop['type'] == 'many-to-one') { $o = Util::Import($prop['class']); $l = $o->table(); foreach($l as $f => $p) { if(isset($p['type']) && $p['type'] != 'one-to-many' && $prop['type'] != 'many-to-many') { $ref->selectAdd(sprintf("%s.%s as %s", "tabela$i", $p['column'], "{$f}_$name")); } } //$ref->selectAs($o, '%s_'.$name); $ref->joinAdd($o, "LEFT", "tabela".($i++)); } } reset($list); $ref->find(); $str = '<table width="100%" cellpadding="2" cellspacing="1" bgcolor="#CCCCCC">' . $nl; $str .= '<tr>'; $ar = array(); $bg = 'bgcolor="white" '; foreach($list as $name => $prop) { if(!isset($prop['sequence_key']) || $prop['sequence_key'] == false) { if(isset($prop['type']) && $prop['type'] != 'many-to-many' && $prop['type'] != 'one-to-many') { $str .= '<td bgcolor="#EFEFEF"><b>'.$name.'</b></td>' . $nl; $ar[] = $name; } } } $key = isset($ref->oTable->sequence_key) ? $ref->oTable->sequence_key : ''; if($key == '') { $keys = $ref->oTable->getPrimaryKeys(); if(count($keys) > 0) { list($key) = each($keys); } } $files = array('longblob','bytea'); while($ref->fetch()) { $str .= '</tr>' . $nl; $keyValue = $ref->$key; foreach($ar as $n) { $t = $ref->oTable->getFieldProperties( $n ); if($ref->$n=='') { $v = '&nbsp;'; } else if(in_array($t['type'], $files)) { $file = $ref->conn->BlobDecode($ref->$n); if(@imagecreatefromstring($file)) { $v = '[ arquivo de imagem ]'; } else { $v = '[ arquivo ]'; } } else { $v = substr($ref->$n, 0, 20); } $labels = array('nome','name','label','descricao','description'); foreach($labels as $l) { $x = $l.'_'.$n; if(isset($ref->$x)) { $v = $ref->$x; break; } } $str .= ' <td '.$bg.'><a href="?lumineAction=edit&id='.$keyValue.($offset ? "&offset=$offset" :'').'">'.$v.'</a></td>' . $nl; } $str .= '</tr>' . $nl; } $pg = $total / $max; if($pg > 0) { $str .= '<tr><td colspan="'.count($ar).'" '.$bg.'> Pginas: |'; for($i=0; $i<$pg; $i++) { $e=$i+1; $s=$i*$max; $str .= '<a href="?offset='.$s.'"> '.$e.' </a> |'; } $str .= '</td></tr>'; } $str .= '</table>'; return $str; } /** * Manipulate the actions for a given class * <code> * $result = Util::handleAction('entities.Person', $_POST['action']); * </code> * @author Hugo Ferreira da Silva * @param String $class Name of classe to manipulate (include package) * @param String $action Name of action to execute * @return Boolean */ function handleAction($class, $action) { $ref = Util::Import($class); switch(strtolower($action)) { case "save": $key = @$ref->oTable->sequence_key; if($key == '') { $lk = $ref->oTable->getPrimaryKeys(); if(count($lk) > 0) { list($key) = each($lk); } } $l = $ref->table(); foreach($l as $n=>$p) { if(isset($p['type']) && preg_match('#\b(bool|boolean|tinyint)\b#', $p['type'])) { $_POST[$n] = sprintf('%d', @$_POST[$n]); } if(isset($_FILES[ $n ]) && is_uploaded_file($_FILES[ $n ]['tmp_name'])) { $contents = $ref->conn->BlobEncode( file_get_contents($_FILES[$n]['tmp_name']) ) ; $ref->$n = $contents; } if(isset($_POST[$n.'_remove_file'])) { $ref->$n = ''; } } $ref->setFrom($_POST); if($key != '' && isset($_POST['_old_'.$key]) && $_POST['_old_'.$key] != '') { $ref->$key = @$_POST['_old_'.$key]; } if(($x = $ref->validate()) === true) { /***************************************************/ // salva as chaves many-to-many $mtm = $ref->oTable->getForeignKeys(); foreach($mtm as $f_name => $f_prop) { if($f_prop['type'] == 'many-to-many') { $ref->removeAll( $f_name ); $ref->$f_name = @$_POST[ $f_name ]; } } /***************************************************/ if(@$_POST['_old_'.$key] == '') { $ref->insert(); } else { $ref->save(); } return true; } return false; break; case "edit": if($ref->get($_REQUEST['id']) > 0) { $_POST = $ref->toArray(); /***************************************************/ // pega as chaves many-to-many $mtm = $ref->oTable->getForeignKeys(); foreach($mtm as $f_name => $f_prop) { if($f_prop['type'] == 'many-to-many') { $link = $ref->getLink( $f_name ); foreach($link as $item) { $pks = $item->oTable->getPrimaryKeys(); $key = key($pks); $_POST[ $f_name ][] = $item->$key; } } } /***************************************************/ return true; } return false; break; case "remove": if($ref->get($_REQUEST['id']) > 0) { $ref->delete(); return true; } return false; break; } } /** * criptografia */ function _get_rnd_iv($iv_len, $pass_len) { $iv = ''; while ($iv_len-- > 0) { $iv .= chr($pass_len & 0xff); } return $iv; } function encrypt($plain_text, $obj = false, $password = false, $iv_len = 16) { if($password === false) { if(isset($obj->oTable->config->config['crypt-pass'])) { $password = $obj->oTable->config->config['crypt-pass']; } } if($password === false) { return $plain_text; } $plain_text .= "\x13"; $n = strlen($plain_text); if ($n % 16) $plain_text .= str_repeat("\0", 16 - ($n % 16)); $i = 0; $enc_text = Util::_get_rnd_iv($iv_len, strlen($password)); $iv = substr($password ^ $enc_text, 0, 512); while ($i < $n) { $block = substr($plain_text, $i, 16) ^ pack('H*', md5($iv)); $enc_text .= $block; $iv = substr($block . $iv, 0, 512) ^ $password; $i += 16; } return base64_encode($enc_text); } function decrypt($enc_text, $obj = false, $password = false, $iv_len = 16) { if($password === false) { if(isset($obj->oTable->config->config['crypt-pass'])) { $password = $obj->oTable->config->config['crypt-pass']; } } if($password === false) { return $enc_text; } $enc_text = base64_decode($enc_text); $n = strlen($enc_text); $i = $iv_len; $plain_text = ''; $iv = substr($password ^ substr($enc_text, 0, $iv_len), 0, 512); while ($i < $n) { $block = substr($enc_text, $i, 16); $plain_text .= $block ^ pack('H*', md5($iv)); $iv = substr($block . $iv, 0, 512) ^ $password; $i += 16; } return preg_replace('/\\x13\\x00*$/', '', $plain_text); } function toUTF8( $o ) { if(is_string($o)) { //$o = preg_replace('/([^\x09\x0A\x0D\x20-\x7F]|[\x21-\x2F]|[\x3A-\x40]|[\x5B-\x60])/e', '"&#".ord("$0").";"', $o); $o = utf8_encode($o); //$o = preg_replace('@&([a-z,A-Z,0-9]+);@e','html_entity_decode("&\\1;")',$o); return $o; } if(is_array($o)) { foreach($o as $k=>$v) { $o[$k] = Util::toUTF8($o[$k]); } return $o; } if(is_object($o)) { $l = get_object_vars($o); foreach($l as $k=>$v) { $o->$k = Util::toUTF8( $v ); } } // padro return $o; } function fromUTF8( $o ) { if(is_string($o)) { //$o = preg_replace('/([^\x09\x0A\x0D\x20-\x7F]|[\x21-\x2F]|[\x3A-\x40]|[\x5B-\x60])/e', '"&#".ord("$0").";"', $o); $o = utf8_decode($o); //$o = preg_replace('@&([a-z,A-Z,0-9]+);@e','html_entity_decode("&\\1;")',$o); return $o; } if(is_array($o)) { foreach($o as $k=>$v) { $o[$k] = Util::fromUTF8($o[$k]); } return $o; } if(is_object($o)) { $l = get_object_vars($o); foreach($l as $k=>$v) { $o->$k = Util::fromUTF8( $v ); } } // padro return $o; } } ?>
Python
UTF-8
23,233
2.921875
3
[]
no_license
#Importation des packages: import string import regex as re import pandas as pd from nltk.tokenize import word_tokenize from nltk.probability import FreqDist import unicodedata #Importation de la base de données: df = pd.read_csv("s3://projet-stat-ensai/Lacentrale.csv",sep=';', dtype=str) df = pd.read_csv(".aws/automobile.csv",error_bad_lines=False,index_col=0) #Traitement des valeurs manquantes : nan = float('nan') print(df["version"].isna().value_counts()) #Pas de valeurs manquantes. #Récupération de la colonne version: Version = df["version"] def Recuperation_generation_voiture(): n = len(df) L = [] for i in range(n): if re.match(r"I\s", Version[i]) != None: L.append("CLIO") elif re.match(r"II\s", Version[i]) != None: L.append("CLIO 2") elif re.match(r"III\s", Version[i]) != None: L.append("CLIO 3") elif re.match(r"IV\s", Version[i]) != None: L.append("CLIO 4") elif re.match(r"V\s", Version[i]) != None: L.append("CLIO 5") else: L.append(nan) return(L) L = Recuperation_generation_voiture() #Il reste 10 erreurs dans la base : les variables modèles et version n'indiquent pas la même génération pour la voiture. #Ajout de la colonne génération au data frame: df["generation"] = pd.Series(L, index = df.index) #Vérification des valeurs manquantes dans chacune des colonnes : print(df["modele_com"].isna().value_counts()) #Avant 998 valeurs manquantes dans modele_com. print(df["generation"].isna().value_counts()) #Avec 1386 valeurs manquantes dans generation. #Création d'une fonction permettant de compléter les valeurs manquantes de la variable modele_com à partir de la variable # generation construite en exploitant la variable version. def Fill_modele_com(): n = len(df) list_of_missing_model_com = df["modele_com"].isna() list_of_missing_generation = df["generation"].isna() for i in range(n): if list_of_missing_model_com[i] == True and list_of_missing_generation[i] == False: df["modele_com"][i] = df["generation"][i] return(True) Fill_modele_com() #Création d'une fonction permettant d'uniformiser les modalités de la variable modele_com: def Uniformisation_modele_com(): n = len(df) Indice_modele_invalide = [] for i in range(n): if type(df["modele_com"][i]) == str: if "CLIO 1" in df["modele_com"][i] or "CLIO SOCIETE" in df["modele_com"][i]: df["modele_com"][i] = "CLIO" elif "CLIO 2" in df["modele_com"][i] or "WILLIAMS" in df["modele_com"][i]: df["modele_com"][i] = "CLIO 2" elif "CLIO 3" in df["modele_com"][i]: df["modele_com"][i] = "CLIO 3" elif "CLIO 4" in df["modele_com"][i]: df["modele_com"][i] = "CLIO 4" elif "CLIO 5" in df["modele_com"][i]: df["modele_com"][i] = "CLIO 5" elif "ZOE" in df["modele_com"][i]: Indice_modele_invalide.append(i) elif "GRAND" in df["modele_com"][i]: Indice_modele_invalide.append(i) elif "CAPTUR" in df["modele_com"][i]: Indice_modele_invalide.append(i) elif "MEGANE" in df["modele_com"][i]: Indice_modele_invalide.append(i) elif "TWINGO" in df["modele_com"][i]: Indice_modele_invalide.append(i) return(Indice_modele_invalide) Liste_Modele_Invalide = Uniformisation_modele_com() #Suppression des modalités n'étant pas des RENAULT CLIO et réindexation des observation du dataframe: # On retire 7 modalités du data frame : 52513 observations ===> 52506 observations df = df.drop(Liste_Modele_Invalide) df.reset_index(drop=True, inplace=True) #Visualisation des modalités de la variable modele_com : df['modele_com'].value_counts() #Recomptage des valeurs manquantes de la variable modele_com : print(df["modele_com"].isna().value_counts()) #Après avoir complété modele_com grâce à la variable version il n'y a plus que 256 valeurs manquantes. #Récupération de la liste des index des valeurs manquantes et création d'un dataframe ne comportant que les observations ayant des valeurs manquantes dans la variable modele_com. index_of_missing_values_model_com = df[df['modele_com'].isnull()].index.tolist() df_missing_values_modele_com = df.loc[index_of_missing_values_model_com,] #Création de plusieurs foncions permettant de rechercher les index des observations sans valeurs manquantes pour modele_com ayant une version similaire # aux observations ayant des valeurs manquantes pour modele_com. def search_index_MEDIANAV(): n = len(df) L_medianav = [] for i in range(n): if "MEDIANAV" in df["version"][i]: if type(df["modele_com"][i]) == str: L_medianav.append(i) return(L_medianav) def search_index_AIR(): n = len(df) L_AIR = [] for i in range(n): if "1.5" in df["version"][i] and "DCI" in df["version"][i] and "AIR" in df["version"][i]: if type(df["modele_com"][i]) == str: L_AIR.append(i) return(L_AIR) def search_index_ENERGY(): n = len(df) L_energy = [] for i in range(n): if "1.5" in df["version"][i] and "ENERGY" in df["version"][i] and "DCI" in df["version"][i]: if type(df["modele_com"][i]) == str: L_energy.append(i) return(L_energy) #Création des data frames associées à chacune des listes renvoyées par la fonction ci-dessus, et visualisation de la génération #des véhicules ayant des versions similaires aux véhicules dont la génération est manquante. L_medianav = search_index_MEDIANAV() df_version_medianav = df.loc[L_medianav,] df_version_medianav["modele_com"].value_counts() #Tous les véhicules comportant un systeme MEDIANAV sont des CLIO 4. L_AIR = search_index_AIR() df_version_AIR= df.loc[L_AIR,] df_version_AIR["modele_com"].value_counts() #Le mode est CLIO 4. L_ENERGY = search_index_ENERGY() df_version_ENERGY = df.loc[L_ENERGY,] df_version_ENERGY["modele_com"].value_counts() #15296 véhicules des versions comportant les mots 1.5, ENERGY et DCI sont des CLIOS 4, 1 véhicule comportant ces trois mots est une CLIO 3. # Création d'une fonction permettant d'imputer les valeurs manquantes de modele_com à partir des observations présentant une version similaire. def Imputation_modele_com(): n = len(df) for i in index_of_missing_values_model_com: if "MEDIANAV" in df["version"][i]: df["modele_com"][i] = "CLIO 4" elif "MEDIA" in df["version"][i]: df["modele_com"][i] = "CLIO 4" elif "1.5" and "DCI" and "AIR" in df["version"][i]: df["modele_com"][i] = "CLIO 4" elif "1.5" and "ENERGY" and "DCI" in df["version"][i]: df["modele_com"][i] = "CLIO 4" Imputation_modele_com() #Visualisation des valeurs manquantes après imputation : df["modele_com"].isna().value_counts() # il reste 16 valeurs manquantes après avoir rajouté les véhicules MEDIANAV #Mise à jour du data frame comportant les valeurs manquantes restantes de modele_com. index_of_missing_values_model_com = df[df['modele_com'].isnull()].index.tolist() df_missing_values_modele_com = df.loc[index_of_missing_values_model_com,] # Imputation manuelle des 16 dernières valeurs manquantes en cherchant la génération des véhicules ayant une version similaires à ceux-ci # (J'ai modifié la fonction au fur et à mesure, toutes les recherches ne sont pas visibles ici et la fonction écrite ci-dessous est surtout présente pour illustrer la démarche). def search_quick(): n = len(df) L_END = [] for i in range(n): if "SOCIETE" in df["version"][i] and "90" in df["version"][i] and "TCE" in df["version"][i] and "ENERGY" in df["version"][i]: if type(df["modele_com"][i]) == str: L_END.append(i) return(L_END) L_END = search_quick() df_version_EDITION= df.loc[L_END,] df_version_EDITION["modele_com"].value_counts() #Imputation des 16 dernières valeurs manquantes à partir des recherches effectuées ci-dessus. def Fin_imputation_modele_com(): df["modele_com"][14301] = "CLIO 2" df["modele_com"][50411] = "CLIO 2" df["modele_com"][11117] = "CLIO 4" df["modele_com"][11539] = "CLIO 4" df["modele_com"][19966] = "CLIO 4" df["modele_com"][16702] = "CLIO 4" df["modele_com"][17903] = "CLIO 4" df["modele_com"][10449] = "CLIO 4" df["modele_com"][22999] = "CLIO 4" df["modele_com"][20861] = "CLIO 5" df["modele_com"][27024] = "CLIO 5" df["modele_com"][48021] = "CLIO 4" df["modele_com"][35305] = "CLIO 4" df["modele_com"][28189] = "CLIO 3" df["modele_com"][4220] = "CLIO 2" df["modele_com"][37468] = "CLIO 4" return("Terminé") Fin_imputation_modele_com() #Visualisation des valeurs manquantes et des modalités de modele_com : print(df["modele_com"].isna().value_counts()) # Il n'y a plus de valeur manquante dans la variable modele_com. print(df["modele_com"].value_counts()) #Uniformisation de la variable energie. def Uniformisation_energie(): n = len(df) for i in range(n): if "GPL" in df["energie"][i]: df["energie"][i] = "Essence" elif "Bicarburation" in df["energie"][i]: df["energie"][i] = "Essence" elif "Biocarburant" in df["energie"][i]: df["energie"][i] = "Diesel" return() Uniformisation_energie() print(df["energie"].value_counts()) #Récupération cylindrée def Recuperation_cylindree(): n = len(df) L = [] for i in range(n): if "0.9" in Version[i]: L.append("0.9") elif "1.0" in Version[i]: L.append("1.0") elif "1.2" in Version[i]: L.append("1.2") elif "1.3" in Version[i]: L.append("1.3") elif "1.4" in Version[i]: L.append("1.4") elif "1.5" in Version[i]: L.append("1.5") elif "1.6" in Version[i]: L.append("1.6") elif "1.9" in Version[i]: L.append("1.9") elif "2.0" in Version[i]: L.append("2.0") elif "9.3" in Version[i]: L.append("9.3") else: L.append(nan) return(L) L_Cyl = Recuperation_cylindree() df["Cylindree"] = pd.Series(L_Cyl, index = df.index) #Visualisation des valeurs manquantes dans engine: print(df["engine"].isna().value_counts()) #Il y a 889 valeurs manquantes dans engine. print(df["Cylindree"].isna().value_counts()) # Il y a 897 valeurs manquantes dans cylindree. def Fill_engine(): n = len(df) list_of_missing_engine = df["engine"].isna() list_of_missing_cylindree = df["Cylindree"].isna() for i in range(n): if list_of_missing_engine[i] == True and list_of_missing_cylindree[i] == False: df["engine"][i] = df["Cylindree"][i] return("Terminé") Fill_engine() df["engine"].isna().value_counts() #Il reste 177 valeurs manquantes. #Imputation des valeurs manquantes de engine à partir de modele_com et energie. #Regroupement des observations selon les variables modele_com et energie : df["engine"] = df.groupby(['modele_com','energie'])["engine"].transform(lambda x: x.fillna(x.mode()[0])) #Revisualisation des valeurs manquantes de engine : print(df["engine"].isna().value_counts()) #Il n'y a plus de valeurs manquantes pour la variable engine. #Récupération Horse-Power: def Recuperation_Horse_Power(): n = len(df) L = [] for i in range(n): if "90" in Version[i]: L.append("90") elif "75" in Version[i]: L.append("75") elif "100" in Version[i]: L.append("100") elif "85" in Version[i]: L.append("85") elif "120" in Version[i]: L.append("120") elif "130" in Version[i]: L.append("130") elif "115" in Version[i]: L.append("115") elif "110" in Version[i]: L.append("110") elif "70" in Version[i]: L.append("70") elif "200" in Version[i]: L.append("200") elif "65" in Version[i]: L.append("65") elif "220" in Version[i]: L.append("220") elif "60" in Version[i]: L.append("60") elif "105" in Version[i]: L.append("105") elif "95" in Version[i]: L.append("95") elif "80" in Version[i]: L.append("80") elif "140" in Version[i]: L.append("140") elif "203" in Version[i]: L.append("203") elif "128" in Version[i]: L.append("128") elif "255" in Version[i]: L.append("255") elif "182" in Version[i]: L.append("182") elif "230" in Version[i]: L.append("230") elif "55" in Version[i]: L.append("68") elif "172" in Version[i]: L.append("172") elif "201" in Version[i]: L.append("201") elif "12" in Version[i]: L.append("12") elif "16" in Version[i]: L.append("16") elif "88" in Version[i]: L.append("88") else: L.append(nan) return (L) L_horsepower = Recuperation_Horse_Power() df["Horsepower_version"] = pd.Series(L_horsepower, index = df.index) #Visualisation des valeurs manquantes : df["horsepower"].isna().value_counts() #Il y a 750 valeurs manquantes. df["Horsepower_version"].value_counts() #Il y a 376 valeurs manquantes. def Fill_horsepower(): n = len(df) list_of_missing_horsepower = df["horsepower"].isna() list_of_missing_Horsepower_version = df["Horsepower_version"].isna() for i in range(n): if list_of_missing_horsepower[i] == True and list_of_missing_Horsepower_version[i] == False: df["horsepower"][i] = df["Horsepower_version"][i] return("Terminé") Fill_horsepower() #Revisualisation des valeurs manquantes de horsepower. df["horsepower"].isna().value_counts() #Il reste 99 valeurs manquantes. #Regroupement des observations selon les variables modele_com et energie. df["horsepower"] = df.groupby(['modele_com','energie'])["horsepower"].transform(lambda x: x.fillna(x.mode()[0])) #Revisualisation des valeurs manquantes de horsepower : print(df["horsepower"].isna().value_counts()) #Il n'y a plus de valeurs manquantes pour la variable horsepower. #Imputation des trois valeurs manquantes de puissance_fiscale. df["puissance_fiscale"] = df.groupby(['modele_com','energie'])["puissance_fiscale"].transform(lambda x: x.fillna(x.mode()[0])) df["puissance_fiscale"].isna().value_counts() #Ajout d'une colonne type de moteur à la base de données: def Recuperation_type_de_moteur(): n = len(df) L = [] for i in range(n): if "DCI" in Version[i]: L.append("DCI ") elif "TCE" in Version[i]: L.append("TCE ") else: L.append(nan) return(L) L_Moteur = Recuperation_type_de_moteur() df["type_moteur"] = pd.Series(L_Moteur, index = df.index) #Récupération des finitions. def Recuperation_finition(): n = len(df) L = [] for i in range(n): if "LIFE" in Version[i]: L.append("Life") elif "TREND" in Version[i]: L.append("Trend") elif "ZEN" in Version[i]: L.append("Zen") elif "LIMITED" in Version[i]: L.append("Limited") elif "BUSINESS" in Version[i]: L.append("Business") elif "INTENS" in Version[i]: L.append("Intens") elif "PRIVILEGE" in Version[i]: L.append("Privilege") elif "AUTHENTIQUE" in Version[i]: L.append("Authentique") elif "SOCIETE" in Version[i]: L.append("Societe") elif "ALIZE" in Version[i]: L.append("Alize") elif "INITIALE" in Version[i]: L.append("Initiale") elif "TOMTOM" in Version[i]: L.append("Tomtom") elif "AIR" in Version[i]: L.append("Societe") elif "CAMPUS" in Version[i]: L.append("Campus") elif "EXPRESSION" in Version[i]: L.append("Expression") elif "GENERATION" in Version[i]: L.append("Generation") elif "EXCEPTION" in Version[i]: L.append("Exception") elif "RS" in Version[i]: L.append("RS") elif "RS LINE" in Version[i]: L.append("RS LINE") elif "DYNAMIQUE" in Version[i]: L.append("Dynamique") elif "GT" in Version[i]: L.append("GT") elif "SPORT" in Version[i]: L.append("Sport") elif "ONE" in Version[i]: L.append("One") elif "EXTREME" in Version[i]: L.append("Extreme") elif "BILLABONG" in Version[i]: L.append("Billabong") elif "LUXE" in Version[i]: L.append("Luxe") elif "RTA" in Version[i]: L.append("RTA") elif "RTE" in Version[i]: L.append("RTE") elif "RXE" in Version[i]: L.append("RXE") elif "RXT" in Version[i]: L.append("RXT") elif "SI" in Version[i]: L.append("SI") elif "BASE" in Version[i]: L.append("Base") else: L.append(nan) return(L) L_Finition = Recuperation_finition() df["Finition"] = pd.Series(L_Finition, index = df.index) df["Finition"].isna().value_counts() #1157 valeurs manquantes dans la variable Finition. #Imputation des valeurs manquantes de la variable Finition. df["Finition"] = df.groupby(['modele_com','energie'])["Finition"].transform(lambda x: x.fillna(x.mode()[0])) df["Finition"].isna().value_counts() df["Finition"].value_counts() def Recuperer_modalite_fintion(): Finition_Intens = [] Finition_Business = [] Finition_Limited = [] Finition_Zen = [] Finition_Societe = [] Finition_Trend = [] Finition_RS = [] Finition_Expression = [] Autre_finition = [] n = len(df) for i in range(n): if df["Finition"][i] == "Intens": Finition_Intens.append(1) Finition_Business.append(0) Finition_Limited.append(0) Finition_Zen.append(0) Finition_Societe.append(0) Finition_Trend.append(0) Finition_RS.append(0) Finition_Expression.append(0) Autre_finition.append(0) elif df["Finition"][i] == "Business": Finition_Intens.append(0) Finition_Business.append(1) Finition_Limited.append(0) Finition_Zen.append(0) Finition_Societe.append(0) Finition_Trend.append(0) Finition_RS.append(0) Finition_Expression.append(0) Autre_finition.append(0) elif df["Finition"][i] == "Limited": Finition_Intens.append(0) Finition_Business.append(0) Finition_Limited.append(1) Finition_Zen.append(0) Finition_Societe.append(0) Finition_Trend.append(0) Finition_RS.append(0) Finition_Expression.append(0) Autre_finition.append(0) elif df["Finition"][i] == "Zen": Finition_Intens.append(0) Finition_Business.append(0) Finition_Limited.append(0) Finition_Zen.append(1) Finition_Societe.append(0) Finition_Trend.append(0) Finition_RS.append(0) Finition_Expression.append(0) Autre_finition.append(0) elif df["Finition"][i] == "Societe": Finition_Intens.append(0) Finition_Business.append(0) Finition_Limited.append(0) Finition_Zen.append(0) Finition_Societe.append(1) Finition_Trend.append(0) Finition_RS.append(0) Finition_Expression.append(0) Autre_finition.append(0) elif df["Finition"][i] == "Trend": Finition_Intens.append(0) Finition_Business.append(0) Finition_Limited.append(0) Finition_Zen.append(0) Finition_Societe.append(0) Finition_Trend.append(1) Finition_RS.append(0) Finition_Expression.append(0) Autre_finition.append(0) elif df["Finition"][i] == "RS": Finition_Intens.append(0) Finition_Business.append(0) Finition_Limited.append(0) Finition_Zen.append(0) Finition_Societe.append(0) Finition_Trend.append(0) Finition_RS.append(1) Finition_Expression.append(0) Autre_finition.append(0) elif df["Finition"][i] == "Expression": Finition_Intens.append(0) Finition_Business.append(0) Finition_Limited.append(0) Finition_Zen.append(0) Finition_Societe.append(0) Finition_Trend.append(0) Finition_RS.append(0) Finition_Expression.append(1) Autre_finition.append(0) else: Finition_Intens.append(0) Finition_Business.append(0) Finition_Limited.append(0) Finition_Zen.append(0) Finition_Societe.append(0) Finition_Trend.append(0) Finition_RS.append(0) Finition_Expression.append(0) Autre_finition.append(1) return(Finition_Intens, Finition_Business, Finition_Limited, Finition_Zen, Finition_Societe, Finition_Trend, Finition_RS, Finition_Expression, Autre_finition) Finition_Intens, Finition_Business, Finition_Limited, Finition_Zen, Finition_Societe, Finition_Trend, Finition_RS, Finition_Expression, Autre_finition = Recuperer_modalite_fintion() df["finition_intens"] = pd.Series(Finition_Intens, index = df.index) df["finition_business"] = pd.Series(Finition_Business, index = df.index) df["finition_limited"] = pd.Series(Finition_Limited, index = df.index) df["finition_zen"] = pd.Series(Finition_Zen, index = df.index) df["finition_societe"] = pd.Series(Finition_Societe, index = df.index) df["finition_trend"] = pd.Series(Finition_Trend, index = df.index) df["finition_rs"] = pd.Series(Finition_RS, index = df.index) df["finition_expression"] = pd.Series(Finition_Expression, index = df.index) df["autre_finition"] = pd.Series(Autre_finition, index = df.index) #Ajout des variables de version au data frame. df.to_csv(".aws/automobile.csv") df.to_csv(".aws/automobile2.csv")
Java
UTF-8
6,135
2.5
2
[]
no_license
package Paneles; import Botones.BtnCancelar; import ManejadoresEventos.EmpleadoEventos; import Colecciones.HashTEmpleado; import ClasesBase.Departamento; import Colecciones.ArrayLDepartamentos; import TextFields.JEnterosField; import TextFields.JFloatField; import TextFields.JLetrasField; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.ArrayList; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.SwingConstants; public class EmpleadoPanel extends JDialog { private JLetrasField txtNombre, txtApPat, txtApMat; private JEnterosField txtClave; private JFloatField txtSueldo; private JTextField txtDomicilio; private JLabel lblNombre, lblApPat, lblApMat, lblDomicilio, lblSueldo, lblClave; private JComboBox cmbDepartamentos; private HashTEmpleado tablaEmpleado; private JButton btnGuardar, btnLimpiar; private BtnCancelar btnCancelar; private JCheckBox chkEncargado; private ArrayLDepartamentos arrDeptos; public EmpleadoPanel(JFrame m, HashTEmpleado tablaEmpleado, ArrayLDepartamentos arrDeptos) { super(m, "Registro Empleados", true); this.tablaEmpleado = tablaEmpleado; this.arrDeptos = arrDeptos; EmpleadoEventos manejaE= new EmpleadoEventos(this, tablaEmpleado, arrDeptos); setLayout(new FlowLayout(SwingConstants.CENTER, 10, 15)); lblClave = new JLabel("Clave : "); add(lblClave); txtClave = new JEnterosField(10,4); add(txtClave); revalidate(); lblNombre = new JLabel("Nombre: "); add(lblNombre); txtNombre = new JLetrasField(20, 10); add(txtNombre); lblApPat = new JLabel("Apellido Paterno:"); add(lblApPat); txtApPat = new JLetrasField(15,10); add(txtApPat); lblApMat = new JLabel("Apellido Materno:"); add(lblApMat); txtApMat = new JLetrasField(15,10); add(txtApMat); lblDomicilio = new JLabel("Domicilio: "); add(lblDomicilio); txtDomicilio = new JTextField(31); add(txtDomicilio); lblSueldo = new JLabel("Sueldo Diario: "); add(lblSueldo); txtSueldo = new JFloatField(7); add(txtSueldo); cmbDepartamentos = new JComboBox(); add(new JLabel("Departamentos")); ArrayList<Departamento> departamentos = arrDeptos.getArrDeptos(); for (int i = 0; i < arrDeptos.getSize(); i++) { cmbDepartamentos.addItem(departamentos.get(i)); } cmbDepartamentos.setMinimumSize(new Dimension(40, 15)); cmbDepartamentos.setPreferredSize(new Dimension(80,25)); add(cmbDepartamentos); chkEncargado = new JCheckBox("Encargado"); add(chkEncargado); add(new JLabel(" ")); add(new JLabel(" ")); btnGuardar = new JButton("Guardar"); add(btnGuardar); btnLimpiar = new JButton("Limpiar"); add(btnLimpiar); btnCancelar = new BtnCancelar(this,"Cancelar"); add(btnCancelar); txtDomicilio.addKeyListener(new KeyAdapter(){ public void keyTyped(KeyEvent e) { char c = e.getKeyChar(); if (Character.isLowerCase(c)) { e.setKeyChar(Character.toUpperCase(c)); } } }); txtDomicilio.setTransferHandler(null); btnGuardar.addActionListener(manejaE); btnLimpiar.addActionListener(new ManejadorBtnLimpiar(this)); setSize(500, 250); setLocationRelativeTo(null); setVisible(true); } public JCheckBox getChkEncargado() { return chkEncargado; } public JLetrasField getTxtNombre() { return txtNombre; } public JLetrasField getTxtApPat() { return txtApPat; } public JLetrasField getTxtApMat() { return txtApMat; } public JTextField getTxtDomicilio() { return txtDomicilio; } public JFloatField getTxtSueldo() { return txtSueldo; } public JEnterosField getTxtClave() { return txtClave; } public JLabel getLblNombre() { return lblNombre; } public JLabel getLblApPat() { return lblApPat; } public JLabel getLblApMat() { return lblApMat; } public ArrayLDepartamentos getArrDeptos() { return arrDeptos; } public JLabel getLblDomicilio() { return lblDomicilio; } public JLabel getLblSueldo() { return lblSueldo; } public JLabel getLblClave() { return lblClave; } public JComboBox getCmbDepartamentos() { return cmbDepartamentos; } public HashTEmpleado getTablaEmpleado() { return tablaEmpleado; } public JButton getBtnGuardar() { return btnGuardar; } public JButton getBtnLimpiar() { return btnLimpiar; } public BtnCancelar getBtnCancelar() { return btnCancelar; } private class ManejadorBtnLimpiar implements ActionListener { private EmpleadoPanel ventana; ManejadorBtnLimpiar(EmpleadoPanel el) { this.ventana=el; } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == ventana.getBtnLimpiar()) { limpiar(); } } public void limpiar() { ventana.getTxtClave().setText(""); ventana.getTxtNombre().setText(""); ventana.getTxtApPat().setText(""); ventana.getTxtApMat().setText(""); ventana.getTxtDomicilio().setText(""); ventana.getTxtSueldo().setText(""); ventana.getChkEncargado().setSelected(false); } } }
Python
UTF-8
7,216
2.9375
3
[]
no_license
import pygame, sys, random from pygame.locals import * class Grille: def __init__(self, x, y): self.matrice = [[ESPACE for i in range(y)] for j in range(x)] self.longueur = x self.largeur = y class Snake: def __init__(self): self.list_blocks = [] self.direction = "right" self.blocks = 2 self.pos = [1, 1] def verif_pos(self): ### Modifie les coordonés ### if self.direction == "up": if grille.matrice[self.pos[0]][self.pos[1] - 1] not in OBSTACLES: self.pos[1] -= 1 else: Var.GAME_OVER = True return False elif self.direction == "down": if grille.matrice[self.pos[0]][self.pos[1] + 1] not in OBSTACLES: self.pos[1] += 1 else: Var.GAME_OVER = True return False elif self.direction == "left": if grille.matrice[self.pos[0] - 1][self.pos[1]] not in OBSTACLES: self.pos[0] -= 1 else: Var.GAME_OVER = True return False elif self.direction == "right": if grille.matrice[self.pos[0] + 1][self.pos[1]] not in OBSTACLES: self.pos[0] += 1 else: Var.GAME_OVER = True return False return True def actualise_pos(self): ### Efface ### for snake_block in self.list_blocks: grille.matrice[snake_block[0]][snake_block[1]] = ESPACE ### Actualise les valeurs ### self.list_blocks.append(self.pos[:]) if len(self.list_blocks) > self.blocks: self.list_blocks.pop(0) ### Actualise la grille ### for snake_block in self.list_blocks: if snake_block == self.pos: grille.matrice[snake_block[0]][snake_block[1]] = TETE else: grille.matrice[snake_block[0]][snake_block[1]] = CORP def verif_point_mange(self): if self.pos == point.pos: ## Si le point est mangé point.spawn_point() self.blocks += 1 Var.SCORE += 1 pygame.display.set_caption('Snake - Score: {}'.format(Var.SCORE)) Var.FPS += 0.25 class Point: def spawn_point(self): while True: ### Au cas ou, si le point est dans le snake il se regénère x = random.randint(1, grille.longueur - 2) y = random.randint(1, grille.largeur - 2) if grille.matrice[x][y] not in OBSTACLES: break self.pos = [x, y] grille.matrice[x][y] = POINT def blocks2pixels(x, y): return (x * BLOCK_DIM), (y * BLOCK_DIM) def dessine(): ### Murs ### for block_y in range(GRILLE_LARG): x, y = blocks2pixels(0, block_y) if block_y == 0 or block_y == GRILLE_LARG - 1: for block_x in range(GRILLE_LONG): grille.matrice[block_x][block_y] = MUR else: grille.matrice[0][block_y] = MUR grille.matrice[GRILLE_LONG - 1][block_y] = MUR ### Éléments du jeu ### for block_x in range(GRILLE_LONG): for block_y in range(GRILLE_LARG): x, y = blocks2pixels(block_x, block_y) if grille.matrice[block_x][block_y] != ESPACE: pygame.draw.rect(DISPLAYSURF, grille.matrice[block_x][block_y][1], (x, y, BLOCK_DIM, BLOCK_DIM)) def message(msg='', dim=32, pos=None): if pos is None: pos = FENETRE_LONG // 2, FENETRE_LARG // 2 Var.fontObj = pygame.font.Font('freesansbold.ttf', dim) Var.textSurfaceObj = Var.fontObj.render(msg, True, (255, 255, 255)) Var.textRectObj = Var.textSurfaceObj.get_rect() Var.textRectObj.center = pos def reset(): global grille, snake, point Var.FPS = 5 Var.GAME_OVER = False Var.PAUSED = False Var.SCORE = 0 grille = Grille(GRILLE_LARG, GRILLE_LONG) snake = Snake() point = Point() point.spawn_point() pygame.display.set_caption('Snake - Score: {}'.format(Var.SCORE)) class Var: FPS = 5 GAME_OVER = False PAUSED = False SCORE = 0 GRILLE_LONG = 30 # blocks GRILLE_LARG = 30 # blocks BLOCK_DIM = 20 # px FENETRE_LONG = GRILLE_LONG * BLOCK_DIM FENETRE_LARG = GRILLE_LARG * BLOCK_DIM ORANGE = (255, 128, 0) VERT = (0, 204, 0) BLANC = (255, 255, 255) ROUGE = (255, 0, 0) BG = (100, 100, 100) ESPACE = ["espace", BG] MUR = ["mur", ORANGE] TETE = ["tete", BLANC] CORP = ["corp", VERT] POINT = ["point", ROUGE] OBSTACLES = [MUR, TETE, CORP] pygame.init() FPSCLOCK = pygame.time.Clock() DISPLAYSURF = pygame.display.set_mode((FENETRE_LONG, FENETRE_LARG)) pygame.display.set_caption('Snake - Score: {}'.format(Var.SCORE)) message() # Juste pour l'initialisation grille = Grille(GRILLE_LARG, GRILLE_LONG) snake = Snake() point = Point() point.spawn_point() while True: frame_direction = snake.direction DISPLAYSURF.fill(BG) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if Var.GAME_OVER == False and Var.PAUSED == False: if (event.key == pygame.K_UP or event.key == pygame.K_z) and frame_direction != "down": snake.direction = "up" elif (event.key == pygame.K_DOWN or event.key == pygame.K_s) and frame_direction != "up": snake.direction = "down" elif (event.key == pygame.K_LEFT or event.key == pygame.K_q) and frame_direction != "right": snake.direction = "left" elif (event.key == pygame.K_RIGHT or event.key == pygame.K_d) and frame_direction != "left": snake.direction = "right" if (event.key == pygame.K_SPACE or event.key == pygame.K_p) and Var.GAME_OVER == False: if Var.PAUSED == False: Var.PAUSED = True pygame.display.set_caption('Snake - Score: {} (Paused)'.format(Var.SCORE)) else: Var.PAUSED = False pygame.display.set_caption('Snake - Score: {}'.format(Var.SCORE)) if Var.GAME_OVER == True: if event.key == pygame.K_r: reset() elif event.key == pygame.K_ESCAPE: pygame.quit() sys.exit() if Var.GAME_OVER == False and Var.PAUSED == False: if snake.verif_pos() is True: snake.actualise_pos() snake.verif_point_mange() dessine() if Var.PAUSED == True: message('Paused') DISPLAYSURF.blit(Var.textSurfaceObj, Var.textRectObj) if Var.GAME_OVER == True: message('Game Over') DISPLAYSURF.blit(Var.textSurfaceObj, Var.textRectObj) message('(appuyez [r] pour recommencer et [ESC] pour quitter)', 16, (FENETRE_LONG // 2, FENETRE_LARG // 2 + 30)) DISPLAYSURF.blit(Var.textSurfaceObj, Var.textRectObj) pygame.display.set_caption('Snake - Score: {} (Game Over)'.format(Var.SCORE)) pygame.display.update() FPSCLOCK.tick(Var.FPS)
Markdown
UTF-8
1,872
4.09375
4
[]
no_license
1. `charAt` - Parameter: (index) defaults to 0 - (number data type) - Return: character at specific index in the string (string data type) - Example: ```js let name = 'Arya Stark'; name.charAt(2); //"y" let sentance = 'A quick brown fox jumped over a lazy dog'; sentance(4); // "i" let houseName = 'Starks'; houseName.charAt(0); // "S" ``` - `charAt` accepts a index (number data type) and return the character on that index in the string. 2. `toUpperCase` ```js let userName = 'Zehan Khan'; userName.toUpperCase(); //"ZEHAN KHAN" let sentance = 'A quick brown fox jumped over a lazy dog'; sentance.toUpperCase(); //"A QUICK BROWN FOX JUMPED OVER A LAZY DOG" let houseName = 'Starks'; houseName.toUpperCase(); //"STARK" ``` `toUpperCase` doesn't accept a parameter and return the character into a uppercase 3. `toLowerCase` ```js let lastName = 'KHAN' lastName.toLowerCase(); //"khan" let words = 'A QUICK BROWN FOX JUMPED OVER A LAZY DOG'; words.toLowerCase(); //"a quick brown fox jumped over a lazy dog" let houseName = 'STARKS'; houseName.toLowerCase(); //"starks" ``` 4. `trim` ```js let title = " Hello World "; title.trim(); //"Hello World" let ``` `trim` does't accept a parameter and return the character with removed whitespace from start and end 5. `trimEnd` ```js let title = " Hello World "; title.trimEnd(); //" Hello World" ``` `trimEnd` does't accept a parameter and return the character with removed whitespace from end 6. `trimStart` ```js let title = " Hello World "; title.trimStart(); //"Hello World " ``` `trimEnd` does't accept a parameter and return the character with removed whitespace start 7. `concat` ```js let letter1 = "Hello" let letter2 = "World" letter1.concat(letter2); //"HelloWorld" letter1.concat(' ',letter2); //"Hello World" ```
PHP
UTF-8
746
2.5625
3
[ "MIT" ]
permissive
<?php namespace App\Http\Requests; use pebibits\validation\Rule\Alpha\Alpha; use Illuminate\Foundation\Http\FormRequest; class SpecificEvent extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ ///////// REGISTRATION OF A SPECIFIC EVENT Validation\\\\\\\\\\ 'customfield_1'=>['nullable',new Alpha], 'customfield_2'=>['nullable',new Alpha], 'customfield_3'=>['nullable',new Alpha] ]; } }
Java
UTF-8
2,785
2.765625
3
[]
no_license
package dao; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import entities.Definition; public class DefinitionDao extends Dao<Definition> { @Override public Definition findById(int id) throws SQLException { Definition def = null; String query = "SELECT * FROM DefinitionFR WHERE idDefinition = ?"; PreparedStatement stmt = connection.prepareStatement(query); stmt.setInt(1, id); ResultSet results = stmt.executeQuery(); if (!results.first()) { return null; } String definition = results.getString("definition"); boolean validate = results.getBoolean("existe"); def = new Definition(id, definition, validate); return def; } @Override public Definition create(Definition obj) throws SQLException { if (obj == null) { throw new IllegalArgumentException("la definition est null"); } String chaine = obj.getDefinition(); Definition def = getByDefinition(chaine); if (def != null) { return def; } String query = "INSERT INTO DefinitionFR VALUES(NULL, ?, ?)"; PreparedStatement pstmt = connection.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS); pstmt.setString(1, obj.getDefinition()); pstmt.setBoolean(2, false); pstmt.executeUpdate(); ResultSet rs = pstmt.getGeneratedKeys(); if (rs.first()) { int id = rs.getInt(1); def = findById(id); } return def; } public Definition getByDefinition(String chaine) throws SQLException { Definition def = null; String query = "SELECT * FROM DefinitionFR WHERE definition LIKE ?"; PreparedStatement stmt = connection.prepareStatement(query); stmt.setString(1, chaine); ResultSet rs = stmt.executeQuery(); if (rs.first()) { int idDef = rs.getInt("idDefinition"); String s = rs.getString("definition"); boolean validate = rs.getBoolean("existe"); def = new Definition(idDef, s, validate); return def; } return def; } @Override public Definition update(Definition obj) throws SQLException { if (obj == null) { throw new IllegalArgumentException("La definition est null"); } Definition def = null; String query = "UPDATE DefinitionFR SET definition = ? WHERE idDefinition = ?"; PreparedStatement stmt = connection.prepareStatement(query); stmt.setString(1, obj.getDefinition()); stmt.setInt(2, obj.getIdDefinition()); stmt.executeUpdate(); def = findById(obj.getIdDefinition()); return def; } @Override public void delete(Definition obj) throws SQLException { if (obj == null) { throw new IllegalArgumentException("La definition est null"); } String query = "DELETE FROM DefinitionFR WHERE idDefinition = ?"; PreparedStatement stmt = connection.prepareStatement(query); stmt.setInt(1, obj.getIdDefinition()); stmt.executeUpdate(); } }
C
UTF-8
1,421
3.84375
4
[]
no_license
/************************************************************************* > File Name: 9.c > Author: Crow > Mail: qnglsk@163.com > Created Time: Thu Sep 3 15:56:03 2020 ************************************************************************/ #include<stdio.h> /* * Write a program that initializes a two-dimensional 3×5 array-of- double and uses a VLA * based function to copy it to a second two-dimensional array. Also provide a VLA-based * function to display the contents of the two arrays. The two functions should be capable * in general, of processing arbitrary N×M arrays. * (If you don’t have access to a VLA-capable compiler, use the traditional C approach of functions that can process an N×5 array). */ #define ROWS 3 #define COLS 5 void cpar(int rs, int cs, const double arr[][cs], double cpr[][cs]); void show(int rs, int cs, const double arr[][cs]); int main(void) { double foo[ROWS][COLS] = { {1,2,3,4,5}, {6,7,8,9,10}, {11,12,13,14,15} }; double bar[ROWS][COLS]; cpar(ROWS, COLS, foo, bar); show(ROWS, COLS, foo); show(ROWS, COLS, bar); return 0; } void cpar(int rs, int cs, const double arr[][cs], double cpr[][cs]) { for(int i = 0; i < rs; i++) for(int j = 0; j < cs; j++) cpr[i][j] = arr[i][j]; } void show(int rs, int cs, const double arr[][cs]) { for(int i = 0; i < rs; i++) for(int j = 0; j < cs; j++) printf("%.0lf%c", arr[i][j], " \n"[j == cs-1]); }
Python
UTF-8
597
3.34375
3
[]
no_license
# # dictionary is a key value pair let suppose course is the dictonary 1 = english # # course ={ "khalid":"English","Ali":"urdu","salman":"Physics","imran":["English","Urdu","Dari"], # "ikram":{"A":"Computer","B":"Web Developement"}} # # # print(course["ikram"]["B"]) # # # methods # # Get # # # print(course.get("khalid")) # # course.update({"naveed":{"1":"GIS","2":"Urban"}}) # # print(course.items()) print("Enter a words") d1 = {"diligent":"inteligient","need":"to get something","want":"to need something","set":"a collection of numbers"} search =input() print (d1[search])
Markdown
UTF-8
1,972
3.359375
3
[ "MIT" ]
permissive
Data.TypeNat ============ The classic first example of a dependently typed program is the list of fixed length, or `Vect`, where the length is in its type. It's known that GHC's type system can handle this, through the GADTs, KindSignatures, and DataKinds extensions. This module provides the fixed-length list type `Vect a Nat`, as well as the `Nat` definitions which it demands. Through the use of a type-directed recursion in the `IsNat` class, we are able to provide the function `listToVect :: IsNat n => [a] -> Maybe (Vect a n)`; we did not require a special class just for the implementation of this function! Here is an example use: ```Haskell import Data.TypeNat.Vect import Data.TypeNat.Fin -- Typechecks myVector :: Vect String Three myVector = VCons "Static" (VCons "Types" (VCons "Rule" VNil)) -- Does not typecheck myBadVector :: Vect String Four myBadVector = VCons "Static" (VCons "Types" (VCons "Rule" VNil)) -- Typechecks myVectorAsList :: [String] myVectorAsList = vectToList myVector -- Typechecks, is Just myVectorAgain :: Maybe (Vect String Three) myVectorAgain = listToVect myVectorAsList -- Typechecks, is Nothing myVectorAgainBad :: Maybe (Vect String Four) myVectorAgainBad = listToVect myVectorAsList -- Typechecks mySecondElement :: String mySecondElement = safeIndex myVector ix2 -- Does not typecheck myFourthElement :: String myFourthElement = safeIndex myVector ix4 main = do putStrLn $ showVect myVector -- Prints the list, since 'vectToList myVector' has length 3 and we gave -- the type Three in our annotation. case (listToVect (vectToList myVector) :: Maybe (Vect String Three)) of Nothing -> putStrLn "Nothing" Just v -> putStrLn $ showVect v -- Prints "Nothing", since 'vectToList myVector' has length 3 and we gave -- the type Two in our annotation. case (listToVect (vectToList myVector) :: Maybe (Vect String Two)) of Nothing -> putStrLn "Nothing" Just v -> putStrLn $ showVect v ```
Java
UTF-8
930
2.625
3
[ "Apache-2.0" ]
permissive
package com.hofer.tij.common; /** * @author hofer.bhf * created on 2018/05/19 5:28 PM */ public class HelloWorld { public static void main(String[] args) { /** * http://baike.corp.taobao.com/index.php/MemberPlatform/userTagWiki#promotedType * userTag3 2的49次方 标记此用户是否为分销平台的供应商 */ final long SUPPLIER = 1L << 49; /** * userTag4 2的44次方 标记此用户是分销平台的品牌商 */ final long BRAND_SELLER = 1L << 44; long userTag3 = 72691599965995136L; long userTag4 = 1166511468326421504L; System.out.println((userTag3 & SUPPLIER) == SUPPLIER); System.out.println((userTag4 & BRAND_SELLER) == BRAND_SELLER); boolean isSupplier = ((userTag3 & SUPPLIER) == SUPPLIER) || ((userTag4 & BRAND_SELLER) == BRAND_SELLER); System.out.println(isSupplier); } }
PHP
UTF-8
2,889
2.953125
3
[]
no_license
<?php require_once './model/Actor.php'; //require_once '../model/data/MySQLiCustomerDataModel.php'; require_once './model/data/PDOMySQLCustomerDataModel.php'; class ActorModel { private $m_DataAccess; public function __construct() { //$this->m_DataAccess = new MySQLiCustomerDataModel(); $this->m_DataAccess = new PDOMySQLCustomerDataModel(); } public function __destruct() { // not doing anything at the moment } public function getAllActors() { $this->m_DataAccess->connectToDB(); $arrayOfActorObjects = array(); $this->m_DataAccess->selectActors(); while($row = $this->m_DataAccess->fetchActors()) { $currentActor = new Actor($this->m_DataAccess->fetchActorID($row), $this->m_DataAccess->fetchActorFirstName($row), $this->m_DataAccess->fetchActorLastName($row)); $arrayOfActorObjects[] = $currentActor; } $this->m_DataAccess->closeDB(); return $arrayOfActorObjects; } public function getActor($custID) { $this->m_DataAccess->connectToDB(); $this->m_DataAccess->GetActorByID($custID); $record = $this->m_DataAccess->fetchActors(); $fetchedCustomer = new Actor($this->m_DataAccess->fetchActorID($record), $this->m_DataAccess->fetchActorFirstName($record), $this->m_DataAccess->fetchActorLastName($record)); $this->m_DataAccess->closeDB(); return $fetchedCustomer; } public function deleteActor($custID) { $this->m_DataAccess->connectToDB(); $this->m_DataAccess->DeleteActor($custID); $this->getAllActors(); $this->m_DataAccess->closeDB(); } public function searchActor($query) { $this->m_DataAccess->connectToDB(); $this->m_DataAccess->searchActors($query); $arrayOfActorObjects = array(); while($row = $this->m_DataAccess->fetchActors()) { $currentActor = new Actor($this->m_DataAccess->fetchActorID($row), $this->m_DataAccess->fetchActorFirstName($row), $this->m_DataAccess->fetchActorLastName($row)); $arrayOfActorObjects[] = $currentActor; } $this->m_DataAccess->closeDB(); return $arrayOfActorObjects; } public function UpdateActor($Actor){ $custID = $Actor->getID(); $fName = $Actor->getFirstName(); $lName = $Actor->getLastName(); $this->m_DataAccess->connectToDB(); $this->m_DataAccess->UpdateActor($custID,$fName,$lName); $this->m_DataAccess->closeDB(); } public function AddActor($fName,$Lname){ $this->m_DataAccess->connectToDB(); $this->m_DataAccess->AddActor($fName,$Lname); $this->m_DataAccess->closeDB(); } }
TypeScript
UTF-8
5,314
2.546875
3
[]
no_license
import * as assert from "assert"; import * as discovery from "../lib/index"; const pairs = { SERVICE_REDIS_TCP_PROTO: "tcp", SERVICE_REDIS_TCP_HOST: "redis.com", SERVICE_REDIS_TCP_PORT: "6379", SERVICE_GOOGLE_API_PROTO: "https", SERVICE_GOOGLE_API_HOST: "api.google.com", SERVICE_GOOGLE_API_PORT: "80", SERVICE_LONG_APP_NAME_API_HOST: "arbitrary", SERVICE_MISSING_PROTO_API_HOST: "missingproto.host", SERVICE_MISSING_PROTO_API_PORT: "5000", SERVICE_MISSING_HOST_API_PROTO: "missinghost.proto", SERVICE_MISSING_HOST_API_PORT: "5000", SERVICE_MISSING_PORT_API_PROTO: "missingport.proto", SERVICE_MISSING_PORT_API_HOST: "example.com", SERVICE_MISSING_PROTO_AND_HOST_FOOBAR_PORT: "8000", }; describe("discovery", () => { beforeAll(() => { const results = []; for (const name of Object.keys(pairs)) { const value = pairs[name as keyof typeof pairs]; results.push((process.env[name] = value)); } return results; }); it("test redis tcp discovery", () => { const expected_proto = "tcp"; const expected_host = "redis.com"; const expected_port = "6379"; const expected_url = `${expected_proto}://${expected_host}:${expected_port}`; const expected_proto_host = `${expected_proto}://${expected_host}`; const expected_host_port = `${expected_host}:${expected_port}`; const disc = discovery("redis", "tcp"); assert.equal(disc.proto(), expected_proto); assert.equal(disc.host(), expected_host); assert.equal(disc.port(), expected_port); assert.equal(disc.url(), expected_url); assert.equal(disc.proto_host(), expected_proto_host); return assert.equal(disc.host_port(), expected_host_port); }); it("test google https discovery", () => { const expected_proto = "https"; const expected_host = "api.google.com"; const expected_port = "80"; const expected_url = `${expected_proto}://${expected_host}:${expected_port}`; const expected_proto_host = `${expected_proto}://${expected_host}`; const expected_host_port = `${expected_host}:${expected_port}`; const disc = discovery("google", "api"); assert.equal(disc.proto(), expected_proto); assert.equal(disc.host(), expected_host); assert.equal(disc.port(), expected_port); assert.equal(disc.url(), expected_url); assert.equal(disc.proto_host(), expected_proto_host); return assert.equal(disc.host_port(), expected_host_port); }); it("test long arbitrary name with dashes", () => { const disc = discovery("long-app-name", "api"); assert.equal(disc.host(), "arbitrary"); assert.throws(() => disc.proto(), /Missing env var SERVICE_LONG_APP_NAME_API_PROTO/); assert.throws(() => disc.port(), /Missing env var SERVICE_LONG_APP_NAME_API_PORT/); assert.throws(() => disc.proto_host(), /Missing env var SERVICE_LONG_APP_NAME_API_PROTO/); assert.throws(() => disc.host_port(), /Missing env var SERVICE_LONG_APP_NAME_API_PORT/); assert.throws(() => disc.url(), /Missing env var SERVICE_LONG_APP_NAME_API_[\w]+/); }); it("test expect error on missing proto", () => { const disc = discovery("missing-proto", "api"); assert.equal(disc.host(), "missingproto.host"); assert.equal(disc.port(), "5000"); assert.equal(disc.host_port(), "missingproto.host:5000"); const expected_error = /Missing env var SERVICE_MISSING_PROTO_API_PROTO/; assert.throws(() => disc.proto(), expected_error); assert.throws(() => disc.proto_host(), expected_error); assert.throws(() => disc.url(), expected_error); }); it("test expect error on missing host", () => { const disc = discovery("missing-host", "api"); assert.equal(disc.proto(), "missinghost.proto"); assert.equal(disc.port(), "5000"); const expected_error = /Missing env var SERVICE_MISSING_HOST_API_HOST/; assert.throws(() => disc.host(), expected_error); assert.throws(() => disc.proto_host(), expected_error); assert.throws(() => disc.host_port(), expected_error); assert.throws(() => disc.url(), expected_error); }); it("test expect error on missing port", () => { const disc = discovery("missing-port", "api"); assert.equal(disc.proto(), "missingport.proto"); assert.equal(disc.host(), "example.com"); assert.equal(disc.proto_host(), "missingport.proto://example.com"); const expected_error = /Missing env var SERVICE_MISSING_PORT_API_PORT/; assert.throws(() => disc.port(), expected_error); assert.throws(() => disc.host_port(), expected_error); assert.throws(() => disc.url(), expected_error); }); return it("test expect error on missing two vars", () => { const disc = discovery("missing-proto-and-host", "foobar"); assert.equal(disc.port(), "8000"); assert.throws( () => disc.proto(), /Missing env var SERVICE_MISSING_PROTO_AND_HOST_FOOBAR_PROTO/, ); assert.throws(() => disc.host(), /Missing env var SERVICE_MISSING_PROTO_AND_HOST_FOOBAR_HOST/); assert.throws( () => disc.proto_host(), /Missing env var SERVICE_MISSING_PROTO_AND_HOST_FOOBAR_[\w]+/, ); assert.throws( () => disc.host_port(), /Missing env var SERVICE_MISSING_PROTO_AND_HOST_FOOBAR_HOST/, ); assert.throws(() => disc.url(), /Missing env var SERVICE_MISSING_PROTO_AND_HOST_FOOBAR_[\w]+/); }); });
Markdown
UTF-8
1,149
2.765625
3
[]
no_license
# oddball MATLAB code for auditory oddball task with eyetracking. This is just a super simple example for how to play sound and record eyetracking using Psychtoolbox (http://psychtoolbox.org/) in MATLAB. SPECIAL NOTE: The sounds in the folder 'SoundFiles' have not been RMS equalised!!! SPECIAL NOTE 2: There might be **many bugs!** ## Stimuli In one block, deviant sounds were presented against standard sounds. The standard sound is a 500-Hz pure tone, and there are two deviant types: white noise and harmonic tones (f0=200 Hz; 30 harmonics). All sounds are 500 ms long and with 30-ms cosine onset and offset ramps. (THEY SHOULD ALSO BE RMS EQUALISED.) In total, each deviant type was presented 10 times, for 20 deviant trials in total, and the standard type presented 60 times, resulting in an overall deviant probability of 25%. The inter-sound-onset interval is randomised between 3-3.5 second. ## Procedure After calibration, subjects should be instructed to fixate their pupils on a fixation cross and listen to the sounds through headphones. Before the presentation of the first sound, there is a 15-second long resting state recording.
Java
UTF-8
674
2.125
2
[]
no_license
package com.juggle.juggle.primary.setting.dto; import java.io.Serializable; import java.util.List; public class DomainRelation implements Serializable { private Long id; private String name; private List<DomainRelation> children; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<DomainRelation> getChildren() { return children; } public void setChildren(List<DomainRelation> children) { this.children = children; } }
C#
UTF-8
872
2.734375
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Cloney.Core.Reflection; using Cloney.Core.SubRoutines; namespace Cloney.Core { /// <summary> /// This class can be used to find every sub routine /// that is defined in the executing assembly. /// </summary> /// <remarks> /// Author: Daniel Saidi [daniel.saidi@gmail.com] /// Link: http://danielsaidi.github.com/Cloney /// </remarks> public class SubRoutineLocator : ISubRoutineLocator { public IEnumerable<ISubRoutine> FindAll() { var assembly = Assembly.GetExecutingAssembly(); var routines = assembly.GetTypesThatImplement(typeof (ISubRoutine)); return routines.Select(routine => (ISubRoutine) Activator.CreateInstance(routine)).ToList(); } } }
PHP
UTF-8
2,732
3.3125
3
[]
no_license
<?php include __DIR__ . '/vendor/autoload.php'; ini_set('error_reporting', E_ALL); ini_set('display_errors', 1); ini_set('display_startup_errors', 1); echo '<h2>-----Бинарный поиск-----</h2><br>'; $binarySearch = new \App\GrokkingAlgorithms\BinarySearch(); echo 'Исходный массив: '; echo '<pre>'; var_dump($binarySearch->getArray()); echo '</pre>'; // --------------Example------------------ echo $binarySearch->exampleSearch(3); echo '<br>Задача 1: Имеется отсортированный список из 128 имен, и вы ищите в нем значение методом бинарного поиска. Какое максимальное кол-во проверок?<br>'; // ОТВЕТ: log128 = 7 echo '<br>Задача 2: Предположим, размер списка увеличился вдвоем. Как изменится максимальное кол-во проверок<br>'; // ОТВЕТ: log256 = 8 echo '<h2>-----Сортировка выбором-----</h2><br>'; $selectionSort = new \App\GrokkingAlgorithms\SelectionSort(); echo 'Исходный массив: '; echo '<pre>'; var_dump($selectionSort->getArray()); echo '</pre>'; $array = $selectionSort->sort($selectionSort->getArray()); echo 'Отсортированный массив: '; echo '<pre>'; var_dump($array); echo '</pre>'; //echo '<h2>-----Рекурсия-----</h2><br>'; // //$recursion = new \App\GrokkingAlgorithms\Recursion(); // // //$pile = [ // 'box0', // 'box' => ['box', 'box'], // 'box1'=>['box', 'box'], // 'box2'=>['box', 'box', 'key'], // 'box3'=>['box', 'box'], // //]; // //$recursion->searchKey($pile); echo '<h2>-----Сумма массива рекурсия-----</h2><br>'; $fastSotringObject = new \App\GrokkingAlgorithms\QuickSort(); $array = [1, 2, 3, 14, 5, 12]; $summ = $fastSotringObject->sum($array); echo $summ; echo '<h2>-----Число элементов массива рекурсия-----</h2><br>'; $count = $fastSotringObject->count($array); echo $count; echo '<h2>-----Поиск макс. значения массива рекурсия-----</h2><br>'; $max = $fastSotringObject->searchMax($array); echo $max; echo '<h2>-----Быстрая сортировка-----</h2><br>'; $quickArray = $fastSotringObject->sort($array); echo "<pre>"; var_dump($quickArray); echo "</pre>"; echo '<h2>-----Графы-----</h2><br>'; $graphs = new \App\GrokkingAlgorithms\Graphs(); $mango = $graphs->searchSeller(); var_dump($mango); echo '<h2>-----Алгоритм Дейкстры-----</h2><br>'; $dijkstras = new \App\GrokkingAlgorithms\Dijkstras(); $nodes = $dijkstras->searchWay(); var_dump($nodes);
C#
UTF-8
1,375
2.671875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GUI.ViewModel { /// <summary> /// Абстракная модель представления рабочей области(вкладки) /// </summary> public abstract class WorkSpaceViewModel : ValidatedViewModelBase { /// <summary> /// Ссылка на главную модель представления /// </summary> //public MainWindowViewModel Parent { get; set; } /// <summary> /// Событие закрытмя рабочей области /// </summary> public event EventHandler Closed; /// <summary> /// Виртуальный метод обработки вызова закрытия вкладки /// </summary> protected virtual void OnClosed() { Closed?.Invoke(this, EventArgs.Empty); } /// <summary> /// Статус режима только для чтения (заглушка => всегда нет) /// </summary> public override bool IsReadOnly => false; /// <summary> /// Закрытие вкладки /// </summary> public void Close() { //Parent?.Remove(this); OnClosed(); } } }
Markdown
UTF-8
2,048
2.703125
3
[ "MIT" ]
permissive
onetwopunch =========== Nmap is by far the most comprehensive port scanner, able to identify services, fingerprint operating systems, and even run several scripts against the services to identify potential vulnerabilities. This helps cut down the manual work involved in service enumeration. Nmap uses a default list of ports when none are provided by the attacker. This can cause nmap to miss certain ports that are not in its default list. There is the option to let nmap scan all 65,535 ports on each machine, but as you can imagine, this will take a considerable amount of time, especially if you’re scanning a lot of targets. Unicornscan is another port scanner that utilizes it’s own userland TCP/IP stack, which allows it to run a asynchronous scans. This makes it a whole lot faster than nmap and can scan 65,535 ports in a relatively shorter time frame. Since unicornscan is so fast, it makes sense to use it for scanning large networks or a large number of ports. So, the idea behind this post is to utilize both tools to generate a scan of 65,535 ports on the targets. We will use unicornscan to scan all ports, and make a list of those ports that are open. We will then take the open ports and pass them to nmap for service detection. For more details, see [http://blog.techorganic.com/2012/05/31/port-scanning-one-two-punch/](http://blog.techorganic.com/2012/05/31/port-scanning-one-two-punch/) Improvements ============ + Added -v flag to see the command used and be verbose + Print usage in case the script is not run as root + Use a single target instead of a target file + Made the default of no option for nmap REALLY no option + Made logdir in the pwd + Removed unnecessary directories in /scan and made .txt output files only Updated usage ============= ``` Usage: onetwopunch -t target [-p tcp/udp/all] [-n nmap-options] [-v] [-h] -h: Help -t: Target -p: Protocol. Defaults to tcp -n: NMAP options (-A, -O, etc). Defaults to no options. -v: Debug, see commands and be verbose ```
Java
UTF-8
1,229
2.5625
3
[]
no_license
package com.github.sdvic; //****************************************************************************************** // * Application to extract Cash Flow data from Quick Books P&L and build Cash Projections // * version 210115 // * copyright 2020 Vic Wintriss //******************************************************************************************* import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.File; import java.io.FileOutputStream; public class BudgetWriter { private final File updated2020MasterBudgetOutputFile = new File("/Users/vicwintriss/-League/Financial/Budget/Budget2021/Updated2021Budget.xlsx"); public void writeBudget(XSSFWorkbook budgetWorkbook) { System.out.println("(9) Writing budget workbook to File: " + updated2020MasterBudgetOutputFile); try { FileOutputStream budgetOutputFOS = new FileOutputStream(updated2020MasterBudgetOutputFile); budgetWorkbook.write(budgetOutputFOS); budgetOutputFOS.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println("(10) Finished writing budget workbook to File: " + updated2020MasterBudgetOutputFile); } }
Markdown
UTF-8
16,664
2.640625
3
[]
no_license
# 3. Python을 활용한 머신러닝 정리 Python을 활용한 머신러닝에 있는 교재와 강의 내용을 재구성하여 정리합니다. ## 머신러닝 머신러닝은 데이터로부터 경험을 축적하여 스스로 학습할 수 있는 모델을 연구하는 분야입니다. 어떤 현상을 예측하는 모델(시스템)을 만들 때, 고전적인 방식으로는 통계적 알고리즘을 통해 모델을 만들었습니다. (이는 Python을 활용한 데이터분석과 시각화에서 했었습니다.) 최근에는 **머신러닝 알고리즘**을 통해 모델을 만듭니다. 고전적인 방식과는 달리 머신러닝 알고리즘은 새로운 데이터를 학습하여 모델을 더욱 강화시켜 예측력을 높입니다. 데이터의 업데이트에 자동으로 적응하여 자동화가 가능하다는 점이 있습니다. --- ### 머신러닝의 종류 #### 지도학습 머신러닝 독립변수와 종속변수 모두 주어진 상태로 종속변수를 기준으로 독립변수의 차이점을 이용하여 나눌 수 있는 모델을 만들어냅니다.(Python을 활용한 데이터분석과 시각화에서의 기법을 일부 사용합니다.) **KNN, 일반화 선형 모델, 의사결정 트리, 랜덤 포레스트, 신경망 딥러닝**이 있습니다. #### 자율학습 머신러닝 독립변수만 주어진 상태로 독립변수의 값이 비슷한 것끼리 묶여 하나의 군집을 이룹니다. (Python을 활용한 텍스트 마이닝의 기법을 일부 사용합니다.) **클러스터링, 차원 축소, 비정상 탐지**가 있습니다. --- #### 머신러닝 모델이 잘 만들어질 조건 데이터의 양이 많아야 하고 질이 좋아야 합니다. (지도학습에 있어서는) 변수들이 종속변수에 관련성이 높아야 합니다. 또한 수치로 표현된 데이터는 표준화, 정규화를 적절히 해야합니다. 과대적합, 과소적합을 피하고 머신러닝 알고리즘을 다양하게 이용해 보는게 좋습니다. ### 머신러닝 알고리즘 머신러닝 알고리즘의 절차에 대해 소개합니다. 1. 데이터 전처리과정을 거칩니다. 데이터를 **표준화**, **정규화**를 거쳐야 합니다. 이는 데이터의 단위가 다르기 때문에 거쳐야 할 부분입니다. 범주형 특성변수는 데이터 변수를 늘리고 0과 1로 나타내는 방식을 사용합니다(**one-hot-encoding**). 계산하기 힘든 고차원일 경우에는 PCA 명령어로 차원 축소할 수 있습니다. 2. 데이터 셋(Data set)을 무작위로 **학습(훈련) 데이터**, **테스트 데이터**로 나눕니다. 이때 그 비율은 7:3을 가지게 합니다. 필요하면 학습 데이터를 학습 데이터, **검증 데이터**로 나눌 수 있습니다 (7:3). 학습 데이터를 그룹으로 나누어서 교차 검증하면 좋습니다. 3. 학습 데이터와 파라미터에 영향을 받는 **머신러닝 알고리즘 모델**을 만듭니다. 그리고 검증 데이터를 이용하여 모델을 평가합니다. 정확도, 과소/과대추정이 되었는지 확인해보고 **파라미터**(머신러닝 알고리즘에 있는 상수값)을 조금씩 조정하면서 최적의 값을 찾아봅니다. 파라미터를 연구자가 직접 정하는 Grid Search방식으로, 범위 내에서 마구잡이로 찾아보는 Random Search 방식으로 찾을 수 있습니다. 4. 파라미터 값을 조금씩 조정하다가 테스트 데이터에 가장 잘 맞는 최적의 파라미터(**Hyper Parameter**를 조정)을 찾고 그 모델로 결정합니다. --- 머신러닝의 각 절차에 대해 알아보기 전에 머신러닝 맛보기를 해 봅시다. ## K-최근접 이웃(KNN) 지도 학습중 하나로서 **데이터 분류**를 위한 기계학습 알고리즘 중 하나입니다. KNN은 각 데이터를 XYZ...축으로 두고 각 데이터 사이의 거리를 측정하여 k개의 다른 데이터의 레이블을 참조하여 분류하는 방법입니다. 보통 거리를 잴 때에는 유클리디안 거리 계산법을 사용합니다. k값은 KNN의 **파라미터**가 되고 k가 작을수록 학습 데이터의 정확도는 높아지나, 테스트 데이터에는 부적합 할 수 있습니다(underfitting). 반대로 k가 클수록 일반화는 가능하지만 정확도가 떨어질 수 있습니다(overfitting). 보통 3~10 정도가 일반적 k수가 됩니다. #### 특징 장점은 알고리즘이 간단하고 구현하기가 쉽습니다. 수치 기반 데이터 분류 작업에서 성능이 좋습니다. 단점은 데이터의 양이 많으면 계산 속도가 느립니다. 차원의 크기가 커지면 계산량이 많아집니다. 새로운 데이터가 들어오면 기존 데이터의 거리를 모두 계산 후 분류합니다. (인스턴트 기반 학습) #### 명령어 X변수에 따라 투표의 유무, 어느 정당을 지지하는지 볼 수 있습니다. ```python # 1. 데이터를 불러옵니다. import pandas as pd data = pd.read_csv('vote.csv') # 2. 특성변수(X)와 레이블 변수(y)로 나눕니다. X = data[data.columns[0:8]] # data.loc[:, 'gender':'score_intention] # data[['gender', 'region', ... , 'score_intention]] 도 가능합니다. y1 = data[['vote']] y2 = data[['parties']] # 3. train set, test set으로 나눕니다. from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y1, stratify=y1, random_state=42) # stratify는 혹시나 레이블 변수가 특정 값 한쪽에만 너무 쏠리지 않을까 해서 골고루 뽑힐 수 있게 하는 안전장치힙니다. # random_state는 시드입니다. 아무렇게나 써도 됩니다. # 4. 모델을 적용합니다. from sklearn.neighbors import KNeighborsClassifier knn = KNeighborsClassifier(n_neighbors=3) # knn을 사용할 Class를 가져옵니다. K수는 3으로 지정해봅니다. knn.fit(X_train, y_train) # <class>.fit(<train data>)는 머신러닝 알고리즘을 이용한 모델을 만드는 명령어이므로 핵심적으로 돌아가는 부분입니다. 상황에 따라서 오래 걸릴 수 있습니다. #이제 knn은 학습이 된 모델입니다. # 5. 모델을 평가합니다. pred_train = knn.predict(X_train) print(knn.score(X_train, y_train)) # output : train data 예측 확률 print(pd.crosstab(y_train.vote, pred_train)) # output : 오차행렬 pred_test = knn.predict(X_test) print(knn.score(X_test, pred_test)) # output : test data 예측 확률 print(pd.crosstab(y_test.vote, pred_test)) # output : 오차행렬 ``` ---- 이제 머신러닝 알고리즘 순서에 따라 봅시다. ## 1. 데이터 스케일링과 범주특성의 변환 연속형 자료에서 단위가 다를 경우 과대 혹은 과소한 파라미터가 추정되기에 동일한 기준으로 자료를 변환합니다. 키와 시력에 대한 자료를 보면 키의 값이 훨씬 평균과 표준편차가 훨씬 높게 나타나므로 자료를 변환해야합니다. #### Min-Max Scaling 각 데이터의 값를 원래 (현재 데이터의 값 - 가장 작은 데이터의 값)을 가장 큰 값과 가장 작은 값의 차이로 나누어줍니다. (0~1 사이의 값을 가지게 됩니다.) 그 값으로 변환합니다. #### standardization 표준화는 각 수치와 평균의 차이를 표준편차로 나눈 값입니다. 표준화로 스케일링 하면 평균이 0, 표준편차가 1이 되는 통계적인 자료 표준화의 대표적 값입니다. #### one-hot-encoding 범주형 자료가 숫자로 되어있을 경우 여러 개의 연속형 자료로 나누는 것. 각 변수의 하위 범주에 해당되는지 아닌지를 구분하는 0과 1의 값으로 하위 범주 변수들을 생성합니다. vote.csv 파일을 스케일링하여 봅시다. ```Python import pandas as pd data = pd.read_csv('vote.csv', encoding='utf-8') #one-hot-encoding X1 = data[['gender', 'region']] # one-hot-encoding 할 부분 X2 = data[['edu', 'income', 'score_gov', 'score_progress', 'score_intention']] y = data[['vote', 'parties']] # Min-Max scaling 할 부분 X1['gender'] = X1['gender'].replace([1,2], ['male', 'female']) X1['region'] = X1['region'].replace([1,2,3,4,5], ['Sudo', 'Chungcheung', 'Honam', 'Youngnam', 'Others']) X1_dum = pd.get_dummies(X1) # Min-max scaling from sklearn.preprocessing import MinMaxScaler scaler1 = MinMaxScaler() scaler1.fit(X2) X_scaled1 = scaler1.transform(X2) # Standardization from sklearn.preprocessing import StandardScaler scaler2 =sStandradScaler() scaler2.fit(X2) X_scaled2 = scaler2.transform(X2) pd.DataFrame(X_scaled2).describe() #자료 통합 및 저장하기 import pandas as pd X_scaled = pd.DataFrame(X_scaled1) X_scaled.columns = ['edu', 'income', 'age', 'score_gov', 'score_progress', 'score_intention'] Fvote = pd.concat([X1_dum, X_scaled, y], axis=1) Fvote.to_csv('Fvote.csv', sep=',', encoding='utf-8') ``` ## 2. 데이터 셋 나누기 결과의 일반화 성능비교를 위해서 훈련데이터와 테스트데이터로 구분합니다. 일반적으로 훈련데이터의 교차검증과 테스트 데이터를 병행하는 것이 안정적입니다. #### cross_val_score(랜덤없는 교차검증) 데이터를 5폴드(군집)으로 나누어서 4개의 군집은 훈련데이터로, 1개는 테스트 데이터로 하여 각 군집에 대해서 5번 반복합니다. #### KFold(랜덤있는 교차검증) 랜덤있는 교차검증은 순서에 영향을 받는 랜덤없는 교차 검증과 달리 종속 변수(레이블)에 따라 폴드가 나누기 때문에 과소, 과대하게 분류되지 않는 장점이 있습니다. #### shuffle-split cross validation(임의분할 교차검증) 훈련데이터와 테스트 데이터를 구성할 대 다른 교차검증에 사용되었던 데이터도 랜덤으로 선택되게 하는 방법입니다. (복원추출) 그런 과정에서 전체 데이터 중 일부는 훈련데이터 또는 테스트데이터 어디에서 선택되지 않을 수 있습니다. (미선택 데이터) ### 훈련-검증-테스트 데이터로 나누기 훈련데이터, 테스트 데이터 이외에 **검증 데이터**를 두어 일반화 경향을 더 파악하는 방법입니다. 보통 훈련데이터, 검증데이터, 테스트 데이터를 5:2:3으로 둡니다. ```python import pandas as pd data = pd.read_csv('Fvote.csv', encoding = 'utf-8') X = data[data.columns[1:14]] y = data[['vote']] from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=42) from sklearn.neighbors import KNeighborsClassifier knn = KNeighborsClassifier(n_neighbors=3) #1 랜덤없는 교차검증 from sklearn.model_selection import cross_val_score score1 = cross_val_score(knn, X_train, y_train, cv=5) #KNN방식(k=3)으로 머신러닝합니다. X_train과 y_train방식으로, 폴드는 순서대로 5폴드 #2 랜덤있는 교차검증 from sklearn.model_selection import KFold kfold = KFold(n_splits=5, shuffle=True, random_state=42) #랜덤으로 섞고(이 때 시드는 42) 폴드는 5폴드 score2 = cross_val_score(knn, X_train, y_train, cv=kfold) #knn방식(k=3)으로 머신러닝합니다, 폴드는 kfold값에 따라서 합니다. #3 임의분할 교차검증 from sklearn.model_selection import ShuffleSplit shuffle_split = ShuffleSplit(test_size=0.5, train_size=0.5, random_state=42) #전체의 test데이터 비율, 전체의 train비율을 정합니다. score3 = cross_val_score(knn, X_train, y_train, cv=shuffle_split) #knn방식(k=3)으로 머신러닝합니다, 폴드는 shuffle_split값에 따라서 합니다. # --- #4 train/test/validity 분할과 교차검증 from skelarn.model_selection import train_test_split X_train_val, X_test, y_train_val, y_test = train_test_split(X, y, random_state = 1) X_train, X_vaild, y_train, y_vaild = train_test_split(X_train_val, y_train_cal, random_state=2) from sklearn.neighbors import KNeighborsClassifier knn = KNeighborsClassifier(n_neighbors=3) knn.fit(X_train, y_train) scores = cross_val_score(knn, X_train, y_train, cv=5) knn.score(X_valid, y_valid) knn.score(X_test, y_test) #이렇게 검증데이터, 시험데이터로 나누어서 해 볼 수가 있다. ``` ## 3. 파라미터 조절 및 지정 (모델 훈련과 세부튜닝) 연구자가 일일히 파라미터 값을 지정하기에는 비효율적입니다. 그래서 컴퓨터가 다양한 파라미터를 머닝러닝 알고리즘에 넣어 가장 좋은 데이터를 집어주는 모델을 세우고자 한다. #### 그리드 탐색 탐색하고자 하는 하이퍼파라미터를 지정하면 가능한 조합에 대한 교차검증을 사용해 평가하는 방법입니다. 분석자가 직접 하이퍼파라미터를 지정해주어야 합니다. ```python import pandas as pd data = pd.read_csv('Fvote.csv', encoding = 'utf-8') X = data[data.columns[1:14]] y = data[['vote']] from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=42) from sklearn.model_selection import GridSearchCV param_grid = {'n_neighbors' : [1, 2, 3, 4, 5, 6, 7, 8, 9 ,10]} from sklearn.neighbors import KNeighborsClassifier grid_search = GridSearchCV(KNeighborsClassifier(), param_grid, cv=5) #찾는 방법은 그리드 탐색, KNN(k=1,2,3,4,5,6,7,8,9,10), 군집은 5군집 => 총 50번 반복하게 된다! grid_search.fit(X_train, y_train) #이를 X, y 훈련 데이터에 적용하여 머신러닝 모델이 완성됩니다. grid_search.best_params_ # output : 최적의 k값 grid_search.best_score_ # output : 최적의 k값을 사용했을때의 정확도 grid_search.score(X_test, y_test) # output : 시험데이터를 머신러닝 모델에 적용했을때의 정확도 result_gird = pd.DataFrame(grid_search.cv_results_) # 각 c값에 대해서 정확도 체크 import matplotlib.pyplot as plt plt.plot(result_grid['param_n_neighbors'], result_grid['mean_train_score'], label='Train') plt.plot(result_grid['param_n_neighbors'], result_grid['mean_test_score'], label = 'Test') plt.legend() ``` #### 랜덤 탐색 분석자가 지정한 하이퍼파라미터의 조합이 아닌 지정한 범위 내에서 랜덤으로 하이퍼파라미터를 선정하여 분석하는 방법입니다. 그리드 탐색에 비해 더욱 다양한 탐색이 가능합니다. ```python import pandas as pd data = pd.read_csv('Fvote.csv', encoding = 'utf-8') X = data[data.columns[1:14]] y = data[['vote']] from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=42) #여기까지 기본 세팅 #랜덤 탐색을 위해 K값을 지정합니다 from sklearn.model_selection import RandomizedSearchCV from scipy.stats import randint param_distribs = {'n_neighbors':randint(low=1, high=20)} #최소 1, 최대 20 from sklearn.neighbors import KNeighborsClassifier random_search = RandomizedSearchCV(KNeighborsClassifier(), param_distributions = param_distribs, cv = 5) #랜덤 탐색을 해라, knn방식으로, k는 param_distrub 변수에 따라 파라미터 결정, 군집은 5개 나누어서 random_search.fit(X_train, y_train) #머신러닝 모델을 만들었음! 군집 5개에 파라미터 10개이므로 총 50번 계산함을 알 수 있다. #각각의 output 확인 random_search.best_params_ random_search.best_score_ random_search.score(X_test, y_test) # 교재에 없는 이 과정 꼭 해주어야 합니다!!! 그래프를 보기 위해서 정렬 작업을 해 줍니다. result_random = random_search.cv_results_ result_random = pd.DataFrame(result_random) result_random = result_random.sort_values('param_n_neighbors') import matplotlib.pyplot as plt plt.plot(result_random['param_n_neighbors'], result_random['mean_train_score'], label='Train') plt.plot(result_random['param_n_neighbors'], result_random['mean_test_score'], label='Test') plt.legend() ``` ## 4. 모델평가 훈련된 머신러닝 알고리즘 모델을 테스트 데이터셋에 적용해 봄으로써 모델의 일반화 가능성을 평가합니다. 정확도를 통해 실제와 예측이 얼마나 일치하는가를 보아 모델의 성능을 평가합니다.
Markdown
UTF-8
2,576
3.640625
4
[]
no_license
# Asset Tree Overview Asset tree is a key function of EnOS Device Management service. Asset tree mainly targets to asset owners who understand the enterprise asset management business. Therefore, they can quickly create the asset topology to manage assets in the cloud. The asset tree function and the device management function are decoupled, which means that the device management operation is independent of the asset management. Therefore, you can complete device management and connection first and then bind the connected devices to the nodes of the asset tree. You can also create an asset tree before you provision and connect the devices. Generally, a connected device is usually bound to a node of the asset tree. ## Key Concepts ### Asset Tree An asset tree is the hierarchical organization of assets. An asset can be added to multiple asset trees so that the assets can be managed from different dimensions for different business scenarios. Scenarios for multiple asset trees are as follows: - Management based on geographical location: country, state, city, district, etc. - Management based on industry domain: wind power, photovoltaic, energy storage, etc. - Management based on device type: fan, inverter, combiner box, etc. For the scenarios above, you can create three asset trees for the same group of assets. ### Asset An asset is the minimum element that forms an asset tree. It can be bound to a node on an asset tree. Assets can be divided into device assets and logical assets. A device asset is a physical device, for example, a photovoltaic inverter, or a wind turbine. A logical asset can be a place to hold devices or a collection of devices, such as a site, an area, or a floor. Each asset of an asset tree has a unique identifier. An asset can be bound to different asset trees and must be unique under one asset tree. The relationship between asset trees, assets, and devices is shown in the following figure: .. image:: ../../media/asset_tree.png :width: 300px If a user deleted a device in **Device Management**, the corresponding asset bound to the asset tree node becomes an invalid node. Except for an invalid node, you can continue to bind assets to every node on an asset tree. The maximum layers that an asset tree can have is 7, including the root layer. On each layer except the root layer, a maximum of 10000 peer assets are allowed to exist. - Asset 1 is bound to Tree 1. - Asset 3 is a device and is a child node of Asset 2. ## Related Information - [Getting Started with Asset Tree](gettingstarted_assettree)
Python
UTF-8
223
3.109375
3
[]
no_license
import re def validate_phone_number(number): if re.match(r'^01[016789][1-9]\d{6,7}', number): return True return False print(validate_phone_number('01042103117')) print(validate_phone_number('0125077006'))
Python
UTF-8
1,436
3.265625
3
[]
no_license
#!/usr/bin/env python3 def func(fore_color='black', back_color='white', link_color='blue', visited_color='yellow'): return (fore_color, back_color, link_color, visited_color) def test1_func(): test = ('red', 'blue', 'yellow', 'chartreuse') assert test == func('red', 'blue', 'yellow', 'chartreuse') def test2_func(): test = ('black', 'blue', 'red', 'yellow') assert test == func(link_color='red', back_color='blue') def test3_func(): test = ('purple', 'blue', 'red', 'yellow') assert test == func('purple', link_color='red', back_color='blue') regular = ('red', 'blue') links = {'link_color': 'chartreuse'} def test4_func(): test = ('red', 'blue', 'chartreuse', 'yellow') assert test == func(*regular, **links) def func2(*args, **kwargs): print('args: ', args) print('kwargs: ', kwargs) return (args, kwargs) def test1_func2(): test = (('red', 'blue', 'yellow', 'chartreuse'), {}) assert test == func2('red', 'blue', 'yellow', 'chartreuse') def test2_func2(): test = ((), {'link_color': 'red', 'back_color': 'blue'}) assert test == func2(link_color='red', back_color='blue') def test3_func2(): test = (('purple',), {'link_color': 'red', 'back_color': 'blue'}) assert test == func2('purple', link_color='red', back_color='blue') def test4_func2(): test = (('red', 'blue'), {'link_color': 'chartreuse'}) assert test == func2(*regular, **links)
C++
UTF-8
481
3.078125
3
[]
no_license
#include <fstream> #include <iostream> #include <vector> #include <string> #include <string.h> using namespace std; void removeChar(string & source, unsigned int index) { for(unsigned int i=0; i<source.size(); i++){ if(i >= index){ source[i] = source[i+1]; } } } int main(int argc, char ** argv){ if(argc > 1){ // char * a = argv[1]; string a(argv[1]); removeChar(a, 2); cout << a << " " << endl; } };
Go
UTF-8
1,555
2.859375
3
[]
no_license
// Package main initializes server and in-memory map loaded from offline database, // and registers handlers to controller functions. package main import ( "fmt" "log" "net/http" "os" "time" "gpl/ch7/exercises/e7.12/ctrl" "gpl/ch7/exercises/e7.12/model" "gpl/ch7/exercises/e7.12/util" ) func main() { // create db directory and log directory/file if non-existent if _, err := os.Stat("db"); os.IsNotExist(err) { os.Mkdir("db", 0744) fmt.Println("'main': 'db' directory created") } if _, err := os.Stat("log"); os.IsNotExist(err) { os.Mkdir("log", 0744) fmt.Println("'main': 'log' directory created") } if _, err := os.Stat("log/fail_log.log"); os.IsNotExist(err) { os.Create("log/fail_log.log") fmt.Println("'main':'log/fail_log.log' created") } // create/open database and load contents in memory if err := model.MainTx(ctrl.DbMap); err != nil { util.FailLog(err) os.Exit(1) } // create server and handler functions fmt.Println("initializing server...") srv := &http.Server{ ReadTimeout: 5 * time.Second, WriteTimeout: 5 * time.Second, Addr: "localhost:8000", Handler: nil, } fmt.Printf("server address: %v\nread timeout: %v\nwrite timeout: %v\n", srv.Addr, srv.ReadTimeout, srv.WriteTimeout) fmt.Printf("listening at: '%v'...\n", srv.Addr) http.HandleFunc("/home", ctrl.Home) http.HandleFunc("/list", ctrl.ReadOpList) http.HandleFunc("/price", ctrl.ReadOpPrice) http.HandleFunc("/update", ctrl.CreUpOp) http.HandleFunc("/delete", ctrl.DelOp) log.Fatal(srv.ListenAndServe()) }
C++
UTF-8
693
2.65625
3
[]
no_license
#include <cstdio> #include <vector> using namespace std; int vis[101], n, m, u, v; vector<int> res; vector<int> g[101]; void solve(int i){ vis[i] = 1; for(int j : g[i]){ if(vis[j] == 0) solve(j); } res.push_back(i); } int main(){ while(scanf("%d %d", &n, &m),n+m){ res.clear(); memset(vis, 0, sizeof vis); for(auto &v : g) v.clear(); while(m--){ scanf("%d %d", &u, &v); g[u].push_back(v); } for(int i = 0; i < n; i++) if(vis[i] == 0) solve(i); for(int i = (int)res.size() - 1; i >= 1; i--) printf("%d ", res[i]); printf("\n"); } }
Java
UTF-8
346
2.90625
3
[]
no_license
package day15; public class ExceptEx07 { public static void main(String[] args) { try { System.out.println("try 구문"); //throw new Exception ("hello"); throw new RuntimeException (); }catch (NullPointerException e) { System.out.println("Null"); }catch (Exception e) { System.out.println("모든 예외"); } } }
C++
UTF-8
915
2.90625
3
[]
no_license
#include <stdio.h> #include <conio.h> #include <stdlib.h> #include <iostream> int main() { char *str = (char*)malloc(1); int i = 1, c; while((c = getchar()) != EOF && c != '\n') { i++; str = (char*)realloc(str, i); str[i - 2] = c; str[i - 1] = '\0'; } int flag = 0; i = 0; while (str[i] != ' ') { i++; if (str[i] == '\0') { flag = 1; break; } } i--; for (int j = 0; j < i; j++, i--) { char tmp = str[i]; str[i] = str[j]; str[j] = tmp; } if (!flag) { i = 0; while (str[i] != '\0') i++; int j = i - 1; while (str[i] != ' ') i--; i++; for (; i < j; i++, j--) { char tmp = str[i]; str[i] = str[j]; str[j] = tmp; } } printf("%s\n", str); _getch(); return 0; }
C++
UTF-8
546
2.96875
3
[]
no_license
#include <iostream> #include <string> #include <algorithm> #include <set> #include <sstream> using namespace std; set<string> dic; int main(){ string s,buf; while(cin>>s){ for(int i=0;i<s.length();i++){ if(s[i]>='A'&&s[i]<='Z') s[i]=tolower(s[i]); else if(s[i]>='a'&&s[i]<='z') continue; else s[i]=' '; } stringstream ss(s); while(ss>>buf) dic.insert(buf); } for(set<string>::iterator it=dic.begin();it!=dic.end();++it) cout<<*it<<endl; return 0; }
C#
UTF-8
9,114
3.109375
3
[]
no_license
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Linq; using System.Runtime.ExceptionServices; using System.Text; using System.Threading.Tasks; namespace Test.boolean_function { abstract public class BFType { public virtual object Generate() { return null; } public virtual object Generate(List<object> parameters) { return null; } public virtual string Print(object obj) { return obj.ToString(); } } //sets class Cardinality:BFType { public int Data; public override object Generate(List<object> parameters) { var rnd = new Random(DateTime.Now.Millisecond); return rnd.Next(15); } } class Set: BFType { public List<int> Data; public override object Generate(List<object> parameters) { int n; if (parameters.Count > 0) { n = Convert.ToInt32(parameters[0]); } else { n = 10; } var set = new CustomSet(n); return set.getSet(); } public override string Print(object obj) { Data = obj as List<int>; return "{" + String.Join("; ", Data) + "}"; } } class ListOfSets: BFType { public List<CustomSet> Data; public override object Generate(List<object> parameters) { int n; if (parameters.Count > 0) { n = Convert.ToInt32(parameters[0]); } else { n = 2; } var sets = new List<CustomSet>(); for (int i = 0; i< n; i++) { sets.Add(new CustomSet()); } return sets; } public override string Print(object obj) { Data = obj as List<CustomSet>; var stringSets = new List<string>(); foreach(CustomSet set in Data) { stringSets.Add(set.getString()); } return String.Join(", ", stringSets); } } //bf class Formula : BFType { public string Data; public Formula() { } public Formula(string str) { Data = str; } public override string ToString() { return Data; } public override string Print(object obj) { return obj.ToString(); } } class IntArray : BFType { public int[] Data; public IntArray() { } public IntArray(int[] ar) { Data = ar; } public override object Generate(List<object> parameters) { int n; if (parameters.Count > 0) { n = Convert.ToInt32(parameters[0]); } else { n = 3; } var f = new BooleanFunction(n); return f.Vector; } public override string Print(object obj) { Data = obj as int[]; var s = "("; foreach (var a in Data) s += a; s += ")"; return s; } } class IntArray8 : BFType { public int[] Data; public IntArray8() { } public IntArray8(int[] ar) { Data = ar; } public override object Generate(List<object> parameters) { var f = new BooleanFunction(3); return f.Vector; } public override string Print(object obj) { Data = obj as int[]; var s = "("; foreach (var a in Data) s += a; s += ")"; return s; } } class IntArray3 : BFType { public int[] Data; public IntArray3() { Data = new int[3]; } public IntArray3(int[] ar) { Data = ar; } public override object Generate(List<object> parameters) { Data = new int[3]; var rnd = new Random(DateTime.Now.Millisecond); for (var i = 0; i < 3; i++) Data[i] = rnd.Next(0, 2); return Data; } public override string Print(object obj) { var ar = obj as int[]; var s = "("; foreach (var a in ar) s += a; s += ")"; return s; //Data = obj as int[]; //var f = ""; //var s = ""; //for (var i = 0; i < 3; i++) //{ // if (Data[i] == 0) // { // if (f != "") // f += ", "; // f += "x" + (i + 1); // } // else // { // if (s != "") // s += ", "; // s += "x" + (i + 1); // } //} //var str = ""; //if (s != "") //{ // str += "Существенные - " + s; // if (f != "") // str += "; "; //} //if (f != "") // str += "Фиктивные - " + f; //return str; } } class IntArray5 : BFType { public int[] Data; public IntArray5() { } public IntArray5(int[] ar) { Data = ar; } public override object Generate(List<object> parameters) { var res = new int[5]; var rnd = new Random(DateTime.Now.Millisecond); BooleanFunction f; if (rnd.Next(50) < 40) { f = new BooleanFunction(FunctionClass.Linear, 3); } else { f = new BooleanFunction(rnd.Next(256), 3); } res = f.FindProperties(); return res; } public override string Print(object obj) { var ar = obj as int[]; var s = "("; foreach (var a in ar) s += a; s += ")"; return s; } } class FunctionSystem : BFType { public List<BooleanFunction> Data; public FunctionSystem() { } private Boolean ContainsFunction(List<BooleanFunction> list, int func, int nargs) { foreach (var f in list) { if (f.Function == func && f.NumberOfArguments == nargs) return true; if (func == 0 && f.Function == 0) return true; if (func == Math.Pow(2, Math.Pow(2, nargs)) - 1 && f.Function == Math.Pow(2, f.NumberOfBytes) - 1) return true; } return false; } public override object Generate(List<object> parameters) { var fs = new List<BooleanFunction>(); var rnd = new Random(); var nfunc = rnd.Next(3, 6); var n = rnd.Next(2, 4); for (var i = 0; i < nfunc; i++) { var n1 = rnd.Next(1, n + 1); var f = rnd.Next(Convert.ToInt32(Math.Pow(2, Math.Pow(2, n1)))); while (ContainsFunction(fs, f, n1)) f = rnd.Next(Convert.ToInt32(Math.Pow(2, Math.Pow(2, n1)))); fs.Add(new BooleanFunction(f, n1)); } return fs; } public override string Print(object obj) { Data = obj as List<BooleanFunction>; var res = "{"; foreach (var f in Data) { if (res != "{") res += " , "; res += f.VectorString; } return res + "}"; } } class SetOfSystems : BFType { public List<List<BooleanFunction>> Data; public override object Generate(List<object> parameters) { return new List<List<BooleanFunction>>(); } public override string Print(object obj) { Data = obj as List<List<BooleanFunction>>; if (Data.Count == 0) return "Нет ни одной функционально полной системы"; var res = ""; foreach (var sys in Data) { if (res != "") res += " ; "; res += new FunctionSystem().Print(sys); } return res; } } }
PHP
UTF-8
863
2.59375
3
[ "MIT" ]
permissive
<?php namespace Gecche\Multidomain\Console; use Symfony\Component\Console\Input\InputDefinition; use Symfony\Component\Console\Input\InputOption; class Application extends \Illuminate\Console\Application { /** * Get the default input definitions for the applications. * * @return \Symfony\Component\Console\Input\InputDefinition */ protected function getDefaultInputDefinition(): InputDefinition { $definition = parent::getDefaultInputDefinition(); $definition->addOption($this->getDomainOption()); return $definition; } /** * Get the global environment option for the definition. * * @return \Symfony\Component\Console\Input\InputOption */ protected function getDomainOption() { $message = 'The domain the command should run under.'; return new InputOption('--domain', null, InputOption::VALUE_OPTIONAL, $message); } }
Java
UTF-8
1,353
4
4
[]
no_license
package day_56_exceptions; public class TryCatch { public static void main(String[] args) { System.out.println("Before Try Catch: "); //lets handle the following ArithmeticException try{ System.out.println("In try block"); int result = 10/0; //if 10/2 then it doesnt find any issue so jumps catch without printing it. System.out.println("After 10/0 line"); //if exception occurs then it directly jumps to catch. } catch (ArithmeticException e){ System.out.println("Exception happened, and was handled!"); } System.out.println("After Try Catch: "); System.out.println("-----------------2.nd example-----------------------"); try{ System.out.println("In second try block"); String str = "java is fun!"; System.out.println(str.charAt(0)); System.out.println(str.charAt(1)); System.out.println(str.charAt(20));//found exception StringOutOfBoundException occurred System.out.println(str.charAt(1)); //this line will not be run }catch (Exception e){ System.out.println("Exception happened in try block and caught"); System.out.println("Continue to compile"); } System.out.println("After second try catch "); } }
JavaScript
UTF-8
2,139
2.625
3
[ "MIT" ]
permissive
/** * ButtonOptionWidget is a special type of {@link OO.ui.mixin.ButtonElement button element} that * can be selected and configured with data. The class is * used with OO.ui.ButtonSelectWidget to create a selection of button options. Please see the * [OOUI documentation on MediaWiki] [1] for more information. * * [1]: https://www.mediawiki.org/wiki/OOUI/Widgets/Selects_and_Options#Button_selects_and_options * * @class * @extends OO.ui.OptionWidget * @mixins OO.ui.mixin.ButtonElement * @mixins OO.ui.mixin.IconElement * @mixins OO.ui.mixin.IndicatorElement * * @constructor * @param {Object} [config] Configuration options */ OO.ui.ButtonOptionWidget = function OoUiButtonOptionWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.ButtonOptionWidget.super.call( this, config ); // Mixin constructors OO.ui.mixin.ButtonElement.call( this, config ); OO.ui.mixin.IconElement.call( this, config ); OO.ui.mixin.IndicatorElement.call( this, config ); // Initialization this.$element.addClass( 'oo-ui-buttonOptionWidget' ); this.$button.append( this.$icon, this.$label, this.$indicator ); this.$element.append( this.$button ); this.setTitledElement( this.$button ); }; /* Setup */ OO.inheritClass( OO.ui.ButtonOptionWidget, OO.ui.OptionWidget ); OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.ButtonElement ); OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.IconElement ); OO.mixinClass( OO.ui.ButtonOptionWidget, OO.ui.mixin.IndicatorElement ); /* Static Properties */ /** * Allow button mouse down events to pass through so they can be handled by the parent select widget * * @static * @inheritdoc */ OO.ui.ButtonOptionWidget.static.cancelButtonMouseDownEvents = false; /** * @static * @inheritdoc */ OO.ui.ButtonOptionWidget.static.highlightable = false; /* Methods */ /** * @inheritdoc */ OO.ui.ButtonOptionWidget.prototype.setSelected = function ( state ) { OO.ui.ButtonOptionWidget.super.prototype.setSelected.call( this, state ); if ( this.constructor.static.selectable ) { this.setActive( state ); } return this; };
Java
UTF-8
925
2.078125
2
[]
no_license
package com.fileManager.service.user; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import com.fileManager.entity.user.User; import com.fileManager.service.common.BaseService; /** * 描述:用户 * 项目名称:fileManager * 创建日期:2015年9月22日上午11:25:00 * @author Administrator * @version */ public interface UserService extends BaseService<User, Integer>{ /** * 描述:按条件获取用户集合 * @author Administrator * @param user * @return */ public List<User> getUserListByParam(User user); /** * 描述: 插入用户 * @author Administrator * @param user * @return */ public int insertUser(User user); /** * 描述: 登录验证 * @author Administrator * @param user * @return */ public Map<String, Object> loginChk(User user, HttpServletRequest request); }
C++
UTF-8
2,815
2.875
3
[]
no_license
#include "tile.h" #include "Vector2.h" #include "Renderer.h" #include "InputSystem.h" Tile::Tile(int x, int y, TileCategory tileCategory) : id(0, 0) , tileType(UNDETERMINED) , locked(false) { id.x = x; id.y = y; this->tileCategory = tileCategory; } Tile::~Tile() { } bool Tile::Initialise(Renderer& renderer, TileType tileType, int rotation) { this->tileType = tileType; switch (tileType) { case CORNERCONCAVE: m_pSprite = renderer.CreateSprite("..\\Assets\\Tiles\\Corner Concave.png"); break; case CORNERCONVEX: m_pSprite = renderer.CreateSprite("..\\Assets\\Tiles\\Corner Convex.png"); break; case STRAIGHT: m_pSprite = renderer.CreateSprite("..\\Assets\\Tiles\\Straight.png"); break; case MIDDLE: m_pSprite = renderer.CreateSprite("..\\Assets\\Tiles\\Middle1.png"); break; case RAILCONCAVE: m_pSprite = renderer.CreateSprite("..\\Assets\\Tiles\\Rail Concave.png"); break; case RAILCONVEX: m_pSprite = renderer.CreateSprite("..\\Assets\\Tiles\\Rail Convex.png"); break; case RAILSTRAIGHT: m_pSprite = renderer.CreateSprite("..\\Assets\\Tiles\\Rail Straight.png"); break; case GOOSURFACE: m_pSprite = renderer.CreateSprite("..\\Assets\\Tiles\\Goo Surface.png"); break; case GOODEEP: m_pSprite = renderer.CreateSprite("..\\Assets\\Tiles\\Goo Deep.png"); break; case BACKGROUNDLIGHT: m_pSprite = renderer.CreateSprite("..\\Assets\\Tiles\\Background1.png"); break; case BACKGROUNDDARK: m_pSprite = renderer.CreateSprite("..\\Assets\\Tiles\\Background2.png"); break; case LADDERTOP: m_pSprite = renderer.CreateSprite("..\\Assets\\Tiles\\Ladder Top.png"); break; case LADDERMIDDLE: m_pSprite = renderer.CreateSprite("..\\Assets\\Tiles\\Ladder Middle.png"); break; case LADDERBOTTOM: m_pSprite = renderer.CreateSprite("..\\Assets\\Tiles\\Ladder Bottom.png"); break; } Rotate(rotation); return false; } void Tile::Process(float deltaTime) { Entity::Process(deltaTime); } void Tile::Draw(Renderer& renderer) { Entity::Draw(renderer); } void Tile::SetPosition(float x, float y) { m_position.x = x; m_position.y = y; } void Tile::SetScale(float scale) { m_pSprite->SetScale(scale); } Vector2 Tile::GetID() { return id; } void Tile::GetBounds(Vector2* &topLeft, Vector2* &bottomRight) { float radius = m_pSprite->GetScale() * 4; float x = m_pSprite->GetX() - radius; float y = m_pSprite->GetY() - radius; topLeft->x = x; topLeft->y = y; bottomRight->x = x + (2 * radius); bottomRight->y = y + (2 * radius); } float Tile::GetScale() { return m_pSprite->GetScale(); } TileType Tile::GetTileType() { return tileType; } TileCategory Tile::GetTileCategory() { return tileCategory; } bool Tile::GetLocked() { return locked; } void Tile::SetLocked() { locked = true; }
Python
UTF-8
1,447
3.25
3
[ "MIT" ]
permissive
#!/usr/bin/env python3 import pygame import pygame.gfxdraw from PIL import Image, ImageDraw # --- constants --- BLACK = ( 0, 0, 0) WHITE = (255, 255, 255) BLUE = ( 0, 0, 255) GREEN = ( 0, 255, 0) RED = (255, 0, 0) GREY = (128, 128, 128) PI = 3.1415 # --- main ---- pygame.init() screen = pygame.display.set_mode((800,600)) # - generate PIL image - pil_size = 300 pil_image = Image.new("RGBA", (pil_size, pil_size)) pil_draw = ImageDraw.Draw(pil_image) #pil_draw.arc((0, 0, pil_size-1, pil_size-1), 0, 270, fill=RED) pil_draw.pieslice((0, 0, pil_size-1, pil_size-1), 330, 0, fill=GREY) # - convert to PyGame image - mode = pil_image.mode size = pil_image.size data = pil_image.tobytes() image = pygame.image.fromstring(data, size, mode) image_rect = image.get_rect(center=screen.get_rect().center) # - mainloop - clock = pygame.time.Clock() running = True while running: clock.tick(10) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: running = False screen.fill(RED) #pygame.draw.arc(screen, BLACK, (300, 200, 200, 200), 0, PI/2, 1) #pygame.gfxdraw.pie(screen, 400, 300, 100, 0, 90, RED) #pygame.gfxdraw.arc(screen, 400, 300, 100, 90, 180, GREEN) screen.blit(image, image_rect) pygame.display.flip() # - end - pygame.quit()
C#
UTF-8
2,329
3.625
4
[]
no_license
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace _4 { class Program { public static void Quicksort(int[] elements, int left, int right, int k1, int k2) { if (left > k2 || right < k1) return; int i = left, j = right; int pivot = elements[(left + right) / 2]; while (i <= j) { while (elements[i].CompareTo(pivot) < 0) { i++; } while (elements[j].CompareTo(pivot) > 0) { j--; } if (i <= j) { int tmp = elements[i]; elements[i] = elements[j]; elements[j] = tmp; i++; j--; } } if (left < j) { Quicksort(elements, left, j, k1, k2); } if (i < right) { Quicksort(elements, i, right, k1, k2); } } static void Main(string[] args) { int n, k1, k2; int A, B, C; int[] a; using (StreamReader sr = new StreamReader("input.txt")) { string[] FirstLine = sr.ReadLine().Split(); n = int.Parse(FirstLine[0]); k1 = int.Parse(FirstLine[1]) - 1; k2 = int.Parse(FirstLine[2]) - 1; string[] SecondLine = sr.ReadLine().Split(); A = int.Parse(SecondLine[0]); B = int.Parse(SecondLine[1]); C = int.Parse(SecondLine[2]); a = new int[n]; a[0] = (int.Parse(SecondLine[3])); a[1] = (int.Parse(SecondLine[4])); } for (int i = 2; i < n; i++) { a[i] = (A * a[i - 2] + B * a[i - 1] + C); } using (StreamWriter sw = new StreamWriter("output.txt")) { Quicksort(a, 0, n - 1, k1, k2); for (int i = k1; i <= k2; i++) { sw.Write($"{a[i]} "); } } } } }
SQL
UTF-8
10,346
3.78125
4
[ "Apache-2.0" ]
permissive
-- --------------------------------------------------------------------- -- Declaraciones de la BDejemplo -- Sin PK's ni FK's para NORMALIZAR -- Es una BD de Clientes "activos" que invierten en empresas. -- Algunos clientes son morosos. Alg�n moroso no es cliente -- Clientes que trabajan en cierto puesto. Clientes que compran con -- Tarjetas --------------------------------------------------------------------- /* --- Caracter�sticas detalladas de BDejemplo: - Hay morosos, que pueden ser clientes o no, con la misma informaci�n que los clientes. No relacionar con el resto. - Un cliente trabaja como m�ximo en un puesto, estar en paro tambi�n se incluye, con T�tulo = 'parado'. - Un cliente puede no invertir o invertir en varias empresas. Puede tener varios Tipos de inversiones en la misma empresa. - El cliente invierte en una empresa, una cantidad y en un tipo. Solo puede invertir una vez en el mismo tipo para la misma empresa. Puede invertir en varios tipos en varias empresas. - El cliente hace compras con tarjetas - En compras, para un mismo cliente hay un num. factura secuencial sin duplicados para una tarjeta determinada. - Una tarjeta tiene un tipo, un n�mero diferente en todas las tarjetas y la organizaci�n propietaria del tipo. - El cliente puede tener varias tarjetas o ninguna. Como m�ximo tiene tres tarjetas. Puede haber m�s de un propietario de cada tarjeta. Cada propietario tiene para cada tarjeta una caducidad y un saldo. */ REM ... Empresa: E(NombreE, Cotizacion, Capital) -- Nombre de Empresa, Precio de Acci�n (cotizaci�n), Cantidad de Capital create table Empresa (NombreE CHAR(20) not null, Cotizacion INT default 99, Capital FLOAT, CHECK (Capital > 0), PRIMARY KEY (NombreE) ); --------------------------------------------------------------------- REM ... Cliente: CL(DNI, NombreC,Direccion,Telefono) -- DNI del cliente, Nombre del Cliente, su Tel�fono create table Cliente (DNI CHAR(8) not null, NombreC CHAR(30), Direccion VARCHAR2(50), Telefono CHAR(12), -- Total_invertido -- Para redundancia entre tablas -- -- Raz�n para dejar esta redundancia PRIMARY KEY (DNI) ); --------------------------------------------------------------------- REM ... Moroso: MO(DNI, NombreC,Direccion,Telefono) -- DNI del cliente moroso, Nombre del Cliente, su Tel�fono create table Moroso (DNI CHAR(8) not null, NombreC CHAR(30), Direccion VARCHAR2(50), Telefono CHAR(12), PRIMARY KEY (DNI) ); --------------------------------------------------------------------- REM ... Invierte: I(DNI, NombreE,Cantidad,Tipo) ------------- -- DNI del cliente, Nombre de Empresa en la que invierte, Cantidad y -- el Tipo de inversi�n create table Invierte (DNI CHAR(8) not null, NombreE CHAR(20) not null, Cantidad FLOAT, Tipo CHAR(10) not null, PRIMARY KEY (DNI, NombreE, Tipo), FOREIGN KEY (DNI) REFERENCES Cliente(DNI), FOREIGN KEY (NombreE) REFERENCES Empresa(NombreE) ); --------------------------------------------------------------------- REM ... Tarjeta: T(NumT, TipoT, Organizacion) -- N�mero de Tarjeta, Tipo de Tarjeta, Organizaci�n de esa Tarjeta create table Tarjeta (NumT INT CHECK (NumT <> 0), TipoT CHAR(10), Organizacion CHAR(20), CHECK (TipoT in ('VXK','COSA','PISA')), PRIMARY KEY (NumT) ); --------------------------------------------------------------------- REM ... Compras: CO(DNI, NumT, NumF, Fecha, Tienda, Importe) -- DNI del cliente comprador, Num de su tarjeta, Num de Factura, -- la fecha de compra en entero, Tienda donde se compr�, Importe de compra create table Compras (DNI CHAR(8) not null, NumT INT, NumF INT, Fecha INT, Tienda CHAR(20), Importe INT, PRIMARY KEY (DNI, NumT, NumF), FOREIGN KEY (DNI) REFERENCES Cliente(DNI), FOREIGN KEY (NumT) REFERENCES Tarjeta(NumT) ); --------------------------------------------------------------------- REM ... Puesto: P(DNI, Titulo, Sueldo) -- DNI del cliente, T�tulo del puesto de trabajo, sueldo en ese puesto create table Puesto (DNI CHAR(8) not null, Titulo VARCHAR2(30), Sueldo FLOAT, PRIMARY KEY (DNI, Titulo), FOREIGN KEY (DNI) REFERENCES Cliente(DNI) ); --------------------------------------------------------------------- REM ... TieneT: TTA(DNI,NumT, Caducidad, Saldo) -- Tarjetas que tiene el cliente: su DNI, N�m Tarjeta -- Caducidad de esa tarjeta, Saldo de esa tarjeta create table TieneT (DNI CHAR(8) not null, NumT INT not null, Caducidad INT, Saldo FLOAT, PRIMARY KEY (Dni, NumT), FOREIGN KEY (DNI) REFERENCES Cliente(DNI), FOREIGN KEY (NumT) REFERENCES Tarjeta(NumT) ); --------------------------------------------------------------------- REM --- > crear los datos completos e integros REM ... Cliente: CL(DNI, NombreC,Direccion,Telefono) INSERT INTO Cliente VALUES ('00000001','Client A','direc 11','911111111111'); INSERT INTO Cliente VALUES ('00000003','Client B','direc 13','911111111113'); INSERT INTO Cliente VALUES ('00000002','Client C','direc 12','911111111112'); INSERT INTO Cliente VALUES ('00000005','Client A','direc 11','911111111115'); INSERT INTO Cliente VALUES ('00000004','Client A','direc 14','911111111114'); INSERT INTO Cliente VALUES ('00000006','Client D','direc 16','911111111116'); --------------------------------------------------------------------- REM ... Moroso: MO(DNI, NombreC,Direccion,Telefono) INSERT INTO Moroso VALUES ('00000003','Client B','direc 13','911111111113'); INSERT INTO Moroso VALUES ('00000007','Client E','direc 17','911111111117'); INSERT INTO Moroso VALUES ('00000005','Client A','direc 11','911111111115'); INSERT INTO Moroso VALUES ('00000006','Client D','direc 16','911111111116'); --------------------------------------------------------------------- REM ... Empresa: E(NombreE, Cotizacion, Capital) INSERT INTO Empresa VALUES ('Empresa 11', 111111, 110000.00); INSERT INTO Empresa VALUES ('Empresa 22', 222222, 220000.00); INSERT INTO Empresa VALUES ('Empresa 33', 333333, 330000.00); INSERT INTO Empresa VALUES ('Empresa 44', 444444, 440000.00); INSERT INTO Empresa VALUES ('Empresa 55', 555555, 550000.00); --------------------------------------------------------------------- REM ... Invierte: I(DNI, NombreE,Cantidad,Tipo) INSERT INTO Invierte VALUES ('00000002', 'Empresa 55',210000, 'bono1'); INSERT INTO Invierte VALUES ('00000002', 'Empresa 55',220000, 'bono2'); INSERT INTO Invierte VALUES ('00000002', 'Empresa 55',230000, 'bono3'); INSERT INTO Invierte VALUES ('00000002', 'Empresa 44',240000, 'bono4'); INSERT INTO Invierte VALUES ('00000003', 'Empresa 55',310000, 'bono1'); INSERT INTO Invierte VALUES ('00000003', 'Empresa 33',320000, 'bono2'); INSERT INTO Invierte VALUES ('00000004', 'Empresa 22',410000, 'bono1'); INSERT INTO Invierte VALUES ('00000004', 'Empresa 22',420000, 'bono2'); --------------------------------------------------------------------- REM ... Tarjeta: T(NumT, TipoT, Organizacion) INSERT INTO Tarjeta VALUES ('10000001', 'PISA','MASTERUIN'); INSERT INTO Tarjeta VALUES ('30000002', 'PISA','MASTERUIN'); INSERT INTO Tarjeta VALUES ('50000003', 'PISA','MASTERUIN'); INSERT INTO Tarjeta VALUES ('00000010', 'COSA','MENOSRUIN'); INSERT INTO Tarjeta VALUES ('30000020', 'COSA','MENOSRUIN'); INSERT INTO Tarjeta VALUES ('50000030', 'COSA','MENOSRUIN'); INSERT INTO Tarjeta VALUES ('00000100', 'VXK','MENOSRUIN'); INSERT INTO Tarjeta VALUES ('40000200', 'VXK','MENOSRUIN'); INSERT INTO Tarjeta VALUES ('30000300', 'VXK','MENOSRUIN'); INSERT INTO Tarjeta VALUES ('50000400', 'VXK','MENOSRUIN'); --------------------------------------------------------------------- REM ... Compras: CO(DNI, NumT, NumF, Fecha, Tienda, Importe) INSERT INTO Compras VALUES ('00000005', '50000400',1, 0501,'tienda1',50); INSERT INTO Compras VALUES ('00000005', '50000030',1, 0501,'tienda1',5); INSERT INTO Compras VALUES ('00000005', '50000400',2, 0502,'tienda1',500); INSERT INTO Compras VALUES ('00000005', '50000400',3, 0501,'tienda2',5000); INSERT INTO Compras VALUES ('00000005', '50000003',1, 0501,'tienda8',50000); INSERT INTO Compras VALUES ('00000003', '30000002',1, 0501,'tienda7',3); INSERT INTO Compras VALUES ('00000003', '30000300',1, 0501,'tienda7',30); INSERT INTO Compras VALUES ('00000003', '30000020',1, 0501,'tienda7',300); INSERT INTO Compras VALUES ('00000003', '30000020',2, 0501,'tienda7',3000); INSERT INTO Compras VALUES ('00000003', '30000020',3, 0501,'tienda8',30000); INSERT INTO Compras VALUES ('00000004', '40000200',1, 0501,'tienda7',4); --------------------------------------------------------------------- REM ... Puesto: P(DNI, T�tulo, Sueldo) INSERT INTO Puesto VALUES ('00000001', 'cajera', 300); INSERT INTO Puesto VALUES ('00000002', 'estudiante', 301); INSERT INTO Puesto VALUES ('00000003', 'Presidente', 30000); INSERT INTO Puesto VALUES ('00000004', 'VicePresidente', 3000); INSERT INTO Puesto VALUES ('00000005', 'Presidente', 30000); INSERT INTO Puesto VALUES ('00000006', 'Parado', 0); --------------------------------------------------------------------- REM ... TieneT: TTA(DNI,NumT, Caducidad, Saldo) INSERT INTO TieneT VALUES ('00000001', '10000001', 0901, 30); INSERT INTO TieneT VALUES ('00000003', '30000002', 0901, 30); INSERT INTO TieneT VALUES ('00000003', '30000020', 0901, 300); INSERT INTO TieneT VALUES ('00000003', '30000300', 0901, 3000); INSERT INTO TieneT VALUES ('00000004', '40000200', 0901, 40); INSERT INTO TieneT VALUES ('00000005', '50000003', 0901, 50); INSERT INTO TieneT VALUES ('00000005', '50000030', 0901, 500); INSERT INTO TieneT VALUES ('00000005', '50000400', 0901, 50000); --------------------------------------------------------------------- ---------------------------------------------------------------------
Ruby
UTF-8
1,051
2.5625
3
[]
no_license
class Condition < ApplicationRecord validates_presence_of :date validates_presence_of :max_temperature_f validates_presence_of :mean_temperature_f validates_presence_of :min_temperature_f validates_presence_of :mean_humidity validates_presence_of :mean_visibility_miles validates_presence_of :mean_wind_speed_mph validates_presence_of :precipitation_inches validates_presence_of :zip_code def self.trip_numbers_by_temp_range joins('INNER JOIN trips ON conditions.date = trips.start_date') .group(:date, :max_temperature_f).count end def self.trip_numbers_by_precipitation joins('INNER JOIN trips ON conditions.date = trips.start_date') .group(:date, :precipitation_inches).count end def self.trip_numbers_by_wind_speed joins('INNER JOIN trips ON trips.start_date = conditions.date') .group(:date, :mean_wind_speed_mph).count end def self.trip_numbers_by_visibility joins('INNER JOIN trips ON trips.start_date = conditions.date') .group(:date, :mean_visibility_miles).count end end
C
UTF-8
1,680
2.953125
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_pathjoin.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbaffier <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/08/21 22:09:48 by dbaffier #+# #+# */ /* Updated: 2018/09/05 11:54:56 by dbaffier ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" char *ft_strjoin_test(char const *s1, char const *s2, int a) { char *new_str; size_t i; size_t j; size_t s1_len; size_t s2_len; if (!s1 || !s2) return (NULL); s1_len = ft_strlen(s1); s2_len = ft_strlen(s2); new_str = ft_strnew(s1_len + s2_len); if (!new_str) return (NULL); i = -1; j = -1; while (++i < s1_len) *(new_str + i) = *(s1 + i); while (++j < s2_len) *(new_str + i++) = *(s2 + j); if (a == 1 || a == 3) free((void *)s1); else if (a == 2 || a == 3) free((void *)s2); return (new_str); } char *ft_pathjoin(const char *p1, const char *p2) { char *str; char *tmp; if (!ft_strendswith(p1, "/")) { tmp = ft_strjoinch(p1, '/'); str = ft_strjoin(tmp, p2); free(tmp); return (str); } str = ft_strjoin(p1, p2); return (str); }
Python
UTF-8
218
3.171875
3
[]
no_license
def f(x): res=0 for a in str(x): res+=int(a) return res N=int(input()) L=[] for i in range(max(0,N-200),N+1): if i+f(i)==N: L.append(i) print(len(L)) for i in L: print(i)
JavaScript
UTF-8
11,176
2.859375
3
[]
no_license
/* global $ */ function EventManager() { /* * _listenerHash looks like this: * { * "eventType1": { (etListenerHash) * "_global_": [ func1, func2, func3 ], (idListenerArray) * "id1": [ func4 ], * "id2": [ func5, func6] * }, * "eventType2": { * ... * } * ... * } */ var _listenerHash; _init(); function _init() { // Initialize _listenerHash = {}; } // ******************************************* // // *** EVENT HANDLING ************************ // // ******************************************* // function _addEventListener(eventType, targetId, listenerFunc) { if (targetId == null) targetId = "_global_"; _removeEventListener(eventType, targetId, listenerFunc, true); var etListenerHash = _listenerHash[eventType]; if (!etListenerHash) { etListenerHash = _listenerHash[eventType] = {}; } var idListenerArray = etListenerHash[targetId]; if (!idListenerArray) { idListenerArray = etListenerHash[targetId] = [] } idListenerArray.push(listenerFunc); } function _addIdEventListeners(targetId, eventTypeListenerFuncHash) { $.each(eventTypeListenerFuncHash, function(eventType, listenerFunc) { _addEventListener(eventType, targetId, listenerFunc); }); } function _removeEventListener(eventType, targetId, listenerFunc, bFromAdd) { if (bFromAdd == null) bFromAdd = false; var etListenerHash = _listenerHash[eventType]; if (!etListenerHash) { return; } if (targetId == null) targetId = "_global_"; var idListenerArray = etListenerHash[targetId]; if (!idListenerArray) { return; } var len = idListenerArray.length; for (var i = len - 1; i >= 0; i--) { // If listenerFunc is null then remove all functions, otherwise find the specific function if (listenerFunc == null || idListenerArray[i] == listenerFunc) { if (bFromAdd) console.log("removeEventListener(): duplicate add found"); // Slice it out idListenerArray.splice(i, 1); if (len == 1) { // This is the only listener for the event type and target id // => Remove listener entry for this event type and target id delete(etListenerHash[targetId]); if ($.isEmptyObject(_listenerHash[eventType])) { // This event type has no more targets => Remove delete(_listenerHash[eventType]); } } if (listenerFunc != null) break; } } } function _removeAllEventListeners(eventType, targetId) { if (!targetId) { if (!eventType) { // no eventType, no targetId _listenerHash = {}; // reset } else { // eventType X, no targetId delete(_listenerHash[eventType]); // remove all for this event type } } else { if (!eventType) { // no eventType, targetId Y $.each(_listenerHash, function(et, etListenerHash) { delete(etListenerHash[et][targetId]); // remove all for this event id }); } else { // eventType X, targetId Y delete(_listenerHash[eventType][targetId]); } } } function _addSingleEventListener(eventType, targetId, listenerFunc) { // Add listener and remove it after the first event has dispatched var singleListenerFunc = function(eventObj) { _removeEventListener(eventType, targetId, singleListenerFunc); eventObj._removed = true; return listenerFunc(eventObj); }; _addEventListener(eventType, targetId, singleListenerFunc); } function _dispatchEvent(eventObj, target) { var retObj = null; if (eventObj && eventObj.type) { // Get listener hash for the event type var eventType = eventObj.type; var etListenerHash = _listenerHash[eventType]; if (!etListenerHash) { return retObj; } // Set event target, i.e. source item that triggered the event eventObj.target = target||eventObj.target||this; // Set targetIds, i.e. items that should receive the event var targetIdArray = []; if (eventObj.targetIds) targetIdArray = eventObj.targetIds.slice(0); targetIdArray.push("_global_"); // Trigger listeners for (var targetIdx = 0; targetIdx < targetIdArray.length; targetIdx++) { var targetId = targetIdArray[targetIdx]; var idListenerArray = etListenerHash[targetId]; if (idListenerArray != null) { var removeListenerArray = []; for (var listenerIdx = 0; listenerIdx < idListenerArray.length; listenerIdx++) { var listener = idListenerArray[listenerIdx]; if (listener == null) debugger; var obj = listener(eventObj); if (eventObj.hasOwnProperty("_removed") && eventObj._removed == true) { listenerIdx--; delete eventObj["_removed"]; } if (obj != null) { var objTypeStr = $.type(obj); if (objTypeStr === "array" || objTypeStr === "string" || objTypeStr === "number" || objTypeStr === "boolean" || objTypeStr === "date") { if (retObj == null) retObj = new Array(); retObj = retObj.concat(obj); } else { // extendable object if (retObj == null) retObj = {}; $.extend(retObj, obj); } } } for (var i = 0; i < removeListenerArray.length; i++) { _removeEventListener(eventType, targetId, listener); } } } } return retObj; } // ******************************************* // // *** PUBLIC METHODS ************************ // // ******************************************* // function _getListenerHash() { return _listenerHash; } // DEBUG return { // Public methods go here addEventListener: _addEventListener, removeEventListener: _removeEventListener, removeAllEventListeners: _removeAllEventListeners, addIdEventListeners: _addIdEventListeners, addSingleEventListener: _addSingleEventListener, dispatchEvent: _dispatchEvent, _getListenerHash: _getListenerHash // DEBUG } } function EventManagerPrototype() { /* * _listenerHash looks like this: * { * "eventType1": { (etListenerHash) * "_global_": [ func1, func2, func3 ], (idListenerArray) * "id1": [ func4 ], * "id2": [ func5, func6] * }, * "eventType2": { * ... * } * ... * } */ this.listenerHash = {}; } /* EventManagerPrototype.prototype.addEventListener = function(eventType, targetId, listenerFunc) { if (targetId == null) targetId = "_global_"; this.removeEventListener(eventType, targetId, listenerFunc, true); var etListenerHash = this.listenerHash[eventType]; if (!etListenerHash) { etListenerHash = this.listenerHash[eventType] = {}; } var idListenerArray = etListenerHash[targetId]; if (!idListenerArray) { idListenerArray = etListenerHash[targetId] = [] } idListenerArray.push(listenerFunc); }; EventManagerPrototype.prototype.addIdEventListeners = function(targetId, eventTypeListenerFuncHash) { var pThis = this; $.each(eventTypeListenerFuncHash, function(eventType, listenerFunc) { pThis.addEventListener(eventType, targetId, listenerFunc); }); }; EventManagerPrototype.prototype.removeEventListener = function(eventType, targetId, listenerFunc, bFromAdd) { if (bFromAdd == null) bFromAdd = false; var etListenerHash = this.listenerHash[eventType]; if (!etListenerHash) return; if (targetId == null) targetId = "_global_"; var idListenerArray = etListenerHash[targetId]; if (!idListenerArray) return; var len = idListenerArray.length; for (var i = len - 1; i >= 0; i--) { // If listenerFunc is null then remove all functions, otherwise find the specific function if (listenerFunc == null || idListenerArray[i] == listenerFunc) { if (bFromAdd) console.log("removeEventListener(): duplicate add found"); // Slice it out idListenerArray.splice(i, 1); if (len == 1) { // This is the only listener for the event type and target id => Remove listener entry delete(etListenerHash[targetId]); if ($.isEmptyObject(this.listenerHash[eventType])) { // This event type has no more targets => Remove delete(this.listenerHash[eventType]); } } if (listenerFunc != null) break; } } }; EventManagerPrototype.prototype.removeAllEventListeners = function(eventType, targetId) { if (!targetId) { if (!eventType) { // no eventType, no targetId this.listenerHash = {}; // reset } else { // eventType X, no targetId delete(this.listenerHash[eventType]); // remove all for this event type } } else { if (!eventType) { // no eventType, targetId Y $.each(this.listenerHash, function(et, etListenerHash) { delete(etListenerHash[et][targetId]); // remove all for this event id }); } else { // eventType X, targetId Y delete(this.listenerHash[eventType][targetId]); } } }; EventManagerPrototype.prototype.addSingleEventListener = function(eventType, targetId, listenerFunc) { // Add listener and remove it after the first event has dispatched var singleListenerFunc = function(eventObj) { this.removeEventListener(eventType, targetId, singleListenerFunc); eventObj._removed = true; return listenerFunc(eventObj); }; this.addEventListener(eventType, targetId, singleListenerFunc); }; EventManagerPrototype.prototype.dispatchEvent = function(eventObj, target) { var retObj = null; if (eventObj && eventObj.type) { // Get listener hash for the event type var eventType = eventObj.type; var etListenerHash = this.listenerHash[eventType]; if (!etListenerHash) { return retObj; } // Set event target, i.e. source item that triggered the event eventObj.target = target||eventObj.target||this; // Set targetIds, i.e. items that should receive the event var targetIdArray = []; if (eventObj.targetIds) targetIdArray = eventObj.targetIds.slice(0); targetIdArray.push("_global_"); // Trigger listeners for (var targetIdx = 0; targetIdx < targetIdArray.length; targetIdx++) { var targetId = targetIdArray[targetIdx]; var idListenerArray = etListenerHash[targetId]; if (idListenerArray != null) { var removeListenerArray = []; for (var listenerIdx = 0; listenerIdx < idListenerArray.length; listenerIdx++) { var listener = idListenerArray[listenerIdx]; if (listener == null) debugger; var obj = listener(eventObj); if (eventObj.hasOwnProperty("_removed") && eventObj._removed == true) { listenerIdx--; delete eventObj["_removed"]; } if (obj != null) { var objTypeStr = $.type(obj); if (objTypeStr === "array" || objTypeStr === "string" || objTypeStr === "number" || objTypeStr === "boolean" || objTypeStr === "date") { if (retObj == null) retObj = new Array(); retObj = retObj.concat(obj); } else { // extendable object if (retObj == null) retObj = {}; $.extend(retObj, obj); } } } for (var i = 0; i < removeListenerArray.length; i++) { this.removeEventListener(eventType, targetId, listener); } } } } return retObj; }; EventManagerPrototype.prototype.getListenerHash = function() { return this.listenerHash; }; */
Java
UTF-8
1,711
2.359375
2
[]
no_license
package de.enterprise.lokaServer.events.execution; import java.util.ArrayList; import net.sf.json.JSONObject; import de.enterprise.lokaServer.events.CommandEvent; import de.enterprise.lokaServer.events.ServerEvent; import de.enterprise.lokaServer.pojos.DoubleLocPojo; import de.enterprise.lokaServer.pojos.LocationPojo; import de.enterprise.lokaServer.pojos.PostMapPojo; import de.enterprise.lokaServer.tools.GeoTools; import de.enterprise.lokaServer.tools.JSONConverter; public class RequestPostsMapEvent extends ServerEvent{ public static final int REQUEST_POSTS_RADIUS = 8000; public RequestPostsMapEvent(){ CMD = "RPM"; } @Override protected void execute(CommandEvent evt) throws Exception { String json = evt.getCmd()[1]; JSONObject obj = JSONObject.fromObject(json); String dbl = null; if(obj.has("L")){ dbl = obj.getString("L"); } String pos = null; if(obj.has("P")){ pos = obj.getString("P"); } int groupID = obj.getInt("gID"); String searchWord = ""; if(obj.containsKey("Que")){ searchWord = obj.getString("Que"); } DoubleLocPojo dblLoc = null; LocationPojo loc = null; if(dbl != null){ dblLoc = (DoubleLocPojo)JSONConverter.fromJSON(dbl, DoubleLocPojo.class.getName()); }else if(pos != null){ loc = (LocationPojo)JSONConverter.fromJSON(pos, LocationPojo.class.getName()); } if(loc != null){ LocationPojo[] locs = GeoTools.getRectOfCoord(loc, REQUEST_POSTS_RADIUS); dblLoc = new DoubleLocPojo(locs[0], locs[1]); } ArrayList<PostMapPojo> postsInView = this.lokaServer.getDBQuery().getPosts(dblLoc, groupID, searchWord); sendResponse(evt.getResponse(), JSONConverter.toJsonArray(postsInView.toArray())); } }
Python
UTF-8
41,482
3.015625
3
[]
no_license
# -*- coding: utf-8 -*- ''' CalStressTensor.py Script to calculate the assembly averaged stress tensor based on contact force and branch vector. Usage: python CalStressDrop.py -test 1 -filter median -param 21 python CalStressDrop.py -case shear-rate-10-press-1e5 -test 1 References: [1] Dorostkar, O., Guyer, R. A., Johnson, P. A., Marone, C. & Carmeliet, J. On the role of fluids in stick-slip dynamics of saturated granular fault gouge using a coupled computational fluid dynamics-discrete element approach. J. Geophys. Res. Solid Earth 122, 3689¨C3700 (2017). [2] Cao, P. et al. Nanomechanics of slip avalanches in amorphous plasticity. J. Mech. Phys. Solids 114, 158¨C171 (2018). [3] Bi, D. & Chakraborty, B. Rheology of granular materials: Dynamics in a stress landscape. Philos. Trans. R. Soc. A Math. Phys. Eng. Sci. 367, 5073¨C5090 (2009). [4] Gao, K., Guyer, R., Rougier, E., Ren, C. X. & Johnson, P. A. From Stress Chains to Acoustic Emission. Phys. Rev. Lett. 123, 48003 (2019). ''' # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ from sys import argv, exit import os import numpy as np import seaborn as sns import pandas as pd import matplotlib.pyplot as plt from scipy import optimize from scipy import stats from scipy.signal import savgol_filter from scipy.ndimage import gaussian_filter1d from scipy.ndimage import median_filter from scipy.signal import medfilt from mpl_toolkits.axes_grid1.inset_locator import inset_axes # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # def rightTrim(input, suffix): if (input.find(suffix) == -1): input = input + suffix return input def mkdir(path): # 引入模块 import os # 去除首位空格 path = path.strip() # 去除尾部 \ 符号 path = path.rstrip("/") # 判断路径是否存在 # 存在 True # 不存在 False isExists = os.path.exists(path) # 判断结果 if not isExists: # 如果不存在则创建目录 print(path + ' 创建成功') # 创建目录操作函数 os.makedirs(path) return True else: # 如果目录存在则不创建,并提示目录已存在 print(path + ' 目录已存在') return False # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Distance of two vertexes # def vertex_distance(a, b): return np.sqrt((a[0] - b[0])**2.0 + (a[1] - b[1])**2.0 + (a[2] - b[2])**2.0) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # array normalization # def array_normalization(array): return (array - np.min(array))/(np.mean(array) - np.min(array)) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # split the arr into N chunks # def chunks(arr, m): n = int(np.ceil(len(arr)/float(m))) return [arr[i:i + n] for i in range(0, len(arr), n)] # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # q-Exponential function # def func(x, q, lamda): return (2-q)*lamda*(1-lamda*(1-q)*x)**(1/(1-q)) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # non-gaussian parameter # def non_gaussian(array, dimension): if dimension == 1: Cn3 = 1.0/3.0 elif dimension == 2: Cn3 = 1.0/2.0 elif dimension == 3: Cn3 = 3.0/5.0 return Cn3*np.mean(array**4.0)/np.power(np.mean(array**2.0),2.0) - 1.0 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # standard error # def standard_error(sample): std=np.std(sample, ddof=0) standard_error=std/np.sqrt(len(sample)) return standard_error # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Author : 余欢 # Date : Dec 28, 2015 4:09:29 PM # company : 南京师范大学--大数据实验室 # description : 清理异常值 # https://blog.csdn.net/redaihanyu/article/details/50421773 # def is_outlier(points, threshold=2): """ 返回一个布尔型的数组,如果数据点是异常值返回True,反之,返回False。 数据点的值不在阈值范围内将被定义为异常值 阈值默认为3.5 """ # 转化为向量 if len(points.shape) == 1: points = points[:,None] # 数组的中位数 median = np.median(points, axis=0) # 计算方差 diff = np.sum((points - median)**2, axis=-1) #标准差 diff = np.sqrt(diff) # 中位数绝对偏差 med_abs_deviation = np.median(diff) # compute modified Z-score # http://www.itl.nist.gov/div898/handbook/eda/section4/eda43.htm#Iglewicz modified_z_score = 0.6745*diff/med_abs_deviation # return a mask for each outlier return modified_z_score > threshold # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # If your data is well-behaved, you can fit a power-law function by first converting to a linear equation by using the logarithm. # Then use the optimize function to fit a straight line. Notice that we are weighting by positional uncertainties during the fit. # Also, the best-fit parameters uncertainties are estimated from the variance-covariance matrix. # You should read up on when it may not be appropriate to use this form of error estimation. # Refereces: https://scipy-cookbook.readthedocs.io/items/FittingData.html#Fitting-a-power-law-to-data-with-errors # def powerlaw(x, amp, index): # Define function for calculating a power law powerlaw = lambda x, amp, index: amp*(x**index) def fit_powerlaw(xdata, ydata, yerr, weight=False): ########## # Fitting the data -- Least Squares Method ########## # Power-law fitting is best done by first converting # to a linear equation and then fitting to a straight line. # Note that the `logyerr` term here is ignoring a constant prefactor. # # y = a*x^b # log(y) = log(a) + b*log(x) # # Define function for calculating a power law powerlaw = lambda x, amp, index: amp*(x**index) logx = np.log10(xdata) logy = np.log10(ydata) if weight: logyerr = yerr/ydata else: logyerr = np.ones(len(logx)) # logyerr[np.where(logyerr == 0)] = 1 # define our (line) fitting function fitfunc = lambda p, x: p[0] + p[1]*x errfunc = lambda p, x, y, err: (y - fitfunc(p, x))/err pinit = [10.0, -10.0] out = optimize.leastsq(errfunc, pinit, args=(logx, logy, logyerr), full_output=1) pfinal = out[0] covar = out[1] # print(pfinal) # print(covar) index = pfinal[1] amp = 10.0**pfinal[0] indexErr = np.sqrt(covar[1][1]) ampErr = np.sqrt(covar[0][0])*amp ########## # Plotting data ########## # plt.clf() # plt.subplot(2, 1, 1) # plt.plot(xdata, powerlaw(xdata, amp, index)) # Fit # plt.errorbar(xdata, ydata, yerr=yerr, fmt='k.') # Data # plt.text(5, 6.5, 'Ampli = %5.2f +/- %5.2f' % (amp, ampErr)) # plt.text(5, 5.5, 'Index = %5.2f +/- %5.2f' % (index, indexErr)) # plt.title('Best Fit Power Law') # plt.xlabel('X') # plt.ylabel('Y') # plt.xlim(1, 11) # # plt.subplot(2, 1, 2) # plt.loglog(xdata, powerlaw(xdata, amp, index)) # plt.errorbar(xdata, ydata, yerr=yerr, fmt='k.') # Data # plt.xlabel('X (log scale)') # plt.ylabel('Y (log scale)') # plt.xlim(1.0, 11) # plt.show() return pfinal # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Power law distribution with exponential cutoff # Truncated power law # def truncated_powerlaw(x, amp, alpha, beta): return amp*x**(-alpha)*np.exp(-x/beta) def log_truncated_powerlaw(x, amp, alpha, beta): # power law decay return np.log10(amp) - alpha*np.log10(x) - (x/beta)*np.log10(np.e) def fit_truncated_powerlaw(xdata, ydata, yerror): popt, pcov = optimize.curve_fit(log_truncated_powerlaw, xdata, np.log10(ydata), bounds=([0, 0, 0], [100, 100, 100])) amp, alpha, beta = popt return popt # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # def plot_fittingline(ax, sample, power_law, xdata, xerr, ydata, yerr, xlabel, ylabel): # Define function for calculating a power law powerlaw = lambda x, amp, index: amp*(x**index) truncated_powerlaw = lambda x, amp, alpha, beta: amp*x**(-alpha)*np.exp(-x/beta) # plt.figure(figsize=(6,6)) if ylabel == 'stress drop': ax.errorbar(xdata, ydata, xerr=xerr, yerr=yerr, fmt='o', ecolor='b', color='b', elinewidth=2, capsize=4) else: ax.scatter(xdata, ydata, marker='o', color='b') # ax.errorbar(xdata, ydata, xerr=xerr, yerr=yerr, fmt='o', ecolor='b', color='b', elinewidth=2, capsize=4) if len(power_law) == 2: amp = 10**power_law[0] index = power_law[1] ax.plot(xdata, powerlaw(xdata, amp, index), color="r", linewidth=2) #画拟合直线 ax.text(5e-5, 5e-3, "τ= %4.3f" %index, fontsize=12) else: amp = power_law[0] alpha = power_law[1] beta = power_law[2] ax.plot(xdata, truncated_powerlaw(xdata, amp, alpha, beta), color="r", linewidth=2) #画拟合直线 ax.text(1e-4, 1e-1, "τ= %4.3f, s$\mathregular{_*}$= %4.3f" % (alpha, beta), fontsize=12) ax.set_xscale('log') ax.set_yscale('log') ax.set_xlabel(xlabel, fontsize=12) ax.set_ylabel(ylabel, fontsize=12) ax.tick_params(axis='both', labelsize=12) # ax.legend(fontsize=12) # plt.savefig(file_path, dpi=500, bbox_inches = 'tight') # plt.show() # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Bootstrap resampling with Python # https://nbviewer.jupyter.org/gist/aflaxman/6871948 # def bootstrap_resample(X, n=None): """ Bootstrap resample an array_like Parameters ---------- X : array_like data to resample n : int, optional length of resampled array, equal to len(X) if n==None Results ------- returns X_resamples """ if isinstance(X, pd.Series): X = X.copy() X.index = range(len(X.index)) if n == None: n = len(X) resample_i = np.floor(np.random.rand(n)*len(X)).astype(int) X_resample = np.array(X[resample_i]) # TODO: write a test demonstrating why array() is important return X_resample def histgram_logform(data, minimum, step=0.05): # lb, ub = np.floor(np.log10(np.min(Par_potential))), np.ceil(np.log10(np.max(Par_potential))) lb, ub = np.floor(np.log10(minimum)), np.ceil(np.log10(np.max(data))) bins_try = np.arange(lb, ub, step) bins_try = 10**bins_try hist, bin_edges = np.histogram(data, bins=bins_try, density=False) # delete the bin without data points bins = np.delete(bins_try, np.where(hist == 0)[0]) hist, bin_edges = np.histogram(data, bins=bins, density=False) digitized = np.digitize(data, bins) data_binning = np.array([[data[digitized == i].mean(), data[digitized == i].std()] for i in range(1, len(bins))]) bin_value, bin_range = data_binning[:, 0], data_binning[:, 1] # bin_value = np.array([0.5*(bin_edges[i] + bin_edges[i+1]) for i in range(len(bin_edges)-1)]) frequency = hist/(np.sum(hist)*np.diff(bin_edges)) frequency = frequency/np.sum(frequency) return bin_value, bin_range, frequency, digitized def CalStressDrops(case, test_id, shear_rate, delta_strain, steady_strain, strain_interval, filter_method, filter_param, threshold, k_sampling, M0): # data file path and results file path data_path = os.path.pardir + '/' + case + '/test-' + str(test_id) output_path = os.path.pardir + '/' + case + '/test-' + str(test_id) + '/stress drop' mkdir(output_path) truncated_powerlaw = lambda x, amp, alpha, beta: amp*x**(-alpha)*np.exp(-x/beta) powerlaw = lambda x, amp, index: amp*(x**index) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # 1. Visualization setting # # sns.set_style('ticks') plt.style.use('seaborn-paper') my_palette = "bright" # deep, muted, pastel, bright, dark, colorblind, Set3, husl, Paired sns.set_palette(my_palette) #不同类别用不同颜色和样式绘图 # colors = ['c', 'b', 'g', 'r', 'm', 'y', 'k', 'w'] # colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'b'] # colors = ['C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9'] colors = sns.color_palette(my_palette, 10) markers = ['o', '^', 'v', 's', 'D', 'v', 'p', '*', '+'] # markers = ['*', 'o', '^', 'v', 's', 'p', 'D', 'X'] # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # 2. Load data set # domain_depth = 0.02 domain_length = 0.04 time_resolution = strain_interval/shear_rate force_info = open(data_path + '/output.dat', 'r') alllines = force_info.readlines() lines = alllines[801:] force_info.close() for i in range(len(lines)): if (lines[i] == '\n'): del lines[i] time = np.array([float(line.strip().split(' ')[0]) for line in lines]) # 字段以空格分隔,这里取得是第1列 system_height = np.array([float(line.strip().split(' ')[1]) for line in lines]) # 字段以空格分隔,这里取得是第2列 system_volume = np.array([float(line.strip().split(' ')[2]) for line in lines]) # 字段以空格分隔,这里取得是第3列 solid_fraction = np.array([float(line.strip().split(' ')[3]) for line in lines]) # 字段以空格分隔,这里取得是第4列 normal_force = np.array([float(line.strip().split(' ')[4]) for line in lines]) # 字段以空格分隔,这里取得是第5列 shear_force_top= np.array([float(line.strip().split(' ')[5]) for line in lines]) # 字段以空格分隔,这里取得是第6列 shear_force_bot= np.array([float(line.strip().split(' ')[6]) for line in lines]) # 字段以空格分隔,这里取得是第7列 coord_num = np.array([float(line.strip().split(' ')[7]) for line in lines]) # 字段以空格分隔,这里取得是第8列 time0 = time[0] height0 = system_height[0] shear_time = time - time0 shear_strain = (time - time0)*shear_rate volumetric_strain = (height0 - system_height)/height0 normal_pressure = normal_force/(domain_depth*domain_length)*1e-6 shear_stress = shear_force_bot/(domain_depth*domain_length)*1e-6 shear_stress /= np.mean(normal_pressure) # force_info = open(data_path + '/Particle assembly stress.dat', 'r') # alllines = force_info.readlines() # lines = alllines # force_info.close() # for i in range(len(lines)): # if (lines[i] == '\n'): del lines[i] # time1 = np.array([float(line.strip().split(',')[1]) for line in lines]) # 字段以空格分隔,这里取得是第2列 # sxx = np.array([float(line.strip().split(',')[2]) for line in lines]) # 字段以空格分隔,这里取得是第3列 # syy = np.array([float(line.strip().split(',')[3]) for line in lines]) # 字段以空格分隔,这里取得是第4列 # szz = np.array([float(line.strip().split(',')[4]) for line in lines]) # 字段以空格分隔,这里取得是第5列 # sxy = np.array([float(line.strip().split(',')[5]) for line in lines]) # 字段以空格分隔,这里取得是第6列 # sxz = np.array([float(line.strip().split(',')[6]) for line in lines]) # 字段以空格分隔,这里取得是第7列 # syz = np.array([float(line.strip().split(',')[7]) for line in lines]) # 字段以空格分隔,这里取得是第8列 # sxy = abs(sxy)*1e-6 # plt.figure(figsize=(8,6)) # plt.plot(time1, sxy, linewidth=2, label='sxy') # plt.xlabel('time', fontsize=15) # plt.ylabel('sxy', fontsize=15) # plt.xticks(fontsize=15) # plt.yticks(fontsize=15) # plt.legend(fontsize=15) # plt.grid(axis='both', color='grey', linestyle='--', lw=0.5, alpha=0.5) # plt.show() # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # 2.1 Sampling from the original data set # data_interval = int(round(strain_interval/delta_strain)) volumetric_strain = volumetric_strain[::data_interval] shear_stress = shear_stress[::data_interval] shear_strain = shear_strain[::data_interval] # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # 2.2 Data smooth # To remove fluctuations from the original time series of the shear stress obtained from the simulations, # we smoothed the time series using different filters, such as Savitzky–Golay filter, gaussian filter, and median filter. # References: # [1] Niiyama, T., Wakeda, M., Shimokawa, T., Ogata, S., 2019. Structural relaxation affecting shear-transformation avalanches in metallic glasses. Phys. Rev. E 100, 1–10. # [2] Cao, P., Short, M.P., Yip, S., 2019. Potential energy landscape activations governing plastic flows in glass rheology. Proc. Natl. Acad. Sci. U. S. A. 116, 18790–18797. if 'gaussian' in filter_method: # https: // docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.gaussian_filter1d.html shear_stress_fld = gaussian_filter1d(shear_stress, sigma=filter_param) # standard deviation of shear stress elif 'median' in filter_method: # https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.median_filter.html # https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.medfilt.html shear_stress_fld = medfilt(shear_stress, kernel_size=int(filter_param)) # shear_stress_fld = median_filter(shear_stress, size=filter_param, mode='nearest') elif 'savgol' in filter_method: # Apply a Savitzky-Golay filter to an array # https://codeday.me/bug/20170710/39369.html # http://scipy.github.io/devdocs/generated/scipy.signal.savgol_filter.html # https://en.wikipedia.org/wiki/Savitzky%E2%80%93Golay_filter # A Savitzky–Golay filter is a digital filter that can be applied to a set of digital data points for the purpose of smoothing the data. shear_stress_fld = savgol_filter(shear_stress, window_length=int(filter_param), polyorder=3) elif 'ewma' in filter_method: # Exponentially-weighted moving average # https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.ewm.html?highlight=ewma # http://connor-johnson.com/2014/02/01/smoothing-with-exponentially-weighted-moving-averages/ df_shear_stress_fwd = pd.Series(shear_stress) df_shear_stress_bwd = pd.Series(shear_stress[::-1]) fwd = df_shear_stress_fwd.ewm(span=filter_param).mean() # take EWMA in fwd direction bwd = df_shear_stress_bwd.ewm(span=filter_param).mean() # take EWMA in bwd direction shear_stress_fld = np.vstack((fwd, bwd[::-1])) # lump fwd and bwd together shear_stress_fld = np.mean(shear_stress_fld, axis=0) # average else: print('original data') fig = plt.figure(figsize=(8, 4)) ax1 = fig.add_subplot(111) ax1.plot(shear_strain, shear_stress, color=colors[0], alpha=0.1, linewidth=1, label='Original stress data') ax1.plot(shear_strain, shear_stress_fld, color=colors[0], linewidth=1, label='Filtered stress data') ax1.set_xlabel('shear strain, $\gamma$', fontsize=12, labelpad=5) ax1.set_ylabel('shear stress, ' + r'$\tau$(MPa)', fontsize=12, labelpad=5) ax1.tick_params(axis='both', labelsize=12) ax1.set_xlim(0., 5) # ax1.set_ylim(0.24, 0.27) ax2 = ax1.twinx() ax2.plot(shear_strain, volumetric_strain, color=colors[1], linewidth=1, label='Volumetric strain') ax2.set_ylabel('volumetric strain, $\epsilon_v$', fontsize=12, labelpad=5) ax2.tick_params(axis="y", labelsize=12) fig.legend(loc='center', fontsize=12) plt.grid(axis='both', color='grey', linestyle='--', lw=0.5, alpha=0.5) plt.grid() plt.savefig(output_path + '/Macroscopic responses.png', dpi=600, bbox_inches='tight') plt.show() # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # 3. Identify the stress drop、strain duration # steady_range = shear_strain > steady_strain shear_time = shear_time[steady_range] shear_strain = shear_strain[steady_range] shear_stress = shear_stress_fld[steady_range] avalanches = [] # https://stackoverflow.com/questions/16841729/how-do-i-compute-the-derivative-of-an-array-in-python # dydx = np.diff(shear_stress)/np.diff(shear_strain) # https://docs.scipy.org/doc/numpy/reference/generated/numpy.gradient.html dydx = np.gradient(shear_stress, shear_strain) d2ydx2 = np.gradient(dydx, shear_strain) drop_pos = dydx < 0 drop_slice = [] slice = [] for i in range(len(shear_stress)): if drop_pos[i]: slice.append(i) else: if len(slice) > 1: # combine two drop slice if they are two close if len(drop_slice) == 0: drop_slice.append(slice) else: if (slice[0] - drop_slice[-1][-1]) <= 0: drop_slice[-1].extend(slice) else: drop_slice.append(slice) slice = [] for i, slice in enumerate(drop_slice): drop_start = np.min(slice) drop_end = np.max(slice) stress_drop = shear_stress[drop_start] - shear_stress[drop_end] strain_duration = shear_strain[drop_end] - shear_strain[drop_start] time_duration = strain_duration/shear_rate t0 = shear_time[drop_start] t1 = shear_time[drop_end] if i == 0: waiting_time, waiting_strain = 0, 0 else: previous_drop_end = np.max(drop_slice[i-1]) waiting_strain = shear_strain[drop_start] -shear_strain[previous_drop_end] waiting_time = shear_time[drop_start] -shear_time[previous_drop_end] avalanches.append([stress_drop, strain_duration, time_duration, waiting_strain, waiting_time, t0, t1]) avalanches = np.array(avalanches) df_avalanches = pd.DataFrame(avalanches, columns=['Stress_drop', 'Strain_duration', 'Time_duration', 'Waiting_strain', 'Waiting_time', 'T0', 'T1']) # Remove the very small stress drops df_avalanches = df_avalanches[df_avalanches['Stress_drop'] > threshold] df_avalanches = df_avalanches[df_avalanches['Strain_duration'] < 0.01] dataset_size = len(df_avalanches) for i in range(dataset_size): if i == 0: df_avalanches.iloc[i]['Waiting_time'], df_avalanches.iloc[i]['Waiting_strain'] = 0, 0 else: df_avalanches.iloc[i]['Waiting_time'] = df_avalanches.iloc[i]['T0'] - df_avalanches.iloc[i-1]['T1'] df_avalanches.iloc[i]['Waiting_strain'] = df_avalanches.iloc[i]['Waiting_time']*shear_rate df_avalanches.reset_index() writer = pd.ExcelWriter(output_path + '/Stress avalanches.xlsx') df_avalanches.to_excel(writer, sheet_name='Stress avalanches') # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # 4. Statistical analysis # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # 4.1 Frequency density of stress drop # stress_drop = df_avalanches['Stress_drop'].values bin_value, bin_range, frequency, digitized = histgram_logform(stress_drop, threshold, 0.05) data_selected = (frequency > 1e-6) fit_params1 = fit_truncated_powerlaw(bin_value[data_selected], frequency[data_selected], np.zeros(np.sum(data_selected == True))) stress_drop_pdf = pd.DataFrame(np.stack((bin_value, frequency), axis=1), columns=['Stress_drop', 'PDF']) stress_drop_pdf.to_excel(writer, sheet_name='PDF of stress drops') # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # 4.2 Frequency density of time duration # time_duration = df_avalanches['Time_duration'].values bin_value, bin_range, frequency, digitized = histgram_logform(time_duration, time_resolution, 0.05) data_selected = (frequency > 1e-6) fit_params2 = fit_truncated_powerlaw(bin_value[data_selected], frequency[data_selected], np.zeros(np.sum(data_selected == True))) time_duration_pdf = pd.DataFrame(np.stack((bin_value, frequency), axis=1), columns=['Time_duration', 'PDF']) time_duration_pdf.to_excel(writer, sheet_name='PDF of time duration') # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # 4.3 Time duration vs stress drop # time_duration_binning = np.array([[time_duration[digitized == i].mean(), time_duration[digitized == i].std()] for i in range(1, len(bin_value)+1)]) stress_drop_binning = np.array([[stress_drop[digitized == i].mean(), stress_drop[digitized == i].std()] for i in range(1, len(bin_value)+1)]) # https://stackoverflow.com/questions/2831516/isnotnan-functionality-in-numpy-can-this-be-more-pythonic time_duration, duration_range = time_duration_binning[:, 0], time_duration_binning[:, 1] stress_drop, drop_range = stress_drop_binning[:, 0], stress_drop_binning[:, 1] fit_params3 = fit_powerlaw(time_duration_binning[:, 0][data_selected], stress_drop_binning[:, 0][data_selected], stress_drop_binning[:, 1][data_selected], weight=False) df_duration_drop = pd.DataFrame(np.stack((time_duration, duration_range, stress_drop, drop_range), axis=1), columns=['Time_duration', 'Duration_range', 'Stress_drop', 'Drop_range']) df_duration_drop.to_excel(writer, sheet_name='Duration vs Drop') # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # 4.4 Frequency density of interevent time (waiting time of avalanche events) # waiting_time = df_avalanches['Waiting_time'].values bin_value, bin_range, frequency, digitized = histgram_logform(waiting_time, time_resolution, 0.05) data_selected = (frequency > 1e-6) fit_params4 = fit_truncated_powerlaw(bin_value[data_selected], frequency[data_selected], np.zeros(np.sum(data_selected == True))) waiting_time_pdf = pd.DataFrame(np.stack((bin_value, frequency), axis=1), columns=['Waiting_time', 'PDF']) waiting_time_pdf.to_excel(writer, sheet_name='PDF of inter-event time') writer.save() writer.close() # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # 4.4 Bootstrap resampling # bs_fit_params1 = [[] for i in range(k_sampling)] bs_fit_params2 = [[] for i in range(k_sampling)] bs_fit_params3 = [[] for i in range(k_sampling)] bs_fit_params4 = [[] for i in range(k_sampling)] for k in range(k_sampling): data_resample = bootstrap_resample(np.arange(dataset_size), n=int(dataset_size*0.33)) df_resample_avalanches = df_avalanches.iloc[data_resample] stress_drop = df_resample_avalanches['Stress_drop'] time_duration = df_resample_avalanches['Time_duration'] waiting_time = df_resample_avalanches['Waiting_time'] # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # 4.4.1 Frequency density of stress drop # bin_value, bin_range, frequency, digitized = histgram_logform(stress_drop, threshold, 0.05) data_selected = (frequency > 1e-6) power_coeff = fit_truncated_powerlaw(bin_value[data_selected], frequency[data_selected], np.zeros(np.sum(data_selected == True))) bs_fit_params1[k] = power_coeff # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # 4.4.2 Frequency density of time duration # bin_value, bin_range, frequency, digitized = histgram_logform(time_duration, time_resolution, 0.05) data_selected = (frequency > 1e-6) power_coeff = fit_truncated_powerlaw(bin_value[data_selected], frequency[data_selected], np.zeros(np.sum(data_selected == True))) bs_fit_params2[k] = power_coeff # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # 4.4.3 Stress drop vs strain duration # time_duration_binning = np.array([[time_duration[digitized == i].mean(), time_duration[digitized == i].std()] for i in range(1, len(bin_value)+1)]) stress_drop_binning = np.array([[stress_drop[digitized == i].mean(), stress_drop[digitized == i].std()] for i in range(1, len(bin_value)+1)]) # https://stackoverflow.com/questions/2831516/isnotnan-functionality-in-numpy-can-this-be-more-pythonic power_coeff = fit_powerlaw(time_duration_binning[:,0][data_selected], stress_drop_binning[:,0][data_selected], stress_drop_binning[:,1][data_selected], weight=False) bs_fit_params3[k] = power_coeff # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # 4.4.4 Frequency density of interevent time (waiting time of avalanche events) # bin_value, bin_range, frequency, digitized = histgram_logform(waiting_time, threshold, 0.05) data_selected = (frequency > 1e-6) power_coeff = fit_truncated_powerlaw(bin_value[data_selected], frequency[data_selected], np.zeros(np.sum(data_selected == True))) bs_fit_params4[k] = power_coeff df_fit_params1 = pd.DataFrame(np.array(bs_fit_params1), index=np.arange(1, 1+k_sampling, 1), columns=['Amp', 'Alpha', 'Beta']) df_fit_params2 = pd.DataFrame(np.array(bs_fit_params2), index=np.arange(1, 1+k_sampling, 1), columns=['Amp', 'Alpha', 'Beta']) df_fit_params3 = pd.DataFrame(np.array(bs_fit_params3), index=np.arange(1, 1+k_sampling, 1), columns=['Amp', 'Tau']) df_fit_params4 = pd.DataFrame(np.array(bs_fit_params4), index=np.arange(1, 1+k_sampling, 1), columns=['Amp', 'Alpha', 'Beta']) writer = pd.ExcelWriter(output_path + '/Parameter space of data fitting.xlsx') df_fit_params1.to_excel(writer, sheet_name='Stress drop') df_fit_params2.to_excel(writer, sheet_name='Time duration') df_fit_params3.to_excel(writer, sheet_name='Duration vs Drop') df_fit_params4.to_excel(writer, sheet_name='Inter-event time') writer.save() writer.close() # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # 5 Plot # nrows, ncols, size = 2, 2, 4 fig = plt.figure(figsize=(ncols*size, nrows*size)) ax1 = plt.subplot(nrows, ncols, 1) ax2 = plt.subplot(nrows, ncols, 2) ax3 = plt.subplot(nrows, ncols, 3) ax4 = plt.subplot(nrows, ncols, 4) amp_mean, alpha_mean, beta_mean = df_fit_params1['Amp'].median(), df_fit_params1['Alpha'].median(), df_fit_params1['Beta'].median() amp_std, alpha_std, beta_std = df_fit_params1['Amp'].std(), df_fit_params1['Alpha'].std(), df_fit_params1['Beta'].std() ax1.scatter(stress_drop_pdf['Stress_drop'], stress_drop_pdf['PDF'], s=15, marker=markers[0], color=colors[0]) ax1.plot(stress_drop_pdf['Stress_drop'], truncated_powerlaw(stress_drop_pdf['Stress_drop'], fit_params1[0], fit_params1[1], fit_params1[2]), color=colors[0], linewidth=2, label='Fit line') ax1.set_xscale('log') ax1.set_yscale('log') ax1.set_xlabel('stress drop, $s$', fontsize=12) ax1.set_ylabel('$P(s)$', fontsize=12) ax1.tick_params(axis='both', labelsize=12) ax1.set_title("τ=%4.3f±%4.3f, $s\mathregular{_*}$=%4.3f±%4.3f" % (alpha_mean, alpha_std, beta_mean, beta_std), fontsize=12) # ax1.legend(fontsize=12) amp_mean, alpha_mean, beta_mean = df_fit_params2['Amp'].median(), df_fit_params2['Alpha'].median(), df_fit_params2['Beta'].median() amp_std, alpha_std, beta_std = df_fit_params2['Amp'].std(), df_fit_params2['Alpha'].std(), df_fit_params2['Beta'].std() ax2.scatter(time_duration_pdf['Time_duration'], time_duration_pdf['PDF'], s=15, marker=markers[0], color=colors[1]) ax2.plot(time_duration_pdf['Time_duration'], truncated_powerlaw(time_duration_pdf['Time_duration'], fit_params2[0], fit_params2[1], fit_params2[2]), color=colors[1], linewidth=2, label='Fit line') ax2.set_xscale('log') ax2.set_yscale('log') ax2.set_xlabel('time duration, $T_n$', fontsize=12) ax2.set_ylabel('$P(T_n)$', fontsize=12) ax2.tick_params(axis='both', labelsize=12) ax2.set_title("τ=%4.3f±%4.3f, $T\mathregular{_*}$=%4.3f±%4.3f" % (alpha_mean, alpha_std, beta_mean, beta_std), fontsize=12) # ax2.legend(fontsize=12) amp_mean, tau_mean = df_fit_params3['Amp'].median(), df_fit_params3['Tau'].median() amp_std, tau_std = df_fit_params3['Amp'].std(), df_fit_params3['Tau'].std() ax3.scatter(df_duration_drop['Time_duration'], df_duration_drop['Stress_drop'], s=15, marker=markers[0], color=colors[2]) ax3.plot(df_duration_drop['Time_duration'], powerlaw(df_duration_drop['Time_duration'], 10**fit_params3[0], fit_params3[1]), color=colors[2], linewidth=2, label='Fit line') ax3.set_xscale('log') ax3.set_yscale('log') ax3.set_xlabel('time duration, $T_n$', fontsize=12) ax3.set_ylabel('stress drop, $s$', fontsize=12) ax3.tick_params(axis='both', labelsize=12) ax3.set_title("τ=%4.3f±%4.3f" % (tau_mean, tau_std), fontsize=12) # ax3.legend(fontsize=12) amp_mean, alpha_mean, beta_mean = df_fit_params4['Amp'].median(), df_fit_params4['Alpha'].median(), df_fit_params4['Beta'].median() amp_std, alpha_std, beta_std = df_fit_params4['Amp'].std(), df_fit_params4['Alpha'].std(), df_fit_params4['Beta'].std() ax4.scatter(waiting_time_pdf['Waiting_time'], waiting_time_pdf['PDF'], s=15, marker=markers[0], color=colors[3]) ax4.plot(waiting_time_pdf['Waiting_time'], truncated_powerlaw(waiting_time_pdf['Waiting_time'], fit_params4[0], fit_params4[1], fit_params4[2]), color=colors[3], linewidth=2, label='Fit line') ax4.set_xscale('log') ax4.set_yscale('log') ax4.set_xlabel('inter-event time, ' + r'$\tau_\ell$', fontsize=12) ax4.set_ylabel(r'$P({\tau_\ell})$', fontsize=12) ax4.tick_params(axis='both', labelsize=12) ax4.set_title("τ=%4.3f±%4.3f, $T\mathregular{_*}$=%4.3f±%4.3f" % (alpha_mean, alpha_std, beta_mean, beta_std), fontsize=12) # ax4.legend(fontsize=12) # fig.legend(loc='center', fontsize=15) plt.tight_layout() file_path = output_path + '/Statistics of stress drop.png' plt.savefig(file_path, dpi=600, bbox_inches='tight') plt.show() # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # 6 Statistics of granular avalanches and earthquakes # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # 6.1 Mainshocks: By defining the large stress drops as mainshocks, and other shocks are either foreschocks or aftershocks # References: # [1] Hatano, T., Narteau, C., Shebalin, P., 2015. Common dependence on stress for the statistics of granular avalanches and earthquakes. Sci. Rep. 5, 1–9. doi:10.1038/srep12280 # [2] Johnson, P.A., Jia, X., 2005. Nonlinear dynamics, granular media and dynamic earthquake triggering. Nature 437, 871–874. doi:10.1038/nature04015 # [3] Lherminier, S., Planet, R., Vehel, V.L.D., Simon, G., Vanel, L., Måløy, K.J., Ramos, O., 2019. Continuously Sheared Granular Matter Reproduces in Detail Seismicity Laws. Phys. Rev. Lett. 122, 218501. # df_mainshocks = df_avalanches[df_avalanches['Stress_drop'] >= M0] df_weakshocks = df_avalanches[df_avalanches['Stress_drop'] < M0] # Now, the waiting time is the time interval between mainshocks for i in range(len(df_mainshocks)): if i == 0: df_mainshocks.iloc[i]['Waiting_time'] = df_mainshocks.iloc[i]['Time_duration'] df_mainshocks.iloc[i]['Waiting_strain'] = df_mainshocks.iloc[i]['Strain_duration'] else: df_mainshocks.iloc[i]['Waiting_time'] = df_mainshocks.iloc[i]['T0'] - df_mainshocks.iloc[i-1]['T1'] df_mainshocks.iloc[i]['Waiting_strain'] = df_mainshocks.iloc[i]['Waiting_time']*shear_rate Ttol = shear_time.max() - shear_time.min() seismicity_rate = len(df_mainshocks)/Ttol characteristic_time = 1/seismicity_rate mainshocks_sita = df_mainshocks['Waiting_time']/characteristic_time # Foreshocks and aftershocks digitized = np.digitize(df_weakshocks.index, df_mainshocks.index) weakshocks_type = [[] for i in range(len(df_weakshocks))] weakshocks_time = np.zeros(len(df_weakshocks)) for i, j in enumerate(digitized): if digitized[i] <= 0: weakshocks_type[i] = 'Foreshocks' weakshocks_time[i] = df_mainshocks.iloc[j]['T0'] - df_weakshocks.iloc[i]['T1'] elif (digitized[i] > 0) & (digitized[i] < len(df_mainshocks)): T_fore = df_mainshocks.iloc[j]['T0'] - df_weakshocks.iloc[i]['T1'] T_after = df_weakshocks.iloc[i]['T0'] - df_mainshocks.iloc[j-1]['T1'] if T_after <= T_fore: weakshocks_type[i] = 'Aftershocks' weakshocks_time[i] = T_after else: weakshocks_type[i] = 'Foreshocks' weakshocks_time[i] = T_fore else: weakshocks_type[i] = 'Aftershocks' weakshocks_time[i] = df_weakshocks.iloc[i]['T0'] - df_mainshocks.iloc[j-1]['T1'] df_weakshocks_type = pd.DataFrame(weakshocks_type, columns=['Type'], index=df_weakshocks.index) df_weakshocks_time = pd.DataFrame(weakshocks_time, columns=['Tl'], index=df_weakshocks.index) df_weakshocks = pd.concat([df_weakshocks, df_weakshocks_type, df_weakshocks_time], axis=1) writer = pd.ExcelWriter(output_path + '/Earthquake.xlsx') df_mainshocks.to_excel(writer, sheet_name='Mainshocks') df_weakshocks.to_excel(writer, sheet_name='Foreshocks and aftershocks') # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # 6.2 Frequency density of inter-event times, in terms of θ = τ/τ∗. # bin_value, bin_range, frequency, digitized = histgram_logform(mainshocks_sita, np.min(mainshocks_sita), step=0.05) data_selected = (frequency > 1e-6) fit_params1 = fit_truncated_powerlaw(bin_value[data_selected], frequency[data_selected], np.zeros(np.sum(data_selected == True))) sita_pdf = pd.DataFrame(np.stack((bin_value, frequency), axis=1), columns=['Sita', 'PDF']) sita_pdf.to_excel(writer, sheet_name='PDF of sita') # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # 6.3 Foreshock and aftershock analysis # foreshock_tl = df_weakshocks[df_weakshocks['Type'] == 'Foreshocks']['Tl'] aftershock_tl = df_weakshocks[df_weakshocks['Type'] == 'Aftershocks']['Tl'] bin_value, bin_range, frequency, digitized = histgram_logform(foreshock_tl, np.min(foreshock_tl), step=0.05) foreshock_tl_pdf = pd.DataFrame(np.stack((bin_value, frequency), axis=1), columns=['Tl_fore', 'PDF']) bin_value, bin_range, frequency, digitized = histgram_logform(aftershock_tl, np.min(aftershock_tl), step=0.05) aftershock_tl_pdf = pd.DataFrame(np.stack((bin_value, frequency), axis=1), columns=['Tl_after', 'PDF']) foreshock_tl_pdf.to_excel(writer, sheet_name='Foreshock rate') aftershock_tl_pdf.to_excel(writer, sheet_name='Aftershock rate') writer.save() writer.close() # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # 6.4 Plot # nrows, ncols, size = 1, 2, 4 fig = plt.figure(figsize=(ncols*size, nrows*size)) ax1 = plt.subplot(nrows, ncols, 1) ax2 = plt.subplot(nrows, ncols, 2) ax1.plot(sita_pdf['Sita'], sita_pdf['PDF'], marker=markers[0], color=colors[0]) ax1.set_xscale('log') ax1.set_yscale('log') ax1.set_xlabel(r'${\Theta}$', fontsize=12) ax1.set_ylabel(r'$P({\Theta})$', fontsize=12) ax1.tick_params(axis='both', labelsize=12) # ax1.legend(fontsize=12) ax2.plot(foreshock_tl_pdf['Tl_fore'], foreshock_tl_pdf['PDF'], marker=markers[0], color=colors[0], label='Foreshocks') ax2.plot(aftershock_tl_pdf['Tl_after'], aftershock_tl_pdf['PDF'], marker=markers[1], color=colors[1], label='Aftershocks') ax2.set_xscale('log') ax2.set_yscale('log') ax2.set_xlabel('$t$', fontsize=12) ax2.set_ylabel('$n(t)$', fontsize=12) ax2.tick_params(axis='both', labelsize=12) ax2.legend(fontsize=12) plt.tight_layout() file_path = output_path + '/Earthquake.png' plt.savefig(file_path, dpi=600, bbox_inches='tight') plt.show() # ================================================================== # S T A R T # if __name__ == '__main__': file_path = None file_name = None case = 'shear-rate-2-press-1e6' test_id = 1 shear_rate = 2 delta_strain = 1e-5 steady_strain = 1.0 strain_interval = 1e-5 filter_method = 'ewma' # savgol, gaussian, median, ewma filter_param = 11 threshold = 1e-5 M0 = 1e-2 k_sampling = 1000 argList = argv argc = len(argList) i = 0 while (i < argc): if (argList[i][:2] == "-c"): i += 1 case = str(argList[i]) elif (argList[i][:2] == "-t"): i += 1 test_id = int(argList[i]) elif (argList[i][:4] == "-rat"): i += 1 shear_rate = float(argList[i]) elif (argList[i][:4] == "-del"): i += 1 delta_strain = float(argList[i]) elif (argList[i][:4] == "-ste"): i += 1 steady_strain = float(argList[i]) elif (argList[i][:2] == "-i"): i += 1 strain_interval = float(argList[i]) elif (argList[i][:2] == "-f"): i += 1 filter_method = str(argList[i]) elif (argList[i][:2] == "-p"): i += 1 filter_param = float(argList[i]) elif (argList[i][:2] == "-h"): print(__doc__) exit(0) i += 1 print("Running case: %s" % case) print("Test id: %d" % test_id) print("Shear rate: %.5f" % shear_rate) print("Delta strain: %.5f" % delta_strain) print("Strain interval: %.5f" % strain_interval) print("Steady state upon: %.5f" % steady_strain) print("filter_method: %s" % filter_method) print("filter_param: %.5f" % filter_param) print("Drop threshold: %.5f" % threshold) print(60 * '~') CalStressDrops(case, test_id, shear_rate, delta_strain, steady_strain, strain_interval, filter_method, filter_param, threshold, k_sampling, M0)
Python
UTF-8
1,036
4.34375
4
[]
no_license
#Autor: Luis Ricardo Chagala Cervantes. #Determinar que tipo de triangulo es, referente a las medidas de los lados ingresados. def calculoTriangulo(a, b, c): x = a**2 y = b**2 z = c**2 if a <= 0 or b <= 0 or c <= 0: return "Estos lados no corresponden a un triángulo" if int(float(x+y)) == int(float(z))or int(float(x+z)) == int(float(y))or int(float(z+y)) == int(float(x)): return "Es un triangulo cuadrado" if int(float(a)) == int(float(b)) and int(float(a)) == int(float(c)): return "Es un triangulo Equilatero" if int(float(a)) == int(float(b)) or int(float(a)) == int(float(c))or int(float(b)) == int(float(c)): return "Es un triangulo Isósceles" else: return "Estos lados no corresponden a un triángulo" def imprimir(triangulo): print(triangulo) def main(): a = float(input("Lado A: ")) b = float(input("Lado b: ")) c = float(input("Lado C: ")) triangulo = calculoTriangulo(a, b, c) imprimir(triangulo) main()
Markdown
UTF-8
658
2.875
3
[]
no_license
# Bookmark Challenge # This web application has been designed to maintain a collection of bookmarks. Users are able to save useful URLs and tag them in order to find them later on. Additionally you can browse bookmarks that other users have added and comment on them. Before building this project we created user stories and domain models. ``` As someone who does not have a up to date browser I would like to see my favourite websites As someone who has bad download speeds and cant download chrome I would like to be able to add my favourite websites I would like to be able to see these websites in my list ``` ![alt text](https://imgur.com/HD5NS2Y)
TypeScript
UTF-8
804
2.765625
3
[]
permissive
import { getScrollBarSize } from '../../browser/scrollbar' type HTMLBodyStyle = { overflow: string | null paddingRight: string | null } const memo: HTMLBodyStyle = { overflow: null, paddingRight: null } let locked = false export function lock() { const style = document.body.style // cache memo.overflow = style.overflow memo.paddingRight = style.paddingRight // take scrollbar size into account, // avoid page flashing... if (document.documentElement.clientWidth < window.innerWidth) { style.paddingRight = `${getScrollBarSize()}px` } // always make `body` hidden when modal shown style.overflow = 'hidden' locked = true } export function unlock() { locked = false Object.assign(document.body.style, memo) } export function isLocked() { return locked }
C
UTF-8
1,554
3.609375
4
[]
no_license
/* Demostrar el problema de bloqueos cuando se invierten los mutexes para proteger dos variables globales */ #include <stdio.h> #include <pthread.h> #define NTHREADS 2 #define VECES 50 pthread_mutex_t mutex_c = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex_p = PTHREAD_MUTEX_INITIALIZER; int c, p; void * consumidor(void *); void * productor(void *); int main(int argc, char **argv) { pthread_t hilos[NTHREADS]; int result, i; // Crear hilos result = pthread_create(&hilos[0], NULL, productor, NULL); if (result) printf("Error al crear el sumador \n"); result = pthread_create(&hilos[1], NULL, consumidor, NULL); if (result) printf("Error al crear el restador \n"); // Esperar que terminen los hilos for(i = 0; i < NTHREADS; ++i) { result = pthread_join(hilos[i], NULL); if (result) printf("Error al adjuntar el hilo %d \n", i); } //Garantizar que se liberen los recursos de los hilos pthread_exit(NULL); } void * productor(void * arg) { int i; for(i = 0; i < VECES; ++i) { pthread_mutex_lock(&mutex_p); //Cambio de contexto sleep(rand()%5; pthread_mutex_lock(&mutex_c); p = c + 1; pthread_mutex_unlock(&mutex_c); pthread_mutex_unlock(&mutex_p); } pthread_exit(NULL); } void * consumidor(void * arg) { int i; for(i = 0; i < VECES; ++i) { pthread_mutex_lock(&mutex_c); //Cambio de contexto sleep(rand()%5; pthread_mutex_lock(&mutex_p); p = c + 1; pthread_mutex_unlock(&mutex_p); pthread_mutex_unlock(&mutex_c); } pthread_exit(NULL); }
PHP
UTF-8
2,728
3.140625
3
[]
no_license
<?php namespace Jazzee\Entity; /** * Message * * Messages between applicants and programs * * @Entity * @Table(name="messages") * @SuppressWarnings(PHPMD.ShortVariable) * @author Jon Johnson <jon.johnson@ucsf.edu> * @license http://jazzee.org/license BSD-3-Clause */ class Message { /** * Sender Types */ const APPLICANT = 2; const PROGRAM = 4; /** * @Id * @Column(type="bigint") * @GeneratedValue(strategy="AUTO") */ private $id; /** * @ManyToOne(targetEntity="Thread",inversedBy="messages") * @JoinColumn(onDelete="CASCADE") */ private $thread; /** @Column(type="integer") */ private $sender; /** @Column(type="text") */ private $text; /** @Column(type="datetime") */ private $createdAt; /** @Column(type="boolean") */ private $isRead; public function __construct() { $this->isRead = false; $this->createdAt = new \DateTime(); } /** * Get id * * @return bigint $id */ public function getId() { return $this->id; } /** * Set sender * * @param string $sender */ public function setSender($sender) { if (!in_array($sender, array(self::APPLICANT, self::PROGRAM))) { throw new \Jazzee\Exception("Invalid sender type. Must be one of the constants APPLICANT or PROGRAM"); } $this->sender = $sender; } /** * Get sender * * @return string $sender */ public function getSender() { return $this->sender; } /** * Set text * * @param text $text */ public function setText($text) { $this->text = $text; } /** * Get text * * @return text $text */ public function getText() { return $this->text; } /** * Set createdAt * * @param string $createdAt */ public function setCreatedAt($createdAt) { $this->createdAt = new \DateTime($createdAt); } /** * Get createdAt * * @return datetime $createdAt */ public function getCreatedAt() { return $this->createdAt; } /** * Mark as read */ public function read() { $this->isRead = true; } /** * Un Mark as read */ public function unRead() { $this->isRead = false; } /** * Get read status * * @param integer $sender who is the sender * @return boolean $isRead */ public function isRead($sender) { if ($this->sender == $sender) { return $this->isRead; } return true; } /** * Set thread * * @param Entity\Thread $thread */ public function setThread(Thread $thread) { $this->thread = $thread; } /** * Get thread * * @return \Jazzee\Entity\Thread $thread */ public function getThread() { return $this->thread; } }
PHP
UTF-8
3,249
2.796875
3
[]
no_license
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> .content { width: 450px; margin: 0 auto; padding: 0px 20px 20px; background: white; border: 2px solid navy; } h1 { color: navy; } label { width: 10em; padding-right: 1em; float: left; } #data input { float: left; width: 15em; margin-bottom: .5em; } #button input { float: left; margin-bottom: .5em; } #error { color: red; } br { clear: left; } </style> </head> <body> <?php function check($num) { return is_numeric($num) && $num > 0 && floor($num) == $num; } if ($_SERVER["REQUEST_METHOD"] == "POST") { $Product = $_POST["product"]; $Price = $_POST["price"]; $Percent = $_POST["percent"]; $error = ""; if (check($Price) && check($Percent)) { $DiscountAmount = $Price * $Percent / 100; $DiscountPrice = $Price - $DiscountAmount; ?> <div class="content"> <h1>Product Discount Calculator</h1> <form> <div id="data"> <label>Product Description:</label> <span><?= $Product ?></span><br /> <label>List Price:</label> <span><?= "$" . $Price ?></span><br /> <label>Discount Percent:</label> <span><?= $Percent . '%' ?></span><br /> <label>Discount Amount:</label> <span><?= "$" . $DiscountAmount ?></span><br /> <label>Discount Price:</label> <span><?= "$" . $DiscountPrice ?></span><br /> </div> </form> </div> <?php } else { $error = "Wrong Input"; ?> <div class="content"> <h1>Product Discount Calculator</h1> <form action="discount.php" method="POST"> <div id="data"> <label>&nbsp;</label> <P id="error"><?= $error ?></P> <label>Product Description:</label> <input type="text" name="product" /><br /> <label>List Price:</label> <input type="text" name="price" /><br /> <label>Discount Percent:</label> <input type="text" name="percent" />% </div> <div id="buttons"> <label>&nbsp;</label> <input type="submit" value="Calculate Discount" /><br /> </div> </form> </div> <?php } } ?> </body> </html>
Python
UTF-8
7,009
3
3
[]
no_license
""" Audio Pre-processing Classes """ import torch from torch.utils.data import Dataset import random import librosa import numpy as np """ Class to apply data pre-processing for model input """ class LoadAudio(): # load audio data def load(audio_file): data, sr = librosa.load(audio_file,sr=None,mono=False) #print(data.shape) return (data, sr) # resample audio to standard rate so all arrays have same dimensions def resample(audio, rate): data, sr = audio if (rate == sr): # ignore if audio is already at correct sampling rate return audio else: data2 = librosa.resample(data, sr, rate) # merge channels #print(data2.shape) return (data2, rate) # convert all audio to mono def mono(audio): data, sr = audio if (data.shape[0] == 1): # ignore if audio is already stereo return audio else: data2 = librosa.to_mono(data) # Convert to mono by averaging samples across channels #print(data2.shape) return data2, sr # resize all audio to same length def resize(audio, max_s): data, sr = audio data_len = len(data) max_len = sr * max_s if (data_len > max_len): # Truncate the signal to the given length data = data[:max_len] elif (data_len < max_len): pad_begin_len = random.randint(0, max_len - data_len) # Length of padding to add at the beginning of the signal pad_end_len = max_len - data_len - pad_begin_len # Length of padding to add at the beginning of the signal pad_begin = np.zeros(pad_begin_len) # Pad beginning with 0s pad_end = np.zeros(pad_end_len) # Pad end with 0s data = np.concatenate((pad_begin, data, pad_end)) # Concatenate data with padding #print(data.shape) return (data, sr) # add random noise def add_noise(audio): data, sr = audio noise = np.random.randn(len(data)) noisy_data = data + (0.0005*noise) return (noisy_data, sr) # shift pitch of audio data by random amount def pitchShift(audio,shift_int): data, sr = audio n = random.randint(0-shift_int,shift_int) shifted_data = librosa.effects.pitch_shift(data,sr,n) #print(shifted_data.shape) return (shifted_data, sr) # create mel spectrograms def spectrogram(audio, n_mels=128, n_fft=1024, hop_len=None): data,sr = audio spec = librosa.feature.melspectrogram(data, sr) # [channel, n_mels, time] spec_dB = librosa.core.power_to_db(spec, ref=np.max) # convert to decibels #print(spec.shape) return spec_dB # hpss spectrograms def hpssSpectrograms(audio,sgram): data, sr = audio sgram = np.expand_dims(sgram, axis=0) # add extra dimension D = librosa.feature.melspectrogram(data, sr) # create Mel spect of audio data H, P = librosa.decompose.hpss(D) # Apply HPSS to Mel spect H = np.expand_dims(H, axis=0) # add extra dimension P = np.expand_dims(P, axis=0) # add extra dimension H_dB = librosa.core.power_to_db(H, ref=np.max) # convert to decibels P_dB = librosa.core.power_to_db(P, ref=np.max) # convert to decibels sgram = np.concatenate((sgram, H_dB), axis=0) # combine spectrograms sgram = np.concatenate((sgram, P_dB), axis=0) # combine spectrograms #print(sgram.shape) return sgram # return combined spectrogram # nn filtering def nnSpectrograms(audio,sgram): data, sr = audio D = librosa.feature.melspectrogram(data, sr) # create Mel spect of audio data nn = librosa.decompose.hpss(D) # Apply nn to Mel spect nn_dB = librosa.core.power_to_db(nn, ref=np.max) # convert to decibels sgram = np.concatenate((sgram, nn_dB), axis=0) # combine spectrograms return sgram # zero crossing rate def zeroCrossingRate(audio): data, sr = audio z =librosa.feature.zero_crossing_rate(data) z = np.expand_dims(z, axis=0) return z # mfcc def mfcc(audio): data, sr = audio m = librosa.feature.mfcc(y=data, sr=sr) m = np.expand_dims(m, axis=0) return m # spectral centroids def spectralCentroid(audio): data, sr = audio c = librosa.feature.spectral_centroid(data) c = np.expand_dims(c, axis=0) return c """ Class to load dataset for CNN models """ class AudioDS(Dataset): def __init__(self, labels, train=True): self.labels = labels self.max_s = 1 # max length of audio input = 1 sec self.sr = 44100 # audio input samplig rate self.pitch_shift = 3 # maximum pitch shift amount self. train = train # train or test data (bool) def __len__(self): return len(self.labels) def __getitem__(self, idx): relative_path = self.labels[idx][0] # audio file location class_id = self.labels[idx][1] # class label audio = LoadAudio.load(relative_path) # load audio file audio = LoadAudio.resample(audio, self.sr) # resample audio audio = LoadAudio.mono(audio) # make audio stereo audio = LoadAudio.resize(audio, self.max_s) # resize audio if self.train == True: audio = LoadAudio.pitchShift(audio, self.pitch_shift) # apply pitch shift #audio = LoadAudio.add_noise(audio) # add random noise sgram = LoadAudio.spectrogram(audio, n_mels=128, n_fft=1024, hop_len=None) # create spectrogram sgram = LoadAudio.hpssSpectrograms(audio,sgram) # create HPSS spectrograms sgram_tensor = torch.tensor(sgram) # convert to tensor audio_file, sr = audio return sgram_tensor, class_id, sr
PHP
UTF-8
1,387
2.96875
3
[ "BSD-2-Clause" ]
permissive
<?php Rhaco::import("lang.StringUtil"); /** * @author Kazutaka Tokushima * @license New BSD License * @copyright Copyright 2008- rhaco project. All rights reserved. */ class DocFunction{ var $description; var $name; var $vars = array(); var $tests = array(); /** * コンストラクタ * @param string $name * @param string $contents * @param string $description */ function DocFunction($name,$contents,$description=""){ $this->description = StringUtil::comments($description); $this->name = trim($name); $this->tests = $this->_test($contents); $this->vars = $this->_one_variable($contents); } function _one_variable($value){ $result = array(); if(preg_match_all("/[^\\$\\\\](\\$[\w_]+)/"," ".$value,$variables)){ $vars = array(); foreach($variables[1] as $variable){ $vars[$variable] = (isset($vars[$variable])) ? true : false; } foreach($vars as $key => $bool){ if(!$bool && !in_array($key,array("\$this","\$GLOBALS","\$_SERVER","\$_SESSIO","\$_COOKIE"))) $result[] = $key; } } return $result; } function _test($value){ $result = array(); if(preg_match_all("/\/\*\*\*.+?\*\//s",$value,$match)){ foreach($match[0] as $test){ $result[] = StringUtil::comments($test); } } return $result; } /** * @return boolean */ function isLocal(){ return !(!empty($this->name) && substr($this->name,0,1) != "_"); } } ?>
Python
UTF-8
331
2.703125
3
[]
no_license
import urllib.request from app.controllers.save_file import save_file # download and save image from url def from_url(url: str): filename = url.split('/')[-1] # name with which the file will be saved at ./upload directory with urllib.request.urlopen(url) as f: data = f.read() save_file(filename, data)
Markdown
UTF-8
694
2.609375
3
[]
no_license
## Hello guys! 👋 - 😃 My name is Jelson. - 📚 I am graduated in IT management and I am currently studying database technology and web development (HTML, CSS, JAVASCRIPT). ![jbinario GitHub Stats](https://github-readme-stats.vercel.app/api?username=jbinario&show_icons=true) 🌎 where to find me: <a target="_blank" href="https://www.linkedin.com/in/jelsonalves/"> <img align="left" alt="LinkdeIN" width="22px" src="https://img.icons8.com/cute-clipart/64/000000/linkedin.png"/> </a> <a target="_blank" href="https://api.whatsapp.com/send?phone=11951375018"> <img align="left" alt="Whatsapp" width="22px" src="https://img.icons8.com/cute-clipart/64/000000/whatsapp.png"/> </a>
C++
UTF-8
2,336
2.640625
3
[]
no_license
#pragma once #include "azer/effect/effect.h" #include "azer/effect/effect_creator.h" #include "azer/effect/light.h" #include "azer/effect/material.h" namespace azer { class AmbientColorEffect : public Effect { public: static const char kEffectName[]; AmbientColorEffect(); ~AmbientColorEffect(); const char* GetEffectName() const override; #pragma pack(push, 4) struct vs_cbuffer { Matrix4 pv; Matrix4 world; Vector4 camerapos; }; struct ps_cbuffer { Vector4 ambient; }; #pragma pack(pop) void SetPV(const Matrix4& value) { pv_ = value;} void SetWorld(const Matrix4& value) { world_ = value;} void SetAmbient(const Vector4& c) { ambient_ = c;} static Effect* CreateObject() { return new AmbientColorEffect;} protected: ShaderClosurePtr InitVertexStage(Shader* shader) override; ShaderClosurePtr InitPixelStage(Shader* shader) override; void ApplyShaderParamTable(Renderer* renderer) override; Matrix4 pv_; Matrix4 world_; Vector4 ambient_; DECLARE_EFFECT_DYNCREATE(AmbientColorEffect); DISALLOW_COPY_AND_ASSIGN(AmbientColorEffect); }; class ColorEffect : public Effect { public: static const char kEffectName[]; ColorEffect(); ~ColorEffect(); const char* GetEffectName() const override; #pragma pack(push, 4) struct vs_cbuffer { Matrix4 pv; Matrix4 world; Vector4 camerapos; }; struct ps_cbuffer { ColorMaterialData mtrl; UniverseLight lights[4]; int light_count; }; #pragma pack(pop) void SetPV(const Matrix4& value); void SetWorld(const Matrix4& value); void SetCameraPos(const Vector4& pos); void SetLights(const LightPtr* value, int32_t count); void SetLightData(const UniverseLight* value, int32_t count); void SetMaterial(const ColorMaterialData& mtrl); static Effect* CreateObject() { return new ColorEffect;} protected: void ApplyShaderParamTable(Renderer* renderer) override; ShaderClosurePtr InitVertexStage(Shader* shader) override; ShaderClosurePtr InitPixelStage(Shader* shader) override; Matrix4 pv_; Matrix4 world_; Vector4 camerapos_; int32_t light_count_; static const int32_t kMaxLightCount = 8; UniverseLight lights_[kMaxLightCount]; ColorMaterialData mtrl_; DECLARE_EFFECT_DYNCREATE(ColorEffect); DISALLOW_COPY_AND_ASSIGN(ColorEffect); }; } // namespace azer
Java
UTF-8
1,936
2.609375
3
[]
no_license
package com.samajackun.sumascript.core.instructions; import com.samajackun.rodas.core.eval.Context; import com.samajackun.rodas.core.eval.EvaluationException; import com.samajackun.rodas.core.eval.EvaluatorFactory; import com.samajackun.rodas.core.model.Expression; import com.samajackun.sumascript.core.ExecutionException; import com.samajackun.sumascript.core.Instruction; import com.samajackun.sumascript.core.Jump; import com.samajackun.sumascript.core.SumaInstructionSerializerException; import com.samajackun.sumascript.core.expressions.Assignable; import com.samajackun.sumascript.core.jumps.NoJump; public class AssignationInstruction implements Instruction { private static final long serialVersionUID=8524622322183083120L; private final Assignable leftSide; private final Expression rightSide; public AssignationInstruction(Assignable leftSide, Expression rightSide) { super(); this.leftSide=leftSide; this.rightSide=rightSide; } @Override public Jump execute(Context context) throws ExecutionException { try { Object value=computeValue(context, context.getEvaluatorFactory(), this.leftSide, this.rightSide); this.leftSide.set(context, context.getEvaluatorFactory(), value); return NoJump.getInstance(); } catch (EvaluationException e) { throw new ExecutionException(e); } } protected Object computeValue(Context context, EvaluatorFactory evaluatorFactory, Assignable leftSide2, Expression rightSide2) throws EvaluationException { return rightSide2.evaluate(context, context.getEvaluatorFactory()); } @Override public String toCode(SumaInstructionSerializer serializer) throws SumaInstructionSerializerException { return serializer.serializeAssignation(this); } public Assignable getLeftSide() { return this.leftSide; } public Expression getRightSide() { return this.rightSide; } }