text:
Q: Are async useEffect Callbacks Actually Harmful, or Just a "Smell"? I can find lots of articles on the web that will tell you to change:
 useEffect(async() => {
   await doSomethingAsynchronous();
 })

into:
 useEffect(() => {
   const pointlessFunction = async () => {
       await doSomethingAsynchronous();
   };
   pointlessFunction();
 })

But what I can't find is any explanation of the actual harm caused by the former.
I understand that React's ESLint rules will complain if you do the former, and I understand that it's complaining because the former might confusingly suggest that useEffect is waiting for the AJAX to complete (when it's not).
In both cases the async function is generating a promise, and in both cases that promise is being ignored (meaning that neither version is actually waiting for doSomethingAsynchronous to complete).
But ... if you understand the above, and can still write working code in spite of it ... is there any actual harm to doing the former?
EDIT:
It seems from the answers so far there is some "harm", but it's only in the form of limiting options.  If I go with form #2, I can't:

*

*return a cleanup function (because the async will make the function always return a promise)

*wrap the callback with a try/catch
So maybe that's the only harm: form #1 can't error handle or do cleanup.  But I'm still curious: aside from limiting my options, if I don't need to cleanup or handle errors, will form #1 actually break anything (ie. cause harm)?
After all, using a one-line arrow function (() => 5) limits your options too ... but we still use them all the time, and just use the more verbose form when we need it.  Why not do the same here?

A: There are a couple of issues.

*

*React expects two possible return values from the callback: nothing (in which case there is no cleanup function to run), or a function (in which case that function is the cleanup function that will be run). If you return something other than those two return values, you're doing something that React doesn't know how to handle - which means that the logic you're implementing may well be buggy - the script-writer is returning a value of an unexpected type, and may be expecting React to do something with it - but it won't.
It's a bit like doing
someArray.forEach((item) => {
  // do something
  return true;
});

Because forEach ignores the value returned from the callback, any time you see code like this, it's probably a bug (or useless). If some library-writer nowadays decided to implement forEach themselves they might decide to be strict and show a warning when it sees a value returned from the callback.
React is doing something similar. Using an async function (or returning a non-undefined, non-function value) isn't inherently absolutely forbidden and so doesn't produce an error, but it does indicate that there's something wrong, so it produces a warning.

*Async functions that reject will result in unhandled rejections, which should absolutely be avoided for the same reason that plain runtime errors should be avoided. If you had
useEffect(async() => {
await doSomethingAsynchronous();
})

and doSomethingAsynchronous rejected, you would end up with an unhandled rejection - because React does not do anything with the returned Promise, and you should implement the error handling yourself.

A: While the other answers here are great and informative, none directly answered my original question, ie. "Is there any harm to providing useEffect with an async callback?
The answer is ... no, there is no harm.
However, there is an important limitation to that approach, which is that you cannot provide a cleanup function if you use it (because async functions can never return functions, only promises).  Also, some devs may be concerned  that future versions of React may break when an async callback is given to useEffect.
Both concerns can easily be addressed with a wrapper around useEffect, called something like useAsyncEffect.  This allows you to avoid ES Lint issues (and ensure compatibility with future React versions), while still providing a cleanup function.
export const useAsyncEffect = (effect, dependencies, cleanup) => {
  // If no dependencies are provided but a cleanup function is, fix args
  if (!cleanup && typeof dependencies === 'function') {
    cleanup = dependencies;
    dependencies = undefined;
  }

  // Main wrapper code
  useEffect(() => {
    effect();
    return cleanup;
  }, dependencies);
};

A: I think that it is a bad practice to use async functions in use effects because:

*

*The useEffect function expects to receive a function that returns another function to execute once your component is unmounted, rather than a promise.

*As far as I know, non-handled async functions may cause some issues with states when your component is re-rendered, but your async function is not completed yet.


text:
Q: Difference in a C++ pointer behavior when incremented in the for loop definition vs inside for loop I'm onto a leetcode problem (Floyd's Cycle Detection Algorithm for Linked List) wherein I noticed a strange behavior on the pointer states.
When I change the pointer state inside the for loop, the program executes correctly (pointer states move to the right states):
ListNode *detectCycle(ListNode *head) {

        if(!head or !head->next)
            return nullptr;

        ListNode *slow, *fast;

        for(slow = head, fast = head; fast && fast->next;)
        {
            slow = slow->next, fast = fast->next->next; // This hops the pointers correctly

            if(slow == fast)
            {
                slow = head;
                while(slow != fast)
                {
                    slow = slow->next;
                    fast = fast->next;
                }
                return slow;
            }
        }
        return nullptr;
    }

But when I state change slow & fast in the for loop definition, the state change is wrong and the program doesnt give the right output.
ListNode *detectCycle(ListNode *head) {

        if(!head or !head->next)
            return nullptr;

        ListNode* slow, *fast;

        for(slow = head, fast = head; fast && fast->next; slow = slow->next, fast=fast->next->next) // Pointers dont hop correctly
        {
            if(slow == fast)
            {
                slow = head;
                while(slow != fast)
                {
                    slow = slow->next;
                    fast = fast->next;
                }
                return slow;
            }
        }
        return nullptr;
    }

I dont know whats causing this. In my head, incrementing the pointers in the for loop definition vs immediately in the for loop should be the same thing. Can someone throw an insight as to why incrementing pointers within the loop vs in the for loop signature leads to different behavior?

A: A
for (init-statement; condition; iteration-expression)
{
    dostuff();
}

maps to
{
    init-statement
    while ( condition )
    {
        dostuff();
        iteration-expression ;
    }
}

so we get
{
    slow = head, fast = head;
    while (fast && fast->next)
    {
        slow = slow->next, fast = fast->next->next;
        dostuff(); // for example purposes only. Not really replacible with a function
    }
}

and
{
    slow = head, fast = head;
    while (fast && fast->next)
    {
        dostuff();
        slow = slow->next, fast=fast->next->next;
     }
}

In the first, slow and fast are always updated before dostuff().
In the second, dostuff happens before slow and fast are updated, so the values of slow and fast used in dostuff will be different on the first loop iteration.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Column with lists values to rows I have a data frame with 131 millions rows.
The data.frame has 2 columns. Column 1 is a number. Column 2 is a list of values
Something like this
Col1 | Col2
1    | a, b, c
2    | d, e, f
3    | a, e, f

And I need to put it like this:
Col1 | Col2
1    | a
1    | b
1    | c
2    | d
2    | e
2    | f
3    | a
3    | e
3    | f

It must be quick because of the 131 millions rows.

A: By using unnest if Col2 is string
library(tidyr)
library(dplyr)
dt %>%
    mutate(Col2 = strsplit(Col2,",")) %>%
    unnest(Col2)
# A tibble: 9 x 2
   Col1  Col2
  <dbl> <chr>
1     1     a
2     1     b
3     1     c
4     2     d
5     2     e
6     2     f
7     3     a
8     3     e
9     3     f

Data Input :
dt=data_frame(Col1 = c(1,2,3),Col2 = c('a, b, c','d, e, f','a, e, f'))

As you mention it is list of value , so you just need to
dt %>% unnest(Col2)
# A tibble: 9 x 2
   Col1  Col2
  <dbl> <chr>
1     1     a
2     1     b
3     1     c
4     2     d
5     2     e
6     2     f
7     3     a
8     3     e
9     3     f

Data Input
dt
# A tibble: 3 x 2
   Col1      Col2
  <dbl>    <list>
1     1 <chr [3]>
2     2 <chr [3]>
3     3 <chr [3]>


text:
Q: Can I get / How can I get the full user profile and roles from OpenAM after authentication? My project authentication use OpenAM with Spring Security and SAML extension.
It's work fine.
I implemented the SAMLUserDetailsService interface, get back the uid (user id) from OpenAM (nameid-format:unspecified).
It's ok too, but I need the user information (email, phone...) and roles from OpenAM. How can I do this from here ?

A: You can add more claims to the SAML assertion (the docs describe how to do this). Use something like Firefox SAML tracer to view the SAML assertions.
You could also query the users profile directly from OpenDJ using their uid.


text:
Q: Showing $f+g$ is measurable when $f$ and $g$ are measurable As part of a proof that $f + g$ is measurable I have that
$f(x) + g(x) > \lambda$
$\Longleftrightarrow$
$f(x) > \lambda - g(x)$
$\Longleftrightarrow$
$\exists r \in \mathbb{Q}$
such that $f(x) > r$ and $\lambda - g(x) < r$
$\Longleftrightarrow$ $f(x) > r$ and $g(x) > \lambda - r$
i.e. $x \in \{f > r\} \cap \{g > \lambda - r\}$ for some $r \in \mathbb{Q}$
Let $\{r_1, r_2, ...\}$ be an enumeration of $\mathbb{Q}$
Then,
$\{f + g > \lambda\} = \bigcup_{n =1}^{\infty} \{f > r_n\} \cap \{g > \lambda - r_n\}$
So we have a countable union of measurable sets which means $f + g$ is measurable.
Question
What I don't understand is why we have to take an enumeration of $\mathbb{Q}$?
Why isn't this statement on it's own, that uses some $r \in \mathbb{Q}$, enough to say that $f + g$ is measurable?
$$x \in \{f > r\} \cap \{g > \lambda - r\}$$ for some $$r \in \mathbb{Q}$$

A: I prefer to look at it this way:
Let $\Delta = \{(a,b)| a+b < \lambda \}$. Let $q_n \in \mathbb{Q}$ be an enumeration of the rationals.
Let $\Delta_{n} = \{ a | a < q_n \} \times \{ b | b < \lambda - q_n \}$. It is clear that $\Delta_{n} \subset \Delta$, and so $\cup_{n} \Delta_{n} \subset \Delta$.
Now suppose $(a,b) \in \Delta$. Then $a+b < \lambda$. Now choose $a_n \in \mathbb{Q}$ such that $a_n \downarrow a$. Since $b < \lambda -a$, it should be clear that for $n$ sufficiently large that $b < \lambda -a_n$. Since $q_n$ is an enumeration of the rationals, we must have $a_n = q_k$ for some $k$, and so $(a,b) \in \Delta_{k}$. And so we have $\cup_{n} \Delta_{n} = \Delta$.
The utility of this expression is that $(f(x),g(x)) \in  \Delta$ iff for some $n$, we have $(f(x),g(x)) \in  \Delta_{n}$, and we have $(f(x),g(x)) \in  \Delta_{n}$ iff $x \in \{ y | f(y) < q_n \} \cap \{ y | g(y) < \lambda - q_n \}$, both of which are measurable.
That is,
\begin{eqnarray}
\{x | f(x)+g(x) < \lambda\} &=& \{ x | (f(x),g(x)) \in  \Delta \} \\
&=& \cup_{n} \{ x | (f(x),g(x)) \in  \Delta_{n} \} \\
&=& \cup_{n} \left( \{ y | f(y) < q_n \} \cap \{ y | g(y) < \lambda - q_n \} \right)
\end{eqnarray}
Note: To illustrate why we must take the union of all the $\Delta_n$, take $f(x)=x, g(x) = 1-x$. Note that $\Delta = \begin{cases} \mathbb{R}, & 1 < \lambda \\ \emptyset, & \lambda \le 1 \end{cases}$. Then $\Delta_n = (-\infty,q_n) \cap (1-\lambda+q_n,\infty)$. If $\lambda >1$, then $\Delta_n = (1-\lambda+q_n, q_n)$. Hence it is insufficient to just show measurablility of $\Delta_n$.

A: Well, first of all, $\mathbb{Q}$ is used because it is a countable dense set in R. That is, you'll always find a rational in any open interval. In fact, every time you need a set in R with these features, you must think of $\mathbb{Q}$.
So the idea is to show that the set { $x / f(x)+g(x) < \lambda$ } is countable junction expressed as measurable sets. That is why making an enumeration of the rational numbers.
In fact, if you try to prove the equality of these two sets, you'll not simply one rational as you think, it is necessary for all rational.
Hope that helps to dispel your doubt, but so, ask your teacher to understand better.
Good Luck!


text:
Q: Running code only once in a lifecycle react native stateless component I am trying to run my code only once in life cycle. right now i have put my code in useEffects and put a condition on to it but i want to ask is there any way we can write code that runs only once in a lifecycle of component

A: use [] to run one time
useEffect(()=>{
    // Your code
},[])


text:
Q: @Transactional method called from @Async method in spring class A {
     @Autowired
     B b;
     @Async
     public void updateDBAsync(){
         b.updateDBTransactional();
     }
}

class B {
     @Transactional
     public void updateDBTransactional() {
         // Updating DB from here
     }
}

Now Issue is - trying to call a.updateDBAsync() from two different machine at same time. In DB data is getting corrupted. Do anyone has any idea why this is happening and any solution?


text:
Q: Optional regular expression match I have an string like 1566-02, where -02 is optional. If I use a regular expression like this
1566\s*-\s*\d{2}

it will always expect 2 numeric number with hyphen after 1566.
How I can make the -02 part optional, so that the IsMatch should be true for 1566 also?
For example -
The value of IsMatch should be true if we pass the string as 1566 or 1566-02 or 1566-45
IsMatch value should be false for 1566-AC or 1566-

A: Simply wrap it in a group and make it optional with the zero-or-one quantifier (?):
1566(\s*-\s*\d{2})?

To prohibit any other characters before or after the matched string, use start (^) and end ($) anchors:
^1566(\s*-\s*\d{2})?$


text:
Q: Titanium Android webView evalJS does not deal well with typeof I've got a webview in my Titanium app that returns an empty string when I ask it to check for the typeof a variable. The point of this exercise is figuring out if a function exists on a page that reloads itself in different forms.
var hasAuth = self.registerView.evalJS("typeof authenticate;")

This works fine in iOS, and in fact in Android it works on many occasions as well. Yet on Android, it will sometimes return nothingness, represented as 'undefined.'
PS: No, the problem is not about including 'return' in the javascript string. Titanium does that for you and it will causes errors if you do it too.

A: The solution in this case turns out to be:
var hasAuth = self.registerView.evalJS("'' + typeof authenticate;")

Somehow evalJS can get the typeof to work, but not if the line starts with typeof.

A: The problem with Titanium's webView load event is that it often fires too early. At least on Android. When it fires too early, there is not yet a 'authenticate' function whose type can be returned.
So the problem is not with evalJS, it's with the timing of the load event.


text:
Q: Receive real referrer IP but not client IP in PHP Lets assume that we have some intermediate site page with iframe, some remote user visit this site and loads my page in this iframe. Can I somehow detect IP address of that intermediate site, but not IP of the user machine in PHP?
So I want to detect referrer IP but not client IP.
Thanks!

A: If the browser sends a referer header then you can use that to capture the URL of the page containing the iframe element, extract the hostname from it, and then perform a DNS lookup on that hostname.
There are many situations where the browser won't send the referer header though, and in those cases you will be out of luck.


text:
Q: Condition for redirecting to different page? I wrote a servlet whose purpose is to login into the application only if the query executes...now what is the condition to be used for invalid username and id...I'm unable to write the condition..pls help me out...the servlet is...
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        try{
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl ","scott","tiger");
            System.out.println("cnnection est");
        int Id = Integer.parseInt(request.getParameter("id"));
        String Name=request.getParameter("firstname");
        boolean b=true;

        //Connection con =JdbcConnectionUtil.getConnection();

        PreparedStatement pst = con.prepareStatement("select * from login where id=? and firstname=?");
        pst.setInt(1, Id);
        pst.setString(2, Name);

        ResultSet rs = pst.executeQuery();
        if(rs!=null && rs.next())
        {

        //while(rs.next()){
            PrintWriter pw = response.getWriter();
            System.out.println("here");
            pw.println("hello");
            pw.println(rs.getInt(1));
            pw.println(rs.getString(2));
            pw.println(rs.getString(3));

        }
        //}
        else
        {
            RequestDispatcher rd = request.getRequestDispatcher("/LoginFailed.html");

        }
//

        }
        catch(Exception ex){

            ex.printStackTrace();

        }
    }

A: Using rd.forward will solve the problem I think.
How to forward requests from Servlet to JSP

A: First you check for the correct parameters and then you do the logic. Also do not forget to close statements and connections to avoid memory leaks.
Here is refactored code:
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //get parameters from request
    try {
        String idParam = request.getParameter("id");
        String name = request.getParameter("firstname");

        //check if request contains such parameters
        if (idParam == null || name == null) {
            throw new IllegalArgumentException(
                    "Id and Name parameters must not be null.");
        }

        //try casting idParam to int
        Integer id = null;
        try {
            id = Integer.parseInt(idParam);
        } catch (NumberFormatException nfe) {
            throw nfe;
        }

        PreparedStatement pst = null;
        Connection con = null;
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            con = DriverManager.getConnection(
                    "jdbc:oracle:thin:@localhost:1521:orcl ", "scott", "tiger");

            pst = con.prepareStatement(
                    "select * from login where id=? and firstname=?");
            pst.setInt(1, id);
            pst.setString(2, name);

            //check if result returned any data
            ResultSet rs = pst.executeQuery();
            if (!rs.next()) {
                throw new Exception(
                        "No such user for id: " + id + " and name: " + name);
            }

            PrintWriter pw = response.getWriter();
            pw.println("hello");
            pw.println(rs.getInt(1));
            pw.println(rs.getString(2));
            pw.println(rs.getString(3));

        } catch (Exception ex) {
            throw ex;
        } finally {
            try {
                if (pst != null) {
                    pst.close();
                }
                if (con != null) {
                    con.close();
                }
            } catch (SQLException sqle) {
                throw sqle;
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        RequestDispatcher rd = request.getRequestDispatcher("/LoginFailed.html");
        rd.forward(request, response);
    }
}

Something like that would be appropriate I think.


text:
Q: Facebook Prophet API documenation I'm looking for a API Python documentation for Facebook Prophet
Here there are good examples https://facebook.github.io/prophet/docs
future = m.make_future_dataframe(periods=365)

or
future = m.make_future_dataframe(periods=300, freq='H')

But it doesn't explain all possible parameters in make_future_dataframe, or the valid values for freq.
Any idea where to find the API documentation?

A: Here is where it is defined
https://github.com/facebook/prophet/blob/f123a1a7cc6ab51bd21f01e41738d97910a2b2b7/python/fbprophet/forecaster.py#L1548
    def make_future_dataframe(self, periods, freq='D', include_history=True):

A: The arguments and API usages are documented as per "October 14, 2022" in this link:
https://cran.r-project.org/web/packages/prophet/prophet.pdf


text:
Q: How can I get a vector type in C#? I want to use Vectors in a C# application I'm writing, sepcifically a Vector3.
What's the best way for me to get a Vector type without writing my own?

A: Well, there's a struct called Microsoft.DirectX.Vector3 if that's what you're looking for. You need to reference Microsoft.DirectX.dll to use it.

A: For completeness, there is also one in XNA: Microsoft.XNA.Framework.Vector3.
Sounds like something in dire need of consolidation.

A: In WPF you have:
System.Windows.Media.Media3D.Vector3D

A: You should be able to use the vector classes in SlimDX:  http://code.google.com/p/slimdx/
You could also pull out the vector/math classes from an open source XNA port like XNATouch: http://xnatouch.codeplex.com/

A: I used one in a POC that I found on CodeProject. It's not ideal, but it worked for our situation. At the time, however, it did not have a method to reflect a Vector3 about a given normal, but that may have changed since then.
If you don't mind using DirectX (some stay away from it for whatever reason), then there is a Vector3 type in that library as well.


text:
Q: Determine if a microsoft account is logged in on the current browser usingn javascript So I have a website that has a SSO log in method. If the user click the sign in, it will automatically log in the user using the microsoft account the is logged in on the browser.
But I added a functionality to have an internal log in, so currently there are two ways of sign in, first, is the SSO, second is using the credentials created by the website.
What I want to achieve is to detect if there is a microsoft account that is currently logged in in the browser so the SSO login method will automatically triggered.
E.g
If("There is a microsoft logged in on the current browser"){
sso function will trigger
}else{
window.location.href="www.domain.com/signin"
}


text:
Q: How to make multiple reaction roles So I'm working on a reaction role cog, and the commands work so far. There's just one problem. When I create two different reaction roles, it only works for the second one. It's because I only have one dictionary and it updates that every time. I think I've seen people use a payload for reaction roles, but I have no idea what that does and if it would fix my problem. Is there a way to use payload to fix my problem? Thanks!! Here's my code:
import discord
from discord.ext import commands
from discord.ext.commands import BucketType, cooldown, CommandOnCooldown
import random
import json

reaction_title = ""
reactions = {}
reaction_message_id = ""

class ReactionRoles(commands.Cog):
    """Reaction roles!!\nYou need manage roles permissions to use these"""

    def __init__(self, bot):
        self.bot = bot

    # Bot Commands

    @commands.command(aliases=['rcp'])
    async def reaction_create_post(self, ctx):
        """Creates an embed that shows all the reaction roles commands"""

        embed = discord.Embed(title="Create Reaction Post", color=discord.Colour.dark_purple())
        embed.set_author(name="Botpuns")
        embed.add_field(name="Set Title", value=".rst [New Title]", inline=False)
        embed.add_field(name="Add Role", value=".rar [@Role] [EMOJI]", inline=False)
        embed.add_field(name="Remove Role", value=".rrr [@Role]", inline=False)
        embed.add_field(name="Reaction Send Post", value=".rsp", inline=False)

        await ctx.send(embed=embed)
        await ctx.message.delete()

    @commands.command(aliases=['rst'])
    async def reaction_set_title(self, ctx, *, new_title):

        global reaction_title
        reaction_title = new_title

        await ctx.send(f"The title for the message is now `{new_title}`")
        await ctx.message.delete()

    @commands.command(aliases=['rar'])
    async def reaction_add_role(self, ctx, role: discord.Role, reaction):

        global reactions

        reactions[role.name] = reaction
        await ctx.send(f"Role `{role.name}` has been added with the emoji {reaction}")
        await ctx.message.delete()

        print(reactions)

    @commands.command(aliases=['rrr'])
    async def reaction_remove_role(self, ctx, role: discord.Role):

        if role.name in reactions:
            del reactions[role.name]
            await ctx.send(f"Role `{role.name}` has been deleted")
            await ctx.message.delete()

        else:
            await ctx.send("That role wasn't even added smh")

        print(reactions)

    @commands.command(aliases=['rsp'])
    async def reaction_send_post(self, ctx):

        description = "React to add roles\n"

        for role in reactions:
            description += f"`{role}` - {reactions[role]}\n"

        embed = discord.Embed(title=reaction_title, description=description, color=discord.Colour.purple())
        embed.set_author(name="Botpuns")

        message = await ctx.send(embed=embed)

        global reaction_message_id

        reaction_message_id = str(message.id)

        for role in reactions:
            await message.add_reaction(reactions[role])

        await ctx.message.delete()

    @commands.Cog.listener()
    async def on_reaction_add(self, reaction, user):

        if not user.bot:

            message = reaction.message

            if str(message.id) == reaction_message_id:

                # Add roles to user
                role_to_give = ""

                for role in reactions:

                    if reactions[role] == reaction.emoji:
                        role_to_give = role

                role_for_reaction = discord.utils.get(user.guild.roles, name=role_to_give)
                await user.add_roles(role_for_reaction)

    @commands.Cog.listener()
    async def on_reaction_remove(self, reaction, user):

        if not user.bot:

            message = reaction.message

            if str(message.id) == reaction_message_id:

                # Add roles to user
                role_to_remove = ""

                for role in reactions:

                    if reactions[role] == reaction.emoji:
                        role_to_remove = role

                role_for_reaction = discord.utils.get(user.guild.roles, name=role_to_remove)
                await user.remove_roles(role_for_reaction)

def setup(bot):
    bot.add_cog(ReactionRoles(bot))


text:
Q: Python while loop not ending when condition is met I'm assuming the issue has to be with setting a global variable but even with my trying to fix it with that, I still can't seem to figure it out. Code is pretty rough but I only started learning <2 days ago so please bear with me. From my understanding, if the password is entered correctly, the game variable should be equal to False which should end the loop. However, it keeps going on and asking player 1 for input. Also, I can't seem to be getting the checkGame function to work properly inside the while loop.
board = [
0,1,2,
3,4,5,
6,7,8
]
print(board)

global counter
counter = 0

global game
game = True

def checkGame():
    if board[0] == player_1:
        print("Game won by player 1!")
        game == False

def player_1():
    player_1 = 'X'
    # return player_1
    selection = int(input("P1: Pick a position: "))
    board[selection] = player_1
    print(board)
    global game
    global counter
    counter += 1
    print("Counter = ", counter)
    print("game:", game)

def player_2():
    player_2 = "O"
    selection = int(input("P2: Pick a position: "))
    board[selection] = player_2
    print(board)
    global counter
    counter += 1
    print("Counter = ", counter)
    print("game:", game)

while game == True:

    password = input("password: ")
    if password == 'testing':
        game = False
        print(game)
    else:
        pass

    if counter == 9:
        game = False

    player_1()

    if board[0] == player_1:
        print("Game won by player 1!")
        game == False

    if counter == 9:
        game == False

    checkGame()
    player_2()

    if counter == 9:
        game == False

    checkGame()

A: A while loop's condition is not checked continuously, only at the start of each loop iteration. To exit the loop immediately use a break statement. For example, in this code it will print "Keep running" even after you type "exit"
running = True
while running:
    password = input("password: ")
    if password == "exit":
        running = False # does not exit the loop, just stops the next run

    print("Keep running")

but in this code it will not
running = True
while running:
    password = input("password: ")
    if password == "exit":
        break # exits the loop

    print("Keep running")

Also, unrelated to your immediate issue of not exiting on the password entry, var == False does not set var to false, it just checks if it is equal to false. Be sure to use = for assignment, not ==.
You also seem to be mixing method names and variable names (e.g. player_1) which is probably going to cause problems...


text:
Q: existence of a finite free resolution Problem 2.1.26 in Bruns and Herzog, CMR, reads as follows: "Let $R$ be a Cohen-Macaulay local ring of dimension $d$ and $M$ a finite $R$-module. Deduce that the $d$-th syzygy of $M$ in an arbitrary finite free resolution is either $0$ or a maximal Cohen-Macaulay module."

Question: Are the hypotheses of the problem enough to guarantee that $M$ has a finite free resolution?

Remark: As a reminder, see also this related question what classes of modules admit finite free resolutions?

A: No, it is not enough. Take $M = R/\mathfrak m$, where $\mathfrak m$ is the maximal ideal. If $M$ has a finite free resolution, then $R$ is regular, and there are CM local rings which are not regular. For instance, take $R =\mathbb Z/(4)$ and $M =\mathbb Z/(2)$.
Problem 2.1.26 asks a property of a syzygy module which in general is not free.


text:
Q: Windows Server 2008 With VPN Client Always On I have a Windows Server 2008 Ent VPS that I have setup to connect to my hone VPN server. I'm able to get connected to the VPN but it disconnects me when I logout.
Is there a way I can setup the server to keep the VPN Connection alive even when I log out from RDC?

A: Have a look at persistent demand-dial connections in Routing and Remote Access Service. That'll do what you want to do re: an always-on VPN connection.

A: I done this in way:
- create vpn connection, save password allow all users to use this connection
- download autoconnect application (http://www.instalki.pl/programy/download/Windows/sieciowe/AutoConnect.html) - Polish version and configure autoconnection of my vpn created above
- create scheduled task that this app above will start after system boot
- run this task
it works 2 days now and it is ok.


text:
Q: Vanishing zero point energy in harmonic oscillator In classical mechanics, adding a constant to the potential changes nothing. In quantum mechanics, this just shifts the energy and multiples the wavefunction with a phase term.
But now suppose I use the potential $$V(x)=(1/2)m \omega^2x^2 - (1/2)\hbar\omega$$ instead of $$V(x)=(1/2)m \omega^2x^2 $$ for the harmonic oscillator. Then the energy spectrum will be $$E_n=n\hbar\omega$$ instead of $$E_n=(n+1/2)\hbar\omega.$$ This would mean that the harmonic oscillator can have a vanishing ground state energy depending on the potential that we choose. But the non-vanishing ground state energy of the harmonic oscillator is the source of the zero point energy of vacuum. So does that mean adding a constant to potential changes the system in quantum mechanics?

A: The right way to interpret energy in the quantum vacuum is not known. Especially, its gravitational influence is not known.
If we say that the energy $(1/2)\hbar \omega$ is in fact present in the vacuum for every field mode, then we get an enormous energy density, and this leads to predictions about cosmic expansion which are way off from the observations. Such a model predicts an expansion accelerating at rates many orders of magnitude higher than is observed. On the other hand the Casimir effect can be calculated correctly by taking the zero point energy as $(1/2)\hbar \omega$ for each mode. So there is a real puzzle here and no-one knows the answer.


text:
Q: Using Ajax.ActionLink, how can I display a custom modal confirmation? I have a requirement to show a custom modal jQuery confirmation when a user clicks on an Ajax ActionLink. However, when I try to add this onto the Ajax link, the ajax call continues and doesn't allow the confirmation to stop the call. I've tried using OnBegin function, but when I call preventDefault it throws a method not supported error. If I return false it doesn't allow any way to continue the call. Does anybody know how to achieve this?
Here is the link I'm trying to add the confirmation to:

@Model.Email | @Ajax.ActionLink("Sign Out", "SignOut", new { area = "", controller = "Account" }, new AjaxOptions { HttpMethod = "POST" })

And here is the code that I'm trying to execute:
    $('#MainNav ul li a, .header-top a').click(function (e) {
        e.preventDefault();
        var link = $(this).attr('href');
        $('.confirm-dialog .confirm-this').attr('href', link);

        $('.confirm-dialog').dialog({
            modal: true,
            draggable: false,
            overlay: { opacity: 0.8 },
            resizable: false,
            width: 400,
            open: function () {
                $('.close-dialog').click(function (e) { e.preventDefault(); $(this).parents('.ui-dialog').remove(); });
                $('.confirm-this').click(function () { });
            }
        });
    });

Any help would be greatly appreciated. I've already done a lot of searching and trying to figure this out but am left with the same basic problem. How do I stop the Ajax call until the User clicks on Confirm?

A: Don't rely too much on the predefined ActionLink way. There are two ways to archive this:

*

*The Microsoft unobstrucive Ajax methods will be added automatically to the link - you have to remove them with jquery and do the ajax call by your own. But you have to remove the handler with jquery after they have been added - thats maybe strange and I don't know when to do that exactly.

*Don't use the @Ajax.ActionLink in your case - just use build your own a tag with @Url.Action and set your onclick handler to your a tag. But you have to do the ajax call on your own as well.
In both cases to build your own ajax call just change your confirm:
$('.confirm-this').click(function () { $.post(link) });


text:
Q: Can iptables REDIRECT back into a docker container Let's say I have a docker container on a docker network with ip 172.20.0.2.
Inside that docker container there are two processes running.

*

*An http server listening on port 8000 that always replies 'hello'

*A http client that constantly tries to connect to http://example.com
Is it possible, using ip tables on the host machine, to forward all outbound traffic in that container back into the same container.
So in the scenario above, the http request to example.com, would actually goto the 8000 port inside that same container, returning 'hello'.
I feel like the following would work if this wasn't in docker. Am I close?
iptables -t nat -A OUTPUT -s 172.20.0.0/16 -j REDIRECT --to-ports 8000

But I think this is just forwarding to 8000 on the host machine :(

A: I would suggest editing the /etc/hosts file on the docker container:
172.20.0.2  example.com

This means that everytime the client attempts to connect to http://example.com:8000 via HTTP, traffic will be pointed to docker container at 172.20.0.2:8000, and receive a "hello" reply as expected.


text:
Q: Bash treat star character as word in associative array I'm trying to do a word count in a file and use every word in the file as key in an associative array. The value should be the occurences of the word.
while read line; do
  ((occs["$line"]=${occs[$line]}+1))
done < $predfile

Now the problem is that there can be a * (star) in the file and I want to treat this star as a word. However when I want to output the occurences of the words with
for i in "${!occs[@]}"
do
  echo "$i : ${occs[$i]}" >> $resultfile
done

then bash trys to output ${occs[*]} when it reaches the star and I get "occs[*]: bad array subscript". I could use an if statement to handle this but I want to know if I can fill the array keys with escaped keys.

A: Your error occurs when you try to assign the array element, not when you use it. * and @ have special meaning as an array subscript, and apparently bash will not let you use those values as a regular array subscript. You have to handle * and @ specially.
Arrays subscripts must be integers.If you want to store arbitrary words as the array key, you need to declare your variable as an associative array.
declare -A occs
while read line; do
    [[ $line = "*" ]] && line=star
    [[ $line = "@" ]] && line=asterisk
    ((occs["$line"]++))
done < <(printf "%s\n" a b c \* \* c b a \* 1 2 3 \@)

for key in "${!occs[@]}"; do
    printf "%s\t%d\n" "$key" "${occs[$key]}"
done | column -t

star      3
a         2
b         2
c         2
asterisk  1
1         1
2         1
3         1


text:
Q: How to get form submit object keys and iterate over them in google apps script? I have a form that looks like this:
<form id="myForm" onsubmit="handleFormSubmit(this)">
      Identity
      <select class="input-combobox" id="parentAttr" value="Identity" name="Identity">
         <? var dropdownOptions = getDropdownOptions(); ?>
          <option name="Identity" value="placeholder"></option>
          <?
            for(i=0; i<dropdownOptions.length;i++){
          ?>
          <option value= "<?= dropdownOptions[i] ?> "> <?= dropdownOptions[i] ?> </option>
          <? } ?>
      </select>
      <input name="myFile" type="file" />
      <input type="submit" value="Submit" />
    </form>

and in Code.gs
function processForm(formObject) {
  Logger.log(formObject);    //logs {myFile=FileUpload, Identity=c } Those are the values I picked in my form.

}

After I log the formObject. I want to Log formObject.keys- im not sure what the call is as the formObject doesn't seem to be a valid javascript object. Further I would like to do something like for (var key in formObject.keys) {execute something} but Im not sure how to iterate through this formObject either.

A: Have you actually tried this and run into any errors? The for loop for iterating over object properties is
for(var key in object) {

Logger.log(key); // logs property name
Logger.log(object[key]); //logs value for the property

}

Another option to log property names
Logger.log(Object.keys(yourFormObject));


text:
Q: Convert a list of decimal values in a text file into hex format I have a need to convert a list of decimal values in a text file into hex format, so for example test.txt might contain:
131072
196608
262144
327680
393216
...

the output should be list of hex values (hex 8 digit, with leading zeroes):
00020000
00030000
00040000
...

the output is printed into the text file. How to make this with python or linux shell script?
EDIT #1
I missed one extra operation:  I need to add 80000000 hex to each of the created hex values. (arithmetic addition, to apply to already created list of hex values).

A: Three possible solutions (assuming each line is a set of only digits):
For shells like ksh, bash, zsh:
printf '%08x\n' $(<infile)

Only for bash
<file.txt mapfile -t arr;   printf '%08x\n' "${arr[@]}"

For simpler shells: dash (the default sh in Debian based systems), ash (busybox emulated shell), yash and some default shells in AIX and Solaris:
printf '%08x\n' $(cat infile)

In fact, for a shell like the heirloom version (Bourne like) it needs to be written like (which do work on all posix shells listed above but I strongly recommend to do not use it ):
$ printf '%08x\n' `cat infile`

Answer to EDIT #1
Understand that an hex value of 80000000 will cause overflow on a 32 bit computer (not common this days, but possible). Check that echo "$((0x80000000))" do not print a negative value.
$ for i in $(<infile); do printf '%08x\n' "$(($i+0x80000000))"; done
80020000
80030000
80040000
80050000
80060000

A: Using awk:
$ awk '/[0-9]/ { printf("%08x\n", $0) }' file
00020000
00030000
00040000
00050000
00060000

A: Yet another one-liner. Still not python, but which allows comments, empty lines and whatever in the file, and only prints out the result for lines which contain only a number.
perl -ne '/^(\d+)$/ && printf "%08x\n", $1'  $your_file

Given a file like this:
$ cat $your_file
# some numbers,
131072
196608

262144
327680
393216

and empty lines
and whatever...

It prints
00020000
00030000
00040000
00050000
00060000

A: You can do this using printf and bash:
printf '%08x\n' $(< test.txt)

Or using printf and bc...just...because?
printf '%08s\n' $(bc <<<"obase=16; $(< test.txt)")

In order to print the output to a text file just use the shell redirect > like:
printf '%08x\n' $(< test.txt) > output.txt

A: Here are a couple of one line solutions in PHP:
<?php
foreach (file('test.txt') as $s) echo dechex(+$s), "\n";

<?php
array_map(fn($s) => print dechex(+$s) . "\n", file('test.txt'));

A: Using julia
$ julia -e 'function hexadd(x) hex(( x + 0x80000000),8) end ; output = open("output.txt","w") ; open("test.txt") do inputfile for num in eachline(inputfile) write(output,"$(hexadd(parse(Int,num)))\n") end end'

It should be easier to read multiline:
function hexadd(x)
    hex(( x + 0x80000000),8)
end
output = open("output.txt","w")
open("test.txt") do inputfile
    for num in eachline(inputfile)
        write(output,"$(hexadd(parse(Int,num)))\n")
    end
end

*

*hex( value, pad) converts a value to hex, and adds padding as needed.
hexadd requires integer as input so we convert strings (output of eachline) to Int with parse(Int,"string") and use that in our function.

*julia -e evaluates an expression.

*julia can be installed natively in fedora,ubuntu

Using dc:
$ dc -f test.txt -e '16o16i[80000000+psaz1<r]dsrx80000000+p' > output.txt

Explanation:

*

*dc -f test.txt -e '16o 16i [80000000 + p sa z 1 <r] sr z 1 <r 80000000 + p' > output.txt

*-f file push contents of file to the stack

*-e execute expression

*16o convert output to base 16

*16i assume input in base 16. This happens after reading the file, so the file was read in base 10. More explicitly I could do dc -e '10i' -f file -e '16 i 8000000'

*[...] push a string to the stack. This string will be used as a macro.

*80000000 + add the current top of stack and hex 80000000. Push the result to top of stack.

*p Print current top of stack, without popping. Only print option that prints a newline.

*sa Pop and store top of stack in register 'a'. It never gets used, just a way to get rid of the top of sack.

*z The current top of stack now has the stack depth. Required to end the recursive call.

*1 push 1 to top of stack. Useful in comparison to stack depth (z) pushed earlier.

*<r compare 2 values from stack, if 2nd is less than 1st, execute register 'r'. In effect compare stack depth and '1'.

*sr pop and store in register 'r'. Now the macro is in register 'r', and will execute as long as stack depth greater than 1. Except nothing has called it yet.

*d Duplicate top of stack and push.

*x Execute top of stack as macro.

*d sr x Duplicate macro and push, now stack has 2 copies, pop and store top copy to register, pop and execute 2nd copy...

*So push stack depth and 1, compare and execute, and for last element, again add the hex value and print.


text:
Q: Why does synchronous use of a Promise return asynchronous results? The code
I actually thought that the new Ecmascript 6 Promise implementation was synchronous in its inner workings (with good use for simplifying asynchronous operations). I then made this example, which I perceive as synchronous code:
for (var i=0; i<5; i++) {

    foo = new Promise (function(resolve, reject) {

        console.log(i);
        resolve(i);
    });

    foo.then (function(i) {

        console.log(i);
    });
}

and to my surprise it returns:
0
1
2
3
4
0
1
2
3
4

I would have expected synchronous code to return:
0
0
1
1
2
2
3
3
4
4

Question
What is the explanation for the result returned by the above code?

A: When you call the Promise constructor, it will synchronously invoke the function you gave to it, which may or may not include a synchronous call to its resolve or reject.  Regardless of whether it has been resolved/rejected, the returned Promise has a then method which you pass another function to, and again the code within then (note, not your callback) is executed synchronously, where we arrive at step 7:

Return PerformPromiseThen(promise, onFulfilled, onRejected, resultCapability).

PerformPromiseThen has a number of steps, but both step 8b and 9b result in a call to EnqueueJob depending on whether it was resolved/rejected, where this says:

Add pending at the back of the Job Queue named by queueName.

(queueName in this instance being "PromiseJobs")
We can then follow the spec further to see how the jobs on the PromiseJobs queue are invoked, but ultimately they are not dequeued and executed while any other code is running - ie the for loop will run to completion before any then callbacks are invoked.


text:
Q: Constructing a List of Interface that requires Type Argument via Dependency Injection in C# I have a report like so:
public class Report : IReport
{
    public PageViewSection PageViews {get;set;}
}

Which has sections defined as such:
public class PageViewSection : IStateSection
{
}

Which uses data processing factories defined as such:
public class PageViewProcessor : IProcessor<PageViewSection>
{
}

And I'm attempting to use these factories in the report data repository:
public class DataRepository : IParticularReportTypeRepository
{
    private IProcessor[] _processors;

    public DataRepository(IProcessor[] processors)
    {
        _processors = processors;
    }
}

Is this possible to do, to have DI retrieve multiple instances of IProcessor without the type argument? There are going to eventually be hundreds of IProcessor instances, so writing a specific interface for each processor type seems unreasonable. I would love some architecture advice on how best to do this.
EDIT: Adding IProcessor:
public interface IProcessor<TReportSection>
{
    bool ShouldProcess(IncomingData data);
    TReportSection Process(IncomingData data, TReportSection section);
}

In the time since I've posted this I've considered architecting this such that the report sections are able to retrieve their processors.
Processors are used like so in the repo:
var reportSection = await GetReportSectionAsync(evt.EventTime, evt.ContextId);

foreach (var processor in _processors)
{
    processor.Process(evt, reportSection);
}

return await AddOrUpdateDocumentAsync(report);

A: Unless IProcessor<T> implements a non-generic version IProcessor, it is impossible to inject them all into the constructor. But even if you do so, it forces you to iterate all processors, while it only makes sense to call the versions that implement IProcessor<T> where the T is the required type.
There are several ways to solve this problem. Here are two:
1. Make DataRepository generic:
For instance:
public class DataRepository<TReportSection>
    : IParticularReportTypeRepository<TReportSection>
{
    private IProcessor<TReportSection>[] _processors;

    public DataRepository(IProcessor<TReportSection>[] processors)
    {
        _processors = processors;
    }

    public async Task<TReportSection> Process(IncomingData evt)
    {
        TReportSection reportSection = ...;

        foreach (var processor in _processors)
        {
            processor.Process(evt, reportSection);
        }

        ...
    }
}

With this approach you would inject a specific IParticularReportTypeRepository<TReportSection> (e.g. IParticularReportTypeRepository<PageViewSection> into the constructor of a consumer.
This design is only possible when each consumer has only one (or a few types of report sections) that it passes on. Otherwise, consumers get many dependencies of type IParticularReportTypeRepository<T> in their constructors.
If you need a more dynamic approach, you can start using Reflection inside the DataRepository and (optionally) call back into the used DI Container. This is demonstrated next.
2. Resolve collections from inside DataRepository:
For instance:
public class DataRepository : IParticularReportTypeRepository
{
    private readonly Container _container;

    public DataRepository(Container container)
    {
        _container = container;
    }

    public async Task<IStateSection> Process(IncomingData evt)
    {
        IStateSection reportSection =
            await GetReportSectionAsync(evt.EventTime, evt.ContextId);

        Type processorType =
            typeof(IProcessor<>).MakeGenericType(reportSection.GetType())

        IEnumerable<object> processors =
            _container.GetAllInstances(processorType);

        // NOTE the dynamic keywords here.
        foreach (dynamic processor in processors)
        {
            processor.Process(evt, (dynamic)reportSection);
        }

        ...
    }
}

With this implementation, DataRepository only knows during the call to its Process method what type of processor it needs. It does so by constructing a closed generic version of IProcessor<T> and asks the DI Container to return a list of them. Note that the API calls might look different depending on the DI Container you use. You should review your container's documentation to find out how to resolve collections. If you don't use a DI Container, you might want to inject an Func<Type, IEnumerable<object>> factory delegate instead.

IMPORTANT: Because of the dependency on the DI Container, this class should now be part of your Composition Root.

The DataRepository.Process method makes use of Reflection and calls the processor using C#'s dynamic keyword. This isn't per se the best approach (there are some downsides to it), but it produces the least amount of code, which is useful for demonstration purposes. Jimmy Bogard recently did an article that demonstrated two different approaches concerning the invocation of generic types. You might want to take a look at that article.


text:
Q: Markov State Model in Tikz I am quite lost as I am very new to latex. Could anyone lend me a hand to draw something that looks like this please?
In advance I appreciate your help guys....

A: \documentclass{article}

\usepackage{tikz}
\usetikzlibrary{cd}

\begin{document}

\begin{tikzcd}[
  >=latex,arrow style=tikz,
  row sep/custom/.initial=6em,column sep/custom/.initial=6em,
  row sep=custom,column sep=custom,
  every arrow/.append style={shift left},
  /tikz/annot/.style={draw,rounded corners,inner sep=.3ex,minimum size=1.5em},
  execute at end picture={
    \draw[dashed,<-] (k+1.south) to[out=180,in=-80] +(-.7,+.5) node[above] {$C_i$};
    \draw[dashed,<-] (k-1.north) to[out=  0,in=100] +(+.7,-.5) node[below] {$3N_i$};
    \draw[dashed,<-] (k-3.south) to[out=180,in=-80] +(-.7,+.5) node[above] {$C_e$};
    \draw[dashed,<-] (k+3.north) to[out=  0,in=100] +(+.7,-.5) node[below] {$3N_e$};
  }
  ]
  |[label={[annot]above left:X_1}]|
  E_i(N_i)_3 \ar[r,"k_1"{name=k+1}] \ar[d,"k_{-4}"] &
  |[label={[annot]above right:X_2},label={right:\mbox{inside}}]|
  E_i(C_i)   \ar[l,"k_{-1}"{name=k-1}] \ar[d,"k_2"] \\
  |[label={[annot]below left:Y_1}]|
  E_e(N_e)_3 \ar[r,"k_{-3}"{name=k-3}] \ar[u,"k_4"] &
  |[label={[annot]below right:Y_2},label={right:\mbox{outside}}]|
  E_e(C_e)   \ar[l,"k_3"{name=k+3}] \ar[u,"k_{-2}"] \\
\end{tikzcd}

\end{document}


text:
Q: Vuejs Filter String Replace I have an image that i am binding the source to pull in dynamic data:

The media.client.name returns a string that has %20 instead of spaces.
I have created a filter:
removeSpecial(value) {
  return value.replace("%20", " ");
}

How can I use this filter in the data binding of source please?
I have tried:

and

Neither seem to work unfortunately.

A: You can make method which will return prepared url computed method like this:
imageUrl(media){
  return '/public/images/' + media.client.name.replace("%20", " ") + '_' + media.client.id + '/' + media.type + '/' + media.fileName + '.' + media.ext;
}

Or if media is assigned in data you can use computed method which will return you same url
computed: {
 imageUrl(){
  return '/public/images/' + this.media.client.name.replace("%20", " ") + '_' + this.media.client.id + '/' + this.media.type + '/' + this.media.fileName + '.' + media.ext;
 }
}

A: That would depend on how you want to decode the URI component. If this media data is populated dynamically (I suppose so), you could make a method for parsing and decoding it (see example below). If you need this decoder as a filter, however, here's an excerpt from the docs:

Filters should be appended to the end of the JavaScript expression, denoted by the "pipe" symbol.

So your best bet is probably to use a computed property so you can "pipe" it. And yes, you could utilize the native method decodeURIComponent() for this exact purpose.
Approach #1: Method only

new Vue({
  el: '#app',

  data() {
    return {
      rootPath: '/public/images/',

      media: {
        client: {
          name: 'Music%20file%20with%20spaces',
          id: 123
        },
        type: 'music-file',
        fileName: 'some_music',
        ext: 'mp3'
      }
    }
  },

  methods: {
    getImgSource(media) {
      // Destructures the properties for improved readability.
      const { client, type, fileName, ext } = media;
      const { name, id } = client;

      // Uses template literals. Particularly useful for this situation
      // where you have several, unique delimiters.
      // Helps you see clearer how each of these URI components is combined.
      return `${this.rootPath}${decodeURIComponent(name)}_${id}/${type}/${fileName}.${ext}`;
    }
  }
})

Approach #2: Computed property + filter

new Vue({
  el: '#app',

  data() {
    return {
      rootPath: '/public/images/',

      media: {
        client: {
          name: 'Music%20file%20with%20spaces',
          id: 123
        },
        type: 'music-file',
        fileName: 'some_music',
        ext: 'mp3'
      }
    }
  },

  computed: {
    mediaFile() {
      const { client, type, fileName, ext } = this.media;
      const { name, id } = client;

      return `${this.rootPath}${name}_${id}/${type}/${fileName}.${ext}`;
    }
  },

  filters: {
    decodeName: window.decodeURIComponent
  }
})

{{ mediaFile | decodeName }}

Hope that helps.


text:
Q: create array at startup in extern variable xcode Hi I am looking for a way to perform a database fetch at start up and keep those items in an array.
My solution, although crude was to create an extern variable in viewDidFinishLaunchingWithOptions
I used
appdelegate.h
extern NSArray *listArray;

then
appdelegate.m
NSArray *listArray;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
listArray = [self createGlobalArray];
//other startup code, etc...

The problem is that when I go to any view controller and for example in viewdidload I say
VC1.m

-(void)viewDidLoad{
myVCArray = [NSArray arrayWithArray:listArray];

}

I get two errors: Apple Match-O linker error (directory not found...)
How do i fix this error?
Also is there a better way to do this?
Thank you

A: Usually linker errors are because things aren't being properly included in your build settings somewhere.  I'd make sure that Build Phases > Compile Sources as well as Build Phases > Linked Libraries contain all the files your project needs.


text:
Q: How to make subclass accept superclass as value? I have a superclass called Tree and a subclass called AVLTree that extends the class Tree.
A tree has children that are also Tree typed. An AVLTree has children that are AVLTree. I want to use the methods i wrote on the  Tree class, on this case the getLeft(returns the left son) and setLeft(set the left son).
The problem is the compiler can't convert a Tree to an AVLTree, even though they have the same variables, structure and constructors.
Any ideas on how should I solve this? Or should I just write all the methods that just an AVLTree has on the Tree class?
The code:
Tree.java:
public class Tree<T extends Tree<T>> {
  private T left = null;
  private T right = null;
  private Object data = null;

  public Tree () {
    //nothing
  }
  public Tree (Object data, T left, T right) {
    this.data = data;
    this.left = left;
    this.right = right;
  }
  public Tree (Object data) {
    this.data = data;
  }

  //Get Values
  public T getLeft() {
    return this.left;
  }
  public T getRight() {
    return this.right;
  }
  public Object getData() {
    return this.data;
  }
  //Set Values
  public void setLeft(T left) {
    this.left = left;
  }
  public void setRight(T right) {
    this.right = right;
  }
  public void setData(Object data) {
    this.data = data;
  }

  public T treeFromText(String in) {
    if (in=="()") return null;
    int i=0;
    T result = null;
    //Find expression
    int d = in.indexOf('c')+1;
    if (d==0) return null;

    int begl, endl, begr, endr;

    begl = d+1;
    endl = ClosingParentesis(in,begl);
    endr = in.length()-2;
    begr = OpeningParentesis(in,endr);

    T left = null, right = null;

    if (begl-endl==0) {
      left = null;
    } else left = treeFromText(in.substring(begl,endl+1));
    if (begr-endr==0) {
      right = null;
    } else right = treeFromText(in.substring(begr,endr+1));

    result.setData(in.charAt(d));
    result.setLeft(left);
    result.setRight(right);
    return result;
  }

  public static int ClosingParentesis(String in, int openPos) {
    int closePos = openPos;
    int counter = 1;
    while (counter > 0 && closePos < in.length()-1) {
      closePos++;
      if (in.charAt(closePos)=='(') counter++;
      if (in.charAt(closePos)==')') counter--;
    }
    return closePos;
  }

  public static int OpeningParentesis(String in, int closePos) {
    int openPos = closePos;
    int counter = 1;
    while (counter > 0 && openPos > 0) {
      openPos--;
      if (in.charAt(openPos)=='(') counter--;
      if (in.charAt(openPos)==')') counter++;
    }
    return openPos;
  }

AVLTree.java:
public class AVLTree extends Tree<AVLTree> {
  /*
  //Values and Variables
  private AVLTree left = null;
  private AVLTree right = null;
  private Object data;

  //Inicialization
  public AVLTree (Object data, AVLTree left, AVLTree right) {
    super(data,left,right);
  }
  public AVLTree (Object data) {
    super(data);
  }

  */
  public int getfactor() {
    return getHeight(this.getLeft())-getHeight(this.getRight());
  }
}

Test.java:
public static void main(String[] args) {
  AVLTree tree = new AVLTree();

  Scanner console = new Scanner(System.in);
  String in = console.nextLine().toLowerCase();

  tree = (AVLTree) tree.treeFromText(in); //The error is here.
  System.out.println(tree.getHeight());
  System.out.println(tree.TreePreOrder());

}

The way I expect it to work is that if the String 'in' in the Test.java is "(c3()(c2()()))" the return must be an Tree with value 3 and a right son with value 2. This return must be of type Tree or anything that extends Tree.

A: You can achieve this by the power of generics: define a new circular generic T:
public class Tree<T extends Tree<T>>
{
    T left;
    T right;

    public T doSomething()
    {
        return left;
    }

    public static class AVLTree extends Tree<AVLTree>
    {
        public AVLTree foo()
        {
            return doSomething();
        }
    }
}

UPDATE: here is how you can create different tree instances:
import java.util.Objects;
public class TreesFactory
{
    public static AVLTree createAVLTreeFrom(String in)
    {
        return treeFromText(in, AVLTree::new);
    }

    @FunctionalInterface
    interface SimpleFactory<T extends Tree<T>>
    {
        T createNew();
    }

    public static <T extends Tree<T>> T treeFromText(String in, SimpleFactory<T> treeFactory)
    {
        if (Objects.equals(in, "()"))
            return null;

        T result = treeFactory.createNew();
        //Find expression
        int d = in.indexOf('c') + 1;
        if (d == 0)
            return null;

        int begl, endl, begr, endr;

        begl = d + 1;
        endl = ClosingParentesis(in, begl);
        endr = in.length() - 2;
        begr = OpeningParentesis(in, endr);

        T left, right;

        if (begl - endl == 0)
        {
            left = null;
        }
        else
            left = treeFromText(in.substring(begl, endl + 1), treeFactory);
        if (begr - endr == 0)
        {
            right = null;
        }
        else
            right = treeFromText(in.substring(begr, endr + 1), treeFactory);

        result.setData(in.charAt(d));
        result.setLeft(left);
        result.setRight(right);
        return result;
    }

    public static int ClosingParentesis(String in, int openPos)
    {
        int closePos = openPos;
        int counter = 1;
        while (counter > 0 && closePos < in.length() - 1)
        {
            closePos++;
            if (in.charAt(closePos) == '(')
                counter++;
            if (in.charAt(closePos) == ')')
                counter--;
        }
        return closePos;
    }

    public static int OpeningParentesis(String in, int closePos)
    {
        int openPos = closePos;
        int counter = 1;
        while (counter > 0 && openPos > 0)
        {
            openPos--;
            if (in.charAt(openPos) == '(')
                counter--;
            if (in.charAt(openPos) == ')')
                counter++;
        }
        return openPos;
    }
}

And the Main:
public static void main(String[] args)
{
    Scanner console = new Scanner(System.in);
    String in = console.nextLine().toLowerCase();

    AVLTree tree = TreesFactory.createAVLTreeFrom(in);
    //...
}

A: You need a way to get an AVLTree instantiated from a String, using the logic in Tree.treeFromText.

*

*Declare Tree as abstract.

*Create a new method in Tree:
abstract protected T createEmptyTree();

*Override that method in AVLTree to return an empty instance of AVLTree.
@Override
protected AVLTree createEmptyTree() {
  return new AVLTree();
}

*In treeFromText(), wherever you need to create an empty instance of T, invoke createEmptyTree().
You already have the rest of the logic.
Try to avoid returning null anywhere. It's best to return an empty AVLTree instead of a null.


text:
Q: Render docx file in a browser I'm using docx4j to convert a microsoft word document into a pdf then displaying it in a browser http://www.docx4java.org/trac/docx4j and it works well for a preview. The problem I'm facing is that this conversion loses most of the microsoft word document formatting. Page breaks and fonts don't transfer into the PDF format properly and even though I'm using standard font types docx4j doesn't come with them. In a Linux Tomcat hosted scenario fonts are not found and throw exceptions as it falls back to sans serif or other generic types.
I have found this Microsoft tool to make documents render online, but I'm behind a firewall so I cannot include this tool as an option: https://products.office.com/en-us/office-online/view-office-documents-online
I'm open to suggestion on displaying a docx file as a preview and print option from within a browser. Pdf conversion appears to be the most promising, but I run into formatting issues.
Any ideas are welcome!

A: Have a play with http://converter-eval.plutext.com/viewer.html
Consider it an alpha level preview.  We haven't quite released it yet, but you will be able to host it behind a firewall.
It isn't open source, I'm afraid, and we're still working out pricing (and whether/how there could be a free edition).

A: If you only need to render a docx document in a browser, u can use Google Documents Viewer for this as :
<iframe src="http://docs.google.com/gview?url=pathOfDocx&embedded=true" />


text:
Q: Does Entity Framework need to be "refreshed" to pick up database schema changes while site is still running? I have an ASP.NET site using Entity Framework that was deployed to our test environment. It turned out that the test database was not up to date with schema changes. We were getting errors such as:

Resource not found for the segment 'myTableName'.

We subsequently updated the database schema (we confirmed the schema is now identical to the development database schema we were using previously), but we are still getting the same errors.
Note: at this point the .edmx matches what the schema of the database is, as it was up to date with the dev database, and the test database schema is now identical.
Does Entity Framework need to somehow "refresh" its view of the database schema (say by restarting the IIS site), or should it be aware of the schema changes on each page request?
I know I could just try restarting the IIS site and see if it fixes it (I work for a large company and have already put in the request but it takes a long time), but I would like to understand what exactly is going on.
EDIT
Ok to clarify, we already updated the .edmx when we first made the schema changes (in the dev database). The site works just fine in the development environment. We deployed to test assuming the database had the exact same schema but it didn't and we updated the schema while the site was still running.


text:
Q: Linked Databases in SQL Developer I'm using SQL Developer to host some data, but I think my configuration isn't right. Lets say I have a database named DB1 with the tables
DB1
-db1_name
-db1_cities

The problem is when I try to create a new database let say DB2, SQLdeveloper creates the database but it also includes all the tables from DB1 (db1_name,db1_cities). Also if I removed the tables from DB2, the tables also  disappear from DB1. How can I change my configuration so this does not happen anymore and each database is independent from each other?
To create a new data base I usually go in the SQL Developer GUI interface  to connections, then I click on new Connection and provide the connection name, user name, and password. I leave the connection type to basic and the role to default. The host name as local host, and the default port.

A: That's happening because you are currently adding a new database connection instead of creating a database.
To create a new database from scratch, take a look at this link, it'll take you through step by step on creating the new database.


text:
Q: Getting extra Row containing Null Value for specific Names In my Query if CompanyName has Coamount = NULL then Final should be as of Contract amount. If CompanyName has Coamount then Final would be ContractAmount + Coamount.
I am getting all these answers but the query is also returning me rows which has NULL value in Coamount for those company name in which coamount is already present.
for eg: Row1,  why is that row coming when I am getting row 2 as my answer according to my query.
Here is the code:
SELECT DISTINCT
                    HBRegions.RegionName,PropertyGroups.Name AS Owner,Properties.EntityID,  Properties.Address,Vendors.CompanyName,
                    SubContractorDrawDetails.InvoiceUploadDate,SubContractorDrawDetails.InvoiceAmount,SubContractorDrawDetails.PaymentDate,
                     LienWaivers.FinalLienWaiverRcvdDate,SubContractorDrawDetails.PaymentAmount, subcontractors.ContractAmount,cc.Coamount ,
                     (subcontractors.ContractAmount + cc.Coamount ) AS ActualContractAmount,

                     case when cc.Coamount is null then SubContractors.ContractAmount
                     when CC.Coamount is not null then (subcontractors.ContractAmount + cc.Coamount ) end as Final

FROM         Users inner JOIN
                      Vendors ON Users.UserId = Vendors.UserID inner JOIN
                      LienWaivers ON Users.UserId = LienWaivers.UserID inner JOIN
                      Constructions ON LienWaivers.ConstructionID = Constructions.ConstructionId inner JOIN
                      Properties ON Constructions.HBId = Properties.HBId inner  JOIN
                      ChangeOrderDetails ON Constructions.ConstructionId = ChangeOrderDetails.ConstructionId left JOIN
                      ChangeOrderLineItems ON Users.UserId = ChangeOrderLineItems.SubContractorId AND
                      ChangeOrderDetails.ChangeOrderId = ChangeOrderLineItems.ChangeOrderId

                      left join
                      (select  sum(ChangeOrderDetails.ChangeOrderApprovedAmountContractor) as Coamount, ChangeOrderLineItems.SubContractorId,Constructions.ConstructionId
                      from ChangeOrderDetails  inner join ChangeOrderLineItems
                      on ChangeOrderDetails.ChangeOrderId = ChangeOrderLineItems.ChangeOrderId
                      inner join Users on ChangeOrderLineItems.SubContractorId = Users.UserId
                      left join Constructions on Constructions.ConstructionId = ChangeOrderDetails.ConstructionId
                     -- left join  Properties on Properties.HBId = Constructions.HBId
                    where ChangeOrderDetails.ChangeOrderApprovedAmountContractor is not null
                      group by ChangeOrderLineItems.SubContractorId,Constructions.ConstructionId
                      ) AS cc on cc.SubContractorId = ChangeOrderLineItems.SubContractorId and cc.ConstructionId = Constructions.ConstructionId
                    inner join   HBRegions ON Properties.RegionId = HBRegions.RegionID inner JOIN
                      PropertyGroups ON Properties.PropertyGroup = PropertyGroups.PropertyGroupId
                    inner join  SubContractors ON Users.UserId = SubContractors.UserID AND Properties.HBId = SubContractors.HBId
                    inner join SubContractorDrawDetails ON SubContractors.SubContractorId = SubContractorDrawDetails.SubContractorId

WHERE (Properties.Address = '470 ROYCROFT BLVD BUFFALO NY 14225')[enter image description here][1]


text:
Q: Convert comma-separated fields to concat() function I have a table_product that contains comma-separated strings;
id | products
-----------
1  | tv,phone,tablet
2  | computer,tv
3  | printer,tablet,radio

To avoid manual concatenation, like concat(tv,',',phone,',',tablet)
I want to select the data from table_product.products as concat() statement.
Tried this, but getting an error:
select concat(select products from table_product where id=1) from table_sales

Is there any short and basic way to perform this query?


text:
Q: Stuck in a while Loop while parsing JSON into an array of Objects I am pulling data from MySQL into a web page and I can not see while I am stuck in my while loop.
For background I am pulling data from my database and trying to put it into objects that look something like this:
var SawtoothPassTrailhead = {
  name: "Sawtooth Pass Trailhead",
  lat:  36.453165,
  long:  -118.596751,
  type: "backpacking",

  //Title then link
  seekAdventure: [],
  blogs: ['Mineral King Loop – Sequoia National Park (45 Mile Loop) - Backpackers Review' , 'https://backpackers-review.com/trip-reports/sequoia-mineral-king/'],
  youtTube: []
};

The JSON data that is coming back from my DB call for my test looks like this:
[{"TrailHeadID":"1","TrailHeadName":"Tanner Trail - Grand Canyon","TrailHeadLat":"36.03260","TrailHeadLong":"-111.85250","GuideTitle":"1 Week Traversing the Grand Canyon","GuideLink":"https:\/\/www.seekadventure.net\/d\/94-1-week-traversing-the-grand-canyon","GuideMediaType":"SeekAdventure"},{"TrailHeadID":"2","TrailHeadName":"Badger Pass - Yosemite","TrailHeadLat":"37.66480","TrailHeadLong":"-119.66340","GuideTitle":"22 Hours of Driving, 1.5 Days of Snowshoeing, Yosemite National Park","GuideLink":"https:\/\/www.seekadventure.net\/d\/79-22-hours-of-driving-1-5-days-of-snowshoeing-yosemite-nationa","GuideMediaType":"SeekAdventure"},{"TrailHeadID":"2","TrailHeadName":"Badger Pass - Yosemite","TrailHeadLat":"37.66480","TrailHeadLong":"-119.66340","GuideTitle":"Snowshoeing to Dewey Point in Yosemite (Socal Hike)r","GuideLink":"https:\/\/socalhiker.net\/snowshoeing-to-dewey-point-in-yosemite\/","GuideMediaType":"blog"},{"TrailHeadID":"3","TrailHeadName":"Descanso Beach - Catalina","TrailHeadLat":"33.35040","TrailHeadLong":"-118.32820","GuideTitle":"Kayak Camping Catalina Island","GuideLink":"https:\/\/www.seekadventure.net\/d\/76-kayak-camping-catalina-island","GuideMediaType":"SeekAdventure"},{"TrailHeadID":"4","TrailHeadName":"Trans Catalina Trail","TrailHeadLat":"33.34030","TrailHeadLong":"-118.32620","GuideTitle":"Mini Trans Catalina Trail","GuideLink":"https:\/\/www.seekadventure.net\/d\/73-mini-trans-catalina-trip","GuideMediaType":"SeekAdventure"},{"TrailHeadID":"4","TrailHeadName":"Trans Catalina Trail","TrailHeadLat":"33.34030","TrailHeadLong":"-118.32620","GuideTitle":"Backpacking the Trans-Catalina Trail (Bearfoot Theory)","GuideLink":"https:\/\/bearfoottheory.com\/backpacking-the-trans-catalina-trail\/","GuideMediaType":"blog"},{"TrailHeadID":"5","TrailHeadName":"High Sierra Trail","TrailHeadLat":"36.55470","TrailHeadLong":"-118.74890","GuideTitle":"High Sierra Trail Complete Guide","GuideLink":"https:\/\/www.seekadventure.net\/d\/22-california-high-sierra-trail-to-mt-whitney'","GuideMediaType":"SeekAdventure"},{"TrailHeadID":"5","TrailHeadName":"High Sierra Trail","TrailHeadLat":"36.55470","TrailHeadLong":"-118.74890","GuideTitle":"High Sierra Trail (SoCal Hiker)","GuideLink":"https:\/\/socalhiker.net\/overview-of-the-high-sierra-trail\/","GuideMediaType":"blog"},{"TrailHeadID":"6","TrailHeadName":"Deer Springs Trail - San Jacinto","TrailHeadLat":"33.75300","TrailHeadLong":"-116.72270","GuideTitle":"Deer Springs Trail","GuideLink":"https:\/\/www.seekadventure.net\/d\/26-california-deer-springs-trail-san-jacinto-mountain","GuideMediaType":"SeekAdventure"},{"TrailHeadID":"7","TrailHeadName":"Reflection Canyon","TrailHeadLat":"37.25220","TrailHeadLong":"-110.97350","GuideTitle":"Reflection Canyon","GuideLink":"https:\/\/www.seekadventure.net\/d\/24-utah-photographing-reflection-canyon","GuideMediaType":"SeekAdventure"},{"TrailHeadID":"7","TrailHeadName":"Reflection Canyon","TrailHeadLat":"37.25220","TrailHeadLong":"-110.97350","GuideTitle":"Reflection Canyon Backpacking Guide (Clever Hiker)","GuideLink":"https:\/\/www.cleverhiker.com\/blog\/reflection-canyon-backpacking-guide","GuideMediaType":"blog"},{"TrailHeadID":"8","TrailHeadName":"Big Pine Lakes - North Fork Trail","TrailHeadLat":"37.12820","TrailHeadLong":"-118.42770","GuideTitle":"North Fork to 2nd Lake Sierra Nevada in a Snow Storm","GuideLink":"https:\/\/www.seekadventure.net\/d\/18-california-north-fork-to-2nd-lake-sierra-nevada-in-a-snow-storm","GuideMediaType":"SeekAdventure"},{"TrailHeadID":"8","TrailHeadName":"Big Pine Lakes - North Fork Trail","TrailHeadLat":"37.12820","TrailHeadLong":"-118.42770","GuideTitle":"Hiking To Big Pine Lakes via The North Fork Trail (Trail to Peak)","GuideLink":"https:\/\/trailtopeak.com\/2017\/07\/09\/hiking-to-big-pine-lakes-via-the-north-fork-trail\/","GuideMediaType":"blog"},{"TrailHeadID":"9","TrailHeadName":"Fish Creek Wash Anza Borrego","TrailHeadLat":"33.03872","TrailHeadLong":"-116.09941","GuideTitle":"Jeeping in Fish Creek Wash Anza Borrego","GuideLink":"https:\/\/www.seekadventure.net\/d\/99-jeeping-in-fish-creek-wash-anza-borrego","GuideMediaType":"SeekAdventure"}]

I am creating objects from the data so I can insert each object as a marker on a google map with a pop-up. The tricky part is anything from the above JSON that starts with the same TrailHeadID needs to be in the same Object so it is the same pop-up bubble on Google Maps. Which is where the wile loop comes in with my code below.
I through a console.log() in right before the end of thw while loop and it looks like its getting caught as a 2, so it processes the first one right and then doesn't increment:
function myFunction(response) {
    var arr = JSON.parse(response);
    var i;
    var localTrailHeadID;
    var trailHeadCounter;
    var TrailHeadObject

    //set array conts all to zero
    var seekAdventureCount;
    var blogsCount;
    var youtubeCount;

    //for each row returned by mySQL
    for(i = 0; i < arr.length; i++){

      localTrailHeadID = arr[i].TrailHeadID;

      //create new trailhead object
      TrailHeadObject = new Object();

      //set array counters to zero
      var seekAdventureCount =0;
      var blogsCount = 0;
      var youtubeCount = 0;

      //set name lat and long
      TrailHeadObject.name = arr[i].TrailHeadName;
      TrailHeadObject.lat = arr[i].TrailHeadLat;
      TrailHeadObject.long = arr[i].TrailHeadLong;

      //set TrailHeadObject Guide arrays to empty
      TrailHeadObject.seekAdventureGuideList = [];
      TrailHeadObject.blogGuideList = [];
      TrailHeadObject.youTubegGuideList = [];

      //Add trail Guides
      while(localTrailHeadID == arr[i].TrailHeadID ){
        //check first guide media type and add to correct Array
        if(arr[i].GuideMediaType == "SeekAdventure"){
          TrailHeadObject.seekAdventureGuideList[seekAdventureCount] = arr[i].GuideTitle;
          seekAdventureCount = seekAdventureCount + 1;
          TrailHeadObject.seekAdventureGuideList[seekAdventureCount] = arr[i].GuideLink;
          seekAdventureCount = seekAdventureCount + 1;
        }
        if(arr[i].GuideMediaType == "blog"){
          TrailHeadObject.blogGuideList[blogsCount] = arr[i].GuideTitle;
          blogsCount = blogsCount + 1;
          TrailHeadObject.blogGuideList[blogsCount] = arr[i].GuideLink;
          blogsCount = blogsCount + 1;
        }
        if(arr[i].GuideMediaType == "YouTube"){
          TrailHeadObject.youTubegGuideList[youtubeCount] = arr[i].GuideTitle;
          youtubeCount = youtubeCount + 1;
          TrailHeadObject.youTubegGuideList[youtubeCount] = arr[i].GuideLink;
          youtubeCount = youtubeCount + 1;
        }
        console.log(arr[i+1].TrailHeadID);
        localTrailHeadID = arr[i+1].TrailHeadID;

      } //end while loop adding guides

      //add object to array of markers
      markers1[i] = TrailHeadObject;

    }//end for Loop

} //end my function

I cant see why the while loop isn't breaking. shouldn't this line break it: localTrailHeadID = arr[i+1].TrailHeadID;Based on my input data above?

A: The problem is that you are not incrementing i inside the while loop
This means that the loops condition will always compare the TrailHeadID properties of the i and i + 1 objects in the array. If the array has objects that have the same value for this property, the while loop's condition will always be true.
Here is how I will do it:

const arr = [{"TrailHeadID":"1","TrailHeadName":"Tanner Trail - Grand Canyon","TrailHeadLat":"36.03260","TrailHeadLong":"-111.85250","GuideTitle":"1 Week Traversing the Grand Canyon","GuideLink":"https:\/\/www.seekadventure.net\/d\/94-1-week-traversing-the-grand-canyon","GuideMediaType":"SeekAdventure"},{"TrailHeadID":"2","TrailHeadName":"Badger Pass - Yosemite","TrailHeadLat":"37.66480","TrailHeadLong":"-119.66340","GuideTitle":"22 Hours of Driving, 1.5 Days of Snowshoeing, Yosemite National Park","GuideLink":"https:\/\/www.seekadventure.net\/d\/79-22-hours-of-driving-1-5-days-of-snowshoeing-yosemite-nationa","GuideMediaType":"SeekAdventure"},{"TrailHeadID":"2","TrailHeadName":"Badger Pass - Yosemite","TrailHeadLat":"37.66480","TrailHeadLong":"-119.66340","GuideTitle":"Snowshoeing to Dewey Point in Yosemite (Socal Hike)r","GuideLink":"https:\/\/socalhiker.net\/snowshoeing-to-dewey-point-in-yosemite\/","GuideMediaType":"blog"},{"TrailHeadID":"3","TrailHeadName":"Descanso Beach - Catalina","TrailHeadLat":"33.35040","TrailHeadLong":"-118.32820","GuideTitle":"Kayak Camping Catalina Island","GuideLink":"https:\/\/www.seekadventure.net\/d\/76-kayak-camping-catalina-island","GuideMediaType":"SeekAdventure"},{"TrailHeadID":"4","TrailHeadName":"Trans Catalina Trail","TrailHeadLat":"33.34030","TrailHeadLong":"-118.32620","GuideTitle":"Mini Trans Catalina Trail","GuideLink":"https:\/\/www.seekadventure.net\/d\/73-mini-trans-catalina-trip","GuideMediaType":"SeekAdventure"},{"TrailHeadID":"4","TrailHeadName":"Trans Catalina Trail","TrailHeadLat":"33.34030","TrailHeadLong":"-118.32620","GuideTitle":"Backpacking the Trans-Catalina Trail (Bearfoot Theory)","GuideLink":"https:\/\/bearfoottheory.com\/backpacking-the-trans-catalina-trail\/","GuideMediaType":"blog"},{"TrailHeadID":"5","TrailHeadName":"High Sierra Trail","TrailHeadLat":"36.55470","TrailHeadLong":"-118.74890","GuideTitle":"High Sierra Trail Complete Guide","GuideLink":"https:\/\/www.seekadventure.net\/d\/22-california-high-sierra-trail-to-mt-whitney'","GuideMediaType":"SeekAdventure"},{"TrailHeadID":"5","TrailHeadName":"High Sierra Trail","TrailHeadLat":"36.55470","TrailHeadLong":"-118.74890","GuideTitle":"High Sierra Trail (SoCal Hiker)","GuideLink":"https:\/\/socalhiker.net\/overview-of-the-high-sierra-trail\/","GuideMediaType":"blog"},{"TrailHeadID":"6","TrailHeadName":"Deer Springs Trail - San Jacinto","TrailHeadLat":"33.75300","TrailHeadLong":"-116.72270","GuideTitle":"Deer Springs Trail","GuideLink":"https:\/\/www.seekadventure.net\/d\/26-california-deer-springs-trail-san-jacinto-mountain","GuideMediaType":"SeekAdventure"},{"TrailHeadID":"7","TrailHeadName":"Reflection Canyon","TrailHeadLat":"37.25220","TrailHeadLong":"-110.97350","GuideTitle":"Reflection Canyon","GuideLink":"https:\/\/www.seekadventure.net\/d\/24-utah-photographing-reflection-canyon","GuideMediaType":"SeekAdventure"},{"TrailHeadID":"7","TrailHeadName":"Reflection Canyon","TrailHeadLat":"37.25220","TrailHeadLong":"-110.97350","GuideTitle":"Reflection Canyon Backpacking Guide (Clever Hiker)","GuideLink":"https:\/\/www.cleverhiker.com\/blog\/reflection-canyon-backpacking-guide","GuideMediaType":"blog"},{"TrailHeadID":"8","TrailHeadName":"Big Pine Lakes - North Fork Trail","TrailHeadLat":"37.12820","TrailHeadLong":"-118.42770","GuideTitle":"North Fork to 2nd Lake Sierra Nevada in a Snow Storm","GuideLink":"https:\/\/www.seekadventure.net\/d\/18-california-north-fork-to-2nd-lake-sierra-nevada-in-a-snow-storm","GuideMediaType":"SeekAdventure"},{"TrailHeadID":"8","TrailHeadName":"Big Pine Lakes - North Fork Trail","TrailHeadLat":"37.12820","TrailHeadLong":"-118.42770","GuideTitle":"Hiking To Big Pine Lakes via The North Fork Trail (Trail to Peak)","GuideLink":"https:\/\/trailtopeak.com\/2017\/07\/09\/hiking-to-big-pine-lakes-via-the-north-fork-trail\/","GuideMediaType":"blog"},{"TrailHeadID":"9","TrailHeadName":"Fish Creek Wash Anza Borrego","TrailHeadLat":"33.03872","TrailHeadLong":"-116.09941","GuideTitle":"Jeeping in Fish Creek Wash Anza Borrego","GuideLink":"https:\/\/www.seekadventure.net\/d\/99-jeeping-in-fish-creek-wash-anza-borrego","GuideMediaType":"SeekAdventure"}];
const getPropName = (o) => {
  if(o.GuideMediaType == "SeekAdventure") {
    return "seekAdventureGuideList";
  } else if (o.GuideMediaType == "blog"){
    return "blogGuideList"
  } else if(o.GuideMediaType == "YouTube") {
    return "youTubegGuideList";
  }
  return "unknown";
}

const markers = arr.reduce((a, c) => {
  const found = a.find(v => v.id == c.TrailHeadID);
  const propName = getPropName(c);
  if (found) {
    found[propName] = [...(found[propName] || []), c.GuideTitle, c.GuideLink];
  } else {
    a.push({
      id: c.TrailHeadID,
      name: c.TrailHeadName,
      lat: c.TrailHeadLat,
      long: c.TrailHeadLong,
      [propName]: [c.GuideTitle, c.GuideLink]
    });
  }
  return a;
}, []);

console.log(markers);


text:
Q: Modify pop up iframe google calendar I have an iframe on my web page to display google calendar. I am using django and it correctly shows me the events that I create.
I've been looking for several days, but I can't find a way to modify the pop up that the iframe generates when you select an event.
Let's see if someone can give me some ideas on how to do it or where to look.
A greeting.
This is my code iframe generate for Google:
<iframe src="https://calendar.google.com/calendar/embed?height=700&wkst=1&bgcolor=%23ffffff&ctz=Europe%2FMadrid&src=amZhbHZhcmV6MjMyQGdtYWlsLmNvbQ&color=%23039BE5&title=Web%20Asociacion&showDate=1&showPrint=0&showTabs=0&showCalendars=0&showTz=0" style="border:solid 1px #777" width="900" height="700" frameborder="0" scrolling="no"></iframe>

A: Due to the CORS policy, you can't
If you have an iframe on your website, unless that iframe is generated from the same origin then you won't have access to it.
If it does come from the same origin, you can do something like the following:
document.getElementById('myframe').contentWindow.document

Though since you are using Google Calendar as an iframe, you won't have access to it as it's origin is Google's servers.


text: Q: endpoint is working! but in the response and array of data is empty(ReactJs) also in postman it is working fine enter image description herein postman am getting array of data but in local or on the server arrayy of data is empty please help!


text:
Q: Fast way to generate samples with np.random.choice()? I want to generate random sample without replacement for N times, like following:
import numpy as np

sample = np.zeros([100000, 4], int)
for i in range(100000):
    sample[i] = np.random.choice(128, 4, replace=False)

If the iterations become very large, the overall sampling will be time consuming. Is there any way to speed up this sampling?

A: Your method
In [16]: sample = np.zeros([100000, 4], int)

In [17]: %timeit for i in range(100000):sample[i] = np.random.choice(128, 4, rep
    ...: lace=False)
1 loop, best of 3: 2.5 s per loop

While you can write:
In [149]: %timeit d=np.random.choice(128,100000);sample1=np.array([(d+x)%128 for x in np.random.choice(128,4)])
The slowest run took 4.63 times longer than the fastest. This could mean that an intermediate result is being cached.
100 loops, best of 3: 4.11 ms per loop

This is way faster on my machine
This is less random maybe, but this depends on your application.
after all for loop is very slow in vanilla python. you maybe interested in Cython, or Numba

A: This will give you a random int range(0,128) in the shape (100000,4)
np.random.randint(128, size=(100000,4))

A: Use random.sample instead of np.random.choice
In [16]: import time
    ...: start_time = time.time()
    ...: sample = np.zeros([100000, 4], int)
    ...: for i in range(100000):
    ...:     sample[i] = random.sample(range(128), 4)
    ...: print("--- %s seconds ---" % (time.time() - start_time))
    ...:
--- 0.7096474170684814 seconds ---

In [17]: import time
    ...: start_time = time.time()
    ...: sample = np.zeros([100000, 4], int)
    ...: for i in range(100000):
    ...:     sample[i] = np.random.choice(128, 4, replace=False)
    ...: print("--- %s seconds ---" % (time.time() - start_time))
    ...:
--- 5.2036824226379395 seconds ---


text:
Q: Cannot access PHP Basic Authentication variables I had this question posted here, maybe admins did not understand it correctly and marked it as duplicate, so I am posting it again, because I cannot access these variables as defined here. And so called duplicate question does not help me with my query. In my case when I call PHP_AUTH_USER, PHP_AUTH_PW, and AUTH_TYPE they are empty, null. Can someone please help me understand why? My .htaccess file:
AuthType Basic

AuthName "You need to login to access this page."
AuthUserFile /usr/local/..../.htpasswd
Require valid-user

RewriteEngine on
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]

When I do var_dump($_SERVER); in my PHP code, I see that none of these variables are set, why is that? Is it impossible to access these variables if basic HTTP Authentication used with .htaccess and .htpasswd files alone?

A: The answer is: PHP doesn't get AUTH-variables because Apache doesn't send them to PHP-interpreter. Why?
This part will work for PHP-CGI:
<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
</IfModule>

Only if

Apache won't pass it to CGI apps unless you compile it with the
  SECURITY_HOLE_PASS_AUTHORIZATION flag.
  How can I use Basic HTTP Authentication in PHP?

You should disable basic auth in .htaccess file and use it in PHP.
Manual: http://php.net/manual/en/features.http-auth.php


text:
Q: Simplifying complex nested SQL View. Transpose and versioned data I have a very complicated (to me, anyway) Nested SQL View.  I have several separate sub-Views that are almost all the same.  I think my view would be much more efficient if I could combine them into fewer statements.  In essence, I am trying to transpose data in a particular table, but there is also revision history in the tables.  I need to first eliminate all except the latest revision data.  I only know how to do this one at a time.  Code I've included is two of the sub-views.  I would like to combine these into one view.  I can then hopefully add in more when I understand the logic and context of the statements.
One of the Views.
The view i have actually works perfectly.  However, in certain circumstances, depending on the application calling for the SQL View, it may take several minutes to generate the results.  Mind you what I have included here is just a small portion of my entire compound View, but for sake of simplicity, I'm only posting a small part of it, that should solve 80% of the problem, if I can combine views.
SELECT DocumentID, VariableID, ExtensionID, Description, RevisionNo, CurrentStatusID, Date, TransitionNr, RevNr, LatestRevisionNo, Filename, Deleted
FROM     (SELECT dbo.VariableValue.DocumentID, dbo.VariableValue.VariableID, dbo.Documents.ExtensionID, dbo.VariableValue.ValueText AS PartNumber, dbo.VariableValue.RevisionNo, dbo.Documents.CurrentStatusID,
                                    dbo.TransitionHistory.Date, dbo.TransitionHistory.TransitionNr, dbo.TransitionHistory.RevNr, dbo.Documents.LatestRevisionNo, dbo.Documents.Filename, dbo.Documents.Deleted, ROW_NUMBER() OVER (PARTITION BY
                                    dbo.VariableValue.DocumentID
                  ORDER BY dbo.VariableValue.RevisionNo DESC, dbo.TransitionHistory.TransitionNr DESC) AS Seq
FROM     dbo.Documents INNER JOIN
                  dbo.VariableValue ON dbo.Documents.DocumentID = dbo.VariableValue.DocumentID INNER JOIN
                  dbo.TransitionHistory ON dbo.Documents.DocumentID = dbo.TransitionHistory.DocumentID
WHERE  (dbo.Documents.Deleted = 0) AND (dbo.Documents.ExtensionID = 3) AND (dbo.Documents.CurrentStatusID <> 0) AND (dbo.VariableValue.VariableID = 47)) t
WHERE  Seq = 1

Another view (Note only difference is VariableID ="49" (AS Description) instead of "47" (AS PartNumber).
SELECT DocumentID, VariableID, ExtensionID, Description, RevisionNo, CurrentStatusID, Date, TransitionNr, RevNr, LatestRevisionNo, Filename, Deleted
FROM     (SELECT dbo.VariableValue.DocumentID, dbo.VariableValue.VariableID, dbo.Documents.ExtensionID, dbo.VariableValue.ValueText AS Description, dbo.VariableValue.RevisionNo, dbo.Documents.CurrentStatusID,
                                    dbo.TransitionHistory.Date, dbo.TransitionHistory.TransitionNr, dbo.TransitionHistory.RevNr, dbo.Documents.LatestRevisionNo, dbo.Documents.Filename, dbo.Documents.Deleted, ROW_NUMBER() OVER (PARTITION BY
                                    dbo.VariableValue.DocumentID
                  ORDER BY dbo.VariableValue.RevisionNo DESC, dbo.TransitionHistory.TransitionNr DESC) AS Seq
FROM     dbo.Documents INNER JOIN
                  dbo.VariableValue ON dbo.Documents.DocumentID = dbo.VariableValue.DocumentID INNER JOIN
                  dbo.TransitionHistory ON dbo.Documents.DocumentID = dbo.TransitionHistory.DocumentID
WHERE  (dbo.Documents.Deleted = 0) AND (dbo.Documents.ExtensionID = 3) AND (dbo.Documents.CurrentStatusID <> 0) AND (dbo.VariableValue.VariableID = 49)) t
WHERE  Seq = 1

Any takers on this one?
Thank you.
Added 7/1/2019: 13:37pm CST
I will need to add some more detail.  No, simply adding the additional OR statement to include 47 and 49 does not work.  Mainly because 47 will end up being one column, and 49 in another.  Both had independent RevisionNo sequence to find MAX for as well.
As it stands, the entire VIEW routines that I'm using results in perfect data.  However, depending on how applications call for the VIEW, it can take in excess of 3 minutes to generate the results.  I have used In SQL Studio, When I generate results in Design mode, it only takes a few second.  I did notice that If I used any kind of TOP statement, that is where it takes up to several minutes to generate results.  Even in Studio.  I'll post some data samples.
Added 7/1/2019: 15:18pm CST
It is difficult to explain in words what I'm trying to do.  Here is a graphic of what it is I am attempting:
Show Visual Description of this post.


text:
Q: Load all csv/txt files from one directory and merge them via python I have a folder which contains hundreds (possibly over 1 k) of csv data files, of chronological data. Ideally this data would be in one csv, so that I can analyse it all in one go. What I would like to know is, is there a way to append all the files to one another using python.
My files exist in folder locations like so:
C:\Users\folder\Database Files\1st September
C:\Users\folder\Database Files\1st October
C:\Users\folder\Database Files\1st November
C:\Users\folder\Database Files\1st December
etc

Inside each of the folders there is 3 csv (I am using the term csv loosly since these files are actually saved as .txt files containing values seperated by pipes |)
Lets say these files are called:
MonthNamOne.txt
MonthNamTwo.txt
MonthNameOneTwoMurged.txt

How would I, or even is it possible to code something to go through all of these folders in this directory and then merge together all the OneTwoMurged.txt files?

A: This will recursively process a directory, match a specific file pattern for processing, and append the results of processed files.  This will parse the csvs as well, so you could do individual line analysis and processing as well.  Modify as needed :)
#!python2
import os
import fnmatch
import csv
from datetime import datetime as dt

# Open result file
with open('output.txt','wb') as fout:
    wout = csv.writer(fout,delimiter='|')

    # Recursively process a directory
    for path,dirs,files in os.walk('files'):

        # Sort directories for processing.
        # In this case, sorting directories named "Month Year" chronologically.
        dirs.sort(key=lambda d: dt.strptime(d,'%B %Y'))
        interesting_files = fnmatch.filter(files,'*.txt')

        # Example for sorting filenames with a custom chronological sort "Month Year.txt"
        for filename in sorted(interesting_files,key=lambda f: dt.strptime(f,'%B %Y.txt')):

            # Generate the full path to the file.
            fullname = os.path.join(path,filename)
            print 'Processing',fullname

            # Open and process file
            with open(fullname,'rb') as fin:
                for line in csv.reader(fin,delimiter='|'):
                    wout.writerow(line)

A: Reading into pandas dataframe (choice of axis depends on your application), my example adds columns of same length
import glob
import pandas as pd

df=pd.DataFrame()
for files in glob.glob("*.csv"):
    print files
    df = pd.concat([df,pd.read_csv(files).iloc[:,1:]],axis=1)

axis = 0 would add row-wise

A: For all files in folder with .csv suffix
import glob
import os

filelist = []

os.chdir("folderwithcsvs/")
for counter, files in enumerate(glob.glob("*.csv")):
    filelist.append(files)
    print "do stuff with file:", files, counter

print filelist

for fileitem in filelist:
    print fileitem

Obviously the "do stuff part" depends on what you want done with the files, this is looking getting your list of files.
If you want to do something with the files on a monthly basis then you could use datetime and create possible months, same for days or yearly data.
For example, for monthly files with the names Month Year.csv it would look for each file.
import subprocess, datetime, os

start_year, start_month = "2001", "January"

current_month = datetime.date.today().replace(day=1)
possible_month = datetime.datetime.strptime('%s %s' % (start_month, start_year), '%B %Y').date()
while possible_month <= current_month:
    csv_filename = possible_month.strftime('%B %Y') + '.csv'
    month = possible_month.strftime('%B %Y').split(" ")[0]
    year = possible_month.strftime('%B %Y').split(" ")[1]
    if os.path.exists("folder/" + csv_filename):
        print csv_filename
    possible_month = (possible_month + datetime.timedelta(days=31)).replace(day=1)

Obviously you can change that to however you feel fit, let me know if you need more or if this suffices.


text:
Q: Counterexample to show that the set of global minima of a function $f$ is a strict subset of the set of minima of the convex envelope of $f$ Let $f_C$ be the convex envelope of $f$ on a non-empty convex set $C \subset \mathbb{R}^n$
I need to show that $\{ x^∗ \in C : f(x^∗) \leq f(x), \forall x \in C \} \subset \{x^∗ \in C : f_C(x^∗) \leq f_C(x), \forall x \in C \}.$
Right now, I can show that: $\{ x^∗ \in C : f(x^∗) \leq f(x), \forall x \in C \} \subseteq \{x^∗ \in C : f_C(x^∗) \leq f_C(x) \forall x \in C\}$
However, I need a counterexample to show that the equality in the subset relation does not hold.
For reference: The convex envelope of $f$ on $C$, denoted $f_C : C \rightarrow R$ is a convex function such that $f_C(x) \leq f(x) \forall x \in C$. The definition also requires that if $g$ is any other convex function on $C$ for which $g(x) \leq f(x), \forall x \in C$ then $f_C(x) \geq g(x),  \forall x \in C$.
EDIT: Sorry for this, turns out that there was a typo and the $\subset$ should have actually been a $\subseteq$. After all, f could be a convex function in which case, it would be the same as it's convex hull.

A: Take the function $f(x)=x^2 (x-1)^2$ on $I=[-2,2]$, then the global minimum of f are $0,1$. If $f_C$ is its convex envelope, then you showed that 0,1 are global minimum for $f_C$ but then all the points in $[0,1]$ must be global minimum. (or in the general case, the global minimum of $f_C$ will contain the convex hull of the global minimum of $f$).

A: EDIT: Sorry for this, turns out that there was a typo and the ⊂ should have actually been a ⊆. After all, f could be a convex function in which case, it would be the same as it's convex hull.