language stringclasses 15
values | src_encoding stringclasses 34
values | length_bytes int64 6 7.85M | score float64 1.5 5.69 | int_score int64 2 5 | detected_licenses listlengths 0 160 | license_type stringclasses 2
values | text stringlengths 9 7.85M |
|---|---|---|---|---|---|---|---|
Python | UTF-8 | 1,130 | 2.578125 | 3 | [
"MIT"
] | permissive | import numpy as np
import cv2
import os
import img_rec as im
face_recognizer=cv2.face.LBPHFaceRecognizer_create()
face_recognizer.read(r'C:\Users\pabhi\PycharmProjects\asish_py\trainingData.yml')
cap=cv2.VideoCapture(0) #If you want to recognise face from a video then replace 0 with video path
name={0:'abhi'}
while True:
ret,test_img=cap.read()
faces_detected,gray_img=im.faceDetection(test_img)
print("face Detected: ",faces_detected)
for (x, y, w, h) in faces_detected:
cv2.rectangle(test_img, (x, y), (x + w, y + h), (0, 255, 0), thickness=5)
for face in faces_detected:
(x, y, w, h) = face
roi_gray = gray_img[y:y + h, x:x + h]
label, confidence = face_recognizer.predict(roi_gray)
print("Confidence :", confidence)
print("label :", label)
im.draw_rect(test_img, face)
predicted_name = name[label]
im.put_text(test_img, predicted_name, x, y)
resized_img = cv2.resize(test_img, (1000, 700))
cv2.imshow("face detection ", resized_img)
if cv2.waitKey(10) == ord('q'):
break |
Java | UTF-8 | 418 | 2.546875 | 3 | [] | no_license | package com.epam;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
public class StringTask {
static final Scanner scanner = new Scanner(System.in);
static List<String> filter(List<String> list) {
return list.
stream().
filter(str -> str.startsWith("a") && str.length() == 3).
collect(Collectors.toList());
}
}
|
C | UTF-8 | 215 | 2.859375 | 3 | [] | no_license | #include<stdio.h>
#include"data.h"
void set_age(struct data *p,int age)
{
p->age = age;
}
static void datashow(struct data *p)
{
printf("age=%d\n",p->age);
}
void show (struct data *p)
{
datashow(p);
} |
JavaScript | UTF-8 | 2,649 | 2.5625 | 3 | [] | no_license | import {WebGLRenderer, sRGBEncoding, OrthographicCamera } from 'three';
import * as TWEEN from "@tweenjs/tween.js/dist/tween.amd";
import Scene1 from './scenes/Scene1';
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls'
import Observer, { EVENTS } from './Observer';
export class App {
constructor(container) {
this.container = container;
this.cameraPanUp=40;
this.camera_y = 300;
this.scene = new Scene1();
// ## Camera's config
this.camera = new OrthographicCamera(
this.container.clientWidth/-2,
this.container.clientWidth/2,
this.container.clientHeight/2,
this.container.clientHeight/-2,
-10000,
10000
)
this.camera.position.set(10, 10+this.camera_y, 10);
this.camera.lookAt(0, this.camera_y, 0);
// this.control = new OrbitControls(this.camera, this.container);
// ## Renderer's config
this.renderer = new WebGLRenderer({
antialias: true,
})
this.renderer.setPixelRatio(window.devicePixelRatio);
// sRGBEncoding
this.renderer.outputEncoding = sRGBEncoding;
// ## Light's config
this.renderer.physicallyCorrectLights = true;
this.container.appendChild(this.renderer.domElement);
this.onResize();
this.render();
this.events();
}
events(){
Observer.on(EVENTS.STACK,()=>{
this.camera_y += this.cameraPanUp;
const camera_up = new TWEEN.Tween(this.camera.position)
.to({
y:10+this.camera_y
},500)
.easing(TWEEN.Easing.Sinusoidal.In);
camera_up.start();
});
Observer.on(EVENTS.START,()=>{
this.camera_y = 300;
this.camera.position.set(10, 10+this.camera_y, 10);
this.camera.lookAt(0,this.camera_y,0);
const camera_zoom_in = new TWEEN.Tween(this.camera)
.to({
zoom:1
},900)
.easing(TWEEN.Easing.Sinusoidal.In)
.onUpdate(()=>{
this.camera.updateProjectionMatrix()
});
camera_zoom_in.start();
});
Observer.on(EVENTS.GAME_OVER,()=>{
const camera_zoom_out = new TWEEN.Tween(this.camera)
.to({
zoom:.6
},700)
.easing(TWEEN.Easing.Quadratic.Out)
.onUpdate(()=>{
this.camera.updateProjectionMatrix()
});
camera_zoom_out.start();
});
}
onResize() {
this.renderer.setSize(this.container.clientWidth, this.container.clientHeight);
this.camera.left =this.container.clientWidth/-2;
this.camera.right =this.container.clientWidth/2;
this.camera.top =this.container.clientHeight/2;
this.camera.bottom =this.container.clientHeight/-2;
this.camera.updateProjectionMatrix();
}
render() {
this.renderer.render(this.scene, this.camera);
// Updates here
this.scene.update();
this.renderer.setAnimationLoop(() => this.render());
}
}
|
Ruby | UTF-8 | 444 | 3.15625 | 3 | [] | no_license | filename = ARGV.first
puts "Please hit RETURN to start the survey"
$stdin.gets.chomp
target = open(filename, 'w')
print "How old are you?"
line1 = $stdin.gets.chomp
print "What is your favorite color?"
line2 = $stdin.gets.chomp
print "What time is it right now?"
line3 = $stdin.gets.chomp
target.write line1
target.write ("\n")
target.write line2
target.write ("\n")
target.write line3
target.write ("\n")
puts "Thank you!"
target.close
|
SQL | UTF-8 | 1,345 | 3.265625 | 3 | [] | no_license | '''
MIT License
Copyright (c) 2019 Arshdeep Bahga and Vijay Madisetti
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'''
SELECT first_name, last_name, salary
FROM employees, salaries
WHERE employees.emp_no=salaries.emp_no
AND employees.emp_no='10009'
AND to_date=(
SELECT MAX(to_date)
FROM salaries
WHERE emp_no = '10009'
);
'Sumant' 'Peac' 94409
|
Python | UTF-8 | 2,411 | 4.21875 | 4 | [] | no_license | '''
Note that for every forward function, there is a corresponding backward function. That is why at every step of your forward module you will be storing some values in a cache. The cached values are useful for computing gradients. In the backpropagation module you will then use the cache to calculate the gradients. This assignment will show you exactly how to carry out each of these steps.
3 - Initialization
You will write two helper functions that will initialize the parameters for your model. The first function will be used to initialize parameters for a two layer model. The second one will generalize this initialization process to LL layers.
3.1 - 2-layer Neural Network
Exercise: Create and initialize the parameters of the 2-layer neural network.
Instructions:
- The model's structure is: LINEAR -> RELU -> LINEAR -> SIGMOID.
- Use random initialization for the weight matrices. Use np.random.randn(shape)*0.01 with the correct shape.
- Use zero initialization for the biases. Use np.zeros(shape).
'''
def initialize_parameters(n_x, n_h, n_y):
"""
Argument:
n_x -- size of the input layer
n_h -- size of the hidden layer
n_y -- size of the output layer
Returns:
parameters -- python dictionary containing your parameters:
W1 -- weight matrix of shape (n_h, n_x)
b1 -- bias vector of shape (n_h, 1)
W2 -- weight matrix of shape (n_y, n_h)
b2 -- bias vector of shape (n_y, 1)
"""
np.random.seed(1)
### START CODE HERE ### (≈ 4 lines of code)
W1 = np.random.randn(n_h, n_x)*0.01
b1 = np.zeros((n_h, 1))
W2 = np.random.randn(n_y, n_h)*0.01
b2 = np.zeros((n_y, 1))
### END CODE HERE ###
assert(W1.shape == (n_h, n_x))
assert(b1.shape == (n_h, 1))
assert(W2.shape == (n_y, n_h))
assert(b2.shape == (n_y, 1))
parameters = {"W1": W1,
"b1": b1,
"W2": W2,
"b2": b2}
return parameters
parameters = initialize_parameters(3,2,1)
print("W1 = " + str(parameters["W1"]))
print("b1 = " + str(parameters["b1"]))
print("W2 = " + str(parameters["W2"]))
print("b2 = " + str(parameters["b2"]))
'''
Output:
W1 = [[ 0.01624345 -0.00611756 -0.00528172]
[-0.01072969 0.00865408 -0.02301539]]
b1 = [[ 0.]
[ 0.]]
W2 = [[ 0.01744812 -0.00761207]]
b2 = [[ 0.]]
''' |
Java | UTF-8 | 1,529 | 1.664063 | 2 | [] | no_license | //$Header: /gestionale/org.activebpel.rt.bpel/src/org/activebpel/rt/bpel/impl/addressing/IAeWsAddressingFactory.java,v 1.1 2009/09/23 13:08:42 zampognaro Exp $
/////////////////////////////////////////////////////////////////////////////
//PROPRIETARY RIGHTS STATEMENT
//The contents of this file represent confidential information that is the
//proprietary property of Active Endpoints, Inc. Viewing or use of
//this information is prohibited without the express written consent of
//Active Endpoints, Inc. Removal of this PROPRIETARY RIGHTS STATEMENT
//is strictly forbidden. Copyright (c) 2002-2004 All rights reserved.
/////////////////////////////////////////////////////////////////////////////
package org.activebpel.rt.bpel.impl.addressing;
/**
* Interface for a factory class that hands out the appropriate serializer/deserializer
* for a given WSA namespace
*/
public interface IAeWsAddressingFactory
{
/**
* Returns the WS-Addressing deserializer for a given namespace.
* The default deserializer is returned if the namespace parameter is null.
* @param aNamespace
* @return the Deserializer
*/
public IAeAddressingDeserializer getDeserializer(String aNamespace);
/**
* Returns the WS-Addressing serializer for a given namespace.
* The default serializer is returned if the namespace parameter is null.
* @param aNamespace
* @return the Serializer
*/
public IAeAddressingSerializer getSerializer(String aNamespace);
} |
Markdown | UTF-8 | 54,815 | 3.15625 | 3 | [] | no_license | In the Society: From Economics to Politics
==========================================
Let us begin our discussion on social issues with the basic part of any
society: work.
Work
----
There are two aspects to work:
1- Its value as a means: Products or results can only be achieved
through work. There are no exceptions to that. If the simple-minded
think that results can be obtained without effort or hard work, they are
wrong.
2- Its value as a topic: Work, in nature, is valuable.
Some thinkers believe that work is merely a means, and has no certain
value by itself. We must say that in relation to fatalistic reasons,
work has no specific value, but in relation to man, work can affect man,
for man consciously aims for a certain piece of work. Some people begin
work as soon as the grounds for carrying it out are prepared; results
are of no significance to them. The subject is important for them, so as
long as there is a possibility to succeed, they will continue. Those who
believe that the value of work lies solely in its results, always lose
many opportunities, because they regard them as fruitless. This is why
it is said that belief in work as a subject shows how alive the
individual and the society is, and the least opportunity produces the
best results.
The Definition of Work
----------------------
Work consists of an action that has useful results and arises from
conscious intention.
This definition can apply to all kinds of work. In business, for
instance, it can be modified as, a conscious, effective action done on
raw material in order to create positive change in man's living.
The Value of Work
-----------------
There has been a great deal of effort throughout history aiming to prove
the value and right to work. These efforts have basically been based
upon two factors:
1- Those who put their physical and mental efforts into producing things
were in fact endeavoring to prove the value of work. Group efforts,
however, have begun since two centuries ago, for the labor class needed
to be established first. Before that, workers did not attempt to defend
their rights, because the products were not large-scale or general (it
was the increase in factories and industries that made that possible)
and also the fact was ignored that human life wears out gradually by
work.
Furthermore, laborers had no cooperation or unity toward defending their
rights. Man's culture greatly emphasizes that work is valuable, and
cannot be accounted for by means of specific formulae, especially in
cases in which workers are forced to work. Pioneer culture believes that
the worker should be satisfied, and the real wages for his work should
be paid to him, for many workers are too concerned with making the ends
meet in their own lives to have time to think about the true value of
work.
2- True anthropologists have always preached the importance and value of
work. The fact that they have taught man that justice is the basis of
social human life shows how important they wanted to show work is.
When discussing the value of work, we must always keep in mind the human
aspect of values. If values are only considered as useful things, and
man is omitted from their definition, that would not be accurate. The
definition should be: Whatever is useful for man, and getting it calls
for work or losing something important to man or society, is a value.
In the past, there were various forms of value of work. Feudalism, for
instance included three kinds of trade and value of work:
1- Master and employee share the products
2- Receiving goods necessary for life as salary
3- Hard labor for which workers were paid too little
In other trade systems, the employer paid the apprentice in goods or
money.
After developments in economics and business, salary and wage became
important issues, and the value of work received more attention. The
question was posed, “What is the value of work?”
Three issues are to be considered before we can answer the question:
a) The scale and unit used for measuring work
b) The scale and unit used for measuring the value of work
c) The scale and unit used for measuring the prices
These units are either physically observable, like work and effects on
materials and the prices paid for the work done, or are not, and involve
an abstraction which clearly shows its origin.
Work is a phenomenon resulting from man's continual, unrepeatable vital
and mental activities. Thus, if we are to have a unit for work, it would
be a flow of human life and soul; it cannot be separate from man's life.
Since the phenomenon of life and soul cannot be mathematically measured,
neither can work, particularly in the case of mental endeavors, which
are extremely more complex than physical work, and can be measured by
means of no scientific scale.
In the case of mental endeavor, it is more complicated, for what
scientific scale or measurement unit can ever discover what the manager
of a large system is guessing about how he can bring about his system's
progress? Which scientific measurement scale can be used by a
discoverer, an artist or a social pioneer to determine his rout to
success? Can we hope to have a scientific measurement someday for the
emotional efforts made by man in order to achieve his highest goals?
What precision tools can ever determine the measurement units for
education and create a class which can create both the likes of Einstein
and Planck and also savage tyrants? Can we expect to see mathematics,
physics, physiology and psychology to join forces one day and determine
the scientific measurement system that can measure the activities of a
faithful soul, which is full of mental endeavor, or physical work that
is filled with hope and character and aim for the highest of social
goals and interpretation of the aim of life? Undoubtedly not.
The Domains of the Value of Work
--------------------------------
The issues on work and value are not confined to a economic aspect; work
and its value had better be studied in three domains:
1- The Purely Economic Domain: Economists deal with the observable
effects of work, its usefulness, demand, production, etc. Man and human
values and principles seldom show up in economists' discussions. Some
economic schools of thought, like the physiocrats, consider issues
concerning work as purely economic, and ignore human beings who do no
work at all. They see economic effects similar to other physical issues;
they even let the powerful to do as they please - with the excuse of
enforcing social order - which actually allows them to also break any
law they like, too.
2- The Socio-economic Domain: Here, dealing with issues on work and its
value is more difficult, for the social factors of work, production and
distribution and the need to prevent inflation and unemployment have a
great influence on work and labor. In this domain, work and its value
find a humane aspect, and profiteering tendencies are decreased.
However, some intellectuals interpret the society in a way to pay less
attention to the value of man; they see the society as a set of
individuals who are absolutely free, and should only be careful not to
disturb others. From such a viewpoint, social laws only serve to provide
mutual coexistence. These thinkers do not realize that man's selfish,
advantage-seeking nature cannot be corrected with mere social laws; the
highest of human values and supernatural principles must dominate man's
life in order to control his selfishness.
3- The Human-economic Domain: This domain is related to intelligible
life - that is, the type of life based on divine principles and values.
Man's mental and physical forces are not at the service of the
power-greedy and the selfish, who tend to use them as buyers of their
cleverly advertised - but in fact harmful and intoxicating - goods and
increase their own riches. In this domain, work and economic endeavor
does not move toward stupefying people and adding to the wealth of the
minority of the selfish. Rather, it serves to fulfill man's real needs
and uphold social justice.
Various Kinds and Aspects of Human Work
---------------------------------------
A preliminary classification of human work can be:
a) Mental efforts and positive mental work
b) Physical work
Mental work can be classified into these groups:
1- Purely mental work: such as mathematical, logical or philosophical
thoughts. Purely mental efforts may lead to physically observable
results. However, one out of every thousand mental endeavors may lead to
such effects only.
2- Mental work as a preliminary for physically observable work: Such
mental efforts serve as the preliminary to administer things like
designing or engineering activities.
3- Mental work in order to continue with the natural flow of an issue:
For example, thoughts on medicine in order to diagnose an illness or
cure a disease, or legal mental effort aiming to destroy atrocity and
help the oppressed, which may all lead to social justice.
4- Mental work serving to elevate man's individual life and build a
desirable social life: Actions taken with educational aims are examples
of this category. Such forms of work help human potentials and talents
flourish.
5- Artistic mental work: Some forms of artistic work are imitative, and
can be regarded as professions. Others, which are innovative, are
exploratory, mental activities. Mental artistic work can be categorized
into three groups:
a) Artistic work materialized upon useful material which makes the
material look beautiful. The artistic work both fulfills the
individual's needs and saturates his aesthetic tendencies.
b) Artistic work that motivates man to achieve intelligible life: A
beautiful painting or an exquisitely meaningful poem can activate man's
feelings to gain an intelligible life.
c) Artistic work that merely shows the artist's brainchild: This form of
work depicts the pinnacle of the artist's imagination, like abstract
works of art that are irrelevant to reality.
6- Political mental effort: This kind of work involves a series of
logical thoughts aiming to make social intelligible life go on.
7- Exploratory mental effort: The six forms mentioned above follow
logical rules, but this form of work goes far beyond logic. This is why
most discoverers are not professional logic scholars. Edison was not an
expert on logic, and neither were Mendeleyev or Roentgen. Some forms of
mental work may serve merely to satisfy our curiosity, whereas they
possess great value to economy and standard of living.
From a humanistic/economic point of view, work is highly significant,
for it relates to man's intelligible life.
Physical work: Let us further elaborate physical work by considering it
from three aspects:
1- The internal aspect: Any muscular work is accompanied by a series of
internal factors, some of which are the causes for the work, some others
occur tat he same time as the piece of work is produced, and some others
occur after the final product is created. The factors that serve as the
cause for the work and begin functioning prior to the work are:
● The necessary information for the work
● The willingness, determination and will power to do the work
● The will power to receive and understand parts of the work
In kinds of work that are created by free will, the dominance of the
character upon positive and negative poles and the quality and
characteristics are also important, for they manage the internal
factors.
The factors mentioned above are related to these four issues:
a) The information and experience about the work
b) The eagerness, reluctance, force or emergency to do the work
c) The quality of managing the factors and internal phenomena concerning
the work
d) The ideological viewpoints concerning the work
Many kinds of work - mental and physical - have been carried out by
means of ideological motives throughout history.
The internal factors that are simultaneous with the work are using
mental and muscular energy, continuous awareness about doing the work
and readiness to prevent inhibiting factors.
Some of the mental and spiritual phenomena that occur subsequent to the
work are: new experiences, the joy of having completed the work, or the
feeling of sadness or frustration of having done something we are forced
to do, or we do reluctantly.
2- The external aspect: Man's muscular movement in order to carry out
the work.
3- The aspect of picturing work in the material: Here, by picturing we
mean the various shapes and qualities that materialize upon the
materials used as a result of the work, and a product is made.
The Relationship between Work and Human Life
--------------------------------------------
As we know, in order to gain complete knowledge about a phenomenon, we
must study it in relation to all other phenomena it pertains to. For
instance, if we want to study a tree leaf, we usually remove a green
leaf from a tree and study it in the lab by means of sophisticated
equipment. In such research, we are considering the general leaf
separate from the branch, tree, water, the sun rays and the material it
gets from the tree. Such a study will be incomplete, for the leaf we are
studying has no relation with them.
Likewise, when studying human work and activities, again we must
identify all affairs and issues related to work, especially man's own
life, which has the most fundamental relationship with work. Work, in
return, is the most significant factor in man's development. Throughout
various stages of human life, man uses up his energy on mental or
physical work.
Values
------
Various definitions have been presented for value, but the point they
have in common is usefulness; i.e, man makes something useful and gives
it away in return for another useful thing. We do not agree with such a
definition; each kind of value calls for a separate, specific
definition:
1- Usage value: This form of value consists of the most useful materials
that turn into goods by means of work:
This form of value, which changes certain materials into goods by means
of work, involves the usefulness of the materials, due to their physical
andor chemical qualities. With these qualities, the valuable subject
fulfills man's needs and wishes.
This kind of value has three basic aspects:
a) Useful observable facts in materials, like physical or chemical
characteristics.
b) Limited things that have useful qualities. Things like air, sunrays,
water and other plentiful natural objects, though useful and valuable,
do not change into price or value.
c) The human aspect; materials and goods find value with regard to man.
Social leaders should make efforts to separate and distinguish true,
original values from those based on desires, whims and wishes. They
should reinforce what is useful to human life so that greedy
opportunists cannot produce goods that serve only to fulfill man's
desires and wishes.
2- Exchange value involves the price paid in return for work or goods
received. This form of value is created with regard to factors such as
demand, production, competition among producers, financial issues and
other social matters, all of which cause fluctuations in the values of
work and goods.
3- Innately justifying values: This form of value pertains to work
people do in order to account for and justify themselves on their paths
to achieve their individual or social goals. These values can be
categorized into two groups:
a) Mental values - whether scientific, philosophical, artistic or
ideological - that are necessary for adjusting the goals and ideals of
the society, or cause evolutionary progress in the society.
b) Values justifying or accounting for compulsory affairs, such as
education, group management or social activities.
4- Ultra-exchange value such as the value of mental work and activities
done in order to make great human ideals and goals a reality. These
values cannot be assessed with money. Many great endeavors have been
made throughout history with the aim of making human values come true,
without the people making the effort expecting any money in return .
Ownership
---------
The phenomenon called ownership is one of the forms of man's
relationship with objects. It can neither be observed externally nor by
imagination. The most important element in the relationship of ownership
is the free will and authority regarding the thing man owns. In other
words, man must have the right to do as he pleases with his belongings.
Two factors, however, limit man's authority in defining his authority.
First, natural forbiddances, and second, legal limitations, like man is
not allowed to use weapons in order to destroy others.
Ownership is one of the phenomena that is not confined to fulfill man's
needs. In other words, man does not regard it as merely a
requirement-fulfilling phenomenon; it is one that can cast doubt and
disorder in many principles. Sometimes ownership makes man's authority
and free will regarding an object become absolute, and even eliminate
others' authority and free will. Such affairs occur by means of the law.
Nowadays, legal powers take some people's authority away and exploit
them.
The Natural Roots of Ownership
------------------------------
Personal ownership arises out of four main roots:
1- Instinctive roots: Some thinkers believe that ownership is deeply
rooted in man's instincts, and cannot be removed. In other words, man
has “the tendency to gain power, authority and free will in progressing
the life he desires or get total authority to gain the things or
material he wants.”
2- Purely mental roots: Some people believe that man's possession over
his belongings is a side-effect of his possession over himself. When man
owns something, he feels it is part of him, and those who believe man's
mental possession over things is equal to his possession over himself
are making a big mistake, for on one hand, possession of external
objects is something conventional which occurs based on social credit,
and on the
other hand, any observable or non-observable thing man possesses can be
transferred to others, whereas the human character cannot be transacted
or traded.
The thing in common between man's possession over himself and over
things is that since both take place due to God's will, God has set
certain instructions for making use of things and ourselves. For
example, with regard to his possession over himself, man must adjust his
own character and avoid ruining it. Man must not oppose his own or
others' characters; he must not disturb others' personalities. About
possession of things, man has been ordered not to become enslaved by the
things he possesses.
3- Purely natural roots: Some believe that man has to gain certain
things and materials and use them in order to survive. He cannot use
natural materials without making effort, and when he uses his physical
or mental strength to do so, he feels he owns the materials.
4- The necessity for realizing and identifying situations: If man does
not have ownership over things, his relationship with them will wither,
and no individual's standing in the society can be strengthened.
Possession is an instinctive issue, and by instinct here we mean man's
tendency toward gaining authority and freedom in order to achieve an
intelligible life. Man innately feels that he has to make effort and
endeavor in order to survive and go on with his life. Thus, the first
and third of the reasons mentioned above are in fact the same, and the
fourth is nullified.
In fact, the tendency to gain power and authority and the freedom to use
it is deeply rooted in man. Many thinkers have also emphasized on this
point; however, they have not realized that such a tendency is
two-sided - there is no certain, clear-cut factor in man that can create
the same effect in all circumstances. In fact, this tendency pertains to
man himself. In other words, the effects this tendency can make are
related to the two contradictory selves (egos) in man - the natural and
the ideal.
If a desired life is regarded as solely being accounted for according to
the “natural self,” the above mentioned tendency will be moving toward
gaining better possessions for the purely natural life. Not only
possession, but even thought, reasoning and all of man's external and
internal activities will be at the service of the natural ego.
When making use of power and authority in regard to natural life, man
faces two kinds of activities:
a) activities that pertain only to man - personal activities. One may
use his power and free will to become a good poet, for example. He will
drown in his own thoughts and imaginations, and his poetry will only
serve to satisfy his natural ego.
b) kind of activities pertains to others; they may even endanger the
life or freedom of other people, like using power and authority in order
to dominate others.
If man's life becomes gaining possession of everything - in other words,
if the ideal of his natural self is set as expanding his belongings - he
will endanger others' lives and freedom. If man has an ideal self (ego),
however, all of his external or internal activities will become the
means instead of being the end; for such a man, ownership will only
serve as the means to
gain his requirements in life. Those who focus upon ownership as the
goal are not owners; in fact, they are enslaved by what they possess.
The Limitation of Personal Ownership
------------------------------------
There are three reasons why personal ownership is limited:
1- God has created whatever there is in the universe for man, and has
also instructed man how to make use of it. Of course, what God has
created belongs to all people, and man can learn to use it only through
work and effort. And since each individual's work and effort is limited,
man's possession will also be limited.
2- Not only does the principle of work and endeavor prove that man's
ownership is limited, even if man or a society succeeds in possessing
all the usable material in the world, it would require some people to
stay alive and some others to die, or the lives of some to be at the
mercy of few others, which leaves no choice but to accept limited
ownership.
3- Religious commands ordering man not to disturb others' lives, avoid
co emption or being usurious, prohibit the production or trade of
harmful goods, prohibit monopoly, avoid making a corner in gold or
silver, and control the society's economy.
Also, the Qur’an tells us to safeguard values from absolute destruction,
whether regarding work or goods; this again shows that possession is
limited.
<p dir="rtl">
و لا تبخسوا الناس اشيائهم
</p>
***“Do not decrease the value people's work really has.” (11:85, 7:85,
26:83)***
Unity among People
------------------
Unity among mankind is one of the most significant issues of the
humanities and the arts. If these two fields do not take any action on
this issue, they will not have done anything for mankind at all. On the
other hand, Thomas Hobbes has said, Men are like wolves to each other.”
He saw no unity among human beings at all. But knowledge of man's
various aspects and positive and negative talents and potentials makes
the humanities and the arts to “make effort toward creating the sacred
feeling of intelligible unity and harmony among human beings.
One of the duties of various arts, especially literature in the form of
prose and poetry, is paving the path toward achieving human unity. Man
has attempted to reach unity among mankind by means of religion and
reason; now it is the arts' turn to take serious action, and use its
various forms in order to motivate people's feelings on the path toward
creating unity between human beings.
If unity is to be achieved, we must first make people realize the
necessity of unity among people. Artists can use their works to serve
this cause, and show how people are affected by each other's joys or
sorrows, thus proving the need for harmony and mutual sympathy. Artists
can show others the heartfelt tranquility the people who help others
relieve their pains and suffering feel. They can also motivate people
toward taking steps toward
elevating each other by showing the relation between actions and
reactions in their works. As Jalal-addin Muhammad Molawi (Rumi) says:
<p dir="rtl">
اين جهان کوه است و فعــل ما ندا ســوی مـا آيد نــداها را صـــدا
</p>
*(This world is like a mountain, and our actions like the shouting
toward that mountain; they are echoed back to us.)*
Not even a single step can be taken toward making people realize the
necessity of unity among people - and then creating that unity - unless
the anti-human thoughts of figures like Machiavelli, Hobbes, Nietzsche
and Freud are disregarded and nullified.
The Various Forms of Unity
--------------------------
There different kinds of unity are:
1- Numerical Unity: Such a form of unity cannot acceptably be applied to
human beings, for man is far beyond a numerical unit.
2- Natural Unity: There are two forms of natural unity:
a) Human beings' natural characteristics: All human beings have forces
and aspects such as reason, intelligence, imagination and abstraction,
which provide a form of unity among them with regard to these natural
characteristics. But this kind of unity is incapable of bringing people
together, for throughout history, people have been aware of these points
they have in common, but they have still shown a great deal of brutal
atrocities toward each other.
b) Unity in issues such as race, natural environments, social life and
history: This form of unity is more effective than the former in
attracting people toward unity. For example, ethnic unity has been able
to bring people from the same ethnic background closer to each other,
sometimes even making them ready to fight other races for their lives.
Most of such forms of unity are abused, and they are often put to use
destructively.
3- Self-preservation: Sometimes people unite in order to save their own
lives or get rid of disturbances. This form of harmony is merely due to
fear of harm, and is thus unstable. It has no innate value, for this
harmony lies in the need to escape harm and gain advantage, like when
conquerors attack.
4- The Factor that Saturates Emotions: Some people see the origin of
unity lying in seeing the pains of others, and feeling sympathy for
them. Such a feeling, if raw and undeveloped, will wane when we see the
atrocities some other people commit; if the feeling arises out of
supreme understanding and pure reason and intelligence, however, it will
prove extremely valuable.
5- The Law of Actions and Reactions: The fact that any action leads to a
reaction can be a factor helping to arouse unity among human beings.
Many Iranian poets have put this concept under emphasis in their works.
As Nasser Khusro says:
<p dir="rtl">
عيسی به رهی ديد يکی کشتـه فتــاده حيران شد و بگرفت به دندان سر انگشت
</p>
<p dir="rtl">
گفتا که که را کشتی؟ تا کشته شدی زار تا باز کجا کشتـه شود آن که تو را
کشت
</p>
<p dir="rtl">
انگشت مکن رنجه به درکوفتــن کس تا کـس نکند رنجه به درکوفتنت مشت
</p>
*(One day, Jesus saw a dead man lying on the ground. Shocked, Jesus bit
his finger and said, 'who did you kill that made someone else kill you,
and now I wonder how your killer will be killed. Indeed, never raise a
finger to hurt someone, or someone else will raise his fist to hurt you
in return.')*
The Factors Influencing Unity in Intelligible Life
The five factors mentioned above provide the preliminary background
necessary for gaining knowledge and realizing the necessity of unity
among human beings. Achieving unity calls for higher motives so that
human beings feel united in their intelligible life. These factors are:
1- Sound sense and reason: If common sense and reason are free of
short-mindedness and advantage-seeking, human beings can realize how
valuable unity, equality and brotherhood among them can be.
2- Morals: High human moral ethics can also help people reach unity and
brotherhood.
3- The delicate feeling that is beyond obligation: There is very
delicate feeling inside pure human beings which is far superior to moral
factors and makes man see human life from a much more elevated
viewpoint, and consider respecting it as totally necessary. Iranian
literature shows this feeling in various ways. As the renowned Iranian
poet, Sa'adi says,
<p dir="rtl">
به جان زنده دلان سعديا که ملک وجود نيــرزد آن که دلی را ز خود
بيــازاری
</p>
(I swear, O Sa'adi, on the lives of all the pure-hearted, that this
worldly life is not worth you hurting others.)
4- Religion: When following religion, man has the attraction toward
divine evolution, and has an extreme feeling of unity for his fellow
human beings. With religion, man's inside is purified of all immoral, so
he can understand other human beings' joys and sorrows, and achieve
greater human unity. As religion sees it, there are twelve different
forms of unity among people that can help build up extreme unity among
them. They are:
a) Unity and equality in relationship with the Creator: All human beings
have been created by one God.(The Greeks, 30:40)
b) Unity in God's will which created man to worship Him. (The
Scatterers, 51:56)
c) Unity and equality among people in the fact that they all deserve to
have divinity breathed into them. (Muhammad, 32:9)
d) Unity in the material man is created of: all human beings are created
out of earth. (El-Hijr, 15:26)
e) Unity in the origin of creation: All human beings come from the same
ancestors. (Women, 4:1)
f) Unity in innate greatness and dignity: God has created human beings
in a way that they all have innate dignity. (The Night Journey, 17:70)
g) Unity among people in gaining merit-based dignity: All human beings
are capable of gaining great dignity by means of piety.(The Apartments,
49:13)
h) Unity in human characteristics and qualities: All of mankind has
reason, intelligence, conscience, etc. (The Resurrection, 75:2)
i) Unity in natural aims and goals: The goals people have in their lives
either pertain to their natural lives or their desired ones; the axis to
both is self-preservation.
j) Unity in the basics of divine religions: All divine religions are
based upon man's innate tendency and disposition toward God, and have
many points in common.
k) Unity in having the seeds of knowledge and mysticism inside. (The
Cow, 2:31)
l) Unity in setting natural, descriptive or any other laws needed for
adjusting man's natural or mental life. If man is to achieve unity, he
must consider the grounds that can make unity a reality. The principles
and facts common between man and the universe mentioned above are of the
most important of the grounds needed.
Furthermore, three other significant points must also be kept in mind:
● We must increase people's knowledge to such an extent that they
understand what supreme unity means. Unfortunately, only the most
elementary of steps have been taken so far in order to achieve supreme
unity among human souls.
● People must be taught that although man has the potential to make this
unity come true deep in his innate, activating and flourishing it calls
for freeing oneself from the natural self and entering intelligible
life, which is feasible through gaining divine manners and morals.
● Arts contribute to making this come true. Poetry can motivate people.
If responsible artists make endeavors toward motivating unity, not only
will art itself become more valuable, but also social and political
evolution will occur.
Differences among People
------------------------
The differences and disagreements people have can be categorized into
two main groups:
1- Natural differences and disagreements
2- Artificial differences and disagreements
There are three kinds of natural differences and disagreements:
a) Natural differences between people in understanding and realizing
realities: For example, people may make errors in using their senses and
misunderstand realities. Such disagreements lie in differences in their
sensory and mental structures. Hereditary factors can also lead to such
differences.
b) Differences and disagreements due to environmental conditions and
man's approach to them.
c) Differences and disagreements due to scientific knowledge: People
differ in their acquisition of knowledge and experiences.
The three forms of differences and disagreements mentioned above are
natural and necessary, cause no disturbance for man's individual or
social life. If considered in a logical and calculated fashion, they can
help human evolution and development; otherwise, however, they will lead
to thoughts like those of Epicurus, Machiavelli, Thomas Hobbes and
Nietzsche, which conflict with intelligible human life.
Artificial differences and disagreements can be categorized as:
a) Differences and disagreements due to lack of control on
self-opportunism and advantage-seeking: Although advantage-seeking has
natural roots, it can endanger human life if it gets out of hand. If
people do not harness and control their desires and wishes, there will
be a harmful, artificial difference or disagreement.
b) Differences and disagreements due to social classifications: Ethnic
and national differences among peoples are examples of this. Social
leaders can make use of these differences in the most atrocious of ways,
or in the best and most educating fashion, too.
If man succeeds in correctly developing and educating his own mind and
soul, he will see disputes as owing to merely seeing different colors
and shapes instead of seeing the real truth. Some thinkers, including
Jalal-addin Muhammad Molawi believe that all disputes and disagreements
are due to man's own stubbornness and spiritual deviation from the right
path:
<p dir="rtl">
در معـــانی اختـــلاف و در صـور روز و شب بين خار و گل سنگ و گهر
</p>
<p dir="rtl">
تا ز زهـــر و از شکــر درنگـذری کــی تو از گلــزار وحدت بـو بری
</p>
<p dir="rtl">
وحدت اندر وحدت است اين مثنوی از سمک رو تـا سماک ای معنــوی
</p>
*(Differences occur both in meanings and in appearances. For instance,
consider the how day differs from night, or how worthless pebbles are
different from gems and diamonds. You will never be able to appreciate
the unity existent in the universe unless you step beyond apparent
things like bitter and sweet… the Mathnavi you see is filled with unity
and harmony - it bonds truths - O mystic man, with this book you can
rise from the earth and reach the heavens.)*
We cannot not agree with Jalal-addin Muhammad Molawi here, for on one
hand, the sense of unity-seeking is one of the most important ideals of
human life; it is this sense that has led to the birth of many
philosophical schools of thought, and many philosophers have claimed to
have considered unity of thought in their spiritual basics.
On the other hand, there is a great difference between the two facts
“all disputes among human beings are baseless and there is unity above
all schools of thought” and “from natural opposites we can extract a
greater unit.”
On the whole, there are two forms of differences and disagreements that
must be taken into consideration;
1- Differences on thoughts and ideas: If logically used, these disputes
can prove quite useful.
2- Differences arising from one's interpretation of the truth about the
universe: This is where various schools of thought and scholars differ.
The Principle of the Mutual Necessity of Unity and Diversity
There is a principle in the humanities stating that first, no theorem
can achieve total agreement without there being some points of
disagreement on it. For instance, the issue that human life has two
phenomena called joy and pain is generally agreed upon among thinkers;
however, there is a great deal of debate upon what joy and pleasure is,
what pain and suffering is, and what should be done when these two
collide. Secondly, there will be no
disagreement on an issue unless there are basics about it which are
agreeable. For example, although there is dispute on whether members of
the society have individual freedom or not, it is agreed that man has to
live socially, and likes freedom.
This is called the principle of mutual necessity between unity and
disagreement. Let us elaborate on it via the following points:
1- Man is not an individual; humanity consists of many people, who do
not think the same about all issues.
2- The universe has numerous evolving creatures, and each human being
can only reach a certain level of the truth about them.
3- No human being can achieve absolute knowledge of man and the
universe. The universe always spreads a compound scene of light and dark
before man's mind.
4- What develops human societies is the open path of identification and
knowledge, which is feasible through great minds.
If everything were understandable immediately for all human beings,
human life would be destroyed in its very early stages, for there would
be no more contradicting ideas that could lead to human effort, and
activate man's development. As Jalal-addin Muhammad Molawi says,
<p dir="rtl">
قبلـــة جان را چو پنهـان کردهانــد هر کســی رو جانبــــی آوردهانــد
</p>
*(Since the main path and direction toward the truth - God - is hidden,
people have taken various paths.)*
5- And if the 'focus of life,' i.e. the absolute goal, were revealed to
all, or if everyone had unified knowledge in order to choose their tools
and means of reaching the goal, there would be no effort or endeavor
toward the goal at all.
6- Nature is related with the supernatural. If we are to discover the
former, we should unveil the latter. Only few can truly know nature, for
its total discovery needs supernatural understanding.
Dispute among experts is one of the most common issues in knowledge.
Diverse ideas and beliefs have always existed, and have even led to the
development and evolution of thoughts. As far as such disputes do not
cause any harm to the “basic common principles of belief,” they are
quite necessary. The interpretation of some of the main and minor
principles of the religion has in most cases added to the profundity of
Islamic philosophical and scholastic studies. Generally, these disputes
can be categorized into two groups:
1- Intelligible disputes: These disputes originate from the information
relevant to various subjects, potentials and different perceptions, like
disagreements in perceiving facts about the universe, which leads to
various scientific and philosophical viewpoints. This is why great
scholars of Islam, both Shiite and Sunnites, have produced treatises and
criticisms of each other’s' works. Mulla Ali Qushji, for instance, has
added side notes to Khajeh Nasir's book Tajreed-ol-e'teqad, and Mulla
Mohsen Fayz has done the same for Qazali's Ehya-ol-uloomIntelligible
disputes can help develop both theoretical and practical domains.
2- Unintelligible disputes: These disputes arise out of deviational,
illegal factors, like disputes owing to desires and lusts. Throughout
history, some people pretending to be advocates of freedom of thought -
who were, in fact, greedy for fame or power - have presented ideas that
have led to unintelligible disputes. Unintelligible disputes are passive
and superficial, for they are based upon desires for fame or power.
The Various Forms of Unity
--------------------------
Several forms of unity can exist in the framework of religion:
1- Absolute unity: Agreement concerning all knowledge, religious decrees
and beliefs. Taking into consideration the freedom of thought and
reasoning and the diversity in people's understanding potentials, such a
unity is impossible. The disputes thinkers have in their ideas and
information on various issues, and also their differences in
intelligence, memory and comprehension contradict the concept of
absolute unity.
2- Unity caused by external elements: This form of unity is a result of
factors other than the truth and context of religion. Usually, when
destructive, dangerous factors arise, the contradictions and disputes
between various sects and religions are ignored, and unity somewhat
forms between them. Such a unity is caused by compulsory factors other
than religion, which if removed, the unity will also vanish.
3- Intelligible unity: Considering the freedom of thought and reasoning
in implementing and choosing the reasons for the elements of religion,
this form of unity is acceptable. It can be defined as: placing the
general context of Abraham's religion for all societies to believe in,
and removing personal, theoretical beliefs, local cultures and the
characteristics and theories about the components of the religion which
relate to reasoning and individual or group brainstorming.
This is the kind of unity great scholars of both groups of religious
scholars have emphasized, not the one caused by external elements, which
is quite baseless. In order to achieve intelligible unity, it is
essential to make the viewpoints of Islamic thinkers vaster, and free
them of the framework of illogical prejudices. Great thinkers like
Farabi, Avicenna, Ibn Rushd, Ibn Muskuyeh, Ibn Heisam, Zachariah Razi,
Jalal-addin Muhammad Molawi (Rumi), Mirdamad and Mollasadra have had
such vastness of point of views, and that is why they never fell for
destructive disturbances and contradictions.
Social Order and Cooperation
----------------------------
Any sound mind and aware conscience would approve of the necessity of
order and discipline in individual and social life. Societies that lack
an original culture, but follow order and discipline in various
economic, political, legal and cultural aspects, enjoy more luxury and
progress than societies that do not have order and discipline, even
though they may have an original culture and economic, political, legal
and cultural laws and principles.
The problems that arise in the absence of social order and discipline
are:
a) No individual or group will know where they stand socially.
b) Everyone would seek their own benefit, considering others as both the
means and the end.
c) Nobody would pay any attention to what is to the society's benefit.
d) People would not be content with their legal rights.
e) In such societies, human conscience heads for doom.
The Principles of Social Order and Cooperation
----------------------------------------------
Religious, moral, political, and legal basics are the most important
motives for social participation. Pioneer culture has put a great deal
of emphasis upon people's social harmony and participation. The reasons
we find for this in the Qur’an are:
1- Verses in the Qur’an that invite people to socially cooperate and
create the proper grounds for social life, like (The Table, 5:2).
2- Verses that condemn disharmony and lack of unity, and emphasize the
importance of collaboration and cooperation, like (The House of Imran,
3:103).
3- There are also many hadith on the necessity and effect of social
participation.
<p dir="rtl">
يدالله مع الجماعة
</p>
*“God's hand is with the public unity.”*
4- Other hadith show the importance of the community.
<p dir="rtl">
من اصبح و لم يهتم بامور المسلمين فليس بمسلم
</p>
*“He who wakes up in the morning without caring about the lives of other
Muslims is not a Muslim.”*
Moral ethics are another basic factor in social harmony and
participation. Moral ethics makes people observe social law and order
for the sake of human values rather than force. If these two points are
taken into consideration, moral virtues will be regarded as pillars of
social harmony:
1- Knowledge of how great man is, and how valuable it is to help solve
people's problems.
2- The will and determination to do proper deeds that the conscience
also approves of.
If people's cooperation and participation does not aim to make social
benefits come true, eliminate factors disturbing social life which is
based upon religion and divine conscience, it will not be different from
the cooperation seen in ants and bees.
Without making effort toward cooperation and physically and mentally
endeavoring to adjust a social life based upon religion and divine
conscience, it will not be considered valuable, even if it does produce
outstanding results in providing advantages and benefits for the
society; bees and ants also cooperate and work hard together, but that
arises out of their specifically compulsory animal instinct, and has no
value.
Power and Right
---------------
Right: Generally all necessary or useful realities that have innate or
clear poles are called right. The realities about the world outside and
the essential rules governing it are part of rights. So are all values
useful to man, like justice, freedom, development, the sense of
responsibility and social laws.
Anything that causes corruption or destruction, on the other hand, is
the opposite of righteousness. Each right has two poles:
1- The obvious, clear pole: Realities that are necessary and useful to
man. They really exist, regardless of how man makes contact with them,
like the realities and facts about the universe. The obvious, clear pole
includes all the laws and properness man needs for an intelligible life.
2- The innate pole: By “innate” here we mean man's existence against
inhuman realities; in other words, we are referring to the human side of
righteousness. This pole must always accompany the former one.
Studying the verses in the Qur’an can guide us to these conclusions on
righteousness:
● The foundation of the universe is right. Righteousness depends upon
God's will, which no one can ever destroy. If man, in a balanced, sound
state of mind, understands the meaning of righteousness, he will have
respect for it.
● Rights are stable and sustainable; evil and wrong, however, fade away
like foam on water.
● Righteousness is the cornerstone of the universe, and using it calls
for human effort; man must reach evolution based upon righteous
principles. By means of intelligence and reason, conscience, prophets
and men of wisdom, God shows us what the right is.
● Tendency toward righteousness and acting thus requires upbringing and
education. Righteousness cannot be provided to people automatically;
human beings should consciously, voluntarily aim to follow righteousness
as their evolutionary goal.
● Man should not rush for achieving righteousness. They should not
imagine that the right is at all times achievable.
● Man must realize that any kind of effort aiming to uphold and bring
about righteousness is a part of the right, and the greater the effort
made is, the more man makes progress in the direction of righteousness.
● Man needs to make serious effort if he is to reach righteousness and
perform actions based on what is right; he must realize that the
right-based realities of the universe do not obey we human beings' lusts
and desires. Righteousness, the factor that promotes human evolution,
needs action and effort on man's behalf.
● God's will tends toward the wrong and evil being destroyed and the
right prevailing successfully. The lust-infatuated cannot defeat
righteousness.
Power: Power is the factor causing motion and change in various forms.
Power is one of the realities of the universe which influences man and
the universe both, for power is the natural changer and acting factor
effecting man and the universe in various forms. Thus, power is an
example of righteousness.
Now the question comes up: power or righteousness - which is the
dominant conqueror? There are two theories in response:
1- Some people believe that righteousness will always succeed, and the
powerful will never be able to defeat it. They believe that man's
intelligible
life has appropriate and valuable elements that are righteous.
Responsibility, freedom and moderating selfishness are real, and they
are right.
2- Some others believe that power is the winner; righteousness, they
believe, is a mental ideal that cannot withstand power. History also
provides many cases in which power overcomes righteousness.
Righteousness never confronts power at all. Power is itself one of the
rights that motivate the universe and mankind. The question whether
power will overcome or righteousness is a trivial, illogical one.
Righteousness shows how false, improper and worthless the wrong is
rather than conflict with power which is right itself. When man gains
power, he can change it into a constructive factor or abuse it and use
it destructively. Men's deviation from righteousness makes power - a
factor necessary for development and construction - be misused.
Power is the unconscious reality that is - from the aspect that it is
the basic cause for all changes and movements - an example of
righteousness; thus, it neither wins nor loses, for when power
unconsciously destroys the resistance of a creature, it does not feel
joy by hearing the creature fall and break. It does not regard this as a
victory. It is man, however, who abuses power; man even treats his own
mere existence as a plaything, too.
The most lethal factor endangering power is the feeling of absolute,
independent power. Accompanied with imagination and induction, this
feeling prevents power from gaining a logical, accurate calculation, and
eventually brings about the powerful person's demise. Absolute power
leads to inflatedness and rebelling against realities. This is why it is
the feeling of absolute power and all its imaginations that the Qur’an
condemns, not power itself. ( 96:6)
The power-greedy, who lust for controlling people's lives, had better
realize that they are in fact drinking a cup of poison. Those who become
playthings in the hands of the powerful and oppress the weak are no
different, either. Losing one's right to live at the hands of the
powerful has been, however, one of the most painful phenomena history
has witnessed. The powerful have always tended to create such a corrupt
state of minds in those they have crushed that these poor downtrodden
souls regard them as saviors.
In fact, those people who surrender to the powerful have downtrodden
their own character; no power can defeat man unless he himself breaks
his own character first. The human character is a forbidden zone into
which only God and man himself can find a way into; no one else is able
to enter it.
As we have already mentioned, righteousness is far superior to success
or failure. Power is a reality that may fall in the hands of
righteousness or selfish people. Now let us see what will happen in
either case:
Power in the hands of selfish man
---------------------------------
If power falls into the hands of those who have been overwhelmed by
their selfishness, the consequences are:
1- Since the identity of the power itself is unaware and aimless, its
attraction will destroy the power-greedy.
2- Those intoxicated with power lose all their freedom and free will,
for power is the motive that, by means of its false promises of absolute
freedom, presses every element of the character of the power-greedy
person inside his aimless, ignorant nature, and every change he
undergoes will be merely going though one fatalistic phase into another.
3- The power-greedy defy others in order to establish their own
existence.
4- The power-greedy attempt to make everyone else their slaves in order
to saturate their authoritarian desires; if they do not find anyone to
do so, they will feel despair.
5- When the power-greedy face each other, they neutralize their
potentials and add to the darkness of their beings instead of becoming
aware of their hidden potentials and being guided to the path of
intelligible life.
6- The power-greedy are too selfish to take unexpected, uncalculated
events into consideration, and that is why they are destroyed, just like
Napoleon was destroyed by a black cloud at Waterloo.
7- The greed for power is not sweet enough to compensate for the
bitterness of its demise. When one drowns into the attraction of power,
all of his logical calculations disappear, so the power he acquires will
be no more than an inflated natural self. The joys of the power-greedy
are not original or pure; when power gradually falls, a tremendous
bitterness will engulf him.
When power arises, it pours baseless hallucinations and illusions into
the personality of the power-greedy person, and inflates it; when power
goes, all the elements of his character are awaken, and they make him
see how futile power was. This is why we can say that there is no fall
as painful in this world as the fall of the powerful. The mental
suffering they undergo when their power disappears is truly
unimaginable.
8- The power-greedy consider power - an unconscious picture of
unconscious phenomena and facts - as the authentic image of awareness,
freedom and law. They see the criteria for any good or evil in power.
9- The power-greedy ignore the relativity of power. They do not realize
that power may be influenced by time or unexpected events.
10- The power-greedy are slaves of power; thus, they always think that
they can preserve their power with awareness and will.
Power in developed man
----------------------
If power and authority is given to human beings who have overcome their
selfishness, the consequences will be:
1- These human beings know that they should increase their awareness.
They feel it necessary to have more knowledge and alertness if they want
to fulfill their responsibilities flawlessly.
2- Though having power and authority, developed characters always feel
themselves incapable, for they know that God is the absolute owner of
life, so even the slightest mistake of theirs is considered by them as
an unforgivable sin.
3- Since developed man has self-control, he seldom falls under the
compulsory pressures of authority.
4- If developed man makes a mistake using his authority, he will feel
deep sorrow and repentance.
5- Since developed man takes intellectual and conscientious calculations
into consideration in order to use his power and authority, he has no
fear of unexpected events. His high aim helps him avoid misusing his
power. Such a human being sees power as a means to create harmony, order
and an intelligible life. He knows well that power is not so absolute as
to keep him safe from fall or doom.
6- If such a man loses his power, he will not feel sorry or upset at
all.
|
C++ | UTF-8 | 7,584 | 3.140625 | 3 | [] | no_license | #include "ListBase.h"
#include "Product.h"
#include <queue>
#ifndef PRODUCTLISTARRAY_H
#define PRODUCTLISTARRAY_H
using namespace std;
const int SIZE=100;
//list array template class
template <class T>
class ProductListArray: public ListBase<T>
{
private:
T* item;
int ArraySize;
int** Indexes;
ComparatorProduct<T> COM;
int searchstate;
public:
ProductListArray()
{
item = new T[SIZE];
ArraySize=SIZE;
_size=0;
for(int i=0; i<ArraySize; i++)
{
item[i]=NULL;
}
Indexes=new int*[26];
for(int i=0;i<26;i++)
Indexes[i]=NULL;
searchstate=3;
//1 for Category by default
//2 for Name
//3 for Manufacturer
}
~ProductListArray()
{
delete [] item;
}
void sortByWorth(){}
void setState(int x){searchstate=x;}
int getState(){return searchstate;}
int LetterCheck(char letter,bool checking)
{
switch(letter)
{
case 'A':
if((Indexes[0]==NULL && checking==false) || (Indexes[0]!=NULL && checking==true))
return 0;
break;
case 'B':
if((Indexes[1]==NULL && checking==false) || (Indexes[1]!=NULL && checking==true))
return 1;
break;
case 'C':
if((Indexes[2]==NULL && checking==false) || (Indexes[2]!=NULL && checking==true))
return 2;
break;
case 'D':
if((Indexes[3]==NULL && checking==false) || (Indexes[3]!=NULL && checking==true))
return 3;
break;
case 'E':
if((Indexes[4]==NULL && checking==false) || (Indexes[4]!=NULL && checking==true))
return 4;
break;
case 'F':
if((Indexes[5]==NULL && checking==false) || (Indexes[5]!=NULL && checking==true))
return 5;
break;
case 'G':
if((Indexes[6]==NULL && checking==false) || (Indexes[6]!=NULL && checking==true))
return 6;
break;
case 'H':
if((Indexes[7]==NULL && checking==false) || (Indexes[7]!=NULL && checking==true))
return 7;
break;
case 'I':
if((Indexes[8]==NULL && checking==false) || (Indexes[8]!=NULL && checking==true))
return 8;
break;
case 'J':
if((Indexes[9]==NULL && checking==false) || (Indexes[9]!=NULL && checking==true))
return 9;
break;
case 'K':
if((Indexes[10]==NULL && checking==false) || (Indexes[10]!=NULL && checking==true))
return 10;
break;
case 'L':
if((Indexes[11]==NULL && checking==false) || (Indexes[11]!=NULL && checking==true))
return 11;
break;
case 'M':
if((Indexes[12]==NULL && checking==false) || (Indexes[12]!=NULL && checking==true))
return 12;
break;
case 'N':
if((Indexes[13]==NULL && checking==false) || (Indexes[13]!=NULL && checking==true))
return 13;
break;
case 'O':
if((Indexes[14]==NULL && checking==false) || (Indexes[14]!=NULL && checking==true))
return 14;
break;
case 'P':
if((Indexes[15]==NULL && checking==false) || (Indexes[15]!=NULL && checking==true))
return 15;
break;
case 'Q':
if((Indexes[16]==NULL && checking==false) || (Indexes[16]!=NULL && checking==true))
return 16;
break;
case 'R':
if((Indexes[17]==NULL && checking==false) || (Indexes[17]!=NULL && checking==true))
return 17;
break;
case 'S':
if((Indexes[18]==NULL && checking==false) || (Indexes[18]!=NULL && checking==true))
return 18;
break;
case 'T':
if((Indexes[19]==NULL && checking==false) || (Indexes[19]!=NULL && checking==true))
return 19;
break;
case 'U':
if((Indexes[20]==NULL && checking==false) || (Indexes[20]!=NULL && checking==true))
return 20;
break;
case 'V':
if((Indexes[21]==NULL && checking==false) || (Indexes[21]!=NULL && checking==true))
return 21;
break;
case 'W':
if((Indexes[22]==NULL && checking==false) || (Indexes[22]!=NULL && checking==true))
return 22;
break;
case 'X':
if((Indexes[23]==NULL && checking==false) || (Indexes[23]!=NULL && checking==true))
return 23;
break;
case 'Y':
if((Indexes[24]==NULL && checking==false) || (Indexes[24]!=NULL && checking==true))
return 24;
break;
case 'Z':
if((Indexes[25]==NULL && checking==false) || (Indexes[25]!=NULL && checking==true))
return 25;
break;
default:
break;
}
return -1;//false value
}
bool insert(int index, T& newItem)//insert at index
{
if(full())//if full ++
{
increaseSize();
}
if(index <= _size)//0 -> n-1
{
for(int i=_size;i>=index;i--)
{
item[i]=item[i-1];
}
item[index]= newItem;
_size++;
return true;
}
else
return false;//out of array scope
}
bool remove(int index)//remove at position x. check if item being removed is an indexer
{
if(index < _size)
{
delete item[index];//delete what the pointer points to
for(int i=index;i<_size-1;i++)//move the rest forward by 1.
item[i]=item[i+1];
item[_size]=NULL;//to prevent replication of data
_size--;
return true;
}
else
return false;//out of array scope
}
bool retrieve(int index,T& dataItem)
{
if(index < _size)
{
dataItem = item[index];//assign dataitem to current
return true;
}
else
return false;//out of array scope
//not found
}
bool increaseSize()//increase size of array by 1
{
int newSize=ArraySize+SIZE;//increase int size
T* temp=item;//new container
item=new T[newSize];
for(int i=0;i<ArraySize;i++)//for whole array
item[i]=temp[i];
for(int i=ArraySize;i<newSize;i++)//for whole loop
item[i]=NULL;
ArraySize=newSize;//size = new size
return true;
}
bool full()//check if it is full
{
return (_size==ArraySize);
}
T operator[](int index)//overload
{
return item[index];
}
int AccessIndex(char test)
{
int xx= LetterCheck(test,true);
int xxx=*Indexes[xx];
return xxx;
}
void mergeIndexer()
{
mergeSort(0,_size-1);
for(int i=0;i<_size;i++)
{
int ind=LetterCheck(COM.FirstLetter(item[i],searchstate),false);
if(ind!=-1)
{
Indexes[ind]=new int(i);//Set index of first item
cout<<"Index of "<<COM.FirstLetter(item[i],searchstate)<<" set to "<<*Indexes[ind]<<endl;
}
}
}
void mergeSort(int low,int high)
{
if (low < high) {
int mid = (low+high)/2;
mergeSort(low, mid);
mergeSort(mid+1, high);
merge(item, low, mid, high);
}
}
void merge( T a[], int low, int mid, int high )
{
int n = high-low+1;
T* b = new T[n];
int left = low, right = mid+1, bIdx = 0;
while ( left <= mid && right <= high) {
switch(searchstate)
{
case 1:{
//cout<<"called"<<endl;
if(COM.Compare2(a[left],a[right]))
b[bIdx++] = a[left++];
else
b[bIdx++] = a[right++]; break;}
case 2:{
if(COM.CompareName(a[left],a[right]))
b[bIdx++] = a[left++];
else
b[bIdx++] = a[right++]; break;}
case 3:{
if(COM.CompareManufac(a[left],a[right]))
b[bIdx++] = a[left++];
else
b[bIdx++] = a[right++]; break;}
default:
break;
//cout<<"fail"<<endl;
}
// cout<<"a"<<endl;
}
// continue from previous slide
while ( left <= mid )
b[bIdx++] = a[left++];
while ( right <= high )
b[bIdx++] = a[right++];
for ( int k = 0; k < n; ++k )
a[low+k] = b[k];
delete[] b;
}
};
#endif |
C++ | UTF-8 | 2,695 | 3.46875 | 3 | [] | no_license | /**
* @file neuron.hpp
* @author Jonathan Haab
* @date Automn, 2017
* @brief class that describe a neuron
*/
#include <iostream>
#include <vector>
#include <cmath>
#include "constants.hpp"
#ifndef NEURON_H
#define NEURON_H
/// State of the neuron : Active or Refractory
enum State {ACTIVE, REFRACTORY, stateSize};
/// Type of the neuron : Excitatory or Inhibitory
enum Type {INHIBITORY, EXCITATORY, typeSize};
class Neuron
{
public :
/** Constructor
* needs a type (INHIBITORY or EXCITATORY) to set the specific J (the amplitude of the EPSP)
* @note the neuron is REFRACTORY by default
* @param type the type of the neuron
*/
Neuron(Type type);
/** update
* @param simStep the time expressed in steps at which the neuron update
* @retval TRUE the neuron spikes
* @retval FALSE the neuron doesn't spike
*/
bool update(double simStep);
/** updateTest
*
* @note only used for unittest to check if the update is well implemented
* @param iExt the current given to the neuron
* @param simStep the time expressed in steps at which the neuron update
* @retval TRUE the neuron spikes
* @retval FALSE the neuron doesn't spike
*/
bool updateTest(double iExt, double simStep);
/** getSpikesTime
* @return spikes the step when a spike occured
*/
std::vector<long> getSpikesTime();
/** getV
* @return v the membrane potential of the neuron
*/
double getV();
/** getJ
* @return J the amplitude of the EPSP (excitatory post synaptic potential)
*/
double getJ();
/** receive
* @param step the step at which the neuron receive an EPSP from an other one
* @param J the amplitude of the EPSP that is received
* @brief put the ESPS received in the ringBuffer that manage the delay of the actual effect of the ESPS
*/
void receive(long step, double J);
private :
State state; //!< State of the neuron : Active or Refractory
Type type; //!< Type of the neuron : Excitatory or Inhibitory
double v; //!< Membrane potential
double J; //!< Amplitude of the EPSP (excitatory post synaptic potential)
std::vector<long> spikes; //!< List of the steps at which the neuron spikes
long localStep; //!< Local clock expressed in steps
std::vector<double> ringBuffer; //!< Buffer in which we stock the EPSP that the neuron received for a certain delay
/** updateState
*
* @param simStep the time given in steps
* @brief manage the switch between the ACTIVE and REFRACTORY state
* if the neurons spikes, it will be REFRACTORY for a certain time
* given by refractoryTime
*/
void updateState(double simStep);
};
#endif
|
Shell | UTF-8 | 2,552 | 3 | 3 | [] | no_license | #!/bin/bash
#
# This script will configure the partially built debian system.
# It is expected to be run as root, in a chroot, using the target
# architecture, after multistrap has been run
root_pwd="root"
user_name="debian"
user_pwd="tmppwd"
hostname="octavo_install"
export DEBIAN_FRONTEND=noninteractive DEBCONF_NONINTERACTIVE_SEEN=true
export LC_ALL=C LANGUAGE=C LANG=C
mount proc -t proc /proc
mount sysfs -t sysfs /sys
dpkg --configure -a
# set root password
passwd root <<EOF
$root_pwd
$root_pwd
EOF
# Set useradd default shell
sed -i 's#SHELL=/bin/sh#SHELL=/bin/bash#g' etc/default/useradd
useradd -G sudo -m -d /home/$user_name $user_name
passwd $user_name <<EOF
$user_pwd
$user_pwd
EOF
dpkg --configure -a
# Update CA certicates for curl
update-ca-certificates -f
c_rehash
# To launch window manager at startup
systemctl enable weston.service
# To launch network manager
systemctl enable systemd-networkd.service
# To launch SSH server
systemctl enable ssh
# To prevent the system from waiting on a network connection at startup
systemctl disable systemd-networkd-wait-online.service
# To prevent the service from starting if requested by another service
systemctl mask systemd-networkd-wait-online.service
# Prevent wifi services without configuration
systemctl disable wpa_supplicant.service
systemctl disable hostapd.service
# Link to vendor FS
ln -sf /vendor/lib/gbm_viv.6.2.4.multi.release.so /usr/lib/arm-linux-gnueabihf/gbm_viv.so
ln -sf /vendor/lib/libEGL.6.2.4.multi.release.so /usr/lib/arm-linux-gnueabihf/libEGL.so.1
ln -sf /usr/lib/arm-linux-gnueabihf/libEGL.so.1 /usr/lib/arm-linux-gnueabihf/libEGL.so
ln -sf /vendor/lib/libGAL.6.2.4.multi.release.so /usr/lib/arm-linux-gnueabihf/libGAL.so
ln -sf /vendor/lib/libGLESv1_CM.6.2.4.multi.release.so /usr/lib/arm-linux-gnueabihf/libGLESv1_CM.so
ln -sf /vendor/lib/libGLESv2.6.2.4.multi.release.so /usr/lib/arm-linux-gnueabihf/libGLESv2.so.2
ln -sf /usr/lib/arm-linux-gnueabihf/libGLESv2.so.2 /usr/lib/arm-linux-gnueabihf/libGLESv2.so
ln -sf /vendor/lib/libGLSLC.6.2.4.multi.release.so /usr/lib/arm-linux-gnueabihf/libGLSLC.so
ln -sf /vendor/lib/libOpenVG.6.2.4.multi.release.so /usr/lib/arm-linux-gnueabihf/libOpenVG.so
ln -sf /vendor/lib/libVSC.6.2.4.multi.release.so /usr/lib/arm-linux-gnueabihf/libVSC.so
ln -sf /vendor/lib/libgbm.6.2.4.multi.release.so /usr/lib/arm-linux-gnueabihf/libgbm.so.1
ln -sf /usr/lib/arm-linux-gnueabihf/libgbm.so.1 /usr/lib/arm-linux-gnueabihf/libgbm.so
# Enable RNDIS
systemctl enable usbotg-config
umount /proc
umount /sys
|
PHP | UTF-8 | 5,701 | 2.53125 | 3 | [] | no_license | <?php
namespace App\Controllers;
use App\Classes\CSRFToken;
use App\Classes\Request;
use App\Classes\Cart;
use App\Classes\Session;
use App\Classes\Mail;
use App\Models\Product;
use App\Models\Order;
use App\Models\Payment;
use Stripe\Customer;
use Stripe\Charge;
/**
*
*/
class CartController extends BaseController
{
public function show()
{
return view('cart');
}
public function addItem()
{
if (Request::has('post')) {
$request = Request::get('post');
if (CSRFToken::verifyCSRFToken($request->token, false)) {
if (!$request->product_id) {
throw new \Exception('Malicious Activity');
}
Cart::add($request);
echo json_encode(['success' => 'Product Addet To Cart Successfully']);
exit;
}
}
}
public function getCartItems()
{
try{
$result = array();
$cartTotal = 0;
if (!Session::has('user_cart') || count(Session::get('user_cart')) < 1) {
echo json_encode(['fail' => "No item in the cart"]);
exit;
}
$index = 0;
foreach ($_SESSION['user_cart'] as $cart_items) {
$productId = $cart_items['product_id'];
$quantity = $cart_items['quantity'];
$item = Product::where('id', $productId)->first();
if (!$item) {
continue;
}
$totalPrice = $item->price * $quantity;
$cartTotal = $totalPrice + $cartTotal;
$totalPrice = number_format($totalPrice, 2);
array_push($result, [
'id' => $item->id,
'name' => $item->name,
'image' => $item->image_path,
'description' => $item->description,
'price' => $item->price,
'total' => $totalPrice,
'quantity' => $quantity,
'stock' => $item->quantity,
'index' => $index
]);
$index++;
}
$cartTotal = number_format($cartTotal, 2);
Session::add('cartTotal', $cartTotal);
echo json_encode([
'items' => $result,
'cartTotal' => $cartTotal,
'authenticated' => isAuthenticated(),
'amountInCents' => convertMoneyToCents($cartTotal)
]);
exit;
}catch (\Exception $ex){
//log this in database or email admin
//echo json_encode(value)
}
}
public function updateQuantity()
{
if (Request::has('post')) {
$request = Request::get('post');
if (!$request->product_id) {
throw new \Exception('Malicious Activity');
}
$index = 0;
$quantity = '';
foreach ($_SESSION['user_cart'] as $cart_items) {
$index++;
foreach ($cart_items as $key => $value) {
if ($key == 'product_id' && $value == $request->product_id) {
switch ($request->operator) {
case '+':
$quantity = $cart_items['quantity'] + 1;
break;
case '-':
$quantity = $cart_items['quantity'] - 1;
if ($quantity < 1) {
$quantity = 1;
}
break;
}
array_splice($_SESSION['user_cart'], $index-1, 1, array(
[
'product_id' => $request->product_id,
'quantity' => $quantity
]
));
}
}
}
}
}
public function removeItem()
{
if (Request::has('post')) {
$request = Request::get('post');
if ($request->item_index === '') {
throw new \Exception('Malicious Activity');
}
//remove item
Cart::removeItem($request->item_index);
echo json_encode(['success' => "Product Removed From Cart!"]);
exit;
}
}
public function removeAllItems()
{
Cart::clear();
echo json_encode(['success' => "All Products Removed From Cart"]);
exit;
}
public function checkout()
{
if (Request::get('post')) {
$result['product'] = array();
$result['order_no'] = array();
$result['total'] = array();
$request = Request::get('post');
$token = $request->stripeToken;
$email = $request->stripeEmail;
try {
$customer = Customer::create([
'email' => $email,
'source' => $token
]);
$amount = convertMoneyToCents(Session::get('cartTotal'));
$charge = Charge::create([
'customer' => $customer->id,
'amount' => $amount,
'description' => user()->fullname . '-cart purchase',
'currency' => 'usd'
]);
$order_id = strtoupper(uniqid());
foreach ($_SESSION['user_cart'] as $cart_items) {
$productId = $cart_items['product_id'];
$quantity = $cart_items['quantity'];
$item = Product::where('id', $productId)->first();
if (!$item) {
continue;
}
$totalPrice = $item->price * $quantity;
$totalPrice = number_format($totalPrice, 2);
//store info to database
Order::create([
'user_id' => user()->id,
'product_id' => $productId,
'unit_price' => $item->price,
'status' => 'Pending',
'quantity' => $quantity,
'total' => $totalPrice,
'order_no' => $order_id
]);
$item->quantity = $item->quantity - $quantity;
$item->save();
array_push($result['product'], [
'name' => $item->name,
'price' => $item->price,
'total' => $totalPrice,
'quantity' => $quantity
]);
}
Payment::create([
'user_id' => user()->id,
'amount' => $charge->amount,
'status' => $charge->status,
'order_no' => $order_id
]);
$result['order_no'] = $order_id;
$result['total'] = Session::get('cartTotal');
$data = [
'to' => user()->email,
'subject' => 'Order Confirmation',
'view' => 'purchase',
'name' => user()->fullname,
'body' => $result
];
(new Mail())->send($data);
} catch (\Exception $ex) {
echo $ex->getMessage();
}
Cart::clear();
echo json_encode([
'success' => 'Thank you, we have received your payment and now processing your order.'
]);
}
}
} |
Markdown | UTF-8 | 1,994 | 3.15625 | 3 | [] | no_license | ---
title: 'Evaluation Process for On-Going Volunteers'
taxonomy:
category:
- docs
visible: true
---
**Ongoing Mentoring of Volunteer Leadership Team**
Because the volunteer positions in youth ministry are highly relational, each volunteer will be mentored in a relational manner. It is difficult to quantify a relational ministry. Therefore, at regular intervals, each volunteer will meet with the Youth Pastor and be guided through a self-relfective process in the following areas:
* How well they are meeting expectations of the job description.
* Are they showing up regularly to Pre-Ministry meetings, training, and actual ministry times?
* What are their current perceived strengths and weaknesses?
* Are they spending time regularly with the Lord? What does that look like?
* How do they perceive their ministry is going?
- what challenges are they experiencing?
- What wins have they had?
* How can I (the youth pastor) support them and pray for them?
**Process of Confrontation & Dismissal**
The above process of relational mentoring and feedback from the youth pastor should avoid the need for confrontation of minor issues. Through the above process with the guidance of the youth pastor, volunteers should become aware of any expectations not being met (which they agreed to in the orientation and application process), and committ to self-correction. If over the course of several mentoring sessions, the self-correction has not happened, then the youth pastor may suggest that a different area of ministry might be best, or a time away from student ministry might be best.
If the volunteer has had a serious moral failing or perhaps they have done something to make the ministry space unsafe for students, then confrontation would need to happen immediately. The Youth Pastor, and if need be, the Lead Pastor, would meet with the volunteer in question, and handle the situation in question, including immediate dismissal from the ministry if necessary.
|
Java | ISO-8859-1 | 5,764 | 2.390625 | 2 | [] | no_license | import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.*;
import javax.swing.JButton;
import java.awt.Color;
import javax.swing.SwingConstants;
import javax.swing.JMenu;
import java.awt.BorderLayout;
import java.awt.Component;
import javax.swing.Box;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import java.awt.FlowLayout;
import java.awt.CardLayout;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JMenuItem;
import java.awt.Font;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.DefaultComboBoxModel;
public class FramePrincipal extends JFrame {
private JButton botonLogin,botonBuscar;
public JComboBox combSeccion, combCliente;
private JLabel label;
private JMenuBar menuBar;
private JTextArea textArea;
private JScrollPane panelBarras;
private JPanel panel;
private JButton btnInsertar;
private JLabel label2;
private JTextField CodCircuito;
EnlazaBD enlazaBD = new EnlazaBD();
public FramePrincipal() {
setBounds(100, 100, 711,549);
setLocationRelativeTo(null);
setTitle("Trazabilidad");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
menuBar = new JMenuBar();
setJMenuBar(menuBar);
label = new JLabel(" SELECCIONAR: ");
menuBar.add(label);
combSeccion = new JComboBox(); //INTRODUCIMOS EN EL COMBOBOX LAS DIFERENTES SECCIONES
combSeccion.addItem("Seccion...");
combSeccion.addItem("SMD");
combSeccion.addItem("THT");
combSeccion.addItem("Test");
combSeccion.addItem("Barnizado");
combSeccion.addItem("Embalaje");
menuBar.add(combSeccion);
combCliente = new JComboBox();
combCliente.setEditable(false);
combCliente.addItem("Cliente...");
menuBar.add(combCliente);
addWindowListener(new ControlaClientes(this)); // AGREGAMOS EL LISTENER PARA QUE CUANDO SE ABRA LA VENTANA AADA LOS CLIENTES EN EL COMBOBOX CLIENTES
Component horizontalStrut_1 = Box.createHorizontalStrut(9);
menuBar.add(horizontalStrut_1);
label2 = new JLabel("C\u00F3digo Circuito: ");
menuBar.add(label2);
CodCircuito = new JTextField();
menuBar.add(CodCircuito);
CodCircuito.setColumns(10);
Component horizontalStrut = Box.createHorizontalStrut(95);
menuBar.add(horizontalStrut);
botonBuscar = new JButton("BUSCAR");
menuBar.add(botonBuscar);
botonBuscar.setBackground(new Color(0, 204, 204));
botonBuscar.setForeground(Color.BLACK);
botonBuscar.addActionListener(new ActionListener() { //CON EL BOTON ACEPTAR CERRAREMOS ESTE PANEL
public void actionPerformed(ActionEvent e) {
FrameBuscar frameBuscar = new FrameBuscar();
frameBuscar.setVisible(true);
}
});
botonLogin = new JButton("LOGIN");
menuBar.add(botonLogin);
botonLogin.setBackground(new Color(135, 206, 235));
botonLogin.setForeground(new Color(0, 0, 0));
abrirLogin abrirLogin = new abrirLogin();
botonLogin.addActionListener(abrirLogin);
textArea = new JTextArea();
panelBarras = new JScrollPane(textArea); //AADIMOS EL TEXTAREA EN EL JSCROLLPANE PARA QUE TENGA BARRA DE DESPLAZAMIENTO
getContentPane().add(panelBarras, BorderLayout.CENTER);
panel = new JPanel();
getContentPane().add(panel, BorderLayout.SOUTH);
btnInsertar = new JButton("INSERTAR");
insertarCampos insertaCampo = new insertarCampos();
btnInsertar.addActionListener(insertaCampo);
btnInsertar.setEnabled(false);
panel.add(btnInsertar);
}
public class abrirLogin implements ActionListener {
FrameLogeo frameLogeo;
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
frameLogeo = new FrameLogeo();
frameLogeo.setVisible(true);
btnInsertar.setEnabled(true); // EL BOTON INSERTAR ESTARA ANULADO HASTA QUE SE CLIQUE EL BOTON LOGIN
}
}
public class insertarCampos implements ActionListener{
private String muestraSeccion,muestraCliente,codCircuito,usuarioA;
private Connection miConexion;
private Statement stmt;
private String query;
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
usuarioA = FrameLogeo.usuario.getNombreUsuario(); // ESTOS SON LAS VARIABLES QUE ALMANECARAN CADA DATO DE QUE QUEREMOS INTRODUCIR EN EL TEXTAREA Y EN LA TABLA PRODUCCION
codCircuito = CodCircuito.getText();
muestraSeccion = (String) combSeccion.getSelectedItem();
muestraCliente = (String) combCliente.getSelectedItem();
// AADIMOS LOS DATOS EN EL TEXT AREA
textArea.append("Usuario: " + usuarioA + ", Codigo de circuito: " + codCircuito + ", Seccin: " + muestraSeccion + ", Cliente: " + muestraCliente);
textArea.append("\n");
CodCircuito.setText(""); // CADA VEZ QUE INSERTEMOS UN DATO EN EL TEXT AREA EL TEXTFIELD DONDE INTRODUCIMOS EL CODIGO DEL CIRCUITO SE VACIARA
//----------------- INTRODUCIMOS LOS DATOS TAMBIEN EN LA TABLA PRODUCCION PARA QUE QUEDEN ALMACENADOS
miConexion = enlazaBD.dameConexion();
try {
stmt = miConexion.createStatement();
query = "INSERT INTO PRODUCCION (CODIGOCIRCUITO,NOMBRECLIENTE,DEPARTAMENTO,NOMBREUSUARIO) values('"+codCircuito+"','"+muestraCliente+"','"+muestraSeccion+"','"+usuarioA+"')";
stmt.executeUpdate(query);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
|
C++ | UTF-8 | 639 | 3.328125 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <string>
using namespace std;
/* void lexiSmallestString(string &str)
{
for (int i = str.length() - 2; i >= 0; i--)
{
if (str[i] > str[i + 1])
{
str.erase(str.begin() + i);
break;
}
}
} */
void lexiSmallestString(string &str, int i)
{
if (i)
{
if (str[i] > str[i + 1])
str.erase(str.begin() + i);
else
lexiSmallestString(str, i - 1);
}
}
int main()
{
string s = "abcxd";
// cout << s[s.length() - 1];
// lexiSmallestString(s);
lexiSmallestString(s, s.length() - 2);
cout << s;
} |
Java | UTF-8 | 4,827 | 2.34375 | 2 | [] | no_license | package demo.shiro.realm.dao;
import demo.shiro.realm.entity.User;
import demo.shiro.realm.orm.JdbcTemplateUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.stereotype.Component;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
//@Component
public class UserDaoImpl implements UserDao {
private JdbcTemplate jdbcTemplate = JdbcTemplateUtils.jdbcTemplate();
@Override
public User createUser(User user) {
final String sql = "insert into sys_users(username, password, salt, locked) values(?, ?, ?, ?)";
GeneratedKeyHolder generatedKeyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement preparedStatement = connection.prepareStatement(sql, new String[] { "id" });
preparedStatement.setString(1, user.getUsername());
preparedStatement.setString(2, user.getPassword());
preparedStatement.setString(3, user.getSalt());
preparedStatement.setBoolean(4, user.getLocked());
return preparedStatement;
}
}, generatedKeyHolder);
user.setId(generatedKeyHolder.getKey().longValue());
return user;
}
@Override
public void updateUser(User user) {
String sql = "update sys_user set username=?,password=?,salt=?,locked=? where id=?";
jdbcTemplate.update(sql, user.getUsername(), user.getPassword(), user.getSalt(), user.getLocked(), user.getId());
}
@Override
public void addRolesRelation(Long userId, Long[] roleIds) {
if(roleIds == null || roleIds.length == 0) {
return;
}
String sql = "insert into sys_users_roles(user_id, role_id) values(?, ?)";
for(Long roleId : roleIds) {
if(!exists(userId, roleId)) {
jdbcTemplate.update(sql, userId, roleId);
}
}
}
@Override
public void removeRolesRelation(Long userId, Long[] roleIds) {
if(roleIds == null || roleIds.length == 0) {
return;
}
String sql = "delete from sys_users_roles where user_id=? and role_id=?";
for(Long roleId : roleIds) {
if(exists(userId, roleId)) {
jdbcTemplate.update(sql, userId, roleId);
}
}
}
private boolean exists(Long userId, Long roleId) {
String sql = "select count(1) from sys_users_roles where user_id=? and role_id=?";
return jdbcTemplate.queryForObject(sql, Integer.class, userId, roleId) != 0;
}
@Override
public User findOne(Long userId) {
String sql = "select id, username, password, salt, locked from sys_users where id=?";
List<User> userList = jdbcTemplate.query(sql, new BeanPropertyRowMapper(User.class), userId);
if(userList.size() == 0) {
return null;
}
return userList.get(0);
}
@Override
public User findByUsername(String username) {
String sql = "select id, username, password, salt, locked from sys_users where username=?";
List<User> userList = jdbcTemplate.query(sql, new BeanPropertyRowMapper(User.class), username);
if(userList.size() == 0) {
return null;
}
return userList.get(0);
}
@Override
public Set<String> findRoles(String username) {
String sql = "select role from sys_users u, sys_roles r,sys_users_roles ur where u.username=? and u.id=ur.user_id and r.id=ur.role_id";
return new HashSet(jdbcTemplate.queryForList(sql, String.class, username));
}
@Override
public Set<String> findPermissions(String username) {
StringBuilder sql = new StringBuilder("select p.permission from sys_users u");
sql.append(" left join sys_users_roles ur on u.id = ur.user_id");
sql.append(" left join sys_roles_permissions rp on rp.role_id = ur.role_id");
sql.append(" left join sys_permissions p on p.id = rp.permission_id");
sql.append(" where u.username=?");
return new HashSet(jdbcTemplate.queryForList(sql.toString(), String.class, username));
}
@Override
public boolean checkUsernameIsExists(String username) {
String sql = "select count(1) from sys_users where username=?";
return jdbcTemplate.queryForObject(sql, Integer.class, username) != 0;
}
}
|
Shell | UTF-8 | 269 | 3.109375 | 3 | [] | no_license | #!/bin/bash
x=0
load_balancer_url=$1
while [[ true ]]; do
curl $load_balancer_url
printf "\n"
if [[ `expr $x % 2` = 0 ]]; then
printf "+\n"
else
printf "*\n"
fi
x=`expr $x + 1`
sleep 0.5
done |
JavaScript | UTF-8 | 5,615 | 2.75 | 3 | [
"BSD-3-Clause"
] | permissive | var parser = require("./main");
describe("Test AST structure", function() {
it('fix #127 - echo statements', function() {
var ast = parser.parseEval('echo "hello"; ?> world');
ast.children.length.should.be.exactly(2);
ast.children[0].kind.should.be.exactly("echo");
ast.children[1].kind.should.be.exactly("inline");
});
it('fix #127 - inline', function() {
var ast = parser.parseEval('?>?>?>');
ast.children.length.should.be.exactly(1);
ast.children[0].kind.should.be.exactly("inline");
ast.children[0].value.should.be.exactly("?>?>");
});
it("test program", function() {
var ast = parser.parseEval("");
ast.kind.should.be.exactly("program");
ast.children.length.should.be.exactly(0);
});
it("test syntax error", function() {
var err = null;
(function() {
try {
var ast = parser.parseCode(
[
"<?php",
" $a = 1",
" $b = 2" // <-- unexpected $b expecting a ';'
].join("\n"),
"foo.php"
);
} catch (e) {
err = e;
throw e;
}
}.should.throw(/line\s3/));
err.name.should.be.exactly("SyntaxError");
err.lineNumber.should.be.exactly(3);
err.fileName.should.be.exactly("foo.php");
err.columnNumber.should.be.exactly(1);
});
it("test inline", function() {
const ast = parser.parseCode("Hello <?php echo 'World'; ?>\n !");
ast.children[0].kind.should.be.exactly("inline");
ast.children[2].kind.should.be.exactly("inline");
ast.children[0].value.should.be.exactly("Hello ");
ast.children[2].value.should.be.exactly(" !");
ast.children[2].raw.should.be.exactly("\n !");
});
it("fix #120", function() {
const ast = parser.parseCode("<?php echo 'World'; ?>\r\n !");
ast.children[1].value.should.be.exactly(" !");
ast.children[1].raw.should.be.exactly("\r\n !");
});
it("test magics", function() {
var ast = parser.parseEval("echo __FILE__, __DIR__;");
ast.children[0].arguments[0].kind.should.be.exactly("magic");
ast.children[0].arguments[1].kind.should.be.exactly("magic");
ast.children[0].arguments[0].value.should.be.exactly("__FILE__");
ast.children[0].arguments[1].value.should.be.exactly("__DIR__");
});
it("test shell", function() {
var ast = parser.parseEval("echo `ls -larth`;");
ast.children[0].arguments[0].kind.should.be.exactly("encapsed");
ast.children[0].arguments[0].type.should.be.exactly("shell");
});
it("test clone", function() {
var ast = parser.parseEval("$a = clone $var;");
ast.children[0].right.kind.should.be.exactly("clone");
ast.children[0].right.what.kind.should.be.exactly("variable");
});
it("test echo, isset, unset, empty", function() {
var ast = parser.parseEval(
[
'echo ($expr) ? "ok" : "ko";',
'print "some text"',
"isset($foo, $bar)",
"unset($var)",
"empty($var)",
""
].join(";\n")
);
ast.children[0].kind.should.be.exactly("echo");
ast.children[1].kind.should.be.exactly("print");
ast.children[2].kind.should.be.exactly("isset");
ast.children[3].kind.should.be.exactly("unset");
ast.children[4].kind.should.be.exactly("empty");
});
it("should be variable", function() {
// @todo
});
it("test literals", function() {
// @todo string / numbers / booleans
});
it("test constants", function() {
var ast = parser.parseEval("const FOO = 3.14;");
ast.children[0].kind.should.be.exactly("constant");
ast.children[0].name.should.be.exactly("FOO");
ast.children[0].value.kind.should.be.exactly("number");
ast.children[0].value.value.should.be.exactly("3.14");
});
it("test eval", function() {
var ast = parser.parseEval('eval("return true;");');
ast.children[0].kind.should.be.exactly("eval");
ast.children[0].source.kind.should.be.exactly("string");
ast.children[0].source.value.should.be.exactly("return true;");
});
it("test die/exit", function() {
var ast = parser.parseEval('die("bye");');
ast.children[0].kind.should.be.exactly("exit");
ast.children[0].status.value.should.be.exactly("bye");
ast = parser.parseEval("exit(-1);");
ast.children[0].kind.should.be.exactly("exit");
ast.children[0].status.value.should.be.exactly("-1");
});
it("test coalesce operator", function() {
var ast = parser.parseEval("$var = $a ?? true;");
ast.children[0].right.kind.should.be.exactly("bin");
ast.children[0].right.type.should.be.exactly("??");
ast.children[0].right.left.kind.should.be.exactly("variable");
ast.children[0].right.right.kind.should.be.exactly("boolean");
});
it("test include / require", function() {
var ast = parser.parseEval(
[
'include "file.php"',
'include_once (PATH . "/file.php")',
'require "req.php"',
'require_once "file.php"',
""
].join(";\n")
);
ast.children[0].kind.should.be.exactly("include");
ast.children[0].once.should.be.exactly(false);
ast.children[0].require.should.be.exactly(false);
ast.children[1].kind.should.be.exactly("include");
ast.children[1].once.should.be.exactly(true);
ast.children[1].require.should.be.exactly(false);
ast.children[2].kind.should.be.exactly("include");
ast.children[2].once.should.be.exactly(false);
ast.children[2].require.should.be.exactly(true);
ast.children[3].kind.should.be.exactly("include");
ast.children[3].once.should.be.exactly(true);
ast.children[3].require.should.be.exactly(true);
});
});
|
JavaScript | UTF-8 | 2,150 | 2.984375 | 3 | [
"MIT"
] | permissive | "use strict";
window.addEventListener("load", (function () {
const commonUnitsTime = document.getElementById("cu-time");
const percentOfToday = document.getElementById("cu-percent");
const progressLoader = document.getElementById("progress-loader");
const siDate = document.getElementById("si-time").querySelector('.date');
const siTime = document.getElementById("si-time").querySelector('.time');
siDate.addEventListener('click', () =>
localStorage.setItem('useISO',
localStorage.getItem('useISO') ? '' : '1'));
siTime.addEventListener('click', () =>
localStorage.setItem('use24h',
localStorage.getItem('use24h') ? '' : '1'));
const [ kiloClarke, hectoClarke, clarke ] = Array
.from(commonUnitsTime.children)
.map(el => el.children[0]);
const dayInS = 24 * 60 * 60;
const dayInMs = dayInS * 1000;
const dayInϾ = 100 * 10 * 100;
// Number of seconds to a clarke
const interval = dayInS / dayInϾ;
const multiplierIndex = [ 60 * 60 * 1000, 60 * 1000, 1000, 1 ];
const splitTime = date => [
date.getHours(),
date.getMinutes(),
date.getSeconds(),
date.getMilliseconds(),
];
const getTimeInMs = date =>
splitTime(date).reduce(
(acc, cur, i) => acc + cur * multiplierIndex[i], 0);
const convertTimeToCommonUnits = (date) => {
const percent = (getTimeInMs(date) / dayInMs) * 100;
const [ kϾ, rest ] = percent.toFixed(3).split(".");
// Slice rest to get hϾ and Ͼ
return [ percent, kϾ, rest.slice(0, 1), rest.slice(1) ];
};
setInterval(function () {
const now = new Date();
siDate.textContent = (
localStorage.getItem('useISO')
? dateFns.format(now, 'YYYY-MM-DD')
: dateFns.format(now, 'DD/MM/YYYY')
);
siTime.textContent = (
localStorage.getItem('use24h')
? dateFns.format(now, 'HH:mm:ss')
: dateFns.format(now, 'hh:mm:ss A')
);
const [ percent, kϾ, hϾ, Ͼ ] = convertTimeToCommonUnits(now);
const percentString = `${percent.toFixed(3)}%`;
percentOfToday.textContent = percentString
progressLoader.style.width = percentString;
kiloClarke.textContent = kϾ;
hectoClarke.textContent = hϾ;
clarke.textContent = Ͼ;
}, interval);
}));
|
Java | UTF-8 | 2,679 | 3.90625 | 4 | [] | no_license | package duke;
import duke.task.Task;
/**
* A class in charge of the interaction to {@code Duke} users.
*/
public class Ui {
private static final String GREETING_TEXT = "Hello, I'm Duke!\n"
+ "How can I help you?";
private static final String FAREWELL_TEXT = "Why do you choose to leave me!";
/**
* Greets the users by printing the greeting text.
*/
public static String greet() {
return GREETING_TEXT;
}
/**
* Farewells the users by printing the farewell message.
*/
public static String farewell() {
return FAREWELL_TEXT;
}
/**
* Returns a message when a task is added to a {@code TaskList}.
*
* @param tasks The list to which a new task is added.
* @param task The task added to the list.
* @return The message indicating the addition of the task.
*/
public static String addTaskMessage(TaskList tasks, Task task) {
return "Got it. I've added this task:\n "
+ task
+ "\nTask(s) remaining in the list: "
+ tasks.size();
}
/**
* Returns a message when a task is updated.
*
* @param taskNum The item number of the task.
* @param task The task added to the list.
* @return The message indicating the update of the task.
*/
public static String updateTaskMessage(int taskNum, Task task) {
return "Got it. I've update the task as:\n "
+ taskNum + ". " + task;
}
/**
* Returns a message <strong>after</strong> a task is removed from the list.
*
* @param tasks The list from which a task is removed.
* @param task The task that is removed.
* @return The message indicating the deletion of the task.
*/
public static String removeTaskMessage(TaskList tasks, Task task) {
int tasksSize = tasks.size();
return "Noted. I've removed this task:\n "
+ task
+ "\nTask(s) remaining in the list: "
+ tasksSize;
}
/**
* Returns a message when a task is done.
*
* @param task The task list to be marked done.
* @return The message indicating the task is done.
*/
public static String taskDoneMessage(Task task) {
return "Nice! I've marked this task as done:\n " + task;
}
/**
* Returns a message when a task is undone.
*
* @param task The task list to be undone.
* @return The message indicating the task in undone.
*/
public static String taskUndoneMessage(Task task) {
return "Alright. I've undone this task:\n " + task;
}
}
|
Markdown | UTF-8 | 1,872 | 2.640625 | 3 | [
"MIT"
] | permissive | # React App Starter Kit
This is a simple React App starter kit with the essential dependencies that I would use for development.
After experimenting with Create React App, I thought it was really good, but missing a few things, so I
have created something similar, but with a few extra's. I have also included my LESS mixin library, see
below for list of the available mixins for use.
# Installation:
* Node & NPM are dependencies so they need to be installed.
* Clone the project, delete the git files (unless you are contributing to this repo).
* Install packages '$ npm install'.
## Commands:
```bash
$ npm start
```
* Runs Webpack-dev-server on port 3000.
* Updates JS & css on files with hot reload.
* Use this command for development.
* File changes are stored in memory
```bash
$ npm run build
```
* Bundles / minifies files for production.
```bash
$ npm test
```
* Runs unit tests
```bash
$ npm run test_watch
```
* Runs unit tests in watch mode
```bash
$ npm run format
```
* Formats files with Prettier
```bash
$ node app.js
$ nodemon app.js
```
* Serves the production build on Port 5000
* Nodemon should be installed glabally for that command to work
# What's included?:
## React & Redux
* React, React Dom, React Router, Prop-Types
* Redux, Redux Dev Tools, React Redux
## Axios
* Used for http requests
## Webpack Loaders & Plugins:
* Webpack-Dev-Server
* Babel-loader
* Less-loader, CSS-loader, style-loader
* Post CSS Loader (Used for auto prefixing)
* UglifyJS
* HTML & Markdown loaders
## Testing & Linting
* Jest
* ES Lint
* Prettier
* [Airbnb Javascript style guide](https://github.com/airbnb/javascript)
## LESS
I have included my LESS Style library to help with faster CSS developement:
[More info here](https://github.com/rm-bergmann/less-style-library)
|
Java | UTF-8 | 660 | 2.5 | 2 | [] | no_license | package com.leo.test.neural.network.activators;
import java.io.Serializable;
public class HyperbolicTangentActivationStrategy implements ActivationStrategy, Serializable {
private static final long serialVersionUID = -268299068707852082L;
public double activate(double weightedSum) {
double a = Math.exp(weightedSum);
double b = Math.exp(-weightedSum);
return ((a - b) / (a + b));
}
public double derivative(double weightedSum) {
return 1 - Math.pow(activate(weightedSum), 2.0);
}
public HyperbolicTangentActivationStrategy copy() {
return new HyperbolicTangentActivationStrategy();
}
}
|
Python | UTF-8 | 170 | 3.03125 | 3 | [] | no_license | import calculate
number1 = 10
number2 = 2
print(calculate.add(10, 2))
print(calculate.subtract(10, 2))
print(calculate.multiplied(10, 2))
print(calculate.divide(10, 2)) |
Java | UTF-8 | 624 | 2.875 | 3 | [] | no_license | public class EmailErrorHandler implements Receiver {
private Receiver receiver;
@Override
public boolean handleMessage(Message message) {
if(message.msg.contains("Email")){
System.out.println(" EmailErrorHandler processed "+message.messagePriority+ " priority issue: "+message.msg);
return true;
}
else{
if (receiver != null) {
receiver.handleMessage(message);
}
return false;
}
}
@Override
public void nextHandleMessage(Receiver nextReceiver) {
this.receiver=nextReceiver;
}
}
|
Java | UTF-8 | 356 | 2.109375 | 2 | [] | no_license | package com.nav.springbootstarter.topic;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value=HttpStatus.NOT_FOUND)
class TopicNotFoundException extends RuntimeException {
public TopicNotFoundException(String topicId) {
super("could not find Topic '" + topicId + "'.");
}
} |
C# | UTF-8 | 2,148 | 2.546875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace View
{
/// <summary>
/// Interakční logika pro MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private DatabaseControl databaseControl;
public MainWindow()
{
databaseControl = new DatabaseControl();
InitializeComponent();
}
private void loginButton_Click(object sender, RoutedEventArgs e)
{
if ((idTextBox.Text != "") && (passwordTextBox.Text != ""))
{
try
{
databaseControl.SetActiveUser(int.Parse(idTextBox.Text));
if (!databaseControl.CheckPassword(passwordTextBox.Text))
{
MessageBox.Show("Zkontrolujte přihlašovací údaje!", "Neplatné heslo!", MessageBoxButton.OK, MessageBoxImage.Exclamation);
}
else
{
UserWindow window = new UserWindow(databaseControl);
window.ShowDialog();
Close();
}
}
catch (FormatException ex)
{
MessageBox.Show(ex.Message, "Chyba!", MessageBoxButton.OK, MessageBoxImage.Exclamation);
}
catch
{
MessageBox.Show("Zkontrolujte přihlašovací údaje!", "Uživatel nenalezen!", MessageBoxButton.OK, MessageBoxImage.Exclamation);
}
}
else
{
MessageBox.Show("Neplatné údaje!", "Neplatné údaje!", MessageBoxButton.OK, MessageBoxImage.Exclamation);
}
}
}
}
|
Java | UTF-8 | 179 | 1.90625 | 2 | [] | no_license | package friends.reader.parser;
import java.util.List;
public interface FileLinesParser<T> {
List<String> getLines();
void add(String line);
List<T> retrieve();
}
|
C | UTF-8 | 1,206 | 3.296875 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <errno.h>
#define DEAD(mess){perror(mess);exit(-1);}
#define DEATH(mess){printf("%s\n",mess);return 1;}
void realrm(const char *filename){
struct stat st;
struct dirent *fp;
DIR * dirp;
char * childname=NULL;
int ret;
ret=stat(filename,&st);
if(ret<0)
DEAD("stat err");
if((st.st_mode&S_IFMT)!=S_IFDIR)
unlink(filename);
else{
dirp=opendir(filename);
if(!dirp)
DEAD("opendir err");
while((fp=readdir(dirp))){
if(strcmp(fp->d_name,".")==0||strcmp(fp->d_name,"..")==0)
continue;
childname=calloc(strlen(filename)+strlen(fp->d_name)+2,0);
if(!childname)
DEAD("malloc err");
sprintf(childname,"%s/%s",filename,fp->d_name);
realrm(childname);
if(childname)
memset(childname,0,strlen(childname)+1);
}
closedir(dirp);
ret=rmdir(filename);
if(ret<0)
DEAD("rmdir err");
if(childname)
free(childname);
}
printf("delete %s sucessful\n",filename);
}
int main(int argc,char **argv){
if(argc==1)
DEATH("usage:./rm filename");
realrm(argv[1]);
return 0;
}
|
C++ | UTF-8 | 2,785 | 3.234375 | 3 | [] | no_license | #include "Nunchuck.hpp"
// everything related to talking with the nunchuck
namespace Nunchuck {
// anonymous namespace -> everything inside Nunchuck can see the contents, everything outside cannot
namespace {
// array to store nunchuck data
uint8_t buf[6];
uint8_t address = 0x52;
// sends a data request to WII Nunchuck
void send_request()
{
// https://bootlin.com/labs/doc/nunchuk.pdf
Wire.beginTransmission(0x52);
Wire.write((uint8_t)0x00);
Wire.endTransmission();
}
char decode_byte(char x)
{
return (x ^ 0x17) + 0x17; // data XOR with 10111 (magic)
}
// Receive data from nunchuck
// returns 1 if success, 0 if failure
int get_data()
{
int cnt = 0;
Wire.requestFrom(0x52, 6); // request 6 bytes
while (Wire.available()) {
buf[cnt] = decode_byte(Wire.read());
cnt++;
}
send_request(); // send request for next get_data
// success if 6 bytes received
if (cnt >= 5) {
return 1;
}
return 0;
}
// returns zbutton state 0/1
int zbutton()
{
return ((buf[5] >> 0) & 0x01) ? 0 : 1; // checks the first bit and returns it
}
// returns cbutton state 0/1
int cbutton()
{
return ((buf[5] >> 1) & 0x01) ? 0 : 1; // checks the second bit and returns it
}
// returns value of x-axis joystick
int joyx()
{
return buf[0];
}
// returns value of y-axis joystick
int joyy()
{
return buf[1];
}
// returns value of x-axis accelerometer
int accelx()
{
// bit 9-2 are at buf[2], bit 1-0 are at buf[5]
// https://bootlin.com/labs/doc/nunchuk.pdf
return (buf[2] << 2) | ((buf[5] >> 2) & 0x03);
}
// returns value of y-axis accelerometer
int accely()
{
return (buf[3] << 2) | ((buf[5] >> 4) & 0x03);
}
// returns value of z-axis accelerometer
int accelz()
{
return (buf[4] << 2) | ((buf[5] >> 6) & 0x03);
}
}
// sends handshake signal to WII Nunchuck
void handshake()
{
Serial.print("Nunchuck: sending handshake...");
// https://bootlin.com/labs/doc/nunchuk.pdf
Wire.begin();
Wire.beginTransmission(0x52);
Wire.write((uint8_t)0x40);
Wire.write((uint8_t)0x00);
Wire.endTransmission();
Serial.println(" Sent!");
}
Data getNewData()
{
get_data();
Data result;
result.zbut = zbutton(); // 0 - 1
result.cbut = cbutton(); // 0 - 1
result.joyx = joyx(); // 0 - 255
result.joyy = joyy(); // 0 - 255
result.accx = accelx(); // 0 - 1024
result.accy = accely(); // 0 - 1024
result.accz = accelz(); // 0 - 1024
return result;
}
}
|
Python | UTF-8 | 2,466 | 2.921875 | 3 | [
"Apache-2.0"
] | permissive | # -*- coding: utf-8 -*-
import numpy as np
from sklearn.datasets import make_classification
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from mabwiser.mab import MAB, LearningPolicy
######################################################################################
#
# MABWiser
# Scenario: Playlist recommendation for music streaming service
#
# An _online music streaming service wants to recommend a playlist to a user
# based on a user's listening history and user features. There is a large amount
# of data available to train this recommender model, which means the parallel
# functionality in MABWiser can be useful.
#
#
######################################################################################
# Seed
seed = 111
# Arms
arms = list(np.arange(100))
# Historical on user contexts and rewards (i.e. whether a user clicked
# on the recommended playlist or not)
contexts, rewards = make_classification(n_samples=100000, n_features=200,
n_informative=20, weights=[0.01], scale=None)
# Independently simulate the recommended playlist for each event
decisions = np.random.choice(arms, size=100000)
# Split data into train and test data sets
contexts_train, contexts_test = train_test_split(contexts, test_size=0.3, random_state=seed)
rewards_train, rewards_test = train_test_split(rewards, test_size=0.3, random_state=seed)
decisions_train, decisions_test = train_test_split(decisions, test_size=0.3, random_state=seed)
# Fit standard scaler for each arm
arm_to_scaler = {}
for arm in arms:
# Get indices for arm
indices = np.where(decisions_train == arm)
# Fit standard scaler
scaler = StandardScaler()
scaler.fit(contexts[indices])
arm_to_scaler[arm] = scaler
########################################################
# LinUCB Learning Policy
########################################################
# LinUCB learning policy with alpha 1.25 and n_jobs = -1 (maximum available cores)
linucb = MAB(arms=arms,
learning_policy=LearningPolicy.LinUCB(alpha=1.25, arm_to_scaler=arm_to_scaler),
n_jobs=-1)
# Learn from playlists shown and observed click rewards for each arm
linucb.fit(decisions=decisions_train, rewards=rewards_train, contexts=contexts_train)
# Predict the next best playlist to recommend
prediction = linucb.predict(contexts_test)
# Results
print("LinUCB: ", prediction[:10])
|
PHP | UTF-8 | 2,841 | 3.09375 | 3 | [] | no_license | <!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php $ceu = array( "Italy"=>"Rome", "Luxembourg"=>"Luxembourg", "Belgium"=> "Brussels", "Denmark"=>"Copenhagen", "Finland"=>"Helsinki", "France" => "Paris", "Slovakia"=>"Bratislava", "Slovenia"=>"Ljubljana", "Germany" => "Berlin", "Greece" => "Athens", "Ireland"=>"Dublin");
$b = array_values($ceu);
foreach ($b as $key => $value) {
echo ' ', $key, '->', $value;
}
$color = array ( "color" => array ( "a" => "Red", "b" => "Red", "c" => "White"), "numbers" => array ( 1, 2, 3, 4, 5, 6 ), "holes" => array ( "First", 5 => "Second", "Third"));
echo '<br/>';
echo $color["color"]["a"];
echo '<br/>';
define("foo", "you are foo");
echo foo;
$a = "heeloo";
$b = $a. "workjaife";
echo $b;
echo '<br/>';
$d='A00';
for ($i=0; $i <5; $i++) {
$d++;
echo $d;
echo '<br>';
}
$a= 128;
$c= 14;
while ($a > 13) {
$a=$a-$c;
}
echo $a;
echo '<br>';
for ($i=0; $i < 6; $i++) {
echo "<br>";
for ($j=0; $j <$i ; $j++) {
echo "*";
}
}
for($i=6; $i<11; $i++){
echo "<br>";
for ($j=5; $j>10-$i ; $j--) {
echo"*";
}
}
echo "<br>";
echo "<br>";
$ds=0;
function Test() { global $ds; $ds+=7; echo $ds; }
Test(); Test(); Test();
echo "<br>";
echo $ds;
echo "<br>";
echo date("l");
echo date("l jS \of F Y h:i:s A");
echo "<br>";
echo date("l \\t\h\e jS");
echo "<br>";
$nextWeek = time() + (7 * 24 * 60 * 60);
echo 'Now: '. date('Y-m-d') ."\n";
echo 'Next Week: '. date('Y-m-d', $nextWeek) ."\n";
function print_form($f_name, $l_name, $email, $os) { ?> <form action="form_checker.php" method=“get"> First Name: <input type="text" name="f_name" value="<?php echo $f_name?>" /> <br/> Last Name <b>*</b>:<input type="text" name="l_name" value="<?php echo $l_name?>" /> <br/> Email Address <b>*</b>:<input type="text" name="email" value="<?php echo $email?>" /> <br/> Operating System: <input type="text" name="os" value="<?php echo $os?>" /> <br/><br/> <input type="submit" name="submit" value="Submit" /> <input type="reset" /> </form> <?php }
function check_form($f_name, $l_name, $email, $os) { if (!$l_name||!$email){ echo "<h3>You are missing some required fields!</h3>"; print_form($f_name, $l_name, $email, $os); } else{ confirm_form($f_name, $l_name, $email, $os); } }
function confirm_form($f_name, $l_name, $email, $os) { ?> <h2>Thanks! Below is the information you have sent to us.</h2> <h3>Contact Info</h3>
<?php echo "Name: $f_name $l_name <br/>"; echo "Email: $email <br/>"; echo "OS: $os"; }
if (!isset($_GET["submit"])) { ?> <h3>Please enter your information</h3> <p>Fields with a "<b>*</b>" are required.</p> <?php print_form("","","",""); } else{ check_form($_GET["f_name"],$_GET["l_name"],$_GET["email"],$_GET["os"]); } ?>
?>
</body>
</html>
|
Java | UTF-8 | 2,372 | 1.898438 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.github.api.data;
import com.google.gson.annotations.SerializedName;
import com.intellij.openapi.util.text.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.io.mandatory.Mandatory;
import org.jetbrains.io.mandatory.RestModel;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
@RestModel
@SuppressWarnings("UnusedDeclaration")
public class GithubGist {
@Mandatory private String id;
private String description;
@SerializedName("public")
@Mandatory private Boolean isPublic;
private String url;
@Mandatory private String htmlUrl;
private String gitPullUrl;
private String gitPushUrl;
@Mandatory private Map<String, GistFile> files;
private GithubUser owner;
private Date createdAt;
@RestModel
public static class GistFile {
private Long size;
@Mandatory private String filename;
@Mandatory private String content;
@Mandatory private String raw_url;
private String type;
private String language;
@NotNull
public String getFilename() {
return filename;
}
@NotNull
public String getContent() {
return content;
}
@NotNull
public String getRawUrl() {
return raw_url;
}
}
@NotNull
public String getId() {
return id;
}
@NotNull
public String getDescription() {
return StringUtil.notNullize(description);
}
public boolean isPublic() {
return isPublic;
}
@NotNull
public String getHtmlUrl() {
return htmlUrl;
}
@NotNull
public List<GistFile> getFiles() {
return new ArrayList<>(files.values());
}
@Nullable
public GithubUser getUser() {
return owner;
}
}
|
C++ | UTF-8 | 1,333 | 4.03125 | 4 | [] | no_license | //#include<cstring>,该头文件下的函数参数大多为char * ptr。
#include <iostream>
#include <cstring>
using namespace std;
int main () {
char str1[11] = "Hello"; //字符串赋值形式
char str2[11] = "World";
char str3[11];
int len;
//复制 str1 到 str3 , 返回str3。
strcpy( str3, str1);
cout << "strcpy(str3 , str1) : " << str3 << endl;
char s [ ] = "abcdefgh" , *p = s;
p += 3;
printf("%d\n" , strlen(strcpy(p , "ABCD"))); //复制后,返回p,输出4
/*
strcpy复制完之后,字符串为abcABCD,但是p指向的位置是A,
所以计算长度的时候前面三个不会算入其中。
*/
//连接 str1 和 str2
strcat(str1 , str2);
cout << "strcat(str1 , str2) : " << str1 << endl;
//连接后,str1 的总长度
len = strlen(str1);
cout << " strlen(str1) : " << len << endl;
//比较,若str1=str2,i=0;若str1<str2,i<0;若str1>str2,i>0;
int i = strcmp(str1 , str2);
cout << i;
/*
每一string结尾处都是'\0',不论该string的定义是char *、char []还是string。
在#include<cstring>中,strlen(str)输出的str的用户定义字符个数,但实际上str包含两个部分:用户定义字符 和 '\0'。
若有:char str[5] = "loveU";则出错,因为char[]方式定义,必须把最后一个元素留给'\0'。
*/
return 0;
}
|
Python | UTF-8 | 954 | 3.984375 | 4 | [] | no_license | # Use an import statement at the top
import random
word_file = "words.txt"
word_list = []
#fill up the word_list
with open(word_file,'r') as words:
for line in words:
# remove white space and make everything lowercase
word = line.strip().lower()
# don't include words that are too long or too short
if 3 < len(word) < 8:
word_list.append(word)
# Add your function generate_password here
# It should return a string consisting of three random words
# concatenated together without spaces
def generate_password(input_material):
#created output string, and turns for the loop
pwd_output = ""
turns = 0
while turns < 3:
#t is our variable to hold the random numbers which assures us the selection of the word from the "word list" is actually at random
t = random.randint(0, len(word_list))
print(t)
pwd_output = pwd_output + word_list[t]
turns += 1
return pwd_output
# test your function
print(generate_password(word_file)) |
Python | UTF-8 | 640 | 3.125 | 3 | [] | no_license | def ordered_word(word):
l = len(word)
for i in range(l):
next = i + 1
temp = word[next]
if word[i] < temp:
if i + 1 < l:
continue
else:
return False
return true
def crypto_words(word):
l = len(word)
crypto_pairs = []
pair = ["", 1]
for i in range(l):
pair[0] = word[i]
nextword = i + 1
temp = word[next]
if word[i] == temp:
pair[1] += 1
if (i + 1) < l:
continue
else:
crypto_pairs.append(pair)
pair[1] = 1
else:
crypto_pairs.append(pair)
return crypto_pair
if __name__ == "__main__":
ordered_word("zmaap") |
Python | UTF-8 | 3,642 | 2.515625 | 3 | [] | no_license | #
# 共通関数
#
import os
import datetime
import csv
import json
def get_setting(itm,key):
setting_info = json.load(open('info.json', 'r', encoding='utf-8'))
return setting_info[itm][key]
def make_dir(path):
if not os.path.isdir(path):
os.makedirs(path,exist_ok=True)
def dsp_msg(title,msg,lvl):
if os.path.exists('./data')==False:
make_dir('./data')
if os.path.exists('./data/log.txt')==False:
with open('./data/log.txt', 'w', encoding='shift_jis') as f:
f.write('')
tmp = datetime.datetime.now().strftime('[%Y-%m-%d %H:%M:%S] ') + ('*' * lvl) + title + ': ' + msg
with open('./data/log.txt', 'r', encoding='shift_jis') as f:
old_data = f.readlines()[0:1000]
with open('./data/log.txt', 'w', encoding='shift_jis') as f:
f.write(tmp+'\n')
with open('./data/log.txt', 'a', encoding='shift_jis') as f:
f.writelines(old_data)
print(tmp)
def str2num(instr,numtype):
# numtype: 0=int, 1=float
if instr=='-' or instr=='' or instr=='未取得': return 'NULL'
instr = instr.replace(' ','')
instr = instr.replace(',','')
instr = instr.replace('%','')
instr = instr.replace('+','')
instr = instr.replace('USD','')
if numtype==0:
return int(instr)
else:
return float(instr)
def num2str(innum,strtype):
# strype: 0=カンマ, 1=カンマ+符号
str = '{:,}'.format(innum)
if strtype==1 and innum>0:
str = '+'+'{:,}'.format(innum)
return str
def make_html(msg):
dsp_msg('html生成',msg,2)
linkurl = '<a href="' + get_setting('mail_html','pic_link') + '">※</a>'
tbl = []
with open(r'./data/list_shisan.csv','r') as f:
reader = csv.reader(f)
for r in reader:
if r[6]!='0' and r[6]!='-' and r[0]!='資産':
tbl.append([r[0], '', r[1], r[6], num2str(str2num(r[2],0),1), linkurl.replace('*****',r[0])])
with open(r'./data/list_syouhin.csv','r') as f:
reader = csv.reader(f)
for r in reader:
if r[0]=='国内株式':
tbl.append([r[0], r[2], r[14], r[16], num2str(int(str2num(r[12],1) * str2num(r[4],0)),1), linkurl.replace('*****',r[2])])
elif r[0]=='米国株式':
tbl.append([r[0], r[2], r[14], r[16], num2str(int(str2num(r[4],0) * str2num(r[12],1) * (str2num(r[14],0) / str2num(r[8],1) / str2num(r[4],0))),1), linkurl.replace('*****',r[2])])
elif r[0]=='投資信託':
tbl.append([r[0], r[2], r[14], r[16], num2str(int(str2num(r[14],0) / str2num(r[8],0) * str2num(r[12],0)),1), linkurl.replace('*****',r[2])])
tbl = sorted(tbl, reverse=False, key=lambda x: x[0])
tbl = tbl[:-1]
tbl[0][0] =tbl[0][0][5:]
for r in tbl:
if len(r[1])>16:
r[1] = r[1][0:15] + '...'
# テンプレート読み込み
with open(r'./mail_template.html','r',encoding="utf-8") as f:
reader = csv.reader(f)
html = ''
for row in reader:
if len(row)>0:
html += row[0]
# 埋め込みデータ生成
in_table = ''
for dt in tbl:
in_table += '<tr><td align="left">{0}</td><td align="left">{1}</td><td align="right">{2}</td><td align="right">{3}</td><td align="right">{4}</td><td align="center">{5}</td></tr>'.format(dt[0],dt[1],dt[2],dt[3],dt[4],dt[5])
# テンプレートに埋め込み
html = html.replace('{0}',in_table)
html = html.replace('{1}',datetime.datetime.now().strftime('[%Y-%m-%d %H:%M:%S]'))
html = html.replace('{2}',get_setting('mail_html','log_link'))
return html
|
Ruby | UTF-8 | 487 | 3.296875 | 3 | [] | no_license | def bubble_sort arr
j=(arr.size)-1
while j>=0
i=0
while i<j
if(arr[i]>arr[i+1])
arr[i],arr[i+1]=arr[i+1],arr[i]
end
i+=1
end
j-=1
end
arr
end
def bubble_sort_by arr
j=(arr.size)-1
while j>=0
i=0
while i<j
if( yield(arr[i],arr[i+1]) >0)
arr[i],arr[i+1]=arr[i+1],arr[i]
end
i+=1
end
j-=1
end
arr
end
puts bubble_sort ["a","c","b"]
a= bubble_sort_by(["hi","hello","hey"]) do |left,right|
left.length - right.length
end
puts a |
Java | UTF-8 | 700 | 1.5 | 2 | [
"Apache-2.0"
] | permissive | package com.alibaba.alink.operator.common.fm;
import java.io.Serializable;
import com.alibaba.alink.operator.common.fm.BaseFmTrainBatchOp.FmDataFormat;
import com.alibaba.alink.operator.common.fm.BaseFmTrainBatchOp.Task;
/**
* Fm model data.
*/
public class FmModelData implements Serializable {
private static final long serialVersionUID = 7452756889593215611L;
public String vectorColName = null;
public String[] featureColNames = null;
public String labelColName = null;
public FmDataFormat fmModel;
public int vectorSize;
public int[] dim;
public int[] fieldPos;
public Object[] labelValues = null;
public Task task;
public double[] convergenceInfo;
}
|
Java | UTF-8 | 2,473 | 2.609375 | 3 | [] | no_license | package com.example.consumer;
import org.apache.kafka.clients.consumer.CommitFailedException;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.Properties;
public class JsonConsumerCustomSeek {
private static Logger log = LoggerFactory.getLogger(JsonConsumerCustomSeek.class);
private KafkaConsumer<String, String> consumer;
public JsonConsumerCustomSeek(String topic){
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("group.id", "JsonConsumer");
props.put("auto.offset.reset", "latest");
/* Enable following two properties for auto commit */
props.put("enable.auto.commit", "true");
props.put("auto.commit.interval.ms", "2000");
props.put("partition.assignment.strategy", "org.apache.kafka.clients.consumer.RoundRobinAssignor");
props.put("max.poll.records", "1000");
props.put("key.deserializer",
"org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer",
"org.apache.kafka.common.serialization.StringDeserializer");
consumer = new KafkaConsumer<String, String>(props);
consumer.subscribe(Collections.singleton(topic));
}
public void run(){
try {
for (TopicPartition partition: consumer.assignment()){
consumer.seek(partition, 100);
}
while (true) {
ConsumerRecords<String, String> records = consumer.poll(100);
for (ConsumerRecord<String, String> record : records){
System.out.println(String.format("topic = %s, partition = %d, offset = %d, key: %s, message = %s"
, record.topic(), record.partition(), record.offset(),
record.key(), record.value())
);
}
}
}finally {
consumer.close();
}
}
public static void main(String[] args){
String topicName = "demo";
JsonConsumerCustomSeek jsonConsumer = new JsonConsumerCustomSeek(topicName);
jsonConsumer.run();
}
}
|
Markdown | UTF-8 | 1,070 | 2.703125 | 3 | [] | no_license | ### Sample project to figure out how to use expo
Docs found here: https://expo.io/learn
1. Try the snack on the website
2. Download NodeJS if you do not have it already
3. Get the command line tool
You will run this tool locally to package, serve, and publish your projects.
`npm install expo-cli --global` might need to run this as sudo `sudo npm install expo-cli --global`
4. Create your first project
You will be asked to create an Expo account https://expo.io before proceeding.
```
expo init my-new-project
cd my-new-project
expo start
```
5. Preview your project
Worked with the settin on LAN
Open Expo Client on your device. Use it to scan the QR code printed by expo start. You may have to wait a minute while your project bundles and loads for the first time.
6. Start coding!
Select your favorite editor, like Atom, VSCode, Sublime Text, Vim, or Emacs, open your-project/App.js, and start building! We recommend following the [Up and Running](https://docs.expo.io/versions/latest/workflow/up-and-running) tutorial.
|
JavaScript | UTF-8 | 2,597 | 2.96875 | 3 | [] | no_license | import { quarterOption, monthOption } from '../constant'
/**
* 获取从fromYear年开始到当前时间的前一年年份
* parameter 单位
*/
export const yearFromLastYear = (fromYear, parameter = '') => {
const ny = new Date().getFullYear() - 1
const yearNumber = ny - fromYear + 1
return new Array(yearNumber)
.fill(1)
.map((v, i) => {
return {
label: parameter ? ny - i + parameter : ny - i,
value: ny - i
}
})
.reverse()
}
/**
* 获取从fromYear年开始到当前时间的年分
* parameter 单位
*/
export const yearFromCurYear = (fromYear, parameter = '') => {
const ny = new Date().getFullYear()
const yearNumber = ny - fromYear + 1
return new Array(yearNumber)
.fill(1)
.map((v, i) => {
return {
label: parameter ? ny - i + parameter : ny - i,
value: ny - i
}
})
.reverse()
}
export const yearFromYear = (fromYear, parameter = '', isIncludeCurrentYear) => {
const ny = new Date().getFullYear() - (isIncludeCurrentYear ? 0 : 1)
const yearNumber = ny - fromYear + 1
return new Array(yearNumber)
.fill(1)
.map((v, i) => {
return {
label: parameter ? ny - i + parameter : ny - i,
value: ny - i
}
})
.reverse()
}
/**
* 获取从fromYear年开始到当前时间的年分
* parameter 单位
*/
export const yearFromYearTo = (fromYear, parameter = '') => {
const ny = new Date().getFullYear()
const yearNumber = ny - fromYear + 1
return new Array(yearNumber).fill(1).map((v, i) => {
return {
label: parameter ? ny - i + parameter : ny - i,
value: ny - i
}
}).reverse()
}
//isIncludeCurrentYear 是否包含当前年
export const getYearList = (isIncludeCurrentYear, selectYear) => {
let year = new Date().getFullYear() - (isIncludeCurrentYear ? 0 : 1)
let minYear = selectYear ? selectYear : 2019
let yearArr = []
while (year >= minYear) {
yearArr.push(minYear++)
}
return yearArr
}
// 判断当前季度
export const getCurrentQuerty = (month) => {
if (month >= 1 && month <= 3) {
return 1
} else if (month >= 4 && month <= 6) {
return 2
} else if (month >= 7 && month <= 9) {
return 3
} else if (month >= 10 && month <= 12) {
return 4
} else {
return false
}
}
export const getQuertyOption = (querty) => {
let temp = JSON.parse(JSON.stringify(quarterOption))
return temp.splice(0, querty)
}
// 返回月份筛选
export const getMonthOption = (month) => {
let temp = JSON.parse(JSON.stringify(monthOption))
return temp.splice(0, month)
} |
JavaScript | UTF-8 | 261 | 3.234375 | 3 | [] | no_license | 'use strict';
function indexOf(array, element, index) {
typeof index === 'undefined' || typeof index === 'string' ? index = 0 : index;
for(var i = index; i < array.length; i++){
if(array[i] === element) return i;
}
return -1;
}
|
Markdown | UTF-8 | 4,967 | 2.9375 | 3 | [] | no_license | #Welcome to the Banc Sabadell Blockchain Hackathon
This is your team's base repository for the BS Hackathon, please clone it and upload all code and project resources here.
##Our Ethereum network
In order to ease development during the event we've configured a private Ethereum network, this network is shared by all the teams and composed of several Linux virtual machines, each running a dedicated Ethereum node ([`geth`](https://github.com/ethereum/go-ethereum/wiki/geth)). Each team has access to its own unique VM:

To get a better idea of the network and its behavior you can have a look at the different network stats using our monitoring [tool](http://admin-hackathon.westeurope.cloudapp.azure.com/):

###Access to your Ethereum node
Connecting to your `geth` instance through **JSON-RPC**:
* host: `[pending]`
* port: `8545`
In case your project depends on additional software (e.g. Node) you have full access to the machine via **SSH**:
* host: `[pending]`
* user: `[pending]`
* pasword: `[pending]`
##BSToken contract

BSToken is a [digital token](https://www.ethereum.org/token) created exclusively by Banc Sabadell for this hackathon, you can integrate your Ethereum contracts with this token to create a variety of applications based on _tradable goods_ (E.g. [debt](https://forum.ethereum.org/discussion/2989/decentralized-system-for-securitizing-collateral-debt-obligations-using-the-ethereum-blockchain), [watts](http://www.coindesk.com/ethereum-used-first-paid-energy-trade-using-blockchain-technology/), etc. See [bs-scrow](https://github.com/BancoSabadell/bs-escrow) below for an example).
BSToken is implemented with a set of Solidity contracts that follow the [ERC20](https://github.com/ethereum/EIPs/issues/20) token specification:
```
// Abstract contract for the full ERC 20 Token standard
// https://github.com/ethereum/EIPs/issues/20
pragma solidity ^0.4.6;
contract Token {
function totalSupply() constant returns (uint256);
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
```
The full contract(s) source code can be found [here](https://github.com/BancoSabadell/bs-token), including an utility JavaScript library.
###Contract address
The BS Token contract is deployed at address: **`0x6c8f2a135f6ed072de4503bd7c4999a1a17f824b`**
###Accounts per team (with a 1.000 token/ether balance)
account | password
--- | ---
0x6c8f2a135f6ed072de4503bd7c4999a1a17f824b | 111111
0x6c8f2a135f6ed072de4503bd7c4999a1a17f824b | 222222
0x6c8f2a135f6ed072de4503bd7c4999a1a17f824b | 333333
0x6c8f2a135f6ed072de4503bd7c4999a1a17f824b | 444444
0x6c8f2a135f6ed072de4503bd7c4999a1a17f824b | 555555
###Sample integration (Escrow contract)
* [bs-escrow: Escrow contract and JavaScript library](https://github.com/BancoSabadell/bs-escrow)
* [bs-escrow-android-sdk: Android SDK and sample App](https://github.com/BancoSabadell/bs-escrow-android-sdk)
###Add tokens to an account using a credit card (Banking API)
If you want to add more tokens to an account or plan to accept payments in exchange of tokens we provide a simple REST API to add tokens to an account using a (test) credit card.

The API is located at: `127.0.0.1`, including de following endpoints:
**Add tokens to an account**
GET /bs_token/api/v1/cashIn
This call will return an HTML page that will inmediately redirect to the credit card payment form.
Parameters:
name | description
--- | ---
account | Ethereum address
amount | token amount _(1 BST == 1/100 EUR)_
Example ([View in browser](http://127.0.0.1/bs_token/api/v1/cashIn?amount=120&address=0x6c8f2a135f6ed072de4503bd7c4999a1a17f824b)):
http://127.0.0.1/bs_token/api/v1/cashIn?amount=120&address=0x6c8f2a135f6ed072de4503bd7c4999a1a17f824b
Test credit card:
* Number: `4548 8120 4940 0004`
* Expiry date: `12/20`
* Security code: `123`
* CIP: `123456`
##FAQ's
* **Must our project rely on the token contract?** No, we provide the token and escrow contracts as an starting point or a base for *inspiration*.
##Resources
* [Ethereum JavaScript API](https://github.com/ethereum/wiki/wiki/JavaScript-API)
* [web3.js](https://github.com/ethereum/web3.js/)
* [Solidity](http://solidity.readthedocs.io/en/develop/)
* [ERC: Token standard](https://github.com/ethereum/EIPs/issues/20)
##Contact
Need help? Contact us at: [innodev@bancsabadell.com](mailto:innodev@bancsabadell.com)
|
Python | UTF-8 | 1,553 | 2.890625 | 3 | [] | no_license | def start():
云台灯(常量.云台所有, 黄色, 常量.效果常亮)
时间.睡眠(2)
云台灯(常量.云台左, 绿色, 常量.效果熄灭)
云台灯(常量.云台右, 红色, 常量.效果熄灭)
for 序号 in range(1, 5):
云台单灯(常量.云台左, 序号 * 2 - 1, 常量.效果常亮)
云台单灯(常量.云台右, 序号 * 2, 常量.效果常亮)
时间.睡眠(1)
云台单灯(常量.云台左, 偶数, 常量.效果常亮)
云台单灯(常量.云台右, 奇数, 常量.效果常亮)
云台单灯(常量.云台左, 奇数, 常量.效果熄灭)
云台单灯(常量.云台右, 偶数, 常量.效果熄灭)
时间.睡眠(2)
def 云台单灯(位置, 序号, 灯效):
LED灯.云台单灯(位置, 序号, 灯效)
def 云台灯(位置, 颜色, 灯效):
LED灯.云台(位置, 颜色['红'], 颜色['绿'], 颜色['蓝'], 灯效)
奇数 = [1, 3, 5, 7]
偶数 = [2, 4, 6, 8]
黄色 = {'红': 255, '绿': 255, '蓝': 0}
红色 = {'红': 255, '绿': 0, '蓝': 0}
绿色 = {'红': 0, '绿': 255, '蓝': 0}
# 以下为API中文化部分, 与程序逻辑无关. 请勿作修改.
LED灯 = led_ctrl
LED灯.云台 = LED灯.set_top_led
LED灯.云台单灯 = LED灯.set_single_led
# 常量部分
常量 = rm_define
常量.云台所有 = 常量.armor_top_all
常量.云台左 = 常量.armor_top_left
常量.云台右 = 常量.armor_top_right
常量.效果常亮 = 常量.effect_always_on
常量.效果熄灭 = 常量.effect_always_off
时间 = time
时间.睡眠 = 时间.sleep |
Java | UTF-8 | 1,416 | 3.203125 | 3 | [] | no_license | package com.qa.test.Guru99Test;
import static org.junit.Assert.assertEquals;
import cucumber.api.PendingException;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class StackSteps {
private StackExample myStack;
private Object pushed;
private Object popped;
@Given("^an empty stack$")
public void an_empty_stack() {
myStack = new StackExample();
}
@When("^I push an item into the stack$")
public void i_push_an_item_into_the_stack() {
pushed = new Object();
myStack.push(pushed);
}
@Then("^the stack contains one item$")
public void the_stack_contains_one_item() {
myStack.size();
assertEquals(1,myStack.size());
}
@When("^I push another item into the stack$")
public void i_push_another_item_into_the_stack() {
myStack.push(pushed);
}
@Then("^the stack contains two items$")
public void the_stack_contains_two_items() {
myStack.size();
assertEquals(2,myStack.size());
}
@When("^I pop from the stack$")
public void i_pop_from_the_stack() {
popped = myStack.pop();
}
@Then("^I get the same item back$")
public void i_get_the_same_item_back() {
assertEquals("Not the same", pushed, popped);
}
@Given("^a stack with (\\d+) things$")
public void a_stack_with_things(int arg1){
myStack = new StackExample();
pushed = new Object();
for(int i=0;i<arg1;i++) {
myStack.push(pushed);
}
}
}
|
Python | UTF-8 | 9,472 | 2.859375 | 3 | [] | no_license | """
Sample code for using webexteamsbot
"""
import os
import requests
from webexteamsbot import TeamsBot
from webexteamsbot.models import Response
import sys
import json
# Retrieve required details from environment variables
bot_email = "smart2s@webex.bot"
teams_token = "Yjc1N2I2YTMtYjFkZi00ZGIxLTg5MjYtYTVhNDFhZTU3ZmViNDVkMDZhMTctMTAx_PF84_a892a6ed-b823-46b8-8336-847d8f4722ae"
bot_url = ""
bot_app_name = "Smartz"
# Example: How to limit the approved Webex Teams accounts for interaction
# Also uncomment the parameter in the instantiation of the new bot
# List of email accounts of approved users to talk with the bot
# approved_users = [
# "josmith@demo.local",
# ]
# If any of the bot environment variables are missing, terminate the app
if not bot_email or not teams_token or not bot_url or not bot_app_name:
print(
"sample.py - Missing Environment Variable. Please see the 'Usage'"
" section in the README."
)
if not bot_email:
print("TEAMS_BOT_EMAIL")
if not teams_token:
print("TEAMS_BOT_TOKEN")
if not bot_url:
print("TEAMS_BOT_URL")
if not bot_app_name:
print("TEAMS_BOT_APP_NAME")
sys.exit()
# Create a Bot Object
# Note: debug mode prints out more details about processing to terminal
# Note: the `approved_users=approved_users` line commented out and shown as reference
bot = TeamsBot(
bot_app_name,
teams_bot_token=teams_token,
teams_bot_url=bot_url,
teams_bot_email=bot_email,
debug=True,
# approved_users=approved_users,
webhook_resource_event=[
{"resource": "messages", "event": "created"},
{"resource": "attachmentActions", "event": "created"},
],
)
# Create a custom bot greeting function returned when no command is given.
# The default behavior of the bot is to return the '/help' command response
def greeting(incoming_msg):
# Loopkup details about sender
sender = bot.teams.people.get(incoming_msg.personId)
# Create a Response object and craft a reply in Markdown.
response = Response()
response.markdown = "Olá {}, eu sou o Smartz. Um dos robôs inteligentes desenvolvidos pela 2S baseado em Python".format(sender.firstName)
response.markdown += "Você pode escolher em que posso ajudá-lo inserindo o comando: **/help**."
return response
# Create functions that will be linked to bot commands to add capabilities
# ------------------------------------------------------------------------
# A simple command that returns a basic string that will be sent as a reply
def do_something(incoming_msg):
"""
Sample function to do some action.
:param incoming_msg: The incoming message object from Teams
:return: A text or markdown based reply
"""
return "i did what you said - {}".format(incoming_msg.text)
# This function generates a basic adaptive card and sends it to the user
# You can use Microsofts Adaptive Card designer here:
# https://adaptivecards.io/designer/. The formatting that Webex Teams
# uses isn't the same, but this still helps with the overall layout
# make sure to take the data that comes out of the MS card designer and
# put it inside of the "content" below, otherwise Webex won't understand
# what you send it.
def show_card(incoming_msg):
attachment = """
{
"contentType": "application/vnd.microsoft.card.adaptive",
"content": {
"type": "AdaptiveCard",
"body": [{
"type": "Container",
"items": [{
"type": "TextBlock",
"text": "This is a sample of the adaptive card system."
}]
}],
"actions": [{
"type": "Action.Submit",
"title": "Create",
"data": "add",
"style": "positive",
"id": "button1"
},
{
"type": "Action.Submit",
"title": "Delete",
"data": "remove",
"style": "destructive",
"id": "button2"
}
],
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"version": "1.0"
}
}
"""
backupmessage = "This is an example using Adaptive Cards."
c = create_message_with_attachment(
incoming_msg.roomId, msgtxt=backupmessage, attachment=json.loads(attachment)
)
print(c)
return ""
# An example of how to process card actions
def handle_cards(api, incoming_msg):
"""
Sample function to handle card actions.
:param api: webexteamssdk object
:param incoming_msg: The incoming message object from Teams
:return: A text or markdown based reply
"""
m = get_attachment_actions(incoming_msg["data"]["id"])
return "card action was - {}".format(m["inputs"])
# Temporary function to send a message with a card attachment (not yet
# supported by webexteamssdk, but there are open PRs to add this
# functionality)
def create_message_with_attachment(rid, msgtxt, attachment):
headers = {
"content-type": "application/json; charset=utf-8",
"authorization": "Bearer " + teams_token,
}
url = "https://api.ciscospark.com/v1/messages"
data = {"roomId": rid, "attachments": [attachment], "markdown": msgtxt}
response = requests.post(url, json=data, headers=headers)
return response.json()
# Temporary function to get card attachment actions (not yet supported
# by webexteamssdk, but there are open PRs to add this functionality)
def get_attachment_actions(attachmentid):
headers = {
"content-type": "application/json; charset=utf-8",
"authorization": "Bearer " + teams_token,
}
url = "https://api.ciscospark.com/v1/attachment/actions/" + attachmentid
response = requests.get(url, headers=headers)
return response.json()
# An example using a Response object. Response objects allow more complex
# replies including sending files, html, markdown, or text. Rsponse objects
# can also set a roomId to send response to a different room from where
# incoming message was recieved.
def ret_message(incoming_msg):
"""
Sample function that uses a Response object for more options.
:param incoming_msg: The incoming message object from Teams
:return: A Response object based reply
"""
# Create a object to create a reply.
response = Response()
# Set the text of the reply.
response.text = "Here's a fun little meme."
# Craft a URL for a file to attach to message
u = "https://sayingimages.com/wp-content/uploads/"
u = u + "aaaaaalll-righty-then-alrighty-meme.jpg"
response.files = u
return response
# An example command the illustrates using details from incoming message within
# the command processing.
def current_time(incoming_msg):
"""
Sample function that returns the current time for a provided timezone
:param incoming_msg: The incoming message object from Teams
:return: A Response object based reply
"""
# Extract the message content, without the command "/time"
timezone = bot.extract_message("/time", incoming_msg.text).strip()
# Craft REST API URL to retrieve current time
# Using API from http://worldclockapi.com
u = "http://worldclockapi.com/api/json/{timezone}/now".format(timezone=timezone)
r = requests.get(u).json()
# If an invalid timezone is provided, the serviceResponse will include
# error message
if r["serviceResponse"]:
return "Error: " + r["serviceResponse"]
# Format of returned data is "YYYY-MM-DDTHH:MM<OFFSET>"
# Example "2018-11-11T22:09-05:00"
returned_data = r["currentDateTime"].split("T")
cur_date = returned_data[0]
cur_time = returned_data[1][:5]
timezone_name = r["timeZoneName"]
# Craft a reply string.
reply = "In {TZ} it is currently {TIME} on {DATE}.".format(
TZ=timezone_name, TIME=cur_time, DATE=cur_date
)
return reply
def cotar_dolar():
#Pegando o conteúdo da página:
pagina = urllib.urlopen('http://www.bc.gov.br/htms/infecon/taxas/taxas.htm')
pagina = pagina.read()
#Obtendo o valor de compra e venda
taxa_compra, taxa_venda = re.findall('[0-9],[0-9][0-9][0-9]', pagina)
#retornand os resultados
return (taxa_compra, taxa_venda)
print cotar_dolar()
# Create help message for current_time command
current_time_help = "Look up the current time for a given timezone. "
current_time_help += "_Example: **/time EST**_"
# Set the bot greeting.
bot.set_greeting(greeting)
# Add new commands to the bot.
bot.add_command("attachmentActions", "*", handle_cards)
bot.add_command("/showcard", "show an adaptive card", show_card)
bot.add_command("/dosomething", "help for do something", do_something)
bot.add_command("/demo", "Sample that creates a Teams message to be returned.", ret_message)
bot.add_command("/time", current_time_help, current_time)
bot.add_command("/cotacao", cotar_dolar)
# Every bot includes a default "/echo" command. You can remove it, or any
# other command with the remove_command(command) method.
bot.remove_command("/echo")
if __name__ == "__main__":
# Run Bot
bot.run(host="0.0.0.0", port=5000) |
Python | UTF-8 | 8,906 | 2.75 | 3 | [] | no_license | from twisted.trial import unittest
from mdht import constants
from mdht.contact import Node
from mdht.kademlia import routing_table
from mdht.kademlia.kbucket import KBucket
from mdht.kademlia.routing_table import _TreeNode, TreeRoutingTable, \
SubsecondRoutingTable
from mdht.test import testing_data
# As long the id is unique per test case, this
# function generates non-conflicting nodes
# with proper addresses
def generate_node(id):
addr = ("127.0.0.1", id % (2**16 - 1))
return Node(id, addr)
def nodes_in_rt(rt):
kbuckets = rt.get_kbuckets()
nodes = []
for kbucket in kbuckets:
nodes.extend(kbucket.get_nodes())
return nodes
def node_id_sequence(start, stop, multiplier):
l = []
while start < stop:
l.append(start)
start *= multiplier
return l
def extract_id(node):
return node.node_id
class TreeRoutingTableTestCase(unittest.TestCase):
# The following tests required a k value of 8
# so monkey patch 8 as a hardcoded value
def setUp(self):
self.orig_k = constants.k
constants.k = 8
def tearDown(self):
constants.k = self.orig_k
def test_offer_node_oneNode(self):
rt = TreeRoutingTable(node_id=2**16)
node_accepted = rt.offer_node(generate_node(15))
self.assertTrue(node_accepted)
def test_offer_node_remove_node_get_node_sixteenNodes(self):
# Note: It is important to choose
# a proper clustering of the node IDs for the
# routing table to accept the nodes
rt = TreeRoutingTable(node_id=1)
# 2**160 / 2**156 == 2**4 == 16
# Insert nodes (offer_node)
for node_id in range(0, 2**160, 2**156):
node_accepted = rt.offer_node(generate_node(node_id + 1))
self.assertTrue(node_accepted)
self.assertEquals(16, len(nodes_in_rt(rt)))
for node in nodes_in_rt(rt):
# Retrieve nodes (get_node)
n = rt.get_node(node.node_id)
self.assertEquals(node, n)
# Remove nodes (remove_node)
node_removed = rt.remove_node(node)
self.assertTrue(node_removed)
self.assertEquals(0, len(nodes_in_rt(rt)))
def test_offer_node_properNumKBuckets(self):
rt = TreeRoutingTable(node_id=1)
# range(2, 9) generates 7 numbers
for node_id in range(2, 9):
rt.offer_node(generate_node(node_id))
rt.offer_node(generate_node(2**158))
rt.offer_node(generate_node(2**159))
self.assertEquals(2, len(rt.get_kbuckets()))
def test_get_closest_nodes_noRecursion(self):
rt = TreeRoutingTable(node_id=1)
target = 2**160 - 5
for node_id in [2, 4, 8, 2**158, 2**159]:
rt.offer_node(generate_node(node_id))
closest_nodes = rt.get_closest_nodes(target, 2)
self.assertEquals(map(extract_id, closest_nodes), [2**159, 2**158])
def test_get_closest_nodes_oneLevelRecursion(self):
rt = TreeRoutingTable(node_id=1)
target = 2**160 - 5
# 7 nodes close to the target
for node_id in node_id_sequence(2**150, 2**157, 2):
rt.offer_node(generate_node(node_id))
# 1 node close to our node id
rt.offer_node(generate_node(5))
closest_nodes = rt.get_closest_nodes(target)
expectedIDs = node_id_sequence(2**150, 2**157, 2)
expectedIDs.append(5)
expectedIDs.sort(key = lambda ID: ID ^ target)
self.assertEquals(len(expectedIDs), len(closest_nodes))
self.assertEquals(expectedIDs, map(extract_id, closest_nodes))
def test_get_closest_nodes_multiLevelRecursion(self):
rt = TreeRoutingTable(node_id=2**160-1)
target = 1
rand_list = testing_data.random_one_hundred_IDs
dist = lambda x, y: x ^ y
rand_list.sort(key = lambda ID: dist(ID, target))
expectedIDs = rand_list[:constants.k]
for ID in rand_list:
rt.offer_node(generate_node(ID))
closest_nodes = rt.get_closest_nodes(target)
self.assertEquals(expectedIDs, map(extract_id, closest_nodes))
def test_split_validNormal(self):
k = KBucket(range_min=0, range_max=32, maxsize=2)
tnode = _TreeNode(k)
tnode.kbucket.offer_node(generate_node(11))
tnode.kbucket.offer_node(generate_node(22))
rt = TreeRoutingTable(node_id=17)
rt.active_kbuckets.append(tnode.kbucket)
split_correctly = rt._split(tnode)
self.assertTrue(split_correctly)
self.assertEquals(1, len(tnode.lchild.kbucket.get_nodes()))
self.assertEquals(1, len(tnode.rchild.kbucket.get_nodes()))
self.assertFalse(tnode.is_leaf())
def test_split_invalidNotLeaf(self):
k = KBucket(range_min=0, range_max=32, maxsize=2)
tnode = _TreeNode(k)
rt = TreeRoutingTable(node_id=12)
rt.active_kbuckets.append(tnode.kbucket)
split_correctly = rt._split(tnode)
self.assertTrue(split_correctly)
# Treenode has already been split (so it isnt a leaf)
split_correctly = rt._split(tnode)
self.assertFalse(split_correctly)
def test_split_invalidNotSplittable(self):
# KBucket is too small to split
k = KBucket(range_min=0, range_max=4, maxsize=2)
tnode = _TreeNode(k)
rt = TreeRoutingTable(node_id=2)
rt.active_kbuckets.append(tnode.kbucket)
split_correctly = rt._split(tnode)
self.assertFalse(split_correctly)
def test_split_invalidNodeID(self):
k = KBucket(range_min=0, range_max=16, maxsize=2)
tnode = _TreeNode(k)
rt = TreeRoutingTable(node_id=122)
rt.active_kbuckets.append(tnode.kbucket)
# 122 doesnt fit in [0, 16)
split_correctly = rt._split(tnode)
self.assertFalse(split_correctly)
class SubsecondRoutingTableTestCase(unittest.TestCase):
# The following tests require a hardcoded
# value of constants.k = 8 to function
def setUp(self):
self.orig_k = constants.k
constants.k = 8
def tearDown(self):
constants.k = self.orig_k
# This is used as a helper function for the split
# tests below
def _split_and_assert_sizes(self, rt, tnode, lsize, rsize):
split_correctly = rt._split(tnode)
self.assertTrue(split_correctly)
lbucket = tnode.lchild.kbucket
rbucket = tnode.rchild.kbucket
self.assertEquals(lsize, lbucket.maxsize)
self.assertEquals(rsize, rbucket.maxsize)
def test_split_validLeftOneLevel(self):
# node_id 17 will cause the right kbucket to take on the larger size
rt = SubsecondRoutingTable(17)
self._split_and_assert_sizes(rt, rt.root, 8, 128)
def test_split_validRightOneLevel(self):
# node_id 2**159 + 1 will cause the
# left kbucket to take on the larger size
rt = SubsecondRoutingTable(2**159 + 1)
self._split_and_assert_sizes(rt, rt.root, 128, 8)
def test_split_validLeftAllTheWayDown(self):
# node_id 1 will cause the right kbucket to take on the larger size
rt = SubsecondRoutingTable(1)
self._split_and_assert_sizes(rt, rt.root, 8, 128)
lchild = rt.root.lchild
self._split_and_assert_sizes(rt, lchild, 8, 64)
lchild = lchild.lchild
self._split_and_assert_sizes(rt, lchild, 8, 32)
lchild = lchild.lchild
self._split_and_assert_sizes(rt, lchild, 8, 16)
lchild = lchild.lchild
self._split_and_assert_sizes(rt, lchild, 8, 8)
def test_offer_node_secondKBucketSplit(self):
# ID of 2**160 - 1 will cause KBuckets on the left
# side of the tree to expand in size (ie 128 maxsize)
rt = SubsecondRoutingTable(2**160 - 1)
# overflow first bucket
for num in range(9):
rt.offer_node(generate_node(num))
self.assertFalse(rt.root.is_leaf())
lchild = rt.root.lchild
rchild = rt.root.rchild
self.assertEquals(128, lchild.kbucket.maxsize)
self.assertEquals(8, rchild.kbucket.maxsize)
self.assertTrue(lchild.is_leaf())
self.assertTrue(rchild.is_leaf())
# overflow second bucket
for num in range(2**159, 2**159+9):
rt.offer_node(generate_node(num))
rl_child = rchild.lchild
rr_child = rchild.rchild
self.assertEquals(64, rl_child.kbucket.maxsize)
self.assertEquals(8, rr_child.kbucket.maxsize)
class TreeNodeTestCase(unittest.TestCase):
def test_is_leaf(self):
k = KBucket(range_min=0, range_max=32, maxsize=20)
tnode = _TreeNode(k)
self.assertTrue(tnode.is_leaf())
# Manually attach two new _TreeNode children
tnode.lchild = _TreeNode(k)
tnode.rchild = _TreeNode(k)
self.assertFalse(tnode.is_leaf())
|
PHP | UTF-8 | 799 | 3.03125 | 3 | [] | no_license | <?php
require_once('../database/MysqlConnection.class.php');
// Model Parent class, all model classes should extend me
// For actual production would add logging and potentially caching
class Model {
protected $table;
private $pdo;
public function __construct ($table) {
$connection = MysqlConnection::getInstance();
$this->pdo = $connection->pdo;
$this->table = $table;
}
/**
* returns an array of results from the mysql / pdo query
* @param {string} sql string
* @param {array} pdo input params
*/
public function query($sql, $untrustedParams = array()){
$stmt = $this->pdo->prepare($sql);
$stmt->execute($untrustedParams);
$result = array();
while ($row = $stmt->fetch()) {
array_push($result, $row);
}
return $result;
}
} |
Swift | UTF-8 | 7,545 | 2.96875 | 3 | [] | no_license | //
// Extensions.swift
// EsteticaFacial
//
// Created by Orlando Amorim on 15/04/16.
// Copyright © 2016 Orlando Amorim. All rights reserved.
//
import Foundation
import UIKit
import RealmSwift
extension String {
func toInt() -> Int {
return Int(self)!
}
func toDate() -> NSDate {
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale.currentLocale()
dateFormatter.dateFormat = "dd/MM/yyyy"
return dateFormatter.dateFromString(self)!
}
}
extension Int{
func toString() -> String{
return String(self)
}
}
extension UIButton {
func selectedButton(title:String, iconName: String, widthConstraints: NSLayoutConstraint){
self.backgroundColor = UIColor(red: 0, green: 118/255, blue: 254/255, alpha: 1)
self.setTitle(title, forState: UIControlState.Normal)
self.setTitle(title, forState: UIControlState.Highlighted)
self.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
self.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Highlighted)
self.setImage(UIImage(named: iconName), forState: UIControlState.Normal)
self.setImage(UIImage(named: iconName), forState: UIControlState.Highlighted)
let image = self.imageView!.frame.width
let text = (title as NSString).sizeWithAttributes([NSFontAttributeName:self.titleLabel!.font!]).width
let width = text + image + 24
//24 - the sum of your insets
widthConstraints.constant = width
self.layoutIfNeeded()
}
}
extension UIColor {
// Creates a UIColor from a Hex string.
convenience init(hexString: String) {
var cString: String = hexString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString
if (cString.hasPrefix("#")) {
cString = (cString as NSString).substringFromIndex(1)
}
if (cString.characters.count != 6) {
self.init(white: 0.5, alpha: 1.0)
} else {
let rString: String = (cString as NSString).substringToIndex(2)
let gString = ((cString as NSString).substringFromIndex(2) as NSString).substringToIndex(2)
let bString = ((cString as NSString).substringFromIndex(4) as NSString).substringToIndex(2)
var r: CUnsignedInt = 0, g: CUnsignedInt = 0, b: CUnsignedInt = 0;
NSScanner(string: rString).scanHexInt(&r)
NSScanner(string: gString).scanHexInt(&g)
NSScanner(string: bString).scanHexInt(&b)
self.init(red: CGFloat(r) / CGFloat(255.0), green: CGFloat(g) / CGFloat(255.0), blue: CGFloat(b) / CGFloat(255.0), alpha: CGFloat(1))
}
}
}
extension UIImage {
func isEqualToImage(image: UIImage) -> Bool {
guard let data1 = UIImagePNGRepresentation(self),
data2 = UIImagePNGRepresentation(image)
else { return false }
return data1.isEqualToData(data2)
}
}
extension UINavigationController {
func progress(progressView: UIProgressView) {
self.view.addSubview(progressView)
let navBar = self.navigationBar
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[navBar]-0-[progressView]", options: .DirectionLeadingToTrailing, metrics: nil, views: ["progressView" : progressView, "navBar" : navBar]))
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[progressView]|", options: .DirectionLeadingToTrailing, metrics: nil, views: ["progressView" : progressView]))
progressView.translatesAutoresizingMaskIntoConstraints = false
if progressView.progress == 1.0 {
progressView.hidden = true
}
}
func progressQuant(count: Int) {
let progressView = UIProgressView()
self.view.addSubview(progressView)
let navBar = self.navigationBar
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[navBar]-0-[progressView]", options: .DirectionLeadingToTrailing, metrics: nil, views: ["progressView" : progressView, "navBar" : navBar]))
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[progressView]|", options: .DirectionLeadingToTrailing, metrics: nil, views: ["progressView" : progressView]))
progressView.translatesAutoresizingMaskIntoConstraints = false
if progressView.progress == 1.0 {
progressView.hidden = true
}
}
}
extension UIAlertController {
class func alertControllerWithTitle(title:String, message:String) -> UIAlertController {
let controller = UIAlertController(title: title, message: message, preferredStyle: .Alert)
controller.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
return controller
}
class func alertControllerWithNoCancel(title:String, message:String) -> UIAlertController {
let controller = UIAlertController(title: title, message: message, preferredStyle: .Alert)
return controller
}
class func alertControllerWithNumberInput(title:String, message:String, buttonTitle:String, handler:(Int?)->Void) -> UIAlertController {
let controller = UIAlertController(title: title, message: message, preferredStyle: .Alert)
controller.addTextFieldWithConfigurationHandler { $0.keyboardType = .NumberPad }
controller.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
controller.addAction(UIAlertAction(title: buttonTitle, style: .Default) { action in
let textFields = controller.textFields! as [UITextField]
let value = Int(textFields[0].text!)
handler(value)
} )
return controller
}
}
extension UIApplication {
class func topViewController(base: UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController) -> UIViewController? {
if let nav = base as? UINavigationController {
return topViewController(nav.visibleViewController)
}
if let tab = base as? UITabBarController {
if let selected = tab.selectedViewController {
return topViewController(selected)
}
}
if let presented = base?.presentedViewController {
return topViewController(presented)
}
return base
}
}
extension NSValue {
func toString() -> String{
return String(self)
}
}
extension Array where Element : Equatable {
// Remove first collection element that is equal to the given `object`:
mutating func removeObject(object : Generator.Element) {
if let index = self.indexOf(object) {
self.removeAtIndex(index)
}
}
}
//Swift 3
//extension Array where Element: Equatable {
//
// // Remove first collection element that is equal to the given `object`:
// mutating func removeObject(object: Element) {
// if let index = index(of: object) {
// remove(at: index)
// }
// }
//}
extension NSBundle {
var releaseVersionNumber: String? {
return self.infoDictionary?["CFBundleShortVersionString"] as? String
}
var buildVersionNumber: String? {
return self.infoDictionary?["CFBundleVersion"] as? String
}
}
|
TypeScript | UTF-8 | 1,931 | 2.625 | 3 | [
"MIT"
] | permissive | export const cpuUsage = `top -bn 1 -i | awk -F ',' 'NR == 3 {print $4}' | awk '{printf "CPU: \{ used: %s \}\\n", 100-$1}'`
export const ramUsage = `top -bn 1 -i | awk '{if (NR == 4) printf "RAM: { free: %s, used: %s, cache: %s }\\n", $6, $8, $10}'`
export const netUsage = `old="$(</sys/class/net/eth0/statistics/tx_bytes)"; $(sleep 1); now=$(</sys/class/net/eth0/statistics/tx_bytes); awk -v now=$now -v old=$old 'BEGIN{printf "%.2fkb/s\\n", (now-old)/1024*8}'`
export const diskUsage = `iostat -d | awk '{if (NR == 4) printf "ROM: \{ read: %s, write: %s \}\\n", $3, $4}'`
const getNetworkCard = () => {
return `ls /sys/class/net`
}
const getNetAutoUnitUsage = (
inOrOut: 'rx' | 'tx',
NIC = 'eth0',
interval = '1'
) => {
return `old="$(</sys/class/net/${NIC}/statistics/${inOrOut}_bytes)"; $(sleep ${interval}); now=$(</sys/class/net/${NIC}/statistics/${inOrOut}_bytes); awk -v now=$now -v old=$old 'BEGIN {kbs = (now - old)/1024*8; if (kbs/1024 >= 1000) printf "%.2fGb/s\\n", kbs/1024/1024; else if (kbs >= 1000) printf "%.2fMb/s\\n", kbs/1024; else printf "%.2fKb/s\\n", kbs}'`
}
const getNetBytesUsage = (
inOrOut: 'rx' | 'tx',
NIC = 'eth0',
interval = '1'
) => {
return `old="$(</sys/class/net/${NIC}/statistics/${inOrOut}_bytes)"; $(sleep ${interval}); echo \`expr $(</sys/class/net/${NIC}/statistics/${inOrOut}_bytes) - $old\``
}
const getNetUsage = (NIC = 'eth0', interval = '0.5') => {
return `oldTx="$(</sys/class/net/${NIC}/statistics/tx_bytes)" oldRx="$(</sys/class/net/${NIC}/statistics/rx_bytes)"; $(sleep ${interval}); echo "NET: { tx: \`expr $(</sys/class/net/${NIC}/statistics/tx_bytes) - $oldTx\`, rx: \`expr $(</sys/class/net/${NIC}/statistics/rx_bytes) - $oldRx\` }"`
}
const shellAllInOne = (NIC = 'eth0', interval = '0.5') => {
return (
cpuUsage +
'&&' +
ramUsage +
'&&' +
getNetUsage('eth0', '0.5') +
'&&' +
diskUsage
)
}
export { shellAllInOne }
|
Java | UTF-8 | 2,232 | 2.453125 | 2 | [] | no_license | package com.notification.challenge.dao;
import static org.junit.Assert.assertEquals;
import java.util.Date;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.runners.MockitoJUnitRunner;
import com.notification.challenge.controllers.UserRequest;
import com.notification.challenge.controllers.UserResponse;
@RunWith(MockitoJUnitRunner.class)
public class UserRepositoryImplTest {
@InjectMocks
private UserRepositoryImpl userRepo;
private UserRequest userReq1;
private UserRequest userReq2;
private UserResponse user1;
private UserResponse user2;
@Before
public void setup() {
userReq1 = new UserRequest();
userReq1.setAccessToken("accessToken1");
userReq1.setUsername("user1");
userReq2 = new UserRequest();
userReq2.setAccessToken("accessToken2");
userReq2.setUsername("user2");
user1 = new UserResponse();
user1.setAccessToken("accessToken1");
user1.setCreationTime(new Date());
user1.setEmail("email1@domain.com");
user1.setNumOfNotificationsPushed(new AtomicLong(0));
user1.setUsername("user1");
user2 = new UserResponse();
user2.setAccessToken("accessToken2");
user2.setCreationTime(new Date());
user2.setEmail("email2@domain.com");
user2.setNumOfNotificationsPushed(new AtomicLong(0));
user2.setUsername("user2");
}
@Test
public void getUser_shouldSucceed() {
userRepo.registerUser(user1);
userRepo.registerUser(user2);
UserResponse userResponse1 = userRepo.getUser("user1");
UserResponse userResponse2 = userRepo.getUser("user2");
assertUser(user1, userResponse1);
assertUser(user2, userResponse2);
}
@Test(expected=IllegalArgumentException.class)
public void getUser_shouldThrowException() {
userRepo.registerUser(user1);
userRepo.getUser("user2");
}
private void assertUser(UserResponse expected, UserResponse actual) {
assertEquals(expected.getAccessToken(), actual.getAccessToken());
assertEquals(expected.getCreationTime(), actual.getCreationTime());
assertEquals(expected.getEmail(), actual.getEmail());
assertEquals(expected.getNumOfNotificationsPushed(), actual.getNumOfNotificationsPushed());
}
}
|
Python | UTF-8 | 441 | 2.640625 | 3 | [
"MIT"
] | permissive | import numpy as np
from abc import ABCMeta, abstractmethod
class BaseResizer(metaclass=ABCMeta):
def __init__(self, out_size: list or tuple):
"""
:param out_size: (width, height)
"""
self._out_size = out_size
@abstractmethod
def __call__(self, inputs, teachers) -> tuple:
"""
:param inputs:
:param teachers:
:return: (inputs, teachers)
"""
pass
|
Java | UTF-8 | 547 | 2.046875 | 2 | [] | no_license | package stepDefinations;
import java.io.IOException;
import io.cucumber.java.Before;
public class CucumberHooks {
@Before //before condition of Cucumber and not junit
public void beforeScenario() throws IOException {
//execute this code only when place id is null
LoginStepDefination sd = new LoginStepDefination();
if(LoginStepDefination.place_id==null) {
sd.add_place_payload_with("Megharaj", "Kannada", "Kundapura");
sd.user_calls_the_with_http_request("addPlaceAPI", "post");
sd.extract_the_value("place_id");
}
}
}
|
Python | UTF-8 | 1,176 | 3.1875 | 3 | [] | no_license | import pygame
from bird import bird
from pipeManager import pipeManager
import time
pygame.init()
width = 1440
height = 800
black = (0,0,0)
bird_x = 300
bird_y = 400
clock = pygame.time.Clock()
#make the pygame window
display_surface = pygame.display.set_mode((width, height))
birdy = bird(bird_x, bird_y)
pipeManager = pipeManager(width, height)
# def collision(bird, pipe):
# for p in pipe.pipeList:
# if bird.bird_x == (p.position[0] - pipe.pipew):
# if p.direction == "bottom" and bird.bird_y >= p.position[1]:
# if p.direction == "top" and bird.bird_y <= p.grow:
# return True
# return False
while (True):
display_surface.fill(black)
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
if birdy.bird_y <= 0 or birdy.bird_y >= height:
print("You Lose!!!")
break
elif pipeManager.collision(birdy):
print("Collision!!!")
break
birdy.draw(display_surface)
birdy.update()
pipeManager.draw(display_surface)
pipeManager.manage()
pygame.display.update()
clock.tick(30)
pygame.quit()
|
Java | UTF-8 | 3,419 | 3.75 | 4 | [] | no_license | package model;
import iterator.Iterator;
import iterator.IteratorContainer;
import observer.Observer;
import observer.Subject;
import java.util.ArrayList;
public class Playlist implements Subject, IteratorContainer {
private String title;
private ArrayList<Song> songs;
private ArrayList<Observer> observers;
/**
* Constructor
*/
public Playlist() {
songs = new ArrayList<Song>();
observers = new ArrayList<Observer>();
}
/**
* Add a song to the playlist.
*
* @param song The song to add.
*/
public void addSong(Song song) {
this.songs.add(song);
}
/**
* Get all the songs that are in the playlist.
*
* @return Arraylist with all the songs.
*/
public ArrayList<Song> getSongs() {
return songs;
}
/**
* Get the title of the playlist.
*
* @return The title of the playlist.
*/
public String getTitle() {
return this.title;
}
/**
* Set the title of the playlist.
*
* @param title Title of the playlist.
*/
public void setTitle(String title) {
this.title = title;
}
/**
* Notify all our observers who are observing the playlist.
*/
public void notifyObservers() {
System.out.print(this.observers);
for (Observer observer : this.observers)
{
observer.update();
}
}
/**
* Register a new observer.
*
* @param observer The observer to register.
*/
public void registerObserver(Observer observer)
{
observer.setPlaylist(this);
this.observers.add(observer);
}
/**
* Remove an observer.
*
* @param observer The observer to remove.
*/
public void removeObserver(Observer observer)
{
this.observers.remove(observer);
}
/**
* Get the playlist iterator.
*
* @return The iterator.
*/
public PlaylistIterator getIterator() {
return new PlaylistIterator();
}
/**
* Iterator class for the songs in the playlist.
*/
private class PlaylistIterator implements Iterator {
int index;
/**
* Check if a next song is available.
*
* @return Returns true when a next song is available.
*/
public boolean hasNext() {
if (index < songs.size()) {
return true;
} else {
return false;
}
}
/**
* Check if a previous song is available.
*
* @return Returns true when a previous song is available.
*/
public boolean hasPrevious() {
if (index > songs.size()) {
return true;
} else {
return false;
}
}
/**
* Get the next object.
*
* @return The next song.
*/
public Object next() {
if (this.hasNext()) {
return songs.get(index++);
}
return null;
}
/**
* Get the previous object.
*
* @return The previous song.
*/
public Object previous() {
if (this.hasPrevious()) {
return songs.get(index--);
}
return null;
}
}
}
|
Java | UTF-8 | 763 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | package com.xiaogua.better.reflect;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
public class TestGetClassCode {
@Test
public void testGetClass() throws Exception {
Class<?> clz = this.getClass();
System.out.println(clz);// TestGetClassCode
Object obj = this.getClass().newInstance();
if (obj instanceof Object) {
System.out.println("obj instanceof Object");
}
TestGetClassCode thisClz = this.getClass().newInstance();
System.out.println(thisClz);
}
@Test
public void testGetClassName() {
List<String> list = new ArrayList<String>();
System.out.println(list.getClass());
Assert.assertEquals("java.util.ArrayList", list.getClass().getName());
}
}
|
Python | UTF-8 | 417 | 2.78125 | 3 | [] | no_license | import csv
openFile = open('/Users/leoniekruger/Downloads/VOCS2016-2017-HOUSEHOLD/VOCS2016-2017-HOUSEHOLD_F1.csv', 'r')
csvFile = csv.reader(openFile)
header = next(csvFile)
headers = map((lambda x: ''+x+'`'), header)
insert = 'INSERT INTO Table (' + ", ".join(headers) + ") VALUES "
for row in csvFile:
values = map((lambda x: '"'+x+'"'), row)
print (insert +" ("+ ", ".join(values) +");" )
openFile.close() |
Java | ISO-8859-1 | 3,577 | 2.921875 | 3 | [] | no_license | package Controleur;
import Modele.Commande;
import Modele.Objet;
import Vue.Screen;
import Vue.ScreenObserver;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import javax.swing.JFileChooser;
/**
* partie contrleur du mvc : prend en charge la gestion des vnements pour
* mettre jour la vue ou le modle et les synchroniser
* Sur ce Control2, le client n'a plus besoin de rappuyer sur le bouton pour
* mettre jour automatiquement les rsultats des traitements
* lors d'un changement d'un rpertoire ou un fichier diffrent.
*
* @author GR03
*/
public class Control2 {
Screen screen;
Objet obj;
JFileChooser m_chooser;
ScreenObserver so;
ArrayList<Class<?>> commandes;
boolean b1 = false;
boolean b2 = false;
boolean b3 = false;
public Control2(Screen s, Objet o, ArrayList<Class<?>> c) {
this.screen = s;
this.obj = o;
this.commandes = c;
m_chooser = new JFileChooser();
m_chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
// add listener to the view
screen.addTraitement1Listener(new Traitement1Listener());
screen.addTraitement2Listener(new Traitement2Listener());
screen.addTraitement3Listener(new Traitement3Listener());
screen.addSelectListener(new SelectListener());
so = new ScreenObserver(obj, s);
}
public void apply(int n){
Class<?> t = commandes.get(n);
Commande com = null;
try {
com = (Commande) t.newInstance();
com.setObjet(obj);
} catch (InstantiationException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IllegalAccessException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
obj.setCommand(com);
obj.applyCommand();
}
/**
* gestion de l'vnement du traitement1
*/
class Traitement1Listener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("traitement1");
apply(0);
b1 = true;
}
}
/**
* gestion de l'vnement du traitement2
*/
class Traitement2Listener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("traitement2");
apply(1);
b2=true;
}
}
/**
* gestion de l'vnement du traitement3
*/
class Traitement3Listener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("traitement3");
apply(2);
b3=true;
}
}
/**
* gre la slection d'un fichier ou d'un dossier avec un JFileChooser
*/
class SelectListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// Handle open button action.
if (e.getSource() == screen.getSelectButton()) {
int returnVal = m_chooser.showOpenDialog(screen
.getSelectButton());
if (returnVal == JFileChooser.APPROVE_OPTION) {
obj.setFile(m_chooser.getSelectedFile());
obj.setObserver(so);
obj.getObserver().selectedFile();
// This is where a real application would open the file.
System.out.println("Opening: " + obj.getFile().getName()+ ".");
if(b1==true){
apply(0);
}
if(b2==true){
apply(1);
}
if(b3==true){
apply(2);
}
} else {
System.out.println("Open command cancelled by user.");
}
// log.setCaretPosition(log.getDocument().getLength());
}
}
}
} |
C | UTF-8 | 419 | 2.875 | 3 | [] | no_license | #include <stdio.h>
int main()
{
int i,j,t;
scanf("%d",&t);
for(i=0;i<t;i++)
{
int ng,nm,maxg=0,maxm=0,temp;
scanf("%d",&ng);
scanf("%d",&nm);
for(j=0;j<ng;j++)
{
scanf("%d",&temp);
if(temp>maxg) maxg=temp;
}
temp=0;
for(j=0;j<nm;j++)
{
scanf("%d",&temp);
if(temp>maxm) maxm=temp;
}
if(maxm>maxg) printf("MechaGodzilla\n");
else printf("Godzilla\n");
}
return 0;
}
|
Java | UTF-8 | 621 | 1.9375 | 2 | [] | no_license | package com.facebook.profilo.core;
public final class TraceEvents {
public static boolean sInitialized;
public static int sLastNameRefreshProvidersState;
public static volatile int sProviders;
public static native void nativeClearAllProviders();
public static native int nativeDisableProviders(int i);
public static native int nativeEnableProviders(int i);
public static native void nativeRefreshProviderNames(int[] iArr, String[] strArr);
public static boolean isEnabled(int i) {
if ((i & sProviders) != 0) {
return true;
}
return false;
}
}
|
PHP | UTF-8 | 636 | 2.609375 | 3 | [] | no_license | <?php
/**
* Verifcacion el login
*/
require("dbConex.php");
class dbverficacion_login extends conex{
/**************************
* VERIFICAICION DEL LOGIN
**************************/
public $estado;
public $correo;
public $id;
function dbverificacion($user,$pass){
$Verif=mysql_query("select * from persona");
while ($Dato=mysql_fetch_array($Verif)) {
if ($Dato['correo'] == $user && $Dato['clave'] == $pass) {
$this->estado="true";
$this->correo=$Dato['correo'];
$this->noA=$Dato['nombre']." ".$Dato['apellido'];
$this->id=$Dato['id'];
break;
}else{
$this->estado="false";
}
}
}
}
?> |
Java | UTF-8 | 527 | 2.390625 | 2 | [] | no_license | package com.blackflight.dof.data.entity;
import com.blackflight.clean.data.entity.DataEntity;
import java.util.UUID;
/**
* Created by peter on 11-11-16.
*/
public class BodyEntity implements DataEntity<UUID> {
private final UUID mId;
private final UUID mBodyTypeId;
public BodyEntity(UUID id, UUID bodyTypeId) {
mId = id;
mBodyTypeId = bodyTypeId;
}
@Override
public UUID getId() {
return mId;
}
public UUID getBodyTypeId() {
return mBodyTypeId;
}
}
|
C# | UTF-8 | 8,998 | 2.734375 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using TheBank.DAL;
using TheBank.Model;
using TheBank.Model.DataContainer.Account;
namespace DAL
{
public class DBStub : IDB
{
/*
* Not part of obligatory #2
*/
public bool changeTransaction(TransactionPresentation tp)
{
throw new NotImplementedException();
}
/*
* Not part of obligatory #2
*/
public byte[] Create_Hash(string inString)
{
throw new NotImplementedException();
}
/*
* Not part of obligatory #2
*/
public string Create_Salt()
{
throw new NotImplementedException();
}
/*
* Not part of obligatory #2
*/
public int deleteTransaction(int tID)
{
throw new NotImplementedException();
}
/*
* This stub will return a boolean value to simulate the success or lack of success regarding
* the deletion of a user in the database.
*/
public bool deleteUser(string pID)
{
if(pID == null)
{
return false;
}
else
{
return true;
}
}
/*
* This stub will return a boolean value to stimulate the success of lack of success regarding
* the deletion of an account in the database.
*/
public bool deactivateAccount(string accountName)
{
if(accountName == null)
{
return false;
}
else if(accountName == "no balance")
{
return false;
}
else
{
return true;
}
}
/*
* This stub returns a boolean value to emulate a successful or unsuccessful edit
* of account information.
*/
public bool editAccount (string accountNumber, string accountName)
{
if(accountNumber == null || accountName == null)
{
return false;
}
else
{
return true;
}
}
/*
* This stub returns a boolean value to emulate a successful or unsuccessfull edit
* of a users information.
*/
public bool editUser(Customer inCustomer)
{
if(inCustomer == null)
{
return false;
}
else
{
return true;
}
}
/*
* This stub will return one of three strings depending on what the input is.
*/
public string executeTransaction(int transactionID)
{
if(transactionID == 0)
{
return "Already Transferred!";
}
else if(transactionID == 1)
{
return "Not enough money";
}
else
{
return "ok";
}
}
/*
* Not part of obligatory #2
*/
public AccountPresentation getAccountData(string inAccountNumber, string inPersonalIdentification)
{
throw new NotImplementedException();
}
/*
* Making a list consisting of three customers
*/
public List<Customer> getAllCustomers()
{
List<Customer> custList = new List<Customer>();
Customer cust1 = new Customer();
Customer cust2 = new Customer();
Customer cust3 = new Customer();
// Customer 1
cust1.personalIdentification = "11223344551";
cust1.firstname = "Knut";
cust1.lastname = "Iversen";
cust1.address = "Trondheimgate 3";
cust1.zipCode = "0101";
cust1.city = "Trondheim";
cust1.phoneNumber = "11223344";
cust1.email = "knut.iversen@gmail.com";
custList.Add(cust1);
// Customer 2
cust2.personalIdentification = "22334455667";
cust2.firstname = "Lise";
cust2.lastname = "Iversen";
cust2.address = "Oslogate 3";
cust2.zipCode = "0202";
cust2.city = "Oslo";
cust2.phoneNumber = "22334455";
cust2.email = "lise.iversen@gmail.com";
custList.Add(cust2);
// Customer 3
cust3.personalIdentification = "33445566778";
cust3.firstname = "Arild";
cust3.lastname = "Iversen";
cust3.address = "Stavangergate 3";
cust3.zipCode = "0303";
cust3.city = "Stavanger";
cust3.phoneNumber = "33445566";
cust3.email = "arild.iversen@gmail.com";
custList.Add(cust3);
return custList;
}
/*
* Returning a list of TransactionPresentation with three Transactions.
*
*/
public List<TransactionPresentation> listTransactions(bool isTransferred)
{
List <TransactionPresentation> tpList = new List<TransactionPresentation>();
TransactionPresentation tp1 = new TransactionPresentation();
TransactionPresentation tp2 = new TransactionPresentation();
TransactionPresentation tp3 = new TransactionPresentation();
// First transaction
tp1.ID = 1;
tp1.date = "07.11.2016";
tp1.amount = 100.00;
tp1.message = "This is the first transaction";
tp1.toAccount = "22222222222";
tp1.fromAccount = "11111111111";
tpList.Add(tp1);
// Second transaction
tp2.ID = 2;
tp2.date = "07.11.2016";
tp2.amount = 200.00;
tp2.message = "This is the second transaction";
tp2.toAccount = "33333333333";
tp2.fromAccount = "22222222222";
tpList.Add(tp2);
// Thirs transaction
tp3.ID = 3;
tp3.date = "07.11.2016";
tp3.amount = 300.00;
tp3.message = "This is the third transaction";
tp3.toAccount = "44444444444";
tp3.fromAccount = "33333333333";
tpList.Add(tp3);
return tpList;
}
/*
* Recives a string and uses that string to return an array of strings with user information.
*
*/
public string[] getUserInfo(string pID)
{
// Check if the personal identification is empty (not existing).
if (pID == null)
{
return null;
}
// Creates an array of strings with user info.
else
{
string[] userInfo = new string[8];
userInfo[0] = pID;
userInfo[1] = "Synne";
userInfo[2] = "Sørensen";
userInfo[3] = "synne.sorensen@gmail.com";
userInfo[4] = "Bodøgate 3";
userInfo[5] = "999887766";
userInfo[6] = "8909";
userInfo[7] = "Bodø";
return userInfo;
}
}
/*
* Not part of obligatory #2
*/
public List<AccountPrimitive> listAccountPrimitive(string pID)
{
List<AccountPrimitive> userAccounts = new List<AccountPrimitive>();
userAccounts.Add(new AccountPrimitive("11111111111", "Konto 1", 100, true));
userAccounts.Add(new AccountPrimitive("22222222222", "Konto 2", 2100, true));
userAccounts.Add(new AccountPrimitive("33333333333", "Konto 3", 3100, true));
return userAccounts;
}
/*
* Not part of obligatory #2
*/
public List<TransactionPresentation> listTransactions(string accountNumber, int inMonth, int inYear, bool isTransferred)
{
throw new NotImplementedException();
}
public void logErrorToFile(Exception e)
{
throw new NotImplementedException();
}
/*
* Not part of obligatory #2
*/
public int produceRandomNumber()
{
throw new NotImplementedException();
}
/*
* Not part of obligatory #2
*/
public bool registerTransaction(TransactionPresentation inTransaction)
{
throw new NotImplementedException();
}
/*
* Not part of obligatory #2
*/
public string[] validateUser(string pID, string password)
{
if(pID == "11111111111" && password == "pass")
{
return new string[1];
}
else
{
return null;
}
}
}
}
|
Ruby | UTF-8 | 3,502 | 2.890625 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require_relative 'scraping'
require_relative 'urls'
require_relative 'brewery/beer_list'
module RateBeer
# The brewery class represents one brewery found in RateBeer, with methods
# for accessing information found about the brewery on the site.
module Brewery
class Brewery
# Each key represents an item of data accessible for each beer, and defines
# dynamically a series of methods for accessing this data.
#
def self.data_keys
[:name,
:type,
:address,
:telephone,
:beers]
end
include RateBeer::Scraping
include RateBeer::URLs
attr_reader :established, :location
# CSS selector for the brewery information element.
INFO_SELECTOR = "div[itemtype='http://schema.org/LocalBusiness']".freeze
# Create RateBeer::Brewery instance.
#
# Requires the RateBeer ID# for the brewery in question. Optionally accepts
# a name parameter where the name is already known.
#
# @param [Integer, String] id ID# for the brewery
# @param [String] name The name of the specified brewery
# @param [hash] options Options hash for entity created
#
def initialize(id, name: nil, **options)
super
if options
@established = options[:established]
@location = options[:location]
@type = options[:type]
@status = options[:status]
end
end
def doc
@doc ||= noko_doc(URI.join(BASE_URL, brewery_url(id)))
validate_brewery
@doc
end
def info_root
@info_root ||= doc.at_css(INFO_SELECTOR)
end
private
# Validates whether the brewery with the given ID exists.
#
# Throws an exception if the brewery does not exist.
def validate_brewery
error_message = "This brewer, ID##{id}, is no longer in the database. "\
'RateBeer Home'
if @doc.at_css('body p').text == error_message
raise PageNotFoundError.new("Brewery not found - #{id}")
end
end
# Scrapes the brewery's name.
def scrape_name
@name = fix_characters(info_root.css('h1').first.text)
end
# Scrapes the brewery's address.
def scrape_address
address_root = info_root.css('div[itemprop="address"] b span')
address_details = address_root.map { |e| extract_address_element(e) }
@address = address_details.to_h
end
# Extracts one element of address details from a node contained within the
# address div.
def extract_address_element(node)
key = case node.attributes['itemprop'].value
when 'streetAddress' then :street
when 'addressLocality' then :city
when 'addressRegion' then :state
when 'addressCountry' then :country
when 'postalCode' then :postcode
else raise 'unrecognised attribute'
end
[key, node.text.strip]
end
# Scrapes the telephone number of the brewery.
def scrape_telephone
@telephone = info_root.at_css('span[itemprop="telephone"]')
end
# Scrapes the type of brewery.
def scrape_type
@type = info_root.css('div')[1]
end
# Scrapes beers list for brewery.
def scrape_beers
@beers = BeerList.new(self).beers
end
end
end
end
|
Markdown | UTF-8 | 3,917 | 3.046875 | 3 | [] | no_license | # Data flow analysis POC
## Copy Analysis
**CopyToAnalysis** is a dataflow analysis to track `AnalysisEntity` instances that share the same value or reference.
### Examples
```
var x = new MyClass();
object y = x;
```
In this case there will be two `AnalysisEntity` instances, one for `x` and one for `y` and `CopyAnalysis` will compute that variables `x` and `y` have identical `CopyAbstractValue` with `CopyAbstractValueKind.KnownReferenceCopy`.
```
int c1 = 0;
int c2 = c1;
```
In this case it will compute that `c1` and `c2` have identical `CopyAbstractValue` with `CopyAbstractValueKind.KnownValueCopy`.
### Cons
According to documentation, **CopyAnalysis** is currently off by default for all analyzers as it has known performance issues and needs performance tuning. It can be enabled by end users with **editorconfig** option **copy_analysis**.
## Points-To Analysis (a.k.a. alias analysis or pointer analysis)
PointsToAnalysis: Dataflow analysis to track locations pointed to by AnalysisEntity and IOperation instances. This is the most commonly used dataflow analysis in all our flow based analyzers/analyses.
- `AnalysisEntity` - an `ISymbol` OR one or more `AbstractIndex` indices to index into the parent entity OR "this" instance OR An allocation or an object creation. Each `AnalysisEntity` has a type and an InstanceLocation.
- `IOperation` - Root type for representing the abstract semantics of C# and VB statements and expressions [source](https://github.com/dotnet/roslyn/blob/version-2.9.0/src/Compilers/Core/Portable/Operations/IOperation.cs). 2.6.1 is the recommended minimum version with first fully supported IOperation release [source](https://github.com/dotnet/roslyn/issues/19014#issuecomment-418149014).
### Example
```
var x = new MyClass();
object y = x;
var z = flag ? new MyClass() : y;
```
**PointsToAnalysis** will compute that variables `x` and `y` have identical non-null `PointsToAbstractValue`, which contains a single `AbstractLocation` corresponding to the first `IObjectCreationOperation` for `new MyClass()`.
Variable `z` has a different `PointsToAbstractValue`, which is guaranteed to be non-null, but has two potential `AbstractLocation`, one for each `IObjectCreationOperation` in the above code.
### Usage details
From my tests, you get a `PointsToAbstractValue` for a given `IOperation` (interesting `IOperations` would be `LocalReference`, `ParameterReference`, `FieldReference`, `PropertyReference` etc).
The `PointsToAbstractValue` has a list of `AbstractLocations`. Inside the locations, the interesting information seems to be in the `AnalysisEntityOpt` which has the `Symbol`; or `CreationOpt` which points to the creation of an object.
It can also tell whether the value is Null.
## Property Set Analysis
Dataflow analysis to track values assigned to one or more properties of an object to identify and flag incorrect/insecure object state.
Currently the API is internal and cannot be used outside `roslyn-analyzers`.
## Value Content Analysis
Dataflow analysis to track possible constant values that might be stored in an AnalysisEntity and IOperation instances. This is identical to constant propagation for constant values stored in non-constant symbols.
Consider the following example:
```
int c1 = 0;
int c2 = 0;
int c3 = c1 + c2;
```
`ValueContentAnalysis` will compute that variables `c1`, `c2` and `c3` have identical `ValueContentAbstractValue` with a single literal value `0`.
Consider the following example:
```
var c = flag == 1 ? ""a"" : ""b"";
var d = c;
```
`ValueContentAnalysis` will compute that `flag == 1 ? "a" : "b"` and variables `d` and `c` have identical `ValueContentAbstractValue` with multiple literal values `"a"` and `"b"`.
## References
[Well-known flow analyses](https://github.com/dotnet/roslyn-analyzers/blob/master/docs/Writing%20dataflow%20analysis%20based%20analyzers.md#well-known-flow-analyses)
|
C | UTF-8 | 1,067 | 3.03125 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <signal.h>
int quitflag = 0;
sigset_t mask;
pthread_cond_t waitloc = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* thr_fn(void* arg)
{
int err,signo;
while(1)
{
err = sigwait(&mask,&signo);
if(err != 0)
exit(-1);
switch(signo)
{
case SIGQUIT:
pthread_mutex_lock(&mutex);
quitflag = 1;
pthread_cond_signal(&waitloc);
pthread_mutex_unlock(&mutex);
return 0;
case SIGINT:
printf("\ninterrupt\n");
break;
default:
printf("unexpected signal %d\n",signo);
exit(1);
}
}
}
int main()
{
int err;
sigset_t oldset;
pthread_t tid;
sigemptyset(&mask);
sigaddset(&mask,SIGQUIT);
sigaddset(&mask,SIGINT);
err = pthread_sigmask(SIG_BLOCK,&mask,&oldset);
err = pthread_create(&tid,NULL,thr_fn,NULL);
pthread_mutex_lock(&mutex);
while(quitflag == 0)
pthread_cond_wait(&waitloc,&mutex);
pthread_mutex_unlock(&mutex);
quitflag = 0;
err = pthread_sigmask(SIG_SETMASK,&oldset,NULL);
exit(0);
}
|
Java | UTF-8 | 7,555 | 2.21875 | 2 | [] | no_license | package com.mobileapplicationdev.lab1;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class EditProfile extends AppCompatActivity {
private static final String TAG = "Lab1";
private static final String NAME = "name";
private static final String MAIL = "mail";
private static final String BIO = "bio";
private static final String IMAGE = "image";
private static final int TAKE_PICTURE_REQUEST_CODE = 1;
private static final int CHOOSE_PICTURE_REQUEST_CODE = 2;
private Uri fileUri;
private SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_edit_profile);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Restore saved values
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
restoreValues(sharedPreferences);
//Add a listener on the button to take a photo
Button takePictureButton = (Button) findViewById(R.id.take_picture);
takePictureButton.setOnClickListener(new View.OnClickListener() {
private Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
@Override
public void onClick(View view) {
fileUri = getOutputMediaFileUri(); //Create a file to store the photo
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); //Set the image file name
startActivityForResult(intent, TAKE_PICTURE_REQUEST_CODE); //Launch the camera app
}
}); //End of the listener
//Add a listener on the button to choose a picture
Button choosePictureButton = (Button) findViewById(R.id.choose_picture);
choosePictureButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent choosePictureIntent = new Intent(Intent.ACTION_GET_CONTENT);
choosePictureIntent.setType("image/*");
startActivityForResult(choosePictureIntent, CHOOSE_PICTURE_REQUEST_CODE);
}
}); //End of listener
} //End of onCreate
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_edit_profile, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
if(menuItem.getItemId() == R.id.action_save) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(NAME, ((EditText)findViewById(R.id.name)).getText().toString());
editor.putString(MAIL, ((EditText)findViewById(R.id.mail)).getText().toString());
editor.putString(BIO, ((EditText) findViewById(R.id.bio)).getText().toString());
if (fileUri != null)
editor.putString(IMAGE, fileUri.toString());
editor.commit();
Log.d(TAG, "Saved");
finish();
return true;
}
return super.onOptionsItemSelected(menuItem);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK) {
Log.d(TAG, "result_ok");
if (requestCode == CHOOSE_PICTURE_REQUEST_CODE) {
fileUri = data.getData();
}
setImage(fileUri);
} else if(resultCode == RESULT_CANCELED) {
Log.d(TAG, "result canceled");
}
}
private void setImage(Uri uri) {
Log.d(TAG, "uri = " + uri);
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
} catch (IOException e) {
e.printStackTrace();
}
if (bitmap == null)
Log.d(TAG, "bitmap null");
else {
Matrix matrix = new Matrix();
matrix.postRotate(90);
Bitmap small = Bitmap.createScaledBitmap(bitmap, 800, 600, false);
Bitmap rotated = Bitmap.createBitmap(small, 0, 0, small.getWidth(), small.getHeight(), matrix, true);
((ImageView) findViewById(R.id.image)).setImageBitmap(rotated);
Log.d(TAG, "image set");
}
}
private File getOutputMediaFile() {
File mediaStorageDir = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "Lab1");
if(!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "failed to create directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG" + timeStamp + ".jpg");
return mediaFile;
}
private Uri getOutputMediaFileUri() {
return Uri.fromFile(getOutputMediaFile());
}
@Override
public void onSaveInstanceState(Bundle b) {
b.putString(NAME, ((EditText) findViewById(R.id.name)).getText().toString());
b.putString(MAIL, ((EditText) findViewById(R.id.mail)).getText().toString());
b.putString(BIO, ((EditText) findViewById(R.id.bio)).getText().toString());
if (fileUri != null) {
b.putString(IMAGE, fileUri.toString());
} else {
b.putString(IMAGE, null);
}
Log.d(TAG, "Values saved");
}
@Override
public void onRestoreInstanceState(Bundle b) {
((EditText)findViewById(R.id.name)).setText(b.get(NAME).toString());
((EditText)findViewById(R.id.mail)).setText(b.get(MAIL).toString());
((EditText)findViewById(R.id.bio)).setText(b.get(BIO).toString());
Object obj = b.get(IMAGE);
if (obj != null) {
fileUri = Uri.parse(obj.toString());
Log.d(TAG, "uri restored = " + fileUri);
setImage(fileUri);
}
}
public void restoreValues(SharedPreferences sharedPreferences) {
//Restore saved values
String name = sharedPreferences.getString(NAME, null);
String mail = sharedPreferences.getString(MAIL, null);
String bio = sharedPreferences.getString(BIO, null);
String uri = sharedPreferences.getString(IMAGE, null);
if (name != null)
((EditText)findViewById(R.id.name)).setText(name);
if (mail != null)
((EditText)findViewById(R.id.mail)).setText(mail);
if (bio != null)
((EditText)findViewById(R.id.bio)).setText(bio);
if (uri != null & fileUri == null) {
fileUri = Uri.parse(uri);
setImage(fileUri);
}
}
}
|
C | UTF-8 | 747 | 2.875 | 3 | [] | no_license | #include<sys/types.h>
#include<sys/socket.h>
#include<netdb.h>
#include<string.h>
size_t rio_readn(int fd, void *usrbuf, size_t n){
size_t nleft = n;
size_t nread;
char *bufp = usrbuf;
while(nleft>0){
if((nread = read(fd, bufp, nleft))<0){
if(errno == EINTR){
nread = 0; // 被中断
}else{
return -1;
}
}else if(nread == 0){
break;
}
nleft -= nread;
bufp += nread;
}
return (n - nleft);
}
size_t rio_writen(int fd, void *usrbuf, size_t n){
size_t nleft = n;
size_t nwritten;
char *bufp = usrbuf;
while(nleft>0){
if((nwritten = write(fd, bufp, nleft))<=0){
if(errno == EINTR){
nwritten = 0; // 被中断
}else{
return -1;
}
}
nleft -= nwritten;
bufp += nwritten;
}
return n;
}
|
Python | UTF-8 | 1,428 | 3.1875 | 3 | [] | no_license | import time
print('# TCP')
print('TCP---client')
# # 导入socket库
# import socket
#
# # 创建一个socket
# # AF_INET指定使用IPv4协议; SOCK_STREAM指定使用面向流的TCP协议
# socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#
# # 建立连接
# # 80端口是Web服务的标准端口
# # connect()参数是一个tuple,包含地址host和端口号port
# socket.connect(('www.baidu.com', 80))
#
# # 发送请求,要求返回首页的内容
# # send(data[, flags]) -> count
# #
# # Send a data string to the socket. For the optional flags
# # argument, see the Unix manual. Return the number of(...的数量) bytes
# # sent; this may be less than len(data) if the network is busy.
# socket.send(b'GET / HTTP/1.1\r\nHost: www.baidu.com\r\nConnection: close\r\n\r\n')
#
# # 接受数据
# buffter = []
# while True:
# # 每次最多接收1K字节,直到recv()返回空数据,表示接收完毕,退出循环
# d = socket.recv(1024)
# if d:
# buffter.append(d)
# else:
# break
# data = b''.join(buffter)
#
# # 关闭连接
# socket.close()
#
# # 分离data中的HTTP头、网页
# header, html = data.split(b'\r\n\r\n', 1)
# print('header :', header.decode('utf-8'))
# # 把接收的数据写入文件
# with open('baidu.html', 'wb') as f:
# f.write(html)
print('TCP---server')
# 代码详见echo_server.py / tcp_client.py
|
Java | UTF-8 | 310 | 2.21875 | 2 | [] | no_license | package br.com.negocio;
/**
*
* @author WILL-PC
*/
public interface ListaDupla {
public void adicionar(Object objeto);
public void adicionar(Object objeto, Integer posicao);
public Boolean remover(Integer posicao);
public String inverso();
public Boolean existe(Object objeto);
}
|
TypeScript | UTF-8 | 2,425 | 2.734375 | 3 | [] | no_license | import { Injectable, Inject } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
class Users{
fname: string;
lname: string;
email: string;
password: string;
constructor(fn: string, ln:string, e:string, p:string){
this.fname= fn;
this.lname= ln;
this.email=e;
this.password=p;
}
}
@Injectable()
export class UsersService{
auth: any;
users: Users[]=[];
signup(fn: string, ln:string, e:string, p:string)
{
if (!e || !p) {
alert('email and password required');
}
//Register user in Firebase
this.auth.createUserWithEmailAndPassword(e, p)
.catch(function(error) {
console.log('Error in Registeration', error);
});
this.users.push(new Users(fn, ln, e, p));
localStorage.setItem("users",JSON.stringify(this.users));
localStorage.setItem("login","true");
localStorage.setItem("current_email",e);
alert("Registered");
}
constructor(private router: Router){
this.auth= firebase.auth();
}
signIn(e: string, p:string)
{
localStorage.setItem("login","false");
let eIn = e;
let pIn= p;
// SignIn Using Firebase
this.auth.signInWithEmailAndPassword(e, p)
.then(
(success) => {
localStorage.setItem("login","true");
localStorage.setItem("current_user",this.users[i].fname);
localStorage.setItem("current_email",this.users[i].email);
alert("Signed In!!");
this.router.navigate(['']); //----> navigate to main page after success
}).catch(function(error) {
console.log('signIn error', error);
});
//Localhost
this.users = JSON.parse(localStorage.getItem("users"));
if (this.users != null) {
for (var i = 0; i < this.users.length; i++) {
if (this.users[i].email === eIn && this.users[i].password === pIn) {
localStorage.setItem("login","true");
localStorage.setItem("current_user",this.users[i].fname);
localStorage.setItem("current_email",this.users[i].email);
alert("Signed In!!");
}
}
if (localStorage.getItem("login") === "false") {
alert("Please Enter right details or Sign up!");
}
}
else{
alert('Please Enter right details or Sign up!');
}
}
} |
JavaScript | UTF-8 | 1,040 | 2.625 | 3 | [
"MIT"
] | permissive | // addEventBinder
// --------------
//
// Mixes in Backbone.Events to the target object, if it is not present
// already. Also adjusts the listenTo method to accept a 4th parameter
// for the callback context.
(function(Backbone, Marionette, _){
// grab a reference to the original listenTo
var listenTo = Backbone.Events.listenTo;
// Fix the listenTo method on the target object, allowing the 4th
// context parameter to be specified
Marionette.addEventBinder = function(target){
// If the target is not already extending Backbone.Events,
// then extend that on to it first
if (!target.on && !target.off && !target.listenTo && !target.stopListening){
_.extend(target, Backbone.Events);
}
// Override the built-in listenTo method to make sure we
// account for context
target.listenTo = function(evtSource, events, callback, context){
context = context || this;
return listenTo.call(this, evtSource, events, _.bind(callback, context));
};
};
})(Backbone, Marionette, _);
|
C++ | UTF-8 | 540 | 2.78125 | 3 | [] | no_license | #pragma once
#include "unit.h"
#include <memory>
#include <string>
class ClassUnit;
class MethodUnit;
class PrintOperatorUnit;
class AbstractFactory
{
public:
virtual std::shared_ptr<ClassUnit> CreateClassUnit(const std::string& name) const = 0;
virtual std::shared_ptr<MethodUnit> CreateMethodUnit(const std::string& name, const std::string& returnType, Unit::Flags flags) const = 0;
virtual std::shared_ptr<PrintOperatorUnit> CreatePrintOperator(const std::string& text) const = 0;
virtual ~AbstractFactory() {}
};
|
Python | UTF-8 | 1,740 | 3.09375 | 3 | [
"BSD-2-Clause"
] | permissive | # -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
# Name: immutable
# Purpose: Abstract base class for immutable objects.
#
# Author: Michael Amrhein (michael@adrhinum.de)
#
# Copyright: (c) 2014 ff. Michael Amrhein
# License: This program is part of a larger application. For license
# details please read the file LICENSE.TXT provided together
# with the application.
# ----------------------------------------------------------------------------
# $Source$
# $Revision$
"""Abstract base class for immutable objects."""
from abc import ABCMeta
from collections import Set
from numbers import Number
class Immutable(metaclass=ABCMeta):
"""Abstract base class for immutable objects.
Note: This class is used to register classes that create immutable
instances as virtual subclasses. It does not make instances immutable!"""
__slots__ = ()
def __copy__(self) -> 'Immutable':
"""copy(self)"""
return self
def __deepcopy__(self) -> 'Immutable':
"""deepcopy(self)"""
return self
Immutable.register(Number) # type: ignore
Immutable.register(bytes) # type: ignore
Immutable.register(str) # type: ignore
Immutable.register(Set) # type: ignore
def is_immutable(obj: object) -> bool:
"""Return True if obj is immutable, otherwise False."""
if isinstance(obj, tuple):
try:
hash(obj)
except TypeError:
return False
else:
return True
return isinstance(obj, Immutable)
def immutable(cls: type) -> type:
"""Register `cls` as class creating immutable objects."""
Immutable.register(cls) # type: ignore
return cls
|
Python | UTF-8 | 11,439 | 3.078125 | 3 | [] | no_license | # Author: Robert Guthrie
import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import sys, getopt, re, nltk, timeit, random
torch.manual_seed(1)
random.seed(6)
RRule = random.random()
######################################################################
'''
word_to_ix = {"hello": 0, "world": 1}
embeds = nn.Embedding(2, 5) # 2 words in vocab, 5 dimensional embeddings
lookup_tensor = torch.LongTensor([word_to_ix["world"]])
hello_embed = embeds(autograd.Variable(lookup_tensor))
print(hello_embed)
'''
######################################################################
# An Example: N-Gram Language Modeling
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Recall that in an n-gram language model, given a sequence of words
# :math:`w`, we want to compute
#
# .. math:: P(w_i | w_{i-1}, w_{i-2}, \dots, w_{i-n+1} )
#
# Where :math:`w_i` is the ith word of the sequence.
#
# In this example, we will compute the loss function on some training
# examples and update the parameters with backpropagation.
#
CONTEXT_SIZE = 2
EMBEDDING_DIM = 10
# We will use Shakespeare Sonnet 2
test_sentence = """START_OF_SENTENCE The mathematician ran .
START_OF_SENTENCE The mathematician ran to the store .
START_OF_SENTENCE The physicist ran to the store .
START_OF_SENTENCE The philosopher thought about it .
START_OF_SENTENCE The mathematician solved the open problem . """.split()
# The mathematician ran to the store . The physicist ran to the store . The philosopher thought about it . The mathematician solved the open problem .
# we should tokenize the input, but we will ignore that for now
# build a list of tuples. Each tuple is ([ word_i-2, word_i-1 ], target word)
trigrams = [([test_sentence[i], test_sentence[i + 1]], test_sentence[i + 2])
for i in range(len(test_sentence) - 2)]
# print the first 3, just so you can see what they look like
#print(trigrams)
vocab = set(test_sentence)
# this is the sequence of word.
word_to_ix = {word: i for i, word in enumerate(vocab)}
print("This is the check List",word_to_ix)
class NGramLanguageModeler(nn.Module):
def __init__(self, vocab_size, embedding_dim, context_size):
super(NGramLanguageModeler, self).__init__()
self.embeddings = nn.Embedding(vocab_size, embedding_dim)
self.linear1 = nn.Linear(context_size * embedding_dim, 128)
self.linear2 = nn.Linear(128, vocab_size)
def forward(self, inputs):
embeds = self.embeddings(inputs).view((1, -1))
out = F.relu(self.linear1(embeds))
out = self.linear2(out)
log_probs = F.log_softmax(out, dim=1)
return log_probs
losses = []
loss_function = nn.NLLLoss()
model = NGramLanguageModeler(len(vocab), EMBEDDING_DIM, CONTEXT_SIZE)
# 用初始化的纬度和内容数量建立 model
optimizer = optim.SGD(model.parameters(), lr=0.1)
for epoch in range(10):
total_loss = torch.Tensor([0])
random.shuffle(trigrams, lambda: RRule)
for context, target in trigrams:
# Step 1. Prepare the inputs to be passed to the model (i.e, turn the words
# into integer indices and wrap them in variables)
context_idxs = [word_to_ix[w] for w in context] # word index
context_var = autograd.Variable(torch.LongTensor(context_idxs))
# Step 2. Recall that torch *accumulates* gradients. Before passing in a
# new instance, you need to zero out the gradients from the old
# instance
model.zero_grad()
# Step 3. Run the forward pass, getting log probabilities over next
# words
log_probs = model(context_var)
# Step 4. Compute your loss function. (Again, Torch wants the target
# word wrapped in a variable)
loss = loss_function(log_probs, autograd.Variable(
torch.LongTensor([word_to_ix[target]])))
#print(target, '+++++oooooooo')
# Step 5. Do the backward pass and update the gradient
loss.backward()
optimizer.step()
total_loss += loss.data
losses.append(total_loss)
#print(losses) # The loss decreased every iteration over the training data!
# The mathematician ran to the store .
check_sentence = """START_OF_SENTENCE The mathematician ran to the store . """.split()
check_trigrams = [([check_sentence[i], check_sentence[i + 1]], check_sentence[i + 2])
for i in range(len(check_sentence) - 2)]
check_vocab = set(check_sentence)
check_word_to_ix = {word: i for i, word in enumerate(check_vocab)}
# check_context_idxs = [word_to_ix['The'],word_to_ix['mathematician']] # word index
# check_context_var = autograd.Variable(torch.LongTensor(check_context_idxs))
# print(model(check_context_var))
# print(word_to_ix)
# print('=================================')
# print(check_trigrams)
check_context_idxs = [word_to_ix['START_OF_SENTENCE'],word_to_ix['The']] # word index
check_context_var = autograd.Variable(torch.LongTensor(check_context_idxs))
print(model(check_context_var))
print(word_to_ix)
print('=================================')
print(check_trigrams)
for context, target in check_trigrams:
print('=================================')
print('context is',context)
check_context_idxs = [word_to_ix[w] for w in context] # word index
check_context_var = autograd.Variable(torch.LongTensor(check_context_idxs))
print('----------------------------')
print('target is', target)
print('----------------------------')
log_probs = model(check_context_var)
print(log_probs)
# sortedList, indices = torch.sort(log_probs)
# print(sortedList)
# print(indices)
# print(word_to_ix[torch.max(indices)],'[][][][][]')
print(word_to_ix)
print('=================================')
print('NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN')
print('EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE')
mathematician_var = autograd.Variable(torch.LongTensor([word_to_ix['mathematician']]))
mathematician = model.embeddings(mathematician_var)
checkList = ['physicist','philosopher']
checkVar = [autograd.Variable(torch.LongTensor([word_to_ix[item]])) for item in checkList]
# physicist_var = autograd.Variable(torch.LongTensor([word_to_ix['physicist']]))
# physicist_embedding = model.embeddings(physicist_var)
# philosopher_var = autograd.Variable(torch.LongTensor([word_to_ix['philosopher']]))
# philosopher_embedding = model.embeddings(philosopher_var)
similarityList = [torch.nn.functional.cosine_similarity(mathematician,model.embeddings(item)) for item in checkVar]
print('The result is:')
# similarity_with_physicist = torch.nn.functional.cosine_similarity(mathematician_embedding,physicist_embedding)
# similarity_with_philosopher = torch.nn.functional.cosine_similarity(mathematician_embedding,philosopher_embedding)
print('The similarity of "physicist" and "mathematician" is :',similarityList[0])
print('The similarity of "philosopher" and "mathematician" is :',similarityList[1])
print('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
print('TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT')
print('=================================')
CONTEXT_SIZE = 2 # 2 words to the left, 2 to the right
'''raw_text = """We are about to study the idea of a computational process.
Computational processes are abstract beings that inhabit computers.
As they evolve, processes manipulate other abstract things called data.
The evolution of a process is directed by a pattern of rules
called a program. People create programs to direct processes. In effect,
we conjure the spirits of the computer with our spells.""".split()
'''
raw_text = """The mathematician ran .
The mathematician ran to the store .
The physicist ran to the store .
The philosopher thought about it .
The mathematician solved the open problem .""".split()
# By deriving a set from `raw_text`, we deduplicate the array
vocab = set(raw_text)
vocab_size = len(vocab)
word_to_ix = {word: i for i, word in enumerate(vocab)}
data = []
for i in range(2, len(raw_text) - 2):
context = [raw_text[i - 2], raw_text[i - 1],
raw_text[i + 1], raw_text[i + 2]]
target = raw_text[i]
data.append((context, target))
print(data[:5])
class CBOW(nn.Module):
def __init__(self, vocab_size, embedding_dim):
super(CBOW,self).__init__()
self.embeddings = nn.Embedding(vocab_size,embedding_dim)
self.linear = nn.Linear(embedding_dim, vocab_size)
def forward(self, inputs):
embeds = self.embeddings(inputs)
sum_embedding = torch.sum(embeds, dim=0).view(1,-1)
Linear3 = self.linear(sum_embedding)
log_probs = F.log_softmax(Linear3, dim=1)
return log_probs
# create your model and train. here are some functions to help you make
# the data ready for use by your module
def make_context_vector(context, word_to_ix):
idxs = [word_to_ix[w] for w in context]
return torch.LongTensor(idxs)
losses1 = []
loss_function = nn.NLLLoss()
model = CBOW(len(vocab), EMBEDDING_DIM)
# 用初始化的纬度和内容数量建立 model
optimizer = optim.SGD(model.parameters(), lr=0.1)
for epoch in range(10):
total_loss = torch.Tensor([0])
random.shuffle(trigrams, lambda: RRule)
for context, target in data:
# Step 1. Prepare the inputs to be passed to the model (i.e, turn the words
# into integer indices and wrap them in variables)
context_idxs = [word_to_ix[w] for w in context] # word index
context_var = autograd.Variable(torch.LongTensor(context_idxs))
# Step 2. Recall that torch *accumulates* gradients. Before passing in a
# new instance, you need to zero out the gradients from the old
# instance
model.zero_grad()
# Step 3. Run the forward pass, getting log probabilities over next
# words
log_probs = model(context_var)
# Step 4. Compute your loss function. (Again, Torch wants the target
# word wrapped in a variable)
loss = loss_function(log_probs, autograd.Variable(
torch.LongTensor([word_to_ix[target]])))
#print(target, '+++++oooooooo')
# Step 5. Do the backward pass and update the gradient
loss.backward()
optimizer.step()
total_loss += loss.data
losses.append(total_loss)
make_context_vector(data[0][0], word_to_ix) # example
mathematician_var = autograd.Variable(torch.LongTensor([word_to_ix['mathematician']]))
mathematician = model.embeddings(mathematician_var)
checkList = ['physicist','philosopher']
checkVar = [autograd.Variable(torch.LongTensor([word_to_ix[item]])) for item in checkList]
# physicist_var = autograd.Variable(torch.LongTensor([word_to_ix['physicist']]))
# physicist_embedding = model.embeddings(physicist_var)
# philosopher_var = autograd.Variable(torch.LongTensor([word_to_ix['philosopher']]))
# philosopher_embedding = model.embeddings(philosopher_var)
similarityList = [torch.nn.functional.cosine_similarity(mathematician,model.embeddings(item)) for item in checkVar]
print('The result is:')
# similarity_with_physicist = torch.nn.functional.cosine_similarity(mathematician_embedding,physicist_embedding)
# similarity_with_philosopher = torch.nn.functional.cosine_similarity(mathematician_embedding,philosopher_embedding)
print('The similarity of "physicist" and "mathematician" is :',similarityList[0])
print('The similarity of "philosopher" and "mathematician" is :',similarityList[1])
|
Ruby | UTF-8 | 1,486 | 2.859375 | 3 | [
"MIT"
] | permissive | # encoding: utf-8
module Stefon
# The editor is responsible for forming a team of surveyors and
# asking for and combining their results. The editor decides what story
# to run, i.e. to print recommendations or why recommendations are impossible
class Editor
attr_reader :options, :team
attr_accessor :errors
def initialize(options)
@options = options
# currently unused
@errors = []
# The editor has a team of surveyors, and tells them their importance
@team = [
Surveyor::AddedFiles.new(options[:added_file]),
Surveyor::AddedLines.new(options[:added_line]),
Surveyor::DeletedFiles.new(options[:deleted_file]),
Surveyor::DeletedLines.new(options[:deleted_line])
]
end
def combine_short_reports
@team.reduce(Surveyor::SurveyorStore.new) do |a, e|
a.merge_scores(e.call)
end
end
def short_report
combine_short_reports.sort_by { |k, v| -v }
end
def combine_full_reports
@team.reduce(Surveyor::SurveyorStore.new([])) do |a, e|
a.merge_scores(e.call_verbose)
end
end
def full_report
# sort by the scores
combine_full_reports.sort_by { |k, v| -combine_short_reports[k] }
end
def summarize_results
if @options[:full_report]
full_report.first(@options[:limit]).map(&:last).flatten
else
short_report.first(@options[:limit]).map(&:first).flatten
end
end
end
end
|
C++ | UTF-8 | 2,441 | 3.796875 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <stack>
using namespace std;
template <typename StateType>
class Machine
{
public:
typedef StateType State;
typedef std::stack<Machine<State> *, std::vector<Machine<State> *>> Stack;
Machine (Stack &stack) : stack_ (stack) {}
void start () { stack_.push (this); entered (); }
void finish () { stack_.pop (); exited (); }
virtual void entered () const {}
virtual void exited () const {}
virtual void turn (State &state) = 0;
private:
Stack &stack_;
};
template <typename Machine>
class Engine
{
public:
typedef typename Machine::State State;
typedef typename Machine::Stack Stack;
Engine() : machine_ (stack_) { machine_.start(); }
bool turn (State &state)
{
stack_.top()->turn (state);
return !stack_.empty();
}
private:
Stack stack_;
Machine machine_;
};
class PrintMachine : public Machine<int>
{
public:
PrintMachine (Stack &stack) : Machine<int> (stack) {}
void entered () const { cout << "current state: "; }
void exited () const { cout << endl; }
void turn (int &state) { cout << state; ++state; finish(); }
};
class MyMachine : public Machine<int>
{
public:
enum { STATE1, STATE2, STATE3, STATE4 };
MyMachine (Stack &stack) :
Machine<int> (stack),
printer1_ (stack),
printer2_ (stack),
printer3_ (stack) {}
void turn (int &globalstate)
{
switch (globalstate)
{
case 0: localstate_ = STATE1; break;
case 1: localstate_ = STATE2; break;
case 2: localstate_ = STATE3; break;
case 3: localstate_ = STATE4; break;
}
switch (localstate_)
{
case STATE1: printer1_.start(); break;
case STATE2: printer2_.start(); break;
case STATE3: printer3_.start(); break;
case STATE4: finish(); break;
}
}
private:
PrintMachine printer1_;
PrintMachine printer2_;
PrintMachine printer3_;
int localstate_;
};
int main ()
{
int state = 0;
Engine <MyMachine> statemachine;
while (statemachine.turn (state));
return 0;
}
|
Markdown | UTF-8 | 53,555 | 2.71875 | 3 | [] | no_license | # K8S概念
[TOC]
## 大纲
### 组件
#### Master组件
1. api server:Kubernetes API的实现
2. etcd :存储集群数据
3. scheduler:负责Pods的调度,运行在哪些节点上
4. controler manager:控制器集合
1. Node Controller:当节点下线时,负责通知以及响应。
2. Replication Controller:维护Pods的正确数量
3. Endpoints Controller:填充终端对象
4. Service Account & Token Controller:负责新命名空间的账号创建以及API访问Token
#### Node组件
1. kubelet:运行在每个节点上,负责容器的创建以及健康检查。
2. kubeproxy:网络代理,负责Pods与内部或外部的通信。
3. 容器运行时:运行容器的软件
#### 插件
1. DNS
2. Dashboard
3. 监控
4. 集群日志
### API
### K8S对象
**是一些持久化实体对象,用来描述集群状态。**
1. 哪些程序运行在哪些节点上。
2. 这些程序可以使用哪些资源。
3. 以及这些程序的运行策略,例如,重启,升级,容错等。
**一个K8S对象是一个“意图记录”,描述了集群的期望状态。**一旦创建就会永久运行。
**每个对象包括2个内嵌对象,管理着对象的配置。**
1. spec:用户提供,描述了对象的期望状态。
2. status:K8S提供,描述了对象的实际状态。
**K8S永远管理着这些对象的实际状态,以匹配用户的期望状态。**
描述一个K8S对象:
```yml
apiVersion: apps/v1 # for versions before 1.9.0 use apps/v1beta2
kind: Deployment
metadata:
name: nginx-deployment
spec:
selector:
matchLabels:
app: nginx
replicas: 2 # tells deployment to run 2 pods matching the template
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.7.9
ports:
- containerPort: 80
```
#### 必须字段
1. apiVersion:使用哪个版本的API。
2. kind:对象类型。
3. matadata:对象元数据,用于标志对象的唯一性。
4. spec:描述对象的期望状态。
### K8S对象管理
一个Kubernetes对象应只用一种管理技术,混合使用会出现不可预料的结果。
#### 编程式命令
```shell
kubectl run nginx --image=nginx #会在未来移除kubectl run --generator=deployment/apps.v1 is DEPRECATED and will be removed in a future version. Use kubectl run --generator=run-pod/v1 or kubectl create instead.
kubectl create deployment nginx --image=nginx
```
**对比对象配置的优势:**
1. 简单,易于学习,易于记忆。
2. 只需一个步骤就能对集群做出改变。
**对比对象配置的劣势:**
1. 不能与审查过程集成。
2. 不能提供审计轨迹跟踪。
3. 不能提供记录源。
4. 不能提供对象创建模板。
#### 编程式对象配置
注意:不适用独立于配置文件更新的资源对象,也就是不能用配置文件进行静态更新的资源。
例如:负载均衡器。
```shell
kubectl create -f nginx.yml
kubectl delete -f nginx.yml -f redis.yml
kubectl replace -f nginx.yml
```
**对比编程式命令的优势:**
1. 对象配置能使用版本控制保存。
2. 能集成review以及audit过程。
3. 提供了对象模板。
**对比编程式命令的劣势:**
1. 需要理解基础的对象模式。
2. 需要编写额外的yml文件。
**对比声明式对象配置的优势:**
1. 简单,易于理解。
2. 表现的更自然。
**对比声明式对象配置的劣势:**
1. 只能在文件上工作,不能在目录上工作。
2. 对象的更新只能反映的配置文件中,下次替换会丢失。
#### 声明式对象配置
```shell
kubectl diff -f .
kubectl apply -f .
kubectl diff -R -f .
kubectl apply -R -f .
```
**对比对象配置的优势:**
1. 保留变更历史,即使文件未合并。
2. 更好的支持目录,以及自动检测操作类型。
**对比对象配置的劣势:**
1. 难以调试以及理解。(非常难。。。。)
2. 部分更新会变得复杂。
### 名称
1. 名称:每个命名空间中的每种资源下每个对象的名字唯一。由客户命名。namespace/kind/name
2. UID:集群中每个对象拥有唯一的UID。由系统生成。用于区分同一对象的历史纪录。
### 命名空间
**同一物理集群下的不同虚拟集群称之为命名空间。**
#### 何时使用
多用户跨多个团队或者项目时使用,几个或者几十个的不要考虑。
命名空间提供了名称作用域,命名空间不能嵌套。
在多用户下,命名空间用于划分集群资源。
未来版本中,命名空间会统一对象的访问控制策略。
资源的名称在命名空间中需要唯一,每个资源只能在一个命名空间下,区分资源优先考虑标签。
#### 使用命名空间
```shell
kubectl get namespaces
kubectl create namespace my-namespace
kubectl run nginx --namespace=my-namespace --image=nginx
kubectl create deployment nginx --image nginx --namespace=my-namespace
kubectl get deployment -n my-namespace
kubectl get pods -n my-namespace
kubectl delete namespace my-namespace
kubectl create namespace hiscat
kubectl config set-context --current --namespace=hiscat
kubectl config view --minify
```
#### 默认命名空间
1. default:所有没有命名空间的对象都在这里。
2. kube-system:kubernetes系统创建的对象都在这里。
3. kube-pulibc:整个集群中可见的公共资源都放这里,只是一个通俗的约定并不是强制性。
#### 命名空间与DNS
创建服务时会默认创建一个DNS入口。DNS:服务名.命名空间.svc.cluster.local
意味着,如果容器使用服务名,将会解析到本地命名空间下的服务。
如果要跨多命名空间使用相同的配置则需要全限定域名(FQDN)。
#### 并不是所有的对象都有命名空间
大多数kubernetes对象都有命名空间,例如service,pod,deployment,replication,controller等。
但是命名空间本身不属于命名空间,以及节点,持久化卷都没有命名空间。
```shell
kubectl api-resources --namespaced=true
kubectl api-resources --namesapced=false
```
### 标签以及选择器
#### 标签是什么
metadata.labels节点下的键值对,用于指定识别属性,有意义且与用户相关,并不意味着核心系统的语义。
用于组织以及选择一组子对象。可以在对象创建时附加也可以后续修改。每个key必须唯一。
标签允许高效的查询和监听,最适合UI以及命令行使用。非识别信息应使用注释。
#### 动机
1. 以松散耦合的方式映射自己特有的组织结构到对象上,而不需要客户端存储这些映射。
2. 跨多维度实体操作。
#### 语法
**prefix/label**:
prefix:可选前缀,如果有必须是DNS子域名,总长不能超过253个字符,用点拆分子域名。
label: 63及位以内数字字母开头或结尾,中间可用数字字母,下划线,横杠,点
如果省略前缀,则默认key为用户私有。
自动化系统组件或第三方插件必须指定前缀。
kubernetes.io/或者k8s.io保留给K8S核心组件。
**value:**
63个字符及以内,数字字母开头或结尾,中间可用-_.
#### 选择器
通过标签选择器可以识别一组对象。标签选择器是kubernetes的核心分组原语。
目前支持2种选择器:等价性选择器,集合选择器。
一个选择器可以由多个条件组成,用逗号分隔。每个逗号相当于逻辑与运算符。
空的选择器或未指定的选择器取决于上下文,使用选择器的API类型,应当记录他们的有效性以及含义。
某些选择器,选择的资源不能重叠,例如ReplicaSet。
#### 相等选择器
=,==,!=
```shell
kubectl get pods -l app=nginx
kubectl get pods -l app!=nginx
```
#### 集合选择器
in,notin,exists
```shell
kubectl get pods -l 'app in (nginx,redis)'
kubectl get pods -l 'app notin (redis)'
kubectl get pods -l 'app'
```
#### 在API对象中设置引用
Service以及ReplicationController可以在selector自动引用其他资源,但只支持等价性选择器。
```yml
apiVersion: v1
kind: Service
metadata:
name: nginx-service
spec:
selector:
app: nginx
type: LoadBalancer
ports:
- port: 80
targetPort: 80
```
**Job,Deployment,Replica Set,Daemon支持集合选择器。**
**支持等价性选择器。**
selector:
matchLabels:
enviroment: development
**支持集合选择器,操作符有In,NotIn,Exists,DoesNotExist**
matchExpressions:
- key: tier
operator: In
values:
- frontend
```yml
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
spec:
replicas: 2
selector:
matchLabels:
enviroment: development
matchExpressions:
- key: tier
operator: In
values:
- frontend
template:
metadata:
labels:
enviroment: development
tier: frontend
spec:
containers:
- name: nginx-dev
image: nginx
```
**节点选择器**
### 注释
#### 是什么
**也是对象的元数据,用于附加非识别性数据。**客户端以及工具可以检索此数据。
#### 何时使用
1. 配置默认值。
2. 构建信息,版本号,时间戳,分支号,镜像哈希,镜像注册地址等。
3. 日志,监控,分析或审计的仓库地址。
4. 用于工具或客户端的调试信息。
5. 引用信息(引用地址),引用了其他生态系统的组件等。
6. 轻量级滚动升级工具的元数据。
7. 负责人的手机号,座机号,或者团队的网站等信息。
8. 使用了非标准特性或修改了用户行为的指令。
#### 语法
1. 键值对
2. 键:prefix/name。跟标签一样的规则。
3. 值:value。没有限定。
### 字段选择器
#### 是什么
**通过资源的字段名进行过滤。**
**所有的资源都支持metadata.name以及metadata.namespace字段选择器。**
**如果使用不支持的字段选择器会报错。**
```shell
kubectl get pods --all-namspaces --field-selector status.phase=Running
kubectl get pods --field-selector ''
```
**支持的操作符:=,!=,==。**
**可以链式选择,用逗号分隔。**
**可以选择多资源类型。**
```shell
kubectl get pods --all-namespace --field-selector status.phase=Running,spec.restartPolicy=Always
kubectl get statefulsets,svc --all-namespace --field-selector metadata.namespace=default
```
### 建议标签
**使用一组常见的标签使得工具具有更好的互操作性,并且易于理解。**
**建议化的标签能更好的查询应用。**
元数据是围绕应用程序的概念进行组织的,K8S不提供也不强制实施应用程序的概念。
应用是非正式且以元数据进行描述的,应用程序内容的定义是松散的。
#### 常用标签
| Key | 描述 | 案例 | 类型 |
| ---------------------------- | ------------------ | ------------- | ------ |
| app.kubernetes.io/name | 应用名称 | mysql | string |
| app.kubernetes.io/instance | 唯一的实例名称 | rbac-10.2.2.3 | string |
| app.kubernetes.io/version | 版本号 | 1.0.0 | string |
| app.kubernetes.io/component | 架构组件 | database | string |
| app.kubernetes.io/part-of | 所属高层应用名 | hiscat | string |
| app.kubernetes.io/managed-by | 管理应用操作的工具 | helm | string |
```yml
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app.kubernetes.io/name: disvoery
app.kubernetes.io/instance: discovery-deployment
app.kubernetes.io/version: 1.0.0
app.kubernetes.io/component: discovery
app.kubernetes.io/part-of: hiscat-blog
```
#### 应用程序以及应用程序实例
在集群中一个应用能安装多次,某些情况下是在同一个命名空间中。
应用程序名以及实例名是单独记录的。每个实例的实例名必须唯一。
## 集群架构
### 节点
K8S中一个节点是一台工作机,可以是虚拟机也可以是物理机。
每个节点包含着运行Pods的必要服务以及受Master组件管理。
节点服务包括容器运行时,kubelet,kubeproxy。
#### 节点状态
一个节点的状态包含四个信息。
- 地址
- 条件
- 容量以及可分配资源
- 通用信息
```shell
kubectl describe node nodeName
Name: k8s-server
Roles: master
Labels: beta.kubernetes.io/arch=amd64
beta.kubernetes.io/os=linux
kubernetes.io/arch=amd64
kubernetes.io/hostname=k8s-server
kubernetes.io/os=linux
node-role.kubernetes.io/master=
Annotations: kubeadm.alpha.kubernetes.io/cri-socket: /var/run/dockershim.sock
node.alpha.kubernetes.io/ttl: 0
projectcalico.org/IPv4Address: 192.168.2.10/24
projectcalico.org/IPv4IPIPTunnelAddr: 192.168.185.128
volumes.kubernetes.io/controller-managed-attach-detach: true
CreationTimestamp: Mon, 06 Jan 2020 07:29:42 +0800
Taints: node-role.kubernetes.io/master:NoSchedule
Unschedulable: false
Lease:
HolderIdentity: k8s-server
AcquireTime: <unset>
RenewTime: Thu, 09 Jan 2020 06:31:02 +0800
Conditions: #条件信息
Type Status LastHeartbeatTime LastTransitionTime Reason Message
---- ------ ----------------- ------------------ ------ -------
NetworkUnavailable False Mon, 06 Jan 2020 07:51:44 +0800 Mon, 06 Jan 2020 07:51:44 +0800 CalicoIsUp Calico is running on this node
MemoryPressure False Thu, 09 Jan 2020 06:27:34 +0800 Mon, 06 Jan 2020 07:29:38 +0800 KubeletHasSufficientMemory kubelet has sufficient memory available
DiskPressure False Thu, 09 Jan 2020 06:27:34 +0800 Mon, 06 Jan 2020 07:29:38 +0800 KubeletHasNoDiskPressure kubelet has no disk pressure
PIDPressure False Thu, 09 Jan 2020 06:27:34 +0800 Mon, 06 Jan 2020 07:29:38 +0800 KubeletHasSufficientPID kubelet has sufficient PID available
Ready True Thu, 09 Jan 2020 06:27:34 +0800 Mon, 06 Jan 2020 07:51:27 +0800 KubeletReady kubelet is posting ready status. AppArmor enabled
Addresses: #地址信息
InternalIP: 192.168.2.10
Hostname: k8s-server
Capacity:#容量信息
cpu: 2
ephemeral-storage: 19540624Ki
hugepages-1Gi: 0
hugepages-2Mi: 0
memory: 2017840Ki
pods: 110
Allocatable:#可分配信息
cpu: 2
ephemeral-storage: 18008639049
hugepages-1Gi: 0
hugepages-2Mi: 0
memory: 1915440Ki
pods: 110
System Info:#通用信息
Machine ID: a7844a3135874a6bb66b0207bfabc345
System UUID: 08914D56-5EF1-70CB-B6F2-5AFD65696049
Boot ID: 7cb1182a-1020-42a4-bd35-6c87288135fd
Kernel Version: 4.15.0-72-generic
OS Image: Ubuntu 18.04.3 LTS
Operating System: linux
Architecture: amd64
Container Runtime Version: docker://18.9.7
Kubelet Version: v1.17.0
Kube-Proxy Version: v1.17.0
PodCIDR: 10.244.0.0/24
PodCIDRs: 10.244.0.0/24
Non-terminated Pods: (6 in total)
Namespace Name CPU Requests CPU Limits Memory Requests Memory Limits AGE
--------- ---- ------------ ---------- --------------- ------------- ---
kube-system calico-node-ds2cz 250m (12%) 0 (0%) 0 (0%) 0 (0%) 2d22h
kube-system etcd-k8s-server 0 (0%) 0 (0%) 0 (0%) 0 (0%) 2d23h
kube-system kube-apiserver-k8s-server 250m (12%) 0 (0%) 0 (0%) 0 (0%) 2d23h
kube-system kube-controller-manager-k8s-server 200m (10%) 0 (0%) 0 (0%) 0 (0%) 2d23h
kube-system kube-proxy-hcnkk 0 (0%) 0 (0%) 0 (0%) 0 (0%) 2d23h
kube-system kube-scheduler-k8s-server 100m (5%) 0 (0%) 0 (0%) 0 (0%) 2d23h
Allocated resources:
(Total limits may be over 100 percent, i.e., overcommitted.)
Resource Requests Limits
-------- -------- ------
cpu 800m (40%) 0 (0%)
memory 0 (0%) 0 (0%)
ephemeral-storage 0 (0%) 0 (0%)
Events: <none>
```
##### 地址
- HostName:主机名,由节点内核显示。--hostname-override参数重写。
- ExternalIP:外部IP,由外部路由分配。
- InternalIP:内部IP,由K8S集群分配。
每个字段的使用取决于裸机配置或云厂商。
##### 条件
描述了所有运行节点的状态。
| 节点条件 | 描述 |
| ------------------ | ------------------------------------------------------------ |
| Ready | True,表示节点健康且准备接受Pods。Unknow表示节点控制器没有收到此节点最后一个周期的心跳(默认40S)。node-monitor-grace-period |
| MemoryPressure | True,表示可用内存过低。 |
| PIDPressure | True,表示节点进程过多。 |
| DiskPressure | True,表示节点可用磁盘容量过低。 |
| NetworkUnavailable | True,表示节点网络配置不正确。 |
```json
"conditions": [
{
"type": "Ready",
"status": "True",
"reason": "KubeletReady",
"message": "kubelet is posting ready status",
"lastHeartbeatTime": "2019-06-05T18:38:35Z",
"lastTransitionTime": "2019-06-05T11:41:27Z"
}
]
```
**如果Ready类型下的status字段是False或者Unknown的状态持续超过pod-eviction-timeout,则此节点上的Pods会被节点控制器删除。默认是五分钟。**
当节点与主节点不能通讯时,Pods仍然可以运行在Node上,直到与Master恢复通讯。
1.5以前的版本Node Controller会删除不可达的Pods。
1.5以后的版本,不会删除,直到确认已经停止。此时Pods状态为Terminating或者Unknown。
当节点永久的离开集群时,K8S无法推断节点不可达,需要管理员手动删除节点对象,此时会删除节点上所有的Pods,以及释放它们的名字。
The node lifecycle controller automatically creates [taints](https://kubernetes.io/docs/concepts/configuration/taint-and-toleration/) that represent conditions. When the scheduler is assigning a Pod to a Node, the scheduler takes the Node’s taints into account, except for any taints that the Pod tolerates.
##### 容量以及可分配资源
描述了节点的可用资源,包括cpu,内存,最大数量Pods。
capacity块描述了节点拥有资源的总数,allocatable块描述了节点可被Pods消费的资源。
##### 通用信息
描述了通用信息,包括内核版本,K8S版本,Docker版本,操作系统名称等。
#### 管理
Node是由外部创建的。metadata.name字段是节点IP。K8S会周期性的通过name字段进行健康检查。直到节点有效或者Node对象删除。
```json
{
"kind": "Node",
"apiVersion": "v1",
"metadata": {
"name": "10.240.79.157",
"labels": {
"name": "my-first-k8s-node"
}
}
}
```
##### 节点控制器
Master组件,管理节点的多个方面。
拥有多个角色,在节点的生命周期中。
- 当节点注册时,赋予CIDR块给节点(如果CIDR块赋值开关打开)
- 保持内部节点列表与云提供商的可用机器一致。
- 监控节点健康。负责更新的NodeStatus的NodeReady条件。每--node-monitor-period周期检查节点状态,默认是40S。
###### 心跳
两种心跳:更新NodeStatus的心跳以及Lease Object的心态(租约对象)。
每个节点在kube-node-lease命名空间中关联了一个lease对象。lease是一个轻量级的资源,随着节点的伸缩改善了节点的心跳性能。
kublet负责创建以及更新NodeStatus和Lease对象。
默认五分钟更新一次NodeStatus对象。
默认十秒钟更新一次Lease Object。Lease的更新独立于NodeStatus。
###### 可靠性
从1.4开始,当Node Controller决定驱逐Pods时会检查所有节点的状态。
大多数情况下,驱逐比率是--node-eviction-rate(0.1),每十秒驱逐一个。
当node在一个给定zone变得不健康时,evication行为将会发生改变,node controller会检查坏死率。默认是阈值是--unhealthly-zon-threshold(0.55),如果大于该阈值,则会减少eviction rate。
如果集群数量小于--large-cluster-size-threshold(50),eviction会停止,否则eviction rate会减少至--secondary-node-eviction-rate(0.01)也就是100秒一个。
主要是应对跨zone的集群,增加可用性。当某个zone不可用时,可以将负载转移到健康zone。
当所有node都在一个zone时,--node-eviction-rate是正常的0.1.
极端情况,所有zone都不可用时,node controller会假设master发生了连接性问题,然后停止eviction直到连接恢复。
从1.6开始,当Pods不能tolerate NoExcute taints时,node controller同样也负责evicting 带有NoExcute taints节点的Pods。
从1.8开始负责创建描述节点条件的taints。
#### 节点的自我注册
kubelet的--register-node默认为true,会自动注册到api server。自我注册选项
- --kubeconfig。注册凭证以及服务路径。Path to credentials to authenticate itself to the apiserver.
- --cloud-provider。读取自身元数据,以及与云提供商会话。
- --register-node。自动注册到api server。
- --register-with-taints。注册taints
- --node-ip。节点IP
- --node-lables。节点标签,用于Pods的标签选择器。
- --node-status-update-frequency。制定多久汇报一次节点状态给master。
### 主节点通信
分类Master与集群的通信路径,加强网络配置,以便在不受信任的网络部署集群。
#### Cluster与Master通信
集群中所有的通信路径都终止于api server。api server不对外暴露服务,内部配置监听443端口,启用多种认证与授权方式,特别是匿名请求以及服务账号token被允许时。
集群中的节点应当被提供公共根证书,以便用于安全的连接到api server。
Pods使用服务账号安全的连接到api server。在实例化的时候K8S会自动的注入证书以及token。
kubernetes服务对外暴露了一个虚拟IP用于重定向至HTTPS的终端。
master组件同样也可以通过HTTPS端口与api server通信。
节点与master的通信默认是安全的,能够运行在不安全的网络中。
#### Master与Cluster通信
1. 通过kubelet进行RPC通信。
1. 用于抓取Pods日志。
2. 附加到运行的Pods。
3. 提供端口转发功能。
2. 通过kubeproxy进行通信。
连接终止于kubelet的HTTPS端口。默认的,api server不校验kubelet证书,这使得连接容易遭受中间人攻击,不能安全的运行在不受信任的网络中。
使用--kubelet-certificate-authority标志,并为apiserver提供根证书包来验证证书。
如果不能提供,则可以使用SSH隧道进行安全通信。(但以标记过期。。。)
apiserver到node,pods,service的连接是plain HTTP且未加密,未认证。
目前master与节点的通信,是不安全的,不能对外暴露。
### 控制器
**控制器是一个非终止回路,调节系统的状态与期望状态匹配。**
#### 控制器模式
一个控制器至少跟踪了一种资源类型。对象的spec字段描述了期望状态,控制器负责控制实际状态以匹配期望状态。
控制器通过apiserver来管理状态。
某些控制器需要对集群外部的资源做出改变。例如节点控制器。
#### 期望与现实
集群会随着工作的发生以及控制回路的自动修复而发生改变,这意味着,集群永远不会达到一个稳定状态。
只要控制器能做出有效改变,稳不稳定不重要。
#### 设计
K8S的设计原则,每个控制器管理一个特殊的集群状态。大多数控制器使用一种资源来描述期望状态,并使用另一种资源来做出改变以匹配期望状态。控制器被设计为允许失败。
控制器之间可能创建或更新同一种资源,但只更新自己关心的资源,不会更新到其他控制器的资源。
#### 运行controller的方式
通过kube-contolelr-manager运行,内部会自动管理失败的控制器。
### CCM(云控制器管理器)
目的是为了K8S能独立的演化,不涉及特定云厂商的代码。CCM与Master组件一起运行,能作为插件启动,运行在K8S之上。
CCM基于插件机制进行设计,运行新的云提供商以插件的方式轻松集成K8S。
未使用CCM的架构

#### 设计
未使用CCM的架构通过:
1. kubelet
2. apiserver
3. contoller manager
与云提供商进行集成。
使用CCM的架构:

#### CCM组件
KCM云依赖组件:
- Node Controller
- Volume Controller
- Route Contoller
- Service Controller
CCM运行的控制器:
- Node Controller
- Route Controller
- Service Controller
Volume Controller打算使用CSI(容器存储接口)替代。
#### CCM功能
CCM继承了KCM的功能
**节点控制器**:
**从云提供商获取节点信息,用于节点的初始化。**
1. 用云特定的Zone/Region 标签初始化节点。
2. 使用特定于云实例的详细信息初始化节点,例如类型,大小。
3. 获取IP以及主机名。
4. 当节点无法响应时,检查cloud是否删除此实例,如果删除,则删除K8S Node对象。
**路由控制器:**
负责节点路由,跨节点容器通信,目前只有谷歌支持。。。
**服务控制器:**
监听服务的CRUD事件。基于当前状态,配置LB反应服务状态。确保LB是最新的。
**kubelet**
初始化无关于cloud provider的节点信息,并给节点打上污点标记,直到CCM初始化完特定云信息。
#### 插件机制
CCM使用Go接口,云厂商可自定义实现。
#### 授权
**Node Controller**
只操作节点对象, It requires full access to get, list, create, update, patch, watch, and delete Node objects.
**Route Controller**
监听节点的创建,配置合适的路由。 It requires get access to Node objects.
**Service Controller**
监听Service Object的创建,更新,删除事件,然后配置合适的终端对象。
v1/Service:
- List
- Get
- Watch
- Patch
- Update
**Other**
CCM核心实现要求能够创建事件,以及服务账号的创建。
v1/Event:
- Create
- Patch
- Update
v1/ServiceAccount:
- Create
#### 厂商实现
- AWS
- Azure
- OpenStack
#### 集群管理
## 容器
#### 镜像
跟docker的语法一样。
##### 更新镜像
镜像默认更新策略是IfNotPresent,如果镜像存在则不会pull新镜像。
- 设置imagePullPolicy为Always则永远pull镜像
- 如果使用latest标签,则永远pull image
- 省略imagePullPolicy以及tag,则永远pull image
- 启用AlwaysPullImage 管理控制器。
镜像应当避免使用:latest标签。
##### 使用清单构建多架构镜像
Docker CLI现在支持docker manifest构建镜像。可以打包多个镜像到一个镜像。
https://docs.docker.com/engine/reference/commandline/manifest/
```shell
docker manifest inspect imageName
docker manifest create
docker manifest push
docker manifest annotate
docker manifest create 45.55.81.106:5000/coolapp:v1 \
45.55.81.106:5000/coolapp-ppc64le-linux:v1 \
45.55.81.106:5000/coolapp-arm-linux:v1 \
45.55.81.106:5000/coolapp-amd64-linux:v1 \
45.55.81.106:5000/coolapp-amd64-windows:v1
Created manifest list 45.55.81.106:5000/coolapp:v1
```
这些命令只能在命令行使用。
##### 使用私有注册表
私有注册表可能需要密钥,在pull 镜像的时候。
- Configuring Nodes to Authenticate to a Private Registry
- all pods can read any configured private registries
- requires node configuration by cluster administrator
- Pre-pulled Images
- all pods can use any images cached on a node
- requires root access to all nodes to setup
- Specifying ImagePullSecrets on a Pod
- only pods which provide own keys can access the private registry
Docker存储私有化注册表在$HOME/.dockercfg或者$HOME/.docker/config.json文件中。
kubelet拉取镜像时会读取这些配置用作凭证。
- `{--root-dir:-/var/lib/kubelet}/config.json`
- `{cwd of kubelet}/config.json`
- `${HOME}/.docker/config.json`
- `/.docker/config.json`
- `{--root-dir:-/var/lib/kubelet}/.dockercfg`
- `{cwd of kubelet}/.dockercfg`
- `${HOME}/.dockercfg`
- `/.dockercfg`
配置私有化注册表建议步骤:
1. ```shell
docker login [server]#在你想要使用凭证的节点上登录
#这会更新$HOME/.docker/config.json
```
2. 查看$HOME/.docker/config.json,确保已经认证。
3. 获取节点列表
1. 获取节点名字
```shell
nodes=$(kubectl get nodes -o jsonpath='{range.items[*].metadata}{.name} {end}')
```
2. 获取节点IP
```shell
nodes=$(kubectl get nodes -o jsonpath='{range .items[*].status.addresses[?(@.type=="ExternalIP")]}{.address} {end}')
```
4. 拷贝config.json文件到上述路径中
1. ```
for n in $nodes; do scp ~/.docker/config.json root@$n:/var/lib/kubelet/config.json; done
```
5. 验证
```shell
kubectl apply -f - <<EOF
apiVersion: v1
kind: Pod
metadata:
name: private-image-test-1
spec:
containers:
- name: uses-private-image
image: $PRIVATE_IMAGE_NAME
imagePullPolicy: Always
command: [ "echo", "SUCCESS" ]
EOF
#pod/private-image-test-1 created
kubectl logs private-image-test-1
kubectl describe pods/private-image-test-1 | grep "Failed"
```
**确保每个节点都有同样的配置。**
可以预拉取镜像,这样可以绕过认证,必须设置imagePullPolicy为IfNotPresent或者Never。
确保所有节点拉取了镜像。(K8S集群搭建的时候可以使用阿里的镜像或者自己拉取镜像)。
**创建密钥与Docker Config文件。**只能在没有证书的时候创建,有证书的时候,参考:https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/#registry-secret-existing-credentials
```shell
kubectl create secret docker-registry <name> --docker-server=DOCKER_REGISTRY_SERVER --docker-username=DOCKER_USER --docker-password=DOCKER_PASSWORD --docker-email=DOCKER_EMAIL
```
**在Pods中引用密钥**
```shell
cat <<EOF > pod.yaml
apiVersion: v1
kind: Pod
metadata:
name: foo
namespace: awesomeapps
spec:
containers:
- name: foo
image: janedoe/awesomeapp:v1
imagePullSecrets:
- name: myregistrykey
EOF
cat <<EOF >> ./kustomization.yaml
resources:
- pod.yaml
EOF
```
**用例:**
1. 只运行在非专有镜像中,不需要隐藏镜像。无需配置。
2. 某些镜像需要隐藏时,但对所有集群用户可见,可以搭建私有镜像仓库,在每个节点上配置密钥。
3. 集群运行在专有镜像上,且有访问控制。开启镜像拉取控制器,控制敏感数据。
4. 运行在多租户环境中,每个租户需要一个私有镜像。开启镜像拉取控制器,运行私有仓库,每个租户生成不同的凭证,并为每个租户的命名空间设置密钥,租户添加密钥至命名空间的imagePullSecrets。
5. 如果需要访问多仓库,则每个仓库创建一个密钥。kubelet会合并这些密钥至.docker/config.json中。
#### 容器环境变量
K8S容器环境提供了几个重要的资源:
- 一个文件系统,这是一个镜像与一个或多个卷的组合。
- 关于容器的信息。
- 集群中其他节点的信息。
##### 容器信息
容器的hostname就是Pod的名字。
Pods名以及namespace作为环境变量传递至容器。
用户自定义的环境变量同样可用。
##### 集群信息
当容器创建时,集群中所有正在运行的服务作为环境变量传递至容器。环境变量匹配docker 的--link语法。
容器内可通过dns访问外部服务,如果DNS插件启用。
#### Runtime Class
**Runtime class**
RuntimeClass用于选择容器运行时,是一种配置。
**动机**
不同的Pods可以运行不同的RuntimeClass以提供性能以及安全的平衡。
不同的Pods可以运行相同的RuntimeClass但可以有不同的配置。
**会有额外的硬件开销。但保证了安全性隔离**
**设置**
1. 在节点上配置CRI实现。
2. 创建相应的RuntimeClass资源。
```yml
apiVersion: node.k8s.io/v1beta1 # RuntimeClass is defined in the node.k8s.io API group
kind: RuntimeClass
metadata:
name: myclass # The name the RuntimeClass will be referenced by
# RuntimeClass is a non-namespaced resource
handler: myconfiguration # The name of the corresponding CRI configuration
---
apiVersion: v1
kind: Pod
metadata:
name: mypod
spec:
runtimeClassName: myclass
# ...
```
#### 容器生命周期钩子
尽可能的保持钩子轻量级。钩子函数可能会调用多次,确保可重复执行。
用于预设置资源,以及清除资源。比如密钥,token等。
容器初始化前后有2个钩子函数:
1. PostStart:无参,在容器创建后执行,同步阻塞,无法达到Running状态,超时会杀死容器。
2. PreStop:无参,在容器销毁前执行,同步阻塞,无法到达Complete状态,超过宽限期会强制杀死容器。
钩子实现:
1. Exec:执行指定的命令,资源消耗统计在容器中。
2. HTTP:执行HTTP请求。
## 负载
### Pods
#### 大纲
##### 理解Pods
K8S中,一个Pod是最基础的执行单元,最小最简单的可部署单元。
Pod即是集群中的进程。封装了应用的容器,存储,网络,以及运行选项,也是部署单元,应用程序实例。Pod由一个或多个紧耦合的容器组成,容器间共享资源。
Pods的2种表现方式:
- **单容器Pod**
- **多容器Pod**.封了多个紧耦合需共享资源的容器。
- 参考:
- [The Distributed System Toolkit: Patterns for Composite Containers](https://kubernetes.io/blog/2015/06/the-distributed-system-toolkit-patterns)
- [Container Design Patterns](https://kubernetes.io/blog/2016/06/container-design-patterns)
每个Pod对应一个应用实例,如需伸缩,可部署多个Pod。通常使用Controller进行伸缩。
**Pods如何管理多个容器**:
Pods被设计为协作多个进程组成一个紧密合作的服务单元。Pod中的容器自动的放置在一起并在调度在同一物理机或虚拟机上。这些容器共享资源以及依赖,可以与其他容器通讯以及协调他们何时以及如何终止。
只有紧耦合共享资源的Pods才考虑放置在同一个Pod中,例如上图。
某些Pods有初始容器以及应用容器,初始容器在应用容器启动之前运行并且完全成功退出。
Pods提供了2种共享的资源,网络以及存储。
**网络**
每个Pod拥有一个唯一的IP,Pod中的每个容器共享同一网络命名空间包括IP地址以及端口。同一Pod内的容器通讯通过localhost。Pod之间的通讯通过CNI插件进行协调,例如calico,flannel。
**存储**
一个Pod能指定一组共享的卷。Pod中的容器通过卷共享数据。卷能持久化数据,在容器重启后依然可以访问。
##### 使用Pods
极少手动创建单独的Pod,因为Pod被设计为一次性实体,用完即删。一旦创建就会被分配至一个节点,直至进程终止,pod对象删除,Pod被驱逐,节点失败。
> **Note:** 不要混淆重启容器与重启Pod。Pod不能运行,只是容器运行的环境。Pod的重启将被分配到其他节点,Pod内容器共享的卷将会被删除。
Pod不能自愈。如果调度到一个失败的节点或调度失败,则Pod会被删除。Pod不能在驱逐中以及节点维护时存活。K8S使用了高层抽象(控制器)来处理Pod的自愈以及伸缩。
**控制器能创建以及管理多个Pod,拥有复制,滚动更新,自愈等能力。**
常见控制器:
- [Deployment](https://kubernetes.io/docs/concepts/workloads/controllers/deployment/)
- [StatefulSet](https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/)
- [DaemonSet](https://kubernetes.io/docs/concepts/workloads/controllers/daemonset/)
控制器使用模板来创建Pod。
##### Pods模板
Pod模板是规范,包括在其他对象中,例如RC,JOB,DS。控制器使用模板来构建真实的Pod。模板如下
```yml
apiVersion: v1
kind: Pod
metadata:
name: myapp-pod
labels:
app: myapp
spec:
containers:
- name: myapp-container
image: busybox
command: ['sh', '-c', 'echo Hello Kubernetes! && sleep 3600']
```
Pod模板不描述期望状态,不影响已创建的Pod,能方便的更新。
Pod拥有状态,指定了所有容器的期望状态。
#### Pods
Pod是最小可部署的计算单元,能被K8S创建以及管理。
##### 是什么
Pod是一组容器,他们共享存储,网络,规范,他们放置在同一位置,同时调度,共享同一上下文。
Pod构建了一个逻辑主机,这个逻辑主机放置了一组紧耦合的容器。
Pod的共享上下文是一Linux命名空间,cgroups,可能是与Docker容器类似的隔离。
在Pod的上下文中,应用可能有更多的子隔离。
Pod中的容器共享同一IP以及端口范围,通过localhost找到对方。Pod间可以通过IPC(中间进程通讯)通讯。不同Pod之间的容器有不同的IP,不能直接通过IPC通讯,需通过CNI插件。
Pod中的容器共享卷。
Pod被认为是相对临时的实体。一旦创建(赋予一个UID)会被调度到节点上,直至终止或删除。如果节点死亡,Pod被调度为删除,超时后,会创建新的Pod调度到新的节点(不同的UID)。
与Pod同生共死的东西,将会在Pod删除时被删除。重新分配的Pod不会再拥有相同的内容。
##### 动机
Management
Pod是一个模型,协调多进程组合成一个紧密的服务单元。Pod简化了应用的部署以及管理。Pod是部署,水平伸缩,复制的单元。Pod中容器的调度,命运(同生共死),协调复制,资源共享,以及依赖管理是自动处理的。
Pod内的应用共享IP以及端口(注意端口的分配),通过localhost与彼此通讯。在共享的扁平网络空间中,每个Pod拥有一个IP,可以跨网络进行通讯。Pod名即是容器主机名。除了共享网络,Pod中的应用还共享卷。
##### 用例
Pod可以用于托管垂直集成的应用程序栈,但主要动机是支持协同放置,协同管理的帮助程序。:
- 内容管理系统,文件,数据加载器,本地缓存管理器。
- 日志,检查点备份,压缩,自旋,快照等。
- 数据监听器,日志收集器,日志以及监控适配器,事件发布器等。
- 代理,桥接,适配器。
- 控制器,管理器,配置器,更新器等。
单独个Pod不打算用于运行多个相同的应用程序实例。
For a longer explanation, see [The Distributed System ToolKit: Patterns for Composite Containers](https://kubernetes.io/blog/2015/06/the-distributed-system-toolkit-patterns).
##### 替换考虑
为什么不要在单个容器中运行多个应用?:
1. 透明性。使得底层基础设施可以为容器提供服务,为用户提供便利。
2. 解耦软件依赖。单容器可以独立的被版本化,重建以及重部署。
3. 易于管理
4. 高效。基础设施承担了大量的工作,容器可以变得轻量级。
*Why not support affinity-based co-scheduling of containers?*
That approach would provide co-location, but would not provide most of the benefits of Pods, such as resource sharing, IPC, guaranteed fate sharing, and simplified management.
##### 持久性
Pods不打算用作持久化实体,不会再调度失败,节点失败,驱逐或节点维护中幸存。
用户不应当直接创建Pods。应使用高层抽象(控制器)来创建Pod。控制器提供了集群范围的自愈,复制,滚动更新。
Pod 被暴露为原语,以便于:
- 调度器以及控制器的可插拔性。
- 支持Pod级别的操作,无需控制器API代理。
- 从控制器的生命期中解耦。
- 解耦控制器以及服务。终端控制器只需观察Pods。
- kubelet级别功能与集群级别功能的清晰组合。kubelet是高效的pod控制器。
- HA应用希望Pod终止时以及删除时提前替换。
##### 终止
优雅的终止Pod是非常重要的(给进程一个clean up的机会)。当客户发起删除请求时,系统会记录预期的宽限期在删除之前,过期后会强制删除。如果kubelet重启,会重新尝试等待宽限期然后再kill。
案例:
1. 用户发送删除命令,默认等待30秒宽限期。
2. API server更新Pod,超出宽限期认为Pod死亡。
3. Pod变成Terminating状态,当查询的时候。
4. 于此同时(步骤3)kubelet看到pod标记为终止状态,pod更新时间已在步骤2设置,开始终止进程。
1. 如果pods内的容器定义了preStop钩子,则调用钩子。如果钩子执行超过了宽限期,则等待扩展宽限期。
2. 容器接受到TERM信号,并不是所有容器都在同一时间接受到终止信号,如果停止顺序很重要,则每个容器都需要一个preStop钩子。
5. 于此同时(步骤3)Pod从endpoints移除,不在参与负载均衡,不再是RC控制的一部分。
6. 当宽限期过后,Pod中的所有进程都会被强制KILL。
7. kubelet完成Pod的删除,在API server上设置宽限期为0(立即删除)。客户端不能再看见此Pod。
默认的,所有的删除都有30S宽限期。kubectl delete 命令支持--grace-period选项来改变宽限期。当值设置为0时,强制删除Pod。必须要指定--force与--grace-period=0才能完成强制删除。
**强制删除Pod**
强制删除定义为,Pod立即从集群和etcd中删除。当pod强制删除时,API server不会等待宽限期。它会立即从API中移除。节点上,立即终止的pod仍然有一小段宽限期。
强制删除pod可能存在危险,应当心。特别是在状态集中的pods。
##### 权限模型
pod中的任意容器都能启用权限模型。容器内的进程能访问外部的网络栈和设备。容器内的进程能获得与外部进程一样的权限。所有网络以及卷插件能从kubelet中分离。容器运行时必须支持相关的设置。
##### API对象
#### 生命周期
- [Pod phase](https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#pod-phase)
- [Pod conditions](https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#pod-conditions)
- [Container probes](https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#container-probes)
- [Pod and Container status](https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#pod-and-container-status)
- [Container States](https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#container-states)
- [Pod readiness gate](https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#pod-readiness-gate)
- [Restart policy](https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy)
- [Pod lifetime](https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#pod-lifetime)
- [Examples](https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#examples)
##### 阶段
Pods的status字段是PodStatus对象,拥有phase字段。
phase字段描述了Pod在生命周期的哪个阶段。phase既不是容器或Pod状态的汇总,也不是状态机。
phase字段只允许出现下面的值:
| Value | Description |
| :---------- | :----------------------------------------------------------- |
| `Pending` | Pod已被接受,但容器还没创建。可能还在调度或者拉取镜像。 |
| `Running` | 已绑定到节点,所有容器已创建。至少还有一个容器在运行或者进程正在启动或重启。 |
| `Succeeded` | 所有容器成功终止且不被重启。 |
| `Failed` | 所有容器已被终止,至少有一个容器终止失败。即非0退出状态或被系统终止。 |
| `Unknown` | 出于某些原因Pod状态不能被获取,典型的由于网络问题不能与Pod主机通讯。 |
##### Pod Conditions
Pod的PodStatus中有一个PodConditions数组,通过Pod传递(也许没有)。PodCondition中的每一个元素有六个可能字段:
- lastProbeTime最后一次探针时间。
- lastTransitionTime最后一次转换时间,由一个状态转换为另一个状态。
- message转换详情,人类可读。
- reason,唯一,一个单词,驼峰命名,条件的最后一次转换原因。
- status字段,可能是True,False,Unknown。
- type字段:
- PodScheduled:Pod已被调度到一个节点。
- Ready:有能力服务请求,应当被添加到负载均衡中。
- Initialized:所有容器启动成功。
- Unschedulable:调度器现在不能调度此Pod,例如资源泄漏或其他问题。
- ContainerReady:所有容器就绪。
```
Conditions:
Type Status
Initialized True
Ready True
ContainersReady True
PodScheduled True
```
##### 探针
探针是对容器周期性的诊断通过kubelet完成。有三种类型的探针实现:
- ExecAction:在容器内执行特定的命令。0退出即成功。
- TCPSocketAction:检查容器的的端口是否打开。
- HTTPGetAction:完成一个HTTP请求。返回码在200-400即成功。
探针结果:
- Success:容器通过诊断。
- Failure:容器未通过诊断。
- Unknown:诊断失败,无动作采取。
探针类型:
- livenessProbe:指示容器是否在运行。如果探测失败,kubelet会杀死容器,然后服从restartPolic策略。如果为提供活性探针,则默认为Sucess。
- readinessProbe:指示容器是否能服务请求。如未就绪,EndpointController会移除Pod的IP不参与LB。初始延迟之前默认状态是Failure。如未提供则默认Sucess。
- startupProbe:指示容器是否启动。所有其他探针都在此探针之后(这是个alpha特性),直到此探针成功。如果失败,kubelet杀死容器,然后服从restartPolicy。如未提供默认Sucess。
**何时使用活性探针。**
**FEATURE STATE:** `Kubernetes v1.0` [stable](https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#)
在探针失败时,自定义容器kill或重启逻辑。
检测死锁。
**何时使用就绪探针:**
**FEATURE STATE:** `Kubernetes v1.0` [stable](https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#)
启动时需加载大量数据,配置文件,迁移数据,下线维护。
**何时使用启动探针:**
启动时间大于活性探针的失败时间:初始延迟+失败阈值*周期
**容器状态:**
一旦Pod分配至节点,kubelet开始创建容器。容器状态:Waiting,Running,Terminated。
查看命令:kubectl describe pod podname。
`Waiting`: 默认状态。正在拉取镜像或使用密钥等其他操作。
- ```yaml
...
State: Waiting
Reason: ErrImagePull
...
```
- `Running`: 进入此状态时,postStart钩子已被执行。
```yaml
...
State: Running
Started: Wed, 30 Jan 2019 16:46:38 +0530
...
```
- `Terminated`: 进入此状态时,preStop钩子已执行完。正常或异常终止。
```yaml
...
State: Terminated
Reason: Completed
Exit Code: 0
Started: Wed, 30 Jan 2019 11:45:26 +0530
Finished: Wed, 30 Jan 2019 11:45:26 +0530
...
```
**重启策略:**
restartPolicy:Always,OnFailure,Never。
**生存期:**
Pod会一直存活至控制器或管理员手动删除它。
三种可用的控制器:
- Job的重启策略只适合OnFailre以及Never
- RC,RS,Deployment的重启策略只适合Always。
- DS的Pod运行在每一台机器上。
这三种类型的控制使用PodTemplate来创建Pod。使用合适的控制器来创建合适的Pod。
如果节点失去连接,则此节点的Pod都会设置为Failed。
**案例:**
Advanced liveness probe example
Liveness probes are executed by the kubelet, so all requests are made in the kubelet network namespace.
```yaml
apiVersion: v1
kind: Pod
metadata:
labels:
test: liveness
name: liveness-http
spec:
containers:
- args:
- /server
image: k8s.gcr.io/liveness
livenessProbe:
httpGet:
# when "host" is not defined, "PodIP" will be used
# host: my-host
# when "scheme" is not defined, "HTTP" scheme will be used. Only "HTTP" and "HTTPS" are allowed
# scheme: HTTPS
path: /healthz
port: 8080
httpHeaders:
- name: X-Custom-Header
value: Awesome
initialDelaySeconds: 15
timeoutSeconds: 1
name: liveness
```
##### Example states
- Pod is running and has one Container. Container exits with success.
- Log completion event.
- If restartPolicy is:
- Always: Restart Container; Pod `phase` stays Running.
- OnFailure: Pod `phase` becomes Succeeded.
- Never: Pod `phase` becomes Succeeded.
- Pod is running and has one Container. Container exits with failure.
- Log failure event.
- If restartPolicy is:
- Always: Restart Container; Pod `phase` stays Running.
- OnFailure: Restart Container; Pod `phase` stays Running.
- Never: Pod `phase` becomes Failed.
- Pod is running and has two Containers. Container 1 exits with failure.
- Log failure event.
- If restartPolicy is:
- Always: Restart Container; Pod `phase` stays Running.
- OnFailure: Restart Container; Pod `phase` stays Running.
- Never: Do not restart Container; Pod `phase` stays Running.
- If Container 1 is not running, and Container 2 exits:
- Log failure event.
- If restartPolicy is:
- Always: Restart Container; Pod `phase` stays Running.
- OnFailure: Restart Container; Pod `phase` stays Running.
- Never: Pod `phase` becomes Failed.
- Pod is running and has one Container. Container runs out of memory.
- Container terminates in failure.
- Log OOM event.
- If restartPolicy is:
- Always: Restart Container; Pod `phase` stays Running.
- OnFailure: Restart Container; Pod `phase` stays Running.
- Never: Log failure event; Pod `phase` becomes Failed.
- Pod is running, and a disk dies.
- Kill all Containers.
- Log appropriate event.
- Pod `phase` becomes Failed.
- If running under a controller, Pod is recreated elsewhere.
- Pod is running, and its node is segmented out.
- Node controller waits for timeout.
- Node controller sets Pod `phase` to Failed.
- If running under a controller, Pod is recreated elsewhere.
#### 初始化容器
#### 预设置
#### 拓扑
#### Disruptions
#### 瞬时容器
### Controller
## 服务,负载均衡,网络
### Endpoint Slices
### 服务
### 服务拓扑
### 服务与Pods的DNS
### 使用服务连接应用程序
### Ingress
### Ingress Controllers
### 网络策略
### 使用主机别名添加入口至Pod的/ets/hosts
### IPv4/IPv6 dual-stack
## 存储
### 卷
### 持久卷
### 卷快照
### CSI卷克隆
### 存储类
### 卷快照类
### 动态卷供应
### 特殊节点卷限制
## 配置
### 配置最佳实践
### Resource Bin Packing for Extended Resources
### 管理容器计算资源
### Pod Overhead
### 赋予Pod至节点
### 污点与容错
### Secrets
### 使用kubeconfig文件组织集群访问
### Pod优先级与抢占
### 调度框架
## 安全
## 策略
### Limit Ranges
### Resource Quotas
### Pod Security Policies
## 调度
### K8S调度器
### 调度器性能调优
## 集群管理
### 集群管理大纲
### 证书
### 云提供商
### 管理资源
### 集群网络
### 日志架构
### 配置kubelet垃圾回收器
### Federation
### K8S中的代理
### Controller manager metrics
### 安装插件
## 扩展 |
Python | UTF-8 | 965 | 2.8125 | 3 | [
"MIT"
] | permissive |
from mc import Dict, List
def chain(*callables):
def f(arg):
result = arg
for c in callables:
result = c(result)
return result
return f
def mux(*callables, **kwcallables):
if len(callables) == 0 and len(kwcallables) != 0:
def f(arg):
result = Dict({})
for c in kwcallables:
result[c] = kwcallables[c](arg)
return result
return f
if len(callables) != 0 and len(kwcallables) == 0:
def f(arg):
result = []
for c in callables:
result.append(c(arg))
return tuple(result)
return f
if len(callables) == 0 and len(kwcallables) == 0:
def f(args):
return f
raise AssertionError(
"You should either pass all named or all not-named arguments")
def add(a, b): return a + b
def subtr(a, b): return a - b
def multiply(a, b): return a * b
|
JavaScript | UTF-8 | 301 | 3.546875 | 4 | [] | no_license | #!/usr/bin/node
let num = parseInt(process.argv[2]);
let neg = false;
if (num < 0) {
num *= -1;
neg = true;
}
function factorial (a) {
if (!a) {
return 1;
}
if (a > 1) {
a *= factorial(a - 1);
}
return a;
}
num = factorial(num);
if (neg) {
num *= -1;
}
console.log(num);
|
Java | UTF-8 | 1,046 | 2.53125 | 3 | [] | no_license | package com.epam.training.ticketservice.presentation.cli.handler;
import com.epam.training.ticketservice.presentation.cli.utils.SeatIntPairBuilder;
import com.epam.training.ticketservice.utils.SeatIntPair;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
public class SeatIntPairBuilderTest {
SeatIntPairBuilder underTest;
@BeforeEach
public void setUp() {
underTest = new SeatIntPairBuilder();
}
@Test
public void testBuildListShouldReturnSeatIntPairListWithTheProperValues() {
String seats = "3,4 5,6 7,8 6,6";
List<SeatIntPair> expected = new ArrayList<>();
expected.add(new SeatIntPair(3,4));
expected.add(new SeatIntPair(5,6));
expected.add(new SeatIntPair(7,8));
expected.add(new SeatIntPair(6,6));
assertThat(underTest.buildList(seats), equalTo(expected));
}
}
|
Shell | UTF-8 | 184 | 2.734375 | 3 | [] | no_license | #!/usr/bin/env bash
# load env variables if local .env file exist
if [ -a .env ] ; then
source .env;
export DATABASE_URL=$DATABASE_URL;
fi
# migrate database
sequelize db:migrate |
Python | UTF-8 | 4,172 | 2.984375 | 3 | [] | no_license | from random import choice, randint, shuffle
from tkinter import *
from tkinter import messagebox
import pyperclip
import json
# ---------------------------- PASSWORD GENERATOR ------------------------------- #
def passw_gen():
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']
pass_letters = [choice(letters) for _ in range(randint(8, 10))]
pass_symbol = [choice(symbols) for _ in range(randint(2, 4))]
pass_numbers = [choice(numbers) for _ in range(randint(2, 4))]
password_list = pass_letters + pass_symbol + pass_numbers
shuffle(password_list)
final_password = "".join(password_list)
passw_entry.insert(0, final_password)
pyperclip.copy(final_password)
# ---------------------------- SAVE PASSWORD ------------------------------- #
def passw_save():
uri = uri_entry.get()
username = user_entry.get()
password = passw_entry.get()
new_data = {
uri: {
"username": username,
"password": password,
}
}
if len(uri) == 0 or len(username) == 0 or len(password) == 0:
messagebox.showinfo(title="Error", message="Please fill out all entries.")
else:
try:
with open("data.json", "r") as data_file:
# Reading old data
read_data = json.load(data_file)
except FileNotFoundError:
with open("data.json", "w") as new_file:
json.dump(new_data, new_file, indent=4)
else:
with open("data.json", "w") as data_file:
# Updating old data with new data
read_data.update(new_data)
# Saving the updated data
json.dump(read_data, data_file, indent=4)
finally:
uri_entry.delete(0, END)
user_entry.delete(0, END)
passw_entry.delete(0, END)
# ---------------------------- SEARCH URI -----------------------------#
def passw_search():
uri = uri_entry.get()
if len(uri) == 0:
messagebox.showinfo(title="Error", message="URI form is empty.")
else:
try:
with open("data.json") as data_file:
data = json.load(data_file)
except FileNotFoundError:
messagebox.showinfo(title="Error", message="No data file found.")
else:
if uri in data:
messagebox.showinfo(title=f"{data[uri]}",
message=f"\nUsername: {data[uri]['username']}"
f"\nPassword: {data[uri]['password']}")
else:
messagebox.showinfo(title="Error", message=f"No data for {uri} found.")
# ---------------------------- UI SETUP ------------------------------- #
window = Tk()
window.title("Password Manager")
window.config(padx=50, pady=50)
bg_img = PhotoImage(file="logo.png")
canvas = Canvas(width=200, height=200)
canvas.create_image(100, 100, image=bg_img)
canvas.grid(column=1, row=0)
#Labels
uri_label = Label(text="URI:")
uri_label.grid(column=0, row=1)
user_label = Label(text="Username:")
user_label.grid(column=0, row=2)
passw_label = Label(text="Password:")
passw_label.grid(column=0, row=3)
#Entries
uri_entry = Entry(width=25)
uri_entry.grid(column=1, row=1)
uri_entry.focus()
user_entry = Entry(width=36)
user_entry.grid(column=1, row=2, columnspan=2)
passw_entry = Entry(width=25, show="*")
passw_entry.grid(column=1, row=3)
# Button layout and config
search_button = Button(text=" Search ", command=passw_search)
search_button.grid(column=2, row=1)
passw_gen_button = Button(text="Generate", command=passw_gen)
passw_gen_button.grid(column=2, row=3)
add_button = Button(text="Add", width=34, command=passw_save)
add_button.grid(column=1, row=4, columnspan=2)
window.mainloop()
|
Shell | UTF-8 | 2,025 | 3.609375 | 4 | [] | no_license | #!/bin/bash -l
### COMP328: example batch script
### usage: "sbatch run.sh -c <num_cores_required> <sourcefile.c>"
### purpose: to OpenMP on requested number of cores
### restrictions: this script can only handle single nodes
### (c) mkbane, University of Liverpool (2020-2021)
# Specific course queue
#SBATCH -p course
# Defaults on Barkla (but set to be safe)
## Specify the current working directory as the location for executables/files
#SBATCH -D ./
## Export the current environment to the compute node
#SBATCH --export=ALL
# load modules
## intel compiler
module load compilers/intel/2019u5
module load mpi/intel-mpi/2019u5/bin
# SLURM terms
## nodes relates to number of nodes
## ntasks-per-node relates to MPI processes per node
## cpus-per-task relates to OpenMP threads (per MPI process)
# determine number of cores requested (NB this is single node implementation)
## further options available via examples: /opt/apps/Slurm_Examples/sbatch*sh
echo "Node list : $SLURM_JOB_NODELIST"
echo "Number of nodes allocated : $SLURM_JOB_NUM_NODES or $SLURM_NNODES"
echo "Number of threads or processes : $SLURM_NTASKS"
echo "Number of processes per node : $SLURM_TASKS_PER_NODE"
echo "Requested tasks per node : $SLURM_NTASKS_PER_NODE"
echo "Requested CPUs per task : $SLURM_CPUS_PER_TASK"
echo "Scheduling priority : $SLURM_PRIO_PROCESS"
# check expected inputs (OpenMP is only supported on a single node)
if [ "$SLURM_NNODES" -gt "1" ]; then
echo more than 1 node not allowed
exit
fi
# parallel using OpenMP
SRC=openmp-aerosol.c
EXE=${SRC%%.c}.exe
rm -f ${EXE}
echo compiling $SRC to $EXE
icc -qopenmp -O0 $SRC -o $EXE
if test -x $EXE; then
# set number of threads
export OMP_NUM_THREADS=${SLURM_CPUS_PER_TASK:-1} # if '-c' not used then default to 1
echo Using ${OMP_NUM_THREADS} OpenMP threads
# run multiple times
./${EXE};echo
else
echo $SRC did not built to $EXE
fi
|
Python | UTF-8 | 6,139 | 3.28125 | 3 | [] | no_license |
import pymysql
#a=8
#if a<5:
# print('你好')
#else:
# print('不好')
#a=5
#b=8
#if b == a+3:
# print('你好')
#else:
# print('hello')
# a = input('请输入成绩')
# b = int(a)
# if b > 90 and b <= 100:
# print('优秀')
# elif b > 80 and b <= 90:
# print('良好')
# elif b >= 70 and b <= 80:
# print('及格')
# elif b < 70:
# print('菜')
# a = input('手动输入字符串')
# if a.startswith('a'):
# if a.endswith('c'):
# print('hello word')
# else:
# print('hello')
# elif a.endswith('c'):
# print('word')
# else:
# print('123')
# a = input(' ')
# if a.startswith('a'):
# print("asd")
# a= input('手动输入字符串')
# if a.startswith('a'):
# if a.endswith('c'):
# print('hello word')
# else:
# print('hello')
# elif a.endswith('c'):
# print('word')
# else:
# print('123')
# a = input('手动输入字符串:')
# if a.startswith('a') and a.endswith('c'):
# print('hello word')
# elif a.startswith('a'):
# print('hello')
# elif a.endswith('c'):
# print('word')
# else:
# print('123')
# a = input('输:')
# s = input('输:')
# d = input('输:')
# z = int(a)
# x = int(s)
# c = int(d)
# f = [z,x,c]
# f.sort()
# if f[0] + f[1] > f[2]:
# if f[0] + f[2] > f[1]:
# if f[1] + f[2] > f[0]:
# print('三角形')
# else:
# print('不是三角形')
# a = [3,4,5]
# a.sort()
# if a[0]+a[1]>a[2]:
# if a[0]**2+a[1]**2 <a[2]**2:
# print('钝角')
# elif a[0]**2+a[1]**2 >a[2]**2:
# print('锐角')
# elif a[0]**2+a[1]**2 ==a[2]**2:
# print('直角')
# else:
# print('123')
# a = 20
# for i in range(0,a,2):
# print(i)
# a = 101
# s = 0
# for i in range(a):
# s=s+i
# print(s)
# a = 0
# for i in range(1,101)
# a+=i
# print(a)
# a = {'qwe':123,'asd':147,'zxc':159}
# for i,j in a.items():
# print(i,j)
# a = [123,147,159]
# for i in a:
# print(i)
# a = 100
# s = 0
# d = 0
# for i in range(1,a,2):
# s=s+i
# for f in range(0,a,2):
# d=d+f
# c=s-d
# print(c)
#a = [142,5412,'qwes','asdc',142]
# a = '12452asda'
# for i in enumerate(a):
# print(i)
# a = ['电脑','计算机','mp3']
# for i,j in enumerate(a):
# print(i,j)
# b= input('输入')
# b= int(b)
# print(a[b])
# a = ['asd','qwe','zxc']
# for i in enumerate(a):
# print(i)
# b = 0
# for i in range(1,100):
# if i % 2 ==0:
# b=b-i
# else:
# b=b+i
# print(b)
# a = random.randrange(1,10) # 随机选取一个数字
# b = int(input('输入一个数字:'))
# for i in range(1,10):
# for j in range(1,i+1):
# print('{}*{}={}\t'.format(j,i,i*j),end='')
# print()
# for i in range(1,10):
# for j in range(1,i+1):
# print('{}*{}={}'.format(j,i,i*j),end='\t')
# print()
# for i in range(1,10):
# if i==6:
# break
# else:
# print(i)
# for i in range(1,10):
# if i==6:
# continue
# else:
# print(i)
# a = ['123','qwe','as1','sda','asdd']
# for i in a:
# if len(i)==2:
# break
# else:
# print('lll')
# a = random.randrange(1,10)
# for i in range(3):
# b = int(input('输入:'))
# if b == a:
# break
# elif b < a:
# print('小了')
# elif b > a:
# print('大了')
# rando
# while True:
# a = int(input('srsz'))
# print(a)
# b =[{'name':'电脑','price':1999},{'name':'鼠标','price':10},{'name':'游艇','price':20},{'name':'美女','price':998}]
# for i,j in enumerate(b):
# print(i,j)
# if a > 'price':
# print('可购买')
# if a < 'price':
# print('不可以')
asd = pymysql.connect(host='192.168.0.185',
port=3306,
user='root',
password='654321',
charset='utf8')
aaa = asd.cursor()
# aaa.execute('show databases;')
# aaa.execute('use fxs;')
# aaa.execute('show tables;')
# aaa.execute('select * from tx;')
# aaa.execute('show databases;')
# aaa.execute('use mmm;')
# aaa.execute('show tables;')
# aaa.execute('select * from uiu;')
# aaa.execute('create database xiao;')
# aaa.execute('show databases;')
# aaa.execute('drop database test1;')
# aaa.execute('show databases;')
# aaa.execute('use xiao;')
# aaa.execute('create table xxtx(name char(30),sex char(20),age int);')
# aaa.execute('desc xxtx')
# aaa.execute('insert into xxtx values("","女",21)')
# aaa.execute('select * from xxtx')
# print(aaa.fetchall())
# aaa.close()
# aaa.execute('show database;')
# aaa.execute('use xiao;')
# aaa.execute('show tables;')
# aaa.execute('select * from uiu;')
# print(aaa.fetchall())
#
# aaa.execute('show databases;') # 执行sql语句
# aaa.execute('use fxs;')
# aaa.execute('show tables;')
# aaa.execute('select * from tx;')
#
#
# # print(aaa.fetchall()) # 读取上一句sql语句的结果
#
# # print(aaa.fetchmany(3)) # 读取上一句sql语句的结果,括号里写多少,就
# # 读取多少,不写默认一个
#
#
# print(aaa.fetchone()) #每次读取一个结果,本身有迭代功能
# print(aaa.fetchone())
# print(aaa.fetchone())
# print(aaa.fetchone())
# aaa.execute('create database mmm;')
# aaa.execute('use mmm;')
# aaa.execute('create table uiu(姓名 char(30),年龄 int, 班级 char(20));')
# list1 = ['小李',1,'测试班']
# for i in range(30):
# aaa.execute('insert into uiu values("{}",{},"{}");'.format(list1[0],list1[1],list1[2]))
# asd.commit()
#
# aaa.execute('select * from uiu;')
# for i in aaa.fetchall():
# print(i)
# aaa.execute('use mmm;')
# aaa.execute('show tables;')
# aaa.execute('select * from uiu;')
# # print(aaa.fetchall())
# b= aaa.fetchall()
# # print(b)
# with open('b.txt','w',encoding='utf-8') as f:
# for i in b:
# f.write('\n'+'{},{},{}'.format(i[0],i[1],i[2]))
|
Java | UTF-8 | 308 | 2.203125 | 2 | [
"MIT"
] | permissive | package com.zlikun.jee.product.impl;
import com.zlikun.jee.product.CPU;
/**
* @auther zlikun <zlikun-dev@hotmail.com>
* @date 2017/6/8 11:05
*/
public class AMDCPU implements CPU {
@Override
public int pins() {
return 120;
}
@Override
public String model() {
return "AMD";
}
}
|
C++ | UTF-8 | 648 | 2.828125 | 3 | [] | no_license | #pragma once
#include <string>
#include <list>
class StateRequestStack;
struct PopUpData
{
PopUpData() : mainMessage(L"error"), buttonMessage(L"error") {}
PopUpData(std::wstring mainMess, std::wstring buttonMess) : mainMessage(mainMess), buttonMessage(buttonMess) {}
std::wstring mainMessage;
std::wstring buttonMessage;
};
class PopUpStack
{
public:
PopUpStack(StateRequestStack& stateStack);
~PopUpStack();
bool isEmpty();
void addMessage(PopUpData message);
void addMessage(std::wstring mainMessage, std::wstring buttonMessage);
PopUpData popMessage();
private:
std::list<PopUpData> mStack;
StateRequestStack& mStateStack;
};
|
Markdown | UTF-8 | 3,564 | 2.609375 | 3 | [
"MIT"
] | permissive | # Official Python BEOWULF Library
`beowulf-python` is the official Beowulf library for Python. It comes with a
BIP38 encrypted wallet and a practical CLI utility called `beowulfpy`.
This library currently works on Python 2.7, 3.5 and 3.6. Python 3.3 and 3.4 support forthcoming.
## Main Functions Supported
1. CHAIN
- get_block
- get_transaction
2. TRANSACTION
- broadcast_transaction
- create transaction transfer
- create account
## Requirements
* `beowulf-python` requires Python 3.5 or higher.
* Library dependencies
```sh
appdirs
certifi
ecdsa>=0.13
funcy
future
langdetect
prettytable
pycrypto>=1.9.1
pylibscrypt>=1.6.1
scrypt>=0.8.0
toolz
ujson
urllib3
voluptuous
w3lib
```
### OSX
On Mac OSX, you may need to do the following first:
```bash
brew install openssl
export CFLAGS="-I$(brew --prefix openssl)/include $CFLAGS"
export LDFLAGS="-L$(brew --prefix openssl)/lib $LDFLAGS"
```
### Ubuntu
On Ubuntu, Beowulf-python requires libssl-dev
```bash
sudo apt-get install libssl-dev
```
## Installation
From pip:
```bash
pip install beowulf-python
```
From Source:
```
git clone https://github.com/beowulf-foundation/beowulf-python.git
cd beowulf-python
python3 setup.py install # python setup.py install for 2.7
or
make install
```
## Configuration
* Create a new client instance of Beowulfd and add your account to wallet
* Replace nodes with your endpoints which participate to MAINNET or TESTNET chain
*Note:* Client library will detect MAINNET or TESTNET properties through your provided endpoint.
##### Client setup
```
from beowulf.beowulfd import Beowulfd
from beowulf.commit import Commit
s = Beowulfd(nodes = ['https://testnet-bw.beowulfchain.com/rpc'])
```
##### Replace with your Private key and account name already have or get
##### from services
```pri_key = "5Jxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
account = "creatorwallet"
c = Commit(beowulfd_instance=s, no_wallet_file=True)
```
##### Provide a passphrase for the new wallet for the first time.
##### Unlock wallet before create transactions with passphrase.
```c.wallet.unlock("your_password")
if not c.wallet.getOwnerKeyForAccount(account):
c.wallet.addPrivateKey(pri_key)
```
## Example Usage
##### Get block
```python
# Get block from block number
block_num = 1869
block = c.beowulfd.get_block(block_num)
print(block)
```
##### Get transaction
```python
# Get transaction from transaction_id
transaction_id = '45618f73e9dbbe87a9ae6bfc316de8457c502b7c'
trx = c.beowulfd.get_transaction(transaction_id)
print(trx)
```
##### Transfer native coin
###### Transfer BWF
```python
# Transfer native coin
asset_bwf = "BWF"
asset_w = "W"
asset_tot = "TOT"
asset_fee = "W"
amount = "1.00000"
fee = "0.01000"
# Transfer BWF from creator to new_account_name
c.transfer(account=creator, amount=amount, asset=asset_bwf, fee=fee, asset_fee=asset_fee, memo="", to=new_account_name)
```
###### Transfer W
```python
# Transfer native coin
asset_bwf = "BWF"
asset_w = "W"
asset_tot = "TOT"
asset_fee = "W"
amount = "1.00000"
fee = "0.01000"
# Transfer W from creator to new_account_name
c.transfer(account=creator, amount=amount, asset=asset_w, fee=fee, asset_fee=asset_fee, memo="", to=new_account_name)
```
##### Create wallet
```python
# Variances
creator = "creatorwallet"
new_account_name = "newwallet"
new_password_seed = "password_seed"
new_password_wallet = "password_wallet"
# Create account
if not c.beowulfd.get_account(new_account_name):
c.create_account_simple(account_name=new_account_name, creator=creator, password_seed=new_password_seed, password_wallet=new_password_wallet)
```
|
Python | UTF-8 | 2,615 | 3.28125 | 3 | [] | no_license | from citis import Cities
from collections import defaultdict
import string
import bs4
class DocParser:
def __init__(self, doc_folder='files'):
self.doc_dir = doc_folder
self.city_utilities = Cities()
self.city_map = self.city_utilities.load_look_up_table()
def process_doc(self, doc_name):
'''
There are two different file format: txt or htm / html.
For files in txt format, we just read it directly.
For files in htm format, we read its full conent with the help of extra packages.
Find the sections below:
item 1 business
item 2 properties
(item 3 legal proceedings)
item 6 selected financial data
item 7 managements discussion and analysis
(item 8 financial statements)
We need to break down the text into a list of words, and then compare every word with
the city / state names.
We need to return a dictionary where its key is the full state name and its value is
the number of appearance of the cities in that state in the document.
'''
with open(doc_name, 'r') as fin:
text = fin.read()
if 'htm' in doc_name[-4:]:
text = bs4.BeautifulSoup(text).text
else:
print('Can\'t recognize format of file: {}'.format(doc_name))
return
# process on text
text = text.lower().encode('ascii', 'ignore').translate(string.maketrans("",""), string.punctuation)
text = self.find_sections(text)
# if successfully identify sections in the text
if text:
state_count = self.city_match(text)
return text
def find_sections(self, text):
i1 = text.rfind('item 1 business')
text = text[i1:]
# i2 = text.find('item 2 properties')
i3 = text.find('item 3 legal proceedings')
i6 = text.find('item 6 selected financial data')
# i7 = text.find('item 7 managements discussion and analysis')
i8 = text.find('item 8 financial statements')
if i8 != -1:
print('found section 1, 2, 6, 7')
return text[:i3] + ' ' + text[i6:i8]
elif i3 != -1:
print('found section 1, 2')
return text[:i3]
print('no section found')
return []
# return [ text[:i2], text[i2:i3], text[i6:i7], text[i7:i8] ]
def city_match(self, text):
# initialize a hashtable to store city count
state_count_table = self.city_utilities.init_state_count_table()
text = text.split()
for word in text:
if word in self.city_map:
state_count_table[self.city_map[word]] += 1
# for state, count in state_count_table.items():
# print('{}: {}'.format(state, count))
return state_count_table
if __name__ == '__main__':
doc_parser = DocParser()
text = doc_parser.process_doc('files/1110783-000095013706011768-c08447e10vk.htm')
# print(text)
|
Python | UTF-8 | 10,251 | 2.515625 | 3 | [] | no_license | import os, inspect
import numpy as np
import pybullet as p
import time
import pybullet_data
# from utils.general import *
# import utils.transformations as tf
class Manipulator(object):
"""
Provides a pybullet API wrapper for simpler interfacing and manipulator-specific functions.
The update() function should be called in a loop in order to store joint states and update joint controls.
"""
def __init__(self, arm, cid, ee_link_index, control_method, gripper_indices=[]):
# user selected parameters -- non-private can be modified on the fly
self.arm = arm
self.cid = cid
self.num_joints = p.getNumJoints(self.arm[0])
self.joint_infos = [p.getJointInfo(self.arm[0], i) for i in range(self.num_joints)]
self._active_joint_indices = [j for j, i in zip(range(p.getNumJoints(self.arm[0])), self.joint_infos) if
i[3] > -1]
self._gripper_indices = gripper_indices
self._control_method = control_method
self._ee_link_index = ee_link_index
# GET - PRIVATE
# --------------------------------------------------------------------------------------------------------------
def _get_joint_states(self):
"""
Get positions, velocities and torques of active joints (as opposed to passive, fixed joints)
"""
joint_states = p.getJointStates(self.arm[0], range(p.getNumJoints(self.arm[0])))
joint_states = [j for j, i in zip(joint_states, self.joint_infos) if i[3] > -1] # get only active states
self.jnt_pos = [state[0] for state in joint_states]
self.jnt_vel = [state[1] for state in joint_states]
self.jnt_torq = [state[3] for state in joint_states]
return self.jnt_pos, self.jnt_vel, self.jnt_torq
def _get_link_state(self, link_index):
"""
Returns information on the link URDF frame and centre of mass poses in the world frame
"""
result = p.getLinkState(self.arm[0],
linkIndex=link_index) # , computeLinkVelocity=1, computeForwardKinematics=1)
return result
def _get_link_pose(self, link_index):
"""
Get a links pose in the world frame as a 7 dimensional vector containing the
position (x,y,z) and quaternion (x,y,z,w)
"""
result = self._get_link_state(link_index)
link_frame_pos = np.asarray(result[4])
link_frame_rot = np.asarray(result[5])
link_frame_pose = np.concatenate((link_frame_pos, link_frame_rot)) # transform from x,y,z,w to w,x,y,z
return link_frame_pose
def _get_link_jacobian(self, link_index):
"""
Get the Jacobian of a link frame in the form 6xN [J_trans; J_rot]
"""
zero_vec = [0.0] * len(self.jnt_pos)
jac_t, jac_r = p.calculateJacobian(self.arm[0], link_index, [0, 0, 0], self.jnt_pos, zero_vec, zero_vec)
J = np.concatenate((jac_t, jac_r), axis=0)
return J
# SET AND CONTROL LOOPS - PRIVATE
# --------------------------------------------------------------------------------------------------------------
def _hard_set_joint_positions(self, cmd):
"""
Set joint positions without simulating actual control loops
"""
k = 0
cmd_ind = [j for j, i in zip(range(p.getNumJoints(self.arm[0])), self.joint_infos) if i[3] > -1]
for j in cmd_ind:
p.resetJointState(self.arm[0], j, cmd[k])
k = k + 1
def _joint_position_control(self, cmd):
"""
Position control loop, max torques set to an arbitrary 5000
"""
p.setJointMotorControlArray(self.arm[0], jointIndices=self._active_joint_indices,
controlMode=p.POSITION_CONTROL, targetPositions=cmd, forces = [100000, 100000, 100000, 100000, 100000, 100000, 100000, 100000, 100000])
def _joint_velocity_control(self, cmd):
"""
Velocity control loop - not really tested
"""
p.setJointMotorControlArray(self.arm[0], jointIndices=self._active_joint_indices,
controlMode=p.VELOCITY_CONTROL, targetVelocities=cmd)
# FETCH INFO FOR ANY NUMBER OF FRAMES
# ----------------------------------------------------------------------------------------------------------------
def get_states(self, link_indices):
"""
Return a tuple of states of URDF links given link indices
"""
states = ()
for i in link_indices:
link_state = self._get_link_state(i)
states = states + (link_state,)
return states
def get_poses(self, link_indices):
"""
Return poses of URDF link frames given link indices.
Poses are returned in the form of a tuple of numpy arrays (np.array(x,y,z,w,x,y,z))
"""
poses = ()
for i in link_indices:
link_pose = self._get_link_pose(i)
poses = poses + (link_pose,)
return poses
def get_jacobians(self, link_indices):
"""
Return Jacobians of frames given frame_indices in the form of numpy arrays
"""
jacobians = ()
for i in link_indices:
link_jacobian = self._get_link_jacobian(i)
jacobians = jacobians + (link_jacobian,)
return jacobians
def get_link_names(self):
"""
Returns a list of all link names
"""
names = []
for info in self.joint_infos:
names.append(info[12])
return names
def get_joint_names(self):
"""
Returns a list of all joint names
"""
names = []
for info in self.joint_infos:
names.append(info[1])
return names
def check_contact(self, list = []):
"""
Checks for contacts between bodyID and given list of links indices.
"""
if not list:
list = range(self.num_joints)
for i in list:
cont = p.getContactPoints(self.arm[0], -1, i)
if cont: return True
return False
# END-EFFECTOR SPECIFIC IMPLEMENTATIONS FOR CONVENIENCE
# ----------------------------------------------------------------------------------------------------------------
def get_manipulability_ellipsoid(self):
"""
Get manipulability ellipsoid of the end effector
"""
J = self.get_end_effector_jacobian()
el = np.linalg.pinv(np.matmul(J, np.transpose(J)))
return el
def get_end_effector_state(self):
"""
Get the state of the end-effector
"""
result = self._get_link_state(self._ee_link_index)
self.ee_link_trn, self.ee_link_rot, self.ee_com_trn, self.ee_com_rot, self.ee_frame_pos, self.ee_frame_rot = result
def get_end_effector_pose(self):
"""
Using pybullet frame info, grab the current global pose as a numpy array
"""
# pose of end effector frame in the world frame
ee_pose = self._get_link_pose(self._ee_link_index)
return ee_pose
def get_end_effector_jacobian(self):
"""
Grab the rotational and translational jacobian of the end effector
"""
zero_vec = [0.0] * len(self.jnt_pos)
self.get_end_effector_state()
jac_t, jac_r = p.calculateJacobian(self.arm[0], self._ee_link_index, self.ee_com_trn, self.jnt_pos, zero_vec,
zero_vec)
J = np.concatenate((jac_t, jac_r), axis=0)
return J
# SET GOALS
# ----------------------------------------------------------------------------------------------------------------
def set_control_method(self, m):
"""
Sets the control method variable
"""
self._control_method = m
def set_joint_position_goal(self, cmd):
"""
Set goal joint position
"""
self.pos_cmd = cmd
def set_joint_velocity_goal(self, cmd):
"""
Set goal joint velocity
"""
self.vel_cmd = cmd
def set_frame_pose_goal(self, index, t_pos, t_rot):
''' set a pose goal for an arbitrary frame'''
result = p.calculateInverseKinematics(self.arm[0], index, targetPosition=t_pos.tolist(),
targetOrientation=t_rot.tolist(), maxNumIterations = 200, residualThreshold = 0.002)
self.pos_cmd = result
return self.pos_cmd
def set_frame_position_goal(self, index, t_pos):
''' set a pose goal for an arbitrary frame'''
result = p.calculateInverseKinematics(self.arm[0], index, targetPosition=t_pos.tolist(), maxNumIterations = 200, residualThreshold = 0.002)
self.pos_cmd = result
return self.pos_cmd
def set_frame_velocity_goal(self, index, t_vel):
"""
Set Cartesian velocity goal for arbitrary frame
"""
J = self.get_end_effector_jacobian()
result = np.dot(np.linalg.pinv(J), t_vel)
self.vel_cmd = result
def close_gripper(self):
"""
Close the robot gripper (modifies the current joint position command)
"""
_cmd = list(self.pos_cmd)
for i in self._gripper_indices:
_cmd[i] = 1
self.pos_cmd = tuple(_cmd)
def open_gripper(self):
"""
Open the robot gripper (modifies the current joint position command)
"""
_cmd = list(self.pos_cmd)
for i in self._gripper_indices:
_cmd[i] = 0
self.pos_cmd = tuple(_cmd)
# UPDATE INTERNALLY
# ----------------------------------------------------------------------------------------------------------------
def update(self):
"""
This function should be configurable
"""
# run iteration of control loop
if self._control_method == 'p':
self._joint_position_control(self.pos_cmd)
#self._hard_set_joint_positions(self.pos_cmd)
elif self._control_method == 'v':
self._joint_velocity_control(self.vel_cmd)
# get joint positions, velocities, torques
self._get_joint_states()
|
Markdown | UTF-8 | 5,090 | 2.59375 | 3 | [] | no_license | ---
layout: post
title: "VHDL Simulation Workflow in macOS"
date: 2019-02-01 23:54:23 +0300
categories: VHDL
comments: true
---
The [XILINX Vivado Design Suite](https://www.xilinx.com/products/design-tools/vivado.html) does not work natively on the macOS platform, so you can not download your code to your development board. What you _can_ do, however, is to run simulations of your VHDL code. This post will show how to do it using `ghdl` and `gtkwave`.
## Installations
# GHDL
The first thing you have to do is install [GHDL](https://github.com/ghdl/ghdl), which is "the open-source compiler and simulator for VHDL". This tool can be downloaded from the [releases](https://github.com/ghdl/ghdl/releases) tab. The downloaded tar will have `bin`, `include` and `lib` folders. After moving the contents of these files to somewhere in your `$PATH`, (for example `usr/local/bin`) you can check if the setup is working.
{% highlight bash %}
which ghdl
/usr/local/bin/ghdl
ghdl --version
GHDL 0.36-dev (20181129) [Dunoon edition]
Compiled with GNAT Version: GPL 2017 (20170515-63)
mcode code generator
Written by Tristan Gingold.
Copyright (C) 2003 - 2015 Tristan Gingold.
GHDL is free software, covered by the GNU General Public License. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
{% endhighlight %}
# gtkwave
To be able to view the resulting waveforms, you can use [gtkwave](http://gtkwave.sourceforge.net). On macOS systems, it can easily be installed via `brew cask install gtkwave`. After the installation is completed, _gtkwave.app_ will be available in your default _Applications_ folder.
## Simulation
Let's use a simple half-adder circuit coded in VHDL.
{% highlight VHDL %}
library ieee;
use ieee.std_logic_1164.all;
entity half_adder is
port(
A : in std_logic;
B : in std_logic;
S : out std_logic;
C : out std_logic
);
end half_adder;
architecture RTL of half_adder is
begin
S <= A XOR B;
C <= A AND B;
end RTL;
{% endhighlight %}
To simulate this code, you will need a test-bench module. Here's an example:
{% highlight VHDL %}
library ieee;
use ieee.std_logic_1164.all;
entity half_adder_tb is
end entity;
architecture Behavioural of half_adder_tb is
constant c_WAIT : time := 20 ns;
signal r_input_a : std_logic := '0';
signal r_input_b : std_logic := '0';
signal r_output_s : std_logic := '0';
signal r_output_c : std_logic := '0';
component half_adder is
port(
A : in std_logic;
B : in std_logic;
S : out std_logic;
C : out std_logic
);
end component half_adder;
begin
UUT : half_adder
port map (
A => r_input_a,
B => r_input_b,
S => r_output_s,
C => r_output_c
);
p_comb : process is
begin
wait for c_WAIT;
r_input_a <= '0';
r_input_b <= '0';
wait for c_WAIT;
r_input_a <= '0';
r_input_b <= '1';
wait for c_WAIT;
r_input_a <= '1';
r_input_b <= '0';
wait for c_WAIT;
r_input_a <= '1';
r_input_b <= '1';
end process;
end Behavioural;
{% endhighlight %}
The files are named `half_adder.vhd` and `half_adder_tb.vhd`. To run the simulation, first you have to analyse and elaborate the source files.
{% highlight bash %}
ghdl -a half_adder.vhd
ghdl -e half_adder
ghdl -a half_adder_tb.vhd
ghdl -e half_adder_tb
{% endhighlight %}
Notice how the elaborate commands do not have the file extensions in their parameters. Finally, we can run the simulation and output the results in a _fst_ file to be opened by _gtkwave_.
{% highlight bash %}
ghdl -r half_adder_tb --stop-time=200ns --fst=half_adder.fst
open half_adder.fst
{% endhighlight %}
The `open` will launch _gtkwave_ and there you can see the waveform results of the simulation. Simply by dragging your signals from the left bar, you can observe them.

And there it is! You can now easily simulate your code in macOS before downloading it to your hardware.
## Extras
Running each specific `ghdl` command can be a bit tedious. You can write a simple `bash` script to automate some of the task. For example, the following script takes the main module name - _half_adder_ in this case - and a stop time for the simulation. I gave it the name _mhdl_, so I can simply run `mhdl half_adder 200ns`
{% highlight bash %}
#!/bin/bash
ghdl -a $1.vhd
ghdl -e $1
ghdl -a $1_tb.vhd
ghdl -e $1_tb
ghdl -r $1_tb --stop-time=$2 --fst=$1.fst
open $1.fst
{% endhighlight %}
# Downloads
[half_adder.vhd][1]
[half_adder_tb.vhd][2]
[mhdl][3]
[1]:{{ site.url }}/downloads/2019-02-01-vhdl-sim-workflow-in-macos/half_adder.vhd
[2]:{{ site.url }}/downloads/2019-02-01-vhdl-sim-workflow-in-macos/half_adder_tb.vhd
[3]:{{ site.url }}/downloads/2019-02-01-vhdl-sim-workflow-in-macos/mhdl
|
Java | UTF-8 | 2,990 | 3.03125 | 3 | [] | no_license | /**
* Listener.java
* @asignatura Programacion de Aplicaciones Interactivas
* @practica Practica
* @author Aythami Torrado Cabrera <alu0100837018@ull.edu.es>
* @date 30 mar. 2017
*
*/
package eventos;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
public class Listener implements MouseListener {
JButton listenUp;
JButton listenDown;
JButton listedLeft;
JButton listenRight;
JuegoPanel juego;
boolean pressed = false;
Listener(JButton botonarriba, JButton botonabajo, JButton botonizquierda, JButton botonderecha, JuegoPanel juego){
setListenUp(botonarriba);
setListenDown(botonabajo);
setListedLeft(botonizquierda);
setListenRight(botonderecha);
this.juego = juego;
}
/**
* Getter de listenUp
* @return the listenUp
*/
public JButton getListenUp() {
return listenUp;
}
/**
* Setter de listenUp
* @param listenUp the listenUp to set
*/
public void setListenUp(JButton listenUp) {
this.listenUp = listenUp;
}
/**
* Getter de listenDown
* @return the listenDown
*/
public JButton getListenDown() {
return listenDown;
}
/**
* Setter de listenDown
* @param listenDown the listenDown to set
*/
public void setListenDown(JButton listenDown) {
this.listenDown = listenDown;
}
/**
* Getter de listedLeft
* @return the listedLeft
*/
public JButton getListedLeft() {
return listedLeft;
}
/**
* Setter de listedLeft
* @param listedLeft the listedLeft to set
*/
public void setListedLeft(JButton listedLeft) {
this.listedLeft = listedLeft;
}
/**
* Getter de listenRight
* @return the listenRight
*/
public JButton getListenRight() {
return listenRight;
}
/**
* Setter de listenRight
* @param listenRight the listenRight to set
*/
public void setListenRight(JButton listenRight) {
this.listenRight = listenRight;
}
@Override
public void mouseClicked(MouseEvent e) {
// if(e.getSource() == getListenUp() ){
// juego.moveBall(0);
// juego.repaint();
// } else if(e.getSource() == getListenDown()){
// juego.moveBall(1);
// juego.repaint();
// }else if(e.getSource() == getListedLeft()){
// juego.moveBall(2);
// juego.repaint();
// }else if(e.getSource() == getListenRight()){
// juego.moveBall(3);
// juego.repaint();
// }
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
pressed = true;
if(e.getSource() == getListenUp() ){
juego.moveBall(0);
juego.repaint();
} else if(e.getSource() == getListenDown()){
juego.moveBall(1);
juego.repaint();
}else if(e.getSource() == getListedLeft()){
juego.moveBall(2);
juego.repaint();
}else if(e.getSource() == getListenRight()){
juego.moveBall(3);
juego.repaint();
}
}
@Override
public void mouseReleased(MouseEvent e) {
pressed = false;
}
}
|
Markdown | UTF-8 | 2,220 | 4.3125 | 4 | [] | no_license | # C# - String the Exception
- `String` and `string` are equivalent in C#
- Strings are technically reference types but with some unique behaviours
## Value Type Behaviour
- A `string` reference will always point to the original object, so modifying one reference will not affect other references
- strings are _immutable_, anything that appears to modify a string actually returns a new `string` object
```c#
// Example 1
string dog = "chihuahua";
string tinyDog = dog;
dog = "dalmation";
Console.WriteLine(dog);
// Output: "dalmation"
Console.WriteLine(tinyDog);
// Output: "chihuahua"
// Example 2
string s1 = "Hello ";
string s2 = s1;
s1 += "World";
System.Console.WriteLine(s1);
// Output: "Hello World"
System.Console.WriteLine(s2);
// Output: "Hello"
```
- Comparing strings with equality operator (`==`) performs a **value comparison** (NOT referential)
```c#
string s = "hello";
string t = "hello";
// b is true
bool b = (s == t);
```
## Null, Empty, or Unassigned Strings
Like `object` and other reference types, `string` references can be `null` or `unassigned`. String also has a special third value: **empty**.
- **Unassigned**: programmer did not give the variable any value
- **Null**: programmer intentionally made the variable refer to no object
- **Empty**: signifies a piece of text with zero character. Often to represent a blank text field
- Can use `""` or `String.Empty`
```c#
// Unassigned
string s;
// Null
string s2 = null;
// Empty string
string s3 = "";
// Also empty string
string s4 = String.Empty;
// This prints true
Console.WriteLine(s3 == s4);
```
- Use `String.Empty` or `""` instead of `null` to avoid `NullReferenceException` errors.
- Check for null OR empty string using method `String.IsNullOrEmpty()`
```c#
using System;
namespace StringTheException
{
class Program
{
static void Main(string[] args)
{
Console.Write("Your favourite color: ");
string color = Console.ReadLine();
if (String.IsNullOrEmpty(color))
{
Console.WriteLine("You didn't enter anything!");
}
else
{
Console.WriteLine("Thank you for your submission!");
}
}
}
}
```
|
Python | UTF-8 | 1,400 | 3.78125 | 4 | [] | no_license | text = input()
while True:
tokens = input().split(' ')
if tokens[0] == 'Finish':
break
command = tokens[0]
if command == 'Replace':
current_char = tokens[1]
new_char = tokens[2]
text = text.replace(current_char, new_char)
print(text)
elif command == 'Cut':
start_index = int(tokens[1])
end_index = int(tokens[2])
if start_index >= 0 and end_index < len(text):
part = text[start_index:end_index + 1]
text = text.replace(part, '')
print(text)
else:
print('Invalid indexes!')
elif command == 'Make':
case = tokens[1]
if case == 'Upper':
text = text.upper()
elif case == 'Lower':
text = text.lower()
print(text)
elif command == 'Check':
string = tokens[1]
if string in text:
print(f'Message contains {string}')
else:
print(f'Message doesn\'t contain {string}')
elif command == 'Sum':
start_index = int(tokens[1])
end_index = int(tokens[2])
substring = text[start_index:end_index + 1]
sum_substring = 0
if start_index >= 0 and end_index < len(text):
for i in substring:
sum_substring += ord(i)
print(sum_substring)
else:
print('Invalid indexes!')
|
Python | UTF-8 | 771 | 4.40625 | 4 | [] | no_license | """
This is program that asks the user for an 8-bit binary number
and replies whether the parity bit checks OK.
Parity bits are used as the simplest form of error detecting code.
"""
# Get a byte from the user.
while True:
bits_8 = input("Enter binary number: ")
# Check if user inserted 8 bits.
if (len(bits_8) == 8):
break
# If not, prompt the user again.
else:
print('A byte consists of 8 bits. Try again.\n')
# Get the last bit.
last_bit = int(bits_8[-1])
# Seperate the first 7 bits.
bits_7 = bits_8[:7]
# The sum of 1 bits.
sum_of_ones = 0;
for bit in bits_7:
if (int(bit) == 1):
sum_of_ones += 1
if (sum_of_ones % 2 != 0 and last_bit == 1):
print("Parity check OK.")
else:
print("Parity check not OK.")
|
Python | UTF-8 | 539 | 3.796875 | 4 | [] | no_license | SECONDS_DAY = 86400
SECONDS_HOUR = 3600
SECONDS_MINUTE = 60
seconds = int(input("Enter the number of seconds: "))
if seconds >= SECONDS_DAY:
days = seconds // SECONDS_DAY
seconds = seconds % SECONDS_DAY
print("Days: ", days)
if seconds >= SECONDS_HOUR:
hours = seconds // SECONDS_HOUR
seconds = seconds % SECONDS_HOUR
print("Hours: ", hours)
if seconds >= SECONDS_MINUTE:
minutes = seconds // SECONDS_MINUTE
seconds = seconds % SECONDS_MINUTE
print("Minutes: ", minutes)
print("Seconds: ", seconds)
|
Java | UTF-8 | 378 | 2.765625 | 3 | [] | no_license | package abstractfactory;
public class TestAbstractFactory {
public static void main(String[] args) {
Computer pc = ComputerFactory.getComputer(new PcFactory("16Mb", "1Tb", "CoreI7"));
Computer server = ComputerFactory.getComputer(new ServerFactory("32Mb", "10Tb", "Xenon"));
System.out.println("pc : " + pc);
System.out.println("server : " + server);
}
}
|
C | UTF-8 | 2,849 | 2.640625 | 3 | [
"MIT",
"NCSA"
] | permissive |
#include "cq-header.h"
int sec(pd0) /* 6.2 Float and double */
/* 6.3 Floating and integral */
/* 6.4 Pointers and integers */
/* 6.5 Unsigned */
/* 6.6 Arithmetic conversions */
struct defs *pd0;
{
setupTable(pd0);
static char s626er[] = "s626,er%d\n";
static char qs626[8] = "s626 ";
int rc;
char *ps, *pt;
float eps, f1, f2, f3, f4, f;
long lint1, lint2, l, ls;
char c, t[28], t0;
short s;
int is, i, j;
unsigned u, us;
double d, ds;
ps = qs626;
pt = pd0->rfs;
rc = 0;
while (*pt++ = *ps++);
/* Conversions of integral values to floating type are
well-behaved. */
f1 = 1.;
lint1 = 1.;
lint2 = 1.;
for(j=0;j<pd0->lbits-2;j++){
f1 = f1*2;
lint2 = (lint2<<1)|lint1;
}
f2 = lint2;
f1 = (f1-f2)/f1;
if(f1>2.*pd0->fprec){
rc = rc+2;
if(pd0->flgd != 0) printf(s626er,2);
}
/* Pointer-integer combinations are discussed in s74,
"Additive operators". The unsigned-int combination
appears below. */
c = 125;
s = 125;
i = 125; is = 15625;
u = 125; us = 15625;
l = 125; ls = 15625;
f = 125.;
d = 125.; ds = 15625.;
for(j=0;j<28;j++) t[j] = 0;
if(c*c != is) t[ 0] = 1;
if(s*c != is) t[ 1] = 1;
if(s*s != is) t[ 2] = 1;
if(i*c != is) t[ 3] = 1;
if(i*s != is) t[ 4] = 1;
if(i*i != is) t[ 5] = 1;
if(u*c != us) t[ 6] = 1;
if(u*s != us) t[ 7] = 1;
if(u*i != us) t[ 8] = 1;
if(u*u != us) t[ 9] = 1;
if(l*c != ls) t[10] = 1;
if(l*s != ls) t[11] = 1;
if(l*i != ls) t[12] = 1;
if(l*u != us) t[13] = 1;
if(l*l != ls) t[14] = 1;
if(f*c != ds) t[15] = 1;
if(f*s != ds) t[16] = 1;
if(f*i != ds) t[17] = 1;
if(f*u != ds) t[18] = 1;
if(f*l != ds) t[19] = 1;
if(f*f != ds) t[20] = 1;
if(d*c != ds) t[21] = 1;
if(d*s != ds) t[22] = 1;
if(d*i != ds) t[23] = 1;
if(d*u != ds) t[24] = 1;
if(d*l != ds) t[25] = 1;
if(d*f != ds) t[26] = 1;
if(d*d != ds) t[27] = 1;
t0 = 0;
for(j=0; j<28; j++) t0 = t0+t[j];
if(t0 != 0){
rc = rc+4;
if(pd0->flgd != 0){
printf(s626er,4);
printf(" key=");
for(j=0;j<28;j++) printf("%d",t[j]);
printf("\n");
}
}
/* When an unsigned integer is converted to long,
the value of the result is the same numerically
as that of the unsigned integer. */
l = (unsigned)0100000;
if((long)l > (unsigned)0100000){
rc = rc+8;
if(pd0->flgd != 0) printf(s626er,8);
}
return rc;
}
#include "cq-main.h"
|
Java | UTF-8 | 4,230 | 2.09375 | 2 | [] | no_license | package e.b.a.a.a.u;
import e.b.a.a.a.m;
import e.b.a.a.a.n;
import e.b.a.a.a.t;
import e.b.a.a.a.u.t.o;
import e.b.a.a.a.u.t.u;
import e.b.a.a.a.v.b;
import e.b.a.a.a.v.c;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
public class f {
/* renamed from: d reason: collision with root package name */
public static final b f5261d = c.a("org.eclipse.paho.client.mqttv3.internal.nls.logcat", f.class.getName());
/* renamed from: a reason: collision with root package name */
public Hashtable f5262a;
/* renamed from: b reason: collision with root package name */
public String f5263b;
/* renamed from: c reason: collision with root package name */
public n f5264c = null;
public f(String str) {
f5261d.i(str);
this.f5262a = new Hashtable();
this.f5263b = str;
f5261d.h("e.b.a.a.a.u.f", "<Init>", "308");
}
public void a() {
f5261d.e("e.b.a.a.a.u.f", "clear", "305", new Object[]{new Integer(this.f5262a.size())});
synchronized (this.f5262a) {
this.f5262a.clear();
}
}
public int b() {
int size;
synchronized (this.f5262a) {
size = this.f5262a.size();
}
return size;
}
public m[] c() {
m[] mVarArr;
synchronized (this.f5262a) {
f5261d.h("e.b.a.a.a.u.f", "getOutstandingDelTokens", "311");
Vector vector = new Vector();
Enumeration elements = this.f5262a.elements();
while (elements.hasMoreElements()) {
t tVar = (t) elements.nextElement();
if (tVar != null && (tVar instanceof m) && !tVar.f5223a.n) {
vector.addElement(tVar);
}
}
mVarArr = (m[]) vector.toArray(new m[vector.size()]);
}
return mVarArr;
}
public t d(u uVar) {
return (t) this.f5262a.get(uVar.m());
}
public void e(n nVar) {
synchronized (this.f5262a) {
f5261d.e("e.b.a.a.a.u.f", "quiesce", "309", new Object[]{nVar});
this.f5264c = nVar;
}
}
public t f(String str) {
f5261d.e("e.b.a.a.a.u.f", "removeToken", "306", new Object[]{str});
if (str != null) {
return (t) this.f5262a.remove(str);
}
return null;
}
public t g(u uVar) {
return f(uVar.m());
}
public m h(o oVar) {
m mVar;
synchronized (this.f5262a) {
String num = new Integer(oVar.f5339b).toString();
if (this.f5262a.containsKey(num)) {
mVar = (m) this.f5262a.get(num);
f5261d.e("e.b.a.a.a.u.f", "restoreToken", "302", new Object[]{num, oVar, mVar});
} else {
mVar = new m(this.f5263b);
mVar.f5223a.i = num;
this.f5262a.put(num, mVar);
f5261d.e("e.b.a.a.a.u.f", "restoreToken", "303", new Object[]{num, oVar, mVar});
}
}
return mVar;
}
public void i(t tVar, String str) {
synchronized (this.f5262a) {
f5261d.e("e.b.a.a.a.u.f", "saveToken", "307", new Object[]{str, tVar.toString()});
tVar.f5223a.i = str;
this.f5262a.put(str, tVar);
}
}
public void j(t tVar, u uVar) {
synchronized (this.f5262a) {
if (this.f5264c == null) {
String m = uVar.m();
f5261d.e("e.b.a.a.a.u.f", "saveToken", "300", new Object[]{m, uVar});
i(tVar, m);
} else {
throw this.f5264c;
}
}
}
public String toString() {
String stringBuffer;
String property = System.getProperty("line.separator", "\n");
StringBuffer stringBuffer2 = new StringBuffer();
synchronized (this.f5262a) {
Enumeration elements = this.f5262a.elements();
while (elements.hasMoreElements()) {
stringBuffer2.append("{" + ((t) elements.nextElement()).f5223a + "}" + property);
}
stringBuffer = stringBuffer2.toString();
}
return stringBuffer;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.