text:
Q: IIS 7 dynamic compression truncates downloaded files I have an issue on ASP.NET application which have been recently migrated to new server running IIS7 instead of IIS6. The application has been upgraded to .NET4 though most of the code remains as it was originally written in .NET 1.1. The application manages company's static tables and user can download any static table data in CSV or XML from a web page.
Issue - In case IIS7 feature 'Enable dynamic content compression' is turned on, the file is corrupted (the end of the file is trimmed). The corruption seems NOT to be random, i.e. I get always the same result as long as input data are equal. For different input data sets, the size of the effect (number of characters trimmed) are also different. When I switch dynamic compression off, the problem completely disappears.
Examples of downloads (i am posting always only the last line of the whole CSV file):

*

*static table A

*

*dynamic compresion off (complete file length 720 bytes):
2010-10-21 00:00:00;;"P ";"registrované partnerství";"REGISTERED PARNTERSHIP";"registrované partnerstvo";0

*dynamic compresion off (last 1 byte trimmed - i.e. last line-break lost its "LF" char), file length = 719 bytes):

*static table B

*

*dynamic compression off (no corruption, file length = 593349 bytes):
2012-04-16 00:00:00;;"800650";"Finanční centrum Třebíč";"PSB FC Třebíč";"PSB FC Třebíč";"PSB FC Třebíč";9;2;61;"67401";"Třebíč";"Karlovo náměstí 32/26";5057;2518;852;;;2012-05-02 00:00:00;0

*dynamic compression on (last 2 bytes trimmed (i.e. last CRLF is lost), file length = 593347 bytes):

*static table C

*

*dynamic compression off (no corruption, file length = 282 bytes):
2012-04-16 00:00:00;;"3";"Zaslat do vlastních rukou";0

*dynamic compression on (last 5 characters trimmed, file length = 275 bytes):
2012-04-16 00:00:00;;"3";"Zaslat do vlastních ruk

*static table D

*

*dynamic compression off (no corruption, file length = 6506 bytes):
2010-02-20 00:00:00;2010-03-20 00:00:00;390;"879001";2;0

*dynamic compression on (last 13 characters trimmed, file length = 6491 bytes):
2010-02-20 00:00:00;2010-03-20 00:00:00;390

The same happens for XML output format - but in such case the effect is always the same - XML is always trimmed by 1 character. Consequence is the end tag of the root element is not closed:
</Export>

versus
</Export

As a workaround I recommended to turn off dynamic compression. But I would like to understand what causes this behaviour. I have searched for solutions to the same issue on the web, but I have found only this issue, which is probably not relevant, since the input data are pure uncompressed CSV or XML:


text:
Q: Reading .las file, processing and displaying it with PCL I used libLAS library to read the cloud points of a .las file. Then I stored the points in a PCL point cloud variable in order to process and display the point cloud using the Point Cloud Library.
This is the code that I used:
class PointCloud
{
    public:
        //PointCloud(const std::string& path);

        uint32_t getVertsCount();
        float4* getVertsData();

        template<typename PointT>
        typename pcl::PointCloud<PointT>::Ptr read(const std::string& path);//void read(const std::string &path);
}

template<typename PointT>
typename pcl::PointCloud<PointT>::Ptr PointCloud::read(const string& path)
{
    typename pcl::PointCloud<PointT>::Ptr lasCloud(new pcl::PointCloud<PointT>);

    std::ifstream ifs;
    ifs.open(path, std::ios::in | std::ios::binary);
    //std::ifstream inf(path, std::ios::in | std::ios::binary);

    liblas::ReaderFactory f;
    liblas::Reader reader = f.CreateWithStream(ifs);
    liblas::Header const& header = reader.GetHeader();

    std::cout << "Compressed: " << (header.Compressed() == true) ? "true" : "false";
    std::cout << "Signature: " << header.GetFileSignature() << '\n';
    std::cout << "Points count: " << header.GetPointRecordsCount() << '\n';

    while (reader.ReadNextPoint())
    {
        liblas::Point const& p = reader.GetPoint();

        PointT cloudPoint;
        cloudPoint.x = float(p.GetX()) * 0.001 + 590284.000; // (double)(x * scaleX) + offsetX;
        cloudPoint.y = float(p.GetY()) * 0.001 + 4339456.000; // (double)(y * scaleY) + offsetY;
        cloudPoint.z = float(p.GetZ()) * 0.001 + 157.000; // (double)(z * scaleZ) + offsetZ;
        std::cout << p.GetX() << ", " << p.GetY() << ", " << p.GetZ() << "\n";
        //cloudPoint.intensity = p.GetIntensity(); // (double)(intensity) / 65536.0;
        lasCloud->points.push_back(cloudPoint);
    }

    if (!ifs.good())
        throw runtime_error("Reading went wrong!");

    lasCloud->width = lasCloud->points.size();
    lasCloud->height = 1;
    lasCloud->is_dense = true;
    std::cout << "Cloud size = " << lasCloud->points.size() << endl;
    return lasCloud;

}

int main (int argc, char** argv)
{

    std::cout << "starting enviroment" << std::endl;
    pcl::visualization::PCLVisualizer::Ptr viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
    CameraAngle setAngle = FPS; //XY, FPS, Side, TopDown
    initCamera(setAngle, viewer);
    pcl::PointCloud<pcl::PointXYZ>::Ptr inputCloudI; //
    inputCloudI = pcd.read<pcl::PointXYZ>("C:/Users/hedey/OneDrive/Documents/Research_papers/STDF/10_4231_MFQF-Q141/I-65/LiDAR/RoadSurface/NB/20180524_I65_NB_RoadSurface_1_50.5.las");
    std::cout << "Cloud size = " << inputCloudI->points.size() << endl;
    renderPointCloud(viewer, inputCloudI, "lasCloud");
    while (!viewer->wasStopped())
    {
        viewer->spinOnce();
    }
}

However, the displayed cloud using the PCL viewer looks like one point. What I noticed is that when I printed out the coordinates that I read using libLAS, the x & y coordinates don't have decimal values, which is inaccurate compared to the actual coordinates stored in the las file. I got the actual point coordinates using las2txt from the command prompt. This is the txt file containing the actual coordinates. And here is an image showing the cout results:

Also, this is how the point cloud looks like when I opened it using CloudCompare. I look forward to geting the same displayed when I read it into a PCL Point Cloud variable and display the results using the PCL viewer, because I'll need to do further processing in order to make sensor fusion (Camera and Lidar).

A: The default precision of std::cout is 6 decimal digits. Please add something like
    std::cout.precision(12);

before the while loop.
Also, casting p.GetX() etc. to float is pointless: if you multiply it by 0.001, the left hand side of the argument of operator* will naturally by promoted to at least double. However, float  has only about 7 digits of precision, so for 9-digit integers  stored inside doubles (yes!) such truncation is catastrophic.
Also there's another (minor) error, the correct line reads
    std::cout << "Compressed: " << ((header.Compressed() == true) ? "true\n" : "false\n");

Please notice the () braces surrounding  the conditional expression (and \n). Please use standard compiler options that will warn against such simple issues.
Please read also https://stackoverflow.com/help/minimal-reproducible-example

redpajama_set_name: RedPajamaStackExchange


text:
Q: Insert 2 values into MySQL, and then stop said values appearing again I have a script, its supposed to insert a vote (either -1 or +1) to a MySQL value, it does this fine, but it's also supposed to insert the ID of the item they have just voted on, into another table, in array format, to the user who has just voted, so that it doesn't appear again for that user.
1) I don't know how to stop the values appearing again
2) It's not sending the id of the website
The code:
    $sql = "SELECT * FROM webmash ORDER BY RAND() LIMIT 1";
    $result = mysql_query($sql) or print ("Can't select entry from table webmash.
" . $sql . "
" . mysql_error());

    while($row = mysql_fetch_array($result)) {
    $name = stripslashes($row['name']);
    $description = stripslashes($row['description']);
    $link =($row['link']);
    $votes = ($row['votes']);
    $id = $row['id'];
    }

    $sql2 = "SELECT * FROM webmashusers";
    $result2 = mysql_query($sql) or print ("Can't select entry from table webmashusers.
" . $sql . "
" . mysql_error());

    while($row = mysql_fetch_array($result2)) {
    $username = stripslashes($row['username']);
    $likes = ($row['likes']);
    $dislikes = ($row['dislikes']);
    }

    if(isset($_POST['like'])) {
    $votes += 1;
    $sql = "UPDATE webmash SET votes = $votes WHERE id = ".$_POST['id'];
    mysql_query($sql);

    $sqllikes = array (serialize($id));
    $sql2 = "INSERT '$sqllikes' INTO webmashusers (likes) WHERE 'username' = '$376770'";
    mysql_query($sql2);
    }

    if(isset($_POST['dislike'])) {
    $votes -= 1;
    $sql = "UPDATE webmash SET votes = $votes WHERE id = ".$_POST['id'];
    mysql_query($sql);

    $sqldislikes = array (serialize($id));
    $sql2 = "INSERT '$sqldislikes' INTO webmashusers (dislikes) WHERE 'username' = '$376770'";
    mysql_query($sql2);

    }

EDIT: $376770 is my username cookie.

A: Saving serialized arrays in mysql isn't a good way.
Anyway I think you have a couple of errors starting with:
 $sqllikes = array (serialize($id));

basically you are serializing a simple int ?
$id is previsouly setted to = $row['id'];
That makes 0 sense.
You should store just the int of the ID in a single column and maybe to avoid duplicate insert you can make it UNIQUE with the other key.

A: Side note, you use $_POST['id'] in raw query.. way vulnerable for sql injections.
$sql = "UPDATE webmash SET votes = $votes WHERE id = ".$_POST['id'];

As for your question, you use INSERT, even if there is already such user in the second table. UPDATE should be useful in the case. Overall, you could google for "INSERT ... ON DUPLICATE UPDATE" Mysql syntax for $sql2 queries and use it (together with making user name unique index in second table).


text:
Q: Referring to an object in the URL - do you use primary key or what is the best practice? I want to refer to some instance of a data through my URL. What is the recommended way to do that? Should I use the primary key of that data or is that exposing database information unnecessarily? Even with using PKs, the URL is not 'clean'. So how do you handle this usually?
Details:
I use django for my website. I have a model called 'Team'. Any teacher can create her own Team online at which point it gets added to the database. I do not require the Team name to be unique. A teacher can have multiple teams.
Now any action "add students to the team", "assign homework to the team" anything, requires that a reference to the team should be passed in the URL. Something like:
 {{ SITE_URL }}/add-student/{{ team }}/

Since names are non-unique, I cannot use the name.
Currently, I assign a UUID to every team when it is created and use the uuid in my URLs. That works, but it makes for ugly URLs.
I could use primary key of the team, which would be shorter than the uuid, but again not a very nice URL. I also wonder whether exposing primary key of a model's database entry is a security issue? Though, I noticed that SO seems use primary keys in its URLs.
So what is the best practice here?

A: Django's class based views (DetailView, UpdateView) default to using the pk in the url as a named url group to determing which object to fetch, so judging by that i think it doesn't violate any practices by using the pk in the url.
If you want a very memorable url you could create a slug and append the pk, while not perfectly optimal, would still be more memorable then a UUID
I also believe, your view should be validating whether the requesting user has the correct permissions to view the url, this should be independent of the actual url structure.


text:
Q: Amazon MWS API returning InvalidParameterValue on GetMyFeesEstimate request I have a script that sends some ASINs to Amazon in order to retrieve their FeeEstimates, i'm using a php client for the api.
Here is the main part of my code:
       $n = count($products);
       $amazonFeesAux['MarketplaceId'] = 'my-market-place-id';
       $amazonFeesAux['IdType'] = 'ASIN';
       $amazonFeesAux['ListingPrice']['CurrencyCode'] = 'EUR';
       $amazonFeesAux['IsAmazonFulfilled'] = true;

       echo 'Total number of unique ASINs: ' . $n;

       for($i = 1; $i <= $n; ++$i)
       {
            $amazonFeesAux['IdValue'] = $products[$i - 1]['ASIN'];
            $amazonFeesAux['ListingPrice']['Value'] = $products[$i - 1]['price'];
            $amazonFeesAux['Identifier'] = $i;
            array_push($amazonFees, $amazonFeesAux);

            if($i % $this->requestQuota == 0)
            {
                if (++$batchN > $this->requestQuota) sleep(2);    //  wait 2 seconds to restore 20 items before next request

                echo "\n========================================= Batch number: " . $batchN . " =============================================== \n";

                $newAmazonProductRanks = $this->getAmazonProductFeesData($amazonFees);
                $amazonFees = [];       // reset array as to re-populate with next batch
                $this->updateProductFees($newAmazonProductRanks); <-- do something with the fees
            }
       }

Here, my $products is just my array of ASINs, and $this->getAmazonProductFeesData is just my function which sends the request to amazon. Everything works fine but for some ASINs I get back a vague Client Side Error which looks like this:

Does anybody have any idea what am I doing wrong or missing here?
PS: This code uses GetMyFeesEstimate original MWS api request.

A: I'm having this issue too, with a particular ASIN. I was able to verify this using the MWS Scratchpad. Other ASINs using the Scratchpad works find though.


text:
Q: Not able to print using 14.04 I have ubuntu and I love it but I cannot get my printer to print even though its showing that its installed in the printer screen.
I am using 14.04, when ubuntu was first installed on my computer I had 12.0 and a hp printer I had was connected very quickly. Now I have another hp but this time a laserJet pro m127fw and cannot connect it. The printer itself shows that it is not connected to the computer but the computer says otherwise.
I have been trying for the past two weeks. I am new to this and feel very stuck. I don't know what else to do at this point. This is my 8th printer. After trying six I was told the other brands does not work with ubuntu, got a brother they said the same. I was told only hp does so I got this one.
Someone please HELP
Thanks

A: Please try the below steps which may help,

*

*Ping your printers and check whether it was successfull

*To get started, open Printers utility from Unity Dash search results
or System Settings.

*Once it opens, go to menu Server -> Settings

*Check the box where it says "Publish shared printers connected to
this system" to enable network sharing of connected printers.

*Finally, right-click on a printer in the list and go to its
Properties window. Under Policies tab, make sure all three boxes
(Enabled, Accepting jobs, and Shared) are checked.
Now try to connect to your printer from Ubuntu client using Internet Printing Protocol (ipp://ip.address.or.name/printers/Printername).
If Issue persists, please install CUPS to get rid of it

*

*CUPS is installed right into Ubuntu and Linux Mint and if for some strange reason can't find it, you can easily install it with the following command.
sudo apt-get install cups

*Now the page would look something like in the image below. As you could have already recognized with the Unity dock on the left, we are running Ubuntu (13.10). You will be able to access CUPS on the same address on Linux Mint, or any other Linux distribution with CUPS as well. Once you are on this page, click on "Administrator", and then click on "Add Printer." You might be asked for username and password of your computer.

*In the "Add Printer" page, choose the appropriate option – choose local HP Printer (HPIP) or printer or Other Networks Printers or Select Internet Printing Protocol.

In the connection field you will have to enter the IP address of your printer in the format, socket://hostname and hit continue.
It could look something like this, socket://10.33.20.23

*In this page you will be asked to give a name, description and location of your machine, you can also choose if you want to share this printer or not with the sharing option. Hit "continue" to go to the next page. In this page you will have to choose your printer manufacturer and subsequently the model and hit "Add printer." You could find almost all the printers in the list, if you don't, you will manually have to add the PPD file, which will have all the information required.

*At this point you will be able to set the default options and you are in business. Your printer will be ready for use, and whenever you need to print anything you can access your printer from the address
http://localhost:631
Hope this helps!

A: I've just reinstalled all printers and it worked.


text:
Q: Okta login using angular through Node I am creating a login strategy for my angular 6 web app. The user clicks the login button and it triggers an HTTP request to localhost:3000/login on my node server. I am using okta as an authenticator and using the passport oidc strategy.  If I go to localhost:3000/login it performs the redirect as expected to the okta sign-in the portal. When I try it from my angular front end I get a CORS error. I have enabled Access-Control-Allow-Origin with a wildcard.

//app.js

require("dotenv").config();
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const routes = require("./routes/routes");
const mongoose = require("mongoose");
const casperRoutes = require("./routes/casper-routes");
const oktaRoutes = require("./routes/okta-routes");
const slackRoutes = require("./routes/slack-routes");
const session = require("express-session");
const passport = require("passport");
const OidcStrategy = require("passport-openidconnect").Strategy;

const oktaBaseAuth = process.env.OKTA_AUTH_URI;
mongoose
  .connect(
    "mongodb+srv://xxxxx",
    { useNewUrlParser: true }
  )
  .then(() => {
    console.log("connected to database!");
  })
  .catch(() => {
    console.log("connection failed");
  });

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader(
    "Access-Control-Allow-Headers",
    "Origin, X-requested-With, Content-Type, Accept"
  );
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET, POST, PATCH, PUT, DELETE, OPTIONS, PUT"
  );

  next();
});

app.use(
  session({
    secret: "xxx",
    resave: false,
    saveUninitialized: true
  })
);
app.use(passport.initialize());
app.use(passport.session());
passport.use(
  "oidc",
  new OidcStrategy(
    {
      issuer: oktaBaseAuth + "/oauth2/default",
      authorizationURL: oktaBaseAuth + "/oauth2/default/v1/authorize",
      tokenURL: oktaBaseAuth + "/oauth2/default/v1/token",
      userInfoURL: oktaBaseAuth + "/oauth2/default/v1/userinfo",
      clientID: process.env.OKTA_AUTH_CLIENT_ID,
      clientSecret: process.env.OKTA_AUTH_CLIENT_SECRET,
      callbackURL: 'http://localhost:3000/authorization-code/callback',
      scope: "openid profile"
    },
    (issuer, sub, profile, accessToken, refreshToken, done) => {
      return done(null, profile);
    }
  )
);
passport.serializeUser((user,next)=>{
  next(null,user);
});
passport.deserializeUser((obj,next)=>{
  next(null,obj);
});

app.use('/login', passport.authenticate('oidc'));
app.use('/authorization-code/callback',
passport.authenticate('oidc', {failureRedirect: '/error'}),

(req,res)=>{
  res.redirect('/');

});
function checkLogged(req,res,next){
  if (req.isAuthenticated()){
    return next();
  }
  res.redirect('/login');
}

app.use("/api/casper",checkLogged, casperRoutes);
app.use("/api/data",checkLogged, routes);
app.use("/api/okta", checkLogged,oktaRoutes);
app.use("/api/slack", checkLogged, slackRoutes);

module.exports = app;

The front end service

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Subject, Observable } from "rxjs";
import * as OktaSignIn from "@okta/okta-signin-widget";
import { Injectable } from "@angular/core";
import { Router } from "@angular/router";

@Injectable({
  providedIn: "root"
})
export class OktaService {
  widget;
  isAuthenticated = false;
  user;
  private headers = new HttpHeaders();

  private authStatusListener = new Subject<boolean>();

  constructor(private http: HttpClient, private router: Router) {}

  loginUser(){
    this.http.get('http://localhost:3000/login').subscribe(res=>console.log(res));
  }

}

And the error

Failed to load https://dev-795809.oktapreview.com/oauth2/default/v1/authorize?response_type=code&client_id=0oag898j7zj7j8jqw0h7&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fauthorization-code%2Fcallback&scope=openid%20openid%20profile&state=rtFMOtsHHBOc90UcM3nLIz%2Fp: Redirect from 'https://dev-795809.oktapreview.com/oauth2/default/v1/authorize?response_type=code&client_id=0oag898j7zj7j8jqw0h7&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fauthorization-code%2Fcallback&scope=openid%20openid%20profile&state=rtFMOtsHHBOc90UcM3nLIz%2Fp' to 'https://dev-795809.oktapreview.com/login/login.htm?fromURI=/oauth2/v1/authorize/redirect?okta_key=c8hyLEuNV3KeYJyLfw2EU9xDjqsqeSOLft2jLzh-07E' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

I've enabled CORS on my OKTA app as well. I read somewhere this may be because I cannot resolve CORS with a wildcard for authorization data. How can I connect to the backend for login using angular front-end running on a different port?

A: This happens because you're trying to make an XHR request to your backend. If you change it to redirect to your backend, it should work.
  loginUser() {
    window.location.href = 'http://localhost:3000/login'
  }

The problem with this approach is that you'll likely be redirected back to your Node app after successfully logging in, rather than your Angular app. You could write custom code in your Node app to redirect back to the referrer after authentication. I've done this with Spring Security, but I'm not sure how to do it for Node.
Another option would be to use our Angular SDK and do the authentication in your Angular app, and set up your Node API as a resource server that simply validates the access token that's passed in.


text:
Q: Implementing in python I am pretty new in Python. I would like to implement a program in an object-oriented form. In the end, I like to use the objects of a class in this format.
ObjectA.add.func1()

I am not sure what kind of structure I need to use for add? If whether it is another object inside another object?
The functionality of my program should be like this:
add is object or something else that I will pass some functions to it. It will contain those functions.
at the end, I will call forexample ObjectA.apply() and it will apply all functions to the object. The object can be vector of floats. I also open to any suggestion, what should add be? but I like to use the add in the instruction form I mentioned.

A: Yes, it'd be an object that is a member of another object.  Something like:
class Adder:
    def func1(self):
        pass

class MainObject:
    def __init__(self):
        self.add = Adder()

object_a = MainObject()
object_a.add.func1()

As an aside piece of advice: it's better to figure out what your code will do before you figure out what "shape" it will have.  Trying to force your program logic into a particular OOP model before you know anything else about what you're trying to do is likely to make your life more difficult, whereas the goal of OOP should be to make it easier.  :)


text:
Q: django ListView - Sort queryset by the order of mptt-TreeForeignKey field I have the following two models.
class Category(MPTTModel):
    name=models.CharField(max_length=75,null=False,blank=False, unique=True)
    parent=TreeForeignKey('self', null=True, blank=True, related_name='children')

and
class ProductGroup(models.Model):
    name = models.CharField(max_length=30,null=False, blank=False)
    category=TreeForeignKey('category.Category', null=False,blank=False)

I have set an order for the categories through the admin panel.
I need to get the ProductGroup objects sorted in the same order through its ListView sub class.
I have tried,
class ProductGroupList(ListView):
    model=ProductGroup
    ordering = ['category']

but this lists the objects in the order of id of Categories.
Is there a way to specify the order specified in the mptt tree?
Thanks.


text:
Q: React-dnd with multiple canDrops split via a array I'm working with building a drag and drop from one div container to another. It works under a normal circumstance with the code below if I do not separate out my drop area into separate divs. However this is what I need to do so I hide the div's which are steps adn then use a next previous button to toggle through them however I can't create 4 separate dropzones because that number could change dynamically.
So my question is how can I split up the can drop section to make it dynamic based on the array its contained within. I'm mostly referring to the boxes.map area as that is what generates the result as you drag in any elements because I have it contained within another array but I need there to be Multiple CanDrops in this scenario there would be 4 because stepBlock is equal to 4 but I'm not sure how to tie that into the parent array. Here is my code:
 import { useDrag, useDrop, useDragLayer } from 'react-dnd'

  let stepBlock = 4;

const ELEMENT = 'element';

const [{ isDragging }, drag, dragPreview] = useDrag(() => ({
    type: ELEMENT,
    collect: (monitor) => ({
    isDragging: monitor.isDragging()
    })
}))

const [{ canDrop, isOverCurrent }, drop] = useDrop({
    accept: 'element',
    canDrop: () => true,
    drop: item => {
    if (isOverCurrent) {
    setBoxes([...boxes, item]);
    }
    },
    collect: monitor => ({
    canDrop: monitor.canDrop(),
    isOverCurrent: monitor.isOver({ shallow: true })
    )
})

{[...Array(stepBlock)].map((e, i) =>
<div key={i} className={`stepBlock ${i !== index ? "hidden" : ""}`}>
    {boxes.map(member => (

        {member.name}

    ))}
    <div className={`drop-area ${canDrop ? 'highlight': ''}`} ref={drop}>
    {canDrop ? 'Release to drop' : 'Drag a box here'}

)}

<button
 disabled={index === 0}
 onClick={() => setIndex((prevIndex) => prevIndex - 1)}
 className={'previousBTN'}>previous</button>
 <button
   disabled={index === stepBlock - 1}
    onClick={() => setIndex((prevIndex) => prevIndex + 1)}
     className={'nextBTN'}>next</button>


text:
Q: Bad Request Почта России удаление заказа Предварительно отправляю заказ - получаю ID заказа и хочу его сразу удалить по инструкции https://otpravka.pochta.ru/specification#/orders-delete_new_order.
Отправляю следующие данные:
$orderData = array
    ('backlog_ids' =>
        array(my_id));
$url = 'https://otpravka-api.pochta.ru/1.0/backlog';
$method = 'DELETE';
$headers = [
    'Content-Type: application/json;charset=UTF-8',
    'Authorization: AccessToken ХхххХхХхххХхХХХХХхххххХХХХХХХ',
    'X-User-Authorization: Basic ХхххХхХхххХхХХХХХхххххХХХХХХХ',
];
$data = json_encode([$orderData]);

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

$response =  curl_exec($curl);
curl_close($curl);

Получаю ответ:
{
   "timestamp": "2020-05-01T15:38:45+0300",
   "status": 400,
   "error": "Bad Request",
   "message": "Bad Request",
   "path": "/1.0/backlog"
}

Что я не так делаю?

A: Всё! Разобрался! Просто невнимательно читал документацию.
$orderData = 12345678; //нужно было просто вписать номер my_id


text:
Q: how to insert other object to event listener? this is my javascript :
var tool = {
    addEvent : function(element, eventName, callback){
        if (element.addEventListener) {
            element.addEventListener(eventName, callback, false);
        } else if (element.attachEvent) {
            element.attachEvent("on" + eventName, callback);
        }
    },
    getPosition : function(el){
        var _x = 0;
        var _y = 0;
        while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
            _x += el.offsetLeft - el.scrollLeft;
            _y += el.offsetTop - el.scrollTop;
            el = el.offsetParent;
        }
        return { top: _y, left: _x };
    }
}
function getObj(){
    this.a = document.getElementById('div');
    this.b = document.getElementById('table');

    this.func = function(){
        var pos = tool.getPosition(this);
        // how to insert this.b here
        // i want to set this.b offset from this.a offset
    }

    tool.addEvent(this.a,'scroll',this.func);
}

var obj = new getObj();

how to modify this.func so whenever this.a is scrolling, this.b will be syncronized to this.a
this.b offset is get from this.a offset.
when i try :
 this.func = function(){
        var pos = tool.getPosition(this);
        // value from pos will be set to this.b
        console.log(this.b);
        // how to insert this.b here
        // i want to set this.b offset from this.a offset
 }

this.b is undefined.

A: Your getPosition function is a member of this, so you cannot call it using getPosition(...). You must call it using this.getPosition(...) or redeclare the getPosition function as a function scope variable:
function getObj() {
    ...
    var getPosition = function(...) { ... };

    this.addEvent = function(...) { ... };
    ...
}

Edit:
When adding the DOM event, you'll also need bind this.func to the current context:
this.func = this.func.bind(this);

this.addEvent(this.a,'scroll',this.func);


text:
Q: Prevent "GenServer terminating" error in exunit test with supervised process I have a test in my Phoenix app that is testing a Phoenix.PubSub subscriber that uses Genserver. The subscriber does some database work as part of its handle_info/2.
test "sending creating a referral code upon user registration" do
  start_supervised(MyApp.Accounts.Subscriber)
  user = insert(:user)

  Phoenix.PubSub.broadcast(MappApp.PubSub, "accounts", {:register, user})

  assert_eventually(Repo.exists?(ReferralCode))

  stop_supervised(MyApp.Accounts.Subscriber)
end

Running this test module by itself is fine. However when I run my entire test suite I get an error like so (the test still passes):
[error] GenServer MyApp.Accounts.Subscriber terminating
** (stop) exited in: DBConnection.Holder.checkout(#PID<0.970.0>, [log: #Function<9.124843621/1 in Ecto.Adapters.SQL.with_log/3>, cache_statement: "ecto_insert_referral_codes", timeout: 15000, pool_size: 10, pool: DBConnection.Ownership])
    ** (EXIT) shutdown: "owner #PID<0.969.0> exited"
    <stacktrace...>

This looks like it's an issue with the database connection still being open when the process is terminated so it doesn't die gracefully. But I'm not sure how to deal with this.
Any advice on how to prevent this error?

A: I ran into this today.  Any time you are doing database operations in separate child processes (e.g. database operations triggered inside a GenStage or GenServer et al), then you need to read the Sandbox adapter documentation carefully.  There is an FAQ that deals with this error specifically, and the solution can be either to explicitly grant the Sandbox adapter access to the child process like this (from the docs):
test "gets results from GenServer" do
  {:ok, pid} = MyAppServer.start_link()
  Ecto.Adapters.SQL.Sandbox.allow(Repo, self(), pid)
  assert MyAppServer.get_my_data_fast(timeout: 1000) == [...]
end

or you can enabled "shared" mode by altering your test setup to set the Sandbox mode:
  setup do
    :ok = Sandbox.checkout(Repo)
    Sandbox.mode(Repo, {:shared, self()})
  end

I had more luck with the latter, but be aware that if you are using some other adapter anywhere explicitly (e.g. to make raw database calls), then it might cause tests to fail (because it can no longer get a connection).


text:
Q: app crashing with "Called From Wrong Thread Exception" I added this part of the code in my onCreate() method and it crashes my app.
need help.
LOGCAT:
android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread
that created a view hierarchy can touch its views.

CODE:
final TextView timerDisplayPanel = (TextView) findViewById(R.id.textView2);

    Timer t = new Timer();
    t.schedule(new TimerTask(){
        public void run(){
            timerInt++;
            Log.d("timer", "timer");
            timerDisplayPanel.setText("Time ="+ timerInt +"Sec");
        }
    },10, 1000);

A: Only the UI thread that created a view hierarchy can touch its views.

You are trying to change the text of the UI element in Non UI Thread, so it gives exception.Use runOnUiThread
 Timer t = new Timer();
 t.schedule(new TimerTask() {
 public void run() {
        timerInt++;
        Log.d("timer", "timer");

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                timerDisplayPanel.setText("Time =" + timerInt + "Sec");
            }
        });

    }
}, 10, 1000);


text:
Q: google maps + jquery auto close last infowindow I am trying to call mouseover event on markers when a user hovers over address. When open new infowindow need to close last infowindow, but dont know how to start. Open this page:
http://fiddle.jshell.net/spYYh/12/
Plz help me! Thanks!

A: This question is similar to this one - Google Maps API v3: Close infowindow when DOM element is clicked - so the answer applies.
The key difference being that you want to detect a mouse over event, which will be a "mouseover" event instead of the "click" event mentioned in the reference question and answer.
google.maps.event.addListener(marker, 'mouseover', function() {
   infowindow.setContent(contentString);
   infowindow.open(map, marker);
});

It doesn't matter that your problem is serving multiple markers.  We can do this:-
var infowindow = null;
.
.
.
/* now inside your initialise function */
infowindow = new google.maps.InfoWindow({
    content: "holding..."
});

for (var i = 0; i < markers.length; i++) {
    var marker = markers[i];
    google.maps.event.addListener(marker, 'mouseover', function() {
        //open the infowindow when it's not open yet
        if(contentStringCal!=infowindow.getContent())
        {
          infowindow.setContent(contentStringCal);
          infowindow.open(map, marker);
        }
    });

    google.maps.event.addListener(marker, 'click', function() {
        //when the infowindow is open, close it an clear the contents
        if(contentStringCal==infowindow.getContent())
        {
          infowindow.close(map, marker);
          infowindow.setContent('');
        }
        //otherwise trigger mouseover to open the infowindow
        else
        {
          google.maps.event.trigger(marker, 'mouseover');
        }
    });

    //clear the contents of the infwindow on closeclick
    google.maps.event.addListener(infowindow, 'closeclick', function() {
          infowindow.setContent('');
    });
}


text:
Q: SVG transparency with multiple gradients I am trying to find out the optimal model for 4-way gradient filling. My latest model is this fiddle:
<svg height="360" width="400" xmlns="http://www.w3.org/2000/svg" version="1.1">
  <defs>
    <clipPath id="C">
      <path d="M 100 200 L 300 58 L 400 250 L 300 341 Z" />
    </clipPath>
    <radialGradient id="G1" cx="50%" cy="50%" r="50%" fx="50%" fy="50%">
      <stop offset="0%"   style="stop-color:rgb(255,0,0);    stop-opacity:1" />
      <stop offset="100%" style="stop-color:rgb(128,128,64); stop-opacity:0" />
    </radialGradient>
    <radialGradient id="G2" cx="50%" cy="50%" r="50%" fx="50%" fy="50%">
      <stop offset="0%"   style="stop-color:rgb(0,255,0);    stop-opacity:1" />
      <stop offset="100%" style="stop-color:rgb(128,128,64); stop-opacity:0" />
    </radialGradient>
    <radialGradient id="G3" cx="50%" cy="50%" r="50%" fx="50%" fy="50%">
      <stop offset="0%"   style="stop-color:rgb(0,0,255);    stop-opacity:1" />
      <stop offset="100%" style="stop-color:rgb(128,128,64); stop-opacity:0" />
    </radialGradient>
    <radialGradient id="G4" cx="50%" cy="50%" r="50%" fx="50%" fy="50%">
      <stop offset="0%"   style="stop-color:rgb(255,255,0);  stop-opacity:1" />
      <stop offset="100%" style="stop-color:rgb(128,128,64); stop-opacity:0" />
    </radialGradient>
  </defs>
  <ellipse cx="100" cy="200" rx="200" ry="200" clip-path="url(#C)" fill="url(#G1)" />
  <ellipse cx="300" cy="58"  rx="200" ry="200" clip-path="url(#C)" fill="url(#G2)" />
  <ellipse cx="400" cy="250" rx="200" ry="200" clip-path="url(#C)" fill="url(#G3)" />
  <ellipse cx="300" cy="341" rx="200" ry="200" clip-path="url(#C)" fill="url(#G4)" />
</svg>

which comes with result:

But when I change order of <ellipse> elements (see this fiddle):
  <ellipse cx="100" cy="200" rx="200" ry="200" clip-path="url(#C)" fill="url(#G1)" />
  <ellipse cx="300" cy="58"  rx="200" ry="200" clip-path="url(#C)" fill="url(#G2)" />
  <ellipse cx="300" cy="341" rx="200" ry="200" clip-path="url(#C)" fill="url(#G4)" />
  <ellipse cx="400" cy="250" rx="200" ry="200" clip-path="url(#C)" fill="url(#G3)" />

result changes to:

Which means transparency is not calculated same way. I would like to have transparency calculated always with same results, regardless of order of the elements. What is a solution for this issue?

A: At any given point on that surface, the final color is computed by taking into account all the elements that cover that point, in their stacking order. There is always a stacking order in SVG, you can't have all the gradients taken as a whole.
A true 4-way gradient must have at each point a color that mixes in an amount of each color equal to the percentage of the distance from the color source to the shape edge at that specific point. But that can't be obtained with stacked layers, and here's why:
Assuming that you have layers with a uniform transition from color to transparency, and that the layer order is red, green, blue, yellow, with red at the bottom and yellow on top, then a point right in the middle will have roughly
 50% yellow + 50% of the color below

which becomes
(50% yellow + 50%(50% blue + 50% of the color below))
->
(50% yellow + 50%(50% blue + 50%(50%green + 50%(50% red +50% background))))
->
(50%yellow + 25%blue + 12.5%green + 6.25%red)

which is far from a 50% of everything mix.
You could try to adjust how abruptly each layer becomes transparent, knowing that the final transparency isn't given by that layer's transparency alone, but also by how opaque the layers above it are. So, if you want to obtain 25% of each layer in the middle, then you'd have to solve the equation:
(y% yellow + (100-y)%(b% blue + (100-b)%(g% green + (100-g)%(r% red))))
=
(25% yellow + 25% blue + 25% green + 25% red)

While this equation is fairly simple to solve (y=25, b=33.3, g=50, r=100), the equation must stand at each point on the surface, and I doubt that you can get a valid answer with simple radial or linear gradients.


text:
Q: platform difference? I was trying out the bitset class in C++ and I tried this with the number 137 as an example:
So, I converted it to binary number which gave me 10001001. Now, I wanted to cut off the MSB and store the rest bits 0001001 in another bit instance called bitarray and I was expecting to see that in the bitarray but it wasn't giving the right value. what could have been the problem? I was just trying to split the MSB from the rest of the bits in the 137 binary representation...here is the code:
bitset<8> bitarray;

bitset<8> bitsetObject(num);
int val = bitsetObject.size();

for (int i = 0; i <= (val - 1); i++)
{
    if (i == 6)
        break;
    else
        bitarray[i] = bitsetObject[i + 1];
}

If anyone knows how I could easily slice from the second element to the last element in the bitsetObject array, let me know. Thanks..

A: If you're just trying to make a new bitset object with the most significant set bit reset, then consider the following:
template<std::size_t N>
std::bitset<N> strip_mssb(std::bitset<N> bitarray)
{
    for (std::size_t i = bitarray.size(); i--;)
        if (bitarray[i])
        {
            bitarray.reset(i);
            break;
        }
    return bitarray;
}

Online demo.

A: You set bitarray[0] equal to bitsetObject[1], which is 0 (assuming num is really 137).
You seem to expect the least bit of bitarray to be equal to 1.


text:
Q: Databricks Autoloader is reading files from subfolders without explicitely asked to do so I'm working with Azure Databricks where I am stream reading files from an Azure Datalake container. I am using the autoloader functionality with .format("cloudFiles").
The file structure in the container looks like this:

*

*../accounts/*.csv

*../accounts/snapshot/*.csv

Both folders (files and snapshot) contains lots of csv files and while for the loading path i'm only specifying "../files" anything that is in snapshot is also getting ingested by the autoloader.
My problem is: I want the autoloader to ignore any subfolder, but I have no clue how can that be achieved.
For technical restrictions this snapshot folder cannot be moved as it is produced by the MS Dynamics365 data export functionality; essentially it creates its own file structure and doesn't allow for much configuration.
Thorough testing proved that the subfolder is getting picked up, but we have no idea why. Is it a default behaviour of autoloader?
The options I am using for this:

*

*("cloudFiles.useNotifications", True) -> this is an implementational requirement. Could this be the problem?

*("recursiveFileLookup", False) -> The default value is false, but the existence of this option suggests that reading subfolders is not the default behaviour of autoloader.

As a workaround I can call the .option("pathGlobFilter", ?????.csv) which then filters for the files in account which are different from snapshot, but there has to be something else that resolves this.


text:
Q: How to use sumifs to total tips by time range? I have a tip report that gives me tips by specific time. I need to sum the tips for each hour of the day starting at 5AM. When using sumifs, I'm able to sum the total without the second criteria range. Could someone help? Thanks!
Here is the code I am using.
=SUMIFS($D$4:$D$283,$C$4:$C$283,">="&G4,$C$4:$C$283,"<="&H4)
[1]: https://i.stack.imgur.com/2YJ9n.png

A: Here is a possible solution:

A
B
C
D
E
F

Time
Tip
Hour
=IF(COUNTA(A:A)>COUNTA(C:C),"Increase Hour column length","Hour column lenght checked")
Hour
Tips' total by hour

44796,2471064815
2,4
=HOUR(A2)

5
=SUMIF(C:C,E2,B:B)

44796,2731134259
5,04
=HOUR(A3)

6
=SUMIF(C:C,E3,B:B)

44796,2751967593

=HOUR(A4)

7
=SUMIF(C:C,E4,B:B)

44796,2773958333
3,32
=HOUR(A5)

8
=SUMIF(C:C,E5,B:B)

44796,2843055556
4,03
=HOUR(A6)

9
=SUMIF(C:C,E6,B:B)

44796,284375
5,81
=HOUR(A7)

10
=SUMIF(C:C,E7,B:B)

44796,2847800926
6,47
=HOUR(A8)

11
=SUMIF(C:C,E8,B:B)

44796,2855787037
4,53
=HOUR(A9)

12
=SUMIF(C:C,E9,B:B)

44796,2857986111
3,65
=HOUR(A10)

13
=SUMIF(C:C,E10,B:B)

44796,2880208333
3,32
=HOUR(A11)

14
=SUMIF(C:C,E11,B:B)

44796,2891203704
3,3
=HOUR(A12)

15
=SUMIF(C:C,E12,B:B)

44796,2896990741
2,7
=HOUR(A13)

16
=SUMIF(C:C,E13,B:B)

44796,2913888889

=HOUR(A14)

17
=SUMIF(C:C,E14,B:B)

44796,2928935185

=HOUR(A15)

18
=SUMIF(C:C,E15,B:B)

44796,2988425926
2,18
=HOUR(A16)

19
=SUMIF(C:C,E16,B:B)

44796,3238194444
2,88
=HOUR(A17)

20
=SUMIF(C:C,E17,B:B)

21
=SUMIF(C:C,E18,B:B)

22
=SUMIF(C:C,E19,B:B)

23
=SUMIF(C:C,E20,B:B)

24
=SUMIF(C:C,E21,B:B)


text:
Q: Deploying Django app using passenger I can get through everything on their wiki - and then I'm lost. http://wiki.dreamhost.com/Django
I have a blank Django template, and whenever I try to change anything I get a 500 internal server error.
I have completely developed my django app locally and just want to host it online - figured it would be easy but am slowly learning that it is not.
I upload my app "videos" to this directory and then put it into the installed apps and ran "python manage.py syncdb", which finds no fixtures (which I Found odd).
From there, it just gets an internal server error.
Here is the error I am getting: http://tweettune.com/ and here is the error log:
[Wed Aug 24 01:49:15 2011] [error] [client 66.212.30.122] Premature end of script headers:
[Wed Aug 24 01:49:15 2011] [error] [client 66.212.30.122] Premature end of script headers: internal_error.html
[Wed Aug 24 08:16:40 2011] [error] [client 99.229.160.94] Premature end of script headers:
[Wed Aug 24 08:16:41 2011] [error] [client 99.229.160.94] Premature end of script headers: internal_error.html
[Wed Aug 24 08:21:38 2011] [error] [client 99.229.160.94] Premature end of script headers:
[Wed Aug 24 08:21:38 2011] [error] [client 99.229.160.94] Premature end of script headers: internal_error.html
[Wed Aug 24 08:27:41 2011] [error] [client 99.229.160.94] Premature end of script headers:
[Wed Aug 24 08:27:41 2011] [error] [client 99.229.160.94] Premature end of script headers: internal_error.html

I've been trying for 6 hours now and can not figure out what I am doing wrong. I suppose I just don't understand how to deploy an application at all - my thought process now is take my locally hosted app and replace all the files in the default django template online. I don't see why this should not work but it's not. I tried the "hello world app" example by using this code in my passenger_wdgi file and it works...
def application(environ, start_response):
    start_response('200 OK', [('Content-type', 'text/plain')])
    return ["Hello, world!"]

Any direction would be helpful.
EDIT: Here are the contents of my passenger_wsgi.py file which may be helpful (although it is automatically generated by dreamhost...so figured it would be correct).
import sys, os
sys.path.append(os.getcwd())
os.environ['DJANGO_SETTINGS_MODULE'] = "sotd.settings"
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
project_path='/home/tweettune.com/sotd/'
sys.path.insert(1, project_path)

A: I had the same problem.
The solution was to add the folder of my application in the wsgi_passenger.py
import sys, os
sys.path.append(os.getcwd())
sys.path.append(os.path.join(os.getcwd(), 'include your apps folder here'))
os.environ['DJANGO_SETTINGS_MODULE'] = "cpc.settings"
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()

This link was very useful to me:
http://discussion.dreamhost.com/thread-128918.html

A: If using django>1.7 replace two last line with
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

A: It's difficult to know exactly what you're doing wrong without seeing your setup. I followed the instructions, and it wasn't that hard.
One thing you can do to debug your application is to run through manage.py. It won't be able to bind to a socket (and if it does, it will get autokilled after a few minutes), but that will at least show if there are other problems that prevent your app from running.
One other thing to note: the file is called passenger_wsgi.py, and should live in your site root. For example, I have ~/testing.tustincommercial.com/passenger_wsgi.py, and all of my project code lives under ~/testing.tustincommercial.com/oneclickcos. My static content lives under ~/testing.tustincommercial.com/public.
It can help to have some error-handling middleware installed, so that errors don't propagate all the way to passenger, thus triggering a 500 error.
My wsgi_passenger.py is:
import sys, os, re
cwd = os.getcwd()
sys.path.append(os.getcwd())

#add all installed eggs to path
for x in ['/home/marcintustin/django/'+x for x in os.listdir('/home/marcintustin/django/') if re.search('egg$', x)]:
    sys.path.insert(0,x)

sys.path.insert(0,'/home/marcintustin/django')
sys.path.insert(0,'/home/marcintustin/django/Django-1.3')
sys.path.insert(0,'/home/marcintustin/django/Paste-1.7.5.1-py2.5.egg')
sys.path.insert(0,'/home/marcintustin/django/South-0.7.3-py2.5.egg')
sys.path.insert(0,'/home/marcintustin/django/Werkzeug-0.6.2-py2.5.egg')

myapp_directory = cwd + '/oneclickcos'
sys.stdout = sys.stderr
sys.path.insert(0,myapp_directory)
sys.path.append(os.getcwd())

os.environ['DJANGO_SETTINGS_MODULE'] = "oneclickcos.settings"
import django.core.handlers.wsgi
#from paste.exceptions.errormiddleware import ErrorMiddleware
from werkzeug.debug import DebuggedApplication
from django.core.servers.basehttp import run, AdminMediaHandler, WSGIServerException

application = django.core.handlers.wsgi.WSGIHandler()
handler = AdminMediaHandler(application, '/home/marcintustin/testing.tustincommercial.com/public/static/admin')
application = DebuggedApplication(handler, evalex=True)

This does a bunch of stuff, most of which isn't strictly necessary - all of the stuff at the top is to make sure that the libraries I've installed are available. The stuff at the bottom installs middleware. You're probably better off with paste.exceptions.errormiddleware.ErrorMiddleware, unless the werkzeug debugger works for you (it won't work for me on Dreamhost).
Edit: I think your config is wrong. Please go the directory which holds your project, and use pwd to get the full path. I think you will find you have not got your paths right.

A: I had the exact same problem. The answers here put me in the right direction, thanks. I use virtualenv with my django app and the os.getcwd() did it for me.
import os, sys

#Fix for passenger
INTERP = "/var/webapps/myapp_env/bin/python"
if sys.executable != INTERP: os.execl(INTERP, INTERP, *sys.argv)
sys.path.append(os.getcwd())
#

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()


text:
Q: selecting element from xml file my code is showing all the addresses of shops.xml file. but i want to show just that address (in shops.php)on google map that matched with the inputted address
shops.xml file:
<shops>
<shop>
<name>Galaxy</name>
<address>72 Callander Road, Noble Park</address>
</shop>
<shop>
<name>Home</name>
<address>7 Close Avenue, Dandenong </address>
</shop>
</shops>

shop.htm:

<form>
Ente Address: <input type="text" name="address" size="40" />
<input name="submit" type = "button" onClick = "load()" value = "Search"  />
</form>

shop.js
function load()
  {
    var  map = new GMap2(document.getElementById("map"));
     map.setCenter(new GLatLng(-37.816667,144.966667), 10);
     map.addControl(new GSmallMapControl());
     map.addControl(new GMapTypeControl());

    var  geocoder = new GClientGeocoder();

  GDownloadUrl("shops.xml", function(data) {
      var addr =document.getElementsByName['address'];
      var xml = GXml.parse(data);
     var  shop = xml.documentElement.getElementsByTagName("shop");
      for (var i = 0; i < shop.length; i++) {
      var   addre= shop[i].getElementsByTagName("address");
        addre = addre[0].childNodes[0].nodeValue;
        if(addre==addr)
        var address=addre;
        geocoder.getLocations(address, addToMap);}
    });
   }

function addToMap(response)
  {
  place = response.Placemark[0];
  point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);

  function createMarker(point,address)
   {
   var marker = new GMarker(point);
   GEvent.addListener(marker, "click", function()
   {
    map.openInfoWindowHtml(point, address);
   });
   return marker;
   }
   map.addOverlay(createMarker(point, response.name));
  }

A: I think you forget to put condition in this function of matching the address.
-> GDownloadUrl ... in this you have to check condition wheather it is matching the xml address.
->take your value in js variable like var addr =document.getElementsByName['adr'];
-> than have to pass in  geocoder.getLocations(address, addToMap);


text:
Q: Regex for password of minimum 8 characters, including at least 3 of these: uppercase character, lowercase character, number and special character Following is the regex that I am currently using for validating passwords: at least one uppercase character, at least one lowercase character, at least one number and minimum 8 characters in length.
func isValidPassword() -> Bool {
    let passwordRegEx = "^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{8,}$"
    return NSPredicate(format:"SELF MATCHES %@", passwordRegEx).evaluate(with: self)
}

I would now like to include special characters and update the validation rule as follows.
minimum 8 characters in length, should include at least 3 of these: uppercase character, lowercase character, number and special character.
What would be the regex for this requirement?

A: I think you better write a for-loop to iterate through the single characters and keep track of which createria has already passed, instead of creating a more and more complex regular expression.

*

*The regex will be hard to understand / maintained by any programmer in just a few month. And any programmer includes you in a few months

*You could provide detailled information to the user if the requiremens do not match. You could display a message "No uppercase character found in password" etc.

*You could (more) easily implement stuff like "disallow repeating numbers" and so on

*Although performance does not matter, regexp will be way slower than looping.


text:
Q: How to invoke Property/Field of Generic Type with Reflection Consider Following class
class A<T> where T:new()
{
  public static T Instance = new T();
  A()
  {
  }
}

I have 2 questions

*

*I need Instance object with Reflection.  I have tried following
var type = typeof(A<int>);
// var type = typeof(A<>).MakeGenericType(typeof(int)); // Also tried this

var instanceMember1 = type.GetMember("Instance",  BindingFlags.Static );  // returns null
var instanceMember2 = type.GetField("Instance",  BindingFlags.Static ); // returns null

I have also tried to Change Instance to property and call GetProperty with no success.

*After removing new() constraint and making constructor private, How to invoke private (parameterless) constructor through reflection.

A: Add BindingFlags.Public to your flags for GetField.
var instanceMember1 = type.GetField("Instance", BindingFlags.Static |
    BindingFlags.Public);

To invoke the private constructor:
var ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic,
    null, Type.EmptyTypes, new ParameterModifier[0]);
var instance = ctor.Invoke(null) as A<int>;


text:
Q: Сравнение данных с++ Есть файл с данными которые необходимо сравнить с данными вводимыми с клавиатуры
Есть код, но он не работает
int i = 0;
int j = 0;
ifstream mfile("managersRegister.txt", ios_base::in);
if(!mfile)
{
    cout << "\nОшибка открытия файла.";
    exit(1);
}
do
{
    mfile >> larr[i].login;
    mfile >> larr[i].password;
    i++;
} while (!mfile.eof());

cout << "\nВведите логин.";
cin >> carr[i].login;
cout << "\nВведите пароль.";
cin >> carr[i].password;

if(larr[i].login == carr[i].login && larr[i].password == carr[i].password)
{
    cout << "\nВы авторизовались как менеджер.";
}
else
{
    cout << "\nВведены неверные данные.";
    exit(1);
}

в консоли делает вывод неверных данных

A: Ну, промолчим о том, что неизвестно, какие типы вы используете; будем считать, что все верно.
После цикла чтения i - индекс за пределами заполненного массива.
И вы сравниваете этот незаполненный элемент с введенными данными.
Вам ничего не кажется странным?
Почему бы не построить программу иначе: запрос пароля и логина, сохранение, и далее - в цикле - чтение очередных данных и сравнение с ними? И никакой массив не нужен...


text:
Q: How do I create View/Filter to allow Teachers to see all Student assignments in a library, but the students to only be able to see their own? So I use SharePoint in school for students turn in assignments and for teachers to grade them via Office 365.
I have a SharePoint user group (Teachers) who need to see all the documents uploaded to the library by all the students. However, each student should only see the documents they added to the library and nobody else's.
Can a specific view be assigned to each user group based on their user ID? I.e. Teachers Group are directed the "All Documents" view and Students Group is filtered by [Me]. Can I prevent students accessing the "All Documents" view?
Thanks for your help guys.

A: You could use Audience Targeting on the List View Web Parts.  For instance for the default LVWP for your document library, set its target audience to be the Teachers group.  Then add another LVWP for the same document library to the same page, set its target audience to be the Students group, set up a view for that LVWP that filters by Created by = [Me], and show no toolbar so they can't change the view. They should still be able to upload documents through the Ribbon.

A: I'm not sure about preventing access to a view, but you could prevent access to the documents.
I've had this requirement before, so I create a SharePoint 2010 list workflow with an impersonation step that, when the document is created/uploaded, permissions are replaced with the user who created it, and whoever else needs access.  I try to use groups as much as possible with the "whoever else needs access", as that will make management a little easier.
With this you can also make it so the student can't change the document once they upload it by making their permissions Read.
I have found that with SharePoint Online, finding where the permissions are broken is much easier, so I don't worry too much about this, though I try to document where I have done this.


text:
Q: mysql regular expression for exact word match I want regular expression for exact word match for mysql select query. If i have below string from database
string :  my name is amit patel with surname amitnindroda

Now i want to match whole word amit from above string then it should find exact word amit and it should not find match from amitnindroda. Please suggest regular expression for mysql query

A: You can use REGEXP Keyword and the [[:<:]] and [[:>:]] word-boundary markers:
SELECT *
FROM tablename
WHERE keywords REGEXP '[[:<:]]word[[:>:]]'

Example:
Input
id  name
1   my name is admin in userwindow
2   my name is user in adminWindow

Query:
SELECT * FROM test WHERE test.name REGEXP '[[:<:]]admin[[:>:]]'

Output:
 id  name
 1   my name is admin in userwindow

So You can see here above query is searching word 'admin' only.


text:
Q: In C++, were SFINAE and metaprogramming intentional or just a byproduct of templates? SFINAE and template metaprogramming can do wonderful things and many libraries also use them considerably.
Historically both of these "magic concepts" were intentionally introduced/supported in C++ ? Or they were just later discovered as useful byproducts (side products) of original template programming ?

A: About a decade ago after a conference day I happened to find myself in a pub with Erwin Unruh and a few others and I asked him about the program VJovic mentioned. We have had a couple of beers by then, it was an unofficial meeting, and it's lived in my head for a decade, so take this with a grain of salt, but according to my memories:
He said that they had added template features in order to better serve the STL. According to him, some/many in the committee felt that they were creating something without knowing its full capabilities. He himself suspected that all the template stuff, especially so partial specialization, made up a Turing-complete language, and he always meant to do a formal proof of that, but never got around doing so.
Instead one night at a standardization meeting he came up with that program which printed prime numbers as error messages (a version that should work with modern compilers is here) that it computed during the compilation. As a template meta-program it isn't very impressive by today's standards, but it was a first, after all. Someone made what he considered a joke by formally submitting the program so it became an official ISO standardization document.
I remember that I specifically asked him about Bjarne Stroustrup's reaction to the program, and in response Erwin mimicked him by covering his eyes with his hand. :)
In hindsight I regret I hadn't asked Todd Veldhuizen, who also was at that conference, how he came up with expression templates. (He certainly was a nice chap to talk to.) But I was much younger than, and let the life-time opportunity slip by. :(

A:
In 1994 during a meeting of the c++ standardization committee, E. Unruh
  discovered that templates can be used to compute something at compile
  time. He wrote a program that prints prime numbers. The intriguing
  part of this exercise was that the production of the prime numbers was
  performed  by the compiler during the compilation process and not at
  the run time. Although this program wasn't fully portable, the program
  did show that the template instantiation mechanism is a primitive
  recursive language that can perform non-trivial computations at
  compile time.

This excerpt is taken from "c++ templates" by Vandevoorde and Josuttis (chapter 17).
As you can see, it was discovered early and its power was recognized immediately.


text:
Q: List the year when the table was dropped If I have these tables:
SUMMERGAMES (sg_gameno [PK], sg_year)
GAME-DISCIPLINE ( discipline_code[PFK], sg_gameno[PFK] )
DISCIPLINE (discipline_code, discipline_name)

I need to list the discipline code and discipline name of those disciplines that ran in 2004 but did not run in 2008 or 2012. I also need to list the year it was dropped, i.e., (2008 or 2012) the first year it did not appear.
I used MINUS operator to solve the first part. But I do not know how to list the year it was dropped.

A: How about using aggregation and getting the maximum year something was around and whether it was around in 2004?
select d.discipline_code, d.displine_name,
       max(sg.sg_year) as lastYearRan,
       max(sg.sg_year) + 4 as firstYearDropped
from summergames sg join
    gamediscipline gd
    on sg.sg_gameno = gd.sg_gameno join
    discipline d
    on gd.discipline_code = d.discipline_code
group by d.discipline_code, d.displine_name
having sum(case when sg.sg_year = 2004 then 1 else 0 end) > 0 and
       sum(case when sg.sg_year in (2008, 2012) then 1 else 0 end) = 0;

The having clause has two conditions.  The first says that the discipline ran in 2004.  The second says it didn't run in 2012 -- so was presumably dropped in 2008 or 2012.
Each condition in the having clause is counting the number of matching rows.  For instance, the first condition is counting the number of rows that have a year of 2004.  The > 0 is requiring that there be at least one.  Similarly the second counts the number of rows where the discipline has a year of 2008 or 2012.  The = 0 requires that there be no such records.


text:
Q: Is it possible to be a frequentist and a subjectivist at the same time? I'm trying to understand the differences between (1) Bayesian vs frequentist; and (2) subjectivist vs objectivist.
So far my understanding (correct me if I'm wrong) is that:
(1) Bayesian vs frequentist.

*

*Frequentist: A probability $p$ represents a long-run frequency.

*Bayesian: A probability $p$ simply reflects our tentative state of knowledge. Given new information, we may update $p$.

(2) Subjectivist vs objectivist.

*

*Subjectivist: A probability is simply one's personal, subjective degree of belief about some particular matter. So two rational, intelligent people with the same information and knowledge can disagree about a probability $p$.

*Objectivist: It is impossible for two perfectly-rational people with the same information and knowledge to disagree about a probability $p$.

My understanding is that Bayesians are typically subjectivist and frequentists are typically objectivist.
However, it is possible for Bayesians to be objectivist.
My question is this: Is it possible for frequentists to be subjectivist?  And how would such a subjectivist-frequentist interpret probability?


text:
Q: getInvoices method failing We have been using the getInvoices to extract costs for a specific time period. Today we tried this command.
curl -k -n "https://api.softlayer.com/rest/v3/SoftLayer_Account/286900/getInvoices?objectMask=mask%5Bid,closedDate,createDate,typeCode,invoiceTotalAmount,invoiceTotalOneTimeAmount,invoiceTotalRecurringAmount,invoiceTopLevelItems%5Bid,description,hostName,domainName,totalRecurringAmount,totalOneTimeAmount,parentId,categoryCode,billingItemId,billingItem%5Bid,orderItem%5Bid,order%5Bid,userRecord%5Bid,username,firstName,lastName%5D%5D%5D%5D%5D%5D&objectFilter=%7B%22invoices%22:%7B%22createDate%22:%7B%22operation%22:%20%22betweenDate%22,%22options%22:%20%5B%7B%22name%22:%20%22startDate%22,%20%22value%22:%20%5B%227/29/2016%200:0:0%22%5D%7D,%7B%22name%22:%20%22endDate%22,%20%22value%22:%20%5B%228/5/2916%2023:59:59%22%5D%7D%5D%7D%7D%7D"

The return is "{"error":"Internal Error","code":"SoftLayer_Exception_Public"}"
I have no idea what this error means.  The date span for the invoices is from 7/29/2016 to 8/5/2016.
Thanks for any help.

A: I'm not able to reproduce the problem, but maybe the cause is related a lot information in the response. Please try again the request by adding Result limits.
These articles can help you:
http://sldn.softlayer.com/blog/phil/How-Solve-Error-fetching-http-headers
https://sldn.softlayer.com/article/REST
Update:
After executing some tests more, an error message displays when trying to execute SoftLayer_Account::getInvoices

{   "error": "Allowed memory size of 402653184 bytes exhausted (tried
  to allocate 4 bytes)",   "code": "Client" }

I assume that is a huge number of data to break the execution and the problem may be the memory usage limit.
In that case result limits can help us, this is a basic example:
https://api.softlayer.com/rest/v3/SoftLayer_Account/getInvoices?resultLimit=0,10

Method: GET


text:
Q: How to correctly use python webbrowser with system service I have a service running a python script. In the script, I use webbrowser.open() to launch the default browser. It opens browser correctly when I just run the script.
When I add the script in ExecStart, everything works fine without any exception when system boots. However, it just doesn't open browser.

A: Your question is a variation of the FAQ "Why do things work differently under systemd?.
In this case, systemd is not supplying the DISPLAY environment variable that is available in your CLI.
The value for DISPLAY is not always stable, and there may not always be a DISPLAY connect to.
A recommended alternate solution for launching GUI apps is to use your desktop environment's "autostart" feature to automatically launch something on login.


text:
Q: Discord bot crashes after starting i tried to use this code and everythink looks quite cool but everytime im gettin an big error after second from starting
from discord import Intents
from discord.ext import commands
from dotenv import load_dotenv
import os
import replicate

os.environ["DISCORD_TOKEN"] = "TOKEN"

load_dotenv()

intents = Intents.default()
intents.message_content = True

bot = commands.Bot(
    command_prefix="!",
    description="Runs models on Replicate!",
    intents=intents,
)

@bot.command(aliases=["sd"])
async def stable_diffusion(ctx, *, prompt):
    """Generate an image from a text prompt using the stable-diffusion model"""
    msg = await ctx.send(f""{prompt}"\n> Generating...")

    model = replicate.models.get("stability-ai/stable-diffusion")
    image = model.predict(prompt=prompt)[0]

    await msg.edit(content=f""{prompt}"\n{image}")

bot.run(os.environ["DISCORD_TOKEN"])

error message
\[2022-11-17 20:33:21\] \[INFO    \] discord.client: logging in using static token
Traceback (most recent call last):
File "bot.py", line 34, in \<module\>
bot.run(os.environ\["DISCORD_TOKEN"\])
File "C:\\Users\\Roman\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages\\discord\\client.py", line 828, in run
asyncio.run(runner())
File "C:\\Users\\Roman\\AppData\\Local\\Programs\\Python\\Python38\\lib\\asyncio\\runners.py", line 43, in run
return loop.run_until_complete(main)
File "C:\\Users\\Roman\\AppData\\Local\\Programs\\Python\\Python38\\lib\\asyncio\\base_events.py", line 608, in run_until_complete
return future.result()
File "C:\\Users\\Roman\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages\\discord\\client.py", line 817, in runner
await self.start(token, reconnect=reconnect)
File "C:\\Users\\Roman\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages\\discord\\client.py", line 746, in start
await self.connect(reconnect=reconnect)
File "C:\\Users\\Roman\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages\\discord\\client.py", line 672, in connect
raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
Exception ignored in: \<function \_ProactorBasePipeTransport.__del__ at 0x000001CBA8AA73A0\>
Traceback (most recent call last):
File "C:\\Users\\Roman\\AppData\\Local\\Programs\\Python\\Python38\\lib\\asyncio\\proactor_events.py", line 116, in __del__
self.close()
File "C:\\Users\\Roman\\AppData\\Local\\Programs\\Python\\Python38\\lib\\asyncio\\proactor_events.py", line 108, in close
self.\_loop.call_soon(self.\_call_connection_lost, None)
File "C:\\Users\\Roman\\AppData\\Local\\Programs\\Python\\Python38\\lib\\asyncio\\base_events.py", line 711, in call_soon
self.\_check_closed()
File "C:\\Users\\Roman\\AppData\\Local\\Programs\\Python\\Python38\\lib\\asyncio\\base_events.py", line 504, in \_check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed


text:
Q: Is added or has been added What is right way to write or speak?
I am a developer and want to add message to my application once the record has been added to the database.
So I am confused about the right way to write/speak the message.

The record is added

or

The record has been added

A: Another possibility is to simply say it like this:

Record added.

That's short for "[The] record [has been / was] added."
You will see that sort of thing all the time in software.

Message sent.
File deleted.

Users don't like to read a lot of text. It's good to get straight to the point with them.

A: "The record is added" is incorrect--it should be "the record was added." Both sentences would then be correct. But, for a software application, "the record has been added" sounds better to me.

A: I usually prefer "Record added successfully", especially with databases. The reason for this is because there might be access restrictions causing the record to be revoked ("no permission").


text:
Q: Javascript: How to remove lastChild among select statements The below code I have is designed to create and remove a new dropdown menu upon clicking the button. However, when clicking the remove button, it removes the first created dropdown. How do I set it up to remove the last created dropdown?

 document.getElementById('add').addEventListener('click',
  function(addioc){
   var addition = document.getElementById('IOC_select').cloneNode(true);
   document.getElementById('IOC_input').appendChild(addition);
  }
 );

 document.getElementById('remove').addEventListener('click',
  function(removeioc){
   var subtraction = document.getElementById('IOC_select');
   subtraction.parentNode.removeChild(subtraction);
  }
 )
<!DOCTYPE html>
<html>
<body>
<form id="IOC_input">
 <select id = "IOC_select">
  <option value = "IOC"> IOC Type: </option>
 </select>
</form>

<button id="add">ADD IOCs</button>
<button id="remove"> REMOVE IOCs</button>
<button id="submit"> SUBMIT IOCs</button>
</body>
</html>

Edited to add the HTML code that was asked for.

A: document.getElementById('IOC_select'); will always return the first element with id="IOC_select".
Remove the last element of the subtraction.parentNode.children Change the following part
document.getElementById('remove').addEventListener('click',
        function(removeioc){
            removeioc.preventDefault();
            var subtraction = document.getElementById('IOC_select');
            let children = subtraction.parentNode.children
            subtraction.parentNode.removeChild(children[children.length - 1]);
            return false;
        }
    )

A: If you use .querySelector(), you can get a direct reference to the last option element by using the last-child pseudo-class and remove it:
Also, you don't need the lines about .preventDefault() since there is no default behavior associated with these events. You also don't need return false here.

document.getElementById('remove').addEventListener('click', function(){
    var subtraction = document.querySelector('#IOC_select > option:last-child');
    // If there is an element to remmove
    if (subtraction){
      subtraction.parentNode.removeChild(subtraction);
    }
});
<select id="IOC_select">
  <option>choice 1</option>
  <option>choice 2</option>
  <option>choice 3</option>
  <option>choice 4</option>
  <option>choice 5</option>
  <option>choice 6</option>
  <option>choice 7</option>
  <option>choice 8</option>
</select>
<button id="remove">Remove last choice</button>


text:
Q: IIS Manager opens maximized and the Restore Down button minimizes the window; the window cannot be made smaller I have two monitors on a Windows 10 x64 system. IIS Manager (IIS 10) opens maximized in the left monitor and it cannot be made smaller or moved to the other monitor. Clicking the "Restore Down" button minimizes the window. Is this a known problem and is there  a fix for it?  I have tablet mode disabled.

A: I have not heard of such a problem.
It might be due to the fact that
IIS Manager will not let you reduce its window below a certain size.
The screen of your tablet might be too small for it not to take up
the entire screen.
If you suspect Windows corruption, run
Dism /Online /Cleanup-Image /RestoreHealth
and
sfc /scannow.
Ensure also that Windows 10 is fully updated.


text:
Q: JSF-2 f:selectItems with Map does not display itemLabel When I use f:selectItems to display items in a Map I cannot display the value of the Map item, only the key.  f:selectItems does not use the itemLabel at all.  When I use a List instead things work.
The following does make use of the itemLabel to display the "description" of an item in a List:
<h:selectOneMenu>
  <f:selectItems value="#{testBB.testList}" var="s"
    itemLabel="TEST #{s.description}" itemValue="#{TEST s.name}" />
</h:
selectOneMenu>

The following attempt to display the value of an item in a Map does not work.  It displays the item's key, but not using the itemLabel attribute, as can be discerned by that lack of output of the "TEST" text.
<rich:select>
  <f:selectItems value="#{testBB.testMap}" var="s"
    itemLabel="TEST #{s.value}" itemValue="TEST #{s.key}" />
</rich:select>

The simple backing bean used follows:
public class TestBB {
  private Map<String, String> testMap;
  private List<TestItem> testList;

  public TestBB() {
    testMap = new HashMap<String, String>();
    testMap.put("1_key", "Item One");
    testMap.put("2_key", "Item Two");
    testMap.put("3_key", "Item Three");

    testList = new ArrayList<TestItem>();
    testList.add( new TestItem("name_1", "description_1") );
    testList.add( new TestItem("name_2", "description_2") );
    testList.add( new TestItem("name_3", "description_3") );
  }

  public Map<String, String> getTestMap() {
    return testMap;
  }

  public List<TestItem> getTestList() {
    return testList;
  }

}

So, any ideas on how to make this work, that is, how to effectively use a Map with selectItems?

A: Your question is sound, but the code makes it confusing and ambiguous. I'll just ignore your code in this answer.
As to the concrete question "How to use Map in <f:selectItems>", you need to realize that map keys are by default been used as item labels and that map values are by default been used as item values. You seem to expect it to be the other way round (honestly, I'd intuitively also expect that, but that was just a design desicion --the map key forces uniqueness and option labels should in UI perspective definitely be unique, but option values does not necessarily need to be unique).
So, this should do (note that I use LinkedHashMap here as it maintains the insertion order):
map = new LinkedHashMap<String, String>();
map.put("Label 1", "value1");
map.put("Label 2", "value2");
map.put("Label 3", "value3");

with
<f:selectItems value="#{bean.map}" />

If you want so swap the keys and values, then you should be iterating over Map#entrySet(). This works only when your environment supports EL 2.2 as you have to invoke it by a direct method invocation as there's no getter for that.
E.g.
map = new LinkedHashMap<String, String>();
map.put("value1", "Label 1");
map.put("value2", "Label 2");
map.put("value3", "Label 3");

with
<f:selectItems value="#{bean.map.entrySet()}" var="entry"
    itemValue="#{entry.key}" itemLabel="#{entry.value}" />

See also:

*

*Our selectOneMenu wiki page


text:
Q: How to retrieve image width with Jsoup I'm creating a curation plugin for a custom solution.
When a Member gives an url, I retrieve all images, then I give the choice to choose an image from this page.
How could I only offer images which have a minimum width ?
(Considering some img tags doesn't have width or height attributes)
Should  I parse each image ?
Or is there a solution with Jsoup ?

A: The only way to find a image's true size is to retrieve it.  Even if there is a width/height attribute in the HTML, it might not match the actual dimensions of the image.  JSoup has provisions to allow you to get the full URI of an image given the base URL of the page you are parsing.

A: yes,you can store image using ImageIO.read(new BufferedImage(new URL(YOUR URL))) ,extract its size,height,width and store it in a File .
Here comes the JSOUP with File Parse. you can use JSOUP this way!!!
Take a look at ,
http://jsoup.org/cookbook/input/load-document-from-file

A: Using Jsoup we can get only width and height attributes defined for the image tag  which displays the image on the page for the given pixels, but not exact width and height of the image, we can use ImageIO to get the exact width and height of the image as below:
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;

public Main{
    public static void main(String args[]){
        try {
            BufferedImage bimg = ImageIO.read(new URL("https://pictures.dealer.com/w/woodhouseomahaincfordfd/0027/a958ba95df26eaf392e298293da2847ex.jpg"));
            System.out.println(bimg.getWidth()+"==="+bimg.getHeight());
            bimg = ImageIO.read(new URL("https://pictures.dealer.com/ddc/resize/240x/quality/70/sharpen/1/ddc/w/woodhouseomahaincfordfd/0027/a958ba95df26eaf392e298293da2847ex.jpg"));
            System.out.println(bimg.getWidth()+"==="+bimg.getHeight());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

If you want just attributes of an Image, we can use Jsoup api for this, the below code snippet depicts the same:
Elements images = document.select("img[src~=(?i)\\.(png|jpe?g|gif)]");
for (Element image : images)
{
    System.out.println("height : " + image.attr("height"));
    System.out.println("width : " + image.attr("width"));
}


text:
Q: Sending eMail to self using iOS. I have worked with MFMailComposeViewController via messageUIFramework. I have a case where I have to send email to self. How do i add the "from" address MFMailComposeViewController delegate? any suggestions?

A: How to send an email in-APP ?
- (IBAction)sendMail:(id)sender {
    if ([MFMailComposeViewController canSendMail])
    {
        MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];

        mailer.mailComposeDelegate = self;

        [mailer setSubject:@"Message Pro"];

        //Destination adress
        NSArray *toRecipients = [NSArray arrayWithObjects:@"your adress", nil];
        [mailer setToRecipients:toRecipients];

        //Attachement Object
        UIImage *myImage = [UIImage imageNamed:@"image.jpeg"];
        NSData *imageData = UIImagePNGRepresentation(myImage);
        [mailer addAttachmentData:imageData mimeType:@"image/png" fileName:@"mobiletutsImage"];

        //Message Body
        NSString *emailBody = @"message body";
        [mailer setMessageBody:emailBody isHTML:NO];

        [self presentModalViewController:mailer animated:YES];

        [mailer release];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Failure"
                                                        message:@"Your device doesn't support the composer sheet"
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles: nil];
        [alert show];
        [alert release];
    }
}

-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error{
    switch (result)
    {
        case MFMailComposeResultCancelled:
            NSLog(@"Mail cancelled: you cancelled the operation and no email message was queued.");
            break;
        case MFMailComposeResultSaved:
            NSLog(@"Mail saved: you saved the email message in the drafts folder.");
            break;
        case MFMailComposeResultSent:
            NSLog(@"Mail send: the email message is queued in the outbox. It is ready to send.");
            break;
        case MFMailComposeResultFailed:
            NSLog(@"Mail failed: the email message was not saved or queued, possibly due to an error.");
            break;
        default:
            NSLog(@"Mail not sent.");
            break;
    }

    // Remove the mail view
    [self dismissModalViewControllerAnimated:YES];
}

Don't forgot

*

*to add a button with IBAction = sendMail

*to import MessageUI.framework

*add delegate in your .h file MFMailComposeViewControllerDelegate

A: The "from" address is specified for you by the MFMailComposeViewController (and the user can override to be any of their configured mail accounts when they get the compose mail view). You, the programmer, don't have to worry about getting/setting the "from" address.


text:
Q: PostgreSQL, reconfigure existing table, changing primary key to type=serial I have to reconfigure one table with existing data so need advice/example how to do that.
My favourite example table:
DROP TABLE IF EXISTS kalksad1;

CREATE TABLE kalksad1(
kalk_id     int PRIMARY KEY,
brkalk      integer,
brred       integer,
description text
);

INSERT INTO kalksad1 VALUES
(12, 2, 5, 'text index 12 doc 2 row 5'),
(26, 2, 1, 'text index 26 doc 2 row 1'),
(30, 2, 2, 'text index 30 doc 2 row 2'),
(32, 4, 1, 'text index 32 doc 4 row 1'),
(36, 1, 1, 'text index 36 doc 1 row 1'),
(37, 1, 2, 'text index 37 doc 1 row 2'),
(38, 5, 1, 'text index 38 doc 5 row 1'),
(39, 5, 2, 'text index 39 doc 5 row 2'),
(42, 2, 3, 'text index 42 doc 2 row 3'),
(43, 2, 4, 'text index 43 doc 2 row 4'),
(46, 3, 1, 'text index 46 doc 3 row 1'),
(47, 3, 2, 'text index 47 doc 3 row 2');

By simple words I need few steps.
1) Add one new column 'kalk_br' of 'int' type. (I know to do that),
2) Copy contents of all cells 'kalk_id' to 'kalk_br'. (I don't know to do that),
3) Change column type for 'kalk_id' from 'int' to 'serial'. (I don't know to do that since 'kalk_id' is PRIMARY KEY).
EDIT by wildplasser's advice:
4) set the current value for the serial to MAX(kalk_id)
Is this possible to do and how?
If not, please any idea to solve this differently.
EDIT:
This is I came so far:
/*1. rename kalk_id to kalk_br. 2. create a serial column kalk_id. 3. copy contents from kalk_br to kalk_id.*/

ALTER TABLE kalksad1 RENAME COLUMN kalk_id TO kalk_br;
ALTER TABLE kalksad1 ADD COLUMN kalk_id serial;
UPDATE kalksad1 SET kalk_id = kalk_br;

Now remains:
1) Terminate 'kalk_br' to be primary key.
2) Set 'kalk_id' which is now serial to be primary key with highest value updated as current value.

A: CREATE SEQUENCE kalksad1_kalk_id_seq;

ALTER TABLE kalksad1
        ALTER COLUMN kalk_id SET DEFAULT nextval('kalksad1_kalk_id_seq' )
        ;

ALTER SEQUENCE kalksad1_kalk_id_seq OWNED BY kalksad1.kalk_id;

WITH mx AS (SELECT max(kalk_id) AS mx FROM kalksad1)
SELECT setval( 'kalksad1_kalk_id_seq' , mx.mx)
FROM mx
        ;

   -- Test it ...
INSERT INTO kalksad1(brkalk, brred, description) VALUES (42, 666, 'Tralala' );
SELECT * FROM kalksad1;

Result:
NOTICE:  table "kalksad1" does not exist, skipping
DROP TABLE
CREATE TABLE
INSERT 0 12
CREATE SEQUENCE
ALTER TABLE
ALTER SEQUENCE
 setval
--------
     47
(1 row)

INSERT 0 1
 kalk_id | brkalk | brred |        description
---------+--------+-------+---------------------------
      12 |      2 |     5 | text index 12 doc 2 row 5
      26 |      2 |     1 | text index 26 doc 2 row 1
      30 |      2 |     2 | text index 30 doc 2 row 2
      32 |      4 |     1 | text index 32 doc 4 row 1
      36 |      1 |     1 | text index 36 doc 1 row 1
      37 |      1 |     2 | text index 37 doc 1 row 2
      38 |      5 |     1 | text index 38 doc 5 row 1
      39 |      5 |     2 | text index 39 doc 5 row 2
      42 |      2 |     3 | text index 42 doc 2 row 3
      43 |      2 |     4 | text index 43 doc 2 row 4
      46 |      3 |     1 | text index 46 doc 3 row 1
      47 |      3 |     2 | text index 47 doc 3 row 2
      48 |     42 |   666 | Tralala
(13 rows)


text:
Q: Is there a consensus about printable UTF8 characters (to be used for a username)? In my chat app TalkTalkTalk, for usernames, I allowed alphanumeric characters only (A-Z, a-z, 0-9):
username = re.sub(r'\W+', '', username)        # regex to keep alphanumeric only

This is a bit too restrictive because UTF8 characters are useful in many cases (people who have a name with another alphabet than latin, etc.). Now I would like to allow these useful UTF8 characters from other alphabets, and even things like ❤ ☀ ☆ ☂ ☻ ♞ ☯ ☭ ☢. (Why not?)
But I don't want :

*

*all kind of whitespaces, all kind of newlines (
)

*malicious characters that look like empty zero-width char : http://unicode-table.com/fr/200D/

*etc. and more generally every character that could make that userA<malicious_char> looks like real userA.
Which are the printable UTF8 characters? (to be used in a username)
How to filter them with a regex, for example in Python?
Note: This question is about finding a regex to filter them, so it's not a duplicate of some linked questions.

A: You can use flag re.UNICODE and unicode in regex expression, \u200b is not technically defined as whitespace
python 2.7 and 3
import re
username = u'My \u200bNick \u2602 \u263b \u200c '
white_chars = ['\s', u'\u200b',u'\u200c']     #etc
regex_str = '[' + ''.join(white_chars) + ']'
regex = re.compile(regex_str, flags=re.UNICODE)
regex.sub("", username )
print ( regex.sub("", username ) )

you get
u'MyNick\u2602\u263b'
MyNick☂☻


text:
Q: Is Hyper-V Server 2008 working on Intel's Atom platform Did anybody try to install Hyper-V on Intel Atom platform?
Hyper-V requires:

*

*x64 compatible processor with Intel VT or AMD-V technology enabled

*Hardware Data Execution Prevention (DEP)

It seems that both requirements are satisfied with Atom as processor. However, I wonder whether there is some blocking issue (e.g. BIOS that does not support it) since all Atom motherboards I checked had quite old north/south-bridge.
My intentions are to run two low-requirements virtual machines (embedded Linux), so performance should not be an issue.

A: Plenty of people have tried VMWare ESXi on Atom, and have come to the conclusion that it works if you get the right motherboard, but performance is absolutely awful.
I can't see this being different for Hyper-V. You're going to be able to buy a cheap AMD Opteron system with virtualization built-in and fully supported by Hyper-V for as little as an Atom system is going to cost you, I'd recommend going down that route.

A: just to let you know that I have just installed Windows 2008 R2 (64 bits) on my newly purchased Intel motherboard (ITX Atom D510MO) and that the HyPer-V feature refuses to install, stating it is not supported by the CPU.
Voila, we now have an answer for sure :-)

A: While there's nothing specific in the  system requirements for Hyper-V that contraindicates using Atom processors..
The wikipedia article on Atom processors indicates that only Z520, Z530, Z540 and Z550 "Silverthorne" processors support Intel VT.
I think if it was me doing it, I'd be using ubuntu-server as a host, running KVM, then using that for virtualising the linux guests. (but I'm not sure if that would be much better, as you'd end up doing software virtualisation! :( )

A: The Atom Z520 supports VT and very suitable for KVM.
The VT extension needs to be enabled in the BIOS however. In my Acer A075h there's no BIOS option - so I'm screwed. I can't imagine why they would disable it and leave now way for the user to turn it on.

A: Intel D945GCLF2
Has the atom 330 chip which does NOT support intel-vt.  It does support hyperthreading.
Somewhere at intel's website there is a way to compare atom chips and their features.  This will show you which versions of the Atom include virtualization support.
I am using (or trying to) ESXi with the D945GCLF2 motherboard.  If you are going to try this, you have to try compiling the r8168 driver (on a different system) and installing it in an unsupported configuration.  It didn't work for me.  The alternative, a far, far, better one is that the only PCI slot is consumed by a "supported" ethernet card.
I don't have throughput numbers yet.  I don't expect anything stellar, but will be satisfied if I can watch stutter free video and make use of backups.

A: intel VT support on Z560 , Z550 Z540 Z530 Z520 Below these are not supported.


text:
Q: What happens when we get latest version of the excluded file in TFS? Will that get updated? I have a web.config file excluded in my solution, when i take get latest version, will that get updated and will i have the web config file same as in the server or it doesn't gets updated??

A: It really depends on what you mean by excluded
If your web.config file is not in tfs source control at all (excluded from source control) - then getting latest from source control will not change your file
If your web.config file is in source control, but excluded from your project (excluded from the current open project) - then getting latest from source control may alter the file (this depends on what you got latest on and where the web.config file actually lives). For example if your Web.config file lives in $/MyTFS/Code and the open project is in $/MyTFS/Code/Projects, and you get latest on $/MyTFS/Code/Projects then the web.config file won't be changed.
If your web.config file is in source control, and it's part of the current project, and you have local changes that are excluded in your "Pending Changes" view in Team Explorer (excluded from pending changes) - then when you get latest, if there are changes to web.config, TFS will merge those changes with your version of the file. If there are conflicts, you will have to resolve those conflicts manually (Visual Studio will show a resolve conflicts dialog). At the end of that process the web.config file will still be checked out locally and excluded.


text:
Q: Colour image classification using Stacked Autoencoders I want to use Stacked Autoencoders for colour image classification. The example given on matlab site for image classification of MNIST dataset is only for black and white images which has only one colour channel. But for colour images, it has 3 colour channels, RGB. So what pre processing should i do to the colour images since colour images are matrix in 3 dimensions, for the stacked autoencoders to work. I just need the concept, not specific detailed answer.
URL for matlab example - https://in.mathworks.com/help/nnet/examples/training-a-deep-neural-network-for-digit-classification.html


text:
Q: Leaflet: Popup of polygon and function onMapClick(e) To my leaflet map i've added a function onMapClick(e) to show the current coordinates. At the same time, i've created a polygon with a popup.
If i click on the polygon, the current coordinates occur instead of the polygon's popup window. It seems like the function overwrites the polygon popup window.
Do you have an idea, how i can solve this problem?
Thank you so much!
See my code fragments below:

// popup with coordinates

   var popup = L.popup();

   function onMapClick(e) {
      popup
          .setLatLng(e.latlng)
          .setContent("Koordinaten (WGS-84): " + e.latlng.lng.toFixed(8) + " E, " + e.latlng.lat.toFixed(8) + " N")
          .openOn(map)
   }

   map.on('click', onMapClick);

// polygon

            var POI_Alte_Baeckerei = L.polygon([
    [46.97482843, 7.43818506],
    [46.97484775, 7.43860268],
    [46.97469802, 7.43860976],
    [46.97464490, 7.43903446],
    [46.97456279, 7.43902031],
    [46.97455313, 7.43825584]
    ]).addTo(map).bindPopup('Alte Bäckerei');

   var activated_on_map_detail = L.layerGroup([map_detail, POI_Alte_Baeckerei]);

   map.on('zoomend', function () {
     if (map.getZoom() >= 17.6 && map.hasLayer(activated_on_map_detail)==false) {
       map.addLayer(activated_on_map_detail);
     }
     if (map.getZoom() < 17.6 && map.hasLayer(activated_on_map_detail)) {
       map.removeLayer(activated_on_map_detail);
     }
   });


text:
Q: Suppose that $a_n = a_0r^n$. This is a geometric sequence, since $a_{n+1}/a_n = r$ is independent of n. Suppose that $a_n = a_0r^n$. This is a geometric sequence, since $a_{n+1}/a_n = r$ is independent of n.
a) Give the generating function $A(X) = \sum_{n}a_nX^n$
b) Give the generating function $B(X) = \sum_{n}b_nX^n$ with $b_n = \sum_{k=0}^n a_k$
c) Calculate $[X^n]B(X)$, and thus give a formula for the sum of a finite geometric sequence.
For Part a) what I thought to do from my notes was
$A(X) + A(−X) = (a_0 + a_1X + a_2X^2 + a_3X^3 +...) +(a_0 + a_1(−X) + a_2(−X)^2 + a_3(−X)^3 +...) $
$= (a_0 + a_1X + a_2X^2 + a_3X^3 +...) + (a_0 − a_1X + a_2X^2 − a_3X^3 +...)$
$= (2a_0 + a_2X^2 + a_4X^4 +...) $
Which gives the generating function for the even terms and you can use it to get the odd terms with a small change. Im not sure if this is right however.


text:
Q: Text output starts with new line before every comma appearance I want to get the output in such a way that new line should start before every comma after tab indent.
Desired output:
function (formula
    , data
    , subset)

from function (formula, data, subset). My MWE is
Txt <- "function (formula, data, subset)"
gsub(pattern=",", replacement=",\n\tab", x=Txt)

A: Your regular expression pattern is almost correct, you just need the magical incantation for a tab stop, which is \t.
Try this:
cat(gsub(pattern=",", replacement="\n\t,", x=Txt))

function (formula
    , data
    , subset)

A: This gives much close to required output
cat(gsub(pattern=",", replacement="\n\t,", x=formatR:::usage(lm)))

lm(formula, data, subset, weights, na.action, method = "qr", model = TRUE,
    x = FALSE, y = FALSE, qr = TRUE, singular.ok = TRUE, contrasts = NULL,
    offset, ...)
lm(formula
    , data
    , subset
    , weights
    , na.action
    , method = "qr"
    , model = TRUE
    ,
    x = FALSE
    , y = FALSE
    , qr = TRUE
    , singular.ok = TRUE
    , contrasts = NULL
    ,
    offset
    , ...)


text:
Q: Laravel coloca argumento em fonte? há como tirar?

fonts/vendor/materialize-css/dist/roboto/Roboto-Medium.woff2?1561b424aaef2f704bbd89155b3ce514  65.4 kB          [emitted]

   fonts/vendor/materialize-css/dist/roboto/Roboto-Thin.woff2?1f35e6a11d27d2e10d28946d42332dc5  63.1 kB          [emitted]

  fonts/vendor/materialize-css/dist/roboto/Roboto-Light.woff2?3c37aa69cd77e6a53a067170fa8fe2e9  64.3 kB          [emitted]
   fonts/vendor/materialize-css/dist/roboto/Roboto-Light.woff?ea36cd9a0e9eee97012a67b8a4570d7b  89.7 kB          [emitted]
fonts/vendor/materialize-css/dist/roboto/Roboto-Regular.woff2?5136cbe62a63604402f2fedb97f246f8  64.8 kB          [emitted]
 fonts/vendor/materialize-css/dist/roboto/Roboto-Regular.woff?3cf6adf61054c328b1b0ddcd8f9ce24d  89.8 kB          [emitted]
    fonts/vendor/materialize-css/dist/roboto/Roboto-Thin.woff?44b78f142603eb69f593ed4002ed7a4a  88.1 kB          [emitted]
  fonts/vendor/materialize-css/dist/roboto/Roboto-Medium.woff?cf4d60bc0b1d4b2314085919a00e1724  90.6 kB          [emitted]
   fonts/vendor/materialize-css/dist/roboto/Roboto-Bold.woff2?c0f1e4a4fdfb8048c72e86aadb2a247d  64.8 kB          [emitted]
    fonts/vendor/materialize-css/dist/roboto/Roboto-Bold.woff?eed9aab5449cc9c8430d7d258108f602  90.3 kB          [emitted]
                                                                                \js\app.js  1.63 MB       0  [emitted]  [big]  \js\app
                                                                                \css\app.css   210 kB       0  [emitted]         \js\app
a

Laravel Inclui um argumento ao acessar as fontes, o problema é que estas fontes estão resultando em erro usando o cache do html 5, alguem sabe como remover este argumento? para que serve? e como posso resolver o conflito no html5 cache caso não tenha como tirar ou seja importante?


text:
Q: Change background color of iframe with external href src? Is it possible to load an external href src inside your iframe and then override the bg color of the external href src? Here's what I've tried:
<iframe src="https://www.externaldomain.com" style="background-color: #FFF !important;"></iframe>

A: You can try with an event with javascript or jquery. Something like this:
function changeBackground(color) {
   document.body.style.background = color;
}

<BODY onload="changeBackground('red');">

change background color