text:
Q: Is it possible to get all the projects and subprojects using TFS API I am working on TFS API. I am trying to get the entire list of projects, subprojects, files from TFS.
Could someone guide me regarding it.
TfsTeamProjectCollection teamProjectCollection = teamFoundationserver.TfsTeamProjectCollection;
ProjectCollection projCollect = (ProjectCollection) teamProjectCollection.GetService(typeof(ProjectCollection));

The above code just shows the first level from TFS. How Can I go further deep into TFS tree.
I want the entire list of projects, and solutions under each project.
Thanks,
SV

A: There's no such thing as a "subproject."  What it sounds like you want to do is get a listing of all subfolders / files under each project.
To do that, iterate through each of your projects, and do a GetItems on each.  Here's some code:
TfsTeamProjectCollection teamProjectCollection = new TfsTeamProjectCollection(new Uri("http://sw100429:8080"));

ProjectCollection projCollect = (ProjectCollection)teamProjectCollection.GetService(typeof(ProjectCollection));

VersionControlServer vcs = teamProjectCollection.GetService<VersionControlServer>();

// This approach lets you get the list of files for each team project individually.

foreach (TeamProject tp in projCollect)
{
    string path = string.Format("$/{0}", tp.Name);
    var filesAndFolders = vcs.GetItems(path, RecursionType.Full);
}

// However, this approach is a bit more succinct - instead
// of getting them for each team project, just start at "$/" and work your way down

var allFilesAndFolders = vcs.GetItems("$/", RecursionType.Full);

A: Using your q&a (thanks) I was able to put this sample together after a lot of trial and error. It goes a step further to show how to map the local paths too. I hope this saves some readers some head aches.
This example was put together in a form in VS 2015 and uses the following assembly references (that were also tricky to track down)
All located in C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\vl45o2it.tph on my machine.
Microsoft.TeamFoundation.Client.dll
Microsoft.TeamFoundation.Common.dll
Microsoft.TeamFoundation.VersionControl.Client.dll
Microsoft.VisualStudio.TeamFoundation.dll

Apologies if my terminology is out in places. I don't mind if you edit any of this.
using System;
using System.Linq;
using System.Windows.Forms;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Common;
using Microsoft.TeamFoundation.Framework.Client;
using System.Diagnostics;
using Microsoft.TeamFoundation.VersionControl.Client;

namespace Tfs
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            Uri tfsUri = new Uri("http://server:8080/tfs");
            string repositoryName = "yourrepository";
            string projectPath = "$/project/path/path/path";

            Uri repositoryUri = new Uri(string.Format("{0}/{1}", tfsUri.AbsoluteUri, repositoryName));

            TfsConfigurationServer tfscs = TfsConfigurationServerFactory.GetConfigurationServer(tfsUri);

            //get the repository
            CatalogNode repository = tfscs.CatalogNode.QueryChildren(new Guid[] { CatalogResourceTypes.ProjectCollection }, false, CatalogQueryOptions.None)
                .FirstOrDefault(a => string.Compare(a.Resource.DisplayName, repositoryName, true) == 0);

            //open in the project collection
            TfsTeamProjectCollection pc = tfscs.GetTeamProjectCollection(new Guid(repository.Resource.Properties["InstanceId"]));

            //tfs project file structure access
            VersionControlServer vcs = pc.GetService<VersionControlServer>();

            WorkspaceInfo wsi = Workstation.Current.GetAllLocalWorkspaceInfo().FirstOrDefault(a => a.ServerUri == repositoryUri);

            //user functionality (checkin, localpaths etc)
            Workspace ws = wsi.GetWorkspace(pc);

            //get the file structure
            ItemSet items = vcs.GetItems(projectPath, RecursionType.Full);

            foreach (Item i in items.Items)
            {
                Debug.WriteLine(string.Format("{0} ({1}) - {2} - {3}", i.ServerItem,
                                                                       i.ContentLength.ToString(),
                                                                       i.ItemType.ToString(),
                                                                       ws.GetLocalItemForServerItem(i.ServerItem)));
            }
        }

    }
}


text:
Q: Issue on upload image in nodejs Req.file and req.files comes out to be undefined.
I have tried using the methods people have found useful but none worked for me.
var upload = multer({dest: './public/files/lost/'});

//INDEX - show all items
router.get("/", function(req, res){
   res.render("items/report");
});

//CREATE - add new lost to DB
router.post("/", upload.single("image"), function(req, res){
    // get data from form and add to items array
    console.log(req.file);
    console.log(req.files);
    // Other req.body usage here
})

Form

Report for the Lost Item

            <form action="/report" method="POST" enctype="multipart/form-data">

                    <input class="form-control" type="text" name="name" placeholder="name">

                    <input class="form-control" type="text" name="type" placeholder="request type">

                    <input class="form-control" type="text" name="date" placeholder="date">

                    <input class="form-control" type="text" name="time" placeholder="time">

                    <input class="form-control" type="text" name="location" placeholder="location">

                    <input class="form-control" type="text" name="phone" placeholder="phone">

                    <input class="form-control" type="file" name="image" placeholder="image url">

                    <input class="form-control" type="text" name="description" placeholder="description">

                    <button class="btn btn-lg btn-primary btn-block">Submit!</button>

            </form>
            Go Back

<% include ../partials/footerstudent %>

I expect req.file to contain the filename and other attributes of the file uploaded.

A: I observed you are submitting the form to report endpoint. it should be consume in this way
router.post("/report", upload.single("image"), function(req, res){
    // get data from form and add to items array
    console.log(req.file);
    console.log(req.files);
    // Other req.body usage here
})

But to reassemble the uploaded file in your application, you'll need to parse the request body (as multipart form data).
In Express 3.x you could use express.bodyParser middleware to handle multipart forms but as of Express 4.x, there's no body parser bundled with the framework.
There are many packages available Assuming that you are using mutler and Express 4.0
First make sure that API is consuming right by sending other params

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get Process Name for RPC Client Given an RPC call I can easily impersonate the client and get their process token, but how do I get the process name from that?

A: To get the process name for an RPC client, you must use RpcServerInqCallAttributes to query the process ID, OpenProcess with the process ID to get the process handle, and QueryFullProcessImageName with the process handle to get the full process name.


text:
Q: Unable to start Cloudera services on Cloudera Quickstart Docker I'm trying to start up cloudera services on Cloudera's quickstart docker image (5.13.0).
I downloaded the image from Cloudera's website and did the following steps as described here: https://docs.cloudera.com/documentation/enterprise/5-13-x/topics/quickstart_docker_container.html
tar -zxvf ~/Downloads/cloudera-quickstart-vm-5.13.0-0-beta-docker.tar.gz
cd ~/Downloads/cloudera-quickstart-vm-5.13.0-0-beta-docker/
docker import cloudera-quickstart-vm-5.13.0-0-beta-docker.tar cloudera-quickstart:5.13.0
docker run --hostname=quickstart.cloudera --privileged=true -i -t -p 8888:8888 -p 7180:7180 cloudera_quickstart:5.13.0 /usr/bin/docker-quickstart

The container starts successfully and runs /usr/bin/docker-quickstart fine. (I can access HDFS and pyspark).
Problem begins when I want to start Cloudera manager:
# In cloudera_quickstart
/home/cloudera/cloudera-manager --express

The command will run to completion, but when I go to Cloudera manager @ localhost:7180 and click recent commands, I will see the following error message:

I've tried redownloading the image, and googled everywhere but i can't find anyone with similar issues, so i've posted here for some help. Cheers!
Update 2019/11/05
Failing setup:
1. Docker version 19.03.4, build 9013bf583a
2. Ubuntu 16.04
Working setup:
1. Docker version 18.09.3, build 774a1f4
2. Ubuntu 18.04
So I tried this on another laptop with the exact same image. Cloudera manager and the services start up perfectly. Only difference is Docker version which I listed out above.
I'm not entirely certain if docker version is the issue, or the different OS.  Whatever the case, if someone else has this issue maybe try a lower docker version and reporting back here if it helps?


text:
Q: Implementing simple jQuery plugins with AngularJS (and RequireJS) I'm currently using Angular and Require in a project for the first time. At the moment it seems like it's very hard to do the things that should be simple when using Angular.
I'm currently trying to put a click event using jQuery for a simple tabbed menu and of course, $(document).ready will not work because Angular loads the views after this has fired. Are there any examples of how to implement jQuery plugins with Angular (and Require)?
Also, I will need to turn jQuery plugins on/off on window resize using another plugin. What is the correct method of doing these things? Any help would be greatly appreciated.
I've attached some (very) stripped down code from a controller. I have also tried putting the click event straight between the angular.element ready code. Still doesn't seem to work.
define(['app', 'modules/Social'], function(app, social) {
  'use strict';

  return app.controller('HomeCtrl', function($scope, $http) {

    angular.element(document).ready(function () {
       // This code attaches an event listener in jQuery (.click())
       social.init();
    });

  });

});

EDIT: I am using includes as templating and it appears that the includes are getting fired AFTER the angular.element ready function. Which means it is not adding the event listener.


text:
Q: Display Days/Hours Until Certain Time I need to calculate the remaining time (days/hours) until a certain date/time.
However, I'm not using a static date.
Imagine I have an event at 17:00 hrs on every Sunday. I need to display the time remaining until the next event, i.e. the oncoming Sunday 17:00.
I've found the following code in this answer. It works for a static date/time, but obviously isn't what I'm looking for.
$now = new DateTime();
$future_date = new DateTime('2011-05-11 12:00:00');
$interval = $future_date->diff($now);
echo $interval->format("%d days, %h hours, %i minutes, %s seconds");

Thanks for your time.

A: You can use the relative time format next Sunday 17:00. Like this:
$now = new DateTime();
$future_date = new DateTime('next Sunday 17:00');
$interval = $future_date->diff($now);
echo $interval->format("%d days, %h hours, %i minutes, %s seconds");

Output:
6 days, 2 hours, 33 minutes, 53 seconds

Read more about relative time formats here: http://www.php.net/manual/en/datetime.formats.relative.php


text:
Q: ZBAR sdk free to use? So I have read over this page a couple of times
http://zbar.sourceforge.net/iphone/sdkdoc/licensing.html
Maybe its just been a long weekend or Im missing something but the page is almost suggesting that we need to "pay" something to use? Even though it states its open source. Or that Apple might not allow the SDK?
So question is.. do we need to pay for use of this SDK? Will Apple approve an app using this SDK, and does anyone know of any approved apps that are using this sdk?
Thanks in advance!

A: I agree, that licensing page is not very straightforward and doesn't do much to alleviate concerns.
Consider using ZXing if you are worried about this.  It's licensing questions page is more clear.  I have released an app that uses this library and know that Apple does not (at this time) seem to have an issue with it.
PS: I know this did not answer your question, but what I'm trying to say is: I don't think anyone on SO would venture to provide an authoritative judgement based on that document, so I'd look for alternatives.


text:
Q: Remote restore of DB in MSSQL 2008 I have a remote MSSQL server meant to centralize SQL for development projects. I hand out DB's and access to developers as they need it. I do not want to give them access to filesystem in any way (would require RDP access or opening several firewalls).
My question is how can the developers easily copy their local DB to the remote DB as they transit from local databases to remote shared database?
For reference this is how you would do it in MySQL:
mysql -h host -uuser -p db < db.txt

A: Use SQL Management Studio Generate SQL scripts function (with Script data=TRUE - optional) on your database to generate SQL script, then run sqlcmd utility with correspondent options to execute sql commands from specified script from local system on remote sql server(s).
To automate database script generation you can download and install Database Publishing Wizard - it can generate scripts for database schema and/or data


text:
Q: Android Maps V2: Polygon fill disappears when zooming out I am trying to show multiple polygons on my MapView, some of them overlap and have different colors. When I add them everything looks good, but as soon as I zoom out, many (not all) of the polygons stop being filled. Zooming back and forth and scrolling sometimes fills some of them again, but it appears to be random behavior.
The code for adding the polygons:
clearAreas();
for (Area area: areas) {
    for (List<LatLng> subArea: area.getSubAreas()) {
        mAreaPolygons.add(getMap().addPolygon(
             new PolygonOptions()
                .strokeWidth(2.0f)
                .zIndex(++zIndex)
                .strokeColor(area.getColor())
                .fillColor(area.getTransparentColor())
                .addAll(subArea)));
    }
}

I understand that (according to the documentation) a Polygon will not be filled if its geometry is not specified correctly. I tried adding the points in both clockwise and counter-clockwise order, it doesn't make a difference.
Can anyone explain this behavior?
Update: If the debugger is attached, everything works perfectly! The polygons are all filled and stay filled when zooming out. As soon as I detach the debugger, polygons start losing their fill again. What's going on here?
Update #2: The problem shows up on my Galaxy S3. Surprisingly, it works on a slower, older device! Since attaching a debugger makes the app become quite slow, maybe there is some kind of connection here?
Thanks a lot,
Marco

A: This reeks of threading if what you've said in your two updates is true. Somewhere you've got threading issues. With just the snippet of code you've provided, nothing looks out of place, but it would require examination of the rest of your code to figure this out. What's most likely going on is that the call to draw these polygons is starting before the view is ready to be drawn on. Without seeing anything, I'd suggest something along these lines to approach a fix:
mMap.setOnCameraChangeListener(new OnCameraChangeListener() {

@Override
public void onCameraChange(CameraPosition pos) {
    if (pos.zoom != currentZoom) {
            mMap.post(new Runnable() {
                public void run() {
                    // TODO: call the method that wraps the code you provided
                });
    }
});

What this will do is call the Runnable you provided here after the views are done rendering. This may not work as intended on the map view, you may have to post it into a different queue, or do some delayed posting. I'm not familiar enough with the map framework to know for sure that this will solve it, but it definitely sounds like there are threading issues here.


text:
Q: Scroll faster using css or javascript - parallax I am trying to figure out how this website does this effect :
http://rosedalelivery.com/
Can this be done using css?  I tried using multiple background images, but the scrolling effect just doesn't match up.
Thanks in advance.

A: The best way to checkout how a website achieves something in CSS or JS is to use Chrome's Inspector tool.
You can right-click on the site's page and inspect the site's resources (cmd + option + i on Mac) -- click the resource tab. Under the scripts it shows a stellar.js which is a popular jQuery plug-in for doing parallax scrolling that's done on the website you're referencing.
The Stellar.js website: http://markdalgleish.com/projects/stellar.js/
Stellar.js Github page: https://github.com/markdalgleish/stellar.js
It also looks like the site is using NiceScroll for mobile scrolling: http://areaaperta.com/nicescroll/


text:
Q: Pulling data from MongoDB existing databas with Django(Djongo) So i am working on a proyect with mongodb and django(djongo) and i have to use an already existing database(MongoDB compass) and i cant find the way to pull or import the information from MongoDB, already try with: python manage.py inspectdb > models.py and python manage.py inspectdb and when create the models.py is not with the database instead it pulls the default MongoDb, already try the Documentation of django and nothing works. Anyone got some info about it?
PD: my app is totally empty and already configured the settings.py as the documentation on Django instruct.
Thanks in advance.

A: in your model you should specify db_table same as the collection name in your Mongo database


text:
Q: What is the Firebase Auth Session Cookie JWK URL? With a regular Firebase auth ID token we can verify using the JWK URL of https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com
If you make a Session Cookie instead, where the issuer is https://session.firebase.google.com/, what URL is the JWK located at?

A: The public certificates are here:
https://www.googleapis.com/identitytoolkit/v3/relyingparty/publicKeys
Each certificate is in PEM format. Extract the public key from the certificate and verify the signature after validating the JWT header and payload. The JWT header kid will tell you which certificate to use.
Google provides an API that you can call to fetch the JWK for a session cookie:
Method: getSessionCookiePublicKeys


text:
Q: How to use PanelSnap plugin package in angular2 project I was using jquery.Panelsnap plugin in static HTML pages. Now I am migrating my application to angular8. But I am unable to refer PanelSnap plugin.
    npm install panelsnap

In my app.component.ts,
    import { PanelSnap } from 'panelsnap/src/panelsnap';
    new PanelSnap()

is throwing error saying PanelSnap is undefined. I tried to create object on constructor, but no success. Also tried to refer panelsnap.js in angular.json, still no luck.
     "scripts": [
          "node_modules/jquery/dist/jquery.min.js",
          "node_modules/panelsnap/src/panelsnap.js",

A: In the documentation you can find the basic setup. You should not add brackets around your import, as the module is directly exported.
import PanelSnap from 'panelsnap';

const instance = new PanelSnap();


text:
Q: Converting existing python classes into Django Models I have a small program with a command line interface that uses a number of python classes with thorough implementations.  I want to scrap the command line interface and wrap the app within a Django app, but I'm just learning Django and I'm unfamiliar with the conventions.
I have a number of classes, in-memory storage structures, getters/setters etc and I'd like to convert them into Django models so that I can persist them to the database and interact with them around the django app.  Is there a general approach for doing something like this?
Should I just inherit the django.db.models.Model class in my existing classes and set them up for direct interaction? Or is there a better, more general/conventional way to do this?
I would like to be able to use all of this code in other apps, not necesarilly Django ones, so I don't really want to modify my existing classes in a way that would make them only work with Django. I thought of creating the models separately and then a sort of middle-man class to manage interaction of the actual in-memory class with the django model class, but that just seems like more places I have to make changes when I extend/modify the code.
Thanks for any help ahead of time...

A: Personally, I would modify your existing classes to extend models.Model and maintain separate versions of these classes for use outside of Django.
This will keep your classes lean and maintainable within their respective environments.
You could also create a new class that extends both models.Model and your python model through multiple inheritance. However this will result in duplicate fields for the same data.
If you would like, post an example Model as a new question and tag me in a link to it here, and I can help you convert it.

A: One of greatest django strengths is its ORM, if you want import i recommend you use it, and yes you would probably need rewrite the part that interacts with the database, but if you already have isolated this functions in a Models folder~classes, the modification won't be really hard
Although in your case i would recommending checking out Tornado/Aiohttp Since looks like you are just trying to create a interface for your functions


text:
Q: How to access FAT32 HDD in Linux I have this FAT32 HDD that I would like to access but everytime I get this error message:

Unable to Access "Windows C:"
The drive is either corrupted, inaccessable or uses an unsupported file system.

I am currently using debian. When I load a portable hard drive formatted with FAT32, It loads fine. I only get this error with internal FAT32 hard drives. I swapped it out for a NTFS and it worked accessed it, when I put the FAT32 hard drive back in, it gave the exact same error message as before. Debain crashes whenever I try to access it after manually mounting the drive.

A: You can see the logs(/var/log/syslog I think) to understand why your debian is crashing on mounting.
I think you must try first to connect it, but not manually mounting. Look to dmesg (sudo dmesg)last messages because debian will try to automount it, and could be failing.
Then run a sudo fdisk -l to know which is you device on /dev and then execute a sudo fsck /dev/sdX.
That should give you some info.


text:
Q: Run powershell.exe as a service, or help me find an alternate solution Summary: I need to run a Powershell script continuously in the background whether a user is logged on or not. This is on Server 2012.
I ran the following command:
sc.exe create "MyService" binPath="powershell.exe 'c:\myFolder\myScript.ps1'"

This command ran successfully. However, when I start the service, it immediately errors out with "The service did not respond in a timely fashion." I know it's against best practices to run Powershell as a service, but is it even possible?
The best advice I've gotten is to run this script as a Scheduled Task instead of a service. That would make sense, but my security staff has enabled the GPO option "Network access: Do not allow storage of passwords and credentials". This prevents Task manager from running tasks with the correct credentials when no user is logged in.
Why am I doing this? We have an old program that runs only in windowed mode (not as a service) and prints both stdout and stderr to the screen. That means that (a)a user has to be logged into this server 24 hours a day, and (b)there are no log files. If you're not staring at the screen when an error occurs, the error will scroll right past you. The executable starts in a new window, so redirection operators have no effect on it.
While we replace this program, I need it to (a)run at all times, even after user logoff or reboot, and (b)write stdout and stderr to a log file.
I solved the second issue with a Powershell simple Powershell script:
"Program started at $(get-date)" | Out-File c:\myFolder\CrapProgram.log -append
& "c:\myFolder\CrapProgram.exe" | Tee-Object c:\myFolder\CrapProgram.log

This starts the program in Powershell. Its output is directed both to the Powershell window and to the log file.
Now if I can get this script to run when no one is logged on...and get it to start at computer startup...and make it easy for my lower-level support team to stop and start it easily, I'll be in business.
That's why I'm trying to register Powershell as a service. If there's a better solution, let me know.

A: You could try running it as a scheduled task and set the user to run the task as 'NT Authority\System' . You don't have to enter a password for that account.


text:
Q: Updating CSV file in FTP server in PHP I'm trying to updating a CSV file which in a external FTP server, I tried to follow the basic ftp_fput() but it's not working. File is not updating and also a blank CSV file is downloading when I run this script which is not needed. I've been trying to solve this but can't find the solution
<?php

// connect and login to FTP server
//ftp setup
 $ftp_server = "ftp.test.test.co.uk";
        $ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
        $ftp_username='ftp_username';
        $ftp_userpass='ftp_userpass';
      $login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);

//local DB setup
$servername = "localhost";
$username = "root";
$password = "TEST";
$dbname= "TEST";

// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
//END database connection//

$sql = "SELECT sku,SUM(quantity) as quantity FROM tbl_old_books GROUP BY isbn";

$result = $conn->query($sql);

         header("Content-Disposition: attachment; filename=AllOpenOrders.csv");
         header("Content-Type: application/csv; ");

         // file creation
       $file = fopen('php://temp', 'W');

        $header = array("SKU","QUANTITY");
        fputcsv($file, $header);

      if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
            fputcsv($file, $row );
        }
    }

 $remote_path = "/export/AllOpenOrders.csv";

ftp_fput($ftp_conn, $remote_path, $file, FTP_BINARY, 0);

  fclose($file);
ftp_close($ftp_conn);
?>

A: You file handler $file points at the end of the file as you write in it. There is nothing left to write via ftp_fput.
You can reset your file pointer at the beginning of the file with rewind($file); before writing in the FTP : rewind documentation


text:
Q: Add new user on button click in reactJS I have following code
my code
I have a button "add", and when I am clicking "new user" was added in my array.
But it works only the first time when I  am clicking second, third.... times nothing was happening.
how many times I click so many times "new user" should be added into an array.
like this.

I am using functional components and useState hook.
Please help me resolve that problem

A: Put the <NewUser /> inside of the setAddNew([...addNew])array. Check the following code:
function add() {
   setAddNew([...addNew, <NewUser />]);
}

A: Try this code in your Add.jsx
import React, { useState } from "react";

function Add() {
  const [addNew, setAddNew] = useState([]);
  function add() {
    // HERE is the change, you need to keep the previous values
    setAddNew([...addNew, <NewUser />]);
  }

  return (

      <button onClick={add}>Add </button>

 {addNew}

  );
}
const NewUser = () => {
  return (

New User

  );
};

export default Add;

addNew - is the state, in this case, an array.
setAddNew - is the function to handle the State, but you need to handle the logic

A: This is happening because you are resetting the value of array for pushing new value to it you have to use
setAddNew((old) => [...old, <NewUser />]);

this will copy your old array and will also insert the new element to it

A: In the Add.jsx what needs to change is:
  function add() {
    setAddNew(<NewUser />);
  }

into...
  function add() {
    setAddNew([...addNew, <NewUser />]);
  }

The previous function would keep resetting <NewUser/ > with itself, thus being only 1.
When adding the previous addNew state via ...addNew within an array [], thus being [...addNew, <NewUser />], this will take the previous state of addNew and add a <NewUser /> on top of that.


text:
Q: Bootstrap validator resetForm I am using bootstrapvalidator with Bootstrap 3.3
I need to reset a form in a modal dialog.
I used the right method but it does not work into the modal dialog.
 $('#emailForm').bootstrapValidator("resetForm",true);

If I open the modal and insert an email, and then try to reset the form, the validation controls are still there.
JSFiddle

A: It is simple, you just only need to add
excluded: [':disabled'],

Into validation init.
Example:
    $('#emailForm').bootstrapValidator({
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        excluded: [':disabled'],
        fields: {
            email: {
                validators: {
                    emailAddress: {
                        message: 'The value is not a valid email address'
                    }
                }
            }
        }
    });

A: I know this is very old.
$("#emailForm").data('bootstrapValidator').resetForm();

Resets the form validation, but will not clear the fields. Which is fine in my case. Using one form for multiple customers. Easier for the visitor to have their name and email left there, but just retype the message. So I just clear message field.


text:
Q: argparse: store_true and int at same time I'm using argparse for cli arguments. I want an argument -t, to perform a temperature test. I also want to specify the period of temperature measurements.
I want:
python myscript.py -t to perform a measurement every 60 seconds,
python myscript.py -t 30 to perform a measurement every 30 seconds and,
python myscript.py not to do the temperature measurement.
Right now I am doing it like this:
parser.add_argument('-t', '--temperature',
                    help='performs temperature test (period in sec)',
                    type=int, default=60, metavar='PERIOD')

The problem is that I can not distinguish between python myscript.py and python myscript.py -t.
It would like to be able to do something like action='store_true' and type=int at the same time. Is it possible? Any other way to do it?
Thanks!

A: Use the const parameter:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
    '-t', '--temperature',
    help='performs temperature test (period in sec)',
    type=int,
    nargs='?',
    const=60,         # Default value if -t is supplied
    default=None,     # Default value if -t is not supplied
    metavar='PERIOD')

args = parser.parse_args()
print(args)

% test.py
Namespace(temperature=None)
% test.py -t
Namespace(temperature=60)
% test.py -t 30
Namespace(temperature=30)

A: I haven't used argparse before. But recently I saw a presentation on docopt https://github.com/docopt/docopt that blew me away.
Maybe give that a try?


text:
Q: NX component testing with cypress error process is not defined I am using NX 14.5.1 and cypress 10.2.0. When I run cypress component testing for "libs/ui" always got "Process not defined" error. In the component call ".env" like this:
import consola from 'consola'

export const logger = consola.create({
  level: process.env.NX_ENV_NAME === 'production' ? 0 : 5
})

This is my "cypress.config.ts":
import { defineConfig } from 'cypress';
import { nxComponentTestingPreset } from '@nrwl/react/plugins/component-testing';

export default defineConfig({
  component: {
     ...nxComponentTestingPreset(__dirname)
  }
})

And the error is like this:
process is not defined
ReferenceError
The following error originated from your test code, not from Cypress.

  > process is not defined

When Cypress detects uncaught errors originating from your test code it will automatically fail the current test.

Cypress could not associate this error to any specific test.

We dynamically generated a new test to display this failure.

I think Cypress doesn't recognize my ".env". How do I pass my ".env" when I run component testing?

A: I think the basic problem is the app is server-side-rendered. The server compiles in Node where process is available, but the component test runs in the browser where process isn't valid.
This is the way you might tackle it:
In cypress.config.js load the process.env you need into Cypress.env
import { defineConfig } from 'cypress';
import { nxComponentTestingPreset } from '@nrwl/react/plugins/component-testing';

const  setupNodeEvents = (on, config) => {
  config.env = {
    ...config.env,
    ...process.env.NX_ENV_NAME,
  }
  return config
}

export default defineConfig({
  component: {
     ...nxComponentTestingPreset(__dirname),
     setupNodeEvents
  }
})

In the component, check where the component is being run from.
import consola from 'consola'

const envName = window && window.Cypress
  ? window.Cypress.env('NX_ENV_NAME')     // running in browser, take Cypress.env
  : process.env.NX_ENV_NAME;              // running SSR, take process.env

const level = envName === 'production' ? 0 : 5;

export const logger = consola.create({
  level
})

This is messy but removes the restriction on running SSR code in a browser environment.


text:
Q: tcl - how to save all parameters that go into a proc for later re-use? I am using a function (A) that forms the content of a packet.
The function accepts an arbitrary amount of arguments.
I wish to implement another function (B) that forms that last packet formed by (A).
I wish to do this by running (A) on the same parameters I last used with (A).
The trick is (A) accepts an unknown number of parameters using something like
proc example {first {second ""} args}

Is there any easy way to save all the arguments quickly and then call (A) with the same params again at a later time?

A: The easiest way is to have A create B when run, which it's pretty simple to do with the help of info level 0:
proc A {p q {r ...} args} {
    # Make B which will call us *exactly* as we've just been called
    proc B {} [list uplevel 1 [info level 0]]
    # ... continue with normal processing ...
}

There are certain caveats to this (e.g., if you're doing heavy processing with aliases or complex cross-namespace work) but for most code — especially the sort of thing where you'd want this — that's not a big deal.

In 8.6, use proc B {} [list tailcall {*}[info level 0]] instead.

A: Well you could use a global array to store the parameters:
proc printArguments {first {second ""} args} {
global params
set params(first) $first
set params(second) $second
set params(args) $args
}
%
%
% printArguments 1 2 3 4 5
3 4 5
%
% parray params
params(args)   = 3 4 5
params(first)  = 1
params(second) = 2


text:
Q: How to design an adjustable 5A current regulator with LM338? I have recently taken interest in laser diodes, and I would like to drive one of them (NUBM08) without destroying it. Looking over the internet I learned there are many devices one can build to do this, one of which is called "linear regulator". Most times, the current regulator people use for these types of endeavors is one based on the LM317 voltage regulator. However, the datasheet of the NUBM08 states that its operating current is around 3A, with an operating voltage between 3.6 and 4.8V.
Now, the LM317 can't be used with more than 1.5A, so I thought I may simply substitute it with a higher rated LM338 which supports up to 5A.
The schematic I had in mind was this one I found online:
With the LM317 swapped for the LM338. However I'm not sure of a few things:

*

*If I want 3A on the diode, my "feedback resistor" (indicated as R1) should dissipate a power of 1.25V*3A=3.75W... do I really need such a high power rated resistor or is my logic incorrect? Also, the resistor should be 1.25V/3A≈0.4Ω... does that make sense? Could I use many resistors in series instead so that the voltage drop on each of them is smaller (and so smaller power dissipation)?

*If I wanted to gradually adjust the current up to a max of 3A, my understanding is that I could add a potentiometer in series with R1 so that I can rotate the knob and gradually let the potentiometer's resistance go to zero, and then I can increase the current up to the max that R1 limits... But does this mean that also my potentiometer needs to be rated for at least 3.75W?

*How do I make sure that the operating voltage of the diode stays within limits? I understand that I am fixing the current to be constant at 3A, but then I don't understand what will happen to the voltage, how do I make sure it doesn't exceed  the 4.8V? I'm very confused about this point...

I apologize for the huge post but thank you do much to anyone who'll help me!

A: I don't think you should be married to the LM338. From your first point you already know that this topology is guaranteed to be inefficient. Read e.g. AN-2157 Constant Current Constant Voltage Buck Converter With LM25085 for hints on a way to use a buck regulator in constant-current mode:

or more simply, pick out any high-current buck regulator with integrated current limit. This class of devices has an internal or external sense resistor and circuitry to control the buck waveform to limit the current accordingly. For an example see the AOZ2262NQI which has an external current limit setting resistor "ROCS":

For a current limit adjustable to 5A, you would have a resistor with a maximum of 4k.

A: The LM338 will waste a lot of power. If you want an efficient constant current driver, why not use a LED driver chip?

This is the cheapest one on digikey. Voltage on the current sense resistor is 0.1V, so with a 33 mOhm resistor you will get 3A. The resistor will dissipate 0.3W, so a good choice would be three 1206 0R1 resistors in parallel, which is both cheaper and more flexible than one 0R033 resistor.
You'll need an inductor, about 3.3µH or 4.7µH with a saturation current above 4A, a >3A schottky diode for D1, a bunch of 10µF SMD X7R ceramic caps in parallel for C1, and a 5V logic level MOSFET with say <20mOhm RdsON, preferably in SMD for lower inductance and therefore smoother switching.
Power supply should be 5V 3A, and you'll need to pay good attention to the layout.
EDIT
The aliexpress module should work if it has a potentiometer to adjust output current. The capacitors on this are likely to be garbage though, so if they get too hot you can just solder some low-ESR caps on the input and output. Just scratch the soldermask on the back with an Xacto and stick a bunch of 10-22µF 1206 X7R ceramics in there:

...or if the extra thickness doesn't bother you, you can use some low-ESR aluminium caps. If you feel adventurous and don't want to pay $8 postage for two 50c caps, electrolytic caps next to the CPU voltage regulator on an obsolete/dead PC motherboard are a good source.


text:
Q: Stretch images if needed only up to 20% We have an image gallery with responsive sizes, using a ready made React gallery.
The images need to fit into a container with predefined, responsive height and width, but the images we're getting from the server are in different proportions and sizes: sometimes the proportions don't match, and sometimes the image is not big enough to even fill the container.
The product requirement is that an image should only be scaled up to 20% of the original image size to fit the container:

How do I even refer to the original image size in CSS? If I use percentage that would be referring to the container size... I stumbled upon Object-fit but it's not supported on IE.
I thought of using inline styles from JS but that would be complicated since this is responsive and the sizes would need to be calculated again on each window resize.
Thank you.

A: There can be two cases :

*

*If you are taking  inside you container

.container
{
  width:100%;
  height:300px;
}
.container img
{
  min-height:100%;
  min-width:100%;
  max-height:100%;
  max-width:100%;
}

*If you are taking image as background of the container

.container
{
  background-image: url('https://regmedia.co.uk/2015/11/16/help_2.jpg');
  background-size: 100% 100%;
  width:80%;
  height:200px;
}


text:
Q: How would you find the limit of the following function ?? How would you use L'Hopital's Rule to find the limit of the following function ???
$$\lim_{n \rightarrow 0} \frac{1}{\pi x} \frac{\sin(\frac{\pi x}{2})} { e^{2\pi x}}$$
How would you define your $f(x)$ and $g(x)$  ?
Why cant I define $f(x) =\frac{ \sin(\frac{\pi x}{2})} {\pi x}$ and $g(x) =  e^{2\pi x}$ instead??

A: If you want L'Hopital:
Let $f(x) = \sin\left(\frac{\pi x}{2}\right)$, $g(x) = \pi x e^{2\pi x}$.  Thus
$$\lim_{x \to 0} \frac{f(x)}{g(x)} = \lim_{x \to 0} \frac{f'(x)}{g'(x)} = \lim_{x \to 0} \frac{\frac{\pi}{2} \cos\left(\frac{\pi x}{2}\right)}{\pi e^{2\pi x} (2\pi x +1)} = \frac{\pi}{2\pi} \cdot \frac{\cos 0}{e^0 (0+1)} = \frac{1}{2}$$

A: I would say that the $e^{2\pi x}$ approaches $1$, so is harmless. Then you can deal with the rest.
So I would let $f(x)=\sin\left(\frac{\pi x}{2}\right)$ and $g(x)=\pi x$.  We could equally well say that $\pi e^{2\pi x}$ has limit $\pi$, and let $f(x)$ be as before, and $g(x)=x$.
Remark: We can also keep things exactly as they are given to us, let $f(x)$ be the top, $g(x)$ the bottom. It is more work, for the differentiation of the bottom is more complicated, with a greater chance of error. And anyway sooner or later we will have to use the fact that $e^{2\pi x}$ approaches $1$.


text:
Q: Consequences of adding a user to a project but not to an organisation I am trying to understand the complete purpose of organisations in ADO. What I have understood is that an organisation groups projects, defines resources, extensions, billing, etc. that is related to the organization.
I am struggling with the user part of an organization. I can add users to an org giving them an access level. But I can also add users directly to a project without adding them to an organization at all.
What is then the consequence of this? Is then access level by default stakeholder for those users?
Thank you

A: If you add an user to a project that user will be added to the organisation as well. At least when the said user first logs in. The user will get the access level you define as default.

A:
You can add people to projects instead of to your organization. Users
  are automatically assigned Basic features if your organization has
  seats available, or Stakeholder features if not.

For this please refer to the Note of this document.
When you add members to projects and you don't have billing set up, Basic access is automatically assigned, until you run out of seats available. When you add members to projects and you do have billing set up, Basic access is assigned only if your default access level is set to Basic. Otherwise, project members are assigned Stakeholder permissions.
You can refer to Add members to projects or teams for details.


text:
Q: c# refactor duplicated property setter and getter with different names I've got some public properties which other then the property names they are identical. Im just wondering if there is a cleaner way since there seems to be a lot repeated code there. Here is an example:
    public static bool Property1
    {
        get => LocalSettingsService.RetrieveSetting<bool>();
        set => LocalSettingsService.SaveSetting<bool>(value);
    }

    public static bool Property2
    {
        get => LocalSettingsService.RetrieveSetting<bool>();
        set => LocalSettingsService.SaveSetting<bool>(value);
    }
    public static bool Property3
    {
        get => LocalSettingsService.RetrieveSetting<bool>();
        set => LocalSettingsService.SaveSetting<bool>(value);
    }
    public static bool Property4
    {
        get => LocalSettingsService.RetrieveSetting<bool>();
        set => LocalSettingsService.SaveSetting<bool>(value);
    }

The RetrieveSetting and SaveSetting methods pull the CallingMemberName to do it's thing.
Any tricks on chopping down the repeated code?

A: Aesthetics
If it's about aesthetics, then you could just rename things.
public static bool Property1 { get => LSL.Get<bool>(); set => LSL.Set(value); }
public static string Property2 { get => LSL.Get<string>(); set => LSL.Set(value); }
public static int Property3 { get => LSL.Get<int>(); set => LSL.Set(value); }
public static uint Property4 { get => LSL.Get<uint>(); set => LSL.Set(value); }

SaveSetting...erm... I mean Set should not need the type as it can be inferred from the type of value.

IOptions<TOptions>
If you're after something more you could look at IOptions<TOptions> pattern from .net core.


text:
Q: how to compile css in production React Rails(5.2.3) I'm working on react with rails (5.2.3). I have imported css file in js. All styles are properly applied in the local (development) but in production, style does not seem to be applied. All touch functions are properly executed but only style is missing.
Which file should I modify to successfully apply style in the production?
import React from 'react'
import '/name_of_css.css'

class App extends React.Component {
..
}

and
javascript/packs/index.js
<Router>
  <Route path ="/" component = {App} />
</Router>

and then, views/controller_name/index.html, I imported js file like below.
<%= javascript_pack_tag 'index' %>

Again, I want to know how to apply css in the production for rails app! (:

A: Just add <%= stylesheet_pack_tag 'index' %> in your view.
From the Webpacker doc :

You can then link the JavaScript pack in Rails views using the
  javascript_pack_tag helper. If you have styles imported in your pack
  file, you can link them by using stylesheet_pack_tag

https://github.com/rails/webpacker#usage
Let me know if that solves your issue.


text:
Q: Uso de variáveis globais e variáveis de classe no Delphi Eu tenho algumas dúvidas quanto ao uso de variáveis globais e variáveis de classe usando class var no Delphi.
Declarando variáveis de classe com class var.
unit Unit1;

interface

type
  TClass = class
  public
    class var _Object: TObjectList<Integer>
  end;

implementation
end.

Declarando variáveis globais
unit Unit1;

interface

var
  _Object: TObjectList<Integer>

implementation
end.

Pergunta:
Como o compilador aloca memória para essas declarações?
Qual forma de uso é a mais indicada para ser utilizada?

A: O processo de alocação de memória de uma variável de classe usando o class var é o mesmo que uma variável global.
A unica diferença é que a variável declarada como class var vai ter um escopo de classe.
https://stackoverflow.com/questions/21986202/use-of-variables-global-and-variables-of-class-in-delphi

A: Após a separação da CodeGear da Borland a equipe responsável pelo Delphi procurou modernizar a linguagem. Neste sentido, adicionou construções de linguagem que visam permitir melhores práticas de programação, notadamente dando à aplicação um modelo mais orientado a objetos.
As variáveis de classe públicas e globais são relativamente similares, no sentido de que terão apenas uma instância, mas as variáveis de classe têm a vantagem de estar definidas dentro do escopo da classe, o que evita eventuais colisões de nomes em diferentes units ou mesmo dentro da mesma unit.
Por este último motivo eu recomendo o uso de variáveis de classe.

A: Em qualquer ambiente de desenvolvimento que forneça facilidades de escopo para as variáveis de forma que você possa criar membros na Classe (Java, Delphi, C#, etc.) use sempre estas funcionalidades em vez de variáveis globais ou de classe pois estas variáveis vão criar acoplamento excessivo no seu código dificultando a manutenção. O Design Pattern Singleton permite que se crie algo melhor que simplesmente usar Variáveis globais mas também deve ser evitado.

A: Só para incrementar o que já foi falado.
Eu já vi duas variáveis globais em unit´s diferentes mas com o mesmo nome. Eram do tipo de uma classe. Ao instanciá-la na unit1, era instanciada a da unit2. Na hora de destruir, era então destruida a da unit1. Resultado: "Access Violation".
Como era praticamente impossível mudar a cultura do pessoal em relação ao var Global, eu instrui a declararem dentro do escopo de implementation na unit, em vez da interface. Isso fez ela não ficar visível para as outras units, resolvendo temporariamente o problema.

A: A linguagem de programação por traz do Delphi é o Object Pascal cuja origem está no Pascal estruturado, isto é, não orientado a objeto. Por este motivo existe na sintaxe suporte a variáveis globais. Mas num programa Orientado a Objetos não é uma boa prática usar variáveis globais.
Se mesmo assim desejar usar variáveis globais tenha em mente as seguintes regras:
1- Variáveis globais não estão relacionadas a nenhuma classe.
2- Elas são declaradas na seção INTERFACE da unit e quando usadas é boa prática seguir a sintaxe UnitNome.VariavelNome. Exemplo: UnitPessoa.QtdePopulacao := 1234;
3- Elas podem ser referidas em todas os códigos de programas, procedure, function e métodos que usam a unit na qual a variável está definida;
4- Elas podem ser inicializadas ou finalizadas nas seções INITIALIZATION E FINALIZATION da unit na qual está declarada.
Variáveis estáticas das classes "Class Var" seguem as seguintes regras:
1- São declaradas na definição da classe e seu valor é compartilhado por todas as instâncias da classe.
2- Métodos de classe podem fazer referência a elas;
Minha sugestão final:
1- Use variável global quando ela for armazenar informações relacionadas a Unit na qual está declarada, e não específicas de uma determinada classe desta unit;
2- Nos demais casos, use variável de classe que é mais elegante, mais elucidativa, e segue o que é definido como boa prática de OO.

A: Quando você declara uma variável no VAR na unit esta variável é estática e fica visível em qualquer local que importar a unit em questão.
Resumindo: Se unit1 tiver uma variável varDaUnit1 e unit2 uses unit1, unit2 pode acessar varDaUnit1 como se ela fizesse parte de unit2. Qualquer alteração em seu valor será refletido para outras units que utilizam unit1.
Ao declarar uma variável no public da classe ela é uma variável dinâmica, que é criada e destruída junto com a classe. A acesso a variáveis no public é via classe, por exemplo:
classe1.varDaClasseDecalradaNoPublic;

Quando trabalhava com Delphi a empresa onde eu trabalhava traçou um conjunto de regras quanto ao uso do var, desencorajando seu uso. A única situação onde vejo que o uso do var seja plausível seria caso precise de uma variável global compartilhada em várias telas do sistema, ex.: Usuário logado.


text:
Q: Duplicate error messages when posting answer If the user inserts in his answer a link to jsfiddle (for example: http://jsfiddle.net/asd123) without providing some code, the following error is thrown:

Links to jsfiddle.net must be accompanied by code.

That's OK.
The problem is when the user insert more than one link to jsfiddle, without providing some code. Suppose that he insert 3 links. Three duplicate errors will be thrown.
See the following screen shot.

If the user will insert n links to jsfiddle, n errors will be shown.

A: This is fixed now. Error messages are now de-duped prior to display.


text:
Q: Variation on Adding HTML Attributes to Html.BeginForm() I need a form on my ASP.NET MVC Razor page. My preference would be to use the following syntax:
@using (Html.BeginForm())
{
}

However, I need several attributes added to the form. So I ended up with something like the following:
@using (Html.BeginForm(null, null, FormMethod.Post, new { name = "value" }))
{
}

However, this has an undesired side effect. If there are query arguments in this page's request, the first form passes them along when the form is submitted. However, the second version does not.
I really don't know why BeginForm() doesn't support attributes, but is there a straight-forward way to add attributes to BeginForm() and still pass along any query arguments when the for is submitted?
EDIT:
After looking into this, it would seem the best solution is something like this:
<form action="@Request.RawUrl" method="post" name="value">
</form>

However, when using this syntax, client-side validation is disabled. It seems there is no good solution to this situation without more complicated and potentially unreliable constructs.

A: That's indeed true, but I would go with a custom helper in order to preserve the form context inside which is used for client side validation:
public static class FormExtensions
{
    private static object _lastFormNumKey = new object();

    public static IDisposable BeginForm(this HtmlHelper htmlHelper, object htmlAttributes)
    {
        string rawUrl = htmlHelper.ViewContext.HttpContext.Request.RawUrl;
        return htmlHelper.FormHelper(rawUrl, FormMethod.Post, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
    }

    private static int IncrementFormCount(IDictionary items)
    {
        object obj2 = items[_lastFormNumKey];
        int num = (obj2 != null) ? (((int)obj2) + 1) : 0;
        items[_lastFormNumKey] = num;
        return num;
    }

    private static string DefaultFormIdGenerator(this HtmlHelper htmlhelper)
    {
        int num = IncrementFormCount(htmlhelper.ViewContext.HttpContext.Items);
        return string.Format(CultureInfo.InvariantCulture, "form{0}", new object[] { num });
    }

    private static IDisposable FormHelper(this HtmlHelper htmlHelper, string formAction, FormMethod method, IDictionary<string, object> htmlAttributes)
    {
        var builder = new TagBuilder("form");
        builder.MergeAttributes<string, object>(htmlAttributes);
        builder.MergeAttribute("action", formAction);
        builder.MergeAttribute("method", HtmlHelper.GetFormMethodString(method), true);
        bool flag = htmlHelper.ViewContext.ClientValidationEnabled && !htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled;
        if (flag)
        {
            builder.GenerateId(htmlHelper.DefaultFormIdGenerator());
        }
        htmlHelper.ViewContext.Writer.Write(builder.ToString(TagRenderMode.StartTag));
        var form = new MvcForm(htmlHelper.ViewContext);
        if (flag)
        {
            htmlHelper.ViewContext.FormContext.FormId = builder.Attributes["id"];
        }
        return form;
    }
}

which could be used like this:
@using (Html.BeginForm(htmlAttributes: new { name = "value" }))
{
    ...
}

A: I had a similar problem and here is quick solution (it works with MVC4).
Declare the extension method:
public static MvcForm BeginForm(this HtmlHelper helper, object htmlAttributes)
{
        return helper.BeginForm(helper.ViewContext.RouteData.Values["Action"].ToString(),
                                helper.ViewContext.RouteData.Values["Controller"].ToString(),
                                FormMethod.Post, htmlAttributes);
}

and use it in your page:
@using (Html.BeginForm(htmlAttributes: new {@class="form-horizontal"}))
{
...
}

A: Small modification to source code:
http://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Mvc/Html/FormExtensions.cs
public static MvcForm BeginForm(this HtmlHelper htmlHelper, object htmlAttributes)
{
   // generates <form action="{current url}" method="post">...</form>
   string formAction = htmlHelper.ViewContext.HttpContext.Request.RawUrl;
   return FormHelper(htmlHelper, formAction, FormMethod.Post, new RouteValueDictionary(htmlAttributes));
}

private static MvcForm FormHelper(this HtmlHelper htmlHelper, string formAction, FormMethod method, IDictionary<string, object> htmlAttributes)
{
   TagBuilder tagBuilder = new TagBuilder("form");
   tagBuilder.MergeAttributes(htmlAttributes);
   // action is implicitly generated, so htmlAttributes take precedence.
   tagBuilder.MergeAttribute("action", formAction);
   // method is an explicit parameter, so it takes precedence over the htmlAttributes.
   tagBuilder.MergeAttribute("method", HtmlHelper.GetFormMethodString(method), true);

   bool traditionalJavascriptEnabled = htmlHelper.ViewContext.ClientValidationEnabled
                                       && !htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled;

   if (traditionalJavascriptEnabled)
   {
       // forms must have an ID for client validation
       tagBuilder.GenerateId(htmlHelper.ViewContext.FormIdGenerator());
   }

   htmlHelper.ViewContext.Writer.Write(tagBuilder.ToString(TagRenderMode.StartTag));
   MvcForm theForm = new MvcForm(htmlHelper.ViewContext);

   if (traditionalJavascriptEnabled)
   {
       htmlHelper.ViewContext.FormContext.FormId = tagBuilder.Attributes["id"];
   }

   return theForm;
}


text:
Q: How to fix Javadoc comment has parse error, Details: no viable alternative at input ' *' while parsing JAVADOC_TAG [NonEmptyAtClauseDescription] /**
* This method is used for ABC.
* @return
* @throw IOException when this exceptional condition occurs
*/

[Error]:line:4- Javadoc comment at column 0 has parse error. Details:
no viable alternative at input '     *' while parsing JAVADOC_TAG
[NonEmptyAtClauseDescription]

Any idea why am I getting this error in the @throw line of Javadoc? How to fix this?

A: As described above, add a description to the return tag or remove it completely to resolve the error.
$ cat TestClass.java
public class TestClass {
    /**
    * This method is used for ABC.
    * @return desc
    * @throw IOException when this exceptional condition occurs
    */
    int method() throws IOException  {
        return 0;
    }
}

$ cat TestConfig.xml
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
          "-//Puppy Crawl//DTD Check Configuration 1.3//EN"
          "https://checkstyle.org/dtds/configuration_1_3.dtd">

<module name="Checker">
    <property name="charset" value="UTF-8"/>

    <module name="TreeWalker">
        <module name="NonEmptyAtclauseDescriptionCheck" />
    </module>
</module>

$ java -jar checkstyle-9.0.1-all.jar -c TestConfig.xml TestClass.java
Starting audit...
Audit done.


text:
Q: Update Matrix of Individual Probabilities There are three ships (1,2 and 3) each ship is traveling towards one of three destinations (A, B and C).
Ship 1 has a 95% chance of going to A, a 2.5% chance of B and a 2.5% chance of C.
Ship 2 has a 5% chance of going to A, a 47.5% chance of B and a 47.5% chance of C.
Ship 3 has a 0% chance of going to A, a 50% chance of B and a 50% chance of C.
By taking the sum of each ships probability by region you expect one ship to arrive at each region but suppose you receive new information that two ships will arrive at A, one ship will arrive at B and no ships will arrive at C.
What is each ships probability of arriving at each region given the new information?


text:
Q: How does individual probability of a sample relate to P(X|Y) (Gaussian Naive Bayes) I am trying to implement a Gaussian Naive Bayes for image classification using MAP. I have a large set of images (28x28 pixels) and I am stuck on how the equation to calculate the probability for a single sample (image) relates to the overall probability P(X|Y) for a category y.
# Variance over all pixels over full data set
var = X_train.var(axis=0) + l

for y in range(10):
    # Calculate the Mean per category
    means[y] = X_train[y_train == y, :].mean(axis=0)

# Loop through categories
for y in range(10):
    # Calculate the probability per category
    for sample in X_train[y_train == y]:
        prob = (1 / np.sqrt(2 * np.pi * var)) * \
            np.exp(-(sample - means[y]) ** 2 / (2 * var))

        # NEED HELP HERE... How does the sample probability relate to P(X|Y)?
        P_xy[y] += prob

 # Further on I sum the log(P(Y) and log(P(X|Y) and find the argmax

As you can see above, currently I am adding all of the probabilities over all samples in a category. However, this leaves me with a number much greater than 1 (i.e. like 700) which clearly isn't right for a probability. My question is how does the sample probability feed into the category probability. Thank you in advance!


text:
Q: Import keywords into ace editor highlighter in webpy server (python) I am using the Javascript Ace text editor and need to load keywords into the (DynHighlightRules) to provide highlighting of the imported keywords. I have highlights working from static keywords in the

editor.getSession().setMode("ace/mode/highlightRules")

, but I need to import new rules after the editor is rendered. I found a great solution which works perfectly in an Apache server but not in the Web.py python server. I believe this is due to the template page not being at the root level of the server. Has anyone deployed the Ace editor in Webpy and solved this issue?

A: Ok, I found a solution to my problem. It's a work around and not the way I was originally going to solve the issue. My first attempts were to embed an ajax call in the "ace.define" function but it wouldn't process it correctly and parts would be missing causing errors. Then I tried to dynamically import the keywords but couldn't make that work in the python environment. Finally I thought to just wrap the whole thing in the success of the ajax call and now it works exactly right. I guess when embedded in the ace function the timing between the ajax events and the other parts of the definition were out of sync.
So the answer in short is to wrap the whole definition in the ajax success callback.
$.ajax({
            url: "/readUserCreatedKeywords",
            type: "POST",
            success: function(response){
                var keywordsString = "";
                var tmpArr = response.split(",");
                var tmpArrLen = tmpArr.length;
                var s = 0;
                var halfNum = 0;
                while (s < tmpArrLen) { // Clean array and save keywords and args into respective arrays
                    halfNum = parseInt(s/2);
                    tmpArr[s] = tmpArr[s].replace("u'", "").replace("[", "").replace("'", "").replace("(u", "").replace(")", "").replace("]", "").replace("(", "").replace(" ", "");

                    if (s % 2 == 0){ //Store even values in keywords
                       keywordsString += tmpArr[s] + "|";
                       //console.log("tmpArr[" + s + "]" + tmpArr[s]);
                    }
                    s++;
                }

                ace.define("ace/mode/python_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) {
                ...............................................lots of code..........................................

                exports.Mode = Mode;
                });

}

});


text:
Q: Real examples of multinomial distribution I found multinomial distribution really powerful in theory. But I don't know if my real case can be treated as multinomial. There are two cases:

*

*There are $n$ students, $30\%$ chose apple, $40\%$ chose banana, $30\%$ chose grape. Then can I say the choice of single student follow a $\mathrm{Multinomial}(n,0.3,0.4,0.3)$ distribution?

*Similar, say I have $n$ books, $30\%$ will be distributed to group 1, $40\%$to group 2, the rest to group 3. Then can I assume the allocation of a single book follows a multinomial distribution? What if I was to allocate money instead of books? In this case, money is continuous not discrete.

A: When your variable is the choice of fruit, if you extract a sample of n students from a population of N students then Y is distributed as a multinomial.
Another example is the extraction of n balls from a urn having red, blue and orange balls, or the extraction of n patients who have been administered a certain treatment (treatmentA, treatmentB and placebo).
about the question #2: if it is a feature already present on each book (and mutually exclusive, for example if you want to group by Author) then yes, if you extract a sample of books and observe this feature the distribution of this variable will be distributed as a multinomial.
The same holds for money: if you have a sample of "money" (bank notes and coins) and you extract a sample of n money and observe the feature "kind of money" (bank notes vs coins) you will then have a binomial distribution. You could instead observe another feature, such as the "head" (defined as the name of the person who's drawn on the head side of the coin or on the banknote) of each coin/banknote and that would follow instead  a multinomial distribution.
Edit:
I am assuming that the N individuals of each population present one and only one category of the characteristic.


text:
Q: Navigation menu list (sub-menu)dropdown isn't working in reactjs I want to implement a navbar like component in reactjs. but pesudo-classes(:hover) for css seem not to be supported by react(css-in-js). I try the another way out to solve the problem using li and state control.
Another problem for this solution is that i can't ripped off the unordered bullet list using display:inline-block or list-style:none because it make the sub-menu items to be disappear when moving my pointer down to them.I am using material-ui/core as UI libraryAn example of my code:
showMenu = () =>{
    this.setState({showMenu: true});
}

hideMenu = () =>{
    this.setState({showMenu: false});
}

html, css

dropdownMenu:{
    position: "absolute",
    fontSize: "0.9rem",
    marginTop: 0,
    right: 15,
    left: "auto",
    top: "63px",
    backgroundColor:"white",
    border:"1px solid #D9E4E3",
    boxShadow: "0px 3px 21px 0px rgba(0, 0, 0, 0.2)",
    animationDuration: "0.25s",
    animationFillMode: "both",
},

            <Avatar style={{backgroundColor: "transparent"}}><Icon>account_circle</Icon></Avatar>
            Louis Barnett

        {this.state.showMenu &&

                    <SideMenuItem label="My Profile" icon={this.renderIcon('person')} onClick={() => this.handleMenuClick("/me")}/>
                    <SideMenuItem label="Settings" icon={this.renderIcon('settings')} />
                    <SideMenuItem label="Logout" icon={this.renderIcon('exit_to_app')} onClick={this.handleSignoutClick}/>

        }

SideMenuItem Component
render() {
    const selected = this.props.location.pathname === this.props.path;
    return(
    <ListItem button dense selected={selected} onClick={this.handleOnClick}>
        <ListItemIcon>
            {this.props.open || !this.props.label ? this.props.icon : <Tooltip title={this.props.label}>{this.props.icon}</Tooltip>}
        </ListItemIcon>
        <ListItemText primary={this.props.label}/>
    </ListItem>
    );
}

A: Hello mate the :hover styling should work in this case. Just try specifying it in a style-sheet instead of inline style.
Sample code
yourCssFile.css
.my-button {
   background-color: yellow;
 }

In your component
import './path_to_css/yourCssFile.css';

In the button
<button class="my-button">Click me</button>

This will apply your styles for your button. Similarly you can try out hover.Check out the reference!


text:
Q: CellValueChanged and Checkbox issue I am using the below code to detect changes on cells and then do a update, but I am having one column of checkbox for detele.
The problem is when I check the checkbox, it will also means that the cell value had been changed.
Is there a workaround on this or is there a stop/end cellvaluechanged command or cellvaluechanged only for certain cells/rows/columns?
Thanks.
protected override void OnLoad(EventArgs e)
    {
        myDataGridView.CellValueChanged += new DataGridViewCellEventHandler(
        myDataGridView_CellValueChanged);
    }

    private void myDataGridView_CellValueChanged(
    object sender, DataGridViewCellEventArgs e)
    {
       //some very crude examples of actions you might want to perform when the event handler is triggered.
       myObject.update();
       //or something else like
       myObject.isUpdatable = true;
    }

A: You only have to check for the ColumnIndex from the DataGridViewCellEventArgs parameter.
http://msdn.microsoft.com/fr-fr/library/system.windows.forms.datagridviewcelleventargs.aspx


text:
Q: Problems unraring a split file in ubuntu 12.04 I installed rar but when i run unrar x -e file_name.part01.rar I get the error message "Failed".
Can someone tell me what I'm doing wrong.
I'm pretty new to ubuntu.

A: If you try to open a split archive file, and you don't have all the parts of the file in your present working directory, you're going to get an error message saying that parts of the archive are missing. However if you just want to extract the first part(s) of the split archive, you can do it using the Archive Manager application which is installed by default in Ubuntu.
The files in a split archive that has missing parts will be extracted by default to a hidden folder, so you will have to use the keyboard combination Ctrl + H to view the hidden folder.
You can't extract the files from part of a split archive unless you have all of the previous parts of the archive.


text:
Q: How can I tell when existentially quantified data constructors are needed to achieve my goals? Recently I implemented a type hierarchy similar to Exception. The gist of it is this:
class (Typeable a) => Hierarchy a where
    toHierarchy :: a -> HierarchyBase
    fromHierarchy :: HierarchyBase -> Maybe a

-- HierarchyBase
data HierarchyBase = forall h. (Hierarchy h) => HierarchyBase h
instance Hierarchy HierarchyBase where
    toHierarchy = id
    fromHierarchy = Just

-- MyType ⊂ HierarchyBase
data MyType = forall e. (Hierarchy h) => MyType h
instance Hierarchy MyType where
    toHierarchy x = HierarchyBase x
    fromHierarchy (HierarchyBase x) = cast x

-- SubType ⊂ MyType ⊂ HierarchyBase
data SubType = SubType
instance Hierarchy SubType where
    toHierarchy x = toHierarchy $ MyType x
    fromHierarchy (HierarchyBase x) = cast x >>= \(MyType x') -> cast x'

-- dispatchHierarchy automatically casts a type into any of its ancestors.
-- for instance, you can do any of these:
-- > disptachHierarchy (f :: HierarchyBase -> ...) SubType
-- > disptachHierarchy (f :: MyType        -> ...) SubType
-- > disptachHierarchy (f :: SubType       -> ...) SubType
hierarchyDispatch :: (Hierarchy a, Hierarchy a') => (a' -> b) -> a -> b
hierarchyDispatch f h = f . fromJust . fromHierarchy . toHierarchy $ h

This solution uses existentially quantified data constructors to define some subtypeable hierarchy types. I've tried to rewrite it without using existentials, but I didn't manage.
I understand that using existential quantifiers this way lets you hide the type variable used in a type constructor: the datatype doesn't depend on it, and I can see why that's necessary to define the Hierarchy typeclass and its instances.
However I don't understand when or why this feature is useful or necessary. Now, every time I get stuck on a type's kind when defining a typeclass or an instance, I feel that I have to try to use existential quantifiers. But it never worked so far. The problem was always somewhere else. And my code is cluttered with unnecessary existentials (think of the classical example of having [Showable 1, Showable 'a'] instead of simply [show 1, show 'a']).
How can I tell when existentially quantified data constructors are needed or useful, as opposed to unnecessary overhead?

A: The simplification of existential datatypes to non-existentials follows from parametricity: the inability to pattern match on types.
data Showable = forall a. Show a => Showable a
-- simplify: Show a is basically a -> String (ignoring showsPrec and showList)
data Showable' = forall a. Showable' a (a -> String)
-- simplify: because pattern matching on the type inside a Showable is not allowed,
-- the only thing that you can do with the a is pass it to the function
-- and the only thing you can do to the function is pass in the given a
data Showable'' = Showable'' String
-- now you realize a Showable type is mostly useless

But Typeable is much harder to deal with than Show. This is understandable: Typeable a essentially means "you can match the type a against patterns". Even if you give up the "open GADT" TypeRep a that comes with Typeable and keep e.g. just the cast operator, you get a higher-rank type:
data Object = forall a. Object a
-- simplify: because pattern matching on the type inside an Object is not allowed
-- the only thing you can do with the a is nothing
data Object' = Object' -- so Object is useless (just use ()!)

data Dynamic = forall a. Typeable a => Dynamic a
-- "simplify": weaken Typeable a to cast :: a -> forall b. Typeable b => Maybe b, then apply parametricity
data Dynamic' = Dynamic' (forall a. Typeable a => Maybe a)
-- but a) you lose the TypeRep and b) this is not exactly simpler
-- (*all* existential types have a higher-rank encoding anyway)

So existential types involving Typeable (including yours) can't be meaningfully simplified.
Existential types are also useful if you really can't control how many values of the quantified type you have, such as in
data Coyoneda f a = forall b. Coyoneda (f b) (b -> a)

Simplifying this type according to the scheme above requires you to "find the bs" in f b and preapply the b -> a to them, but f is not fixed so that's not possible. (When f is a Functor actually Coyoneda f a ~= f a, but there are still performance reasons for using Coyoneda.) The only way out is the generic-but-unhelpful higher-ranked translation:
data Coyoneda' f a = Coyoneda' (forall r. (forall b. f b -> (b -> a) -> r) -> r)

With those examples done, I think this is a good place to put the real answer to your question: it is nontrivial to simplify away an existential type, or even to tell when that is possible. There are some "obvious" markers for types that can't be simplified, and even types that can be simplified may look very different afterwards. For one last example of that kind, the following type came up for me recently. I used it to represent navigation on a non-planar surface:
data Map = forall pos. Map { -- an "associated type" kind of existential, where an existential is used to "create a type at runtime" such as in singletons
  mapInit :: pos,
  mapForward :: (pos, Facing) -> (pos, Facing), -- moving forward on a non-flat surface may change the direction of travel
  mapBacking :: pos -> Index -- "lower" a position to an index into a backing store
}
foldIntoTorus :: BackingStore -> Maybe Map
foldIntoCube  :: BackingStore -> Maybe Map
-- etc.

This type was easy to come up with: I thought of the cases and operations I needed to handle and wrote them down. However, the scheme for removing existentials actually applies pretty easily, and simplifies Map to
type Map' = Pos
-- infinite tree, where the root is the current position and each child is the position in the given direction
data Pos = Pos Index (Facing -> (Pos, Facing))

Is this encoding more or less intuitive? In some cases, the choice of whether to use an existential is more about what you find easy to think about, not necessity.


text:
Q: Flask can't run in development mode, can't find flask module I'm on Windows, using git bash.
I'm able to run Flask if it's not in development mode. If I set FLASK_ENV to "development" to try to trigger debugging and other helpful things, then flask run fails.
The error message is pretty peculiar.
$ flask run
 * Serving Flask app "Neuroethics_Behavioral_Task" (lazy loading)
 * Environment: development
 * Debug mode: on
 * Restarting with stat
d:\miniconda3\python.exe: No module named D:\miniconda3\Scripts\flask

What's weird is that... in the directory D:\miniconda3\Scripts, there is a flask.exe or flask application file.
By typing "where flask", I get returned D:\miniconda3\Scripts\flask.exe. So this executable definitely exists in the location that they're trying to look for, but even then Flask can't seem to find it when I try doing flask run.
How do I approach this?
Edit: some more info. This seems to have to do with the fact that I had Flask previously installed in Anaconda, removed it from anaconda using conda uninstall flask, then I had it installed with pip.
where flask gives D:\miniconda3\Scripts\flask.exe
but pip show flask gives Location: d:\miniconda3\lib\site-packages. The location offered by pip however DOES NOT contain any flask.exe file whatsoever.

A: The flask run command is recommended, but there's currently an issue with Werkzeug on Windows. See Flask reloader crashes with "no module named Scripts\flask" on Windows for the workaround until the bug is fixed.
If you don't want to use that workaround, you can add an if __name__ == "__main__" block and call app.run(debug=True) directly, running it as python app.py. Again, this is not the recommended way to run Flask and there is another workaround to the bug.
from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run(debug=True)


text:
Q: Density of Subgraphs I am stuck trying to make sense of this review problem:
Given a graph G(V, E), we say that the induced subgraph G(S) on a subset of vertices S ⊆ V is a subgraph of G whose vertex set is S and edge set E(S) is the set of all edges in E such that both end points are in S. We say that d(S), the density of the induced subgraph on S, is the ratio of the number of edges to the number of vertices, i.e. d(S) = $|E(S)|/|S|$.
Given a non-empty graph G(V, E), the densest subgraph problem is the problem of
finding S ⊆ V such that the density d(S) is maximized. Let $d^* = max_{S⊆V} d(S)$. Here, we will analyze a simple greedy algorithm for this problem (see the pseudocode below) that is guaranteed to find a subset S ⊆ V such that $d(S) ≥ d^*/2$. The algorithm starts with the set of all vertices and repeatedly removes the minimum degree vertex in the induced subgraph on the current set of vertices. Of all the subgraphs produced in this process, it returns the one with the highest density.
Find Dense Subgraph(V,E)

*

*$S_n = V$ , $S_{max} = S_n$

*for $i = n$ to 2
2(a). v = minimum degree vertex in $G(S_i)$
2(b). $S_{i−1} = S_i$ \ {v}
2(c). if $(d(S_{i−1}) > d(S_{max}))$ then $S_{max} = S_{i−1}$

*output $S_max$
The two questions I'm trying to answer are:
(a) Let $S^∗ ⊆ V$ be such that $d(S^∗) = d^∗$, i.e., $G(S^∗)$ has the maximum possible density over all subgraphs. Prove that for any $v ∈ S^∗$, the degree of v in $G(S^∗)$ is greater than or equal to $d^∗$.
(b) Prove that the density of the subgraph $S_{max}$ output by the algorithm is greater than or equal to $d^∗/2.$
Any help would be so appreciated, even just with understanding the problem. Thanks so much.

A: Hint:

*

*The quantity $d(S)$ can be though of as average over degrees (in $G(S)$, not $G$) divided by 2, that is $$2\cdot d(S) = \frac{2\cdot |E(S)|}{|S|} = \frac{\sum_{v \in S}\deg_{G(S)}(v)}{|S|}$$

*For (a): If some set $S^*$ has the biggest average degree possible, then any its member has to have degree at least this big, otherwise you could remove it from the set, thus make the average higher.

*For (b): Consider the first vertex of $S^*$ that is removed by the algorithm from $S_i$ in step 2. What is its degree and what it implies about degrees of other vertices in $S_i$?

I hope this helps $\ddot\smile$


text:
Q: Powershell script causing a strange character in the output I have this script:
# Read in the RESOURCE ID values I want to locate
$TextToFind = Get-Content -Path .\ResourceIDs.txt

$Text = ""
$PathArray = @()
$Results = ".\ResultsResourceIDs.txt"

# Now iterate each of these text values
$TextToFind | ForEach-Object {
    $Text = $_
    Write-Host "Checking for: " $Text

    If ((Get-Content .\Resources.rc) | Select-String -Pattern $Text) {
        $PathArray += $Text + "¬Found"
    }
    Else {
        $PathArray += $Text + "¬Not Found"
    }
}

Write-Host "Contents of ArrayPath:"
$PathArray | ForEach-Object {$_}

$PathArray | % {$_} | Out-File $Results

It works fine. But the resulting text file has content like:
IDR_ANNOUNCE_TEXT¬Not Found
IDC_BUTTON_UNDO¬Found
IDS_STR_CBS2¬Not Found

Why does it have the strange character?

A: This is due to encoding, you should use set_content CmdLet and you can play on -encoding param if necessary.
$PathArray | % {$_} | Set-Content $Results -Encoding UTF8


text:
Q: Cannot tap red minus delete button in UITableView I am able to make the red minus button appear on each of my UITableViewCells with the following calls:
[self.tableview setEditing:YES];

and
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {

    return UITableViewCellEditingStyleDelete;
}

Now, the red minus buttons appear to the left of the UITableViewCells. However, I can't interact with them via a simple tap (only if I swipe from the red minus to the right).
I want the "Delete" button to appear when I tap on the "Red Minus" button, not just when I swipe.
Why isn't my "Red Minus" button listening to a tap gesture?
EDIT: Here's a screenshot of what my UITableViewCells look like:

A: Figured it out. I had a gesture recognizer getting in the way (dismisses the keyboard when you click outside of the searchbar).
once I removed that everything worked great!

A: Have you implemented the commitEditingStyle tableViewDelegate method?
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
}


text:
Q: How to get and concatenate values from one column based on another column in Excel Excel is beating me up for a day here.
I have this table:
+---+--------+--------+--------+--------+
|   |   A    |   B    |   C    |   D    |
+---+--------+--------+--------+--------+
| 1 |   AGE  |  EX#   |   DG1  |   DG2  |
+---+--------+--------+--------+--------+
| 2 |   19   |   C01  |  ASC   |        |
+---+--------+--------+--------+--------+
| 3 |   45   |   C02  |  ATR   |        |
+---+--------+--------+--------+--------+
| 4 |   27   |   C03  |  LSI   |        |
+---+--------+--------+--------+--------+
| 5 |   15   |   C04  |  LSI   |        |
+---+--------+--------+--------+--------+
| 6 |   49   |   C05  |  ASC   |  AGC   |
+---+--------+--------+--------+--------+
| 7 |   76   |   C06  |  AGC   |        |
+---+--------+--------+--------+--------+
| 8 |   33   |   C07  |  ASC   |        |
+---+--------+--------+--------+--------+
| 9 |   17   |   C08  |  LSI   |        |
+---+--------+--------+--------+--------+

Now, I need to create a new table based on that data, with one row and one column, which I'll fill column A and need a formula to fill column B:
+----+--------+---------------+
|    |   A    |        B      |
+--=-+--------+---------------+
|    |   DG   |       AGE     |
+--=-+--------+---------------+
| 10 |   AGC  |     49, 76    |
+----+--------+---------------+
| 11 |   ASC  |   19, 33, 49  |
+----+--------+---------------+
| 12 |   ATR  |       45      |
+----+--------+---------------+
| 13 |   LSI  |   15, 17, 27  |
+----+--------+---------------+

So I need a formula to check the first table's columns C and D for each DGs, and check the age of each one in column A, and then concatenate all values that match into one cell with a , as a separator.
Can anyone help me?
Thanks

A: On the great excel website from Chip Pierson, I found the custom function: StringConcat. Just copy-paste the code in a VBA module.
Something like the following formula (in cell B10 & fill down)should work for you. It's an array formula (commit with [ctrl-shift-enter]
=StringConcat(", ",IF(Sheet1!$B$2:$C$100=A10,Sheet1!$A$2:$A$100,""))

You'll have to adjust the ranges off course.


text:
Q: How to retrieve a Google Sheet in a Browser Extension with a JS fetch() call? So I have been doing several hours of searching on this and cannot find anything that works with the current Google Sheets API (v4) in a browser. I can 100% get data through Postman and even a browser address bar. I have a public Google Spreadsheet. I have an API Key. I can successfully return all of the row data.
As soon as I try to do so in a browser extension, I get nothing.
Is anyone aware of how to configure a JavaScript fetch() call to get a successful return on a public Google Spreadsheet? No editing, no deleting. Just a GET.
Here's what I'm trying but isn't working:
var url = `https://sheets.googleapis.com/v4/spreadsheets/${spreadsheetId}/values/${sheetId}?key=${key}`

var response = await fetch(url, {
        method: "GET",
        mode: "no-cors",
        headers: {
            "Host": "sheets.googleapis.com"
        }
    });

Two things I noticed:

*

*If mode wasn't set to no-cors in the fetch() I would get a NetworkError

*In Postman if there wasn't a Host header, I would get an error response

A: Keep in mind this is an issue that specifically has to do with writing Browser Extensions/Addons, not just the typical fetch() usage in a browser.
To resolve this, I had to add a host permission in the manifest.json file to allow the URL for the Google API sheets.googleapis.com I am calling, like this:
{
    "manifest_version": 2,
    "name": "Browser Extension",
    "description": "description",
    "version": "1.0.0",
    "icons": {
        "64": "icons/icon.png"
    },
    "background": {
        "scripts": [
            "background_script.js"
        ]
    },
    "permissions": [
        "*://sheets.googleapis.com/*"
    ],
    "content_scripts": [
    [...]

As far as the fetch call, all I need is the URL. No need for any options to be set.


text:
Q: Update Dropdownlist on listview update using update panel asp.net c# I want to re-populate data of a dropdownlist using sql data source when i insert or update data using the Listview control. Is there a way that i can do this without having to refresh my page manually?
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>

        <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1" AutoPostBack="true" DataTextField="type" DataValueField="type" Width="66px">
        </asp:DropDownList>
        <asp:SqlDataSource runat="server" OnInserted="SqlDataSource1_Inserted" ID="SqlDataSource1" InsertCommand="INSERT INTO [permit] ([type]) VALUES (@type, @description, @Priceday, @Priceweek, @Pricemonth, @Pricesem, @Priceyear)" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [permit]" DeleteCommand="DELETE FROM [permit] WHERE [pid] = @pid" UpdateCommand="UPDATE [permit] SET [type] = @type, [description] = @description, [Priceday] = @Priceday, [Priceweek] = @Priceweek, [Pricemonth] = @Pricemonth, [Pricesem] = @Pricesem, [Priceyear] = @Priceyear WHERE [pid] = @pid">
            <DeleteParameters>
                <asp:Parameter Name="pid" Type="Int32" />
            </DeleteParameters>
            <InsertParameters>
                <asp:Parameter Name="type" Type="String" />
            </InsertParameters>
            <UpdateParameters>
                <asp:Parameter Name="type" Type="String" />
            </UpdateParameters>
        </asp:SqlDataSource>

        <asp:ListView ID="ListView1" runat="server" DataKeyNames="pid" DataSourceID="SqlDataSource2" InsertItemPosition="LastItem">
            <AlternatingItemTemplate>
                pid:
                <asp:Label ID="pidLabel" runat="server" Text='<%# Eval("pid") %>' />

                type:
                <asp:Label ID="typeLabel" runat="server" Text='<%# Eval("type") %>' />

                description:
                <asp:Label ID="descriptionLabel" runat="server" Text='<%# Eval("description") %>' />

                Priceday:
                <asp:Label ID="PricedayLabel" runat="server" Text='<%# Eval("Priceday") %>' />

                Priceweek:
                <asp:Label ID="PriceweekLabel" runat="server" Text='<%# Eval("Priceweek") %>' />

                Pricemonth:
                <asp:Label ID="PricemonthLabel" runat="server" Text='<%# Eval("Pricemonth") %>' />

                Pricesem:
                <asp:Label ID="PricesemLabel" runat="server" Text='<%# Eval("Pricesem") %>' />

                Priceyear:
                <asp:Label ID="PriceyearLabel" runat="server" Text='<%# Eval("Priceyear") %>' />

                <asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Edit" />
                <asp:Button ID="DeleteButton" runat="server" CommandName="Delete" Text="Delete" />

            </AlternatingItemTemplate>
            <EditItemTemplate>
                pid:
                <asp:Label ID="pidLabel1" runat="server" Text='<%# Eval("pid") %>' />

                type:
                <asp:TextBox ID="typeTextBox" runat="server" Text='<%# Bind("type") %>' />

                description:
                <asp:TextBox ID="descriptionTextBox" runat="server" Text='<%# Bind("description") %>' />

                Priceday:
                <asp:TextBox ID="PricedayTextBox" runat="server" Text='<%# Bind("Priceday") %>' />

                Priceweek:
                <asp:TextBox ID="PriceweekTextBox" runat="server" Text='<%# Bind("Priceweek") %>' />

                Pricemonth:
                <asp:TextBox ID="PricemonthTextBox" runat="server" Text='<%# Bind("Pricemonth") %>' />

                Pricesem:
                <asp:TextBox ID="PricesemTextBox" runat="server" Text='<%# Bind("Pricesem") %>' />

                Priceyear:
                <asp:TextBox ID="PriceyearTextBox" runat="server" Text='<%# Bind("Priceyear") %>' />

                <asp:Button ID="UpdateButton" runat="server" CommandName="Update" Text="Update" />
                <asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Cancel" />

            </EditItemTemplate>
            <EmptyDataTemplate>
                No data was returned.
            </EmptyDataTemplate>
            <InsertItemTemplate>
                <asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
                    <ContentTemplate>
                type:
                <asp:TextBox ID="typeTextBox" runat="server" Text='<%# Bind("type") %>' />

                description:
                <asp:TextBox ID="descriptionTextBox" runat="server" Text='<%# Bind("description") %>' />

                Priceday:
                <asp:TextBox ID="PricedayTextBox" runat="server" Text='<%# Bind("Priceday") %>' />

                Priceweek:
                <asp:TextBox ID="PriceweekTextBox" runat="server" Text='<%# Bind("Priceweek") %>' />

                Pricemonth:
                <asp:TextBox ID="PricemonthTextBox" runat="server" Text='<%# Bind("Pricemonth") %>' />

                Pricesem:
                <asp:TextBox ID="PricesemTextBox" runat="server" Text='<%# Bind("Pricesem") %>' />

                Priceyear:
                <asp:TextBox ID="PriceyearTextBox" runat="server" Text='<%# Bind("Priceyear") %>' />

                <asp:Button ID="InsertButton" runat="server" CommandName="Insert" Text="Insert" />
                <asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Clear" />

                        </ContentTemplate>
                    <Triggers>
                        <asp:AsyncPostBackTrigger ControlID="InsertButton" EventName="Click" />
                    </Triggers>
                    </asp:UpdatePanel>
            </InsertItemTemplate>
            <ItemTemplate>
                pid:
                <asp:Label ID="pidLabel" runat="server" Text='<%# Eval("pid") %>' />

                type:
                <asp:Label ID="typeLabel" runat="server" Text='<%# Eval("type") %>' />

                description:
                <asp:Label ID="descriptionLabel" runat="server" Text='<%# Eval("description") %>' />

                Priceday:
                <asp:Label ID="PricedayLabel" runat="server" Text='<%# Eval("Priceday") %>' />

                Priceweek:
                <asp:Label ID="PriceweekLabel" runat="server" Text='<%# Eval("Priceweek") %>' />

                Pricemonth:
                <asp:Label ID="PricemonthLabel" runat="server" Text='<%# Eval("Pricemonth") %>' />

                Pricesem:
                <asp:Label ID="PricesemLabel" runat="server" Text='<%# Eval("Pricesem") %>' />

                Priceyear:
                <asp:Label ID="PriceyearLabel" runat="server" Text='<%# Eval("Priceyear") %>' />

                <asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Edit" />
                <asp:Button ID="DeleteButton" runat="server" CommandName="Delete" Text="Delete" />

            </ItemTemplate>
            <LayoutTemplate>

            </LayoutTemplate>
            <SelectedItemTemplate>
                pid:
                <asp:Label ID="pidLabel" runat="server" Text='<%# Eval("pid") %>' />

                type:
                <asp:Label ID="typeLabel" runat="server" Text='<%# Eval("type") %>' />

                description:
                <asp:Label ID="descriptionLabel" runat="server" Text='<%# Eval("description") %>' />

                Priceday:
                <asp:Label ID="PricedayLabel" runat="server" Text='<%# Eval("Priceday") %>' />

                Priceweek:
                <asp:Label ID="PriceweekLabel" runat="server" Text='<%# Eval("Priceweek") %>' />

                Pricemonth:
                <asp:Label ID="PricemonthLabel" runat="server" Text='<%# Eval("Pricemonth") %>' />

                Pricesem:
                <asp:Label ID="PricesemLabel" runat="server" Text='<%# Eval("Pricesem") %>' />

                Priceyear:
                <asp:Label ID="PriceyearLabel" runat="server" Text='<%# Eval("Priceyear") %>' />

                <asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Edit" />
                <asp:Button ID="DeleteButton" runat="server" CommandName="Delete" Text="Delete" />

            </SelectedItemTemplate>
        </asp:ListView>
        <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConflictDetection="CompareAllValues" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" DeleteCommand="DELETE FROM [permit] WHERE [pid] = @original_pid AND [type] = @original_type AND [description] = @original_description AND [Priceday] = @original_Priceday AND [Priceweek] = @original_Priceweek AND [Pricemonth] = @original_Pricemonth AND [Pricesem] = @original_Pricesem AND [Priceyear] = @original_Priceyear" InsertCommand="INSERT INTO [permit] ([type], [description], [Priceday], [Priceweek], [Pricemonth], [Pricesem], [Priceyear]) VALUES (@type, @description, @Priceday, @Priceweek, @Pricemonth, @Pricesem, @Priceyear)" OldValuesParameterFormatString="original_{0}" SelectCommand="SELECT * FROM [permit] WHERE ([type] = @type)" UpdateCommand="UPDATE [permit] SET [type] = @type, [description] = @description, [Priceday] = @Priceday, [Priceweek] = @Priceweek, [Pricemonth] = @Pricemonth, [Pricesem] = @Pricesem, [Priceyear] = @Priceyear WHERE [pid] = @original_pid AND [type] = @original_type AND [description] = @original_description AND [Priceday] = @original_Priceday AND [Priceweek] = @original_Priceweek AND [Pricemonth] = @original_Pricemonth AND [Pricesem] = @original_Pricesem AND [Priceyear] = @original_Priceyear">
            <DeleteParameters>
                <asp:Parameter Name="original_pid" Type="Int32" />
                <asp:Parameter Name="original_type" Type="String" />
                <asp:Parameter Name="original_description" Type="String" />
                <asp:Parameter Name="original_Priceday" Type="Decimal" />
                <asp:Parameter Name="original_Priceweek" Type="Decimal" />
                <asp:Parameter Name="original_Pricemonth" Type="Decimal" />
                <asp:Parameter Name="original_Pricesem" Type="Decimal" />
                <asp:Parameter Name="original_Priceyear" Type="Decimal" />
            </DeleteParameters>
            <InsertParameters>
                <asp:Parameter Name="type" Type="String" />
                <asp:Parameter Name="description" Type="String" />
                <asp:Parameter Name="Priceday" Type="Decimal" />
                <asp:Parameter Name="Priceweek" Type="Decimal" />
                <asp:Parameter Name="Pricemonth" Type="Decimal" />
                <asp:Parameter Name="Pricesem" Type="Decimal" />
                <asp:Parameter Name="Priceyear" Type="Decimal" />
            </InsertParameters>
            <SelectParameters>
                <asp:ControlParameter ControlID="DropDownList1" Name="type" PropertyName="SelectedValue" Type="String" />
            </SelectParameters>
            <UpdateParameters>
                <asp:Parameter Name="type" Type="String" />
                <asp:Parameter Name="description" Type="String" />
                <asp:Parameter Name="Priceday" Type="Decimal" />
                <asp:Parameter Name="Priceweek" Type="Decimal" />
                <asp:Parameter Name="Pricemonth" Type="Decimal" />
                <asp:Parameter Name="Pricesem" Type="Decimal" />
                <asp:Parameter Name="Priceyear" Type="Decimal" />
                <asp:Parameter Name="original_pid" Type="Int32" />
                <asp:Parameter Name="original_type" Type="String" />
                <asp:Parameter Name="original_description" Type="String" />
                <asp:Parameter Name="original_Priceday" Type="Decimal" />
                <asp:Parameter Name="original_Priceweek" Type="Decimal" />
                <asp:Parameter Name="original_Pricemonth" Type="Decimal" />
                <asp:Parameter Name="original_Pricesem" Type="Decimal" />
                <asp:Parameter Name="original_Priceyear" Type="Decimal" />
            </UpdateParameters>
        </asp:SqlDataSource>
    </ContentTemplate>
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="ListView1" />

Code-Behind
public partial class Default3 : System.Web.UI.Page

{
    protected void Page_Load(object sender, EventArgs e)
    {
}
protected void SqlDataSource1_Inserted(object sender, SqlDataSourceStatusEventArgs e)
{
    DropDownList1.Items.Clear();

    //DropDownList1.Items.Dispose();

    DropDownList1.DataSourceID = "SqlDataSource1";
    DropDownList1.DataTextField = "type";
    DropDownList1.DataValueField = "type";
    DropDownList1.DataBind();
}

}

A: After your ContentTemplate, try adding:
<Triggers>
<asp:AsynchronousPostBack ControlID="ListView1" />
</Triggers>

EDIT:
You can try adding to your ListView
OnItemInserted="ListView1_OnItemInserted"

Then in the codebehind method:
DropDownList1.DataBind();

A: Just add this on your SqlDataSource1_OnItemInserted event:
// will delete all of its items
DropDownList1.Items.Clear();

// will release all resourses used by those items
DropDownList1.Items.Dispose();

// this will reload the items on your ddl
DropDownList1.DataSourceID = "SqlDataSource1";
DropDownList1.DataTextField = "type";
DropDownList1.DataValueField = "type";
DropDownList1.DataBind();