how does a DAO pattern make our business class loosely coupled from persistence?

Question: I have a business class, which calls the DAOimpl class which implements DAO interface, now how is this reducing coupling. DAO is used to reduce coupling with persistence logic. WHat should we do to reduce coupling between DAO and business logic.
Comment: DAO pattern is an anachronism with modern ORM.  The EntityManager/H-Session/etc is already an abstraction for the relational persistence model.  Inserting yet another one is an artifact.
Comment: I believe, this question is these days offtopic here and belongs on programmers.se. But ala, if you happen to use Java EE, I just wanted to say, lately with Java EE 5/6, the new JPA API has made the "homegrown" DAO pattern obsolete. JPA is the whole DAO at its own. JPA API is now the interface and Hibernate, EclipseLink, etc are now the concrete implementations which you actually don't need to code on your own but just drop in the classpath (like as you "previously" do with JDBC API and JDBC drivers). See also e.g. http://stackoverflow.com/q/2100115
Comment: @BalusC Say a requirement changes and you can't directly access the database anymore. Instead, you have to use a web service connected to some administration web application. The dao interface would remain unchanged. You would only add a different implementation. Am I missing the point?
Comment: @Soti: when I said Hibernate, I don't mean the "good old" Hibernate for J2EE, but their actual JPA implementation, the `EntityManager`, which they provided since Java EE 5 over 7 years ago. Perhaps it's time to catch up the new things in Java EE?
Comment: @BalusC All the same, I'm not going to write JPQL queries directly in my business code.
Comment: @Soti: So, you want to be able to switch between e.g. raw JDBC, old Hibernate, new JPA and whatever (MyBatis?). How does that make sense in a modern Java EE application offering JPA out the box? Note that JPQL is not specific to Hibernate, but just to JPA API.
Comment: @Soti: a DAO to access a web service? If it runs on same webapp, just inject it directly. Or if it really runs on a different context, change the business service implementation instead of "DAO" implementation.
Comment: @BalusC I think we're saying the same thing, but I might be using the wrong terms. Can you please comment on my answer below?
Comment: Code oriented to interfaces instead of class implementation.
Comment: @Esko they can indeed. I confronted a use case where the main problem was accessing to the data too many times, so the Dao implementation looked up the data in cache and retrieve the query results from the cache instead going to database (as usual).
Comment: @BalusC I wouldn't want to use (for example) the Hibernate classes directly from my business layer. I would still wrap all that behavior in a [`Data Mapper`](http://martinfowler.com/eaaCatalog/dataMapper.html) or DAO.
Comment: Are you using spring, you can inject DAO layer using spring.
Comment: I for one definitely *do* want to write JPQL in the business class. Hardly anything describes the business logic better than datastore queries. Inserting another layer of indirection just forces you to think up of an ugly long name for each of your queries.
Comment: @All Why do you want to add as many additional layers? For more pay? No other reason. I prefer the simplicity of Java EE 6/7 over the complexity acquired as a habit.
Comment: Isn't JPA offtopic here? For JPA I recommend using repository pattern instead of directly accessing entitymanager from business classes - it generally makes things easier to test.
Answer: Your business class wants to interact with other business classes. The interface your DAO provides should only require dependencies on business classes.
For example
public class Apple extends Fruit {}

and
public interface AppleDao extends Dao { // can be refactored even more
    public void add(Apple apple) throws FruityException;
}

and an implementation
public class AppleDaoHibernateImpl implements AppleDao {
    @Inject
    private Session session; // Hibernate session or JPA EntityManager, etc.

    public void add(Apple apple) throws FruitException {
        // do something with session, entityManager, etc.
    }
}

When your business classes use AppleDao, they don't see any SQL, I/O, etc. classes they need to import (depend on). Instead they see only more business (model) classes like Apple and FruityException.
This way you can change your underlying implementation, for example use a web service instead of using a database directly, without changing the interface.
Comment: [**JPA/EJB3 KILLED THE DAO**](http://www.adam-bien.com/roller/abien/entry/jpa_ejb3_killed_the_dao)
Comment: @Sotirios If i am writing a code like this in my business class to aceess my DAO  public class BUsiness{  AppleDAO appDao= new AppleDAOImpl();  appDAO.add(Apple);} then it wil lead to coupling between the business and the DAO. how to reduce that ?
Comment: @PaulVargas I disagree with the premise of the article. JPA is something that can be still be abstracted in a DAO. If you know for sure you'll always use JPA forever, that's fine, but the whole point of a DAO is to abstract the details of persistence, and JPA is a persistence detail even though its an interface that abstracts a subset of persistence solutions.


Most efficient way to get index of a table from HDF5

Question: I have an HDF5 file containing pandas Series/DataFrame tables. I need to get (pandas) index of a table stored under a key in HDF, but not necessarily the whole table:
I can think of two (effectively the same) methods of getting the index:
import pandas as pd

hdfPath = 'c:/example.h5'
hdfKey = 'dfkey'
# way 1:
with pd.HDFStore(hdfPath) as hdf:
    index = hdf[hdfKey].index

# way 2:
index = pd.read_hdf(hdfPath, hdfKey)

However for a pandas Series of ~2000 rows this takes 0.6 sec:
%timeit pd.read_hdf(hdfPath, hdfKey).index
1 loops, best of 3: 605 ms per loop

Is there a way to get only index of a table in HDF?
Answer: The HDFStore object has a select_column method that will allow you to get the index. Note that it will return a Series with the index as the values.
with pd.HDFStore(hdfPath) as hdf:
    index = hdf.select_column(hdfKey, 'index').values


Intutitive way for user to navigate to a second window in application?

Question: I have a 3D model of an aircraft in which the user uses to navigate to get to a specific parts.  When the user hovers over a part the part is highlighted with a rectangle.
When the part is highlighted, there is a floating window that displays additional information about the part, such as whether or not it's time for it to be replaced.
This window is interactive.
The problem is, I'm not sure what's the most inituitive way to get the user to go to the window.  I tried using a popup that appears when the user selects the part, but it gets in the way of rotating the model so I decided to put the floating window to the side.
If the user moves the mouse and tries to go to the window they risk selecting another part on the aircraft which will update the information in the floating window to the new part.
I wasn't sure if forcing the user to double click on the selected part and then giving focus to the floating window would be a good route to take.
I've tried looking for other interfaces similiar to this one, but the only one that comes to mind is the WebMD symptom tracker. So if you know of any other application that has similiar navigation to this situtation that'll help too.
Answer: Why are you updating the side window on mouse over? Could you just update the side window on a single click?
Another option is to deactivate the rotation of the model until the popup window is closed.
Answer: Hovering is an odd (non intuitive) way to be selecting. Also, it poses some accessibility concerns.
On hover, the part should be highlighted to convey select-ability.
Then, on click, the part should be selected.
When selected, the part should have a new highlight color.
Summary:
You have 3 states:

not selected
hover
selected

This parallels tabs on a website.
See this example of the menu in Pinterest. Gardening is highlighted, because I am hovering it and it is select-able. Health and Fitness is bold, because it is selected. The grey text would be the 3rd state, neither hovered nor selected.

You may also indicate select-ability with a cursor change. (The hand which has a pointer finger would be appropriate here.)
Also, having the 'floating window' as a locked section on the side, as you chose, is great, because it provides consistency of location and user expectation.


Slow shutdown caused by cryptswap

Question: After upgrading to 15.04 my computer takes a very long time to power off. Hitting escape during shutdown shows messages like so:
(1 of 6) A stop job is running for /dev/disk/by-id/dm-uuid-CRYPT-PLAIN-cryptswap1 (30s / 1min 30s)

On the next boot, I've tried looking for these messages all throughout my logs but I can't find them anywhere so I'm having difficulty working out which programs might be responsible. I also can't see any error logs relating to cryptswap or ecryptfs.
Ideally I'd like to solve the root problem, but I'd settle for being able to drastically reduce the timeout on whatever is waiting for these processes (I'm assuming it's systemd, but I don't know where to look to change that setting).
Comment: how many disks do you have involved? (including partitions if using raid) also if you are dual or multi booting it could be affecting things  It looks more like (from the output) that you have some kind of server style services that are running that are taking some time to quit.  Hope suggestion helps...
Comment: Seems cryptswap is slow on 14.04 as well. Swap makes it unbearably slow.
Answer: Hopefully this answer coming more than a year after the question will help some users.
I spent some time on this issue and I finally got a satisfying answer for my configuration.
In short: it is not necessarly cryptswap the culprit but can be another process hanging and thus blocking cryptswap.
In my case, my VPN client is not shutting down properly and blocks cryptswap exit.
Here is how to diagnosis that:

Deactivate cryptswap by following these instructions: https://www.logilab.org/blogentry/29155
Reboot, Reboot
Do you still see a stop job running?
If yes, then it is probably the one blocking cryptswap

Identifying this job is not always easy. I was already suspecting my VPN as I noticed that when rebooting immediately after startup, I had no issue. That was because I was rebooting too quick to allow the VPN startup.
If you have no idea, please look for further help on how to identify that particular process blocking your shutdown.

Once identified, re-activate cryptswap with sudo ecryptfs-setup-swap
reboot
exit the identified process
shutdown

No stop job ? You found your issue :)
Comment: This saved my day. How do you work around VPN blocking swap?

Slow shutdown caused by cryptswap


any Guide path to learn PlayFramework for Java

Question: there is no guided documentation available for Play(java). Can any one give me a link or something that shows how to do things in play. I have checked the documentation on the official site but it is bare minimal and not to explanatory.
I really like this framework and would love to develop my new project in Play. But right now it is not like anything I have worked on earlier so it is all very confusing to me.
Answer: Oh c'mon there are some useful resources :)

First you have documentation - traverse the Getting started - that's good point to start
There is also step-by-step tutorial describing how to create Your first application.
Finally, examine samples delivered with Play sources - you can run every and check how it works, you can test what happens, when you changes code. You'll find there apps for most typical uses.
Comment: Do not forget to mention the [book](http://www.manning.com/leroux/), and the [community section](http://www.playframework.org/community) on the play framework website.
Comment: @adis you are welcome to edit my post :) (or write another answer)
Comment: I have been to all of the above links, But still I am not able to understand how things are done in play. I think I have to buy the book.

One more thing. are there things which can not be done in java version but can be done in scala version. Please guide if play with scala is more powerful then play for java.


Align this video to right

Question: I want to align this :
<video width="300" height="200" autoplay="autoplay">
    <source src="video/supercoolvideo.mp4" type="video/mp4" />
</video>

To paste it in wordpress text and embed it with a link to a page.
Is it possible?
Answer: <video width="300" height="200" autoplay="autoplay" style="float: right;">
<source src="video/supercoolvideo.mp4" type="video/mp4" />

or

<video width="300" height="200" autoplay="autoplay"><source src="video/supercoolvideo.mp4" type="video/mp4" />

Align this video to right


Strange behaviour in gnuplot for label with Arial font face in pdfcairo terminal

Question: I am obtaining a strange behaviour on gnuplot 5.2.2 pdfcairo terminal with a label composed of several lines and attempted to be printed align to center. The label is the signature for my plots, it is composed of my name (first line), my institution (second line) and the date, obtained from time(0) and strftime.
In a multiplot script I noticed that the date (3rd line) was printed align to left while the other two line were printed align to center as intended. Then I placed the set label instruction before the first plot was called so that the label is printed two times. Then, in the first call, date was aligned to left but in the second call the date was aligned to center, as intended. Same happens if the align to right mode is intended. However if the strftime string is substituted by a regular string "foo" then alignment works fine.
This behaviour only happens if font is set to Arial and if the terminal is set to pdfcairo. If font is set to Ubuntu (or Times) or if the terminal is set to pngcairo then all calls print the label truly align to center.
A minimal workable example is:
set terminal pdfcairo enhanced color font "Arial,"
set output "prueba.pdf"

set multiplot layout 1,2

set colors podo
Cadena_firma="Martin-Olalla JM\nUniversidad de Sevilla\n".strftime("%Y/%m/%d",time(0))
set label 1 at screen 0.85,0.25 Cadena_firma noenhanced center font "Arial,10" tc rgb '#9d2235' front
set yrange [-2:2]
plot sin(x) lc 3

plot cos(x) lc 3

I attached the output, highlighting the weird printing of the date.
This is only happening in one of the computers I handle. It is easily solvable by changing the font. Nonetheless I am curious and it might be interesting for others.
Answer: There have been multiple reports of font problems that all appear to trace back to bad pango/cairo library versions.  Some of the problems are OS-specific and some are font-specific.  So there are probably multiple issues involved.  Here are some tracker items:
    https://gitlab.gnome.org/GNOME/pango/issues/422
and
    https://sourceforge.net/p/gnuplot/bugs/2052/


How to sand/smooth out this uneven/chipped wood?

Question: We have 2x10 triple wood beams which are not only uneven lengths, but they have chipped wood from when a steel column was installed.
My question is, how should we go about sanding/smoothing out the uneven chipped wood so that it can be perfectly level and so then we can install a wall along the beam probably in between our 3 posts? Would a belt sander work, or would we need a random orbital sander, or is there some better way to do it? We don't have to do it ourselves, we could have contractors do it, but we're kind of just wondering the recommended tools for doing this to make sure it's done properly.
Here are a couple pictures of the uneven wood in question:  and
Here is a picture of the entire basement:
Cheers.
Comment: Maybe you don't have to do anything. This is something to spend a few hundred dollars on to ask a professional structural engineer what the safe options are to achieve what you want. You don't want to have the supported beams break and collapse. The fact that there are 3 steel supports fairly close together indicates to me that they are holding a lot of weight.
Comment: I really can't quite gather if you are trying to do something over the whole length of the beam or only in the area where the one post is standing. If it is only the area around that one post, I'd probably use chisels - it looks like it was chiseled out before, just not with big enough care to make it look nice. Doing that over the whole length of a beam is a chore though.
Comment: wood filler would work
Comment: I believe it's not that high of a load, it's just one floor above, I believe the 2 end posts are permanent unlike the middle one. I'm kind of just wondering the best way of sanding the beams smooth including near the chipped parts, that way if we want to wall it off, or encase the columns with like a box of wood (just like 4 vertical two by eights) it'd be smooth and able to have lumber sit flush.
Comment: Well, we'd probably want to box the posts off with some sort of lumber, and then build some sort of wall around them. Chisels could work but I'd worry it'd cause chipping, though I guess it could get sanded flat.
Comment: As has been articulated in several ways below, there's nothing to do here. Slam your (non-bearing) wall plate up under that beam and move on. If things tilt more than you like, shim the gap in a couple places. Done and done.
Comment: **The green/gray post is not supposed to be there.** It's not on a footing, and posts wouldn't need to be so close in the first place. What's going on? The slab is at risk of cracks and deformity.
Comment: You want to add, not subtract from beams.
Answer: I would leave the posts in place and build the wall around them. The footings for the posts are not the same as a footing for a load bearing wall. That slight difference in the beam at the bottom will be of no consequence if you leave the posts and build a slightly thicker wall around them. Perhaps a 2X6 wall to get wiring around them or at least 2X4 with a 1X material added to get past the posts that way.
Comment: ^^ this, with extra agreement to "leave the posts". Anything else is expensive or dangerous.
Comment: A 2X6 wall will give about an inch of play to get around that type of issue Sch 40 lally columns should be about 4 1/2" OD. Other than that the way they are lagged in at the top, anchors in the bottom with new footings poured, they are most likely permanent. The gray one in the middle is the temporary one....
Comment: That's a good suggestion, but given the price of metals these days, those posts are probably worth quite a bit.   2x6 walls are great, my entire home's walls are 2x6, made it so much easier to run electrical and plumbing.
Comment: I know this answer did not directly answer your question, but in my opinion you may be sweating a detail that is not critical at all. If the floor could be made bearing for a replacement wall, then there might be a small issue with the  wood below the rest. Since it would be a new bearing wall, it would in essence eliminate the need for the beam. not to say remove it, but the wood could be simply chiseled off since a wall plate with studs will reinforce anything that is removed. If a wall was simply added the wood there will be ample to keep it steady for the long haul.
Comment: To me, from the picture, the placement of the red posts looks uneven, which I interpret as "temporary use". Building a wall around them would lead to an uneven wall.
Comment: It's just a lens distortion effect. The posts are actually plumb and level. Yeah, the middle is the temporary one.
Comment: Yeah it probably shouldn't be a load-bearing wall then, that's a good point. I think probably just boxing off the posts with some sort of lumber would be fine and then building a wall around it. I guess we could chisel off the wood and then sand it flat. Thanks for the answers.
Answer: You want to even out the underside of a (presumably) nail laminated beam to install a wall where the line of posts are.
So to make it level just add thin wood (MDF . plywwood, hardboard, card, building paper etc.)to the beams that are too high so that they come out level on the understide.
You could staple it in place or just shove it in on top of the top plate of the wall after standing it up.
Unless you need an opening in the wall where one of the posts is I would leave the posts in-place and just build non-structural walls in the gaps. I would use the same nail gun I hired to nail the bottom plate to the concrete to also nail the end studs to the posts.
Answer: You don't need to do anything. You don't need flush attachment along the entire underside of the beam. That defeats the purpose of a beam.
Consult with a skilled framer. He'll show you that you'll need to put a few load bearing posts under the beam, and then frame in studs around it, which hold no load.
To me, from the picture, the placement of the red posts looks uneven, which I interpret as "temporary use". Building a wall around them would lead to an uneven wall. I'm open to being wrong here, but they really don't strike me as a permanent solution. Or, if they are, they look poorly installed. I'd bet the middle post is doing nothing. Someone put it there for peace of mind.
Comment: I think there's a camera lens effect causing those red posts to appear out of line. To me the wall the the left also looks like it has a weird curve to it as it gets closer to the camera.
Comment: Yeah, it's just a lens distortion effect. The posts are actually plumb and level.
Answer: You don't want to build a load bearing wall under that beam. The posts are, and will continue to support the load of the beam (in conjunction with the pockets at the end that the beam is resting on) on the footings that are evident in the concrete at their bases. The rest of the floor is likely not designed to support the weight of whatever is above this beam since it's highly likely that there isn't a footing under this stretch of floor except where the posts are.
You will want to build a non-load bearing partition wall that will fill in the spaces between (and be wide enough to hide) the posts.
Additionally, there is no need to "tidy" up that chiseled out area. The new top plate can just be banged into place and nailed up to attach it to the beam to keep the wall from moving when someone leans heavily on it. (You will, of course, want to attach the sole plate to the floor, as well.)
The recommendations to build a 2x6 wall make a lot of sense, as this will allow you to bury the posts in the wall. However, there is no reason to build the whole wall out of 2x6 since it's not going to support any weight. Use a 2x6 for sole and top plates, then use 2x6 at each end and a 2x6 next to each post. Once you've got that part of the wall outlined, fill in the rest of the spaces with 2x4 studs, alternating which face of the footer/top plate they're lined up to. This will give you sufficient attachment surface for your drywall at a lower cost than 2x6.
It would look something like this (looking down at the wall from above with the ^ and v representing a post):
---------------------------
|     |     |^|     |     |
|  |     |  |v|  |     |  |
---------------------------

This type of wall construction is often used for improved sound insulation in partition walls, so it should be perfectly acceptable for this use, too. If you do want to reduce noise between the spaces, it gives you plenty of room for insulation to do so.
Answer: It would seem that the 3 existing posts are temporary, right? So to install a load bearing wall to replace them would involve a top plate nailed or screwed to the 2x10's when you say "uneven lengths" do you mean uneven widths, that is apparent from the pics.   If you tried with with a random orbit or even a belt sander, you'd make a big mess of sanding dust as well as take years to get done!
If  I had to do this, I'd use a hand held power planer. (see pic below).  You'd have to draw a perfectly level line, plumb as well along the 2x10's and go at it.
But I don't think that's necessary, maybe others with more framing exp. can chime in, but you could also cut thin strips of wood and fur it out, making a level surface that would land evenly on the top plate.    A small cutout like pictured is of no consequence if you're doing what I believe you are doing. Better to leave it alone rather than reduce the width of the beams, IMHO.
Comment: OK, but often it takes multiple tools to get a job done. Maybe a belt sander near the cutout would work best, but there's nothing wrong with using a powered plan cross grain or diagonal across the 2x's.  I would think that would be easier and more reliable than a belt sander and a lot less messy.   Removing that much material with a belt sander would produce a lot of dust.  you could minimize that with an attached vacuum, but without, I'd be wearing a full blown respirator.  Not only that, belt sanders are pretty heavy, unless you are a gym rat in good shape, you'll be sore the next day.
Comment: The red posts are not temporary. I've done a lot of basement finishes, and it would be dangerous and awkward to replace them with wood, which needs to be on the point-load footings and not evenly distributed. The _beam_ is the expensive part. If it wasn't needed it wouldn't be there.
Comment: @isherwood  THAT makes a lot of sense, in retrospect, those 2 red posts do look permanent.  The tough part is for the OP to decide on whether to fur the 2xs out to the exact same height (level?, Square, etc.) or to try and cut them back to make them even.   Frankly, I don't think it's all that big a deal considering now that the 2 red posts are doing most of the work.   Still, as Ive said before, I'm a belt and suspenders kinda guy and having both the posts and 2x6 walls as supporting is not a bad idea.
Comment: I believe the 2 on the end are supposed to be permanent posts. I feel like with the posts attached there wouldn't be enough room for a hand planer, since it cuts from the middle.

With a low grit sandpaper like 80, would it technically be possible to smooth out the chipped parts with a random orbit or belt sander? Dust wouldn't be a concern since that could just be vacuumed.
Comment: That makes a lot of sense, that's a good point that the majority of wood removal could be done with a powered plan across the 2x10s and then use a sander near the cutout. I may not even end up doing this myself, I can always have a contractor do it, but it's just good to get ideas of how this can be approached. It's less than like a quarter inch that would need to be shaved to get it flat so it's not like it's a huge amount or anything I think, it seems pretty doable. Thanks for your replies.
Comment: Yeah that's how I see it too, more can't hurt. Maybe even box them off with some 2x6s/2x8s and then build a wall as well.
Answer:
My question is, how should we go about sanding/smoothing out the uneven chipped wood so that it can be perfectly level

It looks to be unlevel for the entire length of the board, correct?
Aside from smoothing out the jaggies I would advise against tackling the entire length of the board because you are more likely to make it worse than better.

and so then we can install a (likely) load-bearing wall along the beam probably in between our 3 posts?

Sorry, this is nonsense. The two red posts are load bearing and hold up your house; notice how they are set on a concrete footer?
You are most likely not qualified to put up a load bearing wall so if you add a wall in between the posts then it is effectively a non load bearing wall.
However, I am a bit confused/worried about that jack post in the middle. Those are typically considered temporary. The most common use case for those would be to support a heavy static load like a large couch, entertainment center, or cast iron tub.

Would a belt sander work, or would we need a random orbital sander, or is there some better way to do it?

Either choice would be excellent for smoothing out the jaggies.
For leveling out the entire board, I would expect a circular saw to be used.

We don't have to do it ourselves, we could have contractors do it, but we're kind of just wondering the recommended tools for doing this to make sure it's done properly.

Yes, ask the contractors.

Closing thoughts:
I am confused as to how that proud beam board prevents a wall from being built.
Comment: I don't think it's the chipped part that's the potential problem, but everything else.  The one board in the beam was hanging down a bit lower than the other two and was chiseled out to be the same height above the floor where the post was added.
Comment: @JS99 I don't understand how that proud beam board prevents you from building a wall.
Comment: Yeah, my question was more about how to best go about making the beams all the same height so some sort of wall could get put in, maybe even box in the posts with some lumber, etc - I didn't word my question in the best way. I'm sure contractors could take care of it but I was just more curious about how it'd be done in general.
Comment: @DanIsFiddlingByFirelight I don't understand how that proud beam board prevents a wall from being built.


How to deal with a huge number of intents using DialogFlow?

Question: I created a relational database, that has multiple table. For example, in the first table are all the cars available, in the second table the available models of each car and in the third table the price of each model.
I need to use this with Google Dialogflow Chatbot.
My question is that If I want to create intents for each car and for each model manually, it'll end up having hundreds of intents, which I do believe is not a professional way. So, what should I do in this situation.
The flow for example would be like this:

User: What cars are available?
Prompt: "displays a list of all the cars"
User: I want the models of BMW
Prompt: "displays a list of all the models available of BMW"
User: I want the price of Model XXXX
Prompt: "Displays the price of this model"

I need help in this.
I've tried creating manually the intents, but I'm stuck due to the huge number of intents. I expect a more professional way to handle these intents.
Answer: If you make all of intent completely rely on cars, the amount of intent will explode.
How about creating the 3 intents listed below that handle car, model, price respectively.
I hope this help you.

Dialogflow setting
Entities

entity name
reference value
synonyms

car
car
cars, vehicle

company
BMW
bmw

Mercedes-Benz
mercedes, benz

Nissan
nissan

model
XXXX
xxxx

Intents

intent name
entity
context in
context out

car intent
@car
-
car

company intent
@company
car
company

model intent
@model
company
model

Each Intent behavior
car intent

description
When user wants to see cars, this intent shows cars.

utterance and entities

utterance
entity name
value

What cars are available?
@car
cars

pseudo SQL for prompt

SELECT car_name FROM car_table;

company intent

description
When user says the car company, this intent shows models.

utterance and entities

utterance
entity name
value

I want the models of BMW
@company
BMW

pseudo SQL for prompt

SELECT model_name FROM model_table WHERE comapny_name = '[@company]';

model intent

description
When user says anything about model, this intent shows the price of model.

utterance and entities

utterance
entity name
value

I want the price of model XXXX
@model
XXXX

pseudo SQL for prompt

SELECT price FROM price_of_each_model_table WHERE model_name = '[@model]';


How do I install VMware Player 4.0.3 (and patch the installer to work on my 12.04 system)?

Question: I can't install VMwarePlayer 4.0.3 on Ubuntu 12.04 64Bit. For Version 4.0.2, I found a script that I have to run to patch VMware Player for it to work on my system to properly, and after that I could install 4.0.2.
Is there an similar solution for Version 4.0.3?
Comment: on VMware Kernel Module Updater -Dialog I get the Error on Compiling "Virtual Network Device" and an Error-Messagebox: "Unable to start services."
Answer: I ran into the same problem, and I was able to make the same patch work by editing a version number in the script which applies it.

WARNING: I don't actually know what I'm talking about when it comes to
  VMware patching, I just made an educated guess that seems to work.

Whether you want to try this yourself depends on how risk-averse you are. But hey, your VMware Player install is already broken, right? I figured worst-case scenario I could uninstall and reinstall version 4.0.2.
I based this on the instructions I found here: vmware player compile issue.  To boil it down to the simplest steps:

Download this tarball: http://weltall.heliohost.org/wordpress/wp-content/uploads/2012/01/vmware802fixlinux320.tar.gz
Extract the tarball in your home directory
Edit the file patch-modules_3.2.0.sh.  Look for the line plreqver=4.0.2 and change it to plreqver=4.0.3
Save the file, then run it.  sudo ./patch-modules_3.2.0.sh

If you have run the same patch on version 4.0.2 before, you may get this error: "/usr/lib/vmware/modules/source/.patched found. You have already patched your sources. Exiting".  If you see that, just delete the /usr/lib/vmware/modules/source/.patched file and try again.

Please remember to have patch packet installed: apt-get install patch. My default installation of latest Kubuntu didn't have it, so I got error:
./patch-modules_3.2.0.sh: line 42: patch: command not found

Sometimes, the version check does not properly. In this case, you could remove it by deleting  the 4 lines following "unset product", all of them begin with "[". This again may increse the risk of breaking something.
Comment: This workaround also works for Vmware Player 4.0.4 (change 4.0.2 or 4.0.3 in the patch-modules_3.2.0.sh-File to "4.0.4"; check if "patch"-package is installed on your system or get it from the Ubuntu Software Center; remove the ".patched" file if you get an error during patching - if you have already patched for an other version - type: /usr/lib/vmware/modules/source/.patched in terminal)
Comment: +1 Awesome, It worked after changing 4.0.2 to 4.0.3
Comment: @dbrewer, I got this from a submitted edit but I can't tell if it's correct, can you look at it and see if it's necessary to add to your answer? "Helllo, your answer is very strong and congratulate!!!! But i have to mention that after editing the patch-modules_3.2.0.sh file we need to change not only the plreqver=4.0.3 but also the vmreqver=8.0.4 and follow the steps that you described. AND it'll work."
Comment: Hi Jorge. I'm not sure if that's correct either. I know that when I originally did this I only had to do exactly what I described in my original answer, and that I haven't had to change anything since to keep VMware Player working. But, I have to concede that it's possible things have changed since I did this in May, since updated versions of both the kernel and VMware Player have been released since then...
Comment: I have the same problem with VMPlayer 5.0.1 Will this patch work also for this version ?
Comment: Such a huge agreement... :'/
Answer: Works for different Versions, i tested it with version 220.127.116.114019:
Run vmware-installer -l in a console to get version number.
Edit the file patch-modules_3.2.0.sh:

Look for the line plreqver=4.0.2 and change it to plreqver=[copy and paste version number, just the three digit x.x.x ]
Remove the following lines:

unset product [ -z "$vmver" ] && error "VMWare is not installed
  (properly) on this PC" [ "$vmver" == "workstation$vmreqver" ] &&
  product="VMWare WorkStation" [ "$vmver" == "player$plreqver" ] &&
  product="VMWare Player" [ -z "$product" ] && error "Sorry, this script
  is only for VMWare WorkStation $vmreqver or VMWare Player $plreqver"
[ "id -u" != "0" ] && error "You must be root to run this script" [
  -f "$ptoken" ] && error "$ptoken found. You have already patched your sources" [ ! -d "$basedir" ] && error "Source '$basedir' directory not
  found, reinstall $product" [ ! -f "$fpatch" ] && error "'$fpatch' not
  found. Please, copy it to the current '$curdir' directory"

Now run the patch via sudo sh patch-modules_3.2.0.sh


How to make FFXIV chat sticky from typing?

Question: In Final Fantasy Online (FFXIV) when I'm in a party and type /p Hello, the chat mode does not stick to "Party", but remains on the previous one instead. This makes my next message appear in the old channel:

I can click on the talking bubble icon to make chat stick to another channel, but I'd like the game to remember a channel from my previous / message. Can that be done?
I've gone through the "Character Configuration" > "Log Window Setting" configuration, but haven't found any such option yet.
Answer: There is no sticky chat command... however, there is a simple chat command to switch the default chat mode.
Send /p or /party without any chat text to switch the default chat mode to party.  This also works for /say, /yell, /alliance, /freecompany and many others.
It also works with /tell if you supply a player name.
Comment: while @IG_42 has been downvoted, what he says about shout is true for this method too
Answer: Just click on that speech bubble and pick which channel you want to use, works for everything except shout.


Does a huge amount of warnings make C# compile time longer?

Question: We have a big solution with thousands of warnings. Would it take less to compile the solution if I removed all of the warnings (either manually or using a tool)?
I've tried lowering the verbosity level to silent, no use. Maximum verbosity level makes no difference either.
Comment: Regardless the answer, you should always remove the warnings...
Comment: The deadline's always yesterday B-)
Comment: Yeah, I know that but should I make it a priority when the deadline is yesterday... :)
Answer: No, it wouldn't make a significant impact on compilation time. Unlike special tools like FX Cop the compiler itself doesn't perform any complicated checks so in respect to the other logic it has to perform it's insignificant.
What actually may decrease the performance a bit is outputting a very large amount of messages into the console window when compiling from the command line. In this case redirecting the output into a file is a possible improvement.
However, it's a good idea to fix those parts of code that generate warnings. You'll end up with a higher quality code base and mitigate some bugs that would otherwise occur more easily.

Update: Experimental results.
Our codebase has approx. 340 thousand lines of C# code divided into 48 projects in a single solution. Recompiling yields 460 warnings. The compiler's output is 2800 lines longs and occupies nearly 400 kB when redirected into a file.
Compilation speed on a Core i7 920, 9 GB RAM, single 7.2 krpm disk:

47 seconds when outputting into a console window,
43 seconds when redirecting into a file — that is 9.1% decrease in compilation time.

All times are averages from three compilations, with a few initial compiles to force the files into the cache. Note that I didn't do any measurements with warnings turned off.
Comment: You can ignore certain warnings.  I imagine of your 5000+, that 4500 of them are warning 1591, "missing XML comment for publicly visible type or member...".  My advice isn't to fix all the warnings, its to pick low-hanging fruit.  If you can deal with 80% of them in less than an hour, do that and call it a day.
Comment: It's a legacy codebase so fixing the warning would take much effort. Maybe resharper can do something. But if not, I would rather not try to fix the literally more than 5000 warnings manually.
Comment: Anyway, are you absolutely sure? Can you explain why with more detail? Then I can accept this as an answer. This is very important to me (and at least for other 5 people). If you say you have tried or similar i can accept that or you wrote this particular piece of the compiler (who knows ... ).
Comment: @naeron84 I wrote a particular piece (a whole actually) of a completely different compiler (a 200k SLOC beast) B-) However, I've attached some experimental results from compilation of my current project.
Comment: @naeron84 Can't play with it right now, but a few hours later I can retry it with warnings turned off.
Answer: You should not silent the warnings. Most of the warnings indicates problems with your code. You should look into your code and fix them.
Processing all the warning should cost compile time (The compieler need to send the warnings to visual studio, more warnings should mean more output data. But I don't know how big the impact is). But if you fix the warnings you propably fix bugs, too.
Comment: Right, but that's **not** what the OP asked for.
Answer: Silencing the warnings has no effect on compilation time. Silencing affects whether the warnings are reported, not whether the compiler checks all rules or whether it generates errors/warnings.
As Fox32 said, silencing the warnings is not a good idea. If you have too many of them somethings is seriously wrong with the code. This will also make compilation marginally faster as the compiler will have to handle fewer edge cases.


page not getting forwarded through createRenderUrl

Question: I am a newbie to liferay..what I want to do is to pass value to javascript function on click of a link and call another jsp page from that function with the value passed to that function..
Here is what I tried.

for (User usersList: users) {

%>

        <a href="#" onclick="sendId('<%=usersList.getUserId()%>');"><%=usersList.getFullName()%>
        <%=usersList.getEmailAddress()%>

<%
}
%>

I want to retrieve the userId on assignSites.jsp so i am setting that value in portletURL.
But when I click the link alert gets showed up and nothing happens..am I doing it right..?
Please someone guide me.
Comment: `<%=usersList.getFullName()%>`
Instead of above, can you use this code
`<%=usersList.getFullName()%>`
Comment: there is nothing written in js code that make something to happen.
Comment: Iam setting the url to which I want to forward in portletUrl ..I thought by doing so it will forward to the desired page..can you please correct my code on what i need to perform?
Comment: I also tried modifying the javascript code by adding portletId and making the AUI().use() to AUI.action() still nothing happens
Answer: There are two problems with the code you provide:

AUI namespaces are meant to be top-level, not parts of the implementation of a function.
Despite this, you're not doing anything with the constructed portletURL variable.

Pankaj Kathiriya's comment already gives a way to generate the URLs without any javascript involved at all, here's a pretty-printed (and slightly changed) version of it: (Warning: Pseudocode, written here and never tested)
for (User usersList: users) {
%>
    <portlet:renderURL var="assignSiteURL">
       <portlet:param name="id" value="<%=usersList.getUserId()%>"/>
       <portlet:param name="jspPage" value="/html/assignsites/assignSites.jsp"/>
    </portletRenderURL>

        <a href="<%=assignSiteURL%>"><%=usersList.getFullName()%>
        <%=usersList.getEmailAddress()%>

<%
}
%>

Keep in mind that AUI namespaces are meant to isolate your JS code from the code of other portlets: Your proposed code would end up with a global function called sendId(x) - any other portlet on the same page could introduce just another method with the same name. This would result in a conflict that can be hard to resolve, thus you shouldn't do this.
Of course, the drawback of this isolation is that you can't just call such methods as easily in "onclick" handlers. However, you can enumerate all nodes that you want to change and dynamically update them.
If you insist on the javascript solution, I leave this for you (or somebody else), partly because I don't expect it to be necessary in this case.


Vuetify, how to center content and strech a column

Question: I'm trying to have a layout with 2 columns, I want them to have the same height and the content inside should be centered verticaly.
Here is my code in vuetify

  <v-app>
    <v-row align="center">
      <v-col cols=6 style="background-color: #FF5000;"  align="center">
           <v-btn class="m">Column 1</v-btn>
      </v-col>
      <v-col cols=6 style="background-color: #5fc3c7;">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
      </v-col>
    </v-row>
  </v-app>

I have tried to change <v-row align="center"> to <v-row align="stretch"> the column is stretch as I want but the content is not center..
Any help would be great
Answer: As Tingsen Cheng mentioned, you can add flex styles to your v-col to achieve vertical center. Additionally, as of Vuetify 2.3.10, you can make use of their flex helper which gives you utility classes to control your layout with ease.
So instead of using inline style, you can use just use something like this: class="d-flex justify-center align-center"
<v-row align="stretch">
  <v-col
    cols="6"
    style="background-color: #FF5000;"
    class="d-flex justify-center align-center"
  >
    <v-btn>...</v-btn>
  </v-col>
  <v-col cols="6" style="background-color: #5fc3c7;">...</v-col>
</v-row>

Here is a demo at codesandbox.
Comment: Thank you! Work as expected ! I thought v-col was flex by default but actually not, it's a block, unlike v-row, so when I tried justify-center it didn't work, with d-flex class it's fine !!
Answer: You can add some css styles in v-col, using the flex to achieve the vertical middle
<v-col cols=6 style="background-color: #FF5000; display: flex; align-items: center; justify-content: center"  align="center">

https://codepen.io/chengtingsen/pen/abNGxLd


Error using mex: No supported compiler or SDK was found

Question: Despite the fact that I get the following message by typing mex -setup:
>> mex -setup
MEX configured to use 'Microsoft Visual C++ 2013 Professional (C)' for C language compilation.
Warning: The MATLAB C and Fortran API has changed to support MATLAB
     variables with more than 2^32-1 elements. In the near future
     you will be required to update your code to utilize the
     new API. You can find more information about this at:
     http://www.mathworks.com/help/matlab/matlab_external/upgrading-mex-files-to-use-64-bit-api.html.

To choose a different language, select one from the following:
 mex -setup C++
 mex -setup FORTRAN

When I want to compile a certain .cpp file, I get the following error:
>> mex -g mx_minimum_power.cpp cvm_em64t_debug.lib
Error using mex
No supported compiler or SDK was found. For options, visit
http://www.mathworks.com/support/compilers/R2015a/win64.html.

Comment: Compiling `.cpp` file uses C++ compiler. Use `mex -setup C++`, for setting up C++ compiler.
Comment: @Rotem that doesn't make any difference. I've used mex a lot of times.
Comment: Either you dont have a supported compiler or there is a bug and you need to contact mathworks. 99% sure its the first one
Comment: @Rotem I'm using it on another system now. that was several days ago. any way, despite my first comment, your solution did work. do you want to add it as an answer?
Answer: Compiling .cpp file uses C++ compiler (.c file uses C compiler).
Use mex -setup C++, for setting up C++ compiler.
Apparently source file extension does matter when using mex instruction...


Multiple while matches in python

Question: I have 5 different strings i am searching for in a text file. I am trying to get python to ask the user for a "room number" and if any of those numbers match, to continue, otherwise ask again until a correct number is entered.
I can get it to work if try:
roomNumber = input("Enter the room number: ")
while roomNumber != ("L1"):
    roomNumber = input ("Please enter a correct room number:")

However i wish to have a positive match for L1, L2, L3, L4, and L5.
I tried:
roomNumber = input("Enter the room number: ")
while roomNumber != ("L1", "L2", "L3", "L4", "L5"):
    roomNumber = input ("Please enter a correct room number:")

however this doesn't work and i assume it wants all of those matches, not just the one.
I also tried putting each value in a ([ ]) and also tried using OR between each value but didn't work either.
I've been searching for ages and can't seem to find examples of multiple matches in a while loop.
Surely i'm missing something simple?
Answer: Python has an in/not in operator that is useful for things like this:
while roomNumber not in ("L1", "L2", "L3", "L4", "L5"):
    ...

It works for almost any container type in Python; all of the following are true:
1 in [1, 2, 3]
3 in range(50)
"foo" in { "foo": "bar" }
"bar" not in { "foo": "bar" } # (it only looks at keys for dictionaries)

Answer: Use in:
while not roomNumber in ("L1", "L2", "L3", "L4", "L5"):

Multiple while matches in python


Nested templates are not binding 2 way to Controller variables

Question: Having a lot of trouble with the following setup (which i cant change without a major rewrite).
The overview of the issue is that when I embed a partial via ng-include from another partial which was loaded via a ui-view (from ui-router) ng-bind is not binding back to the controller scope.
Here is a simplified example...
Here is the ui router
.state('investments', {
        url: '/investments/:Uid',
        abstract: true,
        templateUrl: 'views/investments.html',
        controller: 'InvestmentsCtrl',
        parent: 'root'
      })
        .state('investments.funds', {
          url: '',
          templateUrl: 'views/investments/funds.html',
        })

The first partial - views/investments.html includes a ui-view

Which loads up funds.html which contains the following
<tabset class="tabbable">
<tab>
    <ng-include src="'/views/investments/_investment.html'"></ng-include>
</tab>

And finally _investment.html has an input box which is binding to a variable on the controller (InvestController)
<input type="text" placeholder="Search" class="search-query" ng-model="invsearch.query"/>
<button ng-click="update();">Update</button>

Now in the controller I have the following:
angular.module('cougarApp')
  .controller('InvestController', function ($scope, $sce, $state, $debounce) {

     $scope.invsearch = {};

     $scope.update= function () {
         console.log($scope.invsearch);
    };

So its pretty straight forward (despite all the nested includes).
Bottom line when i click the button which calls $scope.update() - the function is called in the controller however the value of $scope.invsearch is an empty object. Even if I put a value into my textbox??
Now the exact same code works when I dont use the initial ui-view.
ie if my first template calls an ng-include directly then everything works fine.
I am still a little new to angular and there is obviously something about nested scopes that I am missing here.
Please can someone help me out here.
Thanks
Comment: where you declare **InvestController**?
Comment: i just pasted the relevant snippet from my controller. I have updated and shown the controller declaration above
Comment: Which state does `InvestController` belong to?  In the code pasted, the parent state requires `InvestmentsCtrl`, and the child state has no controller specified.  This is key to understanding  the question.
Answer: Try to declare the controller in your investments.html file like this.


PHP - Create thumbnail from picture without having white/black bars (and keeping proportion)

Question: I want to create a thumbnail for an image so that it's a square with no black bars/white bars and it fills the whole square while maintaining proportion. Kind of like CSS background-size: cover.
Like this:

Even if the image is smaller than the tuhmbnail size (which is arbitrary) it should still create the thumbnail.
The thumbnail size should be 400x400 (px).
I actually wrote a function to create a thumbnail with the white bars, here it is:
function createThumbnail($orig, $sizes){
    $width = $sizes[0];
    $height = $sizes[1];

    $targetSize = 340;

    $targetWidth = ($width > $height) ? $targetSize : round(($width * $targetSize) / $height);
    $targetHeight = ($width > $height) ? round(($height * $targetSize) / $width) : $targetSize;

    $targetLayer = imagecreatetruecolor($targetSize, $targetSize);
    $color = imagecolorallocate($targetLayer, 255, 255, 255);

    imagefill($targetLayer, 0, 0, $color);

    $targetX = ($width > $height) ? 0 : ($targetSize - $targetWidth) / 2;
    $targetY = ($width > $height) ? ($targetSize - $targetHeight) / 2 : 0;

    imagecopyresampled($targetLayer, $orig, $targetX, $targetY, 0, 0, $targetWidth, $targetHeight, $width, $height);

    return $targetLayer;
}

But I can't figure out a way to crop them and have them accomodated as I want. Thanks in advance!
Answer: Well after some back and forth I actually came up with a solution, probably not the best or most efficient, I have yet to test it for all cases but it seems to work for now:
function createThumbnail($orig, $sizes){
    $width = $sizes[0];
    $height = $sizes[1];

    $targetSize = 400;

    $srcX = 0;
    $srcY = 0;
    $src = $width;

    if ($width > $height){
        $ratio = $targetSize / $height;
        $srcX = (($ratio * $width) - $targetSize) / (2 * $ratio);
        $src = $height;
    }else if ($height > $width){
        $ratio = $targetSize / $width;
        $srcY = (($ratio * $height) - $targetSize) / (2 * $ratio);
    }

    $targetLayer = imagecreatetruecolor($targetSize, $targetSize);
    $color = imagecolorallocate($targetLayer, 255, 255, 255);

    imagecopyresampled($targetLayer, $orig, 0, 0, $srcX, $srcY, $targetSize, $targetSize, $src, $src);

    return $targetLayer;
}

If someone has a better solution or knows how to improve this one please let me know!


Loop to add docs to Google Firestore

Question: I am trying to loop through a List to add each item to a google firestore doc. However, the problem I am facing is that ONLY the last item in the List is added to the doc.
Note: The line print("=== $i POST SUCCESSFULLY ADDED ====") prints incremental for 5 times as expected
QUESTION: How can I get this loop to add all items to the firestore doc?
  void addPost() {
    DocumentReference documentReferencer = _firestore.collection('posts').doc();
    var i = 0;
    while (i < 5) {
      documentReferencer.set(postsData[i]);
      print("=== $i POST SUCCESSFULLY ADDED ===="); //PRINTS 5 TIMES
      i++;
    }
  }

Answer: I don't exactly know what your problem is in here, but it looks like your code is ignoring the fact that POST-ing data to a server is an asynchronous operation.
In other words, I'd expect that you need to await that to happen.
Also, I'd refactor the loop for readability.
Your code should be something like:
Future<void> addPost() async {
    DocumentReference documentReferencer = _firestore.collection('posts').doc();
    for(final post in postsData) {
      await documentReferencer.set(post);
      print("=== $i POST SUCCESSFULLY ADDED ===="); //PRINTS 5 TIMES
    }
  }

Comment: As nothing is happening after `set()` using an `async` function with `await` should not be necessary. And also because the order in which the items are written to the database does not matter using a sync call is perfectly fine.

The only issue is that the information in the print statement is wrong because at that point the item did not finish writing to the database. Also we do not know if the action was successful.
Comment: I am not sure what exactly you want to know but see my answer below for additional information to the original question. I hope that helps.
Comment: True that. Care to share more context, or code, so that I can look into it?
Answer: In fact all items are written to the doc but you keep overwriting the document with the next item ending up with only the last item.
When calling set() you should use SetOptions to set merge to true like so.
  void addPost() {
    DocumentReference documentReferencer = _firestore.collection('posts').doc();
    var i = 0;
    while (i < 5) {
      documentReferencer.set(postsData[i], SetOptions(merge: true));
      print("=== $i POST SUCCESSFULLY ADDED ===="); //PRINTS 5 TIMES
      i++;
    }
  }

Alternatively use update(). Attention: This will fail if the document does not exist yet.
  void addPost() {
    DocumentReference documentReferencer = _firestore.collection('posts').doc();
    var i = 0;
    while (i < 5) {
      documentReferencer.update(postsData[i]);
      print("=== $i POST SUCCESSFULLY ADDED ===="); //PRINTS 5 TIMES
      i++;
    }
  }

I recommend you debugging your code step by step while keeping an eye on the database. Then you can see how you keep overwriting the doc.
Also be aware that you are not catching any errors in case the database calls go wrong. So you can't tell if the action was successful. The only thing you know at the point of your print() is that the request was sent to Firebase.
Further readings:

Firebase documentation: Add data to Cloud Firestore
Flutter Firebase documentation: Usage - Writing data
Stack Overflow: Difference between set with {merge: true} and update

Loop to add docs to Google Firestore


how to implement a section block in eLearning module - odoo 14

Question: i was tryin to add a section block which allows me to block all the possible sections (except for the first) and then if all the slides in the section are complete, makes the next one available
I tried with the templates but it don't seem the way to approach this problem cause I cannot find any way to check the previous slides, I was trying to figure it out with javascript maybe but I'm not that good with JS
that's my actual progress:
<odoo>
<data>
        <template id="section_lock" inherit_id='website_slides.course_slides_list_slide'>
            <xpath expr="//div[@class='text-truncate mr-auto']" position="replace">

            </xpath>
        </template>
    </data>

and then the model with the flag needed for the check
class Slide(models.Model):
_inherit = 'slide.slide'

previous_category_complete = fields.Boolean(default=True)

how do u suggest to do it? I think i'm way off th road with this
Comment: Le'ts investigate the controller file main.py (located in directory controllers of the elearning module)
Comment: which field (m2o) or model makes the relation between each course (model: slide.slide) and its sections ?
Comment: @sylvain what should i look inside the controller?
Comment: no one btw, the section is a slide.slide entity, is just a slide with the "is_category" flag True
Comment: uh i just saw these were before the answer, my bad
Answer: The relationship between an e-Course and its section is based on the same model (slide.slide) using these relational fields :
    category_id = fields.Many2one('slide.slide', string="Section", compute="_compute_category_id", store=True)
    slide_ids = fields.One2many('slide.slide', "category_id", string="Slides")

    @api.depends('channel_id.slide_ids.is_category', 'channel_id.slide_ids.sequence')
    def _compute_category_id(self):

        self.category_id = False  # initialize whatever the state

        channel_slides = {}
        for slide in self:
            if slide.channel_id.id not in channel_slides:
                channel_slides[slide.channel_id.id] = slide.channel_id.slide_ids

        for cid, slides in channel_slides.items():
            current_category = self.env['slide.slide']
            slide_list = list(slides)
            slide_list.sort(key=lambda s: (s.sequence, not s.is_category))
            for slide in slide_list:
                if slide.is_category:
                    current_category = slide
                elif slide.category_id != current_category:
                    slide.category_id = current_category.id

To know wether a specific student has attended an e-course, there is an existing field in the model 'slide.slide.partner':

class SlidePartnerRelation(models.Model):
    _name = 'slide.slide.partner'

    slide_id = fields.Many2one('slide.slide', ondelete="cascade", index=True, required=True)
    partner_id = fields.Many2one('res.partner', index=True, required=True, ondelete='cascade')
    completed = fields.Boolean('Completed')

So you can check wether all the previous Slide Sections are completed for the current partner_id,  inheriting the class WebsiteSlides located in website_slides/controllers/main.py  > def channel(...)... :

from odoo.addons.website_slides.controllers.main import WebsiteSlides

class WebsiteSlidesCustom(WebsiteSlides):

    @http.route()
    def channel(self, channel, category=None, tag=None, page=1, slide_type=None, uncategorized=False, sorting=None, search=None, **kw):

        res_super = super(WebsiteSlidesCustom, self).channel(channel,        category=None, tag=None, page=1, slide_type=None, uncategorized=False, sorting=None, search=None, **kw)

        values = res_super.qcontext

        sections_completion = request.env['slide.slide.partner'].sudo().search([
            ('channel_id', '=', current_channel_id),
            ('is_category','=', True),
            ('partner_id', '=', request.env.user.partner_id.id)
        ])

        dic_sections_completion={}
        for sec in sections_completion.sorted('sequence'):
          dic_sections_completion[sec.id] = sec.completed

        values['sections_completion'] = dic_sections_completion

        return request.render('website_slides.course_main', values)

in your module directory views, create a new xml file : course_main_custom.xml
         <template id="course_main_custom" inherit_id="website_slides.course_main" name="Course Main" >
            <xpath expr="//t[@t-set='category']" position="after">
             ...
            </xpath>
          </template>

Comment: but there's no current_partner/slide field in slide.slide
if i paste the last block it will still work fine even without those fields in the slide.slide? (idk if they're like some odoo definitions or else, i'm still a beginner with it)
Comment: current_partner= request.env.user.partner_id.id
Comment: the issue is i cannot modify the core module, i'm working on a custom module for this implementation
btw, even if i copy-paste the last block inside the core module, how could i manage the xml to add this new block?
btw many thanks for all this help <3
Comment: how to inherit model using your custom module: https://www.youtube.com/watch?v=46yecsKX2tw
Comment: how to inherit view using your custom module:  https://www.youtube.com/watch?v=3iY3ea-wvjw
Comment: thank, i'm trying to inherit the controller and add the part u gave me, i 'll let u know if it works fine
Comment: hey, do u have any social where can i write to u? StackOverflow suggest me to use the chat but i don't have enough reputation so i can't, if for u isn't a problem we could end up that rapidly with small chat
Comment: btw it ain't worked, i pasted it inside the inherited controller and updated the module but nothing happened, idk if i have to do anything else other pastin it in the controller
Comment: yes, i have just given you guide lines, not the whole work... without advanced understanding of odoo development, it seems to be too complicated
Comment: uh ok, thx btw, i will try to figure it out i guess, i'm stuck on this task since may....


Remove a scratch from powder coated mailbox

Question: I have an ugly scratch on my mailbox. According to the manufacture, it has a powder coat. Here is a picture I am enclosing,

It is rather unsightly, what can I use to fix this?
Answer: I'd probably try a car-paint touch-up  product.
Comment: I will give it a try and let you know. Do you have a particular brand you prefer?


Potion effect Giver from item frames

Question: I remember doing this a long time ago with armor stands as it was the only entity to easily do it. I wanted to make an invisible item frame that gives the player jump boost when under the item frame. I know that I will have to use a command block to do it, or is there something that I can do with signs? (you can right click to use a command, but for the item frame have a small radius that is given to a player close to it).
I can't remember exactly how to do this, as I did once and I don't have any references to this anymore.
Answer: For the item frame, you can place the item frame and then run this command in a repeating command block:
execute at @e[type=item_frame] as @a[distance=..2] run effect give @s minecraft:jump_boost 2 1

This command will execute at the item frame and as any player near the location within a radius of 2, in a sphere.
You can also add a tag to the item frame to make it unique.
This will summon an invisible item frame with the custom tag Inv:
/summon item_frame ~ ~ ~ {Invisible:1b,Tags:["Inv"],Item:{}}

You can also add the tag Fixed so it doesn't need a block to sit on, as well as Invulnerable:
/summon item_frame ~ ~ ~ {Invulnerable:1b,Invisible:1b,Fixed:1b,Tags:["Inv"],Item:{}}

To test for the tagged item frame you can use this command:
execute at @e[type=item_frame,tag=Inv] as @a[distance=..2] run effect give @s minecraft:jump_boost 2 1

You can change the distance as you wish like this, the number before the two dots is the minimum, and the number after is the maximum. This distance=2..5 will affect all players at least 2 blocks away but not further than 5.

And this will give you a sign that when you click it provides the player with a jump boost:
/give @p oak_sign{BlockEntityTag:{Text1:"{\"text\":\"Click for jump boost\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"effect give @s jump_boost 2 1\"}}",id:"Sign"}}

Change this command:
effect give @s jump_boost 2 1

You'll change the first number for as many seconds as you'd like, and the amplifier is the second number.
Jump Boost I is 0
Jump Boost II is 1
and so forth.
Comment: this is awesome, it works just like how I wanted it to, just a quick question, is it possible to hide the jump boost applied to the player from the command block without changing the gamerule, i know that if you apply a command on a sign, it doesn't log it at all, i want something similar if it is possible.
Comment: Sorry for the delayed answer... If you get the gray info message like this one:
https://i.imgur.com/W6Up574.png
then the only way to remove it is through changing the gamerule comandblockoutput to false.

Potion effect Giver from item frames


ESO - Condition/curse stacking

Question: Ok... I've tried for a while to find a clear answer to this, but the closest I got was here (https://www.reddit.com/r/elderscrollsonline/comments/2n2uti/do_dots_stack/). Unfortunately is still not clear for me.
Let's take an example to explain what I don't get. Say we got 2 werewolves - because it has 2 different types of strong conditions (me and a friend).
1. Let's say I (first ww) bleed for 8k dmg/8 sec. on each hit.
2. Second ww bleeds for 10k dmg/8 sec. on each hit.
3. First ww poisons for 6k dmg/hit (5th skill, Claws).
4. Second ww poisons for 7k.
5. First ww has Claws of Life morph (drains 50% of the poison damage).

Let's assume for simplicity that all further attacks are instant (you can hit twice in 0 seconds).
Now this is what I got from different posts:
1. If first of the ww hits twice, the bleeding is not stacked in intensity (they give the normal bleed damage - 8k, over 8 seconds).
2. If first ww bleed, then poisons, the damage is stacked - 14k dmg.

And... that's it :). Further cases are still a mystery to me.
1. First ww hits (bleeds) and second ww hits (bleeds). How does this stack? The result is 18k dmg (total)? The condition is rewritten at each hit (whoever hits last gives the dmg)? Or the higher damage remains (in this case 10k)?
2. Same for poison.
3. For poison, if both ww apply poison, do the first ww heals over time (Claws of Life)?

Any other cases that I haven't considered are welcomed.
Answer: While I can't test this right now, it should work pretty much like this:

If the effect you're applying is a named buff/debuff (e.g. Minor Fortitude, Major Brutality, Minor Shatter, Minor Maim, etc.), only the strongest will be applied/persist (or reset its duration in case they're equal).
If the effect you're applying isn't named as a buff/debuff, like it's just a general bleeding or some other damage over time effect (e.g. poison), it should be limited to once per attacker.

So if both of you hit someone with a light attack, you both should see your own bleeding effect being applied (and constantly reset in case you attack again).

ESO - Condition/curse stacking


How much should I automatically sanitize filenames for compatibility?

Question: I'm writing a program for Mac OS X that allows the user to drag a row from a list in the application to Finder, where it automatically exports the data represented by the row to a file named after the row's display name (which must be able to contain almost any Unicode character). The user can edit this display name in the application, and it places no restrictions on this name for its internal use, but obviously I need to strip : and / from individual path components on OS X.
This program only runs on OS X, but in theory someone could write a similar program on another OS and want to import these files, or the user could be trying to export to a FAT32 or NTFS filesystem.
How far should I go?

Strip / replace leading . characters to avoid a hidden file?
Strip characters like \ or < which may not be valid on the target filesystem?
Fix up names that might confuse OS X tools, like -rf *?
Fix up names that might confuse non-OS X tools, like con?

Is this worth a preemptive pop-up dialog full of text about filename compatibility? Or should I punt and show the user the error the OS gives me when I try to open the file?
Answer: If there is a potential future usability problem for a user, and an easy solution now, you should solve it now.
I would present a dialogue letting the user know that the file name that will be generated needs to be modified slightly because it contains characters that may cause compatibility issues.
Then show them what the file name will be, and give them the option to accept the modified name or choose their own name for the file.
Comment: It's not possible to rename the row (it must match another name I have no control over), only the filename.
Comment: @JoeWreschnig Please add that information to your question, and I will edit my answer accordingly.


What's the highest item rarity type you can find in NPC's shop

Question: I noticed that except normal items the NPCs also sell items of blue-named rarity as well. Is there a chance an NPC will sell items of higher rarity then blue-named? If so what is the highest possible rarity of an item you can find in the shop?
Answer: Merchants only sell white and blue items. The idea of selling rares is not implemented because there is already a fine chance of finding them while playing.
Also, there are orbs with which you can upgrade normal items to rare -so you can buy the base item you want in the store and upgrade it with the orb. Just trade for those orbs with other players if you don't find enough.
Comment: Yeah i know about the orbs.


What is the optimal number of images in a carousel so the user can see all of it?

Question: I am working on a client's clothing store website. He asked for 7 plus images in the carousel, all with the horizontal transition. He wants to update his product daily with the latest items in the carousel. That means if he is going to update 5 items or maybe 10, he is going to create a mess in the banner portion.
How to deliver the landed user almost all the information? I think too much slider in a carousel is boring and not everyone is going to click the next button and see all the information in the carousel.
If the carousel transition is too quick, the user will miss the information as well when they only wait and see. Even if the transition is up to user readable time, I don't think they will go through all the banner.
What is an effective way to provide the latest updates?
How many images must be in a carousel so that the user can see all of it?
Comment: By banner do you mean a carousel? Just trying to clarify terms
Comment: yes @CharlesWesley
Comment: Obligatory [Should I use a carousel?](http://shouldiuseacarousel.com/)
Comment: Carousel in a real store - https://instagram.com/p/mDnxTxsQA4/ ;)
Comment: Obligatory [Lee Duddell](http://ux.stackexchange.com/a/10318/21341).
Answer: Q: How many images must be in a carousel so that the user can see all of it?
A: 1
In an interesting blog post about carousel interaction stats, Eric Runyon collected data on carousel interactions for various ND.edu web pages.
What he found is that effectively users only interact with the first item in the carousel:

A concise analysis of this data:
Answer: A carousel is an animated content. Therefore, you have to be aware that it will bother the readability of the other informations on the page.
That being said, using a carousel, there is no straight answer to your questions.
The reading time depends of the content complexity. A quite good pattern consists into pausing the animation on mouse over (with a visual feedback of the pause). Of course, the user should be able to play back and forth.
About the number of items, the probability of reading the items decrease with their quantity and complexity. 5 is a usual quantity, related to the cognitive span.
An other option, if many updates are to be provided regularly, is to give up the carousel for a vertical endless scroll...
Answer: Carousel should only have 3 or you risk folks missing it.
What about if you create a carousel on the section homepage?
How about just using a product tile gallery homepage.  More eyeballs and easier to switch out


MSVC is linking to release libraries in debug build instead of debug versions

Question: I am using Microsoft Visual Studio 2008 (C++). I am having a solution which I want to build in debug mode. I am referencing some third party libraries (e.g. MyGUI). By the end of the debug build the linker gives a fatal error (LNK1104) that "MyGUIEngine.lib" cannot be found. So actually in debug mode the linker should link to "MyGUIEngine_d.lib". Why does it look for the release version of this library?
I am building Multithreaded-Debug-DLL (/MDd).
Answer: The "C/C++" -> "Code Generation" -> "Runtime Library" setting (which you have set to "Multi-Threaded Debug DLL") controls what version of the C and C++ runtime you compile and link against, and has nothing to do with 3rd party libraries (such as "MyGUIEngine").
To change the version of "MyGUIEngine" you link to, change the value in "Linker" -> "Input" -> "Additional Dependancies" to "MyGUIEngine_d.lib" for the Debug configuration, and "MyGUIEngine.lib" for the Release configuration.
Comment: Yes, the strange thing is that MyGUIEngine.lib is not set as additional dependency, neither in release nor in debug. But that helped me finding the problem, there was in pragma in code: #pragma comment(lib,"MyGUIEngine.lib")
Comment: Yep, that'll do it.  That #pragma is the equivalent of setting the library as an additional dependency, just a different way to go about it.  You could do something like "#ifdef _DEBUG #pragma comment(lib, "MyGUIEngine_d.lib") #else #pragma comment(lib, "MyGUIEngine.lib") #endif if you want to stick with that approach.  (sorry about the formatting, can't type code in comments)
Comment: Thx, I'll do the #ifdef _Debug conditional. Actually I dont think its a good way to bind libraries within code via #pragma comment(lib, ) - you dont see it when looking in project properties and you have to search for it within the code.
Comment: I 100% agree, and I honestly have never used the #pragma method myself, nor would I ever if given the choice.


Why copying a character to a char array results in weird behaviour

Question: I have the following code which aims to implemente a simple LZW based text compression:
int compress(FILE text_file, FILE *output) {
  char input[20];
  short code = 0;
  short size = 0;

  memset(input, '\0', 20);

  char c = fgetc(text_file);
  while (c != EOF) {
    strncat(input, &c, 1);
    code = getCodeFromInput(input);
    if ((size + 1) > 1 && code == -1) {
      addInput(input);
      fwrite(&code, 2, 1, output);
      strcpy(input, &c);
      printf(%s, input);
      size = 1;
      code = 0;
    } else {
      size++;
    }
    c = fgetc(text_file);
  }
  fwrite(&input, 2, 1, output);
  return 0;
 }

So after finding a suitable string I need to override my string input with with the last char I've received. When using strcpy() I can easily copy arrays to my input string, but when trying to copy a single character, if I print the result I will get the expected output plus some weird character, for example copying the caracter 'a' I get a�. Is this expected? Why does strcpy() behave like that?
Comment: `strcpy()` will read characters until it reaches a null character. You probably want to use `strncpy()` which only copies the number of characters that you tell it too.
Comment: I think you are trying to copy a file, so why don't you just use fwrite() inside the loop for each character? You can simplify the code by removing the variable input, since it can create segmentation failts due to its size. In case you want to monitor the characters read you can simply use printf("%c", c);
Answer: The standard defines strcpy as a function copying a NUL terminated string, you are copying the last input (a character), but even if you get his address, it is not a NUL terminated string:
strcpy(input, &c);

you can try using a compound literal:
strcpy(input, (char[2]){c, '\0'}); // A NUL terminated string

Also, notice that fgetc wants an int instead of a char in order to handle EOF:
char c = fgetc(text_file);

should be
int c = fgetc(text_file);

in consequence:
strcpy(input, (char[2]){(char)c, '\0'}); // A NUL terminated string


Apply volume to PCM samples producing static/noise?

Question: I'm attempting to apply a volume limit to some PCM samples.
However, whenever the volume I apply is anything but 1.0 heavy static/noise is produced (interestingly only for about 80% of the duration of the sound, the rest seems to play without distortion) and the volume doesn't even seem affected.
Like I said, if soundVolume is 1.0 in the code below, works great. If it's 0.1-0.9 it produces horrible noise and doesn't work at all. I'm out of ideas as to why.
The PCM samples are signed 16-bit.
<code>// Get samples, apply volume, clamp, write back.
short s1 = (short)((pcmBytes[i] << 8) | (pcmBytes[i + 1]));

s1 = (short)(s1 * soundVolume);

pcmBytes[i] = (byte)((s1 >> 8) & 0xFF);
pcmBytes[i + 1] = (byte)(s1 & 0xFF);
</code>
Is there something wrong with this code? Tracing out s1 as it goes through the algorithm seems to show it being properly modified. Am I manipulating the bytes correctly?
Edit: This occurs even when the sound I'm modifying is pure silence. If soundVolume is anything other than 1.0 I get the static.

Solution: New code, I was incorrectly processing the bytes as big-endian when they were little-endian. Couple that with some missing masks 0xFF and this is the solution.
<code>short s1 = (short)(((pcmBytes[i + 1] & 0xFF) << 8) | (pcmBytes[i] & 0xFF));

s1 = (short)(s1 * soundVolume);

pcmBytes[i + 1] = (byte)((s1 >> 8) & 0xFF);
pcmBytes[i] = (byte)(s1 & 0xFF);
</code>
Answer: Just from your description of the problem, I would guess that you are processing little-endian data as if it were big-endian data.  Swapping the [i]s with the [i+1]s would fix that.  Note that this would also happen if your array is one byte out of alignment with the sample stream.
Your code also has a bug when you say:
| pcmBytes[i+1]
The byte is converted to an int here, and if it's "negative" then it will be sign-extended with a bunch of 1s that will stomp on the high bits from pcmBytes[i].
The result would sound horrible all the time, even when your volume is 1.0.  The reason it doesn't sound horrible is again probably because you have the byte order mixed up, so you're really only stomping on the low bits instead of the high bits.
So, when you fix the byte order, be sure to & the byte with 0xFF before or-ing it into the sample word.
Comment: Wow, that was exactly it. I had tried swapping the [i] and [i+1] indices before, but it produced odd-sounding sound. Then I had also tried throwing 0xFF masks everywhere, didn't work. Never tried them both together, haha. Thanks a lot for the help!


Array{Float64,2} problem when multiplying matrixes Julia

Question: I was doing something fairly simple with matrixes:
for i in 1:N
  X=XT[1:2,i]
  A[i]=X'*Sig*X+b
end

Where XT is an Array of arrays (1×5 Array{Any,2}) that I imported from Matlab, and by doing so I get X of type Array{Float64,2}. And Sig is a 2x2 matrix, also Array{Float64,2}.
The problem is: the result from X'SigX is of Array{Float64,2} type, although having just one element. And I can't sum it to b.
I Know I can put a dot and make the sum, but if I do that, I will still have this array type, and will be storing that on the other Array, which can be a big mess.
Any ideas to solve it keeping it simple?
Comment: What is the dimension of A? is it also Array{Float64,2}, and what is its size? Do you want the result of the sum to be an array stored in A or just a scalar stored in A[i]?
Comment: This is odd. `XT[1:2, i]` should be a vector, not a matrix. Very strange.
Comment: I want it to be stored as Float64. A should be also Array{Float64,2}.
Comment: Would you please edit your question to include initialization for the arrays A and XT?  It matters how that was done.
Comment: I've edited it. As it happens, my array XT was not a normal matrix. And there lies the problem. It seems I can do XT[i][:] and get the correct dimension, but I don't know why it does not happen the other way.
Comment: Can you show _exactly_ what `A` looks like? Even your last edit does not completely clarify. If `A` is `1×5 Array{Any,2}`, then `A[1:2, i]` should give an error. Without showing a complete, runnable example, helping becomes very hard.
Answer: Julia explicitly distinguishes between elements and arrays of elements. Some other languages, less explicit about types (like R and Matlab), treat a single-element Matrix as a number, and users get used to doing that implicitly. In Julia, however, these two things are fundamentally different - one is a container of numbers, the other is a number.
So the answer is simply, do (X'*Sig)[1] or first(X'*Sig) to get out the element. On coming versions of Julia you should be able to do only(X'*Sig) explicitly for containers with only one element.
It is simple and clear, just different from Matlab or R. There's actually a fundamental philosophical difference of what "simple" means in the languages. In R or Matlab I'd say "simple" means "not too many operation/characters". In Julia "simple" means "clear, explicit, straightforward to reason about". It's just a different philosophy that will take some time adapting to.
Comment: That was my first approach for an answer but there is actually another mistake in OP's code: `X=XT[1:2,i]` gives the first two elements (the first two arrays) in  `XT` (a `1D` array of arrays) when  `i` is 1 otherwise an error. The first line does not index `XT` appropriately for the purpose. There is also `A[]` to access the only element.
Comment: `MAT.jl` reads row or column vectors of MATLAB as Julia's 2D matrices. The OP's `1x1` matrix problem would be avoided if `X` was made a `Vector` with, for example, `vec`. `v'*M*v` automatically uses `LinearAlgebra.dot` giving a scalar rather than an array and does so in a performant way avoiding a matrix multiplication. The credit goes to Andreas Peter who explained this solution on #helpdesk channel of Julia Slack  today.
Comment: Nice, great perspective.


Rad Grid prerender event Issue

Question: Can anyone tell me the things happening in this section? Why is it making items invisible?
protected void rgStateTax_PreRender( object sender, EventArgs e )
    {
        if( rgStateTax.MasterTableView.IsItemInserted )
        {
            foreach( GridItem item in rgStateTax.Items )
            {
                item.Visible = false;
            }
        }

        if( rgStateTax.EditItems.Count > 0 )
        {
            foreach( GridDataItem item in rgStateTax.Items )
            {
                if( item != rgStateTax.EditItems[0] )
                {
                    item.Visible = false;
                }
            }
        }
    }

here rgStateTax is rad grid and PreRender is the event before the page is actually displayed on the screen, right?
Answer: Yes, PreRender is called before the control is rendered for the page.
This snippet of code is simply looping through almost every item in the grid and making it invisible.
if( rgStateTax.MasterTableView.IsItemInserted ) This checks if an item has been inserted into the grid.
foreach( GridItem item in rgStateTax.Items ) This loops through every item in the radgrid.
item.Visible = false; This sets each item to be invisible.
As for the next part:
if( rgStateTax.EditItems.Count > 0 )
This checks if there are any grid items in edit mode.
foreach( GridDataItem item in rgStateTax.Items ) This loops through every item in the radgrid (regardless if each item is in edit mode or not).
if( item != rgStateTax.EditItems[0] ) This checks if the current item is not the first item in edit mode (so we enter this for all but one item.
item.Visible = false; This sets each item to be invisible.
And that's what's happening.
Answer: You probably wanted
    if(!item.Edit){item.Visible = false;}

Rad Grid prerender event Issue


How to show the $B_p \to A \otimes B_p$ is injective

Question: Let $A$ and $B$ be commutative rings with unity and suppose we have $\phi: B \to A$. Take a prime ideal $p$ of $B$ and localize $B$ at $p$, $B_p$. Then we can consider $A \otimes B_{p}$. I would like to show that $B_p \to A \otimes B_p$, defined by $b/x \to 1 \otimes b/x$, is injective... Any explanation is appreciated. Thank you.
Edit. The tensor product is over $B$.
Answer: It seems that the user is assuming $A\otimes B_p$ to be taken over $B$.
In general, given $B$-algebras $A,C$, then $C$ injects into $A \otimes_B C$ if
1) the morphism $B\longrightarrow A$ is injective.
2) $C$ is flat over $B$.
Now, localisation $B_p$ is flat over $B$: localisation is an exact functor so the functor $B_p\otimes_B-$ is exact as well.
The other assumption is necessary: consider $A = \mathbb Z/p, B = \mathbb Z$, then $B_p\otimes A = \mathbb Z_{(p)} \otimes (\mathbb Z /p) \simeq \mathbb{Z}_{(p)}/p\mathbb{Z}_{(p)}\neq 0$ but the map $Z_{(p)}\longrightarrow \mathbb{Z}_{(p)} \otimes (\mathbb{Z}/p)$ cannot be injective (it sends elements of the maximal ideal to zero, for example).
Comment: You are welcome. An exact functor sends exact sequences to exact sequences; in your case I meant that every short exact sequence $0\to K\to L\to M\to 0$ of $R$-modules is sent into an exact sequence $0\to K_p\to L_p\to M_p\to 0$.
Comment: Could you possibly explain me what you mean by localisation is an exact functor?
Comment: And thank you for you answer! As long as $B \to A$ is injective, the answer to my question is true! :)
Answer: If the tensor product is over $\mathbb{ Z}$, then the tensor product $A \otimes_{B} B_p$ of $A$ and $B_p$ is considered as $B$-module.
Then $b/x \to 1 \otimes_{B} b/x$ is a group homomorphism whose Kernel is the torsion of $B_p$.
So it is injective iff $B_p$ is torsion free.


How should I mount a 10 ft 2x6 as a wall shelf?

Question: My living room has a wall with a 10-foot-wide alcove, which has a set of windows that share a Craftsman-kinda window trim with a 2x3 capitol - maybe not the correct term, but see picture.
I have a 10-foot-long 2x6 board to attach above this, as a shelf. (I think it goes better with the trim style than a 1x6 board). But that's heavy obviously so what method is good to attach it to the wall? Brackets? Pocket screws?
The wall surface is probably 1 or 2 layers of drywall or that grainy, concrete-looking wall stuff that's in the kitchen.
Comment: The way I install all shelfs are: Buy a threaded iron rod, cut into 6 1/2" sections, Drill holes 5" deep in the side of the 2x6x10 for the rod to slide into, then drill a hole 1" 1/2 into the other walls studs, the hole should be slightly smaller than the threaded rod so you can use the rod to thread the hole in the wall. With the rods in the wall slide your 2x6x10 into the 5" sticking out, then drill a much smaller hole in the bottom of the 2x6x10 where the iron inserts are, make sure it penetrates the rod, insert your regular 1" 1/2 screw in the hole through the rod where it grabs the wood.
Comment: I did much the same as @moto, except with 1/2" copper tubing. I did not use any screws and it stayed tight for years.
Answer: So, the good news is that you almost certainly have solid wood all above the window to fasten to. This makes it a good candidate for blind shelf supports. (Google, but rockler sells them...)
Alternately (and cheaper), you could have inverted L brackets. Paint the top legs wall color and you'll stop noticing them. Only your fussiest visitors would notice. It's up to you to decide how sturdy you need, but if you find that you haven't got enough to be comfortable, simply add a few more.
Comment: If he's planning on putting a lot of weight on the shelf, plants etc, I'd recommend 4 either triangular, or nicely routed and curved brackets going down at least 8" below the shelf. Those right angle metal brackets are OK, but will buckle under serious weight. A couple screws into window frame apiece, countersunk, with covering plugs, should be strong enough, and still look decent.
Answer: If you want the best performance and look the french cleat is your best bet.   You can either create this yourself using the shelf or you can buy brackets to help you.
Answer: An L-bracket will not hold, if weight is up there. A triangle of metal would work, many types out there. Even wood ones. Would use four brackets. Should be a header in the frame to screw to. I'm talking about brace on top of shelf so window treatment works.


Is there a way to control Cursor Point in std::fstream?

Question: I'm reading big datas from .txt file(s) like 1000-5000 persons data. and they saved in a file with alegorithm that i can easily read datas back. but to do it more easy, I'm seeking the way to control File cursor point.
for example in console app you can use VT100 Escape sequences like \033[3A (3 line up) \033[2D (2 Letter Left) \0337 (Save Position)
So is there way to control cursor point like that?
Comment: There's no such thing. You can read whole lines and store these in a `std::vector` though.
Comment: Are you looking for [`std::istream::seekg()` et al.](https://en.cppreference.com/w/cpp/io/basic_istream/seekg)?
Comment: @πάνταῥεῖ not really, because I'm not struggling with searcing datas, when I found, my problem is I have to push_back 2 Lines above to the string. And I don't want to rescan file untill i reach 2 lines up point
Answer: std::fstream can be seen as a linear stream of single bytes. As this, there is no way to use something like "cursor up" which as std::fstream has no knowledge of lines in the file.
What you can do is asking for the current position you are currently reading tellgor writing with tellp.
After keeping such positions, you can go back with seekg or seekp.
If you like you can store current line positions while reading the file and navigate later with this stored position. Alternatively, if you modify the file in a random fashion and the file is not such big, you can read it completely to a data structure of your choice, modify the data internally and write it back later.
Comment: Thank you for useful answer, Maybe I'll store 'n' lines in vector where every data iterates to another person. so if i found data in middle of the persons data, I can read back from vector.
Comment: Due to i read datas with lines, I set counter that counts lines, and I get informations where i want
Comment: Sorry, Forgot that ':D
Comment: @AhmetYusufYatkın Thanks :-)


How do I get a Celery worker to consume an 'outside' RabbitMQ queue?

Question: I have the following scripts:
celery_tasks.py
from celery import Celery
app = Celery(broker='amqp://guest:guest@localhost:5672//')
app.conf.task_default_queue = 'test_queue'

@app.task(acks_late=True)
def test(a):
   return a

publish.py
from celery_tasks import test
test.delay('abc')

When i run publish.py and start the worker (celery -A celery_tasks worker --loglevel=DEBUG), the 'abc' content is published in the 'test_queue' and is consumed by the worker.
Is there a way for the worker to consume something from a queue that was not posted by Celery? For example, when I put something in the test_queue straight through RabbitMQ, without going through the Celery publisher, and run the Celery worker, it gave me the following warning:

WARNING/MainProcess] Received and deleted unknown message.  Wrong destination?!?
The full contents of the message body was: body: 'abc' (3b)
{content_type:None content_encoding:None
    delivery_info:{'exchange': '', 'redelivered': False, 'delivery_tag': 1, 'consumer_tag': 'None2', 'routing_key': 'test_queue'} headers={}}

Is there a way to solve this?
Comment: How did you manually publish the message to rabbitmq? From poking around the docs, it looks like content_type and content_encoding are required, and there may be other required fields as well.
Answer: Celery has a specific format and a set of headers that needs to be maintained to comply with it. Therefore you would have to reverse engineer it to make celery-compliant message not produced by celery.
Keep in mind that celery is not really made to send messages across the broker, but to send tasks, which are enhanced messages therefore have extras in the header part of the amqp message
Answer: It's a late answer but custom consumers might help you. I'm using this for consuming messages from rabbitmq. Where these messages are being populated from another app with pika.
http://docs.celeryproject.org/en/latest/userguide/extending.html#custom-message-consumers


how to affect foreach items style every item alone

Question: i used "foreach" statement to access all items of IEnumerable and present it in details page ....and i want to make float property of each item different from the other items ....so i used  jQuery to affects on each item....but when i run the code all items became with the same direction.....how to affects on each item alone and make its direction of first to right and second to left and third to right ...etc?
here is html code:
@foreach (var item in Model.TimeLines)
{

                    @item.EventDate

@item.Title

@item.Body

                    @*
Edit
*@

حذف

تعديل

}

and jQuery code:

Comment: You could loop with an index, and conditionally add the style/class with `index % 2 == 0`. [See this](https://stackoverflow.com/a/22373172/3717691). Otherwise you can perhaps do it with [CSS entirely](https://stackoverflow.com/questions/5080699/using-css-even-and-odd-pseudo-classes-with-list-items).
Comment: can you make it easy for me and show me the full code to be clear for me>>>if you can
Answer: Your code won't work, cause you set the next sibling to left, but in the next iteration this sibling still get float: right.
As Jeppe mentioned in his comment you could use an index like this:
var index = 0;
$('section article').each(function (i, element) {
    var setFloat = (index % 2 === 0) ? "right" : "left";
  $(element).find('div.inner').css('float', setFloat);
  index++;
});

EDIT:
The CSS solution from dfliess was on the right way, but since there is only one div.inner in every article tag it will not work this way, cause every article has only one div.inner child.
If you still want a CSS only solution, you could do something like this:
section:nth-of-type(odd) article div.inner {
    float: left;
}

section:nth-of-type(even) article div.inner {
    float: right;
}

This one gives the styles to the div.inner of every odd/even section.
Working fiddle here: https://jsfiddle.net/jg6ht1ro/
Comment: You're welcome :). I updatet my answer, if you still want a css only solution
Comment: I think it is cleaner with CSS. `.css(...)` applies the styling on the `style` attribute,  which is a lot harder to maintain IMO.
Answer: You can try with @tawin answer or I would suggest to use css selector :nth-child
Try with something like:
section article div.inner:nth-child(odd) {
    float:left;
}

section article div.inner:nth-child(even) {
    float:right;
}

More info on https://developer.mozilla.org/es/docs/Web/CSS/:nth-child


How to find the port number of jvm which is running in ubuntu

Question: How can I know the debug port number of jvm (Java Virtual Machine) in Linux?
Comment: Are you talking about the Java Virtual Machine (jvm)? If yes, which port are you looking for? The debug port?
Comment: Yes Java Virtual Machine. Yes the debug port
Answer: I'm pretty sure that the debug port is not enabled by default.  You have to enable it via the -Xdebug parameter.  Here is an example how to start java with enabled debugging and port 8000 as debug port:
<code>java -Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n ...
</code>
Comment: Yes this was my solution:   -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8000
Answer: As per Stefan Endrullis suggestion, This was my solution:
<code>-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8000
</code>