language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
3,793
2.5625
3
[]
no_license
package Model; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Calendar; import java.util.List; import java.util.stream.Collectors; import Controller.HashingUtils; import org.javatuples.Decade; import org.javatuples.Ennead; public class Block implements Serializable{ private String currentHash; private String previoushash; private String owner; private String creator; private String digitalSignature; private List<Decade<String, String, String, String, String, String, String,String,String,String>> data; //block data private long timestamp; public Block(List<List<String>> data, String previoushash,String ownerID,String digitalSignature,long timestamp,String creator) { List<Decade<String, String, String, String, String, String,String,String,String,String>> DecadeList = data.stream().map( elem -> Decade.fromCollection(elem) ).collect(Collectors.toList()); this.previoushash = previoushash; this.data = DecadeList; this.timestamp = timestamp; this.owner = ownerID; this.digitalSignature = digitalSignature; this.creator = creator; this.currentHash = this.blockHashCode(Block.genByteArr(this.data), this.previoushash, this.owner ,this.timestamp); } public List<Decade<String, String, String, String, String, String,String,String,String,String>> getData() { return data; } public String getCurrentHash() { return currentHash; } public String getPrevioushash() { return previoushash; } public void setCurrentHash(String currentHash) { this.currentHash = currentHash; } public void setPrevioushash(String previoushash) { this.previoushash = previoushash; } @Override public int hashCode() { return super.hashCode(); } // ---- Unused method ---- // public String blockHashCode() { // return HashingUtils.hash(Block.genByteArr(this), "SHA-256"); // } public String getDigitalSignature() { return digitalSignature; } public void setDigitalSignature(String digitalSignature) { this.digitalSignature = digitalSignature; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator; } public long getTimestamp() { return timestamp; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } public String blockHashCode(byte[] data, String prehash, String owner, long tmestamp) { return HashingUtils.hashBlock( data + prehash + owner + tmestamp, "SHA-256"); } // private static byte[] genByteArr(Block b) { private static byte[] genByteArr(List<Decade<String, String, String, String, String, String,String,String,String,String>> b) { ByteArrayOutputStream boas = new ByteArrayOutputStream(); ObjectOutputStream out; if (b != null) { try { out = new ObjectOutputStream(boas); out.writeObject(b); out.flush(); } catch (IOException ex) { System.out.println(ex.getMessage()); return null; } return boas.toByteArray(); } else { return null; } } @Override public String toString() { return "Current Hash:" + this.currentHash + "\nPrevious Hash:" + this.previoushash + "\n"; } }
Markdown
UTF-8
5,006
3.28125
3
[]
no_license
# FinalProject Git repository to hold the code for my Msci final year project. I am investigating the importance of the crossover and mutation operators when evoling neural networks. I will evaluate the implemented operators on the board game Pentago. # Pentago Pentago is a variation of noughts and crosses. It is played on a 6x6 grid which is also split down into 4 smaller 3x3 grids that can each rotate. The objective is to obtain 5 of your colour tiles in a row. A turn consists of a player placing one of their tiles in an available space on the board and then choosing one of the four smaller grids to rotate 90 degrees clockwise or anti-clockwise. # Crossover Operator The crossover operator is inspired by the concept of reproduction and survival of the fittest that occurs in natural evolution. 2 individuals from the population being evolved are selected for crossover and combined in some manner depending on their genotypic information to produce offspring that, in theory, take the common and favourable qualities of both the parents. The primary role of crossover is to better explore the population search space by combining traits of individuals that unlock new areas of the search space. # Mutation Operator The mutation operator is inspired by genetic mutation that occurs in nature. An individuals genotypic information is randomly altered in some way to produce slightly different bahviours. These behaviours can sometimes be detrimental to the individual but sometimes can be a positive change that presents a more optimum solution to the problem. If the mutation results in a positive change then that individual will have a higher fitness and therefore perform the desired task better. The primary role of mutation is exploitation of a local search space around a promising individual. Mutation is what drives convergence when promising individuals exist in the population as it can in theory continuously move through the search space iteratively improving from one individual to an optimum solution. # Permutation problem We must be careful when evolving neural networks through evolutionary algorithms given how we represent them. It is possible that a individual in the population(Phenotype) can have a number of different representations(Genotype). This can cause problems when recombining individuals through crossover as 2 almost indistuinguishable phenotypes can have completly different genotypic structure resulting in non functional offspring. Ideally we would like to find a crossover operator that is able to ensure neural networks can be recombined in a positive way that maintains the common behaviour of the parents. This is known as safe crossover Similarly when dealing with deep and recurrent neural networks that consists of hundreds of thousands of parameters the fragility of mutation also comes into play. Applying mutation to certain values within the genotypic structure can have more drastically then desired effects on the overal behaviour of the individual. For example altering weights closer to the inputs of a neural network will have much larger rippling effects that altering the weights closer to the outputs. It is because of this we look for a mutation operator that is able to predict the sensitivity of certain neuron outputs and alter the scale of mutation accordingly. This is known as safe mutation. # Evaluation To evaluate the implementation of the researched safe crossover and safe mutation operators I will compare then to a number of different algorithms on the pentago proble. First I will compare to that of a random rule based Pentago player that has random moves. I will implement a standard neuroevolution algorithm using standard crossover and mutation operators to present the permutation problem. I will implement the safe crossover and safe mutation operators individually to observe how they alter the behaviour of the algorithm and then look to combine them. Finally, if time is available, I will look at a standard NEAT implementation and compare the performance of NEAT to that of my combined algorithm as a benchmark test. # If I have time If time is available towards the end of the project I will look to improve upon my developed algorithm by looking for parallelisation opportunities and any potential for reducing the evaluation time of an individual in the population. # Expected Timeline - Implement a working version of Pentago - Implement some form of simple GUI to observe pentago works correctly - Implement random AI as a a baseline of testing performance - Implement standard neuroevolution approach - Implement a number of different standard crossover/mutation operators - Implement Safe mutation operator - Implement Safe crossover operator - Apply either/both operators to the developed algorithm - Find NEAT implementation - Parallelisation (May come earlier if poor performance) - Reduce evaluation function to NN outputs? - Minimise evaluation via minimax?
Python
UTF-8
1,143
3.203125
3
[]
no_license
from errors import NotNegative def parser_number(number): if '-' in number: raise NotNegative if len(number) == 1 and number.isalpha(): raise ValueError if 'b' == number[-1]: return int(number.replace('b', ''), 2) elif 'd' == number[-1]: return int(number.replace('d', '')) elif 'h' == number[-1]: return int(number.replace('h', ''), 16) return int(number) def to_binary(n, bits): """ Extraída de https://stackoverflow.com/questions/12946116/twos-complement-binary-in-python """ s = bin(parser_number(str(n).lower()) & int("1"*bits, 2))[2:] return ("{0:0>%s}" % bits).format(s) def parse_lit(literal, variables_data): try: lit = to_binary(literal, 16) except ValueError: lit = to_binary(variables_data[literal]['dir_memory'], 16) return lit def parse_dir(direction_memory, variables_data): memory_dir = direction_memory.strip('(').strip(')') try: direction = to_binary(memory_dir, 16) except ValueError: direction = to_binary(variables_data[memory_dir]['dir_memory'], 16) return direction
C++
UTF-8
2,356
2.890625
3
[]
no_license
#include <gtest/gtest.h> #include <fccl/semantics/JntArraySemantics.h> #include <vector> using namespace fccl::semantics; class JntArraySemanticsTest : public ::testing::Test { protected: virtual void SetUp() { joint_names.push_back("joint0"); joint_names.push_back("joint1"); joint_names.push_back("joint2"); joint_names.push_back("joint3"); joint_names2.push_back("shoulder"); joint_names2.push_back("elbow"); joint_names3.push_back("joint0"); joint_names3.push_back("shoulder"); joint_names3.push_back("elbow"); joint_names3.push_back("joint3"); } virtual void TearDown() { } std::vector<std::string> joint_names; std::vector<std::string> joint_names2, joint_names3; }; TEST_F(JntArraySemanticsTest, Basics) { JntArraySemantics js; js.resize(joint_names.size()); ASSERT_EQ(joint_names.size(), js.size()); for(std::size_t i=0; i < js.size(); i++) js(i).setName(joint_names[i]); JntArraySemantics js2(js); JntArraySemantics js3; js3.resize(js.size()); for(std::size_t i=0; i<js.size(); i++) js3(i).setName(js(i).getName()); JntArraySemantics js4; js4 = js; JntArraySemantics js5; js5.joints() = js.joints(); EXPECT_TRUE(js.equals(js2)); EXPECT_TRUE(js.equals(js3)); EXPECT_TRUE(js.equals(js4)); EXPECT_TRUE(js.equals(js5)); } TEST_F(JntArraySemanticsTest, partialAssignement) { JntArraySemantics js, js2, js3; js.resize(joint_names.size()); for(std::size_t i=0; i < js.size(); i++) js(i).setName(joint_names[i]); js2.resize(joint_names2.size()); for(std::size_t i=0; i < js2.size(); i++) js2(i).setName(joint_names2[i]); js3.resize(joint_names3.size()); for(std::size_t i=0; i < js3.size(); i++) js3(i).setName(joint_names3[i]); js.partialAssignment(1, 2, js2); EXPECT_TRUE(js.equals(js3)); } TEST_F(JntArraySemanticsTest, init) { JntArraySemantics js; js.init(joint_names); ASSERT_EQ(js.size(), joint_names.size()); for(std::size_t i=0; i<js.size(); i++) EXPECT_STREQ(js(i).getName().c_str(), joint_names[i].c_str()); std::vector<std::string> joint_names2 = js.jointNames(); ASSERT_EQ(joint_names2.size(), joint_names.size()); for(std::size_t i=0; i<joint_names2.size(); i++) EXPECT_STREQ(joint_names2[i].c_str(), joint_names[i].c_str()); }
C#
UTF-8
1,806
2.890625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; namespace FindInFile.Wpf.ViewModels.Commands { /// <summary> /// Usage within view model: /// public ICommand Command { get; set; } /// public ViewModel() { this.Command = new RelayCommand(ExecuteCommand, CanExecuteCommand); } /// public void ExecuteCommand(object parameter) { } /// public bool CanExecuteCommand(object parameter) { return true; } /// </summary> public class RelayCommand : ICommand { public delegate void ICommandOnExecute(object parameter); public delegate bool ICommandOnCanExecute(object parameter); private ICommandOnExecute m_Execute; private ICommandOnCanExecute m_CanExecute; public RelayCommand(ICommandOnExecute onExecuteMethod) { m_Execute = onExecuteMethod; m_CanExecute = ReturnTrue; } public RelayCommand(ICommandOnExecute onExecuteMethod, ICommandOnCanExecute onCanExecuteMethod) { m_Execute = onExecuteMethod; m_CanExecute = onCanExecuteMethod; } #region ICommand Members public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } public bool CanExecute(object parameter) { return m_CanExecute.Invoke(parameter); } public void Execute(object parameter = null) { m_Execute.Invoke(parameter); } private bool ReturnTrue(object parameter) { return true; } #endregion } }
Python
UTF-8
1,156
3.265625
3
[]
no_license
#!/bin/env python #coding:UTF8 import csv def encode(s): "将unicode解码为utf8" if isinstance(s, unicode): return s.encode('utf8') else: return s def write(file_name,iter_obj,heads=[]): "定义写入CSV文件,iter_obj是List或者db-cursor,heads是标题列" with open(file_name,'ab') as csv_file: csv_wr = csv.writer(csv_file, delimiter=',', #分隔符,默认为","。如果指定错了,会将列表中的字符串连接在一起了 quotechar='"', #特殊符号前加符号 quoting=csv.QUOTE_MINIMAL ) heads = map(encode,heads) if heads: csv_wr.writerow(heads)#写入表头 if isinstance(iter_obj, list): iter_obj = map(encode,iter_obj) #写入CSV文件内容,一个列表。eg['name1','age1'],['name2','age2'] csv_wr.writerow(iter_obj) else: #下面是针对数据库cursor对象的情况 for lst in iter_obj: lst = map(encode,lst) csv_wr.writerow(lst) return 200
Java
UTF-8
7,380
2.140625
2
[]
no_license
package davgeo.github.tickettoridescoreboard; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.graphics.Typeface; import android.support.v7.app.AlertDialog; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.util.Locale; public class PlayerActionActivity extends BaseGameActivity { /** Called when activity is created **/ @Override protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.activity_player_action); super.onCreate(savedInstanceState); } /** Add extra activity specific behaviour to onCreate method **/ @Override protected void doActivitySetup() { m_game_complete = false; doSettingUpdate(); } /** Call to display player stats */ @Override protected void displayPlayerStats() { int idx = m_playerNum - 1; TextView nameTxt = (TextView) findViewById(R.id.playerName); nameTxt.setText(m_playerNameArray[idx]); nameTxt.setTextColor(getPlayerColour(m_playerNum)); TextView scoreTxt = (TextView) findViewById(R.id.scoreValueTxt); scoreTxt.setText(String.format(Locale.getDefault(), "%d", m_trainScoreArray[idx])); TextView trainTxt = (TextView) findViewById(R.id.trainsValueTxt); trainTxt.setText(String.format(Locale.getDefault(), "%d", m_trainCountArray[idx])); TextView stationTxt = (TextView) findViewById(R.id.stationsValueTxt); stationTxt.setText(String.format(Locale.getDefault(), "%d", m_stationCountArray[idx])); String actionString = getResources().getString(R.string.selectActionTxt, m_playerNum); TextView actionTxt = (TextView) findViewById(R.id.selectActionTxt); actionTxt.setText(actionString); } /** Call to implement setting change updates **/ @Override protected void doSettingUpdate() { Button pickedTrainCardBtn = (Button) findViewById(R.id.pickupTrainsBtn); Button pickedRouteCardBtn = (Button) findViewById(R.id.pickupRoutesBtn); if(m_preferences.getBoolean("Settings.CardPickup", true)) { pickedTrainCardBtn.setText(R.string.pickupTrainsBtn); pickedRouteCardBtn.setVisibility(View.VISIBLE); } else { pickedTrainCardBtn.setText(R.string.pickupBtnAlternate); pickedRouteCardBtn.setVisibility(View.GONE); } } /** Call to configure buttons in played trains dialog **/ protected void setPlayedTrainButtonTxt(Button button, final AlertDialog dialog) { Resources res = getResources(); int[] routeScoreArray = res.getIntArray(R.array.trainScores); int buttonTag = Integer.parseInt(button.getTag().toString()); // Update button text button.setText(res.getString(R.string.playedTrainsDialogBtn, buttonTag, routeScoreArray[buttonTag-1])); // Update onClick method to call scoreTrains function and then dismiss dialog button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { scoreTrains(view); dialog.dismiss(); } }); } /** Called when either the Pickup Route/Train Cards buttons are pressed */ public void pickupCards(View view) { saveUndoState(); goToNextPlayer(); } /** Called when the Played Trains button is pressed **/ public void playedTrains(View view) { AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this); // Load dialog from custom layout xml LayoutInflater inflater = this.getLayoutInflater(); alertBuilder.setView(inflater.inflate(R.layout.played_trains_dialog, null)) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); final AlertDialog playedTrainsDialog = alertBuilder.create(); playedTrainsDialog.show(); // Configure each button setPlayedTrainButtonTxt((Button) playedTrainsDialog.findViewById(R.id.playedTrainsBtn1), playedTrainsDialog); setPlayedTrainButtonTxt((Button) playedTrainsDialog.findViewById(R.id.playedTrainsBtn2), playedTrainsDialog); setPlayedTrainButtonTxt((Button) playedTrainsDialog.findViewById(R.id.playedTrainsBtn3), playedTrainsDialog); setPlayedTrainButtonTxt((Button) playedTrainsDialog.findViewById(R.id.playedTrainsBtn4), playedTrainsDialog); setPlayedTrainButtonTxt((Button) playedTrainsDialog.findViewById(R.id.playedTrainsBtn5), playedTrainsDialog); setPlayedTrainButtonTxt((Button) playedTrainsDialog.findViewById(R.id.playedTrainsBtn6), playedTrainsDialog); setPlayedTrainButtonTxt((Button) playedTrainsDialog.findViewById(R.id.playedTrainsBtn7), playedTrainsDialog); setPlayedTrainButtonTxt((Button) playedTrainsDialog.findViewById(R.id.playedTrainsBtn8), playedTrainsDialog); } /** Called when the Played Stations button is pressed **/ public void playedStations(View view) { saveUndoState(); m_stationCountArray[m_playerNum-1] -= 1; if(m_preferences.getBoolean("Settings.AutoNextPlayer", true)) { goToNextPlayer(); } else { displayPlayerStats(); } } /** Called when the End Game button is pressed **/ public void endGame(View view) { Intent intent = new Intent(this, EndGameActivity.class); Bundle bundle = new Bundle(); saveBundleState(bundle); intent.putExtras(bundle); startActivity(intent); } /** Called when the Edit Player Name button is pressed **/ public void editName(View view) { doEditNameDialog(); } /** Called when a button is clicked from played trains dialog **/ public void scoreTrains(View view) { int trainCount = Integer.parseInt(view.getTag().toString()); int[] routeScoreArray = getResources().getIntArray(R.array.trainScores); saveUndoState(); // Update scores and train count m_trainScoreArray[m_playerNum-1] += routeScoreArray[trainCount-1]; m_trainCountArray[m_playerNum-1] -= trainCount; // Check if train count goes below threshold value int trainThreshold = m_preferences.getInt("Settings.EndGameTrainThreshold", getResources().getInteger(R.integer.endGameTrainThreshold)); if(m_trainCountArray[m_playerNum-1] <= trainThreshold) { Toast.makeText(this, String.format(Locale.getDefault(), "End game approaching - %s has %d or fewer trains remaining", m_playerNameArray[m_playerNum-1], trainThreshold), Toast.LENGTH_SHORT).show(); Button endGameBtn = (Button) findViewById(R.id.endGameBtn); endGameBtn.setTypeface(null, Typeface.BOLD); } // Update display if(m_preferences.getBoolean("Settings.AutoNextPlayer", true)) { goToNextPlayer(); } else { displayPlayerStats(); } } }
Java
UTF-8
1,459
2.890625
3
[ "MIT" ]
permissive
package view.grid; import javafx.scene.Group; /** * @author Teddy Franceschi, Harshil Garg */ public class EngineGrid extends Grid { private static final int CELL_PIXELS = 50; public EngineGrid(int gridWidth, int gridHeight, int renderWidth, int renderHeight) { super(gridWidth, gridHeight, renderWidth, renderHeight, CELL_PIXELS); } public void blockToGridPane(int row, int col, String name) { GridPaneNode temp = new GridPaneNode(row + WRAP / 2, col + WRAP / 2, name); blockList.add(temp); } public void populateBorder() { for (int i = 0; i < gridWidth; i++) { for (int j = 0; j < gridHeight; j++) { if ((i < WRAP / 2 || j < WRAP / 2) || (i >= (gridWidth - WRAP / 2) || j >= (gridHeight - WRAP / 2))) { GridPaneNode temp = new GridPaneNode(j, i, BORDER); blockList.add(temp); } } } } public Group getGroup() { return group; } public double getBlockSize() { return CELL_PIXELS; } public double getWidth() { return gridWidth; } public double getHeight() { return gridHeight; } public boolean reRender(int row, int col, String newPath) { GridPaneNode newGPN = new GridPaneNode(row, col, newPath); GridPaneNode temp = grid[row + WRAP / 2][col + WRAP / 2]; temp.swap(newGPN, 0); return true; } }
JavaScript
UTF-8
819
2.9375
3
[ "MIT" ]
permissive
/******************************************************************* * @file: Light.js * @author: Aniket Dashpute * @description: Lights file with Phong shading parameters * Northwestern University *******************************************************************/ function CLight(lightPos) { // light position this.position = vec4.create(); vec4.copy(this.position, lightPos); // light color this.color = vec4.fromValues(0.8, 0.8, 0.8, 1.0); // light power this.power = 40.0; console.log("Light position: "+this.position); } CLight.prototype.setPower = function(nPower) { this.power = nPower; } CLight.prototype.setPosition = function(lightPos) { vec4.copy(this.position, lightPos); } CLight.prototype.setColor = function(color) { vec4.copy(this.color, color); }
PHP
UTF-8
514
2.625
3
[]
no_license
<?php require 'model.php'; $message = ""; switch($userStatus){ case '3': $message = "Welcome superadministrator"; $class = "superadmin"; break; case '2': $message = "Welcome administrator"; $class = "admin"; break; case '1': $message = "Welcome user"; $class = "user"; break; default: $message = "Unknown user type"; $class = "unknown"; break; } ?>
Markdown
UTF-8
723
3.171875
3
[]
no_license
## Installation Begin by installing this package through Composer. Edit your project's `composer.json` file to require `varmad/laravel-haml`. It might look something like: ```php "require": { "laravel/framework": "4.0.*", "varmad/laravel-haml": "dev-master", } ``` Next, update Composer from the Terminal: ```php composer update ``` Once this operation completes, add the service provider. Open `app/config/app.php`, and add a new item to the providers array. ```php 'Varmad\LaravelHaml\LaravelHamlServiceProvider' ``` ## Usage Creating a view file filename.haml.php(hello.haml.php) Rendering form the controller public function index() { return View::make('hello'); }
Java
UTF-8
326
2
2
[]
no_license
package com.sisveco.dao; import java.util.List; import java.util.Map; import com.sisveco.entity.Control; import com.sisveco.entity.Producto; public interface ProductoDao { int create(Producto co); int update(Producto co); int delete(int key); Producto read(int key); List<Map<String, Object>> readAll(); }
C#
UTF-8
4,688
2.59375
3
[]
no_license
using System; using System.Linq; using System.Collections.Generic; using System.Text; using C2LP.PDA.Datas.Model; using System.Data; namespace C2LP.PDA.Datas.BLL { public class RegionServer : BaseServer { /// <summary> /// 清空所有区域信息 /// </summary> /// <returns></returns> public static int ClearRegions() { string sql = "delete from c2lp_Region;"; try { return _SqlHelp.ExecuteNonQuery(sql, CommandType.Text); } catch (Exception ex) { throw ex; } } /// <summary> /// 根据拉取到的区域信息,获取需要更新的区域ID /// </summary> /// <param name="updateIdList"></param> /// <returns></returns> public static List<int> GetUpdateRegionIdList(List<string> updateIdList) { List<int> idList = new List<int>(); if (updateIdList.Count > 0) { try { string sql = "select Id from c2lp_region where Id in (" + string.Join(",", updateIdList.ToArray()) + ")"; DataSet ds = _SqlHelp.ExecuteDataSet(sql, System.Data.CommandType.Text); if (ds != null && ds.Tables.Count > 0) { foreach (DataRow row in ds.Tables[0].Rows) { idList.Add(Convert.ToInt32(row["Id"])); } } } catch (Exception ex) { throw ex; } } return idList; } /// <summary> /// 更新区域信息 /// </summary> /// <param name="valueStr">sql value数据字符</param> /// <returns></returns> public static int UpdateRegions(string valueStr) { //string sql = "delete from c2lp_Region;"; string sql = string.Empty; try { //_SqlHelp.ExecuteNonQuery(sql, System.Data.CommandType.Text); if (!string.IsNullOrEmpty(valueStr)) { sql += "insert into c2lp_Region (Id,`name`,parentId) values " + valueStr; return _SqlHelp.ExecuteNonQuery(sql, System.Data.CommandType.Text); } return 0; } catch (Exception ex) { throw ex; } } /// <summary> /// 更新区域信息 /// </summary> /// <param name="valueStr">sql value数据字符</param> /// <returns></returns> public static int UpdateRegions(ref string insertSql, ref string updateSql) { //string sql = "delete from c2lp_Region;"; //string sql = string.Empty; try { if (!string.IsNullOrEmpty(insertSql)) insertSql = _SqlHelp.ExecuteNonQuery(insertSql, System.Data.CommandType.Text).ToString(); else insertSql = "0"; if (!string.IsNullOrEmpty(updateSql)) updateSql = _SqlHelp.ExecuteNonQuery(updateSql, System.Data.CommandType.Text).ToString(); else updateSql = "0"; return 0; } catch (Exception ex) { throw ex; } } /// <summary> /// 获取所有区域 /// </summary> /// <returns></returns> public static List<MyRegion> GetAllRegion() { List<MyRegion> list = new List<MyRegion>(); try { //查询所有城市 string sql = "select id,`name`,parentId from c2lp_region "; DataSet ds = _SqlHelp.ExecuteDataSet(sql, System.Data.CommandType.Text); if (ds != null && ds.Tables.Count > 0) { foreach (DataRow row in ds.Tables[0].Rows) { MyRegion r = new MyRegion(); r.Id = Convert.ToInt32(row["id"]); r.Name = row["Name"].ToString(); r.ParentId = Convert.ToInt32(row["parentId"]); list.Add(r); } } } catch (Exception ex) { throw ex; } return list; } } }
SQL
UTF-8
258
3.828125
4
[]
no_license
-- 11. How to find 2nd highest salary without using a co-related subquery? (solution) -- Using CROSS JOIN SELECT max(e.salary) as second_highest_salary FROM Employee e cross join Employee e2 WHERE e.salary < e2.salary ; -- Using RANK in PostgreSQL
Markdown
UTF-8
569
2.625
3
[ "Apache-2.0" ]
permissive
--- layout: post title: "Video: What's new in Strimzi 0.33.0" date: 2023-01-25 author: jakub_scholz --- Strimzi 0.33.0 has been released with multiple new features and improvements. As with previous releases, we created a video that introduces the main changes. You can watch the video here or on our [YouTube channel](https://youtu.be/CclPi4zp7Cs). <!--more--> <iframe width="560" height="315" src="https://www.youtube.com/embed/CclPi4zp7Cs" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
Markdown
UTF-8
1,896
2.6875
3
[]
no_license
# YouCompleteMe ### Required Vim Features YouCompleteMe requires vim to have support for python scripting. Run the following and ensure that there is a + before python3: ``` vim --version | grep python ``` If not, you will need to [compile vim from source](https://github.com/Valloric/YouCompleteMe/wiki/Building-Vim-from-source) (don't worry, it's easy). ### Build Dependencies YouCompleteMe depends on some programs being installed to build successfully; see the (short) [installation guide](https://github.com/ycm-core/YouCompleteMe#linux-64-bit). For Ubuntu 20.04+ for example: ``` sudo apt install build-essential cmake python3-dev ``` Vim-plug will have successfully built YouCompleteMe if you already had these dependencies installed when vim-plug downloaded YouCompleteMe for the first time. Otherwise, run `:PlugInstall!` in vim to force a rebuild of YouCompleteMe. Following this short guide should be enough to successfully build a basic build of YouCompleteMe. If you're on a different distro than the ones listed or if something goes wrong with the installation, refer to the [full installation guide](https://github.com/Valloric/YouCompleteMe#full-installation-guide). ### Semantic Completion (Optional) The short installation guide also includes instructions on how to enable semantic completion for supported languages and their respective dependencies (e.g. C/C++ semantic completion requires libclang, and Go requires, well, Go to be installed). Note that you don't _need_ semantic completion, but it can be nice to have especially if the set-up doesn't take much effort (e.g. Go). Rebuilding YouCompleteMe with the appropriate flags should be enough to enable semantic completion for your target languages. However, to maximize your experience, read the [user guide](https://github.com/Valloric/YouCompleteMe#user-guide) for language-specific set-up instructions.
Markdown
UTF-8
709
2.609375
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: "Additional Termination Considerations | Microsoft Docs" ms.custom: "" ms.date: "11/04/2016" ms.technology: ["cpp-language"] ms.topic: "language-reference" dev_langs: ["C++"] helpviewer_keywords: ["quitting applications", "exiting applications", "programs [C++], terminating"] ms.assetid: acbe2332-9d8a-4a58-a471-dd652a837384 author: "mikeblome" ms.author: "mblome" ms.workload: ["cplusplus"] --- # Additional Termination Considerations You can terminate a C++ program by using `exit`, **return**, or `abort`. You can add exit processing using the `atexit` function. These are discussed in the following sections. ## See also [Startup and Termination](../cpp/startup-and-termination-cpp.md)
Shell
UTF-8
298
2.609375
3
[ "MIT" ]
permissive
#! /bin/bash ldapadd -x -D "cn=admin,$LDAP_BASE_DN" -w "$LDAP_ADMIN_PASSWORD" -f /container/service/slapd/assets/default_nodes/add_nodes.ldif code=$? if [[ "$code" != "0" && "$code" != "68" ]]; then echo "Adding default nodes failed. Try to set bigger timeout" pkill -f /container/tool/run fi
C#
UTF-8
848
3.375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _10.Unicode_Characters { class Program { static void Main(string[] args) { var input = Console.ReadLine().ToCharArray(); foreach (var VARIABLE in input) { Console.Write("\\u"); if ((int) VARIABLE > 99) { //Console.Write((int) VARIABLE); } else { //Console.Write("0"); //Console.Write((int)VARIABLE); } //Console.WriteLine(); Console.Write(String.Format("{0:x4}", (int)VARIABLE)); } } } }
C++
UTF-8
1,019
4.125
4
[]
no_license
// C++ program for implementation of Heap Sort #include <iostream> using namespace std; void heapify(int arr[],int n, int i){ int largest = i; int l = 2*i + 1; int r = 2*i +2; if(l<n && arr[largest] < arr[l]) largest = l; if(r<n && arr[largest]<arr[r]) largest = r; if(largest != i) { swap(arr[i],arr[largest]); heapify(arr,n,largest); } } void heapSort(int arr[], int n) { for(int i = n/2 - 1 ;i>=0;i--) heapify(arr, n, i); for(int i =n-1 ;i >= 0 ;i--) { swap(arr[i], arr[0]); heapify(arr,i, 0); } } /* A utility function to print array of size n */ void printArray(int arr[], int n) { for (int i = 0; i < n; ++i) cout << arr[i] << " "; cout << "\n"; } // Driver program int main() { int arr[] = { 12, 11, 13, 5, 6, 7 }; int n = sizeof(arr) / sizeof(arr[0]); heapSort(arr, n); cout << "Sorted array is \n"; printArray(arr, n); }
Markdown
UTF-8
1,713
2.640625
3
[ "MIT" ]
permissive
--- layout: post title: "Perceptual Compressive Sensing" date: 2018-02-01 07:19:18 categories: arXiv_CV tags: arXiv_CV CNN author: Xuemei Xie, Jiang Du, Guangming Shi, Chenye Wang, Xun Xu mathjax: true --- * content {:toc} ##### Abstract This paper proposes perceptual compressive sensing. The network is composed of a fully convolutional measurement and reconstruction network. For the following contributions, the proposed framework is a breakthrough work. Firstly, the fully-convolutional network measures the full image which preserves structure information of the image and removes the block effect. Secondly, with the employment of perceptual loss, we no longer concentrate on the Euclidean distance of reconstruction. Instead, we just care about the perceptual invariance, which makes the reconstructed image obtain much semantic information. We call it semantics-oriented reconstruction. Experimental results show that the proposed framework outperforms the existing state-of-the-art methods. ##### Abstract (translated by Google) 本文提出了感知压缩感知。网络由一个完全卷积的测量和重建网络组成。对于下面的贡献,提出的框架是一项突破性的工作。首先,全卷积网络测量保存图像结构信息的全图像,消除块效应。其次,利用感知损失,我们不再专注于重建的欧式距离。相反,我们只关心感知不变性,这使得重构图像获得了很多的语义信息。我们称之为语义导向重构。实验结果表明,提出的框架优于现有的最先进的方法。 ##### URL [http://arxiv.org/abs/1802.00176](http://arxiv.org/abs/1802.00176) ##### PDF [http://arxiv.org/pdf/1802.00176](http://arxiv.org/pdf/1802.00176)
Shell
UTF-8
383
2.921875
3
[ "MIT" ]
permissive
#!/bin/bash if [ ! -f '/config/config.xml' ]; then # Run syncthing to generate initial configuration files, stop it, then edit # config.xml to remove 127.0.0.1 limit from the GUI address. /syncthing -home=/config & sleep 5 pkill syncthing sed -i 's/<address>127.0.0.1:8384<\/address>/<address>:8384<\/address>' /config/config.xml fi /syncthing -home=/config
C#
UTF-8
1,520
2.90625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Monitoring.GeometricMonitoring.MonitoringType { public abstract partial class MonitoringScheme { public sealed class SketchedChangeDistance : MonitoringScheme, IEquatable<SketchedChangeDistance> { public string SketchName { get; } public int norm { get; } public SketchedChangeDistance(string sketchName, int norm) { SketchName = sketchName; this.norm = norm; } public override string AsString() => "SKD"; public bool Equals(SketchedChangeDistance other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return string.Equals(SketchName, other.SketchName) && norm == other.norm; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; return obj is SketchedChangeDistance && Equals((SketchedChangeDistance) obj); } public override int GetHashCode() { unchecked { return ((SketchName != null ? SketchName.GetHashCode() : 0) * 397) ^ norm; } } } } }
Markdown
UTF-8
3,286
2.6875
3
[]
no_license
# PI-shutdown-push-button A header mounted push button that will safely shutdown the Raspberry PI This project describes a very simple but very very usefull tool that allows you to safely shutdown your Raspberry PI. This might be particularly usefull when, for instance, your headless PI is unreacheable because your network/wifi-router happens to be down at the exact moment you need to shut down the PI ... you probably know what I mean... the question is then how to safely shutdown the PI without risking any SD card corruptions. Now I didn't devised this setup, the credit all goes to [GIMX](https://gimx.fr/wiki/index.php?title=RPi#Autostart_GIMX_at_boot_without_GUI) where I found it. A bit of advertisement here:... GIMX is a cool project that allows old gamers, like me, to use the mouse and keyboard to play games on the PlayStation or XBox. Sounds like a gimmick doesn't it :-) !!! I thought this was so usefull that I wanted to replicate it here so I would not loose it. My meager contribution is repackaging the push button and the led to easily mount them on the PI header. The led will turn on when a program of your choosing is running, in my case it is python... ### Breadboard view `Fritzing` does not allow the kind of 3D drawing I need to explain how to mount the resistors and the push button (PB) on top of a dual inline 6 pins female header, sorry for the distorded "perspective" view... ![PI_header_BP_led](https://github.com/jeanrocco/PI-shutdown-push-button/blob/master/PI_Header_PB_LED_bb1.png) ### and Schematic ![schematic](https://github.com/jeanrocco/PI-shutdown-push-button/blob/master/PI_Header_PB_LED_schem.png) ### Pictures Some pictures might help... ![picture1](https://github.com/jeanrocco/PI-shutdown-push-button/blob/master/20180928_173451.jpg) ![picture2](https://github.com/jeanrocco/PI-shutdown-push-button/blob/master/20180928_173256.jpg) ![picture3](https://github.com/jeanrocco/PI-shutdown-push-button/blob/master/20180928_173220.jpg) some epoxy glue visible on that one... ![picture4](https://github.com/jeanrocco/PI-shutdown-push-button/blob/master/20180928_172805.jpg) ![picture5](https://github.com/jeanrocco/PI-shutdown-push-button/blob/master/20180928_172744.jpg) ### Python Script Of course there is a python script that handles it all, copy it in your `/home/pi` directory as [`blink.py`](https://github.com/jeanrocco/PI-shutdown-push-button/blob/master/blink.py.github). To start the script `blink.py` at boot, add it to the pi user crontab (`crontab -e`) as: `@reboot python /home/pi/blink.py &` . ### UPDATE april 20, 2023: I just installed `Moode 8.3.1`, which comes with an Airplay2 renderer, on a `PI-3b 1.2` equipped with an `IQaudio DAC Pro` HAT. This allows my 2 old mid-2012 MACs, recently upgraded with the wonderfull `https://dortania.github.io/OpenCore-Legacy-Patcher/`, to `VENTURA 13.3.1` no less, to stream music with Airplay2. The push button and the led work as before but in order to start the script at boot time you will have to add as root, at the end of `/etc/rc.local`, and before `exit 0` : `(/home/pi/blink.py)&` as is, with the the brackets and all. I got this from `https://www.msldigital.com/pages/shutdown-scripts-for-moode-audio` . jrb. ### Enjoy !
Java
UTF-8
921
2.734375
3
[]
no_license
package jaffa.physics; import org.junit.Assert; import org.junit.Test; public class QuadraticEquationTest { @Test public void testGetNegativeX() throws ImaginaryNumberException, DivideByZeroException { QuadraticEquation q = null; q = new QuadraticEquation(1, 3, -4); double x = q.getNegativeX(); Assert.assertEquals(-4, x, .1); } @Test public void testGetPositiveX() throws ImaginaryNumberException, DivideByZeroException { QuadraticEquation q = null; q = new QuadraticEquation(1, 3, -4); double x = q.getPositiveX(); Assert.assertEquals(1, x, .1); } @Test public void testThrowsInvalidException() throws ImaginaryNumberException, DivideByZeroException { // test to make sure that exceptions are being thrown try { new QuadraticEquation(0, 0, 0); Assert.fail("Didn't throw Exception"); } catch (ImaginaryNumberException e) { } catch (DivideByZeroException e) { } } }
JavaScript
UTF-8
1,858
2.65625
3
[]
no_license
import { useState, useEffect } from "react"; import axios from "axios"; export default function useCasesBiz(props) { const [cases, setCases] = useState([]); const [loading, setLoading] = useState(false); const [countries, setCountries] = useState([]); const [dateIndex, setDateIndex] = useState(0); const [country, setCountry] = useState("India"); const [type, setType] = useState(0); useEffect(() => { getCases(); getCountries(); }, []); useEffect(() => { document.getElementById("multi-bar").innerHTML = ""; document.getElementById("pie").innerHTML = ""; country && getCases(); }, [country]); const PROXY_SERVER = "https://cors-anywhere.herokuapp.com/"; const header = { "x-requested-with": true }; const getCases = async () => { let url = `${PROXY_SERVER}https://api.covid19api.com/dayone/country/${country}`; setLoading(true); axios .get(url, header) .then((result) => { if (result.status === 200 || result.status === 304) { result.data.sort((a, b) => { return new Date(a) - new Date(b); }); setLoading(false); setDateIndex(result.data.length - 1); setCases(result.data); } }) .catch((e) => { setLoading(false); alert("unable to fetch data, try again later"); }); }; const getCountries = async () => { let url = `${PROXY_SERVER}https://api.covid19api.com/countries`; let result = await axios.get(url, header); if (result.status === 200 || result.status === 304) { setCountries(result.data); } else { alert("unable to fetch countries, try again later"); } }; return { cases, setCases, getCases, loading, countries, setCountry, country, dateIndex, setDateIndex, type, setType, }; }
Markdown
UTF-8
5,335
2.921875
3
[ "Apache-2.0" ]
permissive
--- layout: post title: "淡如水的爱" subtitle: "爱不可言 清淡如水" image: feature: "23.jpg" date: 2016-05-13 author: "小粒玲" header-img: "img/postcover/丹顶鹤.jpg" tags: [tag04] categories: [cat04] comments: true --- 如果说爱情一定要像火焰一样热情,我想,那只能存在于热恋期才会有的状态,如果说爱情一定要像水一样平静,我想,那是相濡以沫,共守一生的状态,时常把爱情比做水那再也合适不过了。 前几个星期看了一部韩国的纪录片《亲爱的,不要跨过那条江》里面讲的是一对高龄的夫妇在晚年相处的最后一段时光,有人说童话里都是骗人的,但当你看到这部纪录片的时候,你会感叹爱情,原来是经久不衰的,平淡里的生活也过的有滋有味,爱情是什么?你可能会找到答案,没有轰轰烈烈的事迹,没有甜蜜的爱语,行动告诉你,执子之手,与子偕老,一切真实的那么不真实,美好的超越了美好,在江原道横城山村里,98岁的爷爷和89岁的奶奶,他们在雪地里吃初雪、堆雪人,手拉手才能睡觉,半夜上厕所也要相互陪着,打扫院子也会相互挑逗,奶奶喜欢爷爷唱的歌,其中爷爷因为年事已高,已经分不清哪些是夏天的衣服,哪些是冬天衣服,但是奶奶还是会帮爷爷准备好衣服,每天出去的时候,他们都会穿情侣装,但是爷爷身有疾病,应该是气管炎,走没多久路就会气喘,奶奶还是会陪着他,那天他们养的小狗死了,奶奶已经意识到爷爷也即将要离开了,就把爷爷的衣服提前烧了,因为怕爷爷以后走了之后认不出衣服,但时间总是残忍的,爷爷最终还是走了,奶奶哭成了泪人,再也没有人陪她度过漫长的岁月,她跪在爷爷的坟墓上说,冷了就要穿多点衣服,即使思念也要忍着不要去想念 ![亲爱的,不要跨过那条江](http://7xtust.com2.z0.glb.clouddn.com/%E4%BA%B2%E7%88%B1%E7%9A%84.jpg "亲爱的,不要跨过那条江") 爷爷说:我只想做一个对自己的女人无尽地好的好人,爷爷也说:人生和花与树叶都是一样的,我是树叶就在春天茂盛生长,在夏天享尽雨水的拍打,到了秋天就随着寒霜飘落,人生又何尝不是这样,当初年少时像花儿一样含苞待放,花开后的样子虽然很美,最终都要随着岁月流逝枯萎衰败,归于虚无,凋落的话就是结束。 ![爷爷奶奶](http://7xtust.com2.z0.glb.clouddn.com/%E4%BA%B2%E7%88%B1%E7%9A%842.jpg "爷爷奶奶") 他们的爱情平淡而有趣,知足常乐于一切。 我父母的爱情,其实在我眼里看来,是很平常的,但在日常生活中,我也慢慢得去发现,去体会他们之间的爱,我爸爸近年身体不太好,检查住院是今年的事情了,以前,我是认为我妈不爱我爸的,但是越长大越发现。原来这一切都是源于爱,我妈喜欢抱怨我爸,经常觉得我爸怎么怎么样,我爸总摆着一副无所谓的样子,我妈是一个急性子,所以他们两个是互补的,说实话,我不太喜欢我妈的性子,可能遗传到我爸,我总是以平常心去对待很多事情,很多时候我是站在我爸这边的,我妈有时候觉得我爸不听她的话,会让我去和我爸说说,我表面上说好,实际上我有时候有说有时候没说,因为每个人都有自己的自由 我妈呢?其实还是一个非常好的女人,当我爸最远的时候,她有空就陪着她,那时候在惠州,经常陪到凌晨十二点才回到家,怕我爸不能吃什么,就买多点,让我爸挑,我爸没胃口就熬粥,我妈会晕车,每次坐车都很痛苦,我都替她难受,然而她还是会去看我爸,次数也很多,现在在广州,我姑姑早上问我爸谁在陪他的时候,我爸说开敏在(我妈的名字),我想,这句话很令我感动,一个人听到最有幸福感的话就是有他(她)在就足够了,她怕我爸一个人孤独,有时候让我弟陪他,有时候自己去陪他,我妈特抱怨医院的床板硬,睡的不舒服,有时候和我爸挤一张床,睡得比我爸还香,真是可爱,但是为了陪我爸,她也会去承受这么一点儿痛苦,我妈是刀子嘴豆腐心,心里无比心疼我爸,但是还是不说,只是用行动表现出来,她不喜欢虚的东西,是一个实实在在的女人,我爸娶了她,应该是一生最骄傲的事情吧,我妈拥有我爸,膝盖痛有人搽药,背痛有人锤,那也足够了,他们的爱真的像水一样,有时候争吵只是波浪,但是一日夫妻百日恩,床头吵架床尾和,不是吗?他们也是我的榜样啊。 ![聊天记录](http://7xtust.com2.z0.glb.clouddn.com/%E4%BA%B2%E7%88%B1%E7%9A%843.jpg "聊天记录") 爱情,因爱生情,而这一个过程,就像水一样,偶尔会起波浪,偶尔也会风平浪静,这就是爱的一切。 <small>2016.05.13 09:18</small> <a href="http://www.jianshu.com/p/b0c821eb4fd1">著作权归作者所有,转载请联系作者获得授权,并标注“作者”</a>
Java
UTF-8
1,343
2.140625
2
[]
no_license
package com.inno72.machine.vo; /** * @Auther: wxt * @Date: 2018/7/4 14:01 * @Description: */ public class AppStatus { private String machineId; private String appPackageName; private String versionName; private int versionCode; private String appName; private int appStatus;// 0 未启动 1前台运行 2 后台运行 private int appType;// 1:监控 2:正常 public String getAppPackageName() { return appPackageName; } public void setAppPackageName(String appPackageName) { this.appPackageName = appPackageName; } public String getMachineId() { return machineId; } public void setMachineId(String machineId) { this.machineId = machineId; } public String getVersionName() { return versionName; } public void setVersionName(String versionName) { this.versionName = versionName; } public int getVersionCode() { return versionCode; } public void setVersionCode(int versionCode) { this.versionCode = versionCode; } public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } public int getAppStatus() { return appStatus; } public void setAppStatus(int appStatus) { this.appStatus = appStatus; } public int getAppType() { return appType; } public void setAppType(int appType) { this.appType = appType; } }
C
UTF-8
10,453
2.515625
3
[]
no_license
/* C########################################################### SUBROUTINE LSOL(FI) C########################################################### C In this solver the TDMA algorithm is applied line-by-line C alternately along J and I lines. C Warning: arrays A() and C() should be dimensioned C as the maximum of NX and NY! C=========================================================== */ void LSOL(int NX, int NY, int NI, int NJ, int NIM, int NJM, int MAXIT, int LI[], double RESMAX, double ALFA, double ERRNOR, double RES0, double X[], double Y[], double AE[], double AW[], double AN[], double AS[], double AP[], double Q[],double FI[], double XC[], double YC[]){ double A[NX],C[NX]; /*DATA A,C /NX*0.,NX*0./ */ for(int N = 1; N <= MAXIT; N++){ /*C.....SOLVE WITH "TDMA" ALONG J-LINES*/ for(int i = 2; i<= NIM; i++){ for(int j = 2; j<= NJM; j++){ int ij = LI[i]+j; double APR = (1.0)/(AP[ij]-AS[ij]*A[j-1]); A[j]=AN[ij]*APR; C[j]=(Q[ij]-AE[ij]*FI[ij+NJ]-AW[ij]*FI[ij-NJ]-AS[ij]*C[j-1])*APR; } for(int j =NJM; j>=2; j--){ int ij = LI[i]+j; FI[ij] = C[j]-A[j]*FI[ij+1]; } } /*C.....SOLVE WITH "TDMA" ALONG I-LINES*/ for(int j = 2; j<=NJM; j++){ for(int i = 2; i<=NIM; i++){ int ij = LI[i]+j; double APR= (1.0)/(AP[ij]-AW[ij]*A[i-1]); A[i] = AE[ij]*APR; C[i]=(Q[ij]-AN[ij]*FI[ij+1]-AS[ij]*FI[ij-1]-AW[ij]*C[i-1])*APR; } for(int i=NIM; i>=2; i--){ int ij = LI[i]+j; FI[ij]=C[i]-A[i]*FI[ij+NJ]; } } /*.....CHECK CONVERGENCE OF INNER ITERATIONS*/ double RESN=0.0; for(int i = 2; i<=NIM; i++){ for(int j = 2; j<=NJM; j++){ int ij = LI[i]+j; double RES = Q[ij]-AP[ij]*FI[ij]-AE[ij]*FI[ij+NJ]-AW[ij]*FI[ij-NJ]-AS[ij]*FI[ij-1]-AN[ij]*FI[ij+1]; RESN = RESN + abs(RES); } } if(N == 1){RES0=RESN;} double RSM = RESN/RES0; printf("SWEEP, RSM = %lf \n", RSM); if(RSM<RESMAX){ return; } } return; } /* C########################################################### SUBROUTINE ADI(BETA,FI) C########################################################### C This is the standard ADI solver, as described in Sect. C 5.3.5. The original version of this code was written C by Joel H. Ferziger, Stanford University, 1995. C=========================================================== */ void ADI(double BETA, int NX, int NY, int NI, int NJ, int NIM, int NJM, int MAXIT, int LI[], double RESMAX, double ALFA, double ERRNOR, double RES0, double X[], double Y[], double AE[], double AW[], double AN[], double AS[], double AP[], double Q[],double FI[], double XC[], double YC[]){ int NXY = NX*NY; double AI[NX], CI[NX], AJ[NY], CJ[NY], API[NX], QI[NX], APJ[NY], QJ[NY], FF[NXY]; /*C.....CALCULATE ADI COEFFICIENTS*/ for(int i =1; i<= NI; i++){ for(int j = 1; j<=NJ; j++){ int ij = LI[i]+j; } } /*.....START ITERATION LOOP*/ for(int N = 1; N<=MAXIT; N++){ /*C.....SOLVE WITH "TDMA" ALONG I-LINES*/ for(int j = 2; j<=NJM; j++){ for(int i = 2; i<=NIM; i++){ int ij = LI[i]+j; API[i]=BETA-AE[ij]-AW[ij]; QI[i]=BETA+AN[ij]+AS[ij]; } for (int i = 2; i<=NIM; i++){ int ij = LI[i]+j; double APR = (1.0)/(API[i]-AW[ij]*AI[i-1]); AI[i]=AE[ij]*APR; CI[i]=(Q[ij]+QI[i]*FI[ij]-AN[ij]*FI[ij+1]-AS[ij]*FI[ij-1]-AW[ij]*CI[i-1])*APR; } for(int i = NIM; NIM>=2; i--){ int ij = LI[i]+1; FF[ij] = CI[i] - AI[i]*FF[ij+NJ]; } } /*C.....SOLVE WITH "TDMA" ALONG J-LINES*/ for(int i = 2; i<=NIM; i++){ for(int j = 2; j<=NJM; j++){ int ij = LI[i] +j ; APJ[j]=BETA-AN[ij]-AS[ij]; QJ[j]=BETA+AE[ij]+AW[ij]; } for(int j = 2; j<=NJM; j++){ int ij = LI[i]+j; double APR = (1.0)/(APJ[j]-AS[ij]*AJ[j-1]); AJ[j]=AN[ij]*APR; CJ[j]=(Q[ij]+QJ[j]*FF[ij]-AE[ij]*FF[ij+NJ]-AW[ij]*FF[ij-NJ]-AS[ij]*CJ[j-1])*APR; } for (int j=NJM; j>=2; j--){ int ij = LI[i]+j; FI[ij] = CJ[j]-AJ[j]*FI[ij+1]; } } /*C.....CHECK CONVERGENCE OF INNER ITERATIONS*/ double RESN=0.0; for(int i = 2; i<= NIM; i++){ for(int j = 2;j<=NJM; j++){ int ij = LI[i]+j; double RES = Q[ij]-AP[ij]*FI[ij]-AE[ij]*FI[ij+NJ]-AW[ij]*FI[ij-NJ]-AS[ij]*FI[ij-1]-AN[ij]*FI[ij+1]; RESN = RESN + abs(RES); } } if(N == 1){RES0=RESN;} double RSM = RESN/RES0; printf("SWEEP, RSM = %lf \n", RSM); if(RSM<RESMAX){ return; } } return; } /* C C############################################################# SUBROUTINE SIPSOL(FI) C############################################################# C This is the ILU solver after Stone; see Sect. 5.3.4 for C a description of the algorithm. C C M. Peric, Institut fuer Schiffbau, Hamburg, 1995 C============================================================= */ void SIPSOL(double BETA, int NX, int NY, int NI, int NJ, int NIM, int NJM, int MAXIT, int LI[], double RESMAX, double ALFA, double ERRNOR, double RES0, double X[], double Y[], double AE[], double AW[], double AN[], double AS[], double AP[], double Q[],double FI[], double XC[], double YC[]){ int NXY=NX*NY; double LW,LS,LPR; double UN[NXY],UE[NXY],RES[NXY], \ LW2[NXY],LS2[NXY],LPR2[NXY]; /*C.....CALCULATE ELEMENTS OF [L] AND [U] MATRICES*/ for(int i =2; i<=NIM; i++){ for(int ij = LI[i]+2; ij<=LI[i]+NJM; ij++){ LW2[ij]=AW[ij]/((1.0)+ALFA*UN[ij-NJ]); LS2[ij]=AS[ij]/((1.0)+ALFA*UE[ij-1]); double P1=ALFA*LW2[ij]*UN[ij-NJ]; double P2=ALFA*LS2[ij]*UE[ij-1]; LPR2[ij]=(1.0)/(AP[ij]+P1+P2-LW2[ij]*UE[ij-NJ]-LS2[ij]*UN[ij-1]); UN[ij]=(AN[ij]-P1)*LPR2[ij]; UE[ij]=(AE[ij]-P2)*LPR2[ij]; } } /*C.....CALCULATE RESIDUAL AND AUXILLIARY VECTORS; INNER ITERATION LOOP*/ for(int N=1; N=MAXIT; N++){ int RESN=0.0; for (int i = 2; i<=NIM; i++){ for(int ij=LI[i]+2; ij<=LI[i]+NJM; ij++){ RES[ij]=Q[ij]-AP[ij]*FI[ij]-AN[ij]*FI[ij+1]- \ AS[ij]*FI[ij-1]-AN[ij]*FI[ij+NJ]-AW[ij]*FI[ij-NJ]; RESN=RESN+abs(RES[ij]); RES[ij]=(RES[ij]-LS2[ij]*RES[ij-1]-LW2[ij]*RES[ij-NJ])*LPR2[ij]; } } if(N == 1){RES0 = RESN;} /*C.....CALCULATE INCREMENT AND CORRECT VARIABLE*/ for(int i = NIM; i>=2; i--){ for(int ij=LI[i]+NJM; ij<=LI[i]+2; ij--){ RES[ij]=RES[ij]-UN[ij]*RES[ij+1]-UE[ij]*RES[ij+NJ]; FI[ij]=FI[ij]+RES[ij]; } } /*C.....CONVERGENCE CHECK*/ double RSM = RESN/(RES0+1.e-20); printf("SWEEP, RSM = %lf \n", RSM); if(RSM<RESMAX){ return; } } return; } /* C############################################################## SUBROUTINE CGS(FI) C############################################################## C This is a pre-conditioned conjugate gradient solver for C symmetric matrices (e.g., pressure or pressure-correction C equation, heat conduction, etc.). A 3D version is included C in LAPL3D.F file. The original code was written by Ismet C Demirdzic, Masinski Fakultet, Sarajevo, 1987 (see Sect. C 5.3.6 for a description of the algorithm). C=============================================================== */ void CGS(double BETA, int NX, int NY, int NI, int NJ, int NIM, int NJM, int MAXIT, int LI[], double RESMAX, double ALFA, double ERRNOR, double RES0, double X[], double Y[], double AE[], double AW[], double AN[], double AS[], double AP[], double Q[],double FI[], double XC[], double YC[]){ int NXY=NX*NY; double PK[NXY], ZK[NXY], D[NXY], RES[NXY]; /*C.....CALCULATE INITIAL RESIDUAL VECTOR*/ RES0=0; for(int i = 2; i<=NIM; i++){ for(int ij = LI[i]+2; ij <= LI[i]+NJM; ij++){ RES[ij]=Q[ij]-AP[ij]*FI[ij]-AE[ij]*FI[ij+NJ]- \ AW[ij]*FI[ij-NJ]-AN[ij]*FI[ij+1]-AS[ij]*FI[ij-1]; RES0=RES0+abs(RES[ij]); } } /*C.....PRECONDITIONING MATRIX DIAGONAL*/ for(int i = 2; i<=NIM; i++){ for(int ij=LI[i]+2; ij<=LI[i]+NJM; ij++){ D[ij]=(1.0)/(AP[ij]-D[ij-NJ]*pow(AW[ij],2)-D[ij-1]*pow(AS[ij], 2)); } } /*C.....CALCULATION OF ZK; INNER ITERATION LOOP*/ double S0 = 1.e20; for(int n = 1; n<=MAXIT; n++){ /*C.....FORWARD SUBSTITUTION*/ for(int i = 2; i<=NIM; i++){ for(int ij=LI[i]+2; ij<=LI[i]+NJM; ij++){ ZK[ij]=(RES[ij]-AW[ij]*ZK[ij-NJ]-AS[ij]*ZK[ij-1])*D[ij]; } } for (int i = 2; i<=NIM; i++){ for(int ij= LI[i]+2; ij<=LI[i]+NJM; ij++){ ZK[ij]=ZK[ij]/(D[ij]+1.e-20); } } /*C.....BACKWARD SUBSTITUTION*/ double SK = 0.0; for (int i = NIM; i>=2; i--){ for(int ij = LI[i]+NJM; ij>=LI[i]+2; ij--){ ZK[ij]=(ZK[ij]-AE[ij]*ZK[ij+NJ]-AN[ij]*ZK[ij+1])*D[ij]; SK = SK + RES[ij]*ZK[ij]; } } /*C.....CALCULATE BETA AND NEW SEARCH VECTOR*/ double BET = SK/S0; for(int i = 2; i<=NIM; i++){ for(int ij= LI[i]+2; ij<=LI[i]+NJM; ij++){ PK[ij] = ZK[ij]+BET*PK[ij]; } } /*C.....CALCULATE SCALAR PRODUCT (PK . A PK) AND ALPHA (A PK OVERWRITES ZK)*/ double S2 = 0.0; for(int i = 2; i<=NIM; i++){ for(int ij = LI[i]+2; ij<=LI[i]+NJM; ij++){ ZK[ij]= AP[ij]*PK[ij]+AE[ij]*PK[ij+NJ]+AW[ij]*PK[ij-NJ]+\ AN[ij]*PK[ij+1]+AS[ij]*PK[ij-1]; S2 = S2+PK[ij]*ZK[ij]; } } double ALF= SK/S2; /*C.....CALCULATE NEW RESIDUAL AND UPDATE VARIABLE*/ double RESN = 0; for(int i = 2; i<=NIM; i++){ for(int ij = LI[i]+2; ij<= LI[i]+NJM; ij++){ FI[ij]=FI[ij]+ALF*PK[ij]; RES[ij]=RES[ij]-ALF*ZK[ij]; RESN=RESN+abs(RES[ij]); } } S0=SK; /*C....CHECK CONVERGENCE*/ double RSM = RESN/(RES0+1.e-20); printf("SWEEP, RSM = %lf \n", RSM); if(RSM<RESMAX){ return; } } return; } void PRINT2(int NI, double NJ, double IJST, double FI[], char NAME, int NX){ /* C######################################################### SUBROUTINE PRINT(NI,NJ,IJST,FI,NAME) C######################################################### PARAMETER (NX=162,NY=162,NXY=NX*NY,NXYA=NXY+NXY/2) IMPLICIT DOUBLE PRECISION (A-H,O-Z) DIMENSION FI(NXYA),LI(NX) CHARACTER*6 NAME */ int LI[NX]; for(int i = 1; i<=NI; i++){ LI[i]=IJST+(i-1)*NJ; } printf("NAME\n"); int IE=1; double NL = NI/12 +1; if(NI%12 == 0){NL = NI/12;} for(int L = 1; L<= NL ;L++){ int IS = IE; IE = min(NI, IS+11); int i = IS; printf("i= %d , IS = %d, IE = %d", i, IS, IE); for(int j = NJ; j>=1; j--){ printf("%lf, %lf, %lf\n", FI[LI[i]+j], i=IS, IE); } } return; }
JavaScript
UTF-8
686
3.125
3
[ "Unlicense" ]
permissive
function Ack(m, n) { if (m == 0) { return n + 1; } else if(n == 0) { return Ack(m - 1, 1); } else { return Ack(m - 1, Ack(m, n - 1)); } } let inicio = process.hrtime(); inicio = inicio[1]; let inicioRuntime = process.memoryUsage().heapUsed; // let resultado = Ack(1, 1); // let resultado = Ack(1, 2); let resultado = Ack(2, 1); // let resultado = Ack(2, 2); // let resultado = Ack(3, 1); // let resultado = Ack(3, 2); //let resultado = Ack(3, 2); let fim = process.hrtime(); fim = fim[1]; let fimRuntime = process.memoryUsage().heapUsed; console.log(resultado); console.log(fim - inicio); console.log(fimRuntime - inicioRuntime);
C++
UTF-8
398
3.046875
3
[]
no_license
#pragma once #include <string> class Ratio { public: Ratio(const std::string &string) { if (string == "-") { c = -INF; } else if (string == "+") { c = INF; } else { c = std::stod(string); } } Ratio() = default; [[nodiscard]] bool match(double) const ; private: double c = 0; double INF = 1 << 16; };
Python
UTF-8
1,866
2.890625
3
[]
no_license
from .base_object import * import datetime as dt class Person(BaseObj): # _id = None _login = None _surname = None _forename = None _dob = None _gender = None _phone = None def __init__(self, **init_dict): super(Person, self).__init__() if init_dict is None: return self._login = init_dict['login'] self._surname = init_dict['surname'] self._forename = init_dict['forename'] self._phone = init_dict['phonenumber'] self._dob = init_dict['dob'] self._gender = init_dict['gender'] # if "personid" in init_dict: # self._id = init_dict['personid'] def to_dict(self) -> dict: return {'login': self._login, 'surname': self._surname, 'forename': self._forename, 'dob': self._dob, 'gender': self._gender, 'phonenumber': self._phone} # def get_id(self): return self._id def get_login(self): return self._login def get_surname(self): return self._surname def get_forename(self): return self._forename def get_dob(self): return self._dob def get_gender(self): return self._gender def get_phone(self): return self._phone # def set_id(self, val): self._id = val def set_login(self, val): self._login = val def set_surname(self, val): self._surname = val def set_forename(self, val): self._forename = val def set_dob(self, val): self._dob = val def set_gender(self, val): self._gender = val def set_phone(self, val): self._phone = val # id = property(get_id, set_id) login = property(get_login, set_login) surname = property(get_surname, set_surname) forename = property(get_forename, set_forename) dob = property(get_dob, set_dob) gender = property(get_gender, set_gender) phone = property(get_phone, set_phone)
Java
UTF-8
987
2.46875
2
[ "MIT" ]
permissive
package org.usfirst.frc.team2503.r2016.subsystem; import org.usfirst.frc.team2503.r2016.subsystem.base.DataSpeedControllerSubsystem; import org.usfirst.frc.team2503.r2016.subsystem.base.DataSubsystem; import edu.wpi.first.wpilibj.SpeedController; public class RhinoTrackSubsystem extends DataSpeedControllerSubsystem { public enum RhinoTrackSubsystemDataKey implements DataSubsystem.SubsystemDataKey { POWER } @Override public void tick() { double power = (double) this.getDataKey(RhinoTrackSubsystemDataKey.POWER); this.set(power); } public void setPower(double power) { this.setDataKey(RhinoTrackSubsystemDataKey.POWER, power); } public RhinoTrackSubsystem(SpeedController _controller) { super(_controller); this.setDataKey(RhinoTrackSubsystemDataKey.POWER, 0.0d); } public RhinoTrackSubsystem(SpeedControllerSubsystemType type, final int channel) { super(type, channel); this.setDataKey(RhinoTrackSubsystemDataKey.POWER, 0.0d); } }
Python
UTF-8
1,223
3.890625
4
[]
no_license
""" 105. Construct Binary Tree from Preorder and Inorder Traversal Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree. """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def buildTree(self, preorder, inorder): """ :type preorder: List[int] :type inorder: List[int] :rtype: TreeNode """ if inorder: tmp = preorder.pop(0) # Root Node idx = inorder.index(tmp) root = TreeNode(inorder[idx]) root.left = self.buildTree(preorder, inorder[:idx]) root.right = self.buildTree(preorder, inorder[idx+1:]) return root """ Runtime: 128 ms, faster than 54.04% of Python online submissions for Construct Binary Tree from Preorder and Inorder Traversal. Memory Usage: 52.5 MB, less than 42.60% of Python online submissions for Construct Binary Tree from Preorder and Inorder Traversal. """
Java
UTF-8
865
2.1875
2
[]
no_license
package kilanny.shamarlymushaf.data.alarms; import android.content.Context; import androidx.room.Database; import androidx.room.Room; import androidx.room.RoomDatabase; import androidx.room.TypeConverters; import kilanny.shamarlymushaf.data.RoomConverters; @Database(entities = {Alarm.class}, version = 1, exportSchema = false) @TypeConverters({ RoomConverters.class }) public abstract class AlarmDb extends RoomDatabase { private static AlarmDb instance; public static AlarmDb getInstance(Context context) { if (instance == null) { Context appContext = context.getApplicationContext(); instance = Room.databaseBuilder(appContext, AlarmDb.class, "alarm-db") .allowMainThreadQueries() .build(); } return instance; } public abstract AlarmDao alarmDao(); }
C++
UTF-8
1,939
2.8125
3
[ "MIT" ]
permissive
#ifndef _graphics #define _graphics #include <stdio.h> #include <stdlib.h> #include <iostream> #include "../qif/qif.hpp" // Cartesian plan origin #define ORIGIN_X -0.1 #define ORIGIN_Y -0.5 // Number of triangles that make up a circle #define CIRCLES_SIDES 300 // Prior probability distribution radius #define PRIOR_RADIUS 0.1f // Main Window dimensions #define WINDOW_WIDTH 800 #define WINDOW_HEIGHT 800 using namespace std; class Point{ public: long double x; long double y; Point(){ this->x = 0.0f; this->y = 0.0f; } Point(long double x, long double y){ this->x = x; this->y = y; } }; // Transforms a prior probability distribution on 3 elements in a barycentric point void dist2BaryCoord(Distribution &prior, Point &p); // Transforms a prior probability distribution on 3 elements in a barycentric point. void dist2BaryCoord(long double x1, long double x2, long double x3, Point &p); /* Transforms a barycentric coordiante in a probability distribution on 3 elements. * The coordinate of p is in screen coordinate. * It returns true if a probability distribution was sucefully generated or false * otherwise. */ bool baryCoord2Dist(Point p, vector<long double> &prob); // Euclidian distance between two points long double euclidianDistance(Point a, Point b); // Transforms a pixel coordinates (window width and height) into screen coordinates (from (-1,-1) to (1,1)) void pixelCoord2ScreenCoord(double x, double y, Point &p, int window_width, int window_height); // Transforms a pixel coordinates (window width and height) into screen coordinates (from (-1,-1) to (1,1)) void screenCoord2PixelCoord(double x, double y, Point &p, int window_width, int window_height); // Creates the array buffer of a circle, including the color as the second attribute void createCircle(double x, double y, double radius, double r, double g, double b, double circleVertices[6 * (CIRCLES_SIDES+2)]); #endif
C++
UTF-8
1,746
3.671875
4
[]
no_license
#pragma once #include<iostream> #include<vector> #include"Container.h" using namespace std; template <typename T> class Stack : public Container<T> { int size; char type; Object<T>* top; public: Stack(); Stack(std::vector<T>& other); bool member(const T& x); void print()const; void push(const T& x); //void remove(const T& x); }; template <typename T> Stack<T>::Stack():size(0),type('S'),top(nullptr){} template <typename T> Stack<T>::Stack(std::vector<T> &other) { Stack(); int i = 0; while (!other.empty()) { push(other[i]); other.erase(other.begin()); } } template<typename T> void Stack<T>::push(const T& x) { if (top == nullptr) { Object<T>* n = new Object<T>(x, nullptr, nullptr); top = n; } else { Object<T>* c = new Object<T>(x, nullptr, nullptr); Object<T>* curr = top; while (curr->nextOb != nullptr) { curr = curr->nextOb; } curr->nextOb = c; c->prevOb = curr; } size++; } /*template <typename T> void Stack<T>::remove(const T& x) { Object<T>* curr = top; if (curr->data == top->data) {top= curr->nextOb; } while (curr != nullptr) { if (curr->data == x) { curr->prevOb->nextOb = curr->nextOb; size--; } curr = curr->nextOb; } }*/ template <typename T> bool Stack<T>::member(const T& x) { Object<T>* curr = top; while (curr) { if (curr->data == x) { cout << "The result of function member is True"<<endl; return true; } else {curr = curr->nextOb; } } cout << "The result of function member is False"<<endl; return false; } template <typename T> void Stack<T>::print()const { Object<T>* curr = top; cout << "Stack: "; while (curr->nextOb) { curr=curr->nextOb; } while (curr) { cout << curr->data<<" "; curr = curr->prevOb; } cout << endl; }
C#
UTF-8
4,426
2.84375
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Calculator { public partial class Calculadora : Form { double num1 = 0; double num2 = 0; char Operacion; public Calculadora() { InitializeComponent(); } private void añadirNumero(string numero) { if (textMain.Text == "0") textMain.Text = ""; textMain.Text += numero; } private void btnZero_Click(object sender, EventArgs e) { var revisar = ((Button)sender); añadirNumero(revisar.Text); } private void btnUno_Click(object sender, EventArgs e) { var revisar = ((Button)sender); añadirNumero(revisar.Text); } private void btnDos_Click(object sender, EventArgs e) { var revisar = ((Button)sender); añadirNumero(revisar.Text); } private void btnTres_Click(object sender, EventArgs e) { var revisar = ((Button)sender); añadirNumero(revisar.Text); } private void btnCuatro_Click(object sender, EventArgs e) { var revisar = ((Button)sender); añadirNumero(revisar.Text); } private void btnCinco_Click(object sender, EventArgs e) { var revisar = ((Button)sender); añadirNumero(revisar.Text); } private void btnSeis_Click(object sender, EventArgs e) { var revisar = ((Button)sender); añadirNumero(revisar.Text); } private void btnSiete_Click(object sender, EventArgs e) { var revisar = ((Button)sender); añadirNumero(revisar.Text); } private void btnOcho_Click(object sender, EventArgs e) { var revisar = ((Button)sender); añadirNumero(revisar.Text); } private void btnNueve_Click(object sender, EventArgs e) { var revisar = ((Button)sender); añadirNumero(revisar.Text); } private void btnPunto_Click(object sender, EventArgs e) { var revisar = ((Button)sender); añadirNumero(revisar.Text); if (!textMain.Text.Contains(".")) { textMain.Text += "."; } } private void operadores(object sender, EventArgs e) { var revisar = ((Button)sender); num1 = Convert.ToDouble(textMain.Text); Operacion = Convert.ToChar(revisar.Tag); textMain.Text = "0"; } private void btnResultado_Click(object sender, EventArgs e) { num2 = Convert.ToDouble(textMain.Text); if (Operacion == '+') { textMain.Text = (num1 + num2).ToString(); num1 = Convert.ToDouble(textMain.Text); } if (Operacion == '-') { textMain.Text = (num1 - num2).ToString(); num1 = Convert.ToDouble(textMain.Text); } if (Operacion == 'x') { textMain.Text = (num1 * num2).ToString(); num1 = Convert.ToDouble(textMain.Text); } if (Operacion == '÷') { textMain.Text = (num1 / num2).ToString(); num1 = Convert.ToDouble(textMain.Text); } } private void btnEliminar_Click(object sender, EventArgs e) { if (textMain.Text.Length > 1) { textMain.Text = textMain.Text.Substring(0, textMain.Text.Length - 1); } else { textMain.Text = "0"; } } private void borrarTodo_Click(object sender, EventArgs e) { textMain.Text = "0"; } private void btnSigno_Click(object sender, EventArgs e) { num1 = Convert.ToDouble(textMain.Text); num1 *= -1; textMain.Text = num1.ToString(); } } }
Java
UTF-8
155
2.65625
3
[]
no_license
package ex4; public class demo { double a,b; demo(double i,double j){ this.a=i; this.b=j; } double average(){ return (a+b)/2; } }
Markdown
UTF-8
1,355
2.78125
3
[ "MIT" ]
permissive
![](https://ga4gh.datainsights.cloud/api?repo=CFCD-exercises/platform_security&empty) # Platform Security ## Topics - Roles & Permissions - Application security groups ## Exercises ### List users in an org called 'my_org' by their assigned roles <details><summary>show</summary> <p> ```bash cf org-users my_org ``` </p> </details> ### Assign the Org Manager role to a user named 'my@user.com' to the org 'my_org' <details><summary>show</summary> <p> ```bash cf set-org-role 'my@user.com' my_org OrgManager ``` </p> </details> ### Remove a user named 'my@user.com' from the Org Manager role in the org 'my_org' <details><summary>show</summary> <p> ```bash cf unset-org-role 'my@user.com' my_org OrgManager ``` </p> </details> ### List users in the 'dev' space of an org called 'my_org' by their assigned roles <details><summary>show</summary> <p> ```bash cf space-users my_org dev ``` </p> </details> ### Assign the Space Developer role to a user named 'my@user.com' in the 'dev' space of the org 'my_org' <details><summary>show</summary> <p> ```bash cf set-space-role 'my@user.com' my_org dev SpaceDeveloper ``` </p> </details> ### Remove a user named 'my@user.com' from the Space Developer role in the 'dev' space of the org 'my_org' <details><summary>show</summary> <p> ```bash cf unset-space-role 'my@user.com' my_org dev SpaceDeveloper ``` </p> </details>
Python
UTF-8
442
3.53125
4
[]
no_license
# http://www.practicepython.org/exercise/2014/03/05/05-list-overlap.html import random #a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] #b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] a = random.sample(range(120), k = 10) b = random.sample(range(101), k = 8) #common = set(a).intersection(set(b)) #clean version of the below common = [] for i in a: if i in b and i not in common: common.append(i) print (a) print (b) print (common)
Java
UTF-8
1,225
2.234375
2
[]
no_license
package com.reiras.reservationmicroservice.repository; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.Optional; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest; import com.reiras.reservationmicroservice.domain.Customer; import com.reiras.reservationmicroservice.util.TestUtils; @DataMongoTest() public class CustomerRepositoryTest { @Autowired private CustomerRepository customerRepository; @Test public void findById_ExistingReservationIdGiven_ShouldReturnReservationMatchingId() throws Exception { Customer savedEntity = customerRepository.save(TestUtils.createRandomCustomer()); assertNotNull(savedEntity); Customer foundEntity = customerRepository.findById(savedEntity.getId()).get(); assertNotNull(foundEntity); assertEquals(savedEntity.getId(), foundEntity.getId()); } @Test public void findById_NoExistingReservationIdGiven_ShouldReturnEmpty() throws Exception { Object foundEntity = customerRepository.findById("-1"); assertEquals(Optional.empty(), foundEntity); } }
Java
UTF-8
5,970
1.71875
2
[]
no_license
/** * Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng) * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.xyz.browser.app.modular.api; import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.collection.CollUtil; import cn.stylefeng.roses.core.base.controller.BaseController; import com.alibaba.fastjson.JSON; import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.xyz.browser.app.core.util.JsonResult; import com.xyz.browser.app.modular.api.dto.PageDto; import com.xyz.browser.app.modular.api.vo.SummaryVo; import com.xyz.browser.app.modular.hbase.model.Transaction; import com.xyz.browser.app.modular.hbase.service.TransactionService; import com.xyz.browser.app.modular.system.model.RankingAsset; import com.xyz.browser.app.modular.system.model.RankingMiner; import com.xyz.browser.app.modular.system.model.Summary; import com.xyz.browser.app.modular.system.model.TxnDaily; import com.xyz.browser.app.modular.system.service.IRankingAssetService; import com.xyz.browser.app.modular.system.service.IRankingMinerService; import com.xyz.browser.app.modular.system.service.ISummaryService; import com.xyz.browser.app.modular.system.service.ITxnDailyService; import com.xyz.browser.app.modular.system.service.impl.SummaryServiceImpl; import lombok.extern.slf4j.Slf4j; import net.sf.ehcache.search.aggregator.Sum; import org.apache.commons.lang3.time.FastDateFormat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.math.BigInteger; import java.util.List; import static sun.misc.Version.print; import static sun.misc.Version.println; @RestController @RequestMapping("/api/vns/stat") @Slf4j public class StatController extends BaseController { private static FastDateFormat sdf = FastDateFormat.getInstance("yyyy-MM-dd"); @Autowired private TransactionService transactionService; @Autowired private ISummaryService summaryService; @Autowired private ITxnDailyService txnDailyService; @Autowired private IRankingAssetService rankingAssetService; @Autowired private IRankingMinerService rankingMinerService; // // public static void main(String[] args) { // Summary s = new Summary(); // s.setTtc("dfs"); // JsonResult jr = new JsonResult().addData(s); // System.out.println(jr); // } @RequestMapping(value = "/summary", method = RequestMethod.GET) public JsonResult summary() { JsonResult result = new JsonResult(); List<Summary> list = summaryService.selectList(new EntityWrapper<>()); if(CollUtil.isNotEmpty(list)){ SummaryVo summaryVo = new SummaryVo(); BeanUtil.copyProperties(list.get(0),summaryVo); result.addData(summaryVo); } String circulation = rankingAssetService.selectCirculation(); result.addData("circulation",circulation); return result; } @RequestMapping(value = "/txnDailyRecent", method = RequestMethod.GET) public JsonResult txnDailyRecent () { List<TxnDaily> list = txnDailyService.selectList(new EntityWrapper<TxnDaily>().orderBy("day",false).last("limit 14")); return new JsonResult().addData("txnDaily",list); } @RequestMapping(value = "/rankAsset", method = RequestMethod.POST) public JsonResult rankAsset (@RequestBody PageDto pageDto) { BigInteger page = new BigInteger(pageDto.getPage()).subtract(BigInteger.ONE); BigInteger limit = new BigInteger(pageDto.getLimit()); if(page.intValue()<0 || limit.intValue() > 200){ return new JsonResult(); } BigInteger offset = page.multiply(limit); EntityWrapper ew = new EntityWrapper<RankingAsset>(); int total= rankingAssetService.selectCount(ew); List<RankingAsset> list = rankingAssetService.selectList(ew.orderBy("rank").last("limit "+offset+","+limit)); int size ; if(total % limit.intValue() == 0){ size = total/limit.intValue(); }else{ size = total/limit.intValue()+1; } return new JsonResult().addData("ranks",list).addData("total",String.valueOf(total)).addData("size",String.valueOf(size)); } @RequestMapping(value = "/rankMiner", method = RequestMethod.POST) public JsonResult rankMiner (@RequestBody PageDto pageDto) { BigInteger page = new BigInteger(pageDto.getPage()).subtract(BigInteger.ONE); BigInteger limit = new BigInteger(pageDto.getLimit()); if(page.intValue()<0 || limit.intValue() > 200){ return new JsonResult(); } BigInteger offset = page.multiply(limit); EntityWrapper ew = new EntityWrapper<RankingAsset>(); int total= rankingMinerService.selectCount(ew); List<RankingMiner> list = rankingMinerService.selectList(ew.orderBy("rank").last("limit "+offset+","+limit)); int size ; if(total % limit.intValue() == 0){ size = total/limit.intValue(); }else{ size = total/limit.intValue()+1; } return new JsonResult().addData("ranks",list).addData("total",String.valueOf(total)).addData("size",String.valueOf(size)); } }
C
UTF-8
2,365
3.53125
4
[]
no_license
#include <time.h> #include <string.h> #include <assert.h> #include "cache.h" #define CACHE_SIZE 50 #define URL_SIZE 100 typedef struct CacheBlock{ char* url; char* content; int content_length; time_t last_accessed; } *CacheBlock; struct T { CacheBlock cache[CACHE_SIZE]; int total_elements; }; CacheBlock returnCacheBlock(CacheBlock cblock, char* url); void removeLastAccessed(Cache cache); Cache createCache(){ Cache new_cache = malloc(sizeof(*new_cache)); new_cache->total_elements = 0; for(int i = 0; i < CACHE_SIZE; i++){ new_cache->cache[i] = NULL; } return new_cache; } CacheBlock createCacheBlock(){ CacheBlock block = malloc(sizeof(*block)); block->last_accessed = time(NULL); return block; } void insertToCache(Cache cache, char* url, char* content, int content_length){ CacheBlock block = createCacheBlock(); block->url = malloc(URL_SIZE); block->content = malloc(content_length); block->content_length = content_length; memcpy(block->url, url, URL_SIZE); memcpy(block->content, content, content_length); cache->cache[cache->total_elements] = block; cache->total_elements += 1; } void removeLastAccessed(Cache cache){ time_t last_accessed = time(NULL); int index = 0; for(int i = 0; i < cache->total_elements; i++){ CacheBlock block = cache->cache[i]; time_t block_access = block->last_accessed; if(block_access < last_accessed){ last_accessed = block_access; index = i; } } cache->total_elements -= 1; CacheBlock block = cache->cache[index]; cache->cache[index] = cache->cache[cache->total_elements]; cache->cache[cache->total_elements] = NULL; free(block); } char* getFromCache(Cache cache, char* url){ int total_elements = cache->total_elements; for(int i = 0; i < total_elements; i++){ if( strcmp( cache->cache[i]->url, url) == 0 ){ return cache->cache[i]->content; } } return NULL; } /* returns -1 if url not found */ int content_size(Cache cache, char* url) { int total_elements = cache->total_elements; for(int i = 0; i < total_elements; i++){ if( strcmp( cache->cache[i]->url, url) == 0 ){ return cache->cache[i]->content_length; } } return -1; }
Java
UTF-8
575
1.921875
2
[]
no_license
package com.sisdent.repository.helper.produto; import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import com.algaworks.brewer.dto.ProdutoDTO; import com.algaworks.brewer.dto.ValorItensEstoque; import com.sisdent.model.Produto; import com.sisdent.repository.filter.ProdutoFilter; public interface ProdutosQueries { public Page<Produto> filtrar(ProdutoFilter filtro, Pageable pageable); public List<ProdutoDTO> porCodigoOuNome(String codigoOuNome); public ValorItensEstoque valorItensEstoque(); }
JavaScript
UTF-8
3,144
3
3
[]
no_license
/** * ****************IMPORTS ********************************* */ const express = require("express"); const cors = require("cors"); const { getUID, getPhoto } = require("./Services/lookup"); /** * *****************SET-UP SERVER *************************** */ const server = express(); server.use(cors()); server.use(express.urlencoded({ extended: true })); server.use(express.json()); //create a body property for the req.body /** * *****************SET-UP PORT ******************************* */ const PORT = process.env.PORT || 3000; //make our server listen on a port server.listen(PORT, () => console.log("Server on")); /** * *****************SET-UP DATABASE *************************** */ const { db } = require("./Database"); /** * *****************ROUTES ****************************** */ /** * ***************** READ / GET ROUTES ******************************** * READ / GET => db : READ */ server.get("/", (req, res) => { res.send(db); }); /** * *****************CREATE / POST ROUTES ******************************** * CREATE / POST => db : CREATE * expects{name, location, description?} * before we create a destination in our db, we will get a photo of that destination from * unsplash */ server.post("/", async (req, res) => { let found = false; const { name, location, description } = req.body; if (!name || !location) return res.status(400).json({ error: "message" }); const uid = getUID(); // generate a UID const photo = await getPhoto(name); //get picture from unsplash db.push({ uid, name, photo, location, description: description || "", }); res.send({ uid }); console.log(db); // console.log("post /"); // console.log(req.body); }); /** * ***************** UPDATE / PUT ROUTES ******************************** * UPDATE : PUT /?uid * expects{name. location, description?} */ server.put("/", async (req, res) => { const { uid } = req.query; if (!uid || uid.length !== 6) return res.status(400).json({ error: "uid is required" }); found = true; const { name, location, description } = req.body; if (!name && !location & !description) { return res .status(400) .json({ error: "we need at least one property to update" }); } for (let i = 0; i < db.length; i++) { const dest = db[i]; if (dest.uid === uid) { dest.description = description ? description : dest.description; dest.location = location ? location : dest.location; if (name) { const photo = await getPhoto(name); dest.name = name; dest.photo = photo; } break; } } console.log(db); res.send({ sucess: "true" }); }); /** * ***************** DELETE ROUTES ******************************** * //DELETE :DELETE /?uid */ server.delete("/", (req, res) => { let found = false; const { uid } = req.query; for (let i = 0; i < db.length; i++) { const dest = db[i]; if (dest.uid === uid) { db.splice(i, 1); break; } if (found) return res.send({ status: "found and Deleted" }); return res.send({ status: "not found" }); } res.send(db); });
PHP
UTF-8
436
2.6875
3
[]
no_license
<?php namespace model; use \library\Session as Session; use \library\Database as Database; class Model { protected $database; public function __construct($session = false, $database = false) { if ($session === true) { new Session(43200, false, 64800); } if ($database === true) { $this->database = new Database('localhost', '8889', 'captions', 'root', 'root'); } } } ?>
C#
UTF-8
1,836
2.59375
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class GameController : MonoBehaviour { [SerializeField] private Text gameOverText; [SerializeField] private Text restartText; [SerializeField] private Text timeText; [SerializeField] private Text warningText; [SerializeField] private Text lifeText; private bool gameOver; private bool restart; private float startTime; private float amountOfLife; // Use this for initialization void Start () { gameOver = false; restart = false; restartText.text = ""; gameOverText.text = ""; warningText.text = ""; startTime = Time.time; amountOfLife = 3; lifeText.text = "Life: " + amountOfLife; } // Update is called once per frame void Update () { //reload the current scene at restart -> ! if new scene change name to given scene if(restart){ if(Input.GetKey(KeyCode.F)){ SceneManager.LoadScene(SceneManager.GetActiveScene().name); } } if(gameOver){ restartText.text = "You failed to save your Planet - Try again with 'F'"; restart = true; } //stop time when game is over if(gameOver){ return; } else { float t = Time.time - startTime; string minutes = ((int) t / 60).ToString(); string seconds = (t % 60).ToString("f0"); timeText.text = minutes + " min & " + seconds + " sec"; } } public void GameOver(){ // gameOverText.text = "You died"; gameOver = true; // Time.timeScale = 0; //tried to pause game while dead } public void Warning(){ // Debug.Log("Warning"); warningText.text = "Warning! You've been hit - The Alien substance makes the planet grow"; } public void LifeBar(){ amountOfLife = amountOfLife - 1; Debug.Log(amountOfLife); lifeText.text = "Life: " + amountOfLife; } }
C#
UTF-8
1,464
2.90625
3
[]
no_license
using MyPropertiesMachine.Data; using MyPropertiesMachine.Entities; using System; namespace MyPropertiesMachine.Business { public class MachineBL { //Obtiene información de maquina y consume capa de datos para almacenar en BD. Retorna entidad de tipo maquina. public Machine GetMachineProperties() { //Capturamos datos de maquina. Machine machine = new Machine(); machine.MachineName = Environment.MachineName; machine.UserDomain = Environment.GetEnvironmentVariable("USERDOMAIN") ?? Environment.GetEnvironmentVariable("HOSTNAME"); machine.SO = Environment.OSVersion.VersionString; machine.IP = MonitorMachineHardwareBL.GetIPAddressMachine(); machine.HardDisk = MonitorMachineHardwareBL.GetHardDiskProperties(); machine.RAM = MonitorMachineHardwareBL.GetMemoryRAMProperties(); machine.CPU = MonitorMachineHardwareBL.getCPUProperties(); //insertamos registro en BD new MachineDAL().InsertMachineProperties(machine); return machine; } //Genera el archivo txt en disco local. public string DownloadFileFlat(string prmIPAddress, string prmFileName) { var machinePropertiesList = new MachineDAL().GetMachinePropertiesByIP(prmIPAddress); return FileMachineBL.generateFileFlat(prmFileName, machinePropertiesList); } } }
Java
UTF-8
540
2.4375
2
[]
no_license
package EntitySets; import poj.EntitySet.*; import Resources.GameResources; import Resources.GameConfig; import poj.linear.*; import poj.Render.ImageRenderObject; import Components.*; /** * Power-up to allow the player to do more damage * @author Alex * @version 1.0 - 03/18/19 */ public class PowerUp extends CollectibleSet { public PowerUp(float x, float y) { super(x, y, GameConfig.PICKUP_COLLISION_BODY, GameResources.powerupImage); } public PowerUp(Vector2f posVector) { this(posVector.x, posVector.y); } }
Markdown
UTF-8
2,161
2.609375
3
[ "Apache-2.0" ]
permissive
--- layout: layout.pug navigationTitle: dcos edge-lb show title: dcos edge-lb show menuWeight: 54 excerpt: Reference for the dcos edge-lb show command enterprise: false --- Use this command to show the pool definition for a given pool name. If you don't specify a pool name, the command returns information for all pool configurations. You can also use this command to convert YAML files to their equivalent JSON format. If you have configuration files previously written using YAML, you should use this command to convert the configuration settings to their equivalent JSON format. ## Usage ***%%% is the sample command missing the [ < flags > ] component?*** ```bash dcos edgelb show <pool-name> [options] ``` ## Options | Name, shorthand | Description | |-----------------|-------------| | `--help, -h` | Display usage information. | | `--verbose, -v` | Enable additional logging of requests and responses. | | `--name="<name>"` | Specify the name of the service instance to query. | | `--reference` | Display the configuration reference. | | `--convert-to-json=<pool-file>` | Converts local YAML file to JSON. | | `--json` | Show unparsed JSON response. | <!--### Permissions--> ## Examples To display the pool definition information for the ping-lb Edge-LB pool, use the command: ```bash dcos edgelb show ping-lb ``` The command returns information similar to the following: ```bash Summary: NAME ping-lb APIVERSION V2 COUNT 5 ROLE slave_public CONSTRAINTS hostname:UNIQUE STATSPORT 0 Frontends: NAME PORT PROTOCOL frontend_0.0.0.0_15001 15001 HTTP Backends: FRONTEND NAME PROTOCOL BALANCE frontend_0.0.0.0_15001 ping-backend HTTP roundrobin Marathon Services: BACKEND TYPE SERVICE CONTAINER PORT CHECK ping-backend AUTO_IP /ping pong-port enabled Mesos Services: BACKEND TYPE FRAMEWORK TASK PORT CHECK ``` To convert a YAML configuration file to JSON and output the results to standard output (`stdout`), use the command: ```bash dcos edgelb show --convert-to-json=/path/to/yaml ```
Python
UTF-8
1,713
3.296875
3
[]
no_license
import random import math import matplotlib.pyplot as plt numnodes = 500 q = 3 graph = [[0 for node in xrange(numnodes)] for node in xrange(numnodes)] degrees = [0 for node in xrange(numnodes)] def init_clique(graph, q): for i in xrange(2*q + 1): for j in xrange(2*q + 1): if i != j: graph[i][j] = 1 def add_vertex(graph, i): counter = 0 while counter < q: vertex = random.randint(0, i) if vertex != i and graph[i][vertex] == 0 and graph[vertex][i] == 0: graph[i][vertex] = 1 graph[vertex][i] = 1 counter += 1 def create_graph(graph): init_clique(graph, q) for i in xrange(2*q + 2, numnodes): add_vertex(graph, i) def calculate_degrees(graph): for i in xrange(numnodes): degrees[i] = sum(graph[i]) def mean(degrees): return float(sum(degrees))/float(numnodes) def median(degrees): sorted_degrees = sorted(degrees) return float(degrees[249]+degrees[250])/2. create_graph(graph) calculate_degrees(graph) # print degrees # print "sum = " + str(mean(degrees)) # print "median = " + str(median(degrees)) # print "max = " + str(max(degrees)) # print "min = " + str(min(degrees)) def distribution(degrees): distr = [0.0 for node in xrange(max(degrees))] for i in xrange(max(degrees)): distr[i] = float(degrees.count(i))/float(numnodes) return distr def poisson(degrees): distr = [0.0 for node in xrange(max(degrees))] for i in xrange(max(degrees)): distr[i] = math.exp(-1. * mean(degrees)) * ( math.pow(mean(degrees), i ) / float(math.factorial(i)) ) return distr plt.plot(range(max(degrees)), distribution(degrees), 'r-') # plt.plot(range(max(degrees)), poisson(degrees), 'b-') plt.xscale('log') plt.yscale('log') plt.xlim([3, max(degrees)+1]) plt.show()
Python
UTF-8
2,588
3.0625
3
[]
no_license
#!/usr/bin/env python """ Pong | . | """ import field import weapon import sprites import key class Game(object): def __init__(self): self.time = 0 self.tick = 0 self.is_running = False self.players = [] self.zombies = [] self.scores = [] self.collidables = {} for x in range(4): self.collidables['quadrant_%d' % (x+1)] = [] self.key = key.Key.key # err.. class Pong(Game): def __init__(self): pass def rules(self): return """ PONG A player on each side of the screen is able to go up and down in order to prevent the opposing player from bouncing the one ball on the field into their side. | | player 1 | | | player 1's ----> | | | <---- goal | | o | | | | | | | <----- player 2's | | | player 2 goal ----> | | | | | | | | """ def setup_game(self, players=1): for x in range(players): paddle = self.new_paddle() self.players.append(paddle) for x in range(players, 2): enemy_paddle = self.new_paddle() self.zombies.append(enemy_paddle) self.scores = [0 for x in range(2)] # these twos might change self.zombies.append(new_ball()) def new_paddle(self): return particle.Block(image="[]", width="5") def new_ball(self): return particle.Ball() def paddle_control(self, paddle, keystroke=None): current_x = paddle.x current_y = paddle.y if keystroke: if keystroke == self.key['up']: paddle.y -= 1 elif keystroke == self.key['down']: paddle.y += 1 if self.collided(paddle): paddle.y = current_y def ball_control(self, ball): current_x = ball.x current_y = ball.y bounce = self.collided(ball) if bounce: # bounce is a point pass # .... pause # .... need to do work work
Java
UTF-8
862
1.96875
2
[]
no_license
package it.gov.pagopa.hubpa.payments.mock; import it.gov.pagopa.hubpa.payments.model.partner.CtReceipt; import it.gov.pagopa.hubpa.payments.model.partner.PaSendRTReq; import it.gov.pagopa.hubpa.payments.model.partner.StOutcome; public class PaSendRTReqMock { public final static PaSendRTReq getMock() { CtReceipt receipt = new CtReceipt(); receipt.setReceiptId("c110729d258c4ab1b765fe902aae41d6"); receipt.setNoticeNumber("311111111112222222"); receipt.setFiscalCode("77777777777"); receipt.setOutcome(StOutcome.OK); receipt.setCreditorReferenceId("11111111112222222"); PaSendRTReq mock = new PaSendRTReq(); mock.setIdBrokerPA("77777777777"); mock.setIdPA("77777777777"); mock.setIdStation("77777777777_01"); mock.setReceipt(receipt); return mock; } }
C++
UTF-8
693
2.65625
3
[ "MIT" ]
permissive
// Copyright (c) 2018 The Kore Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef KORE_SUPPORT_CSVROW_H #define KORE_SUPPORT_CSVROW_H #include <fstream> #include <iostream> #include <iterator> #include <sstream> #include <string> #include <vector> class CSVRow { public: std::string const& operator[](std::size_t index) const; std::size_t size() const; std::istream& readNextRow(std::istream& str, char separator = ','); void operator<<(std::istream& str); private: std::vector<std::string> m_data; char m_separator; }; #endif // KORE_SUPPORT_CSVROW_H
C++
UTF-8
585
3.125
3
[ "Unlicense" ]
permissive
/* * @lc app=leetcode id=35 lang=cpp * * [35] Search Insert Position */ // @lc code=start #include <vector> using namespace std; class Solution { public: int searchInsert(vector<int> &nums, int target) { auto lhs = nums[0]; if (target <= lhs) { return 0; } if (target > nums[nums.size() - 1]) { return nums.size(); } for (std::size_t i = 1; i < nums.size(); i++) { const auto rhs = nums[i]; if ((rhs == target) || (lhs < target && target < rhs)) { return i; } } return nums.size(); } }; // @lc code=end
Python
UTF-8
154
4.03125
4
[]
no_license
def fact(n): f = 1 for i in range(1,n+1): f*=i; return(f) n = int(input("-----FACTORIAL-----\nEnter the value of n: ")) print(n,"! = ",fact(n))
Java
UTF-8
2,164
3.578125
4
[]
no_license
import java.util.HashSet; import java.util.Set; /* https://leetcode.com/problems/continuous-subarray-sum/ Given a list of non-negative numbers and a target integer k, write a function to check if the array has a continuous subarray of size at least 2 that sums up to a multiple of k, that is, sums up to n*k where n is also an integer. */ public class CheckSubarraySum { public static boolean find(int[] nums, int k) { // edge case checks if ( nums.length < 2 ) return false; for ( int i = 1; i < nums.length ; ++i){ // zeres are multiples of everything including zeros, n*k=0 if ( nums[i-1] == 0 && nums[i] == 0 ) return true; } // only zero is a multiple of zero if ( k == 0 ) return false; Set<Integer> prefixSet = new HashSet<>(); int prefixSum = nums[0]; prefixSet.add(nums[0]); // numbers are positive but k does not have to be positive. 10 is multiple of -5. -5 * -2=10, n=-2 k=Math.abs(k); for ( int i = 1; i < nums.length; ++i){ prefixSum += nums[i]; // check for current [2,4] k = 6, should pass if ( prefixSum % k == 0 ) return true; for( int multipleK = k; multipleK < prefixSum; multipleK += k) { // don't include just added multipleK e.g [2,12] k=6, should fail, if ( nums[i] == multipleK ) continue; // check for all multiples of k if ( prefixSet.contains( prefixSum - multipleK ) ){ return true; } } prefixSet.add(prefixSum); } return false; } public static void main(String[] args){ // int[] arr = Stream.of(args[0].split("[\\s,]+")).mapToInt(Integer::parseInt).toArray(); // int[] arr = {11,5,7}; //// int k = 0; // int[] nums = {23,6,9}; // int k = 6; // int[] nums = {23,2,6,4,7}; // int k = -6; // int[] nums = {1,2,4,7}; // int k = 6; int[] nums = {0,1,0}; int k = -1; System.out.println(find(nums,k)); } }
Java
UTF-8
564
3.25
3
[]
no_license
package top.sde.util; import java.util.Scanner; /** * Hello world! * */ public class Example { public static void main( String[] args ) { Scanner scan = new Scanner(System.in); while (true) { System.out.println("Please input a line to find the max length word or Enter/Return to quit:"); String line = scan.nextLine(); System.out.println(MaxLenWord.matchLine(line)); System.out.println(""); if (line.length() == 0) { break; } } System.out.println( "" ); scan.close(); } }
Python
UTF-8
579
2.953125
3
[]
no_license
import re import requests from bs4 import BeautifulSoup def url_to_soup_converter(url): #Some header settings to get everything in english, with US IP headers = {'Accept-Language': 'en','X-FORWARDED-FOR': '2.21.184.0'} #url request by given url paramter and soup conversion url_request = requests.get(url, headers=headers) soup = BeautifulSoup(url_request.text,features="html.parser") return soup def get_name(url): my_soup = url_to_soup_converter(url) return my_soup.find_all('span',attrs={'class': 'itemprop'})[0].contents[0] #Get actors
Markdown
UTF-8
1,776
3.40625
3
[]
no_license
# CONTENTS * [Headings](#headings) * [Styling](#styling) * [Blocks](#blocks) * [Links](#links) * [Lists](#lists) * [Dividers](#dividers) * [Tables](#tables) # HEADINGS Denoted by strings of `#` ``` # Size 1 ## Size 2 ### Size 3 #### Size 4 ##### Size 5 ###### Size 6 ``` # Size 1 ## Size 2 ### Size 3 #### Size 4 ##### Size 5 ###### Size 6 # STYLING **Strong** with `** **` __Strong__ with `__ __` *Italics* with `* *` _Italics_ with `_ _` ~~Strike~~ with `~~ ~~` # BLOCKS ### Quotes ``` > This is > a quoted > block of text ``` > This is > a quoted > block of text ### Code Individual commands like `git status` can be marked inline or in blocks. Mark them with ``` backticks ``` git status git add * git commit -m 'Test message' ``` # LINKS ### Hyperlinks ``` [ link to github homepage](https://github.com) ``` [ link to github homepage](https://github.com) ### Section Links ``` [section](#headings) ``` Links to a [section](#headings) ### Relative Links ``` [text](file/path) ``` See the document linked within this repo [here](docs/hi.md) # LISTS `-` List: - Item 1 - Item 2 - Item 3 `*` List: * Item 1 * Item 2 * Item 3 Number List: 1. This 2. is 3. too 4. obvious Task List: ``` - [x] Check - [ ] No-check ``` - [x] Done - [ ] Not Done # DIVIDERS Use 3-ofs to make Equals === Hyphens --- Asterisks *** Underscores ___ # TABLES Colons can optionaly be used to specify alignment ``` TITLE | Stuff | Things | Items --- | --- | --- | --- Item 1 | Yes | Yes | Yes Item 2 | Yes | Sure | Why Not? Object 1 | Nope | Nope | Nope Object 2 | Never | Say | Never ``` TITLE | Stuff | Things | Items --- | --- | --- | --- Item 1 | Yes | Yes | Yes Item 2 | Yes | Sure | Why Not? Object 1 | Nope | Nope | Nope Object 2 | Never | Say | Never
Java
UTF-8
1,000
2.484375
2
[]
no_license
package by.bsuir.ddjames.techrepair.dao.impl; import by.bsuir.ddjames.techrepair.dao.entity.Client; import by.bsuir.ddjames.techrepair.util.HibernateUtil; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.criterion.Restrictions; public class ClientDao extends EntityDao<Client> { public ClientDao() { super(new Client()); } public Client getByLogin(String login) { Client client = null; try { session = HibernateUtil.openSession(); session.beginTransaction(); List<Client> list = session.createCriteria(Client.class).add(Restrictions.eq("login", login)).list(); if (!list.isEmpty()) { client = list.get(0); } session.getTransaction().commit(); } catch (HibernateException e) { this.session.getTransaction().rollback(); } finally { session.close(); } return client; } }
Python
UTF-8
948
3.34375
3
[ "MIT" ]
permissive
import abc class NatBase(object): @abc.abstractmethod def clear(self): raise NotImplementedError @abc.abstractmethod def unify(self, t): raise NotImplementedError @abc.abstractmethod def subst(self): raise NotImplementedError class NatLiteral(NatBase): def __init__(self, n): self.n = n def clear(self): pass def unify(self, t): return isinstance(t, NatLiteral) and t.n == self.n def subst(self): return self class NatVariable(NatBase): _nat = None def clear(self): NatVariable._nat = None def unify(self, other): assert isinstance(other, NatBase) if NatVariable._nat is not None: return NatVariable._nat.unify(other) else: NatVariable._nat = other return True def subst(self): assert NatVariable._nat is not None return NatVariable._nat
Markdown
UTF-8
3,920
2.578125
3
[]
no_license
# 5. Thymeleaf 사용법 ## Thymeleaf 사용법 기존의 JSP에서 벗어나 템플릿 기반의 화면 처리가 지원된다. 따라서 FreeMarker , Mustache, Thymeleaf를 이용해 확장자가 html인 페이지를 개발할 수 있다. ### Tymeleaf를 이용하기 위해 필요한 사항 1. 별도의 라이브러리\(STS4 에서 프로젝트 생성시에 추가하면 됨\) 2. application.properties에 필요한 설정 이유 : Thymeleaf로 개발된 화면을 수정하면 매번 프로젝트를 재시작해야되기 때문에 서버 내부에 Cache 보관 못하게 끄자. ```text spring.thymeleaf.cache=false ``` Thymleaf는 html 파일에서 추가 해야될 것 ```text <html xmlns:th="http://www.thymeleaf.org"> 생략 ... </html> ``` 1. 페이지 수정시에 DevTools 를 추가하고 쓰자 자동으로 스프링부트를 재시작 해주기때문에 사용함. 1. Thymeleaf 플러그인 설치하기 자체 기능을 사용하기 위해서는 템플릿 코드를 쓰면되지만 좀 더 편하게 활용하려면 추가 플러그인이 필요하다. 설치관련 사이트 : [thymeleaf github](https://github.com/thymeleaf/thymeleaf-extras-eclipse-plugin) 해당사이트에서 URL 을 보고 STS4 -&gt; help -&gt; install new softwares New Repository -&gt; name : thymeleaf , location : 사이트에 나옴 -&gt; 라이센스 동의 -&gt; reboot ## Model 파라미터 전달법 thymeleaf 는 Controller에서 Model을 이용하여 attribute를 전달할 수 있다. * Controller ```text @GetMapping("/1") public void sample(Model model){ MemberVO vo = new MemberVO(p1,p2,p3); model.addAttribute("member",vo); } ``` * View ```text <h1 th:text="${vo}"></h1> ``` ## each 문을 통해서 얻을 수 있는 점 ```text <tr th:each="memeber : ${list}"> <td th:text="${member.mid}"></td> </tr> ``` 아래의 요소들 추가가능 ```text <tr th:each="memeber, iterState : ${list}"> <td th:text="${member.mid}"></td> <td th:text="${iterState.size}></td> // 대상의 size <td th:text="${iterState.index}></td> // 대상의 인덱스번호 <td th:text="${iterState.odd or even}></td> // 짝 홀 <td th:text="${iterState.first or last}></td> // 첫번째 마지막 </tr> ``` ## Thymeleaf 의 유틸리티 객체 * 기본 표현식 객체 * **ctx** * **vars** * **locale** * **httpServletRequest** * **httpSession** * 표현식 유틸 객체 * **dates** * **calendars** * **numbers** * **strings** * **objects** * **bools** * **arrays** * **lists** * **sets** * **maps** * **aggregates** * **messages** ### 유틸객체 사용법 Controller ```text model.addAttribute("now",new Date()); ``` View ```text <h2 th:text="${#dates.format(now,'yyyy-mm-dd')}"></h2> <div th:with="timeVal=${#dates.createToday()}"> <p>[[${timeVal}]]</p> </div> ``` ### thymeleaf 링크 처리 WAS 상 경로를 줄때 '/'을 중심으로 둘 경우가 있기 때문에 문제가 발생할 수 있다. Thymeleaf는 경로 처리문제를 해결하기 위해 @{} 을 사용한다. 장점은 현재경로를 기반으로 해서 일처리를 진행한다. 절대경로로 처리하고 싶으면 안에다가 절대경로를 지정해도 된다. 현재 경로 : /test ```text 1. @{/sample1} => /test/sample1 2. @{~/sample1} => /sample1 ``` 현재 경로 : / ```text 1. @{/sample1} => /sample1 2. @{~/sample1} => /sample1 ``` * Get 방식 파라미터 전달방법 ```text @{/sample1(p1='aaa')} => /sample1?p1='aaa' ``` ## thymeleaf 레이아웃 기능 ```text https://html5boilerplate.com/ 에서 레이아웃 재사용을 위한 탬플릿을 사용할 수 있음. <!-- https://mvnrepository.com/artifact/nz.net.ultraq.thymeleaf/thymeleaf-layout-dialect --> <dependency> <groupId>nz.net.ultraq.thymeleaf</groupId> <artifactId>thymeleaf-layout-dialect</artifactId> <version>2.2.1</version> </dependency> ```
Python
UTF-8
204
3.46875
3
[]
no_license
def isPalindrome(string): # Write your code here. reverse_chars = [] for i in reversed(range(len(string))): reverse_chars.append(string[i]) return "".join(reverse_chars) == string
Python
UTF-8
944
3.015625
3
[]
no_license
from scipy.special import comb dp = {} def main(): k = 7 X = 150 p = 0.51 E = 0.0 for x in range(X + 1): tmp = (k + 2 * x + 2) * combinations(k + 1, x) tmp *= (p ** (k + x + 2)) tmp *= ((1 - p) ** x) E += tmp print(E) def combinations(ahead, X): ''' ahead means how many blocks of the initial chain is ahead of the attacker's new chain x means how many blocks will be linked to the initial chain ''' if X == 0: return 1 has_key = False if ahead in dp.keys(): has_key = True if X in dp[ahead].keys(): return dp[ahead][X] res = 0 for x in range(1, X + 1): if x > ahead + 1: break res += comb(ahead + 1, x) * combinations(2 * x - 1, X - x) if has_key: dp[ahead][X] = res else: dp[ahead] = {X: res} return res if __name__ == '__main__': main()
C#
UTF-8
758
3.125
3
[]
no_license
using Lingua.Core.Extensions; namespace Lingua.Core.Tokens { public abstract class Word : Element { public int VariationIndex { set => Modifiers |= GetVariationModifier(value); } protected virtual Modifier GetVariationModifier(int variationIndex) => Modifier.None; public bool PossibleAbbreviation { get; set; } public override Token Capitalize() => Clone(Value.Capitalize()); public override Token Decapitalize() => Clone(Value.Decapitalize()); public Word Clone(string newValue = null) { var clone = (Word)MemberwiseClone(); clone.Value = newValue ?? clone.Value; return clone; } } }
Java
UTF-8
687
2.625
3
[ "Apache-2.0" ]
permissive
package com.trunk.rx.jdbc.sql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; /** * A function to defer the creation of {@link PreparedStatement}s so we can * safely manage their lifecycle. * * @see Execute * @see ExecuteQuery * @see ExecuteUpdate */ @FunctionalInterface public interface PreparedStatementBuilder { /** * Return a new {@link PreparedStatement} from the given connection * * @param connection the JDBC connection to use when creating the {@link PreparedStatement} * @return a new PreparedStatement * @throws SQLException */ PreparedStatement build(Connection connection) throws SQLException; }
C
UTF-8
1,838
2.75
3
[ "BSD-2-Clause" ]
permissive
/** * Copyright (C) 2017, Hao Hou **/ #include <testenv.h> runtime_servlet_binary_t* binary; runtime_servlet_t* servlet; runtime_task_t* task; int task_started = 0; static void trap(int id) { if(id == 0) { task = runtime_task_current(); } else if(id == 1) { task = runtime_task_current(); if(task->flags == (RUNTIME_TASK_FLAG_ACTION_EXEC | 3 | RUNTIME_TASK_FLAG_ACTION_INVOKED)) { LOG_DEBUG("Successfully verified the task"); task_started = 1; } else { LOG_ERROR("Wrong task flags"); } } else if(id == 2) { task = runtime_task_current(); LOG_DEBUG("Unload has been called"); } } int test_get_current_task(void) { const char* argv[] = {"task_test"}; ASSERT_OK(runtime_servlet_set_trap(trap), CLEANUP_NOP); const char* path = runtime_servlet_find_binary ("serv_task_test"); LOG_DEBUG("Binary path: %s", path); ASSERT_PTR(path, CLEANUP_NOP); ASSERT_PTR(binary = runtime_servlet_binary_load(path, "task_test", 1), CLEANUP_NOP); expected_memory_leakage(); ASSERT_PTR(servlet = runtime_servlet_new(binary, 1, argv), CLEANUP_NOP); ASSERT_PTR(task, CLEANUP_NOP); return 0; } int test_exec_task(void) { runtime_task_t* task = runtime_task_new(servlet, (RUNTIME_TASK_FLAG_ACTION_EXEC | 3)); ASSERT_PTR(task, CLEANUP_NOP); ASSERT_OK(runtime_task_start(task), runtime_task_free(task)); ASSERT_OK(runtime_task_free(task), CLEANUP_NOP); ASSERT(task_started == 1, CLEANUP_NOP); return 0; } int setup(void) { ASSERT_OK(runtime_servlet_append_search_path(TESTDIR), CLEANUP_NOP); return 0; } int teardown(void) { ASSERT_OK(runtime_servlet_free(servlet), CLEANUP_NOP); ASSERT_OK(runtime_servlet_binary_unload(binary), CLEANUP_NOP); ASSERT_PTR(task, CLEANUP_NOP); return 0; } TEST_LIST_BEGIN TEST_CASE(test_get_current_task), TEST_CASE(test_exec_task) TEST_LIST_END;
C#
UTF-8
1,223
2.5625
3
[]
no_license
public class DisplayNameEnforcingDescriptor : PropertyDescriptor { private PropertyDescriptor _descriptor; public DisplayNameEnforcingDescriptor(PropertyDescriptor descriptor) : base(descriptor) { this._descriptor = descriptor; } public override string Name { get { return string.IsNullOrEmpty(DisplayName) ? base.Name : DisplayName; } } public override bool CanResetValue(object component) { return _descriptor.CanResetValue(component); } public override Type ComponentType { get { return _descriptor.ComponentType; } } public override object GetValue(object component) { return _descriptor.GetValue(component); } public override bool IsReadOnly { get { return _descriptor.IsReadOnly; } } public override Type PropertyType { get { return _descriptor.PropertyType; } } public override void ResetValue(object component) { _descriptor.ResetValue(component); } public override void SetValue(object component, object value) { _descriptor.SetValue(component, value); } public override bool ShouldSerializeValue(object component) { return _descriptor.ShouldSerializeValue(component); } }
Java
UTF-8
649
1.890625
2
[]
no_license
package com.hfut.dao; import com.hfut.entity.ClazzEntity; import com.hfut.entity.CourseEntity; import com.hfut.entity.SelectCourseEntity; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; /** * Created by chenjia on 2017/3/11. */ public interface SelectCourseDao extends JpaRepository<SelectCourseEntity,Integer> { public List<SelectCourseEntity> findByCourseByCourseId(CourseEntity courseEntity); public List<SelectCourseEntity> findByClazzByClassId(ClazzEntity clazzEntity); public SelectCourseEntity findByClazzByClassIdAndCourseByCourseId(ClazzEntity clazzEntity,CourseEntity courseEntity); }
PHP
UTF-8
427
2.546875
3
[]
no_license
<?php namespace Scrapertests\Unit; class CsvTest extends \ScraperTests\Lib\BaseTestCase { public function test_getConverted() { $toConvert = [ ['col1' => 'a,b', 'col2' => 'row1'], ['col1' => 'c' , 'col2' => 'row2'], ]; $filter = new \Scraper\Format\Csv(); $this->assertEquals("col1,col2\n\"a,b\",row1\nc,row2", $filter->getConverted($toConvert)); } }
C
UTF-8
11,682
2.953125
3
[]
no_license
/* * mm-naive.c - The fastest, least memory-efficient malloc package. * * In this naive approach, a block is allocated by simply incrementing * the brk pointer. A block is pure payload. There are no headers or * footers. Blocks are never coalesced or reused. Realloc is * implemented directly using mm_malloc and mm_free. * * NOTE TO STUDENTS: Replace this header comment with your own header * comment that gives a high level description of your solution. */ #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <unistd.h> #include <string.h> #include "mm.h" #include "memlib.h" /********************************************************* * NOTE TO STUDENTS: Before you do anything else, please * provide your team information in the following struct. ********************************************************/ team_t team = { /* Team name */ "Group ", /* First member's full name */ "Eric Brown", /* First member's email address */ "ericbrown1.2018@u.northwestern.edu", /* Second member's full name (leave blank if none) */ "Tyler Rodgers", /* Second member's email address (leave blank if none) */ "TylerRodgers2020@u.northwestern.edu" }; /* single word (4) or double word (8) alignment */ #define ALIGNMENT 8 /* rounds up to the nearest multiple of ALIGNMENT */ #define ALIGN(size) (((size) + (ALIGNMENT-1)) & ~0x7) #define SIZE_T_SIZE (ALIGN(sizeof(size_t))) ///////////////// Additional constants and macros for use //////////////////////// ///////////////// Macros from book, page 830 ///////////////////////////////////// #define WordSize 4 //Number of bytes in word #define DoubleSize 8 //Number of bytes in double word size #define ChunkSize (1<<12) //Size of the chunks for the heap #define ReallocBuffer (1<<7) #define ListMax 20 #define Max(x,y) ((x) > (y) ? (x) : (y)) #define Min(x,y) ((x) < (y) ? (x) : (y)) // our equivalent macro to max #define Pack(size,alloc) ((size) | (alloc)) //allocated bit into word // Write & Read word at p #define Get(p) (*(unsigned int *)(p)) #define Put(p,val) (*(unsigned int *)(p) = (val) | GetTag(p)) // added get tag to book definition #define putNotag(p,val) (*(unsigned int *)(p) = (val)) // our macro based off get and put // Store pointers for free blocks #define SetPointer(p,ptr) (*(unsigned int*)(p) = (unsigned int)(ptr)) //find header and footer given block #define HeadP(bp) ((char *)(bp) - WordSize) #define FootP(bp) ((char *)(bp) + GetSize(HeadP(bp)) - DoubleSize) // get size and allocation from p #define GetSize(p) (Get(p) & ~0x7) #define GetAlloc(p) (Get(p) & 0x1) // get address of next and previous blocks from current block #define NextBlock(bp) ((char *)(bp) + GetSize(((char *)(bp) - WordSize))) #define PrevBlock(bp) ((char *)(bp) - GetSize(((char *)(bp) - WordSize))) ////////////////////// End Book Macros ////////////////////// #define GetTag(p) (Get(p) & 0x2) //grabs tag of block #define PredPtr(ptr) ((char *)(ptr)) //get pointer for predecessor block #define SuccPtr(ptr) ((char *)(ptr) + WordSize) //get pointer for successor block //find address of free block's predecessor and successor on seg list #define pred(ptr) (*(char **)(ptr)) // retrieve dereferenced pointer to free block predecessor #define succ(ptr) (*(char **)(SuccPtr(ptr))) // retrieve dereferenced pointer to free block successor //////////////// End Macros and constants /////////////////////// // Helper Function Decleration static void *extendHeap(size_t size); static void *place(void *ptr, size_t size); static void *coalesce(void *ptr); static void deleteNode(void *ptr); static void insertNode(void *ptr, size_t size); // Global variables void *sfl[ListMax]; // list of free segments to be searched and filled //////////////// Start Helper Functions ///////////////////////// static void *extendHeap(size_t words) { ////////////// from book page 831 ////////////////////// char *ptr; size_t size; size = (words %2) ? (words+1) * WordSize: words * WordSize; if((long)(ptr = mem_sbrk(size)) == -1) return NULL; putNotag(HeadP(ptr),Pack(size,0)); putNotag(FootP(ptr),Pack(size,0)); putNotag(HeadP(NextBlock(ptr)),Pack(0,1)); return coalesce(ptr); ////////////// end book page 831 reference /////////////// } static void insertNode(void *ptr, size_t size){ int list = 0; void *search_ptr =ptr; void *insert_ptr = NULL; //Selected seglist for(list = 0; (list <ListMax-1) && (size>1); list++){ size >>=1; } search_ptr = sfl[list]; while ((search_ptr != NULL) && (size > GetSize(HeadP(search_ptr)))) { insert_ptr = search_ptr; search_ptr = pred(search_ptr); } if (search_ptr == NULL){ if (insert_ptr == NULL){ SetPointer(PredPtr(ptr),NULL); SetPointer(SuccPtr(ptr),NULL); sfl[list] = ptr; } else{ SetPointer(PredPtr(ptr),NULL); SetPointer(SuccPtr(ptr), insert_ptr); SetPointer(PredPtr(insert_ptr),ptr); } }else{ if(insert_ptr == NULL){ SetPointer(PredPtr(ptr), search_ptr); SetPointer(SuccPtr(search_ptr),ptr); SetPointer(SuccPtr(ptr),NULL); sfl[list] = ptr; }else{ SetPointer(PredPtr(ptr), search_ptr); SetPointer(SuccPtr(search_ptr),ptr); SetPointer(SuccPtr(ptr), insert_ptr); SetPointer(PredPtr(insert_ptr),ptr); } } return; } static void deleteNode(void *ptr) { int list; size_t size = GetSize(HeadP(ptr)); for(list =0; (list < ListMax - 1) && (size >1); list++) { size >>=1; } if (pred(ptr) == NULL){ if (succ(ptr) == NULL){ sfl[list] = NULL; } else { SetPointer(PredPtr(succ(ptr)),NULL); } } else { if(succ(ptr) == NULL) { SetPointer(SuccPtr(pred(ptr)),NULL); sfl[list] = pred(ptr); }else{ SetPointer(SuccPtr(pred(ptr)),succ(ptr)); SetPointer(PredPtr(succ(ptr)),pred(ptr)); } } return; } static void *coalesce(void *ptr){ ////////////////////// Book Page 833 ///////////////////// size_t prev_alloc = GetAlloc(FootP(PrevBlock(ptr))); size_t next_alloc = GetAlloc(HeadP(NextBlock(ptr))); size_t size = GetSize(HeadP(ptr)); // Create case value for switch based on 4 potential coalescing cases if(prev_alloc && next_alloc){ return ptr; } else if (prev_alloc && !next_alloc){ size += GetSize(HeadP(NextBlock(ptr))); Put(HeadP(ptr), Pack(size,0)); Put(FootP(ptr),Pack(size,0)); }else if(!prev_alloc && next_alloc){ size += GetSize(HeadP(PrevBlock(ptr))); Put(FootP(ptr),Pack(size,0)); Put(HeadP(PrevBlock(ptr)), Pack(size,0)); ptr = PrevBlock(ptr); }else{ size += GetSize(HeadP(PrevBlock(ptr))) + GetSize(FootP(NextBlock(ptr))); Put(HeadP(PrevBlock(ptr)), Pack(size,0)); Put(FootP(NextBlock(ptr)), Pack(size,0)); ptr = PrevBlock(ptr); } return ptr; ////////////////// End book ///////////////////////////// } static void *place(void *ptr, size_t asize){ //////////////// From book page 857 ////////////////////// size_t csize = GetSize(HeadP(ptr)); if ((csize - asize) >= (2*DoubleSize)) { Put(HeadP(ptr), Pack(asize, 1)); Put(FootP(ptr), Pack(asize, 1)); ptr = NextBlock(ptr); Put(HeadP(ptr), Pack(csize-asize, 0)); Put(FootP(ptr), Pack(csize-asize, 0)); } else { Put(HeadP(ptr), Pack(csize, 1)); Put(FootP(ptr), Pack(csize, 1)); } ////////////////// END BOOK ///////////////////////////////// } ////////////////////// End Helper Functions ///////////////////////// /* * mm_init - initialize the malloc package. */ int mm_init(void) { ///////// from book code page 831 ///////// char *heap_start; //allocate memorty in the initial heap if ((heap_start = mem_sbrk(4*WordSize)) ==(void*)-1) return -1; //Create alignment padding, start header/footer and end header putNotag(heap_start,0); putNotag(heap_start + (1*WordSize), Pack(DoubleSize,1)); putNotag(heap_start + (2*WordSize), Pack(DoubleSize,1)); putNotag(heap_start + (3*WordSize), Pack(0,1)); if(extendHeap(ChunkSize/WordSize) == NULL) return -1; return 0; //////// end book code reference ///////////// } /* * mm_malloc - Allocate a block by incrementing the brk pointer. * Always allocate a block whose size is a multiple of the alignment. */ void *mm_malloc(size_t size) { ///////////// adapted from book page 834 //////////// size_t adjsize; size_t extsize; void *ptr = NULL; if (size == 0) return NULL; if (size <= DoubleSize){ adjsize = 2*DoubleSize; }else{ adjsize = ALIGN(size + DoubleSize); } //////////// end adaptation ///////////////////////// // following section similar to book's "static void *find_fit(size_t asize) function // size_t searchsize = adjsize; // search free block in list int list; for(list =0; list < ListMax; list++){ if((list == ListMax -1) || ((searchsize<=1) && (sfl[list] != NULL))){ ptr = sfl[list]; while((ptr != NULL) && ((adjsize > GetSize(HeadP(ptr))) || (GetTag(HeadP(ptr))))) { ptr=pred(ptr); } if (ptr != NULL) break; } searchsize >>=1; } ///////// Directly from book page 834 //////////// if (ptr == NULL) { extsize = Max(adjsize, ChunkSize); if((ptr = extendHeap(extsize))==NULL) return NULL; } ptr = place(ptr,adjsize); return ptr; } /* * mm_free - Freeing a block does nothing. */ void mm_free(void *ptr) { ////// book page 833 ///////////////// size_t size = GetSize(HeadP(ptr)); Put(HeadP(ptr), Pack(size,0)); Put(FootP(ptr),Pack(size,0)); coalesce(ptr); ///////end book page 833 ///////////// } /* * mm_realloc - Implemented simply in terms of mm_malloc and mm_free */ void *mm_realloc(void *ptr, size_t size) { void *newPtr = ptr; size_t newSize = size; int remain; int extsize; int blockBuffer; if(size ==0) return NULL; if(newSize > DoubleSize){ newSize= ALIGN(size + DoubleSize); }else{ newSize = 2 * DoubleSize; } // create overhead requirements newSize+=ReallocBuffer; // get block buffer blockBuffer = GetSize(HeadP(ptr)) - newSize; // perform allocation when overhead too small if(blockBuffer <0){ if(GetAlloc(HeadP(NextBlock(ptr))) || GetSize(HeadP(NextBlock(ptr)))){ newPtr = mm_malloc(newSize - DoubleSize); memcpy(newPtr, ptr, Min(size,newSize)); mm_free(ptr); }else{ remain = GetSize(HeadP(ptr)) + GetSize(HeadP(NextBlock(ptr))) - newSize; if(remain <0) { extsize = Max(-remain, ChunkSize); if(extendHeap(extsize) == NULL) return NULL; remain += extsize; } deleteNode(NextBlock(ptr)); putNotag(HeadP(ptr), Pack(newSize + remain, 1)); putNotag(FootP(ptr), Pack(newSize + remain, 1)); } blockBuffer = GetSize(HeadP(newPtr)) - newSize; } if(blockBuffer< 2*ReallocBuffer) Get(HeadP(NextBlock(newPtr))) |= 0x2; return newPtr; }
Java
UTF-8
1,326
2.234375
2
[]
no_license
package com.study.controllers; import java.util.Map; import javax.servlet.http.HttpSession; import com.study.annotation.Component; import com.study.bind.DataBinding; import com.study.dao.OilDAO; import com.study.vo.MemberVO; @Component("/Fee/oilDelete.do") public class OilDeleteController implements Controller, DataBinding { private OilDAO oilDAO; @Override public Object[] getDataBinders() { // TODO Auto-generated method stub return new Object[] { "oil_no", Integer.class }; } public OilDeleteController setOilDAO(OilDAO oilDAO) { this.oilDAO = oilDAO; return this; } @Override public String exec(Map<String, Object> model) throws Exception { // TODO Auto-generated method stub HttpSession session = (HttpSession) model.get("session"); boolean isInternal = (Boolean)model.get("isInternal"); String abnormalAcc = (String) model.get("strReferer"); MemberVO vo = (MemberVO) session.getAttribute("member"); if(vo!=null) { if(isInternal && vo.getAuthority().equals("ADMIN") && abnormalAcc!=null) { oilDAO.delete((Integer)model.get("oil_no")); return "redirect:oil_list.do"; }else if(abnormalAcc==null) { return "../abnormalAccess.jsp"; }else { return "/authentication/denied.jsp"; } }else { return "redirect:../authentication/logon.do"; } } }
Java
UTF-8
1,832
3.703125
4
[]
no_license
/* * [2] Add Two Numbers * * https://leetcode.com/problems/add-two-numbers * * Medium (27.26%) * Total Accepted: * Total Submissions: * Testcase Example: '[2,4,3]\n[5,6,4]' * * Can you solve this problem? 🤔 */ /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { if (l1 == null) { return l2; } if (l2 == null) { return l1; } ListNode fakeHead = new ListNode(0); ListNode cur = fakeHead; ListNode curL1 = l1; ListNode curL2 = l2; int carry = 0; while (curL1 != null || curL2 != null) { int num1 = curL1 == null ? 0 : curL1.val; int num2 = curL2 == null ? 0 : curL2.val; int sum = num1 + num2 + carry; cur.next = new ListNode(sum % 10); cur = cur.next; carry = sum / 10; if (curL1 != null) { curL1 = curL1.next; } if (curL2 != null) { curL2 = curL2.next; } } while (curL1 != null) { int sum = curL1.val + carry; cur.next = new ListNode(sum % 10); cur = cur.next; carry = sum / 10; curL1 = curL1.next; } while (curL2 != null) { int sum = curL2.val + carry; cur.next = new ListNode(sum % 10); cur = cur.next; carry = sum / 10; curL2 = curL2.next; } if (carry > 0) { cur.next = new ListNode(carry); } return fakeHead.next; } }
C#
UTF-8
445
2.71875
3
[ "Unlicense", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SpotyScraper.Utils { public static class CollectionsExtensions { public static void AddRange<TItem>(this ICollection<TItem> collection, IEnumerable<TItem> values) { foreach (var value in values) { collection.Add(value); } } } }
JavaScript
UTF-8
2,324
2.515625
3
[ "MIT" ]
permissive
#!/usr/bin/env node var fs = require('fs') var path = require('path') var split2 = require('split2') var sort = require('lodash.sortby') var range = require('lodash.range') var shuffle = require('lodash.shuffle') var config = require('rc')('shuf', { n: null, lc: null }) begin() function begin () { if (config._.length === 0 && config.n === null) return mode_to_stdout() if (config._.length === 2 && config.n === null) { return mode_equal_dist() } if (config._.length !== 2 && config.n === null) { return mode_equal_dist() } if (config._.length === 2 && config.n !== null) { var a = fs.createWriteStream(path.resolve(config._[0])) var b = fs.createWriteStream(path.resolve(config._[1])) if (config.lc) return mode_two_file_with_limit_and_lc(a, b, config.n, config.lc) else return mode_two_file_with_limit(a, b, config.n) } if (config._.length !== 2 && config.n !== null) { console.log('Error, invalid mode. n option only available with 2 files') return usage() } } function mode_to_stdout () { process.stdin.pipe(split2()) .on('data', function (line) { if (!!Math.floor(Math.random() * 2)) console.log(line) }) } function mode_two_file_with_limit (a, b, limit) { var count = 0 process.stdin.pipe(split2()) .on('data', function (line) { var target = a if (count < limit) { if (!!Math.floor(Math.random() * 2)) { target = b count++ } } target.write(line + '\n') }) } function mode_two_file_with_limit_and_lc (a, b, limit, line_count) { var count = 0 var numbers = sort(shuffle(range(0, line_count)).slice(0, limit)) process.stdin.pipe(split2()) .on('data', function (line) { if (count === numbers[0]) { b.write(line + '\n') numbers.shift() } else a.write(line + '\n') count++ }) } function mode_equal_dist () { var output = [] config._.forEach(function (file) { output.push(fs.createWriteStream(path.resolve(file))) }) process.stdin.pipe(split2()) .on('data', function (line) { var random_index = Math.floor(Math.random() * output.length) var target = output[random_index] target.write(line + '\n') }) } function usage () { console.log('cat file.txt | shuf [-n] out1.txt out2.txt') }
Java
UTF-8
2,366
2.140625
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 com.miudelar.server.ejb; import com.miudelar.server.logic.entities.Estudiante_Curso; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; /** * * @author rmoreno */ @Stateless public class Estudiante_CursoFacade extends AbstractFacade<Estudiante_Curso> implements Estudiante_CursoFacadeLocal { @PersistenceContext(unitName = "miudelar") private EntityManager em; @Override protected EntityManager getEntityManager() { return em; } public Estudiante_CursoFacade() { super(Estudiante_Curso.class); } @Override public List<Estudiante_Curso> findEstudiante_CursoByUsuario_Asignatura(String cedula, Long asignatura_carrera) { Query q = getEntityManager().createNamedQuery(Estudiante_Curso.FINDBY_ESTUDIANTE_CURSO_ASIGNATURA).setParameter("cedula", cedula).setParameter("asignatura_carrera", asignatura_carrera); return q.getResultList(); } @Override public Long getMaxCalificacionAsignatura(String cedula, Long asignatura_carrera){ Query q = getEntityManager().createNamedQuery(Estudiante_Curso.GET_MAX_CALIF_ASIG).setParameter("cedula", cedula).setParameter("asignatura_carrera", asignatura_carrera); if(!q.getResultList().isEmpty() && q.getSingleResult() instanceof Long){ return (Long)q.getSingleResult(); }else{ return 0L; } } @Override public List<Estudiante_Curso> findByCurso(Long idCurso){ Query q = getEntityManager().createNamedQuery(Estudiante_Curso.FINDBY_CURSO).setParameter("idCurso",idCurso); return q.getResultList(); } @Override public Estudiante_Curso find(Long idCurso, String cedula){ Query q = getEntityManager().createNamedQuery(Estudiante_Curso.FIND).setParameter("cedula", cedula).setParameter("idCurso",idCurso); if(!q.getResultList().isEmpty() && q.getSingleResult() instanceof Estudiante_Curso){ return (Estudiante_Curso)q.getSingleResult(); }else{ return null; } } }
JavaScript
UTF-8
757
2.578125
3
[]
no_license
const { MessageEmbed } = require("discord.js") module.exports = { name: "avatar", aliases: ["av"], run: async (client, message, args, db, prefix) => { let usuario = args[0] ? message.mentions.users.first() || await client.users.fetch(args[0]).catch(_ => message.author) : message.author let png = usuario.avatarURL({ size: 1024, format: "png" }); let gif = usuario.avatarURL({ dynamic: true, size: 1024 }); let webp = usuario.avatarURL({ size: 1024, format: "webp" }); let embed = new MessageEmbed() .setAuthor(`${usuario.username} - Avatar`, usuario.displayAvatarURL({dynamic: true})) .setDescription(`**[PNG](${png}) | [GIF](${gif}) | [WEBP](${webp})**`) .setImage(gif) message.channel.send(embed) } }
Java
UTF-8
433
2.3125
2
[]
no_license
package com.github.brigade; /** * <b>TODO</b>: Class that keeps track of the following: * <ul> * <li>Wins / Losses (And Percent Wins)</li> * <li>Total units killed, units controlled</li> * <li>Units lost</li> * <li>Buildings made / destroyed (Chandler said Cities will have a build queue * a player can interact with)</li> * <li>In-Game time</li> * <li>Resources accumulated</li> * </ul> */ public class BattleStats { }
Markdown
UTF-8
2,083
2.984375
3
[ "BSD-3-Clause" ]
permissive
# Transformer: PLY to LAS converter This extractor converts PLY 3D point cloud files into LAS files. ### Docker The Dockerfile included in this directory can be used to launch this Transformer in a container. ### Sample Docker Command Line Below is a sample command line that shows how the .ply to .las file converter Docker image could be run. An explanation of the command line options used follows. Be sure to read up on the [docker run](https://docs.docker.com/engine/reference/run/) command line for more information. ```sh docker run --rm --mount "src=/home/test,target=/mnt,type=bind" agpipeline/ply2las:2.1 --working_space "/mnt" --metadata "/mnt/08f445ef-b8f9-421a-acf1-8b8c206c1bb8_metadata_cleaned.json" /mnt/3c807fe1-a5ba-4b4b-b618-1d2c9c981678__Top-heading-east_0.ply ``` This example command line assumes the source files are located in the `/home/test` folder of the local machine. The name of the image to run is `agpipeline/ply2las:2.1`. We are using the same folder for the source files and the output files. By using multiple `--mount` options, the source and output files can be separated. **Docker commands** \ Everything between 'docker' and the name of the image are docker commands. - `run` indicates we want to run an image - `--rm` automatically delete the image instance after it's run - `--mount "src=/home/test,target=/mnt,type=bind"` mounts the `/home/test` folder to the `/mnt` folder of the running image We mount the `/home/test` folder to the running image to make files available to the software in the image. **Image's commands** \ The command line parameters after the image name are passed to the software inside the image. Note that the paths provided are relative to the running image (see the --mount option specified above). - `--working_space "/mnt"` specifies the folder to use as a workspace - `--metadata "/mnt/08f445ef-b8f9-421a-acf1-8b8c206c1bb8_metadata.cleaned.json"` is the name of the source metadata to use - `/mnt/3c807fe1-a5ba-4b4b-b618-1d2c9c981678__Top-heading-east_0.ply` is the name of the ply file to convert
SQL
UTF-8
1,325
4.28125
4
[]
no_license
-- timestamps for lowest flyby select   time_stamp as nadir,   altitude from flyby_altitudes where flyby_altitudes.altitude=28.576 and date_part(‘year’, time_stamp) = 2008 and date_part(‘week’, time_stamp) = 41; -- the lowest timestamp for that week select   min(time_stamp) +   (max(time_stamp) - min(time_stamp))/2   as nadir,   altitude from flyby_altitudes where flyby_altitudes.altitude=28.576 and date_part(‘year’, time_stamp) = 2008 and date_part(‘week’, time_stamp) = 41 group by altitude; -- the CTE with lows_by_week as (   select     date_part(‘year’,time_stamp) as year,     date_part(‘week’,time_stamp) as week,     min(altitude) as altitude   from flyby_altitudes   group by date_part(‘year’,time_stamp), date_part(‘week’,time_stamp) ), nadirs as (   select (       min(time_stamp) + (max(time_stamp) - min(time_stamp))/2     ) as nadir,     lows_by_week.altitude   from flyby_altitudes,lows_by_week   where flyby_altitudes.altitude =lows_by_week.altitude   and date_part(‘year’, time_stamp) = lows_by_week.year   and date_part(‘week’, time_stamp) = lows_by_week.week   group by lows_by_week.altitude   order by nadir ) select nadir at time zone ‘UTC’, altitude from nadirs;
C#
UTF-8
871
2.828125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
using System.IO; using System.Security.AccessControl; namespace Scalar.Common { public static class DirectoryEx { public static DirectorySecurity GetAccessControl(string path) { var di = new DirectoryInfo(path); return di.GetAccessControl(); } public static void SetAccessControl(string path, DirectorySecurity security) { var di = new DirectoryInfo(path); di.SetAccessControl(security); } public static void CreateDirectory(string path, DirectorySecurity security) { var di = new DirectoryInfo(path); di.Create(); di.SetAccessControl(security); } public static void CreateDirectory(string path) { var di = new DirectoryInfo(path); di.Create(); } } }
Markdown
UTF-8
2,539
3.03125
3
[ "Apache-2.0" ]
permissive
project_path: /web/tools/_project.yaml book_path: /web/tools/_book.yaml description:爲您反覆使用的命令行任務設置快捷方式。如果您發現自己在命令行中反覆鍵入相同的內容,這將爲您帶來很大方便。 {# wf_updated_on:2015-04-13 #} {# wf_published_on:2014-09-24 #} # 設置命令行快捷方式 {: .page-title } {% include "web/_shared/contributors/megginkearney.html" %} {% include "web/_shared/contributors/mattgaunt.html" %} 爲您反覆使用的命令行任務設置快捷方式。如果您發現自己在命令行中反覆鍵入相同的內容,這將爲您帶來很大方便。 ### TL;DR {: .hide-from-toc } - 掌控命令行;創建易於記住和可快速鍵入的別名。 - 嘗試保存、分享 Github 點文件,並同步您的命令行快捷方式。 ## 如何設置 創建命令行快捷方式最簡單的方法就是將常見命令的別名添加至 bashrc 文件。 在 Mac 或 Linux 上: 1. 從命令行任意位置,鍵入: open -a 'Sublime Text' ~/.bashrc 2. 添加新別名,例如: alias master='git checkout master' 3. 任何時候當您位於帶 git repo 的目錄時,都可以運行命令 `master`,它將爲您檢查主分支。 注:請參閱[設置 Windows 別名](https://msdn.microsoft.com/en-us/library/windows/desktop/ms682057(v=vs.85).aspx)的說明。 ## 我們推薦的快捷方式 您可能會發現以下幾個快捷方式比較有用。 <table class="responsive"> <thead> <tr> <th colspan="2" data-th="Command">命令和別名</th> </tr> </thead> <tbody> <tr> <td data-th="Command">打開您的編輯器</td> <td data-th="Alias"><code>alias st='open -a "Sublime Text"'</code></td> </tr> <tr> <td data-th="Command">啓動服務器</td> <td data-th="Alias"><code>alias server="python -m SimpleHTTPServer"</code></td> </tr> <tr> <td data-th="Command">轉到您通常在其中工作的目錄</td> <td data-th="Alias"><code>alias p="cd ~/projects"</code></td> </tr> </tbody> </table> ## 保存、分享和同步您的快捷方式 在 Github 上保存您的快捷方式和點文件。主要好處是可以在各個設備之間分享快捷方式,而且始終可以備份快捷方式。 Github 還創建了一個[點文件專用頁面](https://dotfiles.github.io/){: .external },Chrome 團隊的許多人都複製了 [Mathias Bynens 的點文件](https://github.com/mathiasbynens/dotfiles)。 {# wf_devsite_translation #}
Ruby
UTF-8
4,306
2.875
3
[]
no_license
require 'json' require 'time' # #iso8601 require 'blog-generator/post' require 'blog-generator/models' require 'blog-generator/file-system-actions' module BlogGenerator class ValidationError < StandardError; end class ContentDirectoryHandler # content_directory: i. e. drop-area/, it doesn't have any name specific to the post. def initialize(content_directory) @content_directory = content_directory end def main_file Dir.glob("#{@content_directory}/*.md").first end def post slug = File.basename(self.main_file).split('.').first @post ||= Post.new(slug, File.read(self.main_file)) end end class ContentDirectoryValidator < ContentDirectoryHandler def validate self.validate_one_post_file self.validate_is_valid_markdown self.validate_image_paths true end protected # There must be exactly 1 file with .md extension in the content directory. def validate_one_post_file unless Dir.glob("#{@content_directory}/*.md").length == 1 raise ValidationError, "There must be exactly 1 .md file in #{@content_directory}" end end def validate_is_valid_markdown self.post.validate end def validate_image_paths self.post.image_paths.each do |src| unless File.exist?(File.join(@content_directory, src)) raise ValidationError, "Image #{src} doesn't exist in #{@content_directory}" end end end end class Generator < ContentDirectoryHandler def initialize(content_directory, output_directory) @content_directory = content_directory @output_directory = output_directory end def output_posts_directory File.join(@output_directory, 'posts') end def output_post_directory File.join(self.output_posts_directory, self.output_post_basename) end def output_post_basename "#{Time.now.strftime('%Y-%m-%d')}-#{self.post.slug}" end def output_tags_directory File.join(@output_directory, 'tags') end def generate actions, published_at = FileSystemActions.new, Time.now actions << CreateDirectoryAction.new(self.output_posts_directory) actions << CreateDirectoryAction.new(self.output_post_directory) Dir.glob("#{@content_directory}/*").each do |file| if File.file?(file) && File.basename(file) != File.basename(self.main_file) actions << MoveFileAction.new(file, self.output_post_directory) end end json = Models::FullPostFromPost.new(self.post).as_json(published_at).to_json actions << FileWriteAction.new(File.join(self.output_post_directory, "#{self.post.slug}.json"), json) actions << self.generate_index(published_at) actions << CreateDirectoryAction.new(self.output_tags_directory) actions.push(*self.generate_tag_files(self.post.header[:tags], published_at)) actions end def existing_posts posts = Array.new if Dir.exist?(self.output_posts_directory) # On the first run, it will not exist until the actions are committed. Dir.glob("#{self.output_posts_directory}/*/*.json").each do |file| posts << JSON.parse(file) rescue => error warn "~ Error occurred when parsing #{file}" ### raise error end end posts end # The current post doesn't exist as a JSON file yet. def all_posts(published_at) self.existing_posts << Models::PostIndexFromPost.new(self.post).as_json(published_at) end def post_data(post) Models::PostFromStoredPost.new(post).as_json end def generate_index(published_at) posts = self.all_posts(published_at).map { |post| self.post_data(post) } FileWriteAction.new(File.join(@output_directory, 'posts.json'), posts.to_json) end def generate_tag_files(tags, published_at) tags.map do |tag_name| posts = self.all_posts(published_at). select { |post| post.fetch(:tags).include?(tag_name) }. map { |post| Models::PostFromStoredPost.new(post) } tag_data = Models::Tag.new(tag_name, posts).as_json(published_at) FileWriteAction.new(File.join(@output_directory, 'tags', "#{tag_name}.json"), tag_data.to_json) end end end end
Markdown
UTF-8
7,992
2.515625
3
[]
no_license
二六 宫燕秋立刻想到了普慈庵发生的怪事,先是有人被杀,看似是自戕。守庵的妇人失踪,接着来了武林判官,要完成未完成的杀人买卖,剑拔弩张之际,一向仅属传闻的蓬莱三翁之中的"铁头翁"突然现身,指出看似自杀的汉子是死于推元反戕……..心念之中,向小二挥手道:"小二哥,你可以自便了,没什麽事。"小二迟疑地退了出去。 "浪子,你到底是弄什么鬼?"紫薇大声问。 宫燕秋没答腔,心里在苦苦地想:二先生当时并不在场,他怎么知道推元反戕这档事?照字条表面解释,他怀疑自己与推元反戕这门失传功夫的门人有关,所以才有不宜留难之语…"浪子,你怎么啦?"紫薇似已动了火。 "我……没什么!""你不肯说拉倒,反正我们之间谈不上交情,从后各走各路!"紫薇似赌气地灌了一杯酒,嘴翘得老高。 "不是,紫薇,你先别生气,我告诉你。"宫燕秋陪了个笑脸,"我这次出诊,病家很古怪,把我限制在客房里不许走动,到今天最后一次施行针灸之术,对方忽然接到一个字条,立刻送我回店,所以你一提到二先生送字条,我便想到这个中有文章,因为请我去的是二先生。""是这样,怎不早说!"紫薇脸色缓和下来。 "先我没想到这一点。""你去的不是谷家?""天知道,轿子是被遮住的黑轿,抬了很久,停轿时又在内院根本不知道是什么鬼地方。""算了,反正人己经平安回来,喝酒吧!"紫薇代宫燕秋斟上店小二刚送来的所谓好酒,自己也斟了一杯。 宫燕秋喝了一口,点点头表示的确是好酒。 紫薇虽说不提了,但他的心并未松开,这整个的事件太古怪了,他告诉紫薇的,并非全部事实。 二更初起,两人酒意到了八分。 八分酒意的人,人就有些飘飘然了。 灯光,酒意,紫薇的神色显得更艳更野。 俗语说酒能乱性,宫燕秋不是喝了酒会乱性的人,但任何人在喝到了八分醉的时候,多多少少跟清醒的时候是有些不同的,在情绪的表露方面,不会有太多的顾忌,动于中则形于外。 现在,宫燕秋便是这样。他呆呆地望着这野艳少女,静夜,客邸,一男一女杯酒相对,能无动于衷么?"为什么要这样看我?"紫薇偏起头,眸子飘起一层雾,蒙蒙的水雾,她似乎突然消失了野性,变得很温驯,红艳艳的双颊像盛开的花瓣,充满了女性的诱惑。 "你不喜欢我看你?"眼睛长在你脸上,你爱看就看,谁也管不了!""紫薇,你真的很美!""是你说的?""是真心话!""那你就尽情地看吧,趁现在有机会。""你说这话是什么意思?""人生聚散无常!"紫薇的目光忽然黯了一下,用低沉的声音道:"水上的浮萍,偶而聚在一起,说不定什么时候一阵风又被吹散,也许能重聚,也许就此永远分开,江湖人,连生死都很难预测的。"她现在像一个淑女,又像多愁善感的婉约少女。 宫燕秋心想:女人实在是善变,令人无法捉摸,与她持剪刀杀人时的那一份狠劲,根本就是两个截然不同的女人。 "紫薇,这不像是你说的话。""为什么?""因为你不是多愁善感的女人。""在你看来,我该是什么样的女人。"紫薇的眸子又开始发亮,象火堆黯下去经过一挑又突然旺了起来。 "你应该是提得起、放得下,豪爽大方,狠辣与美艳兼具的女人。"宫燕秋坦白地说出了心里对她的感受。 "你说得不错,我是个连杀人都不怎么在乎的人。可是浪子,我是女人,女人始终是女人,尽管有时猛如虎,狠如狼,如大风,如飞扬的云,可我还是个女人,在感情上永远不会变成男人,你说对不对?"紫薇的眉毛挑起了又垂下,只是两眼明亮如故,隐隐有一种火焰在燃烧。 这种火焰最容易燃烧到男人的心房。 宫燕秋的心火似已被点燃,他的双眸也透出了火焰。 "紫薇!"他突然伸手按住她放在桌面上的手,这手柔白细腻,完全不象是杀人的手,而是一双令人动心的真正女人的手,"我能永远握住它吗?""不能!"紫薇不加思索地回答。 "为什么?"宫燕秋的心头之火未消减。 "就是因为不能!"慧黠又回到了她脸上。 "我要知道理由!""浪子,我们象目前这样不是很好吗?"紫薇笑了笑,笑得很苦涩,眸子里的火燃也突然消失:"何必一定要问原因呢?有些原因是很伤感情的。""我更不懂!""将来有一天你会懂的。""紫薇!"宫燕秋按着的手变为抓,紧紧握住她的皓腕:"听你的口气,你好象并不喜欢我?""我很喜欢你,打从普慈庵外第一眼看到你时就已经喜欢上了你,前提只限于喜欢,不能要进一步。""到底为什么?"我已经说过不能两个字。"人最想得到的,便是他想得到而得不到的东西,而一旦心里起了"想得到"的念头,就象柴薪被点燃,很快便成为熊熊烈火。 宫燕秋的一点心火,已变成了烈火,他的目光更使人心悸,紫薇现在的心已在悸动,脸更红,能助长烈火的红。 "紫薇,我不喜欢听不能两个字……""浪子,只怕你非听不可。""紫薇,你可别误会,我没有什么歪念头,只是喜欢你,只是想……"话锋顿了顿,他在想如何措词。 "只想什么?"紫薇在暗暗咬牙。 "只是想我们之间应该距离更短些更亲近些。""不能,这已经过份了。"紫薇用力抽回手。 宫燕秋惊愕地望着她。 紫薇起身走到门边,向外望了望夜空,然后关上门, 回到桌边,没再坐下,眸子己恢复正常。 宫燕秋深吐了口气,把心火压低下去。 一个始终在心里的老问题又涌上脑海,籍着酒意,他情不自禁地问了出来。 "紫薇,我只问这一次,以后绝不再提它……""什么?""你到底是不是复仇使女?"宫燕秋的神情立变严肃。 "在你是,在别人不是。""什么意思?""因为这外号是你替我起的。""那就是说你不是真正的复仇使女?""我已经回答的很清楚了。""那……真正的复仇使女该是谁?"宫燕秋两眼直盯着紫薇,似两把利刃,象要戳穿她的内心,看看她这句话可信的程度有多深。 "真正的复仇使女就是复仇使女!"回答的不是紫薇,而是另外一个似曾相识的女人声音,而声音就近在咫尺。 宫燕秋心头大震,但他仍坐着不动,急急捉摸声音的来源,两边是房间,一间是紫薇住的,她一直守着没离开过。 另一间是自己的,回来到现在没进去过,难道人藏在里面吗?再一个可能人在窗外,明间朝后开了两个窗子,窗外是院子……"是谁呀?"紫薇首先开口喝问。 "复仇使女!"一个字一个字的吐出来,三个字,给人以极大的震撼。 宫燕秋望向那声音,这已证明了紫薇不是复仇使女,紫薇却瞪着左边那扇窗,因为声音来自窗外。 房里有灯火,无法外望。 宫燕秋站起身来,努力沉住气道:"深夜光临,有什么指教?"他全身抽紧了,这是完全估不到的意外。"有几句话跟你谈!"窗外声音回答。 "有话要跟在下谈?""不错!""请进来谈好吗?""用不着。"宫燕秋明知这句话是多余,对方是绝对不会随便现身的。 一个强烈的意念,极想见一下这个可怖人物到底什么样子。 在鲁班庙,她现过身,但只是个模糊的影子,当时一直怀疑她是紫薇的化身。 "芳驾有什么话要和在下谈?"沉寂了片刻。
Go
UTF-8
1,106
2.515625
3
[ "MIT" ]
permissive
package tasks import ( "flag" "fmt" "github.com/gsmake/gsmake" "github.com/gsmake/gsmake/vfs" ) // TaskUpdate . func TaskUpdate(runner *gsmake.Runner, args ...string) error { var flagSet flag.FlagSet nocache := flagSet.Bool("nocache", false, "also update cached package") if err := flagSet.Parse(args); err != nil { return err } if runner.Name() == gsmake.PacakgeAnonymous { *nocache = true } if flagSet.NArg() > 0 { if runner.Name() == gsmake.PacakgeAnonymous { for _, target := range flagSet.Args() { if err := runner.RootFS().UpdateCache(fmt.Sprintf("gsmake://%s", target)); err != nil { return err } } } else { for _, target := range flagSet.Args() { err := runner.RootFS().List(func(srcE, targetE *vfs.Entry) bool { if fmt.Sprintf("%s%s", targetE.Host, targetE.Path) == target { err := runner.RootFS().Update(targetE.String(), *nocache) if err != nil { panic(err) } } return true }) if err != nil { return err } } } return nil } return runner.RootFS().UpdateAll(*nocache) }
Java
UTF-8
2,193
3.40625
3
[]
no_license
class Payment{ /* void payFromWallet (int amount) { System.out.println("Amount Paid from Wallet"); } void payFromUPI(int amount, String upi) { System.out.println("Amount Paid From UPI: "+upi); } void payFromBank(int amount, String userName, String password) { System.out.println("Amount Paid from Bank"); System.out.println("UserName used: "+userName); } void payFromCard(int amount, String cardNumber, String name, int cvv, String expiry) { System.out.println("Amount Paid form Card"); System.out.println("Card Details"); System.out.println(cardNumber); System.out.println(name); } */ void pay(int amount) { System.out.println("Amount Paid from Wallet"); } void pay(int amount, String upi) { System.out.println("Amount Paid from UPI: "+upi); } /*void pay(int total, String upiUserName) { System.out.println("Amount Paid from UPI:"+upiUserName); }*/ // error /*int pay(int amount, String upi) { System.out.println("Amount Paid from UPI:"+upi); return 0; }*/ // error /* Signature of method (This Signature is different from upper one) _____________/\_________________ / \ */ void pay(String upi, int amount) { System.out.println("Amount Paid from UPI: "+upi); } void pay(int amount, String userName, String password) { System.out.println("Amount Paid from Bank"); System.out.println("Username used: "+userName); } void pay(int amount, String cardNumber, String name, int cvv, String expiry) { System.out.println("Amount Paid from Card"); System.out.println("Card Details"); System.out.println(cardNumber); System.out.println(name); } } // Polymorphism // Compile Time Polymorphism -> Method Overloading // RULE1: Method Name Should be same // RULE2: Method Must have Unique Inputs i.e. different // RULE3: Return type plays no role public class MethodOverloading { public static void main(String[] args) { Payment payment = new Payment(); payment.pay(300); payment.pay(300, "8776944@paytm"); payment.pay("8776944@googlepay", 300); payment.pay(300, "john.watson", "john@123"); } }
Java
UTF-8
907
3.078125
3
[]
no_license
package ex1_cliente; public class Cliente { int cpf; int cod; String primeiroNome; String sobrenome; public Cliente(int cpf, int cod, String primeiroNome, String sobrenome) { this.cpf = cpf; this.cod = cod; this.primeiroNome = primeiroNome; this.sobrenome = sobrenome; } public String nomeCompleto() { String nomeCompleto; nomeCompleto = primeiroNome + " " + sobrenome; return nomeCompleto; } public int getCpf() { return cpf; } public void setCpf(int cpf) { this.cpf = cpf; } public int getCod() { return cod; } public void setCod(int cod) { this.cod = cod; } public String getPrimeiroNome() { return primeiroNome; } public void setPrimeiroNome(String primeiroNome) { this.primeiroNome = primeiroNome; } public String getSobrenome() { return sobrenome; } public void setSobrenome(String sobrenome) { this.sobrenome = sobrenome; } }
Java
UTF-8
566
1.867188
2
[ "Apache-2.0" ]
permissive
package com.creactiviti.piper.config; public class GitProperties { private boolean enabled = false; private String url; private String[] searchPaths; public String getUrl() { return url; } public void setUrl(String aUrl) { url = aUrl; } public String[] getSearchPaths() { return searchPaths; } public void setSearchPaths(String[] aSearchPaths) { searchPaths = aSearchPaths; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean aEnabled) { enabled = aEnabled; } }
C++
UTF-8
1,832
3.703125
4
[]
no_license
/* We stack glasses in a pyramid, where the first row has 1 glass, the second row * has 2 glasses, and so on until the 100th row. Each glass holds one cup (250ml) * of champagne. * * Then, some champagne is poured in the first glass at the top. When the top most * glass is full, any excess liquid poured will fall equally to the glass immediately * to the left and right of it. When those glasses become full, any excess champagne * will fall equally to the left and right of those glasses, and so on. (A glass at * the bottom row has it's excess champagne fall on the floor.) * * For example, after one cup of champagne is poured, the top most glass is full. * After two cups of champagne are poured, the two glasses on the second row are * half full. After three cups of champagne are poured, those two cups become full * - there are 3 full glasses total now. After four cups of champagne are poured, * the third row has the middle glass half full, and the two outside glasses are a * quarter full, as pictured below. */ #include <vector> #include <cassert> using namespace std; double champagneTower(int poured, int query_row, int query_glass) { double amount = poured; vector<vector<double>> glass; int index = 0; glass.push_back(vector<double>(1, 0)); glass[0][0] = amount; for (int row = 0; row <= query_row; ++row) { glass.push_back(vector<double>(row + 2, 0)); for (int col = 0; col <= row; ++col) { amount = glass[row][col]; glass[row][col] = (amount >= 1.0f) ? 1.0f : amount; amount = (amount >= 1.0f) ? (amount - 1) : 0.0f; glass[row + 1][col] += amount / 2; glass[row + 1][col + 1] += amount / 2; } } return glass[query_row][query_glass]; } int main() { int pour = 6; double ans = 0.75; double ret = champagneTower(6,2,0); assert(abs(ans - ret) < 1E-12); return 0; }
Markdown
UTF-8
1,235
2.890625
3
[ "MIT" ]
permissive
--- order: 3 title: zh-CN: 切换方向 en-US: Vertical --- ## zh-CN 默认情况下,`direction` 为 `horizontal`。通过设置 `direction` 为 `vertical` 来使用垂直方向切换。 ## en-US The default value for `direction` is `horizontal`. Use the vertical direction switch by setting `direction` to `vertical`. ```js import { Carousel } from '@arco-design/web-react'; const imageSrc = [ '//p1-arco.byteimg.com/tos-cn-i-uwbnlip3yd/cd7a1aaea8e1c5e3d26fe2591e561798.png~tplv-uwbnlip3yd-webp.webp', '//p1-arco.byteimg.com/tos-cn-i-uwbnlip3yd/6480dbc69be1b5de95010289787d64f1.png~tplv-uwbnlip3yd-webp.webp', '//p1-arco.byteimg.com/tos-cn-i-uwbnlip3yd/0265a04fddbd77a19602a15d9d55d797.png~tplv-uwbnlip3yd-webp.webp', '//p1-arco.byteimg.com/tos-cn-i-uwbnlip3yd/24e0dd27418d2291b65db1b21aa62254.png~tplv-uwbnlip3yd-webp.webp' ]; ReactDOM.render( <Carousel style={{ width: 600, height: 240, }} showArrow="never" direction="vertical" indicatorPosition="right" > {imageSrc.map((src, index) => ( <div key={index}> <img src={src} style={{ width: '100%', }} /> </div> ))} </Carousel>, CONTAINER ); ```
Java
UTF-8
690
2.328125
2
[]
no_license
package com.okliu.util; import java.time.LocalDateTime; /** * @author liuhaolie * @Time 2020/3/17-3:07 */ public class LogUtils { private static String IN = ">---IN-->>|"; private static String OUT = "<<--OUT--<|"; public static void errOut(String error) { String prefix = OUT + LocalDateTime.now() + "|"; System.err.println(prefix + error); } public static void infoIn(String info) { String prefix = IN + LocalDateTime.now() + "|"; System.out.println(prefix + info); } public static void infoOut(String info) { String prefix = OUT + LocalDateTime.now() + "|"; System.out.println(prefix + info); } }
C#
UTF-8
2,081
2.546875
3
[]
no_license
 using System; using System.Collections.Generic; using System.Linq; using System.Text; using Modelo; using System.Data; using System.Data.Objects; namespace DataAccess { public class MaterialxPreparadoDA { #region MaterialxPreparado public List<MaterialxPreparadoEntity> GetMaterialxPreparado() { List<MaterialxPreparadoEntity> listadoMaterialesxPreparado = new List<MaterialxPreparadoEntity>(); using (OncologiaEntities context = new OncologiaEntities()) { listadoMaterialesxPreparado = context.MaterialxPreparado.Select(c => new MaterialxPreparadoEntity() { IDMaterial = c.IDMaterial, IDPreparado = c.IDPreparado, Dosis = c.Dosis }).ToList(); } return listadoMaterialesxPreparado; } public MaterialxPreparado FindbyID(int idMaterial, int idPreparado) { MaterialxPreparado objc = null; using (OncologiaEntities contex = new OncologiaEntities()) { objc = contex.MaterialxPreparado.First(c => c.IDMaterial == idMaterial && c.IDPreparado == idPreparado) ; } return objc; } public void CreateMaterialxPreparado(MaterialxPreparado objC) { using (OncologiaEntities contex = new OncologiaEntities()) { contex.MaterialxPreparado.Add(objC); contex.SaveChanges(); contex.Entry(contex.MaterialxPreparado).Reload(); } } public void UpdateMaterialxPreparado(MaterialxPreparado objC) { using (OncologiaEntities contex = new OncologiaEntities()) { contex.MaterialxPreparado.Attach(objC); contex.Entry(objC).State = EntityState.Modified; contex.SaveChanges(); contex.Entry(contex.MaterialxPreparado).Reload(); } } #endregion } }
C#
UTF-8
1,711
2.625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace TerraViewer { public partial class LanguageSelect : Form { public Language Language; public LanguageSelect() { InitializeComponent(); SetUiStrings(); } private void SetUiStrings() { this.Text = Language.GetLocalizedText(1, "Select Your Language"); this.selectLangLabel.Text = Language.GetLocalizedText(1, "Select Your Language"); this.Cancel.Text = Language.GetLocalizedText(157, "Cancel"); this.OK.Text = Language.GetLocalizedText(156, "OK"); } private void LanguageSelect_Load(object sender, EventArgs e) { Language[] items = Language.GetAvailableLanguages(); Language selected = null; foreach (Language item in items) { langCombo.Items.Add(item); if (item.Url == Properties.Settings.Default.LanguageUrl || (item.Code == "ZZZZ" && Properties.Settings.Default.LanguageCode=="ZZZZ") ) { selected = item; } } langCombo.SelectedItem = selected; } private void OK_Click(object sender, EventArgs e) { Language = (Language)langCombo.SelectedItem; DialogResult = DialogResult.OK; this.Close(); } private void Cancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; this.Close(); } } }
Markdown
UTF-8
803
3.515625
4
[]
no_license
# Tutorial: Python programming for everyone ## Summary This python programming tutorial is not only suitable for a complete beginner who wants to learn python programming, but also for experienced programmers. Using many examples, I explain the basics as well as some useful tricks to write python codes more effectively. ## List of chapters - Chapter 1: Introduction - Chapter 2: Comments and print() - Chapter 3: Data types/structures - Chapter 4: Strings - Chapter 5: Operators - Chapter 6: Lists and tuples - Chapter 7: Dictionaries - Chapter 8: Sets - Chapter 9: If-elif-else - Chapter 10: Loops - Chapter 11: Comprehensions - Chapter 12: Import modules - Chapter 13: Decorators - Chapter 14: Read/write files - Chapter 15: Plotting with matplotlib - Chapter 16: Classes - Chapter 17: Summary
Java
UTF-8
410
2.234375
2
[]
no_license
package com.mz.exception; /** * * @ProjectName :SpringMvcMz * @ClassName:ServiceException * @Description: 自定义服务异常 * @author:Ma Zhen * @date:2016-04-22 * @version */ public class ServiceException extends Exception { /** * 自定义服务异常 */ private static final long serialVersionUID = 1L; public ServiceException(String err){ super(err); } }
Java
UTF-8
397
3.0625
3
[]
no_license
import java.util.Scanner; public class Main { public static void main(String[] args) { //put your code here Scanner s = new Scanner(System.in); int a = Integer.parseInt(s.nextLine()); if(a <= 12 && a > -15){ System.out.println("True"); }else if (a >= 19 || a ==15 ||a == 16){ System.out.println("True"); }else{ System.out.println("False"); } } }
Java
UTF-8
1,353
2.6875
3
[]
no_license
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) public class FakeTimer extends Actor { public int stepsLeft = 0,rest_d; public int count_down_flag=0; long TimerStart = System.currentTimeMillis(); public FakeTimer(int startValue) { //stepsLeft = startValue; setImage(new GreenfootImage(120, 20)); setLocation(1,1); rest_d=stepsLeft; repaint(); } public void act(){ if(count_down_flag==1&&(System.currentTimeMillis() > TimerStart + 60000)) { getImage().drawString("Time Left : " + stepsLeft+" mins", 0, 60); timerStart(); TimerStart = System.currentTimeMillis(); } } public void timerStart() { stepsLeft--; repaint(); if(stepsLeft <= 0) { count_down_flag=0; //Greenfoot.stop(); } } public void setTime(int time) { stepsLeft = time; } public void repaint() { getImage().clear(); getImage().drawString("Time Left: " + stepsLeft+" mins", 0, 20); } public void setFlagcd(int v) { if(v==5) {count_down_flag=v; stepsLeft=rest_d; repaint(); } else count_down_flag=v; } }
Java
UTF-8
3,088
2.09375
2
[ "Apache-2.0" ]
permissive
package com.example.maps; import java.text.SimpleDateFormat; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.ActionBarActivity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.google.gson.Gson; public class ViewTaskActivity extends ActionBarActivity { eventMarker temp; ArrayOfEvents events; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_task); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, new PlaceholderFragment()).commit(); } } @Override protected void onResume(){ super.onResume(); temp = eventMarker.getInstance(this); events = ArrayOfEvents.getInstance(this); TextView tv = (TextView) findViewById(R.id.textView1); tv.setText(temp.Title); tv = (TextView) findViewById(R.id.textView2); tv.setText(temp.Description); SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy h:mm a"); tv = (TextView) findViewById(R.id.textView4); tv.setText(sdf.format(temp.deadline.getTime())); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.view_task, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_view_task, container, false); return rootView; } } public void delete(View V){ for(int i = 0; i < events.eventsArray.size(); i++){ if(events.eventsArray.get(i).Loc.equals(temp.Loc) && events.eventsArray.get(i).Title.equals(temp.Title)){ events.eventsArray.remove(i); break; } } Gson gson = new Gson(); SharedPreferences settings = getSharedPreferences(MainActivity.MYPREFS, 0); Editor editor = settings.edit(); editor.putString(MainActivity.PREF_STRING_1, gson.toJson(events, ArrayOfEvents.class)); editor.commit(); onBackPressed(); } public void edit(View V){ temp = eventMarker.getInstance(this); Intent intent = new Intent(this, EditEvent.class); startActivity(intent); } }