text:
Q: Create a list of beamer slides How can I create a list of all beamer slides (by their frame-title) like the table of contents in a regular latex document? I just need it as a bird's eye view of my presentation, thus it must not be anything fancy.
It should also be able to cope with the following slide that I have at the end of my presentation
\begin{frame}
    {\Huge
        \vspace {0.35\textwidth}
% Don't remove
        \begin{columns}[ccc]
            \begin{column}{0.3\textwidth}
            \end{column}
% Don't remove
            \begin{column}{0.3\textwidth}
                    \textbf{Thanks!}
            \end{column}
% Don't remove
            \begin{column}{0.3\textwidth}
            \end{column}
        \end{columns}
    }
\end{frame}

A: Howdy this is my solution:
   \documentclass{beamer}
\usepackage{etextools}
\makeatletter
%Here comes the Framelist
%
\newcommand{\printframelist}{ }
\newcommand{\@savefrml}{ }
\newcommand{\frameliston}{%
\let\oldframetitle\frametitle
\newcommand{\tgframelistfronthook}{$\cdot$}
\newcommand{\tgframelistbackhook}{\\ }
\newcommand\myaddto[1]{%
  \write\@auxout{\noexpand\@writefile{frml}{\noexpand ##1}}}
  \renewcommand{\printframelist}{\@starttoc{frml}}
\renewcommand{\frametitle}[1]{\oldframetitle{##1}%
\xifstrequal{##1}{\@savefrml}{}{
\myaddto{ \noexpand%
\tgframelistfronthook ##1 \noexpand\tgframelistbackhook}%
}
\global\def\@savefrml{##1}%
}
}

\makeatother
\frameliston
\begin{document}
\frame{\frametitle{FIRST}}
\frame{\frametitle{Second}}
\frame{\frametitle{Third}}
\begin{frame}
\printframelist
\end{frame}
% The following should turn the framlist off for one slide when\anotherft is used
\let\anotherft\oldframetitle
\frame{\anotherft{FIRST A}}
\frame{\frametitle{Second A}}
\frame{\frametitle{Third A}}
\end{document}

This uses the very basic LaTeX mechanism on creating external files (like toc). extetools are used to compare strings and decide to print or not to print the title (for overlays). See in bitbucket.org/tobig/hohenheimbeamertheme/
Redefine \tgframelistbackhookand \tgframelistfronthook as you please.
EDIT: What you are showing in your example given above is that you put the whole columns stuff into the frametitle. And it breaks. Remember the frame environment is defined as
    \begin{frame}<⟨overlay specification⟩>[<⟨default overlay specification⟩>][⟨options⟩]{⟨title⟩}{⟨subtitle⟩}
 ⟨environment contents⟩
    \end{frame}

(see beamer documentation)
The first brakets after \begin{frame} will be interpreted as the title.
This will work:
\begin{frame}
    \Huge
        \vspace {0.35\textwidth}
% Don't remove
        \begin{columns}
            \begin{column}{0.3\textwidth}
            \end{column}
% Don't remove
            \begin{column}{0.3\textwidth}
                    \textbf{Thanks!}
            \end{column}
% Don't remove
            \begin{column}{0.3\textwidth}
            \end{column}
        \end{columns}
\end{frame}


text:
Q: Computing p-value of LM statistic value in Stata Do you know how can I compute out the p-value in LM statistics? (What is the command in stata?)
I know that to implement the LM computing procedure I have to do the following steps:

*

*Obtain the OLS estimators of the restricted model;

*Obtain the residuals regression;

*regress the residuals on all independent variablesof the unrestricted model;

*get the R^2 of this regression;

*get LM stat that is [R^2] * [# of observations];

I know how I have to proceed till now, but how can I compute out the p-value for the LM statistics? Does somebody know how getting the solution?
Thanks in advance for helping!!

A: The entry in wikipedia,

This [the LM statistics] follows a chi-squared distribution, with degrees of freedom equal to the number of estimated parameters (in the auxiliary regression) minus one.

A rapid inspection of the original article of White (1980) confirms this (eq. 2, eq. 3, and Corollary 1 in the article should be what you are looking for).

redpajama_set_name: RedPajamaStackExchange


text:
Q: i am trying to use count() function in laravel but i am running in to this error syntax error, unexpected 'count' (T_STRING) here is where i am using this function
@if($tags count() > 0)

Tags

<select   name="tags"  id="tags" class="form-control" multiple>

    @foreach ($tags as $tag)

    <option value="{{$tag->id}}">
    {{$tag->name}}
    </option>
  @endforeach
</select>

@endif

here in my controller i am using tags as key in my controller as
 public function index()
    {
        //
        return view('posts.index')->with('posts',Post::all())->with('tags',Tag::all());
    }

i am running into this error quite often when ever the count==0 then this error appears which says syntax error, unexpected 'count' (T_STRING)
any idea how i can remove this
i am learner

A: You could check if the tag variable is set or not and then count afterwards
@if(isset($tags) && count($tags) > 0)

Tags

<select   name="tags"  id="tags" class="form-control" multiple>

    @foreach ($tags as $tag)

    <option value="{{$tag->id}}">
    {{$tag->name}}
    </option>
  @endforeach
</select>

@endif


text:
Q: table with resizable columns, should have columns added / removed dynamically & sortable values with in columns I have requirement to develop a list display which should be a table with resizable columns, should have columns added / removed dynamically & sortable values with in columns.
The columns are needed to be added and removed dynamically. Initially some columns can be displayed by default. Later additional columns can be added by choosing from a drop down for columns selection.
Initially one column is sorted by ascending order.
We are using HTML 5 with angularjs on UI layer.
I tried searching for plugin or javascript libraries but none of them provided all the features which matches all our requirement.
Can you please provide a good suggestion of how to go about this situation?

A: You can use ng-grid and customize it accordingly. However, we have used jqx library since it has many other items including grid-
Link for grid-
http://www.jqwidgets.com/jquery-widgets-demo/demos/jqxgrid/index.htm?(arctic)
For adding column dynamically, you can update the column definition in runtime which will help you to add/delete columns.
All other features you mentioned are included as features by jqx itself.


text:
Q: Outer left join of inner join and regular table For the first time in my professional career I found the need of join the result of a join with a table being the first join an inner join and the second a left outer join.
I came to this solution:
SELECT * FROM
(
    TableA INNER JOIN TableB ON
    TableA.foreign = TableB.id
)
LEFT OUTER JOIN TableC
ON TableC.id = TableB.id

I know I could create a view for the first join but I wouldn't like to create new objects in my database.
Is this code right? I got coherent results but I would like to verify if it is theoretically correct.
Do you have any suggestion to improve this approach?

A: You should do it in a simpler way.
SELECT * FROM
TableA
INNER JOIN TableB ON TableA.foreign = TableB.id
LEFT OUTER JOIN TableC ON TableB.id = TableC.id

Usually it is done that way.

A: I believe you are looking for something like this:
SELECT *, t.otherFields
FROM
(
    SELECT TableB.id, otherFields FROM TableA
    INNER JOIN TableB ON
    TableA.foreign = TableB.id
) t
LEFT OUTER JOIN TableC
ON TableC.id = t.id

A: SELECT *
FROM TableA
    INNER JOIN TableB ON
        TableA.foreign = TableB.id
LEFT OUTER JOIN TableC
    ON TableC.id = TableB.id

Also fine

A: Yes it is correct, but it does nothing different than the same (simpler) query without the parentheses:
SELECT  *
FROM    TableA
        INNER JOIN TableB
            ON TableA.foreign = TableB.id
        LEFT OUTER JOIN TableC
            ON TableC.id = TableB.id;

SQL Fiddle showing both queries with the same result
Also worth noting that both queries have exactly the same execution plan
The parentheses are used when you need to left join on the results of an inner join, e.g. If you wanted to return only results from table b where there was a record in tableC, but still left join to TableA you might write:
SELECT  *
FROM    TableA
        LEFT OUTER JOIN TableB
            ON TableA.foreign = TableB.id
        INNER JOIN TableC
            ON TableC.id = TableB.id;

However this effectively turns the LEFT OUTER JOIN on TableB into an INNER JOIN because of the INNER JOIN below. In this case you would use parentheses to alter the JOIN as required:
SELECT  *
FROM    TableA
        LEFT OUTER JOIN (TableB
        INNER JOIN TableC
            ON TableC.id = TableB.id)
            ON TableA.foreign = TableB.id;

SQL Fiddle to show difference in results when adding parentheses


text:
Q: std::stringstream to read int and strings, from a string I am programming in C++ and I'm not sure how to achieve the following:
I am copying a file stream to memory (because I was asked to, I'd prefer reading from stream), and and then trying to access its values to store them into strings and int variables.
This is to create an interpreter. The code I will try to interpret is (ie):
10 PRINT A
20 GOTO 10

This is just a quick example code. Now the values will be stored in a "map" structure at first and accessed later when everything will be "interpreted".
The values to be stored are:
int lnum // line number
string cmd // command (PRINT and GOTO)
string exp // expression (A and 10 in this case but could hold expressions like (a*b)-c )
question is given the following code, how do I access those values and store them in memory?
Also the exp string is of variable size (can be just a variable or an expression) so I am not sure how to read that and store it in the string.
code:

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <map>
#include <sstream>

using namespace std;

 #include "main.hh"

int main ()
{
    int lenght;
    char *buffer;

// get file directory
    string dir;
    cout << "Please drag and drop here the file to interpret: ";
    getline (cin,dir);
    cout << "Thank you.\n";
    cout << "Please wait while your file is being interpreted.\n \n";

// Open File
    ifstream p_prog;
    p_prog.open (dir.c_str());

// Get file size
    p_prog.seekg (0, ios::end);
    lenght = p_prog.tellg();
    p_prog.seekg(0, ios::beg);

// Create buffer and copy stream to it
    buffer = new char[lenght];
    p_prog.read (buffer,lenght);
    p_prog.close();

// Define map<int, char>
    map<int, string> program;
    map<int, string>::iterator iter;

/***** Read File *****/
    int lnum; // line number
    string cmd; // store command (goto, let, etc...)
    string exp; // to be subst with expr. type inst.

//  this is what I had in mind but not sure how to use it properly
//  std::stringstream buffer;
//  buffer >> lnum >> cmd >> exp;

    program [lnum] = cmd; // store values in map

// free memory from buffer, out of scope
    delete[] buffer;
    return 0;
}

I hope this is clear.
Thank you for your help.
Valerio

A: You can use a std::stringstream to pull tokens, assuming that you already know the type.
For an interpreter, I'd highly recommend using an actual parser rather than writing your own. Boost's XPressive library or ANTLR work quite well. You can build your interpreter primitives using semantic actions as you parse the grammar or simply build an AST.
Another option would be Flex & Bison. Basically, these are all tools for parsing pre-defined grammars. You can build your own, but prepare for frustration. Recursively balancing parentheses or enforcing order of operations (divide before multiply, for example) isn't trivial.
The raw C++ parsing method follows:

#include <sstream>
#include <string>

// ... //

istringstream iss(buffer);
int a, b;
string c, d;

iss >> a;
iss >> b;
iss >> c;
iss >> d;

A: Don't do the dynamic allocation of the buffer explicitly use a vector.
This makes memory management implicit.
// Create buffer and copy stream to it
std::vector<char>   buffer(lenght);
p_prog.read (&buffer[0],lenght);
p_prog.close();

Personally I don't explicitly use close() (unless I want to catch an exception). Just open a file in a scope that will cause the destructor to close the file when it goes out of scope.

A: The way something like this can be done (especially the arithmetic expression part that you alluded to) is:

*

*Write some code that determines where a token ends and begins.  For example 5 or + would be called a token.  You might scan the text for these, or common separators such as whitespace.

*Write up the grammar of the language you're parsing.  For example you might write:

    expression -> value
    expression -> expression + expression
    expression -> expression * expression
    expression -> function ( expression )
    expression -> ( expression )

Then based on this grammar you would write something that parses tokens of expressions into trees.
So you might have a tree that looks like this (pardon the ASCII art)

            +
          /   \
         5     *
              / \
             x   3

Where this represents the expression 5 + (x * 3).  By having this in a tree structure it is really easy to evaluate expressions in your code: you can recursively descend the tree, performing the operations with the child nodes as arguments.
See the following Wikipedia articles:

*

*Parser

*Top-down parsing (your needs are probably simple enough to use this)

*Recursive-descent parser (a simple way to convert a grammar into code)

Or consult your local computer science department.  :-)
There are also tools that will generate these parsers for you based on a grammar.  You can do a search for "parser generator".

A: This might be of help:
http://oopweb.com/CPP/Documents/CPPHOWTO/Volume/C++Programming-HOWTO-7.html
Especially section 7.3.
You might be better off just <<'ing the lines in rather than the seeking and charbuffer route.


text:
Q: How can I add iPhone 4 to the list of devices in iOS Simulator (Xcode 6.1)? EDIT: Sorry, it is a duplicate.
Original Question:
The following appear as choices for device within XCode (6.1), but there is no iPhone 4. How can I add this? (A bug is being reported against 7.1.2 on iPhone 4 and I am looking for a way to test it without a physical device).

A: *

*Visit apple downloads page, find the older xcode sdk that has iPhone 4 simulator sdk.

*Copy the simulator sdk from the older xcode to your newer xcode (better create a symbolic link)


text:
Q: Does a server hostname always need a SSL certificate? In the context of a web server with HTTP, HTTPS, IMAPS, POP3S, SMTPS, SFTP and WebDav services, is it necessary to get a SSL certificate for the FQDN hostname of a server (example: something.example.com), if we never use the FQDN hostname for HTTPS (like: https://something.example.com)?
Can't we just install an SSL certificate for the "root" domain (like example.com) and use it for all secured services?

A: The domain name used int he SSL certificate needs to match the hostname that is used to access the service. So if you run all your services on the same server(s), i.e. example.com, you can use the same hostname for all your services, and thus use the same certificate for all of them.
The downside is that this makes it hard for you to should you ever want split your services between different servers.

A: The name which gets used to access the site should be contained in the certificate. Which means if you access the IMAP service with the hostname imap.example.com then it is not enough to have a certificate for example.com only. If these are both the same IP address then you could of course simplify the configuration by accessing the IMAP service with example.com and not imap.example.com.
This is true for all protocols.

A: In this case, get wildcard SSL certificate *.example.com and can use it for your root also example.com

A: If the configuration of the clients are "example.com" and the certificate provided by the services has the same name, you will not have any problem.


text:
Q: Jenkins builds being triggered despite "Don't trigger a build on commit notifications" I have a Pipeline job that checkouts a git repository (let's
call is "repoA") and passes it to some other downstream jobs for
further processing. The upstream job's script is stored in a different
git repo (let's call it "repoB"). This job is configured with the "Poll
SCM" option so that any changes to repoA will trigger it. In the pipeline section, I have selected the "Pipeline script from SCM" option and configured it to get the pipeline script from the master branch of repoB. I have also added the option "Don't trigger a build on commit notifications". The behavior that I'm expecting is that any changes pushed to repoA would trigger the job,
and any changes to repoB would not trigger the job. Yet, when I push a
change to repoB, the job is triggered.
I don't know if this is a bug, or if I'm missing something.
I am running Jenkins 2.7.4. My master Jenkins is running on Ubuntu server 16.04.1 LTS. All my Jenkins plugins are up to date.

A: After some exchange with the Jenkins mailing list, I now understand better how things work so here is what I had to do in case other people need it:

*

*Create a git hook to notify Jenkins that changes have been committed/pushed: on our end we created a post-receive hook on the remote

*Enable polling on your job but leave the schedule empty

*In the Pipeline section, configure it to pull the groovy script from your git repo (in my example it is repoB) but don't add the behavior: "Don't trigger a build on commit notifications"

*Make sure polling is enabled when you checkout your git repository (in my example it is repoA) in your script: by default it is enabled if you don't specify it

As far as I understand, the option "Don't trigger a build on commit notifications" is for notifications comming from the hooks and not from the job polling schedule as I first thought.


text:
Q: What does the % mean in arithmatic expressions in Python? I am taking a codeacademy beginners course in Python.  What does the character "%" mean in this expression - 45 % 12?  I am using Python 2.7.5.  i have looked at various references, and cannot find it.

A: It's the modulus operator - 45 divided by 12 = 3 and 9/12. In short, it would return 9.
It's a neat way of looping up to a certain count
eg the following will run on alternate rows...
for i in range[0,100]
    if i % 2 == 0:
        #Even row
    else:
        #Odd row

A: The % (read "mod" or "modulo") means divide by and return the remainder:
x = 8%3

The above expression says "divide 8 by 3 and compute the remainder. Assign this remainder to x"


text:
Q: Remove a Row from recycle view and Firebase Hi I am trying to remove A row from a recycle view and once it is removed from the recycle view it should also be removed from the firebase realtime database. I am able to remove it from the recycle view but when I go back into my activity it repopulates with all the rows as I am unsure on how to remove it from Firebase. Can anyone help?
public class FindAllContacts extends AppCompatActivity {
    RecyclerView recyclerView;
    RecyclerView.Adapter adapter;
    ArrayList<Contacts> contacts = new ArrayList<>();
    FirebaseAuth mAuth = FirebaseAuth.getInstance();
    FirebaseUser firebaseUser = mAuth.getCurrentUser();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_all);
        getSupportActionBar().setTitle("View All Contacts");
        getAllContacts();
    }

    public void getAllContatcs() {
        DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Contacts");
        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                for (DataSnapshot userSnapshot : snapshot.getChildren()) {
                    Contact contact = userSnapshot.getValue(Contact.class);
                    assert contact != null;
                    contatcs.add(contact);
                    recyclerView = findViewById(R.id.findAllRV);
                    recyclerView.setHasFixedSize(true);
                    recyclerView.setLayoutManager(new LinearLayoutManager(FindAll.this));
                    adapter = new MainAdapter(contacts);
                    new ItemTouchHelper(itemTouch).attachToRecyclerView(recyclerView);
                    recyclerView.setAdapter(adapter);
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Toast.makeText(FindAll.this, "Error Occurred: " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    ItemTouchHelper.SimpleCallback itemTouch = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT | ItemTouchHelper.LEFT) {
        @Override
        public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
            return false;
        }

        @Override
        public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
            int position = viewHolder.getAdapterPosition();
            contatcs.remove(viewHolder.getAdapterPosition());
            adapter.notifyDataSetChanged();

        }
    };
}


text:
Q: How do I fix a "User timeout caused connection failure" error? I'm following these instructions - How do I configure juju for local usage? and all appears well until :
juju deploy mysql - which gives
2012-08-01 16:14:58,560 INFO Searching for charm cs:precise/mysql in charm store
User timeout caused connection failure.
2012-08-01 16:15:28,592 ERROR User timeout caused connection failure.

~/juju/samples/charms/ is empty.
juju bootstrap completed within 10 secs which I suspect is not correct
geme@GEME1:~$ juju bootstrap
2012-08-01 16:13:11,878 INFO Bootstrapping environment 'sample' (origin: distro type: local)...
2012-08-01 16:13:11,880 INFO Checking for required packages...
2012-08-01 16:13:12,525 INFO Starting networking...
2012-08-01 16:13:12,870 INFO Starting zookeeper...
2012-08-01 16:13:13,041 INFO Starting storage server...
2012-08-01 16:13:15,474 INFO Initializing zookeeper hierarchy
2012-08-01 16:13:17,846 INFO Starting machine agent (origin: distro)...
2012-08-01 16:13:19,483 INFO Environment bootstrapped
2012-08-01 16:13:19,487 INFO 'bootstrap' command finished successfully

status shows :
geme@GEME1:~$ juju status
machines:
  0:
    agent-state: running
    dns-name: localhost
    instance-id: local
    instance-state: running
services: {}
2012-08-01 16:13:28,304 INFO 'status' command finished successfully
geme@GEME1:~$ juju -v status
2012-08-01 16:13:44,419 DEBUG Initializing juju status runtime
2012-08-01 16:13:44,522:2807(0xb77abb00):ZOO_INFO@log_env@658: Client environment:zookeeper.version=zookeeper C client 3.3.5
2012-08-01 16:13:44,522:2807(0xb77abb00):ZOO_INFO@log_env@662: Client environment:host.name=GEME1
2012-08-01 16:13:44,523:2807(0xb77abb00):ZOO_INFO@log_env@669: Client environment:os.name=Linux
2012-08-01 16:13:44,523:2807(0xb77abb00):ZOO_INFO@log_env@670: Client environment:os.arch=3.2.0-23-generic-pae
2012-08-01 16:13:44,523:2807(0xb77abb00):ZOO_INFO@log_env@671: Client environment:os.version=#36-Ubuntu SMP Tue Apr 10 22:19:09 UTC 2012
2012-08-01 16:13:44,532:2807(0xb77abb00):ZOO_INFO@log_env@679: Client environment:user.name=geme
2012-08-01 16:13:44,535:2807(0xb77abb00):ZOO_INFO@log_env@687: Client environment:user.home=/home/geme
2012-08-01 16:13:44,535:2807(0xb77abb00):ZOO_INFO@log_env@699: Client environment:user.dir=/home/geme
2012-08-01 16:13:44,535:2807(0xb77abb00):ZOO_INFO@zookeeper_init@727: Initiating client connection, host=192.168.122.1:59761 sessionTimeout=10000 watcher=0xd9f620 sessionId=0 sessionPasswd=<null> context=0x8a43440 flags=0
2012-08-01 16:13:44,545:2807(0xb7483b40):ZOO_INFO@check_events@1585: initiated connection to server [192.168.122.1:59761]
2012-08-01 16:13:44,564:2807(0xb7483b40):ZOO_INFO@check_events@1632: session establishment complete on server [192.168.122.1:59761], sessionId=0x138e2bf765f0003, negotiated timeout=10000
2012-08-01 16:13:44,573 DEBUG Environment is initialized.
machines:
  0:
    agent-state: running
    dns-name: localhost
    instance-id: local
    instance-state: running
services: {}
2012-08-01 16:13:44,599 INFO 'status' command finished successfully

With verbose flag:
juju -vv deploy mysql
2012-08-02 17:37:52,895 DEBUG Initializing juju deploy runtime
2012-08-02 17:37:52,897 INFO Searching for charm cs:precise/mysql in charm store
Traceback (most recent call last):<br>
Failure: twisted.internet.error.TimeoutError: User timeout caused connection failure.
2012-08-02 17:38:22,936 ERROR Traceback (most recent call last):
Failure: twisted.internet.error.TimeoutError: User timeout caused connection failure.

User timeout caused connection failure.
2012-08-02 17:38:22,942 ERROR User timeout caused connection failure.

A: The bootstrapping quickly is to be expected. In most environments the bootstrap will actually spin up a machine, when you're working with a local deployment it just creates the first LXC container and sets up networking. So this typically takes 10-20 seconds. The magic happens on the first deployment, as explained in this local configuration question, this is when Juju downloads ~300MB server image and creates the "master container" which all future deployments are based on.
Now, the error your receiving appears to state that there's a timeout trying to reach the Juju Charm store. I wasn't aware of any outages, but it might be because you're behind a proxy or some other kind of networking issue/timeout. I'd recommend trying again (juju destroy-environment -e local) then re-bootstrap.
If you're having proxy issues, you can download charms locally using Bazaar:
mkdir -p ~/charms/precise
cd ~/charms/precise
bzr branch lp:charms/mysql
juju deploy --repository=~/charms local:mysql

While the directory can be anything, the important item to follow is each charm needs to be in a series folder (following the Ubuntu release names). Outside of that you use --repository which instructs Juju to search here for charms, and the local: prefix tells Juju that the deployment will be from that local --repository path.


text:
Q: Represent Foreign Key Relationship in JSON using Servant and Persistent This morning I was following along with this interesting tutorial on using Servant to build a simple API server.
At the end of the tutorial, the author suggests adding a Blog type, so I figured I would give it a shot, but I got stuck trying to implement and serialize a foreign key relationship that extends upon the logic in the tutorial (perhaps an important disclosure here: I'm new to both Servant and Persistent).
Here are my Persistent definitions (I added the Post):
share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
User
    name String
    email String
    deriving Show
Post
    title String
    user UserId
    summary String
    content String
    deriving Show
|]

The tutorial builds a separate Person data type for the Servant API, so I added one called Article as well:
-- API Data Types
data Person = Person
    { name :: String
    , email :: String
    } deriving (Eq, Show, Generic)

data Article = Article
    { title :: String
    , author :: Person
    , summary :: String
    , content :: String
    } deriving (Eq, Show, Generic)

instance ToJSON Person
instance FromJSON Person

instance ToJSON Article
instance FromJSON Article

userToPerson :: User -> Person
userToPerson User{..} = Person { name = userName, email = userEmail }

Now, however, when I attempt to create a function that turns a Post into an Article, I get stuck trying to deal with the User foreign key:
postToArticle :: Post -> Article
postToArticle Post{..} = Article {
  title = postTitle
  , author = userToPerson postUser -- this fails
  , summary = postSummary
  , content = postContent
  }

I tried a number of things, but the above seemed to be close to the direction I'd like to go in. It doesn't compile, however, due to the following the error:
Couldn't match expected type 'User'
            with actual type 'persistent-2.2.2:Database.Persist.Class.PersistEntity.Key
                                User'
In the first argument of 'userToPerson', namely 'postUser'
In the 'author' field of a record

Ultimately, I'm not really sure what a PersistEntity.Key User really is and my errant googling has not gotten me much closer.
How do I deal with this foreign-key relationship?

Working Version
Edited with an answer thanks to haoformayor
postToArticle :: MonadIO m => Post -> SqlPersistT m (Maybe Article)
postToArticle Post{..} = do
  authorMaybe <- selectFirst [UserId ==. postUser] []
  return $ case authorMaybe of
    Just (Entity _ author) ->
      Just Article {
          title = postTitle
        , author = userToPerson author
        , summary = postSummary
        , content = postContent
        }
    Nothing ->
      Nothing

A: For some record type r, Entity r is the datatype containing Key r and r. You can think of it as a dollied-up tuple (Key r, r).
(You might wonder what Key r is. Different backends have different kinds of Key r. For Postgres it'll be a 64-bit integer. For MongoDB there are object IDs. The documentation goes into more detail. It's an abstraction that allows Persistent to support multiple datastores.)
Your problem here is that you have a Key User. Our strategy will be to get you an Entity User, from which we'll be able to pull out a User. Fortunately, going from Key User to Entity User is easy with a selectFirst – a trip to the database. And going from Entity User to User is one pattern match.
postToArticle :: MonadIO m => Post -> SqlPersistT m (Maybe Article)
postToArticle Post{..} = do
  authorMaybe <- selectFirst [UserId ==. postUser] []
  return $ case authorMaybe of
    Just (Entity _ author) ->
      Article {
          title = postTitle
        , author = author
        , summary = postSummary
        , content = postContent
        }
    Nothing ->
      Nothing

Gross, more generic version
We assumed a SQL backend above, but that function also has the more generic type
postToArticle ::
  (MonadIO m, PersistEntity val, backend ~ PersistEntityBackend val) =>
  Post -> ReaderT backend m (Maybe Article)

Which you might need if you're not using a SQL backend.

A: You don't really need to create a separate data type for each model. It can be helpful to decouple the database model and the API model, especially if the database model has stuff you don't sending over the wire. I didn't want passwords to be included with Users, so I made the Person data type.
The Yesod book has a good explanation of the Entity stuff here.
If you just want to get a single item and you have a key for it, the Persistent type class haddocks tell us about a get method that does precisely that.
So, if you do want to make the Article type, then there are a few options. You could change the articleUser to be a Key User or Int64 or whatever. This is probably what I'd do -- if I wanted to send a list of articles, I wouldn't want to include the user information for each one!
If you want to keep it as an actual user object, then we'll want to extract the query out of the postToArticle function. Ideally that should be a pure function: postToArticle :: Post -> Article. We can do that by also passing in the Person:
postToArticle :: Person -> Post -> Article
postToArticle person Post{..} = Article
    { ...
    }

Of course, this function can't verify that you passed in the right person. You could do:
postToArticle' :: Entity User -> Post -> Maybe Article
postToArticle' (Entity userKey user) post
    | userKey /= postUser post =
        Nothing
    | otherwise =
        Just (postToArticle (userToPerson user) post)

as a safer option.


text:
Q: DHCP for multi netwok I hope I well get help as I got always in this excellent forum.
We have over 120 networks (192, 172 and 10 ranges)and at the moment our DHCP server is windows server 2008, which I would like to change it to Ubuntu. How should I do that? do I have to create sub interfaces for each network and assign range to it in DHCP,conf ?
I know how to configure Ubuntu DHCP as I've configured 2 / in failover modus(Ubuntu 14.04) for our Wi-Fi system but it is only for one network.
I would like to replace the existing windows server 2008, which is serving for 120 networks with Ubuntu.
Many thanks
Madona33

A: DHCP server only seeing packets on the root eth0 device and ignoring all the packets on the vlan devices
For multi network we must to create vlan's
Install the VLAN support package. For example, type:
sudo apt-get install vlan

Edit your /etc/network/interfaces file for something like this:
iface eth0 inet static
        address xxx.xxx.x.x
        netmask 255.255.255.0
        broadcast xxx.xxx.x.xxx
        network xxx.xxx.x.x

# VLAN 2
iface eth0.2 inet static
address yyy.yyy.y.y
netmask 255.255.255.0
broadcast yyy.yyy.y.yyy
network yyy.yyy.y.y
vlan_raw_device eth0

# VLAN 3
iface eth0.3 inet static
address zzz.zzz.z.
netmask 255.255.255.0
broadcast zzz.zzz.z.zzz
network zzz.zzz.z.z
vlan_raw_device eth0

I placed at /etc/rc.local to have them run after the machine boots:
vconfig set_flag eth0.2 1 1
vconfig set_flag eth0.3 1 1

The vconfig lines tell the devices that they should completely separate the packets, and treat the virtual adapters more like a real network card.
Define a subnet for each vlan, and a placeholder subnet for the root adapter just in case:
# Placeholder for root nic (maybe not needed?)
subnet xxx.xxx.x.x netmask 255.255.255.0 {}

# VLAN 2
subnet yyy.yyy.y.y netmask 255.255.255.0 {
        option routers yyy.yyy.y.y;
        option broadcast-address yyy.yyy.y.yyy;
        pool {
                range yyy.yyy.y.yy yyy.yyy.y.yyy;
        }
}

# VLAN 3
subnet zzz.zzz.z.z netmask 255.255.255.0 {
        option routers zzz.zzz.z.;
        option broadcast-address zzz.zzz.z.zzz;
        pool {
                range zzz.zzz.z.zzz zzz.zzz.z.zzz;
        }
}

Tell the DHCP server what to listen on by editing the /etc/default/isc-dhcp-server file to look something like:
INTERFACES="eth0.2 eth0.3"

restart isc-dhcp-server and you should be good to go.


text:
Q: Configuring OpenSSH according to GitLab's documentation I've stumbled upon GitLab's documentation for setting up OpenSSH keys:
The documentation says to create a file ~/.ssh/config and gives the following example:
# GitLab.com server
Host gitlab.com
RSAAuthentication yes
IdentityFile ~/.ssh/config/private-key-filename-01

# Private GitLab server
Host gitlab.company.com
RSAAuthentication yes
IdentityFile ~/.ssh/config/private-key-filename

However, I think that the example paths for IdentityFile should be ~/.ssh/private-key-filename and not ~/.ssh/config/private-key-filename, since ~/.ssh/config is a file and not a folder.
Or am I missing something?

A: The config file path is not related to IdentityFile path and you're free to use what you want. But there is surely a typo since it's not really common to place keys in the ~/.ssh/config/ directory. Most people have their keys in ~/.ssh/. You're right, this example is wrong. You can't have the configuration file config along with a config directory containing your keys.


text:
Q: Unable to determine the relationship represented by navigation property to an Enum type entity I have this .Net Core 3.1 web project that has an entity (Process) reference to an Enum type entity (Status). It is setup this way to be used by the stateless workflow to handle change of process status in the program. At runtime, it failed at this line with the above exception message:
processes = await _dbContext.Process.ToListAsync();

The complete exception message:
'Unable to determine the relationship represented by navigation property 'Process.Status' of type 'Status'.
Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.'

Below are the model and dbcontext codes:
public enum StatusID : int
{
    [Display(Name = "Draft")]
    Draft = 1,

    [Display(Name ="In Review")]
    InReview = 2,

    [Display(Name = "Approved")]
    Inactive = 3
}

[Table("Status", Schema = "Industrial")]
public class Status
{
    private Status() { }

    [Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
    public StatusID StatusID { get; private set; }

    [StringLength(50)]
    public string Name { get; private set; }
}

[Table("Process", Schema = "Industrial")]
public partial class Process
{
    [Key]
    public int ProcessID { get; set; }
    public StatusID StatusID { get; set; } = StatusID.Draft;
    [ForeignKey("StatusID")]
    public virtual Status Status { get; private set; }
}

public class DbContext
{
    public DbSet<Process> Process { get; set; }
    public DbSet<Status> Status { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Status>().HasNoKey().Property(c => c.StatusID)
         .HasConversion(
             v => v.ToString().ToLowerInvariant(),
             v => (StatusID)Enum.Parse(typeof(StatusID), v, true)
         )
         .HasColumnName("GeneralName")
         .IsUnicode(false);
    }
}

I searched for other posts here, many suggested putting up navigation definition in OnModelCreating method in the DbContext, I've tried a few variants of that, all failed. Here are a couple that I tried:
modelBuilder.Entity<Process>()
                .HasOne("Status", "Status")
                .WithOne("Status");

modelBuilder.Entity<Process>()
                    .HasOne(p => p.Status)
                    .WithOne()
                    .HasForeignKey<Status>(m => m.StatusID)
                    .OnDelete(DeleteBehavior.Restrict);

A: I found the root cause of this problem, it is because my database table generation script has an error in the foreign key creation statement, it should be as below:
ALTER TABLE [Industrial].[Process]  WITH CHECK ADD  CONSTRAINT [FK_Process_Status_StatusID] FOREIGN KEY([StatusID])
REFERENCES [Industrial].[Status] ([StatusID])

what I had was [FK_Process_Status], instead of [FK_Process_Status_StatusID]
This is in Microsoft SQL Server.


text:
Q: Need to use specific rows based off of value Python (Pandas) So I am trying to get specific data from a panda dataset based off of the ID of the row.
This is an example of one of the checks
    if data_df.loc["rowID" == neededID]:
        df = data_df.set_index(['rowID']
        while i < df.rows:
            channel = client.get_channel(neededChannelID)
            message = newsChannelSender(df.iloc[i]) #this generates a message using the data send through
            channel.send(message)
        i = 0

Since I'm using Pycharm, the error I get in the console is : KeyError: 'False: boolean label can not be used without a boolean index'
I've tried being less and more specific within the if statement, but I get varying errors based off what I try.
For example I tried just comparing outside the set_index method, but that also didn't work:
if data_df.loc["rowID"] == neededID:


text:
Q: Progressive Loading of Large PDF document (Linearized) in browser We have a requirement to show the initial page(s) of a PDF while the rest of the document gets loaded in the background.
Our data flow is as follows:
Client Browser<->IBM HTTP Server (JSP/Servlet based application)<->Spring Boot (Restful web service)<->IBM Filenet P8

Currently, for a 15 mb document, it takes around 10-12 secs for the entire document to render in the browser. We need to reduce the time taken by progressively loading the document.
We tried the suggested way of using PDF.js observed the Range Requests going from browser to server but the document is not getting rendered. In Chrome it results in an error message-invalid PDF structure. In Firefox it is going into an infinite loop.
Need help with the requirement in terms of technical solutions.


text:
Q: convert xml into dataset When I tried to convert a xml isolated storage file in dataset I get an exception like "cannot access,because being used by another user"
My code:
IsolatedStorageFile isfInsuranceFirm = null;

isfInsuranceFirm = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly | IsolatedStorageScope.Domain, null, null);
Stream stream1 = new IsolatedStorageFileStream("PageAccess.xml",FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None, isfInsuranceFirm);

stream1.Position = 0;

string path1 = stream1.GetType().GetField("m_FullPath", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(stream1).ToString();
string path2 = stream2.GetType().GetField("m_FullPath", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(stream2).ToString();

XmlDataDocument doc = new XmlDataDocument();
//doc.LoadXml(path1.Substring(path1.IndexOf('/') + 1));
doc.Load(path1);

A: You don't seem to be properly disposing IDisposable resources. You should always wrap them in using statements to ensure that you are not leaking handles:
using (IsolatedStorageFile isfInsuranceFirm = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly | IsolatedStorageScope.Domain, null, null))
using (Stream stream1 = new IsolatedStorageFileStream("PageAccess.xml", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None, isfInsuranceFirm))
{

    stream1.Position = 0;

    string path1 = stream1.GetType().GetField("m_FullPath", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(stream1).ToString();
    string path2 = stream2.GetType().GetField("m_FullPath", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(stream2).ToString();

    XmlDataDocument doc = new XmlDataDocument();
    //doc.LoadXml(path1.Substring(path1.IndexOf('/') + 1));
    doc.Load(path1);
}


text:
Q: Do Spark Window functions work independently per partition? I'm trying to get the latest row for each day for each  some_guid.
For example, I have the following data, everything is sorted by item_time by descending:
+----------+--------------------+-------------+
| file_date|           some_guid|    item_time|
+----------+--------------------+-------------+
|2021-11-22|22549ca165d88ffd2...|1637562345493|
|2021-11-22|22549ca165d88ffd2...|1632637545493|
|2021-11-22|22549ca165d88ffd2...|1632723945493|
|2021-11-22|22549ca165d88ffd2...|1632810345493|
|2021-11-22|22549ca165d88ffd2...|1632896745493|
|2021-11-22|22549ca165d88ffd2...|1632983145493|
|2021-11-22|22549ca165d88ffd2...|1633069545493|
|2021-11-22|22549ca165d88ffd2...|1633155945493|
|2021-11-22|22549ca165d88ffd2...|1633242345493|
|2021-11-22|22549ca165d88ffd2...|1633328745493|
|2021-11-22|22549ca165d88ffd2...|1633415145493|
|2021-11-22|22549ca165d88ffd2...|1633501545493|
|2021-11-22|22549ca165d88ffd2...|1633587945493|
|2021-11-22|22549ca165d88ffd2...|1633674345493|
|2021-11-22|22549ca165d88ffd2...|1633760745493|
|2021-11-22|22549ca165d88ffd2...|1633847145493|

As you see all fields in item_time are different. Then I apply the following transformation:
daily_window = Window.partitionBy('file_date', 'some_guid').orderBy(col('item_time').desc())
df.select('file_date','some_guid', first('item_time').over(daily_window).alias('item_time'))

And get the following result:
+----------+--------------------+-------------+
| file_date|           some_guid|    item_time|
+----------+--------------------+-------------+
|2021-11-22|22549ca165d88ffd2...|1637562345493|
|2021-11-22|22549ca165d88ffd2...|1637562345493|
|2021-11-22|22549ca165d88ffd2...|1637562345493|
|2021-11-22|22549ca165d88ffd2...|1637562345493|
|2021-11-22|22549ca165d88ffd2...|1637562345493|
|2021-11-22|22549ca165d88ffd2...|1637562345493|
|2021-11-22|22549ca165d88ffd2...|1637562345493|
|2021-11-22|22549ca165d88ffd2...|1637562345493|
|2021-11-22|22549ca165d88ffd2...|1637562345493|
|2021-11-22|22549ca165d88ffd2...|1637562345493|
|2021-11-22|22549ca165d88ffd2...|1637562345493|
|2021-11-22|22549ca165d88ffd2...|1637562345493|

There are many duplicates, but I'm expecting only one row. Why does this happen? Is window function performed in each partition and give same row, which is printed later as many times as the partitions I have?
UPD:
How can I do the same if I have the fourth column? For example, select last row in the following dataset:
+----------+--------------------+-------------+------+
| file_date|           some_guid|    item_time|  col4|
+----------+--------------------+-------------+------+
|2021-11-22|22549ca165d88ffd2...|1632562345493| data1|
|2021-11-22|22549ca165d88ffd2...|1632637545493| data2|
|2021-11-22|22549ca165d88ffd2...|1632723945493| data3|
|2021-11-22|22549ca165d88ffd2...|1632810345493| data4|

And I need select last row with 'data4' in the col4

A: use row_number followed by a filter.
daily_window = Window.partitionBy('file_date', 'some_guid').orderBy(col('item_time').desc())
df.select(
    'file_date','some_guid','col4',
    row_number().over(daily_window).alias('rn')
  ).filter("rn = 1")

A: You are aggregating by fill_date and some_guid, and looking at your data you only have one group:

fill_date
some_guid

2021-11-22
22549ca165d88ffd2...

(we don't see the rest of some_guid and appears to be the same to all rows)
Then, its apply the first value for all the rows. Until here its seems correct.
But, I would recommend you try withColumn() instead of select:
df.withColumn('item_time'), first('item_time').over(daily_window))

Edit:
If you expect only one row you want to use groupby. Follow the previous answer: https://stackoverflow.com/a/70081054/13960095
Windows is when you want to all the rows of the group have a calculated value based on the group values.

A: use groupBy:
df.groupBy('file_date','some_guid').agg(max('item_time'))

Or use window-functions (i.e. with rank/row_number) to enumerate the records, then use where/filter to select the desired records


text:
Q: sp.utilities.utility.sendemail + how to send email to multiple users Below is my code to send email through SharePoint (2016 OnPrem)
function sendEmail(from, to,subject,body) {
//Get the relative url of the site
var siteurl = _spPageContextInfo.webServerRelativeUrl;
var urlTemplate = siteurl + "/_api/SP.Utilities.Utility.SendEmail";
$.ajax({
    contentType: 'application/json',
    url: urlTemplate,
    type: "POST",
    data: JSON.stringify({
        'properties': {
            '__metadata': {
                'type': 'SP.Utilities.EmailProperties'
            },
            'From': from,
            'To': {
                'results': [to]
            },
            'Body': body,
            'Subject': subject
        }
    }),
    headers: {
        "Accept": "application/json;odata=verbose",
        "content-type": "application/json;odata=verbose",
        "X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
    },
    success: function(data) {
        //alert('Email Sent Successfully');
        var isSent = true;
    },
    error: function(err) {

        alert('Error in sending Email to System Admin: ' + JSON.stringify(err));

    }
});

}
and below is my calling statement;
sendEmail("abc@def.com","a@b.com,b@b.com","Test Subject","Test Body");

Email gets sent when there is 1 user. However when trying with multiple users getting error
Error in sending Email to System Admin: {"readyState":4,"responseText":"{\"error\":{\"code\":\"-2130242040, Microsoft.SharePoint.SPException\",\"message\":{\"lang\":\"en-US\",\"value\":\"The e-mail message cannot be sent. Make sure the e-mail has a valid recipient.\"}}}","responseJSON":{"error":{"code":"-2130242040, Microsoft.SharePoint.SPException","message":{"lang":"en-US","value":"The e-mail message cannot be sent. Make sure the e-mail has a valid recipient."}}},"status":400,"statusText":"Bad Request"}
Kindly let know how to put multiple users in TO. Tried with ; seperated email addresses. However same error.
Thank you

A: The format of your "To" variable must be an Array witch contains emails (or domain\login).
Here, you pass a string witch contains email separated by comma.
Try somthing like :
var recipients = ["a@b.com","b@b.com"];
sendEmail("abc@def.com",recipients ,"Test Subject","Test Body");

And change the "data" in your query like :
data: JSON.stringify({
        'properties': {
            '__metadata': {
                'type': 'SP.Utilities.EmailProperties'
            },
            'From': from,
            'To': {
                'results': to
            },
            'Body': body,
            'Subject': subject
        }
    })

Like kasper said, your recipent must be a SharePoint site users. (And the From too)
You can't send Email from sharepoint to other email who are not in your organisation
check this link for an exemple : SharePoint 2013: REST API/Client Code to send mails


text:
Q: Can I define a variable in Visual Studio debugger? I am wondering if I could define a variable during debugging in visual studio. For instance, I want to know how many times the breakpoint was hit when some flag was true. This rquirement seems need more advanced programmable skill to visual studio debugger.
Visual studio conditional breakpoint can only satisfy partial requirement.

A: To determine the hit count of a break point, set the required hit count of break point to a very high value which you don't expect to be reached.
Then you can examine the break point's current hit count by hovering the break point icon on the left or by right-clicking it and then chosing "Hit Count..." again.
int c3 = 0;
int c5 = 0;
for(int i = 0; i < 100; ++i)
{
    if(0 == i % 3)
    {
        ++c3; // Set break point with hit count 1000 here
    }

    if(0 == i % 5)
    {
        ++c5; // Set normal break point here
    }
}

In the above example, when you reach the normal break point, you can examine the hit count of the other break point.

A: Why don't you use a IFDEBUG kind of flag and conditional compiling?


text:
Q: Optimizing a Dynamic Balanced Tournament I would like to create a schedule for a set of players to play a tournament.  The players are divided into a number of teams, and each round consists of the matches between these teams.
The type of schedule I would like to make should conform to Balanced-Tournament Design.  This means:

*

*each team plays at each location

*

*Sometimes, locations are not always equal.  For example, the centre court at Wimbledon.  A balanced tournament should let everyone play at every location a fair number of times.

*each team plays every other team

*

*A staple of most round robin tournaments

*each team is "home" and "away" and equal number of times

*

*In team sports, often there needs to be a home and away team.  In baseball, for example, the home team gets to bat last in each inning.  This can be an advantage, so a balanced tournament should let every team have this opportunity an equal number of times.

I've had a lot of success using Orthogonal Latin Squares and Factored Balanced Tournament Design, and found a decent way to generate such tournaments.
However, I would like to now do something a little different:

*

*Players are grouped (e.g. based on skill or position).  A team needs one player of each group (e.g. one player of each position or skill level)

*Each round, the teams and matches are recreated such that

*

*The number of times two people play with each other is minimized

*The number of times two people play against each other is minimized

This is similar to Individual-Pairs tournaments, but in my problem, the teams can have more than 2 players and the players are grouped such that each team requires a player from each group.  By changing the teams each round, a single player from each group (e.g. position or skill level) can "win" the tournament by winning more games than any other player.
More formally, this could be described as follows (I am open to changing this notation should anyone have a better way to represent this):

*

*There are p players, divided up into g groups, each consisting of t=p/g players.

*Groups of players are labelled Gi={Pi1, Pi2, ... Pit} where

*

*i is the number of the group (0<=i<=g)

*All players in this group are the same position/skill level, so a team will have exactly one player from each group.

*Players are labelled Pij where

*

*i is the group the player belongs to (0<=i<=g)

*j is the number of the player within group i (0<=j<=t)

*The schedule will contain r=t-1 rounds

*

*This will let everyone play against everyone else within their group.

*Each round, t teams and m=t/2 matches must be created

*Teams are labelled Tij={P1a, P2b, ... Pgc} where

*

*i is the round this team is for (0<=i<=r)

*j is the number of the team within round i(0<=j<=t)

*Each team consists of exactly one player from each group

*Matches are labelled Mij={Tia, Tib} where

*

*i is the round this match is for (0<=i<=r)

*j is the number of the match within round i (0<=j<=m)

*Minimize the following

*

*The number of times two players in the same group play together

*

*a team can only have one player from each group, so this must be 0

*The number of times two players in different groups play together

*

*Through the course of the tournament, two players shouldn't be on the same team more than once

*The number of times two players in the same group play against each other

*

*Should be exactly 1 if r=t-1

*The number of times two players in different groups play against each other

*

*In my experience, this might have to be twice

Should this prove too complicated, I am more than willing to discuss the more specific case where:

*

*each team consists of 4 players (g=4)

*the number of teams is "low", between 5 and 12 (20 to 48 players)

*the number of rounds does not need to be t-1.

*

*If it is t-1, then a player could (and should) play against all the other players of the same group exactly once.  This may not be possible to create, so I would accept a solutions where r is maximized such that a player never plays against another player in the same group more than once (i.e. some players in a group may never play against each other).

While methods dealing generic problem are great, I am most interested in these specific cases since those are what motivated me to look at this problem in more detail.
Thanks!


text:
Q: Not able to run my first program after installing WAMP I installed WAMP. I tested it by localhost\index.php, works. Then I created my first project under www folder named firstproject. I put index.html and xyz.php in it. My xyz.php contents are
<?php
  echo "My first PHP script!";
?>

My index.html contents are:
<html lang="en">
  <head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function(){
        var auto_refresh = setInterval(function (){
          //alert("abc");
          $('#mydiv').load('xyz.php').fadeIn("slow");
        }, 1000);
      });
    </script>
  </head>
  <body>
    <div id="mydiv"> </div>
  </body>
</html>

When I run index.html, browser is blank. When I try to access xyz.php directly like localhost/firstproject/xyz.php, it works
I had asked similar question yesterday,
SetInterval function is not working with PHP File
everybody says it works on their system. Then why its not working on my system. Is there any configuration I have to do? Please suggest. I am not able to run this simple project.

A: Your code is perfectly fine. Check if javascript is enabled in your browser. If not than please enable it and restart the browser.

A: I renamed index.html to index.php and called that by localhost/firstproject/index.php. That worked


text:
Q: What might be the cause of regular periodic slow transactions on an OLTP system? I have a two node Oracle RAC cluster with that runs an oltp application against it.  I have both a production and a duplicate test environment with the same setup. Upon running stress tests on the Test environment (about 160 tps), The average latency is about 70ms.  I noticed that when I examined the maximum transaction time within each minute, that there is a regular spike in the maximum transaction time every 5 minutes of several transactions that take about 1200-1500 ms.  I've traced the individual long transactions down to the second  and them seem to last for anywhere from 3-5 seconds.  There don't seem to be any regular running jobs that would effect the transactions.   In  environment, we see the same thing and in fact once in a while, we see bigger spikes of transactions taking 15-20 seconds (15000-20000 ms) to complete.  While our production environment is in a pilot mode right now, and only pushes about 4 tps, we do still see these spikes where maximum transaction lengths reach 1200-1500 ms, and they also seem to occur on 5 minute intervals.
I have performed ASH analytics on the small few second intervals, and it seems that there is no common wait event that occurs during these spikes.  Sometimes we see "log file sync" events, sometimes we see "gc busy" or other "gc" wait events.  It seems to vary.  I'm just trying to figure out how to diagnose the underlying cause of this periodic slowness.  Any ideas would be appreciated.

A: High Log File Sync wait events mean that throughput on writing to the online redo logs is not high enough. This blog gives a great explanation of how to diagnose and troubleshoot that event:
http://logicalread.solarwinds.com/oracle-log-file-sync-wait-event-dr01/#.V_TSTvkrKUk
GC Busy and other GC wait events indicate RAC cluster related waits. We'd need to see a lot more detail to troubleshoot this accurately. That said, if you are having Log File Sync waits on some or all nodes, most likely the other nodes will start showing GC wait events. The nodes have to cooperate with each other. When one node has problems, the whole cluster is affected.


text:
Q: Reuse Java Bean in Jackson Library When using the Jackson library from FasterXML using an ObjectMapper a new instance of an object (Java Bean) is instantiated every time a JSON string is read. In the following example, a new instance of class Person is created:
ObjectMapper om = new ObjectMapper();
Person p = om.readValue("{\"name\":\"Bob\",\"age\":20}", Person.class);

How can I reuse an old instance of Person and avoiding creating new instances? In this way I avoid doing unnecessary garbage collection.


text:
Q: Rails 5: how to change log level in rails console? I'm using Rails 5.2.5 and I want to change the log level when I use rails console.
I want to stress that I don't want to change any file in the project, but just to do the change from the console.
I saw some suggestions to run:
conf.log_level = :debug

in the console, but I got the error

NameError (undefined local variable or method `config' for
main:Object) Did you mean?  conf

I also tried to execute
conf.log_level = :debug

but I also got the error:

Traceback (most recent call last):
2: from (irb):11
1: from (irb):11:in `rescue in irb_binding'

Do you have any suggestion?

A: Change YourApp configuration (YourApplocated at config/environment/[environment].rb
YourApp.configure do
 config.log_level = :info
end

Or you can use Rails.application.configure
2.5.8 :005 > Rails.application.configure do
2.5.8 :006 >     puts(config.log_level)
2.5.8 :007?>   end
debug
 => nil
2.5.8 :008 > Rails.application.configure do
2.5.8 :009 >     config.log_level = :info
2.5.8 :010?>   end
 => :info
2.5.8 :011 > Rails.application.configure do
2.5.8 :012 >     puts(config.log_level)
2.5.8 :013?>   end
info


text:
Q: restricting hangfire to pick up jobs from a specific queue I have 2 hangfire instances/servers running. Both point to the same hangfire database. How do I restrict one of the hangfire instance to pick up only jobs from a specific queue and ignore other queues?
Thanks

A: When you start your instance, you can provide a list of queues to be watched by the server:
app.UseHangfireServer(new BackgroundJobServerOptions()
    {
        // order defines priority
        // beware that queue names should be lowercase only
        Queues = new [] { "critical", "default", "myqueue" }
    });

A: Believe the Hangfire servers will poll the registered queues for jobs, so first come first serverd if you have the same queue registered with multiple servers.
As mentioned above, just have some queues on each server with unique queue names, as this is what Hangfire used to determine where it gets processed.
For instance, in my case I have 1 server for general maintenance queues applicable to all servers and the app in general, whereas the environment servers contain queues where the jobs target environment specific tasks.


text:
Q: Add global basename/context to React and npm settings I have a problem with urls, I need to run my application not from localhost:8081, but from localhost:8081/admin, so all pages shows me 404, which have /...., anyway main page also doesn't work good, in index.html I have also  tag, example of file.
<link href="../public/css_admin/fonts/fonts.css" rel="stylesheet"/>

Webpack configuration
var path = require('path');

module.exports = {
    entry: './src/index.jsx',
    output: {
        path: path.resolve('dist'),
        publicPath: '/admin/',
        filename: 'bundle.js'
    },
    resolve: {
        extensions: ['.js', '.json', '.jsx']
    },
    .....
    devServer: {
        contentBase: './',
        historyApiFallback: true,
        host: 'localhost',
        port: 8081
    },
    externals: {
        config: JSON.stringify({
            apiUrl: '..../rest/v1'
        })
    }
}

App route
render() {
        return (
            <Router history={history}  basename="admin">
                <div>
                    <Switch>
                        <PrivateRoute exact path="/" component={MainIndexPage} refresh={false} />
                        <PrivateRoute exact path="/staff" component={StaffPage}  refresh={false}  />
                        <Route path="/register" component={RegisterPage} />
                    </Switch>
                </div>
             </Router>

    );
}

A: First, I'm a beginner. basename="admin" or basename="/admin".

A: So please add basename to the history,
export const history = createBrowserHistory({basename: '/admin'});

Also change
 filename: 'bundle.js' -> filename: 'app-[hash].js'


text:
Q: How can I get the TYPO3 "appearance" media images by using "ViewHelper"? thanks for reading and answering...
I have some TYPO3 gridelements in my TYPO3 pagecontent.
Each gridelement has a tab "appearance", where I define an image file.
The database relation from tt_content to the media image are in sys_file_reference.
My question is how can I get this image file in my fluid template by using the ViewHelper and the uid of my gridelement?

A: I wrote an little ViewHelper (tested on 7.6, but should not need so much changes for 8.7) to get referenced images for an newsletter layout:
<?php
  namespace Vendor\Extension\ViewHelpers;

  use TYPO3\CMS\Core\Log\LogManager;
  use TYPO3\CMS\Core\Resource\FileRepository;
  use TYPO3\CMS\Core\Utility\GeneralUtility;
  use TYPO3\CMS\Core\Resource\FileReference;
  use TYPO3\CMS\Core\Resource\Exception;
  use TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelper;
  use TYPO3\CMS\Fluid\Core\ViewHelper\Facets\CompilableInterface;
  use TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer;

  class ImagesReferencesViewHelper extends AbstractViewHelper implements CompilableInterface
  {

    /**
     * Iterates through elements of $each and renders child nodes
     *
     * @param int     $uid       The ID of the element
     * @param string  $table     The Referenced table name
     * @param string  $fieldName The Referenced field name
     * @param string  $as        The name of the iteration variable
     * @param string  $key       The name of the variable to store the current array key
     * @param boolean $reverse   If enabled, the iterator will start with the last element and proceed reversely
     * @param string  $iteration The name of the variable to store iteration information (index, cycle, isFirst, isLast, isEven, isOdd)
     * @param string  $link      The name of the variable to store link
     *
     * @return string Rendered string
     * @api
     */
    public function render($uid, $table = 'tt_content', $fieldName = 'assets', $as, $key = '', $reverse = false, $iteration = null, $link = null)
    {
      return self::renderStatic($this->arguments, $this->buildRenderChildrenClosure(), $this->renderingContext);
    }

    /**
     * @param array                                                     $arguments
     * @param \Closure                                                  $renderChildrenClosure
     * @param \TYPO3\CMS\Fluid\Core\Rendering\RenderingContextInterface $renderingContext
     *
     * @return string
     * @throws \TYPO3\CMS\Fluid\Core\ViewHelper\Exception
     */
    static public function renderStatic(array $arguments, \Closure $renderChildrenClosure, \TYPO3\CMS\Fluid\Core\Rendering\RenderingContextInterface $renderingContext)
    {
      $templateVariableContainer = $renderingContext->getTemplateVariableContainer();
      if ($arguments['uid'] === null || $arguments['table'] === null || $arguments['fieldName'] === null) {
        return '';
      }

      /** @var FileRepository $fileRepository */
      $fileRepository = GeneralUtility::makeInstance(FileRepository::class);
      $images         = array();

      try {
        $images = $fileRepository->findByRelation($arguments['table'], $arguments['fieldName'], $arguments['uid']);
      } catch (Exception $e) {
        /** @var \TYPO3\CMS\Core\Log\Logger $logger */
        $logger = GeneralUtility::makeInstance(LogManager::class)->getLogger();
        $logger->warning('The file-reference with uid  "' . $arguments['uid'] . '" could not be found and won\'t be included in frontend output');
      }

      if (is_object($images) && !$images instanceof \Traversable) {
        throw new \TYPO3\CMS\Fluid\Core\ViewHelper\Exception('ImagesReferencesViewHelper only supports arrays and objects implementing \Traversable interface', 1248728393);
      }

      if ($arguments['reverse'] === true) {
        // array_reverse only supports arrays
        if (is_object($images)) {
          $images = iterator_to_array($images);
        }
        $images = array_reverse($images);
      }
      $iterationData = array(
        'index' => 0,
        'cycle' => 1,
        'total' => count($images)
      );

      $output = '';
      foreach ($images as $keyValue => $singleElement) {
        $templateVariableContainer->add($arguments['as'], $singleElement);

        /** @var FileReference $singleElement */
        if ($arguments['link'] !== null && $singleElement->getLink()) {
          $link = $singleElement->getLink();
          /** @var ContentObjectRenderer $contentObject */
          $contentObject = GeneralUtility::makeInstance(ContentObjectRenderer::class);
          $newLink       = $contentObject->typoLink_URL(array('parameter' => $link));
          $templateVariableContainer->add($arguments['link'], $newLink);
        }

        if ($arguments['key'] !== '') {
          $templateVariableContainer->add($arguments['key'], $keyValue);
        }
        if ($arguments['iteration'] !== null) {
          $iterationData['isFirst'] = $iterationData['cycle'] === 1;
          $iterationData['isLast']  = $iterationData['cycle'] === $iterationData['total'];
          $iterationData['isEven']  = $iterationData['cycle'] % 2 === 0;
          $iterationData['isOdd']   = !$iterationData['isEven'];
          $templateVariableContainer->add($arguments['iteration'], $iterationData);
          $iterationData['index']++;
          $iterationData['cycle']++;
        }
        $output .= $renderChildrenClosure();
        $templateVariableContainer->remove($arguments['as']);
        if ($arguments['link'] !== null && $singleElement->getLink()) {
          $templateVariableContainer->remove($arguments['link']);
        }
        if ($arguments['key'] !== '') {
          $templateVariableContainer->remove($arguments['key']);
        }
        if ($arguments['iteration'] !== null) {
          $templateVariableContainer->remove($arguments['iteration']);
        }
      }
      return $output;
    }
  }


text:
Q: How to cleanup all autogenerated files? To create distribution in perl I use Module::Build. And generate meta files by command: ./Build distmeta
Creating Makefile.PL
Creating README using Pod::Text
Creating LICENSE file
Created META.yml and META.json

At some point I decide to delete all autogenerated files. I run ./Build distclean
Cleaning up build files
Cleaning up configuration files

But metafiles are left: README, LICENSE
Is there a command to cleanup those files too?

A: The META files are removed because those are purely generated, but README and LICENSE are often customized, so they can't be safely removed or overwritten.
If you don't customize README and LICENSE, and if you insist on having a means of removing them, there is a solution if you use git. Don't add the files to the repository (which is made easy by adding them to .gitignore), and use git clean -dfx (instead of ./Build distclean) to freshen your directory.


text:
Q: Issues in Javascript with Async and Await, cannot get the function to wait for the first function to be completed Im new to javascript and Im having an issue with Async and Await. To my understanding the async function will wait for the await function to be completed before running. I dont know if my function is written correctly but Ive tried passing no argument to the await function along with many different variations. unfortunately the logout function runs before the setStatus function is done running. Any help or direction will be greatly appreciated.
function getConfirmationToSaveAndExit() {
               var retVal = confirm("Are you sure you would like to Save Item & Logout?");
               if( retVal == true ) {
                      setStatus('Incomplete');
                      logout();
                      return true;
               } else {
                  console.log("user does not want to continue");
                  return false;
               }
            }

function setStatus(status){
    document.getElementById('filledStatus').value=status;
    showLoader();
}

async function logout(){
    await setStatus('Incomplete');
        window.location.href="/logout";
}

A: setStatus(<args>) {...} function should be an async function or should return a Promise or a function invocation which returns a Promise as well. To be more precise you can even await on an async function without explicitly returning from it. e.g.:
async testFunc() {
  console.log('But, all things being equal, I would rather be in Philadelphia.');
}

This function implicitly returns undefined wrapped into a Promise so you can await on it.


text:
Q: Iterate through jquery selector I have codes that I am sure are pretty redundant and I want to make it shorter and cleaner.
So I have a list of five domains that has a slider for each. I'm using the Simple Slider five times. I have this:
$("#domain-1").bind("slider:changed", function (event, data) {
  alert(data.value);
  alert(data.ratio);
});

$("#domain-2").bind("slider:changed", function (event, data) {
  alert(data.value);
  alert(data.ratio);
});

$("#domain-3").bind("slider:changed", function (event, data) {
  alert(data.value);
  alert(data.ratio);
});

$("#domain-4").bind("slider:changed", function (event, data) {
  alert(data.value);
  alert(data.ratio);
});

$("#domain-5").bind("slider:changed", function (event, data) {
  alert(data.value);
  alert(data.ratio);
});

How do I simplify this so I don't have to repeat the codes? I have to use IDs cause each slider should be unique. Thank you!

A: Use Multiple Selector ("selector1, selector2, selectorN")
$("#domain-1, #domain-2,#domain-3,#domain-4,#domain-5").bind("slider:changed", function (event, data) {
  alert(data.value);
  alert(data.ratio);
});

A: Assigning a class to them all may work out easier.
$(".domains").bind("slider:changed", function (event, data) {
    alert(data.value);
    alert(data.ratio);
 });


text:
Q: How do you setup the firestore rules with a custom authentication token, and then how do you connect with the token in Java? I am trying to setup the security rules and also connect to the firestore database with a custom token. The token is passed to the webpage via cookies which works nicely, however then, I can't connect to the firestore database properly.
Here is how I attempt to connect on the HTML page:
firebase.initializeApp({
      apiKey: "REDACTED",
      authDomain: "REDACTED.firebaseapp.com",
      projectId: "REDACTED"
    });

    var db = firebase.firestore();

    firebase.auth().signInWithCustomToken(cookie_val)
    .then((userCredential) => {
      // Signed in
      var user = userCredential.user;
      // ...
    })
    .catch((error) => {
      var errorCode = error.code;
      var errorMessage = error.message;
      // ...
    });

My rules on the firestore database are below:
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
      allow read, write: if request.auth != null;
    }
    match /commmunities/{communityId} {
        allow read: if request.resource.community_id == communityId;
    }
  }
}

Please let me know why/how I should be connecting to the firestore database with a custom token. I have rigorously read the Google documentation and I'm struggling to comprehend them.
EDIT:
This project is being run on a website, and here is the code to login with the custom token:

    <meta charset="utf-8"/>

    <title>PROFILE SYSTEM</title>

PROFILE PRESENCE LOADER

OLD CONTENT

The cookie that is collected in the script above, is generated in the flask webserver and is set as a cookie here:

uid = f'{newid}'
          additional_claims = {
            'community_id': 231231
          }

          custom_token = auth.create_custom_token(uid, additional_claims)

          resp = make_response(redirect('/client'))
          resp.set_cookie('CUSTOM TOKEN', f'{custom_token}')


text:
Q: Повреждаются данные в объекте Есть приложение (на Kotlin). Оно получает большой JSON-объект (2,5 мегабайта, маленький List в нем объекты с полями Float, String и большой List с объектами из Float, Date и Int) из API (Retrofit2 + OkHttp). В приложении это кэшируется в WeakReference внутри синглтона (простой кэш, чтобы не перезагружать данные, пока юзер переключает фрагменты).
Далее эти данные перебираются циклами (чтобы выбрать нужный кусок) и из этого куска заполняются вьюхи.
Проблема в том, что иногда, после нескольких перезагрузок некоторые цифры во втором объекте обнуляются или содержат какие-то случайные значения.
Пробовал отключать кэш, вьюхи, обновил com.squareup.retrofit2:converter-gson, проверял API. Баг повторяется снова и снова.
Почему значения в объекте могут принимать нулевые или случайные значения? В какую сторону следует копать? Может ли это быть проблема с памятью из-за того, что я работаю с большим объектом напрямую?


text:
Q: MySQL sub query very slow I am developing a LMS in which i have develop an inquiry management system.
the system was working well when database has a few entries
the notification system is based on two tables one is the inquiry information table and the other one has the next follow up date and time including comments

Here is the inquiry table

And this one for inquiry follow up,
and this is the query that i am using to get all the pending inquiries where the date is less than and equal to current date
SELECT t1.*
FROM enquiry_follows AS t1
WHERE t1.dfollow = (   SELECT MAX(t2.dfollow)
                       FROM enquiry_follows AS t2
                       WHERE (t2.enquiryid = t1.enquiryid)
                       AND NOW () >= t2.dfollow
                       AND status = 'unseen'
                       AND EXISTS (   SELECT t3.*
                                      FROM inquiries AS t3
                                      WHERE t2.enquiryid = t3.id
                                      AND status = 'pending'
                                      AND campus = '".$_SESSION['campus']."'))
ORDER BY t1.dfollow DESC;


text:
Q: How to detect navigation back with child coordinators I use coordinator pattern with child coordinators to provide loosely coupled code and accordant with single responsibility principle. To handle with navigating back I've decided to use navigation controller delegate (accordingly with this article https://www.hackingwithswift.com/articles/175/advanced-coordinator-pattern-tutorial-ios).
But my problem is that I have Home VC with Home Coordinator, next I go to Workout VC with Workout Coordinator and next I go to Exercise VC with Exercise Coordinator.
So I want to have a Workout Coordinator and Exercise Coordinator as children for Home Coordinator.

And everything seems to be ok, but I have a memory leak between the Workout Coordinator and Exercise Coordinator because I can't delete the exercise coordinator after I use the back button to navigate back. My navigation controller delegate doesn't recognize when I back.
class HomeCoordinator: NSObject, Coordinator, UINavigationControllerDelegate {

    var childCoordinators = [Coordinator]()
    var navigationController: UINavigationController

    init(navigationController: UINavigationController) {
        self.navigationController = navigationController
        navigationController.navigationBar.prefersLargeTitles = true
        navigationController.navigationBar.largeTitleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.white]
    }

    func start() {
        navigationController.delegate = self
        let vc = HomeFactory.makeHomeScene(delegate: self)
        navigationController.pushViewController(vc, animated: false)
    }

    func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {

        guard let fromViewController = navigationController.transitionCoordinator?.viewController(forKey: .from) else { return }

        if navigationController.viewControllers.contains(fromViewController) {
            return
        }

        if let addWorkoutViewController = fromViewController as? NewWorkoutViewController {
            let workoutCoordinator = addWorkoutViewController.presenter?.workoutCoordinatorDelegate
            childDidFinish(workoutCoordinator)
        }
    }
}

extension HomeCoordinator: HomeCoordinatorDelegate {

    func goToWorkoutCreating() {
        let child = AddWorkoutCoordinator(navigationController: navigationController)
        child.passWorkoutToHomeDelegate = self
        childCoordinators.append(child)
        child.parentCoordinator = self
        child.start()
    }
}

class AddWorkoutCoordinator: NSObject, Coordinator, UINavigationControllerDelegate {

    var parentCoordinator: Coordinator?
    var exerciseNumber: Int?

    weak var passWorkoutToHomeDelegate: PassWorkoutToHome?

    var childCoordinators = [Coordinator]()
    var navigationController: UINavigationController

    init(navigationController: UINavigationController) {
        self.navigationController = navigationController
        navigationController.navigationBar.tintColor = .white

    }

    func start() {
        let vc = AddWorkoutFactory.makeAddWorkoutScene(delegate: self)
        navigationController.pushViewController(vc, animated: true)
    }

    func childDidFinish(_ child: Coordinator?) {
        for (index, coordinator) in childCoordinators.enumerated() {
            if coordinator === child {
                childCoordinators.remove(at: index)
                break
            }
        }
    }

// THIS FUNCTION IS NOT RESPOND AT ALL, BUT IT RESPONDS IN HOME COORDINATOR
        func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {

        guard let fromViewController = navigationController.transitionCoordinator?.viewController(forKey: .from) else { return }

        if navigationController.viewControllers.contains(fromViewController) {
            return
        }

        if let newExerciseViewController = fromViewController as? NewExerciseViewController {

//            childDidFinish(newExerciseViewController.presenter?.exerciseCoordinatorDelegate)
//            childDidFinish(newExerciseViewController.presenter!.exerciseCoordinatorDelegate)
        }
    }
}

extension AddWorkoutCoordinator: AddWorkoutCoordinatorDelegate {

      func goToAddExercise() {

          let child = AddExerciseCoordinator(navigationController: navigationController)
          child.passExerciseToWorkoutDelegate = self
          childCoordinators.append(child)
          child.start()
      }

class AddExerciseCoordinator: NSObject, Coordinator {

    weak var passExerciseToWorkoutDelegate: PassExerciseToWorkoutDelegate?

    var childCoordinators = [Coordinator]()
    var navigationController: UINavigationController

    init(navigationController: UINavigationController) {
        self.navigationController = navigationController
        self.navigationController.navigationBar.tintColor = .white
    }

    func start() {
        let vc = AddExerciseFactory.makeAddExerciseScene(delegate: self)

        navigationController.pushViewController(vc, animated: true)
    }

    func startEditExercise(setData: [ExerciseFieldsModel], exerciseName: String) {
        let vc = AddExerciseFactory.makeAddExerciseScene(delegate: self)
        vc.presenter?.textFieldsModel = setData
        vc.exerciseText = exerciseName
        navigationController.pushViewController(vc, animated: true)
    }
}

extension AddExerciseCoordinator: NewExerciseCoordinatorDelegate {

    func saveExercise(newExercise: ExerciseCellInNewWorkout) {
        navigationController.popViewController(animated: true)
        passExerciseToWorkoutDelegate?.passExerciseToWorkout(exercise: newExercise)
    }
}

So basically the problem is that using navigate controller delegate didShow method I need to get the type of "fromViewController", so if I have one child like Workout Coordinator, everything is ok, I cant remove it easily, but when I have one layer deeper, so I have Workout Coordinator and after that Exercise Coordinator I don't know how to use navigation controller delegate didShow method to recognize if Exercise Coordinator is popped. So I have tried to use navigation controller didShow also in Workout Coordinator, but as I wrote in a comment in code, it doesn't respond at all.
Could you help me to get some advice on how to detect if the user taps the back button on exercise VC? Or maybe my conception is bad and only the workout coordinator should be a child and the exercise coordinator should not be.

A: When your ExerciseViewController goes out of scope (gets deleted) it should be notifying the object that pushed it on the navigation controller. It looks like that is your ExerciseCoordinator.
Setup your Coordinator containment system the same way UIKit's view containment system is setup. Where a Coordinator has an addChild(coordinator:) method and a removeFromParent() method. When the view controller notifies its coordinator that it went out of scope, the coordinator should call its removeFromParent() method.
The system above is far better than relying on didShow and works for any sort of method of presentation.


text:
Q: MONGO + SPRING: The matching wildcard is strict, but no declaration can be found for element 'mongo:db-factory' How fix this error?
Context content:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns="http://www.springframework.org/schema/beans"
   xmlns:mongo="http://www.springframework.org/schema/data/mongo" xsi:schemaLocation=
           "http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-4.2.xsd">
<mongo:db-factory dbname="#{properties.getProperty('mongo.database')}"
                  password="#{properties.getProperty('mongo.password')}"
                  username="#{properties.getProperty('mongo.user')}"
                  port="#{properties.getProperty('mongo.port')}"
                  host="#{properties.getProperty('mongo.host')}"/>

Spring and Mongo versions:
4.3.2.RELEASE
3.3.0

A: You are missing the schema location for mongo namespace:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:mongo="http://www.springframework.org/schema/data/mongo"
 xsi:schemaLocation="http://www.springframework.org/schema/data/mongo
                  http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
                  http://www.springframework.org/schema/beans
                  http://www.springframework.org/schema/beans/spring-beans-4.2.xsd">


text:
Q: Find All Subsets in an array, Recursion is not working, JavaScript I am trying to implement Given a set of distinct integers, S, return all possible subsets problem.
[A, B, C] should give  [ [ ], [A], [A, B], [A, B, C], [A, C], [B], [B, C], [C] ].
Cannot figure out why the function does not backtrack.
For input [A, A, B, C], my implementation outputs [ [], ["A"], ["A", "A"],  ["A", "A", "B"], ["A", "A", "B", "C"] ]
This is my code.
var subsets = function(A){
  /*for input [ A, A, B, C ], appendCount returns [ [A, 2], [B, 1], [C,1] ]*/
  var arr = appendCount(A);
  result =[[]];
  var tempArr = [];

  var findSubsets = function(index, tempArr, a) {
    var arrCopy = a.slice();
    while(index < arrCopy.length) {
      if(arrCopy[index][1] > 0) {
        tempArr.push(arrCopy[index][0]);
        result.push(tempArr.slice());
        var newArr = arrCopy.slice();
        newArr[index][1] -= 1;
        findSubsets(index, tempArr, newArr);
        tempArr.pop();
        index++;
   } else {
       index++;
   }
 }
}
 findSubsets(0, tempArr, arr.slice());
 return result;
}

Thanks in advance

A: Recursive
function findSubsets( array, position ){
    position = position || 0;

    if (position >= array.length) return [[]];

    var output = findSubsets( array, position + 1 );

    for (var i = 1, endI = output.length; i < endI ; i++){
        output.push(
            output.slice(i, i+1).concat( array[position] )
        );
    };

    return output.concat( array[position] );
};

Iterative
function findSubsetsIterative( array ){
    var output = [];

    for (var n = 0 , limit = 1 << array.length ; n < limit ; n++) {
        var subSet = [];
        for (var i = n, p = 0; i ; i >>= 1, p++){
            if (i & 1) subSet.push( array[p] );
        };
        output.push( subSet )
    };

    return output;
};

A: Instead of creating a new array for each recursion call, use a common array for characters and their count and reset the character count values while backtracking.
var subsets = function(array) {
var charCountArray = appendCount(array);
var result = [[]];
var findSubsets = function(tempArray, index) {
   if(index >= array.length) {
     return;
   }
   for(var i=index; i<charCountArray.length; i++) {
    if(charCountArray[i][1] <= 0) {
      continue;
    }
    tempArray.push(charCountArray[i][0]);
    result.push(tempArray.slice());
    charCountArray[i][1] -= 1;
    findSubsets(tempArray, i);
    charCountArray[i][1] += 1;
    tempArray.pop();
 }
}
findSubsets([],0);
return result;
}


text:
Q: Jquery - find content between span tag and appen My span tag looks like this test123 what i want to do is read the contents between the tag and add a Copyright 2013 before the  tag, so it would look like test123Copyright 2013

A: $('span[itemprop="description"]').append("Copyright 2013");

this should fix it, even though i am not sure if the selector is correct
as suggested here's a link to the documentation

A: use .append():
$(function(){
  $('span[itemprop="description"]').append('Copyright 2013');
});

A: $("span[itemprop='description']").append("Copyright 2013");


text:
Q: Can't start a server in BlackBox I'm trying to start a server in BlackBox and so far I have just this
    MODULE server;
        IMPORT Dialog,Strings,Win:=WinApi, Server:=CommObxStreamsServer, Stream:=CommStreams;

    BEGIN
        Server.Start();
        Server.Stop();
    END server.

and when I run it I get the error
server:error starting the server(2). I looked up that error 2 means invalid local address but start method doesn't require any arguments and I don't get where should I specify my local address:
code from documentation (theories: do i need to start a new listener myself? are default ports busy? (upd:it's 900 and it's open))
SOLVED! In CommObxStreamsServer file:
localAdr="900" change to localAdr="localhost:900"

A: In CommObxStreamsServer file: localAdr="900" should be changed to localAdr="localhost:900"


text:
Q: testing for quadratic residues using Legendre's symbol So I am a bit confused about an example in the book Elementary Number Theory by Jones. I am doing a problem which makes me show 3 is a quadratic residue of 13, but not of 7. I did this question numerically using the law of quadratic reciprocity. I am a bit confused about the example it gives though.
First lets see what the theorem says. It says that if $p, q$ are distinct odd primes, then  $$\left( \frac{q}{p} \right) = \left( \frac{p}{q} \right)$$
except when the case $p \equiv q \equiv 3 \pmod 4$. An equivalent result by Legendre is  $$ \left( \frac{q}{p} \right) \cdot \left( \frac{p}{q} \right) =(-1)^{(p-1)(q-1)/4}$$
Note that I have shown $3$ is not a quadratic residue of 7. The example states the following

For which primes $p$ is 3 a quadratic residue. Since 3 is a QR of 2 and 3 is NOT a QR of 3, we may assume $p>3$. If $p \equiv 1 \mod 4$ then the law gives $$\left( \frac{3}{p} \right) = \left( \frac{p}{3} \right) = \begin{cases} +1 & \text{if $p \equiv 1 \pmod 3$, that is if $p \equiv 1 \pmod {12}$} \\
-1 &\text{if $p \equiv 2 \pmod 3$, that is if $p \equiv 5 \pmod {12}$} \end{cases} $$

It further has more case when $p \equiv 3 \pmod 4$ .
So my questions are (though basic):
1) Why do they assume $p>3$.
2) How can $p \equiv 1 \pmod 3$ mean $p \equiv 1 \pmod 12$
and if we take $p  = 7$ then since $7 \equiv 1 \pmod 3$ it must be that $$ \left( \frac{3}{7} \right) = 1$$ by the above example/theorem. No? but I am certain that 3 is NOT a QR for 7.

A: For (1), because they have examined the cases for $p$ less than $3$, they can assume $p$ is greater than $3$.
For (2), the theorem assumes at the beginning that $p\equiv 1\pmod4$; this, combined with $p\equiv1\pmod3$, then gives $p\equiv1\pmod{12}$.Moreover, since $7\equiv3\pmod4$, the theorem does not apply in this case, so there is no contradiction here.
Edit:
Actually the example is only to specify a case of the quadratic reciprocity law. And in fact, as $7\equiv3\pmod4$, the law tells us that $(\frac{3}{7})=-(\frac{7}{3})=-1$.If one wonders why the above example fails, it is because that both $3$ and $7$ are $\equiv3\pmod4$, so that the result of the theorem should be reversed, thus coinciding with your result of manual chack.

A: Since $3$ and $7$ are both of the form $4k+3$, by Reciprocity we have $(3/7)=-(7/3)=-(1/3)=-1$.
As to why start past $3$,  there is a special "rule" for determining whether $(2/p)$ is $1$ or $-1$.  We have for the odd prime $p$ that $(2/p)=1$ if $p\equiv \pm 1\pmod{8}$, and $(2/p)=-1$ if $p\equiv \pm 3\pmod{8}$. This is much easier to establish than Reciprocity.


text:
Q: Getting Selected Values of Picklist RecordType Currently I am able to get all the values that are for a picklist. But I was wondering if it's possible to get just the selected values of a picklist for a RecordType using Apex? screenshot below:

Current snippet:
List<Schema.PicklistEntry> picklistValues;
Schema.DescribeFieldResult fieldResult = Account.PicklistField__c.getDescribe();
picklistValues = fieldResult.getPicklistValues();


text:
Q: Hide the field along with the row in SharePoint form I was able to hide the textbox and label form SharePoint from using the below code. But there is a row which still there after removing text which looks like a gap between textboxes how do i remove it using css

A: try to use the below script
<script src="http://code.jquery.com/jquery-1.7.2.min.js" type=text/javascript>
</script>
<script type="text/javascript">
    $(document).ready(function(){
    $('nobr:contains("field name")').closest('tr').hide();
   });
</script>


text:
Q: Is it possible to redirect a TCP connection based on host name? What I want to be able to do is connect to a postgres server like this:
psql -h postgres-a.example.com -p 9000
That connection should be received by a proxy server (like nginx or haproxy) and it will be redirected to database A because of host name postgres-a.example.com. If I use postgres-b.example.com and the same port, it should go to database B.
I have been researching this, but I am still not 100% sure of how this would work. I read that the only way to redirect a TCP connection (psql) based on host name is using the SNI header. But I still don't understand if we will need a SSL certificate for this, or if we will need to use https://postgres-a.example.com (That doesn't make any sense to me). How it will work?
Can someone help me understand this?

A: Yes. You will need a certificate for TLS/SSL and you can route the requests based on req.ssl_sni to the proper backend.
I'm not sure if psql uses SNI but i think this have you check.
frontend public_ssl

  bind :::9000 v4v6 crt /usr/local/etc/haproxy-certs

  option tcplog

  tcp-request inspect-delay 5s
  tcp-request content accept if { req.ssl_hello_type 1 }

  use-server postgres-a if { req.ssl_sni -i postgres-a.example.com }
  use-server postgres-b if { req.ssl_sni -i postgres-b.example.com }

backend postgres-a
    server postgres-a FURTHER SERVER PARAMS

backend postgres-b
    server postgres-b FURTHER SERVER PARAMS

I have created a blog post with a picture for a more detailed description.
https://www.me2digital.com/blog/2019/05/haproxy-sni-routing/


text:
Q: Data structure to track and store objects when hooking into APIs I am solving a very specific problem which requires using data structures to store and track objects. Using a simple example, say I have the following 2 classes:
class Foo
{
    Foo Foo(bool isRed) {m_bRed = isRed} ;
    bool m_bRed;
}

class Bar
{
    Bar Bar(Foo* pFoo) {m_pFoo = pFoo} ;
    Foo * m_pFoo;
}

As the program runs, many Foos and Bars will be created, and at program termination, I'd like to know how many Bars are red (from it's contained Foo). Please assume there's no getters/setters for both classes, and the only way to solve this problem is to hook into Foo's and Bar's constructors. Now, what's the best data structure to do this?
I think a potential solution is to use two (unordered) maps of the following formats:
std::map<Foo*, bool> g_FooContainers;
std::map<Bar*, bool> g_BarContainers;

And when Foo is being created, we insert it into its map,
g_FooContainers.insert(std::make_pair(Foo*, isRed));

And when Bar is being created, we look for the passed-in Foo* in its map, and if found, insert the Bar into its map with the corresponding isRed.
r = g_FooContainers.find(Foo*);
if (r != unordered_map::end)
{
    g_BarContainers.insert(std::make_pair(Bar*, r->second)));
}

And at the end of the program execution, we can loop through g_BooContainers and see which Bar is red or not.
Now, I am wondering if there's an more efficient way to do this? Perhaps with only one std::map?
Please let me know.

A: I am going to suggest:

*

*Keep a set of Bar*.

*Add the Bar* to the set in the constructor.

*Remove the Bar* from the set in the destructor.

*At the end, go through the set of Bar* and gather the set of Foo* from them. I am assuming Foos are not deleted without deleting the Bars that have a pointer to it. This makes sure that if there are multiple Bars pointing to the same Foo, you wouldn't count it more than once.

*Iterate over the set of Foo* and count how many are red.

Sample Code
std::set<Bar*> g_aliveBars;

class Bar
{
   Bar(Foo* pFoo) {m_pFoo = pFoo; g_aliveBars.insert(this);}
   ~Bar() {g_aliveBars.erase(this);}

   Foo * m_pFoo;
}

int getRedFoos()
{
   std::set<Foo*> aliveFoos;
   for ( auto bar: g_aliveBars )
   {
      aliveFoos.insert(bar->m_pFoo);
   }
   int count = 0;
   for ( auto foo; aliveFoos)
   {
      count += (foo->m_bRed? 1 : 0);
   }
   return count;
}

Without getters and setters in classes, I hope you can provide a mechanism to get the Foo* from a Bar. You can accomplish that by keeping a map of Boo* -> Foo*. Similarly, you can provide a mechanism to answer whether a Foo is red or not. In essence, you would need:
std::map<Foo*, bool> g_FooIsRedMap;
std::map<Bar*, Foo*> g_BarToFooMap;

Given that, getRedFoos() can be translated to:
int getRedFoos()
{
   std::set<Foo*> aliveFoos;
   for ( auto bar: g_aliveBars )
   {
      aliveFoos.insert(getFoo(bar));
   }
   int count = 0;
   for ( auto foo; aliveFoos)
   {
      count += (isRed(foo)? 1 : 0);
   }
   return count;
}


text:
Q: Average daily max/min temperature if within date/time range in Excel I have the following array formula which calculates the average daily temperature for a season (outlined in more detail here: Average day and night temperature in excel).
=AVERAGE(IF(Sheet1!$C$7:$C$17622>=$A$20,IF(Sheet1!$C$7:$C$17622<$A$21,IF(Sheet1!$B$7:$B$17622>=$B18,IF(Sheet1!$B$7:$B$17622<$B19,OFFSET(Sheet1!A$7:A$17622,0,(COLUMN(Sheet1!A$7)*3)))))))

The OFFSET function is to account for alternating columns of temperature and humidity for each site (site temperature/humidity are in columns in Sheet1; there are four columns for each site, hence the *3).
I can get the absolute maximum for each season by replacing AVERAGE with MAX.
However, I would like to obtain the average maximum/minimum daily and nightly temperatures for each season, but I cannot figure out how to do it (after several hours). I'd appreciate it if anyone could help me out here.
Sample data here:
https://www.dropbox.com/s/9brbxjbcrhjwrhc/Climate%20by%20season.xlsx?dl=0

A: Just add 1 extra column to 'collect' you daily maximum temperature and 1 more column for daily minimum temperature. Then use the same AVERAGE or AVERAGEIFS formula to work on each of these column to obtain your intended results.
Hope that helps.  ( :