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
|
|---|---|---|---|---|---|---|---|
Java
|
UTF-8
| 2,336
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
package com.salama.workflow.core.util;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import org.apache.log4j.Logger;
public class BeanUtil {
private final static Logger logger = Logger.getLogger(BeanUtil.class);
public static void simpleDataValueCopy(Object srcData, Object destData)
throws IllegalAccessException, InstantiationException, IntrospectionException, InvocationTargetException{
if(srcData == null || destData == null) {
return;
}
PropertyDescriptor[] props = Introspector.getBeanInfo(srcData.getClass()).getPropertyDescriptors();
PropertyDescriptor prop = null;
if(props == null || props.length == 0) {
return;
} else {
for(int i = 0; i < props.length; i++) {
prop = props[i];
if((prop.getWriteMethod() != null) && (prop.getReadMethod() != null)) {
prop.getWriteMethod().invoke(destData, prop.getReadMethod().invoke(srcData));
}
}
}
}
public static Object simpleDataCopy(Object data)
throws IllegalAccessException, InstantiationException, IntrospectionException, InvocationTargetException {
if(data == null) {
return null;
}
try {
Object newData = data.getClass().newInstance();
PropertyDescriptor[] props = Introspector.getBeanInfo(data.getClass()).getPropertyDescriptors();
PropertyDescriptor prop = null;
if(props == null || props.length == 0) {
return newData;
} else {
for(int i = 0; i < props.length; i++) {
prop = props[i];
if((prop.getWriteMethod() != null) && (prop.getReadMethod() != null)) {
prop.getWriteMethod().invoke(newData, prop.getReadMethod().invoke(data));
}
}
return newData;
}
} catch (IllegalArgumentException e) {
logger.error("simpleDataCopy()", e);
throw e;
} catch (InstantiationException e) {
logger.error("simpleDataCopy()", e);
throw e;
} catch (IllegalAccessException e) {
logger.error("simpleDataCopy()", e);
throw e;
} catch (IntrospectionException e) {
logger.error("simpleDataCopy()", e);
throw e;
} catch (InvocationTargetException e) {
logger.error("simpleDataCopy()", e);
throw e;
}
}
}
|
JavaScript
|
UTF-8
| 1,716
| 3.640625
| 4
|
[] |
no_license
|
/**
* Created by pl on 5/12/15.
*/
//Standalone functions
x=[4, 15, 6, 3];
y=[7, 1, 3, 6, 2];
function sum(x, y){
var temp = 0;
for (var i in x){
temp += x[i];
}
for (var j in y){
temp += y[j];
}
console.log(temp);
}
function minimum(x){
var temp=x[0];
for (var i in x){
if (temp > x[i]){
temp = x[i];
}
}
console.log(temp);
}
function average(x){
var temp=0;
for (var i in x){
temp += x[i];
}
temp = temp/(x.length);
console.log(temp);
}
//assigned to variables
var zesum = function sum(x, y){
var temp = 0;
for (var i in x){
temp += x[i];
}
for (var j in y){
temp += y[j];
}
console.log(temp);
};
var zeminimum = function minimum(x){
var temp = x[0];
for (var i in x){
if (temp > x[i]){
temp = x[i];
}
}
console.log(temp);
};
var zeaverage = function average(x){
var temp=0;
for (var i in x){
temp += x[i];
}
temp = temp/(x.length);
console.log(temp);
};
var part1 = {
sum: function sum(x, y){
var temp = 0;
for (var i in x){
temp += x[i];
}
for (var j in y){
temp += y[j];
}
console.log(temp);
},
minimum :function minimum(x){
var temp=x[0];
for (var i in x){
if (temp > x[i]){
temp = x[i];
}
}
console.log(temp);
},
average :function average(x){
var temp=0;
for (var i in x){
temp += x[i];
}
temp = temp/(x.length);
console.log(temp);
}
};
part1.sum(x, y);
|
C#
|
UTF-8
| 1,534
| 3.359375
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AL_13_01
{
class Program
{
static StringBuilder wynik = new StringBuilder(1000000);
static void Main(string[] args)
{
int Q = int.Parse(Console.ReadLine());
for (int i = 1; i <= Q; i++)
{
bool num = false;
if (i == Q)
num = true;
Solution(num);
}
Console.WriteLine(wynik.ToString());
}
static void Solution(bool j)
{
int x = Convert.ToInt32(Console.ReadLine());
int[] tab = new int[x];
int i = 1;
bool w = true;
StringBuilder result = new StringBuilder(1000000);
while (i <= x)
{
for(int k = 0; k < tab.Length; k++)
{
if (tab[k] == 0)
{
if (w)
{
tab[k] = i;
i++;
}
w = (w == true) ? w = false : w = true;
}
}
}
foreach (int y in tab)
{
result.Append($"{y} ");
}
if (!j)
wynik.Append($"{result}\n");
else
wynik.Append($"{result}");
}
}
}
|
C++
|
UTF-8
| 833
| 3.390625
| 3
|
[] |
no_license
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int cursum = 0;
// Inorder traversal
TreeNode* solve(TreeNode *root){
if(root == nullptr) return nullptr;
TreeNode *right = solve(root->right);
cursum += root->val;
TreeNode *ret = new TreeNode(cursum);
TreeNode *left = solve(root->left);
ret->left = left;
ret->right = right;
return ret;
}
TreeNode* convertBST(TreeNode* root) {
return solve(root);
}
};
|
Python
|
UTF-8
| 3,560
| 2.71875
| 3
|
[
"MIT",
"Elastic-2.0",
"Apache-2.0",
"BSD-3-Clause"
] |
permissive
|
#
# Copyright (c) 2023 Airbyte, Inc., all rights reserved.
#
import inspect
from abc import ABC, abstractmethod
from typing import Any, Callable, Dict, Generator, List, Mapping, Tuple
from airbyte_cdk.models import AirbyteStream, ConfiguredAirbyteCatalog, ConfiguredAirbyteStream, SyncMode
from airbyte_cdk.sources.utils.schema_helpers import ResourceSchemaLoader
def package_name_from_class(cls: object) -> str:
"""Find the package name given a class name"""
module: Any = inspect.getmodule(cls)
return module.__name__.split(".")[0]
class StreamStateMixin:
def get_stream_state(self, name: str) -> Any:
"""Get state of stream with corresponding name"""
raise NotImplementedError
def set_stream_state(self, name: str, state: Any):
"""Set state of stream with corresponding name"""
raise NotImplementedError
def stream_has_state(self, name: str) -> bool:
"""Tell if stream supports incremental sync"""
return False
class BaseClient(StreamStateMixin, ABC):
"""Base client for API"""
schema_loader_class = ResourceSchemaLoader
def __init__(self, **kwargs):
package_name = package_name_from_class(self.__class__)
self._schema_loader = self.schema_loader_class(package_name)
self._stream_methods = self._enumerate_methods()
def _enumerate_methods(self) -> Mapping[str, Callable]:
"""Detect available streams and return mapping"""
prefix = "stream__"
mapping = {}
methods = inspect.getmembers(self.__class__, predicate=inspect.isfunction)
for name, method in methods:
if name.startswith(prefix):
mapping[name[len(prefix) :]] = getattr(self, name)
return mapping
@staticmethod
def _get_fields_from_stream(stream: AirbyteStream) -> List[str]:
return list(stream.json_schema.get("properties", {}).keys())
def _get_stream_method(self, name: str) -> Callable:
method = self._stream_methods.get(name)
if not method:
raise ValueError(f"Client does not know how to read stream `{name}`")
return method
def read_stream(self, stream: AirbyteStream) -> Generator[Dict[str, Any], None, None]:
"""Yield records from stream"""
method = self._get_stream_method(stream.name)
fields = self._get_fields_from_stream(stream)
for message in method(fields=fields):
yield dict(message)
@property
def streams(self) -> Generator[AirbyteStream, None, None]:
"""List of available streams"""
for name, method in self._stream_methods.items():
supported_sync_modes = [SyncMode.full_refresh]
source_defined_cursor = False
if self.stream_has_state(name):
supported_sync_modes += [SyncMode.incremental]
source_defined_cursor = True
yield AirbyteStream(
name=name,
json_schema=self._schema_loader.get_schema(name),
supported_sync_modes=supported_sync_modes,
source_defined_cursor=source_defined_cursor,
)
@abstractmethod
def health_check(self) -> Tuple[bool, str]:
"""Check if service is up and running"""
def configured_catalog_from_client(client: BaseClient) -> ConfiguredAirbyteCatalog:
"""Helper to generate configured catalog for testing"""
catalog = ConfiguredAirbyteCatalog(streams=[ConfiguredAirbyteStream(stream=stream) for stream in client.streams])
return catalog
|
Python
|
UTF-8
| 515
| 3.0625
| 3
|
[] |
no_license
|
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
table = {}
result = 0
for ss in s:
if not table.has_key(ss):
table[ss] = 1
else:
table[ss] += 1
for v in table.values():
if v % 2 == 0:
result += v
else:
result += (v - 1)
if result < len(s):
result += 1
return result
|
Markdown
|
UTF-8
| 6,271
| 3.03125
| 3
|
[
"MIT"
] |
permissive
|
# Fabric

[](https://travis-ci.org/FabricLabs/fabric)
[](https://codecov.io/gh/FabricLabs/fabric)
[](https://github.com/FabricLabs/fabric/graphs/contributors)
<small>**Notice:** use of Fabric in production is **not recommended** in its current state. Please wait for an official release before deploying.</small>
Fabric is a **research project** intent on discovering the best means for
developing secure, decentralized applications that benefit humanity in its
relentless pursuit of truth.
We're designing next-generation technologies that solve the most fundamental
challenges in society, ranging from economic oppression and institutional
violence to the efficient distribution of cat photos and dank memes.
## Getting Started
To install Fabric, ensure `node -v >= 8.0.0` and `npm i FabricLabs/fabric` into
whichever repository you intend to publish.
## Available Commands
- `npm run cli` provides a direct command-line interface to the Fabric network.
- `npm run docs` creates a local HTTP server for browsing documentation.
- `npm run examples` creates a local HTTP server for interacting with examples.
- `npm start` creates a local Fabric node.
## Using as a Library
Fabric exposes a constructor with several components which are convenient for
including in your existing applications. Convenient functions exist for common
frameworks such as React and Angular.
### Simple Example
```js
const Fabric = require('fabric');
const service = new Fabric();
```
`service` now contains a full instance of Fabric, including `GET` and `SET`
methods for storing and retrieving documents. Use `npm run examples` to see
more.
## Why?
Legacy systems are [constantly failing][everything-is-broken],
resulting in the loss of some really cool things! Some are rushing to save the
good stuff, from content (see the great folks at Archive.org) to infrastructure
and even the applications themselves. When systems fail, they often take value
with them as _collateral damage_. Fabric is an attempt at solving this problem.
It's more than content — it's how we approach it, too. Society has a complex
relationship with technology, and a good technology is an extension of our
humanity. A _great_ technology is one that **improves** our humanity. If we're
designing systems that must be saved, how can we change our approach so that
they survive on their own?
It turns out our technology has been designed around old paradigms, and in some
cases it _wasn't_ the best idea or design that "won". Some parts of the world's
most important infrastructure (the Internet) are incredibly vulnerable, and in
some cases even directly endanger people's **lives**.
It's time we started building software that is **secure by default**, made
widely available (especially to those in need), and empowering in a deeply
personal way.
### Who are we?
We're the people behind projects like the Maki application framework, the
DECENTRALIZE podcast, and the Bitcoin Strategy Group. Our community comes from
all around the globe, but we've all been connected by a powerful technology like
none before: the Internet. We want to protect the value that the Internet
offers society.
## Our Approach
We believe that secure decentralized systems play an essential role in creating
the trust necessary for a future society to rely on infrastructure that operates
outside of their direct control. We believe that for such a society to exist,
the default mode should be `local`, wherein the user is most empowered to effect
change.
We believe in the power of the people to create better things in collaboration,
and have ideas about general improvements to quality of life that derive from
the mathematical quality of _superadditivity_. "A sum greater than its parts"
is the famous anecdote, a feeling often evoked upon observing [the beauty in
coordination][coordination].
![Flock of Birds][coordination]
We believe that collaboration begins with the author, who has the power to
publish their own content and right to benefit from its use. Intermediaries
offering little or no value should be removed, and efficiencies gained.
## Other Fabrics
Several other projects have used the name Fabric, as it's a great way to
describe a network of things, conjuring feelings of _nets_ and _webs_. Here are
some links to them, as they offer some interesting things completely unrelated
to our goals.
- Fabric python project (#fabric on Freenode)
- Fabric application framework by Twitter (ours is called Maki)
## Learning More
The best place to get started is in the [#learning][learning] community, a
collection of empassioned educators eager to help you.
## Getting Involved
Fabric is an open-source project, meaning we rely on volunteer time to develop
and maintain our initiative. We collect donations [through a publicly-auditable
system][bitcoin-donations] (hint, it's Bitcoin!), but the most valuable thing
you can do _right now_ is to [participate in the conversation][join], and if
you're so inclined — consider contributing some code!
Developers, head on over to [#development][development] to dive straight in.
We've got a lot of cool things to build, so please come help. :)
### Donations
Bitcoin donations may be sent to
[3Nc9HqZdfQR7W6c1JN926Rc7vU6eT1wxxn][bitcoin-donations], or perhaps even [set up
a recurring donation through Gratipay][gratipay].
### Elsewhere
We love social media. Connect and chat with us.
Twitter: [@FabricProtocol][twitter]
[learning]: https://maki.io/topics/learning
[development]: https://maki.io/topics/development
[everything-is-broken]: https://medium.com/message/everything-is-broken-81e5f33a24e1
[coordination]: https://i.imgur.com/Ki3fbTh.gif
[bitcoin-donations]: bitcoin:3Nc9HqZdfQR7W6c1JN926Rc7vU6eT1wxxn
[gratipay]: https://gratipay.com/fabric
[twitter]: https://twitter.com/FabricProtocol
[join]: https://maki.io/community
|
PHP
|
UTF-8
| 13,193
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace App\Classes\Pedidos;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
class ImportarPedidos
{
public function importar() {
//$ORDER_ID = $this->input->post("idped");
$arquivo = "arquivoML";
//$ACCESS_TOKEN = $this->session->userdata("token");
session_start();
if(isset($_SESSION['access_token'])){
$token = $_SESSION['access_token'];
}else{
dd('token não encontrado');
}
$token = $_SESSION['access_token'];
//Pegar pedidos do banco de dados tbimport
//$array = DB::table('tbimport')->get()->toArray();
//dd($array);
$usuario = Auth::user()->name;
$objeto = DB::table('tbimport')->where('usuario', $usuario)->get();
//dd($objeto);
//var_dump($array);
//$object = new stdClass();
//$objeto = (object) $array;
$listaPedido = null;
$errno = null;
$errno2 = null;
foreach ($objeto as $pedido) {
//echo 'ped-->> ' . $pedido->pedido;
$ORDER_ID = str_replace(" ", "", $pedido->pedido);
$existe = false;
//dd($pedido);
//echo '<br />';
//IMPORTAR O PEDIDO DO ML - ORDER
//curl -X GET -H 'Authorization: Bearer $ACCESS_TOKEN' https://api.mercadolibre.com/orders/2032217210
//curl -X GET -H 'Authorization: Bearer $ACCESS_TOKEN' https://api.mercadolibre.com/orders/768570754
$response = Http::withToken($token)->get('https://api.mercadolibre.com/orders/' . $ORDER_ID);
//dd($response->json());
//var_dump($resposta);
$importado = json_decode($response, FALSE);
//echo $len;
// Verifica se houve erros e exibe a mensagem de erro
if ($response->failed()) {
//erro
} else {
if (!$token) {
//echo '<br /><br />';
// echo("ERRO - Tokem não gerado ou pedido não encontrado");
$existe = true;
//echo '<br /><br />';
//var_dump($importado);
//echo '<br /><br />';
} else {
//var_dump($importado);
//print_r($resposta);
$idPedidoML = $importado->id ?: "";
$total_amount = $importado->total_amount ?: 0;
$paid_amount = $importado->paid_amount ?: 0;
$title = $importado->order_items[0]->item->title ?: "";
$seller_sku = $importado->order_items[0]->item->seller_sku ?: 999999999;
if (property_exists($importado, "value_name")) {
$value_name = $importado->order_items[0]->item->variation_attributes[0]->value_name ?: "";
}else{
$value_name = "";
}
$quantity = $importado->order_items[0]->quantity ?: 0;
$unit_price = $importado->order_items[0]->unit_price ?: 0;
$sale_fee = $importado->order_items[0]->sale_fee ?: 0;
$shipping = $importado->shipping->id ?: "inexistente";
$buyerid = $importado->buyer->id ?: "";
$nickname = $importado->buyer->nickname ?: "";
$email = $importado->buyer->email ?: "";
$first_name = "";
$last_name = "";
$area_code = $importado->buyer->phone->area_code ?: "";
$numberfone = $importado->buyer->phone->number ?: "";
$area_code2 = $importado->buyer->alternative_phone->area_code ?: "";
$numberfone2 = $importado->buyer->alternative_phone->number ?: "";
}
}
//IMPORTAR COMPRADOR - BUYER
//curl -X GET -H 'Authorization: Bearer $ACCESS_TOKEN' https://api.mercadolibre.com/orders/$ORDER_ID/billing_info
$response3 = Http::withToken($token)->get('https://api.mercadolibre.com/orders/' . $ORDER_ID . '/billing_info');
//dd($response3->json());
//var_dump($resposta);
$importado3 = json_decode($response3, FALSE);
//var_dump($importado2);
// Verifica se houve erros e exibe a mensagem de erro
if ($response3->failed()) {
//erro importação
} else {
//print_r($resposta);
if (!$token) {
//echo '<br /><br />';
//echo("ERRO - Tokem não gerado ou envio não encontrado");
//echo '<br /><br />';
//var_dump($importado2);
} else {
//$city = $importado3->billing_info->additional_info[0]->value ?: "";
//$street_number = $importado3->billing_info->additional_info[1]->value ?: "";
//$site_id = $importado3->billing_info->additional_info[2]->value ?: "";
//$neighborhood = $importado3->billing_info->additional_info[3]->value ?: "";
//$first_name = $importado3->billing_info->additional_info[4]->value ?: "";
//$$state = $importado3->billing_info->additional_info[5]->value ?: "";
//$last_name = $importado3->billing_info->additional_info[6]->value ?: "";
//$street_name = $importado3->billing_info->additional_info[7]->value ?: "";
$doc_type = $importado3->billing_info->doc_type ?: "";
$doc_number = $importado3->billing_info->doc_number ?: "";
//$comment = $importado3->billing_info->additional_info[10]->value ?: "";
//$zip_code = $importado3->billing_info->additional_info[11]->value ?: "";
$tamanho = count($importado3->billing_info->additional_info);
//echo $tamanho;
//die;
if($doc_type == 'CPF'){
for ($i=0; $i < $tamanho; $i++) {
if($importado3->billing_info->additional_info[$i]->type == "FIRST_NAME" ){
$first_name = $importado3->billing_info->additional_info[$i]->value ?: ""; break;
}
}
for ($i=0; $i < $tamanho; $i++) {
if($importado3->billing_info->additional_info[$i]->type == "LAST_NAME" ){
$last_name = $importado3->billing_info->additional_info[$i]->value ?: ""; break;
}
}
}
if($doc_type == 'CNPJ'){
for ($i=0; $i < $tamanho; $i++) {
if($importado3->billing_info->additional_info[$i]->type == 'BUSINESS_NAME' ){
$first_name = $importado3->billing_info->additional_info[$i]->value ?: "";
$last_name ="";
}
}
}
//echo("first_name -- " . $first_name . " ");
//echo("last_name -- ". $last_name . "<br />");
//echo("doc_type -- " . $doc_type . "<br />");
//echo("doc_number -- " . $doc_number . "<br />");
//die;
}
}
//IMPORTAR ENTREGA - SHIPMENTS
//echo '---------------------';
//echo '<br /><br />';
//curl -X GET -H 'Authorization: Bearer $ACCESS_TOKEN' https://api.mercadolibre.com/shipments/shipment_id
$response2 = Http::withToken($token)->get('https://api.mercadolibre.com/shipments/' . $shipping);
//dd($response->json());
//var_dump($resposta);
$importado2 = json_decode($response2, FALSE);
//var_dump($importado2);
// Verifica se houve erros e exibe a mensagem de erro
if ($response->failed()) {
//erro importação
} else {
//print_r($resposta);
if (!$token) {
//echo '<br /><br />';
//echo("ERRO - Tokem não gerado ou envio não encontrado");
//echo '<br /><br />';
//var_dump($importado2);
} else {
$street_name = $importado2->receiver_address->street_name ?: "";
$street_number = $importado2->receiver_address->street_number ?: "";
$comment2 = $importado2->receiver_address->comment ?: "";
$comment = preg_replace('/[\x00-\x1F\x7F]/u', '-', $comment2);
$zip_code = $importado2->receiver_address->zip_code ?: "";
$city = $importado2->receiver_address->city->name ?: "";
$state = $importado2->receiver_address->state->id ?: "";
$neighborhood = $importado2->receiver_address->neighborhood->name ?: "";
$receiver_name = $importado2->receiver_address->receiver_name ?: "";
$receiver_phone = $importado2->receiver_address->receiver_phone ?: "";
$cost = $importado2->shipping_option->cost ?: 0;
//echo("street_name -- " . $street_name . " - ");
//echo($street_number . "<br />");
//echo("comment -- " . $comment . "<br />");
//echo("zip_code -- " . $zip_code . "<br />");
//echo("city -- " . $city . " - ");
//echo($state . "<br />");
//echo("neighborhood -- " . $neighborhood . "<br />");
//echo("receiver_name -- " . $receiver_name . "<br />");
//echo("receiver_phone -- " . $receiver_phone . "<br />");
//echo("cost -- " . $cost . "<br />");
}
}
//CSV - Criar arquivo - criando o array de valores a ser gravado
$listaPedido[$idPedidoML]['idPedidoML'] = $idPedidoML;
$listaPedido[$idPedidoML]['total_amount'] = $total_amount;
$listaPedido[$idPedidoML]['paid_amount'] = $paid_amount;
$listaPedido[$idPedidoML]['seller_sku'] = $seller_sku;
$listaPedido[$idPedidoML]['title'] = $title;
$listaPedido[$idPedidoML]['value_name'] = $value_name;
$listaPedido[$idPedidoML]['quantity'] = $quantity;
$listaPedido[$idPedidoML]['unit_price'] = $unit_price;
$listaPedido[$idPedidoML]['sale_fee'] = $sale_fee;
$listaPedido[$idPedidoML]['shipping'] = $shipping;
$listaPedido[$idPedidoML]['buyerid'] = "";
$listaPedido[$idPedidoML]['nickname'] = $nickname;
$listaPedido[$idPedidoML]['email'] = $email;
$listaPedido[$idPedidoML]['first_name'] = str_replace(";", " ", $first_name);
$listaPedido[$idPedidoML]['last_name'] = str_replace(";", " ", $last_name);
$listaPedido[$idPedidoML]['area_code'] = $area_code;
$listaPedido[$idPedidoML]['numberfone'] = $numberfone;
$listaPedido[$idPedidoML]['area_code2'] = $area_code2;
$listaPedido[$idPedidoML]['numberfone2'] = $numberfone2;
$listaPedido[$idPedidoML]['doc_type'] = $doc_type;
$listaPedido[$idPedidoML]['doc_number'] = $doc_number;
$listaPedido[$idPedidoML]['street_name'] = str_replace(";", " ", $street_name);
$listaPedido[$idPedidoML]['street_number'] = $street_number;
$listaPedido[$idPedidoML]['comment'] = str_replace(";", " ", $comment);
$listaPedido[$idPedidoML]['zip_code'] = $zip_code;
$listaPedido[$idPedidoML]['city'] = $city;
$listaPedido[$idPedidoML]['state'] = $state;
$listaPedido[$idPedidoML]['neighborhood'] = str_replace(";", " ", $neighborhood);
$listaPedido[$idPedidoML]['receiver_name'] = str_replace(";", " ", $receiver_name);
$listaPedido[$idPedidoML]['receiver_phone'] = str_replace(" ", "", $receiver_phone);
$listaPedido[$idPedidoML]['cost'] = $cost;
//echo("---Nome da Rua --- " . "<br />");
//print_r($listaPedido[$idPedidoML]['street_name']) . "<br />";
//print_r($listaPedido);
//echo '-----------------------------------------------------------' . '<br />';
}// foreach pedidos
//print_r($listaPedido);
//die;
//Exportar arquivo para csv
dd($listaPedido);
}
}
|
Markdown
|
UTF-8
| 53,350
| 3.484375
| 3
|
[] |
no_license
|
# 你不知道的Javascript学习笔记
## 上册
### 作用域和闭包
#### 引擎查询
LHS/RHS:变量在赋值操作左边(LHS)、在赋值操作右边(RHS)
```js
a = 2 //LHS
b = a // ..=a RHS
```
嵌套作用域:作用域发生嵌套,引擎会在外层作用域中继续查找,直到找到或者抵达全局作用域。
#### 异常
RHS中若找不到,则抛出**ReferenceError**
LHS找不到,则会在全局作用域中创建该变量,**注意!**若采用**'use strict'** (ES5中引入) 则不会创建,同样抛出**ReferenceError**
RHS若查找到但进行了不合理操作,则抛出**TypeError**
#### 查找
**”遮蔽效应“**:作用域查找会在找到第一个匹配的标识符时停止。逐级向上查找。
全局变量会自动成为全局对象,例如window.a
#### 欺骗词法
1. eval
```js
function foo(str,a) {
eval( str )
console.log( a, b );
}
var b = 2;
foo( "var b = 3;" 1 ); // 1, 3 遮蔽了外部同名变量b=2
```
通过代码欺骗和假装**词法期**来修改**词法作用域环境**。
在严格模式中,eval有其自己的词法作用域,无法修改所在的作用域:
```js
function foo(str) {
"use strict";
eval( str );
console.log( a ); //ReferenceError: a is not defined
}
foo( "var a = 2" )
```
2. with
重复引用同一个对象中多个属性的快捷方式
```js
var obj = {
a: 1,
b: 2,
c: 3
}
//可通过with(...)
with(obj) {
a = 3;
b = 4;
c = 5
}
```
同时还可以用于赋值
```js
function foo(obj) {
with(obj) {
a = 2;
}
}
var o1 = {
a: 3
};
var o2 = {
b: 3
};
foo( o1 );
console.log( o1.a ); //2
foo( o2 );
console.log( o2.a ); //undefined
console.log( a ); // 2--a被泄露到了全局作用域
```
上述两种方式会存在运行效率问题,同时不推荐使用,在严格模式下会被限制。
#### 函数作用域
通过最小暴露原则进行设计,可以实现内容私有化,规避作用域冲突。
```js
function doSomething(a) {
function doSomethingElse(a) { //内部函数
return a - 1;
}
var b; //内部变量
b = a + doSomethingElse( a * 2);
console.log( b * 3);
}
doSomething( 2 ); // 15
```
通过内部定义可以隐藏变量和函数定义,但是会导致额外的**作用域污染**
```js
//...全局作用域
function foo() {
}
foo(); //具名函数foo()污染了全局作用域
//可通过包装函数来解决作用域污染
(function foo(){ //函数会当做函数表达式来处理
...
})(); //第二个()表示立即执行 IIFE(Immediately Invoked Function Expression)
```
#### 匿名和具名
匿名函数会导致
1. 在栈追踪中不会显示出有意义的函数名,导致调试困难
2. 引用自身时需要使用已过期的arguments.callee
3. 可读性差
```js
setTimeout( function() { //匿名函数
...
},1000)
setTimeout( function timeoutHandler() { //行内函数表达式
...
},1000)
```
#### 立即执行函数表达式
两种方式:
```js
(function foo(){ .. })()
(function(){ .. }())
```
IIFE可以当做函数调用并传递参数进去
```js
(function IIFE( global ){ //将window参数名global传入
var a = 3;
console.log( a ); //3
console.log( global.a ); //2
})( window );
console.log( a ); //2
```
可以解决undefined默认标识符被错误覆盖导致的异常
```js
undefined = true; //错误赋值
(function IIFE( undefined ){
var a;
if(a === undefined){
console.log("Undefined is safe here!");
}
})(); //undefined
```
可以倒置代码运行顺序,UMD中广泛使用:
```js
var a = 2;
(function IIFE( def ){
def( window );
})(function def( global ){ //将window作为global在def中使用
var a = 3;
console.log( a ); //3
console.log( global.a ); //2
});
```
#### 块作用域
在for中,定义的变量i会被绑定在**外部作用域中**!!!
```js
for (var i=0; i<10; i++) {
console.log( i );
}
```
##### 1.with
用with从对象中创建的作用域仅在with生命中而非外部作用域中有效。
##### **2.try/catch**
从ES3规范中规定catch分句中会创建一个块作用域,仅在catch中有效
```js
try {
undefined(); //创造异常
}
catch (err) {
console.log( err );
}
console.log( err ) //ReferenceError
```
###### ES6之前的块作用域替代方案
```js
// 在ES6中可以利用块作用域
{
let a = 2;
console.log( a ); // 2
}
console.log( a ); // ReferenceError
// ES6之前,try/catch中的catch是块作用域,从而实现。
try{throw 2;}catch(a){
console.log( a ); // 2
}
console.log( a ); // ReferenceError
```
##### **3.let**
let形成了一个块作用域
```js
var foo = true;
if(foo) {
{ // <--显式的块
let bar = foo * 2;
bar = something( bar );
console.log( bar );
}
}
console.log( bar ); //ReferenceError
```
(1) 垃圾收集
```js
function process(data) {
}
var someReallyBigData = { .. }
process( someReallyBigData );
var btn = document.getElementById( "my_button" );
btn.addEventListener( "click", function click(evt){
console.log("button clicked");
}, /*capturingPhase*/false );
```
click形成了一个覆盖整个作用域的闭包,会导致someReallyBigData无法回收。可通过块作用域解决:
```js
{ //块中定义内容可以销毁
let someReallyBigData = { .. };
process( someReallyBigData )
}
```
(2) let循环
let不仅将i绑定到了for循坏的块中,事实上将其重新绑定到了循环的每一个迭代中重新赋值。
```js
{
let j;
for (j=0; j<10; j++){
let i = j //每个迭代重新绑定
console.log( i );
}
}
```
###### let和var的区别
1. var存在变量提升,let不存在
2. let不允许在相同作用域内,重复声明同一个变量
3. 暂时性死区
```js
// 在代码块内,使用let声明前该变量均不可用
//暂时性死区 temporal dead zone TDZ
var tmp = 123;
if(true){
tmp = 'abc'; //ReferenceError
let tmp;
}
```
##### 4.const
const为固定常量,也可以用来创建块作用域变量。
#### 提升
##### 1.变量提升
变量和函数的所有声明会在任何代码被执行前首先被处理。
范例1:
```js
// 代码
a = 2;
var a;
console.log( a );
// 执行顺序
var a;
a = 2;
console.log( a ); //2
```
范例2:
```js
// 代码
console.log( a );
var a = 2;
// 执行顺序
var a;
console.log( a ); //undefined
a = 2;
```
范例3:
```js
foo(); //不是ReferenceError,而是TypeError
var foo = function bar() {
// ...
};
```
foo变量定义被提升,但并未赋值,对于undefined进行函数调用抛出TypeError异常。
范例4:
```js
foo(); //TypeError
bar(); //ReferenceError
var foo = function bar() {
// ...
};
// 实际提升后
var foo;
foo(); //TypeError
bar(); //ReferenceError
foo = function(){
var bar = ...self...
// ...
}
```
##### 2.函数优先
函数声明和变量声明都被提升,但是函数优先级高
````js
// var foo和function foo声明重复而被忽略,函数声明被提到普通变量之前。同时出现在后面的函数会覆盖前面的,最终输出3
foo(); //3
var foo;
function foo(){
console.log( 1 );
}
var foo = function(){
console.log( 2 );
};
function foo(){
console.log( 3 );
};
//引擎理解形式如下:
function foo() {
console.log( 3 );
}
foo(); //3
foo = function(){
console.log( 2 );
};
````
#### 闭包
当函数可以记住并访问所在的词法作用域,即使函数实在当前词法作用域之外执行,这时就产生了闭包。
范例1:
```js
//bar()在自己定义的词法作用域以外执行,它拥有涵盖foo()内部作用域的闭包,使该作用于一直存活。
function foo() {
var a = 2;
function bar(){
console.log( a );
}
return bar;
}
var baz = foo();
baz(); // 2 ——闭包
```
范例2:
```js
function foo(){
var a = 2;
function baz(){
console.log( a ); //2
}
bar( baz )
}
function bar(fn){
fn(); //闭包。 fn即baz拥有foo()的整个作用域,访问变量a
}
foo();
```
范例3:
```js
//timer涵盖wait(..)的作用域闭包,传递给setTimeout(..),同时还保留对变量message的引用
function wait(message){
setTimeout( function timer(){
console.log( message )
}, 1000);
}
wait( "Hello,closure!" )
```
##### 循环
```js
//延迟函数的回调会在循环结束时才执行。
for(var i=1;i<=5;i++){
setTimeout(function timer(){
console.log(i); //6 6 6 6 6
},i*1000);
}
//将i作为参数传递给IIFE解决问题。
for(var i=1;i<=5;i++){
(function(j)
setTimeout(function timer(){
console.log( j ); //1 2 3 4 5
}, j*1000 );
)( i );
}
//进一步的
for(let i=1; i<=5; i++){
setTimeout( function timer(){
console.log( i );
}, i*1000 );
}
```
##### 模块
以下模式称为**模块**,实现模块方式的方法称为模块暴露
模块模式的必要条件:
1. 必须有外部的封闭函数,该函数被至少调用一次
2. 封闭函数返回一个内部函数,这样内部函数才能在私有作用域中形成闭包,并可以访问或者修改私有状态。
```js
function CoolModule(){
var something = "cool";
var another = [1, 2, 3];
function doSomething(){
console.log( something );
}
function doAnother(){
console.log( another.join( " ! ") );
}
return{
doSomething: doSomething,
doAnother: doAnother
};
}
var foo = CoolModule();
foo.doSomething(); //cool
foo.doAnother(); // 1 ! 2 ! 3
```
单例模式:
```js
var foo = (function CoolModule(){
var something = "cool";
var another = [1, 2, 3];
function doSomething(){
console.log( something );
}
function doAnother(){
console.log( another.join( " ! ") );
}
return {
doSomething: doSomething,
doAnother: doAnother
}
})(); //立即调用函数IIFE
foo.doSomething();
foo.doAnother();
```
###### 现代模块机制
通过封装进API,实现模块依赖加载器/管理器
```js
var MyModules = (function Manager(){
var modules = {};
function define(name, deps, impl){
for(var i=0; i<deps.length; i++){
deps[i] = module[deps[i]];
}
modules[name] = impl.apply( impl, deps );
}
function get(name){
return modules[name];
}
return {
define: define,
get: get
}
})();
```
使用方法:
```js
MyModules.define("bar",[],function(){
function hello(who){
return "Let me introduce: " + who;
}
return {
hello: hello
};
});
MyModules.define("foo",["bar"],function(bar){
var hungry = "hippo";
function awesome(){
console.log( bar.hello( hungry ).toUpperCase());
}
return {
awesome: awesome
};
});
var bar = MyModules.get( "bar" );
var foo = MyMudules.get( "foo" );
console.log(
bar.hello("hippo")
); //Let me introduce: hippo
foo.awesome(); // LET ME INTRODUCE: HIPPO
```
###### 未来的模块机制
ES6增加一级语法支持,导入或导出其他模块或特定的API成员,模块需要定义在**独立文件中**,没有**“行内”**格式。
```js
//bar.js
function hello(who){
return "Let me introduce: " + who;
}
export hello;
//foo.js
import hello from "bar";
var hungry = "hippo";
function awesome(){
console.log(
hello( hungry ).toUpperCase()
);
}
export awesome;
//baz.js
module foo from "foo";
module bar from "bar";
console.log(
bar.hello("rhino")
); //let me introduce: rhino
foo.awesome(); //LET ME INTRODUCE: HIPPO
```
### this解析
调用栈中的调用位置,决定了this的绑定
```js
function baz() {
// 当前调用栈是:baz
// 因此,当前调用位置是全局作用域
console.log( "baz" );
bar(); // <-- bar 的调用位置
}
function bar() {
// 当前调用栈是 baz -> bar
// 因此,当前调用位置在 baz 中
console.log( "bar" );
foo(); // <-- foo 的调用位置
}
function foo() {
// 当前调用栈是 baz -> bar -> foo
// 因此,当前调用位置在 bar 中
console.log( "foo" );
}
baz(); // <-- baz 的调用位置
```
#### 绑定规则
##### 默认绑定
决定this绑定对象的并不是调用位置是否处于严格模式,而是函数体是否处于严格模式,从而this绑定到undefined或者全局对象上
```js
//this的默认绑定指向全局对象
function foo(){
console.log( this.a )
}
var a =2;
foo(); // 2
//在严格模式下,全局对象无法使用默认绑定,此处的this会绑定到undefined
function foo(){
"use strict"
console.log( this.a )
}
var a = 2;
foo(); // TypeError: this is undefined
//虽然this的绑定取决于调用位置,但是只有foo()运行在非strict mode下时,默认绑定才能绑定到全局对象;严格模式下与foo()的调用位置无关。
function foo() {
console.log( this.a );
}
var a = 2;
(function(){
"use strict";
foo(); // 2
})();
```
##### 隐式绑定
对象属性引用链中只有最顶层或者说最后一层会影响调用位置。
```js
function foo() {
console.log( this.a );
}
var obj2 = {
a: 42,
foo: foo
};
var obj1 = {
a: 2,
obj2: obj2
};
obj1.obj2.foo(); // 42
```
###### 隐式丢失
被隐式绑定的函数会丢失绑定对象,应用默认绑定,将this绑定到全局对象或者undefined上。
```js
function foo() {
console.log( this.a );
}
function doFoo(fn) {
// fn 其实引用的是 foo
fn(); // <-- 调用位置!
}
var obj = {
a: 2,
foo: foo
};
var a = "oops, global"; // a 是全局对象的属性
doFoo( obj.foo ); // "oops, global"
//调用语言内置函数没有区别
setTimeout( obj.foo, 100); // "oops, global"
```
参数传递也是一种隐式赋值
##### 显式绑定
可通过call(..)和apply(..)进行显式绑定,但显式绑定无法解决丢失绑定问题。
```js
var a = 123;
function foo(){
console.log( this.a );
}
var obj = {
a:2
};
foo.call( obj ); //2 通过.call(..)强制将this绑定到obj上
setTimeout( foo, 100 ); //123 绑定丢失
```
当传入一个原始值来当做this的绑定对象,这个原始值会被转换成它的对象形式( new String(..)、new Boolean(..)或者new Number(..))。这成为“装箱”。
###### call和apply区别
参数传递格式不同,apply为数组形式,call为参数列表形式
apply( [ thisObj [ , argArray ] ] );
call( [ thisObject [ , arg1 [ , arg2 [ , ... , argn ] ] ] ] );
###### apply的用法
apply可以将一个数组默认转换为一个参数列表。对于Math.max不支持数组形式的参数,但是支持Math.max(param1, param2, param3...)。因此可以通过apply来解决这一问题;Arrayprototype.push方法也可以通过apply来解决数组的传值。
```js
Math.max.apply( null, array );
Math.min.apply( null, array );
var arr1 = new Array("1", "2", "3");
var arr2 = new Array("4", "5", "6");
Array.prototype.push.apply( arr1, arr2 );
```
###### 硬绑定
显式的强制绑定,无论如何调用函数bar,都会手动在obj上调用foo
```js
function foo() {
console.log( this.a );
}
var obj = {
a:2
};
var bar = function() {
foo.call( obj );
};
bar(); // 2
setTimeout( bar, 100 ); // 2
// 硬绑定的 bar 不可能再修改它的 this
bar.call( window ); // 2
```
硬绑定的典型应用场景就是创建包裹函数,传入所有的参数并返回接收到的所有值
```js
var bar = function(){
return foo.apply( obj, arguments );
}
//也可以创建一个可复用的辅助函数
function bind(fn, obj){
return function(){
return fn.apply( obj, arguments );
}
}
...
var bar = bind( foo, obj );
var b = bar( 3 );
```
由于硬绑定的常用性,在ES5中提供了内置的方法Function.prototype.bind,使用.bind(..)会返回一个硬编码的新函数,并将参数设置为this的上下文并调用原始函数。
###### API调用的“上下文”
第三方库或者JavaScrpit语言和宿主环境中的许多新的内置函数,都提可选参数,被称为“上下文”(context),确保回调函数使用指定的this
```js
[1, 2, 3].forEach( foo, obj ); //把this绑定到obj
```
##### new绑定
使用new来调用函数会执行四步操作:
1. 创建一个全新对象
2. 新对象被执行[[原型]]连接
3. 新对象绑定到函数调用的this
4. 如果没有返回其他对象,new表达式中的函数调用会自动返回新对象
```js
function foo(a) {
this.a = a;
}
var bar = new foo(2);
console.log( bar.a ); // 2
```
##### 优先级
new优先级 > 显式优先级
```js
function foo(p1,p2) {
this.val = p1 + p2; }
// 之所以使用 null 是因为在本例中我们并不关心硬绑定的 this 是什么
// 反正使用 new 时 this 会被修改
var bar = foo.bind( null, "p1" );
var baz = new bar( "p2" );
baz.val; // p1p2
```
###### 判断this
1. new绑定,this绑定的是新创建的对象
```js
var bar = new foo()
```
2. call、apply (显式绑定),this绑定是指定的对象
```js
var bar = foo.call(obj2)
```
3. 上下文对象调用(隐式绑定),this绑定的是上下文对象。
```js
var bar = obj1.foo()
```
4. 如果都不是,使用默认绑定。在严格模式下绑定undefined,否则绑定到全局对象
```js
var bar = foo()
```
#### 绑定例外
##### 忽略this
把null或者undefined作为this的绑定对象传入call、apply或者bind,应用默认规则绑定。
**应用场景**:使用apply(..)来展开一个数组,并当做参数传入函数。bind(..)可以对参数进行柯里化(预先设置一些参数)。
但是默认规则会把**this绑定到全局对象**,会导致全局对象修改等问题、
```js
function foo(a,b){
console.log( "a:" + a + ", b:" + b );
}
//把数组展开成参数
foo.apply( null, [2, 3] ); // a:2, b:3
//使用bind(..)进行柯里化
var bar = foo.bind( null, 2);
bar( 3 ); // a:2, b:3
```
###### **更安全的this**
可以传入特殊对象,把this绑定到DMZ(demilitarized zone,非军事区)
```js
//创建了一个空对象,但是相比{},不会创建Object.prototype这个委托
var ø = Object.create( null ); //创建一个DMZ对象
foo.apply( ø, [..] );
```
##### 间接引用
```js
function foo() {
console.log( this.a );
}
var a = 2;
var o = { a: 3, foo: foo };
var p = { a: 4 };
o.foo(); // 3
(p.foo = o.foo)(); // 2
//p.foo = o.foo 返回值是目标函数的引用,调用的是foo()而不是p.foo()或者o.foo(),因此这里应用的是默认绑定。
```
##### 软绑定
硬绑定后无法通过显式或者隐式来修改this,可以给默认绑定指定一个全局对象或者undefined以外的值来实现硬绑定相同效果,同时保留修改this的能力。
```js
if (!Function.prototype.softBind) {
Function.prototype.softBind = function(obj) {
var fn = this;
// 捕获所有 curried 参数
var curried = [].slice.call( arguments, 1 );
var bound = function() {
return fn.apply(
(!this || this === (window || global)) ?
obj : this
curried.concat.apply( curried, arguments )
);
};
bound.prototype = Object.create( fn.prototype );
return bound;
};
}
```
上述代码会检查调用时的this,如果是全局对象或者undefined,就把指定的默认对象obj绑定到this,否则不会修改this
```js
function foo() {
console.log("name: " + this.name);
}
var obj = { name: "obj" },
obj2 = { name: "obj2" },
obj3 = { name: "obj3" };
var fooOBJ = foo.softBind( obj );
fooOBJ(); // name: obj
obj2.foo = foo.softBind(obj);
obj2.foo(); // name: obj2 <---- 看!!!
fooOBJ.call( obj3 ); // name: obj3 <---- 看!
setTimeout( obj2.foo, 10 );
// name: obj <---- 应用了软绑定
```
#### this词法
箭头函数根据外层(函数或全局)作用域来决定this,箭头函数的绑定无法被修改。
```js
function foo(){
return (a) => {
//this继承自foo()
console.log( this.a )
};
}
var obj1 = { a:2 };
var obj2 = { a:3 };
var bar = foo.call( obj1 );
bar.call( obj2 ); // 2
```
### 对象
#### 类型
JavaScript共有六种主要类型:string、number、boolean、null、undefined、object
前5种简单基本类型不是对象,null有时会被当做一种对象,但是其实这是语言本身的一个bug,即对null执行typeof null会返回字符串"object"。(JavaScript中二进制前三位为0会被判断为object,**null的二进制全是0**,所以执行typeof会返回"object")
##### 内置对象
对象子类型被称为内置对象:
String、Number、Boolean、Object、Function、Array、Date、RegExp、Error
这些内置函数可以当做构造函数来使用(new产生的函数调用)
```js
//此处只是一个字面量不可变,若进行操作需要转换成String对象
//语言会在必要时自动把字符串转换成一个String对象
var strPrimitive = "I am a string";
typeof strPrimitive; // "string"
strPrimitive instanceof String; // false
var strObject = new String( "I am a string" );
typeof strObject; // "object"
strObject instanceof String; // true
// 检查 sub-type 对象
Object.prototype.toString.call( strObject ); // [object String]
```
null和undefined没有构造形式,只有文字形式。
Date只有构造,没有文字形式。
对于Object、Array、Function和RegExp,无论使用文字形式还是构造形式,都是对象,不是字面量。
Error一般在抛出异常自动创建,也可以new Error(..)。
#### 内容
```js
var myObject = {
a: 2
};
myObject.a; // 2 属性访问,需满足标识符的命名规范
myObject["a"]; // 2 键访问,可接受任意UTF-8/Unicode字符串
```
##### 可计算属性名
ES6中增加了可计算属性名,使用[]包裹表达式来当做属性名
```js
var prefix = "foo";
var myObject = {
[prefix + "bar"]: "hello",
[prefix + "baz"]: "world"
};
myObject["foobar"]; // hello
myObject["foobaz"]; // world
```
##### 数组
数组也支持 [ ] 访问形式,数组通过索引值来访问,也可以添加命名属性( . 语法或者 [ ] 语法)
```js
//当向数组添加一个属性,但是属性名“看起来”想一个数字,则会变成数组下标
var myArray = [ "foo", 42, "bar" ];
myArray["3"] = "baz";
myArray.length; // 4
myArray[3]; // "baz"
```
##### 复制对象
ES6定义了Object.assign(..)方法实现浅复制。它会遍历一个或多个源对象的所有可枚举的自由键,并通过=操作复制到目标对象,源对象属性的一些特性(比如writable)不会被复制到目标对象。
```js
function anotherFunction() { /*..*/ }
var anotherObject = {
c: true
};
var anotherArray = [];
var myObject = {
a: 2,
b: anotherObject, // 引用,不是复本!
c: anotherArray, // 另一个引用!
d: anotherFunction
};
var newObj = Object.assign( {}, myObject )
newObj.a; // 2
newObj.b === anotherObject; // true
newObj.c === anotherArray; // true
newObj.d === anotherFunction; // true
```
##### 属性描述符
ES5之后所有属性都具备属性描述符
```js
var myObject = {
a:2
};
Object.getOwnPropertyDescriptor( myObject, "a" );
// {
// value: 2,
// writable: true, 可写
// enumerable: true, 可枚举
// configurable: true, 可配置
// }
```
在创建普通属性是属性描述符会使用默认值,也可以通过Object.defineProperty(..)修改
```js
var myObject = {};
Object.defineProperty( myObject, "a", {
value: 2,
writable: true,
configurable: true,
enumerable: true
});
```
1. writable:设置为false默认无法修改,严格模式会报TypeError
2. configurable:单项修改,设定后无法修改属性(例外:false状态下可以把writable从true修改为false,但是无法改回;无法用delete删除属性
3. enumerable:控制属性是否出现在对象的属性没居中,比如 for .. in 循环。
##### 不变性
###### 对象常量
结合writable:false 和 configurable:false 可以创建一个常量属性(不可修改、重定义或者删除)
###### 禁止扩展
使用Object.preventExtensions(..)禁止一个对象添加新属性并保留已有属性。
```js
var myObject = {
a:2
};
Object.preventExtensions( myObject );
myObject.b = 3;
myObject.b; // undefined 严格模式会抛出TypeError
```
###### 密封
Object.seal(..)会创建一个密封的对象,实际上会在现有对象上调用Object.preventExtensions(..) 并把所有现有属性标记为configurable:false
###### 冻结
Object.freeze(..)会创建一个冻结对象,即现有对象调用Object.seal(..)并把所有writable:false
##### [[Get]]
查找是否有名称相同的属性,若为找到,则遍历肯能存在的[[Prototype]]原型链。
```js
var myObject = {
a:undefined
};
myObject.a; // undefined
myObject.b; // undefined
```
返回值都为undefined,但是对于myObject.b进行了更复杂的处理。
##### [[Put]]
1. 实行是否是访问描述符?是并且存在调用setter
2. writalbe是否是false?静默失败或者抛出TypeError(严格模式)
##### Getter和Setter
可使用getter和setter部分改写默认操作,当设定getter、setter时,JavaScript会忽略他的value和writable特性。
```js
var myObject = {
get a(){
return this._a_;
},
set a(val){
this._a_ = val * 2
}
};
Object.defineProperty(
myObject, // 目标对象
"b", // 属性名
{ // 描述符
// 给b设置一个getter
get: function(){ return this.a * 2 },
// 确保b会出现在对象的属性列表中
enumerable: true
}
);
myObject.a = 2;
myObject.a; // 4
myObject.b; // 8
```
##### 存在性
```js
var myObject = {
a:2
}
("a" in myObject); //true
("b" in myObject); //false
myObject.hasOwnProperty( "a" ); //true
myObject.hasOwnProperty( "b" ); //false
```
in 操作会检查属性是否在对象及其 [[Prototype]] 原型链中,hasOwnProperty(..) 只会检查属性是否在myObject对象中。但有的对象可能没有连接到Object.prototype(通过Object.creat(null)来创建)。此时可以通过更强硬的方法判断:
```js
Object.prototype.hasOwnProperty.call(myObject,"a")
```
**注意**:in操作检查的是某个属性名是否存在,4 in [2, 4, 6]结果是False,因为访问的是属性名的下标。
###### 枚举
```js
var myObject = { a:2 };
Object.defineProperty(
myObject,
"b",
// 让b不可枚举
{ enumerable: false, value: 3 }
)
//通过in和hasOwnProperty均可查到
myObject.b; // 3
("b" in myObject); //true
myObject.hasOwnProperty( "b" ); // true
//通过for..in循环不能得到
for (var k in myObject) {
console.log( k, myObject[k] ); // a 2
}
//判断是否存在于对象中(而不是原型链上)并满足enumerable:true
myObject.propertyIsEnumerable( "b" ); //false
//返回数组包含所有可枚举属性(而不是原型链上)
Object.keys( myObject ); // ["a"]
//返回一个数组包含所有属性,无论是否可以枚举
Object.getOwnPropertyNames( myObject ); // ["a", "b"]
```
#### 遍历
标准for循环便利的是下标来指向值
forEach(..)会遍历数组中的所有值并忽略回调函数的返回值
every(..)会一直运行到回调函数返回false
some(..)会一直运行到回调函数返回true
for..in遍历对象的可枚举属性,需要手动获取属性值
for..of (ES6) 可直接遍历值
```js
// for..of会访问对象请求一个迭代器对象,然后通过调用迭代器对象的next()方法来遍历所有返回值。
var myArray = [ 1, 2, 3 ];
for (var v of myArray) {
console.log( v );
}
//数组有内置迭代器@@iterator,可以通过Symbol.iterator来手动遍历数组
var it = myArray[Symbol.iterator]();
it.next(); // { value:1, done:false }
it.next(); // { value:2, done:false }
it.next(); // { value:3, done:false }
it.next(); // { done:true }
```
和数组不同,普通对象没有内置的@@iterator,可以给任何想遍历的对象定义@@iterator
```js
var myObject = {
a: 2,
b: 3
};
Object.defineProperty( myObject, Symbol.iterator, {
enumerable: false,
writable: false,
configurable: true,
value: function() {
var o = this;
var idx = 0;
var ks = Object.keys( o );
return {
next: function() {
return {
value: o[ks[idx++]],
done: (idx > ks.length)
};
}
};
}
} );
// 手动遍历 myObject
var it = myObject[Symbol.iterator]();
it.next(); // { value:2, done:false }
it.next(); // { value:3, done:false }
it.next(); // { value:undefined, done:true }
// 用 for..of 遍历 myObject
for (var v of myObject) {
console.log( v ); // 2 3
}
```
for..of循环每次调用myObject迭代器对象的next()方法是,内部的指针都会向前移动并返回对象属性列表的下一个值。只要next()调用会返回value和done:true ,ES6中的for..of就可以遍历它。
例如可以定义一个无限迭代器等功能
```js
var randoms = {
[Symbol.iterator]: function() {
return {
next: function() {
return { value: Math.random() };
}
};
}
};
var randoms_pool = [];
for (var n of randoms) {
randoms_pool.push( n );
// 防止无限运行!
if (randoms_pool.length === 100) break;
}
```
#### 混合对象“类”
面向类的设计模式:实例化(instantiation)、继承(inheritance)和多态(polymorphism)
##### 混入
继承或者实例化时,JavaScript的对象机制不会自动执行复制行为,JavaScript通过**混入**来模拟类的复制行为。
###### 显式混入
1. 显式多态
在许多库和框架中被称作extend(..),这里称作mixin(..)。
```js
// mixin(..) 例子 :
function mixin( sourceObj, targetObj ) {
for (var key in sourceObj) {
// 只会在不存在的情况下复制,子类对父类属性的重写
if (!(key in targetObj)) {
targetObj[key] = sourceObj[key];
}
}
return targetObj;
}
var Vehicle = {
engines: 1,
ignition: function() {
console.log( "Turning on my engine." );
},
drive: function() {
this.ignition();
console.log( "Steering and moving forward!" );
}
};
var Car = mixin( Vehicle, {
wheels: 4,
drive: function() {
// 显式多态:JS在ES6之前没有相对多态的机制,必须绝对引用。使用.call(this)来确保drive()在Car对象的上下文中执行。
Vehicle.drive.call( this );
console.log(
"Rolling on all " + this.wheels + " wheels!"
);
}
} );
```
2. 混合复制
可以先复制然后再对Car进行特殊化,从而跳过存在性检查,但是效率更低。
```js
// 另一种混入函数,可能有重写风险
function mixin( sourceObj, targetObj ) {
for (var key in sourceObj) {
targetObj[key] = sourceObj[key];
}
return targetObj;
}
var Vehicle = {
// ... 无需再绑定this了
};
```
3. 寄生继承
复制Vehicle对象的定义,然后混入子类的定义(如果需要保存到父类的特殊引用),然后用这个符合对象构建实例。
```js
//“寄生类”Car
function Car() {
var car = new Vehicle();
car.wheels = 4;
//保存到Vehicle::drive()的特殊引用
var vehDrive = car.drive;
//重写Vehicle::drive()
car.drive = function() {
vehDrive.call( this );
console.log(
"Rolling on all" + this.wheels + " wheels!"
);
return car;
}
}
var myCar = new Car();
myCar.drive();
//Turning on my engine.
//Steering and moving forward!
//Rolling on all 4 wheels!
```
###### 隐式混入
这里通过this绑定隐式的把Something混入Another,最终Something.cool()重的赋值操作都会应用在Another对象上
```js
var Something = {
cool:function(){
this.greeting = 'hello world'
this.count = this.count?this.count+1:1
}
}
Something.cool()
Something.greeting //'hello world'
Something.count // 1
var Another = {
cool:function(){
//隐式把Someting混入Another
Something.cool.call(this)
}
}
Another.cool()
Another.greeting //'hello world'
//this绑定在了Another中
Another.count //1
```
### 原型
#### [[Prototype]]
JavaScript对象有特殊的内置属性,其实就是对于其他对象的引用。
```js
var anotherObject = {
a:2
};
//创建一个关联到anotherObject的对象,将myObject对象的[[Prototype]]关联到了anotherObject
var myObject = Object.create( anotherObject );
myObject.a; // 2
```
##### Object.prototype
所有普通的[[Prototype]]链最终都会指向内置的Object.prototype。而Object.prototype对象包含了许多通用功能,如.toString()、.valueOf()、.hasOwnProperty(..)、.isPrototypeOf(..)等。
##### 属性设置和屏蔽
```js
myObject.foo = "bar"
```
1. 针对这一赋值语句,若myObject中包含foo的普通数据访问属性,则只会修改已有属性值。
2. 若foo存在myObject中,也出现在[[Prototype]]链上层,会发生屏蔽。myObject中包含的foo属性会屏蔽原型链上层的所有foo属性。
3. 若foo不存在于myObject中,就会遍历[[Prototype]]
1. 若链上存在foo的普通数据访问属性,并且没有被标记为只读(writable:true),就会在myObject中添加一个foo的新属性,它是屏蔽属性。
2. 若存在且被标记为只读(writable:false),不会发生屏蔽,该条赋值语句被忽略,严格模式下抛出错误。
3. 若链上存在foo并且是一个setter,就会调用setter,foo不会添加到myObject,也不会重新定义foo这个setter。
若想在3.2和3.3中也屏蔽foo,不能使用 = 操作来赋值,而是使用Object.defineProperty(..)
**注意,有些情况下会产生隐式屏蔽**
```js
var anotherObject = { a:2 };
var myObject = Object.create( anotherObject ); anotherObject.a; // 2
myObject.a; // 2
anotherObject.hasOwnProperty( "a" ); // true
myObject.hasOwnProperty( "a" ); // false
// ++ 相当于myObject.a = myObject.a + 1,因此通过原型链查找到a并获取属性值anotherObject.a,然后加1,接着用[[Put]]将3赋值给myObject新建的屏蔽属性a。
//需要使用anotherObject.a++来增加其值
myObject.a++; // 隐式屏蔽!
anotherObject.a; // 2
myObject.a; // 3
myObject.hasOwnProperty( "a" ); // true
```
#### “类”和“构造函数”
JavaScript中没有类似面向类语言中的复制机制。不能创建一个类的多个实例,只能创建多个对象,它们的[[Prototype]]关联同一个对象。JavaScript不是继承,更准确的说应该是通过**委托**访问另一个对象的属性和函数。
```js
function Foo() {
// ...
}
var a = new Foo();
Object.getPrototypeOf( a ) === Foo.prototype; // true
Foo.prototype.constructor === Foo; // true
//Foo.prototype中有一个共有并且不可枚举的属性.constructor,应用的是对象关联的函数Foo
a.constructor === Foo; // true
```
Foo并不是构造函数,当在普通的函数调用前加上new关键字后,就会把这个函数调用编程一个“构造函数调用”。new会劫持所有普通函数并用构造对象的形式来调用它。
```js
function NothingSpecial() {
console.log( "Don't mind me!" );
}
var a = new NothingSpecial();
// "Don't mind me!"
a; // {}
```
使用new调用时,会构造一个对象并赋值给a,可以说带new的函数调用是JavaScript中的“构造函数调用”
##### 技术
```js
function Foo() { /* .. */ }
Foo.prototype = { /* .. */ }; // 创建一个新原型对象
var a1 = new Foo();
a1.constructor === Foo; // false!
a1.constructor === Object; // true!
```
a1没有.constructor属性,会委托[[Prototype]]链上的Foo.prototype,而Foo也没有,因此继续委托给委托连顶端的Object.prototype。这个对象有.constructor属性,指向内置的Object(..)函数。
若想要修复.constructor,需要手动添加一个不可枚举属性:
```js
function Foo() { /* .. */ }
Foo.prototype = { /* .. */ }; // 创建一个新原型对象
// 需要在 Foo.prototype 上“修复”丢失的 .constructor 属性
// 新对象属性起到 Foo.prototype 的作用
Object.defineProperty( Foo.prototype, "constructor" , {
enumerable: false,
writable: true,
configurable: true,
value: Foo // 让 .constructor 指向 Foo
} );
```
#### (原型)继承
```js
// ES6前需要抛弃默认的Bar.prototype 调用Object.create(..)会凭空创建一个“新”对象并把新对象内部[[Prototype]]关联到指定的对象
Bar.prototype = Object.create( Foo.prototype );
// ES6开始可以直接修改现有Bar.prototype
Object.setPrototypeOf( Bar.prototype, Foo.prototype );
// 此方法不会创建一个新对象,而是让Bar.prototype直接引用Foo.prototype对象。
Bar.prototype = Foo.prototype
// 使用Foo(..)的“构造函数调用”,存在副作用(写日志、修改状态、注册到其他对象等)会影响Bar()的“后代”
Bar.prototype = new Foo()
```
##### 检查“类”关系
检查对象a的委托对象,在传统面向类环境中通常称为内省(或者反射)
```js
// 查询a的整条[[Prototype]]链中是否有指向Foo.prototype的对象。智能处理对象(a)和函数(带.prototype引用的Foo)之间的关系,无法判断两个对象是否通过[[Prototype]]链关联
a instanceof Foo;
// 是否出现过Foo.prototype
Foo.prototype.isPrototypeOf( a ); // true
b.isProtytypeOf(c) //可判断两个对象之间的关系
//获取一个对象的[[Prototype]]链
Object.getPrototypeOf( a );
// .__proto__存在于Object.prototype中,像一个getter/setter低啊用Object.getPrototypeOf和Object.setPrototypeOf
a.__proto__ === Foo.prototype; //ES6
```
#### 对象关联
##### 创建关联
Object.create(..)会创建一个新对象并关联到指定对象,充分发挥[[Prototype]]的委托机制,而**避免new构造函数调用生成.prototype和.constructor引用**
**Object.create(null)**会创建一个拥有空链接的对象,无法进行委托。由于没有原型链,所以instanceof操作符无法进行判断。这种特殊的空[[Prototype]]对象通常被称作“字典”,适合用来存储数据。
在ES5之前使用,可以采用polyfill代码实现:
```js
// 构造一个一次性函数F,并改写它的.prototype 属性使其指向要关联的对象,在使用new F()来构造一个新的对象进行关联
if(!Object.create) {
Object.create = function(o){
function F(){}
F.prototype = o;
return new F();
};
}
```
##### 关联关系是备用
```js
var anotherObject = {
cool: function() {
console.log( "cool!" )
}
};
// 使用myObject无法处理时使用备用anotherObject,会导致难以维护,myObject中不存在cool()
var myObject = Object.create( anotherObject );
myObject.cool(); // "cool!"
// 委托设计模式,通过[[Prototype]]委托到anotherObject.cool(),可以使API接口设计更加清晰
myObject.doCool = function() {
this.cool(); // 内部委托!
};
myObject.doCool(); // "cool!"
```
### 行为委托
#### 面向委托的设计
##### 委托理论
在类理论中,通常定义一个通用父(基)类,并集成其来添加一些特殊的行为来处理对应的任务。可以重写和多态,甚至通过super调用原始版本。
在JavaScript中,采用委托行为来考虑此问题。相比于面向对象,可以称之为“对象关联”(OLOO, objects linked to other objects):
```js
Task = {
setID: function(ID) { this.id = ID; },
outputID: function() { console.log( this.id ); }
}
// 让XYZ委托Task
XYZ = Object.create( Task );
XYZ.prepareTask = function(ID,Label) {
this.setID( ID );
this.label = Label;
};
XYZ.outputTaskDetails = function() {
this.outputID();
console.log( this.label );
};
```
与面向类方式的不同:
1. 状态最好直接存储在委托者(XYZ)上,而不是委托目标(Task)上。
2. 类设计模式中,采用重写方式尽量少使用容易被重写的通用方法名。
3. 当委托者寻找不到的方法,会通过[[Prototype]]委托关联查找。
##### 比较思维模型
###### 典型的面向对象风格
```js
function Foo(who) {
this.me = who;
}
Foo.prototype.identify = function() {
return "I am " + this.me;
};
function Bar(who) {
Foo.call( this, who );
}
Bar.prototype = Object.create( Foo.prototype );
Bar.prototype.speak = function() {
alert( "Hello, " + this.identify() + ".");
};
var b1 = new Bar( "b1" );
var b2 = new Bar( "b2" );
b1.speak();
b2.speak();
```
###### 采用对象关联风格
```js
Foo = {
init: function(who) {
this.me = who;
},
identify: function() {
return "I am " + this.me;
}
};
Bar = Object.create( Foo );
Bar.speak = function() {
alert( "Hello, " + this.identify() + "." );
};
var b1 = Object.create( Bar );
b1.init( "b1" );
var b2 = Object.create( Bar );
b1.init( "b2" );
b1.speak();
b2.speak();
```
对象关联风格更加简介,而无需模仿类的行为(构造函数、原型以及new)。
类风格代码的思维模型强调实体以及实体间的关系:
<img src="README.assets/image-20210218143429269.png" alt="image-20210218143429269" style="zoom:50%;" />
简化上图,只展示必要的对象和关系:
<img src="README.assets/image-20210218143705939.png" alt="image-20210218143705939" style="zoom:50%;" />
虚线表示的是Bar.prototype继承Foo.prototype 之后丢失的.constructor属性引用。
对象关联风格代码的思维模型:
<img src="README.assets/image-20210218144023704.png" alt="image-20210218144023704" style="zoom:50%;" />
#### ES6中的class
class是现有[[Prototype]]委托机制的一种语法糖,JavaScript中并不会像传统面向类的语言一样在生命时静态复制所有行为。如果修改了父“类”中的方法,那所有子“类”都会受到影响,只是使用基于[[Prototype]]的实时委托。
```js
class C {
constructor() {
this.num = Math.random();
}
rand() {
console.log( "Random: " + this.num );
}
}
var c1 = new C();
c1.rand();
```
## 中册
### 类型和语法
#### 类型
##### 内置类型
JavaScript有七种内置类型 null / undefined / boolean / number / string / object / symbol
```js
// JS对于null的判断存在问题
typeof null === "object"; // true
//针对于null类型的检测方式,可以采用复合条件来检测
var a = null;
(!a && typeof a === "object"); // true
// fucntion是object一个子类型,内部具有属性[[call]],该属性使其可以被调用
typeof function a(){ /* .. */ } === "function"; // true
```
##### 值和类型
JavaScript中变量没有类型,值才有类型。变量可以随时持有任何类型的值。
###### undefined和undeclared
在作用域中声明但没有赋值的变量是undefined;未在作用域中声明过的变量是undeclared
```js
var a;
a; // undefined
b; // ReferenceError: b is not defined
typeof a; // "undefined"
//typeof有一个特殊的安全防范机制,因此typeof b并未报错。
typeof b; // "undefined"
```
###### typeof Undeclared
针对于全局变量,可以通过typeof检查避免出现ReferenceError
```js
// 会抛出错误
if(DEBUG) {
console.log( "Debugging is starting" );
}
// 这样是安全的
if(typeof DEBUG !== "undefined") {
console.log( "Debugging is starting" );
}
// 也可以通过浏览器全局对象window,但是在其他环境中可能不能使用
if(window.DEBUG) {
// ..
}
```
#### 值
##### 字符串
字符串和字符数组都是类数组,都有length属性以及indexOf(..)(ES5之后开始支持)和concat(..)方法。
字符串可以采用数组的访问方式a[1],但是在老版本IE中不允许,可以采用a.charAt(1)。
字符串没有一些数组函数,可以借用数组的非变更方法来处理字符串:
```js
a = "foo";
a.join; // undefined
a.map; // undefined
var c = Array.prototype.join.call( a, "-" );
var d = Array.prototype.map.call( a, function(v){
return v.toUpperCase() + ".";
} ).join( "" );
c; // "f-o-o"
d; // "F.O.O"
```
字符串没有可变更成员函数reverse():
```js
a.reverse; //undefined
var c = a
// 将a的值转换为字符数组
.split( "" )
// 将数组中的字符进行倒转
.reverse()
// 将数组中的字符拼接回字符串
.join( "" );
c; // "oof"
```
##### 数字
JavaScript中只有number,没有真正意义上的整数,采用双精度格式(64位二进制)。
```js
var a = 5E10
a; // 50000000000
a.toExponential(); // "5e+10"
var a = 42.59;
a.toFixed( 1 ); // "42.6" 返回的是字符串形式
a.toPrecision( 2 ); // "43" 指定有效数位的显示位数
a.toPrecision( 5 ); // "42.590"
//也适用于数字常量 注意 . 会被优先识别为数字常量的一部分
42.toFixed( 3 ); // SyntaxError
0.42.toFixed( 3 ); // "0.420"
42..toFixed( 3 ); // "42.000"
```
数字常量还支持二进制、八进制和十六进制
```js
0xf3; // 243的十六进制
//ES6 non-strict mode
0363 // 243的八进制
//ES6 strict mode 不再支持0363八进制格式,支持以下新格式
0o363 // 243的八进制
0b11110011 // 243的二进制
```
###### 数值精度
二进制浮点数存在精度不准确问题:
```js
0.1 + 0.2 === 0.3; // false
// ES6中,将机器精度2^-52 (2.220446049250313e-16)定义在了Number.EPSILON中
// ES6之前,可采用polyfill
if(!Number.EPSILON) {
Number.EPSILON = Math.pow(2,-52);
}
//用来比较数字是否相等
function numbersCloseEnoughToEqual(n1,n2) {
return Math.abs( n1 - n2 ) < Number.EPSILON;
}
// 最大浮点数1.798e+308
Number.MAX_VALUE
// 最小浮点数5e-324
Number.MIN_VALUE
// 最大整数 2^53 - 1 9007199254740991
Number.MAX_SAFE_INTEGER
// 最小整数 -9007199254740991
Number.MIN_SAFE_INTEGER
```
###### 整数检测
```js
// 检测一个值是否是整数
// ES6
Number.isInteger( 42 ); //true
// ES6之前
if(!Number.isInteger) {
Number.isInteger = function(num) {
return typeof num == "number" && num % 1 == 0;
}
}
// 检测一个值是否是安全的整数
// ES6
Number.isSafeInteger( Number.MAX_SAFE_INTEGER ); //true
// ES6之前
if(!Number.isSafeInteger) {
Number.isSafeInteger = function(num) {
return Number.isInteger( num ) &&
Math.abs( num ) <= Number.MAX_SAFE_INTEGER
}
}
```
###### 32位有符号整数
虽然整数最大能够达到53位,数位操作只适用于32位数字,安全范围就要小很多,变成从 Math.pow(-2,31)(-2147483648, 约-21 亿)到 Math.pow(2,31) - 1(2147483647,约 21 亿)。
```js
//可以将变量a中的数字转换为32位有符号整数,因为数位运算符|只适用于32位整数
a | 0
```
##### 特殊数值
###### 不是值的值
undefined和null只有一个值,即它本身。他们的名称即是类型也是值。
null指空值(empty value)
undefined指没有值(missing value)
可以采用void运算符来得到undefined
```js
// void ___ 使表达式不返回值
void a // 没有返回值,因此返回结果是undefined
```
###### 特殊的数字
1. 不是数字的数字
当数学运算的操作数不是数字类型,无法返回一个有效数字,这种情况下返回值为NaN。
NaN是唯一一个非自反的值(自反,reflexive,即 x === x 不成立)
```js
// 可采用内建的全局工具函数isNaN(..)来判断是否是NaN
var a = 2 / "foo";
isNaN( a ); //true
```
isNaN(..)过于死板,检查参数是不是NaN,也不是数字
```js
// ES6开始可以使用工具函数Number.isNaN(..)
// ES6前polyfill
if(!Number.isNaN) {
Number.isNaN = function(n) {
return (
typeof n === "number" &&
window.isNaN( n )
);
};
}
// 可以采用NaN不等于自身这个特点来简单判断
if(!Number.isNaN) {
Number.isNaN = function(n) {
return n !== n;
};
}
```
###### 无穷数
JS使用有限数字表示法,在JS中运行时错误,例如“除以0”,结果为Infinity
```js
// Number.POSITIVE_INfiNITY
var a = 1 / 0; // Infinity
// Number.NEGATIVE_INfiNITY
var b = -1 / 0; // -Infinity
// 对超出处理范围,IEEE 754规范采用就近取整模式
var a = Number.MAX_VALUE // 1.7976931348623157e+308
a + a; // Infinity
a + Math.pow( 2, 970); // Infinity 更接近Infinity被先上去整
a + Math.pow( 2, 969); // 1.7976931348623157e+308 向下取整
```
###### 零值
JavaScript包含常规的 0 和一个 -0。
```js
// 加法和减法怒算不会得到负零。
var a = 0 / -3; // -0
// 对 -0 进行字符化会返回 0
a.toString(); // "0"
// 反向操作得到结果是准确的
Number( "-0" ); // -0
+"-0"; // -0
//区分 -0 和 0
function isNegZero(n) {
n = Number( n )
return (n === 0) && (1/n === -Infinity);
}
isNegZero(-0); //true
isNegZeron(0); //false
```
负零可以保留符号位用于代表其他信息(例如移动的方向)。
###### 特殊等式
ES6中加入了Object.is(..)判断两个值是否绝对相等
```js
var a = 2 / "foo"
bar b = -3 * 0;
Object.is( a, NaN ); // true
Object.is( b, -0 ); // true
Object.is( b, 0 ); // false
// ES6前polyfill
if(!Object.is) {
Object.is = function(v1, v2) {
// 判断是否是 -0
if (v1 === 0 && v2 ===0) {
return 1 / v1 === 1 / v2;
}
// 判断是否是NaN
if (v1 !== v1) {
return v2 !== v2;
}
// 其他情况
return v1 === v2;
};
}
```
##### 值和引用
简单值(即标量基本类型值,scalar primitive)总是通过值复制的方式来赋值 / 传递,包括null、undefined、字符串、数字、布尔和 ES6 中的 symbol。
复合值(compound value)——对象(包括数组和封装对象)和函数,则总是通过引用复制的方式来赋值 / 传递。
```js
var a = 2;
var b = a;
b++;
a; // 2
b; // 3
var c = [1,2,3];
var d = c;
d.push( 4 ); // 改变的是值本身,而非指向变化
c; // [1,2,3,4]
d; // [1,2,3,4]
// 由于引用指向的是值本身而非变量,所以一个引用无法更改另一个引用的指向
var a = [1,2,3];
var b = a;
a; // [1,2,3]
b; // [1,2,3]
b = [4,5,6];
a; // [1,2,3]
b; // [4,5,6]
//如果通过值复制的方式来传递复合值,就需要创建一个副本
foo( a.slice() );
// slice(..)不带参数会返回当前数组的一个浅复本(shallow copy),由于传递给函数的是指向该复本的引用,所以foo(..)操作不会影响a指向的数组
// 相反的,如果将标量基本类型传到函数内进行更改,就需要封装到一个复合值中
function foo(wrapper) {
wrapper.a = 42;
}
var obj = {
a: 2
};
foo(obj);
obj.a; // 42
//岁软传递的是指向数字对象的引用副本,但是由于x = x + 1 时拆箱,x变成了数字对象,而b仍指向原来的值为2的数字对象
function foo(x) {
x = x + 1;
x; // 3
}
var a = 2;
var b = new Number( a ); // Object(a)也一样
foo( b );
console.log( b ); // 是2,不是3
```
#### 原生函数
String() / Number() / Boolean() / Array() / Object()
Function() / RegExp() / Date() / Error() / Symbol()
```js
var a = new String( "abc" );
typeof a; // 是"object",不是"String" 返回的是对象类型的子类型
a instanceof String // true
Object.prototype.toString.call( a ) // "[object String]"
```
##### 内部属性[[Class]]
所有typeof返回值为"object"的对象都包含一个内部属性[[Class]],无法直接访问,一般通过Object.prototype.toString(..)查看。
##### 封装对象
基本类型没有 .length 和 .toString() 这样的属性和方法,需要通过封装对象才能访问,JavaScript会自动对基本类型值包装。
要想自行封装基本类型值,可以使用Object(..)函数,但不推荐使用
```js
var a = "abc";
a.length; // 3
a.toUpperCase(); // "ABC"
var b = new String(a);
var c = Object(a);
typeof b; // "object"
typeof c; // "object"
b instanceof String; // true
c instanceof String; // true
Object.prototype.toString.call(b); // "[object String]"
Object.prototype.toString.call(c); // "[object String]"
```
拆封对象可以使用valueOf()函数
```js
var b = new Number(42);
b.valueOf(); // 42
```
##### 原生函数作为构造函数
对于数组(array)、对象(object)、函数(function)和正则表达式,常量和使用构造函数的效果是一样的,尽量避免使用构造函数。
###### Array(..)
数组没有预设长度,创造出的是空数组。在Chrome中如下表示
```js
var a = new Array( 3 );
var b = [ undefined, undefined, undefined ];
var c = [];
c.length = 3;
a; // [empty × 3]
b; // [undefined,undefined,undefined]
c; // [empty × 3]
//通过下述方式创建undefiend单元的数组(而非空单元)
var a = Array.apply( null, { length: 3} );
a; // [ undefined, undefined, undefined ]
```
###### Object(..)、Function(..) 和 RegExp(..)
尽量不要使用上述来创建对象。RegExp(..)可以用来定义动态正则表达式
```js
var name = "Kyle";
var namePattern = new RegExp( "\\b(?:" + name + ")+\\b", "ig" );
var matches = someText.match( namePattern );
```
###### Date(..) 和 Error(..)
Date()用来获取当前Unix时间戳(1970年1月1日开始计算,以秒为单位)。创建日期使用new Date(),如果调用Date()时不带new,会得到当前日期的字符串值,浏览器使用 "Fri Jul 18 2014 00:31:02 GMT-0500(CDT)"。
ES5中引入了静态函数Date.now()
```js
// polyfill ES5之前
if(!Date.now) {
Date.now = function() {
return (new Date()).getTime();
};
}
```
###### Symbol(..)
符号是具有唯一性的特殊值,用它来命名对象属性不容易导致重名。ES6中有一些预定义符号,以Symbol的静态属性形式出现,如Symbol.create、Symbol.iterator等。使用Symbol(..)原生构造函数来自定义符号,不能带new关键字
|
C++
|
UTF-8
| 787
| 3.09375
| 3
|
[] |
no_license
|
#include "TextureManager.h"
TextureManager* TextureManager::m_Instance = new TextureManager();
TextureManager::TextureManager(){}
TextureManager::~TextureManager(){}
TextureManager* TextureManager::getInstance(){
return m_Instance;
}
// Returns a textue, if the texture dont exist then try to load the texture
sf::Texture* TextureManager::getTexture(const std::string name){
sf::Texture* tex = m_Textures[name];
if (tex == nullptr){
if (loadTexture(name))
return m_Textures[name];
else
return nullptr;
}
return tex;
}
// Load a texture with name
bool TextureManager::loadTexture(const std::string name){
sf::Texture* tex = new sf::Texture;
tex->loadFromFile("Assets/" + name + ".png");
if (tex == nullptr)
return false;
m_Textures[name] = tex;
return true;
}
|
PHP
|
UTF-8
| 1,479
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
<?php
/**
* TransportStatus.
*
* PHP version 5
*
* @author Stefan Neuhaus / ClouSale
*/
/**
* Selling Partner API for Fulfillment Inbound.
*
* The Selling Partner API for Fulfillment Inbound lets you create applications that create and update inbound shipments of inventory to Amazon's fulfillment network.
*
* OpenAPI spec version: v0
*/
namespace ClouSale\AmazonSellingPartnerAPI\Models\FulfillmentInbound;
/**
* TransportStatus Class Doc Comment.
*
* @description Indicates the status of the Amazon-partnered carrier shipment.
*
* @author Stefan Neuhaus / ClouSale
*/
class TransportStatus
{
/**
* Possible values of this enum.
*/
const WORKING = 'WORKING';
const ESTIMATING = 'ESTIMATING';
const ESTIMATED = 'ESTIMATED';
const ERROR_ON_ESTIMATING = 'ERROR_ON_ESTIMATING';
const CONFIRMING = 'CONFIRMING';
const CONFIRMED = 'CONFIRMED';
const ERROR_ON_CONFIRMING = 'ERROR_ON_CONFIRMING';
const VOIDING = 'VOIDING';
const VOIDED = 'VOIDED';
const ERROR_IN_VOIDING = 'ERROR_IN_VOIDING';
const ERROR = 'ERROR';
/**
* Gets allowable values of the enum.
*
* @return string[]
*/
public static function getAllowableEnumValues()
{
return [
self::WORKING,
self::ESTIMATING,
self::ESTIMATED,
self::ERROR_ON_ESTIMATING,
self::CONFIRMING,
self::CONFIRMED,
self::ERROR_ON_CONFIRMING,
self::VOIDING,
self::VOIDED,
self::ERROR_IN_VOIDING,
self::ERROR, ];
}
}
|
Python
|
UTF-8
| 856
| 3.0625
| 3
|
[] |
no_license
|
import unittest
from X18_4Sum import Solution
class TestSum(unittest.TestCase):
def test1(self):
sol = Solution()
self.assertListEqual(sorted(sol.fourSum([1, 0, -1, 0, -2, 2], 0)),
sorted([
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]))
self.assertListEqual(sorted(sol.fourSum([-3,-2,-1,0,0,1,2,3], 0)),
sorted([[-3,-2,2,3],[-3,-1,1,3],[-3,0,0,3],[-3,0,1,2],[-2,-1,0,3],[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]))
self.assertListEqual(sorted(sol.fourSum([-5,5,4,-3,0,0,4,-2], 4)),
sorted([[-5,0,4,5],[-3,-2,4,5]]))
if __name__ == "__main__":
unittest.main()
|
Shell
|
UTF-8
| 211
| 3.4375
| 3
|
[] |
no_license
|
#!/usr/bin/bash
NUM=5
target=$(($RANDOM % $NUM))
read -p "Guess the number between 1 to 5 =" guess
if [[ ${guess} = ${target} ]];then
echo "Correc.t you won!!"
else
echo "try again"
fi
|
C
|
UTF-8
| 290
| 3.703125
| 4
|
[] |
no_license
|
#include <stdio.h>
#define LEN 5
int main(int argc, char **argv)
{
int my_array[LEN] = {1,2,3,4,5};
int size = sizeof(my_array);
int len = sizeof(my_array)/sizeof(my_array[0]);
printf("size of array in bytes: %d, number of elements: %d\n", size, len);
return 0;
}
|
Java
|
UTF-8
| 487
| 2.984375
| 3
|
[] |
no_license
|
package aqa.core.lesson11.RomanovYevgen;
public class Test {
public static void main(String[] args) {
Company GL = new Company("GL", "Lviv, UA", "+3805023255__");
GL.addNewEmployee("A", "+3805023255__", 700);
GL.addNewEmployee("B", "+3805023255__", 450);
GL.addNewEmployee("C", "+3805023255__", 300);
System.out.println(GL.getNameOfEmployeeWithHighestSallary());
GL.theAmountOfSalaryCosts();
GL.theAvarageSalary();
}
}
|
Go
|
UTF-8
| 1,507
| 3.140625
| 3
|
[] |
no_license
|
package util
import (
"net/url"
"testing"
"github.com/stretchr/testify/assert"
)
func TestSetQuery(t *testing.T) {
url1, err := url.Parse("http://example.com/foo?that=thing")
assert.NoError(t, err)
assert.Equal(t, "thing", url1.Query().Get("that"))
SetQuery(url1, "that", "random thing")
assert.Equal(t, "random thing", url1.Query().Get("that"))
assert.Equal(t, "http://example.com/foo?that=random+thing", url1.String())
}
func TestGetSubdomain(t *testing.T) {
// Get an empty string if no sub-domain
assert.Equal(t, "", GetSubdomains("example.com"))
assert.Equal(t, "", GetSubdomains("example.co.uk"))
assert.Equal(t, "", GetSubdomains("localhost"))
// Get a sub-domain if present
assert.Equal(t, "foo", GetSubdomains("foo.bar.com"))
assert.Equal(t, "foo", GetSubdomains("foo.bar.co.uk"))
assert.Equal(t, "foo", GetSubdomains("foo.localhost"))
// Support sub-sub domains
assert.Equal(t, "foo.bar", GetSubdomains("foo.bar.example.com"))
assert.Equal(t, "foo.bar", GetSubdomains("foo.bar.example.co.uk"))
assert.Equal(t, "foo.bar", GetSubdomains("foo.bar.localhost"))
// Don't break if a port is included
assert.Equal(t, "", GetSubdomains("example.com:3000"))
assert.Equal(t, "", GetSubdomains("localhost:321"))
assert.Equal(t, "abc", GetSubdomains("abc.example.com:3000"))
assert.Equal(t, "abc", GetSubdomains("abc.localhost:321"))
assert.Equal(t, "abc.def", GetSubdomains("abc.def.example.com:3000"))
assert.Equal(t, "abc.def", GetSubdomains("abc.def.localhost:321"))
}
|
Markdown
|
UTF-8
| 380
| 2.828125
| 3
|
[] |
no_license
|
# Aggregate
When you use GROUP_BY, you can only select aggregates or columsn in the GROUP_BY
#### Count
- `COUNT(*)` /`COUNT(1)`counts all rows
- `COUNT(column)` counts non-NULLs only
```sql
SELECT COUNT(*) FROM orders GROUP BY ds;
```
#### Max
Even works for strings where later in the alphabet is more
#### Min
Even works for strings where later in the alphabet is more
|
C++
|
UTF-8
| 403
| 2.71875
| 3
|
[] |
no_license
|
#include <iostream>
#include <iomanip>
using namespace std;
//https://e-tutor.itsa.org.tw/e-Tutor/mod/programming/view.php?id=2667
int main(int argc, char *argv[]) {
int x = 0;
int y = 0;
while(cin >> x >> y)
{
for(int i=1;i<=x;i++)
{
for(int j=1;j<=y;j++)
{
cout << i <<" x "<< j << " = " << i*j << endl;
//printf("%d x %d = %d\n",i,j,i*j);
}
}
}
}
/*
2 2
135790
97531
*/
|
C#
|
UTF-8
| 3,562
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
using System;
using System.Numerics;
using System.Runtime.CompilerServices;
using Box2D.NetStandard.Common;
using Math = Box2D.NetStandard.Common.Math;
namespace Box2D.NetStandard.Collision.Shapes
{
/// <summary>
/// /// The chain has one-sided collision, with the surface normal pointing to the right of the edge.
/// This provides a counter-clockwise winding like the polygon shape.
/// Connectivity information is used to create smooth collisions.
/// </summary>
/// <warning>The chain will not collide properly if there are self-intersections.</warning>
public class ChainShape : Shape
{
internal const byte contactMatch = 3;
internal int m_count;
internal Vector2 m_prevVertex, m_nextVertex;
internal Vector2[] m_vertices;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ChainShape() => m_radius = Settings.PolygonRadius;
public Vector2[] Vertices
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => m_vertices;
}
internal override byte ContactMatch => contactMatch;
/// <summary>
/// Create a loop. This automatically adjusts connectivity.
/// </summary>
/// <param name="vertices">An array of vertices. These are copied</param>
public void CreateLoop(in Vector2[] vertices)
{
int count = vertices.Length;
if (count < 3)
{
return;
}
m_count = count + 1;
m_vertices = new Vector2[m_count];
Array.Copy(vertices, m_vertices, count);
m_vertices[count] = m_vertices[0];
m_prevVertex = m_vertices[m_count - 2];
m_nextVertex = m_vertices[1];
}
/// <summary>
/// Create a chain with ghost vertices to connect multiple chains together.
/// </summary>
/// <param name="vertices">An array of vertices. These are copied</param>
public void CreateChain(in Vector2[] vertices, in Vector2 prevVertex, in Vector2 nextVertex)
{
int count = vertices.Length;
m_count = count;
m_vertices = new Vector2[m_count];
Array.Copy(vertices, m_vertices, m_count);
m_prevVertex = prevVertex;
m_nextVertex = nextVertex;
}
public override Shape Clone() => (ChainShape) MemberwiseClone();
public override int GetChildCount() => m_count - 1;
public void GetChildEdge(out EdgeShape edge, int index)
{
edge = new EdgeShape
{
m_radius = m_radius,
m_vertex0 = index > 0 ? m_vertices[index - 1] : m_prevVertex,
m_vertex1 = m_vertices[index + 0],
m_vertex2 = m_vertices[index + 1],
m_vertex3 = index < m_count - 2 ? m_vertices[index + 2] : m_nextVertex,
m_oneSided = true
};
}
public override bool TestPoint(in Transform xf, in Vector2 p) => false;
public override bool RayCast(
out RayCastOutput output,
in RayCastInput input,
in Transform transform,
int childIndex)
{
var edgeShape = new EdgeShape();
int i1 = childIndex;
int i2 = childIndex + 1;
if (i2 == m_count)
{
i2 = 0;
}
edgeShape.m_vertex1 = m_vertices[i1];
edgeShape.m_vertex2 = m_vertices[i2];
return edgeShape.RayCast(out output, input, transform, 0);
}
public override void ComputeAABB(out AABB aabb, in Transform xf, int childIndex)
{
int i1 = childIndex;
int i2 = childIndex + 1;
if (i2 == m_count)
{
i2 = 0;
}
Vector2 v1 = Math.Mul(xf, m_vertices[i1]);
Vector2 v2 = Math.Mul(xf, m_vertices[i2]);
aabb.lowerBound = Vector2.Min(v1, v2);
aabb.upperBound = Vector2.Max(v1, v2);
}
public override void ComputeMass(out MassData massData, float density)
{
massData = default;
}
}
}
|
JavaScript
|
UTF-8
| 7,245
| 2.8125
| 3
|
[] |
no_license
|
function ShellUI() {
console.log("in shell");
var self = this;
self.shellUserDropdown = null;
self.shellNavDropdown = null;
self.shellNavTab = null;
self.shellToggle = null;
// Breakpoint between small and large devices
self.breakpoint = 899;
// Throttle resize events to avoid firing a lot of resize handlers
self.resizeTimeout = null;
self.resizeThrottler = function() {
// Ignore resize events as long as a resizeHandler execution is in the queue
if (!self.resizeTimeout) {
self.resizeTimeout = setTimeout(function() {
self.resizeTimeout = null;
self.resizeHandler();
// Wait 250ms before firing the resize handler
}, 250);
}
};
self.resizeHandler = function() {
self.shellNavDropdown.adjustOffset();
};
// Are we on a small viewport?
self.matchesSmall = function() {
if (window.matchMedia) {
// The browser supports JS media queries
return window.matchMedia('(max-width: ' + self.breakpoint + 'px)').matches;
} else {
// Fallback solution
return ($(window).width() < self.breakpoint);
}
};
// Are we on a large viewport?
self.matchesLarge = function() {
if (window.matchMedia) {
// The browser supports JS media queries
return window.matchMedia('(min-width: ' + self.breakpoint + 'px)').matches;
} else {
// Fallback solution
return ($(window).width() >= self.breakpoint);
}
};
self.init = function() {
self.shellUserDropdown = new ShellUserDropdown(self);
self.shellNavDropdown = new ShellNavDropdown(self);
self.shellNavTab = new ShellNavTab(self);
self.shellToggle = new ShellToggle(self);
$(window).resize(self.resizeThrottler);
};
self.init();
}
// User menu
function ShellUserDropdown(shellUI) {
var self = this;
// Reference of the parent ShellUI instance
self.shellUI = shellUI;
self.open = function() {
$('.shell-header-user').addClass('active');
};
self.close = function() {
$('.shell-header-user').removeClass('active');
};
self.toggle = function(label) {
$(label).closest('.shell-header-user').toggleClass('active');
};
self.init = function() {
$('.shell-header-user-label a').on('click.shellUserDropdown', function() {
self.toggle(this);
return false;
});
// Close the user menu when clicking outside
$(document).on('click.shellUserDropdownOutside', function(event) {
if (! $(event.target).closest('.shell-header-user').length) {
self.close();
}
});
// Close the user menu when pressing Esc key
$(document).on('keyup.shellUserDropdownOutside', function(event) {
if (event.keyCode == 27) {
self.close();
}
});
};
self.init();
}
// Nav menus (L1)
function ShellNavDropdown(shellUI) {
console.log("in nav");
var self = this;
// Reference of the parent ShellUI instance
self.shellUI = shellUI;
self.open = function(dropdown) {
dropdown.addClass('active');
if (self.shellUI.matchesLarge()) {
// Set the first tab as active on desktop
self.shellUI.shellNavTab.displayFirst(dropdown);
// Adjust horizontal offset
self.offset(dropdown);
}
};
// Calculate dropdown horizontal offset on desktop to avoid overflow
self.offset = function(dropdown) {
var shellHeaderWrapper = dropdown.closest('.shell-header-wrapper'),
dropdownContent = dropdown.find('.shell-header-dropdown-content'),
offset = shellHeaderWrapper.offset().left + shellHeaderWrapper.outerWidth() -
(dropdown.offset().left + dropdownContent.outerWidth());
// Set left position if needed
dropdownContent.css('left', (offset < 0) ? offset : '');
};
self.adjustOffset = function() {
var dropdown = $('.shell-header-dropdown.active');
if (dropdown.length) {
self.offset(dropdown);
}
};
self.close = function(dropdown) {
dropdown.removeClass('active');
};
self.closeAll = function() {
$('.shell-header-dropdown').removeClass('active');
};
self.toggle = function(label) {
var dropdown = $(label).closest('.shell-header-dropdown'),
otherDropdowns = dropdown.siblings('.shell-header-dropdown');
if (dropdown.hasClass('active')) {
// Close the active dropdown if its label is clicked
self.close(dropdown);
} else {
// Close all the dropdowns minus the chosen dropdown
otherDropdowns.removeClass('active');
self.open(dropdown);
}
};
self.init = function() {
// Direct link without dropdown
$('.shell-header-dropdown-label a:not(.shell-header-direct-link)').click(function() {
self.toggle(this);
return false;
});
// Close dropdowns when clicking outside
$(document).on('click.shellNavDropdownOutside', function(event) {
if (! $(event.target).closest('.shell-header-nav').length) {
self.closeAll();
}
});
// Close dropdowns when pressing Esc key
$(document).on('keyup.shellNavDropdownOutside', function(event) {
if (event.keyCode == 27) {
self.closeAll();
}
});
};
self.init();
}
// Nav submenus (L2)
function ShellNavTab(shellUI) {
var self = this;
// Reference of the parent ShellUI instance
self.shellUI = shellUI;
self.display = function(label) {
var tab = $(label).closest('.shell-header-dropdown-tab'),
tabs = tab.siblings('.shell-header-dropdown-tab');
if (! tab.hasClass('active')) {
tabs.removeClass('active');
tab.addClass('active');
self.displayImg(tab);
}
};
// Lazy loading of images in a tab container
self.displayImg = function(tab) {
// Changing data-src attribute to src
tab.find('img[data-src]').attr('src', function() {
return $(this).attr('data-src');
}).removeAttr('data-src');
};
self.toggle = function(label) {
var tab = $(label).closest('.shell-header-dropdown-tab'),
tabs = tab.siblings('.shell-header-dropdown-tab');
if (tab.hasClass('active')) {
tab.removeClass('active');
} else {
tabs.removeClass('active');
tab.addClass('active');
}
};
// Display the first tab
self.displayFirst = function(dropdown) {
self.display(dropdown.find('.shell-header-dropdown-tab:first-child .shell-header-dropdown-tab-label a'));
};
self.init = function() {
$('.shell-header-dropdown-tab-label a').on('mouseenter.shellNavTab focus.shellNavTab', function() {
// On desktop tabs are activated when hovering
if (self.shellUI.matchesLarge()) {
self.display(this);
}
}).on('click.shellNavTab', function() {
// On mobile tabs are toggled when clicking
if (self.shellUI.matchesSmall()) {
self.toggle(this);
}
return false;
});
};
self.init();
}
// Toggle search, user menu, nav on mobile
function ShellToggle(shellUI) {
var self = this;
// Reference of the parent ShellUI instance
self.shellUI = shellUI;
self.init = function() {
$('.shell-header-toggle-search').on('click.shellToggle', function() {
var shellHeaderSearch = $('.shell-header-search');
shellHeaderSearch.toggleClass('expanded');
// Focus the search input field when expanded
if (shellHeaderSearch.hasClass('expanded')) {
shellHeaderSearch.find('input[type="search"]').focus();
}
});
$('.shell-header-toggle-menu').on('click.shellToggle', function() {
$('.shell-header-user, .shell-header-nav').toggleClass('expanded');
});
};
self.init();
}
// Initialize the shell on DOM loaded
$(function() {
window.shellUI = new ShellUI();
});
|
Java
|
UTF-8
| 6,148
| 2.03125
| 2
|
[] |
no_license
|
package mybaby.action;
import android.app.Activity;
import android.webkit.WebView;
import com.umeng.socialize.controller.UMSocialService;
import org.json.JSONArray;
import org.json.JSONException;
import org.xutils.common.util.LogUtil;
import java.io.Serializable;
import java.util.Map;
import mybaby.Constants;
import mybaby.models.community.ParentingPost;
import mybaby.ui.main.MainUtils;
import mybaby.util.MaterialDialogUtil;
/**
*
* @author bj
* mybaby_alert?title=xxx&desc=xxx&cancel=xxx&items=json串
*/
public class DialogTipInfoAction extends Action implements Serializable {
public static String DialogSheetAction="mybaby_alert";//操作选项列表
private String title_text="";
private String desc_text="";
private String cancel_text="";
private String itmes_json="";
public String getDesc_text() {
return desc_text;
}
public void setDesc_text(String desc_text) {
this.desc_text = desc_text;
}
public String getCancel_text() {
return cancel_text;
}
public void setCancel_text(String cancel_text) {
this.cancel_text = cancel_text;
}
public String getTitle_text() {
return title_text;
}
public void setTitle_text(String title_text) {
this.title_text = title_text;
}
public String getItmes_json() {
return itmes_json;
}
public void setItmes_json(String itmes_json) {
this.itmes_json = itmes_json;
}
public DialogTipInfoAction() {
}
public DialogTipInfoAction(String title_text, String desc_text, String cancel_text, String itmes_json) {
this.title_text = title_text;
this.desc_text = desc_text;
this.cancel_text = cancel_text;
this.itmes_json = itmes_json;
}
@Override
public Action setData(String url,Map<String, Object> map) {
// TODO Auto-generated method stub
if (url.contains(DialogSheetAction)) {
//Map<String, Object> map=Action.getHeader(getReal_url());
this.title_text=(String) map.get("title");
this.desc_text=(String) map.get("desc");
this.cancel_text=(String) map.get("cancel");
this.itmes_json=(String) map.get("items");
return new DialogTipInfoAction(title_text,desc_text,cancel_text,itmes_json).setActiontTitle(title_text);
}else {
return null;
}
}
@Override
public Boolean excute(final Activity activity, final UMSocialService webviewController,
final WebView webView, final ParentingPost parentingPost) {
// TODO Auto-generated method stub
//Gson gson=new Gson();可以用,但是没必要
try {
JSONArray array=new JSONArray(getItmes_json());
if (array==null)
return true;
//final DialogItem[] items=new DialogItem[array.length()];
final String[] titles=new String[array.length()];
final String[] actions=new String[array.length()];
for (int i = 0; i < array.length(); i++) {
titles[i]=array.getJSONObject(i).getString("title");
actions[i]=array.getJSONObject(i).getString("action");
//items[i]=gson.fromJson(array.getString(i), DialogItem.class);
}
if (actions.length>0){
MaterialDialogUtil.DialogCommListener listener1=new MaterialDialogUtil.DialogCommListener() {
@Override
public void todosomething() {
try {
if (!Constants.hasLoginOpenIM)
MainUtils.loginIM();
Action.createAction(actions[0]).excute(activity, webviewController, webView, parentingPost);
} catch (Exception e) {
e.printStackTrace();
LogUtil.e("action执行异常");
}
}
};
MaterialDialogUtil.showCommDialog(activity,getTitle_text(),desc_text,titles[0],cancel_text,listener1,null);
/*if (actions.length==1){
MaterialDialogUtil.DialogCommListener listener1=new MaterialDialogUtil.DialogCommListener() {
@Override
public void todosomething() {
try {
if (!Constants.hasLoginOpenIM)
MainUtils.loginIM();
Action.createAction(actions[0]).excute(activity, webviewController, webView, parentingPost);
} catch (Exception e) {
e.printStackTrace();
LogUtil.e("action执行异常");
}
}
};
MaterialDialogUtil.showCommDialog(activity,getTitle_text(),desc_text,null,cancel_text,listener1,null);
}else {
//MaterialDialogUtil.showCommDialog(activity,getTitle_text(),desc_text,"",cancel_text,listener1,null);
MaterialDialogUtil.showListDialog(activity, getTitle_text(), titles, new MaterialDialogUtil.DialogListListener() {
@Override
public void todosomething(int position) {
try {
if (!Constants.hasLoginOpenIM)
MainUtils.loginIM();
Action.createAction(actions[position]).excute(activity, webviewController, webView, parentingPost);
} catch (Exception e) {
e.printStackTrace();
LogUtil.e("action执行异常");
}
}
});
}*/
}
} catch (JSONException e) {
e.printStackTrace();
return true;
}
return true;
}
}
|
Java
|
UTF-8
| 2,244
| 2.296875
| 2
|
[] |
no_license
|
package sroom_pkg.ui.view;
import javax.swing.*;
import java.awt.event.*;
public class AddSlotInterfaceDialog extends JDialog {
private JPanel contentPane;
private JButton buttonOK;
private JButton buttonCancel;
private JTextField tfInterfaceName;
private JComboBox cbDeviceSlots;
private JButton addSlotButton;
private JButton renameSlotButton;
private JTextField tfDesc;
public AddSlotInterfaceDialog() {
setContentPane(contentPane);
setModal(true);
getRootPane().setDefaultButton(buttonOK);
setTitle("Add new interface");
/*buttonOK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
onOK();
}
});*/
buttonCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
onCancel();
}
});
// call onCancel() when cross is clicked
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
onCancel();
}
});
// call onCancel() on ESCAPE
contentPane.registerKeyboardAction(new ActionListener() {
public void actionPerformed(ActionEvent e) {
onCancel();
}
}, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
}
/*private void onOK() {
// add your code here
dispose();
}*/
private void onCancel() {
// add your code here if necessary
dispose();
}
public JComboBox getCbDeviceSlots() {
return cbDeviceSlots;
}
public JButton getButtonOK() {
return buttonOK;
}
public JTextField getTfInterfaceName() {
return tfInterfaceName;
}
public JButton getAddSlotButton() {
return addSlotButton;
}
public JButton getRenameSlotButton() {
return renameSlotButton;
}
public JTextField getTfDesc() {
return tfDesc;
}
public void setTfDesc(JTextField tfDesc) {
this.tfDesc = tfDesc;
}
}
|
C++
|
UTF-8
| 299
| 2.671875
| 3
|
[] |
no_license
|
#include<iostream>
#include<vector>
#include<set>
#include<cmath>
using namespace std;
int main(){
int N;
cin>>N;
float n1,n2;
float max=0;
for(int i=0;i<N;i++){
cin>>n1>>n2;
if((n1*n1+n2*n2)>max){
max= n1*n1 + n2*n2;
}
}
float res = sqrt(max);
printf("%0.2f",res);
return 0;
}
|
JavaScript
|
UTF-8
| 10,585
| 2.5625
| 3
|
[] |
no_license
|
'use strict';
/**
* This module provides useful functions that wrap around Sequelize to perform
* certain tedious things for us.
*/
var debug = require('debug')('zotago:ormHelpers');
var dataHelpers = require('./dataHelpers');
var util = require('./.');
var models = require('../models');
var Promise = require('bluebird');
// imported so that we can reexport the NoSuchAccountError
var auth = require('./auth');
/**
* An exception signifying that a post could not be found.
*
* @param {string} [message] - A message associated with this exception.
*/
function NoSuchPostError(message) {
this.message = message;
this.name = name;
Error.captureStackTrace(this, NoSuchPostError);
}
NoSuchPostError.prototype = Object.create(Error.prototype);
NoSuchPostError.prototype.constructor = NoSuchPostError;
module.exports.NoSuchPostError = NoSuchPostError;
/**
* Gets a nice JSON form of a specific post.
*
* @param object postModel -- The post model to obtain. Must be either {@link
* models.SellPost} or {@link models.WantPost}
* @param object where -- A Sequelize `where` object.
* @return Promise -- Resolves to an object fully representing the post.
*/
function getPost(postModel, selector) {
var thePost = {};
return postModel
.findOne(selector)
.then(function(post) {
if(!post) {
debug("throwing NoSuchPostError");
throw new auth.NoSuchPostError();
}
thePost.post = post;
return thePost.post.getTags();
})
.then(function(tags) {
thePost.tags = tags;
return thePost.post.getOffers();
})
.then(function(offers) {
thePost.offers = offers;
return thePost.post.getFollowers();
})
.then(function(followers) {
thePost.followers = followers;
return thePost.post.getCreator();
})
.then(function(creator) {
thePost.creator = creator;
return thePost;
})
.catch(NoSuchPostError, function(exc) {
debug("Handling NoSuchPostError");
return null;
});
}
module.exports.getPost = getPost;
/**
* Provides a high-level interface for querying different post models.
*
* @param object postModel -- the model of the post to query.
* @param object query -- the parameters of the query.
* @param object query.tags -- a list of tags that each post must have
* @return Promise -- resolves to an array of post instances of the given post
* model.
*/
function getPosts(postModel, query, activeAccount) {
// want to find all want posts whose tags are a superset of the given
// query.tags.
var q = {};
if(query.creatorId)
q.creatorId = query.creatorId;
var p = postModel.findAll({
where: q,
include: [{
model: models.Tag,
as: 'tags'
}, {
model: models.Account,
as: 'creator'
}]
})
.then(function(posts) {
return Promise.map(posts, function(post) {
return post.countFollowers()
.then(function(count) {
post.get().followerCount = count;
debug("Counted followers.");
return post.countOffers();
})
.then(function(count) {
post.get().offerCount = count;
debug("Counted offers.");
return post;
});
});
});
if(activeAccount) {
debug("Account active. Determining follow status.");
p = p.then(function(posts) {
return Promise.map(posts, function(post) {
return post.hasFollower(activeAccount)
.then(function(followStatus) {
// damn that's nasty
post.get().isFollowed = followStatus;
debug("Set post " + post.id + " follow status " + followStatus);
return post;
});
});
});
}
else {
debug("No active account. Skipping follow status check.");
}
// Because there's no good way to perform this kind of filtering on the
// Sequelize level (believe me, I tried) we'll have to do it on the
// application level (and hit the database more times than I would like).
// TODO optimize this code to run in the database.
if(query.tags)
p = p.then(function(wantPosts) {
return Promise.map(wantPosts, function(wp) {
return wp.getTags()
.then(function(wpTags) {
if(util.isSubset(
query.tags,
util.toSet(wpTags.map(function(t) {
return t.name;
})))) {
return wp;
}
else
return null;
});
})
.then(function(wantPosts) {
wantPosts = wantPosts.filter(function(wp) {
return wp != null
});
return wantPosts;
});
});
return p;
}
module.exports.getPosts = getPosts;
/**
* Creates a new post of the given model.
*
* @param Object postModel -- the model of the post to create
* @param Object data -- the post and related parameters
* @param Object data.mkPost -- the post parameters
* @param string data.mkPost.description -- post description
* @param int data.mkPost.creatorId -- id of the creator
* @param string data.mkPost.imageUrl -- url of image for post
* @param array data.tags -- names of tags to add to the post
* @return Promise -- resolves to the post instance that has been created
*/
function createPost(postModel, data) {
var mkPost = data.mkPost;
var tags = data.tags;
var dataUrlScheme = "data";
var p = Promise.resolve();
if(mkPost.imageUrl.slice(0, dataUrlScheme.length) === dataUrlScheme) {
var imageBuf = dataHelpers.parseDataUrl(mkPost.imageUrl);
p = dataHelpers.saveImage(imageBuf)
.then(function(imageData) {
var imageUrl = dataHelpers.getImageUrl(imageData.id)
mkPost.imageUrl = imageUrl;
});
}
var thePost;
debug('creating post for account ' + mkPost.creatorId);
return p
.then(function() {
return postModel.create(mkPost);
})
.then(function(post) {
thePost = post;
return Promise.all(tags.map(function(tag) {
return models.Tag.findOne({
where: {
name: tag
}
})
.then(function(tagInstance) {
// if the tag doesn't exist, then we need to create it
if(tagInstance)
return Promise.resolve(tagInstance);
else
return models.Tag.create({
name: tag
});
});
}))
})
.then(function(tags) {
debug('adding the tags to the post');
return Promise.all([
models.Account.findById(mkPost.creatorId),
thePost.addTags(tags)
]);
})
.then(function(resolved) {
var account = resolved[0];
debug('adding the creator as a follower of the post');
return thePost.addFollowers([account]);
})
.then(function() {
return getPost(postModel, {
where: {
id: thePost.id
}
});
});
}
module.exports.createPost = createPost;
/**
* Makes an account follow a post.
*
* Uses sequelizes `findOne` model method, so only a single account may be
* associated to a single post with this function.
*
* @param {Model} postModel - The model class of the type of post.
* @param {Object} options - Options for determining the account and post to
* associate.
* @param {Object} options.post - Options for selecting the post.
* @param {Object} options.account - Options for selecting the account.
* @return {Promise.<Post>} - The full post object of the selected post.
*/
function followPost(postModel, options) {
var postSelector = options.post;
var accountSelector = options.account;
return Promise.all([
postModel.findOne(postSelector),
models.Account.findOne(accountSelector)
])
.then(function(resolved) {
var post = resolved[0];
var account = resolved[1];
if(!post) {
debug("Throwing NoSuchPostError");
throw new auth.NoSuchPostError();
}
if(!account) {
debug("Throwing NoSuchAccountError");
throw new auth.NoSuchAccountError();
}
debug('Adding follower. ' + post + ' ' + account);
return post.addFollower(account);
})
.then(function(v) {
debug('Added follower. ' + JSON.stringify(v));
return getPost(postModel, postSelector);
})
.then(function(post) {
if(!post) {
debug("Throwing NoSuchPostError");
throw new auth.NoSuchPostError();
}
return post;
});
}
module.exports.followPost = followPost;
function unfollowPost(postModel, options) {
var postSelector = options.post;
var accountSelector = options.account;
return Promise.all([
postModel.findOne(postSelector),
models.Account.findOne(accountSelector)
])
.then(function(resolved) {
var post = resolved[0];
var account = resolved[1];
if(!post) {
debug("Throwing NoSuchPostError");
throw new auth.NoSuchPostError();
}
if(!account) {
debug("Throwing NoSuchAccountError");
throw new auth.NoSuchAccountError();
}
debug("Removing follower.");
return post.removeFollower(account);
})
.then(function(v) {
debug("Removed follower.");
return getPost(postModel, postSelector);
})
.then(function(post) {
if(!post) {
debug("Throwing NoSuchPostError");
throw new auth.NoSuchPostError();
}
return post;
});
}
module.exports.unfollowPost = unfollowPost;
|
Python
|
UTF-8
| 763
| 2.796875
| 3
|
[] |
no_license
|
import requests
import csv
import json
response = requests.get("https://jsonplaceholder.typicode.com/users")
users = json.loads(response.text)
def flattenjson(b, delim):
val = {}
for i in b.keys():
if isinstance( b[i], dict ):
get = flattenjson( b[i], delim )
for j in get.keys():
val[ i + delim + j ] = get[j]
else:
val[i] = b[i]
return val
users = list(map( lambda x: flattenjson( x, "_" ), users ))
columns = [ x for row in users for x in row.keys() ]
columns = list(columns)
print(json.dumps(users, indent=2))
filename = "demo.csv"
with open(filename, 'w') as file:
writer = csv.DictWriter(file, fieldnames=columns)
writer.writeheader()
writer.writerows(users)
|
C#
|
UTF-8
| 1,241
| 3.546875
| 4
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Step199_BooleanLogic
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hi, let's find out if you are qualified for our auto insurance.");
// Obtains age from applicant.
Console.WriteLine("(1/3) What is your age?");
string ageStr = Console.ReadLine();
byte age = Convert.ToByte(ageStr);
// Obtains DUI info from applicant.
Console.WriteLine("(2/3) True or False? Have you ever had a DUI?");
string duiStr = Console.ReadLine();
bool dui = Convert.ToBoolean(duiStr);
// Obtains driving record info from applicant.
Console.WriteLine("(3/3) How many speeding tickets do you have?");
string numOfTicketsStr = Console.ReadLine();
byte numOfTickets = Convert.ToByte(numOfTicketsStr);
// Determines qualification of application.
Console.WriteLine("Qualified?");
Console.WriteLine(age > 15 && dui == false && numOfTickets <= 3);
Console.ReadLine();
}
}
}
|
Python
|
UTF-8
| 139
| 3.453125
| 3
|
[] |
no_license
|
a = int(input())
b = int(input())
c = int(input())
d = int(input())
sum = a + b + c + d
m = sum % 3600 // 60
s = sum % 60
print(m)
print(s)
|
Java
|
UTF-8
| 6,225
| 2.328125
| 2
|
[] |
no_license
|
package io.walter.realmcrud;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.design.widget.Snackbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomListAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<PersonModel> temporaryArray;
public CustomListAdapter(Context context, ArrayList<PersonModel> data) {
this.mContext = context;
this.temporaryArray = data;
}
@Override
public int getCount() {
return temporaryArray.size();// # of items in your arraylist
}
@Override
public Object getItem(int position) {
return temporaryArray.get(position);// get the actual movie
}
@Override
public long getItemId(int id) {
return id;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
convertView = inflater.inflate(R.layout.list_item_layout, parent, false);
viewHolder = new ViewHolder();
viewHolder.tvNames = (TextView) convertView.findViewById(R.id.tvPersonName);
viewHolder.imgViewDelete= (ImageView) convertView.findViewById(R.id.ivDeletePerson);
viewHolder.imgViewEdit= (ImageView) convertView.findViewById(R.id.ivEditPesonDetail);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
final PersonModel personModel = temporaryArray.get(position);
viewHolder.tvNames.setText(personModel.getName());
viewHolder.imgViewDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PersonModel model=temporaryArray.get(position);
int id= model.getId();
show_confirmDialog(id, position);
}
});
viewHolder.imgViewEdit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PersonModel model=temporaryArray.get(position);
int id= model.getId();
show_update_dialog(model,id, position);
}
});
return convertView;
}
private void show_update_dialog(final PersonModel model, final int id, final int position) {
LayoutInflater inflater = LayoutInflater.from(mContext);
final View add_view = inflater.inflate(R.layout.prompt_dialog, null);
final android.support.v7.app.AlertDialog addDialog = new android.support.v7.app.AlertDialog.Builder(mContext).setTitle("Update Person").create();
addDialog.setView(add_view);
final EditText edtNames = (EditText) add_view.findViewById(R.id.etAddPersonName);
edtNames.setText(model.getName());
final EditText edtEmail = (EditText) add_view.findViewById(R.id.etAddPersonEmail);
edtEmail.setText(model.getEmail());
final EditText edtAddress = (EditText) add_view.findViewById(R.id.etAddPersonAddress);
edtAddress.setText(model.getAddress());
final EditText edtAge = (EditText) add_view.findViewById(R.id.etAddPersonAge);
edtAge.setText(String.valueOf(model.getAge()));
Button btnSave= (Button) add_view.findViewById(R.id.btnSave);
Button btnClose= (Button) add_view.findViewById(R.id.btnClose);
btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String names = edtNames.getText().toString().trim();
String email = edtEmail.getText().toString().trim();
String address = edtAddress.getText().toString().trim();
String age_string = edtAge.getText().toString().trim();
if (names.isEmpty() || email.isEmpty() || address.isEmpty() || age_string.isEmpty()) {
Snackbar.make(add_view, "Fill in all fields", Snackbar.LENGTH_LONG).show();
return;
}
int age = Integer.parseInt(age_string);
model.setName(names);
model.setAge(age);
model.setAddress(address);
model.setEmail(email);
MainActivity.getInstance().updateToReal(model,id,position);
Snackbar.make(add_view, "Updated Successfully", Snackbar.LENGTH_LONG).show();
addDialog.dismiss();
}
});
btnClose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addDialog.dismiss();
}
});
addDialog.show();
}
private void show_confirmDialog(final int id, final int position) {
AlertDialog.Builder alertDialog=new AlertDialog.Builder(mContext);
alertDialog
.setTitle("Sure?")
.setMessage("Do you really want to delete this record?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
MainActivity.getInstance().deleteFromRealm(id,position);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setCancelable(true)
.create()
.show();
}
static class ViewHolder
{
TextView tvNames;
ImageView imgViewEdit;
ImageView imgViewDelete;
}
}
|
Java
|
UTF-8
| 1,271
| 2.3125
| 2
|
[] |
no_license
|
package com.iseven.learn.xdlearn.configuration;
import com.iseven.learn.xdlearn.interceptor.CorsInterceptor;
import com.iseven.learn.xdlearn.interceptor.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 拦截器配置
* <p>
* 不用权限可以访问url /api/v1/pub/
* 要登录可以访问url /api/v1/pri/
*/
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Autowired
private LoginInterceptor loginInterceptor;
@Autowired
private CorsInterceptor corsInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
/**
* 拦截全部路径,这个跨域需要放在最上面
*/
registry.addInterceptor(corsInterceptor).addPathPatterns("/**");
registry.addInterceptor(loginInterceptor).addPathPatterns("/api/v1/pri/*/*/**")
//不拦截哪些路径 斜杠一定要加
.excludePathPatterns("/api/v1/pri/user/login", "/api/v1/pri/user/register");
}
}
|
JavaScript
|
UTF-8
| 8,580
| 2.640625
| 3
|
[] |
no_license
|
//柱状图 比例
(function (name, definition) {
// this is considered "safe":
var hasDefine = typeof define === 'function';
var hasExports = typeof module !== 'undefined' && module.exports;
if (hasDefine) {
// AMD Module or CMD Module
define(definition);
} else if (hasExports) {
// Node.js Module
module.exports = definition();
} else {
// Assign to common namespaces or simply the global object (window)
this[name] = definition();
}
})('StackRatio', function () {
return function (config) {
this.config = config;
// 4 params must need
var container = typeof config.container === 'string' ? document.getElementById(config.container) //id
: config.container; // dom node
var data = config.data || [
{ name: '尼尔森零研',
total: 13000,
children: [
{"name":"海飞丝", "value":8167},
{"name":"沙宣", "value":1492},
{"name":"爱茉莉", "value":2782}
]
},
{ name: '尼尔森电商',
total: 1400,
children: [
{"name":"海飞丝", "value":167},
{"name":"沙宣", "value":492},
{"name":"爱茉莉", "value":782}
]
},
{ name: '淘宝天猫',
total: 13000,
children: [
{"name":"海飞丝", "value":7167},
{"name":"沙宣", "value":1492},
{"name":"爱茉莉", "value":2782}
]
}
];
var color = config.color;
var width = config.width || $(container).width() || 960;
var height = config.height || $(container).height() || 500;
var margin = config.margin || {top: 20, right: 20, bottom: 50, left: 100};
var getColor = color ? d3.scale.ordinal().range(color) : d3.scale.category10();
this.setSource = function (sourceData) {
data = sourceData;
};
this.setOptions = function (config) {
width = config.width || width;
height = config.height || height;
margin = config.margin || margin;
color = config.color || color;
getColor = color ? d3.scale.ordinal().range(color) : getColor;
};
var processData = this.processData = function (data) {
data.forEach(function (d, i) {
d.index = i;
});
data.forEach(function (d) {
var sum = 0;
d.children.forEach(function (c) {
c.h = sum;
sum += c.value / d.total;
c.v = c.value / d.total;
c.group = d;
c.color = c.color || getColor(c.name);
});
});
};
var floatTag = this.floatTag = (function () {
var mouseToFloatTag = {x: 20, y: 20};
var setContent = function () {};
var node;
var container;
//set floatTag location, warning: the html content must be set before call this func,
// because jqNode's width and height depend on it's content;
var _changeLoc = function (m) {
//m is mouse location, example: {x: 10, y: 20}
var x = m.x;
var y = m.y;
var floatTagWidth = node.outerWidth ? node.outerWidth() : node.width();
var floatTagHeight = node.outerHeight ? node.outerHeight() : node.height();
if (floatTagWidth + x + 2 * mouseToFloatTag.x <= $(container).width()) {
x += mouseToFloatTag.x;
} else {
x = Math.max(1, x - floatTagWidth - mouseToFloatTag.x);
}
if (y >= floatTagHeight + mouseToFloatTag.y) {
y = y - mouseToFloatTag.y - floatTagHeight;
} else {
y += Math.min(mouseToFloatTag.y, $(container).height() - floatTagHeight);
}
node.css("left", x);
node.css("top", y);
};
var _mousemove = function (e) {
var offset = $(container).offset();
if (!(e.pageX && e.pageY)) {return false;}
var x = e.pageX - offset.left,
y = e.pageY - offset.top;
setContent.call(this);
_changeLoc({'x': x, 'y': y});
};
var floatTag = function (cont) {
container = $(cont);
container.css('position', 'relative');
node = $("<div/>").css({
"border": "1px solid",
"border-color": $.browser.msie ? "rgb(32, 32, 32)" : "rgba(32, 32, 32, 0.9)",
"background-color": $.browser.msie ? "rgb(255, 255, 255)" : "rgba(255, 255, 255, 0.8)",
"color": "#000",
"border-radius": "2px",
"padding": "12px 8px",
"font-size": "12px",
"box-shadow": "3px 3px 6px 0px rgba(0,0,0,0.58)",
"font-familiy": "宋体",
"z-index": 1000,
"text-align": "center",
"visibility": "hidden",
"position": "absolute"
});
container.append(node);
container.on('mousemove', _mousemove);
container.on('tap', _mousemove);
node.creator = floatTag;
return node;
};
floatTag.setContent = function (sc) {
if (arguments.length === 0) {
return setContent;
}
setContent = sc;
return floatTag;
};
floatTag.mouseToFloatTag = function (m) {
if (arguments.length === 0) {
return mouseToFloatTag;
}
mouseToFloatTag = m;
return floatTag;
};
floatTag.changeLoc = _changeLoc;
return floatTag;
}())(container);
var render = this.render = function () {
$(container).empty();
$(container).addClass('stack-ratio');
$(container).css('position', 'relative').append(floatTag);
processData(data);
var w = width - margin.left - margin.right,
h = height - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.domain(data.map(function(d) { return d.index; }))
.rangeRoundBands([0, w], .5);
var y = d3.scale.linear()
.domain([0, 1]).nice()
.range([h, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickFormat(function (d, i) { return data[i].name; });
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickSize(-w)
.ticks(5, "%");
//.ticks(10, "%");
var svg = d3.select(container).append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + h + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
var bar = svg.selectAll(".bar-group")
.data(data)
.enter().append('g').selectAll(".bar")
.data(function (d) { return d.children;})
.enter().append("rect")
.attr("class", "bar")
.attr("fill", function (d) {
return d.color; })
.attr("x", function(d) { return x(d.group.index); })
.attr("width", x.rangeBand())
.attr("y", function(d) {
console.log(d.h, d.h + d.v); return y(d.h + d.v); })
.attr("height", function(d) {
console.log(d.v); return y(d.h) - y(d.h + d.v); });
bar.on('mouseover', function () {
var data = this.__data__;
var html = '';
html += data.group.name + '<br>';
data.group.children.slice().reverse().forEach(function (d) {
html += '<div style="position: relative;color:' + (data.name === d.name ? '#000' : 'gray') + '">' +
'<span class="float-tag-point" style="background-color:' + d.color + ';"></span>' +
'<span class="float-tag-name">' + d.name + '</span>' +
'<span class="float-tag-value">' + d3.format('.2%')(d.v) + '</span>' +
'<span class="float-tag-value">' + d3.format(',')(d.value) + '</span>' +
'</div>' +
'<div style="clear:both;"></div>';
});
floatTag.html(html);
floatTag.css({"visibility" : "visible"});
});
bar.on('mouseout', function () {
floatTag.css({"visibility" : "hidden"});
});
//legend
var legend = $('<div class="legend"></div>');
data[0].children.forEach(function (d) {
$('<span/>').css('border-color', d.color).html(d.name).appendTo(legend);
});
$(container).append(legend);
};
};
});
|
Markdown
|
UTF-8
| 5,717
| 2.640625
| 3
|
[
"Apache-2.0"
] |
permissive
|
**Elasticsearch Sink**
The sink reads events from a channel, serializes them into json documents and batches them into a bulk processor.
Bulk processor batches the writes to elasticsearch as per configuration.
The elasticsearch index and type for each event can be defined statically in the configuration file or can be derived dynamically using a custom IndexBuilder.
By default, events are assumed to be in json format.
This assumption can be overridden by implementing the Serializer interface.
Follow these steps to use this sink in Apache flume:
* Build the plugin. This command will create the zip file inside the target directory.
`mvn clean assembly:assembly`
* Extract the file into the flume installation directories plugin.d folder.
* 如果是CDH环境的Flume(CDH5.16.1)需要删除/opt/cloudera/parcels/CDH/lib/flume-ng/lib文件夹中以下jar包,否则会出现jar包冲突程序无法启动
httpclient-4.2.5.jar
httpcore-4.2.5.jar
jackson-core-2.3.1.jar
* Configure the sink in the flume configuration file with properties as below
Required properties are in bold.
| Property Name | Default | Description |
|--------------------------------------------|--------------|:----------------------------------------------------------------------------------------------|
| **channel** | - | |
| **type** | - | The component type name, has to be com.cognitree.flume.sink.elasticsearch.ElasticSearchSink |
| **batchSize** | 1000 | Single transaction batch size |
| **es.cluster.name** | elasticsearch | Name of the elasticsearch cluster to connect to |
| **es.client.hosts** | - | Comma separated hostname:port pairs ex: host1:9200,host2:9200. The default port is 9200 |
| es.bulkActions | 10000 | The number of actions to batch into a request |
| es.bulkProcessor.name | flume | Name of the bulk processor |
| es.bulkSize | 5 | Flush the bulk request every mentioned size |
| es.bulkSize.unit | MB | Bulk request unit, supported values are KB and MB |
| es.concurrent.request | 1 | The maximum number of concurrent requests to allow while accumulating new bulk requests |
| es.flush.interval.time | 10s | Flush a batch as a bulk request every mentioned seconds irrespective of the number of requests|
| es.backoff.policy.time.interval | 50M | Backoff policy time interval, wait initially for the 50 miliseconds |
| es.backoff.policy.retries | 8 | Number of backoff policy retries |
| es.index | default | Index name to be used to store the documents |
| es.index.builder |com.cognitree.<br>flume.sink.<br>elasticsearch.<br>StaticIndexBuilder | Implementation of com.cognitree.flume.sink.elasticsearch.IndexBuilder interface |
| es.serializer |com.cognitree.<br>flume.sink.<br>elasticsearch.<br>SimpleSerializer | Implementation of com.cognitree.flume.sink.elasticsearch.Serializer interface |
| es.serializer.csv.fields | - | Comma separated csv field name with data type i.e. column1:type1,column2:type2, Supported data types are string, boolean, int and float |
| es.serializer.csv.delimiter | ,(comma) | Delimiter for the data in flume event body|
| es.serializer.avro.schema.file | - | Absolute path for the schema configuration file |
Example of agent named agent
````
agent.channels = es_channel
agent.sinks = es_sink
agent.sinks.es_sink.channel=es_channel
agent.sinks.es_sink.type=com.cognitree.flume.sink.elasticsearch.ElasticSearchSink
agent.sinks.es_sink.batchSize=2000
agent.sinks.es_sink.es.bulkActions=5000
agent.sinks.es_sink.es.bulkProcessor.name=bulkprocessor
agent.sinks.es_sink.es.bulkSize=5
agent.sinks.es_sink.es.bulkSize.unit=MB
agent.sinks.es_sink.es.concurrent.request=1
agent.sinks.es_sink.es.flush.interval.time=10s
agent.sinks.es_sink.es.backoff.policy.time.interval=50M
agent.sinks.es_sink.es.backoff.policy.retries=8
agent.sinks.es_sink.es.cluster.name=es-cluster
agent.sinks.es_sink.es.client.hosts=127.0.0.1:9200
agent.sinks.es_sink.es.index=defaultindex
agent.sinks.es_sink.es.index.builder=com.cognitree.flume.sink.elasticsearch.HeaderBasedIndexBuilder
agent.sinks.es_sink.es.serializer=com.cognitree.flume.sink.elasticsearch.SimpleSerializer
agent.sinks.es_sink.es.serializer.csv.fields=id:int,name:string,isemployee:boolean,leaves:float
agent.sinks.es_sink.es.serializer.csv.delimiter=,
agent.sinks.es_sink.es.serializer.avro.schema.file=/usr/local/schema.avsc
````
|
Python
|
UTF-8
| 321
| 2.75
| 3
|
[] |
no_license
|
# Written by Charlie Vrattos
import pandas as pd
def generateComplement(sequence):
sequence.columns = ['T', 'A', 'G', 'C']
sequence = sequence[::-1].reset_index(drop=True)
return sequence
def main():
with open('control/GAME.json') as f:
game = pd.read_json(f)
generateComplement(game)
if __name__ == "__main__":
main()
|
Python
|
UTF-8
| 1,200
| 4.1875
| 4
|
[
"MIT"
] |
permissive
|
"""
Numerical integration.
"""
def next_step(a, b, h):
x = a + h
while x < (b - h):
yield x
x = x + h
def trapezoidal(left, right, steps):
"""
Trapezoidal Rule: int(f) = h/2 * (f1 + 2f2 + ... + fn)
:param left: left end of searching range
:param right: right end of searching range
:param steps: steps for searching
:return: int(f)
"""
a, b = left, right
h = (b - a) / steps
y = 0
y += (h / 2) * f(a)
for i in next_step(a, b, h):
y += h * f(i)
y += (h / 2) * f(b)
return y
def simpson(left, right, steps):
"""
Simpson's Rule: int(f) = h/2 * (b-a)/3*(f1 + 4f2 + 2f_3 + ... + fn)
:param left: left end of searching range
:param right: right end of searching range
:param steps: steps for searching
:return: int(f)
"""
a, b = left, right
h = (b - a) / steps
y = 0
y += (h / 3) * f(a)
cnt = 2
for i in next_step(a, b, h):
y += (h / 3) * (4 - 2 * (cnt % 2)) * f(i)
cnt += 1
y += (h / 3) * f(b)
return y
if __name__ == '__main__':
def f(x):
return x ** 2
print(trapezoidal(0, 3, 100))
print(simpson(0, 3, 100))
|
C++
|
UTF-8
| 2,173
| 3.234375
| 3
|
[] |
no_license
|
#include <iostream>
using namespace std;
template <typename T, int stack_size>
class Stack
{
int top = 0;
T ara[stack_size];
public:
void push(T a)
{
if(top >= stack_size)
{
cout << "Error: Stack is FULL!" << endl;
exit(1);
}
else
{
ara[top] = a;
top++;
}
}
T pop()
{
if(top == 0)
{
cout << "Error: Stack is EMPTY!" << endl;
exit(1);
}
else
{
top--;
return ara[top];
}
}
T stackTop()
{
if(top == 0)
{
cout << "Error: Stack is EMPTY!" << endl;
exit(1);
}
else
{
return ara[top-1];
}
}
int getTop()
{
return top;
}
bool isEmpty() { return top == 0; }
bool isFull() { return top >= stack_size; }
T peek(int i)
{
if(top - i > -1)
return ara[top-i];
else
{
cout << "Invalid Index : ";
return -1;
cout << endl;
}
}
void beEmpty() { top = 0; }
};
int main()
{
int t; cin >> t;
Stack<string, 101> back, front;
string cmd, url = "http://www.lightoj.com/";
for (int i = 0; i < t; i++)
{
url = "http://www.lightoj.com/";
cout << "Case " << i+1 << ":" << endl;
cin >> cmd;
while(1)
{
if(cmd == "VISIT")
{
back.push(url);
cin >> url;
cout << url << endl;
front.beEmpty();
}
else if(cmd == "BACK")
{
if(!back.isEmpty())
{
front.push(url);
url = back.pop();
cout << url << endl;
}
else
cout << "Ignored" << endl;
}
else if(cmd == "FORWARD")
{
if(!front.isEmpty())
{
back.push(url);
url = front.pop();
cout << url << endl;
}
else
cout << "Ignored" << endl;
}
else if(cmd == "QUIT")
{
break;
}
cin >> cmd;
}
back.beEmpty();
front.beEmpty();
}
return 0;
}
|
Markdown
|
UTF-8
| 3,986
| 2.875
| 3
|
[] |
no_license
|
---
layout: blog-single
title: Creating Grafana Annotations with InfluxDb
description: When reviewing historical data it's useful to overlay a timeline of key events. Here, we'll look at creating annotations for InfluxDb Grafana visualizations.
date: August 08, 2016
tags: [Monitoring, Grafana, InfluxDB]
related_posts:
- "Send A Kapacitor Alert If No Data Is Received"
- "Using Kapacitor UDFs to monitor URL query parameter usage"
- "MySQL Query Cache Hit Rate"
---
When reviewing historical data in tools such as InfluxDb, it's typically useful to overlay a timeline of key events. For example, [Google Analytics features a simple GUI for adding annotations](https://analytics.googleblog.com/2010/01/annotations-now-available-in-all.html) and [New Relic offers an API for marking deployments](https://docs.newrelic.com/docs/apm/new-relic-apm/maintenance/recording-deployments). In this post we'll look at creating annotations for your InfluxDb powered Grafana visualizations.
<!-- excerpt_separator -->
### Composition of an annotation
As shown in [the official Grafana documentation for annotations with InfluxDb](http://docs.grafana.org/reference/annotations/#influxdb-annotations), an annotation is composed of up to 3 pieces of data...
1. Title
2. Tags
3. Text
Grafana hasn't provided any official recommendation on how to use these three fields (that I can find), but in the screenshot below...
1. "Deployed v10.2.0" is the "Title"
2. "Release notes" is the "Text"
3. "these" "are" "the" "tags" are the "Tags"
<img
src="/img/blog/grafana-annotations/grafana-influxdb-annotation-screenshot@1x.jpg"
srcset="/img/blog/grafana-annotations/grafana-influxdb-annotation-screenshot@1x.jpg 1x, /img/blog/grafana-annotations/grafana-influxdb-annotation-screenshot@2x.jpg 2x"
alt="Grafana InfluxDb Annotation Screenshot">
From my research it seems that...
1. The title is typically used to provide a heading for the event
2. The text provides additional information. Linking to release notes is good use case
3. I'm not sure what tags are meant to be used for. Perhaps to allow filtering of annotations on a dashboard for certain tags, although I haven't seen that documented anywhere.
### Writing to data to InfluxDb
Grafana expects that each of the pieces of data will come from a [field](https://docs.influxdata.com/influxdb/v0.13//concepts/glossary/#field) not a [tag](https://docs.influxdata.com/influxdb/v0.13/concepts/glossary/#tag).
The InfluxDb query to create the annotation from the screenshot above looks like this.
```
$ curl -X POST "http://localhost:8086/write?db=mydb&precision=s" --data-binary 'events title="Deployed v10.2.0",text="<a href='https://github.com'>Release notes</a>",tags="these,are,the,tags" 1470661200'
```
As you can see...
- Grafana will let you send HTML in the "Text" such as a link to the release notes
- The tags are separated by commas
### Pulling the data into Grafana
The annotation can be pulled into Grafana as follows...
<img
src="/img/blog/grafana-annotations/grafana-influxdb-add-annotation@1x.jpg"
srcset="/img/blog/grafana-annotations/grafana-influxdb-add-annotation@1x.jpg 1x, /img/blog/grafana-annotations/grafana-influxdb-add-annotation@2x.jpg 2x"
alt="Grafana InfluxDb Add Annotation">
Per the Grafana docs, if you only select one field you don't need to fill out the Column mappings and that field will automatically be pulled in as the title
### Limitations
Annotations are created on a per dashboard basis....
- They can't apply to a single graph
- They can't apply to a single panel
- They can't apply across multiple dashboards
### Conclusion
When I was first reading on annotations I found that a lot of information was missing from [the Grafana annotation docs](http://docs.grafana.org/reference/annotations/), so I'm hoping this will help a few people. Feel free to use the comments section below or [hit me up on Twitter](https://twitter.com/maxpchadwick) if you have comments or questions.
|
C
|
UTF-8
| 705
| 3.6875
| 4
|
[] |
no_license
|
#include<stdio.h>
#include<stdlib.h>
struct linked{
char d;
struct linked *next;
};
typedef struct linked ELEMENT;
typedef ELEMENT*LINK;
LINK string_to_list(char s[])
{
int i=1;
LINK head; LINK temp; LINK head2;
head=malloc(sizeof(ELEMENT));
head->d=s[0];
head2=head;
while(s[i]!='\0')
{
head->next=malloc(sizeof(ELEMENT));
head=head->next;
head->d=s[i];
i++;
}
return head2;
}
void print(LINK head){
if(head==NULL)
printf("NULL\n");
else{
printf("%c --> ",head->d);
print(head->next);
}
}
int main()
{
char input[100];
LINK h;
printf("type: ");
scanf("%s",input);
h=string_to_list(input);
print(h);
return 0;
}
|
Java
|
UTF-8
| 188
| 2.296875
| 2
|
[] |
no_license
|
public class EmptyHeapException extends RuntimeException {
public EmptyHeapException(){
super();
}
public EmptyHeapException(String msg) {
super(msg);
}
}
|
Java
|
WINDOWS-1252
| 1,656
| 2.40625
| 2
|
[] |
no_license
|
package com.gc.hr.po;
import org.hibernate.Hibernate;
import org.hibernate.proxy.HibernateProxy;
import com.gc.util.CommonUtil;
/**
* ù
* @author hsun
*
*/
public class RegType {
private RegTypePK id;
private Double no;
private Integer active;
public RegType() {
}
public RegType(Integer branchId, String name) {
this(new RegTypePK(branchId, name));
}
public RegType(RegTypePK id) {
setId(id);
}
public Integer getBranchId() {
return (id == null) ? null : id.getBranchId();
}
public String getName() {
return (id == null) ? null : id.getName();
}
public RegTypePK getId() {
return id;
}
public void setId(RegTypePK id) {
this.id = id;
}
public Double getNo() {
return no;
}
public void setNo(Double no) {
this.no = no;
}
public Integer getActive() {
return active;
}
public void setActive(Integer active) {
this.active = active;
}
public boolean equals(Object obj) {
RegType po = (obj instanceof RegType) ? (RegType) obj : null;
return CommonUtil.equals(this, po);
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Personal.RegType{id=").append(id)
.append(", no=").append(no).append("}");
return sb.toString();
}
public static RegType getSafeObject(RegType po) {
if (Hibernate.isInitialized(po)) {
if (po instanceof HibernateProxy) return (RegType) ((HibernateProxy) po).getHibernateLazyInitializer().getImplementation();
else return po;
} else {
if (po == null) return null;
else return new RegType(po.getId());
}
}
}
|
Java
|
UTF-8
| 440
| 1.695313
| 2
|
[] |
no_license
|
package com.xinmiao.back.mapper;
import com.xinmiao.back.domain.Img;
import com.xinmiao.back.util.MyMapper;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface ImgMapper extends MyMapper<Img> {
@Select("select * from img where scene_id=#{id} order by img_pos asc")
@ResultMap("BaseResultMap")
public List<Img> selectImgsBySceneId(Integer id);
}
|
JavaScript
|
UTF-8
| 2,237
| 3.53125
| 4
|
[] |
no_license
|
const input = 'uugsqrei';
const reverse = (list, index, num) => {
const len = list.length;
const copy = list.slice(index, Math.min(index + num, len))
.concat(list.slice(0, Math.max(0, index + num - len)))
.reverse();
for (let i = 0; i < num; i++) {
list[(index + i) % len] = copy[i];
}
}
const knot = (lengths, iterations=64) => {
const sequence = [...Array(256).keys()];
let index = 0;
let skipSize = 0;
for (let i = 0; i < iterations; i++) {
lengths.forEach(x => {
reverse(sequence, index, x);
index += x + skipSize++;
index %= sequence.length;
});
}
return sequence;
}
const denseHash = (sequence) => {
const blockSize = 16;
return Array(blockSize).fill()
.map((x, i) => sequence
.slice(i * blockSize, (i + 1) * blockSize)
.reduce((a, b) => a ^ b)
);
}
const toHex = (sequence) => {
return sequence.map(x => x.toString(16).padStart(2, '0')).join('');
}
const knotHash = (key) => {
const suffix = [17, 31, 73, 47, 23];
const lengths = [...key].map(x => x.charCodeAt(0)).concat(suffix);
const sequence = knot(lengths);
const dense = denseHash(sequence);
return toHex(dense);
}
const hexToBinary = (x) => {
return [...x].map(y => parseInt(y, 16).toString(2).padStart(4, '0')).join('');
}
const binaryHashGrid = (input) => {
return [...Array(128).keys()]
.map(i => knotHash(`${input}-${i}`))
.map(hexToBinary)
.map(x => [...x]);
}
const buildRegion = (grid, x, y, n) => {
if (!grid[y] || grid[y][x] !== '1')
return;
grid[y][x] = n;
buildRegion(grid, x + 1, y, n);
buildRegion(grid, x - 1, y, n);
buildRegion(grid, x, y + 1, n);
buildRegion(grid, x, y - 1, n);
}
const countRegions = (grid) => {
let numRegions = 0;
for (let i = 0; i < grid.length; i++) {
for (let j = 0; j < grid[0].length; j++) {
if (grid[i][j] === '1') {
buildRegion(grid, j, i, numRegions++);
}
}
}
return numRegions;
}
const part1 = (input) => {
return binaryHashGrid(input)
.map(x => x.filter(y => y === '1').length)
.reduce((a, b) => a + b);
}
const part2 = (input) => {
return countRegions(binaryHashGrid(input));
}
console.log(part1(input));
console.log(part2(input));
|
Java
|
UTF-8
| 546
| 3.4375
| 3
|
[] |
no_license
|
import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int stairs = Integer.parseInt(console.next());
int multiplier = Integer.parseInt(console.next());
int answer = 0;
if (stairs %2 == 1){
answer = (stairs / 2) + 1;
}
else{
answer = stairs /2;
}
boolean run = true;
if (stairs < multiplier){
answer = -1;
run = false;
}
while((answer % multiplier) != 0 && run){
answer++;
}
console.close();
System.out.println(answer);
}
}
|
Rust
|
UTF-8
| 2,600
| 3.421875
| 3
|
[] |
no_license
|
use std::collections::HashMap;
fn main() {
let mut neighboring_sums: HashMap<(i64, i64), i64> = HashMap::new();
neighboring_sums.insert((0, 0), 1);
for (n, (x, y)) in SquareSpiral::new().take(347992).enumerate() {
let n = n + 1;
let mut sum = 0;
for i in x-1..x+2 {
for j in y-1..y+2 {
if let Some(v) = neighboring_sums.get(&(i, j)) {
sum += v;
}
}
}
neighboring_sums.insert((x, y), sum);
// part one
// if n == 347991 {
// println!("n={} ({}, {}) d={} val={}", n, x, y, manhattan_distance(0, 0, x, y), sum);
// }
// part two
if sum >= 347991 {
println!("n={} ({}, {}) d={} val={}", n, x, y, manhattan_distance(0, 0, x, y), sum);
return
}
}
}
// Generate (x, y) coordinates for a point on the square spiral starting at
// (0, 0), moving to (1, 0) and then proceeding counter-clockwise.
//
// 17 - 16 - 15 - 14 - 13
// | |
// 18 5 - 4 - 3 12
// | | | |
// 19 6 1 - 2 11
// | | |
// 20 7 - 8 - 9 - 10
// |
// 21 - 22 - 23---> ...
//
// SquareSpiral is an infite iterator.
struct SquareSpiral {
x: i64,
y: i64,
dx: i64,
dy: i64,
pos_in_side: usize,
side_len: usize,
last_side_len: usize,
}
impl SquareSpiral {
fn new() -> SquareSpiral {
SquareSpiral {
x: 0,
y: 0,
dx: 1,
dy: 0,
pos_in_side: 0,
side_len: 1,
last_side_len: 0,
}
}
}
impl Iterator for SquareSpiral {
type Item = (i64, i64);
fn next(&mut self) -> Option<Self::Item> {
// save the current (x, y) to return
let (x, y) = (self.x, self.y);
self.x += self.dx;
self.y += self.dy;
self.pos_in_side += 1;
if self.pos_in_side == self.side_len {
// reset side
self.pos_in_side = 0;
// rotate 90
let (new_dx, new_dy) = (-1 * self.dy , self.dx);
self.dx = new_dx;
self.dy = new_dy;
//increment side len
if self.side_len == self.last_side_len {
self.side_len += 1
} else {
self.last_side_len = self.side_len
}
}
Some((x, y))
}
}
fn manhattan_distance(x1: i64, y1: i64, x2: i64, y2: i64) -> i64 {
(x2 - x1).abs() + (y2 - y1).abs()
}
|
PHP
|
UTF-8
| 970
| 2.953125
| 3
|
[] |
no_license
|
<?php
/**
* Created by IntelliJ IDEA.
* User: capitanjovi
* Date: 4/2/17
* Time: 2:29 PM
*/
class Conexion {
private static $conexion;
public static function abrirConexion() {
if (!isset(self::$conexion)) {
try {
include_once "config.inc.php";
self::$conexion = new PDO("mysql:host=$nombreServidor; dbname=$nombreBaseDatos", $nombreUsuario, $password);
self::$conexion->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
self::$conexion->exec("SET CHARACTER SET utf8");
} catch (PDOException $exception) {
print "ERROR: " . $exception->getMessage() . "<br>";
die();
}
}
}
public static function cerrarConexion() {
if (isset(self::$conexion)) {
self::$conexion = null;
}
}
public static function obtenerConexion() {
return self::$conexion;
}
}
|
C++
|
UTF-8
| 1,029
| 3.0625
| 3
|
[] |
no_license
|
#include<iostream>
#include<future>
#include<string>
using namespace std;
using namespace std::placeholders;
namespace nm21
{
double div1(double x, double y)
{
return x / y;
}
void main()
{
cout << "1/4=" << div1(1, 4) << endl;
cout << "2/4=" << div1(2, 4) << endl;
cout << "3/4=" << div1(3, 4) << endl;
cout << "_______________________" << endl;
std::function<double(double)> fp = std::bind(&div1, _1, 4);
cout << "1/4=" << fp(1) << endl;
cout << "2/4=" << fp(2) << endl;
cout << "3/4=" << fp(3) << endl;
std::function<double(double)> fp1 = std::bind(&div1, 4, _1);
cout << "_______________________" << endl;
cout << "4/1=" << fp1(1) << endl;
cout << "4/2=" << fp1(2) << endl;
cout << "4/3=" << fp1(3) << endl;
cout << "_______________________" << endl;
std::function<double(double, double)> fp2 = std::bind(&div1, _2, _1);
cout << "1/4=" << fp2(1, 4) << endl;
cout << "2/4=" << fp2(2, 4) << endl;
cout << "3/4=" << fp2(3, 4) << endl;
cout << "_______________________" << endl;
}
}
|
Java
|
UTF-8
| 1,228
| 2.28125
| 2
|
[] |
no_license
|
package com.demo.asm.model.location;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name = "physical_location")
@SequenceGenerator(name = "physical_location_seq", sequenceName = "physical_location_seq", allocationSize = 1)
public class PhysicalLocation extends Location implements Serializable {
private static final long serialVersionUID = -7520724946566388839L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="physical_location_seq")
@Column(name = "id")
private int id;
@Column(name = "coord_x")
private int coordX;
@Column(name = "coord_y")
private int coordY;
@Column(name = "coord_z")
private int coordZ;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getCoordX() {
return coordX;
}
public void setCoordX(int coordX) {
this.coordX = coordX;
}
public int getCoordY() {
return coordY;
}
public void setCoordY(int coordY) {
this.coordY = coordY;
}
public int getCoordZ() {
return coordZ;
}
public void setCoordZ(int coordZ) {
this.coordZ = coordZ;
}
}
|
Java
|
UTF-8
| 85
| 1.890625
| 2
|
[] |
no_license
|
package videogames;
public interface TwoD {
int mapHeight();
int mapWidth();
}
|
Python
|
UTF-8
| 1,206
| 2.828125
| 3
|
[] |
no_license
|
"""
This script provides sending emails through a configured mailserver
"""
import smtplib
import datetime
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import config
def create_mail(recipient, content):
"""
Create Mail from content with all necessary Headers
Parameters
----------
recipient (str): email address of recipient
content (str): content of the email
Return:
-------
object: an instance of mail object
"""
date=datetime.datetime.now().date()
msg = MIMEMultipart()
msg['From']=config.MAIL_USER
msg['To']=recipient
msg['Subject']="DNA Center Report " + str(date)
msg.attach(MIMEText(content, 'plain'))
return msg
def send_mail(recipient, content):
"""
Send mail to defined recipient
Parameters
----------
recipient (str): email address of recipient
content (str): content of the email
"""
sender = smtplib.SMTP(host=config.MAIL_SERVER, port=config.MAIL_PORT)
sender.starttls()
sender.login(config.MAIL_USER, config.MAIL_PASSWORD)
sender.sendmail(config.MAIL_USER, recipient, create_mail(recipient, content).as_string())
sender.quit()
|
C++
|
UTF-8
| 1,417
| 2.953125
| 3
|
[] |
no_license
|
/*
* LightMaterial.h
*
* Created on: Sep 21, 2016
* Author: colin
*/
#ifndef LIGHTMATERIAL_H_
#define LIGHTMATERIAL_H_
#include "RGB.h"
#include "Singular.h"
class Light {
private:
RGB rgb = RGB(-1, -1, -1);
Point position = Point();
bool notAmbient = true;
public:
Light();
Light(double red, double green, double blue, double x, double y, double z, bool notAmbient);
RGB color() const { return rgb; }
double red() const { return rgb.red(); }
double green() const { return rgb.green(); }
double blue() const { return rgb.blue(); }
Point getPosition() const { return position; }
bool hasPosition() const { return notAmbient; }
RGB operator*(const double &scalar) const;
};
class Material {
private:
int mindex, begin, end;
double lambdaOne, lambdaTwo, lambdaThree;
double k, alpha, translucence;
bool null = false;
public:
Material();
Material(int, int, int, double, double, double, double, double, double);
Material(const Material &);
int model() const { return mindex; }
int beginning() const { return begin; }
int ending() const { return end; }
double lone() const { return lambdaOne; }
double ltwo() const { return lambdaTwo; }
double lthree() const {return lambdaThree; }
double rConst() const { return k; }
double shininess() const { return alpha; }
double translucency() const { return translucence; }
bool isNull() { return null; }
};
#endif /* LIGHTMATERIAL_H_ */
|
Java
|
UTF-8
| 3,844
| 2.875
| 3
|
[] |
no_license
|
package app;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import javax.swing.JPanel;
import model.Note;
class Piano extends JPanel {
private static final long serialVersionUID = 1L;
final App app;
private final PianoKey[] keys;
PianoKey cursorPos;
PianoKey pressedOn;
Piano(App app, int numKeys) {
this.app = app;
keys = new PianoKey[numKeys];
setLayout(new GridLayout(numKeys, 1));
rebuildKeys();
setPreferredSize(new Dimension(Const.KEY_SIZE.width, numKeys * Const.KEY_SIZE.height));
setMaximumSize(new Dimension(Const.KEY_SIZE.width, Integer.MAX_VALUE));
}
void rebuildKeys() {
removeAll();
for (int i = 0; i < keys.length; i++) {
add(keys[i] = new PianoKey(i, this), 0);
}
revalidate();
}
private List<Integer> getActiveKeys() {
List<Integer> indices = Arrays.stream(keys).filter(PianoKey::isActive).map(key -> key.index).collect(Collectors.toList());
Collections.sort(indices);
return indices;
}
void activateKeys(List<Integer> keys) {
keys.forEach(key -> this.keys[key].setActive(true));
}
boolean isPianoKeyBeingPressed() {
return pressedOn != null;
}
void moveChordUp() {
// Skip if a key is beign mouse pressed
if(isPianoKeyBeingPressed()) {
return;
}
List<Integer> indices = getActiveKeys();
if(indices.isEmpty()) {
return;
}
// Move the whole chord one semitone up
if(indices.get(indices.size() - 1) < keys.length - 1) {
indices.forEach(index -> keys[index].setActive(false));
indices.forEach(index -> keys[index + 1].setActive(true));
}
}
void moveChordDown() {
if(isPianoKeyBeingPressed()) {
return;
}
List<Integer> indices = getActiveKeys();
if(indices.isEmpty()) {
return;
}
if(indices.get(0) > 0) {
indices.forEach(index -> keys[index].setActive(false));
indices.forEach(index -> keys[index - 1].setActive(true));
}
}
void moveHighestKeyUp() {
if(isPianoKeyBeingPressed()) {
return;
}
List<Integer> indices = getActiveKeys();
if(indices.isEmpty()) {
return;
}
int highest = indices.get(indices.size() - 1);
if(highest < keys.length - 1) {
keys[highest].setActive(false);
keys[highest + 1].setActive(true);
}
}
void moveHighestKeyDown() {
if(isPianoKeyBeingPressed()) {
return;
}
List<Integer> indices = getActiveKeys();
if(indices.isEmpty()) {
return;
}
int highest = indices.get(indices.size() - 1);
// Move down the highest note without overlapping the lower one
if(indices.size() == 1 || highest > indices.get(indices.size() - 2) + 1) {
keys[highest].setActive(false);
keys[highest - 1].setActive(true);
}
}
void moveLowestKeyUp() {
if(isPianoKeyBeingPressed()) {
return;
}
List<Integer> indices = getActiveKeys();
if(indices.isEmpty()) {
return;
}
int lowest = indices.get(0);
if(indices.size() == 1 || lowest < indices.get(1) - 1) {
keys[lowest].setActive(false);
keys[lowest + 1].setActive(true);
}
}
void moveLowestKeyDown() {
if(isPianoKeyBeingPressed()) {
return;
}
List<Integer> indices = getActiveKeys();
if(indices.isEmpty()) {
return;
}
int lowest = indices.get(0);
if(lowest > 0) {
keys[lowest].setActive(false);
keys[lowest - 1].setActive(true);
}
}
List<Integer> grabActiveKeys() {
List<Integer> keys = new ArrayList<>();
// Grab active keys from piano then release them
Arrays.stream(this.keys).filter(PianoKey::isActive).forEach(key -> {
keys.add(key.index);
key.setActive(false);
});
return keys;
}
void playPress(Note note) {
playRelease();
note.forEach(key -> keys[key].playPress());
}
void playRelease() {
Arrays.stream(keys).forEach(key -> key.playRelease());
}
}
|
PHP
|
UTF-8
| 743
| 2.734375
| 3
|
[
"MIT",
"BSD-3-Clause"
] |
permissive
|
<?php
namespace AppBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
class ArchivierungsUpload
{
/**
* @Assert\NotBlank(message="Bitte Laden Sie die Archivierungsliste als CSV-Datei hoch.")
* @Assert\File(
* mimeTypes={ "application/csv", "text/csv", "application/vnd.ms-excel", "text/plain", "text/x-csv", "application/x-csv", "text/comma-separated-values", "text/x-comma-separated-values" },
* maxSize = "10M",
* mimeTypesMessage = "Bitte laden Sie eine valide CSV-Datei hoch.")
*/
private $csv;
public function getCsv()
{
return $this->csv;
}
public function setCsv($csv)
{
$this->csv = $csv;
return $this;
}
}
|
C#
|
UTF-8
| 5,156
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
using MathExpr.Syntax;
using System.Linq;
using MathExpr.Utilities;
namespace MathExprTests
{
public class ParserTests
{
[Fact]
public void TokenizeString()
{
var tokens = Tokenizer.Tokenize("a+b*c/d^ehij % k %( 3.442*ident) ^^ y & y \"haha this is a \\\" string literal &^\"" +
"# line comment\n #( block comment )# x #( multiline\nblock\ncomment )#");
var expect = new[]
{
new Token(TokenType.Identifier, "a", 0, 1),
new Token(TokenType.Plus, null, 1, 1),
new Token(TokenType.Identifier, "b", 2, 1),
new Token(TokenType.Star, null, 3, 1),
new Token(TokenType.Identifier, "c", 4, 1),
new Token(TokenType.Slash, null, 5, 1),
new Token(TokenType.Identifier, "d", 6, 1),
new Token(TokenType.Exponent, null, 7, 1),
new Token(TokenType.Identifier, "ehij", 8, 4),
new Token(TokenType.Percent, null, 14, 1),
new Token(TokenType.Identifier, "k", 16, 1),
new Token(TokenType.Percent, null, 18, 1),
new Token(TokenType.OpenParen, null, 19, 1),
new Token(TokenType.Literal, 3.442m, 21, 5),
new Token(TokenType.Star, null, 26, 1),
new Token(TokenType.Identifier, "ident", 27, 5),
new Token(TokenType.CloseParen, null, 32, 1),
new Token(TokenType.Xor, null, 34, 2),
new Token(TokenType.Identifier, "y", 37, 1),
new Token(TokenType.And, null, 39, 1),
new Token(TokenType.Identifier, "y", 41, 1),
new Token(TokenType.String, "haha this is a \" string literal &^", 43, 37),
new Token(TokenType.LineComment, "# line comment", 80, 14),
new Token(TokenType.BlockComment, "#( block comment )#", 94, 19),
new Token(TokenType.Identifier, "x", 115, 1),
new Token(TokenType.BlockComment, "#( multiline\nblock\ncomment )#", 118, 32),
};
foreach (var (actual, expected) in tokens.Zip(expect, Helpers.Tuple))
{
Assert.Equal(expected, actual);
}
}
[Theory]
[InlineData("a + b + c - 3 * d ^ e * (f - g)", true)]
[InlineData("a + b + c - 3 * d ^ e * (f - g", false)]
[InlineData("a + b + c - 3 * d ^ e * f - g)", false)]
[InlineData("a + b + c - 3 * d ^ e * {f - g)", false)]
[InlineData("a + b + c - 3 * d ^ e * f - g", true)]
[InlineData("a + b + c - 3 * d ^ e * f - g # line comment", true)]
[InlineData("a + b + c - 3 * d ^ e * f - g # line comment\n + h", true)]
[InlineData("a + b + c - 3 * d ^ e * f - g # line comment\n h", false)]
[InlineData("a + b + c - 3 * d ^ e * f - g #( line comment )# + h", true)]
[InlineData("a + b + c - 3 * d ^ e * f - g #( line comment )# h", false)]
[InlineData("a + b + c - 3 * d ^ e * f - g #( line comment ) h", false)]
[InlineData("a + b + c - 3 * d ^ e * f - g #( line comment ) + h", false)]
[InlineData("a+b*c/d^ehij % k %( 3.442*ident) ^^ y & y | A ~& b ~| c ~= d >= e", true)]
[InlineData("x = y + 2 ~^ y * 2 > z", true)]
[InlineData("func'(a, b) = 14.3 * a * b!", true)]
[InlineData("5!", true)]
[InlineData("-5!", true)]
[InlineData("(x+1)!", true)]
[InlineData("-(x+1)!", true)]
[InlineData("(x = y + 2 ~^ y * 2 > z) * (x+1)!", true)]
[InlineData("f'(x, y) = x^2 + y - 1; f'(2, 3 + z)^2", true)]
[InlineData("vec3(a, b, c).x", true)] // ideally this should be able to simplify to just 'a'
[InlineData("(vec3(a, b, c) * 13 + vec3(1,2,3)).z", true)]
[InlineData("\"Hello there!\"", true)]
[InlineData("\"Hello there!", false)]
[InlineData("\"Hello there!\\\"", false)]
[InlineData("1 | ", false)]
[InlineData("0 || 1", false)]
[InlineData("0 | 1", true)]
[InlineData("a'(x) = x*2; a + (b * c}", false, false)]
[InlineData("a'(x) = x * {2 + x); a + (b * c)", false, false)]
[InlineData("a'(x) = x * {2 + x); a + (b * c}", false, true)]
public void ParseString(string input, bool valid, bool throwsMulti = false)
{
try
{
_ = MathExpression.Parse(input);
Assert.True(valid, "Parser did not throw when it was supposed to");
}
catch (SyntaxException e)
{
_ = e.ToString();
Assert.False(valid, "Parser threw when it was not supposed to");
Assert.False(throwsMulti, "Parser threw one error when it should have thrown multiple");
}
catch (AggregateException e)
{
_ = e.ToString();
Assert.True(throwsMulti, "Parser threw multiple errors when it should not have");
}
}
}
}
|
Java
|
UTF-8
| 5,186
| 2.140625
| 2
|
[] |
no_license
|
package com.ths.domain;
import java.math.BigDecimal;
import java.util.Date;
/**
*
* 同花顺的概念个股数据
*
**/
public class StockThsGnInfo implements java.io.Serializable {
private static final long serialVersionUID = 1L;
/****/
private Long id;
/**概念名**/
private String gnName;
/**概念的code**/
private String gnCode;
/**股票code**/
private String stockCode;
/**股票名**/
private String stockName;
/**现价**/
private BigDecimal stockPrice;
/**涨跌幅(单位百分比:%)**/
private BigDecimal stockChange;
/**涨跌价格**/
private BigDecimal stockChangePrice;
/**涨跌速(单位百分比:%)**/
private BigDecimal stockChangeSpeed;
/**换手率(单位百分比:%)**/
private BigDecimal stockHandoverScale;
/**量比**/
private BigDecimal stockLiangBi;
/**振幅(单位百分比:%)**/
private BigDecimal stockAmplitude;
/**成交额(单位:万)**/
private BigDecimal stockDealAmount;
/**流通股票量(单位:万)**/
private BigDecimal stockFlowStockNumber;
/**流通市值(单位:万)**/
private BigDecimal stockFlowMakertValue;
/**市盈率**/
private BigDecimal stockMarketTtm;
/**发起抓取时间**/
private String crawlerTime;
/**当前抓取的版本**/
private String crawlerVersion;
/**扩展数据**/
private String someExt;
/****/
private Date createTime;
/****/
private Date updateTime;
public void setId(Long id) {
this.id = id;
}
public Long getId() {
return this.id;
}
public void setGnName(String gnName) {
this.gnName = gnName;
}
public String getGnName() {
return this.gnName;
}
public void setGnCode(String gnCode) {
this.gnCode = gnCode;
}
public String getGnCode() {
return this.gnCode;
}
public void setStockCode(String stockCode) {
this.stockCode = stockCode;
}
public String getStockCode() {
return this.stockCode;
}
public void setStockName(String stockName) {
this.stockName = stockName;
}
public String getStockName() {
return this.stockName;
}
public void setStockPrice(BigDecimal stockPrice) {
this.stockPrice = stockPrice;
}
public BigDecimal getStockPrice() {
return this.stockPrice;
}
public void setStockChange(BigDecimal stockChange) {
this.stockChange = stockChange;
}
public BigDecimal getStockChange() {
return this.stockChange;
}
public void setStockChangePrice(BigDecimal stockChangePrice) {
this.stockChangePrice = stockChangePrice;
}
public BigDecimal getStockChangePrice() {
return this.stockChangePrice;
}
public void setStockChangeSpeed(BigDecimal stockChangeSpeed) {
this.stockChangeSpeed = stockChangeSpeed;
}
public BigDecimal getStockChangeSpeed() {
return this.stockChangeSpeed;
}
public void setStockHandoverScale(BigDecimal stockHandoverScale) {
this.stockHandoverScale = stockHandoverScale;
}
public BigDecimal getStockHandoverScale() {
return this.stockHandoverScale;
}
public void setStockLiangBi(BigDecimal stockLiangBi) {
this.stockLiangBi = stockLiangBi;
}
public BigDecimal getStockLiangBi() {
return this.stockLiangBi;
}
public void setStockAmplitude(BigDecimal stockAmplitude) {
this.stockAmplitude = stockAmplitude;
}
public BigDecimal getStockAmplitude() {
return this.stockAmplitude;
}
public void setStockDealAmount(BigDecimal stockDealAmount) {
this.stockDealAmount = stockDealAmount;
}
public BigDecimal getStockDealAmount() {
return this.stockDealAmount;
}
public void setStockFlowStockNumber(BigDecimal stockFlowStockNumber) {
this.stockFlowStockNumber = stockFlowStockNumber;
}
public BigDecimal getStockFlowStockNumber() {
return this.stockFlowStockNumber;
}
public void setStockFlowMakertValue(BigDecimal stockFlowMakertValue) {
this.stockFlowMakertValue = stockFlowMakertValue;
}
public BigDecimal getStockFlowMakertValue() {
return this.stockFlowMakertValue;
}
public void setStockMarketTtm(BigDecimal stockMarketTtm) {
this.stockMarketTtm = stockMarketTtm;
}
public BigDecimal getStockMarketTtm() {
return this.stockMarketTtm;
}
public void setCrawlerTime(String crawlerTime) {
this.crawlerTime = crawlerTime;
}
public String getCrawlerTime() {
return this.crawlerTime;
}
public void setCrawlerVersion(String crawlerVersion) {
this.crawlerVersion = crawlerVersion;
}
public String getCrawlerVersion() {
return this.crawlerVersion;
}
public void setSomeExt(String someExt) {
this.someExt = someExt;
}
public String getSomeExt() {
return this.someExt;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getCreateTime() {
return this.createTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Date getUpdateTime() {
return this.updateTime;
}
}
|
C#
|
UTF-8
| 3,893
| 3.109375
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LinqDemo
{
class Program
{
static void Main(string[] args)
{
DataTable dt = ToSql.CreateDataTable();
ToSql.QueryByName(dt);
ToSql.OrderByAgeDesc(dt);
LinqWhere.Query();
LinqWhere.QueryLambda();
Console.Read();
}
}
public class ToSql
{
/// <summary>
/// 构造datatable
/// </summary>
/// <returns></returns>
public static DataTable CreateDataTable()
{
using (DataTable dt = new DataTable("student"))
{
DataColumn dcname = new DataColumn("name", typeof(string));
dt.Columns.Add(dcname);
DataColumn dcage = new DataColumn("age", typeof(int));
dt.Columns.Add(dcage);
DataColumn dcsex = new DataColumn("sex", typeof(bool));
dt.Columns.Add(dcsex);
DataColumn dcaddress = new DataColumn("address", typeof(string));
dt.Columns.Add(dcaddress);
DataRow dr = dt.NewRow();
dr["name"] = "a";
dr["age"] = 20;
dr["sex"] = false;
dr["address"] = "苏州";
dt.Rows.Add(dr);
DataRow dr2 = dt.NewRow();
dr2["name"] = "b";
dr2["age"] = 18;
dr2["sex"] = false;
dr2["address"] = "上海";
dt.Rows.Add(dr2);
DataRow dr3 = dt.NewRow();
dr3["name"] = "c";
dr3["age"] = 19;
dr3["sex"] = true;
dr3["address"] = "无锡";
dt.Rows.Add(dr3);
DataRow dr4 = dt.NewRow();
dr4["name"] = "d";
dr4["age"] = 18;
dr4["sex"] = true;
dr4["address"] = "杭州";
dt.Rows.Add(dr4);
DataRow dr5 = dt.NewRow();
dr5["name"] = "e";
dr5["age"] = 17;
dr5["sex"] = false;
dr5["address"] = "宜兴";
dt.Rows.Add(dr5);
return dt;
}
}
/// <summary>
/// 根据名字查询
/// </summary>
/// <param name="dt"></param>
public static void QueryByName(DataTable dt)
{
var rows = from dr in dt.AsEnumerable() where dr.Field<string>("name") == "a" select dr;
//获取名字
var list = from dr in rows select dr["name"].ToString();
foreach (var item in list)
{
Console.WriteLine(item);
}
}
/// <summary>
/// 根据年龄倒序
/// </summary>
/// <param name="dt"></param>
public static void OrderByAgeDesc(DataTable dt)
{
var rows = from dr in dt.AsEnumerable() orderby dr.Field<int>("age"),dr.Field<string>("name") descending select dr;
var listage = from row in rows select int.Parse(row["age"].ToString());
StringBuilder sb = new StringBuilder();
foreach (var item in listage)
{
sb.Append(item+" ");
}
sb.Append("\r\n");
var listname = from row in rows select row["name"].ToString();
foreach (var item in listname)
{
sb.Append(item + " ");
}
Console.WriteLine(sb);
}
}
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
public bool Sex { get; set; }
public string Address { get; set; }
}
}
|
Markdown
|
UTF-8
| 2,565
| 2.65625
| 3
|
[] |
no_license
|
# Circuito
El circuito consiste en una lona blanca de PVC con una o dos líneas negras que indican la trayectoria que debe seguir el robot. Estas líneas al mismo tiempo se utilizarán como guías que el robot podrá leer para conocer su posición. La utilización de una o dos líneas en el trazado queda a elección de la organización del evento, pudiendo no desvelarse hasta el día de la competición.
La trayectoria definida por las líneas será cerrada, es decir, el punto de inicio y el punto de meta serán el mismo.
Las líneas negras tendrán un grosor de **20±2 mm**, y habrá una separación entre sus centros de **20±1 cm**. Las curvas tendrán un radio mínimo de **40±2 cm**. Entre el borde exterior de la lona y el trazado habrá un margen mínimo libre de obstáculos de al menos **10 cm**, al igual que la separación mínima que ha de haber entre el trazado y cualquier obstáculo o impresión (ya sea publicidad o no) en la lona, siendo blanco homogéneo el fondo sobre el que se sitúa el trazado.
En dos zonas del trazado se situarán marcas de salida a ambos lados del recorrido, separadas **10 cm** de las líneas a seguir. Estos dos puntos de salida dividirán el recorrido en dos partes igual de largas, de tal manera que ninguno de los dos robots que compiten en modo persecución tenga ventaja uno sobre el otro, saliendo cada uno desde detrás de una de las líneas de salida.
En el caso de existir elementos tridimensionales tales como curvas peraltadas, puentes, cambios de rasante... etc, se avisará a los participantes antes de la prueba. Adicionalmente, estos elementos serán lisos, sin escalones, y no presentarán inclinaciones mayores de **25º**
La superficie de la pista podrá presentar pequeñas irregularidades, aunque se intentará que sea lo más lisa posible. Además, la pista podrá estar iluminada con diferentes niveles de luminosidad, pero se intentará que la iluminación no sea agresiva y esté distribuída de forma uniforme a lo largo de todo el circuito. No se garantiza la no exitencia de flashes u otras perturbaciones lumínicas provocadas por el público en ocasiones puntuales. Adicionalmente, se procurará que la pista se mantenga lo más limpia posible durante el desarrollo de la competición, pudiendo llegar a penalizar a los participantes que pisen y/o encucien las líneas.
A continuación se muestra un trazado de ejemplo para una competición de velocistas:
<p align="center"><img src="https://raw.githubusercontent.com/Resaj/basic-circuit-maker/master/images/circuito.bmp"></p>
|
Java
|
UTF-8
| 714
| 2.953125
| 3
|
[] |
no_license
|
package ru.zvezdov.ocprof.chapter_4.FunctionalProgramming.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Created by Dmitry on 26.06.2017.
*/
public class _5_Collectors_groupingBy {
public static void main(String[] args) {
List<String> list = Arrays.asList("j", " ", "a", "v", "a", " " , "!");
// Map<Integer, List<String>> collect = list.stream().collect(Collectors.groupingBy(String::length));
Map<Integer, List<String>> collect = list.stream().collect(Collectors.groupingBy(String::length, Collectors.mapping(o -> {return o.toUpperCase();}, Collectors.toList())));
System.out.println(collect);
}
}
|
Markdown
|
UTF-8
| 24,707
| 3.875
| 4
|
[] |
no_license
|
#PROGRAMING FOR PROBLEM SOLVING LAB PRACTICAL
#MY PROGRAMS
##My Details:-
**Name-** Gurjot Singh
**CRN-** 1915025
**Branch-** Cse
**Year-** 1st
**Submitted to-** prof. Hardeep Singh Kang
####1. Hello Budding Engineers
#include<stdio.h>
int main()
{
puts("Hello Budding Engineers\n");
return 0;
}
##### OUTPUT:
>Hello Budding Engineers
####2. Address using puts
#include<stdio.h>
int main()
{
puts("My address:");
puts(Halwara,Ludhiana,Punjab, India");
return 0;
}
#####OUTPUT:
>My address:
Halwara,Ludhiana, Punjab, India
####3. Sum of two numbers
#include<stdio.h>
int main()
{
int a, b, sum;
printf("Enter two numbers\n");
scanf("%d %d",&a,&b);
sum=a+b;
printf("sum=%d\n",sum);
return 0;
}
#####OUTPUT:
>Enter two numbers
12
26
sum=38
####4. Convert Celsius to Fahrniet
#include<stdio.h>
int main()
{
float fahr, cel;
printf("Enter the temperature in celsius: ");
scanf("%f", &cel);
fahr = (1.8 * cel) + 32.0;
printf("\nTemperature in Fahrenheit: %.2f F\n", fahr);
return 0;
}
#####OUTPUT:
>Enter the temperature in celsius: 32
>
>Temperature in Fahrenheit: 89.60 F
####5. Multiplication Table
#include<stdio.h>
int main()
{
int num,n, i,table;
printf("Enter a number");
scanf("%d",&num);
printf("Enter the number upto which you wanna see the table\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
table=0;
table=num*i;
printf("%d*%d=%d\n",num,i,table);
}
return 0;
}
#####OUTPUT:
>Enter a number 7
Enter the number upto which you wanna see the table
10
7*1=7
7*2=14
7*3=21
7*4=28
7*5=35
7*6=42
7*7=49
7*8=56
7*9=63
7*10=70
####6. Perimeter and area of circle
#include<stdio.h>
#define PI 3.14
int main()
{
float radius,area,peri;
printf("Enter the radius of circle\n");
scanf("%f",&radius);
area=PI*radius*radius;
peri=2*PI*radius;
printf("Area of the circle=%f\n",area);
printf("Perimeter of the circle=%f\n",peri);
return 0;
}
#####OUTPUT:
>Enter the radius of circle
>5
>Area of the circle=78.500000
>Perimeter of the circle=31.400000
####7. Reverse
#include <stdio.h>
int main()
{
int n, reversedNumber = 0, remainder;
printf("Enter an integer: ");
scanf("%d", &n);
while(n != 0)
{
remainder = n%10;
reversedNumber = reversedNumber*10 + remainder;
n /= 10;
}
printf("Reversed Number = %d", reversedNumber);
return 0;
}
#####OUTPUT:
>Enter an integer: 1356
>Reversed Number = 6531
####8. Swapping without using a third variable
#include <stdio.h>
int main()
{
int x, y, t;
printf("Enter two integers\n");
scanf("%d%d", &x, &y);
printf("Before Swapping\nFirst integer = %d\nSecond integer = %d\n", x, y);
t = x;
x = y;
y = t;
printf("After Swapping\nFirst integer = %d\nSecond integer = %d\n", x, y);
return 0;
}
#####OUTPUT:
>Enter an integer: 1356
>Reversed Number = 6531
####9. Even Odd
#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d", &number);
if(number % 2 == 0)
printf("%d is even.", number);
else
printf("%d is odd.", number);
return 0;
}
#####OUTPUT:
> Enter an integer: 13
>13 is odd.
####10. Factorial
#include<stdio.h>
int main()
{
int i,fact=1,number;
printf("Enter a number: ");
scanf("%d",&number);
for(i=1;i<=number;i++){
fact=fact*i;
}
printf("Factorial of %d is: %d",number,fact);
return 0;
}
#####OUTPUT:
>Enter a number: 3
>Factorial of 3 is: 6
####11. Weekdays using switch case
#include <stdio.h>
int main()
{
int week;
printf("Enter week number(1-7): ");
scanf("%d", &week);
switch(week)
{
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
case 7:
printf("Sunday");
break;
default:
printf("Invalid input! Please enter week number between 1-7.");
}
return 0;
}
#####OUTPUT:
>Enter week number(1-7): 4
>Thursday
####12. Arithmetic operations using switch case
#include<stdio.h>
void main()
{
int a,b;
int op;
printf(" 1.Addition\n 2.Subtraction\n 3.Multiplication\n 4.Division\n");
printf("Enter the values of a & b: ");
scanf("%d %d",&a,&b);
printf("Enter your Choice : ");
scanf("%d",&op);
switch(op)
{
case 1 :
printf("Sum of %d and %d is : %d",a,b,a+b);
break;
case 2 :
printf("Difference of %d and %d is : %d",a,b,a-b);
break;
case 3 :
printf("Multiplication of %d and %d is : %d",a,b,a*b);
break;
case 4 :
printf("Division of Two Numbers is %d : ",a/b);
break;
default :
printf(" Enter Your Correct Choice.");
break;
}
}
#####OUTPUT:
> 1.Addition
>2.Subtraction
>3.Multiplication
>4.Division
>Enter the values of a & b: 12
>76
>Enter your Choice : 3
>Multiplication of 12 and 76 is : 912
####13. Prime Numbers
#include <stdio.h>
int main()
{
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
for(i = 2; i <= n/2; ++i)
{
if(n%i == 0)
{
flag = 1;
break;
}
}
if (n == 1)
{
printf("1 is neither a prime nor a composite number.");
}
else
{
if (flag == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);
}
return 0;
}
#####OUTPUT:
>Enter a positive integer: 13
>13 is a prime number.
####14. Fibonacci Series
#include <stdio.h>
int main()
{
int prev=0;
int curr=1;
int n;
int next,a;
printf("Enter the number of terms\n");
scanf("%d", &n);
printf("First %d terms of Fibonacci series are:\n",n);
for (a = 0; a < n; a++)
{
if (a <= 1)
next = a;
else
{
next = prev + curr;
prev = curr;
curr = next;
}
printf("%d\n", next);
}
return 0;
}
#####OUTPUT:
>Enter the number of terms
>8
>First 8 terms of Fibonacci series are:
>0
>1
>1
>2
>3
>5
>8
>13
####15. Palindrome
#include <stdio.h>
int main()
{
int n, reversedInteger = 0, remainder, originalInteger;
printf("Enter an integer: ");
scanf("%d", &n);
originalInteger = n;
while( n!=0 )
{
remainder = n%10;
reversedInteger = reversedInteger*10 + remainder;
n /= 10;
}
if (originalInteger == reversedInteger)
printf("%d is a palindrome.", originalInteger);
else
printf("%d is not a palindrome.", originalInteger);
return 0;
}
#####OUTPUT:
>Enter an integer: 12321
>12321 is a palindrome.
####16. Palindrome words
#include <stdio.h>
#include <string.h>
void check(char [], int);
int main()
{
char word[15];
printf("Enter a word to check if it is a palindrome\n");
scanf("%s", word);
check(word, 0);
return 0;
}
void check(char word[], int index)
{
int len = strlen(word) - (index + 1);
if (word[index] == word[len])
{
if (index + 1 == len || index == len)
{
printf("The entered word is a palindrome\n");
return;
}
check(word, index + 1);
}
else
{
printf("The entered word is not a palindrome\n");
}
}
#####OUTPUT:
>Enter a word to check if it is a palindrome
>naman
>The entered word is a palindrome
####17. Star Half Pyramid
#include <stdio.h>
int main()
{
int x, y, rows;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(x=1; x<=rows; ++x)
{
for(y=1; y<=x; ++y)
{
printf("* ");
}
printf("\n");
}
return 0;
}
#####OUTPUT:
> Enter number of rows: 5
> *
> * *
> * * *
> * * * *
> * * * * *
####18. Star Full Pyramid
#include <stdio.h>
int main()
{
int i, j, rows;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=rows; i>=1; --i)
{
for(j=1; j<=i; ++j)
{
printf("%d ",j);
}
printf("\n");
}
return 0;
}
#####OUTPUT:
>Enter number of rows: 8
> *
> * * *
> * * * * *
> * * * * * * *
> * * * * * * * * *
> * * * * * * * * * * *
> * * * * * * * * * * * * *
>* * * * * * * * * * * * * * *
####19. Star Inverted Half Pyramid
#include <stdio.h>
int main()
{
int i, j, rows;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=rows; i>=1; --i)
{
for(j=1; j<=i; ++j)
{
printf("* ");
}
printf("\n");
}
return 0;
}
#####OUTPUT:
>Enter number of rows: 4
>* * * *
>* * *
>* *
>*
####20. 1D Array
#include <stdio.h>
void main()
{
int arr[10];
int i;
printf("\n\nRead and Print elements of an array:\n");
printf("-----------------------------------------\n");
printf("Input 10 elements in the array :\n");
for(i=0; i<10; i++)
{
printf("element - %d : ",i);
scanf("%d", &arr[i]);
}
printf("\nElements in array are: ");
for(i=0; i<10; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}
#####OUTPUT:
> Read and Print elements of an array:
>-----------------------------------------
>Input 10 elements in the array :
>element - 0 : 1
>element - 1 : 3
>element - 2 : 4
>element - 3 : 2
>element - 4 : 6
>element - 5 : 8
>element - 6 : 5
>element - 7 : 7
>element - 8 : 0
>element - 9 : 9
>
>Elements in array are: 1 3 4 2 6 8 5 7 0 9
####21. Maximum Size of an array
#include <stdio.h>
#define MAX_SIZE 100 // Maximum array size
int main()
{
int arr[MAX_SIZE];
int size, i, toSearch, found;
printf("Enter size of array: ");
scanf("%d", &size);
printf("Enter elements in array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}
printf("\nEnter element to search: ");
scanf("%d", &toSearch);
for(i=0; i<size; i++)
{
if(arr[i] == toSearch)
{
found = 1;
break;
}
}
if(found == 1)
{
printf("\n%d is found at position %d", toSearch, i + 1);
}
else
{
printf("\n%d is not found in the array", toSearch);
}
return 0;
}
#####OUTPUT:
>Enter the number of elements in array
>4
>Enter 4 integers
>2
>4
>0
>9
>Maximum element is present at location 4 and it's value is 9.
####22. 2D Array
#include<stdio.h>
int main(){
/* 2D array declaration*/
int disp[2][3];
/*Counter variables for the loop*/
int i, j;
for(i=0; i<2; i++) {
for(j=0;j<3;j++) {
printf("Enter value for disp[%d][%d]:", i, j);
scanf("%d", &disp[i][j]);
}
}
printf("Two Dimensional array elements:\n");
for(i=0; i<2; i++) {
for(j=0;j<3;j++) {
printf("%d ", disp[i][j]);
if(j==2){
printf("\n");
}
}
}
return 0;
}
#####OUTPUT:
>Enter value for disp[0][0]:2
>Enter value for disp[0][1]:3
>Enter value for disp[0][2]:2
>Enter value for disp[1][0]:3
>Enter value for disp[1][1]:4
>Enter value for disp[1][2]:2
>Two Dimensional array elements:
>2 3 2
>3 4 2
####23. Sum of two matrices
#include <stdio.h>
int main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter the elements of second matrix\n");
for (c = 0; c < m; c++)
for (d = 0 ; d < n; d++)
scanf("%d", &second[c][d]);
printf("Sum of entered matrices:-\n");
for (c = 0; c < m; c++) {
for (d = 0 ; d < n; d++) {
sum[c][d] = first[c][d] + second[c][d];
printf("%d\t", sum[c][d]);
}
printf("\n");
}
return 0;
}
#####OUTPUT:
>Enter the number of rows and columns of matrix
>2
>3
>Enter the elements of first matrix
>1
>2
>3
>6
>4
>8
>Enter the elements of second matrix
>2
>4
>7
>2
>5
>7
>Sum of entered matrices:-
>3 6 10
>8 9 15
####24. Transpose of matrix
#include<stdio.h>
void main()
{
int a[10][10], b[10][10];
int m,n,i,j;
printf("Enter size of matrix A as m, n:");
scanf("%d%d",&m,&n);
printf("\n Enter elements of matrix A row wise\n",m ,n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
b[j][i]=a[i][j];
}
}
printf("\n\nTranspose of matrix is:\n");
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
printf("%d",b[i][j]);
}
}
}
#####OUTPUT:
>Enter size of matrix A as m, n:3
>2
>
>Enter elements of matrix A row wise
>1
>4
>2
>5
>7
>9
>
>
>Transpose of matrix is:
>127459
####25. Substraction of two matrices
#include <stdio.h>
int main()
{
int m, n, c, d, first[10][10], second[10][10], difference[10][10];
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");
for (c = 0; c < m; c++)
for (d = 0 ; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter the elements of second matrix\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &second[c][d]);
printf("Difference of entered matrices:-\n");
for (c = 0; c < m; c++) {
for (d = 0; d < n; d++) {
difference[c][d] = first[c][d] - second[c][d];
printf("%d\t",difference[c][d]);
}
printf("\n");
}
return 0;
}
#####OUTPUT:
>Enter the number of rows and columns of matrix
>2
>2
>Enter the elements of first matrix
>3
>2
>4
>5
>Enter the elements of second matrix
>
>7
>9
>0
>2
>Difference of entered matrices:-
>-4 -7
>4 3
####26. Multiplication of two matrices
#include <stdio.h>
int main()
{
int m, n, p, q, c, d, k, sum = 0;
int first[10][10], second[10][10], multiply[10][10];
printf("Enter number of rows and columns of first matrix\n");
scanf("%d%d", &m, &n);
printf("Enter elements of first matrix\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter number of rows and columns of second matrix\n");
scanf("%d%d", &p, &q);
if (n != p)
printf("The matrices can't be multiplied with each other.\n");
else
{
printf("Enter elements of second matrix\n");
for (c = 0; c < p; c++)
for (d = 0; d < q; d++)
scanf("%d", &second[c][d]);
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++) {
for (k = 0; k < p; k++) {
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
sum = 0;
}
}
printf("Product of the matrices:\n");
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++)
printf("%d\t", multiply[c][d]);
printf("\n");
}
}
return 0;
}
#####OUTPUT:
>Enter number of rows and columns of first matrix
>2
>2
>Enter elements of first matrix
>23
>65
>98
>10
>Enter number of rows and columns of second matrix
>2
>2
>Enter elements of second matrix
>54
>60
>0
>160
>Product of the matrices:
>1242 11780
>5292 7480
>
####27. Square of a number using function
#include<stdio.h>
int square(int); // function prototype declaration.
void main()
{
int number, answer;
printf("Enter your number:");
scanf("%d", &number);
answer = square(number); //Call function.
printf("Square of %d is %d.", number, answer);
}
int square(int n)
{
return(n*n);
}
#####OUTPUT:
>Enter your number:6
>Square of 6 is 36.
####28. Swaping call by value
#include <stdio.h>
void swap(int, int);
int main()
{
int x, y;
printf("Enter the value of x and y\n");
scanf("%d%d",&x,&y);
printf("Before Swapping\nx = %d\ny = %d\n", x, y);
swap(x, y);
printf("After Swapping\nx = %d\ny = %d\n", x, y);
return 0;
}
void swap(int a, int b)
{
int temp;
temp = b;
b = a;
a = temp;
printf("Values of a and b is %d %d\n",a,b);
}
#####OUTPUT:
>Enter the value of x and y
>5
>8
>Before Swapping
>x = 5
>y = 8
>Values of a and b is 8 5
>After Swapping
>x = 5
>y = 8
>
####29. Swapping call by reference
#include <stdio.h>
void swap(int *n1, int *n2);
int main()
{
int num1, num2;
printf("Enter the num1 and num2");
scanf("%d%d",&num1,&num2);
swap( &num1, &num2);
printf("num1 = %d\n", num1);
printf("num2 = %d", num2);
return 0;
}
void swap(int* n1, int* n2)
{
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;
}
#####OUTPUT:
>Enter the num1 and num2
>3
>5
>num1 = 5
>num2 = 3
####30. Factorial using recursion
#include<stdio.h>
int main()
{
#include <stdio.h>
long int multiplyNumbers(int n);
int main()
{
int n;
printf("Enter a positive integer: ");
scanf("%d", &n);
printf("Factorial of %d = %ld", n, multiplyNumbers(n));
return 0;
}
long int multiplyNumbers(int n)
{
if (n >= 1)
return n*multiplyNumbers(n-1);
else
return 1;
}
#####OUTPUT:
>Enter a positive integer: 5
>Factorial of 5 = 120
####31. Fibonacci series using recursion
#include<stdio.h>
int Fibonacci(int);
int main()
{
int n, i = 0, c;
scanf("%d",&n);
printf("Fibonacci series\n");
for ( c = 1 ; c <= n ; c++ )
{
printf("%d\n", Fibonacci(i));
i++;
}
return 0;
}
int Fibonacci(int n)
{
if ( n == 0 )
return 0;
else if ( n == 1 )
return 1;
else
return ( Fibonacci(n-1) + Fibonacci(n-2) );
}
#####OUTPUT:
>4
>Fibonacci series
>0
>1
>1
>2
>
####32. Structure
#include <stdio.h>
struct student
{
char name[50];
int roll;
float marks;
} s[10];
int main()
{
int i;
printf("Enter information of students:\n");
// storing information
for(i=0; i<10; ++i)
{
s[i].roll = i+1;
printf("\nFor roll number%d,\n",s[i].roll);
printf("Enter name: ");
scanf("%s",s[i].name);
printf("Enter marks: ");
scanf("%f",&s[i].marks);
printf("\n");
}
printf("Displaying Information:\n\n");
// displaying information
for(i=0; i<10; ++i)
{
printf("\nRoll number: %d\n",i+1);
printf("Name: ");
puts(s[i].name);
printf("Marks: %.1f",s[i].marks);
printf("\n");
}
return 0;
}
#####OUTPUT:
>Roll number: 5
>Name: bhola
>Marks: 32.0
>
>Roll number: 6
>Name: kaka
>Marks: 66.0
>
>Roll number: 7
>Name: billa
>Marks: 100.0
>
>Roll number: 8
>Name: john
>Marks: 89.0
>
>Roll number: 9
>Name: jacky
>Marks: 38.0
>
>Roll number: 10
>Name: Blacky
>Marks: 42.0
####33. Pointers
#include<stdio.h>
int main()
{
int a,*p;
a=10;
p=&a;
printf("%d\n",p);
printf("%d\n",*p);
printf("%d\n",&p);
return 0;
}
#####OUTPUT:
>-1306961924
>10
>-1306961936
####34. Addition using Pointers
#include <stdio.h>
int main()
{
int first, second, *p, *q, sum;
printf("Enter two integers to add\n");
scanf("%d%d", &first, &second);
p = &first;
q = &second;
sum = *p + *q;
printf("Sum of the numbers = %d\n", sum);
return 0;
}
#####OUTPUT:
>Enter two integers to add
>4
>65
>Sum of the numbers = 69
>
####35. Pointers to an array
#include<stdio.h>
int main()
{
int arr[5] = { 1, 2, 3, 4, 5 };
int *ptr = arr;
printf("%p\n", ptr);
return 0;
}
#####OUTPUT:
>0x7ffd4b542230
####36. Pointers to a function
#include <stdio.h>
void fun(int a)
{
printf("Value of a is %d\n", a);
}
int main()
{
void (*fun_ptr)(int) = fun;
fun_ptr(10);
return 0;
}
#####OUTPUT:
>Value of a is 10
####37. Printing values of an array using pointers
#include<stdio.h>
void main()
{
int a[5]= {5,4,6,8,9};
int *p=&a[0];
int i;
for(i=0; i<5; i++)
printf("\nArray[%d] is %d ",i,*(p+i));
for(i=0; i<5; i++)
printf("\n %d at %u ",*(p+i),(p+i));
}
#####OUTPUT:
>Enter two integers to add
>58
>94
>Sum of the numbers = 152
####38. Bubble Sort
#include <stdio.h>
int main()
{
int array[100], n, c, d, swap;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
for (c = 0 ; c < n - 1; c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1]) /* For decreasing order use < */
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
printf("Sorted list in ascending order:\n");
for (c = 0; c < n; c++)
printf("%d\n", array[c]);
return 0;
}
#####OUTPUT:
>Enter number of elements
>5
>Enter 5 integers
>23
>4
>54
>87
>98
>Sorted list in ascending order:
>4
>23
>54
>87
>98
####39. Quick Sort Using Recursion
#include <stdio.h>
void quicksort (int [], int, int);
int main()
{
int list[50];
int size, i;
printf("Enter the number of elements: ");
scanf("%d", &size);
printf("Enter the elements to be sorted:\n");
for (i = 0; i < size; i++)
{
scanf("%d", &list[i]);
}
quicksort(list, 0, size - 1);
printf("After applying quick sort\n");
for (i = 0; i < size; i++)
{
printf("%d ", list[i]);
}
printf("\n");
return 0;
}
void quicksort(int list[], int low, int high)
{
int pivot, i, j, temp;
if (low < high)
{
pivot = low;
i = low;
j = high;
while (i < j)
{
while (list[i] <= list[pivot] && i <= high)
{
i++;
}
while (list[j] > list[pivot] && j >= low)
{
j--;
}
if (i < j)
{
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
temp = list[j];
list[j] = list[pivot];
list[pivot] = temp;
quicksort(list, low, j - 1);
quicksort(list, j + 1, high);
}
}
#####OUTPUT:
> Enter the number of elements: 5
>Enter the elements to be sorted:
>45
>32
>76
>455
>34
>After applying quick sort
>32 34 45 76 455
|
Python
|
UTF-8
| 657
| 2.671875
| 3
|
[] |
no_license
|
import datetime
import re
import matplotlib.pyplot as plt
NUM_PACKS_TO_REACH = 100000
PYPI = 'https://pypi.python.org/pypi'
DATA = './data.txt'
if __name__ == "__main__":
dates = []
counts = []
re_pattern = re.compile(r'(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2}):(\d+)')
with open(DATA) as data_file:
for line in data_file:
year, month, day, hour, minute, second, count = map(int, re_pattern.match(line).groups())
dates.append(datetime.datetime(year, month, day,
hour, minute, second))
counts.append(count)
plt.plot(dates, counts)
plt.show()
|
C#
|
UTF-8
| 3,018
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ProjetoForm1
{
public partial class Atividade7 : Form
{
public Atividade7()
{
InitializeComponent();
}
private void Atividade7_Load(object sender, EventArgs e)
{
}
private void Atividade7_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("Você realmente deseja sair?", "Deseja sair?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
Application.ExitThread();
}
else
{
e.Cancel = true;
}
}
private void button2_Click(object sender, EventArgs e)
{
Menu menu = new Menu();
menu.Show();
this.Hide();
}
private void button1_Click(object sender, EventArgs e)
{
TimeSpan t1;
int idade;
string dt_2;
DateTime dt_incio, dt_atual;
dt_incio = DateTime.Parse(monthCalendar1.SelectionStart.ToShortDateString());
dt_atual = DateTime.Now;
lbl_dtatual.Text = dt_atual.ToShortDateString();
dt_2 = dt_incio.AddDays(int.Parse(txt_da.Text)).ToShortDateString();
if (dt_atual > dt_incio)
{
t1 = dt_atual - dt_incio;
}
else
{
t1 = dt_incio - dt_atual;
}
DateTime datanasc = DateTime.Parse(txt_datanasc.Text);
if(datanasc.DayOfYear <= dt_atual.DayOfYear)
{
idade = dt_atual.Year - datanasc.Year;
}
else
{
idade = dt_atual.Year - datanasc.Year - 1;
}
MessageBox.Show("Data nova: " + dt_2, "Data nova", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessageBox.Show("Idade: " + idade.ToString(), "Idade", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
{
DateTime dt_atual = DateTime.Now;
DateTime selected = monthCalendar1.SelectionRange.Start;
lbl_dtatual.Text = dt_atual.ToShortDateString();
if (dt_atual < selected)
{
int difference = selected.DayOfYear - dt_atual.DayOfYear;
lbl_difference.Text = difference + " dias";
}
else
{
int difference = dt_atual.DayOfYear - selected.DayOfYear;
lbl_difference.Text = difference + "dias";
}
}
}
}
|
C++
|
UTF-8
| 520
| 3.015625
| 3
|
[] |
no_license
|
#include "graph_helper.h"
namespace GraphHelper
{
UndirectedGraph<> createLinearGraph(int nVertices)
{
UndirectedGraph<> result( nVertices );
for (int i = 0; i < nVertices - 1; ++i)
result.add_edge(i, i + 1);
return result;
}
UndirectedGraph<> createSimpleCycleGraph( int nVertices )
{
UndirectedGraph<> result( nVertices );
for (int i = 0; i < nVertices; ++i)
result.add_edge(i, (i + 1) % nVertices);
return result;
}
}
|
Java
|
UTF-8
| 379
| 1.8125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.github.devmix.sample.undertow.microservice.core;
import org.glassfish.jersey.server.ResourceConfig;
import javax.ws.rs.ApplicationPath;
/**
* @author Sergey Grachev
*/
@ApplicationPath("/api/*")
public final class JaxRsApplication extends ResourceConfig {
public JaxRsApplication() {
packages(true, "com.github.devmix.sample.undertow.microservice");
}
}
|
C
|
UTF-8
| 960
| 3.84375
| 4
|
[] |
no_license
|
#include <stdio.h>
#define MAX 1000
int maxGCD(int m, int n)
{
// 求最大公约数
// 欧几里得方法计算两个数的最大公约数
if(n == 0)
return m;
return maxGCD(n, m % n);
}
int main()
{
int a, b, k;
int al[MAX] = {};
scanf("%d %d %d", &a, &b, &k);
int num = maxGCD(a, b);
int j = 0;
for(int i = 1; i <= num; i++){ // 优化:从最开始直接判断条件至a,b中的较小值调整到最大公约数
if (a % i == 0 && b % i == 0){ // 当i是a和b的的公约数时,才放到数组中
al[j] = i; // 数组下标加1,指向下一个位置
j++;
}
}
if (k <= j){ // k 从1 开始计数,j从0开始计数,此处的j比数组中正确的最大下标多了1
printf("%d", al[k-1]); // k 和 j的正确对应关系为:第k个值在数组中对应的下标为k-1,
} else { // k-1=j即可找到对应的值(此处j的值已经完成了自加操作)
printf("0");
}
return 0;
}
|
Python
|
UTF-8
| 5,835
| 2.796875
| 3
|
[] |
no_license
|
import pygame
from pygame import *
import sys
import math
from pyquaternion import Quaternion
import examples
from polytope import cross_product
class Cam:
def __init__(self, pos=(0,0,0), rot=(0,0,0)):
self.pos = list(pos)
self.rot = list(rot)
self.quat = Quaternion(axis=[1, 0, 0], degrees=0)
def update(self, dt, key):
s = dt / 200
if key[pygame.K_q]: self.pos[2] -= s
if key[pygame.K_e]: self.pos[2] += s
x = s*math.sin(self.rot[1])
y = s*math.cos(self.rot[1])
s = 0
x, y = s, s;
if key[pygame.K_s]: self.pos[1] += x#; self.pos[1] += y
if key[pygame.K_w]: self.pos[1] -= x#; self.pos[1] -= y
if key[pygame.K_d]: self.pos[0] -= y#; self.pos[1] += x
if key[pygame.K_a]: self.pos[0] += y#; self.pos[1] -= x
def events(self, event):
if event.type == pygame.MOUSEMOTION:
x, y = event.rel
x /= 1000
y /= 1000
#self.rot[0] += y #*math.cos(self.rot[0])-x*math.sin(self.rot[1])
#self.rot[1] -= x
q1 = Quaternion(axis=[1, 0, 0], angle=y)
q2 = Quaternion(axis=[0, 1, 0], angle=-x)
self.quat = q2*q1*self.quat
class PolytopeView:
polytope_list = [examples.right_120cell, examples.right_120cell2, examples.sliced_cube, examples.football]
params = {examples.right_120cell2: -18/180*math.pi, examples.sliced_cube: 0.2}
def __init__(self):
self.alpha = 0
self.polytope_num = -1
self.next()
def get_polytope(self):
return self.polytope
pol_func = self.polytope_list[self.polytope_num]
if pol_func in self.params:
return pol_func(self.alpha)
return pol_func()
def next(self):
self.polytope_num = (self.polytope_num + 1) % len(self.polytope_list)
pol_func = self.polytope_list[self.polytope_num]
if pol_func in self.params:
self.alpha = self.params[pol_func]
self.polytope = pol_func(self.alpha)
else:
self.polytope = pol_func()
#self.alpha = self.params[next_pol]
def change_parameter(self, alpha):
self.alpha = alpha
if self.polytope_list[self.polytope_num] in self.params:
self.polytope = self.polytope_list[self.polytope_num](alpha)
WIN_WIDTH = 1200
WIN_HEIGHT = 800
cx = WIN_WIDTH//2
cy = WIN_HEIGHT//2
DISPLAY = (WIN_WIDTH, WIN_HEIGHT)
BACKGROUND_COLOR = "#FFFFFF"
clock = pygame.time.Clock()
cam = Cam((0, 0, -25))
pol = PolytopeView()
def rotate2d(pos, rad):
x, y = pos
s, c = math.sin(rad), math.cos(rad)
return x*c-y*s, y*c+x*s
def point_to_screen(point):
if point.dim != 3:
return None
x, y, z = cam.quat.rotate(point.coords)
x -= cam.pos[0]
y -= cam.pos[1]
z -= cam.pos[2]
z += 5
f = 200*cam.pos[2]/z
x, y = x*f, y*f
return (cx + int(x), cy + int(y))
def main():
pygame.init()
screen = pygame.display.set_mode(DISPLAY)
pygame.display.set_caption("polytope_list")
bg = Surface((WIN_WIDTH,WIN_HEIGHT))
pygame.event.get()
pygame.mouse.get_rel()
pygame.mouse.set_visible(0)
pygame.event.set_grab(1)
while True:
dt = clock.tick()
for e in pygame.event.get():
if e.type == QUIT or \
(e.type == KEYDOWN and e.key == K_ESCAPE):
pygame.quit()
sys.exit()
cam.events(e)
simp = pol.get_polytope() #examples.football(alpha=alpha)#right_120cell(alpha)
screen.fill(Color(BACKGROUND_COLOR))
'''
front_vert = []
l = len(simp.vertices)
for i in range(l):
for j in range(i+1, l):
for k in range(j+1, l):
p = cross_product(simp.vertices[i] - simp.vertices[k],
simp.vertices[j] - simp.vertices[k])
d = -1*p*simp.vertices[k]
if d > 0:
# print('HGRJDFSJDFJSJ')
p = -1*p
d *= -1
is_front = True
for vert in simp.vertices:
print('{} {} {}'.format(i, j, k))
if p*vert + d < -0.0001:
# print('{}'.format(p*vert+d))
is_front = False
break
if is_front:
print('{} {} {}', i, j, k)
front_vert.append(simp.vertices[i])
front_vert.append(simp.vertices[j])
front_vert.append(simp.vertices[k])
'''
for vert in simp.vertices:
coords = point_to_screen(vert)
pygame.draw.circle(screen, (0, 0, 0), coords, 6)
for edge in simp.edges:
v1_coords = point_to_screen(edge.v1)
v2_coords = point_to_screen(edge.v2)
pygame.draw.line(screen, (0, 0, 0), v1_coords, v2_coords, 1)
pygame.display.flip()
key = pygame.key.get_pressed()
if key[pygame.K_k]:
pol.change_parameter(pol.alpha + dt/2000)
print(pol.alpha*180/math.pi+90)
if key[pygame.K_j]:
pol.change_parameter(pol.alpha - dt/2000)
print(pol.alpha*180/math.pi+90)
if key[pygame.K_RETURN]:
pol.next()
cam.update(dt, key)
if __name__ == "__main__":
examples.right_120cell().matrix('examples/120cell_1_inner_cell.txt')
examples.right_120cell2().matrix('examples/120cell_2_inner_cells.txt')
examples.football().matrix('examples/sliced_icosahedron.txt')
examples.sliced_cube().matrix('examples/sliced_cube.txt')
main()
|
Java
|
UTF-8
| 5,447
| 2.78125
| 3
|
[] |
no_license
|
package com.maid;
import com.maid.android.Android;
import com.maid.form.FormDaftar;
import com.maid.web.Web;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
Android android = null;
Web web = null;
Main main = new Main();
String rawInputMenu;
int inputMenu;
String rawInputMenuData;
int inputMenuData;
while (true) {
System.out.println("Form Pendaftaran PT MAID");
System.out.println("1. Android Development");
System.out.println("2. Web Development");
System.out.print("Pilih Jenis Form : ");
rawInputMenu = main.scanner.nextLine();
try {
inputMenu = Integer.parseInt(rawInputMenu);
if (inputMenu > 0 && inputMenu < 3) {
break;
} else {
System.out.println("Input Tidak Valid");
}
} catch (Exception e) {
System.out.println("Input Tidak Valid!");
}
}
ArrayList<String> dataDiri = main.inputDataForm(0);
if (inputMenu == 1) {
android = new Android(dataDiri);
} else {
web = new Web(dataDiri);
}
while (true) {
System.out.println("Menu");
System.out.println("1. Edit");
System.out.println("2. Tampil");
System.out.println("3. Exit");
System.out.print("Pilih : ");
rawInputMenuData = main.scanner.nextLine();
try {
inputMenuData = Integer.parseInt(rawInputMenuData);
if ((inputMenuData > 0) && (inputMenuData < 4)) {
switch (inputMenuData) {
case 1:
dataDiri = main.inputDataForm(1);
if (inputMenu == 1) {
android.setNilaiTulis(Float.parseFloat(dataDiri.get(0)));
android.setNilaiCoding(Float.parseFloat(dataDiri.get(1)));
android.setNilaiWawancara(Float.parseFloat(dataDiri.get(2)));
} else {
web.setNilaiTulis(Float.parseFloat(dataDiri.get(0)));
web.setNilaiCoding(Float.parseFloat(dataDiri.get(1)));
web.setNilaiWawancara(Float.parseFloat(dataDiri.get(2)));
}
break;
case 2:
float nilaiAkhir;
String nama;
String divisi;
if (inputMenu == 1) {
nilaiAkhir = (android.penilaianCoding() + android.penilaianTulis() + android.penilaianWawancara());
nama = android.getNama();
divisi = "Android";
} else {
nilaiAkhir = (web.penilaianCoding() + web.penilaianTulis() + web.penilaianWawancara());
nama = web.getNama();
divisi = "Web";
}
System.out.println("Nilai Akhir : " + nilaiAkhir);
if (nilaiAkhir < 85) {
System.out.println("Keterangan : GAGAL!");
System.out.println("Mohon Maaf Kepada " + nama + " Telah Ditolak Sebagai " + divisi + " Developer");
} else {
System.out.println("Keterangan : LOLOS!");
System.out.println("Selamat Kepada " + nama + " Telah Diterima Sebagai " + divisi + " Developer");
}
break;
case 3:
System.exit(1);
break;
}
}
} catch (Exception e) {
System.out.println("Input Tidak Valid!");
}
}
}
private String integerInput(String msg) {
String rawInput;
int input;
while (true) {
System.out.print(msg);
rawInput = scanner.nextLine();
try {
input = Integer.parseInt(rawInput);
return String.valueOf(input);
} catch (Exception ignored) {
}
}
}
private ArrayList<String> inputDataForm(int determine) {
ArrayList<String> dataDiri = new ArrayList<>();
int i;
if (determine == 1) {
i = 1;
} else {
i = 0;
}
final String[] INPUT_DATA_MSG = {
"Input NIK : ",
"Input Nilai Tes Tulis : ",
"Input Nilai Tes Coding : ",
"Input Nilai Tes Wawancara : "
};
for (; i < INPUT_DATA_MSG.length; i++) {
if (i == 1 && determine != 1) {
System.out.print("Input Nama : ");
dataDiri.add(scanner.nextLine());
}
dataDiri.add(integerInput(INPUT_DATA_MSG[i]));
}
return dataDiri;
}
}
|
Markdown
|
UTF-8
| 3,930
| 4
| 4
|
[] |
no_license
|
# stringAndArrayMethods
charAt -- returns a new string that contains a character at a specific index. Time complexity O(1)
ie let sring - "i love pie"
sring.charAt(1) = (space)
sring.charAt(4) = v
sring.charAt(2) = l
charCodeAt -- returns an integer between 0 and 65535 (code that handles unicode characters-- based on the ASCII) at that specific index. Time complexity O(1)
ie let string - "This is string"
string.charCodeAt(0) = 84
string.charCodeAt(1) = 104
string.charCodeAt(2) = 105
concat -- method to join two or more string, does not change existing strings but returns a new string containing the text of a joined string. Time complexity of O(n)
ie let str1 = 'hello'
let str2 = 'world'
let result = str1.concat(str2) = 'helloworld'
let result = str2.concat(str1) = 'worldhello'
let str3 = 'hello '
let str4 = 'world'
let result = str1.concat(str2) = 'hello world'
let result = str2.concat(str1) = 'worldhello '
includes -- case sensitive method that determines whether it contains specified string/character by returning t or f. Time complexity of O(1)
ie let cost = $50.90
console.log(cost.includes($)) = true
console.log(cost.includes(.)) = true
console.log(cost.includes(%)) = false
let string3= "Just a string"
console.log(string3.includes('Script', 5)) = false
indexOf -- method that returns the index of the element that exists in the array or the first occurance of where it is. Time complexity of O(n)
ie let str1 = 'finding substring in string'
let example2= str1.indexOf('str')
console.log(example) = 11
match -- method that searches a string for a match and returns the match as an array object. Time complexity is O(n) **matches against regular expression, if not 'match()' will convert it to a regular expression **.
ie let str2 = 'Price: $5 - $15'
let result = str2.match(/\$\d+/g)
console.log(result) = [ '$5', '$15']
repeat -- method that returns a string containing a specified number of copies of string. Time complexity is O(1)
ie let str3= 'hello world'
console.log(str3.repeat(2)) = 'hello worldhello world'
replace -- method that searches a string for a specified value or regex and returns ndw string where that specified value is/are replaced. Time complexity is O(n)
ie let str= 'hello world'
let result = str.replace('world', 'mom') = 'hello mom'
search: case sensitive method that searches a string for a specified value and returns the position of the match. Time complexity is O(1).
ie let re = /[A-Z]/
let str = 'hi There! How are you?'
let index = str.search(re)
console.log(index) = 3 --> count by the index after the first cap letter, if doesnt exist it will return (-1)
slice -- method that returns a copy of a sub array between two index, start and end. Time complexity is O(n)
ie const users = [ {name:'Luis', age:15}, {name:'Jose', age:18}, {name:'Aaron', age:40} ];
const adults = users.slice(1, users.length)
console.log(adults) = (2) [{name: "Jose", age: 18}, {name: "Aaron", age: 40}]
split -- method that splits a string into an array of substrings. Time complexity is O(n)
ie let str = 'i like pie'
console.log(str.split('') = [ 'i', 'like', 'pie']
substr -- method that extract part of a string, it begins at the character at the specified position and returns specifed number of characters. Time complexity is O(n)
toLowerCase -- method that converts a string to lowercase letters. Time complexity is O(n)
ie let str = 'HelLO WoRLd'
console.log(str.toLowerCase) = 'hello world'
toUpperCase -- method that converts a string to uppercase letters. Time complexity is O(n)
ie let str = 'HelLO WoRLd'
console.log(str.toUpperCase) = 'HELLO WORLD'
trim - method that removes whitespace string. Time complexity is O(n)
ie let str = 'HelLO WoRLd'
console.log(str.trim) = 'HelLOWoRLd'
|
Java
|
UTF-8
| 1,550
| 2.890625
| 3
|
[] |
no_license
|
package com.logicalkip.bitingdeath.bitingdeath;
import java.util.LinkedList;
import java.util.List;
import com.logicalkip.bitingdeath.bitingdeath.mapping.Zone;
import com.logicalkip.bitingdeath.bitingdeath.survivor.Survivor;
/**
* Showing WHOM the player decided will go WHERE.
* Could possibly be saved and used to run several Raid (as a "favorite")
* @author LogicalKip
*/
public class RaidSettings {
/**
* The place the team will raid. Might be a building, a part of a forest, of a city...
*/
protected Zone destination;
/**
* Survivors running the mission
*/
protected List<Survivor> team;
public RaidSettings(Zone destination, List<Survivor> team) {
this.destination = destination;
if (team == null)
this.team = new LinkedList<Survivor>();
else
this.team = team;
}
/* GETTERS/SETTERS */
/**
* @return the destination
*/
public Zone getDestination() {
return this.destination;
}
/**
* @param destination the destination to set
*/
public void setDestination(Zone destination) {
this.destination = destination;
}
/**
* @return the team
*/
public List<Survivor> getTeam() {
return this.team;
}
/**
* @param team the team to set
*/
public void setTeam(List<Survivor> team) {
this.team = team;
}
@Override
public String toString() {
String res = "";
res += "Destination : " + this.destination.getName() + "\n";
res += "Team : " + this.team.toString();
return res;
}
}
|
PHP
|
UTF-8
| 2,405
| 2.515625
| 3
|
[] |
no_license
|
<?php
/**
* @file
* CA_Gallery admin system, which overrides the default feature settings.
*
* Will allow us to make visual changes to the feature without overriding the
* actual feature.
*/
/**
* Defines the menu for overriding news feature settings.
*
* @return
* Fully formed Form API array.
*/
function ca_gallery_settings_form() {
$form = array();
$form['ca_gallery_menu_title'] = array(
'#type' => 'textfield',
'#title' => t('Menu Title'),
'#default_value' => variable_get('ca_gallery_menu_title', 'Gallery'),
'#required' => TRUE,
'#description' => t('What would you like the menu title to be?'),
);
$form['ca_gallery_panel_title'] = array(
'#type' => 'textfield',
'#title' => t('Panel Title'),
'#default_value' => variable_get('ca_gallery_panel_title', 'Gallery'),
'#required' => TRUE,
'#description' => t('What would you like the panel title to be?'),
);
$form['ca_gallery_list_template'] = array(
'#type' => 'select',
'#title' => t('Gallery\'s list template'),
'#options' => array(
'ca_gallery_list_template_one' => t('Template one'),
'ca_gallery_list_template_one_flex' => t('Template one Flex'),
),
'#required' => TRUE,
'#default_value' => variable_get('ca_gallery_list_template', 'ca_gallery_list_template_one_flex'),
);
$form['ca_gallery_list_count'] = array(
'#type' => 'textfield',
'#title' => t('Number of galleries to display'),
'#default_value' => variable_get('ca_gallery_list_count', 16),
'#required' => TRUE,
'#description' => t('How many galleries would you like displayed per page? Suggested in groups for 4.'),
);
$form['ca_gallery_sublist_count'] = array(
'#type' => 'textfield',
'#title' => t('Number of sub galleries to display'),
'#default_value' => variable_get('ca_gallery_sublist_count', 4),
'#required' => TRUE,
'#description' => t('How many sub galleries would you like displayed per page? Suggested in groups for 4.'),
);
$form['ca_gallery_image_list_count'] = array(
'#type' => 'textfield',
'#title' => t('Number of images to display'),
'#default_value' => variable_get('ca_gallery_image_list_count', 16),
'#required' => TRUE,
'#description' => t('How many gallery images would you like displayed per page? Suggested in groups for 4.'),
);
return system_settings_form($form);
}
|
PHP
|
UTF-8
| 2,399
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
<?php
function get_featured_programs(){
if(!isset($_SESSION["programs"])){
get_programs();
}
$featured = [];
foreach ($_SESSION["programs"] as $program) {
if($program["featured"] == '1') {
$featured[$program["id"]] = $program;
}
}
return $featured;
}
function generate_carousel_items(){
$output = '';
$featured_programs = get_featured_programs();
//var_dump($_SESSION["programs"]);
$first = "active";
foreach($featured_programs as $featured_program) {
$programs_locations ='';
if(isset($_SESSION["user"])){
$programs_locations = get_program_location_id($featured_program["id"] , $_SESSION["user"]);
}
$output .= '<div class="item '. $first .'" id="carousel_program_'. $featured_program["id"] .'">
<a href="program_details.php?action=program_details&program_id='. $featured_program["id"] .'&program_in_location_id='. $programs_locations .'">
<div class="col-sm-6 carousel_item_content">
<h3 class="carousel_item_content-title">'. $featured_program["name"] .'</h3>
<p class="carousel_item_content-text">'. $featured_program["description"].'</p>
</div>
<img src="'. $featured_program["program_image"] .'" alt="Los Angeles" class="col-sm-6 carousel-img">
</a>
</div>';
$first = "";
}
return $output;
}
function generate_all_programs(){
if(!isset($_SESSION["programs"])){
get_programs();
}
$output = '';
foreach ($_SESSION["programs"] as $program) {
$programs_locations ='';
if(isset($_SESSION["user"])){
$programs_locations = get_program_location_id($program["id"] , $_SESSION["user"]);
}
$output .= '<div class="featured_programs_content-list--program col-sm-4" id="'.$program["id"].'">
<img src="'. $program["program_image"] .'" alt="Los Angeles" style="width:100%;">
<div class="featured_programs_content-list--program-description">
<h3>'. $program["name"] .'</h3>
'. substr($program["description"], 0, 100) .'..
<a href="program_details.php?action=program_details&program_id='. $program["id"] .'&program_in_location_id='.$programs_locations .'" class="btn featured_programs_content-list--program-description--btn_signup"> See </a>
</div>
</div>'; //<a> beshe button
}
return $output;
}
?>
|
Java
|
UTF-8
| 1,298
| 2.21875
| 2
|
[] |
no_license
|
package indi.shine.boot.base.model;
import indi.shine.boot.base.model.api.resp.PageInfo;
import indi.shine.boot.base.model.search.QueryCondition;
import java.util.List;
public interface BaseService<T, PK> {
/**
* 保存
* @author xiezhenxiang 2019/6/13
* @param var1 插入数据
* @return 保存的数据
**/
T save(T var1);
/**
* 保存, 判断空值
* @author xiezhenxiang 2019/6/13
* @param var1 插入数据
* @return 保存的数据
**/
T saveSelective(T var1);
/**
* 根据主键ID删除
* @author xiezhenxiang 2019/6/13
* @param var1 主键ID
**/
void deleteByPrimaryKey(PK var1);
/**
* 根据ID查找
* @author xiezhenxiang 2019/6/13
* @param var1 ID
**/
T getByPrimaryKey(PK var1);
/**
* 根据ID更新,判断空值
* @author xiezhenxiang 2019/6/13
* @param var1 更新数据
**/
void updateByPrimaryKeySelective(T var1);
/**
* 条件查找
* @author xiezhenxiang 2019/6/13
* @param qcList 查找条件
* @param qoList 排序条件
* @param page 分页信息
* @return 返回查找结果
**/
PageInfo<T> list(List<QueryCondition> qcList, List<QueryCondition> qoList, PageModel page);
}
|
Java
|
UTF-8
| 2,507
| 2.515625
| 3
|
[] |
no_license
|
package com.jeincrementer.incrementer;
import java.util.Optional;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import com.jeincrementer.dao.JEStatsDao;
import com.jeincrementer.model.JEStats;
@Service
public class CounterIncrementerDefault {
private static final Logger LOGGER = LogManager.getLogger(JEStatsDao.class);
@Autowired
private JEStatsDao jEStatsDao;
public static final long MAX_HEADER_COUNTER_VALUE = 1_500;
public long getHeaderCounter() {
JEStats jeStats = getJEStatsFirstObjectFromPersistence();
LOGGER.info("Retrieved Data: HEADER COUNTER = {}, LINE COUNTER = {}", jeStats.getHeaderCounter(),
jeStats.getLineCounter());
long newHeaderCounter = getNewHeaderCounter(jeStats.getHeaderCounter());
jeStats.setHeaderCounter(newHeaderCounter);
jEStatsDao.update(jeStats);
return newHeaderCounter;
}
private long getNewHeaderCounter(final long currentHeaderCounter) {
long headerCounter = currentHeaderCounter;
if (validateIfHeaderShouldBeReseted(headerCounter)) {
headerCounter = 1;
} else {
headerCounter += 1;
}
return headerCounter;
}
private boolean validateIfHeaderShouldBeReseted(long headerCounter) {
return headerCounter == MAX_HEADER_COUNTER_VALUE || headerCounter == 0;
}
private JEStats getJEStatsFirstObjectFromPersistence() {
Optional<JEStats> jeStatsOptional = getFirstCountersFromPreviousData();
if (!jeStatsOptional.isPresent()) {
jeStatsOptional = Optional.of(createJEStatusInitialData());
}
return jeStatsOptional.get();
}
private Optional<JEStats> getFirstCountersFromPreviousData() {
try {
return Optional.ofNullable(jEStatsDao.getFirstElement());
} catch (DataAccessException dae) {
LOGGER.error(dae.getMessage());
return Optional.empty();
}
}
private JEStats createJEStatusInitialData() {
JEStats jeStats = new JEStats(0, 0);
jeStats = jEStatsDao.create(jeStats);
return jeStats;
}
public long getLineCounter() {
JEStats jeStats = getJEStatsFirstObjectFromPersistence();
LOGGER.info("Retrieved Data: HEADER COUNTER = {}, LINE COUNTER = {}", jeStats.getHeaderCounter(),
jeStats.getLineCounter());
long newLineCounterValue = jeStats.getLineCounter() + 1;
jeStats.setLineCounter(newLineCounterValue);
jEStatsDao.update(jeStats);
return newLineCounterValue;
}
}
|
C++
|
UTF-8
| 7,246
| 2.671875
| 3
|
[] |
no_license
|
// Fuzz 2 injections with 2 symbols, e.g. SELECT[XX]1[XX]FROM test;
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string.h>
#include <vector>
#include <mysql.h>
#include <algorithm>
#include <sstream>
using namespace std;
#define SERVER "localhost"
#define USER "root"
#define PASSWORD ""
#define DATABASE "test"
char* fillArray(char Alphabet[])
{
for (int i = 32; i <= 96; i++) {
char a = i;
Alphabet[i - 32] = a;
}
int i = 123; // {
char a = i;
Alphabet[65] = a;
i = 124; // |
a = i;
Alphabet[66] = a;
i = 125; // }
a = i;
Alphabet[67] = a;
i = 126; // ~
a = i;
Alphabet[68] = a;
}
bool replace_one(std::string& str, const std::string& from, const std::string& to)
{
// replaces only 1 substring
size_t start_pos = str.find(from);
if (start_pos == std::string::npos)
return false;
if ((start_pos = str.find(from, start_pos)) != std::string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length();
}
return true;
}
bool replace(std::string& str, const std::string& from, const std::string& to)
{
// replaces only 1 substring
size_t start_pos = str.find(from);
if (start_pos == std::string::npos)
return false;
while ((start_pos = str.find(from, start_pos)) != std::string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length();
}
return true;
}
std::string parse_libinjection(std::string text)
{
#define BUFSIZE 128
char cmd[500];
string libInjInput = text;
// TODO: better bash escaping
replace(libInjInput, "'", "'\\''");
strcpy(cmd, "./detect '");
strcat(cmd, libInjInput.c_str());
strcat(cmd, "'");
char buf[BUFSIZE];
FILE* fp;
if ((fp = popen(cmd, "r")) == NULL) {
printf("Error opening file!\n");
return "";
}
fgets(buf, BUFSIZE, fp);
return buf;
}
string dec2hex(unsigned long long i)
{
stringstream ss;
ss << hex << uppercase << i;
return ss.str();
}
void StringExplode(string str, string separator, vector<string>* results)
{
int found;
found = str.find_first_of(separator);
while (found != string::npos) {
if (found > 0) {
results->push_back(str.substr(0, found));
}
str = str.substr(found + 1);
found = str.find_first_of(separator);
}
if (str.length() > 0) {
results->push_back(str);
}
}
bool WriteSQLToDB(MYSQL* connect, string sql, string sql_unicode, string db_name, string mysqlMessage, bool calcLibinj = false)
{
char* escaped_sql = new char[strlen(sql.c_str()) * 3 + 1];
char* escaped_sql_unicode = new char[strlen(sql_unicode.c_str()) * 3 + 1];
mysql_real_escape_string(connect, escaped_sql, sql.c_str(), sql.length());
mysql_real_escape_string(connect, escaped_sql_unicode, sql_unicode.c_str(), sql_unicode.length());
string escaped_sql_string = string(escaped_sql);
string escaped_sql_unicode_string = string(escaped_sql_unicode);
replace(mysqlMessage, "'", "\\\'");
vector<string> R;
string sql_add;
if (calcLibinj == true) {
string thisstring = parse_libinjection(escaped_sql_string);
StringExplode(thisstring, ":", &R);
sql_add = "INSERT INTO " + db_name + " (id, vector, unicode_vector, mysql_message, "
"libinj_token, libinj_isSQLi) VALUES (NULL, '"
+ escaped_sql_string + "', '" + escaped_sql_unicode_string + "', '" + mysqlMessage + "', '" + R[0] + "', '" + R[1] + "');";
}
else {
sql_add = "INSERT INTO " + db_name + " (id, vector, unicode_vector, mysql_message) VALUES (NULL, '" + escaped_sql_string + "', '" + escaped_sql_unicode_string + "', '" + mysqlMessage + "');";
}
mysql_query(connect, sql_add.c_str());
return true;
}
int main(int argc, char* argv[])
{
string sql_input;
if (argc > 1) {
sql_input = string(argv[1]);
}
else {
cout << "Please input fuzzing string with [XX] input, e.g. ./mysql_fuzz.out 'SELECT[XX]1[XX]FROM tbl1'\r\n";
return 0;
}
MYSQL* connect;
connect = mysql_init(NULL);
if (!connect) {
cout << "MySQL Initialization Failed";
return 1;
}
else {
cout << "DB Init OK, start fuzzing";
}
connect = mysql_real_connect(connect, SERVER, USER, PASSWORD, DATABASE, 0, NULL, 0);
MYSQL_RES* res_set;
MYSQL_ROW row;
char Alphabet[68];
fillArray(Alphabet);
int good = 0;
for (int i = 0; i <= sizeof(Alphabet); i++) {
for (int j = 0; j <= sizeof(Alphabet); j++) {
for (int k = 0; k <= sizeof(Alphabet); k++) {
for (int l = 0; l <= sizeof(Alphabet); l++) {
string FinalFuzzWord1 = "";
string FinalFuzzWord2 = "";
FinalFuzzWord1 += Alphabet[i];
FinalFuzzWord1 += Alphabet[j];
FinalFuzzWord2 += Alphabet[k];
FinalFuzzWord2 += Alphabet[l];
char tmpc1 = Alphabet[i];
int tmpi = tmpc1;
char tmpc2 = Alphabet[j];
int tmpj = tmpc2;
char tmpc3 = Alphabet[k];
int tmpk = tmpc3;
char tmpc4 = Alphabet[l];
int tmpl = tmpc4;
string FinalFuzzWordUnicode1 = "";
string FinalFuzzWordUnicode2 = "";
FinalFuzzWordUnicode1 += "%" + dec2hex(tmpi);
FinalFuzzWordUnicode1 += "%" + dec2hex(tmpj);
FinalFuzzWordUnicode2 += "%" + dec2hex(tmpk);
FinalFuzzWordUnicode2 += "%" + dec2hex(tmpl);
string sql = sql_input;
string sql_unicode = sql;
replace_one(sql, "[XX]", FinalFuzzWord1);
replace_one(sql, "[XX]", FinalFuzzWord2);
replace_one(sql_unicode, "[XX]", FinalFuzzWordUnicode1);
replace_one(sql_unicode, "[XX]", FinalFuzzWordUnicode2);
mysql_query(connect, sql.c_str());
while (mysql_store_result(connect) != NULL) { }
string mysqlError = mysql_error(connect);
size_t isSyntaxError = mysqlError.find("You have an error in your SQL syntax");
if (isSyntaxError != 0) {
// If not SQL syntax error
if (mysqlError != "") {
// but still error -> write to DB for manual analysis
WriteSQLToDB(connect, sql, sql_unicode, "mysqlErrors", mysqlError);
}
else {
// GOOD query!
WriteSQLToDB(connect, sql, sql_unicode, "good", "");
good++;
}
}
}
}
}
}
cout << "\nGOOD: ";
cout << good;
cout << "\n";
mysql_close(connect);
return 0;
}
|
Python
|
UTF-8
| 1,646
| 3.46875
| 3
|
[] |
no_license
|
'''
https://leetcode.com/problems/cut-off-trees-for-golf-event/
'''
class Solution(object):
def cutOffTree(self, forest):
"""
:type forest: List[List[int]]
:rtype: int
"""
G = forest
if not G and not G[0]: return -1
m, n = len(G), len(G[0])
trees = []
for i in range(m):
for j in range(n):
if G[i][j] > 0:
trees.append((G[i][j], i, j))
trees = sorted(trees)
count = 0
cx, cy = 0, 0
for h, x, y in trees:
step = self.bfs(G, cx, cy, x, y)
if step == -1:
return -1
else:
count += step
cx, cy = x, y
G[x][y] = 1
return count
def bfs(self, G, cx, cy, x, y):
visited = [[False for j in range(len(G[0]))] for i in range(len(G))]
visited[cx][cy] = True
queue = collections.deque()
queue.append((cx, cy, 0))
while queue:
i, j, step = queue.popleft()
if i == x and j == y:
return step
for ni, nj in [i + 1, j], [i - 1, j], [i, j + 1], [i, j - 1]:
if 0 <= ni < len(G) and 0 <= nj < len(G[0]) and G[ni][nj] != 0 and not visited[ni][nj]:
queue.append((ni, nj, step + 1))
visited[ni][nj] = True
return -1
'''
Success
Details
Runtime: 7516 ms, faster than 34.59% of Python online submissions for Cut Off Trees for Golf Event.
Memory Usage: 12.9 MB, less than 96.60% of Python online submissions for Cut Off Trees for Golf Event.
'''
|
Markdown
|
UTF-8
| 1,336
| 2.609375
| 3
|
[
"Apache-2.0"
] |
permissive
|
---
title: Using a multi-tenant audio gateway
weight: 5
---
You can send audio input to Watson Assistant Solutions. The flow for processing audio input is different from text input. Audio input is sent from an audio device to an audio gateway component of Watson Assistant Solutions. The audio gateway uses speech-to-text and text-to-speech services to convert audio input to text and to convert the converse response to audio.
A sample audio client is also provided in the [Audio Client Sample Code](https://github.com/Watson-Personal-Assistant/AudioClientSampleCodeJava) GIT repository for you to clone and deploy to your devices. For instructions, see the readme file in the repository.
If you have either the IBM Watson Assistant for Automotive or IBM Watson Assistant for Industry flavor of Watson Assistant Solutions, you have access to a multi-tenant audio gateway.
If you have IBM Watson Assistant for Hospitality, you have access to a single-tenant audio gateway in alpha mode. The process flow for a single-tenant gateway and a multi-tenant gateway is different. If you have Watson Assistant for Hospitality, start with the [Using a single-tenant audio gateway]({{site.baseurl}}/audio_single/audio_support/) topic.
> **What to do next?**<br/>
Learn how [audio is processed]({{site.baseurl}}/audio/how_it_works_audio).
|
PHP
|
UTF-8
| 1,483
| 2.640625
| 3
|
[] |
no_license
|
<?php
/**
* Created by PhpStorm.
* User: Mecxi
* Date: 9/24/2017
* Time: 8:41 PM
*/
/* custom HTTP POST */
function curlHTTPRequest($url, $params){
/* initialise curl resource */
$curl = curl_init();
/* result container, whether we are getting a feedback form url or an error */
$result = null;
/* encode to json format */
$data_string = json_encode($params, JSON_FORCE_OBJECT);
/* set resources options for GET REQUEST */
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_CONNECTTIMEOUT => 10000, //attempt a connection within 10sec
CURLOPT_FAILONERROR => 1,
CURLOPT_POST => 1,
CURLOPT_HTTPHEADER => array('Content-Type: application/json; charset=utf-8'),
CURLOPT_POSTFIELDS => $data_string
));
/* execute curl */
$result = curl_exec($curl);
if(curl_error($curl)){
$result = 'Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl);
}
/* close request to clear up some memory */
curl_close($curl);
/* return the result */
return $result;
}
$user_params = array('Username'=>'B3873556', 'Password'=>'A!S@D#f4');
$result = curlHTTPRequest('http://web.mineworkers.co.za:8090/EBSphere.Service_deploy/api/Login', $user_params);
echo '<pre>'. print_r($result, true). '</pre>';
echo '<pre>'. print_r(json_decode($result, true), true). '</pre>';
|
C#
|
UTF-8
| 7,396
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MyMvvmLib;
using System.Windows.Input;
using System.Windows.Forms;
using System.IO;
using System.Collections.ObjectModel;
using System.Windows.Media;
namespace Word_Wiz
{
public class WordWizVM : ViewModelBase<WordWizModel>
{
public WordWizVM(WordWizModel model)
{
Model = model;
}
private MediaPlayer _player = null;
private ObservableCollection<WordSoundFile> _soundFiles = new ObservableCollection<WordSoundFile>();
public ObservableCollection<WordSoundFile> SoundFiles
{
get
{
return _soundFiles;
}
set
{
_soundFiles = value;
}
}
private ICommand _loadCommand = null;
public ICommand LoadCommand
{
get
{
return _loadCommand ?? (_loadCommand =
new RelayCommand(() =>
{
var dialog = new System.Windows.Forms.FolderBrowserDialog();
dialog.SelectedPath = Directory.GetCurrentDirectory();
System.Windows.Forms.DialogResult result = dialog.ShowDialog();
if (result == DialogResult.OK)
{
string path = dialog.SelectedPath;
var soundFiles = Model.LoadFromPath(path);
SoundFiles.Clear();
foreach (var file in soundFiles)
SoundFiles.Add(file);
}
}));
}
}
private int _numberOfWords = 5;
public int NumberOfWords
{
get { return _numberOfWords; }
set
{
if (value < 2)
value = 2;
SetProperty(ref _numberOfWords, value, () => NumberOfWords);
}
}
// Word group and selection
private ObservableCollection<WordSoundFile> _choiceFiles = new ObservableCollection<WordSoundFile>();
public ObservableCollection<WordSoundFile> ChoiceFiles
{
get
{
return _choiceFiles;
}
set
{
SetProperty(ref _choiceFiles, value, () => ChoiceFiles);
}
}
private WordSoundFile _chosen;
public WordSoundFile Chosen
{
get
{
return _chosen;
}
set
{
SetProperty(ref _chosen, value, () => Chosen);
}
}
private ICommand _nextCommand = null;
public ICommand NextCommand
{
get
{
return _nextCommand ?? (_nextCommand =
new RelayCommand(() =>
{
if(_soundFiles.Count() == 0)
return;
Chosen = Model.Chose(_soundFiles);
var choices = Model.GetChoices(_soundFiles, Chosen, NumberOfWords);
ChoiceFiles.Clear();
foreach (var file in choices)
ChoiceFiles.Add(file);
SelectedWord = null;
TryToPlaySound(Chosen.Path);
}));
}
}
private ICommand _repeatCommand = null;
public ICommand RepeatCommand
{
get
{
return _repeatCommand ?? (_repeatCommand =
new RelayCommand(() =>
{
if(Chosen != null)
TryToPlaySound(Chosen.Path);
}));
}
}
private void TryToPlaySound(string filePath)
{
try
{
// see if file exists
if (File.Exists(filePath))
{
// play
Uri uri = new Uri(filePath, UriKind.RelativeOrAbsolute);
if (_player == null)
_player = new MediaPlayer();
if (_player != null)
{
_player.Open(uri);
_player.Play();
}
}
}
catch (System.Exception)
{
}
}
const string CorrectImageFile = "happyClown3.jpg";
const string IncorrectImageFile = "sadClown3.jpg";
const string NeutralImageFile = "books.png";
private string _imagePathName = NeutralImageFile;
public string ImagePathName
{
get
{
return _imagePathName;
}
set
{
SetProperty(ref _imagePathName, value, () => ImagePathName);
}
}
private WordSoundFile _selectedWord = null;
public WordSoundFile SelectedWord
{
get
{
return _selectedWord;
}
set
{
SetProperty(ref _selectedWord, value, () => SelectedWord);
if (Chosen == null || _selectedWord == null)
ImagePathName = NeutralImageFile;
else if (_selectedWord == Chosen)
{
ImagePathName = CorrectImageFile;
_correctCount++;
_totalCount++;
}
else
{
ImagePathName = IncorrectImageFile;
_totalCount++;
}
CalculatePercentCorrect();
}
}
private int _correctCount = 0;
private int _totalCount = 0;
private int _percentCorrect = 0;
void CalculatePercentCorrect()
{
if (_totalCount == 0)
PercentCorrect = 0;
else
{
PercentCorrect = (int)(100.0 * _correctCount) / _totalCount;
}
}
public int PercentCorrect
{
get
{
return _percentCorrect;
}
set
{
SetProperty(ref _percentCorrect, value, () => PercentCorrect);
}
}
private ICommand _resetPercentCorrectCommand = null;
public ICommand ResetPercentCorrectCommand
{
get
{
return _resetPercentCorrectCommand ?? (_repeatCommand =
new RelayCommand(() =>
{
_correctCount = 0;
_totalCount = 0;
PercentCorrect = 0;
}));
}
}
}
}
|
JavaScript
|
UTF-8
| 3,850
| 3.359375
| 3
|
[
"MIT"
] |
permissive
|
const Employee = require("../lib/employee")
describe("Employee", () => {
//TODO: describe initialization: constructor
describe("Initialization", () => {
it("should create a class with a name, id and email", () => {
// arrange
const name = "John Doe";
const id = 5;
const email = "test@test.com";
// act
const employee = new Employee(name, id, email);
// assert
expect(employee.name).toBe("John Doe");
expect(employee.id).toBe(5);
expect(employee.email).toBe("test@test.com");
});
});
//TODO: describe getName()
describe("getName", () => {
it("should return the name of the employee", () => {
// arrange
const name = "John Doe";
const id = 5;
const email = "test@test.com";
const employee = new Employee(name, id, email);
// act
const employeeName = employee.getName();
// assert
expect(employeeName).toBe(name);
});
it("should return an error is there is no name entered", () => {
// arrange
const name = "";
const id = 5;
const email = "test@test.com";
const employee = new Employee(name, id, email);
const err = new Error("Please enter a name");
// act
const cb = () => employee.getName();
// assert
expect(cb).toThrowError(err);
});
});
//TODO: describe getId()
describe("getId", () => {
it("should return the id of the employee", () => {
// arrange
const name = "John Doe";
const id = 5;
const email = "test@test.com";
const employee = new Employee(name, id, email);
// act
const employeeId = employee.getId();
// assert
expect(employeeId).toBe(id);
});
});
//TODO: describe getEmail()
describe("getEmail", () => {
it("should return the email of the employee", () => {
// arrange
const name = "John Doe";
const id = 5;
const email = "test@test.com";
const employee = new Employee(name, id, email);
// act
const employeeEmail = employee.getEmail();
// assert
expect(employeeEmail).toBe(email);
});
it("should return an error is there is no email entered", () => {
// arrange
const name = "John Doe";
const id = 5;
const email = "";
const employee = new Employee(name, id, email);
const err = new Error("Please enter an email");
// act
const cb = () => employee.getEmail();
// assert
expect(cb).toThrowError(err);
});
it("should return an error is there is no email entered", () => {
// arrange
const name = "John Doe";
const id = 5;
const email = "test";
const employee = new Employee(name, id, email);
const err = new Error("Please enter a valid email address");
// act
const cb = () => employee.getEmail();
// assert
expect(cb).toThrowError(err);
});
});
//TODO: describe getRole()
describe("getRole", () => {
it("should return the role of the employee", () => {
// arrange
const name = "John Doe";
const id = 5;
const email = "test@test.com";
const employee = new Employee(name, id, email);
// act
const employeeRole = employee.getRole();
// assert
expect(employeeRole).toBe("Employee");
});
});
});
|
Java
|
UTF-8
| 2,630
| 2.453125
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*Copyright 2014 M3Team
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/package org.t3.metamediamanager.gui;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import net.miginfocom.swing.MigLayout;
import javax.swing.JLabel;
import org.t3.metamediamanager.M3Config;
import org.t3.metamediamanager.MediaLibrary;
/**
* Frame displayed when the user launches the app for the first time
*/
public class FirstRunFrame extends JDialog {
/**
*
*/
private static final long serialVersionUID = 1L;
private DirectoriesChooserPanel _chooser = new DirectoriesChooserPanel();
public FirstRunFrame() {
setModal(true);
setMinimumSize(new Dimension(700,475));
getContentPane().setLayout(new MigLayout("", "[grow][][grow]", "[][grow][]"));
JLabel lblBienvenueDansMetamediamanager = new JLabel("<html>Bienvenue dans MetaMediaManager ! Vous lancez le programme pour la première fois. Configurez vos dossiers de films et séries :</html>");
getContentPane().add(lblBienvenueDansMetamediamanager, "cell 0 0 3 1");
getContentPane().add(_chooser, "cell 0 1 3 1,grow");
JButton btnSave = new JButton("Continuer");
getContentPane().add(btnSave, "cell 1 3 1 1");
btnSave.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
Vector<String> dirF = _chooser.getFilmsDirectories();
Vector<String> dirS = _chooser.getSeriesDirectories();
if(dirF.isEmpty() && dirS.isEmpty())
{
JOptionPane.showMessageDialog(FirstRunFrame.this,"Ajoutez au moins un dossier...", "Problème", JOptionPane.ERROR_MESSAGE);
return;
}
M3Config.getInstance().setFilmsDirectories(dirF);
M3Config.getInstance().setSeriesDirectories(dirS);
M3Config.getInstance().setParam("firstrun", "false");
M3Config.getInstance().save();
MediaLibrary.getInstance().refreshDB();
FirstRunFrame.this.setVisible(false);
}
});
setPreferredSize(new Dimension(530,300));
}
}
|
Python
|
UTF-8
| 1,668
| 2.6875
| 3
|
[] |
no_license
|
from pyspark.sql import SparkSession
from pyspark.sql.types import StructType,StructField,StringType,IntegerType
#D:/PackUp/PySparkBasics/venv/UDM/resources/people.json
spark=SparkSession.builder.appName("r").master("local").getOrCreate();
df=spark.read.json("D:/PackUp/PySparkBasics/venv/UDM/resources/people.json")
df.show()
df.printSchema()
# its a attribute so no () brakets , TO fetch only columns returns list['age', 'name']
print(df.columns)
#it returns a dataframe with statistical summary need to call .show() to view df have min max and Standered Diviation
df.describe().show()
#here we have small data so schema is infered correctly long and string but sometime we need to provide schema details for data
data_schema=[
StructField("age",IntegerType(),True),
StructField("name",StringType(),True)
]
schema=StructType(data_schema)
df=spark.read.json("D:/PackUp/PySparkBasics/venv/UDM/resources/people.json",schema=schema)
df.printSchema()
#if we need to get a column from this df we can use index call just like in dictionary
print(df['age']) #we will get column object
# if we need df of just this single column we can use select
df.select("age").show()
#if we need first two rows,we will get list of row obect so we can use index here 'df.head(2)[0]'
print(df.head(2))
#select multiple column we can pass in list in select return df
df.select(['age','name']).show()
#we can add a new column by with column
df.withColumn('doubleCol',df['age']*2).show()
#Renaming Existing COlumn
df.withColumnRenamed('age','newAge').show()
#to create temporaryView
df.createOrReplaceTempView("people")
spark.sql("SELECT * FROM people where age =30").show()
|
Markdown
|
UTF-8
| 544
| 2.71875
| 3
|
[] |
no_license
|
---
goal:Connaître la syntaxe de l’allocation mémoire en C++
notions:new,delete
---
Vous devez créer une fonction prenant un tableau de chaîne de caractères ainsi qu’un nombre n valant 1 par défaut.
Cette fonction doit renvoyer un tableau de n cases, chacune contenant la taille de la chaîne de caractère correspondante. - Vous créerez aussi une fonction qui détruit ce tableau.
**Questions**
- Quel est l’utilité du drapeau de compilation `-g` ?
- Que sont les programmes `gdb` et `valgrind` ? Comment s’utilisent-ils ?
|
C++
|
UTF-8
| 1,655
| 2.90625
| 3
|
[] |
no_license
|
#pragma once
#include "Order.h"
#include<fstream>
#include<iostream>
Order::Order(int id, ORD_TYPE r_Type, REGION r_region, int dis, int arr,double mon)
{
ID = (id > 0 && id < 1000) ? id : 0; //1<ID<999
type = r_Type;
Region = r_region;
Distance = dis;
ArrTime = arr;
totalMoney = mon;
priority = 3 * totalMoney - Distance - ArrTime;
}
Order::~Order()
{
}
void Order::setmotor(Motorcycle* m){c=m;}
double Order::getMoney() { return totalMoney; }
void Order::setmon(int mon)
{
totalMoney = mon;
}
void Order::setd(int d){ID=d;}
void Order::settime(int ts) {
ServTime = (c->getTOreturn() - ts) / 2;
WaitingTime = ts - ArrTime;
FinishTime = ArrTime + WaitingTime + ServTime;
}
int Order::getFinish() { return FinishTime; }
void Order::promote()
{
type = TYPE_VIP;
}
void Order::print(ofstream & out)
{
out << FinishTime << " " << ID << " " << ArrTime << " " << WaitingTime << " " << ServTime << endl;
}
int Order::getwt()
{
return WaitingTime;
}
int Order::getarr()
{
return ArrTime;
}
int Order::getst()
{
return ServTime;
}
Motorcycle * Order::getmotorcycle()
{
return c;
}
int Order::GetID()
{
return ID;
}
int Order::GetType() const
{
return type;
}
REGION Order::GetRegion() const
{
return Region;
}
void Order::SetDistance(int d)
{
Distance = d>0?d:0;
}
int Order::GetDistance() const
{
return Distance;
}
bool Order::operator==(Order o1) {
return (ID == o1.ID);
}
double Order::calcpriority() {
return priority;
}
bool Order::operator<=(Order o ) {
return(priority <= o.priority);
}
bool Order::OverWait(int t_s, int ap)
{
if (t_s - ArrTime == ap) {
return true;
}
return false;
}
Order::Order() {}
|
Java
|
UTF-8
| 2,026
| 2.421875
| 2
|
[] |
no_license
|
/**
* tzdesk系统平台
* TzHibernate
* com.meh.manytomany.single
* StudentMantToMany.java
* 创建人:maerhuan
* 时间:2016年11月21日-下午11:15:50
* 2016潭州教育公司-版权所有
*/
package com.meh.manytomany.single;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
/**
* 学生表
*
* StudentMantToMany 创建人:maerhuan 时间:2016年11月21日-下午11:16:28
*
* @version 1.0.0
*
*/
@Entity
@Table(name = "tz_manytomany_student")
public class StudentManyToMany implements Serializable{
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
private Set<CourseManyToMany> courses = new HashSet<CourseManyToMany>(0);
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name="student_name",nullable=false,length=80)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//多对多 默认的是懒加载
@ManyToMany(targetEntity=CourseManyToMany.class,cascade=CascadeType.ALL,fetch=FetchType.LAZY)
@JoinTable(name="tz_manytomany_students_courses",
joinColumns={@JoinColumn(name="student_id",referencedColumnName="id")},
inverseJoinColumns={@JoinColumn(name="course_id",referencedColumnName="id")}
)
public Set<CourseManyToMany> getCourses() {
return courses;
}
public void setCourses(Set<CourseManyToMany> courses) {
this.courses = courses;
}
}
|
C++
|
UTF-8
| 192
| 3.203125
| 3
|
[] |
no_license
|
#include <iostream>
#include <vector>
int fib(int pos)
{
if (pos < 2)
{
return pos;
}
return fib(pos - 2) + fib(pos - 1);
}
int main()
{
std::cout << fib(4);
}
|
PHP
|
UTF-8
| 428
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
<?php
if (!function_exists('starts_with') && class_exists('\Illuminate\Support\Str')) {
function starts_with($haystack, $needle)
{
return \Illuminate\Support\Str::startsWith($haystack, $needle);
}
}
if (!function_exists('ends_with') && class_exists('\Illuminate\Support\Str')) {
function ends_with($haystack, $needle)
{
return \Illuminate\Support\Str::endsWith($haystack, $needle);
}
}
|
Python
|
UTF-8
| 416
| 3.40625
| 3
|
[] |
no_license
|
def isIsomorphic(self, s: str, t: str) -> bool:
cs = Counter(s)
ct = Counter(t)
if list(cs.values()) != list(ct.values()):
return False
d = {}
n = len(s)
for i in range(n):
c = s[i]
if c in d:
if d[c] != t[i]:
return False
else:
d[c] = t[i]
return True
|
C#
|
UTF-8
| 3,088
| 2.703125
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Models
{
public class Karta : Faktura
{
#region Properties
public string Sifra { get; set; }
/// <summary>
/// Prodavac karte
/// </summary>
public ProdavacKarata Prodavac { get; set; }
/// <summary>
/// Kupac karte
/// </summary>
public Kupac Kupac { get; set; }
/// <summary>
/// Termin filma
/// </summary>
public Projekcija Termin { get; set; }
/// <summary>
/// ID Karte
/// </summary>
#endregion
#region Constructors
/// <summary>
/// Prazan konstruktor
/// </summary>
public Karta()
{
}
/// <summary>
/// Konstruktor Karta bez id-a
/// </summary>
/// <param name="sifra">Sifra fakture</param>
/// <param name="vrijeme">Vrijeme izdavanja</param>
/// <param name="menadzer">Menadzer koji je odobrio fakturu</param>
/// <param name="prodavac">Klasa prodavaca karte</param>
/// <param name="kupac">Kupac karte</param>
/// <param name="termin">Termin filma</param>
public Karta(string sifra, DateTime vrijeme, Menadzer menadzer, ProdavacKarata prodavac, Kupac kupac, Projekcija termin)
{
this.Sifra = sifra;
this.Vrijeme = vrijeme;
this.Menadzer = menadzer;
this.Prodavac = prodavac;
this.Kupac = kupac;
this.Termin = termin;
}
/// <summary>
/// Konstruktor Karta sa id-om
/// </summary>
/// <param name="id">Id karte</param>
/// <param name="sifra">Sifra fakture</param>
/// <param name="vrijeme">Vrijeme izdavanja</param>
/// <param name="menadzer">Menadzer koji je odobrio fakturu</param>
/// <param name="prodavac">Klasa prodavaca karte</param>
/// <param name="kupac">Kupac karte</param>
/// <param name="termin">Termin filma</param>
public Karta(int id, string sifra, DateTime vrijeme, Menadzer menadzer, ProdavacKarata prodavac, Kupac kupac, Projekcija termin)
{
this.Id = id;
this.Sifra = sifra;
this.Vrijeme = vrijeme;
this.Menadzer = menadzer;
this.Prodavac = prodavac;
this.Kupac = kupac;
this.Termin = termin;
}
/// <summary>
/// Konstruktor klase Karta koji prima instancu klase Karta
/// </summary>
/// <param name="p">Instanca klase Karta</param>
public Karta(Karta k)
{
this.Id = k.Id;
this.Sifra = k.Sifra;
this.Vrijeme = k.Vrijeme;
this.Menadzer = k.Menadzer;
this.Prodavac = k.Prodavac;
this.Termin = k.Termin;
}
#endregion
}
}
|
Java
|
UTF-8
| 752
| 2.4375
| 2
|
[] |
no_license
|
package fr.eazyender.donjon.commands;
import fr.eazyender.donjon.files.PlayerEconomy;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class CommandMoney implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String msg, String[] args) {
if (cmd.getName().equalsIgnoreCase("money")) {
if (sender instanceof Player) {
Player player = (Player) sender;
player.sendMessage("[]" + "Vous avez " + PlayerEconomy.getEconomy().getMoney(player) + "$");
return true;
}
}
return false;
}
}
|
Java
|
UTF-8
| 694
| 3.0625
| 3
|
[] |
no_license
|
package Generics;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class GenericsExample {
public static void main(String[] args) {
System.out.println("Number of cores=="+Runtime.getRuntime().availableProcessors());
BaseClass[] baseclassArray= new DerivedClass[2];
baseclassArray[0] = new DerivedClass();
baseclassArray[1] = new BaseClass();
for (int i = 0; i < baseclassArray.length; i++) {
System.out.println("valuee=="+baseclassArray[i]);
}
List<Integer> abc = new ArrayList<Integer>();
HashSet<String> hashSet = new HashSet<String>();
//hashSet.add(e)
}
}
|
Java
|
UTF-8
| 1,485
| 3.046875
| 3
|
[] |
no_license
|
package com.testapps.wildWistEast.turn;
import com.playpalgames.library.GameTurn;
/**
* Created by javi on 06/08/2014.
*/
public class TurnAction implements GameTurn {
public TurnAction() {
}
public TurnAction(Action action, int player, int target) {
this.action = action;
this.player = player;
this.target = target;
}
@Override
/**
* Creates an string representing the Turn to be sent
*/
public String dataToString() {
return action.name() + "|" + player + "|" + target;
}
/**
* Reads the state received and populates the Turn
*
* @param data
*/
@Override
public void populateFromString(String data) {
String[] fields = data.split("\\|");
action = Action.valueOf(fields[0]);
player = Integer.parseInt(fields[1]);
target = Integer.parseInt(fields[2]);
}
public enum Action {MOVE, SHOOT, RELOAD}
Action action;
//player id
private int player = -1;
//Shoot/move target
private int target = -1;
public Action getAction() {
return action;
}
public void setAction(Action action) {
this.action = action;
}
public int getPlayer() {
return player;
}
public void setPlayer(int player) {
this.player = player;
}
public int getTarget() {
return target;
}
public void setTarget(int target) {
this.target = target;
}
}
|
Java
|
UTF-8
| 264
| 2.125
| 2
|
[] |
no_license
|
package tabuleiro;
public abstract class Peca {
protected Posicao posicao;
private Tabuleiro tabuleiro;
public Peca(Tabuleiro tabuleiro) {
this.posicao = null;
this.tabuleiro = tabuleiro;
}
protected Posicao getPosicao() {
return posicao;
}
}
|
Python
|
UTF-8
| 563
| 2.765625
| 3
|
[] |
no_license
|
n = int(input())
mylist = []
dptable = [0]*n
for _ in range(n):
mylist.append(list(map(int, input().split())))
for idx in range(n):
#끝나는 날
finish = mylist[idx][0]+idx-1
if idx == 0:
mymax = 0
else:
#지금 날까지 가장 많이 받을 수 있는 보수
mymax = max(dptable[:idx])
if finish < n:
#이미 구해진 해당 날까지의 최대 보수와 만약 이번 상담을 하면 업데이트 되는 해당 날까지의 보수 비교
dptable[finish] = max(dptable[finish], mymax+mylist[idx][1])
print(max(dptable))
|
C++
|
UTF-8
| 313
| 2.953125
| 3
|
[] |
no_license
|
#include <iostream>
using namespace std;
int main() {
cout.setf(ios::fixed);
cout.precision(2);
double n;
string cur;
cin >> n >> cur;
if (cur == "euros") {
cout << n*1.254 << " dolars" << endl;
}
else {
cout << n/1.254 << " euros" << endl;
}
}
|
JavaScript
|
UTF-8
| 1,142
| 3.578125
| 4
|
[] |
no_license
|
function colorClock() {
let date = new Date();
let hours = date.getHours();
let minutes = date.getMinutes();
let seconds = date.getSeconds();
if(seconds < 10) {
seconds = '0' + seconds;
}
if(minutes < 10) {
minutes = '0' + minutes;
}
if(hours < 10) {
hours = '0' + hours;
}
let clockFace = hours + ':' + minutes + ':' + seconds;
// let hexColor = '#' + hours + seconds + minutes;
document.getElementById('clock').innerHTML = clockFace;
// document.body.style.background = hexColor;
}
function changeColor() {
let r = Math.floor(Math.random() * 256);
let g = Math.floor(Math.random() * 256);
let b = Math.floor(Math.random() * 256);
let rgbCode = 'rgb(' + r + ',' + g + ',' + b + ')';
document.body.style.background = rgbCode;
let rComp = 255 - r;
let gComp = 255 - g;
let bComp = 255 - b;
let rgbCodeComplementary = 'rgb(' + rComp + ',' + gComp + ',' + bComp + ')';
document.getElementById('clock').style.color = rgbCodeComplementary;
}
setInterval(function() {
colorClock();
changeColor();
}, 1000);
|
TypeScript
|
UTF-8
| 700
| 2.578125
| 3
|
[
"ISC"
] |
permissive
|
import * as fs from 'fs'
import * as path from 'path'
import * as chalk from 'chalk'
import {popsConfigTemplate} from './templates/popsConfigTemplate'
export default (function () {
let filePath: string = path.join(process.cwd(), 'pops.config.js')
if (fs.existsSync(filePath)) {
let msg: string = `${chalk.red.bold('Error')}: A ${chalk.yellow('pops.config.js')} already exists in: ${chalk.red(process.cwd())}`
console.error(msg)
} else {
fs.writeFile(filePath, popsConfigTemplate())
let msg: string = `${chalk.red.bold('Success')}: A ${chalk.yellow('pops.config.js')} was created in: ${chalk.green(process.cwd())}`
console.log(msg)
}
}())
|
Python
|
UTF-8
| 4,926
| 3.15625
| 3
|
[] |
no_license
|
# 文本分类与TensorFlow Hub
from __future__ import absolute_import, division, print_function, unicode_literals
import numpy as np
import tensorflow as tf
# !pip install -q tensorflow-hub
# !pip install -q tensorflow-datasets
import tensorflow_hub as hub
import tensorflow_datasets as tfds
print("Version: ", tf.__version__)
print("Eager mode: ", tf.executing_eagerly())
print("Hub version: ", hub.__version__)
print("GPU is", "available" if tf.config.experimental.list_physical_devices("GPU") else "NOT AVAILABLE")
# 下载IMDB数据集
# 将训练集分成60%和40%,我们将得到15000个例子
# 对于培训,10,000个例子用于验证,25,000个例子用于测试。
train_validation_split = tfds.Split.TRAIN.subsplit([6, 4])
(train_data, validation_data), test_data = tfds.load(
name="imdb_reviews",
split=(train_validation_split, tfds.Split.TEST),
as_supervised=True)
# 探索数据
# 标签是0或1的整数值,其中0表示负面评论,1表示正面评论。
# 先打印10个例子
# 再打印前10个标签
train_examples_batch, train_labels_batch = next(iter(train_data.batch(10)))
for data in train_examples_batch:
print(data)
print(train_labels_batch)
# 建模
# 神经网络是由堆叠层创建的——这需要三个主要的架构决策:
"""
如何表示文本?
在模型中使用多少层?
每层使用多少隐藏单位?
"""
"""
一种表示文本的方法是将句子转换成嵌入向量
我们可以使用一个预先训练好的文本嵌入作为第一层
这将有三个优点:
*我们不必担心文本预处理
*我们可以受益于转移学习
*嵌入有固定的大小,所以处理起来更简单
"""
"""
本例,我们将使用来自TensorFlow Hub的一个预先训练好的文本嵌入模型
名为谷歌/tf2-preview/gnews-swivel-20dim/1
"""
"""
在本教程中,还有其他三个需要测试的预训练模型:
google/tf2-preview/gnews-swivel-20dim-with-oov/1 -
与谷歌/tf2-preview/gnews-swivel-20dim/1相同,但是将2.5%的词汇表转换为OOV桶
如果任务的词汇表和模型的词汇表没有完全重叠,这将有所帮助
google/tf2-preview/nnlm-en-dim50/1 -
一个大得多的模型~1M词汇量大小和50个维度。
google/tf2-preview/nnlm-en-dim128/1 -
更大的模型,约1M的词汇量和128维。
"""
# 首先创建一个Keras层,它使用TensorFlow Hub模型嵌入句子,并在几个输入示例中进行尝试
# 注意,无论输入文本的长度是多少,embeddings的输出形状都是:(num_examples, embedding_dimension)。
embedding = "https://hub.tensorflow.google.cn/google/tf2-preview/gnews-swivel-20dim/1"
hub_layer = hub.KerasLayer(embedding, input_shape=[],
dtype=tf.string, trainable=True)
hub_layer(train_examples_batch[:3])
# 现在让我们建立完整的模型:
model = tf.keras.Sequential()
model.add(hub_layer)
model.add(tf.keras.layers.Dense(16, activation='relu'))
model.add(tf.keras.layers.Dense(1, activation='sigmoid'))
model.summary()
"""
1.第一层是TensorFlow Hub层
这一层使用预训练的保存模型将一个句子映射到它的嵌入向量中
我们使用的预先训练好的文本嵌入模型(谷歌/tf2-preview/gnews- swivel20 dim/1)将句子分割成标记
嵌入每个标记,然后结合嵌入。结果的维度是:(num_examples, embedding_dimension)
2.这个固定长度的输出向量通过一个具有16个隐藏单元的全连接(密集)层
3.最后一层与单个输出节点紧密连接
使用sigmoid激活函数,这个值是0到1之间的一个浮点数,表示一个概率或可信度
"""
# 损失函数和优化器
"""
模型需要一个损失函数和一个用于培训的优化器。
由于这是一个二进制分类问题,并且模型输出一个概率(一个激活了sigmoid的单单元层)
所以我们将使用binary_crossentropy损失函数
这不是损失函数的惟一选择
例如,可以选择mean_squared_error
但是,一般来说,binary_crossentropy更适合处理概率—它测量概率分布之间的“距离”
或者在我们的例子中,测量地面真实分布和预测之间的“距离”
"""
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
# 训练模型
"""
以512个样品小批量培养20个epoch的模型
这是x_train和y_train张量中所有样本的20次迭代
在训练过程中,对来自验证集的10,000个样本监测模型的损失和准确性:
"""
history = model.fit(train_data.shuffle(10000).batch(512),
epochs=20,
validation_data=validation_data.batch(512),
verbose=1)
# 评估模型
results = model.evaluate(test_data.batch(512), verbose=2)
for name, value in zip(model.metrics_names, results):
print("%s: %.3f" % (name, value))
# 这种相当天真的方法获得了大约87%的准确性。使用更高级的方法,模型应该接近95%。
|
C#
|
UTF-8
| 895
| 2.796875
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
namespace AltaArchive.Services {
public class MultiValueConverter : IMultiValueConverter {
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) {
string one = values[0] as string;
string two = values[1] as string;
string three = values[2] as string;
if(!string.IsNullOrEmpty(one) && !string.IsNullOrEmpty(two) && !string.IsNullOrEmpty(three)) {
return one + two + three;
}
return null;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) {
throw new NotImplementedException();
}
}
}
|
Java
|
UTF-8
| 3,730
| 2.34375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package mvvm.steelkiwi.com.moviefinder.services.rest.dto.movies;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
import mvvm.steelkiwi.com.moviefinder.MovieFinderApp;
import mvvm.steelkiwi.com.moviefinder.R;
/**
* Created by bohdan on 30.03.17.
*/
public class MovieDTO implements Parcelable{
private long id;
private String original_title;
private String original_language;
private String title;
private String backdrop_path;
private float popularity;
private long vote_count;
private boolean video;
private float vote_average;
private String poster_path;
private boolean adult;
private String overview;
private String release_date;
private ArrayList<Integer> genre_ids;
protected MovieDTO(Parcel in) {
id = in.readLong();
original_title = in.readString();
original_language = in.readString();
title = in.readString();
backdrop_path = in.readString();
popularity = in.readFloat();
vote_count = in.readLong();
video = in.readByte() != 0;
vote_average = in.readFloat();
poster_path = in.readString();
adult = in.readByte() != 0;
overview = in.readString();
release_date = in.readString();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(id);
dest.writeString(original_title);
dest.writeString(original_language);
dest.writeString(title);
dest.writeString(backdrop_path);
dest.writeFloat(popularity);
dest.writeLong(vote_count);
dest.writeByte((byte) (video ? 1 : 0));
dest.writeFloat(vote_average);
dest.writeString(poster_path);
dest.writeByte((byte) (adult ? 1 : 0));
dest.writeString(overview);
dest.writeString(release_date);
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<MovieDTO> CREATOR = new Creator<MovieDTO>() {
@Override
public MovieDTO createFromParcel(Parcel in) {
return new MovieDTO(in);
}
@Override
public MovieDTO[] newArray(int size) {
return new MovieDTO[size];
}
};
public long getId() {
return id;
}
public String getOriginalTitle() {
return original_title;
}
public String getOriginalLanguage() {
return original_language;
}
public String getTitle() {
return title;
}
public String getBackdropPath() {
String baseImageUrl = MovieFinderApp.getInstance().getString(R.string.base_image_url);
if (backdrop_path!= null && !backdrop_path.startsWith(baseImageUrl)){
backdrop_path = baseImageUrl + backdrop_path;
}
return backdrop_path;
}
public float getPopularity() {
return popularity;
}
public long getVoteCount() {
return vote_count;
}
public boolean isVideo() {
return video;
}
public float getVoteAverage() {
return vote_average;
}
public String getPosterPath() {
String baseImageUrl = MovieFinderApp.getInstance().getString(R.string.base_image_url);
if (poster_path!= null && !poster_path.startsWith(baseImageUrl)){
poster_path = baseImageUrl + poster_path;
}
return poster_path;
}
public boolean isAdult() {
return adult;
}
public String getOverview() {
return overview;
}
public String getReleaseDate() {
return release_date;
}
public ArrayList<Integer> getGenreIds() {
return genre_ids;
}
}
|
Java
|
UTF-8
| 7,261
| 2.40625
| 2
|
[] |
no_license
|
package com.vortex.cloud.ums.util.tree;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vortex.cloud.vfs.common.lang.StringUtil;
public abstract class CommonTree {
private static Logger log = LoggerFactory.getLogger(CommonTree.class);
private Map<String, CommonTreeNode> treeNodeMaps = new Hashtable<String, CommonTreeNode>();
private CommonTreeNode root;
/**
* root if it's parent is empty
*/
protected void reload(List<Object> nodes, Object rootNode) {
if (log.isInfoEnabled()) {
log.info("tree will start reload all data");
}
boolean hasRoot = false;
synchronized (this) {
// initialize
treeNodeMaps.clear();
root = null;
List<CommonTreeNode> treeNodes = new ArrayList<CommonTreeNode>();
for (int i = 0; i < nodes.size(); i++) {
CommonTreeNode node = this.transform(nodes.get(i)); // transform
if (node == null) {
continue;
}
treeNodes.add(node);
node.setTree(this);
treeNodeMaps.put(node.getNodeId().trim(), node);
}
if (rootNode != null) {
CommonTreeNode node = this.transform(rootNode);
node.setType("Root");
treeNodes.add(node);
node.setTree(this);
treeNodeMaps.put(StringUtil.clean(node.getNodeId()), node);
root = node;
hasRoot = true;
}
for (int i = 0; i < treeNodes.size(); i++) {
CommonTreeNode node = treeNodes.get(i);
String parentId = StringUtil.clean(node.getParentId());
if (hasRoot == false && this.isRootNode(node)) {
if (root == null) {
root = node;
} else {
log.error("find more then one root node. ignore.");
}
} else {
CommonTreeNode parent = treeNodeMaps.get(parentId);
if (parent != null) {
parent.addChild(node);
node.setParent(parent);
} else {
log.warn("node [id=" + node.getNodeId() + " text=" + node.getText() + " parentid=" + node.getParentId() + "]: missing parent node.");
// bug
// root.addChild(node);
// node.setParent(root);
}
}
}
}
if (root == null) {
log.error("the root node is not be defined");
}
}
/**
* root if it's parent is empty
*/
protected void reloadWidthAllParent(List<Object> nodes, Object rootNode) {
if (log.isInfoEnabled()) {
log.info("tree will start reload all data");
}
boolean hasRoot = false;
synchronized (this) {
// initialize
treeNodeMaps.clear();
root = null;
List<CommonTreeNode> treeNodes = new ArrayList<CommonTreeNode>();
for (int i = 0; i < nodes.size(); i++) {
CommonTreeNode node = this.transform(nodes.get(i)); // transform
if (node == null) {
continue;
}
treeNodes.add(node);
node.setTree(this);
treeNodeMaps.put(node.getNodeId().trim(), node);
}
if (rootNode != null) {
CommonTreeNode node = this.transform(rootNode);
node.setType("Root");
treeNodes.add(node);
node.setTree(this);
treeNodeMaps.put(StringUtil.clean(node.getNodeId()), node);
root = node;
hasRoot = true;
}
for (int i = 0; i < treeNodes.size(); i++) {
CommonTreeNode node = treeNodes.get(i);
String parentId = StringUtil.clean(node.getParentId());
if (hasRoot == false && this.isRootNode(node)) {
if (root == null) {
root = node;
} else {
log.error("find more then one root node. ignore.");
}
} else {
CommonTreeNode parent = treeNodeMaps.get(parentId);
if (parent != null) {
parent.addChild(node);
node.setParent(parent);
} else {
log.warn("node [id=" + node.getNodeId() + " text=" + node.getText() + " parentid=" + node.getParentId() + "]: missing parent node.");
// bug
root.addChild(node);
node.setParent(root);
}
}
}
}
if (root == null) {
log.error("the root node is not be defined");
}
}
/**
* root if it's parent is empty
*/
protected void reload(List<Object> nodes, Object rootNode, String rootType) {
log.info("tree will start reload all data");
boolean hasRoot = false;
synchronized (this) {
// initialize
treeNodeMaps.clear();
root = null;
List<CommonTreeNode> treeNodes = new ArrayList<CommonTreeNode>();
for (int i = 0; i < nodes.size(); i++) {
CommonTreeNode node = this.transform(nodes.get(i)); // transform
if (node == null) {
continue;
}
treeNodes.add(node);
node.setTree(this);
treeNodeMaps.put(node.getNodeId().trim(), node);
}
if (rootNode != null) {
CommonTreeNode node = this.transform(rootNode);
node.setType(rootType == null ? "Root" : rootType);
treeNodes.add(node);
node.setTree(this);
treeNodeMaps.put(node.getNodeId().trim(), node);
root = node;
hasRoot = true;
}
for (int i = 0; i < treeNodes.size(); i++) {
CommonTreeNode node = treeNodes.get(i);
String parentId = StringUtil.clean(node.getParentId());
if (hasRoot == false && this.isRootNode(node)) {
if (root == null) {
root = node;
} else {
log.error("find more then one root node. ignore.");
}
} else {
CommonTreeNode parent = treeNodeMaps.get(parentId);
if (parent != null) {
parent.addChild(node);
node.setParent(parent);
} else {
log.warn("node [id=" + node.getNodeId() + " text=" + node.getText() + " parentid=" + node.getParentId() + "]: missing parent node.");
}
}
}
}
if (root == null) {
log.error("the root node is not be defined");
}
}
protected boolean isRootNode(CommonTreeNode node) {
if (node.getParentId() == null || "0".equals(node.getParentId()) || "null".equals(node.getParentId())) {
return true;
} else {
return false;
}
// return StringUtils.isBlank(node.getParentId());
}
public CommonTreeNode getRootNode() {
return root;
}
public CommonTreeNode getTreeNode(String nodeId) {
return treeNodeMaps.get(nodeId);
}
public void addTreeNode(CommonTreeNode node) {
synchronized (this) {
treeNodeMaps.put(node.getNodeId(), node);
String parentId = node.getParentId();
if (StringUtils.isNotBlank(parentId)) {
CommonTreeNode parent = getTreeNode(parentId);
if (parent != null) {
parent.addChild(node);
node.setParent(parent);
} else {
log.error("parent cannot be found: " + node.getParentId());
}
} else {
if (root == null) {
root = node;
} else {
log.error("find more then one root node. ignore.");
}
}
}
}
public void deleteTreeNode(String nodeId) {
synchronized (this) {
CommonTreeNode node = getTreeNode(nodeId);
if (node == null)
throw new IllegalArgumentException(nodeId + " cannot be found.");
if (node.getParent() == null) {
root = null;
treeNodeMaps.clear();
log.warn("the root node has been removed.");
} else {
node.getParent().getChildren().remove(node);
treeNodeMaps.remove(nodeId);
List<CommonTreeNode> children = node.getAllChildren();
for (int i = 0; i < children.size(); i++) {
CommonTreeNode n = children.get(i);
treeNodeMaps.remove(n.getNodeId());
}
}
}
}
protected abstract CommonTreeNode transform(Object info);
}
|
Markdown
|
UTF-8
| 334
| 2.828125
| 3
|
[] |
no_license
|
# Hello-World-
I'm totally new to this, I'd like to get into video game development. I am a full time student and part time worker so my time is limited.
I really like playing video games and I think they are a great way to escape from the world, since I am passionate about them I believe it would be a good project to begin with.
|
JavaScript
|
UTF-8
| 576
| 3.046875
| 3
|
[] |
no_license
|
// to make list icon open and close nav
document.getElementById('toggle-nav').addEventListener('click', function() {
nav = document.getElementById('nav');
nav_is_open = window.getComputedStyle(nav, null).getPropertyValue('position') == 'relative'
classes = document.getElementById('nav').className;
if (nav_is_open) {
document.getElementById('nav').className =
classes.replace('open', '').trim() + " close";
} else {
document.getElementById('nav').className =
classes.replace('close', '').trim() + " open";
}
});
|
Java
|
UTF-8
| 199
| 2.640625
| 3
|
[] |
no_license
|
package Part2;
public class SimplyLinkedListNode {
public int data;
public SimplyLinkedListNode next;
public SimplyLinkedListNode(int iData)
{
this.data = iData;
this.next = null;
}
}
|
Python
|
UTF-8
| 310
| 3.15625
| 3
|
[] |
no_license
|
import turtle
import random
screen = turtle.Screen()
image1 ="back.gif"
image2 ="front.gif"
screen.addshape(image1)
screen.addshape(image2)
t1 = turtle.Turtle()
coin=random.randint(0,1)
if coin == 0:
t1.shape(image1)
t1.stamp()
else :
t1.shape(image2)
t1.stamp()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.