text:
Q: Extending a contour in OpenCv i have several contours that consist of several black regions in my image. Directly adjacent to these black regions are some brighter regions that do not belong to my contours. I want to add these brighter regions to my black region and therefor extend my contour in OpenCv.
Is there a convenient way to extend a contour? I thought about looking at intensity change from my gradient-image created with cv::Sobel and extend until the gradient changes again, meaning the intensity of pixel is going back to the neither black nor bright regions of the image.
Thanks!
Here are example images. The first picture shows the raw Image, the second the extracted Contour using Canny & findContours, the last one the Sobel-Gradient intensity Image of the same area.
I want to include the bright boundaries in the first image to the Contour.

Update: Now i've used some morphological operations on the Sobelgradients and added a contour around them (see Image below). Next step could be to find the adjacent pair of purple & red contours, but it seems very much like a waste of procession time to actually have to search for directly adjacent contours. Any better ideas?

Update 2: My solution for now is to search for morphed gradient (red) contours in a bounding box around my (purple) contours and pick the one with correct orientation & size. This works for gradient contours where the morphological operation closes the "rise" and "fall" gradient areas like in Figure 3. But it is still a bad solution for cases in which the lighted area is wider then in the image above. Any idea is still very much appreciated, thanks!

A: What you're trying to do is find two different features and merge them.  It's not terribly difficult but you have to use multiple copies of the image to make it happen.

*

*Make one copy, and threshold it for the dark portion

*Make another copy and threshold it for the light portion

*Merge both thresholded images into a new image

*Apply a morphological operation like opening or closing (depending on how you threshold)  This will connect nearby components

*Find contours in the resultant image

*Use those contours on your original image.  This will work since all the images are the same size and all based off of the original.


text:
Q: Errors when starting a PowerShell session I was using PowerShell normally (was using posh git, just to mention), and suddenly a weird behavior happened, I tried to restart the session, when I did, I got many errors, which are :
Split-Path : The term 'Split-Path' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path
was included, verify that the path is correct and try again.
At C:\Users\aymen.daoudi\Documents\WindowsPowerShell\Modules\posh-git\profile.example.ps1:1 char:16
+ Push-Location (Split-Path -Path $MyInvocation.MyCommand.Definition -P ...
+                ~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Split-Path:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Import-Module : The specified module '.\posh-git' was not loaded because no valid module file was found in any module directory.
At C:\Users\aymen.daoudi\Documents\WindowsPowerShell\Modules\posh-git\profile.example.ps1:4 char:1
+ Import-Module .\posh-git
+ ~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceUnavailable: (.\posh-git:String) [Import-Module], FileNotFoundException
    + FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand

Enable-GitColors : The term 'Enable-GitColors' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or
if a path was included, verify that the path is correct and try again.
At C:\Users\aymen.daoudi\Documents\WindowsPowerShell\Modules\posh-git\profile.example.ps1:26 char:1
+ Enable-GitColors
+ ~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Enable-GitColors:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Pop-Location : The term 'Pop-Location' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a
path was included, verify that the path is correct and try again.
At C:\Users\aymen.daoudi\Documents\WindowsPowerShell\Modules\posh-git\profile.example.ps1:28 char:1
+ Pop-Location
+ ~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Pop-Location:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Start-SshAgent : The term 'Start-SshAgent' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if
a path was included, verify that the path is correct and try again.
At C:\Users\aymen.daoudi\Documents\WindowsPowerShell\Modules\posh-git\profile.example.ps1:30 char:1
+ Start-SshAgent -Quiet
+ ~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Start-SshAgent:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Here's a picture of that :

I tried to restart the PC, but still have the same problem every time I start a new PowerShell session, I noticed that many commands don't work, what caused this problem ? and what should I do to solve it ?
Update
I removed the profiles added by PoshGit, when starting a new session, I don't have any error, but powershell still doesn't recognize commands, for example calling Clear-host, throws lots of errors that I can't understand the cause !

A: You're PSModulePath system environment varaible is missing C:\windows\system32\WindowsPowerShell\v1.0\Modules which is the location of all "system"/built-in modules in PowerShell.
Something you've installed (posh git maybe?) has probably messed it up. Add it to the system variable.
The easiest way to do it without PowerShell is using the GUI as described here:
http://www.computerhope.com/issues/ch000549.htm

A: If you just installed posh-git it added some Powershell profile files, basically some .ps1 files executed each time a powershell session starts.
Just remove (or fix) them; from the path in the errors thrown probably they are in C:\Users\aymen.daoudi\Documents\WindowsPowerShell\...

A: I had a similar shell error message when loading my profile after installing posh-git ... profile.example.ps1 is not recognized as the name of a cmdlet.
This happened to me when I copied over files to my user directory from an older machine - the older poshgit powershell user profiles came along with it.
The fix for me was to rename the old posh-git profile from the path below...
Original Profile Path
C:\Users\<username>\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

New Profile Name
C:\Users\<username>\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1.notused

After choco uninstall poshgit and choco install poshgit a new profile was created with the right data (went from 5KB to 1KB in size).

redpajama_set_name: RedPajamaStackExchange


text:
Q: UIKeyboard without number I need a UIKeyboard that display the default UIKeyboardType without the number 0-9. I only need to hide those buttons.
Is there a way to access the the different button of the keyboard so i could set then hidden?
If no, can i detect when the ".?123" button is pressed AND add a subview to cover the first row?
Or any pointer to a better approach?

A: There is no public API for disabling access to the number and punctuation keys.  You could dig through the keyboard's view hierarchy to try to hide the number toggle key, but that is likely to break in the future (the keyboard view hierarchy has changed in the past).
It would be much simpler to just filter out the characters you don't like in your text control's delegate.  For example, let's say you only want to allow the user to type in letters.  If you have a UITextField, set its delegate to your view controller and implement this method in your view controller:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSRange all = NSMakeRange(0, string.length);
    if (all.length == 0) {
        // deletion
        return YES;
    }

    NSRange letters = [string rangeOfCharactersFromSet:[NSCharacterSet letterCharacterSet]];
    return NSEqualRanges(all, letters);
}

If you have a UITextView, the method is called textView:shouldChangeTextInRange:replacementText:.


text:
Q: How to change thumbnail image ratio iOS Push Notification? Is it possible to change the image aspect ratio and its size in the thumbnail of an iOS push notification, how ?
That is the current Push Notification I get...
...and that is the render I wish (image from the Apple WWDC, I suppose it is possible to get the same render ?!)

A: I assume you're using UNNotificationAttachment to show the image on the lock screen, correct? If not, you probably should be for this particular case. In it, you can use UNNotificationAttachmentOptionsThumbnailClippingRectKey, where you can specify your cropping rectangle.
If you're trying to get a non-standard aspect ratio, you can specify something like, CGRectMake(x: 0, y: 0, width: 1, height: 0.7). This will crop your image at 70% of its original height and cut off the bottom 30%. You can also play around with x and y values that will move the cropping rectangle from its top-left origin point.
You can, of course, read more about it in Apple's docs.


text:
Q: Действие на комбинацию клавиш WinForms Хочу сделать зум panel по зажатой комбинации...Как отследить комбинацию клавиш Ctrl + MouseWheel? Не понимаю, как одновременно работать с событием вращения колесика мыши и нажатием Ctrl. Вот что есть на данный момент:
private void MainForm_KeyPress(object sender, KeyPressEventArgs e)
{
         if (ModifierKeys.HasFlag(Keys.Control) & колесо мыши активно)
         {
            //####работает для MouseWheel####
            //if (e.Delta > 0) //zoom +
            //{
            //    canvas.Width += e.Delta / 5;
            //    canvas.Height += e.Delta / 5;
            //    canvas.Location = new Point(canvas.Location.X - e.Delta / 10, canvas.Location.Y - e.Delta / 10);
            //}
            //else if (e.Delta < 0) //zoom -
            //{
            //    canvas.Width += e.Delta / 5;
            //    canvas.Height += e.Delta / 5;
            //    canvas.Location = new Point(canvas.Location.X - e.Delta / 10, canvas.Location.Y - e.Delta / 10);
            //}
        }
}

Спасибо

A: Оно работает О_о
private void this_MouseWheel(object sender, MouseEventArgs e)
    {
        if(ModifierKeys == Keys.Control)
        {
            if (e.Delta > 0) //zoom +
            {
                canvas.Width += e.Delta / 5;
                canvas.Height += e.Delta / 5;
                canvas.Location = new Point(canvas.Location.X - e.Delta / 10, canvas.Location.Y - e.Delta / 10);
            }
            else if (e.Delta < 0) //zoom -
            {
                canvas.Width += e.Delta / 5;
                canvas.Height += e.Delta / 5;
                canvas.Location = new Point(canvas.Location.X - e.Delta / 10, canvas.Location.Y - e.Delta / 10);
            }
        }
    }


text:
Q: Give React setState parameters variable value I want to create a function handleFalse() in react so it works something like:
state = {
  Java: false,
  Python: false
}

handleFalse(language) {
  this.setState({language}:true);
}

render() {
  return(
    <Modal onHide={this.handleFalse("show")}></Modal>
  )
}

where language would be one of Java or Python.

A: You can use a computed property like this:
handleTrue(language) {
  this.setState({ [language]: true });
}

You can reference an object property with a variable by using [].
This works when accessing too: this.state[language]


text:
Q: $a,b \in \mathbb N $ , $b$ odd $\implies$ $ \dfrac{2a^2-1}{b^2+2} \notin \mathbb Z $? If $a,b$ are positive integers and $b$ is odd , then is it ever possible that $ \dfrac{2a^2-1}{b^2+2} $ is an integer ?

A: Since $b$ is odd, $b^2 + 2\equiv 3\pmod{8}$. Thus $2$ is not a quadratic residue mod $(b^2 + 2)$. Hence $2a^2\not\equiv 1\pmod{b^2 + 2}$, from which the result follows.

A: Can this formula to use.
How to solve an equation of the form $ax^2 - by^2 + cx - dy + e =0$?
But we'll see this topic and select the desired formula.
Families of curves over number fields


text:
Q: Nested pivot columns I have a table sales:
SalesID. Date. Geography

1.       2020-01.  Italy
1.       2020-01.  France
1.       2020-01.  UK
2.       2020-02.  Italy
2.       2002-02.  Canada
3.       2002-08.  France

I would like to display only top 2 Geography and pivot:
Expected result:
SalesID.   Date. Geography 1.    Geography2.
1.      2020-01. Italy. France

2.     2020-02.  Italy.  France.
3.    2020-08.    France

What I try so far https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=565f80f146fe2a72096b31fc0baba3ad
How to modify it?

A: First, you need a column that defines the ordering of the rows - I assumed ordering_id. Then, you can use row_number() and conditional aggregation.
select saleid, date,
    max(case when rn = 1 then geography end) as geography1,
    max(case when rn = 2 then geography end) as geography2
from (
    select t.*,
        row_number() over(partition by saleid, date order by ordering_id) as rn
    from mytable t
) t
where rn <= 2
group by saleid, date

A: You can use the conditional aggregation as follows:
select t.sales_id,
       date,
       max(CASE WHEN rn = 1 THEN geography END) AS geography1,
       max(CASE WHEN rn = 2 THEN geography END) AS geography2
(select t.*, row_number() over (partition by t.sales_id, date order by t.date) as rn
FROM your_table t) t
GROUP BY t.sales_id, date;


text:
Q: Show or Hide One or More controls based on Checked checkboxList Item Sorry experts but I have spent half of today googling this but could find any helpful solutions.
I have a checkboxList control with ID called ckRequestReview. This checkboxList control has three items.
Our requirement is that if a  user clicks one of those items, display two textboxes associated with it.
If user checks all three checkbox items, display all six textbox controls.
So far, only three are working.
Here is what needs to happen:
On page load, by default all six textbox controls are hidden.
User checks the Job Title checkbox item, two controls, txtTitleChange and txtTitle controls are made visible.
OR User checks the Pay Range checkbox item and two controls, txtPayGradeChange and txtPayGrade are made visible
OR User checks the Class checkbox item and two controls, txtClassSpecChange and txtClassification
OR User checks all three checkbox items and all six textbox controls are made visible.
So far, only these three textbox controls out of the six listed work correctly:
HTML

    Requested Change:

        <asp:TextBox ID="txtTitleChange" runat="server" placeholder="Job Title" Style="margin-right: 0px; width: 200px; display: none;" />

        <asp:TextBox ID="txtPayGradeChange" runat="server" placeholder="for Pay Range" Style="margin-right: 0px; width: 200px; display: none;" />

        <asp:TextBox ID="txtClassSpecChange" runat="server" placeholder="for Class" Style="margin-right: 0px; width: 200px; display: none;" />

The other three do nothing when checkbox is either checked or unchecked.Any ideas what I am doing wrong?
JS

HTML

        Request a Review of:

            <asp:CheckBoxList ID="ckRequestReview" runat="server" CssClass="cb" Style="border-width: 0;" RepeatDirection="horizontal" RepeatColumns="4" RepeatLayout="Table">
                <asp:ListItem onclick="ShowHide(this,'txtTitleChange','txtTitle');"> Job Title</asp:ListItem>
                <asp:ListItem onclick="ShowHide(this,'txtPayGradeChange','txtPayGrade');">Pay Range</asp:ListItem>
                <asp:ListItem onclick="ShowHide(this,'txtClassSpecChange','txtClassification');">Class</asp:ListItem>
            </asp:CheckBoxList>

                Requested Change:

                    <asp:TextBox ID="txtTitleChange" runat="server" placeholder="Job Title" Style="margin-right: 0px; width: 200px; display: none;" />

                    <asp:TextBox ID="txtPayGradeChange" runat="server" placeholder="for Pay Range" Style="margin-right: 0px; width: 200px; display: none;" />

                    <asp:TextBox ID="txtClassSpecChange" runat="server" placeholder="for Class" Style="margin-right: 0px; width: 200px; display: none;" />

            JUSTIFICATION

                            <asp:Label ID="txtTitle" runat="server" Text="Job Title" Style="width: 200px;" Font-Bold="False"></asp:Label>

                            <asp:TextBox ID="txtTitleComments" runat="server" placeholder="Title Change Justification" Style="width: 400px;height:100px;" Font-Bold="False" TextMode="MultiLine"></asp:TextBox>

                            <asp:Label ID="txtPayGrade" runat="server" Text="Pay Range" Style="width: 200px;" Font-Bold="False"></asp:Label>

                            <asp:TextBox ID="txtPayComments" placeholder="Pay Grade Change Justification" runat="server" Style="width: 400px;height:100px;" Font-Bold="False" TextMode="MultiLine"></asp:TextBox>

                            <asp:Label ID="txtClassification" runat="server" Text="Class" Style="width: 200px;" Font-Bold="False"></asp:Label>

                            <asp:TextBox ID="txtClassComments" placeholder="Class Specification Change Justification" runat="server" Style="width: 400px;height:100px;" Font-Bold="False" TextMode="MultiLine"></asp:TextBox>

A: You're correctly passing three parms to your JS, but are only handling 2. Replace it with this


text:
Q: Signal Strength to ADC quantisation levels According to the excellent site of AB4OJ, the Icom 7300 in summary has a 14bit analogue to digital converter with a 1.5 volt peak to peak input (LTC2208-14).  I make this to be 91.5uV per quantisation level. There is a 20db gain amplifier (LTC6401-20) ahead of the ADC so best case this would give 9.1uV per quantisation level.
Wikipedia gives for HF a S5 signal to be 3.2uV (rms relative to 50R). Equivalently this is 9.1uV peak to peak, resulting at best in a S5 signal at most only changing the Least Significant Bit of the ADC. Not much can be hoped to demodulate from this surely?
By the same logic, S9 would only move between 15 levels. Again how much can be demodulated from this strong signal?
As the 7300 works very well, clearly I am missing something but I
 don't know what. Can anyone fill me in?

A: You are missing that a correctly dithered quantiser is LINEAR, and that there is more then enough uncorrelated noise in the ADC input bandwidth to correctly dither the quantiser.
You are not digitising just the signal you care about, you are digitising a whole bands worth of mostly uncorrelated stuff, and then reducing the bandwidth in the digital domain. The bandwidth reduction strips off noise outside the range of interest, but that noise includes quantisation noise.
Every time you halve the bandwidth you gain 3dB on the signal to (total) noise ratio, so that every time you drop the bandwidth by a factor of 4 you gain an effective extra bit.
If the ADC is running at say 125MHz and you are downconverting to an 8KHz sample rate for the baseband processing then that gains you an effective 8 bits of extra meaningful word length if you do it right, putting the noise floor at about 20 bits or so (The number you want for the ADC is the ENOB, not the output word length).
If the thing basically follows the HPSDR architecture there is probably also a 1:2 (voltage ratio) transformer feeding the preamp, so another 3dB on the voltage there (But obviously no power gain).

A: Thermal Floor (Boltzmann noise, et al) for 1,000 Hertz bandwith is
-174dBm + 30 dB = -144dBm
What the voltage level, across 50 ohms from a standard RF interface, for -144 dBm?
Given 0dBm across 50 ohms is 0.632 volts peakpeak, and -120 dBm is down by 1,000,000 to 0.632 microVolts PP, and -140 dBm is down to 0.0632 uV (or 63 nanoVolts), the extra 4 dB drops the level another factor of 2.5X to 25 nanoVolts PP
Summary: the input signal, for 1,000 Hertz bandwidth signal at 0dB SignalNoiseRatio, is 25 nanoVolts PeakPeak.
Thus some amplification, at RF or in an active-mixer or in the Intermediate Frequency filtering stages, occurs prior to feeding the 14-bit ADC.
Or some signal-processing methods are used. Read on.
=================================
If you use a transformer to stepup the signal, converting from 50 ohms to 5,000 ohms impedance and then BUFFER (Unity Voltage Gain) to feed the ADC, you'll have 10X higher voltage or 250 nanoVolts into the ADC.
Still a factor of 40 too low.
You can dither the ADC sample amplitudes (random noise is one ditherer). Then post-process digitally, collapsing the samples from 100,000,000 per second (for example) down to 100,000 per second and pick up a factor of SQRT (1,000) = 31X improvement, which is getting close to the factor of 40x.
[by the way, this averaging, this collapsing of frequency from 100,000,000 to 100,000, is exactly what a MIXER does, in downconverting to a much lower IF frequency.]
Note the original energy level of -144 dBm produces ZERO dB SNR; assume you want 10 dB SNR, which raises the voltages by sqrt(10) or 3.1X, requiring -134 dBm from the Antenna.
Now..... is this what iCOM 7300 uses? You have some of the fundamental limits to muse over.


text:
Q: How do I get 4K output resolution with GTX760 on Ubuntu Desktop 13.10? I have a Nvidia GTX760 with drivers installed. How do I get the option to go up to the 4K output resolution? I am only getting 1920x1080 and below options and I have a 39" Seiki 4K display.
Currently, following this thread to find answers: http://ubuntuforums.org/showthread.php?t=2164924


text:
Q: Take email from vk.com django-social-auth in Django I use django-social-auth in my Django project. I need to recieve e-mail from users. Facebook works fine with this in settings.py:
FACEBOOK_EXTENDED_PERMISSIONS = ['email']
FACEBOOK_PROFILE_EXTRA_PARAMS = {
'fields': 'id, name, email',
}

Auth works fine and i recieve user's email address.
When i try to do the same with VK.com:
VK_EXTRA_SCOPE = ['email']
VK_PROFILE_EXTRA_PARAMS = {
'fields': 'id, name, email',
}

Auth works fine, extra scope works fine, but i don't recieve e-mail.
I also tried:
SOCIAL_AUTH_VK_PROFILE_EXTRA_PARAMS
SOCIAL_AUTH_VK_EXTRA_DATA
VK_PROFILE_EXTRA_PARAMS
VK_EXTRA_DATA

What is wrong?


text:
Q: Best way to recover mysql from a "chmod -R 777 /" with databases intact Question:
What is the best way to recover mysql (or worst case: migrate away) from a "chmod -R 777 /" with databases intact?
System:
Ubuntu 12.04 LTS
MySQL 5.5.24
64 bit Amazon EC2 cloud server.
Background:
Attempting to recover (or at least recover data from) a system which had this done to it:
    chmod -R 777 /

No point in worrying about the why.  It was a manager with too much access and too little experience who likes to swim in deep waters.  It was a pure accident on his part, not actually meaning to hit enter when he did.
I have recovered much of the system, but am really hung up on getting mysql working again.  I have already worked through such pages as:

*

*How to repair/restore ubuntu 10.04 after 'sudo chmod / 777'

*chmod -R 777 / on ubuntu - numerous problems

*chmod / 775 -R and now our mysql database is down…!

*Why is "chmod -R 777 /" destructive?
Have already done this:
    sudo chmod 644 my.cnf
    chown mysql:mysql my.cnf

At which point attempting to start mysql:
    sudo service mysql start

Produces this output in syslog:
    Apr 12 20:51:42 ip-10-10-25-143 kernel: [18632541.774742] type=1400 audit(1365799902.306:41): apparmor="STATUS" operation="profile_replace" name="/usr/sbin/mysqld" pid=18210 comm="apparmor_parser"
    Apr 12 20:51:42 ip-10-10-25-143 kernel: [18632541.964496] init: mysql main process (18214) terminated with status 1
    Apr 12 20:51:42 ip-10-10-25-143 kernel: [18632541.964542] init: mysql main process ended, respawning
    Apr 12 20:51:43 ip-10-10-25-143 kernel: [18632542.959796] init: mysql post-start process (18215) terminated with status 1
    Apr 12 20:51:43 ip-10-10-25-143 kernel: [18632543.002041] type=1400 audit(1365799903.534:42): apparmor="STATUS" operation="profile_replace" name="/usr/sbin/mysqld" pid=18238 comm="apparmor_parser"
    Apr 12 20:51:43 ip-10-10-25-143 kernel: [18632543.098490] init: mysql main process (18242) terminated with status 1
    Apr 12 20:51:43 ip-10-10-25-143 kernel: [18632543.098536] init: mysql main process ended, respawning
    Apr 12 20:51:43 ip-10-10-25-143 kernel: [18632543.140706] init: mysql post-start process (18244) terminated with status 1
    Apr 12 20:51:43 ip-10-10-25-143 kernel: [18632543.158681] type=1400 audit(1365799903.690:43): apparmor="STATUS" operation="profile_replace" name="/usr/sbin/mysqld" pid=18258 comm="apparmor_parser"
    Apr 12 20:51:43 ip-10-10-25-143 kernel: [18632543.285087] init: mysql main process (18262) terminated with status 1
    Apr 12 20:51:43 ip-10-10-25-143 kernel: [18632543.285133] init: mysql respawning too fast, stopped

What I read from that is mysql is terminating with a status 1, and it loops a few times trying to start up and gets stopped from doing that after too many attempts.  I've looked into status 1 but haven't found solutions that seem applicable.

A: *

*Create new VM instance with the same OS version and MySQL version.

*Start MySQL on new VM - it should create MySQL data directory with no databases but with correct permissions - in /var/lib/mysql.

*Stop MySQL on new VM.

*Copy /var/lib/mysql on new VM to /var/lib/mysql.empty.

*Copy /var/lib/mysql from old VM to /var/lib/mysql on new VM.

*Manually set permission on all files and directories in /var/lib/mysql based on permissions on /var/lib/mysql.empty.

*A short prayer to a deity of choice wouldn't hurt now.

*Start MySQL on new VM.

*I'd recommend dumping all data with mysqldump -A, recreating a new, empty mysql data directory and importing this data back just in case.

*When you are confident that it works and all your data is intact shutdown the old VM and archive it's disk image somewhere. It is much less work and much safer to setup a new server than trying to recover from this.

A: Reinstall the system and restore from backup.


text:
Q: Receiving Empty DataFrame for Solved PuLP Optimization Problem I am dabbling with PuLP (and Python, in general) for the first time to run an optimization problem for a fantasy football game.
My code below runs successfully, but it outputs an empty DataFrame.
import pandas as pd
import pulp

print('--- (1/4) Defining the problem ---')

# Read csv
raw_data = pd.read_csv('./csv/fantasypros.csv')

# create new columns that has binary numbers if player == a specific position
raw_data["QB"] = (raw_data["Pos. Parent"] == "QB").astype(float)
raw_data["RB"] = (raw_data["Pos. Parent"] == "RB").astype(float)
raw_data["WR"] = (raw_data["Pos. Parent"] == "WR").astype(float)
raw_data["TE"] = (raw_data["Pos. Parent"] == "TE").astype(float)
raw_data["K"] = (raw_data["Pos. Parent"] == "K").astype(float)
raw_data["DST"] = (raw_data["Pos. Parent"] == "DEF").astype(float)
raw_data["DK"] = (raw_data["Pos. Parent"] == "DK").astype(float)
raw_data["salary"] = raw_data["Point Cost"].astype(float)

model = pulp.LpProblem("NFTdraft", pulp.LpMaximize)

total_points = {}
cost = {}
qb = {}
rb = {}
wr = {}
te = {}
k = {}
dst = {}
dk = {}
num_players = {}

vars = []

# i = row index, player = player attributes
for i, player in raw_data.iterrows():
    var_name = 'x' + str(i)  # Create variable name
    decision_var = pulp.LpVariable(var_name, cat='Binary')  # Initialize Variables

    vars.append(decision_var)

    total_points[decision_var] = player["FPTS"]  # Create FPTS Dictionary
    cost[decision_var] = player["salary"]  # Create Cost Dictionary

    # Create Dictionary for Player Types
    qb[decision_var] = player["QB"]
    rb[decision_var] = player["RB"]
    wr[decision_var] = player["WR"]
    te[decision_var] = player["TE"]
    k[decision_var] = player["K"]
    dst[decision_var] = player["DST"]
    dk[decision_var] = player["DK"]
    num_players[decision_var] = 1.0

objective_function = pulp.LpAffineExpression(total_points)
model += objective_function

total_cost = pulp.LpAffineExpression(cost)
model += (total_cost <= 135)

print('--- (2/4) Defining the constraints ---')
QB_constraint = pulp.LpAffineExpression(qb)
RB_constraint = pulp.LpAffineExpression(rb)
WR_constraint = pulp.LpAffineExpression(wr)
TE_constraint = pulp.LpAffineExpression(te)
K_constraint = pulp.LpAffineExpression(k)
DST_constraint = pulp.LpAffineExpression(dst)
DK_constraint = pulp.LpAffineExpression(dk)
total_players = pulp.LpAffineExpression(num_players)

model += (QB_constraint >= 1)
model += (QB_constraint <= 2)
model += (RB_constraint <= 8)
model += (WR_constraint <= 8)
model += (TE_constraint <= 8)
model += (K_constraint <= 1)
model += (DST_constraint <= 1)
model += (DK_constraint <= 2)
model += (total_players == 10)

print('--- (3/4) Solving the problem ---')
model.solve()

print('--- (4/4) Formatting the results ---')
raw_data["is_drafted"] = 0.0

for var in model.variables():
    raw_data.iloc[int(var.name[1:]), 10] = var.varValue

my_team = raw_data[raw_data["is_drafted"] == 1.0]
my_team = my_team[["Asset Name", "Player", "Pos. Parent", "Rarity", "Point Cost", "FPTS"]]

print(my_team)
print("Total used amount of salary cap: {}".format(my_team["Point Cost"].sum()))
print("Projected points: {}".format(my_team["FPTS"].sum().round(1)))
print('--- Completed ---')

The expected outcome is a lineup of the ten players that the model suggests provide the most expected results, given the constraints.
I'm not sure if this helps, but below is the output in the Python console when I solve the problem and try to format the results.
At line 2 NAME          MODEL
At line 3 ROWS
At line 15 COLUMNS
At line 35896 RHS
At line 35907 BOUNDS
At line 38668 ENDATA
Problem MODEL has 10 rows, 2760 columns and 8324 elements
Coin0008I MODEL read with 0 errors
Continuous objective value is 193.829 - 0.01 seconds
Cgl0003I 2 fixed, 0 tightened bounds, 0 strengthened rows, 0 substitutions
Cgl0003I 2 fixed, 6 tightened bounds, 0 strengthened rows, 0 substitutions
Cgl0003I 0 fixed, 1 tightened bounds, 0 strengthened rows, 0 substitutions
Cgl0004I processed model has 7 rows, 266 columns (266 integer (58 of which binary)) and 773 elements
Cutoff increment increased from 1e-05 to 0.000999
Cbc0012I Integer solution of -192.1 found by DiveCoefficient after 0 iterations and 0 nodes (0.05 seconds)
Cbc0038I Full problem 7 rows 266 columns, reduced to 2 rows 3 columns
Cbc0012I Integer solution of -192.574 found by DiveCoefficient after 10 iterations and 0 nodes (0.08 seconds)
Cbc0031I 2 added rows had average density of 7.5
Cbc0013I At root node, 2 cuts changed objective from -193.82941 to -192.574 in 4 passes
Cbc0014I Cut generator 0 (Probing) - 0 row cuts average 0.0 elements, 3 column cuts (3 active)  in 0.003 seconds - new frequency is 1
Cbc0014I Cut generator 1 (Gomory) - 6 row cuts average 9.0 elements, 0 column cuts (0 active)  in 0.003 seconds - new frequency is 1
Cbc0014I Cut generator 2 (Knapsack) - 0 row cuts average 0.0 elements, 0 column cuts (0 active)  in 0.002 seconds - new frequency is -100
Cbc0014I Cut generator 3 (Clique) - 0 row cuts average 0.0 elements, 0 column cuts (0 active)  in 0.000 seconds - new frequency is -100
Cbc0014I Cut generator 4 (MixedIntegerRounding2) - 1 row cuts average 7.0 elements, 0 column cuts (0 active)  in 0.000 seconds - new frequency is 1
Cbc0014I Cut generator 5 (FlowCover) - 0 row cuts average 0.0 elements, 0 column cuts (0 active)  in 0.001 seconds - new frequency is -100
Cbc0014I Cut generator 6 (TwoMirCuts) - 5 row cuts average 8.0 elements, 0 column cuts (0 active)  in 0.000 seconds - new frequency is -100
Cbc0001I Search completed - best objective -192.574, took 10 iterations and 0 nodes (0.08 seconds)
Cbc0035I Maximum depth 0, 60 variables fixed on reduced cost
Cuts at root node changed objective from -193.829 to -192.574
Probing was tried 4 times and created 3 cuts of which 0 were active after adding rounds of cuts (0.003 seconds)
Gomory was tried 4 times and created 6 cuts of which 0 were active after adding rounds of cuts (0.003 seconds)
Knapsack was tried 4 times and created 0 cuts of which 0 were active after adding rounds of cuts (0.002 seconds)
Clique was tried 4 times and created 0 cuts of which 0 were active after adding rounds of cuts (0.000 seconds)
MixedIntegerRounding2 was tried 4 times and created 1 cuts of which 0 were active after adding rounds of cuts (0.000 seconds)
FlowCover was tried 4 times and created 0 cuts of which 0 were active after adding rounds of cuts (0.001 seconds)
TwoMirCuts was tried 4 times and created 5 cuts of which 0 were active after adding rounds of cuts (0.000 seconds)
Result - Optimal solution found
Objective value:                192.57400000
Enumerated nodes:               0
Total iterations:               10
Time (CPU seconds):             0.08
Time (Wallclock seconds):       0.12
Option for printingOptions changed from normal to all
Total time (CPU seconds):       0.10   (Wallclock seconds):       0.14
--- (4/4) Formatting the results ---
Empty DataFrame
Columns: [Asset Name, Player, Pos. Parent, Rarity, Point Cost, FPTS]
Index: []
Total used amount of salary cap: 0
Projected points: 0.0
--- Completed ---

Thanks in advance for any advice on how to get my optimal 10-player lineup to populate the DataFrame.
EDIT - per the request of @chitown88, here is a link to the CSV.

A: First thing, vars is a builtin function, don't use that as a variable.
Secondly, you can simplify the one-hot encoding you do for the binary positions by simply using panda's .get_dummies().
Lastly, it's not assigning the 1.0 value to your "is_drafted" column. Try .loc instead of .iloc. I'd also use the column name as opposed to the index position for "is_drafted" too, but that just my preference.
Give this a try. I commented where I made changes. I couldn't really test it with out your specific data. So if it doesn't work, you may need to share your csv file so I could debug:
import pandas as pd
import pulp

print('--- (1/4) Defining the problem ---')

# Read csv
raw_data = pd.read_csv('./csv/fantasypros.csv')

# create new columns that has binary numbers if player == a specific position
encoded = pd.get_dummies(raw_data['Pos. Parent']) #<-- One-Hote Encoding
raw_data = raw_data.join(encoded) #<-- joining it to the raw_data table

raw_data["salary"] = raw_data["Point Cost"].astype(float)

model = pulp.LpProblem("NFTdraft", pulp.LpMaximize)

total_points = {}
cost = {}
qb = {}
rb = {}
wr = {}
te = {}
k = {}
dst = {}
dk = {}
num_players = {}

vars_list = []

# i = row index, player = player attributes
for i, player in raw_data.iterrows():
    var_name = 'x' + str(i)  # Create variable name
    decision_var = pulp.LpVariable(var_name, cat='Binary')  # Initialize Variables

    total_points[decision_var] = player["FPTS"]  # Create FPTS Dictionary
    cost[decision_var] = player["salary"]  # Create Cost Dictionary

    # Create Dictionary for Player Types
    qb[decision_var] = player["QB"]
    rb[decision_var] = player["RB"]
    wr[decision_var] = player["WR"]
    te[decision_var] = player["TE"]
    k[decision_var] = player["K"]
    dst[decision_var] = player["DST"]
    dk[decision_var] = player["DK"]
    num_players[decision_var] = 1.0

objective_function = pulp.LpAffineExpression(total_points)
model += objective_function

total_cost = pulp.LpAffineExpression(cost)
model += (total_cost <= 135)

print('--- (2/4) Defining the constraints ---')
QB_constraint = pulp.LpAffineExpression(qb)
RB_constraint = pulp.LpAffineExpression(rb)
WR_constraint = pulp.LpAffineExpression(wr)
TE_constraint = pulp.LpAffineExpression(te)
K_constraint = pulp.LpAffineExpression(k)
DST_constraint = pulp.LpAffineExpression(dst)
DK_constraint = pulp.LpAffineExpression(dk)
total_players = pulp.LpAffineExpression(num_players)

model += (QB_constraint >= 1)
model += (QB_constraint <= 2)
model += (RB_constraint <= 8)
model += (WR_constraint <= 8)
model += (TE_constraint <= 8)
model += (K_constraint <= 1)
model += (DST_constraint <= 1)
model += (DK_constraint <= 2)
model += (total_players == 10)

print('--- (3/4) Solving the problem ---')
model.solve()

print('--- (4/4) Formatting the results ---')
raw_data["is_drafted"] = 0.0

for var in model.variables():
    raw_data.loc[int(var.name[1:]), 'is_drafted'] = var.varValue     # <--- CHANGED HERE

my_team = raw_data[raw_data["is_drafted"] == 1.0]
my_team = my_team[["Asset Name", "Player", "Pos. Parent", "Rarity", "Point Cost", "FPTS"]]

print(my_team)
print("Total used amount of salary cap: {}".format(my_team["Point Cost"].sum()))
print("Projected points: {}".format(my_team["FPTS"].sum().round(1)))
print('--- Completed ---')


text:
Q: Does DeadLetterPublishingRecoverer expect the .DLT topic to be present before hand I'm using spring boot 2.1.7.RELEASE and spring-kafka 2.2.8.RELEASE.And I'm using @KafkaListener annotation to create a consumer and I'm using all default settings for the consumer except below one
auto.create.topics.enable = false
Now I'm trying to use DeadLetterPublishingRecoverer in conjunction with SeekToCurrentErrorHandler to handle deserialization errors.
As per the spring-kafka documentation of DeadLetterPublishingRecoverer,

By default, the dead-letter record is sent to a topic named
  .DLT (the original topic name suffixed with .DLT) and
  to the same partition as the original record

Now my question is, Does the DeadLetterPublishingRecoverer expect the .DLT topic be present before hand or can it create the topic using Adminclient (if not present?

A: Yes; it must exist; just add a NewTopic @Bean and the auto-configured Boot KafkaAdmin will create it.


text:
Q: "MySQL functions missing" error from PHP I'm using EasyPHP on Windows. When I try to run a script (from the command line), I'm having the following error:

DB connection error: MySQL functions missing, have you compiled PHP with the --with-mysql option?

It was strange since all MySQL functions are working fine when running PHP scripts using HTTP. I checked my php.ini file and found all MySQL extensions there:
extension=php_mysql.dll
extension=php_mysqli.dll

Any idea what is wrong?

A: Your PHP CLI does not use the php.ini where the mysql extensions are enabled. Run php --ini on the command line to see which ini it uses and enable the extensions therein.


text:
Q: Simple image upload via form: how to process errors This is a simple form to upload images. One question, the action pointing to upload_file.php does all the work. If an error is thrown how do I capture this error to display it to the user?
(example taken from http://www.w3schools.com/PHP/php_file_upload.asp)

<form action="upload_file.php" method="post"
enctype="multipart/form-data">
Filename:
<input type="file" name="file" id="file">

<input type="submit" name="submit" value="Submit">
</form>

EDIT

I was not clear enough in this question. The file image_upload.php is passed the $_FILES[] array and there is a lot of error checking which works. The errors are bundled into a JSON array in the php and echo'ed back to the calling page. i.e.
echo json_encode(array("error" => $error, "error_desc" => $error_desc, "images" => $images));

From the form I need to be able to do something similar to (in pseudo code)
if ($error) {
$("#div_error").html("Sorry there was an error " . $error_desc);
}

A: if($_FILES['photo']['name'])
{
//if no errors...
if(!$_FILES['photo']['error'])
{
    //now is the time to modify the future file name and validate the file
    $new_file_name = strtolower($_FILES['photo']['tmp_name']); //rename file
    if($_FILES['photo']['size'] > (1024000)) //can't be larger than 1 MB
    {
        $valid_file = false;
        $message = 'Oops!  Your file\'s size is to large.';
    }

    //if the file has passed the test
    if($valid_file)
    {
        //move it to where we want it to be
        move_uploaded_file($_FILES['photo']['tmp_name'], 'uploads/'.$new_file_name);
        $message = 'Congratulations!  Your file was accepted.';
    }
}
//if there is an error...
else
{
    //set that to be the returned message
    $message = 'Ooops!  Your upload triggered the following error:  '.$_FILES['photo']['error'];
}
}

//you get the following information for each file:
$_FILES['field_name']['name']
$_FILES['field_name']['size']
$_FILES['field_name']['type']
$_FILES['field_name']['tmp_name']`

refrence from http://davidwalsh.name/basic-file-uploading-php


text:
Q: How to map array of objects to array of object properties with nested array MongoDB c# I'm trying to create the following methods to retrieve an array of ObjectId from a child array.
GetStorageLocationIds()
GetStorageRoomIds(ObjectId locationId)
GetStorageSectionIds(ObjectId locationId, ObjectId roomId)
GetStorageShelfIds(ObjectId locationId, ObjectId roomId, ObjectId sectionId)
GetStorageSlotIds(ObjectId locationId, ObjectId roomId, ObjectId sectionId, ObjectId shelfId) (this one may not be as difficult because it is already an array of ObjectId)
Each method should return an IEnumerable<ObjectId> containing an array of the id property of the appropriate array. I realize I could just get the entire document for every list but I would prefer a more efficient and elegant solution using the MongoDB c# driver.
This is an example document:
{
"_id" : ObjectId("5cb2271a4bd93c0dec4db163"),
...
"StorageRooms" : [
    {
        "_id" : ObjectId("5cb49adc36ad6719bf947103"),
        ...
        "StorageSections" : [ ]
    },
    {
        "_id" : ObjectId("5cb49afa36ad6719bf947106"),
        ...
        "StorageSections" : [
            {
                "_id" : ObjectId("5cb49bb8c40cd319cb2511ae"),
                ...
                "StorageShelves" : [ ]
            },
            {
                "_id" : ObjectId("5cb49bb8c40cd319cb2511af"),
                ...
                "StorageShelves" : [
                    {
                        "_id" : ObjectId("5cb49bfe8d259019d9207f48"),
                        ...
                        "StorageSlotIds" : [ ]
                    },
                    {
                        "_id" : ObjectId("5cb49bfe8d259019d9207f49"),
                        ...
                        "StorageSlotIds" : [ ]
                    }
                ]
            }
        ]
    },
    {
        "_id" : ObjectId("5cb49afa36ad6719bf947107"),
        ...
        "StorageSections" : [ ]
    }
]

}
The above methods should return the following array, using the above example document as the input data. (assuming it is the only one in the collection):
GetStorageLocationIds() ->  ["5cb2271a4bd93c0dec4db163"]
GetStorageRoomIds("5cb2271a4bd93c0dec4db163") -> ["5cb49adc36ad6719bf947103,"5cb49afa36ad6719bf947106", "5cb49afa36ad6719bf947107"]
GetStorageSectionIds("5cb49afa36ad6719bf947106") -> ["5cb49bb8c40cd319cb2511ae","5cb49bb8c40cd319cb2511af"]
etc...
So far, I've been able to write the first one: GetStorageLocationIds. This is the code seems to work well:
public async Task<IEnumerable<ObjectId>> GetAllDocumentIdsAsync(string database, string collection,
        CancellationToken cancellationToken)
    {
        return (await _mongoContext.MongoClient.GetDatabase(database).GetCollection<T>(collection)
            .Find(new BsonDocument())
            .Project(new BsonDocument {{"_id", 1}})
            .ToListAsync(cancellationToken)).Select(x => x[0].AsObjectId);
    }

When it comes to the next one, I tried using ProjectionDefinition but all it did was return the document id instead of each id in the StorageRooms array.
public async Task<IEnumerable<ObjectId>> GetStorageRoomIdsAsync(ObjectId id, CancellationToken cancellationToken)
    {
        var filter = Builders<StorageLocation>.Filter.And(
            Builders<StorageLocation>.Filter.Where(location => location.Id == id));
        var projectionDefinition = Builders<StorageLocation>.Projection.Include(location => location.StorageRooms);

        var projectionResult = await ProjectAsync(filter, projectionDefinition, cancellationToken);
        return projectionResult.Select(x => x[0].AsObjectId);
    }

After some attempts at using aggregation, I believe it will work with Unwind but I'm lost at how to implement this in c# correctly. Thanks in advance for any help.
Edit Note: ObjectId and string are used exchangeably in this question for brevity. I use AutoMapper for my actual project
Edit 2:
The answer from micki worked for GetStorageRoomIds. I'm now trying to use the following code for GetStorageSectionIds but get an error:
return from location in AsQueryable()
            where location.Id == id
            from room in location.StorageRooms
            where room.Id == roomId
            from section in room.StorageSections
            select section.Id;

The error is here

A: For queries like this you can run AsQueryable() on your IMongoCollection and then use LINQ syntax like below:
var storageRoomIds = from location in Col.AsQueryable()
                     where location.Id == locationId
                     from room in location.StorageRooms
                     select room.Id;

You can also turn on MongoDB profiler to see that it will be translated into
"pipeline" : [
    {
        "$match" : {
            "_id" : ObjectId("5cb2271a4bd93c0dec4db163")
        }
    },
    {
        "$unwind" : "$StorageRooms"
    },
    {
        "$project" : {
            "_id" : "$StorageRooms._id"
        }
    }
],

So you have both simple C# code and efficient MongoDB query
EDIT: for level below you can still use LINQ syntax:
var rooms = from location in Col.AsQueryable()
            where location.Id == locationId
            from room in location.StorageRooms
            select new
            {
                roomId = room.Id,
                storageIds = room.StorageSections.Select(x => x.Id)
            };

var storageIds = from room in rooms
                where room.roomId == roomId
                from storageId in room.storageIds
                select storageId;

var result = storageIds.ToList();

and this gets translated into:
"pipeline" : [
    {
        "$match" : {
            "_id" : ObjectId("5cb2271a4bd93c0dec4db163")
        }
    },
    {
        "$unwind" : "$StorageRooms"
    },
    {
        "$project" : {
            "roomId" : "$StorageRooms._id",
            "storageIds" : "$StorageRooms.StorageSections._id",
            "_id" : 0
        }
    },
    {
        "$match" : {
            "roomId" : ObjectId("5cb49afa36ad6719bf947106")
        }
    },
    {
        "$unwind" : "$storageIds"
    },
    {
        "$project" : {
            "storageIds" : "$storageIds",
            "_id" : 0
        }
    }
],


text:
Q: Delphi 7:How to get the distance between 2 addresses I'm writing a program in Delphi for a (fake) courier company as a project. What I need, is the distance between the recipient and the couriers location. So I can work out what mode of transport should be used.
How can this be achieved? Via Google Maps?

A: You need to use the Google Distance Matrix Service
Take a look at this question for details on how to use it


text:
Q: What is the question tag for sentences whose subjects are "none...is" and "each...is"? I know that  indefinite pronouns like none and each take singular verbs, but what about their question tags?

*

*None of the boys has passed the test, ________?

*Each of the girls was given a prize, _______?

What are the question tags for these two sentences? Should the question tag's verb be in the singular like the subject or plural because we're talking about all of them?
What about that question tag's pronoun? Would gender come into consideration?


text:
Q: The "data" attribute in elements I don't have any trouble running my code. My question is: is this what I'm doing a good practice? Is this cross-browser/cross-platform compatible?
I'm using xhtml strict doctype.

Now you probably wonder why I'm not doing:

I give you an example why I'm doing so.
I'm loading all comments in one website with the default avatar image I want to load the right image only when the user scrolls down so I need to store somewhere the right image source.

without this I need to do:

And that produces dozens unnecessary script tags.
I know I can merge all these scripts in php and than display at once but the code will not be so readable like with the "data" solution.
If you know any better solution please let me know.

A: As parent5446 suggests in his answer, the nice way to do this is with HTML5's custom data attributes.  These begin data- and can be used for your application's own purposes.  They will otherwise be ignored by the browser.
Even better, the most recent versions of jQuery will automatically load them into a .data() call, so you don't need to do a hacky call to .attr().
You could use the following HTML:

And then access it in the following way with jQuery:
alert($('#avatar-1').data('src'));

A: For some reason it seems the data attribute in the way you're using it simply does not exist. The only data attribute in XHTML is that of the  tag. You might be talking about the custom data tags in HTML5. It is very well possible that jQuery is thinking your code is HTML5 and treating the data attributes as such, but I'm not too sure on that part.
Just adding from a comment on this question below, it turns out JavaScript has always been able to read arbitrary attributes, but it will not validate and some developers consider it bad form.


text:
Q: Finding a sequence of functions which Г-converges to a given smooth function in $L^2([0;1])$ In $L^2([0;1])$: $u(x)$ is given smooth (piecewise linear) function, s.t.$u: [0;1]\to \mathbb{R}$.
Function $\rho: [0;1] \to \mathbb{R}$, s.t.
$
    \rho(x) =
    \begin{cases}
        1, & \text{if  $x\in[0;{1\over2})$;} \\
        2, & \text{if $x\in[{1\over2};1]$.}
    \end{cases}
$.
Then $$c = {1\over{\int_{0}^1{1\over{\rho(x)}}dx}} = {4\over3}.$$
We should find a sequence of functions $u_n$, $u_n$ $\Gamma$-converges to $u$, s.t. $$\lim_{n\to\inf}\int_0^1\rho(nx)(u_n^{'}(x))^2dx \to \int_0^1{4\over3}(u^{'}(x))^2dx.$$
Moreover, I know that if $u = {{b-x}\over{b-a}}$, then $u_n$ is a solution of
$$\left\{
    \begin{aligned}
        {d\over{dx}}\Big{[}\rho(nx){d\over{dx}}u_n(x)\Big{]}    &= 0 \\
        u(a)     &= 1  \\
        u(b) &= 0
    \end{aligned}
\right.$$
I don't know how to find any solution even a partial one for $u = {{b-x}\over{b-a}}$.
Can someone help me, please?


text:
Q: Plotting a step (piecewise) function with vertical lines Trying to plot a signal function of 0 and 1, much like the solution given to the question below:
How to plot non-numeric data in Matplotlib
However, I'd like to have vertical lines instead of bent ones when the function goes from 0 to 1. So for instance if f(x)=0 for x = 1 2 3 4 and f(x) = 1 thereafter, I'd like a horizontal line at y=0 up to x=5, and a vertical line at x=5 going from y=0 to y=1, and then a horizontal line at y=1 thereafter
Can this be done within the plot function? Or do I need to draw a ton of squares?
Thanks!

A: You can use stairs or area functions. As shown here:
%# Sample input
x = 1:10;
y = [0 0 0 0 1 1 1 1 1 1];

subplot(2,1,1)
stairs(x,y)
title('Stairs chart (non area)')

subplot(2,1,2)
x = [x;x];
y = [y;y];
area(x([2:end end]),y(1:end))
title('Stairs area')

A: Have you tried the stairs function?


text:
Q: PHP: Is it safe to include a file based on a GET variable, if you use preg_replace to only allow the following -A-Za-z0-9_ How safe is this?
   if (isset($_GET["var"]) && file_exists("path/".$_GET["var"].".php")) {
        include("path/".$_GET["var"].".php");
    } else {
        echo 'File Does Not Exist!';
    }

I'm wondering if $_GET["var"] needs to be "sanitized" opposed to just letting it run against the file_exists function before trying to include it or not. Is this dangerous?
+++UPDATED+++
Thank you all for your responses! Please see updated below...
function mrClean($var) {
$clean_var = (isset($var) && !empty($var)) ? $var : 'index';
$clean_var = preg_replace('/[^-A-Za-z0-9_]/', '', $clean_var);
return $clean_var;
}

$var = mrClean($_GET["var"]);

if (file_exists("path/".$var.".php")) {
  include("path/".$var.".php");
} else {
  echo 'File Does Not Exist!';
}

When I call on mrClean to replace all, but the following:
- A-Z a-z 0-9 _ via preg_replace
...will this now be considered safe? Is there anything that can be added to make this any safer?
I will implement a whitelist as suggested... but anything else?
Thank you!!
-Andrew

A: You do not want to do this.
let's say i am running index.php in /var/www/test and inside of that is path (so /var/www/test/path exsts)
if i ask this question - file_exists('path/../../../../etc/nginx/sites-available/default.php')
the answer is YES
i.e. a file in /etc/nginx/sites-available/default.php does exist. All I did was pass in $_GET['var'] as "../../../../etc/nginx/sites-available/default"
so now you have asked the webserver to include some random file into your page.
now - we have to note here that depending on permissions, operating system etc. this may not work the same. But in general, you don't want to do this - go the long way and if statement / switch statement stuff into the includes.
You can try to make sure the input is safe by removing characters etc. but in the end, one mistake will cost you your whole file system - not worth it!

A: Yes, the regex replace within your question update is SAFE. But be aware of that ANY include is dangerous and if you will allow the user to include some unsafe script.


text:
Q: Create files in fuse using C Im trying to have fuse create files when I mount the system using the init function. However whenever I mount my system the process never ends. Then i cant unmount it afterwards. How do i fix this.
void file_init(struct fuse_conn_info *conn){
FILE *fp;
fp=fopen("/data1/fuse/file.txt","w+");
fclose(fp);
}

Thats the code im using. I need to create multiple files but I cant even get this 1 file to work.

A: Check the return of fopen if you want to know why it fails:
fp = fopen("/data1/fuse/file.txt", "w+");
if (fp == NULL) {
    perror("fopen");
    exit(EXIT_FAILURE);
}
fclose(fp);

If data1 is in the same directory (not in the root path), change
fp=fopen("/data1/fuse/file.txt","w+");

to
fp=fopen("data1/fuse/file.txt","w+"); /* remove the first backslash */


text:
Q: "Select your next badge" modal displays badges with incorrect width and positioning When searching for a badge in the "Select your next badge" modal, the badge width and positioning are incorrect sometimes. The examples below are on Meta Stack Exchange and Stack Overflow:

Even when the search returns three badges, the total width is different from when the modal is unfiltered:

The modal displaying all badges is like this:


text:
Q: button image upload in bootstrap,jquery and php i need to create a button with width 55 and height 45. initially the button should contain some default image. then when the user wants to change it, he can choose an image from his computer by selecting this button and once it is selected the image should be set that button and whenever we hover a mouse it should display change and we select it again we are able to change an image to it. how to do it. Is anybody know this. plz help me.
for ex: in scratch website https://scratch.mit.edu, after login,in profile page you can see this image button


text:
Q: WPF command binding broken I saw this SO question but when I tried it it does not work.
I know I can do mvvm but what the execute command be doing is view specific so I wanted it to be done on the view.
<Grid>
        <TextBox>
            <TextBox.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="_Copy" CommandTarget="{Binding Path=PlacementTarget,
          RelativeSource={RelativeSource FindAncestor,
          AncestorType={x:Type ContextMenu}}}">
                        <MenuItem.CommandBindings>
                            <CommandBinding CanExecute="CommandBinding_CanExecute"
                                                Executed="CommandBinding_Executed"
                                                />
                        </MenuItem.CommandBindings>
                    </MenuItem>
                </ContextMenu>
            </TextBox.ContextMenu>
        </TextBox>
    </Grid>

Code behind:
private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = false;
        }

I am expecting the menu to be disabled but it is not:

I tried other approaches:
<!--Approach 2: CopyCommand as property of the Window. CopyCommand is in code-behind of the window-->
<MenuItem Header="_Copy" Command="{Binding Path=CopyCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"/>

<!--Approach 3: Saw other samples on the net about binding to PlacementTarget. CopyCommand is in code-behind of the window-->
<MenuItem Header="_Copy" Command="{Binding Path=PlacementTarget.CopyCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>

A: If you are trying to implement WPF inbuilt ApplicationCommands.Copy property all you need to do is
<TextBox>
    <TextBox.ContextMenu>
        <ContextMenu>
                <MenuItem Command="ApplicationCommands.Copy"/>
        </ContextMenu>
    </TextBox.ContextMenu>
</TextBox>

Since the command is associated with the textbox it will automatically handle the execute and can execute events.
However if you want to implement your own custom command you have to be little bit verbose
public static class MyCommands
{
    public static readonly RoutedUICommand Copy= new RoutedUICommand
            (
                    "Copy",
                    "_Copy",
                    typeof(MyCommands),
                   null
            );

    //You can define more commands here
}

private void CommandBinding_CanExecute(object sender,  CanExecuteRoutedEventArgs e)
{
        e.CanExecute = true; //can check with debugger...
}

private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
     //Your Action
}

in your xaml
<Window.CommandBindings>
    <CommandBinding Command="local:MyCommands.Copy" CanExecute="CommandBinding_CanExecute" Executed="CommandBinding_Executed" />
</Window.CommandBindings>
<Grid>

    <TextBox>
        <TextBox.ContextMenu>
            <ContextMenu>
                <MenuItem Command="local:MyCommands.Copy"/>
            </ContextMenu>
        </TextBox.ContextMenu>
    </TextBox>
</Grid>

A: I have my CopyCommand in the view's code behind.
View:
public ICommand CopyCommand { get { return _copyCommand; } }

Then I was able to access it when I put the view's instance in the textbox's tag property as specified here
<views:myView>

<Grid>
<TextBox Tag="{Binding RelativeSource={RelativeSource AncestorType={x:Type views:myView}}}">
            <TextBox.ContextMenu>
                <ContextMenu DataContext="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
                        <MenuItem Header="_Copy" Command="{Binding CopyCommand}"/>
                    </ContextMenu>
            </TextBox.ContextMenu>
        </TextBox>
</views:myView>

</Grid>

A: Specify Command in your MenuItem like this :
<MenuItem Command="ApplicationCommands.Copy" .../>

Also specify a value for Command property in the CommandBinding,
<MenuItem.CommandBindings>
     <CommandBinding Command="ApplicationCommands.Copy" CanExecute="CommandBinding_CanExecute"
                     Executed="CommandBinding_Executed" />
</MenuItem.CommandBindings>


text:
Q: Recovering the solution of optimization problem from the dual problem In the context of (most of the times convex) optimization problems -
I understand that I can build a Lagrange dual problem and assuming I know there is strong duality (no gap) I can find the optimum of the primal problem from the one of the dual. Now I want to find the primal optimum point (i.e. the point in which the optimum is attained). Somehow, it is assumed that both the optimum of the primal and dual point are achieved at the same point (which is then a saddle point). Why/when is that true? Does strong duality can happen only at a saddle point? Does that require the primal problem to be convex?
Now, from this, it is assumed it's enough for to find the minimizer of the Lagrangian at the value of dual parameters (point of the solution of the dual problem) in order to get the primal optimal point. Why is that true?
Thank you,
Dany

A: Ok, so I'm not totally sure whether this addresses all (some!) of your doubts, so let me know if it does not. As a disclaimer, what follows is just one out of several ways to view duality in optimisation (you can find others in the answers to this post).
To make things a bit concrete I'm going to assume that your primal problem is a minimisation problem with objective $f:\mathbb{R}^n\to\mathbb{R}$ and set of feasible points $X\subseteq\mathbb{R}^n$. Suppose we can find some function $\phi:\mathbb{R}^m\to\mathbb{R}$ and set $Y\subseteq\mathbb{R}^m$ that has the following property:

$\phi$ evaluated at any point $y\in Y$ gives a lower bound for $f$ over all of $X$. That is, for any $y\in Y$
$$f(x)\geq \phi(y)\quad\quad\forall x\in X.$$

Note that the above implies that for any $y\in Y$, $\phi(y)$ is also a lower bound for the optimum value of the primal (that is, $p^*:=\inf_{x\in X}f(x)$). Then an interesting question to ask is what is the best lower bound we can extract from $\phi$ and $Y$? What is $d^*:=\sup_{y\in Y}\phi(y)$?
We call answering this question "a dual problem to the original primal problem" and we say that "strong duality" holds for this primal-dual pair if $d^*=p^*$.
Strong duality is handy because (assuming we can solve the dual problem) it gives us a way to check how suboptimal a candidate optimal point $\tilde{x}$ (which we have computed in some way) of the primal is by simply computing the difference $f(\tilde{x})-d^*$ (otherwise, since we don't know $p^*$, it is hard to judge how good is our candidate optimal point $\tilde{x}$). Indeed, if $f(\tilde{x})=d^*$ we know that $\tilde{x}$ is optimal and we can stop looking for a better $x$.
In order for the above to be of use, we should aim to construct a dual problem that is simple to solve. This is where the Lagrangian dual problem comes in; it is a dual problem which is always convex irrespective of whether the primal is.
The objective function of the Lagrangian dual problem is
$$\phi(y):=\inf_{x\in X}L(x,y)$$
where $L$ is the so-called "Lagrangian function" and $y$ are the "Lagrangian multipliers".
To check whether strong duality holds for a given primal-dual pair there is a whole battery of sufficient conditions collectively referred to as constraint qualifications. The most basic of which applies to the case where the primal is convex and the dual is the Lagrangian dual is called Slater's condition. It asks that there exists at least one "strictly feasible" point for the primal (that is, that $X$ has non-empty relative interior). If I remember correctly, in this case strong duality holds if and only if $L(x,y)$ has a saddle point (which turns out to be a pair of optimal point $x$ and multipliers $y$), however I don't have an intuitive explanation why this is so.
With regards to how to actually find an optimal point $x^*$ what typically happens in practice is that people run an optimisation algorithm (often gradient decent or Newton's) on both (and separately) the primal and dual problems which hopefully generate some sequences $(x_n)$ and $(y_n)$ such that
$$f(x_1)\geq f(x_2)\geq f(x_3)\geq\dots,\quad\quad L(y_1)\leq L(y_2)\leq L(y_3)\leq\dots.$$
Every few iterations they stop and check whether the difference $f(x_n)-L(y_n)$ is smaller than some tolerance level and if so stop completely and say that $x_n$ optimal. They call the corresponding $y_n$ a certificate of optimality, because anyone can then verify that $x_n$ is (nearly) optimal by checking that the mentioned difference is small. This is the essence of the so called primal-dual solvers. Note that if the primal, said algorithms is guaranteed to generate $x_n$ such that $f(x_n)\to p^*$ (ditto with respect to the dual problem).

A: I know this question was asked some time ago, but I just stumbled upon it myself wondering the same thing, so I will post what I have found out in case it is helpful to someone else.
I think the answer you seek is in Boyd and Vandenberghe's Convex Optimization (freely available on Boyd's website: http://stanford.edu/~boyd/cvxbook/) in sections 5.1-5.5 (especially, see subsection 5.5.5). Below are my key takeaways from that text.
Let
\begin{align}
\min \;\;\;\; &f_0(x)\\
\text{s.t.} \;\;\;\; &f_i(x) \leq 0 \;\;\;\; i = 1,\ldots,m \tag{1} \label{eq:1}\\
 &h_i(x) = 0 \;\;\;\; i = 1,\ldots,p,
\end{align}
where $x \in \mathbb{R}^n$ be the optimization problem (not necessarily convex) we're considering. The Lagrangian of this problem is
$$
L(x, \lambda, \nu) = f_0(x) + \sum_{i=1}^m \lambda_i f_i(x) + \sum_{i=1}^p \nu_i h_i(x).
$$
The Lagrangian dual is
$$
g(\lambda,\nu) = \inf_{x \in \mathcal{D}} \left( f_0(x) + \sum_{i=1}^m \lambda_i f_i(x) + \sum_{i=1}^p \nu_i h_i(x) \right),
$$
where $\mathcal{D} := \left( \bigcap_{i=0}^m \operatorname{dom} f_i \right) \cap \left( \bigcap_{i=1}^p \operatorname{dom} h_i \right)$. The Lagrangian dual problem, in turn, is
\begin{align}
\max \;\;\;\; &g(\lambda,\nu)\\
\text{s.t.} \;\;\;\; &\lambda \succcurlyeq 0.
\end{align}
Note that
\begin{align}
\sup_{\lambda \succcurlyeq 0, \; \nu} L(x,\lambda,\nu)
&= \sup_{\lambda \succcurlyeq 0, \; \nu} \left( f_0(x) + \sum_{i=1}^m \lambda_i f_i(x) + \sum_{i=1}^p \nu_i h_i(x) \right) \\
&=
\begin{cases}
f_0(x) & \text{if } f_i(x) \leq 0, \; i = 1,\ldots,m, \text{ and } h_i(x) = 0, \; i=1,\ldots,p \\
\infty & \text{otherwise}.
\end{cases}
\end{align}
This means that
$$
p^\star := \inf_x \sup_{\lambda \succcurlyeq 0, \; \nu} L(x, \lambda, \nu)
$$
is the optimal value of the primal problem \eqref{eq:1}. Note that there is no restriction on the $x$ values over which we take the infimum, since the conditions of \eqref{eq:1} are already included in the $\sup L$. Moreover, by definition,
$$
d^\star := \sup_{\lambda \succcurlyeq, \; \nu} \inf_x L(x,\lambda,\nu)
$$
is the optimal value of the dual problem.
Let us now assume that strong duality holds. Then $d^\star = p^\star$. Furthermore, also assume that both the primal and dual problem optimal values are attained, i.e., that there exist feasible $x^\star$ and $(\lambda^\star,\nu^\star)$ such that $f(x^\star) = d^\star$ and $g(\lambda^\star,\nu^\star) = d^\star$. Then
\begin{align}
f_0(x^\star)
&= g(\lambda^\star,\nu^\star) \\
&= \inf_x \left( f_0(x) + \sum_{i=1}^m \lambda_i^\star f_i(x) + \sum_{i=1}^p \nu_i^\star h_i(x) \right) \\
&\leq f_0(x^\star) + \sum_{i=1}^m \lambda_i^\star f_i(x^\star) + \sum_{i=1}^p \nu_i^\star h_i(x^\star) \\
&\leq f_0(x^\star)
\end{align}
(for motivations of each equality/inequality, see page 242 in Boyd and Vandenberghe's book). This implies that the inequalities are in fact equalities. We from this, we can conclude that $x^\star$ solves the problem $\inf_x L(x,\lambda^\star,\nu^\star)$. Finally, assume that $\inf_x L(x,\lambda^\star,\nu^\star)$ has a unique solution (which happens e.g. if $L(x,\lambda^\star,\nu^\star)$ is a strinctly convex function of $x$). Then $x^\star$ is that solution, and therefore
$$
x^\star = \arg\min_x L(x,\lambda^\star,\nu^\star).
$$

A: If you solved the dual and have optimal values for the dual variables, then plug those optimal dual values back into the Lagrange equation.  Now you have an equation with only x as unknown.  Minimize, and you've recovered the value for x.


text:
Q: How to ignore the underbrace{}{} in a square root? I want to keep the size of the square root unchanged without putting the underbrace outside

\sqrt{\underbrace{=A}{B}}

A: Smashing the radicand is not sufficient. Here's a working version:
\documentclass{article}
\usepackage{amsmath}
\usepackage{lipsum} % just for the example

\newcommand{\smashedsqrt}[2][]{%
  \vphantom{#2}%
  \sqrt[#1]{\smash[b]{#2}}%
}

\begin{document}

\lipsum*[3]
\[
\smashedsqrt{\underbrace{B}_{=A}}
\]
\lipsum*[3]
\[
\sqrt{\smash[b]{\underbrace{B}_{=A}}}
\]
\lipsum[3]

\end{document}

The second example shows the problem with the simple smashing.

A: I suppose this is what you want:

Here is the exact code:
\sqrt{\smash[b]{{\underbrace{B}_{=A}}}}

However the square root symbol is wider than if there were no underbrace if the "B"  part is too small. In such case one has to do some (limited) manual adjustment because the square root symbol must not be too close from the underbrace. All this is illustrated with the following code:
  \begin{align*}
  & \sqrt{\smash[b]{{\underbrace{B + C + D}_{=A}}}}\qquad \sqrt{B + C + D}\\[4ex]
  & \sqrt{B}\qquad \sqrt{\mskip-6mu \smash[b]{{\underbrace{B}_{=A}}}\mskip-6mu}
  \end{align*}

Moreover, as pointed by @egreg, smashing can cause a problem with vertical spacing with the following text, so one should add, as he did in his answer, a \vphantom of the unsmashed square root, hence the creation of macro in order to make typing less painful — and the  code clearer.

A: Here is an adaptation of
Typesetting 144...4 with "n times" under the 4's is easy, but what about \sqrt{144...4}?, and note that the size of the \sqrt symbol is not affected by the underbrace:

Note:

*

*This does require two runs. First one to determine the locations, and the second to do the drawing.

*The \tikzmark is from Adding a large brace next to a body of text.

*As this is a tikz solution, all the inherent drawing capabilities are available - shown here is just the color of the brace and the text, but many more options are available.
Code:
\documentclass{article}
\usepackage{amsmath}
\usepackage{tikz}
\usepackage{lipsum}
\usetikzlibrary{calc}
\usetikzlibrary{decorations.pathreplacing}

\newcommand{\tikzmark}[1]{\tikz[overlay,remember picture] \node (#1) {};}

% Tweak these as necessary
\newcommand*{\BraceAmplitude}{0.25em}%
\newcommand*{\VerticalOffset}{0.4ex}%
\newcommand*{\HorizontalOffset}{0.12em}%
\newcommand*{\SquareBraceVOffset}{-0.4ex}%

\newcommand*{\InsertUnderBrace}[4][]{%
    \begin{tikzpicture}[overlay,remember picture]
\draw [decoration={brace,amplitude=\BraceAmplitude},decorate, thick,draw=blue,text=black,#1]
        ($(#3)+(\HorizontalOffset,-\VerticalOffset)$) --
        ($(#2)+(-\HorizontalOffset,-\VerticalOffset)$)
        node [below=\VerticalOffset, midway] {#4};
    \end{tikzpicture}%
}%

\newcommand*{\InsertUnderSquareBrace}[4][]{%
    \begin{tikzpicture}[overlay,remember picture]
        \draw [text=black,line width=0.7pt, #1]
            ($(#3)+(\HorizontalOffset,\VerticalOffset+\SquareBraceVOffset)$) --
            ($(#3)+(\HorizontalOffset,-\VerticalOffset+\SquareBraceVOffset)$) --
            ($(#2)+(-\HorizontalOffset,-\VerticalOffset+\SquareBraceVOffset)$)
            node [below, midway] {#4} --
            ($(#2)+(-\HorizontalOffset,\VerticalOffset+\SquareBraceVOffset)$);
    \end{tikzpicture}%
}%

\begin{document}
\lipsum[1]
\[
    \sqrt{\tikzmark{StartBraceA}B\tikzmark{EndBraceA}\,}
    \hspace*{4.0em}
    \sqrt{\tikzmark{StartBraceB}B\tikzmark{EndBraceB}\,}
\]
\InsertUnderBrace[draw=red,text=blue]{StartBraceA}{EndBraceA}{$=A$}
\InsertUnderSquareBrace[draw=red,text=blue]{StartBraceB}{EndBraceB}{$=A$}

\lipsum[2]
\end{document}


text:
Q: Rails: hook for validating model when it's appended to its parent resource? I have a situation where a user submits a multi-model form. Through that form, I have to assign the user a random item from my database along to their account. As I loop through the data, I flag the item that I've assigned to them with a boolean in_use flag. The problem is, in a situation such as the following:
2.times do |n|
   # grab random item which will be parent
   parent = # some random code to grab an item not in use
   parent.in_use = 1
   parent.child.build
   children << child
end

Three models involved here. The parent itself is within its own parent, hence the children << child statement. The problem here is an edge condition is that the code that grabs a random item not in use can grab the same parent twice as I don't know of a hook that will allow me to save parent.in_use after the child has been appended to its parent via children << child. The loop will go again, the in_use flag hasn't been persisted to the database and it can select it again. Is there a way to persist it, then roll it back if validation fails in a situation like this?

A: Does this work?
2.times do |n|
  # grab random item which will be parent
  parent = # some random code to grab an item not in use
  parent.child.build
  parent.in_use
  parent.save # <--- save the parent on the db
  children << child
end

I'm not sure about the last line, since you didn't explain what the children variable was. I'm also assuming that parent.in_use is a method, not a property (otherwise you would have to write parent.in_use = true or something similar)
One more thing - it seems you are using an external attribute (called in_use or similar) in order to store whether a parent has children. It would be probably simpler just to count the number of children. There are several ways to do this, but a good compromise is using an automatic counter cache.
class Parent << ActiveRecord::Base
  has_many :children, :counter_cache => true #this will had a children_count attribute

The attribute is named just like the children table. So if you write has_many :issues, the counter will be issues_Count.
You will have to add a children_count attribute to the parent's table.
You then can do if parent.children_count > 0 instead of checking strange parent.in_use attributes.
More information on the counter cache on railscast#23

A: Your question is frustrating, because you say your issue stems from pulling in the same parent twice, but the code to pull the parent is omitted. Yet the code for an irrelevant confusing contextless 3 model relationship is left in.
Anyway, I'm going to say this how it seems from my perspective, and I think you'll agree:
The solution you are asking for has you getting the same parent twice (now in two places in memory with different state between them) building relationships that shouldn't exist, somehow figuring this out in your validations, having a conditional in the loop to check for it and retry the whole process.
From my perspective, this sounds like a nightmare. As someone who has written horribly convoluted bug inclined code like that, I strongly recommend you just get two different parents in the first place. Don't let errors propagate across your app, contain them early, or better yet, prevent them from happening at all:
class YourUnnamedModel < ActiveRecord::Base
  named_scope :unused  , :conditions => { :in_use => false }
  named_scope :random  , :order => 'RANDOM()'
  named_scope :limited , lambda { |n=1| return :limit => n }

  def self.example
    unused.random.limited(2).each do |parent|
      puts "doing stuff with #{parent.inspect}"
    end
    nil
  end

end

Caveat: For some stupid reason (https://rails.lighthouseapp.com/projects/8994/tickets/1274-patch-add-support-for-order-random-in-queries), it is possible that your 'RANDOM()' could be called something else.


text:
Q: add space between document text and knitr code chunk in compiled pdf I am using RStudio (0.98.501) to compile a .Rnw with R code chunks into a pdf. In the resulting PDF, there is no space between document text and R code chunks. I have not come across any knitr chunk or package options that let me specify vertical space between text and code chunks. I'd like to add one more line in between the text and the code chunk. I'm looking for a global solution; manually adding vertical space before each code chunk would not be reproducible.
Basic example showing partial .tex output from knitr compile:
Histogram of VCCT test dates:
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlcom{# sort}
  \hlstd{vcct.base} \hlkwb{<-} \hlstd{vcct.base[}\hlkwd{do.call}\hlstd{(order, vcct.base[}\hlkwd{c}\hlstd{(}\hlstr{"date.test.vcct"}\hlstd{)]), ]}
...
\end{alltt}
...
\end{knitrout}

A: There must be several ways to do this. For example, you can define the knitrout environment:
\renewenvironment{knitrout}{\vspace{1em}}{}


text:
Q: Printing Produces Error "Could not find image named 'LayoutDirection1.png'." I recently tried running the HelloWorldPrinter.java file that is included as part of Oracle's A Basic Printing Program tutorial. The code does what it is supposed to, but right before the print dialog box appears, I get the following output in my console, which appears in red letters:
2013-04-01 21:06:09.512 java[16458:407] Could not find image named 'LayoutDirection1.png'.

Obviously a problem has been reported, but I don't see anything wrong with the print dialog box. I'm not sure what this means and if it is something that I should fix. When I export HelloWorldPrinter into an app, this error still appears (via Console.app), so it's not a problem with Eclipse. If it matters, I'm currently using Mac OS 10.7.5.
EDIT: Also tried removing the line about setting the look and feel and also setting to default Mac OS X look and feel, but it didn't solve the problem.


text:
Q: Как внести сразу несколько объектов через форму? Есть страница с формой отправки данных документа на django.
Форма имеет несколько табов(вкладок). Один таб на каждый вид документа.
Для всех видов документа одна модель в базе данных. На каждом табе формы одинаковые поля и передается скрытое поле "вид документа".
Как сделать, чтобы при отправки формы, информация из всех табов вносилась в базу данных.

A: Более правильным архитектурным решением было бы использовать разные формы для разных моделей. Но если очень нужен именно такой костыль, то можно использовать обычную форму вместо модельной и в представлении вручную создавать модели, перенося в них данные из формы.


text:
Q: I don't understand the working of placement new and how to free the memory Allocated some memory-
buf = new char[sizeof(student_rec)*5];//student_rec is class

Then create an array of class 'student_rec' using placement new.
student_rec *sr1;
sr1 = new(buf)student_rec[5];

Call the method fun() for each class.
for(i=0; i<5; i++)
{
    sr1[i].fun();
}

And after that call the destructor for each class.
i = 5;
while(i)
    sr1[--i].~student_rec();

And delete the allocated memory chunk using delete.
delete [] buf;

Then why after that using sr1[2].fun() it prints 'hello' ?
When i delete the memory using delete [] buf then there is no memory present for object. Then why sr1[2] works fine ?
Here is my code-
class student_rec
{
    private:

       string name;
       int roll_no;
       float percentage;

    public:

       student_rec()
       {
           cout<<"zero argument constructure\n";
       }

       ~student_rec()
       {
           cout<<"destructure\n";
       }

       student_rec(char *n, int r, float per)
       {
           cout<<"three argument constructure\n";
           name  = n;
           roll_no = r;
           percentage = per;
       }

       void show()
       {
           cout<<"Name= "<<name<<endl;
           cout<<"Roll No.= "<<roll_no<<endl;
           cout<<"Percentage= "<<percentage<<endl;
       }

       void fun()
       {
           cout<<"hello\n";
       }

};

int main()
{
   char *buf;
   buf = new char[sizeof(student_rec)*5];
   student_rec *sr1;
   sr1 = new(buf)student_rec[5];
   int i;
   for(i=0; i<5; i++)
   {
       sr1[i].fun();
   }
   i = 5;
   while(i)
       sr1[--i].~student_rec();
   delete [] buf;
   sr1[2].fun();
   return 0;
}

A: As the comments already mentioned: What you do is "Undefined Behaviour".
But for your special case, your function fun() did not access any data member of your class and is also not a virtual method, so nothing from your object will be used and so it works quite perfect, also if you will clear your memory, because there is really nothing in the objects memory, what is needed to call this function. As this, you can make this method a static one which then can be accessed without a object of that class.
The compiler knows the type of your pointer student_rec and it also knows that there is no access to any object so it will call simply the method without any data access in your allocated and freed memory.
The following code will also work but is also undefined behaviour:
class Bla
{
    public:
        void fun() { std::cout << "Hallo" << std::endl; }
};

int main()
{
    Bla* ptr=0;

    ptr->fun(); // access of 0 pointer? No-> no data access, simply function call! But never do that in real code ;)
}

The method is from the logic point of view part of the class and not of the objects. As you can see, we never create an instance of the class but the code will also work in most cases.
On gcc 6.1 it compiles and works also with -O0, so it is not dependent on optimization at all. No object data access, so it works without object. But remember: This is perfect invalid code! :-)
Edit: From the comments: Why valgrind did not catch such errors?
Quite simple:
If we look into the details of what a compiler makes from a method, we get something like that: ( pseudo code! )
class Bla { void fun() { ... } };

is translated internally to:
Bla::fun( Bla* this ) { ... }

Dependent on the implementation of the compiler, typically the first function parameter is the pointer to the object itself. So the call of fun() results in calling Bla::fun( this ); At this point, it is fully independent of the value of this! So if, as given in my above code example, this is 0! And inside Bla::fun() nothing access the this pointer. So the code seems to be valid!
Valgrind itself checks only on the executable itself, so valgrind will not find an invalid access of data members because it simply find no access which is valid at all :-)
"if this works, what is the difference with static functions?"
If the method is defined as static, the compiler generates a function without the this pointer. So it is different.
"And how are we ever going to trace such errors?"
If your method is not static but did not access any data member, it is a design flaw. I can't see a reason why we should have a method without access to the objects data at all which is not declared static.
My advice here is, to check if you have such non static methods? But yes, I did not know if any compiler can generate a warning on such methods.


text:
Q: Adding a .net core worker service as a webjob to existing webapp Is it possible to add a worker service to a already built .net core webapp?
The worker service is also .net core.
We build using a devops pipeline, and I Have tried this and it produces the extra file.
 - task: DotNetCoreCLI@2
      displayName: 'API Build'
      inputs:
        command: 'build'
        projects: '**/Api.csproj'
        arguments: '--configuration $(buildConfiguration)'

    - task: DotNetCoreCLI@2
      displayName : 'WebJob Builds'
      inputs:
        command: 'build'
        projects: '**/WorkerService.csproj'
        arguments: '--configuration $(BuildConfiguration) --self-contained -r win10-x64'

    #----------------------------------------------------------
    # Publish Artifacts
    #----------------------------------------------------------

    # Publish the artifact
    - task: DotNetCoreCLI@2
      displayName: 'Publish API Build'
      inputs:
        command: 'publish'
        publishWebProjects: False
        projects: '**/Api.csproj'
        arguments: '--configuration $(BuildConfiguration) --output $(Build.ArtifactStagingDirectory)/Api'
        zipAfterPublish: True

    - task: DotNetCoreCLI@2
      displayName : 'WebJobs Publish'
      inputs:
        command: 'publish'
        publishWebProjects: false
        projects: '**/WorkerService.csproj'
        arguments: '--output $(Build.ArtifactStagingDirectory)/Api/App_Data/jobs/continuous/Worker'
        zipAfterPublish: true
        modifyOutputPath: false

 - task: PublishBuildArtifacts@1
      displayName: 'Release API Artifact'
      inputs:
        pathtoPublish: '$(Build.ArtifactStagingDirectory)/Api'
        artifactName: 'WebApi'

I am not sure if this is the correct way, I need the worker to run as a job on the API webapp.  How do I setup the release pipeline if this is correct, or how do I correct this and release it.


text:
Q: Identifying a SF anthology with one story about sentient pond water and another about a universal solvent This was one of my father's old books that I read twenty or more years ago. He had bought it in a barn somewhere in the back country where the owner was just trying to make a couple of bucks. My father only had a quarter, enough to buy this book. When he came back the following weekend with money, the place was gone, shut down or burned down, I don't really remember anymore. This would have been in the 1970's I think.
The book was a hardcover with no dust jacket. The cover was a deep blood red, but that may have been from age. I remember my father was excited about the book because it was something special. He might have said it was the first hardcover SF anthology, but I might be misremembering or he may have been wrong. The book was quite thick, several hundred pages, maybe 500. I think the title was on a dark plate on the front. The binding was a slightly darker and different shade of red.
I remember the stories as very golden age. The only one I remember at all clearly was the first one, I think.
A scientist is walking one day and notices that there is an eerily clear pond surrounded by dead animals and plants. It may have had industrial waste runoff but I don't remember. There is a description of something like a half a cow or a deer on the edge of the water, where the rest has been eaten away by the waters. The scientist takes a sample back to the lab of the pond water.
After experimenting, he finds that the water is able to respond to stimuli, eventually hooking up a speaker and finding the water can converse. The water learns rapidly, and figures out a way to become mobile, the small pool walking around. The scientist feeds the water pieces of raw chicken or something, which it dissolves.
The water wants to explore and to spread, and the scientist knows that if it does, there will be no stopping it as the water takes over. In desperation, the water tries to escape down a drain, but the scientist stops it by pouring carbolic acid into the water (I remember distinctly that it was carbolic acid), killing it.
I think there may have been another story in the anthology I vaguely remember. A scientist is sentenced for a crime. His punishment is to spend the rest of his life researching, which doesn't seem so bad. Then he finds out that there are conditions. He must research one of several classical impossible problems. I don't remember if he would be released if he succeeded or not.
The classic impossible problems were things like developing a perpetual motion machine, or a universal solvent. The government figured that there was no point in wasting good scientists, it seemed a fitting punishment, and if any of them ever actually solved one of these problems, it would be a boon.
The scientist decides to look into the universal solvent. Eventually he announces that he has found it. Investigators, skeptical, come to look and just see him at a table, smiling. They demand to see the solvent and he sneers. He explains that a universal solvent couldn't be held in any container, as it would simply dissolve the container. So he had swallowed it. And soon it would work it's way out of his body, through the floor of the prison, and make its way to the center of the earth. I think the implication was that this would destroy the world in some way, but I don't remember how.
I'd like to find this book again, and my father is sadly no longer available for me to ask what he might remember.

A: The first story (sentient pond) is "Liquid Life", a novelette by Ralph Milne Farley (Roger Sherman Hoar), first published in Thrilling Wonder Stories, October 1936, available at the Internet Archive.
Here is a summary by Everett F. Bleiler in Science-Fiction: The Gernsback Years:

A rambling account of an intelligent virus-like life-form that is discovered in a local pond. A portion taken to a laboratory, provided with radio communication, and educated by oral readings, turns out to be far more intelligent than humans. It aids considerably in the laboratory work, making sensational discoveries, but if it reaches the outside world (since it has developed mobility), humanity is doomed. Part of the situation is the reactions among the lab owners: friendship, exploitation, fear. The situation is resolved when the virus runs its life cycle.

An excerpt from the story, about the discovery of the thing in the pond:

"So you feel it too, eh?" asked Metcalf. "Well, you haven't yet seen the half of it. Not a lily pad nor a reed, you will note. The fish are all gone. There are not even any bugs on the surface." Then as Dee approached the water's edge, "Careful there! Don't let any of the spray get on you—it burns like an acid."
Dee knelt on the beach, and gingerly filled several glass-stoppered bottles with water from the pond. Then he and Metcalf walked slowly and thoughtfully down the road, until they came to a pasture at the end of the pond.
"Here is the latest victim," Metcalf announced. "It has not been disturbed."
Lying on the grass, about fifty feet from the water, was a dead, half eaten cow. Dee stooped down to examine it.
"See how the legs and tail taper off to a point at their upper ends, as though they had been dipped in acid," he said. "I pulled a half dead frog out of a snake's mouth once, and the whole rear end of the poor frog had been dissolved to a point, just like that. You don't suppose—"
"No," Metcalf replied. "There is nothing in that pond large enough to eat a cow. I have had it dredged with dragnets from end to end. The nets were eaten away, and several of the men got badly burned by drops of water, but not a thing did they bring to the surface."
"Well," Dee said, "I've seen enough to start on. Let's get me back to Boston, so that I can analyze these samples."

More excerpts, about the use of carbolic acid:

Then suddenly Dee cried out in pain. "Burned myself!" he shouted, and looked frantically around for an antidote.
Hans Schmidt rushed over and poured something from a small brown bottle onto Dee's hand.
"Dilute carbolic," he announced, in response to a questioning look.
"What! An acid to counteract an acid! How absurd!" Dee declared.
"Well, it worked!"
"But what on earth made you think of using carbolic, Hans?"
"I merely acted instinctively," Schmidt rather sheepishly replied. "When anything goes wrong, a bacteriologist instinctively reaches for his carbolic acid. That's all."
[. . . .]
"Sanctimonious tripe!" Schmidt interjected. "Let me handle this. Let's see what threats will do! Virus, even with your super-mind and your newly learned 'extensibility,' you are physically in our power. A few drops of phenol in your jar, and where would you be? Come across with the secret of how to make gold, or I'll put an end to you. If we can't know the secret, no one else ever shall!"
"I'm not afraid!" calmly replied the voice from the radio set. "You cannot kill me. For I am only a part of me. The rest of me—the pond—would still live. I am deathless."
"I'd pour carbolic in the pond—tons of it!" Schmidt blustered.
[. . . .]
Anson Metcalf hired the best firm of Concord lawyers, and got out an injunction to keep the State troops off his property. But the governor promptly declared martial law, and thus superseded the courts. A big oil truck, filled with carbolic acid, set out for Salt Pond under a strong military escort.

"Liquid Life" was reprinted in The Best of Science Fiction, a 1946 anthology (hardcover, xxvii+785 pp) edited by Groff Conklin. I believe that this was indeed "the first hardcover SF anthology" but don't have an authoritative source handy to back that up. [No, not really; see P.S.] The ISFDB notes, among other differences between the first and second printing:

Boards:

* 1st printing: embossed in silver on front and spine. Verification copy is black cloth.

* 2nd printing: embossed in gold on spine only. Verification copy is maroon cloth.
As you recall the cover being "a deep blood red", it was probably the second printing that you saw.
The second story (universal solvent), as noted in a comment by DavidW, seems to be "Varieties of Technological Experience", a 1978 short story by Barry N. Malzberg, which was the answer to an old question, Looking for a sci-fi story about a prisoner and a universal solvent. Of course that 1978 story was not in Conklin's 1946 anthology.
P.S. Conklin's The Best of Science Fiction was not exactly the first hardcover SF anthology, but it was certainly a notable early landmark in the history of SF anthologies; maybe you could call it the first important one. Quoting The Encyclopedia of Science Fiction:

But the usually accepted candidate as first sf anthology is Adventures to Come (anth 1937) edited by J Berg Esenwein. It was also sf's first Original Anthology i.e., its stories were all previously unpublished – but they were by unknowns (it has been speculated that Esenwein wrote them all under one-off pseudonyms), and it seems the anthology had no influence at all. Much more important was The Other Worlds (anth 1941) edited by Phil Stong, a hardcover publication reprinting stories by Harry Bates, Lester del Rey, Henry Kuttner, Theodore Sturgeon and many other well-known writers from the sf magazines. The first notable paperback anthology was The Pocket Book of Science-Fiction (anth 1943) edited by Donald A Wollheim, eight of whose ten stories are still well remembered, an extraordinarily high batting average considering that more than half a century has since elapsed. Also relevant at this point is Wollheim's Omnibus volume The Portable Novels of Science (omni/anth 1945), comprising three novels and one novella.
The year that presaged the advancing flood was 1946, when two respectable hardcover publishers commissioned huge anthologies, both milestones. In February 1946 came The Best of Science Fiction (anth 1946) edited by Groff Conklin, containing 40 stories in 785pp, and in August came Adventures in Time and Space (anth 1946) edited by Raymond J Healy and J Francis McComas, containing 35 stories in 997pp. The latter was the superior work and even today reads like a roll of honour, as all the great names of the first two decades of Genre SF parade past. But Conklin's book is not to be despised, including as it does Sturgeon's "Killdozer!" (November 1944 Astounding), Robert A Heinlein's "Universe" (May 1941 Astounding) and Murray Leinster's "First Contact" (May 1945 Astounding) (see First Contact).