Categories
discuss

Android Creating Table Programmatically

I am trying to generate a number table with given row and column number. The program takes two parameters from the user and creating a table rows and columns with given parameters. Each cell is going to have a random number value between 1 to 100. As far as, I coded my XML with 2 different EditText views which are going to be my parameters. There are four buttons “Create”, “Calculate”, “Reset”, “Exit” that I am going to use. When the user clicks “Create” button, table will be generated with the given row and column values. Therefore I have to create my table from my java file instead of XML file.

This is my code so far:

public class MainActivity extends AppCompatActivity {

private Button btnCreate, btnCalculate, btnReset, btnExit;
private EditText txtColumn, txtRow;
private LinearLayout linLayout;
private TableLayout table;
private TextView txtResult;
private Random random;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnCreate = (Button) findViewById(R.id.btnCreate);
    btnCalculate = (Button) findViewById(R.id.btnCalculate);
    btnReset = (Button) findViewById(R.id.btnReset);
    btnExit = (Button) findViewById(R.id.btnExit);

    txtColumn = (EditText) findViewById(R.id.txtColumn);
    txtRow = (EditText) findViewById(R.id.txtRow);
    txtResult = (TextView) findViewById(R.id.txtResult);
    txtColumn.requestFocus();

    random = new Random();

    TableLayout table = new TableLayout(this);

    btnCalculate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    });

    btnCreate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            table.setLayoutParams(new TableLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            table.setShrinkAllColumns(true);
            table.setStretchAllColumns(true);
            int columnNumber = Integer.parseInt(txtColumn.getText().toString());
            int rowNumber = Integer.parseInt(txtRow.getText().toString());

            for(int i=0; i<rowNumber; i++) {
                TableRow row = new TableRow();
                for(int j=0; i<columnNumber; i++) {
                    int value = random.nextInt(100) + 1;
                    TextView tv = new TextView();
                    tv.setText(String.valueOf(value));
                    row.addView(tv);
                }
                table.addView(row);
            }
        }
    });

    btnExit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            System.exit(0);
        }
    });
    btnReset.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            txtColumn.setText(null);
            txtRow.setText(null);
            txtResult.setText(null);
        }
    });
}
}

I am getting an error at my “for” loops. It says “TableRow” has to get Context parameter inside. However, I really didn’t understand what kind of parameter it wants. I tried to search for table creation programmatically, however no luck so far. How am I supposed to fix this error?

Answer

You need to pass context while creating a table row. try below code

for (int i=0; i < rowNumber; i++) {
  TableRow row = new TableRow(MainActivity.this);
      for (int j=0; j < columnNumber; j++) {
        int value = random.nextInt(100) + 1;
        TextView tv = new TextView(MainActivity.this);
        tv.setText(String.valueOf(value));
        row.addView(tv);
      }
  table.addView(row);
}

And you also need to add tablelayout to any view of xml for example in your xml file add liner layout like below

<LinearLayout 
    android:id="@+id/mainLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"/>

Cast that view in java file like below

LinearLayout mainLayout = findViewById(R.id.mainLayout); 

Add your table layout to this view like below

mainLayout.addView(table);
Categories
discuss

Canvas to blob on Edge

Getting exception on Microsoft Edge browser when trying to convert Html canvas element to blob. Everything works great on normal browsers. Exception:

SCRIPT438: Object doesn’t support property or method ‘toBlob’

Html snippet:

<canvas id="cnv" width="640px" height="520px" style="display: none"></canvas>

Javascript:

var files[];
var canvas = document.getElementById('cnv');
canvas.toBlob(function (blob) {            
        files.push(blob);
         }
    }, 'image/jpeg', 1);

I get this exception right when I call toBlob method. Are there any ways to teach Edge blob converting? I am using :

Microsoft Edge 41.16299.15.0

Answer

This small polyfill taken from here must help see jsfiddle

if (!HTMLCanvasElement.prototype.toBlob) {
   Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
     value: function (callback, type, quality) {
       var canvas = this;
       setTimeout(function() {
         var binStr = atob( canvas.toDataURL(type, quality).split(',')[1] ),
         len = binStr.length,
         arr = new Uint8Array(len);

         for (var i = 0; i < len; i++ ) {
            arr[i] = binStr.charCodeAt(i);
         }

         callback( new Blob( [arr], {type: type || 'image/png'} ) );
       });
     }
  });
}

This could help as well github.com/blueimp/JavaScript-Canvas-to-Blob

Categories
discuss

Error when compiling with Gradle (can’t find downloaded dependencies)

I develop an app generation system that is regenerating apps by command line Gradle compilation commands.

In my Windows Server 2008, I’m facing a problem after updating to the last Gradle version and Gradle plugin version.

When compiling I’m getting this errors:

C:WindowsSystem32configsystemprofile.gradlecachestransforms-1files-1.1appcompat-v7-25.0.0.aare93435c34d5cae8b6677dcef529711a5resdrawable-xxhdpi-v4abc_text_select_handle_middle_mtrl_light.png: error: file not found.

C:WindowsSystem32configsystemprofile.gradlecachestransforms-1files-1.1appcompat-v7-25.0.0.aare93435c34d5cae8b6677dcef529711a5resdrawableabc_btn_colored_material.xml: error: file not found.

C:WindowsSystem32configsystemprofile.gradlecachestransforms-1files-1.1appcompat-v7-25.0.0.aare93435c34d5cae8b6677dcef529711a5resdrawable-hdpi-v4abc_textfield_search_default_mtrl_alpha.9.png: error: file not found.

and a lot more of errors like those...

I’m not sure why I’m getting this error, because the file is correctly downloaded and it’s correctly located on that exactly direction.

It has a path length of 204 characters, so supposedly it’s not surpassing the limit of 255 path characters on NTFS Windows file system.

It is possible to change the location where Gradle downloads it’s cached dependencies? Is this problem caused by this or by other thing?

Answer

finally i solved this setting the environmental variable GRADLE_USER_HOME in windows to c:/gradle-cache

so definitively it’s related to file path lenght

Categories
discuss

How to make two row of top fixed menu in semantic-ui

AS title, I want the top fixed menu have two rows instead of one.

Here is what I have tried.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.13/semantic.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.13/semantic.css">
<div class="ui top fixed inverted menu">
    <div class="ui container">
        <a class="item">Item</a>
        <a class="item">Item</a>
    </div>
    <div class="ui container">
        <a class="item">Item</a>
    </div>
</div>

Using second container result in both occupying 50% width. Using column and grid also not working (the menu no longer maintain its layout). It seems to be a simple question. Any helps are welcome.

Answer

I just try with a display:block to force your parent div displaying this way. Looks working.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.13/semantic.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.13/semantic.css">
<div class="ui top fixed inverted menu" style="display:block">
    <div class="ui container">
        <a class="item">Item</a>
        <a class="item">Item</a>
    </div>
    <div class="ui container">
        <a class="item">Item</a>
    </div>
</div>
Categories
discuss

ACL – Implement acl together with passport

I am trying out node_acl with passport-local. When I run my code I cannot secure the route for the admin-user '/admin' and I am redirected to the /login page.

Find below my minimum runnable example:

require('dotenv').config()
const express = require('express')
// const fs = require('fs')
const path = require('path')
const logger = require('morgan')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const session = require('express-session')
const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy
const ACL = require('acl')

// load user.json file
// const d = fs.readFileSync(path.join(__dirname, '/../data/user.json'))
// const userObj = JSON.parse(d)
const userObj = [{
  id: 1,
  username: 'admin',
  password: 'admin',
  email: 'admin@admin.com',
  role: 'admin',
},
{
  id: 2,
  username: 'user',
  password: 'user',
  email: 'user@user.com',
  role: 'user',
},
]

const app = express()

// view engine setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'pug')
app.use(logger(process.env.LOG_ENV))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
  extended: false,
}))
app.use(express.static(path.join(__dirname, '/../public')))
app.use(cookieParser())

app.use(session({
  secret: 'super-mega-hyper-secret',
  resave: false,
  saveUninitialized: false,
}))

/**
 * Passport Local
 */
app.use(passport.initialize())
app.use(passport.session())

function authenticate() {
  passport.serializeUser((user, done) => {
    done(null, user.id)
  })

  passport.deserializeUser(async(id, done) => {
    //        const user = await serviceAuth.findById(id)
    const user = userObj.find(item => item.id === id)
    done(null, user)
  })

  // Sign in with username and Password
  passport.use('local', new LocalStrategy({
    usernameField: 'username',
  }, async(username, password, done) => {
    const user = userObj.find(item => item.username === username)
    done(null, user)
  }))
}

const isAuthenticated = (req, res, next) => {
  if (req.isAuthenticated()) {
    res.locals.user = req.session.user
    return next()
  }
  res.redirect('login')
}
authenticate()

/**
 * Node ACL
 */

function accessControl() {
  const nodeAcl = new ACL(new ACL.memoryBackend())

  nodeAcl.allow([{
    roles: 'admin',
    allows: [{
      resources: '/admin',
      permissions: '*',
    }],
  }, {
    roles: 'user',
    allows: [{
      resources: '/dashboard',
      permissions: 'get',
    }],
  }, {
    roles: 'guest',
    allows: [],
  }])

  // Inherit roles
  //  Every user is allowed to do what guests do
  //  Every admin is allowed to do what users do
  nodeAcl.addRoleParents('user', 'guest')
  nodeAcl.addRoleParents('admin', 'user')

  nodeAcl.addUserRoles(1, 'admin')
  nodeAcl.addUserRoles(2, 'user')
  nodeAcl.addUserRoles(0, 'guest')

  return nodeAcl
}

/*
function checkPermission(resource, action) {
  const access = accessControl()

  return (req, res, next) => {
    const uid = req.session.user.id
    access.isAllowed(uid, resource, action, (err, result) => {
      if (result) {
        next()
      } else {
        const checkError = new Error('User does not have permission to perform this action on this resource')
        next(checkError)
      }
    })
  }
} */

const getCurrentUserId = (req) => {
  console.log(req)
  req.user && req.user.id.toString() || false
}

const access = accessControl()

// Routes
app.get('/login', (req, res) => {
  res.render('login')
})

app.post('/login', (req, res, next) => {
  passport.authenticate('local', (err, user) => {
    if (err) return next(err)
    if (!user) {
      return res.status(401).json({
        error: 'Email or password is incorrect.',
      })
    }

    return res.render('dashboard')
  })(req, res, next)
})

app.get('/dashboard', [isAuthenticated, access.middleware()], (req, res) => {
  res.render('dashboard')
})

app.get('/admin', [isAuthenticated, access.middleware()], (req, res) => {
  res.render('admin')
})

app.get('/status', (request, response) => {
  access.userRoles(getCurrentUserId(request), (error, roles) => {
    response.send(`User: ${JSON.stringify(request.user)} Roles: ${JSON.stringify(roles)}`)
  })
})

// Start Server
const port = process.env.APP_PORT || 8080
const host = process.env.APP_URL || 'localhost'

app.listen(port, host, () => {
  console.log(`Listening on ${host}:${port}`)
})

module.exports = app

Any suggestions why the route, /admin cannot be called only be the admin user?

Thank you in advance for your replies!

Answer

I couldn’t run your “runnable” code so i changed it a bit to check it out. So after some tests it seems that it works just fine. Can you check it too?

Using POSTMAN I did a POST on /login?username=user&password=user

After that I did a GET on `/status’ and I got

User: {"id":2,"username":"user","password":"user","email":"user@user.com","role":"user"} Roles: []

Then I did a GET on /admin and i got

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Error</title>
    </head>
    <body>
        <pre>HttpError: Insufficient permissions to access resource
            <br> &nbsp; &nbsp;at C:Usersstamoulis.zamanisDesktopaclTestnode_modulesacllibacl.js:705:14
            <br> &nbsp; &nbsp;at tryCatcher (C:Usersstamoulis.zamanisDesktopaclTestnode_modulesbluebirdjsreleaseutil.js:16:23)
            <br> &nbsp; &nbsp;at Promise.successAdapter [as _fulfillmentHandler0] (C:Usersstamoulis.zamanisDesktopaclTestnode_modulesbluebirdjsreleasenodeify.js:23:30)
            <br> &nbsp; &nbsp;at Promise._settlePromise (C:Usersstamoulis.zamanisDesktopaclTestnode_modulesbluebirdjsreleasepromise.js:566:21)
            <br> &nbsp; &nbsp;at Promise._settlePromise0 (C:Usersstamoulis.zamanisDesktopaclTestnode_modulesbluebirdjsreleasepromise.js:614:10)
            <br> &nbsp; &nbsp;at Promise._settlePromises (C:Usersstamoulis.zamanisDesktopaclTestnode_modulesbluebirdjsreleasepromise.js:693:18)
            <br> &nbsp; &nbsp;at Async._drainQueue (C:Usersstamoulis.zamanisDesktopaclTestnode_modulesbluebirdjsreleaseasync.js:133:16)
            <br> &nbsp; &nbsp;at Async._drainQueues (C:Usersstamoulis.zamanisDesktopaclTestnode_modulesbluebirdjsreleaseasync.js:143:10)
            <br> &nbsp; &nbsp;at Immediate.Async.drainQueues (C:Usersstamoulis.zamanisDesktopaclTestnode_modulesbluebirdjsreleaseasync.js:17:14)
            <br> &nbsp; &nbsp;at runCallback (timers.js:789:20)
            <br> &nbsp; &nbsp;at tryOnImmediate (timers.js:751:5)
            <br> &nbsp; &nbsp;at processImmediate [as _immediateCallback] (timers.js:722:5)
        </pre>
    </body>
</html>

Then I logged in as admin and when I called /admin again i got admin

I had to change app.post('/login'). If i didnt do req.login then passport.serializeUser was never called, the cookie wasn’t correct resulting in bad session.

app.post('/login', (req, res, next) => {
  passport.authenticate('local', (err, user) => {
    if (err) return next(err)
    if (!user) {
      return res.status(401).json({
        error: 'Email or password is incorrect.',
      })
    }
     req.logIn(user, function (err) { // <-- Log user in
       next();
    });


  })(req, res, next)
},function(req,res){
 res.send('dashboard')
})

All code:

require('dotenv').config()
const express = require('express')
// const fs = require('fs')
const path = require('path')
const logger = require('morgan')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const session = require('express-session')
const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy
const ACL = require('acl')

// load user.json file
// const d = fs.readFileSync(path.join(__dirname, '/../data/user.json'))
// const userObj = JSON.parse(d)
const userObj = [{
  id: 1,
  username: 'admin',
  password: 'admin',
  email: 'admin@admin.com',
  role: 'admin',
},
{
  id: 2,
  username: 'user',
  password: 'user',
  email: 'user@user.com',
  role: 'user',
},
]

const app = express()

// view engine setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'pug')
app.use(logger(process.env.LOG_ENV))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
  extended: false,
}))
app.use(express.static(path.join(__dirname, '/../public')))
app.use(cookieParser())

app.use(session({
  secret: 'super-mega-hyper-secret',
  resave: false,
  saveUninitialized: false,
}))



function authenticate() {
  passport.serializeUser((user, done) => {
    done(null, user.id)
  })

  passport.deserializeUser((id, done) => {
    //        const user = await serviceAuth.findById(id)
    const user = userObj.find(item => item.id === id)
    done(null, user)
  })

  // Sign in with username and Password
  passport.use('local', new LocalStrategy({
    usernameField : 'username',
        passwordField : 'password'
  }, async(username, password, done) => {
    const user = userObj.find(item => item.username === username)
    done(null, user)
  }))
}

const isAuthenticated = (req, res, next) => {
  if (req.isAuthenticated()) {
    res.locals.user = req.session.user
    return next()
  }
  res.redirect('login')
}
authenticate()


/**
 * Passport Local
 */
app.use(passport.initialize())
app.use(passport.session())

/**
 * Node ACL
 */

function accessControl() {
  const nodeAcl = new ACL(new ACL.memoryBackend())

  nodeAcl.allow([{
    roles: 'admin',
    allows: [{
      resources: '/admin',
      permissions: '*',
    }],
  }, {
    roles: 'user',
    allows: [{
      resources: '/dashboard',
      permissions: 'get',
    }],
  }, {
    roles: 'guest',
    allows: [],
  }])

  // Inherit roles
  //  Every user is allowed to do what guests do
  //  Every admin is allowed to do what users do
  nodeAcl.addRoleParents('user', 'guest')
  nodeAcl.addRoleParents('admin', 'user')

  nodeAcl.addUserRoles(1, 'admin')
  nodeAcl.addUserRoles(2, 'user')
  nodeAcl.addUserRoles(0, 'guest')

  return nodeAcl
}

/*
function checkPermission(resource, action) {
  const access = accessControl()

  return (req, res, next) => {
    const uid = req.session.user.id
    access.isAllowed(uid, resource, action, (err, result) => {
      if (result) {
        next()
      } else {
        const checkError = new Error('User does not have permission to perform this action on this resource')
        next(checkError)
      }
    })
  }
} */

const getCurrentUserId = (req) => {
  console.log(req)
  req.user && req.user.id.toString() || false
}

const access = accessControl()

// Routes
app.get('/login', (req, res) => {
  res.send('login')
})

app.post('/login', (req, res, next) => {
  passport.authenticate('local', (err, user) => {
    if (err) return next(err)
    if (!user) {
      return res.status(401).json({
        error: 'Email or password is incorrect.',
      })
    }
     req.logIn(user, function (err) { // <-- Log user in
       next();
    });


  })(req, res, next)
},function(req,res){
 res.send('dashboard')
})

app.get('/dashboard', [isAuthenticated, access.middleware()], (req, res) => {
  res.send('dashboard')
})

app.get('/admin', [isAuthenticated, access.middleware()], (req, res) => {
  res.send('admin')
})

app.get('/status', (request, response) => {
  access.userRoles(getCurrentUserId(request), (error, roles) => {
    response.send(`User: ${JSON.stringify(request.user)} Roles: ${JSON.stringify(roles)}`)
  })
})

// Start Server
const port = process.env.APP_PORT || 3335
const host = process.env.APP_URL || 'localhost'

app.listen(port, host, () => {
  console.log(`Listening on ${host}:${port}`)
})

module.exports = app
Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..