text:
Q: R - ggplot - geom_ribbon() makes spikey / jagged plot for groups I'm working with a growth curve model (generated with lmer) and would like to add confidence intervals to the model plot using geom_ribbon(). (The full R code can be downloaded here and the data set is here.)
#Fit Model
GCA.elogit<-lmer(elog~(ot1+ot2+ot3)*Treatment*Experiment + (ot1|Subject),
                 control=lmerControl(optimizer="bobyqa"), data=GCA, weights=1/wts, REML=F)
#Add the fitted values to the data frame
GCA2<-data.frame(GCA, GCA_Full=fitted(GCA.elogit))

I got lower and upper bounds for the confidence interval using library(merTools) and the predictInterval() function and added these bounds to the data frame.
#Use Predict to get confidence intervals (upr and lwr), add to new data frame
library(merTools)
prediction<-predictInterval(GCA.elogit, GCA2, level=0.8)
GCA3 <- cbind(GCA2, prediction)

But when I try to use these lower and upper bounds in a model plot with geom_ribbon(), I get some funny behavior. I can use stat_summary() to draw the bounds using dashed lines, but geom_ribbon doesn't fill in this space like it should. Instead, it creates a shaded period with spikes for each of the data points. 1: https://i.stack.imgur.com/ae8Ma.jpg:
#plot model -- Filtered for Example -- Creates jagged lines
mplot2<-filter(GCA3, Experiment == "Blocking", Time <= 10)%>%
  ggplot(aes(Time, GCA_Full, group=Treatment, fill=Treatment, color=Treatment))+
  stat_summary(aes(y=GCA_Full), fun=mean, geom="line")+ #fit
  stat_summary(aes(y=upr), fun=mean, geom="line", linetype="dashed")+ #dashed upper bounds
  stat_summary(aes(y=lwr), fun=mean, geom="line", linetype="dashed")+ #dashed lower bounds
  geom_ribbon(aes(ymin=lwr, ymax=upr), na.rm=TRUE, color=NA , alpha = .1) + #ribbon should fit between upr and lwr dashed lines
  theme_bw(base_size=10)+facet_wrap(~Experiment)
labels<-labs(x="Item", y="Accuracy (elogit)")
mplot2+labels+scale_x_continuous(breaks=seq(0,10, 1))

The funny thing is that if I look at an individual subject (or group by subject like I did below) it works as expected. https://i.stack.imgur.com/2m8mS.jpg
#plot model color -- Filter includes subject -- Ribbon works as expected
mplot2<-filter(GCA3, Experiment == "Blocking", Time <= 10, as.numeric(Subject)<= 1002) %>%
  ggplot(aes(Time, GCA_Full, group=Subject, fill=Subject, color=Subject))+
  stat_summary(aes(y=GCA_Full), fun=mean, geom="line")+ #fit
  stat_summary(aes(y=upr), fun=mean, geom="line", linetype="dashed")+ #dashed upper bounds
  stat_summary(aes(y=lwr), fun=mean, geom="line", linetype="dashed")+ #dashed lower bounds
  geom_ribbon(aes(ymin=lwr, ymax=upr), na.rm=TRUE, color=NA , alpha = .1) + #ribbon should fit between upr and lwr dashed lines
  theme_bw(base_size=10)+facet_wrap(~Experiment)
labels<-labs(x="Item", y="Accuracy (elogit)")
mplot2+labels+scale_x_continuous(breaks=seq(0,10, 1))

I'm at a complete loss here and I feel like I've tried 1000 small fixes. Any help would be greatly appreciated!

A: Your overall issue here is that you are using stat_summary() to calculate the means for your growth curve line and for its upper and lower bounds, but you are not doing the same for geom_ribbon().  So instead, geom_ribbon() is trying to plot every observation in the original data set, apparently in ascending order within each time point, while stat_summary() is instead only plotting the respective means (one for each time point).  The reason why it appears correct when grouping by subjects is because each subject only has one observation to produce only one data point at each time point, while conversely each treatment group includes all observations, and thus all data points, for each subject that belong to it.
What you can do is first create a new data frame with the calculations of the means for the upper and lower limits at each time point.  The following code first filters for the sample you used as an example (which you can remove for your full data set), then groups by the factor variables to be plotted (Time on the x-axis and Treatment to be grouped), then calculates the means for GCA_Full and its upper and lower limits (note that it is easier to keep the same variable names of GCA_Full, upr, and lwr, respectively, for plotting).
GCA3_means <- GCA3 %>%
  filter(Experiment == "Blocking", Time <= 10) %>%
  group_by(Time, Treatment) %>%
  summarize(GCA_Full = mean(GCA_Full),
            upr = mean(upr),
            lwr = mean(lwr))

Now that those means are calculated, you can call the newly created data frame into the data argument in your original geom_ribbon() call as follows.
#plot model -- Filtered for Example -- Creates jagged lines
mplot4<-filter(GCA3, Experiment == "Blocking", Time <= 10)%>%
  ggplot(aes(Time, GCA_Full, group=Treatment, fill=Treatment, color=Treatment))+
  stat_summary(aes(y=GCA_Full), fun=mean, geom="line")+ #fit
  stat_summary(aes(y=upr), fun=mean, geom="line", linetype="dashed")+ #dashed upper bounds
  stat_summary(aes(y=lwr), fun=mean, geom="line", linetype="dashed")+ #dashed lower bounds
  geom_ribbon(data = GCA3_means, aes(ymin=lwr, ymax=upr), na.rm=TRUE, color=NA , alpha = .1) + #ribbon should fit between upr and lwr dashed lines
  theme_bw(base_size=10)+facet_wrap(~Experiment)
labels<-labs(x="Item", y="Accuracy (elogit)")
mplot4+labels+scale_x_continuous(breaks=seq(0,10, 1))

Now, geom_ribbon() will plot the means for the upper and lower limits at each time point rather than each observation to produce the following plot.
Plot with corrected CIs
All the best,
Ty


text:
Q: Add shp. name as attribute, looping through dates I have been stuck on this for a few days.  I have a folder with hundreds of shapefiles.  I want to add an attribute field to the shapefiles giving the shapefile's name as a date.  The shapefile name includes Landsat path/row, year, and Julien date ('1800742003032.shp).  I want just the date '2003032' to be added under a "Date" field.
Here's what I have so far:
arcpy.env.workspace = r"C:\Users\mkelly\Documents\Namibia\Raster_Water\1993\Polygons"
for fc in arcpy.ListFeatureClasses("*", "ALL"):
    print str("processing" +  fc)
    field = "DATE"
    expression = str(fc)[6:13]
    arcpy.AddField_management(fc, field, "TEXT")
    arcpy.CalculateField_management(fc, field, "expression", "PYTHON")
Results:
processing1800742003032.shp
processing1800742009136.shp
processing1820732010289.shp
end Processing...
It runs perfectly (on a sample 3 shapefiles) but the problem is that when I open the shapefiles in Arcmap, they all have the same date.  The results show that it processed each of the 3 shapefiles, and the add field management must have worked because all of the fields are populated.  So there is an issue with either the expression, or the Calculate field command.
How can I get it to populate the specific date for each shapefile, and not just have all of them be '2003032'?? There are no error messages.
Thanks in advance!

A: I figured it out! For calculate field management, expression should not be in quotes. It should be: arcpy.CalculateField_management(fc, field, expression, "PYTHON")
This post may have been a waste of time, but at least maybe it will help someone with a similar problem in the future.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does x-overflow:hidden cause extra space below? I have two spans inside each other. On the inner span I have overflow-x:hidden. This causes extra space below the inner span. Why?
Some text

Fiddle: http://jsfiddle.net/U92ue/
Note: I have only tested in latest Chrome.

A: Despite the above quote in the accepted answer, this behavior has nothing to do with Block Formatting Context and with "block" part of the inline-block value at all. It's all about the "inline" part of it.
All inline-* elements participate in the Inline Formatting Context. That means, they are placed inside the so called "line boxes" along with text and other inline-level elements. These elements and text are aligned with each other, so the height of each line box is calculated from the top of the highest element to the bottom of the lowest one.
By default, inline-level elements are aligned with the baseline of their fonts (see first line in the example below). Even if parent element has no actual text, the position of the baseline and the minimal height of the line box are calculated as if it had text (the spec calls this "imaginary" text the "strut" of the element). That's why the line box always has some space above the baseline (for the font ascenders and diacritics) and below it (for the font descenders) — see the second line of the example.
The tricky part for the inline-block elements is that overflow property changes what is considered the baseline for these elements (end of section 10.8.1 of the spec):

The baseline of an 'inline-block' is the baseline of its last line box in the normal flow, unless it has either no in-flow line boxes or if its 'overflow' property has a computed value other than 'visible', in which case the baseline is the bottom margin edge.

So, while technically the space below the baseline is always reserved, with default overflow: visible, the inline-block element is placed so that its text's baseline is aligned with the parent baseline, and its bottom part is moved below it. In many cases this makes this inline-block the lowest element in the line, so the space reserved for font descenders is not visible. However, changing the overflow value makes the whole element render above the baseline (like an  element), making all this space visible.

p {
  margin: .5em;
  font: 32px/1.5 serif;
  color: #fff;
  background: #888;
}

span {
  display: inline-block;
  font: 12px/1 sans-serif;
  background: #fff;
  color: #000;
  padding: 2px;
  border: 1px solid green;
}

.ovh {
  overflow: hidden;
  border-color: red;
}

Text with image  and two inline-blocks

 only inline-blocks

 regular, the overflowed trick

In general, inline formatting is tricky. You can find a good explanation of some of its gotchas and surprises in this article: http://iamvdo.me/en/blog/css-font-metrics-line-height-and-vertical-align.
I'd say that a good rule of thumb would be not using display: inline-* for its side effects, if you aren't really going to place the element inside the text. In the OPs example, the best solution would be to use display: block for the inner span, that doesn't involve any "magic" like line box calculation.

A:
Visual formatting model - 9.4.1 Block formatting contexts
Floats, absolutely positioned elements, block containers (such as inline-blocks, table-cells, and table-captions) that are not block boxes, and block boxes with 'overflow' other than 'visible' (except when that value has been propagated to the viewport) establish new block formatting contexts for their contents.

More specifically, a new block formatting context is established when the overflow property is changed. By default, an element's vertical-align property value is baseline. You can simply change this to something like top in order to fix this.
Updated Example
span.yavbc-color-tip span {
    display: inline-block;
    padding: 3px;
    border-radius: 8px;
    border: none;
    background-color:#005e8e;
    color:#7cd3ff;
    overflow-x: hidden; /* This gives extra space under this span. Why? */
    vertical-align:top;
}

Notice this doesn't happen when the element's display isn't changed to inline-block? It doesn't occur with inline elements - example demonstrating this.


text:
Q: How linkers work I need to understand how linkers work and how a linker makes an .exe with all its different sections and segments. To be more precise, I wanna be atleast able to make an .exe which contains the following code, with my hands using a hex editor.
int main()
{
}

Please suggest me some necessary reading. I have Linkers & Loaders by John Levine.

A: Ian Lance Taylor wrote a new ELF linker, called gold. He described the general tasks that linkers do in a series of blog posts.
This is different in details from what a PE linker does, but the general ideas are all the same (and same as in "Linkers & Loaders".

I wanna be atleast able to make an .exe which contains the following code, with my hands using a hex editor

I am not sure why you want a linker in that case. Read the description of PE file format, construct the necessary headers, write a tiny .text section containing xor %eax,%eax; ret, set the entry point to that section, ..., profit?

A: How (static) linkers work:
Take all necessary object files (module), merging/combining/flattening the addresses so that inter-module calls are possible and correct, structuring them to fulfill the executable format requirements, and perhaps do link time optimizations.
To create an executable (note that here I'm not referring to any specific format), you have to know the executable format, usually consists of headers and sections, plus any required startup code (compilers usually already provided this as an object file, precompiled). For PE (.exe) files, MSDN has a good explanation.


text:
Q: How can I get an icon image to appear in my desktop shortcut? How do I get an image to appear in an Ubuntu desktop shortcut?
I am trying to get an icon to appear in my desktop shortcut. I am using Ubuntu 20.04.5 LTS. This is what my desktop file looks like:
[Desktop Entry]
Name=Picture Show
Exec=./MyPrograms/PictureShow/ShoPixLinux
Icon=MyPrograms/PictureShow/PictureShow64.png
Terminal=false
Type=Application

I right-click and select Allow Launching, and it works, except I get a red logo with the international NO symbol (a circle with a cross through it) as the icon. If I add a leading right slash after Icon=, I get no shortcut image, just the title. I have tried the original image in .svg format. I have tried .png images in 44 x 44, 48 x 48, 64 x 64, 128 x 128, and 150 x 150.
What am I doing wrong?
Is there something specific about the color depth of the images? Do the images need to be in a specific location, like usr/share/icons? Do they need to be in a specifically named subfolder? Just what size image should I create for an Ubuntu desktop shortcut?

A: Try running this:
install -D MyPrograms/PictureShow/PictureShow64.png ~/.local/share/icons/hicolor/64x64/apps/PictureShow.png

Then change Icon=... to Icon=PictureShow
Usually Icon= entries in .desktop files refer to an icon by its basename (without extension). Icons being installed, for example, at /usr/share/icons/hicolor/{px}x{px}/apps/myprog.png
A program might ship with a range of icons, including a SVG icons in /usr/share/icons/hicolor/scalable/apps/myprog.svg
Files:
/usr/share/icons/hicolor/scalable/apps/myprog.svg
/usr/share/icons/hicolor/32x32/apps/myprog.png
/usr/share/icons/hicolor/64x64/apps/myprog.png
...

.desktop entry:
...
Icon=myprog
...

Users can have locally-installed icons as well in ~/.local/share/icons/hicolor/{px}x{px}/apps/.

A: It will help to provide a correct file path to your image file. Your current path starts with "MyPrograms". That means the system tries to find a directory "MyPrograms" in whatever is the current directory of the process that interprets the launcher.
Icon images may also be indicated by only the base file name of a graphic (i.e., only the name coming before the extension), provided the graphic is located in one of the standard locations. The system will first search for a graphic with that name (and extension either .png, .svg, .bmp) in ~/.icons, ~/.local/share/icons and then in icons directories under the directories enumerated in the XDG_DATA_DIRS environmental variable.
Thus, bottom line:
Either

*

*Provide a valid file name in your desktop file, e.g. /home/youruser/MyPrograms/PictureShow/PictureShow64.png. (Tip: find the graphics file in your file manager, then hit Ctrl+c to copy the file path to the clipboard.

*Place your graphic in ~/.local/share/icons (create that directory if it does not exist, and refer to it in your desktop file with Icon=PictureShow64.


text:
Q: Android studio Message Tool Window enable text mode In this documentation
http://www.jetbrains.com/idea/webhelp/messages-tool-window.html
I can see that we can enable text mode in  Message Tool Window:

But this button is gone in Message Tool Window in Android Studio

and I can only useit in tree mode. It is very inconvenient. Where can I switch to text mode ?


text:
Q: how to swap records having unique constraint in hibernate I have 2 tables user and userinfo. userinfo table contains user_id(id of user table) column which has UNIQUE constraint.
now i have 2users(primaryUser and secondaryUser) which has records in user and userInfo tables.
The primaryInfo object contains primaryUserId and secondaryInfo object contains secondaryUserId
I want to swap the userinfo data of primaryUser to secondaryUser and viceversa. I am doing like this
primaryInfo.setUserId(secondaryUser.getId());
secondaryInfo.setUserId(primaryUser.getId());

session.update(primaryInfo);
session.update(secondaryInfo);

but when commiting the transaction it is giving error like
ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper:147 ERROR: duplicate key value violates unique constraint "user_infos_unique_user"
  Detail: Key (ui_user_id)=(52560087) already exists.
can you please tell how to do this.. Thanks

A: You can use the DEFERRABLE and INITIALLY DEFERRED properties on the constraint and update both records in a single transaction.   DEFERRED means the constraint will not be evaluated until the transaction is commited -- at which time it should be valid again.
However: I have not figured out how to use Hibernate annotations to specify the DEFERRED properties, so you will have to use LiquiBase to maintain the database schema (not a bad idea anyway.)  (Or use "raw" SQL which is not so good an idea.)
See this question for more about the annotations (alas I cannot use LiquiBase on the project I ask about there.)

A: For Oracle database you can create next unique constraint with special attributes 'DEFERRABLE INITIALLY DEFERRED':
ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE (table_field) DEFERRABLE INITIALLY DEFERRED

A: As error Shows:
there is a unique constraint on userInfo table. that means user must be unique. So If you wnat to swipe the two user Id. you have to perform following steps
 1. Remove the constraint
 2. Swap two id's(same code as you currently have)
 3. Add Constaint.

A: A possible trick to work around the unique constraint is to do 3 updates:

*

*update row A with a value for the column that no other row can use. NULL may be used if not forbidden by a not-NULL constraint, otherwise 0 if not forbidden and assuming it's an integer, otherwise a negative value.

*then update row B with its final value (the previous value from row A)

*then update row A with its real final value (the previous value from row B)


text:
Q: Не работает форма на спйте хотел бы узнать почему не работает форма на сайте, есть сайт http://vialuso.com/product/wordpress-pennant
При клике на купить в 1 клик вылезает модальное окно, хотел бы узнать почему данные не отправляются на почту?
Форма написана на ajax и php

A: Потому что это не форма
            <div class="modal-body-right">
                            <input id="form_email" type="email" placeholder="Введите email">
                            <input id="form_name" type="text" placeholder="Введите имя">
                            <input id="form_phone" type="phone" placeholder="Введите телефон">
                            <button class="form-button" type="submit" id="button_contacts">КУПИТЬ</button>
            </div>

этот блок должен находиться в теге form
да и кто му же у вас ошибки в js скриптах
красного не должно быть


text:
Q: Apply one function on every fields which will get from database table : cakePHP 3 I want to apply one function called htmlentities in every field which retrieve from table.
how can i do this? i have used beforeMarshal but its only affect while save data in database. its not affecting while retrieve data from database.
So is there any function in cakaPHP that i can make the functionality possible as above I don't want to write this function each and every place that i am retrieving I want global solution that i will change at one place and it will affect to every fetch data?
I want to apply htmlentities because to not affecting code from user like content <script>alert("u have hacked");</script>


text:
Q: Elastic search : How to search in two documents in single index? I've two documents configured in a single index named inventory.

*

*profile (this have users and mobile information)

*p2p-relation

Inventory index mapping properties are as follows :
{
    "mappings": {
        "properties": {
            "type": {"type": "keyword"},
            "id": {"type": "keyword"},
            "sourceId": {"type": "keyword"},
            "targetId": {"type": "keyword"},
            "firstName": {"type": "text"},
            "lastName": {"type": "text"},
            "createdBy": {"type": "text"},
            "p_type": {"type": "text"},
            "model": {"type": "text"},
            "OS": {"type": "keyword"}
            }
        }
}

profile has the following information
users :
{   "type":"profile",   "id" : "user1", "p_type" : "user",  "firstName" : "Ashok", "lastName" : "S" }
{   "type":"profile",   "id" : "user2", "p_type" : "user",  "firstName" : "Arun", "lastName" : "V" }

mobiles :
{   "type":"profile",   "id" : "mobile1", "p_type" : "mobile",  "model" : "samsung", "OS" : "Android" }
{   "type":"profile",   "id" : "mobile2", "p_type" : "mobile",  "model" : "iPhone", "OS" : "iOS" }

p2p-relation has the which user used which mobile information :
{   "type":"p2p-relation",  "id" : "user1-owns-mobile1", "sourceId" : "user1",  "targetId" : "mobile1", "createdBy" : "admin" }
{   "type":"p2p-relation",  "id" : "user1-owns-mobile2", "sourceId" : "user1",  "targetId" : "mobile2", "createdBy" : "admin" }

In our business case, we need to retrieve the list of android/iOS mobiles owned by an user which we get as input from the customer.
That is, if the user1 requests for /mymobiles?query=os==Android , it should translate this into ES and expecting
{ "type":"profile",   "id" : "mobile1", "p_type" : "mobile",  "model" : "samsung", "OS" : "Android" }
as the result and if the user2 requests for the same, it should return empty.
I've tried with query and bool. But it search only within a single document. How to achieve this  in elastic search ?

A: Above model falls under many to many relationship data model. An user can have many mobile phones assigned to him and a mobile device can be assigned to many users over the period of time.
So changed the data model to storing it as nested objects.
{
  "mappings": {
    "properties": {
        "type": {"type": "keyword"},
        "id": {"type": "keyword"},
        "firstName": {"type": "text"},
        "lastName": {"type": "text"},
        "createdBy": {"type": "text"},
        "model": {"type": "text"},
        "OS": {"type": "keyword"},
        "mobiles" : {
            "type" : "nested",
            "properties" : {
                "id": {"type": "keyword"},
                "model": {"type": "text"},
                "OS": {"type": "keyword"},
                "createdBy": {"type": "text"}
            }
        },
        "users" : {
            "type" : "nested",
            "properties" : {
                "id": {"type": "keyword"},
                "firstName": {"type": "keyword"},
                "lastName": {"type": "keyword"},
                "createdBy": {"type": "text"}
            }
        }
}}}

But the pain is, whenever a mobile phone is assigned to an user, I have the extra effort of updating two rows.
Data stored as follows
{   "type":"profile",   "id" : "user1",  "firstName" : "Ashok", "lastName" : "S", "mobiles" : [ {"id" : "uuid1", "model": "samsung", "OS" : "Android"}] }

{   "type":"profile",   {"id" : "uuid1", "model": "samsung", "OS" : "Android"}, "users" : [ "id" : "user1",  "firstName" : "Ashok", "lastName" : "S"] }

And to answer the  /mymobiles?query=os==Android, I've used the following query .
{
"query": {
    "bool": {
        "must": [
            {
              { "term": {"OS": "android"} },
              "nested": {
                "path": "users",
                "query": {
                  "bool": {
                    "must": [ {"term": {"users.id": "user1"} }]
                  }
                }
              }
            }
        ]
    }
}}

I've referred the following link to do this : https://medium.com/@mena.meseha/briefly-describe-how-to-store-complex-relational-data-in-elasticsearch-f30277317b1


text:
Q: Office 365 Message header X-MS-Exchange-Organization-Recipient-P2-Type: Bcc missing As part of a workflow I want to move the email with "To" and "BCC" set to same mail address to a specific folder. I was using an inbox rule with condition :   "Message Header Includes : X-MS-Exchange-Organization-Recipient-P2-Type: Bcc", . This was working okay until we migrated to Office 365 but stopped working now.
After upgrade to Office 365, the message header "X-MS-Exchange-Organization-Recipient-P2-Type: Bcc" seems to be missing when both To and BCC are same.
Anyone faced similar issue or any idea how to resolve this?
Thank you for your help.


text:
Q: Getting the connection string in a c# service I'm using VS 2008.
I have a service that needs to be deployed.  The service won't be used from a .NET client (like a website or Windows client).  It needs a database connection.
I initially had a console app that called the service, and the connection string was set in the app.config of the console app.  I want to move the connection string to the service.  So in the web.config that come with the service I put in the following:
<connectionStrings>

     <clear />
     <add name="REConnectionString"
          connectionString="Data Source=MyServer;Initial Catalog=MyDatabase;Integrated Security=True;"
          providerName="System.Data.SqlClient" />

</connectionStrings>

And in my MyService.svc.cs I have the following:
private readonly string connectionString = ConfigurationManager.ConnectionStrings["REConnectionString"].ConnectionString;

But when I run the service this value connectionString is null.  How do I get this value from the web.config?
I have even added the following but it is also not working:
<appSettings>
     <add key="REConnectionString" value="Data Source=MyServer;Initial Catalog=MyDatabase;Integrated Security=True;"/>
</appSettings>

If I loop through the list of connection string then it keeps on bring back the connection string from the calling app.  Is there no way that the config file can be used?

A: I will try with something like this:
Configuration config = ConfigurationManager.OpenExeConfiguration("name_of_your_service.exe");
string connectString = config.ConnectionStrings["YourConnectionStringNameHere"];

You should pay attention to the string passed as name of the config file.
It should be the name of an exe or dll not the config file itself.
OpenExeConfiguration will open as Configuration object a file named "name_of_your_service.exe.config"
Details on OpenExeConfiguration
Just found an interesting question here on SO

A: I right clicked on the project and added a setting of type connection string.  And then I retrieve it like:
MyProject.Properties.Settings.Default.MyConnectionString;


text:
Q: pymssql - Get formatted sql instead of executing See cousin post: psycopg - Get formatted sql instead of executing
I need to transition some code from Postgres to MS SQL Server. I have been using psycopg2 in Python to do all database calls. I have found a simlar library in pymssql that actually has a very similar API.
One thing that is missing is the mogrify call. In short, mogrify prevents SQL injection but does so without executing. Great for building up a SQL string.
Is there a call that is similar to the mogrify call in pymssql? If not, is there anohter Python library that does have a mogrify-like call? If I cannot find anything, I will transition my code to use the execute/executemany calls, but I'd prefer to avoid that if at all possible.

A: The function substitute_params is exported in the _mssql module.  Example usage:
>>> import pymssql
>>> print pymssql._mssql.substitute_params("SELECT * FROM foo WHERE a = %s", ("quoted ' string",))
SELECT * FROM foo WHERE a = 'quoted '' string'


text:
Q: No indexing in SQL tables (neither clustered nor non-clustered) There is a stored procedure which has gets data from table tbl_SPP and makes joins with necessary tables. The table tbl_SPP has 27 million rows. It has 4 non-clustered indexes.
I have to improve the performance of the query. The cost of the query is 99%.
I tried adding a clustered index at the time of executing the procedure. But it takes more time than when it was not there.
I dropped all 4 non-clustered indexes from tbl_SPP and the cost of the query is reduced to 47%. The plan is to drop the index at the being of procedure and re-create it at the end
Now my question is: what are the disadvantages of dropping all the non-clustered indexes from the table? Will it improve the performance of stored procedure at real time?

A:
what are the disadvantages of dropping all the non-clustered indexes from the table?

Other queries may be slower, and you have eliminated options and destroyed statistics.  Have you tried with a columnstore index?


text:
Q: Displaying text and image (RTF) data in WPF & Silverlight In our app (Silverlight 5 and WPF) we are looking to put in a help section.  The help section will contain simple text and images so thought RTF would be perfect for this.  On closer inspection it seems Silverlight doesnt support RTF documents.
What other method could we use to display formatted text / images in both Silverlight and WPF that would allow the content to be generated by a supports person (i.e. no coding knowledge required)


text:
Q: php include error Access denied for user 'ODBC'@'localhost' (using password: NO) I'm trying to put my mysql_connect and mysql_select_db in other page, but it shows error and doesn't work. before I moved the code from the check_login.php to header.php the code works fine
this is my header.php
<?
$domain = 'localhost';
$username = 'root';
$password = '170693';
$con=mysql_connect($domain,$username,$password);
 if(!$con)
 {
 die(mysql_error());
 }
mysql_select_db("sure") or die(mysql_error());
?>

and this is the check_login.php
 <?php
 ob_start();
 session_start();

 include("header.php");
 $user=$_POST['username'];
 $pass=$_POST['password'];
 ....


text:
Q: Calling a Java class with PHP's exec function I need to split a text into sentences, and I am trying to use Stanford Core NLP. I have downloaded the library. Since its a Java library I am using PHP's exec command (please see below) to call it. My PHP script works well and I can parse a text into sentences. Currently, the script needs an input file to be parsed. My question is if I can use a PHP string variable instead of input .txt file. It will be very convenient for me since I will be using mysql db to retrieve text/string. If it is not possible, then I would need to create a corresponding text file for the command line input. Any feedback you provide will greatly be appreciated.
Here is my small PHP script
$text = "Maria and Ted Bobola grow sweet corn. But with little corn to harvest because of a plant-withering drought, the Bobolas were forced to buy corn from Georgia to supply their produce and flower shop just outside Dover. And most years, the strawberry picking season runs three to five weeks, but not this year, store manager Dee Chambers said. ``It was so hot and dry that even though we irrigated, we had only two weeks in the season,'' she said. They did not recoup $70,000 they paid for strawberry plants last year in this year's harvest.";

$parser = "stanford-corenlp-3.5.0.jar";
$class = "edu.stanford.nlp.process.DocumentPreprocessor";
$input = "sample.txt";
$output = "output.txt";
if (exec( "java -cp $parser -Xmx2g $class -file $input", $result))
    {
        echo "success";
    }
    else
    {
        echo "failure";
    }

// Optional
echo '<pre>' . print_r($result, true);

What I am trying to do here is replacing $input (i.e. txt file) with $text (i.e. a php variable).


text:
Q: How do I disable line numbers in an Octopress codeblock? I see some Octopress sites that have no line numbers in their codeblocks. How do you do that? Is there some attribute in {% codeblock %} tag? Or do I have to modify the codeblock plugin source?

A: Using blockquotes through 4 space indentation should do what you're looking for, but it'll be without syntax highlighting.
If you're fine with losing line numbers everywhere, you can modify plugins/pygments_code.rb and remove the bit of code that generates line numbers.

A: A patch for pygments_code.rb as suggested by bilalq above (sorry, too big to fit in the comments of his answer)
--- a/plugins/pygments_code.rb
+++ b/plugins/pygments_code.rb
@@ -29,11 +29,11 @@ module HighlightCode
     end
     highlighted_code
   end
+
   def tableize_code (str, lang = '')
-    table = '

'
+    table = '

'
     code = ''
     str.lines.each_with_index do |line,index|
-      table += "#{index+1}\n"
       code  += "#{line}"
     end
     table += "

#{code}

"

A: If you use the kramdown markup engine, it comes with an option you set in your _config.yml file, coderay_line_numbers:
markdown: kramdown
kramdown:
  use_coderay: true
  coderay:
    coderay_line_numbers:
    coderay_css: class

It can be set to nil (as in this example), inline, table or list. Maybe the blogs you have been seeing without line numbers use this method.
You can see some screenshots of the different options in my blog post about kramdown in Octopress.

A: Simply add:
pre.line-numbers { display: none; }

to sass/custom/_styles.scss.
This is from a comment on one of the answers by @bilalq , but I think it's the best, simplest, and most sane answer around (sane as in you want to keep your customizations under sass/custom/).


text:
Q: Terminal control library that blocks on both input and some custom data channel? ncurses' blocking mode appears to only allow for blocking on stdin - that is, I have no option of doing some select()-esque thing where getch() blocks until either a key is pressed or e.g. data arrives in a pipe. Am I missing something, or is there some other terminal control library that allows me to do this?
Edit: I'm targeting Linux platforms, although the more general the solution, the better.

A: There's an experimental configure-option, which is rarely used:

--enable-wgetch-events
  Compile with experimental wgetch-events code. See ncurses/README.IZ


text:
Q: Resetting OutputStream so updated variables send I've come across an issue when sending an object over a local connection. The object will send the first time as expected. However variables of the object are constantly being changed therefore need to be updated when sending to the other connection. This is done through sending messages prompting the other client to listen and wait for the object being sent.
I'm aware that the java.io.ObjectOutputStream.reset() method exists but keep getting the following error:
error: cannot find symbol
         output.reset();

Here's how the code is currently structured (Minus lots of non relevant code):
import java.net.*;
import java.util.*
import java.io.*;

public class Client
{
    private static Socket cSocket = null;
    private static ObjectOutput output = null;

    private static Person myPerson = null;

    private static String serverHost = "localhost";

    public void Run()
    {
         // Declaring the output
         output = new ObjectOutputStream(
            cSocket.getOutputStream()
         );

    }

    private static void sendPerson()
    {
       try
       {
          output.writeObject( myPerson );
          output.reset();
       } catch (Exception e)
       {

       }
    }
}

TLDR: Each time sendPerson() is called the other client receives the first object sent to the other client rather than the updated variables. Tried using reset(); but error is thrown.
Would just like the objects updated variables to be sent rather than the initial object always being sent.

A: To use ObjectOutputStream#reset you have to define your field with such type.
Not ObjectOutput, but ObjectOutputStream.
Like this:
private static ObjectOutputStream output = null;


text:
Q: Idealizer of one-sided ideal Let $A$ be a ring and let $J$ be a right-sided ideal of $A$. We call the set $I_{A}(J)=\lbrace a \in A \mid aJ\subset J\rbrace$ the idealizer of $J$.
Show that $I_{A}(J)$ is the largest subring of that $A$ containing $J$ as an ideal.

A: $I_A(J)$ is a subring of $A$:
Let $s,r\in I_A(J)$. Then $(r+s)J = rJ + sJ \subset J$ and $(rs)J = r\cdot sJ \subset rJ \subset J$, so $I_A(J)$ is closed under addition and multiplication.
$I_A(J)$ contains $J$ as a two-sided ideal:
This follows directly from the definition of $I_A(J)$.
$I_A(J)$ is the largest subring of $A$ containing $J$ as a two-sided ideal:
Let $S$ be a subring of $R$ such that $I_A(J)$ is a two-sided ideal in $S$. Then for all $s\in S$, $sJ \subset J$, showing that $S \subset I_A(J)$.


text:
Q: Checking to see if a generic class is inherited from an interface I've got a class that inherits from an interface. That interface defines an event that I'd like to subscribe to in the calling code. I've tried a couple of things, but they all resolve to false (where I know it's true). How can I check to see if a class implements a specific interface.
Here's what I've tried (note, the object in question is a usercontrol that implements MyInterface, stored in an array of controls, only some of which implement MyInterface - it is not null):
if (this.controls[index].GetType().IsSubclassOf(typeof(MyInterface)))
    ((MyInterface)this.controls[index]).Event += this.Handler;

if (this.controls[index].GetType().IsAssignableFrom(typeof(MyInterface)))
    ((MyInterface)this.controls[index]).Event += this.Handler;

if (this.controls[index].GetType() == typeof(MyInterface))
    ((MyInterface)this.controls[index]).Event += this.Handler;

All to no avail.

A: if (typeof(MyInterface).IsAssignableFrom(this.controls[index].GetType()))
    ((MyInterface)this.controls[index]).Event += this.Handler;

You just have the IsAssignableFrom inverted.

For your case, however, the best way to do this test is the following for performance and clarity improvements:
if (this.controls[index] is MyInterface)

A: I might be being dense but can't you just do:
MyInterface foo = this.controls[index] as MyInterface;
if (foo != null) { /* do stuff */ }

(and of course the real MyInterface should have a name starting with I)


text:
Q: MongoDB Aggregate нужен совет Есть 2 коллекции, hash_collection и task_to_hash, необходимо создать агрегат, в который войдут все документы из hash_collection, _id которых нет в документах task_to_hash в поле "hash", голову сломал уже.
filter := bson.D{{}}
opt := options.Aggregate().SetAllowDiskUse(true)
lookupStage := bson.D{{"$lookup", bson.D{{"from", "task_to_hash"}, {"localField", "_id"}, {"foreignField", "hash"}, {"as", "exist"}}}}
    matchStage := bson.D{{"$match", bson.D{{"exist", bson.D{{"$eq", bson.A{}}}}}}}
    limitStage := bson.D{{"$limit", 10}}
    showLoadedCursor, err := hash_collections.Aggregate(context.TODO(), mongo.Pipeline{lookupStage, matchStage, limitStage}, opt)
    if err != nil {
        panic(err)
    }

Буду благодарен за совет.


text:
Q: DIY rounding function gives weird values I've coded this simple function to round doubles to a custom step size.
The normal .round() function retuns an int and can only rounds to the nearest 1.
My function returns a double and can round to the nearest 100.0, 5.0, 1.0, 0.1 or 0.23, you get it.
But when I put in certain doubles the result doesn't really work out and is a very tiny fraction off.
I think this has something to do with how computers do floating comma calcualations, but I need an efficient way to get around it.
Run on DartPad
void main() {
  stepround(61.337551616741315, 0.1); // this should be 61.3 but is 61.300000000000004
}

/// rounds a double with given steps/precision
double stepround(double value, double steps) {
  double rounded = (value / steps).round() * steps;
  print(value.toString() + " rounded to the nearest " + steps.toString() + " is " + rounded.toString());
  return rounded;
}

A: As mentioned in the comments, the cause of this issue the way that computers deal with floating numbers. Please refer to the links in the comments for further explanation.
However in a nutshell the problem is mostly caused when dividing or multiplying decimals with decimals. Therefore we can create a similar method to the one you created but with a different approach. We we will take the precision to be as an int.
I.e: 0.1 => 10; 0.001 => 1000
double stepround(double value, int place){
   return (value * place).round() / place;
}

Example
// This will return 61.3
stepround(61.337551616741315, 10);

// This will return 61.34
stepround(61.337551616741315, 100);

// This will return 61.338
stepround(61.337551616741315, 1000);

This method works since the small fraction that is caused by the multiplication is removed by round(). And after that we are doing a division by an integer which doesn't create such a problem.


text:
Q: How can I maintain linear independence through a commutator? Consider a Lie algebra $\mathcal{L}$, a linearly independent generating set $\mathcal{G}$, and an element $X \in \mathcal{L}$.
Edit: Note that $\mathcal{G}$ is not necessarily a basis; the generation is via the Lie bracket.

What are the conditions on $X$ such that $\{[X,g_i]\; \big| \; g_i \in \mathcal{G}\}$ is also linearly independent?

Or is the question too general and the answer must depend on $\mathcal{G}$? In my specific case I am looking at the Lie algebra $\mathfrak{sp}(2n,\mathbb{R})$ if that helps. Also maybe there is a more general answer for any given set of matrices but this is my specific problem.

A: Since $\mathcal{G}$ is a basis, we can write $X\neq 0$ as a non-trivial linear combination of elements of $\mathcal{G}$. Then $ad(X)(\mathcal{G})=\{[X,g_i] \mid g_i\in \mathcal{G}\}$ represents $0=[X,X]$ also non-trivially. Hence this set cannot be linearly independent. In formulas: if $X=a_1g_1+\cdots +a_ng_n$, where not all $a_i=0$, then
\begin{align*}
a_1[X,g_1]+\cdots a_n[X,g_n] & = [X,a_1g_1+\cdots +a_ng_n]\\
 & = [X,X]\\
 & = 0.
\end{align*}


text:
Q: OneDrive Rest Api View changes for rename and move I use rest api "https://api.onedrive.com/v1.0/drive/root/view.delta?token=***"     "reference page" to get oneDrive files changes, it work for add file or folder or delete, but i need to get old path and new path for move, and get old name and new name for renamed file or folder.
Is there any way to get the rename and move changes?

A: The API doesn't return / track the old-state of items.
To accomplish this, you need to maintain that state in a cache by tracking items with their unique identifier. You can then process the changes coming from the delta API, and when the change record is returned to you, you can evaluate your current state vs. the new state provided by the delta API, and use that to have the old-name and new-name, or old-path and new-path.


text:
Q: Workflow for importing a flexviewer website into Flashbuilder 4 I have websites built using the flexviewer, but would like to import them into Flashbuilder 4 in order to enhance them. Is there a way to do this by importing the .xml or config.xml from the compiled flexviewer? Or is the workflow to build custom widgets in flashbuilder and deploy them to the flexviewer?

A: *

*in Flash Builder 4, Go to File Menu -> Import -> Flash Builder project.

*Keeping "File" option selected, click "Browse..." button.

*Select flexviewer-2.3-src.zip downloaded in step 1, e.g. "C:\Documents and Settings\username\My Documents\flexviewer-2.3-src.zip".

*"Extract new project to:" textbox will be automatically set to location where the project source will reside,
e.g. "C:\Documents and Settings\username\Adobe Flash Builder 4\FlexViewer.
Do not put it onto your web server - you should separate your code location from your output.

*Click "Finish" button. Project will be created and displayed in the Package Explorer window of Flash Builder 4, e.g. in this case FlexViewer.
source
http://www.arcgis.com/home/item.html?id=3f6a0bfee48949a88df50bf7686ec72a
(April 15, 2011) unzip flexviewer-2.3-src.zip (readme.txt)

A: You will really want to review the ESRI docs @ Resources.ArcGIS.com
There you will find not only the Source code for the Flex-Viewer, but also complete walk-through for building your first Widget, and how to install/configure it.


text:
Q: Parameters to program in C with Linux How can I send parameters to main in C(Linux):
first one is -c or -d
second is a string like file.
How I'm doing that?

A: First, send data to your program using command line argument Like @haccks said
Second, get the arguments in your code using :
int main(int argc, char **argv)

Tutorial Here


text:
Q: error: control may reach end of non-void function in Luhn's alghoritm bool if_valid(long n) //Implementing the Luhn's alghoritm
{
    int odd = 0;//Will take the sum of the numbers in the 1,3,5,7... th digits
    int even = 0;//Will take the sum of the numbers in the 2,4,6,8... th digits
    for(int k = 1; (n / 10) >= 1; k ++)//My main idea is, take the modulo 10 of the number, subtract
    the remainder from the number and divide the number by 10.
    {
        if (k % 2 == 1)
        {
            int r = n % 10;//Remainder
            odd += r;
            n -= r;
            n /= 10;//Number's digit is increased
        }
        else
        {
            int r = n % 10;
            n -= r;
            n /= 10;
            r *= 2;
            if(r >= 10)
            {
                even += r % 10;
                r -= r % 10;
                r /= 10;
                even += r % 10;

            }
            else
            {
                even += r % 10;
            }
        }
        even = even + odd;
        if(even % 10 == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

I was trying yo check if a credit card number is valid or not. I am getting control may reach end of non-void function error but as i am a fresh c coder i didn't understand why my function isn't working. Could you please help me?


text: Q: O que são "expressões" em javascript? Eu gostaria de saber o que são "expressões" e "expressões primárias" em javascript. O site da mozilla traz como exemplo de expressão x = 7 e 3 + 4, porém na parte de "expressões primárias" ele mostra o "this" que é uma palavra reservada e que não tem nada a ver com x = 7 ou 3 + 4 e mostra o "()" (operador de agrupamento).Se possível também explicar o que é "expressão lado esquerdo" que também é apresentado no site.


text:
Q: Why can't I rename the import of @BeanProperty in Scala In Scala it is possible to use renaming in import statements.
However, it doesn't work with the @BeanProperty-Annotation.
This (admittedly pretty useless) piece of code:
import java.lang.{ Deprecated => D }
import scala.beans.{ BeanProperty => B }

object Foo {
  @D
  val bar = 1;

  @B
  val baz = 2;
}

yields a compilation error for the use of @B: "implementation limitation: the BeanProperty annotation cannot be used in a type alias or renamed import". Renaming @Deprecated does work.
What is the technical reason for this limitation?

A: The scala compiler is architected according to the "wing it" model. In this case that means the decision as to whether to synthesize getters and setters is made before symbols are available, so it attempts to identify @BeanProperty annotations based on whether they spell out "BeanProperty".
In other words it's not a real annotation - it's a pattern match on source code.
def hasAnnotationNamed(name: TypeName) = {
  annotations exists {
    case Apply(Select(New(Ident(`name`)), _), _)     => true
    case Apply(Select(New(Select(_, `name`)), _), _) => true
    case _                                           => false
  }
}


text:
Q: Installing Ubuntu on devices error - fork/exec /usr/bin/xz: cannot allocate memory I'm trying to install Ubuntu in my nexus 10.
I went through all steps with out any problems except at the end "Install Ubuntu using your selected channel, in this case we use the devel channel".
Here is the result from the terminal.
michi@ubuntu:~/Downloads$ ubuntu-device-flash --channel=devel --bootstrap
DEPRECATED: Implicit 'touch' subcommand assumed
2014/11/10 09:52:04 Expecting the device to be in the bootloader... waiting
2014/11/10 09:52:04 Device is |manta|
2014/11/10 09:52:04 Flashing version 243 from devel channel and server https://system-image.ubuntu.com to device manta
/home/michi/.cache/ubuntuimages/ubuntu-touch/devel/manta/version-243.tar.xz
2014/11/10 09:52:15 copied 0 bytes with err: fork/exec /usr/bin/xz: cannot allocate memory
michi@ubuntu:~/Downloads$

Can anyone help me through this problem?


text:
Q: Проблема со $stateProvider Angular JS Имеются три $stateProvider, но работает только первый. Может быть кто-нибудь сталкивался с подобной проблемой? P.S. В index.html все прописано.
'use strict';

angular.module('Libraries', ['angular-sha1', 'ui.router', 'utils', 'ngCookies']);

angular.module('Login', []);
angular.module('Dashboard', []);
angular.module('UserDashboard', []);

var app = angular.module('main', ['Login', 'Dashboard', 'Libraries','UserDashboard'])

.config(function ($stateProvider, $urlRouterProvider, $httpProvider) {
    $urlRouterProvider.when('', '/login').when('/', '/login');

    $stateProvider.state('login', {
            url: '/login',
            controller: 'LoginController',
            templateUrl: '/angular/templates/states/login.html'
        });
    $stateProvider.state('dashboard', {
            url: '/dashboard',
            controller: 'DashboardController',
            templateUrl: '/angular/templates/states/dashboard.html'
        });
    $stateProvider.state('userdashboard', {
            url: '/userdashboard',
            controller: 'UserDashboardController',
            templateUrl: '/angular/templates/states/userdashboard.html'
        });

    $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

}).run(function ($rootScope, utils) {
});


text:
Q: Padding is not showing in chrome but showing in firefox I am adding padding on select box option. But the padding is showing only on Firefox but now showing on chrome i try plenty of things but not working for me so anyone tell me what to do to add padding on chrome This is the Link at bottom you can see the dropdown
This is the code which i am using
select#input_1_1 option {
    padding: 10px 30px !important;
}

A: Firefox allows giving CSS padding to select and option tags, but Chrome doesn't. Period.


text:
Q: Bison pseudo-variables returns wrong value I have strange problem with Bison. I'm begginer, so correct me if I'm wrong, but $1,$2...and so on should return values from first, second and so on terminal/nonterminals, yes?
command: IDENT{printf("%s",$1);} SET{printf("%s",$1);} expression{printf("%s",$1);} ENDCMD

I doing compilator, and i traped because from above example, I had for expression like "a := 1" (where ident is "a", set is ":=" and num is "1") "a" in first call, "a :=" in second and "a := 1" in third.
%union {
    int ival;
    char *sval;
}

ident is sval.
Important thing, I think, is that i recently add string to my bison file. Previously everything was ok.

A: Ok. Now I should blame myself. I dig deeper in stackoverflow and found that: http://www.gnu.org/software/bison/manual/html_node/Strings-are-Destroyed.html. Whats of course a


text:
Q: How do I implement full text search in Chinese on PostgreSQL? This question has been asked before:
Postgresql full text search in postgresql - japanese, chinese, arabic
but there are no answers for Chinese as far as I can see. I took a look at the OpenOffice wiki, and it doesn't have a dictionary for Chinese.
Edit: As we are already successfully using PG's internal FTS engine for English documents, we don't want to move to an external indexing engine. Basically, what I'm looking for is a Chinese FTS configuration, including parser and dictionaries for Simplified Chinese (Mandarin).

A: I know it's an old question but there's a Postgres extension for Chinese: https://github.com/amutu/zhparser/

A: I've just implemented a Chinese FTS solution in PostgreSQL.  I did it by creating NGRAM tokens from Chinese input, and creating the necessary tsvectors using an embedded function (in my case I used plpythonu).  It works very well (massively preferable to moving to SQL Server!!!).

A: Index your data with Solr, it's an open source enterprise search server built on top of Lucene.
You can find more info on Solr here:
http://lucene.apache.org/solr/
A good book on how-to (with PDF download immediately) here:
https://www.packtpub.com/solr-1-4-enterprise-search-server/book
And be sure to use a Chinese tokenizer, such as solr.ChineseTokenizerFactory because Chinese is not whitespace delimited.


text:
Q: shortestpath with OrientDB very slow With OrientDB and Java I have a program with this query to calculate the shortest path to 300000 nodes for the all pairs of nodes but the program is very slow someone can help me.
String query = "select expand(shortestPath("+source.getId()+","+dest.getId()+",'OUT'))";


text:
Q: Spring REST Repositories inheritance null values i have some trouble with mapping parent-child classes in Spring Rest Repositories. My case is that i need to authenticate both types of user with Spring Security, but i want also to be able to assign type specific attributes like Pets to Owner and salary for Employee. Is that good structure to accomplish such goal? If so, please help with that problem.
I already made it to insert into one table differentiating one from eachother with dtype column, but cant manage to insert any other values than dtype.
I'm using newest Spring Boot (default JSON mapper) with MS SQL.
This is my payload for POST request:
{
    "username": "admin",  // null in db
    "firstName": "Delacruz", // null in db
    "lastName": "House", // null in db
    "dtype": "Owner" // present in db
}

This is my class structure:
Repository
@RepositoryRestResource(path = "user", collectionResourceRel = "user")
public interface UserRepository extends PagingAndSortingRepository<User, Long> {
}

Parent class - User
@Entity
@Table(name = "users")
@Inheritance
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME,
        include=JsonTypeInfo.As.EXISTING_PROPERTY,
        property="dtype")
@JsonSubTypes({
        @JsonSubTypes.Type(name="Owner", value=Owner.class),
        @JsonSubTypes.Type(name="Employee", value=Employee.class)})
@RestResource(path="user")
public abstract class User{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column
    private String username;
// rest of properties
}

Employee - first child class
@EqualsAndHashCode(callSuper = true)
@Entity
@Data
public class Employee extends User {

    private String type = "EMPLOYEE";

    @Column
    @Enumerated
    private EmployeeType employeeType;

    @Column
    private LocalDate dateOfEmployment;
    //rest of properties
}

Owner - another child class
@EqualsAndHashCode(callSuper = true)
@Data
@Entity
public class Owner extends User{
    @OneToMany(mappedBy = "owner")
    private List<Pet> pets;
}

A: Adding following constructor (accordingly to Owner) to subclasses resolved issue:
@JsonCreator
public Employee(
        @JsonProperty(value = "username") String username,
        @JsonProperty(value = "firstName") String firstName,
        @JsonProperty(value = "lastName") String lastName,
        @JsonProperty(value = "password") String password,
        @JsonProperty(value = "email") String email,
        @JsonProperty(value = "phoneNumber") String phoneNumber
) {
    super(username, firstName, lastName, password, email, phoneNumber);
}


text:
Q: R: simulating a population where two categorical variables are independent Background
For teaching purpose, I use simulations (mainly in R) to help students (in the social science...no math or stats background) grasping some "tough" concepts/ideas behind some stats topics. I am planning to lecture about chi-squared test of independence, and I have prepared a small 2x2 contingency table which cross-tabulates GENDER (two levels: M and F) vs. POLITICAL AFFILIATION (two levels: PartyA, PartyB). In this toy dataset, there is a significant dependence.
Goal I have in mind
In order to help students understanding the sampling distribution of the chi-squared statistic under the Null Hypothesis, I would like to simulate a population in which the above-mentioned two variables are independent. I would like to do so so that: (1) I can randomly draw a random sample, cross-tabulate the two variables, and show that the chi-sq test turns to be not significant, and (2) I can draw B random samples, calculate the chi-squared statistic B times, and plot a frequency distribution histogram of those B chi-square values (this should represent the sampling distribution of chi-sq under the Null Hypothesis).
Where I need help
I cannot figure out a way of simulating a population where those 2 categorical variables are independent. Ideally, I would like to come up with a dataframe with a number of rows and two columns: each row would represent an observation (an individual in our case), while each column would store (for each observation) a level of each categorical variable being analyzed (i.e., the GENDER and the POLITICAL AFFILIATION).

A: You can use sample with the replace = argument set as TRUE, and combine the new vectors into variables with data.frame:
dat <- data.frame(gender = sample(c("F", "M"), size = 1000, replace = TRUE),
                  party = sample(c("Party A", "Party B"), size = 1000, replace = TRUE))

Because you're generating these two variables separately, they won't be associated with one another.


text:
Q: How would you go about executing a database query based on the value from a form select element? I am using ColdFusion as my application server and SQL Server for the database. I have a select form element which lists a number of vehicles: Volvo S60, BMW M6, VW Jetta.
Based on what vehicle the user selects, I need my webpage to perform a database query to find out what 'type' of vehicle they selected e.g. SUV, Coupe, Convertible.  Depending on what 'type' is returned from the database, the database will return a list of options suitable for that vehicle type. My database tables can do this based on the vehicle drop-down's value so that's all good.
Now then, I want to now list the available options for that vehicle 'type' as a group of checkboxes. Doing this should be a simple case of looping through the database resultset and generating a checkbox for each row.
I want to do this without refreshing the page. How do I dynamically get the value from the  drop-down, pass this value to the database, get the result back and then show the appropriate checkboxes?

A: I mentioned in my earlier comment that the simplest way to do this in ColdFusion was to bind your form elements to cfc methods.  A google search on "cfinput bind" will lead to lot's of examples, but since I was asked to provide an answer, I'll show an example I once wrote.  It's not exactly what the OP wants, but it shows the general idea.  It will populate one text box based on the value of another.
Note that the cfc and cfm files have to be in the same directory.
.cfm file

Clinic Code <input name="clinicCode" type="text" />

Patient Satisfaction Name <cfinput type="text"
name="NameOfClinic"
bind="cfc:PatientSatisfactionClinics.GetClinicName({clinicCode})"
bindonload="no">

.cfc file
<cffunction name="GetClinicName" access="remote" returntype="string">
<cfargument name="clinicCode" type="string" required="yes">
<cfscript>
var clinicName = QueryNew("a");
var returnString = "No Record for Clinic Code " & arguments.clinicCode & ".";
var clinicCodeAsInt = 0;

if (isNumeric(arguments.clinicCode)
and round(arguments.clinicCode) is arguments.clinicCode)
clinicCodeAsInt = arguments.clinicCode;
</cfscript>

<cfif clinicCodeAsInt gt 0>
<cfquery name="clinicName" datasource="dw">
select name
from patient_satisfaction_clinic
where clinic_code =
<cfqueryparam cfsqltype="cf_sql_integer" value="#clinicCodeAsInt#">
</cfquery>

<cfif clinicName.recordcount gt 0>
<cfset returnString = clinicName.name[1]>
</cfif>
</cfif>

<cfreturn returnString>

</cffunction>

A: There's an example of what you need to do in the Adobe ColdFusion docs for <cfajaxproxy>, which demonstrate the necessary techniques. This does not do exactly what you want, but it's a matter of changing the mark-up from just plain text to checkboxes to fit your requirement. it's too much code to reproduce here, but the key is that you use <cfajaxproxy> to set up a proxy between the JS on the client side and a CFC on the server side to enable the JS to retrieve data from the server.
Using <cfajaxproxy> negates the need to roll your own JS AJAX treatment, or use JQuery (etc) to do so. That said, doing it by hand is not too difficult... it'd be easy enough to employ the techniques demonstrated in that doc to decouple CF from the front-end code completely (there's a good case for not using CF to do client-side stuff)... it all just boils down to having event handlers listening to the relevant events, and then making some manner of AJAX call back to the server to get the data, then bung it in a
 or something. In this case CF only rely provides the proxying bit: you still need to do the rest yerself.

A: Ok, here is what I did which seems to work for me so far. But I am going to review Adam's and Dan's kind answers.
I created a form on my Vehicle.cfm page with all my form elements, except the checkboxes.
I created a new CFM template called vehicleOptions.cfm which accepts a parameter, runs a SQL query, and then outputs the actual HTML to create the checkboxes.
I then went to the area in my form on Vehicle.cfm page where I wanted my checkboxes to appear and typed in this:
<cfdiv bind="url:cfincludes/vehicleOptions.cfm?VehicleModel={Model}" />
'Model' is the ID of the  element on my form which holds the value for which vehicle a user has selected. So now whenever a user changes the Model in the drop-down list the  area updates with different checkboxes each time. Its really wonderful and I didn't have to write a single line of Javascript!
This solution works for what I want, but I am guessing it is not the most elegant use of ColdFusion AJAX? As I said I will review the answers and try to work out a better solution. Thanks for all your help fellow CF devs!

A: It's easy. Each option should have the value encoded in it, e.g.
<select>
<option class="car" name="car" value="volvo">Volvo</option>
<option class="car" name="car" value="honda">Honda</option>
<option class="car" name="car" value="ford">Ford</option>
</select>

Then, you use jQuery.
$('#go').on('click', function() {
    var car = $('.car:selected').val();
    // make ajax call here
});

Here's a working example: http://jsfiddle.net/Yxmjk/. It doesn't demonstrate the AJAX call, but it demonstrates how you would get the data that you include in your AJAX call.


text:
Q: How do I get all values of each Extension_ID I have a multitenant schema and here is my Query to retrieve the Column name from 1 table and values from another table.
SELECT
MAX(CASE WHEN TME.EXTENSION_ID = '555' THEN EXT.value END) A,
MAX(CASE WHEN TME.EXTENSION_ID = '556' THEN EXT.value END) B,
MAX(CASE WHEN TME.EXTENSION_ID = '559' THEN EXT.value END) C,
MAX(CASE WHEN TME.EXTENSION_ID = '560' THEN EXT.value END) D,
MAX(CASE WHEN TME.EXTENSION_ID = '557' THEN EXT.value END) E,
MAX(CASE WHEN TME.EXTENSION_ID = '558' THEN EXT.value END) F,
MAX(CASE WHEN TME.EXTENSION_ID = '561' THEN EXT.value END) G,
MAX(CASE WHEN TME.EXTENSION_ID = '562' THEN EXT.value END) H
 FROM TENANTDATAEXTENSION EXT, TENANTMETADATAEXTENSION TME
 WHERE TME.EXTENSION_ID = EXT.EXTENSION_ID;

This only returns 1 row of each Extension_ID. But, I have more than 1 rows. How do I get all?
Current Output:
Column Name:    A    B    C    D     E    F     G     H
Column Values:  A1   B1   C1   D1    E1   F1    G1    H1

Expected Output:
Column Name:    A    B    C    D     E    F     G     H
Column Values:  A1   B1   C1   D1    E1   F1    G1    H1
                A2   B2   C2   D2    E2   F2    G2    H2
                A3   B3   C3   D3    E3   F3    G3    H3

TENANTDATAEXTENSION Table looks like this:
Column Name: Extension_ID Extension_Label
Column Values:
                555      A
                556      B
                557      E
                558      F
                559      C
                560      D
                561      G
                562      H

TENANTMETADATAEXTENSION Table looks like this:
Column Name: Extension_ID Value.

Column Values:
                555      A1
                555      A2
                555      A3
                556      B1
                556      B2
                556      B3
                557      E1
                557      E2
                557      E3
                etc.........

A: See if the below code meets your needs.
SET @ext_id = '***';
SET @level = 0;

SELECT
    MAX(CASE WHEN ext.EXTENSION_ID = '555' THEN tme.value ELSE '' END) A,
    MAX(CASE WHEN ext.EXTENSION_ID = '556' THEN tme.value ELSE '' END) B,
    MAX(CASE WHEN ext.EXTENSION_ID = '559' THEN tme.value ELSE '' END) C,
    MAX(CASE WHEN ext.EXTENSION_ID = '560' THEN tme.value ELSE '' END) D,
    MAX(CASE WHEN ext.EXTENSION_ID = '557' THEN tme.value ELSE '' END) E,
    MAX(CASE WHEN ext.EXTENSION_ID = '558' THEN tme.value ELSE '' END) F,
    MAX(CASE WHEN ext.EXTENSION_ID = '561' THEN tme.value ELSE '' END) G,
    MAX(CASE WHEN ext.EXTENSION_ID = '562' THEN tme.value ELSE '' END) H
FROM TENANTDATAEXTENSION ext
LEFT JOIN
 ( SELECT CASE WHEN @ext_id <> tme.extension_id THEN @level := 0 ELSE @level := @level +1 END level,
        @ext_id := tme.extension_id extension_id,
        tme.value
 FROM TENANTMETADATAEXTENSION tme
 ORDER BY extension_id, value ) tme
ON ext.extension_id = tme.extension_id
GROUP BY tme.level
HAVING CONCAT(A, B, C, D, E, F, G, H) <> ''

Here's SQL Fiddle DEMO
You may want to try your test cases there.


text:
Q: Uniform distribution on the unit sphere rotated by a random orthogonal matrix Question 1. Let $u\in \mathbb{R}^n $ be a random vector uniformly distributed on $\mathbb{S}^{n-1}$, and $T\in \mathbb{R}^{n\times n}$ be a random orthogonal matrix. If $u$ and $T$ are independent, is $Tu$ uniformly distributed on $S^{n-1}$ and statistically independent of $T$?
I get this question when thinking about the following one.
Question 2. Let $u, v\in\mathbb{R}^n$ be two independent random vectors, and $u$ be uniformly distributed on $\mathbb{S}^{n-1}$. Consider the inner product $u^\top v$. Take a constant vector $v_0\in \mathbb{S}^{n-1}$. It seems that

*

*$u^\top v$ has the same distribution as $u^\top v_0$;

*$u^\top v$ and $v$ are statistically  independent.

Is this true?
Towards a positive answer to Question 2, we let $T$ be the Housholder matrix such that $Tv = v_0$. Note that $T$ is independent of $u$. Then
$$
u^\top v = u^\top (T^\top v_0) = (Tu)^\top v_0.
$$
If the answer to Question 1 is yes, then $Tu$ and $u$ are identically distributed, and $Tu$ is independent of $v$, and hence the answer to Question 2 is yes. (BTW, are Question 1 and Question 2 equivalent?)
Any comments or criticism will be appreciated. Thank you.
(A different but related question: $X$ is independent of $\mathcal{G}$, $f(X ,Y)$ is independent of $Y$, $Y$ is $\mathcal{G}$-measurable, then $f(X,Y)$ is independent of $\mathcal{G}$?)

A: Let $X$ be a standard Gaussian in $\mathbb{R}^n$. In spherical coordinates, this may be expressed as $(R,u)$ where $R \in [0,\infty)$ and $u$ are independent, and $u$ is uniform on $\mathbb{S}^{n-1}.$
Let $\mathbf T$ is a random orthogonal matrix independent of $X$, with law $\mu$. Notice that $|\det(T)| = 1$ for any orthogonal matrix. So, using Fubini's theorem a couple of times, and a change of coordinates $$P(\mathbf{T}X \in A) = \int_T\int_{x \in T^{-1}(A)} e^{-\|Tx\|^2/2}\mathrm{d}x\,\mu(\mathrm{d}T) = \int_T\int_{y \in A} e^{-\|y\|^2/2}\,\mathrm{d}y\,\mu(\mathrm{d}T)\\ = \int_{x \in A} e^{-\|x\|^2/2}\mathrm{d}x = P(X \in A),$$ and so $\mathbf{T}X$ is also a standard Gaussian. But $\mathbf{T} (R,u) = (R, \mathbf{T} u),$ since $\mathbf{T}$ is norm preserving, so it follows that $\mathbf{T}u$ has the same law as $u$.
Finally, notice that the above calculation was completely agnostic to the law of $T$. This implies that if I replaced the law of $T$ with something else - for instance a conditional law given that $T$ lies in some set, I'll get the same calculation out. Of course this means that $$ P(\mathbf{T} X \in A| \mathbf{T} \in \tau) = P(X \in A) = P(\mathbf{T}X \in A).$$ It follows that $\mathbf{T}X,$ and thus $\mathbf{T}u,$ are indepdendent of $\mathbf{T}$.

A: The answer to question #1 is yes.  Here's the proof.
Let $\mu$ be the uniform distribution on $S^{n-1}$, and let $\nu$ be the distribution for $T$ on $O(n)$.  Given any measurable set $A\subseteq S^{n-1}$, let
$$
A' = \{(u,T)\in S^{n-1}\times O(n) \mid T(u)\in A\}
$$
and let $I_{A'}$ be the indicator function for $A'$.  Then
$$
P(v\in A) = (\mu\times \nu)(A') = \int_{S^{n-1}\times O(n)} I_{A'} d(\mu\times \nu) = \int_{O(n)} \int_{S^{n-1}} I_{A'}(u,T)\,\mu(du)\,\nu(dT)
$$
But for any $T\in O(n)$, we have
$$
\int_{S^{n-1}} I_{A'}(u,T)\,\mu(du) = \mu(T^{-1}(A)) = \mu(A)
$$
where the last equality follows from the fact that $\mu$ is invariant under the action of $O(n)$.  We conclude that
$$
P(v\in A) = \int_{O(n)} \mu(A)\,\nu(dT) = \mu(A).
$$
This holds for every measurable set $A\subseteq S^{n-1}$, so the distribution for $v$ is also $\mu$.
For independence of $v$ and $T$, let $A$ be any measurable subset of $S^{n-1}$, let $A'$ be as above, let $B$ be any measurable subset of $O(n)$, and let $B'=S^{n-1}\times B$.  Then
\begin{align*}
P(v\in A\text{ and }T\in B) &= \int_{S^{n-1}\times O(n)} I_{A'} I_{B'}\, d(\mu\times \nu) \\[6pt]
&= \int_{O(n)}\int_{S^{n-1}} I_{A'}(u,T)\, I_{B'}(u,T) \,\mu(du)\,\nu(dT) \\[6pt]
&= \int_{O(n)}\int_{S^{n-1}} I_{A'}(u,T)\, I_{B}(T) \,\mu(du)\,\nu(dT) \\[6pt]
&= \int_{O(n)} I_B(T) \int_{S^{n-1}} I_{A'}(u,T) \,\mu(du)\,\nu(dT) \\[6pt]
&= \int_{O(n)} I_B(T) \,\mu(A)\,\nu(dT) \\[6pt]
&= \mu(A)\, \nu(B) \\[6pt]
&= P(v\in A)\,P(T\in B).
\end{align*}


text:
Q: Dynamically create / draw images to put in android view I'm not sure I'm doing this the "right" way, so I'm open to other options as well. Here's what I'm trying to accomplish:
I want a view which contains a graph. The graph should be dynamically created by the app itself. The graph should be zoom-able, and will probably start out larger than the screen (800x600 or so)
I'm planning on starting out simple, just a scatter plot. Eventually, I want a scatter plot with a fit line and error bars with axis that stay on the screen while the graph is zoomed ... so that probably means three images overlaid with zoom functions tied together.
I've already built a view that can take a drawable, can use focused pinch-zoom and drag, can auto-scale images, can switch images dynamically, and takes images larger than the screen. Tying the images together shouldn't be an issue.
I can't, however, figure out how to dynamically draw simple images.
For instance: Do I get a BitMap object and draw on it pixel by pixel? I wanted to work with some of the ShapeDrawables, but it seems they can only draw a shape onto a canvas ... how then do I get a bitmap of all those shapes into my view? Or alternately, do I have to dynamically redraw /all/ of the image I want to portray in the "onDraw" routine of my view every time it moves or zooms?
I think the "perfect" solution would be to use the ShapeDrawable (or something like it to draw lines and label them) to draw the axis with the onDraw method of the view ... keep them current and at the right level ... then overlay a pre-produced image of the data points / fit curve / etc that can be zoomed and moved. That should be possible with white set to an alpha on the graph image.
PS: The graph image shouldn't actually /change/ while on the view. It's just zooming and being dragged. The axis will probably actually change with movement. So pre-producing the graph before (or immediately upon) entering the view would be optimal. But I've also noticed that scaling works really well with vector images ... which also sounds appropriate (rather than a bitmap?).
So I'm looking for some general guidance. Tried reading up on the BitMap, ShapeDrawable, Drawable, etc classes and just can't seem to find the right fit. That makes me think I'm barking up the wrong tree and someone with some more experience can point me in the right direction. Hopefully I didn't waste my time building the zoom-able view I put together yesterday :).

A: First off, it is never a waste of time writing code if you learned something from it. :-)
There is unfortunately still no support for drawing vector images in Android.  So bitmap is what you get.
I think the bit you are missing is that you can create a Canvas any time you want to draw on a bitmap.  You don't have to wait for onDraw to give you one.
So at some point (from onCreate, when data changes etc), create your own Bitmap of whatever size you want.
Here is some psuedo code (not tested)
Bitmap mGraph;

void init() {
    // look at Bitmap.Config to determine config type
    mGraph = new Bitmap(width, height, config);
    Canvas c = new Canvas(mybits);
    // use Canvas draw routines to draw your graph
}

// Then in onDraw you can draw to the on screen Canvas from your bitmap.
protected void onDraw(Canvas canvas) {
    Rect dstRect = new Rect(0,0,viewWidth, viewHeight);
    Rect sourceRect = new Rect();
    // do something creative here to pick the source rect from your graph bitmap
    // based on zoom and pan
    sourceRect.set(10,10,100,100);

    // draw to the screen
    canvas.drawBitmap(mGraph, sourceRect, dstRect, graphPaint);
}

Hope that helps a bit.


text:
Q: Best way to add video uploading, encoding and streaming functionality to my Rails app? What is the best way to add video uploading, encoding and streaming functionality to my Rails app ?
I'm thinking about a mix as : Rails app + Video Online Encoder + Amazon S3. What do you think ?
For the Video Online Encoder (VOE), which one is the easier to use with Rails : heywatch, panvidea, encoding.com, pandastream, ... ?
By the way, the application will allow users to play streamed videos with dynamic Texts, Schemas and Sounds added to them at the run time. There's an example :

*

*in rails app (backoffice or frontoffice) : Video upload (.mov, .avi, ...)

*VOE : video encoding in FLV format + storage in Amazon S3

*in rails app, backoffice : in a home-made Flash application, "add" to the video a Text and a Schemas showed after 1 minute for example (informations stored in the Rails app DB).

*in rails app, frontoffice : play the streamed video from Amazon S3 (+Cloudfront) in a home-made Flash player which show dynamicaly the Text and the Schema over the video after 1 minute of playing.

The part I really don't understand is the FLV video Stream. I was thinking that Cloudfront could do that.
I hope I'm clear enough ;-)
Thank you all for your answers !

A: Zencoder looks cool and it probably has the API support you want.  Use flash for the player I'm guessing?  You will need FMS or Red5 for that.  Here is a link to a really simple example that transcodes something stored in S3 for you, in Ruby of course!: http://zencoder.com/docs/integration-libraries/#library

A: Disclaimer: I am a co-founder for transloadit.com.
I would discourage you from rolling your own solution. The link alexy13 posted will certainly get you an application that can receive user videos and encode them. However, you'll end up with a few limitations:

*

*Resized videos will be distorted unless their aspect ratio is 4:3. To avoid that you need to sniff their dimension before the conversion and then apply a set of padding -vfilters to ffmpeg. Sniffing the dimension correctly will require a cocktail of at least 2 command lines tools (ffmpeg itself and exiftool) + a bunch of crazy code to deal with display aspect ratios that differ from the pixel aspect ratios.

*Not all videos will convert. Sometimes you need to do additional sniffing on the video content and set some custom flags, otherwise you'll receive an error. Granted, 95% of all videos will probably work - but getting those last 5% is hard.

*You will need an additional web server that does the video encoding, otherwise your site will be very sluggish while a video is being encoded. You can work around this by using the nice command to limit the CPU resources used by ffmpeg, but that will result in significantly longer encoding times.

This is a short list of problems, but generally you are ~100 hours away from having a system that runs without hickups and can deal with some load.
So I would encourage you to re-consider going with a service. Our competitors are quite nice, but of course I'd also be very happy if you would check out our service (transloadit.com) or shoot me an email at felix.geisendoerfer@transloadit.com if you have any questions.
There is also a Rails3 sample application for using transloadit with paperclip and S3:
http://github.com/joerichsen/transloadit-paperclip-example
--fg

A: I would feel skeptical using a free third party online service.  I would consider using  server-side video encoding because the third-party web service could have variable performance, and could do basically anything to the video.  If you don't have many CPU's then a third-party service might be a good choice.
EDIT: This Link should help you a bit


text:
Q: IIS: Adding sub directory (Visual Studio aplication) to websites I have a couple of projects/application on IIS under the foler RootFolder, and I am trying to add one more application to this foler. I added a virtual directory called ProjectFolder to the RootFolder and linked it to the location of my new application in the wwwroot folder. However, I keep getting the error below when trying to navigate to the page on the web browser.

Configuration Error
Description: An error occurred during the processing of a configuration file required to > service this request. Please review the specific error details below and modify your configuration file appropriately.
Parser Error Message: It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level.  This error can be caused by a virtual directory not being configured as an application in IIS.
Source Error:

Line 43:     </authorization>
Line 44:     <customErrors mode="Off"/>
Line 45:     <authentication mode="Forms">
Line 46:       <forms loginUrl="~/LogOn" timeout="2880" />
Line 47:     </authentication>

Source File: C:\inetpub\wwwroot\RootFolder\ProjectFolder\web.config    Line: 45

To be sure it is a problem with my application, I copied the content of another application that is working well onto my ProjectFolder, but the same error shows. I have also tried right clicking on the virtual directory folder and selecting change to application (this changed the icon of the the virtual directory folder. However, none of the icons of the other applications that are on my ISS and are working look anything like this new icon), yet this give the same error.
I was thinking of maybe deleting this virtual directory and recreating it but when I right click on the folder, I have no option for properties or to delete the directory.
Can anyone help PLEASE?
Thanks


text:
Q: Condition to ensure that this producer-consumer example won't deadlock? I started to doubt about the concept of semaphores; please read well to understand my problem...
According to the manual, sem_post will unlock a thread when the semaphore's value becomes greater than 0... so if I have this code:
void* producer(void* arg)
{
    while(1)
    {
        sem_wait(&sem_produce);
        sem_wait(&mutex);
        // Insert item into buffer
        sem_post(&mutex);
        sem_post(&sem_consume);
    }
    pthread_exit(NULL);
}

void* consumer(void* arg)
{
    while(1)
    {
        sem_wait(&sem_consume);
        sem_wait(&mutex);
        // Remove item from buffer
        sem_post(&mutex);
        sem_post(&sem_produce);
    }
    pthread_exit(NULL);
}

Where sem_consume is initialized with the value of 0, and sem_produce is initialized with N.
What happens if, for example, the N consumers run before producers and try to consume? Then sem_consume should have the value of -N, and if then there are N insertions, sem_consume and sem_produce both should be 0, or am I wrong? Then that means the consumers would be stuck because (according to the manual) sem_post will unlock a thread when the semaphore's value becomes greater than zero...
So from what I understand from the manual and considering the above example, the only way this program would work fine is if sem_consume never reach the value of -N.
I am right? If yes, how can I improve the example so it won't get stuck? If the answer is no, in what I was wrong?

A:
So from what I understand from the manual and considering the above
  example, the only way this program would work fine is if sem_consume
  never reach the value of -N.

Thats correct, semaphores are just flat out not permitted to be a negative value period. As pointed out by many people in the comments, the semaphore manuals clearly state this:

A semaphore is an integer whose value is never allowed to fall below
         zero.

And this:

If the semaphore
         currently has the value zero, then the call blocks until either it
         becomes possible to perform the decrement (i.e., the semaphore value
         rises above zero), or a signal handler interrupts the call.

And this:

Decrementing is a (possibly) blocking function. If the resulting semaphore value is negative, the calling thread or process is blocked, and cannot continue until some other thread or process increments it.

Essentially, the entire point of a semaphore being positive only is that when a process tries to decrement it into a negative, that process gets halted until another process increments it sufficiently for it not to become negative when the original process is allowed to decrement.
To your comment:

That's odd , in my parallel programming course I thought I heard from the teacher that the value of a semaphore could be negative and that this negative value would represent the number of blocked threads, if this value can't be negative then I have no doubts.

Thats essentially what happens, but you can't view this value. If you attempt to grab a semaphore which is currently not positive, then the function trying to grab it is blocked until it becomes positive again.

A: I think the definitions of sem_post and sem_wait are as follows.
sem_wait()
    Decrements the value of semaphore by one and wait if the value is negative.
sem_post()
    Increments the value of semaphore by one and if there are one or more threads waiting then wake one.
Hence sem_post() does not really check if the value is greater than 0 or not.
Also, if sem_post() really checks that then semaphore can never be used as a lock. Please see the below code snippet.
sem_t m;
sem_init(&m, 0, 1)

sem_wait(&m)
... critical section...
sem_post(&m)

Let's say, thread 1 gets scheduled first and decrements the value to 0 and enters the critical section. Before it completes, three other threads get scheduled one after another and each of them further decrements the semaphore and blocks. Now, thread 1 gets scheduled again, completes the critical section and calls sem_post(). My point is that if it really checks for a positive value then other threads will never be scheduled which is not the case. Please let me know if this answers your question.
Thank you.


text:
Q: Relation does not exist after switch from database postgres to smart_brain After switching databases, my table does no longer exist:
postgres=# SELECT * FROM users;
 id | name | email | entries | joined
----+------+-------+---------+--------
(0 rows)

postgres=# \c smart_brain
You are now connected to database "smart_brain" as user "postgres".
smart_brain=# SELECT * FROM users;
ERROR:  relation "users" does not exist
LINE 1: SELECT * FROM users;
                      ^

A: That is as expected. You created a table in the database postgres, not in smart_brain. Consequently, you cannot use the table in the latter database.
Databases are strictly logically separated in PostgreSQL.
I recommended that you don't create user objects in postgres, but only use that database for administrative purposes.


text:
Q: Differences between will, going to and doing+V to describe future time in everyday English I know there are some subtle academic differences between them but do native speakers really consider it before choosing the correct tense to use or they are interchangeable in everyday English?

A: I don't think native speakers consider which one to use, it's just that different ones come naturally in different  situations.
(In British English) "If you eat too much cake you will be sick" is a prediction. "I'm going to be sick!" is an urgent warning. However, I'm going to can also be a prediction - "I'm going to miss you when you leave." If you are promising to do something, it's "I will give him your message."
"I'm taking my driving test next week" implies an arrangement that is already fixed. I think if going to was used, it would imply a less definite date. "I'm going to take my test this summer if I can get enough practice."


text:
Q: how to set column count for each row dynamically in flutter I have gridView builder which is displaying 2 items in a row. like below image

I want to display like this image

\n
Please help me to achieve this in flutter

                            GridView.builder(
                              gridDelegate:
                                  SliverGridDelegateWithMaxCrossAxisExtent(
                                      maxCrossAxisExtent: 200,
                                      childAspectRatio: 2.5 / 3,
                                      crossAxisSpacing: 10,
                                      mainAxisSpacing: 10),
                              shrinkWrap: true,
                              primary: false,
                              itemCount: nListLevels.modules.length,
                              itemBuilder: (context, j) {

                          // displaying contents here
                         }
                   ));

A: I guess you can return "column" and inside the "column", you can add "Row" widget to suit your UI

A: for different size of grid items, you need flutter_staggered_grid_view:
StaggeredGridView.countBuilder(
  crossAxisCount: 4,
  itemCount: 8,
  itemBuilder: (BuildContext context, int index) => new Container(
      color: Colors.green,
      child: new Center(
        child: new CircleAvatar(
          backgroundColor: Colors.white,
          child: new Text('$index'),
        ),
      )),
  staggeredTileBuilder: (int index) =>
      new StaggeredTile.count(2, index.isEven ? 2 : 1),
  mainAxisSpacing: 4.0,
  crossAxisSpacing: 4.0,
)


text:
Q: Turn array into nested array using nested loops in php I am building comments for CMS. I have the following data structure:
$comments=[
[comment_id=>1,...,comment_repay_to=>null],
[comment_id=>2,...,comment_repay_to=>1],
[comment_id=>3,...,comment_repay_to=>2],
[comment_id=>4,...,comment_repay_to=>null]
];

I want to turn into:
$comments=[
    [
        'comment'=>[comment_id=>1,...,comment_repay_to=>null],
        'children'=>[
                [
                        'comment'=>[comment_id=>2,...,comment_repay_to=>1],
                        'children'=>[...]
                ],
        ],
        'comment'=>[comment_id=>4,...,comment_repay_to=>null],
    ],
];

I have written the following incomplete code. I am stuck in loops.
$arr=[];
    $level=0;
    foreach ($comments as $comment){
        if($comment->comment_replay_to==null){
            $temp_comment=$comment;
            $temp_arr=[
                'comment'=>$comment,
                'children'=>[]
            ];
            $level++;
            while($level>0){

            }
        }
    }

Any help would be highly appreciated. Thanks.
Edit:
I got the answer on this link:https://books.google.com.pk/books?id=xHc5DwAAQBAJ&pg=PA109&lpg=PA109&dq=recursive+display+threaded+comments&source=bl&ots=b2PLCOnMnX&sig=ACfU3U1Jy6iUh-qeOZlPfgz3QnIAFlitLA&hl=en&sa=X&ved=2ahUKEwjK86Sm6PjjAhXsA2MBHfORAdsQ6AEwEnoECAkQAQ#v=onepage&q&f=false

A: Not exactly beautiful, but should point you into the right direction:
<?php

// process input in reverse order
$input = array_reverse([
    ['id' => 1, 'message' => 'A', 'parent' => null],
    ['id' => 2, 'message' => 'B', 'parent' => 1],
    ['id' => 3, 'message' => 'C', 'parent' => 2],
    ['id' => 4, 'message' => 'D', 'parent' => null]
]);

// use 'id' as actual key for the entry, saves a lot of hassle
array_walk($input, function($entry) use (&$output) {
    $output[$entry['id']] = $entry;
});

array_walk($output, function (&$entry, $id) use (&$output) {
    $parent = $entry['parent'];
    unset($entry['parent']);
    // if entry belongs into a parent, then move it there
    if (array_key_exists($parent, $output)) {
        $output[$parent]['children'][] = $entry;
        unset($output[$id]);
    }
});

print_r($output);

The output is:
Array
(
    [4] => Array
        (
            [id] => 4
            [message] => D
        )

    [1] => Array
        (
            [id] => 1
            [message] => A
            [children] => Array
                (
                    [0] => Array
                        (
                            [id] => 2
                            [message] => B
                            [children] => Array
                                (
                                    [0] => Array
                                        (
                                            [id] => 3
                                            [message] => C
                                        )

                                )

                        )

                )

        )

)

A: This is the final code for someone's help
public static function commentRecursive($comments,$n){
        if(isset($comments[$n])){
            self::$str.="<ul>";
            foreach($comments[$n] as $comment){
                self::$str.=$comment['comment_content'];
                self::commentRecursive($comments,$comment['comment_id']);
            }
            self::$str.="</ul>";
        }
    }
    public static function commentsDataStructure($comments){
        self::$str='';
        $output=[];
        foreach ($comments as $comment){
            $output[$comment['comment_reply_to']][]=$comment;
        }
        self::commentRecursive($output,0);
        return self::$str;
    }


text:
Q: Show basic circuit diagrams in code Suppose I have the following circuit image of an example XORD gate using AND, OR, and NOT gates:

Are there any open source tools that are capable of converting this into text characters, so that I can show the diagram inside text documentation without having to link to the image? An example of a square being drawn using ASCIFLOW would be:
+-----------------+
|                 |
|                 |
|                 |
|                 +------------------>
|                 |
|                 |
|                 |
+-----------------+

But I'm trying to see how to create basic circles, triangles and other gate-shapes.