language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
C#
UTF-8
1,356
2.96875
3
[]
no_license
namespace Northwind.Common.Infrastructure.Validation { using System; public class Validator { public static void ThrowIfNull(object obj, string message = "") { if (obj == null) { if (message == string.Empty) { message = string.Format(ValidationConstants.ValueNullMsg, nameof(obj)); } throw new ArgumentException(message); } } public static void ThrowIfNullEmptyOrWhiteSpace(string param, string paramName, string message = "") { if (string.IsNullOrWhiteSpace(param)) { if (message == string.Empty) { message = string.Format(ValidationConstants.ValueNullEmptyWhiteSpaceMsg, paramName); } throw new ArgumentException(message); } } public static void ThrowIfZeroOrNegative(int param, string paramName, string message = "") { if (param <= 0) { if (message == string.Empty) { message = string.Format(ValidationConstants.ValueZeroOrNegativeMsg, paramName); } throw new ArgumentException(message); } } } }
JavaScript
UTF-8
2,112
2.703125
3
[]
no_license
var testCase = require('nodeunit').testCase; module.exports = testCase({ setUp: function(callback){ var rps = require('../src/rps'); this.rps = new rps.RPS(); callback(); }, tearDown: function(callback){ callback(); }, "TC 1 - Player() - constructor": testCase({ "test should take 1 string arg, a player id unique to this RPS instance": function(test) { var that = this; test.throws( function() { var player = new that.rps.Player(); }, Error ); test.throws( function(){ var player1 = new that.rps.Player('abc123'); var player2 = new that.rps.Player('abc123'); }, Error ) test.done(); } }), "TC 2 - Player.ready()": testCase({ "test should set player.ready to true": function(test) { var player = new this.rps.Player('abc123'); player.ready(); test.equal(player.isReady(), true); test.done(); }, }), "TC 3 - Player.updateRecord()": testCase({ "test should accept a record type arg and increment it by 1": function(test) { var player = new this.rps.Player('abc123'); player.updateRecord('wins'); test.equal(player.getRecord()['wins'], 1); test.equal(player.getRecord()['losses'], 0); test.equal(player.getRecord()['ties'], 0); player.updateRecord('wins'); player.updateRecord('losses'); player.updateRecord('ties'); test.equal(player.getRecord()['wins'], 2); test.equal(player.getRecord()['losses'], 1); test.equal(player.getRecord()['ties'], 1); test.done(); } }), "TC 4 - Player.again()": testCase({ "test should reset player.ready back to false": function(test) { var player = new this.rps.Player('abc123'); player.ready(); player.again(); test.equal(player.isReady(), false); test.done(); } }) });
SQL
UTF-8
147
2.609375
3
[]
no_license
DROP PROCEDURE IF EXISTS GetAll; DELIMITER // CREATE PROCEDURE GetAll() BEGIN SELECT * FROM user u, project p WHERE u.id = p.id; END // DELIMITER ;
Markdown
UTF-8
2,618
3.0625
3
[]
no_license
--- description: Haiku Animator integrates with the tools you already love. Draw in Sketch, bring to life in Animator. Let's start by covering how to get your Sketch design into Animator. --- # Sketch and Other Image Assets Animator doesn't _yet_ provide its own drawing tools. Though we plan to add some in the future, this was an intentional decision. Designers told us resoundingly that they don't want _yet another drawing tool_, so we simply integrated with existing ones. Think of it this way: **draw in your favorite drawing tool, bring to life in Animator.** Let's first cover how to get your Sketch design into Animator: <br> #### HOW TO LINK A SKETCH FILE {#linksketch} The first step to bringing your Sketch design to life is to import it. To do so, simply click "IMPORT" at the top of the library panel. ![](/assets/import-sketch.jpg) Behind the scenes, we convert all your Sketch design's artboards, pages, and slices into individual assets that may be independently composed and animated on stage. To get an asset on stage, just drag and drop it! <br> #### DRAGGING AND DROPPING ITEMS ON STAGE {#draganddrop} This one's self-explanatory: to get an item from the Library to the Stage, simply drag and drop. The new element will show up on the stage where you drop it, and a new row will show up in the Timeline representing the new element. <br> #### CHANGING ASSETS FROM SKETCH {#changeassets} What if you need to make a change to the Sketch file? That's fine! We'll take care of bringing your new changes into Animator and onto any assets you've placed on the stage. When you import a Sketch file, we automatically make a copy of that file and start tracking changes behind the scenes with Git. _What this means is if you make changes to your original file, they won't show up by default in Animator._ **To make changes to your Sketch-linked assets, double-click the Sketch file in the library.** Sketch will launch, and when you **Save** in Sketch, changes will automatically be tracked in Animator. Even elements already on the stage remain linked and can be updated directly from Sketch. ![](/assets/open-sketch.gif) #### Other Image Assets {#other} Animator also supports SVG files. If you want to work with an .svg file, just click "IMPORT" in your library as we did above for a .sketch file. If you want to work with raster assets (JPEG, PNG, etc) the best way to currently do that is to paste your asset into a .sketch file, and mark that Sketch layer for export or as a slice. <br> [Next: Importing Figma Projects](/using-haiku/importing-figma-projects.md) &rarr;
Markdown
UTF-8
2,587
3.65625
4
[]
no_license
### LESS >LESS是一种动态样式语言,属于CSS预处理语言的一种,它使用类似CSS的语法,为CSS赋予了动态语言的特性,如变量、继承、运算、函数等,更方便CSS的编写和维护。 #### 变量 ```less @red: #E10602; @blue: #2932E1; @yellow: #CAA066; .name{ color: @yellow; .first{ color: @red; } .second{ color: @blue; } } ``` 编译之后为: ```css .name { color: #CAA066; } .name .first { color: #E10602; } .name .second { color: #2932E1; } ``` 变量甚至可以在定义的时候使用其他变量的值 ```less @content: '.'; @pseudo: 'content'; clearfix:after{ content: @@pseudo; } ``` 输出css: ```css clearfix:after { content: "."; } ``` 变量中的作用域,当前作用域中最后一次的定义将被使用,和css的机制是类似的。 ```less @var: 0; html{ @var: 1; body{ @var: 2; div: @var; @var: 3; } div: @var; } ``` 编译处理之后为: ```css html { div: 1; } html body { div: 3; } ``` ### 混合 混合——通俗的将有点像php中的Trait,会将一段定义好的样式代码直接复制到使用的地方 ```less .clearfix-after{ content: '.'; height: 0; display: block; clear: both; overflow: hidden; } #flow-left{ flow: left; } .show-name{ color: red; width: 100px; .clearfix-after; #flow-left; } ``` 编译之后的css: ```css .clearfix-after { content: '.'; height: 0; display: block; clear: both; overflow: hidden; } .show-name { color: red; width: 100px; content: '.'; height: 0; display: block; clear: both; overflow: hidden; flow: left; } ``` 但是这样会将不想要的`.clearfix-after`、`#flow-left`也引到样式文件中,污染了样式表,可以通过在样式名后面加双括号让编译器知道他不是一个正常的样式`.clearfix-after()`。当然了,混合中还可以使用参数以及默认值`.clearfix-after(@x: 0, @y: 0, @blur: 1px, @color: #000)`,使用的时候`.clearfix-after(2px 5px);`, ```less .box-shadow(@x: 0,@y: 0, @blur: 1px, @color: #000){ box-shadow: @arguments; -moz-box-shadow: @arguments; -webkit-box-shadow: @arguments; } .box-shadow(2px, 5px); ``` 输出 ```css box-shadow: 2px 5px 1px #000; -moz-box-shadow: 2px 5px 1px #000; -webkit-box-shadow: 2px 5px 1px #000; ``` @arguments——`@arguments`表示所有的参数。 @rest——`@rest`表示从自己开始的所有参数。 !important——`!important`会给混合中的所有属性都标记为`!important`。
Java
UTF-8
1,137
1.960938
2
[]
no_license
package com.example.nychighschools.di.scores; import android.arch.lifecycle.ViewModelProviders; import com.example.nychighschools.di.app.Repository; import com.example.nychighschools.repo.DataSource; import com.example.nychighschools.scores.DetailsActivity; import com.example.nychighschools.scores.DetailsViewModel; import com.example.nychighschools.scores.DetailsViewModelFactory; import dagger.Module; import dagger.Provides; @Module public class ScoreDetailsModule { private final DetailsActivity detailsActivity; public ScoreDetailsModule(DetailsActivity detailsActivity) { this.detailsActivity = detailsActivity; } @Provides @ScoreDetailsScope public DetailsViewModelFactory provideDetailsViewModelFactory(@Repository DataSource schoolsRepository) { return new DetailsViewModelFactory(schoolsRepository); } @Provides @ScoreDetailsScope public DetailsViewModel provideDetailsViewModel(DetailsViewModelFactory detailsViewModelFactory){ return ViewModelProviders.of(detailsActivity, detailsViewModelFactory) .get(DetailsViewModel.class); } }
Markdown
UTF-8
5,643
2.90625
3
[]
no_license
# Connecting to an LDAP Directory Lightweight Directory Access Protocol (LDAP) servers are common user stores for Liferay DXP. You can configure LDAP at the system scope in System Settings or at the instance scope in Instance settings. Users can be imported from or exported to LDAP. ## Adding a New LDAP Server Connection To access LDAP configuration settings at the Instance level, 1. Navigate to *Control Panel &rarr; Configuration* &rarr; *Instance Settings* ![LDAP configurations are available at the instance level and at the System level.](./connecting-to-an-ldap-directory/images/01.png) 1. Click *LDAP* &rarr; and click *Servers* 1. Click the *Add* button to add an LDAP server connection. 1. Enter configuration values for your LDAP server. See the [configuration reference](#ldap-server-configuration-reference) for details. You may, however, need to customize the rest of the configuration, as it represents "best guesses" as to correct defaults. The default attribute mappings usually provide enough data to synchronize back to the Liferay database when a user attempts to log in. To test the connection to your LDAP server, click the *Test LDAP Connection* button. If you have more than one LDAP server, you can arrange the servers by order of preference using the up/down arrows. Regardless of how many LDAP servers you add, each server has the same configuration options. ### Using the System Settings Scope Alternatively, you can define an LDAP server connection at the System Settings scope through the System Settings menu or with the usage of OSGi `.config` files. ```tip:: The LDAP server configuration screen in *Instance Settings* has utilities to assist with configuring an LDAP connection. You can use this utility to validate your settings first, before entering them at the System Settings scope. ``` The easiest way to do use `.config` files is to use the GUI and export the configuration. Then you can use the resulting `.config` file anywhere you need it (such as other nodes in a cluster). ```note:: To use `config` files for LDAP server configuration, you must specify the Virtual Instance ID (in the source, the variable name is `companyId`) in the exported configuration file, because servers are defined at the instance scope, not the system scope. To do this, specify the virtual instance ID somewhere in the file like this: :: companyId=1234 You can find your Virtual Instance ID in *Control Panel* -> *Configuration* -> *Virtual Instances*. ``` ## LDAP Server Configuration Reference **Server Name:** Enter a name for your LDAP server. **Default Values:** Several common directory servers appear here. If you use one of these, select it to populate the rest of the form with default values for that directory. These settings cover the connection to LDAP. **Base Provider URL:** The link to the LDAP server. Make sure the Liferay server can communicate with the LDAP server. If there is a firewall between the two systems, make sure the appropriate ports are opened. **Base DN:** The Base Distinguished Name for your LDAP directory, usually modeled after your organization. It may look like this: `dc=companynamehere,dc=com`. **Principal:** The default LDAP administrator user ID is populated here. If your administrator ID differs, use that credential instead. You need an administrative credential because Liferay uses this ID to synchronize user accounts to and from LDAP. **Credentials:** Enter the password for the LDAP administrative user. ## Checkpoint Before proceeding to fine tune Liferay's LDAP connections, ensure the following steps have been taken: 1. The LDAP connection is enabled. Depending on your needs, LDAP authentication may be required so that only users who have been bound may log in. 1. *Export/Import*: for users in a clustered environment, Enable Import/Export on Startup should be disabled so that there are no massive imports on every node upon start up. 1. When adding the LDAP server, the *Server Name*, *Default Values*, *Connection* values are correct. It is always a good idea to click the *Test LDAP Connection* before saving. ## Using SSL to Connect to an LDAP Server If you run your LDAP directory in SSL mode to encrypt credential information on the network, you must perform extra steps to share the encryption key and certificate between the two systems. For example, if your LDAP directory is Microsoft Active Directory on Windows Server 2003, you'd share the certificate like this: 1. Click *Start* &rarr; *Administrative Tools* &rarr; *Certificate Authority*. 1. Highlight the machine that is the certificate authority, right-click on it, and click *Properties*. 1. From the General menu, click *View Certificate*. 1. Select the Details view, and click *Copy To File*. Use the resulting wizard to save the certificate as a file. 1. Import the certificate into the *cacerts keystore* like this: ```bash keytool -import -trustcacerts -keystore /some/path/java-8-jdk/jre/lib/security/cacerts -storepass changeit -noprompt -alias MyRootCA -file /some/path/MyRootCA.cer ``` The `keytool` utility ships as part of the Java SDK. 1. Go back to the LDAP page in the Control Panel. 1. Modify the LDAP URL in the Base DN field to the secure version by changing the protocol to `ldaps` and the port to `636` like this: ``` ldaps://myLdapServerHostname:636 ``` Save the changes. Communication to LDAP is now encrypted. To tune or configure how Liferay DXP matches users in LDAP for syncing, please see [configuring import and export](./configuring-user-import-and-export.md).
Java
UTF-8
1,503
3
3
[]
no_license
package repository; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Query; import model.Product; import util.EntityManagerUtil; public class ProductRepository { private EntityManager em; public List<Product> findAll() { em = EntityManagerUtil.getEntityManager(); // read the existing entries and write to console Query q = em.createQuery("select t from Product t"); List<Product> productList = q.getResultList(); for (Product product : productList) { System.out.println(product); } System.out.println("Size: " + productList.size()); em.close(); return productList; } public Product create(Product product) { em = EntityManagerUtil.getEntityManager(); em.getTransaction().begin(); em.persist(product); em.getTransaction().commit(); em.close(); return product; } public Product update(Product product) { em = EntityManagerUtil.getEntityManager(); em.getTransaction().begin(); em.merge(product); em.getTransaction().commit(); em.close(); return product; } public Product findById(Integer id) { em = EntityManagerUtil.getEntityManager(); em.getTransaction().begin(); Product product = em.find(Product.class, id); em.close(); return product; } public boolean delete(Integer id) { em = EntityManagerUtil.getEntityManager(); em.getTransaction().begin(); Product product = em.find(Product.class, id); em.remove(product); em.getTransaction().commit(); em.close(); return true; } }
Java
UTF-8
2,735
2.34375
2
[]
no_license
package dalcoms.pub.connect3blocks; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.andengine.engine.handler.timer.ITimerCallback; import org.andengine.engine.handler.timer.TimerHandler; import org.andengine.extension.physics.box2d.PhysicsWorld; import android.util.Log; import com.badlogic.gdx.physics.box2d.Contact; import com.badlogic.gdx.physics.box2d.ContactImpulse; import com.badlogic.gdx.physics.box2d.ContactListener; import com.badlogic.gdx.physics.box2d.Fixture; import com.badlogic.gdx.physics.box2d.Manifold; import dalcoms.pub.connect3blocks.scene.SceneGame; public class RectangleBrick extends RectanglePhysics { private int mBreakLevel = 1; public RectangleBrick( float pX, float pY, float pWidth, float pHeight, SceneGame pSceneGame ) { super( pX, pY, pWidth, pHeight, pSceneGame ); } public RectangleBrick( float pWidth, float pHeight, SceneGame pSceneGame ) { super( 0, 0, pWidth, pHeight, pSceneGame ); } public RectangleBrick setBreakLevel( int pBreakLevel ) { this.mBreakLevel = pBreakLevel; return this; } public int getBreakLevel( ) { return this.mBreakLevel; } @Override public void onUpdateCheck( ) { } public float getCenterX( ) { return getX() + getWidth() * 0.5f; } public float getCenterY( ) { return getY() + getHeight() * 0.5f; } private boolean checkCollisionWithBall( ) { boolean result = false; if ( this.collidesWith( getGameScene().getMainBall() ) ) { result = true; } return result; } private boolean checkBreakMySelf( boolean pBreak ) { // if break level reach to zero, byebye myself boolean result = false; if ( pBreak ) { final int pBreakLevel = getBreakLevel() - 1; if ( pBreakLevel > 0 ) { setBreakLevel( pBreakLevel ); this.breakMySelf(); } else { result = true; } } return result; } public boolean checkBreakMySelf( ) { // if break level reach to zero, byebye myself boolean result = false; final int pBreakLevel = getBreakLevel() - 1; if ( pBreakLevel > 0 ) { setBreakLevel( pBreakLevel ); this.breakMySelf(); } else { result = true; } return result; } private void breakMySelf( ) { if ( this.getWidth() > this.getHeight() ) { this.setWidth( this.getWidth() * 0.5f ); } else { this.setHeight( this.getHeight() * 0.5f ); } this.getGameScene().getEngine().registerUpdateHandler( new TimerHandler( 0.05f, new ITimerCallback() { @Override public void onTimePassed( TimerHandler pTimerHandler ) { getGameScene().getEngine().unregisterUpdateHandler( pTimerHandler ); reCreateBody(); } } ) ); } }
Markdown
UTF-8
1,521
2.640625
3
[]
no_license
# Live Updating / Streams / Websockets / Push Models --- > stub --- How does this work? - rooms created per-user (like Emailbox) - is Firebase overkill? (yeah) - Just need to be notified of new models, changes, and to know the last __version, corret? This will be tested/used on the Inbox PageView at first. It is a perfect candidate to be "pushed" updates. When a collection is fetched, it would want to know when a certain model type is updated, correct? Collection "live" status can be - triggers a "fetch" or "pager" or something on the collection? - nah, just listen for an update, then do the necessary fetch/pager - `App.Events.on('model-added-of-type-Profile', ...` - Models listen on App.Events. if App.Events is a Firebase queue, can I choose which queue it is on? And then set permissions to access that queue? - yes - Looks like I need to simply add an Auth rules for every queue ( https://www.firebase.com/docs/security/custom-login.html one of your models has been updated, or a friend's model updated - on server: determine everybody the action/db change affects (user_ids) - determine the Models affected (User, Message) - increment _version of that Model for each affected user - basically creates a few rooms/channels/urls(firebase) for each user - on client: connect to stream/websocket from server - when an update occurs, we'll get the Model it affects, and update all the created local models (by checking version?) - ...does it make sense to update all the models? -
Swift
UTF-8
1,549
2.859375
3
[ "MIT" ]
permissive
// // NSLayoutConstraintSearch.swift // UIKitSwagger // // Created by Sam Odom on 9/25/14. // Copyright (c) 2014 Sam Odom. All rights reserved. // import UIKit internal extension NSLayoutConstraint { internal func hasItem(item: AnyObject) -> Bool { return firstItem.isEqual(item) || (secondItem != nil && secondItem!.isEqual(item)) } internal func hasItems(itemOne: AnyObject, _ itemTwo: AnyObject) -> Bool { assert(itemOne !== itemTwo, "The items must be different") return secondItem != nil && itemsMatch(itemOne, itemTwo) } private func itemsMatch(itemOne: AnyObject, _ itemTwo: AnyObject) -> Bool { return firstItem.isEqual(itemOne) && secondItem!.isEqual(itemTwo) || firstItem.isEqual(itemTwo) && secondItem!.isEqual(itemOne) } internal func hasAttribute(attribute: NSLayoutAttribute) -> Bool { return firstAttribute == attribute || secondAttribute == attribute } internal func hasAttributedItem(attributedItem: AutoLayoutAttributedItem) -> Bool { switch attributedItem.attribute { case firstAttribute: return firstItem.isEqual(attributedItem.item) case secondAttribute: return secondItem != nil && secondItem!.isEqual(attributedItem.item) default: return false } } internal func hasAttributedItems(itemOne: AutoLayoutAttributedItem, _ itemTwo: AutoLayoutAttributedItem) -> Bool { return hasAttributedItem(itemOne) && hasAttributedItem(itemTwo) } }
Shell
UTF-8
4,378
3.734375
4
[]
no_license
#!/bin/sh # Usage: sh jabbaPerfTest.sh {Experiment Number List} {Request Per Second List} # Example : sh jabbaPerfTest.sh batch 5,10,15 100,200,300,350,400 # Example : sh jabbaPerfTest.sh single 1,3,6,9 100,200,300,350,400 # Example : sh jabbaPerfTest.sh batch 5,10,15 100,200,300,350,400,800 mixed if [ -f jabbaPerfTest.pid ]; then echo "There is an instance of jabbaPerfTest is running, can't run two jabbaPerfTest instance at the same time" exit 1 fi echo $$ > jabbaPerfTest.pid user_str="" batch_or_single=${1} export batch_or_single host="" if [ "${batch_or_single}" == "single" ]; then test_file_prefix="jga512" log_type="tga512" mutual_exclusive=true output_file="single_list" else test_file_prefix="jba512" log_type="tba512" mutual_exclusive=false output_file="batch_list" fi # By default, single assignment test mutual exclusion and batch assignment does # not. but you can change it if you want to test otherwise. # mutual_exclusive=false # By default, we're testing server internal-jabba-perf-ilb-1595286552.us-west-2.elb.amazonaws.com. # but you can change default host when need test other server. # host=internal-jabba-perf-ilb-1595286552.us-west-2.elb.amazonaws.com # read experiment numbers to mens IFS=',' read -ra mens <<< "${2}" # read throughput list to tpts IFS=',' read -ra tpts <<< "${3}" # Setting this flag as true we will delete every experiment we created for the # test. otherwise we will keep all files on batch_list_all that we can delete # them all once. # we support three modes: new, old, mixed mode="new" if [ -n "${4}" ]; then mode=${4} fi housekeeping_need=true if [ "${housekeeping_need}" == "false" ]; then rm -rf ${output_file}_all fi # Keep all echo "Clean rurun file ${0}.rerun" rm -rf ${0}.rerun echo "Clean result file test_result" rm -rf test_result echo "Running throughput : " ${tpts[@]} echo "Experiment numbers : " ${mens[@]} mkdir -p logs for throughput in ${tpts[@]} do # Backup jmeter test file cp ${test_file_prefix}A.jmx .${test_file_prefix}A.bak cp ${test_file_prefix}C.jmx .${test_file_prefix}C.bak tpm=`expr ${throughput} \\* 60` tmp="${tpm}.0" # Default throughtput is 96000.0. We're setting throughtput here. # Given value is request per second, jmeter needs request per minute. sed -i -- "s/96000/${tpm}/g" ${test_file_prefix}A.jmx sed -i -- "s/96000/${tpm}/g" ${test_file_prefix}C.jmx if [ "${host}" != "" ]; then sed -i -- "s/internal-jabba-perf-ilb-1595286552.us-west-2.elb.amazonaws.com/${host}/g" ${test_file_prefix}A.jmx sed -i -- "s/internal-jabba-perf-ilb-1595286552.us-west-2.elb.amazonaws.com/${host}/g" ${test_file_prefix}C.jmx fi for exp_number in ${mens[@]} do echo batch_or_single=${1} >> ${0}.rerun echo export batch_or_single >> ${0}.rerun echo runTest.sh ${exp_number} ${mutual_exclusive} ${mode} >> ${0}.rerun sh runTest.sh ${exp_number} ${mutual_exclusive} ${mode} if [ $? -ne 0 ]; then echo "Error happened in runTest.sh, terminating tests and backup the result..." # No matter what we keep the result. mkdir ../../result mv test_result ../../result mv baklog* ../../result exit 1 fi if [ "${housekeeping_need}" == "true" ]; then sh deleteExperiments.sh ${output_file} else cat ${output_file} >> ${output_file}_all fi # Process the result. user_str=$(tr a-z A-Z <<< ${mode:0:1})${mode:1} user_str="${user_str} User" result=`sh extract_result.sh jmeter.log logs/${log_type}-${mode}.jtl` if [ "${mutual_exclusive}" == "true" ]; then with_str="With" else with_str="Without" fi me_str="(${with_str} Mutual Exclusive Throughput : ${throughput})" echo "${user_str}${me_str}: ${exp_number} Experiment" ${result} >> test_result done # restore jmeter files cp .${test_file_prefix}A.bak ${test_file_prefix}A.jmx cp .${test_file_prefix}C.bak ${test_file_prefix}C.jmx mkdir baklog-${batch_or_single}-${throughput} mv baklog/* baklog-${batch_or_single}-${throughput} #rename_files=`(cd baklog && ls)` #for file in ${files} #do # mv baklog/${file} baklog/${batch_or_single}-${throughput}-${file} #done done # Move test result for artifactory mkdir ../../result mv test_result ../../result mv baklog* ../../result # remove pid file to prevent lock. rm -rf jabbaPerfTest.pid
Java
UTF-8
15,649
1.742188
2
[]
no_license
package com.tecmanic.toketani.activity; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.RetryPolicy; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.tecmanic.toketani.R; import com.tecmanic.toketani.config.BaseURL; import com.tecmanic.toketani.modelclass.DeliveryModel; import com.tecmanic.toketani.util.SessionManagement; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.tecmanic.toketani.config.BaseURL.SELECT_ADDRESS_URL; import static com.tecmanic.toketani.config.BaseURL.SHOW_ADDRESS; public class SelectAddress extends AppCompatActivity { private static final int REQUEST_LOCATION_PERMISSION = 123; SessionManagement sessionManagement; LinearLayout back; LinearLayout addAddress; RecyclerView recycleraddressList; List<DeliveryModel> dlist; DeliveryAdapter deliveryAdapter; String userId; private int lastSelectedPosition = -1; private boolean showAdd = false; private LinearLayout progressBar; private void show() { if (progressBar.getVisibility() == View.VISIBLE) { progressBar.setVisibility(View.GONE); } else { progressBar.setVisibility(View.VISIBLE); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_select_address); dlist = new ArrayList<>(); init(); } private void init() { back = findViewById(R.id.back); addAddress = findViewById(R.id.addAdreess); recycleraddressList = findViewById(R.id.recycleraddressList); progressBar = findViewById(R.id.progress_bar); back.setOnClickListener(v -> { showAdd = false; onBackPressed(); }); sessionManagement = new SessionManagement(getApplicationContext()); userId = sessionManagement.getUserDetails().get(BaseURL.KEY_ID); addAddress.setOnClickListener(v -> { if (!userId.equalsIgnoreCase("")) { if (ContextCompat.checkSelfPermission(SelectAddress.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(SelectAddress.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { checkAndRequestPermissions(true); }else { Intent intf = new Intent(SelectAddress.this, AddAddressNew.class); startActivityForResult(intf, 21); } } else { Intent intf = new Intent(SelectAddress.this, LoginActivity.class); startActivity(intf); finish(); } }); showAdreesUrl(); } private void checkAndRequestPermissions(boolean status) { int locationPermission = ContextCompat.checkSelfPermission(SelectAddress.this, Manifest.permission.ACCESS_FINE_LOCATION); int locationPermissionCoarse = ContextCompat.checkSelfPermission(SelectAddress.this, Manifest.permission.ACCESS_COARSE_LOCATION); List<String> listPermissionsNeeded = new ArrayList<>(); if (locationPermission != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION); } if (locationPermissionCoarse != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION); } if (!listPermissionsNeeded.isEmpty()) { androidx.appcompat.app.AlertDialog.Builder alertDialog = new androidx.appcompat.app.AlertDialog.Builder(SelectAddress.this); alertDialog.setCancelable(false); alertDialog.setTitle("Location permission for grocery door step delivery"); alertDialog.setMessage("We need location for the following things and mentioned here.\n1. To show you your nearest grocery store at you location.\n2. To save your delivery address to provide your grocery at your door step or where you want."); alertDialog.setPositiveButton("Ok", (dialogInterface, i) -> { ActivityCompat.requestPermissions(SelectAddress.this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_LOCATION_PERMISSION); dialogInterface.dismiss(); }); alertDialog.setNegativeButton("dismiss", (dialogInterface, i) -> { dialogInterface.dismiss(); }); alertDialog.show(); } } private void showAdreesUrl() { dlist.clear(); show(); if (!userId.equalsIgnoreCase("")) { StringRequest stringRequest = new StringRequest(Request.Method.POST, SHOW_ADDRESS, response -> { try { JSONObject jsonObject = new JSONObject(response); String status = jsonObject.getString("status"); String msg = jsonObject.getString("message"); if (status.equals("1")) { JSONArray jsonArray = jsonObject.getJSONArray("data"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject1 = jsonArray.getJSONObject(i); String addressId = jsonObject1.getString("address_id"); String receiverName = jsonObject1.getString("receiver_name"); String receiverPhone = jsonObject1.getString("receiver_phone"); String cityyyy = jsonObject1.getString("city"); String society = jsonObject1.getString("society"); String houseNo = jsonObject1.getString("house_no"); String pincode = jsonObject1.getString("pincode"); String stateeee = jsonObject1.getString("state"); String landmark2 = jsonObject1.getString("landmark"); int selectStatus = jsonObject1.getInt("select_status"); DeliveryModel ss = new DeliveryModel(addressId, receiverName, receiverPhone, houseNo + ", " + society + "," + cityyyy + ", " + stateeee + ", " + pincode); ss.setCityName(cityyyy); ss.setHouseNo(houseNo); ss.setLandmark(landmark2); ss.setPincode(pincode); ss.setState(stateeee); ss.setReceiverPhone(receiverPhone); ss.setReceiverName(receiverName); ss.setId(addressId); ss.setSelectStatus(selectStatus); ss.setSociety(society); dlist.add(ss); } deliveryAdapter = new DeliveryAdapter(dlist); recycleraddressList.setLayoutManager(new LinearLayoutManager(getApplicationContext())); recycleraddressList.setAdapter(deliveryAdapter); deliveryAdapter.notifyDataSetChanged(); } else { Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } finally { show(); } }, error -> show()) { @Override protected Map<String, String> getParams() throws AuthFailureError { HashMap<String, String> param = new HashMap<>(); param.put("user_id", userId); param.put("store_id", sessionManagement.getStoreId()); return param; } }; stringRequest.setRetryPolicy(new RetryPolicy() { @Override public int getCurrentTimeout() { return 90000; } @Override public int getCurrentRetryCount() { return 0; } @Override public void retry(VolleyError error) throws VolleyError { } }); RequestQueue requestQueue = Volley.newRequestQueue(SelectAddress.this); requestQueue.getCache().clear(); requestQueue.add(stringRequest); } else { show(); } } @Override public void onBackPressed() { Intent intent = new Intent(); intent.putExtra("show_address", showAdd); setResult(2, intent); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { finishAndRemoveTask(); } else { finish(); } } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 21 && data != null && data.getBooleanExtra("select_address", false)) { showAdreesUrl(); } } public class DeliveryAdapter extends RecyclerView.Adapter<DeliveryAdapter.MyViewHolder> { private List<DeliveryModel> dlist; public DeliveryAdapter(List<DeliveryModel> dlist) { this.dlist = dlist; } @NonNull @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.layout_deliveryaddress, parent, false); return new MyViewHolder(itemView); } @Override public void onBindViewHolder(MyViewHolder holder, int position) { DeliveryModel dd = dlist.get(position); holder.name.setText(dd.getName()); holder.address.setText(dd.getAddress()); holder.phone.setText(dd.getPhone()); holder.radioButton.setChecked(lastSelectedPosition == position); holder.layout.setOnClickListener(v -> { Intent intent = new Intent(getApplicationContext(), OrderSummary.class); intent.putExtra("dId", dd.getId()); intent.putExtra("dName", dd.getName()); startActivity(intent); }); holder.edit.setOnClickListener(v -> { Intent i = new Intent(SelectAddress.this, AddAddress.class); i.putExtra("update", "UPDATE"); i.putExtra("addId", dd.getId()); i.putExtra("city_name", dd.getCityName()); i.putExtra("society", dd.getSociety()); i.putExtra("receiver_name", dd.getReceiverName()); i.putExtra("receiver_phone", dd.getReceiverPhone()); i.putExtra("house_no", dd.getHouseNo()); i.putExtra("landmark", dd.getLandmark()); i.putExtra("state", dd.getState()); i.putExtra("pincode", dd.getPincode()); Log.d("ff", dd.getId()); startActivity(i); }); holder.radioButton.setOnClickListener(v -> { lastSelectedPosition = position; selectAddrsUrl(dlist.get(position).getId()); notifyDataSetChanged(); }); } @Override public int getItemCount() { return dlist.size(); } private void selectAddrsUrl(String id) { show(); StringRequest stringRequest = new StringRequest(Request.Method.POST, SELECT_ADDRESS_URL, response -> { try { JSONObject jsonObject = new JSONObject(response); String status = jsonObject.getString("status"); String msg = jsonObject.getString("message"); if (status.equals("1")) { showAdd = true; onBackPressed(); } else { Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } finally { show(); } }, error -> { show(); Toast.makeText(SelectAddress.this, "Server error ", Toast.LENGTH_SHORT).show(); }) { @Override protected Map<String, String> getParams() throws AuthFailureError { HashMap<String, String> param = new HashMap<>(); param.put("address_id", id); return param; } }; stringRequest.setRetryPolicy(new RetryPolicy() { @Override public int getCurrentTimeout() { return 90000; } @Override public int getCurrentRetryCount() { return 0; } @Override public void retry(VolleyError error) throws VolleyError { error.printStackTrace(); } }); RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext()); requestQueue.getCache().clear(); requestQueue.add(stringRequest); } public class MyViewHolder extends RecyclerView.ViewHolder { TextView name; TextView phone; TextView address; ImageView editAddress; RadioButton radioButton; LinearLayout edit; LinearLayout layout; public MyViewHolder(View view) { super(view); radioButton = view.findViewById(R.id.radioButton); layout = view.findViewById(R.id.layout); editAddress = view.findViewById(R.id.edit_address); name = (TextView) view.findViewById(R.id.txt_name_myhistoryaddrss_item); phone = (TextView) view.findViewById(R.id.txt_mobileno_myaddrss_history); address = (TextView) view.findViewById(R.id.txt_address_myaddrss_history); edit = view.findViewById(R.id.edit); } } } }
Python
UTF-8
1,344
2.5625
3
[ "Apache-2.0", "CC-BY-4.0" ]
permissive
# Copyright 2023 The Google Earth Engine Community Authors # # 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 # # https://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. # [START earthengine__apidocs__ee_string_aside] def print_result(val, *params): """A print function to invoke with the aside method.""" print(val.getInfo()) for param in params: print(param) # aside with no var_args. # a ee.String('a').aside(print_result) # foo # bar ee.String('foo').aside(print_result, 'bar') # foo # bar # # foo print(ee.String('foo').aside(print_result, 'bar').getInfo()) # aside in the middle of a chain of calls. # a # b # # ac print(ee.String('a').aside(print_result, 'b').cat('c').getInfo()) # aside with more than one var_args. # a # 1 # 2 ee.String('a').aside(print_result, 1, 2) # Print a empty JSON string. # '' ee.String('').aside(print_result) # [END earthengine__apidocs__ee_string_aside]
Java
UTF-8
4,847
2.953125
3
[ "LicenseRef-scancode-free-unknown", "Apache-2.0", "LicenseRef-scancode-public-domain" ]
permissive
package io.opensphere.server.util; import java.awt.GridBagConstraints; import java.awt.Insets; /** * Builder class for {@link GridBagConstraints}. */ public class GridBagConstraintsBuilder { /** The x grid position. */ private int myGridx = GridBagConstraints.RELATIVE; /** The y grid position. */ private int myGridy = GridBagConstraints.RELATIVE; /** The horizontal grid span. */ private int myGridWidth = 1; /** The vertical grid span. */ private int myGridHeight = 1; /** The x weight. */ private double myWeightx; /** The y weight. */ private double myWeighty; /** The anchor position of components. */ private int myAnchor = GridBagConstraints.CENTER; /** The cell's fill type. */ private int myFill = GridBagConstraints.NONE; /** The cell insets (i.e. margins). */ private Insets myInsets = new Insets(0, 0, 0, 0); /** The internal x padding. */ private int myIPadx; /** The internal y padding. */ private int myIPady; /** * Set the anchor position of components. * * @param anchor The anchor position of components * @return This {@link GridBagConstraints} Builder */ public GridBagConstraintsBuilder anchor(int anchor) { myAnchor = anchor; return this; } /** * Builds the {@link GridBagConstraints}. * * @return the {@link GridBagConstraints} */ public GridBagConstraints build() { return new GridBagConstraints(myGridx, myGridy, myGridWidth, myGridHeight, myWeightx, myWeighty, myAnchor, myFill, myInsets, myIPadx, myIPady); } /** * Set the cell's fill type. * * @param fill The cell's fill type * @return This {@link GridBagConstraints} Builder */ public GridBagConstraintsBuilder fill(int fill) { myFill = fill; return this; } /** * Set the vertical grid span. * * @param gridheight The vertical grid span * @return This {@link GridBagConstraints} Builder */ public GridBagConstraintsBuilder gridheight(int gridheight) { myGridHeight = gridheight; return this; } /** * Set the horizontal grid span. * * @param gridwidth The horizontal grid span * @return This {@link GridBagConstraints} Builder */ public GridBagConstraintsBuilder gridwidth(int gridwidth) { myGridWidth = gridwidth; return this; } /** * Set the x grid position. * * @param gridx The x grid position * @return This {@link GridBagConstraints} Builder */ public GridBagConstraintsBuilder gridx(int gridx) { myGridx = gridx; return this; } /** * Set the y grid position. * * @param gridy The y grid position * @return This {@link GridBagConstraints} Builder */ public GridBagConstraintsBuilder gridy(int gridy) { myGridy = gridy; return this; } /** * Set the cell insets (i.e. margins). * * @param insets The cell insets * @return This {@link GridBagConstraints} Builder */ public GridBagConstraintsBuilder insets(Insets insets) { myInsets = insets; return this; } /** * Set the cell insets (i.e. margins). * * @param top the inset from the top * @param left the inset from the left * @param bottom the inset from the bottom * @param right the inset from the right * @return This {@link GridBagConstraints} Builder */ public GridBagConstraintsBuilder insets(int top, int left, int bottom, int right) { myInsets = new Insets(top, left, bottom, right); return this; } /** * Set the internal x padding. * * @param ipadx The internal x padding * @return This {@link GridBagConstraints} Builder */ public GridBagConstraintsBuilder ipadx(int ipadx) { myIPadx = ipadx; return this; } /** * Set the internal y padding. * * @param ipady The internal y padding * @return This {@link GridBagConstraints} Builder */ public GridBagConstraintsBuilder ipady(int ipady) { myIPady = ipady; return this; } /** * Set the x weight. * * @param weightx The x weight * @return This {@link GridBagConstraints} Builder */ public GridBagConstraintsBuilder weightx(double weightx) { myWeightx = weightx; return this; } /** * Set the y weight. * * @param weighty The y weight * @return This {@link GridBagConstraints} Builder */ public GridBagConstraintsBuilder weighty(double weighty) { myWeighty = weighty; return this; } }
C++
UTF-8
1,521
2.59375
3
[ "MIT", "BSL-1.0", "BSD-2-Clause" ]
permissive
/* * Copyright (c) 2019, 2020, 2021 SiKol Ltd. * Distributed under the Boost Software License, Version 1.0. */ /* * Configuration file parser. */ #ifndef IVY_CONFIG_LEX_HXX_INCLUDED #define IVY_CONFIG_LEX_HXX_INCLUDED #include <any> #include <cstdint> #include <optional> #include <ivy/string.hxx> namespace ivy::config { // A token enum token_type { T_EOF = 0, T_INT, T_UINT, T_STRING, T_IDENTIFIER, T_LBRACE, T_RBRACE, T_LPAREN, T_RPAREN, T_EQ, T_SEMICOLON, }; class token { private: token_type _type; std::any _value; public: explicit token(token_type type); explicit token(token_type type, string value); explicit token(token_type type, std::int64_t value); // explicit token(token_type type, std::uint64_t value); token(token const &other); token(token &&other); auto operator=(token const &other) -> token &; auto operator=(token &&other) -> token &; auto type() const -> token_type; auto value() const -> std::any const &; }; auto as_string(token const &) -> string const &; auto as_int(token const &) -> std::int64_t; // auto as_uint(token const *) -> std::uint64_t; auto match_next(string s) -> std::pair<std::optional<token>, string>; } // namespace ivy::config #endif // IVY_CONFIG_LEX_HXX_INCLUDED
C++
UTF-8
1,558
3.375
3
[]
no_license
#include <iostream> #include <string> #include <vector> using namespace std; void binary(int num){ for(int i = 31; i >= 0; i--){ cout << ((num & (1 << i)) == 0 ? 0: 1) << " "; } cout << endl; } int length_ones(int num){ int len = 0; for(int i = 31; i >= 0; i--){ int bit = ((num & (1 << i)) == 0 ? 0: 1); if(bit == 1) len += 1; } return len; } int max_seq(int num){ vector<int> index; int len = 0; int max_len = 0; int prev_bit = 0; for(int i = 31; i >= 0; i--){ int bit = ((num & (1 << i)) == 0 ? 0: 1); if(bit == 1) len += 1; else len = 0; if (len>max_len) max_len = len; } return max_len; } int main(){ int a = 5; int output = 0; binary(1775); cout << "Maximum sequence of ones in a number is " << max_seq(1775) << endl; //=======================================================================// // Finds longest sequence of 1s that can be created by flipping a 0 to 1 //=======================================================================// int seq, long_seq = 0; int num = 1775; for (int i = 31; i >= 0; i--) { int temp_num = ((num | (1 << i))); seq = max_seq(temp_num); if (seq > long_seq){ long_seq = seq; } temp_num = num; } cout << "Maximum sequence of ones by flipping a bit is " << long_seq << endl; return 0; }
Java
UTF-8
11,050
1.796875
2
[]
no_license
package black.kr.hs.mirim.sosimtapaxml; import android.Manifest; import android.content.CursorLoader; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.location.Address; import android.location.Geocoder; import android.net.Uri; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; public class MyPlaceWrite extends AppCompatActivity implements OnMapReadyCallback, ActivityCompat.OnRequestPermissionsResultCallback { private GoogleMap mMap; private Geocoder geocoder; private Button button; private Button writeAll; private EditText editText; FirebaseFirestore ff; //이미지 띄우기 ImageView imageView; Button img_button; FirebaseStorage storageRef; StorageReference userPlaceImage; //위치 String address; public static MyPlaceWrite newInstance() { MyPlaceWrite fragment = new MyPlaceWrite(); return fragment; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my_place_write); editText = (EditText) findViewById(R.id.placewrite_editText); button=(Button)findViewById(R.id.placewrite_button); writeAll = findViewById(R.id.placeWriteAll); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); // 키보드 생성시 UI도 같이 올라가게 Intent it = getIntent(); final String userID = it.getStringExtra("userID"); storageRef = FirebaseStorage.getInstance("gs://sosimtapaxml.appspot.com"); StorageReference mStorageRef = FirebaseStorage.getInstance().getReference(); userPlaceImage = mStorageRef.child(userID+"/myPlaceImg.jpg"); ff = FirebaseFirestore.getInstance(); /*권한*/ requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},0); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.write_map); mapFragment.getMapAsync(this); //이미지 imageView = (ImageView)findViewById(R.id.image); img_button = (Button)findViewById(R.id.button); img_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(intent, 1); } }); final EditText content = findViewById(R.id.write_contents_text); //내용 writeAll.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { Map<String, Object> grade = new HashMap<>(); grade.put("userID", userID); grade.put("userEditAddress",editText.getText().toString()); grade.put("address", address); // 장소 grade.put("content",content.getText().toString()); // 내용 ff.collection("myplace").document() .set(grade) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Log.d("장소저장", "DocumentSnapshot successfully written!"); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.d("장소저장실패", "Error writing document", e); } }); Toast.makeText(MyPlaceWrite.this,"등록완료",Toast.LENGTH_SHORT); finish(); } }); } @Override //이미지 protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 1) { if (resultCode == RESULT_OK) { try { // 선택한 이미지에서 비트맵 생성 InputStream in = getContentResolver().openInputStream(data.getData()); Bitmap img = BitmapFactory.decodeStream(in); in.close(); // 이미지 표시 imageView.setImageBitmap(img); //여기까지 선택한 이미지 화면에 띄우는 소스 // System.out.print(data.getData()); // System.out.println(getPath(data.getData())); //Log.d("제발",getPath(data.getData())); /*Uri file = Uri.fromFile(new File(getPath(data.getData()))); StorageReference riversRef = storageRef.child("images/"+file.getLastPathSegment()); UploadTask uploadTask = riversRef.putFile(file); // Register observers to listen for when the download is done or if it fails uploadTask.addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { // Handle unsuccessful uploads } }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { // taskSnapshot.getMetadata() contains file metadata such as size, content-type, etc. // ... } });*/ } catch (Exception e) { e.printStackTrace(); } } } } /* public String getPath(Uri uri){ String [] proj = {MediaStore.Images.Media.DATA}; Cursor cursor = getContentResolver().query(uri, proj, null, null, null); int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(index); }*/ @Override public void onMapReady(final GoogleMap googleMap) { mMap = googleMap; geocoder = new Geocoder(this); // 맵 터치 이벤트 구현 - 터치시 마커가 추가됨 mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener(){ @Override public void onMapClick(LatLng point) { MarkerOptions mOptions = new MarkerOptions(); // 마커 타이틀 mOptions.title("마커 좌표"); Double latitude = point.latitude; // 위도 Double longitude = point.longitude; // 경도 // 마커의 스니펫(간단한 텍스트) 설정 mOptions.snippet(latitude.toString() + ", " + longitude.toString()); // LatLng: 위도 경도 쌍을 나타냄 mOptions.position(new LatLng(latitude, longitude)); // 마커(핀) 추가 googleMap.addMarker(mOptions); } }); // 버튼 이벤트 button.setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View v){ String str=editText.getText().toString(); List<Address> addressList = null; try { // editText에 입력한 텍스트(주소, 지역, 장소 등)을 지오 코딩을 이용해 변환 addressList = geocoder.getFromLocationName( str, // 주소!!!! 100); // 최대 검색 결과 개수 } catch (IOException e) { e.printStackTrace(); } System.out.println(addressList.get(0).toString()); // 콤마를 기준으로 split String []splitStr = addressList.get(0).toString().split(","); address = splitStr[0].substring(splitStr[0].indexOf("\"") + 1,splitStr[0].length() - 2); // 주소 System.out.println(address); String latitude = splitStr[10].substring(splitStr[10].indexOf("=") + 1); // 위도 String longitude = splitStr[12].substring(splitStr[12].indexOf("=") + 1); // 경도 System.out.println(latitude); System.out.println(longitude); // 좌표(위도, 경도) 생성 LatLng point = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude)); // 마커 생성 MarkerOptions mOptions2 = new MarkerOptions(); mOptions2.title(editText+"의 검색 결과"); mOptions2.snippet(address); mOptions2.position(point); // 마커 추가 mMap.addMarker(mOptions2); // 해당 좌표로 화면 줌 mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(point,15)); } }); // Add a marker in Sydney and move the camera LatLng mirim = new LatLng(37.466614,126.9310583); mMap.addMarker(new MarkerOptions().position(mirim).title("미림 IT쇼에 오신것을 환영합니다")); mMap.moveCamera(CameraUpdateFactory.newLatLng(mirim)); mMap.moveCamera((CameraUpdateFactory.newLatLngZoom(mirim,15))); } }
Java
UTF-8
2,353
2.3125
2
[]
no_license
package com.example.nathan.studenthub.presenter; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.nathan.studenthub.R; import com.example.nathan.studenthub.model.MenuItem; /** * Created by Nathan on 11/05/2017. */ public class MentalHealthPagerFragment extends Fragment { private TabLayout tabLayout; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.content_viewpager_fragment, container, false); Bundle bundle = new Bundle(); bundle.putSerializable(ContentActivity.MENU_RESOURCE, (MenuItem) getArguments().get(ContentActivity.MENU_RESOURCE)); // Create the fragments for each section and add the requested service final MentalHealthAboutFragment aboutFragment = new MentalHealthAboutFragment(); aboutFragment.setArguments(bundle); final MentalHealthTreatmentFragment treatmentFragment = new MentalHealthTreatmentFragment(); treatmentFragment.setArguments(bundle); ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewPager); viewPager.setOffscreenPageLimit(3); viewPager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) { @Override public android.support.v4.app.Fragment getItem(int position) { return position == 0 ? aboutFragment : treatmentFragment; } @Override public int getCount() { return 2; } @Override public CharSequence getPageTitle(int position) { return position == 0 ? "About" : "Treatment"; } }); tabLayout = (TabLayout) view.findViewById(R.id.tabLayout); tabLayout.setupWithViewPager(viewPager); return view; } public void RemoveTab(int position) { this.tabLayout.removeTabAt(position); } }
Java
UTF-8
2,145
2.171875
2
[]
no_license
package com.example.waimai2; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.example.waimai2.BmobSql.Customer; import cn.bmob.v3.exception.BmobException; import cn.bmob.v3.listener.UpdateListener; public class Changename_page extends AppCompatActivity { private ImageButton back; private Button modifyname; private EditText newname; @Override protected void onCreate(Bundle saveInstanceState) { super.onCreate(saveInstanceState); setContentView(R.layout.change_name); back = (ImageButton) findViewById(R.id.btn_back); modifyname=findViewById(R.id.btn_modifyname); newname=findViewById(R.id.newname); back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Changename_page.this.finish(); } }); modifyname.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //在此处修改数据库中用户名 Intent intent = new Intent(Changename_page.this, Mine_page.class); String str1=newname.getText().toString().trim(); Customer customer=new Customer(); /*customer.setCname(str1); customer.update("kcIpSSSd", new UpdateListener() { @Override public void done(BmobException e) { if(e==null){ Toast.makeText(Changename_page.this,"昵称已修改",Toast.LENGTH_SHORT).show(); } } });*/ intent.putExtra("username new", str1); startActivity(intent); //用str1修改数据库中用户名 Changename_page.this.finish(); } }); } }
Python
UTF-8
233
3.421875
3
[]
no_license
import random print("number guessing game" ) number=int(input("enter a number between 1 and 9")) if(number<12): print("No admission") elif(number==12): print("adimssion granted") else: print("advance level")
C
UTF-8
594
3.46875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <unistd.h> //pid_t waitpid(pid_t pid, int *wstatus, int options); int main() { printf("Hello all\n"); pid_t child_pid = fork(); // If fork returns a positive value for child_id then I'm (the process) the parent if ( child_pid > 0 ) { int status; waitpid(child_pid, &status, 0); printf("I', the parent: %d\n", getpid()); } // fork returns a 0 value for child_id means I'm (the process) the child if ( child_pid == 0 ) printf("I'm the mischevious child: %d\n", getpid()); printf("Yeah: %d\n", getpid()); }
Python
UTF-8
3,010
2.59375
3
[]
no_license
import logging import azure.functions as func import sys import json import wolframalpha import configparser from azure.servicebus import ServiceBusClient, ServiceBusMessage config = configparser.ConfigParser() config.read('./config.ini') if "service_bus_client" not in config: raise RuntimeError("config.ini file should have service_bus_client section") if "CONNECTION_STR" not in config["service_bus_client"] or "QUEUE_NAME" not in config["service_bus_client"]: raise RuntimeError("config.ini file should have CONNECTION_STR and QUEUE_NAME to the service bus") CONNECTION_STR = config["service_bus_client"]["CONNECTION_STR"] QUEUE_NAME = config["service_bus_client"]["QUEUE_NAME"] if "wolfram_api" not in config: raise RuntimeError("config.ini file should have wolfram_api section") if "APP_ID" not in config["wolfram_api"]: raise RuntimeError("config.ini file should have APP_ID to the wolframalpha api") APP_ID = config["wolfram_api"]["APP_ID"] def some_calculator_magic(question: str) -> str: # Instance of wolf ram alpha # client class client = wolframalpha.Client(APP_ID) # Stores the response from # wolf ram alpha res = client.query(question) try: # Includes only text from the response answer = next(res.results).text except StopIteration: answer = "It's too hard for us, try WolframAlpha instead." return answer def send_single_message(sender, message): # create a Service Bus message message = ServiceBusMessage(message) # send the message to the queue sender.send_messages(message) print("Sent a single message") def main(req: func.HttpRequest) -> func.HttpResponse: logging.info("Python HTTP trigger function processed a request.") try: req_body = req.get_json() question = req_body.get('question') # question = data["question"] except ValueError: return func.HttpResponse( "Bad input. Unable to read json body.", status_code=400 ) # get username if no than put None try: # name = data["username"] name = req_body.get('username') except KeyError: name = None answer = some_calculator_magic(question) resault = { "username":name, "question":question, "response":answer } resault = json.dumps(resault) if sys.getsizeof(resault) <= 250*1000: servicebus_client = ServiceBusClient.from_connection_string(conn_str=CONNECTION_STR, logging_enable=True) with servicebus_client: # get a Queue Sender object to send messages to the queue sender = servicebus_client.get_queue_sender(queue_name=QUEUE_NAME) with sender: # send one message send_single_message(sender, resault) return func.HttpResponse( json.dumps({"response":answer}), status_code=200 )
Java
UTF-8
19,521
2.21875
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Presentation; import DAL.*; import DTO.*; import BLL.*; import java.awt.Color; import java.awt.Frame; import java.awt.event.KeyEvent; import javax.swing.JFrame; import javax.swing.JOptionPane; import org.mindrot.jbcrypt.BCrypt; /** * * @author LTSNLH5586 */ public class frmDangNhap extends javax.swing.JFrame { int xMouse; int yMouse; /** * Creates new form frmDangNhap */ MainClass main = new MainClass(); public frmDangNhap() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); txtTenDangNhap = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); jSeparator2 = new javax.swing.JSeparator(); txtMatKhau = new javax.swing.JPasswordField(); jButton1 = new javax.swing.JButton(); btnDangNhap = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setUndecorated(true); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel1.setBackground(new java.awt.Color(85, 78, 59)); jPanel1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED, null, new java.awt.Color(63, 0, 4), null, null)); jPanel1.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseDragged(java.awt.event.MouseEvent evt) { jPanel1MouseDragged(evt); } }); jPanel1.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { jPanel1MousePressed(evt); } }); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/Multiply_20px.png"))); // NOI18N jLabel1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel1MouseClicked(evt); } }); jLabel5.setBackground(new java.awt.Color(212, 216, 225)); jLabel5.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N jLabel5.setForeground(new java.awt.Color(212, 216, 225)); jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/Cafe_20px_1.png"))); // NOI18N jLabel5.setText("Phần Mềm Quản Lý Quán Cafe"); jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/Minus_20px.png"))); // NOI18N jLabel6.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel6MouseClicked(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 213, Short.MAX_VALUE) .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel5) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jLabel6)) ); getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 500, 30)); jPanel2.setBackground(new java.awt.Color(255, 235, 178)); jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/Cafe_200px.png"))); // NOI18N jLabel3.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N jLabel3.setForeground(new java.awt.Color(139, 0, 0)); jLabel3.setText("Tên Đăng Nhập"); jSeparator1.setForeground(new java.awt.Color(0, 0, 0)); txtTenDangNhap.setBackground(new java.awt.Color(255, 235, 178)); txtTenDangNhap.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N txtTenDangNhap.setBorder(null); txtTenDangNhap.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtTenDangNhapActionPerformed(evt); } }); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N jLabel4.setForeground(new java.awt.Color(139, 0, 0)); jLabel4.setText("Mật Khẩu"); jSeparator2.setForeground(new java.awt.Color(0, 0, 0)); txtMatKhau.setBackground(new java.awt.Color(255, 235, 178)); txtMatKhau.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N txtMatKhau.setBorder(null); txtMatKhau.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtMatKhauActionPerformed(evt); } }); txtMatKhau.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { txtMatKhauKeyPressed(evt); } }); jButton1.setBackground(new java.awt.Color(0, 13, 51)); jButton1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jButton1.setForeground(new java.awt.Color(255, 248, 229)); jButton1.setText("Hủy"); jButton1.setBorder(null); jButton1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { jButton1MouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { jButton1MouseExited(evt); } }); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); btnDangNhap.setBackground(new java.awt.Color(0, 20, 77)); btnDangNhap.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N btnDangNhap.setForeground(new java.awt.Color(255, 255, 255)); btnDangNhap.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/Login Rounded Right_25px.png"))); // NOI18N btnDangNhap.setText("Đăng Nhập"); btnDangNhap.setBorder(null); btnDangNhap.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseEntered(java.awt.event.MouseEvent evt) { btnDangNhapMouseEntered(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { btnDangNhapMouseExited(evt); } }); btnDangNhap.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnDangNhapActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 218, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(btnDangNhap, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 237, Short.MAX_VALUE) .addComponent(txtTenDangNhap))) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(4, 4, 4) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3))) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txtMatKhau, javax.swing.GroupLayout.DEFAULT_SIZE, 237, Short.MAX_VALUE) .addComponent(jSeparator2)))) .addContainerGap(27, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(57, Short.MAX_VALUE) .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtTenDangNhap, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(23, 23, 23) .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtMatKhau, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(4, 4, 4) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(27, 27, 27) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnDangNhap, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); getContentPane().add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 30, 500, 270)); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void jPanel1MouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel1MouseDragged int x = evt.getXOnScreen(); int y = evt.getYOnScreen(); this.setLocation(x - xMouse, y - yMouse); }//GEN-LAST:event_jPanel1MouseDragged private void jPanel1MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel1MousePressed xMouse = evt.getX(); yMouse = evt.getY(); }//GEN-LAST:event_jPanel1MousePressed private void jLabel1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel1MouseClicked System.exit(0); }//GEN-LAST:event_jLabel1MouseClicked private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed txtTenDangNhap.setText(""); txtMatKhau.setText(""); }//GEN-LAST:event_jButton1ActionPerformed private void txtMatKhauActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtMatKhauActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtMatKhauActionPerformed private void txtTenDangNhapActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtTenDangNhapActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtTenDangNhapActionPerformed private void jLabel6MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel6MouseClicked setState(ICONIFIED); }//GEN-LAST:event_jLabel6MouseClicked private void btnDangNhapActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDangNhapActionPerformed //frmHome frmh = new frmHome(); //frmh.show(); //this.dispose(); login(); }//GEN-LAST:event_btnDangNhapActionPerformed private void btnDangNhapMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnDangNhapMouseEntered btnDangNhap.setBackground(new Color(51, 13, 0)); }//GEN-LAST:event_btnDangNhapMouseEntered private void btnDangNhapMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnDangNhapMouseExited btnDangNhap.setBackground(new Color(0, 20, 77)); }//GEN-LAST:event_btnDangNhapMouseExited private void jButton1MouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseEntered jButton1.setBackground(new Color(85, 93, 119)); }//GEN-LAST:event_jButton1MouseEntered private void jButton1MouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseExited jButton1.setBackground(new Color(0, 13, 51)); }//GEN-LAST:event_jButton1MouseExited private void txtMatKhauKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtMatKhauKeyPressed if (evt.getKeyCode() == KeyEvent.VK_ENTER) { login(); } }//GEN-LAST:event_txtMatKhauKeyPressed private void login() { String username = txtTenDangNhap.getText(); String pwd = String.valueOf(txtMatKhau.getPassword()).trim(); EnDeCryption cryption = new EnDeCryption("hoangnlpk00573"); String passmahoa = cryption.encoding(pwd); Users u = new Users(username, passmahoa, 1); //UsersDAL.CauTruyVanThemNhanVien(u); if (username.equals("")) { ThongBao("Nhập Tên Đăng Nhập!", "Lỗi đăng nhập", 1); } else if (pwd.equals("")) { ThongBao("Nhập Mật Khẩu!", "Lỗi đăng nhập", 1); } else if (LoginBLL.KiemTra(username)) { if (passmahoa.equals(LoginBLL.matkhau)) { frmHome frmh = new frmHome(); frmh.show(); this.dispose(); } else { ThongBao("Sai Mật Khẩu", "Lỗi đăng nhập", 2); } } else { ThongBao("Bạn nhập sai tài khoản hoặc mật khẩu", "Lỗi đăng nhập", 2); } } private void ThongBao(String noiDungThongBao, String tieuDeThongBao, int icon) { JOptionPane.showMessageDialog(new JFrame(), noiDungThongBao, tieuDeThongBao, icon); } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(frmDangNhap.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(frmDangNhap.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(frmDangNhap.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(frmDangNhap.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new frmDangNhap().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnDangNhap; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator2; private javax.swing.JPasswordField txtMatKhau; private javax.swing.JTextField txtTenDangNhap; // End of variables declaration//GEN-END:variables }
JavaScript
UTF-8
540
2.921875
3
[]
no_license
var fileInput = document.getElementById('file'), previewImg = document.getElementById('bigImg'); fileInput.addEventListener('change', function () { var file = this.files[0]; var reader = new FileReader(); // 监听reader对象的的onload事件,当图片加载完成时,把base64编码賦值给预览图片 reader.addEventListener("load", function () { previewImg.src = reader.result; }, false); // 调用reader.readAsDataURL()方法,把图片转成base64 reader.readAsDataURL(file); }, false);
Python
UTF-8
817
3.734375
4
[]
no_license
''' For this problem, use the same data set as in the previous problem. Your task now is to run the greedy algorithm that schedules jobs (optimally) in decreasing order of the ratio (weight/length). In this algorithm, it does not matter how you break ties. You should report the sum of weighted completion times of the resulting schedule --- a positive integer --- in the box below. ''' jobsFile = open('jobs.txt','r') lines = jobsFile.readlines()[1:] jobs = [] length,weight = 0,0 for line in lines: weight = int(line.split()[0]) length = int(line.split()[1]) jobs.append([weight,length,float(weight) / float(length)]) jobs = sorted(jobs,key = lambda x:x[2]) jobs = jobs[-1::-1] sumTime = 0 sumLength = 0 for job in jobs: sumLength += job[1] sumTime += job[0] * sumLength print(sumTime)
C++
UTF-8
1,518
3.0625
3
[]
no_license
#ifndef GRAPHICS_H #define GRAPHICS_H #include "../header/sprite.h" /* Graphics Class Holds all information dealing with graphics for the game */ #include <SDL.h> #include <map> #include <string> struct SDL_Window; struct SDL_Renderer; class Graphics { public: Graphics(); ~Graphics(); /* SDL_Surface* loadImage Loads an image into the _spriteSheets map if it doesn't already exist As a result, each image will only ever be loaded once Returns the image form the map regardless of whether or not it was loaded */ SDL_Surface* loadImage(const std::string& filePath); /* void blitsSurface Draws a texture to a certain part of the screen */ void blitSurface(SDL_Texture* source, SDL_Rect* sourceRectangle, SDL_Rect* destinationRectangle); /* void flip renders everything to the screen */ void flip(); /* void clear Clears the screen */ void clear(); /* SDL_Renderer* Returns the renderer */ SDL_Renderer* getRenderer() const; /* Every time we draw a frame, we will first clear out the render After its been cleared out, we will blitsSurface, drawing on to the screen Flip will take whatever is on the render, and draw it to the screen */ private: SDL_Window* _window; // where we are drawing to SDL_Renderer* _renderer; // what actually does all the drawing to the window // going to hold in memory, every sprite graphics loaded up into the game // if it is already loaded once, you won't have to load it again std::map<std::string, SDL_Surface*> _spriteSheets; }; #endif
JavaScript
UTF-8
9,571
2.546875
3
[]
no_license
// ------------------------------------------------------------------------------------------- // Registry module. // -Implements API calls over registry services. // // list = { // 'IP:PORT': { // 'service1': { ... }, // 'service2': { ... } // }, // 'IP2:PORT': { ... } // } // // ------------------------------------------------------------------------------------------- const http = require('http') const https = require('https') const logger = require('../utils/log') const httpServer = require('../httpServer') const g = require('../global') let log let nodesList = {} let heartBeatInterval = 1000 * 10 // Interval pulse to request status on listed services let clientSideInterval = 1000 * 7 // Parameter sent to the services. const serviceType = { 'host': '', // IP:PORT 'service': '', // Service Type 'environment': '', // Service environment 'address': { // Service address data 'protocol': '', 'server': '', 'port': '' }, 'version': '', // Service Version 'time': '', // Service entry creation timestamp 'load': {} // Service server workload data } /************************************************* Cycles && Services heartbeating *************************************************/ /* * Make a status request to each of the registered services. * Then recall the parent function to create a recursive loop. */ const heartBeat = () => { setTimeout(() => { for (const host of Object.keys(nodesList)) { log.info('Heartbeat: ' + host + ' ' + g.getConfig().nodeId) heartBeatCheck(nodesList[host]) } heartBeat() }, heartBeatInterval) } const heartBeatCheck = (node) => { let protocol = node.address.protocol === 'https' ? https : http let options = { 'host': node.address.server, 'port': node.address.port, 'path': '/api/registry/check', 'method': 'GET', 'headers': { 'Content-Type': 'application/json', 'Authorization': 'APIKEY 123' } } let req = protocol.request(options, (res) => { let output = '' res.setEncoding('utf8') res.on('data', (chunk) => { output += chunk }) res.on('end', () => { if (output && output.length > 0 && output.charAt(0) === '{') { node.load = JSON.parse(output) log.debug('HeartBeat ok for ' + node.host) } node.time = Date.now() }) }) req.on('error', (err) => { log.error('Heartbeat ' + options.host + ' ERROR: ' + err + '. DELETING ENTRY !!!') deleteNode(node.address.server + ':' + node.address.port) }) req.end() } /********************************** Registry actions **********************************/ const listAll = (req, res) => { getAllServices(true) .then((allServices) => { return res.status(200).jsonp(allServices) }) } const register = (req, res) => { log.debug('New register request.') addServiceEntry(req) .then(getAllServices) .then((allServices) => { g.addRemoteServices(allServices.services) return res.status(200).jsonp(allServices) }) } const unRegister = (req, res) => { log.debug('New unregister request.') removeServiceEntry(req) .then(getAllServices) .then((allServices) => { return res.status(200).jsonp(allServices) }) } const removeServiceEntry = (req) => { log.debug('removeService') return new Promise((resolve, reject) => { checkRequestData(req) .then((node) => { deleteNode(node) }) .then(resolve) .catch((e) => { log.error(e.message) reject(e) }) }) } const addServiceEntry = (req) => { return new Promise((resolve, reject) => { checkRequestData(req) // .then((node) => checkServiceAddress(node)) .then((node) => updateNode(node)) .then(resolve) .catch((e) => { log.error(e.message) reject(e) }) }) } const checkRequestData = (req) => { return new Promise((resolve, reject) => { if ((!req.body.hasOwnProperty('services')) && (!req.body.hasOwnProperty('service'))) reject(new Error('Missing SERVICE(s) property')) if (!req.body.hasOwnProperty('environment')) reject(new Error('Missing ENV property')) if (!req.body.hasOwnProperty('address')) reject(new Error('Missing ADDRESS property')) if (!req.body.address.hasOwnProperty('protocol')) reject(new Error('Missing PROTOCOL property')) if (!req.body.address.hasOwnProperty('server')) reject(new Error('Missing SERVER property')) if (!req.body.address.hasOwnProperty('port')) reject(new Error('Missing PORT property')) let serviceEntry = Object.assign({}, serviceType) serviceEntry.service = req.body.services || req.body.service serviceEntry.environment = req.body.environment || 'dev' serviceEntry.version = req.body.version || '1.0' serviceEntry.time = Date.now() serviceEntry.load = req.body.load serviceEntry.address = {} serviceEntry.address.protocol = req.body.address.protocol serviceEntry.address.server = req.body.address.server serviceEntry.address.port = req.body.address.port // Request data serviceEntry.host = serviceEntry.address.server + ':' + serviceEntry.address.port log.info(JSON.stringify(serviceEntry)) resolve(serviceEntry) }) } const checkServiceAddress = (service) => { return new Promise((resolve, reject) => { if (!service) reject(new Error('Missing service object to test')) let protocol = service.address.protocol === 'https' ? https : http protocol.get({ host: service.address.server, port: service.address.port, path: '/api/registry/check', method: 'GET', headers: { 'Content-Type': 'application/json', Authorization: 'APIKEY 123' } }, (res) => { resolve(service) }).on('error', (err) => { log.error(err.message) reject(new Error('Address unreachable: ' + service.address.server + ':' + service.address.server)) }) }) } /************************************************************ Service List Operations ************************************************************/ /* * Returns list of available services with the following structure: * { * services: { * 'serviceType': [{server: '127.0.0.1', port: 8081, protocol: 'https'}], * ... * } * } */ const getAllServices = (detailed) => { return new Promise((resolve, reject) => { let currentServices = { 'refresh': clientSideInterval, 'services': listServices(detailed) } resolve(currentServices) }) } const listServices = (detailed) => { let list = {} for (const host of Object.keys(nodesList)) { for (let i = 0; i < nodesList[host].service.length; i++) { let serviceType = nodesList[host].service[i] if (!list.hasOwnProperty(serviceType)) list[serviceType] = [] let data = { 'host': nodesList[host].host, 'environment': nodesList[host].environment, 'server': nodesList[host].address.server, 'port': nodesList[host].address.port, 'protocol': nodesList[host].address.protocol } if (detailed) { data.version = nodesList[host].version data.time = nodesList[host].time data.load = nodesList[host].load } list[serviceType].push(data) } } // Add our own services let l = g.getBootServices() for (let i = 0; i < l.length; i++) { if (l[i] !== 'registry') { let data = { 'host': g.getConfig().apiHost || ':' || g.getConfig().apiPort, 'environment': process.env.NODE_ENV || 'dev', 'server': g.getConfig().apiHost, 'port': g.getConfig().apiPort, 'protocol': 'http' } if (detailed) { data.version = '1.0' data.time = '' data.load = {} } if (!list[l[i]]) list[l[i]] = [] list[l[i]].push(data) } } return list } /* * Atomic and batch operations on Services List * The service object sended on request can contain an array or a string. * Functions must be able to use both types of data * */ const deleteNode = (host) => { log.warn('deleteNode on ' + host) delete (nodesList[host]) } const updateNode = (node) => { if (nodesList[node.host]) { node.time = nodesList[node.host].time log.debug('updateNode on ' + node.host) } else { log.debug('addNode on ' + node.host) } nodesList[node.host] = Object.assign({}, node) } /********************************** Service Init **********************************/ const init = () => { return new Promise((resolve, reject) => { if (g.isLocalService('registry')) { log = logger.getLogger('registry') log.debug('>> registry init()') g.addLocalService('registry').then(() => { httpServer.getApi().post('/api/registry/register', (req, res) => register(req, res)) httpServer.getApi().delete('/api/registry/unregister', (req, res) => unRegister(req, res)) httpServer.getApi().get('/api/registry/services', (req, res) => listAll(req, res)) heartBeat() resolve() }) } else resolve() }) } module.exports = { init }
JavaScript
UTF-8
996
5.21875
5
[]
no_license
// it restructures a function so it takes one argument, //then returns another function that takes the next argument, and so on. //Un-curried function function unCurried(x, y) { return x + y; } //Curried function function curried(x) { return function(y) { return x + y; } } //Alternative using ES6 const curried = x => y => x + y curried(1)(2) // Returns 3 //This is useful in your program if you can't supply all the arguments to a function at one time. //You can save each function call into a variable, which will hold the returned function reference // that takes the next argument when it's available. Here's an example using the curried function in the example above: // Call a curried function in parts: var funcForY = curried(1); console.log(funcForY(2)); // Prints 3 //Impartial function function impartial(x, y, z) { return x + y + z; } var partialFn = impartial.bind(this, 1, 2); //late binding partialFn(10); // Returns 13
Markdown
UTF-8
5,753
2.6875
3
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
--- title: Hello World Explained url: tutorials/develop/hello-world-explained layout: subpage --- Now that we've installed the tools necessary to create and preview the default PhoneGap application, it's worth stopping to take a moment to look through the default application and point out some important details. ## `viewport` Open the **index.html** file (located within your project root's ***www*** folder) and notice the `viewport` meta element. This is used to indicate how much of the screen should be used by the application content and specify how it should scale. Scaling refers to the zoom level, where `initial-scale` indicates the desired zoom upon load, the `maximum-scale`, `minimum-scale` values control the least and most allowed and `user-scalable` properties control whether a user should be allowed to control the scale or zoom factor (via pinch gesture for instance). In the default application the settings are configured to load the content at 100%, (`initial-scale=1`) allow no user scaling (`user-scalable=no`), and use the maximum width and height of the device. ```html <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" /> ``` ## `cordova.js` In the **index.html** file you'll notice a script tag pointing to a `cordova.js` file like below: ```html <script type="text/javascript" src="cordova.js"></script> ``` The **cordova.js** file is the PhoneGap (powered by the open-source Apache Cordova project, hence the name) library and what's used to specifically access the native device hardware (camera, contacts, GPS etc) from JavaScript in our PhoneGap apps. Including this file reference ensures the Cordova APIs have access to those features and are available. You may notice that there isn't a **cordova.js** file however located anywhere in the folder. That's because the right version for the platform is injected for you at runtime by the Developer app or the PhoneGap CLI if you're building your projects using the CLI. You simply need to ensure the reference is available. ## `index.js` The **index.js** file is another JavaScript file referred to in another script tag in the index.html. This file is not required in your applications, but is specific to this default application and used to add simple logic around determining when the Cordova library has loaded and is ready to be used. More information on that follows in the next section. Notice that the index.html contains a line to call an `initialize` function via an `app` variable right before the closing HTML body tag: ```html <script type="text/javascript"> app.initialize(); </script> ``` This calls the `initialize` function on the app variable defined in the index.js file under the **www/js** folder. Open that now before moving on. ## `deviceready` The other important Cordova-specific feature to point out is the `deviceready` event. This event signals that Cordova's device APIs have loaded and are ready to access. If you start making calls to Cordova APIs without relying on this event, you could end up in a situation where the native code is not yet fully loaded and not available. Applications typically attach an event listener with `document.addEventListener` once the HTML document's DOM has loaded as shown below and in the default Hello application: ```js document.addEventListener('deviceready', this.onDeviceReady, false); ``` In the index.js file you'll see that the `onDeviceReady` function then calls a `receivedEvent` function to visually display that the device is now ready. It does this by setting the CSS `display` attribute to `none` on the initial `<p>` element that was shown and instead shows the *Device is Ready* element in index.html by setting its `display` attribute to `block`. Below is the relevant code snippet from the index.js followed by the index.html block. ### `index.js` ```js onDeviceReady: function() { app.receivedEvent('deviceready'); }, // Update DOM on a Received Event receivedEvent: function(id) { var parentElement = document.getElementById(id); var listeningElement = parentElement.querySelector('.listening'); var receivedElement = parentElement.querySelector('.received'); listeningElement.setAttribute('style', 'display:none;'); receivedElement.setAttribute('style', 'display:block;'); console.log('Received Event: ' + id); } ``` ### `index.html` ```html <div id="deviceready" class="blink"> <p class="event listening">Connecting to Device</p> <p class="event received">Device is Ready</p> </div> ``` ## more `<meta/>` tags Some other meta tags included in the default project are explained here as well. ## `format-detection` ```html <meta name="format-detection" content="telephone=no" /> ``` This meta tag represents an Apple feature to recognize a telephone number and make an automatic link from it providing implicit click-to-call support. However, too many numbers tend to get selected with this enabled including some addresses, ISBN numbers and other numeric data, so the recommendation is to set it to no to disable it and use the `tel:` scheme (per RFC 3966) in the URL instead. See [this link](https://developer.apple.com/library/safari/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/MetaTags.html) for more details on this and other meta tags supported by Apple. ## `msapplication-tap-highlight` ```html <meta name="msapplication-tap-highlight" content="no" /> ``` This meta tag allows you to disable the grey tap highlight on Windows Phone 8 and greater. This property is similar to the `-webkit-tap-highlight-color` in iOS Safari except an HTML meta element rather than a CSS property.
Markdown
UTF-8
1,454
3.578125
4
[ "MIT" ]
permissive
# 39. Combination Sum [Original Page](https://leetcode.com/problems/combination-sum/) Given a set of candidate numbers (**_C_**) and a target number (**_T_**), find all unique combinations in **_C_** where the candidate numbers sums to **_T_**. The **same** repeated number may be chosen from **_C_** unlimited number of times. **Note:** * All numbers (including target) will be positive integers. * The solution set must not contain duplicate combinations. For example, given candidate set `[2, 3, 6, 7]` and target `7`, A solution set is: <pre>[ [7], [2, 2, 3] ] </pre> <div> [Subscribe](/subscribe/) to see which companies asked this question </div> <div> <div id="company_tags" class="btn btn-xs btn-warning">Show Company Tags</div> <span class="hidebutton">[Snapchat](/company/snapchat/) [Uber](/company/uber/)</span></div> <div> <div id="tags" class="btn btn-xs btn-warning">Show Tags</div> <span class="hidebutton">[Array](/tag/array/) [Backtracking](/tag/backtracking/)</span></div> <div> <div id="similar" class="btn btn-xs btn-warning">Show Similar Problems</div> <span class="hidebutton">[(M) Letter Combinations of a Phone Number](/problems/letter-combinations-of-a-phone-number/) [(M) Combination Sum II](/problems/combination-sum-ii/) [(M) Combinations](/problems/combinations/) [(M) Combination Sum III](/problems/combination-sum-iii/) [(M) Factor Combinations](/problems/factor-combinations/)</span></div>
Markdown
UTF-8
1,608
3.453125
3
[]
no_license
--- title: Finalize login --- # Finalize login endpoint Now that we have signup in place, we can finalize our login endpoint! Our current login endpoint is using hardcoded userId to generate the `jwt` token and it isn't really looking for users on a table. We are going to have to change it into something like this: ```js router.post("/login", (req, res) => { const { email, password } = req.body; if (!email || !password) { res.status(400).send({ message: "Please supply a valid email and password", }); } else { // 1. find user based on email address // 2. use bcrypt.compareSync to check the recieved password against the stored hash // 3. if the password is correct, return a JWT with the userId of the user (user.id) res.send({ jwt: toJWT({ userId: 1 }), }); } }); ``` Try and do this steps on your own, below is an example but before taking a look think it through. ```js // 1. find user based on email address const user = await User.findOne({ where: { email: email, }, }); if (!user) { res.status(400).send({ message: "User with that email does not exist", }); } // 2. use bcrypt.compareSync to check the password against the stored hash else if (bcrypt.compareSync(password, user.password)) { // 3. if the password is correct, return a JWT with the userId of the user (user.id) const jwt = toJWT({ userId: user.id }); res.send({ jwt, }); } else { res.status(400).send({ message: "Password was incorrect", }); } ``` > ✍️ Finalize and test your login endpoint. Does it properly check your password now?
Markdown
UTF-8
6,371
2.890625
3
[]
no_license
--- title: 第一个自己独立开发并发布的软件 date: 2014-09-09 10:23:38 categories: Before 2016 tags: Selenium --- &#160; &#160; &#160; &#160;这篇博文也是产于14年。[点此查看原文][1] &#160; &#160; &#160; &#160;当时比较有空,自己鼓捣出了一个桌面软件,超鸡冻!现在再看觉得有点杀鸡用牛刀了,同样的功能也许curl一下简单方便又高效。而且连API文档都不知道该怎么使用,但是当时做这个东西的热情和执着,还是值得表扬的哈哈哈哈哈哈哈哈。 ---------- &#160; &#160; &#160; &#160;9.15号才开学,前几天闲的蛋疼,跟一朋友聊起了“超级课程表”。我一直以为他们是跟每个高校有合作,才能取得各高校的数据库数据。后来百度了一下发现原来他们不是通过这个方式,而是直接用学生输入的用户名和密码来访问各高校的教务网获取课程表之类的相关数据。这样就有一个问题让我很感兴趣,各教务网的验证码系统他们是如何攻破的。然后我又百度了一下验证码的破解与反破解原理,想拿QQ空间的留言板来对比着理解一下,结果意外发现不知道什么时候QQ空间的留言板不再需要输入验证码即可发表留言。。。然后我思绪突然一转就把验证码的事给抛到一边了,想能不能自己写个自动刷QQ空间留言的工具? &#160; &#160; &#160; &#160;根据自身的知识储备我找到了一条思路,利用SeleniumIDE录制留言过程,然后把脚本转换成Java代码。接着就是一步步的调试和修改,当天晚上6点开始动手,到凌晨两点的时候程序基本跑通,可以实现自动留言,兴奋的一整夜没睡着。但是因为QQ空间留言板的CSS比较复杂,我当天只实现了通过点击表情按钮来实现留言,还无法直接输入任意字符串作为留言内容。 &#160; &#160; &#160; &#160;后来想起来以前见过有人提供刷空间留言服务来赚钱的,于是自己也想尝试一下。加了好多QQ群,像什么初中生群呀,00后群呀,00后富二代群呀。。。刚想到这个点子的那个晚上在群里问了一下,有个孩子跟我说市场很有需求,结果我信了。我想这么晚了,估计他们都睡了,明天再开始宣传吧~然后自己就躺在床上开始YY,心想如果真的有市场,一个孩子我给他刷个几千条赚一百块,一天可以赚好几百,那不是要发财了?越想越兴奋,然后这个晚上又一整夜没睡着。。。接下来的几天我天天给那些小阔少爷阔小姐私聊发广告,可是到头来要么不鸟我,要么问我想表达什么,要么“呵呵”,要么“傻X,我才不上你的当了!!”。。。 &#160; &#160; &#160; &#160;之后无奈放弃了这个念头,但是不想让这个程序就死在我的MyEclipse IDE里面。所以决定把它做成一款软件。想想之前也有过类似想法,但因为知识储备不足一直没能实现,现在何不尝试一下了。于是又开始码代码。 &#160; &#160; &#160; &#160;改善代码的过程中碰到最棘手的问题就是前文提到的,如何直接输入任意字符串作为留言内容,而不是单一的表情。本来这应该很简单的,用下面这行代码可以解决。 ``` java selenium.type(locator, value); ``` &#160; &#160; &#160; &#160;但是这个是针对输入框、复选框、下拉框等才有效的一个函数,QQ空间留言板的那个输入框不是一个input,而是放在一个iframe下面的可编辑的body下面的一个div.所以我尝试了N次都不能实现以字符串作为留言内容的功能,期间一度情绪暴躁。。。 &#160; &#160; &#160; &#160;后来到一个软件测试群里面去请教了一下,慢慢摸索慢慢尝试终于被我踩到狗屎了. ```java selenium.selectFrame("veditor1_Iframe");//进入一个iframe selenium.runScript(content);//留言内容 ``` &#160; &#160; &#160; &#160;首先得进入那个iframe里面,然后使用selenium.runScript(String script)这个函数就可以达成目的。说实话我也不清楚为什么这个函数可以,也没谁告诉我用这个函数,只是真 的挑了个函数试一下,结果“留言成功”。意外欣喜之情难以言表。。。 &#160; &#160; &#160; &#160;再啰嗦一下这个iframe,按常理来讲Selenium IDE应该能录下我输入文字作为留言内容的这段代码,可是就是这个iframe捣蛋,搞得录出来的代码只有我“点击”发表按钮那一行。 ```java selenium.click("id=btnPostMsg"); ``` &#160; &#160; &#160; &#160;所以我才一步步摸索出,怎么调用Selenium RC的API才能实现以字符串作为留言内容的功能。 &#160; &#160; &#160; &#160;之后的路就相对平坦一点了,用SWING给这个程序套了个又丑又土的GUI壳子,然后整个项目打包成一个Jar文件。然后再用exe4j将其转化成一个.exe文件,但是这样还是不能让这个程序在没有安装JRE的机器上跑,所有又找了个瘦身过的JRE,加上那个Jar文件一起打包成一个.exe文件。这样就终于可以在没有安装的JRE或者JDK的机器上运行了。终于可以一次编译,满世界的跑。 &#160; &#160; &#160; &#160;可是当我把这个程序放到同学的电脑上测试的时候,一秒钟就被360这条狗当成木马病毒给删掉了。我去你大爷。国人的原创积极性就是这样被打消的,狗一样的360。没办法,正好我也想把这个软件搞的正式一点,于是就用Inno Setup给这个程序做了个安装包,这样再重新安装到有360的机器上面,它就一声都不叫了。这样的工作做下来,三天中秋假期基本没怎么休息,全是在操心这事。昨晚上弄好了,又兴奋地一夜睡不着。。。凌晨3点穿个裤衩坐在阳台上点支籣州,想一个魂淡妹子。。。 &#160; &#160; &#160; &#160;下面是本软件1.0.0版的下载地址,百度云盘下载下来如果文件名乱码重命名一下正常解压缩就好。好用的话帮忙转发支持一下,谢谢。 [点此下载][2] &#160; &#160; &#160; &#160;验证码的事,以后再说吧~~~ [1]: http://www.cnblogs.com/aiyokaishuige/p/3962534.html [2]: http://pan.baidu.com/s/1hqqtjW4
Java
UTF-8
3,741
1.734375
2
[]
no_license
package com.ghotel.oss.console.modules.index.service.impl; import com.ghotel.oss.console.core.logging.dao.GocNoticeRepository; import com.ghotel.oss.console.core.utils.GocBeanUtil; import com.ghotel.oss.console.modules.admin.bean.PaginationResult; import com.ghotel.oss.console.modules.index.bean.NoticeSearchCriteria; import com.ghotel.oss.console.modules.index.bean.TaskSearchCriteriaBean; import com.ghotel.oss.console.modules.index.service.IndexService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Map; @Service public class IndexServiceImpl implements IndexService { @Autowired private GocNoticeRepository gocNoticeRepository; @Override public PaginationResult getTasks(TaskSearchCriteriaBean object) throws Exception { Map map = GocBeanUtil.transBean2Map(object); PaginationResult result = new PaginationResult(); result.setStart(object.getStart()); result.setNum(object.getEnd()); // result.setTotal(mapper.countAllTasks(map)); // result.setList(mapper.getAllTasks(map)); return result; } @Override public PaginationResult getNotices(NoticeSearchCriteria object) throws Exception { Map map = GocBeanUtil.transBean2Map(object); PaginationResult result = new PaginationResult(); result.setStart(object.getStart()); result.setNum(object.getEnd()); result.setTotal((int)(gocNoticeRepository.count())); Pageable pageable = new PageRequest(object.getStart(),object.getEnd(),new Sort("createTime","DESC")); result.setList(gocNoticeRepository.findAll(pageable).getContent()); return result; } @Override public List getExecutingTask() { // TODO Auto-generated method stub // return this.mapper.getExecutingTasks(); return null; } @Override public PaginationResult getTasksByJobType(TaskSearchCriteriaBean object) throws Exception { // TODO Auto-generated method stub PaginationResult result = new PaginationResult(); result.setStart(object.getStart()); result.setNum(object.getEnd()); // result.setTotal(mapper.countAllTasksByType(BeanUtil.transBean2Map(object))); // result.setList(mapper.getTasksByJobType(object)); return result; } @Override public int finishTask(TaskSearchCriteriaBean object) { // return this.mapper.finishTask(object); return 0; } //TODO @Override public List<Map<String, String>> getStatistics() { List<Map<String, String>> returnList = new ArrayList<Map<String, String>>(); // Map<String, String> map1 = mapper.statisticTopUserNotice(null); // map1.put("name", "七天内操作第一"); // returnList.add(map1); // Map<String, String> map4 = mapper.statisticTopUserTask(null); // map4.put("name", "七天内总任务第一"); // returnList.add(map4); // Map<String, String> map2 = mapper.statisticTopUserNotice("1"); // map2.put("name", "总操作第一"); // returnList.add(map2); // Map<String, String> map3 = mapper.statisticTopUserTask("1"); // map3.put("name", "总任务第一"); // returnList.add(map3); return returnList; } @Override public int updateTaskResult(Map map) { // return this.mapper.updateTaskResult(map); return 0; } }
C#
UTF-8
1,884
2.96875
3
[ "MIT" ]
permissive
using Microsoft.AspNetCore.Http; using System.Collections.Generic; using System.Linq; using System.Security.Claims; namespace CommonUtil.Helpers { public sealed class CurrentUser : ICurrentUser { private readonly HttpContext _httpContext; public CurrentUser(IHttpContextAccessor httpContextAccessor) => _httpContext = httpContextAccessor.HttpContext; public CurrentUser(HttpContext httpContext) => _httpContext = httpContext; /// <summary> /// Take logged in user Id from HttpContext. default value is -1 /// </summary> public int Id => IsAuthenticated ? int.Parse(_httpContext.User.Identity.Name) : -1; /// <summary> /// Take NameIdentifier claim value as logged in user name. default is "anonymous" /// </summary> public string Name => IsAuthenticated ? (_httpContext.User.Identity as ClaimsIdentity).Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value : "anonymous"; /// <summary> /// Convert int roles values to their corresponding enum values and filter out their corresponding description attribute values /// </summary> public IEnumerable<string> Roles { get { if (!IsAuthenticated) return Enumerable.Empty<string>(); IEnumerable<string> roles = (_httpContext.User.Identity as ClaimsIdentity).Claims.Where(c => c.Type == ClaimTypes.Role).Select(d => d.Value); return roles.Select(role => EnumInfo.GetDescriptionByInt<Permission>(role)); } } public bool IsAuthenticated => _httpContext.User.Identity.IsAuthenticated; public bool HasRole(params Permission[] roles) => roles.Any(role => _httpContext.User.IsInRole(EnumInfo.GetValue(role).ToString())); } }
Python
UTF-8
1,254
3.203125
3
[]
no_license
class Solution: def gameOfLife(self, board: List[List[int]]) -> None: m = len(board) n = len(board[0]) dir = [[0, -1], [-1, -1], [-1, 0], [-1, 1], [0, 1], [1, 1], [1, 0], [1, -1]] for i in range(m): for j in range(n): lnc = 0 for cord in dir: x = i + cord[0] y = j + cord[1] if self.isValid(m, n, x, y): p = board[x][y] if p == -1: p = 1 elif p == 2: p = 0 if p == 1: lnc += 1 if board[i][j] == 1: if lnc < 2 or lnc > 3: board[i][j] = -1 else: if lnc == 3: board[i][j] = 2 for i in range(m): for j in range(n): if board[i][j] == 2: board[i][j] = 1 elif board[i][j] == -1: board[i][j] = 0 def isValid(self, m, n, i, j): if i >= 0 and j >= 0 and i < m and j < n: return True return False
Java
UTF-8
179
2.203125
2
[]
no_license
package j8c.Exceptions; public class ParametersNotSetException extends Exception { public ParametersNotSetException() { super("You need to set the parameters"); } }
Markdown
UTF-8
1,026
3.671875
4
[]
no_license
# 单子风格 ## 约束 - 有一个可以修改数据的抽象 - 抽象提供三个操作:1.封装数据;2.将若干函数逐个绑定,建立函数调用顺序;3.打开封装,查看数据的最终结果 ## 注解 单子风格是顺序调用函数的另一种变体,不同于其他传统的函数组合方式,我们建立了在**值与函数之间充当胶水的抽象方式**——“单子”。它包括两个主要操作: 1. 封装操作,输入一个简单值并返回一个胶水抽象的实例 2. 绑定操作,将封装的数据传递给函数 ```python class WFTHeOne: def __init__(self, v): self._value = v def bind(self, func): self._value = func(self._value) return self def printme(self): print(self._value) ``` ## 发展历程 单子起源风格起源于 Haskell 的单位原子。Haskell 是有着严格**零副作用**约束的函数式编程语言。Haskell 的设计者使用单子,来定义程序中概念,如状态、异常等。
Markdown
UTF-8
6,274
3.09375
3
[]
no_license
Syntax: `f ': x` ([each-parallel](adverbs/#each-parallel)) Syntax: `f peach x` (binary, uniform) Syntax: `.[g;] peach y` (binary, uniform) Where - `f` is a unary function and `x` is a list of arguments - `g` is a binary function and `y` is a list of argument pairs `f peach`, or the derivative `f':`, is used for parallel execution of a function over data. This can be useful, for example, for computationally expensive functions, or for accessing several drives at once from a single CPU. In order to execute in parallel, q must be started with multiple slaves, using [`-s` in the command line](cmdline/#-s-slaves), and (since V3.5) the [`\s`](syscmds/#s-number-of-slaves) system command. ```q q)f:{sum exp x?1.0} q)\t f each 2#1000000 132 q)\t f peach 2#1000000 / with 2 CPUs 70 ``` peach-both: ```q q)g:{sum y*exp x?1.0} q)\ts g'[2#1000000;2 3] 57 16777856 q)\ts .[g;]peach flip(2#1000000;2 3) 32 1744 ``` The slaves used by _parallel-each_ and `peach` are either threads or processes according to the sign of the [value used in the command line](cmdline/#-s-slaves). ## Threads ### Globals The function `f` is executed within the slaves, unless the list `x` is a single-item list, in which case the function is executed within the main q thread. !!! info "Only the main q thread may update global variables" The function executed with `peach` is restricted to updating local variables only. Thus: <pre><code class="language-c"> q){\`a set x} peach enlist 0 </code></pre> works, as single-item list shortcuts to execute on the main q thread <pre><code class="language-c"> q){\`a set x} peach 0 1 </code></pre> fails and signals `'noupdate` as it is executed from within slave threads. `peach` defaults to `each` in the case that no slave threads are specified on startup. It then executes on the only available thread, the main q thread. ```q q){`a set x} peach 0 1 ``` works when no slave threads are specified, as `peach` defaults to `each`. Results from the function are copied (via serialization/deserialization) to the main thread, as q uses thread-local heaps. Hence for best performance, `peach` should crunch large amounts of data in a computationally intense function and return small data sets, as serialization has an overhead. This overhead can be observed with ```q \t do[100;-9!-8!object] ``` where `object` is the data being passed or returned. The algorithm for grouping symbols differs between slave threads and the main q thread. The main q thread uses an optimization not available to the slave threads. E.g. q started with 2 slave threads ```q q)s:100000000?`3 q)\t {group s} peach enlist 0 / defaults to main thread as only single item 2580 q)\t {group s} peach 0 1 / group in slave threads, can't use optimized algorithm 9885 ``` However, grouping integers behaves as expected ```q q)s:100000000?1000 q)\t {group s} peach enlist 0 2308 q)\t {group s} peach 0 1 2802 ``` Perfect scaling may not be achieved, because of resource clashes. ### Number of cores/slave threads A vector with _n_ items peached with function `f` with _s_ slaves on _m_ cores is distributed such that threads are preassigned which items they will be responsible for processing, e.g. for 9 jobs over 4 threads, thread \#0 will be assigned elements 0, 4, 8; if each job takes the same time to complete, then the total execution time of jobs will be quantized according to \#jobs _mod_ \#cores, i.e. with 4 cores, 12 jobs should execute in a similar time as 9 jobs (assuming \#slaves&ge;\#cores). ### Sockets and handles !!! warning "Handles between threads" A handle must not be used concurrently between threads as there is no locking around a socket descriptor, and the bytes being read/written from/to the socket will be garbage (due to message interleaving) and most likely result in a crash. Since V3.0, a socket can be used from the main thread only, or if you use the single-shot sync request syntax as ```q q)`:localhost:5000 "2+2" ``` `peach` forms the basis for a multithreaded HDB. For illustration, consider the following query. ```q q){select max price by date,sym from trade where date=d} peach date ``` This would execute a query for each date in parallel. The multithreaded HDB with `par.txt` hides the complexity of splitting the query up between threads and aggregating the results. ### Memory usage Each slave thread has its own heap, a minimum of 64Mb. Since V2.7 2011.09.21, [`.Q.gc[]`](dotq/#qgc-garbage-collect) in the main thread collects garbage in the slave threads too. Automatic garbage collection within each thread (triggered by a wsful, or hitting the artificial heap limit as specified with [`-w`](cmdline/#-w-memory) on the command line) is executed only for that particular thread, not across all threads. Symbols are internalized from a single memory area common to all threads. ## Processes (distributed each) Since V3.1, `peach` can use multiple processes instead of threads, configured through the startup [command-line option `-s`](cmdline/#-s-slaves) with a negative integer, e.g. `-s -4`. Unlike multiple threads, the distribution of the workload is not precalculated, and is distributed to the slave processes as soon as they complete their allocated items. All data required by the peached function must either already exist on all slave processes, or be passed as an argument. Argument sizes should be minimised because of IPC costs. If any of the slave processes are restarted, the master process must also restart to reconnect. The motivating use case for this mode is multiprocess HDBs, combined with non-compressed data and [`.Q.MAP[]`](dotq/#qmap-maps-partitions). Slave processes must be started explicitly and [`.z.pd`](dotz/#zpd-peach-handles) set to a vector of their connection handles, or a function that returns it. These handles must not be used for other messages: `peach` will close them if it receives anything other than a response message. e.g. ```q q).z.pd:{n:abs system"s";$[n=count handles;handles;[hclose each handles;:handles::`u#hopen each 20000+til n]]} q).z.pc:{handles::`u#handles except x;} q)handles:`u#`int$(); ``` <i class="fa fa-hand-o-right"></i> [`.Q.fc`](dotq/#qfc-parallel-on-cut) (parallel on cut)
Java
UTF-8
2,324
2.0625
2
[]
no_license
//package com.wonana.restapi.config; // //import com.wonana.restapi.accounts.AccountService; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.context.annotation.Configuration; //import org.springframework.security.authentication.AuthenticationManager; //import org.springframework.security.crypto.password.PasswordEncoder; //import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; //import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; //import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; //import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; //import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; //import org.springframework.security.oauth2.provider.token.TokenStore; // //@Configuration //@EnableAuthorizationServer //public class AuthServerConfig extends AuthorizationServerConfigurerAdapter { // // @Autowired // PasswordEncoder passwordEncoder; // // @Autowired // AuthenticationManager authenticationManager; // // @Autowired // AccountService accountService; // // @Autowired // TokenStore tokenStore; // // @Override // public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { // security.passwordEncoder(passwordEncoder); // } // // @Override // public void configure(ClientDetailsServiceConfigurer clients) throws Exception { // clients.inMemory() // .withClient("myApp") // .authorizedGrantTypes("password", "refresh_token") // .scopes("read","write") // .secret(this.passwordEncoder.encode("pass")) // .accessTokenValiditySeconds(10 * 60) // .refreshTokenValiditySeconds(6 * 10 * 60); // } // // // authenticationManager(유저 인증정보), tokenStore, // @Override // public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { // endpoints.authenticationManager(authenticationManager) // .tokenStore(tokenStore); // } //}
Java
UTF-8
3,947
2.046875
2
[]
no_license
package net.tacs.game.services.impl; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import net.tacs.game.model.opentopodata.auth.AuthTokenResponse; import net.tacs.game.model.opentopodata.auth.AuthUserResponse; import net.tacs.game.services.SecurityProviderService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.*; import org.springframework.stereotype.Service; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import java.util.List; @Service public class SecurityProviderServiceImpl implements SecurityProviderService { @Value("${auth0.grant.type}") private String grantType; @Value("${auth0.client.id}") private String clientId; @Value("${auth0.client.scrt}") private String scrt; @Value("${auth0.audience}") private String audience; @Value("${auth0.oauth.url}") private String oauthUrl; @Value("${auth0.endpoint.users}") private String endpointUsers; @Autowired private ObjectMapper objectMapper; @Autowired private RestTemplate restTemplate; @Override public String getToken() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>(); map.add("grant_type", grantType); map.add("client_id", clientId); map.add("client_secret",scrt); map.add("audience", audience); HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers); ResponseEntity<String> response = restTemplate.postForEntity(oauthUrl, request, String.class); if (!response.getStatusCode().equals(HttpStatus.OK)) { handleErrorResponse(response); } AuthTokenResponse tokenResponse = objectMapper.readValue(response.getBody(), AuthTokenResponse.class); return tokenResponse.getAccessToken(); } @Override public List<AuthUserResponse> getUsers(String authToken) throws Exception { HttpEntity request = generateRequestEntity(authToken); ResponseEntity<String> response = restTemplate.exchange( audience.concat(endpointUsers), HttpMethod.GET, request, String.class); if (!response.getStatusCode().equals(HttpStatus.OK)) { handleErrorResponse(response); } JavaType type = objectMapper.getTypeFactory().constructCollectionType(List.class, AuthUserResponse.class); return objectMapper.readValue(response.getBody(), type); } @Override public AuthUserResponse getUserById(String authToken, String id) throws Exception { HttpEntity request = generateRequestEntity(authToken); ResponseEntity<String> response = restTemplate.exchange( new StringBuilder(audience).append(endpointUsers).append("/").append(id).toString(), HttpMethod.GET, request, String.class); if (!response.getStatusCode().equals(HttpStatus.OK)) { handleErrorResponse(response); } return objectMapper.readValue(response.getBody(), AuthUserResponse.class); } private HttpEntity generateRequestEntity(String authToken) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setBearerAuth(authToken); return new HttpEntity(headers); } //TODO Completar método handler errores private void handleErrorResponse(ResponseEntity<String> response) throws Exception { throw new Exception("Handlear errores"); } }
Markdown
UTF-8
1,133
3.5
4
[]
no_license
# 09.图像渲染 ![image-20210114205424631](https://raw.githubusercontent.com/TWDH/Leetcode-From-Zero/pictures/img/image-20210114205424631.png) ## 解法一:DFS ```java class Solution { int[] dx = {1, 0, 0, -1}; int[] dy = {0, 1, -1, 0}; public int[][] floodFill(int[][] image, int sr, int sc, int newColor) { int curColor = image[sr][sc]; //先把当前点变为newColor image[sr][sc] = newColor; if(curColor == newColor){ return image; } dfs(image, sr, sc, curColor, newColor); return image; } public void dfs(int[][] image, int row, int col, int curColor, int newColor){ int numRow = image.length; int numCol = image[0].length; for(int i = 0; i < 4; i++){ int newRow = row + dx[i]; int newCol = col + dy[i]; if(newRow >= 0 && newRow < numRow && newCol >=0 && newCol < numCol && image[newRow][newCol] == curColor){ image[newRow][newCol] = newColor; dfs(image, newRow, newCol, curColor, newColor); } } } } ```
C++
UTF-8
6,488
2.71875
3
[]
no_license
/* * File: StateInfoTimeStamp.cpp * Author: essam * * Created on June 18, 2015, 1:50 PM */ #include "StateInfoTimeStamp.h" #include "AViterbi.h" #include <string> #include<iostream> #include<stdlib.h> StateInfoTimeStamp::StateInfoTimeStamp(double p, std::string v_path, double v_prob, TransList *list) { this->latest = 0; // most recently written index this->lasttime = -1; // time at last write this->StatesList = list; //for debug // this->prob = 0; // this->v_path = v_path; // this->v_prob = v_prob; // // mi[0].v_path = v_path; mi[0].v_prob = v_prob; mi[1].v_path = ""; mi[1].v_prob = 0.0; } StateInfoTimeStamp::StateInfoTimeStamp(double p, std::string v_path, double v_prob) { this->latest = 0; // most recently written index this->lasttime = -1; // time at last write // mi[0].v_path = v_path; mi[0].v_prob = v_prob; mi[1].v_path = ""; mi[1].v_prob = 0.0; } struct StateInfoTimeStamp::ViterbiStateInfo StateInfoTimeStamp::Read(int ts_plus1) { // if the timestamp is older than expects then the value is zero // ts_plus1 is the timestamp +1 // if the actual timestamp is less than last time, then read the old value // otherwise read the new value //if((ts_plus1)<=lasttime) // return mi[latest^1]; //else // return mi[latest]; // what is acceptable is the following: // I want to read time stamp n and it exists // I want to read time stamp n-1 and it exists // 1- lasttime stamp is n, and current readts is n-1 // 2- lasttime stamp is n, and current readts is n // System.out.println("read from ts = "+lasttime+"at time ="+(ts_plus1-1)); if (((ts_plus1 - 1) == this->lasttime) || ((ts_plus1 - 1) == (this->lasttime - 1))) { // std::cout << "get viterbi state info"; if ((ts_plus1) <= this->lasttime) { return this->mi[latest ^ 1]; } else { return this->mi[latest]; } } else { // System.out.println("reseting..."); StateInfoTimeStamp::Write(0, "", 0, ts_plus1 - 1); //lasttime = ts_plus1-1; //mi[0].Write(0,"",0); //mi[1].Write(0,"",0); return mi[latest]; //either 0 or 1 } } bool StateInfoTimeStamp::Write(double prob, std::string v_path, double v_prob, int ts) { // bool flag = true; //#pragma omp single // { if (ts <= lasttime) { std::cout << "State error in StateInfoTimeStamp; write time stamp is " << ts << ", while last written timestamp is\t" << lasttime << std::endl; // flag = false; return false; } // std::cout << "update values" << std::endl; latest = latest ^ 1; //write values mi[latest].prob = prob; mi[latest].v_path = v_path; mi[latest].v_prob = v_prob; mi[latest].ts = ts; if ((lasttime + 1) != ts) { mi[latest ^ 1].prob = 0; mi[latest ^ 1].v_path = ""; mi[latest ^ 1].v_prob = 0; mi[latest ^ 1].ts = ts; } lasttime = ts; //is this correct? // } return true; } bool StateInfoTimeStamp::tWrite(int index, double prob, std::string v_path, double v_prob, int ts) { // bool flag = true; //#pragma omp single // { if (ts <= lasttime) { std::cout << "State @id "<<index <<" error in StateInfoTimeStamp; write time stamp is " << ts << ", while last written timestamp is\t" << lasttime << std::endl; // flag = false; return false; } // std::cout << "update values" << std::endl; latest = latest ^ 1; //write values mi[latest].prob = prob; mi[latest].v_path = v_path; mi[latest].v_prob = v_prob; mi[latest].ts = ts; if ((lasttime + 1) != ts) { mi[latest ^ 1].prob = 0; mi[latest ^ 1].v_path = ""; mi[latest ^ 1].v_prob = 0; mi[latest ^ 1].ts = ts; } lasttime = ts; //is this correct? // } return true; } struct StateInfoTimeStamp::ViterbiStateInfo StateInfoTimeStamp::tRead(int ts_plus1) { // if the timestamp is older than expects then the value is zero // ts_plus1 is the timestamp +1 // if the actual timestamp is less than last time, then read the old value // otherwise read the new value //if((ts_plus1)<=lasttime) // return mi[latest^1]; //else // return mi[latest]; // what is acceptable is the following: // I want to read time stamp n and it exists // I want to read time stamp n-1 and it exists // 1- lasttime stamp is n, and current readts is n-1 // 2- lasttime stamp is n, and current readts is n // System.out.println("read from ts = "+lasttime+"at time ="+(ts_plus1-1)); if (((ts_plus1 - 1) == this->lasttime) || ((ts_plus1 - 1) == (this->lasttime - 1))) { // std::cout << "get viterbi state info"; if ((ts_plus1) <= this->lasttime) { return this->mi[latest ^ 1]; } else { return this->mi[latest]; } } else { ViterbiStateInfo tmi; tmi.prob = 0; tmi.v_path=""; tmi.v_prob=0; // System.out.println("reseting..."); // StateInfoTimeStamp::Write(0, "", 0, ts_plus1 - 1); //lasttime = ts_plus1-1; //mi[0].Write(0,"",0); //mi[1].Write(0,"",0); return tmi; //either 0 or 1 } } //bool StateInfoTimeStamp::Write(AViterbi::vr tvr, int ts) { // // bool flag = true; // //#pragma omp critical // // { // if (ts <= lasttime) { // std::cout << "State error in StateInfoTimeStamp; write time stamp is " << ts << ", while last written timestamp is\t" << lasttime << std::endl; // // flag = false; // return false; // } // // // std::cout << "update values" << std::endl; // // latest = latest ^ 1; // //write values // mi[latest].prob = tvr.total; // mi[latest].v_path = tvr.argmax; // mi[latest].v_prob = tvr.valmax; // mi[latest].ts = ts; // // if ((lasttime + 1) != ts) { // mi[latest ^ 1].prob = 0; // mi[latest ^ 1].v_path = ""; // mi[latest ^ 1].v_prob = 0; // mi[latest ^ 1].ts = ts; // } // // lasttime = ts; //is this correct? // // } // return true; //}
C
UTF-8
3,435
2.828125
3
[]
no_license
#include <stdio.h> #include <stdarg.h> #include <string.h> #include <errno.h> #include <fcntl.h> #include <asm/termios.h> #include <unistd.h> #include "types.h" #include "hardware.h" // Global variable for holding file descriptor to talk to UART0 for MIDI communications: int uart0_fd = -1; // Default UART0 device name on Raspberry Pi Model B: const char *midi_fname = "/dev/ttyAMA0"; // Open UART0 device for MIDI communications and set baud rate to 31250 per MIDI standard: int midi_init(void) { struct termios2 tio; uart0_fd = open(midi_fname, O_RDWR | O_NOCTTY | O_NONBLOCK); if (uart0_fd == -1) { char err[100]; sprintf(err, "open('%s')", midi_fname); perror(err); return -1; } // Requirements: // * UART0 is enabled // * UART0 is unused by the system for any ttys (remove mention of ttyAMA0 from `/etc/inittab`) // * UART0 clock rate is set to default of 3MHz in /boot/config.txt // * `init_uart_clock=3000000` // * UART0 clock rate for Linux is set to default of 3MHz in /boot/cmdline.txt // * `bcm2708.uart_clock=3000000` // // NOTE: Any hacks to change the default UART clock speed of the RPi B to adjust the // standard baud rates of 38400 to actually be ~31250 DO NOT WORK on latest Raspbian // kernels. I'm using `Linux 4.1.18 armv6l` as of 2017-02-20. // // The only thing that DOES work on latest Raspbian kernels is the code below which uses // termios2 to set a custom baud rate of 31250 which is the MIDI standard. // Set baud rate to 31250 for MIDI: ioctl(uart0_fd, TCGETS2, &tio); tio.c_cflag &= ~CBAUD; tio.c_cflag |= BOTHER; tio.c_ispeed = 31250; tio.c_ospeed = 31250; ioctl(uart0_fd, TCSETS2, &tio); return uart0_fd; } void midi_send_cmd1_impl(u8 cmd_byte, u8 data1) { int count; u8 buf[2]; buf[0] = cmd_byte; buf[1] = data1; count = write(uart0_fd, buf, 2); if (count != 2) { perror("Error sending MIDI bytes"); return; } printf("MIDI: %02X %02X\n", cmd_byte, data1); } void midi_send_cmd2_impl(u8 cmd_byte, u8 data1, u8 data2) { int count; u8 buf[3]; buf[0] = cmd_byte; buf[1] = data1; buf[2] = data2; count = write(uart0_fd, buf, 3); if (count != 3) { perror("Error sending MIDI bytes"); return; } printf("MIDI: %02X %02X %02X\n", cmd_byte, data1, data2); } // 256 byte buffer for batching up SysEx data to send in one write() call: u8 sysex[256]; size_t sysex_p = 0; // Buffer up SysEx data until terminating F7 byte is encountered: void midi_send_sysex(u8 byte) { //printf("MIDI: %02X\n", byte); if (sysex_p >= 256) { fprintf(stderr, "MIDI SysEx data too large (>= 256 bytes)\n"); return; } // Buffer data: sysex[sysex_p++] = byte; if (byte == 0xF7) { size_t i; size_t write_count = sysex_p; sysex_p = 0; printf("MIDI SysEx:"); for (i = 0; i < write_count; i++) { printf(" %02X", sysex[i]); } printf("\n"); ssize_t count = write(uart0_fd, sysex, write_count); if (count < 0) { perror("write in midi_send_sysex"); return; } if (count != write_count) { fprintf(stderr, "midi_send_sysex write didnt write enough bytes\n"); return; } } }
PHP
UTF-8
1,545
2.6875
3
[ "MIT" ]
permissive
<?php namespace Terminus; class Fixtures { static $fixtures_dir = 'tests/fixtures'; static $current_fixture; /** * This creates a "phony" data blob that we can use for unit testing. */ static function put($args, $data) { $key = Fixtures::getArgsKey($args); if (!defined('CLI_ROOT')) { $cli_root = dirname(dirname(__DIR__)); } else { $cli_root = constant('CLI_ROOT'); } $fixture = sprintf( "%s/%s/%s", $cli_root, self::$fixtures_dir, $key ); file_put_contents($fixture, serialize($data)); } static function get($args) { $key = Fixtures::getArgsKey($args); $cli_root = dirname(dirname(__DIR__)); $filename = sprintf('%s/%s/%s', $cli_root, self::$fixtures_dir, $key); if( file_exists($filename) ) { return unserialize(file_get_contents("$filename")); } else { var_dump($filename); } return false; } static function getArgsKey($args) { // strip UUIDs $string = preg_replace('#https://dashboard.getpantheon.com/api/(sites|users|ogranizations)\/(.*)\/(.+)$#s','$1/$3',$args[0]); $key = sprintf('%s%s', $args[1], strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $string)))); if (\Terminus::get_config('debug')) { \Terminus\Loggers\Regular::debug(var_export($args,1)); \Terminus\Loggers\Regular::debug($key); } return $key; } static function setFixture($fixture) { self::$current_fixture = $fixture; } static function clear() { self::$current_fixture = false; } }
C#
UTF-8
1,660
3.484375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CarDelegate { class Program { static void Main(string[] args) { //First, make a Car object Car c1 = new Car("SlugBug", 100, 10); //Теперь говорим машине какой метод вызвать //когда машина посылает нам сообщение c1.RegisterWithCarEngine(new Car.CarEngineHandler(OnCarEngineEvent)); //регистрация множественных целей для уведомления c1.RegisterWithCarEngine(new Car.CarEngineHandler(OnCarEngineEvent2)); //Speed up (this will trigger the events). Console.WriteLine("***** Speeding up *****"); for (int i = 0; i < 6; i++) c1.Accelerate(20); Console.ReadLine(); } //теперь мы имеем два метода которые будут вызваны из класса Car когда мы отправим сообщение (уведомление) public static void OnCarEngineEvent2(string msg) { Console.WriteLine($"=> {msg.ToUpper()}"); } //Это цель для входящих сообщений private static void OnCarEngineEvent(string msg) { Console.WriteLine("\n***** Message From Car Object *****"); Console.WriteLine($"=> {msg}"); Console.WriteLine("*************************************\n"); } } }
Go
UTF-8
1,684
3.390625
3
[]
no_license
package lru import "container/list" type Cache struct { //允许使用的最大内存 maxBytes int //当前已使用的内存 nbytes int ll *list.List cache map[interface{}]*list.Element OnEvicted func(key string, value Value) } type entry struct { key string value Value } type Value interface { Len() int } func New(maxBytes int,onEvicted func(string,Value)) *Cache { return &Cache{ maxBytes: maxBytes, ll: list.New(), cache: make(map[interface{}]*list.Element), OnEvicted: onEvicted, } } func (c *Cache) Add(key string,value Value){ if c.cache == nil{ c.cache = make(map[interface{}]*list.Element) c.ll = list.New() } if ee,ok := c.cache[key];ok{ c.ll.PushFront(ee) kv := ee.Value.(*entry) c.nbytes += int(value.Len()) - int(kv.value.Len()) kv.value = value }else { ele := c.ll.PushFront(&entry{key,value}) c.cache[key] = ele c.nbytes += int(len(key)) + int(value.Len()) } if c.maxBytes != 0 && c.maxBytes < c.nbytes{ c.RemoveOldest() } } func (c *Cache) Get(key string) (value Value,ok bool){ if ele,ok := c.cache[key];ok{ c.ll.MoveToFront(ele) kv := ele.Value.(*entry) return kv.value,true } return } func (c *Cache) Remove(key string){ if c.cache == nil{ return } if ele,ok := c.cache[key];ok{ c.removeElement(ele) } } func (c *Cache) RemoveOldest(){ if c.cache == nil{ return } ele := c.ll.Back() if ele != nil{ c.removeElement(ele) } } func (c *Cache) removeElement(e *list.Element){ c.ll.Remove(e) kv := e.Value.(*entry) delete(c.cache,kv.key) if c.OnEvicted != nil{ c.OnEvicted(kv.key,kv.value) } } func (c *Cache) Len() int{ if c.cache == nil{ return 0 } return c.ll.Len() }
Go
UTF-8
450
2.6875
3
[]
no_license
package api import ( "fmt" "net/http" ) // Index ... func Index(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") auth := r.Header["X-Auth-Token"][0] user := r.Header["X-User-Id"][0] service := r.Header["X-Service"][0] // bytes, _ := json.Marshal(r.Header) returnInfo := fmt.Sprintf( "Index Page for user: %s, service: %s with auth: %s", user, service, auth) w.Write([]byte(returnInfo)) }
SQL
UTF-8
469
3.1875
3
[]
no_license
CREATE TABLE `comments` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `user_id` int(10) unsigned NOT NULL, `type` varchar(10) NOT NULL, `type_id` int(10) unsigned NOT NULL, `message` text NOT NULL, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, PRIMARY KEY (`id`), KEY `type,type_id,created_at` (`type`,`type_id`,`created_at`), KEY `user_id,type,created_at` (`user_id`,`type`,`created_at`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8
Java
UTF-8
595
1.734375
2
[ "MIT" ]
permissive
package com.jkcoxson.camelmod; import net.fabricmc.api.ModInitializer; import net.fabricmc.loader.api.FabricLoader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Path; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.UUID; public class Camelmod implements ModInitializer { @Override public void onInitialize() { CommandReg command = new CommandReg(); command.RegisterCommands(); tcamelp.Connect("jkcoxson.com",42069); } }
Java
UTF-8
382
2.09375
2
[]
no_license
package repository; import model.Message; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; /** * Created by Ольга on 04.08.2014. */ public interface MessageRepository extends CrudRepository<Message, Long> { @Query("select m from Message m order by date desc") Iterable<Message> findAllOrderBy(); }
C++
UTF-8
1,078
2.9375
3
[]
no_license
#ifndef PLOT_H #define PLOT_H #include <qwt_plot.h> #include <qwt_plot_grid.h> #include <QWidget> /*! \class Plot * \brief 2D display widget * * This class inherits QwtPlot and allows to display a two dimensionel graph. \n * It is used for a 2D display of the drone's position. * */ class Plot : public QwtPlot { public: Plot(QWidget *parent); /*! * \brief Draw the position * * This function is called each time the position needs to be redrawn \n * Convert the drone's position in the widget's coordinates * * \param painter : Painter used for drawing * */ virtual void drawCanvas (QPainter *painter) ; void setPosX(double x); void setPosY(double y); void drawTarget(double xMission, double yMission); void removeTarget(); private: QwtPlotGrid *grid ; QPixmap *img ; double posX ; double posY ; double xMission ; double yMission ; bool missionActive ; }; #endif // PLOT_H
Java
UTF-8
437
3.09375
3
[]
no_license
/** * A node to be used in a linked list * 2020-02-14 * Author: Elliot Duchek */ public class Node { String data; Node next; public Node(String data, Node next) { this.data = data; this.next = next; } public Node(String data) { this.data = data; this.next = null; } public String getData() { return data; } public Node getNext() { return next; } }
Java
UTF-8
1,575
3.546875
4
[]
no_license
package demo10; import java.util.Random; import java.util.concurrent.*; /** * callable和runable区别是可以返回线程执行的结果 * Created by Administrator on 2016/7/4 0004. */ public class FutureAndCallableTest { public static void main(String[] args) { //通过executor提交任务 ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<Integer> future = executorService.submit(new Callable<Integer>() { @Override public Integer call() throws Exception { Thread.sleep(0500); Random random = new Random(); return random.nextInt(1000); } }); try { System.out.println(future.get(1,TimeUnit.SECONDS)); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } catch (TimeoutException e) { e.printStackTrace(); } //普通方式提交任务 Callable<Integer> data = new Callable<Integer>(){ @Override public Integer call() throws Exception { return 1; } }; FutureTask<Integer> futureTask = new FutureTask<Integer>(data); new Thread(futureTask).start(); try { System.out.println(futureTask.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }
Java
UTF-8
2,302
2.140625
2
[]
no_license
package pages; import actors.User; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.Select; import selenium.WebDriverWrapper; import utils.Log4Test; import java.util.concurrent.TimeUnit; /** * Created by test on 11/3/14. */ public class HomePage { private static final By searchField = By.id("searchbox"); private static final By searchBtn = By.id("doSearch"); public static final String SITE = "http://hotline.ua"; private static final By registerBtn = By.className("reg"); public static final By CLOSESELECTOR = By.id("shade"); private static final By catalogItemBt = By.xpath("//a[@href='/bt/']"); private static final By holodilnikiItem = By.xpath("//a[@href='/bt/holodilniki/']"); protected WebDriverWrapper driver; public HomePage(WebDriverWrapper driver) { this.driver = driver; } public void open() { driver.get(SITE); closeSelector(); } public void closeSelector() { WebElement shade = driver.findElement(CLOSESELECTOR); if (shade.isDisplayed()) { shade.click(); } } public RegistrationPage goRegistration() { driver.findElement(registerBtn).click(); return new RegistrationPage(driver); } public GoodsPage findProduct(String product) { Log4Test.info("Searching for the " + product); driver.findElement(searchField).clear(); driver.findElement(searchField).sendKeys(product); driver.findElement(searchBtn).submit(); driver.manage().timeouts().implicitlyWait(WebDriverWrapper.TIME_TO_WAIT, TimeUnit.SECONDS); return new GoodsPage(driver); } public FilterPage findFridgeItem() { Actions actions = new Actions(driver.getOriginalDriver()); actions.moveToElement(driver.findElement(catalogItemBt)); Log4Test.info("Opening fridge category from menu..."); actions.perform(); driver.manage().timeouts().implicitlyWait(WebDriverWrapper.TIME_TO_WAIT, TimeUnit.SECONDS); driver.findElement(holodilnikiItem).click(); return new FilterPage(driver); } }
TypeScript
ISO-8859-1
12,388
2.828125
3
[]
no_license
///<reference path='Haendler.ts' /> namespace Haendler { document.addEventListener("DOMContentLoaded", init); let trees: string[] = ["Nordmanntanne", "Rotfichte", "Fichte", "Gucci-Fichte"]; let treesPrice: number[] = [34.99, 29.99, 19.99, 349.99]; let balls: string[] = ["Kugel rot", "Kugel blau", "Kugel gold", "Kugel Supreme"]; let ballsPrice: number[] = [4.99, 9.99, 3.99, 129.99]; let candles: string[] = ["Kerze rot", "Kerze blau", "Kerze gold", "Kerze VVS"]; let candlesPrice: number[] = [2.99, 2.99, 3.99, 49.99]; let lightstring: string[] = ["Lichterkette 3m", "Lichterkette 6m", "Lichterkette 10m", "Lichterkette Prada"]; let lightstringPrice: number[] = [19.99, 24.99, 29.99, 149.99]; let peak: string[] = ["Egel", "Stern", "Supreme", "Gucci"]; let peakPrice: number[] = [14.99, 129.99, 199.99, 249.99]; let shoppingCartName: string[] = []; let shoppingCartPrice: number[] = []; // let fieldset: HTMLFieldSetElement; // let inputTree: HTMLInputElement[] = []; // let inputBalls: HTMLInputElement[] = []; // let inputCandle: HTMLInputElement[] = []; // let inputLight: HTMLInputElement[] = []; // let inputPeak: HTMLInputElement[] = []; function init(): void { radioButton(); createInput(); createFirstStepper(); createThirdStepper(); createRadioButtonPeak(); createRadioButtonLight(); createRadioButtonTree(); console.log("Init"); let fieldsets: NodeListOf<HTMLFieldSetElement> = document.getElementsByTagName("fieldset"); for (let i: number = 0; i < fieldsets.length; i++) { let fieldset: HTMLFieldSetElement = fieldsets[i]; fieldset.addEventListener("change", handleChange); } } /* Funktion zum lschen der Array Elemente welche zu vor angewhlt waren function cutShoppingCar(): void { for (let i: number = 0, i < trees.lenght, i++) { let baum: string = shoppingCartName.indexOf(tree[i].name); if (baum <= 0) { shopingCartName.splice(baum, 1); } } */ function handleChange(_event: Event): void { // console.log(_event); //*/ let target: HTMLInputElement = <HTMLInputElement>_event.target; console.log("Changed " + target.name + " to " + target.value); //*/ //*/ note: this == _event.currentTarget in an event-handler // eventuell switch case______ let id: string = this.id; switch (id) { // PEAK // zum raus schneiben aus dem Array einen wert mit geben welcher vor dem Name Preis steht zb "1" dadurch kann man // mit indexof ein // nach dem wert suchen und ihn und das folge Objekt lschen case "fieldsetRadio1": { shoppingCartName.push(peak[0]); shoppingCartPrice.push(peakPrice[0]); console.log(shoppingCartName, shoppingCartPrice); break; } /* else { let indexName: number = shoppingCartName.indexOf(trees[0]); let indexPrice: number = shoppingCartName.indexOf(treesPrice[0]); if (ind <= 0) { shoppingCartName.splice(indexName, i); shoppingCartPrice.splice(indexPrice, i); // es ist mglich falls der preis zweimal vorhandne ist // das man den flachen entfernt }*/ case "fieldsetRadio2": { shoppingCartName.push(peak[1]); shoppingCartPrice.push(peakPrice[1]); console.log(shoppingCartName, shoppingCartPrice); break; } case "fieldsetRadio3": { shoppingCartName.push(peak[2]); shoppingCartPrice.push(peakPrice[2]); console.log(shoppingCartName, shoppingCartPrice); break; } case "fieldsetRadio4": { shoppingCartName.push(peak[3]); shoppingCartPrice.push(peakPrice[3]); console.log(shoppingCartName, shoppingCartPrice); break; } case "fieldsetRadio5": { // function zum entfernen des Produkts break; } // PEAK ENDE // LCIHTERKETTE case "fieldsetRadio6": { shoppingCartName.push(lightstring[1]); shoppingCartPrice.push(lightstringPrice[1]); console.log(shoppingCartName, shoppingCartPrice); break; } case "fieldsetRadio7": { shoppingCartName.push(lightstring[2]); shoppingCartPrice.push(lightstringPrice[2]); console.log(shoppingCartName, shoppingCartPrice); break; } case "fieldsetRadio8": { shoppingCartName.push(lightstring[3]); shoppingCartPrice.push(lightstringPrice[3]); console.log(shoppingCartName, shoppingCartPrice); break; } case "fieldsetRadio9": { shoppingCartName.push(lightstring[3]); shoppingCartPrice.push(lightstringPrice[3]); console.log(shoppingCartName, shoppingCartPrice); break; } case "fieldsetRadio10": { // function zum entfernen des Produkts break; } // LICHTERKETTE ENDE //BAUM case "fieldsetRadio11": { shoppingCartName.push(trees[0]); shoppingCartPrice.push(treesPrice[0]); console.log(shoppingCartName, shoppingCartPrice); break; } case "fieldsetRadio12": { shoppingCartName.push(trees[1]); shoppingCartPrice.push(treesPrice[1]); console.log(shoppingCartName, shoppingCartPrice); break; } case "fieldsetRadio13": { shoppingCartName.push(trees[2]); shoppingCartPrice.push(treesPrice[2]); console.log(shoppingCartName, shoppingCartPrice); break; } case "fieldsetRadio14": { shoppingCartName.push(trees[3]); shoppingCartPrice.push(treesPrice[3]); console.log(shoppingCartName, shoppingCartPrice); break; } // ENDE BAUM case "fieldsetCandles1": { shoppingCartName.push(trees[3]); shoppingCartPrice.push(treesPrice[3]); console.log(shoppingCartName, shoppingCartPrice); break; } } } /* if (target.name == "fieldsetBalls") { let meter: HTMLProgressElement = <HTMLProgressElement>document.getElementsByTagName("meter")[0]; meter.value = parseFloat(target.value); console.log(target.value); } if (target.name == "kugel_rot") { let anzahl: HTMLProgressElement = <HTMLProgressElement>document.getElementsByTagName("anzahl"); anzahl.value = parseFloat(target.value); console.log(anzahl); } */ function createInput(): Node { let label: HTMLLabelElement = document.createElement("label"); let input: HTMLInputElement = document.createElement("input"); // let legend: HTMLLegendElement = document.createElement("legend"); label.appendChild(input); input.type = "number"; input.min = "0"; input.max = "30"; input.step = "2"; input.value = "0"; return input; } function createFirstStepper(): void { let ballsStepperRot: Node = createInput(); let rot: HTMLElement = document.getElementById("kugel_rot"); rot.appendChild(ballsStepperRot); let ballsStepperBlau: Node = createInput(); let weis: HTMLElement = document.getElementById("kugel_blau"); weis.appendChild(ballsStepperBlau); let ballsStepperGold: Node = createInput(); let gold: HTMLElement = document.getElementById("kugel_gold"); gold.appendChild(ballsStepperGold); let ballsStepperSupreme: Node = createInput(); let supreme: HTMLElement = document.getElementById("kugel_supreme"); supreme.appendChild(ballsStepperSupreme); } function createThirdStepper(): void { let stepperCandles1: Node = createInput(); let red: HTMLElement = document.getElementById("fieldsetCandles1"); red.appendChild(stepperCandles1); let stepperCandles2: Node = createInput(); let blue: HTMLElement = document.getElementById("fieldsetCandles2"); blue.appendChild(stepperCandles2); let stepperCandles3: Node = createInput(); let gold: HTMLElement = document.getElementById("fieldsetCandles3"); gold.appendChild(stepperCandles3); let stepperCandles4: Node = createInput(); let vvs: HTMLElement = document.getElementById("fieldsetCandles4"); vvs.appendChild(stepperCandles4); } function radioButton(): Node { let input: HTMLInputElement = document.createElement("input"); input.type = "radio"; input.required = true; input.name = "container"; return input; } function createRadioButtonPeak(): void { let radio1: Node = radioButton(); let engel: HTMLElement = document.getElementById("fieldsetRadio1"); engel.appendChild(radio1); let radio2: Node = radioButton(); let stern: HTMLElement = document.getElementById("fieldsetRadio2"); stern.appendChild(radio2); let radio3: Node = radioButton(); let supreme: HTMLElement = document.getElementById("fieldsetRadio3"); supreme.appendChild(radio3); let radio4: Node = radioButton(); let gucci: HTMLElement = document.getElementById("fieldsetRadio4"); gucci.appendChild(radio4); let radio5: Node = radioButton(); let noProduct: HTMLElement = document.getElementById("fieldsetRadio5"); noProduct.appendChild(radio5); } function createRadioButtonLight(): void { let radio1: Node = radioButton(); let lk3m: HTMLElement = document.getElementById("fieldsetRadio6"); lk3m.appendChild(radio1); let radio2: Node = radioButton(); let lk6m: HTMLElement = document.getElementById("fieldsetRadio7"); lk6m.appendChild(radio2); let radio3: Node = radioButton(); let lk10m: HTMLElement = document.getElementById("fieldsetRadio8"); lk10m.appendChild(radio3); let radio4: Node = radioButton(); let prada: HTMLElement = document.getElementById("fieldsetRadio9"); prada.appendChild(radio4); let radio5: Node = radioButton(); let noProduct: HTMLElement = document.getElementById("fieldsetRadio10"); noProduct.appendChild(radio5); } function createRadioButtonTree(): void { let radio1: Node = radioButton(); let nordmanntanne: HTMLElement = document.getElementById("fieldsetRadio11"); nordmanntanne.appendChild(radio1); let radio2: Node = radioButton(); let rotFichte: HTMLElement = document.getElementById("fieldsetRadio12"); rotFichte.appendChild(radio2); let radio3: Node = radioButton(); let fichte: HTMLElement = document.getElementById("fieldsetRadio13"); fichte.appendChild(radio3); let radio4: Node = radioButton(); let supreme: HTMLElement = document.getElementById("fieldsetRadio14"); supreme.appendChild(radio4); } }
PHP
UTF-8
2,744
2.609375
3
[ "MIT" ]
permissive
<?php include '../dataConnections.php'; session_start(); if(!isset($_SESSION['principal'])){ echo "<script language='javascript'>window.location='../index.php';</script>"; } $currentPage = 'other'; include 'header.php'; $data = array(); $yands = '2/4 Sem-1'; $Branch = 'CSE'; $sql = "SELECT student_marks.CourseID,COUNT(student_marks.CourseID) AS count FROM student_marks WHERE student_marks.YearandSem = '$yands' AND student_marks.CourseID IN (SELECT course_yands.CourseID FROM course_yands WHERE course_yands.Branch = '$Branch') GROUP BY CourseID ORDER BY CourseID"; $retval = mysqli_query($conn, $sql); while($row = mysqli_fetch_array($retval)) { $data[$row['CourseID']] = $row['count']; } $dataPoints1 = array(); $dataPoints2 = array(); foreach ($data as $cid => $count) { $pass = 0; $fail = 0; $sql="SELECT courses.CourseName,courses.sessional, courses.SEE,student_marks.MidExam1, student_marks.MidExam2, student_marks.External FROM student_marks INNER JOIN courses ON courses.CourseID = student_marks.CourseID WHERE student_marks.CourseID = '$cid' ORDER BY student_marks.CourseID"; $retval = mysqli_query($conn, $sql); $total = 0; while($row = mysqli_fetch_array($retval)) { $max = $row['sessional'] + $row['SEE']; $cname = $row['CourseName']; $total = ($row['MidExam1'] + $row['MidExam2'])/2 + $row['External']; if ($total >= ($max * 0.4)) { $pass++; } else { $fail++; } } array_push($dataPoints2, array("label"=> "$cname", "y"=> $pass)); array_push($dataPoints1, array("label"=> "$cname", "y"=> $fail)); } ?> <!DOCTYPE HTML> <html> <head> <script> window.onload = function () { var chart = new CanvasJS.Chart("chartContainer", { animationEnabled: true, theme: "light2", title:{ text: "Student Marks Analysis" }, legend:{ cursor: "pointer", verticalAlign: "center", horizontalAlign: "right", itemclick: toggleDataSeries }, data: [{ type: "column", name: "Fail", indexLabel: "{y}", // yValueFormatString: "$#0.##", showInLegend: true, dataPoints: <?php echo json_encode($dataPoints1, JSON_NUMERIC_CHECK); ?> },{ type: "column", name: "Pass", indexLabel: "{y}", // yValueFormatString: "$#0.##", showInLegend: true, dataPoints: <?php echo json_encode($dataPoints2, JSON_NUMERIC_CHECK); ?> }] }); chart.render(); function toggleDataSeries(e){ if (typeof(e.dataSeries.visible) === "undefined" || e.dataSeries.visible) { e.dataSeries.visible = false; } else{ e.dataSeries.visible = true; } chart.render(); } } </script> </head> <body> <div id="chartContainer" style="height: 370px; width: 100%;"></div> <script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script> </body> </html>
Java
UTF-8
1,227
2.4375
2
[]
no_license
package com.shridhar.actions; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.shridhar.dao.CommonDAO; public class FetchRights { private Role role = new Role(); private List<String> rightlist = new ArrayList<String>(); public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } public List<String> getRightlist() { return rightlist; } public void setRightlist(List<String> rightlist) { this.rightlist = rightlist; } @Override public String toString() { return "FetchRights [role=" + role + ", rightlist=" + rightlist + "]"; } public String fetchright() throws ClassNotFoundException, SQLException { Connection con = null; PreparedStatement pstmt,pstmt1 = null; ResultSet rs,rs1 = null; con = CommonDAO.getConnection(); pstmt = con.prepareStatement("select rightname from right_mst"); rs = pstmt.executeQuery(); while(rs.next()) { rightlist.add(rs.getString(1)); } System.out.println(rightlist); role.setRightlist(rightlist); return "success"; } }
PHP
UTF-8
596
2.734375
3
[]
no_license
<?php namespace Botlife\Entity\Bar\Dao; class ItemPrice { public function getPrice($itemId) { $response = \DataGetter::getData( 'file-content', 'http://rscript.org/lookup.php?type=ge&search=' . $itemId ); $response = explode("\n", $response); foreach ($response as &$data) { $data = explode(': ', $data); if ($data[0] == 'ITEM') { $data = explode(' ', $data[1]); $math = new \Botlife\Utility\Math; return $math->evaluate($data[2]); } } } }
C++
UTF-8
3,807
3.953125
4
[]
no_license
#include <iostream> #include<vector> #include <algorithm> using namespace std; class Observer; /** * Subject interface is implemented by all concrete implementation of Subject * class.These methods will accept Observer instance for register,removal and * notification */ class Subject{ public: virtual void RegisterObserver(Observer *obj) = 0; virtual void RemoveObserver(Observer *obj) = 0; virtual void NotifyObservers() = 0; }; /** * The Observer interface is implemented by all Observers, * so they all have to implement the update() method. */ class Observer{ public: virtual void update(float temp, float humidity, float pressure) = 0; }; /** * The DisplayElement interface just includes one method,disply() * that we will call when the display element needs to be displayed */ class DisplayElement{ virtual void display() = 0; }; /** * Concreate implementation of Subject class, WeatherData implements all interfaces of * Subject class */ class WeatherData : public Subject { public: vector<Observer*> Objlist; //!< Added vector Objlist to hold the Observers float temp; float humidity; float pressure; /** * When an Observer registers , we just add it to the list */ void RegisterObserver(Observer *obj) { Objlist.push_back(obj); } /** * When an Observer de-register, just remove it from the list */ void RemoveObserver(Observer *obj) { Objlist.erase(std::remove(Objlist.begin(), Objlist.end(), obj), Objlist.end()); } /** Itertively notify all Observers by taking out the * instance of Observer from the list */ void NotifyObservers() { for(vector<Observer*>::const_iterator iter = Objlist.begin(); iter != Objlist.end(); ++iter) { if(*iter != 0) { (*iter)->update(temp, humidity, pressure); } } } /** * Notify the Observers when we get updated * measurements from the Weather Station */ void MeasurementsChanged() { NotifyObservers(); } /** * API to update weather parameters */ void SetMeasurements(float temp, float humidity, float pressure) { this->temp = temp; this->humidity = humidity; this->pressure = pressure; MeasurementsChanged(); } }; /** * Concrete implementation of Observer */ class CurrentConditionsDisplay: public Observer, public DisplayElement{ private: float temp; float humidity; float pressure; Subject *weatherData; public: CurrentConditionsDisplay(Subject *weatherdata){ weatherData = weatherdata; weatherData->RegisterObserver(this); } void update(float temp, float humidity, float pressure) { this->temp = temp; this->humidity = humidity; this->pressure = pressure; } void display() { std::cout<<" Current temperature is "<<temp<<" "<<" at humidiity level "<<humidity<<" pressure is "<<pressure<<std::endl; } }; /** * Client program */ int main() { WeatherData *weatherData = new WeatherData; CurrentConditionsDisplay *currentConditionsDisplay = new CurrentConditionsDisplay(weatherData); weatherData->SetMeasurements(80,65, 30); delete weatherData; return 0; } ## Output Current temperature is 80 at humidiity level 65 pressure is 30
Markdown
UTF-8
795
2.65625
3
[]
no_license
# _{Andres Garcia}_ #### _{Portfolio}, {V 1.0.0}_ #### By _**{Developed by Andres Garcia}**_ ## Description _{This is my personal portfolio, here you will find any relevant information to me, including my work experience, background information and much more. }_ ## Setup/Installation Requirements * _Computer_ * _Internet_ * _Web browser_ * _Thats it!_ ## Known Bugs _{There are no known bugs in this version, but feel free to explore the code and find some yourself!}_ ## Support and contact details _{Feel free to contact me at: Email: andresgarciar96@gmail.com}_ ## Technologies Used _{For this project I used Atom, HTML, Javascriot and Boostrap.}_ ### License *{Determine the license under which this application can be used. See below for more details on licensing.}* Copyright (c) 2016 **_{Andres Garcia}_**
Java
UTF-8
1,638
2.484375
2
[]
no_license
package cz.kinst.jakub.weather.android.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.List; import butterknife.ButterKnife; import butterknife.InjectView; import cz.kinst.jakub.weather.android.R; /** * Adapter used in navigation drawer * <p> * Created by jakubkinst on 04/04/15. */ public class NavigationAdapter extends ArrayAdapter<NavigationAdapter.NavigationItem> { private static final int LAYOUT = R.layout.item_navigation; public NavigationAdapter(Context context, List<NavigationItem> objects) { super(context, LAYOUT, objects); } @Override public View getView(final int position, View view, ViewGroup parent) { ViewHolder row; if (view == null) { view = LayoutInflater.from(getContext()).inflate(LAYOUT, parent, false); row = new ViewHolder(view); view.setTag(row); } else { row = (ViewHolder) view.getTag(); } row.title.setText(getItem(position).title); row.icon.setImageResource(getItem(position).iconResource); return view; } public static class ViewHolder { @InjectView(R.id.navigation_title) public TextView title; @InjectView(R.id.navigation_icon) public ImageView icon; public ViewHolder(View v) { ButterKnife.inject(this, v); } } public static class NavigationItem { public String title; public int iconResource; public NavigationItem(String title, int iconResource) { this.title = title; this.iconResource = iconResource; } } }
Java
UTF-8
777
3.046875
3
[]
no_license
package com.jhlc.second.second.saunfa; /** * Created by licheng on 8/1/16. */ public class CountNonDivisible { public static void main(String[] args) { int[] A = {3,1,2,0,6}; for (int i = 0; i < A.length; i++) { System.out.print(solution(A)[i] + " "); } } //66分 https://codility.com/demo/results/training5G6KAK-JMW/ public static int[] solution(int[] A){ int len = A.length; int[] results = new int[len]; for (int i = 0; i < len; i++) { int count = 0; for (int j = 0; j < len; j++) { if(A[j] != 0 && A[i] % A[j] != 0){ count ++; } } results[i] = count; } return results; } }
C
UTF-8
490
2.671875
3
[]
no_license
#include<stdlib.h> #include<stdio.h> #define debug(...) printf(__VA_ARGS__) #define debug2(x...) printf(x) #define fun(n) printf("test"#n"=%d",token##n) #define token9 9 static inline int func(int x,int y){ return x+y; //printf("%s\n",__func__); } int main(){ func(1,2); debug("%s\n",__FILE__); debug("%d\n",__LINE__); debug("hello world %d\n",1); debug2("hello %d %s\n",123,"abcd"); fun(9); int *p; printf("%d\n",sizeof(*p)); //name(abcde); }
Java
UTF-8
927
2.578125
3
[]
no_license
package me.Andrew.IslandExtras.IslandBorder; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import java.util.ArrayList; /** * Created by Andrew on 04/06/2017. */ public class ChatHandler { private String prefix = cc("&a[Prefix] "); public void sendHelp(Player p){ ArrayList help = new ArrayList(); help.add("&cHelp1"); help.add("&cHelp2"); help.add("&cHelp3"); help.add("&cHelp4"); } public void send(String msg, Player p){ p.sendMessage(prefix+cc(msg)); } public void sendList(ArrayList<String> al, Player p){ send("--------------------------",p); for(String st : al){ send(st,p); } send("--------------------------",p); } public void sendError(String ce,Player p){ } public String cc(String txt){ return(ChatColor.translateAlternateColorCodes('&',txt)); } }
Markdown
UTF-8
1,794
3.109375
3
[]
no_license
# Bird Speak This app allows users to read the latest 25 tweets, up to 7 days ago, from any twitter handle. ### App Design Choices For user authentication, Devise is a no brainer. It's the goto for quick and reliable authentication. For styling, I chose Tachyons because it is also quick, lightweight and prevents me from having to write extra css. For ENV variables, I chose to use dotenv, which allows you to store secret vars in one file. For the application logic, I started at first putting small modules (like Utils and Twitter API) into the lib directory. I like this approach because it's sort of a functional style and it allows for easy unit testing. However, I moved these modules into their own classes, because it was easier to config with Heroku. I also added Redis caching to this class. I could have added basic Rails caching, but I thought it would be fun to spin up a quick Redis db. And finally I added a few mini tests. ### Setup Instructions - Git clone the repo and cd into the directory. - See Doug for the secret .env file and add it to the root of this project. Alternatively, create your own Twitter Dev App (https://apps.twitter.com/) and enter the corresponding values to these four keys: ``` TWITTER_CONSUMER_KEY="Your value here, and the others below" TWITTER_CONSUMER_SECRET= TWITTER_ACCESS_TOKEN= TWITTER_ACCESS_SECRET= ``` - You will also need a Redis & Postgres server running ``` $ brew install redis $ redis-server /usr/local/etc/redis.conf $ pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start ``` - Run `$ bundle` - Run `rake db:migrate` - Run `rails s` to start up the server on localhost:3000 ### Test Suite Instructions - Run `$ rake db:test:prepare` - Run `$ rake test`
PHP
UTF-8
4,741
2.703125
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers\Admin; use Auth; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\User; use Illuminate\Support\Facades\Mail; use Illuminate\Mail\Mailable; use Malahierba\ChileRut\Facades\ChileRut; /** * Es el controlador del administrador del sistema. * */ class UserController extends Controller { /** * Es la funcion que presenta la vista principal de la gestion de usuarios * por parte del administrador */ public function index(){ //$users = User::where('role', 1)->get(); Est es para que el admin solo pueda ver Compradores $users = User::all(); return view('admin.users.index')->with(compact('users')); } /** * Es la funcion que almacena el usuario creado por el administrador */ public function store(Request $request){ // Estas son las reglas que tendrá el usuario creado, las cuales pueden ser modificadas $rules =[ 'name' => 'required|string|max:255', 'email' => 'required|string|email|max:255|unique:users', 'password' => 'required|string|min:6', 'role'=>'required', 'rut' => 'required|string|min:9', ]; $chilerut = new ChileRut; $validarut = $request->input('rut'); $this->validate($request, $rules); if ($chilerut::check($validarut)) { $user = new User; $user->name = $request->input('name'); $user->email = $request->input('email'); $user->role = $request->input('role'); $user->rut = $request->input('rut'); $user->password = bcrypt($request->input('password')); $user->save(); /* * Se envia un email con la contraseña asignada al usuario. */ $email = $request->input('email'); $dates = array('name'=>$request->input('name'), 'password'=>$request->input('password')); $this->Email($dates, $email); return back()->with('notification', 'Usuario registrado exitosamente.'); } else { return back()->with('danger', 'El rut ingresado no es valido'); } } /** * Es la funcion permite al administrador seleccionar un usuario, para su posterior edición. La cual recibe como parametro el id del usuario seleccionado, para mostrar la vista 'admin.users.edit' */ public function edit($id){ $user = User::find($id); return view('admin.users.edit', compact('user')); } /* * Es la funcion que permite la modificacion de los datos del usuario seleccionado por el administrador, muy parecida a la funcion store */ public function update($id, Request $request){ // Estas son las reglas que tendrá el usuario durante su modificación, las cuales pueden ser modificadas $rules =[ 'name' => 'required|string|max:255', 'email' => 'required|string|email|max:255', 'role'=>'required', 'rut'=>'required|string|max:13', ]; $this->validate($request, $rules); $user = User::find($id); $user->name = $request->input('name'); $user->email = $request->input('email'); $user->role = $request->input('role'); $user->rut = $request->input('rut'); $user->save(); return back()->with('notification', 'Usuario editado exitosamente.'); } /* * Es la funcion que permite que se pueda eliminar algún usuario por parte del administrador */ public function delete($id){ $user = User::find($id); $user->delete(); return back()->with('notification', 'Usuario eliminado exitosamente.'); } /* * Es la funcion que permite que se envíe un email al usuario creado, con la contraseña generada por el administrador. */ public function Email($dates, $email) { Mail::send('emails.plantilla', $dates, function($message) use ($email){ $message->subject('Bienvenido a la Plataforma'); $message->to($email); $message->from('no-repply_da@arica.cl', 'Portal de Departamento de Adquisiciones'); }); } /* * Es la funcion que permite que se pueda realizar la busqueda de los usuarios. * Hace uso del modelo User para poder realizar estas busquedas. */ public function share(Request $request){ $name = $request->get('name'); $email = $request->get('email'); $rut = $request->get('rut'); $users = User::orderBy('id', 'DESC') ->name($name) ->email($email) ->rut($rut) ->paginate(4); return view('admin.users.index', compact('users')); } }
JavaScript
UTF-8
3,883
2.625
3
[]
no_license
 angular.module("mainModule", []) .controller("mainController", function($scope) { $scope.firstName = "John", $scope.lastName = "Doe"; $scope.updateName = function(firstName, lastName) { $scope.firstName = firstName; $scope.lastName = lastName; }; }) // 1 - Shared scope (scope : false) .directive("nghSharedScopeDir", function() { return { scope: false, template: '<label>First Name: <input type="text" ng-model="firstName"/></label><br/>' + '<label>Last Name: <input type="text" ng-model="lastName"/></label><br/>' + '<br/>' + '<strong>First Name:</strong>{{firstName}}<br/>' + '<strong>Last Name:</strong>{{lastName}}<br/>' }; }) // 2 - Inherited scope (scope : true) .directive("nghInheritedScopeDir", function() { return { scope: true, template: '<label>First Name: <input type="text" ng-model="firstName"/></label><br/>' + '<label>Last Name: <input type="text" ng-model="lastName"/></label><br/>' + '<br/>' + '<strong>First Name:</strong>{{firstName}}<br/>' + '<strong>Last Name:</strong>{{lastName}}<br/>' }; }) // 3- Isolated scope (scope:{}) .directive("nghIsolatedScopeDir", function() { return { scope: { firstName: '@dirFirstName', lastName: '=dirLastName', setNameMethod: '&dirUpdateNameMethod' }, template: '<label>First Name: <input type="text" ng-model="firstName"/></label><br/>' + '<label>Last Name: <input type="text" ng-model="lastName"/></label><br/>' + '<button ng-click="execSetNameMethod()">Set name on external scope</button><br/>' + '<br/>' + '<strong>First Name:</strong>{{firstName}}<br/>' + '<strong>Last Name:</strong> {{lastName}}', link: function(scope, element, attrs) { scope.execSetNameMethod = function() { scope.setNameMethod( { newFirstName: scope.firstName, newLastName: scope.lastName } ); }; } }; }) // 4- Scope Tester: shared scope .directive("nghSharedScopeTester", function() { return { scope: false, link: function(scope, element, attrs) { element.on("click", function() { scope.$root.$$childHead["sharedDirScopeId" + attrs.nghSharedScopeTester] = scope.$id; scope.$root.$digest(); }); } }; }) .directive("nghSharedScopeTesterCopy", function() { return { scope: false, link: function(scope, element, attrs) { element.on("click", function() { scope.$root.$$childHead["sharedDirScopeId" + attrs.nghSharedScopeTesterCopy] = scope.$id; scope.$root.$digest(); }); } }; }) // 4- Scope Tester: inherited scope .directive("nghInheritedScopeTester", function() { return { scope: true, link: function(scope, element, attrs) { element.on("click", function() { scope.$root.$$childHead["inheritedDirScopeId" + attrs.nghInheritedScopeTester] = scope.$id; scope.$root.$digest(); }); } }; }) .directive("nghInheritedScopeTesterCopy", function() { return { scope: true, link: function(scope, element, attrs) { element.on("click", function() { scope.$root.$$childHead["inheritedDirScopeId" + attrs.nghInheritedScopeTesterCopy] = scope.$id; scope.$root.$digest(); }); } }; }) // 4- Scope Tester: isolated scope .directive("nghIsolatedScopeTester", function() { return { //scope: {}, link: function(scope, element, attrs) { element.on("click", function() { scope.$root.$$childHead["isolatedDirScopeId" + attrs.nghIsolatedScopeTester] = scope.$id; scope.$root.$digest(); }); } }; }) .directive("nghIsolatedScopeTesterCopy", function(){ return{ //scope:{}, link: function(scope, element, attrs){ element.on("click", function(){ scope.$root.$$childHead["isolatedDirScopeId" + attrs.nghIsolatedScopeTesterCopy] = scope.$id; scope.$root.$digest(); }); } }; });
Ruby
UTF-8
491
3.296875
3
[]
no_license
def change_possibilities_bottom_up(amount, denominations) ways_of_doing_n_cents = [0] * (amount + 1) ways_of_doing_n_cents[0] = 1 for coin in denominations (coin..amount).each do |num| higher_amount_remainder = num - coin ways_of_doing_n_cents[num] += ways_of_doing_n_cents[higher_amount_remainder] end end p ways_of_doing_n_cents return ways_of_doing_n_cents[amount] end coins = [1, 5, 10, 25] amount = 25 p change_possibilities_bottom_up(amount, coins)
Java
UHC
3,138
3.015625
3
[]
no_license
package swExpert_5653_ٱ⼼; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; public class Solution { static int N, M, K; static int data[] = new int[1000 * 1000]; static int map[] = new int[1000 * 1000]; static int depth[] = new int[1000 * 1000]; static int dy[] = { -1, 1, 0, 0 }; static int dx[] = { 0, 0, 1, -1 }; static int ans; static Queue<Point> q = new LinkedList<>(); static class Point { int y, x; public Point(int y, int x) { super(); this.y = y; this.x = x; } } public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int tc = Integer.parseInt(br.readLine()); for (int t = 1; t <= tc; t++) { StringTokenizer st = new StringTokenizer(br.readLine()); N = Integer.parseInt(st.nextToken()); M = Integer.parseInt(st.nextToken()); K = Integer.parseInt(st.nextToken()); ans = 0; Arrays.fill(map, 0); Arrays.fill(data, 0); Arrays.fill(depth, 0); q.clear(); for (int i = 500; i < 500 + N; i++) { st = new StringTokenizer(br.readLine()); for (int j = 500; j < 500 + M; j++) { map[i * 1000 + j] = Integer.parseInt(st.nextToken()); data[i * 1000 + j] = map[i * 1000 + j]; if (map[i * 1000 + j] != 0) { depth[i * 1000 + j] = 1; q.add(new Point(i, j)); } } } bfs(); printMap(); System.out.println("#" + t + " " + ans); } } static void bfs() { int size = 0; int ny, nx; int dep = 1; while (K > 0) { size = q.size(); for (int i = 0; i < size; i++) { Point p = q.poll(); if (map[p.y * 1000 + p.x] == 0) { // map[p.y * 1000 + p.x] = -1; for (int d = 0; d < 4; d++) { ny = p.y + dy[d]; nx = p.x + dx[d]; if (data[ny * 1000 + nx] == 0) { map[ny * 1000 + nx] = data[p.y * 1000 + p.x]; data[ny * 1000 + nx] = data[p.y * 1000 + p.x]; depth[ny * 1000 + nx] = dep; q.add(new Point(ny, nx)); } else if(depth[ny * 1000 + nx] == dep){ if (map[ny * 1000 + nx] < data[p.y * 1000 + p.x]) { map[ny * 1000 + nx] = data[p.y * 1000 + p.x]; data[ny * 1000 + nx] = data[p.y * 1000 + p.x]; } } } } else { map[p.y * 1000 + p.x]--; q.add(new Point(p.y, p.x)); } } K--; dep++; } count(); } public static void count() { for (int i = 0; i < 1000; i++) { for (int j = 0; j < 1000; j++) { if (data[i * 1000 + j] != 0 && map[i * 1000 + j] != -1) { ans++; } } } } public static void printMap() { System.out.println("----------------------"); for (int i = 0; i < 1000; i++) { for (int j = 0; j < 1000; j++) { System.out.print(map[i * 1000 + j]); } System.out.println(); } System.out.println("----------------------"); } }
PHP
UTF-8
2,607
2.78125
3
[ "MIT" ]
permissive
<?php /** * This file is part of the EnabledChecker package * * (c) InnovationGroup * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code */ namespace FivePercent\Component\EnabledChecker\Checker; use FivePercent\Component\EnabledChecker\Exception\NotSupportedException; /** * Chain checker adapter * * @author Vitaliy Zhuk <zhuk2205@gmail.com> */ class ChainChecker implements CheckerInterface { /** * @var array */ private $checkers = []; /** * @var bool */ private $sortedCheckers = false; /** * Add checker * * @param CheckerInterface $checker * @param int $priority * * @return ChainChecker */ public function addChecker(CheckerInterface $checker, $priority = 0) { $this->sortedCheckers = false; $this->checkers[spl_object_hash($checker)] = [ 'checker' => $checker, 'priority' => $priority ]; return $this; } /** * Get checkers * * @return array */ public function getCheckers() { $this->sortCheckers(); return $this->checkers; } /** * {@inheritDoc} */ public function isSupported($object) { $this->sortCheckers(); foreach ($this->checkers as $entry) { /** @var CheckerInterface $checker */ $checker = $entry['checker']; if ($checker->isSupported($object)) { return true; } } return false; } /** * {@inheritDoc} */ public function check($object) { $this->sortCheckers(); foreach ($this->checkers as $entry) { /** @var CheckerInterface $checker */ $checker = $entry['checker']; if ($checker->isSupported($object)) { return $checker->check($object); } } throw new NotSupportedException(sprintf( 'The object "%s" not supported for check enabled status.', get_class($object) )); } /** * Get checkers * * @return array|CheckerInterface[] */ private function sortCheckers() { if ($this->sortedCheckers) { return; } $this->sortedCheckers = true; uasort($this->checkers, function ($a, $b) { if ($a['priority'] == $b['priority']) { return 0; } return $a['priority'] > $b['priority'] ? -1 : 1; }); } }
Python
UTF-8
114
3.109375
3
[]
no_license
ven=int(input()) for g in range(2,ven): if ven%g==0: print("yes") break else: print("no")
Java
UTF-8
1,056
2.234375
2
[]
no_license
package cn.wtu.broadcast.parent.vo.cmd; import java.io.Serializable; /** * RDS设置频点VO * @author yinjie * */ public class RdsFrequencyPointVo implements Serializable{ private static final long serialVersionUID = 1L; //频点序号 private Integer rdsPointSequence; //频点优先级 private Integer rdsPriority; //频率 private Double rdsFrequency; public Integer getRdsPointSequence() { return rdsPointSequence; } public void setRdsPointSequence(Integer rdsPointSequence) { this.rdsPointSequence = rdsPointSequence; } public Integer getRdsPriority() { return rdsPriority; } public void setRdsPriority(Integer rdsPriority) { this.rdsPriority = rdsPriority; } public Double getRdsFrequency() { return rdsFrequency; } public void setRdsFrequency(Double rdsFrequency) { this.rdsFrequency = rdsFrequency; } @Override public String toString() { return "RdsFrequencyPointVo [rdsPointSequence=" + rdsPointSequence + ", rdsPriority=" + rdsPriority + ", rdsFrequency=" + rdsFrequency + "]"; } }
Java
UTF-8
498
1.664063
2
[]
no_license
package com.iuh.ABCStore.services; import java.util.HashMap; import javax.transaction.Transactional; import org.springframework.stereotype.Service; import com.iuh.ABCStore.model.GioHang; import com.iuh.ABCStore.model.NguoiDung; @Service @Transactional public interface IGioHangService { boolean thanhToanPayPal(HashMap<String, GioHang> gioHang,NguoiDung nguoiDung,String idLienHe); boolean thanhToanGiaohang(HashMap<String, GioHang> gioHang,NguoiDung nguoiDung,String idLienHe); }
C++
UTF-8
1,421
2.65625
3
[]
no_license
#ifndef FAS_SERIALIZATION_COMMON_DESER_AD_INTEGER_HPP #define FAS_SERIALIZATION_COMMON_DESER_AD_INTEGER_HPP namespace fas{ namespace serialization{ namespace common{ namespace deser{ /*template<typename TgParseNumber>*/ struct ad_integer { //typedef TgParseNumber _number_; template<typename T, typename J, typename V, typename R> R operator()(T&, J, V& v, R r) { std::cout << std::endl << "ad_integer<>" << std::endl; /*if ( !t.get_aspect().template get< _number_ >().peek(t, r) ) { t.get_aspect().template get<_status_>() = false; return r; } */ return this->deserealize(v, r); /*R res = this->deserealize(v, r); typedef typename J::target target; typedef typename target::deserializer_tag deserializer_tag; r = t.get_aspect().template get< deserializer_tag >()(t, target(), v, r); return res; */ } private: template<typename V, typename R > R deserealize( V& v, R r ) { if( !r ) return r; v = 0; register bool neg = *r=='-'; if ( neg ) ++r; if ( !r || *r < '0' || *r > '9') return r; // цифры с первым нулем запрещены (напр 001), только 0 if (*r=='0') return ++r; for ( ;r; ++r ) { if (*r < '0' || *r > '9') break; v = v*10 + (*r- '0'); } if (neg) v*=-1; return r; } }; }}}} #endif
Markdown
UTF-8
667
2.609375
3
[]
no_license
# High School Contract Tracing Ontario Engineering Competition 2021 Entry ## About - This program was built with the intention of contact tracing a hypothetical virus in a high school - The contact tracing algorithm leveraged a weighted directed graph to track possible transitions on the limited data we were given (student and teacher timetables) ## Team Members * Namit Chopra * Andrew Balmakund * Divya Thakkar * Janahan Rajagopalan ## Installation and Use * Install openpyxly using command prompt * If you currently have python3 you can use 'pip install openpyxl' * If you have an older version use 'pip3 insall openpyxl' * Run the gui.py code to open the ZBY1 infection information window
Shell
UTF-8
1,786
3.6875
4
[ "BSD-3-Clause" ]
permissive
#!/bin/bash # # CoRM: Compactable Remote Memory over RDMA # # Help functions to measure latency of CoRM # # Copyright (c) 2020-2021 ETH-Zurich. All rights reserved. # # Author(s): Konstantin Taranov <konstantin.taranov@inf.ethz.ch> # source core.sh trap 'echo -ne "Stop all servers..." && killAllProcesses && killCorm && echo "done" && exit 1' INT define HELP <<'EOF' Script for measuring latency usage : $0 [options] options: --server=IP # file containing IP addressof the CoRM server --num=INT # the number of records to consume --dir=PATH #absolute path to corm EOF usage () { echo -e "$HELP" } num=10000 server="" for arg in "$@" do case ${arg} in --help|-help|-h) usage exit 1 ;; --server=*) server=`echo $arg | sed -e 's/--server=//'` server=`eval echo ${server}` # tilde and variable expansion ;; --num=*) num=`echo $arg | sed -e 's/--num=//'` num=`eval echo ${num}` # tilde and variable expansion ;; --dir=*) WORKDIR=`echo $arg | sed -e 's/--dir=//'` WORKDIR=`eval echo ${WORKDIR}` # tilde and variable expansion ;; esac done startCorm $server "--send_buf_size=65536 --threads=1 --recv_buf_size=4096 --num_recv_buf=256" sleep 0.5 #real:16 user:8; #real:24 user:15; #real:32 user:24; #real:64 user:56; #real:128 user:118; #real:248 user:236; #real:504 user:488; #real:1016 user:992; #real:2040 user:2000; allSizes=(8 15 24 56 118 236 488 992 2000) echo "Starting latency test" for size in ${allSizes[@]}; do outputfilename=latency_${size}.txt runLatency $size $num $outputfilename done killCorm echo "----------Done--------------"
C++
UTF-8
1,218
3.375
3
[]
no_license
#include <unordered_map> #include <vector> #include <iostream> #include <map> using namespace std; class Solution { public: double frogPosition(int n, vector<vector<int>>& edges, int t, int target) { unordered_map<int,vector<int>> m; for(auto edge : edges){ int from = min(edge[0],edge[1]); int to = max(edge[0],edge[1]); m[from].push_back(to); } double res = 0.0; dfs(m,t,target,1,1.0,res); return res; } void dfs(unordered_map<int,vector<int>>&m,int t,int target,int curVertex,double curPro,double& res){ if(t == 0){ if(curVertex == target){ res = curPro; } return; } if(m[curVertex].empty()){ dfs(m,t-1,target,curVertex,curPro,res); }else{ curPro = curPro * 1.0/m[curVertex].size(); for(auto vertex : m[curVertex]){ dfs(m,t-1,target,vertex,curPro,res); } } } }; int main(int argc, char const *argv[]) { vector<vector<int>> edges = {{2,1},{3,2},{4,1}}; std::cout << Solution().frogPosition(4,edges,4,1) << std::endl; return 0; }
C++
UTF-8
355
2.5625
3
[]
no_license
// // Created by Erik Stevenson on 9/16/17. // // Human controller, polls keyboard for up/down arrows, returns the respective command. // #ifndef CSCI437_HUMAN_H #define CSCI437_HUMAN_H #include "Player.h" class Human : public Player { public: Human(Player::Side); Player::Command logic(const sf::FloatRect, const float); }; #endif //CSCI437_HUMAN_H
Swift
UTF-8
1,011
3.578125
4
[ "MIT" ]
permissive
// // Service.swift // MVVM_Practice // // Created by 윤병일 on 2021/07/01. // import Foundation class Service { // Repository 를 이용해서 서버 모델 가져온것을 Logic(Service) 에서 사용하는 Model 로 바꿔줬다. var currentModel = Model(currentDateTime: Date()) let repository = Repository() func fetchNow(completion : @escaping(Model) -> Void) { // Entity -> Model 로 한번 변형이 일어났다. repository.fetchNow { [weak self] UtcDateModel in let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm'Z'" guard let now = formatter.date(from: UtcDateModel.currentDateTime) else {return} let model = Model(currentDateTime: now) self?.currentModel = model completion(model) } } func moveDay( day : Int) { guard let movedDay = Calendar.current.date(byAdding: .day, value: day, to: currentModel.currentDateTime) else {return} currentModel.currentDateTime = movedDay } }
Java
UTF-8
3,192
1.976563
2
[]
no_license
package com.getusroi.dynastore.config; import java.io.Serializable; import com.getusroi.config.beans.ConfigurationUnit; import com.getusroi.dynastore.config.jaxb.DynastoreConfiguration; import com.getusroi.dynastore.config.jaxb.DynastoreName; public class DynaStoreConfigurationUnit extends ConfigurationUnit implements Serializable{ private static final long serialVersionUID = 5000658055134380162L; public static final String DYNASTORECONFIG_GROUPKEY_SUFFIX="-DSC"; public static final String DYNASTORECONFIG_DEFULAT_VERSION="v1"; public static final String DYNA_UNIQUE_ID_NAME="DYNA_COLLECTION"; public static final String DYNA_COLLECTION_PREFIX="DYNA_COLL-"; private String siteId; /** It is matches with the ConfigId in the database i.e confignodedata{table}.nodeDataId{column} */ private Integer dbconfigId; /** Id of the Node in db that this configuration is attached with */ private Integer attachedNodeId; //private DynastoreConfiguration dynastoreConfiguration; private String dynaCollectionId; public DynaStoreConfigurationUnit(String tenantId, String siteId,Integer attachedNodeId, Boolean isEnabled,DynastoreConfiguration dynastoreConfiguration,String dynaCollectionId) { super(tenantId, dynastoreConfiguration, isEnabled, getDynaStoreKey(dynastoreConfiguration.getDynastoreName()), getConfigGroupKey(attachedNodeId)); this.siteId=siteId; this.attachedNodeId=attachedNodeId; this.dynaCollectionId=dynaCollectionId; } public String getSiteId() { return siteId; } public void setSiteId(String siteId) { this.siteId = siteId; } public Integer getDbconfigId() { return dbconfigId; } public void setDbconfigId(Integer dbconfigId) { this.dbconfigId = dbconfigId; } public Integer getAttachedNodeId() { return attachedNodeId; } public void setAttachedNodeId(Integer attachedNodeId) { this.attachedNodeId = attachedNodeId; } public static long getSerialversionuid() { return serialVersionUID; } public static String getDynastoreconfigGroupkeySuffix() { return DYNASTORECONFIG_GROUPKEY_SUFFIX; } public String getDynaCollectionId() { return dynaCollectionId; } public void setDynaCollectionId(String dynaCollectionId) { this.dynaCollectionId = dynaCollectionId; } public static String getConfigGroupKey(Integer attachedToNodeId){ String dsGroupKey = attachedToNodeId.intValue() +DYNASTORECONFIG_GROUPKEY_SUFFIX; return dsGroupKey; } public static String getDynaStoreKey(DynastoreName dynastoreName){ String dynaStoreName=dynastoreName.getValue(); if(dynastoreName.getVersion()!=null &&!dynastoreName.getVersion().isEmpty() ) return dynaStoreName+"-"+dynastoreName.getVersion(); return dynaStoreName+"-"+DYNASTORECONFIG_DEFULAT_VERSION; } public DynastoreConfiguration getDynastoreConfiguration() { return (DynastoreConfiguration)this.getConfigData(); } public String toString() { return "DynaStoreConfigurationUnit [siteId=" + siteId + ", dbconfigId=" + dbconfigId + ", attachedNodeId=" + attachedNodeId + ", dynaCollectionId=" + dynaCollectionId + ", getKey()=" + getKey() + ", getConfigGroup()=" + getConfigGroup() + "]"; } }
Python
UTF-8
362
3.4375
3
[]
no_license
import itertools s = "plyvmcthyommabcqtmqklpfkopccabybkneifgjdqhexoezlykccgpfidcqizmotounzpslphlpwghbubwthhpivqvwmvuirfhfnkjzpxyccwnuqodbdmsxybztgzvtonheaxcrpukdpgapfczulexugxghuzuvwqvgckpsgjqyzywlxtzmkqmzgavdmchnyaqzidzjfbizxgikjbsmhyikjvgveeifntxpmpgaoqbzwxyfsnexidvxdxxzzzykphrzprlzoyqqlbxbbgmyzplgqnzphbbdxitexvvjzhtpgkfpfazqiqeyczhkkooykaotkqwuuehbgfyznwjqutbltsamcmzyhzrdvvdrzhyzmcmastlbtuqjwnzyfgbheuuwqktoakyookkhzcyeqiqzafpfkgpthzjvvxetixdbbhpznqglpzymgbbxblqqyozlrpzrhpkyzzzxxdxvdixensfyxwzbqoagpmpxtnfieevgvjkiyhmsbjkigxzibfjzdizqaynhcmdvagzmqkmztxlwyzyqjgspkcgvqwvuzuhgxguxeluzcfpagpdkuprcxaehnotvzgtzbyxsmdbdoqunwccyxpzjknfhfriuvmwvqviphhtwbubhgwplhplspznuotomziqcdifpgcckylzeoxehqdjgfienkbybaccpokfplkqmtqcbammoyhtcmvylp" class Solution: def longestPalindrome(self, s: str) -> str: for j in range(len(s)+1,0,-1): for i in range(len(s)-j+1): if s[i:i+j] == s[i:i+j][::-1]: return s[i:i+j] a = Solution() print(a.longestPalindrome(s)) P I N A L S I G Y A H R P I
JavaScript
UTF-8
960
3.375
3
[ "MIT" ]
permissive
/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ /** * @param {TreeNode} root * @return {boolean} */ const isEvenOddTree = function(root) { const q = [root] const v = [] let l = 0 while(q.length) { const size = q.length const row = [] for(let i = 0; i < size; i++) { const cur = q.shift() row.push(cur.val) if(l % 2 === 0 && cur.val % 2 === 0) return false if(l % 2 === 1 && cur.val % 2 === 1) return false if(row.length > 1) { if(l % 2 === 0 && row[row.length - 1] <= row[row.length - 2]) return false if(l % 2 === 1 && row[row.length - 1] >= row[row.length - 2]) return false } if(cur.left) q.push(cur.left) if(cur.right) q.push(cur.right) } l++ } return true };
Markdown
UTF-8
13,444
2.765625
3
[]
no_license
--- title: Education --- # 教務の概要 学生の履修や出席,成績などのモデルを定義する. ## 依存モデル ```alloy private open Base private open Curriculum private open CurriculumExtensions private open Department private open Facility as F private open Staff as S private open Student as G private open Timetable as T ``` ## 履修 各学生は時間割に対して履修登録できる. 履修抽選を実現する上で履修とは区別が必要となるため履修申請をモデル定義している. ```alloy sig 履修{ 履修者 : 学生, 履修時間割 : 時間割, 再履修 : Bool, 由来する : lone 履修申請, } sig 履修申請{ 申請者 : 学生, 申請時間割 : 時間割, 状態 : 履修申請状態, 結果 : 履修申請結果, 再履修 : Bool, } ``` ## 出席 ```alloy sig 出席情報{ 時間割 : 時間割, 学生 : 学生, 教室 : 教室, 回 : Int, 出欠 : 出欠状態, }{ nonneg[回] } ``` ## 成績評価 成績は単位認定,さらに卒業進級判定を行う上で絶対に必要となる. 編転入などですでに履修の機会を失っている学生に対しても認定で成績を作ることで卒業および学士号などの取得を可能にする. 試験成績は期の中間や期末に行う試験の成績を保持する. ```alloy sig 成績{ 学生 : 学生, 科目 : 科目, 評価 : 評価コード, } sig 試験成績{ 学生 : 学生, 時間割 : 時間割, 区分 : 試験区分, 期 : 試験時期, 評価 : 評価コード, } ``` ## 前提 以下にモデルが有効であるための前提を示す. この前提は運用を含めたシステム全体に対する仮定であり,次の正当性検証の前件となる. ```alloy fact 重複する履修登録はない{ no g: G/学生 | some disj r,r': g.~履修者 | r.履修時間割 = r'.履修時間割 } fact 成績の評価は学則の評価基準の範囲にある必要がある{ all s: 成績 | let rs = {r : s.学生.適用.~含まれる | r.科目 = s.科目} | s.評価 in rs.評価基準.取り得る評価 } fact 単位修得できる成績は学生科目ごとに高々ひとつしかない{ no s: G/学生 | some disj e,e': s.~(成績 <: 学生) | e.科目 = e'.科目 and 単位になる[e] and 単位になる[e'] } fact 履修の科目は履修者の全履修可能科目の範囲内にある{ all r: 履修 | 履修科目[r] in 全履修可能科目[r.履修者] } fact 対称的な事前修得前提科目はない{ all c: カリキュラム | no disj p,p': 事前修得前提[c] | p.対象 = p'.前提 and p.前提 = p'.対象 } -- 前提を推移的に辿っていないことに注意 fact 学生が事前修得前提科目の対象科目を履修できるなら前提科目を全て修得している{ all g: G/学生 | all r: g.~履修者 | all k: 事前修得前提科目群[g.適用, 履修科目[r]] | some {s: g.~(成績 <: 学生) | 単位になる[s] and s.科目 = k } } -- 前提を推移的に辿っていないことに注意 fact 学生が事前履修前提科目の対称科目を履修できるなら前提科目を全て修得しているか履修している{ all g: G/学生 | all r: g.~履修者 | all k: 事前履修前提科目群[g.適用, 履修科目[r]] | some {s: g.~(成績 <: 学生) | 単位になる[s] and s.科目 = k } or some {r': g.~履修者 | r'.科目 = k } } -- セット科目の他の科目セットを辿っていないことに注意 fact 学生が科目セットの科目を履修したら他のセット科目も履修することになる{ all g: G/学生 | all r: g.~履修者 | セット科目[g.適用, 履修科目[r]] in g.~履修者.履修科目 } ``` ## 仕様および基本設計の正当性検証 上記モデルの満足すべき仕様を以下に示す. これらの検証により基本設計としてのモデルが正当であることを保証する. ```alloy assert 任意の成績の科目は適用カリキュラムの学則に含まれる{ all s: 成績 | s.科目 in 修得可能学則[s.学生].科目 } check 任意の成績の科目は適用カリキュラムの学則に含まれる assert 任意の成績のGPAは一意に決まる{ all s: 成績 | #GPA[s] = 1 } check 任意の成績のGPAは一意に決まる assert 同じ科目に対して単位認定可能な成績は一意に決まる{ no g: G/学生 | some disj s,s': g.~(成績 <: 学生) | s.科目 = s'.科目 and 単位になる[s] and 単位になる[s'] } check 同じ科目に対して単位認定可能な成績は一意に決まる assert 時間割があればその科目を履修できる学生はその授業を履修できる{ all j: T/授業 | some j.時間割 => { some {g: G/学生 | j.科目 in g.全履修可能科目} => some {g: G/学生 | j in g.全履修可能授業} } } check 時間割があればその科目を履修できる学生はその授業を履修できる ``` ```alloy pred 異なる学科の学生が同じ時間割を履修できる{ some disj r,r': 履修 | not 学部学科が同じ[r.履修者,r'.履修者] and 時間割が同じ[r,r'] } run 異なる学科の学生が同じ時間割を履修できる pred 異なるディプロマポリシーの学生が同じ時間割を履修できる{ some disj r,r': 履修 | not ディプロマポリシーが同じ[r.履修者,r'.履修者] and 時間割が同じ[r,r'] } run 異なるディプロマポリシーの学生が同じ時間割を履修できる pred 適用カリキュラムにない科目を履修できる{ some r: 履修 | 履修科目[r] not in 基本履修可能科目[r.履修者] } run 適用カリキュラムにない科目を履修できる pred 異なるカリキュラムの学生が同じ時間割を履修できる{ some disj r,r': 履修 | not カリキュラムが同じ[r.履修者,r'.履修者] and 時間割が同じ[r,r'] } run 異なるカリキュラムの学生が同じ時間割を履修できる pred 異なる学年の学生が同じ時間割を履修できる{ some disj r,r': 履修 | not 学年が同じ[r.履修者,r'.履修者] and 時間割が同じ[r,r'] } run 異なる学年の学生が同じ時間割を履修できる pred 時間割がなくても成績は作れる{ no t: T/時間割 | some s: 成績 | s.科目 = t.授業.科目 } run 時間割がなくても成績は作れる pred 履修がなくても成績は作れる{ no r: 履修 | some s: 成績 | s.学生 = r.履修者 and s.科目 = 履修科目[r] } run 履修がなくても成績は作れる pred 試験成績はなくても成績はつけられる{ no t: 試験成績 | some s: 成績 | s.学生 = t.学生 and s.科目 = 試験成績科目[t] } run 試験成績はなくても成績はつけられる pred 出欠は取らなくても成績はつけられる{ no a: 出席情報 | some s: 成績 | a.学生 = s.学生 and 出席情報科目[a] = s.科目 } run 出欠は取らなくても成績はつけられる pred 履修がなくても出欠はつけられる{ no r: 履修 | some a: 出席情報 | r.履修者 = a.学生 and 履修科目[r] = 出席情報科目[a] } run 履修がなくても出欠はつけられる pred 単独科目授業を履修できる{ some disj r,r': 履修 | 履修科目[r] = 履修科目[r'] and 履修時期[r] = 履修時期[r'] and 履修場所[r] = 履修場所[r'] and 履修曜時[r] = 履修曜時[r'] and 評価者[r] = 評価者[r'] } run 単独科目授業を履修できる pred 分割科目を履修できる{ some disj r,r': 履修 | 履修科目[r] = 履修科目[r'] and 履修時期[r] = 履修時期[r'] and 履修場所[r] != 履修場所[r'] and 評価者[r] != 評価者[r'] } run 分割科目を履修できる pred 一貫分割型複数担当科目を履修できる{ some disj r,r': 履修 | 履修科目[r] = 履修科目[r'] and 履修時期[r] = 履修時期[r'] and 評価者[r] = 評価者[r'] and #講師陣[r] > 1 and #講師陣[r'] > 1 } run 一貫分割型複数担当科目を履修できる pred 途中分割型複数担当科目を履修できる{ some disj r,r': 履修 | 履修科目[r] = 履修科目[r'] and 履修時期[r] = 履修時期[r'] and 履修場所[r] != 履修場所[r'] and some (履修場所[r] & 履修場所[r']) and 評価者[r] != 評価者[r'] and some (講師陣[r] & 講師陣[r']) } run 途中分割型複数担当科目を履修できる pred シリーズ科目を履修できる{ some disj r,r': 履修 | 履修科目[r] = 履修科目[r'] and 履修時期[r] = 履修時期[r'] and 履修場所[r] = 履修場所[r'] and 評価者[r] = 評価者[r'] and #講師陣[r] > 1 and #講師陣[r'] > 1 } run シリーズ科目を履修できる pred 学生は複数の履修ができる{ some s: G/学生 | #s.~履修者 > 1 } run 学生は複数の履修ができる pred 同じ科目の履修を複数持ち得る{ some g: G/学生 | some disj r,r': g.~履修者 | 履修科目[r] = 履修科目[r'] } run 同じ科目の履修を複数持ち得る pred 同じ科目の成績を複数持ち得る{ some g: G/学生 | some disj s,s': g.~(成績 <: 学生) | s.科目 = s'.科目 } run 同じ科目の成績を複数持ち得る pred 合併時間割に異なる科目の履修を含めることができる{ some j: T/時間割 | some disj r,r': 履修 | (r + r').履修時間割 in 合併時間割[j] and 履修科目[r] != 履修科目[r'] } run 合併時間割に異なる科目の履修を含めることができる pred 合併時間割に異なる科目の出席情報を含めることができる{ some j: T/時間割 | some disj a,a': 出席情報 | (a + a').時間割 in 合併時間割[j] and 出席情報科目[a] != 出席情報科目[a'] } run 合併時間割に異なる科目の出席情報を含めることができる pred 合併時間割に異なる科目の試験成績を含めることができる{ some j: T/時間割 | some disj t,t': 試験成績 | (t + t').時間割 in 合併時間割[j] and 試験成績科目[t] != 試験成績科目[t'] } run 合併時間割に異なる科目の試験成績を含めることができる pred 時間割に対して学生の履修申請を作ることができる{ some t: T/時間割 | some s: G/学生 | some r: 履修申請 | r.申請者 in s and r.申請時間割 in t } run 時間割に対して学生の履修申請を作ることができる pred 履修申請に対応する履修を作ることができる{ some r: 履修申請 | some x: 履修 | x.由来する in r } run 履修申請に対応する履修を作ることができる pred 抽選による履修登録ができる{ some t: T/時間割 | some s: G/学生 | some x: 履修 | let r = x.由来する | some r and r.申請者 in s and r.申請時間割 in t and x.履修者 in s and x.履修時間割 in t } run 抽選による履修登録ができる pred 履修申請のない履修を作ることができる{ some x: 履修 | no x.由来する } run 履修申請のない履修を作ることができる pred 事前修得前提科目が設定された科目を履修できる{ some r: 履修 | 履修科目[r] in 事前修得前提[r.履修者.適用].対象 } run 事前修得前提科目が設定された科目を履修できる pred 事前履修前提科目が設定された科目を履修できる{ some r: 履修 | 履修科目[r] in 事前履修前提[r.履修者.適用].対象 } run 事前履修前提科目が設定された科目を履修できる pred 科目セットの時間割を履修できる{ some r: 履修 | some 科目セット群[r.履修者.適用, 履修科目[r]] } run 科目セットの時間割を履修できる pred 履修が不可能な開講なし授業を作れる{ some j: T/授業 | 科目の履修は可能だが履修できない[j] } run 履修が不可能な開講なし授業を作れる ``` ## ユーティリティ ```alloy fun 評価者(r: 履修) : S/教員{ r.履修時間割.担当 } fun 講師陣(r: 履修) : set S/教員{ 講師陣[r.履修時間割] } fun 履修授業(r: 履修) : T/授業{ r.履修時間割.授業 } fun 履修科目(r: 履修) : Base/科目{ 履修授業[r].科目 } fun 履修場所(r: 履修) : set F/教室{ r.履修時間割.教室時間割 } fun 履修時期(r: 履修) : Base/年度 -> Base/期{ let t = r.履修時間割 | t.実施年度 -> t.実施期 } fun 履修曜時(r: 履修) : set Base/曜日時限 -> Base/週間隔{ let t = r.履修時間割 | t.曜時 -> t.週間隔区分 } fun 試験成績科目(t: 試験成績) : Base/科目{ t.時間割.授業.科目 } fun 出席情報科目(a: 出席情報) : Base/科目{ a.時間割.授業.科目 } fun GPA(s: 成績) : set GPA値{ {r : 学則 | r in 修得可能学則[s.学生] and r.科目 = s.科目}.評価基準.GPA[s.評価] } ``` ```alloy pred 時間割が同じ(r,r': 履修){ r.履修時間割 = r'.履修時間割 } pred 単位になる(s: 成績){ some r: 修得可能学則[s.学生] | s.科目 = r.科目 and s.評価 in r.評価基準.単位認定評価 } pred 科目の履修は可能だが履修できない(j: T/授業){ some {g : G/学生 | j.科目 in g.全履修可能科目} and no {g: G/学生 | j in g.全履修可能授業} } ```
Java
UTF-8
4,196
2.171875
2
[]
no_license
package com.xunhe.javaweb.controller; import java.io.UnsupportedEncodingException; import java.text.SimpleDateFormat; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.alibaba.fastjson.JSON; import com.xunhe.javaweb.po.AccountTable; import com.xunhe.javaweb.service.AccountService; @RestController public class AccountController { //定义字段 @Autowired private AccountService accountService; //insert @RequestMapping("/accountInsert") public String calendarInsert(HttpServletRequest req,HttpServletResponse resp) { try { req.setCharacterEncoding("utf8"); resp.setCharacterEncoding("utf-8"); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //接受值 String userId=req.getParameter("userId"); String shouruFlag=req.getParameter("shouruFlag"); String item=req.getParameter("item"); String sum=req.getParameter("sum"); String useDate=req.getParameter("useDate"); String beiKao=req.getParameter("beiKao"); //处理 AccountTable accountTable = null; try { accountTable = new AccountTable(userId, Integer.parseInt(shouruFlag),item, sum, new SimpleDateFormat("yyyy-MM-dd hh:mm:ss") .parse(useDate), beiKao); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //返回值 return String.valueOf(accountService.accountInsert(accountTable)); }; //SelectAll @RequestMapping("/accountSelectAll") public String calendarSelectAll() { List<AccountTable> listCalendar=accountService.accountSelectAll(); if (listCalendar!=null) { return JSON.toJSONString(listCalendar); } else { return null; } } //delete @RequestMapping("/accountDelete") public String accountDelete(HttpServletRequest req, HttpServletResponse resp) { try { req.setCharacterEncoding("utf8"); resp.setCharacterEncoding("utf-8"); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //接收值 String id = req.getParameter("id"); // 处理 String strResult = String.valueOf(accountService.accountDelete(Integer.valueOf(id))); // 返回值 return strResult; } //update @RequestMapping("/accountUpdate") public String accountUpdate(HttpServletRequest req, HttpServletResponse resp) { try { req.setCharacterEncoding("utf8"); resp.setCharacterEncoding("utf-8"); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //接收值 String id=req.getParameter("id"); String shouruFlag = req.getParameter("shouruFlag"); String sum = req.getParameter("sum"); String item = req.getParameter("item"); String useDate = req.getParameter("useDate"); //处理 AccountTable accountTable = new AccountTable(); try { accountTable.setId(Integer.parseInt(id)); accountTable.setShouruFlag(Integer.parseInt(shouruFlag)); accountTable.setItem(item); accountTable.setSum(sum); accountTable.setUseDate(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss") .parse(useDate)); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // 处理 String strResult = String.valueOf(accountService.accountUpdate(accountTable)); // 返回值 return strResult; } //selectOne @RequestMapping("/accountSelectGroup") public String accountSelectGroup(HttpServletRequest req, HttpServletResponse resp) { try { req.setCharacterEncoding("utf8"); resp.setCharacterEncoding("utf-8"); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String userId = req.getParameter("userId"); String queryDate = req.getParameter("queryDate"); AccountTable accountTable = new AccountTable(); accountTable = accountService.accountSelectGroup(userId, queryDate); if (accountTable!=null) { return JSON.toJSONString(accountTable); } else { return null; } } }
Java
UTF-8
1,010
3.609375
4
[]
no_license
package OurStudyGroup; public class OddEven1 { public static void main(String[] args) { //write a program that can print all the ODD/Even numbers between 0 ~ 100 that can be divisible by 3 & 5 for(int i=1; i<=100;i+=2){ if (i%5==0 && i%3==0){ System.out.print(i+" "); } } System.out.println(); for(int i=0;i<=100; i+=2){ if(i%3==0 && i%5==0){ System.out.print(i+" "); } } System.out.println(); System.out.println("============================================"); for (int i=0;i<=100;i++){ if(i%2!=0){ if(i%5==0 && i%3==0){ System.out.print(i+" "); } } } System.out.println(); for(int i =0; i<=100; i++){ if(i%2==0){ if(i%15==0){ System.out.print(i+" "); } } } } }
JavaScript
UTF-8
693
4.375
4
[]
no_license
// Problem: // Given a non-negative integer num, return the number of steps to reduce it to zero. // If the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it. // Solution: var numberOfSteps = function (num) { let steps = 0 while (num > 0) { // use a ternary to check if the current num is even num % 2 == 0 // if the num is even, increase our steps counter and divide num by two ? (++steps) && (num /= 2) // if the num is odd, increase our steps counter and subtract one from num : (++steps) && (num -= 1) } return steps }; const num = 14; console.log(numberOfSteps(num))
Java
UTF-8
616
2.875
3
[ "MIT" ]
permissive
package net.jacobpeterson.abstracts.enums; /** * {@link SortDirection} defines enums for directional sorting. */ public enum SortDirection implements APIName { /** The Ascending {@link SortDirection}. */ ASCENDING("asc"), /** The Descending {@link SortDirection}. */ DESCENDING("desc"); /** The API name. */ String apiName; /** * Instantiates a new {@link SortDirection}. * * @param apiName the api name */ SortDirection(String apiName) { this.apiName = apiName; } @Override public String getAPIName() { return apiName; } }
C#
UTF-8
2,221
2.765625
3
[ "CC-BY-4.0" ]
permissive
using System; using System.Diagnostics; using System.Net; using System.IO; using System.Windows.Forms; namespace CRYENGINE_ImportHub { class CUpdateNotification { const string UPDATE_CHECK_URL = "http://www.guillaume-puyal.com/systems/CEI_check_update.php"; private string m_final_url; private string m_newUpdateVersion; private string m_newUpdateUrl; public CUpdateNotification(string version) { m_final_url = UPDATE_CHECK_URL + "?v=" + version; Framework.Log("Beginning update check"); GetRequest(); } private void GetRequest() { WebRequest wrGETURL = WebRequest.Create(m_final_url); wrGETURL.Proxy = WebRequest.GetSystemWebProxy(); wrGETURL.Timeout = 6000; try { Stream objStream = wrGETURL.GetResponse().GetResponseStream(); StreamReader objReader = new StreamReader(objStream); string returnValues = objReader.ReadLine(); objReader.Close(); if (returnValues != null && returnValues != "") { Framework.Log("New update available!"); GetUpdateInfos(returnValues); } else Framework.Log("No update available"); } catch (Exception ex) { Framework.Log("ERROR: Unable to access the online update system"); } } private void GetUpdateInfos(string getValues) { string[] finalValues = getValues.Split(';'); m_newUpdateVersion = finalValues[0]; m_newUpdateUrl = finalValues[1]; ShowDialog(); } private void ShowDialog() { DialogResult dialogResult = MessageBox.Show("Do you want to access to the download page of the " + m_newUpdateVersion + " update?", "New update available!", MessageBoxButtons.YesNo, MessageBoxIcon.Information); if (dialogResult == DialogResult.Yes) { Process.Start(m_newUpdateUrl); } } } }
Java
UTF-8
181
1.890625
2
[]
no_license
package com.coderzoe.entity; /** * @author yhs * @date 2020/5/31 17:04 * @description */ public class Cat { public void bark(){ System.out.println("miao"); } }
Python
UTF-8
945
2.671875
3
[]
no_license
import io import sys import random import argparse import matplotlib import datetime as dt import itertools as it def get_key(d): # group by 1 minute d = dt.datetime.fromtimestamp(float(d)) k = d - dt.timedelta(seconds=d.second % 60) return dt.datetime(k.year, k.month, k.day, k.hour, k.minute, k.second) def normizer(fin,fout, factor): data = open(fin, "r").readlines() g = it.groupby(sorted([i.split()[1].strip() for i in data]), key=get_key) timestamps = [] for key, items in g: _i = list(items) ch = int(len(_i)*factor) timestamps += random.sample(_i,ch ) print(len(timestamps)) lines = [ line for line in data if line.split()[1].strip() in timestamps ] with open(fout, "w") as f: for line in lines: f.write(line) if __name__=="__main__": fin = sys.argv[1] fout = sys.argv[2] factor = float(sys.argv[3]) normizer(fin,fout,factor)
C++
UTF-8
410
2.625
3
[]
no_license
#ifndef StandardJoint_h #define StandardJoint_h #include "Arduino.h" #include "Servo.h" #include "Adafruit_PWMServoDriver.h" class StandardJoint { public: StandardJoint(int pin); void setTarget(int target); void updateJoint(); bool reachedTarget(); private: Servo _servo; int _target; int _currentPos; int _step = 5; int _nextPos; bool _targetReached; }; #endif
Markdown
UTF-8
5,930
2.609375
3
[]
no_license
# Maximo API for Service Requests Below are some details on how to create/update a Maximo Service Request w/attachment via Maximo's RESTful Api. In this situation, the company has built a proxy application that relay the request between the internet and intranet. This proxy application is a Azure Function app hosting in Azure. Was able to use this application locally for testing. ## CREATE Service Request ========================= POST http://localhost:7071/api/mxapisr?lean=1 Accept: application/json, text/plain, */* Content-Type: application/json maxauth: <BASE64-token> properties: * Body: ```json { "description": "Field Issue Reporter", "description_longdescription": "<div>An issue has been filed via Field Issue Reporter. Below are the details of that report.</div><br /><div><b>Longitude</b>: -80.0000</div><div><b>Latitude:</b> 40.000</div><div><b>Pole Number:</b> 1234M</div><br /><div><b>Is there a vegetation issue?</b> No</div><div><b>Is something broken or leaning past 30 degrees?</b> No</div><div><b>Are there signs of leaking?</b> No</div><div><b>Is anything external contacting a DLC asset?</b> No</div><div><b>High or Low Priority?</b> No</div><div><b>Comments:</b> no comment at this time</div>", "classstructureid": 1479, "reportedpriority": 2, "reportedby": "", "status": "NEW" } ``` > NOTE! including `"ticketid": "0",` in the JSON body will result in a new service request. But the ticket id is set to "0", which is difficult to search against. ### Attachments can be included along with the initial creation. > NOTE!: the `documentdata` must be a base64 encoded document Body: ```json { "description": "Field Issue Reporter w/ Attachment", "description_longdescription": "<div>An issue has been filed via Field Issue Reporter. Below are the details of that report.</div><br /><div><b>Longitude</b>: -80.0000</div><div><b>Latitude:</b> 40.000</div><div><b>Pole Number:</b> 1234M</div><br /><div><b>Is there a vegetation issue?</b> No</div><div><b>Is something broken or leaning past 30 degrees?</b> No</div><div><b>Are there signs of leaking?</b> No</div><div><b>Is anything external contacting a DLC asset?</b> No</div><div><b>High or Low Priority?</b> No</div><div><b>Comments:</b> no comment at this time</div>", "classstructureid": 1479, "reportedpriority": 2, "reportedby": "", "status": "NEW", "doclinks":[ { "urltype":"FILE", "documentdata":"aGV5IGhvdyBhcmUgeW91", "doctype":"Attachments", "urlname":"greetingsabcd.txt" }, { "urltype":"FILE", "documentdata":"aGV5IGhvdyBpcyB0aGF0", "doctype":"Attachments", "urlname":"howisthatfor.txt" } ] } ``` ### UPDATE Service Request ========================== POST http://localhost:7071/api/mxapisr/64462?lean=1 Accept: application/json, text/plain, */* Content-Type: application/json maxauth: <BASE64-token> properties: * x-method-override: PATCH Body: ```json { "ticketuid": 64462, "ticketid": "23415", "description": "Field Issue Reporter", "description_longdescription": "<div>An issue has been filed via Field Issue Reporter. Below are the details of that report.</div><br /><div><b>Longitude</b>: -80.0000</div><div><b>Latitude:</b> 40.000</div><div><b>Pole Number:</b> 1234M</div><br /><div><b>Is there a vegetation issue?</b> No</div><div><b>Is something broken or leaning past 30 degrees?</b> No</div><div><b>Are there signs of leaking?</b> No</div><div><b>Is anything external contacting a DLC asset?</b> No</div><div><b>High or Low Priority?</b> No</div><div><b>Comments:</b> no comment at this time</div>", "classstructureid": 1479, "reportedpriority": 2, "reportedby": "", "status": "NEW" } ``` > !! Take notice to the URL id that matches the `ticketuid`. The `ticketuid` is NOT require within the JSON body to update the record. ## Other Information status = [NEW, PENDING, INPROG, QUEUED, REJECTED, RESOLVED, CLOSED, CANCELLED] reportedpriority (1-4) = [Low, Medium, High, Urgent] reportedby = this is a user from the 'Person' table, not 'User' table * Swagger * https://{server}:{port}/maximo/api.html * https://{server}:{port}/maximo/oslc/oas?includeaction=1 * JSON Schemas * https://{server}:{port}/maximo/oslc/jsonschemas/%OBJECT_STRUCTURE% * https://{server}:{port}/maximo/oslc/jsonschemas/MXAPISR * (Maybe) Userful Links https://www.ibm.com/docs/en/mam/7.6.1.2?topic=structure-creating-object-structures https://www.ibm.com/docs/en/mam/7.6.0?topic=ra-rest-api-framework https://developer.ibm.com/components/maximo/ https://www.ibm.com/mysupport/s/forumshome?language=en_US https://www.ibm.com/docs/en/control-desk/7.6.1?topic=desk-service-requests https://www.ibm.com/docs/en/control-desk/7.6.1?topic=requests-creating-service-request ### ```html <HTML> <form name="input" action="http://SERVER/maxrest/rest/os/DOCLINK?_lid=maxadmin&_lpwd=maxadmin" method="POST"> <p> ADDINFO <input name="ADDINFO" value="1" type="text"> <p/> <p> DOCUMENT <input name="DOCUMENT" value="REST FILE " type="text"> <p/> <p> DESCRIPTION <input name="DESCRIPTION" value="TESTING REST DOC 2" type="text"> <p/> <p> OWNERTABLE <input name="OWNERTABLE" value="WORKORDER" type="text"> <p/> <p> OWNERID <input name="OWNERID" value="1662" type="text"> <p/> <p> DOCTYPE <input name="DOCTYPE" value="Attachments" type="text"> <p/> <p> NEWURLNAME <input name="NEWURLNAME" value="www.ibm.com" type="text"> <p/> <p> URLNAME <input name="URLNAME" value="C:\doclinks\attachments\MXPO_Attachment.txt" type="text"> <p/> <p> URLTYPE <input name="URLTYPE" value="FILE" type="text"> <p/> <p> DOCUMENTDATA <input name="DOCUMENTDATA" value="PT09PT09PT09PT09PT09PT09PT09PT0NCkludGVncmF0aW9uIEZyYW1ld29yaw0KPT09PT09PT09PT09PT09PT09PT09PT0NCg0KUHVyY2hhc2UgT3JkZXIgYXR0YWNobWVudCBURVNU" type="text"> <p/> <input type="submit" value="Submit"> </form> </HTML> ```
Markdown
UTF-8
2,445
2.828125
3
[ "MIT" ]
permissive
# MHacks ## Preview <a href="https://gmoraitis.github.io/MHacks_Filtering_A_Drum_Loop/" target="_blank">![Filtering a Drum Loop](img/filter_demo.png) </a> ## Usage ### Basic Usage After downloading, simply edit the HTML and CSS files included with the template in your favorite text editor to make changes. These are the only files you need to worry about, you can ignore everything else! To preview the changes you make to the code, you can open the `index.html` file in your web browser. ### Advanced Usage After installation, run `npm install` and then run `npm start` which will open up a preview of the template in your default browser, watch for changes to core template files, and live reload the browser when changes are saved. You can view the `gulpfile.js` to see which tasks are included with the dev environment. You must have npm and Gulp installed globally on your machine in order to use these features. ## About This project is my submission for the MHacks13 beta Hackathon. I decided to make a simple example with an educational goal to showcase what a filter in the digital domain can too. You can read more about digital filters in <a href="https://en.wikipedia.org/wiki/Digital_filter#:~:text=In%20signal%20processing%2C%20a%20digital,certain%20aspects%20of%20that%20signal." target="_blank">Wikipedia</a>. I used a <a href="https://startbootstrap.com/templates/scrolling-nav/" target="_blank">Bootstrap template</a> for the UI and <a href="https://tonejs.github.io/" target="_blank">Tone.js</a> to be able to work with the filters. All of the free templates and themes on Start Bootstrap are released under the MIT license, which means you can use them for any purpose, even for commercial projects. * <https://startbootstrap.com> * <https://twitter.com/SBootstrap> Start Bootstrap was created by and is maintained by **[David Miller](http://davidmiller.io/)**. * <http://davidmiller.io> * <https://twitter.com/davidmillerskt> * <https://github.com/davidtmiller> Start Bootstrap is based on the [Bootstrap](https://getbootstrap.com/) framework created by [Mark Otto](https://twitter.com/mdo) and [Jacob Thorton](https://twitter.com/fat). ## Copyright and License Copyright 2013-2020 Start Bootstrap LLC. Code released under the [MIT](https://github.com/StartBootstrap/startbootstrap-scrolling-nav/blob/gh-pages/LICENSE) license.
Java
UTF-8
2,430
2.296875
2
[]
no_license
package com.example.seconlifeps; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class DBHelper extends SQLiteOpenHelper { final static String DBName = "SheltersDB"; final static String TBName_User = "Users"; final static String TBName_UserPayment = "UserPayment"; final static String TBName_Business = "Business"; final static String TBName_Reviews = "Reviews"; public DBHelper(Context context) { super(context, DBName, null, 1); SQLiteDatabase db = this.getWritableDatabase(); } @Override public void onCreate(SQLiteDatabase db) { try { String sql = " CREATE TABLE " + TBName_User + "(us_id INTEGER PRIMARY KEY AUTOINCREMENT,\n" + "us_email VARCHAR, us_password VARCHAR, us_firstName VARCHAR, us_lastName VARCHAR, us_dob DATE , \n" + "us_image BLOB, us_latitude VARCHAR, us_longitude VARCHAR, us_lastLogin DATE)"; db.execSQL(sql); sql = " CREATE TABLE " + TBName_UserPayment + "(up_id INTEGER PRIMARY KEY AUTOINCREMENT,\n" + "us_id INTEGER, up_holderName VARCHAR, up_cardNumber VARCHAR, up_ccv VARCHAR, up_expire VARCHAR, up_default BOOLEAN )"; db.execSQL(sql); sql = " CREATE TABLE " + TBName_Business + "(bu_id INTEGER PRIMARY KEY AUTOINCREMENT,\n" + "bu_name VARCHAR, bu_address VARCHAR, bu_lastName VARCHAR, bu_latitude VARCHAR, bu_longitude VARCHAR, bu_contactNo VARCHAR,\n" + "bu_email VARCHAR,\n" + "bu_description,\n" + "bu_price DECIMAL , \n" + "bu_visitDays VARCHAR,\n" + "bu_visitHours VARCHAR)"; db.execSQL(sql); sql = " CREATE TABLE " + TBName_Business + "(rv_id INTEGER PRIMARY KEY AUTOINCREMENT,\n" + "bu_id INTEGER, us_id INTEGER, rv_date DATE, rv_description VARCHAR, rv_stars INTEGER )"; db.execSQL(sql); } catch (Exception e) { Log.e("DBHelper" , e.getMessage()); } } @Override public void onUpgrade(SQLiteDatabase db, int i, int i1) { try { db.execSQL("DROP TABLE IF EXISTS " + TBName_User); onCreate(db); } catch (Exception e) { Log.e("DBHelper" , e.getMessage()); } } }
C
UTF-8
1,722
2.59375
3
[ "MIT" ]
permissive
#include "usb_dev.h" #include "usb_xinput.h" #include "core_pins.h" // for yield(), millis() #include <string.h> // for memcpy() //#include "HardwareSerial.h" #ifdef XINPUT_INTERFACE // defined by usb_dev.h -> usb_desc.h #if F_CPU >= 20000000 //Function receives packets from the RX endpoint //We will use this for receiving LED commands int usb_xinput_recv(void *buffer, uint32_t timeout) { usb_packet_t *rx_packet; uint32_t begin = millis(); while (1) { if (!usb_configuration) return -1; rx_packet = usb_rx(XINPUT_RX_ENDPOINT); if (rx_packet) break; if (millis() - begin > timeout || !timeout) return 0; yield(); } memcpy(buffer, rx_packet->buf, XINPUT_RX_SIZE); usb_free(rx_packet); return XINPUT_RX_SIZE; } //Function to check if packets are available //to be received on the RX endpoint int usb_xinput_available(void) { uint32_t count; if (!usb_configuration) return 0; count = usb_rx_byte_count(XINPUT_RX_ENDPOINT); return count; } // Maximum number of transmit packets to queue so we don't starve other endpoints for memory #define TX_PACKET_LIMIT 3 //Function used to send packets out of the TX endpoint //This is used to send button reports int usb_xinput_send(const void *buffer, uint32_t timeout) { usb_packet_t *tx_packet; uint32_t begin = millis(); while (1) { if (!usb_configuration) return -1; if (usb_tx_packet_count(XINPUT_TX_ENDPOINT) < TX_PACKET_LIMIT) { tx_packet = usb_malloc(); if (tx_packet) break; } if (millis() - begin > timeout) return 0; yield(); } memcpy(tx_packet->buf, buffer, XINPUT_TX_SIZE); tx_packet->len = XINPUT_TX_SIZE; usb_tx(XINPUT_TX_ENDPOINT, tx_packet); return XINPUT_TX_SIZE; } #endif // F_CPU #endif // XINPUT_INTERFACE
C
UTF-8
155
3.203125
3
[]
no_license
# include <stdio.h> void main() { int i, sum =0; for(i=0;i<=20;i++) { if( i % 2 != 0 && i % 3 != 0) { sum += i; } } printf("%d", sum);
Markdown
UTF-8
2,992
3.171875
3
[]
no_license
# Firmware Code This folder holds all of the code used throughout this project. This code is primarily used for controlling the microcontroller used on the custom PCB, the ESP32. The code was done in C++ via the Arduino IDE. Within the folder, there also exists the flow diagram for the NodeRed server that handles the user web interface. Individual pieces of code are present in this folder, which was how they were developed. After the individual pieces of code were able to successfully work on their own, they were adapted into a single .ino file to be uploaded to the ESP32, called ESP_Firmware. ## Functions ### void check_time() Helper function whose main job is to check the timers and current time. When the current time minus the time each timer started goes beyond the set time limit, it calls a separate function to turn off the plugs and reset all the values. This could be improved by consolidating the functions (a previous revision needed 3 seperate functions this current revision does not) so only one "timer complete" function is called with a specific argument for what plug to turn off (Ex. Timer_complete(1) -> turn off plug one). Inputs: None Outputs: none ### String get_time(int time_to, int plug) Helper function that will convert the time data variables (which are stored as raw millisecond values) to human-readable strings. In this case it will take in the time at which the plug timer started (time_to) and how long the plug is supposed to remain on (plug). These values are used along with the current time (millis) to find exactly how long it's been since the plug timer started. This value is then divided into hours, minutes and seconds and then casted into a string with the format HH:MM:SS. This function is kinda clunky because it uses strings and not char arrays. Since the format is known (HH:MM:SS) it would be better to just have a 8 char static array and then populate it with values as we calculate them. Inputs: Time that the timer started at (time_to), how long the timer is on for (plug) Outputs: String formatted as HH:MM:SS (int values) ### void timer_complete_X() There are 3 of these functions for each plug. All it does is turn "off" the plug (by setting the relay high) and resets the time the plug is supposed to be on to 0. This is kind of a stupid way to do this and it should definitely be improved. Consolidating it into another function and not having 3 seperate functions to do a very simple task would be a good start. Inputs: None Outputs: None ### setup_wifi() This function will attempt to connect to the specified wifi SSID with the given password. IT is a blocking function and will hold up all other operations if it cannot connect to the givien SSID. This should be fixed so that it is not blocking and will just retry the connection every X seconds when it can't connect. Inputs: None Outputs: None ### start_timers()
Markdown
UTF-8
3,587
3.4375
3
[]
no_license
# read underscore3 ``` var _ = function(obj){ if(obj instanceof _) return obj; if(!(this instanceof _)) return new _(obj); this._wrapped = obj; } ``` 这里是创建了 underscore 对象.这个函数的目的其实就是为了创建 underscore 对象, 如果在 new 命令的时候有对象传进来, 那么就将这个对象传给新建对象的 _wrapped 属性存储起来. ``` if(typeof exports != 'undefined' && !exports.nodeType) { if(typeof module != 'undefined' && !module.nodeType && module.exports) { exports = module.exports = _; } exports._ = _; } else { root._ = _; } ``` 这段代码如何理解呢? 这个是前端与 node.js 通用的模块封装模式, 我们知道 exports 和 module.exports 是 node 模块化的显著标志, 第一个先判断 exports 是否存在, 还有就是判断 exports 变量是否有 nodeType 属性, 如果有, 说明 exports 变量是一个 html 元素, 所以不使用 node 方式模块加载, 同理 module 变量也是这样.这里不再细讲 exports 和 module.exports 的区别, 简单总结就是 exports 看作是 module.exports 的一个快照. ``` var optimizeCb = function(func, context, argCount) { if (context === void 0) return func; switch (argCount) { case 1: return function(value) { return func.call(context, value); }; // The 2-parameter case has been omitted only because no current consumers // made use of it. case null: case 3: return function(value, index, collection) { return func.call(context, value, index, collection); }; case 4: return function(accumulator, value, index, collection) { return func.call(context, accumulator, value, index, collection); }; } return function() { return func.apply(context, arguments); }; }; ``` 这个函数是什么意思?从整体上看并没有太大的意思,我们知道 this 的指向是动态的,所以在实际开发中肯定免不了对函数的 this 值进行硬绑定的做法,但是 bind 函数会有兼容性问题, 所以会倾向于使用 call 方法和 apply 方法,这两个原生函数在使用的时候区别就在于 call 后面是可以跟随 n 的参数,而 apply 后面是跟随数组形式的参数的, 那为什么 underscore 源码需要将这两种方法区分呢?可以看到 optimizeCb 函数会将传递参数少于或等于 4 个的采用 call 方法来绑定 this, 而对于多于 4 个参数的方法则会采用 apply 方法来进行绑定,其实这是代码性能优化的手段,apply 方法在执行的时候其实是比 call 方法要慢得多, apply 方法在执行的时候需要对传进来的参数数组 进行深拷贝:apply 内部执行伪代码 ``` argList = []; len = argArray.length; index = 0; while(index < len){ indexName = index.toString(); argList.push(argArray[indexName]); index = index + 1; } return func(argList); ``` 此外,apply 内部还需要对传进来的参数数组进行判断到底是不是一个数组对象,是否是 null 或者 undefined,而对于 call 则简单许多: ``` argList = []; if(argCount > 1) { while(arg) { argList.push(arg); } } return func(argList); ``` 总的来说就是 apply 不管在什么时候,对参数的循环遍历都是必定执行的,而对于 call 来说则是当参数数目大于 1 的时候才会执行循环遍历,而且 apply 比 call 多了一些对参数的检查, 所以 call 比 apply 快,基于这一点,underscore 使用 optimize 函数优化需要硬绑定的代码性能。
Java
UTF-8
10,997
1.875
2
[]
no_license
import android.view.View; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public final class xe extends zc { ArrayList a = new ArrayList(); ArrayList b = new ArrayList(); ArrayList c = new ArrayList(); ArrayList d = new ArrayList(); ArrayList e = new ArrayList(); ArrayList f = new ArrayList(); ArrayList g = new ArrayList(); private ArrayList n = new ArrayList(); private ArrayList o = new ArrayList(); private ArrayList p = new ArrayList(); private ArrayList q = new ArrayList(); private static void a(List paramList) { for (int i = paramList.size() - 1; i >= 0; i--) { gt.o(((zr)paramList.get(i)).a).a(); } } private void a(List paramList, zr paramzr) { for (int i = paramList.size() - 1; i >= 0; i--) { xn localxn = (xn)paramList.get(i); if ((a(localxn, paramzr)) && (localxn.a == null) && (localxn.b == null)) { paramList.remove(localxn); } } } private void a(xn paramxn) { if (paramxn.a != null) { a(paramxn, paramxn.a); } if (paramxn.b != null) { a(paramxn, paramxn.b); } } private boolean a(xn paramxn, zr paramzr) { boolean bool2 = false; boolean bool1 = false; if (paramxn.b == paramzr) { paramxn.b = null; } for (;;) { gt.c(paramzr.a, 1.0F); gt.a(paramzr.a, 0.0F); gt.b(paramzr.a, 0.0F); a(paramzr, bool1); bool1 = true; do { return bool1; bool1 = bool2; } while (paramxn.a != paramzr); paramxn.a = null; bool1 = true; } } public final void a() { int i; int j; label26: int k; label39: int m; if (!this.n.isEmpty()) { i = 1; if (this.p.isEmpty()) { break label79; } j = 1; if (this.q.isEmpty()) { break label85; } k = 1; if (this.o.isEmpty()) { break label91; } m = 1; label52: if ((i != 0) || (j != 0) || (m != 0) || (k != 0)) { break label97; } } for (;;) { return; i = 0; break; label79: j = 0; break label26; label85: k = 0; break label39; label91: m = 0; break label52; label97: Iterator localIterator = this.n.iterator(); Object localObject2; Object localObject1; while (localIterator.hasNext()) { localObject2 = (zr)localIterator.next(); localObject1 = gt.o(((zr)localObject2).a); this.f.add(localObject2); ((ih)localObject1).a(this.j).a(0.0F).a(new xi(this, (zr)localObject2, (ih)localObject1)).b(); } this.n.clear(); label254: label329: long l1; label403: long l2; if (j != 0) { localObject1 = new ArrayList(); ((ArrayList)localObject1).addAll(this.p); this.b.add(localObject1); this.p.clear(); localObject2 = new xf(this, (ArrayList)localObject1); if (i != 0) { gt.a(((xo)((ArrayList)localObject1).get(0)).a.a, (Runnable)localObject2, this.j); } } else { if (k != 0) { localObject2 = new ArrayList(); ((ArrayList)localObject2).addAll(this.q); this.c.add(localObject2); this.q.clear(); localObject1 = new xg(this, (ArrayList)localObject2); if (i == 0) { break label466; } gt.a(((xn)((ArrayList)localObject2).get(0)).a.a, (Runnable)localObject1, this.j); } if (m == 0) { break label473; } localObject1 = new ArrayList(); ((ArrayList)localObject1).addAll(this.o); this.a.add(localObject1); this.o.clear(); localObject2 = new xh(this, (ArrayList)localObject1); if ((i == 0) && (j == 0) && (k == 0)) { break label493; } if (i == 0) { break label475; } l1 = this.j; if (j == 0) { break label481; } l2 = this.k; label414: if (k == 0) { break label487; } } label466: label473: label475: label481: label487: for (long l3 = this.l;; l3 = 0L) { l2 = Math.max(l2, l3); gt.a(((zr)((ArrayList)localObject1).get(0)).a, (Runnable)localObject2, l1 + l2); break; ((Runnable)localObject2).run(); break label254; ((Runnable)localObject1).run(); break label329; break; l1 = 0L; break label403; l2 = 0L; break label414; } label493: ((Runnable)localObject2).run(); } } public final boolean a(zr paramzr) { c(paramzr); this.n.add(paramzr); return true; } public final boolean a(zr paramzr, int paramInt1, int paramInt2, int paramInt3, int paramInt4) { View localView = paramzr.a; paramInt1 = (int)(paramInt1 + gt.k(paramzr.a)); int j = (int)(paramInt2 + gt.l(paramzr.a)); c(paramzr); int i = paramInt3 - paramInt1; paramInt2 = paramInt4 - j; if ((i == 0) && (paramInt2 == 0)) { e(paramzr); } for (boolean bool = false;; bool = true) { return bool; if (i != 0) { gt.a(localView, -i); } if (paramInt2 != 0) { gt.b(localView, -paramInt2); } this.p.add(new xo(paramzr, paramInt1, j, paramInt3, paramInt4)); } } public final boolean a(zr paramzr1, zr paramzr2, int paramInt1, int paramInt2, int paramInt3, int paramInt4) { float f3 = gt.k(paramzr1.a); float f1 = gt.l(paramzr1.a); float f2 = gt.f(paramzr1.a); c(paramzr1); int i = (int)(paramInt3 - paramInt1 - f3); int j = (int)(paramInt4 - paramInt2 - f1); gt.a(paramzr1.a, f3); gt.b(paramzr1.a, f1); gt.c(paramzr1.a, f2); if ((paramzr2 != null) && (paramzr2.a != null)) { c(paramzr2); gt.a(paramzr2.a, -i); gt.b(paramzr2.a, -j); gt.c(paramzr2.a, 0.0F); } this.q.add(new xn(paramzr1, paramzr2, paramInt1, paramInt2, paramInt3, paramInt4)); return true; } public final boolean b() { if ((!this.o.isEmpty()) || (!this.q.isEmpty()) || (!this.p.isEmpty()) || (!this.n.isEmpty()) || (!this.e.isEmpty()) || (!this.f.isEmpty()) || (!this.d.isEmpty()) || (!this.g.isEmpty()) || (!this.b.isEmpty()) || (!this.a.isEmpty()) || (!this.c.isEmpty())) {} for (boolean bool = true;; bool = false) { return bool; } } public final boolean b(zr paramzr) { c(paramzr); gt.c(paramzr.a, 0.0F); this.o.add(paramzr); return true; } void c() { if (!b()) { e(); } } public final void c(zr paramzr) { View localView = paramzr.a; gt.o(localView).a(); for (int i = this.p.size() - 1; i >= 0; i--) { if (((xo)this.p.get(i)).a == paramzr) { gt.b(localView, 0.0F); gt.a(localView, 0.0F); e(paramzr); this.p.remove(i); } } a(this.q, paramzr); if (this.n.remove(paramzr)) { gt.c(localView, 1.0F); d(paramzr); } if (this.o.remove(paramzr)) { gt.c(localView, 1.0F); f(paramzr); } ArrayList localArrayList; for (i = this.c.size() - 1; i >= 0; i--) { localArrayList = (ArrayList)this.c.get(i); a(localArrayList, paramzr); if (localArrayList.isEmpty()) { this.c.remove(i); } } i = this.b.size() - 1; if (i >= 0) { localArrayList = (ArrayList)this.b.get(i); for (int j = localArrayList.size() - 1;; j--) { if (j >= 0) { if (((xo)localArrayList.get(j)).a != paramzr) { continue; } gt.b(localView, 0.0F); gt.a(localView, 0.0F); e(paramzr); localArrayList.remove(j); if (localArrayList.isEmpty()) { this.b.remove(i); } } i--; break; } } for (i = this.a.size() - 1; i >= 0; i--) { localArrayList = (ArrayList)this.a.get(i); if (localArrayList.remove(paramzr)) { gt.c(localView, 1.0F); f(paramzr); if (localArrayList.isEmpty()) { this.a.remove(i); } } } this.f.remove(paramzr); this.d.remove(paramzr); this.g.remove(paramzr); this.e.remove(paramzr); c(); } public final void d() { Object localObject1; Object localObject2; for (int i = this.p.size() - 1; i >= 0; i--) { localObject1 = (xo)this.p.get(i); localObject2 = ((xo)localObject1).a.a; gt.b((View)localObject2, 0.0F); gt.a((View)localObject2, 0.0F); e(((xo)localObject1).a); this.p.remove(i); } for (i = this.n.size() - 1; i >= 0; i--) { d((zr)this.n.get(i)); this.n.remove(i); } for (i = this.o.size() - 1; i >= 0; i--) { localObject1 = (zr)this.o.get(i); gt.c(((zr)localObject1).a, 1.0F); f((zr)localObject1); this.o.remove(i); } for (i = this.q.size() - 1; i >= 0; i--) { a((xn)this.q.get(i)); } this.q.clear(); if (!b()) {} for (;;) { return; int j; for (i = this.b.size() - 1; i >= 0; i--) { localObject2 = (ArrayList)this.b.get(i); for (j = ((ArrayList)localObject2).size() - 1; j >= 0; j--) { localObject1 = (xo)((ArrayList)localObject2).get(j); View localView = ((xo)localObject1).a.a; gt.b(localView, 0.0F); gt.a(localView, 0.0F); e(((xo)localObject1).a); ((ArrayList)localObject2).remove(j); if (((ArrayList)localObject2).isEmpty()) { this.b.remove(localObject2); } } } for (i = this.a.size() - 1; i >= 0; i--) { localObject1 = (ArrayList)this.a.get(i); for (j = ((ArrayList)localObject1).size() - 1; j >= 0; j--) { localObject2 = (zr)((ArrayList)localObject1).get(j); gt.c(((zr)localObject2).a, 1.0F); f((zr)localObject2); ((ArrayList)localObject1).remove(j); if (((ArrayList)localObject1).isEmpty()) { this.a.remove(localObject1); } } } for (i = this.c.size() - 1; i >= 0; i--) { localObject1 = (ArrayList)this.c.get(i); for (j = ((ArrayList)localObject1).size() - 1; j >= 0; j--) { a((xn)((ArrayList)localObject1).get(j)); if (((ArrayList)localObject1).isEmpty()) { this.c.remove(localObject1); } } } a(this.f); a(this.e); a(this.d); a(this.g); e(); } } } /* Location: C:\DEV\android\dex2jar-2.1-SNAPSHOT\classes-dex2jar.jar!\xe.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */