text:
Q: Using the ccwc() function for risk set sampling WITHOUT replacement Does anyone know if it is possible to use the ccwc() function from the Epi package (risk set sampling) without replacement? If so, how is this specified? I have not been able to find anything about this in the documentation. See reproducible example below for how the function works:
library(lubridate)
library(dplyr)
library(tidyverse)
library(Epi)
library(survival)

### Create data frame:
Person_IDs <- seq(1,10000,1)
Example_DF <- as.data.frame(Person_IDs)
Example_DF$Start_Date <- as.Date("2020-01-01")
Example_DF$Exposure_Date <- as.Date("2020-01-01") + days(sample (c(45:365), size=10000, replace =T))
Example_DF$End_Date <- as.Date("2021-05-01")
Example_DF$Sex <- sample(c("Male", "Female"), size = 10000, replace = T)
Example_DF$Age <- sample(c(1:100), size = 10000, replace = T)
Example_DF$Fail <- sample(c(0,1), size = 10000, replace = TRUE, prob = c(0.9, 0.1))

### Show first rows of data frame:
head(Example_DF)

## Set seed for the random number generator
set.seed(20140111)
## Generate a nested case-control study
Risk_Set_Sampling_With_Replacement <- ccwc(entry    = Start_Date,    # Time of entry to follow-up
               exit     = Exposure_Date,    # Time of exit from follow-up
               fail     = Fail,    # Status on exit (1 = Fail, 0 = Censored)
               origin   = Start_Date,    # Origin of analysis time scale
               controls = 5,      # The number of controls to be selected for each case
               data     = Example_DF,   # data frame
               include = Person_IDs,
               match    = list(Age, Sex),    # List of categorical variables on which to match cases and controls
               silent   = TRUE
)
## Show how many times each person_ID is included as case and controls, respectively:
Risk_Set_Sampling_With_Replacement[Risk_Set_Sampling_With_Replacement$Fail == 1,] %>% group_by(Person_IDs) %>% tally(sort = TRUE)
## Only one for each person, which is supposed to be the case (can not be selected as case >1 time)

Risk_Set_Sampling_With_Replacement[Risk_Set_Sampling_With_Replacement$Fail == 0,] %>% group_by(Person_IDs) %>% tally(sort = TRUE)
## Many person IDs selected more than once, which is supposed to be the case if sampling with replacement is desired. I do however want sampling without replacement.


text:
Q: Annotating vertical lines below the x-axis with pyplot With matplotlib, I am trying to annotate vertical lines that I have drawn on a plot of sequential data. With the line
plt.annotate('%.2f' % 2.34, xy=(0,0), xytext=(0,-20), xycoords='axes fraction', textcoords='offset points',color='r')

I am able to get text to show up below my plot. However, I have vertical lines plotted -- say, at intervals of 240 -- and I would like to specifically annotate each of these lines below the x-axis.
I tried switching the xycoords format to 'data' and then using xy=(240,0), but when I switch the xycoords format to 'data' the annotation text ceases to appear on my plot.
I also tried calculating the fraction where I wanted to place my annotation (e.g. 240/length of plot), but this still did not place it correctly.
Why does the annotation command stop adding text to my plot when I change the coordinate system to 'data' instead of 'axis fraction'? Thanks!

A: It's difficult to say what is the exact problem without a workable example. In any case as solution to your problem I would advise you to duplicate your axis (in the same figure) and just use the second one to control the accessory stuff.
Here is a working solution:
import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny()

# Add some extra space for the second axis at the bottom
fig.subplots_adjust(bottom=0.2)
ax1.set_xticks(range(-100, 100, 10))
ax1.set_xlim(-100, 100)
ax1.set_xticklabels([str(i) for i in range(-100, 100, 10)], rotation=45)

ax2.spines["bottom"].set_position(("axes", -0.1))
ax2.xaxis.set_ticks_position("bottom")
ax2.spines["bottom"].set_visible(True)
ax2.set_xticks([-50,50])
ax2.set_xticklabels(['Line 1', 'Line 2'], rotation=45, color='blue')
ax2.set_xlim(-100, 100)

b1 = np.random.randint(0,100,6)
b2 = np.random.randint(0,100,6)
b3 = np.random.randint(0,100,6)
ax1.scatter(np.random.normal(0, 1, 100)*100, np.random.normal(0, 1, 100)*100, c='green', s=90)
ax1.axvline(-50)
ax1.axvline(50)

plt.show()

, which results in this:

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to change panel-body background-color in bootstrap? I am creating a webpage using twitter bootstrap, here i wanna change panel-body background-color form white to light-pink, but i haven't any idea that how it will be done? So ..... help me
Thank You

A: The CSS being as follows (as an example) should work fine. If not then you'll need to show your code.
.panel-body {
background:#FFCCFF;}


text:
Q: Create tree table from JSON object using jQuery I have following data structure coming as a JSON object from server side
var data = {
    "name": "preprodwizard",
    "cSVServers": [{
        "name": "preprodwizard_80_csvs",
        "status": "UP",
        "ipAddress": "162.115.34.53",
        "port": "80",
        "protocol": "HTTP",
        "lBVServers": [{
            "name": "preprodwizard_static_lbvs",
            "status": "UP",
            "ipAddress": "0.0.0.0",
            "port": "0",
            "protocol": "HTTP",
            "serviceGroups": [{
                "name": "preprodwizard_static_30443_sg",
                "status": "--",
                "ipAddress": "--",
                "port": "--",
                "protocol": "--",
                "servers": [{
                    "name": "--",
                    "status": "UP",
                    "ipAddress": "10.255.48.28",
                    "port": "30443",
                    "protocol": "--"
                }, {
                    "name": "--",
                    "status": "UP",
                    "ipAddress": "10.255.48.37",
                    "port": "30443",
                    "protocol": "--"
                }]
            }]
        }]
    }, {
        "name": "preprodwizard_443_csvs",
        "status": "UP",
        "ipAddress": "162.115.34.53",
        "port": "443",
        "protocol": "SSL",
        "lBVServers": [{
            "name": "preprodwizard_static_lbvs",
            "status": "UP",
            "ipAddress": "0.0.0.0",
            "port": "0",
            "protocol": "HTTP",
            "serviceGroups": [{
                "name": "preprodwizard_static_30443_sg",
                "status": "--",
                "ipAddress": "--",
                "port": "--",
                "protocol": "--",
                "servers": [{
                    "name": "--",
                    "status": "UP",
                    "ipAddress": "10.255.48.28",
                    "port": "30443",
                    "protocol": "--"
                }, {
                    "name": "--",
                    "status": "UP",
                    "ipAddress": "10.255.48.37",
                    "port": "30443",
                    "protocol": "--"
                }]
            }]
        }, {
            "name": "preprodwizard_web_lbvs",
            "status": "UP",
            "ipAddress": "0.0.0.0",
            "port": "0",
            "protocol": "HTTP",
            "serviceGroups": [{
                "name": "preprodwizard_web_28443_sg",
                "status": "--",
                "ipAddress": "--",
                "port": "--",
                "protocol": "--",
                "servers": [{
                    "name": "--",
                    "status": "UP",
                    "ipAddress": "10.255.48.28",
                    "port": "28443",
                    "protocol": "--"
                }, {
                    "name": "--",
                    "status": "UP",
                    "ipAddress": "10.255.48.37",
                    "port": "28443",
                    "protocol": "--"
                }]
            }]
        }]
    }]
};

Now I want to create a Tree table structure out of this JSON object. e.g.
There would be multiple csvServers, each csvServer will have some properties like name / status / ipAddress / Port / Protocol which will be in one row
Now each csvServer will have IBVServers, each IBVServer will have ServiceGroups and each ServiceGroups will have Servers.
How can I create this tree table http://wwwendt.de/tech/dynatree/doc/samples.html for above data structure.

A: The dynatree you mention does not seem to have tree table capabilities.
I have can propose a solution using jsTreeTable.
    function normalize(data, hirarchy) {
        var hirarchy = hirarchy.slice(0)
        var nextLevel = hirarchy.shift()
        $.each(data, function(i, d) {
            d['children'] = d[nextLevel]
            if (hirarchy.length > 0) {
                normalize(d[nextLevel], hirarchy)
            }
        })
    }
    normalize(data.cSVServers, [ 'lBVServers', 'serviceGroups', 'servers' ])

    com_github_culmat_jsTreeTable.register(this)
    var options = {
        idAttr : 'name',
        slider : true,
        renderedAttr : {
            name : 'Name',
            status : 'Status',
            ipAddress : 'IP',
            port : 'Port',
            protocol : 'Protocol'
        },
        initialExpandLevel : 4
    }
    appendTreetable(data.cSVServers, options)

*

*Demo

*Fiddle with the demo


text:
Q: Get Image dimension on click in Android using open cv and java? I am new in android development and I have to make a module for android app which automatically detects the exact dimensions of an object being photographed by the user's camera.
I have stumbled upon many examples and the best one is:
http://www.pyimagesearch.com/2016/03/28/measuring-size-of-objects-in-an-image-with-opencv/
I have read this complete post. But I think there must be also a way to get the object's size without a reference object.
could someone suggest any way to achieve this. Or some API which might be providing this capability.

A: Used the pyimagesearch's way of calculating dimensions of the package. Right now this approach works fine for us. But the reference object concept is a bit non-satisfactory. But for now it's the only way I could think of.
please refer to this URL for the python solution to the problem.


text:
Q: Does Absolute Improper Integrability imply Lebesgue Integrability? These is the definition I use:
Definition 1: An improper integral will be an integral of the form:
$$\int_a^b f(x) \, dx $$
Where $f$ is Riemann Integrable, on every finite subinterval, $[s,t] \subseteq (a,b)$. ($a,b$ can be $ \pm \infty$). If for some $c \in (a,b)$, the limits exists, $$ \int_a^b f(x) \, dx := \lim_{s \rightarrow a } \int_s^c f (x) \, dx + \lim _{ t \rightarrow b}
\int_c^t f(x) \, dx . $$
An improper integral is \textit{absolutely convergent} if $\int_a^b |f(x)| \,dx $ converges.

Question: I know if $f$ is Riemann Integrable on $[a,b]$ then (i) it is measurable, and (ii) its integral conincides with the Lesbgue
  Integral. But if $f$ is improperly Riemann Integrable, then is it
  even measurable in the first place?

A: Since $f$ and, hence, $|f|$ is Riemann integrable on $[a + 1/n,b-1/n]$, for every positive integer $n$ the restriction of $|f|$ to any such interval is measurable.
Hence, for every $\alpha \in \mathbb{R}$, the set $E_{\alpha,n}=\{x \in [a+1/n,b-1/n]:|f(x)| > \alpha \}$ is measurable. Consequently, for every $\alpha$ we have measurability of
$$E_\alpha = \{x \in [a,b]:|f(x)| > \alpha \} = \bigcup_{n=1}^\infty E_{\alpha,n} \cup F,$$
since $F$ is either $\phi$, $\{a\}$, $\{b\}$, or $\{a,b\}$ which is a measure-zero measurable set and, hence, $E_\alpha$ is a countable union of measurable sets.
Therfore, $f$ is measurable on $[a,b]$.
Also, the Lebesgue integral of $|f|$ coincides with the improper Riemann integral of $|f|$. For one side (and similarly for the other) we have by the monotone convergence theorem,
$$\int_c^b |f(x)| \, dx = \lim_{t \to b-} \int_c^t |f(x)| \, dx = \lim_{t \to b-} \int_{[c,t]} |f| = \lim_{t \to b-} \int_{[c,b]} |f| \chi_{[c,b]} = \int_{[c,b]}|f|$$
Here I use $\int_c^d g(x) \, dx$ to denote a Riemann integral and $\int_{[c,d]} g$ to denote a Lebesgue integral.
Now, the Lebesgue and improper Riemann integrals of $f$ can be shown equivalent using the dominated convergence theorem.


text:
Q: I don't know why the socket's connecting is increasing in nodeJS with socket.io Each time I access the page(F5 ect..), the number of socket connections increases.
ouput
(1)
re
connect

(2) - F5 or RegetPage after backspace
disconnect
re
connect
connect

(3)
re
disconnect
disconnect
connect
connect
connect

It seems to me that the connection to the socket is not closing, but pausing
My Code
server.js
const app = express();
const server = require("http").createServer(app);
const io = require("socket.io")(server);

app.use((req, res, next) =>{
    req.io = io;
    next();
});

const temp = require("./routes/temp");
app.use("/temp", temp);

temp.js
router.get('/', (req, res) => controller.getPage(req, res, req.io));

function getPage of controller
getPage(req, res, io){
    console.log('re');
    io.on('connection', (socket) => {
      console.log('connect');
      socket.on('disconnect', () => {
        console.log('disconnect');
        socket.disconnect(0);
      });
    });
    //action
  }

I don't know what the problem is.

A: This is happening because you are attaching new connection and disconnect listeners whenever the page is loaded. Those listeners are not per socket so you only need to do it once, not for every page request. So you could move that part to your server.js.


text:
Q: Unable to use TempData more than once even after using TempData.Keep() asp.net core mvc I have an mvc project that will pass a tempdata["username"]  in my middleware. But when debugging my middleware in the if(tempdata.ContainsKey("username"), I noticed that it only enters that if statement once and never enters it again. I read this article that explains how to use TempData and how to keep the data to be able to use it more than once but in my case it does not work. Is there something that I am missing to achieve this?
On my application I have 4 pages, on the home controller it will ask me to enter a username. When I do it then passes the tempdata in the middleware and enters the if statement. When proceeding to the post method and am on a new page it will not hold any value. So basically on the 3rd request tempdata gets deleted. How do I fix this so it can be passed throughout all my pages?
HomeController:
    public IActionResult Index()
    {
        // Gather IP

       var userip = Request.HttpContext.Connection.RemoteIpAddress;

        _logger.LogInformation("IP address of user logged in: {@IP-Address}", userip);

        // Call AddressService API

         var result = _addressServiceClient.SampleAsync().Result;
        _logger.Log(LogLevel.Information, "Home Page...");

        return View();
    }

        [HttpPost]
        public IActionResult AddressValidate(IFormCollection form)
        {
            // if radio button was checked, perform the following var request.

            // username

            username = form["UserName"];
            TempData["username"] = username;
            TempData.Keep("username");

            //HttpContext.Items["username"] = username;

            string status = form["Status"];

            _logger.LogInformation("Current user logged in: {@Username}", username);

            switch (status)
            {
                case "1":
                    _logger.LogInformation("Address entered was valid!");
                    break;
                case "2":
                    _logger.LogError("Address entered was invalid!");
                    ViewBag.Message = string.Format("You did not enter your address correctly! Please enter it again!");
                    return View("Index");
                case "3":
                    _logger.LogError("Invalid Address");
                    throw new Exception("Invalid Address");

            }

            var request = new AddressRequest
            {

                StatusCode = Convert.ToInt32(status),
                Address = "2018 Main St New York City, NY, 10001"
            };

            var result = _addressServiceClient.ValidateAddress(request).Result;

            return RedirectToAction("SecIndex", "Second");
        }

middleware:
    public class CorrelationIdMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger _logger;
        private readonly ITempDataDictionaryFactory _tempDataDictionaryFactory;
        public CorrelationIdMiddleware(RequestDelegate next, ILoggerFactory loggerFactory, ITempDataDictionaryFactory tempDataDictionaryFactory)
        {
            _next = next;
            _logger = loggerFactory.CreateLogger<CorrelationIdMiddleware>();
            _tempDataDictionaryFactory = tempDataDictionaryFactory;
        }

        public async Task Invoke(HttpContext context)
        {
            string correlationId = null;
            string userName;
            var tempData = _tempDataDictionaryFactory.GetTempData(context);

            var key = context.Request.Headers.Keys.FirstOrDefault(n => n.ToLower().Equals("x-correlation-id"));
            if (!string.IsNullOrWhiteSpace(key))
            {
                correlationId = context.Request.Headers[key];
                _logger.LogInformation("Header contained CorrelationId: {@CorrelationId}", correlationId);
            }
            else
            {
                if (tempData.ContainsKey("username"))
                {
                    userName = tempData["username"].ToString();
                    context.Response.Headers.Append("X-username", userName);
                }

                correlationId = Guid.NewGuid().ToString();
                _logger.LogInformation("Generated new CorrelationId: {@CorrelationId}", correlationId);
            }
            context.Response.Headers.Append("x-correlation-id", correlationId);
            using (LogContext.PushProperty("CorrelationId", correlationId))
            {
                await _next.Invoke(context);
            }
        }
    }

A: You can use Peek when you always want to retain the value for another request. Use Keep when retaining the value depends on additional logic.
In your case you have to use Peek. Instead of var val= TempData["username"] use val = TempData.Peek("username");
When you call val= TempData["username"] , under hood, after returnig data  it
automaticaly calls TempData.Remove("username").


text:
Q: After page refresh react page not working I have create a bundle of react project by npm run build and create a virtual host file which is pointing to build folder, the application is working fine with different route, but when I page refresh other then root route then page not working.
This image is without page Load:
https://i.stack.imgur.com/EnBOU.png
But after page load it giving me this error.
https://i.stack.imgur.com/GooRM.png

A: Hi Please make base href on build index.html file inside head tag like this.
<base href="/reactapp/" /> // your root folder path

and add a .htaccess file in the root, paste below code inside the .htaccess.
<IfModule mod_rewrite.c>
    RewriteEngine on

    # Don't rewrite files or directories
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^ - [L]

    # Rewrite everything else to index.html
    # to allow html5 state links
    RewriteRule ^ index.html [L]
</IfModule>

I hope it's useful for you.
Thanks


text:
Q: Google cloud Backend service is unhealthy - 502 error I believe I have a pretty straight forward set up but I am receiving the dreaded "backend service is unhealthy" notification on my load balancer in google cloud. I will list out steps I have taken so far to provide as much info as possible as I know this could be many things.

*

*I created a VM in compute engine hosting wordpress

*I created an unmanaged instance group linked to that VM

*I created a load balancer (HTTPS),

*I created a HTTP backend service linking to my instance group

*I created a health check, protocol HTTP, port 80, left everything else as default

*I created a new front end HTTP, port 80, premium, reserved a new static IP address

*I pointed my domain at the new load balancer

It's worth mentioning at this point I tested I could access the web page stored on the VM without any issues.

*

*I then created a HTTPS front end, protocol HTTPS, port 443, premium

*I set the value of the IP to be the same as the value of the static IP I reserved when creating the HTTP front end.

*I created a new google cloud managed certificate, which was provisioned successfully

At this point I tested again and could no longer access the site and I received the 502 error on the web page.

*

*I created two firewall rules both set to ingress, allow-health-checks, 130.211.0.0/22
35.191.0.0/16. the only difference between the two is one is set to tcp 80 and one is set to tcp 443, I was just trying to cover off both in case. I also did try one without the other but that made no difference.

Now I am pretty stuck as I am not seeing any other potential steps I could take to resolve this issue.
I would be grateful for any potential solutions.
Cheers

A: I managed to overcome this issue by following this guide. https://www.jiyuulife.net/google-cloud-cdn-for-gcp-wordpress/ In case anyone has similar issues.
There isn't a lot of good material out there for unmanaged IG's linked to existing VM's. I found even googles documentation to be a little light on the subject. Sometimes you do want to provide load balancing to existing VM's to make use of CDN without the redundancy or expense.
I welcome additional contributions here.


text:
Q: How to avoid unnecessary updates when using on conflict with Postgres? My use case involves syncing a table with an upstream source on a recurring schedule.
Each row has a unique identifier and other columns, and I want to make sure I'm inserting any new upstream rows, and updating any changed upstream rows. And there could be thousands of rows to sync.
But I'd like to avoid unnecessary updates where the row in the database doesn't differ from what's upstream.
Currently I'm using ON CONFLICT UPDATE like so:
INSERT INTO symbols (id, name, status)
VALUES
  (1, 'one', 'online'),
  (2, 'two', 'offline'),
  ...
ON CONFLICT (id)
UPDATE SET (id, name, status) = (excluded.id, excluded.name, excluded.status)
RETURNING *

But this will write the updates even when nothing is changing. How should I tweak the UPDATE to performantly check and apply to rows that need it?

A: You can add a where clause to only update those rows that are different.
INSERT INTO symbols (id, name, status)
VALUES
  (1, 'one', 'online'),
  (2, 'two', 'offline'),
  ...
ON CONFLICT (id) DO
UPDATE SET (id, name, status) = (excluded.id, excluded.name, excluded.status)
WHERE (symbols.id, symbols.name, symbols.status) IS DISTINCT FROM (excluded.id, excluded.name, excluded.status)
RETURNING *

However, this will only return the rows that are actually updated, which may impact how you use the returning clause.


text:
Q: Mageto 2 : getUrl returns true even the page is set to disabled I created a page testPage and use $pageExist = $this->getUrl('testPage') ?> so i could render an a block if it exist like so if ($pageExist)
BUT when i go from amdin panel and set page from enabled to disabled, clear cache, the $pageExist is till true, or what i assume, since if statement is getting fired even tho you can not enter that URL

A: getUrl() is just a return address Magento understands no matter the particular page exists or not. you should debug how magento redirects to 404 when no page found.
Check File : \Magento\Framework\App\FrontController
 public function dispatch(RequestInterface $request)
    {
        \Magento\Framework\Profiler::start('routers_match');
        $this->validatedRequest = false;
        $routingCycleCounter = 0;
        $result = null;
        while (!$request->isDispatched() && $routingCycleCounter++ < 100) {
            /** @var \Magento\Framework\App\RouterInterface $router */
            foreach ($this->_routerList as $router) {
                try {
                    $actionInstance = $router->match($request);
                    if ($actionInstance) {
                        $result = $this->processRequest(
                            $request,
                            $actionInstance
                        );
                        break;
                    }
                } catch (\Magento\Framework\Exception\NotFoundException $e) {
                    $request->initForward();
                    $request->setActionName('noroute');
                    $request->setDispatched(false);
                    break;
                }
            }
        }
        \Magento\Framework\Profiler::stop('routers_match');
        if ($routingCycleCounter > 100) {
            throw new \LogicException('Front controller reached 100 router match iterations');
        }
        return $result;
    }


text:
Q: Update Value on Vuetify Slider What I'm trying todo is update the value when the slider position has moved.
[codepen]https://codepen.io/JakeHenshall/pen/WLezNg

   <v-app id="inspire">
<v-card flat color="transparent">

  <v-subheader>Tick labels</v-subheader>

     {{ ticksLabels[0] }}

    {{ ticksLabels[1] }}

    {{ ticksLabels[2] }}

    {{ ticksLabels[3] }}

    {{ ticksLabels[4] }}

  <v-card-text>
    <v-slider
      v-model="fruits"
      :tick-labels="ticksLabels"
      :max="4"
      step="1"
      ticks="always"
      tick-size="2"
    ></v-slider>
  </v-card-text>
</v-card>

Javascript:
new Vue({
    el: '#app',
    data () {
      return {
        value: 0,
        ticksLabels: [
          '0 - £5k',
          '£5k - £10k',
          '£10k - £25k',
          '£25k - £50k',
          '£50k+'
        ]
      }
    }
  })

Any help with this would be great and some info on how to tidy up the if statement would be great.
Thanks.

A: You don't need your if clause at all. To get the index of your selected item, use v-model="value" (as you already do, just 'fruits' is probably wrong) and replace your if clause with this tiny piece of code:

  {{ticksLabels[value]}}

I've updated your fiddle here

A: There are a couple of things you got to do,

*

*The fruits that you are using as v-model on your v-slider has no reference whatsoever, meaning its not declared anywhere. So ensure to use a model that is declared, value has been declared but never used, so you could use that has your model.

*Use the model both on the slider and the text value which represents the
position of the slider that way you can eliminate all the ifs.

Such as this
<v-text-field v-model="ticksLabels[value]"
              class="mt-0"
              type="text"></v-text-field>

<v-card-text>
  <v-slider v-model="value"
            :tick-labels="ticksLabels"
            :max="4"
            step="1"
            ticks="always"
            tick-size="2"></v-slider>

Here is your updated codepen https://codepen.io/jayas/pen/QzLrZd


text:
Q: Can't use 'three.js' library remotely I'd like to use three.js library that's located online, and I've included a path to three.js file into my <script> tag inside index.html. But my script doesn't work because there's no access to three.js library.
<script src="https://threejs.org/build/three.js"></script>

Is it possible to use three.js library remotely?

A: Try this way:
<script src="https://threejs.org/build/three.js" crossorigin="anonymous"></script>

It is working in my project.
If it still wont working, try to find here, how to install this: Instalation Three.js


text:
Q: MySql - Case Sensitive issue of tables in different server I am working in three different servers which are unix/windows/unix.
case-1: In my loacl server which is unix I have one table name Country_master and its fields pk_CountryId, CountryName etc.
case-2:In my Demo server which is window table name changed automatically to country_master.
case-3:In my Live server which is unix table name country_master.
But in my code table name i taken is Country_master so it gives me error like this
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S02]: Base table or view not found: 1146 Table 'markets.Country_master' doesn't exist'.

Can i have any way not to change table name in database and also in code but it takes lower case?

A: You can change the case sensitivity by setting the lower_case_table_names system variable. See here for instructions:
http://dev.mysql.com/doc/refman/5.6/en/identifier-case-sensitivity.html

A: From the fine manual:

In MySQL, databases correspond to directories within the data directory. Each table within a database corresponds to at least one file within the database directory (and possibly more, depending on the storage engine). Triggers also correspond to files. Consequently, the case sensitivity of the underlying operating system plays a part in the case sensitivity of database, table, and trigger names.

So the case sensitivity of your table names depends on the underlying file system: they will (usually) be case insensitive on Windows and OSX but case sensitive on Linux. This behavior is partially dependent on the lower_case_table_names setting:

If set to 0, table names are stored as specified and comparisons are case sensitive. If set to 1, table names are stored in lowercase on disk and comparisons are not case sensitive. If set to 2, table names are stored as given but compared in lowercase. This option also applies to database names and table aliases.

So you have various things that will affect the case sensitivity of your table names. The only sane solution (IMO) is to always use lower case table names so that you don't have to worry about it; you should also use lower case column names for consistency.

A: http://dev.mysql.com/doc/refman/5.0/en/identifier-case-sensitivity.html

9.2.2. Identifier Case Sensitivity In MySQL, databases correspond to directories within the data directory. Each table within a database
  corresponds to at least one file within the database directory (and
  possibly more, depending on the storage engine). Consequently, the
  case sensitivity of the underlying operating system plays a part in
  the case sensitivity of database and table names. This means database
  and table names are not case sensitive in Windows, and case sensitive
  in most varieties of Unix. One notable exception is Mac OS X, which is
  Unix-based but uses a default file system type (HFS+) that is not case
  sensitive. However, Mac OS X also supports UFS volumes, which are case
  sensitive just as on any Unix. See Section 1.8.4, "MySQL Extensions to
  Standard SQL". The lower_case_table_names system variable also affects
  how the server handles identifier case sensitivity, as described later
  in this section.
Note Although database and table names are not case sensitive on some
  platforms, you should not refer to a given database or table using
  different cases within the same statement. The following statement
  would not work because it refers to a table both as my_table and as
  MY_TABLE:
mysql> SELECT * FROM my_table WHERE MY_TABLE.col=1; Column, index, and
  stored routine names are not case sensitive on any platform, nor are
  column aliases. Trigger names are case sensitive, which differs from
  standard SQL.
By default, table aliases are case sensitive on Unix, but not so on
  Windows or Mac OS X. The following statement would not work on Unix,
  because it refers to the alias both as a and as A:
mysql> SELECT col_name FROM tbl_name AS a
      -> WHERE a.col_name = 1 OR A.col_name = 2; However, this same statement is permitted on Windows. To avoid problems caused by such
  differences, it is best to adopt a consistent convention, such as
  always creating and referring to databases and tables using lowercase
  names. This convention is recommended for maximum portability and ease
  of use.
How table and database names are stored on disk and used in MySQL is
  affected by the lower_case_table_names system variable, which you can
  set when starting mysqld. lower_case_table_names can take the values
  shown in the following table. On Unix, the default value of
  lower_case_table_names is 0. On Windows the default value is 1. On Mac
  OS X, the default value is 2.
Value Meaning 0   Table and database names are stored on disk using the
  lettercase specified in the CREATE TABLE or CREATE DATABASE statement.
  Name comparisons are case sensitive. You should not set this variable
  to 0 if you are running MySQL on a system that has case-insensitive
  file names (such as Windows or Mac OS X). If you force this variable
  to 0 with --lower-case-table-names=0 on a case-insensitive file system
  and access MyISAM tablenames using different lettercases, index
  corruption may result. 1  Table names are stored in lowercase on disk
  and name comparisons are not case sensitive. MySQL converts all table
  names to lowercase on storage and lookup. This behavior also applies
  to database names and table aliases. 2    Table and database names are
  stored on disk using the lettercase specified in the CREATE TABLE or
  CREATE DATABASE statement, but MySQL converts them to lowercase on
  lookup. Name comparisons are not case sensitive. This works only on
  file systems that are not case sensitive! InnoDB table names are
  stored in lowercase, as for lower_case_table_names=1. If you are using
  MySQL on only one platform, you do not normally have to change the
  lower_case_table_names variable from its default value. However, you
  may encounter difficulties if you want to transfer tables between
  platforms that differ in file system case sensitivity. For example, on
  Unix, you can have two different tables named my_table and MY_TABLE,
  but on Windows these two names are considered identical. To avoid data
  transfer problems arising from lettercase of database or table names,
  you have two options:
Use lower_case_table_names=1 on all systems. The main disadvantage
  with this is that when you use SHOW TABLES or SHOW DATABASES, you do
  not see the names in their original lettercase.
Use lower_case_table_names=0 on Unix and lower_case_table_names=2 on
  Windows. This preserves the lettercase of database and table names.
  The disadvantage of this is that you must ensure that your statements
  always refer to your database and table names with the correct
  lettercase on Windows. If you transfer your statements to Unix, where
  lettercase is significant, they do not work if the lettercase is
  incorrect.
Exception: If you are using InnoDB tables and you are trying to avoid
  these data transfer problems, you should set lower_case_table_names to
  1 on all platforms to force names to be converted to lowercase.
If you plan to set the lower_case_table_names system variable to 1 on
  Unix, you must first convert your old database and table names to
  lowercase before stopping mysqld and restarting it with the new
  variable setting. To do this for an individual table, use RENAME
  TABLE:
RENAME TABLE T1 TO t1; To convert one or more entire databases, dump
  them before setting lower_case_table_names, then drop the databases,
  and reload them after setting lower_case_table_names:
Use mysqldump to dump each database:
mysqldump --databases db1 > db1.sql mysqldump --databases db2 >
  db2.sql ... Do this for each database that must be recreated.
Use DROP DATABASE to drop each database.
Stop the server, set lower_case_table_names, and restart the server.
Reload the dump file for each database. Because lower_case_table_names
  is set, each database and table name will be converted to lowercase as
  it is recreated:
mysql < db1.sql mysql < db2.sql ... Object names may be considered
  duplicates if their uppercase forms are equal according to a binary
  collation. That is true for names of cursors, conditions, procedures,
  functions, savepoints, stored routine parameters and stored program
  local variables. It is not true for names of names of columns,
  constraints, databases, statements prepared with PREPARE, tables,
  triggers, users, and user-defined variables.

A: If you are using MySQL you can set table and column name case sensitive in my.conf by using following directive
set-variable = lower_case_table_names=1

Do not forget the restart server after update. It would be better if you use same column names in all servers


text:
Q: Assigning new observations to K-Means clusters with Cosine Similarity I have a set of 4 million feature vectors that I have clustered using K-Means, generating 21 clusters with relatively good inertia scores. Let's assume the centroid values and corresponding labels are stored in DataFrame.
Each vector (and centroid) is a 50-position numpy array:
[ -3.92581884  14.4241874 ... -3.13031101   2.30989949]
Next, I need to classify a new, 50-position vector into one of the existing clusters. My current solution to achieve this is based on a 1K-NN classifier that works by computing the cosine similarity between the new vector and any of the 21 existing centroids. Something like this, as suggested on this thread's accepted answer:
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
import pandas as pd

# Simulate new entry
feature = np.random.rand(1,50)

# Pairwise cosine similarity
centroid_df['Similarity'] = cosine_similarity(centroid_df['Centroid'].tolist(), feature)

# Order dataframe by similarity
ordered_df = centroid_df.sort_values(by=['Similarity'], ascending=[0])

# Get first element label (highest similarity)
cluster = int(ordered_df['Label'].iloc[0])

The example above works to an extent. It gives me a new label which corresponds to one of the 21 existing clusters. However, I then tried to evaluate its performance on random, pre-classified samples. For this, I collected 1000 feature vectors for which I know the correct label and tried classifying them with the proposed approach. This method only managed to match the 'real' label 799 out of 1000 times. I would have expected much higher accuracy.
Could the dissapointing results be associated with using cosine_similarity to classify labels? If so, what is a more sensible approach to classifying new observations? Or could my issue stem from an underlying problem, such as the centroid values themselves?


text:
Q: Object or function in module pattern OO JS? Recently started writing modularised js and I'm starting to notice the numerous ways one can write them.
I know the core principles of when to use an object literal or function but whats the beneficiaries of writing a module as an object literal or function on a larger scale development? Portability, flexibilty, maintainability?
var filterOverlays = { ..code .. };

var filterOverlays = function() { ..code ..}

Call in another page:
$(document).ready(filterOverlays.init);

filterOverlays();

A: It might worth reading about Javascript AMD leaning towards functions. It can provide useful input for your decision.
https://github.com/amdjs/amdjs-api/wiki/AMD
http://requirejs.org/docs/whyamd.html


text:
Q: Laravel - Create dynamically prefixed database tables based on separate table row creation When I create a new "company" in the database, it gets an ID. Upon creation of that company, I want to dynamically create tables prefixed with this ID. For instance:

*

*Company 01 created in table Companies.

*Table 01_data_type created.

*Table 01_other_data_type created.

Step 1 is triggered by form. Steps 2-3 and beyond are triggered by step 1.
The best way I can think to do this inside Laravel is in my store method, upon store, call an artisan command for the migration and pass the ID. Is there a better way to do this?

A: The answer was provided by @Ohgodwhy in comments on question. spawn a job that creates the tables dynamically.


text:
Q: Could Not Load Static (JS/CSS) Files Over Proxy_Pass on SSL I have to docker instances, one where it houses my Wordpress Installation composing of NGINX, PHP7.1 (PHP-FPM), MariaDD and Memcache containers. Those connect to an NGINX container that servers traffic to the outside world.
Everything works find over HTTP. When I switched to HTTPS, I ran into several issues. I've resolves some of them and I am left, I believe, with one issue of not being able to load to JS/CSS files.
Here is my Nginx Configuration on my Wordpress Container
server {
  listen 0.0.0.0:80;
  error_log /var/log/nginx/localhost.error.log;
  access_log /var/log/nginx/localhost.access.log;

  root /app/web;
  index index.php index.html index.htm;

  location / {
    try_files $uri $uri/ /index.php?$args;
  }

  location ~ \.php$ {
    try_files $uri =404;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/var/run/php-fpm.sock;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param SCRIPT_NAME $fastcgi_script_name;
    fastcgi_index index.php;
    include fastcgi_params;
  }
}

Here is my Nginx Config on my Nginx container (The one that does the reverse_proxy)
server {
  listen 443 ssl http2;
  listen [::]:433 ssl http2;
  server_name www.example.com;

  ssl_certificate /etc/nginx/certs/live/www.example.com/fullchain.pem;
  ssl_certificate_key /etc/nginx/certs/live/www.example.com/privkey.pem;
  ssl_dhparam /etc/nginx/ssl/dhparam.pem;
  ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
  ssl_ciphers HIGH:!aNULL:!MD5;

  sendfile off;
  error_log /dev/stdout info;
  access_log /dev/stdout;

  location / {
    proxy_pass http://example-wordpress;
    proxy_redirect off;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Port 443;
    proxy_set_header X-Forwarded-Proto https;
    proxy_set_header X-Real-IP  $remote_addr;

    proxy_set_header   SSL_PROTOCOL $ssl_protocol;
    proxy_set_header   SSL_CLIENT_CERT $ssl_client_cert;
    proxy_set_header   SSL_CLIENT_VERIFY $ssl_client_verify;
    proxy_set_header   SSL_SERVER_S_DN $ssl_client_s_dn;
  }

  location ~* \.(jpg|jpeg|gif|png|css|js|ico|xml)$ {
    expires 5d;
  }

  # deny access to . files, for security
  #
  location ~ /\. {
      log_not_found off;
      deny all;
  }

  location ^~ /.well-known {
    allow all;
    auth_basic off;
  }

}

Here's what I did on my wp-config.php
if (
    (!empty( $_SERVER['HTTP_X_FORWARDED_HOST'])) ||
    (!empty( $_SERVER['HTTP_X_FORWARDED_FOR'])) )
{

  $_SERVER['HTTPS'] = 'on';
}

This configuration manage to fix the redirect loop when I go to the admin side. But it doesn't load the the some css and JS files.

When I inspect the link, it directs me to a 404 page. I spun my local instance in my machine to see if the links were changed in some way. But comparing them, there're the same minus the domain.
https://www.example.com/app/themes/theme-v1.2/build/main.bundle.js?ver=1.0.0
http://www.example.local/app/themes/theme-v1.2/build/main.bundle.js?ver=1.0.0

I've spent a day figuring this out but I don't seem to know what else is there to get this last part done. I hope someone here can help me since it appears to be a nginx issue.
I would also include this link since this helped me solved the redirect issue.
Sumnmary

*

*I am running 2 dockers. One is wordpress one NGINX and a NGINX container that serves serves outbound traffic to the other containers.

*I am using proxy_pass to forward my traffic from www.domain.com to my nginx instance of my wordpress container.

*It works fine on HTTP. When I switch over HTTPS things didn't work.

*I manage to fix the redirect loop on the admin. But static files like JS and CSS fails to load.

A: put this codes in wp-config
define('FORCE_SSL_LOGIN', false);
define('FORCE_SSL_ADMIN', false);
define( 'CONCATENATE_SCRIPTS', false );
define( 'SCRIPT_DEBUG', true );


text:
Q: How to execute results of dbms_output.put_line There is a table contains this kind of data: select to_char(sysdate,'day') from dual in a column. I want to get results of the every query that the table keeps.
My result set should be the result of select to_char(sysdate,'day') from dual query. So in this case it is a tuesday.
SO_SQL_BODY is Varchar2.
I wrote this code but it returns only table data.
CREATE  or replace PROCEDURE a_proc
AS

 CURSOR var_cur IS

select  SO_SQL_BODY FROM SO_SUB_VARS group by SO_SQL_BODY;

var_t  var_cur%ROWTYPE;

   TYPE var_ntt IS TABLE OF var_t%TYPE;

var_names  var_ntt;
BEGIN
OPEN  var_cur;
FETCH var_cur BULK COLLECT INTO var_names;
CLOSE var_cur;

FOR indx IN 1..var_names.COUNT LOOP

   DBMS_OUTPUT.PUT_LINE(var_names(indx).SO_SQL_BODY);

END LOOP;
END a_proc;

A: İf var_names(indx).SO_SQL_BODY output is a runnable sql text;
CREATE  or replace PROCEDURE a_proc
AS

 CURSOR var_cur IS

select  SO_SQL_BODY FROM SO_SUB_VARS group by SO_SQL_BODY;

var_t  var_cur%ROWTYPE;

   TYPE var_ntt IS TABLE OF var_t%TYPE;

var_names  var_ntt;
BEGIN
OPEN  var_cur;
FETCH var_cur BULK COLLECT INTO var_names;
CLOSE var_cur;

FOR indx IN 1..var_names.COUNT LOOP

   DBMS_OUTPUT.PUT_LINE(var_names(indx).SO_SQL_BODY);
   EXECUTE IMMEDIATE var_names(indx).SO_SQL_BODY;
END LOOP;
END a_proc;

A: You don't need a full cursor for this example. An implicit one would make it a lot shorter.
create or replace procedure a_proc is
        lReturnValue varchar2(250);
    begin
        for q in (select so_sql_body from so_sub_vars group by so_sql_body)
        loop

            execute immediate q.so_sql_body into lReturnValue;
            dbms_output.put_line(lReturnValue);

        end loop;
    end a_proc;

You should add an exception handler that will care for cases where there is a  bad SQL query in your table. Also note that executing querys saved in a database table is your entry point to SQL injection.

A: DECLARE
   res varchar2(4000);
   sql_str varchar2(1000);
BEGIN
  FOR r IN
    (select  SO_SQL_BODY FROM SO_SUB_VARS  WHERE SO_SQL_BODY IS NOT NULL
  )
  LOOP
     sql_str := r.SO_SQL_BODY;
     EXECUTE immediate sql_str INTO res;
     dbms_output.put_line(sql_str);
     dbms_output.put_line('***********************');
     dbms_output.put_line(res);
     dbms_output.put_line('***********************');
  END LOOP;
END;
/

Try this - iterate to not null records - execute them and print the result.This script works supposing the fact that SO_SQL_BODY contains a query which projects only one column.Also if the projection is with more than two columns then try to use a refcursor and dbms_sql package


text:
Q: How to run multiple commands in split mode? I needed to run the server and client console in a 'split mode'.
The first attempt was:
w: && cd "w:\client"
npm run client

cmd -new_console:s
w: && cd "w:\server"
npm run server

In this case, only the first command is run.
Then I tried this approach:
start cmd /k w: && cd "w:\client" && npm run client
start cmd -new_console:s /k w: && cd "w:\server" && npm run server

No results at all.
Maybe someone has already faced such a problem?

A: Ok, so I figured out how to run both processes, but not in a split view
cd /d "W:\client"
start npm run client

cd /d "W:\server"
start npm run server

Does any one know how open second process in a split view?


text:
Q: Get how many times each player get max score based on date I want to find how many times each player has max score based on created_at.
In below table.
player_id 1 has two times max score on date 12 and 13.
player_id 2 has one time max score on date 14.
So i want to check it for player_id = 1. how many time this player get max score.
+-----------+-------+-------------+------------+
| player_id | score |   sector    | created_at |
+-----------+-------+-------------+------------+
|         1 |    25 | Midfielder  | 2017-12-12 |
|         2 |    23 | Defender    | 2017-12-12 |
|         3 |    24 | Goalkeeper  | 2017-12-12 |
|         4 |    20 | Midfielder  | 2017-12-12 |
|         1 |    26 | Midfielder  | 2017-12-13 |
|         2 |    20 | Defender    | 2017-12-13 |
|         3 |    19 | Goalkeeper  | 2017-12-13 |
|         4 |    16 | Midfielder  | 2017-12-13 |
|         1 |    18 | Midfielder  | 2017-12-14 |
|         2 |    20 | Defender    | 2017-12-14 |
|         3 |    12 | Goalkeeper  | 2017-12-14 |
+-----------+-------+-------------+------------+

A: You can use the following code,
SELECT PLAYER_ID, COUNT(*) MAX_SCORE_COUNT
FROM
(
  SELECT player_id PLAYER_ID FROM YOUR_TABLE_NAME a
  WHERE a.score = ( SELECT MAX(b.score) FROM YOUR_TABLE_NAME b WHERE b.created_at = a.created_at)
) s
GROUP BY PLAYER_ID

This query return number of times each player got max score based on created_at.
If you want to check it for player_id = 1 then you can use,
SELECT PLAYER_ID, COUNT(*) MAX_SCORE_COUNT
FROM
(
  SELECT player_id PLAYER_ID FROM YOUR_TABLE_NAME a
  WHERE a.score = ( SELECT MAX(b.score) FROM YOUR_TABLE_NAME b WHERE b.created_at = a.created_at)
) s
WHERE PLAYER_ID = 1
GROUP BY PLAYER_ID


text:
Q: User Wise TIME ZONE possible in Linux Red HAT Any possibility to changes user wise time zone in Linux.

A: Which user (a web client, or someone remotely logged thru ssh)? He could set the TZ environment variable, perhaps by adding a line like
export TZ='Europe/Paris'

in his ~/.bashrc file if bash is his login shell.
See environ(7) and tzselect(8)


text:
Q: OpenLayers 3 GeoJSON not loading I am having trouble loading a GeoJSON layer (below is my defintion). Everything works fine when I read the file locally in a web browser, e.g. file:///Z:/inetpub/wwwroot/bang.html. However, when I try to access the site through the domain, e.g www.daverules.com/bang.html, none of my GeoJSON layers show up.
It should also bear mentioning that I have a couple of Leaflet maps that will load GeoJSON with similar URLs without issue.
var wellsLayer = new ol.layer.Vector({
  source: new ol.source.GeoJSON({
    projection: 'EPSG:3857',
    url: "./data/WELLS.geojson"
  }),
  name: 'Wells',
  style: customStyleFunction
});

Response from the server is as follows. It shows file not found, however, I am pretty sure it is there.
GET http://daverules.com/data/WELLS.geojson 404 (Not Found)

A: Hopefully the better I get at this the fewer questions I will answer myself. after doing some research I found the solution here
apparently there was no mimetype for geojson so the server wasn't putting it out there. here are the steps.

*

*Open IIS Manager

*head over to the properties of the IIS  Server and click MIME Types

*add this: extension: geojson     MIME type application/json


text:
Q: ABC class number from number module ABC classes are created to check object type and as such they cannot be instantiated. In fact:
basestring()

throws:
TypeError: The basestring type cannot be instantiated

However, this does not happen for the ABC number:
from numbers import number

number()

it does not throw any exceptions. Whereas other ABCs from the same module do:
from numbers import Real
from numbers import Complex

Real()  # or Complex()

throws:
TypeError: Can't instantiate abstract class Real with abstract methods __abs__, __add__, __div__, __eq__, __float__, __floordiv__, __le__, __lt__, __mod__, __mul__, __neg__, __pos__, __pow__, __radd__, __rdiv__, __rfloordiv__, __rmod__, __rmul__, __rpow__, __rtruediv__, __truediv__, __trunc__

Why is that ?

A: A look at the source for the numbers module provides the answer:

class Number(metaclass=ABCMeta):
    """All numbers inherit from this class.
    If you just want to check if an argument x is a number, without
    caring what kind, use isinstance(x, Number).
    """
    __slots__ = ()

    # Concrete numeric types must provide their own hash implementation
    __hash__ = None

As you can see, the numbers.Number class has abc.ABCMeta as metaclass. And since it has no methods decorated with @ab.cabstractmethod, @abc.abstractclassmethod or @abc.abstractstaticmethod the abc.ABCMeta class does not prevent the instanciation.
The classes numbers.Real and numbers.Complex on the other hand inherit from numbers.Number and decorate many methods with @abc.abstractmethod, therefore they cannot be instanciated.
That means numbers.Number is most likely only instanciable because of the way abstract classes work in Python and not because someone specifically build it to be so.


text:
Q: How do I install a JRE from an Inno Setup? I'm trying to install the most current platform (x64 or x86) appropriate Java Runtime Environment via Inno Setup (along with another application). I've found some script examples for how to detect the version and install if correct and adapted them to my needs but I keep running into this:

Unable to open file "path\to\JREInstall.exe":
  CreateProcess failed: Code 5:
  Access Is Denied

This is the code strictly responsible for installing the JRE:
[Setup]
AppName="JRE Setup"
AppVersion=0.1
DefaultDirName="JRE Setup"

[Languages]
Name: "english"; MessagesFile: "compiler:Default.isl"

[Files]
Source: "jre-8u11-windows-x64.exe"; DestDir: "{tmp}\JREInstall.exe"; \
    Check: IsWin64 AND InstallJava();
Source: "jre-8u11-windows-i586.exe"; DestDir: "{tmp}\JREInstall.exe"; \
    Check: (NOT IsWin64) AND InstallJava();

[Run]
Filename: "{tmp}\JREInstall.exe"; Parameters: "/s"; \
    Flags: nowait postinstall runhidden runascurrentuser; Check: InstallJava()

[Code]

procedure DecodeVersion(verstr: String; var verint: array of Integer);
var
  i,p: Integer; s: string;
begin
  { initialize array }
  verint := [0,0,0,0];
  i := 0;
  while ((Length(verstr) > 0) and (i < 4)) do
  begin
    p := pos ('.', verstr);
    if p > 0 then
    begin
      if p = 1 then s:= '0' else s:= Copy (verstr, 1, p - 1);
      verint[i] := StrToInt(s);
      i := i + 1;
      verstr := Copy (verstr, p+1, Length(verstr));
    end
    else
    begin
      verint[i] := StrToInt (verstr);
      verstr := '';
    end;
  end;
end;

function CompareVersion (ver1, ver2: String) : Integer;
var
  verint1, verint2: array of Integer;
  i: integer;
begin
  SetArrayLength (verint1, 4);
  DecodeVersion (ver1, verint1);

  SetArrayLength (verint2, 4);
  DecodeVersion (ver2, verint2);

  Result := 0; i := 0;
  while ((Result = 0) and ( i < 4 )) do
  begin
    if verint1[i] > verint2[i] then
      Result := 1
    else
      if verint1[i] < verint2[i] then
        Result := -1
      else
        Result := 0;
    i := i + 1;
  end;
end;

function InstallJava() : Boolean;
var
  ErrCode: Integer;
  JVer: String;
  InstallJ: Boolean;
begin
  RegQueryStringValue(
    HKLM, 'SOFTWARE\JavaSoft\Java Runtime Environment', 'CurrentVersion', JVer);
  InstallJ := true;
  if Length( JVer ) > 0 then
  begin
    if CompareVersion(JVer, '1.8') >= 0 then
    begin
      InstallJ := false;
    end;
  end;
  Result := InstallJ;
end;

In the full setup script the same message continues to come up.
How can I get the JRE Setup to run from this scripted setup file?

A: I was able to figure out the issue:
Evidently I was mistaken in my use of these lines:
Source: "jre-8u11-windows-x64.exe"; DestDir: "{tmp}\JREInstall.exe"; Check: IsWin64 AND InstallJava();
Source: "jre-8u11-windows-i586.exe"; DestDir: "{tmp}\JREInstall.exe"; Check: (NOT IsWin64) AND InstallJava();

and they should have been in place like so:
Source: "jre-8u11-windows-x64.exe"; DestDir: "{tmp}"; DestName: "JREInstall.exe"; Check: IsWin64 AND InstallJava();
Source: "jre-8u11-windows-i586.exe"; DestDir: "{tmp}"; DestName: "JREInstall.exe"; Check: (NOT IsWin64) AND InstallJava();

That seems to have solved the problem.
Also this line I was mistaken in:
Filename: "{tmp}\JREInstall.exe"; Parameters: "/s"; Flags: nowait postinstall runhidden runascurrentuser; Check: InstallJava()

It should have been:
Filename: "{tmp}\JREInstall.exe"; Parameters: "/s"; Flags: nowait runhidden runascurrentuser; Check: InstallJava()

This is the best solution my limited experience with this particular tool is able to come up with. I will look into the PrepareToInstall option when I have a chance but this works for now.

A: According to the initial question, "How do I install a JRE from an Inno script?", and taking as a starting solution the best proposed one, I propose a solution that I think works more coherently.
I understand that the user wants to install a JRE for their application if the target computer does not have installed a Java runtime environment or its version is lower than the required one. Ok, what I propose is to use the AfterInstall parameter and reorder a bit the distribution files in a different way.
We will first sort the files in the [Files] section in another way, putting first the redist install files.
Source: "redist\jre-8u121-windows-i586.exe"; DestDir: "{tmp}"; DestName: "JREInstaller.exe";\
    Flags: deleteafterinstall; AfterInstall: RunJavaInstaller(); \
    Check: (NOT IsWin64) AND InstallJava();
Source: "redist\jre-8u121-windows-x64.exe"; DestDir: "{tmp}"; DestName: "JREInstaller.exe"; \
    Flags: deleteafterinstall; AfterInstall: RunJavaInstaller(); \
    Check: IsWin64 AND InstallJava();
Source: "Myprog.exe"; DestDir: "{app}"; Flags: ignoreversion

The next step we must do is to modify the section [Run] as follows.
[Run]
Filename: "{app}\{#MyAppExeName}"; \
    Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; \
    Flags: nowait postinstall skipifsilent

And last but not least, we implemented in the [Code] section the RunJavaInstaller() procedure as follows:
[Code]

procedure RunJavaInstaller();
var
  StatusText: string;
  ResultCode: Integer;
  Path, Parameters: string;
begin
  Path := '{tmp}\JREInstaller.exe';
  { http://docs.oracle.com/javase/8/docs/technotes/guides/install/config.html#table_config_file_options }
  Parameters := '/s INSTALL_SILENT=Enable REBOOT=Disable SPONSORS=Disable REMOVEOUTOFDATEJRES=1';
  StatusText:= WizardForm.StatusLabel.Caption;
  WizardForm.StatusLabel.Caption:='Installing the java runtime environment. Wait a moment ...';
  WizardForm.ProgressGauge.Style := npbstMarquee;
  try
    if not Exec(ExpandConstant(Path), Parameters, '', SW_SHOW, ewWaitUntilTerminated, ResultCode) then
    begin
      { we inform the user we couldn't install the JRE }
      MsgBox('Java runtime environment install failed with error ' + IntToStr(ResultCode) +
        '. Try installing it manually and try again to install MyProg.', mbError, MB_OK);
    end;
  finally
    WizardForm.StatusLabel.Caption := StatusText;
    WizardForm.ProgressGauge.Style := npbstNormal;
  end;
end;

You may need to replace the Enabled value with 1 and the Disabled value with 0 if the Java runtime installer is not working properly. I have not experienced any problem doing it this way. Anyways, in the code you have a comment with the Oracle link if you want to take a look.
Finally, since unfortunately we can not receive the installation progress status of the JRE in any way, we show a message and a progress bar so that the user does not have the feeling that the installer has hung.
To do this, we save the state before, execute Exec with the flag ewWaitUntilTerminated, to wait for that installation to finish before continuing with ours, and we restore the previous state once the function execution has finished.


text:
Q: Efficient way to serve both API and web requests With the following code, I can serve raw data to an API (or AJAX) client that passes the 'Accept' 'application/json' header, and a view with the data for web clients:
    if ($request->wantsJson()) {
        return $laptops;
    } else {
        return view('laptops')->withLaptops($laptops);
    }

My question is, what's the best way to apply this logic to every request without copying the code into every Controller?

A: It is hard to give you the best answer because you do not provide much details about your context.  Here is one possibility:
You could use two set of controllers
App\Http\Controllers
App\Http\Controllers\API

and use resource controller, to which you can also implement API versionning
Route::resource('laptop', 'LaptopController');
Route::resource('api/v1/laptop', 'API\LaptopController');

Finally, you abstract your controller logic to a service class such as
class LaptopService {

    protected $laptop;

    public function __construct($LaptopId){
          $this->laptop = Laptops::findOrFail($LaptopId);
    }

    public function get() {
       return $this->laptop;
    }
}

Then in your controllers you could have
public function show($id){
    $ls = new LaptopService($id)

    //In App\Http\Controllers
    //return view('laptops')->withLaptops($ls->get());
    //In  App\Http\Controllers\API
    //return Response::json($ls->get(), 200);
 }

A: You can achieve it using the concept of namespaces and routing groups.
You can create 2 controllers of same name but with different namespaces.
Such as in your routes.php
// Routes pointing to the Controllers Within The "App\Http\Controllers" Namespace
Route::resource('laptops', 'LaptopsController');

Route::group(['prefix' => 'api', namespace' => 'Api'], function()
{
    // Routes pointing to Controllers Within The "App\Http\Controllers\Api" Namespace
    Route::resource('v1/laptops', 'LaptopsController');
});

Your Controllers should be in the namespaces

*

*App\Http\Controllers - LaptopsComputer.php

*App\Http\Controllers\Api - LaptopsComputer.php

Your controller should include namespaces like:
// -------- App\Http\Controllers\LaptopsComputer.php --------
namespace App\Http\Controllers;
class LaptopsComputer exends Controller {
    // Methods with reponse to WEB calls...
}

// -------- App\Http\Controllers\Api\LaptopsComputer.php --------
namespace App\Http\Controllers\Api;
class LaptopsComputer exends Controller {
    // Methods with reponse to API calls...
}

For more reference about routings, take a look at - Laravel Routing Groups
Hope this helps you to make a proper use of one of the best features of Laravel.


text:
Q: Center a vector img in a responsive div box? I have a vector img that appears, with the correct dimensions, in a responsive div-box using this css:
.col1 > div {
  width:100%;
  height:25%;
  position: relative;
}
.thisIMGcontainer {
  height: 100%;
  width: 100%;
  position: absolute;
  display: table;
}
.thisIMG {
  background-image: url('../img/thisIMG.png');
  background-size: contain;
  background-repeat: no-repeat;
}

For this HTML:

I have tried multiple combinations of CSS to get the img aligned in the center, but it either remains aligned to the left, or it randomly disappears!

display: table-caption; or display: inline-block; and margin: 0 auto;

A: You image div has no width, so it takes all available width - 100%. If you want an image to be centered, you either have to use  tag instead of using a background image, or you have to set a width in .thisIMG class.


text:
Q: Installing the Pyramid Framework on a disconnected system I am working in Python and have decided to focus on learning Pyramid as my primary framework. The problem is that the work I do is done on a private LAN with no external connectivity and I cannot find any resource to get all the packages needed to setup the virtual environment and pyramid on a system without access to the open internet.
Any ideas or resources anyone might have would be greatly appreciated.
Thanks

A: Hello and thanks for the two options put forward in attempt to answer this question. I was unable to get back to this problem until recently at which point I read these answers and tried one of them before stumbling across the best solution.
Given everything else I was working with was being done from source I tried that (thanks for the link I had been unable to find the source prior) and as I feared I was unable to install pyramid that way given the number of dependencies it needs to install along with it. This however did give me the ability to see exactly what the dependency packages were.
I was getting ready to try the other option with the virtualenv relocatable flag but before I did I came across an option in pip, which is installed as part of virtualenv, that allows you to bundle packages and install them later without the need of a network connection. This ended up being the solution I tried and it worked. At least mostly.
The solution to the basic question is this.
1)Change directories to your virtualenv dir
[user home]$ cd /path/to/virualenv/directory

2)Type the following on a network connected system and it will download the pyramid files and dependencies into the bundle file
[virtualenv_directory]$ bin/pip bundle <nameOfBundle>.pybundle pyramid

3) move to target system and cd to target directory as above and install with the following command
[virtualenv_directory]$ bin/pip install <nameOfBundle>.pybundle

and in this case it will install the pyramid files and dependencies.

A: They have the source available for download on the package page -- couldn't you just download the source and then bring it into your environment on a usb drive? As far as other required packages, it should be fairly easy to install it via pip and see what the dependencies are -- you could then just bring all of that in. In fact, the dependencies are all listed on the package page.
In general, if you're working with a closed network, you're going to have to bring it in somehow, right? Just do that however you can.

A: The simplest way to do this is install it in a virtualenv on a machine outside the network, using the same version of Python as what you use inside the closed network. Then use virtualenvs --relocatable flag to make the environment relocatable, before copying it to physical media that you can bring in to your closed network. By far the most difficult part will be if Pyramid or any of it's dependencies have compiled extensions, as the compiled binaries are very unlikely to be portable.
If they do, the best alternative is to use something like ClueReleaseManager on your external machine, and install Pyramid using it as your primary PyPI mirror (instructions on how to set it up are on the linked page). This will pull down all the source packages into a single directory that you can then bring into your closed environment to compile. This will save you the hassle of manually downloading all of the dependencies, but the setup cost is a bit high.


text:
Q: Mapping a position within a QHeaderView to the context of the scrolled Viewport I have a QHeaderView that does a few things when clicking either to the left or right of the center of a section header.
For this, I need to know the position of the click in relation to the (possibly scrolled) content of the QHeaderView's viewport.
The actual click position, however, refers only to the QHeaderView (which is always fixed).
I tried variants of mapTo/From, but can't find the correct way to do it.
Here's simplified code:
void MyTableHeader::headerSectionClicked(int section_index, int click_pos)
{
    int section_size = sectionSize(0); // All sections in a header are equally sized
    int section_center = (section_size * (section_index+ 1)) - (section_size / 2); // Center of the clicked section

    if (section_index>= 0)// if mouse is over an item
    {
        if (orientation() == Qt::Horizontal)
        {
            QPoint x_pos = QPoint(click_pos, 0);
            int mapped_offset = viewport()->mapFrom(this, x_pos).x();

            if (mapped_offset != -1)
            {
                // If the click was to the right of the center, iterate on the index
                if (mapped_offset >= section_center)
                {
                    section_index++;
                }
            }
        }
        else
        {
            // Same thing for the Y-dimension
        }
    }

    // Neat stuff after this
}

The part where the problem occurs, is where I want to find out on which side of the section the click happened.
// If the click was to the right of the center, iterate on the index
if (mapped_offset >= section_center)
{
    in_index++;
}

This mapped_offset does not properly refer to the same context as the section center.

A: The following solution might give you an idea on what to do.
MyHeaderView.h
#pragma once

#include <QHeaderView>

class MyHeaderView : public QHeaderView
{
    Q_OBJECT
public:
    MyHeaderView(Qt::Orientation orientation, QWidget* parent = nullptr);
};

MyHeaderView.cpp
#include "MyHeaderView.h"
#include <QDebug>

MyHeaderView::MyHeaderView(Qt::Orientation orientation, QWidget* parent) : QHeaderView(orientation, parent)
{
    setSectionsClickable(true);
    connect(this, &MyHeaderView::sectionClicked, [this](int section)
        {
            QRect currentSectionRect;
            currentSectionRect.setRect(sectionViewportPosition(section), 0, sectionSize(section), viewport()->height());
            auto pos = QCursor::pos();
            auto localPos = mapFromGlobal(pos);

            qDebug() << currentSectionRect << localPos;
            qDebug() << currentSectionRect.contains(localPos); //"Always true!"
        });
}

main.cpp
#include "MyHeaderView.h"
#include <QApplication>
#include <QTableView>
#include <QStandardItemModel>

int main(int argc, char **args)
{
    QApplication app(argc, args);
    auto model = new QStandardItemModel;
    auto view = new QTableView;
    view->setModel(model);
    model->setRowCount(4);
    model->setColumnCount(4);
    view->setHorizontalHeader(new MyHeaderView(Qt::Horizontal));
    view->show();
    app.exec();
}


text:
Q: Facing issue while runningj ustb4/jmeterwith docker -- I am trying to run jmeter container with another container localhost:55001 in windows system Facing an issue while running justb4/jmeter with docker -- I am trying to run jmeter container with another container localhost:55001 in the windows system
I have two container
--one container with localhost:55001
--another container with justb4/jmeter
Now I am trying to run justb4/jmeter jmx file, which in my local
docker run -d -p 8081:88 --network="HSM" --mount type=bind,source="/D/D_Backup/Jmeter/apache-jmeter-5.2.1/bin",target="/opt/apache-jmeter-5.4.3/bin" justb4/jmeter -n -t bin/.jmx -l bin/NextGen_HSM_Run.jtl -e -o bin/h.html
Getting below error
1651205770221,39,GetConnectionStatus_1,Non HTTP response code: org.apache.http.conn.HttpHostConnectException,Non HTTP response message: Connect to localhost:55001 [localhost/127.0.0.1] failed: Connection refused (Connection refused),HSM.GetConnectionStatus.Thread 2-1,text,false,Test failed: code expected to contain /200/,2647,0,1,2,http://localhost:55001/GetConnectionStatus,0,0,39
But when I am running from JMeter all transactions are passing.

A: If you want to use justb4/jmeter for testing another application in another container you need to use not localhost in JMeter but the IP address of the container where the application is running.
So you need to obtain the IP of the "other" container with something running on port 55001 using docker inspect command and replace localhost with the IP address of that container in the test plan.
More information: Networking with standalone containers

Just in case I truly hope you know what you're doing because running JMeter and the application under test on the same machine, especially virtual, especially a Docker one is the worst approach for assessing the performance as JMeter might be very resource intensive as well as the system under load so you will have hard time analyzing the results due to race conditions so I would recommend reconsidering your test lab setup or at least using software like cAdvisor or JMeter PerfMon Plugin to monitor resources utilization.
However the best option would be having the system under test and JMeter on a different physical or at least virtual machines.


text:
Q: How to restrict interrupt signal to just the child process? I have a bunch of log files and I want to do a tail -f on them in a loop such that when I press Ctrl-C, the current tail -f gets killed and I proceed to the next log file:
for log in *.log; do
    printf '%s\n' "Tailing log '$log'; press Ctrl-C to skip to the next"
    tail -f "$log"
done

The issue is that pressing Ctrl-C kills the loop itself.  How can I restrict the interrupt signal to just the child process, tail in this case?

A: Put
trap ":" SIGINT

before the loop. This makes the shell ignore the signal. But just in the sense that it executes a dummy command, not "ignore" in the signal handler sense.
Because the shell process does not block this signal (from the kernel perspective) it gets through to its child processes (like tail in this example).


text:
Q: What is the difference between these class declarations with Comparable? Here is one declaration
public class BinarySearchTree<AnyType extends Comparable<? super AnyType>> {
   ....
}

Here is the other declaration
public class BinarySearchTree<AnyType extends Comparable<AnyType>>{
    .....
}

I know the first declaration is preferred(seen it in alot of java examples and textbooks) but why is that? All my code ran fine when I tried using the second declaration as well.
I know that super used in this context, ? super AnyType, means AnyType or any of its super classes. Super
To me both are saying that this class, BinarySearchTree, supports any object type that is comparable. Can anyone describe or give an example of where this subtle difference actually makes a difference?
With dog example
class Animal implements Comparable<Animal>
class Dog extends Animal
public class BinarySearchTree<AnyType extends Comparable<? super AnyType>> {
  ...}
Would allow for
BinarySearchTree<Dog> but
 public class BinarySearchTree<AnyType extends Comparable<AnyType>>{
    .....
} wouldn't

A:
Can anyone describe or give an example of where this subtle difference actually makes a difference?

Yes. Two examples from the JDK:

*

*java.util.Date;

*java.sql.Date.

You will note that the latter extends the former, yet what (sql) Date implements is Comparable of java.util.Date.
If it were "only" implementing Comparable of itself, you wouldn't be able to compare it to a "normal" Date.
Also consider the simple case of a Consumer (interface which appeared in Java 8). The most frequently used Consumer of all is System.out::println; its argument is an Object in this case.
Now, if the signature of Stream's .forEach() were .forEach(Consumer<T> consumer) instead of .forEach(Consumer<? super T>), you wouldn't be able to use that "universal consumer" at all, except for Stream<Object>s!
That is the CS part of the PECS rule (Producer Extends, Consumer Super).

A: If you have
class Animal implements Comparable<Animal>
class Dog extends Animal

then BinarySearchTree<Dog> would be legal with the first signature but not with the second. It's not legal with the second signature because Dog does not implement Comparable<Dog> (and there is no way to make it implement Comparable<Dog>, since it already implements Comparable<Animal>, and a type cannot implement an interface with two different type arguments).
If you think about it, BinarySearchTree<Dog> is perfectly fine because Dogs are comparable to themselves (in fact they are comparable to all Animals, which includes all Dogs). All we need is to guarantee someDog.compareTo(someOtherDog) works. For this to work, we don't need that compareTo take exactly Dog -- any supertype of Dog will also work. That's what the ? super represents. It relaxes the constraint to a more general one that still provides all the type guarantees we need. In generics, we should always use the least restrictive bounds that give us the type safety we need.
Another way to think about it is through the PECS rule (Producer extends, Consumer super). A Comparable<T> can only be a "consumer" of T, because its only method takes a parameter of type T, and it does not return T. Therefore, Comparable should always be used with a ? super ... wildcard.


text:
Q: Delay in javascript debugging I have many linked Javascript files which I need to debug from the point they start executing. I am using the inbuilt debugger in chrome for this purpose. But by the time I am able to open the debugger, the script has already completed the part I want to debug. So, is there a standard way built in chrome (or any other debugger, though I would like to stick to chrome) to stall the execution for debugging. I want to avoid putting a delay like function in my script.
Also, reloading the script is not an option for me.

A: Set a breakpoint in Developer Tools. When the interpretor gets to that line, it will break, allowing you to examine a few things.

Not the best example, because Stack Overflow's JavaScript is minified, but you get the idea.

A: just write
function name()
{
         debugger;
        // you code
  }

in you code


text:
Q: Global Parameters Window in Meshlab I'm a new user, so this is probably a simple question, but in the Mac version of Meshlab, where do I find the Global Parameters Window? There is no Tools menu and the help search doesn't help. Thanks!

A: Under the meshlab->Preferences menu (Command+,)


text:
Q: How to find elements within string in C++ For a google URL, ex. https://www.google.com/search?q=some+query&oq=some+query&aqs=chrome..69i57j0l5.2991j0j9&sourceid=chrome&ie=UTF-8
I need to grab the search engine (google.com)
Any queries (some, query)
and all options (oq, aqs, sourceid, and ie)
I'm assuming I need to find the characters in between the two backslashes for the search engine.
But how would I find every query when there can be and endless amount of them and I can't define a star and an end in the string to look for? The same goes with the options.
Any help would be appreciated.

A: Let's use the example you gave: https://www.google.com/search?q=some+query&oq=some+query&aqs=chrome..69i57j0l5.2991j0j9&sourceid=chrome&ie=UTF-8
The general idea here is to split the string based on certain delimiters. In this case, the various sections of the actual URL are divided based on "/". If we split the string based on that, we get this:

*

*https:

*www.google.com

*search?q=some+query&oq=some+query&aqs=chrome..69i57j0l5.2991j0j9&sourceid=chrome&ie=UTF-8

The third section can be split further based on "&" to give:

*

*search?q=some+query

*oq=some+query

*aqs=chrome..69i57j0l5.2991j0j9

*sourceid=chrome

*ie=UTF-8

You can then split each of these based on "=" to get the option name and the value chosen. For example "sourceid=chrome" would split to give the option name "sourceid" and the value "chrome".
Implemented in actual C++ code it looks like this:
// Includes
#include <iostream>
#include <vector>

// For simplicity's sake, we'll call std::vector<std::string> "Tokens"
using Tokens = std::vector<std::string>;

// Create a function to return an std::vector<std::string>
Tokens getTokens(std::string inputString, std::string delimiter)
{
    // Create a list of tokens
    Tokens tokens;

    // Create a string to store the curernt token
    std::string token;

    // Iterate through until there are no more delimiters (at which our token will be identical to our input string)
    while (token != inputString)
    {
        // Set the token to the section of the input string from its beginning to where the first delimiter is found
        token = inputString.substr(0, inputString.find(delimiter));

        // If that token isn't empty append it to the list of tokens (we could get any empty token if two delimiters follow one another, e.g. //)
        if (token != "")
        {
            tokens.push_back(token);
        }

        // Remove the token from the original input string
        inputString = inputString.substr(inputString.find(delimiter) + 1);
    }

    return tokens;
}

int main()
{
    // This is our URL:
    std::string URL = "https://www.google.com/search?q=some+query&oq=some+query&aqs=chrome..69i57j0l5.2991j0j9&sourceid=chrome&ie=UTF-8";

    // Split up the URL into tokens based on the delimiter "/"
    Tokens URL_tokens = getTokens(URL, "/"); // <--- should contain three tokens, "https:", "www.google.com" and everything after that

    // Split up the third token of the URL tokens based on the delimiter "&"
    Tokens details_tokens = getTokens(URL_tokens[2], "&");

    // Print out the tokens
    std::cout << URL_tokens[0] << "\n";
    std::cout << URL_tokens[1] << "\n\n";

    for (int token = 0; token < details_tokens.size(); token++)
    {
        // Split into option and value
        Tokens option_and_value = getTokens(details_tokens[token], "=");

        std::cout << "Option: " << option_and_value[0] << "\n";
        std::cout << "Value: " << option_and_value[1] << "\n\n";
    }
}

On my computer this produced the following output:
https:
www.google.com

Option: search?q
Value: some+query

Option: oq
Value: some+query

Option: aqs
Value: chrome..69i57j0l5.2991j0j9

Option: sourceid
Value: chrome

Option: ie
Value: UTF-8


text:
Q: Codeigniter - How to convert a html page to an image? I've a webpage, coded on codeigniter framework, which lists all available certificates. Then I can print a certificate by clicking on its name or by checking checkboxes if the user wants to print more than 1 certificates.
Currently what I do is just to view the html of the certificate, and the user had to right click on their browser and click on print. Which is fine for 1 page of certificate.
But when I've 2 or more certificates, the certificates aren't stack perfectly. As far as I know, I can't set the html page to be an A4 size print.
Codeigniter had an image manipulation library. http://codeigniter.com/user_guide/libraries/image_lib.html
But couldn't find what I wanted.
Is there a way to convert these html pages into image which I can later print those? Or should I try other libraries?

A: I would use DOMPDF to create a PDF document. You can generate them the html as normal, then use the third parameter of the load view function to return the html for the PDF processing.
Something like this in your controller;
    $this->load->helper('pdf');
    $html = $this->load->view('certificate_view', array(), TRUE);
    $attachment_location = $_SERVER["DOCUMENT_ROOT"] . '/certs/'.$title.'.pdf';
    pdf_create($html, $title, $stream=FALSE, $orientation='portrait');
    // send open/save pdf dialog to user
    header('Cache-Control: public'); // needed for i.e.
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="'.$title.'"');
    readfile($attachment_location);
    exit;

The Codeigniter DOMPDF library is here.

A: You can convert an html to image by using this simple tutorial. It uses imagick and no gd library.


text:
Q: Objective C: CoreData and aggregation Given a CoreData-Entity with an date (days) and an ammount called Transaction.
Is it with CoreData possible (and how) to aggregate/group the 'table' (with all Transactions) by Date and calculate the sum of the day in a second column/attribute?
(the SQL-Solution would be SELECT date, sum(ammount) FROM transaction GROUP BY date)

A: They may not do exactly what you want, but since Core Data is fully KVC compliant, take a look at the Key-Value Coding Set and Array operators. This should at least get you pretty close to what you're looking to do.

A: Stack Overflow: "CoreData equivalent of sum…group by"


text:
Q: AlertDialog does not dismiss, takes twice tap to close I have been trying to learn and play with Android studio for about 3 weeks now. I just came to a situation where AlertDialogue doesn't dismiss on clicking on positive button.
private void showGPSDisabledAlertToUser() {
    AlertDialog.Builder builder;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert);
    } else {
        builder = new AlertDialog.Builder(this);
    }

    builder.setTitle("Turn On Location / GPS");
    builder.setCancelable(false);
    builder.setMessage("Application Needs To Determine Device's Physical Location.");
    builder.setPositiveButton("YES, TURN ON", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss(); // This ain't working
                    goToInternetSettings();
                }
            });
    builder.setNegativeButton("NO, CANCEL", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    closeApplication();
                }
            });
    builder.create().show();
}

private void goToInternetSettings() {
    Intent gpsSetting = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    startActivity(gpsSetting);
}

private void closeApplication() {
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    startActivity(intent);
}

It looks like I am only able to close the dialogue if I have to double click on positive.
On the other hand, with negative button there is no such trouble. I guess, since negative button shuts down the whole application, and hence that is taking care of that problem else it would have been the same.

A: You don't need to call dialog.dismiss() inside setPositiveButton() OnClickListener because it is called implicitly.
You probably call the showGPSDisabledAlertToUser() multiple times when checking for the GPS availability. You can try to create the dialog once and reshow it again with something like this:
AlertDialog mAlertDialog;

private void showGPSDisabledAlertToUser() {
  // build the alert dialog once.
  if (mAlertDialog == null) {
    AlertDialog.Builder builder;

    ...
    // Do your dialog initialization here.
    ...

    mAlertDialog = builder.create();
  }

   mAlertDialog.show();
}

A: You don't need to explicitly dismiss the alert dialog by calling dialog.dismiss(); inside the onClick method of the dialog interface buttons.
The dialog will automatically be closed once you click any of those buttons.
If you're telling the dialog isn't gone after you click the button, you might have created multiple dialogs so that even one dialog is dismissed, another one is still there.


text:
Q: Make a button activate JavaScript code What I would like to accomplish today is making a button activate JavaScript code. For example, lets take a code to make snow appear on the page. At first, the page doesn't have snow falling, but the code is in the page. Then the visitor clicks on the button and snow starts falling on the page. That's what I want it to do.
Website to use on: http://gravitate.webs.com
Snow Code:
BEGINNING
<!-- -->
<script type="text/javascript" src="http://static.websimages.com/static/global/js/webs/usersites/escort.js"></script>
<script type="text/javascript">
  if(typeof(urchinTracker)=='function') {
    _uacct="UA-230305-2";
    _udn="none";
    _uff=false;
    urchinTracker();
  }
</script>

</body>

<script language="JavaScript" src="http://www.ig33kstas.com/wp-content/plugins/wp-christmas/wp-christmas.js.php?swf=http://www.ig33kstas.com/wp-content/plugins/wp-christmas/wp-christmas-EN.swf"></script>

</div>

<script type="text/javascript">
  sitePath = "http://www.ig33kstas.com/wp-content/plugins/wp-christmas/";
  sflakesMax = 89;
  sflakesMaxActive = 64;
  svMaxX = 4;
  svMaxY = 5;
  ssnowStick = 1;
  sfollowMouse = 1;
</script>
}
</script>

END
What I tried that totally failed:
<body>
<button onclick="mysnowcode">Snow</button>
</body>
</html>

A: <html>
<head>
    <script type="text/javascript">
        function makeitsnow() { ...your snowfall code... }
    </script>
</head>
<body>
    <button onclick="makeitsnow();">Click</button>
</body>
</html>


text:
Q: Why does my jquery modal stop working after full page ajax load? Ive discovered that I have an issue with the jQuery dialog (using jquery 1.3 , pretty old but I cannot update it).
When I do
var request = $.ajax({
  url: "${Request.context}/info/" + userId,
  success: function(response) {
    $("#userInfo").html(response);
  }
});

$("#divUserInfo").dialog('open');
}

where
$('#divUserInfo').dialog({
  width: 700,
  height: 250,
  autoOpen: false,
  modal: true,
  title: "User Info",
  resizable: false
});

The dialog itself works fine, opens everytime when it has no content or when I do $("#userInfo").html("any string possible");
But when I load the entire page of the ajax response, I see no error on my console but I cannot re-open the dialog. Is there any way I can avoid that happening? should I reload the DOM or something similar? or extract the body of the response?

A: You need to re-initialize dialog plugin after replacing DOM with ajax response, so that it works for updated DOM elements as well
Try this:
var request = $.ajax({
  url: "${Request.context}/info/" + userId,
  success: function(response) {
    $("#userInfo").html(response);
    $('#divUserInfo').dialog({
      width: 700,
      height: 250,
      autoOpen: false,
      modal: true,
      title: "User Info",
      resizable: false
    });
  }
});


text:
Q: Choosing a random sample from each row of Numpy array, excluding negative numbers I have a Numpy array that looks like
>>> a
array([[ 3. ,  2. , -1. ],
       [-1. ,  0.1,  3. ],
       [-1. ,  2. ,  3.5]])

I would like to select a value from each row at random, but I would like to exclude the -1 values from the random sampling.
What I do currently is:
x=[]
for i in range(a.shape[0]):
    idx=numpy.where(a[i,:]>0)[0]
    idxr=random.sample(idx,1)[0]
    xi=a[i,idxr]
    x.append(xi)

and get
>>> x
[3.0, 3.0, 2.0]

This is becoming a bit slow for large arrays and I would like to know if there is a way to conditionally select random values from the original a matrix without dealing with each row individually.

A: I really don't think that you will find anything in Numpy that does exactly what you are asking as packaged so I've decided to offer what optimizations I could think up.
There are several things that could make this slow here. First off, numpy.where() is rather slow because it has to check every value in the sliced array (the slice is generated for each row as well) and then generate an array of values. The best thing that you could do if you plan on doing this process over and over again on the same matrix would be to sort each row. Then you would just use a binary search to find where the positive values start and just use a random number to select a value from them. Of course, you could also just store the indices where the positive values start after finding them once with binary searches.
If you don't plan on doing this process many times over, then I would recommend using Cython to speed up the numpy.where line. Cython would allow you to not need to slice the rows out and speed up the process overall.
My last suggestion is to use random.choice rather than random.sample unless you really do plan on choosing sample sizes that are larger than 1.


text:
Q: Long code that needs to wrap How would I enter this text on an 8.5x11 worksheet with 1.25inch margins all around so wraps around and does not extend onto the margins? Using normalsize text.
SolverAdd CellRef:=Worksheets("Worksheet_Alpha_Gamma_TestResult").Range("$H$43:$H$46")Relation:=5, FormulaText:="binary

A: You could use listings:

\documentclass{article}
\usepackage{lipsum}% http://ctan.org/pkg/lipsum
\usepackage[margin=1.25in,letterpaper]{geometry}% http://ctan.org/pkg/geometry
\usepackage{listings}% http://ctan.org/pkg/listings
\begin{document}
\lipsum[1]
\begin{lstlisting}[breaklines,basicstyle=\ttfamily]
SolverAdd CellRef:=Worksheets("Worksheet_Alpha_Gamma_TestResult").Range("$H$43:$H$46")Relation:=5, FormulaText:="binary
\end{lstlisting}
\lipsum[2]
\end{document}

breaklines=true allows for line-breaking within the lstlistings environment. I used basicstyle=\ttfamily, although that is not necessary.
lipsum provided some dummy text, while geometry was used to obtain the layout requirements.