language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Markdown
UTF-8
3,184
3.015625
3
[]
no_license
# Mean-Variance模型 ## 理论基础: 假设市场上有 n 种风险资产,资产的收益率分别为$r_1,r_2,⋯,r_n$ ,投资者在各风险资产上的配置比例分别为 $ω1,ω2,⋯,ωn$ ,则投资组合的收益率为 $rp=∑_{i=1}^{n}ω_ir_i$ ,其中 $∑_{i=1}^{n}ω_i=1$. 从而,投资组合的期望收益率为 $E(rp)=\sum\limits_{i=1}^{n}ω_iE(r_i)$ 方差为 $Var(rp) = ∑\limits_{i=1}^{n}ω_i^2Var(r_i)+∑\limits_{i≠j}ω_iω_jCov(r_i,r_j)$ 投资者资产配置的前提是对未来形成预期,即 $r_1,r_2,⋯,r_n$ 的概率分布,然后设定自己的预期收益目标, 最后确定在各风险资产的投资比例 $ω_1,ω_2,⋯,ω_n$ ,达成投资目标。 假设投资者的初始资产为 $W_0$,则未来的资产为 $W_0(1+rp)$,若投资者的效用水平仅与资产水平相关, 则效用水平 $U(rp)$ 也是一个随机变量。从最大化期望效用的角度出发,投资者决策过程就由如下公式展示: $max$ $E[U(W_0r_p)]$ $s.t ∑\limits_{i=1}^{n}ωi=1$ 上式可简化为 $ \mathop{max}\limits_{wi}\ E[U(r_p)]$ $s.t ∑\limits_{i=1}^{n}ω_i=1$ 将 $E[U(r_p)]$ 进行$Taylor$展开,可以发现,若 $r_1,r_2,⋯,r_n$ 服从正态分布, **则期望效用完全取决于投资组合收益率的均值与方差** 。再假设效用函数是凹函数,则投资者的决策问题为: $$ \mathop{min}\limits_{wi} \ Var(r_p) \\ \\ f(n) = \begin{cases} \bar r=∑\limits_{i=1}^{n}ωiE(r_p)\\ ∑\limits_{i=1}^{n}ω_i=1 \end{cases} \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ (1) $$ 求解(1)式,在既定收益率下,用优化求解算出组合方差最小的对应权重。 tips:这里只对均值/方差模型进行推演,后续出现还有最大夏普或者CVAR其他util的优化,但是原理是一致的,都是按照目标值进行参数优化得出权重。 ## 代码实现: ### 1、参数预处理:对前端传过来的参数做一次性的批量处理。 代码:py文件mv_parameter_settle中的Mv_parameter类 ### 2、计算组合在不同日期的时间,按照指定的间隔进行计算。 代码:py文件mv_model中的Mv_main_funMv_paramete类 ### 3、计算基础指标,算出不同资产收益率的基础风险指标以及协方差。 ### 4、**求解权重,主业务逻辑全部在这里,请注意**。 代码在common_function.py里面的Common_function类里,权重求解函数在solve_weights里面。 #### 1)确定可行域,要考虑各种资产的约束。(对应的三种情况:无约束,单资产约束,多资产约束) #### 2)确定优化目标方向,两种情况:[按照风险值优化,按照预期收益率优化]。 #### 3)进入拟合函数,根据收益目标方向,计算拟合和优化的值。 ### 5、得出权重后,根据前端传进来的参数进行其他处理(是否根据某些资产固定权重微调) ## 调用和测试: 1、模块有现成的入参样例。 2、调用mv_parameter_settle.py 即可进入本地调试 3、进入model之后,断点观察中间变量即可。
TypeScript
UTF-8
3,032
2.953125
3
[]
no_license
import { Handles, Rect, ResizeHandleInfo, Size } from "./mathUtils"; export class Painter{ private canvasBounds:DOMRect = null; private flags = { hasStroke: false, hasFill: false }; private mem = { x:null, y:null, w:null, h:null, r:null }; static getInstance(canvasContext:CanvasRenderingContext2D, callback?:(painter:Painter)=>void){ let p = new Painter(canvasContext); if (callback){ callback(p); p.end(); } return p; } static renderSelectorHandles(canvasContext:CanvasRenderingContext2D, selectorHandles:ResizeHandleInfo){ let p = new Painter(canvasContext); let {size,cursor,selectedHandleName,isHandleActive, ...handles} = selectorHandles; for (let [n, h] of Object.entries(handles)){ p.circle(h.x, h.y, size.w / 2).fillCircle({style: n!==selectedHandleName ? 'deepskyblue' :'deeppink' }); } p.end(); } constructor(private context:CanvasRenderingContext2D){ this.canvasBounds = this.context.canvas.getBoundingClientRect(); } rect(x:number, y:number, w:number, h:number){ this.mem = { ...this.mem, x,y,w,h }; return this; } circle(cx:number, cy:number, radius:number){ this.mem = { ...this.mem, x: cx, y: cy, r: radius }; return this; } fillCircle(opt?:{style?: string | CanvasGradient | CanvasPattern}){ if (opt?.style) this.context.fillStyle = opt.style; this.context.beginPath(); this.context.arc(this.mem.x, this.mem.y, this.mem.r, 0, 2 * Math.PI); this.context.closePath(); this.context.fill(); return this; } drawCircle(opt?:{style?: string | CanvasGradient | CanvasPattern, autoStroke?:boolean}){ if (opt?.style) this.context.strokeStyle = opt.style; this.context.beginPath(); this.context.arc(this.mem.x, this.mem.y, this.mem.r, 0, 2 * Math.PI); this.flags.hasStroke = (opt?.autoStroke !== true); if (opt?.autoStroke) this.context.stroke(); return this; } drawRect(opt?:{style?: string | CanvasGradient | CanvasPattern, autoStroke?:boolean}){ if (opt?.style) this.context.strokeStyle = opt.style; this.context.beginPath(); this.context.rect(this.mem.x, this.mem.y, this.mem.w, this.mem.h); this.flags.hasStroke = (opt?.autoStroke !== true); if (opt?.autoStroke) this.context.stroke(); return this; } fillRect(opt?:{style?: string | CanvasGradient | CanvasPattern}){ if (opt?.style) this.context.fillStyle = opt.style; this.context.fillRect(this.mem.x, this.mem.y, this.mem.w, this.mem.h); return this; } end(){ if (this.flags.hasStroke) this.context.stroke(); if (this.flags.hasFill) this.context.fill(); } }
Java
UTF-8
3,092
2.546875
3
[]
no_license
package socialgossip.server.dataproviders; import socialgossip.server.core.entities.session.Session; import socialgossip.server.core.entities.user.User; import socialgossip.server.core.gateways.session.SessionAlreadyExistsException; import socialgossip.server.core.gateways.session.SessionNotFoundException; import socialgossip.server.core.gateways.session.SessionRepository; import socialgossip.server.core.gateways.user.UserAlreadyExistsException; import socialgossip.server.core.gateways.user.UserNotFoundException; import socialgossip.server.core.gateways.user.UserRepository; import java.util.HashMap; import java.util.Objects; import java.util.Optional; public class InMemoryRepository implements UserRepository, SessionRepository { private final HashMap<String, User> userMap; private final HashMap<String, Session> sessionMap; public InMemoryRepository() { this(null, null); } InMemoryRepository(final HashMap<String, User> userMap, final HashMap<String, Session> sessionMap) { this.userMap = Optional.ofNullable(userMap).orElseGet(HashMap::new); this.sessionMap = Optional.ofNullable(sessionMap).orElseGet(HashMap::new); } @Override public void insert(final User user) throws UserAlreadyExistsException { synchronized (userMap) { Objects.requireNonNull(user); if (Objects.nonNull(userMap.putIfAbsent(user.getId(), user))){ throw new UserAlreadyExistsException(user.getId()); } } } @Override public User findByUsername(final String username) throws UserNotFoundException { synchronized (userMap) { Objects.requireNonNull(username); return Optional.ofNullable(userMap.get(username)) .orElseThrow(() -> new UserNotFoundException(username)); } } @Override public void insert(final Session session) throws SessionAlreadyExistsException { synchronized (sessionMap) { Objects.requireNonNull(session); if (Objects.nonNull(sessionMap.putIfAbsent(session.getToken(), session))) { throw new SessionAlreadyExistsException( session.getToken(), session.getUser().getId() ); } } } @Override public Session findByToken(final String token) throws SessionNotFoundException { synchronized (sessionMap) { Objects.requireNonNull(token); return Optional.ofNullable(sessionMap.get(token)) .orElseThrow(() -> new SessionNotFoundException(token)); } } @Override public void remove(final Session session) throws SessionNotFoundException { synchronized (sessionMap) { Objects.requireNonNull(session); Optional.ofNullable(sessionMap.get(session.getToken())) .map((s) -> sessionMap.remove(s.getToken())) .orElseThrow(() -> new SessionNotFoundException(session.getToken())); } } }
Python
UTF-8
1,706
3.0625
3
[ "MIT" ]
permissive
import os.path import sqlite3 import Scraper import sys def create_db(): conn = sqlite3.connect('reellog.db') c = conn.cursor() c.execute('''CREATE TABLE reellog (lure text, body text, location text, species text, level integer, weight real, class text, unique(lure, body, location, species, level, weight, class))''') conn.commit() conn.close() def sample_db_entry(): scrape_data = "'Culprit Worm', 'Amazon River', 'Baia de Santa Rosa', 'Matrincha', '6', '0.062', 'Wimpy III'" command = "INSERT INTO reellog VALUES (%s)" % scrape_data conn = sqlite3.connect('reellog.db') c = conn.cursor() c.execute(command) conn.commit() conn.close() def parse_and_store(html_file_path): conn = sqlite3.connect('reellog.db') c = conn.cursor() c.execute("SELECT COUNT(*) from reellog") (old_entry_count, ) = c.fetchone() to_write = Scraper.scrape(html_file_path) for row in to_write: command = "INSERT INTO reellog VALUES (%s)" % row try: c.execute(command) print('+ %s' % row) except sqlite3.IntegrityError: print('= %s' % row) conn.commit() c.execute("SELECT COUNT(*) from reellog") (new_entry_count,) = c.fetchone() conn.close() print("%i new entries added" % (int(new_entry_count) - int(old_entry_count))) if __name__ == '__main__': if len(sys.argv) != 2: print("Need one argument: path to html_file", file=sys.stderr) sys.exit(1) if not os.path.isfile('reellog.db'): print('No reellog.db found, creating') create_db() parse_and_store(sys.argv[1]) # sample_db_entry() print('Done')
Java
UTF-8
3,284
2.046875
2
[]
no_license
package com.questionnaire.controllers; import com.questionnaire.core.Constants; import com.questionnaire.entity.sessionentity.LoginState; import com.questionnaire.services.SessionCache; import com.questionnaire.services.UserService; import com.questionnaire.services.VkOAuthService; import com.vk.api.sdk.client.VkApiClient; import com.vk.api.sdk.client.actors.UserActor; import com.vk.api.sdk.exceptions.ApiException; import com.vk.api.sdk.exceptions.ClientException; import com.vk.api.sdk.objects.UserAuthResponse; import com.vk.api.sdk.objects.users.UserXtrCounters; import com.vk.api.sdk.queries.users.UserField; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author Igor_Strakhov */ @Controller @RequestMapping(path = "/user") public class UserController { @Autowired private VkOAuthService vkOAuthService; @Autowired private SessionCache sessionCache; @Autowired private UserService userService; @RequestMapping(path = "/authorization/user") public void getAuthentication(HttpServletRequest request, HttpServletResponse response) throws ClientException, ApiException, IOException { String code = request.getParameter("code"); VkApiClient vk = vkOAuthService.getApiClient(); UserAuthResponse authResponse = vk.oauth() .userAuthorizationCodeFlow(Integer.valueOf(Constants.ID_APPLICATION), Constants.KEY_APPLICATION, "http://localhost:8080/user/authorization/user", code) .execute(); UserActor actor = new UserActor(authResponse.getUserId(), authResponse.getAccessToken()); LoginState loginState = new LoginState(authResponse.getUserId(), authResponse.getAccessToken()); sessionCache.put(request, loginState); request.getSession().setAttribute("authenticate", true); UserXtrCounters userInfo = vk.users().get(actor).fields(UserField.SEX).execute().get(0); request.getSession().setAttribute("userName", userInfo.getLastName() + " " + userInfo.getFirstName()); userService.saveUser(userInfo); response.sendRedirect("/personalaccount"); } @RequestMapping(path = "/authorize") public void authorize(HttpServletRequest request, HttpServletResponse response) throws IOException { response.sendRedirect("https://oauth.vk.com/authorize?client_id=5761453&display=page&redirect_uri=http://localhost:8080/user/authorization/user&response_type=code&v=5.60"); } @RequestMapping(path = "/logout") public void logOut(HttpServletRequest request, HttpServletResponse response) throws IOException { request.getSession().removeAttribute("authenticate"); sessionCache.drop(request, LoginState.class); response.sendRedirect("/"); } }
Java
UTF-8
3,137
2.5
2
[]
no_license
package Control; import Modelo.Usuario; import javafx.scene.control.TextField; import java.io.IOException; import java.io.PrintWriter; import java.net.URL; import java.time.LocalDate; import java.util.ArrayList; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.DatePicker; import javafx.scene.control.PasswordField; import javax.swing.JOptionPane; /** * FXML Controller class * * @author Momo */ public class RegistrarController implements Initializable { @FXML private TextField TFnombre, TFapellido, TFcorreo; @FXML private PasswordField PFclave; @FXML private DatePicker DPnacimiento; Usuario objUsuario; ArrayList<Usuario> arrUsuario; LocalDate localdate; @FXML private void registrarUsuario(ActionEvent event) throws IOException { String idusuario = ""; String correo; String nombre; String clave; String apellido; String nacimiento; ArrayList arr; String idUsuario, correoU; nombre = TFnombre.getText(); apellido = TFapellido.getText(); correo = TFcorreo.getText(); clave = PFclave.getText(); localdate = DPnacimiento.getValue(); nacimiento = localdate.toString(); objUsuario = new Usuario(nombre, apellido, correo, clave, nacimiento, idusuario); arrUsuario.add(objUsuario); boolean insertar = false; boolean conexion; BaseDatos objbases = new BaseDatos(); try { conexion = objbases.crearConexion(); if (conexion) { insertar = objUsuario.insertarUsuario(arrUsuario); arr = objbases.buscarCorreo(correo); idUsuario = arr.get(5).toString(); correoU = arr.get(2).toString(); PrintWriter writer = new PrintWriter("src/Imagenes/usuario.txt", "UTF-8"); String User = idUsuario + "," + correoU; writer.println(User); writer.close(); } } catch (IOException e) { } if (insertar) { System.out.println("Se han insertado los usuarios correctamente"); } else { System.out.println("No se pudo insertar adecuadamente"); } arrUsuario.clear(); Picr.changeScene("CrearPerfil.fxml", event); } @FXML private void cancelar(ActionEvent event) throws IOException { Picr.changeScene("Inicio.fxml", event); } @Override public void initialize(URL url, ResourceBundle rb) { DPnacimiento.setValue(LocalDate.of(1996, 1, 1)); BaseDatos objBases = new BaseDatos(); boolean conexion; conexion = objBases.crearConexion(); if (conexion) { } else { System.out.println("no se pudo realizar la conexión"); } objUsuario = new Usuario(); arrUsuario = new ArrayList<>(); } }
Java
UTF-8
525
1.820313
2
[]
no_license
package com.consulting.core.cra.model; import lombok.*; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import java.time.Month; /** * A CRA * Created by nizaraouissaoui on 21/04/2018. */ @Entity @Getter @Setter @NoArgsConstructor @ToString @EqualsAndHashCode public class Cra { @Id @GeneratedValue private Long id; private Long year; private Month month; private Long days; private Long status; //private Contract contract; }
Java
UTF-8
3,831
1.875
2
[]
no_license
package com.alltheducks.enabler.stripes; import blackboard.admin.data.IAdminObject; import blackboard.admin.data.course.CourseSite; import blackboard.admin.persist.course.CourseSiteLoader; import blackboard.admin.persist.course.CourseSitePersister; import blackboard.admin.persist.course.impl.CourseSiteDbLoader; import blackboard.admin.persist.course.impl.CourseSiteDbPersister; import blackboard.data.ValidationException; import blackboard.db.ConstraintViolationException; import blackboard.persist.PersistenceException; import blackboard.platform.intl.BbResourceBundle; import blackboard.platform.intl.BundleManager; import blackboard.platform.intl.BundleManagerFactory; import blackboard.platform.plugin.PlugIn; import blackboard.platform.plugin.PlugInManager; import blackboard.platform.plugin.PlugInManagerFactory; import blackboard.platform.plugin.PlugInUtil; import blackboard.platform.servlet.InlineReceiptUtil; import com.alltheducks.bb.stripes.EntitlementRestrictions; import net.sourceforge.stripes.action.*; import com.alltheducks.bb.stripes.BlackboardActionBeanContext; @EntitlementRestrictions(entitlements = "atd.enabler.admin.MODIFY", errorPage = "error.jsp") public class EnablerAction implements ActionBean { private BlackboardActionBeanContext context; private boolean courseEnabled; private String batchUid; private String courseName; @DefaultHandler public Resolution displayEnabler() { return new ForwardResolution("/WEB-INF/jsp/enabler.jsp"); } public Resolution displayCourseStatus() throws PersistenceException { CourseSiteLoader courseLoader = CourseSiteDbLoader.Default.getInstance(); CourseSite cs = courseLoader.load(batchUid); IAdminObject.RowStatus status = cs.getRowStatus(); courseEnabled = status.equals(IAdminObject.RowStatus.ENABLED); courseName = cs.getTitle(); return new ForwardResolution("/WEB-INF/jsp/status.jsp"); } public Resolution saveCourseStatus() throws PersistenceException, ConstraintViolationException, ValidationException { CourseSiteLoader courseLoader = CourseSiteDbLoader.Default.getInstance(); CourseSitePersister coursePersister = CourseSiteDbPersister.Default.getInstance(); CourseSite cs = courseLoader.load(batchUid); if (courseEnabled) { cs.setRowStatus(IAdminObject.RowStatus.ENABLED); } else { cs.setRowStatus(IAdminObject.RowStatus.DISABLED); } coursePersister.save(cs); String destUrl = InlineReceiptUtil.addSuccessReceiptToUrl("Enabler.action", getMessage("enabler-app.enabler.saveStatus.success.message", cs.getTitle())); return new RedirectResolution(destUrl, false); } public boolean isCourseEnabled() { return courseEnabled; } public void setCourseEnabled(boolean courseEnabled) { this.courseEnabled = courseEnabled; } public String getBatchUid() { return batchUid; } public void setBatchUid(String batchUid) { this.batchUid = batchUid; } public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } private String getMessage(String key, String... args) { PlugInManager pluginMgr = PlugInManagerFactory.getInstance(); PlugIn plugin = pluginMgr.getPlugIn("atd", "enabler"); BundleManager bm = BundleManagerFactory.getInstance(); BbResourceBundle bundle = bm.getPluginBundle(plugin.getId()); return bundle.getString(key, args); } public ActionBeanContext getContext() { return context; } public void setContext(ActionBeanContext context) { this.context = (BlackboardActionBeanContext)context; } }
Java
UTF-8
1,585
2.421875
2
[]
no_license
package ver0.village.WritingUpload; import android.content.Context; import android.graphics.BitmapFactory; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import androidx.recyclerview.widget.RecyclerView; import com.esafirm.imagepicker.model.Image; import java.util.List; import ver0.village.R; public class WritingItemPhotoAdapter extends RecyclerView.Adapter<WritingItemPhotoAdapter.ViewHolder> { private List<Image> itemList; private Context context; private View.OnClickListener onClickItem; public WritingItemPhotoAdapter(Context context, List<Image> itemList) { this.context = context; this.itemList = itemList; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // context 와 parent.getContext() 는 같다. View view = LayoutInflater.from(context) .inflate(R.layout.writing_item_picture, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.imageView.setImageBitmap(BitmapFactory.decodeFile(itemList.get(position).getPath())); } @Override public int getItemCount() { return itemList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { public ImageView imageView; public ViewHolder(View itemView) { super(itemView); imageView = itemView.findViewById(R.id.itemimg); } } }
Python
UTF-8
479
3.53125
4
[ "Apache-2.0" ]
permissive
#coding=utf-8 import parent class SonClass(parent.ParentClass):#继承父类,这里一定要写模块名.类名 ''' 在继承中基类的构造(__init__()方法) 不会被自动调用,它需要在其派生类的构造中亲自专门调用 ''' def __init__(self,name): self.name=name print "son is inited" def sum(self,a,b): print a+b if(__name__ == "__main__"): s=SonClass("son") s.sum(10,2)
Java
UTF-8
2,835
2.6875
3
[]
no_license
package edu.andrazpencelj.parkinginljubljana; import android.util.Log; /** * Created by Andraž on 18.11.2013. * * parkirišče * * mId - id parkirišča * mName - ime parkirišča * mCapacity - kapaciteta parkirišča * mDisabledPersonCapacity - število mest namenjenih invalidom * * mLocation - lokacija parkirišča * mOccupancy - zasedenost parkirišča */ public class ParkingLot { private int mId; private String mName; private int mCapacity; private int mOccupancy; private int mDisabledPersonCapacity; private ParkingLotLocation mLocation; private String mOpen; private String mPrice; public ParkingLot(){ } public ParkingLot(int id, String name, int capacity, int disabledPersonCapacity, String open, String price){ this.mId = id; this.mCapacity = capacity; this.mDisabledPersonCapacity = disabledPersonCapacity; this.mName = name; this.mOpen = open; this.mPrice = price; } public ParkingLot(int id, String name, int capacity, int disabledPersonCapacity, String open, String price, ParkingLotLocation location, int occupancy){ this.mId = id; this.mCapacity = capacity; this.mDisabledPersonCapacity = disabledPersonCapacity; this.mName = name; this.mOpen = open; this.mPrice = price; this.mLocation = location; this.mOccupancy = occupancy; } public void setId(int id){ this.mId = id; } public void setName(String name){ this.mName = name; } public void setCapacity(int capacity){ this.mCapacity = capacity; } public void setDisabledPersonCapacity(int capacity){ this.mDisabledPersonCapacity = capacity; } public void setOpen(String open){ this.mOpen = open; } public void setPrice(String price){ this.mPrice = price; } public void setLocation(ParkingLotLocation location){ this.mLocation = location; } public void setOccupancy(int occupancy){ this.mOccupancy = occupancy; } public int getId(){ return this.mId; } public String getName(){ return this.mName; } public int getCapacity(){ return this.mCapacity; } public int getDisabledPersonCapacity(){ return this.mDisabledPersonCapacity; } public String getOpen(){ return this.mOpen; } public String getPrice(){ return this.mPrice; } public ParkingLotLocation getLocation(){ return this.mLocation; } public int getOccupancy(){ return this.mOccupancy; } public double getLatitude(){ return this.mLocation.getLatitude(); } public double getLongitude(){ return this.mLocation.getLongitude(); } }
Java
UTF-8
3,619
2.203125
2
[]
no_license
package com.nkhoang.gae.utils; import com.nkhoang.gae.model.Word; import com.nkhoang.gae.service.LookupService; import com.nkhoang.gae.utils.web.DownloadUtils; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"/applicationContext-service.xml", "/applicationContext-dao.xml", "/applicationContext-resources.xml"}) public class DownloadUtilsTest { private static final int THREAD_POOL_QUEUE_SIZE = 60; private static final int THREAD_POOL_KEEP_ALIVE_TIME = 0; private static final int THREAD_POOL_MAX_SIZE = 15; private static final int THREAD_POOL_CORE_SIZE = 15; private static final Logger LOG = LoggerFactory .getLogger(DownloadUtilsTest.class.getCanonicalName()); private static ExecutorService _executor = new ThreadPoolExecutor( THREAD_POOL_CORE_SIZE, THREAD_POOL_MAX_SIZE, THREAD_POOL_KEEP_ALIVE_TIME, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(THREAD_POOL_QUEUE_SIZE), new ThreadPoolExecutor.CallerRunsPolicy()); @Autowired private LookupService cambridgeLookupService; @Test public void testDownloadFile() { DownloadUtils.fileDownload("http://dictionary.cambridge.org/media/british/us_pron/c/com/come_/come.mp3", "abc", "sound/english/"); } @Test public void testGetCosmicBook() { DownloadUtils.getCosmicBook("http://vechai.info/Tam-tan-ky/", "/Users/nkhoangit/Downloads/TamTanKy/"); } @Test public void startDownloadThread() { List<String> wordList = com.nkhoang.common.FileUtils.readWordsFromFile("lucene/src/main/resources/fullList.txt"); int index = 13000; int size = 4000; if (CollectionUtils.isNotEmpty(wordList)) { LOG.info("Total words found: " + wordList.size()); for (int i = index; i < index + size; i++) { String word = wordList.get(i); _executor.submit(new DownloadWordTask(word)); LOG.info("index: " + i); } } } class DownloadWordTask implements Runnable { private String _word; public DownloadWordTask(String word) { _word = word; } public void run() { Word w = cambridgeLookupService.lookup(_word); if (StringUtils.isNotEmpty(w.getDescription()) && StringUtils.isNotEmpty(w.getSoundSource())) { String downloadUrl = w.getSoundSource().trim(); downloadUrl = downloadUrl.replaceAll("playSoundFromFlash\\(\\'", ""); downloadUrl = downloadUrl.replaceAll("\\', this\\)", ""); downloadUrl = downloadUrl.trim(); DownloadUtils.fileDownload(downloadUrl, w.getDescription(), "sound/english/"); } } } public void setCambridgeLookupService(LookupService cambridgeLookupService) { this.cambridgeLookupService = cambridgeLookupService; } }
Python
UTF-8
971
2.78125
3
[]
no_license
import os import requests import datetime from dotenv import load_dotenv load_dotenv() def info_about_user(target_id: str): ACCESS_TOKEN = os.getenv('VK_ACCESS_TOKEN') API_VERSION = '5.124' URL = f'https://api.vk.com/method/users.get?user_ids={target_id}&fields=online,last_seen' \ f'&access_token={ACCESS_TOKEN}&v={API_VERSION}' response = requests.request('GET', URL) try: target_name = response.json()['response'][0]['first_name'] + ' ' + response.json()['response'][0]['last_name'] target_status = 'online' if response.json()['response'][0]['online'] else 'offline' target_last_seen = response.json()['response'][0]['last_seen']['time'] date_time = datetime.datetime.fromtimestamp(target_last_seen) time = date_time.strftime('%H:%M:%S') return target_name, target_status, time except KeyError: return 'Invalid user ID or something wrong.'
Ruby
UTF-8
1,104
3
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class VentureCapitalist attr_accessor :name, :total_worth @@all = [] def initialize(name, total_worth) @name = name @total_worth = total_worth @@all << self end def offer_contract(startup, type, investment) FundingRound.new(startup, self, type, investment) end def funding_rounds FundingRound.all.select {|fr| fr.venture_capitalist == self} end def portfolio funding_rounds.map {|fr| fr.startup}.uniq end def biggest_investment biggest_investment = 0.0 funding_rounds.each do |fr| if fr.investment > biggest_investment biggest_investment = fr.investment end end biggest_investment end def invested(domain) invested_domains = funding_rounds.select {|fr| fr.startup.domain == domain} investments = invested_domains.map {|fr| fr.investment} investments.sum end def self.tres_commas_club all.select {|vc| vc.total_worth > 1000000000 } end def self.all @@all end end
Ruby
UTF-8
566
3.140625
3
[]
no_license
require 'singleton' # Components to use require 'comp1' require 'comp2' class Module def component(id,klass) module_eval <<-"end_eval" def init puts "init: id=#{id}, class=#{klass}" @#{id.id2name} = #{klass}.new end #~ self.init end_eval end end class MMContainer include Singleton def initialize @ch = Hash.new end def add(c) #~ @ch[] @#{id.id2name} = #{klass}.new end def get end def start end end #~ mc = MMContainer.instance #~ mc.add(Comp1) #~ mc.add(Comp2) #~ mc.start
Java
UTF-8
1,818
2.078125
2
[]
no_license
package kafka; import java.util.UUID; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.event.SpringApplicationEvent; import org.springframework.cloud.stream.annotation.EnableBinding; import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import kafka.producer.Consumer; import kafka.producer.Producer; import kafka.producer.QueueIn; @EnableBinding({ QueueIn.class }) @SpringBootApplication(scanBasePackages = "kafka.producer") @Configuration public class AppConsumer implements ApplicationListener<SpringApplicationEvent> { public static Producer producer; public static String serverId; static int kcount = 10; static int icount = 100; // @Autowired public void setProducer(Producer producer) { AppConsumer.producer = producer; } public static void main(String[] args) { // kcount = Integer.parseInt(args[0]); // icount = Integer.parseInt(args[1]); serverId = UUID.randomUUID().toString(); SpringApplication.run(AppConsumer.class, args); } @Bean public Consumer consumer() { return new Consumer(); } // @Bean public Producer producer() { return new Producer(); } public void onApplicationEvent(SpringApplicationEvent arg0) { // SpringApplication sa = (SpringApplication) arg0.getSource(); // Iterator<?> i = sa.getSources().iterator(); // if (i.hasNext() && i.next().equals(AppConsumer.class)) { // List<T> tl = new ArrayList<T>(); // for (int k = 0; k < kcount; k++) { // T t = new T(k, icount); // tl.add(t); // } // for (T t : tl) { // t.start(); // } // } } }
Java
UTF-8
2,913
2.046875
2
[]
no_license
package ru.aplana.renessains.pages; import org.junit.Assert; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.ui.Select; import java.util.List; public class DepositPage extends IndexPage { @FindBy(xpath = "//input[@name = 'replenish']") private WebElement inputMonthPayment; @FindBy(xpath = "//span[text() = 'Ежемесячная капитализация']") private WebElement everyMonthCheckbox; @FindBy(xpath = "//span[text() = 'Частичное снятие']") private WebElement PartWithdrowalCheckbox; @FindBy(xpath = "//select") private WebElement selectTerm; @FindBy(xpath = "//input[@name = 'amount']") private WebElement inputAmount; @FindBy(xpath = "//div[@class = 'calculator__currency-content']//input") private List<WebElement> currencyList; @FindBy(xpath = "//span[@class = 'js-calc-rate']") private WebElement checkRate; @FindBy(xpath = "//span[@class = 'js-calc-earned']") private WebElement checkWithdrawal; @FindBy(xpath = "//span[@class = 'js-calc-replenish']") private WebElement checkInvestment; @FindBy(xpath = "//span[@class = 'js-calc-result']") private WebElement checkAccured; public void chooseCurrency(String currency) { for (WebElement element: currencyList) { if (currency.equalsIgnoreCase(element.findElement(By.xpath("./following::span[contains(@class, 'currency-field-text')]")).getText())){ waitElementandClick(element.findElement(By.xpath("./following::span[contains(@class, 'currency-field-text')]"))); return; } } Assert.fail("No such currency."); } public void setDeposit(int sum) { waitElementandClick(inputAmount); inputAmount.sendKeys(String.valueOf(sum)); } public void setTerm(String months) { new Select(selectTerm).selectByVisibleText(months + " месяцев"); } public void setMonthPayment(int sum) { waitElementandClick(inputMonthPayment); inputMonthPayment.sendKeys(Keys.BACK_SPACE); new Actions(driver).pause(500).build().perform(); inputMonthPayment.sendKeys(String.valueOf(sum)); } public void clickCapital() { waitElementandClick(everyMonthCheckbox); } public String getRate() { return checkRate.getText(); } public String getWithdrawal() { return checkWithdrawal.getText(); } public String getInvestment() { return checkInvestment.getText(); } public String getAccured() { return checkAccured.getText(); } public void tickPartWithdrowalCheckbox() { waitElementandClick(PartWithdrowalCheckbox); } }
Java
UTF-8
1,736
2.890625
3
[]
no_license
package com.example.bookapp; import java.text.DecimalFormat; public class Book { private int id; public int getId() { return id; } public void setId(int id) { this.id = id; } private int imgRes; private String title,author,description; private double price; public Book(int imgRes, String title, String author, String description, double price) { this.imgRes = imgRes; this.title = title; this.author = author; this.description = description; this.price = price; } public Book(int id, int imgRes, String title, String author, String description, double price) { this.id = id; this.imgRes = imgRes; this.title = title; this.author = author; this.description = description; this.price = price; } public int getImgRes() { return imgRes; } public String getTitle() { return title; } public String getAuthor() { return author; } public String getDescription() { return description; } public double getPrice() { return price; } public String getStringPrice() { DecimalFormat decimalFormat = new DecimalFormat("0.00 р"); return decimalFormat.format(price); } public void setImgRes(int imgRes) { this.imgRes = imgRes; } public void setTitle(String title) { this.title = title; } public void setAuthor(String author) { this.author = author; } public void setDescription(String description) { this.description = description; } public void setPrice(double price) { this.price = price; } }
PHP
UTF-8
556
3.078125
3
[]
no_license
<?php class Connection { private $servername = "localhost"; private $username = "root"; private $password = "root"; private $dbname = "licenta"; private $conn; private static $instance = null; public function __construct() { } public function getConnection(){ return new mysqli($this->servername, $this->username, $this->password, $this->dbname); } public static function getInstance() { if (!isset(static::$instance)) { static::$instance = new static; } return static::$instance; } }
PHP
UTF-8
9,894
2.671875
3
[]
no_license
<?php /** * @package phpunk\component */ namespace PHPunk\Component; use PHPunk\cache; use PHPunk\url_schema; use PHPunk\Database\schema as db_schema; /** * @property object $database Single database schema instance * @property object $router Single url schema instance * @property object $cache Single cache instance * @property object $model Default model instance * @property object $controller Default controller instance * @property object $renderer Default renderer instance */ class application { /** * @ignore internal variable */ private $_database; /** * @ignore internal variable */ private $_database_conn; /** * @ignore internal variable */ private $_database_meta; /** * @ignore internal variable */ private $_router; /** * @ignore internal variable */ private $_router_host; /** * @ignore internal variable */ private $_router_meta; /** * @ignore internal variable */ private $_cache; /** * @ignore internal variable */ private $_cache_server; /** * @ignore internal variable */ private $_default_model; /** * @ignore internal variable */ private $_default_controller; /** * @ignore internal variable */ private $_default_renderer; /** * @ignore internal variable */ private $_models = []; /** * @ignore internal variable */ private $_controllers = []; /** * @ignore internal variable */ private $_renderers = []; /** * @ignore magic method */ public function __get($key) { switch ($key) { case 'database': return $this->load_database(); case 'router': return $this->load_router(); case 'cache': return $this->load_cache(); case 'model': return $this->load_model(); case 'controller': return $this->load_controller(); case 'renderer': return $this->load_renderer(); } } /** * @ignore magic method */ public function __call($func, $args) { if (count($args) == 1) { $resource = $args[0]; switch ($func) { case 'model': return $this->load_model($resource); case 'controller': return $this->load_controller($resource); case 'renderer': return $this->load_renderer($resource); } } $class = get_class($this); trigger_error("Call to undefined method $class::$func()", E_USER_WARNING); } /** * Initializes database connection and table structures. An E_USER_ERROR * error will be triggered if the database is inaccessible. * @param object $config Traversable object containing DB credentials * @param object $meta Traversable object containing table structures */ public function init_database($config, $meta) { if (is_null($this->_database_conn)) { $this->_database_conn = new \mysqli( $config->hostname, $config->username, $config->password ); if ($this->_database_conn->connect_errno) { trigger_error($this->_database_conn->connect_error, E_USER_ERROR); return false; } $this->_database_conn->set_charset('utf8'); $query = "SHOW DATABASES LIKE '$config->database'"; if ($result = $this->_database_conn->query($query)) { if (0 == $result->num_rows) { $query = "CREATE DATABASE `$config->database`"; if (!$this->_database_conn->query($query)) { trigger_error($this->_database_conn->error, E_USER_ERROR); return false; } } $result->close(); } $this->_database_conn->select_db($config->database); $this->_database_meta = $meta; } } /** * Lazy-loads a database schema instance, using the previously-initialized * database connection and table structures. An E_USER_ERROR error will be * triggered if the database connection has not yet been initialized. * @return object The database schema object */ public function load_database() { if (is_null($this->_database)) { if (!($connection = $this->_database_conn)) { trigger_error("No database connection", E_USER_ERROR); return false; } $this->_database = new db_schema($connection); foreach ($this->_database_meta as $table_name => $table_meta) { $this->_database->add_table($table_name, @$table_meta->pkey); if (isset($table_meta->relations)) { foreach ($table_meta->relations as $rel_name => $rel_meta) { $rel_meta->ftable = $table_name; $this->_database->add_relation( $rel_name, $rel_meta->ptable, $rel_meta->ftable, $rel_meta->fkey ); } } } } return $this->_database; } /** * Initializes host and metadata for url schema. * @param string $host Hostname for url schema * @param object $meta Traversable object containing url structures */ public function init_router($host, $meta) { $this->_router_host = $host; $this->_router_meta = $meta; } /** * Lazy-loads a url schema instance, using the previously-initialized host * and metadata. * @return object The url schema object */ public function load_router() { if (is_null($this->_router)) { $this->_router = new url_schema($this->_router_host); foreach ($this->_router_meta as $res_name => $res_meta) { if ('<global>' == $res_name) $res_name = false; else $this->_router->add_resource($res_name); $aliases = @$res_meta->aliases ?: []; $actions = @$res_meta->actions ?: []; $views = @$res_meta->views ?: []; foreach ($aliases as $alias) $this->_router->add_alias($alias, $res_name); foreach ($actions as $action) $this->_router->add_action($action, $res_name); foreach ($views as $view) $this->_router->add_view($view, $res_name); } } return $this->_router; } /** * Initializes caching server connection. * @param object Traversable object containing host and port for server */ public function init_cache($config) { if (is_null($this->_cache_server)) { switch (strtolower($config->driver)) { case 'memcached': $this->_cache_server = new Memcached(); break; case 'memcache': default: $this->_cache_server = new Memcache(); break; } $this->_cache_server->addServer($config->host, $config->port); } } /** * Lazy-loads a cache instance, using the previously-initialized connection. * If server is not initalized, cache object will only use in-memory data. * @return object The cache object */ public function load_cache() { if (is_null($this->_cache)) { $this->_cache = new cache($this->_cache_server); } return $this->_cache; } /** * Lazy-loads a model object for the specified resource, if given. * @param string $resource OPTIONAL resource name * @return object A model object */ public function load_model($resource = false) { if ($resource) { if (!isset($this->_models[$resource])) { $this->_models[$resource] = $this->create_model($resource); } return $this->_models[$resource]; } else { if (is_null($this->_default_model)) $this->_default_model = $this->create_model(); return $this->_default_model; } } /** * Lazy-loads a controller object for the specified resource, if given. * @param string $resource OPTIONAL resource name * @return object A controller object */ public function load_controller($resource = false) { if ($resource) { if (!isset($this->_controllers[$resource])) $this->_controllers[$resource] = $this->create_controller($resource); return $this->_controllers[$resource]; } else { if (is_null($this->_default_controller)) $this->_default_controller = $this->create_controller(); return $this->_default_controller; } } /** * Lazy-loads a renderer object for the specified resource, if given. * @param string $resource OPTIONAL resource name * @return object A renderer object */ public function load_renderer($resource = false) { if ($resource) { if (!isset($this->_renderers[$resource])) $this->_renderers[$resource] = $this->create_renderer($resource); return $this->_renderers[$resource]; } else { if (is_null($this->_default_renderer)) $this->_default_renderer = $this->create_renderer(); return $this->_default_renderer; } } /** * Constructs a model object for the specified resource. An E_USER_ERROR is * triggered if the database connection has not yet been initialized. * This method is intended to be extensible for child classes. * @param string $resource OPTIONAL resource name * @return object A model object */ protected function create_model($resource = false) { if (!($database = $this->database)) { trigger_error("No default database", E_USER_ERROR); return false; } if ($resource) { $class = "{$resource}_model"; if (class_exists($class)) return new $class($database, $this->cache); } return new model($resource, $database, $this->cache); } /** * Constructs a controller object for the specified resource. An E_USER_ERROR * is triggered if the database connection has not yet been initialized. * This method is intended to be extensible for child classes. * @param string $resource OPTIONAL resource name * @return object A controller object */ protected function create_controller($resource = false) { $model = $this->load_model($resource); if ($resource) { $class = "{$resource}_controller"; if (class_exists($class)) return new $class($model); } return new controller($model); } /** * Constructs a renderer object for the specified resource. An E_USER_ERROR * is triggered if the database connection has not yet been initialized. * This method is intended to be extensible for child classes. * @param string $resource OPTIONAL resource name * @return object A renderer object */ protected function create_renderer($resource = false) { if ($resource) { $class = "{$resource}_renderer"; if (class_exists($class)) return new $class(); } return new renderer($resource); } }
PHP
UTF-8
11,379
2.578125
3
[]
no_license
<?php /** * 特别处理 * 动态字段/PHP栏目功能处理 */ /* 创建类别数据表语句 */ $alone_table_sql = " CREATE TABLE IF NOT EXISTS `__TABLE_NAME__` ( `id` int(11) NOT NULL auto_increment, `cn_type` varchar(200) collate utf8_general_ci NULL default '', `en_type` varchar(200) collate utf8_general_ci NULL default '', `cn_title` varchar(200) collate utf8_general_ci NULL default '', `en_title` varchar(200) collate utf8_general_ci NULL default '', `cn_keywords` varchar(200) collate utf8_general_ci NULL default '', `en_keywords` varchar(200) collate utf8_general_ci NULL default '', `cn_description` longtext collate utf8_general_ci NULL, `en_description` longtext collate utf8_general_ci NULL, `num` int(11) default '0', `type_id` int(11) default '__TYPE_ID__', `admin_id` int(11) DEFAULT '1', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci AUTO_INCREMENT=".($id+1)."; "; /** * 类别处理 */ $table_name = 'atype'; /* 建立独立数据表 */ if($_REQUEST['cc']['class_alone_table_name']){ $table_name = $_REQUEST['cc']['class_alone_table_name']; if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '{$_REQUEST['cc']['class_alone_table_name']}'"))<1){ mysql_query( str_replace( array('__TABLE_NAME__','__TYPE_ID__'), array($_REQUEST['cc']['class_alone_table_name'],$id), $alone_table_sql ) ) or die('Create Class Alone Table: '.mysql_error()); } } /* 表扩展字段处理 */ if(isset($_REQUEST['cc']['class_extend_field'])){ $atype_fields = array(); $fields = mysql_list_fields($mysql_db, $table_name); $columns = mysql_num_fields($fields); for ($i = 0; $i < $columns; $i++) { $fields_name = mysql_field_name($fields, $i); $atype_fields[$fields_name] = array( 'name'=>$fields_name, 'type'=>mysql_field_type($fields, $i), 'len'=>mysql_field_len($fields, $i), 'flags'=>mysql_field_flags($fields, $i) ); } foreach($_REQUEST['cc']['class_extend_field'] as $field_info){ if(empty($field_info['field'])) continue; //构建SQL语句 $field_type_sql = ''; $index_sql = ''; $field_defval_sql = ''; get_extend_field_csql($table_name, $field_info); if(isset($atype_fields[$field_info['field']])){ if( (in_array($atype_fields[$field_info['field']]['type'], array('string','datetime')) && !in_array($field_info['type'],array('string','int','password','password_md5','img','select','radio','checkbox'))) || (in_array($atype_fields[$field_info['field']]['type'], array('int')) && !in_array($field_info['type'],array('int'))) || (in_array($atype_fields[$field_info['field']]['type'], array('blob')) && !in_array($field_info['type'],array('text','rtext'))) ){ show_msg("字段 '{$field_info['field']}' 已存在!\\n当前类型为: {$atype_fields[$field_info['field']]['type']}\\n请更换字段类型或者字段名称。"); } if(!mysql_query("ALTER TABLE `{$table_name}` CHANGE `{$field_info['field']}` `{$field_info['field']}` {$field_type_sql} {$field_defval_sql} COMMENT '{$field_info['title']}'")){ show_msg("类别字段 '{$field_info['field']}' 修改失败!\n".mysql_error()); } }else{ if(!mysql_query("ALTER TABLE `{$table_name}` ADD `{$field_info['field']}` {$field_type_sql} {$field_defval_sql} COMMENT '{$field_info['title']}'")){ show_msg("类别字段 '{$field_info['field']}' 添加失败!\n".mysql_error()); } if($index_sql) mysql_query($index_sql); } } } /* 创建类别数据表语句 */ $alone_table_sql = " CREATE TABLE IF NOT EXISTS `__TABLE_NAME__` ( `id` int(11) NOT NULL auto_increment, `type_id` int(11) default '__TYPE_ID__', `num` int(11) default '0', `cn_name` varchar(200) collate utf8_general_ci NULL default '', `en_name` varchar(200) collate utf8_general_ci NULL default '', `cn_title` varchar(200) collate utf8_general_ci NULL default '', `en_title` varchar(200) collate utf8_general_ci NULL default '', `cn_keywords` varchar(200) collate utf8_general_ci NULL default '', `en_keywords` varchar(200) collate utf8_general_ci NULL default '', `cn_description` longtext collate utf8_general_ci NULL, `en_description` longtext collate utf8_general_ci NULL, `images1` varchar(200) collate utf8_general_ci NULL default '', `images2` varchar(200) collate utf8_general_ci NULL default '', `cn_content` longtext collate utf8_general_ci NULL, `en_content` longtext collate utf8_general_ci NULL, `date1` datetime default '0000-00-00 00:00:00', `hot1` int(11) default '0', `admin_id` int(11) DEFAULT '1', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci AUTO_INCREMENT=1 ; "; /** * 信息处理 */ $table_name = 'atype_info'; /* 建立独立数据表 */ if(!empty($_REQUEST['cc']['info_alone_table_name'])){ $table_name = $_REQUEST['cc']['info_alone_table_name']; if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '{$_REQUEST['cc']['info_alone_table_name']}'"))<1){ mysql_query( str_replace( array('__TABLE_NAME__','__TYPE_ID__'), array($_REQUEST['cc']['info_alone_table_name'],$id), $alone_table_sql ) ) or die('Create Info Alone Table: '.mysql_error()); } } /* 表扩展字段处理 */ if(isset($_REQUEST['cc']['info_extend_field'])){ $atype_info_fields = array(); $fields = mysql_list_fields($mysql_db, $table_name); $columns = mysql_num_fields($fields); for ($i = 0; $i < $columns; $i++) { $fields_name = mysql_field_name($fields, $i); $atype_info_fields[$fields_name] = array( 'name'=>$fields_name, 'type'=>mysql_field_type($fields, $i), 'len'=>mysql_field_len($fields, $i), 'flags'=>mysql_field_flags($fields, $i) ); } foreach($_REQUEST['cc']['info_extend_field'] as $field_info){ if(empty($field_info['field'])) continue; //构建SQL语句 $field_type_sql = ''; $index_sql = ''; $field_defval_sql = ''; get_extend_field_csql($table_name, $field_info); if(isset($atype_info_fields[$field_info['field']])){ if( (in_array($atype_info_fields[$field_info['field']]['type'], array('string','datetime')) && !in_array($field_info['type'],array('string','int','password','password_md5','img','select','radio','checkbox'))) || (in_array($atype_info_fields[$field_info['field']]['type'], array('int')) && !in_array($field_info['type'],array('int'))) || (in_array($atype_info_fields[$field_info['field']]['type'], array('blob')) && !in_array($field_info['type'],array('text','rtext'))) ){ show_msg("字段 '{$field_info['field']}' 已存在!\\n当前类型为: {$atype_info_fields[$field_info['field']]['type']}\\n请更换字段类型或者字段名称。"); } if(!mysql_query("ALTER TABLE `{$table_name}` CHANGE `{$field_info['field']}` `{$field_info['field']}` {$field_type_sql} {$field_defval_sql} COMMENT '{$field_info['title']}'")){ show_msg("信息字段 '{$field_info['field']}' 修改失败!\n".mysql_error()); } }else{ if(!mysql_query("ALTER TABLE `{$table_name}` ADD `{$field_info['field']}` {$field_type_sql} {$field_defval_sql} COMMENT '{$field_info['title']}'")){ show_msg("信息字段 '{$field_info['field']}' 添加失败!\n".mysql_error()); } if($index_sql) mysql_query($index_sql); } } } /* 自定义菜单内容处理 */ if(is_array($_REQUEST['cc']['custom_menu'])){ foreach($_REQUEST['cc']['custom_menu'] as $_key=>$_val){ //先清除原有设置 @unlink(CC_SAVE_PATH.($cc_info['class_alone_table_name']?"{$cc_info['class_alone_table_name']}_":'').'custom_menu_'.$_key.'_'.$id.'.php'); if($_REQUEST['cc']['custom_menu'][$_key]['content'] && $_REQUEST['cc']['custom_menu'][$_key]['type']=='php'){ file_put_contents(CC_SAVE_PATH.($cc_info['class_alone_table_name']?"{$cc_info['class_alone_table_name']}_":'').'custom_menu_'.$_key.'_'.$id.'.php', "<?php\n".$_REQUEST['cc']['custom_menu'][$_key]['content']); } } } /* 类别,信息列表栏目处理 */ /* 先清除之前已设置类别,信息列表栏目PHP功能 */ $class_file_head = ($cc_info['class_alone_table_name']?"{$cc_info['class_alone_table_name']}_":'').'class_extend_column_'.$id.'_'; $class_file_head_len = strlen($class_file_head); $info_file_head = ($cc_info['class_alone_table_name']?"{$cc_info['class_alone_table_name']}_":'').'info_extend_column_'.$id.'_'; $info_file_head_len = strlen($info_file_head); $dh = opendir(CC_SAVE_PATH); while($fn = readdir($dh)){ if(substr($fn,0,$class_file_head_len)==$class_file_head || substr($fn,0,$info_file_head_len)==$info_file_head){ @unlink(CC_SAVE_PATH.$fn); } } closedir($dh); /* 重新生成类别列表栏目PHP文件 */ if(isset($_REQUEST['cc']['class_extend_column'])){ foreach($_REQUEST['cc']['class_extend_column'] as $extend_column_info){ if($extend_column_info['type']=='php'){ file_put_contents(CC_SAVE_PATH.($cc_info['class_alone_table_name']?"{$cc_info['class_alone_table_name']}_":'').'class_extend_column_'.($type?($type.'_'):'').$id.'_'.create_extend_column_mark($extend_column_info['title']).'.php', "<?php\n".$extend_column_info['content']); } } } /* 重新生成信息列表栏目PHP文件 */ if(isset($_REQUEST['cc']['info_extend_column'])){ foreach($_REQUEST['cc']['info_extend_column'] as $extend_column_info){ if($extend_column_info['type']=='php'){ file_put_contents(CC_SAVE_PATH.($cc_info['class_alone_table_name']?"{$cc_info['class_alone_table_name']}_":'').'info_extend_column_'.$id.'_'.create_extend_column_mark($extend_column_info['title']).'.php', "<?php\n".$extend_column_info['content']); } } } /* 自定义扩展脚本处理 */ //类别扩展脚本 if($_REQUEST['cc']['class_script']){ foreach($_REQUEST['cc']['class_script'] as $_key=>$_val){ //先清除原有设置 @unlink(CC_SAVE_PATH.($cc_info['class_alone_table_name']?"{$cc_info['class_alone_table_name']}_":'').'class_script_'.$_key.'_'.$id.'.php'); if($_REQUEST['cc']['class_script'][$_key]['content']){ file_put_contents(CC_SAVE_PATH.($cc_info['class_alone_table_name']?"{$cc_info['class_alone_table_name']}_":'').'class_script_'.$_key.'_'.$id.'.php', "<?php\n".$_REQUEST['cc']['class_script'][$_key]['content']); } } } //信息扩展脚本 if($_REQUEST['cc']['info_script']){ foreach($_REQUEST['cc']['info_script'] as $_key=>$_val){ //先清除原有设置 @unlink(CC_SAVE_PATH.($cc_info['class_alone_table_name']?"{$cc_info['class_alone_table_name']}_":'').'info_script_'.$_key.'_'.$id.'.php'); if($_REQUEST['cc']['info_script'][$_key]['content']){ file_put_contents(CC_SAVE_PATH.($cc_info['class_alone_table_name']?"{$cc_info['class_alone_table_name']}_":'').'info_script_'.$_key.'_'.$id.'.php', "<?php\n".$_REQUEST['cc']['info_script'][$_key]['content']); } } } //更新菜单 $conf_showmenu = is_file(CC_SAVE_PATH.'conf_showmenu.ccset')?unserialize(file_get_contents(CC_SAVE_PATH.'conf_showmenu.ccset')):array(); unset($conf_showmenu[$id]); if($_REQUEST['cc']['menu']['class_show']['status']=='show'){ $conf_showmenu[$id] = $id; } if(!empty($conf_showmenu)){ $query = mysql_query("SELECT * FROM `atype` WHERE `id` IN ('".implode("','", $conf_showmenu)."') ORDER BY `num` ASC"); $conf_showmenu = array(); while($_info = mysql_fetch_assoc($query)){ $conf_showmenu[$_info['id']]=$_info['id']; } } file_put_contents(CC_SAVE_PATH.'conf_showmenu.ccset', serialize($conf_showmenu)); //整理自定义字段内容 include dirname(__FILE__).'/ccupdate.php';
JavaScript
UTF-8
546
3.53125
4
[]
no_license
var word = 'OCNP'; var checker = '.'.repeat(word.length); var text = ''; for (var i = 0; i < 1000; i++) { var ch = word.charAt(Math.floor(Math.random() * word.length)); text = text + '&nbsp;' + ch; checker = checker.substr(1) + ch; console.log(checker); setTimeout("document.getElementById('ochinpo').innerHTML = '" + text + "'", 100 * i); if (checker == word) { text = text + "<br>[" + i + "]"; setTimeout("document.getElementById('ochinpo').innerHTML = '" + text + "'", 100 * i); break; } }
TypeScript
UTF-8
1,205
4.15625
4
[]
no_license
/* https://leetcode.com/problems/sum-of-all-odd-length-subarrays/ Given an array of positive integers arr, calculate the sum of all possible odd-length subarrays. A subarray is a contiguous subsequence of the array. Return the sum of all odd-length subarrays of arr. Example 1: Input: arr = [1,4,2,5,3] Output: 58 Explanation: The odd-length subarrays of arr and their sums are: [1] = 1 [4] = 4 [2] = 2 [5] = 5 [3] = 3 [1,4,2] = 7 [4,2,5] = 11 [2,5,3] = 10 [1,4,2,5,3] = 15 If we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58 Example 2: Input: arr = [1,2] Output: 3 Explanation: There are only 2 subarrays of odd length, [1] and [2]. Their sum is 3. Example 3: Input: arr = [10,11,12] Output: 66 Constraints: 1 <= arr.length <= 100 1 <= arr[i] <= 1000 * */ /** * @param {number[]} arr * @return {number} */ var sumOddLengthSubarrays = function(arr) { let sum = 0; let length = 1; while (length<=arr.length){ for (let i=0;(i+length)<=arr.length;i++){ for (let j=i;j<(i+length);j++){ sum+=arr[j]; } } length+=2; } return sum; }; export default sumOddLengthSubarrays;
C#
UTF-8
2,657
2.671875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using DemoIdentity.Data; using DemoIdentity.Models; namespace DemoIdentity.ControllersApi { [Route("api/[controller]")] [ApiController] public class PressesController : ControllerBase { private readonly ApplicationDbContext _context; public PressesController(ApplicationDbContext context) { _context = context; } // GET: api/Presses [HttpGet] public async Task<ActionResult<IEnumerable<Press>>> GetPress() { return await _context.Press.ToListAsync(); } // GET: api/Presses/5 [HttpGet("{id}")] public async Task<ActionResult<Press>> GetPress(int id) { var press = await _context.Press.FindAsync(id); if (press == null) { return NotFound(); } return press; } // PUT: api/Presses/5 [HttpPut("{id}")] public async Task<IActionResult> PutPress(int id, Press press) { if (id != press.Id) { return BadRequest(); } _context.Entry(press).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!PressExists(id)) { return NotFound(); } else { throw; } } return NoContent(); } // POST: api/Presses [HttpPost] public async Task<ActionResult<Press>> PostPress(Press press) { _context.Press.Add(press); await _context.SaveChangesAsync(); return CreatedAtAction("GetPress", new { id = press.Id }, press); } // DELETE: api/Presses/5 [HttpDelete("{id}")] public async Task<ActionResult<Press>> DeletePress(int id) { var press = await _context.Press.FindAsync(id); if (press == null) { return NotFound(); } _context.Press.Remove(press); await _context.SaveChangesAsync(); return press; } private bool PressExists(int id) { return _context.Press.Any(e => e.Id == id); } } }
Java
UTF-8
1,260
2.234375
2
[]
no_license
package vaycent.testbaidumap.Utils; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.util.ArrayList; import java.util.List; /** * Created by vaycent on 2017/6/2. */ public class HistroySharePreference { private final String POI_SEARCH_HISTROY="PoiSearchHistroy"; public void save(String keyWord){ if(null==keyWord||"".equals(keyWord)) return; List<String> mKeyWords = read(); if(mKeyWords.size()==20){ mKeyWords.remove(mKeyWords.size()-1); } for(int i=0;i<mKeyWords.size();i++){ if(mKeyWords.get(i).equals(keyWord)) return; } mKeyWords.add(0,keyWord); Gson gson = new Gson(); String gsonStr = gson.toJson(mKeyWords); SharedPreferencesUtil.getInstance().saveString(POI_SEARCH_HISTROY, gsonStr); } public List<String> read(){ String gsonStr = SharedPreferencesUtil.getInstance().getString(POI_SEARCH_HISTROY, ""); Gson gson = new Gson(); ArrayList<String> mKeyWords = gson.fromJson(gsonStr,new TypeToken<List<String>>(){}.getType()); if(null==mKeyWords) mKeyWords = new ArrayList<String>(); return mKeyWords; } }
C++
UTF-8
3,186
3.109375
3
[ "MIT" ]
permissive
/* * Copyright (C) 2008 Emweb bvba, Heverlee, Belgium. * * See the LICENSE file for terms of use. */ #include <Wt/WApplication.h> #include <Wt/WBreak.h> #include <Wt/WContainerWidget.h> #include <Wt/WLineEdit.h> #include <Wt/WPushButton.h> #include <Wt/WText.h> #include <memory> /* * A simple hello world application class which demonstrates how to react * to events, read input, and give feed-back. */ class HelloApplication : public Wt::WApplication { public: HelloApplication(const Wt::WEnvironment& env); private: Wt::WLineEdit *nameEdit_; Wt::WText *greeting_; void greet(); }; /* * The env argument contains information about the new session, and * the initial request. It must be passed to the WApplication * constructor so it is typically also an argument for your custom * application constructor. */ HelloApplication::HelloApplication(const Wt::WEnvironment& env) : WApplication(env) { setTitle("Hello world"); // application title root()->addWidget(std::make_unique<Wt::WText>("Your name, please ? ")); // show some text nameEdit_ = root()->addWidget(std::make_unique<Wt::WLineEdit>()); // allow text input nameEdit_->setFocus(); // give focus auto button = root()->addWidget(std::make_unique<Wt::WPushButton>("Greet me.")); // create a button button->setMargin(5, Wt::Side::Left); // add 5 pixels margin root()->addWidget(std::make_unique<Wt::WBreak>()); // insert a line break greeting_ = root()->addWidget(std::make_unique<Wt::WText>()); // empty text /* * Connect signals with slots * * - simple Wt-way: specify object and method */ button->clicked().connect(this, &HelloApplication::greet); /* * - using an arbitrary function object, e.g. useful to bind * values with std::bind() to the resulting method call */ nameEdit_->enterPressed().connect(std::bind(&HelloApplication::greet, this)); /* * - using a lambda: */ button->clicked().connect([=]() { std::cerr << "Hello there, " << nameEdit_->text() << std::endl; }); } void HelloApplication::greet() { /* * Update the text, using text input into the nameEdit_ field. */ greeting_->setText("Hello there, " + nameEdit_->text()); } int main(int argc, char **argv) { /* * Your main method may set up some shared resources, but should then * start the server application (FastCGI or httpd) that starts listening * for requests, and handles all of the application life cycles. * * The last argument to WRun specifies the function that will instantiate * new application objects. That function is executed when a new user surfs * to the Wt application, and after the library has negotiated browser * support. The function should return a newly instantiated application * object. */ return Wt::WRun(argc, argv, [](const Wt::WEnvironment &env) { /* * You could read information from the environment to decide whether * the user has permission to start a new application */ return std::make_unique<HelloApplication>(env); }); }
Go
UTF-8
1,533
3.0625
3
[]
no_license
/* Cashcalc 2020 Copyright (C) 2019-2020 Istvan Nemeth mailto: nemethistvanius@gmail.com */ package services import "testing" func TestGetMongoDBNameFromURI(t *testing.T) { testCases := []struct { input string expected string }{ {"mongodb://user:pw@host:port/db", "db"}, {"mongodb://user:pw@host:port//db", "db"}, {"mongodb://host/db", "db"}, {"mongo://token@host/db", "db"}, {"db", "db"}, {"/db", "db"}, {"/host:port/db", "db"}, {"mongodb://user:pw@host:port/db?ssl=true", "db"}, } for _, tc := range testCases { actual := GetMongoDBNameFromURI(tc.input) if actual != tc.expected { t.Errorf("getDBnameFromURI(%v) failed: expected: %v, got: %v", tc.input, tc.expected, actual) } } } func TestGetPostgresDBSpecsFromURL(t *testing.T) { testCases := []struct { input, expectedUser, expectedPw, expectedHost, expectedPort, expectedDBName string }{ {"protocol://user:pw@host:port/db", "user", "pw", "host", "port", "db"}, } for _, tc := range testCases { actualHost, actualUser, actualPort, actualPw, actualDB := GetPostgresDBSpecsFromURL(tc.input) if actualHost != tc.expectedHost && actualUser != tc.expectedUser && actualPort != tc.expectedPort && actualPw != tc.expectedPw && actualDB != tc.expectedDBName { t.Errorf("GetPostgresDBSpecsFromURL(%v) failed: exptected: protocol://%v:%v@%v:%v/%v, got: protocol://%v:%v@%v:%v/%v", tc.input, tc.expectedUser, tc.expectedPw, tc.expectedHost, tc.expectedPort, tc.expectedDBName, actualUser, actualPw, actualHost, actualPort, actualDB) } } }
PHP
UTF-8
2,273
2.671875
3
[]
no_license
<?php function get_string_between($string, $start, $end){ $string = ' ' . $string; $ini = strpos($string, $start); if ($ini == 0) return ''; $ini += strlen($start); $len = strpos($string, $end, $ini) - $ini; return substr($string, $ini, $len); } function get_post_content($post) { return get_string_between($post->post_content, "#TEASER START#", "#TEASER END#")." ".get_string_between($post->post_content, "#MAIN START#", "#MAIN END#"); } $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' )[0]; $all_products = get_posts(array( 'post_type' => 'product', 'posts_per_page' => -1 )); $delimiterStart; $delimiterEnd; switch ($post->post_type) { case 'f_designer': $delimiterStart = '¤designers¤'; $delimiterEnd = '¤/designers¤'; break; case 'f_distributor': $delimiterStart = '¤distributors¤'; $delimiterEnd = '¤/distributors¤'; break; case 'f_manufacturer': $delimiterStart = '¤manufacturers¤'; $delimiterEnd = '¤/manufacturers¤'; break; default: $delimiterStart = 'NOPE'; $delimiterEnd = 'NOPE'; } foreach($all_products as $m_product) { $productCollsString = get_string_between($m_product->post_content, $delimiterStart, $delimiterEnd); $productCollsArray = explode(',', $productCollsString); $productIsMadeByThisCollaborator = in_array($post->post_title, $productCollsArray); $collTitleIsNotEmpty = $post->post_title != ''; if($productIsMadeByThisCollaborator && $collTitleIsNotEmpty) { array_push($products, $m_product); } } ?> <div class="row col-sm-12" id="collaborator-content"> <div class="col-sm-5 col-sm-push-7" id="collaborators-image"> <img src=<?php echo $image; ?>> </div> <div class="col-sm-7 col-sm-pull-5 main-content"> <div id="collaborators-text"> <?php echo get_post_content($post) ?> </div> </div> </div> <div class="product-grid col-sm-12"> <?php foreach($products as $product) { $image = wp_get_attachment_image_src( get_post_thumbnail_id( $product->ID ), 'single-post-thumbnail' )[0]; ?> <div> <img class="images-pointer" src=<?php echo $image ?> onclick="window.location.href='<?php echo get_post_permalink($product->ID) ?>'"> </div> <?php } ?> </div>
Rust
UTF-8
827
3.703125
4
[]
no_license
use std::io; fn check_num(num: i32) { if num < 0 { println!("{} is negative", num); } else if num > 0 { println!("{} is positive", num); } else { println!("Number equals to zero"); } } fn main() { let mut number: i32; println!("Please enter a number:"); loop { let mut flag = false; let mut temp_num = String::new(); io::stdin().read_line(&mut temp_num).expect("Failed to read number input"); number = match temp_num.trim().parse::<i32>() { Ok(num) => { flag = true; num }, Err(_) => { println!("Please enter a valid number"); 0 } }; if flag == true { break; } } check_num(number); }
Markdown
UTF-8
4,596
2.96875
3
[ "Apache-2.0" ]
permissive
# MockDB (LocalDB) This is a mock DB that represents a lightweight database that is defined by JSON files. It is used for testing purposes. ## Configuration In order to configure your root directory (Catalog), please create a Connector Configuration file as `~/.partiql/plugins/<catalog_name>.ion`, where `<catalog_name>` will be the catalog name. See the below example: ```ion // File: ~/.partiql/plugins/fs.ion // Description: Stands for File System { "connector_name": "localdb", // This connector "localdb_root": "/Users" // The (configurable) root of my filesystem to query against } ``` ## Catalog Your Catalog is specified as the `localdb_root` directory from your configuration file above. If not specified, it defaults to `${HOME}/.partiql/localdb`. Each Catalog holds Directories. Here's an example filesystem using the Configuration File from further above: ```text fs (Connector: localdb) (Root: /Users) ├── john │ ├── plants.json │ └── pets.json └── jack ├── living | ├── furniture.json | └── pets.json └── kitchen └── appliances.json ``` In the above PartiQL Environment, we have loaded all of the files from our filesystem starting at `/Users`. We can see that there are two top-level directories `john` and `jack`. `john` does not have child directories, but `jack` does. `john` directly holds Value Descriptors, while `jack`'s child directories hold Value Descriptors. ## Table Descriptors Table schemas are stored as JSON files and have the following format: ```json { "name": "plants", "type": "TABLE", "attributes": [ { "name": "id", "type": "STRING", "attributes": [] }, { "name": "room_no", "type": "INT", "attributes": [] }, { "name": "water_frequency_days", "type": "DECIMAL", "attributes": [32, 0] }, { "name": "metas", "type": "STRUCT", "attributes": [ { "name": "a", "type": "INT", "attributes": [] }, { "name": "b", "type": "STRING", "attributes": [] } ] } ] } ``` ## Inference Examples ### Using Current Catalog/Namespace If we are referencing `plants`, and we've set our current namespace to `john` within the current catalog `fs`, we can reference `plants`, similar to how we can reference files relative to our current working directory in Unix. See `query.pql` below: ```partiql --query.pql SELECT id AS identifier, room_no AS room_number, water_frequency_days FROM plants ``` The output, using the command further above, is: ```text ---------------------------------------------- | Schema Name: UNSPECIFIED_NAME | ---------------------------------------------- | identifier | string | | room_number | int | | water_frequency_days | int | ---------------------------------------------- ``` Similarly, if our current namespace is `jack` with the current catalog `fs` we can reference the table `appliances` using a relative path: ```partiql SELECT * FROM kitchen.appliances ``` If we have set a current namespace and if the requested table doesn't match any position relative to the current namespace, we will attempt to resolve it from the root of the catalog. If we can't find it there, we will attempt all other catalogs. If you'd like to use an absolute reference to remove ambiguity and improve efficiency, please use the fully-qualified name: ```partiql SELECT * FROM fs.jack.kitchen.appliances ``` ### More Complex Queries You can even create multiple tables and run more-complex queries: ```partiql -- infer_join.pql SELECT p1.id AS identifier, p1.room_no + 50 AS room_number, p1.water_frequency_days, p1.water_amount_liters, p2.name, p2.age, p2.weight, p2.favorite_toy FROM plants AS p1 CROSS JOIN pets AS p2 ``` The above query outputs: ```text ---------------------------------------------- | Schema Name: UNSPECIFIED_NAME | ---------------------------------------------- | identifier | string | | room_number | int | | water_frequency_days | int | | water_amount_liters | decimal (32, 0) | | name | string | | age | int | | weight | decimal | | favorite_toy | string | ---------------------------------------------- ```
Java
UTF-8
3,262
2.4375
2
[]
no_license
package local.hal.st32.android.itarticlecollection60213; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.EditText; public class ArticleAddActivity extends AppCompatActivity { // POSTするACCESS先URL private static final String POST_ACCESS_URL = "http://hal.architshin.com/st32/insertItArticle.php"; // このActivityのinstanceを宣言(PostMyArticleクラスにてこのActivityのinstanceを使用する) private static ArticleAddActivity instance = null; private EditText _etTitle; private EditText _etUrl; private EditText _etComment; private EditText _etLastName; private EditText _etFirstName; private EditText _etStudentId; private EditText _etSeatNo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_article_add); // このActivityのinstanceを入れる instance = this; // 戻るボタン追加 android.support.v7.app.ActionBar actionBar = getSupportActionBar(); actionBar.setHomeButtonEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); _etTitle = findViewById(R.id.etTitle); _etUrl = findViewById(R.id.etUrl); _etComment = findViewById(R.id.etComment); _etLastName = findViewById(R.id.etLastName); _etFirstName = findViewById(R.id.etFirstName); _etStudentId = findViewById(R.id.etStudentId); _etSeatNo = findViewById(R.id.etSeatNo); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); // アクションバーに登録マークのメニューを追加 inflater.inflate(R.menu.article_add_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // 戻るボタンが押されたらfinish()する case android.R.id.home: finish(); break; // 登録ボタンが押されたら構造体(PostItem)へURL情報と入力情報をセットし、 // PostMyArticleクラスにて非同期でサーバーへ構造体(PostItem)の内容を送信する case R.id.addButton: PostItem p = new PostItem(); p.postUrl = POST_ACCESS_URL; p.title = _etTitle.getText().toString(); p.articleUrl = _etUrl.getText().toString(); p.comment = _etComment.getText().toString(); p.lastName = _etLastName.getText().toString(); p.firstName = _etFirstName.getText().toString(); p.studentId = _etStudentId.getText().toString(); p.seatNo = _etSeatNo.getText().toString(); PostMyArticle postMyArticle = new PostMyArticle(); postMyArticle.execute(p); break; } return super.onOptionsItemSelected(item); } public static ArticleAddActivity getInstance() { return instance; } }
PHP
UTF-8
5,709
2.90625
3
[]
no_license
<?php class Product{ private $productID, $productName, $productDescription, $productPrice, $salePrice, $quantity,$image,$isDiscountedProduct; /* * To display catalog products * */ public function getAllCatalogProducts(){ $display = ""; $display .= "<div class = 'product_details' id = 'product_" .$this->productID ."'>"; $display .= "<div class='product_thumb_image' id ='product_thumb_image'> <img src ='" . $this->image . "' style = 'height:173px; width: 308px'> </img> </div>"; $display .= "<div class = 'item_details'><div class = 'item_name'> <h3>".$this->productName ."</h3> </div>"; $display .="<div class = 'item_description'> <p>". $this->productDescription ."</p> </div>"; $display .="<div id = 'availableQty' name = 'available Qty'><span id = 'QtyWrapper'> <strong>Available Quantity:\t</strong></span>\t" .$this->quantity . "</div></div><br/>" ; $display .= "<div class = 'price_description'>"; $display .= "<form class = 'productInformation' action='http://kelvin.ist.rit.edu/~kjs5335/756/ecommerceproject/index.php' method='post'>"; $display .="<input type = 'hidden' name='productID' id='productID' value =". $this->productID ."><br/>"; $display .="<div class = 'actual_price'><span id = 'priceWrapper'> <strong>Product Price:\t</strong></span>\t $" . $this->productPrice ."</div><br/>"; $display .= "<label><abbr title='Quantity'>Qty</abbr> <input type='text' name='quantityMap' size='3' value='1' id='quantityMap' style='width:40px;'/> </label><span> <abbr title='Minimum order quantity'> Min: 1 </abbr></span>"; $display .= "<div id='addToCartButton'><input type ='submit' name = 'product_addToCart' id ='product_addToCart' value='Add To Cart' onclick='cartItems()'></div>"; $display .= "</form></div></div>"; return $display; } /* * To display Sale Products */ public function getAllSaleProducts(){ //return "{$this->FirstName} {$this->LastName} and my nickname is {$this->$NickName}"; $display = ""; $display .= "<div class = 'product_details' id = 'product_" .$this->productID ."'>"; $display .= "<div class='product_thumb_image' id ='product_thumb_image'> <img src ='" . $this->image . "' style = 'height:173px; width: 308px'> </img> </div>"; $display .= "<div id = 'item_details'><div class = 'item_name'> <h3>".$this->productName ."</h3> </div>"; $display .="<div class = 'item_description'> <p>". $this->productDescription ."</p> </div>"; $display .="<div id = 'availableQty' name = 'available Qty'><span id = 'QtyWrapper'> <strong>Available Quantity:\t</strong></span>\t" .$this->quantity . "</div></div><br/>" ; $display .= "<div class = 'price_description'>"; $display .= "<form class = 'productInformation' action='http://kelvin.ist.rit.edu/~kjs5335/756/ecommerceproject/index.php' method='post'>"; $display .="<input type = 'hidden' name='productID' id ='productID' value =". $this->productID .">"; $display .="<div class = 'actual_price'><span id = 'priceWrapper'> <strong>Product Price:\t</strong></span>\t $" . $this->productPrice ."</div><br/>"; $display .="<div class = 'actual_price'><span id = 'salepriceWrapper'> <strong>Sale Price:\t</strong></span>\t $" . $this->salePrice ."</div><br/>"; $display .= "<label><abbr title='Quantity'>Qty</abbr> <input type='text' name='quantityMap' size='3' value='1' id='quantityMap' style='width:40px;'/> </label><span>"; $display .= "<div class='addToCartButton'><input type ='submit' name = 'product_addToCart' id ='product_addToCart' value='Add To Cart' onclick='cartItems()'></div>"; $display .= "</form></div></div>"; return $display; } /* * To edit products - Admin Operations */ function editProductsAdmin(){ $option = "<option value = '" . $this->productID . "'>" . $this->productName . "</option>"; return $option; } function getProductDetailsEdit($allproducts,$selectProductID){ $editproductdetail = array(); foreach($allproducts as $product){ if($product->productID == $selectProductID) { $editproductdetail = array("productID"=>$product->productID, "productName"=>$product->productName, "productDescription"=>$product->productDescription, "productPrice"=>$product->productPrice, "salePrice"=>$product->salePrice, "quantity"=>$product->quantity, "isDiscountedProduct"=>$product->isDiscountedProduct, "image" =>$product->image ); } } return($editproductdetail); } }
Java
UTF-8
714
2.171875
2
[]
no_license
package com.linjun.service.impl; import com.linjun.common.domain.PeopleException; import com.linjun.dao.SuggestMapper; import com.linjun.model.Suggest; import com.linjun.service.SuggestService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class SuggestServiceImpl implements SuggestService { @Autowired SuggestMapper suggestMapper; @Override public Suggest add(Suggest suggest) { long result=suggestMapper.insertSelective(suggest); if (result>0){ return suggestMapper.selectByPrimaryKey(result); }else { throw new PeopleException("添加失败"); } } }
Java
UTF-8
353
3.1875
3
[]
no_license
package Day_15.buffer; public class TestStringBuilder { public static void main(String[] args) { String str = "Hello";//定义字符串Hello str += "World";//将World追加给Hello //1.创建StringBuilder //2.调用append追加的方法 //3.调用toString转换回String System.out.println(str);//打印追加后的str } }
Java
UTF-8
2,203
2.046875
2
[]
no_license
package com.example.android.MusicPlayer; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageButton; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.example.android.MusicPlayer.R; import org.w3c.dom.Text; import java.util.ArrayList; import java.util.HashMap; import java.util.SortedMap; /** * Created by HP on 4/6/2016. */ public class playerActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_player_list); int position = getIntent().getIntExtra("currentPosition", -1); ArrayList<Song> songs = new ArrayList<Song>(); songs.add(new Song("Desafinado", "Ella Fitzgerald", "The best of Ella")); songs.add(new Song("Corcovado", "Andy Williams", "The shadow of your smile")); songs.add(new Song("Smoke on the water", "Deep Purple", "Machine Head")); songs.add(new Song("'Na sera e maggio", "Patrizio Buanne", "The Italian")); songs.add(new Song("Yolanda", "Pink Martini", "Sympathique")); songs.add(new Song("La soledad", "Pink Martini", "Simpathique")); songs.add(new Song("Mil Passos", "Soha", "D'ici et d'ailleurs")); songs.add(new Song("Su lado de cama ", "Joao Soriano", "El Duque de la Bachata")); ArrayList<Song> songs2 = new ArrayList<Song>(); songs2.add(songs.get(position)); com.example.android.MusicPlayer.playerAdapter Adapter = new com.example.android.MusicPlayer.playerAdapter(this, songs2); ListView listView = (ListView) findViewById(R.id.activity_player_list); listView.setAdapter(Adapter); ImageButton imageButton = (ImageButton) findViewById(R.id.previous); } }
C++
UTF-8
1,370
2.78125
3
[]
no_license
// // Created by Kenji Nomura on 8/22/17. // #include "Network.h" #include <iostream> #include "common/functions/functions.h" Network::Network() {} Network::Network(const std::vector<Eigen::MatrixXd> &Ws, const std::vector<Eigen::MatrixXd> &Bs) : Ws(Ws), Bs(Bs) {}; void Network::setWeight(const std::vector<Eigen::MatrixXd> &Ws) { this->Ws = Ws; } void Network::setBias(const std::vector<Eigen::MatrixXd> &Bs) { this->Bs = Bs; } Eigen::MatrixXd Network::forward(const Eigen::MatrixXd &X) const { std::cout << "X = " << X << std::endl; Eigen::MatrixXd Ai; Eigen::MatrixXd Zi = X; for (size_t i = 0; i < Ws.size(); i++) { Ai = Zi * Ws[i] + Bs[i]; std::cout << "A" << i << " = " << Ai << std::endl; if (i == Ws.size() - 1L) break; Zi = functions::activation::sigmoid(Ai); std::cout << "Z" << i << " = " << Zi << std::endl; } const auto y = functions::activation::softmax(Ai); return y; /* auto A1 = X * W[0] + b[0]; std::cout << "A1 = " << A1 << std::endl; auto Z1 = functions::sigmoid(A1); std::cout << "Z1 = " << Z1 << std::endl; auto A2 = Z1 * W[1] + b[1]; std::cout << "A2 = " << A2 << std::endl; auto Z2 = functions::sigmoid(A2); std::cout << "Z2 = " << Z2 << std::endl; auto A3 = Z2 * W[2] + b[2]; std::cout << "A3 = " << A3 << std::endl; auto y = functions::softmax(A3); return y; */ }
Go
UTF-8
2,892
2.75
3
[]
no_license
package eventsapi import ( "encoding/json" "fmt" "github.com/oklahomer/golack/v2/event" "github.com/tidwall/gjson" ) // https://api.slack.com/events-api#callback_field_overview type outer struct { Token string `json:"token"` TeamID string `json:"team_id"` APIAppID string `json:"api_app_id"` Type string `json:"type"` AuthedUsers []string `json:"authed_users"` EventID event.EventID `json:"event_id"` EventTime *event.TimeStamp `json:"event_time"` } // EventWrapper contains given event, metadata and the request. type EventWrapper struct { *outer Event interface{} Request *SlackRequest } // URLVerification is a special payload for initial configuration. // When an administrator register an API endpoint to Slack APP configuration page, this payload is sent to the endpoint // to verify the validity of that endpoint. // // This is part of the events list located at https://api.slack.com/events, // but the structure is defined in this package because this is specifically designed for Events API protocol // Just like Ping and Pong events are specifically designed for RTM API protocol. type URLVerification struct { Type string `json:"type"` Challenge string `json:"challenge"` Token string `json:"token"` } // DecodePayload receives req and decode given event. // The returning value can be one of *event.URLVerification or *EventWrapper. // *event.URLVerification can be sent on the initial configuration when an administrator inputs API endpoint to Slack. func DecodePayload(req *SlackRequest) (interface{}, error) { parsed := gjson.ParseBytes(req.Payload) typeValue := parsed.Get("type") if !typeValue.Exists() { return nil, event.NewMalformedPayloadError(fmt.Sprintf("required type field is not given: %s", parsed)) } switch eventType := typeValue.String(); eventType { case "url_verification": verification := &URLVerification{} err := json.Unmarshal(req.Payload, verification) if err != nil { return nil, fmt.Errorf("failed to unmarshal JSON: %w", err) } return verification, nil case "event_callback": o := &outer{} err := json.Unmarshal(req.Payload, o) if err != nil { return nil, fmt.Errorf("failed to unmarshal JSON: %w", err) } // Read the event field that represents the Slack event being sent eventValue := parsed.Get("event") if !eventValue.Exists() { return nil, event.NewMalformedPayloadError(fmt.Sprintf("requred event field is not given: %s", parsed)) } ev, err := event.Map(eventValue) if err != nil { return nil, err } // Construct a wrapper object that contains meta, event and request data return &EventWrapper{ outer: o, Event: ev, Request: req, }, nil default: return nil, event.NewUnknownPayloadTypeError(fmt.Sprintf("undefined type of %s is given", eventType)) } }
Java
UTF-8
626
2.78125
3
[]
no_license
package com.class33; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; public class Task { public static void main(String[] args) { List <String >list=new ArrayList<String>(); list.add("John"); list.add("James"); list.add("Jane"); list.add("Jasmine"); list.add("Jane"); list.add("James"); HashSet <String >alist=new HashSet<String>(list); System.out.println(alist); //Using AddAll Set<String>noDublicate=new TreeSet<>(); noDublicate.addAll(list); System.out.println(list); } }
C#
UTF-8
2,312
2.875
3
[ "MIT" ]
permissive
using System; using Xunit.Abstractions; namespace Cuemon.Extensions.Xunit { /// <summary> /// Represents the base class from which all implementations of unit testing should derive. /// </summary> /// <seealso cref="Disposable"/> /// <seealso cref="ITestOutputHelper"/> public abstract class Test : Disposable, ITest { /// <summary> /// Initializes a new instance of the <see cref="Test" /> class. /// </summary> /// <param name="output">An implementation of the <see cref="ITestOutputHelper" /> interface.</param> /// <param name="callerType">The <see cref="Type"/> of caller that ends up invoking this instance.</param> /// <remarks><paramref name="output" /> is initialized automatically in an xUnit project.</remarks> protected Test(ITestOutputHelper output = null, Type callerType = null) { TestOutput = output; CallerType = callerType ?? GetType(); } /// <summary> /// Gets the type of caller for this instance. Default is <see cref="object.GetType"/>. /// </summary> /// <value>The type of caller for this instance.</value> public Type CallerType { get; } /// <summary> /// Gets the console substitute to write out unit test information. /// </summary> /// <value>The console substitute to write out unit test information.</value> protected ITestOutputHelper TestOutput { get; } /// <summary> /// Gets a value indicating whether <see cref="TestOutput"/> has a reference to an implementation of <see cref="ITestOutputHelper"/>. /// </summary> /// <value><c>true</c> if this instance has has a reference to an implementation of <see cref="ITestOutputHelper"/>; otherwise, <c>false</c>.</value> protected bool HasTestOutput => TestOutput != null; /// <summary> /// Called when this object is being disposed by either <see cref="M:Cuemon.Disposable.Dispose" /> or <see cref="M:Cuemon.Disposable.Dispose(System.Boolean)" /> having <c>disposing</c> set to <c>true</c> and <see cref="P:Cuemon.Disposable.Disposed" /> is <c>false</c>. /// </summary> protected override void OnDisposeManagedResources() { } } }
PHP
UTF-8
2,295
2.625
3
[]
no_license
<?php /**************************************************************************** * Copyleft meh. [http://meh.doesntexist.org | meh@paranoici.org] * * * * This file is part of miniLOL. A PHP implementation. * * * * miniLOL is free software: you can redistribute it and/or modify * * it under the terms of the GNU Affero General Public License as * * published by the Free Software Foundation, either version 3 of the * * License, or (at your option) any later version. * * * * miniLOL is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Affero General Public License for more details. * * * * You should have received a copy of the GNU Affero General Public License * * along with miniLOL. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************/ class Filter { private $_type; private $_regexp; private $_to; public function __construct ($dom, $censor) { $this->_type = $dom->getAttribute('type'); if (($tmp = $dom->getAttribute('regexp'))) { $this->_regexp = $tmp; } else if (($tmp = $dom->getAttribute('raw'))) { $this->_regexp = "/{$tmp}/i"; } $this->_regexp = preg_replace('#/([^/g]*)g([^/g]*)$#', '/$1$2', $this->_regexp); if ($this->_type == 'censor') { $this->_to = ($censor) ? $censor : '@#!%$'; } else if ($this->_type == 'replace') { $this->_to = ($tmp = $dom->getAttribute('to')) ? $tmp : '$1'; } else { $this->_to = '$1'; } } public function apply ($text) { return preg_replace($this->_regexp, $this->_to, $text); } } ?>
JavaScript
UTF-8
7,336
2.953125
3
[]
no_license
(function() { var SignaturePad = function(selector) { return new SignaturePad.fn.init(selector); }; SignaturePad.fn = SignaturePad.prototype = { signaturepad: "proto-2", constructor: SignaturePad }; var init = SignaturePad.fn.init = function(selector) { if(typeof selector === "string") { var elements = document.querySelectorAll(selector); for(var i = 0; i < elements.length; i++) this[i] = elements[i]; this.length = elements.length; } else { this[0] = selector; this.length = 1; } }; init.prototype = SignaturePad.fn; SignaturePad.fn.map = function(callback) { var ret = [], i = 0; for(; i < this.length; i++) ret.push(callback.call(this, this[i], i)); return ret; }; SignaturePad.fn.each = function(callback) { this.map(callback); return this; }; SignaturePad.fn.mapOne = function(callback) { var ret = this.map(callback); return ret.length > 1 ? ret : ret[0]; }; SignaturePad.fn.text = function(text) { if(typeof text !== "undefined") { return this.each(function (el) { el.innerText = text; }); } else { return this.mapOne(function(el) { return el.innerText; }); } }; SignaturePad.fn.getDom = function() { return this[0]; }; SignaturePad.fn.html = function(html) { if(typeof html !== "undefined") { return this.each(function(el) { el.innerHTML = html; }); } else { return this.mapOne(function(el) { return el.innerHTML; }); } }; SignaturePad.fn.val = function(val) { if(typeof val !== "undefined") { return this.each(function(el) { el.value = val; }); } else { return this.mapOne(function(el) { return el.value; }); } }; SignaturePad.fn.append = function(html) { return this.each(function(el) { el.insertAdjacentHTML("beforeend", html); }); }; SignaturePad.fn.prepend = function(html) { return this.each(function(el) { el.insertAdjacentHTML("afterbegin", html); }); }; SignaturePad.fn.on = function(type, callback, passive) { return this.each(function(el) { el.addEventListener(type, callback, {capture: false, passive: passive}); }); }; SignaturePad.fn.click = function(callback, passive) { return this.on("click", callback, passive); }; SignaturePad.fn.show = function() { return this.each(function(el) { el.style.display = "block"; }); }; SignaturePad.fn.hide = function() { return this.each(function(el) { el.style.display = "none"; }); }; SignaturePad.fn.focus = function() { return this.each(function(el) { el.focus(); }); }; SignaturePad.fn.blur = function() { return this.each(function(el) { el.blur(); }); }; function preparePage() { SignaturePad("body").append('<div id="pad-modal"></div>' + '<div id="pad-container">' + '<canvas id="pad" width="700" height="400"></canvas>' + '<div id="pad-btn-cancel">Cancel</div>' + '<div id="pad-btn-done">Done</div>' + '</div>'); SignaturePad("#pad-btn-cancel").click(function() { SignaturePad("#pad-modal").hide(); SignaturePad("#pad-container").hide(); reset(); }, true); initCanvas(); }; var canvas, ctx, paint = false, clickX = new Array(), clickY = new Array(), clickDrag = new Array(); function initCanvas() { canvas = document.getElementById("pad"); ctx = canvas.getContext("2d"); canvas.onmousedown = function(e) { e.preventDefault(); paint = true; addClick(e.pageX - canvas.parentNode.offsetLeft - canvas.offsetLeft - parseInt(window.getComputedStyle(canvas).paddingLeft, 10), e.pageY - canvas.parentNode.offsetTop - canvas.offsetTop - parseInt(window.getComputedStyle(canvas).paddingTop, 10)); redraw(); }; canvas.onmousemove = function(e) { e.preventDefault(); if(paint) { addClick(e.pageX - canvas.parentNode.offsetLeft - canvas.offsetLeft - parseInt(window.getComputedStyle(canvas).paddingLeft, 10), e.pageY - canvas.parentNode.offsetTop - canvas.offsetTop - parseInt(window.getComputedStyle(canvas).paddingTop, 10), true); redraw(); } }; canvas.onmouseup = function() { paint = false; }; canvas.ontouchstart = function(e) { e.preventDefault(); paint = true; addClick(e.touches[0].pageX - canvas.parentNode.offsetLeft - canvas.offsetLeft - parseInt(window.getComputedStyle(canvas).paddingLeft, 10), e.touches[0].pageY - canvas.parentNode.offsetTop - canvas.offsetTop - parseInt(window.getComputedStyle(canvas).paddingTop, 10)); redraw(); }; canvas.ontouchmove = function(e) { e.preventDefault(); if(paint) { addClick(e.touches[0].pageX - canvas.parentNode.offsetLeft - canvas.offsetLeft - parseInt(window.getComputedStyle(canvas).paddingLeft, 10), e.touches[0].pageY - canvas.parentNode.offsetTop - canvas.offsetTop - parseInt(window.getComputedStyle(canvas).paddingTop, 10), true); redraw(); } }; canvas.ontouchend = function() { paint = false; }; canvas.ontouchcancel = function() { paint = false; }; resetCanvas(); } function addClick(x, y, drag) { clickX.push(x); clickY.push(y); clickDrag.push(drag); } function redraw() { resetCanvas(); for(var i = 0; i < clickX.length; i++) { ctx.beginPath(); if(clickDrag[i] && i) ctx.moveTo(clickX[i - 1], clickY[i - 1]); else ctx.moveTo(clickX[i] - 1, clickY[i]); ctx.lineTo(clickX[i], clickY[i]); ctx.closePath(); ctx.stroke(); } } function resetCanvas() { ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); ctx.strokeStyle = "#000000"; ctx.lineJoin = "round"; ctx.lineWidth = 2.5; ctx.beginPath(); ctx.moveTo(20, ctx.canvas.height - 60); ctx.lineTo(ctx.canvas.width - 20, ctx.canvas.height - 60); ctx.closePath(); ctx.stroke(); } function reset() { clickX = new Array(); clickY = new Array(); clickDrag = new Array(); resetCanvas(); } function encode() { var json = { version: "proto-2", path: { x: clickX, y: clickY, d: clickDrag } }; return base64_encode(JSON.stringify(json)); } function base64_encode(str) { return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) { return String.fromCharCode('0x' + p1); })); } SignaturePad.fn.acquireSignature = function() { return this.each(function(el) { if((SignaturePad(el).getDom().nodeName == "TEXTAREA" && SignaturePad(el).val() === "") || (SignaturePad(el).getDom().nodeName !== "TEXTAREA" && SignaturePad(el).text() === "")) { if(SignaturePad("#pad-container").length == 0) preparePage(); SignaturePad("#pad-modal").show(); SignaturePad("#pad-container").show(); SignaturePad(el).blur(); SignaturePad("#pad-btn-done").click(function() { SignaturePad("#pad-modal").hide(); SignaturePad("#pad-container").hide(); SignaturePad(el).val(encode()); reset(); }, true); } }); }; var _$ = window.$, _SignaturePad = window.SignaturePad; SignaturePad.fn.noConflict = function(deep) { if(window.$ === SignaturePad) window.$ = _$; if(deep && window.SignaturePad === SignaturePad) window.SignaturePad = _SignaturePad; return SignaturePad; }; window.SignaturePad = window.$ = SignaturePad; })();
Markdown
UTF-8
778
2.609375
3
[]
no_license
# Detecting face and sending Mail, whatsapp message & launching ec2 instance using Terraform ## Changes to do before running the code: * Update `phone number` in `sendWhatsApp.py` file. * Update mail-id (sender and receiver) and password in the FaceRecognition.ipynb file where `sendemail.sendemail ` is used. ## Run code *** `configure AWS` in CMD to configure AWS to Launch the ec2 instance using the Terraform ## Run ### First ```bash Face_Recognition_model_creation.ipynb ``` #### This will Train and Save model. ### Second ```bash Face_Recognition.ipynb ``` #### This will recognize face and run respective functions stored in the below files. * AWS.tf * sendemail.py * sendWhatsApp.py ## Youtube Video Link: https://youtu.be/iNnq8lYN7lY
Python
UTF-8
4,704
2.734375
3
[]
no_license
""" @Authors: mikhail-matrosov and Alexey Boyko @Created August, 20 This script takes image and converts it into engraving, a path that also can be drawn with a pen or a marker. """ import cv2 import numpy as np from findPaths import * from plotter import plot_from_file # PARAMETERS LINE_THICKNESS = 3 # Minimal distance between lines. Not recommended to make less then 3 EROSION_MAX_DEPTH = 1000 TARGET_SIZE=(1024.0,768.0) def getKernel(r): gk = cv2.getGaussianKernel(r*2+1, r) kernel = gk.dot(gk.transpose()) kernel = (kernel >= kernel[r,r]/1.8).astype(np.uint8) return kernel # N = 10 # Number of intencity layers def img2engrave(eq, N=10): white = np.ones(eq.shape) lowestLevel = -1 for i in range(0,N): Isplit = (i+0.5)*255/N I = i*255.0/N level = (eq>Isplit).astype(np.float32) if level.all(): lowestLevel = i print 'Level %d is skipped' % (i,) continue white += level # kill already existing infill for this level #level = cv2.GaussianBlur(level, (0,0), 1) R = LINE_THICKNESS/(1-I/255.0) kernel = getKernel(int(R)) level = cv2.erode(level, getKernel(int(R/2+1))) for j in range(int(EROSION_MAX_DEPTH/R)): g = cv2.Laplacian(level, cv2.CV_32F) > 0 white *= 1-g # draw black lines level = cv2.erode(level, None, iterations = int(R)) if not np.any(level): break print '%d out of %d layers' % (i, N) # the whitest level = (eq>(N-0.5)*255/N).astype(np.float32) white += level # fill black regions Isplit = (lowestLevel+1.5)*255/N I = (lowestLevel+1.0)*255/N R = LINE_THICKNESS/(1-I/255.0) kernel = getKernel(int(R)) level = (eq<=Isplit).astype(np.float32) level = cv2.erode(level, getKernel(int(R/2+1))) for j in range(int(EROSION_MAX_DEPTH/R)): g = cv2.Laplacian(level, cv2.CV_32F) > 0 white *= 1-g # draw black lines if not np.any(level): break level = cv2.erode(level, kernel) return white def boykoLines(img, stat_params, Canny_param_koefs) : buf=np.zeros(img.shape) med=np.mean(img) variance=np.sqrt(np.var(img)) minblur=int(round(np.sqrt(img.shape[0]**2+img.shape[1]**2)/stat_params[0])) minblur=minblur-1+(minblur % 2) if minblur<3: minblur=3 maxblur=int(round(np.sqrt(img.shape[0]**2+img.shape[1]**2)/stat_params[1])) stepblur=int(round((maxblur-minblur)/stat_params[2])) if stepblur<2: stepblur=2 stepblur = int(2*round(stepblur /2)) print minblur,maxblur,stepblur for i,m in enumerate(np.arange(minblur,maxblur,stepblur)): img_buf=cv2.medianBlur(np.uint8(img),int(m)) img_buf=cv2.Canny(np.uint8(img_buf),np.uint8(med+Canny_param_koefs[0]*variance),int(med+Canny_param_koefs[1]*variance)) buf=np.logical_or(buf>0,img_buf>0) arr = 255-255*buf.astype(np.uint8) return arr def main(inputImagePath, layers=1, stat_params=[300,30,10], Canny_param_koefs=[-1.3,-0.3]): print "main" # open img = cv2.imread(inputImagePath).astype(np.float32) if len(img.shape)>2: img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) # resize scale = min(TARGET_SIZE[0]/img.shape[0], TARGET_SIZE[1]/img.shape[1]) img = cv2.resize(img, dsize=(0,0), fx=scale, fy=scale) # equalize and blur eq = cv2.equalizeHist(img.astype(np.uint8)) eq = cv2.GaussianBlur(eq, (0,0), 2) cv2.subtract(eq, 65, eq) cv2.multiply(eq, 4, eq) # engrave print 'Tracing lines for shading...' engraving = img2engrave(eq, 10) #engraving = np.zeros(img.shape) + 255 pathsE = findPaths(engraving) #Boyko-style print 'Boyko lines...' arr = boykoLines(img, stat_params, Canny_param_koefs) print 'Tracing...' pathsA = findPaths(arr) print len(pathsE), len(pathsA), len(pathsE+pathsA) paths = sortPaths(pathsE + pathsA) print 'Done.' printPathStatistics(paths, img.shape) parts = inputImagePath.split('/') parts[-1] = 'r_'+parts[-1] fname = '/'.join(parts)+'.npy' np.save(fname, (eq.shape,paths)) plot_from_file(fname, 0) return fname def showpic(image): cv2.imshow('',image) k = cv2.waitKey(0) if k == ord('s'): # wait for 's' key to save and exit cv2.imwrite('ololo.png',image) cv2.destroyAllWindows() #main('aysilu.JPG')
Markdown
UTF-8
2,081
2.546875
3
[ "MIT" ]
permissive
<br> <p align="center"> <img alt="to.do" src="public/logo.svg" width="200px"> </p> <p align="center"> <i>Desafio de ReactJs do <a href="https://rocketseat.com.br/ignite">Ignite</a>, na <a href="https://rocketseat.com.br/">Rocketseat</a>.</i><br> <div align="center"> <a href="https://"><img src="https://img.shields.io/static/v1?label=&message=HTML5&color=%23E34F26&style=for-the-badge&logo=html5&logoColor=whitesmoke" alt="HTML5"></a> <a href="https://"><img src="https://img.shields.io/static/v1?label=&message=CSS3&color=%231572B6&style=for-the-badge&logo=css3&logoColor=whitesmoke" alt="CSS3"></a> <a href="https://"><img src="https://img.shields.io/static/v1?label=&message=SASS&color=%23CC6699&style=for-the-badge&logo=sass&logoColor=whitesmoke" alt="SASS"></a> <a href="https://"><img src="https://img.shields.io/static/v1?label=&message=Typescript&color=%231570B6&style=for-the-badge&logo=typescript&logoColor=whitesmoke" alt="Typescript"> </a> <a href="https://"><img src="https://img.shields.io/static/v1?label=&message=ReactJS&color=%231545B6&style=for-the-badge&logo=react&logoColor=whitesmoke" alt="ReactJS"></a> </div> </p> <br> ![alt text](https://i.ibb.co/1s5RywS/screencapture-localhost-8080-2021-07-14-11-21-34.png) <p align="center"> <a href="#-tecnologias">Tecnologias</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp; <a href="#-projeto">Projeto</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp; <a href="#-como-executar">Como executar</a> </p> <br> ## ✨ Tecnologias Esse projeto foi desenvolvido com as seguintes tecnologias: - [React](https://reactjs.org) - [TypeScript](https://www.typescriptlang.org/) ✔ Responsivo para Mobile ## 💻 Projeto Primeiro desafio da trilha de ReactJS do Ignite, curso da Rocketseat ## 🚀 Como executar - Clone o repositório - Instale as dependências com `npm i` - Inicie o servidor com `npm run dev` Agora você pode acessar [`localhost:8080`](http://localhost:8080) do seu navegador. <br> Made with 💜 by Rafael Andrade 👋 [Check out my LinkedIn](https://www.linkedin.com/in/andraderafa72)
C++
UTF-8
705
2.921875
3
[]
no_license
/* * @Author: tanht * @Date: 2020-08-30 22:54:20 * @Last Modified by: tanht * @Last Modified time: 2020-08-31 13:34:00 * @Email: tanht.lavamyth@gmail.com */ #include <iostream> #include <cstring> using namespace std; #define AMAX 50 bool marks[AMAX]; int main () { string s; cin >> s; int sLen = (int)s.size(); memset(marks, false, sizeof(marks)); bool flag = false; for (int i = 0; i < sLen; ++i) { int decimalNumOfChar = int(s[i] - 'A'); if (marks[decimalNumOfChar] == false) { flag ^= true; marks[decimalNumOfChar] = true; } } if (flag) { cout << "IGNORE HIM!"; } else { cout << "CHAT WITH HER!"; } } // Read more bits: https://www.geeksforgeeks.org/check-whether-k-th-bit-set-not/
JavaScript
UTF-8
1,311
2.625
3
[]
no_license
import React, { Component } from 'react'; class SignIn extends Component { constructor(props) { super(props); this.state = { email: '', password: '', error: '', }; this.handleOnChange = this.handleOnChange.bind(this); this.handleLoginUser = this.handleLoginUser.bind(this); } handleOnChange(e) { const { name, value } = e.target; this.setState({ [name]: value }); } handleLoginUser() { const { email, password } = this.state; if (!email || !password) { return this.setState({ error: 'Please complete the form' }); } this.setState({ error: null }); return console.log({ email, password }); } render() { const { email, password, error } = this.state; return ( <div> <h2>Sign In</h2> {error && <p className="errorText">{error}</p>} <input type="email" name="email" value={email} onChange={this.handleOnChange} placeholder="email" /> <input type="password" name="password" value={password} onChange={this.handleOnChange} placeholder="password" /> <button onClick={this.handleLoginUser}>Login</button> </div> ); } } export default SignIn;
Java
UTF-8
669
2.78125
3
[]
no_license
package com.mbi; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; class StringValidator implements Validator { @Override public <T> void compareWithSchema(JSONObject schema, T object) { String actualResult = (String) object; if (actualResult.startsWith("{")) { new JsonObjectValidator().compareWithSchema(schema, new JSONObject(actualResult)); } else if (actualResult.startsWith("[")) { new JsonArrayValidator().compareWithSchema(schema, new JSONArray(actualResult)); } else { throw new JSONException("Invalid json: " + actualResult); } } }
Rust
UTF-8
1,896
2.875
3
[ "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
use crate::parser::error::Error; use nom::branch::alt; use nom::bytes::complete::is_a; use nom::character::complete::{alpha1, alphanumeric1, multispace0}; use nom::combinator::recognize; use nom::error::ParseError; use nom::multi::many0; use nom::sequence::{delimited, tuple}; use nom::{IResult, Parser}; // > The metric name … must match the regex [a-zA-Z_:][a-zA-Z0-9_:]*. pub fn parse_metric_name(input: &str) -> IResult<&str, &str, Error<&str>> { recognize(tuple(( alt((alpha1, is_a("_:"))), many0(alt((alphanumeric1, is_a("_:")))), )))(input) } // > Label names … must match the regex [a-zA-Z_][a-zA-Z0-9_]*. Label names beginning with __ are reserved for internal use. pub fn parse_label_name(input: &str) -> IResult<&str, &str, Error<&str>> { recognize(tuple(( alt((alpha1, is_a("_"))), many0(alt((alphanumeric1, is_a("_")))), )))(input) } pub fn ws<'a, O, E: ParseError<&'a str>, F: Parser<&'a str, O, E>>( f: F, ) -> impl Parser<&'a str, O, E> { delimited(multispace0, f, multispace0) } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse_label() { assert_eq!(parse_label_name("instance)"), Ok((")", "instance"))); assert_eq!(parse_label_name("a"), Ok(("", "a",))); assert_eq!(parse_label_name("abcd"), Ok(("", "abcd",))); assert_eq!(parse_label_name("__a__"), Ok(("", "__a__",))); assert_eq!(parse_label_name("__name__"), Ok(("", "__name__"))); assert_eq!(parse_label_name("job="), Ok(("=", "job"))); } #[test] fn test_parse_metric_name() { assert_eq!(parse_metric_name("a1234"), Ok(("", "a1234",))); assert_eq!( parse_metric_name("method_code:http_errors:rate5m"), Ok(("", "method_code:http_errors:rate5m",)) ); assert_eq!(parse_metric_name("__1__"), Ok(("", "__1__",))); } }
C++
UTF-8
717
3.453125
3
[]
no_license
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: //in-order traversal bool isValidBST(TreeNode* root) { if(!root) { return true; } inOrderTraversal(root); for(int i=0; i<seq.size()-1; i++) { if(seq[i]>=seq[i+1]) { return false; } } return true; } private: vector<int> seq; void inOrderTraversal(TreeNode* root) { if(root) { inOrderTraversal(root->left); seq.push_back(root->val); inOrderTraversal(root->right); } } };
Python
UTF-8
5,555
2.90625
3
[]
no_license
import numpy as np import random from collections import deque #Funciones auxiliares def centroPersonal(objNvidia): (x, y) = objNvidia.Center # Pasamos el centro a int x, y = int(x), int(y) return (x,y) class Vehiculo: def __init__(self, objNvidia, idLoop): # Datos NVIDIA self.Area = objNvidia.Area self.Bottom = objNvidia.Bottom self.Center = objNvidia.Center self.ClassID = objNvidia.ClassID self.Confidence = objNvidia.Confidence self.Height = objNvidia.Height self.Instance = objNvidia.Instance self.Left = objNvidia.Left self.Right = objNvidia.Right self.Top = objNvidia.Top self.Width = objNvidia.Width # Datos personales self.Centro = centroPersonal(objNvidia) self.ID = idLoop self.numeroFramesSinDeteccionNueva = 0 # Para controlar frames en los que no se detecte # Memorias de las ultimas 50 posiciones (aprox 0.3s en modo MAX0) self.memoriaTop = deque([], 50) self.memoriaTop.append(objNvidia.Top) self.memoriaBottom = deque([], 50) self.memoriaBottom.append(objNvidia.Bottom) self.memoriaRight = deque([], 50) self.memoriaRight.append(objNvidia.Right) self.memoriaLeft = deque([], 50) self.memoriaLeft.append(objNvidia.Left) def relacionaConDeteccionNueva(self, objNuevo): # Actualizacion de info deteccion self.Area = objNuevo.Area self.Bottom = objNuevo.Bottom self.Center = objNuevo.Center self.ClassID = objNuevo.ClassID self.Confidence = objNuevo.Confidence self.Height = objNuevo.Height self.Instance = objNuevo.Instance self.Left = objNuevo.Left self.Right = objNuevo.Right self.Top = objNuevo.Top self.Width = objNuevo.Width self.Centro = centroPersonal(objNuevo) # Añadir a memoria self.memoriaTop.append(objNuevo.Top) self.memoriaBottom.append(objNuevo.Bottom) self.memoriaRight.append(objNuevo.Right) self.memoriaLeft.append(objNuevo.Left) print(f'MemoriaBott-{self.memoriaBottom}') # Actualizacion prediccion Kalman filter # if self.memoriaBottom. def noRelacionaConNuevo(self): self.numeroFramesSinDeteccionNueva += 1 # Actualizacion de info deteccion con la prediccion! self.Confidence = 0.00 # self.Top = # self.Bottom = # self.Left = # self.Right = return self.numeroFramesSinDeteccionNueva def getID(self): return self.ID def setID(self, id): self.ID = id def getCentro(self): return self.Centro def getPrediccionKalman(self): pass # (top, bottom, left, right) # Nvidia getters def getArea_nv(self): return self.Area def getBottom_nv(self): return self.Bottom def getCenter_nv(self): return self.Center def getClassID_nv(self): return self.ClassID def getConfidence_nv(self): return self.Confidence def getHeight_nv(self): return self.Height def getInstance_nv(self): return self.Instance def getLeft_nv(self): return self.Left def getRight_nv(self): return self.Right def getTop_nv(self): return self.Top def getWidth_nv(self): return self.Width class Peaton: pass # Algoritmos de Tracking def algoritmoTrackingVehiculos(vehiculosFrameAnterior, vehiculosFrameActual, limiteDistancia): def calculaMasCercanoAnterior(lista, indiv): indiv_centro = indiv.getCentro() lista_centros = list(map(lambda x: x.getCentro(), lista)) distancias = [] for centro in lista_centros: dist = np.sqrt( (indiv_centro[0] - centro[0])**2 + (indiv_centro[1] - centro[1])**2 ) # Distancia euclidea entre los centros distancias.append(dist) print(f' distancias -> {distancias}') dist_minima = np.min(distancias) arg_min = np.argmin(distancias) res = lista[arg_min] print(f'mascercanoAnterior = {res}, distancia = {dist_minima}') return res, dist_minima res = [] # Para los nuevos, comprobamos si son alguno de los anteriores y los relacionamos vactualaasignados = [] for nuevo in vehiculosFrameActual: if vehiculosFrameAnterior == []: break masCercanoAnterior, distancia = calculaMasCercanoAnterior(vehiculosFrameAnterior, nuevo) if distancia <= limiteDistancia: masCercanoAnterior.relacionaConDeteccionNueva(nuevo) vehiculosFrameAnterior.remove(masCercanoAnterior) # Eliminamos al anterior puesto que ya se ha relacionado vactualaasignados.append(nuevo) res.append(masCercanoAnterior) # Para los que no se relacionan, dependiendo del numero de frames que lleven sin relacion se olvidan o no for v in vehiculosFrameAnterior: if v not in res: a = v.noRelacionaConNuevo() if a <= 10: # 10 frames de margen res.append(v) # Para los que aparecen por primera vez en el frame nuevo (no se relacionan con ninguno anterior) for v in vehiculosFrameActual: if v not in vactualaasignados: v.setID(random.randrange(10,100)) res.append(v) return res
Java
UTF-8
21,029
1.5
2
[]
no_license
/* 1: */ package com.asinfo.as2.datosbase.controller; /* 2: */ /* 3: */ import com.asinfo.as2.controller.LanguageController; /* 4: */ import com.asinfo.as2.controller.PageControllerAS2; /* 5: */ import com.asinfo.as2.datosbase.servicio.ServicioCategoriaEmpresa; /* 6: */ import com.asinfo.as2.entities.CategoriaEmpresa; /* 7: */ import com.asinfo.as2.entities.CuentaContable; /* 8: */ import com.asinfo.as2.entities.DocumentoDigitalizado; /* 9: */ import com.asinfo.as2.entities.DocumentoDigitalizadoCategoriaEmpresa; /* 10: */ import com.asinfo.as2.entities.Organizacion; /* 11: */ import com.asinfo.as2.entities.Sucursal; /* 12: */ import com.asinfo.as2.nomina.configuracion.servicio.ServicioDocumentoDigitalizado; /* 13: */ import com.asinfo.as2.util.AppUtil; /* 14: */ import java.util.ArrayList; /* 15: */ import java.util.HashMap; /* 16: */ import java.util.List; /* 17: */ import java.util.Map; /* 18: */ import javax.annotation.PostConstruct; /* 19: */ import javax.ejb.EJB; /* 20: */ import javax.faces.bean.ManagedBean; /* 21: */ import javax.faces.bean.ViewScoped; /* 22: */ import org.apache.log4j.Logger; /* 23: */ import org.primefaces.component.datatable.DataTable; /* 24: */ import org.primefaces.model.LazyDataModel; /* 25: */ import org.primefaces.model.SortOrder; /* 26: */ /* 27: */ @ManagedBean /* 28: */ @ViewScoped /* 29: */ public class CategoriaEmpresaBean /* 30: */ extends PageControllerAS2 /* 31: */ { /* 32: */ private static final long serialVersionUID = -1812294963753017704L; /* 33: */ @EJB /* 34: */ protected ServicioCategoriaEmpresa servicioCategoriaEmpresa; /* 35: */ @EJB /* 36: */ private ServicioDocumentoDigitalizado servicioDocumentoDigitalizado; /* 37: */ private CategoriaEmpresa categoriaEmpresa; /* 38: */ private LazyDataModel<CategoriaEmpresa> listaCategoriaEmpresa; /* 39: */ private CuentaContable cuentaContable; /* 40: */ private DataTable dtCuentaContable; /* 41: */ private List<DocumentoDigitalizado> listaDocumentosDigitalizadosNoAsignados; /* 42: */ private DocumentoDigitalizado[] listaDocumentosDigitalizadosSeleccionados; /* 43: */ private List<DocumentoDigitalizadoCategoriaEmpresa> listaDocumentoDigitalizadoCategoriaEmpresa; /* 44: */ private DocumentoDigitalizadoCategoriaEmpresa documentoDigitalizadoCategoriaEmpresa; /* 45: */ private enumCuentaContableEditada cuentaContableEditada; /* 46: */ private DataTable dtCategoriaEmpresa; /* 47: */ /* 48: */ private static enum enumCuentaContableEditada /* 49: */ { /* 50: 71 */ CUENTA_CONTABLE_CLIENTE, CUENTA_CONTABLE_PROVEEDOR, CUENTA_CONTABLE_ANTICIPO_CLIENTE, CUENTA_CONTABLE_ANTICIPO_PROVEEDOR, CUENTA_CONTABLE_DESCUENTO_COMPRAS, CUENTA_CONTABLE_DESCUENTO_VENTAS, CUENTA_CONTABLE_SUELDO_POR_PAGAR, CUENTA_CONTABLE_ANTICIPO_CLIENTE_NOTA_CREDITO, CUENTA_CONTABLE_ANTICIPO_PROVEEDOR_NOTA_CREDITO, CUENTA_CONTABLE_IVA_PRESUNTIVO, CUENTA_CONTABLE_3X1000, CUENTA_CONTABLE_2X1000; /* 51: */ /* 52: */ private enumCuentaContableEditada() {} /* 53: */ } /* 54: */ /* 55: */ @PostConstruct /* 56: */ public void init() /* 57: */ { /* 58: 81 */ this.listaCategoriaEmpresa = new LazyDataModel() /* 59: */ { /* 60: */ private static final long serialVersionUID = 1L; /* 61: */ /* 62: */ public List<CategoriaEmpresa> load(int startIndex, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) /* 63: */ { /* 64: 88 */ List<CategoriaEmpresa> lista = new ArrayList(); /* 65: 89 */ boolean ordenar = sortOrder == SortOrder.ASCENDING; /* 66: */ /* 67: 91 */ lista = CategoriaEmpresaBean.this.servicioCategoriaEmpresa.obtenerListaPorPagina(startIndex, pageSize, sortField, ordenar, filters); /* 68: 92 */ CategoriaEmpresaBean.this.listaCategoriaEmpresa.setRowCount(CategoriaEmpresaBean.this.servicioCategoriaEmpresa.contarPorCriterio(filters)); /* 69: */ /* 70: 94 */ return lista; /* 71: */ } /* 72: */ }; /* 73: */ } /* 74: */ /* 75: */ public String editar() /* 76: */ { /* 77:107 */ if (getCategoriaEmpresa().getId() > 0) /* 78: */ { /* 79:108 */ this.categoriaEmpresa = this.servicioCategoriaEmpresa.cargarDetalle(getCategoriaEmpresa().getId()); /* 80:109 */ setEditado(true); /* 81: */ } /* 82: */ else /* 83: */ { /* 84:111 */ addInfoMessage(getLanguageController().getMensaje("msg_info_seleccionar")); /* 85: */ } /* 86:113 */ return ""; /* 87: */ } /* 88: */ /* 89: */ public String guardar() /* 90: */ { /* 91: */ try /* 92: */ { /* 93:124 */ this.servicioCategoriaEmpresa.guardar(getCategoriaEmpresa()); /* 94:125 */ addInfoMessage(getLanguageController().getMensaje("msg_info_guardar")); /* 95:126 */ limpiar(); /* 96:127 */ setEditado(false); /* 97: */ } /* 98: */ catch (Exception e) /* 99: */ { /* 100:129 */ addErrorMessage(getLanguageController().getMensaje("msg_error_guardar")); /* 101:130 */ LOG.error("ERROR AL GUARDAR DATOS", e); /* 102: */ } /* 103:132 */ return ""; /* 104: */ } /* 105: */ /* 106: */ public String eliminar() /* 107: */ { /* 108: */ try /* 109: */ { /* 110:143 */ this.servicioCategoriaEmpresa.eliminar(getCategoriaEmpresa()); /* 111:144 */ addInfoMessage(getLanguageController().getMensaje("msg_info_eliminar")); /* 112: */ } /* 113: */ catch (Exception e) /* 114: */ { /* 115:146 */ addErrorMessage(getLanguageController().getMensaje("msg_error_eliminar")); /* 116:147 */ LOG.error("ERROR AL ELIMINAR DATOS", e); /* 117: */ } /* 118:149 */ return ""; /* 119: */ } /* 120: */ /* 121: */ public String limpiar() /* 122: */ { /* 123:159 */ crearCategoriaEmpresa(); /* 124:160 */ this.listaDocumentoDigitalizadoCategoriaEmpresa = null; /* 125:161 */ return ""; /* 126: */ } /* 127: */ /* 128: */ public String cargarDatos() /* 129: */ { /* 130:171 */ return ""; /* 131: */ } /* 132: */ /* 133: */ public void crearCategoriaEmpresa() /* 134: */ { /* 135:180 */ this.categoriaEmpresa = new CategoriaEmpresa(); /* 136:181 */ this.categoriaEmpresa.setIdOrganizacion(AppUtil.getOrganizacion().getIdOrganizacion()); /* 137:182 */ this.categoriaEmpresa.setIdSucursal(AppUtil.getSucursal().getIdSucursal()); /* 138: */ } /* 139: */ /* 140: */ public void actualizarCuentaContableCliente() /* 141: */ { /* 142:187 */ this.cuentaContableEditada = enumCuentaContableEditada.CUENTA_CONTABLE_CLIENTE; /* 143:188 */ this.cuentaContable = this.categoriaEmpresa.getCuentaContableCliente(); /* 144: */ } /* 145: */ /* 146: */ public void actualizarCuentaContableProveedor() /* 147: */ { /* 148:192 */ this.cuentaContableEditada = enumCuentaContableEditada.CUENTA_CONTABLE_PROVEEDOR; /* 149:193 */ this.cuentaContable = this.categoriaEmpresa.getCuentaContableProveedor(); /* 150: */ } /* 151: */ /* 152: */ public void actualizarCuentaContableAnticipoCliente() /* 153: */ { /* 154:197 */ this.cuentaContableEditada = enumCuentaContableEditada.CUENTA_CONTABLE_ANTICIPO_CLIENTE; /* 155:198 */ this.cuentaContable = this.categoriaEmpresa.getCuentaContableAnticipoCliente(); /* 156: */ } /* 157: */ /* 158: */ public void actualizarCuentaContableAnticipoProveedor() /* 159: */ { /* 160:202 */ this.cuentaContableEditada = enumCuentaContableEditada.CUENTA_CONTABLE_ANTICIPO_PROVEEDOR; /* 161:203 */ this.cuentaContable = this.categoriaEmpresa.getCuentaContableAnticipoProveedor(); /* 162: */ } /* 163: */ /* 164: */ public void actualizarCuentaContableSueldoPorPagar() /* 165: */ { /* 166:207 */ this.cuentaContableEditada = enumCuentaContableEditada.CUENTA_CONTABLE_SUELDO_POR_PAGAR; /* 167:208 */ this.cuentaContable = this.categoriaEmpresa.getCuentaContableSueldoPorPagar(); /* 168: */ } /* 169: */ /* 170: */ public void actualizarCuentaContableAnticipoClienteNotaCredito() /* 171: */ { /* 172:212 */ this.cuentaContableEditada = enumCuentaContableEditada.CUENTA_CONTABLE_ANTICIPO_CLIENTE_NOTA_CREDITO; /* 173:213 */ this.cuentaContable = this.categoriaEmpresa.getCuentaContableAnticipoClienteNotaCredito(); /* 174: */ } /* 175: */ /* 176: */ public void actualizarCuentaContableAnticipoProveedorNotaCredito() /* 177: */ { /* 178:217 */ this.cuentaContableEditada = enumCuentaContableEditada.CUENTA_CONTABLE_ANTICIPO_PROVEEDOR_NOTA_CREDITO; /* 179:218 */ this.cuentaContable = this.categoriaEmpresa.getCuentaContableAnticipoProveedorNotaCredito(); /* 180: */ } /* 181: */ /* 182: */ public void actualizarCuentaContableIvaPresuntivo() /* 183: */ { /* 184:222 */ this.cuentaContableEditada = enumCuentaContableEditada.CUENTA_CONTABLE_IVA_PRESUNTIVO; /* 185:223 */ this.cuentaContable = this.categoriaEmpresa.getCuentaContableIvaPresuntivo(); /* 186: */ } /* 187: */ /* 188: */ public void actualizarCuentaContable3X1000() /* 189: */ { /* 190:227 */ this.cuentaContableEditada = enumCuentaContableEditada.CUENTA_CONTABLE_3X1000; /* 191:228 */ this.cuentaContable = this.categoriaEmpresa.getCuentaContable3X1000(); /* 192: */ } /* 193: */ /* 194: */ public void actualizarCuentaContable2X1000() /* 195: */ { /* 196:232 */ this.cuentaContableEditada = enumCuentaContableEditada.CUENTA_CONTABLE_2X1000; /* 197:233 */ this.cuentaContable = this.categoriaEmpresa.getCuentaContable2X1000(); /* 198: */ } /* 199: */ /* 200: */ public void cargarCuentaContable() /* 201: */ { /* 202:238 */ this.cuentaContable = ((CuentaContable)this.dtCuentaContable.getRowData()); /* 203:240 */ switch (2.$SwitchMap$com$asinfo$as2$datosbase$controller$CategoriaEmpresaBean$enumCuentaContableEditada[this.cuentaContableEditada.ordinal()]) /* 204: */ { /* 205: */ case 1: /* 206:243 */ this.categoriaEmpresa.setCuentaContableCliente(this.cuentaContable); /* 207:244 */ break; /* 208: */ case 2: /* 209:247 */ this.categoriaEmpresa.setCuentaContableProveedor(this.cuentaContable); /* 210:248 */ break; /* 211: */ case 3: /* 212:251 */ this.categoriaEmpresa.setCuentaContableAnticipoCliente(this.cuentaContable); /* 213:252 */ break; /* 214: */ case 4: /* 215:255 */ this.categoriaEmpresa.setCuentaContableAnticipoProveedor(this.cuentaContable); /* 216:256 */ break; /* 217: */ case 5: /* 218:259 */ this.categoriaEmpresa.setCuentaContableSueldoPorPagar(this.cuentaContable); /* 219:260 */ break; /* 220: */ case 6: /* 221:263 */ this.categoriaEmpresa.setCuentaContableAnticipoClienteNotaCredito(this.cuentaContable); /* 222:264 */ break; /* 223: */ case 7: /* 224:267 */ this.categoriaEmpresa.setCuentaContableAnticipoProveedorNotaCredito(this.cuentaContable); /* 225:268 */ break; /* 226: */ case 8: /* 227:271 */ this.categoriaEmpresa.setCuentaContableIvaPresuntivo(this.cuentaContable); /* 228:272 */ break; /* 229: */ case 9: /* 230:275 */ this.categoriaEmpresa.setCuentaContable3X1000(this.cuentaContable); /* 231:276 */ break; /* 232: */ case 10: /* 233:279 */ this.categoriaEmpresa.setCuentaContable2X1000(this.cuentaContable); /* 234:280 */ break; /* 235: */ } /* 236: */ } /* 237: */ /* 238: */ public CategoriaEmpresa getCategoriaEmpresa() /* 239: */ { /* 240:293 */ if (this.categoriaEmpresa == null) { /* 241:294 */ crearCategoriaEmpresa(); /* 242: */ } /* 243:296 */ return this.categoriaEmpresa; /* 244: */ } /* 245: */ /* 246: */ public void setCategoriaEmpresa(CategoriaEmpresa categoriaEmpresa) /* 247: */ { /* 248:306 */ this.categoriaEmpresa = categoriaEmpresa; /* 249: */ } /* 250: */ /* 251: */ public LazyDataModel<CategoriaEmpresa> getListaCategoriaEmpresa() /* 252: */ { /* 253:315 */ return this.listaCategoriaEmpresa; /* 254: */ } /* 255: */ /* 256: */ public void setListaCategoriaEmpresa(LazyDataModel<CategoriaEmpresa> listaCategoriaEmpresa) /* 257: */ { /* 258:325 */ this.listaCategoriaEmpresa = listaCategoriaEmpresa; /* 259: */ } /* 260: */ /* 261: */ public DataTable getDtCategoriaEmpresa() /* 262: */ { /* 263:334 */ return this.dtCategoriaEmpresa; /* 264: */ } /* 265: */ /* 266: */ public void setDtCategoriaEmpresa(DataTable dtCategoriaEmpresa) /* 267: */ { /* 268:344 */ this.dtCategoriaEmpresa = dtCategoriaEmpresa; /* 269: */ } /* 270: */ /* 271: */ public enumCuentaContableEditada getCuentaContableEditada() /* 272: */ { /* 273:353 */ return this.cuentaContableEditada; /* 274: */ } /* 275: */ /* 276: */ public void setCuentaContableEditada(enumCuentaContableEditada cuentaContableEditada) /* 277: */ { /* 278:363 */ this.cuentaContableEditada = cuentaContableEditada; /* 279: */ } /* 280: */ /* 281: */ public CuentaContable getCuentaContable() /* 282: */ { /* 283:372 */ return this.cuentaContable; /* 284: */ } /* 285: */ /* 286: */ public void setCuentaContable(CuentaContable cuentaContable) /* 287: */ { /* 288:383 */ this.cuentaContable = cuentaContable; /* 289: */ } /* 290: */ /* 291: */ public DataTable getDtCuentaContable() /* 292: */ { /* 293:387 */ return this.dtCuentaContable; /* 294: */ } /* 295: */ /* 296: */ public void setDtCuentaContable(DataTable dtCuentaContable) /* 297: */ { /* 298:391 */ this.dtCuentaContable = dtCuentaContable; /* 299: */ } /* 300: */ /* 301: */ public List<DocumentoDigitalizado> getListaDocumentosDigitalizadosNoAsignados() /* 302: */ { /* 303:395 */ return this.listaDocumentosDigitalizadosNoAsignados; /* 304: */ } /* 305: */ /* 306: */ public void setListaDocumentosDigitalizadosNoAsignados(List<DocumentoDigitalizado> listaDocumentosDigitalizadosNoAsignados) /* 307: */ { /* 308:399 */ this.listaDocumentosDigitalizadosNoAsignados = listaDocumentosDigitalizadosNoAsignados; /* 309: */ } /* 310: */ /* 311: */ public DocumentoDigitalizado[] getListaDocumentosDigitalizadosSeleccionados() /* 312: */ { /* 313:403 */ return this.listaDocumentosDigitalizadosSeleccionados; /* 314: */ } /* 315: */ /* 316: */ public void setListaDocumentosDigitalizadosSeleccionados(DocumentoDigitalizado[] listaDocumentosDigitalizadosSeleccionados) /* 317: */ { /* 318:407 */ this.listaDocumentosDigitalizadosSeleccionados = listaDocumentosDigitalizadosSeleccionados; /* 319: */ } /* 320: */ /* 321: */ public void cargarDocumentosDigitalizadosNoAsignados() /* 322: */ { /* 323:411 */ this.listaDocumentosDigitalizadosSeleccionados = null; /* 324:412 */ Map<String, String> filtros = agregarFiltroOrganizacion(null); /* 325:413 */ this.listaDocumentosDigitalizadosNoAsignados = this.servicioDocumentoDigitalizado.obtenerListaCombo("nombre", true, filtros); /* 326: */ /* 327:415 */ HashMap<Integer, DocumentoDigitalizado> documentosMap = new HashMap(); /* 328:416 */ for (DocumentoDigitalizado docDigitalizado : this.listaDocumentosDigitalizadosNoAsignados) { /* 329:417 */ documentosMap.put(Integer.valueOf(docDigitalizado.getIdDocumentoDigitalizado()), docDigitalizado); /* 330: */ } /* 331:420 */ for (DocumentoDigitalizadoCategoriaEmpresa docDigitalizadoCategoriaEmpresa : this.categoriaEmpresa.getListaDocumentoDigitalizadoCategoriaEmpresa()) { /* 332:421 */ if (!docDigitalizadoCategoriaEmpresa.isEliminado()) { /* 333:422 */ documentosMap.remove(Integer.valueOf(docDigitalizadoCategoriaEmpresa.getDocumentoDigitalizado().getIdDocumentoDigitalizado())); /* 334: */ } /* 335: */ } /* 336:426 */ this.listaDocumentosDigitalizadosNoAsignados = new ArrayList(documentosMap.values()); /* 337: */ } /* 338: */ /* 339: */ public String agregarDocumentosDigitalizados() /* 340: */ { /* 341:430 */ if (this.listaDocumentosDigitalizadosSeleccionados != null) { /* 342:431 */ for (DocumentoDigitalizado documento : this.listaDocumentosDigitalizadosSeleccionados) /* 343: */ { /* 344:432 */ boolean encontre = false; /* 345:433 */ for (DocumentoDigitalizadoCategoriaEmpresa docDigitalizadoCategoriaEmpresa : this.categoriaEmpresa /* 346:434 */ .getListaDocumentoDigitalizadoCategoriaEmpresa()) { /* 347:435 */ if (docDigitalizadoCategoriaEmpresa.getDocumentoDigitalizado().getId() == documento.getId()) /* 348: */ { /* 349:436 */ docDigitalizadoCategoriaEmpresa.setEliminado(false); /* 350:437 */ encontre = true; /* 351:438 */ break; /* 352: */ } /* 353: */ } /* 354:441 */ if (!encontre) /* 355: */ { /* 356:442 */ DocumentoDigitalizadoCategoriaEmpresa documentoCategoriaEmpresa = new DocumentoDigitalizadoCategoriaEmpresa(); /* 357:443 */ documentoCategoriaEmpresa.setDocumentoDigitalizado(documento); /* 358:444 */ documentoCategoriaEmpresa.setCategoriaEmpresa(this.categoriaEmpresa); /* 359:445 */ this.categoriaEmpresa.getListaDocumentoDigitalizadoCategoriaEmpresa().add(documentoCategoriaEmpresa); /* 360:446 */ this.listaDocumentosDigitalizadosNoAsignados.remove(documento); /* 361: */ } /* 362: */ } /* 363: */ } /* 364:451 */ this.listaDocumentosDigitalizadosSeleccionados = null; /* 365:452 */ this.listaDocumentoDigitalizadoCategoriaEmpresa = null; /* 366: */ /* 367:454 */ return ""; /* 368: */ } /* 369: */ /* 370: */ public String eliminarDocumentoDigitalizadoCategoriaEmpresa() /* 371: */ { /* 372:458 */ this.documentoDigitalizadoCategoriaEmpresa.setEliminado(true); /* 373:459 */ this.listaDocumentoDigitalizadoCategoriaEmpresa = null; /* 374:460 */ return ""; /* 375: */ } /* 376: */ /* 377: */ public DocumentoDigitalizadoCategoriaEmpresa getDocumentoDigitalizadoCategoriaEmpresa() /* 378: */ { /* 379:464 */ return this.documentoDigitalizadoCategoriaEmpresa; /* 380: */ } /* 381: */ /* 382: */ public void setDocumentoDigitalizadoCategoriaEmpresa(DocumentoDigitalizadoCategoriaEmpresa documentoDigitalizadoCategoriaEmpresa) /* 383: */ { /* 384:468 */ this.documentoDigitalizadoCategoriaEmpresa = documentoDigitalizadoCategoriaEmpresa; /* 385: */ } /* 386: */ /* 387: */ public List<DocumentoDigitalizadoCategoriaEmpresa> getListaDocumentoDigitalizadoCategoriaEmpresa() /* 388: */ { /* 389:472 */ if (this.listaDocumentoDigitalizadoCategoriaEmpresa == null) /* 390: */ { /* 391:473 */ this.listaDocumentoDigitalizadoCategoriaEmpresa = new ArrayList(); /* 392:474 */ for (DocumentoDigitalizadoCategoriaEmpresa documento : this.categoriaEmpresa.getListaDocumentoDigitalizadoCategoriaEmpresa()) { /* 393:475 */ if (!documento.isEliminado()) { /* 394:476 */ this.listaDocumentoDigitalizadoCategoriaEmpresa.add(documento); /* 395: */ } /* 396: */ } /* 397: */ } /* 398:480 */ return this.listaDocumentoDigitalizadoCategoriaEmpresa; /* 399: */ } /* 400: */ /* 401: */ public void setListaDocumentoDigitalizadoCategoriaEmpresa(List<DocumentoDigitalizadoCategoriaEmpresa> listaDocumentoDigitalizadoCategoriaEmpresa) /* 402: */ { /* 403:484 */ this.listaDocumentoDigitalizadoCategoriaEmpresa = listaDocumentoDigitalizadoCategoriaEmpresa; /* 404: */ } /* 405: */ } /* Location: C:\backups\AS2(26-10-2017)\WEB-INF\classes\ * Qualified Name: com.asinfo.as2.datosbase.controller.CategoriaEmpresaBean * JD-Core Version: 0.7.0.1 */
Markdown
UTF-8
2,281
2.609375
3
[]
no_license
A Flamework library for decoding User Agent strings =================================================== This library is designed to be used with <a href="https://github.com/exflickr/flamework">Flamework</a>, but works standalone too. Usage: # single shot $ret = useragent_decode($ua); # when decoding in batches $ret = useragent_decode_cached($ua); # return structure $ret = array( 'agent' => 'chrome', 'agent_version' => '15.0.874.121', 'engine' => 'webkit', 'engine_version' => '535.2', 'os' => 'osx', 'os_version' => '10.7.2', ); Possible values --------------- <code>agent</code> will be one of the following, with the full version number in <code>agent_version</code>: * <code>chrome</code> * <code>safari</code> * <code>firefox</code> * <code>msie</code> * <code>dalvik</code> (android VM, not actually the browser) * <code>opera</code> * <code>netscape</code> * <code>konqueror</code> * <code>blackberry</code> (pre-safari) <code>engine</code> contains the rendering engine, with the full version number in <code>engine_version</code>: * <code>webkit</code> * <code>gecko</code> * <code>trident</code> * <code>presto</code> <code>os</code> and <code>os_version</code> contain the platform, with the following values: * <code>osx/n.n(.n)</code> * <code>iphone/n.n(.n)</code> * <code>ipad/n.n(.n)</code> * <code>ipod/n.n(.n)</code> * <code>windows/xp</code> * <code>windows/xp-x64</code> * <code>windows/vista</code> * <code>windows/7</code> * <code>linux/i686</code> * <code>linux/x86_64</code> * <code>android/n.n(.n)</code> * <code>blackberry/$model</code> When a field does not match one of the known values, it will be set to null. Caveats ------- * Not all browsers, rendering engines and platforms are supported - this is by design! Only common agents are included. * We just return <code>"linux/i686"</code> rather than e.g. <code>"Ubuntu"</code>, since most Linux flavors don't give distro, plus nobody cares. * Chromium returns <code>"chrome"</code> - same thing anyway, plus it has a different version number. * We differentiate iPad, iPhone and iPod, even though they are the same OS. You can easily patch this locally if you don't need to know.
Java
UTF-8
8,014
1.867188
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2016 Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.tetopology.management.api.link; import com.google.common.base.MoreObjects; import com.google.common.base.Objects; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import org.onosproject.tetopology.management.api.EncodingType; import org.onosproject.tetopology.management.api.SwitchingType; import org.onosproject.tetopology.management.api.TeStatus; import java.util.BitSet; import java.util.List; /** * Representation of link common attributes. */ public class CommonLinkData { private final TeStatus adminStatus; private final TeStatus opStatus; private final BitSet flags; private final SwitchingType switchingLayer; private final EncodingType encodingLayer; private final ExternalLink externalLink; private final UnderlayPath underlayPath; private final TePathAttributes teAttributes; private final List<Long> interLayerLocks; private final LinkBandwidth bandwidth; private final Long adminGroup; /** * Creates an instance of CommonLinkData. * * @param adminStatus the admin status * @param opStatus the operational Status * @param flags the flags * @param switchingLayer the network layer switching type * @param encodingLayer the network layer encoding type * @param externalLink the external link specific attributes * @param underlayPath the link underlay path and supporting tunnel * @param teAttributes the link path TE attributes * @param adminGroup the administrative group * @param interLayerLocks the supported inter-layer locks * @param bandwidth the link maximum and available bandwidth at * each priority level */ public CommonLinkData(TeStatus adminStatus, TeStatus opStatus, BitSet flags, SwitchingType switchingLayer, EncodingType encodingLayer, ExternalLink externalLink, UnderlayPath underlayPath, TePathAttributes teAttributes, Long adminGroup, List<Long> interLayerLocks, LinkBandwidth bandwidth) { this.adminStatus = adminStatus; this.opStatus = opStatus; this.flags = flags; this.switchingLayer = switchingLayer; this.encodingLayer = encodingLayer; this.externalLink = externalLink; this.underlayPath = underlayPath; this.teAttributes = teAttributes; this.adminGroup = adminGroup; this.interLayerLocks = interLayerLocks != null ? Lists.newArrayList(interLayerLocks) : null; this.bandwidth = bandwidth; } /** * Creates an instance of CommonLinkData with a TeLink. * * @param link the TE link */ public CommonLinkData(TeLink link) { this.adminStatus = link.adminStatus(); this.opStatus = link.opStatus(); this.flags = link.flags(); this.switchingLayer = link.switchingLayer(); this.encodingLayer = link.encodingLayer(); this.externalLink = link.externalLink(); this.underlayPath = new UnderlayPath(link); this.teAttributes = new TePathAttributes(link); this.adminGroup = link.administrativeGroup(); this.interLayerLocks = link.interLayerLocks() != null ? Lists.newArrayList(link.interLayerLocks()) : null; this.bandwidth = new LinkBandwidth(link); } /** * Returns the admin status. * * @return the admin status */ public TeStatus adminStatus() { return adminStatus; } /** * Returns the operational status. * * @return the optional status */ public TeStatus opStatus() { return opStatus; } /** * Returns the flags. * * @return the flags */ public BitSet flags() { return flags; } /** * Returns the network layer switching type for this link. * * @return the switching layer type */ public SwitchingType switchingLayer() { return switchingLayer; } /** * Returns the network layer encoding type for this link. * * @return the encoding type */ public EncodingType encodingLayer() { return encodingLayer; } /** * Returns the external link. * * @return the external link */ public ExternalLink externalLink() { return externalLink; } /** * Returns the link underlay path and tunnel. * * @return the underlay path */ public UnderlayPath underlayPath() { return underlayPath; } /** * Returns the path TE attributes. * * @return the path TE Attributes */ public TePathAttributes teAttributes() { return teAttributes; } /** * Returns the link administrative group. * * @return the admin group */ public Long adminGroup() { return adminGroup; } /** * Returns the supported inter-layer locks. * * @return the inter-layer locks */ public List<Long> interLayerLocks() { if (interLayerLocks == null) { return null; } return ImmutableList.copyOf(interLayerLocks); } /** * Returns the link maximum and available bandwidth at each priority level. * * @return the bandwidth */ public LinkBandwidth bandwidth() { return bandwidth; } @Override public int hashCode() { return Objects.hashCode(adminStatus, opStatus, flags, switchingLayer, encodingLayer, externalLink, underlayPath, teAttributes, interLayerLocks, bandwidth); } @Override public boolean equals(Object object) { if (this == object) { return true; } if (object instanceof CommonLinkData) { CommonLinkData that = (CommonLinkData) object; return Objects.equal(adminStatus, that.adminStatus) && Objects.equal(opStatus, that.opStatus) && Objects.equal(flags, that.flags) && Objects.equal(switchingLayer, that.switchingLayer) && Objects.equal(encodingLayer, that.encodingLayer) && Objects.equal(externalLink, that.externalLink) && Objects.equal(underlayPath, that.underlayPath) && Objects.equal(teAttributes, that.teAttributes) && Objects.equal(interLayerLocks, that.interLayerLocks) && Objects.equal(bandwidth, that.bandwidth); } return false; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("adminStatus", adminStatus) .add("opStatus", opStatus) .add("flags", flags) .add("switchingLayer", switchingLayer) .add("encodingLayer", encodingLayer) .add("externalLink", externalLink) .add("underlayPath", underlayPath) .add("teAttributes", teAttributes) .add("interLayerLocks", interLayerLocks) .add("bandwidth", bandwidth) .toString(); } }
C#
UTF-8
199
2.625
3
[]
no_license
class ProviderService { public TResult Interact<TResult> (Func<Foobar, TResult> lambdaCode) { var x = new Foobar(); Initialize(x); //or whatever return lambdaCode(x); } }
C++
UTF-8
6,145
2.609375
3
[]
no_license
#include "Application.h" const int WINDOW_WIDTH = 1920; const int WINDOW_HEIGHT = 1080; Application::Application() :_windowWidth(WINDOW_WIDTH) ,_windowHeight(WINDOW_HEIGHT) { glfwInit(); _window = glfwCreateWindow(_windowWidth, _windowHeight, "PBR Application", glfwGetPrimaryMonitor(), NULL); glfwMakeContextCurrent(_window); glewInit(); } Application::~Application() { delete _masterRenderer; glfwTerminate(); } int activeSkybox = 0; glm::vec3 forwardVec = {1, 0, 0}, cameraPos = {-50, 0, 0}; bool usePBR = false; void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) { if(key == GLFW_KEY_ESCAPE) { glfwSetWindowShouldClose(window, true); } else if(key == GLFW_KEY_0 && action == GLFW_PRESS) activeSkybox = 0; else if(key == GLFW_KEY_1 && action == GLFW_PRESS) activeSkybox = 1; else if(key == GLFW_KEY_2 && action == GLFW_PRESS) activeSkybox = 2; else if(key == GLFW_KEY_3 && action == GLFW_PRESS) activeSkybox = 3; else if(key == GLFW_KEY_4 && action == GLFW_PRESS) activeSkybox = 4; if(key == GLFW_KEY_P && action == GLFW_PRESS) usePBR = !usePBR; GLfloat movementFactor = 5; glm::vec3 right = glm::normalize(glm::cross(forwardVec, glm::vec3(0, 1, 0))); if (key == GLFW_KEY_W && (action == GLFW_PRESS || action == GLFW_REPEAT)) cameraPos += movementFactor * forwardVec; if (key == GLFW_KEY_S && (action == GLFW_PRESS || action == GLFW_REPEAT)) cameraPos -= movementFactor * forwardVec; if (key == GLFW_KEY_D && (action == GLFW_PRESS || action == GLFW_REPEAT)) cameraPos += movementFactor * right; if (key == GLFW_KEY_A && (action == GLFW_PRESS || action == GLFW_REPEAT)) cameraPos -= movementFactor * right; } bool firstMouse = true; float lastX, lastY, yaw = 0, pitch = 0; void MouseHandler(GLFWwindow *window, double mouseX, double mouseY) { if (firstMouse) { lastX = mouseX; lastY = mouseY; firstMouse = false; } float xoffset = mouseX - lastX; float yoffset = lastY - mouseY; lastX = mouseX; lastY = mouseY; float sensitivity = 0.3f; xoffset *= sensitivity; yoffset *= sensitivity; yaw += xoffset; pitch += yoffset; if (pitch > 89.0f) pitch = 89.0f; if (pitch < -89.0f) pitch = 89.0f; forwardVec.x = cos(yaw * 3.14 / 180) * cos(pitch * 3.14 / 180); forwardVec.y = sin(pitch * 3.14 / 180); forwardVec.z = sin(yaw * 3.14 / 180) * cos(pitch * 3.14 / 180); forwardVec = glm::normalize(forwardVec); } void Application::run() { Material material1("Resources/Cerberus/Textures/Cerberus_A.tga", "Resources/Cerberus/Textures/Cerberus_N.tga", "Resources/Cerberus/Textures/Cerberus_M.tga", "Resources/Cerberus/Textures/Cerberus_R.tga", true); Material material2("Resources/Cerberus/Textures/Cerberus_A.tga", "Resources/Cerberus/Textures/Cerberus_N.tga", "Resources/Cerberus/Textures/Cerberus_M.tga", "Resources/Cerberus/Textures/Cerberus_R.tga", false); Cubemap cubeMap0("Resources/Textures/Tokyo_BigSight_3k.hdr"); Cubemap cubeMap1("Resources/Textures/Frozen_Waterfall_Ref.hdr"); Cubemap cubeMap2("Resources/Textures/Brooklyn_Bridge_Planks_2k.hdr"); Cubemap cubeMap3("Resources/Textures/Factory_Catwalk_2k.hdr"); Cubemap cubeMap4("Resources/Textures/Milkyway_small.hdr"); Tag tag = Mesh; Renderable object1("Resources/Cerberus/Cerberus_LP.obj", material1, tag); Renderable object2("Resources/Cerberus/Cerberus_LP.obj", material2, tag); PointLight pLight1(glm::vec3(0.0f, 100.0f, 0.0f), glm::vec3(2000.0f, 2000.0f, 2000.0f)); PointLight pointLights[1] = {pLight1}; _masterRenderer = new MasterRenderer(&_mainCamera, pointLights, 1); glfwSetKeyCallback(_window, keyCallback); glfwSetCursorPosCallback(_window, MouseHandler); glfwSetInputMode(_window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); double lastTime = glfwGetTime(); int nbFrames = 0; while(!glfwWindowShouldClose(_window)) { if(glfwGetTime() - lastTime > 0.0166) { lastTime = glfwGetTime(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); _mainCamera.setMatrix(cameraPos, cameraPos + forwardVec); if(activeSkybox == 0) { _masterRenderer->renderCubemap(cubeMap0); if(usePBR) _masterRenderer->render(object1, cubeMap0); else _masterRenderer->render(object2, cubeMap0); } else if(activeSkybox == 1) { _masterRenderer->renderCubemap(cubeMap1); if(usePBR) _masterRenderer->render(object1, cubeMap1); else _masterRenderer->render(object2, cubeMap1); } else if(activeSkybox == 2) { _masterRenderer->renderCubemap(cubeMap2); if(usePBR) _masterRenderer->render(object1, cubeMap2); else _masterRenderer->render(object2, cubeMap2); } else if(activeSkybox == 3) { _masterRenderer->renderCubemap(cubeMap3); if(usePBR) _masterRenderer->render(object1, cubeMap3); else _masterRenderer->render(object2, cubeMap3); } else if(activeSkybox == 4) { _masterRenderer->renderCubemap(cubeMap4); if(usePBR) _masterRenderer->render(object1, cubeMap4); else _masterRenderer->render(object2, cubeMap4); } glfwSwapBuffers(_window); glfwPollEvents(); } } glfwTerminate(); }
TypeScript
UTF-8
3,203
2.640625
3
[ "MIT" ]
permissive
import { KeySelector, ParametricKeySelector } from 're-reselect'; import { isPropSelector } from './createPropSelector'; import { arePathsEqual, defaultKeySelector, isCachedSelector } from './helpers'; import { isComposedKeySelector, KeySelectorComposer, } from './createKeySelectorComposer'; const areSelectorsEqual = (selector: unknown, another: unknown) => { if (selector === another) { return true; } if (isPropSelector(selector) && isPropSelector(another)) { return arePathsEqual(selector.path, another.path); } return false; }; const flatKeySelectors = <S, P>( keySelectors: (KeySelector<S> | ParametricKeySelector<S, P>)[], ) => { const result: typeof keySelectors = []; for (let i = 0; i < keySelectors.length; i += 1) { const keySelector = keySelectors[i]; if (isComposedKeySelector(keySelector)) { result.push(...flatKeySelectors(keySelector.dependencies)); } else { result.push(keySelector); } } return result; }; const uniqKeySelectors = <S, P>( keySelectors: (KeySelector<S> | ParametricKeySelector<S, P>)[], ) => { const result: typeof keySelectors = []; for (let i = 0; i < keySelectors.length; i += 1) { const keySelector = keySelectors[i]; const isKeySelectorAdded = result.some((resultKeySelector) => areSelectorsEqual(keySelector, resultKeySelector), ); if (!isKeySelectorAdded) { result.push(keySelector); } } return result; }; export const excludeDefaultSelectors = <S, P>( keySelectors: (KeySelector<S> | ParametricKeySelector<S, P>)[], ) => { const result: typeof keySelectors = []; for (let i = 0; i < keySelectors.length; i += 1) { const keySelector = keySelectors[i]; if (keySelector !== defaultKeySelector) { result.push(keySelector); } } return result; }; export function createKeySelectorCreator( keySelectorComposer: KeySelectorComposer, ): <S, D>(selectorInputs: { inputSelectors: D; keySelector?: KeySelector<S>; }) => KeySelector<S>; export function createKeySelectorCreator( keySelectorComposer: KeySelectorComposer, ): <S, P, D>(selectorInputs: { inputSelectors: D; keySelector?: ParametricKeySelector<S, P>; }) => ParametricKeySelector<S, P>; export function createKeySelectorCreator( keySelectorComposer: KeySelectorComposer, ) { return <S, P>({ inputSelectors, keySelector, }: { inputSelectors: unknown[]; keySelector?: KeySelector<S> | ParametricKeySelector<S, P>; }) => { let keySelectors: (KeySelector<S> | ParametricKeySelector<S, P>)[] = []; if (keySelector) { keySelectors.push(keySelector); } inputSelectors.forEach((selector) => { if (isCachedSelector(selector)) { keySelectors.push(selector.keySelector); } }); keySelectors = flatKeySelectors(keySelectors); keySelectors = uniqKeySelectors(keySelectors); keySelectors = excludeDefaultSelectors(keySelectors); if (keySelectors.length === 0) { return defaultKeySelector; } if (keySelectors.length === 1) { const [resultSelector] = keySelectors; return resultSelector; } return keySelectorComposer(...keySelectors); }; }
Java
UTF-8
397
1.953125
2
[]
no_license
package com.ward.services; import com.ward.entities.CreditCard; import com.ward.entities.Guest; import org.springframework.data.repository.CrudRepository; import java.util.List; /** * Created by Troy on 12/6/16. */ public interface CreditCardRepository extends CrudRepository<CreditCard,Integer> { CreditCard findFirstByType(String type); List<CreditCard> findByGuest(Guest guest); }
Python
UTF-8
1,549
3.875
4
[]
no_license
# Follow up for "Unique Paths": # # Now consider if some obstacles are added to the grids. How many unique paths would there be? # # An obstacle and empty space is marked as 1 and 0 respectively in the grid. # # For example, # There is one obstacle in the middle of a 3x3 grid as illustrated below. # # [ # [0,0,0], # [0,1,0], # [0,0,0] # ] # The total number of unique paths is 2. # # Note: m and n will be at most 100. # @param {Integer[][]} obstacle_grid # @return {Integer} class Solution: def uniquePathsWithObstacles(self, obstacleGrid): """ :type obstacleGrid: List[List[int]] :rtype: int """ ob = obstacleGrid m, n = len(ob), len(ob[0]) if not m or ob[m-1][n-1] == 1: return 0 for i in reversed(range(n)): if ob[m-1][i] == 0: ob[m-1][i] = 1 else: for j in range(i + 1): ob[m-1][j] = 0 break for i in reversed(range(0, m - 1)): # xrange from 1 if ob[i][n - 1] == 0: ob[i][n - 1] = 1 else: for j in range(i + 1): ob[j][n - 1] = 0 break for i in reversed(range(m - 1)): for j in reversed(range(n - 1)): ob[i][j] = 0 if ob[i][j] == 1 else ob[i+1][j] + ob[i][j+1] return ob[0][0] ob = [[0, 0, 0], [0, 1, 0], [0, 0, 0]] s = Solution() print (s.uniquePathsWithObstacles(ob))
PHP
UTF-8
371
2.5625
3
[ "MIT" ]
permissive
<?php namespace App\Exceptions; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Exception\HttpException; class BadRequest extends HttpException { public static function invalidRole($role): self { return new static(Response::HTTP_BAD_REQUEST, 'Role '.$role.' does not exist.', null, []); } }
C#
UTF-8
6,433
2.671875
3
[]
no_license
using MorphAnalysis.HelperClasses; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace MorphAnalysis.TablesDataInitialization { public partial class TableSolutions : Form { private string id; private MorphModel db; //кешування рішень функцій private CacheData solOfFuncCacheData = CacheData.GetInstance(); //Завантажити всі відібрані функції з ОЗУ List<Function> funcList; public TableSolutions() { InitializeComponent(); db = new MorphModel(); funcList = solOfFuncCacheData.GetListElements<Function>(); } private void TableSolutions_Load(object sender, EventArgs e) { db.Solutions.Load(); dataGridView1.DataSource = db.Solutions.Local.ToBindingList(); comboBox1.Items.Clear(); //Заповнити комбо-бокс тільки іменами функції comboBox1.Items.AddRange(funcList.Select(f=>f.name).ToArray()); //Перейменувати заголовки стовбців dataGridView1.Columns[0].HeaderText = "ID"; dataGridView1.Columns[1].HeaderText = "Назва"; dataGridView1.Columns[2].HeaderText = "Текстовий опис";//"Характеристика"; dataGridView1.Columns[3].HeaderText = "Бібліографічний опис"; //Cховати стовбці dataGridView1.Columns[3].Visible = false; dataGridView1.Columns[4].Visible = false; dataGridView1.Columns[5].Visible = false; dataGridView1.Columns[6].Visible = false; dataGridView1.Columns[7].Visible = false; dataGridView1.Columns[8].Visible = false; dataGridView1.Columns[9].Visible = false; } //Add private void buttonAdd_Click(object sender, EventArgs e) { if (textBox1.Text == String.Empty || textBox2.Text == String.Empty || textBox3.Text == String.Empty) { MessageBox.Show("Текстові поля незаповнені!"); return; } Solution sol = new Solution { name = textBox1.Text.Trim(), characteristic = textBox2.Text.Trim(), bibliographic_description = textBox3.Text.Trim() }; db.Solutions.Add(sol); db.SaveChanges(); dataGridView1.Refresh(); textBox1.Text = String.Empty; textBox2.Text = String.Empty; textBox3.Text = String.Empty; } //Edit private void buttonEdit_Click(object sender, EventArgs e) { if (id == String.Empty) return; var sol = db.Solutions.Find(int.Parse(id)); if (sol == null) return; sol.name = textBox1.Text.Trim(); sol.characteristic = textBox2.Text.Trim(); sol.bibliographic_description = textBox3.Text.Trim(); db.Solutions.AddOrUpdate(sol); db.SaveChanges(); dataGridView1.Refresh(); } private void buttonDelete_Click(object sender, EventArgs e) { if (id == String.Empty) return; var sol = db.Solutions.Find(int.Parse(id)); db.Solutions.Remove(sol); db.SaveChanges(); dataGridView1.Refresh(); } private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { if (dataGridView1.CurrentRow == null) return; var sol = dataGridView1.CurrentRow.DataBoundItem as Solution; if (sol == null) return; id = Convert.ToString(sol.id_solution); textBox1.Text = sol.name.Trim(); textBox2.Text = sol.characteristic.Trim(); textBox3.Text = sol.bibliographic_description.Trim(); } //Додавання функцій та їх технічних рішень private void buttonAddSolutionsOfFunctionsToList_Click(object sender, EventArgs e) { if (dataGridView1.CurrentRow == null) return; Solution sol = dataGridView1.CurrentRow.DataBoundItem as Solution; if (sol == null) { MessageBox.Show("Рішення для функції не обрано!", "Помилка"); return; } //Знаходимо функцію, яку вибрав користувач в базі даних. для зв'язки string selectedFuncName = comboBox1.SelectedItem.ToString(); Function selectedFunc = funcList.FirstOrDefault(f => f.name == selectedFuncName); if(selectedFunc == null) { MessageBox.Show("Обраної функції не існує в базі даних! \n Оберіть існуючу функцію!", "Помилка вибору функції"); return; } //Створюємо об'єкт де функція має своє рішення SolutionsOfFunction solOfFunc = new SolutionsOfFunction() { Solution = sol, Function = selectedFunc }; //Зберегти в локальне сховище if (solOfFuncCacheData.AddElement<SolutionsOfFunction>(solOfFunc)) MessageBox.Show("Рішення: " + solOfFunc.Solution.name + " для функції: " + solOfFunc.Function.name + " додано для оцінювання!", "Підтверджено"); else MessageBox.Show("Рішення: " + solOfFunc.Solution.name + " для функції: " + solOfFunc.Function.name + " вже занесено для оцінювання!", "Відхилено"); //Зберегти до бази даних //db.SolutionsOfFunctions.AddOrUpdate(solOfFunc); } } }
Python
UTF-8
544
3.21875
3
[]
no_license
import unittest from singleton import Singleton class TestSingleton(unittest.TestCase): def setUp(self): self.singleton_1 = Singleton(10) self.singleton_2 = Singleton(50) def test_singleton_data_does_update(self): self.assertEqual(self.singleton_1.data, 50) self.assertEqual(self.singleton_2.data, 50) def test_singleton_is_singleton(self): self.assertEqual(self.singleton_1.data, self.singleton_2.data) self.assertEqual(id(self.singleton_1), id(self.singleton_2))
SQL
UTF-8
559
3.015625
3
[ "MIT" ]
permissive
.mode csv .bail on .echo on -- drop/create new tables .open ./data/processed/sf-food-safety.sqlite .read ./src/dba/schema.sql -- import the data .changes on .import ./data/raw/businesses_plus.csv business .import ./data/raw/inspections_plus.csv inspection .import ./data/raw/violations_plus.csv violation -- index the data .read ./src/dba/indexes.sql -- remove the repeated headers DELETE FROM business WHERE business_id = 'business_id'; DELETE FROM inspection WHERE business_id = 'business_id'; DELETE FROM violation WHERE business_id = 'business_id';
JavaScript
UTF-8
622
2.640625
3
[]
no_license
const Discord = require("discord.js"); module.exports.run = async(bot, message, args) => { let rpsdact = true; let user2 = message.mentions.members.first(); if(!user2) return message.reply("**User not found!**"); await message.channel.send(`${user2.user.id}, do accept ${message.author.id}'s challenge? yes or no`); if(user2 && message.content === "yes"){ await message.channel.send("choose between rock, paper and scissors"); if(message.author && message.content === "rock"){ let rock = "rock"; } } } module.exports.help = { name: "rpsduel" }
JavaScript
UTF-8
4,262
2.828125
3
[ "MIT" ]
permissive
/* * * xxxxxxx xxxxxxx * x:::::x x:::::x * x:::::x x:::::x * x:::::xx:::::x * x::::::::::x * x::::::::x * x::::::::x * x::::::::::x * x:::::xx:::::x * x:::::x x:::::x * x:::::x x:::::x * THE xxxxxxx xxxxxxx TOOLKIT * * http://www.goXTK.com * * Copyright (c) 2012 The X Toolkit Developers <dev@goXTK.com> * * The X Toolkit (XTK) is licensed under the MIT License: * http://www.opensource.org/licenses/mit-license.php * * * * */ // provides goog.provide('X.cylinder'); // requires goog.require('CSG.cylinder'); goog.require('X.base'); goog.require('X.constructable'); goog.require('X.object'); /** * Create a displayable cylinder. * * @constructor * @extends X.object * @mixin X.constructable */ X.cylinder = function() { // // call the standard constructor of X.base goog.base(this); // // class attributes /** * @inheritDoc * @const */ this._classname = 'cylinder'; /** * The start point of this cylinder. * * @type {!Array} * @protected */ this._start = [-10, -10, -10]; /** * The end point of this cylinder. * * @type {!Array} * @protected */ this._end = [10, 10, 10]; /** * The radius of this cylinder. * * @type {!number} * @protected */ this._radius = 10; /** * The number of slices to generate the cylinder shape. * * @type {!number} * @protected */ this._slices = 32; inject(this, new X.constructable()); // this object is constructable }; // inherit from X.object goog.inherits(X.cylinder, X.object); /** * Get the start point of this cylinder. * * @return {!Array} The start point as an array with length 3. * @public */ X.cylinder.prototype.__defineGetter__('start', function() { return this._start; }); /** * Set the start point of this cylinder. * * @param {!Array} start The start point as an array with length 3 ([X,Y,Z]). * @throws {Error} An error, if the start point is invalid. * @public */ X.cylinder.prototype.__defineSetter__('start', function(start) { if (!goog.isDefAndNotNull(start) || !goog.isArray(start) || (start.length != 3)) { throw new Error('Invalid start'); } this._start = start; }); /** * Get the end point of this cylinder. * * @return {!Array} The end point as an array with length 3. * @public */ X.cylinder.prototype.__defineGetter__('end', function() { return this._end; }); /** * Set the end point of this cylinder. * * @param {!Array} end The end point as an array with length 3 ([X,Y,Z]). * @throws {Error} An error, if the end point is invalid. * @public */ X.cylinder.prototype.__defineSetter__('end', function(end) { if (!goog.isDefAndNotNull(end) || !goog.isArray(end) || (end.length != 3)) { throw new Error('Invalid end'); } this._end = end; }); /** * Get the radius of this cylinder. * * @return {!number} The radius. * @public */ X.cylinder.prototype.__defineGetter__('radius', function() { return this._radius; }); /** * Set the radius of this cylinder. * * @param {!number} radius The radius. * @throws {Error} An error, if the given radius is invalid. * @public */ X.cylinder.prototype.__defineSetter__('radius', function(radius) { if (!goog.isNumber(radius)) { throw new Error('Invalid radius.'); } this._radius = radius; }); /** * @inheritDoc * @suppress {missingProperties} */ X.cylinder.prototype.modified = function() { this.fromCSG(new CSG.cylinder({ start: this._start, end: this._end, radius: this._radius, slices: this._slices })); // call the super class goog.base(this, 'modified'); }; // export symbols (required for advanced compilation) goog.exportSymbol('X.cylinder', X.cylinder); goog.exportSymbol('X.cylinder.prototype.modified', X.cylinder.prototype.modified);
Java
UTF-8
2,616
2.375
2
[ "BSD-2-Clause" ]
permissive
/* * Copyright (c) 2014. Philip DeCamp * Released under the BSD 2-Clause License * http://opensource.org/licenses/BSD-2-Clause */ package bits.thicket; import java.util.Random; /** * @author decamp */ interface RefineFunc { public void refine( LayoutParams params, Graph src, Graph dst ); public static final RefineFunc NOTHING = new RefineFunc() { @Override public void refine( LayoutParams params, Graph src, Graph dst ) { for( Vert v = dst.mVerts; v != null; v = v.mGraphNext ) { v.mGraphOwner = null; } } }; public static final RefineFunc EXPAND_PERTURB = new RefineFunc() { @Override public void refine( LayoutParams params, Graph src, Graph dst ) { final int dim = params.mDim; final Random rand = ( params.mRand != null ? params.mRand : new Random() ); float expandScale = (float)( Math.pow( dst.mVertNo, 1.0 / dim ) / Math.pow( src.mVertNo, 1.0 / dim ) ); if( expandScale != expandScale ) { expandScale = 1f; } float noiseScale = params.mScale * 0.001f; float noiseTrans = -noiseScale * 0.5f; if( dim == 2 ) { for( Vert v = dst.mVerts; v != null; v = v.mGraphNext ) { if( v.mGraphOwner == null ) { v.mX *= expandScale; v.mY *= expandScale; } else { Vert u = v.mGraphOwner; v.mGraphOwner = null; v.mX = expandScale * u.mX + noiseScale * rand.nextFloat() + noiseTrans; v.mY = expandScale * u.mY + noiseScale * rand.nextFloat() + noiseTrans; } } } else { for( Vert v = dst.mVerts; v != null; v = v.mGraphNext ) { if( v.mGraphOwner == null ) { v.mX *= expandScale; v.mY *= expandScale; v.mZ *= expandScale; } else { Vert u = v.mGraphOwner; v.mGraphOwner = null; v.mX = expandScale * u.mX + noiseScale * rand.nextFloat() + noiseTrans; v.mY = expandScale * u.mY + noiseScale * rand.nextFloat() + noiseTrans; v.mZ = expandScale * u.mZ + noiseScale * rand.nextFloat() + noiseTrans; } } } } }; }
Swift
UTF-8
1,615
3.28125
3
[]
no_license
// // CalculatorLogic.swift // Calculator // // Created by Berta Devant on 19/07/2017. // Copyright © 2017 Berta Devant. All rights reserved. // import Foundation class CalculatorPresenter { private let displayer: CalculatorDisplayer private let calculator: Calculator init(displayer: CalculatorDisplayer, calculator: Calculator) { self.displayer = displayer self.calculator = calculator } func presentCalculator() { displayer.setCalculator(calculator: calculator) displayer.attachListener(listener: newListener()) } private func newListener() -> CalculatorActionListener { return CalculatorActionListener( operationAction: { [displayer] operation in var result: Double = 0 switch operation.operationType { case .Sum: result = operation.leftSideValue + operation.rightSideValue case .Minus: result = operation.leftSideValue - operation.rightSideValue case .Multiply: result = operation.leftSideValue * operation.rightSideValue case .Divide: result = operation.leftSideValue / operation.rightSideValue case .Equals: break } displayer.setNewResults(results: result) }, inputAction: { [displayer] input in //TODO accept non numbered inputs guard let number = Double(input) else { return } displayer.setNewResults(results: number) }) } func stopPresenting() { displayer.detachListener() } }
TypeScript
UTF-8
1,952
2.53125
3
[]
no_license
import { normalizePath, relative } from "../src/normalize"; import { Node } from "../src/Node"; it("normalizePath", () => { expect(normalizePath(".")).toEqual(""); expect(normalizePath("a/b/c/")).toEqual("a/b/c"); expect(normalizePath("a/b/c")).toEqual("a/b/c"); expect(normalizePath("/a/b/c")).toEqual("/a/b/c"); expect(normalizePath("a/././b/./c/./")).toEqual("a/b/c"); expect(normalizePath("a/../b/../c/")).toEqual("c"); expect(normalizePath("a\\b\\.\\c\\")).toEqual("a/b/c"); }); it("relative", () => { expect(relative("a/b/", "a/b/c/d")).toEqual("c/d"); expect(relative("a/c/d", "a/b")).toEqual("../../b"); expect(relative("", ".gitignore")).toEqual(".gitignore"); }); it("generateRootNode", () => { const allFiles: string[] = [ ".gitignore", "apps/infra/libs/package.json", "apps/infra/project1/src/App.tsx", "apps/infra/project1/src/index.tsx", "apps/infra/project1/package.json", "common/config/rush/.pnpmfile.cjs", "common/config/rush/common-version.json", "package.json", ]; const root = Node.From(allFiles); expect(root.toJSON()).toMatchSnapshot(); }); it("generateRootNode combine path", () => { const allFiles: string[] = [ ".gitignore", "apps/tools/tool1/tool2/package.json", "apps/infra/libs/package.json", "apps/infra/project1/src/App.tsx", "apps/infra/project1/src/index.tsx", "apps/infra/project1/package.json", "common/config/rush/.pnpmfile.cjs", "common/config/rush/common-version.json", "package.json", ]; const root = Node.From(allFiles); const result = root.combinePath().toJSON(); const assertFn = (d: Node) => { if (d.isFolder) { const folders = d.filesOrFolders.filter((dd) => dd.isFolder); expect(d.filesOrFolders.length > 1 || folders.length === 0).toBe(true); folders.forEach((f) => assertFn(f)); } }; result.filesOrFolders.forEach(assertFn); expect(result).toMatchSnapshot(); });
Java
UTF-8
707
3.53125
4
[]
no_license
import java.util.*; // find size of k bloomed flowers class Solution { public static int kEmptySlots(int[] flowers, int k) { int N = flowers.length; TreeSet<Integer> bloomed = new TreeSet(); bloomed.add(0); bloomed.add(N + 1); int day = N; for (int i = N - 1; i >= 0; i--) { int flower = flowers[i]; day--; bloomed.add(flower); Integer prev = bloomed.lower(flower); Integer next = bloomed.higher(flower); if (prev != null && flower - prev - 1 == k || next != null && next - flower - 1 == k) { return day; } } return -1; } public static void main(String[] args) { int[] flowers = {3, 1, 5, 4, 2}; System.out.print(kEmptySlots(flowers, 3)); } }
Python
UTF-8
876
3.203125
3
[]
no_license
import sys fp = open(sys.argv[1], 'r') # for each command line in the workload file, create JSON object and execute GET/POST to API line = fp.readline() output = set() hash_bucket = {} while line: uname = line.strip().split(' ')[1].split(',')[1] if uname[0] != '.': output.add(uname) line = fp.readline() for name in output: letter = name[0] if letter in hash_bucket: hash_bucket[letter] = hash_bucket[letter] + 1 else: hash_bucket[letter] = 1 max = 0 min = 100000000 modulo = 5 for name in hash_bucket: if max < hash_bucket[name]: max = hash_bucket[name] if min > hash_bucket[name]: min = hash_bucket[name] print(name + " (" + str(ord(name) % modulo) + ") freq: " + str(hash_bucket[name])) print("min freq: " + str(min) + "\nmax freq: " + str(max)) print("TOTAL NAMES: " + str(len(output)))
Markdown
UTF-8
1,068
2.515625
3
[]
no_license
# Article 47 La mise en conformité des conditions d'aménagement, d'exploitation et de suivi des installations de stockage continuant à recevoir des déchets à la date de publication au Journal officiel de la République française du présent arrêté est obligatoire. L'exploitant doit remettre au préfet au plus tard un an après la publication au Journal officiel de la République française du présent arrêté une étude permettant de vérifier la conformité de l'installation de stockage aux exigences du présent arrêté ou de mettre en évidence les points pour lesquels une mise en conformité est nécessaire, assortie d'une proposition d'échéancier. Sur la base de cette étude, le préfet fixe, s'il y a lieu, les conditions de la poursuite de l'exploitation, intégrant, le cas échéant, un échéancier pour la réalisation des mesures nécessaires. S'il est décidé de mettre fin à l'activité de l'installation, le suivi, après la mise en place de la couverture finale, sera effectué selon les dispositions du chapitre IV du titre V.
Python
UTF-8
6,994
2.8125
3
[]
no_license
"""This modules contains entries for the movies and TV serials. The movie entries are instances of Movie class and TV serials are instances of TVSerial class. More entries can be added in this module. """ import webbrowser import media # contains Movie and TVSerial classes import fresh_tomatoes # contains functions that create an external HTML page # 7 instances of Movie class # RATINGS = ['NR', 'G', 'PG', 'PG-13', 'R', 'NC-17'] interstellar = \ media.Movie("Interstellar", "A team of explorers travel through a wormhole in space in an"\ " attempt to ensure humanity's survival.", 169, "Matthew McConaughey, Anne Hathaway, Jessica Chastain", "Adventure, Drama, Sci-Fi", "https://upload.wikimedia.org/wikipedia/en/b/bc/"\ "Interstellar_film_poster.jpg", "https://www.youtube.com/watch?v=zSWdZVtXT7E", 8.7, 2014) interstellar.RATINGS = interstellar.RATINGS[3] inception = \ media.Movie("Inception", "A thief who steals corporate secrets through the use of"\ " dream-sharing technology is given the inverse task of planting"\ " an idea into the mind of a CEO.", 148, "Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page", "Action, Mystery, Sci-Fi", "https://upload.wikimedia.org/wikipedia/en/7/7f/Inception"\ "_ver3.jpg", "https://www.youtube.com/watch?v=YoHD9XEInc0", 8.8, 2010) inception.RATINGS = inception.RATINGS[3] avatar = \ media.Movie("Avatar", "A paraplegic marine dispatched to the moon Pandora on a"\ " unique mission becomes torn between following his"\ " orders and protecting the world he feels is his home.", 162, "Sam Worthington, Zoe Saldana, Sigourney Weaver", "Action, Adventure, Fantasy", "http://upload.wikimedia.org/wikipedia/id/b/b0/Avatar-Teaser-"\ "Poster.jpg", "https://www.youtube.com/watch?v=5PSNL1qE6VY", 7.9, 2009) avatar.RATINGS = avatar.RATINGS[3] the_dark_knight = \ media.Movie("The Dark Knight", "When the menace known as the Joker wreaks havoc and chaos on"\ " the people of Gotham, the caped crusader must come to terms"\ " with one of the greatest psychological tests of his ability"\ " to fight injustice.", 152, "Christian Bale, Heath Ledger, Aaron Eckhart", "Action, Crime, Drama", "https://upload.wikimedia.org/wikipedia/en/8/8a/Dark_Knight.jpg", "https://www.youtube.com/watch?v=_PZpmTj1Q8Q", 9.0, 2008) the_dark_knight.RATINGS = the_dark_knight.RATINGS[3] the_hunger_games = \ media.Movie("The Hunger Games", "Katniss Everdeen voluntarily takes her younger sister's"\ " place in the Hunger Games, a televised fight to the"\ " death in which two teenagers from each of the twelve"\ " Districts of Panem are chosen at random to compete.", 142, "Jennifer Lawrence, Josh Hutcherson, Liam Hemsworth", "Adventure, Drama, Sci-Fi", "https://upload.wikimedia.org/wikipedia/en/4/42/Hunger"\ "GamesPoster.jpg","https://www.youtube.com/watch?v=mfmrPu43DF8", 7.3, 2012) the_hunger_games.RATINGS = the_hunger_games.RATINGS[3] troy = \ media.Movie("Troy", "An adaptation of Homer's great epic, the film follows the"\ " assault on Troy by the united Greek forces and chronicles"\ " the fates of the men involved.", 163, "Brad Pitt, Eric Bana, Orlando Bloom", "Adventure", "https://upload.wikimedia.org/wikipedia/en/b/b8/Troy"\ "2004Poster.jpg", "https://www.youtube.com/watch?v=znTLzRJimeY", 7.2, 2004) troy.RATINGS = troy.RATINGS[4] fight_club = \ media.Movie("Fight Club", "An insomniac office worker, looking for a way to change"\ " his life, crosses paths with a devil-may-care soap maker,"\ " forming an underground fight club that evolves into something"\ " much, much more...", 139, "Brad Pitt, Edward Norton, Helena Bonham Carter", "Drama", "https://upload.wikimedia.org/wikipedia/en/f/fc/Fight_"\ "Club_poster.jpg", "https://www.youtube.com/watch?v=SUXWAEX2jlg", 8.9, 1999) fight_club.RATINGS = fight_club.RATINGS[4] # 5 instances of TVSerial class # RATINGS = ['TV-Y', 'TV-Y7', 'TV-G', 'TV-PG', 'TV-14', 'TV-MA'] hardhome = \ media.TVSerial("Game of Thrones", "Tyrion advises Daenerys. Sansa forces"\ " Theon to tell her a secret. Cersei remains stubborn."\ " Arya meets her first target. Jon and Tormund meet with the"\ " Wildling Elders.", 61, "Peter Dinklage, Lena Headey, Emilia Clarke", "Adventure, Drama,"\ " Fantasy", "http://watchersonthewall.com/wp-content/uploads/2015"\ "/02/GOT-S5-Poster.jpg", "https://www.youtube.com/watch?v=agWcTyXr"\ "jfM", 9.8, 5, 8, "Hardhome", "HBO") hardhome.RATINGS = hardhome.RATINGS[5] how_your_mother_met_me = \ media.TVSerial("How I Met Your Mother", "The story of The Mother, from"\ " her traumatic 21st birthday to a number of close calls with"\ " meeting Ted to the night before Barney and Robin's wedding.", 23, "Josh Radnor, Jason Segel, Cobie Smulders", "Comedy, Romance", "http://vignette2.wikia.nocookie.net/himym/images/f/f1/How-i-met-"\ "your-mother-season-9-dvd-cover.jpg/revision/latest?cb=2014100422"\ "3440", "https://www.youtube.com/watch?v=RV0ay9zEG64", 9.5, 9, 16, "How Your Mother Met Me", "CBS") how_your_mother_met_me.RATINGS = how_your_mother_met_me.RATINGS[4] slap_bet = \ media.TVSerial("How I Met Your Mother", "The gang discovers that Robin's"\ " been hiding a huge secret, but they have no idea what it is."\ " Marshall thinks she is married, and Barney thinks she was"\ " a porn star.", 23, "Josh Radnor, Jason Segel, Cobie Smulders", "Comedy, Romance", "http://tvstock.net/sites/default/files/po"\ "ster-how-i-met-your-mother-season-7.jpg", "https://www.youtube"\ ".com/watch?v=cZ_86XTkyz8", 9.4, 2, 9, "Slap Bet", "CBS") slap_bet.RATINGS = slap_bet.RATINGS[4] the_last_one_part_2 = \ media.TVSerial("Friends", "Rachel is leaving for her job in Paris."\ " Monica and Chandler are packing up the apartment.", 22, "Jennifer Aniston, Courteney Cox, Lisa Kudrow", "Comedy, Romance", "http://pics.filmaffinity.com/Friends_Serie_de_TV-888842701-large"\ ".jpg", "https://www.youtube.com/watch?v=Eibl9JIpcKk", 9.7, 10, 18, "The Last One: Part 2", "NBC") the_last_one_part_2.RATINGS = the_last_one_part_2.RATINGS[3] the_hounds_of_baskerville = \ media.TVSerial("Sherlock", "Sherlock and John investigate the ghosts of a"\ " young man who has been seeing monstrous hounds out in the woods"\ " where his father died.", 88, "Benedict Cumberbatch, Martin Freeman, Una Stubbs", "Crime, Drama, Mystery", "https://lh4.ggpht.com/LY5atFtolosm_TGq5"\ "VjVxwFigtQ5J40sL_vYIdr3XRI-SyWC_mRJdyihI8HaWeoZTA=h900", "https://www.youtube.com/watch?v=bm78r2innnE", 8.5, 2, 2, "The Hounds of Baskerville", "BBC One") the_hounds_of_baskerville.RATINGS = the_hounds_of_baskerville.RATINGS[4] movies = [interstellar, inception, avatar, the_dark_knight, the_hunger_games, troy, fight_club] tvserials = [hardhome, how_your_mother_met_me, slap_bet, the_last_one_part_2, the_hounds_of_baskerville] videos = movies + tvserials fresh_tomatoes.open_videos_page(videos)
Java
UTF-8
3,174
2.4375
2
[]
no_license
package com.example.workmanagerimplementation.Models; import android.content.ContentResolver; import android.database.Cursor; import android.util.Log; import com.example.workmanagerimplementation.Models.Pojo.MainMenu; import com.example.workmanagerimplementation.data.DBHandler; import com.example.workmanagerimplementation.data.DataContract; import com.google.gson.Gson; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; /** * Created by Md.harun or rashid on 09,April,2021 * BABL, Bangladesh, */ public class MainMenuModel{ ContentResolver contentResolver; DBHandler db; public MainMenuModel(ContentResolver contentResolver) { this.contentResolver = contentResolver; } public ArrayList<MainMenu> getAllMenuList(String role_code){ ArrayList<MainMenu> mainMenuArrayList=new ArrayList<MainMenu>(); String[] projection={ DataContract.MenuListEntry.LOGO, DataContract.MenuListEntry.POSITION, DataContract.MenuListEntry.TITLE, DataContract.MenuListEntry.MENU_ID, }; String[] selctionArgs={""}; String selectionClause=null; selctionArgs[0]=role_code; selectionClause = DataContract.MenuListEntry.ROLE_CODE + " = ?"; Cursor cursor=contentResolver.query(DataContract.MenuListEntry.CONTENT_URI,projection,selectionClause,selctionArgs,null); Log.e("Cursor",new Gson().toJson(cursor)); if(cursor.moveToFirst()){ do { Log.e("FirstCursor",cursor.getString(0)); Log.e("SecondCursor",cursor.getString(1)); Log.e("ThirdCursor",cursor.getString(2)); Log.e("FourthCursor",cursor.getString(3)); mainMenuArrayList.add(new MainMenu(cursor.getString(2),cursor.getString(0),cursor.getInt(1),cursor.getInt(3))); }while (cursor.moveToNext()); } return mainMenuArrayList; } public ArrayList<MainMenu> sort(ArrayList<MainMenu> mainMenuArrayList){ Comparator<MainMenu> compareByPosition = new Comparator<MainMenu>() { @Override public int compare(MainMenu o1, MainMenu o2) { return o1.getMenuPosition().compareTo(o2.getMenuPosition()); } }; Collections.sort(mainMenuArrayList,compareByPosition); return mainMenuArrayList; } public ArrayList<MainMenu> readAllItems() { ArrayList<MainMenu> items = new ArrayList<>(); Cursor cursor = contentResolver.query(DataContract.MenuListEntry.CONTENT_URI,null,null,null,null); if (cursor!=null) { while (cursor.moveToNext()) { // move the cursor to next row if there is any to read it's data MainMenu item = readItem(cursor); items.add(item); } } return items; } private MainMenu readItem(Cursor cursor) { MainMenu item = new MainMenu(); item.setMenuTitle(cursor.getString(cursor.getColumnIndex(DataContract.MenuListEntry.IS_SYNCED))); return item; } }
Java
UTF-8
251
2.484375
2
[]
no_license
package com.Tutorial; import java.util.Scanner; public class LogicalOps { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int b=50; while (b>=20) { System.out.println(b); b--; } } }
C#
UTF-8
775
2.640625
3
[ "MIT" ]
permissive
using GoogleApi.Entities.Common; using NUnit.Framework; namespace GoogleApi.UnitTests.Common; [TestFixture] public class ViewPortTests { [Test] public void ConstructorTest() { var southWest = new Coordinate(1, 1); var northEast = new Coordinate(2, 2); var viewPort = new ViewPort(southWest, northEast); Assert.AreEqual(northEast, viewPort.NorthEast); Assert.AreEqual(southWest, viewPort.SouthWest); } [Test] public void ToStringTest() { var southWest = new Coordinate(1, 1); var northEast = new Coordinate(2, 2); var viewPort = new ViewPort(southWest, northEast); var toString = viewPort.ToString(); Assert.AreEqual($"{southWest}|{northEast}", toString); } }
C++
UTF-8
2,894
3.03125
3
[]
no_license
#ifndef UTILS_H #define UTILS_H #include <stdio.h> #define stdmax(a,b) (a>b?a:b) inline float RandomFloat(float min, float max) { float r = (float)rand() / (float)RAND_MAX; return min + r * (max - min); } inline float RandomInt(int min, int max) { float r = (float)rand() / (float)RAND_MAX; return (int)((float)min + r * float(max - min)); } class BlockIndexBitField { public: BlockIndexBitField(int numBits) { dataSize = 32; if (numBits == 0) numBits = dataSize; m_numBits = numBits; m_sizeInInts = (numBits / dataSize) + 1; // need to add one int m_data = new int[(m_sizeInInts)]; //memset( (void*)m_data, 0, sizeof(m_data) ); for (int i = 0; i < m_sizeInInts; i++) { m_data[i] = 0; } } ~BlockIndexBitField() { if (m_data) delete[] m_data; } void SetBit(int idx) { if (idx > m_numBits) return; if (idx < 0) return; int blockIndex = (int)((float)(idx) / dataSize); int remainder = idx - blockIndex*dataSize; m_data[blockIndex] |= (1 << remainder); } bool CheckBit(int idx) { if (idx > m_numBits) return false; if (idx < 0) return false; int blockIndex = (int)((float)(idx) / dataSize); int remainder = idx - blockIndex*dataSize; return m_data[blockIndex] & (1 << remainder); } void ResetBit(int idx) { if (idx > m_numBits) return; if (idx < 0) return; int blockIndex = (int)((float)(idx) / dataSize); int remainder = idx - blockIndex*dataSize; m_data[blockIndex] &= ~(1 << remainder); } void Clear() { for (int i = 0; i < m_sizeInInts; i++) { m_data[i] = 0; } } bool Binary_AND(BlockIndexBitField &B, BlockIndexBitField &C) { if (B.m_numBits != C.m_numBits) { return false; } if (this->m_numBits != B.m_numBits) { return false; } for (int i = 0; i < B.m_sizeInInts; i++) { this->m_data[i] = B.m_data[i] & C.m_data[i]; } return true; } bool Binary_OR(BlockIndexBitField &B, BlockIndexBitField &C) { if (B.m_numBits != C.m_numBits) { return false; } if (this->m_numBits != B.m_numBits) { return false; } for (int i = 0; i < B.m_sizeInInts; i++) { this->m_data[i] = B.m_data[i] | C.m_data[i]; } return true; } bool Binary_NAND(BlockIndexBitField &B, BlockIndexBitField &C) { if (B.m_numBits != C.m_numBits) { return false; } if (this->m_numBits != B.m_numBits) { return false; } for (int i = 0; i < B.m_sizeInInts; i++) { this->m_data[i] = B.m_data[i] & ~C.m_data[i]; } return true; } bool Binary_XOR(BlockIndexBitField &B, BlockIndexBitField &C) { if (B.m_numBits != C.m_numBits) { return false; } if (this->m_numBits != B.m_numBits) { return false; } for (int i = 0; i < B.m_sizeInInts; i++) { this->m_data[i] = B.m_data[i] ^ C.m_data[i]; } return true; } int m_sizeInInts; int m_numBits; int dataSize; int *m_data; }; #endif
TypeScript
UTF-8
4,030
2.515625
3
[ "MIT" ]
permissive
import t from '../src/readable-ansi' import chalk from 'chalk' import { CSI } from './util' import { wrap as w } from '../src/common' describe('foreground color', () => { it('naming colors', () => { expect(t(CSI + '30m')).toBe(w('黑')) expect(t(CSI + '31m')).toBe(w(chalk.red('红'))) expect(t(CSI + '32m')).toBe(w(chalk.green('绿'))) expect(t(CSI + '33m')).toBe(w(chalk.yellow('黄'))) expect(t(CSI + '34m')).toBe(w(chalk.blue('蓝'))) expect(t(CSI + '35m')).toBe(w(chalk.magenta('紫'))) expect(t(CSI + '36m')).toBe(w(chalk.cyan('青'))) expect(t(CSI + '37m')).toBe(w(chalk.white('白'))) expect(t(CSI + '39m')).toBe(w('fD')) }) it('naming bright colors', () => { expect(t(CSI + '90m')).toBe(w('黑+')) expect(t(CSI + '91m')).toBe(w(chalk.redBright('红+'))) expect(t(CSI + '92m')).toBe(w(chalk.greenBright('绿+'))) expect(t(CSI + '93m')).toBe(w(chalk.yellowBright('黄+'))) expect(t(CSI + '94m')).toBe(w(chalk.blueBright('蓝+'))) expect(t(CSI + '95m')).toBe(w(chalk.magentaBright('紫+'))) expect(t(CSI + '96m')).toBe(w(chalk.cyanBright('青+'))) expect(t(CSI + '97m')).toBe(w(chalk.whiteBright('白+'))) }) it('true color', () => { expect(t(CSI + '38;2;255;165;0m')).toBe(w(`\x1b[38;2;255;165;0m` + 'fT' + '\x1b[39m')) }) it('unknown more color', () => { expect(t(CSI + '38;6;255;165;0m')).toBe(w(chalk.yellow('㉄'))) }) }) describe('background color', () => { it('naming background colors', () => { expect(t(CSI + '40m')).toBe(w(chalk.bgBlack('黑'))) expect(t(CSI + '41m')).toBe(w(chalk.bgRed('红'))) expect(t(CSI + '42m')).toBe(w(chalk.bgGreen('绿'))) expect(t(CSI + '43m')).toBe(w(chalk.bgYellow('黄'))) expect(t(CSI + '44m')).toBe(w(chalk.bgBlue('蓝'))) expect(t(CSI + '45m')).toBe(w(chalk.bgMagenta('紫'))) expect(t(CSI + '46m')).toBe(w(chalk.bgCyan('青'))) expect(t(CSI + '47m')).toBe(w(chalk.bgWhite('白'))) expect(t(CSI + '49m')).toBe(w('bD')) }) it('naming background bright colors', () => { expect(t(CSI + '100m')).toBe(w(chalk.bgBlackBright('黑+'))) expect(t(CSI + '101m')).toBe(w(chalk.bgRedBright('红+'))) expect(t(CSI + '102m')).toBe(w(chalk.bgGreenBright('绿+'))) expect(t(CSI + '103m')).toBe(w(chalk.bgYellowBright('黄+'))) expect(t(CSI + '104m')).toBe(w(chalk.bgBlueBright('蓝+'))) expect(t(CSI + '105m')).toBe(w(chalk.bgMagentaBright('紫+'))) expect(t(CSI + '106m')).toBe(w(chalk.bgCyanBright('青+'))) expect(t(CSI + '107m')).toBe(w(chalk.bgWhiteBright('白+'))) }) it('true background color', () => { expect(t(CSI + '48;2;255;165;0m')).toBe(w(`\x1b[48;2;255;165;0m` + 'bT' + '\x1b[49m')) }) }) describe('font styles', () => { it('bold', () => { expect(t(CSI + '1m')).toBe(w('𝐁')) expect(t(CSI + '21m')).toBe(w('𝐁⌀')) }) it('italic', () => { expect(t(CSI + '3m')).toBe(w('𝐼')) expect(t(CSI + '23m')).toBe(w('𝐼⌀')) }) it('underline', () => { expect(t(CSI + '4m')).toBe(w('_')) expect(t(CSI + '24m')).toBe(w('_⌀')) }) }) describe('other styles', () => { it('cross-out', () => { expect(t(CSI + '9m')).toBe(w('c̶')) }) it('cross-out off', () => { expect(t(CSI + '29m')).toBe(w('c̶⌀')) }) it('framed', () => { expect(t(CSI + '51m')).toBe(w('⬚')) }) it('framed off', () => { expect(t(CSI + '54m')).toBe(w('⬚⌀')) }) it('encircled', () => { expect(t(CSI + '52m')).toBe(w('ⓒ')) }) it('overlined', () => { expect(t(CSI + '53m')).toBe(w('o̅')) }) it('overlined off', () => { expect(t(CSI + '55m')).toBe(w('o̅⌀')) }) it('inverse off', () => { expect(t(CSI + '27m')).toBe(w('◑⌀')) }) it('blink', () => { expect(t(CSI + '5m')).toBe(w('闪')) expect(t(CSI + '6m')).toBe(w('闪')) expect(t(CSI + '25m')).toBe(w('闪⌀')) }) it('reset', () => { expect(t(CSI + '0m')).toBe(w('®')) }) it('normal', () => { expect(t(CSI + '22m')).toBe(w('☐')) }) })
Java
UTF-8
731
2.484375
2
[]
no_license
package com.academiccourseregistration.core.dao.mapper; import com.academiccourseregistration.core.api.model.StudentDto; import com.academiccourseregistration.core.dao.model.Student; import lombok.experimental.UtilityClass; @UtilityClass public class StudentMapper { public StudentDto toDto(Student entity) { StudentDto dto = new StudentDto(); dto.setId(entity.getId()); dto.setFirstName(entity.getFirstName()); dto.setLastName(entity.getLastName()); return dto; } public Student toEntity(StudentDto dto) { Student entity = new Student(); entity.setFirstName(dto.getFirstName()); entity.setLastName(dto.getLastName()); return entity; } }
Java
UTF-8
989
3.34375
3
[]
no_license
package com.srk.graphs; import java.util.Arrays; import java.util.LinkedList; import java.util.ListIterator; public class Graph { int vertices; LinkedList<Integer>[] dll = null; public Graph(int v) { this.vertices = v; dll = new LinkedList[this.vertices]; for(int i = 0; i<vertices; i++) { dll[i] = new LinkedList<>(); } } public void addEdge(int source, int dest) { if(source<vertices && dest < vertices) { this.dll[source].addLast(dest); //this.dll[dest].addLast(source); } } public void printGraph() { System.out.println(">>Adjacency List of Directed Graph<<"); for (int i = 0; i < vertices; i++) { if(dll[i]!=null){ System.out.print("|" + i + "| => "); ListIterator<Integer> listIterator = dll[i].listIterator(); while (listIterator.hasNext()) { System.out.print("[" + listIterator.next() + "] -> "); } System.out.println("null"); } else{ System.out.println("|" + i + "| => "+ "null"); } } } }
C
UTF-8
532
2.953125
3
[]
no_license
int a; int b; int c; while(true) { a = input(); b = input(); c = input(); if (a <= b && a <= c) { output(a); if (b <= c) { output(b); output(c); } else { output(c); output(b); } } else if (b <= a && b <= c) { output(b); if (a <= c) { output(a); output(c); } else { output(c); output(a); } } else { output(c); if (a <= b) { output(a); output(b); } else { output(b); output(a); } } }
Markdown
UTF-8
4,403
2.859375
3
[ "BSD-4-Clause", "BSD-2-Clause" ]
permissive
# ECNS Implementations for registrars and local resolvers for the Ethereum Classic Name Service. For documentation of the original ENS system, see [docs.ENS.domains](http://docs.ens.domains/). # Differences between ENS and ECNS 1. ECNS will not burn funds. There is a special `burn` address at the Registrar that will receive funds at destroy of the `Deed` instead of burning them. 2. ECNS registry natively supports `namehash` algorithm. It is possible to call `namehash(string)` and get its nameHash without having to implement the algorithm by third parties. 3. There is a function to extract stuck ERC20 tokens from each contract: Registry and Registrar. 4. rootNode is `.etc` #### ECNS contracts are deployed on ETC main net: Hash Registrar: [0xcb177520ACa646881D53909b456A9B2B730391f0](https://gastracker.io/addr/0xcb177520ACa646881D53909b456A9B2B730391f0) Registry: [0xb96836a066ef81ea038280c733f833f69c23efde](https://gastracker.io/addr/0xb96836a066ef81ea038280c733f833f69c23efde) Public Resolver: [0x4fa1fc37a083abe4c53b6304f389042bc0566855](https://gastracker.io/addr/0x4fa1fc37a083abe4c53b6304f389042bc0566855) Reverse Registrar:[0x9434e3f592f5d63de25dbd54af4bd58b822b6136](https://gastracker.io/addr/0x9434e3f592f5d63de25dbd54af4bd58b822b6136) #### ECNS contracts are deployed on Rinkeby testnet: Hash Registrar: [0xb93d8610e5efae1c7f7bcb5c65cfb58c3346ed0d](https://rinkeby.etherscan.io/address/0xb93d8610e5efae1c7f7bcb5c65cfb58c3346ed0d) Registry: [0xB6FedAA1c1a170eecb4d5C1984eA4023aEb91d64](https://rinkeby.etherscan.io/address/0xB6FedAA1c1a170eecb4d5C1984eA4023aEb91d64) ## ECNS.sol Implementation of the ECNS Registry, the central contract used to look up resolvers and owners for domains. ## FIFSRegistrar.sol Implementation of a simple first-in-first-served registrar, which issues (sub-)domains to the first account to request them. ## HashRegistrar.sol Implementation of a registrar based on second-price blind auctions and funds held on deposit, with a renewal process that weights renewal costs according to the change in mean price of registering a domain. Largely untested! ## PublicResolver.sol Simple resolver implementation that allows the owner of any domain to configure how its name should resolve. One deployment of this contract allows any number of people to use it, by setting it as their resolver in the registry. # ECNS Registry interface The ECNS registry is a single central contract that provides a mapping from domain names to owners and resolvers, as described in [EIP 137](https://github.com/ethereum/EIPs/issues/137). The ECNS operates on 'nodes' instead of human-readable names; a human readable name is converted to a node using the namehash algorithm, which is as follows: def namehash(name): if name == '': return '\0' * 32 else: label, _, remainder = name.partition('.') return sha3(namehash(remainder) + sha3(label)) The registry's interface is as follows: ## owner(bytes32 node) constant returns (address) Returns the owner of the specified node. ## resolver(bytes32 node) constant returns (address) Returns the resolver for the specified node. ## setOwner(bytes32 node, address owner) Updates the owner of a node. Only the current owner may call this function. ## setSubnodeOwner(bytes32 node, bytes32 label, address owner) Updates the owner of a subnode. For instance, the owner of "foo.com" may change the owner of "bar.foo.com" by calling `setSubnodeOwner(namehash("foo.com"), sha3("bar"), newowner)`. Only callable by the owner of `node`. ## setResolver(bytes32 node, address resolver) Sets the resolver address for the specified node. # Resolver interface Resolvers must implement one mandatory method, `has`, and may implement any number of other resource-type specific methods. Resolvers must `throw` when an unimplemented method is called. ## has(bytes32 node, bytes32 kind) constant returns (bool) Returns true if the specified node has the specified record kind available. Record kinds are defined by each resolver type and standardised in EIPs; currently only "addr" is supported. `has()` must return false if the corresponding record type specific methods will throw if called. ## addr(bytes32 node) constant returns (address ret) Implements the addr resource type. Returns the Ethereum address associated with a node if it exists, or `throw`s if it does not.
C#
UTF-8
489
2.984375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Topdeck { class Deck { int deckSize = 0; Card[] deck; int Wins { get; set; } int Losses { get; set; } public double Winrate { get { return (double)Wins / Losses; } private set { } } public Deck(int deckSize) { this.deckSize = deckSize; deck = new Card[deckSize]; } } }
Java
UTF-8
4,439
2.3125
2
[]
no_license
package com.truedev.application.Service; import android.app.IntentService; import android.content.Intent; import android.os.Binder; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.util.Log; import com.truedev.application.ImageManager.ImageUtils; import com.truedev.application.NetworkManager.NetworkManager; import com.truedev.application.Utils.CommonUtils; import com.truedev.application.models.GeneralResponse; import org.json.JSONObject; import java.io.EOFException; import java.util.HashMap; import java.util.Map; /** * Created by lakshaygirdhar on 23/3/16. */ public class ImageUploadService extends IntentService { private static final String TAG = "ImageUploadService"; public static String IMAGE_PATH = "imagePath"; public static String IMAGE_PARAMS = "imageParams"; private int DESIRED_WIDTH = 1024; public static final int IMAGE_UPLOADED = 1; public static final int IMAGE_FAILED = 2; public static final int IMAGE_ERROR = 3; private int DESIRED_HEIGHT = 900; private HashMap<String, String> params; private ImageUploadBinder imageUploadBinder = new ImageUploadBinder(); private Handler mHandler; /** * Creates an IntentService. Invoked by your subclass's constructor. */ public ImageUploadService() { super("imageuploadservice"); } public void setmHandler(Handler mHandler) { this.mHandler = mHandler; } public void setDesiredWidth(int DESIRED_WIDTH) { this.DESIRED_WIDTH = DESIRED_WIDTH; } public void setDesiredHeight(int DESIRED_HEIGHT) { this.DESIRED_HEIGHT = DESIRED_HEIGHT; } @Override protected void onHandleIntent(Intent intent) { if (CommonUtils.isNetWorkAvailable(getBaseContext())) { Bundle extras = intent.getExtras(); String imagePath = extras.getString(IMAGE_PATH); params = (HashMap<String, String>) extras.getSerializable(IMAGE_PARAMS); uploadImage(imagePath, params); } else { //// TODO: 22/3/16 Internet not working } } @Override public IBinder onBind(Intent intent) { return imageUploadBinder; } public void uploadImage(String imagePath, HashMap<String, String> params) { if (imagePath == null) if (mHandler != null) { Message message = Message.obtain(null, IMAGE_ERROR); mHandler.sendMessage(message); } try { requestForImageUpload(imagePath, createRequest(params)); } catch (EOFException e) { Log.d(TAG, "onHandleIntent: " + e.getLocalizedMessage()); } } private void requestForImageUpload(final String imagePath, final String params) throws EOFException { new Thread(new Runnable() { @Override public void run() { GeneralResponse response = NetworkManager.makeImageUploadRequest(ImageUtils.compressImage(imagePath, DESIRED_WIDTH, DESIRED_HEIGHT), params); if (response != null && NetworkManager.SUCCESS.equals(response.getStatus())) { Log.d(TAG, "requestForImageUpload: " + response.getMessage()); if (mHandler != null) { Message message = Message.obtain(null, IMAGE_UPLOADED, response); mHandler.sendMessage(message); } } if (mHandler != null) { Message message = Message.obtain(null, IMAGE_FAILED, response); mHandler.sendMessage(message); } Log.d(TAG, "requestForImageUpload: Not Uploaded"); } }).start(); } private String createRequest(HashMap<String, String> params) { try { JSONObject paramsJson = new JSONObject(); for (Map.Entry<String, String> entry : params.entrySet()) { paramsJson.put(entry.getKey(), entry.getValue()); } return paramsJson.toString(); } catch (Exception e) { Log.e(TAG, "Exception e : " + e.getStackTrace().toString()); return null; } } public class ImageUploadBinder extends Binder { public ImageUploadService getService() { return ImageUploadService.this; } } }
Java
UTF-8
1,016
1.945313
2
[]
no_license
package server; import server.controllers.NoteController; import server.controllers.UserController; import server.dao.AccessRightService; import server.dao.NoteService; import server.dao.UserService; import com.google.gson.Gson; /* Very simple implementation of DI */ public class DI { public static final DI instance = new DI(); private DI() { } public final UserService userDAO = new UserService(); public final NoteService noteDAO = new NoteService(); public final AccessRightService accessRightDAO = new AccessRightService(); public final TokenValidator tokenValidator = new TokenValidator(); public final ProtocolValidator protocolValidator = new ProtocolValidator(); public final RequestProcessor requestProcessor = new RequestProcessor(); public final Session session = new Session(); public final Gson gson = new Gson(); public final UserController userController = new UserController(); public final NoteController noteController = new NoteController(); }
Python
UTF-8
2,285
2.890625
3
[]
no_license
#! /home/asim/projects/RoverProject/.venv/bin/python import PySimpleGUI as sg """ buttons looks okay, need to find a way to incorporate this into existing system call button can reflect actual state ie before clicking : call on click: calling on ack : Called on rover reaching : GO on GO: call stations too can show some color to signfy its state rover movement maybe shown throuh colors """ CALL_state = 'CALL' sg.theme('BluePurple') _size1 = (11,2) _size = (7,4) layout = [[sg.Button('CALL',size=_size1,key='-CALL-',pad=(5,5)),sg.Button('E-STOP',size=_size1),sg.Button('Restart',size=_size1)], [sg.Button('1',size=_size),sg.Button('2',size=_size),sg.Button('3',size=_size),sg.Button('4',size=_size)], [sg.Button('5',size=_size),sg.Button('6',size=_size),sg.Button('7',size=_size),sg.Button('8',size=_size),], [sg.Button('9',size=_size),sg.Button('10',size=_size),sg.Button('11',size=_size),sg.Button('12',size=_size)]] window = sg.Window('Pattern 2B', layout) station_selected = 0 while True: # Event Loop event, values = window.read() print(event, values) if event in [sg.WIN_CLOSED, 'Exit']: break if event == '-CALL-': # Update the "output" text element to be the value of "input" element print(f"CALL presses : state{CALL_state}") if CALL_state == 'CALL': # Do stuff #send call message CALL_state ='GO' window['-CALL-'].update(CALL_state,button_color='green') station_selected = 0 elif CALL_state == 'GO': # Do stuff # check which station has been highlighted # Send Go message if station_selected == 0: sg.popup("No station selected") else: print(f"set the destination as : {station_selected}") CALL_state ='CALL' window['-CALL-'].update(CALL_state,button_color='blue') station_selected = 0 for btn in range(1,13): if event ==f"{btn}": station_selected = event window[f'{btn}'].update(button_color='white') print(f"{btn}: has been pressed") else : window[f'{btn}'].update(button_color='blue') window.close()
Markdown
UTF-8
5,268
2.875
3
[ "Apache-2.0" ]
permissive
# Dependencies * [PyTorch](http://pytorch.org/) * [torchvision](https://github.com/pytorch/vision/) * [tabulate](https://pypi.python.org/pypi/tabulate/) # Usage The code in this repository implements both the curve-finding procedure with examples on the CIFAR-10 datasets. ## Curve Finding ### Training the endpoints To run the curve-finding procedure, you first need to train the two networks that will serve as the end-points of the curve. You can train the endpoints using the following command ```bash python3 train.py --dir=<DIR> \ --dataset=<DATASET> \ --data_path=<PATH> \ --transform=<TRANSFORM> \ --model=<MODEL> \ --epochs=<EPOCHS> \ --lr_init=<LR_INIT> \ --wd=<WD> \ [--use_test] ``` Parameters: * ```DIR``` &mdash; path to training directory where checkpoints will be stored * ```DATASET``` &mdash; dataset name [CIFAR10] (default: CIFAR10) * ```PATH``` &mdash; path to the data directory * ```TRANSFORM``` &mdash; type of data transformation [VGG/ResNet] (default: VGG) * ```MODEL``` &mdash; DNN model name: - VGG16/VGG16BN/VGG19/VGG19BN - PreResNet110/PreResNet164 - WideResNet28x10 * ```EPOCHS``` &mdash; number of training epochs (default: 200) * ```LR_INIT``` &mdash; initial learning rate (default: 0.1) * ```WD``` &mdash; weight decay (default: 1e-4) Use the `--use_test` flag if you want to use the test set instead of validation set (formed from the last 5000 training objects) to evaluate performance. For example, use the following commands to train VGG16, PreResNet or Wide ResNet: ```bash #VGG16 python3 train.py --dir=<DIR> --dataset=[CIFAR10] --data_path=<PATH> --model=VGG16 --epochs=200 --lr_init=0.05 --wd=5e-4 --use_test --transfrom=VGG #PreResNet python3 train.py --dir=<DIR> --dataset=[CIFAR10] --data_path=<PATH> --model=[PreResNet110 or PreResNet164] --epochs=150 --lr_init=0.1 --wd=3e-4 --use_test --transfrom=ResNet #WideResNet28x10 python3 train.py --dir=<DIR> --dataset=[CIFAR10] --data_path=<PATH> --model=WideResNet28x10 --epochs=200 --lr_init=0.1 --wd=5e-4 --use_test --transfrom=ResNet ``` ### Training the curves Once you have two checkpoints to use as the endpoints you can train the curve connecting them using the following comand. ```bash python3 train.py --dir=<DIR> \ --dataset=<DATASET> \ --data_path=<PATH> \ --transform=<TRANSFORM> --model=<MODEL> \ --epochs=<EPOCHS> \ --lr_init=<LR_INIT> \ --wd=<WD> \ --curve=<CURVE>[Bezier|PolyChain] \ --num_bends=<N_BENDS> \ --init_start=<CKPT1> \ --init_end=<CKPT2> \ [--fix_start] \ [--fix_end] \ [--use_test] ``` Parameters: * ```CURVE``` &mdash; desired curve parametrization [Bezier|PolyChain] * ```N_BENDS``` &mdash; number of bends in the curve (default: 3) * ```CKPT1, CKPT2``` &mdash; paths to the checkpoints to use as the endpoints of the curve Use the flags `--fix_end --fix_start` if you want to fix the positions of the endpoints For example, use the following commands to train VGG16, PreResNet or Wide ResNet: ```bash #VGG16 python3 train.py --dir=<DIR> --dataset=[CIFAR10 or CIFAR100] --use_test --transform=VGG --data_path=<PATH> --model=VGG16 --curve=[Bezier|PolyChain] --num_bends=3 --init_start=<CKPT1> --init_end=<CKPT2> --fix_start --fix_end --epochs=600 --lr=0.015 --wd=5e-4 #PreResNet python3 train.py --dir=<DIR> --dataset=[CIFAR10 or CIFAR100] --use_test --transform=ResNet --data_path=<PATH> --model=PreResNet164 --curve=[Bezier|PolyChain] --num_bends=3 --init_start=<CKPT1> --init_end=<CKPT2> --fix_start --fix_end --epochs=200 --lr=0.03 --wd=3e-4 #WideResNet28x10 python3 train.py --dir=<DIR> --dataset=[CIFAR10 or CIFAR100] --use_test --transform=ResNet --data_path=<PATH> --model=WideResNet28x10 --curve=[Bezier|PolyChain] --num_bends=3 --init_start=<CKPT1> --init_end=<CKPT2> --fix_start --fix_end --epochs=200 --lr=0.03 --wd=5e-4 ``` ### Evaluating the curves To evaluate the found curves, you can use the following command ```bash python3 eval_curve.py --dir=<DIR> \ --dataset=<DATASET> \ --data_path=<PATH> \ --transform=<TRANSFORM> --model=<MODEL> \ --lr_init=<LR_INIT> \ --wd=<WD> \ --curve=<CURVE>[Bezier|PolyChain] \ --num_bends=<N_BENDS> \ --ckpt=<CKPT> \ --num_points=<NUM_POINTS> \ [--use_test] ``` Parameters * ```CKPT``` &mdash; path to the checkpoint saved by `train.py` * ```NUM_POINTS``` &mdash; number of points along the curve to use for evaluation (default: 61) `eval_curve.py` outputs the statistics on train and test loss and error along the curve. It also saves a `.npz` file containing more detailed statistics at `<DIR>`. ### Training the endpoints with poisoned dataset to perform backdoor attack similar to training the endpoints with train.py. But instead of train.py, use train_injection.py
Java
UTF-8
402
2.125
2
[]
no_license
package com.mercacortex.ad_json.model; import com.google.gson.annotations.SerializedName; import java.util.List; public class Person { @SerializedName("contacts") public List<Contact> contacts; public Person() { } public List<Contact> getContactos() { return contacts; } public void setContactos(List<Contact> contacts) { this.contacts = contacts; } }
Java
UTF-8
3,256
2.890625
3
[ "Apache-2.0" ]
permissive
/** * Copyright (C) 2009 - present by OpenGamma Inc. and other contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fudgemsg.types; /** * Granularity options for {@link DateTimeFieldType} and {@link TimeFieldType}. * * @author Andrew Griffin */ public enum DateTimeAccuracy { /** * Millenia precision. */ MILLENIUM (0), /** * Century precision. */ CENTURY (1), /** * Year precision. */ YEAR (2), /** * Month precision. */ MONTH (3), /** * Day precision. */ DAY (4), /** * Hour precision. */ HOUR (5), /** * Minute precision. */ MINUTE (6), /** * Second precision. */ SECOND (7), /** * Millisecond precision. */ MILLISECOND (8), /** * Microsecond precision. */ MICROSECOND (9), /** * Nanosecond precision. */ NANOSECOND (10); private final int _encodedValue; private DateTimeAccuracy (final int encodedValue) { _encodedValue = encodedValue; } /** * The numeric value to be encoded in Fudge time and datetime representations. See <a href="http://wiki.fudgemsg.org/display/FDG/DateTime+encoding">DateTime encoding</a> * * @return the numeric value */ /* package */ int getEncodedValue () { return _encodedValue; } /** * Resolves the symbolic enum value from an encoded value (e.g. one returned by {@link #getEncodedValue} or received in a Fudge message). * * @param n numeric value * @return the {@link DateTimeAccuracy} or {@code null} if the value is invalid */ /* package */ static DateTimeAccuracy fromEncodedValue (int n) { switch (n) { case 10 : return NANOSECOND; case 9 : return MICROSECOND; case 8 : return MILLISECOND; case 7 : return SECOND; case 6 : return MINUTE; case 5 : return HOUR; case 4 : return DAY; case 3 : return MONTH; case 2 : return YEAR; case 1 : return CENTURY; case 0 : return MILLENIUM; default : return null; } } /** * Tests if this accuracy is a greater precision than another. E.g. SECOND precision is greater than MINUTE precision. * * @param accuracy other accuracy * @return {@code true} if greater, {@code false} otherwise */ public boolean greaterThan (final DateTimeAccuracy accuracy) { return getEncodedValue () > accuracy.getEncodedValue (); } /** * Tests is this accuracy is a lower precision than another. E.g. MINUTE precision is less than SECOND precision. * * @param accuracy other accuracy * @return {@code true} if lower, {@code false} otherwise. */ public boolean lessThan (final DateTimeAccuracy accuracy) { return getEncodedValue () < accuracy.getEncodedValue (); } }
PHP
UTF-8
7,152
2.953125
3
[]
no_license
<?php class Perfil{ private $pdo; private $idInstructor; private $Nombres; private $Apellidos; private $TipoDocumento; private $NumeroDocumento; private $CorreoElectronico; private $Usuario; public function __CONSTRUCT(){ $this->pdo = BasedeDatos::Conectar(); } public function getidInstructor() : ?int{ return $this->idInstructor; } public function setidInstructor(int $id){ $this->idInstructor=$id; } public function getNombresInstructor() : ?string{ return $this->Nombres; } public function setNombresInstructor(string $Nombres){ $this->Nombres=$Nombres; } public function getApellidosInstructor() : ?string{ return $this->Apellidos; } public function setApellidosInstructor(string $Apellidos){ $this->Apellidos=$Apellidos; } public function getTipoDocumentoInstructor() : ?string{ return $this->TipoDocumento; } public function setTipoDocumentoInstructor(string $TipoDocumento){ $this->TipoDocumento=$TipoDocumento; } public function getNumeroDocumentoInstructor() : ?int{ return $this->NumeroDocumento; } public function setNumeroDocumentoInstructor(int $NumeroDocumento){ $this->NumeroDocumento=$NumeroDocumento; } public function getCorreoElectronicoInstructor() : ?string{ return $this->CorreoElectronico; } public function setCorreoElectronicoInstructor(string $CorreoElectronico){ $this->CorreoElectronico=$CorreoElectronico; } public function getCorreoInstitucionalInstructor() : ?string{ return $this->CorreoInstitucional; } public function setCorreoInstitucionalInstructor(string $CorreoInstitucional){ $this->CorreoInstitucional=$CorreoInstitucional; } public function getfk_idUsuario() : ?int{ return $this->Usuario; } public function setfk_idUsuario(int $Usuario){ $this->Usuario=$Usuario; } public function Listar(){ try{ $consulta=$this->pdo->prepare('SELECT ins."idInstructor", ins."NombresInstructor", ins."ApellidosInstructor", ins."TipoDocumentoInstructor", ins."NumeroDocumentoInstructor", ins."CorreoElectronicoInstructor", ins."CorreoInstitucionalInstructor", ins."fk_idUsuario", usu."Usuario", usu."Estados", usu."idUsuario" FROM "Instructor" ins INNER JOIN "Usuario" usu ON ins."fk_idUsuario"= usu."idUsuario"'); $consulta->execute(); return $consulta->fetchAll(PDO::FETCH_OBJ); }catch(Exeption $e){ die($e->getMessage()); } } public function Obtener($id){ try{ $consulta=$this->pdo->prepare('SELECT * FROM "Instructor" WHERE "idInstructor"=?;'); $consulta->execute(array($id)); $r=$consulta->fetch(PDO::FETCH_OBJ); $p=new Instructor(); $p->setidInstructor($r->idInstructor); $p->setNombresInstructor($r->NombresInstructor); $p->setApellidosInstructor($r->ApellidosInstructor); $p->setTipoDocumentoInstructor($r->TipoDocumentoInstructor); $p->setNumeroDocumentoInstructor($r->NumeroDocumentoInstructor); $p->setCorreoElectronicoInstructor($r->CorreoElectronicoInstructor); $p->setfk_idUsuario($r->fk_idUsuario); $p->setCorreoInstitucionalInstructor($r->CorreoInstitucionalInstructor); return $p; }catch(Exeption $e){ die($e->getMessage()); } } public function ObtenerUsuId($id){ try{ $consulta=$this->pdo->prepare('SELECT * FROM "Instructor" WHERE "fk_idUsuario"=?;'); $consulta->execute(array($id)); $r=$consulta->fetch(PDO::FETCH_OBJ); $p=new Instructor(); $p->setidInstructor($r->idInstructor); $p->setNombresInstructor($r->NombresInstructor); $p->setApellidosInstructor($r->ApellidosInstructor); $p->setTipoDocumentoInstructor($r->TipoDocumentoInstructor); $p->setNumeroDocumentoInstructor($r->NumeroDocumentoInstructor); $p->setCorreoElectronicoInstructor($r->CorreoElectronicoInstructor); $p->setCorreoInstitucionalInstructor($r->CorreoInstitucionalInstructor); $p->setfk_idUsuario($r->fk_idUsuario); return $p; }catch(Exeption $e){ die($e->getMessage()); } } public function Insertar(Instructor $p){ try{ $consulta=('INSERT INTO public."Instructor"( "NombresInstructor", "ApellidosInstructor", "TipoDocumentoInstructor", "NumeroDocumentoInstructor", "CorreoElectronicoInstructor", "fk_idUsuario", "CorreoInstitucionalInstructor") VALUES (?,?,?,?,?,?,?);'); $this->pdo->prepare($consulta)->execute(array( $p->getNombresInstructor(), $p->getApellidosInstructor(), $p->getTipoDocumentoInstructor(), $p->getNumeroDocumentoInstructor(), $p->getCorreoElectronicoInstructor(), $p->getfk_idUsuario(), $p->getCorreoInstitucionalInstructor(), )); }catch(Exeception $e){ die($e->getMessage()); } } public function Actualizar(Instructor $p){ try{ $consulta=('UPDATE "Instructor" SET "NombresInstructor"=?, "ApellidosInstructor"=?, "TipoDocumentoInstructor"=?, "NumeroDocumentoInstructor"=?, "CorreoElectronicoInstructor"=?, "fk_idUsuario"=?, "CorreoInstitucionalInstructor"=? WHERE "idInstructor"=?;'); $this->pdo->prepare($consulta)->execute(array( $p->getNombresInstructor(), $p->getApellidosInstructor(), $p->getTipoDocumentoInstructor(), $p->getNumeroDocumentoInstructor(), $p->getCorreoElectronicoInstructor(), $p->getfk_idUsuario(), $p->getCorreoInstitucionalInstructor(), $p->getidInstructor() )); }catch(Exeception $e){ die($e->getMessage()); } } public function ActualizarUsuId(Instructor $p){ try{ $consulta=('UPDATE "Instructor" SET "NombresInstructor"=?, "ApellidosInstructor"=?, "TipoDocumentoInstructor"=?, "NumeroDocumentoInstructor"=?, "CorreoElectronicoInstructor"=?, "fk_idUsuario"=?, "CorreoInstitucionalInstructor"=? WHERE "idInstructor"=?;'); $this->pdo->prepare($consulta)->execute(array( $p->getNombresInstructor(), $p->getApellidosInstructor(), $p->getTipoDocumentoInstructor(), $p->getNumeroDocumentoInstructor(), $p->getCorreoElectronicoInstructor(), $p->getfk_idUsuario(), $p->getCorreoInstitucionalInstructor(), $p->getidInstructor() )); }catch(Exeception $e){ die($e->getMessage()); } } }
Java
UTF-8
207
2.015625
2
[]
no_license
package com.nilestanner.filtersortpagesample.exceptions; public class SqlInsertException extends Exception { public SqlInsertException(String exceptionString) { super(exceptionString); } }
Java
UTF-8
1,089
2.140625
2
[]
no_license
package com.stud.api; import java.util.List; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.stud.bean.StudentDto; import com.stud.util.AppConstants; @RestController @RequestMapping(AppConstants.URL_ROOT) public interface RestStudentService { @GetMapping(AppConstants.URL_GET) public List<StudentDto> getStudent() throws Exception; @PostMapping(AppConstants.URL_ADD) public StudentDto addStudent(@RequestBody StudentDto user); @PutMapping(AppConstants.URL_UPDATE) public StudentDto updateSudent(@RequestBody StudentDto user); @DeleteMapping(AppConstants.URL_DELETE) public String removeStudent(@PathVariable Long roll); }
Java
UTF-8
268
1.835938
2
[]
no_license
package com.xmw.catalina.http; /** * @author xmw. * @date 2018/7/8 10:50. */ public abstract class XmwServlet { public abstract void doGet(XmwRequest request, XmwResponse response); public abstract void doPost(XmwRequest request, XmwResponse response); }
Python
UTF-8
6,619
2.671875
3
[]
no_license
import numpy as np import copy, time import torch import torch.optim as optim import torch.nn as nn from torchviz import make_dot from torch.utils.data import Dataset, TensorDataset, DataLoader from torch.utils.data.dataset import random_split from torch.autograd import Variable from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter import matplotlib.pyplot as plt from Transpose import Transpose def DFL(x_t, x_tm1, eta_fn, u_tm1): # Compute augmented state eta_tm1 = eta_fn(x_tm1) eta_t = eta_fn(x_t ) # Dummy input u_t = torch.zeros(u_tm1.size()) # Assemble xi xi_tm1 = torch.cat((x_tm1, eta_tm1, u_tm1), 0) xi_t = torch.cat((x_t , eta_t , u_t ), 0) # Linear regression to compute A and H xi_pinv = torch.pinverse(xi_tm1) A = torch.matmul( x_t, xi_pinv) H = torch.matmul(eta_t, xi_pinv) return A, H, eta_t, xi_tm1 def train_model(model, x, y, title=None): # Reshape x and y to be vector of tensors x = torch.transpose(x,0,1) y = torch.transpose(y,0,1) dataset = TensorDataset(x, y) N_train = int(3*len(y)/5) train_dataset, val_dataset = random_split(dataset, [N_train,len(y)-N_train]) train_loader = DataLoader(dataset=train_dataset, batch_size=50) val_loader = DataLoader(dataset=val_dataset , batch_size=50) loss_fn = torch.nn.MSELoss(reduction='sum') # Use the optim package to define an Optimizer that will update the weights of # the model for us. Here we will use Adam; the optim package contains many other # optimization algorithms. The first argument to the Adam constructor tells the # optimizer which Tensors it should update. learning_rate = .0001 n_epochs = 1000 training_losses = [] validation_losses = [] optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) def step(x_batch, y_batch, model, loss_fn): # Send data to GPU if applicable x_batch = x_batch.to(device) y_batch = y_batch.to(device) # Reshape data for linear algebra x_batch = torch.transpose(x_batch, 0,1) y_batch = torch.transpose(y_batch, 0,1) # Label input data x_tm1 = x_batch[:2,:] u_tm1 = x_batch[2,:][None,:] x_t = y_batch A, H, eta_t, xi_tm1 = DFL(x_t, x_tm1, model, u_tm1) # Estimate x and eta using DFL model x_hat = torch.matmul(A,xi_tm1) eta_hat = torch.matmul(H,xi_tm1) # Return return loss_fn(x_t, x_hat) + loss_fn(eta_t, eta_hat) for t in range(n_epochs): batch_losses = [] with torch.no_grad(): val_losses = [] for x_val, y_val in val_loader: val_loss = step(x_val, y_val, model, loss_fn).item() val_losses.append(val_loss) validation_loss = np.mean(val_losses) validation_losses.append(validation_loss) # if t>100 and validation_losses[-2]<=validation_losses[-1]: # break for x_batch, y_batch in train_loader: loss = step(x_batch, y_batch, model, loss_fn) optimizer.zero_grad() loss.backward() optimizer.step() batch_losses.append(loss.item()) training_loss = np.mean(batch_losses) training_losses.append(training_loss) print(f"[{t+1}] Training loss: {training_loss:.3f}\t Validation loss: {validation_loss:.3f}") plt.figure() plt.semilogy(range(len(training_losses)), training_losses, label='Training Loss') plt.semilogy(range(len(validation_losses)), validation_losses, label='Validation Loss') plt.xlabel('Epoch') plt.ylabel('Loss') plt.legend() if title is not None: plt.title(title) plt.show() model.eval() return model # def lazyOpt(fn, lwrBnd, uprBnd, disc, intMask): # n_vars = len(disc) # step = [] # for v in range(n_vars): # step.append((uprBnd[v]-lwrBnd[v])/disc[v]) # step = np.asarray(step) # J = np.zeros(disc) # for i in range(np.prod(disc)): # idx = np.unravel_index(i,disc) # inp = (np.asarray(lwrBnd).copy()+idx*step).tolist() # for v in range(len(inp)): # if intMask[v]: # inp[v] = int(inp[v]) # J[idx] = controller(inp) # mindx = np.asarray(np.unravel_index(np.argmin(J), disc)) # mindx_m1 = [max(0,v-1) for v in mindx] # mindx_p1 = [min(uprBnd[v], mindx[v]+1) for v in range(len(mindx))] # inp = np.asarray(lwrBnd).copy() # inp_opt = inp+mindx*step # inp_lwr = inp+mindx_m1*step # inp_upr = inp+mindx_p1*step # print('Optimal params: ',inp_opt) # print('Between: ', inp_lwr, ' and ', inp_upr) def randu(m,n,a,b): return (b-a)*torch.rand(m,n)+a if __name__ == '__main__': # Options torch.manual_seed(3) #5 device = 'cpu'#'cuda' if torch.cuda.is_available() else 'cpu' dtype = torch.FloatTensor RETRAIN = False RETRAIN = True # Parameters k, b, m, dt, T = 1, 1, 1, 0.1, 400 M = 10000 H, leta = 256, 2 # Define state transition function def f(x,u): # Continuous-Time state-space matrices A_x = torch.tensor([[0,1],[0,0]]).type(dtype) A_eta = torch.tensor([[0,0],[-1/m,-1/m]]).type(dtype) B_x = torch.tensor([[0],[1/m]]).type(dtype) # Convert state-space matrices to discrete-time A_x = dt*A_x+torch.tensor([[1,0],[0,1]]).type(dtype) A_eta = dt*A_eta B_x = dt*B_x # Nonlinear elements Fs = k*x[0,:][None,:]**3 Fd = b*x[1,:][None,:]**3 eta = torch.cat((Fs, Fd), 0) return torch.matmul(A_x , x) + \ torch.matmul(A_eta, eta) + \ torch.matmul(B_x , u) # Create training data x_tm1 = randu(2,M,-1,1).type(dtype) u_tm1 = randu(1,M,-1,1).type(dtype) x_t = f(x_tm1,u_tm1) # Initialize model g = torch.nn.Sequential( Transpose(), torch.nn.Linear(2,H), torch.nn.ReLU(), torch.nn.ReLU(), torch.nn.ReLU(), torch.nn.ReLU(), torch.nn.Linear(H,leta), Transpose() ) # Train model # if RETRAIN: # g = train_model(g, torch.cat((x_tm1, u_tm1), 0), x_t) # torch.save(g.state_dict(), 'g.pt') # else: # g.load_state_dict(torch.load('g.pt')) A, H, _, _ = DFL(x_t, x_tm1, g, u_tm1) # Simulate step response x0 = torch.tensor([[0],[0]]).type(dtype) x = float('nan')*torch.ones(2,T).type(dtype) xs = float('nan')*torch.ones(2,T).type(dtype) eta = float('nan')*torch.ones(2,T).type(dtype) u = 0.5*torch.ones(1,T).type(dtype) x [:,0] = torch.squeeze( x0 ) xs [:,0] = torch.squeeze( x0 ) eta[:,0] = torch.squeeze(g(x0)) for t in range(1,T): x[:,t] = f(x[:,t-1][:,None], u[:,t-1][:,None]).squeeze() xi_tm1 = torch.cat((xs[:,t-1], eta[:,t-1], u[:,t-1]), 0)[:,None] xs[:,t] = torch.matmul(A,xi_tm1).squeeze() eta[:,t] = torch.matmul(H,xi_tm1).squeeze() # Illustrate plt.figure() plt.plot(range(T), x[0,:].detach().numpy(), label='x') plt.plot(range(T), u[0,:].detach().numpy(), label='u') plt.plot(range(T), xs[0,:].detach().numpy(), label='xs') plt.xlabel('Time') plt.legend() plt.show()
Python
UTF-8
1,114
3.328125
3
[]
no_license
# -*- coding: utf-8 -*- #!/usr/bin/env python3 #使用特定欄位名稱-尋找特定欄位 #此範例要找"Invoice Number","Purchase Date" """ Created on Thu Sep 21 09:51:09 2017 @author: vizance """ import csv import sys input_file = sys.argv[1] output_file = sys.argv[2] my_columns = ['Invoice Number','Purchase Date'] my_columns_index = []#用來儲存搜尋欄位的index with open(input_file,'r',newline='') as csv_in_file: with open(output_file, 'w', newline='') as csv_out_file: filereader = csv.reader(csv_in_file) filewriter = csv.writer(csv_out_file) header = next(filereader,None) #處理標題欄位 for index_value in range(len(header)): if header[index_value] in my_columns: my_columns_index.append(index_value)#輸出結果為欄位index[0,3] filewriter.writerow(my_columns) for row_list in filereader:#處理內文欄位 row_list_output = [] for index_value in my_columns_index: row_list_output.append(row_list[index_value]) filewriter.writerow(row_list_output)
Shell
UTF-8
1,125
3.03125
3
[]
no_license
#!/bin/bash MYSQL_ROOT_USER=root MYSQL_ROOT_PASSWORD=<root_password> MYSQL_CI_DATABASE=experchat_ci ENV_SETTING=ci ENV_DECRYPTION_PASSWD=<ci_config_decreption_password> REPO_USERNAME=<common_repo_user> REPO_PASSWORD=<common_repo_password> docker stop CONTAINER $(docker ps -q) docker rm $(docker ps -a -q) docker rmi $(docker images -q) mysqladmin -u$MYSQL_ROOT_USER -p$MYSQL_ROOT_PASSWORD drop $MYSQL_CI_DATABASE -f mysqladmin -u$MYSQL_ROOT_USER -p$MYSQL_ROOT_PASSWORD create $MYSQL_CI_DATABASE --default-character-set=utf8mb4 git clone https://$REPO_USERNAME:$REPO_PASSWORD@bitbucket.org/avihoffer/ec_python.git experchat cd experchat/ git checkout -f origin/$1 docker build --rm --build-arg env_setting=$ENV_SETTING --build-arg env_decryption_passwd=$ENV_DECRYPTION_PASSWD --build-arg common_repo_password=$REPO_PASSWORD --build-arg common_repo_user=$REPO_USERNAME -t experchat . docker run experchat ./manage.py check if [ $? -ne 0 ] then echo "Django check failed." exit 1 fi docker run experchat pytest --no-cov if [ $? -ne 0 ] then echo "Python Test Failed." exit 1 fi docker run -d -p 8000:8000 experchat
JavaScript
UTF-8
1,368
3.1875
3
[]
no_license
export default class Circle { constructor(){ this.element = document.createElement('div'); this.element.className = 'circle'; const body = document.getElementsByTagName('body')[0]; this.isActive = false; this.element.addEventListener('mousedown', this.onMouseDownHandler.bind(this), true); this.element.addEventListener('mouseup', this.onMouseUpHandler.bind(this), true); document.addEventListener('mousemove', this.onMouseMoveHandler.bind(this), true); body.appendChild(this.element); } getElementCoordinat() { return { x: this.element.style.left.replace('px', ''), y: this.element.style.top.replace('px', ''), } } onMouseDownHandler(e) { this.isActive = true; this.offset = [ this.element.offsetLeft - e.clientX, this.element.offsetTop - e.clientY ]; } onMouseUpHandler () { this.isActive = false; } onMouseMoveHandler(e) { e.preventDefault(); if (this.isActive) { let mousePosition = { x : e.clientX, y : e.clientY }; this.element.style.left = (mousePosition.x + this.offset[0]) + 'px'; this.element.style.top = (mousePosition.y + this.offset[1]) + 'px'; } } }
Markdown
UTF-8
2,030
3.09375
3
[ "MIT" ]
permissive
# Getting Started Everything starts with a [Nx workspace](https://nx.dev). ```bash npx create-nx-workspace myworkspace ``` **Note:** We recommend the following options when creating your Nx workspace: - Choose `Apps` preset - Use `Nx` cli We find this provides opportunities for broader use cases while also allowing you to setup your workspace the way you want which may include using `xplat` app generators (which we'll install in a moment) which leverage those from Nx however enhances a few to work best for xplat tooling. # Install Nrwl cli Having Nrwl's cli installed globally will enhance usability of the tooling: **Using `npm`** ``` npm install -g @nrwl/cli ``` **Using `yarn`** ``` yarn global add @nrwl/cli ``` # xplat install options **Using `npm`** ```bash npm install --save-dev @nstudio/xplat ``` **Using `yarn`** ```bash yarn add --dev @nstudio/xplat ``` **If using Nx already configured with Angular preset** ```bash ng add @nstudio/xplat ``` # Generate supporting architecture After installing xplat tools, your default schematic collection should now be set to `@nstudio/xplat`. The most common use case is to use the supporting xplat architecture. Initialize your workspace with the platforms you intend to develop apps with: ``` nx g init ``` You will be prompted for which platforms to generate support for. You can optionally pass a collection of platforms: ``` nx g init --platforms web,nativescript ``` # Generate apps ``` nx g app ``` **Note:** If you're using an Nx workspace with any angular presets you may need to replace `nx` with `ng`. This also applies to the `nx serve appname` step. Follow the prompts to generate the type of app you'd like: <img src="assets/img/xplat-api-app-gen.gif"> If you would like to set your default schematics to anything other than `@nstudio/xplat` you can always execute app generators via the more verbose style: ``` nx g @nstudio/xplat:app ``` ## Serving Application Run `nx serve appname` to serve the newly generated application!
Markdown
UTF-8
6,627
2.515625
3
[]
no_license
--- title: iOS与React-Native通信 date: 2017-03-17 09:46:48 tags: - React Native - iOS --- # iOS 与 React Native 通信踩坑小结 公司目前的项目主要使用的 React Native,但是 RN 这么久了还只是在 0.x 徘徊,不可避免有很多缺失的功能需要原生开发,然后嵌入到 RN 中,尤其是一些有我天朝特色的,比如支付宝支付,微信 QQ 等的第三方分享。 集成支付宝支付的时候,需要在原生里面监听支付结束的动作,然后收到支付宝返回的结果参数,再与自家的后端交互确定最终的支付结果,这里不可避免的涉及到 iOS 监听到支付结束,然后向 RN 发消息。 <!--more--> ## 支付宝带给我的伤害 iOS 相关目录大致如下: ![](https://ww2.sinaimg.cn/large/006tNbRwly1fdpn3d7nuej30770fsmx7.jpg) `Alipay` 文件夹下即为支付宝相关文件,这里就是比较常用的使 `AlipayXss` 类遵守 `RCTBridgeModule` 协议,`#import "RCTEventDispatcher.h"` 这个是 OC 向 RN 发事件需要用到的。 ```Objective-C // AlipayXss.h #import <Foundation/Foundation.h> #import "RCTBridgeModule.h" #import "RCTEventDispatcher.h" @interface AlipayXss : NSObject <RCTBridgeModule> @end ``` ```Objective-C // AlipayXss.m @synthesize bridge = _bridge; // 括号中的参数用来制定在 js 中访问这个模块的名字,不指定的情况下使用类的名字 RCT_EXPORT_MODULE(AlipayXss); // 为声明的模块添加方法,对外暴露的方法 RCT_EXPORT_METHOD(pay:(NSString *)orderString fromApp:(NSString *)appScheme) { // 调用支付宝支付 [self doAlipayPay :orderString :appScheme]; } ``` 这里`RCT_EXPORT_MODULE``RCT_EXPORT_METHOD`这两个宏是将 AlipayXss 模块暴露给 RN,如此 RN 才能调用这里的支付方法。 ```Objective-C [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) { // 向商家服务端发送 resultDic 在服务端验证是否正确完成支付 [self.bridge.eventDispatcher sendAppEventWithName:@"payResult" body:resultDic]; }]; ``` 支付宝文档写明支付完成时会调用这个回掉,然后我就这么写了,在这里发事件将参数传给 RN,在模拟器上表现也很正常,但是后来拿到真机上就傻了,无论如何都 RN 都接收不到这个事件,后来仔细看看文档才知道这个回掉只在用户调起的是网页版支付宝支付结束才会启用,真机上调起的是支付宝 app ,所以不会走这个回调。 支付宝 app 支付结束后启用的回掉在 AppDelegate 里,如下 ```Objective-C // AppDelegate.m - (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options { if ([url.host isEqualToString:@"safepay"]) { // 支付跳转支付宝钱包进行支付,处理支付结果 [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) { [self.bridge.eventDispatcher sendAppEventWithName:@"payResult" body:resultDic]; }]; } return YES; } ``` 这是我最开始的代码,但是相信我,如果你也这么写了那么你还是只能在 RN 那里干瞪眼,因为你同样接收不到事件,如果你再打断点一步步跟着走你还会发现上面这个方法每一步都完美地执行了,但你就是收不到消息。原因大致是AppDelegate 那里我们用处理之前的 AlipayXss 一样的手法使它遵守了 RCTBridgeModule,这会在模块启动的时候创建一个对象,但是 iOS 应用启动的时候也会创建一个 AppDelegate 的对象,这两个对象是不一样的。 StackOverFlow 上有相关问题,[链接在这里](http://stackoverflow.com/questions/35192324/react-native-sending-events-from-native-to-javascript-in-appdelegate-ios)。 但是悲剧的是没有实例呀,对于我这种 OC 都看不太懂的人真是要了老命了,后来陆陆续续看了点 OC 与 RN 通信原理解析又尝试了多种方法弄出来了一个相对简单的方法,如下: ```Objective-C // AppDelegate.m RCTRootView *rootView; - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [self configureAPIKey]; NSURL *jsCodeLocation; jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil]; rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation moduleName:@"xss" initialProperties:nil launchOptions:launchOptions]; rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1]; // 其他操作 } ``` iOS 应用启动时会走 `- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions` 方法,在这里实例化了 RCTRootView 对象,并且在这里指定了 js 的引用位置,它作为一个容器包裹着我们的 RN 应用,而在`RootView`创建之前,RN 先创建了一个 `Bridge` 对象,它是 OC 与 RN 交互的桥梁,这个东西就与我们碰到的问题息息相关,顺手一提,这里还有一个 `setUp` 方法,任务是创建 `BatchBridge`,据说大部分的工作都在这个东西里面。 ```Objective-C // AppDelegate.m - (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options { if ([url.host isEqualToString:@"safepay"]) { // 支付跳转支付宝钱包进行支付,处理支付结果 [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) { [rootView.bridge.eventDispatcher sendAppEventWithName:@"payResult" body:resultDic]; }]; } return YES; } ``` 将原本的 self 变为 rootView,这次你可以再 RN 正常地接收事件了。 ## 其他的坑 有的时候发消息 RN 无法接收到,一个可能的原因是此时 RN 端的监听事件还没有来得及建立,只要写个延时就 OK。 ```Objective-C [self performSelector:@selector(FounctionName) withObject:nil afterDelay:1.0f]; ``` ## 参考链接 - [React Native 从入门到原理](http://www.jianshu.com/p/978c4bd3a759) - [一篇较为详细的 iOS react-native 创建 View 过程 源码解析](http://www.jianshu.com/p/c2a458555de9) - [ReactNative iOS源码解析](http://awhisper.github.io/2016/06/24/ReactNative%E6%B5%81%E7%A8%8B%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/) - [React Native 与原生之间的通信(iOS)](http://www.jianshu.com/p/9d7dbf17daa5#)
C++
UTF-8
4,425
3.140625
3
[]
no_license
#pragma once #ifndef PT_MATH_PLANE_H #define PT_MATH_PLANE_H #include "pt/vector.h" #include "pt/matrix.h" #include "pt/matrix_operations.h" namespace pt { namespace math { // The members of the Plane structure take the form of the general plane equation. They fit into the general plane equation so that Ax + By + Cz + Dw = 0. // a*x + b*y + c*z + d = 0 class plane { public: plane() { } plane(vector3f normal, float d) : m_data(normal, d) { } vector3f normal() const { return vector3f(m_data[0], m_data[1], m_data[2]); } float d() const { return m_data[3]; } float const* data() const { return m_data.data(); } vector4f const& as_vector() const { return m_data; } private: vector4f m_data; }; inline plane make_plane(vector3f const& point, vector3f const& normal) { auto normalized = normalize(normal); float d = -dot(point, normalized); return plane(normalized, d); } inline plane make_plane(vector3f const& point, vector3f const& direction1, vector3f const& direction2) { vector3f normal = cross(direction1, direction2); return make_plane(point, normal); } inline plane make_plane_from_points(vector3f const& point0, vector3f const& point1, vector3f const& point2) { auto normal = normalize(cross(point1 - point0, point2 - point0)); return make_plane(point0, normal); } inline plane normalize(plane const& p) { auto normal = p.normal(); float distance = length(normal); normal = normal / distance; float d = p.d() / distance; return plane(normal, d); } inline float distance(plane const& plane, vector3f const& point) { auto normal = plane.normal(); return normal[0] * point[0] + normal[1] * point[1] + normal[2] * point[2] + plane.d(); } inline vector3f closest_point(plane const& plane, vector3f const& point) { return point - plane.normal() * distance(plane, point); } inline float dot_coord(plane const& plane, vector3f const& v) { auto normal = plane.normal(); return normal[0] * v[0] + normal[1] * v[1] + normal[2] * v[2] + plane.d(); } inline float dot_normal(plane const& plane, vector3f const& v) { auto normal = plane.normal(); return normal[0] * v[0] + normal[1] * v[1] + normal[2] * v[2]; } inline matrix4x4f reflect(plane const& plane_) { // P = normalize(plane); // - 2 * P.a * P.a + 1 - 2 * P.b * P.a - 2 * P.c * P.a 0 // - 2 * P.a * P.b - 2 * P.b * P.b + 1 - 2 * P.c * P.b 0 // - 2 * P.a * P.c - 2 * P.b * P.c - 2 * P.c * P.c + 1 0 // - 2 * P.a * P.d - 2 * P.b * P.d - 2 * P.c * P.d 1 plane p = normalize(plane_); float a = p.normal()[0]; float b = p.normal()[1]; float c = p.normal()[2]; float d = p.d(); matrix4x4f m(matrix4x4f::uninitialized); m(0, 0) = -2.0f * a * a + 1; m(1, 0) = -2.0f * a * b; m(2, 0) = -2.0f * a * c; m(3, 0) = -2.0f * a * d; m(0, 1) = -2.0f * b * a; m(1, 1) = -2.0f * b * b + 1; m(2, 1) = -2.0f * b * c; m(3, 1) = -2.0f * b * d; m(0, 2) = -2.0f * c * a; m(1, 2) = -2.0f * c * b; m(2, 2) = -2.0f * c * c + 1; m(3, 2) = -2.0f * c * d; //m.set_row(3, vector4f(0, 0, 0, 1)); m.set_column(3, vector4f(0, 0, 0, 1)); return m; } inline plane transform(plane const& p, matrix4x4f const& m) { //_pos = trans * _pos; //_direction = trans * _direction - trans * Vector0; //_d = -(_pos*_direction); //plane p2 = normalize(p); //vector3f origo = p2.normal() * p2.d(); //vector3f normal = p2.normal(); //origo = transform_position(origo, m); //auto m2 = transpose(invert(m)); //normal = transform_direction(normal, m2) - transform_direction(vector3f(), m2); //float d = -dot(origo, normal); //return normalize(plane(normal, d)); ///// vector3f origo = p.normal() * p.d(); vector3f normal = p.normal(); assert(length(normal) > 0.99f && length(normal) < 1.01f); auto m2 = transpose(invert(m)); origo = transform_position_w(origo, m); normal = transform_direction(normal, m2); //normal = transform_direction(normal, m2); ////normal = transform_direction(normal, transpose(m2)); ////float d = dot(origo, normal); ////return plane(normal, d); return make_plane(origo, normal); } }} #endif
Markdown
UTF-8
6,435
2.78125
3
[]
no_license
# How to setup a project with webpack + react + Eslint & prettier In this tutorial i will guide you through the steps that will brings to the final result by explaining the every step in order to obtain this INSERT MP4 HERE ## initial setup first let create a new folder ```sh mkdir MyProject cd MyProject ``` Now let's initialize the project with npm that allows us to manage our dependencies ```sh npm init -y ``` use -y if you want to skip the wizard and to use default values that can be changes inside `package.json` [optional] Initialize the project if you want to push it to a github repo: ```sh git init touch .gitignore ``` **pro tip**: [touch](https://www.geeksforgeeks.org/touch-command-in-linux-with-examples/) can be used to create new files in the .gitignore let's add the following ``` node_modules ``` let's start creating some folders, the structure is up to you but i suggest to organize things in this way: ```sh mkdir src mkdir assets ``` - **src** is where all the codebase will be placed - **assets** is where you can place images, fonts etc Now you are ready to install all the needed dependencies ## initial webpack setup Using *webpack* gives the power to let's start by installing in our dev dependencies **webpack** and **webpack-cli** and **webpack-dev-server** plus **html-webpack-plugin** ```sh npm install -D webpack webpack-cli webpack-dev-server html-webpack-plugin babel-loader style-loader css-loader ``` [webpack-dev-server](https://www.npmjs.com/package/webpack-dev-server) is used for running your project in watch mode, and for every change in the codebase included in webpack your project will rebuild and reload automatically in the browser. This will save your mental sanity and boost your humor, since you do not have to hit "compile" every single change you do let's also create the webpack config that will be used for development purposes ```sh touch webpack-config.js ``` let's also create a `main.jsx` and an `index.html` inside **src** folder ```sh cd src touch main.jsx touch index.html cd .. ``` in the `index.html` put ```html <!DOCTYPE html> <head> <title> test </title> </head> <html> <body> <div id="root"> </div> </body> </html> ``` while in the `main.jsx` put ```jsx import React from "react"; import ReactDOM from "react-dom"; const App = () => { return <div> ChronosOutOfTime thanks so much</div>; }; ReactDOM.render(<App />, document.querySelector("#root")); ``` now we just need to configure our webpack to run it when we run **npm start** so in the `webpack.config.js` put: ```js const path = require("path"); const HtmlWebpackPlugin = require("html-webpack-plugin"); module.exports = { mode: "development", entry: "./src/main.jsx", output: { path: path.resolve(__dirname, "dist"), filename: "bundle.js", clean: true, }, plugins: [ new HtmlWebpackPlugin({ title: "My Awesome Custom Project", template: "src/index.html", }), ], resolve: { extensions: [".js", ".jsx"], }, module: { rules: [ { test: /\.css$/i, use: ["style-loader", "css-loader"], }, { test: /\.jsx?$/, loader: "babel-loader", exclude: /node_modules/, include: [path.join(__dirname, "src")], }, ], }, devServer: { hot: true, client: { progress: true, }, }, }; ``` ## Install our preferred framework libs or other vanilla js deps (React) In my case i chose React since it's widely used, but you can use different frameworks / libs, the purpose of this tutorial is the same. ```sh npm install react react-dom ``` And since we are using react we want to take advantage of writing out components with the **[jsx](https://reactjs.org/docs/introducing-jsx.html)** format hence we need to **[babelize](https://babeljs.io/docs/en/#jsx-and-react)** our code. let's install babel dependencies ```sh npm install -D @babel/core @babel/preset-env @babel/preset-react babel-eslint babel-loader ``` and let's create our `.babelrc` ```sh touch .babelrc ``` where we will put the following ```json { "presets": [ "@babel/preset-env", "@babel/preset-react" ] } ``` ## ESlint let's prepare eslint configuration and needed deps ```sh npm install -D eslint eslint-config-prettier eslint-loader eslint-plugin-prettier prettier ``` i also suggest if you are using vs code to install the extension [error lens](https://marketplace.visualstudio.com/items?itemName=usernamehw.errorlens) let's create our eslint config ```sh touch .eslintrc.js ``` and copy the following code: ```js module.exports = { env: { commonjs: true, node: true, browser: true, es6: true, jest: true, }, parserOptions: { extends: ["react:recommended", "eslint:recommended", "prettier"], parser: "@babel/eslint-parser", sourceType: "module", ecmaVersion: 2020, ecmaFeatures: { jsx: true, }, }, plugins: ["prettier"], // add your custom rules here rules: { "prettier/prettier": [ "error", { endOfLine: "auto", }, ], }, }; ``` ## but, Why prettier + eslint? The reason is that [prettier](https://prettier.io/docs/en/why-prettier.html) does very well one thing, formatting your code. While [ESlint](https://eslint.org/) does many things, it is great for checking your syntax of your code and to prevent errors Let me share [this blog](https://blog.theodo.com/2019/08/why-you-should-use-eslint-prettier-and-editorconfig-together/) where i found the inspiration for this video Now let's configure a settings for vs code that will be absolutely the cherry on the pie: - open vs code settings (json) with CTRL + P - add the following: ```json "editor.codeActionsOnSave": { "source.fixAll.eslint": true }, ``` This tiny option is what allows you to get the magic ## Conclusions So this is it, this project can be used with any framework you like, some changes may be needed in the `.eslintrc.js` and `.babelrc` If you have any suggestions you can: - open an issue - open a PR - fork it and do whatever you want - comment on the youtube channel or discord I hoped i helped anybody with this little demo and if you liked this you can subscribe: - on my [youtube channel](https://www.youtube.com/channel/UCOQOna7UFhT2skDitsDXaLA/videos) - on my [discord channel](https://discord.com/channels/760625029930156042/760625029930156045)
Java
UTF-8
463
2.625
3
[]
no_license
public class Filho extends Pai implements Familia{ private String email; public Filho(String nome, int idade, String email) { super(nome, idade); this.email = email; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String dados() { return ("Nome: "+this.getNome()+ " Idade: "+this.getIdade()+ " Email: "+ email); } }