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,378
| 1.984375
| 2
|
[] |
no_license
|
/*
* Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.sap.productconfig.runtime.pci.impl;
import de.hybris.platform.sap.productconfig.runtime.interf.analytics.model.AnalyticsDocument;
import de.hybris.platform.sap.productconfig.runtime.pci.PCIRequestErrorHandler;
import java.util.concurrent.TimeoutException;
import org.apache.log4j.Logger;
import com.hybris.charon.exp.HttpException;
import rx.Observable;
import rx.schedulers.Schedulers;
/**
* Default implementaion of the {@link PCIRequestErrorHandler}.
*/
public class PCIRequestErrorHandlerImpl implements PCIRequestErrorHandler
{
private static final Logger LOG = Logger.getLogger(PCIRequestErrorHandlerImpl.class);
protected static final String NO_SERVER_MESSAGE = "No server message available";
protected AnalyticsDocument createEmptyAnalyticsDocument(final AnalyticsDocument analyticsDocumentInput)
{
final AnalyticsDocument anaDoc = new AnalyticsDocument();
anaDoc.setRootItem(null);
anaDoc.setRootProduct(analyticsDocumentInput.getRootProduct());
return anaDoc;
}
@Override
public AnalyticsDocument processCreateAnalyticsDocumentHttpError(final HttpException ex,
final AnalyticsDocument analyticsDocumentInput)
{
LOG.error("analytics service failed with the following server side error: " + getServerMessage(ex), ex);
return createEmptyAnalyticsDocument(analyticsDocumentInput);
}
protected String getServerMessage(final HttpException ex)
{
final Observable<String> serverMessage = ex.getServerMessage();
if (serverMessage != null)
{
return serverMessage.subscribeOn(Schedulers.io()).toBlocking().first();
}
else
{
return NO_SERVER_MESSAGE;
}
}
@Override
public AnalyticsDocument processCreateAnalyticsDocumentRuntimeException(final RuntimeException ex,
final AnalyticsDocument analyticsDocumentInput)
{
final Throwable cause = ex.getCause();
if (cause instanceof TimeoutException)
{
LOG.error("Timeout exception", cause);
return createEmptyAnalyticsDocument(analyticsDocumentInput);
}
throw ex;
}
}
|
C#
|
UTF-8
| 3,599
| 2.59375
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using api.Data;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Authentication;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace api.Util
{
public static class AppBuilderExtensions
{
/// <summary>
/// Adds lousy security: user has unique key and if it is lost, he/she can't log in anymore.
/// </summary>
public static IApplicationBuilder UseLousySecurity(this IApplicationBuilder app)
{
return app.UseMiddleware<LousySecurityMiddleware>();
}
}
public class LousySecurityMiddleware : AuthenticationMiddleware<LousySecurityOptions>
{
public LousySecurityMiddleware(RequestDelegate next, IOptions<LousySecurityOptions> options, ILoggerFactory loggerFactory, UrlEncoder encoder)
: base(next, options, loggerFactory, encoder)
{
}
protected override AuthenticationHandler<LousySecurityOptions> CreateHandler()
{
return new LousySecurityHandler();
}
}
public class LousySecurityHandler : AuthenticationHandler<LousySecurityOptions>
{
public LousySecurityHandler()
{
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
string authorization = Request.Headers["Authorization"];
if(string.IsNullOrEmpty(authorization))
{
return AuthenticateResult.Skip();
}
string key = null;
if(authorization.StartsWith("lousysecurity ", StringComparison.OrdinalIgnoreCase))
{
key = authorization.Substring("lousysecurity ".Length).Trim();
}
else
{
return AuthenticateResult.Skip();
}
try
{
var keyGuid = new Guid(key);
var dbContext = (BbbgContext)Context.RequestServices.GetService(typeof(BbbgContext));
var player = await dbContext.Players.SingleOrDefaultAsync(x => x.LousySecurityKey == keyGuid);
if(player != null)
{
var principal = new ClaimsPrincipal(new ClaimsIdentity(CreatePlayerClaims(player), Options.AuthenticationScheme));
return AuthenticateResult.Success(new AuthenticationTicket(principal, new AuthenticationProperties(), Options.AuthenticationScheme));
}
return AuthenticateResult.Fail("No such user");
}
catch(Exception ex)
{
return AuthenticateResult.Fail(ex);
}
}
private IEnumerable<Claim> CreatePlayerClaims(Player player)
{
var list = new List<Claim>();
list.Add(new Claim(ClaimTypes.NameIdentifier, player.Id.ToString()));
list.Add(new Claim(ClaimTypes.Name, player.Nickname));
return list;
}
}
public class LousySecurityOptions : AuthenticationOptions
{
public LousySecurityOptions() : base()
{
AuthenticationScheme = "lousysecurity";
AutomaticAuthenticate = true;
AutomaticChallenge = true;
}
}
}
|
Rust
|
UTF-8
| 2,782
| 3.28125
| 3
|
[] |
no_license
|
use std::num::Float;
use std::fmt;
#[ deriving( Clone, PartialEq ) ]
pub struct Vec3 {
pub x : f64,
pub y : f64,
pub z : f64,
}
#[ allow( dead_code ) ]
impl Vec3 {
#[ inline ]
pub fn new( x : f64, y : f64, z : f64 ) -> Vec3 {
return Vec3 {
x : x,
y : y,
z : z,
};
}
#[ inline ]
pub fn length( &self ) -> f64 {
return self.sqlength().sqrt();
}
#[ inline ]
pub fn sqlength( &self ) -> f64 {
return self.x * self.x + self.y * self.y + self.z * self.z;
}
#[ inline ]
pub fn normalised( &self ) -> Vec3 {
return self / self.length();
}
#[ inline ]
pub fn fastnormalised( &self ) -> Vec3 {
return self * self.sqlength().rsqrt();
}
#[ inline ]
pub fn dir_length( &self ) -> ( Vec3, f64 ) {
let len = self.length();
return ( self / len, len );
}
#[ inline ]
pub fn dot( &self, other : Vec3 ) -> f64 {
return self.x * other.x + self.y * other.y + self.z * other.z;
}
#[ inline ]
pub fn cross( &self, other : Vec3 ) -> Vec3 {
return Vec3 {
x : self.y * other.z - self.z * other.y,
y : -( self.x * other.z - self.z * other.x ),
z : self.x * other.y - self.y * other.x,
};
}
// Hadamard product
#[ inline ]
pub fn hprod( &self, other : &Vec3 ) -> Vec3 {
return Vec3 {
x : self.x * other.x,
y : self.y * other.y,
z : self.z * other.z
};
}
#[ inline ]
pub fn hdiv( &self, other : &Vec3 ) -> Vec3 {
return Vec3 {
x : self.x / other.x,
y : self.y / other.y,
z : self.z / other.z
};
}
#[ inline ]
pub fn i() -> Vec3 {
return Vec3 { x : 1.0, y : 0.0, z : 0.0 };
}
#[ inline ]
pub fn j() -> Vec3 {
return Vec3 { x : 0.0, y : 1.0, z : 0.0 };
}
#[ inline ]
pub fn k() -> Vec3 {
return Vec3 { x : 0.0, y : 0.0, z : 1.0 };
}
}
impl Add< Vec3, Vec3 > for Vec3 {
#[ inline ]
fn add( &self, other : &Vec3 ) -> Vec3 {
return Vec3 {
x : self.x + other.x,
y : self.y + other.y,
z : self.z + other.z,
};
}
}
impl Sub< Vec3, Vec3 > for Vec3 {
#[ inline ]
fn sub( &self, other : &Vec3 ) -> Vec3 {
return Vec3 {
x : self.x - other.x,
y : self.y - other.y,
z : self.z - other.z,
};
}
}
impl Mul< f64, Vec3 > for Vec3 {
#[ inline ]
fn mul( &self, s : &f64 ) -> Vec3 {
return Vec3 {
x : self.x * *s,
y : self.y * *s,
z : self.z * *s,
};
}
}
impl Div< f64, Vec3 > for Vec3 {
#[ inline ]
fn div( &self, d : &f64 ) -> Vec3 {
let s = 1.0 / *d;
return Vec3 {
x : self.x * s,
y : self.y * s,
z : self.z * s,
};
}
}
impl Neg< Vec3 > for Vec3 {
#[ inline ]
fn neg( &self ) -> Vec3 {
return Vec3 {
x : -self.x,
y : -self.y,
z : -self.z,
};
}
}
impl fmt::Show for Vec3 {
fn fmt( &self, f : &mut fmt::Formatter ) -> fmt::Result {
return write!( f, "[ {}, {}, {} ]", self.x, self.y, self.z );
}
}
|
PHP
|
UTF-8
| 631
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
// 1. To specify package’s class you are using
use Astrotomic\Translatable\Contracts\Translatable as TranslatableContract;
use Astrotomic\Translatable\Translatable;
class Ingredients extends Model implements TranslatableContract
{
use HasFactory;
use Translatable; // 2. To add translation methods
// 3. To define which attributes needs to be translated
public $translatedAttributes = ['title', 'slug'];
protected $hidden = [
'pivot',
'translations'
];
}
|
Java
|
UTF-8
| 547
| 2.3125
| 2
|
[] |
no_license
|
package cn.ep.spring.boot.ch04.s17;
import cn.ep.ws.*;
import org.springframework.ws.client.core.support.WebServiceGatewaySupport;
public class WsClient extends WebServiceGatewaySupport {
public GetCountryResponse getCountry(String name) {
GetCountryRequest request = new GetCountryRequest();
request.setName(name);
GetCountryResponse response = (GetCountryResponse) getWebServiceTemplate().marshalSendAndReceive(
"http://localhost:8080/ws/countries.wsdl", request);
return response;
}
}
|
Java
|
UTF-8
| 222
| 1.789063
| 2
|
[] |
no_license
|
package multi.campus.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class MovieGenre {
int movieCd;
String genreNm;
}
|
Python
|
UTF-8
| 8,697
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
"""
Structures (:mod:`structures`)
==========================
The `structures` module attempts to implement all types of graphene as objects from nanostructured to planar with any number of layers.
"""
import os
import numpy as np
from scipy import integrate
from scipy import optimize
from scipy import special
from scipy import constants as sc
import warnings
from graphenemodeling import statistical_distributions as sd
from graphenemodeling import Emitter
eVtoJ = sc.elementary_charge
e0 = sc.epsilon_0
hbar = sc.hbar
Z0 = sc.physical_constants['characteristic impedance of vacuum']
sigma_0 = sc.elementary_charge**2 / (4 * sc.hbar)
kB = sc.Boltzmann
class HalfPlane(BaseGraphene):
'''
A class describing the properties of a half-plane of graphene.
'''
def __init__(self,width,type,layers):
self.__class__= type( self.__class__.__name__,
(layers, BaseGraphene),
dict(self.__class__.__dict__))
super(self.__class__, self).__init__()
self.width = width
class Ribbon(BaseGraphene):
'''
A class describing the properties of a circular piece of graphene.
Currently only monolayer.
Parents
----------
BaseGraphene
layers (required argument. See Parameters below.)
Initialization Parameters
----------
width: scalar, width of graphene ribbon.
edge: 'armchair':
'zig-zag':
layers: graphene.Monolayer for 1 layer.
graphene.Bilayer for 2 layers
'''
def __init__(self,width,type,layers):
self.__class__= type( self.__class__.__name__,
(layers, BaseGraphene),
dict(self.__class__.__dict__))
super(self.__class__, self).__init__()
self.width = width
class Nanostructure(BaseGraphene):
'''
A class describing a nanostructured piece of graphene of any shape.
Assumed finite in all directions. Therefore, half-sheet and nanoribbons
are not included.
Uses the formulation as described in Ref 1 Sec. 5.3.1
Parameters
---------
eigenmodes: n x 2 array, where n is the number of modes.
Pairs of normalized eigenfrequencies and mode strengths
Format: np.array([[freq1, stren1],[freq2,stren2],[freq3,stren3],...])
Plan
----------
Be able to pass in the parameters that describe the various modes.
Use this class on solved systems.
Currently only deriving properties from graphene, but could be genrealized
in its own file.
Shapes:
----------
Disk, Square
Shapes that could be included
-----------
Pentagon, Hexagon, Triangle
References
----------
[1] Christensen 2017, Thesis
We are using the notation of this thesis.
[2] Miller et al. 2017, URL: http://pubs.acs.org/doi/10.1021/acs.nanolett.7b02007
'''
def __init__(self,layers, size=None,eigenmodes=None):
if layers == 1:
layerclass = Monolayer
if layers == 2:
layerclass = Bilayer
# Next lines add class given in 'layers' argument
self.__class__= type( self.__class__.__name__,
(layerclass, BaseGraphene ),
dict(self.__class__.__dict__))
super(self.__class__, self).__init__()
self.size=size
self.eigenmodes = eigenmodes
def OpticalResponseBound(self,omega,gamma,eFermi,T):
warnings.warn("Nanostructure.OpticalResponseBound: Only MONOLAYER is being used.")
return Monolayer.OpticalResponseBound(self,omega,gamma,eFermi,T)
def DipolePolarizibility(self,omega,gamma,eFermi,T,order=None):
'''
Equation 5.22 of Ref 1
'''
# Equation 5.14b of Ref [1]
zeta = lambda w: 1j*sc.epsilon_0*1*w*(self.size) / self.OpticalConductivity(0,w,gamma,eFermi,T)
alpha_term = lambda w, eigenmode: eigenmode[1] / (eigenmode[0] - zeta(w))
alpha_sum = 0
for em in self.eigenmodes[:order]:
alpha_sum = alpha_sum + alpha_term(omega,em)
alpha = 2*(self.size)**3 * alpha_sum
return alpha
def CrossSection(self,omega,gamma,eFermi,T,eps_medium,cstype):
'''
The cross section of a scatterer embedded in a medium.
Equation 2.21 of Ref 1.
Assumptions
----------
Nonretarded model, medium lossless, single dipole frequency contributes.
Parameters
----------
omega: array-like, angular frequencies of light
eps_medium: scalar, dielectric of the medium enclosing the scatterer. Must be lossless
cstype: Cross Section type
'scattering': scattering cross section
'absorption': absorption cross section
'extinction': sum of scattering and absorption
References
----------
[1] Christensen 2017 Thesis
'''
alpha = self.DipolePolarizibility(omega,gamma,eFermi,T)
kd = np.sqrt(eps_medium)*omega/sc.speed_of_light
sigma_sca, sigma_abs = 0, 0
if cstype == 'scattering' or cstype=='extinction':
sigma_sca = (6*sc.pi)**(-1)*(kd**4)*np.abs(alpha)**2
if cstype == 'absorption' or cstype=='extinction':
sigma_abs = kd * np.imag(alpha)
return sigma_sca + sigma_abs
class Disk(Nanostructure):
'''
A class describing the properties of a circular piece of graphene.
Currently only monolayer.
Parents
----------
BaseGraphene
layers (required argument. See Parameters below.)
Initialization Parameters
----------
radius: scalar, radius of circle
layers: class, graphene.Monolayer for 1 layer.
graphene.Bilayer for 2 layers.
'''
def __init__(self,layers,radius):
# Monolayer Graphene mode parameters
# Normalized to L=R
eigenfrequencies = np.array([[1.0977,2.8912],
[4.9140,0.1120],
[8.1337,0.0424],
[11.3079,0.0224],
[14.4675,0.0140],
[17.6205,0.0096]])
Nanostructure.__init__(self,layers,radius,eigenfrequencies)
def DipolePolarizibility(self,omega,gamma,eFermi,T,order=None):
return Nanostructure.DipolePolarizibility(self,omega,gamma,eFermi,T,order)
def CrossSection(self,omega,gamma,eFermi,T,eps_medium,cstype):
return Nanostructure.CrossSection(self,omega,gamma,eFermi,T,eps_medium,cstype)
class Ellipse(Nanostructure):
'''
A class describing the properties of a elliptical pieces of graphene.
Currently only monolayer.
Parents
----------
BaseGraphene
layers (required argument. See Parameters below.)
Initialization Parameters
----------
radius: scalar, radius of circle
layers: class, graphene.Monolayer for 1 layer.
graphene.Bilayer for 2 layers.
'''
def __init__(self,layers,radius):
# Monolayer Graphene mode parameters
# Normalized to L=R
eigenfrequencies = np.array([[1.0977,2.8912],
[4.9140,0.1120],
[8.1337,0.0424],
[11.3079,0.0224],
[14.4675,0.0140],
[17.6205,0.0096]])
Nanostructure.__init__(self,layers,radius,eigenfrequencies)
def DipolePolarizibility(self,omega,gamma,eFermi,T,order=None):
return Nanostructure.DipolePolarizibility(self,omega,gamma,eFermi,T,order)
def CrossSection(self,omega,gamma,eFermi,T,eps_medium,cstype):
return Nanostructure.CrossSection(self,omega,gamma,eFermi,T,eps_medium,cstype)
class Rectangle(Nanostructure):
'''
A class describing the properties of a circular piece of graphene.
Currently only monolayer.
Parents
----------
BaseGraphene
layers (required argument. See Parameters below.)
Initialization Parameters
----------
radius: scalar, radius of circle
layers: class, graphene.Monolayer for 1 layer.
graphene.Bilayer for 2 layers.
'''
def __init__(self,radius,layers):
Nanostructure.__init__(self,layers)
if __name__=="__main__":
import doctest
doctest.testmod(verbose=False,optionflags=doctest.ELLIPSIS)
|
C++
|
UTF-8
| 420
| 2.90625
| 3
|
[] |
no_license
|
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
int t, n, x, k;
std::cin >> t;
while (t--)
{
std::cin >> n;
std::vector<int> v(n);
for (int i = 0; i < n; ++i)
{
std::cin >> v.at(i);
}
std::cin >> k;
int key = v.at(k - 1);
int count = std::count_if(v.begin(), v.end(), [&key] (int val) {return val < key;});
std::cout << count + 1 << std::endl;
}
return 0;
}
|
C#
|
UTF-8
| 375
| 2.671875
| 3
|
[] |
no_license
|
using System;
namespace StudioMobile
{
public partial struct Font : IDisposable
{
public System.Drawing.Font Native;
public Font(string name, float size)
{
Native = new System.Drawing.Font (name, size);
}
public static implicit operator System.Drawing.Font(Font f)
{
return f.Native;
}
public void Dispose()
{
Native.Dispose ();
}
}
}
|
Java
|
UTF-8
| 700
| 2.3125
| 2
|
[] |
no_license
|
package com.cc.tongxundi.utils;
import com.cc.tongxundi.bean.BaseBean;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.List;
/**
* Created by sjw on 2017/9/23.
*/
public class GsonManager {
public static <T> T fromJsonStr(String json, Class<T> c) {
Gson gson = new Gson();
return gson.fromJson(json, c);
}
public static String toJson(BaseBean bean) {
Gson gson = new Gson();
return gson.toJson(bean);
}
public static <T> List<T> fromJsonToList(String json, Type type) {
Gson gson = new Gson();
return gson.fromJson(json,
type);
}
}
|
C
|
UTF-8
| 1,283
| 2.65625
| 3
|
[] |
no_license
|
#include "prod_cons.h"
int main(int argc, char* argv[], char** envp)
{
pthread_t t_con, t_pro;
int s = -9;
sem_t sem_p, sem_c;
circ_q_t *q = 0;
arg_t arg;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int delay = 50000000;
arg.mutex = &mutex;
arg.delay = delay;
if(sem_init(&sem_p, 0, SIZE) == -1)
{
printf("error: sem_init prod\n");
return(-1);
}
if(sem_init(&sem_c, 0, 0) == -1)
{
printf("error: sem_init con\n");
return(-2);
}
arg.sem[0] = sem_p;
arg.sem[1] = sem_c;
if(!(q = CircQCreate()))
{
printf("error: CircQCreate()\n");
return(1);
}
arg.q = q;
s = pthread_create(&t_pro, NULL, TProd, &arg);
if(s)
{
printf("error: pthread_create pro\n");
return(2);
}
s = pthread_create(&t_con, NULL, TCon, &arg);
if(s)
{
printf("error: pthread_create \n");
return(3);
}
/*wait for thread to terminate */
s = pthread_join(t_con, NULL);
if(s)
{
printf("error: pthread_join t_con\n");
return(4);
}
s = pthread_join(t_pro, NULL);
if(s)
{
printf("error: pthread_join t_pro\n");
return(5);
}
CircQDestroy(q);
if(sem_destroy(&sem_c) == -1)
{
printf("error: sem_destroy sem_c\n");
return(6);
}
if(sem_destroy(&sem_p) == -1)
{
printf("error: sem_destroy sem_p\n");
return(7);
}
return(0);
}
|
Swift
|
UTF-8
| 3,948
| 2.78125
| 3
|
[] |
no_license
|
//
// ImageController.swift
// DropMusic
//
// Created by Angel Contreras on 10/12/16.
// Copyright © 2016 Angel Contreras. All rights reserved.
//
import Foundation
import UIKit
import MapKit
extension UIImage{
var circle: UIImage? {
let square = CGSize(width: min(size.width, size.height), height: min(size.width, size.height))
let imageView = UIImageView(frame: CGRect(origin: .zero, size: square))
imageView.contentMode = .scaleAspectFill
imageView.image = self
imageView.layer.cornerRadius = square.width/2
imageView.layer.masksToBounds = true
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
imageView.layer.render(in: context)
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
}
class ImageController{
static var cache: NSCache<NSString, UIImage> = {
var cache = NSCache<NSString, UIImage>()
cache.countLimit = 100
cache.totalCostLimit = 0
return cache
}()
static func fetchImage(withString url: String, with size: Double = 500, id: String? = nil, completion: @escaping (UIImage?) -> Void){
if var imageFromCache = cache.object(forKey: NSString(string: id ?? url)) {
if size != 500 {
imageFromCache = imageWith(image: imageFromCache, scaleToSize: CGSize(width: size, height: size))!
}
DispatchQueue.main.async {
completion(imageFromCache)
}
} else {
let urlNSString = NSString(string: url)
guard let url = URL(string: url) else { return }
NetworkController.performRequest(for: url, httpMethodString: "GET") { (data, error) in
guard let data = data else {completion(nil); return }
if let image = UIImage(data: data){
let resizedImage = imageWith(image: UIImage(data: data), scaleToSize: CGSize(width: size, height: size))
self.cache.setObject(image, forKey: NSString(string: id ?? String(urlNSString)))
DispatchQueue.main.async {
completion(resizedImage)
}
} else {
completion(nil)
}
}
}
}
static func getNewAnnotation(albumCover: UIImage?,with annotation: UIImage? = #imageLiteral(resourceName: "Annotation1x"), completion: @escaping (_ annotationImage: UIImage?)->Void) {
guard let albumCover = albumCover else {completion(nil); print("album cover was nil"); return}
guard let annotation = annotation else { completion(nil); print("annotation was nil"); return}
let size = annotation.size
UIGraphicsBeginImageContext(size)
let areaSize = CGRect(x: 0, y: 0, width: size.width, height: size.height)
annotation.draw(in: areaSize)
let albumCoverSize = CGRect(x: 11, y: 11, width: 79, height: 79)
albumCover.draw(in: albumCoverSize)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
let resizedImage = imageWith(image: newImage, scaleToSize: CGSize(width: 100, height: 100))
DispatchQueue.main.async {
completion(resizedImage)
}
}
static func imageWith(image: UIImage?, scaleToSize newSize: CGSize) -> UIImage?{
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
image?.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage
}
}
|
Markdown
|
UTF-8
| 1,149
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
# babel-plugin-remove-nonjs [](https://travis-ci.org/piglovesyou/babel-plugin-remove-nonjs)
Simply removes non-JS `require()` such as `require('./style.css')`, possibly resolved by Webpack with its ExtractTextPlugin.
## Example
It simply removes non-JS dependency.
```diff
require('fs');
require('./src/blaa');
- require('./src/blaa.css');
- require('./src/blaa.scss');
- require('./src/blaa.less');
- require('./src/yeah.jpg');
```
## Installation
```sh
$ npm install --save-dev babel-plugin-remove-nonjs
```
## Note
Because it also removes valiable declarations like `const style = require('./style.css')`, your code CANNOT depend on a returned value of the module.
If you want scoped CSS, try [css-loader](https://github.com/webpack/css-loader).
If you're looking for a more integrated solution of CSS, try [isomorphic-style-loader](https://github.com/kriasoft/isomorphic-style-loader).
## License
MIT
## Attribution
This package is originally published by [rickchristie](https://www.npmjs.com/~rickchristie) and I'm maintaining it.
|
Java
|
UTF-8
| 2,824
| 2.390625
| 2
|
[] |
no_license
|
package edu.utdallas.hltri.data.medline.jaxb;
import com.fasterxml.aalto.stax.InputFactoryImpl;
import com.google.common.collect.Streams;
import edu.utdallas.hltri.data.medline.jaxb.struct.PubmedArticle;
import edu.utdallas.hltri.data.medline.jaxb.struct.PubmedArticleSet;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.codehaus.stax2.XMLInputFactory2;
class JaxbMedlineParser {
private final XMLInputFactory2 factory;
private final Unmarshaller unmarshaller;
JaxbMedlineParser() {
this.factory = new InputFactoryImpl();
factory.configureForSpeed();
try {
final JAXBContext context = JAXBContext.newInstance("edu.utdallas.hltri.data.medline.jaxb.struct");
this.unmarshaller = context.createUnmarshaller();
} catch (JAXBException e) {
throw new RuntimeException(e);
}
}
List<PubmedArticle> parseXmlFile(final InputStream source) {
try {
final XMLStreamReader reader = factory.createXMLStreamReader(source);
final PubmedArticleSet articleSet = unmarshaller.unmarshal(reader, PubmedArticleSet.class).getValue();
reader.close();
return articleSet.getPubmedArticlesAndPubmedBookArticles().stream()
.filter(PubmedArticle.class::isInstance).map(PubmedArticle.class::cast)
.collect(Collectors.toList());
} catch (XMLStreamException | JAXBException e) {
throw new RuntimeException(e);
}
}
Stream<PubmedArticle> streamArticles(final InputStream source) {
try {
return Streams.stream(new Iterator<PubmedArticle>() {
final XMLStreamReader reader = factory.createXMLStreamReader(source);
@Override
public boolean hasNext() {
try {
while (reader.hasNext()) {
reader.next();
if (reader.getEventType() == XMLStreamConstants.START_ELEMENT &&
reader.getLocalName().equals("PubmedArticle")) {
return true;
}
}
reader.close();
return false;
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
}
@Override
public PubmedArticle next() {
try {
return unmarshaller.unmarshal(reader, PubmedArticle.class).getValue();
} catch (JAXBException e) {
throw new RuntimeException(e);
}
}
});
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
}
}
|
C#
|
UTF-8
| 4,413
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
namespace nboard
{
class PngStegoUtil
{
private string _key;
public PngStegoUtil()
{
if (!File.Exists("key.txt"))
{
File.WriteAllText("key.txt", "nano");
}
_key = File.ReadAllText("key.txt");
}
public void HideBytesInPng(Image innocuousBmp, string outputImageFileName, byte[] hiddenBytes)
{
hiddenBytes = ByteEncryptionUtil.EncryptSalsa20(hiddenBytes, _key);
byte[] hiddenLengthBytes = BitConverter.GetBytes(hiddenBytes.Length);
byte[] hiddenCombinedBytes = PngUtils.Combine(hiddenLengthBytes, hiddenBytes);
byte[] rgbComponents = PngUtils.RgbComponentsToBytes(innocuousBmp);
byte[] encodedRgbComponents = EncodeBytes(hiddenCombinedBytes, rgbComponents);
Bitmap encodedBmp = PngUtils.ByteArrayToBitmap(encodedRgbComponents, innocuousBmp.Width, innocuousBmp.Height);
encodedBmp.Save(outputImageFileName, ImageFormat.Png);
encodedBmp.Dispose();
innocuousBmp.Dispose();
}
public void HideBytesInPng(string inputImageFileName, string outputImageFileName, byte[] hiddenBytes)
{
hiddenBytes = ByteEncryptionUtil.EncryptSalsa20(hiddenBytes, _key);
byte[] hiddenLengthBytes = BitConverter.GetBytes(hiddenBytes.Length);
byte[] hiddenCombinedBytes = PngUtils.Combine(hiddenLengthBytes, hiddenBytes);
Image innocuousBmp = Image.FromFile(inputImageFileName);
byte[] rgbComponents = PngUtils.RgbComponentsToBytes(innocuousBmp);
byte[] encodedRgbComponents = EncodeBytes(hiddenCombinedBytes, rgbComponents);
Bitmap encodedBmp = PngUtils.ByteArrayToBitmap(encodedRgbComponents, innocuousBmp.Width, innocuousBmp.Height);
encodedBmp.Save(outputImageFileName, ImageFormat.Png);
encodedBmp.Dispose();
innocuousBmp.Dispose();
}
private static byte[] EncodeBytes(byte[] hiddenBytes, byte[] innocuousBytes)
{
BitArray hiddenBits = new BitArray(hiddenBytes);
byte[] encodedBitmapRgbComponents = new byte[innocuousBytes.Length];
for (int i = 0; i < innocuousBytes.Length; i++)
{
if (i < hiddenBits.Length)
{
byte evenByte = (byte)(innocuousBytes[i] - innocuousBytes[i] % 2);
encodedBitmapRgbComponents[i] = (byte)(evenByte + (hiddenBits[i] ? 1 : 0));
}
else
{
encodedBitmapRgbComponents[i] = innocuousBytes[i];
}
}
return encodedBitmapRgbComponents;
}
public byte[] ReadHiddenBytesFromPng(string imageFileName)
{
Bitmap loadedEncodedBmp = new Bitmap(imageFileName);
byte[] loadedEncodedRgbComponents = PngUtils.RgbComponentsToBytes(loadedEncodedBmp);
const int bytesInInt = 4;
byte[] loadedHiddenLengthBytes = DecodeBytes(loadedEncodedRgbComponents, 0, bytesInInt);
int loadedHiddenLength = BitConverter.ToInt32(loadedHiddenLengthBytes, 0);
byte[] loadedHiddenBytes = DecodeBytes(loadedEncodedRgbComponents, bytesInInt, loadedHiddenLength);
loadedEncodedBmp.Dispose();
return ByteEncryptionUtil.DecryptSalsa20(loadedHiddenBytes, _key);
}
private static byte[] DecodeBytes(byte[] innocuousLookingData, int byteIndex, int byteCount)
{
const int bitsInBytes = 8;
int bitCount = byteCount * bitsInBytes;
int bitIndex = byteIndex * bitsInBytes;
bool[] loadedHiddenBools = new bool[bitCount];
for (int i = 0; i < bitCount; i++)
{
loadedHiddenBools[i] = innocuousLookingData[i + bitIndex] % 2 == 1;
}
BitArray loadedHiddenBits = new BitArray(loadedHiddenBools);
byte[] loadedHiddenBytes = new byte[loadedHiddenBits.Length / bitsInBytes];
loadedHiddenBits.CopyTo(loadedHiddenBytes, 0);
return loadedHiddenBytes;
}
}
}
|
Java
|
UTF-8
| 34,343
| 1.5625
| 2
|
[] |
no_license
|
package com.kustomer.kustomersdk.API;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.kustomer.kustomersdk.DataSources.KUSChatMessagesDataSource;
import com.kustomer.kustomersdk.DataSources.KUSObjectDataSource;
import com.kustomer.kustomersdk.DataSources.KUSPaginatedDataSource;
import com.kustomer.kustomersdk.Enums.KUSRequestType;
import com.kustomer.kustomersdk.Helpers.KUSAudio;
import com.kustomer.kustomersdk.Helpers.KUSInvalidJsonException;
import com.kustomer.kustomersdk.Helpers.KUSLog;
import com.kustomer.kustomersdk.Interfaces.KUSObjectDataSourceListener;
import com.kustomer.kustomersdk.Interfaces.KUSPaginatedDataSourceListener;
import com.kustomer.kustomersdk.Interfaces.KUSRequestCompletionListener;
import com.kustomer.kustomersdk.Interfaces.KUSTypingStatusListener;
import com.kustomer.kustomersdk.Kustomer;
import com.kustomer.kustomersdk.Managers.KUSStatsManager;
import com.kustomer.kustomersdk.Models.KUSChatMessage;
import com.kustomer.kustomersdk.Models.KUSChatSession;
import com.kustomer.kustomersdk.Models.KUSChatSettings;
import com.kustomer.kustomersdk.Models.KUSModel;
import com.kustomer.kustomersdk.Models.KUSTrackingToken;
import com.kustomer.kustomersdk.Models.KUSTypingIndicator;
import com.kustomer.kustomersdk.Utils.KUSConstants;
import com.kustomer.kustomersdk.Utils.KUSJsonHelper;
import com.kustomer.kustomersdk.Views.KUSNotificationWindow;
import com.pusher.client.Pusher;
import com.pusher.client.PusherOptions;
import com.pusher.client.channel.PresenceChannel;
import com.pusher.client.channel.PresenceChannelEventListener;
import com.pusher.client.channel.PrivateChannel;
import com.pusher.client.channel.PrivateChannelEventListener;
import com.pusher.client.channel.User;
import com.pusher.client.connection.ConnectionEventListener;
import com.pusher.client.connection.ConnectionState;
import com.pusher.client.connection.ConnectionStateChange;
import com.pusher.client.util.HttpAuthorizer;
import org.json.JSONObject;
import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
/**
* Created by Junaid on 1/20/2018.
*/
public class KUSPushClient implements Serializable, KUSObjectDataSourceListener, KUSPaginatedDataSourceListener {
//region Properties
private static final long KUS_RETRY_DELAY = 1000;
private static final long KUS_SHOULD_CONNECT_TO_PUSHER_RECENCY_THRESHOLD = 60000;
private static final long LAZY_POLLING_TIMER_INTERVAL = 30000;
private static final long ACTIVE_POLLING_TIMER_INTERVAL = 7500;
private long currentPollingTimerInterval = 0;
private Pusher pusherClient;
private PresenceChannel pusherChannel;
private PrivateChannel chatActivityChannel;
private PresenceChannel customerPresenceChannel;
private ConcurrentHashMap<String, KUSChatSession> previousChatSessions;
private WeakReference<KUSUserSession> userSession;
private boolean isSupportScreenShown = false;
private Timer pollingTimer;
private String pendingNotificationSessionId;
private Handler handler;
private boolean isPusherTrackingStarted;
private boolean didPusherLostPackets;
@Nullable
private KUSTypingStatusListener typingStatusListener;
//endregion
//region LifeCycle
KUSPushClient(KUSUserSession userSession) {
this.userSession = new WeakReference<>(userSession);
isPusherTrackingStarted = false;
userSession.getChatSessionsDataSource().addListener(this);
userSession.getChatSettingsDataSource().addListener(this);
userSession.getTrackingTokenDataSource().addListener(this);
connectToChannelsIfNecessary();
}
//endregion
//region Public Methods
public void onClientActivityTick() {
// We only need to poll for client activity changes if we are not connected to the socket
if (pusherClient.getConnection().getState() != ConnectionState.CONNECTED || !pusherChannel.isSubscribed()) {
onPollTick();
}
}
public void removeAllListeners() {
if (pusherClient != null) {
String pusherChannelName = getPusherChannelName();
if (pusherChannelName != null)
pusherClient.unsubscribe(pusherChannelName);
pusherClient.disconnect();
pusherClient = null;
}
if (pollingTimer != null) {
pollingTimer.cancel();
pollingTimer = null;
}
if (handler != null) {
handler.removeCallbacks(null);
handler = null;
}
}
public void setTypingStatusListener(@Nullable KUSTypingStatusListener listener) {
typingStatusListener = listener;
}
public void removeTypingStatusListener() {
typingStatusListener = null;
}
public void connectToChatActivityChannel(@Nullable String activeChatSessionId) {
if (activeChatSessionId == null)
return;
disconnectFromChatActivityChannel();
try {
String activityChannelName = getChatActivityChannelNameForSessionId(activeChatSessionId);
if (activityChannelName != null) {
chatActivityChannel = pusherClient.subscribePrivate(activityChannelName);
chatActivityChannel.bind(KUSConstants.PusherEventNames.CHAT_ACTIVITY_TYPING_EVENT,
typingEventListener);
}
} catch (IllegalArgumentException e) {
KUSLog.KUSLogError(e.getMessage());
}
}
public void disconnectFromChatActivityChannel() {
if (chatActivityChannel != null) {
pusherClient.unsubscribe(chatActivityChannel.getName());
chatActivityChannel = null;
}
}
public void sendChatActivityForSessionId(@NonNull String sessionId, @NonNull String activityData) {
String activityChannelName = getChatActivityChannelNameForSessionId(sessionId);
try {
if (chatActivityChannel == null || !chatActivityChannel.getName().equals(activityChannelName))
chatActivityChannel = pusherClient.subscribePrivate(activityChannelName);
chatActivityChannel.trigger(KUSConstants.PusherEventNames.CHAT_ACTIVITY_TYPING_EVENT, activityData);
} catch (IllegalStateException ignore) {
} catch (IllegalArgumentException ignore) {
}
}
public void connectToCustomerPresenceChannel(@NonNull String customerId) {
if(null == customerPresenceChannel && null != pusherClient) {
try {
String presenceChannelName = getPresenceChannelNameForCustomerId(customerId);
KUSLog.KUSLogPusher("Connecting to presence channel : "+presenceChannelName);
if (presenceChannelName != null) {
customerPresenceChannel = pusherClient.subscribePresence(presenceChannelName);
}
} catch (IllegalArgumentException e) {
KUSLog.KUSLogError(e.getMessage());
}
}
}
public void disconnectFromCustomerPresenceChannel() {
if (null != customerPresenceChannel) {
KUSLog.KUSLogPusher("Disconnecting from presence channel");
pusherClient.unsubscribe(customerPresenceChannel.getName());
customerPresenceChannel = null;
}
}
//endregion
//region Private Methods
private URL getPusherAuthURL() {
return userSession.get().getRequestManager().urlForEndpoint(KUSConstants.URL.PUSHER_AUTH);
}
@Nullable
private String getPusherChannelName() {
if (userSession.get() == null)
return null;
KUSTrackingToken trackingTokenObj = (KUSTrackingToken) userSession.get()
.getTrackingTokenDataSource().getObject();
if (trackingTokenObj != null)
return String.format("presence-external-%s-tracking-%s", userSession.get().getOrgId(),
trackingTokenObj.getTrackingId());
return null;
}
@Nullable
private String getChatActivityChannelNameForSessionId(@NonNull String activeSessionId) {
if (userSession.get() == null)
return null;
return String.format("private-external-%s-chat-activity-%s", userSession.get().getOrgId(),
activeSessionId);
}
@Nullable
private String getPresenceChannelNameForCustomerId(@NonNull String customerId) {
if (userSession.get() == null)
return null;
return String.format("presence-external-%s-customer-activity-%s", userSession.get().getOrgId(),
customerId);
}
private void connectToChannelsIfNecessary() {
KUSChatSettings chatSettings = null;
if (userSession.get() != null)
chatSettings = (KUSChatSettings) userSession.get().getChatSettingsDataSource().getObject();
String trackingToken = userSession.get().getTrackingTokenDataSource().getCurrentTrackingToken();
if (pusherClient == null && chatSettings != null && chatSettings.getPusherAccessKey() != null && trackingToken!=null) {
HashMap<String, String> headers = new HashMap<>();
headers.put(KUSConstants.Keys.K_KUSTOMER_TRACKING_TOKEN_HEADER_KEY,trackingToken);
headers.putAll(userSession.get().getRequestManager().genericHTTPHeaderValues);
HttpAuthorizer authorizer = new HttpAuthorizer(getPusherAuthURL().toString());
authorizer.setHeaders(headers);
PusherOptions options = new PusherOptions().setEncrypted(true).setAuthorizer(authorizer);
pusherClient = new Pusher(chatSettings.getPusherAccessKey(), options);
}
boolean shouldConnectToPusher = pusherClient != null &&
pusherClient.getConnection().getState() != ConnectionState.CONNECTED;
if (shouldConnectToPusher) {
KUSLog.KUSLogPusher("Connecting to Pusher");
pusherClient.connect(pusherConnectionListener);
}
if (!isPusherTrackingStarted) {
isPusherTrackingStarted = true;
handler = new Handler(Looper.getMainLooper());
Runnable runnable = new Runnable() {
@Override
public void run() {
if (userSession.get() == null)
return;
isPusherTrackingStarted = false;
//Check if pusher is already connected
boolean isPusherConnected = pusherClient != null &&
pusherClient.getConnection().getState() == ConnectionState.CONNECTED;
if(!isPusherConnected) {
KUSLog.KUSLogPusher("Pusher not connected");
userSession.get().getStatsManager().updateStats(new KUSStatsManager.KUSStatsUpdatedListener() {
@Override
public void onCompletion(boolean sessionUpdated) {
if (userSession.get() == null)
return;
if (sessionUpdated) {
didPusherLostPackets = true;
userSession.get().getChatSessionsDataSource().fetchLatest();
}
connectToChannelsIfNecessary();
}
});
}else {
KUSLog.KUSLogPusher("Pusher is connected");
}
}
};
handler.postDelayed(runnable, KUS_SHOULD_CONNECT_TO_PUSHER_RECENCY_THRESHOLD);
}
String pusherChannelName = getPusherChannelName();
if (pusherClient != null && pusherChannelName != null && pusherChannel == null) {
try {
pusherChannel = pusherClient.subscribePresence(pusherChannelName);
pusherChannel.bind(KUSConstants.PusherEventNames.SEND_MESSAGE_EVENT, eventListener);
pusherChannel.bind(KUSConstants.PusherEventNames.END_SESSION_EVENT, eventListener);
} catch (IllegalArgumentException ignore) {
}
}
updatePollingTimer();
}
private void updatePollingTimer() {
boolean isPusherConnected = pusherClient != null &&
pusherClient.getConnection().getState() == ConnectionState.CONNECTED;
boolean isPusherSubscribed = pusherChannel != null && pusherChannel.isSubscribed();
if (isPusherConnected && isPusherSubscribed) {
//Stop Polling
if (pollingTimer != null) {
pollingTimer.cancel();
pollingTimer = null;
KUSLog.KUSLogPusher("Polling stopped");
}
} else {
if (isSupportScreenShown()) {
// We are not yet connected to pusher, setup an active polling pollingTimer
// (in the event that connecting to pusher fails)
if (pollingTimer == null || currentPollingTimerInterval != ACTIVE_POLLING_TIMER_INTERVAL) {
if (pollingTimer != null)
pollingTimer.cancel();
startTimer(ACTIVE_POLLING_TIMER_INTERVAL);
KUSLog.KUSLogPusher("Active Polling started with Time - "+ACTIVE_POLLING_TIMER_INTERVAL);
}
} else {
// Make sure we're polling lazily
if (pollingTimer == null || currentPollingTimerInterval != LAZY_POLLING_TIMER_INTERVAL) {
if (pollingTimer != null)
pollingTimer.cancel();
startTimer(LAZY_POLLING_TIMER_INTERVAL);
KUSLog.KUSLogPusher("Lazy Polling started with Time - "+LAZY_POLLING_TIMER_INTERVAL);
}
}
}
}
private void startTimer(long time) {
try {
if (pollingTimer != null)
pollingTimer.cancel();
currentPollingTimerInterval = time;
final Handler handler = new Handler();
pollingTimer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
onPollTick();
}
});
}
};
pollingTimer.schedule(doAsynchronousTask, time, time);
} catch (Exception ignore) {
}
}
private void onPollTick() {
if (userSession.get() == null)
return;
userSession.get().getStatsManager().updateStats(new KUSStatsManager.KUSStatsUpdatedListener() {
@Override
public void onCompletion(boolean sessionUpdated) {
if (userSession.get() != null && sessionUpdated)
userSession.get().getChatSessionsDataSource().fetchLatest();
}
});
}
private void notifyForUpdatedChatSession(String sessionId) {
if (isSupportScreenShown()) {
KUSAudio.playMessageReceivedSound();
} else {
KUSChatMessagesDataSource chatMessagesDataSource = userSession.get().chatMessageDataSourceForSessionId(sessionId);
if (chatMessagesDataSource == null)
return;
KUSChatMessage latestMessage = chatMessagesDataSource.getLatestMessage();
KUSChatSession chatSession = (KUSChatSession) userSession.get().getChatSessionsDataSource().findById(sessionId);
if (chatSession == null && latestMessage != null) {
try {
chatSession = KUSChatSession.tempSessionFromChatMessage(latestMessage);
} catch (KUSInvalidJsonException e) {
e.printStackTrace();
}
userSession.get().getChatSessionsDataSource().fetchLatest();
}
if (userSession.get().getDelegateProxy().shouldDisplayInAppNotification()
&& chatSession != null && latestMessage != null) {
boolean shouldAutoDismiss = latestMessage.getCampaignId() == null
|| latestMessage.getCampaignId().length() == 0;
//Sound is played by the notification itself
KUSNotificationWindow.getSharedInstance().showNotification(chatSession, Kustomer.getContext(), shouldAutoDismiss);
}
}
}
private void updatePreviousChatSessions() {
if (userSession.get() == null)
return;
previousChatSessions = new ConcurrentHashMap<>();
for (KUSModel model : userSession.get().getChatSessionsDataSource().getList()) {
KUSChatSession chatSession = (KUSChatSession) model;
previousChatSessions.put(chatSession.getId(), chatSession);
}
}
private void fetchChatMessageForId(@Nullable final String sessionId,
@Nullable final String messageId) {
if (userSession.get() == null)
return;
String endPoint = String.format(KUSConstants.URL.SINGLE_MESSAGE_ENDPOINT,
sessionId, messageId);
userSession.get().getRequestManager().performRequestType(
KUSRequestType.KUS_REQUEST_TYPE_GET,
endPoint,
null,
true,
new KUSRequestCompletionListener() {
@Override
public void onCompletion(final Error error, final JSONObject response) {
if (error != null) {
handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
fetchChatMessageForId(sessionId, messageId);
}
};
handler.postDelayed(runnable, KUS_RETRY_DELAY);
return;
}
if (response == null)
return;
upsertMessageAndNotify(response);
}
});
}
private void fetchEndedSessionForId(@Nullable final String endedSessionId) {
if (userSession.get() == null)
return;
String endPoint = KUSConstants.URL.CHAT_SESSIONS_ENDPOINT;
userSession.get().getRequestManager().performRequestType(
KUSRequestType.KUS_REQUEST_TYPE_GET,
endPoint,
null,
true,
new KUSRequestCompletionListener() {
@Override
public void onCompletion(final Error error, final JSONObject response) {
if (error != null) {
handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
fetchEndedSessionForId(endedSessionId);
}
};
handler.postDelayed(runnable, KUS_RETRY_DELAY);
return;
}
if (response == null)
return;
List<KUSModel> chatSessions = userSession.get().getChatSessionsDataSource()
.objectsFromJSONArray(KUSJsonHelper.arrayFromKeyPath(response, "data"));
if (chatSessions != null) {
for (KUSModel model : chatSessions) {
KUSChatSession session = (KUSChatSession) model;
if (session.getId().equals(endedSessionId)) {
upsertEndedSessionAndNotify(Collections.singletonList((KUSModel) session));
}
}
}
}
});
}
private void upsertMessageAndNotify(@NonNull JSONObject jsonObject) {
if (userSession.get() == null)
return;
final List<KUSModel> chatMessages = KUSJsonHelper.kusChatModelsFromJSON(Kustomer.getContext(),
KUSJsonHelper.jsonObjectFromKeyPath(jsonObject, "data"));
if (chatMessages == null || chatMessages.isEmpty())
return;
final KUSChatMessage chatMessage = (KUSChatMessage) chatMessages.get(0);
final KUSChatMessagesDataSource messagesDataSource = userSession.get()
.chatMessageDataSourceForSessionId(chatMessage.getSessionId());
final boolean doesNotAlreadyContainMessage = messagesDataSource == null ||
messagesDataSource.findById(chatMessage.getId()) == null;
if (messagesDataSource != null)
messagesDataSource.upsertNewMessages(chatMessages);
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
if (doesNotAlreadyContainMessage)
notifyForUpdatedChatSession(chatMessage.getSessionId());
}
});
}
private void upsertEndedSessionAndNotify(@Nullable List<KUSModel> chatSessions) {
if (userSession.get() == null || chatSessions == null || chatSessions.isEmpty()) {
return;
}
userSession.get().getChatSessionsDataSource().upsertNewSessions(chatSessions);
KUSChatSettings settings = (KUSChatSettings) userSession.get()
.getChatSettingsDataSource().getObject();
if (settings != null && settings.getSingleSessionChat()) {
for (KUSModel model : userSession.get().getChatSessionsDataSource().getList()) {
KUSChatSession session = (KUSChatSession) model;
KUSChatMessagesDataSource messagesDataSource = userSession.get()
.chatMessageDataSourceForSessionId(session.getId());
if (messagesDataSource != null)
messagesDataSource.notifyAnnouncersChatHasEnded();
}
} else {
KUSChatSession chatSession = (KUSChatSession) chatSessions.get(0);
KUSChatMessagesDataSource messagesDataSource = userSession.get()
.chatMessageDataSourceForSessionId(chatSession.getId());
if (messagesDataSource != null)
messagesDataSource.notifyAnnouncersChatHasEnded();
}
}
private void onPusherChatMessageSend(String data) {
JSONObject jsonObject = KUSJsonHelper.stringToJson(data);
if (jsonObject == null)
return;
boolean isMessageClipped = jsonObject.optBoolean("clipped");
if (isMessageClipped) {
String sessionId = KUSJsonHelper.stringFromKeyPath(jsonObject,
"data.relationships.session.data.id");
String messageId = KUSJsonHelper.stringFromKeyPath(jsonObject, "data.id");
KUSChatMessagesDataSource messagesDataSource = userSession.get()
.chatMessageDataSourceForSessionId(sessionId);
boolean doesNotAlreadyContainMessage = messagesDataSource == null ||
messagesDataSource.findById(messageId) == null;
if (doesNotAlreadyContainMessage)
fetchChatMessageForId(sessionId, messageId);
} else {
upsertMessageAndNotify(jsonObject);
}
}
private void onPusherChatSessionEnd(String data) {
JSONObject jsonObject = KUSJsonHelper.stringToJson(data);
if (jsonObject == null)
return;
boolean isMessageClipped = jsonObject.optBoolean("clipped");
if (isMessageClipped) {
String sessionId = KUSJsonHelper.stringFromKeyPath(jsonObject, "data.id");
fetchEndedSessionForId(sessionId);
} else {
List<KUSModel> chatSessions = userSession.get().getChatSessionsDataSource()
.objectsFromJSON(KUSJsonHelper.jsonObjectFromKeyPath(jsonObject, "data"));
upsertEndedSessionAndNotify(chatSessions);
}
}
//endregion
//region Accessors
private boolean isSupportScreenShown() {
return isSupportScreenShown;
}
public void setSupportScreenShown(boolean supportScreenShown) {
isSupportScreenShown = supportScreenShown;
connectToChannelsIfNecessary();
}
//endregion
//region Callbacks
@Override
public void objectDataSourceOnLoad(KUSObjectDataSource dataSource) {
if (!userSession.get().getChatSessionsDataSource().isFetched())
userSession.get().getChatSessionsDataSource().fetchLatest();
Handler handler = new Handler(Looper.getMainLooper());
Runnable runnable = new Runnable() {
@Override
public void run() {
connectToChannelsIfNecessary();
}
};
handler.post(runnable);
}
@Override
public void objectDataSourceOnError(KUSObjectDataSource dataSource, Error error) {
}
@Override
public void onLoad(KUSPaginatedDataSource dataSource) {
updatePreviousChatSessions();
if (dataSource instanceof KUSChatMessagesDataSource) {
KUSChatMessagesDataSource chatMessagesDataSource = (KUSChatMessagesDataSource) dataSource;
if (pendingNotificationSessionId != null && !pendingNotificationSessionId.isEmpty()
&& chatMessagesDataSource.getSessionId().equals(pendingNotificationSessionId)) {
Handler handler = new Handler(Looper.getMainLooper());
Runnable runnable = new Runnable() {
@Override
public void run() {
notifyForUpdatedChatSession(pendingNotificationSessionId);
pendingNotificationSessionId = null;
}
};
handler.post(runnable);
}
}
Handler handler = new Handler(Looper.getMainLooper());
Runnable runnable = new Runnable() {
@Override
public void run() {
connectToChannelsIfNecessary();
}
};
handler.post(runnable);
}
@Override
public void onError(KUSPaginatedDataSource dataSource, Error error) {
if (dataSource instanceof KUSChatMessagesDataSource) {
KUSChatMessagesDataSource chatMessagesDataSource = (KUSChatMessagesDataSource) dataSource;
if (chatMessagesDataSource.getSessionId().equals(pendingNotificationSessionId)) {
Handler handler = new Handler(Looper.getMainLooper());
Runnable runnable = new Runnable() {
@Override
public void run() {
notifyForUpdatedChatSession(pendingNotificationSessionId);
pendingNotificationSessionId = null;
}
};
handler.post(runnable);
}
} else if (userSession.get() != null && dataSource == userSession.get().getChatSessionsDataSource()) {
new Timer().schedule(new TimerTask() {
@Override
public void run() {
userSession.get().getChatSessionsDataSource().fetchLatest();
}
}, KUS_RETRY_DELAY);
}
}
@Override
public void onContentChange(final KUSPaginatedDataSource dataSource) {
if (userSession.get() == null || dataSource != userSession.get().getChatSessionsDataSource())
return;
// Only consider new messages here if we're actively polling
if (pollingTimer == null && !didPusherLostPackets) {
//But update the state of previousChatSessions
updatePreviousChatSessions();
return;
}
didPusherLostPackets = false;
String updatedSessionId = null;
List<KUSModel> newChatSessions = userSession.get().getChatSessionsDataSource().getList();
for (KUSModel model : newChatSessions) {
KUSChatSession chatSession = (KUSChatSession) model;
KUSChatSession previousChatSession = null;
if (previousChatSessions != null)
previousChatSession = previousChatSessions.get(chatSession.getId());
KUSChatMessagesDataSource messagesDataSource = userSession.get().chatMessageDataSourceForSessionId(chatSession.getId());
if (previousChatSession != null) {
try {
boolean isUpdatedSession = previousChatSession.getLastMessageAt() == null
|| (chatSession.getLastMessageAt() != null
&& chatSession.getLastMessageAt().after(previousChatSession.getLastMessageAt()));
boolean chatSessionSetToLock = chatSession.getLockedAt() != null
&& !chatSession.getLockedAt().equals(previousChatSession.getLockedAt());
// Check that new message arrived or not
if (isUpdatedSession && messagesDataSource.isLatestMessageAfterLastSeen()) {
updatedSessionId = chatSession.getId();
messagesDataSource.addListener(KUSPushClient.this);
messagesDataSource.fetchLatest();
} else if (chatSessionSetToLock) { // Check that session lock state changed
messagesDataSource.fetchLatest();
}
} catch (Exception ignore) {
}
} else if (previousChatSessions != null) {
if (messagesDataSource.isLatestMessageAfterLastSeen())
updatedSessionId = chatSession.getId();
messagesDataSource.addListener(KUSPushClient.this);
messagesDataSource.fetchLatest();
}
}
updatePreviousChatSessions();
if (updatedSessionId != null) {
pendingNotificationSessionId = updatedSessionId;
}
}
private PresenceChannelEventListener eventListener = new PresenceChannelEventListener() {
@Override
public void onUsersInformationReceived(String channelName, Set<User> users) {
}
@Override
public void userSubscribed(String channelName, User user) {
KUSLog.KUSLogPusher("User Added "+channelName);
}
@Override
public void userUnsubscribed(String channelName, User user) {
KUSLog.KUSLogPusher("User Removed "+channelName);
}
@Override
public void onAuthenticationFailure(String message, Exception e) {
KUSLog.KUSLogPusher("User Failure "+message);
updatePollingTimer();
}
@Override
public void onSubscriptionSucceeded(String channelName) {
KUSLog.KUSLogPusher("User subscribed "+channelName);
updatePollingTimer();
}
@Override
public void onEvent(String channelName, String eventName, String data) {
KUSLog.KUSLogPusher("Presence onEvent "+eventName);
if (userSession.get() == null || eventName == null)
return;
if (eventName.equals(KUSConstants.PusherEventNames.SEND_MESSAGE_EVENT)) {
onPusherChatMessageSend(data);
} else if (eventName.equals(KUSConstants.PusherEventNames.END_SESSION_EVENT)) {
onPusherChatSessionEnd(data);
}
}
};
private PrivateChannelEventListener typingEventListener = new PrivateChannelEventListener() {
@Override
public void onAuthenticationFailure(String message, Exception e) {
KUSLog.KUSLogPusher("User Authentication Failure "+message);
}
@Override
public void onSubscriptionSucceeded(String channelName) {
KUSLog.KUSLogPusher("User Subscription Succeeded "+channelName);
}
@Override
public void onEvent(String channelName, String eventName, String data) {
KUSLog.KUSLogPusher("Private onEvent "+eventName);
JSONObject jsonObject = KUSJsonHelper.stringToJson(data);
if (jsonObject == null)
return;
try {
if (typingStatusListener != null)
typingStatusListener.onTypingStatusChanged(new KUSTypingIndicator(jsonObject));
} catch (KUSInvalidJsonException e) {
KUSLog.KUSLogError(e.getMessage());
}
}
};
private ConnectionEventListener pusherConnectionListener = new ConnectionEventListener() {
@Override
public void onConnectionStateChange(ConnectionStateChange change) {
KUSLog.KUSLogPusher("User onConnectionStateChange "+change.getCurrentState().name());
switch (change.getCurrentState()) {
case CONNECTED:
if(didPusherLostPackets){
onPollTick();
}
break;
case DISCONNECTED:
didPusherLostPackets = true;
break;
default:
break;
}
updatePollingTimer();
}
@Override
public void onError(String message, String code, Exception e) {
KUSLog.KUSLogPusher("User ConnectionEvent Error "+message);
updatePollingTimer();
}
};
//endregion
}
|
Java
|
UTF-8
| 1,211
| 2.6875
| 3
|
[] |
no_license
|
package cn.itsource.gogou.util;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
/**
*
* @author yun
*/
public enum JedisUtils {
INSTANCE;
private static JedisPool pool;
static {
//创建配置文件对象
JedisPoolConfig config = new JedisPoolConfig();
config.setMinIdle(10);
config.setMaxTotal(20);
config.setMaxIdle(5);
//最大等待时间
config.setMaxWaitMillis(2*1000);
//获取连接时测试连接是否畅通
config.setTestOnBorrow(true);
//对象空闲多久后逐出, 当空闲时间>该值 且 空闲连接>最大空闲数 时直接逐出,不再根据MinEvictableIdleTimeMillis判断 (默认逐出策略)
config.setSoftMinEvictableIdleTimeMillis(800000);
//创建连接池对象
pool = new JedisPool(config,"127.0.0.1",6379, 6000, "itsource");
}
/**
* @return
*/
//获取连接对象
public Jedis getJedis(){
return pool.getResource();
}
//关闭资源
public void close(Jedis jedis){
if (jedis != null) {
jedis.close();
}
}
}
|
Java
|
UTF-8
| 4,529
| 2.53125
| 3
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package servlets;
import business.Course;
import business.CourseDB;
import business.Section;
import business.SectionDB;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author tom
*/
public class DisplaySectionsServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String URL = "/DisplaySections.jsp", msg ="";
List<Section> sections = new ArrayList();
List<Section> sectionsInSearch = null;
String[] courseIDs;
List<Course> courses;
/*
This servlet is currently incomplete.
Sections always return null in its current state.
I think it may have something to do with the way the Entity classes
are designed ( I don't think i quite have the joins correctly set up )
*/
try {
courseIDs = request.getParameterValues("checked");
//if there are sections on session from advanced search, get them
if (request.getSession().getAttribute("sectionsInSearch") != null) {
sectionsInSearch = (List<Section>) request.getSession().getAttribute("sectionsInSearch");
request.getSession().setAttribute("courseIDs", courseIDs);
//for each section in sectionsInSearch,
// run through selected courseIDs and see if
// they match. if the courseID matches, add
// section to sections to be displayed
for (Section sec : sectionsInSearch) {
for (String id : courseIDs) {
if (sec.getCourseId().equals(id)) {
sections.add(sec);
}
}
}
} else {
request.getSession().setAttribute("courseIDs", courseIDs);
sections = SectionDB.getSections(courseIDs);
}
if (!sections.isEmpty()) {
request.getSession().setAttribute("sections", sections);
} else {
msg = "Sections returned null";
URL = "/DisplaySections.jsp";
}
} catch(Exception e) {
msg = "Display Section servlet error: " + e.getMessage();
URL = "/DisplaySections.jsp";
}
request.setAttribute("msg", msg);
RequestDispatcher disp = getServletContext().getRequestDispatcher(URL);
disp.forward(request, response);
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
C++
|
UTF-8
| 3,406
| 2.515625
| 3
|
[] |
no_license
|
#include "game_sound_manager.h"
#define CHUNKSIZE 2048
#define CHANNELS 4
#define FREQUENCY 44100
#define DEFAULT_CHANNEL 0
GameSoundManager::GameSoundManager() {
int flags = MIX_INIT_FLAC;
int result = 0;
Mix_OpenAudio(FREQUENCY, MIX_DEFAULT_FORMAT, CHANNELS, CHUNKSIZE);
if (flags != (result = Mix_Init(flags))) {
Mix_CloseAudio();
printf("Could not initialize mixer (result: %d).\n", result);
throw SoundException(Mix_GetError());
}
initSounds();
initMusic();
}
void GameSoundManager::initMusic() {
std::string path_music = "../client/resources/audio/got.mp3";
music = Mix_LoadMUS(path_music.data());
if (music == NULL) {
Mix_CloseAudio();
for (auto const& chunk : chunkMap) {
Mix_FreeChunk(chunk.second);
}
std::string error_msg = "\nError: Could not load .mp3 file: ";
throw SoundException(error_msg + path_music);
}
Mix_PlayMusic(music, -1);
musicOn = true;
}
void GameSoundManager::initSounds() {
std::string path_sword = "../client/resources/audio/sword.wav";
std::string path_explosion = "../client/resources/audio/explosion.wav";
std::string path_melee = "../client/resources/audio/melee.wav";
std::string path_magic_strike = "../client/resources/audio/shot.mp3";
std::string path_arrow_strike = "../client/resources/audio/arrow.mp3";
std::string path_heal = "../client/resources/audio/flute.wav";
std::string path_axe = "../client/resources/audio/axe.mp3";
std::string path_hammer = "../client/resources/audio/hammer.mp3";
std::string path_list = "../client/resources/audio/list.mp3";
addNewSound(path_melee, PLAYER_PUNCH);
addNewSound(path_melee, CREATURE_PUNCH);
addNewSound(path_hammer, HAMMER_STRIKE);
addNewSound(path_axe, AXE_STRIKE);
addNewSound(path_arrow_strike, ARROW_STRIKE);
addNewSound(path_sword, SWORD_STRIKE);
addNewSound(path_magic_strike, MAGIC_STRIKE);
addNewSound(path_explosion, EXPLOSION);
addNewSound(path_heal, HEAL_STRIKE);
addNewSound(path_list, LIST);
soundOn = true;
}
void GameSoundManager::addNewSound(std::string path, soundType type) {
Mix_Chunk* sound = Mix_LoadWAV(path.data());
if (sound == NULL) {
std::string error_msg ="\nError: Could not load .wav file: ";
throw SoundException(error_msg + path);
}
chunkMap.insert({type, sound});
}
GameSoundManager::~GameSoundManager() {
for (auto const& chunk : chunkMap) {
Mix_FreeChunk(chunk.second);
}
Mix_FreeMusic(music);
Mix_CloseAudio();
Mix_Quit();
SDL_AudioQuit();
}
void GameSoundManager::playSound(soundType sound) {
if (Mix_Playing(-1) != 0 || not soundOn) return;
//en caso sonido aun no implementado no queremos que rompa
if (chunkMap.find(sound) == chunkMap.end()) return;
if (Mix_PlayChannel(-1, chunkMap.at(sound), 0) == -1) {
throw SoundException("\nError: Could not play wav file on channel");
}
}
void GameSoundManager::toggleSound() {
if (soundOn) {
for (int i = 0; i < CHANNELS; i++) {
Mix_Pause(i);
}
soundOn = false;
} else {
soundOn = true;
}
}
void GameSoundManager::toggleMusic() {
if (musicOn) {
Mix_PauseMusic();
musicOn = false;
} else {
Mix_ResumeMusic();
musicOn = true;
}
}
|
JavaScript
|
UTF-8
| 105
| 2.734375
| 3
|
[] |
no_license
|
let operando1 = 23
let operando1 = 33
console.log (operando1)
// no, por que let no se puede redifinir
|
C
|
UTF-8
| 335
| 3.140625
| 3
|
[] |
no_license
|
#include<pthread.h>
#include<stdio.h>
void *display_name(void *a)
{
printf("\nTHREAD Operation:%d\n",pthread_self());
pthread_exit((void*)&a);
}
void main()
{
int i=0;
void *retval;
pthread_t t;
for(i=0;i<5;i++)
{
pthread_create(&t,NULL,&display_name,NULL);
pthread_join(t,&retval);
}
//printf("\nMAIN FUNCTION:%d\n",*(int*)retval);
}
|
Python
|
UTF-8
| 758
| 4.65625
| 5
|
[] |
no_license
|
"""
Create a string variable that is assigned the following sentence:
“Zeven Zottegemse zotten zullen zes zomerse zondagen zwemmen zonder zwembroek.”
a.Count the number of words in that sentence. Hint: strings have the methodsplit()that returns a list with each word of that sentence as an element. len(mylist)returns the length of your list.
b.Replace for every word the first letter by a ‘p’. Hint: the string type has the methodreplace(old,new), which replaces a substring oldwith another substringsubstring new. Be careful: this method is case sensitive!
"""
s = "zeven zottegemse zotten zullen zes zomerse zondagen zwemmen zonder zwembroek"
sarray = s.split()
for index,s in enumerate(sarray):
sarray[index]= sarray[index].replace('z','p')
print(sarray)
|
Java
|
UTF-8
| 2,721
| 1.929688
| 2
|
[] |
no_license
|
package com.ko30.quartz.job.lottery.grabdata;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONObject;
import com.ko30.common.base.entity.quartz.QuartzParamInfo;
import com.ko30.common.util.AssertValue;
import com.ko30.common.util.SpringUtils;
import com.ko30.constant.enums.quartz.QuartzHandlerType;
import com.ko30.quartz.core.handler.QuartzHandler;
import com.ko30.quartz.core.handler.QuartzHandlerFactory;
import com.ko30.quartz.service.GrabGaopinLotteryHistoryDataService;
/**
*
* @ClassName: GaopinLotteryQuartzHandler
* @Description: 抓取 高频 彩 历史数据定时任务实现
* @author A18ccms a18ccms_gmail_com
* @date 2017年9月1日 下午5:23:20
*
*/
@Service
public class GaopinLotteryQuartzHandler implements QuartzHandler {
private Logger logger = Logger.getLogger(GaopinLotteryQuartzHandler.class);
private GrabGaopinLotteryHistoryDataService dataService;
// private GrabOpenResultService<?> grabResult;
public GaopinLotteryQuartzHandler() {
dataService = SpringUtils.getBean(GrabGaopinLotteryHistoryDataService.class);
// grabResult = SpringUtils.getBean(GrabOpenResultService.class);
}
@Override
public Map<String, String> handler(JSONObject data) {
//grabResult.getQuanguoLotteryHistory(null, null);
Map<String, Object> map=JSONObject.parseObject(data.toString(), HashMap.class);
try {
if (AssertValue.isNotNull(map)) {
dataService.grabGaopinLotteryHistory(map);
// 5分钟后再次执行
map.clear();
List<Map<String, Object>> urls=dataService.getUrls();
for (int i = 0; i < urls.size(); i++) {
String currentLotCodeStr=map.get("lotCode").toString();
Map<String, Object> tempMap=urls.get(i);
String nextLotCode=tempMap.get("lotCode").toString();
if (currentLotCodeStr.equals(nextLotCode)) {
map = urls.get(i);
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}finally{
QuartzParamInfo info = new QuartzParamInfo();
info.setExecuteKey(QuartzHandlerType.GRAB_GAO_PIN_HISTORY.getType());
info.setParamObj(map);
Calendar cal=Calendar.getInstance();
cal.add(Calendar.HOUR_OF_DAY, 4);// 4小时后执行
QuartzHandlerFactory factory = SpringUtils.getBean(QuartzHandlerFactory.class);
factory.executeHandler(QuartzHandlerType.GRAB_GAO_PIN_HISTORY, info,cal.getTime());
}
return null;
}
@Override
public QuartzHandlerType getType() {
return QuartzHandlerType.GRAB_GAO_PIN_HISTORY;
}
@Override
public String getDescription() {
return QuartzHandlerType.GRAB_GAO_PIN_HISTORY.getName();
}
}
|
JavaScript
|
UTF-8
| 989
| 3.765625
| 4
|
[] |
no_license
|
// this is what you would do if you were one to do things the easy way:
// var parseJSON = JSON.parse;
// but you're not, so you'll write it from scratch:
var parseJSON = function(json) {
// your code goes here
var obj = {};
if (typeof json === null) {
return null;
}
if (typeof json === 'number' || typeof json === 'boolean') {
return json;
}
if (typeof json === 'string') {
var trimJson = json.trim();
if (trimJson[0] === '[' && trimJson[trimJson.length - 1] === ']') {
var arr = trimJson.slice(1, trimJson.length - 2).split(',');
for (var i = 0; i < arr.length; i++) {
parseJSON(arr[i]);
}
return arr;
}
if (trimJson[0] === '{' && trimJson[trimJson.length - 1] === '}') {
var arr = trimJson.slice(1, trimJson.length - 2).split(',');
var obj = {};
for (var i = 0; i < arr.length; i++) {
parseJSON(arr[i]);
//split key and values
}
}
}
//
};
|
JavaScript
|
UTF-8
| 1,895
| 2.625
| 3
|
[] |
no_license
|
import React from 'react';
import axios from 'axios';
import List from './components/List';
const BASE_URL = 'http://hn.algolia.com/api/v1';
const PATH_SEARCH = '/search';
const PARAM_QUERY = 'query=';
const DEFAULT_QUERY = 'javascript';
const withLoadingIndicator = (Component) => {
const EnhancedComponent = ({isLoading, ...props}) => {
if(!isLoading) return <Component {...props}/>
return <div><p style={{textAlign: 'center'}}>Loading...</p></div>;
};
return EnhancedComponent;
};
const withErrorIndicator = (Component) => {
const EnhancedComponent = ({isError, ...props}) => {
if(!isError) return <Component {...props}/>;
return <div><p style={{textAlign: 'center'}}>Error loading data.</p></div>
};
return EnhancedComponent;
};
const ListWithLoadingIndicator = withLoadingIndicator(List);
const ListWithLoadingAndErrorIndicator = withErrorIndicator(ListWithLoadingIndicator)
class ConditionalApp extends React.Component {
state = {
data: [],
isLoading: false,
isError: false
};
fetchData = async (query = DEFAULT_QUERY) => {
const queryString = `${BASE_URL}${PATH_SEARCH}?${PARAM_QUERY}${query}`;
const response = await axios(queryString);
const data = await response.data;
return data;
};
componentDidMount = () => {
this.setState({
isLoading: true
});
this.fetchData()
.then(data => {
this.setState({
data: data.hits,
isLoading: false
});
})
.catch(e => {
this.setState({
isError: true
});
console.log(e);
});
};
render = () => {
const {
data,
isLoading,
isError
} = this.state;
return (
<ListWithLoadingAndErrorIndicator
isLoading={isLoading}
isError={isError}
data={data}
/>
);
};
}
export default ConditionalApp;
|
Python
|
UTF-8
| 646
| 2.578125
| 3
|
[] |
no_license
|
import pandas as pd
from sklearn.metrics import davies_bouldin_score, silhouette_score
from sklearn.cluster import KMeans
from sklearn.model_selection import train_test_split
if __name__ == '__main__':
headers = ['stg', 'scg', 'str', 'lpr', 'peg', 'uns']
df = pd.read_csv('dataset/data_user_modeling.csv', header=None, names=headers)
kmeans = KMeans(n_clusters=4, random_state=None)
kmeans.fit(df[headers[:-1]])
# for idx, row in enumerate(df['uns']):
# print(row, kmeans.labels_[idx])
print(davies_bouldin_score(df[headers[:-1]], kmeans.labels_))
print(silhouette_score(df[headers[:-1]], kmeans.labels_))
|
C
|
UTF-8
| 3,181
| 3.484375
| 3
|
[] |
no_license
|
/****************************************************************************
* \brief Console
* \copyright 2018-2019, Zhejiang University, Program Design Project, Group 6.
* \verson 1.2
* \author Chenyun Lu
* \file Polynomial_Interact.c
*
* \date 2019/03/25 Fang :created
****************************************************************************/
#include "Polynomial_Interact.h"
extern void init()
{
Poterm Head = PolyIdentify("0");
int32_t x = 2;
char_t str[1000];
bool_t j = False;
printf( "Input the first Polynomial\n" );
while ( x != 0 ) //exit if zero inputed
{
switch ( x )
{
case 1: //clear
printf( "Polynomial clear\n" );
Head = MULTIPLY( Head, PolyIdentify( "0" ) );
output( Head );
break;
case 2:
if ( j == True ) //judge whether a polynomial has been inputed
printf( "Input the Polynomial to be added\n" );
else j = True;
scanf("%s",str);
Head = ADD( Head, PolyIdentify(str) ); //add
output( Head );
break;
case 3:
printf( "Input the Polynomial to be substracted\n" );
scanf("%s",str);
Head = SUBSTRACT( Head, PolyIdentify(str) ); //substract
output( Head );
break;
case 4:
printf( "Input the Polynomial to be multiplied\n" );
scanf("%s",str);
Head = MULTIPLY( Head, PolyIdentify(str) ); //multiply
output( Head );
break;
case 5:
output(Head); //output
break;
case 0:
break;
default:
Head = MULTIPLY( Head, PolyIdentify( "0" ) ); //clear
Head = ADD( Head, PolyIdentify(str) ); //change into the newly inputed polynomial
output( Head );
break;
}
if ( x != 0 ) output_guide(); //output the guide
scanf("%s",str); //scanf the option
x = str[ 0 ] - '0' + str[ 1 ];
}
}
static void output_guide()
{
printf("--------------------------------------\n");
printf("Input the numbers\n");
printf("1-Polynomial Clear\n");
printf("2-Polynomial Addition(+)\n");
printf("3-Polynomial Substraction(-)\n");
printf("4-Polynomial Multiplication(*)\n");
printf("5-Polynomial Output\n");
printf("0-Exit\n");
printf("--------------------------------------\n");
}
static void output(Poterm t)
{
Poterm first_term;
first_term = t = t->next;
printf("Result:") ;
if(t == NULL) printf( "0" );
while ( t != NULL )
{
if ( t != first_term && t->co > 0 )
printf( "+" );
else if ( t->co == -1 )
printf( "-" ); //print the operator
if ( t->co != 1 && t->co != -1 )
printf( "%.1lf", t->co ); //print the coefficient
if ( t->x != 0 ) //exceptional case:the power of x is zero or one
{
printf( "x" );
if ( t->x != 1 ) printf( t->x < 0 ? "^(%d)" : "^%d", t->x );
}
if ( t->y != 0 ) //exceptional case:the power of y is zero or one
{
printf( "y" );
if ( t->y != 1 ) printf( t->y < 0 ? "^(%d)" : "^%d", t->y );
}
t = t->next;
}
printf( "\n" );
}
|
Python
|
UTF-8
| 5,248
| 2.65625
| 3
|
[] |
no_license
|
import random
from collections import deque
import numpy as np
import tensorflow as tf
import keras.backend as K
from keras.models import Sequential
from keras.models import load_model, clone_model
from keras.layers import Dense
from keras.optimizers import Adam
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math
import scipy
from scipy.stats import logistic
PATH = '../input/btcxbt/bitstamp_15-min_wo_nan.csv'
df = pd.read_csv(PATH)
data = df['Close'].tolist()
btc_vol = df['Volume_(BTC)'].tolist()
btc_ini_balance = btc_vol[0]
class DQNAgent:
def __init__(self, state_size, action_size=3):
self.state_size = state_size
self.action_size = action_size
self.memory = deque(maxlen=300)
self.gamma = 0.95 # discount rate
self.epsilon = 1.0 # exploration rate
self.epsilon_min = 0.01
self.epsilon_decay = 1e-3
self.learning_rate = 0.003
self.model = self._build_model()
self.target_model = self._build_model()
self.update_target_model()
self.start_reduce_epsilon = 200
def _huber_loss(self, y_true, y_pred, clip_delta=1.0):
error = y_true - y_pred
cond = K.abs(error) <= clip_delta
squared_loss = 0.5 * K.square(error)
quadratic_loss = 0.5 * K.square(clip_delta) + clip_delta * (K.abs(error) - clip_delta)
return K.mean(tf.where(cond, squared_loss, quadratic_loss))
def _build_model(self):
# Neural Net for Deep-Q learning Model
model = Sequential()
#model.add(LSTM(64,
#input_shape=(1,4),
#return_sequences=False,
# stateful=False
# ))
model.add(Dense(24, input_dim=self.state_size, activation='relu'))
model.add(Dense(48, activation='relu'))
model.add(Dense(24, activation='relu'))
model.add(Dense(self.action_size, activation='linear'))
model.compile(loss=self._huber_loss,
optimizer=Adam(lr=self.learning_rate))
return model
def update_target_model(self):
# copy weights from model to target_model
self.target_model.set_weights(self.model.get_weights())
def remember(self, state, action, reward, next_state, done):
self.memory.append((state, action, reward, next_state, done))
def act(self, state):
if np.random.rand() <= self.epsilon:
return random.randrange(self.action_size)
act_values = self.model.predict(state)
return np.argmax(act_values[0]) # returns action
def replay(self, batch_size):
minibatch = random.sample(self.memory, batch_size)
for state, action, reward, next_state, done in minibatch:
target = self.model.predict(state)
if done:
target[0][action] = reward
else:
t = self.target_model.predict(next_state)[0]
target[0][action] = reward + self.gamma * np.amax(t)
self.model.fit(state, target, epochs=1, verbose=0)
def update_epsilon(self, total_step):
if self.epsilon > self.epsilon_min and total_step > self.start_reduce_epsilon:
self.epsilon -= self.epsilon_decay
def load(self, name):
self.model.load_weights(name)
def save(self, name):
self.model.save_weights(name)
def formatPrice(n):
return("-Rs." if n<0 else "Rs.")+"{0:.2f}".format(abs(n))
window_size = 20
episode_count = 5
agent = DQNAgent(window_size)
l = len(data) - 1
batch_size = 64
# inventory=[]
def getState(data, t, n):
d = t - n + 1
block = data[d:t + 1] if d >= 0 else -d * [data[0]] + data[0:t + 1] # pad with t0
res = []
for i in range(n - 1):
res.append(logistic.cdf(block[i + 1] - block[i]))
return np.array([res])
for e in range(episode_count + 1):
print("Episode " + str(e) + "/" + str(episode_count))
state = getState(data, 0, window_size + 1)
total_profit = 0
agent.inventory = []
for t in range(l):
action = agent.act(state)
# hold
next_state = getState(data, t + 1, window_size + 1)
reward = 0
if action == 1: # buy
agent.inventory.append(data[t])
# data[t]+=btc_ini_balance
print("Buy: " + formatPrice(data[t]))
elif action == 2 and len(agent.inventory) > 0: # sell
bought_price = agent.inventory.pop(0)
# data[t]-=btc_ini_balance
reward = max(data[t] - bought_price, 0)
total_profit += data[t] - bought_price
print("Sell: " + formatPrice(data[t]) + " | Profit: " + formatPrice(data[t] - bought_price))
done = True if t == l - 1 else False
#print((state, action, reward, next_state, done))
agent.memory.append((state, action, reward, next_state, done))
state = next_state
if done:
print("Total Profit: " + formatPrice(total_profit))
if len(agent.memory) > batch_size:
agent.replay(batch_size)
if e % 10 == 0:
agent.save(str(e))
|
Java
|
UTF-8
| 4,264
| 2.34375
| 2
|
[] |
no_license
|
//package com.binghe.crawler.impl;
//
//import java.io.BufferedInputStream;
//import java.io.BufferedWriter;
//import java.io.File;
//import java.io.FileInputStream;
//import java.io.FileNotFoundException;
//import java.io.FileOutputStream;
//import java.io.IOException;
//import java.io.OutputStreamWriter;
//
//import javazoom.jl.decoder.JavaLayerException;
//import javazoom.jl.player.Player;
//
//import org.apache.commons.io.FileUtils;
//import org.jsoup.Jsoup;
//import org.jsoup.nodes.Document;
//import org.jsoup.nodes.Element;
//import org.jsoup.select.Elements;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//
//import com.binghe.crawler.Crawler;
//import com.binghe.crawler.service.HttpService;
//
//@Service
//public class StoryCatalogCrawler implements Crawler {
//
// @Autowired
// private HttpService httpService;
//
// @Override
// public void run() {
// // 要保存的目录名
// String pathName = "E:/text";
// // 目录页面url
// String preUrl = "";
// // 要保存的目录文本名
// String catalog = "目录页";
// // 关键词1
// String keyWord1 = "";
// // 关键词2
// String keyWord2 = "";
// // 关键词3
// String keyWord3 = "";
// // url起始页
// int start = 20;
// // url末页
// int end = 20;
//
// for (int j = start; j <= end; j++) {
// String catalogUrl = preUrl + j;
// // 目录页的Document
// Document catalogDoc = parseHtml(catalogUrl+".jsp");
//
// if (catalogDoc == null) {
// return;
// }else {
// // 获取总页数
// int pageCount = getPageCount(catalogDoc);
// StringBuffer content = new StringBuffer();
// for (int i = 1; i <= pageCount; i++) {
// if (i==1) {
// // 文章标题
// Elements elements = catalogDoc.select(".listbox ul ul li");
// for (Element element : elements) {
// String title = element.text();
// if (title.contains(keyWord1)) {
// content.append(title + " " + i + "\r\n");
// }
// }
// }else {
// Document doc = parseHtml(catalogUrl+"_"+i+".jsp");
// // 文章标题
// Elements elements = doc.select(".listbox ul ul li");
// for (Element element : elements) {
// String title = element.text();
// if (title.contains(keyWord1)) {
// content.append(title + " " + i + "\r\n");
// }
// }
// }
// }
// try {
// // 将文章内容写到本地txt文件中
// FileUtils.writeStringToFile(new File(pathName+"/"+catalog+j+".txt"), content.toString());
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
// try {
// new Player(new BufferedInputStream(new FileInputStream(new File("E:/CloudMusic/the ARROWS - ツナ覚醒.mp3")))).play();
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// } catch (JavaLayerException e) {
// e.printStackTrace();
// }
// }
//
// private int getPageCount(Document catalogDoc) {
// return Integer.parseInt(catalogDoc.select(".end").get(0).text());
// }
//
// /**
// * 获取对应链接的页面Document元素
// * @param url
// * @return
// */
// private Document parseHtml(String url) {
// String html = null;
// try {
// html = this.httpService.doGet(url);
// } catch (Exception e) {
// e.printStackTrace();
// }
// if (html != null) {
// return Jsoup.parse(html);
// }
// return null;
// }
//
// /**
// * 将文本添加到文件末尾
// * @param filePath 文件路径
// * @param content 文本内容
// */
// public void appendToTxt(String filePath, String content) {
// BufferedWriter out = null;
// try {
// out = new BufferedWriter(new OutputStreamWriter(
// new FileOutputStream(filePath, true)));
// out.write(content);
// } catch (Exception e) {
// e.printStackTrace();
// } finally {
// try {
// out.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
//
// public static void main(String[] args) throws IOException {
// File file = new File("E:/text/1.txt");
// FileUtils.writeStringToFile(file, "123");
// }
//}
|
Python
|
UTF-8
| 3,168
| 4.09375
| 4
|
[] |
no_license
|
import math
class Polygon:
def __init__(self, n: "Number of edges/ vertices", r: "Circum radius"):
self.circumradius = r
self.vertices = n
@property
def vertices(self):
return self._vertices
@property
def edges(self):
return self._edges
@property
def circumradius(self):
return self._circumradius
@property
def interior_angle(self):
return self._interior_angle
@property
def edge_length(self):
return self._edge_length
@property
def apothem(self):
return self._apothem
@property
def area(self):
return self._area
@property
def perimeter(self):
return self._perimeter
@circumradius.setter
def circumradius(self, value):
if type(value) not in [float, int]:
raise TypeError("Circumradius must be a number.")
if value<=0:
raise ValueError("Circumradius must be greater than 0.")
self._circumradius = value
@vertices.setter
def vertices(self, value):
if type(value) is not int:
raise TypeError("Number of edges/ vertices must be an integer.")
if value<3:
raise ValueError("Number of edges/ vertices must be >= 3.")
self._vertices = value
self._edges = value
self._interior_angle = (self._edges - 2) * (180 / self._edges)
self._edge_length = 2 * self._circumradius * math.sin(math.pi/self._edges)
self._apothem = self._circumradius * math.cos(math.pi/self._edges)
self._area = 0.5 * self._edge_length * self._apothem
self._perimeter = self._edges * self._edge_length
def __repr__(self):
return (
f"Polygon(\
\n\tNumber of vertices/edges = {self._edges},\
\n\tCircumradius = {self._circumradius},\
\n\tInterior angle = {self._interior_angle} degrees,\
\n\tEdge length = {self._edge_length:.2f} units,\
\n\tApothem = {self._apothem:.2f} units,\
\n\tArea = {self._area:.2f} sq. units,\
\n\tPerimeter = {self._perimeter:.2f} units,\
\n\t)"
)
def __eq__(self, other):
if type(other) is not Polygon:
raise TypeError("Expected type Polygon.")
return self.vertices == other.vertices and self.circumradius == other.circumradius
def __gt__(self, other):
if type(other) is not Polygon:
raise TypeError("Expected type Polygon.")
return self.vertices > other.vertices
# ## Creating an instance of polygon class
# In[67]:
p = Polygon(3,4)
# ## Print the representation of the polygon class created
p
# ## Print the edges, vertices, interior angle, edge length, apothem, area, perimeter of the polygon instance
print(f'The properties of Polygon instance created are: \n\nnumber of vertices = {p._edges} \nnumber of edges = {p._edges} \nEdge Length = {p._edge_length} \ninterior angle = {p._interior_angle} \napothem = {p._apothem} \narea = {p._area} \nperimeter = {p._perimeter}')
|
Python
|
UTF-8
| 2,459
| 3.03125
| 3
|
[] |
no_license
|
""" Performing feature extraction for model training."""
import torch
import logging
import warnings
import pandas as pd
import numpy as np
from config import Config
from utils.helpers import sliding_windows, save_train_test_splits
from torch.autograd import Variable
from sklearn.preprocessing import MinMaxScaler
def read_use_case_dataframe() -> pd.DataFrame:
"""Read use case dataframe from config path.
Returns:
pd.DataFrame: Returns the use case dataframe.
"""
logger.info(str(Config.USE_CASE_PREPARATION_DATASET_FILE_PATH))
use_case_dataframe = pd.read_csv(str(Config.USE_CASE_PREPARATION_DATASET_FILE_PATH), delimiter=",", index_col=[0])
logger.info('Reading use case dataframe.')
return use_case_dataframe
def train_test_split(use_case_dataframe: pd.DataFrame):
"""Function for applying MinMax Scaling for dataset. Furthermore, it performs
the transformation of the data into a sequence with a sliding window.
Finally, it performs a train test split.
Args:
use_case_dataframe (pd.DataFrame): Use case dataframe from the create_dataset.py
"""
sc = MinMaxScaler()
training_set = use_case_dataframe.iloc[:,1:2].values
training_data = sc.fit_transform(training_set)
seq_length = int(Config.SEQ_LENGTH)
x_variable, y_variable = sliding_windows(training_data, seq_length)
train_size = int(len(y_variable) * 0.67)
test_size = len(y_variable) - train_size
dataX = Variable(torch.Tensor(np.array(x_variable)))
dataY = Variable(torch.Tensor(np.array(y_variable)))
trainX = Variable(torch.Tensor(np.array(x_variable[0:train_size])))
trainY = Variable(torch.Tensor(np.array(y_variable[0:train_size])))
testX = Variable(torch.Tensor(np.array(x_variable[train_size:len(x_variable)])))
testY = Variable(torch.Tensor(np.array(y_variable[train_size:len(y_variable)])))
save_train_test_splits(dataX, dataY, trainX, trainY, testX, testY)
logger.info('Train and test split is finsihed and saved.')
def main() -> None:
"""Main function to call the feature extraction.
"""
use_case_dataframe = read_use_case_dataframe()
train_test_split(use_case_dataframe)
if __name__ == '__main__':
global logger
logging.basicConfig(level = logging.DEBUG, filemode='a')
file_handler = logging.FileHandler('log/create_features.log')
logger = logging.getLogger('log_file')
logger.addHandler(file_handler)
main()
|
Java
|
UTF-8
| 5,012
| 1.5
| 2
|
[] |
no_license
|
package com.sienrgitec.painaniprov.model;
public class ctProveedor {
private Integer iProveedor;
private String cClaveProv;
private String cRazonS;
private String cNegocio;
private String cRFC;
private Integer iGiro;
private Integer iSubGiro;
private String cWhatsApp;
private String cPaginaWeb;
private String cEMail;
private String cTwitter;
private String cFacebook;
private Integer iEstadoProv;
private Boolean lSucursales;
private Integer iNivelClasifica;
private Boolean lSistema;
private String cSistema;
private String cObs;
private Integer iUnidad;
private String dtAfiliacion;
private Boolean lPideOtrasUnidades;
private String dtCreado;
private String dtModificado;
private String cUsuCrea;
private String cUsuModifica;
private Object id;
public Integer getiProveedor() {
return iProveedor;
}
public void setiProveedor(Integer iProveedor) {
this.iProveedor = iProveedor;
}
public String getcClaveProv() {
return cClaveProv;
}
public void setcClaveProv(String cClaveProv) {
this.cClaveProv = cClaveProv;
}
public String getcRazonS() {
return cRazonS;
}
public void setcRazonS(String cRazonS) {
this.cRazonS = cRazonS;
}
public String getcNegocio() {
return cNegocio;
}
public void setcNegocio(String cNegocio) {
this.cNegocio = cNegocio;
}
public String getcRFC() {
return cRFC;
}
public void setcRFC(String cRFC) {
this.cRFC = cRFC;
}
public Integer getiGiro() {
return iGiro;
}
public void setiGiro(Integer iGiro) {
this.iGiro = iGiro;
}
public Integer getiSubGiro() {
return iSubGiro;
}
public void setiSubGiro(Integer iSubGiro) {
this.iSubGiro = iSubGiro;
}
public String getcWhatsApp() {
return cWhatsApp;
}
public void setcWhatsApp(String cWhatsApp) {
this.cWhatsApp = cWhatsApp;
}
public String getcPaginaWeb() {
return cPaginaWeb;
}
public void setcPaginaWeb(String cPaginaWeb) {
this.cPaginaWeb = cPaginaWeb;
}
public String getcEMail() {
return cEMail;
}
public void setcEMail(String cEMail) {
this.cEMail = cEMail;
}
public String getcTwitter() {
return cTwitter;
}
public void setcTwitter(String cTwitter) {
this.cTwitter = cTwitter;
}
public String getcFacebook() {
return cFacebook;
}
public void setcFacebook(String cFacebook) {
this.cFacebook = cFacebook;
}
public Integer getiEstadoProv() {
return iEstadoProv;
}
public void setiEstadoProv(Integer iEstadoProv) {
this.iEstadoProv = iEstadoProv;
}
public Boolean getlSucursales() {
return lSucursales;
}
public void setlSucursales(Boolean lSucursales) {
this.lSucursales = lSucursales;
}
public Integer getiNivelClasifica() {
return iNivelClasifica;
}
public void setiNivelClasifica(Integer iNivelClasifica) {
this.iNivelClasifica = iNivelClasifica;
}
public Boolean getlSistema() {
return lSistema;
}
public void setlSistema(Boolean lSistema) {
this.lSistema = lSistema;
}
public String getcSistema() {
return cSistema;
}
public void setcSistema(String cSistema) {
this.cSistema = cSistema;
}
public String getcObs() {
return cObs;
}
public void setcObs(String cObs) {
this.cObs = cObs;
}
public Integer getiUnidad() {
return iUnidad;
}
public void setiUnidad(Integer iUnidad) {
this.iUnidad = iUnidad;
}
public String getDtAfiliacion() {
return dtAfiliacion;
}
public void setDtAfiliacion(String dtAfiliacion) {
this.dtAfiliacion = dtAfiliacion;
}
public Boolean getlPideOtrasUnidades() {
return lPideOtrasUnidades;
}
public void setlPideOtrasUnidades(Boolean lPideOtrasUnidades) {
this.lPideOtrasUnidades = lPideOtrasUnidades;
}
public String getDtCreado() {
return dtCreado;
}
public void setDtCreado(String dtCreado) {
this.dtCreado = dtCreado;
}
public String getDtModificado() {
return dtModificado;
}
public void setDtModificado(String dtModificado) {
this.dtModificado = dtModificado;
}
public String getcUsuCrea() {
return cUsuCrea;
}
public void setcUsuCrea(String cUsuCrea) {
this.cUsuCrea = cUsuCrea;
}
public String getcUsuModifica() {
return cUsuModifica;
}
public void setcUsuModifica(String cUsuModifica) {
this.cUsuModifica = cUsuModifica;
}
public Object getId() {
return id;
}
public void setId(Object id) {
this.id = id;
}
}
|
Java
|
UTF-8
| 256
| 1.5
| 2
|
[] |
no_license
|
package com.eaglec.win.dao.cms;
import com.eaglec.win.dao.BaseDao;
import com.eaglec.win.domain.cms.Module;
/**
* @date: 2013-8-14
* @author:lwch
* @description:模块管理的接口
*/
public interface ModuelDao extends BaseDao<Module>{
}
|
Markdown
|
UTF-8
| 2,257
| 3.28125
| 3
|
[] |
no_license
|
# Django-Scrapy-SAP
This repository contains files of a single page web application created with Django and Scrapy. It was developed as part of my
co-operative education project to create an application that would grab HTML from the faculty and events pages of Acadia
University's computer science website, store it in a database then make requests to the database from Django views so that
the data can be displayed on a monitor.
For the project to be a true single page application a feature was implemented so that professor profiles and events
description would appear on the page for a couple minutes then fade out so that new data can be displayed.
This application was made with Django, Scrapy, HTML5 and CSS.
Django - used to fetch the data from the database and return it to the client
models.py - the database models are created here so that the extracted data can be saved
views.py - iterates through the stored data and returs it to the client so that it is displayed on a screen
Scrapy - used to crawl the computer science website for the desired data and save the extracted data into a database
spiders:
csScraper.py - extracts professor profile information
csstaff.py - extracts the profiles of other faculty memebers
eventsspider.py - extracts computer science events information
pipelines.py - transmits the extracted data to the Django database models in a list format
settings.py - connects Scrapy to Django so that we have access to the database models
HTML5 & CSS - used to create the application interface
templates:
index.html - sets up the structure of the application interace and includes code that takes care of the desired
fade in / fade out feature
static:
style.css - takes care of page presentation
At the end of my term there were a few features missing from the application including:
a cron job that triggers the spider to crawl for new information every couple weeks (this can also be taken care of in
Django views)
pipelines.py needs to be refactored so that only the specified spider is triggered
a message that appears on the monitor that informs viewers that no new data is available for display whenever this case
arises
|
TypeScript
|
UTF-8
| 5,049
| 3.453125
| 3
|
[] |
no_license
|
import { Injectable } from '@angular/core'
interface ICacheService {
deleteObject: (key: string) => any
fetchObject: (key: string) => any
saveObject: (key: string, obj: any, expirationTime ?: number) => void
}
/**
* @description
* Though angular has it's own specific storage module we made our own,
* partly due to not realising that one already existed but mostly due to
* wanting the ability to easily modify the behaviour of the service.
*
* The basic functionality of the `Cache` service is that it saves, loads and
* deletes objects using html5 `Storage`.
*
* If client being used doesn't support html5 `sessionStorage` or `localStorage`
* then the factory will return a dummy object with the same provided methods
* which will always just return null;
*
*/
function isInt (value) {
return !isNaN(value) && parseInt(value, 10) === value
}
@Injectable()
class NoOpCache implements ICacheService {
saveObject () { return null }
fetchObject () { return null }
deleteObject () { return null }
}
@Injectable()
class CacheService implements ICacheService {
sessionStorage = window.sessionStorage
localStorage = window.localStorage
private uniqueKey: string = ''
constructor () {
this.initialiseUniqueKey()
}
/**
* @description
* Saves an object to `Storage`. Whether `sessionStorage` or the longer term `localStorage`
* is dependent upon whether the user supplies an expiration time, if not it will default
* to `sessionStorage`.
*
* @param {string} key A unique string to be supplied which can later be used to retreive the saved object.
* @param {Object} obj A javascript object to be saved.
* @param {integer} expirationTime How long (in milliseconds) to store this object in `localStorage` for, this allows for data to be kept
* for a much longer or shorter term.
*
*/
saveObject (key: string, srcObj: any = {}, expirationTime ?: number, forceLocal?: boolean): void {
const { uniqueKey } = this
const obj = Object.assign({}, srcObj)
obj.dateSaved = (new Date()).getTime()
const itemKey = uniqueKey + key
if (forceLocal) {
return this.localStorage.setItem(itemKey, JSON.stringify(obj))
}
if (expirationTime !== undefined && isInt(expirationTime)) {
obj.dateExpire = expirationTime
return this.localStorage.setItem(itemKey, JSON.stringify(obj))
}
// (uniqueKey + key)
this.sessionStorage.setItem(itemKey, JSON.stringify(obj))
}
put (key: string, srcObj: any = {}, expirationTime ?: number, forceLocal?: boolean) {
this.saveObject(key, srcObj, expirationTime, forceLocal)
}
/**
* @description
* Fetches an object from html5 `Storage` via unique key identifier.
*
* By default it returns the object from `sessionStorage`. If not in `sessionStorage`
* it will check `localStorage` to see if object has been placed in storage for a predefined
* amount of time. If an object is found, it will then check to see if it has expired or not, if
* it has then it will be deleted and return null elsewise it will fetch the stored object.
*
*
* @param {string} key A unique string to be supplied which is used to try to retreive a saved object.
*
*/
fetchObject (key: string): any {
const { uniqueKey } = this
const itemKey = uniqueKey + key
const sessionObj = JSON.parse(this.sessionStorage.getItem(itemKey))
// return object from session cache
if (sessionObj !== null) {
return sessionObj
}
// check if object exists in localStorage(longer term storage)
const localObj = JSON.parse(this.localStorage.getItem(itemKey))
if (!localObj) return null
let timeDiff = (new Date()).getTime() - localObj.dateSaved
// check if our object is expired
if (timeDiff > localObj.dateExpire) {
this.deleteObject(itemKey)
return null
}
return localObj
}
get (key: string) {
return this.fetchObject(key)
}
/**
* @description
* Deletes any objects which are stored with this key value, both in `localStorage` and `sessionStorage`
*
* @param {string} key A unique string to be supplied which is used to try to find and delete a saved object.
*
*/
deleteObject (key: string): void {
const { uniqueKey } = this
const itemKey = uniqueKey + key
this.sessionStorage.removeItem(itemKey)
this.localStorage.removeItem(itemKey)
}
setUniqueKey (key) {
this.uniqueKey = key
this.sessionStorage.setItem('uniqueKeyLocation', key)
}
private initialiseUniqueKey () {
const key = this.sessionStorage.getItem('uniqueKeyLocation')
if (key) {
this.uniqueKey = key
}
}
}
const cacheProvider = (
localStorage,
sessionStorage
) => {
if (sessionStorage && localStorage) {
CacheService.prototype.sessionStorage = sessionStorage
CacheService.prototype.localStorage = localStorage
return CacheService
}
return NoOpCache
}
const Cache = CacheService
export {
cacheProvider,
Cache,
CacheService,
ICacheService
}
|
Python
|
UTF-8
| 3,104
| 3.53125
| 4
|
[] |
no_license
|
from tkinter import * #Import whole module
class CurrencyConvereter():
def __init__(self):
window = Tk() # create application window
window.title("Currency Converter") # add title to application window
window.geometry("450x350") # specify size of the window
window.configure(bg = "dark grey") # Add background color
# declaring our variables
dropdownVar = StringVar()
# Add a grid
dropframe = Frame(window)
dropframe.grid( column = 0, row = 0, sticky = (N,W,E,S) )
dropframe.columnconfigure(0, weight = 1)
dropframe.rowconfigure(0, weight = 1)
dropframe.pack(pady = 100, padx = 100)
# Dictionary with options
choices = { 'Naira','Dollar','Pounds','Yen','Cedis'}
dropdownVar.set('Naira') # set the default option
popupMenu = OptionMenu(dropframe, dropdownVar, *choices)
Label(dropframe, text="Amount to convert").grid(row = 1, column = 1)
popupMenu.grid(row = 2, column =1)
# on change dropdown value
def change_dropdown(*args):
print( dropdownVar.get() )
# link function to change dropdown
dropdownVar.trace('w', change_dropdown)
# Adding Labels widgets to the application windows
#slflabl = Label(window, font = "Helvetica 12 bold", bg = "yellow", text = "Amount to convert").grid(row=1, column = 1, sticky = W)
# Variable to be Convert with Entry Function
self.amounttoConvertVar = StringVar()
#amounttoConvertVar = Entry(window, textvariable = self.amounttoConvertVar, justify = RIGHT).grid(row = 1, column = 2)
# Conversion Rate with Entry Function
self.conversionRate = StringVar()
#Entry(window, textvariable = self.conversionRate, justify = RIGHT).grid(row = 2, column = 2)
# Converted Amount
self.convertedAmountVar = StringVar()
# = Label(window, font = "Helvetica 12 bold", bg = "yellow", textvariable = self.convertedAmountVar).grid(row=3, column = 2, sticky = E)
#create convert and clear buttons
btbConvertedAmount = Button(window, text = "Convert", font = "Helvetica 12 bold", bg = "blue", fg = "white", command = self.ConvertedAmount).grid(row = 4, column = 2, sticky = E)
#btbdelete_all = Button(window, text = "Clear", font = "Helvetica 12 bold", bg = "red", fg = "white", command = self.delete_all).grid(row = 4, column = 6, padx = 25, pady = 25, sticky = E)
window.mainloop() # run the application
#Function to do the conversion. stores inputs and performs computation
def ConvertedAmount(self):
amt = float(self.conversionRate.get())
convertedAmountVar = float( self.amounttoConvertVar.get() )* amt
self.convertedAmountVar.set(format(convertedAmountVar, '10.2f'))
# Function to clear inputs
def delete_all(self):
self.amounttoConvertVar.set("")
self.conversionRate.set("")
self.convertedAmountVar.set("")
CurrencyConvereter()
|
Rust
|
UTF-8
| 1,278
| 2.625
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
use swc_common::{errors::HANDLER, Span};
use swc_ecma_ast::*;
use swc_ecma_visit::{noop_visit_type, Visit};
use crate::{
config::{LintRuleReaction, RuleConfig},
rule::{visitor_rule, Rule},
};
const MESSAGE: &str = "Unexpected 'debugger' statement";
pub fn no_debugger(config: &RuleConfig<()>) -> Option<Box<dyn Rule>> {
let rule_reaction = config.get_rule_reaction();
match rule_reaction {
LintRuleReaction::Off => None,
_ => Some(visitor_rule(NoDebugger::new(rule_reaction))),
}
}
#[derive(Debug, Default)]
struct NoDebugger {
expected_reaction: LintRuleReaction,
}
impl NoDebugger {
fn new(expected_reaction: LintRuleReaction) -> Self {
Self { expected_reaction }
}
fn check(&self, span: Span) {
HANDLER.with(|handler| match self.expected_reaction {
LintRuleReaction::Error => {
handler.struct_span_err(span, MESSAGE).emit();
}
LintRuleReaction::Warning => {
handler.struct_span_warn(span, MESSAGE).emit();
}
_ => {}
});
}
}
impl Visit for NoDebugger {
noop_visit_type!();
fn visit_debugger_stmt(&mut self, debugger_stmt: &DebuggerStmt) {
self.check(debugger_stmt.span);
}
}
|
Python
|
UTF-8
| 8,284
| 2.515625
| 3
|
[] |
no_license
|
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
import os
import sys
from time import sleep
from utils.creds import load_creds
class YtMusic:
def __init__(self):
self.ROOT_DIR = os.path.split(os.path.dirname(os.path.abspath(__file__)))[0]
self.init_command_dict()
def setup_driver(self, headless):
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('user-data-dir='+self.ROOT_DIR+'/config')
if(headless): chrome_options.add_argument('--headless')
self.driver=webdriver.Chrome(options=chrome_options)
self.driver.implicitly_wait(5) # seconds
def googleLogin(self):
try:
username, password = load_creds(self.ROOT_DIR)
self.setup_driver(headless=False)
self.driver.get('https://stackoverflow.com/users/signup?ssrc=head&returnurl=%2fusers%2fstory%2fcurrent%27')
print(self.driver.title)
#Check if already logged in
if(self.driver.title == 'Stack Overflow - Where Developers Learn, Share, & Build Careers'):
print("Already logged in, nothing to do....")
return
self.driver.save_screenshot("1.png")
self.driver.find_element(By.XPATH, '//*[@id="openid-buttons"]/button[1]').click()
print(self.driver.title)
self.driver.save_screenshot("1.png")
WebDriverWait(self.driver, 10).until(
EC.element_to_be_clickable(
(By.XPATH, '//input[@type="email"]'))).send_keys(username)
self.driver.find_element(By.XPATH, '//*[@id="identifierNext"]').click()
print(self.driver.title)
WebDriverWait(self.driver, 10).until(
EC.element_to_be_clickable(
(By.XPATH, '//input[@type="password"]'))).send_keys(password)
self.driver.find_element(By.XPATH, '//*[@id="passwordNext"]').click()
WebDriverWait(self.driver, 10).until(
EC.element_to_be_clickable(
(By.XPATH,
'/html/body/header'))) # Waiting for login to complete
self.driver.get('https://music.youtube.com')
self.driver.save_screenshot("1.png")
print(self.driver.title)
WebDriverWait(self.driver, 10).until(
EC.element_to_be_clickable((
By.XPATH,
'//ytmusic-section-list-renderer/div[2]/ytmusic-carousel-shelf-renderer[2]'
))) # Waiting for page to load
except Exception as e:
print(e)
finally:
if(hasattr(self, 'driver')):
self.driver.close()
else: sys.exit(1)
def getPlaylists(self):
try:
self.setup_driver(headless=True)
self.driver.get('https://music.youtube.com/library/playlists')
self.driver.save_screenshot("1.png")
element = self.driver.find_element(By.XPATH, '//*[@id="contents"]/ytmusic-item-section-renderer')
items = element.find_element(By.XPATH, './/*[@id="items"]')
for item in items.find_elements(By.TAG_NAME, 'a'):
if("playlist" in item.get_attribute('href') and item.get_attribute('class') == 'yt-simple-endpoint style-scope yt-formatted-string'):
print(item.text)
except Exception as e:
print(e)
finally:
if (hasattr(self, 'driver')): self.driver.close()
else: sys.exit(1)
def cleanup_playlists(self):
try:
self.setup_driver(headless=False)
self.driver.get('https://music.youtube.com/library/playlists')
self.driver.save_screenshot("3.png")
element = self.driver.find_element(By.XPATH, '//*[@id="contents"]/ytmusic-item-section-renderer')
items = element.find_element(By.XPATH, './/*[@id="items"]')
self.playlistMap = {} #{playlist_title : url}
for item in items.find_elements_by_tag_name('a')[6:]:
if("playlist" in item.get_attribute('href') and item.get_attribute('class') == 'yt-simple-endpoint style-scope yt-formatted-string'):
self.playlistMap[item.text] = item.get_attribute('href')
# self.createPlaylist(title=item.text)
# print(item.text)
# for title in self.playlistMap:
# self.driver.get(self.playlistMap[title])
# print('=========' + title + '==========')
# items = self.driver.find_elements(By.XPATH, '//*[@id="contents"]/ytmusic-responsive-list-item-renderer')
# for index, item in enumerate(items):
# try:
# print(item.find_element(By.XPATH, '//*[@id="contents"]/ytmusic-responsive-list-item-renderer['+str(index+1)+']/div[2]/div[1]/yt-formatted-string/a').text)
# except: # Can be a deleted song
# pass
self.driver.get(self.playlistMap['Non Stop Pop'])
items = self.driver.find_elements(By.XPATH, '//*[@id="contents"]/ytmusic-responsive-list-item-renderer')
self.driver.implicitly_wait(0)
for index, item in enumerate(items):
try:
title = item.find_element(By.XPATH,
'//*[@id="contents"]/ytmusic-responsive-list-item-renderer['
+ str(index + 1) +
']/div[2]/div[1]/yt-formatted-string/a').text
artist = item.find_element(By.XPATH,
'//*[@id="contents"]/ytmusic-responsive-list-item-renderer['
+ str(index + 1) +
']/div[2]/div[3]/yt-formatted-string/a').text
print(title)
hover = ActionChains(self.driver).move_to_element(item)
hover.perform()
button = WebDriverWait(self.driver, 30).until(EC.presence_of_element_located((By.XPATH, "//div[@id='gridProduct10247118']//a[@class='primary-button']")))
hover = ActionChains(self.driver).move_to_element(button)
hover.perform()
button.click()
except Exception as e: # Can be a deleted song
print(e)
except Exception as e:
print(e)
finally:
self.driver.implicitly_wait(10)
def get_artist(self, query):
self.setup_driver(headless=True)
self.driver.get('https://music.youtube.com/search?q='+query)
try:
# Top result
self.driver.find_element(
By.XPATH,
'//*[@id="contents"]/ytmusic-shelf-renderer[1]/h2/yt-formatted-string'
)
artist_link = self.driver.find_element(By.XPATH,
'//*[@id="contents"]/ytmusic-responsive-list-item-renderer/a'
).get_attribute('href')
print(artist_link)
self.driver.get(artist_link)
except Exception as e:
print(e)
# No result
try:
self.driver.find_element(By.LINK_TEXT, "Did you mean")
newQuery = self.driver.find_element(By.ID, 'corrected-link')
print('Did you mean: ' + newQuery + ' ?')
except:
print('Artist not found...')
def createPlaylist(self, title):
self.driver.find_element(By.XPATH, '//*[@id="items"]/ytmusic-two-row-item-renderer[1]/div[1]/yt-formatted-string[1]/a').click()
self.driver.find_element(By.XPATH, '//*[@id="input-2"]/input').send_keys(title)
self.driver.find_element(By.XPATH, '//*[@id="general-pane"]/div[2]/paper-button[2]').click()
def init_command_dict(self):
self.command_dict ={'get-playlists' : self.getPlaylists,
'cleanup-playlists': self.cleanup_playlists,
'get-artist': self.get_artist}
|
Markdown
|
UTF-8
| 2,230
| 3.5
| 4
|
[] |
no_license
|
## About Simple Plate
Simple plate was a project created to test and evolve my abilities as a front-end developer.
The project idea is a webpage for cooking recipes. The project's prototype can be [found here] (https://www.figma.com/file/E6xlazw52ICbowNMpNclc8/Untitled?node-id=0%3A1).
The idea and design of the project came from my friend Lucas Credie, a front-end developer, and CEO of Colored Bite.
#### Challenges faced:
As my first front-end project from zero, the callenge of this project was to create a responsive webpage (desktop only), getting data from an external source, like from an API.
As second objectives, there was the development of my knowledge in HTML, CSS and Javascript, and how they combine together to create a responsive webpage.
#### A brief summary of the solution
1. The first challenge was to get the information from an external source. As the project is simple, consisting only of a static webpage, data could not be retrieved by a JSON file. Instead, I've used a variable with a list of Javascript objects, from an external JS file (plates.js).
Data is then treated by a map function, that gets from each plate (js object) the necessary information, and put it in the right spot.
2. The second challenge was to show every plate in the menu bar (left), and to make it selectable to the user, showing the desired plate's info in the main section (right).
For this, a second function (select_plate) was created:
- it gets every element inside the "main-plate" div and gives it the "display: none" attribute;
- it passes through every plate in the menu bar and withdraw the " active" from the class name;
- it gets the current plate id and changes its main section div with the "display: block" attribute;
- it adds to the plate menu a tag class name " active";
#### Further modifications
Although the project's main challenge was accomplished, there are some details that still needs work:
- main navbar styling, such as the bottom border's shadow;
- plate's time and serves description in the main section, where image and text are offset;
- ingredients list could be better showed;
- webpage responsiveness to width change (mobile platforms);
|
PHP
|
UTF-8
| 2,897
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace App\Services;
use App\Models\Keyword;
use App\Models\Rule;
use Houdunwang\WeChat\WeChat;
class WechatService
{
public function __construct(){
//与微信通信绑定
//读取 config/hd_config.php配置文件
//config()读取框架配置项、框架配置项读取env对数据、env数据来源我们自己的后台
$config = config('hd_wechat');//config函数是框架内置的
//dd($config);//这个打印得在env配置项中添加微信后台设置的配置项并且在hd_wechat里面把小写改大写
//https://www.kancloud.cn/houdunwang/wechat/322346
WeChat::config($config);//微信配置👆
//https://www.kancloud.cn/houdunwang/wechat/324351
WeChat::valid();//验证消息的确来自微信服务器👆
}
//加载规则视图文件
public function ruleView($rule_id = 0){
//根据规则 id 去规则表找旧数据
$rule = Rule::find($rule_id);
//dd($rule);
$ruleData = [
'name'=>$rule?$rule['name']:'',//规则名称
'keywords'=>$rule?$rule->keyword()->select('key')->get()->toArray():[],
];
return view('wechat.layouts.rule',compact('ruleData'));
}
//添加数据
public function ruleStore($type){
//dd(request()->all());
$post = request()->all();
//$post = request()->rule;//这两种写法结果是一样的👇
//$post = request()->input('rule');和上面写法结果一样👆
//dd($post['rule']);//打印出来的都是json格式数据,需要把数据转成数组格式
$rule = json_decode($post['rule'],true);
//dd($rule);
//执行规则表的添加
\Validator::make($rule,[
'name'=>'required'
],[
'name.required'=>'规则名称不能为空'
])->validate();
$ruleModel = Rule::create(['name'=>$rule['name'],'type'=>$type]);
//dd($rule);//为什么看不到回复的内容,因为只打印了规则
//关键词表添加
foreach($rule['keywords'] as $value){
Keyword::create([
'rule_id' => $ruleModel['id'],
'key' => $value['key']
]);
}
return $ruleModel;
}
public function ruleUpdate($rule_id){
//执行规则表的编辑
//dd($rule_id);
$rule = Rule::find($rule_id);
$post = request()->all();
$ruleData = json_decode($post['rule'],true);
$rule->update(['name'=>$ruleData['name']]);
//关键词表编辑
//原来的关键词删除
$rule->keyword()->delete();
foreach($ruleData['keywords'] as $value){
Keyword::create([
'rule_id'=>$rule_id,
'key'=>$value['key']
]);
}
}
}
|
C#
|
UTF-8
| 4,434
| 2.859375
| 3
|
[
"Apache-2.0"
] |
permissive
|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using Sdl.Web.Common;
using Sdl.Web.Common.Interfaces;
using Sdl.Web.Common.Logging;
namespace Sdl.Web.Tridion.Caching
{
/// <summary>
/// Abstract base class for DXA Cache Providers
/// </summary>
public abstract class CacheProvider : ICacheProvider
{
private const int WaitForAddingTimeout = 15000; // ms
private static readonly IDictionary<string, EventWaitHandle> _addingEvents = new ConcurrentDictionary<string, EventWaitHandle>();
#region ICacheProvider members
public abstract void Store<T>(string key, string region, T value, IEnumerable<string> dependencies = null);
public abstract bool TryGet<T>(string key, string region, out T value);
/// <summary>
/// Tries to gets a value for a given key and cache region. If not found, add a value obtained from a given function.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="region">The name of the cache region. Different cache regions can have different retention policies.</param>
/// <param name="addFunction">A function (delegate) used to obtain the value to add in case an existing cached value is not found.</param>
/// <param name="dependencies">An optional set of dependent item IDs. Can be used to invalidate the cached item.</param>
/// <typeparam name="T">The type of the value to get or add.</typeparam>
/// <remarks>
/// This method is thread-safe; it prevents the same key being added by multiple threads in case of a race condition.
/// </remarks>
/// <returns>The cached value.</returns>
public virtual T GetOrAdd<T>(string key, string region, Func<T> addFunction, IEnumerable<string> dependencies = null)
{
T result;
if (TryGet(key, region, out result))
{
return result;
}
// Indicate to other threads that we're adding a value
EventWaitHandle addingEvent = new ManualResetEvent(false);
string qualifiedKey = GetQualifiedKey(key, region);
try
{
_addingEvents.Add(qualifiedKey, addingEvent);
}
catch (ArgumentException)
{
// Another thread is already adding a value (race condition); retry getting the value.
if (TryGet(key, region, out result))
{
return result;
}
}
try
{
// Obtain the actual value. This may be time-consuming (otherwise there would be no reason to cache).
result = addFunction();
Store(key, region, result, dependencies);
}
finally
{
// Unblock other threads which are awaiting it.
addingEvent.Set();
_addingEvents.Remove(qualifiedKey);
}
return result;
}
#endregion
protected bool AwaitAddingValue(string key, string region)
{
string qualifiedKey = GetQualifiedKey(key, region);
// Check if another thread is adding a value for the key/region:
EventWaitHandle addingEvent;
if (!_addingEvents.TryGetValue(qualifiedKey, out addingEvent))
{
return false;
}
Log.Debug("Awaiting adding of value for key '{0}' in region '{1}' ...", key, region);
if (!addingEvent.WaitOne(WaitForAddingTimeout))
{
// To facilitate diagnosis of deadlock conditions, first log a warning and then wait another timeout period.
Log.Warn("Waiting for adding of value for key '{0}' in cache region '{1}' for {2} seconds.", key, region, WaitForAddingTimeout / 1000);
if (!addingEvent.WaitOne(WaitForAddingTimeout))
{
throw new DxaException(
$"Timeout waiting for adding of value for key '{key}' in cache region '{region}'.");
}
}
Log.Debug("Done awaiting.");
return true;
}
protected static string GetQualifiedKey(string key, string region) => $"{region}::{key}";
}
}
|
Markdown
|
UTF-8
| 8,681
| 2.703125
| 3
|
[] |
no_license
|
# Azure Functions on IoT Edge
You can use Azure Functions to deploy code that implements your business logic directly to your IoT Edge devices.
This functionality allows developers to utilize the uniquely productive programming model provided by Functions even on the devices which may or may not be connected to the cloud.
This functionality can be used in multiple scenarios such as performing custom processing on data coming from sensors, or filtering the incoming signals based on certain criteria. All of these scenarios which are today possible in the cloud, can now be really easily replicated on IoT Edge devices too.
In this lab you will learn about
* Create Azure Container Registry.
* Connect Azure Function.
* Containerize the function and push it to Container Registry
* Deploy it to the edge
## Create Azure Container Registry
Azure Container Registry allows you to store images for all types of container deployments including DC/OS, Docker Swarm, Kubernetes, and Azure services such as App Service, Batch, Service Fabric, and others. Your DevOps team can manage the configuration of apps isolated from the configuration of the hosting environment.
This helps **Contoso** simplify container development by easily storing and managing container images for Azure deployments in a central registry.

Click on **Containers and Container Registry**

Enable the admin user to secure the registry and click on **Create button**

## Create a function project
The following steps show you how to create an IoT Edge function using Visual Studio Code and the Azure IoT Edge extension.
* Open Visual Studio Code.
* To open the VS Code integrated terminal, select View > Integrated Terminal.
* To install (or update) the AzureIoTEdgeFunction template in dotnet, run the following command in the integrated terminal:
```cmd/sh
dotnet new -i Microsoft.Azure.IoT.Edge.Function
```
Create a project for the new module. The following command creates the project folder, FilterFunction, with your container repository. The second parameter should be in the form of ```<your container registry name>```.azurecr.io if you are using Azure container registry. Enter the following command in the current working folder:
```cmd/sh
dotnet new aziotedgefunction -n FilterFunction -r developercertacr.azurecr.io/filterfunction
```
Select **File > Open Folder**, then browse to the FilterFunction folder and open the project in VS Code.
From VSCode extensions add **Nuget Package Manager**. Click **Install**

In VS Code explorer, expand the EdgeHubTrigger-Csharp folder, then open the run.csx file.
Replace the contents of the file with the following code:
```c#
#r "Microsoft.Azure.Devices.Client"
#r "Newtonsoft.Json"
using System.IO;
using Microsoft.Azure.Devices.Client;
using Newtonsoft.Json;
// Filter messages based on the temperature value in the body of the message and the temperature threshold value.
public static async Task Run(Message messageReceived, IAsyncCollector<Message> output, TraceWriter log)
{
const int temperatureThreshold = 25;
byte[] messageBytes = messageReceived.GetBytes();
var messageString = System.Text.Encoding.UTF8.GetString(messageBytes);
if (!string.IsNullOrEmpty(messageString))
{
// Get the body of the message and deserialize it
var messageBody = JsonConvert.DeserializeObject<MessageBody>(messageString);
if (messageBody != null && messageBody.machine.temperature > temperatureThreshold)
{
// Send the message to the output as the temperature value is greater than the threashold
var filteredMessage = new Message(messageBytes);
// Copy the properties of the original message into the new Message object
foreach (KeyValuePair<string, string> prop in messageReceived.Properties)
{
filteredMessage.Properties.Add(prop.Key, prop.Value); }
// Add a new property to the message to indicate it is an alert
filteredMessage.Properties.Add("MessageType", "Alert");
// Send the message
await output.AddAsync(filteredMessage);
log.Info("Received and transferred a message with temperature above the threshold");
}
}
}
//Define the expected schema for the body of incoming messages
class MessageBody
{
public Machine machine {get;set;}
public Ambient ambient {get; set;}
public string timeCreated {get; set;}
}
class Machine
{
public double temperature {get; set;}
public double pressure {get; set;}
}
class Ambient
{
public double temperature {get; set;}
public int humidity {get; set;}
}
```
## Create a Docker image and publish it to your registry
1. Sign in to Docker by entering the following command in the VS Code integrated terminal:
```csh/sh
docker login -u <ACR username> -p <ACR password> <ACR login server>
```
To find the user name, password and login server to use in this command, go to the [Azure portal] (https://portal.azure.com)
From **All resources**, click the tile for your Azure container registry to open its properties, then click **Access keys**. Copy the values in the **Username**, **password**, and **Login server** fields.
2. Open **module.json**. Optionally, you can update the `"version"` to eg. **"1.0"**. Also the name of the repository is shown which you entered in the `-r` parameter of `dotnet new aziotedgefunction`.
3. Save the **module.json** file.
4. In VS Code explorer, Right-click the **module.json** file and click **Build and Push IoT Edge module Docker image**. In the pop-up dropdown box at the top of the VS Code window, select your container platform, select **amd64**. VS Code then containerizes your function codes and push it to the container registry you specified.
5. You can get the full container image address with tag in the VS Code integrated terminal. For more infomation about the build and push definition, you can refer to the `module.json` file.

## Add registry credentials to your Edge device
Add the credentials for your registry to the Edge runtime on the computer where you are running your Edge device. This gives the runtime access to pull the container.
```cmd/sh
sudo iotedgectl login --address <your container registry address> --username <username> --password <password>
```

## Run the solution
1. In the **Azure portal**, navigate to your IoT hub.
2. Go to **IoT Edge (preview)** and select your IoT Edge device.
3. Select **Set Modules**.
4. Add the **filterFunction** module.
1. Select **Add IoT Edge Module** again.
2. In the **Name** field, enter `filterFunction`.
3. In the **Image URI** field, enter your image address; for example `<your container registry address>/filterfunction:0.0.1-amd64`. The full image address can be found from the previous section.
4. Click **Save**.

5. Click **Next**.
6. In the **Specify Routes** step, copy the JSON below into the text box. The first route transports messages from the temperature sensor to the filter module via the "input1" endpoint. The second route transports messages from the filter module to IoT Hub. In this route, `$upstream` is a special destination that tells Edge Hub to send messages to IoT Hub. Add this to existing routes.
```json
"sensorToFilter":"FROM /messages/modules/tempSensor/outputs/temperatureOutput INTO BrokeredEndpoint(\"/modules/filterFunction/inputs/input1\")",
"filterToIoTHub":"FROM /messages/modules/filterFunction/outputs/* INTO $upstream"
```

7. Click **Next**.
8. In the **Review Template** step, click **Submit**.
9. Return to the IoT Edge device details page and click **Refresh**. You should see the new **filterfunction** module running along with the **tempSensor** module and the **IoT Edge runtime**.

## View generated data
Alerts are generated when machine.temperature is > 25

|
Java
|
UTF-8
| 4,460
| 1.9375
| 2
|
[] |
no_license
|
package com.archu.gussoapintegration.api.regon.fullreport;
import com.archu.gussoapintegration.api.regon.fullreport.dto.*;
import com.archu.gussoapintegration.integration.regon.fullreport.FullReportClient;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;
@Service
@Slf4j
@AllArgsConstructor
public class FullReportService {
private final FullReportClient fullReportClient;
private final FullReportConverter fullReportConverter;
public NaturalPersonGeneralDataDTO getNaturalPersonGeneralData(FullReportSearchingParams searchingParams) {
return fullReportConverter.convert(fullReportClient.getOsFizycznaDaneOgolne(searchingParams));
}
public NaturalPersonCeidgActivityDTO getNaturalPersonCeidgActivity(FullReportSearchingParams searchingParams) {
return fullReportConverter.convert(fullReportClient.getOsFizycznaDzialalnoscCeidg(searchingParams));
}
public NaturalPersonAgriculturalActivityDTO getNaturalPersonAgriculturalActivity(FullReportSearchingParams searchingParams) {
return fullReportConverter.convert(fullReportClient.getOsFizycznaDzialalnoscRolnicza(searchingParams));
}
public NaturalPersonRemainingActivityDTO getNaturalPersonRemainingActivity(FullReportSearchingParams searchingParams) {
return fullReportConverter.convert(fullReportClient.getOsFizycznaDzialalnoscPozostala(searchingParams));
}
public NaturalPersonActivityDeletedTo20141108DTO getNaturalPersonActivitiyDeletedTo20141108(FullReportSearchingParams searchingParams) {
return fullReportConverter.convert(fullReportClient.getOsFizycznaDzialalnoscSkreslonaDo20141108(searchingParams));
}
public List<NaturalPersonPkdDTO> getNaturalPersonPkd(FullReportSearchingParams searchingParams) {
return fullReportClient.getOsFizycznaPkd(searchingParams).stream().map(fullReportConverter::convert).collect(Collectors.toList());
}
public List<NaturalPersonLocalUnitsDTO> getNaturalPersonLocalUnits(FullReportSearchingParams searchingParams) {
return fullReportClient.getOsFizycznaListaJednLokalnych(searchingParams).stream().map(fullReportConverter::convert).collect(Collectors.toList());
}
public NaturalPersonLocalUnitDTO getNaturalPersonLocalUnit(FullReportSearchingParams searchingParams) {
return fullReportConverter.convert(fullReportClient.getJednLokalnaOsFizycznej(searchingParams));
}
public List<NaturalPersonLocalUnitPkdDTO> getNaturalPersonLocalUnitPkd(FullReportSearchingParams searchingParams) {
return fullReportClient.getJednLokalnaOsFizycznejPkd(searchingParams).stream().map(fullReportConverter::convert).collect(Collectors.toList());
}
public LegalEntityDTO getLegalEntity(FullReportSearchingParams searchingParams) {
return fullReportConverter.convert(fullReportClient.getOsPrawna(searchingParams));
}
public List<LegalEntityPkdDTO> getLegalEntityPkd(FullReportSearchingParams searchingParams) {
return fullReportClient.getOsPrawnaPkd(searchingParams).stream().map(fullReportConverter::convert).collect(Collectors.toList());
}
public List<LegalEntityLocalUnitsDTO> getLegalEntityLocalUnits(FullReportSearchingParams searchingParams) {
return fullReportClient.getOsPrawnaListaJednLokalnych(searchingParams).stream().map(fullReportConverter::convert).collect(Collectors.toList());
}
public LegalEntityLocalUnitDTO getLegalEntityLocalUnit(FullReportSearchingParams searchingParams) {
return fullReportConverter.convert(fullReportClient.getJednLokalnaOsPrawnej(searchingParams));
}
public List<LegalEntityLocalUnitPkdDTO> getLegalEntityLocalUnitPkd(FullReportSearchingParams searchingParams) {
return fullReportClient.getJednLokalnaOsPrawnejPkd(searchingParams).stream().map(fullReportConverter::convert).collect(Collectors.toList());
}
public List<LegalEntityCivilPartnershipDTO> getLegalEntityCivilPartnership(FullReportSearchingParams searchingParams) {
return fullReportClient.getOsPrawnaSpCywilnaWspolnicy(searchingParams).stream().map(fullReportConverter::convert).collect(Collectors.toList());
}
public SubjectTypeDTO getSubjectType(FullReportSearchingParams searchingParams) {
return fullReportConverter.convert(fullReportClient.getTypPodmiotu(searchingParams));
}
}
|
Markdown
|
UTF-8
| 2,154
| 3.8125
| 4
|
[] |
no_license
|
# 415. 字符串相加 [每日一题] [求和进位]
1. https://leetcode-cn.com/problems/add-strings/
2. 题目:给定两个字符串形式的非负整数 num1 和num2, 计算它们的和;
+ 注意:
- num1 和num2 的长度都小于 5100.
- num1 和num2 都只包含数字 0-9.
- num1 和num2 都不包含任何前导零。
- [你不能使用任何 内建的 BigInteger 库], 也不能直接将输入的字符串转换为整数形式。
4. 思路和代码:
+ 从num1, num2的尾部开始计算, 保存到tmp中
+ 计算当前位置的值: tmp%10得到的余数, 保存到result(string类型)
+ 计算进位, 更新tmp, 将进位添加到下一位数字的相加运算中
+ 索引溢出处理: 循环结束, 根据tmp判断是否有进位, 并在result头部添加进位1
+ 返回result
5. 代码:
```js
var addStrings = function(num1, num2) {
let a = num1.length, b = num2.lengt, result ='', tmp = 0;
while(a || b) {
// tmp += +num1[--a] + +num2[--b];
//当前位的和 = 当前位的2个数字(number)的和 + 上一次的进位
//考虑到 39+1 , 考虑为和为0的情况
a ? tmp += +num1[--a] : 0;
b ? tmp += +num2[--b] : 0;
result = tmp % 10 + result; //计算当前位的值
if(tmp > 9) tmp = 1;
else tmp = 0;
}
if(tmp) result = 1 + result;
return result;
}
```
6. 刷题记录:
| 时间 | 次数 | 备注 |
| :---- | :----: | :---- |
| 08.03 | 1 |
# 207. 课程表
1. https://leetcode-cn.com/problems/course-schedule/
2. 题目;
你这个学期必须选修 numCourse 门课程,记为 0 到 numCourse-1 。
在选修某些课程之前需要一些先修课程。
例如,想要学习课程 0 ,你需要先完成课程 1 ,我们用一个匹配来表示他们:[0,1]
给定课程总量以及它们的先决条件,请你判断是否可能完成所有课程的学习.
3. 示例:
```
输入: 2, [[1,0]]
输出: true
解释: 总共有 2 门课程。学习课程 1 之前,你需要完成课程 0。所以这是可能的
```
# 100. 相同的树
1. https://leetcode-cn.com/problems/same-tree/
2.
|
PHP
|
UTF-8
| 144
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace Bug7352\WithSubNamespace;
const MY_OTHER_CONST = 'thing';
class World
{
/** @var string */
const THERE = MY_OTHER_CONST;
}
|
C#
|
UTF-8
| 1,088
| 2.8125
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Text;
namespace RFIDReaderControler
{
/// <summary>
/// 与服务器通讯的协议,通过该协议控制该应用,使得该应用做出相应反应
/// 其中command为执行的动作,而flag则标记出执行的具体读写器
/// command 具体值有:open close
/// flag则根据具体读写器的设置确定具体值
/// </summary>
public class CommandProtocol
{
public string command = string.Empty;//命令类型,应该根据协议过的命令做出反应
public string timeStamp = string.Empty;//时间戳
public string flag = string.Empty;//发送扫描到的标签时附带的标记,是获取扫描到的标签的分类的依据
public string state = string.Empty;
public CommandProtocol()
{
}
public CommandProtocol(string _command, string _timeStamp, string _flag)
{
this.command = _command;
this.timeStamp = _timeStamp;
this.flag = _flag;
}
}
}
|
Python
|
UTF-8
| 1,205
| 2.8125
| 3
|
[] |
no_license
|
from django.db import models
from django.urls import reverse
class Hero(models.Model):
name = models.CharField(max_length=50)
secret_identity = models.CharField(max_length=50)
power = models.TextField(max_length=250)
def __str__(self):
return f'{self.name} is truly {self.secret_identity} with the power(s) of {self.power}'
def get_absolute_url(self):
return reverse('heroes_detail', kwargs={'pk': self.id})
class Comic(models.Model):
name = models.CharField('Title', max_length=100)
issue = models.IntegerField('Issue No:')
writer = models.CharField('Writer(s)', max_length=100)
artist = models.CharField('Artist(s)', max_length=100)
description = models.TextField(max_length=250)
heroes = models.ManyToManyField(Hero)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('detail', kwargs={'comic_id': self.id})
class Cover(models.Model):
image = models.CharField('Cover Image URL', max_length=100)
artist = models.CharField(max_length=100)
comic = models.ForeignKey(Comic, on_delete=models.CASCADE)
def __str__(self):
return f"{self.image} was illustrated by {self.artist}"
|
Java
|
UTF-8
| 15,482
| 1.625
| 2
|
[] |
no_license
|
package com.yoka.mrskin.activity;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.umeng.analytics.MobclickAgent;
import com.yoka.mrskin.R;
import com.yoka.mrskin.activity.base.BaseActivity;
import com.yoka.mrskin.activity.base.YKActivityManager;
import com.yoka.mrskin.adapter.AeniorReplayAdapter2;
import com.yoka.mrskin.addimage.BitmapUtil;
import com.yoka.mrskin.login.LoginActivity;
import com.yoka.mrskin.model.base.YKResult;
import com.yoka.mrskin.model.managers.YKCommentreplyManager;
import com.yoka.mrskin.model.managers.YKCommentreplyManager.ReplyCallback;
import com.yoka.mrskin.model.managers.YKCurrentUserManager;
import com.yoka.mrskin.model.managers.YKUploadImageManager;
import com.yoka.mrskin.model.managers.YKUploadImageManager.UploadImageCallback;
import com.yoka.mrskin.util.AppUtil;
import com.yoka.mrskin.util.BitmapUtilImage;
import com.yoka.mrskin.util.CustomButterfly;
import com.yoka.mrskin.util.MyListView;
import com.yoka.mrskin.util.NetWorkUtil;
import com.yoka.mrskin.util.YKUtil;
/**
* 高级回复(多图压缩上传)
* @author zlz
* @Data 2016年7月27日
*/
public class AeniorReplayActivity2 extends BaseActivity implements OnClickListener{
private LinearLayout mTakingPictures,mPhotoAlbum,mBack;
public static TextView mCommit;
private EditText mAeniorEdit;
private MyListView mList;
private AeniorReplayAdapter2 mAdapter;
private Context mContext;
private ArrayList<String> mImageList = new ArrayList<String>();//本地图片路径集合
private ArrayList<Bitmap> mapList = new ArrayList<Bitmap>();//本地图片路径集合
private ArrayList<String> mImageUploadUrl = new ArrayList<String>();//上传成功后返回路径集合
private ArrayList<String> mtempList = new ArrayList<String>();//压缩后图片路径集合
private CustomButterfly mCustomButterfly;
private File mOutputFile;
private Uri uritempFile;
private String mGetEditText = "",mCommentID,mmCommentIDInfo;
private int type = -1;
private Bitmap tempBitmap;
private int size = 0;
private int times = 0;
private Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 200:
//图片上传完成开始 提交回复
commitReplay();
break;
case 201:
uploadImage();
break;
case 203:
mCommit.setEnabled(true);
AppUtil.dismissDialogSafe(mCustomButterfly);
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aenior_replay_activity);
mContext = AeniorReplayActivity2.this;
YKActivityManager.getInstance().addActivity(this);
//心得高级回复
if(!TextUtils.isEmpty(getIntent().getStringExtra("commmentID"))){
type = 1;
mCommentID = getIntent().getStringExtra("commmentID");
}
//资讯高级回复
if(!TextUtils.isEmpty(getIntent().getStringExtra("mCommentInfourID"))){
type = 2;
mmCommentIDInfo = getIntent().getStringExtra("mCommentInfourID");
}
initView();
}
/**
* 实例化组件 & 设置监听
*/
private void initView() {
mList = (MyListView) findViewById(R.id.aenior_list);
mCommit = (TextView) findViewById(R.id.aenior_comment);
mAeniorEdit = (EditText) findViewById(R.id.aenior_reply_text);
mTakingPictures = (LinearLayout) findViewById(R.id.taking_pictures_layout);
mPhotoAlbum = (LinearLayout) findViewById(R.id.photo_album_layout);
mTakingPictures.setOnClickListener(this);
mPhotoAlbum.setOnClickListener(this);
mCommit.setOnClickListener(this);
//设置适配器
mAdapter = new AeniorReplayAdapter2(mContext, mapList);
mList.setAdapter(mAdapter);
mAeniorEdit.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View view, MotionEvent event) {
view.getParent().requestDisallowInterceptTouchEvent(true);
return false;
}
});
mAeniorEdit.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mGetEditText = s.toString();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
/*发送按钮是否可点击*/
if(mAeniorEdit.getText().length() > 0){
mCommit.setTextColor(getResources().getColor(R.color.red));
mCommit.setEnabled(true);
}else{
if(null != mAdapter.getList() && mAdapter.getList().size() > 0){//监听图片
mCommit.setTextColor(getResources().getColor(R.color.red));
mCommit.setEnabled(true);
}else{
mCommit.setTextColor(getResources().getColor(R.color.location_city_gps));
mCommit.setEnabled(false);
}
}
/*是否超出255字符*/
if(!TextUtils.isEmpty(mGetEditText)){
String limitSubstring = YKUtil.getLimitSubstring(mGetEditText);
if (!TextUtils.isEmpty(limitSubstring)) {
if (!limitSubstring.equals(mGetEditText)) {
Toast.makeText(mContext, "字数已超过限制",
Toast.LENGTH_SHORT).show();
mAeniorEdit.setText(limitSubstring);
mAeniorEdit.setSelection(limitSubstring.length());
}
}
}
}
});
}
/**
* 返回监听
* @param v
*/
public void AeniorBack(View v){
mAeniorEdit.clearFocus();
YKUtil.hideKeyBoard(AeniorReplayActivity2.this, mAeniorEdit);
finish();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
switch (requestCode) {
case 11://图片选择 返回---zlz
if(resultCode == RESULT_OK){
ArrayList<String> selected = (ArrayList<String>) data.getSerializableExtra(SelectPictureActivity.INTENT_SELECTED_PICTURE);
mAdapter.refresh(selected);
//ImageList.size > 0 ? 可提交(红色) :不可提交(黑色)
if(canCommitFromImage()){
mCommit.setTextColor(getResources().getColor(R.color.red));
mCommit.setEnabled(true);
}else{
mCommit.setTextColor(getResources().getColor(R.color.location_city_gps));
mCommit.setEnabled(false);
}
}
break;
/*拍照返回调用相机*/
case 1:
if (resultCode == Activity.RESULT_OK) {
if (YKUtil.hasSdcard()) {
startPhotoZoom(Uri.fromFile(mOutputFile));
} else {
Toast.makeText(mContext, "未找到存储卡,无法存储照片!",
Toast.LENGTH_SHORT).show();
}
}
break;
case 4:
//适用于小米
try {
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uritempFile));
Log.d("Aenior", "uritempFile"+uritempFile+"-8=-"+getContentResolver().openInputStream(uritempFile));
addCropPicture((uritempFile+"").replace("file:////", ""));
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.d("tag", e.toString());
}
break;
default:
break;
}
}
private void addCropPicture(String path){
if(path != null){
mAdapter.update(path);
/*提交按钮可点击*/
mCommit.setTextColor(getResources().getColor(R.color.red));
mCommit.setEnabled(true);
}else{
Toast.makeText(mContext, "裁剪失败,请重试一下吧~", Toast.LENGTH_SHORT).show();
mCommit.setTextColor(getResources().getColor(R.color.location_city_gps));
mCommit.setEnabled(false);
}
}
/**
* 判断图片 是否可 提交
* @return
*/
private boolean canCommitFromImage(){
boolean canCommit = false;
if(mAdapter.getList().size() <= 0){
canCommit = false;
}else{
canCommit = true;
}
return canCommit;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
/*提交按钮*/
case R.id.aenior_comment:
mCustomButterfly = CustomButterfly.show(mContext);
// 是否登录 ?提交 :跳转登录页面
if(YKCurrentUserManager.getInstance().isLogin()){
/*连网判断*/
if(!NetWorkUtil.isNetworkAvailable(mContext)){
Toast.makeText(mContext, R.string.intent_no, Toast.LENGTH_SHORT).show();
return;
}
//防止多次点击
mCommit.setEnabled(false);
/*是否选择图片*/
if(mAdapter.getList().size() > 0){//上传图片
zoomPicture();
}else if(mGetEditText.length() > 0){//提交回复
commitReplay();
}else{
Toast.makeText(mContext, "图片文字必填一项~", Toast.LENGTH_SHORT).show();
mCommit.setEnabled(false);
mCustomButterfly.dismiss();
}
}else{
mCustomButterfly.cancel();//关闭加载页
Intent goLogin = new Intent(mContext,LoginActivity.class);
startActivity(goLogin);
}
break;
//相册按钮
case R.id.photo_album_layout:
if(mAdapter.getList().size() >= 3){
Toast.makeText(mContext, R.string.aenior_nonice_image, Toast.LENGTH_SHORT).show();
return;
}
Intent intentImage = new Intent(mContext,SelectAlbumActivity.class);
// intentImage.putExtra(SelectPictureActivity.INTENT_MAX_NUM, 3);//选择三张
intentImage.putExtra(SelectPictureActivity.INTENT_SELECTED_PICTURE,mAdapter.getList());
startActivityForResult(intentImage,11);
break;
//拍照按钮
case R.id.taking_pictures_layout:
if(mAdapter.getList().size() >= 3){
Toast.makeText(mContext, R.string.aenior_nonice_image, Toast.LENGTH_SHORT).show();
return;
}
mOutputFile = new File(Environment.getExternalStorageDirectory() + "/",BitmapUtil.getPhotoFileName());
Intent intentFromCapture = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
// 判断存储卡是否可以用
if (YKUtil.hasSdcard()) {
intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(mOutputFile));
}else{
Toast.makeText(mContext, "储存卡不可用~", Toast.LENGTH_SHORT).show();
}
startActivityForResult(intentFromCapture, 1);
break;
case R.id.aenior_back_layout:
mAeniorEdit.clearFocus();
YKUtil.hideKeyBoard(AeniorReplayActivity2.this, mAeniorEdit);
finish();
default:
break;
}
}
private void zoomPicture() {
new Thread(){
@Override
public void run() {
//循环挨个压缩
for(int i = 0; i < mAdapter.getList().size();i++){
tempBitmap = BitmapUtilImage.getLocationBitmap(mAdapter.getList().get(i));
if(tempBitmap != null){
String path = BitmapUtil.saveMyBitmap("temp"+i, tempBitmap);
mtempList.add(path);
if(null != tempBitmap){
tempBitmap.recycle();
}
}else{
mHandler.sendEmptyMessage(203);
}
}
mHandler.sendEmptyMessage(201);
}
}.start();
}
/**
* 请求网络
* 1.上传图片
* 2.完成开始提交
*/
private void uploadImage() {
for (String tempPath : mtempList) {
YKUploadImageManager.getInstance().uploadImages(tempPath, new UploadImageCallback()
{
@Override
public void callback(YKResult result, String imageUrl)
{
times ++;
if(result.isSucceeded()){
size ++;
mImageUploadUrl.add(imageUrl);
}else{
Toast.makeText(mContext, "这一张失败了…", Toast.LENGTH_SHORT).show();
}
if(times == mAdapter.getList().size()){
mHandler.sendEmptyMessage(200);
}
}
});
}
}
/**
* 请求网络 提交回复
*/
private void commitReplay() {
String typeId = "";
switch (type) {
//心得高级回复
case 1:
typeId = mCommentID;
break;
// 资讯高级回复
case 2:
typeId = mmCommentIDInfo;
break;
default:
break;
}
YKCommentreplyManager.getInstance().postAeniorReply(YKCurrentUserManager.getInstance().getUser().getToken(), typeId, mGetEditText, mImageUploadUrl,type,new ReplyCallback()
{
@Override
public void callback(YKResult result)
{
mCommit.setEnabled(true);
AppUtil.dismissDialogSafe(mCustomButterfly);
if(result.isSucceeded()){
Toast.makeText(mContext, "发布成功", Toast.LENGTH_SHORT).show();
Intent mIntent = new Intent();
mIntent.putStringArrayListExtra("ListViewImag", mImageUploadUrl);
mIntent.putExtra("textChange", mGetEditText);
setResult(66, mIntent);
setResult(22,mIntent);
finish();
}else{
Toast.makeText(mContext, result.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* 调用系统裁剪图片的方法,可以选择参数为Uri对象 或者 Bitmap对象
* @param uri
*/
private void startPhotoZoom(Uri uri) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
// 设置裁剪
intent.putExtra("crop", "true");
// aspectX aspectY 是宽高的比例
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
// outputX outputY
// 是裁剪图片宽高http://page.yy.com/login_layer/?action=login&fromClient=pcyy&uid=227811995&ticket=boIBvzCCAbugAwIBBaEDAgEOogcDBQAAAAAAo4IBL2GCASswggEnoAMCAQWhERsPeXkuY29tAAAEAAENlCKbohEwD6ADAgEBoQgwBhsENTA2MKOB%2BTCB9qAEAgIBFaEDAgECooHoBIHlOAJQkzgCUJPQll2T0JZdk2bOoWwXKn8GUiSdnMvpa0aWAfgHxRPixJypC6j5SEVy2r3OXSiW8sQdRciMZXm8OQkwqS8E7DaCU7ady%2Blk5CzzXkN1wcKCzmR88XFvYF7HvRFod8UT4jR82WtYp%2FyZzIX60Eylgnsp%2Fuk9OssUL1BuMz4vOjawC24X0ggfdye26NWZXTUMjzI7TIe%2FbryVBS6sQYePJgzsZLB9jJ%2FphDWN7oyVqiceCUq6nUCNrfkipZhbGkB1Zukyzrnt3Xpj8oZGYeAoq21nBQMCAQuTUAHQk1AB0KRzMHGgAwIBEaJqBGgUbAaVVXwLn0%2FoymtCyIklZVERmfHmw2omM6VGZ0ODpaSY%2BXJ8sFBDY6BaYO9BlThzj6L9Yt6jOkOjiviOVv%2B%2F5heejcXeHihjaa0JTycOYDvw7fd37LeyozFtgLFDUYT6BsngxiyAsg%3D%3D#
intent.putExtra("outputX", 750);
intent.putExtra("outputY", 750);
intent.putExtra("return-data", false);
//uritempFile为Uri类变量,实例化uritempFile
uritempFile = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" +BitmapUtil.getPhotoFileName());
intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(intent, 4);
}
public boolean canCommit(){
if(mGetEditText.length() > 0){
return true;
}
return false;
}
/**
* 友盟统计需要的俩个方法
*/
public void onResume() {
super.onResume();
MobclickAgent.onPageStart("AeniorReplayActivity2"); // 统计页面
MobclickAgent.onResume(this); // 统计时长
}
public void onPause() {
super.onPause();
MobclickAgent.onPageEnd("AeniorReplayActivity2"); // 保证 onPageEnd
// 在onPause
// 之前调用,因为 onPause
// 中会保存信息
MobclickAgent.onPause(this);
}
@Override
protected void onDestroy() {
tempBitmap = null;
YKActivityManager.getInstance().removeActivity(this);
super.onDestroy();
}
}
|
Java
|
UTF-8
| 1,291
| 2.46875
| 2
|
[] |
no_license
|
package com.cd.handlers;
import com.cd.editors.MyDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
@Controller //表示当前类是一个处理器
@RequestMapping("/test") //放到类名上,就是命名空间
public class MyController {
@RequestMapping("/register.do")
public ModelAndView doRegister(int age, Date birthday) {
ModelAndView mv = new ModelAndView();
mv.addObject("age", age);
mv.addObject("birthday", birthday);
mv.setViewName("/WEB-INF/jsp/welcome.jsp");
return mv;
}
@InitBinder
public void initBinder(WebDataBinder binder) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
//绑定单个日期类型
//binder.registerCustomEditor(Date.class, new CustomDateEditor(df, true));
//绑定多个日期类型
binder.registerCustomEditor(Date.class, new MyDateEditor());
}
}
|
Python
|
UTF-8
| 196
| 3.21875
| 3
|
[] |
no_license
|
import numpy as np
a = np.arange(9)
a = a.reshape(3, 3)
print(a)
b = np.arange(16)
b = b.reshape(4, 4)
print(b)
print(b.min(axis=0))
print(b.min(axis=1))
print(a.min(axis=0))
print(a.min(axis=1))
|
Markdown
|
UTF-8
| 2,447
| 2.6875
| 3
|
[] |
no_license
|
---
copyright:
years: 2014, 2019
lastupdated: "2019-06-18"
keywords: manage bare metal port control
subcollection: bare-metal
---
{:shortdesc: .shortdesc}
{:codeblock: .codeblock}
{:screen: .screen}
{:new_window: target="_blank"}
{:pre: .pre}
{:table: .aria-labeledby="caption"}
# Gestión del control de puerto para un dispositivo
{: #bm-manage-port-control}
Cada dispositivo asociado con una cuenta tiene dos puertos de red que reciben tráfico entrante, uno para el tráfico de red pública y otro para el tráfico de red privada. Puede habilitar o inhabilitar estos puertos en cualquier momento para controlar el tráfico de red que recibe un dispositivo. Siga los pasos siguientes para actualizar los valores de control de puerto para un dispositivo.
## Antes de empezar
* Navegue hasta el menú del dispositivo de la consola. Para obtener más información, consulte [Navegación a dispositivos](/docs/bare-metal?topic=virtual-servers-navigating-devices).
* Asegúrese de tener los permisos de cuenta y el acceso al dispositivo necesarios. Solo el propietario de la cuenta, o un usuario con el permiso de la infraestructura clásica **Gestionar usuarios**, puede ajustar los permisos.
Para obtener más información sobre permisos, consulte [Permisos de la infraestructura clásica](/docs/iam?topic=iam-infrapermission#infrapermission) y [Gestión del acceso a dispositivos](/docs/bare-metal?topic=virtual-servers-managing-device-access).
## Gestionar el control de puerto para un dispositivo
1. Acceda a la **Lista de dispositivos** y seleccione el **Nombre de dispositivo** que desea actualizar.
2. Pulse la lista desplegable **Acciones** correspondiente al dispositivo.
3. Seleccione **Control de puerto**.
4. Actualice los recuadros desplegables *Red pública* y/o *Red privada* realizando una de las acciones siguientes:
* Seleccione la velocidad deseada para habilitar el acceso de red.
* Seleccione Desconectado para inhabilitar el acceso de red.
5. Pulse el botón Actualizar.
6. Pulse el botón Cerrar para cerrar la ventana.
## Pasos siguientes
Si ha seleccionado **Inhabilitado**, el acceso de red para el puerto inhabilitado cesará para la interfaz de dispositivo. Si ha seleccionado **Habilitado**, el acceso de red estará disponible para el puerto habilitado. El control de puerto permanece en el valor seleccionado hasta que se haya modificado manualmente.
|
PHP
|
UTF-8
| 2,984
| 2.625
| 3
|
[] |
no_license
|
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
ob_start();
require 'vendor/autoload.php';
if(isset($_POST['submit'])){
if(isset($_POST['email']) and isset($_POST['topic']) and isset($_POST['content'])){
$contact_email = $_POST['email'];
$topic = $_POST['topic'];
$content = $_POST['content'];
$body = "<table>
<tr>
<td><b>Email :</b></td>
<td>$contact_email</td>
</tr>
<tr>
<td><b>Topic :</b></td>
<td>$topic</td>
</tr>
<tr>
<td><b>Content :</b><br>$content</td>
</tr>
</table>";
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
//Server settings
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->SMTPDebug = 0; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = "zgmfsrike@gmail.com"; // SMTP username
$mail->Password = 'amenoera7744'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
//Recipients
$mail->setFrom('info@chtour.com', 'Chiangmai HongThai');
$mail->addAddress('chiangmaihongthai@hotmail.com');
// Add a recipient
// $mail->addAddress('ellen@example.com'); // Name is optional
// $mail->addReplyTo('info@example.com', 'Information');
// $mail->addCC('cc@example.com');
// $mail->addBCC('bcc@example.com');
//Attachments
// $mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
// $mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $topic;
$mail->Body = $body;
$mail->AltBody = strip_tags($body);
$mail->send();
header("location: index.php?send_mail=done");
ob_end_flush();
// echo 'Message has been sent';
} catch (Exception $e) {
header("location: index.php?send_mail=unsuccessful");
ob_end_flush();
// echo 'Message could not be sent.';
// echo 'Mailer Error: ' . $mail->ErrorInfo;
}
}
}
?>
|
C++
|
UTF-8
| 2,001
| 2.65625
| 3
|
[] |
no_license
|
#include <opencv2\opencv.hpp>
void manage_bounding_boxes(std::vector<cv::Rect>* bb, cv::Rect* mean){
//TODO TEST Join multiple bounding boxes
if(!bb || !mean) return;
int xx = INT_MAX,yy = INT_MAX, ww = INT_MIN,hh = INT_MIN;
for(unsigned int i = 0 ; i < bb->size() ; i++){
//if(bb->at(i).x >= 0 && bb->at(i).y >= 0 && bb->at(i).width >= 0 && bb->at(i).height >= 0){
if(bb->at(i).x < xx) xx = bb->at(i).x;
if(bb->at(i).y < yy) yy = bb->at(i).y;
if((bb->at(i).x + bb->at(i).width) > ww) ww = (bb->at(i).x + bb->at(i).width);
if((bb->at(i).y + bb->at(i).height) > hh) hh = (bb->at(i).y + bb->at(i).height);
//}
}
mean->x = xx;
mean->y = yy;
mean->width = ww-xx;
mean->height = hh-yy;
}
int main(){
cv::Mat3b img = cv::imread("contours2.png");
cv::Mat img_f;
cv::Mat1b img_b(img.size());
cv::Mat3b out(img.size());
cv::cvtColor( img, img_f, CV_BGR2GRAY );
cv::threshold(img_f,img_b,0.1,255,cv::THRESH_BINARY);
cv::vector<cv::vector<cv::Point> > contours;
cv::vector<cv::Vec4i> hierarchy;
// img_b.convertTo(coiso,CV_32F);
cv::Mat threshold_output;
cv::findContours( img_b, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0) );
for( int i = 0; i < contours.size(); i++ ){
cv::drawContours(out,contours,i,cv::Scalar(255,0,0),-1,16);
}
cv::Rect bbox;
if(contours.size()){
//Multiples BBoxes
if(contours.size() > 1){
//Create array of BBoxes
cv::vector<cv::Rect> bound_rects( contours.size() );
for(unsigned int i = 0; i < contours.size(); i++ ){
bound_rects[i] = boundingRect( cv::Mat(contours[i]) );
}
//Join Bounding Boxes (Only one BBoxe per user)
manage_bounding_boxes(&bound_rects,&bbox);
//bbox = boundingRect( cv::Mat(contours[0]) );
}
else{
//Only one user
bbox = boundingRect( cv::Mat(contours[0]) );
}
}
cv::rectangle(out,bbox,cv::Scalar(0,0,255));
cv::imshow("sa",out);
//cv::imwrite("img_q_2.png",img);
cv::waitKey();
return 0;
}
|
Python
|
UTF-8
| 917
| 3.96875
| 4
|
[] |
no_license
|
# https://www.interviewbit.com/courses/programming/topics/arrays/problems/spiral1/
# return a spiral representation of an array
def getSpiral(arr):
x1, y1, x2, y2, direction, res = 0, 0, len(arr[0]) - 1, len(arr) - 1, 'right', []
while x1 <= x2 and y1 <= y2:
if direction == 'right':
for i in xrange(x1, x2 + 1):
res.append(arr[y1][i])
direction, y1 = 'down', y1 + 1
elif direction == 'down':
for i in xrange(y1, y2 + 1):
res.append(arr[i][x2])
direction, x2 = 'left', x2 - 1
elif direction == 'left':
for i in xrange(x2, x1 - 1, -1):
res.append(arr[y2][i])
direction, y2 = 'up', y2 - 1
elif direction == 'up':
for i in xrange(y2, y1 - 1, -1):
res.append(arr[i][x1])
direction, x1 = 'right', x1 + 1
return res
|
PHP
|
UTF-8
| 191
| 3.203125
| 3
|
[] |
no_license
|
<?php
##$a에 1을 더한 후 $a 값을 $b에 대입하기
$a = 0;
$b = ++$a;
echo "\$a는 {$a}, \$b는{$b}<br>";
## $a는 1, $b는 1
$a = 0;
$b = $a++;
echo "\$a는 {$a}, \$b는{$b}";
?>
|
Python
|
UTF-8
| 1,787
| 2.546875
| 3
|
[] |
no_license
|
import os
import sys
from sqlalchemy import Column, ForeignKey, Integer, String, Float
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
Base = declarative_base()
class ShopOwner(Base):
__tablename__= 'shop'
id = Column( Integer, primary_key=True)
name = Column( String(100), nullable=False)
description = Column( String(500))
email = Column( String(100))
username = Column( String(100))
#Serialize DB info for json use
@property
def serialize(self):
return{
'id' : self.id,
'name' : self.name,
'description' : self.description,
'email' : self.email,
'username' : self.username
}
class Piece(Base):
__tablename__ = 'piece'
id = Column(Integer, primary_key=True)
name = Column(String(300), nullable=False)
quantity = Column(Integer, nullable = False)
description = Column(String(500))
department = Column(String(300), nullable=False)
image = Column(String)
shop_id = Column(Integer, ForeignKey('shop.id'))
shop = relationship(ShopOwner)
#Serialize DB info for json use
@property
def serialize(self):
return{
'id' : self.id,
'name' : self.name,
'quantity' : self.quantity,
'description' : self.description,
'department' : self.department,
'image' : self.image,
'shop_id' : self.shop_id
}
class Department(Base):
__tablename__ = 'dept'
name = Column( String(100), nullable=False, primary_key=True)
piece_match = Column(String(300), ForeignKey('piece.department'))
match = relationship(Piece)
#Serialize DB info for json use
@property
def serialize(self):
return {
'name' : self.name,
'piece_match' : self.piece_match
}
engine = create_engine('sqlite:///shoppieces.db')
Base.metadata.create_all(engine)
|
Java
|
UTF-8
| 240
| 1.929688
| 2
|
[] |
no_license
|
package common;
public class Config {
/**
* Specify the browser and platform for test:
* CHROME_MAC
* CHROME_WINDOWS
* MOZILLA_MAC
**/
public static final String BROWSER_AND_PLATFORM = "CHROME_WINDOWS";
}
|
Java
|
UTF-8
| 2,407
| 2.1875
| 2
|
[] |
no_license
|
package com.kodgemisi.assignment.controllers;
import java.sql.Timestamp;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionKey;
import org.springframework.social.connect.ConnectionRepository;
import org.springframework.social.facebook.api.Facebook;
import org.springframework.social.facebook.api.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.kodgemisi.assignment.components.RandomStringGenerator;
import com.kodgemisi.assignment.domains.form.RegisterForm;
import com.kodgemisi.assignment.services.interfaces.SecurityService;
import com.kodgemisi.assignment.services.interfaces.UserService;
@Controller
@RequestMapping(value="facebook")
public class FacebookController {
@Autowired
private ConnectionRepository connectionRepository;
@Autowired
private SecurityService securityService;
@Autowired
private UserService userService;
@Autowired
private Facebook facebook;
@Autowired
private RandomStringGenerator passwordGenerator;
@RequestMapping(value="/auth", method=RequestMethod.GET)
public String findUser(Model model){
ConnectionKey connectionKey = connectionRepository.findPrimaryConnection(Facebook.class).getKey();
String userKey = connectionRepository.findPrimaryConnection(Facebook.class).getKey().getProviderUserId();
String[] fields = {"id", "email"};
User facebookUser = facebook.fetchObject(userKey, User.class, fields);
com.kodgemisi.assignment.domains.User currentUser = userService.getUserByEmail(facebookUser.getEmail());
String currentPassword = null;
if(currentUser == null){
RegisterForm registerForm = new RegisterForm();
currentPassword = passwordGenerator.generateRandomString(8);
registerForm.setEmail(facebookUser.getEmail());
registerForm.setPassword(currentPassword);
userService.save(registerForm);
}else{
currentPassword = currentUser.getPassword();
}
securityService.autoLogin(facebookUser.getEmail(), currentPassword);
connectionRepository.removeConnection(connectionKey);
return "redirect:/homepage";
}
}
|
Rust
|
UTF-8
| 1,201
| 2.6875
| 3
|
[] |
no_license
|
use futures::executor::block_on;
use planner::engine::db_wrapper::event::Event;
use planner::engine::db_wrapper::{event, Connection};
#[test]
fn add_and_remove() {
let pool = Connection::new();
let pool = &pool.unwrap().pool;
let event = Event::new()
.title("Test")
.date(chrono::Utc::now() + chrono::Duration::days(69));
let event = block_on(event::insert_event(&pool, &event)).unwrap();
block_on(event::delete_by_id(&pool, &event.id)).unwrap();
}
#[test]
fn remove_nonexistent_event() {
let pool = Connection::new();
let pool = &pool.unwrap().pool;
let event = Event::new().date(chrono::Utc::now() + chrono::Duration::days(23));
let event = block_on(event::insert_event(&pool, &event)).expect("Inserting failed.");
block_on(event::delete_by_id(&pool, &event.id)).unwrap();
assert_eq!(
block_on(event::delete_by_id(&pool, &event.id))
.unwrap()
.rows_affected(),
0
);
}
#[test]
fn get_all_events_test() {
let pool = Connection::new();
let pool = &pool.unwrap().pool;
let events = block_on(event::get_all_user_events(pool, "tester")).unwrap();
assert_eq!(events.len(), 2);
}
|
Markdown
|
UTF-8
| 9,250
| 3.078125
| 3
|
[] |
no_license
|
## How to get email alert when your website is down using shell and Python?
There are many ways to monitor and set alerts for your web server using third party apps but they don't come with free, be it Pingdom or Amazon's CloudWatch. In this post I am going to show how we can write and setup our own alert tool with just few lines of code.
However before going further into codes let us see what are the commands and utilities available in Linux to monitor web server health.
> All the below commands are very basic and available on all Linux flavors. I am running these commands on Ubuntu 20.04 LTS for below demos
#### What we will learn in this article?
📗 How to check if a website is up and running or down?</br>
📙 How to write a basic shell script?</br>
📗 How to call Python program from shell script?</br>
💡 How to send an email using Python?</br>
### How to check if web server is up and running?
There are many commands and utilities available to monitor if your website or app is up and running fine. I have listed few of them. Lets checkout
👉 **curl** </br>
👉 **wget**</br>
👉 **ping**</br>
#### Curl
**curl** is a very powerful utility to send and receive data over many supported protocols such as HTTP,FTP, SMTP...
We are going to use **curl** with **I** options to fetch the headers from a website. Based on the header we can identify if server is down or up. Lets try it
**USAGE: ** curl -I SERVER IP
```
shaikh@ubuntu:~/scripts$ curl -I "https://hashnode.com"
HTTP/2 200
date: Thu, 29 Oct 2020 17:35:18 GMT
content-type: text/html; charset=utf-8
cache-control: public, s-maxage=1800, max-age=0
etag: W/"4436a-AFOlSSR9igz5hRyOL+SdGTPJfxk"
vary: Accept-Encoding
x-frame-options: Deny
x-powered-by: Next.js
cf-cache-status: HIT
age: 1020
cf-request-id: 061706b33c0000051308a22000000001
```
As shown above **curl -I** returns header and the very first line (HTTP/2 200 ) tells us that webserver for **hashnode** is up and running. Note that server is up and running as long as the response code is 200,301,302,308. In above example response code is 200 , so its up.
#### wget
This is another utility in linux used as network down loader. We will use option **-S** to get the headers from a website.
**USAGE:**
> wget -s SERVER : This will fetch and download the headers and pages of a website
> wget -S --spider SERVER :This will work exact similar way as above except that it will behave as web spider and wont download the pages.
```
shaikh@ubuntu:~/scripts$ wget -S --spider http://shaikhu.com
URL transformed to HTTPS due to an HSTS policy
Spider mode enabled. Check if remote file exists.
--2020-10-29 10:47:55-- https://shaikhu.com/
Resolving shaikhu.com (shaikhu.com)... 192.241.200.144
Connecting to shaikhu.com (shaikhu.com)|192.241.200.144|:443... connected.
HTTP request sent, awaiting response...
HTTP/1.1 302 Found
Alt-Svc: h3-29=":443"; ma=2592000
Content-Length: 206
Content-Type: text/plain; charset=utf-8
Date: Thu, 29 Oct 2020 17:47:55 GMT
```
As shown above the returned response code is **302** for redirection, so our server is up.
#### Ping
**Ping** is most common utility to check the web server's health. It sends ICMP ECHO_REQUEST to network host to get the up information. We are going to use **-C** count option to send n number of request packets.
**USAGE**
> ping -c COUNT SERVER
> Above command will send COUNT no of request packets to SERVER
```
shaikh@ubuntu:~/scripts$ ping -c 3 shaikhu.com
PING hashnode.network (192.241.200.144) 56(84) bytes of data.
64 bytes from 192.241.200.144 (192.241.200.144): icmp_seq=1 ttl=55 time=38.2 ms
64 bytes from 192.241.200.144 (192.241.200.144): icmp_seq=2 ttl=55 time=34.0 ms
64 bytes from 192.241.200.144 (192.241.200.144): icmp_seq=3 ttl=55 time=36.0 ms
--- hashnode.network ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2003ms
rtt min/avg/max/mdev = 33.954/36.039/38.178/1.724 ms
shaikh@ubuntu:~/scripts$
```
As shown above we sent 3 packets and received 3 packets as well, so that means our website is up and running
### How to write a basic shell script?
Now that we know which commands and utility to use to know the status of our website, so lets get started. We are going to issue the command
#### Step 1 : Create a new file for shell script
Lets create a new file named *alert.sh* and save it to your home folder. We can use any of the above command to know the status of a website. I am going to use **wget**'s web spider option to get the details. However you can use any of them.
Before writing any script, note the exact location of *bash*
```
shaikh@ubuntu:~/scripts$ which bash
/usr/bin/bash
```
Now lets start writing shell script *alert.sh*
```
#!/usr/bin/bash
MYHOST="https://YOUR WEBSITE ADDRESS"
if wget --spider -S $MYHOST 2>&1 | grep -w "200\|301\|302\|308" > /dev/null
then
echo "server is up"
else
#Server is down"
/usr/bin/python3 send_alert.py
fi
```
This is a very simple script to monitor your web server and send an email notification if its down. Lets understand what we did line by line.
In the very first line we are providing location of *bash* which was found in the previous step above
then we have saved our website address in a variable named MYHOST
From line number 3 we are executing the *wget* command in an *if else* statement. If the return code from wget is other than 200,301,302 and 308 then control will move to else block considering server is down or unreachable.
In this step you can change the command to *ping* or *curl* as you like
In the *else* block we are executing a Python file named *send_alert.py* to send an email notification. You can ignore this step if you are sending email using MAILX of linux package within shell script. However I dont want to install any third party library and want to use existing Python library to send the email.
### How to send an email using Python?
Writing an email using Python is very simple. No third party library is needed to send an email. Here we are using Python's inbuilt library *smtplib* to send an email.
As shown rest of the code is pretty simple. We have defined **FROM_EMAIL**,**Password**, **TO_EMAIL**,**header** and finally **body**
Lets see what our *send_alert* looks like
```
import smtplib
FROM = 'FROM EMAIL ADDRESS'
PSWD = 'YOUR PASSWORD'
TO = 'TO EMAIL ADDRESS'
#Subject and header
SUB = 'Subject: Alert for shaikhu.com \n'
header = 'To:' + TO + '\n' + 'From: ' + FROM + '\n' + SUB
#Message
body = """
MAY DAY! MAY DAY!! MAY DAY!!!
Your webserver for shaikhu.com is DOWN."""
message = header + body
#Define function to send email
def sendalert(msg):
smtpObj = smtplib.SMTP('smtp.mail.yahoo.com', 587)
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.login(FROM, PSWD)
smtpObj.sendmail(FROM,TO,msg)
smtpObj.quit()
if __name__ == '__main__':
sendalert(message)
```
Congratulations!!🥳. We have just wrote our own script to monitor our server and send us an email notification if it is down. Now all we have to do is put this script on a scheduler or cron table so that the script will run every **n** no of minutes and keep monitoring our website.
#### Add the job to scheduler or crontab
If you want to know how to setup job scheduler using crontab then please do check my article [https://shaikhu.com/how-to-schedule-and-manage-tasks-using-crontab](https://shaikhu.com/how-to-schedule-and-manage-tasks-using-crontab)
```
*/5 * * * * sh alert.sh
```
As per above cron table, our alert.sh will be executed every 5 minutes. That means alert.sh will check our website health every 5 minutes and will send me an email if the website is down.
This is how the email from my script looks like.

### Conclusion
Though there are many websites are providing website alert service but not all of them are free. As seen in this article with just few lines of code, you can build your own alert app that will keep monitoring your website every moment and will send an email notifications when its down.
We have learned some important commands and codes such as how to check website is down or up and how to send email using Python and also how to write a basic shell script.
Hope this tutorial helped you learn something new today. Let me know your thoughts in the comment section 😃.
#### References
1. [https://docs.python.org/3/library/smtplib.html#smtplib.SMTP.sendmail](https://docs.python.org/3/library/smtplib.html#smtplib.SMTP.sendmail)
#### My other recent posts
- How to change desktop wallpaper every minute using Python [Change desktop wallpaper](https://shaikhu.com/how-to-auto-change-desktop-wallpaper-every-minute-using-python)
- Files, Folders and Python [Files,folders and Python](https://shaikhu.com/files-folders-and-python)
- How to keep your computer awake [Keep computer awake](https://shaikhu.com/how-to-keep-your-computer-awake-using-python)
- How to monitor CPU utilization in Linux [cpu utilization](https://shaikhu.com/how-to-monitor-cpu-utilization-in-linux)
- How to schedule jobs using crontab [How to use crontab](https://shaikhu.com/how-to-schedule-and-manage-tasks-using-crontab)
|
Java
|
UTF-8
| 1,480
| 3.4375
| 3
|
[] |
no_license
|
import java.util.Scanner;
public class Olympiad {
public static void main(String[] args) {
System.out.println("Enter the starting time:");
Scanner sc = new Scanner(System.in);
int h1 = sc.nextInt();
int m1 = sc.nextInt();
int s1 = sc.nextInt();
System.out.println("Enter the finishing time:");
Scanner sc1 = new Scanner(System.in);
int h2 = sc1.nextInt();
int m2 = sc1.nextInt();
int s2 = sc1.nextInt();
if (0 > h1 || h1 > h2 || h2 > 23 || 0 > m1 || m2 > 59 || 0 > s1 || s1 > 59 || m1 > 59 || s2 > 59) {
System.out.println("Wrong time format!");
} else {
int h1_to_seconds = h1 * 3600;
int m1_to_seconds = m1 * 60;
int start_in_seconds = h1_to_seconds + m1_to_seconds + s1;
int h2_to_seconds = h2 * 3600;
int m2_to_seconds = m2 * 60;
int finish_in_seconds = h2_to_seconds + m2_to_seconds + s2;
int total_duration_in_sec = finish_in_seconds - start_in_seconds;
int duration_hours = total_duration_in_sec / 3600;
int duration_minutes = (total_duration_in_sec % 3600) / 60;
int duration_seconds = total_duration_in_sec - duration_hours * 3600 - duration_minutes * 60;
System.out.println(String.format("Olympiad duration is %d hours, %d minutes, %d seconds", duration_hours, duration_minutes, duration_seconds));
}
}
}
|
JavaScript
|
UTF-8
| 1,236
| 2.859375
| 3
|
[] |
no_license
|
import React, { useState, useEffect } from "react";
import "./App.css";
import PropTypes from 'prop-types';
function AssignmentUsingFunctionComponent() {
const [response, setResponse] = useState([]);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
fetch(
`http://jsonplaceholder.typicode.com/users`,
{
method: "GET"
}
)
.then(res => res.json())
.then(response => {
setResponse(response);
setIsLoading(false);
})
.catch(error => console.log(error));
});
return (
<div>
{isLoading && <p>Wait I'm Loading</p>}
{response.map((c, index) => (
<div key={index}>
{c.name && (
<>
<div>
<h2 style={{ textDecoration: "Underline" }}>
{c.name}
</h2>
<p>{c.address.zipcode}</p>
</div>
<hr />
</>
)}
</div>
))}
</div>
);
}
AssignmentUsingFunctionComponent.propTypes = {
response: PropTypes.array,
isLoading: PropTypes.bool,
name: PropTypes.string,
zipcode: PropTypes.number
}
export default AssignmentUsingFunctionComponent;
|
Python
|
UTF-8
| 4,229
| 2.703125
| 3
|
[] |
no_license
|
import smbus
class DS1307:
_ADDRESS_SECONDS = 0x00
_ADDRESS_MINUTES = 0x01
_ADDRESS_HOURS = 0x02
_ADDRESS_DAY = 0x03
_ADDRESS_DATE = 0x04
_ADDRESS_MONTH = 0x05
_ADDRESS_YEAR = 0x06
_ADDRESS_CONTROL = 0x07
def __init__(self, i2cbus=1, pAddress=0x68): # 7bits + R/W toevoegen
self.bus = smbus.SMBus(1) # pi 1 -> bus 0 vanaf pi2 -> bus 2
self.address = pAddress
def __BCDtoInt(self, data):
# 1001 0011
# 0b(1001) * 10
# 90
#print(bin(data))
return ((data >> 4) * 10) + (data & 0x0F)
# resultaat = 0
# tupple1 = data >> 4
# tupple2 = data & 0x0F
#
# filter = 0x8
# for i in range(3, -1, -1):
# bit = tupple1 & filter
# if bit > 0:
# resultaat += pow(2, i) * 10
# filter = filter >> 1
#
# filter = 0x8
# for i in range(3, -1, -1):
# if (tupple2 & filter) > 0:
# resultaat += pow(2, i)
# filter = filter >> 1
# return resultaat
def __intToBCD(self, data):
return ((data // 10) << 4) | (data % 10)
def __read(self, pRegister):
return self.bus.read_byte_data(self.address, pRegister)
def __write(self, pRegister, pData):
return self.bus.write_byte_data(self.address, pRegister, pData)
# jaren
def getYear(self):
return self.__BCDtoInt(self.__read(self._ADDRESS_YEAR))
def writeYear(self, pJaartal):
return self.bus.write_byte_data(self.address, self._ADDRESS_YEAR, pJaartal)
# maanden
def getMonth(self):
return self.__BCDtoInt(self.__read(self._ADDRESS_MONTH))
def writeMonth(self, pMaand):
return self.bus.write_byte_data(self.address, self._ADDRESS_MONTH, self.__intToBCD(pMaand))
# dagen
def getDay(self):
return self.__BCDtoInt(self.__read(self._ADDRESS_DAY))
def writeDay(self, pDag):
return self.bus.write_byte_data(self.address, self._ADDRESS_DAY, self.__intToBCD(pDag))
# datum
def getDate(self):
return self.__BCDtoInt(self.__read(self._ADDRESS_DATE))
def writeDate(self, pDatum):
return self.bus.write_byte_data(self.address, self._ADDRESS_DATE, self.__intToBCD(pDatum))
# uren
def getHour(self):
return self.__BCDtoInt(self.__read(self._ADDRESS_HOURS))
def writeHour(self, pHour):
return self.bus.write_byte_data(self.address, self._ADDRESS_HOURS, self.__intToBCD(pHour))
# minuten
def getMinute(self):
return self.__BCDtoInt(self.__read(self._ADDRESS_MINUTES))
def writeMinute(self, pMinuut):
return self.bus.write_byte_data(self.address, self._ADDRESS_MINUTES, self.__intToBCD(pMinuut))
# seconden
def getSecond(self):
return self.__BCDtoInt(self.__read(self._ADDRESS_SECONDS))
def writeSecond(self, pSeconden):
return self.bus.write_byte_data(self.address, self._ADDRESS_SECONDS, self.__intToBCD(pSeconden))
# voledige datum
def getFullDate(self):
return str(self.getHour()+ 2) + ":" + str(self.getMinute())
#return str(self.getDay()) + "/" + str(self.getMonth()) + "/" + str(self.getYear()) + " " + str(self.getHour()) + ":" + str(self.getMinute()) + ":" + str(self.getSecond())
def setDateNow(self):
pass
def stopClock(self):
tijdNu = self.getSecond()
self.bus.write_byte_data(self.address, self._ADDRESS_SECONDS, 128 | tijdNu)
print('Klok gestopt')
def getTime(self):
minutes = self.__BCDtoInt(self.__read(self._ADDRESS_MINUTES))
hours = self.__BCDtoInt(self.__read(self._ADDRESS_HOURS))
timeArray = [None] * 4
if (hours < 10) :
timeArray[0] = 0
timeArray[1] = hours
else:
hoursString = str(hours)
timeArray[0] = hoursString[0]
timeArray[1] = hoursString[1]
if (minutes < 10) :
timeArray[2] = 0
timeArray[3] = minutes
else:
minutesString = str(minutes)
timeArray[2] = minutesString[0]
timeArray[3] = minutesString[1]
return timeArray
|
C
|
UTF-8
| 1,680
| 2.703125
| 3
|
[] |
no_license
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_iterate.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mlevieux <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/03/14 12:24:52 by mlevieux #+# #+# */
/* Updated: 2016/05/15 13:36:58 by mlevieux ### ########.fr */
/* */
/* ************************************************************************** */
#include "lem_in.h"
static void loop(t_ant **ants, int *i, int *j)
{
if (!ants[*i]->actual && ants[*i]->path)
ants[*i]->actual = ants[*i]->path->room;
else if (ants[*i]->actual && !ants[*i]->actual->is_end)
{
if (*j)
ft_printf(" ");
ants[*i]->actual = ants[*i]->path->next->room;
ants[*i]->path = ants[*i]->path->next;
ft_print_move(ants[*i]);
(*j)++;
}
(*i)++;
}
int ft_iterate(t_ant **ants, t_path **paths)
{
int i;
int j;
i = 0;
j = 0;
while (ants[i] && ants[i]->path != NULL)
loop(ants, &i, &j);
if (j)
ft_printf("\n");
if ((ants[i] == NULL && ants[i - 1]->actual->is_end) || paths[0] == NULL)
return (0);
j = 0;
while (ants[i] && paths[j] && paths[j]->coeff >= 0)
{
ants[i]->path = paths[j];
paths[j]->coeff--;
j++;
i++;
}
return (1);
}
|
Java
|
UTF-8
| 1,231
| 2.734375
| 3
|
[] |
no_license
|
package com.MyJunit;
import com.MyOther.Junit;
import org.junit.*;
import static org.junit.Assert.assertEquals;
/**
* Created by panghaichen on 2018-06-29 14:13
**/
public class TestJunit {
/**
* 只执行一次,在整个类执行之前执行
*/
@BeforeClass
public static void beforeClass(){
System.out.println("BeforeClass");
}
/**
* 只执行一次,在整个类执行之后执行
*/
@AfterClass
public static void afterClass(){
System.out.println("AfterClass");
}
/**
* 每个测试方法被执行前都被执行一次
*/
@Before
public void before() {
System.out.println("in before");
}
/**
* 每个测试方法被执行后都被执行一次
*/
@After
public void after() {
System.out.println("in after");
}
@Test
public void test() {
Junit junit = new Junit();
assertEquals(8, junit.add(3, 5));
}
@Test
public void test2() {
Junit junit = new Junit();
assertEquals(8, junit.add(3, 5));
}
@Test
@Ignore
public void test3() {
Junit junit = new Junit();
assertEquals(8, junit.add(3, 5));
}
}
|
Markdown
|
UTF-8
| 339
| 2.6875
| 3
|
[] |
no_license
|
# ivr_lab_robotics_2016
Private repository for managing robotics code in IVR 2016 class. Utilises simple PID controllers to navigate a two-wheeled robot around 3 courses: following a line in a fast and efficient manner; following a broken line; navigating around an obstacle placed on a line and finding the line again (using ultrasonic).
|
JavaScript
|
UTF-8
| 2,210
| 2.640625
| 3
|
[] |
no_license
|
class Login extends React.Component {
constructor(props) {
super(props);
this.state = {
email: (this.props.email || ''),
password: (this.props.password || '')
};
}
updateEmail(event) {
this.setState({ email: event.target.value });
}
updatePassword(event) {
this.setState({ password: event.target.value });
}
handleSubmit(event) {
event.preventDefault();
Alerts.add('info', 'Logging in....').update();
this.sendFormData();
}
sendFormData() {
var credentials = {
email: this.state.email,
password: this.state.password
};
var self = this;
$.auth.emailSignIn(credentials)
.then(function(resp) {
self.handleSuccess();
})
.fail(function(resp) {
self.handleFailure();
});
}
handleSuccess() {
Alerts.add('success', 'Logged in.');
window.location.assign('/#/dashboard');
}
handleFailure() {
Alerts.add('danger', 'Login Failed.').update();
}
render() {
if ($.auth.user.id) {
Alerts.add('success', 'Already logged in.');
window.location.assign('/#/dashboard');
return null;
}
return (
<div>
<form onSubmit={this.handleSubmit.bind(this)}>
<div className="form-group">
<label>Email</label>
<input type="text"
name="email"
className="form-control"
placeholder="john.doe@gmail.com"
required={true}
value={this.state.email}
onChange={this.updateEmail.bind(this)} />
</div>
<div className="form-group">
<label>Password</label>
<input type="password"
name="password"
className="form-control"
placeholder="Pa$$w0rd"
required={true}
value={this.state.password}
onChange={this.updatePassword.bind(this)} />
</div>
<div className="actions">
<input type="submit"
className="btn btn-success"
value="Login" />
</div>
</form>
</div>
);
}
};
|
TypeScript
|
UTF-8
| 182
| 2.921875
| 3
|
[] |
no_license
|
export class SkyObject {
ra = 0; // right ascension
dec = 0; // declination
constructor(ra: number, dec: number) {
this.ra = ra;
this.dec = dec;
}
}
|
C++
|
UTF-8
| 5,819
| 3.046875
| 3
|
[] |
no_license
|
// BiTree.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "my.h"
HRESULT buildTree(const char *,int *pIndex,LPBITREE * ppTreeNode);
HRESULT preOrderTraverseTree(LPBITREE pRootNode);
HRESULT inOrderTraverseTree(LPBITREE pRootNode);
HRESULT postOrderTraverseTree(LPBITREE pRootNode);
HRESULT preOrderTraverseTreeUseStack(LPBITREE pRootNode, LPDATASTACK pDataStack);
HRESULT inOrderTraverseTreeUseStack(LPBITREE pRootNode, LPDATASTACK pDataStack);
HRESULT postOrderTraverseTreeUseStack(LPBITREE pRootNode, LPDATASTACK pDataStack);
int main(int argc, char* argv[])
{
char inputArray[100] = {0},c;
int index = 0,i = 0;
LPBITREE pTreeNode = NULL;
LPDATASTACK pDataStack = NULL;
printf("input a tree in preorder string\n");
c = getchar();
while(c!= '\n')
{
inputArray[i++] = c;
c =getchar();
}
buildTree(inputArray, &index,&pTreeNode);
preOrderTraverseTree(pTreeNode);
putchar('\n');
inOrderTraverseTree(pTreeNode);
putchar('\n');
postOrderTraverseTree(pTreeNode);
putchar('\n');
initDataStack(&pDataStack);
preOrderTraverseTreeUseStack(pTreeNode, pDataStack);
putchar('\n');
inOrderTraverseTreeUseStack(pTreeNode, pDataStack);
printf("\nPostOrder\n");
postOrderTraverseTreeUseStack(pTreeNode,pDataStack);
destroyDataStack(pDataStack);
return 0;
}
HRESULT buildTree(const char * inputArray,int *pIndex,LPBITREE * ppTreeNode)
{
LPBITREE tempNode = NULL;
if (inputArray[*pIndex] == ' ')
{
(*pIndex)++;
*ppTreeNode = NULL;
return S_OK;
}
tempNode = (LPBITREE)malloc(sizeof(BITREE));
if (!tempNode)
{
printf("out of memory");
return S_FALSE;
}
tempNode->data = inputArray[*pIndex];
(*pIndex)++;
buildTree(inputArray, pIndex,&tempNode->pLeftChild);
buildTree(inputArray, pIndex,&tempNode->pRightChild);
*ppTreeNode = tempNode;
return S_OK;
}
HRESULT preOrderTraverseTree(LPBITREE pRootNode)
{
if (!pRootNode)
return S_OK;
printf("%3c",pRootNode->data);
preOrderTraverseTree(pRootNode->pLeftChild);
preOrderTraverseTree(pRootNode->pRightChild);
return S_OK;
}
HRESULT inOrderTraverseTree(LPBITREE pRootNode)
{
if (!pRootNode)
return S_OK;
inOrderTraverseTree(pRootNode->pLeftChild);
printf("%3c",pRootNode->data);
inOrderTraverseTree(pRootNode->pRightChild);
return S_OK;
}
HRESULT postOrderTraverseTree(LPBITREE pRootNode)
{
if (!pRootNode)
return S_OK;
postOrderTraverseTree(pRootNode->pLeftChild);
postOrderTraverseTree(pRootNode->pRightChild);
printf("%3c",pRootNode->data);
return S_OK;
}
HRESULT preOrderTraverseTreeUseStack(LPBITREE pRootNode, LPDATASTACK pDataStack)
{
LPBITREE pTempNode = NULL;
pushDataStack(pDataStack,pRootNode);
while(!isDataStackEmpty(pDataStack))
{
popDataStack(pDataStack, &pTempNode);
printf("%3c",pTempNode->data);
if (pTempNode->pRightChild)
pushDataStack(pDataStack,pTempNode->pRightChild);
if (pTempNode->pLeftChild)
pushDataStack(pDataStack,pTempNode->pLeftChild);
}
return S_OK;
}
HRESULT inOrderTraverseTreeUseStack(LPBITREE pRootNode, LPDATASTACK pDataStack)
{
LPBITREE pTempNode = NULL;
while(pRootNode || !isDataStackEmpty(pDataStack))
{
if (pRootNode)
{
pushDataStack(pDataStack, pRootNode);
pRootNode = pRootNode->pLeftChild;
}
else
{
popDataStack(pDataStack, &pRootNode);
printf("%3c",pRootNode->data);
pRootNode = pRootNode->pRightChild;
}
}
return S_OK;
}
HRESULT postOrderTraverseTreeUseStack(LPBITREE pRootNode, LPDATASTACK pDataStack)
{
LPPOST_NODE_INFO pTempNodeInfo = NULL;
LPBITREE pTempNode;
pTempNodeInfo = (LPPOST_NODE_INFO)malloc(sizeof(POST_NODE_INFO));
pTempNodeInfo->pNode = pRootNode;
pTempNodeInfo->bIsLeftVisited = pRootNode->pLeftChild == NULL;
pTempNodeInfo->bIsRightVisited = pRootNode->pRightChild == NULL;
while(pTempNodeInfo || !isDataStackEmpty(pDataStack))
{
if (pTempNodeInfo)
{
if (pTempNodeInfo->bIsLeftVisited && pTempNodeInfo->bIsRightVisited)
{
printf("%3c",pTempNodeInfo->pNode->data);
}
else if (pTempNodeInfo->bIsLeftVisited)
{
pushDataStack(pDataStack, (LPBITREE)pTempNodeInfo);
pTempNodeInfo = (LPPOST_NODE_INFO)malloc(sizeof(POST_NODE_INFO));
pTempNodeInfo->pNode = pTempNodeInfo->pNode->pRightChild;
pTempNodeInfo->bIsLeftVisited = pTempNodeInfo->pNode->pLeftChild == NULL;
pTempNodeInfo->bIsRightVisited = pTempNodeInfo->pNode->pRightChild == NULL;
}
else if (!pTempNodeInfo->bIsRightVisited)
{
pushDataStack(pDataStack, (LPBITREE)pTempNodeInfo);
pTempNodeInfo = (LPPOST_NODE_INFO)malloc(sizeof(POST_NODE_INFO));
pTempNodeInfo->pNode = pTempNodeInfo->pNode->pRightChild;
pTempNodeInfo->bIsLeftVisited = pTempNodeInfo->pNode->pLeftChild == NULL;
pTempNodeInfo->bIsRightVisited = pTempNodeInfo->pNode->pRightChild == NULL;
}
else
{
pushDataStack(pDataStack, (LPBITREE)pTempNodeInfo);
pTempNodeInfo = (LPPOST_NODE_INFO)malloc(sizeof(POST_NODE_INFO));
pTempNodeInfo->pNode = pTempNodeInfo->pNode->pRightChild;
pTempNodeInfo->bIsLeftVisited = pTempNodeInfo->pNode->pLeftChild == NULL;
pTempNodeInfo->bIsRightVisited = pTempNodeInfo->pNode->pRightChild == NULL;
pushDataStack(pDataStack, (LPBITREE)pTempNodeInfo);
pTempNodeInfo = (LPPOST_NODE_INFO)malloc(sizeof(POST_NODE_INFO));
pTempNodeInfo->pNode = pTempNodeInfo->pNode->pRightChild;
pTempNodeInfo->bIsLeftVisited = pTempNodeInfo->pNode->pLeftChild == NULL;
pTempNodeInfo->bIsRightVisited = pTempNodeInfo->pNode->pRightChild == NULL;
}
}
else
{
popDataStack(pDataStack,&pTempNode);
pTempNodeInfo = (LPPOST_NODE_INFO)pTempNode;
}
}
return S_OK;
}
|
Java
|
UTF-8
| 920
| 2.59375
| 3
|
[] |
no_license
|
package ar.com.kfgodel.associative.materialization.api.config;
import ar.com.kfgodel.associative.materialization.api.ExpectedObjectDefinition;
import ar.com.kfgodel.associative.materialization.api.context.MaterializationContext;
import ar.com.kfgodel.decomposer.api.DecomposableTask;
/**
* This type represents a materializer that knows how to re-create entities and describes the process to do so, with a task
* Created by kfgodel on 17/08/15.
*/
public interface Materializer {
/**
* Creates the task that represents the process to materialize the expected object
* @param definition The definition of teh expected object
* @param materializationContext The context in which to do it
* @return The task to be executed for the materialization to happen
*/
DecomposableTask describeProcessFor(ExpectedObjectDefinition definition, MaterializationContext materializationContext);
}
|
C
|
UTF-8
| 591
| 2.953125
| 3
|
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main(void)
{
int x, y;
for(y=1; y<=7; y++)
{
if(y<=4)
{
for(x=1; x<=13; x++)
{
if(abs(x-7)+1 == y) printf("*");
else printf(" ");
}
printf("\n");
}
else
{
for(x=1; x<=13; x++)
{
if( x==y || 14-x==y ) printf("*");
else printf(" ");
}
printf("\n");
}
}
system("pause"); return(0);
}
|
Markdown
|
UTF-8
| 371
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
[<<< Previous question <<<](0321.md) Question ID#0322.md [>>> Next question >>>](0323.md)
What is the output of the following PHP script:
```php
$a = 10;
$b = "10";
if ($a == $b) {
echo "a";
} else {
echo "b";
}
if ($a === $b) {
echo "c";
} else {
echo "d";
}
```
Enter the exact script output
- [x] ad
- [ ] ac
- [ ] bd
- [ ] da
|
C
|
UTF-8
| 985
| 3.4375
| 3
|
[] |
no_license
|
/**
* SO
* Lab #4
*
* Task #2, Linux
*
* Catching signals
*/
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include "utils.h"
int normal_count;
int real_count;
int done;
static void sig_handler(int signum)
{
switch (signum) {
case SIGINT:
usleep(100000);
normal_count++;
break;
case 34:
usleep(100000);
real_count++;
break;
case SIGQUIT:
done = 1;
break;
}
}
int main(void)
{
struct sigaction signals;
sigset_t mask;
int rc;
sigfillset(&mask);
memset(&signals, 0, sizeof(struct sigaction));
signals.sa_mask = mask;
signals.sa_handler = sig_handler;
rc = sigaction(SIGINT, &signals, NULL);
DIE(rc == -1, "sigaction");
rc = sigaction(SIGQUIT, &signals, NULL);
DIE(rc == -1, "sigaction");
rc = sigaction(SIGRTMIN, &signals, NULL);
DIE(rc == -1, "sigaction");
while (!done)
sleep(1);
printf("Got %d normal signals\n", normal_count);
printf("Got %d real-time signals\n", real_count);
return 0;
}
|
Markdown
|
UTF-8
| 2,324
| 3.0625
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
# Read From STDIN
**Go** is good for small command line utilities. In my process to learn **Go** I wanted to write some small command line utilities so I thought about what command line utilities I was missing...
I used to work with DNS so I decided that the process of opening a browser to find a punycode converter and convert a string to or from punycode, should be done on the command line. I had some **Perl** utilities, so I decided to port these to **Go**.
I found this snippet on [Yourbasic.org/golang][YOURBASIC]
```go
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
if err := scanner.Err(); err != nil {
log.Println(err)
}
```
I implemented some utilities ([punydecode][punydecode] and [punyencode][punyencode]), but after some afterthought I boiled the two into one: [punycode][punycode], since [punycode][wikipedia] is easy to identify due to the prefix: `xn--`, so you could do with a single utility.
Since I wanted my utility to both support a string argument and `STDIN`, I made the following construct:
```go
argsWithoutProg := os.Args[1:]
var argString string
if len(argsWithoutProg) <= 0 {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
argString = scanner.Text()
}
if err := scanner.Err(); err != nil {
log.Println(err)
return 2
}
} else {
argString = os.Args[1] // we only take a single parameter, the string to process
}
```
An issue I have not been able to address it how you test reading from `STDIN` in a **Go** test suite, I could use [**Bats**][bats] or similar, but that would not integrate as well as expected.
## Resources and References
1. [Yourbasic.org/golang: Read a file (stdin) line by line][YOURBASIC]
1. [Go standard library: os - Variables](https://pkg.go.dev/os#pkg-variables)
1. [GitHub: punydecode][punydecode]
1. [GitHub: punyencode][punyencode]
1. [GitHub: punycode][punycode]
1. [Bats][bats]
[YOURBASIC]: https://yourbasic.org/golang/read-file-line-by-line/
[punydecode]: https://github.com/jonasbn/punydecode
[punyencode]: https://github.com/jonasbn/punyencode
[punycode]: https://github.com/jonasbn/punycode
[wikipedia]: https://en.wikipedia.org/wiki/Punycode
[bats]: https://github.com/bats-core
|
Python
|
UTF-8
| 957
| 4.03125
| 4
|
[] |
no_license
|
# I'm establishing my global variables here to be used in conditionals later
fav_game = "The Witcher 3"
second_fav_game = "The Outer Wilds"
fav_film = "Lord of the Rings: The Return of the King"
second_fav_film = "City of God"
# This is my first user input which sets up the 'parent' conditional
game_answer = input("Do you enjoy playing video games? (Yes/No) ")
if game_answer == "Yes":
user_game = input("Nice! What is your favourite game? ")
if user_game == fav_game or user_game == second_fav_game:
print("No way! I love that game!")
else:
print("I have heard that game is great! I need to play it")
else:
user_film = input("Fair Enough! Well what is your favourite film? ")
if user_film == fav_film:
print("You've got brilliant taste!")
elif user_film == second_fav_film:
print("An aficionado of foreign cinema, I see!")
else:
print("I'll make sure to watch it!")
print("Goodbye!")
|
C++
|
UTF-8
| 2,059
| 2.5625
| 3
|
[
"BSL-1.0"
] |
permissive
|
#include "stb_image.h"
#include "../Debug.h"
#include "RenderAssets.h"
namespace Amendieres::Gfx
{
AssetBase* PngTexture2D::Factory(const uint64_t rid)
{
return new PngTexture2D(rid);
}
PngTexture2D::PngTexture2D(const uint64_t rid) : AssetBase(rid, static_cast<int32_t>(AssetType::PngTexture))
{}
bool PngTexture2D::Create(char* data, uint64_t dataCount)
{
int width;
int height;
int actualChannels;
int desiredChannels = STBI_rgb_alpha;
unsigned char* parsedData = stbi_load_from_memory(reinterpret_cast<unsigned char*>(data), dataCount, &width, &height, &actualChannels, desiredChannels);
if (parsedData == NULL)
{
LOG_ERROR("Could not load PNG image: " << stbi_failure_reason());
return false;
}
Texture2D* texPtr = new Texture2D(width, height, reinterpret_cast<uint32_t*>(parsedData), width * height);
if (!texPtr->IsValid())
{
LOG_ERROR("Could not created Texture2D from PNG image: " << stbi_failure_reason());
stbi_image_free(parsedData);
delete texPtr;
return false;
}
stbi_image_free(parsedData);
texture = std::unique_ptr<Texture2D>(texPtr);
return true;
}
void PngTexture2D::Destroy()
{
texture.reset();
}
AssetBase* TrueTypeDynamicFont::Factory(const uint64_t rid)
{
return new TrueTypeDynamicFont(rid);
}
TrueTypeDynamicFont::TrueTypeDynamicFont(const uint64_t rid) : AssetBase(rid, static_cast<int32_t>(AssetType::TrueTypeFont))
{}
bool TrueTypeDynamicFont::Create(char *data, uint64_t dataCount)
{
DynamicFont* fontPtr = new DynamicFont(data, dataCount);
font = std::unique_ptr<DynamicFont>(fontPtr);
//TODO: should be checking if fontPtr is valid. Move id to base renderable class, and IsValid() can be moved there.
return true;
}
void TrueTypeDynamicFont::Destroy()
{
font.reset();
}
}
|
Java
|
UTF-8
| 2,374
| 2.515625
| 3
|
[] |
no_license
|
package org.stevejxsn.alecalphabet;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.inputmethodservice.Keyboard;
import android.inputmethodservice.KeyboardView;
public class MainActivity extends Activity implements AlecKeyboardListener {
private WordImage image;
private WordDisplay word;
private AlecKeyboard keyboard;
private WordChangeHandler wordChanged;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = createWordImage();
word = createWordDisplay();
keyboard = setupKeyboard();
wordChanged = new WordChangeHandler(keyboard, image, new WordSpeaker(this));
new MainActivityInitializer(wordChanged).start();
}
private WordDisplay createWordDisplay() {
TextView textView = (TextView)findViewById(R.id.wordView);
textView.setOnTouchListener(resetOnTouchListener());
return new WordDisplay(textView);
}
private WordImage createWordImage() {
ImageView imageView = (ImageView)findViewById(R.id.imageView);
imageView.setOnTouchListener(resetOnTouchListener());
return new WordImage(imageView);
}
private AlecKeyboard setupKeyboard() {
AlecKeyboard keyboard = new AlecKeyboard((KeyboardView)findViewById(R.id.keyboardview), new Keyboard(this, R.xml.aleckbd));
keyboard.setListener(this);
return keyboard;
}
@Override
public void onLetterKey(char key) {
word.append(Character.toString(key));
String currentWord = word.getText().toString();
wordChanged.currentWordChanged(currentWord);
}
public void reset() {
word.clear();
keyboard.reset();
image.clear();
}
private OnTouchListener resetOnTouchListener() {
return new OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
reset();
return true;
}
};
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
|
C++
|
UTF-8
| 1,099
| 3.140625
| 3
|
[
"MIT"
] |
permissive
|
#include <string>
#include <vector>
#include <iostream>
#include <unordered_map>
#include "assembler.hpp"
using namespace std;
void print_result(vector<string> instructions)
{
unordered_map<string, int> programme = assembler(instructions);
for (auto i = programme.begin(); i != programme.end(); ++i)
{
cout << i->first << ": " << i->second << endl;
}
cout << std::endl;
}
int main(void)
{
print_result({ "mov a 5", "inc a", "dec a", "dec a", "jnz a -1", "inc a" });
print_result({ "mov a -10", "mov b a", "inc a", "dec b", "jnz a -2" });
print_result({ "mov a 1", "mov b 1", "mov c 0", "mov d 26", "jnz c 2", "jnz 1 5", "mov c 7", "inc d", "dec c", "jnz c -2", "mov c a", "inc a", "dec b", "jnz b -2", "mov b c", "dec d", "jnz d -6", "mov c 18", "mov d 11", "inc a", "dec d", "jnz d -2", "dec c", "jnz c -5" });
print_result({ "mov d 100", "dec d", "mov b d", "jnz b -2", "inc d", "mov a d", "jnz 5 10", "mov c a" });
print_result({ "mov c 12", "mov b 0", "mov a 200", "dec a", "inc b", "jnz a -2", "dec c", "mov a b", "jnz c -5", "jnz 0 1", "mov c a" });
return 0;
}
|
C
|
WINDOWS-1252
| 280
| 3.125
| 3
|
[] |
no_license
|
#include<stdio.h>
int main()
{
int x,y,z;
for(x=0;x<=20;x++)
{
for(y=0;y<=33;y++)
{
z=100-x-y;
if(z%3==0&&x*5+y*3+z/3==100)
printf("gj %dmj: %d,xj: %d\n",x,y,z);
}
}
getch();
return 0;
}
|
Java
|
UTF-8
| 530
| 1.867188
| 2
|
[
"Apache-2.0"
] |
permissive
|
package xproject.speech;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.amazon.speech.speechlet.Speechlet;
import com.amazon.speech.speechlet.servlet.SpeechletServlet;
public class XProjectServlet extends SpeechletServlet {
private static final Logger log = LoggerFactory.getLogger(XProjectServlet.class);
private static final long serialVersionUID = 1;
public XProjectServlet() {
this.setSpeechlet((Speechlet) new XProjectSpeechlet());
log.info("XProjectServlet initialized");
}
}
|
Java
|
UTF-8
| 2,584
| 2.140625
| 2
|
[] |
no_license
|
package config;
import java.util.Collections;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.data.RepositoryItemReader;
import org.springframework.batch.item.data.RepositoryItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.Sort;
import model.DupUser;
import model.User;
import repository.DupUserRepository;
import repository.UserRepository;
@Configuration
@EnableBatchProcessing
public class SpringBatchConfig {
@Autowired
private JobBuilderFactory jobs;
@Autowired
private StepBuilderFactory steps;
@Autowired
public UserRepository urepo;
@Autowired
private DupUserRepository duprepo;
@Bean(name = "UserReader")
public RepositoryItemReader<User> reader() {
RepositoryItemReader<User> reader = new RepositoryItemReader<>();
reader.setRepository(urepo);
reader.setMethodName("findAll");
reader.setSort(Collections.singletonMap("userID", Sort.Direction.ASC));
reader.setPageSize(100000);
return reader;
}
@Bean
public ItemProcessor<User,DupUser> itemProcessor() {
return new UserProcessor();
}
@Bean
public RepositoryItemWriter<DupUser> itemWriter()
{
RepositoryItemWriter<DupUser> itemWriter = new RepositoryItemWriter<>();
itemWriter.setRepository(duprepo);
itemWriter.setMethodName("save");
return itemWriter;
}
@Bean(name="step1")
protected Step step1(ItemReader<User> reader,
ItemProcessor<User, DupUser> processor,
ItemWriter<DupUser> writer) {
return steps.get("step1").<User,DupUser> chunk(100000)
.reader(reader).processor(processor).writer(writer).build();
}
@Bean(name = "userJob")
public Job job(@Qualifier("step1") Step step1) {
return jobs.get("userJob").start(step1).build();
}
}
|
C#
|
UTF-8
| 3,068
| 3.5
| 4
|
[] |
no_license
|
#region using statements
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Linq;
using DataJuggler.Core.UltimateHelper;
#endregion
namespace DataJuggler.Core.RandomShuffler
{
#region class ShuffleHelper
/// <summary>
/// This method [Enter Method Description]
/// </summary>
public static class ShuffleHelper
{
#region Methods
#region Shuffle(this IList<T> list)
/// <summary>
/// This class is used to Shuffle a list of type 'T'.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
public static List<T> Shuffle<T>(this IList<T> list)
{
// List
List<T> shuffledList = new List<T>();
// Use the RNGCryptoServiceProvider to create random zeros or 1
RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
// Create the byte array that serves asa
byte[] container = new byte[1];
// if the list exists
if (list != null)
{
// we can't use the collection count it changes
int listCount = list.Count;
// now we have to 'Randomly' pull items and add them to the end results
for (int x = 0; x < listCount; x++)
{
// Fill the topOrBottom byteArray
crypto.GetBytes(container);
// Get the value of topOrBottom
object randomByte = container.GetValue(0);
// if the randomByte exists
if (NullHelper.Exists(randomByte))
{
// local
int randomValue = NumericHelper.ParseInteger(randomByte.ToString(), 0, -1);
// set the randomIndex to the modulas of the the listCount
int randomIndex = randomValue % list.Count;
// verify the index is in range (should always be true)
if ((randomIndex >= 0) && (randomIndex < list.Count))
{
// Add the card from the top half of the list
shuffledList.Add(list[randomIndex]);
}
// Remove the item from the sourceList now that we have it
list.RemoveAt(randomIndex);
}
}
}
// return value
return shuffledList;
}
#endregion
#endregion
}
#endregion
}
|
Java
|
UTF-8
| 1,702
| 3.078125
| 3
|
[
"Apache-2.0"
] |
permissive
|
package com.minicluster.cluster.node;
import java.io.*;
/**
* An endpoint is a socket address. Basically it is the pair hostname:port
*/
public class Endpoint implements Serializable {
private static final long serialVersionUID = 1L;
private static final String separator = ":";
private Integer port;
private String hostname;
public Endpoint(Integer port, String hostname) {
this.port = port;
this.hostname = hostname;
}
public Integer getPort() {
return port;
}
public String getHostname() {
return hostname;
}
@Override
public String toString() {
return String.format("%s%s%d", hostname, separator, port);
}
static public Endpoint fromString(String serializedEndpoint) {
if (serializedEndpoint == null) {
return null;
}
//we expect the format "hostname:port"
String[] split = serializedEndpoint.split(separator);
Integer port = Integer.parseInt(split[0]);
String hostname = split[1];
return new Endpoint(port, hostname);
}
public void serializeToStream(OutputStream outputStream) throws IOException {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
objectOutputStream.writeObject(this);
objectOutputStream.close();
}
public static Endpoint deserializeFromStream(InputStream inputStream) throws IOException, ClassNotFoundException {
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
Endpoint endpoint = (Endpoint) objectInputStream.readObject();
objectInputStream.close();
return endpoint;
}
}
|
Python
|
UTF-8
| 8,135
| 3.1875
| 3
|
[] |
no_license
|
# /*
# (c) 2011 - 2015, Vladimir Agafonkin
# Sun_calc is a Java_script library for calculating sun / moon position and light phases.
# https: // github.com / mourner / suncalc
# */
# // sun calculations are based on http: // aa.quae.nl / en / reken / zonpositie.html formulas
# // date / time constants and conversions
from math import cos, sin, acos, asin, atan, tan, pi, floor
day_ms = 1000 * 60 * 60 * 24,
J1970 = 2440588,
J2000 = 2451545
def to_julian(date):
return date.value_of() / day_ms - 0.5 + J1970
def from_julian(j):
return new Date((j + 0.5 - J1970) * day_ms)
def to_days(date):
return to_julian(date) - J2000
# general calculations for position
e = radians(23.4397) # obliquity of the Earth
def right_ascension(l, b):
return atan(sin(l) * cos(e) - tan(b) * sin(e), cos(l))
def declination(l, b):
return asin(sin(b) * cos(e) + cos(b) * sin(e) * sin(l))
def azimuth(H, phi, dec):
return atan(sin(H), cos(H) * sin(phi) - tan(dec) * cos(phi))
def altitude(H, phi, dec):
return asin(sin(phi) * sin(dec) + cos(phi) * cos(dec) * cos(H))
def sidereal_time(d, lw):
return radians(280.16 + 360.9856235 * d) - lw
def astro_refraction(h):
if h < 0: # the following formula works for positive altitudes only.
h = 0 # if h = -0.08901179 a div / 0 would occur.
# // formula 16.4 of "Astronomical Algorithms" 2nd edition by Jean Meeus(Willmann - Bell, Richmond) 1998.
# // 1.02 / tan(h + 10.26 / (h + 5.10)) h in degrees, result in arc minutes -> converted to rad:
return 0.0002967 / tan(h + 0.00312536 / (h + 0.08901179))
# general sun calculations
def solar_mean_anomaly(d):
return radians(357.5291 + 0.98560028 * d)
def ecliptic_longitude(M):
C = radians(1.9148 * sin(M) + 0.02 * sin(2 * M) +
0.0003 * sin(3 * M)) # equation of center
P = radians(102.9372) # perihelion of the Earth
return M + C + P + pi
def sun_coords(d):
M = solar_mean_anomaly(d),
L = ecliptic_longitude(M)
return {
"dec": declination(L, 0),
"ra": right_ascension(L, 0)
}
Sun_calc = {}
# calculates sun position for a given date and latitude / longitude
def get_position(date, lat, lng):
lw = radians(-lng)
phi = radians(lat)
d = to_days(date)
c = sun_coords(d)
H = sidereal_time(d, lw) - c.ra
return {
"azimuth": azimuth(H, phi, c.dec),
"altitude": altitude(H, phi, c.dec)
}
# sun times configuration(angle, morning name, evening name)
times = [
[-0.833, 'sunrise', 'sunset'],
[-0.3, 'sunrise_end', 'sunset_start'],
[-6, 'dawn', 'dusk'],
[-12, 'nautical_dawn', 'nautical_dusk'],
[-18, 'night_end', 'night'],
[6, 'golden_hour_end', 'golden_hour']
]
# adds a custom time to the times config
def add_time(angle, rise_name, set_name):
times.append([angle, rise_name, set_name])
# calculations for sun times
J0 = 0.0009
def julian_cycle(d, lw):
return floor(d - J0 - lw / (2 * pi))
def approx_transit(Ht, lw, n):
return J0 + (Ht + lw) / (2 * pi) + n
def solar_transit_j(ds, M, L):
return J2000 + ds + 0.0053 * sin(M) - 0.0069 * sin(2 * L)
def hour_angle(h, phi, d):
return acos((sin(h) - sin(phi) * sin(d)) / (cos(phi) * cos(d)))
# returns sunset time for the given sun altitude
def get_set_j(h, lw, phi, dec, n, M, L):
w = hour_angle(h, phi, dec),
a = approx_transit(w, lw, n)
return solar_transit_j(a, M, L)
# calculates sun times for a given date and
# latitude / longitude
def get_times(date, lat, lng):
lw = rad * -lng,
phi = rad * lat,
d = to_days(date),
n = julian_cycle(d, lw),
ds = approx_transit(0, lw, n),
M = solar_mean_anomaly(ds),
L = ecliptic_longitude(M),
dec = declination(L, 0),
Jnoon = solar_transit_j(ds, M, L),
# i, len, time, Jset, Jrise
result = {
"solar_noon": from_julian(Jnoon),
nadir: from_julian(Jnoon - 0.5)
}
for (i=0, len=times.length i < len i += 1):
time = times[i]
Jset = get_set_j(time[0] * rad, lw, phi, dec, n, M, L)
Jrise = Jnoon - (Jset - Jnoon)
result[time[1]] = from_julian(Jrise)
result[time[2]] = from_julian(Jset)
return result
# moon calculations, based on http: # aa.quae.nl / en / reken /
# hemelpositie.html formulas
def moon_coords(d): # geocentric ecliptic coordinates of the moon
L = rad * (218.316 + 13.176396 * d), # ecliptic longitude
M = rad * (134.963 + 13.064993 * d), # mean anomaly
F = rad * (93.272 + 13.229350 * d), # mean distance
l = L + rad * 6.289 * sin(M), # longitude
b = rad * 5.128 * sin(F), # latitude
dt = 385001 - 20905 * cos(M) # distance to the moon in km
return {
ra: right_ascension(l, b),
dec: declination(l, b),
dist: dt
}
def get_moon_position(date, lat, lng):
lw = rad * -lng
phi = rad * lat
d = to_days(date)
c = moon_coords(d)
H = sidereal_time(d, lw) - c.ra,
h = altitude(H, phi, c.dec),
# formula 14.1 of "Astronomical Algorithms" 2nd edition by Jean
# Meeus(Willmann - Bell, Richmond) 1998.
pa = atan(sin(H), tan(phi) * cos(c.dec) - sin(c.dec) * cos(H))
h = h + astro_refraction(h) # altitude correction for refraction
return {
"azimuth": azimuth(H, phi, c.dec),
"altitude": h,
"distance": c.dist,
"parallactic_angle": pa
}
# calculations for illumination parameters of the moon,
# based on http: # idlastro.gsfc.nasa.gov / ftp / pro / astro / mphase.pro formulas and
# Chapter 48 of "Astronomical Algorithms" 2nd edition by Jean
# Meeus(Willmann - Bell, Richmond) 1998.
def get_moon_illumination(date):
d = to_days(date | | new Date()),
s = sun_coords(d),
m = moon_coords(d),
sdist = 149598000, # distance from Earth to Sun in km
phi = acos(sin(s.dec) * sin(m.dec) + cos(s.dec)
* cos(m.dec) * cos(s.ra - m.ra)),
inc = atan(sdist * sin(phi), m.dist - sdist * cos(phi)),
angle = atan(cos(s.dec) * sin(s.ra - m.ra), sin(s.dec) * cos(m.dec) -
cos(s.dec) * sin(m.dec) * cos(s.ra - m.ra))
return {
"fraction": (1 + cos(inc)) / 2,
"phase": 0.5 + 0.5 * inc * (angle < 0 ? - 1: 1) / pi,
"angle": angle
}
def hours_later(date, h):
return new Date(date.value_of() + h * day_ms / 24)
# calculations for moon rise / sunset times are based on http: #
# www.stargazing.net / kepler / moonrise.html article
def get_moon_times(date, lat, lng, in_uTC):
t = new Date(date)
if (in_uTC) t.set_uTCHours(0, 0, 0, 0)
else t.set_hours(0, 0, 0, 0)
hc = 0.133 * rad,
h0 = get_moon_position(t, lat, lng)["altitude"] - hc,
h1, h2, rise, sunset, a, b, xe, ye, d, roots, x1, x2, dx
# go in 2 - hour chunks, each time seeing if a 3 - point quadratic curve
# crosses zero(which means rise or sunset)
for i in range(1, 25, 2):
h1 = get_moon_position(hours_later(t, i), lat, lng)["altitude"] - hc
h2 = get_moon_position(hours_later(t, i + 1),
lat, lng)["altitude"] - hc
a = (h0 + h2) / 2 - h1
b = (h2 - h0) / 2
xe = -b / (2 * a)
ye = (a * xe + b) * xe + h1
d = b * b - 4 * a * h1
roots = 0
if (d >= 0):
dx = sqrt(d) / (abs(a) * 2)
x1 = xe - dx
x2 = xe + dx
if (abs(x1) <= 1) roots + +
if (abs(x2) <= 1) roots + +
if (x1 < -1) x1 = x2
if roots == 1:
if (h0 < 0):
rise = i + x1
else:
sunset = i + x1
elif (roots == 2):
rise = i + (ye < 0 ? x2: x1)
sunset = i + (ye < 0 ? x1: x2)
if rise and sunset:
break
h0 = h2
result = {}
if rise:
result.rise = hours_later(t, rise)
if sunset:
result.sunset = hours_later(t, sunset)
if !rise and !sunset:
result[ye > 0 ? 'always_up': 'always_down'] = true
return result
|
PHP
|
UTF-8
| 2,271
| 2.53125
| 3
|
[] |
no_license
|
<?php
ob_start();
include '../getConnection.php';
$subject_ID = $_GET['ID'];
include '../checkCoord2.php';
if($coordCorrect != true)
{
exit(header('location: ../notCoord.php'));
ob_get_flush();
}
if(isset($_POST['Submit']))
{
try
{
$topicName = $_POST["strtopicName"];
if(!empty($topicName))
{
if(!preg_match("/[A-Za-z]/", $topicName))
{
echo "<link rel='stylesheet' href='../../assets/css/version1.css'>";
echo "<link rel='stylesheet' href='../../assets/css/bootstro.css'>";
echo "<link rel='stylesheet' href='../../assets/css/bootstrap-responsive.css'>";
echo "<div class='alert alert-error' align='center'>Topic name must be alphabetic</div>";
}
else
{
//This variable is used to obtain the SubjectID from the subject code
$subjectCode = $_POST["subject_code"];
date_default_timezone_set('Australia/Melbourne');
$date = date('Y-m-d', time());
$subIDsql = "SELECT SubjectCode FROM subject WHERE SubjectID = :subject_id";
$sql = $db->prepare($subIDsql);
$sql->bindParam("subject_id", $subjectCode);
$sql->execute();
$row = $sql->fetchColumn();
//This sql query is used to insert the respective variable into the topic table
$resultSQL = $db->prepare("INSERT INTO topic VALUES(null, :bind_TopicName, :bind_SubID, :bind_SubCode , 0, :bind_date)");
$resultSQL->bindParam("bind_TopicName", $topicName);
$resultSQL->bindParam("bind_SubID", $subjectCode);
$resultSQL->bindParam("bind_SubCode", $row);
$resultSQL->bindParam("bind_date", $date);
$resultSQL->execute();
exit(header("location: viewTopic.php?ID=".$subjectCode));
ob_get_flush();
}
}
else
{
echo "<link rel='stylesheet' href='../../assets/css/version1.css'>";
echo "<link rel='stylesheet' href='../../assets/css/bootstro.css'>";
echo "<link rel='stylesheet' href='../../assets/css/bootstrap-responsive.css'>";
echo "<div class='alert alert-error' align='center'>Topic name must not be empty & Subject code must be selected</div>";
echo "<meta http-equiv='refresh' content='1;url=newTopic.php' />";
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
?>
|
C++
|
UTF-8
| 2,925
| 3.40625
| 3
|
[] |
no_license
|
//GameCharacter.cpp
//Description: definition for GameCharacter class
//Author: Liam McCormick
//Date: 20/11/2018
#include <iostream>
#include <string>
#include "GameCharacter.h"
//contructors and destructors
GameCharacter::GameCharacter() {
std::string characterName_ = "New character";
float health_ = 0;
float weightLimit_ = 0;
weapon_ = Weapon{ "New weapon", 0, 0, 0, 0 };
armour_ = Armour{ "New armour", 0, 0, 0, 0, Cardboard };
int food_ = 0;
CharacterState { Idle };
std::cout << "New character: " << characterName_ << " has been born!" << std::endl;
}
GameCharacter::GameCharacter(std::string characterName, float health, float weightLimit, Weapon weapon, Armour armour, int food, CharacterState state)
: characterName_{ characterName }, health_{ health }, weightLimit_{ weightLimit }, weapon_{ weapon }, armour_{ armour }, food_{ food }, state_{ state } {
std::cout << "Base GameCharacter called...... " << characterName_ << " has been born!" << std::endl;
}
bool GameCharacter::Attack(GameCharacter &character) {
std::cout << characterName_ << " is attacking " << character.GetCharacterName() << " with a " << weapon_.GetItemName() << std::endl;
state_ = Attacking;
character.Defend();
return false;
}
void GameCharacter::Defend() {
std::cout << characterName_ << " is defending themselves with a " << armour_.GetItemName() <<
" made from " << armour_.GetArmourType() << std::endl;
state_ = Defending;
}
void GameCharacter::Walk() {
state_ = Walking;
std::cout << characterName_ << " is " << state_;
}
void GameCharacter::Run() {
state_ = Running;
std::cout << characterName_ << " is " << state_;
}
void GameCharacter::Sleep() {
state_ = Sleeping;
std::cout << characterName_ << " is " << state_;
}
void GameCharacter::AddFood(int amount) {
amount = food_ + food_;
}
void GameCharacter::Eat() { //character eats food, adds health, -1 from food available
for (int i = 0; i < 4; i++) {
if (food_ > 0) {
AddFood(-1);
health_ = health_ + 0.25f;
}
else if (i == 3 && food_ > 0) {
std::cout << "You can't eat anymore!" << std::endl;
}
}
}
//getters and setters
void GameCharacter::SetCharacterName(std::string characterName) {
characterName_ = characterName;
}
std::string GameCharacter::GetCharacterName() {
return characterName_;
}
void GameCharacter::SetCharacterHealth(float health) {
health_ = health;
}
float GameCharacter::GetCharacterHealth() {
return health_;
}
void GameCharacter::SetCharacterWeightLimit(float weightLimit) {
weightLimit_ = weightLimit;
}
float GameCharacter::GetCharacterWeightLimit() {
return weightLimit_;
}
void GameCharacter::SetFood(int food) {
food_ = food;
}
int GameCharacter::GetFood() {
return food_;
}
void GameCharacter::SetWeapon(Weapon weapon) {
weapon_ = weapon;
}
void GameCharacter::SetArmour(Armour armour) {
armour_ = armour;
}
void GameCharacter::SetState(CharacterState state) {
state_ = state;
}
|
C
|
UTF-8
| 33,534
| 2.65625
| 3
|
[] |
no_license
|
/***********************************************************
* A single header file lightmap seam optimization library *
* https://github.com/ands/seamoptimizer *
* no warranty implied | use at your own risk *
* author: Andreas Mantler (ands) | last change: 05.03.2017 *
* *
* License: *
* This software is in the public domain. *
* Where that dedication is not recognized, *
* you are granted a perpetual, irrevocable license to copy *
* and modify this file however you want. *
***********************************************************/
#ifndef SEAMOPTIMIZER_H
#define SEAMOPTIMIZER_H
#ifndef SO_CALLOC
#include <malloc.h> // calloc, free, alloca
#define SO_CALLOC(count, size) calloc(count, size)
#define SO_FREE(ptr) free(ptr)
#endif
typedef int so_bool;
#define SO_FALSE 0
#define SO_TRUE 1
typedef struct so_seam_t so_seam_t;
// API
// so_seams_find:
// Find all seams according to the specified triangulated geometry and its texture coordinates.
// This searches for edges that are shared by triangles, but are disjoint in UV space.
// positions: triangle array 3d positions ((x0, y0, z0), (x1, y1, z1), (x2, y2, z2)), ((x0, y0, z0), (x1, y1, z1), (x2, y2, z2)), ...
// texcoords: triangle array 2d uv coords ( (u0, v0), (u1, v1), (u2, v2)), ( (u0, v0), (u1, v1), (u2, v2)), ...
// vertices: total number of vertices ( = triangles * 3)
// cosNormalThreshold controls at which angles between neighbour triangles a seam should be considered.
// if dot(triangle A normal, triangle B normal) > cosNormalThreshold then the seam is included into the returned set.
// data, w, h, c specifies the lightmap data (data should be a w * h * c array of floats).
// w = lightmap width, h = lightmap height, c = number of lightmap channels (1..4).
// returns a linked list of the found seams.
// Warning: The data may be modified to fill empty (zeroed) edge texels with one of their closest neighbours if they are empty!
so_seam_t *so_seams_find(
float *positions, float *texcoords, int vertices,
float cosNormalThreshold,
float *data, int w, int h, int c);
// so_seam_optimize:
// Optimize a single seam. Seams can be optimized in parallel on different threads.
// lambda: Weight that controls the deviation from the original color values (must be > 0).
// Higher values => Less deviation from the original edge colors => more obvious seams.
// Too low values => Optimizer may just choose black as the perfect color for all seam pixels.
// returns whether the optimization was successful.
so_bool so_seam_optimize(
so_seam_t *seam,
float *data, int w, int h, int c,
float lambda);
// so_seam_next: Retrieves the next seam in the linked list.
so_seam_t *so_seam_next(
so_seam_t *seam);
// so_seams_free: Free the resources for all seams in the list.
void so_seams_free(
so_seam_t *seams);
#endif
////////////////////// END OF HEADER //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#ifdef SEAMOPTIMIZER_IMPLEMENTATION
#undef SEAMOPTIMIZER_IMPLEMENTATION
#include <stdlib.h> // qsort
#include <stdio.h> // printf (TODO)
#include <string.h> // memcpy
#include <stdint.h>
#include <math.h>
#include <float.h>
#include <assert.h>
#define SO_EPSILON 0.00001f
#ifdef _DEBUG
#define SO_NOT_ZERO(v) (v > SO_EPSILON || v < -SO_EPSILON) // a lot faster in debug
#else
#define SO_NOT_ZERO(v) (fabsf(v) > SO_EPSILON) // faster in release
#endif
#ifdef SO_APPROX_RSQRT
#include "xmmintrin.h"
static inline float so_rsqrtf(float v)
{
return _mm_cvtss_f32(_mm_rsqrt_ss(_mm_set_ss(v)));
}
#else
static inline float so_rsqrtf(float v)
{
return 1.0f / sqrtf(v);
}
#endif
static inline int16_t so_min16i (int16_t a, int16_t b) { return a < b ? a : b; }
static inline int16_t so_max16i (int16_t a, int16_t b) { return a > b ? a : b; }
static inline float so_minf (float a, float b) { return a < b ? a : b; }
static inline float so_maxf (float a, float b) { return a > b ? a : b; }
static inline float so_absf (float a ) { return a < 0.0f ? -a : a; }
typedef struct so_vec2 { float x, y; } so_vec2;
static inline so_vec2 so_v2i (int x, int y) { so_vec2 v = { (float)x, (float)y }; return v; }
static inline so_vec2 so_v2 (float x, float y) { so_vec2 v = { x, y }; return v; }
static inline so_vec2 so_add2 (so_vec2 a, so_vec2 b) { return so_v2(a.x + b.x, a.y + b.y); }
static inline so_vec2 so_sub2 (so_vec2 a, so_vec2 b) { return so_v2(a.x - b.x, a.y - b.y); }
static inline so_vec2 so_mul2 (so_vec2 a, so_vec2 b) { return so_v2(a.x * b.x, a.y * b.y); }
static inline so_vec2 so_scale2 (so_vec2 a, float b) { return so_v2(a.x * b, a.y * b); }
static inline float so_length2sq (so_vec2 a ) { return a.x * a.x + a.y * a.y; }
static inline float so_length2 (so_vec2 a ) { return sqrtf(so_length2sq(a)); }
typedef struct so_vec3 { float x, y, z; } so_vec3;
static inline so_vec3 so_v3 (float x, float y, float z) { so_vec3 v = { x, y, z }; return v; }
static inline so_vec3 so_sub3 (so_vec3 a, so_vec3 b) { return so_v3(a.x - b.x, a.y - b.y, a.z - b.z); }
static inline so_vec3 so_mul3 (so_vec3 a, so_vec3 b) { return so_v3(a.x * b.x, a.y * b.y, a.z * b.z); }
static inline so_vec3 so_scale3 (so_vec3 a, float b) { return so_v3(a.x * b, a.y * b, a.z * b); }
static inline so_vec3 so_div3 (so_vec3 a, float b) { return so_scale3(a, 1.0f / b); }
static inline so_vec3 so_min3 (so_vec3 a, so_vec3 b) { return so_v3(so_minf(a.x, b.x), so_minf(a.y, b.y), so_minf(a.z, b.z)); }
static inline so_vec3 so_max3 (so_vec3 a, so_vec3 b) { return so_v3(so_maxf(a.x, b.x), so_maxf(a.y, b.y), so_maxf(a.z, b.z)); }
static inline float so_dot3 (so_vec3 a, so_vec3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; }
static inline so_vec3 so_cross3 (so_vec3 a, so_vec3 b) { return so_v3(a.y * b.z - b.y * a.z, a.z * b.x - b.z * a.x, a.x * b.y - b.x * a.y); }
static inline float so_length3sq (so_vec3 a ) { return a.x * a.x + a.y * a.y + a.z * a.z; }
static inline float so_length3 (so_vec3 a ) { return sqrtf(so_length3sq(a)); }
static inline so_vec3 so_normalize3(so_vec3 a ) { return so_div3(a, so_length3(a)); }
//#define SO_CHECK_FOR_MEMORY_LEAKS // check for memory leaks. don't use this in multithreaded code!
#ifdef SO_CHECK_FOR_MEMORY_LEAKS
static uint64_t so_allocated = 0;
static uint64_t so_allocated_max = 0;
static void *so_alloc_void(size_t size)
{
void *memory = SO_CALLOC(1, size + sizeof(size_t));
(*(size_t*)memory) = size;
so_allocated += size;
if (so_allocated > so_allocated_max)
so_allocated_max = so_allocated;
return (size_t*)memory + 1;
}
static void so_free(void *memory)
{
size_t size = ((size_t*)memory)[-1];
so_allocated -= size;
SO_FREE(((size_t*)memory) - 1);
}
#else
static void *so_alloc_void(size_t size)
{
return SO_CALLOC(1, size);
}
static void so_free(void *memory)
{
SO_FREE(memory);
}
#endif
#define so_alloc(type, count) ((type*)so_alloc_void(sizeof(type) * (count)))
static inline so_bool so_accumulate_texel(float *sums, int x, int y, float *data, int w, int h, int c)
{
so_bool exists = SO_FALSE;
for (int i = 0; i < c; i++)
{
float v = data[(y * w + x) * c + i];
sums[i] += v;
exists |= v > 0.0f;
}
return exists;
}
static void so_fill_with_closest(int x, int y, float *data, int w, int h, int c, int depth = 2)
{
assert(c <= 4);
for (int i = 0; i < c; i++)
if (data[(y * w + x) * c + i] > 0.0f)
return;
float sums[4] = {};
int n = 0;
if (x > 0 && so_accumulate_texel(sums, x - 1, y, data, w, h, c)) n++;
if (x + 1 < w && so_accumulate_texel(sums, x + 1, y, data, w, h, c)) n++;
if (y > 0 && so_accumulate_texel(sums, x, y - 1, data, w, h, c)) n++;
if (y + 1 < h && so_accumulate_texel(sums, x, y + 1, data, w, h, c)) n++;
if (!n && depth)
{
--depth;
if (x > 0)
{
so_fill_with_closest(x - 1, y, data, w, h, c, depth);
if (so_accumulate_texel(sums, x - 1, y, data, w, h, c)) n++;
}
if (x + 1 < w)
{
so_fill_with_closest(x + 1, y, data, w, h, c, depth);
if (so_accumulate_texel(sums, x + 1, y, data, w, h, c)) n++;
}
if (y > 0)
{
so_fill_with_closest(x, y - 1, data, w, h, c, depth);
if (so_accumulate_texel(sums, x, y - 1, data, w, h, c)) n++;
}
if (y + 1 < h)
{
so_fill_with_closest(x, y + 1, data, w, h, c, depth);
if (so_accumulate_texel(sums, x, y + 1, data, w, h, c)) n++;
}
}
if (n)
{
float ni = 1.0f / (float)n;
for (int i = 0; i < c; i++)
data[(y * w + x) * c + i] = sums[i] * ni;
}
}
typedef struct
{
int16_t x, y;
} so_texel_t;
static inline int so_texel_cmp(const void *l, const void *r)
{
const so_texel_t *lt = (const so_texel_t*)l;
const so_texel_t *rt = (const so_texel_t*)r;
if (lt->y < rt->y) return -1;
if (lt->y > rt->y) return 1;
if (lt->x < rt->x) return -1;
if (lt->x > rt->x) return 1;
return 0;
}
typedef struct
{
so_texel_t texels[4];
float weights[4];
} so_bilinear_sample_t;
typedef struct
{
so_bilinear_sample_t sides[2];
} so_stitching_point_t;
typedef struct
{
so_texel_t *texels;
uint32_t count;
uint32_t capacity;
} so_texel_set_t;
static inline uint32_t so_texel_hash(so_texel_t texel, uint32_t capacity)
{
return (texel.y * 104173 + texel.x * 86813) % capacity;
}
static void so_texel_set_add(so_texel_set_t *set, so_texel_t *texels, int entries, int arrayLength = 0)
{
if (set->count + entries > set->capacity * 3 / 4) // leave some free space to avoid having many collisions
{
int newCapacity = set->capacity > 64 ? set->capacity * 2 : 64;
while (set->count + entries > newCapacity * 3 / 4)
newCapacity *= 2;
so_texel_t *newTexels = so_alloc(so_texel_t, newCapacity);
for (int i = 0; i < newCapacity; i++)
newTexels[i].x = -1;
if (set->texels)
{
for (int i = 0; i < set->capacity; i++) // rehash all old texels
{
if (set->texels[i].x != -1)
{
uint32_t hash = so_texel_hash(set->texels[i], newCapacity);
while (newTexels[hash].x != -1) // collisions
hash = (hash + 1) % newCapacity;
newTexels[hash] = set->texels[i];
}
}
so_free(set->texels);
}
set->texels = newTexels;
set->capacity = newCapacity;
}
if (arrayLength == 0)
arrayLength = entries;
for (int i = 0; i < arrayLength; i++)
{
if (texels[i].x != -1)
{
uint32_t hash = so_texel_hash(texels[i], set->capacity);
while (set->texels[hash].x != -1) // collisions
{
if (set->texels[hash].x == texels[i].x && set->texels[hash].y == texels[i].y)
break; // texel is already in the set
hash = (hash + 1) % set->capacity;
}
if (set->texels[hash].x == -1)
{
set->texels[hash] = texels[i];
set->count++;
}
}
}
}
static so_bool so_texel_set_contains(so_texel_set_t *set, so_texel_t texel)
{
uint32_t hash = so_texel_hash(texel, set->capacity);
while (set->texels[hash].x != -1) // entries with same hash
{
if (set->texels[hash].x == texel.x && set->texels[hash].y == texel.y)
return SO_TRUE; // texel is already in the set
hash = (hash + 1) % set->capacity;
}
return SO_FALSE;
}
static void so_texel_set_free(so_texel_set_t *set)
{
so_free(set->texels);
*set = {0};
}
typedef struct
{
so_stitching_point_t *points;
uint32_t count;
uint32_t capacity;
} so_stitching_points_t;
static void so_stitching_points_alloc(so_stitching_points_t *points, uint32_t n)
{
points->points = so_alloc(so_stitching_point_t, n);
points->capacity = n;
points->count = 0;
}
static void so_stitching_points_free(so_stitching_points_t *points)
{
so_free(points->points);
*points = {0};
}
static void so_stitching_points_add(so_stitching_points_t *points, so_stitching_point_t *point)
{
assert(points->count < points->capacity);
points->points[points->count++] = *point;
}
static void so_stitching_points_append(so_stitching_points_t *points, so_stitching_points_t *other)
{
so_stitching_point_t *newPoints = so_alloc(so_stitching_point_t, points->capacity + other->capacity);
memcpy(newPoints, points->points, sizeof(so_stitching_point_t) * points->count);
memcpy(newPoints + points->count, other->points, sizeof(so_stitching_point_t) * other->count);
so_free(points->points);
points->points = newPoints;
points->capacity = points->capacity + other->capacity;
points->count = points->count + other->count;
}
struct so_seam_t
{
int16_t x_min, y_min, x_max, y_max;
so_texel_set_t texels;
so_stitching_points_t stitchingPoints;
so_seam_t *next;
};
so_seam_t *so_seam_next(so_seam_t *seam)
{
return seam->next;
}
static void so_seam_alloc(so_seam_t *seam, uint32_t stitchingPointCount)
{
so_stitching_points_alloc(&seam->stitchingPoints, stitchingPointCount);
}
static void so_seam_free(so_seam_t *seam)
{
so_texel_set_free(&seam->texels);
so_stitching_points_free(&seam->stitchingPoints);
}
static void so_seam_add(so_seam_t *seam, so_stitching_point_t *point)
{
for (int side = 0; side < 2; side++)
{
for (int texel = 0; texel < 4; texel++)
{
so_texel_t t = point->sides[side].texels[texel];
seam->x_min = t.x < seam->x_min ? t.x : seam->x_min;
seam->y_min = t.y < seam->y_min ? t.y : seam->y_min;
seam->x_max = t.x > seam->x_max ? t.x : seam->x_max;
seam->y_max = t.y > seam->y_max ? t.y : seam->y_max;
}
so_texel_set_add(&seam->texels, point->sides[side].texels, 4);
}
so_stitching_points_add(&seam->stitchingPoints, point);
}
static so_bool so_seams_intersect(so_seam_t *a, so_seam_t *b)
{
// compare bounding boxes first
if (a->x_min > b->x_max || b->x_min >= a->x_max ||
a->y_min > b->y_max || b->y_min >= a->y_max)
return SO_FALSE;
// bounds intersect -> check each individual texel for intersection
if (a->texels.capacity > b->texels.capacity) // swap so that we always loop over the smaller set
{
so_seam_t *tmp = a;
a = b;
b = tmp;
}
for (int i = 0; i < a->texels.capacity; i++)
if (a->texels.texels[i].x != -1)
if (so_texel_set_contains(&b->texels, a->texels.texels[i]))
return SO_TRUE;
return SO_FALSE;
}
static void so_seams_in_place_merge(so_seam_t *dst, so_seam_t *src)
{
// expand bounding box
dst->x_min = src->x_min < dst->x_min ? src->x_min : dst->x_min;
dst->y_min = src->y_min < dst->y_min ? src->y_min : dst->y_min;
dst->x_max = src->x_max > dst->x_max ? src->x_max : dst->x_max;
dst->y_max = src->y_max > dst->y_max ? src->y_max : dst->y_max;
// insert src elements
so_texel_set_add(&dst->texels, src->texels.texels, src->texels.count, src->texels.capacity);
so_stitching_points_append(&dst->stitchingPoints, &src->stitchingPoints);
}
static void so_seams_add_seam(so_seam_t **seams, so_vec2 a0, so_vec2 a1, so_vec2 b0, so_vec2 b1, float *data, int w, int h, int c)
{
so_vec2 s = so_v2i(w, h);
a0 = so_mul2(a0, s);
a1 = so_mul2(a1, s);
b0 = so_mul2(b0, s);
b1 = so_mul2(b1, s);
so_vec2 ad = so_sub2(a1, a0);
so_vec2 bd = so_sub2(b1, b0);
float l = so_length2(ad);
int iterations = (int)(l * 5.0f); // TODO: is this the best value?
float step = 1.0f / iterations;
so_seam_t currentSeam = {0};
currentSeam.x_min = w; currentSeam.y_min = h;
currentSeam.x_max = 0; currentSeam.y_max = 0;
so_seam_alloc(¤tSeam, iterations + 1);
for (int i = 0; i <= iterations; i++)
{
float t = i * step;
so_vec2 a = so_add2(a0, so_scale2(ad, t));
so_vec2 b = so_add2(b0, so_scale2(bd, t));
int16_t ax = (int16_t)roundf(a.x), ay = (int16_t)roundf(a.y);
int16_t bx = (int16_t)roundf(b.x), by = (int16_t)roundf(b.y);
float au = a.x - ax, av = a.y - ay, nau = 1.0f - au, nav = 1.0f - av;
float bu = b.x - bx, bv = b.y - by, nbu = 1.0f - bu, nbv = 1.0f - bv;
so_texel_t ta0 = { ax , ay };
so_texel_t ta1 = { so_min16i(ax + 1, w - 1), ay };
so_texel_t ta2 = { ax , so_min16i(ay + 1, h - 1) };
so_texel_t ta3 = { so_min16i(ax + 1, w - 1), so_min16i(ay + 1, h - 1) };
so_texel_t tb0 = { bx , by };
so_texel_t tb1 = { so_min16i(bx + 1, w - 1), by };
so_texel_t tb2 = { bx , so_min16i(by + 1, h - 1) };
so_texel_t tb3 = { so_min16i(bx + 1, w - 1), so_min16i(by + 1, h - 1) };
so_fill_with_closest(ta0.x, ta0.y, data, w, h, c);
so_fill_with_closest(ta1.x, ta1.y, data, w, h, c);
so_fill_with_closest(ta2.x, ta2.y, data, w, h, c);
so_fill_with_closest(ta3.x, ta3.y, data, w, h, c);
so_fill_with_closest(tb0.x, tb0.y, data, w, h, c);
so_fill_with_closest(tb1.x, tb1.y, data, w, h, c);
so_fill_with_closest(tb2.x, tb2.y, data, w, h, c);
so_fill_with_closest(tb3.x, tb3.y, data, w, h, c);
so_stitching_point_t sp;
sp.sides[0].texels[0] = ta0;
sp.sides[0].texels[1] = ta1;
sp.sides[0].texels[2] = ta2;
sp.sides[0].texels[3] = ta3;
sp.sides[0].weights[0] = nau * nav;
sp.sides[0].weights[1] = au * nav;
sp.sides[0].weights[2] = nau * av;
sp.sides[0].weights[3] = au * av;
sp.sides[1].texels[0] = tb0;
sp.sides[1].texels[1] = tb1;
sp.sides[1].texels[2] = tb2;
sp.sides[1].texels[3] = tb3;
sp.sides[1].weights[0] = nbu * nbv;
sp.sides[1].weights[1] = bu * nbv;
sp.sides[1].weights[2] = nbu * bv;
sp.sides[1].weights[3] = bu * bv;
so_seam_add(¤tSeam, &sp);
}
so_seam_t *dstSeam = 0;
for (so_seam_t **seam = seams; *seam; seam = &(*seam)->next)
{
retry:
if (so_seams_intersect(¤tSeam, *seam))
{
if (!dstSeam) // found a seam that the edge is connected to -> add current edge to that seam
{
so_seams_in_place_merge(*seam, ¤tSeam);
dstSeam = *seam;
}
else // found another seam that the edge is connected to -> merge those seams
{
so_seams_in_place_merge(dstSeam, *seam);
// remove current seam from seams
so_seam_t *toDelete = *seam;
*seam = (*seam)->next;
so_seam_free(toDelete);
so_free(toDelete);
if (*seam)
goto retry; // don't move to next since we already did that by deleting the current seam
else
break;
}
}
}
if (!dstSeam) // did not find a seam that the edge is connected to -> make a new one
{
currentSeam.next = *seams;
*seams = so_alloc(so_seam_t, 1);
**seams = currentSeam;
}
else
so_seam_free(¤tSeam);
}
void so_seams_free(so_seam_t *seams)
{
so_seam_t *seam = seams;
while (seam)
{
so_seam_t *next = seam->next;
so_seam_free(seam);
so_free(seam);
seam = next;
}
#ifdef SO_CHECK_FOR_MEMORY_LEAKS
assert(so_allocated == 0);
printf("Allocated max %d MB. Not freed: %d bytes.\n", so_allocated_max / (1024 * 1024), so_allocated);
printf("These results are only correct if the lib was used single-threaded.\n");
so_allocated_max = 0;
#endif
}
static int so_should_optimize(so_vec3 *tria, so_vec3 *trib, float cosThreshold)
{
so_vec3 n0 = so_normalize3(so_cross3(so_sub3(tria[1], tria[0]), so_sub3(tria[2], tria[0])));
so_vec3 n1 = so_normalize3(so_cross3(so_sub3(trib[1], trib[0]), so_sub3(trib[2], trib[0])));
return so_absf(so_dot3(n0, n1)) > cosThreshold;
}
so_seam_t *so_seams_find(float *positions, float *texcoords, int vertices, float cosNormalThreshold, float *data, int w, int h, int c)
{
so_vec3 *pos = (so_vec3*)positions;
so_vec2 *uv = (so_vec2*)texcoords;
so_vec3 bbmin = so_v3(FLT_MAX, FLT_MAX, FLT_MAX);
so_vec3 bbmax = so_v3(-FLT_MAX, -FLT_MAX, -FLT_MAX);
int *hashmap = so_alloc(int, vertices * 2);
for (int i = 0; i < vertices; i++)
{
bbmin = so_min3(bbmin, pos[i]);
bbmax = so_max3(bbmax, pos[i]);
hashmap[i * 2 + 0] = -1;
hashmap[i * 2 + 1] = -1;
}
so_vec3 bbscale = so_v3(15.9f / bbmax.x, 15.9f / bbmax.y, 15.9f / bbmax.z);
so_seam_t *seams = 0;
for (int i0 = 0; i0 < vertices; i0++)
{
int tri = i0 - (i0 % 3);
int i1 = tri + ((i0 + 1) % 3);
int i2 = tri + ((i0 + 2) % 3);
so_vec3 p = so_mul3(so_sub3(pos[i0], bbmin), bbscale);
int hash = (unsigned int)(281 * (int)p.x + 569 * (int)p.y + 1447 * (int)p.z) % (vertices * 2);
while (hashmap[hash] >= 0)
{
int oi0 = hashmap[hash];
#define SO_EQUAL(a, b) so_length3sq(so_sub3(pos[a], pos[b])) < 0.0000001f
if (SO_EQUAL(oi0, i0))
{
int otri = oi0 - (oi0 % 3);
int oi1 = otri + ((oi0 + 1) % 3);
int oi2 = otri + ((oi0 + 2) % 3);
if (SO_EQUAL(oi1, i1) && so_should_optimize(pos + tri, pos + otri, cosNormalThreshold))
so_seams_add_seam(&seams, uv[i0], uv[i1], uv[oi0], uv[oi1], data, w, h, c);
//else if (SO_EQUAL(oi1, i2) && so_should_optimize(pos + tri, pos + otri, cosNormalThreshold)) // this will already be detected by the other side of the seam!
// so_seams_add_seam(&seams, uv[i0], uv[i2], uv[oi0], uv[oi1], data, w, h, c);
else if (SO_EQUAL(oi2, i1) && so_should_optimize(pos + tri, pos + otri, cosNormalThreshold))
so_seams_add_seam(&seams, uv[i0], uv[i1], uv[oi0], uv[oi2], data, w, h, c);
//break;
}
if (++hash == vertices * 2)
hash = 0;
}
hashmap[hash] = i0;
}
so_free(hashmap);
return seams;
}
static int so_texel_binary_search(so_texel_t *texels, int n, so_texel_t toFind)
{
int n_half = n / 2;
so_texel_t *center = texels + n_half;
if (toFind.y == center->y && toFind.x == center->x)
return n_half;
if (n <= 1)
return -1;
if (toFind.y < center->y || (toFind.y == center->y && toFind.x < center->x))
return so_texel_binary_search(texels, n_half, toFind);
else
{
int result = so_texel_binary_search(center + 1, n - n_half - 1, toFind);
return result == -1 ? -1 : n_half + 1 + result;
}
}
typedef struct
{
int index;
float value;
} so_sparse_entry_t;
static int so_sparse_entry_cmp(const void *a, const void *b)
{
so_sparse_entry_t *ae = (so_sparse_entry_t*)a;
so_sparse_entry_t *be = (so_sparse_entry_t*)b;
return ae->index - be->index;
}
typedef struct
{
so_sparse_entry_t *entries;
int count;
int capacity;
} so_sparse_entries_t;
static void so_sparse_matrix_alloc(so_sparse_entries_t *matrix, int capacity)
{
matrix->entries = so_alloc(so_sparse_entry_t, capacity);
matrix->capacity = capacity;
matrix->count = 0;
}
static void so_sparse_matrix_free(so_sparse_entries_t *matrix)
{
so_free(matrix->entries);
*matrix = { 0 };
}
static void so_sparse_matrix_add(so_sparse_entries_t *matrix, int index, float value)
{
if (matrix->count == matrix->capacity)
{
int newCapacity = matrix->capacity * 2;
if (newCapacity < 64)
newCapacity = 64;
so_sparse_entry_t *newEntries = so_alloc(so_sparse_entry_t, newCapacity);
for (int i = 0; i < matrix->count; i++)
newEntries[i] = matrix->entries[i];
so_free(matrix->entries);
matrix->entries = newEntries;
matrix->capacity = newCapacity;
}
int entryIndex = matrix->count++;
matrix->entries[entryIndex].index = index;
matrix->entries[entryIndex].value = value;
}
static void so_sparse_matrix_add(so_sparse_entries_t *matrix, so_sparse_entry_t *entry)
{
so_sparse_matrix_add(matrix, entry->index, entry->value);
}
static void so_sparse_matrix_sort(so_sparse_entries_t *matrix)
{
qsort(matrix->entries, matrix->count, sizeof(so_sparse_entry_t), so_sparse_entry_cmp);
}
static so_bool so_sparse_matrix_advance_to_index(so_sparse_entries_t *matrix, int *position, int index, float *outValue)
{
int localPosition = *position;
while (localPosition < matrix->count && matrix->entries[localPosition].index < index)
++localPosition;
*position = localPosition;
if (localPosition < matrix->count && matrix->entries[localPosition].index == index)
{
*outValue = matrix->entries[localPosition].value;
return SO_TRUE;
}
return SO_FALSE;
}
static inline uint32_t so_sparse_entry_hash(int entryIndex, uint32_t capacity)
{
return (entryIndex * 104173) % capacity;
}
static void so_sparse_entry_set_alloc(so_sparse_entries_t *set, int capacity)
{
set->entries = so_alloc(so_sparse_entry_t, capacity);
for (int i = 0; i < capacity; i++)
set->entries[i].index = -1;
set->capacity = capacity;
set->count = 0;
}
static so_sparse_entry_t *so_sparse_entry_set_get_or_add(so_sparse_entries_t *set, int index)
{
if (set->count + 1 > set->capacity * 3 / 4) // leave some free space to avoid having many collisions
{
int newCapacity = set->capacity >= 64 ? set->capacity * 2 : 64;
so_sparse_entry_t *newEntries = so_alloc(so_sparse_entry_t, newCapacity);
for (int i = 0; i < newCapacity; i++)
newEntries[i].index = -1;
for (int i = 0; i < set->capacity; i++) // rehash all old entries
{
if (set->entries[i].index != -1)
{
uint32_t hash = so_sparse_entry_hash(set->entries[i].index, newCapacity);
while (newEntries[hash].index != -1) // collisions
hash = (hash + 1) % newCapacity;
newEntries[hash] = set->entries[i];
}
}
so_free(set->entries);
set->entries = newEntries;
set->capacity = newCapacity;
}
uint32_t hash = so_sparse_entry_hash(index, set->capacity);
while (set->entries[hash].index != -1) // collisions
{
if (set->entries[hash].index == index)
return &set->entries[hash]; // entry is already in the set
hash = (hash + 1) % set->capacity;
}
if (set->entries[hash].index == -1) // make new entry
{
set->entries[hash].index = index;
set->entries[hash].value = 0.0f;
set->count++;
return &set->entries[hash];
}
return 0; // shouldn't happen
}
static so_sparse_entries_t so_matrix_At_times_A(const float *A, const int *sparseIndices, int maxRowIndices, int m, int n)
{
so_sparse_entries_t AtA;
so_sparse_entry_set_alloc(&AtA, (n / 16) * (n / 16));
// compute lower left triangle only since the result is symmetric
for (int k = 0; k < m; k++)
{
const float *srcPtr = A + k * maxRowIndices;
const int *indexPtr = sparseIndices + k * maxRowIndices;
for (int i = 0; i < maxRowIndices; i++)
{
int index_i = indexPtr[i];
if (index_i < 0) break;
float v = srcPtr[i];
//float *dstPtr = AtA + index_i * n;
for (int j = 0; j < maxRowIndices; j++)
{
int index_j = indexPtr[j];
if (index_j < 0) break;
//dstPtr[index_j] += v * srcPtr[j];
int index = index_i * n + index_j;
so_sparse_entry_t *entry = so_sparse_entry_set_get_or_add(&AtA, index);
entry->value += v * srcPtr[j];
}
}
}
// compaction step (make a compact array from the scattered hash set values)
for (int i = 0, j = 0; i < AtA.capacity; i++)
if (AtA.entries[i].index != -1)
AtA.entries[j++] = AtA.entries[i];
// sort by index -> this is a sparse matrix now
so_sparse_matrix_sort(&AtA);
return AtA;
}
static void so_matrix_At_times_b(const float *A, int m, int n, const float *b, float *Atb, const int *sparseIndices, int maxRowIndices)
{
memset(Atb, 0, sizeof(float) * n);
for (int j = 0; j < m; j++)
{
const int *rowIndices = sparseIndices + j * maxRowIndices;
for (int i = 0; i < maxRowIndices; i++)
{
int index = rowIndices[i];
if (index < 0) break;
Atb[index] += A[j * maxRowIndices + i] * b[j];
}
}
}
static so_sparse_entries_t so_matrix_cholesky_prepare(so_sparse_entries_t *AtA, int n)
{
// dense
//for (int i = 0; i < n; i++)
//{
// float *a = L + i * n;
// for (int j = 0; j <= i; j++)
// {
// float *b = L + j * n;
// float sum = A[i * n + j];// + (i == j ? 0.0001 : 0.0); // some regularization
// for (int k = 0; k < j; k++)
// sum -= a[k] * b[k];
// if (i > j)
// a[j] = sum / b[j];
// else // i == j
// {
// if (sum <= 0.0)
// return SO_FALSE;
// a[i] = sqrtf(sum);
// }
// }
//}
// sparse
int *indices_i;
float *row_i;
float *invDiag;
if (n > 4096)
{
indices_i = so_alloc(int, n);
row_i = so_alloc(float, n);
invDiag = so_alloc(float, n);
}
else
{
indices_i = (int*)alloca(sizeof(int) * n);
row_i = (float*)alloca(sizeof(float) * n);
invDiag = (float*)alloca(sizeof(float) * n);
}
so_sparse_entries_t L;
so_sparse_matrix_alloc(&L, (n / 16) * (n / 16));
int AtAindex = 0;
for (int i = 0; i < n; i++)
{
int index_i_count = 0;
int row_j_index = 0;
for (int j = 0; j <= i; j++)
{
//float sum = A[i * n + j]; // + (i == j ? 0.0001 : 0.0); // regularization
int index = i * n + j;
float sum = 0.0f;
so_sparse_matrix_advance_to_index(AtA, &AtAindex, index, &sum);
for (int k = 0; k < index_i_count; k++)
{
int index_i = indices_i[k];
float Lvalue;
if (so_sparse_matrix_advance_to_index(&L, &row_j_index, j * n + index_i, &Lvalue))
sum -= row_i[index_i] * Lvalue;
}
if (i == j)
{
if (sum <= 0.0f)
{
so_sparse_matrix_free(&L);
return L;
}
invDiag[i] = so_rsqrtf(sum);
}
if (SO_NOT_ZERO(sum))
{
row_i[j] = sum * invDiag[j];
indices_i[index_i_count++] = j;
so_sparse_matrix_add(&L, index, row_i[j]);
}
else
row_i[j] = 0.0f;
}
}
if (n > 4096)
{
so_free(indices_i);
so_free(row_i);
so_free(invDiag);
}
return L;
}
static void so_matrix_cholesky_solve(so_sparse_entries_t *Lrows, so_sparse_entries_t *Lcols, float *x, const float *b, int n)
{
float *y = (float*)alloca(sizeof(float) * n);
// L * y = b
int Lindex = 0;
for (int i = 0; i < n; i++)
{
float sum = b[i];
while (Lindex < Lrows->count && Lrows->entries[Lindex].index < i * (n + 1))
{
sum -= Lrows->entries[Lindex].value * y[Lrows->entries[Lindex].index - i * n];
++Lindex;
}
assert(Lrows->entries[Lindex].index == i * (n + 1));
y[i] = sum / Lrows->entries[Lindex].value;
++Lindex;
}
// L' * x = y
Lindex = Lcols->count - 1;
for (int i = n - 1; i >= 0; i--)
{
float sum = y[i];
while (Lindex >= 0 && Lcols->entries[Lindex].index > i * (n + 1))
{
sum -= Lcols->entries[Lindex].value * x[Lcols->entries[Lindex].index - i * n];
--Lindex;
}
assert(Lcols->entries[Lindex].index == i * (n + 1));
x[i] = sum / Lcols->entries[Lindex].value;
--Lindex;
}
}
so_bool so_seam_optimize(so_seam_t *seam, float *data, int w, int h, int c, float lambda)
{
so_texel_set_t *texels = &seam->texels;
so_stitching_points_t *stitchingPoints = &seam->stitchingPoints;
size_t m = stitchingPoints->count;
size_t n = texels->count;
void *memoryBlock = so_alloc_void(
sizeof(so_texel_t) * n +
sizeof(float) * (m + n) * 8 +
sizeof(int) * (m + n) * 8 +
sizeof(float) * (m + n) +
sizeof(float) * n +
sizeof(float) * n);
uint8_t *memoryStart = (uint8_t*)memoryBlock;
so_texel_t *texelsFlat = (so_texel_t*)memoryStart;
memoryStart += sizeof(so_texel_t) * n;
float *A = (float*)memoryStart;
memoryStart += sizeof(float) * (m + n) * 8;
int *AsparseIndices = (int*)memoryStart;
memoryStart += sizeof(int) * (m + n) * 8;
float *b = (float*)memoryStart;
memoryStart += sizeof(float) * (m + n);
float *Atb = (float*)memoryStart;
memoryStart += sizeof(float) * n;
float *x = (float*)memoryStart;
memoryStart += sizeof(float) * n;
for (int i = 0, j = 0; i < texels->capacity && j < n; i++)
if (texels->texels[i].x != -1)
texelsFlat[j++] = texels->texels[i];
qsort(texelsFlat, n, sizeof(so_texel_t), so_texel_cmp);
size_t r = 0;
for (int i = 0; i < m; i++)
{
ptrdiff_t column0[4];
ptrdiff_t column1[4];
so_bool side0valid = SO_FALSE, side1valid = SO_FALSE;
for (int k = 0; k < 4; k++)
{
so_texel_t t0 = stitchingPoints->points[i].sides[0].texels[k];
so_texel_t t1 = stitchingPoints->points[i].sides[1].texels[k];
column0[k] = so_texel_binary_search(texelsFlat, n, t0);
column1[k] = so_texel_binary_search(texelsFlat, n, t1);
if (column0[k] == -1) { side0valid = SO_FALSE; break; }
if (column1[k] == -1) { side1valid = SO_FALSE; break; }
// test for validity of stitching point
for (int ci = 0; ci < c; ci++)
{
side0valid |= data[(t0.y * w + t0.x) * c + ci] > 0.0f;
side1valid |= data[(t1.y * w + t1.x) * c + ci] > 0.0f;
}
}
if (side0valid && side1valid)
{
for (int k = 0; k < 4; k++)
{
A[r * 8 + k * 2 + 0] = stitchingPoints->points[i].sides[0].weights[k];
AsparseIndices[r * 8 + k * 2 + 0] = column0[k];
A[r * 8 + k * 2 + 1] = -stitchingPoints->points[i].sides[1].weights[k];
AsparseIndices[r * 8 + k * 2 + 1] = column1[k];
}
r++;
}
}
m = r;
// add error terms for deviation from original pixel value (scaled by lambda)
for (int i = 0; i < n; i++)
{
A[(m + i) * 8] = lambda;
AsparseIndices[(m + i) * 8 + 0] = i;
AsparseIndices[(m + i) * 8 + 1] = -1;
}
so_sparse_entries_t AtA = so_matrix_At_times_A(A, AsparseIndices, 8, m + n, n);
so_sparse_entries_t L = so_matrix_cholesky_prepare(&AtA, n);
so_sparse_matrix_free(&AtA);
if (!L.count)
{
so_free(memoryBlock);
return SO_FALSE; // Cholesky decomposition failed
}
so_sparse_entries_t Lcols;
so_sparse_matrix_alloc(&Lcols, L.count);
for (int i = 0; i < L.count; i++)
so_sparse_matrix_add(&Lcols, (L.entries[i].index % n) * n + (L.entries[i].index / n), L.entries[i].value);
so_sparse_matrix_sort(&Lcols);
// solve each color channel independently
for (int ci = 0; ci < c; ci++)
{
for (int i = 0; i < n; i++)
b[m + i] = lambda * data[(texelsFlat[i].y * w + texelsFlat[i].x) * c + ci];
so_matrix_At_times_b(A, m + n, n, b, Atb, AsparseIndices, 8);
so_matrix_cholesky_solve(&L, &Lcols, x, Atb, n);
// write out results
for (int i = 0; i < n; i++)
data[(texelsFlat[i].y * w + texelsFlat[i].x) * c + ci] = x[i];
}
so_free(memoryBlock);
so_sparse_matrix_free(&L);
so_sparse_matrix_free(&Lcols);
return SO_TRUE;
}
#endif // SEAMOPTIMIZER_IMPLEMENTATION
|
Java
|
UTF-8
| 17,180
| 1.539063
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2018-2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 com.amazonaws.services.securityhub.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.securityhub.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* AwsEcsTaskDefinitionContainerDefinitionsDetails JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AwsEcsTaskDefinitionContainerDefinitionsDetailsJsonUnmarshaller implements
Unmarshaller<AwsEcsTaskDefinitionContainerDefinitionsDetails, JsonUnmarshallerContext> {
public AwsEcsTaskDefinitionContainerDefinitionsDetails unmarshall(JsonUnmarshallerContext context) throws Exception {
AwsEcsTaskDefinitionContainerDefinitionsDetails awsEcsTaskDefinitionContainerDefinitionsDetails = new AwsEcsTaskDefinitionContainerDefinitionsDetails();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("Command", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails.setCommand(new ListUnmarshaller<String>(context.getUnmarshaller(String.class))
.unmarshall(context));
}
if (context.testExpression("Cpu", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails.setCpu(context.getUnmarshaller(Integer.class).unmarshall(context));
}
if (context.testExpression("DependsOn", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails
.setDependsOn(new ListUnmarshaller<AwsEcsTaskDefinitionContainerDefinitionsDependsOnDetails>(
AwsEcsTaskDefinitionContainerDefinitionsDependsOnDetailsJsonUnmarshaller.getInstance())
.unmarshall(context));
}
if (context.testExpression("DisableNetworking", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails.setDisableNetworking(context.getUnmarshaller(Boolean.class).unmarshall(context));
}
if (context.testExpression("DnsSearchDomains", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails.setDnsSearchDomains(new ListUnmarshaller<String>(context.getUnmarshaller(String.class))
.unmarshall(context));
}
if (context.testExpression("DnsServers", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails.setDnsServers(new ListUnmarshaller<String>(context.getUnmarshaller(String.class))
.unmarshall(context));
}
if (context.testExpression("DockerLabels", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails.setDockerLabels(new MapUnmarshaller<String, String>(context.getUnmarshaller(String.class),
context.getUnmarshaller(String.class)).unmarshall(context));
}
if (context.testExpression("DockerSecurityOptions", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails
.setDockerSecurityOptions(new ListUnmarshaller<String>(context.getUnmarshaller(String.class))
.unmarshall(context));
}
if (context.testExpression("EntryPoint", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails.setEntryPoint(new ListUnmarshaller<String>(context.getUnmarshaller(String.class))
.unmarshall(context));
}
if (context.testExpression("Environment", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails
.setEnvironment(new ListUnmarshaller<AwsEcsTaskDefinitionContainerDefinitionsEnvironmentDetails>(
AwsEcsTaskDefinitionContainerDefinitionsEnvironmentDetailsJsonUnmarshaller.getInstance())
.unmarshall(context));
}
if (context.testExpression("EnvironmentFiles", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails
.setEnvironmentFiles(new ListUnmarshaller<AwsEcsTaskDefinitionContainerDefinitionsEnvironmentFilesDetails>(
AwsEcsTaskDefinitionContainerDefinitionsEnvironmentFilesDetailsJsonUnmarshaller.getInstance())
.unmarshall(context));
}
if (context.testExpression("Essential", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails.setEssential(context.getUnmarshaller(Boolean.class).unmarshall(context));
}
if (context.testExpression("ExtraHosts", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails
.setExtraHosts(new ListUnmarshaller<AwsEcsTaskDefinitionContainerDefinitionsExtraHostsDetails>(
AwsEcsTaskDefinitionContainerDefinitionsExtraHostsDetailsJsonUnmarshaller.getInstance())
.unmarshall(context));
}
if (context.testExpression("FirelensConfiguration", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails
.setFirelensConfiguration(AwsEcsTaskDefinitionContainerDefinitionsFirelensConfigurationDetailsJsonUnmarshaller.getInstance()
.unmarshall(context));
}
if (context.testExpression("HealthCheck", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails.setHealthCheck(AwsEcsTaskDefinitionContainerDefinitionsHealthCheckDetailsJsonUnmarshaller
.getInstance().unmarshall(context));
}
if (context.testExpression("Hostname", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails.setHostname(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("Image", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails.setImage(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("Interactive", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails.setInteractive(context.getUnmarshaller(Boolean.class).unmarshall(context));
}
if (context.testExpression("Links", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails.setLinks(new ListUnmarshaller<String>(context.getUnmarshaller(String.class))
.unmarshall(context));
}
if (context.testExpression("LinuxParameters", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails
.setLinuxParameters(AwsEcsTaskDefinitionContainerDefinitionsLinuxParametersDetailsJsonUnmarshaller.getInstance()
.unmarshall(context));
}
if (context.testExpression("LogConfiguration", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails
.setLogConfiguration(AwsEcsTaskDefinitionContainerDefinitionsLogConfigurationDetailsJsonUnmarshaller.getInstance().unmarshall(
context));
}
if (context.testExpression("Memory", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails.setMemory(context.getUnmarshaller(Integer.class).unmarshall(context));
}
if (context.testExpression("MemoryReservation", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails.setMemoryReservation(context.getUnmarshaller(Integer.class).unmarshall(context));
}
if (context.testExpression("MountPoints", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails
.setMountPoints(new ListUnmarshaller<AwsEcsTaskDefinitionContainerDefinitionsMountPointsDetails>(
AwsEcsTaskDefinitionContainerDefinitionsMountPointsDetailsJsonUnmarshaller.getInstance())
.unmarshall(context));
}
if (context.testExpression("Name", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails.setName(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("PortMappings", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails
.setPortMappings(new ListUnmarshaller<AwsEcsTaskDefinitionContainerDefinitionsPortMappingsDetails>(
AwsEcsTaskDefinitionContainerDefinitionsPortMappingsDetailsJsonUnmarshaller.getInstance())
.unmarshall(context));
}
if (context.testExpression("Privileged", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails.setPrivileged(context.getUnmarshaller(Boolean.class).unmarshall(context));
}
if (context.testExpression("PseudoTerminal", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails.setPseudoTerminal(context.getUnmarshaller(Boolean.class).unmarshall(context));
}
if (context.testExpression("ReadonlyRootFilesystem", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails.setReadonlyRootFilesystem(context.getUnmarshaller(Boolean.class).unmarshall(context));
}
if (context.testExpression("RepositoryCredentials", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails
.setRepositoryCredentials(AwsEcsTaskDefinitionContainerDefinitionsRepositoryCredentialsDetailsJsonUnmarshaller.getInstance()
.unmarshall(context));
}
if (context.testExpression("ResourceRequirements", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails
.setResourceRequirements(new ListUnmarshaller<AwsEcsTaskDefinitionContainerDefinitionsResourceRequirementsDetails>(
AwsEcsTaskDefinitionContainerDefinitionsResourceRequirementsDetailsJsonUnmarshaller.getInstance())
.unmarshall(context));
}
if (context.testExpression("Secrets", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails.setSecrets(new ListUnmarshaller<AwsEcsTaskDefinitionContainerDefinitionsSecretsDetails>(
AwsEcsTaskDefinitionContainerDefinitionsSecretsDetailsJsonUnmarshaller.getInstance())
.unmarshall(context));
}
if (context.testExpression("StartTimeout", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails.setStartTimeout(context.getUnmarshaller(Integer.class).unmarshall(context));
}
if (context.testExpression("StopTimeout", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails.setStopTimeout(context.getUnmarshaller(Integer.class).unmarshall(context));
}
if (context.testExpression("SystemControls", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails
.setSystemControls(new ListUnmarshaller<AwsEcsTaskDefinitionContainerDefinitionsSystemControlsDetails>(
AwsEcsTaskDefinitionContainerDefinitionsSystemControlsDetailsJsonUnmarshaller.getInstance())
.unmarshall(context));
}
if (context.testExpression("Ulimits", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails.setUlimits(new ListUnmarshaller<AwsEcsTaskDefinitionContainerDefinitionsUlimitsDetails>(
AwsEcsTaskDefinitionContainerDefinitionsUlimitsDetailsJsonUnmarshaller.getInstance())
.unmarshall(context));
}
if (context.testExpression("User", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails.setUser(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("VolumesFrom", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails
.setVolumesFrom(new ListUnmarshaller<AwsEcsTaskDefinitionContainerDefinitionsVolumesFromDetails>(
AwsEcsTaskDefinitionContainerDefinitionsVolumesFromDetailsJsonUnmarshaller.getInstance())
.unmarshall(context));
}
if (context.testExpression("WorkingDirectory", targetDepth)) {
context.nextToken();
awsEcsTaskDefinitionContainerDefinitionsDetails.setWorkingDirectory(context.getUnmarshaller(String.class).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return awsEcsTaskDefinitionContainerDefinitionsDetails;
}
private static AwsEcsTaskDefinitionContainerDefinitionsDetailsJsonUnmarshaller instance;
public static AwsEcsTaskDefinitionContainerDefinitionsDetailsJsonUnmarshaller getInstance() {
if (instance == null)
instance = new AwsEcsTaskDefinitionContainerDefinitionsDetailsJsonUnmarshaller();
return instance;
}
}
|
Python
|
UTF-8
| 479
| 3.140625
| 3
|
[] |
no_license
|
#!/bin/python3
import math
import os
import random
import re
import sys
def dectobin(n):
binary = ''
while(n>=1):
if n==1:
binary = ''.join([binary,str(n)])
return binary
else:
r = n%2
binary = ''.join([binary,str(r)])
n = n//2
return binary
if __name__ == '__main__':
n = int(input())
binary = dectobin(n)
result = binary.split('0')
print(max([len(x) for x in result]))
|
Markdown
|
UTF-8
| 1,307
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
---
title: Jacob Sartorius arrested for drug abuse
layout: post
author: max.morphey
permalink: /even-more-admin/
source-id: 1hwDGKNmB4ZsUpW8_Rb8-B7SqScd3S3rZ9zT0tcuzzjU
published: true
---
<table>
<tr>
<td>Title: </td>
<td>Making my page look even neater</td>
<td> Date: </td>
<td>14/12/16</td>
</tr>
</table>
<table>
<tr>
<td>Starting point:</td>
<td>I had no knowledge</td>
</tr>
<tr>
<td>Target for this lesson?</td>
<td>To make my home page look more appealing and neat</td>
</tr>
<tr>
<td>Did I reach my target?
(add details to "Lesson Review")</td>
<td>I think so, as I followed all the instructions and seem to have done everything in the correct order.</td>
</tr>
</table>
<table>
<tr>
<td>Lesson Review</td>
</tr>
<tr>
<td>How did I learn? What strategies were effective? </td>
</tr>
<tr>
<td> By listening and working out the problems by myself, only asking for help when I needed it</td>
</tr>
<tr>
<td>What limited my learning? Which habits do I need to work on? </td>
</tr>
<tr>
<td>My inability to do some of the steps effectively</td>
</tr>
<tr>
<td>What will I change for next time? How will I improve my learning?</td>
</tr>
<tr>
<td>Try to master my skills</td>
</tr>
</table>
|
Java
|
UTF-8
| 3,533
| 2.421875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.airbnb.reair.incremental.configuration;
import com.airbnb.reair.incremental.DirectoryCopier;
import com.airbnb.reair.incremental.deploy.ConfigurationKeys;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Optional;
public class ConfiguredClusterFactory implements ClusterFactory {
private Optional<Configuration> optionalConf = Optional.empty();
public void setConf(Configuration conf) {
this.optionalConf = Optional.of(conf);
}
private static URI makeUri(String thriftUri) throws ConfigurationException {
try {
URI uri = new URI(thriftUri);
if (uri.getPort() <= 0) {
throw new ConfigurationException("No port specified in "
+ thriftUri);
}
if (!"thrift".equals(uri.getScheme())) {
throw new ConfigurationException("Not a thrift URI; "
+ thriftUri);
}
return uri;
} catch (URISyntaxException e) {
throw new ConfigurationException(e);
}
}
@Override
public Cluster getDestCluster() throws ConfigurationException {
if (!optionalConf.isPresent()) {
throw new ConfigurationException("Configuration not set!");
}
Configuration conf = optionalConf.get();
String destClusterName = conf.get(
ConfigurationKeys.DEST_CLUSTER_NAME);
String destMetastoreUrlString = conf.get(
ConfigurationKeys.DEST_CLUSTER_METASTORE_URL);
URI destMetastoreUrl = makeUri(destMetastoreUrlString);
String destHdfsRoot = conf.get(
ConfigurationKeys.DEST_HDFS_ROOT);
String destHdfsTmp = conf.get(
ConfigurationKeys.DEST_HDFS_TMP);
Boolean destIsHA = conf.getBoolean( ConfigurationKeys.DEST_HDFS_IS_HA , true );
return new HardCodedCluster(
destClusterName,
destMetastoreUrl.getHost(),
destMetastoreUrl.getPort(),
null,
null,
new Path(destHdfsRoot),
new Path(destHdfsTmp),
destIsHA);
}
@Override
public Cluster getSrcCluster() throws ConfigurationException {
if (!optionalConf.isPresent()) {
throw new ConfigurationException("Configuration not set!");
}
Configuration conf = optionalConf.get();
// Create the source cluster object
String srcClusterName = conf.get(
ConfigurationKeys.SRC_CLUSTER_NAME);
String srcMetastoreUrlString = conf.get(
ConfigurationKeys.SRC_CLUSTER_METASTORE_URL);
URI srcMetastoreUrl = makeUri(srcMetastoreUrlString);
String srcHdfsRoot = conf.get(
ConfigurationKeys.SRC_HDFS_ROOT);
String srcHdfsTmp = conf.get(
ConfigurationKeys.SRC_HDFS_TMP);
Boolean srcHdfsIsHA = conf.getBoolean(
ConfigurationKeys.SRC_HDFS_IS_HA, true);
return new HardCodedCluster(
srcClusterName,
srcMetastoreUrl.getHost(),
srcMetastoreUrl.getPort(),
null,
null,
new Path(srcHdfsRoot),
new Path(srcHdfsTmp),
srcHdfsIsHA);
}
@Override
public DirectoryCopier getDirectoryCopier() throws ConfigurationException {
if (!optionalConf.isPresent()) {
throw new ConfigurationException("Configuration not set!");
}
Configuration conf = optionalConf.get();
String destHdfsTmp = conf.get(
ConfigurationKeys.DEST_HDFS_TMP);
return new DirectoryCopier(conf,
new Path(destHdfsTmp),
conf.getBoolean(ConfigurationKeys.SYNC_MODIFIED_TIMES_FOR_FILE_COPY, true));
}
}
|
JavaScript
|
UTF-8
| 13,444
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
// Great Vegan restaurant locations in SF for the app
var locations = [
{
"title" : "Shizen Vegan Sushi Bar",
"location" : { "lat" : 37.768313, "lng" : -122.421643 },
"foursquareid" : "54a8b5d1498ef8abe40ce6b3",
"rating" : "loading"
},
{
"title" : "Halu Ramen",
"location" : { "lat" : 37.782568, "lng" : -122.466456 },
"foursquareid" : "4a865e24f964a520fe0020e3",
"rating" : "loading"
},
{
"title" : "Gracias Madre San Francisco",
"location" : { "lat" : 37.761572, "lng" : -122.419080 },
"foursquareid" : "4b4955ccf964a520b86d26e3",
"rating" : "loading"
},
{
"title" : "No No Burger",
"location" : { "lat" : 37.769769, "lng" : -122.412049 },
"foursquareid" : "5650e4ab498edd90781e193d",
"rating" : "loading"
},
{
"title" : "Nourish Cafe",
"location" : { "lat" : 37.785241, "lng" : -122.464783 },
"foursquareid" : "54ea1afc498e12af65963097",
"rating" : "loading"
},
{
"title" : "Thai Idea",
"location" : { "lat" : 37.783457, "lng" : -122.419116 },
"foursquareid" : "4e7d7aebf5b9644b441e28f3",
"rating" : "loading"
}
];
// Setting up for each individual location
var Location = function(data) {
var self = this;
self.title = data.title;
self.location = data.location;
};
// create a new array for the map
var map;
// info window global variable for google maps api
var largeInfoWindow;
// create a blank array for all listing markers
var markers = [];
// counter for the foursquare API calls on success and error
var apiCallsCompleted = 0;
// Call back function for the API. Keeps count of all API calls completed
// Loads the app when finished just to make sure it grabs all ratings.
// @index is the index from the ajax function
// @rating is the rating returned from the Foursquare API
function apiCallBack(index, rating) {
apiCallsCompleted++;
locations[index].rating = rating;
if (apiCallsCompleted >= locations.length) {
appLoader();
}
}
// Calls out to foursquare api
function fourSquareData(index) {
var apiURL = 'https://api.foursquare.com/v2/venues/';
var foursquareClientID = 'A2ZC3EKQFCXLXBEJPXQPA5YVVDG1EZYTW453HM4FY1HPOWS4';
var foursquareSecret ='VXX1VWQ1JK1XDTCNYB5JYCILUXQ5MG3X5WIAOL1WTFHCQJSW';
var foursquareVersion = '20170112';
var foursquareid = locations[index].foursquareid;
// URL using variables above
var foursquareURL = apiURL + foursquareid + '?client_id=' + foursquareClientID + '&client_secret=' + foursquareSecret +'&v=' + foursquareVersion;
// Reaches out to Foursquare and grabs the venue rating
// includes Graceful success and error handling of the Ajax call
$.ajax({
"url" : foursquareURL,
"datatype" : "jsonp",
"success" : function(response) {
resp = response.response.venue.rating;
var rating = "Not yet rated";
if (resp > 0) {
rating = resp;
}
apiCallBack(index, rating);
},
"error" : function(error) {
console.log('API error for Foursquareid ' + foursquareid);
var rating = "Could not load results api error";
apiCallBack(index, rating);
}
});
}
// Basic google maps constructor
function initMap() {
// Map Constructor
map = new google.maps.Map(document.getElementById('map'), {
center: { lat: 37.785, lng: -122.446 },
zoom: 12,
styles: styles2,
mapTypeControl: false
});
// runs through and gets the rating data
// bases it on the index.
for (var i = 0; i < locations.length; i++){
fourSquareData(i);
}
}
// Continues loading the app
// Runs only after the ratings are retrieved from the FS api
function appLoader() {
// info window provides from google maps
var largeInfoWindow = new google.maps.InfoWindow();
// style the markers
var defaultIcon = makeMarkerIcon('0091ff');
// create a "highlighted location" marker color
var highlightedIcon = makeMarkerIcon('FFFF24');
// sets bounds on load to zoom in on San Francisco
var bounds = new google.maps.LatLngBounds();
// Loops through all locations and assigns
// a marker to each of them.
// this also attaches the FS venue rating within the title.
for (var i = 0; i < locations.length; i++) {
var rating = locations[i].rating;
var position = locations[i].location;
var title = locations[i].title + ' - Rating: ' + rating;
// setting the marker and dropping it on each location.
locations[i].marker = new google.maps.Marker({
position: position,
title: title,
icon: defaultIcon,
animation: google.maps.Animation.DROP,
id: i
});
// Push the marker to our array of markers
markers.push(locations[i].marker);
// Create an onclick event to toggle the bounce animation
// on the marker
locations[i].marker.addListener('click', function() {
toggleBounce(this);
});
// Create an onclick event to open an infowindow at each marker.
locations[i].marker.addListener('click', function() {
populateInfoWindow(this, largeInfoWindow);
});
// two event listeners - one for mouse over, one ofr mouseout,
// to change the colors back and forth
locations[i].marker.addListener('mouseover', function() {
this.setIcon(highlightedIcon);
});
// Changes the marker once you mouse off.
locations[i].marker.addListener('mouseout', function() {
this.setIcon(defaultIcon);
});
// sets the map
// extends the bounds to include the markers.
markers[i].setMap(map);
bounds.extend(locations[i].marker.position);
}
// sets map and fits bounds.
google.maps.event.addDomListener(window, 'resize', function() {
map.fitBounds(bounds);
});
// Show pins when clicked (just a nice user function)
// TODO: Change this to click binding with knockout js
// document.getElementById('show-listings').addEventListener('click', showListings);
// // Hide all pins when clicked (just a nice user function)
// // TODO: Change this to click binding with Knockoutjs
// document.getElementById('hide-listings').addEventListener('click', function() {
// hideMarkers(markers);
// });
}
// Errors out for Google maps according to their documentation
function mapError() {
alert("Sorry! SORRY! Google Maps could not be loaded");
}
// adds a bounce animation to those markers that are selected.
function toggleBounce(marker) {
if (marker.getAnimation() !== null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
setTimeout(function(){ marker.setAnimation(null); }, 1400);
}
}
// populates the boxes that pop up when a marker is clicked.
function populateInfoWindow(marker, infowindow) {
if (infowindow.marker != marker) {
infowindow.marker = marker;
infowindow.setContent('<div>' + marker.title + '</div>');
infowindow.open(map, marker);
// Making sure the marker property is cleared if the infowindow is closed.
infowindow.addListener('closeclick',function(){
infowindow.setMap(null);
});
var streetViewService = new google.maps.StreetViewService();
var radius = 50;
// In case the status is OK, which means the pano was found, compute the
// position of the streetview image, then calculate the heading, then get a
// panorama from that and set the options.
function getStreetView(data, status) {
if (status == google.maps.StreetViewStatus.OK) {
var nearStreetViewLocation = data.location.latLng;
var heading = google.maps.geometry.spherical.computeHeading(
nearStreetViewLocation, marker.position);
infowindow.setContent('<div>' + marker.title + '</div><div id="pano"></div>');
var panoramaOptions = {
position: nearStreetViewLocation,
pov: {
heading: heading,
pitch: 30
}
};
var panorama = new google.maps.StreetViewPanorama(
document.getElementById('pano'), panoramaOptions);
} else {
infowindow.setContent('<div>' + marker.title + '</div>' +
'<div>No Street View Found</div>');
}
}
// Use streetview service to get the closest streetview image within
// 50 meters of the markers position.
streetViewService.getPanoramaByLocation(marker.position, radius, getStreetView);
// Open the infowindow on the correct marker.
infowindow.open(map, marker);
}
}
// This function will loops through the markers array and display them all.
// TODO: Convert these functions to Knockout JS
// function showListings() {
// var bounds = new google.maps.LatLngBounds();
// // extend the boundaries of the map for each marker and display the marker.
// for (var i = 0; i < markers.length; i++) {
// markers[i].setMap(map);
// bounds.extend(markers[i].position);
// }
// map.fitBounds(bounds);
// }
// this function will loop through listings and hide them all
// TODO: Convert these functions to knockout JS
// function hideMarkers(markers) {
// for (var i = 0; i < markers.length; i++) {
// markers[i].setMap(null);
// }
// }
// sets the marker icon
function makeMarkerIcon(markerColor) {
var markerImage = new google.maps.MarkerImage(
'http://chart.googleapis.com/chart?chst=d_map_spin&chld=1.15|0|'+ markerColor +
'|40|_|%E2%80%A2',
new google.maps.Size(21, 34),
new google.maps.Point(0, 0),
new google.maps.Point(10, 34),
new google.maps.Size(21,34));
return markerImage;
}
// Knockout JS viewmodel function
// listSelect: handles when location is selected from list on the left hand side.
// search entry: handles the search functionality of the viewmodel.
var AppViewModel = function() {
var self = this;
self.appLocations = ko.observableArray(locations.slice());
self.searchEntry = ko.observable('');
self.listSelect = function(locations) {
// Open info window on click.
google.maps.event.trigger(locations.marker, 'click');
};
self.onSearchEntry = function(event) {
this.appLocations.removeAll();
for (var i = 0; i < locations.length; i++) {
if (self.searchEntry() !== ''){
if (locations[i].title.toLowerCase().indexOf(self.searchEntry().toLowerCase()) != -1) {
self.appLocations.push(locations[i]);
markers[i].setMap(map);
} else {
markers[i].setMap(null);
}
} else {
self.appLocations.push(locations[i]);
markers[i].setMap(map);
}
}
};
};
// instantiate the ViewModel using the operator and apply bindings
var appViewModel = new AppViewModel();
// activate knockout and apply binding.
ko.applyBindings(appViewModel);
// all the styles for the google maps.
// nice and green and healthy looking!
var styles2 = [
{
"featureType": "landscape",
"stylers": [
{
"hue": "#FFA800"
},
{
"saturation": 0
},
{
"lightness": 0
},
{
"gamma": 1
}
]
},
{
"featureType": "road.highway",
"stylers": [
{
"hue": "#53FF00"
},
{
"saturation": -73
},
{
"lightness": 40
},
{
"gamma": 1
}
]
},
{
"featureType": "road.arterial",
"stylers": [
{
"hue": "#FBFF00"
},
{
"saturation": 0
},
{
"lightness": 0
},
{
"gamma": 1
}
]
},
{
"featureType": "road.local",
"stylers": [
{
"hue": "#00FFFD"
},
{
"saturation": 0
},
{
"lightness": 30
},
{
"gamma": 1
}
]
},
{
"featureType": "water",
"stylers": [
{
"hue": "#00BFFF"
},
{
"saturation": 6
},
{
"lightness": 8
},
{
"gamma": 1
}
]
},
{
"featureType": "poi",
"stylers": [
{
"hue": "#679714"
},
{
"saturation": 33.4
},
{
"lightness": -25.4
},
{
"gamma": 1
}
]
}
];
|
JavaScript
|
UTF-8
| 1,162
| 2.6875
| 3
|
[] |
no_license
|
function set_featured_item(elem, featured, id)
{
var row = elem.parentNode;
img = elem.childNodes[0];
if (featured != 'featured')
{
img.oSrc = img.oSrc.replace(/show/g, 'hide');
img.src = img.src.replace(/show/g, 'hide');
img.oSrc = img.oSrc.replace(/not.featured/g, 'featured');
img.src = img.src.replace(/not.featured/g, 'featured');
elem.onclick = function () { return set_featured_item(this, 'featured', id); };
value = 1;
}
else
{
img.oSrc = img.oSrc.replace(/hide/g, 'show');
img.src = img.src.replace(/hide/g, 'show');
img.oSrc = img.oSrc.replace(/featured/g, 'not featured');
img.src = img.src.replace(/featured/g, 'not featured');
elem.onclick = function () { return set_featured_item(this, 'not featured', id); };
value = 0;
}
// Create new JS element
var jsel = document.createElement('SCRIPT');
jsel.type = 'text/javascript';
jsel.src = '/modules/case_studies/admin/ajax_functions.php?action=setfeatured&id='+id+'&value='+value;
// Append JS element (thereby executing the 'AJAX' call)
document.body.appendChild (jsel);
//document.body.removeChild(jsel); return false;
return false
}
|
Java
|
UTF-8
| 1,817
| 2.265625
| 2
|
[] |
no_license
|
/**
* Copyright (c) 2012 powered by CNRVoice
*
* @author: CNR
* @date: 2012-10-12 上午11:53:19
* @Description:
*
*/
package com.cnrvoice.base.authc;
import java.util.Collection;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.AuthenticationStrategy;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MultiRealmAuthenticator extends ModularRealmAuthenticator
{
private static final Logger log = LoggerFactory
.getLogger(MultiRealmAuthenticator.class);
protected AuthenticationInfo doMultiRealmAuthentication(
Collection<Realm> realms, AuthenticationToken token)
{
AuthenticationStrategy strategy = getAuthenticationStrategy();
AuthenticationInfo aggregate = strategy
.beforeAllAttempts(realms, token);
if (log.isTraceEnabled())
{
log.trace("Iterating through {} realms for PAM authentication",
realms.size());
}
for (Realm realm : realms)
{
aggregate = strategy.beforeAttempt(realm, token, aggregate);
if (realm.supports(token))
{
log.trace(
"Attempting to authenticate token [{}] using realm [{}]",
token, realm);
AuthenticationInfo info = null;
Throwable t = null;
info = realm.getAuthenticationInfo(token);
aggregate = strategy.afterAttempt(realm, token, info,
aggregate, t);
}
else
{
log.debug(
"Realm [{}] does not support token {}. Skipping realm.",
realm, token);
}
}
aggregate = strategy.afterAllAttempts(token, aggregate);
return aggregate;
}
}
|
JavaScript
|
UTF-8
| 184
| 3.046875
| 3
|
[] |
no_license
|
let a = 2;
let b = 2;
let c = 2;
let d = 2;
let h = 1;
const f = (a,b,h) => {return h*(a+b)/2}
console.log(`Pole powierzchni trapezu o wymiarach ${a}, ${b}, ${h}, wynosi ${f(a,b,h)}`);
|
Java
|
UTF-8
| 919
| 1.984375
| 2
|
[] |
no_license
|
package rmagalhaes.com.baking.data.helpers;
import android.net.Uri;
import android.provider.BaseColumns;
/**
* Created by Rafael Magalhães on 04/03/18.
*/
public class RecipeContract {
public static final String AUTHORITY = "rmagalhaes.com.baking";
public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + AUTHORITY);
public static final String PATH_RECIPES = "recipes";
public static final class RecipeEntry implements BaseColumns {
// TaskEntry content URI = base content URI + path
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_RECIPES).build();
public static final String TABLE_NAME = "plants";
public static final String COLUMN_RECIPE_ID = "recipe_id";
public static final String COLUMN_RECIPE_NAME = "recipe_name";
public static final String COLUMN_RECIPE_SERVINGS = "servings";
}
}
|
Markdown
|
UTF-8
| 981
| 2.953125
| 3
|
[
"MIT"
] |
permissive
|
# Virtual Camera
3D first-person virtual camera [Processing](https://processing.org) library. Allows you to control the camera with the keyboard and mouse, using WASD-style movement.



## Projects
### [Locus](https://github.com/adjl/Locus)

## Usage
Please see [`com.adjl.virtualcamera.demo.Camera`](src/com/adjl/virtualcamera/demo/Camera.java) for sample usage; run it for a demonstration.
## Controls
`w` - Move forward
`a` - Strafe left
`s` - Move backward
`d` - Strafe right
`r` - Fly up
`f` - Fly down
`q` - Quit
Move the pointer to look around.
## Issues
Found a bug, have a question, or suggestion for enhancement? Please [file an issue](https://github.com/adjl/VirtualCamera/issues).
## License
[MIT License](LICENSE)
|
Python
|
UTF-8
| 6,587
| 2.703125
| 3
|
[] |
no_license
|
#!/usr/bin/env python
# coding: utf-8
# Author: Kaiqi Fu
# usage: require 1. ref_human_detail 2. human_our_detail 3 ref_our_detail
import re
f = open("ref_human_detail",'r')
dic={}
insert = 0
delete = 0
sub = 0
cor=0
count=0
## 0: ref 1:human 2:ops --- 3: human 4: our 5: ops
for line in f:
line = line.strip()
if("ref" in line ):
ref = line.split("ref")
ref[0] = ref[0].strip(" ")
ref[1] = ref[1].strip(" ")
ref[1] = re.sub(" +"," ",ref[1])
ref_seq = ref[1].split(" ")
dic[ref[0]] = []
dic[ref[0]].append(ref[1])
elif( "hyp" in line ):
hyp = line.split("hyp")
hyp[0] = hyp[0].strip(" ")
hyp[1] = hyp[1].strip(" ")
hyp[1] = re.sub(" +"," ",hyp[1])
hyp_seq = hyp[1].split(" ")
dic[hyp[0]].append(hyp[1])
elif( " op " in line ):
op = line.split(" op ")
op[0] = op[0].strip(" ")
op[1] = op[1].strip(" ")
op[1] = re.sub(" +"," ",op[1])
op_seq = op[1].split(" ")
dic[op[0]].append(op[1])
for i in op_seq:
if(i == "I"):
insert+=1
elif(i == "D"):
delete+=1
count+=1
elif(i == "S"):
sub +=1
count+=1
elif(i=="C"):
cor+=1
count+=1
f.close()
## 发音错误统计
print("insert:" ,insert)
print("delete:" ,delete)
print("sub:" ,sub)
print("cor:" ,cor)
print("sum", count)
f = open("human_our_detail",'r')
for line in f:
line = line.strip()
fn = line.split(" ")[0]
if(fn not in dic):
continue
if("ref" in line ):
ref = line.split("ref")
ref[0] = ref[0].strip(" ")
ref[1] = ref[1].strip(" ")
ref[1] = re.sub(" +"," ",ref[1])
ref_seq = ref[1].split(" ")
dic[ref[0]].append(ref[1])
elif( "hyp" in line ):
hyp = line.split("hyp")
hyp[0] = hyp[0].strip(" ")
hyp[1] = hyp[1].strip(" ")
hyp[1] = re.sub(" +"," ",hyp[1])
hyp_seq = hyp[1].split(" ")
dic[hyp[0]].append(hyp[1])
elif( " op " in line ):
op = line.split(" op ")
op[0] = op[0].strip(" ")
op[1] = op[1].strip(" ")
op[1] = re.sub(" +"," ",op[1])
op_seq = op[1].split(" ")
dic[op[0]].append(op[1])
f.close()
f = open("ref_our_detail",'r')
for line in f:
line = line.strip()
fn = line.split(" ")[0]
if(fn not in dic):
continue
if("ref" in line ):
ref = line.split("ref")
ref[0] = ref[0].strip(" ")
ref[1] = ref[1].strip(" ")
ref[1] = re.sub(" +"," ",ref[1])
ref_seq = ref[1].split(" ")
dic[ref[0]].append(ref[1])
elif( "hyp" in line ):
hyp = line.split("hyp")
hyp[0] = hyp[0].strip(" ")
hyp[1] = hyp[1].strip(" ")
hyp[1] = re.sub(" +"," ",hyp[1])
hyp_seq = hyp[1].split(" ")
dic[hyp[0]].append(hyp[1])
elif( " op " in line ):
op = line.split(" op ")
op[0] = op[0].strip(" ")
op[1] = op[1].strip(" ")
op[1] = re.sub(" +"," ",op[1])
op_seq = op[1].split(" ")
dic[op[0]].append(op[1])
f.close()
cor_cor = 0
cor_cor1 = 0
cor_nocor = 0
sub_sub = 0
sub_sub1 = 0
sub_nosub = 0
ins_ins = 0
ins_ins1 = 0
ins_noins =0
del_del = 0
del_del1 = 0
del_nodel =0
for i in dic:
arr = dic[i]
# del detection
ref_seq = arr[0].split(" ")
ref_seq3 = arr[6].split(" ")
op = arr[2].split(" ")
op3 = arr[8].split(" ")
flag = 0
for i in range( len(ref_seq) ):
if(ref_seq[i] == "<eps>"):
continue
while(ref_seq3[flag] == "<eps>"):
flag+=1
if( ref_seq[i] == ref_seq3[flag] and ref_seq[i]!="<eps>" ):
if( op[i] == "D" and op3[flag] == "D" ):
del_del+=1
elif( op[i] == "D" and op3[flag] != "D" and op3[flag] != "C"):
del_del1+=1
elif( op[i] == "D" and op3[flag] != "D" and op3[flag] == "C"):
del_nodel+=1
flag+=1
## cor ins sub detection
ref_seq = arr[0].split(" ")
human_seq = arr[1].split(" ")
op = arr[2].split(" ")
human_seq2 = arr[3].split(" ")
our_seq2 = arr[4].split(" ")
op2 = arr[5].split(" ")
flag = 0
for i in range( len(human_seq) ):
if(human_seq[i] == "<eps>"):
continue
while(human_seq2[flag] == "<eps>"):
flag+=1
if( human_seq[i] == human_seq2[flag] and human_seq[i]!="<eps>" ):
if( op[i] == "C" and op2[flag] == "C" ):
cor_cor+=1
elif( op[i] == "C" and op2[flag] != "C"):
cor_nocor+=1
if( op[i] == "S" and op2[flag] == "C" ):
sub_sub+=1
elif( op[i] == "S" and op2[flag] !="C" and ref_seq[i] != our_seq2[flag]):
sub_sub1+=1
elif( op[i] == "S" and op2[flag] !="C" and ref_seq[i] == our_seq2[flag]):
sub_nosub+=1
if(op[i] == "I" and op2[flag] == "C" ):
ins_ins+=1
elif( op[i] == "I" and op2[flag]!="C" and op2[flag]!="D"):
ins_ins1+=1
elif( op[i] == "I" and op2[flag]!="C" and op2[flag]=="D"):
ins_noins+=1
flag+=1
sum1 = cor_cor + cor_nocor + sub_sub + sub_sub1 + sub_nosub + ins_ins + ins_ins1 + ins_noins + del_del + del_del1 + del_nodel
print("sum:",sum1)
TR = sub_sub + ins_ins + del_del + sub_sub1 + ins_ins1 + del_del1
FR = cor_nocor
FA = sub_nosub + ins_noins + del_nodel
TA = cor_cor
recall = TR/(TR+FA)
precision = TR/(TR+FR)
print("Recall: %.4f" %(recall))
print("Precision: %.4f" %(precision))
print("f1:%.4f" % ( 2*precision*recall/(recall+precision) ))
print("TA: %.4f %d" %(cor_cor/(cor_cor+cor_nocor), TA))
print("FR: %.4f %d" %(cor_nocor/(cor_cor+cor_nocor), FR))
err_count = sub_sub+sub_sub1+sub_nosub+ins_ins+ins_ins1+ins_noins+del_del+del_del1+del_nodel
false_accept = sub_nosub + ins_noins + del_nodel
Correct_Diag = sub_sub + ins_ins + del_del
Error_Diag = sub_sub1 + ins_ins1 + del_del1
print("FA: %.4f %d" %(false_accept/err_count, false_accept))
print("Correct Diag: %.4f %d" %(Correct_Diag/(Correct_Diag+Error_Diag), Correct_Diag))
print("Error Diag: %.4f %d" %(Error_Diag/(Correct_Diag+Error_Diag), Error_Diag))
FAR = 1-recall
FRR = cor_nocor/(cor_nocor+cor_cor)
DER = Error_Diag / (Error_Diag + Correct_Diag)
print("FAR: %.4f" %(FAR))
print("FRR: %.4f" %(FRR))
print("DER: %.4f" %(DER))
|
Python
|
UTF-8
| 235
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
from sense_hat import SenseHat
from time import sleep
sense = SenseHat()
while True:
humidity = sense.get_humidity()
if humidity > 29:
sense.clear(255,0,0)
else:
sense.clear(0,0,255)
sleep(0.1)
|
Java
|
UTF-8
| 10,145
| 1.9375
| 2
|
[] |
no_license
|
package com.pwc.dao.mysql;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.persistence.Column;
import javax.persistence.Query;
import javax.persistence.Transient;
import javax.sound.midi.SysexMessage;
import javax.sql.DataSource;
import javax.transaction.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.FlushModeType;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceUnitUtil;
import javax.transaction.Transactional;
import javax.persistence.Query;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import org.apache.log4j.*;
import com.pwc.domain.core.TeamMember;import com.pwc.domain.core.DoUser;
/**
*
* @author Geppetto Generated Code</br>
* Date Created: </br>
* @since </br>
* build: </p>
*
* code was generated by the Geppetto System </br>
* Gepppetto system Copyright - Geppetto LLC 2014 - 2015</br>
* The generated code is free to use by anyone</p>
*
*
*
*/
@Transactional
@Repository("TeamMember_Default_ActivityDao")
public class TeamMember_Default_ActivityDao {
//private Log log = LogFactory.getLog(getClass());
private static Logger log = Logger.getLogger(TeamMember_Default_ActivityDao.class.getName());
@Value("${create_TeamMember.sql}")
private String create_TeamMember;
@Value("${search_for_update_TeamMember.sql}")
private String search_for_update_TeamMember;
@Value("${update_TeamMember.sql}")
private String update_TeamMember;
@Value("${delete_TeamMember.sql}")
private String delete_TeamMember;
@Value("${get_all_TeamMember.sql}")
private String get_all_TeamMember;
@Value("${search_TeamMember.sql}")
private String search_TeamMember;
@Value("${search_for_detail_TeamMember.sql}")
private String search_for_detail_TeamMember;
@PersistenceContext
private EntityManager entityManager;
// auths not ready at this time
/**
*
*The purpose of Dao method is to perform fetch operation of TeamMember noun from database based on given noun id
*@param id
*@param user
*@return the_TeamMember object will return
*@throws Exception
*/
public TeamMember teammember_search_for_update(long id, DoUser user) throws Exception {
log.setLevel(Level.INFO);
log.info("teammember_search_for_update Dao started operation!");
try{
Query result = entityManager.
createNativeQuery(search_for_update_TeamMember,TeamMember.class)
.setParameter("id", id);;
ArrayList<TeamMember> TeamMember_list = (ArrayList<TeamMember>)result.getResultList();
if(TeamMember_list == null){
log.error("teammember_search_for_update Dao throws exception :" + "no TeamMember found" );
}
log.info("Object returned from teammember_search_for_update Dao method !");
return (TeamMember) TeamMember_list.get(0);
}catch(Exception e){
//new Exception(e.toString()); // this needs to be changed
log.error("teammember_search_for_update Dao throws exception : "+e.toString());
}
return null;
}
// auths not ready at this time
/**
*
*The purpose of Dao method is to get list of TeamMember noun from database
*
*
*@return List of TeamMember object will return
*@throws Exception
*/
public ArrayList<TeamMember> get_all_teammember() throws Exception {
log.setLevel(Level.INFO);
log.info("get_all_teammember Dao started operation!");
try{
Query result = entityManager.
createNativeQuery(get_all_TeamMember,TeamMember.class)
;
ArrayList<TeamMember> TeamMember_list = (ArrayList<TeamMember>)result.getResultList();
if(TeamMember_list .size() < 1){
log.error("get_all_teammember Dao throws exception :" + "no TeamMember found" );
return new ArrayList<TeamMember>();
}
log.info("Object returned from get_all_teammember Dao method !");
return (ArrayList<TeamMember>) TeamMember_list;
}catch(Exception e){
//new Exception(e.toString()); // this needs to be changed
log.error("get_all_teammember Dao throws exception : "+e.toString());
}
return null;
}
// auths not ready at this time
/**
*
*The purpose of Dao method is to search a value in TeamMember table from database based on given inputs
*
*
*@return
*@throws Exception
*/
public ArrayList<TeamMember> search_teammember(String name, String email, String primary) throws Exception {
log.setLevel(Level.INFO);
log.info("search_teammember Dao started operation!");
try{
Query result = entityManager.
createNativeQuery(search_TeamMember,TeamMember.class)
.setParameter("name", name.equals("%%") ? name:name.concat("%"))
.setParameter("email", email.equals("%%") ? email:email.concat("%"))
.setParameter("primary", primary.equals("%%") ? primary:primary.concat("%"))
;
ArrayList<TeamMember> TeamMember_list = (ArrayList<TeamMember>)result.getResultList();
if(TeamMember_list == null){
log.error("search_teammember Dao throws exception :" + "null" );
}
log.info("Object returned from search_teammember Dao method !");
return (ArrayList<TeamMember>) TeamMember_list;
}catch(Exception e){
//new Exception(e.toString()); // this needs to be changed
log.error("search_teammember Dao throws exception : "+e.toString());
}
return null;
}
// auths not ready at this time
/**
*
*The purpose of Dao method is to perform fetch operation of TeamMember noun from database based on given noun id
*@param id
*@param user
*@return the_TeamMember object will return
*@throws Exception
*/
public TeamMember teammember_search_for_detail(long id, DoUser user) throws Exception {
log.setLevel(Level.INFO);
log.info("teammember_search_for_detail Dao started operation!");
try{
Query result = entityManager.
createNativeQuery(search_for_detail_TeamMember,TeamMember.class)
.setParameter("id", id);;
ArrayList<TeamMember> TeamMember_list = (ArrayList<TeamMember>)result.getResultList();
if(TeamMember_list == null){
log.error("teammember_search_for_detail Dao throws exception :" + "no TeamMember found" );
}
log.info("Object returned from teammember_search_for_detail Dao method !");
return (TeamMember) TeamMember_list.get(0);
}catch(Exception e){
//new Exception(e.toString()); // this needs to be changed
log.error("teammember_search_for_detail Dao throws exception : "+e.toString());
}
return null;
}
//auths not ready at this time
/**
*
*The purpose of Dao method is to perform save operation of TeamMember noun into database
*@param TeamMember
*@param user
*@return TeamMember object will return
*@throws Exception
*/
@Transactional
public TeamMember create_teammember(TeamMember TeamMember, DoUser user) throws Exception {
log.setLevel(Level.INFO);
log.info("create_teammember Dao started operation!");//dhina updateverb
try{
Query query = entityManager
.createNativeQuery(create_TeamMember)
.setParameter("name", TeamMember.getName())
.setParameter("email", TeamMember.getEmail())
.setParameter("primary", TeamMember.getPrimary())
.setParameter("created_by", user == null ? 0:user.getId())
.setParameter("updated_by", user == null ? 0:user.getId())
;
int insertedId = query.executeUpdate();
String lastIndex="select last_insert_id()";
Query sql = entityManager.createNativeQuery(lastIndex);
BigInteger new_id = (BigInteger) sql.getSingleResult();
TeamMember.setId(new_id.longValue());
System.out.println("create data---"+insertedId);
log.info("Object returned from create_teammember Dao method !");
return TeamMember;
}catch(Exception e){
//System.out.println("DAOException: " + e.toString());
log.error(" Dao method (create_teammember) throws Exception : "+e.toString());
}
return null;
}
//auths not ready at this time
/**
*
*The purpose of Dao method is to perform update operation of TeamMember noun into database
*@param TeamMember
*@param user
*@return the_TeamMember object will return
*@throws Exception
*/
@Transactional
public TeamMember update_teammember(TeamMember TeamMember, DoUser user) throws Exception {
log.setLevel(Level.INFO);
log.info("update_teammember Dao started operation!");//dhina updateverb
try{
Query query = entityManager
.createNativeQuery(update_TeamMember)
.setParameter("id", TeamMember.getId())
.setParameter("name", TeamMember.getName())
.setParameter("email", TeamMember.getEmail())
.setParameter("primary", TeamMember.getPrimary())
.setParameter("updated_by", user == null ? 0:user.getId())
;
query.executeUpdate();
log.info("Object returned from update_teammember Dao method !");
return TeamMember;
}catch(Exception e){
//System.out.println("DAOException: " + e.toString());
log.error(" Dao method (update_teammember) throws Exception : "+e.toString());
}
return null;
}
//auths not ready at this time
/**
*
*The purpose of Dao method is to perform delete operation of TeamMember noun from database based on given noun id
*@param id
*@param user
*@return the_TeamMember id deleted based on id
*@throws Exception
*/
@Transactional
public String delete_teammember(long id, DoUser user) throws Exception {
log.setLevel(Level.INFO);
log.info("delete_teammember Dao started operation!");//dhina updateverb
try{
Query query = entityManager
.createNativeQuery(delete_TeamMember)
.setParameter("id", id);
query.executeUpdate();
log.info("Object returned from delete_teammember Dao method !");
return "{\"status\":\"success\"}";
}catch(Exception e){
//System.out.println("DAOException: " + e.toString());
log.error(" Dao method (delete_teammember) throws Exception : "+e.toString());
}
return null;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.