How can I locate a wall from a crawl space?

Question: I am needing to add RG6 cabling to a bedroom that currently does not have an outlet.  I have no problem connecting the RG6 to the splitter outside my home, feeding into my crawlspace and running the length of the home.  The question I have is, once I reach the room I need to add the cabling to, how do I knew exactly where in the floor to drill up?
Meaning - I don't want to drill through the floor, I want it to be a wallfish (which I have experience doing but from coming down the wall from say an attic), so how can I locate exactly where to drill up in order to not go through the floor or the baseboard?
I also have an attic and a crawlspace, is there anyway that connects the crawlspace straight up to the attic that I could possibly run a cable up to the attic then wall fish down to a room up there as well?  Maybe somehow follow the chimney up, is that possible?
Comment: I've done this before - for rooms that have carpeting I use a long, thin nail and simply drive it into the floor. Then go into the crawl space where I can see the nail and thus know where to drill up into the wall space. For rooms that have hardwood or tile I've removed baseboards and drilled (with a thin drill bit) diagonally into the wall space going down. Then poke a wire through so I can see it from the crawl space - then drill a hole up into the wall space for cabling.
Answer:
Cut an opening in the wall for a low voltage box/bracket,and install the bracket.

Position a flexible drill bit into the hole, so that you'll drill straight through the bottom plate of the wall and into the crawlspace.

This is a poor image since the guy is not drilling straight down, but you get the idea.

Go into the crawlspace and attach the cable to the drill bit.
Pull the drill bit (and cable) up into the wall.
Make up the connections to a wall plate, and install the wall plate in the low voltage box/bracket.
Answer: Measure carefully. There are usually plenty of reference points... duct vents plumbing, etc.
Once you've done that, either drill a very small hole to feel for the wall's bottom plate, or run a long screw up through. An assistant on the floor above can help determine if you're off target and warn you.
If you have absolutely no reference points, drive a screw down from above in an inconspicuous location. Have an assistant tap it with a hammer to help you find it. Use it as a reference. If screwing through carpet, be very careful to prevent the carpet from grabbing the screw and zipping out a thread. You could remove a piece of base trim to create a hidden hole.
There's unlikely to be a clean passage from your crawl space to your attic through a wall. You'll probably have 3 wall plates in between, and possibly mid-wall blocking. If it was that easy, it wouldn't be called "fishing". :)
Comment: Well, if you're cutting holes in your wall you don't need a fancy tool and this entire question is moot. :)
Comment: The room I am wanting to run to, has only one interior wall with no electrical outlet or plumbing.  Which leaves me scratching my head on exactly how to conquer this.
Comment: Would something like this be a good resource to try as well, since no reference point?  (just go down instead of up as the pics show)  http://www.licensedelectrician.com/Store/RT/Bumper-Balls.htm
Comment: How would you get inside the wall to use that? If you're inside the wall you don't need a location.
Comment: Cut the rectangle in the wall where I would want the wall plate to go then drill down with this, so I already have a hole in my crawlspace and no "guessing"
Comment: I was originally trying to discover how to make sure that the hole drilled from crawlspace up lined up with hole cut in wall.  As I did not have an indicator to determine where to drill.
Comment: @user2676140: the magnetic / studfinder approach might be what you were initially looking for. If you are in a carpeted area though, isherwood's solution would be faster and w/ a small enough hole, there'd be no way for anyone else to see/know. ..and if someone _does_ find out... "it was always there" ;-)
Answer: I came up w/ a 'cool trick' (I think so, at least).  Get some of those strong, rectangular magnets..  Upstairs, on the edge of the wall, where you want the receptacle to be above, put the magnet on the floor and a heavy weight on it, so it won't move.  Then, take some measurements to help you figure out where it'll be, when trying to find it from the other side of the wall/floor/whatever.  Then, using one of those telescoping magnetic wands (the ones that're designed to help you pick up screws/nails/etc. from behind furniture or whatever) see if you can find where your first magnet is.
Realize:  using this method, you have really found the center of the magnet above - meaning you need to account for 1/2 the width of the magnet + the widths of any additional materials (such as baseboards, wallboards, tile, etc..)
Then you can drill a hole (starting small is always sage advice) and if you've done your measurements and locating correctly, the hole will be inside the wall, precisely where you want it to be.
Additional advice:  nails/screws/other-metallic-stuff will attract your magnetic wand (false positives).  If you think you found where the magnet is, put a dot or an 'X' w/ a sharpie or something and go flip the magnet upside down.  Now your magnetic wand should be repelled from the magnet upstairs.  If it's being repelled from the dot you made before, then it's a true positive.
Another note:  using this method, it's pretty easy to do a couple of sample spots/dots and use those and a straight-edge to make lines showing you where your walls are on the floor above, but letting you have a relatively precise diagram of where they are as you look up from underneath the floor.
Comment: I've done more or less this same thing with a few 75lb pull neodymium magnets and the compass in my phone.  Works like a charm even on floors that are 2 inches thick.
Comment: Interesting idea. Though I thought stud finders were capacitance based - not magnetic.. (I could be wrong though). That does make me think of another bit of advise for everyone. If you're drilling from the underside of a floor, hoping to get your hole inside the wall above, it's possible you'll be so "lucky" as to put your hole into the bottom of a stud - making the hole useless.. (not that I've ever done that.. :-p) when placing your 'upstairs' magnet, use a stud-finder or some other mechanism to avoid that scenario. As always: start small. poke a wire through it, see if its where you want it
Comment: That would have to be a seriously strong set of magnets.  The floors in my home are about an inch thick. And don't forget, that you could stick the wand near a nail and think it's the magnet.
Comment: @Matt  Well, sorta strong.  I've been able to use this w/ some run-o-the-mill magnets from a hobby shop and the magnetic wand through 1.25" thick 'floor' (subfloor + backer board + tile).  The trick is to try to 'balance' the magnetic wand between your thumb and index/middle fingers - then move it around the area you think the magnet is located (those rough measurements I mentioned). Since you're talking about 2 magnets trying to attract(or repel - nail scenario) each other, they don't need to be terribly strong. There's a little subtlety to the approach, but it's worked for me. Hope it helps.
Comment: Cool.  It makes sense and avoids drilling.  It also gives me another idea which is to use a stud finder and a piece of metal.
Answer: Here are some suggestions.  I've used all of these except the last one which I think would work pretty well.

Locate a power socket as my reference point.  You'll know it's there because you'll see the wires going up into the inside of the wall.

Position your outlet on the outer wall since the outer wall is always known.  Although, that might not be a good position for it in your room.

Drill a tiny hole from the edge of the wall through and poke a wire down through it.  Then go below and locate it.  The wall is right next to it.

Locate the piles, often piles are below walls.  They may give some clues.

Run the wire up through the inside a built in wardrobe to the ceiling space and then along and down through the wall.  You can drill these holes next to the wall inside the wardrobe and poke a piece of string or wire down to find it from below.
You can hide/protect the wire in the wardrobe with conduit.  Sometimes, this method is just easier, especially when you lack the tools or in my case I had to do this in an old church building and there was were areas I could not crawl to from below so had to transition the wire to above.

Carefully measure.  But this is hard to get right because you need to be sure you are measuring from the right position.  10cm out and my may miss the wall completely.

Another idea, put a strip of steel against the baseboard such as a rafter square and use a stud finder to try to locate that.  Since most detectors also sense steel it should find it quite easily.  Combined with option 6 above you should be able to locate the wall pretty easily.

Ok heres another option.  A compass and magnet.  See post by Matthias Wandel here
Answer: I've only seen this done, so ymmv, but take the long straight part of a coat hanger. Chuck it in the drill. Cut the other end at a slight angle with side cutters. Drill through in a subtle place. (Maybe between the base and the wall.) Once you're through, there should be enough length for you to landmark in the crawl space.
Cheaper than a flex bit!


50% off Dollar Bill Machine in Bioshock Infinite "Vending Empty"

Question: I'm in the Hall of Heroes and found a 50% off dollar bill vending machine. However the machine says "Vending Empty" when I walk up to it. Screenshot attached.

Anyone else run into this and know why it doesn't work?
Comment: If I ever find a dollar bill vending machine that's selling dollar bills at 50% off, it'll be empty pretty quickly.
Comment: I *think* it's supposed to be empty. It's been empty for me in all of my play throughs. =(
Comment: Well, considering that he's covered in what appears to be tar and that he looks quite damaged, I'd say he was assaulted by the Vox Populi and robbed blind. Well, he might have sold out beforehand though; who wouldn't jump at the occasion to buy some 50%-off ammo to defend against the Vox (except the Vox themselves, of course)?
Answer: When I played through this section, this machine had one or two items for sale. They weren't standard Dollar Bill items, but Minute Man's Armory items, i.e., weapon upgrades. Perhaps if you've already bought the upgrades somewhere else, there isn't anything available to sell you.
Answer: I ran into the exact same thing on my playthrough.  When I was on the return trip back through this area, it was selling a limited selection of items.
Answer: The 50% off is only for the Clip Increase for the pistol. If you already bought it before reaching the tear, it will be empty.


jsTree fails on second refresh

Question: I'm using a jsTree plugin and found that on the second time I call the refresh(), the tree will remain in an error / loading state.
Here is the code:
.on('changed.jstree', function (e, data) {
    var i, j, selectedNode;
    selectedNode = data.node;
    currentlySelectedNodeGUID = selectedNode.id;
    //for (i = 0, j = data.selected.length; i < j; i++) {
    //    selectedNode = data.instance.get_node(data.selected[i]);
    //    currentlySelectedNodeGUID = selectedNode.id;
    //}
    $.ajax({
        url: '@Url.Action("LocationProperties","Location")',
        type: 'GET',
        data: { id: currentlySelectedNodeGUID },
        success: function (result) {
            $('#locationPropertiesPartial').html(result);
        },
        error: function (e) {
            alert(e);
        }
    });
});

The only problem I found was that I get this error
Uncaught TypeError: Cannot read property 'id' of undefined
at this line currentlySelectedNodeGUID = selectedNode.id;.
The data however is there, the data.node does contain an id property and it does have a value, which gets assigned to currentlySelectedNodeGUID.
I'm pretty much clueless as to why this happens. Any help please?
Answer: When you call refresh() your currently selected node is deselected, which triggers the changed event. When there is no node selected data.node is null (or undefined). That's why data.node.id also is undefined. After the tree has been refreshed the node gets selected again, which triggers changed once again - this time with the node object available.
So you'll need to check if there actually is a node selected before you send that ajax query.
Answer: Evaluate whether data.node or data.selected is null before the assignment,
when the jstree is refreshed don't take error, and you can refresh any times you need.
if (data.node != null) {
   var dataid = data.node.id;
}

jsTree fails on second refresh


Populating an array row with unique values recursively - Sudoku Solver

Question: I am trying to create a sudoku solver using the Naive/Brute Force approach. I'm starting with solving the row then moving to solving the columns with the rows followed by each sub grid.
What I'm having trouble with is exiting my recursion once I have found the unique value needed for the row. Once I have found the value I need, when the function traverses back up the recursion, it takes the top recursive value instead of the value at the bottom of the recursion giving the incorrect value returned.
For example, if my row is this:
[0,5,4,0,0,3,0,0,8]
My function will populate as follows:
[1,5,4,0,0,3,0,0,8]
[1,5,4,2,0,3,0,0,8]
[1,5,4,2,2,3,0,0,8]
But as you see, the third iteration populates the value 2 twice, when it should be a 6. When I run in debug, I see that, before my function starts to traverse back up the recursion, it populates with a 6 but then the value is changed back to a 2 when the function finally exits.
Anyone know what I'm doing wrong here? Also, feel free to give me any tips or pointers on what I already have.
Here's my code:
def checkExists(board, row1, col1, value):
    if value in board[row1]:
        value = value + 1
        checkExists(board, row1, col1, value)
    board[row1][col1] = value

def solveSudoku(board):
    for row in range (0,9):
        print('Beginning Row: ', board[row])
        for col in range(0,9):
            if board[row][col] == 0:
                value = 1
                checkExists(board, row, col, value)
                print('New Row:       ', board[row])
                time.sleep(2)

EDIT:
Thanks to Ajay below for seeing my silly mistake. I needed the else statement in my recursive function.
Comment: `def checkExists(board, row1, col1, value):`. The function takes 4 parameters but you're passing 5 in `checkExists(board, row1, col1, value, count)`. If that's a typing mistake, please correct it.
Comment: I have fixed this issue. It should not have had the 5th parameter. I was attempting to count the recursions for testing.
Answer: The issue is that you're missing the else block in checkExists. If value is in current row, you increment value by 1 and recurse again but without the else block, 2 will be set as the value in row when you trace back in recursion.
def checkExists(board, row1, col1, value):
    if value in board[row1]:
        value = value + 1
        checkExists(board, row1, col1, value)
    else: # <<-- missing else
        board[row1][col1] = value

Comment: This worked correctly. I thought I had tried that, but I guess I did something wrong. Thanks so much, i've been racking my brain for an hour on this.


Does the pthread_cond_wait() unlock all the waiting mutexes, or just the waiting mutex? If so, why doesnt it unlock a mutex from the same thread?

Question: Does the pthread_cond_wait() unlock all the waiting mutexes, or just a specific mutex? If so, why doesn't it unlock a mutex from the same kind of thread?
What i mean is that in case the next waiting mutex comes from a different thread of the same function, why would the pthread_cond_wait() not unlock that one instead, but it unlocks the thread from where the signal will be broadcasted afterwards?
First time writing in stackoverflow so hope I was clear enough.
Answer:
Does the pthread_cond_wait() unlock all the waiting mutexes, or just a
specific mutex?

pthread_cond_wait() unlocks only the specific mutex passed to it.  Additionally, the calling thread must hold that mutex locked at the time of the call, and the same mutex must be used with the particular CV in all pthread_cond_wait()-family operations.  After being awakened, the calling thread will not return from the wait until it reacquires the mutex, so once it does return, it will hold all the same mutexes that it did at the time of the call.

If so, why doesn't it unlock a mutex from the same
kind of thread? What i mean is that in case the next waiting mutex
comes from a different thread of the same function, why would the
pthread_cond_wait() not unlock that one instead, but it unlocks the
thread from where the signal will be broadcasted afterwards?

Only one mutex can be used with any given CV, else undefined behavior results.  Since every thread waiting on that CV will present the same mutex, the question is moot -- there is no alternative mutex to consider unlocking.


Character counter should not display amount if amount is 1

Question: def encode(message):
    encoded_message = ""
    i = 0

    while (i <= len(message)-1):
        count = 1
        ch = message[i]
        j = i
        while (j < len(message)-1):
            if (message[j] == message[j+1]):
                count = count+1
                j = j+1
            else:
                break
        encoded_message=encoded_message+str(count)+ch
        i = j+1
    return encoded_message

#Provide different values for message and test your program
encoded_message=encode("ABBBBCCCCCCCCAB")
print(encoded_message)

This code generates the following output: 1A4B8C1A1B
But if the value is 1 it should just display the letter like this: A4B8CAB
Answer: Simply replace this line:
encoded_message=encoded_message+str(count)+ch

with this:
encoded_message += (str(count) if count > 1 else "") + ch

It should do the trick. Now it only appends the count to the string if said count is bigger than one.


Minimum Value of expression 2

Question: What is the minimum value of $$(2x+3y)(8/x + 3/y)$$ when $x$ and $y$ are positive?
I have tried expanding the equation but I did not get anything
I got :  $$25 + \frac{6(4y^2 +x^2)}{xy}$$ but I don't know how to answer after this.
I have also tried AM-GM but I couldn't manipulate the variables to cancel  out and get the inequality.
This is from Sipnayan 2017
Answer: You were on the right track:
$$\begin{align}(2x+3y)\left(\frac{8}{x} + \frac{3}{y}\right) &= 25+24 \frac{y}{x}+6\frac{x}{y}\\
&=25+12\left(\frac{2y}{x}+\frac{x}{2y}\right) \\
&\geq 25+12 \times 2 \\
&=49\end{align}$$
and notice that $x=2,y=1$ achieves this bound, so the minimum value is $49$.
The bound $\frac{2y}{x} + \frac{x}{2y} \geq 2$ can be proved from AM-GM, or from letting $t = \frac{2y}{x}$ and considering the function $f(t) = t + \frac{1}{t}$ and using calculus.
Answer: From where you have left of,
For real $x-2y,$
$$(x-2y)^2\ge0\implies x^2+4y^2\ge4xy$$
Alternatively, using AM-GM inequality, $$\dfrac{x^2+4y^2}2\ge\sqrt{4x^2y^2}=?$$
Answer: By C-S $$(2x+3y)\left(\frac{8}{x}+\frac{3}{y}\right)\geq\left(\sqrt{2x\cdot\frac{8}{x}}+\sqrt{3y\cdot\frac{3}{y}}\right)^2=49.$$
The equality occurs for $x=2$ and $y=1$, which says that we got a minimal value.
Done!

Minimum Value of expression 2


Why should I buy a car in Cyberpunk 2077?

Question: I get constant messages from fixers urging me to buy a car.
Yet I wonder: Why should and would I invest money in them? They are not cheap, and apparently, I can't customize them.

 And through  progressing the story within my Nomad playthrough, I unlocked two bikes and two cars very early and they all seem pretty decent.
 The Archer Hella EC-D I360 was shortly damaged but repaired early in the Delamain quest line. After Jackie's funeral I got his bike from his mother. As a Nomad, my old car got activated allowing me to buy it cheap for 100 Eurodollars from Lana. And during Panam's sidequest I got Scorpion's bike.

Is this merely a money sink to allow me to buy a fancy car for bragging rights?
Or are there some quests or races attached once I buy some of them?
Comment: FWIW, playing corpo, there's a point in the story where you lose your car and you cannot claim another to be called. You have to buy as far as I can tell.
Comment: @JeffMercado that event occurs regardless of backstory but you should get Jackie's bike around the same time. I suspect whether you get Jackie's bike might depend on whether you return him to Vik or not.
Comment: @kalina, ah crud, I didn't get the opportunity to. I had him wait for me when things went down. That would explain it.
Comment: @JeffMercado You should still get your starting car, the Archer Hella EC-D I360, back early in the Delamain quest line after you reported the damage.
Comment: @k0pernikus, ok, I have a quest going back to Delamain HQ which I haven't done yet, got sidetracked.
Answer: There is no benefit other than having an additional choice to ride around in Night City.
There is a car racing quest with Claire from Afterlife, but you can always choose to pick her ride instead, and in one of the races you are even forced to.
Comment: Car ownership **is** required for one achievement, though -- Autojock!
Answer: Many of the cars you can buy are better (faster, more durable, better handling) than the ones you get for free.
Every vehicle in Night City is a unique mix in its characteristics, and many are substantially more or less pleasant to drive than others. As for not being able to customize your ride... you're looking at this the wrong way. Buying a preem new set of wheels is how you customize your ride. No, there's no paint shop. But with literally dozens of rides to buy or find, you're sure to find one that suits your style.
Comment: Yeah there are definitely many vehicles that drive far better. Personal favourite is the Coyote.
Comment: I get your intent, still to say that "buying new is how you customize" is a weird phrasing.


AJAX.NET Subscribe to Reorderlist ItemCommand or DeleteCommand?

Question: I would like to subscribe to the ItemCommand event of a Reorderlist I have on my page.  The front end looks like this...
<cc1:ReorderList id="ReorderList1" runat="server" CssClass="Sortables" Width="400"  OnItemReorder="ReorderList1_ItemReorder" OnItemCommand="ReorderList1_ItemCommand">
...
<asp:ImageButton ID="btnDelete" runat="server" ImageUrl="delete.jpg" CommandName="delete" CssClass="playClip" />
...
</cc1:ReorderList>

in the back-end I have this on Page_Load
ReorderList1.ItemCommand += new EventHandler<AjaxControlToolkit.ReorderListCommandEventArgs>(ReorderList1_ItemCommand);

and this function defined
protected void ReorderList1_ItemCommand(object sender, AjaxControlToolkit.ReorderListCommandEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            if (e.CommandName == "delete")
            {
                //do something here that deletes the list item
            }
        }
    }

Despite my best efforts though, I can't seem to get this event to fire off.  How do you properly subscribe to this events in a ReorderList control?
Answer: this works:
<cc2:ReorderList ID="rlEvents" runat="server" AllowReorder="True" CssClass="reorderList"
        DataKeyField="EventId" DataSourceID="odsEvents" PostBackOnReorder="False"
        SortOrderField="EventOrder" OnDeleteCommand="rlEvents_DeleteCommand">
...
<asp:ImageButton ID="btnDeleteEvent" runat="server" CommandName="Delete" CommandArgument='<%# Eval("EventId") %>' ImageUrl="~/images/delete.gif" />
...
</cc2:ReorderList>

code behind:
protected void rlEvents_DeleteCommand(object sender, AjaxControlToolkit.ReorderListCommandEventArgs e)
{
   // delete the item
   // this will give you the DataKeyField for the current record -> int.Parse(e.CommandArgument.ToString());
   //rebind the ReorderList
}

Answer: Since your ImageButton's CommandName="delete" you should be hooking up to the DeleteCommand event instead of ItemCommand.


How to group close distant items by multiples of an integer

Question: My goal is to group the list below by multiples of 7 (ie 7,14,21)
mylist=[1,3,7,8,10,14,15,19,22]

Ideal result:[(1,3,7),(8,10,14),(15,19),(22)]
My attempt:
>>>groups=[]
>>> for x in itertools.groupby(mylist,lambda x: x<=range(7,49,7)):
             groups.append(x)
>>> groups
[(True, <itertools._grouper object at 0x0000000002EBC128>)]

Any ideas on how to arrive at the ideal result? Thanks.
Answer: You can use:
itertools.groupby(mylist, lambda x: (x - 1) // 7)

Your current attempt compares each item to the range object, not the values it produces. This makes no sense, and is a TypeError in Python 3.x.
To unpack the groupby object to a list of tuples:
list(map(lambda g: tuple(g[1]), itertools.groupby(...)))

Comment: thanks for the solution. However, I got the following result which is not the ideal thing i'm looking for:
Comment: @Tiger1 that *is* the correct result! I will edit my question to demonstrate unpacking this object.
Answer: jonrsharpe gives an excellent solution. This alternative is universal (not necessarily Python-specific) and correct for obvious reasons:
groups = []
l = [1,3,7,8,10,14,15,19,22]
a = 0
sublist = []
for item in l:
    if 7*a<item and item<=7*(a+1):
        sublist.append(item)
    else:
        groups.append(tuple(sublist))
        a = item/7
        sublist = [item]

if sublist:
    groups.append(tuple(sublist))

Comment: thanks for the solution, although its a bit lengthy.
Answer: I think this code help you:
if __name__ == '__main__':
    a = [1,3,7,8,10,14,15,19,22]
    b = []
    c = set()
    for i in a:
        x = i/7
        if i%7 == 0:
            x -= 1
        b.append(x)
        c.add(x)
    c = list(c)
    a.sort()
    res = []
    for i in c:
        res.append(b.count(i))
    count = 0
    for i in res:
        print a[count:count+i]
        count += i

Comment: This only works for the case where `a` is sorted (which may be adequate, but should be made clear), and will still just `print` the output! You could simplify - `c = set(b)`, for example, and look into [list comprehensions](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions)
Comment: No, it isn't - if the user inputs `[1, 3, 10, 6]` they may not expect `[(1, 3, 6), (10,)]` rather than `[(1, 3), (10,), (6,)]`. And `c = list(c)` has added nothing; my point was that you could build *just `b`* in the `for` loop (or with a list comp.) then easily create `c = set(b)` in one step.


Editing values in DataTable with sorting active sorts table on input

Question: This question is related to the following Bug Report: https://github.com/vuetifyjs/vuetify/issues/3468
I have a VDataTable with sortable column headers and various input elements (VTextField and VSelect).
Editing the input elements with sorting active on a specific column edits the model. This causes the table to re-order while typing (in the VTextField) or when selecting a different value (in the VSelect).
Ideally the table should only re-order once the appropriate column header is clicked. In other words, the table shouldn't automatically sort but only manually sort.
This Pen illustrates the issue. Make sure sorting on countries is selected when testing the behaviour with the VSelect
Comment: Were you ever able to fix this issue? Or is it still an open issue?
Comment: @SvenHakvoort It's still open unfortunately
Answer: I have come up with a hack to get around this behavior. See the following fiddle:
https://jsfiddle.net/Loh5kyzt/
To exercise the fiddle, click on of the check boxes. Then sort on the "Chkd" column. Then check a currently unchecked row input box. The rows won't move around again until you sort once again on a column.
The behavior was very annoying at first in my fiddle; I thought I had written a bug. I am cross posting my fiddle to the issue reported in Vue.
JS Code
Vue.component('data-row', {
  props: ['row', 'index', 'currentSortCol'],
  template: `

      <input type="checkbox" @click="$emit('checkee', $event.target.checked, index)"/>
      {{ row.a }}
      {{ row.b }}
      {{ row.c }}
      {{ row.d }}
      {{ row.e }}
      {{ row.chkd }}

  `,
});

Vue.component('head-row', {
  props: [],
  template: `

      Delete
      Col A
      Col B
      Col C
      Col D
      Col E
      Chkd

  `
})

new Vue({
  el: "#app",
  data: {
    coldata: [
      { "a": "Foo", "b": 2, "c": 3, "d": 4, "e": 5, "chkd": false},
      { "a": "Bar", "b": 3, "c": 4, "d": 5, "e": 1, "chkd": false },
      { "a": "Baz", "b": 4, "c": 5, "d": 1, "e": 2, "chkd": false },
      { "a": "Daz", "b": 5, "c": 1, "d": 2, "e": 3, "chkd": false }
    ],
    currentSortCol: "a",
    currentSortDir: 'asc',
    currentSortDict: {"a": "desc", "b": "desc", "c": "desc", "d": "desc", "e": "desc"},
    preventSort: false
  },
  methods: {
    sort: function(s) {
      if (this.preventSort) {
        this.preventSort = false;
      }
      //if (s === this.currentSortCol) {
        this.currentSortDict[s] = this.currentSortDict[s]==='asc'?'desc':'asc';
      //}
      this.currentSortCol = s;
      this.currentSortDir = this.currentSortDict[s]
    },
    checkee: function(cs, i) {
        //console.log("len args is " + arguments.length)
        if (this.currentSortCol == "chkd") {
          this.preventSort = true
        }
        else {
          this.preventSort = false
        }
        this.coldata[i].chkd = cs;
    }
  },
  computed: {
    sortedRows: function() {
      if (this.preventSort) {
        return this.coldata;
      }
      return this.coldata.sort((a,b) => {
        let modifier = 1;
        if(this.currentSortDir === "desc") modifier = -1;
        if(a[this.currentSortCol]  b[this.currentSortCol]) return 1 * modifier;
        return 0;
      });
    }
  },
});

HTML Code

foo

Data:

CSS Code
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

del {
  color: rgba(0, 0, 0, 0.3);
}

table {
  table-layout: fixed;
  width: 420px;
}

td, th {
  width: 60px;
  text-align: center;
  white-space: nowrap
}


How to recreate the keystore file if it got deleted accidentally

Question: I have an app which is signed and several keystore files. I'd like to update the app, so I need to find out which one of keys was used.

How to recreate the keystore file if it got deleted accidentally.

I have recovered it but I want to generate the keystore file again.

I know the user name & password also.

Simply my question is :
How to convert .RSA file to .JKS
Please Help
Comment: @Mij this it not at all funny, I am very sad. :-(
Comment: Any chances if any As `my old app have many users and good reviews.`
Comment: it's ipmossible to restore a keystore file after it has been deleted.
Comment: I won' t say that its **impossible** but It may be [very difficult](http://docs.oracle.com/javase/1.5.0/docs/tooldocs/solaris/keytool.html)  to do that, still if you have the `.RSA` file with you which you extracted it from signed apk of playstore. http://tordtech.blogspot.in/2009/10/signing-android-applications.html As this would be violation of google playstore security :(
Comment: If you lost keystore then , your playstore never allow to upadate your app with new keystore . It always conceder as a new application.
Comment: You can't. Lesson learned in a hard way, I also learn it in that way ;)
Answer: if you lost your keystore then it is gone forever, you can't do anything with that...
if you have your keystore (and log/pass, if not you may try bruteforce) then you can try sign your apk with every key and check fingerprint matches version from Google Play (you can "extract" APK installed on device). note that there is also possiblity of multi-signing APK, but Google Play allows only single one, so it's not for you...
Having only RSA signature (extracted from prev signed APK?) is not sufficient at all, it is only "public" part of keystore, which may be extracted by everyone. you need "private" part, which is stored in your keystore only.
keytool is tool for playing with keystores - generating keys, signing files, recovering "public" key etc. but in your case it will be useless probably. Just find this damn keystore... Good luck!
Comment: thanks for the quick reply, I have the `.RSA` file with me, any hope in that case?
Comment: have you checked [THIS](http://stackoverflow.com/questions/16562850/how-to-sign-android-application-with-rsa-key) topic? keystore is "sum" of private and public key. you can try to re-create/produce "new" public key from private key, but not private from public, obviusly (it wouldn't be so secure then)... Do your best and find this file, I'm affraid that this is your only hope... Good luck!
Comment: Can you edit the answer and post the steps you just told. thanks  I will accept that.


JavaScript encoding for potentially dangerous requests

Question: So, I've run up against the ubiquitous ASP.NET "potentially dangerous request" issue a few times now in different contexts. When using CKEditor, I've had pretty good success at defeating it by using the general suggestion to set the "htmlEncodeOutput" option to true. In other cases, I've used the other widely given suggestion of reverting page validation to the older version, which essentially tells the server to ignore HTML coming through. So, fine.
But what I've not been able to figure out is how to encode text on my own (and keep the validation in place). In a wild stab in the dark, I've tried the JavaScript escape() and encodeURI() functions, along with a small string.replace() function that turned brackets into > and <. None of these seemed to work. In the most recent wild stab, I encoded text server-size using "HttpUtility.HtmlEncode," shipped it off to a browser , and tried to send it back. Up popped the "potentially dangerous request." Arg.
Is there available any working samples of a JavaScript function that will do whatever magic the CKEditor "htmlEncodeOutput" function does? I'd sure appreciate any tips.
Answer: <code>function htmlEncode(s) {
  return s.replace(/&/g, '&').replace(/</g, '<')
      .replace(/>/g, '>').replace(/"/g, '&quot');
}
</code>
Comment: Thanks. That works on the test sample I'm using, and I'm going to use it. Still, I wonder about the weird instances I've read about -- like "ON." -- which is supposed to trigger the "potentially" dangerous error to help prevent SQL injection attacks.
Comment: @Brent, can you point me to the article where you read about that?  I'm not quite sure what you're referring to.
Comment: Hmmm...well, not an article, but more a thread where the poster was trying to figure out why he was getting the error:

http://forums.asp.net/t/1235144.aspx/1/10
Comment: @Brent, Sounds like the poster is using an anti-XSS filter that is trying to reject patterns like `onclick=javascript_goes_here`.  If you have such overly broad filters, `.replace(/=/g, '=')` will help address it.


Controlling single bulb through two switches

Question: My front porch overhead light fixture has two light bulbs, each of which has a positive and neutral lead. We have a two family house, and the porch is shared. Each of us has a switch in our house that turns on one of the two light bulbs. Each light bulb is on a different circuit. This works fine, but I need to replace the fixture.
Note, these are not three way switches to a single load. There are two circuits running to a fixture which has two sockets, each socket has a discrete positive and neutral.
I'd like to maintain the ability for us to control our lights individually, which would require a fixture with four leads (two per bulb). And I could just buy another, which would be fine.
But I am wondering if there is such thing as an "OR" switch that would turn on a single fixture/load if either (or both) of our switches are turned on, and only have it off if neither of our switches are on.
I could do this easily in the 12V DC world but this is 120V AC and an outdoor location so I don't want to hack this together.
Here is a picture of the current situation, after I removed the old fixture.
Comment: Does each household have its own electricity meter? If so then you can't "OR" them into one point to power a single load. RMSman's answer is probably the best way to go - just find a 2-bulb fixture you like the look of and decouple the bulb holders from each other.
Comment: Whats wrong with a two-way switching circuit so either can turn both of them on or off.
Comment: @RohitGupta it's not the behavior I want but more precisely, I don't want to touch the existing switches in each unit, it would be a big pain.
Comment: @brhans yes, and thank you for pointing that out.
Answer: Almost any fixture with a 2 bulb setup will have hot and neutral from each bulb tied together to a single pigtail for the hot and neutrals, and a ground for the body of the fixture.   You will simply need to remove the pigtails and you will have your separate hot and neutrals for each bulb.
Answer:
My front porch overhead light fixture has two light bulbs, each of which has a positive and neutral lead.

There's no positive.  It's AC power.
I gather you have familiarity with 12 volt DC stuff from automotive electrical and the like, and you're going "well I can merge these with a diode!" No you can't.
By the way, neutral is not ground and it is not "common"/chassis.  Houses are wired as an "isolated system" with all neutrals being run with their partner hot/live wires.  The neutral must serve ONLY its partner hot/live because neutrals don't have fuses.  What keeps a neutral from overloading? Nothing, expect that neutral current can't exceed hot/live current when everything is properly wired.
Properly wire.

We have a two family house, and the porch is shared. Each of us has a switch in our house that turns on one of the two light bulbs. Each light bulb is on a different circuit.

OK, that's a standard setup with multi-unit properties.  Each light bulb in the fixture is fed from a different light switch inside the tenant unit, and powered by the tenant's electrical service that they pay for.   That way you avoid a) tenant 1 paying for tenant 2's leaving the light on, and b) having a separate meter and billing just for commons loads, as is required in the USA.

This works fine, but I need to replace the fixture.

Well. That's tricky. You need to get a fixture which supports that feature.
If you think you're going to go "tra la la" through the furniture store or Amazon and go "that one" solely on aesthetics, afraid not. Finding the "separate bulbs" feature will be paramount.

But I am wondering if there is such thing as an "OR" switch that would turn on a single fixture/load if either (or both) of our switches are turned on, and only have it off if neither of our switches are on.

Like a diode if this were 12 volt wiring in a vehicle?   No.  You have two big problems.
First, what do you do about neutral? If you use one tenant's neutral then when the other tenant switches on the light, current is returning on the wrong neutral.   If you connect both neutrals, you have a neutral loop.  Suppose one flat has a problem with their neutral connection at the utility pole.  Now the whole flat's neutral current will path through your little tie-in at the light! And that wire is not rated for that, and again, it's not fused.
Second, who pays? Even if you have tenant 2's light power a 12 volt transformer that picks up a relay inside tenant 1's switch box, now tenant 1 is paying all the power and that's not fair.
I suppose you could have tenant 1's switch be DPDT and switch both hot and neutral, when tenant 1's switch is off it connects the light to tenant 2's switch.  That's the only legal option I can see.
Note that if tenant 2 is supplied a different phase of power, there will be 400 volts between tenant 1 and tenant 2's line/hot.  The switch will need to be rated for that.

I could do this easily in the 12V DC world but this is 120V AC and an outdoor location so I don't want to hack this together

Well, there's an option. Have each tenant's switch feed a 12 volt power supply (so two 12 volt power supplies).  Getting 12 volt fixtures is not a problem, look at RV lighting.
But other than that, everything you learned about low voltage DC is wrong about mains AC.  AC is complicated and all the wiring practices are different.
Comment: "AC is complicated" for me, it was like another world when I started to learn about it!
Comment: Good points. I'm going to go with a two bulb fixture and keep things as they are. For the "who pays" option, in our case it's not a problem because it's family in both units, no one will care who pays for an LED light bulb, but if we sell the house, it wouldn't be an ideal setup for the next owner and might be downright confusing.


Package com.google.api.client.extensions.android.http does not exist

Question: I'll go direct to point. While I'm try to run the app I got some errors
package com.google.api.client.extensions.android.http does not exist

package com.google.api.client.extensions.android.json does not exist

package io.reactivex does not exist

build.gradle file
dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.facebook.android:facebook-android-sdk:4.16.0'
    compile 'com.pkmmte.view:circularimageview:1.1'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.github.yalantis:ucrop:2.2.1'
    compile 'com.android.support:design:23.3.0'
    compile 'com.google.android.gms:play-services-gcm:11.0.4'
    compile 'com.writingminds:FFmpegAndroid:0.3.2'
    compile 'com.google.apis:google-api-services-youtube:v3-rev186-1.23.0'
    compile group: 'com.google.oauth-client', name: 'google-oauth-client-java6', version: '1.23.0'
    compile group: 'com.google.oauth-client', name: 'google-oauth-client-jetty', version: '1.23.0'
    compile 'com.github.PierfrancescoSoffritti:AndroidYouTubePlayer:4.1.7'
    //compile "android.arch.lifecycle:runtime:1.0.0-alpha2"
    //compile "android.arch.lifecycle:extensions:1.0.0-alpha2"
    compile 'com.google.code.gson:gson:2.8.2'
    compile 'com.netflix.rxjava:rxjava-android:0.16.1'
    compile 'com.google.api-client:google-api-client:1.23.0'
    implementation "android.arch.lifecycle:livedata:1.1.1"
    implementation "android.arch.lifecycle:viewmodel:1.1.1"
    implementation "android.arch.lifecycle:extensions:1.1.1"
    compile files('libs/YouTubeAndroidPlayerApi.jar')
    testCompile 'junit:junit:4.12'
}

Do I need to compile some library in the build.gradle? Let me know and thank's to all!
Comment: Yes i'm using rxjava
Comment: Are you using rxjava?
Answer: Try :
compile 'io.reactivex:rxjava:1.0.10'
compile 'com.google.api-client:google-api-client:1.23.0'

OR
compile 'com.netflix.rxjava:rxjava-android:0.16.1'
compile 'com.google.api-client:google-api-client:1.23.0'

EDIT
compile group: 'com.google.api-client', name: 'google-api-client', version: '1.22.0'
compile group: 'com.google.api-client', name: 'google-api-client-android', version: '1.22.0'

Comment: Ty for help me with the last i've solved the rxjava dependencies but i still got error
Comment: package com.google.api.client.extensions.android.http does not exist

package com.google.api.client.extensions.android.json does not exist
Comment: @Trusted Happy to help :) happy coding :)
Comment: @Trusted Thanks :)
Answer: compile group: 'com.google.http-client', name: 'google-http-client-android', version: '1.12.0-beta'

Click here!
Select gradle.


Why don't the Sequelize migrations work properly with schemas other than public?

Question: I'm using the Sequelize CLI to perform migrations, and it doesn't seem to play nice with schemas, outside of "public". I ran a series of tests, and it appears that even when I provide the schema in the "options" of the Sequelize command, it only works on some and not others.
For example, I can create a table on the "up" portion and it ends up in the proper schema, but fails on the "down" because it can't find the table in public:
module.exports = {
    up: (queryInterface, Sequelize) => {
        return queryInterface.createTable("migration_test", {
            name: Sequelize.DataTypes.STRING,
            isBetaMember: {
                type: Sequelize.DataTypes.BOOLEAN,
                defaultValue: false,
                allowNull: false
            }
        }, {
            schema: "profile"
        });
    },
    down: (queryInterface, Sequelize) => {
        return queryInterface.dropTable("migration_test", {
            schema: "profile"
        });
    }
};

The table is created correctly:

Executing (default): CREATE TABLE IF NOT EXISTS
"profile"."migration_test" ("name" VARCHAR(255), "isBetaMember"
BOOLEAN NOT NULL DEFAULT false);

However, on "down":

Executing (default): DROP TABLE IF EXISTS "migration_test";

The table obviously isn't deleted, so not super useful. The SequelizeMeta table ends up in "public" schema, which I can live with, if I have to.
I tried addColumn as well, and the "schema" attribute isn't even recognized:
module.exports = {
    up: (queryInterface, Sequelize) => {
        return queryInterface.addColumn(
            "migration_test",
            "test_column_1",
            Sequelize.STRING(100), {
                schema: "profile"
            }
        );
    },
    down: (queryInterface, Sequelize) => {
        return queryInterface.removeColumn("migration_test", "test_column_1", {
            schema: "profile"
        });
    }
};

...throws an error:

Executing (default): ALTER TABLE "public"."migration_test" ADD COLUMN
"test_column_1" VARCHAR(100);
ERROR: relation "public.migration_test" does not exist

Am I doing something wrong, or is this just the state of things? It seems inconceivable that this wasn't built to handle pg schemas? Am I better off using something like db-migrate or just writing one-off SQL scripts for db changes, than using this framework?
Answer: It's better to indicate a schema explicitly if it's other than public:
const table = { schema: SchemaName, tableName: TableName };

module.exports = {
    up: (queryInterface: QueryInterface): Promise<void> => queryInterface.sequelize.transaction(
        async (transaction) => {
            await queryInterface.createTable(table, attributes, { transaction });
        }
    ),

    down: (queryInterface: QueryInterface): Promise<void> => queryInterface.sequelize.transaction(
        async (transaction) => {
            await queryInterface.dropTable(table as any, { transaction });
        }
    )

Comment: Yes, thanks! This is correct. I found it on another Stack post and it works wonderfully. Wish the official documentation was better!


Hibernate exception on Joining two tables

Question: DB Tables:
student (
   stud_id int primary key,
   stud_name varchar(10)
);

product (
   product_id int primary key,
   product_name varchar(10),
   product_price int
);

user (
   stud_id int,
   product_id int,
   foreign key(product_id) references product(product_id),
   foreign key(stud_id) references student(stud_id)
);

SQL Query I am running:
select s.stud_name, result.tot_exp
from student s
inner join (
   select u.stud_id sid, sum(product_price) tot_exp
   from product p
   inner join user u on u.product_id = p.product_id
   group by u.stud_id order by tot_exp desc
) result on s.stud_id = result.sid
order by result.tot_exp desc;

Entity Class:
class Product {

   @Id
   int product_id;
   String product_name;
   int product_price;

   @ManyToOne() //not accepting cascade
   @JoinTable(name="user",
      joinColumns= { @JoinColumn(name="stud_id") },
      inverseJoinColumns= { @JoinColumn(name = "product_id") }
   )
   Student s;

   // ...
}

class Student {

   @Id
   int stud_id;
   String stud_name;

   @OneToMany//(cascade = CascadeType.ALL)
    //      @JoinTable(name="user",
    //                 joinColumns= { @JoinColumn(name="stud_id") },
    //                 inverseJoinColumns= { @JoinColumn(name = "product_id") }
    //                )
    //      //Initially join-table was here
    List<Product> products;

    // ...
}

Now my question is if I mention @JoinTable in the Product class then I am getting  exceptions but surprisingly getting correct result while executing select query but getting wrong while inserting new values to Student class.
And if I mention @JoinTable is the Student class I am not getting any error and getting result as expected. Also no issues if I insert new Student in the table.
Can anyone elucidate what's actually going on? Is it wrong to declare @JoinTable in the Product class?  Please help.
Exception:
  Hibernate: alter table Student_Product drop index UK_f28mdtx7chxxfked98qbllv2j
    Hibernate: alter table Student_Product add constraint UK_f28mdtx7chxxfked98qbllv2j unique (products_product_id)
    Hibernate: alter table Student_Product add constraint FKad7avlyg2mjh9nhnh3u64yacd foreign key (products_product_id) references Product (product_id)
    Hibernate: alter table Student_Product add constraint FKkkdpc75v3wtdvoq2087lt5rjn foreign key (Student_stud_id) references Student (stud_id)
    Apr 28, 2021 11:07:45 PM org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl handleException
    WARN: GenerationTarget encountered exception accepting command : Error executing DDL "Apr 28, 2021 11:07:43 PM org.hibernate.Version logVersion
    INFO: HHH000412: Hibernate ORM core version 5.4.27.Final
    Apr 28, 2021 11:07:44 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
    INFO: HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
    Apr 28, 2021 11:07:44 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
    WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
    Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
    Apr 28, 2021 11:07:44 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
    INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/fst]
    Apr 28, 2021 11:07:44 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
    INFO: HHH10001001: Connection properties: {password=****, user=root}
    Apr 28, 2021 11:07:44 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
    INFO: HHH10001003: Autocommit mode: false
    Apr 28, 2021 11:07:44 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
    INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
    Apr 28, 2021 11:07:44 PM org.hibernate.dialect.Dialect <init>
    INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
    Apr 28, 2021 11:07:45 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
    INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@daf22f0] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
    Hibernate: create table Student_Product (Student_stud_id integer not null, products_product_id integer not null) type=MyISAM
    Apr 28, 2021 11:07:45 PM org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl handleException
    WARN: GenerationTarget encountered exception accepting command : Error executing DDL "create table Student_Product (Student_stud_id integer not null, products_product_id integer not null) type=MyISAM" via JDBC Statement
    org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "create table Student_Product (Student_stud_id integer not null, products_product_id integer not null) type=MyISAM" via JDBC Statement
        at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67)
        at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlString(AbstractSchemaMigrator.java:559)
        at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlStrings(AbstractSchemaMigrator.java:504)
        at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.createTable(AbstractSchemaMigrator.java:277)
        at org.hibernate.tool.schema.internal.GroupedSchemaMigratorImpl.performTablesMigration(GroupedSchemaMigratorImpl.java:71)
        at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.performMigration(AbstractSchemaMigrator.java:207)
        at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:114)
        at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:184)
        at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:73)
        at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:316)
        at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:469)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
        at hibernate.retry.hibernate.App.main(App.java:30)
    Caused by: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'type=MyISAM' at line 1
        at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
        at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
        at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
        at com.mysql.cj.jdbc.StatementImpl.executeInternal(StatementImpl.java:764)
        at com.mysql.cj.jdbc.StatementImpl.execute(StatementImpl.java:648)
        at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54)
        ... 13 more

    Hibernate: alter table Student_Product drop index UK_f28mdtx7chxxfked98qbllv2j
    Hibernate: alter table Student_Product add constraint UK_f28mdtx7chxxfked98qbllv2j unique (products_product_id)
    Hibernate: alter table Student_Product add constraint FKad7avlyg2mjh9nhnh3u64yacd foreign key (products_product_id) references Product (product_id)
    Hibernate: alter table Student_Product add constraint FKkkdpc75v3wtdvoq2087lt5rjn foreign key (Student_stud_id) references Student (stud_id)
    Apr 28, 2021 11:07:45 PM org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl handleException
    WARN: GenerationTarget encountered exception accepting command : Error executing DDL "alter table Student_Product add constraint FKad7avlyg2mjh9nhnh3u64yacd foreign key (products_product_id) references Product (product_id)" via JDBC Statement
    org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "alter table Student_Product add constraint FKad7avlyg2mjh9nhnh3u64yacd foreign key (products_product_id) references Product (product_id)" via JDBC Statement
        at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67)
        at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlString(AbstractSchemaMigrator.java:559)
        at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlStrings(AbstractSchemaMigrator.java:504)
        at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applyForeignKeys(AbstractSchemaMigrator.java:433)
        at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.performMigration(AbstractSchemaMigrator.java:249)
        at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:114)
        at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:184)
        at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:73)
        at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:316)
        at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:469)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
        at hibernate.retry.hibernate.App.main(App.java:30)
    Caused by: java.sql.SQLSyntaxErrorException: Table 'fst.student_product' doesn't exist
        at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
        at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
        at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
        at com.mysql.cj.jdbc.StatementImpl.executeInternal(StatementImpl.java:764)
        at com.mysql.cj.jdbc.StatementImpl.execute(StatementImpl.java:648)
        at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54)
        ... 12 more

    Apr 28, 2021 11:07:45 PM org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl handleException
    WARN: GenerationTarget encountered exception accepting command : Error executing DDL "alter table Student_Product add constraint FKkkdpc75v3wtdvoq2087lt5rjn foreign key (Student_stud_id) references Student (stud_id)" via JDBC Statement
    org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "alter table Student_Product add constraint FKkkdpc75v3wtdvoq2087lt5rjn foreign key (Student_stud_id) references Student (stud_id)" via JDBC Statement
        at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67)
        at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlString(AbstractSchemaMigrator.java:559)
        at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlStrings(AbstractSchemaMigrator.java:504)
        at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applyForeignKeys(AbstractSchemaMigrator.java:433)
        at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.performMigration(AbstractSchemaMigrator.java:249)
        at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:114)
        at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:184)
        at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:73)
        at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:316)
        at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:469)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
        at hibernate.retry.hibernate.App.main(App.java:30)
    Caused by: java.sql.SQLSyntaxErrorException: Table 'fst.student_product' doesn't exist
        at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
        at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
        at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
        at com.mysql.cj.jdbc.StatementImpl.executeInternal(StatementImpl.java:764)
        at com.mysql.cj.jdbc.StatementImpl.execute(StatementImpl.java:648)
        at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54)
        ... 12 more

    Hibernate: alter table user add constraint FKhfswe0v9qoihn3j6e8lxgdkj4 foreign key (stud_id) references Product (product_id)
    Apr 28, 2021 11:07:45 PM org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl handleException
    WARN: GenerationTarget encountered exception accepting command : Error executing DDL "alter table user add constraint FKhfswe0v9qoihn3j6e8lxgdkj4 foreign key (stud_id) references Product (product_id)" via JDBC Statement
    org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "alter table user add constraint FKhfswe0v9qoihn3j6e8lxgdkj4 foreign key (stud_id) references Product (product_id)" via JDBC Statement
        at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67)
        at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlString(AbstractSchemaMigrator.java:559)
        at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlStrings(AbstractSchemaMigrator.java:504)
        at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applyForeignKeys(AbstractSchemaMigrator.java:433)
        at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.performMigration(AbstractSchemaMigrator.java:249)
        at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:114)
        at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:184)
        at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:73)
        at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:316)
        at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:469)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
        at hibernate.retry.hibernate.App.main(App.java:30)
    Caused by: java.sql.SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`fst`.`#sql-1aa8_b7`, CONSTRAINT `FKhfswe0v9qoihn3j6e8lxgdkj4` FOREIGN KEY (`stud_id`) REFERENCES `product` (`product_id`))
        at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:117)
        at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
        at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
        at com.mysql.cj.jdbc.StatementImpl.executeInternal(StatementImpl.java:764)
        at com.mysql.cj.jdbc.StatementImpl.execute(StatementImpl.java:648)
        at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54)
        ... 12 more

    Hibernate: select s.stud_name,result.tot_exp from student s inner join
    (select u.stud_id sid, SUM(product_price) tot_exp from product p inner join user u on u.product_id=p.product_id group by u.stud_id order by tot_exp desc) result
    on s.stud_id=result.sid order by result.tot_exp desc
    Name :Austin Spending:14000
    Name :Jason Spending:9000
    Name :Kendall Spending:3500
    Name :Ramsey Spending:3000
    Name :Jeremy Spending:1500

Hibernate Config File:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>

    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">123</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/fst</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.default_schema">fst</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hbm2ddl.auto">update</property>
        <property name="show_sql">true</property>

        <property name="hibernate.current_session_context_class">thread</property>
        <mapping class="hibernate.retry.hibernate.Student"/>
        <mapping class="hibernate.retry.hibernate.Product"/>
    </session-factory>
</hibernate-configuration>

Answer: The @JoinTable annotation should be used only on the owning side of the association, the other one being referred to as the inverse (or the mappedBy) side.
The correct mapping for your case should be like below:
@Entity
class Product {

   // ...

   @ManyToOne
   @JoinTable(name="user",
      joinColumns= @JoinColumn(name="stud_id"),
      inverseJoinColumns = @JoinColumn(name = "product_id")
   )
   Student s;

   // ...
}

@Entity
class Student {

   @OneToMany(mappedBy = "s")
   List<Product> products;
}

P.S. Usually join table is used for modeling @ManyToMany association. A common case of the bidirectional @OneToMany association is required only one foreign key on  the owning side.
Comment: How are you deciding the "owning side of the association" ? In the  inner select query I used product id as a key to get result but in the outer select query I used student id...so who is the owing side?
Comment: I am still getting same error...only getting exception-free result if I put it in Student class rather than Product class
Comment: `How are you deciding the "owning side of the association"` - for your case it can be any one. Could you please show also your hibernate config.
Comment: I have added the cfg file and also added a question -: "if I mention #JoinTable in the Product class then I am getting exceptions but surprisingly getting correct result while executing select query but getting wrong while inserting new values to Student class.

And if I mention #JoinTable is the Student class I am not getting any error and getting result as expected. Also no issues if I insert new Student in the table"
Comment: What mysql version do you use?
Comment: As you specify database name in the jdbc [connection url](https://dev.mysql.com/doc/connector-j/8.0/en/connector-j-reference-jdbc-url-format.html) , I guess you can remove this : `fst`
Comment: MySQL 8.x.x I am removing that property
Comment: You should use `org.hibernate.dialect.MySQL8Dialect` for MySQL 8.x.x
Comment: Does these thing any how related to my question? Is it throwing exceptions due this configuration mistakes?
Comment: As I see from your stack trace `java.sql.SQLSyntaxErrorException: Table 'fst.student_product' doesn't exist` , so this is quite probable
Comment: But if I add #JoinTable in Student class why it is not throwing this exception?


Should we have a 'popular-psychology' tag?

Question: We get a fair few questions from people about what is often called 'popular psychology'. E.g., questions about the MBTI, some questions grounded in self-help books, or other popular psychology books.

Would it be useful to have a tag for 'popular-psychology'?
What would be its scope?

For example, I was thinking of adding it to this question:
Are there any personality theories that use the scientific method?
Comment: It's a meta-tag anyway, isn't it? Id addition to Artem's points
Comment: Yes, I guess so; to some extent.
Answer:
I think most of the popular psychology questions detract significantly from the site, thus I am skeptical of having a tag for them.
A lot of the questions that I can imagine in pop-psych are of the demything or "does real research support this" type. These are not a good fit for a scientific site, we already have Skeptics.SE for questions like this.
I think a number of the regular users (myself, for sure) will use/view the tag in a derogatory way and thus it can suffer from many of the shortcomings and controversy that the homework tag faced on exchanges like CS, Physics, Stats, and Math.
I don't think popular-psychology is really all that well defined. Tagging will be difficult, and for me it will mostly be a 'bad question' tag.
Comment: I think they are some good arguments for not having the tag. The only comment I'd make is that I'm happy to have demything type questions on this site if they relate to psychology or cognitive science. But I agree with your arguments for not needing a specific tag.


Converting the solr response (solrdocumentlist) to json (or xml)

Question: I am working on a search in which I am trying to convert the response from a HttpSolrServer to json format.  The response comes as a SolrDocumentList.  The code I have right now is:
SolrQuery solrQuery = new SolrQuery(query);
solrQuery.setParam("wt", "json");  //doesn't affect the return format

QueryResponse rsp = solrServer.query(solrQuery);
SolrDocumentList docs = rsp.getResults();

return docs.toString();

When I print out the return, it comes back as:
{numFound=2,start=0,docs=[SolrDocument{cat=[electronics, camera], features=[3x zoop, 7.1 megapixel Digital ELPH, movie clips up to 640x480 @30 fps, 2.0" TFT LCD, 118,000 pixels, built in flash, red-eye reduction], id=9885A004, inStock=true, includes=32MB SD card, USB cable, AV cable, battery, manu=Canon Inc., manufacturedate_dt=Mon Feb 13 10:26:37 EST 2006, name=Canon PowerShot SD500, popularity=7, price=329.95, store=45.17614,-93.87341, weight=6.4}, SolrDocument{cat=[electronics, multifunction printer, printer, scanner, copier], features=[Multifunction ink-jet color photo printer, Flatbed scanner, optical scan resolution of 1,200 x 2,400 dpi, 2.5" color LCD preview screen, Duplex Copying, Printing speed up to 29ppm black, 19ppm color, Hi-Speed USB, memory card: CompactFlash, Micro Drive, SmartMedia, Memory Stick, Memory Stick Pro, SD Card, and MultiMediaCard], id=0579B002, inStock=true, manu=Canon Inc., name=Canon PIXMA MP500 All-In-One Photo Printer, popularity=6, price=179.99, store=45.17614,-93.87341, weight=352.0}]}}

for a search on canon using their example data.
If I instead do return rsp.toString(); I get back the header information with it as:
{responseHeader={status=0,QTime=1,params={indent=true,q=canon\*,wt=xml,version=2.2}},response={numFound=2,start=0,docs=[SolrDocument{cat=[electronics, camera], features=[3x zoop, 7.1 megapixel Digital ELPH, movie clips up to 640x480 @30 fps, 2.0" TFT LCD, 118,000 pixels, built in flash, red-eye reduction], id=9885A004, inStock=true, includes=32MB SD card, USB cable, AV cable, battery, manu=Canon Inc., manufacturedate_dt=Mon Feb 13 10:26:37 EST 2006, name=Canon PowerShot SD500, popularity=7, price=329.95, store=45.17614,-93.87341, weight=6.4}, SolrDocument{cat=[electronics, multifunction printer, printer, scanner, copier], features=[Multifunction ink-jet color photo printer, Flatbed scanner, optical scan resolution of 1,200 x 2,400 dpi, 2.5" color LCD preview screen, Duplex Copying, Printing speed up to 29ppm black, 19ppm color, Hi-Speed USB, memory card: CompactFlash, Micro Drive, SmartMedia, Memory Stick, Memory Stick Pro, SD Card, and MultiMediaCard], id=0579B002, inStock=true, manu=Canon Inc., name=Canon PIXMA MP500 All-In-One Photo Printer, popularity=6, price=179.99, store=45.17614,-93.87341, weight=352.0}]}}

I know that with HttpSolrServer the response format can only currently be of xml or javabin (which I have set to xml).  This seems to have no impact on the actual returned results and their format.
I cannot seem to find anything about converting the response to a json.  Any ideas?
Answer: For what you are attempting to do, you do not need to use solrj library.  You can use CommonsHTTPClient to send query parameters over HTTP directly AND set 'wt=json' - to retrieve the response in JSON.
Answer: Well although it is an old question, I have come up with a similar issue and after digging the code, i was able to convert the response into json, although i am still sceptical about the speed and performance of the code in case there are too many reqs are coming..
so below is the piece of code that I wrote(I used the JSON lib from Jettison and ignore the stupid structure of the for loop):
QueryResponse qp = server.query(solrQuery);
SolrDocumentList docList= qp.getResults();
JSONObject returnResults = new JSONObject();
Map<Integer, Object> solrDocMap = new HashMap<Integer, Object>();
int counter = 1;
for(Map singleDoc : docList)
{
  solrDocMap.put(counter, new JSONObject(singleDoc));
  counter++;
}
returnResults.put("docs", solrDocMap);

basically this will let you get results in json... solrj doesnt let you use any kind other than javabin although you may set wt in the query explicitly
hope it helps
Answer: The following code works
SolrDocumentList list =  new SolrDocumentList();
JSONArray jArray =new JSONArray();
QueryResponse result = solr.query(parameters);
list=result.getResults();

for (int i = 0; i < list.size(); i++) {
     JSONObject json = new JSONObject(list.get(i));
     jArray.put(json);
}

Also add the parameter json.nl=map.
Source: http://wiki.apache.org/solr/SolJSON
Answer: Import Gson and use its utility methods.
Comment: Please eloborate. I don't think that's a way to go.


Leveling drywall patch

Question: Due to a problem with my furnace, I recently had a lot of moisture get behind a wall and of course, mold to follow. All said and done I will need roughly 3 4x8 sheets to replace the damaged drywall.
My problem is they appear to have used 2 3/8" sheets stacked on one another, making it 3/4" total. All I can find around here is 5/8" boards. So, I need to make up a 1/16" difference. My friend suggested just mudding out the difference, but there is some large, older molding on the ceiling that i need to marry up to that makes that seem really difficult.
My thought was corrugated cardboard. But I saw this post and it didn't give a sure answer on whether or not that would be ok.
It mentions the cardboard giving too much and cracking the joints right away, but as I see it, the cardboard is thicker than what I need, so once it is compressed, it's not going anywhere. Any thoughts on what I should do?
Comment: Since you'll be taking the molding down to replace the drywall, doesn't it just make sense to re-trim the room and cope as needed?
Comment: FYI, your math is a little off.  3/4 - 5/8 = 1/8, not 1/16
Answer: Why not use standard 1/2" drywall after you shim out the studs. Use 1/4" stock or rip 1 1/2" strips of 1/4" plywood. Tack these to each stud. Then screw the 1/2" drywall through the shims and into the studs. I would probably use 1 5/8" drywall screws for a better grip.
By the way, if this is in or near a furnace room, be sure to use fire rated drywall.
Comment: Great suggestion. Beat me to it.
Comment: +1 I like this suggestion if the 1/2" is used. If 5/8" type X is used, then I think you're looking at a lot of mud instead of attempting a 1/16" shim.
Comment: You could also do the 1/2" drywall & 1/4" drywall to make the 3/4" needed. Then really nothing would change. You'll just have to be careful that the end bevels don't match up since that would be good cracking/bending opportunities.
Comment: I think this sounds like the best way to go. Thanks for your time.
Answer: You may want the type X 5/8" drywall with the furnace there (may not be required but it won't hurt). When you use a large mudding knife, the 1/16" over a 8-12" span will be difficult to impossible to detect. If you can pull the ceiling moulding without damaging it, I'd do that first. Replace the drywall behind the moulding, mud and tape the entire patch area, prime the wall, reinstall the moulding, and paint.
Comment: Sorry, I worded that poorly. The furnace is in the room below, the exhaust was running up through the wall, out the chimney, causing condensation. Got a new high eff. furnace that exhausts directly through the basement wall now.
Comment: In that case, I like blb's suggestion best. Shim out the wall 1/4" strips of wood and install 1/2" drywall over top. It will have the best resulting appearance.
Answer: They make 1/16" Drywall shims, you can find them at home depot, Drywall suppliers have 1/8" drywall shims. They are made of cardboard, and do the job nicely.

Leveling drywall patch


transformation $y = u v$ transforms the differential equation

Question: I f a transformation $y = u v$ transforms the given differential equation
$$f(x) y'' - 4 f'(x) y'+ g(x) y = 0 $$ into the equation of the form
$$v'' + h(x) v = 0 $$ then $u$ must be

$ \frac{1}{f^2}  $
$xf $
$ \frac{1}{2f}  $
$f^2$

I am stuck on this problem. Can anyone help me please...............
Answer: take $y=uv$ we have
$$y'=u'v+v'u$$
and
$$y''=u''v+2u'v'+uv''$$
replace in equation we have
$$(f(x)u''-4f'(x)u')v+f(x)uv''+(f(x)2u'-4f'(x)u)v'=0$$
Then if we want get the equation
$$v''+h(x)v=0$$
we can assume that
$$f(x)2u'-4f'(x)u=0$$
solving this simple equaton to u
we have
$u=e^{2lnf}=f^2$,
and we get the equation desired,
$$v''+h(x)v=0$$,
where $h(x)=\frac{f(x)u''-4f'(x)u'}{f(x)u}$


Inverting holomorphisms: beyond a small neighbourhood?

Question: Obviously, if $f(z)$ is holomorphic on an open connected set $D$ and $f'(z)$ never vanishes, then around each point in $D$, we can find a neighbourhood in which $f(z)$ is invertible.
But what general conditions ensure that $f(z)$ is invertible on the whole of $D$? If, for instance, on the disc of radius $\frac{1}{2}$ around $(1+0i)$, we cannot invert $f(z)=z^{100}$.
It will suffice, I suppose, if $\Re (f'(z))$ never attains $0$. But no stronger conditions come to mind.
Answer: The inequality $\operatorname{Re}f'>0$ is sufficient for global invertibility in a convex domain, where one can integrate it along line segments to obtain $\operatorname{Re} \frac{f(a)-f(b)}{a-b}>0$ for all $a\ne b$. In general, it is not sufficient when the domain is not convex.
There are many sufficient univalence criteria (search for this term) for holomorphic functions on the unit disk. They often involve the Schwarzian derivative $Sf(z) = (f''/f')' -\frac12(f''/f')^2$.  The most notable is $|Sf(z)| \le 2/(1-|z|^2)^2$; Nehari's paper Univalence criteria depending on the Schwarzian derivative gives a few others.


What is a procedure in MySQL?

Question: I've Googled but come up with nothing that I can get my head around.
Are the performance gains from using stored procedures significant?
Would I still want to use prepared statements in conjunction with stored procs or is it generally a one or the other thing?
Can I create stored procs through PHPMyAdmin and manage them from there as well?
What would a stored procedure look like for something simple like this-
SELECT * FROM table a
INNER JOIN otherTable b
ON a.join_id=b.join_id
WHERE someVar = :boundParam

and how would the PHP work (PDO) to call it and bind its parameter?
Comment: no contest - sprocs are more efficient on so many levels. Let's forget query optimisation and execution speed - let's think in terms of calls required, bytes sent..., grants required (exec vs all), security, how many calls does mysqli/pdo need to make to exec 1 parameterised query ? would that be 2 ??? lol
Answer: A procedure:

can have zero or more SQL statements with BEGIN ... END statement. *No statement without BEGIN ... END statement gets error.

can have only single statement without BEGIN ... END statement not changing the delimiter to $$ without error.

can have multiple parameters with IN, OUT and INOUT and without them.

can get zero or more values with zero or more IN and INOUT parameters from the caller.

can return zero or more values to the caller with OUT and INOUT parameters.

can have local variables and user-defined variables. *My answer explains local variables and user-defined variables.

can have transaction.

cannot have RETURN statement otherwise there is the error.

is not atomic by default so if there is error, it is not rollbacked automatically. *My answer explains it in detail.

*In this answer, I explain how to create a procedure with an IN parameter and my answer and my answer explain OUT and INOUT parameters respectively and the doc explains a procedure in detail.
For example, you create test table as shown below:
CREATE TABLE test (
  num int
);

Then, you insert the row whose num is 2 as shown below:
INSERT INTO test (num) VALUES (2);

Now, you can create addition(IN value INT) procedure which adds value to num as shown below. *The IN parameter IN value INT can get the value from the caller and you can also use value INT without IN which is also recognized as an IN parameter and basically, you need to change the default delimiter ; to something like $$ when creating a procedure otherwise there is error, then after creating a procedure, you need to change the delimiter $$ back to ; as shown below and my answer explains delimiter and you must select a database when creating a procedure otherwise there is the error:
DELIMITER $$

CREATE PROCEDURE addition(IN value INT)
BEGIN
UPDATE test SET num = num + value;
END$$

DELIMITER ;

DELIMITER $$

CREATE PROCEDURE addition(INOUT v1 INT, INOUT v2 INT)
BEGIN
SELECT v1+1, v2+1 into v1, v2;
END$$

DELIMITER ;

Then, you can call addition(3) with CALL statement, then 3 is added to num as shown below:
mysql> CALL addition(3);
...
mysql> SELECT num FROM test;
+------+
| num  |
+------+
|  5   |
+------+

Or, you can set the user-defined session variable e.g. @v with 3, then 3 is added to num as shown below. *The initial value of a user-defined session variable is NULL:
mysql> SET @v = 3;
...
mysql> CALL addition(@v);
...
mysql> SELECT num FROM test;
+------+
| num  |
+------+
|  5   |
+------+

In addition, you can create addition() procedure with the user-defined session variable e.g. @v and without an IN parameter as shown below:
DELIMITER $$

CREATE PROCEDURE addition()
BEGIN                    -- ↓↓ Here
UPDATE test SET num = num + @v;
END$$

DELIMITER ;

Then, you set @v with 3 and call addition(), then 3 is added to num as shown below:
mysql> SET @v = 3;
...
mysql> CALL addition();
...
mysql> SELECT num FROM test;
+------+
| num  |
+------+
|  5   |
+------+

And, in this case below, you can create addition(IN value INT) procedure not changing the delimiter to $$ without error:
CREATE PROCEDURE addition(IN value INT)
UPDATE test SET num = num + value;

Comment: I wonder if this answer would have been better placed on one of the duplicates, especially considering that another, well-upvoted, answer to this question has been deleted.
Comment: @AndrewMorton I find the checkers related to database are strange, mean, close-minded, unreasonable or too strict. I ofter answer Python's questions and the checkers related to Python are good, open-minded and reasonable.

What is a procedure in MySQL?


question about the matrix of linear transformation

Question: I am learning the matrix of linear transformation but have trouble understanding it when reading the notes. The part I am stuck at is as follows:

To see how important the choice of basis is, let's use the standard basis for the linear transformation that projects the plane onto a line at a $45^\circ$ angle. If we choose $\boldsymbol{\mathrm v_1} = \boldsymbol{\mathrm w_1} = \begin{bmatrix}1 \\ 0\end{bmatrix}$ and $\boldsymbol{\mathrm v_2} = \boldsymbol{\mathrm w_2} = \begin{bmatrix}0 \\ 1\end{bmatrix}$, we get the projection matrix $P = \dfrac{\boldsymbol{\mathrm{aa}}^T}{\boldsymbol{\mathrm a}^T\boldsymbol{\mathrm a}} = \begin{bmatrix} 1/2 & 1/2 \\ 1/2 & 1/2 \end{bmatrix}$. We can check by graphing that this is the correct matrix, but calculating $P$ directly is more difficult for this basis than it was with a basis of eigenvectors.

My question is:
How to get the projection matrix $P$?
Comment: The notes say "but calculating $P$ directly is more difficult for this basis than it was with a basis of eigenvectors".  Are you asking about how get the matrix using eigenvectors, or how to get the matrix directly?
Comment: both if it is possible. I can't figure out why P is \begin{bmatrix}1/2&1/2\\1/2&1/2\end{bmatrix}.
Answer: Let $a$ and $b$ be two vectors in $R^m$.
Note that the projection of vector $b$ onto vector $a$ is $\frac{b^{T}a}{a^{T}a}a$
Rewrite the same as $a\frac{a^{T}b}{a^{T}a}=\frac{aa^{T}}{a^{T}a}b=Pb$      [Note that $\frac{b^{T}a}{a^{T}a}$ is a scaler and that $P=\frac{aa^{T}}{a^{T}a}$ is a rank 1 matrix which projects $b$ onto $a$ ]
Now as per your question, choose $a$ to be any vector on the line $y=x$, for example  $a=(1,1)^{T}$ and get $P$ from $P=\frac{aa^{T}}{a^{T}a}$


Recursive -notmatch in get-childitem with regex

Question: Recursive -notmatch in get-childitem with regex
I am trying to find some files with set extensions with the following code.
$include = @('*.keystore', '*.cer', '*crt', '*pfx', '*jks', '*.ks')
$exclude = [RegEx]'^C:\\Windows|^C:\\Program Files|^C:\\Documents and Settings|^C:\\Users|\bBackup\b|\bbackup\b|\brelease\b|\breleases\b|\bReleases\b|\bRelease\b'
$trace="trace.txt"
Get-ChildItem "D:\","C:\" -Directory |
  where FullName -notmatch $exclude | ForEach {
  Get-ChildItem -Path $_.FullName -Include $include -Recurse -Force -EA 0|
  Select-Object -ExpandProperty FullName
} *>&1 >> $trace

It works but only excludes if the root directory contains one of the patterns.
Ex.
Excludes D:\Backup but includes D:\something\Backup
Is there a way to exclude the second folder as well?
Comment: I don't see a problem with your regex; `'D:\something\Backup' -match $exclude` returns `$true`, as intended.
Comment: Also, if you construct a `[regex]` instance explicitly - instead of passing a _string_ to `-notmatch` - you're creating a case-_sensitive_ regex instance. By contrast, using a string implicitly creates a case-_insensitive_ instance, in line with PowerShell's fundamentally case-insensitive behavior; e.g. `'foo' -match 'FOO'` returns `$true`.
Comment: You need to add `-Recurse` also to the _first_ `Get-ChildItem` call, so that folders such as `backup` are excluded on every level of the directory hierarchy. Theo's solution is simpler and more efficient, however.
Comment: Maybe *wildcard expressions* are better suited for this?
Comment: @mklement0 I have D:\something\backup\test.jks. The above does not exclude it. However, excludes D:\backup. Test it by creating these 2 folders.
Answer: Try this with a single call to Get-ChildItem and have it look for files. Then in the Where-Objectclause, you filter on the DirectoryName to exclude the folders you don't want in the output.
Also, you can simplify your regex and use it case-insensitively.
Try:
$include = '*.keystore', '*.cer', '*.crt', '*.pfx', '*.jks', '*.ks'
$exclude = '^C:\\(Windows|Program Files|Documents and Settings|Users)|\bBackup\b|\breleases?\b'
$trace   = 'trace.txt'
Get-ChildItem -Path 'C:\','D:\' -File -Include $include -Recurse -Force -ErrorAction SilentlyContinue |
  Where-Object { $_.DirectoryName -notmatch $exclude } |
  Select-Object -ExpandProperty FullName |
  Set-Content -Path $trace -PassThru

Switch -PassThru makes the result also display on screen

The C:\ drive contains system-defined junction points you do not have access to, even when running as admin.
Based on this answer, you can change the code to:
$include = '*.keystore', '*.cer', '*.crt', '*.pfx', '*.jks', '*.ks'
$exclude = '^C:\\(Windows|Program Files|Documents and Settings|Users)|\bBackup\b|\breleases?\b'
$trace   = 'trace.txt'
Get-ChildItem -Path 'C:\','D:\' -File -Include $include -Force -Recurse -Attributes !Hidden, !System, !ReparsePoint -ErrorAction SilentlyContinue |
  Where-Object { $_.DirectoryName -notmatch $exclude } |
  Select-Object -ExpandProperty FullName |
  Set-Content -Path $trace -PassThru

As per your comment, here's an example on how you can do this on remote computers, and save the resulting file locally on your computer.
For this demo, I have removed the -Force switch because as you stated you don't need to capture hidden or system files.
$remoteComputers = 'PC01', 'PC01'  # your list of remote machine names here
$trace   = 'trace.csv'             # make your output a CSV file, so you can have the computernam in there as well

$result = Invoke-Command -ComputerName $remoteComputers -ScriptBlock {
    $include = '*.keystore', '*.cer', '*.crt', '*.pfx', '*.jks', '*.ks'
    $exclude = '^C:\\(Windows|Program Files|Documents and Settings|Users)|\bBackup\b|\breleases?\b'
    Get-ChildItem -Path 'C:\','D:\' -File -Include $include -Recurse -ErrorAction SilentlyContinue |
          Where-Object { $_.DirectoryName -notmatch $exclude } |
          # this time, output an object with the current computername and the file fullname combined
          Select-Object @{Name = 'ComputerName'; Expression = {$env:COMPUTERNAME}}, FullName
}

# save the resulting array of objects in a single CSV file on YOUR local computer
$result | Set-Content -Path $trace -PassThru

You may need to append parameter -Credential to Invoke-Command and feed it admin credentials for the remote machines
Comment: @Delyan No, no problem. Removing `-Force` will work, but then it will skip all hidden and/or system files (don't think you are after those, so it shoud be fine)
Comment: Thanks, it is working but not with C:\ for some reason it gives Get-ChildItem : Access is denied even with -EA0 and the admin privileges.
Comment: @Delyan Please see my edit, where I have added code to to hopefully prevent Access Denied on the C:\ drive
Comment: thank you. The issue was with an installed software and one of its folders. Removed -force and now I dont get the error. Probably it wont be a problem.
Comment: any idea why this does not work on remote servers? The $trace does not get populated. If I remove the filter and list disks for example it works.
Comment: @Delyan Please see my edit


Generic return types in a singly linked list

Question: I'm working on a program that works with a linked list of generic objects, inside the class that defines a single list there is a method that returns the value of that link:
 public class Link<E> {
      private E _value;

      public E getValue() {
           return _value;
      }

Then I want to use this return value of type < E > in the linked link class to return the value of a link at a certain position in the list
public class LinkedList <E> implements List <E> {
    public E get(int index){
        Link current = goTo(index); //go to is a helper method that returns a pointer to a Link at position index
        E value = current.getValue(); //this is the source of the problem
        return value;

    }

}

The problem has something to with the generic type < E >, I don't fully understand how it works.
Update
I get the message: Type mismatch: cannot convert from Object to E on the line indicated in the source.
Comment: What is the problem?  You forgot to tell us.
Comment: You are trying to implement List but List isn't an interface? Should you use extends List instead?
Comment: List is an interface
Comment: The problem is with  E value = current.getValue();
Comment: I get the following message: Type mismatch: cannot convert from Object to E
Comment: I think the line above your problem should be `Link current = goTo(index);` but I can't know for sure without seeing the `goTo` method.
Answer: It seems you should do like this:
Link<E> current = goTo(index);

as Link current (without <E>) pointed to list of Object class.
Answer: You have to provide actual type to the type parameter when you implement it. A sample is given below.
package com.example.transformer;

/**
 * This represents the transformer contract to transform domain objects into
 * data transfer objects.
 *
 * @param <S>
 *            source to be transformed.
 * @param <T>
 *            result after the transformation.
 */
public interface Transformer<S, T> {
    T transform(S source);

}

Here is the implementation,
package com.example.transformer;

import com.example.domain.dto.OrderDetailsDTO;
import com.example.domain.dto.ProductDetailsDTO;
import com.example.domain.dto.ShippingDetailsDTO;

public class ProductDetailsDTOTOOrderDetailsDTOTransformer implements Transformer<ProductDetailsDTO, OrderDetailsDTO> {
    private ShippingDetailsDTO shippingInformation;

    public ProductDetailsDTOTOOrderDetailsDTOTransformer(ShippingDetailsDTO shippingInformation) {
        super();
        this.shippingInformation = shippingInformation;
    }

    @Override
    public OrderDetailsDTO transform(ProductDetailsDTO source) {
        return new OrderDetailsDTO(source.getName(), source.getUnitPrice() + shippingInformation.getCost(),
                source.getUnitPrice(), source.getCurrency(), source.getSoldBy(),
                shippingInformation.getCourierService(), shippingInformation.getAddress(),
                shippingInformation.getCost());
    }

}

Note that S and T is substituted with actual types ProductDetailsDTO and OrderDetailsDTO in the actual implementation. Iny your case it would be something like this.
public class LinkedList <YourType> implements List <E> {
   // your code goes here ...
}

Hope this helps. happy coding.
Comment: It does not have to be
Comment: If you leave it empty it will Object class. But still you can't pass E or so.
Answer: I think your problem is this line: Link current = goTo(index);  You have to correct it to specify the type of Object you want to use: Link <TypeOfObject> current = goTo(index);  replace "TypeOfObject with the return type value of goTo method.  I am assuming it is an Integer, so if that is the case just replace Link <TypeOfObject> current = goTo(index); with Link <Integer> current = goTo(index);
Comment: What type value does goTo(index) returns? String? Integer? replace  with that return type of goTo method.


How to execute an updated "start" attribute in "package.json" instead of the original one using "npm start"?

Question: I'm totally new at React, I'm trying to learn that language using a book that starts by teaching the basics of node (and npm).
The author teaches how to create a simple server, and how to execute it using npm start; here is the code.

server.js

require("http").createServer((inRequest, inResponse) =>
{
    inResponse.end("My first server");
}).listen(8011);

package.json

{
  "name": "ServerFirst",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "start": "node server.js"
}

executing npm start runs server.js alright.

Adding the request module is what I did next so the new server_time.js script obtains a json file with eastern standard time.

server_time.js

require("http").createServer((inRequest, inResponse) =>
{
    const requestModule = require("request");
    requestModule(
        "http://worldclockapi.com/api/json/est/now",
        function(inErr, inResp, inBody)
        {
            inResponse.end(`My first server: ${inBody}`);
        }
    );
}).listen(8011);

Then, I modified package.json to start with server_time.js instead of starting with server.js

package.json

{
  "name": "ServerFirst",
  "version": "1.0.1",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "start": "node server_time.js",
  "dependencies": {
    "request": "^2.88.2"
  }
}

when I execute npm start the terminal prints the same as before except for the version which now is 1.0.1, and when I check in my browser it runs server.js and not the script I want:
firstname.lastname@example.com start ~\ServerFirst
node server.js

why is npm start running node server.js instead of node server_time.js? it obviously can tell that the version attribute changed, but not the start attribute.
Note that node server_time.js works as it's supposed to.
Answer: You need to move the second "start" script into the scripts block:
{
  "name": "ServerFirst",
  "version": "1.0.1",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start-time": "node server_time.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "request": "^2.88.2"
  }
}

Name it whatever you want, then run npm run start-time (in this example).
Comment: Nice! it works just fine with `npm run`, the whole point was to just modify the `package.json` so I wouldn't have to type the script name.
Comment: You have to type `run` for custom scripts. You can see all the commands by typing `npm help`. Also see the [docs](https://docs.npmjs.com/misc/scripts) for how they work.