text:
Q: What's the best way to return different cells depending on position in a UITableView I have a grouped UITableView that has 3 sections and a number of cells in each section that each need to be a different custom cell, with different display requirements.
I currently have a large if statement in cellForRowAtIndexPath, with each branch instantiating and returning the appropriate custom cell based on interrogating the indexPath's section and row properties.  e.g.
if (indexPath.section == 0 && indexPath.row == 0) {
    // instantiate and return cell A
} else if (indexPath.section == 1 && indexPath.row == 2) {
    // instantiate and return cell B
} //etc etc

What is best practice for this scenario?  A large if statement does the job, but is it the best implementation?

A: One method I've used once or twice is a nested series of NSArray objects that I initialize in viewDidLoad:
// sec<n>Row<n>Cell are IB Outlets to UITableViewCell objects defined in your .xib
NSArray *firstSectionRows = [[NSArray alloc] initWithObjects: sec1row1Cell, sec1row2cell, nil];
NSArray *secondSectionRows = [[NSArray alloc] initWithObjects: sec2row1Cell, sec2row2cell, nil];

// cellTree is an instance variable
cellTree = [[NSArray alloc] initWithObjects: firstSectionRows, secondSectionRows, nil];
[firstSectionRows release];
[secondSectionRows release];

Then in your tableView:cellForRowAtIndexPath: method would look like this:
...
return [[cellTree objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
...

This assumes that each of your cells is unique, in which case you don't even need to try and dequeue reusable cells. If you have more than one of the same type of cell in any section, you'll have to create/dequeue them appropriately and assign them a unique cell-type identifier.
If you have a large or complicated structure you might be able to do your array setup in a .plist file and use NSArray's initWithContentsOfFile: method to read it in. However you will have to do some kind of KVC magic to get cell objects from the strings in your array:
return [self valueForKey:[[cellTree objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]];

A: On complex table views I've considered splitting up the UITableViewDataSource routines into sub-delegates, one delegate for each section.  So for 3 sections, I would create 3 separate objects each one responsible for providing the UITableViewDataSource methods for that section of the table.  Then the UITableView's delegate just dispatches to one of the appropriate sub-delegates depending on which section the request is for.

A: By far the best way to do this is described in this post from Cocoa With Love. Basically it's a custom controller for each cell type but it ends up being really simple to implement.

A: I think this is pretty much common practice. Just be sure that you specify a unique cell identifier for those different cells. So that caching of the cells works properly.


text:
Q: How to replace specific lat and long value in a text file? string line = string.Empty;
int line_number = 1;
int line_to_edit = 2;

using (StreamReader reader = new StreamReader(@"C:\ut.txt"))
{
    using (StreamWriter writer = new StreamWriter(@"C:\ut1.txt"))
    {
        while ((line = reader.ReadLine()) != null)
        {
            if (line_number == line_to_edit)
            {
                writer.WriteLine(line);
            }
            line_number++;
        }
    }
}

This is input file ut.txt
1
2  ----no. of splines
6 0  --- 6 denotes no of lines in first spline
365608.901276044 1288380.47235694  ----1st line
365771.386298595 1288324.72422065
366114.128536966 1288263.42618414
366540.124442843 1288196.19420711
367310.251273576 1288150.21544542
368104.085736344 1288201.50959757----6th line
4 0  ----4 denotes no of lines in second spline
368825.120730879 1301890.60510298----6th line in first spline replace this line
368712.400375608 1301704.1672357
368741.48892057 1301615.81711783
368740.370207785 1301488.64428575----1st line in first spline replace this line

Output needed is:
1
2
6 0
365608.901276044 1288380.47235694
365771.386298595 1288324.72422065
366114.128536966 1288263.42618414
366540.124442843 1288196.19420711
367310.251273576 1288150.21544542
368104.085736344 1288201.50959757
4 0
368104.085736344 1288201.50959757
368712.400375608 1301704.1672357
368741.48892057 1301615.81711783
365608.901276044 1288380.47235694

A: Update your code with below
while ((line = reader.ReadLine()) != null)
{
  if (line.Contains("Specific Lat/Long Value"))
    {
        line.Replace("Specific Lat/Long Value", "New Value");
    }
}

Above code with replace the string with updated values.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Multiple panels with BoxSizer I m trying to divide a single panel into two panels.
So Button1 should be in one panel abd Button 2 , 3, 4 should be on another panel.
Here is my runnable code which does not display the panels correctly.
import wx
from numpy import arange, sin, pi
import matplotlib
matplotlib.use('WXAgg')

from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.figure import Figure

class Frame1(wx.Frame):

    def __init__(self, parent):

        wx.Frame.__init__(self, None,
                          pos=wx.Point(0, 0),size=wx.Size(800, 200),
                          style=wx.DEFAULT_FRAME_STYLE | wx.MAXIMIZE )

        self.panel1 = wx.Panel(self)
        self.panel2 = wx.Panel(self)
        #self.panel1.SetBackgroundColour('blue')
        self.panel3 = wx.Panel(self)
        self.panel4 = wx.Panel(self)
        self.panel3.SetBackgroundColour('red')

        sizer1 = wx.BoxSizer(wx.VERTICAL)
        sizer1.Add(self.panel4, 1, wx.EXPAND)
        sizer1.Add(self.panel1, 1, wx.EXPAND)
        self.SetSizer(sizer1)
        sizer1.Fit(self)

        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add(sizer1, 1, wx.EXPAND)
        sizer.Add(self.panel2, 1, wx.EXPAND)
        sizer.Add(self.panel3, 1, wx.EXPAND)
        self.SetSizer(sizer)
        #sizer.Fit(self)

        self.log = wx.TextCtrl(self.panel3, style=wx.TE_RICH|wx.TE_MULTILINE)
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add(self.log, 1, wx.EXPAND|wx.ALL, 15)
        self.panel3.SetSizer(sizer)

        emptycell = (0,0)
        self.button1 = wx.Button(self.panel4, -1, "Button1", size=wx.Size(150, 70))
        self.button2 = wx.Button(self.panel1, -1, "Button2")
        self.button3 = wx.Button(self.panel1, -1, "Button3")
        self.button4 = wx.Button(self.panel1, -1, "Button4")

        sizer = wx.GridSizer(8,3,0,0)

        sizer.Add(emptycell, 0, wx.EXPAND)
        sizer.Add(self.button1, 0, wx.ALIGN_CENTER|wx.LEFT, 10)
        sizer.Add(emptycell, 0, wx.EXPAND)
        sizer.Add(self.button2, 0, wx.ALIGN_CENTER)
        sizer.Add(self.button3, 0, wx.ALIGN_CENTER)
        sizer.Add(self.button4, 0, wx.ALIGN_CENTER)
        self.panel1.SetSizer(sizer)

        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)
        self.canvas = FigureCanvas(self.panel2, -1, self.figure)

        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add(self.canvas, 0, wx.EXPAND)
        self.panel2.SetSizer(sizer)
        #self.panel2.Fit()

        t = arange(0.0, 3.0, 0.01)
        s = sin(2 * pi * t)
        self.axes.plot(t, s)

        #self.Center()

#Every wxWidgets application must have a class derived from wxApp
class MyApp(wx.App):
    # wxWidgets calls this method to initialize the application
    def OnInit(self):

        # Create an instance of our customized Frame class
        self.frame = Frame1(None)
        self.SetTopWindow(self.frame)
        self.frame.Show()
        return True

if __name__ == '__main__':
    application = MyApp(0)
    application.MainLoop()

Desired result

Actual result

A: I had to hack it about a bit but try to give each panel a sizer of its own and bring them together at the end. Also, use descriptive names, or it soon becomes a morass, which is difficult to follow.
import wx
from numpy import arange, sin, pi
import matplotlib
matplotlib.use('WXAgg')

from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.figure import Figure

class Frame1(wx.Frame):

    def __init__(self, parent):

        wx.Frame.__init__(self, None,
                          pos=wx.Point(0, 0),size=wx.Size(800, 200),
                          style=wx.DEFAULT_FRAME_STYLE | wx.MAXIMIZE )

        self.panel1_1 = wx.Panel(self)
        self.panel1_2 = wx.Panel(self)
        self.panel2 = wx.Panel(self)
        self.panel3 = wx.Panel(self)
        self.panel3.SetBackgroundColour('red')
        self.panel1_1.SetBackgroundColour('green')
        self.panel1_2.SetBackgroundColour('blue')

        self.log = wx.TextCtrl(self.panel3, style=wx.TE_RICH|wx.TE_MULTILINE)
        log_sizer = wx.BoxSizer(wx.HORIZONTAL)
        log_sizer.Add(self.log, 1, wx.EXPAND|wx.ALL, 15)
        self.panel3.SetSizer(log_sizer)

        self.button1 = wx.Button(self.panel1_1, -1, "Button1", size=wx.Size(150, 70))

        button_sizer1 = wx.GridSizer(1,3,0,0)
        button_sizer1.Add((0,0), 0, wx.ALL, 10)
        button_sizer1.Add(self.button1, 0, wx.ALL, 10)
        button_sizer1.Add((0,0), 0, wx.ALL, 10)
        self.panel1_1.SetSizer(button_sizer1)

        self.button2 = wx.Button(self.panel1_2, -1, "Button2")
        self.button3 = wx.Button(self.panel1_2, -1, "Button3")
        self.button4 = wx.Button(self.panel1_2, -1, "Button4")

        button_sizer2 = wx.GridSizer(1,3,0,0)
        button_sizer2.Add(self.button2, 0, wx.ALL|wx.ALIGN_LEFT, 10)
        button_sizer2.Add(self.button3, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, 10)
        button_sizer2.Add(self.button4, 0, wx.ALL|wx.ALIGN_RIGHT, 10)
        self.panel1_2.SetSizer(button_sizer2)

        main_button_sizer = wx.BoxSizer(wx.VERTICAL)
        main_button_sizer.Add(self.panel1_1)
        main_button_sizer.Add(self.panel1_2, 1, wx.EXPAND)

        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)
        self.canvas = FigureCanvas(self.panel2, -1, self.figure)

        fig_sizer = wx.BoxSizer(wx.HORIZONTAL)
        fig_sizer.Add(self.canvas, 0, wx.EXPAND)
        self.panel2.SetSizer(fig_sizer)

        main_sizer = wx.BoxSizer(wx.HORIZONTAL)
        main_sizer.Add(main_button_sizer, 1, wx.EXPAND)
        main_sizer.Add(self.panel2, 1, wx.EXPAND)
        main_sizer.Add(self.panel3, 1, wx.EXPAND)
        self.SetSizer(main_sizer)
        self.Layout()

        t = arange(0.0, 3.0, 0.01)
        s = sin(2 * pi * t)
        self.axes.plot(t, s)

#Every wxWidgets application must have a class derived from wxApp
class MyApp(wx.App):
    # wxWidgets calls this method to initialize the application
    def OnInit(self):

        # Create an instance of our customized Frame class
        self.frame = Frame1(None)
        self.SetTopWindow(self.frame)
        self.frame.Show()
        return True

if __name__ == '__main__':
    application = MyApp(0)
    application.MainLoop()

A: Oof, some of those panel and sizer variable names are hard to follow.
It may be helpful, when dealing with wx, to keep good track of what windows (so, panels, buttons, etc) are going to be inside of what other windows, and be vigilant about how you're declaring the parent of each one.
For instance, if you have one panel (say, panel1) that contains multiple elements, then when you instantiate those elements, do so with their parent all set to panel1. For instance, when you create self.button1, do so with its parent as panel1 (the same as your other buttons), because you're fitting all of them inside panel1.
This is because wx will naturally try to fit windows inside of their parents. When a window has a parent that's one element, but a sizer is trying to put it inside another element, things get pretty screwy. It's hard to follow exactly, but I imagine this is where your problem is.
The other thing that is going to make your code (a) easier to read/follow/debug, and (b) work nicer, is: don't be afraid of instantiating multiple sizer variables. Better yet, give them names that match the panels they're organizing!
I've found it helpful (and this may work for you as well) to divide the __init__ function into three sections: (1) instantiating all the windows/objects you'll need, from "top level" down, assigning them their correct parent windows; (2) instantiating all your sizers, one for each windows that contains other elements; and (3) from the "bottom level" up, add windows to their parent sizers, calling SetSizer on each parent panel, and working up until you set the main sizer for your top-level window.
If that doesn't work out for you, feel free to send me a message and we'll see if we can parse out why wx isn't working out like it should.


text:
Q: INSERT OR REPLACE adding a whole new row SQLite I'm creating a little stock tracking project using Flask.  I have generally used an ORM, but was trying vanilla SQLite on this.
I have 3 tables, users, stocks and a join table of stocks_users that has a column for user_id, symbol, and quantity
            db.execute(f"""
                INSERT OR REPLACE INTO user_stocks(user_id, stock_id, quantity)
                VALUES (
                    (SELECT 1 FROM users WHERE id = '{user_id}'),
                    (SELECT 1 FROM stocks WHERE symbol = '{symbol}'),
                    {shares}
                )
            """)

I am running this trying to insert a row if it does not exist, but if a row has the matching user_id and symbol (primary key for the users and stocks tables respectively) I would just like to update the quantity.
Any direction on this would be much appreciated.


text:
Q: Haskell SDL-mixer compilation error I am trying to install the SDL-mixer haskell package by using "cabal install sdl-mixer".
When I do so, it gives the error
Resolving dependencies...
[1 of 1] Compiling Main             ( /tmp/SDL-mixer-0.6.1-10381/SDL-mixer-0.6.1/Setup.lhs, /tmp/SDL-mixer-0.6.1-10381/SDL-mixer-0.6.1/dist/setup/Main.o )
Linking /tmp/SDL-mixer-0.6.1-10381/SDL-mixer-0.6.1/dist/setup/setup ...
Configuring SDL-mixer-0.6.1...
configure: WARNING: unrecognized options: --with-compiler, --with-gcc
checking for sdl-config... /usr/bin/sdl-config
checking for gcc... gcc
checking whether the C compiler works... no
configure: error: in `/tmp/SDL-mixer-0.6.1-10381/SDL-mixer-0.6.1':
configure: error: C compiler cannot create executables
See `config.log' for more details.
Failed to install SDL-mixer-0.6.1
cabal: Error: some packages failed to install:
SDL-mixer-0.6.1 failed during the configure step. The exception was:
ExitFailure 77

If it makes a difference, I am on Arch Linux. How do I install this package?

A: make sure you have installed libsdl-mixer as a prerequisite.

A: Got the same symptoms on package network, on ubuntu 12.04. It was caused by /usr/bin/ld being gold instead of ld.bfd. Passing --with-ld=ld.bfd is apparently not enough for some packages.
Workaround:
mkdir /tmp/ld_override

ln -s /usr/bin/ld.bfd /tmp/ld_override/ld

PATH=/tmp/ld_override:$PATH cabal install ...

A: I try this, and it works for me. But I donnot know the reason :-)
brew install sdl_mixer

Then try
cabal install SDL-mixer


text:
Q: Serve Different Angular Apps on Different Express Routes I want to serve two defferent angular apps on two different routes: domain.com/admin for admin app and domain.com/customer for customer app.
app.use("/admin", express.static(path.join(process.cwd(), "web/dist/admin")));
app.use("/customer", express.static(path.join(process.cwd(), "web/dist/customer")));

app.get("/admin/**", (req, res) => {
    res.sendFile(path.join(process.cwd(), "web/dist/admin/index.html"));
});
app.get("/customer/**", (req, res) => {
    res.sendFile(path.join(process.cwd(), "web/dist/customer/index.html"));
});

This works, apps are on the routes where they have to be. But I'm getting these error from angular:

Seems like angular can't get files from the server. Is there something like baseUrl, a path for angular to get the files from?


text:
Q: high drain lead acid battery concern I have a couple of deep cycle lead acid 12V batteries (Kirkland Brand), 125 amp-hours each.
I want to run a 120 volt dryer-blower off a 2000 watt inverter for 20 minutes.
I calculate 2000 watts/120 volts = 16.6 amps on AC side,
16.6 amps X 120/12 volts = 166 amps on the DC side.
166 amps X 20 minutes = 55 amp-hours.
Add efficiency losses and we are still under 75 amp-hours.
So, the capacity is there, even with just one battery (and I have 2).
Question: If I am drawing that much power from the battery, are there any problems or concerns? Overheating? Safety?
I realize that this will shorten the battery life somewhat, but I only expect to do this a few times each year.

A: Based on above comments if Costco does not have detailed specs for the Kirkland battery, then you need to test the batteries.
80A per battery may cause H2 outgassing so use in a ventilated area.
1kW = 80A * 12.5V
Although it may work. Your test results are the best bet.  No obvious faults except a worn out cell.
Ensure you have the proper charge profile as AGM types need temperature compensated voltages.


text:
Q: Multiple-passes SSAO border artifact I am playing with multiple passes in WebGL to apply some visual enhancements to my renders.
I am ping-ponging two textures  (taken from here: WebGL Image Processing Continued), and this is basically my workflow:

*

*draw the geometry and store the depth vales in a texture buffer

*apply the SSAO pass (based on this Fiddle from Rabbid76)

*at the end, I am rendering the texture to the screen

Now, I am not able to understand why there is a black border around some parts of the final image.
I tried to fine adjust some SSAO parameters, but I wasn't able to get rid from that artifact, so, just guessing, i believe now that this black border is due a wrong blending setup of my texture buffers.
This is actually the code in the depth pass:
gl.disable(gl.BLEND);
gl.enable(gl.DEPTH_TEST);
gl.depthMask(true);
... drawings

I tried also this way:
gl.enable(gl.BLEND);
gl.blendEquation(gl.FUNC_ADD);
gl.blendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA);

...but is not leading me to any result.
In the picture below, this artifact is clearly to see as a thin black line around the stanford dragon:

As I am completely lost with this issue, can someone point me to the right direction?
My question: I need to draw a geometry with transparent background - which is the correct blending mode for that, when rendering to a back buffer and ping-ponging two textures to apply multiple effects?

A: For the posterity, I was using:
gl.clearColor(0, 0, 0, 1);

so i changed the pack/unpack functions as follows:
vec4 PackDepth32_0(float depth) {
    const vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);
    const vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);
    vec4 res = fract(depth * bit_shift);
    res -= res.xxyz * bit_mask;
    return res;
}
float UnpackDepth32_0(vec4 color) {
    const vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);
    return dot(color, bit_shift);
}

which solves my problem.


text:
Q: Javascript to Parse Reddit Comment Page for Usernames I'm working on a bookmarklet for a Sub reddit and I'm trying to grab all the usernames on a comments page so I can parse them, then come back and update info next to them, similar to what RES does. The author of each comment has a class that is prefixed with Author but then has different stuff at the end of the class name. How would I go about grabbing all the usernames?
Then once I have the list, how would I update each one with an additional icon essentially?
Any suggestions/Tutorials that do similar things would be great.
Edit: I'm not really sure what portions of the markup would be helpful without giving a huge block. Here's the same question I asked in the Javascript Subreddit. http://www.reddit.com/r/javascript/comments/yhp7j/best_way_to_find_all_the_usernames_on_a_reddit/
You should be able to Inspect the name elements and See what I'm working with.
Currently working with this: http://net.tutsplus.com/tutorials/javascript-ajax/create-bookmarklets-the-right-way/
So I've got a Hello World Style Bookmarklet working that checks for Jquery and loads it if it's not present and just throws an alert.

A: From a quick look at the page you linked to in your question, it seems as if the mark-up surrounding user-names is as follows (using, presumably, your user-name as an example):
DiscontentDisciple

If that's the case, and the jQuery library is available (again, from your question), one approach is to simply use:
var authors = [];

$('a.author').html(
    function(i, h) {
        var authorName = $(this).text();
        if ($.inArray(authorName, authors) == -1) {
            authors.push(authorName); // an array of author-names
        }
        return '' + h;
    });

console.log(authors);

JS Fiddle proof-of-concept.
Or, similarly just use the fact that the user-name seems to be predictably the last portion of the URL in the a element's href attribute:
var authors = [];

$('a.author').html(
    function(i, h) {
        var authorName = this.href.split('/').pop();
        if ($.inArray(authorName, authors) == -1) {
            authors.push(authorName);
        }
        return '' + h;
    });

console.log(authors);

JS Fiddle proof-of-concept.
Both of these approaches put the img within the a element. If you want it before the a element, then simply use:
// creates an 'authors' variable, and sets it to be an array.
var authors = [];

$('a.author').each( // iterates through each element returned by the selector
    function() {
        var that = this, // caches the this variable, rather than re-examining the DOM.
            // takes the href of the current element, splits it on the '/' characters,
            // and returns the *last* of the elements from the array formed by split()
            authorName = that.href.split('/').pop();

        // looks to see if the current authorName is in the authors array, if it *isn't*
        // the $.inArray returns -1 (like indexOf())
        if ($.inArray(authorName, authors) == -1) {
            // if authorName not already in the array it's added to the array using
            // push()
            authors.push(authorName);
        }

        // creates an image element, concatenates the authorName variable into the
        // src attribute-value
        $('')
            // inserts the image before the current (though converted to a jQuery
            // object in order to use insertBefore()
            .insertBefore($(that));
    });

console.log(authors);

JS Fiddle proof-of-concept.
References:

*

*each().

*$.inArray().

*insertBefore().


text:
Q: Reorder factor in mosaic plot in R with ggmosaic and geom_mosaic() I have tried to familiarise myself with making mosaic plots in R with the ggmosaic package's geom_mosaic() command.
My problem is that I want the regions to be ordered by the share of seniors in each region, and not by name as now. Any help?
I am not very used to work with factors, but I have tried to do different things with forecat's fct_reorder() command without any luck.
Here is a sample dataset (not the actual dataset I work with) and the code I have made so far:
# install.packages(c("ggplot2", "ggmosaic"))
library(ggplot2)
library(ggmosaic)

# Make data set
region <- c("Oslo", "Oslo", "Oslo", "Viken", "Viken", "Viken",
            "Nordland", "Nordland", "Nordland")
age    <- c("young", "adult", "senior", "young", "adult", "senior",
            "young", "adult", "senior")
pop    <- c(145545, 462378, 89087, 299548, 729027, 223809, 52156, 136872, 51317)
df     <- data.frame(region, age, pop)

# Make mosaic plot
ggplot(data = df) +
  geom_mosaic(aes(x = product(age, region), fill = age, weight = pop)) +
  coord_flip() +
  theme_minimal()

UPDATE:
Sorry If I was unclear but what I wanted was this:
mosaic plot ranked
Where the regions are ranked/ordered by the share of seniors rather than the default order, like this:
mosaic plot unranked
I solved it somehow by using the fct_reorder() command in an 'untidy' way rather than as part of a mutate command in a pipeline. I have no idea why that meant any difference. Another comment, the fct_reorder() command works fine within a regular ggplot2 geom_... command but not (at least the way I tried) in the geom_mosaic command from the ggmosaic package.
NEW CODE (which is way too verbose to estimate the share of seniors)
# install.packages(c("ggplot2", "ggmosaic"))
library(ggplot2)
library(ggmosaic)

# Make data set
region <- c("Oslo", "Oslo", "Oslo", "Viken", "Viken", "Viken",
            "Nordland", "Nordland", "Nordland")
age    <- c("young", "adult", "senior", "young", "adult", "senior",
            "young", "adult", "senior")
pop    <- c(145545, 462378, 89087, 299548, 729027, 223809, 52156, 136872, 51317)
df     <- data.frame(region, age, pop)

df <- df %>%
  group_by(region, age) %>%
  summarise(pop = sum(pop)) %>%
  mutate(senior = case_when(age == "senior" ~ pop))

# Get total population of each region
df_tot <- df %>%
  group_by(region) %>%
  summarise(poptot = sum(pop),
            senior = median(senior, na.rm = TRUE)) %>%
  mutate(senior_share = senior / poptot * 100) %>%
  select(region, senior_share)

# Estimate senior share of each region
# Change order of regions
df <- df %>%
  left_join(df_tot, by = "region") #%>%

# Fix the factors
df$region <- fct_reorder(df$region, df$senior_share)
df$age <- factor(df$age, levels = c("young", "adult", "senior"))

# Make mosaic plot
ggplot(data = df) +
  geom_mosaic(aes(x = product(age, region), fill = age, weight = pop)) +
  coord_flip() +
  theme_minimal()

A: use this code , to set sequence ,
df$age <- factor(df$age, levels = c("senior","adult","young"))


text:
Q: Remove or Delete spawning objects from the List I made a script that spawning unlimited moving objects with LIST from positions .I want to delete the objects that collides  for example with boundary.I tried to delete them applying destroy script to the object , but the console output was ..."has been destroyed but you are still trying to access it" or "use DestroyImmediate".How to destroy them?Any suggestions?
Spawning Code:
public  List<GameObject> respawn = new List<GameObject> ();
public Vector3[] positions=new Vector3[5];
public GameObject barrier;
public BarrierMoving barrierMoving;
public bool isMoving=true;
public int lastRandom = 0;

float speed=60f;

void Start ()
{
    barrierMoving = GameObject.FindObjectOfType<BarrierMoving> ();
    InvokeRepeating ("SpawnBarrier",1f,speed*Time.deltaTime);
}

public void Update ()
{
    if(isMoving)
    {
        foreach(GameObject stop in respawn)
        {
            stop.transform.Translate (0f,0f,-0.4f);
        }
    }
}

// Spawning Function
void SpawnBarrier()
{
    for(int i=0;i<=5;i++)
    {
        respawn.Add (Instantiate (barrier, positions [i], Quaternion.identity)as GameObject);
    }
}

Destroy Script:
RespawnBarriers respawnBarriers;

void Start ()
{
    respawnBarriers = GameObject.FindObjectOfType<RespawnBarriers> ();
}

void OnTriggerEnter(Collider other)
{
    if(other.gameObject.CompareTag("Destroy"))
    {
        Destroy (respawnBarriers.barrier);
    }
}

A: You reference your list in the update method of your spawning code.
When you destroy your object in your destroy script, the reference of it in your respawn list is lost and generates your error.
You should remove the reference from the respawn list before destroying the object.
I would recommend making a static reference to your spawn script for easy access, if you only have one instance of it.


text:
Q: BizTalk Zombies - any way to explicitly REMOVE a subscription from within a BizTalk orchestration Background:
We make use of a lot of aggregation, singleton and multiton orchestrations, similar to Seroter's Round Robin technique described here (BizTalk 2009).
All of the these orchestration types have fairly arbitrary exit or continuation points (for aggregations), usually defined by a timer - i.e. if an Orch hasn't received any more messages within X minutes then proceed with the batching, and if after Y more minutes have elapsed and no more messages then quit. (We also exit our Single / N-Tons due to concerns about degraded performance after large numbers of messages are subscribed to the singleton over a period).
As much as we've tried to mitigate against Zombies e.g. by Starting any continuation processing in an asynch refactored orchestration, there is always a point of weakness where a 'well' timed message could cause a zombie. (i.e. receiving more incoming messages correlated to the 'already completed' shapes of an orchestration),
If a message causes a zombie on one of the subscriptions, the message does not appear to be propogated to OTHER subscribers either (i.e. orchs totally decoupled from the 'zombie causing' orchestration), i.e. the zombie-causing message is not processed.
Question
So I would be very interested in seeing if anyone has another way, programmatically or otherwise, to explicitly remove a correlated subscription from a running orchestration once the orchestration has 'progressed' beyond the point where it is interested in this correlated message. (this new message would then would typically start a new orchestration with its own correlations etc)
At this point we would consider even a hack solution such as a reflected BizTalk API call or direct SQL delete against the MsgBoxDB.

A: No you can't explicitly remove the subscription in an Orchestration.
The subscription will be removed as the Orchestration is tearing itself down, but a message arriving at that exact instance will be routed to the Orchestration but the Orchestration will end without processing it, and that's your Zombie.
Microsoft Article about Zombies http://msdn.microsoft.com/en-us/library/bb203853.aspx
I once also had to have an receive, debatch, aggregate, send pattern.  Receiving enveloped messages from multiple senders, debatching them, aggregating by intended recipient (based on two rules, number of messages or time delay, whichever occurred first).
This scenario was ripe for Zombies and when I read about them I designed it so it would not occur.  This was for BizTalk 2004
I debatched the messages, and inserted them into a database. I had a stored procedure that was polled by a receive port that would work out if there was a batch to send in if there was it would trigger of an Orcherstration that would take that message and route it dynamically.
Since neither Orchestrations had to wait for a another message they could end gracefully and there would be no Zombies.


text:
Q: A group $(G,\circ)$ does not have any proper subgroups if and only if $\text{ord}(G)=p$,where $p$ is a prime number. A non-trivial group $(G,\circ)$ does not have any proper subgroups if and only if $\text{ord}(G)=p$,where $p$ is a prime number.
$\Longleftarrow$ If  $(G,\circ)$ is a group of prime order, then Lagrange's theorem implies that the order of the subgroups of $G$ divides $p$, which happens if the order is either $1$ or $p$, and hence the subgroups are improper subgroups of $(G,\circ)$, shows the only subgroups of $G$ are proper ones.
$\Longrightarrow$ Assume $(G,\circ)$ does not have any proper subgroups, if $G$ is not cyclic then it's generated by two distinct elements (generators) $a,b \in G$ (such elements exist since $G$ is non-trivial), Hence $\langle a\rangle$ and $\langle b\rangle$ are two distinct proper subgroups of $G$, a contradiction. (I think it's not true to say "two" distant proper subgroups, since it may happen that one of them is the identity element of $G$, but in either case at least one of them is a proper subgroup of $G$ ad this leads to the desired contradiction)
Now we should show that $G$ is a finite group (I guess we need to show that if $G$ is generated by an element $g \in G$, and does not exist a positive integer for which $g^n=1$ does hold, then this leads to a contradiction).
For the prime part, If $n$ is a composition number then we can find a prime number $m <n$,then $\langle g^m\rangle$ has order $\frac{n}{\gcd\left(m,n\right)}$,how to get the desired contradiction?

A: One direction is clear by Lagrange (since $p$ has no divisors).
For the converse, if $G$ is finite, we could use Cauchy's theorem to get an element of order $p$, where $p||G|$.  Then the cyclic group generated by that element has to be the whole group.
If $G$ is infinite, we can just take an element and consider the cyclic subgroup it generates.  It must be the whole thing.  So we have $\Bbb Z$.  But $\Bbb Z$ has nontrivial proper subgroups.  So $G$ can't be infinite.

A: No need for Cauchy's theorem. Pick an element $g$. It must generate the whole group, else as you mentioned there is another subgroup distinct from $\langle g \rangle$. Therefore $G$ is cyclic. If it is infinite then $\langle g^2 \rangle$ is a proper subgroup, so $G$ is finite. If it is of order $m$ and $d\neq 1$ divides $m$, then $\langle g^d \rangle$ is a proper subgroup. Therefore $m$ is prime.


text:
Q: Trigger a function for when checkbox is checked/unchecke? i need to recalculate a total price for each change on the page. Select menus and checkboxes. For select menus i use
  $('select').on('change', function() {
        calculatePrice();
    });

but now i need something similar for

  $('input checkbox').on('change', function() {
        calculatePrice();
    });

doesn't work.

A: use
$('input[type=checkbox]').on('change', function() {
    calculatePrice();
});

A: You can use the exact same logic (even the same function) for this:
$('select, input:checkbox').on('change', function() {
  calculatePrice();
});

What I've done here is setup a multiple selector for the same callback: 'select, input:checkbox'. This selector will target any <select> and also any <input type="checkbox" /> elements. When either triggers a change event, the calculatePrice() function will be called.
I would also recommend that you give some identification properties to your elements, for example a class value such as triggers_calculate. Then your selector will have improved readability and would look something like this:
$('.triggers_calculate')

The selector will match only elements with the triggers_calculate class and when they fire the change event the function will be called.

A: Separate selectors with a comma:
$('select, :checkbox').on('change', function() {
    calculatePrice();
});

or simply use $(':input') which would also include text inputs, textareas, radio buttons. Don't know if you need them though.

A:

    <meta charset="utf-8">
    <link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">

    <form>

                Student

                    <select name="stu" id="Student">
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                        <option value="4">4</option>
                        <option value="5">5</option>
                    </select>

                House Type

                    <input type="checkbox" name="accom" value="100" id="a1">
                    Hotel
                    <input type="checkbox" name="accom" value="0" id="a2">
                    House

    </form>


text:
Q: How to hide password while sending mail from linux commad line I tried the approach in https://superuser.com/a/462871 and it works. But I don't want my gmail password to be stored in command history. Is there a way to avoid this?

A: If you are using a Bash shell then try adding a space to the beginning of the command you enter.
If that does not work then add [ \t]* to HISTIGNORE.


text:
Q: How to make python not close it self after error, python exception I have made an program in python that i converted into .exe using auto-py-to-exe and im wondering how to stop .exe stop closing it self after an error (python exception) the .exe closes it self in the speed of light and you cant read the error.
Does someone knows how to make it not close it self?
using input doesnt work if the exception happens in a pip library
Thanks

A: You can use a try-except based system (that you have to build suitably to catch every exception of your code) and to print the exception you can use the module traceback like so:
try:
    ## code with error ##
except Exception:
    print("Exception in user code:")
    print("-"*60)
    traceback.print_exc(file=sys.stdout)
    print("-"*60)

or you could use a simpler form like:
try:
    ## code with error ##
except Exception as e:
    print(e, file='crash log.txt')

that only prints the error class (like file not found).
I should also point out that the finally keyword exists with the purpose of executing code either if an exception arose or not:
try:
    ## code with error ##
except:                                             #optional
    ## code to execute in case of exception ##
finally:
    ## code executed either way ##

Something you could do on top of that is logging everything your program does with
print(status_of_program, file=open('log.txt','a'))
this is useful to see exactly at what point the program has crashed and in general to see the program in action step by step.
But a thing you should do is properly test the program while in .py form and if it works you could possibly assume the error comes from the actual exportation method and consult the documentation or try exporting simpler programs to catch the difference (and so the error).
i'd suggest to consult:
https://docs.python.org/3/library/exceptions.html
to learn the error types and the try-except construct.

If input() doesn't work try using sys.stdout().

A: I gather that this is a console app. If it's a GUI app, you can use a similar approach but the details will be different.
The approach I'd use is to set sys.excepthook to be your own function that prints the exception, then waits for input. You can call the existing exception hook to actually do the printing.
import sys, traceback as tb

oldhook = sys.excepthook

def waitexcepthook(type, exception, traceback):
    oldhook(type, exception, traceback)
    input()

sys.excepthook = waitexcepthook


text:
Q: How to export excel file from php I want to remove warning (warning)
P.S I know that .xls is old version and I'm trying to use .xlsx but don't working.
header("Content-Type: application/xls");
header("Content-Type: application/octet-stream");
header('Content-Encoding: UTF-8');
header('Content-Type: application/vnd.ms-excel; charset=UTF-8');
$data = "Some utf-8 characters ąćżźćł";
header("Content-Transfer-Encoding: binary");
header('Expires: '.gmdate('D, d M Y H:i:s').' GMT');
header('Content-Disposition: attachment; filename = "Export '.date("Y-m-d").'.tsv"');
header("Content-Disposition: attachment; filename=municipaliteties_list.xls");
header("Pragma: no-cache");
header("Expires: 0");


text:
Q: Solr speeding up large or boolean filter I'm currently using solr 4.2.1 with approximately 10 mln documents in the index.
The index is updated frequently.
I'm using EDisMaxQueryParser with filter_query. The filter_query is just a one big boolean or query by id.
fq=id:(1 2 3 4 ... 50950)
ids list is always different and not sequential.
The problem is that query performance not so well, as you can imagine.
In some particular cases i'm able to do filtering based on different fields, but sometimes (like 30-40% of all queries) i'm still end up with this large id filter.
I'm looking for the ways to improve this query performance.
It doesn't seem like solr join could be applied there.
Another option would be to somehow cover the whole interval with subsets and switch to range filter queries. But I couldn't say that this is an easy solutions and also probably not the optimal one.
Is there any other alternatives?

A: This is known problem  - I'm having the problem of "security filter lists".
So what you should do:

*

*Write your own custom QParserPlugin + QParser and use Lucene's FieldCacheTermsFilter

*Disable caching for this filter

*Use it as a PostFilter in case your are having different filters.

Details:

*

*http://lucene.472066.n3.nabble.com/Solr-large-boolean-filter-td4070747.html#a4070964

*http://java.dzone.com/articles/custom-security-filtering-solr


text:
Q: Python 3 - Can pickle handle byte objects larger than 4GB? Based on this comment and the referenced documentation, Pickle 4.0+ from Python 3.4+ should be able to pickle byte objects larger than 4 GB.
However, using python 3.4.3 or python 3.5.0b2 on Mac OS X 10.10.4, I get an error when I try to pickle a large byte array:
>>> import pickle
>>> x = bytearray(8 * 1000 * 1000 * 1000)
>>> fp = open("x.dat", "wb")
>>> pickle.dump(x, fp, protocol = 4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 22] Invalid argument

Is there a bug in my code or am I misunderstanding the documentation?

A: You can specify the protocol for the dump.
If you do pickle.dump(obj,file,protocol=4) it should work.

A: Reading a file by 2GB chunks takes twice as much memory as needed if bytes concatenation is performed, my approach to loading pickles is based on bytearray:
class MacOSFile(object):
    def __init__(self, f):
        self.f = f

    def __getattr__(self, item):
        return getattr(self.f, item)

    def read(self, n):
        if n >= (1 << 31):
            buffer = bytearray(n)
            pos = 0
            while pos < n:
                size = min(n - pos, 1 << 31 - 1)
                chunk = self.f.read(size)
                buffer[pos:pos + size] = chunk
                pos += size
            return buffer
        return self.f.read(n)

Usage:
with open("/path", "rb") as fin:
    obj = pickle.load(MacOSFile(fin))

A: Here is a simple workaround for issue 24658. Use pickle.loads or pickle.dumps and break the bytes object into chunks of size 2**31 - 1 to get it in or out of the file.
import pickle
import os.path

file_path = "pkl.pkl"
n_bytes = 2**31
max_bytes = 2**31 - 1
data = bytearray(n_bytes)

## write
bytes_out = pickle.dumps(data)
with open(file_path, 'wb') as f_out:
    for idx in range(0, len(bytes_out), max_bytes):
        f_out.write(bytes_out[idx:idx+max_bytes])

## read
bytes_in = bytearray(0)
input_size = os.path.getsize(file_path)
with open(file_path, 'rb') as f_in:
    for _ in range(0, input_size, max_bytes):
        bytes_in += f_in.read(max_bytes)
data2 = pickle.loads(bytes_in)

assert(data == data2)

A: To sum up what was answered in the comments:
Yes, Python can pickle byte objects bigger than 4GB. The observed error is caused by a bug in the implementation (see Issue24658).

A: Here is the full workaround, though it seems pickle.load no longer tries to dump a huge file anymore (I am on Python 3.5.2) so strictly speaking only the pickle.dumps needs this to work properly.
import pickle

class MacOSFile(object):

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

    def __getattr__(self, item):
        return getattr(self.f, item)

    def read(self, n):
        # print("reading total_bytes=%s" % n, flush=True)
        if n >= (1 << 31):
            buffer = bytearray(n)
            idx = 0
            while idx < n:
                batch_size = min(n - idx, 1 << 31 - 1)
                # print("reading bytes [%s,%s)..." % (idx, idx + batch_size), end="", flush=True)
                buffer[idx:idx + batch_size] = self.f.read(batch_size)
                # print("done.", flush=True)
                idx += batch_size
            return buffer
        return self.f.read(n)

    def write(self, buffer):
        n = len(buffer)
        print("writing total_bytes=%s..." % n, flush=True)
        idx = 0
        while idx < n:
            batch_size = min(n - idx, 1 << 31 - 1)
            print("writing bytes [%s, %s)... " % (idx, idx + batch_size), end="", flush=True)
            self.f.write(buffer[idx:idx + batch_size])
            print("done.", flush=True)
            idx += batch_size

def pickle_dump(obj, file_path):
    with open(file_path, "wb") as f:
        return pickle.dump(obj, MacOSFile(f), protocol=pickle.HIGHEST_PROTOCOL)

def pickle_load(file_path):
    with open(file_path, "rb") as f:
        return pickle.load(MacOSFile(f))

A: Had the same issue and fixed it by upgrading to Python 3.6.8.
This seems to be the PR that did it:  https://github.com/python/cpython/pull/9937

A: I also found this issue, to solve this problem i chunk the code into several iteration. Let say in this case i have 50.000 data which i have to calc tf-idf and do knn classfication. When i run and directly iterate 50.000 it give me "that error". So, to solve this problem i chunk it.
tokenized_documents = self.load_tokenized_preprocessing_documents()
    idf = self.load_idf_41227()
    doc_length = len(documents)
    for iteration in range(0, 9):
        tfidf_documents = []
        for index in range(iteration, 4000):
            doc_tfidf = []
            for term in idf.keys():
                tf = self.term_frequency(term, tokenized_documents[index])
                doc_tfidf.append(tf * idf[term])
            doc = documents[index]
            tfidf = [doc_tfidf, doc[0], doc[1]]
            tfidf_documents.append(tfidf)
            print("{} from {} document {}".format(index, doc_length, doc[0]))

        self.save_tfidf_41227(tfidf_documents, iteration)


text:
Q: Add an interactive Check Box to a Flexdashboard in R I'm building a flexdashboard out in an RMarkdown document, but I've run into issues with interactivity. So I've gotten a solution in shiny up and running, but the issue is that at my place of work we don't have any shiny server options out there to support the app anywhere off my local machine. So I've checked out htmlwidgets and crosstalk in hopes of finding what I need there, but even that has been to niche for my problem.
So specifically, what's happening is I have a function that builds a list of lists. Let's call the bigger list plots for reference. Each list inside of list plots has 3 elements, the first labelled p is a plotly line graph. The second element is an error metric element which I use to order the lists so that the plots with the highest error metric appear first in the list. The 3rd element is called type, which basically describes the model type used for each plot built. There are 2 types, for reference I will refer to them as type1 and type2.
Now the flexdashboard is currently laid out like so:
---
title: "Dashboard"
author: "Me"
output:
  flexdashboard::flex_dashboard:
    orientation: rows
    vertical_layout: scroll
---

```{r global, include=FALSE}
library(ggplot2)
library(plotly)
library(htmltools)
require(htmlwidgets)
require(manipulateWidget)
theme_set(theme_classic())
source("~/directory_where_bigRun_is_stored")

# Build Plots
plots = bigRun(parameters)

# Pull out types for reference
type_vector = unlist(lapply(plots,"[", 3))
```

Column {.sidebar data-width=200}
-------------------------------------

### Filters

<form>
  <input type="checkbox" name="type1" value=1>
   Include type1 models

  <input type="checkbox" name="type2" value=2>
   Include type2 models

  <input type="submit" value="Go">
</form>

```{r echo = FALSE}
tags$submit("No idea what to do here")
```

```{r eval = FALSE}

# I also tried using this package to build out checkboxes
# but that didn't work either

manipulateWidget(
  {
    if(length(type) == 0){
      plots2 = vector(mode = 'list', length = 50)
    }else{
      plots2 = lapply(plots, function(x) x[x$type %in% type])
    }
  },
   type= mwCheckboxGroup(c("type1" = 1, "type2" = 2), c(1,2)),
   .updateBtn = TRUE
 )

```

Row
-----------------------------------------------------------------------

### #1 Worst

```{r}
plots2[[1]][[1]]
```

### #2 Worst

```{r}
plots2[[2]][[1]]
```

So as you can see, I've tried a couple of things within the sidebar to get a checkbox that will do exactly what I want. The raw html code actually creates a useable checkbox, but I don't know how to interact with it to do the filtering I need to do on the list. Basically, I want the checkbox to filter the list plots into a smaller list plots2 that only contains the elements chosen in the checkbox (either type1 or type2). It doesn't seem that any htmlWidgets will work for this given scenario since I'm not changing the plots themselves, but instead I'm changing a list of plots that will be automatically printed out to the dashboard.
Thanks in advance for any help you can offer. This has been driving me bonkers for over a week now, and I'd really like to wrap up this hurdle for the dashboard as there are still other changes I need to make to it.
For reference I've looked at these questions posted as well but am still stumped:
Add HTML and javascript code to flexdashboard in R
Selecting a default value in an R plotly plot using a selectize box via crosstalk in R, using static html not shiny


text:
Q: Threads indefinitely waiting for timer signal I'm having trouble with creating and implementing a timer for a multithreaded program. I create 3 threads and they are supposed to wait for 1, 2, and 4 seconds, respectively. However all three threads never stop waiting and the program just sits there indefinitely.
I need 2 of my functions looked at:
CreateAndArmTimer():
-I'm not sure if I'm using sigemptyset and sigaddset correctly. I'm supposed to "Create the signal mask corresponding to the chosen signal_number in timer_signal". I basically looked at the man pages for pthread_sigmask and copied what I found there.
WaitFortimer():
-This function is what is causing my program to not finish. My threads function normally up until this point, and once they call this function they get trapped in it and never exit.
Both functions are located at the bottom of my code. I appreciate any help with this! I can't for the life of me get this to work.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/time.h>
#include <time.h>
#include <string.h>
#include <signal.h>

int threadNumber = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

#define NUM_THREADS    3

//used to store the information of each thread
typedef struct{
   pthread_t  threadID;
   int num;
   int policy;
   struct sched_param param;
   long startTime;
   long endTime;

   int signal_number;
   int missed_signal_count;
   int timer_Period;

   sigset_t timer_signal;

   timer_t timer_Id;

}ThreadInfo;

ThreadInfo myThreadInfo[NUM_THREADS];

void *ThreadRunner(void *vargp);
void CreateAndArmTimer(int unsigned period, ThreadInfo* threadInfo);
void WaitForTimer(ThreadInfo* threadInfo);
int sigwait(const sigset_t* set, int* sig);
int timer_create(clockid_t clockid, struct sigevent* sevp, timer_t* timerid);

//main function
int main(void){

   sigset_t alarm_sig;
   sigemptyset(&alarm_sig);
   for(int i = SIGRTMIN; i <= SIGRTMAX; i++)
   sigaddset(&alarm_sig, i);
   pthread_sigmask(SIG_BLOCK, &alarm_sig, NULL);  //*****apply the blocking*****

   printf("\nrunning...\n");

   int fifoPri = 60;

   //create the 3 fifo threads
   for(int i=0; i<NUM_THREADS; i++){

         myThreadInfo[i].policy = SCHED_FIFO;
         myThreadInfo[i].param.sched_priority = fifoPri++;

      pthread_create(&myThreadInfo[i].threadID, NULL, ThreadRunner, &myThreadInfo[i]);

   }

   printf("\n\n");
   sleep(1);

   //tell all the threads to unlock
   pthread_cond_broadcast(&cond);

   //join each thread
   for(int g = 0; g < NUM_THREADS; g++){

      pthread_join(myThreadInfo[g].threadID, NULL);

   }

   return 0;
}

//the function that runs the threads
void *ThreadRunner(void *vargp){

   struct tm *ts;
   struct timeval  tv;
   size_t last;
   time_t timestamp = time(NULL);
   threadNumber++;
   ThreadInfo* currentThread;
   currentThread = (ThreadInfo*)vargp;
   currentThread->num = threadNumber;
   if(currentThread->num == 1){
      currentThread->timer_Period = 1000000;
   }
   else if(currentThread->num == 2){
      currentThread->timer_Period = 2000000;
   }
   else{
      currentThread->timer_Period = 4000000;
   }

        //lock the thread until it's ready to be unlocked
        pthread_mutex_lock(&mutex);

        pthread_cond_wait(&cond, &mutex);

        //unlocking for all other threads
        pthread_mutex_unlock(&mutex);

   if(pthread_setschedparam(pthread_self(), currentThread->policy,(const struct sched_param *) &(currentThread->param))){
      perror("pthread_setschedparam failed");
      pthread_exit(NULL);
   }

   if(pthread_getschedparam(pthread_self(), &currentThread->policy,(struct sched_param *) &currentThread->param)){
      perror("pthread_getschedparam failed");
      pthread_exit(NULL);
   }

   //create and arm the timer
   printf("thread#[%d] waiting for %d seconds\n", currentThread->num, (currentThread->timer_Period/1000000));
   CreateAndArmTimer(currentThread->timer_Period, currentThread);

   //set the start time of the timer
   gettimeofday(&tv, NULL);
   long startTime = (tv.tv_sec) * 1000 + (tv.tv_usec) / 1000;
   currentThread->startTime = startTime;

   //Wait for the timer
   WaitForTimer(currentThread);

   //set the end time of the timer
   gettimeofday(&tv, NULL);
   long endTime = (tv.tv_sec) * 1000 + (tv.tv_usec) / 1000;
   currentThread->endTime = endTime;

   //do the printing
   printf("\nThread[%d]  Timer Delta[%lu]us           Jitter[]us\n", currentThread->num, endTime-startTime);

   pthread_exit(NULL);
}

//used to create and arm a new timer
void CreateAndArmTimer(int unsigned period, ThreadInfo* threadInfo){

   //Create a static int variable to keep track of the next available signal number
   pthread_mutex_lock(&mutex);
   static int nextSignalNumber = 0;

   if(nextSignalNumber == 0){
      nextSignalNumber = SIGRTMIN;
   }
   else{
      nextSignalNumber += 1;
   }

   pthread_mutex_unlock(&mutex);

   threadInfo->signal_number = nextSignalNumber;

   //Create the signal mask corresponding to the chosen signal_number in "timer_signal"
   //Use "sigemptyset" and "sigaddset" for this
   sigemptyset(&threadInfo->timer_signal);
   sigaddset(&threadInfo->timer_signal, SIGQUIT);
   sigaddset(&threadInfo->timer_signal, SIGUSR1);

   //Use timer_Create to create a timer
   struct sigevent mySignalEvent;
   mySignalEvent.sigev_notify = SIGEV_SIGNAL;
   mySignalEvent.sigev_signo = threadInfo->signal_number;
   mySignalEvent.sigev_value.sival_ptr = (void*)&(threadInfo->timer_Id);
   int ret = timer_create(CLOCK_MONOTONIC, &mySignalEvent, &threadInfo->timer_Id);
   if(ret != 0){
      printf("error during timer_create for thread#[%d]\n", threadInfo->num);
   }

   //Arm timer
   struct itimerspec timerSpec;
   int seconds = period/1000000;
   long nanoseconds = (period - (seconds * 1000000)) * 1000;
   timerSpec.it_interval.tv_sec = seconds;
   timerSpec.it_interval.tv_nsec = nanoseconds;
   timerSpec.it_value.tv_sec = seconds;
   timerSpec.it_value.tv_nsec = nanoseconds;
   int ret2 = timer_settime(threadInfo->timer_Id, 0, &timerSpec, NULL);
   if(ret2 != 0){
      printf("error with timer_settime!\n");
   }

}

//used to make a thread wait for a timer
void WaitForTimer(ThreadInfo* threadInfo){

   pthread_sigmask(SIG_UNBLOCK, &threadInfo->timer_signal, NULL); //*****unblock the signal*****

   //Use sigwait function to wait on the "timer_signal"
   int wait = sigwait(&threadInfo->timer_signal, &threadInfo->signal_number);
   if(wait != 0){
      printf("error with sigwait!\n");
   }

   //update missed_signal_count by calling "timer_getoverrun"
   threadInfo->missed_signal_count = timer_getoverrun(threadInfo->timer_Id);

}

When I run this, the output is:
running...
thread#[l] waiting for 1 seconds
thread#[2] waiting for 2 seconds
thread#[3] waiting for 4 seconds

A: First, you should probably be using pthread_sigmask(2) rather than sigprocmask(2). Besides the fact that your comments (instructions, if this is homework?) state that is to be used, the former is explicitly specified as part of the POSIX standard in multithreaded programs, while the latter is not. I don't think this matters on Linux, but it's probably good practice.
The second, and more important, is that you're not really using the signals correctly. First, you block every signal with the call to sigprocmask(2) in your main function, but then never change that. Inside the CreateAndArmTimer() function, you never actually specify that all signals except your threadInfo->signal_number should be blocked. You instead add SIGQUIT and SIGUSR1 to a sigset, but then never do anything with that set. Did you mean to call pthread_sigmask(2) here? If so, you should be sure to add threadInfo->signal_number to the set too before doing so.
On the "listening" side, you never actually unblock any signals in the WaitForTimer() function (or anywhere else). Even if you correctly blocked them earlier, if you don't unblock them before calling sigwait(2), they'll never be delivered to your threads. So the timer is generating the requested signals, but they're just sitting in the signal queue for your process. You must call pthread_sigmask(SIG_UNBLOCK, ...) somewhere so they can actually be delivered.
In short:

*

*Call pthread_sigmask(2) instead of sigprocmask(2).

*Block all signals except your chosen threadInfo->signal_number in the threads.

*Unblock those signals before calling sigwait(2).


text:
Q: Having Camera Calibration matrix how to extract distortion? I have a camera calibration matrix that looks like this:
  8471.595573      0.000000   1251.025035
     0.000000   8438.951911    330.567798
     0.000000      0.000000      1.000000

I want to undistort the image with width: 1920, height: 1080

Yet when I call:
undistort(frame, out_frame, cam_k, noArray(), noArray());
imwrite("in.png", frame);
imwrite("out.png", out_frame);

there is no difference between frame and out_frame.
Do I do something wrong? Does OpenCV require something more than Camera Calibration matrix to undistort image? If yes Having a Camera Calibration matrix how to extract distortion?


text:
Q: Debugging a fitness calculator with multiple nested IF statements I'm using the Harris Benedict Equation to calculate people's TDEE. I'm using Google Sheets to create a sort of form for this but Google Sheets is sort of difficult to work with. I'm getting a formula parse error. Formatting is pretty bad sorry about that.
I know I'm making a small comma or parenthesis error somewhere but I'm not sure where.
The code is supposed to ask if people prefer metric/imperial, male/female, height, weight, activity level, and age.
Here's how Google Sheets does if statements. It pretty much is:
IF(A2 = "foo","A2 is foo")

Syntax is:

IF(logical_expression, value_if_true, value_if_false)

=IF (D9="Imperial",
    IF(D10="Male",
            IF(D16="Sedentary (no exercise)",
                    66 + ( 6.2 x D14 ) + ( 12.7 x (D13x12+G13) ) – ( 6.76 x D12 )x1.2,

                    IF(D16="Lightly Active (1-3 days of exercise/week)",
                            66 + ( 6.2 x D14 ) + ( 12.7 x (D13x12+G13) ) – ( 6.76 x D12 )x1.375,

                            IF(D16="Moderately Active (3-5 days of exercise/week)",
                                    66 + ( 6.2 x D14 ) + ( 12.7 x (D13x12+G13) ) – ( 6.76 x D12 )x1.55,

                                    IF(D16="Very Active(6-7 days of exercise/week)",

                                            66 + ( 6.2 x D14 ) + ( 12.7 x (D13x12+G13) ) – ( 6.76 x D12 )x1.725,
                                            IF(D16="Extremely Active(exercise twice a day)",

                                                    66 + ( 6.2 x D14 ) + ( 12.7 x (D13x12+G13) ) – ( 6.76 x D12 )x1.9,
                                            " ")))))

            IF(D16="Sedentary (no exercise)",
                    655.1 + ( 4.35 x D14 ) + ( 4.7 x (D13x12+G13) ) - ( 4.7 x D12 ) x1.2,

                            IF(Lightly Active (1-3 days of exercise/week)",
                                    655.1 + ( 4.35 x D14 ) + ( 4.7 x (D13x12+G13) ) - ( 4.7 x D12 ) x1.375,

                                    IF(Moderately Active (3-5 days of exercise/week)",
                                            655.1 + ( 4.35 x D14 ) + ( 4.7 x (D13x12+G13) ) - ( 4.7 x D12 ) x1.55,

                                            IF(D16="Very Active(6-7 days of exercise/week)",
                                                    655.1 + ( 4.35 x D14 ) + ( 4.7 x (D13x12+G13) ) - ( 4.7 x D12 ) x1.725,

                                                    IF(D16="Extremely Active(exercise twice a day)",
                                                            655.1 + ( 4.35 x D14 ) + ( 4.7 x (D13x12+G13) ) - ( 4.7 x D12 ) x1.9,
                                                    " "))))))

    IF(D10="Male",
            IF(D16="Sedentary (no exercise)",
                    66.5 + ( 13.75 x D14 ) + ( 5.003 x D13 ) – ( 6.755 x D12 )x1.2,

                    IF(Lightly Active (1-3 days of exercise/week)",
                            66.5 + ( 13.75 x D14 ) + ( 5.003 x D13 ) – ( 6.755 x D12 )x1.375,

                            IF(Moderately Active (3-5 days of exercise/week)",
                                    66.5 + ( 13.75 x D14 ) + ( 5.003 x D13 ) – ( 6.755 x D12 )x1.55,

                                    IF(D16="Very Active(6-7 days of exercise/week)"
                                            66.5 + ( 13.75 x D14 ) + ( 5.003 x D13 ) – ( 6.755 x D12 )x1.725,

                                            IF(D16="Extremely Active(exercise twice a day)",

                                                    66.5 + ( 13.75 x D14 ) + ( 5.003 x D13 ) – ( 6.755 x D12 )x1.9,

                                            " ")))))

            IF(D16="Sedentary (no exercise)",
                    655.1 + ( 9.563 x D14 ) + ( 1.850 x D13 ) – ( 4.676 x D12 ) x1.2,

                    IF(Lightly Active (1-3 days of exercise/week)",
                            655.1 + ( 9.563 x D14 ) + ( 1.850 x D13 ) – ( 4.676 x D12 ) x1.375,

                            IF(Moderately Active (3-5 days of exercise/week)",
                                    655.1 + ( 9.563 x D14 ) + ( 1.850 x D13 ) – ( 4.676 x D12 ) x1.55,

                                    IF(D16="Very Active(6-7 days of exercise/week)",

                                            655.1 + ( 9.563 x D14 ) + ( 1.850 x D13 ) – ( 4.676 x D12 ) x1.725,

                                            IF(D16="Extremely Active(exercise twice a day)",

                                                    655.1 + ( 9.563 x D14 ) + ( 1.850 x D13 ) – ( 4.676 x D12 ) x1.9,

                                            " "))))))

    )

A: You have things like IF(Lightly Active (1-3 days of exercise/week)" which obviously aren't going to work. This sort of nesting of IFs shouldn't be there in the first place, it's a minefield of typos. Use hlookup or vlookup instead. Example of vlookup replacing five nested IFs:
=if(D9="Imperial",
  if(D10="Male",
    vlookup(D16, {
      "Sedentary (no exercise)",
        66 + ( 6.2 x D14 ) + ( 12.7 x (D13x12+G13) ) – ( 6.76 x D12 )x1.2;
      "Lightly Active (1-3 days of exercise/week)",
        66 + ( 6.2 x D14 ) + ( 12.7 x (D13x12+G13) ) – ( 6.76 x D12 )x1.375;
      "Moderately Active (3-5 days of exercise/week)",
        66 + ( 6.2 x D14 ) + ( 12.7 x (D13x12+G13) ) – ( 6.76 x D12 )x1.55;
      "Very Active(6-7 days of exercise/week)",
        66 + ( 6.2 x D14 ) + ( 12.7 x (D13x12+G13) ) – ( 6.76 x D12 )x1.725;
      "Extremely Active(exercise twice a day)",
        66 + ( 6.2 x D14 ) + ( 12.7 x (D13x12+G13) ) – ( 6.76 x D12 )x1.9,
       }, 2, false)
    ....

Notice that you can put 15 instead of 5 options here, and no new parentheses will be needed.
Depending on how your data is structured, you may be able to put this reference tables elsewhere in the sheet, say in Table!A1:B5, Table!A6:B11, etc:
=if(D9="Imperial",
   if(D10="Male",
     vlookup(D16, Table!A1:B5, 2, false),
     vlookup(D16, Table!A6:B11, 2, false)
     ),
   if(D10="Male",
     vlookup(D16, Table!A12:B16, 2, false),
     vlookup(D16, Table!A17:B21, 2, false)
     )
   )

One can wrap each vlookup in iferror so that when the input data is not of expected kind, you get blank output instead of #N/A! error (though the latter is more informative).


text:
Q: jcifs - How to copy folder from shared folder to local folder I have to copy files and folders from a shared folder to a local folder (linux). I access to the shared folder using SmbFile and I copy the files using InputStream/OutputStream.
I want to copy the folders with their contents too. How can I perform this task? I have to create the folder with FileIO operation and then copy all the subfiles with InputStream/OutputStream or there is another way to copy the folder and the subfiles in one single step?


text:
Q: "mounting ext3 file system using the ext4 subsystem" - what does this mean exactly? I am running Ubuntu 16.04.1, and my main partition is formatted as ext3. Checking syslog I see : mounting ext3 file system using the ext4 subsystem does this mean that the partition is mounted as ext4?
GParted and blkid show ext3.

A: No, the partition is mounted as ext3; it's just that ext3 file systems are handled by the ext4 driver nowadays, with the message you see when they're mounted. There used to be a separate ext3 driver, but it was dropped when the ext4 driver had proven itself reliable. The ext4 driver checks that file systems mounted as ext3 only use ext3 features, so that they remain compatible with the old ext3 driver.


text:
Q: Incorrect Output on MSSQL varchar ODBC I'm using odbc_exec to get a varchar(MAX) from MSSQL server. however the value is returning like:
År)2014-0
It should look like: 59877d4c7baa6-h0d27e80
Here's some code to help give insight:
$conn = odbc_connect("Driver={SQL Native Client};Server=Server;Database=Database;", "Username", "Password");

$out = odbc_exec($conn, "SELECT [uuid] FROM [Database].[dbo].[Table]");

        if (odbc_num_rows($out)) {
            while ($row = odbc_fetch_array($out)) {
                echo $row['uuid']
            }
        }

(statement abstracted for example)

A: It would seem this issue is a known bug with no solution to date (PDO ODBC does have a fix)
Changing the SQL Driver to SQL Server from SQL Native Client resolves this issue, however I am aware of certain performance issues with using this driver.


text:
Q: Content doesn't change after v-model is updated from dropdown Froala Editor VueJs My requirement is to bind text to Froala Editor based on dropdown value.
I set value to v-model.
<Carevender-Editor :dataValue="model.csContent" ref="froalaEditor"></Carevender-Editor>

I set immediateVueModelUpdate to true but it doesn't work.
config: {
          immediateVueModelUpdate:true,
}

I want to update content in editor after selecting dropdown.
But now v-model doesn't update.

A: Finally I got it.
I add function in Froala editor component to set value for model.
methods:{
   setValue(value){
     this.model = value;
   }
}

I add ref for editor component in other components
<Carevender-Editor @getText="getEditorValue" :dataValue="templatebody" ref="froalaEditor"></Carevender-Editor>

And then in dropdown selected change event,
I call that ref with value.
selectedTemplate(value) {
          var tem = this.templates.filter(x => x.oid == value)[0];
          this.templatebody = tem.body;
          setTimeout(() => {
            this.isViewMode = false;
          }, 200);
      }


text:
Q: Trainer Component Error in Tensorflow Extension it is my first time building a tfx pipeline after I went through the tutorials and trying to build one with my own dataset. I could use some advice on the transform code that I wrote, and understand better, I'd appreciate your time and thanks in advance.
I've done the ExampleGen, StatisticsGen, SchemaGen, ExampleValidator, Transform, and having error in Trainer components.
ERROR:
c:\lib\site-packages\tfx\orchestration\launcher\in_process_component_launcher.py in _run_executor(self, execution_id, input_dict, output_dict, exec_properties)
     65         executor_context)  # type: ignore
     66
---> 67     executor.Do(input_dict, output_dict, exec_properties)

c:\lib\site-packages\tfx\components\trainer\executor.py in Do(self, input_dict, output_dict, exec_properties)
    317
    318     fn_args = self._GetFnArgs(input_dict, output_dict, exec_properties)
--> 319     trainer_fn = self._GetFn(exec_properties, 'trainer_fn')
    320
    321     schema = io_utils.parse_pbtxt_file(fn_args.schema_file, schema_pb2.Schema())

c:\lib\site-packages\tfx\components\trainer\executor.py in _GetFn(self, exec_properties, fn_name)
    128     if has_module_file:
    129       return import_utils.import_func_from_source(
--> 130           exec_properties['module_file'], fn_name)
    131
    132     fn_path_split = exec_properties[fn_name].split('.')

c:\lib\site-packages\tfx\utils\import_utils.py in import_func_from_source(source_path, fn_name)
     66       user_module = types.ModuleType(loader.name)
     67       loader.exec_module(user_module)
---> 68       return getattr(user_module, fn_name)
     69
     70   except IOError:

AttributeError: module 'user_module' has no attribute 'trainer_fn'

CODE:
def get_model(show_summary=True):

#one-hot categorical features
num_A = 4,
num_B = 3,
num_C = 2,
num_D = 8,
num_E = 12,
num_F = 4,
num_G = 16,
num_H = 26

input_A = tf.keras.Input(shape=(num_A,), name="A_xf")
input_B = tf.keras.Input(shape=(num_B,), name="B_xf")
input_C = tf.keras.Input(shape=(num_C,), name="C_xf")
input_D = tf.keras.Input(shape=(num_D,), name="D_xf")
input_E = tf.keras.Input(shape=(num_E,), name="E_xf")
input_F = tf.keras.Input(shape=(num_F,), name="F_xf")
input_G = tf.keras.Input(shape=(num_G,), name="G_xf")
input_H = tf.keras.Input(shape=(num_H,), name="H_xf")

fl = keras.Input(shape=(75,))
dense = layers.Dense(35, activation = "relu")
x = dense(fl)
x = layers.Dense(15, activation="relu")(x)
outputs = layers.Dense(1, activation="sigmoid")(x)

_inputs = [input_A, input_B, input_C, input_D, input_E, input_F, input_G, input_H]

model = keras.Model(inputs=inputs, outputs=outputs)

model.compile(optimizer='rmsprop',
          loss='binary_crossentropy',
          metrics=['accuracy'])

if show_summary:
    model.summary()

return model

A: We had the same problem and were able to solve it by migrating from the tf.keras sequential model api to the functional api. You can read about the different model apis here. You'll notice in the tutorials that the wide and deep model is implemented as a functional api.
As an example, here is a sample of a keras model for the trainer component:
def _build_functional_test_model():
colname = 'feature_string_xf'
feature_columns = [
    tf.feature_column.numeric_column(colname, shape=_MAX_REQUEST_LEN, dtype=tf.dtypes.int64, default_value=0)]

input_layers = {
    colname: tf.keras.layers.Input(name=colname, shape=_MAX_REQUEST_LEN, dtype=tf.int64)
}

input_dense_layer = tf.keras.layers.DenseFeatures(feature_columns)(input_layers)

embedding = tf.keras.layers.Embedding(_N_UNIQUE_WORDS,
                                      _N_EMBED,
                                      input_length=_MAX_REQUEST_LEN)(input_dense_layer)

embedding_dropout = tf.keras.layers.SpatialDropout1D(_DROPOUT_EMBEDDING)(embedding)

conv_1 = tf.keras.layers.Conv1D(_N_CONV_1,
                                _K_CONV_1,
                                activation='linear',
                                activity_regularizer=tf.keras.regularizers.l1(_REGULARIZE_L1_CONV))(
    embedding_dropout)
activation_1 = tf.keras.layers.Activation('relu')(conv_1)
dropout_1 = tf.keras.layers.Dropout(_DROPOUT_CONV_1)(activation_1)

conv_2 = tf.keras.layers.Conv1D(_N_CONV_1,
                                _K_CONV_2,
                                activation='linear',
                                activity_regularizer=tf.keras.regularizers.l1(_REGULARIZE_L1_CONV))(dropout_1)
activation_2 = tf.keras.layers.Activation('relu')(conv_2)
dropout_2 = tf.keras.layers.Dropout(_DROPOUT_CONV_1)(activation_2)

conv_3 = tf.keras.layers.Conv1D(_N_CONV_3,
                                _K_CONV_3,
                                activation='linear',
                                activity_regularizer=tf.keras.regularizers.l1(_REGULARIZE_L1_CONV))(dropout_2)
activation_3 = tf.keras.layers.Activation('relu')(conv_3)
dropout_3 = tf.keras.layers.Dropout(_DROPOUT_CONV_1)(activation_3)

conv_4 = tf.keras.layers.Conv1D(_N_CONV_4,
                                _K_CONV_4,
                                activation='linear',
                                activity_regularizer=tf.keras.regularizers.l1(_REGULARIZE_L1_CONV))(dropout_3)
activation_4 = tf.keras.layers.Activation('relu')(conv_4)
dropout_4 = tf.keras.layers.Dropout(_DROPOUT_CONV_1)(activation_4)

max_pool_5 = tf.keras.layers.GlobalMaxPooling1D()(dropout_4)

dense_6 = tf.keras.layers.Dense(_N_DENSE_1,
                                activation='linear',
                                # activity_regularizer=keras.regularizers.l1(_REGULARIZE_L1_DENSE_1)
                                )(max_pool_5)
activation_6 = tf.keras.layers.Activation('relu')(dense_6)
dropout_6 = tf.keras.layers.Dropout(_REGULARIZE_L1_DENSE_1)(activation_6)

dense_7 = tf.keras.layers.Dense(_N_DENSE_2,
                                activation='linear',
                                # activity_regularizer=keras.regularizers.l1(_REGULARIZE_L1_DENSE_1)
                                )(dropout_6)
activation_6 = tf.keras.layers.Activation('relu')(dense_7)
dropout_7 = tf.keras.layers.Dropout(_REGULARIZE_L1_DENSE_1)(activation_6)

output = tf.keras.layers.Dense(1, activation='sigmoid')(dropout_7)

model = tf.keras.Model(input_layers, output)
model.compile(loss='binary_crossentropy', optimizer=_OPTIMIZER, metrics=['accuracy'])

return model

A: By using the directions and comment by Jason, I've changed up the model part as tfx doesn't support the sequential model but the Keras functional API.
def get_model(show_summary=True):

#one-hot categorical features
num_A = 4,
num_B = 3,
num_C = 2,
num_D = 8,
num_E = 12,
num_F = 4,
num_G = 16,
num_H = 26

input_A = tf.keras.Input(shape=(num_A,), name="A_xf")
input_B = tf.keras.Input(shape=(num_B,), name="B_xf")
input_C = tf.keras.Input(shape=(num_C,), name="C_xf")
input_D = tf.keras.Input(shape=(num_D,), name="D_xf")
input_E = tf.keras.Input(shape=(num_E,), name="E_xf")
input_F = tf.keras.Input(shape=(num_F,), name="F_xf")
input_G = tf.keras.Input(shape=(num_G,), name="G_xf")
input_H = tf.keras.Input(shape=(num_H,), name="H_xf")

inputs_con = tf.keras.layers.concatenate([
input_A,
input_B,
input_C,
input_D,
input_E,
input_F,
input_G,
input_H])

dense_1 = tf.keras.layers.Dense(50, activation = 'relu')(inputs_con)
dense_2 = tf keras.layers.Dense(25, activation = "rely") (dense_1)
output = tf.keras.laters.Dense(1, activation = "sigmoid") (dense_2)
model = keras.Model(inputs=inputs, outputs=outputs)

_inputs = [
input_A,
input_B,
input_C,
input_D,
input_E,
input_F,
input_G,
input_H]

model = tf.keras.models.Model(_inputs, output)

model.compile(optimizer='rmsprop',
          loss='binary_crossentropy',
          metrics=['accuracy'])

if show_summary:
    model.summary()

return model


text:
Q: How to look at past DML on your table? a friend asked me if there is a way to see the past dml statements and I wasn't really sure on how to go about answering that question.  What he wants to see is the last set of insert statements.  So that means it could be more than 1 record.  At first I was just saying to check the latest identity, but then he asked what if more inserts were performed at the same time.  Can you guys help me out?  Is there a DMV I should use that I just don't know about?  Thanks.

A: If you did not prepare for this question then there is no build in way to get to that information. However, you could use third party log reader tools to recover (all) the last statements that where executed against the database. This requires the database to be in Full recovery mode. You could potentially go back as far as you have log backups with this method.
If you want to prepare for that question being ask in the future, you have several options.
The most obvious one is Change Data Capture. You also could write a trigger yourself that records data changes.
You could also run a trace capturing SQL Batch Started.
Finally you could use a third party network sniffer/logger to capture all statements send to the server (this however requires that connection encryption is not used).


text:
Q: Wait for condition before strategy starts trading in PineScript I want to wait untill a condition is met before the strategy begins trading.
Trying to make code that waits for the 15 sma to cross below the 12 sma (the Start Trading condition), and then once that happens the strategy can begin trading, but only once the start trading condition is met.
How can I do this ?
--
I tryed to use a switch but this did not work
--
The code so far:
//@version=5
strategy("My script", overlay=true)

fifteensma = ta.sma(close, 15)

twelvesma = ta.sma(close, 12)

sevensma = ta.sma(close, 7)

fourteensma = ta.sma(close, 14)

starttrading =  (fifteensma[0]  < twelvesma[0] ) and (fifteensma[1]  > twelvesma[1] )

longcondition = (sevensma[0]  > fourteensma[0] ) and (sevensma[1]  < fourteensma[1] )

starttradingsignalsoccurred = 0.0

//Wait untill a start trading signal occurs

if (starttrading)

    //when a starttrading signal happens add 1 to the starttrading signal variable
    starttradingsignalsoccurred := starttradingsignalsoccurred[1] + 1

if starttradingsignalsoccurred > 0

    if ( longcondition)

        //Enter Trade Long
        strategy.entry("Long", strategy.long, qty=10)

plot(fifteensma, color=color.red)
plot(twelvesma, color=color.green)
plot(sevensma, color=color.orange)
plot(fourteensma, color=color.blue)

A: I think you mess a bit with 'starttrading' and 'starttradingsignalsoccurred'.
Try :
var starttradingsignalsoccurred = 0

if (starttrading)
    starttradingsignalsoccurred := starttradingsignalsoccurred + 1

if starttradingsignalsoccurred > 0
    if longcondition
    ....

A: I think there is a different way of looking at it -
If I understand correctly, you are looking to start trading after the 12 SMA crossed over the 15 SMA, and stop trading if the 12 SMA crossed under the 15 SMA, and in this trading window you are looking for a crossover of the 7 SMA over the 14 SMA. If that's correct, your trading window is just whenever the 12 SMA is over the 15 SMA, because the trading window is between crossover and crossunder  of those numbers.
If so, you can use:
//@version=5
strategy("My script", overlay=true)

fifteensma = ta.sma(close, 15)
twelvesma = ta.sma(close, 12)
sevensma = ta.sma(close, 7)
fourteensma = ta.sma(close, 14)

starttrading =  (fifteensma[0]  < twelvesma[0] )

longcondition = (sevensma[0]  > fourteensma[0] ) and (sevensma[1]  < fourteensma[1] ) and starttrading

if ( longcondition)
    //Enter Trade Long
    strategy.entry("Long", strategy.long, qty=10)

BTW - instead of your longcondition, you can use a built in function:
starttrading = fifteensma < twelvesma
longcondition = ta.crossover(sevensma, fourteensma) and starttrading

if ( longcondition)
    //Enter Trade Long
    strategy.entry("Long", strategy.long, qty=10)


text:
Q: FFprobeKit command not showing the specific error when it fails to execute I'm getting the video duration of a video in react native by using FFMpegkit library and by running bellow code
const getVideoDuration = async (uri: string): Promise<void> => {
      try {
      await FFprobeKit.executeAsync(
        `-v error -select_streams v:0 -show_entries stream=duration -of default=noprint_wrappers=1:nokey=1 ${uri}`,
      ).then(async information => {
        const failStackTrace = await information.getFailStackTrace();
        console.log(failStackTrace);
        await information.getOutput().then(output => {
          const value = parseFloat(output.toString());
          const time = value * 1000;
          setInputVideoDuration(time);
        });
      });
    } catch (error) {
      console.log(error);
    }
  };

The issue is that the the code isn't executing sometimes. And it's like sporadic. I want to trigger the exact error given when failing this code. The exact error is not given by the library logs but it produce other command executing logs. Is there any way to get the exact error or the exception?
Currently the error shows like this in the logs but it doesn't have any information. also failStackTrace isn't producing any logs either
 libswscale      6.  1.102 /  6.  1.102
 LOG    libswresample   4.  0.100 /  4.  0.100
 LOG  ReturnCode.ERROR


text:
Q: Is it possible to use and httphandler to download image, serve to browser and repeat process? I was wondering if it is possible to use an httphandler to download an image, serve that image to the browser and then do it again.
I currently have access to a url that produces a snapshot image from an ip camera that I would like to continue to pull from.  Essentially making a slide show of the snapshots indefinitely.
I have already figured out how to download the image and display it.  The next step would to, for a lack of better terms, recursively repeat the process.
I certainly can do this with Ajax calls from the client but would much rather remove handle it at the server.
Thanks,
Chad
using Newtonsoft.Json.Linq;
using System;
using System.Net;
using System.Web;
using System.Threading;

namespace Something.App_Code
{
class CameraSnapshotHandler : IHttpAsyncHandler
{
    public bool IsReusable { get { return false; } }

    public CameraSnapshotHandler() { }

    public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
    {
        SnapshotAsynchOperation asynch = new SnapshotAsynchOperation(cb, context, extraData);
        asynch.StartAsyncWork();
        return asynch;
    }

    public void EndProcessRequest(IAsyncResult result) { }

    public void ProcessRequest(HttpContext context)
    {
        throw new InvalidOperationException();
    }
}

class SnapshotAsynchOperation : IAsyncResult
{
    private bool _completed;
    private Object _state;
    private AsyncCallback _callback;
    private HttpContext _context;

    bool IAsyncResult.IsCompleted { get { return _completed; } }
    WaitHandle IAsyncResult.AsyncWaitHandle { get { return null; } }
    Object IAsyncResult.AsyncState { get { return _state; } }
    bool IAsyncResult.CompletedSynchronously { get { return false; } }

    public SnapshotAsynchOperation(AsyncCallback callback, HttpContext context, Object state)
    {
        _callback = callback;
        _context = context;
        _state = state;
        _completed = false;
    }

    public void StartAsyncWork()
    {
        ThreadPool.QueueUserWorkItem(new WaitCallback(StartAsyncTask), null);
    }

    private void StartAsyncTask(Object workItemState)
    {
        using (var client = new WebClient())
        {
            // Get Json data
            string username;
            string password;
            using (var credClient = new WebClient())
            {
                dynamic stuff = JObject.Parse(credClient.DownloadString(new Uri("http://www.some-url.com/servicestack/equipment-credentials.json?equipmentId=" + _context.Request.QueryString["id"])));
                username = stuff.Username;
                password = stuff.Password;
            }

            // Wait until we have full buffer before displaying
            _context.Response.BufferOutput = true;
            // Set content type to match
            _context.Response.ContentType = "image/png";

            // Digest Authenticate
            client.Credentials = new NetworkCredential(username, password);

            // Download into bit array
            byte[] content = client.DownloadData("http://some-url/cgi/image.php?type=snapshot");
            // Output stream to client
            _context.Response.OutputStream.Write(content, 0, content.Length);
        }

        _completed = true;
        _callback(this);
    }
}

}


text:
Q: How to get data from two tables for CGridView in YII I have the following tables,
CREATE TABLE `m_user`(
    `user_id` INT AUTO_INCREMENT PRIMARY KEY,
    `user_name` VARCHAR(50) NOT NULL,
    `pwd` VARCHAR(50) NOT NULL,
    `type` VARCHAR(25) NOT NULL,
    `actv_sw` VARCHAR(2) NOT NULL,
    `cre8_ts` TIMESTAMP NOT NULL,
    `lst_updt_ts` TIMESTAMP NOT NULL
);

CREATE TABLE `m_expense`(
    `expense_id` INT AUTO_INCREMENT PRIMARY KEY,
    `expense_name` VARCHAR(100) NOT NULL,
    `actv_sw` VARCHAR(2) NOT NULL,
    `added_dt` DATE NOT NULL,
    `cre8_ts` TIMESTAMP NOT NULL,
    `cre8_by` INT NOT NULL,
    `lst_updt_ts` TIMESTAMP,
    `lst_updt_by` INT,
    CONSTRAINT `m_expense_fk1` FOREIGN KEY (`cre8_by`)
        REFERENCES `m_user` (`user_id`),
    CONSTRAINT `m_expense_fk2` FOREIGN KEY (`lst_updt_by`)
        REFERENCES `m_user` (`user_id`)
);

and the CGridview definition is as follows,
$this->widget('zii.widgets.grid.CGridView', array(
    'id' => 'expense-grid',
    'emptyText' => 'No data Found',
    'dataProvider' => Expense::model()->search(),
    'cssFile' => Yii::app()->theme->baseUrl . '/css/gridView.css',
    'enablePagination' => true,
    'enableSorting' => true,
    'pagerCssClass' => 'pager',
    'columns' => array(
        //styling default buttons
        array(
            'header' => 'Update',
            'class' => 'CButtonColumn',
            'template' => '{update}',
            'updateButtonImageUrl' => Yii::app()->theme->baseUrl . '/images/' . 'gr-update.png'
        ),
        array(
            'name' => 'expense_id',
            'header' => 'Id',
            'value' => '$data->expense_id',
            'htmlOptions' => array('style' => 'min-width:20px;')
        ),
        array(
            'name' => 'expense_name',
            'header' => 'Expense Name',
            'value' => '$data->expense_name',
            'htmlOptions' => array('style' => 'min-width:150px;')
        ),
        array(
            'name' => 'added_dt',
            'header' => 'Added Date',
            'value' => '$data->added_dt',
            'htmlOptions' => array('style' => 'min-width:100px;')
        ),
        array(
            'name' => 'actv_sw',
            'header' => 'Active',
            'filter' => array('Y' => 'Yes', 'N' => 'No'),
            'value' => '($data->actv_sw=="Y")?("Yes"):("No")',
            'htmlOptions' => array('style' => 'min-width:50px;')
        ),
        array(
            'name' => 'cre8_ts',
            'header' => 'Created Time',
            'value' => '$data->cre8_ts',
            'htmlOptions' => array('style' => 'min-width:100px;')
        ),
        array(
            'name' => 'cre8_by',
            'header' => 'Created By',
            'value' => '$data->user_name',
            'htmlOptions' => array('style' => 'min-width:50px;')
        ),
        array(
            'name' => 'lst_updt_ts',
            'header' => 'Updated Time',
            'value' => '$data->lst_updt_ts',
            'htmlOptions' => array('style' => 'min-width:100px;')
        ),
        array(
            'name' => 'lst_updt_by',
            'header' => 'Updated By',
            'value' => '$data->user_name',
            'htmlOptions' => array('style' => 'min-width:50px;')
        )
    )
        )
);

Model is defined as follows,
class Expense extends CActiveRecord {

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'm_expense';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        return array(
            array('expense_name, actv_sw, added_dt, cre8_ts, cre8_by', 'required'),
            array('cre8_by, lst_updt_by', 'numerical', 'integerOnly' => true),
            array('expense_name', 'length', 'max' => 100),
            array('actv_sw', 'length', 'max' => 2),
            array('lst_updt_ts', 'safe'),
            array('expense_id, expense_name, actv_sw, added_dt, cre8_ts, cre8_by, lst_updt_ts, lst_updt_by', 'safe', 'on' => 'search')
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        return array(
            'cre8By' => array(self::BELONGS_TO, 'MUser', 'cre8_by'),
            'lstUpdtBy' => array(self::BELONGS_TO, 'MUser', 'lst_updt_by'),
            'tExpensesPayments' => array(self::HAS_MANY, 'TExpensesPayment', 'expense_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'expense_id' => 'Expense',
            'expense_name' => 'Expense Name',
            'actv_sw' => 'Active Status',
            'added_dt' => 'Added Date',
            'cre8_ts' => 'Cre8 Ts',
            'cre8_by' => 'Cre8 By',
            'lst_updt_ts' => 'Lst Updt Ts',
            'lst_updt_by' => 'Lst Updt By',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function search() {
        $criteria = new CDbCriteria;

        /* $criteria->compare('expense_id', $this->expense_id);
          $criteria->compare('expense_name', $this->expense_name, true);
          $criteria->compare('actv_sw', $this->actv_sw, true);
          $criteria->compare('added_dt', $this->added_dt, true);
          $criteria->compare('cre8_ts', $this->cre8_ts, true);
          $criteria->compare('cre8_by', $this->cre8_by);
          $criteria->compare('lst_updt_ts', $this->lst_updt_ts, true);
          $criteria->compare('lst_updt_by', $this->lst_updt_by); */

        return new CActiveDataProvider('Expense', array(
            'criteria' => array(
                'with' => array('cre8By' => array('joinType' => 'LEFT JOIN'))
            )
        ));
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return Expense the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

}

Actually i want to display username instead of cre8_by & lst_updt_by columns in CGridView, Help me to resolve this issue. Thanks in advance...............

A: Replace
'value' => '$data->cre8_by', by
'value' => '$data->cre8By->user_name',

Then
replace 'value' => '$data->user_name', by
'value' => '$data->lstUpdtBy->user_name',

You have to add another relation in search:
return new CActiveDataProvider('Expense', array(
            'criteria' => array(
                    'with' => array('cre8By' => array('joinType' => 'LEFT JOIN'),
                                    'lstUpdtBy' => array('joinType' => 'LEFT JOIN')
                                   ),
                     'together'  => true
            )
        ));


text:
Q: Merge 3 flat, indexed arrays into one flat, indexed array I'd like to merge three arrays like this:
$a = array(1,2,3,4);
$b = array(5,6,7,8);
$c = array(1,2,3,4);

into one big array so that the output would be:
$result = array(1,2,3,4,5,6,7,8,1,2,3,4);

A: http://php.net/manual/en/function.array-merge.php
$a = array(1,2,3,4);
$b = array(5,6,7,8);
$c = array(1,2,3,4);

$out = array_merge($a, $b, $c);

Result:
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 1
    [9] => 2
    [10] => 3
    [11] => 4
)


text:
Q: Gulp TypeError: Arguments to path.join must be strings I have i problem with gulp-ruby-sass. When i try to run the watch task and change some .sass files it occurs error:
TypeError: Arguments to path.join must be strings

Here is my gulpfile.js
var gulp = require('gulp');
var jade = require('gulp-jade');
var sass = require('gulp-ruby-sass');
var watch = require('gulp-watch');

gulp.task('sass', function() {
    return gulp.src('sass/*.sass')
        .pipe(sass())
                .pipe(gulp.dest('./css'));

});
gulp.task('watch', function() {
    gulp.watch('./sass/*.sass', ['sass']);
})

I used gulp-slash but it don't works.

A: With the syntax changes in gulp-ruby-sass starting from 1.0.0-alpha, you'll need to use gulp-ruby-sass() instead of gulp.src() to compile your Sass from a file or directory.
If you try to use the original syntax with newer or latest versions, you may encounter the following error:
TypeError: Arguments to path.join must be strings
For example, the original syntax in 0.7.x and earlier using gulp.src(), now deprecated:
var gulp = require('gulp');
var sass = require('gulp-ruby-sass');

// gulp-ruby-sass: 0.7.1
gulp.task('sass', function() {
    return gulp.src('path/to/scss')
        .pipe(sass({ style: 'expanded' }))
        .pipe(gulp.dest('path/to/css'));
});

The new syntax introduced in 1.x using gulp-ruby-sass() as a gulp source adapter:
// gulp-ruby-sass: 1.x
gulp.task('sass', function() {
    return sass('path/to/scss', { style: 'expanded' })
        .pipe(gulp.dest('path/to/css'));
});

Notice the difference in the first line of the return statement.
Also keep in mind, as of this writing when using gulp-ruby-sass 1.0.0-alpha, globs are not supported yet.

A: gulp-ruby-sass syntax changes in version 1.0.0. See this issue:
https://github.com/sindresorhus/gulp-ruby-sass/issues/191
New docs are currently here:
https://github.com/sindresorhus/gulp-ruby-sass/tree/rw/1.0#gulp-ruby-sass-is-a-gulp-source-adapter
This should compile sass files in specified directory:
gulp.task('sass', function() {
    return sass('sass/')
        .pipe(gulp.dest('./css'));
});

A: Slightly off-topic, but in the case of also wanting to use gulp-sourcemaps, the various documentation out there is somewhat outdated. To use rjb's example with sourcemaps, you would thus go
// gulp-ruby-sass: 1.x
gulp.task('sass', function() {
    return sass('path/to/scss', { style: 'expanded', sourcemap: true })
        .pipe(sourcemaps.init({loadMaps: true}))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest('path/to/css'));
});

Note that the destination arg for sourcemaps, './', will evaluate to the folder in the line below, gulp.dest(...), effectively here, map-file will end up in 'path/to/css'.
Credit for this goes to http://www.devworkflows.com/posts/getting-scss-auto-prefixer-and-source-map-to-play-nice/.


text:
Q: Macbook Pro - no sound output I have a Macbook Pro 2015 running Mojave 10.14.6.
I have absolutely no sound output both from internal speakers and headphones, even the startup sound doesn't play. Microphone input is fine. The sound settings are OK, connecting and disconnecting the headphones is recognized correctly, no red light from the headphones jack socket. No peripherals are connected, Bluetooth is turned off.
I tried:

*

*Reboot, multiple times

*Install the latest system update

*Reboot to safe mode

*Reset PRAM

*Run sudo killall audiod

*Log in a guest account

Any other ideas? Thanks!

A: I know you've already reset the NVRAM (what you're referring to as PRAM), but the first thing I'd try is to reset both the NVRAM and SMC in that order. Before following the steps below, ensure you have no external hardware connected and make sure you use the built-in keyboard.
Reset the NVRAM
Your Mac uses Non-Volatile Random-Access Memory (NVRAM). Here's how to reset the NVRAM on your particular MBP:

*

*Shut down your machine. Yes, a full shut down, not just logging out.

*Press the power button and then press the commandoptionpr keys. You have to make sure you press these keys before the gray screen appears or it won't work.

*Hold those keys down until your Mac reboots again and you here the startup chime for the second time.

*Let go of the keys and let your Mac reboot normally.

Note: When you log back in you may need to readjust some of your system preferences (e.g. speaker volume, screen resolution, startup disk selection, time zone information, etc).
Once done, proceed to resetting the SMC as well.
Reset the SMC
To reset the System management Controller on your particular MBP, follow these steps:

*

*Shut down your computer

*Keep the power cable plugged in

*Press at the same time shiftoptioncontrol (on the left side of the keyboard) and the power button and hold all these down for at least 10 seconds

*Let go

*Turn your computer back on with the power button.

After resetting both the NVRAM and SMC, use your Mac to determine if you still have no sound output.
If it doesn't, then it's time to test your hardware with Apple Diagnostics.
Run Apple Diagnostics
Follow the steps below to run Apple Diagnostics:

*

*Fully shut down your MBP

*Restart your MBP

*Immediately press the D key and keep it down until you see the Diagnostics screen appear

*Wait for Diagnostics to finish (this typically only takes a few minutes)

*Once complete, one of two things will appear on the screen:

*

*a No issues found message

*a brief description of any errors found plus further instructions

*If the diagnostics test does find errors, take a note of what they are

Note: If pressing and holding the D key at Step 3 doesn't work, start again at Step 1 and, at Step 3 press and hold both the OptionD keys instead. This will try and run diagnostics from the internet instead, so you will need to allow more time for it to complete.
Regardless, take a note of what happens and let me know how you went.


text:
Q: Does the ASHWID change if the BIOS is upgraded? Microsoft provides a method to get an ASHWID (App Specific Hardware ID) which has many components, one of which is some kind of BIOS ID.
http://msdn.microsoft.com/en-us/library/windows/apps/jj553431.aspx
Does that BIOS ID change if the user upgrades the BIOS on their computer?
RANT:
I don't understand why Microsoft makes getting a unique ID for an OS installation so complicated for Windows Store Apps. Android is so simple, when the Android OS boots the very first time they generate a GUID (see http://developer.android.com/reference/android/provider/Settings.Secure.html#ANDROID_ID) that never changes. Why doesn't Microsoft do this?

A: First of all, that value changes with factory reset in Android.
Second of all, try checking out EasClientDeviceInformation.Id. It uses a combination of the MachineId (local user group SID), the UserId, and the Package Id, but doesn't give you the whole thing.
This is good because Thirdly, giving devs access to use them directly to generate things like crypto keys can lead to other apps getting your apps keys, like has happened on many iOS devices. By limiting what device id's you can use, they're making it so that you must use a system resource that is literally only accessible from inside of a given application with a given Id from inside that user's account. The Windows Store is very strongly sandboxed for exactly this reason. While it can be a pain sometimes, it makes the platform much more secure, which is a huge boon.