text:
Q: Problem in Trigger? trigger CopyAttachmentsToCon on Attachment (after insert) {

Set<Id> AccountIds = new Set<Id>();
for(Attachment file : Trigger.new) {

    if(file.ParentId.getSObjectType() == Account.getSObjectType()) {
        AccountIds.add(file.ParentId);
    }
}

if(AccountIds!=null && !AccountIds.isEmpty()){
    list<contact> tempList = [select id from contact where id in : AccountIds];
    if(tempList!=null && !tempList.isEmpty()){
        for(contact con : tempList){
            Attachment obj = new Attachment();
            obj.ParentId = con.id;
        }

    }
}

Trying to copy same inserted attachment on account object to its related contact.

A: You are querrying Contact where id you comparing is of acccount.
Quickfix would be to compare AccountID in where clause.
  Trigger CopyAttachmentsToCon on Attachment(after insert) {

      Set < Id > AccountIds = new Set < Id > ();
      Map < String, List < Attachment >> accountIDvsAttachmentList = new Map < String, List < Attachment >> ();
      for (Attachment file: Trigger.new) {

       if (file.ParentId.getSObjectType() == Account.getSObjectType()) {
        AccountIds.add(file.ParentId);

        //Adding attachment to Map
        if (accountIDvsAttachmentList.containsKey(file.ParentId)) {
         (accountIDvsAttachmentList.get(file.ParentID)).add(file);
        } else {
         accountIDvsAttachmentList.put(file.ParentID, new List < Attachment > {
          file
         });

        }

       }
      }
      if (AccountIds != null && !AccountIds.isEmpty()) {
       //Query wrt AccountID and not id
       list < contact > tempList = [select id, AccountID from contact where AccountID in : AccountIds];
       List < Attachment > attachmentsToBeInserted = new List < Attachment > ();
       if (tempList != null && !tempList.isEmpty()) {
        for (contact con: tempList) {
         if (accountIDvsAttachmentList.containsKey(con.AccountID)) {
          for (Attachment attached: accountIDvsAttachmentList.get(con.AccountID)) {

           Attachment obj = new Attachment();
           obj.ParentId = con.id;
           obj.body = attached.body;
           obj.name = attached.name;
           attachmentsToBeInserted.add(obj);
          }
         }
        }
        insert attachmentsToBeInserted;

       }
      }


text:
Q: Converting this AsyncTask to RxAndroid? Bit new to Rx, so am looking for some help on converting the following AsyncTask to Rx, hopefully so I can visualize Rx a bit more with code that I already know that does something. I've found a few other SO answers that were somewhat relevant, but alot of them werent network requests and many used different operators for different answers, so am a bit confused.
Heres the AsyncTask:
public class BackgroundStuff extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {

        UserAgent myUserAgent = UserAgent.of("xxx:xxxx:xxx");

        RedditClient redditClient = new RedditClient(myUserAgent);
        Credentials credentials = Credentials.userlessApp("xxxxxxxx", UUID.randomUUID());
        OAuthData authData = null;
        try {
            authData = redditClient.getOAuthHelper().easyAuth(credentials);
            redditClient.authenticate(authData);
        } catch (OAuthException e) {
            e.printStackTrace();
        }

        SubredditPaginator sp = new SubredditPaginator(redditClient);

        sp.setLimit(7);
        sp.setSorting(Sorting.HOT);
        sp.setTimePeriod(TimePeriod.DAY);

        sp.setSubreddit("pics");

        sp.next(true);
        Listing<Submission> list = sp.getCurrentListing();

        Submission sub = list.get(1);
        for (Submission submission : list) {
            Log.d("test", "title: " + submission.getTitle());
        }
        Submission sub2 = redditClient.getSubmission(sub.getId());
        System.out.println(sub2.getComments().get(0).getComment().getBody());

        return null;
    }
}

For reference, this authenticates to Reddit and then grabs some results from a particular subreddit.
I know I need an Observable, and then .suscribeOn(Schedulers.newThread()) and .observeOn(AndroidSchedulers.mainThread()), but am not sure how to make the observable.

A: Wrap it in function:
    Void doSomething(){
    UserAgent myUserAgent = UserAgent.of("xxx:xxxx:xxx");

    RedditClient redditClient = new RedditClient(myUserAgent);
    Credentials credentials = Credentials.userlessApp("xxxxxxxx", UUID.randomUUID());
    OAuthData authData = null;
    try {
        authData = redditClient.getOAuthHelper().easyAuth(credentials);
        redditClient.authenticate(authData);
    } catch (OAuthException e) {
        e.printStackTrace();
    }

    SubredditPaginator sp = new SubredditPaginator(redditClient);

    sp.setLimit(7);
    sp.setSorting(Sorting.HOT);
    sp.setTimePeriod(TimePeriod.DAY);

    sp.setSubreddit("pics");

    sp.next(true);
    Listing<Submission> list = sp.getCurrentListing();

    Submission sub = list.get(1);
    for (Submission submission : list) {
        Log.d("test", "title: " + submission.getTitle());
    }
    Submission sub2 = redditClient.getSubmission(sub.getId());
    System.out.println(sub2.getComments().get(0).getComment().getBody());

    return null;
    }

Wrap it in an observable:
Observable.just(doSomething);

Wrap it in a defer so it will run only when someone subscribes to it:
Observable<Void> doSomethingObservable = Observable.defer(()-> Observable.just(doSomething))

Decide where it will run with subscribeOn and observeOn, and subscribe to it to make it run:
doSomethingObservable
.suscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread()).subscribe();

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why did an HTTP request return lines giving an expiration date in 1984? I am working through Chapter 12 of the Python for Everybody course, and when I ran the code for an HTTP request, in addition to getting the expected information, I also got these lines:
Cache-Control: max-age=0, no-cache, no-store, must-revalidate
 Pragma: no-cache
 Expires: Wed, 11 Jan 1984 05:00:00 GMT

I have no idea what they mean, or if this means I made an error of some kind. Any explanation anyone can offer for this strange message from pre-1984 would be greatly appreciated. Thanks.

A: It's an arbitrarily old date that in combination with the other headers should cause no client to cache the response, ever, and always issue a new request for that resource.


text:
Q: Does order of loops matter for speed in R I have a problem where I want to run a simulation study where the simulation depends on two variables x and y.  x and y are vectors of potential values that I want to evaluate (so different combinations) in my simulation study.  Furthermore, for each combination of x and y I want multiple replicates (since there is a stochastic term in there and each run of x and y will vary).
To give an example of what I am dealing with I have the following simplified example:
x = 1:10
y = 11:20

iterations = 2000
iter = 1

solution = array(NA,c(length(x),3,iterations))
for(i in x){
    for(j in y){
        for(k in 1:iterations){
            z = rnorm(3) + c(i,j,1)
            solution[i,,k] = z
        }
    }
}

However in my actual problem, the code that get evaluated inside the for loop is much less trivial to evaluate. However, the structure of my inputs are the same as well as the output.
So what I would like to know, say using the above example, is it most efficient to set up the loops in that order or would it be better to let k in 1:iterations be the outermost loop and try to use some sort of outer() command within that 1 loop since I will be evaluating the function (z in this example) over the grid x and y?
Also, I am very open to a completely different set-up and design.  At the end of the day I want to be able to obtain a solution that is based on x and y and averaged over all the iterations, i.e., apply(solution, c(1,2),mean)

Edit:
As was suggested to me, here is the actual code that I am using.
library(survival)

iter = 2000
n = 120
base = 2
hr = 0.5
m.x = 3
m.y = m.x/hr

ANS = NULL
for (vecX in c(0.3, 0.5, 0.6, 0.7)){
out = NULL

    for (vecY in c(0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95)){
        m.x.p = m.x/vecX
        m.y.p = m.y/vecX
        m.x.n = m.x
        m.y.n = m.y

        n.t = round(n*base/(base+1))
        n.c = n - n.t

        for (ii in 1:iter){
            n.t.p = rbinom(1, n.t, vecY)
            n.t.n = n.t - n.t.p
            n.c.p = rbinom(1, n.c, vecY)
            n.c.n = n.c - n.c.p

            S = c(rexp(n.t.p, log(2)/m.y.p), rexp(n.t.n, log(2)/m.y.n), rexp(n.c.p, log(2)/m.x.p), rexp(n.c.n, log(2)/m.x.n))

            data1 = data.frame(Group = c(rep("T", n.t), rep("C", n.c)), dx = c(rep("P", n.t.p), rep("N", n.t.n), rep("P", n.c.p), rep("N", n.c.n)), S)

            fit = survfit(Surv(data1$S)~data1$Group)
            coxfit = coxph(Surv(data1$S)~data1$Group)

            HR = exp(coxfit$coefficients)
            p.val=summary(coxfit)$logtest["pvalue"]

            out = rbind(out, c(vecX, vecY, n.t.p, n.t.n, n.c.p, n.c.n, HR, p.val))
        }

    }
    colnames(out) = c("vecX", "vecY", "n.t.p", "n.t.n", "n.c.p", "n.c.n", "HR", "p.val")

    ans = as.data.frame(out)
ANS = rbind(ANS, ans)

}

A: Yes, I believe that in theory it should make a difference (see example below).
R uses column-major ordering like Fortran (and unlike C), so to minimize cache misses you'd want to be traversing down columns. So for filling a matrix, the optimal approach is the one where the outer loop has our column index.
And for n-dimensional arrays, you'd want to bear this in mind, too. In the case that n = 3, I guess this would mean having the layer be the outermost loop, then the column, then the row. I could be mistaken here, though.
I ran this quick example with 5000 by 5000 matrices. And we are seeing a difference of about 50 seconds, with fill_matrix2() being faster.
    n <- 5000
    A <- matrix(NA, n, n)
    B <- matrix(NA, n, n)

    fill_matrix1 <- function(X, val) {
        for (i in 1:nrow(X)) {
            for (j in 1:ncol(X)) {
                X[i, j] <- val
            }
        }
        return(X)
    }

    fill_matrix2 <- function(X, val) {
        for (j in 1:ncol(X)) {
            for (i in 1:nrow(X)) {
                X[i, j] <- val
            }
        }
        return(X)
    }

    system.time(fill_matrix1(A, 0))
    system.time(fill_matrix2(B, 0))

A: The order of the loops is practically irrelevant here. If you profile your code (see help("Rprof")) you'll see that the CPU time is spent in functions like survfit and coxph. And of course in growing out, which you should avoid. Pre-allocate out to its final size and fill it instead of growing it.


text:
Q: Complicated SQL query to find number difference in same table Could someone please help me write an SQL server query which would give me expected outcome from current data.I need to find meter Gap between each position.

A: just use LEAD and combine it with subquery (reading table data once), like this
select tt.PersonId, tt.PreviousPosition, tt.NextPosition,
       tt.NextMeter - tt.previousMeter
  from (select PersonId, t.position PreviousPosition,
                LEAD(Position) OVER(order by Position) NextPosition,
                t.Meter PreviousMeter,
                LEAD(Meter) OVER(order by Position) NextMeter
           from myTable t) tt
 where tt.NextPosition is not null

but i have sorted by Position, if you have some key (which keep inserting ordering ) or you have some special logic with inerting and ordering use only that columns in sorting

A: Try something like this.
SELECT id, position as previous,(
       SELECT TOP 1 position
       FROM table t1
       WHERE ti.position > t2.position
       ORDER BY
             position
       ) as next,
       (
       SELECT TOP 1 meter
       FROM table t1
       WHERE ti.position > t2.position
       ORDER BY
             position
       ) - meter AS gap
FROM table t2
ORDER BY position

A: Try this (I had to add a unique PK column to your data)
CREATE TABLE #Data
(
    ID INT,
    PersonId INT,
    Position INT,
    Meter INT
)

INSERT INTO #Data VALUES (1,1,10,10),(2,1,22,20),(3,1,34,35),(4,1,46,46)

SELECT  PersonId,
        Position AS PreviousPosition,
        LEAD(Position) OVER (ORDER BY ID) NextPosition,
        Meter as ThisMeter,
        LEAD(Meter) OVER (ORDER BY ID) NextMeter
INTO    #Results
FROM    #Data

SELECT PersonId,
       PreviousPosition,
       NextPosition,
       NextMeter - ThisMeter AS MetreGap
FROM   #Results
WHERE  NextPosition IS NOT  NULL

DROP TABLE #Results
DROP TABLE #Data


text:
Q: How do I attach datepickers to text boxes with the same ID? I have an ASPX that has a repeater. Inside the repeater is a  text box with a JQuery datepicker attached to it. The text box's ID is static, so it is the same for all of those items within the repeater. However, when I make a change to the second or subsequent repeater item's date box using a datepicker, it changes the first item's date box and leaves the one actually attached to the selected datepicker alone.
Other than the obvious solution of "don't define items with the same ID," which results in another problem that will probably end up in another question, is there a way to fix this problem?

A: This example
<asp:Repeater runat="server"
              ID="rptWhatever"
              ClientIDMode="Predictable">
  <ItemTemplate>
    <asp:TextBox runat="server"
                 ID="tbxWhoCares"
                 CssClass="ImaDatePicker">
    </asp:TextBox>
  </ItemTemplate>
</asp:Repeater>

Will render the textbox to something like:
<input id="tbxWhoCares" type="text" class="ImaDatePicker"/>

So regardless of the id you should be able to do this in your script:
$(".ImaDatePicker").datepicker();

The problem with non-unique ID's is a big one but should be an easy fix if you set the attributes in the Repeater to ClientIDMode="Predictable" and leave the same attribute in the TextBox to its default.
Update
It seems jquery UI datepicker requires a unique id.
So you can select multiple inputs using a common css class but the id's must be unique otherwise you run into that problem.
It shouldn't work that way...but it does.
Alternatively you could just use the native <input type="date" ... />

$(function() {
  $(".ImaDatePicker").datepicker();
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/themes/base/theme.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/themes/base/jquery-ui.min.css" rel="stylesheet"/>

<input id="tbxWhoCares" type="text" class="ImaDatePicker" />
<input id="tbxWhoCares" type="text" class="ImaDatePicker" />
<input id="tbxWhoCares" type="text" class="ImaDatePicker" />

<input id="tbxWhoCares_1" type="text" class="ImaDatePicker" />
<input id="tbxWhoCares_2" type="text" class="ImaDatePicker" />
<input id="tbxWhoCares_3" type="text" class="ImaDatePicker" />


text:
Q: How to use Wordpress Functions on an external PHP - On any wordpress site, not only mine I am working on a PHP program that does some tasks and then generates a text, this text must be able to be published later in a Wordpress (.org).
The Wordpress sites where it will publish are not mine and are not on my server so include wp-load or similar will not to work, for this, I will have in my database the login information (URL of the site, user, password).
I need to know how to connect from PHP and create the session in Wordpress.
After that, I need to get the list of categories of the blog and then publish the generated text in one of them. Can it be done directly or do I need to make a plugin for this? I don't have experience making plugins and wordpress Rest API, so if there is a direct way it would be better.


text:
Q: Moving complex conditional statements to code behind I was just wondering, if by moving complex if else statements and the resulting html markup to the code behind violates some 'MVC' law?
It seems like a great option when faced with inline if else statements that can become extremely unreadable.

A: It's not horrible to have conditionals in your view.  I would keep them in the ASPX not the code behind.  However, a conditional often indicates controlling behavior.  Consider the following ASPX code:
<%if (ViewData["something"] == "foo") {%>
     <%=Html.ActionLink("Save", "Save") %>
<%}%>
<%if (ViewData["somethingElse"] == "bar") {%>
     <%=Html.ActionLink("Delete", "Delete") %>
<%}%>

This set of conditionals represents controlling behavior that is being handled by the view -- i.e., in the wrong place.  This behavior is not unit testable.  Consider instead:
<%foreach (var command in (IList<ICommand>)ViewData["commands"]) {%>
     <%=Html.ActionLink(command) %>
<%}%>

In this example ActionLink is a custom extension of HtmlHelper that takes our own ICommand specification object.  The controller action that renders this view populates ViewData["commands"] based on various conditions.  In other words, the controller does the controlling.  In the unit tests for this action, we can test that the correct set of commands will be presented under various conditions.
At first this might seem like a hassle compared with quickly throwing a few IFs into the view.  The question you have to ask yourself is, "Does this IF represent controlling behavior, and do I want to ensure does not at some point break?"

A: I prefer not to use the code behind class in my views. This is not because it violates MVC by default, but because I found that the "natural" way (at least for me) is different.
When I face complex HTML markup that relates to purely view concerns, I usually write an extension method for HtmlHelper class in order to hide the complexity. Thus I have extensions like Html.MoneyTextBox(), Html.OptionGroup() and Html.Pager<T>.
In other cases when complex conditions arise, usually I missed something from the controller. For example, all issues related to the visibility, readonly or enabled of elements usually stem from something that the controller can provide. In that case instead of passing the model to the view, I create a view model which encapsulates the model and the additional info that the controller can provide in order to simplify the HTML markup. A typical example of view model is the following:
public class CustomerInfo
{
  public Customer Customer { get; set; }
  public bool IsEditable { get; set; }  // e.g. based on current user/role
  public bool NeedFullAddress { get; set; }  // e.g. based on requested action
  public bool IsEligibleForSomething { get; set; }  // e.g. based on business rule
}

That said, the code behind is part of the view, so you can use it freely, if it fits your needs better.

A: I believe as long as it's a rendering code and it's in a "View" not in a controller, then putting it on code behind or inline won't matter. Just make sure that you don't write this piece of the rendering code in the Controllers actions (this way you will really violate the MVC pattern).

A: The codebehind is part of the View -- it's up to you if you want to put things in the ASPX directly or in the codebehind. MVC doesn't mean you have to code things all ugly in the ASPX :).


text:
Q: How to block in list members messages I wanted to do list of muted members and delete every message they write but I did something wrong because that command works at all members:
Muted_members = ["muted member id"]

@bot.event
async def on_message(message):
for message.author in Muted_members:
...

A: You should replace
for message.author in Muted_members:
with
if message.author in Muted_members:
to check if the author is in the list and than execute your deletion and not execute your deletion code once for all muted members as you currently are doing.


text:
Q: how to make a series of number jumps based on the numbers of variables I want to make row of number jumps, example I have $a = 1 and $b = 2. then I want loop $a and $b and the result is $a = '1', '5', '9', '13', '17' and $b = '2', '6', '10', '14', '18' . How to make it?

A: You might want to add some context as to me it looks like a generic PHP question, but you also added the codeigniter tag which looks like there is more to it than you wrote.
If I understand you correctly, you start with two numbers and want to generate an list (array) for each of those numbers. Reusing $a and $b for the results might not be a good idea. So I suggest you save the result to a different variable:
// initialize A
$a=1;
$a_result=[];

// initialize B
$b=2;
$b_result=[];

// set the jump size
$jump_size=4;

// loop 5 jumps
for($i=0; $i<5; $i++) {
    // add new elements to the result arrays
    $a_result[] = $a + $jump_size * $i;
    $b_result[] = $b + $jump_size * $i;
}

// print the results
print_r($a_result);
print_r($b_result);

If you have more than just two numbers to start from, you might want to put those in an array too (as well as the result arrays).

A: You can check odd or even number using modulo, and skip next number.
See below example.
See Running Example
$a = 1;
$b = 2;

for($i = $a; $i <= 20; $i++){
    if($i > 1 && $i % 2){
        $i = $i + 2;
    }
    if($i % 2 == 1) {
        echo $i;
    }
}

echo " b=> ";
for($i = $b; $i <= 20; $i++){
    if($i > 1 && $i % 2){
        $i = $i + 2;
    }
    if($i % 2 == 0) {
        echo $i;
    }
}


text:
Q: Git & GitHub - Too many branches to submit pull requests Here is the situation: I have a Fork from a Original Repo (Upstream).
So according to the document from GitHub: https://help.github.com/articles/creating-a-pull-request , we need to create a new branch to work on a feature, then push it to my Fork. Then use Pull Request to ask for a merge into original repo.
I understand that. But if each feature deserves a branch, then I will have a hundred/thousand of temporary branches in my local machine (and in my fork).
I know that after my Pull Request is accepted, I can merge those temporary branches into my Develop branch, and delete the branches. Am I doing correctly? Is it a correct flow for using Git and Pull Requests?

A: It is the recommended workflow (meaning isolating each PR in its own branch).
The guide "Tidying up Pull Requests" does illustrate that you can delete a PR branch in one click.
No need to merge anything: once merged in the main upstream repo, your local clone should update master from upstream/master (with upstream being the name of the remote referring to the main repo, the one you have forked): see "Pull new updates from original Github repository into forked Github repository".
More tips at "git push to the forked repo; pull request to a parent branch"


text:
Q: Proving a dimension inequality about two subspaces, one contained in the other. I have been asked to show the following:

Let $V$ and $W$ be subspaces of $\mathbb{R}^n$ such that $V\subseteq W$. Prove that $\dim(V)\leq \dim(W)$.

Can I say that since $V$ is less than $W$, that also means that $\dim(V)$ is less than $\dim(W)$ by definition of subspace? This is the only step I have so far.

A: If $\mathcal{B}$ is a basis of $V$, then $\mathcal{B}$ is a linearly independent subset of $W$. Hence $\dim W\ge|\mathcal{B}|=\dim V$.

A: Assuming both are finite dimensional:
let B be a basis for V.
if B is a basis for W then we are done.
If not add vectors to B until we have a basis in W.
This relies somewhat on the fact that if W is a finite dimensional vector space, then any linearly independent set of vectors from W has a lesser or equal dimension than the basis of W.


text:
Q: PySimpleGUI issue with Button trigger/click after it works once I'm new to using PySimpleGUI so bear with me. I wrote a script which randomly populates 4 rows of information, on the click of a button 'Generate'.
This works fine and I can click as often as I want, and every time it successfully re-generates the random for rows of string in the GUI.
Quit also works like a charm. However, I'm running into issues with the 'Change CSV Path' button.
The initial click of this button opens up a second GUI window, which asks users for a csv file path to replace the data set, and this works fine. You can close and such, and Submit with no issues.
No matter what you do in the CSV GUI, once the button has been clicked, it will not re-enable. You can click it a million times and it wont trigger again. Also, it doesn't matter what you did on the CSV GUI, the results are the same on the main GUI: the button 'Change CSV Path' doesn't work again.
I would like to know if this is something simple with using the while function within this, or if it's something else I'm missing!
Here is the code:
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 18 15:16:48 2021

@author: nikita twaalfhoven
"""
try:
    import PySimpleGUI as ui
except:
    print("The GUI is not installed. Run this in your Python command line:")
    print('pip install pysimplegui')

import listScripts as lists
import listObjects as objs

## ty
## https://pypi.org/project/PySimpleGUI/
## https://pysimplegui.readthedocs.io/en/latest/
## https://www.geeksforgeeks.org/themes-in-pysimplegui/

try:
    # build the lists
    lists.userChosenListsCSV('D:\Dropbox\Dropbox\Business\Lee Kim\WhoWhatWhy','sampleLee.csv')
    first = objs.Who
    second = objs.What
    third = objs.Why
    fourth = objs.Cons

    # Set theme for UI
    ui.theme('TealMono')
    # ui.theme_previewer()

    # Define the main pop-up layout
    layout = [  [ui.Text("Welcome to WhoWhatWhy MVP!")],
                [ui.Text("Hit the 'Generate' button below to play.")],
                [ui.Text("")],
                [ui.Text("Who:         "), ui.Text(size=(50,1), key ='-WHO-')],
                [ui.Text("What:        "), ui.Text(size=(50,1), key ='-WHAT-')],
                [ui.Text("Why:         "), ui.Text(size=(50,1), key ='-WHY-')],
                [ui.Text("Constraint: "), ui.Text(size=(50,1), key ='-CONS-')],
                [ui.Text("")],
                [ui.Button('Generate'), ui.Button('Change CSV Dataset'), ui.Button('Quit')]]

    # Create the main pop-up
    window = ui.Window("WhoWhatWhy MVP - Nikita Twaalfhoven", layout, resizable = True)

    # Define the CSV pop-up
    layoutCSV = [   [ui.Text("Add your CSV file path below, then hit 'Submit'")],
                    [ui.Text("Sample: 'C:\FolderName\sampleCSV.csv'")],
                    [ui.Input(key = '-INPUT-')],
                    [ui.Text("")],
                    [ui.Button('Submit')]]

    # Create the CSV pop-up
    windowCSV = ui.Window("New CSV - WhoWhatWhy MVP", layoutCSV, resizable = True)

    # The events loop
    while True:
        event, values = window.read()
        window.bring_to_front()

        # If user wants to Quit
        if event == ui.WIN_CLOSED or event == 'Quit':
            break

        # When Generate is hit
        if event == 'Generate':
            window['-WHO-'].update(first.getAnother(first))
            window['-WHAT-'].update(second.getAnother(second))
            window['-WHY-'].update(third.getAnother(third))
            window['-CONS-'].update(fourth.getAnother(fourth))

        # When the button is pressed for CSV
        if event == 'Change CSV Dataset':
            while True:
                event, values = windowCSV.read()
                window.bring_to_front()

                # If user wants to Quit
                if event == ui.WIN_CLOSED:
                    break

                if event == 'Submit':
                    path = values['-INPUT-']

                    if len(path) == 0:
                        ui.Popup("Please add a CSV path and then hit Submit. " +
                                 "Otherwise, close the CSV dialog.",
                                 title="Empty Path")

                    elif len(path) > 6 and path[len(path)-4] == ".":
                        lists.userChosenListsCSV(path)
                        first = objs.Who
                        second = objs.What
                        third = objs.Why
                        fourth = objs.Cons

                        window['-WHO-'].update(first.getAnother(first))
                        window['-WHAT-'].update(second.getAnother(second))
                        window['-WHY-'].update(third.getAnother(third))
                        window['-CONS-'].update(fourth.getAnother(fourth))
                        ui.Popup("CSV imported!", title="Success")
                        break
                    else:
                        ui.Popup("The CSV couldn't be updated.", title="Error")
                        break
            windowCSV.close()

    # Remove when done
    window.close()

except:
    ui.Popup("An error occured: " + str(ValueError))

EDIT: for Torben
I tried adding the windowCSV = .. line into the first loop, and this error I received:
[![Error after moving 'windowCSV = ..' into the loop][1]][1]

-------------------------------------------------------------------------

EDIT:
I've tried making the layout a function, and the issue persists non the less, see adjusted script below:

# -*- coding: utf-8 -*-
"""
Created on Mon Jan 18 15:16:48 2021

@author: nikita twaalfhoven
"""
try:
    import PySimpleGUI as ui
except:
    print("The GUI is not installed. Run this in your Python command line:")
    print('pip install pysimplegui')

import listScripts as lists
import listObjects as objs

## ty
## https://pypi.org/project/PySimpleGUI/
## https://pysimplegui.readthedocs.io/en/latest/
## https://www.geeksforgeeks.org/themes-in-pysimplegui/

def createWindow(ui,title,layout):
    # To create a window for the GUI

    return ui.Window(title,layout, resizable = True)

def layoutMain(ui):
    # Define the main pop-up layout
    return [  [ui.Text("Welcome to WhoWhatWhy MVP!")],
                [ui.Text("Hit the 'Generate' button below to play.")],
                [ui.Text("")],
                [ui.Text("Who:         "), ui.Text(size=(50,1), key ='-WHO-')],
                [ui.Text("What:        "), ui.Text(size=(50,1), key ='-WHAT-')],
                [ui.Text("Why:         "), ui.Text(size=(50,1), key ='-WHY-')],
                [ui.Text("Constraint: "), ui.Text(size=(50,1), key ='-CONS-')],
                [ui.Text("")],
                [ui.Button('Generate'), ui.Button('Change CSV Dataset'), ui.Button('Quit')]]

def layoutCSV(ui):
    # Define the CSV pop-up
    return [   [ui.Text("Add your CSV file path below, then hit 'Submit'")],
                    [ui.Text("Sample: 'C:\FolderName\sampleCSV.csv'")],
                    [ui.Input(key = '-INPUT-')],
                    [ui.Text("")],
                    [ui.Button('Submit')]]

try:
    # build the lists
    lists.userChosenListsCSV('D:\Dropbox\Dropbox\Business\Lee Kim\WhoWhatWhy','sampleLee.csv')
    first = objs.Who
    second = objs.What
    third = objs.Why
    fourth = objs.Cons

    # Set theme for UI
    ui.theme('TealMono')
    # ui.theme_previewer()

    # Create the main pop-up
    window = createWindow(ui,"WhoWhatWhy MVP - Nikita Twaalfhoven", layoutMain(ui))

    # Create the CSV pop-up
    windowCSV = createWindow(ui,"New CSV - WhoWhatWhy MVP", layoutCSV(ui))

    # The events loop
    while True:
        event, values = window.read()
        window.bring_to_front()

        # If user wants to Quit
        if event == ui.WIN_CLOSED or event == 'Quit':
            break

        # When Generate is hit
        if event == 'Generate':
            window['-WHO-'].update(first.getAnother(first))
            window['-WHAT-'].update(second.getAnother(second))
            window['-WHY-'].update(third.getAnother(third))
            window['-CONS-'].update(fourth.getAnother(fourth))

        # When the button is pressed for CSV
        if event == 'Change CSV Dataset':

            while True:
                event, values = windowCSV.read()
                windowCSV.bring_to_front()

                # If user wants to Quit
                if event == ui.WIN_CLOSED:
                    break

                if event == 'Submit':
                    path = values['-INPUT-']

                    if len(path) == 0:
                        ui.Popup("Please add a CSV path and then hit Submit. " +
                                 "Otherwise, close the CSV dialog.",
                                 title="Empty Path")

                    elif len(path) > 6 and path[len(path)-4] == ".":
                        lists.userChosenListsCSV(path)
                        first = objs.Who
                        second = objs.What
                        third = objs.Why
                        fourth = objs.Cons

                        window['-WHO-'].update(first.getAnother(first))
                        window['-WHAT-'].update(second.getAnother(second))
                        window['-WHY-'].update(third.getAnother(third))
                        window['-CONS-'].update(fourth.getAnother(fourth))
                        ui.Popup("CSV imported!", title="Success")
                        break
                    else:
                        ui.Popup("The CSV couldn't be updated.", title="Error")
                        break
            windowCSV.close()

    # Remove when done
    window.close()

except:
    ui.Popup("An error occured: " + str(ValueError))

A: After first time Change CSV Dataset event generated, you do something, and after that you close the window windowCSV. So next time, no window windowCSV shown.
It's better to create function and return the window, so you need to call that function to generate the window again.
It's important, not to use the layout again. It means elements should called again, not just to use the variable layout for generation of a new window.
simple example for it
layout = [[sg.Button('OK')]]
window = sg.Window('Title', layout) # <--- OK
window.close()
window = sg.Window('Title', layout) # <--- NG, reuse layout
window.close()

layout = [[sg.Button('OK')]]
window = sg.Window('Title', layout) # <--- OK
window.close()
layout = [[sg.Button('OK')]]
window = sg.Window('Title', layout) # <--- OK
window.close()

def layout():
    return [[sg.Button('OK')]]

window = sg.Window('Title', layout())   # <--- OK
window.close()
window = sg.Window('Title', layout())   # <--- OK
window.close()

So your code updated as following
"""
layoutCSV = [   [ui.Text("Add your CSV file path below, then hit 'Submit'")],
                [ui.Text("Sample: 'C:\FolderName\sampleCSV.csv'")],
                [ui.Input(key = '-INPUT-')],
                [ui.Text("")],
                [ui.Button('Submit')]]

windowCSV = ui.Window("New CSV - WhoWhatWhy MVP", layoutCSV, resizable = True)
"""
def new_CSV_window():
    layoutCSV = [
        [ui.Text("Add your CSV file path below, then hit 'Submit'")],
        [ui.Text("Sample: 'C:\FolderName\sampleCSV.csv'")],
        [ui.Input(key = '-INPUT-')],
        [ui.Text("")],
        [ui.Button('Submit')]
    ]
    return ui.Window("New CSV - WhoWhatWhy MVP", layoutCSV, resizable = True)

"""
if event == 'Change CSV Dataset':
    while True:
"""
if event == 'Change CSV Dataset':
    windowCSV = new_CSV_window_window()
    while True:

A: Thank you Jason Yang & Torben Klein, the issue was answered when I combined both of your answers:
I defined the layouts within a function (per Jason's answer), and then moved the call to the window creation into the while loop (per Torben's suggestion). This now works!
The code which runs is as follows:
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 18 15:16:48 2021

@author: nikita twaalfhoven
"""
try:
    import PySimpleGUI as ui
except:
    print("The GUI is not installed. Run this in your Python command line:")
    print('pip install pysimplegui')

import listScripts as lists
import listObjects as objs

## ty
## https://pypi.org/project/PySimpleGUI/
## https://pysimplegui.readthedocs.io/en/latest/
## https://www.geeksforgeeks.org/themes-in-pysimplegui/

def createWindow(ui,title,layout):
    # To create a window for the GUI

    return ui.Window(title,layout, resizable = True)

def layoutMain(ui):
    # Define the main pop-up layout
    return [  [ui.Text("Welcome to WhoWhatWhy MVP!")],
                [ui.Text("Hit the 'Generate' button below to play.")],
                [ui.Text("")],
                [ui.Text("Who:         "), ui.Text(size=(50,1), key ='-WHO-')],
                [ui.Text("What:        "), ui.Text(size=(50,1), key ='-WHAT-')],
                [ui.Text("Why:         "), ui.Text(size=(50,1), key ='-WHY-')],
                [ui.Text("Constraint: "), ui.Text(size=(50,1), key ='-CONS-')],
                [ui.Text("")],
                [ui.Button('Generate'), ui.Button('Change CSV Dataset'), ui.Button('Quit')]]

def layoutCSV(ui):
    # Define the CSV pop-up
    return [   [ui.Text("Add your CSV file path below, then hit 'Submit'")],
                    [ui.Text("Sample: 'C:\FolderName\sampleCSV.csv'")],
                    [ui.Input(key = '-INPUT-')],
                    [ui.Text("")],
                    [ui.Button('Submit')]]

try:
    # build the lists
    lists.userChosenListsCSV('D:\Dropbox\Dropbox\Business\Lee Kim\WhoWhatWhy','sampleLee.csv')
    first = objs.Who
    second = objs.What
    third = objs.Why
    fourth = objs.Cons

    # Set theme for UI
    ui.theme('TealMono')
    # ui.theme_previewer()

    # Create the main pop-up
    window = createWindow(ui,"WhoWhatWhy MVP - Nikita Twaalfhoven", layoutMain(ui))

    # The events loop
    while True:
        event, values = window.read()
        window.bring_to_front()

        # If user wants to Quit
        if event == ui.WIN_CLOSED or event == 'Quit':
            break

        # When Generate is hit
        if event == 'Generate':
            window['-WHO-'].update(first.getAnother(first))
            window['-WHAT-'].update(second.getAnother(second))
            window['-WHY-'].update(third.getAnother(third))
            window['-CONS-'].update(fourth.getAnother(fourth))

        # When the button is pressed for CSV
        if event == 'Change CSV Dataset':

            # Create the CSV pop-up
            windowCSV = createWindow(ui,"New CSV - WhoWhatWhy MVP", layoutCSV(ui))

            while True:
                event, values = windowCSV.read()
                windowCSV.bring_to_front()

                # If user wants to Quit
                if event == ui.WIN_CLOSED:
                    break

                if event == 'Submit':
                    path = values['-INPUT-']

                    if len(path) == 0:
                        ui.Popup("Please add a CSV path and then hit Submit. " +
                                 "Otherwise, close the CSV dialog.",
                                 title="Empty Path")

                    elif len(path) > 6 and path[len(path)-4] == ".":
                        lists.userChosenListsCSV(path)
                        first = objs.Who
                        second = objs.What
                        third = objs.Why
                        fourth = objs.Cons

                        window['-WHO-'].update(first.getAnother(first))
                        window['-WHAT-'].update(second.getAnother(second))
                        window['-WHY-'].update(third.getAnother(third))
                        window['-CONS-'].update(fourth.getAnother(fourth))
                        ui.Popup("CSV imported!", title="Success")
                        break
                    else:
                        ui.Popup("The CSV couldn't be updated.", title="Error")
                        break
            windowCSV.close()

    # Remove when done
    window.close()

except:
    ui.Popup("An error occured: " + str(ValueError))


text:
Q: Custom Login with htaccess through HTML/PHP I'm working on a site with a directory that is protected with htaccess. I'd like to create a custom login page instead of relying on the browser default. Anyone have any experience with this?
I want to connect via a HTML form. Anyone think is it possible?
Thanks.

A: Yes it's possible but you shouldn't use the htaccess digest authentication, you have to implement a custom Login Form in HTML & PHP.
You can implement something like this in PHP & htaccess
admin/.htaccess:
RewriteCond %{REQUEST_FILENAME} !check_auth.php
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule .* check_auth.php?file=$0 [QSA,L] # pass everything thru php

admin/check_auth.php:
$file = $_GET['file'];

if($_SESSION['user_authenticated']) {
  // please mind you need to add extra security checks here (see comments below)
   readfile($file); // if it's php include it. you may need to extend this code
}else{
  // bad auth error
}

you can access directory files like this
check_auth.php?file=filename


text:
Q: IOS 8.4 UIActivityViewController Viber crush I use UIActivityViewController for posting text and image to socials. When I tap Viber, it give me console messages:
1)plugin com.viber.app-share-extension interrupted
2)Hub connection error Error Domain=NSCocoaErrorDomain Code=4097 "The operation couldn't be completed. (Cocoa error 4097.)" (connection to service named com.viber.app-share-extension) UserInfo=0x14f51ef0
Code:
NSArray *shareItems = @[ image, message];

UIActivityViewController *activityController = [[UIActivityViewController alloc] initWithActivityItems:sharingArray
                                                                            applicationActivities:nil;
[self presentViewController:ac animated:YES completion:nil];'

How to fix it? Or how to catch exception from UIActivityViewController?


text:
Q: Error extracting XML values in PostgreSQL using XPath: SQL Error [42601]: ERROR: syntax error at or near "[" I'm trying to extract values from XML stored in the PostgreSQL DB using XPath. I've got an error:

SQL Error [42601]: ERROR: syntax error at or near "["

My SQL is:
-- Find "e" nodes which have "p1" child nodes and does not have "p3" child nodes
WITH tbl(p_xml) AS (
   SELECT '<root>
    <e id="1">
        <p1>P1</p1>
        <p2>P2</p2>
    </e>
    <e id="2">
        <p1>P1</p1>
        <p3>P2</p3>
    </e>
    <e id="3">
        <p2>P1</p2>
        <p3>P3</p3>
    </e>
</root>'::xml
)
select *
FROM   tbl
where
    (xpath('count(/root/e/p1)', p_xml)[1]::text)::int > 0 and
    (xpath('count(/root/e/p3)', p_xml)[1]::text)::int = 0

I've seen plenty of examples on StackOverflow with using squares to get data (as xpath function returns array), but all of them fails with the same error on my PostgreSQL. I tried this on PostgreSQL DB versions 9.6 and 10.1 with no luck.

A: That's because your query lacks a brackets. Anyways, if you want to return just e elements that fulfill that condition you'll need to shred the XML, for example :
WITH tbl(p_xml) AS (
   SELECT '<root>
    <e id="1">
        <p1>P1</p1>
        <p2>P2</p2>
    </e>
    <e id="2">
        <p1>P1</p1>
        <p3>P2</p3>
    </e>
    <e id="3">
        <p2>P1</p2>
        <p3>P3</p3>
    </e>
</root>'::xml
)
SELECT e
FROM tbl
CROSS JOIN LATERAL UNNEST(xpath('//e[p1 and not(p3)]', p_xml)) e

rextester demo: http://rextester.com/FZGP41665

A: I'm not experienced with postgresql, but this seems to work:
where
    (xpath('count(/root/e/p1)', p_xml)::text[])[1]::int > 0 and
    (xpath('count(/root/e/p3)', p_xml)::text[])[1]::int = 0

It looks, as if xpath() must be casted to an array of string, where you pick the first element to cast it to int. Not very intuitive.
There might be a better approach...


text:
Q: complex reductive Lie groups which are not defined over the real numbers Hello
Someone knows something about the complex reductive Lie groups (the complexification of a compact Lie group) which are not defined over the real numbers. I would like to know, if is it possible, an simple example.
I appreciate any help or references.


text:
Q: Duplicate data in a table given table name For a performance testing application we need to have lot more data in our tables than what we have now. How do I duplicate the data in a table.
In the process of duplicating I also need to set new values for primary key column. I'm thinking getting the max value of primary key column and adding a incrementing number to it will solve the primary key issue.
Is it possible to do this in PL/SQL.
-- more information
This table have over 200 columns and 3 unique keys (there are no table level constants), all the operations are happening through views and oracle packages, these packages are responsible for keeping the primary key combination unique. In the duplication process If I could add a incrementing value (starting with max+1 of the column) to a single column I can keep the uniqueness of the key combination.

A: I like to use rownum. Using a CTE to get the current maximum PK value, you can easily double-up your data.
Example below.
Test table:
create table yourperftest
( pk number,
  col1 number,
  col2 number,
  col3 number
);

Test data:
insert into yourperftest values (1,1,1,1);
insert into yourperftest values (2,2,2,2);
insert into yourperftest values (3,3,3,3);
insert into yourperftest values (4,4,4,4);
insert into yourperftest values (5,5,5,5);

Query to "double up" the table:
insert into yourperftest
with maxvalue as (
  select max(pk) as maxvalue
  from yourperftest
)
select rownum+maxvalue, col1, col2, col3
from yourperftest,maxvalue;

I'd probably use an /*+APPEND*/ hint too, plus make sure you gather stats on the table afterwards.
Having said that, stats play a big part in testing - you want to make sure that your data/performance test environment is as close to production as possible. Going forward, the stats are the key to this. Stats that are different between test and production will cause different query plans to be picked by the optimiser, which may make your performance testing invalid when production is going tits-up.
EDIT:
Since you ask about doing this for more than 1 column, here's another example:
 insert into yourperftest
with maxvalue as (
  select max(pk) as maxvalue
  from yourperftest
), col1tab as (
   select max(col1) as col1maxvalue
   from yourperftest
)
select rownum+maxvalue, col1maxvalue+rownum, col2, col3
from yourperftest,maxvalue,col1tab ;

CTEs are brilliant.

A: Take a look here - point 2 here (recipes for disaster),
2. We will check data integrity at the application level instead of taking advantage of Oracle's constraint checking abilities.

Jonathan Lewis is the man for Oracle and indexes.
If I were you, I would do something like (works in MySQL and PostgreSQL, don't have Oracle up and running at the moment).
mysql>
mysql>
mysql> create table billy (fred INT PRIMARY KEY AUTO_INCREMENT, mary INT);
Query OK, 0 rows affected (0.30 sec)

mysql> INSERT INTO billy (mary) VALUES( 3);
Query OK, 1 row affected (0.06 sec)

mysql> INSERT INTO billy (mary) VALUES( 4);
Query OK, 1 row affected (0.06 sec)

mysql> INSERT INTO billy (mary) VALUES( 5);
Query OK, 1 row affected (0.04 sec)

mysql> SELECT * FROM billy;
+------+------+
| fred | mary |
+------+------+
|    1 |    3 |
|    2 |    4 |
|    3 |    5 |
+------+------+
3 rows in set (0.00 sec)

mysql> INSERT INTO billy (mary) SELECT mary FROM billy;
Query OK, 3 rows affected (0.05 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> select * from billy;
+------+------+
| fred | mary |
+------+------+
|    1 |    3 |
|    2 |    4 |
|    3 |    5 |
|    4 |    3 |
|    5 |    4 |
|    6 |    5 |
+------+------+
6 rows in set (0.00 sec)

mysql>

So, it's possible to do the first part without the use of CTEs


text:
Q: Only left hand column items in a 2 by 2 grid are transitioning margin on hover I can't work out why my left hand column's margin transitions on hover, but not the right side?
At first I thought it was my a tags, making them display:block has not enabled the right hand column to transition.
I am using a selector [class^="col-"] as a column's width may change. Will this have something to do with its failure?

.wrapper {
  padding-left:3vw;
  padding-right:3vw;
}

main {
  padding-top:200px;
  padding-bottom:200px;
}

h2 {
  line-height: 1.3;
  letter-spacing: .046rem;
  font-size: 3.5rem
}

.col-5-5 {
  width:45%
}

a,a:hover,a:visited,a:focus,a:active {
  color:black;
  text-decoration:none;
}

.pic {
  padding-bottom:65%;
}

.column {
  float:left;
  display:block;
}

.column.right {
  float:right
}

.vogue-grid .item {
  display:block
}

.vogue-grid .item > [class^="col-"] {
  -webkit-transition: margin 300ms ease;
  -moz-transition: margin 300ms ease;
  transition: margin 300ms ease;
}

.vogue-grid .item > [class^="col-"] > .description {
  display: flex;
  margin: 12px 0 65px 0;
}

.vogue-grid .item:hover > [class^="col-"] {
  margin-left: 3vw
}

.vogue-grid .item > [class^="col-"] > .description > .insert {
  padding: 12px 0;
  margin-right: 16%
}

                                        2018

Calendar

                                        2018

Arts

A: I believe this is because of the float: right; applied to the right item. It's already stuck to the right so the margin-left doesn't seem to affect the layout.


text:
Q: Raise Parent event from the User Control in SharePoint 2010 I have created Custom User control which i am using in my application Page(which is deployed at _layouts folder).
Here is my scenario.
I have a save button in my custom user control, when i click on that control i would like to execute a method in .aspx(which is layout page).  How can i acheive this ?  Any ideas ?
Thanks in advance.

A: This is really not a SharePoint question but here you can find an answer:
Calling a method in parent page from user control
I never actually done this but by looking at code there is nothing special and it should work on SharePoint. Of course instead of System.Web.UI.Page you are using Microsoft.SharePoint.WebControls.LayoutsPageBase


text:
Q: Is there a way to initiate the save-as modal with a button click using node? I hope you can help.
I am using node, express, router and ejs.
A use case is: I am on http://localhost:8080/save/page1 and in order to save the page I need to right-click and save-as.
Ideally I want the user to be able to initiate the save-as modal by clicking on a button on the page.
Is there a way to initiate the right-click > save-as modal?
I have tried Googling with little success. I'm probably Googling all wrong.
Thanks for all your help. It's much appreciated.
Moe


text:
Q: Can example "GLImageProcessing" work with multi filters I use the example GLImageProcessing, but it can not process the image with both brightness and contrast, so i write the code to adjust both brightness and contrast, but it can't work at all, can anybody can help me about this, thank you for review
//init
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrthof(0, wide, 0, high, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glScalef(wide, high, 1);
glBindTexture(GL_TEXTURE_2D, Input.texID);

//bind result fbo
glBindFramebufferOES(GL_FRAMEBUFFER_OES, resultFBO);
glViewport(0, 0, result.wide*result.s, result.high*result.t);
glClear(GL_COLOR_BUFFER_BIT);
glDisable(GL_BLEND);

//process 1 adjust brightness
float t = 1.2;
glVertexPointer  (2, GL_FLOAT, sizeof(V2fT2f), &flipquad[0].x);
glTexCoordPointer(2, GL_FLOAT, sizeof(V2fT2f), &flipquad[0].s);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE);

static GLfloat constColor[4] = { 0.1, 0.2, 0.3, 0.4 };
if (t > 1.0f)
{
    glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB,      GL_ADD);
    //glColor4f(t-1, t-1, t-1, t-1);
    constColor[0] = t-1;
    constColor[1] = t-1;
    constColor[2] = t-1;
    constColor[3] = t-1;
}
else
{
    glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB,      GL_SUBTRACT);
    constColor[0] = 1-t;
    constColor[1] = 1-t;
    constColor[2] = 1-t;
    constColor[3] = 1-t;
}

glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, constColor);

glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_RGB,         GL_TEXTURE);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC1_RGB,         GL_CONSTANT);
glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA,    GL_REPLACE);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_ALPHA,       GL_TEXTURE);

//process 2 adjust contrast
t = 1.6;
GLfloat h = t*0.5f;

// One pass using two units:
// contrast < 1.0 interpolates towards grey
// contrast > 1.0 extrapolates away from grey
//
// Here, the general extrapolation 2*(Src*t + Dst*(0.5-t))
// can be simplified, because Dst is a constant (grey).
// That results in: 2*(Src*t + 0.25 - 0.5*t)
//
// Unit0 calculates Src*t
// Unit1 adds 0.25 - 0.5*t
// Since 0.5*t will be in [0..0.5], it can be biased up and the addition done in signed space.
glActiveTexture(GL_TEXTURE1);
glEnable(GL_TEXTURE_2D);
//glVertexPointer  (2, GL_FLOAT, sizeof(V2fT2f), &flipquad[0].x);
//glTexCoordPointer(2, GL_FLOAT, sizeof(V2fT2f), &flipquad[0].s);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE);
glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB,      GL_MODULATE);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_RGB,         GL_PREVIOUS);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC1_RGB,         GL_PRIMARY_COLOR);
glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA,    GL_REPLACE);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_ALPHA,       GL_PREVIOUS);

glDisable(GL_TEXTURE_2D);
glActiveTexture(GL_TEXTURE2);
glEnable(GL_TEXTURE_2D);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE);
glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB,      GL_ADD_SIGNED);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_RGB,         GL_PREVIOUS);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC1_RGB,         GL_PRIMARY_COLOR);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB,     GL_SRC_ALPHA);
glTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE,        2);
glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA,    GL_REPLACE);
glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_ALPHA,       GL_PREVIOUS);

glColor4f(h, h, h, 0.75 - 0.5 * h); // 2x extrapolation
validateTexEnv();
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

//save to file
snapshot(result,"/test3.jpg");

// Restore state
glDisable(GL_TEXTURE_2D);
glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB,     GL_SRC_COLOR);
glTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE,        1);
glActiveTexture(GL_TEXTURE0);
//process 3 adjust hue

//process 4 mask

//save to buffer

//bind system rbo
glBindFramebufferOES(GL_FRAMEBUFFER_OES, SystemFBO);
glCheckError();

A: Using multitexturing, it should be possible to find a solution to this problem that would do the trick in one pass. Unfortunately, the first iPhone's PowerVR MBX GPU only features 2 texture units (the minimum required by the OpenGL ES 1.1 standard) which would not be enough to apply both filters. I think more recent hardware can have up to eight texture units and a single pass solution could be found.
A more generic approach, that will allow you to apply as many filters as you want, is to use frame buffer objects to literally "render-to-texture". Here is a link to another post that outlines the technique: OpenGL ES Render to texture.
Basically, you must apply the first filter to the original image and store the result in a texture (instead of the system provided frame buffer). Then use the result texture which contains the filtered image as input for the next filter and, again, render to texture. Repeat until you reach the very last filter of the chain. At this point, restore the original frame buffer object before doing your rendering in order to be able to display the result on screen.
Here is some sample code on how to do it for 2 filters:
// Remember the FBO being used for the display framebuffer
glGetIntegerv(GL_FRAMEBUFFER_BINDING_OES, (GLint *)&SystemFBO);

// Create the texture and the FBO the will hold the result of applying the first filter
glGenTextures(1, &ResultTexture);
glBindTexture(GL_TEXTURE_2D, ResultTexture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glGenFramebuffersOES(1, &ResultFBO);
glBindFramebufferOES(GL_FRAMEBUFFER_OES, ResultFBO);
glFramebufferTexture2DOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_TEXTURE_2D, ResultTexture, 0);

// bind the result FBO
glBindFramebufferOES(GL_FRAMEBUFFER_OES, ResultFBO);

// apply 1st filter
...

// restore original frame buffer object
glBindFramebufferOES(GL_FRAMEBUFFER_OES, SystemFBO);

// use ResultTexture as input for the 2nd filter
glBindTexture(GL_TEXTURE_2D, ResultTexture);

// apply 2nd filter
...


text:
Q: How to use "OR" using Django's model filter system? It seems that Django's object model filter method automatically uses the AND SQL keyword.
For example:
>>> Publisher.objects.filter(name__contains="press", country__contains="U.S.A")

will automatically translate into something like:
SELECT ...
FROM publisher
WHERE name LIKE '%press%'
AND country LIKE '%U.S.A.%'

However, I was wondering whether there was a way to make OR? I can't seem to find it in the documentation (oddly enough, searching for 'or' isn't really useful).

A: You can use Q objects to do what you want, by bitwise OR-ing them together:
from django.db.models import Q
Publisher.objects.filter(Q(name__contains="press") | Q(country__contains="U.S.A"))

A: Without Q(), you can also run OR operater as shown below:
Publisher.objects.filter(name__contains="press") | \
Publisher.objects.filter(country__contains="U.S.A")


text:
Q: Cordova Ios Assets Catalog Compiler error on Xcode 9.4 I have this error when excecute the cordova app in iphone device:
/Users/myuser/Desktop/myionicCordovaproject/platforms/ios/MyprojectName/Images.xcassets: error: Failed to write image data for the launch image set from "LaunchImage.launchimage/Default-Portrait@2x~ipad.png" to "/Users/myuser/Library/Developer/Xcode/DerivedData/myProjectName-agddjdisjisxvgbuefjxrhzmruvc/Build/Products/Debug-iphoneos/myProjectName.app/LaunchImage-Portrait@2x~ipad.png".
Underlying Errors:
    Description: pngcrush exited with signal '6' for "/Users/myuser/Desktop/myionicCordovaproject/platforms/ios/myProjectName/Images.xcassets/LaunchImage.launchimage/Default-Portrait@2x~ipad.png".
Error output:
dyld: Library not loaded: /System/Library/Frameworks/OpenDirectory.framework/Versions/A/Frameworks/CFOpenDirectory.framework/Versions/A/CFOpenDirectory
  Referenced from: /System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/OSServices.framework/Versions/A/OSServices
  Reason: malformed mach-o: load commands size (1533929015) > 32768

This error only present with compile the app in phisical devices , in emulator not present error.
My system information:
Cordova CLI: 8.0.0
Gulp version:  CLI version 2.0.1
Gulp local:   Local version 3.9.1
Ionic Framework Version: 1.2.4-nightly-1917
Ionic CLI Version: 2.0.0
Ionic App Lib Version: 2.0.0-beta.20
ios-deploy version: 2.0.0
ios-sim version: 7.0.0
OS: Mac OS X El Capitan
Node Version: v4.8.0
Xcode version: Xcode 9.4.1 Build version 9F2000


text:
Q: Comparing amount of variation due to different variables in ANOVA We have performed the same experiment under a bunch of different conditions, and now wish to know which type of change in condition caused the greatest variation in results. I.e., do results vary more when different people do the same experiment in the same location, than if the same person does the experiment in multiple locations. We are not interested in whether 'location' or 'experimenter' in itself has a statistically significant influence on the outcome, but rather a comparison of the likely effect sizes.
What is the best way to go about it? It seems that 'ANOVA' is probably somewhere in the answer? At first we thought we should simply take the 'mean squared error', but then we got to thinking that since the F-values and the p-values seem to take more information into account, those might be more accurate for comparing variables. It should be noted that there is a mixture of nominal and ordinal variables, and they have different degrees of freedom.
It feels like using p-values might unintentionally conflate 'likelihood of having an effect' with 'size of effect', but are those two questions meaningfully different when the answer is extracted from the same data set like this?
I hope the question(s) make sense.


text:
Q: Session not preserving state in MOSS 2007 I have created a button that will load a page that contains a PDF document that users can fill out and save.  After the save is clicked, the page posts-back and there is code to save the changes.  However, I'm not able to get the session to preserve the value after postback.  I have it enabled on the site and in the web.config.  When the button is initially clicked and the page with the PDF is loaded, the ItemId gets pulled from the query string and stored in the session state variable.  The next the page posts-back is when the user clicks the button to save the PDF, but at this point, the session state gets reset and even gets assigned a new unique identifier.  Does anyone know a way to prevent this from happening?
 protected void Page_Load(object sender, EventArgs e)
    {
        itemId = Request.QueryString["ItemId"];

        if (Session["ItemId"] == null || Session["ItemId"] != itemId){
            //HttpContext.Current.Session["ItemId"] = itemId;
            Session["ItemId"] = itemId;
        }

        if (!PostBackFromPDF())
        {
            //-- Generate the pdf or display pre-existing message
            GenerateOutput(itemId);
        }
        else
        {
            string savedValue = string.Empty;

            if (Session["ItemId"] != null)
            {
                savedValue = Session["ItemId"].ToString();
                itemId = savedValue;
            }

            //-- Post Back From PDF Form
            ProcessReportAction(itemId);
        }

    }

Thanks in advnce

A: Ever thought of using the viewstate to store the itemid instead of the session state?

A: I did get this working, but it looks like it wasn't really a problem of session.  We ended up setting the session in a different page and it worked.


text:
Q: WordPress usermeta scaling for thousands of users I have developed a CRM plugin for a client integrated with WordPress user management and I stored additional information for each user under the wp_usermeta table.
However, the client's customer database is growing exponentially, and we are now in the thousands, which gives us several tens of thousands rows in wp_usermeta: at this point I am starting to be worried about scalability of this architecture.
Does anybody have any experience on managing such an amount of users the WordPress way? Should I add columns to the wp_users table instead of relying on the wp_usermeta one? How can I diagnose/profile WordPress and my own code performance at this stage?
I have never worked on such an amount of data and at this increasing rate, and any pointer would be valuable.

A: Unless you are running your own queries instead of using the API, the size of table doesn't matter that much as wordpress runs queries by the indexes of the table and MYSQL supposed to optimize this kind of queries. Each query also fetches all meta information in one query.
If you insist you can split the user meta table into several tables using an hash on the user ID as the table name, but then you will probably have to write a replacement to the wp_db class to access the right table based on the query. If you are interested in following this path then look for solutions for handling big network installs with many blogs.
But if you don't have any performance issues now then you can grow much further without doing any significant adjustment. When you start getting performance issues just move the DB to a faster server, it will be more cost effective than any manipulation you can do to the way WP access that info.

A: The size of the table isn't really the issue, the queries you're running on that table might be.
For example, if you're selecting users based on data stored in the user-meta table, then that query will be highly unoptimized, because meta_value is not an indexed field. In which case you may need to add extra indexes or consider storing that particular data in a different manner, such as with a custom taxonomy.
Generally speaking, stuff that you store as meta should never be something that you will exclusively search based on. This applies across all the meta tables in WordPress. Meta is mainly designed to be pulled out by the meta_key, not by the meta_value. Taxonomies limit the possible values to a set and organize the information differently, so they do better when the "value" counts as what you're selecting on.
Note, selecting by both meta_key and meta_value is generally okay, because mySQL will optimize the query to be based on the meta_key first, reducing the amount of data to search to a (hopefully) manageable limit. If even this becomes a problem, you can "fix" it by adding a new index to the meta table with both meta_key and meta_value on the index, however because meta_value is LONGTEXT, you need to limit the length of that index to something reasonable, like 20-30 or something, depending on your data. Note that this index may be much, much larger than your actual data and will drastically increase the storage space needed. However, it will be much faster at those types of queries. Consult a qualified DBA if this ever becomes a real issue.
For reference, on WordPress.org we have approximately 11 million users registered. The amount of meta varies per user, with probably a minimum of 8 rows per, and maybe a max of around 250-ish. The users table is about 2.5 GB, the usermeta table around 4 GB. Seems to run okay, for the most part, but every once in a while we find some oddball query that we have to go optimize.


text:
Q: How do you source control .code-workspace files? In VS Code there is this concept of a workspace that can contain folders, settings, recommended (and ignored) extensions, launch configurations and tasks. Semantically a workspace is hierarchically above the folder/repo concept, i.e. a workspace contains (zero or more) folders. This being the case, it makes sense for a .code-workspace file to be outside it's root folders/repositories.
Folder structure example:
/Repos/
    /repository1/           <= Source controlled
    /repository2/           <= Source controlled
    repos.code-workspace    <= Not source controlled

This begs the question: how do you keep .code-workspace files source controlled and how do you share them with your team?


text:
Q: In OpenCart, I have a permission denied message In OpenCart, I have a permission denied message.
I upgraded from Opencart 2.0.2.0 to opencart 2.2.2.0
Suddenly I cannot view anything except for the dashboard
Please click to see the problem
I don't know what cause this issue and why it happened after upgrading the CMS
I tried to add a user via PhPMyadmin and it did not work
Please advise
Regards


text:
Q: Middleware логгер Laravel 5.2 Хочу сделать запись в логи действий пользователя:
switch ($request->segment(2)) {
    case 'login':
        $request->method() != "POST" ?: \Log::info(auth()->user()->id .  ' user is login');
        break;
    case 'logout':
        \Log::info(auth()->user()->id . ' user is logout');
        break;
    case 'register':
        $request->method() != "POST" ?: \Log::info(auth()->user()->id . ' is register');
        break;
}
return $next($request);

При действии login выдает ошибку:

Trying to get property of non-object

Добавил $response = $next($request); все работает, но хотелось бы улучшить код, как можно это сделать?

A: Думаю, дело в том, что если пользователь еще не существует, при попытке выполнить auth()->user()->id  и возникает ошибка. Короче правильнее проверять, есть ли пользователь в системе.


text:
Q: Monitoring file changes in Docker volumes I have a docker container that is running a python script: waiting for input requests and processing data accordingly.
Since I am using docker for development, I would like that, whenever I change the source code of that python file (in my machine, not the container), the container would stop the python script and relaunch it with the new code. Because right now I have to manually stop the container and relaunch it. I could also monitor the file changes on my side (rather than inside the container) but I would like to avoid that and do it within the container itself.
I am using docker-compose's volumes option to share the source code between my FS and the container's.
To monitor the file changes, I've been trying to use the watchmedo shell utility from the the watchdog python module. I just have this weird problem that I can't notice the file changes of that python source file unless I am editing it from the inside of the container and not in my local FS, even though they are mounted with the volumes option.
I get the feeling that this is something to do with how docker works and maybe the volumes thing too. I've been trying to read up on it online, but didn't get much luck. Any ideas? I'm totally stuck!
EDIT: Here's a gif that better explains it. The top to panes are connected to the same container and the bottom two to my local machine. All the panes are pointed to the same folder.

A: You could have your container run something like this ( need inotify installed ):
while true
do
        inotifywait -e create -e modify  /path/to/python/script
        pkill python
        python /path/to/python/script
done

Basically wait for changes on the file, kill python on the machine, run script again.
If the python script is not running in the background/deamonized in any way you could use an & like so: the python /path/to/python/script &
Put this into run.sh, add something like this to your Dockerfile
COPY run.sh /run.sh
CMD ["bash", "-l", "/run.sh"]

... and you should be good.


text:
Q: Many bookmark icons changed in Chrome; how to efficiently change them back? Days ago, I had many bookmark icons changed in this way:
Then I followed Synetech's advice at How to refresh bookmark favicons in chrome and that worked to correct the bookmark icons at the sites I revisited.
If I open each website, I get the correct icon again.  If it's already bookmarked with the strange icon, I delete it and save it again.  But, I have hundreds of bookmarked websites.  Therefore, I'm looking for a way to get all correct icons back.
Is there a more efficient way to do this than manually revisiting every one of those websites?


text:
Q: Oracle parameter with Dapper issue I am struggling with using ORACLE parameters via DAPPER. The error message received is "ORA-00942: table or view does not exist".
However the code works without the parameter, and I suspect that this is a simple Oracle parameter syntax issue. The code follows:
    public List<ForecastData>GetByFiscalYear(string fiscalYear)
    {
        List<ForecastData> queryResults = new List<ForecastData>();

        String sqlQuery = @"SELECT RES.FISCALYEAR year FROM RESOURCE_AVAILABILITY RES WHERE RES.FISCALYEAR = :p_fiscalYear";

        using (var oraCon = new OracleConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Oracle_HRZD"].ToString()))
        {
            oraCon.Open();
            queryResults = oraCon.Query<ForecastData>(sqlQuery, new { p_fiscalYear = fiscalYear }).ToList();
        }

        return new List<ForecastData>(queryResults);
    }

Any assistance will be greatly appreciated...

A: Usually, ORA-00942 is exactly what it says, it can't find the table/view (RESOURCE_AVAILABILITY) you are selecting from. So it's not in the schema for the user you log on as or the user has not been granted SELECT on the table/view if it's another schema.
But you say that if you remove WHERE RES.FISCAL_YEAR :p_fiscalyear, then it works. So it seems like you have select permissions on the table. Do you mean remove the whole where selection or have you tested enter a fixed string, as in WHERE RES.FISCAL_YEAR='2016'?
My other top tip is to run Wireshark and look at what really is sent to the database, usually you connect on port 1521 filter on that.

A: The answer was to use the fully-qualified database-object name, including the schema. Thanks for your assistance.


text:
Q: Stop UIWebView from reloading So I have a UIWebView and a very simple line of code in the viewDidLoad:
[bandcamp loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://hatfilms.bandcamp.com"]]];

It works so that when I push a button, a new view loads and this is the code that is executed. Trouble is, when I then go to another view, and then go back to the webView ViewController, the webView reloads. When I play music in the webView, the music keeps playing but the webView reloads - like it's created another instance of itself.
How would I stop this from happening?


text:
Q: Rescaling of a problem I'm having a tough time trying to figure this question out mainly because I haven't any formal training in "scaling" of a problem.
An infinite cylindrical rod (radius $a$) is initially at temperature $T = T_0$ and its surface temperature is reduced to $T = 0$. Determine the time required for the cylinder to cool.
Write down the defining equations and scale the problem to reduce it to the form:
$$\frac{1}{r}\left ( rT_{r} \right )_{r}=T_{t}.$$
In cylindrical coordinates we have:
$$T_{t} = \kappa \nabla ^{2}T(r,t)$$
which gives
$$T_{t} = \kappa \frac{1}{r}\frac{d}{dr}\left ( r\frac{dT}{dr}\right )$$ assuming heat diffusion is independent of $\theta$ and $t$.

A: You have
$$\frac{dT}{dt} = \kappa \frac{1}{r}\frac{d}{dr}\left ( r\frac{dT}{dr}\right )$$
now nondimensionalise by choosing characteristic scales. For $T$, which will vary between $0$ and $T_0$, let $T=T_0\hat T$, where $\hat T$ is the nondimensional variable that varies between $0$ and $1$. For $r$, choose $r=a\hat r$ as the radius of the rod seems like a good length scale for this problem. For time, there is no obvious scale to use, so let $t=t_c\hat t$ where $t_c$ is some unknown for the being. Putting this into the equation and simplifying gives
$$\frac{dT}{dt} = \frac{\kappa t_c}{a^2} \frac{1}{r}\frac{d}{dr}\left ( r\frac{dT}{dr}\right )$$
where everything is nondimensional except for $\kappa$, $t_c$ and $a$, so I didn't put all the hats on everything. We have free choice over what we make $t_0$, so let's choose $t_c=a^2/\kappa$ which reduces the equation to
$$\frac{dT}{dt} = \frac{1}{r}\frac{d}{dr}\left ( r\frac{dT}{dr}\right ).$$
Having $t_c=a^2/\kappa$ makes sense, because we'd expect that if the rod got bigger it would take longer for the temperature to diffuse, (and ought to be proportional to the square) and increasing the thermal conductivity should increase the rate of diffusion and decrease the time scale for the temperature change.


text:
Q: Passing a variable to __wakeup() I am storing certain objects in the database. Each node in the database carries a serialized object. The node can have children, and thus, the object can have children too. Therefore, i want to fill a $children property in the object with an array containing its immediate children. $children should get filled when the object is unserialized.
In trying to avoid doing this from the outside i thought i'd rather let the object itself do it. However, the object does not know which database entry it belongs to. So when __wakeup() is called, the object lacks the required information to load its own, corresponding database entry.
What would seem best, would be to be able to pass a variable to __wakeup(), although i am aware that unserialize() offers no such option.
I was not able to find any information regarding this. I was about to conclude that it won't be possible, other than using a global, which is not a route i'd choose to take.
Is it possible? If yes, how?

A: The magic __wakeup() method does not allow passing of arguments. The idea here is to have everything the object needs in order to unserialize itself into a valid state in the serialized form already, e.g. it expects the object to be in a valid state when it gets serialized.
This means, if the information which database entry a child belongs to is missing but is required for the object to be in a valid state, you should add it into the object in the first place. Then you can simply access that value when unserializing the object. This would be the cleanest solution.
Another option would be to resort to globals. I agree, no one wants that.
Yet another equally doubtful and incredibly magic option would be to mess with the serialized form before unserializing the object to add the missing information.
Here's a proof of concept:
function unserialize_with_args($string, array $args, $key = 'tmp')
{
    // serialize $args to $key for inserting into $string
    $tmps = sprintf(
        's:%d:"%s";%s}',
        strlen($key),
        $key,
        serialize($args)
    );

    // increase property count in original string
    $string = preg_replace_callback(
        '/^(O:\d+:"[a-z]+":)(\d+)/i',
        function (array $matches) {
            return $matches[1] . ($matches[2] + 1);
        },
        $string
    );

    // insert $tmps, unserialize, remove tmps
    $instance = unserialize(substr_replace($string, $tmps, -1));
    unset($instance->$key);

    return $instance;
}

With that you can do:
class Foo
{
    public function __wakeup()
    {
        print_r($this->tmp);
    }
}

unserialize_with_args(
    serialize(new Foo),
    [1,2,3]
);

Running that code will print (demo):
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)

This works because the function adds a property tmp to the serialized form holding the serialized array that was passed as $args. So when the object is woken up, it will have access to these values. The function will remove that property before the unserialized object is returned, so you can only access it during __wakeup.
But just to be clear about this solution: this is desperate measures. Try to make the missing information available in the serialized form in the first place instead.


text:
Q: Why is this code throwing an out of memory exception? I decided to dig up a Haskell project I started a few months ago. It's the beginning of a sparse matrix library. Can anyone see anything obvious about this code that would cause it to throw an out of memory exception for a medium sized matrix (2500 x 2500 doubles)? I understand that normally it's best to post complete build able code, I can post more if needed. The code below converts a SparseMatrix type (an IntMap (IntMap Double) ) into a more efficient SkyLine representation using unboxed vectors. This works fine for smaller matrices. I thought it might be related to the use of foldl vs. foldr, so I switched them but it didn't seem to make a difference. Is this a "space leak"? Thanks.
Edit: After looking at this a little more,I'm thinking the problem is the Vector Append. This must be creating a new Vector each time. I noticed I got a down vote, maybe if I solve the problem and post the answer I can regain some cred?
import Math.LinearAlgebra.Sparse hiding (mulMV,dot)
import qualified Data.IntMap as IM
import qualified Data.Vector.Unboxed as V

type IdxM = (Int,Int)

data SKYSpM = SKYSpM {val   :: V.Vector Double
                     ,rcIdx :: V.Vector (Int, Int)
                     ,dims  :: IdxM
                     }deriving(Show)

skySpM :: Int -> SKYSpM
skySpM i = SKYSpM (V.empty::V.Vector Double) (V.empty::V.Vector (Int,Int)) (i,i)

toSKY :: SparseMatrix Double -> SKYSpM
toSKY m = SKYSpM v' (V.snoc idxs' $ V.last idxs') d'
  where (SKYSpM v' idxs' d')  = foldl f (skySpM $ height m) [1..(height m)]
        f (SKYSpM v idxs d) i = SKYSpM (v V.++ v') (V.snoc idxs (V.length v,jmin-1)) d
          where v' = foldl (\acc x -> V.snoc acc (r ! x)) V.empty [jmin..jmax]
                (jmin,_) = (IM.findMin $ vec r)
                (jmax,_) = (IM.findMax $ vec r)
                r        = row m i


text:
Q: pushbuttonfield with double byte character Searched around on Google as well as stackoverflow but didn't see this come up anywhere. I need a pushbuttonfield with double byte characters as the text. Does anybody know if this is possible?
Currently if I set the button text as any double byte text, the text won't show up. It shows up fine if it's just in the body of the PDF.
Edit#1: Double byte character set (DBCS) like Japanese, Russian, Dutch, etc.
Edit#2:
PushbuttonField myButton = new PushbuttonField(writer, rect, "myJapaneseButton");
myButton.setText("japanese text here");

A: Please take a look at the CreateJapaneseButton example. It creates a PDF with a button that looks like this:

Your code snippet is very short, but you probably have all the code you need, except the line that sets the font:
public static final String JAPANESE = "\u3042\u304d\u3089";
public static final String FONT = "resources/fonts/FreeSans.ttf";

public void createPdf(String dest) throws IOException, DocumentException {
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
    document.open();
    PushbuttonField button = new PushbuttonField(writer, new Rectangle(36, 780, 144, 806), "japanese");
    BaseFont bf = BaseFont.createFont(FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
    button.setFont(bf);
    button.setText(JAPANESE);
    writer.addAnnotation(button.getField());
    document.close();
}

If you don't set the font, the default font is used. The default font is the Standard Type 1 font Helvetica. This font doesn't know how to write Japanese. I used the font freesans.ttf. If you don't have that font, you can try arialuni.ttf or any other font that supports Japanese.


text:
Q: What is the proper way to format this txt document with csv writer and pandas? I am a newbie at writing and formatting files I only started today so please go easy on me. I have this piece of code which will create a csv file and writes a single column with header named Vertices. Each row in the csv would contain 64 vertices extracted from a 3d cylinder model. Each vertex will contains a group of x, y, z values. Basically I want something like this:
  Extracted_Vertices
0 [(3.2, 9.9, 3.4), (5.8, 4.5, 2.3), (7.5, 1.9, 2.9)...]
1 [(2.2, 9.2, 3.4), (3.8, 9.5, 4.7), (8.5, 3.9, 5.5)...]

Each row will contain 64 vertices, with each vertex contains 3 values for xyz.
Code that writes the csv file.
What the csv file looks like.
What happens when I try to read the file in pandas.
Edited: The copy and pasted code
with open('cylinder_data.csv', 'w', newline='') as f:
        writer = csv.writer(f)
        writer.writerow(['Vertices'])

        for i in range(2):
            vertices_temp = cylinder_generation()
            vertices_temp = np.round(vertices_temp,3)
            file_names.append('img_' + str(i))
            writer.writerow([*vertices_temp])

Pandas Code:
import os
import numpy as np
import pandas as pd
foo = pd.read_csv('cylinder_data.csv')
foo.head()
foo['Vertices'][0]

Edited2:
Cylinder_generation function:
This is the only code that matters from cylinder_generation, I didn't want to post this code because as you can see it's sort of irrelevant, all it does is use list comprehension to store 3 xyz values by calling Blender's own python api.
ob = bpy.data.objects['Cylinder'] # Select Cylinder
ob.rotation_euler = rotation_xyz # Change its rotation

verts = [vert.co for vert in ob.data.vertices]

If you check the 2nd image I posted the result of writing to the text document is the writerow('img_ + str(i)') plus all the vertices from the list comprehension.

A: I have solved my own problem.
verts = []
for vert in ob.data.vertices:
    verts.extend(vert.co)

I used extended instead of append which gave me a nice list of [x1, y1, z1....x64, y64, z64]
I also took away of the other extra useless lines
with open(path, 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(['Vertices'])
    for i in range(2):
        # vertices_temp = np.round(vertices_temp,3) # REMOVED
        # file_names.append('img_' + str(i)) # REMOVED
        vertices_temp = cylinder_generation() # This contains all 64 (xyz) for the vertex
        writer.writerow([vertices_temp]) # REMOVED the *

Once I started to mess with the actual generated text file and its formatting I realized the exact format pandas need to display the data correctly, all I had to do now is just to recreate the formatting from my script.


text:
Q: WPF Added Line in Code not displayed - XAML displayed I am adding to a CavnasObject (Size 0, 0) a Line Element in Code. But it gets not displayed. So I added the same line object in xaml with same Properties. In XAML it gets displayed but not in C#.
Here is my code in C#:
Line line = new Line()
{
    X1 = points[0].X,
    Y1 = points[0].Y,
    X2 = points[1].X,
    Y2 = points[1].Y,
    Stroke = new SolidColorBrush(Colors.Red),
    StrokeThickness = 4,
    Visibility = System.Windows.Visibility.Visible
};
lineCanvas.Children.Add(line);

The is not shown.
And here is the line shown:
<StackPanel Grid.Column="1">
    <Grid Height="0">
        <Canvas Name="lineCanvas">
            <Line X1="1" X2="240" Y1="33" Y2="33" StrokeThickness="4" Stroke="Red"/>
        </Canvas>
    </Grid>
    <DataGrid Name="dataGrid" Grid.Column="0" ItemsSource="{Binding ViewMap}" CanUserReorderColumns="False"
              CanUserSortColumns="False" AutoGenerateColumns="False" AllowDrop="True"
              DragEnter="dataGrid_DragEnter" Drop="dataGrid_Drop" SelectionUnit="FullRow"
              HeadersVisibility="Column" IsReadOnly="True" Panel.ZIndex="0" MouseDown="dataGrid_MouseDown">
        <DataGrid.CellStyle>#
....
...

If you are yourself why Height=0 of the Grid. I am connecting datacells of a datagrid with lines.
And to place to lines I am using a very small canvas object and i am simply displaying lines out of the canvas.
So does anyone has an idea whats wrong. The Values of the XAML are taken of the code.

A: Ok after testing I figured out that your XAML might be the problem. Your Canvas is created in the Visual Tree behind the DataGrid so any Line will be shown behind the DataGrid. And since you use a StackPanel as root element I'm not sure where your Line will end up. To fix the issue rewrite your XAML to something similar to this:
<Grid Grid.Column="1">
  <DataGrid/>
  <Canvas x:Name="lineCanvas"/>
</Grid>


text:
Q: Anonymous access to SVN server I am using SVN via apache2. I have Ubuntu as OS. Below are my configurations:
<Location /svn>
  DAV svn
  SVNParentPath /var/lib/svn

  # I have tried basic as well
  AuthName "Subversion repository"
  AuthType Digest
  AuthUserFile /etc/dav_svn.passwd

<IfModule mod_authz_svn.c>
    AuthzSVNAccessFile /etc/apache2/svn_access_control
</IfModule>

  <LimitExcept GET PROPFIND OPTIONS REPORT>
    Require valid-user
  </LimitExcept>
</Location>

Is there a way to allow only registered users to view/checkout svn? I don't want anonymous users to access.
I can still access the SVN via browser and SVN client. I tried to remove the tag  "<LimitExcept GET PROPFIND OPTIONS REPORT>" but then Apache gives "Internal Server Error".
[Tue Oct 29 15:06:16 2013] [crit] [client [IP]] configuration error:  couldn't check user.  Check your authn provider!: /svn/repo1/, referer: http://[IP]

I am totally novice to Linux :(
Thanks

A: You're missing the digest module.
Find this line in your apache2.conf (or httpd.conf) and uncomment:

LoadModule auth_digest_module modules/mod_auth_digest.so
If you can't find it, add it to the existing list of LoadModule lines.


text:
Q: How to get the path of a file in comparison to another file (VSCode)? I am in file A and need to import file B. There is a complex file structure. I don't want to use the absolute path. How can I copy the path to file B from file A?

A: There is no native way to do it in VS Code but this extension does it very well: https://marketplace.visualstudio.com/items?itemName=jakob101.RelativePath


text:
Q: Error on Tomcat Server : Could not resolve placeholder 'jdbc.driverClassName' in string value "${jdbc.driverClassName}" I have a problem when passing on Tomcat Server. The code works on localhost but throws an exception on Tomcat Server. Here is the exception :
WARNING: Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'dataSource' defined in URL [file:/opt/****/WEB-INF/classes/context.xml]: Could not resolve placeholder 'jdbc.driverClassName' in string value "${jdbc.driverClassName}"; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'jdbc.driverClassName' in string value "${jdbc.driverClassName}"

And here is a part of my context.xml :
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location">
        <value>classpath:****.properties</value>
    </property>
</bean>

    <!-- Database Configuration -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
    <property name="driverClass" value="${jdbc.driverClassName}" />
</bean>

And my file ****.properties
jdbc.driverClassName=oracle.jdbc.driver.OracleDriver

Do you have any idea of what doesn't work and how to solve this problem?
Note : I have masked some path or file name by "****" due to confidentiality issue.
EDIT : Here is the complete stack trace :
WARNING: Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'dataSource' defined in URL [file:/opt/pdsa/liferay-portal-6.2-ce-ga4/tomcat-7.0.42/webapps/pdsa-portlet/WEB-INF/classes/pdsaContext.xml]: Could not resolve placeholder 'jdbc.driverClassName' in string value "${jdbc.driverClassName}"; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'jdbc.driverClassName' in string value "${jdbc.driverClassName}"
        at org.springframework.beans.factory.config.PlaceholderConfigurerSupport.doProcessProperties(PlaceholderConfigurerSupport.java:211)
        at org.springframework.beans.factory.config.PropertyPlaceholderConfigurer.processProperties(PropertyPlaceholderConfigurer.java:223)
        at org.springframework.beans.factory.config.PropertyResourceConfigurer.postProcessBeanFactory(PropertyResourceConfigurer.java:86)
        at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:265)
        at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:162)
        at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:606)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:462)
        at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
        at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
        at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
        at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4939)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
        at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:976)
        at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1653)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
        at java.util.concurrent.FutureTask.run(FutureTask.java:262)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'jdbc.driverClassName' in string value "${jdbc.driverClassName}"
        at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174)
        at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126)
        at org.springframework.beans.factory.config.PropertyPlaceholderConfigurer$PlaceholderResolvingStringValueResolver.resolveStringValue(PropertyPlaceholderConfigurer.java:259)
        at org.springframework.beans.factory.config.BeanDefinitionVisitor.resolveStringValue(BeanDefinitionVisitor.java:282)
        at org.springframework.beans.factory.config.BeanDefinitionVisitor.resolveValue(BeanDefinitionVisitor.java:204)
        at org.springframework.beans.factory.config.BeanDefinitionVisitor.visitPropertyValues(BeanDefinitionVisitor.java:141)
        at org.springframework.beans.factory.config.BeanDefinitionVisitor.visitBeanDefinition(BeanDefinitionVisitor.java:82)
        at org.springframework.beans.factory.config.PlaceholderConfigurerSupport.doProcessProperties(PlaceholderConfigurerSupport.java:208)
        ... 22 more

A: I have found the solution! The problem was because of the file ****.properties who had a bad encoding. The encoding was in UTF-8-BOM instead of UTF-8. After changing the encoding, the deployment works very well as expected. Anyway, thanks for your answers.
The issue is closed for me.


text:
Q: Open quote is expected for attribute "src" associated with an element type "script" Sam this side, currently I was working on my sites code . I thought of adding a loading animation in the site , but after adding adding the code it is giving me a strange error whose solution can't be found anywhere
code containing the line which caused this nuisance `

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html>
<html b:css='false' b:defaultwidgetversion='2' b:layoutsVersion='3' b:responsive='true' b:templateUrl='fancy.xml' b:templateVersion='1.3.3' expr:dir='data:blog.languageDirection' expr:lang='data:blog.locale' xmlns='http://www.w3.org/1999/xhtml' xmlns:b='http://www.google.com/2005/gml/b' xmlns:data='http://www.google.com/2005/gml/data' xmlns:expr='http://www.google.com/2005/gml/expr'>
  <head>

<script src=<"//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"><\/script>

<script type="text/javascript">

$(window).load(function() {

$(".loader").fadeOut("slow");

})

</script>

THE ERROR WHICH I GET WHEN TRY TO SAVE THE THEME
org.xml.sax.SAXParseException; lineNumber: 6; columnNumber: 13; Open quote is expected for attribute "src" associated with an element type "script".

SCREENSHOT OF THE ERROR:

I have given the link as I am not allowed to embed images yet
pls tell me if you need more code
Pls help me out with this, your help will be very appreciated
Thanks in advance
EDIT :
 SEE THE SECOND IMAGE WHICH I TOOK AFTER EDIT THE CODE

A: Change it with :
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html>
<html b:css='false' b:defaultwidgetversion='2' b:layoutsVersion='3' b:responsive='true' b:templateUrl='fancy.xml' b:templateVersion='1.3.3' expr:dir='data:blog.languageDirection' expr:lang='data:blog.locale' xmlns='http://www.w3.org/1999/xhtml' xmlns:b='http://www.google.com/2005/gml/b' xmlns:data='http://www.google.com/2005/gml/data' xmlns:expr='http://www.google.com/2005/gml/expr'>
  <head>
<script src=//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js></script>
<script type="text/javascript">
$(window).load(function() {
$(".loader").fadeOut("slow");
})
</script>

It's seems like you wrong using double quotes.

A: As the error says Open quote is expected for attribute "src" associated with an element type "script". You should change :
<script src=<"//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"><\/script>

to :
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

(remove the '<' character after '=', and <\/script> to </script>)
Also, you should change " to ".


text:
Q: Database first, files extensions and their uses When I use the wizard to generate the codes, it will also generate the following file extensions:

*

*xxxx.edmx

*xxxx.Designer.cs

*xxxx.edmx.diagram

*xxxx.tt

What are the purposes of all these files? Can I remove them? (If I'm not mistaken, in code-first approach, I really need the .cs classes only.

A: .tt is T4 template file which generates your Entity Classes and Context.
.edmx.diagram contains information that is used by the Entity Designer to render a graphical display of the conceptual model.
.Designer.cs contains information that is used by the Entity Designer to render a conceptual model graphically and to define some conceptual model and design-time properties. after vs 2012 this file is usually useless and T4 code generators are used by default.
.edmx is an XML file that defines a conceptual model, a storage model, and the mapping between these models


text:
Q: The vector space $L^1$ is complete in its metric
Theorem 2.2 (Riesz-Fischer) The vector space $L^1$ is complete in its metric
  Consider a subsequence $\{f_{n_k}\}_{k=1}^\infty \,$ of $\{f_n\}$ with the following property:$$\Vert f_{n_{k+1}} - f_{n_k}\Vert_1 \leq \frac{1}{2^{k}}$$
  Then consider the series whose convergence will be seen below,
  $$f = f_{n_1}+\sum_{k=1}^\infty (f_{n_{k+1}}-f_{n_k})$$and
  $$g= \vert f_{n_1} \vert+\sum_{k=1}^\infty \vert f_{n_{k+1}}-f_{n_k} \vert$$
  So the monotone convergence theorem implies that $g$ is integrable , and since $\vert f \vert \le g$  , hence so is $f$.

By the monotone convergence theorem , I can show $g$ is integerable, and $\vert f \vert \le g$ can be proved directly.However,since I can not prove $f_{n_k}$ converges to $f$ a.e. at this step.How to prove $f$ is integrable.Or how to show that $f$ is measurable. And how to prove the same conclusion in $L^2$ space, $\vert f \vert ^2 $ is measurable.