export chart to excel using asp.net - javascript

Tried for Gridview:
private void ExportToExcel() {
try {
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=OverallReport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using(StringWriter sw = new StringWriter()) {
HtmlTextWriter hw = new HtmlTextWriter(sw);
//To Export all pages
dgvTrendChart.AllowPaging = false;
this.SearchOverallList();
dgvTrendChart.HeaderRow.BackColor = Color.White;
foreach(TableCell cell in dgvTrendChart.HeaderRow.Cells) {
cell.BackColor = dgvTrendChart.HeaderStyle.BackColor;
}
for (int rowIndex = dgvTrendChart.Rows.Count - 2; rowIndex >= 0; rowIndex--) {
GridViewRow row = dgvTrendChart.Rows[rowIndex];
GridViewRow previousRow = dgvTrendChart.Rows[rowIndex + 1];
for (int i = 0; i < row.Cells.Count; i++) {
if (i != 3) {
if (row.Cells[i].Text == previousRow.Cells[i].Text) {
row.Cells[i].RowSpan = previousRow.Cells[i].RowSpan < 2 ? 2 :
previousRow.Cells[i].RowSpan + 1;
previousRow.Cells[i].Visible = false;
row.Cells[i].HorizontalAlign = HorizontalAlign.Center;
row.Cells[i].VerticalAlign = VerticalAlign.Top;
}
}
}
}
dgvTrendChart.RenderControl(hw);
string style = # "<style>.textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
} catch {
//throw new Exception("");
}
}

Related

sending file through webscoket in browser with js to c# server

I have a problem in sending file through webscoket in browser with js to c# server.
When I want to save the buffer, if it is a txt file, there is no problem
But if it is a photo, for example, the photo will not be opened after saving
Where am I going wrong?
private void BeginReceive()
{
try
{
Buffer = new byte[BufferSize];
Socket.BeginReceive(Buffer, 0, BufferSize, SocketFlags.None, new AsyncCallback(ReceiveCallback), this);
}
catch (SocketException ex)
{
Console.WriteLine("{0}: {1}", "BeginReceive", ex.Message);
Close();
}
catch (Exception ex)
{
Console.WriteLine("{0}: {1}", "BeginReceive", ex.Message);
}
}
private void ReceiveCallback(IAsyncResult ar)
{
try
{
if (CheckState(ar))
{
int bytesRead = Socket.EndReceive(ar);
Console.WriteLine("{0}: {1}", "bytesRead: ", bytesRead);
File.WriteAllText(#"c:\01.jpg", Helper.DecodedBytes(Buffer, bytesRead));
}
}
catch (SocketException)
{
Close();
}
catch (Exception ex)
{
Console.WriteLine("{0}: {1}", "ReceiveCallback", ex.Message);
}
finally
{
if(!Helper.SocketIsDisposed(Socket)) BeginReceive();
}
}
I think the problem is with the decode function
public static string DecodedBytes(byte[] buffer, int length)
{
if(buffer[0] == 136 && (buffer[1] == 130 || buffer[1] == 128)) throw new System.Net.Sockets.SocketException(10054); //[10054]: Connection reset by peer
byte b = buffer[1];
int dataLength = 0;
int totalLength = 0;
int keyIndex = 0;
if (b - 128 <= 125)
{
dataLength = b - 128;
keyIndex = 2;
totalLength = dataLength + 6;
}
if (b - 128 == 126)
{
dataLength = BitConverter.ToInt16(new byte[] { buffer[3], buffer[2] }, 0);
keyIndex = 4;
totalLength = dataLength + 8;
}
if (b - 128 == 127)
{
dataLength = (int)BitConverter.ToInt64(new byte[] { buffer[9], buffer[8], buffer[7], buffer[6], buffer[5], buffer[4], buffer[3], buffer[2] }, 0);
keyIndex = 10;
totalLength = dataLength + 14;
}
if (totalLength > length)
throw new Exception("The buffer length is small than the data length");
byte[] key = new byte[] { buffer[keyIndex], buffer[keyIndex + 1], buffer[keyIndex + 2], buffer[keyIndex + 3] };
int dataIndex = keyIndex + 4;
int count = 0;
for (int i = dataIndex; i < totalLength; i++)
{
buffer[i] = (byte)(buffer[i] ^ key[count % 4]);
count++;
}
return Encoding.UTF8.GetString(buffer, dataIndex, dataLength);
}
and js code:
connect:function(){
var root = this;
root.websocket = new WebSocket(root.url);
root.websocket.binaryType = "arraybuffer";
root.websocket.onopen = () => root.fireEvent('connect');
root.websocket.onmessage = (e) => {
root.fireEvent('receive',JSON.parse(e.data));
}
window.addEventListener("beforeunload", function() {
root.websocket.onclose = function () {};
root.websocket.close();
});
},
sendFile:function(){
var root = this;
var file = document.getElementById('filename').files[0];
var loader = new FileReader();
loader.onload = (e) => {
var a = e.target.result;
root.controller.websocket.send(e.target.result);
}
loader.readAsText(file)
},
Problem solved
JS code changed to:
sendFile:function(){
var root = this;
var file = document.getElementById('filename').files[0];
var loader = new FileReader();
loader.onload = (e) => {
var byteArray = new Uint8Array(e.target.result);
root.controller.websocket.send(byteArray.buffer);
}
loader.readAsArrayBuffer(file);
}
and C# code changed to:
WriteAllText to WriteAllBytes
File.WriteAllBytes(#"c:\01.jpg", Helper.DecodedBytes(Buffer, bytesRead));
and Encoding.Default.GetString(buffer, dataIndex, dataLength) to buffer.Skip(dataIndex).ToArray()
return buffer.Skip(dataIndex).ToArray();

Need help converting .PDE to P5.js

I'm new to both languages, and I'm trying to convert this program I found on github and edited, to p5.js so I can include it in a webpage. I tried following guides and replacing void() with function(), int i with var i etc.. but there seems to be something wrong. The first code is the original .pde and the second one is my attempt at converting it. Many thanks!
final int STAGE_WIDTH = 1200;
final int STAGE_HEIGHT = 950;
final int NB_PARTICLES = 60000;
final float MAX_PARTICLE_SPEED = 5;
final int MIN_LIFE_TIME = 20;
final int MAX_LIFE_TIME = 80;
final String IMAGE_PATH = "starrynight.jpg";
myVector tabParticles[];
float particleSize = 1.2;
PImage myImage;
int imageW;
int imageH;
color myPixels[];
FlowField ff;
GUI gui;
void setup()
{
size(1200, 950, P3D);
background(0);
initializeImage();
initializeParticles();
ff = new FlowField(5);
gui = new GUI(this);
gui.setup();
}
void initializeImage()
{
myImage = loadImage(IMAGE_PATH);
imageW = myImage.width;
imageH = myImage.height;
myPixels = new color[imageW * imageH];
myImage.loadPixels();
myPixels = myImage.pixels;
image(myImage, 0, 0);
}
void setParticle(int i) {
tabParticles[i] = new myVector((int)random(imageW), (int)random(imageH));
tabParticles[i].prevX = tabParticles[i].x;
tabParticles[i].prevY = tabParticles[i].y;
tabParticles[i].count = (int)random(MIN_LIFE_TIME, MAX_LIFE_TIME);
tabParticles[i].myColor = myPixels[(int)(tabParticles[i].y)*imageW + (int)(tabParticles[i].x)];
}
void initializeParticles()
{
tabParticles = new myVector[NB_PARTICLES];
for (int i = 0; i < NB_PARTICLES; i++)
{
setParticle(i);
}
}
void draw()
{
ff.setRadius(gui.getR());
ff.setForce(gui.getF());
particleSize = gui.getS();
float vx;
float vy;
PVector v;
for (int i = 0; i < NB_PARTICLES; i++)
{
tabParticles[i].prevX = tabParticles[i].x;
tabParticles[i].prevY = tabParticles[i].y;
v = ff.lookup(tabParticles[i].x, tabParticles[i].y);
vx = v.x;
vy = v.y;
vx = constrain(vx, -MAX_PARTICLE_SPEED, MAX_PARTICLE_SPEED);
vy = constrain(vy, -MAX_PARTICLE_SPEED, MAX_PARTICLE_SPEED);
tabParticles[i].x += vx;
tabParticles[i].y += vy;
tabParticles[i].count--;
if ((tabParticles[i].x < 0) || (tabParticles[i].x > imageW-1) ||
(tabParticles[i].y < 0) || (tabParticles[i].y > imageH-1) ||
tabParticles[i].count < 0) {
setParticle(i);
}
strokeWeight(1.5*particleSize);
stroke(tabParticles[i].myColor, 250);
line(tabParticles[i].prevX, tabParticles[i].prevY, tabParticles[i].x, tabParticles[i].y);
}
ff.updateField();
}
void mouseDragged() {
if(mouseX>950 && mouseY>830) return;
ff.onMouseDrag();
}
void keyPressed() {
//if (key =='s' || key == 'S') {
// ff.saveField();
//}
}
class myVector extends PVector
{
myVector (float p_x, float p_y) {
super(p_x, p_y);
}
float prevX;
float prevY;
int count;
color myColor;
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
class FlowField {
PVector[][] field;
PVector[][] tempField;
int cols, rows;
int resolution;
int affectRadius;
float force;
File file = new File(dataPath("field.txt"));
FlowField(int r) {
resolution = r;
cols = 1200 / resolution;
rows = 950 / resolution;
field = new PVector[cols][rows];
tempField = new PVector[cols][rows];
init();
affectRadius = 3;
force = 1;
}
void setRadius(int r) {
affectRadius = r;
}
void setForce(float f) {
force = f;
}
void init() {
try {
for (int i=0; i<cols; i++) {
for (int j=0; j<rows; j++) {
tempField[i][j] = new PVector(0, 0);
}
}
readField();
}
catch(Exception e) {
for (int i=0; i<cols; i++) {
for (int j=0; j<rows; j++) {
field[i][j] = new PVector(0, 0);
}
}
}
}
PVector lookup(float x, float y) {
int column = int(constrain(x/resolution, 0, cols-1));
int row = int(constrain(y/resolution, 0, rows-1));
return PVector.add(field[column][row],tempField[column][row]);
}
void drawBrush() {
pushStyle();
noFill();
stroke(255, 255, 255);
ellipse(mouseX, mouseY, affectRadius*10, affectRadius*10);
popStyle();
}
void drawField(float x, float y, PVector v) {
int column = int(constrain(x/resolution, 0, cols-1));
int row = int(constrain(y/resolution, 0, rows-1));
for (int i=-affectRadius; i<=affectRadius; i++) {
for (int j=-affectRadius; j<=affectRadius; j++) {
if (i*i+j*j<affectRadius*affectRadius) {
try {
tempField[column+i][row+j].add(v).mult(0.9);
}
catch(Exception e) {
}
}
}
}
}
void updateField(){
for (int i=0; i<cols; i++) {
for (int j=0; j<rows; j++) {
tempField[i][j].mult(0.992);
}
}
}
void onMouseDrag() {
PVector direc = new PVector(mouseX-pmouseX, mouseY-pmouseY).normalize();
drawField(pmouseX, pmouseY, direc.mult(force));
}
void saveField() {
try {
FileWriter out = new FileWriter(file);
for (int i=0; i<cols; i++) {
for (int j=0; j<rows; j++) {
out.write(field[i][j].x+","+field[i][j].y+"\t");
}
out.write("\r\n");
}
out.close();
}
catch(Exception e) {
}
}
void readField() throws IOException {
try {
BufferedReader in = new BufferedReader(new FileReader(file));
String line;
for (int i = 0; (line = in.readLine()) != null; i++) {
String[] temp = line.split("\t");
for (int j=0; j<temp.length; j++) {
String[] xy = temp[j].split(",");
float x = Float.parseFloat(xy[0]);
float y = Float.parseFloat(xy[1]);
field[i][j] = new PVector(x, y);
}
}
in.close();
}
catch(Exception e) {
throw new IOException("no field.txt");
}
}
}
import controlP5.*;
class GUI {
ControlP5 cp5;
Slider sliderR;
Slider sliderF;
Slider sliderS;
GUI(PApplet thePApplet){
cp5 = new ControlP5(thePApplet);
}
void setup(){
cp5.setColorBackground(0x141414);
sliderR = cp5.addSlider("Radius")
.setPosition(980,890)
.setRange(1,20)
.setValue(12).setSize(150,25);
sliderF = cp5.addSlider("Force")
.setPosition(980,918)
.setRange(0.1,0.5)
.setValue(0.3).setSize(150,25);
sliderS = cp5.addSlider("Particle Size")
.setPosition(980,862)
.setRange(0.8,2)
.setValue(1.5).setSize(150,25);
}
int getR(){
return int(sliderR.getValue());
}
float getF(){
return sliderF.getValue();
}
float getS(){
return sliderS.getValue();
}
}
final var STAGE_WIDTH = 1200;
final var STAGE_HEIGHT = 950;
final var NB_PARTICLES = 60000;
final let MAX_PARTICLE_SPEED = 5;
final var MIN_LIFE_TIME = 20;
final var MAX_LIFE_TIME = 80;
final let IMAGE_PATH = "starrynight.jpg";
myVector tabParticles[];
let particleSize = 1.2;
PImage myImage;
var imageW;
var imageH;
color myPixels[];
FlowField ff;
GUI gui;
function setup()
{
var canvas = createCanvas(1200, 950, P3D);
canvas.parent('canvasForHTML');
background(0);
initializeImage();
initializeParticles();
ff = new FlowField(5);
gui = new GUI(this);
gui.setup();
}
function preload() { img = loadImage('data/starrynight.jpg');
}
function initializeImage()
{ imageW = myImage.width;
imageH = myImage.height;
myPixels = new color[imageW * imageH];
myImage.loadPixels();
myPixels = myImage.pixels;
image(myImage, 0, 0);
}
function setParticle(var i) {
tabParticles[i] = new myVector((var)random(imageW), (var)random(imageH));
tabParticles[i].prevX = tabParticles[i].x;
tabParticles[i].prevY = tabParticles[i].y;
tabParticles[i].count = (var)random(MIN_LIFE_TIME, MAX_LIFE_TIME);
tabParticles[i].myColor = myPixels[(var)(tabParticles[i].y)*imageW + (var)(tabParticles[i].x)];
}
function initializeParticles()
{
tabParticles = new myVector[NB_PARTICLES];
for (var i = 0; i < NB_PARTICLES; i++)
{
setParticle(i);
}
}
function draw()
{
ff.setRadius(gui.getR());
ff.setForce(gui.getF());
particleSize = gui.getS();
let vx;
let vy;
PVector v;
for (var i = 0; i < NB_PARTICLES; i++)
{
tabParticles[i].prevX = tabParticles[i].x;
tabParticles[i].prevY = tabParticles[i].y;
v = ff.lookup(tabParticles[i].x, tabParticles[i].y);
vx = v.x;
vy = v.y;
vx = constrain(vx, -MAX_PARTICLE_SPEED, MAX_PARTICLE_SPEED);
vy = constrain(vy, -MAX_PARTICLE_SPEED, MAX_PARTICLE_SPEED);
tabParticles[i].x += vx;
tabParticles[i].y += vy;
tabParticles[i].count--;
if ((tabParticles[i].x < 0) || (tabParticles[i].x > imageW-1) ||
(tabParticles[i].y < 0) || (tabParticles[i].y > imageH-1) ||
tabParticles[i].count < 0) {
setParticle(i);
}
strokeWeight(1.5*particleSize);
stroke(tabParticles[i].myColor, 250);
line(tabParticles[i].prevX, tabParticles[i].prevY, tabParticles[i].x, tabParticles[i].y);
}
ff.updateField();
}
function mouseDragged() {
if(mouseX>950 && mouseY>830) return;
ff.onMouseDrag();
}
function keyPressed() {
//if (key =='s' || key == 'S') {
// ff.saveField();
//}
}
class myVector extends PVector
{
myVector (let p_x, let p_y) {
super(p_x, p_y);
}
let prevX;
let prevY;
var count;
color myColor;
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
class FlowField {
PVector[][] field;
PVector[][] tempField;
var cols, rows;
var resolution;
var affectRadius;
let force;
File file = new File(dataPath("field.txt"));
FlowField(var r) {
resolution = r;
cols = 1200 / resolution;
rows = 950 / resolution;
field = new PVector[cols][rows];
tempField = new PVector[cols][rows];
init();
affectRadius = 3;
force = 1;
}
function setRadius(var r) {
affectRadius = r;
}
function setForce(let f) {
force = f;
}
function init() {
try {
for (var i=0; i<cols; i++) {
for (var j=0; j<rows; j++) {
tempField[i][j] = new PVector(0, 0);
}
}
readField();
}
catch(Exception e) {
for (var i=0; i<cols; i++) {
for (var j=0; j<rows; j++) {
field[i][j] = new PVector(0, 0);
}
}
}
}
PVector lookup(let x, let y) {
var column = var(constrain(x/resolution, 0, cols-1));
var row = var(constrain(y/resolution, 0, rows-1));
return PVector.add(field[column][row],tempField[column][row]);
}
function drawBrush() {
pushStyle();
noFill();
stroke(255, 255, 255);
ellipse(mouseX, mouseY, affectRadius*10, affectRadius*10);
popStyle();
}
function drawField(let x, let y, PVector v) {
var column = var(constrain(x/resolution, 0, cols-1));
var row = var(constrain(y/resolution, 0, rows-1));
for (var i=-affectRadius; i<=affectRadius; i++) {
for (var j=-affectRadius; j<=affectRadius; j++) {
if (i*i+j*j<affectRadius*affectRadius) {
try {
tempField[column+i][row+j].add(v).mult(0.9);
}
catch(Exception e) {
}
}
}
}
}
function updateField(){
for (var i=0; i<cols; i++) {
for (var j=0; j<rows; j++) {
tempField[i][j].mult(0.992);
}
}
}
function onMouseDrag() {
PVector direc = new PVector(mouseX-pmouseX, mouseY-pmouseY).normalize();
drawField(pmouseX, pmouseY, direc.mult(force));
}
function saveField() {
try {
FileWriter out = new FileWriter(file);
for (var i=0; i<cols; i++) {
for (var j=0; j<rows; j++) {
out.write(field[i][j].x+","+field[i][j].y+"\t");
}
out.write("\r\n");
}
out.close();
}
catch(Exception e) {
}
}
function readField() throws IOException {
try {
BufferedReader in = new BufferedReader(new FileReader(file));
let line;
for (var i = 0; (line = in.readLine()) != null; i++) {
let[] temp = line.split("\t");
for (var j=0; j<temp.length; j++) {
let[] xy = temp[j].split(",");
let x = let.parselet(xy[0]);
let y = let.parselet(xy[1]);
field[i][j] = new PVector(x, y);
}
}
in.close();
}
catch(Exception e) {
throw new IOException("no field.txt");
}
}
}
import controlP5.*;
class GUI {
ControlP5 cp5;
Slider sliderR;
Slider sliderF;
Slider sliderS;
GUI(PApplet thePApplet){
cp5 = new ControlP5(thePApplet);
}
function setup(){
cp5.setColorBackground(0x141414);
sliderR = cp5.addSlider("Radius")
.setPosition(980,890)
.setRange(1,20)
.setValue(12).setSize(150,25);
sliderF = cp5.addSlider("Force")
.setPosition(980,918)
.setRange(0.1,0.5)
.setValue(0.3).setSize(150,25);
sliderS = cp5.addSlider("Particle Size")
.setPosition(980,862)
.setRange(0.8,2)
.setValue(1.5).setSize(150,25);
}
var getR(){
return var(sliderR.getValue());
}
let getF(){
return sliderF.getValue();
}
let getS(){
return sliderS.getValue();
}
}
I felt like doing nothing this evening, so here you go:
Also, I recommend getting the "Better Comments" extension/plugin for your code editor of choice, since I used those here a lot
const STAGE_WIDTH = 1200;
const STAGE_HEIGHT = 950;
const NB_PARTICLES = 60000;
const MAX_PARTICLE_SPEED = 5;
const MIN_LIFE_TIME = 20;
const MAX_LIFE_TIME = 80;
const IMAGE_PATH = "starrynight.jpg";
let tabParticles = [];
let particleSize = 1.2;
let myImage;
let imageW;
let imageH;
let myPixels = [];
let ff;
let gui;
function setup()
{
size(1200, 950, WEBGL);
background(0);
initializeImage();
initializeParticles();
ff = new FlowField(5);
// ! CHANGE THIS AND ALL OF THE OTHER GUI STUFF THAT COME AFTER IT!
// gui = new GUI(this);
// gui.setup();
}
function initializeImage()
{
myImage = loadImage(IMAGE_PATH);
imageW = myImage.width;
imageH = myImage.height;
myPixels = new color[imageW * imageH]; // ? dunno
// myImage.loadPixels();
// myPixels = myImage.pixels;
image(myImage, 0, 0);
}
function setParticle(i) {
tabParticles[i] = new myVector(random(imageW), random(imageH));
tabParticles[i].prevX = tabParticles[i].x;
tabParticles[i].prevY = tabParticles[i].y;
tabParticles[i].count = random(MIN_LIFE_TIME, MAX_LIFE_TIME);
tabParticles[i].myColor = myPixels[(int)(tabParticles[i].y)*imageW + (int)(tabParticles[i].x)];
}
function initializeParticles()
{
// tabParticles = new myVector[NB_PARTICLES];
for(let i = 0; i < NB_PARTICLES; i ++)
tabParticles.push(new myVector())
for (let i = 0; i < NB_PARTICLES; i++)
{
setParticle(i);
}
}
function draw()
{
ff.setRadius(gui.getR());
ff.setForce(gui.getF());
particleSize = gui.getS();
let vx;
let vy;
let v;
for (let i = 0; i < NB_PARTICLES; i++)
{
tabParticles[i].prevX = tabParticles[i].x;
tabParticles[i].prevY = tabParticles[i].y;
v = ff.lookup(tabParticles[i].x, tabParticles[i].y);
vx = v.x;
vy = v.y;
vx = constrain(vx, -MAX_PARTICLE_SPEED, MAX_PARTICLE_SPEED);
vy = constrain(vy, -MAX_PARTICLE_SPEED, MAX_PARTICLE_SPEED);
tabParticles[i].x += vx;
tabParticles[i].y += vy;
tabParticles[i].count--;
if ((tabParticles[i].x < 0) || (tabParticles[i].x > imageW-1) ||
(tabParticles[i].y < 0) || (tabParticles[i].y > imageH-1) ||
tabParticles[i].count < 0) {
setParticle(i);
}
strokeWeight(1.5*particleSize);
stroke(tabParticles[i].myColor, 250);
line(tabParticles[i].prevX, tabParticles[i].prevY, tabParticles[i].x, tabParticles[i].y);
}
ff.updateField();
}
function mouseDragged() {
if(mouseX>950 && mouseY>830) return;
ff.onMouseDrag();
}
function keyPressed() {
//if (key =='s' || key == 'S') {
// ff.saveField();
//}
}
class myVector extends PVector
{
constructor (p_x, p_y) {
super(p_x, p_y);
this.prevX
this.prevY
this.count
this.myColor
}
}
class FlowField {
constructor(r) {
this.field; // PVector[][]
this.tempField; // PVector[][]
this.cols; this.rows; // int
this.resolution; // int
this.affectRadius; // int
this.force; // float
this.file = new File(dataPath("field.txt")); // File
// ! You'll need to have a preload loadStrings(filepath) or fetch(filename).then(blob => blob.text()).then(text => ... )
// ! can't be bothered to do this right now
throw "Ult1: change this!!! also delete this line (just incase: ~129th line)"
resolution = r;
cols = 1200 / resolution;
rows = 950 / resolution;
field = new PVector[cols][rows];
tempField = new PVector[cols][rows];
init();
affectRadius = 3;
force = 1;
}
setRadius(r) {
affectRadius = r;
}
setForce(f) {
force = f;
}
// FROM HERE ON I CONVERTED IT WHILE HALF ASLEEP (11pm)
init() {
try {
for (let i=0; i<cols; i++) {
for (let j=0; j<rows; j++) {
tempField[i][j] = createVector()
}
}
readField();
}
catch(e) {
for (let i=0; i<cols; i++) {
for (let j=0; j<rows; j++) {
field[i][j] = createVector()
}
}
}
}
lookup(x, y) {
let column = int(constrain(x/resolution, 0, cols-1));
let row = int(constrain(y/resolution, 0, rows-1));
return p5.Vector.add(field[column][row],tempField[column][row]);
}
drawBrush() {
pushStyle();
noFill();
stroke(255, 255, 255);
ellipse(mouseX, mouseY, affectRadius*10, affectRadius*10);
popStyle();
}
drawField(x, y, v) {
let column = int(constrain(x/resolution, 0, cols-1));
let row = int(constrain(y/resolution, 0, rows-1));
for (let i=-affectRadius; i<=affectRadius; i++) {
for (let j=-affectRadius; j<=affectRadius; j++) {
if (i*i+j*j<affectRadius*affectRadius) {
try {
tempField[column+i][row+j].add(v).mult(0.9);
}
catch(e) {
}
}
}
}
}
updateField(){
for (let i=0; i<cols; i++) {
for (let j=0; j<rows; j++) {
tempField[i][j].mult(0.992);
}
}
}
onMouseDrag() {
let direc = createVector(mouseX-pmouseX, mouseY-pmouseY).normalize()
drawField(pmouseX, pmouseY, direc.mult(force));
}
saveField() {
try {
// FileWriter out = new FileWriter(file);
throw "FileWriter doesn't exist in Javascript, line: 215"
// ! this doesn't exist! in javascript, I don't remember how to do this, but you can just search it on Google
for (let i=0; i<cols; i++) {
for (let j=0; j<rows; j++) {
out.write(field[i][j].x+","+field[i][j].y+"\t");
}
out.write("\r\n");
}
out.close();
}
catch(e) {
}
}
readField() {
throw "once again, BufferedReader is just not a thing, but it's for file reading, so you can just loadString(\"file\") or fetch... line: 230"
try {
let _in = new BufferedReader(new FileReader(file));
let line;
for (let i = 0; (line = _in.readLine()) != null; i++) {
let temp = line.split("\t");
for (let j=0; j<temp.length; j++) {
let xy = temp[j].split(",");
let x = Float.parseFloat(xy[0]);
let y = Float.parseFloat(xy[1]);
field[i][j] = createVector(x, y);
}
}
_in.close();
}
catch(e) {
throw new IOException("no field.txt");
}
}
}
// I think you should just do this with html to be honest
// copy this into your body (below the <script src="sketch.js"></script>, or above it):
/*
<div id="GUI">
<label for="Radius">Radius</label>
<input type="range" name="Radius" id="slider-radius" min="1" max="20" step="0.5" value="10">
<br>
<label for="Force">Force</label>
<input type="range" name="Force" id="slider-force" min="0.1" max="0.5" step="0.01" value="0.3">
<br>
<label for="Particle-size">Particle size</label>
<input type="range" name="Particle-size" id="slider-particle-size" min="0.8" max="2" step="0.05" value="1.5">
</div>
<style>
html, body {
background-color: #141414;
}
label {
color: #ccc;
}
</style>
*/
// color: #ccc is the same as text-color = #CCCCCC in some other language, maybe...
class GUI {
constructor(){
throw "don't declare the GUI class, instead do GUI.getR(), GUI.getF() ... line: 288, you should be able to see line # in your console"
}
static getR(){
return document.getElementById("slider-radius").value;
}
static getF(){
return document.getElementById("slider-force").value
}
static getS(){
return document.getElementById("slider-particle-size").value
}
}
// static = same between ALL the classes(instances) of a class thing, so:
// class A { static x = 7; this.y = 5 }
// * console.log(A.x) -> 7
// ! console.log(A.y) -> probably null, since you need to do console.log(new A().y)
// here I have it to keep the GUI class, but there is no need to keep this stuff
You will still need to do A LOT of work to get this going, like translating classes, for example class myVector extends PVector {...}. In p5.js there is no PVector, but I'm pretty sure there's p5.Vector though, so class myVector extends p5.Vector might work. File reading and writing will also be messed up, since JavaScript doesn't have the whole new File() and all the stuff like that.
You will also need to deal with CORS, good luck! I also changed most of the GUI stuff to .html stuff and a static class, bit hard words there, but can't really change them to anything.
Anyways, I probably made mistakes here!
It's 11:40 pm here by now, so yeah! this is very more or less transferrrr

How to repeat a function without effecting repeating the token

How do I modify the repeat loop function without it repeating the token variable in the function rowcount()?
function rowcount()
{
var token = getAccessToken();
var module = "sHistory";
var rows = 0;
var go = true;
var i = 1;
var data;
while (go) {
data = getRecordsByPage(i,200,token,module);
if (Number(data.info.count) < 200) {
go = false;
};
if ((i%10) == 0) {
go = false;
}
rows = Number(rows) + Number(data.info.count);
i++;
Logger.log(rows)
}
return rows
}
function repeatloop()
{
let counter = 0;
for(var i = 1; i <= 93; i++)
{
{
Utilities.sleep(10000);
Logger.log(i);
counter += rowcount();
Logger.log(counter);
}
}
return rowcount().rows;
}
What I am also trying to do is let the count continue because right now it goes in an increment of 2000, but I need it to continue like 200...400..600..800...1000...1200...1400...1600...1800...2000...2200. and it goes on until the loop stops.
You can make the token a global variable like this:
var token;
function rowcount()
{
var module = "sHistory";
var rows = 0;
var go = true;
var i = 1;
var data;
while (go) {
data = getRecordsByPage(i,200,token,module);
if (Number(data.info.count) < 200) {
go = false;
};
if ((i%10) == 0) {
go = false;
}
rows = Number(rows) + Number(data.info.count);
i++;
Logger.log(rows)
}
return rows
}
function repeatloop()
{
let counter = 0;
token = getAccessToken();
for(var i = 1; i <= 93; i++)
{
{
Utilities.sleep(10000);
Logger.log(i);
counter += rowcount();
Logger.log(counter);
}
}
return rowcount().rows;
}
Or did I understand you wrong?
I would pass the token as an optional parameter, insted to use GLOBAL variable:
function rowcount(_token = null)
{
let token;
if (_token) {token = _token;}
else {token = getAccessToken();}
var module = "sHistory";
var rows = 0;
var go = true;
var i = 1;
var data;
while (go) {
data = getRecordsByPage(i,200,token,module);
if (Number(data.info.count) < 200) {
go = false;
};
if ((i%10) == 0) {
go = false;
}
rows = Number(rows) + Number(data.info.count);
i++;
Logger.log(rows)
}
return rows
}
function repeatloop()
{
let token = getAccessToken();
let counter = 0;
for(var i = 1; i <= 93; i++)
{
{
Utilities.sleep(10000);
Logger.log(i);
counter += rowcount(token);
Logger.log(counter);
}
}
return rowcount(token).rows;
}

Form a tree or nodes from a raw string

I have the following as a string
var string = "#anno1[ data1 xyz #anno2[data2 #anno3[data3] data4] data5 #anno4[data6] data7]"
And I would like to convert it an object as follows:
var childs = [
{
name : '#anno1',
text : 'data1 xyz data2 data3 data4 data5 data6 data7',
},
{
name : '#anno2',
text : 'data2 data3 data4'
},
{
name : '#anno3',
text : 'data3'
},
{
name : '#anno4',
text : 'data6'
}
]
I've tried out many ways but I was not successful, thanks in advance.
Here is the java code which i have tried
import java.util.HashMap;
import java.util.Map;
public class ExpressionTree {
static Map <String, String> resultMap = new HashMap<String, String>(16);
public static void main(String args[]) {
// String exp = "[data1 xyz #anno2[data2 #anno3[data3] data4] data5 #anno4[data6] data7]";
String exp = "#anno1[ data1 xyz #anno2[data2 #anno3[data3] data4] data5 #anno4[data6] data7 ]";
parseRecursively(exp);
}
private static void parseRecursively(String exp) {
String annotation = null;
String annotationValue = null;
if (exp.startsWith("#")) {
int dataStartIndex = exp.indexOf("[");
annotation = exp.substring(0, dataStartIndex);
annotationValue = exp.substring(0 + dataStartIndex, exp.lastIndexOf("]")+1).trim();
System.out.println(annotation);
System.out.println(annotationValue);
resultMap.put(annotation, annotationValue);
parseRecursively(annotationValue);
} else {
int annotationStartIndex = exp.indexOf("#");
int dataStartIndex = exp.substring(1).indexOf("[");
if( -1 != annotationStartIndex || -1 != dataStartIndex)
{
annotation = exp.substring(annotationStartIndex, dataStartIndex+1).trim();
String nextData = exp.substring(0 + dataStartIndex + 1).trim();
String tmpNextData = nextData;
int countOfOpenBrackets = 0;
for (int i = 0; tmpNextData.charAt(i) != ']'; i++) {
// System.out.println(tmpNextData.charAt(i));
if (tmpNextData.charAt(i) == '[') {
countOfOpenBrackets++;
}
// tmpNextData = tmpNextData.substring(1);
}
tmpNextData = nextData;
int endIndexOfCurrentData = 0;
for (int i = 0; i < tmpNextData.length() && endIndexOfCurrentData == 0; i++) {
// System.out.println(tmpNextData.charAt(i));
if (tmpNextData.charAt(i) == ']') {
countOfOpenBrackets--;
}
if (countOfOpenBrackets == 0) {
endIndexOfCurrentData = i + 1;
}
// tmpNextData = tmpNextData.substring(1);
}
annotationValue = nextData.substring(0, endIndexOfCurrentData).trim();
System.out.println(annotation);
System.out.println(annotationValue);
resultMap.put(annotation, annotationValue);
parseRecursively(annotationValue);
}
}
System.out.println(resultMap);
}
}
Here is a JavaScript (ES6) solution:
function toObject(string) {
"use strict";
const tokens = string.match(/[\[\]]|[^\s\[\]]+/g),
result = [];
let i = 0;
function recurse() {
const words = [];
let obj;
while (i < tokens.length) {
let token = tokens[i];
if (token[0] === '#') {
obj = {name: token};
result.push(obj);
} else if (token === '[') {
i++;
obj.text = recurse();
words.push(obj.text);
} else if (token === ']') {
break;
} else {
words.push(token);
}
i++;
}
return words.join(' ');
}
recurse();
return result;
}
const string = "#anno1[ data1 xyz #anno2[data2 #anno3[data3] data4] data5 #anno4[data6] data7]";
const result = toObject(string);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Compiles through Netbeans, doesn't compile through CMD

i've got my code to work on a Storage Management
Page Replacement Methods assignment. And my code works through Netbeans but it doesn't compile through CMD.
Do you know why?
public class Paging {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException, IOException, IOException, IOException {
BufferedReader obj = new BufferedReader(new InputStreamReader(System.in));
try {
URL url = new URL("www.csc.liv.ac.uk/~ped/COMP104/COMP104-2016-17/Page_Trace_Oldest");
URL url3 = new URL("www.csc.liv.ac.uk/~ped/COMP104/COMP104-2016-17/Page_Trace_Random");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
str = in.readLine().toString();
System.out.println(str);
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
URL url2 = new URL("www.csc.liv.ac.uk/~ped/COMP104/COMP104-2016-17/Page_Trace_LRU");
BufferedReader in = new BufferedReader(new InputStreamReader(url2.openStream()));
String str2;
while ((str2 = in.readLine()) != null) {
str2 = in.readLine().toString();
System.out.println(str2);
}
in.close();
URL url3 = new URL("www.csc.liv.ac.uk/~ped/COMP104/COMP104-2016-17/Page_Trace_Random");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str3;
while ((str3 = in.readLine()) != null) {
str2 = in.readLine().toString();
System.out.println(str3);
}
in.close();
int f, page = 0, ch, pgf = 0, n = 0, chn = 0;
boolean flag;
int pages[];
do {
System.out.println("Menu");
System.out.println("1.FIFO");
System.out.println("2.LRU");
System.out.println("3.LFU");
System.out.println("4.EXIT");
System.out.println("ENTER YOUR CHOICE: ");
try {
ch = Integer.parseInt(obj.readLine());
} catch (IOException ex) {
Logger.getLogger(Paging.class.getName()).log(Level.SEVERE, null, ex);
}
switch (ch) {
case 1:
int pt = 0;
System.out.println("Enter no. of frames (1-8): ");
f = Integer.parseInt(obj.readLine());
int frame[] = new int[f];
for (int i = 0; i < f; i++) {
frame[i] = -1;
}
System.out.println("enter the no of pages ");
n = Integer.parseInt(obj.readLine());
pages = new int[n];
System.out.println("enter the page no ");
for (int j = 0; j < n; j++) {
pages[j] = Integer.parseInt(obj.readLine());
}
do {
int pg = 0;
for (pg = 0; pg < n; pg++) {
page = pages[pg];
flag = true;
for (int j = 0; j < f; j++) {
if (page == frame[j]) {
flag = false;
break;
}
}
if (flag) {
frame[pt] = page;
pt++;
if (pt == f) {
pt = 0;
}
System.out.print("frame :");
for (int j = 0; j < f; j++) {
System.out.print(frame[j] + " ");
}
System.out.println();
pgf++;
} else {
System.out.print("frame :");
for (int j = 0; j < f; j++) {
System.out.print(frame[j] + " ");
}
System.out.println();
}
chn++;
}
} while (chn != n);
System.out.println("Page fault:" + pgf);
break;
case 2:
int k = 0;
System.out.println("enter no. of frames: ");
{
try {
f = Integer.parseInt(obj.readLine());
} catch (IOException ex) {
Logger.getLogger(Paging.class.getName()).log(Level.SEVERE, null, ex);
}
}
int frame1[] = new int[f];
int a[] = new int[f];
int b[] = new int[f];
for (int i = 0; i < f; i++) {
frame1[i] = -1;
a[i] = -1;
b[i] = -1;
}
System.out.println("enter the no of pages ");
{
try {
n = Integer.parseInt(obj.readLine());
} catch (IOException ex) {
Logger.getLogger(Paging.class.getName()).log(Level.SEVERE, null, ex);
}
}
pages = new int[n];
System.out.println("enter the page no ");
for (int j = 0; j < n; j++) {
try {
pages[j] = Integer.parseInt(obj.readLine());
} catch (IOException ex) {
Logger.getLogger(Paging.class.getName()).log(Level.SEVERE, null, ex);
}
}
do {
int pg = 0;
for (pg = 0; pg < n; pg++) {
page = pages[pg];
flag = true;
for (int j = 0; j < f; j++) {
if (page == frame1[j]) {
flag = false;
break;
}
}
for (int j = 0; j < f && flag; j++) {
if (frame1[j] == a[f - 1]) {
k = j;
break;
}
}
if (flag) {
frame1[k] = page;
System.out.println("frame :");
for (int j = 0; j < f; j++) {
System.out.print(frame1[j] + " ");
}
pgf++;
System.out.println();
} else {
System.out.println("frame :");
for (int j = 0; j < f; j++) {
System.out.print(frame1[j] + " ");
}
System.out.println();
}
int p = 1;
b[0] = page;
for (int j = 0; j < a.length; j++) {
if (page != a[j] && p < f) {
b[p] = a[j];
p++;
}
}
for (int j = 0; j < f; j++) {
a[j] = b[j];
}
chn++;
}
} while (chn != n);
System.out.println("Page fault:" + pgf);
break;
case 3:
k = 0;
pgf = 0;
int sml;
System.out.println("enter no. of frames: ");
{
try {
f = Integer.parseInt(obj.readLine());
} catch (IOException ex) {
Logger.getLogger(Paging.class.getName()).log(Level.SEVERE, null, ex);
}
}
int frame2[] = new int[f];
int cnt[] = new int[f];
flag = true;
for (int i = 0; i < f; i++) {
frame2[i] = -1;
cnt[i] = 0;
}
System.out.println("enter the no of pages ");
{
try {
n = Integer.parseInt(obj.readLine());
} catch (IOException ex) {
Logger.getLogger(Paging.class.getName()).log(Level.SEVERE, null, ex);
}
}
pages = new int[n];
System.out.println("enter the page no ");
for (int j = 0; j < n; j++) {
try {
pages[j] = Integer.parseInt(obj.readLine());
} catch (IOException ex) {
Logger.getLogger(Paging.class.getName()).log(Level.SEVERE, null, ex);
}
}
do {
int pg = 0;
for (pg = 0; pg < n; pg++) {
page = pages[pg];
flag = true;
for (int j = 0; j < f; j++) {
if (page == frame2[j]) {
flag = false;
cnt[j]++;
break;
}
}
if (flag) {
sml = cnt[0];
for (int j = 0; j < f; j++) {
if (cnt[j] < sml) {
sml = cnt[j];
break;
}
}
for (int j = 0; j < f; j++) {
if (sml == cnt[j]) {
frame2[j] = page;
k = j;
break;
}
}
cnt[k] = 1;
System.out.print("frame :");
for (int j = 0; j < f; j++) {
System.out.print(frame2[j] + " ");
System.out.println();
pgf++;
}
} else {
System.out.print("frame :");
for (int j = 0; j < f; j++) {
System.out.print(frame2[j] + " ");
}
System.out.println();
}
chn++;
}
} while (chn != n);
System.out.println("Page fault:" + pgf);
break;
case 4:
break;
}
} while (ch != 4);
}
}
The error i'm getting is that :
You're creating 2 BufferedReader objects with the same name.
URL url2 = new URL("www.csc.liv.ac.uk/~ped/COMP104/COMP104-2016-17/Page_Trace_LRU");
BufferedReader in = new BufferedReader(new InputStreamReader(url2.openStream()));
and
URL url3 = new URL("www.csc.liv.ac.uk/~ped/COMP104/COMP104-2016-17/Page_Trace_Random");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

Categories