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
C#
UTF-8
1,732
2.8125
3
[ "MIT" ]
permissive
using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using TeamCityChangeNotifier.Models; namespace TeamCityChangeNotifier.XmlParsers { public class BuildListXmlParser { private readonly XDocument _buildDoc; public BuildListXmlParser(string buildXml) { _buildDoc = XDocument.Parse(buildXml); } public BuildListData FromIdBackToLastPin(int firstBuildId) { var builds = _buildDoc.Root.Descendants("build"); var foundStartBuild = false; var foundEndBuild = false; var buildIds = new List<int>(); int previousPinnedBuildId = 0; foreach (var buildElement in builds) { var buildId = BuildId(buildElement); if (foundStartBuild) { if ( BuildIsPinned(buildElement)) { previousPinnedBuildId = buildId; foundEndBuild = true; break; } buildIds.Add(buildId); } else { if (buildId == firstBuildId) { buildIds.Add(buildId); foundStartBuild = true; } } } if (!foundStartBuild) { throw new ParseException("Did not find first build with Id " + firstBuildId); } if (!foundEndBuild) { throw new ParseException("Did not find previous pinned build after Id " + firstBuildId); } return new BuildListData { Ids = buildIds, PreviousPinnedBuildId = previousPinnedBuildId }; } private static int BuildId(XElement buildElement) { var iddAttr = buildElement.Attributes("id").First().Value; return int.Parse(iddAttr); } private static bool BuildIsPinned(XElement buildElement) { var pinnedAttr = buildElement.Attributes("pinned").FirstOrDefault(); return (pinnedAttr != null) && (pinnedAttr.Value == "true"); } } }
C++
UTF-8
1,444
3.375
3
[]
no_license
#include<iostream> #include<bits/stdc++.h> using namespace std; template<typename T> class Graph{ map<T,vector<T> >adjList; T V; public: Graph(T v){ V=v; } void addEdge(T a, T b, bool bidir = true){ adjList[a].push_back(b); if(bidir) adjList[b].push_back(a); } bool cycle_helper(T node, bool *visited, T parent){ visited[node] = true; for(auto nbr: adjList[node]){ if(!visited[nbr]){ //If the node is not visited, it might be possible that a neighbour node of it, might have been visited. //Call recursively to visit the neighbour nodes bool ans = cycle_helper(nbr,visited,node); if(ans) return true; } else if(nbr != parent){ //If the node is already visited, it might also be possible that it is the parent node, so, to avoid such a case. return true; } } return false; } bool cycle_detection(T src){ bool *visited = new bool[V]; for(int i=0;i<V;i++){ visited[i] = false; } bool ans = cycle_helper(src,visited,-1); return ans; } }; int main(){ Graph<int>g(5); g.addEdge(0,1); g.addEdge(0,2); // g.addEdge(1,3); g.addEdge(2,4); g.addEdge(3,4); if(g.cycle_detection(0)) cout<<"Yes"; else cout<<"No"; }
Java
UTF-8
383
2.21875
2
[ "MIT" ]
permissive
package com.blackstone.goldenquran.models.models; /** * Created by Abdullah on 5/5/2017. */ public class ColorEvent { public void setColorOn(boolean colorOn) { isColorOn = colorOn; } public boolean isColorOn() { return isColorOn; } boolean isColorOn; public ColorEvent(boolean isColorOn) { this.isColorOn = isColorOn; } }
Ruby
UTF-8
2,114
3.359375
3
[]
no_license
def part_1_7(input) num_TLS = 0 input.each do |code| tls = false brackets = false bracket_stack_found = false stack = [] bracket_stack = [] code = code.chars while code.length > 0 while brackets == true && !bracket_stack_found bracket_char = code.shift if bracket_char == "]" brackets = false bracket_stack = [] else bracket_stack << bracket_char end if bracket_stack.length == 4 if test_stack(bracket_stack) bracket_stack_found = true break else bracket_stack.shift end end end break if bracket_stack_found test_char = code.shift if test_char == "[" stack = [] brackets = true else stack << test_char end if stack.length == 4 if test_stack(stack) tls = true else stack.shift end end unless brackets end if tls && !bracket_stack_found num_TLS += 1 end end num_TLS end def test_stack(stack) (stack[0] == stack[3]) && (stack[1] == stack[2]) && (stack[0] != stack[1]) end def part_2_7(input) num_SSL = 0 input.each do |code| code = code.chars abas = [] bracket_abas = [] brackets = false while code.length > 2 if brackets bracket_char = code.shift if bracket_char == "]" brackets = false else test_sequence = bracket_char + code[0] + code[1] if test_sequence[0] == test_sequence[2] && code[0] != "]" && bracket_char != code[0] bracket_abas << code[0] + bracket_char + code[0] end end else char = code.shift if char == "[" brackets = true else test_sequence = char + code[0] + code[1] if test_sequence[0] == test_sequence[2] && code[0] != "[" && char != code[0] abas << test_sequence end end end end num_SSL += 1 if (abas & bracket_abas).length > 0 end num_SSL end
Python
UTF-8
331
2.96875
3
[]
no_license
""" B - K-th Common Divisor """ def solve(): A, B, K = map(int, input().split()) count = 0 for i in reversed(range(1, A + 1)): if A % i == 0 and B % i == 0: count += 1 if count == K: ans = i break print(ans) if __name__ == '__main__': solve()
Shell
UTF-8
888
2.59375
3
[]
no_license
#!/bin/bash #http://redsymbol.net/articles/unofficial-bash-strict-mode/ set -euo pipefail IFS=$'\n\t' sudo dnf install -y salt-master salt-key --gen-keys-dir=pki --gen-keys=salt.vagrant.rbjorklin.com || true for i in $(seq 1 $(egrep '^\$nodes\s?=\s?[1-9]$' config.rb | egrep -o '[1-9]')) ; do salt-key --gen-keys-dir=pki --gen-keys=node0${i}.vagrant.rbjorklin.com || true done vagrant plugin install vagrant-hostmanager vagrant-vbguest vagrant up vagrant ssh master -c "sudo salt 'node0*' test.ping" vagrant ssh master -c "sudo salt 'node0*' state.sls elrepo" vagrant ssh master -c "sudo salt 'node0*' state.sls kernel-lt" vagrant reload node01 node02 node03 node04 vagrant ssh master -c "sudo salt '*' state.highstate" echo "Visit Consul UI here: http://10.10.10.10:8500/ui" echo "See HAproxy stats here: http://10.10.10.13:1936/stats or here: http://10.10.10.14:1936/stats"
Markdown
UTF-8
830
3.140625
3
[]
no_license
## This is a simple example about using Gmail email in express. In order to use this code: - Clone the repository - Run `npm install` - Change `RECEIVER_EMAIL` and `SENDER_EMAIL` in `index.js` - Add credentials of your gmail account on line 17 and 18 in place of `youremail@gmail.com` and `yourpassword`. ```` var transporter = mailer.createTransport({ host: 'smtp.gmail.com', // hostname secureConnection: true, // use SSL requireTLS: true, port: 465, // port for secure SMTP transportMethod: 'SMTP', // default is SMTP. Accepts anything that nodemailer accepts auth: { user: 'youremail@gmail.com', pass: 'yourpassword' } }); ````` Note: You need to turn on access to less secure apps in GMail. Otherwise this will throw error. Read this to understand how to use [nodemailer using Gmail](https://nodemailer.com/using-gmail/);
Markdown
UTF-8
736
2.546875
3
[]
no_license
## Martinique's subdivision, Ducos ![](ducoserrorplot.png) ![](mapviewducos.png) ![](3dplotducos.png) ## Martinique's subdivision, Le Marin ![](lemarinerrorplot.png) ![](mapviewlemarin.png) ![](3dplotlemarin.png) ## Martinique's subdivision, Fort-de-France ![](fortdefranceerrorplot.png) ![](mapviewfortdefrance.png) ![](3dplotfortdefrance.png) # Here are raster plots for predicted sums, means and log of the population in Martinique ## Sums ![](popsums.png) ![](diffsums.png) ![](diffsums3d.png) ## Means ![](popmeans.png) ![](diffmeans.png) ![](diffmeans3d.png) ## Logarithm (For some reason, this produced very similar plots to the predicted mean) ![](poplog.png) ![](difflog.png) ![](difflog3d.png)
Java
UTF-8
4,056
2.390625
2
[]
no_license
package com.matrangola.contentprovider; import android.Manifest; import android.content.pm.PackageManager; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.loader.app.LoaderManager; import androidx.loader.content.CursorLoader; import androidx.loader.content.Loader; public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> { public static final String TAG = "MainActivity"; public static final String PERMISSION = Manifest.permission.READ_EXTERNAL_STORAGE; private static String[] PROJECTION = new String[] { MediaStore.Audio.AudioColumns.ALBUM, MediaStore.Audio.AudioColumns.TITLE }; private static final int MY_PERMISSIONS_REQUEST_ACCESS_MEDIA = 222; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override protected void onStart() { super.onStart(); if (ContextCompat.checkSelfPermission(this, PERMISSION) != PackageManager.PERMISSION_GRANTED) { // Permission is not granted // Should we show an explanation? if (ActivityCompat.shouldShowRequestPermissionRationale(this, PERMISSION)) { // Show an explanation to the user *asynchronously* -- don't block // this thread waiting for the user's response! After the user // sees the explanation, try again to request the permission. } else { // No explanation needed; request the permission ActivityCompat.requestPermissions(this, new String[] { PERMISSION }, MY_PERMISSIONS_REQUEST_ACCESS_MEDIA); // MY_PERMISSIONS_REQUEST_ACCESS_MEDIA is an // app-defined int constant. The callback method gets the // result of the request. } } else { // Permission has already been granted readMedia(); } } private void readMedia() { LoaderManager .getInstance(this) .initLoader(5, null, this); } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case MY_PERMISSIONS_REQUEST_ACCESS_MEDIA: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted, yay! Do the // contacts-related task you need to do. readMedia(); } else { // permission denied, boo! Disable the // functionality that depends on this permission. } return; } } } @NonNull @Override public Loader<Cursor> onCreateLoader(int id, @Nullable Bundle args) { Uri mediaStoreUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; return new CursorLoader( this, mediaStoreUri, PROJECTION, null, // MediaStore.Audio.AudioColumns.TITLE + "LIKE ?" null, // new String[] { "%Love%" } null); } @Override public void onLoadFinished(@NonNull Loader<Cursor> loader, Cursor cursor) { int idxAlbum = cursor.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.ALBUM); int idxTitle = cursor.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.TITLE); Log.i(TAG, "Media Rows: " + cursor.getCount()); while (cursor.moveToNext()) { String album = cursor.getString(idxAlbum); String title = cursor.getString(idxTitle); Log.i(TAG, "Album: " + album + " Title: " + title); } cursor.close(); } @Override public void onLoaderReset(@NonNull Loader<Cursor> loader) { // Release reference to cursor data, by closing or nulling out reference. } }
C#
UTF-8
2,199
2.890625
3
[]
no_license
// This file is part of libnoise-dotnet. // // libnoise-dotnet is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // libnoise-dotnet is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with libnoise-dotnet. If not, see <http://www.gnu.org/licenses/>. // // From the original Jason Bevins's Libnoise (http://libnoise.sourceforge.net) namespace LibNoise.Primitive { /// <summary> /// Noise module that outputs a checkerboard pattern. /// /// This noise module outputs unit-sized blocks of alternating values. /// The values of these blocks alternate between -1.0 and +1.0. /// /// This noise module is not really useful by itself, but it is often used /// for debugging purposes. /// /// </summary> public class Checkerboard :PrimitiveModule, IModule3D { #region Ctor/Dtor /// <summary> /// Create new Checkerboard generator with default values /// </summary> public Checkerboard(){ }//end Checkerboard #endregion #region Interaction /// <summary> /// Generates an output value given the coordinates of the specified input value. /// </summary> /// <param name="x">The input coordinate on the x-axis.</param> /// <param name="y">The input coordinate on the y-axis.</param> /// <param name="z">The input coordinate on the z-axis.</param> /// <returns>The resulting output value.</returns> public float GetValue(float x, float y, float z) { // Fast floor int ix = (x > 0.0 ? (int)x: (int)x - 1); int iy = (y > 0.0 ? (int)y: (int)y - 1); int iz = (z > 0.0 ? (int)z: (int)z - 1); return (ix & 1 ^ iy & 1 ^ iz & 1) != 0 ? -1.0f: 1.0f; }//end GetValue #endregion }//end class }//end namespace
JavaScript
UTF-8
1,237
2.515625
3
[]
no_license
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import RepoStore from '../facades/repoStore'; //const match = this.props.match; export default class Repositories extends Component { constructor(props) { super(props); this.state = { repos: [] }; } /* eksempel brug af async: async componentWillMount(){ let repos = await AsyncRepoStore.getRepos(); this.setState({repos}); } */ componentWillMount() { /*uden facade fetch("https://api.github.com/orgs/Cphdat3sem2017f/repos", { method: "GET" }) .then(response => response.json()) .then(repos => { this.setState({ repos }); }); */ RepoStore.getRepos(repos => { this.setState({ repos }); }); } render() { return ( <div> <h2>Hello from alle repos</h2> <ul> {this.state.repos.map(repo => { return <li key={repo.name}>{repo.name} - <Link to={"/repository/" + repo.name}>Details</Link></li> })} </ul> </div> ) } }
C#
UTF-8
506
2.703125
3
[]
no_license
namespace TrafficSimulation.Simulation.Engine.Environment { /// <summary> /// Manages the lifetime of vehicles /// </summary> public interface IVehicleLifetimeManager { /// <summary> /// Creates a new vehicle /// </summary> /// <returns>The newly created vehicle</returns> IVehicle CreateVehicle(); /// <summary> /// Destroys a vehicle /// </summary> /// <param name="vehicle">The vehicle to destroy</param> void DestoryVehicle(IVehicle vehicle); } }
Markdown
UTF-8
2,170
3.0625
3
[ "MIT-0", "LicenseRef-scancode-proprietary-license" ]
permissive
# Amazon EC2: Limits terminating EC2 instances to an IP address range<a name="reference_policies_examples_ec2_terminate-ip"></a> This example shows how you might create an identity\-based policy that limits EC2 instances by allowing the action, but explicitly denying access when the request comes from outside the specified IP range\. The policy is useful when the IP addresses for your company are within the specified ranges\. This policy grants the permissions necessary to complete this action programmatically from the AWS API or AWS CLI\. To use this policy, replace the *italicized placeholder text* in the example policy with your own information\. Then, follow the directions in [create a policy](access_policies_create.md) or [edit a policy](access_policies_manage-edit.md)\. If this policy is used in combination with other policies that allow the `ec2:TerminateInstances` action \(such as the [AmazonEC2FullAccess](https://console.aws.amazon.com/iam/home#policies/arn:aws:iam::aws:policy/AmazonEC2FullAccess) AWS managed policy\), then access is denied\. This is because an explicit deny statement takes precedence over allow statements\. For more information, see [Determining whether a request is allowed or denied within an account](reference_policies_evaluation-logic.md#policy-eval-denyallow)\. **Important** The `aws:SourceIp` condition key denies access to an AWS service, such as AWS CloudFormation, that makes calls on your behalf\. For more information about using the `aws:SourceIp` condition key, see [AWS global condition context keys](reference_policies_condition-keys.md)\. ``` { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": ["ec2:TerminateInstances"], "Resource": ["*"] }, { "Effect": "Deny", "Action": ["ec2:TerminateInstances"], "Condition": { "NotIpAddress": { "aws:SourceIp": [ "192.0.2.0/24", "203.0.113.0/24" ] } }, "Resource": ["*"] } ] } ```
Python
UTF-8
416
3.453125
3
[]
no_license
''' Created on 18 may. 2020 @author: Guzman Lopez Cesar Gerardo 88-8@live.com.mx ''' from random import random from cmath import sqrt aciertos,num_lanzamientos=0.0,5000000 for n in range(num_lanzamientos): #si es cierto regresara cierto que en #python si lo sumo a un real se toma como uno y 0 si es falso aciertos +=(sqrt((random()**2)+(random()**2)).real<=1) print(" aciertos= ",aciertos," pi= ",4*aciertos/num_lanzamientos)
JavaScript
UTF-8
698
2.671875
3
[]
no_license
var React = require('react'); var ListElement = require('./ListElement.js'); var data = [{"id": 1, "name": "first element"},{"id": 2, "name": "second element"},{"id": 1, "name": "third element"}]; var List = React.createClass({ render: function(){ var listElements = data.map(function(element) { return <ListElement id={element.id} name={element.name}/>; }); return ( <div> <h2>It works!</h2> <h3>You have build the list in React with browserify, babel-preset-react, babelify and watchify.</h3> <ul>{listElements}</ul> </div> ); } }); module.exports = List;
C++
UTF-8
1,816
2.9375
3
[]
no_license
//graph.cpp #include <limits> #include <vector> #include <iostream> #include "Graph.h" #define MASK64_32 0x00000000FFFFFFFF using namespace WPAlgos; PrimGraph::PrimGraph(): m_numNodes{0} {}; void PrimGraph::addNode(uint32_t id) { m_nodes[id] = true; m_numNodes++; } void PrimGraph::removeNode(uint32_t id) { m_nodes[id] = false; m_numNodes--; } void PrimGraph::addEdge(uint64_t edge, double weight) { m_edges[edge] = true; m_weights[edge] = weight; } void PrimGraph::addEdge(uint32_t u, uint32_t v, double weight) { uint64_t u64 = (uint64_t) u; m_edges[(u64 << 32) + (v & MASK64_32)] = true; m_weights[(u64 << 32) + (v & MASK64_32)] = weight; } void PrimGraph::removeEdge(uint64_t edge) { m_edges[edge] = false; } void PrimGraph::removeEdge(uint32_t u, uint32_t v) { uint64_t u64 = (uint64_t) u; m_edges[(u64 << 32) + (v & MASK64_32)] = false; } BFRetStruct PrimGraph::BF(uint32_t u, uint32_t v) { BFRetStruct ret; //set distances to +inf std::unordered_map<uint32_t, double> distances; std::unordered_map<uint32_t, std::vector<uint32_t>> paths; std::cout << m_numNodes << std::endl; for (uint32_t i = 0; i < m_numNodes; i++) { if (m_nodes[i]) distances[i] = std::numeric_limits<double>::max(); } distances[u] = 0; for (uint32_t i = 0; i < m_numNodes; i++) { for (auto it : m_edges) { uint64_t edge = it.first; uint32_t u = (edge >> 32) & MASK64_32; uint32_t v = edge & MASK64_32; if (distances[u] + m_weights[edge] < distances[v]) { distances[v] = distances[u] + m_weights[edge]; paths[v] = paths[u]; paths[v].push_back(edge); } } } ret.path = paths[v]; ret.length = distances[v]; return ret; } BFRetStruct PrimGraph::BF(uint32_t u) { return PrimGraph::BF(u, u); }
Python
UTF-8
92
2.921875
3
[]
no_license
A = input("Ingresevalor de A") B = input("Ingrese valor de B") Y = A * B M = Y + 1 print M
C#
UTF-8
3,075
2.671875
3
[]
no_license
using System; using System.IO; using System.Reflection; using System.Runtime.InteropServices; namespace NetRadio.Devices.G3XDdc { class NativeLoader:IDisposable { [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)] private static extern IntPtr LoadLibraryW(string lpFileName); [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] private static extern bool FreeLibrary(IntPtr hModule); [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)] private static extern IntPtr GetProcAddress(IntPtr hModule, string procName); public string Name { get; private set; } public string LoadFrom { get; private set; } protected readonly IntPtr Module; public NativeLoader(string name, string path = null) { LoadFrom = path ?? Environment.GetFolderPath(Environment.SpecialFolder.SystemX86); Name = name; var fullPath = Path.Combine(LoadFrom, name); Module = LoadLibraryW(fullPath); if(Module==IntPtr.Zero) throw new FileLoadException(string.Format("cannot load '{0}'",fullPath)); } protected IntPtr GetMethodAddress(string name) { var address = GetProcAddress(Module, name); if(address==IntPtr.Zero) throw new MissingMethodException(string.Format("cannot locate '{0}'",name)); return address; } protected T GetMethodDelegate<T>(IntPtr address) { return (T)(object) Marshal.GetDelegateForFunctionPointer(address, typeof (T)); } protected T GetMethodDelegate<T>(string name) { var address = GetMethodAddress(name); return GetMethodDelegate<T>(address); } protected Delegate GetMethodDelegate(IntPtr address,Type t) { return Marshal.GetDelegateForFunctionPointer(address, t); } protected Delegate GetMethodDelegate(string name, Type t) { var address = GetMethodAddress(name); return Marshal.GetDelegateForFunctionPointer(address, t); } protected IntPtr GetFunctionPointer(Delegate handle) { return Marshal.GetFunctionPointerForDelegate(handle); } protected void BindApiCalls() { var fields = GetType().GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); foreach (var f in fields) { var att = f.GetCustomAttributes(typeof (ApiCallAttribute), false); if (att.Length == 0) continue; var name = f.PropertyType.Name; var handle = GetMethodDelegate(name,f.PropertyType); f.SetValue(this,handle,null); } } public void Dispose() { FreeLibrary(Module); } } }
Shell
UTF-8
1,899
3.828125
4
[]
no_license
#!/bin/bash # Perferences WEBROOT=~/public_html/domain.com WORKDIR=~/shadowcopy SHOST=someftphost.com ftpuser=someftpuser ftppass=somepassword db=somedatabase dbuser=somedbuser dbpass=somedbpass sqlfile=domain.sql.bz2 datafile=domain.tar.bz2 SRCDOMAIN=src.domain.com DSTDOMAIN=dst.domain.com # ==== Let's begin ==== # Download last backup echo "$(date|tr -d "\n"): Downloading..." cd ${WORKDIR} rm -f ${sqlfile} rm -f ${datafile} wget --quiet --user="$ftpuser" --password="$ftppass" ftp://$SHOST/backup/*.bz2 if [[ $? -ne 0 ]] ; then echo "$(date|tr -d "\n"): Error: Can not download files!" exit 1 fi echo "$(date|tr -d "\n"): Clean database..." # Cleaning database CLEAN_SQL="SET FOREIGN_KEY_CHECKS=0;" for table in $(mysql -u${dbuser} -p${dbpass} $db <<< 'SHOW TABLES;'|grep -v Tables_in_shop) do CLEAN_SQL="${CLEAN_SQL}DROP TABLE $table;" done CLEAN_SQL="${CLEAN_SQL}SET FOREIGN_KEY_CHECKS=1;" mysql -u${dbuser} -p${dbpass} $db -e "$CLEAN_SQL" >>/dev/null if [[ $? -ne 0 ]] ; then echo "$(date|tr -d "\n"): Error: DB cannot be cleared!" exit 1 fi echo "$(date|tr -d "\n"): Restoring database..." # Restoring DB from last backup bunzip2 < ${WORKDIR}/${sqlfile} | mysql -u${dbuser} -p${dbpass} $db mysql -u$dbuser -p$dbpass $db -e "UPDATE core_config_data SET value=REPLACE(value, \"${SRCDOMAIN}\", \"${DSTDOMAIN}\") WHERE path=\"web/secure/base_url\" OR path=\"web/unsecure/base_url\";" echo "$(date|tr -d "\n"): Clean files..." # Cleaning site root if [[ ! -d ${WEBROOT} ]] then echo "$(date|tr -d "\n"): Warning: Direcrory ${WEBROOT} does not exist!" mkdir -p ${WEBROOT} else rm -rf ${WEBROOT}/* fi echo "$(date|tr -d "\n"): Restoring files..." # Unpack last backup of files cd ${WEBROOT} tar -jxf ${WORKDIR}/${datafile} # Clean cache and sessions rm -rf ${WEBROOT}/var/cache/mage--* rm -f ${WEBROOT}/var/session/sess_* echo "$(date|tr -d "\n"): Completed."
Java
UTF-8
981
2.296875
2
[]
no_license
package org.jmythapi.protocol.response; import org.jmythapi.IVersionable; import org.jmythapi.protocol.annotation.MythProtoVersionAnnotation; import java.util.List; import static org.jmythapi.protocol.ProtocolVersion.PROTO_VERSION_87; @MythProtoVersionAnnotation(from=PROTO_VERSION_87) public interface IFreeInputInfoList extends Iterable<IFreeInputInfo>, IVersionable { /** * Gets the free-inputs as list * * @return * the input devices as list */ public List<IFreeInputInfo> asList(); /** * Gets the input at the given position. * * @param idx * the input index * @return * the input */ public IFreeInputInfo get(int idx); /** * The size of this list * @return * the size of this list */ public int size(); /** * Checks if this list is empty. * * @return * {@code true} if the list is empty. */ public boolean isEmpty(); }
Java
UTF-8
404
2.0625
2
[]
no_license
package uz.controlstudentserver.dto; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class DistrictDto { private Integer id; private String name; private Integer regionId; public DistrictDto(String name, Integer regionId) { this.name = name; this.regionId = regionId; } }
C++
WINDOWS-1250
3,500
2.890625
3
[]
no_license
/** * Mdulo: Limite * Contiene la definicin de la clase TLimite que calcula lmites de * funciones matemticas * * @author Gastn Furini * @version 1.0 * @since 14/02/2005 * @revision 22/01/2007 * 26/10/2007 */ #ifndef uLimiteH #define uLimiteH #include "uEval_Ex.h" //--------------------------------------------------------------------------- class TLimite { private: TEval Eval; // Objeto para evaluar expresiones //--------------------------------------------------------------------------- // LimiteIzq (Limite lateral izquierdo de una funcin) bool LimiteIzq(AnsiString Funcion, long double a, long double &L); // Entrada: // Funcion (AnsiString): Expresin matemtica en notacin infija // a (long double): Valor al que tiende x // Salida: // L (long double&): Valor al que tiende f(x) cuando x -> a- // LimiteIzq (bool): Exito = true //--------------------------------------------------------------------------- // LimiteDer (Limite lateral derecho de una funcin) bool LimiteDer(AnsiString Funcion, long double a, long double &L); // Entrada: // Funcion (AnsiString): Expresin matemtica en notacin infija // a (long double): Valor al que tiende x // Salida: // L (long double&): Valor al que tiende f(x) cuando x -> a+ // LimiteDer (bool): Exito = true //--------------------------------------------------------------------------- public: //--------------------------------------------------------------------------- // Limite (Limite de una funcin) bool Limite(AnsiString Funcion, long double a, long double &L); // Entrada: // Funcion (AnsiString): Expresin matemtica en notacin infija // a (long double): Valor al que tiende x // Salida: // L (long double&): Valor al que tiende f(x) cuando x -> a // Limite (bool): Exito = true //--------------------------------------------------------------------------- // Limite (Limite de una funcin, incluye los limites laterales) bool Limite(AnsiString Funcion, long double a, long double &L, long double &Li, long double &Ld); // Entrada: // Funcion (AnsiString): Expresin matemtica en notacin infija // a (long double): Valor al que tiende x // Salida: // L (long double&): Limite // Li (long double&): Limite izquierdo // Ld (long double&): Limite derecho // Limite (bool): Exito = true //--------------------------------------------------------------------------- }; //--------------------------------------------------------------------------- /* * Clase TLimit */ enum TLimitResult {LimitOk, noLimit}; struct LimitValue { long double value; bool infinity; bool negative; }; class TLimit { private: TEval eval; AnsiString expr; LimitValue value, limit, leftLimit, rightLimit; bool hasLimit, hasLeftLimit, hasRightLimit; public: TLimit(AnsiString expr); bool getLimit(LimitValue value); bool getLeftLimit(LimitValue value); bool getRightLimit(LimitValue value); __property bool HasLimit = {read = hasLimit}; __property bool HasLeftLimit = {read = hasLeftLimit}; __property bool HasRightLimit = {read = hasRightLimit}; __property LimitValue Limit = {read = Limit}; __property LimitValue LeftLimit = {read = LeftLimit}; __property LimitValue RightLimit = {read = RightLimit}; }; #endif
Markdown
UTF-8
542
2.703125
3
[]
no_license
# MkDocs Moonstone Theme This project provides a theme optimized for developer and API documentation to be used with [MkDocs](https://www.mkdocs.org/) projects. ## Installation Install the theme with pip: pip install mkdocs-moonstone After the theme is installed, edit your [mkdocs.yml] file and set the theme [name] to `moonstone`: theme: name: moonstone ## Documentation To learn more about Moonstone and its configuration options [visit the project's documentation](https://byrnereese.github.io/mkdocs-moonstone/).
Go
UTF-8
230
2.765625
3
[]
no_license
package stream func Map[T, U any](it func(func(T) bool) bool, f func(T) U) func(func(U) bool) bool { return func(yield func(U) bool) bool { for v := range it { if !yield(f(v)) { return false } } return true } }
JavaScript
UTF-8
3,522
2.921875
3
[]
no_license
// 可以根据 id、class、element 查找元素 // param (字符串) : #id .class tag // obj : 父元素 function $(param, obj) { // #box } // 如何解决 getElementsByClassName 兼容问题 function getByClass(className, obj) { // 支持 getElementsByClassName 方法的使用 /* 不支持 getElementsByClassName 方法的使用 */ // 保存所有查找到的元素的数组结构 // 查找出 obj 对象后代所有元素 // 遍历每个元素 // 返回结果集 } //获取指定元素的某一个css属性值 //attr:指定的css属性名称(字符串) function css(obj,attr){ /*if (obj.crrentStyle) { return obj.currentStyle[attr]; } return getComputedStyle(obj)[attr];*/ return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj,null)[attr]; } // 为指定元素添加指定的事件绑定 function bind( element,type,fn){ if ( element.addEventListener){//支持使用 addEventlistener 方法添加事件监听 if( type.indexOf("on") === 0) type = type.slice(2); element.addEventListener(type, fn, false); }else {//attachEvent() if ( type.indexOf("on") !== 0) type = "on" + type; element.attachEvent(type,fn); } } //找出指定的元素在文档中 top 定位坐标 function getOffetTop(element){ //先获取一次 element 元素距离祖先节点中有定位节点的顶部高度 //获取 element 元素祖先节点中有定位的最近的节点 // 可能在 element 的祖先节点中有多个节点有定位 // 则每个节点的定位位置都应该获取到并且累加起来 } // 获取/设置指定元素在文档中的(绝对)定位坐标 // 返回元素在文档中定位坐标的对象 // 该对象有两个属性:{top, left} function offset(element, coordinates) { // 将 current 元素在文档中的定位坐标累加计算出来 // true时为 element 本身,false为 element 元素其祖先元素中最近的有定位的元素节点 } function innerWidth(element) { } function innerHeight(element) { } function outerWidth(element, bool) { } function outerHeight(element, bool) { } // 保存 cookie // key : cookie 名 // value : cookie 值 // options : 可选配置参数 // options = { // expires : 7|new Date(), // 失效时间 // path : "/", // 路径 // domain : "", // 域名 // secure : true // 安全连接 // } function cookie(key, value, options) { /* read 读取 */ // 如果没有传递 value ,则表示根据 key 读取 cookie 值 /* write 设置 */ // 设置 options 默认为空对象 options = options || {}; // key = value,对象 key,value 编码 var cookie = encodeURIComponent(key) + "=" + encodeURIComponent(value); // 失效时间 if ((typeof options.expires) !== "undefined") { // 有配置失效时间 if (typeof options.expires === "number") { // 失效时间为数字 var days = options.expires, t = options.expires = new Date(); t.setDate(t.getDate() + days); } cookie += ";expires=" + options.expires.toUTCString(); } // 路径 if (typeof options.path !== "undefined") cookie += ";path=" + options.path; // 域名 if (typeof options.domain !== "undefined") cookie += ";domain=" + options.domain; // 安全连接 if (options.secure) cookie += ";secure"; // 保存 document.cookie = cookie; } // 从所有的 cookie 中删除指定的 cookie function removeCookie(key, options) { options = options || {}; options.expires = -1; // 将失效时间设置为 1 天前 cookie(key, "", options); }
Java
UTF-8
289
1.6875
2
[ "BSD-3-Clause" ]
permissive
/** * Copyright (C) Zhang,Yuexiang (xfeep) * */ package nginx.clojure.net; public interface NginxClojureSocketRawHandler { public void onConnect(long u, long sc); public void onRead(long u, long sc); public void onWrite(long u, long sc); public void onRelease(long u, long sc); }
Java
UTF-8
2,937
2.640625
3
[ "AGPL-3.0-only", "MIT" ]
permissive
/* FRODO: a FRamework for Open/Distributed Optimization Copyright (C) 2008-2013 Thomas Leaute, Brammert Ottens & Radoslaw Szymanek FRODO is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. FRODO is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. How to contact the authors: <http://frodo2.sourceforge.net/> */ package frodo2.algorithms.afb; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import frodo2.communication.Message; import frodo2.solutionSpaces.Addable; /** All AFB messages containing a CPA subclass this class * @author Alexandra Olteanu, Thomas Leaute * @param <V> the type used for variable values * @param <U> the type used for utility values */ public abstract class AFBBaseMsg < V extends Addable<V>, U extends Addable<U> > extends Message implements Externalizable { /** The destination variable */ public String dest; /** The partial assignment that is passed over to dest.*/ protected PA<V, U> pa; /// @todo Backtrack messages don't need to contain the CPA. /**Timestamp for the PA the message carries*/ protected Timestamp timestamp; /** Empty constructor used for externalization */ public AFBBaseMsg () { super (); } /** Constructor * @param type The type of the message * @param dest The destination variable * @param pa The current PA * @param timestamp Timestamp for this PA */ protected AFBBaseMsg (String type, String dest, PA<V, U> pa, Timestamp timestamp) { super (type); this.dest = dest; this.pa=pa; this.timestamp=timestamp; } /** @see Message#toString() */ @Override public String toString () { return super.toString() + "\n\t dest: " + dest + "\n\t pa: " + pa + "\n\t timestamp: " + this.timestamp; } /** @see java.io.Externalizable#writeExternal(java.io.ObjectOutput) */ public void writeExternal(ObjectOutput out) throws IOException { super.writeExternal(out); out.writeObject(this.dest); this.pa.writeExternal(out); this.timestamp.writeExternal(out); } /** @see java.io.Externalizable#readExternal(java.io.ObjectInput) */ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { super.readExternal(in); this.dest = (String) in.readObject(); this.pa = new PA<V, U> (); this.pa.readExternal(in); this.timestamp = new Timestamp (); this.timestamp.readExternal(in); } }
Python
UTF-8
932
2.921875
3
[]
no_license
''' Parses LoadProfiles folder. Performs calculation to determine bill befor solar. May be deleted after Genability.py is functional ''' def run(load, rates): #load profile file parsed, rates is a pd data frame of import and export rates date_time = load.getTotalHour() consumption = [] before_solar = [] export_rates = rates["Export Rates"].tolist() import_rates = rates["Import Rates"].tolist() totalHour = 0 #total hour goes from 0 - 8759 inclusive # Parses load file into 4 outputs: date values, electricity consumption values, # bill before solar, and the rates used to calculate while totalHour < 8760: consumption += [load.getElectricity()[totalHour]] rate_value = import_rates[totalHour] before_solar += [float(rate_value * load.getElectricity()[totalHour])] totalHour += 1 return (date_time, consumption, before_solar, import_rates, export_rates)
Markdown
UTF-8
5,249
2.96875
3
[ "MIT" ]
permissive
- [Doctype 作用?标准模式与兼容模式各有什么区别?](#doctype-%e4%bd%9c%e7%94%a8%e6%a0%87%e5%87%86%e6%a8%a1%e5%bc%8f%e4%b8%8e%e5%85%bc%e5%ae%b9%e6%a8%a1%e5%bc%8f%e5%90%84%e6%9c%89%e4%bb%80%e4%b9%88%e5%8c%ba%e5%88%ab) - [Doctype文档解析类型](#doctype%e6%96%87%e6%a1%a3%e8%a7%a3%e6%9e%90%e7%b1%bb%e5%9e%8b) - [HTML5 的 form 如何关闭自动补全功能?](#html5-%e7%9a%84-form-%e5%a6%82%e4%bd%95%e5%85%b3%e9%97%ad%e8%87%aa%e5%8a%a8%e8%a1%a5%e5%85%a8%e5%8a%9f%e8%83%bd) - [iframe 有那些缺点?](#iframe-%e6%9c%89%e9%82%a3%e4%ba%9b%e7%bc%ba%e7%82%b9) - [Label 的作用是什么?是怎么用的?](#label-%e7%9a%84%e4%bd%9c%e7%94%a8%e6%98%af%e4%bb%80%e4%b9%88%e6%98%af%e6%80%8e%e4%b9%88%e7%94%a8%e7%9a%84) - [页面可见性(Page Visibility API) 可以有哪些用途?](#%e9%a1%b5%e9%9d%a2%e5%8f%af%e8%a7%81%e6%80%a7page-visibility-api-%e5%8f%af%e4%bb%a5%e6%9c%89%e5%93%aa%e4%ba%9b%e7%94%a8%e9%80%94) - [如何在页面上实现一个圆形的可点击区域?](#%e5%a6%82%e4%bd%95%e5%9c%a8%e9%a1%b5%e9%9d%a2%e4%b8%8a%e5%ae%9e%e7%8e%b0%e4%b8%80%e4%b8%aa%e5%9c%86%e5%bd%a2%e7%9a%84%e5%8f%af%e7%82%b9%e5%87%bb%e5%8c%ba%e5%9f%9f) - [实现不使用 border 画出 1px 高的线,在不同浏览器的标准模式与怪异模式下都能保持一致的效果。](#%e5%ae%9e%e7%8e%b0%e4%b8%8d%e4%bd%bf%e7%94%a8-border-%e7%94%bb%e5%87%ba-1px-%e9%ab%98%e7%9a%84%e7%ba%bf%e5%9c%a8%e4%b8%8d%e5%90%8c%e6%b5%8f%e8%a7%88%e5%99%a8%e7%9a%84%e6%a0%87%e5%87%86%e6%a8%a1%e5%bc%8f%e4%b8%8e%e6%80%aa%e5%bc%82%e6%a8%a1%e5%bc%8f%e4%b8%8b%e9%83%bd%e8%83%bd%e4%bf%9d%e6%8c%81%e4%b8%80%e8%87%b4%e7%9a%84%e6%95%88%e6%9e%9c) - [其他文件链接](#%e5%85%b6%e4%bb%96%e6%96%87%e4%bb%b6%e9%93%be%e6%8e%a5) - [厂商定制](#%e5%8e%82%e5%95%86%e5%ae%9a%e5%88%b6) ### Doctype 作用?标准模式与兼容模式各有什么区别? DOCTYPE是用来声明文档类型和DTD规范的。 `<!DOCTYPE html>`声明位于HTML文档中的第一行,不是一个HTML标签,处于 html 标签之前。告知浏览器的解析器用什么文档标准解析这个文档。DOCTYPE不存在或格式不正确会导致文档以兼容模式呈现。 标准模式的排版 和 JS 运作模式都是以该浏览器支持的最高标准运行。在兼容模式中,页面以宽松的向后兼容的方式显示,模拟老式浏览器的行为以防止站点无法工作。 在HTML4.01中<!doctype>声明指向一个DTD,由于HTML4.01基于SGML,所以DTD指定了标记规则以保证浏览器正确渲染内容 HTML5不基于SGML,所以不用指定DTD ### Doctype文档解析类型 - 标准模式:页面按照 HTML 与 CSS 的定义渲染 `<!DOCTYPE html>` - 怪异模式模式(默认): 会模拟更旧的浏览器的行为 - 近乎标准模式(已淘汰): 会实施了一种表单元格尺寸的怪异行为(与IE7之前的单元格布局方式一致),除此之外符合标准定义 ### HTML5 的 form 如何关闭自动补全功能? 给不想要提示的 form 或某个 input 设置为 autocomplete=off。 ### iframe 有那些缺点? - iframe 会阻塞主页面的 Onload 事件; - 搜索引擎的检索程序无法解读这种页面,不利于 SEO; - iframe 和主页面共享连接池,而浏览器对相同域的连接有限制,所以会影响页面的并行加载。 使用 iframe 之前需要考虑这两个缺点。如果需要使用 iframe,最好是通过 javascript 动态给 iframe 添加 src 属性值,这样可以绕开以上两个问题。 ### Label 的作用是什么?是怎么用的? label 标签来定义表单控制间的关系,当用户选择该标签时,浏览器会自动将焦点转到和标签相关的表单控件上。 ```html <label for="Name">Number:</label> <input type=“text“name="Name" id="Name"/> <label>Date:<input type="text" name="B"/></label> ``` ### 页面可见性(Page Visibility API) 可以有哪些用途? - 通过 visibilityState 的值检测页面当前是否可见,以及打开网页的时间等; - 在页面被切换到其他后台进程的时候,自动暂停音乐或视频的播放; ### 如何在页面上实现一个圆形的可点击区域? - map+area 或者 svg - border-radius - 纯 js 实现 需要求一个点在不在圆上简单算法、获取鼠标坐标等等 ### 实现不使用 border 画出 1px 高的线,在不同浏览器的标准模式与怪异模式下都能保持一致的效果。 ```html <div style="height:1px;overflow:hidden;background:red"></div> ``` ### 其他文件链接 - CSS 文件:<link rel="stylesheet" type="text/css" href="style.css"> - JavaScript 文件:<script src=“script.js"></script> 但是为了让页面的样子更早的让用户看到,一般把JS文件放到body的底部 ### 厂商定制 同样分享页面到QQ的聊天窗口,有些页面直接就是一个链接,但是有些页面有标题,图片,还有文字介绍。为什么区别这么明显呢?其实就是看有没有设置下面这三个内容 ```html <meta itemprop="name" content="这是分享的标题"/> <meta itemprop="image" content="http://imgcache.qq.com/qqshow/ac/v4/global/logo.png" /> <meta name="description" itemprop="description" content="这是要分享的内容" /> ```
C++
UTF-8
1,845
2.921875
3
[]
no_license
//============================================================================ // Name : // Author : // Version : // Copyright : 2013-4-29 // Description : 广度搜索 hash //============================================================================ #include <iostream> #include <cstring> #include <cstdlib> #include <cstdio> #include <vector> #include <algorithm> #define N 1000 using namespace std; struct e { int val; int d; int c; int num; }; int n,in[N+50]; vector<e> hash[N]; int insert(int val ,int d, int c) { e temp; int idx = ((val % (N -3)) + N - 3) % (N - 3); int pos ; for(pos = 0 ; pos < hash[idx].size() ; ++pos) if(hash[idx][pos].val=val) return ++hash[idx][pos].num; temp.val = val ; temp.d = d ; temp.c = c ; temp.num = 1; hash[idx].push_back(temp); return 1; } int main(int arg,char* argv[]) { e temp; int idx; LA: while(cin>>n&&n!=0) { for(int i = 0; i < n ; ++i) cin>>in[i]; sort(in,in+n,greater<int>()); for(int id = 0; id < n ; ++id) { for(int i = 0; i < N ; ++i) hash[i].clear(); for(int ic = 0 ; ic < n ; ++ic) { if(ic == id) continue; insert(in[id]-in[ic],in[id],in[ic]); } for(int ib = 0 ; ib < n ; ++ib) { if(ib==id) continue; for(int ia = 0 ; ia < n ; ++ia) { if(ia==id) continue; if(ia==ib) continue; idx = (((in[ia] + in[ib] ) %(N -3) ) + (N - 3)) % (N - 3); for(int i = 0 ; i < hash[idx].size();++i) { if(hash[idx][i].val == in[ia] + in[ib]&& hash[idx][i].c != in[ia]&& hash[idx][i].c != in[ib] ) { cout<<in[id]<<endl; goto LA; } } } } } cout<<"no solution"<<endl; } return 0; }
Markdown
UTF-8
8,913
2.984375
3
[]
no_license
![Semantic](http://semantic-ui.com/images/logo.png) # **Semantic UI React** # 【介绍】 Semantic UI React是官方对[Semantic UI](https://semantic-ui.com/)进行的React集成。 - 释放jQuery - 声明式API - Augmentation - Shorthand Props 速记的属性 - Sub Components 子组件 - Auto Controlled State 自动控制状态 安装介绍请移步[使用方法](#【使用方法】) ## **释放jQuery** jQuery是一个DOM操作库。它向DOM读取和写入。React使用虚拟DOM(真实DOM的JavaScript表示)。React只对写补丁来更新DOM,但不会从它读取。 将实际的DOM操作与React的虚拟DOM保持同步是不可行的。因此,所有jQuery函数化的东西都在React中被重新实现。 ## **声明式API** 声明式api提供了健壮的特性和属性验证。 ```html <Rating rating={1} maxRating={5} /> ``` 被渲染为: ```html <div class="ui rating" data-rating="1" data-max-rating="5" > </div> ``` ```html <Button size='small' color='green'> <Icon name='download' /> Download </Button> ``` 被渲染为: ```html <button class="ui small green button"> <i class="download icon"></i> Download </button> ``` ## **Augmentation** 控制渲染的HTML标记,或将一个组件渲染为另一个组件。额外的属性被传递给你正在渲染的组件。 Augmentation是强大的。您可以在不添加额外的嵌套组件的情况下组合组件特性和属性。这对于使用`MenuLinks`和`react-router`是很重要的。 ```html <Header as='h3'> Learn More </Header> ``` 渲染为: ```html <h3 class="ui header"> Learn More </h3> ``` ```js import { Link } from 'react-router-dom' <Menu> <Menu.Item as={Link} to='/home'> Home </Menu.Item> </Menu> ``` 被渲染为: ```html div class="ui menu"> <a class="item" href="/home"> Home </a> </div> ``` ## **Shorthand Props** Shorthand props为您生成标记,使许多用例成为轻而易举的事。所有的对象属性都在子组件上传播。 ### **子对象数组** 带有重复子元素的组件接受普通对象的数组。Facebook喜欢使用context来处理父-子耦合问题,我们也是如此。 ```js const panels = [{ title: 'What is a dog?', content: '...', }, { title: 'What kinds are there?', content: '...', }] <Accordion panels={panels} /> ``` 渲染为: ```html <div class="ui accordion"> <div class="title"> <i class="dropdown icon"></i></i> What is a dog? </div> <div class="content"> <p></p...>...</p> </div> <div class="title"> <i class="dropdown icon"></i></i> What kinds are there? </div> <div class="content"> <p></p...>...</p> </div> </div> ``` ### **icon={...}** `icon` 属性是许多组件的标配。它接受一个Icon名称、一个Icon对象或者是`<Icon/>`实例  ```html <Message success icon='thumbs up' header='Nice job!' content='Your profile is complete.' /> ``` 渲染为: ```html  <div class="ui success message"> <i class="thumbs up icon"></i> <div class="content"> <div class="header"> Nice job! </div> Your profile is complete. </div> </div> ``` ### **image={...}** `image`属性是许多组件的标配。它可以接受一个image `src`,一个image props对象,或者一个`<Image />`实例。 ```JS  <Label image='veronika.jpg' /> Rendered HTML ``` 渲染为: ```html <div class="ui image label"> <img src="veronika.jpg"> </div> ``` ## **子组件** 子组件可以让您完全访问标记。这对于定制组件的灵活性非常重要。 ```html <Message icon> <Icon name='circle notched' loading /> <Message.Content> <Message.Header> Just one second </Message.Header> We're fetching that content for you. </Message.Content> </Message> ``` 渲染 HTML ```html <div class="ui icon message"> <i class="loading circle notched icon"></i> <div class="content"> <div class="header"> Just one second </div> We're fetching that content for you. </div> </div> ``` ## **自动控制State** React[有受控和不受控](http://www.css88.com/react/docs/forms.html#controlled-components)的组件的概念。 我们的有状态组件自我管理它们的状态,而不需要连接。下拉菜单打开,没有连接`onClick`到`open`属性。该值也在内部存储,不需要将`onChange`连接到`value`。 如果您添加了一个`value`属性或一个`open`属性,下拉委托控制一个属性到你的值。其他的属性仍然是自动控制的。混合和匹配任意数量的受控和不受控制的属性。添加或移除属性来在任何时间添加或移除控制。一切都只是工作。 看看我们的[AutoControlledComponent](https://github.com/Semantic-Org/Semantic-UI-React/blob/master/src/lib/AutoControlledComponent.js),看看这是怎么做的。查看文档试着把它试一试。 <hr> # 【使用方法】 ## **javascript** 可以通过NPM来安装Semantic UI React包 ```bash $ yarn add semantic-ui-react $ npm install semantic-ui-react --save ``` 安装Semantic UI React来为你的组件提供JavaScript。你也需要包含一个样式表来为你的组件提供样式。这是组件框架的典型模式,例如Semantic UI或Bootstrap。 您选择在项目中包含样式表的方法将取决于您需要的定制级别。 ### 示例 有关如何导入和使用Semantic UI React的示例,请单击任意示例旁边的代码图标。以下是一些直接链接: - Button - List - Card - Modal ## **CSS** ### **内容分发网络(CDN)** 可以通过在您的`index.html`文件中包含一个Semantic UI CSN连接,来使用默认的Semantic UI样式表。 这是开始使用Semantic UI React的最快方法。您将无法用该方法使用自定义主题。 ```html <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.12/semantic.min.css"></link> ``` ### **Semantic UI CSS 包** Semantic UI CSS包与主Semantic UI库自动同步,提供了一个轻量级的CSS的Semantic UI版本。 可以使用NPM在您的项目中安装一个包。您将无法用该方法使用自定义主题。 ```bash $ npm install semantic-ui-css --save ``` 安装完成后,你需要在你的`index.js`文件中引入这个压缩版的CSS。 ``` import 'semantic-ui-css/semantic.min.css'; ``` ### **Semantic UI package** 安装完整版的Semantic UI包。 Semantic UI包括了Gulp的构建工具,这样您的项目就可以保留自己的主题更改,允许您自定义样式变量。 [这里](https://semantic-ui.com/usage/theming.html)提供了关于 Semantic UI中的主题的详细文档。 ```bash $ yarn add semantic-ui --dev $ npm install semantic-ui --save-dev ``` 在使用Gulp构建项目之后,您需要在`index.js`中包含缩小的CSS文件。 ```js import '../semantic/dist/semantic.min.css'; ``` ## **打包器** Semantic UI React得到了所有现代JavaScript打包器的完整支持。我们它们中的一些做了一些例子。您可以将它们作为您的项目的起点。 #### Webpack 1 Webpack 1完整地支持Semantic UI React,但是我们不建议使用它,因为它是被**弃用**的。请确保您在发布前将您的应用程序在生产模式中进行构建,它将`propTypes`从您的构建中去掉。 由于Webpack 1不支持树握手(shaking),所以我们建议在您的构建中使用`babel-plugin-lodash`。您可以在Semantic UI React的`example`目录中找到示例配置。 [![](https://img.shields.io/badge/Github-Example%20configuration-brightgreen.svg)](https://github.com/Semantic-Org/Semantic-UI-React/tree/master/examples/webpack1) [![](https://img.shields.io/badge/Github-babel--plugin--lodash-brightgreen.svg)](https://github.com/lodash/babel-plugin-lodash) #### Webpack 2 Webpack 2完全支持Semantic UI React,它也支持树握手。请确保您在发布前将您的应用程序构建到生产模式中,它将从您的构建中去除`propTypes`。 >Webpack 2树握手并不能完全消除未使用的导出,有很多问题都是长期存在: > >[webpack/webpack#1750](https://github.com/webpack/webpack/issues/1750)<br> [webpack/webpack#2867](https://github.com/webpack/webpack/issues/2867)<br> [webpack/webpack#2899](https://github.com/webpack/webpack/issues/2899)<br> [webpack/webpack#3092](https://github.com/webpack/webpack/issues/3092)<br> > >Semantic UI React imports不会被优化,所以我们建议在您的构建中使用`babel-plugin-lodash`。您可以在示例目录中找到示例配置。 [![](https://img.shields.io/badge/Github-Example%20configuration-brightgreen.svg)](https://github.com/Semantic-Org/Semantic-UI-React/tree/master/examples/webpack2) [![](https://img.shields.io/badge/Github-babel--plugin--lodash-brightgreen.svg)](https://github.com/lodash/babel-plugin-lodash) <hr> ## 详细教程 [访问官网](https://react.semantic-ui.com/introduction)
JavaScript
UTF-8
2,428
3.890625
4
[]
no_license
//create a student object const student = { name: "Abhishek Saran", sclass:"VI", rollno:12 }; const library =[ { author:"Bill Gates", title:"The Road Ahead", readingStatus:true }, { author:"Steve Jobs", title:"Walter Isaacson", readingStatus:true }, { author:"Suzanne Collins", title:"Mockingjay", readingStatus:false } ]; function listObject(object){ for(let property in object){ console.log(property +" -> "+ object[property]); } } function deleteRollno(object){ console.log("Before deleting-"); console.log(object); delete object.rollno; console.log("After deleting-"); console.log(object); } function getLength(object){ return Object.keys(object).length; } function readingStatus(object){ for(let book of library){ for( let property in book){ console.log(property +" -> "+ book[property]); } console.log(); } } cylinder={ set setRadius(radius){ this.r = radius; }, set setHeight(height){ this.h = height; }, calVolume: function(){ volume = Math.PI*this.r*this.r*this.h; this.volume = volume.toFixed(4); }, get getVolume(){ this.calVolume(); return this.volume; } } const library2 =[ { author:"Bill Gates", title:"The Road Ahead", readingStatus:true }, { author:"Suzanne Collins", title:"Mockingjay", readingStatus:true }, { author:"Steve Jobs", title:"Walter Isaacson", readingStatus:false } ]; console.log("Testing..."); console.log("\n1. List properties of student object:"); listObject(student); console.log("\n2. Deleting roll no property of student object:"); deleteRollno(student); console.log("\n3. The length of the student object is: "+ getLength(student)); console.log("\n4. Display the reading status of library books:"); readingStatus(library); console.log("\n5.To calculate volume for the cylinder, set radius and height:"); cylinder.setRadius = 2.3; cylinder.setHeight = 4.3; console.log("The volume of the cylinder is: "+cylinder.getVolume); console.log("\n6. Sort the array of objects (library):"); console.log("Before sorting-") console.log(library2); //sorting objects by authors, then titles and finally by reading status. library2.sort(function(objA, objB){ if(objA.author === objB.author){ if(objA.title === objB.title){ if(objA.readingStatus) return false; else return true; } else return objA.title.localeCompare(objB.title); } else return objA.author.localeCompare(objB.author); }); console.log("After sorting-") console.log(library2);
C#
UTF-8
1,979
3.453125
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _07.Sentence_the_Thief { class Program { static void Main(string[] args) { string idNumeralType = Console.ReadLine(); int idCount = int.Parse(Console.ReadLine()); long id = 0; long thiefID= long.MinValue; for (int i = 0; i < idCount; i++) { id = long.Parse(Console.ReadLine()); switch (idNumeralType) { case "sbyte": if (id<=sbyte.MaxValue&&thiefID<=id) { thiefID = id; } break; case "int": if (id <= int.MaxValue && thiefID <= id) { thiefID = id; } break; case "long": if (id <= long.MaxValue && thiefID <= id) { thiefID = id; } break; default: break; } } decimal thiefSentence = 0; if (thiefID>0) { thiefSentence = (decimal)thiefID / sbyte.MaxValue; } else { thiefSentence = Math.Abs((decimal)thiefID / sbyte.MinValue); } if (thiefSentence <=1) { Console.WriteLine($"Prisoner with id {thiefID} is sentenced to {Math.Ceiling(thiefSentence)} year"); } else { Console.WriteLine($"Prisoner with id {thiefID} is sentenced to {Math.Ceiling(thiefSentence)} years"); } } } }
Java
UTF-8
10,073
2.1875
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * pantalla2.java * * Created on 04-ene-2015, 0:23:39 */ package com.blogspot.rolandopalermo.sockets; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Wolfang M Salazar S */ public class pantalla2 extends javax.swing.JFrame { private String ip = "192.168.2.10"; /** Creates new form pantalla2 */ public pantalla2() { initComponents(); this.setSize(1150, 690); this.setLocation(200, 10); setLocationRelativeTo(null); setVisible(true); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel2 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jTextField2 = new javax.swing.JTextField(); jTextField1 = new javax.swing.JTextField(); jButton5 = new javax.swing.JButton(); jLabel12 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jButton2 = new javax.swing.JButton(); jButton1 = new javax.swing.JButton(); jLabel5 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jButton4 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); getContentPane().setLayout(null); jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blogspot/rolandopalermo/sockets/logo unexpo4.png"))); // NOI18N getContentPane().add(jLabel2); jLabel2.setBounds(10, 0, 210, 180); jLabel4.setBackground(new java.awt.Color(255, 255, 255)); jLabel4.setFont(new java.awt.Font("Arial", 1, 30)); jLabel4.setForeground(new java.awt.Color(255, 255, 255)); jLabel4.setText(" Estación Local ERO"); getContentPane().add(jLabel4); jLabel4.setBounds(210, 110, 370, 70); jTextField2.setBackground(new java.awt.Color(153, 153, 153)); jTextField2.setFont(new java.awt.Font("Tahoma", 3, 18)); jTextField2.setText(" Transmisión "); getContentPane().add(jTextField2); jTextField2.setBounds(700, 550, 160, 30); jTextField1.setBackground(new java.awt.Color(153, 153, 153)); jTextField1.setFont(new java.awt.Font("Tahoma", 3, 18)); jTextField1.setText(" Recepción"); getContentPane().add(jTextField1); jTextField1.setBounds(700, 600, 160, 30); jButton5.setBackground(new java.awt.Color(255, 51, 0)); jButton5.setFont(new java.awt.Font("Tahoma", 1, 14)); jButton5.setForeground(new java.awt.Color(255, 255, 255)); jButton5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blogspot/rolandopalermo/sockets/boton2.png"))); // NOI18N jButton5.setText("ATRAS"); jButton5.setBorder(null); jButton5.setContentAreaFilled(false); jButton5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton5ActionPerformed(evt); } }); getContentPane().add(jButton5); jButton5.setBounds(10, 570, 150, 70); jLabel12.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blogspot/rolandopalermo/sockets/bombillo.gif"))); // NOI18N getContentPane().add(jLabel12); jLabel12.setBounds(180, 310, 10, 10); jLabel11.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blogspot/rolandopalermo/sockets/bombillo.gif"))); // NOI18N getContentPane().add(jLabel11); jLabel11.setBounds(950, 400, 10, 10); jLabel9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blogspot/rolandopalermo/sockets/bombillo.gif"))); // NOI18N getContentPane().add(jLabel9); jLabel9.setBounds(220, 340, 10, 10); jLabel8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blogspot/rolandopalermo/sockets/bombillo.gif"))); // NOI18N getContentPane().add(jLabel8); jLabel8.setBounds(960, 390, 10, 10); jLabel7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blogspot/rolandopalermo/sockets/bombillo.gif"))); // NOI18N getContentPane().add(jLabel7); jLabel7.setBounds(900, 430, 10, 10); jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blogspot/rolandopalermo/sockets/bombillo.gif"))); // NOI18N getContentPane().add(jLabel10); jLabel10.setBounds(190, 320, 10, 10); jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blogspot/rolandopalermo/sockets/animacion.gif"))); // NOI18N getContentPane().add(jLabel6); jLabel6.setBounds(390, 220, 290, 210); jButton2.setFont(new java.awt.Font("Tahoma", 3, 18)); jButton2.setText("Recepción"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); getContentPane().add(jButton2); jButton2.setBounds(250, 530, 160, 30); jButton1.setFont(new java.awt.Font("Tahoma", 3, 18)); jButton1.setText("Transmisión "); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); getContentPane().add(jButton1); jButton1.setBounds(250, 480, 160, 30); jLabel5.setFont(new java.awt.Font("Arial", 1, 30)); jLabel5.setText(" Estación Remota ERC"); getContentPane().add(jLabel5); jLabel5.setBounds(610, 180, 370, 50); jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blogspot/rolandopalermo/sockets/LOGOS4 - copia.png"))); // NOI18N getContentPane().add(jLabel3); jLabel3.setBounds(870, -10, 370, 170); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blogspot/rolandopalermo/sockets/pantallas_ondas.png"))); // NOI18N getContentPane().add(jLabel1); jLabel1.setBounds(0, 0, 1150, 690); jButton4.setBackground(new java.awt.Color(255, 51, 0)); jButton4.setFont(new java.awt.Font("Tahoma", 1, 14)); jButton4.setForeground(new java.awt.Color(255, 255, 255)); jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blogspot/rolandopalermo/sockets/boton2.png"))); // NOI18N jButton4.setText("ATRAS"); jButton4.setBorder(null); jButton4.setContentAreaFilled(false); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); getContentPane().add(jButton4); jButton4.setBounds(0, 560, 150, 70); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed pantalla1 PT = new pantalla1(); PT.setVisible(true); dispose(); }//GEN-LAST:event_jButton4ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed Acceder2Frames AF = new Acceder2Frames(ip); AF.iniciarCaptura(); AF.ejecutarCliente(); this.dispose(); }//GEN-LAST:event_jButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed Thread hilo = new Thread() { @Override public void run() { Server PT = new Server(); PT.ejecutarServidor(); } }; hilo.start(); dispose(); }//GEN-LAST:event_jButton2ActionPerformed private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed pantalla1 PT = new pantalla1(); PT.setVisible(true); dispose(); }//GEN-LAST:event_jButton5ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new pantalla2().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton4; private javax.swing.JButton jButton5; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; // End of variables declaration//GEN-END:variables }
Java
UTF-8
6,314
2.578125
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package db; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.swing.JComboBox; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; /** * * @author Эдик */ public class Commodity_type { private static final String URL = "jdbc:postgresql://localhost:5432/commodities"; private static final String USERNAME = "postgres"; private static final String PASSWORD = "postgres"; private Connection connection; public Commodity_type() { try { connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); } catch(SQLException e) { e.printStackTrace(); } } public Connection getConnection(){return connection;} public void setConnection(Connection connection){this.connection = connection;} public void AddCommodity_type(String name, String producer, String unit) throws ClassNotFoundException { Class.forName("org.postgresql.Driver"); try(Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); Statement statement = (Statement) connection.createStatement()) { ResultSet rs = null; rs = statement.executeQuery("SELECT id " + "FROM producers " + "WHERE name = '"+producer+"';"); Long id_producer = null; while (rs.next()) { id_producer = rs.getLong("id"); } statement.executeUpdate("INSERT INTO commodity_types(name, id_producer, unit) VALUES " + "('"+name+"', "+id_producer+", '"+unit+"');"); } catch (SQLException e) { e.printStackTrace(); } } public void GetAllCommodity_types(JTable table) throws ClassNotFoundException { Class.forName("org.postgresql.Driver"); table.setModel(new javax.swing.table.DefaultTableModel( new Object [][] {}, new String [] { "Наименование", "Производитель", "Измерение" } )); try(Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); Statement statement = (Statement) connection.createStatement()) { ResultSet rs = null; rs = statement.executeQuery("SELECT comm.name as commname, p.name as producername, " + "comm.unit " + "FROM commodity_types comm JOIN producers p " + "ON comm.id_producer = p.id ORDER BY comm.name;"); DefaultTableModel model = (DefaultTableModel) table.getModel(); model.setRowCount(0); while (rs.next()) { model.addRow(new Object[]{rs.getString("commname"), rs.getString("producername"), rs.getString("unit")}); } } catch (SQLException e) { e.printStackTrace(); } } public void DeleteCommodity_type(JTable table) throws ClassNotFoundException { Class.forName("org.postgresql.Driver"); Object name = (Object)table.getValueAt(table.getSelectedRow(), 0); Object producer = (Object)table.getValueAt(table.getSelectedRow(), 1); try(Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); Statement statement = (Statement) connection.createStatement()) { ResultSet rs = null; rs = statement.executeQuery("SELECT id " + "FROM producers " + "WHERE name = '"+producer+"';"); Long id_producer = null; while (rs.next()) { id_producer = rs.getLong("id"); } statement.executeUpdate("DELETE FROM commodity_types WHERE name = '"+name+"' " + "AND id_producer = "+id_producer+";"); } catch (SQLException e) { e.printStackTrace(); } } public void UpdateCommodity_type(JTable table, String name, String producer, String unit) throws ClassNotFoundException { Class.forName("org.postgresql.Driver"); Object value = (Object)table.getValueAt(table.getSelectedRow(), 0); try(Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); Statement statement = (Statement) connection.createStatement()) { Object prod = (Object)table.getValueAt(table.getSelectedRow(), 1); ResultSet rs = null; rs = statement.executeQuery("SELECT id " + "FROM producers " + "WHERE name = '"+prod+"';"); Long id_producer = null; while (rs.next()) { id_producer = rs.getLong("id"); } statement.executeUpdate("UPDATE commodities SET name = '"+name+"', " + "id_producer = "+id_producer+", unit = '"+unit+"' WHERE name = " + "'"+value+"' AND id_producer = "+id_producer+";"); } catch (SQLException e) { e.printStackTrace(); } } public void GetAllComodityNames(JComboBox combobox) throws ClassNotFoundException { Class.forName("org.postgresql.Driver"); combobox.removeAllItems(); combobox.addItem(""); try(Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); Statement statement = (Statement) connection.createStatement()) { ResultSet rs = null; rs = statement.executeQuery("SELECT name FROM commodity_types ORDER BY name;"); while (rs.next()) { combobox.addItem(rs.getString("name")); } } catch (SQLException e) { e.printStackTrace(); } } }
PHP
UTF-8
1,986
2.984375
3
[ "MIT" ]
permissive
<?php /** * AutocompleteAttribute * * autocomplete attribute representation Class * * * @category html5 * @author <a href="mailto:seif.salah@gmail.com">sasedev</a> * @license MIT * @copyright <a href="https://sasedev.net">sasedev</a> 2017 */ namespace Sase\Commons\Htmlmodel\Attribute\Input; use Sase\Commons\Htmlmodel\AbstractAttribute; use Sase\Commons\Htmlmodel\Enum\AutocompleteEnum; /** * AutocompleteAttribute * <p> * The autocomplete attribute specifies whether or not an input field should have autocomplete enabled.<br> * Autocomplete allows the browser to predict the value.<br> * When a user starts to type in a field, the browser should display options to fill in the field, based on earlier typed values.<br> * Note: The autocomplete attribute works with the following &lt;input&gt; types: text, search, url, tel, email, password, datepickers, range, and color.<br> * Tip: In some browsers you may need to activate an autocomplete function for this to work (Look under "Preferences" in the browser's menu). * </p> * <p> * Browser Support: * <ul> * <li>Chrome: 17.0</li> * <li>Internet Explorer: 5.0</li> * <li>Firefox: 4.0</li> * <li>Opera: 9.6</li> * <li>Safari: 5.2</li> * </ul> * </p> * * @author <a href="mailto:seif.salah@gmail.com">sasedev</a> */ class AutocompleteAttribute extends AbstractAttribute { /** * Name of html attribute * * @var string KEY = "autocomplete" */ protected $KEY = "autocomplete"; /** * Set $value * * @param AutocompleteEnum $value * * @return AutocompleteAttribute */ public function setValue($value) { if (!$value instanceof AutocompleteEnum) { throw new \Exception("use Sase\Commons\Htmlmodel\Enum\AutocompleteEnum value"); } return parent::setValue($value->getValue()); } /** * check the list of html elements that can add this Attribute * * @return string[] */ public function getAppliesTo() { $coveredElements = array( 'input' ); return $coveredElements; } }
Markdown
UTF-8
1,470
2.765625
3
[]
no_license
# 访问KafkaManager的WebUI<a name="ZH-CN_TOPIC_0173178872"></a> 用户可以通过KafkaManager的WebUI,在图形化界面监控管理Kafka集群。 ## 前提条件<a name="section3181241161011"></a> - 已安装KafkaManager服务的集群。 - 获取用户“admin”帐号密码。“admin”密码在创建MRS集群时由用户指定。 ## 访问KafkaManager的WebUI<a name="section16790101115"></a> 1. 登录集群详情页面,选择“组件管理 \> KafkaManager”。 >![](public_sys-resources/icon-note.gif) **说明:** >- 若集群详情页面没有“组件管理”页签,请先完成IAM用户同步(在集群详情页的“概览”页签,单击“IAM用户同步“右侧的“点击同步”进行IAM用户同步)。 >- 针对MRS 1.8.10及之前版本,登录MRS Manager页面,具体请参见[访问MRS Manager](访问MRS-Manager.md),然后选择“服务管理”。 2. 在KafkaManager概述的“KafkaManager WebUI“中单击任意一个UI链接,打开KafkaManager的WebUI页面。 KafkaManager的WebUI支持查看以下信息: - Kafka集群列表 - Kafka集群Broker节点列表和Metric监控 - Kafka集群副本监控 - Kafka集群Consumer监控 >![](public_sys-resources/icon-note.gif) **说明:** >在KafkaManager的任何子页面单击左上角KafkaManager的Logo都可以回到KafkaManager的WebUI主界面,显示集群列表信息。
Python
UTF-8
151
3.640625
4
[]
no_license
Name = input ( 'Enter you name :' ) # taking the name of the user print(f'GOOD MORNING {Name}') # printing a greeting message using a formatted string
Ruby
UTF-8
184
3.046875
3
[]
no_license
require 'pry' # create a mathematics.factorial(5) = 120 # loop multiply togethar # get the answer class Mathematics def Mathematics.fact(n) (1..n).to_a.inject(:*) end end
TypeScript
UTF-8
11,542
2.640625
3
[]
no_license
module AgileObjects.BoardGameEngine.Pieces { var _none = new Array<IPieceInteraction>(0); export class PieceInteractionMonitor { private _currentlyChosenPiece: Piece; private _currentlyHighlightedPiece: Piece; private _pieceHighlightTimeouts: Array<ng.IPromise<any>>; private _currentlySelectedPiece: Piece; private _currentPotentialInteractions: Array<IPieceInteraction>; private _interactionHandled: boolean; constructor(private _timeoutService: ng.ITimeoutService, private _game: G.Game) { this._subscribeToGameEvents(); this._pieceHighlightTimeouts = new Array<ng.IPromise<any>>(); this._currentPotentialInteractions = _none; } private _subscribeToGameEvents(): void { this._game.events.pieceSelected.subscribe(piece => this._showPotentialInteractionsAfterDelay(piece)); this._game.events.locationSelected.subscribe(location => this._handleLocationSelected(location)); this._game.events.pieceMoving.subscribe(piece => this._showPotentialInteractionsImmediately(piece)); this._game.events.pieceDeselected.subscribe(location => this._handleInteractionEnded(location)); this._game.events.turnEnded.subscribe(() => this._clearCurrentPieces()); } private _showPotentialInteractionsAfterDelay(piece: Piece): boolean { this._interactionHandled = false; this._currentlyChosenPiece = piece; this._pieceHighlightTimeouts.push(this._timeoutService(() => { if (piece === this._currentlyChosenPiece) { this._currentlyHighlightedPiece = this._currentlyChosenPiece; this._showPotentialInteractionsFor(this._currentlyHighlightedPiece); } }, 500)); return true; } private _showPotentialInteractionsImmediately(piece: Piece): boolean { if (this._currentlyChosenPieceHasNoInteractions()) { return false; } this._clearHighlightTimeouts(); this._showPotentialInteractionsFor(piece); return true; } private _showPotentialInteractionsFor(piece: Piece): void { var potentialInteractions = this._tryGetPotentialInteractionsFor(piece); if (!potentialInteractions) { return; } this._clearCurrentPotentialInteractions(); this._populatePotentialInteractionsFrom(<Ts.IStringDictionary<IPieceInteraction>>potentialInteractions); var interactionsByLocation = new TypeScript.Dictionary<IPieceLocation, Array<IPieceInteraction>>(); var i; for (i = 0; i < this._currentPotentialInteractions.length; i++) { var potentialInteraction = this._currentPotentialInteractions[i]; interactionsByLocation .getOrAdd(potentialInteraction.location,() => new Array<IPieceInteraction>()) .push(potentialInteraction); } for (i = 0; i < interactionsByLocation.count; i++) { interactionsByLocation.keys[i].potentialInteractions(interactionsByLocation.values[i]); } } private _tryGetPotentialInteractionsFor(piece: Piece): Ts.IStringDictionary<IPieceInteraction>|boolean { var potentialInteractions = piece.interactionProfile.getPotentialInteractions(); for (var i in potentialInteractions) { return potentialInteractions; } return false; } private _populatePotentialInteractionsFrom(potentialInteractions: Ts.IStringDictionary<IPieceInteraction>): void { this._currentPotentialInteractions = new Array<IPieceInteraction>(); for (var interactionId in potentialInteractions) { this._currentPotentialInteractions.push(potentialInteractions[interactionId]); } } private _cancelPieceHighlighting(): void { this._clearCurrentPotentialInteractions(); this._currentlyHighlightedPiece = undefined; if (this._pieceIsSelected()) { this._currentlyChosenPiece = this._currentlySelectedPiece; this._showPotentialInteractionsFor(this._currentlySelectedPiece); } } private _clearCurrentPotentialInteractions(): void { while (this._currentPotentialInteractions.length > 0) { var potentialInteraction = this._currentPotentialInteractions.shift(); for (var i = 0; i < potentialInteraction.path.length; i++) { potentialInteraction.path[i].potentialInteractions(_none); } } } private _handleLocationSelected(location: IPieceLocation): boolean { if (this._currentlySelectedPiece === undefined) { return false; } return this._completeMovementInteraction(location,() => false); } private _handleInteractionEnded(location: IPieceLocation): boolean { if (this._interactionHandled) { return true; } this._interactionHandled = true; this._clearHighlightTimeouts(); if (location.contains(this._currentlyChosenPiece)) { if (this._pieceHighlightingIsActive()) { this._cancelPieceHighlighting(); return true; } return this._handlePieceClick(location); } return this._handlePieceMove(location); } private _clearHighlightTimeouts(): void { while (this._pieceHighlightTimeouts.length > 0) { this._timeoutService.cancel(this._pieceHighlightTimeouts.shift()); } } private _pieceHighlightingIsActive(): boolean { return this._currentlyHighlightedPiece !== undefined; } private _handlePieceClick(location: IPieceLocation): boolean { var isPieceOwned = this._currentlyChosenPiece.team.isLocal(); var isPieceFromCurrentTeam = this._game.status.turnManager.currentTeam.owns(this._currentlyChosenPiece); if (isPieceFromCurrentTeam) { if (!isPieceOwned) { // You've clicked on an enemy Piece during that Piece's Team's turn: return false; } if (this._currentlyChosenPieceHasNoInteractions()) { return false; } // You've clicked on one of your Pieces during your turn... if (this._pieceIsSelected()) { this._deselectCurrentlySelectedPiece(); return true; } this._selectCurrentlyChosenPiece(); return true; } // You've clicked on a Piece whose Team does not have the current turn... if (isPieceOwned) { // You've clicked on one of your own Pieces but it's not the turn of that Piece's Team: return false; } var validEnemyPieceChosen = false; this._completeInteractionAt(location,() => { // You've clicked on an enemy Piece who was a valid attack target: validEnemyPieceChosen = true; this._currentlyChosenPiece = this._currentlySelectedPiece; return true; }); // ReSharper disable once ExpressionIsAlwaysConst return validEnemyPieceChosen; } private _deselectCurrentlySelectedPiece(): void { this._deselect(this._currentlySelectedPiece); this._currentlySelectedPiece = undefined; } private _deselect(piece: Piece): void { this._clearCurrentPotentialInteractions(); piece.location.isSelected(false); } private _currentlyChosenPieceHasNoInteractions(): boolean { return !!!this._tryGetPotentialInteractionsFor(this._currentlyChosenPiece); } private _selectCurrentlyChosenPiece(): void { this._deselectCurrentlySelectedPieceIfRequired(); this._currentlySelectedPiece = this._currentlyChosenPiece; this._currentlySelectedPiece.location.isSelected(true); this._showPotentialInteractionsFor(this._currentlySelectedPiece); } private _deselectCurrentlySelectedPieceIfRequired(): void { if (this._pieceIsSelected()) { this._deselectCurrentlySelectedPiece(); } } private _handlePieceMove(destination: IPieceLocation): boolean { if (this._currentPotentialInteractions.length === 0) { var potentialInteractions = this._tryGetPotentialInteractionsFor(this._currentlyChosenPiece); if (!potentialInteractions) { return false; } this._populatePotentialInteractionsFrom(<Ts.IStringDictionary<IPieceInteraction>>potentialInteractions); } this._completeMovementInteraction(destination, interaction => { return this._selectedPieceDraggedOntoEnemyPieceButNotMoved(interaction.location); }); return true; } private _completeMovementInteraction( destination: IPieceLocation, refreshInteractions: (interaction: IPieceInteraction) => boolean): boolean { var pieceMoveCompleted; this._completeInteractionAt(destination, interaction => { pieceMoveCompleted = interaction.location.contains(this._currentlyChosenPiece); return refreshInteractions(interaction); }); // ReSharper disable once ConditionIsAlwaysConst // ReSharper disable once HeuristicallyUnreachableCode if (pieceMoveCompleted) { this._clearCurrentPotentialInteractions(); } return pieceMoveCompleted; } private _completeInteractionAt( location: IPieceLocation, refreshInteractions: (interaction: IPieceInteraction) => boolean): void { for (var i = 0; i < this._currentPotentialInteractions.length; i++) { var interaction = this._currentPotentialInteractions[i]; if (interaction.location.contains(location)) { interaction.complete(); if (refreshInteractions(interaction)) { this._showPotentialInteractionsFor(this._currentlyChosenPiece); } return; } } } private _selectedPieceDraggedOntoEnemyPieceButNotMoved(destination: IPieceLocation) { return this._pieceIsSelected() && destination.isOccupied() && !this._game.status.turnManager.currentTeam.owns(destination.piece) && !destination.contains(this._currentlyChosenPiece); } private _pieceIsSelected(): boolean { return this._currentlySelectedPiece !== undefined; } private _clearCurrentPieces(): boolean { if (this._pieceHighlightingIsActive()) { this._currentlyHighlightedPiece = undefined; } this._deselectCurrentlySelectedPieceIfRequired(); return true; } } }
Python
UTF-8
791
2.796875
3
[]
no_license
import smtplib from email.mime.text import MIMEText from email.header import Header import json #sendmal(title,content) def sendmail(title="Test Mail from Python",content="Hello Python SMTP Mail"): #load config dict from file:config.json with open('config.json','r') as f: con_dict=json.loads(f.read()) print(con_dict) server=con_dict['server'] sender=con_dict['sender'] password=con_dict['password'] receivers=con_dict['receivers'] print(receivers) msg=MIMEText(content) msg['Subject']=Header(title,'utf-8') msg['From']=sender msg['To']=receivers smtp=smtplib.SMTP(server) smtp.login(sender,password) smtp.sendmail(sender,receivers.split(','),msg.as_string()) smtp.quit() if __name__ == "__main__": sendmail()
C#
UTF-8
358
3.296875
3
[]
no_license
public static int[] SplitAsIntSafe (this string delimitedString, char splitChar) { int parsed; string[] split = delimitedString.Split(new char[1] { ',' }); List<int> numbers = new List<int>(); for (var i = 0; i < split.Length; i++) { if (int.TryParse(split[i], out parsed)) numbers.Add(parsed); } return numbers.ToArray(); }
C++
UTF-8
1,679
2.96875
3
[]
no_license
#include <evlist.hh> evlist::evlist(void) { this->_disp=0; } evlist::evlist(const evlist &_evlist) { this->_list=_evlist._list; this->_disp=this->_disp; } evlist& evlist::operator=(const evlist &_evlist) { this->_list=_evlist._list; this->_disp=this->_disp; return(*this); } evlist::~evlist(void) { this->_list.clear(); } void evlist::push(const std::shared_ptr<event> &_event) { this->_list.insert(_event); } std::shared_ptr<event> evlist::top(void) { if(this->empty()) return(nullptr); evlist_t::iterator it=this->_list.begin(); std::advance(it,this->_disp); return(*it); } void evlist::pop(void) { this->_disp++; } bool evlist::empty(void) { if(this->_list.empty() || this->_disp>=this->_list.size()) return(true); return(false); } void evlist::move(const int &_disp) { this->_disp=_disp; } void evlist::remove(const std::shared_ptr<event> &_e) { auto it=std::find_if(this->_list.begin(),this->_list.end(),[&_e](const std::shared_ptr<event> &_i)->bool{return((*_i)==(*_e));}); this->remove(std::distance(this->_list.begin(),it)); } void evlist::remove(const int &_position) { if(_position==this->_list.size()) return; evlist_t::iterator it=this->_list.begin(); std::advance(it,_position); this->_list.erase(it); if(_position<this->_disp) --this->_disp; } int evlist::less_than(const double &_time) { //int position=this->_disp; int position=0; evlist_t::iterator it=this->_list.begin(); //std::advance(it,this->_disp); for(; it!=this->_list.end() && (*it)->time(EXECUTION)<_time; ++it,++position); return(--position); }
Java
UTF-8
1,433
2.4375
2
[]
no_license
package model; import java.util.Date; public class Product { private int productId; private String buyCcy; private String sellCcy; private double quantity; private double settlementAmount; private double fxRate; private Date settlementDate; private Date expiryDate; public int getProductId() { return productId; } public void setProductId(int productId) { this.productId = productId; } public String getBuyCcy() { return buyCcy; } public void setBuyCcy(String buyCcy) { this.buyCcy = buyCcy; } public String getSellCcy() { return sellCcy; } public void setSellCcy(String sellCcy) { this.sellCcy = sellCcy; } public double getQuantity() { return quantity; } public void setQuantity(double quantity) { this.quantity = quantity; } public double getSettlementAmount() { return settlementAmount; } public void setSettlementAmount(double settlementAmount) { this.settlementAmount = settlementAmount; } public double getFxRate() { return fxRate; } public void setFxRate(double fxRate) { this.fxRate = fxRate; } public Date getSettlementDate() { return settlementDate; } public void setSettlementDate(Date settlementDate) { this.settlementDate = settlementDate; } public Date getExpiryDate() { return expiryDate; } public void setExpiryDate(Date expiryDate) { this.expiryDate = expiryDate; } }
Java
UTF-8
5,214
2.734375
3
[]
no_license
package org.dao; import org.config.PostgresConnector; import org.model.Address; import org.model.People; import java.sql.*; import java.util.ArrayList; import java.util.List; public class UserInfoDao { public List<People> getPeopleInfo(){ List<People> peopleList = new ArrayList<>(); try (Connection connection = PostgresConnector.getConnection(); Statement statement = connection.createStatement()){ ResultSet resultSet = statement.executeQuery("SELECT * FROM peopleses"); while (resultSet.next()){ int id = resultSet.getInt("id"); String name = resultSet.getString("name"); String surname = resultSet.getString("surname"); int age = resultSet.getInt("age"); People people = People.builder() .id(id) .name(name) .surname(surname) .age(age) .build(); peopleList.add(people); } } catch (SQLException e) { e.printStackTrace(); } return peopleList; } public void updatePeoples(int id, People people){ String query = "UPDATE peopleses SET name = ?, surname = ?, age = ? WHERE id = ? "; try (Connection connection = PostgresConnector.getConnection(); PreparedStatement prepareStatement = connection.prepareStatement(query)){ prepareStatement.setString(1, people.getName()); prepareStatement.setString(2, people.getSurname()); prepareStatement.setInt(3, people.getAge()); prepareStatement.setInt(4, people.getId()); if (prepareStatement.executeUpdate() > 1) { throw new RuntimeException(); } } catch (SQLException e) { e.printStackTrace(); } } public void deletePeoples(People people){ String query = "DELETE FROM peopleses WHERE name = ? "; try (Connection connection = PostgresConnector.getConnection(); PreparedStatement prepareStatement = connection.prepareStatement(query)){ prepareStatement.setString(1, people.getName()); prepareStatement.setString(2, people.getSurname()); prepareStatement.setInt(3, people.getAge()); if (prepareStatement.executeUpdate() > 1) { throw new RuntimeException(); } } catch (SQLException e) { e.printStackTrace(); } } public void add(People people){ String query = "INSERT INTO peopleses (name, surname, age) VALUES(?,?,?)"; try (Connection connection = PostgresConnector.getConnection(); PreparedStatement prepareStatement = connection.prepareStatement(query)){ prepareStatement.setString(1, people.getName()); prepareStatement.setString(2, people.getSurname()); prepareStatement.setInt(3, people.getAge()); if (prepareStatement.executeUpdate() > 1) { throw new RuntimeException(); } } catch (SQLException e) { e.printStackTrace(); } } public List<People> getPeopleBySurname(String surname, int id){ List<People> peopleList = new ArrayList<>(); String query = "SELECT * FROM peopleses WHERE surname = ? and id = ?"; try (Connection connection = PostgresConnector.getConnection(); PreparedStatement statement = connection.prepareStatement(query)){ statement.setString(1, surname); statement.setInt(2, id); ResultSet resultSet = statement.executeQuery(); while (resultSet.next()){ int id1 = resultSet.getInt("id"); String name = resultSet.getString("name"); String surname1 = resultSet.getString("surname"); int age = resultSet.getInt("age"); People people = People.builder() .id(id) .name(name) .surname(surname) .age(age) .build(); peopleList.add(people); } } catch (SQLException e) { e.printStackTrace(); } return peopleList; } public List<Address> getAddressInfo(){ List<Address> addressList = new ArrayList<>(); try (Connection connection = PostgresConnector.getConnection(); Statement statement = connection.createStatement()){ ResultSet resultSet = statement.executeQuery("SELECT * FROM adres_people"); while (resultSet.next()){ int id = resultSet.getInt("id"); String adress = resultSet.getString("adress"); Address address = Address.builder() .id(id) .address(adress) .build(); addressList.add(address); } } catch (SQLException e) { e.printStackTrace(); } return addressList; } }
C++
UTF-8
2,262
2.96875
3
[]
no_license
// // Created by Melodies Sim on 26/6/21. // Reference: https://www.geeksforgeeks.org/socket-programming-cc/ // #include <unistd.h> #include <stdio.h> #include <sys/socket.h> #include <stdlib.h> #include <netinet/in.h> #include <string.h> #define PORT 8080 int main(int argc, char const *argv[]) { int server_fd, new_socket, valread; struct sockaddr_in address; int addrlen = sizeof(address); int opt = 1; char buffer[1024] = {0}; const char *hello = "Hello from server"; // Create socket file descriptor if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) { perror("socket failed"); exit(EXIT_FAILURE); } // Optional step: enable reuse of address and port // https://stackoverflow.com/questions/14388706/how-do-so-reuseaddr-and-so-reuseport-differ if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) && setsockopt(server_fd, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt))) { perror("setsockopt"); exit(EXIT_FAILURE); } address.sin_family = AF_INET; // Bind server to localhost address.sin_addr.s_addr = INADDR_ANY; // converts the unsigned short integer from host byte order // to network byte order address.sin_port = htons(PORT); // Forcefully attaching socket to the port 8080 if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) { perror("bind failed"); exit(EXIT_FAILURE); } // The backlog, defines the maximum length to which // the queue of pending connections for sockfd may grow // If a connection request arrives when the queue is full, // the client may receive an error with an indication of ECONNREFUSED if (listen(server_fd, 3) < 0) { perror("listen failed"); exit(EXIT_FAILURE); } // TODO: Make this into epoll / multi-threaded if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) <0) { perror("accept failed"); exit(EXIT_FAILURE); } valread = read(new_socket, buffer, 1024); printf("%s\n", buffer); send(new_socket, hello, strlen(hello), 0); printf("Hello message sent\n"); return 0; }
Swift
UTF-8
375
2.671875
3
[ "MIT" ]
permissive
public struct Lock { private let nslock: NSLock public init() { self.nslock = .init() } public func lock() { self.nslock.lock() } public func unlock() { self.nslock.unlock() } public func `do`(_ closure: () throws -> Void) rethrows { self.lock() defer { self.unlock() } try closure() } }
TypeScript
UTF-8
645
2.5625
3
[]
no_license
import promiseWrap from 'promise-chains'; export abstract class LazyContent { constructor(private _hasFetched: boolean) { if (!_hasFetched) { return new Proxy(this, { get (target, key) { return key in target || key === 'length' || key in Promise.prototype ? target[key] : target.fetch()[key]; } }); } } public fetch() { if (this._fetch) { return this._fetch; } else { this.fetch = promiseWrap(this._fetch()); } } protected abstract _fetch(); } export default LazyContent;
C#
UTF-8
1,678
3.34375
3
[ "MIT" ]
permissive
using System; namespace AppTrab { class Matrizes { public int[,] matriz; public int n, p; public Matrizes() { n = 3; p = 3; matriz = new int[n, p]; } public Matrizes(bool isRandomic) { n = 3; p = 3; matriz = new int[n, p]; if (!!isRandomic) preencheMatriz(); } public Matrizes(int linhas, int colunas) { n = linhas; p = colunas; matriz = new int[n, p]; } public Matrizes(int linhas, int colunas, bool isRandomic) { n = linhas; p = colunas; matriz = new int[n, p]; if (!!isRandomic) preencheMatriz(); } public void listar() { Console.Clear(); for (int i = 0; i < n; i++) { for (int j = 0; j < p; j++) { Console.Write("{0,6}", matriz[i, j]); } Console.WriteLine(); } Console.ReadKey(); } private void preencheMatriz() { Console.Clear(); Console.Write("informe o limite minimo: "); int min = int.Parse(Console.ReadLine()); Console.Write("informe o limite maximo: "); int max = int.Parse(Console.ReadLine()); Random rand = new Random(); for (int i = 0; i < n; i++) for (int j = 0; j < p; j++) matriz[i, j] = rand.Next(min, max); } } }
Go
UTF-8
764
2.84375
3
[]
no_license
package goElFinder import ( "os" "path/filepath" "io/ioutil" ) func (self *elf) size() int64 { var size int64 for _, p := range self.targets { s := _size(self.volumes[p.id].Root, p.path) size = size + s } return size } func _size(root, path string) int64 { var size int64 = 0 u, err := os.Open(filepath.Join(root, path)) if err != nil { return 0 } defer u.Close() info, err := u.Stat() if err != nil { return 0 } if info.IsDir() { entries, err := ioutil.ReadDir(filepath.Join(root, path)) if err != nil { return 0 } for _, e := range entries { if info.IsDir() { size = size + _size(root, filepath.Join(path, e.Name())) } else { size = size + e.Size() } } } else { size = info.Size() } return size }
Java
UTF-8
992
2.765625
3
[]
no_license
class LFSR { public LFSR(String exp, int tap) { m_n=exp.length(); m_bits=binstr2int(exp); m_tap=tap; m_mask=(1<<m_n)-1; } public int step() { int t= (((1<<(m_n-1)) & m_bits)>>(m_n-1)) ^ (((1<<m_tap) & m_bits)>>m_tap); m_bits=(m_bits<<1) & m_mask; m_bits |= t; return t; } public int generate(int k) { int r=0; for (int i=0; i<k; i++) { r=r*2+step(); } return r; } public String toString() { String r=""; for (int i=0; i<m_n; i++) { if ( ((1<<i) & m_bits) > 0 ) r="1"+r; else r="0"+r; } return r; } public static void main(String arg[]) { LFSR r=new LFSR("01101000010", 8); for (int i=0 ; i<10; i++) { int t=r.generate(5); System.out.println(r+" "+t); } } private int binstr2int(String s) { int q=1, sum=0; for (int i=0; i<s.length(); i++) { if (s.charAt(s.length()-i-1)=='1') sum+=q; q*=2; } return sum; } private int m_n, m_tap, m_bits, m_mask; }
SQL
UTF-8
1,617
3.46875
3
[ "MIT" ]
permissive
-- phpMyAdmin SQL Dump -- version 4.6.5.2 -- https://www.phpmyadmin.net/ -- -- Servidor: localhost:3306 -- Temps de generació: 24-04-2017 a les 10:27:34 -- Versió del servidor: 5.6.35 -- Versió de PHP: 7.1.1 CREATE DATABASE IF NOT EXISTS MakiTetris; USE MakiTetris; SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; DROP TABLE IF EXISTS Partida CASCADE; DROP TABLE IF EXISTS Replay CASCADE; DROP TABLE IF EXISTS DefaultKeys CASCADE; DROP TABLE IF EXISTS Login CASCADE; CREATE TABLE Login ( user varchar(255) NOT NULL, mail varchar(255) NOT NULL, password varchar(50) NOT NULL, connected BOOLEAN, register_date VARCHAR(255), last_login VARCHAR(255), number_games INT, total_points INT, gaming BOOLEAN, startingGameTime VARCHAR(255), PRIMARY KEY (user, mail) ) ENGINE = InnoDB DEFAULT CHARSET = utf8; CREATE TABLE Replay( user VARCHAR(255), ID INT DEFAULT 0, Order_ INT, move VARCHAR(255), path VARCHAR(255), FOREIGN KEY (user) REFERENCES Login (user) ); CREATE TABLE Partida( user varchar(255) NOT NULL, score INT, time VARCHAR(255), game_date VARCHAR(255), max_espectators INT, replay_path VARCHAR(255), FOREIGN KEY (user) REFERENCES Login (user) ); CREATE TABLE DefaultKeys ( user varchar(255) NOT NULL DEFAULT '', derecha int(255) NOT NULL, izquierda int(255) NOT NULL, abajo int(255) NOT NULL, rderecha int(255) NOT NULL, rizquierda int(255) NOT NULL, pause int(255) NOT NULL, FOREIGN KEY (user) REFERENCES Login (user) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ALTER TABLE DefaultKeys ADD PRIMARY KEY (user);
Java
UTF-8
2,711
2.484375
2
[ "MIT" ]
permissive
/* * Copyright (c) 2014, Lukas Tenbrink. * * http://ivorius.net */ package ivorius.reccomplex.utils.zip; import ivorius.reccomplex.utils.ByteArrays; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.function.Supplier; import java.util.zip.ZipInputStream; /** * Created by lukas on 30.05.17. */ public class ZipFinder { private final Map<String, EntryConsumer<InputStream>> map = new HashMap<>(); public void read(ZipInputStream stream) throws IOException { IvZips.walkStreams(stream, (name, inputStream) -> { EntryConsumer<InputStream> consumer = map.get(name); if (consumer != null) consumer.accept(inputStream); }); } public <T> Result<T> stream(String name, Function<InputStream, T> function) { if (map.containsKey(name)) throw new IllegalArgumentException(); Result<T> result = new Result<>(name); map.put(name, inputStream -> result.set(function.apply(inputStream))); return result; } public <T> Result<T> bytes(String name, Function<byte[], T> function) { return stream(name, inputStream -> { byte[] bytes = ByteArrays.completeByteArray(inputStream); return bytes != null ? function.apply(bytes) : null; }); } @FunctionalInterface public interface Function<S, D> { D apply(S t) throws IOException; } @FunctionalInterface private interface EntryConsumer<T> { void accept(T t) throws IOException; } public class Result<T> { protected String name; protected T t; protected boolean present; public Result(String name) { this.name = name; } protected void set(T t) { this.t = t; present = true; } public boolean isPresent() { return present; } public T get() { if (!isPresent()) throw new MissingEntryException(name); return t; } public T orElse(Supplier<T> defaultVal) { return isPresent() ? t : defaultVal.get(); } public Optional<T> peek() { return present ? Optional.of(t) : Optional.empty(); } } public class MissingEntryException extends RuntimeException { public final String name; public MissingEntryException(String name) { super("Missing Entry: " + name); this.name = name; } } }
C#
UTF-8
2,313
3
3
[]
no_license
using System; using System.Collections.Generic; using System.Diagnostics.Eventing.Reader; using System.Linq; using System.Security.Principal; using System.Text; using System.Threading.Tasks; namespace CSP.Misc.Custom { class CustomList { private int[] _content; public int[] Content { get => _content; set => _content = value; } public CustomList() { _content = new int[0]; } public void Add(int value) { int size = _content.Length; int[] tempArr = new int[size + 1]; Array.Copy(_content, tempArr, size); tempArr[size] = value; _content = tempArr; } public void Remove(int value) { int index = Array.IndexOf(_content, value); int size = _content.Length; int[] tempArr = new int[size - 1]; for (int i = index; i < _content.Length; i++) { if (i != _content.Length - 1) { _content[i] = _content[i + 1]; } } Array.Copy(_content, tempArr, size - 1); _content = tempArr; } public void Sort() { bool token = true; while (token) { int smallest = _content[0]; int counter = 0; for (int i = 1; i < _content.Length; i++) { int current = _content[i]; if (current < smallest) { int indexOfSmallest = Array.IndexOf(_content, smallest); int indexOfCurrent = Array.IndexOf(_content, current); _content[indexOfSmallest] = current; _content[indexOfCurrent] = smallest; } else { ++counter; if (counter == _content.Length - 1) { token = false; } } } } } public void Clear() { _content = new int[0]; } } }
C++
UTF-8
730
3.109375
3
[]
no_license
#include <iostream> using namespace std; bool judge(long long int a,long long int b,long long int c){ if (a + b > c) return true; return false; }; int main(){ int n; long long int a,b,c; cin >> n; bool arr[n]; for(int i = 0; i < n;i++){ cin >> a >> b >> c; arr[i] = false; if (judge(a,b,c)) arr[i] = true; if(arr[i]) {cout<<"Case"<<" "<<"#"<<i+1<<":" <<" "<<"true"<<endl;} else {cout<<"Case"<<" "<<"#"<<i+1<<":" <<" "<<"false"<<endl;} } // for(int i = 0; i < n;i++){ // if(arr[i]) {cout<<"Case"<<" "<<"#"<<i+1<<":" <<" "<<"true"<<endl;} // else {cout<<"Case"<<" "<<"#"<<i+1<<":" <<" "<<"false"<<endl;} // } return 0; };
C
UTF-8
1,671
3.25
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "error.h" void Write_error(char c, const char *e, char **error[]) { char i; for (i = 0; (*error)[i]; i++); if (e) { (*error)[i] = malloc(sizeof(char) * (2 + strlen(e))); sprintf((*error)[i], "%c%s", c, e); } else { (*error)[i] = malloc(sizeof(char)); *((*error)[i]) = c; } } void Cliarg_print_error(FILE *file, char *error[]) { while (*error) { switch ((*error)[0]) { case '0': fprintf(file, "\e[1;31mSyntaxe de l'argument \e[0;33m'%s'\e[1;31m incorrecte\e[0m\n", (*error)+1); break; case '1': fprintf(file, "\e[1;31mPas de valeur attendue pour l'argument \e[0;33m'%s'\e[0m\n", (*error)+1); break; case '2': fprintf(file, "\e[1;31mValeur attendue pour l'argument \e[0;33m'%s'\e[0m\n", (*error)+1); break; case '3': fprintf(file, "\e[1;31mArgument \e[0;33m'%s' \e[1;31minconnu\e[0m\n", (*error)+1); break; case '4': fprintf(file, "\e[1;31mValeur de type \e[1;34mint \e[1;31mattendue pour l'argument \e[0;33m'%s'\e[0m\n", (*error)+1); break; case '5': fprintf(file, "\e[1;31mArgument \e[0;33m'%s' \e[1;31mtrop long\e[0m\n", (*error)+1); break; case '6': fprintf(file, "\e[1;31mErreur dans une des valeurs de l'argument \e[0;33m'%s'\e[0m\n", (*error)+1); break; case '7': fprintf(file, "\e[1;31mPas d'argument !\e[0m\n"); break; default : fprintf(file, "\e[1;31mErreur inconnue !\e[0m\n"); } error++; } } void Cliarg_free_error(char **error[]) { char i; for (i = 0; (*error)[i]; i++) free((*error)[i]); free(*error); }
Java
UTF-8
404
1.820313
2
[ "MIT" ]
permissive
package com.ecommerce.api.model.commons; import java.math.BigDecimal; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Getter; import lombok.Setter; @Getter @Setter @JsonInclude(JsonInclude.Include.NON_NULL) public class FeeMonth { @JsonProperty("mes") private Integer mes; @JsonProperty("fee") private BigDecimal fee; }
Java
UTF-8
1,938
2.40625
2
[ "Apache-2.0" ]
permissive
/* * JPPF. * Copyright (C) 2005-2019 JPPF Team. * http://www.jppf.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package sample.dist.xstream; import java.util.List; import org.jppf.client.*; import org.jppf.node.protocol.Task; /** * Runner class for the XStream demo. * @author Laurent Cohen */ public class XstreamRunner { /** * JPPF client used to submit execution requests. */ private static JPPFClient jppfClient = null; /** * Entry point for this class, submits the tasks to the JPPF grid. * @param args not used. */ public static void main(final String... args) { try { jppfClient = new JPPFClient(); final long start = System.nanoTime(); final JPPFJob job = new JPPFJob(); final Person person = new Person("John", "Smith", new PhoneNumber(123, "456-7890")); job.add(new XstreamTask(person)); // submit the tasks for execution final List<Task<?>> results = jppfClient.submit(job); final long elapsed = (System.nanoTime() - start) / 1_000_000L; System.out.println("Task executed in " + elapsed + " ms"); final Task<?> result = results.get(0); if (result.getThrowable() != null) throw result.getThrowable(); System.out.println("Task execution result: " + result.getResult()); } catch (final Throwable e) { e.printStackTrace(); } finally { if (jppfClient != null) jppfClient.close(); } } }
TypeScript
UTF-8
265
2.65625
3
[]
no_license
const formatDate = (date: Date): string => { const data = new Date(); const day = data.getDate().toString(); const month = (data.getMonth() + 1).toString(); const year = data.getFullYear(); return `${day}/${month}/${year}`; }; export default formatDate;
C++
UTF-8
3,174
2.6875
3
[ "MIT" ]
permissive
/*** Appendix D: Exporting and Packaging Selected Grid Extent ***/ // This code generates the output_bin_dfile() database // function, which is used to export gridded TCP data // in the binary format required by ARSC. #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <sys/stat.h> #include <unistd.h> #include "executor/spi.h" typedef unsigned char byte; extern int output_bin_dfile( text *tbl_name, text *out_file, int x_min, int y_min, int x_max, int y_max, int flip_signs ) { FILE *fpout; char *tablename; char *outfilename; char outfilepath[256]; char tmpPath[256] = ""; bool flipSigns = ( flip_signs == 0 ? false : true ); char query[512]; unsigned int i, rows; int result; bool nullDepth = false; Datum datumDepth; float4 floatDepth; float bigendDepth; byte *lEnd = ((byte *) &floatDepth); byte *bEnd = ((byte *) &bigendDepth); byte cnt = 0; // Prepare tablename tablename = DatumGetCString(DirectFunctionCall1( textout, PointerGetDatum( tbl_name ) )); // Prepare outfilename outfilename = DatumGetCString(DirectFunctionCall1( textout, PointerGetDatum( out_file ) )); // Build the query statement sprintf( query, "SELECT depth::float4 FROM %s WHERE x >= %i AND x <= %i AND y >= %i AND y <= %i ORDER BY y ASC, x ASC;", tablename, x_min, x_max, y_min, y_max ); // Open the output file for binary write access fpout = fopen(outfilename,"wb"); if (fpout==NULL) { elog( ERROR, "Unable to open output file: '%s'", outfilename ); } // Output file is open and ready, query is ready SPI_connect(); // Execute the query result = SPI_exec( query, 0 ); rows = SPI_processed; // If the SELECT statement worked, and returned more than zero rows if (result == SPI_OK_SELECT && rows > 0) { // Get the tuple (row) description for the rows TupleDesc tupdesc = SPI_tuptable->tupdesc; // Get pointer to the tuple table containing the result tuples SPITupleTable *tuptable = SPI_tuptable; // Loop over each row in the result set (tuple set) for( i = 0; i < rows; i++ ) { // Get tuple (row) number i HeapTuple tuple = tuptable->vals[i]; // Store a pointer to the depth value Datum on this row datumDepth = SPI_getbinval( tuple, tupdesc, 1, &nullDepth ); floatDepth = DatumGetFloat4( datumDepth ); if( nullDepth ) elog ( ERROR, "NULL depth value on row %i", i ); if( flipSigns ) floatDepth *= -1.0; // Write the little-endian floatDepth into bigendDepth bEnd += 3; for( cnt = 0; cnt < 4; cnt++ ) { *bEnd = *lEnd; if( cnt < 3 ) { lEnd++; bEnd--; } } lEnd -= 3; // Write the floating point depth value out to the file fwrite(&bigendDepth,sizeof(float),1,fpout); } } // Done using the result set SPI_finish(); // Close the output file fclose(fpout); // CHMOD the file for access by group tportal int mode = ( S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH ); chmod( outfilename, mode ); // Free up memory pfree(tablename); pfree(outfilename); return 0; }
PHP
UTF-8
775
2.578125
3
[]
no_license
<?php namespace Jaccob\AccountBundle\Security; final class Access { /** * Security level private */ const LEVEL_PRIVATE = 0; /** * Security level friends can see */ const LEVEL_FRIEND = 50; /** * Security level public */ const LEVEL_PUBLIC_HIDDEN = 100; /** * Security level public */ const LEVEL_PUBLIC_VISIBLE = 200; /** * Security level private */ const ACCESS_READ = 0x0002; /** * Security level friends can see */ const ACCESS_WRITE = 0x0004; /** * Simple visitor */ const ROLE_VISITOR = 'visitor'; /** * Normal user */ const ROLE_NORMAL = 'user'; /** * Admin user */ const ROLE_ADMIN = 'admin'; }
Java
UTF-8
4,496
2.453125
2
[]
no_license
package it.unisa.microapp.editor; import it.unisa.microapp.utils.Constants; import java.util.ArrayList; import java.util.List; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; public class IconsGrid extends Grid { int startRows = 0; int blockSpacediv2 = Constants.SPACE / 2; int blockCol; List<IconPiece> pieces = new ArrayList<IconPiece>(); Paint paint; //Bitmap buttonImage; public IconsGrid(int h, int l, int sh, int sl) { width = l; height = h; showGrid = true; init(1, 0, 0); paint = new Paint(); paint.setAntiAlias(true); } private void init(int numCols, int numRows, int startRow) { if (numCols > 0) this.numCols = numCols; if (numRows >= 0) this.numRows = numRows; if (startRow >= 0) startRows = startRow; blockCol = numCols * Constants.SPACE; } // aggiornamento private void update(int numCols, int numRows, int startRow) { init(numCols, numRows, startRow); } protected void draw(Canvas canvas, int col, int row) { if (showGrid) drawGrid(canvas, paint, col, row); for (IconPiece piece : pieces) { piece.draw(canvas, paint, true, col, row); } } @Override protected void drawGrid(Canvas panel, Paint paint, int col, int row) { int oldColor = paint.getColor(); // vertical line /di separazione colonne/ int x = 0; paint.setColor(Color.LTGRAY); for (int i = 1; i < Constants.GRID_WSIZE; i++) { x += width + Constants.SPACE; panel.drawLine(x, 0, x, Constants.HEIGTH, paint); } int y = 0; for (int i = 1; i <= Constants.GRID_HSIZE; i++) { y += height + Constants.SPACE; panel.drawLine(0, y, Constants.WIDTH, y, paint); } paint.setColor(oldColor); } public void addNewIconPiece(IconPiece p) { pieces.add(p); updateMatrix(p, true); if (numRows == 0) numRows++; updateGrid(); } public List<IconPiece> getIconPieces() { return pieces; } public void setIconPieces(List<IconPiece> pieces) { this.pieces = pieces; } public void clearIconPieces() { this.pieces.clear(); } private void updateMatrix(IconPiece p, boolean add) { int x = p.getLogicPosition().x; int y = p.getLogicPosition().y; int scalex = 1; int scaley = 1; for (int i = x; i < x + scalex; i++) { for (int j = y; j < y + scaley; j++) { if (!p.isHoled(i)) { if (add) matrix[i - 1][j - 1] = p; else matrix[i - 1][j - 1] = null; } } } } public IconPiece getSelected() { for (IconPiece piece : pieces) { if (piece.isSelected()) return piece; } return null; } public void unselectPieces() { for (IconPiece piece : pieces) { piece.setSelected(false); } } private void updateGrid() { int maxCols = 1; int maxRows = 0; int startR = Constants.MATRIX_SIZE; if (pieces.size() == 0) { startR = 1; } else for (IconPiece piece : pieces) { maxCols = Math.max(maxCols, piece.getLogicPosition().x); maxRows = Math.max(maxRows, piece.getLogicPosition().y + piece.getHeightScale() - 1); startR = Math.min(startR, piece.getLogicPosition().y); } update(maxCols, maxRows, startR); } public Point calcLogicPosition(float x, float y) { int lx = (int) Math.ceil(x / (width + Constants.SPACE)); int ly = (int) Math.ceil(y / (height + Constants.SPACE)); lx = Math.max(lx, 1); ly = Math.max(ly, 1); return new Point(lx, ly); } public Point calcSnapPosition(float x, float y) { Point cp = calcLogicPosition(x, y); int lx = cp.x; int ly = cp.y; if (lx >= this.numCols) { lx = this.numCols; if (this.startRows > 1) { return new Point(lx, 2); } return new Point(lx, 1); } int max = 0; int min = this.numRows + 1; // min max ly for (int j = 0; j <= this.numRows; j++) { if (matrix[lx - 1][j] != null) { if (min > j) min = j; if (max < j) max = j; } } if (max < min) // free column { if (this.startRows > 1) { return new Point(lx, 2); } return new Point(lx, 1); } if (ly < this.startRows) { return new Point(lx, min); } return new Point(lx, max + 2); } public List<Shape> piecesForRow(int row) { List<Shape> lt = new ArrayList<Shape>(); if (row > 0 && row <= numRows) { for (int i = 0; i < numCols; i++) { IconPiece p = (IconPiece)matrix[i][row - 1]; if (p != null && !lt.contains(p)) { lt.add(p); } } } return lt; } }
Java
UTF-8
534
1.976563
2
[]
no_license
package com.hconve.findroom.ui; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import dagger.android.support.DaggerAppCompatActivity; public abstract class BaseActivity extends DaggerAppCompatActivity { public void replaceFragment(int layoutId, Fragment fragment) { FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(layoutId, fragment); transaction.addToBackStack(null); transaction.commit(); } }
Python
UTF-8
865
3.015625
3
[]
no_license
import pandas as pd from scipy import stats from sklearn.cluster import KMeans import matplotlib.pyplot as plt import seaborn as sns df = pd.read_csv('blogdata.csv', sep=';') # df = pd.read_csv('blogdata.csv', sep="\t", quoting=csv.QUOTE_NONE)#, index_col=False) # Make a copy of DF df_tr = df # Transsform the timeOfDay to dummies df_tr = pd.get_dummies(df_tr, columns=['Blog']) # Standardize # clmns = ['Wattage', 'Duration', 'timeOfDay_Afternoon', 'timeOfDay_Evening', # 'timeOfDay_Morning'] clmns = df.columns.values df_tr_std = stats.zscore(df_tr[clmns]) # Cluster the data kmeans = KMeans(n_clusters=2, random_state=0).fit(df_tr_std) labels = kmeans.labels_ # Glue back to originaal data df_tr['clusters'] = labels # Add the column into our list clmns.extend(['clusters']) # Lets analyze the clusters print(df_tr[clmns].groupby(['clusters']).mean())
C++
UTF-8
580
2.75
3
[]
no_license
#ifndef PARALLELEPIPOID_H #define PARALLELEPIPOID_H #include "../types.h" #include "Object.h" class Parallelepipoid : public Object { public: /** * @param p Position at which the object is centered * @param lx Length along the x axis (in meters) * @param ly Length along the y axis (in meters) * @param lz Length along the z axis (in meters) */ Parallelepipoid(Point const & p, float lx, float ly, float lz); protected: float minBounds[3]; float maxBounds[3]; virtual bool computeIntersection(Ray const & ray, Intersection * intersection); }; #endif
Python
UTF-8
735
4
4
[]
no_license
''' xの値で級数の値の計算 級数・・・・一定の法則に従って変化する数を、一定の順に並べた数列の和 ''' from sympy import Symbol, pprint, init_printing def print_series(n, x_value): init_printing(order='rev-lex') x = Symbol('x') series = x for i in range(2, n+1): series = series + (x**i)/i pprint(series) #xで級数評価 series_value = series.subs({x:x_value}) print('xの値が{0}の時、級数は{1}'.format(x_value, series_value)) if __name__ == '__main__': n = input('級数の個数を入力してください: ') x_value = input('級数の値を計算するxの値を入力して下さい: ') print_series(int(n), float(x_value))
Markdown
UTF-8
1,573
3.359375
3
[ "MIT" ]
permissive
# fixing-git-mistakes ## Setup Before the workshop, do the following: ### Clone this repository. It doesn't have much in it yet, but we will be building it up during the workshop. ### Create a new repository on your own GitHub account This is the repo you will use during the workshop - just for you. This can be a private repo, and you could use gitlab (etc) if you're more comfortable with that. If you've never done that before, here are the steps to follow: 1. Sign up for github if you don't already have an account 2. In the upper left, next to "Repositories", click "New" 3. Give your repository a name - it doesn't matter what it is, only you will see it 4. Mark the repo as "private" if you'd like, or keep it public - it doesn't matter for this workshop 5. Click to create the repo 6. Navigate to the new repo, and click "Clone or download" 7. Copy the git or https address, and then in a terminal run: > git clone [address] If that works - you're good to go! If it doesn't work, let me know and I'll help you work through it ## What we'll do during the workshop Throughout the workshop, we'll be using that github repo you just created. We'll add files, make commits, and push to github. We'll also purposefully mess things up! Then we'll see what went wrong, and how to fix it. ## After the workshop Afterwards, you'll have a better understanding of all the different ways a file can exist in git. You'll be able to handle it when mistakes happen - without worrying about losing data, or messing up other people's repos. 🎉
Java
UTF-8
1,120
3.3125
3
[]
no_license
package com.dudev.android.hackernews.Util; import java.util.HashSet; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; public class ListUtils { private ListUtils() {} @SuppressWarnings("unchecked") public static <T> void removeDuplicate(List <T> list) { Set <T> set = new HashSet <T>(); List <T> newList = new ArrayList <T>(); for (Iterator <T>iter = list.iterator(); iter.hasNext(); ) { Object element = iter.next(); if (set.add((T) element)) newList.add((T) element); } list.clear(); list.addAll(newList); } public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>(); list.add("Bart"); list.add("Lisa"); list.add("Marge"); list.add("Marge"); list.add("Barney"); list.add("Homer"); list.add("Maggie"); System.out.println(list); // output : [Bart, Lisa, Marge, Marge, Barney, Homer, Maggie] ListUtils.removeDuplicate(list); System.out.println(list); // output : [Bart, Lisa, Marge, Barney, Homer, Maggie] } }
Python
UTF-8
2,737
4.28125
4
[]
no_license
# Benifits of LinkedList # 1. # Complexity # Indexing O(n) #Inserting/Delete Element at Start O(1) class Node: def __init__(self,data,next): self.data = data self.next = next class LinkedList: def __init__(self): self.head = None def insert_at_beg(self,data): node = Node(data,self.head) self.head = node def insert_at_end(self,data): if self.head is None: self.head = Node(data,None) return itr = self.head while itr.next: itr = itr.next itr.next = Node(data,None) def print(self): if self.head is None: print('LinkedList is Empty') itr = self.head llstr = '' while itr: llstr = llstr + str(itr.data) + '--->' itr = itr.next print(llstr) def insert_items(self,listofitem): for item in listofitem: self.insert_at_end(item) def get_length(self): count = 0 itr = self.head while itr: count = count+1 itr = itr.next return count def remove_at(self,index): if index < 0 or index >= self.get_length(): raise Exception("Invalid Index") itr = self.head count = 0 while itr: if count == index - 1: itr.next = itr.next.next count = count + 1 itr = itr.next def insert_at(self,index,data): if index == 0: self.insert_at_beg(data) elif index == self.get_length(): self.insert_at_end(data) itr = self.head count = 0 while itr: if count == index - 1: nn = Node(data,itr.next) itr.next = nn count = count +1 itr = itr.next def insert_after_value(self, data_after, data_to_insert): # Search for first occurance of data_after value in linked list # Now insert data_to_insert after data_after node itr = self.head while itr: if itr.data == data_after: nn = Node(data_to_insert,itr.next) itr.next = nn return itr = itr.next def remove_by_value(self, data): # Remove first node that contains data p = self.head n = p.next if p.data == data: self.head = n while n: if n.data == data: p.next = n n = n.next if __name__ == '__main__': ll = LinkedList() ll.insert_items([1,2,3,4,6]) ll.print() # ll.insert_at(0,5) ll.insert_after_value(3,8) ll.print() ll.remove_by_value(3) ll.print()
Java
UTF-8
1,091
1.875
2
[]
no_license
package com.sxht.dao; import com.sxht.model.*; import org.apache.ibatis.annotations.Param; import java.util.List; public interface FeatureMapper { int countByExample(FeatureExample example); int deleteByExample(FeatureExample example); int deleteByPrimaryKey(String id); int insert(Feature record); int insertSelective(Feature record); List<Feature> selectByExample(FeatureExample example); Feature selectByPrimaryKey(String id); int updateByExampleSelective(@Param("record") Feature record, @Param("example") FeatureExample example); int updateByExample(@Param("record") Feature record, @Param("example") FeatureExample example); int updateByPrimaryKeySelective(Feature record); int updateByPrimaryKey(Feature record); List<Feature> getFeatures(int index, int size); List<Feature> getFeaturesByRole(String roleId); List<Feature> getFeaturesByUser(String userId); List<Feature> selectByExamplePage(FeatureExamplePage featureExamplePage); int selectCountByExamplePage(FeatureExamplePage featureExamplePage); }
C#
UTF-8
1,199
2.5625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ShoppingCart.Web.Mvc.Tests.Services { public class MockCartRepository : ShoppingCart.Web.Mvc.Services.ICartRepository { private Dictionary<string, Model.Cart> m_Cache; public MockCartRepository() { m_Cache = new Dictionary<string, ShoppingCart.Web.Mvc.Model.Cart>(); } #region ICartRepository Members public string GetCartId() { return "1"; } public ShoppingCart.Web.Mvc.Model.Cart this[string cartId] { get { if (m_Cache.ContainsKey(cartId)) { return m_Cache[cartId]; } return null; } } public void Save(ShoppingCart.Web.Mvc.Model.Cart cart) { m_Cache.Add(cart.Code, cart); } public void Remove(ShoppingCart.Web.Mvc.Model.Cart cart) { m_Cache.Remove(cart.Code); } public void Remove(string cartId) { m_Cache.Remove(cartId); } public IQueryable<ShoppingCart.Web.Mvc.Model.Cart> GetList() { return m_Cache.Select(i => i.Value).AsQueryable(); } public void ChangeCurrent(string cartId) { // Do nothing } #endregion } }
C
UTF-8
248
3.375
3
[]
no_license
#include <stdio.h> #include <stdint.h> #include <stdlib.h> int overflow(int32_t x, int32_t y){ return (x ^ (1<<31) ) + (y ^ (1<<31)); } int main(){ printf("will %d + %d give us an overflow? %d", 2147483647 , 3, overflow(2148473647, 3)); }
Java
UTF-8
4,038
3.203125
3
[]
no_license
package br.usp.larc.tcp.protocolo; import java.text.DecimalFormat; import java.text.MessageFormat; import java.util.Hashtable; import java.util.Iterator; /** * Classe que representa as M�quinas de Conex�es que receber�o pacotes do objeto * Monitor. * * Note que essa classe estende a classe java.util.Hashtable (ela herda todos * os atributos e m�todos) e sobrecarrega/sobrep�e alguns m�todos da mesma. * Estamos usando o conceito de Polimorfismo. * * Detalhes e dicas de implementa��o dessa classe podem ser consultadas na API * da classe java.util.Hashtable. * * Procure sempre usar o paradigma Orientado a Objeto, a simplicidade e a * criatividade na implementa��o do seu projeto. * * * @author Laborat�rio de Arquitetura e Redes de Computadores * @version 1.0 Agosto 2003 */ public class MaquinasDeEstados extends java.util.Hashtable { /** Construtor da classe MaquinasDeEstados */ public MaquinasDeEstados() { super(); } /** * M�todo que adiciona na tabela uma conex�o. No caso de adi��o de conex�es * com o mesmo ID, o m�todo sobrep�e os objetos e permanece na tabela a * �ltima conex�o inserida. * * @param _idConexao O id da Conexao que ser� chave do o objeto m�quina * @param _maquinaDeEstados O objeto m�quina que ser� inserido */ public void put(String _idConexao, MaquinaDeEstados _maquinaDeEstados) { super.put(_idConexao, _maquinaDeEstados); } /** * M�todo que retorna uma m�quina da tabela com a Porta TCP (local) passada, * caso n�o encontre a porta na tabela, retorna null. * * @param _idConexao O idConexao da m�quina que voc� quer obter, nulo se * n�o existir a m�quina com o id passado * @return MaquinaDeEstados A m�quina desejada */ public MaquinaDeEstados get(int _idConexao) { return (MaquinaDeEstados) super.get(Integer.toString(_idConexao)); } /** * M�todo que remove uma m�quina da tabela com o id da conex�o passado, caso * n�o encontre o id na tabela, gera exce��o. * * @param _idConexao O id da conex�o da m�quina que se quer remover da tabela * @throws NullPointerException Caso n�o encontre o objeto com o id passado */ public void remove(int _idConexao) throws NullPointerException { if (super.remove((Integer.toString(_idConexao))) == null) { throw new NullPointerException("Elemento n�o encontrado"); } } /** * M�todo que retorna o tamanho atual da tabela de m�quinas baseado no * n�mero de objetos inseridos. * * @return int O tamanho da tabela de m�quinas */ public int size() { return super.size(); } /** * M�todo que retorna um iterador com todos os objetos MaquinaDeEstados * da HashTable * * Exemplo: * * //cria um iterador para percorrer um objeto do tipo TabelaDeConexoes * Iterator iteratorTabela = (Iterator) tabelaDeMaquinas.maquinas(); * MaquinaDeEstados me = new MaquinaDeEstados(); * * * //percorre todo o iterador * while (iteratorTabela.hasNext()) { * //imprime todos os ID's das conex�es que est�o na tabela * System.out.println(( (MaquinaDeEstados)iteratorTabela.next()).getIdConexao()); * } * * @return Iterator O iterador com os objetos M�quinas da tabela */ public Iterator maquinas() { return (Iterator) (super.values()).iterator(); } /** * M�todo que retorna um iterador com as chaves dos objetos MaquinaDeEstados * da HashTable * * * @return Iterator O iterador com as chaves dos objetos da Hashtable */ public Iterator maquinasKeySet() { return (Iterator) (super.keySet()).iterator(); } }//fim da classe MaquinasDeEstados 2006
JavaScript
UTF-8
1,058
2.609375
3
[ "MIT" ]
permissive
const config = require('config') , disConfig = config.get('discord'); module.exports = { name: 'when', args: true, description: `Shows when an account was created.`, execute(client, message, logger, args) { // // FUNCTION DECLARATIONS // function getUserFromMention(mention) { if (!mention) return; if (mention.startsWith('<@') && mention.endsWith('>')) { mention = mention.slice(2, -1); if (mention.startsWith('!')) { mention = mention.slice(1); } return mention; } } // // MAIN LOGIC // if (!message.member.roles.some((roles) => disConfig.get('mod_roles').includes(roles.name))) return; try { var user = client.users.get(getUserFromMention(args[0])); var timestampFromSnowflake = (user.id / 4194304) + 1420070400000; var then = new Date(timestampFromSnowflake).toUTCString(); message.reply(then); } catch (e) { message.reply(`that's not a valid member. Usage: \`${disConfig.get('prefix')}when <mention>\``); } } };
C++
UTF-8
536
2.9375
3
[]
no_license
#include <vector> using namespace std; class Solution { public: vector<bool> kidsWithCandies(vector<int>& candies, int extraCandies) { vector<bool> abc; int biggest = candies.at(0); for (int i = 1; i < candies.size(); ++i) { if (biggest < candies.at(i)) biggest = candies.at(i); } for (int i = 0; i < candies.size(); ++i) { if (candies.at(i) + extraCandies < biggest) abc.push_back(false); else abc.push_back(true); } return abc; } };
PHP
UTF-8
1,124
2.53125
3
[ "MIT" ]
permissive
<?php namespace PhpOffice\PhpSpreadsheetTests\Worksheet\Table; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; use PHPUnit\Framework\TestCase; class SetupTeardown extends TestCase { /** * @var ?Spreadsheet */ private $spreadsheet; /** * @var ?Worksheet */ private $sheet; /** * @var int */ protected $maxRow = 4; protected function tearDown(): void { $this->sheet = null; if ($this->spreadsheet !== null) { $this->spreadsheet->disconnectWorksheets(); $this->spreadsheet = null; } } protected function getSpreadsheet(): Spreadsheet { if ($this->spreadsheet !== null) { return $this->spreadsheet; } $this->spreadsheet = new Spreadsheet(); return $this->spreadsheet; } protected function getSheet(): Worksheet { if ($this->sheet !== null) { return $this->sheet; } $this->sheet = $this->getSpreadsheet()->getActiveSheet(); return $this->sheet; } }
Java
UTF-8
1,025
2.078125
2
[]
no_license
package cn.edu.szu.bigdata.service.impl; import cn.edu.szu.bigdata.entity.SegmentEntity; import cn.edu.szu.bigdata.mapper.SegmentMapper; import cn.edu.szu.bigdata.service.SegmentService; import org.springframework.stereotype.Service; import java.util.List; /** * Created by longhao on 2017/9/27. * Email: longhao1@email.szu.edu.cn */ @Service("segmentService") public class SegmentServiceImpl extends BaseService<SegmentEntity> implements SegmentService { private SegmentMapper segmentMapper; public SegmentServiceImpl(SegmentMapper segmentMapper){ this.segmentMapper=segmentMapper; } @Override public List<SegmentEntity> getSegmentEntityListBYSegmentName(String segment_name) { return segmentMapper.selectSegmentEntityBySegmentName(segment_name); } @Override public SegmentEntity getSegmentEntityListBySegmentNameAndProjectName(String segment_name, String project_name) { return segmentMapper.selectSegmentEntityBySegmentNameAndProjectName(segment_name,project_name); } }
Java
UTF-8
8,531
2.046875
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package pane; import com.jfoenix.controls.JFXDrawer; import com.jfoenix.controls.JFXHamburger; import com.jfoenix.transitions.hamburger.HamburgerBackArrowBasicTransition; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.image.ImageView; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import login.mycontroller; /** * FXML Controller class * * @author programmer */ public class FxmlController implements Initializable { @FXML private StackPane start; @FXML private AnchorPane home; @FXML private Label label1; @FXML private AnchorPane search; @FXML private Label label2; @FXML private AnchorPane grade; @FXML private Label label3; @FXML private AnchorPane admin; @FXML private Label label4; @FXML private AnchorPane about_us; @FXML private Label label5; @FXML private JFXHamburger hamburger; @FXML private JFXDrawer drawer; @FXML private AnchorPane exam; @FXML private Label exam_label; @FXML private ImageView image1; @FXML private ImageView image2; @FXML private ImageView image3; @FXML private ImageView image4; @FXML private ImageView image5; @FXML private ImageView image6; public static String name = ""; @Override public void initialize(URL url, ResourceBundle rb) { // set images to images views javafx.scene.image.Image im1 = new javafx.scene.image.Image(getClass().getResourceAsStream("home.png")); image1.setImage(im1); javafx.scene.image.Image im2 = new javafx.scene.image.Image(getClass().getResourceAsStream("search.png")); image2.setImage(im2); javafx.scene.image.Image im3 = new javafx.scene.image.Image(getClass().getResourceAsStream("exam.png")); image3.setImage(im3); javafx.scene.image.Image im4 = new javafx.scene.image.Image(getClass().getResourceAsStream("grade.png")); image4.setImage(im4); javafx.scene.image.Image im5 = new javafx.scene.image.Image(getClass().getResourceAsStream("admin.png")); image5.setImage(im5); javafx.scene.image.Image im6 = new javafx.scene.image.Image(getClass().getResourceAsStream("about.png")); image6.setImage(im6); // set style to labels and pane home.getStyleClass().add("home"); label1.getStyleClass().add("label1"); search.getStyleClass().add("home"); label2.getStyleClass().add("label1"); grade.getStyleClass().add("home"); label3.getStyleClass().add("label1"); admin.getStyleClass().add("home"); label4.getStyleClass().add("label1"); about_us.getStyleClass().add("home"); label5.getStyleClass().add("label1"); exam.getStyleClass().add("home"); exam_label.getStyleClass().add("label1"); try { FXMLLoader load = new FXMLLoader(); Parent v = load.load(getClass().getResource("vbox.fxml").openStream()); VboxController user = (VboxController) load.getController(); v.getStylesheets().add("pane/vbox.css"); if (!name.equals("")) { user.user(name); }else { user.cancel_logout(); } drawer.setSidePane(v); } catch (IOException ex) { Logger.getLogger(FxmlController.class.getName()).log(Level.SEVERE, null, ex); } HamburgerBackArrowBasicTransition hab2 = new HamburgerBackArrowBasicTransition(hamburger); hab2.setRate(-1); hamburger.addEventHandler(MouseEvent.MOUSE_PRESSED, (e) -> { hab2.setRate(hab2.getRate() * -1); hab2.play(); if (drawer.isShown()) { drawer.close(); } else { drawer.open(); } }); // home.setStyle("-fx-border-color: red ; -fx-border-width: 1px ; -fx-background-color: red ; "); try { Node ppp = FXMLLoader.load(getClass().getResource("start.fxml")); // pane.getChildren().clear(); start.getChildren().add(ppp); } catch (IOException ex) { Logger.getLogger(FxmlController.class.getName()).log(Level.SEVERE, null, ex); } exam.setDisable(true); grade.setDisable(true); admin.setDisable(true); exam.setStyle("-fx-border-color: red ; -fx-border-width: 1px;"); grade.setStyle("-fx-border-color: red ; -fx-border-width: 1px;"); admin.setStyle("-fx-border-color: red ; -fx-border-width: 1px;"); // javafx.scene.image.Image r3 = new javafx.scene.image.Image(getClass().getResourceAsStream("error.png")); // image3.setImage(r3); // // javafx.scene.image.Image r4 = new javafx.scene.image.Image(getClass().getResourceAsStream("error.png")); // image4.setImage(r4); // // javafx.scene.image.Image r5 = new javafx.scene.image.Image(getClass().getResourceAsStream("error.png")); // image5.setImage(r5); } public void action(ActionEvent e) throws IOException { } public void mouse_Event(MouseEvent ee) throws IOException { if (ee.getSource() == home) { System.out.println("home"); Node p = FXMLLoader.load(getClass().getResource("start.fxml")); start.getChildren().clear(); start.getChildren().add(p); } if (ee.getSource() == search) { System.out.println("search"); Node p = FXMLLoader.load(getClass().getResource("/search/search.fxml")); start.getChildren().clear(); start.getChildren().add(p); } if (ee.getSource() == grade) { System.out.println("grade"); Node p = FXMLLoader.load(getClass().getResource("/grade/grade.fxml")); start.getChildren().clear(); start.getChildren().add(p); } if (ee.getSource() == admin) { System.out.println("admin"); Node p = FXMLLoader.load(getClass().getResource("/admin/admin.fxml")); start.getChildren().clear(); start.getChildren().add(p); } if (ee.getSource() == about_us) { System.out.println("about_us"); Node p = FXMLLoader.load(getClass().getResource("/about_us/about_us.fxml")); start.getChildren().clear(); start.getChildren().add(p); } if (ee.getSource() == exam) { System.out.println("exam"); Node p = FXMLLoader.load(getClass().getResource("/exam/exam.fxml")); start.getChildren().clear(); start.getChildren().add(p); } } public void user_privilage() { exam.setDisable(false); grade.setDisable(false); exam.setStyle("-fx-border-color: white ;"); grade.setStyle("-fx-border-color: white ;"); } public void admin_privilage() { exam.setDisable(false); grade.setDisable(false); admin.setDisable(false); exam.setStyle("-fx-border-color: white ;"); grade.setStyle("-fx-border-color: white ;"); admin.setStyle("-fx-border-color: white ;"); } // public void add(String name) throws IOException { // // FXMLLoader load = new FXMLLoader(); // Parent root = load.load(getClass().getResource("vbox.fxml").openStream()); // VboxController user = (VboxController) load.getController(); // user.add(name); // // } }
Java
UTF-8
752
2.65625
3
[]
no_license
package retrofit.http; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Adds headers literally(逐个的) supplied in the {@code value}. * * &#64;(@)Headers("Cache-Control: max-age=640000") * &#64;(@)GET("/") * ... * * &#64;(@)Headers({ * "X-Foo: Bar", * "X-Ping: Pong" * }) * &#64;(@)GET("/") * ... * * Note: Headers do not overwrite each other(Headers不会覆盖重写). All headers with the same name will * be included in the request. */ @Documented @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Headers { String[] value(); }
Markdown
UTF-8
7,283
2.765625
3
[ "MIT" ]
permissive
iptables ======== Configures the firewall using iptables. This role supports ingress and egress filtering. When egress filtering is enabled, some common protocols are automatically allowed. This includes: * DNS requests to the name servers in `/etc/resolv.conf` * Package management (Gentoo, Debian, Alpine) Requirements ------------ Requires a kernel built with iptables support. On Debian and when `iptables_output_policy` is set to `DROP`, `dig` from `dnsutils` is required so that certain mirrors (e.g. `deb.debian.org`) are whitelisted correctly. Role Variables -------------- `iptables_input_policy` Default policy for `INPUT` chain if nothing else matches Valid values are `ACCEPT` (default) and `DROP`. `iptables_output_policy` Default policy for `OUTPUT` chain if nothing else matches Valid values are `ACCEPT` (default) and `DROP`. `iptables_log_dropped_input`, `iptables_log_dropped_output` When set to `true`, dropped packages on the `INPUT`/`OUTPUT` chain are logged. Logging is limited to 1 packet per second. `iptables_allow_ping` Whether to allow incoming *and* outgoing ICMP and ICMPv6 echo requests. Valid values are `true` (default) and `false`. `iptables_allow_broadcast` Whether to allow incoming IPv4 broadcast traffic. Valid values are `true` (default) and `false`. `iptables_allow_multicast` Whether to allow incoming IPv4 multicast traffic. Valid values are `true` (default) and `false`. `iptables_allow_anycast` Whether to allow incoming IPv4 anycast traffic. Valid values are `true` (default) and `false`. `iptables_accept_ip_input`, `iptables_block_ip_input`, `iptables_accept_ip_output`, `iptables_block_ip_output` Each of these variables contains a list of IP addresses (or hostnames) for which all traffic should be accepted/blocked in the `INPUT`/`OUTPUT` chain. To invert the match, IP addresses (and hostnames) can be prefixed with `!`. The rules are set up early in the respective chains, which means that they take precedence over almost all other rules. `iptables_accept_tcp_input`, `iptables_block_tcp_input`, `iptables_accept_udp_input`, `iptables_block_udp_input`, `iptables_accept_tcp_output`, `iptables_block_tcp_output`, `iptables_accept_udp_output`, `iptables_block_udp_output` These variables can be used to set up port-specific rules that allow/block traffic to a certain TCP/UDP port on the `INPUT`/`OUTPUT` chain, respectively. Accept rules take precedence over block rules. All of these variables are lists. The list entries can simply be port numbers, which sets up a rule for these ports without any further conditions. It is also possible to create more elaborate rules by setting a list entry to a dictionary. In this case, the dictionary must to contain the port number in the key `port`. A number of optional keys can be added: * `sport`: The source port to match on. * `source`: The source address to match on. * `destination`: The destination address to match on. * `user`: The name of the local user that the traffic originates from. Only works on the `OUTPUT` chain. Ports, addresses and users can be prefixed with `!` to invert the match. Example: ```yaml iptables_accept_tcp_input: - 22 - 23 - { port: 80, source: 10.0.0.0/8 } - { port: 80, source: 192.168.0.0/16 } - { port: 443, source: !172.16.0.0/12 } iptables_block_udp_output: - { port: 53, user: root } - 123 ``` `iptables_dns_resolver_user` If the output policy is `DROP`, setting this allows this local user account to do arbitrary DNS requests. This is useful when running a local DNS resolver, such as Unbound or dnsmasq. The default is empty, i.e. only traffic to the configured DNS server in `/etc/resolv.conf` is allowed. `iptables_ntp_client_user` If the output policy is `DROP`, setting this allows this local user account to do arbitrary NTP requests. Default is empty, i.e. no rules for NTP are created. `iptables_smtp_client_user` If the output policy is `DROP`, setting this allows this local user account to connect to arbitrary hosts via SMTP. This is useful when running a local MTA, such as Postfix or Exim. Default is empty, i.e. no rules for SMTP are created. `iptables_unrestricted_users`, `iptables_unrestricted_groups` When `iptables_output_policy` is set to `DROP`, these variables can be used to allow specific users (mostly) unrestricted access to the network. Note that address and port specific rules have a higher precedence, so listing users here may not grant totally unrestricted access. When whitelisting groups, iptables rules for the individual users are created. When group memberships change, the firewall script needs to be restarted to apply the changes to the rules. `iptables_custom_input_rules`, `iptables_custom_output_rules` The previous setting allow setting up commonly used rules without dealing with the complexity of iptables. Unfortunately, this abstraction also takes away some of the power of iptables. These variables allow writing raw iptables rules and therefore provide more control. A few things are to note: * The rules are added directly to the `INPUT` or `OUTPUT` chain, respectively. * The rules are added at the end of these chains, which means that the rules generated by other settings take precedence over these here. * The rules are automatically applied to both `iptables` and `ip6tables`. Rules that start with `-4` or `-6` are added to `iptables` or `ip6tables` only, respectively. * Instead of `-j DROP` or `-j REJECT` it is preferable to use `-j drop_input` or `-j drop_output`. This ensures consistent behaviour and also handle logging (if enabled). Example: ```yaml iptables_custom_input_rules: - '-p tcp --dport 22 --comment "just for the sake of the example" -j ACCEPT' - '-p tcp --dport 23 --comment "just for the sake of the example" -j drop_input' ``` ### Managing rules using groups This role uses several list variables (e.g. `iptables_accept_tcp_input`) to configure the firewall. It may make sense to define them in groups. However, when using the variable name directly, Ansible does not merge the lists. Instead, the last defined variable overwrites earlier definitions. To facilitate group-driven firewall configuration and avoid duplication of data, this role allows appending an arbitrary suffix to each list's variable name to make it unique. These lists are then merged into one. For example, the group `ssh-servers` may define: ```yaml iptables_accept_tcp_input_ssh: - 22 ``` And the group `web-servers` may define: ```yaml iptables_accept_tcp_input_web: - 80 - 443 ``` For a system in both groups, this would result in: ```yaml iptables_accept_tcp_input: - 22 - 80 - 443 ``` Lists defined this way can be overwritten in sub-groups, if desired. For example, a group `secure-web-servers`, which is a child of `web-servers`, could redefined the list: ```yaml iptables_accept_tcp_input_web: - 443 ``` A system in this group would then not accept connection on TCP port 80. Notes: * Suffixes can be completely arbitrary but an `_` needs to be between the original list name and the suffix. * The resulting lists are lexicographically ordered by the suffix name. * If the "base" variable (without a suffix) is defined, the respective suffixed variables are ignored. License ------- MIT
Ruby
UTF-8
2,272
3.796875
4
[]
no_license
require_relative "00_tree_node.rb" class KnightPathFinder attr_accessor :considered_positions attr_reader :root_node def initialize(pos) @pos = pos @root_node = PolyTreeNode.new(pos) @considered_positions = [pos] self.build_move_tree end def build_move_tree #bfs self refers to root node # start with the root node # use pos from root node to generate new_move_positions # while loop, end it when queue is empty # look at first item in queue, removing it, adding its children (new_move_positions) queue = [@root_node] until queue.empty? parent = queue.shift new_moves = new_move_positions(parent.value) new_moves.map! {|pos| PolyTreeNode.new(pos)} new_moves.map {|node| node.parent = parent} queue += new_moves end end def new_move_positions(pos) #returns an array of positions new_moves = KnightPathFinder.valid_moves(pos).select do |move| !@considered_positions.include?(move) end @considered_positions += new_moves new_moves end def self.valid_moves(pos) #this should add2 and 1 to both sides of pos respectively in every direction, and filter out negative results moves = [] moves << [pos[0] + 2, pos[1] + 1] moves << [pos[0] + 1, pos[1] + 2] moves << [pos[0] - 2, pos[1] + 1] moves << [pos[0] - 1, pos[1] + 2] moves << [pos[0] + 2, pos[1] - 1] moves << [pos[0] + 1, pos[1] - 2] moves << [pos[0] - 2, pos[1] - 1] moves << [pos[0] - 1, pos[1] - 2] # moves.each do |move| # moves.delete(move) if move[0] < 0 || move[1] < 0 || move[0] > 7 || move[1] > 7 # end moves.select! do |move| move[0] >= 0 && move[1] >= 0 && move[0] <= 7 && move[1] <= 7 end moves end def find_path(end_pos) node_end = @root_node.dfs(end_pos) return KnightPathFinder.trace_path_back(node_end) end def self.trace_path_back(node_end) arr = [node_end.value] node = node_end while node.parent != nil node = node.parent arr.unshift(node.value) end arr end end game = KnightPathFinder.new([0, 0]) # p game p game.find_path([7, 6])
JavaScript
UTF-8
2,274
2.71875
3
[]
no_license
import {GoBoardBackgroundDrawable as Background} from './goboardbackgrounddrawable.js'; import {GoHorCoordinatesDrawable as HorCoordinates, GoVerCoordinatesDrawable as VerCoordinates} from './gocoordinatesdrawable.js'; import {GoHitBoxDrawable as HitBox, GoHitBoxesDrawable as HitBoxes} from './gohitboxdrawable.js'; import {GoIntersectionsDrawable as Intersections} from './gointersectionsdrawable.js'; import{GoPointDrawable as Point, GoPointsDrawable as Points} from './gopointdrawable.js'; import {default as CanvasMath} from '../gocanvasmath.js'; export default class GoDrawableFactory{ static createPoint(cx, cy, r, pos){ return new Point(cx,cy,r, pos); } static createIntersections(pt, boardSize, offset){ return new Intersections(pt.x, pt.y, boardSize, offset); } static createBoard(pt, canvasSize){ return new Background(pt.x, pt.y, canvasSize); } static createHitBox(x, y, size, pos){ return new HitBox(x, y, size, pos); } static createHitBoxes(startPt, size, boardSize){ const h = []; for(let i =0; i< boardSize; i+=1){ const x = startPt.x + (i* size); for(let j=0; j<boardSize; j+=1){ const y = startPt.y + (j*size); const pt = {x: x, y:y}; const pos = CanvasMath.ptToPos(pt, startPt, size, boardSize); const pt2 = CanvasMath.calcHitBoxPos(pt, size); h.push(new HitBox(pt2.x, pt2.y, size, pos)); } } return new HitBoxes(h); } static createHorCoordinates(pt, w, h, boardSize, offset){ return new HorCoordinates(pt.x, pt.y, w, h, boardSize, offset); } static createVerCoordinates(pt, w, h, boardSize, offset){ return new VerCoordinates(pt.x, pt.y, w, h, boardSize, offset); } static createPoints(points, startPt, offset, radius, boardSize){ const pList = []; for(let i=0; i<points.length; i+=1){ const p = points[i]; const pt = CanvasMath.posToPt(p.position, offset, boardSize); const pos = CanvasMath.ptToPos(pt, startPt, offset, boardSize); pList.push(new Point(pt.x, pt.y, radius, pos)); } return pList; } }
Java
UTF-8
4,762
2.140625
2
[]
no_license
package org.bp.teuno.checklist.UI; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import org.bp.teuno.checklist.Modelo.A98; import org.bp.teuno.checklist.SQLite.BD; import org.bp.teuno.checklist.SQLite.BD.TABLAS; import org.bp.teuno.checklist.SQLite.IT_A98.I_A98; /** * Clase auxiliar que implementa a {@link BD para llevar a cabo el Crud_A98 * sobre las entidades existentes. */ public final class Crud_A98 { private static BD BASEDATOS; private static Crud_A98 INSTANCIA = new Crud_A98(); private Crud_A98() { /* * CONSTRUCTOR VACIO * */ } public static Crud_A98 OBTENER_INSTANCIA(Context CONTEXTO) { if (BASEDATOS == null) { BASEDATOS = new BD(CONTEXTO); } return INSTANCIA; } /* * METODOS CREADOS PARA REALIZAR CONSULTAS A LA BD * */ public Cursor CONSULTA_GENERAL_RONDA(String TURNO, String DIA) { SQLiteDatabase db = BASEDATOS.getReadableDatabase(); String sql = String.format("SELECT * FROM %s WHERE %s=? AND substr(%s, 0, 11) =?", TABLAS.A98, I_A98.ID_TURNO, I_A98.FECHA_INGRESO); String[] selectionArgs = {TURNO, DIA}; return db.rawQuery(sql, selectionArgs); } public Cursor CONSULTA_GENERAL_A98(String FILA, String RACK) { SQLiteDatabase db = BASEDATOS.getReadableDatabase(); String sql = String.format("SELECT * FROM %s WHERE %s=? AND %s=? AND %s=?", TABLAS.A98, I_A98.ID_FILA, I_A98.ID_RACK, I_A98.USUARIO_MODIFICA); String[] selectionArgs = {FILA, RACK, ""}; return db.rawQuery(sql, selectionArgs); } public Cursor EXISTE_DATOS_INGRESADOS_SIN_FINALIZAR_VALIDACION(String FILA, String RACK) { SQLiteDatabase db = BASEDATOS.getReadableDatabase(); String sql = String.format("SELECT * FROM %s WHERE %s=? AND %s=? AND %s=?", TABLAS.A98, I_A98.ID_FILA, I_A98.ID_RACK, I_A98.USUARIO_MODIFICA); String[] selectionArgs = {FILA, RACK, ""}; return db.rawQuery(sql, selectionArgs); } public long INSERTAR_A98(A98 A98) { SQLiteDatabase db = BASEDATOS.getWritableDatabase(); ContentValues VALORES = null; String ID = ""; // GENERAR PK ID = I_A98.GENERAR_ID_A98(); VALORES = new ContentValues(); VALORES.put(I_A98.ID, ID); VALORES.put(I_A98.ID_FILA, A98.ID_FILA); VALORES.put(I_A98.ID_RACK, A98.ID_RACK); VALORES.put(I_A98.ID_AREA, A98.ID_AREA); VALORES.put(I_A98.INICIO, A98.INICIO); VALORES.put(I_A98.FIN, A98.FIN); VALORES.put(I_A98.OBSERVACIONES, A98.OBSERVACIONES); VALORES.put(I_A98.HORA_INGRESO, A98.HORA_INGRESO); VALORES.put(I_A98.HORA_SALIDA, A98.HORA_SALIDA); VALORES.put(I_A98.ID_TURNO, A98.ID_TURNO); VALORES.put(I_A98.RONDA, A98.RONDA); VALORES.put(I_A98.ESTADO, A98.ESTADO); VALORES.put(I_A98.USUARIO_INGRESA, A98.USUARIO_INGRESA); VALORES.put(I_A98.USUARIO_MODIFICA, A98.USUARIO_MODIFICA); VALORES.put(I_A98.FECHA_INGRESO, A98.FECHA_INGRESO); VALORES.put(I_A98.FECHA_MODIFICACION, A98.FECHA_MODIFICACION); return db.insertWithOnConflict(TABLAS.A98, null, VALORES, SQLiteDatabase.CONFLICT_ROLLBACK); } public long MODIFICAR_A98(A98 A98) { SQLiteDatabase db = BASEDATOS.getWritableDatabase(); ContentValues VALORES = null; VALORES = new ContentValues(); VALORES.put(I_A98.FIN, A98.FIN); VALORES.put(I_A98.OBSERVACIONES, A98.OBSERVACIONES); VALORES.put(I_A98.HORA_SALIDA, A98.HORA_SALIDA); VALORES.put(I_A98.RONDA, A98.RONDA); VALORES.put(I_A98.ESTADO, A98.ESTADO); VALORES.put(I_A98.USUARIO_INGRESA, A98.USUARIO_INGRESA); VALORES.put(I_A98.USUARIO_MODIFICA, A98.USUARIO_MODIFICA); VALORES.put(I_A98.FECHA_INGRESO, A98.FECHA_INGRESO); VALORES.put(I_A98.FECHA_MODIFICACION, A98.FECHA_MODIFICACION); String WHERECLAUSE = String.format("%s=?", I_A98.ID); String[] WHEREARGS = {A98.ID}; return db.updateWithOnConflict(TABLAS.A98, VALORES, WHERECLAUSE, WHEREARGS, SQLiteDatabase.CONFLICT_ROLLBACK); } public long ELIMINAR_DATOS_INGRESADOS_SIN_FINALIZAR_VALIDACION(String FILA, String RACK) { SQLiteDatabase db = BASEDATOS.getWritableDatabase(); String whereClause = String.format("%s=? AND %s=? AND %s=?", I_A98.ID_FILA, I_A98.ID_RACK, I_A98.USUARIO_MODIFICA); final String[] whereArgs = {FILA, RACK, ""}; return db.delete(TABLAS.A98, whereClause, whereArgs); } public SQLiteDatabase GETBD() { return BASEDATOS.getWritableDatabase(); } }
Java
UTF-8
370
1.695313
2
[]
no_license
package com.example.vladii.guiaturismocuenca; import android.app.Activity; import android.os.Bundle; /** * Created by vladii on 16/04/2017. */ public class Buscar extends Activity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.buscar);//llamamos al layout buscarxml } }
Python
UTF-8
3,916
2.59375
3
[]
no_license
#! /usr/bin/env python # -*- coding: utf-8 -*- from PyQt4 import QtGui, QtCore from PyQt4.QtGui import QMainWindow, QWidget, QLabel, QPixmap,QWidget,QApplication import cv2 import cv2.cv as cv import sys import pickle import socket import struct """ Area de constantes """ CHAT_PORT = 5000 IP = '127.0.0.1' ### Video CAM_NUMBER= 0 VIDEO_WIDTH = 320 VIDEO_HEIGTH = 240 BUFFER_SIZE = 1024 #************************************************** #Clase que representa la ventana de audio y proximamente #de video #************************************************** class CallWindow(QWidget): # ************************************************** #Constructor de la clase #************************************************** def __init__(self,my_socket): super(CallWindow, self).__init__() self.my_socket = my_socket self.video_size = QtCore.QSize(VIDEO_WIDTH, VIDEO_HEIGTH) self.client_side() self.initUI() # ************************************************** #Metodo Auxiliar que agrega todos los widget a la interfaz #************************************************** def initUI(self): self.image_label = QLabel() self.image_label.setFixedSize(self.video_size) finish_button = QtGui.QPushButton('Finalizar llamada') finish_button.clicked.connect(lambda: self.close()) self.main_layout = QtGui.QVBoxLayout() self.main_layout.addWidget(self.image_label) self.main_layout.addWidget(finish_button) self.setLayout(self.main_layout) self.setGeometry(350, 350, 500, 500) self.setWindowTitle('Llamada') self.show() def closeEvent(self, event): event.accept() def client_side(self): self.capture = cv2.VideoCapture(0) #self.capture.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, VIDEO_WIDTH) #self.capture.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT,VIDEO_HEIGTH) self.split = self.get_image_size(self.capture) splittedstr = [""]*self.split self.my_socket.sendto(str(self.split),(IP, CHAT_PORT)) self.timer = QtCore.QTimer() self.timer.timeout.connect(self.display_video_stream) self.timer.start() def get_image_size(self,capture): _, frame = self.capture.read() #cv.QueryFrame(self.capture) jpgstring = frame.flatten().tostring () #img = cv.fromarray(frame) #jpgstring = cv.EncodeImage(".jpeg", img).tostring() jpglen = len(jpgstring) split = jpglen/BUFFER_SIZE return split def display_video_stream(self): """Read frame from camera and repaint QLabel widget. """ _, frame = self.capture.read() #cv.QueryFrame(self.capture) img = cv.fromarray(frame) jpg_instance = cv.EncodeImage(".jpeg", img) jpg_string = jpg_instance.tostring() jpglen = len(jpg_string) splittedstr = [""]*self.split for i in range(self.split-1): splittedstr[i] = jpg_string[BUFFER_SIZE*i:BUFFER_SIZE*(i+1)] splittedstr[self.split-1] = jpg_string[BUFFER_SIZE*(self.split-1):] for i in range(self.split): my_socket.sendto(splittedstr[i],(IP,CHAT_PORT)) frame = cv2.cvtColor(frame, cv2.cv.CV_BGR2RGB) frame = cv2.flip(frame, 1) image = QtGui.QImage(frame, frame.shape[1], frame.shape[0], frame.strides[0], QtGui.QImage.Format_RGB888) self.image_label.setPixmap(QPixmap.fromImage(image)) def main(): global my_socket my_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,socket.IPPROTO_UDP)#socket.SOCK_STREAM) my_socket.connect((IP, CHAT_PORT)) app = QApplication(sys.argv) mainWindow = CallWindow(my_socket) sys.exit(app.exec_()) if __name__ == '__main__': main()
PHP
UTF-8
4,143
3.234375
3
[]
no_license
<?php // 1,为什么需要分页显示 // 查询数据库,返回的信息数量,往往非常庞大,往往不可能一次性的全部显示出来,此时需要按照需求,输出查询内容 // //使用limit来实现此效果 // //该语句,将所有数据,按照需求,分成不同部分,每次只输出部分之内的数据 // //第一个参数是显示的第一条数据的序号,第二个参数是所显示数据的数量 $host = "127.0.0.1"; $user = "root"; $password = ""; $database = "psd1803"; $port = 3306; $link = mysqli_connect($host,$user,$password,$database,$port); // 第一次查询 // 获取use2的所有数据数量,聚合函数 $query1 = "select count(*) from use2"; $result1 = mysqli_query($link , $query1); $return1 = mysqli_fetch_all($result1); // 总数据数量 $lineSum = $return1[0][0]; // 设定每页输出数据数量 $line = 3; // 每页显示5条数据,总页数 // 总页数,就是超链接的数量 $pagSum = ceil($lineSum/$line); // 第二次查询,查询use2中的所有数据 // //第一次进入当前页面,没有$_GET 传参,需要默认指定从第一页开始显示 // // // // 当前if判断语句,获取到正确的,线束内容的页数,通过计算,获取limit语句的第一个参数 if(isset($_GET["pag"])){ $x = $_GET["pag"]; }else{ $x = 1; } // 根据当前页面数据,设定超链接的输出范围 // if($x < 6){ // 当左侧超出最小值1时 $min = 1; $max = 10; }elseif ($x+4 > $pagSum ){ // 当右侧超出最大值最大页数时 $min = $pagSum-9; $max = $pagSum; }else{ // 其他正常时 $min = $x - 5; $max = $x + 4; } // 计算分页显示,第一条数据的序号,也就是分页显示limit语句的第一个参数 $pag = ($x-1)*$line; $query2 = "select * from use2 limit {$pag} , {$line} "; $result2 = mysqli_query($link , $query2); $return2 = mysqli_fetch_all($result2); mysqli_close($link); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <!-- 先生成对应的页数 --> <!-- 目前使用超链接替代按钮效果 --> <!-- 使用for循环实现 --> <!-- 上一页,实现效果,是将当前需要显示的页面数据,-1传递给PHP程序,但是如果已经是第一页了,就不能再-1,否者limit语句中,第一个参数的计算就会出现错误数值,因此添加if判断,如果当前页面不是第一页,那么传参就执行-1操作,如果是第一页,就给超链接传参设定固定参数1 --> <!-- 首页,超链接传参1 最后一页,超链接传参是$pagSum --> <a href="01_fenye.php?pag=<?php if($x == 1){ $x1 = 1; }else{ $x1 = $x-1; } echo $x1; ?>">上一页</a> <!-- 下一页与上一页原理基本相同,当页面已经是最后一页,那么传递的参数就一直是最后一页,如果不是最后一页,再执行传参+1 --> <a href="01_fenye.php?pag=<?php if($x == $pagSum){ $x2 = $pagSum; }else{ $x2 = $x+1; } echo $x2; ?>">下一页</a> <br> <?php for ($i= $min; $i <= $max ; $i++) { ?> <!-- 点击超链接,跳转当前页面,并且传递数据,该数据为,分页显示limit语句,第一个参数计算的数据 --> <a href="01_fenye.php?pag=<?php echo $i ?>">第<?php echo $i ?>页</a> <?php } ?> <table border="1px"> <tr> <td>序号</td> <td>姓名</td> <td>年龄</td> <td>性别</td> <td>城市</td> <td>部门</td> <td>薪酬</td> </tr> <?php foreach ($return2 as $value) { ?> <tr> <td><?php echo $value[0] ?></td> <td><?php echo $value[1] ?></td> <td><?php echo $value[2] ?></td> <td><?php echo $value[3] ?></td> <td><?php echo $value[4] ?></td> <td><?php echo $value[5] ?></td> <td><?php echo $value[6] ?></td> </tr> <?php } ?> </table> </body> </html> <!-- 分页显示的核心,limit语句的两个参数 --> <!-- 核心中的核心,是limit语句的第一个参数,该参数决定显示内容的起始数据 --> <!-- 第二个参数,决定总页数,通过设定每次显示的数据数量来决定的 -->
Markdown
UTF-8
542
2.515625
3
[]
no_license
# MakersMaker - Dashboard Dashboard for MakersMaker, a programming education platform. ## What we provide in the MakersMaker Dashboard ## - Calendar to easily checkout your course schedules (such as quizzes, assignment deadlines, etc,.) - Lectures list that you are attending now. - Lectures informations such as lecture name, tutor name, progress, level, etc,. ## What we will provide in the MakersMaker Dashboard ## - Link of student's own social networks - Lectures list that student already attended - Wish list of lectures
Markdown
UTF-8
4,803
3.28125
3
[]
no_license
# cocktail-party-algorithm This is an implementation of independent component analysis (ICA) that solves the cocktail party problem. The algorithm falls under the larger class of unsupervised machine learning and is, in my opinion, one of the more refined examples of it. The problem is also called "blind source separation" and is also found in magnetic resonance imaging (MRI). This is a project I made out of curiosity. The cocktail-party problem takes its name from the cocktail-party effect, which refers to the setup you can run into on a cocktail-party: Even though there are lots of people talking at the same time, people are still able to filter out the ones they are talking with. This indicates that the brain has some mechanism to do this filtering, which in turn indicates that this could potentially also be done mathematically. It turns out that it can be done. One solution to this problem is independent component analysis (ICA). ICA assumes that you have more "recorders" (e.g. microphones in the room) than there are "independent sources" (speakers in the room). Assumptions -data is in .wav format. ICA works in a number of steps: 1. Center the data. 2. Whiten the data. This includes the following steps: 2.1. First we run an eigenvalue decomposition on the covariance matrix. This will give us an orthogonal basis indicating the directions of highest variance. Assume that we have two sources, then the complete mix of these sources will produce the highest variance. In a sense, you can think of it as the original sources forming an 'X' and the direction of this highest variance splitting that X in two. 2.2. Using these directions, we rotate the original data. Basically it can be seen as projecting the data into this new space defined by the orthogonal basis found in 2.1. 2.3. We now have the highest variance directions running along the principal axes in the coorinate system. By dividing each variable with its corresponding variance, we will actually get unit (co)variance in every direction. By now we have removed the first and second moments, i.e. the mean and the variance. This process is simply called "whitening." 3. The central limit theorem roughly states that a combination of two random variables will be more gaussian than either random variable alone. We utilize this property to find the original signals using gradient descent: 3.1. We use kurtosis (a.k.a the fourth moment) as measure of non-gaussianity. We randomly pick a vector with unit length as starting point. 3.2. We next estimate the gradient at this point, add the gradient times the learning rate to the vector, and then project this vector onto a unit sphere (-> unit length vector). We repeat this step until convergence. 3.3. When we have found one vector, we continue with the process in 3.2 but additionally requiring that all new vectors be orthogonal to to the found ones. 4. We have now found the unit vectors corresponding to the original signals in the data. At this point we simply project the data on all vectors separately bringing us the original signals. Physics of the problem The effect of sound on a distance from some source is roughly proportional to square of the inverse distance, i.e. when the distance doubles from some source, the effect falls to 1/4. As a consequence, when you have two microphones recording one source you usually measure different effects in this, unless they happen to be at the exact same distance of the source. This version of ICA assumes that the difference in these distances do not cause delays in the measurement, i.e. that the microphones' distances to the source are reasonably small. With this setup, if you plot a point where the x-coordinate is the effect of the sound as measured by microphone 1 at some time, and the y-coordinate is the corresponding metric of microphone 2 at the same time, you will get a point that lies neither on the x-axis nor on the y-axis. If you plot multiple points using the same logic, these will fall around an angled line where the angle can be interpreted as a measure of the difference in distances of the two microphones. If you have a second sound source playing at the same time, the corresponding points of this would fall around a different line, except for that they also interact with with the measurements from sound source 1. As a consequence, the two signals together will mostly fall around a third line which is between the first two and captured by the highest variance direction estimated in 2.1. These are then separated using the process described above. This description can also be extended to cover more microphones and sound sources. The sound files are originally from some researchers at Aalto University, if I remember correctly. I could not find the source anymore.
Go
UTF-8
6,794
2.6875
3
[ "MIT" ]
permissive
package gosn import ( "encoding/json" "fmt" "time" ) func parseTheme(i DecryptedItem) Item { c := Theme{} c.UUID = i.UUID c.ItemsKeyID = i.ItemsKeyID c.ContentType = i.ContentType c.Deleted = i.Deleted c.UpdatedAt = i.UpdatedAt c.CreatedAt = i.CreatedAt c.ContentSize = len(i.Content) var err error if !c.Deleted { var content Content content, err = processContentModel(i.ContentType, i.Content) if err != nil { panic(err) } c.Content = *content.(*ThemeContent) } var cAt, uAt time.Time cAt, err = parseSNTime(i.CreatedAt) if err != nil { panic(err) } c.CreatedAt = cAt.Format(timeLayout) uAt, err = parseSNTime(i.UpdatedAt) if err != nil { panic(err) } c.UpdatedAt = uAt.Format(timeLayout) return &c } type ThemeContent struct { HostedURL string `json:"hosted_url"` LocalURL string `json:"local_url"` PackageInfo json.RawMessage `json:"package_info"` ValidUntil string `json:"valid_until"` ItemReferences ItemReferences `json:"references"` AppData AppDataContent `json:"appData"` Name string `json:"name"` DissociatedItemIds []string `json:"disassociatedItemIds"` AssociatedItemIds []string `json:"associatedItemIds"` Active interface{} `json:"active"` } type Theme struct { ItemCommon Content ThemeContent } func (c Theme) IsDefault() bool { return false } func (i Items) Themes() (c Themes) { for _, x := range i { if x.GetContentType() == "Theme" { component := x.(*Theme) c = append(c, *component) } } return c } func (c *Themes) DeDupe() { var encountered []string var deDuped Themes for _, i := range *c { if !stringInSlice(i.UUID, encountered, true) { deDuped = append(deDuped, i) } encountered = append(encountered, i.UUID) } *c = deDuped } // NewTheme returns an Item of type Theme without content. func NewTheme() Theme { now := time.Now().UTC().Format(timeLayout) var c Theme c.ContentType = "SN|Theme" c.CreatedAt = now c.UUID = GenUUID() return c } // NewTagContent returns an empty Tag content instance. func NewThemeContent() *ThemeContent { c := &ThemeContent{} c.SetUpdateTime(time.Now().UTC()) return c } type Themes []Theme func (c Themes) Validate() error { var updatedTime time.Time var err error for _, item := range c { // validate content if being added if !item.Deleted { updatedTime, err = item.Content.GetUpdateTime() if err != nil { return err } switch { case item.Content.Name == "": err = fmt.Errorf("failed to create \"%s\" due to missing title: \"%s\"", item.ContentType, item.UUID) case updatedTime.IsZero(): err = fmt.Errorf("failed to create \"%s\" due to missing content updated time: \"%s\"", item.ContentType, item.Content.GetTitle()) case item.CreatedAt == "": err = fmt.Errorf("failed to create \"%s\" due to missing created at date: \"%s\"", item.ContentType, item.Content.GetTitle()) } if err != nil { return err } } } return err } func (c Theme) IsDeleted() bool { return c.Deleted } func (c *Theme) SetDeleted(d bool) { c.Deleted = d } func (c Theme) GetContent() Content { return &c.Content } func (c *Theme) SetContent(cc Content) { c.Content = *cc.(*ThemeContent) } func (c Theme) GetItemsKeyID() string { return c.ItemsKeyID } func (c Theme) GetUUID() string { return c.UUID } func (c *Theme) SetUUID(u string) { c.UUID = u } func (c Theme) GetContentType() string { return c.ContentType } func (c Theme) GetCreatedAt() string { return c.CreatedAt } func (c *Theme) SetCreatedAt(ca string) { c.CreatedAt = ca } func (c Theme) GetUpdatedAt() string { return c.UpdatedAt } func (c *Theme) SetUpdatedAt(ca string) { c.UpdatedAt = ca } func (c *Theme) SetContentType(ct string) { c.ContentType = ct } func (c Theme) GetCreatedAtTimestamp() int64 { return c.CreatedAtTimestamp } func (c *Theme) SetCreatedAtTimestamp(ca int64) { c.CreatedAtTimestamp = ca } func (c Theme) GetUpdatedAtTimestamp() int64 { return c.UpdatedAtTimestamp } func (c *Theme) SetUpdatedAtTimestamp(ca int64) { c.UpdatedAtTimestamp = ca } func (c Theme) GetContentSize() int { return c.ContentSize } func (c *Theme) SetContentSize(s int) { c.ContentSize = s } func (cc *ThemeContent) AssociateItems(newItems []string) { // add to associated item ids for _, newRef := range newItems { var existingFound bool var existingDFound bool for _, existingRef := range cc.AssociatedItemIds { if existingRef == newRef { existingFound = true } } for _, existingDRef := range cc.DissociatedItemIds { if existingDRef == newRef { existingDFound = true } } // add reference if it doesn't exist if !existingFound { cc.AssociatedItemIds = append(cc.AssociatedItemIds, newRef) } // remove reference (from disassociated) if it does exist in that list if existingDFound { cc.DissociatedItemIds = removeStringFromSlice(newRef, cc.DissociatedItemIds) } } } func (cc *ThemeContent) GetItemAssociations() []string { return cc.AssociatedItemIds } func (cc *ThemeContent) GetItemDisassociations() []string { return cc.DissociatedItemIds } func (cc *ThemeContent) DisassociateItems(itemsToRemove []string) { // remove from associated item ids for _, delRef := range itemsToRemove { var existingFound bool for _, existingRef := range cc.AssociatedItemIds { if existingRef == delRef { existingFound = true } } // remove reference (from disassociated) if it does exist in that list if existingFound { cc.AssociatedItemIds = removeStringFromSlice(delRef, cc.AssociatedItemIds) } } } func (cc *ThemeContent) GetUpdateTime() (time.Time, error) { if cc.AppData.OrgStandardNotesSN.ClientUpdatedAt == "" { return time.Time{}, fmt.Errorf("ClientUpdatedAt not set") } return time.Parse(timeLayout, cc.AppData.OrgStandardNotesSN.ClientUpdatedAt) } func (cc *ThemeContent) SetUpdateTime(uTime time.Time) { cc.AppData.OrgStandardNotesSN.ClientUpdatedAt = uTime.Format(timeLayout) } func (cc ThemeContent) GetTitle() string { return "" } func (cc *ThemeContent) GetName() string { return cc.Name } func (cc *ThemeContent) GetActive() bool { return cc.Active.(bool) } func (cc *ThemeContent) SetTitle(title string) { } func (cc *ThemeContent) GetAppData() AppDataContent { return cc.AppData } func (cc *ThemeContent) SetAppData(data AppDataContent) { cc.AppData = data } func (cc ThemeContent) References() ItemReferences { return cc.ItemReferences } func (cc *ThemeContent) UpsertReferences(input ItemReferences) { panic("implement me") } func (cc *ThemeContent) SetReferences(input ItemReferences) { cc.ItemReferences = input }
PHP
UTF-8
934
2.53125
3
[ "MIT" ]
permissive
<?php use Illuminate\Database\Eloquent\SoftDeletingTrait; class Entry extends \Eloquent { use SoftDeletingTrait; /** * Which fields may be mass assigned * * @var array */ protected $fillable = [ 'owner_id', 'title', 'body', 'favorite', ]; public static $rules = [ 'title' => 'required' ]; public function owner() { return $this->belongsTo('User'); } public static function getPaginated(array $params) { $recordPerPage = 10; if($params['type']) { if($params['type'] == 'trashed') { return Entry::where('owner_id', '=', Auth::user()->id)->onlyTrashed()->paginate($recordPerPage); } return Entry::where('owner_id', '=', Auth::user()->id)->orderBy('updated_at', 'DESC')->paginate($recordPerPage); } return Entry::where('owner_id', '=', Auth::user()->id)->orderBy('updated_at', 'DESC')->paginate($recordPerPage); } }
Python
UTF-8
1,523
2.875
3
[]
no_license
#--coding:utf-8-- #code by myhaspl #12-9.py from __future__ import unicode_literals from __future__ import division import nltk import sys sys.path.append("../") import jieba def cutstring(txt): #分词 cutstr = jieba.cut(txt) result=" ".join(cutstr) return result #读取文件 txtfileobject = open('nltest2.txt','r') try: filestr = txtfileobject.read( ) finally: txtfileobject.close( ) cutstr=cutstring(filestr) tokenstr=nltk.word_tokenize(cutstr) fdist1=nltk.FreqDist(tokenstr) bigramcolloc=nltk.collocations.BigramCollocationFinder.from_words(tokenstr) print "----出现最频繁的前10个词-----" fdist1=bigramcolloc.word_fd for key,val in sorted(fdist1.iteritems(),key=lambda x:(x[1],x[0]),reverse=True)[:10]: print key,":",val print "----只出现1次的低频词-----" fdist1=bigramcolloc.word_fd for w in fdist1.hapaxes(): print w.encode("utf-8"),"|", #找出文本中搭配词 print print "----找出双连搭配词-----" bigramwords=nltk.bigrams(tokenstr) for fw,sw in set(bigramwords): print fw," ",sw,"|", print print "----双连搭配词以及词频-----" for w,c in sorted(bigramcolloc.ngram_fd.iteritems(),key=lambda x:(x[1],x[0]),reverse=True): fw,sw=w print fw," ",sw,"=>",c,"||", print trigramcolloc=nltk.collocations.TrigramCollocationFinder.from_words(tokenstr) print "----三连搭配词-----" for fw,sw,tw in trigramcolloc.ngram_fd: print fw.encode("utf-8")," ",sw.encode("utf-8")," ",tw.encode("utf-8"),"|", print
JavaScript
UTF-8
782
2.75
3
[]
no_license
const fs = require('fs'); function readFileTests() { const callback = (error, data) => { console.log(data); }; const callback2 = (err, bytesRead, sth) => { console.log(bytesRead, sth); }; fs.readFile('./files', callback); fs.readFile('./files/helloworld.txt', callback); const buffer = Buffer.alloc(12); const fd = fs.openSync('./files/helloworld.txt', 'a'); fs.read(fd, buffer, 0, 12, 0, (...args) => { callback2(...args); fs.closeSync(fd); }); const fd1 = fs.openSync('./files', 'a'); const buffer1 = Buffer.alloc(12); fs.read(fd, buffer1, 0, 12, 0, (...args) => { callback2(...args); fs.closeSync(fd1); }); } //testExists(); //testStat1(); // testStat2(); readFileTests();
Python
UTF-8
939
3.53125
4
[]
no_license
#! /usr/bin/env python #! -*- coding: utf-8 -*- from PIL import Image import face_recognition # Load the jpg file into a numpy array image = face_recognition.load_image_file('biden.jpg') # Find all the faces in the image using the default HOG-based model # This method is fairly accurate, but not as accurate as the CNN model and not GPU accelerated # See also: find_faces_in_picture_cnn.py face_locations = face_recognition.face_locations(image) print('I found {} face(s) in this photograph.'.format(len(face_locations))) for face_location in face_location: #Print the location of each face in this image top,right,bottom,left = face_location print('A face is located at pixel location TOP:{},Left:{},Bottom:{},Right: {}'.format(top,left,bottom,right)) # You can access the actual face itself like this: face_image = image(top:bottom,left:right) pil_image = Image.fromarray(face_image) pil_image.show()
Java
GB18030
5,170
2.515625
3
[]
no_license
package com.example.baihu_calculator; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.EditText; public class three_game extends Activity{ double bh[][] = new double[6][4]; /* * baihu[0]: * baihu[1]: * baihu[2]: * baihu[3]: * baihu[4]: */ EditText et_hz1; EditText et_hz2; EditText et_hz3; EditText et_hn1; EditText et_hn2; EditText et_hn3; EditText et_tn1; EditText et_tn2; EditText et_tn3; EditText et_hlb1; EditText et_hlb2; EditText et_hlb3; EditText et_tlb1; EditText et_tlb2; EditText et_tlb3; EditText et_over; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.three_game);//R.layout.activity_main et_hz1 = (EditText)findViewById(R.id.et_huzi1); et_hz2 = (EditText)findViewById(R.id.et_huzi2); et_hz3 = (EditText)findViewById(R.id.et_huzi3); et_hn1 = (EditText)findViewById(R.id.et_huoniao1); et_hn2 = (EditText)findViewById(R.id.et_huoniao2); et_hn3 = (EditText)findViewById(R.id.et_huoniao3); et_tn1 = (EditText)findViewById(R.id.et_tuoniao1); et_tn2 = (EditText)findViewById(R.id.et_tuoniao2); et_tn3 = (EditText)findViewById(R.id.et_tuoniao3); et_hlb1 = (EditText)findViewById(R.id.et_hlb1); et_hlb2 = (EditText)findViewById(R.id.et_hlb2); et_hlb3 = (EditText)findViewById(R.id.et_hlb3); et_tlb1 = (EditText)findViewById(R.id.et_tlb1); et_tlb2 = (EditText)findViewById(R.id.et_tlb2); et_tlb3 = (EditText)findViewById(R.id.et_tlb3); et_over = (EditText)findViewById(R.id.et_over); } public void calc(View v) { double max=0;int m=0; String h1=et_hz1.getText().toString().trim(), h2=et_hz2.getText().toString().trim(), h3=et_hz3.getText().toString().trim(); //ת bh[0][0]=Double.parseDouble(h1); bh[0][1]=Double.parseDouble(h2); bh[0][2]=Double.parseDouble(h3); String n1=et_hn1.getText().toString().trim(), n2=et_hn2.getText().toString().trim(), n3=et_hn3.getText().toString().trim(); //ת bh[1][0]=Double.parseDouble(n1); bh[1][1]=Double.parseDouble(n2); bh[1][2]=Double.parseDouble(n3); String t1=et_tn1.getText().toString().trim(), t2=et_tn2.getText().toString().trim(), t3=et_tn3.getText().toString().trim(); //ת bh[2][0]=Double.parseDouble(t1); bh[2][1]=Double.parseDouble(t2); bh[2][2]=Double.parseDouble(t3); // for(int i=0;i<bh[0].length-1;i++) { double s=0; for(int j=0;j<bh[0].length-1;j++) { if(bh[0][i]>bh[0][j]) { s=bh[2][i] + bh[2][j]; } else if(bh[0][i]==bh[0][j]) { s=0; } else if(bh[0][i]<bh[0][j]) { s=0-(bh[2][i]+bh[2][j]); } bh[3][i]+=s; } } et_tlb1.setText(bh[3][0]+""); et_tlb2.setText(bh[3][1]+""); et_tlb3.setText(bh[3][2]+""); // for(int i =0;i<bh[0].length;i++) { if(bh[0][i]>0) { if(bh[0][i]%10>=5) { bh[0][i]=(int)(bh[0][i]/10+1)*10; } else { bh[0][i]=(int)bh[0][i]/10*10; } } else if(bh[0][i]<0 && bh[0][i]%10<=-5) { bh[0][i]=(int)(bh[0][i]/10-1)*10; } } // et_hz1.setText(bh[0][0]+""); // et_hz2.setText(bh[0][1]+""); // et_hz3.setText(bh[0][2]+""); // et_hz4.setText(bh[0][3]+""); // for(int i=0;i<bh[0].length-1;i++) { double c=0; for(int j=0;j<bh[0].length-1;j++) { c =bh[0][i]-bh[0][j]; bh[4][i]+=c*0.5*(bh[1][i]+1)*(bh[1][j]+1); } } et_hlb1.setText(bh[4][0]+""); et_hlb2.setText(bh[4][1]+""); et_hlb3.setText(bh[4][2]+""); //Ӯ for(int i=0;i<bh[0].length;i++) { bh[5][i]=bh[4][i]+bh[3][i]; } for(int i=0;i<bh[0].length;i++) { for(int j=0;j<bh[0].length;j++) { if(bh[5][j]>bh[5][i]) { max=bh[5][j]; m=j; } } } switch(m) { case 0:et_over.setText("1Ӯ");break; case 1:et_over.setText("2Ӯ");break; case 2:et_over.setText("3Ӯ");break; } } public void back(View v) { Intent intent = new Intent(this,MainActivity.class); startActivity(intent); } }
Python
UTF-8
891
2.71875
3
[ "Apache-2.0" ]
permissive
import unittest import locust from appian_locust._locust_error_handler import log_locust_error from appian_locust.helper import ENV class TestLocustErrorHandler(unittest.TestCase): def test_obtain_correct_location(self) -> None: ENV.stats.errors.clear() def run_with_error() -> None: e = Exception("abc") log_locust_error(e, raise_error=False) run_with_error() self.assertEqual(1, len(ENV.stats.errors)) # Assert error structure error: locust.stats.StatsError = list(ENV.stats.errors.values())[0] self.assertEqual('DESC: No description', error.method) self.assertEqual('LOCATION: test_locust_error_handler.py/run_with_error()', error.name) self.assertEqual('EXCEPTION: abc', error.error) self.assertEqual(1, error.occurrences) if __name__ == '__main__': unittest.main()
PHP
UTF-8
488
3.046875
3
[]
no_license
<html> <head> <title>Variables </title> </head> <body> <div id = ""> <?php //This program prints hello world, a locally defined variable, and uses a special-reserved variable $_SERVER $txt = "Hello World"; $num1 = 16; echo "<div>"; echo "$txt <br />"; echo "User-defined Variable's value: $num1 <br />"; echo "You are accessing the page with the following browser: <b>" . $_SERVER['HTTP_USER_AGENT']; echo "</b>"; echo "$num1 <br />"; ?> </div> </body> </html>
Python
UTF-8
2,534
2.671875
3
[]
no_license
from bs4 import BeautifulSoup from urllib.request import Request, urlopen from urllib.parse import urlparse import urllib.request import requests import database import re text_file = open('text.txt', 'at') database.MakeTable() def getText(soup): for script in soup(["script", "style"]): script.extract() text = soup.get_text() lines = (line.strip() for line in text.splitlines()) chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) text = '\n'.join(chunk for chunk in chunks if chunk) text_file.write(text + '\n') text_file.write('\n') def getData(URL, DM, depth): if depth == 2: return print(URL) database.PushURL(URL) html_page = requests.get(URL, {'User-Agent': 'Mozilla/5.0'}) soup = BeautifulSoup(html_page.text, "html.parser") getText(soup) for link in soup.findAll('a'): URL = link.get('href') if URL and not URL.startswith('#'): if urllib.parse.urlparse(URL).netloc == '': URL = urllib.parse.urljoin(DM, URL) if not urllib.parse.urlparse(URL).scheme.startswith('http') and not urllib.parse.urlparse(URL).scheme.startswith('https'): continue else: DM = urllib.parse.urljoin(urllib.parse.urlparse(URL).scheme, urllib.parse.urlparse(URL).netloc) if not database.URLvis(URL): getData(URL, DM, depth + 1) Theme = [] def generateTheme(query): query = query.replace(' ', '+') URL = f"https://google.com/search?q={query}" USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:65.0) Gecko/20100101 Firefox/65.0" headers = {"user-agent": USER_AGENT} resp = requests.get(URL, headers=headers) soup = BeautifulSoup(resp.content, "html.parser") for div in soup.find_all('div'): if div.find("div",{"id": 'search'}): for link in div.findAll('a'): URL = link.get('href') if URL is None: continue DM = urllib.parse.urljoin(urllib.parse.urlparse(URL).scheme, urllib.parse.urlparse(URL).netloc) if urllib.parse.urlparse(URL).scheme.startswith('http') or urllib.parse.urlparse(URL).scheme.startswith('https'): inf = (URL, DM) Theme.append( inf ) generateTheme("laptop") for a in Theme: print(a) for link in Theme: getData(link[0], link[1], 0)
Java
UTF-8
3,502
2.125
2
[]
no_license
package com.shcepp.shdippsvr.business.controller; import com.shcepp.shdippsvr.business.bean.pojo.FileUploadReqPojo; import com.shcepp.shdippsvr.business.dao.ShdippSysAttachmentDao; import com.shcepp.shdippsvr.business.service.BaseService; import com.shcepp.shdippsvr.business.service.FileService; import com.shcepp.shdippsvr.sys.util.ApiResult; import com.shcepp.shdippsvr.sys.util.JsonUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.ValidationException; import java.io.FileInputStream; import java.io.OutputStream; @RestController @RequestMapping("resource/") public class UploadFileController { private static final Logger logger = LoggerFactory.getLogger(UploadFileController.class); @Autowired private FileService fileService; @Autowired private ShdippSysAttachmentDao shdippSysAttachmentDao; @PostMapping("/SingleFile") public ApiResult uploadFile(@RequestHeader(required = false) String epToken, @RequestParam("fileName") MultipartFile file, FileUploadReqPojo pojo) { logger.info("开始上传文件"); logger.info("开始根据上传参数上传文件, 上传参数为 : {} ", JsonUtil.beanToJson(pojo)); //认证的部分已经在filter中完成 //在此处只执行查询任务 ApiResult result; try { result = fileService.uploadFile(file, pojo); } catch (ValidationException ver) { logger.error("validate req fial error message is ", ver); result = new ApiResult(); //在参数校验失败的时候 result.setReturnCode(ver.getMessage()); result.setReturnInfo(BaseService.BR_OTHER_ERROR); } catch (Exception err) { logger.error("unexpect error message is ", err); result = new ApiResult(); result.setReturnCode(BaseService.BR_OTHER_ERROR); result.setReturnInfo(BaseService.BR_OTHER_ERROR_MESSAGE); } return result; } // // @RequestMapping(method = RequestMethod.GET, value = "/fileresource") // public void getFile( // HttpServletRequest request, // HttpServletResponse response) { // try { // String pickey = ((String) request.getAttribute("resourceKey")); // // response.setContentType("image/jpeg"); // FileInputStream is = fileService.readPicTopage(pickey); // // if (is != null) { // int i = is.available(); // 得到文件大小 // byte data[] = new byte[i]; // is.read(data); // 读数据 // is.close(); // response.setContentType("image/jpeg"); // 设置返回的文件类型 // OutputStream toClient; // 得到向客户端输出二进制数据的对象 // toClient = response.getOutputStream(); // // toClient.write(data); // 输出数据 // // toClient.close(); // } // } catch (Exception e1) { // logger.error("读取图片的时候发生异常,异常信息为:", e1); // } // // } }
Markdown
UTF-8
261
2.59375
3
[]
no_license
# List-of-play-school-in-Anna-Nagar We provide your child with a safe, friendly and nourishing environment, it is important to ensure that the shortlisted play schools match the requirements. https://preschoolinannanagar.com/list-of-play-school-in-annanagar/
C++
GB18030
1,112
3.21875
3
[]
no_license
#pragma once #ifndef _UF_SET_H_ #define _UF_SET_H_ #include <cstring> namespace SimSTL{ template <size_t N> class uf_set{ public: uf_set(); int Find(int index); void Union(int index1, int index2); void Clear(); private: int parent[N];//parent[i] = -n ʾڵiǸڵiΪйnڵ }; template<size_t N> uf_set<N>::uf_set(){ Clear(); } template<size_t N> int uf_set<N>::Find(int index){ auto root = index; for (; parent[root] >= 0; root = parent[root]){} while (root != index){//·ѹ auto t = parent[index]; parent[index] = root; index = t; } return root; } template<size_t N> void uf_set<N>::Union(int index1, int index2){ auto root1 = Find(index1), root2 = Find(index2); auto total_nodes = parent[root1] + parent[root2];//total nodes if (parent[root1] > parent[root2]){//Ȩϲ parent[root1] = root2; parent[root2] = total_nodes; }else{ parent[root2] = root1; parent[root1] = total_nodes; } } template<size_t N> void uf_set<N>::Clear(){ memset(parent, -1, sizeof(int) * N); } } #endif