language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
Markdown
|
UTF-8
| 12,422 | 2.515625 | 3 |
[
"Apache-2.0"
] |
permissive
|
# Run SMV App using Python smv-pyshell
### Synopsis
Start the shell with
```shell
$ smv-pyshell [smv-options] -- [standard spark-shell-options]
```
**Note:** The above command should be run from your project's top level directory.
## SMV Utility methods
* `df(dataset_name, force_run=False, version=None, runConfig=None)` : Load/Run the given dataset and return the resulting `DataFrame`. Force the module to rerun (ignoring cached data) if force_run is True. If a version is specified, load the published data with the given version.
* `help()`: List the following shell commands
* `lsStage()` : list all the stages of the project
* `ls(stage_name)`: list SmvDataSet in the given stage
* `ls()`: list all the SmvDataSet in the project, organized by stages
* `lsDead()`: list `dead` datasets in the project, `dead` dataset is defined as "no contribution to any Output module"
* `lsDead(stage_name)`: list `dead` datasets in the stage
* `lsDeadLead()`: list `dead leaf` datasets in the project, `dead leaf` is `dead` dataset with no module depends on it
* `lsDeadLead(stage_name)`: list `dead leaf` datasets in the stage
* `props()`: Dump json of the final configuration properties used by the running app (includes dynamic runConfig)
* `exportToHive(dataset_name)`: export the running result of the dataset to a hive table
* `ancestors(dataset_name)`: list `ancestors` of the dataset, `ancestors` are all the datasets current dataset depends
* `descendants(datasetName)`: list `descendants` of the dataset, `descendants` are all the datasets depend on the current dataset
* `graphStage()`: print dependency graph of stages and inter-stage links
* `graph(stage_name)`: print dependency graph of all DS in this stage
* `graph()`: print dependency graph of all DS in the app
* `now()`: current system time
* `smvDiscoverSchemaToFile(path, n, csvAttr)` : use the first `n` (default 100000) rows of csv file at given path to discover the schema of the file based on heuristic rules. The discovered schema is saved to the current path with postfix ".schema.toBeReviewed"
## User-defined utility methods
Users may define their own utility methods in `conf/smv_shell_app_init.py`. If the file exists, everything in it will be imported when the shell starts.
## Examples
### Create temporary DataFrame for testing
```python
>>> tmpDF = app.createDF("a:String;b:Integer;c:Timestamp[yyyy-MM-dd]", "a,10,2015-09-30")
>>> tmpDF.printSchema()
root
|-- a: string (nullable = true)
|-- b: integer (nullable = true)
|-- c: timestamp (nullable = true)
>>> tmpDF.show()
+---+---+--------------------+
| a| b| c|
+---+---+--------------------+
| a| 10|2015-09-30 00:00:...|
+---+---+--------------------+
```
### Resolve existing SmvModule
```scala
>>> s2res=df(StageEmpCategory)
>>> s2res.printSchema()
root
|-- ST: string (nullable = true)
|-- EMP: long (nullable = true)
|-- cat_high_emp: boolean (nullable = true)
>>> s2res.count()
res5: Long = 52
>>> s2res.show()
ST EMP cat_high_emp
32 981295 false
33 508120 false
34 3324188 true
....
>>> s2res.smvHist("cat_high_emp")
Histogram of cat_high_emp: Boolean
key count Pct cumCount cumPct
false 20 38.46% 20 38.46%
true 32 61.54% 52 100.00%
-------------------------------------------------
```
### List all the stages
```python
>>> lsStage()
stage1
stage2
```
### List all DataSets
```python
>>> ls()
stage1:
(O) stage1.employment.EmploymentByState
(I) stage1.inputdata.Employment
stage2:
(L) stage1.employment.EmploymentByState
(O) stage2.category.EmploymentByStateCategory
```
There are 4 values of the leading label
* "O" - SmvOutput
* "L" - SmvModuleLink
* "I" - SmvInput (including SmvCsvFile, SmvHiveTable, etc.)
* "M" - SmvModule (but neither SmvOutput nor SmvModuleLink)
Please see [SMV Introduction](smv_intro.md) for details of the 4 types.
### List DataSets in a Stage
```python
>>> ls("stage1")
(O) stage1.employment.EmploymentByState
(I) stage1.inputdata.Employment
```
### List descendants of a given DataSet
```python
>>> descendants("Employment")
(O) stage1.employment.EmploymentByState
(O) stage2.category.EmploymentByStateCategory
```
### List ancestors of a given DataSet
```python
>>> ancestors("EmploymentByState")
(I) stage1.inputdata.Employment
```
### Plot stage level dependency graph
```python
>>> graphStage()
┌──────┐
│stage1│
└───┬──┘
│
v
┌───────────────────────────────────────┐
│(L) stage1.employment.EmploymentByState│
└───────────────────┬───────────────────┘
│
v
┌──────┐
│stage2│
└──────┘
```
### Plot DataSets dependency graph in a stage
```python
>>> graph("stage2")
┌────────────┐
│(O) stage1.e│
│mployment.Em│
│ploymentBySt│
│ ate │
└──────┬─────┘
│
v
┌────────────┐
│(O) category│
│.EmploymentB│
│yStateCatego│
│ ry │
└────────────┘
```
### Plot DataSets dependency graph of the project
```python
>>> graph()
┌────────────┐
│(I) stage1.i│
│nputdata.Emp│
│ loyment │
└──────┬─────┘
│
v
┌────────────┐
│(O) stage1.e│
│mployment.Em│
│ploymentBySt│
│ ate │
└──────┬─────┘
│
v
┌────────────┐
│(O) stage2.c│
│ategory.Empl│
│oymentByStat│
│ eCategory │
└────────────┘
```
# Run SMV App using Scala smv-shell
### Synopsis
```shell
$ smv-shell [smv-options] -- [standard spark-shell-options]
```
**Note:** The above command should be run from the project top level directory.
### Options
By default, the `smv-shell` command will use the latest "fat" jar in the target directory to use with Spark Shell.
The user can provide `--jar` option to override the default. See [Run Application](run_app.md) for details about this flag.
## Shell init
When `smv-shell` is launched, it will source the file `conf/smv_shell_init.scala` to provide some
helper functions and create a default SMV dummy application (`app`)
* `df(data_set)` : Load/Run the given dataset and return the resulting `DataFrame`
* `smvDiscoverSchemaToFile(path, n, ca=CsvAttributes.defaultCsvWithHeader)` : use the first `n` (default 100000) rows of csv file at given path to discover the schema of the file based on heuristic rules. The discovered schema is saved to the current path with postfix
".schema.toBeReviewed"
* `dumpEdd(data_set)` : Generate base EDD results for given `SmvDataSet` and dump the results to the screen.
## Shell package provided functions
With `import org.tresamigos.smv.shell._` in the `smv_shell_init.scala`, the following
functions are provided to the shell,
* `lsStage` : list all the stages of the project
* `ls(stageName)`: list SmvDataSet in the given stage
* `ls`: list all the SmvDataSet in the project, organized by stages
* `graph(stageName)`: print dependency graph of all DS in this stage, without unused input DS
* `graph`: print dependency graph of stages and inter-stage links
* `graph(dataset)`: print in-stage dependency of that DS
* `ancestors(dataset)`: list all `ancestors` of a dataset
* `descendants(dataset)`: list all `descendants` of a dataset
## Project Shell Init
In addition to the standard `smv_shell_init.scala` file, the `smv-shell` script will look for an optional `conf/shell_init.scala` file and source it if found.
Project specific initialization code, such as common imports, and functions, can be put in the `conf/shell_init.scala` file. For example:
```scala
// create the app init object "a" rather than create initialization at top level because shell
// would launch a separate command for each evaluation which slows down startup considerably.
import com.mycompany.myproject.stage1._
import com.mycompany.myproject.stage1._
object a {
//---- common project imports
...
//---- common inputs/functions
lazy val account_sample = df(Accounts).sample(...)
def totalAcounts = df(Accounts).count
...
}
// move the above imports/functions/etc into global namespace for easy access.
import a._
```
## Examples
### Create temporary DataFrame for testing
```scala
scala> val tmpDF = app.createDF("a:String;b:Integer;c:Timestamp[yyyy-MM-dd]", "a,10,2015-09-30")
scala> tmpDF.printSchema
root
|-- a: string (nullable = true)
|-- b: integer (nullable = true)
|-- c: timestamp (nullable = true)
scala> tmpDF.show
a b c
a 10 2015-09-30 00:00:...
```
### Resolve existing SmvModule
```scala
scala> val s2res=s(StageEmpCategory)
scala> s2res.printSchema
root
|-- ST: string (nullable = true)
|-- EMP: long (nullable = true)
|-- cat_high_emp: boolean (nullable = true)
scala> s2res.count
res5: Long = 52
scala> s2res.show
ST EMP cat_high_emp
32 981295 false
33 508120 false
34 3324188 true
....
scala> s2res.edd.histogram("cat_high_emp").eddShow
Histogram of cat_high_emp: Boolean
key count Pct cumCount cumPct
false 20 38.46% 20 38.46%
true 32 61.54% 52 100.00%
-------------------------------------------------
```
### Discover schema
Please see [Schema Discovery](schema_discovery.md)
### List all DataSets
```scala
scala> ls
com.mycompany.MyApp.stage1:
(O) EmploymentByState
(I) input.employment_CB1200CZ11
com.mycompany.MyApp.stage2:
(O) StageEmpCategory
(L) input.EmploymentStateLink
```
There are 4 values of the leading label
* "O" - SmvOutput
* "L" - SmvModuleLink
* "I" - SmvInput
* "M" - SmvModule (but neither SmvOutput nor SmvModuleLink)
Please see [SMV Introduction](smv_intro.md) for details of the 4 types.
### List DataSets in a Stage
```scala
scala> ls("stage1")
(O) EmploymentByState
(I) input.employment_CB1200CZ11
```
### List ancestors of a given DataSet
```scala
scala> ancestors(StageEmpCategory)
(L) stage2.input.EmploymentStateLink
(O) stage1.EmploymentByState
(I) stage1.input.employment_CB1200CZ11
```
### List descendants of a given DataSet
```scala
scala> descendants(EmploymentByState)
(L) stage2.input.EmploymentStateLink
(O) stage2.StageEmpCategory
```
### Plot stage level dependency graph
```scala
scala> graph
┌──────┐
│stage1│
└────┬─┘
│
v
┌────────────────────────────────────────────────┐
│(O) com.mycompany.MyApp.stage1.EmploymentByState│
│ (L) input.EmploymentStateLink │
└───────────────────────┬────────────────────────┘
│
v
┌──────┐
│stage2│
└──────┘
```
### Plot DataSets dependency graph in a stage
```scala
scala> graph("stage2")
┌────────────┐
│(L) input.Em│
│ploymentStat│
│ eLink │
└──────┬─────┘
│
v
┌────────────┐
│(O) StageEmp│
│ Category │
└────────────┘
```
### Plot dependency graph of a single DataSet
```scala
scala> graph(EmploymentByState)
┌────────────┐
│(F) input.em│
│ployment_CB1│
│ 200CZ11 │
└──────┬─────┘
│
v
┌────────────┐
│(O) Employme│
│ ntByState │
└────────────┘
```
|
TypeScript
|
UTF-8
| 1,991 | 2.65625 | 3 |
[] |
no_license
|
import { Hero } from '../../structures/Hero'
export const Anoki: Hero = {
name: 'Anoki',
title: 'The Blood Guard',
skins: [],
union: null,
faction: 'Mauler',
advantage: 'Wilder',
role: 'Control',
type: 'Strength',
class: 'Tank',
trait: 'Dura\'s Fortitude',
armor: 'Plate',
signature: {
name: 'Blood Guards Warhorn',
description: 'Hefty and colossal, this horn of war has been left scarred by the many battles it was used in. Once again it call shall be heard, ushering in a new era of war',
skill: 'War Fury',
unlock: 'This ability raises Anoki\'s attack rating by 4% for every non-summoned ally that is standing near him and raises his Defnese Rating by 10% for every enemy standing near him',
unlock1: 'This ability raises Anoki\'s attack rating by 8% for every non-summoned ally that is standing near him and raises his Defnese Rating by 15% for every enemy standing near him',
unlock2: 'Excluding summoned entities, when there are more than a total of 3 characters on the battlefied (includes enemies and allies), Anoki recovers 5% of his max health per second and becomes immune to control abilities',
unlock3: 'This ability raises Anoki\'s attack rating by 12% for every non-summoned ally that is standing near him and raises his Defnese Rating by 20% for every enemy standing near him'
},
furniture: {
ability: 'Blood Guard\'s Honor',
unlock1: 'Anoki uses his \'Horn of War\' ability again 15 seconds after its initial use. \'Horn of War\' can be used up to 2 times per battle. Each time the ability is used, the shield that it generates will become 50% weaker than the previous shield',
unlock2: 'Anoki uses his \'Horn of War\' ability again 15 seconds after its initial use. \'Horn of War\' can be used up to 3 times per battle. Each time the ability is used, the shield that it generates will become 70% weaker than the previous shield'
}
}
|
Python
|
UTF-8
| 13,430 | 2.546875 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
'''
Created on 31 Jul 2009
@author: charanpal
'''
import unittest
import numpy
import scipy.linalg
import logging
import sys
import numpy.testing as nptst
from apgl.util.Util import Util
from apgl.util.Parameter import Parameter
from apgl.util.PathDefaults import PathDefaults
from apgl.graph.SparseGraph import SparseGraph
#TODO: Test sampleWithoutReplacemnt
#TODO: Test randNormalInt
class UtilTest(unittest.TestCase):
def setUp(self):
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
numpy.random.seed(22)
numpy.set_printoptions(precision=3, suppress=True, linewidth=150)
def tearDown(self):
pass
def testHistogram(self):
v = numpy.array([0, 0, 1, 5, 0, 2, 2, 2, 5])
(freq, items) = Util.histogram(v)
self.assertTrue((freq == numpy.array([3, 1, 3, 2])).all())
self.assertTrue((items == numpy.array([0, 1, 2, 5])).all())
def testComputeMeanVar(self):
pass
def testMode(self):
x = numpy.array([1,1,1,2,2,3,3,3,3,3,5,5])
self.assertEquals(Util.mode(x), 3)
x = numpy.array([1,1,1,2,2,3,3,3,5,5])
self.assertEquals(Util.mode(x), 1)
x = numpy.array([1,2,3,4])
self.assertEquals(Util.mode(x), 1)
x = numpy.array([0])
self.assertEquals(Util.mode(x), 0)
def testRank(self):
X = numpy.random.rand(10, 1)
self.assertEquals(Util.rank(X), 1)
X = numpy.random.rand(10, 12)
self.assertEquals(Util.rank(X), 10)
X = numpy.random.rand(31, 12)
self.assertEquals(Util.rank(X), 12)
K = numpy.dot(X, X.T)
self.assertEquals(Util.rank(X), 12)
def testPrintIteration(self):
#Util.printIteration(0, 1, 1)
#Util.printIteration(0, 1, 10)
#Util.printIteration(9, 1, 10)
#Util.printIteration(9, 1, 11)
#Util.printIteration(1, 1, 7)
pass
def testRandomChoice(self):
v = numpy.array([0.25, 0.25, 0.25])
tol = 10**-2
c = numpy.zeros(3)
numSamples = 500
for i in range(numSamples):
j = Util.randomChoice(v)
#logging.debug(j)
c[j] += 1
self.assertTrue((c/numSamples == numpy.array([0.33, 0.33, 0.33])).all() < tol)
v = v * 20
c = numpy.zeros(3)
for i in range(numSamples):
j = Util.randomChoice(v)
#logging.debug(j)
c[j] += 1
self.assertTrue((c/numSamples == numpy.array([0.33, 0.33, 0.33])).all() < tol)
#Now try different distribution
v = numpy.array([0.2, 0.6, 0.2])
c = numpy.zeros(3)
for i in range(numSamples):
j = Util.randomChoice(v)
#logging.debug(j)
c[j] += 1
self.assertTrue((c/numSamples == v).all() < tol)
#Test empty vector
v = numpy.array([])
self.assertEquals(Util.randomChoice(v), -1)
#Test case where we want multiple random choices
n = 1000
v = numpy.array([0.2, 0.6, 0.2])
j = Util.randomChoice(v, n)
self.assertEquals(j.shape[0], n)
self.assertAlmostEquals(numpy.sum(j==0)/float(n), v[0], places=1)
self.assertAlmostEquals(numpy.sum(j==1)/float(n), v[1], places=1)
#Now test the 2D case
n = 2000
V = numpy.array([[0.1, 0.3, 0.6], [0.6, 0.3, 0.1]])
J = Util.randomChoice(V, n)
self.assertEquals(J.shape[0], V.shape[0])
self.assertEquals(J.shape[1], n)
self.assertAlmostEquals(numpy.sum(J[0, :]==0)/float(n), V[0, 0], places=1)
self.assertAlmostEquals(numpy.sum(J[0, :]==1)/float(n), V[0, 1], places=1)
self.assertAlmostEquals(numpy.sum(J[0, :]==2)/float(n), V[0, 2], places=1)
self.assertAlmostEquals(numpy.sum(J[1, :]==0)/float(n), V[1, 0], places=1)
self.assertAlmostEquals(numpy.sum(J[1, :]==1)/float(n), V[1, 1], places=1)
self.assertAlmostEquals(numpy.sum(J[1, :]==2)/float(n), V[1, 2], places=1)
def testFitPowerLaw(self):
alpha = 2.7
xmin = 1.0
exponent = (1/(alpha))
numPoints = 15000
x = numpy.random.rand(numPoints)**-exponent
x = x[x>=1]
alpha2 = Util.fitPowerLaw(x, xmin)
self.assertAlmostEquals(alpha, alpha2, places=1)
def testFitDiscretePowerLaw(self):
#Test with small x
x = numpy.array([5])
ks, alpha2, xmin = Util.fitDiscretePowerLaw(x)
self.assertEquals(ks, -1)
self.assertEquals(alpha2, -1)
x = numpy.array([5, 2])
ks, alpha2, xmin = Util.fitDiscretePowerLaw(x)
#Test with a large vector x
alpha = 2.5
exponent = (1/(alpha-1))
numPoints = 15000
x = 10*numpy.random.rand(numPoints)**-exponent
x = numpy.array(numpy.round(x), numpy.int)
x = x[x<=500]
x = x[x>=1]
xmins = numpy.arange(1, 15)
ks, alpha2, xmin = Util.fitDiscretePowerLaw(x, xmins)
self.assertAlmostEqual(alpha, alpha2, places=1)
def testFitDiscretePowerLaw2(self):
try:
import networkx
except ImportError:
logging.debug("Networkx not found, can't run test")
return
nxGraph = networkx.barabasi_albert_graph(1000, 2)
graph = SparseGraph.fromNetworkXGraph(nxGraph)
degreeSeq = graph.outDegreeSequence()
output = Util.fitDiscretePowerLaw(degreeSeq)
def testEntropy(self):
v = numpy.array([0, 0, 0, 1, 1, 1])
self.assertEquals(Util.entropy(v), 1)
v = numpy.array([0, 0, 0])
self.assertEquals(Util.entropy(v), 0)
v = numpy.array([1, 1, 1])
self.assertEquals(Util.entropy(v), 0)
def testExpandIntArray(self):
v = numpy.array([1, 3, 2, 4], numpy.int)
w = Util.expandIntArray(v)
self.assertTrue((w == numpy.array([0,1,1,1,2,2,3,3,3,3], numpy.int)).all())
v = numpy.array([], numpy.int)
w = Util.expandIntArray(v)
self.assertTrue((w == numpy.array([], numpy.int)).all())
def testRandom2Choice(self):
n = 1000
V = numpy.array([[0.3, 0.7], [0.5, 0.5]])
J = Util.random2Choice(V, n)
self.assertAlmostEquals(numpy.sum(J[0, :]==0)/float(n), V[0, 0], places=1)
self.assertAlmostEquals(numpy.sum(J[0, :]==1)/float(n), V[0, 1], places=1)
self.assertAlmostEquals(numpy.sum(J[1, :]==0)/float(n), V[1, 0], places=1)
self.assertAlmostEquals(numpy.sum(J[1, :]==1)/float(n), V[1, 1], places=1)
#Now use a vector of probabilities
v = numpy.array([0.3, 0.7])
j = Util.random2Choice(v, n)
self.assertAlmostEquals(numpy.sum(j==0)/float(n), v[0], places=1)
self.assertAlmostEquals(numpy.sum(j==1)/float(n), v[1], places=1)
def testIncompleteCholesky(self):
numpy.random.seed(21)
A = numpy.random.rand(5, 5)
B = A.T.dot(A)
k = 4
R = Util.incompleteCholesky2(B, k)
R2 = numpy.linalg.cholesky(B)
#logging.debug(R)
#logging.debug(R2)
#logging.debug(B)
#logging.debug(R.T.dot(R))
def testSvd(self):
tol = 10**-6
A = numpy.random.rand(10, 3)
P, s, Q = numpy.linalg.svd(A, full_matrices=False)
A = P[:, 0:2].dot(numpy.diag(s[0:2]).dot(Q[0:2, :]))
P2, s2, Q2 = Util.svd(A)
self.assertTrue(numpy.linalg.norm(P2.dot(numpy.diag(s2)).dot(Q2) -A) < tol )
self.assertTrue(numpy.linalg.norm(P2.conj().T.dot(P2) - numpy.eye(P2.shape[1])) < tol)
self.assertTrue(numpy.linalg.norm(Q2.dot(Q2.conj().T) - numpy.eye(Q2.shape[0])) < tol)
def testPowerLawProbs(self):
alpha = 3
zeroVal = 0.1
maxInt = 100
p = Util.powerLawProbs(alpha, zeroVal, maxInt)
self.assertTrue(p.shape[0] == maxInt)
def testPrintConsiseIteration(self):
#for i in range(10):
# Util.printConciseIteration(i, 1, 10)
pass
def testMatrixPower(self):
A = numpy.random.rand(10, 10)
tol = 10**-6
A2 = A.dot(A)
lmbda, V = scipy.linalg.eig(A)
A12 = Util.matrixPower(A, 0.5)
self.assertTrue(numpy.linalg.norm(A12.dot(A12) - A) < tol)
self.assertTrue(numpy.linalg.norm(numpy.linalg.inv(A) - Util.matrixPower(A, -1)) < tol)
self.assertTrue(numpy.linalg.norm(A - Util.matrixPower(A, 1)) < tol)
self.assertTrue(numpy.linalg.norm(A2 - Util.matrixPower(A, 2)) < tol)
self.assertTrue(numpy.linalg.norm(numpy.linalg.inv(A).dot(numpy.linalg.inv(A)) - Util.matrixPower(A, -2)) < tol)
#Now lets test on a low rank matrix
lmbda[5:] = 0
A = V.dot(numpy.diag(lmbda)).dot(numpy.linalg.inv(V))
A2 = A.dot(A)
A12 = Util.matrixPower(A, 0.5)
Am12 = Util.matrixPower(A, -0.5)
self.assertTrue(numpy.linalg.norm(numpy.linalg.pinv(A) - Util.matrixPower(A, -1)) < tol)
self.assertTrue(numpy.linalg.norm(numpy.linalg.pinv(A) - Am12.dot(Am12)) < tol)
self.assertTrue(numpy.linalg.norm(A12.dot(A12) - A) < tol)
self.assertTrue(numpy.linalg.norm(A - Util.matrixPower(A, 1)) < tol)
self.assertTrue(numpy.linalg.norm(A2 - Util.matrixPower(A, 2)) < tol)
def testMatrixPowerh(self):
A = numpy.random.rand(10, 10)
A = A.T.dot(A)
tol = 10**-6
A2 = A.dot(A)
lmbda, V = scipy.linalg.eig(A)
A12 = Util.matrixPowerh(A, 0.5)
self.assertTrue(numpy.linalg.norm(A12.dot(A12) - A) < tol)
self.assertTrue(numpy.linalg.norm(numpy.linalg.inv(A) - Util.matrixPowerh(A, -1)) < tol)
self.assertTrue(numpy.linalg.norm(A - Util.matrixPowerh(A, 1)) < tol)
self.assertTrue(numpy.linalg.norm(A2 - Util.matrixPowerh(A, 2)) < tol)
self.assertTrue(numpy.linalg.norm(numpy.linalg.inv(A).dot(numpy.linalg.inv(A)) - Util.matrixPowerh(A, -2)) < tol)
#Now lets test on a low rank matrix
lmbda[5:] = 0
A = V.dot(numpy.diag(lmbda)).dot(numpy.linalg.inv(V))
A2 = A.dot(A)
A12 = Util.matrixPowerh(A, 0.5)
Am12 = Util.matrixPowerh(A, -0.5)
self.assertTrue(numpy.linalg.norm(numpy.linalg.pinv(A) - Util.matrixPowerh(A, -1)) < tol)
self.assertTrue(numpy.linalg.norm(numpy.linalg.pinv(A) - Am12.dot(Am12)) < tol)
self.assertTrue(numpy.linalg.norm(A12.dot(A12) - A) < tol)
self.assertTrue(numpy.linalg.norm(A - Util.matrixPowerh(A, 1)) < tol)
self.assertTrue(numpy.linalg.norm(A2 - Util.matrixPowerh(A, 2)) < tol)
def testDistanceMatrix(self):
numExamples1 = 10
numExamples2 = 15
numFeatures = 2
U = numpy.random.randn(numExamples1, numFeatures)
V = numpy.random.randn(numExamples2, numFeatures)
D = Util.distanceMatrix(U, V)
D2 = numpy.zeros((numExamples1, numExamples2))
for i in range(numExamples1):
for j in range(numExamples2):
D2[i, j] = numpy.sqrt(numpy.sum((U[i, :] - V[j, :])**2))
nptst.assert_almost_equal(D, D2)
def testCumMin(self):
v = numpy.array([5, 6, 4, 5, 1])
u = Util.cumMin(v)
nptst.assert_array_equal(u, numpy.array([5, 5, 4, 4, 1]))
v = numpy.array([5, 4, 3, 2, 1])
u = Util.cumMin(v)
nptst.assert_array_equal(u, v)
v = numpy.array([1, 2, 3])
u = Util.cumMin(v)
nptst.assert_array_equal(u, numpy.ones(3))
def testExtendArray(self):
X = numpy.random.rand(5, 5)
X2 = Util.extendArray(X, (10, 5))
nptst.assert_array_equal(X, X2[0:5, :])
nptst.assert_array_equal(0, X2[5:, :])
X2 = Util.extendArray(X, (10, 5), 1.23)
nptst.assert_array_equal(X, X2[0:5, :])
nptst.assert_array_equal(1.23, X2[5:, :])
#Now try extending using an array
X2 = Util.extendArray(X, (10, 5), numpy.array([1, 2, 3, 4, 5]))
nptst.assert_array_equal(X, X2[0:5, :])
for i in range(5, 10):
nptst.assert_array_equal(numpy.array([1, 2, 3, 4, 5]), X2[i, :])
def testPowerEigs(self):
n = 10
numRuns = 10
for i in range(numRuns):
A = numpy.random.rand(n, n)
l, v = Util.powerEigs(A, 0.001)
nptst.assert_array_almost_equal(v*l, A.dot(v), 2)
u, V = numpy.linalg.eig(A)
self.assertAlmostEquals(numpy.max(u), l, 2)
try:
nptst.assert_array_almost_equal(V[:, 0], v, 2)
except AssertionError:
nptst.assert_array_almost_equal(V[:, 0], -v, 2)
if __name__ == "__main__":
unittest.main()
|
PHP
|
UTF-8
| 1,064 | 3 | 3 |
[] |
no_license
|
<?php declare(strict_types=1);
namespace MySelf\Scrabble\Application\StartGameService;
use MySelf\Scrabble\Application\DisplayBoardService\DisplayBoardService;
use MySelf\Scrabble\Domain\Games\GameRepository;
use MySelf\Scrabble\Domain\Players\PlayerRepository;
class StartGameService
{
private GameRepository $gameRepository;
private PlayerRepository $playerRepository;
private DisplayBoardService $boardService;
public function __construct(
DisplayBoardService $boardService,
PlayerRepository $playerRepository,
GameRepository $gameRepository
) {
$this->gameRepository = $gameRepository;
$this->playerRepository = $playerRepository;
$this->boardService = $boardService;
}
public function run(string $player): array
{
$game = $this->gameRepository->getPlayerGame(
$this->playerRepository->getPlayer($player)
);
$game->start();
$this->gameRepository->save($game);
return $this->boardService->run($game->getBoard());
}
}
|
Python
|
UTF-8
| 1,114 | 3.0625 | 3 |
[] |
no_license
|
import msvcrt
import pyautogui
pyautogui.PAUSE = 1
pyautogui.FAILSAFE = True
def wait():
while True:
if msvcrt.kbhit():
chr = msvcrt.getch()
if chr == b"\x1b":
print("ESCAPE")
circle()
def circle():
x,y = pyautogui.position()
pyautogui.mouseDown()
action = 0
while True:
if msvcrt.kbhit():
chr = msvcrt.getch()
if chr == b"\x1b":
pyautogui.mouseUp()
print("ESCAPE")
return
if action == 0:
pyautogui.moveRel(0,100,.5)
action += 1
elif action == 1:
pyautogui.moveRel(100,0,.5)
action += 1
elif action == 2:
pyautogui.moveRel(0,-100,.5)
action += 1
else:
pyautogui.moveRel(-100,0,.5)
action = 0
wait()
"""
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)
>> pyautogui.moveTo(100, 200, 2) # moves mouse to X of 100, Y of 200 over 2 seconds
"""
|
C++
|
UTF-8
| 2,785 | 3.5625 | 4 |
[] |
no_license
|
/*
* List.cpp
*
* Created on: Feb 12, 2015
* Author: juncheng
*/
#include "List.h"
#define SUCCESS 0;
#include "stddef.h"
#include <iostream>
using namespace std;
List::List() {
this->head = NULL;
}
List::List(Node* node){
this->head = node;
}
List::List(const List* l) {
this->head=NULL;
Node* cur = l->head;
while(cur!=NULL) {
this->tailAppend(cur->value);
cur = cur->next;
}
}
void List::tailAppend(int value) {
Node *n=new Node;
n->value=value;
n->next = NULL;
Node *cur = this->head;
if(cur==NULL)
head=n;
while(cur) {
if(cur->next == NULL) {
cur->next = n;
break;
}
cur = cur->next;
}
}
void List::print() const {
Node *cur = this->head;
while(cur!=NULL) {
cout<< cur->value << " -> ";
cur = cur->next;
}
cout << " Null " << endl;
}
void List::duplicateRemove() {
int val;
Node* backupNode;
Node* cur = this->head;
while(cur!=NULL) {
val = cur->value;
backupNode = cur;
cur = cur->next;
Node* cur2 = cur;
while(cur2!=NULL) {
if(cur2->value==val) {
backupNode->next = cur2->next;
cur2 = backupNode->next;
}
else{
backupNode = cur2;
cur2= cur2->next;
}
}
}
}
List::~List() {
Node* cur = this->head;
Node* backupNode;
while(cur!=NULL) {
backupNode = cur->next;
delete cur;
cur = backupNode->next;
}
}
void List::reverse() {
Node* cur=this->head;
Node* backupNode = cur;
Node* backupNext= cur->next;
while(backupNext!=NULL) {
cur = backupNext;
backupNext = cur->next;
cur->next = backupNode;
backupNode = cur;
}
this->head->next = NULL;
this->head = cur;
}
bool palindrome(Node* list) {
List* l = new List(list);
List* newList = new List(l);
newList->reverse();
Node* cur = l->head;
Node* newCur = newList->head;
while(cur!=NULL) {
if(cur->value != newCur->value) {
cout << "This list is NOT a palindrome. " << endl;
return false;
}
cur = cur->next;
newCur = newCur->next;
}
cout << "This list is a palindrome. " << endl;
return true;
}
void braid(Node* list) {
List* oldList = new List(list);
List* newList = new List(oldList);
newList->reverse();
Node* cur = oldList->head;
while(cur->next!=NULL) {
cur = cur->next;
}
cur->next = newList->head;
//list = oldList->head;
}
int main() {
List *list = new List();
list->tailAppend(1);
list->tailAppend(5);
list->tailAppend(7);
list->tailAppend(4);
list->tailAppend(4);
list->tailAppend(4);
list->tailAppend(7);
list->tailAppend(5);
list->tailAppend(1);
cout << "Original List: " << endl;
list->print();
cout << "(a) ";
palindrome(list->head);
cout << "(d) After braiding: " << endl;
braid(list->head);
list->print();
cout << "(c) After duplicating remove:" << endl;
list->duplicateRemove();
list->print();
delete list;
return SUCCESS;
}
|
Java
|
UTF-8
| 696 | 3.40625 | 3 |
[] |
no_license
|
package entities;
public class Account {
private Float balance;
public Account(Float balance) {
this.balance = balance;
}
public void doDeposit(Float amount) {
balance += amount;
}
public Boolean doWithdrawn(Float amount)
{
if ((balance - amount) < 0)
return false;
else {
balance -= amount;
return true;
}
}
public void doTransfer(Float amount, Account account1,Account account2) {
if(account2.doWithdrawn(amount)) account1.doDeposit(amount);
}
public Float showBalance(Account account)
{
return account.balance;
}
}
|
Markdown
|
UTF-8
| 1,348 | 3.015625 | 3 |
[] |
no_license
|
Bamazon ReadMe
================
Bamazon Userflow
----------------
This Bamazon application will mimic the Amazon user interface and allow customers to
purchase items. When the program is run the items available for purchase will be listed with the following information:
Item_Id | Item Name | Item Department | Item price
The user will then be prompted to enter the ID of the item that they wish to purchase.
After an item is selected for purchase the user will then be prompted to ask what quantity
of the item they would like to buy. Once they enter the quantity that they would like to buy the user will be notified of one of two things:
1. The user will be notified that there is enough stock in order to fulfill their order request and be given the total price of their order. In this scenario the MySQL database will also be updated to reflect the new stock quantity in the warehouse.
2. The user will be notified that there is not enough stock to fulfill their order request. The user will also be notified of remaining stock in the warehouse.
After both scenarios the user will then be asked if they would like to continue and look at the list of items to purchase and restart the process. If they select no the process will exit.
Video Link for Customer Userflow
--------------------------------
https://youtu.be/pUMMXwikSss
|
Shell
|
UTF-8
| 214 | 3.140625 | 3 |
[] |
no_license
|
#!/bin/sh
declare PT_host_entry
(( EUID == 0 )) || fail "This utility must be run as root"
getent hosts "$(echo ${PT_host_entry} | awk '{print $2}')" > /dev/null && exit 0
echo "${PT_host_entry}" >> /etc/hosts
|
Java
|
ISO-8859-1
| 17,995 | 2.296875 | 2 |
[] |
no_license
|
/**
*
*/
package DAO;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.object.StoredProcedure;
import Bean.ItemColecao;
import Bean.Pesquisa;
import Bean.Resultado;
import RowMapper.ItemColecaoHomeRowMapper;
import RowMapper.ItemColecaoListaRowMapper;
import RowMapper.ItemColecaoRowMapper;
import RowMapper.ItemListaDesejoRowMapper;
import Util.Utility;
/**
* @author marcos
*
*/
public class ItemColecaoDao {
private JdbcTemplate jdbcTemplate ;
private StoredProcedure procedureCadastroItemColecao;
public ItemColecao cadastroItemColecao (ItemColecao itemColecao){
Map<String, Object> parametros = new HashMap<String, Object>();
Map<String, Object> parametrosOut = new HashMap<String, Object>();
parametros.put("prc_obs_item", itemColecao.getObservacaoItem());
parametros.put("prc_id_estima_item_fk", itemColecao.getEstimaItem().getIdEstimaItem());
parametros.put("prc_id_edicao_album_fk", itemColecao.getEdicaoAlbum().getIdEdicaoAlbum());
parametros.put("prc_id_usuario_pk", itemColecao.getUsuario().getIdUsuario());
parametros.put("prc_dt_adicao_item", itemColecao.getDataAdicaoItem());
parametros.put("prc_quantidade_item", itemColecao.getQuantidadeItem());
parametros.put("prc_estado_item_caixa", itemColecao.getEstadoCaixa());
parametros.put("prc_estado_item_midia", itemColecao.getEstadoMidia());
parametros.put("prc_estado_item_encarte", itemColecao.getEstadoEncarte());
parametrosOut = procedureCadastroItemColecao.execute(parametros);
itemColecao = new ItemColecao();
itemColecao.getResultado().setCode((String)parametrosOut.get("prc_codigo"));
itemColecao.setIdItemColecao((int)parametrosOut.get("prc_id_item_colecao"));
itemColecao.getResultado().setMensagem((String)parametrosOut.get("prc_mensagem"));
return itemColecao;
}
public Resultado cadastroItemListaDesejo (ItemColecao itemColecao){
Resultado resultado = new Resultado();
String sql = "Insert into Lista_Desejo_Item (id_edicao_album_fk, id_usuario_pf_fk, dt_adicao) values (?,?,CURDATE())";
Object [] parametros = {itemColecao.getEdicaoAlbum().getIdEdicaoAlbum(),itemColecao.getUsuario().getIdUsuario()};
int result = jdbcTemplate.update(sql, parametros);
if(result > 0){
resultado.setCode("0");
resultado.setMensagem("Item adicionado com sucesso");
}else{
resultado.setCode("0");
resultado.setMensagem("Erro ao adicionar item");
}
return resultado;
}
public Resultado atualizaItemColecao(ItemColecao itemColecao){
String sql = "UPDATE Item_Colecao SET obs_item = ?, id_estima_item_fk = ?,"
+ " quantidade_item = ?, estado_item_caixa = ?, estado_item_midia = ?, estado_item_encarte = ?"
+ " WHERE id_item_colecao = ?";
Object [] parametros = {itemColecao.getObservacaoItem(),
itemColecao.getEstimaItem().getIdEstimaItem(),
itemColecao.getQuantidadeItem(),
itemColecao.getEstadoCaixa(),
itemColecao.getEstadoMidia(),
itemColecao.getEstadoEncarte(),
itemColecao.getIdItemColecao()};
int result = jdbcTemplate.update(sql, parametros);
Resultado resultado = new Resultado();
if(result > 0){
resultado.setCode("0");
resultado.setCode("Item atualizado com sucesso");
}else{
resultado.setCode("-1");
resultado.setCode("No foi possivel atualizar o item");
}
return resultado;
}
public Resultado deleteItemColecao(ItemColecao itemColecao){
String sql = "DELETE FROM Item_Colecao WHERE id_item_colecao = ?";
Object [] parametros = {itemColecao.getIdItemColecao()};
int result = jdbcTemplate.update(sql, parametros);
Resultado resultado = new Resultado();
if(result > 0){
resultado.setCode("0");
resultado.setCode("Item deletado com sucesso");
}else{
resultado.setCode("-1");
resultado.setCode("No foi possivel deletar o item");
}
return resultado;
}
public Resultado deleteItemListaDesejo(ItemColecao itemColecao){
String sql = "delete from Lista_Desejo_Item where id_edicao_album_fk = ? and id_usuario_pf_fk = ?";
Object [] parametros = {itemColecao.getEdicaoAlbum().getIdEdicaoAlbum(),itemColecao.getUsuario().getIdUsuario()};
int result = jdbcTemplate.update(sql, parametros);
Resultado resultado = new Resultado();
if(result > 0){
resultado.setCode("0");
resultado.setCode("Item deletado com sucesso");
}else{
resultado.setCode("-1");
resultado.setCode("No foi possivel deletar o item");
}
return resultado;
}
//Exibira todos os dados de um item especifico, sera usado como parametro o id do item da colecao
public ItemColecao consultaItemColecaoId(int idItemColecao){
List<ItemColecao> listaItemColecao = new ArrayList<ItemColecao>();
String sql ="Select ic.id_item_colecao, ic.obs_item, ic.quantidade_item, ic.estado_item_caixa, ic.estado_item_midia, ic.estado_item_encarte,"
+ "ei.id_estima_item,ei.desc_estima_item,"
+ "tm.nm_tipo_midia,"
+ "ea.nm_edicao_album, ea.data_lancamento_edicao_album, ea.capa_edicao_album,"
+ "pa.nm_pais, pa.bandeira_pais,"
+ "gr.nm_gravadora,"
+ "ar.nm_artista,"
+ "al.nm_album"
+ " from Item_Colecao ic, Estima_Item ei, Tipo_Midia tm, Edicao_Album ea, Pais pa,"
+ " Gravadora gr, Artista ar, Album al"
+ " where ic.id_item_colecao = ?"
+ " and ic.id_estima_item_fk = ei.id_estima_item"
+ " and ic.id_edicao_album_fk = ea.id_edicao_album"
+ " and ea.id_pais_fk = pa.id_pais"
+ " and ea.id_gravadora_fk = gr.id_gravadora"
+ " and ea.id_tipo_midia_fk = tm.id_tipo_midia"
+ " and ea.id_album_fk = al.id_album"
+ " and al.id_artista_fk = ar.id_artista" ;
Object [] parametros = {idItemColecao};
listaItemColecao = jdbcTemplate.query(sql, parametros, new ItemColecaoRowMapper());
ItemColecao itemColecao = new ItemColecao();
if(listaItemColecao.size() > 0){
itemColecao = listaItemColecao.get(0);
}
return itemColecao;
}
//Opercao paginada, esse metodo retornara os itens de uma colecao de usuario limitando seu retorno a 10 itens por chamada
//Os 10 itens que serao retornados serao decididos de acordo com o numero da pagina enviada
public List<ItemColecao> consultaItemColecaoListaIdUsuario(Pesquisa pesquisa){
List<ItemColecao> listaItemColecao = new ArrayList<ItemColecao>();
int limiteFinal = pesquisa.getNumeroPagina() * 10;
int limiteInicial = limiteFinal - 10;
String sql ="Select ic.id_item_colecao,"
+ "ei.desc_estima_item,"
+ "tm.nm_tipo_midia,"
+ "ea.nm_edicao_album, ea.data_lancamento_edicao_album, ea.capa_edicao_album,"
+ "pa.nm_pais, pa.bandeira_pais,"
+ "gr.nm_gravadora,"
+ "ar.nm_artista,"
+ "al.nm_album"
+ " from Item_Colecao ic, Estima_Item ei, Tipo_Midia tm, Edicao_Album ea, Pais pa,"
+ " Gravadora gr, Artista ar, Album al"
+ " where ic.id_usuario_pk = ?"
+ " and ic.id_estima_item_fk = ei.id_estima_item"
+ " and ic.id_edicao_album_fk = ea.id_edicao_album"
+ " and ea.id_pais_fk = pa.id_pais"
+ " and ea.id_gravadora_fk = gr.id_gravadora"
+ " and ea.id_tipo_midia_fk = tm.id_tipo_midia"
+ " and ea.id_album_fk = al.id_album"
+ " and al.id_artista_fk = ar.id_artista"
+ " LIMIT ?,?" ;
Object [] parametros = {pesquisa.getIdUsuario(),limiteInicial, limiteFinal};
listaItemColecao = jdbcTemplate.query(sql, parametros, new ItemColecaoListaRowMapper());
return listaItemColecao;
}
//Opercao paginada, esse metodo retornara os itens de uma colecao de usuario limitando seu retorno a 10 itens por chamada
//Os 10 itens que serao retornados serao decididos de acordo com o numero da pagina enviada
public List<ItemColecao> consultaItemColecaoListaGuidUsuario(Pesquisa pesquisa){
List<ItemColecao> listaItemColecao = new ArrayList<ItemColecao>();
int limiteFinal = pesquisa.getNumeroPagina() * 10;
int limiteInicial = limiteFinal - 10;
String sql ="Select ic.id_item_colecao,"
+ "ei.desc_estima_item,"
+ "tm.nm_tipo_midia,"
+ "ea.nm_edicao_album, ea.data_lancamento_edicao_album, ea.capa_edicao_album,"
+ "pa.nm_pais, pa.bandeira_pais,"
+ "gr.nm_gravadora,"
+ "ar.nm_artista,"
+ "al.nm_album"
+ " from Item_Colecao ic, Estima_Item ei, Tipo_Midia tm, Edicao_Album ea, Pais pa,"
+ " Gravadora gr, Artista ar, Album al, Usuario us"
+ " where us.guid_usuario = ? "
+ " and ic.id_usuario_pk = us.id_usuario "
+ " and ic.id_estima_item_fk = ei.id_estima_item"
+ " and ic.id_edicao_album_fk = ea.id_edicao_album"
+ " and ea.id_pais_fk = pa.id_pais"
+ " and ea.id_gravadora_fk = gr.id_gravadora"
+ " and ea.id_tipo_midia_fk = tm.id_tipo_midia"
+ " and ea.id_album_fk = al.id_album"
+ " and al.id_artista_fk = ar.id_artista"
+ " LIMIT ?,?" ;
Object [] parametros = {pesquisa.getGuidUsuario(),limiteInicial, limiteFinal};
listaItemColecao = jdbcTemplate.query(sql, parametros, new ItemColecaoListaRowMapper());
return listaItemColecao;
}
//Opercao paginada, esse metodo retornara os itens de uma lista de desejo de usuario limitando seu retorno a 10 itens por chamada
//Os 10 itens que serao retornados serao decididos de acordo com o numero da pagina enviada
public List<ItemColecao> consultaItemListaDesejoIdUsuario(Pesquisa pesquisa){
List<ItemColecao> listaItemColecao = new ArrayList<ItemColecao>();
int limiteFinal = pesquisa.getNumeroPagina() * 10;
int limiteInicial = limiteFinal - 10;
String sql ="Select id.id_edicao_album_fk, id.dt_adicao,"
+ "tm.nm_tipo_midia,"
+ "ea.nm_edicao_album, ea.data_lancamento_edicao_album, ea.capa_edicao_album,"
+ "pa.nm_pais, pa.bandeira_pais,"
+ "gr.nm_gravadora,"
+ "ar.nm_artista,"
+ "al.nm_album"
+ " from Lista_Desejo_Item id, Tipo_Midia tm, Edicao_Album ea, Pais pa,"
+ " Gravadora gr, Artista ar, Album al "
+ " where id.id_usuario_pf_fk = ? "
+ " and id.id_edicao_album_fk = ea.id_edicao_album "
+ " and ea.id_pais_fk = pa.id_pais "
+ " and ea.id_gravadora_fk = gr.id_gravadora "
+ " and ea.id_tipo_midia_fk = tm.id_tipo_midia "
+ " and ea.id_album_fk = al.id_album "
+ " and al.id_artista_fk = ar.id_artista"
+ " limit ?,?" ;
Object [] parametros = {pesquisa.getIdUsuario(),limiteInicial,limiteFinal};
listaItemColecao = jdbcTemplate.query(sql, parametros, new ItemListaDesejoRowMapper());
return listaItemColecao;
}
//Opercao paginada, esse metodo retornara os itens de uma lista de desejo de usuario limitando seu retorno a 10 itens por chamada
//Os 10 itens que serao retornados serao decididos de acordo com o numero da pagina enviada
public List<ItemColecao> consultaItemListaDesejoGuidUsuario(Pesquisa pesquisa){
List<ItemColecao> listaItemColecao = new ArrayList<ItemColecao>();
int limiteFinal = pesquisa.getNumeroPagina() * 10;
int limiteInicial = limiteFinal - 10;
String sql ="Select id.id_edicao_album_fk, id.dt_adicao,"
+ "tm.nm_tipo_midia,"
+ "ea.nm_edicao_album, ea.data_lancamento_edicao_album, ea.capa_edicao_album,"
+ "pa.nm_pais, pa.bandeira_pais,"
+ "gr.nm_gravadora,"
+ "ar.nm_artista,"
+ "al.nm_album"
+ " from Lista_Desejo_Item id, Tipo_Midia tm, Edicao_Album ea, Pais pa,"
+ " Gravadora gr, Artista ar, Album al, Usuario us"
+ " where us.guid_usuario = ?"
+ " and id.id_usuario_pf_fk = us.id_usuario "
+ " and id.id_edicao_album_fk = ea.id_edicao_album "
+ " and ea.id_pais_fk = pa.id_pais "
+ " and ea.id_gravadora_fk = gr.id_gravadora "
+ " and ea.id_tipo_midia_fk = tm.id_tipo_midia "
+ " and ea.id_album_fk = al.id_album "
+ " and al.id_artista_fk = ar.id_artista"
+ " limit ?,?" ;
Object [] parametros = {pesquisa.getGuidUsuario(),limiteInicial,limiteFinal};
listaItemColecao = jdbcTemplate.query(sql, parametros, new ItemListaDesejoRowMapper());
return listaItemColecao;
}
//Operacao para retornar os itens da colecao do usuario na pagina inicial ou de perfil usando como parametro a guid do usuario
public List<ItemColecao> consultaItemColecaoHomeGuidUsuario(String guidUsuario){
List<ItemColecao> listaItemColecao = new ArrayList<ItemColecao>();
String sql ="select ea.id_edicao_album, ea.nm_edicao_album, ea.capa_edicao_album, "
+ "tm.nm_tipo_midia, "
+ "ar.nm_artista, "
+ "al.nm_album "
+ "from Edicao_Album ea, Item_Colecao ic, Usuario us, Tipo_Midia tm, "
+ "Album al, Artista ar "
+ " where us.guid_usuario = ?"
+ " and ic.id_usuario_pk = us.id_usuario "
+ "and ic.id_edicao_album_fk = ea.id_edicao_album "
+ "and ea.id_tipo_midia_fk = tm.id_tipo_midia "
+ "and al.id_album = ea.id_album_fk "
+ "and ar.id_artista = al.id_artista_fk "
+ "limit 4" ;
Object [] parametros = {guidUsuario};
listaItemColecao = jdbcTemplate.query(sql, parametros, new ItemColecaoHomeRowMapper());
return listaItemColecao;
}
//Operacao para retornar os itens da colecao do usuario na pagina inicial ou de perfil usando como parametroo id do usuario
public List<ItemColecao> consultaItemColecaoHomeIdUsuario(int idUsuario){
List<ItemColecao> listaItemColecao = new ArrayList<ItemColecao>();
String sql ="select ea.id_edicao_album, ea.nm_edicao_album, ea.capa_edicao_album, "
+ "tm.nm_tipo_midia, "
+ "ar.nm_artista, "
+ "al.nm_album "
+ "from Edicao_Album ea, Item_Colecao ic, Usuario us, Tipo_Midia tm, "
+ "Album al, Artista ar "
+ "where us.id_usuario = ? "
+ "and ic.id_usuario_pk = us.id_usuario "
+ "and ic.id_edicao_album_fk = ea.id_edicao_album "
+ "and ea.id_tipo_midia_fk = tm.id_tipo_midia "
+ "and al.id_album = ea.id_album_fk "
+ "and ar.id_artista = al.id_artista_fk "
+ "limit 4" ;
Object [] parametros = {idUsuario};
listaItemColecao = jdbcTemplate.query(sql, parametros, new ItemColecaoHomeRowMapper());
return listaItemColecao;
}
//Essa opercao sera responsavel por retornar a quantidade de paginas na exibicao de todos os itens da lista de desejo
//o parametro de entrada sera o id do usuario
public int consultaNumeroPaginaListaDesejoItemIdUsuario(int idUsuario){
String sql = "Select (select COUNT(*) from lista_desejo_item ld, usuario us"
+ " where us.id_usuario = ? "
+ " and ld.id_usuario_pf_fk = us.id_usuario)";
Object [] parametros = {idUsuario};
int numeroFavorito = jdbcTemplate.queryForInt(sql,parametros);
return Utility.calculoQuantidadePagina(numeroFavorito, 10.0);
}
//Essa opercao sera responsavel por retornar a quantidade de paginas na exibicao de todos os itens da lista de desejo
//o parametro de entrada sera a guid do usuario
public int consultaNumeroPaginaListaDesejoItemGuidUsuario(String guidUsuario){
String sql = "Select (select COUNT(*) from lista_desejo_item ld, usuario us"
+ " where us.guid_usuario = ? "
+ " and ld.id_usuario_pf_fk = us.id_usuario)";
Object [] parametros = {guidUsuario};
int numeroFavorito = jdbcTemplate.queryForInt(sql,parametros);
return Utility.calculoQuantidadePagina(numeroFavorito, 10.0);
}
//Essa opercao sera responsavel por retornar a quantidade de paginas na exibicao de todos os itens da colecao
//o parametro de entrada sera o id do usuario
public int consultaNumeroPaginaItemColecaoIdUsuario(int idUsuario){
String sql = "Select (select COUNT(*) from item_colecao ic, usuario us "
+ " where us.id_usuario = ? "
+ "and ic.id_usuario_pk = us.id_usuario)";
Object [] parametros = {idUsuario};
int numeroFavorito = jdbcTemplate.queryForInt(sql,parametros);
return Utility.calculoQuantidadePagina(numeroFavorito, 10.0);
}
//Essa opercao sera responsavel por retornar a quantidade de paginas na exibicao de todos os itens da colecao
//o parametro de entrada sera a guid do usuario
public int consultaNumeroPaginaItemColecaoGuidUsuario(String guidUsuario){
String sql = "Select (select COUNT(*) from item_colecao ic, usuario us "
+ " where us.guid_usuario = ? "
+ "and ic.id_usuario_pk = us.id_usuario)";
Object [] parametros = {guidUsuario};
int numeroFavorito = jdbcTemplate.queryForInt(sql,parametros);
return Utility.calculoQuantidadePagina(numeroFavorito, 10.0);
}
//Opercao paginada, esse metodo retornara os itens de uma lista de desejo de usuario que apareceram na home
public List<ItemColecao> consultaItemListaDesejoHomeIdUsuario(int idUsuario){
List<ItemColecao> listaItemColecao = new ArrayList<ItemColecao>();
String sql ="select ea.id_edicao_album,"
+ " tm.nm_tipo_midia, "
+ " ea.nm_edicao_album, ea.capa_edicao_album, "
+ " ar.nm_artista, "
+ " al.nm_album "
+ " from Lista_Desejo_Item id, Tipo_Midia tm, Edicao_Album ea, "
+ " Artista ar, Album al, Usuario us "
+ " where us.id_usuario = ? "
+ " and id.id_usuario_pf_fk = us.id_usuario "
+ " and id.id_edicao_album_fk = ea.id_edicao_album "
+ " and ea.id_tipo_midia_fk = tm.id_tipo_midia "
+ " and ea.id_album_fk = al.id_album "
+ " and al.id_artista_fk = ar.id_artista "
+ " limit 4 ;" ;
Object [] parametros = {idUsuario};
listaItemColecao = jdbcTemplate.query(sql, parametros, new ItemColecaoHomeRowMapper());
return listaItemColecao;
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public StoredProcedure getProcedureCadastroItemColecao() {
return procedureCadastroItemColecao;
}
public void setProcedureCadastroItemColecao(StoredProcedure procedureCadastroItemColecao) {
this.procedureCadastroItemColecao = procedureCadastroItemColecao;
}
}
|
Java
|
UTF-8
| 229 | 1.953125 | 2 |
[] |
no_license
|
package string;
import leetcode.string.WordPatternII;
import org.junit.Test;
public class WordPatternIITest {
@Test
public void test() {
(new WordPatternII()).wordPatternMatch("abba","dogcatcatdog");
}
}
|
Shell
|
UTF-8
| 471 | 3.59375 | 4 |
[
"Apache-2.0"
] |
permissive
|
#!/bin/bash
# Call from project root directory: ./release/windows.sh
set -e
version=$1;
if [ "$version" == "" ]; then
echo Gimme version number
exit 1
fi
OUT="abstreet_windows_$version"
source release/common.sh
common_release $OUT
cp release/play_abstreet.bat $OUT
mkdir $OUT/game
cross build --release --target x86_64-pc-windows-gnu --bin game
cp target/x86_64-pc-windows-gnu/release/game.exe $OUT/game
cp -Rv game/assets $OUT/game
zip -r $OUT $OUT
rm -rf $OUT
|
Java
|
UTF-8
| 216 | 1.851563 | 2 |
[] |
no_license
|
package lark.net.rpc.server.register;
import java.util.function.Supplier;
/**
* @author cuigh
*/
public interface Register {
void register(Supplier<Provider> supplier);
void remove(Provider provider);
}
|
SQL
|
UTF-8
| 417 | 3.25 | 3 |
[] |
no_license
|
-- sample view for Milestone 7
create view oscars.oscar_nominations as
select entity, count(*) as nomination_count
from `cs327e-sp2019.oscars.Academy_Award`
where category in ('ACTOR IN A LEADING ROLE', 'ACTOR IN A SUPPORTING ROLE', 'ACTRESS', 'ACTRESS IN A LEADING ROLE',
'ACTRESS IN A SUPPORTING ROLE', 'DIRECTING (Comedy Picture)',
'DIRECTING (Dramatic Picture)')
group by entity
order by nomination_count desc
|
C
|
UTF-8
| 612 | 2.609375 | 3 |
[] |
no_license
|
/**
* @file Ogrenci.hpp
* @course 2. Ogretim A
* @assignment 1.Odev
* @date 23.10.2018
* @author Fatih Enis Kaya fatih.kaya18@ogr.sakarya.edu.tr
*/
#include "Random.h"
#include <sys/time.h>
#include <stdio.h>
#include <time.h>
#include <math.h>
unsigned short lfsr = 0xACE1u;
unsigned bit;
unsigned rando()
{
bit = ((lfsr >> 0) ^ (lfsr >> 2) ^ (lfsr >> 3) ^ (lfsr >> 5) ) & 1;
return lfsr = (lfsr >> 1) | (bit << 15);
}
int SayiOlustur(){
int simdikiNanoZamaninKisaHali = (int)rando()%26;
//printf("milliseconds: %d\n", simdikiNanoZamaninKisaHali);
return simdikiNanoZamaninKisaHali;
}
|
Python
|
UTF-8
| 1,223 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
"""
Script for coarse-graining an EM map downloaded from EMD
"""
import cg
import numpy as np
from cg import em
from csb.bio.io import mrc
## change accordingly ...
code = 1290 ## EMD map that will be coarse-grained
n_coarse = None ## number of coarse-grained atoms (if None, K=100)
n_nearest = 10 ## nearest-neighbor cutoff for speeding up the sampler
n_gibbs = 3e3 ## number of Gibbs sampling steps
perc = 0.9 ## percentage of total density that will be represented by beads
## download map and extract voxels carrying the most significant mass
filename = em.fetch_emd(code)
reader = mrc.DensityMapReader(filename)
emmap = reader.read()
cutoff = em.find_cutoff(emmap, perc)
print 'Coarse graining EMD-{0} at a cutoff of {2:.3f} ({1:0.1f}% of total density)'.format(code, 100*perc, cutoff)
(coords,
weights) = em.map2cloud(emmap, cutoff)
n_coarse = 100 if n_coarse is None else n_coarse
coords = coords[weights.argsort()[::-1]]
weights = np.sort(weights)[::-1]
## setup and run Gibbs sampler
gibbs = cg.GibbsSampler(coords, n_coarse, n_nearest, run_kmeans=False, weights=weights)
samples = gibbs.run(n_gibbs)
## show results
cg.utils.plot_samples(samples)
|
C#
|
UTF-8
| 1,266 | 3.921875 | 4 |
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace stringExample
{
class Program
{
static void Main(string[] args)
{
//Replace : 문자열 치환
string sayIntro = "I am swan";
Console.WriteLine(sayIntro);
sayIntro = sayIntro.Replace("swan", "blackswan");
Console.WriteLine(sayIntro);//I am blackswan
//문자열 검색
string songLyrics = "happy birthday to you";
//Contains : 문자열포함여부
Console.WriteLine(songLyrics.Contains("birthday"));
Console.WriteLine(songLyrics.Contains("monday"));
//StartsWith : 문자열 시작을 기준으로 문자열포함여부
Console.WriteLine(songLyrics.StartsWith("happy"));
Console.WriteLine(songLyrics.StartsWith("sad"));
//EndsWith : 문자열 끝을 기준으로 문자열포함여부
Console.WriteLine(songLyrics.EndsWith("you"));
Console.WriteLine(songLyrics.EndsWith("me"));
//문자열 대소문자 변환
Console.WriteLine(songLyrics.ToUpper());
Console.WriteLine(songLyrics.ToLower());
}
}
}
|
Markdown
|
UTF-8
| 2,546 | 2.765625 | 3 |
[
"CC-BY-4.0",
"MIT"
] |
permissive
|
---
title: PwrTest Platform Idle Scenario
description: The PwrTest Platform Idle Scenario (/platidle) polls and attempts to log platform idle transition counts if they are supported by the computer.
ms.date: 04/20/2017
---
# PwrTest Platform Idle Scenario
The PwrTest Platform Idle Scenario (**/platidle**) polls and attempts to log platform idle transition counts if they are supported by the computer.
This scenario is useful for tracking platform idle state transitions that occur while the computer is in use. This scenario can also help diagnose if a system is entering deep platform idle states (if manually entered via the power button).
The **/platidle** scenario requires that the computer has support for the *Always on Always connected* (AoAc) power capability.
## <span id="Syntax"></span><span id="syntax"></span><span id="SYNTAX"></span>Syntax
```
pwrtest /platidle [/t:n] [/i:n] [/?]
```
<span id="_t_n"></span><span id="_T_N"></span>**/t:**<em>n</em>
Specifies the total time (in minutes) for the scenario to run (the default value for *n* is 30 minutes).
<span id="_i_n"></span><span id="_I_N"></span>**/i:**<em>n</em>
Specifies the polling interval (in seconds) for gathering platform idle statistics (the default value for *n* is 5 seconds).
**Examples**
```
pwrtest /platidle /t:60
```
```
pwrtest /platidle
```
### <span id="XML_log_file_output"></span><span id="xml_log_file_output"></span><span id="XML_LOG_FILE_OUTPUT"></span>XML log file output
```XML
<PwrTestLog>
<SystemInformation>
</SystemInformation>
<PlatIdle>
<PlatformIdleStats StateCount="X" Timestamp="XX/XX/XXXX:XX:XX:XX.XXX">
<State Index="X" SuccessCount="X" FailureCount="X" CancelCount="X"/>
</PlatformIdleStats>
</PlatIdle>
</PwrTestLog>
```
The following table describes the XML elements that appear in the log file.
<table>
<colgroup>
<col width="50%" />
<col width="50%" />
</colgroup>
<thead>
<tr class="header">
<th align="left">Element</th>
<th align="left">Description</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left"><strong><PlatIdle></strong></td>
<td align="left"><p>Contains all platform idle statistics. There is only one <strong><PlatIdle></strong> element in a PwrTest log file</p></td>
</tr>
<tr class="even">
<td align="left"><strong><PlatformIdleStats></strong></td>
<td align="left"><p>Platform idle statistics block.</p></td>
</tr>
</tbody>
</table>
## <span id="related_topics"></span>Related topics
[PwrTest Syntax](pwrtest-syntax.md)
|
C++
|
UTF-8
| 2,652 | 3.125 | 3 |
[] |
no_license
|
#ifndef SCHR_FIELD_HH
#define SCHR_FIELD_HH
#include <vector>
#include "global.h"
/*
an n dimensional scalar field
*/
struct Field1D
{
std::vector<field_data_t> field_data;
/*
the dimension of the scalar field is determined
implicitly by the size of the field_sizes vector
*/
std::vector<unsigned int> field_sizes;
Field1D (const std::vector<unsigned int> &sizes);
inline void set_data (const std::vector<unsigned int> &pos, field_data_t value)
{
long long unsigned int flat_pos = 0;
long unsigned int factor = 1;
for (unsigned int i = 0; i < field_sizes.size (); ++i)
{
flat_pos += factor * pos[i];
factor *= field_sizes[i];
}
field_data [flat_pos] = value;
}
inline field_data_t get_data (const std::vector<unsigned int> &pos)
{
long long unsigned int flat_pos = 0;
long unsigned int factor = 1;
for (unsigned int i = 0; i < field_sizes.size (); ++i)
{
flat_pos += factor * pos[i];
factor *= field_sizes[i];
}
return field_data [flat_pos];
}
inline void set_data_2D (unsigned int pos_1, unsigned int pos_2, field_data_t value)
{
std::vector<unsigned int> pos (2);
pos[0] = pos_1;
pos[1] = pos_2;
set_data (pos, value);
}
inline field_data_t get_data_2D (unsigned int pos_1, unsigned int pos_2)
{
std::vector<unsigned int> pos (2);
pos[0] = pos_1;
pos[1] = pos_2;
return get_data (pos);
}
};
/* an n-dimensional vectorfield with vectors from m-dimensional vectorspace */
struct Field
{
unsigned int vectorspace_dimension;
/*
n numbers denoting the size [elements] of the
field in each dimension. i.e. a three-dimensional field of
six-dimensional vectors will have three numbers
*/
std::vector<unsigned int> field_sizes;
/*
each component of the vector data gets its own Field1D
*/
std::vector<Field1D> field_data;
/* the dimension of the field is given implicitly by the sizes-vector */
Field (const std::vector<unsigned int> &sizes, unsigned int vectorspace_dim = 2);
inline field_data_t get_data (const std::vector<unsigned int> &pos, unsigned int component)
{
return field_data [component].get_data (pos);
}
inline void set_data (const std::vector<unsigned int> &pos, unsigned int component, field_data_t value)
{
field_data [component].set_data (pos, value);
}
inline field_data_t get_data_2D (unsigned int pos_1, unsigned int pos_2, unsigned int component)
{
return field_data [component].get_data_2D (pos_1, pos_2);
}
inline void set_data_2D (unsigned int pos_1, unsigned int pos_2, unsigned int component, field_data_t value)
{
field_data [component].set_data_2D (pos_1, pos_2, value);
}
};
#endif
|
Swift
|
UTF-8
| 597 | 3.4375 | 3 |
[
"MIT"
] |
permissive
|
//
// Problem5.swift
// ProjectEuler
//
// Created by Tiago Henriques on 08/05/16.
// Copyright © 2016 Tiago Henriques. All rights reserved.
//
import Foundation
class Problem5: Solvable {
func solve() -> Int {
var value = 20
while value.divisibleByAllNumbersInRange(1...20) == false {
value += 20
}
return value
}
}
extension Int {
func divisibleByAllNumbersInRange(range: Range<Int>) -> Bool {
for divisor in range {
if self % divisor != 0 {
return false
}
}
return true
}
}
|
PHP
|
UTF-8
| 3,533 | 3.078125 | 3 |
[
"MIT"
] |
permissive
|
<?php namespace Rollbar;
final class Utilities
{
// In order to support < 5.6 we had to use __callStatic to define
// coalesce, because the splat operator was introduced in 5.6
public static function __callStatic($name, $args)
{
if ($name == 'coalesce') {
return self::coalesceArray($args);
}
return null;
}
public static function coalesceArray(array $values)
{
foreach ($values as $key => $val) {
if ($val) {
return $val;
}
}
return null;
}
// Modified from: http://stackoverflow.com/a/1176023/456188
public static function pascalToCamel($input)
{
$s1 = preg_replace('/([^_])([A-Z][a-z]+)/', '$1_$2', $input);
return strtolower(preg_replace('/([a-z0-9])([A-Z])/', '$1_$2', $s1));
}
public static function validateString(
$input,
$name = "?",
$len = null,
$allowNull = true
) {
if (is_null($input)) {
if (!$allowNull) {
throw new \InvalidArgumentException("\$$name must not be null");
}
return;
}
if (!is_string($input)) {
throw new \InvalidArgumentException("\$$name must be a string");
}
if (!is_null($len) && strlen($input) != $len) {
throw new \InvalidArgumentException("\$$name must be $len characters long, was '$input'");
}
}
public static function validateBoolean(
$input,
$name = "?",
$allowNull = true
) {
if (is_null($input)) {
if (!$allowNull) {
throw new \InvalidArgumentException("\$$name must not be null");
}
return;
}
if (!is_bool($input)) {
throw new \InvalidArgumentException("\$$name must be a boolean");
}
}
public static function validateInteger(
$input,
$name = "?",
$minValue = null,
$maxValue = null,
$allowNull = true
) {
if (is_null($input)) {
if (!$allowNull) {
throw new \InvalidArgumentException("\$$name must not be null");
}
return;
}
if (!is_integer($input)) {
throw new \InvalidArgumentException("\$$name must be an integer");
}
if (!is_null($minValue) && $input < $minValue) {
throw new \InvalidArgumentException("\$$name must be >= $minValue");
}
if (!is_null($maxValue) && $input > $maxValue) {
throw new \InvalidArgumentException("\$$name must be <= $maxValue");
}
}
public static function serializeForRollbar(
$obj,
array $overrideNames = null,
array $customKeys = null
) {
$returnVal = array();
$overrideNames = $overrideNames == null ? array() : $overrideNames;
$customKeys = $customKeys == null ? array() : $customKeys;
foreach ($obj as $key => $val) {
if ($val instanceof \JsonSerializable) {
$val = $val->jsonSerialize();
}
$newKey = array_key_exists($key, $overrideNames)
? $overrideNames[$key]
: Utilities::pascalToCamel($key);
if (in_array($key, $customKeys)) {
$returnVal[$key] = $val;
} elseif (!is_null($val)) {
$returnVal[$newKey] = $val;
}
}
return $returnVal;
}
}
|
Python
|
UTF-8
| 4,928 | 3.359375 | 3 |
[] |
no_license
|
class SLList(object):
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def addBack(self, val):
if not self.head:
self.head = SLNode(val)
self.tail = self.head
return self
run = self.head
while run.next != None:
run = run.next
run.next = SLNode(val)
self.tail = run.next
self.length += 1
return self
def addFront(self, val):
if not self.tail:
self.head = SLNode(val)
self.tail = self.head
return self
temp = self.head
self.head = SLNode(val)
self.head.next = temp
self.length += 1
return self
def pushListToBack(self, arr):
idx = 0
limit = len(arr)
if not self.head:
self.head = SLNode(arr[idx])
idx += 1
run = self.head
while run.next != None:
run = run.next
while idx != limit:
run.next = SLNode(arr[idx])
idx += 1
run = run.next
self.length += limit
self.tail = run
return self
def returnAsList(self):
ret = []
run = self.head
while run != None:
ret.append(run.val)
run = run.next
return ret
def insertBefore(self, targetVal, newVal, goAnyway=False):
# put True as last argument to insert at end if targetVal not found
if not self.head:
if not goAnyway:
print "Cannot insert before target, as SLL is empty."
return self
else:
self.head = SLNode(newVal)
self.tail = self.head
self.length += 1
return self
run = self.head
while run.next != None and run.next.val != targetVal:
run = run.next
if run.next != None or goAnyway:
temp = run.next
run.next = SLNode(newVal)
run.next.next = temp
self.length += 1
if temp == None:
self.tail = run.next
else:
print "Cannot insert before target, as it was not found in SLL."
return self
def insertAfter(self, targetVal, newVal, goAnyway=False):
# put True as last argument to insert at end if targetVal not found
if not self.head:
if not goAnyway:
print "Cannot insert after target, as SLL is empty."
return self
else:
self.head = SLNode(newVal)
self.tail = self.head
self.length += 1
return self
run = self.head
while run.next != None and run.val != targetVal:
run = run.next
if run.val == targetVal or goAnyway:
temp = run.next
run.next = SLNode(newVal)
run.next.next = temp
self.length += 1
if temp == None:
self.tail = run.next
else:
print "Cannot insert after target, as it was not found in SLL."
return self
def removeOneNode(self, targetVal):
if not self.head:
print "SLL is empty."
return self
run = self.head
while run.next != None:
if run.next.val == targetVal:
if run.next.next == None:
self.tail = run
run.next = run.next.next
self.length -= 1
return self
run = run.next
print "Target value not found."
return self
def removeAllNodes(self, targetVal):
if not self.head:
print "SLL is empty."
return self
run = self.head
while run != None and run.next != None:
if run.next.val == targetVal:
if run.next.next == None:
self.tail = run
run.next = run.next.next
self.length -= 1
run = run.next
return self
def returnInReverse(self):
transformed = self.returnAsList()
ret = []
for idx in range(self.length-1, -1, -1):
ret.append(transformed[idx])
return ret
def reverse(self):
transformed = self.returnAsList()
run = self.head
while run !== None:
run.val = transformed.pop()
run = run.next
return self
class SLNode(object):
def __init__(self, val):
self.val = val
self.next = None
test = SLList()
test.pushListToBack([1,2,4,5])
print test.returnAsList()
test.pushListToBack([6,7,8])
print test.returnAsList()
test.addFront(12)
test.addBack(3)
print test.returnAsList()
test.removeOneNode(3)
print test.returnAsList()
print test.returnInReverse()
print test.head.val
print test.tail.val
print test.length
|
Java
|
UTF-8
| 1,196 | 2.921875 | 3 |
[] |
no_license
|
package Comandos;
import java.util.Scanner;
import memoria.MemoriaVariaveis;
import memoria.MemoriaComando;
/**
*
* @author aluno
*/
public class ReadInt {
MemoriaVariaveis variavel = new MemoriaVariaveis();
MemoriaComando comando = new MemoriaComando();
public ReadInt(){
}
public MemoriaVariaveis getVariavel() {
return variavel;
}
public void setVariaveis(MemoriaVariaveis variavel) {
this.variavel = variavel;
}
public MemoriaComando getComando() {
return comando;
}
public void setComando(MemoriaComando comando) {
this.comando = comando;
}
public void executaReadInt(MemoriaVariaveis variavel) {
int valorInteiro;
Scanner ler = new Scanner(System.in);
int i = comando.getPosicao("readint");
comando.tiraPorPosisao(i);
try{
valorInteiro = ler.nextInt();
variavel.setListaVariaveis(variavel,valorInteiro);
} catch(NumberFormatException ex){
System.out.println("Entrada inválida, o valor digitado não é um número!");
}
}
}
|
Java
|
UTF-8
| 223 | 1.671875 | 2 |
[] |
no_license
|
package com.dev.ieeensut.interfaces;
import android.view.View;
import com.dev.ieeensut.models.Feed;
/**
*
*/
public interface OnHomeSliderInteractionListener {
void onHomeSliderInteraction(View view, Feed feed);
}
|
Markdown
|
UTF-8
| 8,580 | 3.421875 | 3 |
[
"Apache-2.0"
] |
permissive
|
# Echart属性说明
## title
echart标题设置项。
|属性|显示名|类型|默认值|说明|
|------|----|-----|--------|----:|
|show|是否显示标题组件|boolean|true|是否显示标题组件|
|zlevel|所有图形的 zlevel 值|number|无|所有图形的 zlevel 值|
|z|组件的所有图形的z值|number|6|二级层叠控制,同一个canvas(相同zlevel)上z越高约靠顶层。|
|text|主标题文本|string|无|主标题文本|
|link|主标题文本超链接|string|无|主标题文本超链接|
|target|指定窗口打开主标题超链接|string|blank|指定窗口打开主标题超链接|
|subtext|副标题文本|string|无|副标题文本||sublink|副标题文本超链接|string|无|副标题文本超链接|
|subtarget|指定窗口打开主标题超链接|string|blank|指定窗口打开主标题超链接|
|x|水平安放位置|string|left|默认为左侧,可选为:'center' 、 'left' 、 'right' 、 {number}(x坐标,单位px)|
|y|垂直安放位置|string|top|默认为全图顶端,可选为:'top' 、 'bottom' 、 'center' 、 {number}(y坐标,单位px)||textAlign|水平对齐方式|string|left|默认根据x设置自动调整,可选为: 'left' 、 'right' 、 'center'|
|backgroundColor|标题背景色|string|transparent|默认透明。|
|borderColor|标题的边框颜色|string|#ccc|支持的颜色格式同 backgroundColor。|
|borderWidth|标题的边框线宽|number|2|标题的边框线宽|
|padding|标题内边距|string|无|单位px,默认各方向内边距为5,接受数组分别设定上右下左边距。|
|itemGap|主副标题之间的间距|string|无|主副标题之间的间距|
## axis
轴配置属性,这里有横轴和纵轴。
|属性|显示名|类型|默认值|说明|
|------|----|-----|--------|----:|
|zlevel|所有图形的 zlevel 值|number|无|所有图形的 zlevel 值|
|z|组件的所有图形的z值|number|6|二级层叠控制,同一个canvas(相同zlevel)上z越高约靠顶层。|
|show|显示策略|boolean|true|显示策略|
|type|坐标轴类型|string|无|横轴默认为类目型'category',纵轴默认为数值型'value'|
|position|坐标轴类型|string|无|横轴默认为类目型'bottom',纵轴默认为数值型'left',可选为:'bottom' 、 'top' 、 'left' 、 'right'|
|name|坐标轴名称,默认为空|string|无|坐标轴名称,默认为空|
|nameLocation|坐标轴名称位置|string|start|默认为'end',可选为:'start' 、 'end'||boundaryGap|类目起始和结束两端空白策略|boolean|true|类目起始和结束两端空白策略|
|min|最小值|number|无|最小值|
|max|最大值|number|无|最大值|
|scale|脱离0值比例,放大聚焦到最终_min,_max区间|boolean|无|脱离0值比例,放大聚焦到最终_min,_max区间||data|轴数据|array|无|格式为['1','2']|
## legend
图例配置属性。
|属性|显示名|类型|默认值|说明|
|------|----|-----|--------|----:|
|show|是否显示标题组件|boolean|true|是否显示标题组件|
|zlevel|所有图形的 zlevel 值|number|无|所有图形的 zlevel 值|
|z|组件的所有图形的z值|number|6|二级层叠控制,同一个canvas(相同zlevel)上z越高约靠顶层。|
|orient|布局方式|string|无|布局方式|
|x|水平安放位置|string|left|默认为左侧,可选为:'center' 、 'left' 、 'right' 、 {number}(x坐标,单位px)|
|y|垂直安放位置|string|top|默认为全图顶端,可选为:'top' 、 'bottom' 、 'center' 、 {number}(y坐标,单位px)|
|backgroundColor|标题背景色|string|transparent|默认透明。|
|borderColor|标题的边框颜色|string|#ccc|支持的颜色格式同 backgroundColor。|
|borderWidth|标题的边框线宽|number|2|标题的边框线宽|
|padding|标题内边距|string|无|单位px,默认各方向内边距为5,接受数组分别设定上右下左边距。|
|itemGap|主副标题之间的间距|string|无|主副标题之间的间距|
|itemWidth|图例图形宽度|number|20|图例图形宽度|
|itemHeight|图例图形高度|number|14|图例图形高度|
## series
曲线设置。
|属性|显示名|类型|默认值|说明|
|------|----|-----|--------|----:|
|zlevel|所有图形的 zlevel 值|number|无|所有图形的 zlevel 值|
|z|组件的所有图形的z值|number|6|二级层叠控制,同一个canvas(相同zlevel)上z越高约靠顶层。|
|type|图表类型|string|line|可选为: 'line'(折线图) 、 'bar'(柱状图) 、 'scatter'(散点图) 、 'k'(K线图) 、 'pie'(饼图) 、 'radar'(雷达图) 、 'chord'(和弦图) 、 'force'(力导向布局图) 、 'map'(地图)|
|name|系列名称|string|无|如启用legend,该值将被legend.data索引相关|
|clickable|数据图形是否可点击,默认开启,如果没有click事件响应可以关闭|boolean|true|数据图形是否可点击,默认开启,如果没有click事件响应可以关闭|
|selectedMode|选中模式|string|single|默认关闭,可选single,multiple|
|label|label|object|无||
|color|颜色组|array|无|颜色组|
## toolbox
工具栏配置属性
|属性|显示名|类型|默认值|说明|
|------|----|-----|--------|----:|
|show|是否显示工具箱|boolean|true|是否显示工具箱|
|showTitle|是否显示工具箱文字提示|boolean|true|是否显示工具箱文字提示|
|zlevel|一级层叠控制|number|无|一级层叠控制|
|z|组件的所有图形的z值|number|6|组件的所有图形的z值|
|orient|布局方式|string|无|布局方式|
|x|水平安放位置|string|left|默认为全图居中,可选为:'center' 、 'left' 、 'right' 、 {number}(x坐标,单位px)|
|y|垂直安放位置|string|top|默认为全图顶端,可选为:'top' 、 'bottom' 、 'center' 、 {number}(y坐标,单位px)|
|backgroundColor|标题背景色|string|transparent|默认透明。|
|borderColor|标题的边框颜色|string|#ccc|支持的颜色格式同 backgroundColor。|
|borderWidth|标题的边框线宽|number|2|标题的边框线宽|
|padding|标题内边距|string|无|单位px,默认各方向内边距为5,接受数组分别设定上右下左边距。|
|itemGap|主副标题之间的间距|string|无|主副标题之间的间距|
|itemSize|工具箱icon大小,单位(px)|number|16|工具箱icon大小,单位(px)|
|color|工具箱icon颜色序列,循环使用,同时支持在具体feature内指定color|array|无|工具箱icon颜色序列,循环使用,同时支持在具体feature内指定color|
|disableColor|禁用颜色定义|string|#ddd|禁用颜色定义|
|effectiveColor|生效颜色定义|string|red|生效颜色定义|
## tooltip
鼠标以上的显示设置属性。
|属性|显示名|类型|默认值|说明|
|------|----|-----|--------|----:|
|show|是否显示|boolean|true|是否显示|
|zlevel|所有图形的 zlevel 值|number|无|所有图形的 zlevel 值|
|z|组件的所有图形的z值|number|6|二级层叠控制,同一个canvas(相同zlevel)上z越高约靠顶层。|
|showContent|tooltip主体内容显示策略|boolean|true|tooltip主体内容显示策略|
|trigger|触发类型,默认数据触发,见下图,可选为:'item' | 'axis'|string|item|触发类型,默认数据触发,见下图,可选为:'item' 、 'axis'|
|showDelay|显示延迟,添加显示延迟可以避免频繁切换,特别是在详情内容需要异步获取的场景,单位ms|number|20|显示延迟,添加显示延迟可以避免频繁切换,特别是在详情内容需要异步获取的场景,单位ms|
|hideDelay|隐藏延迟,单位ms|number|100|隐藏延迟,单位ms|
|transitionDuration|动画变换时长,单位s|number|0.4|如果你希望tooltip的跟随实时响应,showDelay设置为0是关键,同时transitionDuration设0也会有交互体验上的差别|
|enterable|鼠标是否可进入详情气泡中,默认为false,如需详情内交互,如添加链接,按钮,可设置为true。|boolean|无|鼠标是否可进入详情气泡中,默认为false,如需详情内交互,如添加链接,按钮,可设置为true。|
|backgroundColor|标题背景色|string|transparent|默认透明|
|borderColor|标题的边框颜色|string|#ccc|支持的颜色格式同 backgroundColor|
|borderWidth|标题的边框线宽|number|2|标题的边框线宽|
|borderRadius|提示边框圆角,单位px,默认为4|number|4|提示边框圆角,单位px,默认为4|
|padding|标题内边距|string|无|单位px,默认各方向内边距为5,接受数组分别设定上右下左边距。|
|
Java
|
UTF-8
| 462 | 2.25 | 2 |
[
"MIT"
] |
permissive
|
public void test20() throws Throwable {
Player player0 = new Player((byte)0, "", "", (-1), (byte)0);
int int0 = player0.gangStrength();
assertEquals(0.0F, player0.getY(), 0.01F);
assertEquals(0L, player0.getTimeOfDeath());
assertFalse(player0.isDead());
assertEquals(10.0F, player0.getX(), 0.01F);
assertTrue(player0.isConnected());
assertEquals(0, int0);
assertEquals((-1), player0.getPictureId());
}
|
Python
|
UTF-8
| 1,469 | 3.53125 | 4 |
[] |
no_license
|
# Count of number of given string in 2D character array
# Given a 2-Dimensional character array and a string, we need to find the given string in 2-dimensional character array such that individual characters can be present left to right, right to left, top to down or down to top.
# Input : a ={
# {D,D,D,G,D,D},
# {B,B,D,E,B,S},
# {B,S,K,E,B,K},
# {D,D,D,D,D,E},
# {D,D,D,D,D,E},
# {D,D,D,D,D,G}
# }
# str= "GEEKS"
# Output :2
#
# Input : a = {
# {B,B,M,B,B,B},
# {C,B,A,B,B,B},
# {I,B,G,B,B,B},
# {G,B,I,B,B,B},
# {A,B,C,B,B,B},
# {M,C,I,G,A,M}
# }
# str= "MAGIC"
#
# Output :3
def countword2D(str1,dict1):
count = 0
l = []
for y in range(len(inputt)):
l.append(''.join(list(map(lambda x:x[y],inputt))))
dict1.extend(l)
print(dict1)
for x in dict1:
if str1 in x or str1 in x[::-1]:
print(x)
count += 1
return count
# a=[
# ['D','D','D','G','D','D'],
# ['B','B','D','E','B','S'],
# ['B','S','K','E','B','K'],
# ['D','D','D','D','D','E'],
# ['D','D','D','D','D','E'],
# ['D','D','D','D','D','G']
# ]
needle = "MAGIC"
inputt = ["BBABBM","CBMBBA","IBABBG",
"GOZBBI","ABBBBC","MCIGAM"]
for value in [[needle,inputt]]:
print(f'Input is {value}')
print(countword2D(*value))
|
JavaScript
|
UTF-8
| 5,219 | 2.65625 | 3 |
[] |
no_license
|
const assert = require('assert');
const request = require('request-promise');
const express = require('express');
const bodyParser = require('body-parser');
const config = require('../config');
const restUrl = `http://localhost:${config.REST_PORT}`;
const pubsubUrl = `http://localhost:${config.PUBSUB_PORT}`;
function publishMessage(channel, payload, metadata) {
return request({
method: 'POST',
uri: `${pubsubUrl}/publish`,
json: true,
body: {channel, payload, metadata}
})
}
function getAppointments(specialty, date) {
return request({
uri: `${restUrl}/appointments`,
qs: {specialty, date, minScore: 0},
json: true
})
}
function wait(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms);
})
}
const supermanProvider = {
name: "Clark Kent",
score: 1000,
specialties: [
"Supertreatment"
],
availableDates: [
{
from: 814172400000,
to: 814172400000
}
]
};
function addSuperman() {
const specialty = supermanProvider.specialties[0];
const date = supermanProvider.availableDates[0].to;
return publishMessage(`addProvider`, supermanProvider)
.then(() => wait(100))
.then(() => getAppointments(specialty, date))
.then(result => assert.deepStrictEqual(result, [supermanProvider.name]));
}
function removeSuperman() {
const specialty = supermanProvider.specialties[0];
const date = supermanProvider.availableDates[0].to;
return publishMessage(`deleteProvider`, {name: supermanProvider.name})
.then(() => wait(100))
.then(() => getAppointments(specialty, date))
.then(result => assert.deepStrictEqual(result, []));
}
describe(`# Test part B of the coding interview`, () => {
describe(`# Test POST /appointments`, () => {
let handler;
let server;
function subscribeToNewAppointments() {
const app = express();
const port = config.SUBSCRIBER_PORT;
app.use(bodyParser.json());
app.route('/newAppointment').post((request, response) => handler ? handler(request.body) : response.status(200).send());
server = app.listen(port);
return request({
method: 'POST',
uri: `${pubsubUrl}/subscribe`,
body: {channel: 'newAppointments', address: `http://localhost:${port}/newAppointment`},
json: true
})
}
function shutDownSubscriber() {
server.close();
}
before(subscribeToNewAppointments);
beforeEach(() => handler = null);
after(shutDownSubscriber);
function postAppointment(name, date) {
return request({
uri: `${restUrl}/appointments`,
method: 'POST',
body: {name, date},
json: true,
})
}
it(`# should successfully update an appointment and publish the appointment to the pubsub`, done => {
handler = message => {
if (message.payload.name === "Roland Deschain" && message.payload.date === 1571569200000) done();
else done(new Error(`Unexpected message received from pubsub: ${JSON.stringify(message)}`));
};
postAppointment("Roland Deschain", 1571569200000)
.catch(done);
}
)
});
describe(`# Test addProvider`, () => {
afterEach(removeSuperman);
it(`# Should add a provider`, addSuperman);
it(`# Should update a provider`, () => {
const differentSuperman = {
name: "Clark Kent",
score: 1000,
specialties: [
"Measles"
],
availableDates: [
{
from: 2524633200000,
to: 2524640400000
}
]
};
return addSuperman()
.then(() => publishMessage(`addProvider`, differentSuperman))
.then(() => wait(100))
.then(() => getAppointments(supermanProvider.specialties[0], supermanProvider.availableDates[0].to))
.then(result => assert.deepStrictEqual(result, []))
.then(() => getAppointments(differentSuperman.specialties[0], differentSuperman.availableDates[0].to))
.then(result => assert.deepStrictEqual(result, [differentSuperman.name]));
})
});
describe(`# Test deleteProvider`, () => {
// Make sure we have a provider to delete
before(addSuperman);
// Make sure the provider is deleted no matter what happened in the test
after(removeSuperman);
it(`# Should delete a provider`, () => {
return publishMessage(`deleteProvider`, {name: supermanProvider.name})
.then(() => wait(100))
.then(() => getAppointments(supermanProvider.specialties[0], supermanProvider.availableDates[0].to))
.then(result => assert.deepStrictEqual(result, []));
});
});
});
|
JavaScript
|
UTF-8
| 1,087 | 2.53125 | 3 |
[] |
no_license
|
const ONE_MINUTE = 60 * 1000;
const FIVE_MINUTES = 5 * ONE_MINUTE;
export function getTimeDisplayFeedbackByDiff(diff) {
if (typeof diff !== 'number') {
console.error(`Wrong diff type received in timeDisplayFeedbackRules. Expected "number", got "${typeof diff}".`);
return {
momentMessage: '',
durationMessage: '',
theme: 'secondary',
};
}
if (diff < FIVE_MINUTES * -1) {
return {
momentMessage: 'Very late by',
durationMessage: 'Wasted',
theme: 'danger',
};
}
if (diff < ONE_MINUTE * -1) {
return {
momentMessage: 'Late by',
durationMessage: 'Wasted',
theme: 'warning',
};
}
if (diff < 0) {
return {
momentMessage: 'A little late by',
durationMessage: 'Wasted',
theme: 'warning',
};
}
if (diff < ONE_MINUTE) {
return {
momentMessage: 'On target! Left just',
durationMessage: 'On target! Left just',
theme: 'success',
};
}
return {
momentMessage: 'Advanced by',
durationMessage: 'Saved',
theme: 'success',
};
}
|
C#
|
UTF-8
| 845 | 2.6875 | 3 |
[] |
no_license
|
using DiaryOfSportsNutrition_Andrianova.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DiaryOfSportsNutrition_Andrianova.Concrete
{
public class PlateFoodRecordRepository : IPlateFoodRecordRepository
{
private readonly IEFContext _context;
public PlateFoodRecordRepository(IEFContext context)
{
_context = context;
}
public PlateFoodRecord Add(PlateFoodRecord platefoodrecord)
{
_context.Set<PlateFoodRecord>().Add(platefoodrecord);
_context.SaveChanges();
return platefoodrecord;
}
public IQueryable<PlateFoodRecord> PlateFoodRecords()
{
return _context.Set<PlateFoodRecord>().AsQueryable();
}
}
}
|
C++
|
UTF-8
| 1,097 | 2.75 | 3 |
[] |
no_license
|
#include<iostream>
using namespace std;
int main()
{
int ch, n, temp, j, i, k;
n = 6;
int x[] ={7, 19, 4, 8, 20, 1};
ch = true;
cout << "Latihan 3" << endl;
for (int i=0; i<n; i++)
{
cout << x[i] << ",";
}
cout << "\n\nInsertion Sort : ";
for (i=1; i<=n-1; i++)
{
temp = x[i];
j = i-1;
while((temp<x[j])&&(j>=0))
{
x[j+1] = x[j];
j=j-1;
}
x[j+1] = temp;
}
cout << endl;
for (i=0; i<n; i++)
{
cout << x[i] << ",";
}
cout << "\n\nSelection Sort :";
for(i=0; i<n; i++)
{
k = i;
for(j=i+1; j<n; j++)
{
if(x[k]>x[j])
{
k=j;
}
}
temp = x[k];
x[k]=x[i];
x[i]=temp;
}
cout << endl;
for(i=0; i<n; i++)
{
cout << x[i] << ",";
}
cout << "\n\nBubble Sort : ";
for (i=0; i<n-2 &&ch; i++)
{
ch=false;
for(j=n-1; j>i; j--)
{
if(x[j]<x[j-1])
{
temp = x[j];
x[j] = x[j-1];
x[j-1] = temp;
ch = true;
}
}
}
cout << endl;
for (i=0; i<n; i++)
{
cout << x[i] << ",";
}
}
|
Python
|
UTF-8
| 2,818 | 3.203125 | 3 |
[] |
no_license
|
def gcite(doi=None, opage=False):
"""
Get citation (gcite) information from the web using an 'objects' doi number (digital object identifier).
cite, bibf = gcite(doi)
or
cite, bibf = gcite(doi, opage)
Inputs:
doi number as a string. The doi number can be entered as a url ('https://doi.org/10.1109/JOE.2002.808212') or as a number ('10.1109/JOE.2002.808212').
The function checks for the mssing host address and appends it to the doi number
opage is an optional boolean argument to open the project archive / webpage
Outputs:
cite APA-formatted citation
bibf bibtex-formatted citation
Examples
cite,_ = gcite('https://doi.org/10.1109/JOE.2002.808212')
print(cite) returns:
Johnson, M. P., & Tyack, P. L. (2003). A digital acoustic recording tag for measuring the response of wild marine mammals to sound. IEEE Journal of Oceanic Engineering, 28(1), 3–12. doi:10.1109/joe.2002.808212
cite, bibf = gcite('10.1109/JOE.2002.808212')
print(cite) returns:
Johnson, M. P., & Tyack, P. L. (2003). A digital acoustic recording tag for measuring the response of wild marine mammals to sound. IEEE Journal of Oceanic Engineering, 28(1), 3–12. doi:10.1109/joe.2002.808212
print(bibf) returns:
@article{Johnson_2003,
doi = {10.1109/joe.2002.808212},
url = {https://doi.org/10.1109%2Fjoe.2002.808212},
year = 2003,
month = {jan},
publisher = {Institute of Electrical and Electronics Engineers ({IEEE})},
volume = {28},
number = {1},
pages = {3--12},
author = {M.P. Johnson and P.L. Tyack},
title = {A digital acoustic recording tag for measuring the response of wild marine mammals to sound},
journal = {{IEEE} Journal of Oceanic Engineering}
}
Valid: Python
rjs30@st-andrews.ac.uk
Python implementation dmwisniewska@gmail.com
last modified: 23 July 2021
"""
import subprocess
cite, bibf = ([] for i in range(2))
if not doi or not isinstance(doi, str):
print(help(gcite))
return (cite, bibf)
if not opage:
opage = 0
# Check for missing host address
if doi.find('https://doi.org/')<0:
doi = 'https://doi.org/' + doi
# Get formatted citation (APA style)
command = 'curl -LH "Accept: text/x-bibliography; style=apa" ' + doi
res = subprocess.check_output(command)
cite = res.decode("utf-8")
# Get bibtex-formatted citation info
command = 'curl -LH "Accept: application/x-bibtex" ' + doi
res = subprocess.check_output(command)
bibf = res.decode("utf-8")
# Open webpage
if opage:
import webbrowser
webbrowser.open_new_tab(doi)
return (cite, bibf)
|
C++
|
UTF-8
| 627 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
#pragma once
#include <vector>
#include <queue>
#include <string>
#include <climits>
#include <algorithm>
#include <cmath>
#include <unordered_map>
#include <stack>
using namespace std;
class Solution {
public:
bool repeatedSubstringPattern(string str) {
int n = str.size();
for (int i = n / 2; i >= 1; --i) {
if (n % i == 0) {
int c = n / i;
string t = "";
for (int j = 0; j < c; ++j) {
t += str.substr(0, i);
}
if (t == str) return true;
}
}
return false;
}
};
|
JavaScript
|
UTF-8
| 726 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
fs = require('fs');
var configLoader = function(configFile) {
try {
fs.accessSync(configFile, fs.R_OK, function(err) {
console.log('Cannot read configuration file' + configFile);
process.exit(1);
});
} catch (err) {
console.log('Configuration file ' + configFile + ' not found.');
console.log(err);
throw new Error('Could not find configuration file ' + configFile);
}
var data = fs.readFileSync(configFile);
var config = null;
try {
config = JSON.parse(data);
} catch (err) {
console.log('Failed to parse configuration file.');
console.log(err);
throw new Error('Could not parse configuration file.');
}
return config;
};
module.exports = configLoader;
|
JavaScript
|
UTF-8
| 103 | 2.53125 | 3 |
[] |
no_license
|
function noisy(f) {
return function(arg) {
var val = f(arg);
return val;
};
}
noisy(Boolean)(0);
|
Go
|
UTF-8
| 806 | 3.03125 | 3 |
[
"MIT"
] |
permissive
|
package gitreceive
import (
"testing"
)
func TestReadLine(t *testing.T) {
//readLine() expects a line with two spaces.
good := "foo bar car"
foo, bar, car, err := readLine(good)
if err != nil {
t.Errorf("Expected err to be nil, got '%v'", err)
}
if foo != "foo" {
t.Errorf("Expected 'foo', got '%s'", foo)
}
if bar != "bar" {
t.Errorf("Expected 'bar', got '%s'", bar)
}
if car != "car" {
t.Errorf("Expected 'car', got '%s'", car)
}
bad := "foo bar"
if _, _, _, err = readLine(bad); err == nil {
t.Error("Expected err to be not nil, got nil")
}
}
func TestRun(t *testing.T) {
// NOTE(bacongobbler): not much we can test at this time other than it fails based on bad setup
if err := Run(nil, nil, nil, nil); err == nil {
t.Errorf("expected error to be non-nil, got nil")
}
}
|
Python
|
UTF-8
| 496 | 3.46875 | 3 |
[
"MIT"
] |
permissive
|
lista1 = []
while True:
cont = ''
lista1.append(int(input('Digite um número: ')))
cont = str(input('Deseja continuar? [S/N] ')).strip().upper()
while cont not in 'SSIMNNÃONAO':
cont = str(input('Deseja continuar? [S/N] ')).strip().upper()
if cont in 'NNÃONAO':
break
listapar = []
listaimpar = []
for n in lista1:
if n % 2 == 0:
listapar.append(n)
elif n % 2 != 0:
listaimpar.append(n)
print(lista1)
print(listapar)
print(listaimpar)
|
C++
|
UTF-8
| 1,386 | 3.21875 | 3 |
[] |
no_license
|
#include "leetcode_solutions.h"
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if(preorder.empty() || inorder.empty()) return nullptr;
return build(preorder, inorder, 0, preorder.size() - 1, 0, inorder.size() - 1);
}
TreeNode * build(vector<int>& preorder, vector<int>& inorder, int ps, int pe, int is, int ie){
if (ps == pe) {
TreeNode * root = new TreeNode(preorder[ps]);
return root;
}
// find preorder[ps] in inorder
int rootInIdx;
for (int i = is; i <= ie; ++i){
if(inorder[i] == preorder[ps]){
rootInIdx = i;
break;
}
}
TreeNode * root = new TreeNode(preorder[ps]);
TreeNode *left(nullptr), *right(nullptr);
if (rootInIdx != is){ // left tree exist
left = build(preorder, inorder, ps + 1, ps + (rootInIdx - is), is, rootInIdx - 1);
}
if (rootInIdx != ie){ // right tree exist
right = build(preorder, inorder, ps + (rootInIdx - is) + 1, pe, rootInIdx + 1, ie);
}
root -> left = left;
root -> right = right;
return root;
}
};
int main(){
vector<int> preorder = {1,2};
vector<int> inorder = {2,1};
Solution s;
cout << s.buildTree(preorder, inorder) << endl;
}
|
Shell
|
UTF-8
| 5,818 | 3.25 | 3 |
[] |
no_license
|
#!/bin/bash
###############################################################################
## Codes for the paper:
## ..............
##
## Authors : GUERIN Pierre-Edouard, MATHON Laetitia
## Montpellier 2019-2020
##
###############################################################################
## Usage:
## bash obitools_reference/total_obitools.sh
##
## Description:
## ..............
##
##
##
###############################################################################
## load config global variables
source benchmark_real_dataset/98_infos/config.sh
## Obitools
illuminapairedend=${SINGULARITY_EXEC_CMD}" "${OBITOOLS_SIMG}" illuminapairedend"
obigrep=${SINGULARITY_EXEC_CMD}" "${OBITOOLS_SIMG}" obigrep"
ngsfilter=${SINGULARITY_EXEC_CMD}" "${OBITOOLS_SIMG}" ngsfilter"
obisplit=${SINGULARITY_EXEC_CMD}" "${OBITOOLS_SIMG}" obisplit"
obiuniq=${SINGULARITY_EXEC_CMD}" "${OBITOOLS_SIMG}" obiuniq"
obiannotate=${SINGULARITY_EXEC_CMD}" "${OBITOOLS_SIMG}" obiannotate"
obiclean=${SINGULARITY_EXEC_CMD}" "${OBITOOLS_SIMG}" obiclean"
ecotag=${SINGULARITY_EXEC_CMD}" "${OBITOOLS_SIMG}" ecotag"
obisort=${SINGULARITY_EXEC_CMD}" "${OBITOOLS_SIMG}" obisort"
obitab=${SINGULARITY_EXEC_CMD}" "${OBITOOLS_SIMG}" obitab"
## EDNAtools
vsearch=${SINGULARITY_EXEC_CMD}" "${EDNATOOLS_SIMG}" vsearch"
container_python2=${SINGULARITY_EXEC_CMD}" "${EDNATOOLS_SIMG}" python2"
## Prefix for all generated files
pref="Carry"
## Prefix of the final table, including the step and the program tested (ie: merging_obitools)
step="filter_vsearch"
## Path to the directory containing forward and reverse reads
R1_fastq="${DATA_PATH}"/"$pref"/"$pref"_R1.fastq.gz
R2_fastq="${DATA_PATH}"/"$pref"/"$pref"_R2.fastq.gz
## path to 'sample_description_file.txt'
sample_description_file=${INPUT_DATA}"/sample_description_file.txt"
## path to the file 'db_sim_teleo1.fasta'
refdb_dir=${REFDB_PATH}"/db_carry_all.fasta"
## Path to embl files of the reference database
base_dir=${REFDB_PATH}
### remove '.' and '_' from the prefix files
base_pref=`ls $base_dir/*sdx | sed 's/_[0-9][0-9][0-9].sdx//'g | awk -F/ '{print $NF}' | uniq`
## path to outputs final and temporary (main)
main_dir=`pwd`"/benchmark_real_dataset/04_filtering/Outputs/01_vsearch/main"
fin_dir=`pwd`"/benchmark_real_dataset/04_filtering/Outputs/01_vsearch/final"
################################################################################################
## forward and reverse reads assembly
assembly=${main_dir}"/"${pref}".fastq"
$illuminapairedend -r ${R2_fastq} ${R1_fastq} > ${assembly}
## Remove non-aligned reads
assembly_ali="${assembly/.fastq/.ali.fastq}"
$obigrep -p 'mode!="joined"' ${main_dir}"/"${pref}".fastq" > ${assembly_ali}
## Assign each sequence to a sample
identified="${assembly_ali/.ali.fastq/.ali.assigned.fasta}"
unidentified="${assembly_ali/.ali.fastq/_unidentified.fastq}"
$ngsfilter -t ${sample_description_file} -u ${unidentified} ${assembly_ali} --fasta-output > ${identified}
## Split big file into one file per sample
$obisplit -p $main_dir/"$pref"_sample_ -t sample --fasta ${identified}
all_samples_parallel_cmd_sh=$main_dir/"$pref"_sample_parallel_cmd.sh
echo "" > $all_samples_parallel_cmd_sh
for sample in `ls $main_dir/"$pref"_sample_*.fasta`;
do
sample_sh="${sample/.fasta/_cmd.sh}"
echo "bash "$sample_sh >> $all_samples_parallel_cmd_sh
# Dereplicate reads in unique sequences
dereplicated_sample="${sample/.fasta/.uniq.fasta}"
echo "$obiuniq -m sample "$sample" > "$dereplicated_sample > $sample_sh;
# Keep only sequences longer than 20pb with no N bases
good_sequence_sample="${dereplicated_sample/.fasta/.l20.fasta}"
echo "/usr/bin/time $vsearch --fastx_filter "$dereplicated_sample" --notrunclabels --threads 16 --fastq_maxns 0 --fastq_minlen 20 --fastaout "$good_sequence_sample >> $sample_sh
# Removal of PCR and sequencing errors (variants)
clean_sequence_sample="${good_sequence_sample/.fasta/.r005.clean.fasta}"
echo "$obiclean -r 0.05 -H "$good_sequence_sample" > "$clean_sequence_sample >> $sample_sh
done
parallel < $all_samples_parallel_cmd_sh
# Concatenate all files into one main file
all_sample_sequences_clean=$main_dir/"$pref"_all_sample_clean.fasta
cat $main_dir/"$pref"_sample_*.uniq.l20.r005.clean.fasta > $all_sample_sequences_clean
# Dereplicate in unique sequences
all_sample_sequences_uniq="${all_sample_sequences_clean/.fasta/.uniq.fasta}"
$obiuniq -m sample $all_sample_sequences_clean > $all_sample_sequences_uniq
# Taxonomic assignation
all_sample_sequences_tag="${all_sample_sequences_uniq/.fasta/.tag.fasta}"
$ecotag -d $base_dir/"${base_pref}" -R $refdb_dir $all_sample_sequences_uniq -m 0.98 > $all_sample_sequences_tag
# Removal of unnecessary attributes in sequence headers
all_sample_sequences_ann="${all_sample_sequences_tag/.fasta/.ann.fasta}"
$obiannotate --delete-tag=scientific_name_by_db --delete-tag=obiclean_samplecount \
--delete-tag=obiclean_count --delete-tag=obiclean_singletoncount \
--delete-tag=obiclean_cluster --delete-tag=obiclean_internalcount \
--delete-tag=obiclean_head --delete-tag=obiclean_headcount \
--delete-tag=id_status --delete-tag=rank_by_db --delete-tag=obiclean_status \
--delete-tag=seq_length_ori --delete-tag=sminL --delete-tag=sminR \
--delete-tag=reverse_score --delete-tag=reverse_primer --delete-tag=reverse_match --delete-tag=reverse_tag \
--delete-tag=forward_tag --delete-tag=forward_score --delete-tag=forward_primer --delete-tag=forward_match \
--delete-tag=tail_quality --delete-tag=mode --delete-tag=seq_a_single $all_sample_sequences_tag > $all_sample_sequences_ann
# Sort sequences by 'count'
all_sample_sequences_sort="${all_sample_sequences_ann/.fasta/.sort.fasta}"
$obisort -k count -r $all_sample_sequences_ann > $all_sample_sequences_sort
# Create the final table
$obitab -o $all_sample_sequences_sort > $fin_dir/"$step".csv
gzip $main_dir/*
|
Java
|
UTF-8
| 2,262 | 2.359375 | 2 |
[] |
no_license
|
package service;
import beans.AuthorBean;
import dao.DAOType;
import exception.BusinessException;
import exception.MyException;
import exception.NoSuchObjectInDB;
import exception.SystemException;
import service.dbOperations.DBOperations;
import service.dbOperations.DBOperationsFactory;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created with IntelliJ IDEA.
* User: Admin
* Date: 25.02.13
* Time: 0:06
* To change this template use File | Settings | File Templates.
*/
public class Authentication {
public static AuthorBean authenticate(AuthorBean author, String login, String password) throws BusinessException, SystemException {
if (author.getLogin().equals(login) && author.getPassword().equals(password)) {
return new AuthorBean(author.getId(), login, password);
} else return null;
}
public static void performLogin(HttpServletRequest request, HttpServletResponse response, String login,
String password, ServletContext context) throws ServletException, IOException, MyException {
DBOperations operations = DBOperationsFactory.getDBService((DAOType)context.getAttribute("type"));
if ((login != null) & (password != null)) {
AuthorBean author = operations.getAuthorByLogin(login);
if (author != null) {
AuthorBean tok = authenticate(author, login, password);
if (tok != null) {
request.getSession().removeAttribute("logmessage");
request.getSession().setAttribute("user", tok);
response.sendRedirect("/GetAllDocuments");
} else throw new NoSuchObjectInDB("Incorrect login or password!");
} else {
throw new NoSuchObjectInDB("Incorrect login or password!");
}
} else {
String url = context.getInitParameter("login_page");
if (url != null && !"".equals(url)) {
response.sendRedirect(url);
}
}
}
}
|
Markdown
|
UTF-8
| 1,291 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
# Ember-touchspin
Ember version of [Bootstrap TouchSpin](https://github.com/istvan-ujjmeszaros/bootstrap-touchspin).
## Usage
Ember-touchspin allows you to freely design your TouchSpin component in the way you want by providing a set of yield actions.
```
{{#touch-spin
initVal=inputValue
step=1
decimals=0
as |touchSpin|}}
<button type="button" onmouseup={{action touchSpin.onMouseUpDecrement}} onmousedown={{action touchSpin.onMouseDownDecrement}}>-</button>
<span>hey</span>
<input style="display: inline-block;" value={{touchSpin.value}} type="text" onwheel={{action touchSpin.onWheel}} oninput={{action "onChanged" value="target.value"}}>
<span>%</span>
<button type="button" onmouseup={{action touchSpin.onMouseUpIncrement}} onmousedown={{action touchSpin.onMouseDownIncrement}}>+</button>
{{/touch-spin}}
```
## Installation
* `git clone` this repository
* `npm install`
* `bower install`
## Running
* `ember server`
* Visit your app at http://localhost:4200.
## Running Tests
* `npm test` (Runs `ember try:testall` to test your addon against multiple Ember versions)
* `ember test`
* `ember test --server`
## Building
* `ember build`
For more information on using ember-cli, visit [http://www.ember-cli.com/](http://www.ember-cli.com/).
|
Java
|
UTF-8
| 2,856 | 4.375 | 4 |
[] |
no_license
|
package day0727.ch12;
import java.util.ArrayList;
//------------------------------------------
// MyQueue 클래스 선언
//------------------------------------------
class MyQueue {
//------------------------------------------
// String형으로 ArrayList 변수 arrayQueue 선언,
// String형으로 ArrayList 인스턴스 생성하여 리턴된 메위주 대입
//------------------------------------------
private ArrayList<String> arrayQueue = new ArrayList<String>();
//------------------------------------------
// enQueue() 메서드 선언
// 매개변수로 받은 String형 데이터를 arrayQueue로 add() 메서드 호출하여 맨 뒤에 추가
//------------------------------------------
public void enQueue(String data) {
arrayQueue.add(data);
}
//------------------------------------------
// deQueue() 메서드 선언
// <1> int형 len 변수 선언,
// arrayQueue로 size() 메서드 호출하여 저장된 유효한 자료의 개수를 리턴받아서 대입
// <2> 만약 len의 데이터가 0 이라면
// <3> null 리턴하며 함수 중단
// <4> arrayQueue로 remove() 메서드 호출하여 맨 앞의 자료 반환하고 배열에서 제거
//------------------------------------------
public String deQueue() {
int len = arrayQueue.size(); // <1>
if(len == 0) { // <2>
System.out.println("큐가 비었습니다.");
return null; // <3>
}
return arrayQueue.remove(0); // <4>
}
}
public class Ex06_QueueTest {
public static void main(String[] args) {
//------------------------------------------
// <1> MyQueue형 queue 변수 선언, MyQueue 인스턴스 생성하여 리턴된 메위주 대입
// <2> queue변수로 enQueue() 메서드 호출, "A" 요소 추가
// <3> queue변수로 enQueue() 메서드 호출, "B" 요소 추가
// <4> queue변수로 enQueue() 메서드 호출, "C" 요소 추가
// <5> queue변수로 deQueue() 메서드 호출, 맨 앞 자료 반환하여 출력, A
// <6> queue변수로 deQueue() 메서드 호출, 맨 앞 자료 반환하여 출력, B
// <7> queue변수로 deQueue() 메서드 호출, 맨 앞 자료 반환하여 출력, C
//------------------------------------------
MyQueue queue = new MyQueue(); // <1>
queue.enQueue("A"); // <2>
queue.enQueue("B"); // <3>
queue.enQueue("C"); // <4>
System.out.println(queue.deQueue()); // <5>
System.out.println(queue.deQueue()); // <6>
System.out.println(queue.deQueue()); // <7>
/* =========================================
* 큐
* 선착순을 생각하자.
* 줄을 선 대기열처럼 먼저 추가된 데이터부터 꺼내서 사용하는 방식(First In First Out; FIFO)
* =========================================
*/
}
}
|
C++
|
GB18030
| 1,110 | 4.0625 | 4 |
[] |
no_license
|
//дַеÿո滻20%
// ҳеĿոȻƣַ
/* ַܻʾҪASCIIת%32ո*/
#include <iostream>
#include <cstring>
using namespace std;
char* replacestr(char str[]){
//ûҪµ飬Ϊstr㹻ֱӺԪؼ
if (str == NULL || strlen(str) == 0)/*ע⣺жϴIJǷգ*/
return NULL;
int len = strlen(str);
int count = 0;
int i = 0;
while (count < len && i < len){
if (str[i++] == ' ')
++count;
}
int length = len + count * 2;
i = len;
while (i >= 0){
if (str[i] != ' ')
str[length--] = str[i];
else if (str[i] == ' '){
str[length--] = '0';
str[length--] = '2';
str[length--] = '%';
}
--i;
}
return str;
}
void main04(){
char str[20] = "I am happy";
for (int i = 0; i < strlen(str); ++i){
cout << str[i];
}cout << endl;
int len = strlen(str);
char* s1 = replacestr(str);
for (int i = 0; i < strlen(str); ++i){
cout << str[i];
}
cout << endl;
}
|
Markdown
|
UTF-8
| 1,751 | 2.609375 | 3 |
[] |
no_license
|
# OCI IAM
> IAM, Authentication, Authorization, Policies
## Identity and Access Management (IAM)
It lets you control who has access to your cloud resources.
IAM has 2 principals<sup>**1**</sup> :
- IAM Users
- Instance Principals
### IAM Users and Groups
- Users = individual people or applications
- First IAM User = default administrator
- Users enforce security principle of least privilege:
- Users -> Groups
- Group -> at least one policy with permission to tenancy or a compartment
### Instance Principals
- Instance Principals let instances and applications to make API calls against other OCI services removing the need to configure user credentials or a configuration file.
允许实例和应用程序在实例上运行,以便于对其他OCI服务进行API调用,从而除去用户凭证或配置文件的需要。
<img src="https://imgur.com/OUrwEVH.png" width="720" height="310">
## Authentication
Authentication Service authenticates by:
- User name, Password
- API Signing key (e.g. github API public key)
Required wiehn using the OCI API in conjunction with the SDK/CLI
- Auth Tokens
Oracle-generated toekn strings to authenticate with 3rd party APIs that do no support OCI signature-based authentication
## Authorization
Authorization specifies various actions an authenticated Principal can perform.
**OCI Authorization = Policies**
Policies attachment, can be attached to a compartment or can be attached to an account.
### Policies Syntax
<img src="https://imgur.com/qN8d7kB.png" width="680" height="300">
### Common Policies
<img src="https://imgur.com/uogHaSe.png" width="630" height="310">
---
<sup>**1**</sup> **principal**: is an IAM entity that is allowed to interact with OCI resources
|
C++
|
UTF-8
| 1,722 | 3.796875 | 4 |
[] |
no_license
|
#include<iostream>
#include<conio.h>
#include <chrono>
using namespace std;
using namespace std::chrono;
void heapify(int arr[], int n, int i)
{
int largest = i; // Initialize largest as root
int l = 2 * i + 1; // left = 2*i + 1
int r = 2 * i + 2; // right = 2*i + 2
// If left child is larger than root
if (l < n && arr[l] > arr[largest])
largest = l;
// If right child is larger than largest so far
if (r < n && arr[r] > arr[largest])
largest = r;
// If largest is not root
if (largest != i) {
swap(arr[i], arr[largest]);
// Recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
// main function to do heap sort
void heapSort(int arr[], int n)
{
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
// One by one extract an element from heap
for (int i = n - 1; i > 0; i--) {
// Move current root to end
swap(arr[0], arr[i]);
// call max heapify on the reduced heap
heapify(arr, i, 0);
}
}
int main()
{
int size,A[10],i;
cout<<"\n\t\t\tHEAP SORT\n"<<endl;
cout<<"\tEnter size of array = ";cin>>size;
cout<<"\tEnter values in array : ";
for(i=0;i<size;i++)
{
cin>>A[i];
}
auto start = high_resolution_clock::now();
heapSort(A,size);
cout<<"\tSorted Array - ";
for(int i = 0 ; i < size ; i++){
cout<<" "<<A[i];
}
auto stop = high_resolution_clock::now();
auto duration = duration_cast<milliseconds>(stop - start);
cout <<"\n\tTime taken by Heap Sort: "<< duration.count() << " milliseconds" << endl;
}
|
PHP
|
UTF-8
| 15,824 | 2.65625 | 3 |
[
"CC0-1.0"
] |
permissive
|
<?php
class SWFTextObjectExporterDOCX extends SWFTextObjectExporter {
protected function addSection($textObject) {
// add section name
$heading = new DOCXParagraph;
$heading->paragraphProperties = new DOCXParagraphProperties;
$heading->paragraphProperties->pStyleVal = 'Heading1';
$heading->paragraphProperties->pageBreakBefore = count($this->document->paragraphs) > 0;
$span = new DOCXSpan;
$span->textProperties = new DOCXTextProperties;
$span->textProperties->rStyleVal = 'Heading1Char';
$span->text = $this->beautifySectionName($textObject->name);
$heading->spans[] = $span;
$this->document->paragraphs[] = $heading;
// add the paragraphs
$textFlow = $textObject->tlfObject->textFlow;
foreach($textFlow->paragraphs as $tlfParagraph) {
$docxParagraph = new DOCXParagraph;
$docxParagraph->paragraphProperties = new DOCXParagraphProperties;
$docxParagraphTextProperties = new DOCXTextProperties;
$this->translateProperties($docxParagraph->paragraphProperties, $docxParagraphTextProperties, $textFlow->style);
$this->translateProperties($docxParagraph->paragraphProperties, $docxParagraphTextProperties, $tlfParagraph->style);
$tlfHyperlink = null;
$docxHyperlink = null;
foreach($tlfParagraph->spans as $tlfSpan) {
$docxSpan = new DOCXSpan;
$docxSpan->textProperties = clone $docxParagraphTextProperties;
$docxSpanParagraphProperties = new DOCXParagraphProperties;
$this->translateProperties($docxSpanParagraphProperties, $docxSpan->textProperties, $tlfSpan->style);
if($docxSpanParagraphProperties != new DOCXParagraphProperties) {
// spans cannot have paragraph style properties
// take it off and apply the properties to the paragraph instead
foreach($docxSpanParagraphProperties as $name => $value) {
if($value !== null && $docxParagraph->paragraphProperties->$name !== null) {
$docxParagraph->paragraphProperties->$name = $value;
}
}
}
$docxSpan->text = $tlfSpan->text;
if($tlfSpan->hyperlink !== $tlfHyperlink) {
$tlfHyperlink = $tlfSpan->hyperlink;
if($tlfHyperlink) {
$docxHyperlink = new DOCXHyperlink;
$docxHyperlink->href = $tlfHyperlink->href;
} else {
$docxHyperlink = null;
}
}
$docxSpan->hyperlink = $docxHyperlink;
$docxParagraph->spans[] = $docxSpan;
}
$this->document->paragraphs[] = $docxParagraph;
}
}
protected function translateProperties($docxParagraphProperties, $docxTextProperties, $tlfStyle) {
// backgroundAlpha, blockProgression, breakOpportunity, clearFloats, digitCase, digitWidth, firstBaselineOffset, justificationRule, justificationStyle
// leadingModel, ligatureLevel, lineBreak, textAlpha, wordSpacing, textRotation
// paragraph properties
if($tlfStyle->direction) {
switch($tlfStyle->direction) {
case 'rtl': $docxParagraphProperties->bidi = true; break;
}
}
if($tlfStyle->dominantBaseline) {
switch($tlfStyle->dominantBaseline) {
case 'roman': $docxParagraphProperties->textAlignmentVal = 'baseline'; break;
case 'descent':
case 'ideographicBottom': $docxParagraphProperties->textAlignmentVal = 'bottom'; break;
case 'ascent':
case 'ideographicTop': $docxParagraphProperties->textAlignmentVal = 'top'; break;
case 'ideographicCenter': $docxParagraphProperties->textAlignmentVal = 'center'; break;
}
}
if($tlfStyle->lineHeight) {
if(preg_match('/\d+%$/', $tlfStyle->lineHeight)) {
// when lineRule is "auto", line means 240th of the height of a line
$percentage = (float) $tlfStyle->lineHeight;
$docxParagraphProperties->spacingLine = round($percentage * 240 / 100);
$docxParagraphProperties->spacingLineRule = "auto";
} else if(is_numeric($tlfStyle->lineHeight)) {
$docxParagraphProperties->spacingLine = $this->convertToTwip($tlfStyle->lineHeight);
$docxParagraphProperties->spacingLineRule = "exactly";
}
}
if($tlfStyle->paragraphEndIndent) {
if($tlfStyle->direction == 'rtl') {
$docxParagraphProperties->indLeft = $this->convertToTwip($tlfStyle->paragraphEndIndent);
} else {
$docxParagraphProperties->indRight = $this->convertToTwip($tlfStyle->paragraphEndIndent);
}
}
if($tlfStyle->paragraphSpaceAfter) {
$docxParagraphProperties->spacingAfter = $this->convertToTwip($tlfStyle->paragraphSpaceAfter);
}
if($tlfStyle->paragraphSpaceBefore) {
$docxParagraphProperties->spacingBefore = $this->convertToTwip($tlfStyle->paragraphSpaceBefore);
}
if($tlfStyle->paragraphStartIndent) {
if($tlfStyle->direction == 'rtl') {
$docxParagraphProperties->indRight = $this->convertToTwip($tlfStyle->paragraphStartIndent);
} else {
$docxParagraphProperties->indLeft = $this->convertToTwip($tlfStyle->paragraphStartIndent);
}
}
if($tlfStyle->tabStops) {
$docxParagraphProperties->tabStops = array();
$tlfTabStops = explode(' ', $tlfStyle->tabStops);
foreach($tlfTabStops as $tlfTabStop) {
// see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flashx/textLayout/elements/FlowElement.html#tabStops
if(preg_match('/([sced])([0-9\.]+)(?:\|(.))?/', $tlfTabStop, $m)) {
$docxTabStop = new DOCXTabStop;
$alignment = $m[1];
$position = doubleval($m[2]);
$decimalAlignmentToken = $m[3];
if($tlfStyle->direction == 'rtl') {
switch($alignment) {
case 's': $docxTabStop->type = 'right'; break;
case 'e': $docxTabStop->type = 'left'; break;
case 'c': $docxTabStop->type = 'center'; break;
case 'd': $docxTabStop->type = 'num'; break;
}
} else {
switch($alignment) {
case 's': $docxTabStop->type = 'left'; break;
case 'e': $docxTabStop->type = 'right'; break;
case 'c': $docxTabStop->type = 'center'; break;
case 'd': $docxTabStop->type = 'num'; break;
}
}
$docxTabStop->position = $this->convertToTwip($position);
$docxParagraphProperties->tabStops[] = $docxTabStop;
}
}
}
if($tlfStyle->textAlign) {
switch($tlfStyle->textAlign) {
case 'start': $docxParagraphProperties->jcVal = ($tlfStyle->direction == 'rtl') ? 'right' : 'left'; break;
case 'end': $docxParagraphProperties->jcVal = ($tlfStyle->direction == 'rtl') ? 'left' : 'right'; break;
case 'left': $docxParagraphProperties->jcVal = 'left'; break;
case 'right': $docxParagraphProperties->jcVal = 'right'; break;
case 'center': $docxParagraphProperties->jcVal = 'center'; break;
case 'justify': $docxParagraphProperties->jcVal = 'both'; break;
}
}
if($tlfStyle->textIndent) {
$docxParagraphProperties->indFirstLine = $this->convertToTwip($tlfStyle->textIndent);
}
// text properties
if($tlfStyle->baselineShift) {
switch($tlfStyle->baselineShift) {
case 'superscript': $docxTextProperties->vertAlignVal = 'superscript'; break;
case 'subscript': $docxTextProperties->vertAlignVal = 'subscript'; break;
default:
if(preg_match('/\d+%$/', $tlfStyle->baselineShift)) {
$percentage = (float) $tlfStyle->baselineShift;
$fontSize = ($tlfStyle->fontSize) ? $tlfStyle->fontSize : 12;
$docxTextProperties->vertAlignVal = round($fontSize * 2 * $percentage / 100);
} else if(is_numeric($tlfStyle->baselineShift)) {
$points = (float) $tlfStyle->baselineShift;
$docxTextProperties->vertAlignVal = round($points * 2);
}
}
}
if($tlfStyle->backgroundColor) {
$docxTextProperties->shdFill = substr($tlfStyle->backgroundColor, 1);
}
if($tlfStyle->color) {
$docxTextProperties->colorVal = substr($tlfStyle->color, 1);
}
if($tlfStyle->direction) {
switch($tlfStyle->direction) {
case 'rtl': $docxTextProperties->rtl = true; break;
}
}
if($tlfStyle->fontFamily) {
$docxTextProperties->rFontsAscii = $tlfStyle->fontFamily;
$docxTextProperties->rFontsCs = $tlfStyle->fontFamily;
$docxTextProperties->rFontsHAnsi = $tlfStyle->fontFamily;
$docxTextProperties->rFontsEastAsia = $tlfStyle->fontFamily;
}
if($tlfStyle->fontSize) {
$docxTextProperties->szVal = $docxTextProperties->szCsVal = round($tlfStyle->fontSize * 2);
}
if($tlfStyle->fontStyle) {
switch($tlfStyle->fontStyle) {
case 'italic':
$docxTextProperties->i = true;
$docxTextProperties->iCs = true;
break;
}
}
if($tlfStyle->fontWeight) {
switch($tlfStyle->fontWeight) {
case 'bold':
$docxTextProperties->b = true;
$docxTextProperties->bCs = true;
break;
}
}
if($tlfStyle->kerning) {
switch($tlfStyle->kerning) {
case 'on': $docxTextProperties->kernVal = 8; break; // the smallest size where kerning applies (set to 4 pt)
}
}
if($tlfStyle->lineThrough) {
switch($tlfStyle->lineThrough) {
case 'true': $docxTextProperties->strike = true; break;
}
}
if($tlfStyle->locale) {
$docxTextProperties->langVal = $docxTextProperties->langEastAsia = $docxTextProperties->langBidi = $tlfStyle->locale;
}
if($tlfStyle->textDecoration) {
switch($tlfStyle->textDecoration) {
case 'underline': $docxTextProperties->u = true; break;
}
}
if($tlfStyle->trackingLeft && $tlfStyle->direction == 'rtl') {
$docxTextProperties->spacingVal = $this->convertToTwip($tlfStyle->trackingLeft);
}
if($tlfStyle->trackingRight && $tlfStyle->direction != 'rtl') {
$docxTextProperties->spacingVal = $this->convertToTwip($tlfStyle->trackingRight);
}
if($tlfStyle->typographicCase) {
switch($tlfStyle->typographicCase) {
case 'upper': $docxTextProperties->caps = true; break;
case 'lowercaseToSmallCaps': $docxTextProperties->smallCaps = true; break;
}
}
}
protected function convertToTwip($point) {
return round((float) $point * 20);
}
protected function addDefaultStyles() {
// add font references
$styleUsage = $this->getStyleUsage(array('fontFamily', 'fontSize', 'locale', 'direction', 'lineHeight', 'textIndent'));
$tlfStyle = new TLFFlowElementStyle;
foreach($styleUsage as $propName => $values) {
$mostFrequentValue = key($values);
$frequency = current($values);
// set it as default value if it's used over ninty percent of the times
// or if it's the font family
if($frequency > 0.90 || $propName == 'fontFamily') {
$tlfStyle->$propName = $mostFrequentValue;
}
}
$this->document->defaultTextProperties = new DOCXTextProperties;
$this->document->defaultParagraphProperties = new DOCXParagraphProperties;
$this->translateProperties($this->document->defaultTextProperties, $this->document->defaultParagraphProperties, $tlfStyle);
if(!isset($this->document->styles[$normalStyleId = 'Normal'])) {
$normalStyle = new DOCXStyle;
$normalStyle->styleId = $normalStyleId;
$normalStyle->nameVal = "Normal";
$normalStyle->type = "paragraph";
$normalStyle->default = 1;
$normalStyle->qFormat = true;
$this->document->styles[$normalStyleId] = $normalStyle;
}
if(!isset($this->document->styles[$defaultParagraphFontStyleId = 'DefaultParagraphFont'])) {
$defaultParagraphFontStyle = new DOCXStyle;
$defaultParagraphFontStyle->styleId = $defaultParagraphFontStyleId;
$defaultParagraphFontStyle->nameVal = "Default Paragraph Font";
$defaultParagraphFontStyle->type = "character";
$defaultParagraphFontStyle->semiHidden = true;
$defaultParagraphFontStyle->unhideWhenUsed = true;
$this->document->styles[$defaultParagraphFontStyleId] = $defaultParagraphFontStyle;
}
if(!isset($this->document->styles[$headingStyleId = 'Heading1'])) {
$headingStyle = new DOCXStyle;
$headingStyle->styleId = $headingStyleId;
$headingStyle->nameVal = "heading 1";
$headingStyle->baseOnVal = "Normal";
$headingStyle->linkVal = "Heading1Char";
$headingStyle->uiPriorityVal = 9;
$headingStyle->type = "paragraph";
$headingStyle->qFormat = true;
$headingStyle->paragraphProperties = new DOCXParagraphProperties;
$headingStyle->paragraphProperties->spacingBefore = 480;
$headingStyle->paragraphProperties->spacingAfter = 0;
$headingStyle->paragraphProperties->outlineLvlVal = 0;
$this->document->styles[$headingStyleId] = $headingStyle;
}
if(!isset($this->document->styles[$headingStyleId = 'Heading1Char'])) {
$headingStyle = new DOCXStyle;
$headingStyle->styleId = $headingStyleId;
$headingStyle->nameVal = "Heading 1 Char";
$headingStyle->baseOnVal = "DefaultParagraphFont";
$headingStyle->linkVal = "Heading1";
$headingStyle->uiPriorityVal = 9;
$headingStyle->type = "character";
$headingStyle->textProperties = new DOCXTextProperties;
$headingStyle->textProperties->b = true;
$headingStyle->textProperties->bCs = true;
$headingStyle->textProperties->szVal = 28;
$headingStyle->textProperties->szCsVal = 28;
$headingStyle->textProperties->colorVal = "365F91";
$this->document->styles[$headingStyleId] = $headingStyle;
}
}
protected function addFonts() {
// add properties of embedded fonts
foreach($this->assets->fontFamilies as $fontFamily) {
if(!isset($document->fonts[$fontFamily->name])) {
$docxFont = new DOCXFont;
$docxFont->name = $fontFamily->name;
$docxFont->fontFamily = $fontFamily->name;
// use the information from the normal version of the font if possible
if($fontFamily->normal) {
$embeddedFont = $fontFamily->normal;
} else if($fontFamily->bold) {
$embeddedFont = $fontFamily->bold;
} else if($fontFamily->italic) {
$embeddedFont = $fontFamily->italic;
} else if($fontFamily->boldItalic) {
$embeddedFont = $fontFamily->boldItalic;
}
if($embeddedFont->panose) {
$this->setFontPropertiesFromPanose($docxFont, $embeddedFont->panose);
}
$this->document->fonts[$docxFont->name] = $docxFont;
}
}
// add properties of other referenced fonts
$fontUsage = $this->getFontUsage();
foreach($fontUsage as $fontFamilyName => $usage) {
if(!isset($this->document->fonts[$fontFamilyName])) {
$docxFont = new DOCXFont;
$docxFont->name = $fontFamilyName;
// see if we know this font's appearance
$panose = PanoseDatabase::find($fontFamilyName);
if($panose) {
$this->setFontPropertiesFromPanose($docxFont, $panose);
}
$this->document->fonts[$fontFamilyName] = $docxFont;
}
}
}
protected function setFontPropertiesFromPanose($docxFont, $panose) {
// set generic font-family based on panose values
if($panose[1] == 3) {
$docxFont->family = 'script';
} else if($panose[1] == 4) {
$docxFont->family = 'decorative';
} else if($panose[1] == 5) {
$docxFont->family = 'system';
} else if($panose[1] == 2) {
if($panose[2] >= 11) {
// sans-serif
$docxFont->family = 'swiss';
} else {
// serif
$docxFont->family = 'roman';
}
}
// set the pitch
if($panose[1] == 2) {
if($panose[4] == 9) {
$docxFont->pitch = 'fixed';
} else {
$docxFont->pitch = 'variable';
}
} else if($panose[1] == 3 || $panose[1] == 5) {
if($panose[4] == 3) {
$docxFont->pitch = 'fixed';
} else {
$docxFont->pitch = 'variable';
}
}
$docxFont->panose1 = sprintf("%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", $panose[1], $panose[2], $panose[3], $panose[4], $panose[5], $panose[6], $panose[7], $panose[8], $panose[9], $panose[10]);
}
}
?>
|
Python
|
UTF-8
| 3,969 | 2.640625 | 3 |
[] |
no_license
|
"""
Constructs the data lists of image to id with the following format.
[video_name/%08d] [class_id]
stores them in:
"./Train_list.txt"
"./Test_list.txt"
Customized for the detection task.
"""
import subprocess, os, pickle, csv, argparse
##HARD coded in the dictionaries from the video name to the class index.
#map[videoname][time_stamp] = class_id
#detection_class_index = pickle.load( open("./detection_class_index.pkl","rb"))
VALID_TSmap = pickle.load( open("./VALID_TSmap.pkl", "rb" ) )
TEST_TSmap = pickle.load( open("./TEST_TSmap.pkl", "rb" ) )
UCF_vidmap = pickle.load( open("./UCF_vidmap.pkl", "rb" ) )[1]
detection_class_index = pickle.load( open("./detection_class_index.pkl", "rb" ) )
VID_MAPS = [(UCF_vidmap,VALID_TSmap),TEST_TSmap]
def makeTestList(data_dir, vid_map):
toListFile = []
for d in os.listdir(data_dir): #d is the name of the video
path_to_d = os.path.join(data_dir,d)
frame_to_TS_map = pickle.load( open(os.path.join(path_to_d, "time_stamp_map.pkl"),"rb"))
maxFrame = max(frame_to_TS_map.keys())
for f in os.listdir(os.path.join(data_dir,d)):
get_dot_jpg = f.split('.')
if len(get_dot_jpg) > 1 and get_dot_jpg[1] != "pkl":
frame_name = d+"/"+f
#Now we need to know the label of this image.
frame_num = int(f.split('.'))
if frame_num < maxFrame:
frame_TS = frame_to_TS_map[frame_num]
class_id = vid_map[d][frame_TS]
#print frame_name, frame_index
toListFile.append((frame_name,class_id))
return toListFile
def makeTrainList(data_dir, map_tuple):
UCF_vidmap = map_tuple[0]
VAL_TSmap = map_tuple[1]
toListFile = []
for d in os.listdir(data_dir): #d is the name of the video
path_to_d = os.path.join(data_dir,d)
frame_to_TS_map = pickle.load( open(os.path.join(path_to_d, "time_stamp_map.pkl"),"rb"))
maxFrame = max(frame_to_TS_map.keys())
for f in os.listdir(os.path.join(data_dir,d)):
get_dot_jpg = f.split('.')
if len(get_dot_jpg) > 1 and get_dot_jpg[1] != "pkl":
frame_name = d+"/"+f
#If the frame is a UCF vid, then we should just label the frame as the video class label.
if d in UCF_vidmap.keys():
class_id = UCF_vidmap[d]
toListFile.append((frame_name,class_id))
else:
#The frame is validation, so look at the time stamp.
frame_num = int(f.split('.')[0])
#print f, frame_num, maxFrame, d
if frame_num in frame_to_TS_map.keys():
frame_TS = frame_to_TS_map[frame_num]
if frame_TS in VAL_TSmap[d].keys():
class_id = VAL_TSmap[d][frame_TS]
else:
class_id = 0 #Background by default.
#print frame_name, frame_index
toListFile.append((frame_name,class_id))
return toListFile
def printList(generated_list,out_file):
with open(out_file,'wb') as f:
out = csv.writer(f, delimiter=' ')
for frame, index in generated_list:
out.writerow([frame, index])
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("directory", help="Video directory for this project", type=str, nargs=2)
parser.add_argument('-l', '--list', help="Lists to create from this directory", type=str, nargs=2)
args = parser.parse_args()
if os.path.exists(args.directory[0]):
trainList = makeTrainList(args.directory[0],VID_MAPS[0])
printList(trainList,args.list[0])
if os.path.exists(args.directory[1]):
testList = makeTestList(args.directory[1],VID_MAPS[1])
printList(testList,args.list[1])
|
Python
|
UTF-8
| 1,975 | 4.53125 | 5 |
[] |
no_license
|
# 6. Crear un programa que lea un entero positivo, n, introducido por el usuario y después muestre en pantalla la suma de todos los enteros desde 1 hasta n.
n = int(input('Ingrese un número: '))
suma = 0
# creo la variable suma como contenedor de de los enteros de 1 a n y le sumo el indice del for
for i in range(n + 1):
print(i)
suma = suma + i
print('La suma es', suma)
print()
# 7. Crear un programa que pida al usuario el monto a invertir y calcular cuánto dinero tendrá en su cuenta al cabo de 6 meses si el interés mensual es de 5%. Mostrar el resultado por pantalla.
inversion = float(input('Ingrese el monto a invertir: '))
interes = 0.05 # porcentaje por decimal.
meses = 6
cuenta = (inversion * interes * meses) + inversion
print(cuenta)
# 8. Crear un programa que pida al usuario su edad y muestre por pantalla si es mayor de edad o no.
edad = int(input('Ingrese su edad: '))
if edad >= 18:
print('Usted es mayor de edad')
else:
print('Usted es menor de edad')
print()
# 9. Crear un programa que almacene la cadena de caracteres contraseña en una variable, pregunte al usuario por la contraseña e imprima por pantalla si la contraseña introducida por el usuario coincide con la guardada en la variable sin tener en cuenta mayúsculas y minúsculas.
contraseña = 'puerta18'
login = input('Ingrese su contraseña: ')
if contraseña.lower() == login.lower(): # lower() ignora mayúsculas y minúsculas.
print('Contraseña valida')
else:
print('Contraseña invalida')
print()
# 10. Crear un programa que pida al usuario dos números y muestre por pantalla el cociente de la división entre ellos siempre que el segundo número sea distinto de 0.
numero1 = int(input('Ingrese un número: '))
numero2 = int(input('Ingrese un número mayor que 0: '))
if numero2 == 0:
print('error') # mensaje por si el usuario ingresa por error 0.
else:
cociente = (numero1 / numero2)
print(cociente)
|
Python
|
UTF-8
| 1,489 | 2.890625 | 3 |
[] |
no_license
|
import math
# 1996 Pacejka R25B_13 Lateral Force
# input normal load on tire, slip angle, camber angle, gives lateral force
# on tire y axis
#positive alpha = positive force
#negative camber = "good" camber
#Cyrus
#I have no clue what's happening here, but I believe dynamics is currently working on something similar to this for us
def calc_lat_force(f_z, a, gamma):
#fz- normal force
#fz0 -
fz = f_z*4.448 #lb to N
fz0 = 663.94 #N
pcy1 = 1.377528
pdy1 = 2.4860
pdy2 = -.150167
pdy3 = -1.88895
pey1 = -.000043
pey2 = .000007
pey3 = -3683.9043
pey4 = -15729.78
pky1 = -114.08707
pky2 = -3.621914
pky3 = 2.51886
phy1 = .002182
phy2 = -.001398
phy3 = -.119546
pvy1 = .026184
pvy2 = -.029205
pvy3 = .034106
pvy4 = .424675
dfz = (fz-fz0)/fz0
svy = fz*(pvy1+phy2*dfz+(pvy3+pvy4*dfz)*gamma)
shy = phy1+phy2*dfz+phy3*gamma
cy = pcy1
uy = (pdy1+pdy2*dfz)*(1-pdy3*gamma**2)
dy = uy*fz
kya = pky1*fz0*math.sin(2*math.atan(fz/(pky2*fz0)))*(1-pky3*abs(gamma))
by = kya/(cy*dy)
ay = a+shy
if ay < 0:
sign_ay = -1
elif ay == 0:
sign_ay = 0
else:
sign_ay = 1
ey = (pey1+pey2*dfz)*(1-(pey3+pey4*gamma))*sign_ay
fy0 = -(dy*math.sin(cy*math.atan(by*ay-ey*(by*ay-math.atan(by*ay))))+svy)
lat_force = fy0/4.448
return lat_force
#print(calc_lat_force(.5,.5,.5))
|
Markdown
|
UTF-8
| 11,449 | 2.75 | 3 |
[] |
no_license
|
[TOC]
# 一、概述
内存一直都是性能优化的重点,今天我们主要介绍如何使用`Android Studio`生成分析`hprof`报表,并使用`MAT`分析结果,在介绍之前,首先需要感谢[`Gracker`](https://www.jianshu.com/u/FK4sc4),本文的分析大多数都是来自于它的这篇文章:
> [`http://www.jianshu.com/p/d8e247b1e7b2`](https://www.jianshu.com/p/d8e247b1e7b2)
# 二、获取内存快照并分析
## 2.1 获取内存快照
为了便于大家理解,我们先编写一个用于调试的单例`MemorySingleton`,它内部包含一个成员变量`ObjectA`,而`ObjectA`又包含了`ObjectB`和`ObjectC`,以及一个长度为`4096`的`int`数组,`ObjectB`和`ObjectC`各自包含了一个`ObjectD`,`ObjectD`中包含了一个长度为`4096`的`int`数组,在`Activity`的`onCreate()`中,我们初始化这个单例对象。
```java
public class MemorySingleton {
private static MemorySingleton sInstance;
private ObjectA objectA;
public static synchronized MemorySingleton getInstance() {
if (sInstance == null) {
sInstance = new MemorySingleton();
}
return sInstance;
}
private MemorySingleton() {
objectA = new ObjectA();
}
}
public class ObjectA {
private int[] dataOfA = new int[4096];
private ObjectB objectB = new ObjectB();
private ObjectC objectC = new ObjectC();
}
public class ObjectB {
private ObjectD objectD = new ObjectD();
}
public class ObjectC {
private ObjectD objectD = new ObjectD();
}
public class ObjectD {
private int[] dataOfD = new int[4096];
}
public class MemoryActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_memory);
MemorySingleton.getInstance();
}
}
```
在`Android Studio`最下方的`Monitors/Memory`一栏中,可以看到应用占用的内存数值,它的界面分为几个部分:

我们先点击`2`主动触发一次垃圾回收,再点击`3`来获得内存快照,等待一段时间后,会在窗口的左上部分获得后缀为`hprof`的分析报表:

在生成的`hprof`上点击右键,就可以导出为标准的`hprof`用于`MAT`分析,在屏幕的右边,`Android Studio`也提供了分析的界面,今天我们先不介绍它,而是导出成`MAT`可识别的分析报表。

## 2.2 使用`MAT`分析报表
运行`MAT`,打开我们导出的标准`hprof`文件:

经过一段时间的转换之后,会得到下面的`Overview`界面,我们主要关注的是`Actions`部分:

`Actions`包含了四个部分,点击它可以得到不同的视图:
- `Histogram`:
- `Dominator Tree`
- `Top Consumers`
- `Duplicate Classes`
在平时的分析当中,主要用到前两个视图,下面我们就来依次看一下怎么使用这两个视图来进行分析内存的使用情况。
### 2.2.1 `Histogram`
点开`Histogram`之后,会得到以下的界面:

这个视图中提供了多种方式来对对象进行分类,这里为了分析方便,我们选择按包名进行分类:

要理解这个视图,最关键的是要明白红色矩形框中各列的含义,下面,我们就以在`MemorySingleton`中定义的成员对象为例,来一起理解一下它们的含义:

- `Objects`:表示该类在**内存当中的对象个数**。
这一列比较好理解,`ObjectA`包含了`ObjectB`和`ObjectC`两个成员变量,而它们又各自包含了`ObjectD`,因此内存当中有`2`个`ObjectD`对象。
- `Shallow Heap`
这一列中文翻译过来是“浅堆”,表示的是**对象自身所占用的内存大小,不包括它所引用的对象的内存大小**。举例来说,`ObjectA`包含了`int[]`、`ObjectB`和`ObjectC`这三个引用,但是它并不包括这三个引用所指向的`int[]`数组、`ObjectB`对象和`ObjectC`对象,它的大小为`24`个字节,`ObjectB/C/D`也是同理。
- ```
Retained Heap
```
这一列中文翻译过来是“保留堆”,也就是
当该对象被垃圾回收器回收之后,会释放的内存大小
。举例来说,如果
```
ObjectA
```
被回收了之后,那么
```
ObjectB
```
和
```
ObjectC
```
也就没有对象继续引用它了,因此它也被回收,它们各自内部的
```
ObjectD
```
也会被回收,如下图所示:

因为
```
ObjectA
```
被回收之后,它内部的
```
int[]
```
数组,以及
```
ObjectB/ObjectC
```
所包含的
```
ObjectD
```
的
```
int[]
```
数组所占用的内存都会被回收,也就是:
```cpp
retained heap of ObjectA = shallow heap of ObjectA + int[4096] +retained heap of ObjectB + retained heap of ObjectC
```
下面,我们考虑一种比较复杂的情况,我们的引用情况变为了下面这样:

对应的代码为:
```java
public class MemorySingleton {
private static MemorySingleton sInstance;
private ObjectA objectA;
private ObjectE objectE;
private ObjectF objectF;
public static synchronized MemorySingleton getInstance() {
if (sInstance == null) {
sInstance = new MemorySingleton();
}
return sInstance;
}
private MemorySingleton() {
objectA = new ObjectA();
objectE = new ObjectE();
objectF = new ObjectF();
objectE.setObjectF(objectF);
}
}
public class ObjectE {
private ObjectF objectF;
public void setObjectF(ObjectF objectF) {
this.objectF = objectF;
}
}
public class ObjectF {
private int[] dataInF = new int[4096];
}
```
我们重新抓取一次内存快照,那么情况就变为了:

可以看到`ObjectE`的`Retained Heap`大小仅仅为`16`字节,和它的`Shallow Heap`相同,这是因为它内部的成员变量`objectF`所引用的`ObjectF`,也同时被`MemorySingleton`中的成员变量`objectF`所引用,因此`ObjectE`的释放并不会导致`objectF`对象被回收。
总结一下,`Histogram`是从**类的角度**来观察整个内存区域的,它会列出在内存当中,每个类的实例个数和内存占用情况。
分析完这三个比较重要的列含义之后,我们再来看一下通过右键点击某个`Item`之后的弹出列表中的选项:
- ```
List Objects
```
:

- ```
incomming reference
```
表示它被那些对象所引用

- ```
outgoing
```
则表示它所引用的对象

- `Show objects by class`
和上面的选项类似,只不过列出的是类名。
- ```
Merge Shortest Paths to GC Roots
```
,我们可以选择排除一些类型的引用:

到`Gc`根节点的最短路径
,以
```
ObjectD
```
为例,它的两个实例对象到
```
Gc Roots
```
的路径如下,这个选项很重要,当需要定位内存泄漏问题的时候,我们一般都是通过这个工具:

### 2.2.2 `dominator_tree`
`dominator_tree`则是通过“引用树”的方式来展现内存的使用情况的,通俗点来说,它是站在**对象的角度**来观察内存的使用情况的。例如下图,只有`MemorySingleton`的`Retain Heap`的大小被计算出来,而它内部的成员变量的`Retain Heap`都为`0`:

要获得更详细的情况,我们需要通过它的`outgoing`,也就是它所引用的对象来分析:

可以看到它的`outgoing`视图中有两个`objectF`,但是它们都是指向同一片内存空间`@0x12d8d7f0`,通过这个视图,我们可以列出那么占用内存较多的对象,然后一步步地分析,看究竟是什么导致了它所占用如此多的内存,以此达到优化性能的目的。
# 2.3 分析`Activity`内存泄漏问题
在平时的开发中,我们最容易遇到的就是`Activity`内存泄漏,下面,我们模拟一下这种情况,并演示一下通过`MAT`来分析内存泄漏的原因,首先,我们编写一段会导致内存泄漏的代码:
```java
public class MemorySingleton {
private static MemorySingleton sInstance;
private Context mContext;
public static synchronized MemorySingleton getInstance(Context context) {
if (sInstance == null) {
sInstance = new MemorySingleton(context);
}
return sInstance;
}
private MemorySingleton(Context context) {
mContext = context;
}
}
public class MemoryActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_memory);
MemorySingleton.getInstance(this);
}
}
```
我们启动`MemoryActivity`之后,然后按`back`退出,按照常理来说,此时它应当被回收,但是由于它被`MemorySingleton`中的`mContext`所引用,因此它并不能被回收,此时的内存快照为:

我们通过查看它到`Gc Roots`的引用链,就可以分析出它为什么没有被回收了:

# 三、小结
通过`Android Studio`和`MAT`结合,我们就可以获得某一时刻内存的使用情况,这样我们很好地定位内存问题,是每个开发者必须要掌握的工具!
------
## 更多文章,欢迎访问我的 **Android** 知识梳理系列:
- **Android** 知识梳理目录:[http://www.jianshu.com/p/fd82d18994ce](https://www.jianshu.com/p/fd82d18994ce)
- 个人主页:[http://lizejun.cn](https://link.jianshu.com/?t=http://lizejun.cn)
- 个人知识总结目录:[http://lizejun.cn/categories/](https://link.jianshu.com/?t=http://lizejun.cn/categories/)
作者:泽毛
链接:https://www.jianshu.com/p/fa016c32360f
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
|
Markdown
|
UTF-8
| 1,801 | 2.96875 | 3 |
[
"Apache-2.0"
] |
permissive
|
---
layout: post
title: "Chrome 独享的 Gmail 新功能:浮动窗口可脱离主窗口运行"
date: 2010-06-11 17:44
author: Eyon
comments: true
tags: [Chrome, Chrome技巧, Gmail]
---
继之前 Chrome 用户可优先独享 [Gmail 的附件拖放新功能](http://www.chromi.org/archives/4641)之后,今天 Gmail 团队再次给 Chrome 开小灶,现在 Chrome 用户可以优先使用 Gmail 的另一个新功能——让浮动窗口完全脱离主窗口运行。
<a href="http://img.chromi.org/2010/06/fast_new_window.jpg"></a>
很多朋友可能对 Gmail 的这个浮动窗口不太了解,举个简单的例子:比如你在撰写邮件时,可以点击撰写界面右上角的新窗口按钮,之后就会在一个新弹窗中打开撰写邮件的界面(当然不仅仅是撰写,包括阅读、查收等都可以在一个小浮动窗口中打开)。
<a href="http://img.chromi.org/2010/06/gmail-popup.jpg"></a>
可之前的情况是在浮动窗口打开后,你仍然不能关闭后面的主窗口,因为会连这个浮动窗口一起关掉。而现在如果你使用最新版本 Chrome 浏览器的话,可以将浮动窗口后面的主窗口关掉,浮动窗口可完全独立运行。
今天 Gmail 团队在其官方博客上宣布了这一项全新的功能,并说到这个功能的技术原理,其实很简单:当你关闭主窗口的时候,程序会自动将必须的代码转移到附加的浮动窗口中,而且这是 Chrome 团队完成的。看来,其他浏览器的用户又只能先眼巴巴的看着......
Via [Gmail blog](http://gmailblog.blogspot.com/2010/06/long-lived-new-windows.html)
|
Java
|
UTF-8
| 1,336 | 2.78125 | 3 |
[] |
no_license
|
package leetcode;
import org.omg.CORBA.PUBLIC_MEMBER;
import java.util.*;
public class demo241 {
private Map<String, List<Integer>> map = new HashMap<>();
public List<Integer> diffWaysToCompute(String input) {
if (map.containsKey(input)) return map.get(input);
List<Integer> res = new ArrayList<>();
if (input.isEmpty()) return res;
for (int i = 0; i < input.length(); i++) {
char e = input.charAt(i);
if (e == '+' || e == '-' || e == '*') {
for (int l : diffWaysToCompute(input.substring(0, i))) {
for (int r : diffWaysToCompute(input.substring(i + 1))) {
switch (e) {
case '+':
res.add(l + r);
break;
case '-':
res.add(l - r);
break;
case '*':
res.add(l * r);
break;
}
}
}
}
}
if (res.isEmpty()) res.add(Integer.parseInt(input));
map.put(input, res);
return res;
}
public static void main(String[] args) {
}
}
|
Markdown
|
UTF-8
| 1,574 | 3.296875 | 3 |
[] |
no_license
|
# Naive Bayes Email Classification
We have a set of emails, half of which were written by one person and the other half by another person at the same company.
Our objective is to classify the emails as written by one person or the other based only on the text of the email. We will use the Naive Bayes algorithm. We will also print out the accuracy of our model.
We will start with a list of strings. Each string is the text of an email, which has undergone some basic preprocessing;
we will then split the dataset into training and testing sets.
One particular feature of Naive Bayes is that it’s a good algorithm for working with text classification.
When dealing with text, it’s very common to treat each unique word as a feature, and since the typical person’s vocabulary is
many thousands of words, this makes for a large number of features. The relative simplicity of the algorithm and the
independent features assumption of Naive Bayes make it a strong performer for classifying texts.
We will need to install:
1) Python 3 and pip3
2) Scikit-learn
3) Natural language toolkit
4) Numpy
5) Scipy
Clone this repository into a directory of your choice, then run the startup.py script from there using Terminal (MacOS) with the command 'python startup.py'.
It will first check for the Python modules, then download and unzip a large dataset that we will use. The download/unzipping can take a while.
Next, run the nb_author_id.py script with the command 'python nb_author_id.py' and observe the output. The predictive accuracy of our model is above 97%.
|
PHP
|
UTF-8
| 7,305 | 2.984375 | 3 |
[] |
no_license
|
<?php
//Definir as variaveis para conexao com o Banco de Dados
define('server','mysql:host=localhost; dbname=wim');
define('usuario','root');
define('senha','');
//Classe Clientes
class Clientes{
//Atributos da classe(campos da tabela cliente)
public $cpf;
public $nome;
public $usuario;
public $senha;
public $datanascimento;
public $email;
public $sexo;
public $pais;
public $estado;
public $endereco;
public $complemento;
public $telefone;
public $data;
public $hora;
public $minutos;
public $erro;
public $cmd;
//Meteodo para enviar E-mail
public function enviarEmail(){
// Recebendo dados do formulário
$name = $_GET['nome'];
$email = $_GET['email'];
$usuario = $_GET['usuario'];
$cpf = $_GET['cpf'];
$subject = "Mensagem do Site";
$headers = "Content-Type: text/html; charset=utf-8\r\n";
$headers .= "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";
// Dados que serão enviados
$corpo = "Formulário da página de contato <br>";
$corpo .= "Nome: " . $name . " <br>";
$corpo .= "Usuário: " . $usuario . " <br>";
$corpo .= "Email: " . $email . " <br>";
$corpo .= "CPF: " . $cpf . " <br>";
// Email que receberá a mensagem (Não se esqueça de substituir)
$email_to = 'mariogodaoo@hotmail.com';
// Enviando email
$status = mail($email_to, mb_encode_mimeheader($subject, "utf-8"), $corpo, $headers);
}
//meteodo para inserir Clientes
public function inserir(){
//criar a conexao com o banco de dados
$pdo = new PDO(server,usuario,senha);
//verificar see foi enviado valores pelo formulário
if(isset($_GET["cpf"]) && isset($_GET["nome"]) && isset($_GET["usuario"]) && isset($_GET["senha"]) && isset($_GET["datanascimento"]) && isset($_GET["email"]) && isset($_GET["sexo"]) && isset($_GET["pais"]) && isset($_GET["estado"]) && isset($_GET["endereco"]) && isset($_GET["complemento"]) && isset($_GET["telefone"]) && isset($_GET["data"]) && isset($_GET["hora"]) && isset($_GET["minutos"])){
//preencher os atributos com os valores recebidos
$this->cpf = $_GET["cpf"];
$this->nome = $_GET["nome"];
$this->usuario = $_GET["usuario"];
$this->senha = $_GET["senha"];
$this->datanascimento = $_GET["datanascimento"];
$this->email = $_GET["email"];
$this->sexo = $_GET["sexo"];
$this->pais = $_GET["pais"];
$this->estado = $_GET["estado"];
$this->endereco = $_GET["endereco"];
$this->complemento = $_GET["complemento"];
$this->telefone = $_GET["telefone"];
$this->data = $_GET["data"];
$this->hora = $_GET["hora"];
$this->minutos = $_GET["minutos"];
$this->cmd = password_hash($_GET["cpf"], PASSWORD_DEFAULT);
//Criar o comando SQL com parametros para insercao
$smtp = $pdo->prepare("insert into usuario(cpf,nome,usuario,senha,datanascimento,email,sexo,pais,estado,endereco,complemento,telefone,data,hora,minutos,cargo,cmd) values(:cpf, :nome, :usuario, md5(:senha), :datanascimento, :email, :sexo, :pais, :estado, :endereco, :complemento, :telefone, :data, :hora, :minutos, :cargo, :cmd) ");
//Executar o comando banco de dados passando os valores recebidos
$smtp->execute(array(
':cpf' => $this->cpf,
':nome' => $this->nome,
':usuario' => $this->usuario,
':senha' => $this->senha,
':datanascimento' => $this->datanascimento,
':email' => $this->email,
':sexo' => $this->sexo,
':pais' => $this->pais,
':estado' => $this->estado,
':endereco' => $this->endereco,
':complemento' => $this->complemento,
':telefone' => $this->telefone,
':data' => $this->data,
':hora' => $this->hora,
':minutos' => $this->minutos,
':cargo' => 'c',
':cmd' => $this->cmd
));
//Criar o comando SQL com parametros para insercao - CARTEIRA
$smtp = $pdo->prepare("insert into carteira(codigo,saldo,recebido,cmd,usuario_cpf) values(null, 0, 0, :cmd, :cpf) ");
//Executar o comando banco de dados passando os valores recebidos
$smtp->execute(array(
':cmd' => $this->cmd,
':cpf' => $this->cpf
));
//Criar o comando SQL com parametros para insercao - MENSAGEM INICIAL
$smtp = $pdo->prepare("insert into notificacao(codigo,titulo,descricao,cor,ativo,usuario_cpf) values(null, :titulo, :descricao, :cor, :ativo, :usuario_cpf) ");
//Executar o comando banco de dados passando os valores recebidos
$smtp->execute(array(
':titulo' => 'Sucesso!',
':descricao' => 'Obrigado por usar a nossa plataforma.',
':cor' => 'alert success',
':ativo' => 's',
':usuario_cpf' => $this->cpf
));
//Criar o comando SQL com parametros para insercao - MENSAGEM INICIAL
$smtp = $pdo->prepare("insert into notificacao(codigo,titulo,descricao,cor,ativo,usuario_cpf) values(null, :titulo, :descricao, :cor, :ativo, :usuario_cpf) ");
//Executar o comando banco de dados passando os valores recebidos
$smtp->execute(array(
':titulo' => 'Curiosidade!',
':descricao' => 'Você pode enviar dúvida ou sugestão na nossa página inicial.',
':cor' => 'alert info',
':ativo' => 's',
':usuario_cpf' => $this->cpf
));
//Criar o comando SQL com parametros para insercao - MENSAGEM INICIAL
$smtp = $pdo->prepare("insert into notificacao(codigo,titulo,descricao,cor,ativo,usuario_cpf) values(null, :titulo, :descricao, :cor, :ativo, :usuario_cpf) ");
//Executar o comando banco de dados passando os valores recebidos
$smtp->execute(array(
':titulo' => 'Cuidado!',
':descricao' => 'Evite trapacear em nossa plataforma.',
':cor' => 'alert',
':ativo' => 's',
':usuario_cpf' => $this->cpf
));
//Criar o comando SQL com parametros para insercao - MENSAGEM INICIAL
$smtp = $pdo->prepare("insert into notificacao(codigo,titulo,descricao,cor,ativo,usuario_cpf) values(null, :titulo, :descricao, :cor, :ativo, :usuario_cpf) ");
//Executar o comando banco de dados passando os valores recebidos
$smtp->execute(array(
':titulo' => 'Aviso!',
':descricao' => 'Pense bem caso queira excluir sua conta.',
':cor' => 'alert warning',
':ativo' => 's',
':usuario_cpf' => $this->cpf
));
//Testar se retornou algum resultado
if ($smtp->rowCount() > 0) {
header("location:../index.php");//Retornar para o index.php
}
}else{
header("location:../index.php");//Retornar para o index.php
}
}
}
?>
|
C#
|
UTF-8
| 1,625 | 2.6875 | 3 |
[] |
no_license
|
using System;
using System.Linq;
using System.Collections.Generic;
namespace ConsoleApp1
{
abstract class servize
{
public abstract Product1 chainik();
public abstract Product3 tarelka();
public abstract Product2 chashka();
}
class KazakhstanFactory : servize
{
public override Product1 chainik()
{
return new Chainik();
}
public override Product2 chashka()
{
return new Chashka();
}
public override Product3 tarelka()
{
return new Tarelka();
}
}
class ChainaFactory : servize
{
public override Product1 chainik()
{
return new Chainik();
}
public override Product2 chashka()
{
return new Chashka();
}
public override Product3 tarelka()
{
return new Tarelka();
}
}
class IndiaFactory : servize
{
public override Product1 chainik()
{
return new Chainik();
}
public override Product2 chashka()
{
return new Chashka();
}
public override Product3 tarelka()
{
return new Tarelka();
}
}
abstract class Product1 { }
abstract class Product2 { }
abstract class Product3 { }
class Chainik : Product1 { }
class Chashka : Product2 { }
class Tarelka : Product3 { }
class Program
{
static void Main(string[] args)
{
}
}
}
|
PHP
|
UTF-8
| 4,299 | 2.78125 | 3 |
[] |
no_license
|
<?php
class Controller{
// llamada a la plantilla
public function callTemplate(){
include "views/plantilla.php";
}
#interaccion con el usuario
public function enlacesPaginasController(){
if (isset($_GET["action"])) {
$enlacesController= $_GET["action"];
}else{
$enlacesController="registro";
}
$respuesta=enlacesPaginas::enlacesPaginasModel($enlacesController);
include $respuesta;
}
//Registro de Usuario
public function usuarioRegistroController(){
if (isset($_POST["usuario"])) {
# code...
$usuario= $_POST["usuario"];
$password= $_POST["password"];
$email= $_POST["email"];
$datosController=array("usuario"=>$usuario,"password"=>$password,"email"=>$email);
$repuesta=Usuarios::usuarioRegistroModel($datosController,"usuarios");
if ($repuesta=="success") {
# code...
header("location:index.php?action=ok");
}else{
header("location:index.php");
}
}
}
public function usuarioIngresoController(){
if (isset($_POST["ingresoUsuario"])) {
$usuario= $_POST["ingresoUsuario"];
$password= $_POST["ingresoPassword"];
echo "Registro Exitoso";
$datosController=array("usuario"=>$usuario,"password"=>$password);
$respuesta=Usuarios::usuarioIngresoModel($datosController,"usuarios");
if ($respuesta["usuario"]==$usuario && $respuesta["password"]==$password) {
# code...
session_start();
$_SESSION["validar"]=true;
header("location:index.php?action=usuarios");
}else{
header("location:index.php?action=fallo");
}
}
}
public function vistaUsuariosController(){
$respuesta=Usuarios::vistaUsuariosModel("usuarios");
foreach ($respuesta as $row => $value) {
echo'<tr>
<td>'.$value["usuario"].'</td>
<td>'.$value["password"].'</td>
<td>'.$value["email"].'</td>
<td><a href="index.php?action=editar&id='.$value["id"].'"><button type="button" class="btn btn-success">editar</button></a></td>
<td><a href="index.php?action=usuarios&idB='.$value["id"].'"><button type="button" class="btn btn-danger">eliminar</button></a></td>
</tr>';
}
}
//funcion para editar datos de un usuario
public function editarUsuarioController(){
$id=$_GET["id"];
$editar=Usuarios::editarUsuarioModel($id,"usuarios");
echo '
<input type="hidden" class="form-control my-3" value="'.$editar["id"].'" name="idEditar">
<input type="text" class="form-control my-3" value="'.$editar["usuario"].'" name="usuarioEditar" requerid>
<input type="text" class="form-control my-3" value="'.$editar["password"].'" name="passwordEditar" required>
<input type="email" class="form-control my-3" value="'.$editar["email"].'" name="emailEditar" >
<input type="submit" class="btn btn-danger" value="Actualizar">
';
}
//actualizar usuario
public function actualizarUsuarioController(){
if (isset($_POST["usuarioEditar"])) {
# code...
$id=$_POST["idEditar"];
$usuario= $_POST["usuarioEditar"];
$password= $_POST["passwordEditar"];
$email= $_POST["emailEditar"];
$datos=array("id"=>$id,"usuario"=>$usuario,"password"=>$password,"email"=>$email);
$actualizarUser=Usuarios::actualizarUsuarioModel($datos,"usuarios");
if ($actualizarUser=="success") {
# code...
header("location:index.php?action=cambio");
}else{
echo "error";
}
}
}
#eliminar usuario
public function borraUsuarioController()
{
if (isset($_GET["idB"])) {
$datos=$_GET["idB"];
echo $datos;
$deleteUser=Usuarios::borrarUsuarioModel($datos,"usuarios");
echo $deleteUser;
if ($deleteUser=="success")
{
# code...
header("location:index.php?action=usuarios");
}
}
}
}
#comenzar con videos de session 33
?>
|
Markdown
|
UTF-8
| 2,724 | 2.96875 | 3 |
[] |
no_license
|
# TypeScript
### (一)概述
### (二)主要内容
1.强类型和弱类型
强类型不允许又隐式类型转换;落泪行可以
javascript的问题
const obj={}
obj.foo() //运行才报错
数字+‘字符串’==拼接字符串
强优势
1、错误更早提醒
2、代码智能,提示,准确
3、重构绕靠
4、减少不必要的类型判断
2.静态类型和动态类型
静态类型就是申明之后的变量,类型就确定了, 相反动态就是可以改
3.javascript 自有类型系统问题
4.Flow静态类型检查方案
Flow java..类型检查其
类型注解 ::numbe--babel--->
两种方案处理:babel. flow-remove-types---删除类型注释。控制文件能再生产运行
运行才能提示错误,不友好,所以用插件处理错误提示Flow language support
cosnt a:number = NaN infinity
const :undfiend x void=undifend
元组
对象类型的限制
字面量类型--联合类型 a|b|c
type:xxx---maybe
mix any 联合类型。。string,boolean...
需要类型判断处理
any 类型
还是弱类型。。。
flow 资料

内置对象 APi
HTMLElement 类型
4.Typescript语言规范与基本应用
java 超集,扩展 比flow 更强、生态更号
yarn tsc --init ==>配置表json--->strictNullChecks
原始数据类型
symbol()
标准申明库 声明文件
target-->lib['ES2015']...lib['ES2015','DOM']
配置ts 错误提示--vscode performenc
作用域
对象 不单指对象 const obj:{foo: nubmer,bar: string}={foo:1,bar:'xxx'}
数组类型 flow 基本一直
元组 tuple:[number,string]=[18,'xxx'] 一一对应,不多不少
枚举
//定义状态,然后就能维护,这样其他模块中就能直接用,也不会因为时间久了不知道对应的code含义
enum state {
undo=-1,
doing=0,
done=1,
}//不赋值就从0(或者赋值的第一个值的开始 )累加,
const test={
states:state.undo/.doing
}
函数类型
...rest 操作符控制任意参数
任意类型 any
隐式推断 就是赋值的变量会被认为是什么类型 can not x asssign..
类型断言 as 告诉它 这是什么类型 <string>a //jsx 不能
接口 interface -->其实就是定义数据的一个类型规范,有那些属性和属性类型
interface men{
name:string;
age:number;
marry?:boolean//可选
readonly xx: //只读属性
}
动态的接口定义
interface men{
[tmp:string]: string //key 随便命名,但是都要是string
}
类Class
类的修饰符--private 私有属性,public protected(子类能访问) readonly
抽象类 abstract 注意要实现抽象方法
泛型
Array<T>---->Array<number> ----》Array<string>
类型声明
declare
|
C++
|
UTF-8
| 1,044 | 3.09375 | 3 |
[] |
no_license
|
#include "ClassDeclaration.h"
using namespace std;
ClassDeclaration::ClassDeclaration(): HashElement(""), _baseClass("")
{}
ClassDeclaration::ClassDeclaration(const string& identifer): HashElement(identifer), _baseClass("")
{}
ClassDeclaration::ClassDeclaration(const string& identifer, const string& baseClass): HashElement(identifer), _baseClass(baseClass)
{}
ClassDeclaration::ClassDeclaration(const ClassDeclaration& c): HashElement(c.get_id()), _baseClass(c.getBaseClass())
{}
void ClassDeclaration::print(std::ostream& flux) const
{
HashElement::print(flux);
if (!_baseClass.empty()) flux << endl << "Classe mère : " << _baseClass;
else flux << endl << "Aucune classe mère";
}
bool operator==(const ClassDeclaration& c1, const ClassDeclaration& c2)
{
return c1.is_equal(c2);
}
bool operator!=(const ClassDeclaration& c1, const ClassDeclaration& c2)
{
return (!c1.is_equal(c2));
}
std::ostream& operator<<(std::ostream& flux, const ClassDeclaration& element)
{
element.print(flux);
return flux;
}
|
Python
|
UTF-8
| 1,602 | 4.0625 | 4 |
[] |
no_license
|
shopping = 'y'
pie_list = ["Pecan", "Apple Crisp", "Bean", "Banoffee", "Black Bun",
"Blueberry", "Buko", "Burek", "Tamale", "Steak"]
pie_dict = {pie: amt for pie, amt in zip(pie_list, [0 for i in range(len(pie_list))])}
print(pie_dict)
# Display initial message
print("Welcome to the House of Pies! Here are our pies:")
# While we are still shopping...
while shopping == "y":
# Show pie selection prompt
print("---------------------------------------------------------------------")
print("Pecan, Apple Crisp, Bean, Banoffee, " +
"Black Bun, Blueberry, Buko, Burek, " +
"Tamale, Steak ")
pie_choice = input("Which would you like? ")
# Add pie purchase to the pie dictionary by incrementing its value by 1
pie_dict[pie_choice] += 1
print("------------------------------------------------------------------------")
# Inform the customer of the pie purchase
print("Great! We'll have that " + pie_choice + " right out for you.")
# Provide exit option
shopping = input("Would you like to make another purchase: (y)es or (n)o? ")
# Once the pie list is complete
print("------------------------------------------------------------------------")
# Count instances of each pie
print("You purchased: ")
# Loop through the full pie dict and return pies that have been added to cart
for pie in pie_dict:
if pie_dict[pie] > 0:
pie_name = pie
pie_count = pie_dict[pie]
# Gather the count of each pie in the pie list and print them alongside the pies
print(str(pie_count) + " " + pie_name)
|
C
|
UTF-8
| 1,158 | 2.5625 | 3 |
[
"ISC"
] |
permissive
|
#include <kernel/x86/8259pic.h>
#include <kernel/x86/portio.h>
/* resources: [8259], [osdev/PIC] */
#define PIC_MASTER 0x20
#define PIC_SLAVE 0xa0
#define PIC_CMD(pic) (pic)
#define PIC_DATA(pic) ((pic)+1)
#define PIC_INIT 0x10
#define PIC_EOI 0x20
void remap_8259pic(void) {
out8(PIC_CMD(PIC_MASTER), PIC_INIT);
out8(PIC_CMD(PIC_SLAVE), PIC_INIT);
out8(PIC_DATA(PIC_MASTER), IRQ(0)); /* Set the starting intterupt of the master */
out8(PIC_DATA(PIC_SLAVE), IRQ(8)); /* ...and the slave. */
/* Tell the pics about their relationship. The slave is on the master's
* pin #2. */
out8(PIC_DATA(PIC_MASTER), 1<<2); /* The master expects a bitmask of slaves */
out8(PIC_DATA(PIC_SLAVE), 2); /* The slave expects the master irq number it's
attached to (a 3 bit field). */
}
void disable_8259pic(void) {
/* Okay, now actually disable the pic: */
out8(PIC_DATA(PIC_MASTER), 0xff);
out8(PIC_DATA(PIC_SLAVE), 0xff);
}
void send_8259pic_EOI(int irq) {
if(irq >= 8) {
out8(PIC_CMD(PIC_SLAVE), PIC_EOI);
}
out8(PIC_CMD(PIC_MASTER), PIC_EOI);
}
Regs *ignore_8259pic_irq(Regs *regs) {
send_8259pic_EOI(regs->int_no - IRQ(0));
return regs;
}
|
Java
|
ISO-8859-3
| 3,968 | 3.65625 | 4 |
[] |
no_license
|
package models;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
/**
* @author Pol & Angel
* @name Game.java
* @origin Play.java
* @description Model: motor del programa, conte tots els metodes pel funcionament del joc
* @test GameTest.java
*/
public class Game {
private int arraySolution[];
private String arrayAttempts[][];
private int attempt;
private Random randomCreator = new Random();
/**
* @constructor Creaci del objecte Game amb els seus atributs, es pasa per parametre maxAttempt
* @param maxAttempt Integer: quanitat maxima d'intents, esta creat per futures implementacions ja que podrem canviar si es vol amb 10 o 5 intents per mes dificultat a l'hora de jugar
* @arrayAttempts Array: strings que conten els resultats que va introduint l'usuari
* @attempt Integer: numero d'intent actual
* @arraySolution Array: solucio final per acabar el joc
*/
public Game(int maxAttempt) {
this.arrayAttempts = new String[maxAttempt][6];
this.attempt = 0;
this.arraySolution = new int[4];
}
/**
* @solution Metode que crea una soucio valida pel joc, comprova que cap numero es igual a l'anterior
* @return arraySolution: conte la solucio final per acabar el joc (9-2-3-1, per exemple)
*/
public int[] solution() {
Set<Integer> alreadyUsedNumbers = new HashSet<>();
int total = 0;
while (alreadyUsedNumbers.size() < 4) {
int randomNumber = randomCreator.nextInt(10);
if (!alreadyUsedNumbers.contains(randomNumber)){
arraySolution[total] = randomNumber;
alreadyUsedNumbers.add(randomNumber);
total++;
}
}
return arraySolution;
}
/**
* @checkNumber Metode que comprova si el numero introduit es de 4 digits, en cas de ser-ho intenta convertir-lo a Integer
* @param value String: opcio que ha introduit l'usuari per teclat
* @return Boolean: en cas de se un numero diferent de 4 digits retorna un false, si es de 4 digits pero no son numeros tambe. Unic cas que retorna true es que siguin 4 numeros
*/
public boolean checkNumber(String value) {
if(value.length() != 4) {
return false;
}else {
try {
Integer.parseInt(value);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
/**
* @introduceArrayAttempts Metode que introdueix la opcio de l'usuari a l'array d'intents arrayAttempts
* @param value String: opcio que ha introduit l'usuari per teclat
* @return Array: retorna tota l'array d'intents ja que d'aquesta forma el test tindra mes qualitat
*/
public String[][] introduceArrayAttempts(String value) {
char[] valueSeparate = value.toCharArray();
for(int index = 0; index < 4; index++) {
arrayAttempts[attempt][index] = Character.toString(valueSeparate[index]);
}
return arrayAttempts;
}
/**
* @introduceBalls Metode que introdueix les boles blanques i les boles negres al seu intent corresponent a l'array arrayAttempts
* @param whiteBalls Integer: quanitat de boles blanques que s'introduiran
* @param blackBalls Integer: quanitat de boles negres que s'introduiran
* @return Array: retorna tota l'array d'intents ja que d'aquesta forma el test tindra mes qualitat
*/
public String[][] introduceBalls(int whiteBalls, int blackBalls) {
String white = String.valueOf(whiteBalls);
String black = String.valueOf(blackBalls);
this.arrayAttempts[attempt][4] = white;
this.arrayAttempts[attempt][5] = black;
return arrayAttempts;
}
/**
* @getters Gets de l'objecte Balls
*/
public int[] getArraySolution() {
return arraySolution;
}
public String[][] getArrayAttempts() {
return arrayAttempts;
}
public int getAttempt() {
return attempt;
}
/**
* @setter Set de l'objecte Balls
*/
public void setAttempt(int attempt) {
this.attempt = attempt;
}
}
|
C++
|
UTF-8
| 8,664 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
#include "inputassembler.h"
#include "matrixd.h"
#include "io.h"
#include <stdexcept>
#include <opencv2/opencv.hpp>
#include "iaveragebackgroundcolourlocator.h"
#include <algorithm>
#include <random>
namespace anima
{
namespace ia
{
std::vector<math::vec3> RemoveDuplicatesWithGrid(const cv::Mat& mat, unsigned gridSize)
{
START_TIMER(CleaningWithGrid);
assert(mat.type() == CV_32FC3);
const unsigned r = mat.rows, c = mat.cols;
std::vector<math::vec3> points;
points.reserve(r*c/50);
const unsigned gridCubed = gridSize*gridSize*gridSize;
const unsigned gridSizeMinusOne = gridSize-1;
bool* grid = new(std::nothrow) bool[gridCubed]();
if(!grid)
throw std::runtime_error("Unable to allocate 3D grid for input processing");
for (unsigned i = 0; i < r; ++i)
{
float* data = (float*)(mat.data + mat.step*i);
for(unsigned j = 0; j < c; ++j)
{
math::vec3& p = *((math::vec3*)(data + j*3));
math::vec3i pi(p.x*gridSize,p.y*gridSize,p.z*gridSize);
if(unsigned(pi.x) >= gridSize)
pi.x = gridSizeMinusOne;
if(unsigned(pi.y) >= gridSize)
pi.y = gridSizeMinusOne;
if(unsigned(pi.z) >= gridSize)
pi.z = gridSizeMinusOne;
bool& b = grid[pi.x + gridSize*(pi.y + gridSize*pi.z)];
if (!b)
{
b = true;
points.push_back(p);
}
}
}
delete[] grid;
END_TIMER(CleaningWithGrid);
return points;
}
void RandomSimplify(std::vector<math::vec3>* points, float percentageToRemove)
{
START_TIMER(RandomSimplifying);
size_t initialSize = points->size();
std::random_device rd;
std::mt19937 random(rd());
std::shuffle(points->begin(), points->end(), random);
points->erase(points->begin()+(int)(points->size()*(1.f-percentageToRemove/100.f)), points->end());
Inform("" + ToString(points->size()/float(initialSize)*100) + "% of points remain (" +
ToString(points->size()) + "/" + ToString(initialSize)+")");
END_TIMER(RandomSimplifying);
}
float InputAssembler::normalisationMultiplier(int cvCode)
{
switch(cvCode)
{
case CV_8UC3:
return 1.0/255.0;
case CV_16UC3:
return 1.0/65535.0;
case CV_32FC3:
return 1.0;
default:
throw std::runtime_error("Unknown format in input assember at line " + ToString(__LINE__));
}
assert(0);
}
InputAssembler::InputAssembler(InputAssemblerDescriptor& desc)
{
START_TIMER(ProcessingInput);
//Convert the input into 3 component float mat.
if(desc.foregroundSource == nullptr)
throw std::runtime_error("Null source foreground Mat");
if(desc.backgroundSource == nullptr)
throw std::runtime_error("Null source background mat");
if(desc.backgroundLocator == nullptr)
throw std::runtime_error("Null background colour locator");
if(!desc.ipd.validate())
throw std::runtime_error("Could not validate input processor.");
if(desc.foregroundSource->cols*desc.foregroundSource->rows==0)
throw std::runtime_error("Empty foreground source.");
if(desc.backgroundSource->cols*desc.backgroundSource->rows==0)
throw std::runtime_error("Empty background source.");
desc.foregroundSource->convertTo(mForegroundF, CV_32FC3,
normalisationMultiplier(desc.foregroundSource->type()));
desc.backgroundSource->convertTo(mBackgroundF, CV_32FC3,
normalisationMultiplier(desc.backgroundSource->type()));
//Convert everything to the appropriate colour space:
mColourSpace = desc.targetColourspace;
switch(desc.targetColourspace)
{
case InputAssemblerDescriptor::ETCS_RGB:
break;
case InputAssemblerDescriptor::ETCS_HSV:
cv::cvtColor(mForegroundF, mForegroundF, cv::COLOR_RGB2HSV);
cv::cvtColor(mBackgroundF, mBackgroundF, cv::COLOR_RGB2HSV);
//Normalise hue:
for (int i = 0; i < mForegroundF.rows; ++i)
{
float* data = (float*)(mForegroundF.data + mForegroundF.step*i);
for(int j = 0; j < mForegroundF.cols; ++j)
*(data + j*3)/=360.f;
}
for (int i = 0; i < mBackgroundF.rows; ++i)
{
float* data = (float*)(mBackgroundF.data + mBackgroundF.step*i);
for(int j = 0; j < mBackgroundF.cols; ++j)
*(data + j*3)/=360.f;
}
break;
case InputAssemblerDescriptor::ETCS_LAB:
cv::cvtColor(mForegroundF, mForegroundF, cv::COLOR_RGB2Lab);
cv::cvtColor(mBackgroundF, mBackgroundF, cv::COLOR_RGB2Lab);
//Get into proper range
for (int i = 0; i < mForegroundF.rows; ++i)
{
float* data = (float*)(mForegroundF.data + mForegroundF.step*i);
for(int j = 0; j < mForegroundF.cols; ++j)
{
math::vec3& p = *((math::vec3*)(data + j*3));
p = math::vec3(p.x, (p.y+127.f), (p.z+127.f))/254.f;
}
}
for (int i = 0; i < mBackgroundF.rows; ++i)
{
float* data = (float*)(mBackgroundF.data + mBackgroundF.step*i);
for(int j = 0; j < mBackgroundF.cols; ++j)
{
math::vec3& p = *((math::vec3*)(data + j*3));
p = math::vec3(p.x, (p.y+127.f), (p.z+127.f))/254.f;
}
}
break;
}
//Convert mat to vector, and clean:
mPoints = RemoveDuplicatesWithGrid(mForegroundF, desc.ipd.gridSize);
mBackgroundPoints = RemoveDuplicatesWithGrid(mBackgroundF, desc.ipd.gridSize);
//Find dominant background colour:
mBackground = desc.backgroundLocator->findColour(mBackgroundF);
//Simplify randomly if needed:
if(desc.ipd.randomSimplify)
{
RandomSimplify(&mPoints, desc.ipd.randomSimplifyPercentage);
RandomSimplify(&mBackgroundPoints, desc.ipd.randomSimplifyPercentage);
}
END_TIMER(ProcessingInput);
}
cv::Point3f InputAssembler::debugGetPointColour(math::vec3 p) const
{
switch(mColourSpace)
{
case InputAssemblerDescriptor::ETCS_RGB:
break;
case InputAssemblerDescriptor::ETCS_HSV:
{
p.x *= 360.f;
cv::Mat mat(1,1,CV_32FC3, &p.x);
cv::cvtColor(mat, mat, cv::COLOR_HSV2BGR);
}
break;
case InputAssemblerDescriptor::ETCS_LAB:
{
p = math::vec3(p.x*254.f,
p.y*254.f - 127.f,
p.z*254.f - 127.f);
cv::Mat mat(1,1,CV_32FC3, &p.x);
cv::cvtColor(mat, mat, cv::COLOR_Lab2BGR);
}
break;
default:
assert(0);
}
return cv::Point3f(p.z,p.y,p.x);
}
const std::vector<math::vec3>& InputAssembler::backgroundPoints() const
{
return mBackgroundPoints;
}
const std::vector<math::vec3>& InputAssembler::points() const
{
return mPoints;
}
const cv::Mat& InputAssembler::mat() const
{
return mForegroundF;
}
math::vec3 InputAssembler::background() const
{
return mBackground;
}
}
}
|
Markdown
|
UTF-8
| 19,036 | 2.71875 | 3 |
[
"MIT"
] |
permissive
|
---
title: "Building a directory map with ELK"
#description:
toc: true
authors:
- David Pilato
tags:
- elasticsearch
- logstash
- kibana
categories:
- tutorial
date: 2015-12-10 09:28:15 +0100
lastmod: 2015-12-10 09:28:15 +0100
# featuredImage: blog/2016-03-17-and-the-beats-go-on/beats.png
draft: false
aliases:
- /blog/2015/12/10/building-a-directory-map-with-elk/
---
I gave a [BBL talk](http://www.brownbaglunch.fr/) recently and while chatting with attendees, one of them told me a simple use case he covered with elasticsearch: indexing metadata files on a NAS with a simple `ls -lR` like command.
His need is to be able to search on a NAS for files when a user wants to restore a deleted file.
As you can imagine a search engine is super helpful when you have hundreds of millions files!
I found this idea great and this is by the way why I love speaking at conferences or in companies: you always get great ideas when you listen to others!
I decided then to adapt this idea using the ELK stack.
<!-- more -->
## Find the command line
As I'm running on MacOS, I need to install first [coreutils](https://makandracards.com/mmarschall/4445-change-time-format-when-using-ls-on-mac-osx) as I'm missing one cool parameter to the `ls` command: `--time-style`.
```sh
brew install coreutils
```
I'm starting with `find` and `ls` which offers here a nice way to display our filesystem from a given directory, `~/Documents` here.
```sh
find ~/Documents -type f -print0 | xargs -0 gls -l --time-style="+%Y-%m-%dT%H:%M:%S"
```
This gives something like:
```txt
-rw-r--r-- 1 dpilato staff 6148 2014-09-18T12:49:23 /Users/dpilato/Documents/Elasticsearch/tmp/es/.DS_Store
-rw-r--r-- 1 dpilato staff 110831 2013-01-28T08:47:27 /Users/dpilato/Documents/Elasticsearch/tmp/es/docs/Autoentreprise2012.pdf
-rw-r--r-- 1 dpilato staff 145244 2013-01-15T14:47:28 /Users/dpilato/Documents/Elasticsearch/tmp/es/meetups/Meetup.pdf
-rw-r--r-- 1 dpilato staff 11 2015-05-12T16:34:08 /Users/dpilato/Documents/Elasticsearch/tmp/es/test.txt
```
## Parse with logstash
Let's create a nice JSON document with logstash.
### Analyze current format
What is the format we have? Each line has two main parts separated by a space:
* metadata: `-rw-r--r-- 1 dpilato staff 11 2015-05-12T16:34:08`
* fullpath: `/Users/dpilato/Documents/Elasticsearch/tmp/es/test.txt`
metadata contains:
* `d` if path is a directory or `-` if file. We only print files so we have only `-`.
* `rwx` user rights: `r` for read, `w` for write and `x` for execution
* `r-x` group rights: same format as for user rights
* `r-x` other rights: same format as for user rights
* ` `: a blank
* `1`: number of links
* ` `: a blank
* `dpilato `: user name
* ` `: a blank
* `staff `: group name
* ` `: a blank
* ` 11`: file size. The text length depends on the biggest file we will find.
* ` `: a blank
* `2015-05-12T16:34:08`: last modification date.
### Grok it
I'm using [GROK Constructor](http://grokconstructor.appspot.com/) to incrementally build the grok pattern.
I'm ending up with:
```txt
[d-][r-][w-][x-][r-][w-][x-][r-][w-][x-] %{INT} %{USERNAME} %{USERNAME} %{SPACE}%{NUMBER} %{TIMESTAMP_ISO8601} %{GREEDYDATA}
```
Translating to [logstash grok filter](https://www.elastic.co/guide/en/logstash/current/plugins-filters-grok.html) and setting field names, it gives:
```txt
(?:d|-)(?<permission.user.read>[r-])(?<permission.user.write>[w-])(?<permission.user.execute>[x-])(?<permission.group.read>[r-])(?<permission.group.write>[w-])(?<permission.group.execute>[x-])(?<permission.other.read>[r-])(?<permission.other.write>[w-])(?<permission.other.execute>[x-]) %{INT:links:int} %{USERNAME:user} %{USERNAME:group} %{SPACE}%{NUMBER:size:int} %{TIMESTAMP_ISO8601:date} %{GREEDYDATA:name}
```
Let's test it!
I create a file `treemap.conf`:
```ruby
input { stdin {} }
filter {
grok {
match => { "message" => "(?:d|-)(?<permission.user.read>[r-])(?<permission.user.write>[w-])(?<permission.user.execute>[x-])(?<permission.group.read>[r-])(?<permission.group.write>[w-])(?<permission.group.execute>[x-])(?<permission.other.read>[r-])(?<permission.other.write>[w-])(?<permission.other.execute>[x-]) %{INT:links:int} %{USERNAME:user} %{USERNAME:group} %{SPACE}%{NUMBER:size:int} %{TIMESTAMP_ISO8601:date} %{GREEDYDATA:name}" }
}
}
output { stdout { codec => rubydebug } }
```
Then I launch logstash:
```sh
find ~/Documents -type f -print0 | xargs -0 gls -l --time-style="+%Y-%m-%dT%H:%M:%S" | bin/logstash -f treemap.conf
```
It gives for the same line we discussed before:
```ruby
"message" => "-rw-r--r-- 1 dpilato staff 11 2015-05-12T16:34:08 /Users/dpilato/Documents/Elasticsearch/tmp/es/test.txt",
"@version" => "1",
"@timestamp" => "2015-12-11T11:27:06.386Z",
"host" => "MacBook-Air-de-David.local",
"permission.user.read" => "r",
"permission.user.write" => "w",
"permission.user.execute" => "-",
"permission.group.read" => "r",
"permission.group.write" => "-",
"permission.group.execute" => "-",
"permission.other.read" => "r",
"permission.other.write" => "-",
"permission.other.execute" => "-",
"links" => 1,
"user" => "dpilato",
"group" => "staff",
"size" => 11,
"date" => "2015-05-12T16:34:08",
"name" => " /Users/dpilato/Documents/Elasticsearch/tmp/es/test.txt"
```
When I try to write permission properties to nested fields, I hit an [issue](https://github.com/logstash-plugins/logstash-filter-grok/issues/66). So I need to add some transformations.
### Fix permissions
As seen before, we want to write permissions to a nested data structure.
We can use the [mutate filter](https://www.elastic.co/guide/en/logstash/current/plugins-filters-mutate.html).
First, let's replace `rwx` values to `true` and `-` to `false`:
```ruby
mutate {
gsub => [
"permission.user.read", "r", "true",
"permission.user.read", "-", "false",
"permission.user.write", "w", "true",
"permission.user.write", "-", "false",
"permission.user.execute", "x", "true",
"permission.user.execute", "-", "false",
"permission.group.read", "r", "true",
"permission.group.read", "-", "false",
"permission.group.write", "w", "true",
"permission.group.write", "-", "false",
"permission.group.execute", "x", "true",
"permission.group.execute", "-", "false",
"permission.other.read", "r", "true",
"permission.other.read", "-", "false",
"permission.other.write", "w", "true",
"permission.other.write", "-", "false",
"permission.other.execute", "x", "true",
"permission.other.execute", "-", "false"
]
}
```
It now gives:
```ruby
"permission.user.read" => "true",
"permission.user.write" => "true",
"permission.user.execute" => "false",
"permission.group.read" => "true",
"permission.group.write" => "false",
"permission.group.execute" => "false",
"permission.other.read" => "true",
"permission.other.write" => "false",
"permission.other.execute" => "false",
```
We can mutate again those fields as actual booleans:
```ruby
mutate {
rename => { "permission.user.read" => "[permission][user][read]" }
rename => { "permission.user.write" => "[permission][user][write]" }
rename => { "permission.user.execute" => "[permission][user][execute]" }
rename => { "permission.group.read" => "[permission][group][read]" }
rename => { "permission.group.write" => "[permission][group][write]" }
rename => { "permission.group.execute" => "[permission][group][execute]" }
rename => { "permission.other.read" => "[permission][other][read]" }
rename => { "permission.other.write" => "[permission][other][write]" }
rename => { "permission.other.execute" => "[permission][other][execute]" }
}
```
It now gives:
```ruby
"permission" => {
"user" => {
"read" => "true",
"write" => "true",
"execute" => "false"
},
"group" => {
"read" => "true",
"write" => "false",
"execute" => "false"
},
"other" => {
"read" => "true",
"write" => "false",
"execute" => "false"
}
}
```
Let's now move to `booleans`. We can add that to the same latest mutate filter we just added:
```ruby
convert => { "[permission][user][read]" => "boolean" }
convert => { "[permission][user][write]" => "boolean" }
convert => { "[permission][user][execute]" => "boolean" }
convert => { "[permission][group][read]" => "boolean" }
convert => { "[permission][group][write]" => "boolean" }
convert => { "[permission][group][execute]" => "boolean" }
convert => { "[permission][other][read]" => "boolean" }
convert => { "[permission][other][write]" => "boolean" }
convert => { "[permission][other][execute]" => "boolean" }
```
Et voilà!
```ruby
"permission" => {
"user" => {
"read" => true,
"write" => true,
"execute" => false
},
"group" => {
"read" => true,
"write" => false,
"execute" => false
},
"other" => {
"read" => true,
"write" => false,
"execute" => false
}
}
```
### Date reconciliation
We have 2 fields related to a timestamp:
```ruby
"@timestamp" => "2015-12-11T11:27:06.386Z",
"date" => "2015-05-12T16:34:08"
```
The [date filter](https://www.elastic.co/guide/en/logstash/current/plugins-filters-date.html) will reconciliate the `@timestamp` field with the file date.
```ruby
date {
match => [ "date", "ISO8601" ]
remove_field => [ "date" ]
}
```
Timestamp is now correct:
```ruby
"@timestamp" => "2013-01-15T13:47:28.000Z",
```
### Cleanup
Some fields are now not needed anymore so we can simply remove them by adding a `remove_field` directive to our mutate filter:
```ruby
remove_field => [ "message", "host", "@version" ]
```
We are now all set to send the final data to elasticsearch!
```ruby
{
"@timestamp" => "2015-05-12T14:34:08.000Z",
"links" => 1,
"user" => "dpilato",
"group" => "staff",
"size" => 11,
"name" => "/Users/dpilato/Documents/Elasticsearch/tmp/es/test.txt",
"permission" => {
"user" => {
"read" => true,
"write" => true,
"execute" => false
},
"group" => {
"read" => true,
"write" => false,
"execute" => false
},
"other" => {
"read" => true,
"write" => false,
"execute" => false
}
}
}
```
## Send to elasticsearch
As usual we just have to connect the [elasticsearch output](https://www.elastic.co/guide/en/logstash/current/plugins-outputs-elasticsearch.html):
```ruby
elasticsearch {
index => "treemap-%{+YYYY.MM}"
document_type => "file"
}
```
### Use a template
Actually, we don't want elasticsearch decide for us what the mapping would be. So let's use a template and pass it to logstash:
```ruby
elasticsearch {
index => "treemap-%{+YYYY.MM}"
document_type => "file"
template => "treemap-template.json"
template_name => "treemap"
}
```
### Index settings
In `treemap-template.json`, we will define the following index settings:
```json
"index" : {
"refresh_interval" : "5s",
"number_of_shards" : 1,
"number_of_replicas" : 0
}
```
### Path Analyzer
Also, we need a [path tokenizer](https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-pathhierarchy-tokenizer.html) to analyze the fullpath, so we define an analyzer in index settings:
```json
"analysis": {
"analyzer": {
"path-analyzer": {
"type": "custom",
"tokenizer": "path-tokenizer"
}
},
"tokenizer": {
"path-tokenizer": {
"type": "path_hierarchy"
}
}
}
```
### Mapping
Let's disable the [_all feature](https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-all-field.html).
```json
"_all": {
"enabled": false
}
```
Also, we don't analyze string fields but for `name` field, we use our `path-analyzer`:
```json
"name" : {
"type" : "string",
"analyzer": "path-analyzer"
}
```
## Kibana
While I'm creating some visualizations, I'm also launching the full injection:
```sh
find ~/Documents -type f -print0 | xargs -0 gls -l --time-style="+%Y-%m-%dT%H:%M:%S" | bin/logstash -f treemap.conf
find ~/Applications -type f -print0 | xargs -0 gls -l --time-style="+%Y-%m-%dT%H:%M:%S" | bin/logstash -f treemap.conf
find ~/Desktop -type f -print0 | xargs -0 gls -l --time-style="+%Y-%m-%dT%H:%M:%S" | bin/logstash -f treemap.conf
find ~/Downloads -type f -print0 | xargs -0 gls -l --time-style="+%Y-%m-%dT%H:%M:%S" | bin/logstash -f treemap.conf
find ~/Dropbox -type f -print0 | xargs -0 gls -l --time-style="+%Y-%m-%dT%H:%M:%S" | bin/logstash -f treemap.conf
find ~/Movies -type f -print0 | xargs -0 gls -l --time-style="+%Y-%m-%dT%H:%M:%S" | bin/logstash -f treemap.conf
find ~/Music -type f -print0 | xargs -0 gls -l --time-style="+%Y-%m-%dT%H:%M:%S" | bin/logstash -f treemap.conf
find ~/Pictures -type f -print0 | xargs -0 gls -l --time-style="+%Y-%m-%dT%H:%M:%S" | bin/logstash -f treemap.conf
find ~/Public -type f -print0 | xargs -0 gls -l --time-style="+%Y-%m-%dT%H:%M:%S" | bin/logstash -f treemap.conf
```
And finally, I can build my visualization...
{{< figure src="kibana1.png" caption="My hard disk" >}}
Please don't tell to my boss that I have more music files than work files (in term of disk space)! :D
## Complete files
For the record (in case you want to replay all that)...
### Logstash
`treemap.conf` file:
```ruby
input { stdin {} }
filter {
grok {
match => { "message" => "(?:d|-)(?<permission.user.read>[r-])(?<permission.user.write>[w-])(?<permission.user.execute>[x-])(?<permission.group.read>[r-])(?<permission.group.write>[w-])(?<permission.group.execute>[x-])(?<permission.other.read>[r-])(?<permission.other.write>[w-])(?<permission.other.execute>[x-]) %{INT:links:int} %{USERNAME:user} %{USERNAME:group} %{SPACE}%{NUMBER:size:int} %{TIMESTAMP_ISO8601:date} %{GREEDYDATA:name}" }
}
mutate {
gsub => [
"permission.user.read", "r", "true",
"permission.user.read", "-", "false",
"permission.user.write", "w", "true",
"permission.user.write", "-", "false",
"permission.user.execute", "x", "true",
"permission.user.execute", "-", "false",
"permission.group.read", "r", "true",
"permission.group.read", "-", "false",
"permission.group.write", "w", "true",
"permission.group.write", "-", "false",
"permission.group.execute", "x", "true",
"permission.group.execute", "-", "false",
"permission.other.read", "r", "true",
"permission.other.read", "-", "false",
"permission.other.write", "w", "true",
"permission.other.write", "-", "false",
"permission.other.execute", "x", "true",
"permission.other.execute", "-", "false"
]
}
mutate {
rename => { "permission.user.read" => "[permission][user][read]" }
rename => { "permission.user.write" => "[permission][user][write]" }
rename => { "permission.user.execute" => "[permission][user][execute]" }
rename => { "permission.group.read" => "[permission][group][read]" }
rename => { "permission.group.write" => "[permission][group][write]" }
rename => { "permission.group.execute" => "[permission][group][execute]" }
rename => { "permission.other.read" => "[permission][other][read]" }
rename => { "permission.other.write" => "[permission][other][write]" }
rename => { "permission.other.execute" => "[permission][other][execute]" }
convert => { "[permission][user][read]" => "boolean" }
convert => { "[permission][user][write]" => "boolean" }
convert => { "[permission][user][execute]" => "boolean" }
convert => { "[permission][group][read]" => "boolean" }
convert => { "[permission][group][write]" => "boolean" }
convert => { "[permission][group][execute]" => "boolean" }
convert => { "[permission][other][read]" => "boolean" }
convert => { "[permission][other][write]" => "boolean" }
convert => { "[permission][other][execute]" => "boolean" }
remove_field => [ "message", "host", "@version" ]
}
date {
match => [ "date", "ISO8601" ]
remove_field => [ "date" ]
}
}
output {
stdout { codec => dots }
elasticsearch {
index => "treemap-%{+YYYY.MM}"
document_type => "file"
template => "treemap-template.json"
template_name => "treemap"
}
}
```
### Template
`treemap-template.json` file:
```json
{
"order" : 0,
"template" : "treemap-*",
"settings" : {
"index" : {
"refresh_interval" : "5s",
"number_of_shards" : 1,
"number_of_replicas" : 0
},
"analysis": {
"analyzer": {
"path-analyzer": {
"type": "custom",
"tokenizer": "path-tokenizer"
}
},
"tokenizer": {
"path-tokenizer": {
"type": "path_hierarchy"
}
}
}
},
"mappings" : {
"file" : {
"_all": {
"enabled": false
},
"properties" : {
"@timestamp" : {
"type" : "date",
"format" : "strict_date_optional_time||epoch_millis"
},
"group" : {
"type" : "string",
"index": "not_analyzed"
},
"links" : {
"type" : "long"
},
"name" : {
"type" : "string",
"analyzer": "path-analyzer"
},
"permission" : {
"properties" : {
"group" : {
"properties" : {
"execute" : {
"type" : "boolean"
},
"read" : {
"type" : "boolean"
},
"write" : {
"type" : "boolean"
}
}
},
"other" : {
"properties" : {
"execute" : {
"type" : "boolean"
},
"read" : {
"type" : "boolean"
},
"write" : {
"type" : "boolean"
}
}
},
"user" : {
"properties" : {
"execute" : {
"type" : "boolean"
},
"read" : {
"type" : "boolean"
},
"write" : {
"type" : "boolean"
}
}
}
}
},
"size" : {
"type" : "long"
},
"user" : {
"type" : "string",
"index": "not_analyzed"
}
}
}
},
"aliases" : {
"files" : {}
}
}
```
|
Java
|
UTF-8
| 521 | 2.015625 | 2 |
[] |
no_license
|
package com.eazytec.crm.dao;
import java.util.List;
import com.eazytec.crm.model.Custom;
import com.eazytec.dao.GenericDao;
import com.eazytec.util.PageBean;
public interface CustomDao extends GenericDao<Custom, String> {
List<Custom> getAllCustomList(String num,String name);
Custom saveCustom(Custom custom);
List<Custom> getCustomsByIds(List<String> customIds);
void deleteCustom(Custom custom);
int getAllCustomCount(PageBean<Custom> pageBean);
List<Custom> getAllCustom(PageBean<Custom> pageBean);
}
|
Java
|
UTF-8
| 3,046 | 2.21875 | 2 |
[
"BSD-3-Clause"
] |
permissive
|
package org.scut.ccnl.genomics.io.fasta;
import htsjdk.samtools.SAMException;
import htsjdk.samtools.SAMSequenceDictionary;
import htsjdk.samtools.reference.FastaSequenceIndex;
import htsjdk.samtools.reference.FastaSequenceIndexEntry;
import htsjdk.samtools.reference.ReferenceSequence;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.scut.ccnl.genomics.Arguments;
import org.scut.ccnl.genomics.io.HbaseDAO;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
/**
* Created by shedfree on 2017/3/24.
*/
public class HbaseFasta extends DistributedFastaSequenceFile implements Closeable {
public static int HBASE_LINE = 1000*DEFAULT_LINE_BASES;
public static String TABLE_NAME = "Reference";
public static String FAMILY_NAME = "attribute";
public static String COLUMN_NAME = "base";
public static HbaseFasta hbaseFasta = new HbaseFasta();
HbaseDAO hbaseDAO = new HbaseDAO();
//临时
FastaSequenceIndex index = new FastaSequenceIndex(new File(Arguments.FASTA_INDEX));
static {
hbaseFasta.setSequenceDictionary(getSequenceDictionary(Arguments.FASTA_DICT));
}
@Override
public void close() throws IOException {
hbaseDAO.close();
}
@Override
public ReferenceSequence getSubsequenceAt(String contig, long start, long stop) {
int length = (int)(stop - start + 1);
if(length<=0)
throw new SAMException(String.format("Malformed query; start point %d lies after end point %d",start,stop));
FastaSequenceIndexEntry indexEntry = index.getIndexEntry(contig);
if(stop > indexEntry.getSize())
throw new SAMException("Query asks for data past end of contig");
//前面的行数
long startline = ((start-1)/HBASE_LINE);
int startoffset = (int)(start-1)%HBASE_LINE;
long stopline = (stop-1)/HBASE_LINE + 1;
ResultScanner result = null;
StringBuilder sb = new StringBuilder();
try {
result = hbaseDAO.getResultScan(TABLE_NAME,HbaseDAO.getFastaRowkey(contig,startline),HbaseDAO.getFastaRowkey(contig,stopline),FAMILY_NAME,COLUMN_NAME);
for(Result r : result){
for(Cell cell :r.listCells()){
sb.append(new String(CellUtil.cloneValue(cell)));
}
}
} catch (IOException e) {
e.printStackTrace();
}finally {
result.close();
}
return new ReferenceSequence(contig,index.getIndexEntry(contig).getSequenceIndex(),sb.substring(startoffset,startoffset+length).getBytes());
}
@Override
public SAMSequenceDictionary getSequenceDictionary() {
return sequenceDictionary;
}
@Override
public ReferenceSequence getSequence(String contig) {
return getSubsequenceAt( contig, 1, (int)index.getIndexEntry(contig).getSize() );
}
}
|
C#
|
UTF-8
| 720 | 2.828125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
namespace Epic.TypeConverter
{
public static class TConverter
{
public static T ChangeType<T>(object value)
{
return (T)ChangeType(typeof(T), value);
}
public static object ChangeType(Type t, object value)
{
var tc = TypeDescriptor.GetConverter(t);
return tc.ConvertFrom(value);
}
public static void RegisterTypeConverter<T, TC>() where TC : System.ComponentModel.TypeConverter
{
TypeDescriptor.AddAttributes(typeof(T), new TypeConverterAttribute(typeof(TC)));
}
}
}
|
C
|
UTF-8
| 965 | 3.8125 | 4 |
[] |
no_license
|
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node* next;
};
void InsertionAtEnd(struct Node** head)
{
struct Node *temp=(struct Node*)malloc(sizeof(struct Node));
struct Node *temp1=(struct Node*)malloc(sizeof(struct Node));
temp->next=NULL;
temp1=*head;
printf("Enter Data : " );
scanf("%d",&temp->data);
if(*head==NULL)
*head=temp;
else
{
while(temp1->next!=NULL)
temp1=temp1->next;
temp1->next=temp;
}
}
void print(struct Node** head)
{
struct Node *temp=(struct Node*)malloc(sizeof(struct Node));
temp=*head;
while(temp->next!=NULL)
{
printf("%d\t",temp->data);
temp=temp->next;
}
}
int main()
{
struct Node *head=NULL;
int ch;
while(1)
{
printf("1.insert\n2.Print.");
scanf("%d",&ch);
switch (ch) {
case 1:
InsertionAtEnd(&head);
break;
case 2:
print(&head);
break;
case 3:
exit(0);
}
}
}
|
Java
|
UTF-8
| 1,095 | 2.234375 | 2 |
[
"BSD-3-Clause"
] |
permissive
|
public void testProcessDefinitionProperties(){
List<ProcessDefinition> processDefinitions=repositoryService.createProcessDefinitionQuery().orderByProcessDefinitionName().asc().orderByProcessDefinitionVersion().asc().orderByProcessDefinitionCategory().asc().list();
ProcessDefinition processDefinition=processDefinitions.get(0);
assertEquals("one",processDefinition.getKey());
assertEquals("One",processDefinition.getName());
assertTrue(processDefinition.getId().startsWith("one:1"));
assertEquals("Examples",processDefinition.getCategory());
processDefinition=processDefinitions.get(1);
assertEquals("one",processDefinition.getKey());
assertEquals("One",processDefinition.getName());
assertTrue(processDefinition.getId().startsWith("one:2"));
assertEquals("Examples",processDefinition.getCategory());
processDefinition=processDefinitions.get(2);
assertEquals("two",processDefinition.getKey());
assertEquals("Two",processDefinition.getName());
assertTrue(processDefinition.getId().startsWith("two:1"));
assertEquals("Examples2",processDefinition.getCategory());
}
|
JavaScript
|
UTF-8
| 226 | 3.21875 | 3 |
[] |
no_license
|
//Check to see if script is linked properly.
console.log("This script is linked properly!")
//Write your JS code here...
function changeColor(color) {
document.getElementById("colorDIV").style.backgroundColor = color;
}
|
TypeScript
|
UTF-8
| 4,426 | 3.90625 | 4 |
[] |
no_license
|
/**
* The string values here are only for the sake of debugging. Trying to tell which token is which
* given only an integer is hard.
*/
export enum TokenType {
BRACE_OPEN = "{",
BRACE_CLOSE = "}",
PARENTHESES_OPEN = "(",
PARENTHESES_CLOSE = ")",
SEMICOLON = ";",
/*
UNARY
*/
UNARY_BITWISE_COMPLEMENT = "~",
UNARY_LOGICAL_NEGATION = "!",
/*
BINARY OPERATORS
*/
MINUS = "-", //TODO for now this is subtraction and negation, is that gonna be weird?
BINARY_ADDITION = "+",
BINARY_MULTIPLICATION = "*",
BINARY_DIVISION = "/",
BINARY_MODULO = "%",
BINARY_AND = "&&",
BINARY_OR = "||",
BINARY_BITWISE_AND = "&",
BINARY_BITWISE_OR = "|",
BINARY_BITWISE_XOR = "^",
BINARY_BITWISE_SHIFT_LEFT = "<<",
BINARY_BITWISE_SHIFT_RIGHT = ">>",
BINARY_EQUAL = "==",
BINARY_NOT_EQUAL = "!=",
BINARY_LESS_THAN = "<",
BINARY_LESS_THAN_OR_EQUAL = "<=",
BINARY_GREATER_THAN = ">",
BINARY_GREATER_THAN_OR_EQUAL = ">=",
ASSIGNMENT = "=",
COMPOUND_ASSIGNMENT_ADDITION = "+=",
COMPOUND_ASSIGNMENT_SUBTRACTION = "-=",
COMPOUND_ASSIGNMENT_MULTIPLICATION = "*=",
COMPOUND_ASSIGNMENT_DIVISION = "/=",
COMPOUND_ASSIGNMENT_MODULO = "%=",
COMPOUND_ASSIGNMENT_BITSHIFT_LEFT = "<<=",
COMPOUND_ASSIGNMENT_BITSHIFT_RIGHT = ">>=",
COMPOUND_ASSIGNMENT_BITWISE_AND = "&=",
COMPOUND_ASSIGNMENT_BITWISE_OR = "|=",
COMPOUND_ASSIGNMENT_BITWISE_XOR = "^=",
COLON = ":",
QUESTION_MARK = "?",
COMMA = ",",
/*
KEYWORDS
*/
INT = "int",
RETURN = "return",
IF = "if",
ELSE = "else",
FOR = "for",
WHILE = "while",
DO = "do",
BREAK = "break",
CONTINUE = "continue",
/*
VARIABLE
*/
IDENTIFIER = "identifier",
LITERAL_INTEGER = "literal_integer"
}
/**
* This map helps us quickly tell if a given string is likely to be a constant Token.
*/
const CONSTANT_TOKENS = {
"{": TokenType.BRACE_OPEN,
"}": TokenType.BRACE_CLOSE,
"(": TokenType.PARENTHESES_OPEN,
")": TokenType.PARENTHESES_CLOSE,
";": TokenType.SEMICOLON,
"~": TokenType.UNARY_BITWISE_COMPLEMENT,
"!": TokenType.UNARY_LOGICAL_NEGATION,
"-": TokenType.MINUS,
"+": TokenType.BINARY_ADDITION,
"*": TokenType.BINARY_MULTIPLICATION,
"/": TokenType.BINARY_DIVISION,
"%": TokenType.BINARY_MODULO,
"&&": TokenType.BINARY_AND,
"||": TokenType.BINARY_OR,
"&": TokenType.BINARY_BITWISE_AND,
"|": TokenType.BINARY_BITWISE_OR,
"^": TokenType.BINARY_BITWISE_XOR,
"<<": TokenType.BINARY_BITWISE_SHIFT_LEFT,
">>": TokenType.BINARY_BITWISE_SHIFT_RIGHT,
"==": TokenType.BINARY_EQUAL,
"!=": TokenType.BINARY_NOT_EQUAL,
"<": TokenType.BINARY_LESS_THAN,
"<=": TokenType.BINARY_LESS_THAN_OR_EQUAL,
">": TokenType.BINARY_GREATER_THAN,
">=": TokenType.BINARY_GREATER_THAN_OR_EQUAL,
"=": TokenType.ASSIGNMENT,
"+=": TokenType.COMPOUND_ASSIGNMENT_ADDITION,
"-=": TokenType.COMPOUND_ASSIGNMENT_SUBTRACTION,
"*=": TokenType.COMPOUND_ASSIGNMENT_MULTIPLICATION,
"/=": TokenType.COMPOUND_ASSIGNMENT_DIVISION,
"%=": TokenType.COMPOUND_ASSIGNMENT_MODULO,
"<<=": TokenType.COMPOUND_ASSIGNMENT_BITSHIFT_LEFT,
">>=": TokenType.COMPOUND_ASSIGNMENT_BITSHIFT_RIGHT,
"&=": TokenType.COMPOUND_ASSIGNMENT_BITWISE_AND,
"|=": TokenType.COMPOUND_ASSIGNMENT_BITWISE_OR,
"^=": TokenType.COMPOUND_ASSIGNMENT_BITWISE_XOR,
":": TokenType.COLON,
"?": TokenType.QUESTION_MARK,
",": TokenType.COMMA,
"int": TokenType.INT,
"return": TokenType.RETURN,
"if": TokenType.IF,
"else": TokenType.ELSE,
"for": TokenType.FOR,
"while": TokenType.WHILE,
"do": TokenType.DO,
"break": TokenType.BREAK,
"continue": TokenType.CONTINUE
}
export class Token {
readonly type: TokenType
readonly value: string;
constructor(type: TokenType, value: string) {
this.type = type;
this.value = value;
}
static ofType(tokenType: TokenType): Token {
return new Token(tokenType, undefined);
}
static ofTypeAndValue(tokenType: TokenType, value: string): Token {
return new Token(tokenType, value);
}
static isConstantToken(value: string): Token {
if (value in CONSTANT_TOKENS) {
return Token.ofType(CONSTANT_TOKENS[value]);
}
}
}
|
Python
|
UTF-8
| 237 | 2.703125 | 3 |
[] |
no_license
|
from math import *
#from numpy.random import *
vida = int(input("digite vida"))
D1 = int(input("dado 1"))#randint(1, 20, size = 1)
D2 = int(input("dado 2"))#randint(1, 20, size = 1)
dano = (sqrt(5*D1))+(pi**(D2/3))
print(vida-int(dano))
|
PHP
|
UTF-8
| 606 | 2.765625 | 3 |
[] |
no_license
|
<?php
// Conecta ao banco de dados
mysql_connect('127.0.0.1', 'usuario', 'senha');
mysql_select_db('meusite');
// "Hoje" em formato SQL
$data = date('Y-m-d');
// Monta e executa uma consulta SQL
$sql = "SELECT `id`, `titulo`, `link` FROM `noticias` WHERE `ativa` = 1 AND `data` <= '". $data ."'";
$query = mysql_query($sql);
// Para cada resultado encontrado...
while ($noticia = mysql_fetch_assoc($query)) {
// Exibe um link com a notícia
echo '['. $noticia['titulo'] .']('. $noticia['link'] .')';
echo '';
} // fim while
// Total de notícias
echo 'Total de notícias: ' . mysql_num_rows($query);
|
C
|
UTF-8
| 5,848 | 3.390625 | 3 |
[] |
no_license
|
/*
We have 256MB RAM=256*1024*1024=268 697 600 bytes
Max nums count is 100 000 000= 4*100 000 000 = 400 000 000 bytes max
Which means that we can store half the file in RAM
*/
#include <stdbool.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <err.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <stdint.h>
#include <string.h>
int cmp(const void* n1, const void* n2) {
return ( *((uint32_t*)n1) - *((uint32_t*)n2) );
}
int createTmpFile(int suffix,char* name_buf) { //Returns a file descriptor used to read and write from/to the file
int fname_size=sprintf(name_buf,"tmp_%d_%d",getpid(),suffix);
name_buf[fname_size]='\0';
return open(name_buf,O_RDWR|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR);
}
int main(int argc, char* argv[]) {
if(argc!=2) {
errx(1,"Wrong number of args. Expected 1, got %d",argc-1);
}
struct stat st;
if(stat(argv[1],&st)==-1) {
err(2,"Cannot stat %s",argv[1]);
}
if(st.st_size%sizeof(uint32_t)!=0) {
errx(3,"%s has wrong size",argv[1]);
}
uint64_t file_len=st.st_size;
uint64_t numbersCount=file_len/sizeof(uint32_t);
uint64_t firstHalfNumbers=numbersCount/2;
uint64_t secondHalfNumbers=numbersCount-firstHalfNumbers;
uint32_t* data=(uint32_t*)malloc(firstHalfNumbers*sizeof(uint32_t));
int fd=open(argv[1],O_RDONLY);
if(fd==-1) {
const int olderrno=errno;
free(data);
errno=olderrno;
err(4,"Could not open file %s",argv[1]);
}
int readBytes=read(fd,data,firstHalfNumbers*sizeof(uint32_t));
if(readBytes==-1) {
const int olderrno=errno;
free(data);
close(fd);
errno=olderrno;
err(5,"Could not read from file %s",argv[1]);
}
qsort(data,firstHalfNumbers,sizeof(uint32_t),cmp);
char temp_name1[128];
int temp_fd1=createTmpFile(1,temp_name1);
if(temp_fd1==-1) {
const int olderrno=errno;
free(data);
close(fd);
errno=olderrno;
err(6,"Cannot create a tmp file(1)");
}
int writtenBytes=write(temp_fd1,data,firstHalfNumbers*sizeof(uint32_t));
if(writtenBytes==-1) {
const int olderrno=errno;
free(data);
close(fd);
close(temp_fd1);
errno=olderrno;
err(7,"Could not write to tmp file(1)");
}
free(data);
uint32_t* rest=(uint32_t*)malloc(secondHalfNumbers*sizeof(uint32_t));
readBytes=read(fd,rest,secondHalfNumbers*sizeof(uint32_t));
if(readBytes==-1) {
const int olderrno=errno;
free(rest);
close(fd);
close(temp_fd1);
errno=olderrno;
err(5,"Could not read from file %s",argv[1]);
}
close(fd);//We're finished with reading the file argv[1], so we can safely close this fd
qsort(rest,secondHalfNumbers,sizeof(uint32_t),cmp);
char temp_name2[128];
int temp_fd2=createTmpFile(2,temp_name2);
if(temp_fd2==-1) {
const int olderrno=errno;
free(rest);
close(temp_fd1);
errno=olderrno;
err(6,"Cannot create a tmp file(2)");
}
writtenBytes=write(temp_fd2,rest,secondHalfNumbers*sizeof(uint32_t));
if(writtenBytes==-1) {
const int olderrno=errno;
free(rest);
close(temp_fd1);
close(temp_fd2);
errno=olderrno;
err(7,"Could not write to tmp file(2)");
}
free(rest);
//Time to merge the files
const char* output_file="pesho.txt";
int fd_o=open(output_file,O_WRONLY|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR);
if(fd_o==-1) {
const int olderrno=errno;
close(temp_fd1);
close(temp_fd2);
errno=olderrno;
err(10,"Could not create an output file");
}
if(lseek(temp_fd1,0,SEEK_SET)==-1) {
const int olderrno=errno;
close(fd_o);
close(temp_fd1);
close(temp_fd2);
errno=olderrno;
err(8,"Could not lseek tmp file(1)");
}
if(lseek(temp_fd2,0,SEEK_SET)==-1) {
const int olderrno=errno;
close(fd_o);
close(temp_fd1);
close(temp_fd2);
errno=olderrno;
err(8,"Could not lseek tmp file(2)");
}
uint64_t counter1=0,counter2=0;
uint32_t n1;
uint32_t n2;
while(counter1<firstHalfNumbers&&counter2<secondHalfNumbers) {
if(read(temp_fd1,&n1,sizeof(n1))==-1) {
const int olderrno=errno;
close(fd_o);
close(temp_fd1);
close(temp_fd2);
errno=olderrno;
err(11,"Could not read from tmp file(1)");
}
if(read(temp_fd2,&n2,sizeof(n2))==-1) {
const int olderrno=errno;
close(fd_o);
close(temp_fd1);
close(temp_fd2);
errno=olderrno;
err(11,"Could not read from tmp file(1)");
}
if(n1<n2) {
counter1++;
write(fd_o,&n1,sizeof(n1));
if(lseek(temp_fd2,-1*sizeof(uint32_t),SEEK_CUR)==-1) {
const int olderrno=errno;
close(fd_o);
close(temp_fd1);
close(temp_fd2);
errno=olderrno;
err(12,"Could not lseek tmp file(1)");
}
} else {
counter2++;
write(fd_o,&n2,sizeof(n2));
if(lseek(temp_fd1,-1*sizeof(uint32_t),SEEK_CUR)==-1) {
const int olderrno=errno;
close(fd_o);
close(temp_fd1);
close(temp_fd2);
errno=olderrno;
err(12,"Could not lseek tmp file(2)");
}
}
}
while(counter1<firstHalfNumbers) {
int readBytes=read(temp_fd1,&n1,sizeof(n1));
if(readBytes==-1) {
const int olderrno=errno;
close(fd_o);
close(temp_fd1);
close(temp_fd2);
errno=olderrno;
err(11,"Could not read from tmp file(1)");
}
counter1++;
if(write(fd_o,&n1,sizeof(n1))!=sizeof(n1)) {
const int olderrno=errno;
close(fd_o);
close(temp_fd1);
close(temp_fd2);
errno=olderrno;
err(12,"Could not write to %s",output_file);
}
}
while(counter2<secondHalfNumbers) {
int readBytes=read(temp_fd2,&n2,sizeof(n2));
if(readBytes==-1) {
const int olderrno=errno;
close(fd_o);
close(temp_fd1);
close(temp_fd2);
errno=olderrno;
err(11,"Could not read from tmp file(1)");
}
counter2++;
if(write(fd_o,&n2,sizeof(n2))!=sizeof(n2)) {
const int olderrno=errno;
close(fd_o);
close(temp_fd1);
close(temp_fd2);
errno=olderrno;
err(12,"Could not write to %s",output_file);
}
}
close(fd_o);
close(temp_fd1);
close(temp_fd2);
unlink(temp_name1);
unlink(temp_name2);
exit(0);
}
|
C#
|
UTF-8
| 3,147 | 2.828125 | 3 |
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HighScoreController : MonoBehaviour {
[SerializeField] Text[] highScoreList;
[SerializeField] string readHighScore;
[SerializeField] string highScoreKey = "HighScore";
[SerializeField] string highScoreNameKey = "HighScoreName";
GameController gameController1;
[SerializeField] int[] highScores = new int[10];
string firstPlay;
public void Start()
{
//if statement to write "No Score", and "0" to highscore name and value.
//simply to populate values and add polish
//checks playerprefs for an existig "FirstPlay" string
if (PlayerPrefs.GetString("FirstPlay") != "No")
{
//loops through the length of the highscores(10)
for (int it = 0; it < highScores.Length; it++)
{
//retrieves the highscore at each position through a unique key
highScoreKey = "HighScore"+(it);
//sets each unique key for numbers, to 0
PlayerPrefs.SetInt (highScoreKey, 0);
}
//loops through the length of the highscores(10)
for (int it = 0; it < highScores.Length; it++)
{
//retrieves the highscore at each position through a unique key
highScoreNameKey = "HighScoreName"+(it);
//sets each unique key for names, to 0
PlayerPrefs.SetString (highScoreNameKey,"No Score");
}
//sets the prefs to No, so this if check has been used
PlayerPrefs.SetString("FirstPlay","No");
}
//loops through the length of the high scores
for (int it = 0; it < highScoreList.Length; it++)
{
//reads the highscore balue of each unique key
readHighScore = PlayerPrefs.GetInt (highScoreKey + it).ToString();
//writes to an array Text value,the name and value of the players score at that position
highScoreList [it].text = PlayerPrefs.GetString("HighScoreName" + it) + " : " + readHighScore;
}
}
public void Update()
{
if (Input.GetKeyDown ("="))
{
Debug.Log ("Scores reset");
//loops through the length of the highscores(10)
for (int it = 0; it < highScores.Length; it++)
{
//retrieves the highscore at each position through a unique key
highScoreKey = "HighScore"+(it);
//sets each unique key for numbers, to 0
PlayerPrefs.SetInt (highScoreKey, 0);
}
//loops through the length of the highscores(10)
for (int it = 0; it < highScores.Length; it++)
{
//retrieves the highscore at each position through a unique key
highScoreNameKey = "HighScoreName"+(it);
//sets each unique key for names, to 0
PlayerPrefs.SetString (highScoreNameKey,"No Score");
}
//sets the prefs to No, so this if check has been used
PlayerPrefs.SetString("FirstPlay","No");
//loops through the length of the high scores
for (int it = 0; it < highScoreList.Length; it++)
{
//reads the highscore balue of each unique key
readHighScore = PlayerPrefs.GetInt (highScoreKey + it).ToString();
//writes to an array Text value,the name and value of the players score at that position
highScoreList [it].text = PlayerPrefs.GetString("HighScoreName" + it) + " : " + readHighScore;
}
}
}
}
|
PHP
|
UTF-8
| 6,849 | 2.515625 | 3 |
[] |
no_license
|
<?php
// kernel-functions.inc.php
// functions and classes scriptData to kcm, payroll, gateway, etc
function kernel_array_concat($array, $prefix, $suffix) {
$newArray = array();
foreach( $array as $value ) {
$newArray[] = $prefix . $value . $suffix;
}
return $newArray;
}
function krnLib_assert($isTrue, $error, $line=NULL) {
if ( !$isTrue) {
if ( $line!=NULL) {
$error = ' Notify Jared - Assert Error - ' . $error . ' - ' . $line;
}
print '<br><hr>Programming (assert) Error:<br><br>'.$error.'<br><hr><br>';
exit;
}
}
function krnLib_getSchoolName( $schoolName, $uniquifier=NULL ) {
if ( is_array($schoolName) ) {
$uniquifier = $schoolName['pPr:SchoolNameUniquifier'];
$schoolName = $schoolName['pSc:NameShort'];
}
if ( !empty($uniquifier) ) {
$schoolName.= ' ' . $uniquifier;
}
return $schoolName;
}
function kernel_regMakeLinkButton( $label, $value ) {
// modified from rc_regMakeLinkButton
$html = "<button name='submit' type='submit' value='{$value}'>{$label}</button>";
//-- $target = '';
//-- $suffix = '';
//-- if ($inNewWindow) {
//-- $target = " target='_blank'";
//-- $suffix = "..."; //!!! really want an icon?
//-- }
//-- $classes = $buttonClasses ? " class='{$buttonClasses}'" : "";
//-- $href = str_replace( '&', '&', $href );
//-- $urlParts = parse_url( $href );
//-- $formClass = "linkButton";
//-- $html = '';
//-- //$html = "<form class='{$formClass}' action='{$urlParts['path']}' method='get'{$target}>";
//-- // $html .= "<div>";
//-- if (isset( $urlParts['query'] )) {
//-- $params = array();
//-- parse_str( $urlParts['query'], $params );
//-- foreach( $params as $name => $val ) {
//-- $html .= "<input type='hidden' name='{$name}' value='{$val}'>";
//-- }
//-- }
//-- $html .= "<button type='submit'{$classes}>{$label}{$suffix}</button>";
//-- // $html .= "</div>";
//-- //$html .= "</form>";
return $html;
}
function kernel_processBannerSubmits( $appGlobals, $chain ) {
if ($chain->chn_submit[0]=='banner-logout') {
// need to logout -- is this the best way???
unset( $_SESSION['Admin'] );
unset( $_SESSION['Post']['Admin'] );
$url = rc_reconstructURL();
rc_redirectToURL($url);
}
if ($chain->chn_submit[0]=='banner-profile') {
$emitter = new kcmKernel_emitter($appGlobals, NULL);
$emitter->emit_options->emtSetTitle('Edit Profile');
$emitter->zone_htmlHead();
$emitter->zone_body_start($chain, NULL);
$emitter->krnEmit_banner_output($appGlobals, $emitter ); // '', 'profile'); //??????????
$emitter->zone_start('zone-content-scrollable theme-panel');
rc_showAdminProfilePage('../../');
$emitter->zone_end();
$emitter->zone_body_end();
// need to logout -- is this the best way???
//$url = rc_reconstructURL();
//rc_redirectToURL($url);
}
}
// function krnLib_getFieldList($fieldArray) {
// $sql = '';
// foreach ($fieldArray as &$field) {
// if ( strpos($field,'`')===FALSE )
// $field= '`'.$field.'`';
// }
// }
function krnLib_getAuthorizationDateRange($dateOverride = NULL) {
//????? future enhancement - in calling sql check date to only authourize first week or two of previous/next semester's event
//????? so multiple semesters for an event only happens on the first/last week of viewing that event
//????? otherwise can access other semesters of event using roster access table
$dateToday = empty($dateOverride) ? date_create( "today" ) : date_create( $dateOverride );
while (date_format( $dateToday, 'N' ) != 1) { //1=Monday
date_modify( $dateToday, '-1 day' );
}
$todaySql = date_format($dateToday,'Y-m-d');
$monthDay = substr($todaySql,5,5);;
$year = substr($todaySql,0,4);
if ($monthDay < '02-05') {
$dateStart = date_create( ($year-1) . '-11-15' );
}
else {
$beforeDays = '-14';
$dateStart = clone $dateToday;
date_modify( $dateStart, $beforeDays . ' day' );
}
if ($monthDay > '11-15') {
$dateEnd = date_create( ($year+1) . '-02-05' );
}
else {
$afterDays ='+21'; ;
$dateEnd = clone $dateToday;
date_modify( $dateEnd, $afterDays . ' day' );
}
$pStartDate = date_format( $dateStart, 'Y-m-d' );
$pEndDate = date_format( $dateEnd, 'Y-m-d' );
return array ('start'=>$pStartDate,'end'=>$pEndDate);
}
function kcm_fetch_selectMap_staff($appGlobals, $isCombo = FALSE ) {
$staffSelect = $isCombo ? array(0=>'None (Select a Staff member)') : array();
$query = new draff_database_query;
$query->rsmDbq_selectStart();
$query->rsmDbq_selectAddColumns('dbRecord_staff');
$query->rsmDbq_add( "FROM `st:staff`");
$query->rsmDbq_add( "WHERE `sSt:HiddenStatus`='0'");
$query->rsmDbq_add( "ORDER BY `sSt:FirstName`, `sSt:LastName`");
$result = $appGlobals->gb_pdo->rsmDbe_executeQuery($query);
$dj = new draff_database_joiner;
foreach ($result as $row) {
$staffId = $row['sSt:StaffId'];
$staffSelect[$staffId] = $row['sSt:FirstName'] . ' ' . $row['sSt:LastName'];
}
return $staffSelect;
}
function krnEmit_reportTitleRow($appEmitter, $title, $colSpan) { //?? moved from kernel emitter
$s1 = '<div class="draff-report-top-left"></div>';
$s2 = '<div class="draff-report-top-middle">'.$title.'</div>';
$s3 = '<div class="draff-report-top-right">'.draff_dateTimeAsString(rc_getNow(),'M j, Y' ).'</div>';
$appEmitter->row_start();
$appEmitter->cell_block($s1 . $s2 . $s3 ,'draff-report-top', 'colspan="'.$colSpan.'"');
$appEmitter->row_end();
}
function krnEmit_recordEditTitleRow($appEmitter,$title, $colSpan) { //?? moved from kernel emitter
// used once in roster-results-games
// $s1 = '<div class="draff-report-top-left"></div>';
$s2 = '<div class="draff-report-top-middle">'.$title.'</div>';
// $s3 = '<div class="draff-report-top-right">'.draff_dateTimeAsString(rc_getNow(),'M j, Y' ).'</div>';
$appEmitter->row_start();
$appEmitter->cell_block($title ,'draff-edit-top', 'colspan="'.$colSpan.'"');
$appEmitter->row_end();
}
function krnEmit_button_editSubmit($caption, $value) { //?? moved from kernel emitter
// used twice in set security
// submit for editing - so all are consistent - (design choices:Edit button - caption - caption button that looks like link)
//?????????? if report should not be coded as button ??????????????????????
//$cellClass = empty($cellClass) ? '' : ' class="'.$class.'"';
return '<button type="submit" class="kcmKrn-button-editLink" name="submit" value="'.$value.'">' . $caption . '</button>';
}
?>
|
Java
|
UTF-8
| 5,259 | 2.15625 | 2 |
[
"BSD-3-Clause"
] |
permissive
|
package org.firstinspires.ftc.teamcode.OpModes.Testing;
import com.acmerobotics.roadrunner.geometry.Pose2d;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import org.firstinspires.ftc.robotcore.external.hardware.camera.WebcamName;
import org.firstinspires.ftc.teamcode.Hardware.Robot;
import org.firstinspires.ftc.teamcode.Hardware.RobotValues;
import org.firstinspires.ftc.teamcode.Hardware.Spotter;
import org.firstinspires.ftc.teamcode.Movement.Location;
import org.openftc.easyopencv.OpenCvCamera;
import org.openftc.easyopencv.OpenCvCameraFactory;
import org.openftc.easyopencv.OpenCvCameraRotation;
@Disabled
@Autonomous(name = "One Stone0 Auto PROB NO WORKY")
public class OneStone extends LinearOpMode {
public static int skystoneSpot = 1;
public Robot r;
private double skystone2Pos = -15;
private OpenCvCamera webcam;
private Spotter spot;
private boolean isRed;
private int sidemult;
private String webcamName = "Webcam 1";
@Override
public void runOpMode() throws InterruptedException {
msStuckDetectStop = 8000;
r = new Robot(telemetry, new Location(), hardwareMap);
while (!isStopRequested() && !gamepad1.x) {
telemetry.addData("press a to toggle side", " x to save and move on");
telemetry.addData("Side:", isRed ? "red" : "blue");
if (gamepad1.a) {
isRed = !isRed;
}
webcamName = isRed ? "Webcam 1" : "Webcam 2";
telemetry.update();
}
if (isStopRequested()) {
stop();
}
if (isRed) {
sidemult = 1;
} else {
sidemult = -1;
}
int cameraMonitorViewId = hardwareMap.appContext.getResources().getIdentifier("cameraMonitorViewId", "id", hardwareMap.appContext.getPackageName());
webcam = OpenCvCameraFactory.getInstance().createWebcam(hardwareMap.get(WebcamName.class, webcamName), cameraMonitorViewId);
webcam.openCameraDevice();
spot = new Spotter();
webcam.setPipeline(spot);
webcam.startStreaming(320, 240, OpenCvCameraRotation.UPRIGHT);
while (!isStarted() && !isStopRequested()) {
if (isStopRequested()) {
webcam.closeCameraDevice();
break;
}
telemetry.addData("Skystone Spot: ", skystoneSpot);
telemetry.addData("skystone x", spot.best);
telemetry.update();
}
webcam.closeCameraDevice();
if (!isStopRequested()) {
r.chainbar.goUpBit();
if (skystoneSpot == 3) {
telemetry.addData("thing", "3")
;
telemetry.update();
if (isRed) {
r.rrBot.followTrajectorySync(r.rrBot.trajectoryBuilder().forward(5 * 25.4).build());
} else
r.rrBot.followTrajectorySync(r.rrBot.trajectoryBuilder().back(7 * 25.4).build());
skystone2Pos = -9;
} else if (skystoneSpot == 2) {
telemetry.addData("thing", "2");
telemetry.update();
r.rrBot.followTrajectorySync(r.rrBot.trajectoryBuilder().back(4 * 25.4).build());
} else if (skystoneSpot == 1) {
telemetry.addData("thing", "1")
;
telemetry.update();
if (isRed) {
r.rrBot.followTrajectorySync(r.rrBot.trajectoryBuilder().back(7 * 25.4).build());
} else {
r.rrBot.followTrajectorySync(r.rrBot.trajectoryBuilder().forward(5 * 25.4).build());
}
skystone2Pos = -24;
}
r.turnSync(Math.toRadians(RobotValues.heading * sidemult));
r.intake.turbo();
Thread.sleep(250);
r.intake.intake(1);
r.chainbar.autoHold();
r.rrBot.followTrajectorySync(r.rrBot.fastTrajectoryBuilder().forward((24) * 25.4).build());
r.rrBot.followTrajectorySync(r.rrBot.trajectoryBuilder().forward(8 * 25.4).build());
Thread.sleep(500);
r.rrBot.followTrajectorySync(r.rrBot.fastTrajectoryBuilder().reverse().splineTo(new Pose2d(-24 * 25.4, sidemult * -24 * 25.4, 0)).reverse().back(25 * 25.4).build());
// r.intake.intake(0);
// r.Chainbar.goDown();
// Thread.sleep(500);
// r.Chainbar.grabClose();
// Thread.sleep(250);
// r.Chainbar.goUpAll();
//
// Thread.sleep(5000);
// r.Chainbar.grabOpen();
//
// r.rrBot.followTrajectorySync(r.rrBot.fastTrajectoryBuilder().forward(5 * 25.4).splineTo(new Pose2d(skystone2Pos * 25.4, -24 * 25.4, Math.toRadians(-55))).build());
// r.rrBot.followTrajectorySync(r.rrBot.trajectoryBuilder().forward(12 * 25.4).build());
// r.rrBot.followTrajectorySync(r.rrBot.fastTrajectoryBuilder().reverse().splineTo(new Pose2d(-24 * 25.4, -24 * 25.4, 0)).reverse().back(25 * 25.4).build());
r.rrBot.followTrajectorySync(r.rrBot.trajectoryBuilder().forward(5 * 25.4).build());
}
}
}
|
C#
|
UTF-8
| 2,275 | 2.546875 | 3 |
[] |
no_license
|
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace PrimeAssault.Views
{
/// <summary>
/// The Main PrimeAssault Page
/// </summary>
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class BattlePage: ContentPage
{
/// <summary>
/// Constructor
/// </summary>
public BattlePage ()
{
InitializeComponent ();
}
/// <summary>
/// Attack Action
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void AttackButton_Clicked(object sender, EventArgs e)
{
DisplayAlert("SU", "Attack !!!", "OK");
}
/// <summary>
/// Battle Over
/// Battle Over button shows when all characters are dead
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public async void RoundOverButton_Clicked(object sender, EventArgs e)
{
await Navigation.PushModalAsync(new RoundOverPage());
}
/// <summary>
/// Battle Over
/// Battle Over button shows when all characters are dead
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public async void NewRoundButton_Clicked(object sender, EventArgs e)
{
await Navigation.PushModalAsync(new NewRoundPage());
}
/// <summary>
/// Battle Over
/// Battle Over button shows when all characters are dead
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public async void BattleOverButton_Clicked(object sender, EventArgs e)
{
await Navigation.PushModalAsync(new ScorePage());
}
/// <summary>
/// Battle Over, so Exit Button
/// Need to show this for the user to click on.
/// The Quit does a prompt, exit just exits
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public async void ExitButton_Clicked(object sender, EventArgs e)
{
await Navigation.PopModalAsync();
}
/// <summary>
/// Quit the Battle
///
/// Quitting out
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public async void QuitButton_Clicked(object sender, EventArgs e)
{
bool answer = await DisplayAlert("Battle", "Are you sure you want to Quit?", "Yes", "No");
if (answer)
{
await Navigation.PopModalAsync();
}
}
}
}
|
C#
|
UTF-8
| 2,448 | 3.25 | 3 |
[] |
no_license
|
using System;
namespace OnlineChess
{
public class CreateGame
{
public void CreatePlayer(GameObject[] player, int N)
{
for (int i = 0; i < N; i++)
{
player[i] = new GameObject();
}
for (int i = 0; i < N; i++)
{
var input = Console.ReadLine();
var inputArray = input.Split(' ');
player[i].R = Convert.ToInt32(inputArray[0]);
player[i].Min = Convert.ToInt32(inputArray[1]);
player[i].Max = Convert.ToInt32(inputArray[2]);
player[i].Time = Convert.ToInt32(inputArray[3]);
player[i].IsRated = inputArray[4];
player[i].Color = inputArray[5];
}
}
private bool MatchColor(int i, int j, GameObject[] player)
{
if (player[i].Color == "random" && player[j].Color == "random" ||
player[i].Color == "white" && player[j].Color == "black" ||
player[i].Color == "black" && player[j].Color == "white")
return true;
return false;
}
public bool MatchExist(int i, int j, GameObject[] player)
{
if (player[i].R >= player[j].Min
&& player[i].R <= player[j].Max
&& player[i].IsRated == player[j].IsRated
&& player[i].Time == player[j].Time
&& MatchColor(i, j, player))
return true;
return false;
}
public void MatchPlayers(GameObject[] player, string[] output, int N)
{
output[0] = "wait";
for (int i = 1; i < N; i++)
{
for (int j = 0; j < i; j++)
{
if (MatchExist(i, j, player))
{
if (!IsElementInOutput(output, j))
{
output[i] = (j + 1).ToString();
break;
}
}
output[i] = "wait";
}
}
}
public bool IsElementInOutput(string[] output, int j)
{
foreach (var e in output)
{
if (Convert.ToString(j + 1) == e)
return true;
}
return false;
}
}
}
|
TypeScript
|
UTF-8
| 749 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
import { BaseExtensionOptions } from '@remirror/core';
export interface MulticursorExtensionOptions extends BaseExtensionOptions {
/**
* This determines the character that will be used to represent the cursor.
*
* @default '|'
*/
cursor?: string;
/**
* The class name of the decoration span used to mark the blinking cursor
*
* @default 'multicursor-blinking'
*/
cursorClassName?: string;
/**
* The color of the cursor
*
* @default 'black'
*/
cursorColor?: string;
/**
* The activation key which sets a keypress as
*
* @default 'metaKey'
*/
clickActivationKey?: 'altKey' | 'metaKey' | 'ctrlKey';
}
export type MulticursorExtensionCommands = 'addMulticursor' | 'toggleMulticursor';
|
Markdown
|
UTF-8
| 15,702 | 3.359375 | 3 |
[
"MIT"
] |
permissive
|
# Latex-in-Academic-Writing
记录Latex在学术论文写作中的的常见问题和解决方案,并附有详细代码
## latex基本知识
- 这部分的参考链接
- https://liam.page/2014/09/08/latex-introduction/
- http://liuchengxu.org/blog-cn/posts/quick-latex/
- 本质其实就是一种类似html,markdown的标记语言,只不过相比起来所具有的标记更加多样和复杂而已。
- 或者还可以再拿代码中的宏定义来理解,把一些特定的序列定义为某些操作,某些意思,方便后面的使用。这种特定的序列在latex就叫做是控制序列
- 所有的的标记符号,或者说控制序列,都是以反斜杠 "\"开始,如\ref。。它们不被输出,但是他们会影响输出文档的效果。
- 控制序列可以在文中的任何一个位置加入,而不仅仅只是开头
- 作用范围
- 刚刚提到latex本质是一种标记语言,用来随时随地的控制文档的文字排版等效果,那么怎么选择我要控制的文字呢?
- 一个是\begin 和\end 。这两个控制序列以及他们中间的内容被称为「环境」;它们之后的第一个必要参数总是一致的,被称为环境名。如\begin{eqution} \end{eqution}. 就是一个公式环境,中间你输入的公式就会被辅以某种特定的排版。具体要看不同的环境的作用
另一个则是{},把需要标记的文本框起来,而文字的效果则是看具体的操作。如\textbf{a} 就是把a加粗。
- 其他类似的还有$$等,都是类似的,把需要标记的语言框起来就行。
- 编译器和编辑器
- 刚刚提到latex 本质是一种标记语言,那么就肯定存在一个映射关系,记录着什么对应什么。而latex编译器就是记录这个映射的关系的东西。所以无论是你在那写的latex文档,txt,word,等等,只要你利用编译器编译,都可以得到编译之后的规范的文本文档。而你写东西的地方,被称为编辑器。
- 最开始编译器和编辑器是分开的,后来为了方便用户使用,就合在了一起,叫做IDE发行,比如textstuido。但是实际上过程还是两个过程,latex文本的编辑和编译生成规范文本。就好像你写程序时候的 写代码的过程和编译代码的过程,本质是两个过程,但是你确实在同一个应用上实现的。
- 开发工具
- textstudio
- overleaf
- 推荐使用这个。这是一个网页工具,任何时候只要又网络就可以接入。当然坏处就是没网就不能用。
- 另外去这个不需要配置环境,尤其是中文的开发环境,直接进行开发就行,最大化的降低了用户在编写文档之外其他的精力开销。而其他的工具光是环境可能就需要你去配置很久。
- 最后,这是一个多端的工具,win linux都可以,而其他的工具往往只在win或者linux环境某一个环境下工作,换一个工作环境就要重新配置一个开发工具非常麻烦
- 自带一个历史回溯,甚至不需要你去进行git管理。
- 自带许多模板,不需要自己再去为模板发愁
- 当然,最重要的还是它免费
- 本教程的相关代码也会通过overleaf的方式进行展示。
- overleaf 编译器
- 点击左上角的Meau 或者中文的菜单选项可以配置
- 默认是pdfLatex,如果要编译中文可以换成XeLatex
- 导言区
- 从 \documentclass{article} 开始到 \begin{document} 之前的部
分被称为导言区。你可以将导言区理解为是对整篇文档进行设置的区域——在导言区出现的控制序列,往往会影响整篇文档的格式
- 宏包
- 所谓宏包,就是一系列控制序列的合集。这些控制序列太常用,以至于人们会觉得每次将他们写在导言区太过繁琐,于是将他们打包放在同一个文件中,成为所谓的宏包(台湾方面称之为「巨集套件」)。\usepackage{} 可以用来调用宏包。
- 文档正文
- 也就是\begin{document}到\end{document}之间的内容。只有在 document 环境中的内容,才会被正常输出到文档中去或是作为控制序列对文档产生影响。也就是写作文档正文中的各种标记才会起作用
- latex文档结构
- 导言区和文档正文
- 导言区里面控制正文的大体格式,这时候可以使用宏包,也可以自己定义。然后正文书写内容
- 模板文件
- .sty 和.cls文件。
- 模板文件就有点类似于我们写报告常用的报告模板,格式已经订好了,然后为了方便别人使用,直接把模板,也就是格式文件给他们,然后直接利用这个,进行编辑就好了。而一般格式文件就是.sty 和.cls文件。
- 使用的方式,也就是把格式文件放在目录下,在导言区里面引用它们的东西就好了
- latex 常用操作笔记
- https://mirrors.tuna.tsinghua.edu.cn/CTAN/info/lshort/chinese/lshort-zh-cn.pdf
## latex 写作问题
### 代码参考
- 模板链接: https://www.overleaf.com/read/qbckwmrjjgqm 后面所有的操作的代码也都会放在这里面。读者只能阅读,不能修改。
### overleaf 工具
- 打开 https://www.overleaf.com 注册账户
- 首页的各个分类标签介绍: https://blog.csdn.net/xovee/article/details/100734370
- 点击 New Project 可以创建自己的工程项目。点击按钮后弹出的列的最下面一个选项,点击之后就可以自己搜索各种所需的模板,比如搜索 CVPR 打开搜索的第一个结果 CVPR 2018 Template(不是这个也行,估计再过几年就不是这个了,但是问题不大,打开一个就可以)。通过模板的内容,你就能知道绝大部分的基础latex操作如:加粗,文献引用,等等。
- 模板链接: https://www.overleaf.com/read/qbckwmrjjgqm
- 项目界面和介绍如下图:
### 输入法问题
- 在英语论文写作中,所有的符号必须是英语下的格式符号,特别是 逗号 不然后期编译报错的时候往往就会因为这个编译不成功,而找了半天也找不到错误。
### 公式
- <font color="#dd0000">相关的代码在参考链接的431行处开始。</font><br />
- 所有的数学的符号,公式,都需要放在数学环境里面,否则会报错
- 这个会自动提示,所以不用担心。
- 行内模式 (inline) 和行间模式 (display)。前者在正文的行文中,插入数学公式;后者独立排列单独成行,并自动居中。
- 使用 $ ... $ 可以插入行内公式,使用 $$...$$ 可以插入行间公式
- 如果需要对公式进行编号,则可以使用 equation 环境:
- 这三个公式环境可以满足几乎7成的数学公式的编辑,特别是 equation。简单易用。
- 在公式环境里面的所有的字母不需要再去做斜体变化,它会自己就变成
- 细节
- 下标:  _   如 x_{k-1}
- 上标:^   如 x^{k-1}
- 公式内符号加粗 \bm{} 命令。注意在公式命令中\textbf{}是不能使用的
- 大括号
- 使用\left \right 可以把需要括起来的公式括起来。
- 这个命令往往需要在equation 环境内使用,并且需要和多行公式的环境使用 如\align.
- 所以这个命令就只能对整个大括号进行编号。因为一个equation 环境,就只有一个编号
- case+numcases
- 这个可以对大括号内的所有的公式进行单独编号
- 需要导入cases的宏包
- 这个环境和\algin 环境是不兼容的,不过它本身也自带了多行对齐,所以倒也不用\algin.
- 多行对齐
- \algin 命令,把需要多行对齐的括起来就可以。
- 如果是一个等式的多个等号的推到过程的话,需要使用 &= 的方式,具体看例程
- 可以单独使用,也可以和equation环境使用
- 希腊字母
- https://blog.csdn.net/lanchunhui/article/details/49819445
- 公式截图生成latex
- 当需要输入很多公式的时候,慢慢输入是一件非常恶心的事,这里就推荐一个截图转latex的工具 mathpix.
- mathpix 使用非常简单,这里不做详细介绍。值得一提的是,mathpix 免费版只支持每个月50次截图,如果你想使用更多次,可以每个月交钱,也可以利用多个邮箱注册多个账户,每个账户的使用户次数是独立的。
### 插图
- <font color="#dd0000">相关的代码在参考链接的472行处开始。</font><br />
- 最简单的插图方式
- \begin{figure}
- \centering //设置对齐格式,中心对齐
- \includegraphics[width=2cm,height=2.5cm]{shennai.jpeg}{shennai.jpeg} //指定图形大小和图形名称,一般将该图形放在latex文件同一路径下就不需要指明路径
- \caption{Proposed Secure Systolic Montgomery modular MultiplierArchitecture} 设置插图的题注
- \label{fig:arch} 设置图形引用名称,方便引用
- \end{figure}
- 调整图像大小
- 在\includegraphics[width=2cm,height=2.5cm] 中可以随意调整图像大小,这个在插入多张图像的特别有用,可以自己控制
- 也可以使用\includegraphics[width=0.25\textwidth] 按照比例缩放图像。这里的比例不是图像的放大比例,而是纸张的比例。\textwidth 就是纸张宽度,0.25的纸张宽度,其实就是站宽度的1/4,这样的话,是方便插入多张图,不用自己去慢慢算设置长宽是多少。
- \linewidth - 当前行的宽度
- \columnwidth - 当前分栏的宽度
- \textwidth - 整个页面版芯的宽度
- \paperwidth - 整个页面纸张的宽度
- \hsize - Plain TeX 的宏,是 TeX 在行末考虑分词换行时使用的宽度
- 需要在列表环境中使用表格、图片等宽度的时候,用 \linewidth
- 插入的图像的大小是一致的时候,推荐使用\textwidth。因为可以根据图像的数量直接确定系数插图。而如果图像大小不一致的时候需要自己控制图像的高度和宽度而不推荐使用\textwidth。因为\textwidth 是按照比例放缩图像,而如果图像大小不同,放缩之后还是不同,非常不美观。从政角度来说自己控制高度和宽度更加通用
- 跨栏插图
- 如果模板是双栏的,所有的操作都只是插图在在单栏,如果需要跨过双栏只需要把 \begin{figure} 改成 \begin{figure*}。 同样的 \end 也要修改
- 一行多图
- 有时候需要一行插入多图,而且每个图都有自己的编号,这时候就需要用到 \subfigure. <font color="#dd0000">\subfigure 本身是一个宏包,需要我们自己导入</font><br />
- 使用subfigure的时候默认是行排列。 也就是一行多图
- 图像编号默认是英语小写字母顺序
- 每个子图可以用自己的name,参见例程 494行
- 间隔控制控制参加调整图像大小
- 多行多图
- 最简单的办法就是是使用subfigure的时候,在想要另起一行的地方,换行,图像也会换行。参见例程524 行
- 这样的方式,每一个图像都会有自己的编号,如果想把列当做一个整体呢?每一个列只有一个编号要怎么做?
- 多行多图,按列编号
- subfigure本身不支持内部图片换行,所以结合minipage使用。被minipage 包裹住的图片,会被当做一个整体对待。见例程579行
- minipage可以在每一个includegraphics后跟双斜杠“\”表示换行,也可以像上面代码中写的使用”\vspace{4.pt}”来控制垂直间距,但是需要注意的是”\vspace{4.pt}”必须紧跟在对应的includegraphics,不然得不到想要的结果。
- 多行多列的时候,以列为单位,所以输入看起来是两行但是不需要换行。
- 同时有两个不同的尺寸控制,一个是minipage的,控制一列的大小,调整的时候整个列都会变换。然后列内的每一个图像也有自己的大小控制。具体可以见例程。
### 制表
- 制表工具: https://www.tablesgenerator.com/#
- 可以在线绘制表格,生成对应的latex代码。而且这个工具还可以合并,分离表格,也就是你需要的所有的表格的形状应该都能生成。就算是还有什么不满意可以再单独修改,工作量会少很多。
- 不过这个工具好像需要翻墙,如果不能翻墙就只能手工设计。
- 手动制表
- 参考链接: https://liam.page/2013/08/04/LaTeX-table/
- 这个链接包含了丰富的指标的例程。这里做细节分析
- 常用的基本操作
- \begin{tabular}{|l|r|}
- l r c 就是左右中对齐
- 竖线| 表示表格的的竖线,|c|l| 就是表示有两列,第一列居中,第二列居左
- 竖线不是必须的,可以根据需求把某列的竖线去掉,后面有例子
- tabular 是可以嵌套的。表格的一个空格也可以是一个tabular,后面会有相关的应用介绍
- table 环境
- 为了让表格能够自动编号并尽可能美观的浮动,LaTeX 提供了 table 环境。基本用法如下
- 一般要炸tabular外面再加一层 table 环境,才可以加上caption,自动编号等操作
- \hine 加横线
- & 表示数据的分割。 |c|l| 只是确定了表格有两列,但是每列是什么数据?就是用 & 做区分的。
- \\\ 表示在表格里面另起一行。
- \\\ 必须在tabular 环境里使用。而这时候就存在一种情况,我的一个格子里面想换行怎么办?就需要在这个格子对应的地方重新调用\begin{tabular}. 见例程615 行
- 总的来说就是竖线和横线确定了表格,&区分实际的表格内容,然后我们是可以对每一个最小单元进行各种操作的。再插入新的表格,或者表格合并等等
- 表格线条的加粗
- 需要宏包:\usepackage{booktabs}
- \toprule
- \midrule
- \bottomrule
- 表格合并
- 横向合并表格 例程659
- 只能在\tabular 环境里使用,把单位格子进行合并,而且往往就是在行或者列上操作
- 行合并 \multicolumn{3}{|c|}{information}
- 3 表示合并三个表格,|c|表示居中 且两边有竖线,information 是表格里面的内容
- 合并之后,就没有 & 了。
- 纵向合并 例程675
- 需要 multirow 宏包的支持
- 既跨行又跨列
- 实现这样的需求需要将上述两个命令结合起来使用。但是只能用 \multicolumn{cols}{pos}{\multirow{rows}{width}{text}} 这样的形式,而不能反过来嵌套。具体原因不明。
- 例程 693行
- 表格大小调整
- \scalebox{0.95}{}, 把最大的begin tabular 包裹住
- \renewcommand\arraystretch{2} 放在table 环境之前,控制列高,数字为几就是几倍。
- 表格美化
- 上下线条加粗
- 两边的竖线去掉
- 见例程631行
### 注意事项
- 正确的ref 引用,但是编译之后显示结果不对,一般是label的位置的问题,把label的位置放到caption的后面。公式,图表,都是如此。
- 引用需要在tex 文件的最后,加上这两个东西,不然编译的时候就会找不到论文的相关引用,就算你在bib文件中已经写好了引用,cite也能自动检索到,但是编译就是会失败
```
\bibliographystyle{ieee}
\bibliography{egbib}
|
Python
|
UTF-8
| 851 | 3.1875 | 3 |
[] |
no_license
|
import numpy as np
from __future__ import division
import matplotlib.pyplot as plt
def weights(x):
w = []
for i in xrange(len(x)):
temp = x[i] - x
den = temp[temp != 0]
w.append(1./np.prod(den))
return w
def barycentric(x,y):
w = weights(x)
X = np.linspace(min(x),max(x),500)
Xv = np.vstack(X)
p = lambda a : np.sum(w*y/(a-x))/np.sum(w/(a-x))
Y = np.apply_along_axis(p,1,Xv)
Y[0] = y[0]
Y[-1] = y[-1]
return X,Y
f = lambda x: abs(x)
for n in xrange(2,21):
plt.subplot(7,3,n-1)
plt.title("Degree %d" % n)
x = np.linspace(-1,1,n+1)
y = f(x)
plt.scatter(x,y)
X,Y = barycentric(x,y)
plt.plot(X,Y)
plt.plot([-1,0,1],[1,0,1])
plt.axis([-1.2,1.2,-0.2,1.2])
plt.gca().get_xaxis().set_ticks([])
plt.gca().get_yaxis().set_ticks([])
plt.show()
|
Markdown
|
UTF-8
| 373 | 2.546875 | 3 |
[] |
no_license
|
# FASHION-MNIST
### A Sequential Model with Dense & Flatten layers has been built on Fashion-Mnist dataset of tensorflow.keras.
### The training dataset has Images of "T-shirt/top","Trouser","Pullover","Dress","Coat","Sandal","Shirt","Sneaker","Bag","Ankle Boot".
### Our model basically predicts the images in Training dataset & evaluation of its prediction is also done
|
Markdown
|
UTF-8
| 735 | 2.75 | 3 |
[] |
no_license
|
My Dotfiles
===========
These are my dotfiles. The bootstrapping process was copied from [Rowan's dotfiles][rowan].
Installing
----------
You'll need Git installed for this to work.
```sh
git clone https://github.com/rowanmanning/dotfiles.git ~/.dotfiles && cd ~/.dotfiles && source bootstrap.sh
```
Updating
--------
To update .dotfiles, run the following:
```sh
cd ~/.dotfiles && source bootstrap.sh
```
Custom Commands
---------------
You can create an `~/.extra` file for things like git author name. Mine looks like this:
```sh
# Git credentials
GIT_AUTHOR_NAME="Glynn Phillips"
GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME"
git config --global user.name "$GIT_AUTHOR_NAME"
```
[rowan]: https://github.com/rowanmanning/dotfiles/
|
Swift
|
UTF-8
| 4,385 | 2.921875 | 3 |
[] |
no_license
|
//
// Mapper.swift
// Employees
//
// Created by Farzana Sultana on 7/27/19.
//
import UIKit
import CoreData
class Mapper: NSObject {
class func convert(fromEntity entity:NSObject, toManaged managed:NSManagedObject){
if (entity.isKind(of: EEmployee.self)){
let eObj = entity as! EEmployee
let obj = managed as! Employee
obj.iD = eObj.Id
obj.rating = Int32(eObj.rating.intValue)
obj.name = eObj.employee_name
obj.age = eObj.employee_age
obj.salary = eObj.employee_salary
obj.profileImage = eObj.profile_image
return
}
}
class func convertToEntity(fromManaged managed:NSManagedObject)->NSObject!{
if (managed.isKind(of: Employee.self)){
let eObj = EEmployee()
let obj = managed as! Employee
eObj.Id = obj.iD
eObj.employee_name = obj.name
eObj.employee_age = obj.age
eObj.rating = obj.rating as NSNumber
eObj.profile_image = obj.profileImage
eObj.employee_salary = obj.salary
return eObj
}
return nil
}
class func getEmployees(From dic:[AnyObject]!) -> [EEmployee]{
var employees = [EEmployee]()
if let tempData = dic {
for i in 0..<tempData.count{
let employee = EEmployee()
objectOfDictionary(dictionary: tempData[i] as? [String : AnyObject], cClass: EEmployee.self, object: employee)
let dic = tempData[i] as! [String : AnyObject]
if let aID = dic["id"]{
employee.Id = aID as? String
}
employee.rating = 0
employees.append(employee)
let dm = DataModel()
if !dm.insertData(Array: [employee], entityName: "Employee") {
print ("Not saved")
}
}
}
return employees
}
class func dictionaryOfObject(object : NSObject)->[String: AnyObject]! {
var count:UInt32 = 0
let properties = class_copyPropertyList(object_getClass(object), &count) //objc_property_t
var dic = [String: AnyObject]()
for i in 0...count-1 {
let property = properties?[Int(i)]
let propertyNameC = property_getName(property!)
let propertyName = String(cString: propertyNameC)
//print(propertyName)
let value = object.value(forKey: propertyName)
if value != nil {
dic.updateValue(value as AnyObject, forKey: propertyName)
}
else {
dic.updateValue(NSNull() as AnyObject, forKey: propertyName)
}
}
free(properties)
return dic
}
@objc class func objectOfDictionary(dictionary : [String:AnyObject]!, cClass:NSObject.Type, object : NSObject){
var count:UInt32 = 0
guard let properties = class_copyPropertyList(cClass, &count) else { return }
for i in 0...count-1 {
let property = properties[Int(i)]
let propertyNameC = property_getName(property)
let propertyName = String(cString: propertyNameC)
if let dic = dictionary {
let value = dic[propertyName]
if value != nil && !((value?.isEqual(NSNull()))!) {
object.setValue(value, forKey: propertyName)
}
else {
//object.setValue("", forKey: propertyName)
continue
}
}
else {
//object.setValue("", forKey: propertyName)
continue
}
}
free(properties)
}
}
|
PHP
|
UTF-8
| 827 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace Chigi;
use Chigi\Sublime\Models\ReturnData;
use Chigi\Sublime\Settings\Environment;
use Chigi\Sublime\Models\File;
class BuildMdToPdf{
public function run(){
$env = Environment::getInstance();
$file = new File($env->getArgument('file'));
require_once('pandoc/config.php');
$cmd = "pandoc \"" . $env->getArgument('file') . "\" -o \"" . $file->getDirPath() . '/' . $file->extractFileName() . ".pdf\" "
. "--latex-engine=xelatex --toc --smart --template=\"" . $config['pandoc']['template_pdf'] . "\"";
exec($cmd);
$returnData = new ReturnData();
$returnData->setCode(208);
$returnData->setMsg('Build ended.');
$returnData->setStatusMsg($file->extractFileName() . '.html builded SUCCESSFULLY, VIEW it directly.');
$returnData->setData($cmd);
return $returnData;
}
}
?>
|
JavaScript
|
UTF-8
| 674 | 2.59375 | 3 |
[] |
no_license
|
const uwu = require('uWebSockets.js');
const app = uwu.App();
function delay(ms = 0){
return new Promise((resolve, reject)=>{
setTimeout(()=>{
resolve()
}, ms)
})
}
async function delayLog(){
await delay(500);
console.log("Hey, watch out! Im logging here.")
}
app.get('/', function(res, req){
applyMiddlewares(req, req, [])
});
app.listen(3000, (token) => {
console.log(token)
});
async function applyMiddlewares(res, req, middlewares = [], handler){
for (let m in middlewares){
try{
await m(req, res)
} catch (e) {
res.onabort(e)
}
}
handler(req, res)
}
|
Java
|
UTF-8
| 2,168 | 2.703125 | 3 |
[] |
no_license
|
package nl.finalist.liferay.lam.api;
/**
* Service for managing custom fields.
*/
public interface CustomFields {
/**
* Add a custom field of type text.
*
* @param entityName entity that the field is added to
* @param fieldName name of the field
* @param defaultValue default value of the field
*/
void addCustomTextField(String entityName, String fieldName, String defaultValue, String[] roles);
/**
* Add a custom field of type text array.
*
* @param entityName entity that the field is added to
* @param fieldName name of the field
* @param possibleValues possible values of the field, comma separated
* @param displayType how to display the values of the text array
*/
void addCustomTextArrayField(String entityName, String fieldName, String possibleValues, String[] roles, String displayType);
/**
* Add a custom field of type integer
*
* @param entityName entity that the field is added to
* @param fieldName name of the field
* @param defaultValue default value of the field
*/
void addCustomIntegerField(String entityName, String fieldName, int defaultValue, String[] roles);
/**
* Delete a custom field
*
* @param entityName entity to which the field applies
* @param fieldName name of the field
*/
void deleteCustomField(String entityName, String fieldName);
/**
* Add a value to a custom field
*
* @param entityName entity to which the field applies
* @param fieldName name of the field
* @param classPK primary key of the entity that the value belongs to
* @param content value of the field
*/
void addCustomFieldValue(String entityName, String fieldName, long classPK, String content);
/**
* Update the value of a custom field
*
* @param entityName entity to which the field applies
* @param fieldName name of the field
* @param classPK primary key of the entity that the value belongs to
* @param content new value of the field
*/
void updateCustomFieldValue(String entityName, String fieldName, long classPK, String content);
}
|
JavaScript
|
UTF-8
| 4,062 | 2.53125 | 3 |
[] |
no_license
|
$(document).ready(function () {
function getCookie(name) {
var v = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
return v ? v[2] : null;
};
$("#usernameNavBar").text(getCookie("username"));
if (getCookie("isAdmin") == "" && getCookie("isSeguridad") == "") {
alert("Ud no posee los permisos necesarios para acceder a esta pagina. Por favor contactar al administrador del sitio para solicitarlos");
window.location.replace("default.html");
}
var cargarDatos = function () {
$.getJSON("/api/Usuarios", function (data) {
console.log(data);
var filas = '';
data.forEach(function (fila) {
$('#selectmultiple').append('<option value="' + fila['Username'] + '">' + fila['Username'] + '</option>');
})
});
};
cargarDatos();
$("#selectmultiple").change(function (e) {
e.preventDefault();
var username = $(this).children("option:selected").val();
$.getJSON("/api/Usuarios/BuscarUsuario2?username=" + username, function (data) {
console.log("/api/Usuarios/BuscarUsuario2?username=" + username);
if (data["isAdmin"] == 1) {
$('#rolesCheckboxes-1').prop('checked', true);
}
else {
$('#rolesCheckboxes-1').prop('checked', false);
}
if (data["isSeguridad"] == 1) {
$('#rolesCheckboxes-2').prop('checked', true);
}
else {
$('#rolesCheckboxes-2').prop('checked', false);
}
if (data["isConsecutivo"] == 1) {
$('#rolesCheckboxes-3').prop('checked', true);
}
else {
$('#rolesCheckboxes-3').prop('checked', false);
}
if (data["isMantenimiento"] == 1) {
$('#rolesCheckboxes-4').prop('checked', true);
}
else {
$('#rolesCheckboxes-4').prop('checked', false);
}
if (data["isConsulta"] == 1) {
$('#rolesCheckboxes-5').prop('checked', true);
}
else {
$('#rolesCheckboxes-5').prop('checked', false);
}
});
});
$('#btnActualizar').click(function (e) {
e.preventDefault();
var Username = $('#selectmultiple').children("option:selected").val();
var isAdmin = " ";
var isSeguridad = " ";
var isConsecutivo = " ";
var isMantenimiento = " ";
var isConsulta = " ";
if ($("#rolesCheckboxes-1").prop("checked")) {
isAdmin = 1;
}
if ($("#rolesCheckboxes-2").prop("checked")) {
isSeguridad = 1;
}
if ($("#rolesCheckboxes-3").prop("checked")) {
isConsecutivo = 1;
}
if ($("#rolesCheckboxes-4").prop("checked")) {
isMantenimiento = 1;
}
if ($("#rolesCheckboxes-5").prop("checked")) {
isConsulta = 1;
}
var resJSON = JSON.stringify({ Username: Username, isAdmin: isAdmin, isSeguridad: isSeguridad, isConsecutivo: isConsecutivo, isMantenimiento: isMantenimiento, isConsulta: isConsulta });
alert(resJSON);
console.log(resJSON);
$.ajax({
type: "post",
url: "api/Usuarios/ActualizarRoles",
data: JSON.stringify({ Username: Username, isAdmin: isAdmin, isSeguridad: isSeguridad, isConsecutivo: isConsecutivo, isMantenimiento: isMantenimiento, isConsulta: isConsulta }),
dataType: "json",
contentType: "application/json",
success: function (response) {
console.log(response.msg)
alert(response.msg)
},
error: function (response) {
console.log(response);
window.location.replace("error.html?error=" + response.status + "&men=Error_Agregando_Consecutivo");
}
});
});
});
|
Java
|
UTF-8
| 1,278 | 2.671875 | 3 |
[] |
no_license
|
package extractor;
import config.ConfigurationUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class DefaultWordFilterTest {
private static DefaultWordFilter filter;
@BeforeEach
void init() {
filter = new DefaultWordFilter();
}
@Test
void shouldFilterWordsWithWrongSymbolsInside() {
var words = Set.of("rrr%rrr", "roa9d", "http://example.com");
assertTrue(filter.filter(words).isEmpty());
}
@Test
void shouldFilterEmptyStrings() {
var words = Set.of("");
assertTrue(filter.filter(words).isEmpty());
}
@Test
void shouldUnderstandUmlaut() {
var words = Set.of("äöüÄÖÜß");
assertEquals(1, filter.filter(words).size());
}
@Test
void shouldIgnoreWords() {
var filteredWords = new ArrayList<String>();
ConfigurationUtils.parseResourceToCollection(
"list_of_words_for_filtration/english_words.txt", filteredWords, DefaultWordFilter.class
);
assertTrue(filter.filter(filteredWords).isEmpty());
}
}
|
Python
|
UTF-8
| 273 | 3.4375 | 3 |
[] |
no_license
|
""" Write a python function parse_csv to parse csv (comma separated values) files. """
def parse_csv(filename):
csv=[]
lines=open(filename).readlines()
for line in lines:
csv.append([i for i in line if i != ',' and i != '\n'])
return csv
print parse_csv('a.csv')
|
Python
|
UTF-8
| 696 | 2.671875 | 3 |
[] |
no_license
|
import pytest
from Database import Database
from db import PhraseInput
@pytest.hookimpl()
def pytest_sessionstart(session):
"""Actions before all tests."""
db = Database()
for a in range(1, 4):
data = {
'author': f'test-author-{a}',
'text': f'test-text-{a}'
}
phrase = PhraseInput(**data)
db.add(phrase)
print('created:')
print(list(db.items.keys()))
@pytest.hookimpl()
def pytest_sessionfinish(session, exitstatus):
"""Actions after all tests."""
db = Database()
for key in db.items.scan_iter(f'phrase*'):
db.items.delete(key)
print('deletion completed')
print(list(db.items.keys()))
|
Java
|
UTF-8
| 475 | 1.921875 | 2 |
[] |
no_license
|
package com.sink.service.core;
import java.util.List;
import com.sink.domain.core.Contact;
import com.sink.domain.core.Partner;
public interface ContactService {
public Contact findContactById(int id);
public Contact findContactByName(String name);
public List<Contact> findContactsByPartner(Partner partner);
public int addContact(Contact contact);
public void updateContact(Contact contact);
public void toggleActiveOfContact(int id);
}
|
C
|
UTF-8
| 3,197 | 3.25 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
int max (int a, int b) {
return a > b ? a : b;
}
int rec_opt(int arr[], int i){
if ( i == 0 ) {
return arr[0];
} else if ( i == 1 ){
return max (arr[0], arr[1]);
} else {
int a, b;
a = rec_opt (arr, i - 2) + arr[i];
b = rec_opt (arr, i - 1);
return max (a, b);
}
}
int dp_opt (int arr[], int n) {
int opt[7] = {0};
int i;
int a, b;
opt[0] = arr[0];
opt[1] = max (arr[0], arr[1]);
for (i = 2; i < n; i++) {
a = opt[i - 2] + arr[i];
b = opt[i - 1];
opt[i] = max (a, b);
}
return opt[n - 1];
}
int rec_subset (int arr[], int i, int s) {
if (s == 0)
return 1;
else if (i == 0)
return arr[0] == s;
else if (arr[i] > s)
return rec_subset (arr, i - 1, s);
else {
int a, b;
a = rec_subset (arr, i - 1, s - arr[i]);
b = rec_subset (arr, i - 1, s);
return a || b;
}
}
int dp_subset (int arr[], int s) {
#define arr_len 6
#define S 10
//S = s + 1
int subset[arr_len][S];
int i, j;
for (i = 0; i < arr_len; i++)
subset[i][0] = 1;
for (i = 0; i < s; i++)
subset[0][i] = 0;
subset[0][arr[0]] = 1;
for (i = 0; i < arr_len; i++) {
for (j = 0; j < s + 1; j++) {
if (arr[i] > s)
subset[i][s] = subset[i - 1][s];
else {
int a = subset[i - 1][s - arr[i]];
int b = subset[i - 1][s];
subset[i][s] = a || b;
}
}
}
return subset[arr_len - 1][S - 1];
}
int opt (int x, int recode[], int money[], int prev[]) {
if (recode[x] != 0)
return recode[x];
else {
if (x == 1)
return money[1];
if (x == 0)
return 0;
else
return recode[x] = max (
opt (x - 1, recode, money, prev),
money[x] + opt (prev[x], recode, money, prev));
}
}
int main(){
if (0) {//bad neighbors
int arr[] = {1, 2, 4, 1, 7, 8, 3};
int result;
result = rec_opt (arr, 6);
printf ("%d\n", result);
result = dp_opt (arr, 7);
printf ("%d\n", result);
}
if (0) {//compact numbers
int arr[] = {3, 34, 4, 12, 5, 2};
int result;
result= rec_subset (arr, 6 - 1, 9);
printf ("%d\n", result);
result= rec_subset (arr, 6 - 1, 10);
printf ("%d\n", result);
result= rec_subset (arr, 6 - 1, 11);
printf ("%d\n", result);
result= rec_subset (arr, 6 - 1, 12);
printf ("%d\n", result);
result= rec_subset (arr, 6 - 1, 13);
printf ("%d\n", result);
result= dp_subset(arr, 9);
printf ("%d\n", result);
}
if (1) {
/*
n : 9
start end money [1] : 1 4 5
start end money [2] : 3 5 1
start end money [3] : 0 6 8
start end money [4] : 4 7 4
start end money [5] : 3 8 6
start end money [6] : 5 9 3
start end money [7] : 6 10 2
start end money [8] : 8 11 4
max : 12
*/
int n;
int start[100], end[100], prev[100], money[100], recode[100] = {0};
int i, j;
printf ("n:");
scanf ("%d", &n);
for (i = 1;i < n;i++) {
printf ("start end money [%d]:", i);
scanf ("%d%d%d", &start[i], &end[i], &money[i]);
}
for (i = n;i > 0;i--) {
for (j = i - 1;j > 0;j--) {
if (i - 1 == 0) {
prev[i] = 0;
break;
}
if (start[i] > end[j]) {
prev[i] = j;
break;
}
}
}
printf ("max: %d\n", max(
opt (n - 1, recode, money, prev),
money[n] + opt (prev[n], recode, money, prev)));
}
return 0;
}
|
C
|
UTF-8
| 1,004 | 3.453125 | 3 |
[] |
no_license
|
/*
* queue.c
*
* Created on: 2016年9月13日
* Author: Bill
*/
#include "queue.h"
#include "common.h"
node new_queue_node()
{
node ret = (node)malloc(sizeof(node_t));
ret->m_data = 0;
ret->m_next = NULL;
return ret;
}
void free_node(node n) {
if (n != NULL) {
free(n);
n = NULL;
}
}
queue new_queue() {
queue ret = (queue)malloc(sizeof(queue_t));
ret->m_head = NULL;
ret->m_tail = NULL;
return ret;
}
int queue_empty(queue q) {
if (q == NULL || q->m_head == NULL) {
return 1;
} else {
return 0;
}
}
node queue_front(queue q)
{
return q->m_head;
}
node queue_pop(queue q)
{
node ret = q->m_head;
if (ret != NULL) {
q->m_head = ret->m_next;
if (q->m_head == NULL) {
q->m_tail = NULL;
} else if (ret->m_next == ret) {
q->m_head = NULL;
}
}
return ret;
}
void queue_push(queue q, node n)
{
if (q->m_tail != NULL) {
n->m_next = NULL;
q->m_tail->m_next = n;
q->m_tail = n;
} else {
q->m_head = n;
q->m_tail = n;
n->m_next = NULL;
}
}
|
JavaScript
|
UTF-8
| 322 | 3.046875 | 3 |
[] |
no_license
|
const nationalID = prompt ('what is your NID');
const nidIsValid = (nid) => {
const nationalID = parseInt(nid,10)
if (Number.isNaN(nationalID)) {
return false;
}
if (nationalID % 11 !== 0 ) {
return false;
}
else {
return true;
}
};
document.write (nidIsValid());
|
Markdown
|
UTF-8
| 4,730 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
---
layout: post
title: "Covid-19 disrupts China’s rise as a destination for foreign students"
date: 2021-01-28T17:09:42.000Z
author: 经济学人en
from: https://www.economist.com/china/2021/01/30/covid-19-disrupts-chinas-rise-as-a-destination-for-foreign-students
tags: [ 经济学人en ]
categories: [ 经济学人en ]
---
<!--1611853782000-->
[Covid-19 disrupts China’s rise as a destination for foreign students](https://www.economist.com/china/2021/01/30/covid-19-disrupts-chinas-rise-as-a-destination-for-foreign-students)
------
<div>
<img src="https://images.weserv.nl/?url=www.economist.com/img/b/1280/720/90/sites/default/files/images/print-edition/20210130_CNP004_0.jpg"/><div></div><aside ><div ><time itemscope="" itemType="http://schema.org/DateTime" dateTime="2021-01-30T00:00:00Z" >Jan 30th 2021</time><meta itemProp="author" content="The Economist"/></div></aside><p data-caps="initial" ><span data-caps="initial">W</span><small>HEN HIBA BOUROUQIA</small> won a Chinese government scholarship to study international trade, she was “full of hope, full of life”. Now, however, “I just sit and cry,” says the 19-year-old Moroccan. China’s strict quarantine measures have forced her to study remotely from her home near Casablanca. Ms Bourouqia considered giving up and applying for a Moroccan university. But she says the academic standards are not up to China’s, so she is persevering.</p><p >Around the world the dreams of many international students have been shattered by the pandemic. The virus has also damaged China’s hopes to continue as a major destination for international students. In 2019 it was third globally, receiving almost 500,000 foreign students, just behind Britain, though still only half the number going to America. Now, however, China’s tough border controls have made it almost impossible for overseas students to enter the country. Many are furious.</p><div id="" ><div><div id="econ-1"></div></div></div><p >Africa has been a big target of Chinese efforts to enhance its global “soft power”. More than 80,000 Africans were studying there before the pandemic struck. China has surpassed America (47,000) and Britain (29,000) as the destination of choice for African students and is now closing on the traditional frontrunner, France (112,000). The Chinese government has showered the continent with bursaries. One education charity estimates that 43% of all scholarships to sub-Saharan Africa are provided by the Chinese government.</p><p >Unlike Western students, who usually study in China for a year at most, many Africans live from enrolment to graduation on campus. And for all China’s largesse with scholarships, about 85% of them are self-funded, so they feel heavily invested. They also worry about job prospects. “Would you employ a person who did civil engineering online?” asks Davine, a third-year undergraduate who is stuck in his home country, Zimbabwe.</p><p >Many African students have joined an international social-media campaign, #TakeUsBackToChina. It accuses China of ignoring their pleas to be allowed back, even though they are prepared to take necessary tests for covid-19 and submit to quarantine. They have written a petition saying they cannot continue to pay fees for poor online lessons that often require them to be up in the middle of their night.</p><p >The grievances of African students have been compounded by a spate of racist incidents in China early last year. In the southern city of Guangzhou, dozens of Africans, including students, were evicted from their homes after several Nigerians tested positive for covid-19.</p><div id="" ><div><div id="econ-2"></div></div></div><p >But in spite of the current problems China’s universities are likely to keep attracting Africans. A year at a leading Chinese college, many of which are rising up global league tables, costs no more than $4,000 in fees, one-tenth of the cost in Europe or America. Mostapha El-Salamony, an Egyptian doctoral student in aerodynamics at Peking University, says it is also easier to gain admission to Chinese universities and, in normal times, to secure a visa. He says he works with top-class scientists and equipment, and most classes for international students are taught in English. Says Ms Bourouqia, “China was and still is the best choice.” <span data-ornament="ufinish">■</span></p><p data-test-id="Footnote" >This article appeared in the China section of the print edition under the headline "School’s out"</p><br><hr><div>获取更多RSS:<br><a href="https://feedx.net" style="color:orange" target="_blank">https://feedx.net</a> <br><a href="https://feedx.xyz" style="color:orange" target="_blank">https://feedx.xyz</a><br></div>
</div>
|
Java
|
UTF-8
| 1,143 | 2.546875 | 3 |
[] |
no_license
|
package com.salesforce.tests.dependency.command;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.salesforce.tests.dependency.Item;
import com.salesforce.tests.dependency.util.DependancyUtil;
public class INSTALLCommand implements Command{
@Override
public void execute(CommandOptions options) {
if(options == null) {
System.out.println("Provide some item");
return;
}
Map<String, List<Item>> objectDependancy = DependancyUtil.getDependancy();
Item optionItem = options.getItem().poll();
String keyName = optionItem.getName();
List<Item> keyList = objectDependancy.get(keyName);
if(keyList.size() == 0) {
if(!DependancyUtil.getInstalledItem().contains(keyName)) {
System.out.println("Installing "+ keyName);
DependancyUtil.addToInstalledList(keyName);
}
}
else {
for(Item item : keyList) {
Set<String> set = DependancyUtil.getInstalledItem();
String name = item.getName();
if(!DependancyUtil.getInstalledItem().contains(name)) {
System.out.println("Installing "+ name);
DependancyUtil.addToInstalledList(name);
}
}
}
}
}
|
Java
|
UTF-8
| 723 | 2.125 | 2 |
[] |
no_license
|
package fr.training.spring.library.infrastructure.http.dto;
public class AuthorInfo {
private String name;
private String personal_name;
private DateInfo last_modified;
private String key;
private TypeInfo type;
private int id;
private int revision;
public String getName() {
return name;
}
public String getPersonal_name() {
return personal_name;
}
public DateInfo getLast_modified() {
return last_modified;
}
public String getKey() {
return key;
}
public TypeInfo getType() {
return type;
}
public int getId() {
return id;
}
public int getRevision() {
return revision;
}
}
|
PHP
|
UTF-8
| 1,086 | 2.546875 | 3 |
[] |
no_license
|
<?php
namespace backend\widgets;
use yii\base\Widget;
use yii\helpers\Json;
use yii\web\JsExpression;
class SelectStorySlidesWidget extends Widget
{
public $slidesAction;
public $onSave;
public $selectedSlides = [];
public $buttonTitle = 'Выбрать слайды';
public $stories;
public function run()
{
if ($this->slidesAction === null) {
throw new \DomainException('slidesAction is not set');
}
$this->registerClientScript();
return $this->render('story-slides', [
'buttonTitle' => $this->buttonTitle,
'stories' => $this->stories,
]);
}
private function registerClientScript(): void
{
$view = $this->getView();
$configJson = Json::htmlEncode([
'slidesAction' => $this->slidesAction,
'onSave' => new JsExpression($this->onSave),
'selectedSlides' => $this->selectedSlides,
]);
$js = new JsExpression("window.selectStorySlidesConfig = $configJson;");
$view->registerJs($js);
}
}
|
Markdown
|
UTF-8
| 4,394 | 3.359375 | 3 |
[] |
no_license
|
# Java
## 编码
Java默认字符是Unicode编码,而String类型的编码方式与JVM编码方式都与本机操作系统的默认字符集有关
## 语言特性
### 泛型
- E Element,在集合中使用,集合中存放的元素
- T Type, Java的类
- K key 键
- V Value 值
- N Number 数值类型
- ?不确定的Java类型
### Class类
是所有对象的运行时类型标识,即RTTI-Run Time Type Identification
它是由JVM创建,它的作用就是在运行时提供或获得某个对象的类型信息
```java
public class Shape{}
// get Class method one
Class obj1 = Class.forName("Shape");
// get Class method two
Shape shape = new Shape();
Class obj2 = shape.getClass();
// instace obj
Class<Shape> obj3 = Shape.class;
```
### listener
Java中的事件监听机制,事件观察者向事件发出者进行注册,当事件产生时,事件发出者调用注册的函数进行
发送。
事件发出者管理一个array或list来维护注册者,所以尽量不要在多线程中使用这样,需要单线程依次发送。
特别对于网络的监听是非常多的。
### 反射机制
在运行状态中,对于任意一个类,都能知道这个类的所有属性和方法;对于任意一个对象,都能调用它们的任意一个方法和属性。这种动态获取的信息以及动态调用对象的方法的功能称为Java语言的反射机制
即编译后,这些信息都是可获取的,在语言层面提供了支持。
### 注解
与C语言中的宏是类似功能,Java的注解是在class文件文件基础上的东西,class文件里面是没有注解的,注解的形式是便于编译器在处理class时关联Annotation信息,通过反射去获取信息。
#### 元注解
java.lang.annotation里面定义了4种原语
- @Target,用于明确被修饰的类型,方法,字段,类,接口等
- @Retention,描述注解的生命周期
1. RetentionPolicy.RUNTIME 注解会在class字节码文件中存在,运行时反射即可获得
2. RetentionPolicy.CLASS,注解会在class字节码文件中存在,但运行时不能获取
3. RetentionPolicy.SOURCE,仅存在源码中,class字节码中不存在
- @Documented
- @Jnherited
#### 自定义注解
##### 简单注解
又称标记,这种注解仅利用自身的存在与否来提供信息,如@Override
```java
// 定义一个注解
public @interface Test{}
// 使用注解
@Test
public class MyClass{
}
```
##### 复杂注解
又称元数据Annotation,提供更多的元数据
```java
// 定义注解
@Rentention(RententionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyTag {
// 以method的形式提供
String name();
int age() default 32;
}
// 使用注解
public class Test {
@MyTag(name="test")
public void info() {}
}
```
使用Annotation修饰了程序后,并不会自己生成,需要开发者通过API来提取。所有的元数据的接口都继承
Annotation父接口
方法就是通过反射获取Annotation,将Annotation转换为XXXAnnotation,调用XXXAnnotation中的方法
```java
Class clazz = Class.forName(className);
Annotation[] arr = clazz.getMethod("info").getAnnotations();
for (Annotation an : arr) {
if (an instanceof MyTag) {
MyTag tag = (MyTag)an;
String str = String.format("%s, %d", tag.name(), tag.age());
System.out.println(str);
}
}
```
### bean
Java语言欠缺属性、事件、多重继承功能,要在Java中实现一些面向对象的常见需求,需要大量的胶水代码。
Bean正是编写这套胶水代码的惯用模式或约定,包括
- getXxx
- setXxx
- isXxx
- addXxxListener
- XxxEvent
- ...
这也是Java代码的常见写法,数据都是声明为
```java
private int size;
public int getSize() { return size};
public void setSize(int _size) { size = _size; }
```
public保证接口的向后兼容,内部的实现与size可能会改变, 这就是Java Bean,但是更新的语言C#等就
不需要,它们在语言自身中就提供了足够的语言特性来实现这些功能。
#### 进化
1. java bean1.00-A
2. 因需要实现事务,安全,分布式,升级为EJB
3. DI依赖注入,AOP面向切面技术来解决EJB的臃肿,升级为POJO
4. spring
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.