text:
Q: IPython notebook: How to write cell magic which can access notebook variables? My question is: How can I write an IPython cell magic which has access to the namespace of the IPython notebook?
IPython allows writing user-defined cell magics. My plan is creating a plotting function which can plot one or multiple arbitrary Python expressions (expressions based on Pandas Series objects), whereby each line in the cell string is a separate graph in the chart.
This is the code of the cell magic:
def p(line, cell):
    import pandas as pd
    import matplotlib.pyplot as plt

    df = pd.DataFrame()
    line_list = cell.split('\n')

    counter = 0
    for line in line_list:
        df['series' + str(counter)] = eval(line)
        counter += 1

    plt.figure(figsize = [20,6])
    ax = plt.subplot(111)
    df.plot(ax = ax)

def load_ipython_extension(ipython):
    ipython.register_magic_function(p, 'cell')

The function receives the entire cell contents as a string. This string is then split by line breaks and evaluated using eval(). The result is added to a Pandas DataFrame. Finally the DataFrame is plotted using matplotlib.
Usage example: First define the Pandas Series object in IPython notebook.
import pandas as pd
ts = pd.Series([1,2,3])

Then call the magic in IPython notebook (whereby the whole code below is one cell):
%%p
ts * 3
ts + 1

This code fails with the following error:
NameError: name 'ts' is not defined

I suspect the problem is that the p function only receives ts * 3\n ts + 1 as a string and that it does not have access to the ts variable defined in the namespace of IPython notebook (because the p function is defined in a separate .py file).
How does my code have to be changed so the cell magic has access to the ts variable defined in the IPython notebook (and therefore does not fail with the NameError)?

A: Use the @needs_local_scope decorator decorator. Documentation is a bit missing, but you can see how it is used, and contributing to docs would be welcome.

A: You could also use shell.user_ns from Magics. For example something like:
from IPython.core.magic import Magics

class MyClass(Magics):
    def myfunc(self):
        print(self.shell.user_ns)

See how it's used in code examples: here and here.


text:
Q: How to Stick Footer to Bottom of the site when Page Content is Less? Sometimes on my site, that have few lines of text or very less content.
In such cases, the footer displays below the content somewhere between the page. That does not give a nice look to the page.
Like this:

When I add a css:
.ar-footer{
   position:absolute;
   bottom:0px;
   left:0px;
   right:0px;
   width:100%;
 }

The footer content is changed. Like this:

how to fix it? I want to fix the footer section into bottom of the pages if the content is less or more.

A: If you have a CSS for main content add
#maincontent{
flex-grow: 1;
}

If not you could try add it to the body tag [Not sure if this works tho]
body{
flex-grow: 1;
}

This will force your content to take up the full display and your footer should stick to the bottom

A: Structure your basic HTML-Markup like this:

Then in your css add
#wrap {
  min-height: 100%;
}

Super simple and works across all browsers. Add all your other markup inside the #wrap. If it helps you can also put the header inside the wrap. Just make sure wrap is before the footer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: R DT override default selection color There are similar questions asked before
R Shiny DataTable selected row color
Background color of DT::datatable in shiny
DT datatable selected row color: inconsistent behavior on IE and chrome
However none of the solutions mentioned worked in my case.
I put a DT table in the sidebar of a dashboard, because I want to use that table to control behavior of other pages and would like the table to be visible all the times.
Here is the sample code
if (!require("pacman")) install.packages("pacman")
pacman::p_load(shiny, shinydashboard, DT, data.table, ggplot2)
sidebar_width <- 260
header <- dashboardHeader(title = "Dashboard",
                          titleWidth = sidebar_width,
                          dropdownMenuOutput("messageMenu"))
sidebar <- dashboardSidebar(
  width = sidebar_width,
  sidebarMenu(
    id = "tabs",
    menuItem("menu 1", icon = icon("bar-chart-o"), tabName = "charts"
             ),
    br(), br(), br(),
    fluidRow(
      # tags$head(tags$link(rel = "stylesheet", type = "text/css", href = "www/styles.css")),
      column(11, offset = 0, DTOutput("control_dt"))
    )
  ))
body <- dashboardBody()
ui <- dashboardPage(header, sidebar, body,skin = "green")
server <- function(input, output, session) {
  output$control_dt <- renderDT({
    DT::datatable(mtcars[1:10, 1:2],
                  selection = list(mode = "multiple",
                                       selected = 1,
                                       target = 'row'),
                  options = list(
                    columnDefs = list(list(className = 'dt-center',
                                           targets = "_all")),
                    dom = "t",
                    pageLength = 10),
                  style = "bootstrap",
                  class = "table-condensed",
                  rownames = TRUE
                  ) %>%
      formatStyle("cyl", target = 'row',
                  color = styleEqual(c(4, 6, 8),
                                     c("red", "gray", "yellow")))
  })
}
shinyApp(ui, server)

My problem is that I used different color for rows depend on value of a column. When a row was selected, it will always use a fixed background color and color, so my customized color is lost.
Because the customized color is dynamically calculated from the data/code, I cannot just hardcode it in the css. The selector I found in app is different from the previous answers because I used bootstrap styles for DT, which is
.table.dataTable tbody td.active, .table.dataTable tbody tr.active td {
    background-color: rgb(0, 117, 176);
    color: white;
}

Now I tried with a customized css which can replace the background color, however I don't know how to unset the white color and let the calculated color take effect. I tried color:unset which didn't work.
The specified color is generated by DT format functions which used datatables callback, then it got defined in row element:

B
20
4

A: The only solution I have consists in using a row callback to add a class to the td, and set !important in the CSS.
Update:
I have an easier solution, see at the bottom.
library(shiny)
library(shinydashboard)
library(DT)

rowCallback <- c(
  "function(row, data, displayNum, displayIndex){",
  "  var x = data[2];", # 2 is the index of the 'cyl' column
  "  if(x == 4){",
  "    $('td', row).addClass('red');",
  "  } else if(x == 6){",
  "    $('td', row).addClass('gray');",
  "  } else if(x == 8){",
  "    $('td', row).addClass('yellow')",
  "  }",
  "}"
)

css <- "
table.dataTable tbody tr td.red {color: red !important}
table.dataTable tbody tr td.gray {color: gray !important}
table.dataTable tbody tr td.yellow {color: yellow !important}
"

sidebar_width <- 260
header <- dashboardHeader(title = "Dashboard",
                          titleWidth = sidebar_width,
                          dropdownMenuOutput("messageMenu"))

sidebar <- dashboardSidebar(
  width = sidebar_width,
  sidebarMenu(
    id = "tabs",
    menuItem("menu 1", icon = icon("bar-chart-o"), tabName = "charts"
    ),
    br(), br(), br(),
    fluidRow(
      tags$head(tags$style(HTML(css))),
      column(11, offset = 0, DTOutput("control_dt"))
    )
  ))

body <- dashboardBody()

ui <- dashboardPage(header, sidebar, body,skin = "green")

server <- function(input, output, session) {
  output$control_dt <- renderDT({
    DT::datatable(mtcars[1:10, 1:2],
                  selection = list(mode = "multiple",
                                   selected = 1,
                                   target = 'row'),
                  options = list(
                    rowCallback = JS(rowCallback),
                    columnDefs = list(list(className = 'dt-center',
                                           targets = "_all")),
                    dom = "t",
                    pageLength = 10),
                  style = "bootstrap",
                  class = "table-condensed",
                  rownames = TRUE
    )
  })
}

shinyApp(ui, server)

Update
I've just found an easier solution, which does not require a row callback:
css <- "table.table.dataTable tbody tr.active td {color: unset}"

fluidRow(
  tags$head(tags$style(HTML(css))),
  column(11, offset = 0, DTOutput("control_dt"))
)

and use the friendly formatStyle:
......
) %>%
  formatStyle("cyl", target = 'row',
              color = styleEqual(c(4, 6, 8),
                                 c("red", "gray", "yellow")))

A: I found a subtle difference in other similar table which didn't have this problem.
When using formatStyle to target a row, the row div got the color style, which was not applied after a row was selected in bootstrap style.
If formatStyle was used to target a column, the specific cell got the color style which will have highest priority and keep the color.
So I can format every column specifically using one column value, then the color will not be overridden by the selection.
... %>%
    formatStyle("cyl",
                  color = styleEqual(c(4, 6, 8),
                                     c("red", "gray", "yellow"))) %>%
      formatStyle("mpg", valueColumns = "cyl",
                  color = styleEqual(c(4, 6, 8),
                                     c("red", "gray", "yellow")))

This solved the problem but I'm not satisfied with it so I will not mark it as answer yet. If there is any better solution I'll mark that as answer.
Update: per @Stéphane Laurent suggestion, we can just use a simpler syntax since the parameter can take a vector.
... %>%
      formatStyle(c("cyl", "mpg"), valueColumns = "cyl",
                  color = styleEqual(c(4, 6, 8),
                                     c("red", "gray", "yellow")))


text:
Q: Is it possible get a dictionary of passed in parameters similar to kwargs(python)? I'm currently creating an object like this:
class Obj(object):
    def __init__(self,**kwargs):
        params = ['val1','val2','val3','val4',...]
        for p in params:
            setattr(self,p,kwargs.get(p,None))

I'm doing this so I don't have to do this:
class Obj(object):
    def __init__(self,val1=None,val2=None,val3=None,val4=None,...):
        self.val1=val1
        self.val2=val2
        self.val3=val3
        self.val4=val4
        ...

My question is, can you do a mix of the two? Where I can define the expected parameters yet still loop the parameters to set the attributes? I like the idea of defining the expected parameters because it is self documenting and other developers don't have to search for what kwargs are used.
I know it seems pretty petty but I'm creating an object from some XML so I'll be passing in many parameters, it just clutters the code and bugs me.
I did google this but couldn't find anything, probably because dictionary and kwargs together point to kwarg examples.
UPDATE: To be more specific, is it possible to get a dictionary of passed in parameters so I don't have to use kwargs at all?
Sudo code:
class Obj(object):
    def __init__(self,val1=None,val2=None,val3=None,val4=None,...):
        for k,v in dictionary_of_paramters.iteritems():
            setattr(self,k,v)

A: You can use the inspect module:
import inspect

def myargs(val1, val2, val3=None, val4=5):
        print inspect.currentframe().f_locals

it shows all the locals available on the current stack frame.
myargs('a','b')
==>  {'val3': None, 'val2': 'b', 'val1': 'a', 'val4': 5}

(note: it's not guaranteed to be implemented on all Python interpreters)
edit: i concur that it's not a pretty solution.  what i would do is more like:
def _yourargs(*names):
        "returns a dict with your named local vars"
        alllocs = inspect.stack()[1][0].f_locals
        return {n:alllocs[n] for n in names}

def askformine(val1, val2, val3=None, val4=5):
        "example to show just those args i'm interested in"
        print _yourargs('val1','val2','val3','val4')

class Obj(object):
        "example inserting some named args as instance attributes"
        def __init__(self, arg1, arg2=4):
                 self.__dict__.update(_yourargs('arg1','arg2'))

edit2 slightly better:
def pickdict(d,*names):
    "picks some values from a dict"
    return {n:d[n] for n in names}

class Obj(object):
    "example inserting some named args as instance attributes"
    def __init__(self, arg1, arg2=4):
        self.__dict__.update(pickdict(locals(),'arg1','arg2'))

A: There is no nice way to get a dictionary of all the arguments to a function.  The **kwargs syntax only collects up the extra keyword arguments, not the ones that match explicit parameters in the function definition.

A: Although you won't be able to get the parameters without using kwargs or the inspect module (see other answers), you can do something like this...
class Obj(object):
    def __init__(self, **kwargs):
        self.__dict__.update(**kwargs)

Every object has a dictionary that stores all of the attributes, which you can access via self.__dict__. Then you're just using update to set all of the attributes in that object's internal dictionary.
See this question on some discussion of this method.

A: If you want to obtain the args dict at the very top of your method, before you define any locals, this is as simple as:
class Obj(object):
    def __init__(self,val1=None,val2=None,val3=None,val4=None):
       kwargs = dict(locals())

To read this dict later on, some introspection magic is required:
class Obj(object):
    def __init__(self,val1=None,val2=None,val3=None,val4=None):

       # feel free to add more locals

       loc = dict(locals())
       fun = sys._getframe().f_code
       kwargs = {x:loc[x] for x in fun.co_varnames[:fun.co_argcount]}

You can also make the latter reusable by adding a function like this:
def getargs():
    f = sys._getframe(1)
    return {x:f.f_locals[x] for x in f.f_code.co_varnames[:f.f_code.co_argcount]}

and then:
class Obj(object):
    def __init__(self,val1=None,val2=None,val3=None,val4=None):

       # feel free to add more locals

       kwargs = getargs()

This is cpython-specific, I guess.

A: Yes you can mix the two.
See below:
def method(a, b=1, *args, **kwargs):
    '''some code'''

This is valid. Here:
'a' is a required argument
'b' is a default argument
'args' will have all the non-keyword arguments and
'kwargs' will have all the keyword arguments.

Example:
method(1,2,3,4,5,test=6,test1=7)

This call will have:
a=1
b=2
args=(3,4,5)
kwargs={'test':6,'test1':7}

A: A kind of an ugly workaround: Inject extra arguments into kwargs and use it where you want to loop over all keyword arguments (PS this is an example usage of the inspect module, but not recommended for production use):
#!/usr/bin/env python

import inspect

def inject_defaults(func):
    """ injects '__defaults' key into into kwargs,
        so it can be merged with kwargs in the decorated method """

    args, varargs, varkwargs, defaults = inspect.getargspec(func)
    have_defaults = args[-len(defaults):]
    defaults_dict = dict(zip(have_defaults, defaults))

    def fun(*args, **kwargs):
        kwargs['__defaults'] = defaults_dict
        return func(*args, **kwargs)

    return fun

@inject_defaults
def f1(a,b,c, x=1, **kwargs):
    kwargs.update(kwargs['__defaults'])
    del kwargs['__defaults']

    for k, v in kwargs.items():
        # here, x, y and z will appear
        print(k, v)

f1(1, 2, 3, y=3, z=2)
# prints
# ('y', 3)
# ('x', 1)
# ('z', 2)


text:
Q: What is the best tool for generating C# classes out of XSD? Is there a modern and regularly updated tool for generating C# v.7+ classes of XSD? The only tool I know is xsd2code but it is not free and its last update, according to the official site was "Update 4.4 (June 05, 2017)"

A: There is an alternative tool:

xsd.exe

Run it like this:
xsd /c /namespace:myCompany /language:CS XMLFile.xsd

I have tried it with this XSD, saved it to disk, and runned the tool. It seems to work.
It's available in the VS-20XX command prompt or, in my case in:

C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.7.1 Tools

For more info on the path: see: where to find xsd.exe in visual studio 2013 on windows 8


text:
Q: Looping through a HTML list I would like to have a piece of JS which loops through a list-item series and for each list-item, it stores a unique attribute value (in this case, the href) and then inserts it as a data attribute to another element within the same list-item (in this case, the button). The JS which I have only applies the desired effect to the first list-item and not the whole series. Can my method be tweaked, or does it require surgery?

  link one
  <button class="atc-button--text">button one</button>

  link two
  <button class="atc-button--text">button two</button>

  link three
  <button class="atc-button--text">button three</button>

document.querySelectorAll('.productgrid--item').forEach(function(node) {
  var anchorHref = document.querySelector('.productitem--image-link').getAttribute('href');
  var addToCart = document.querySelector('.atc-button--text');
  addToCart.setAttribute('data', anchorHref);
});

A: Inside forEach() you should use node.querySelector() instead of document.querySelector().
See https://jsfiddle.net/qkd37rsu/
document.querySelector() selects within entire document tree and returns the first matching element while node.querySelector() searches only subtree of node element (and returns the first matching element). Note that node is just a parameter provided by forEach(function(node){...}).

A: it's easier to follow if you work with your foreach node and from there get and set the attributes you want

  document.querySelectorAll('.productgrid--item').forEach(function(node) {
  var anchorHref = node.querySelector('.productitem--image-link').getAttribute('href');
  var addToCart = node.querySelector('.atc-button--text');
  addToCart.setAttribute('data', anchorHref);
  console.log(addToCart)
});

  link one
  <button class="atc-button--text">button one</button>

  link two
  <button class="atc-button--text">button two</button>

  link three
  <button class="atc-button--text">button three</button>


text:
Q: PhoneGap, PhoneGap Build and iOS - Mac needed? firstly I have reviewed previous similar questions, but there were either old and or contradictory in their answers, so I'm asking what is the current (May '14) requirements to build/test/deploy iPhone/iPad apps?
Longer version – I've been asked by a client to develop an app for iOS/Android and as I'm completely new to this I was hoping to use PhoneGap to use my existing web skills to develop the apps. I currently just own an Android phone so installed the Android SDK and PhoneGap onto Ubuntu (everything download this week inc Ubuntu so all current versions) and eventually got the PhoneGap "hello world" example to run on the emulator and actual phone (not via play store, just local copy of APK file)
I've found many guides here and elsewhere detailing how you can publish to App Store using a PC (or Ubuntu I assume) – mostly talking about certs etc. But, from my experience of setting up my tools to build my first hello world app, PhoneGap requires the SDKs for each device you target, so would thus require the Apple SDK to enable you to run an emulator? Or can you emulate an iPhone on Ubuntu?
So it seems to me, that even thought you can deploy to the  App Store without a Mac, you will need one during development to run the emulator – is this correct or what am I missing?
Thanks in advance!

A: Short answer: You don't need to have the iOS SDK on Ubuntu (nor could you anyway). build.phonegap.com takes care of that for you. There don't seem to be iOS emulators for Ubuntu but there may be some online services that you can leverage. But I believe you still need a Mac to publish to the app store.
Long answer:
You will need:

*

*An Apple Developer account for the certificate files

*You probably need an iOS device for testing. There don't seem to be iOS emulators for Ubuntu though there may be some good online services. (Some good threads on this: 1, 2) See Kerri's comment below highly recommending you test on a real device and not an emulator.
Here's how you would do it:

*

*Using your Apple Developer account, create a certificate and provisioning file in the Certificates, Identifiers & Profiles section.

*Create a .p12 file from the certificate. (You should be able to use OpenSSL but I'm not sure of the exact steps.)

*Register an account with build.phonegap.com.

*Create a signing key using your .p12 and provisioning files.

*Upload your code and build.phonegap.com will create the .ipa file for you.

*If you use an iOS device for testing, you can browse to build.phonegap.com on the device and install the app from there.

*To publish to the app store I believe you still need a Mac with Xcode. (Maybe there's a 3rd party service that does this but I couldn't find any.) An alternative to buying a Mac is to buy just the OS and either dual boot or create a virtual machine.


text:
Q: shiny-server: variable names are limited to 10000 bytes I am getting error while running the code in shiny-server only. When I am running the same code from R console using runApp() function it is running well. See the error message below....
Warning: Error in assign: variable names are limited to 10000 bytes
Stack trace (innermost first):
    46: assign
    45: wrapFunctionLabel
    44: public_bind_env$initialize
    43: Observable$new
    42: reactive
    41: templateServer
    40: server [/home/shiny-apps/ACCPlantAnalysis/server.R#20]
     1: runApp
Error in assign(name, func, environment()) :
  variable names are limited to 10000 bytes

Line no 41 and 40 are written by me. but other lines are not written by me; call from any reference library. I don't know from which library.

A: At last I got solution. I wrote functions for every 'if' block and put all code of 'if' block inside the function. Then call the function. And the was problem solved.
SectoralLeverageRatio(){
...
...
}

if (selectedIndex=="Sectoral Leverage Ratio"){
  SectoralLeverageRatio()
}

The conclusion is... if your 'if' block is large enough and you got 'variable names are limited to 10000 bytes' error. Replace the code inside  the 'if' block with user defined function.
This is the problem of shiny-server; not the problem of 'R'. If you run your code from 'R' console using runApp(), you would not get any error. But if you run through(production environment) you might get an error.

A: after a day long research I am able to pinpoint the issue. I have a long if..else block in my code. There are 10 if block and every if block has at least 6-8 line of code. When I comment one 'if' block of code (randomly chosen) the code running fantastically.... below is my 'if' block of code...
  else if (selectedIndex=="Sectoral Leverage Ratio"){
        ## Calculated number of row of the matrix ##
        rowNum <- selectedMonth[2] - selectedMonth[1] + 1

        ## Filter data based on criteria ##
        filteredData <- subset(rawData,Year %in% selectedYear & Month %in% selectedMonth[1]:selectedMonth[2] & Plant %in% selectedPlant)

        LeverageTable <- filteredData[,c('sch1ExpLeverage','sch2ExpLeverage','sch3ExpLeverage','sch4ExpLeverage','sch5ExpLeverage','sch7ExpLeverage','sch10ExpLeverage','sch11ExpLeverage')]
        LeverageSum <- apply(LeverageTable,2,sum)

        ExpTable <- filteredData[,c('sch1Exp','sch2Exp','sch3Exp','sch4Exp','sch5Exp','sch7Exp','sch10Exp','sch11Exp')]
        ExpSum <- apply(ExpTable,2,sum)

        LeverageRatio <- as.matrix(LeverageSum / ExpSum)
        AvgLeverageRatio <- as.matrix((LeverageSum / ExpSum)/rowNum)

        LeverageRatioTable <- cbind(LeverageRatio,AvgLeverageRatio)
        colnames(LeverageRatioTable) <- c('Leverage Ratio','Avg.Leverage Ratio')

        LeverageRatioTable <- data.frame(Sector=c('Health & Sant.','Edn. & Voc.','Social Welfare','Envt. Sust.','Hrtg & Arts','Sports','Rural Dvpt.','Admin Cost'),LeverageRatioTable)

        as.data.frame(LeverageRatioTable)

  }

All other 'if' blocks are almost similar (with some difference in calculation).
This is the problem of shiny-server; not the problem of 'R' itself.
If anybody wants to examin my code; I can share the full code.

A: According to ?name, you have to respect the fact that:

Names are limited to 10,000 bytes (and were to 256 bytes in versions of R before 2.13.0).

and the rule says in ?make.names:

A syntactically valid name consists of letters, numbers and the dot or
  underline characters and starts with a letter or the dot not followed
  by a number. Names such as ".2way" are not valid, and neither are the
  reserved words.


text:
Q: Extract comments in maven plugin I want to implment a maven plugin that can generate i18n resource boundle from source according special emum class with special field commont like this:
public enum MyColor implements I18nAble {

    /**
     * @zh_CN 红色
     * @en_US red
     */
    RED,

    /**
     * @zh_CN 蓝色
     * @en_US blue
     */
    BLUE,

    /**
     * @zh_CN 绿色
     * @en_US green
     */
    GREEN,

    String i18nCode;

    MyColor(String code) {
         this.i18nCode = "color." + code;
    }

    @Override
    public String getCode(){
        return i18nCode;
    }
}

when mvn package, it generate some xxx.properties files like:
color.red=red
color.blue=blue
color.green=green

color.red=红色
color.blue=蓝色
color.green=绿色

Now I have generated keys already, but I can't extract the comment accurately.(I want to use jdk.javadoc.* rather than regex)
jdk: jdk11 not jdk1.8

A: If you have the ability to parse the code, try this sample:
String locale = "@zh_CN";
Pattern pattern = Pattern.compile(locale + "\\s+(.+)\n(.|\\s)*?\\*/\\s+(\\w+)");
Matcher matcher = pattern.matcher(YOUR_SOURCE_CODE_HERE);

while (matcher.find()) {
    String commentColor = matcher.group(1);
    String colorEnum = matcher.group(3).toLowerCase();
    System.out.println(MessageFormat.format("color.{0}={1}", colorEnum, commentColor));
}

Result output:
color.red=红色
color.blue=蓝色
color.green=绿色

To get english comments just set the locale variable to @en_US.
You can test the expression here: https://regexr.com/59mp1


text:
Q: How to awake and enable clients of .NET Remoting server for fetch data asynchronously? I need to perform inter process communication using .NET Remoting. For this I would share some data in form of Data(Objects) & Methods .
Is there any way out by which my .NET Remoting client can detect that there's some data that is being shared or not, if its just go on and collect that data.Each time server server shares the data with its shared able methods and objects by Marshaling, it should be get aware for client that's another process.
Server can have multiple clients and data can be shared in multiple clients(specific clients or broadcast i.e for every client that is running as separate process).
On client side I would have single dedicated thread for checking shared data, if it arrive it would collect, sleep otherwise. Or somehow each time server sends and event to specific client or multiple clients to make them aware about arrived and shared data.
Is this is the functionality what .NET Remoting Events expose?
My .NET Remoting server is C# process and client is C++/CLI processes.
Regards
Usman

A: That is possible with .NET Remoting.  Perhaps the easiest way would be to have the remote object (the server) include an event to which clients can subscribe.  When the server has data that it wishes to share, it just fires that event and any clients that subscribe to the event get a notification along with the data.


text:
Q: Clearing the chart causes memory leak? I am trying to redraw JFreeChart series every a few seconds with new data. Redrawing is doing in own thread. Everything is working fine but clearing the series causes weird memory leak.
I am not sure if the problem comes from sleeping the thread or there's any bug in the clear() method.
This is complete sample code (problematic line in method SampleDataFeed):
import java.util.Calendar;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.time.FixedMillisecond;
import org.jfree.data.time.ohlc.OHLCSeries;
import org.jfree.data.time.ohlc.OHLCSeriesCollection;

public class sample1 {
    private static OHLCSeries series1;

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                // window
                JFrame wnd = new JFrame();
                wnd.setVisible(true);
                wnd.setSize(800, 500);
                wnd.setLocationRelativeTo(null);
                wnd.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                // chart series
                OHLCSeries series = new OHLCSeries("Test");
                OHLCSeriesCollection seriesCollection = new OHLCSeriesCollection();
                seriesCollection.addSeries(series);
                series1 = seriesCollection.getSeries(0);

                // chart
                final JFreeChart chart = ChartFactory.createCandlestickChart(null, "Time", "Price", seriesCollection, false);
                chart.getXYPlot().setOrientation(PlotOrientation.VERTICAL);

                // chart panel
                final ChartPanel chartPanel = new ChartPanel(chart);
                chartPanel.setMaximumDrawHeight(2000);
                chartPanel.setMaximumDrawWidth(3000);
                wnd.add(chartPanel);

                // chart data feeding thread
                new DataFeedingThread().start();
            }
        });

    }

    private static class DataFeedingThread implements Runnable {
        private Thread t;

        @Override
        public void run() {

            // run recursively
            while (true) {

                // feed the chart with random data
                SampleDataFeed();

                // what 1 second before next run
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        // feed the chart with random data
        private void SampleDataFeed() {
            series1.clear(); // -----> This line causes memory leak! If I'd comment it, everything is Ok.
            for (int i = 0; i < 100; i++) {
                Calendar cal = Calendar.getInstance();
                cal.add(Calendar.MINUTE, i);
                FixedMillisecond fm = new FixedMillisecond(cal.getTime());
                series1.add(fm, randInt(95, 105), randInt(105, 110), randInt(90, 95), randInt(95, 105));
            }
        }

        // return random integer
        private int randInt(int min, int max) {
            Random rand = new Random();
            int randomNum = rand.nextInt((max - min) + 1) + min;
            return randomNum;
        }

        public void start() {
            if (t == null) {
                t = new Thread(this);
                t.start();
            }
        }
    }

}

Update:
JFreeChart version: 1.0.19
Compiler options: none
Memory usage without clearing ~15-30 MB:

Memory usage with clearing ~430MB and raising:

A: I've found out that removings all series of collection and then add new prepared serie with data is solution for this (bug?).
Here's my new code:
import java.util.Calendar;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.time.FixedMillisecond;
import org.jfree.data.time.ohlc.OHLCSeries;
import org.jfree.data.time.ohlc.OHLCSeriesCollection;

public class sample1 {
    private static final OHLCSeriesCollection seriesCollection = new OHLCSeriesCollection();
    private static final DataFeedingThread dataFeedingThread = new DataFeedingThread();

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                createAll();
            }
        });
    }

    public static void createAll() {
        // window
        JFrame wnd = new JFrame();
        wnd.setVisible(true);
        wnd.setSize(800, 500);
        wnd.setLocationRelativeTo(null);
        wnd.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // chart series
        seriesCollection.addSeries(new OHLCSeries("Test"));

        // chart
        final JFreeChart chart = ChartFactory.createCandlestickChart(null, "Time", "Price", seriesCollection, false);
        chart.getXYPlot().setOrientation(PlotOrientation.VERTICAL);

        // chart panel
        final ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setMaximumDrawHeight(2000);
        chartPanel.setMaximumDrawWidth(3000);
        wnd.add(chartPanel);

        // chart data feeding thread
        dataFeedingThread.start();
    }

    public static void setOHLCSeries(OHLCSeries series) {
        seriesCollection.removeAllSeries();
        seriesCollection.addSeries(series);
    }

    private static class DataFeedingThread implements Runnable {
        private Thread t;

        @Override
        public void run() {

            // run recursively
            while (true) {

                // feed the chart with random data
                SampleDataFeed();

                // what 1 second before next run
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        // feed the chart with random data
        private void SampleDataFeed() {
            OHLCSeries series = new OHLCSeries("test");
            for (int i = 0; i < 100; i++) {
                Calendar cal = Calendar.getInstance();
                cal.add(Calendar.MINUTE, i);
                FixedMillisecond fm = new FixedMillisecond(cal.getTime());
                series.add(fm, randInt(95, 105), randInt(105, 110), randInt(90, 95), randInt(95, 105));
            }
            setOHLCSeries(series);
        }

        // return random integer
        private int randInt(int min, int max) {
            Random rand = new Random();
            int randomNum = rand.nextInt((max - min) + 1) + min;
            return randomNum;
        }

        public void start() {
            if (t == null) {
                t = new Thread(this);
                t.start();
            }
        }
    }

}

In the code above I remove all the series in chart and add new serie (with prepared data). That's all and everything's working fine.
Here is the memory profilling:

As you can see, all the application doesn't consume more than 110 MB.
UPDATE 1:
In fact the example above didn't solve the problem. There are a lot of situations where this bug occurres. I've had many hours testing and finding the final solution of the memory leak problem.
The only one posibility is this can be #1111 bug in JFreeGhart. It is open longer than a year.  Mr. Gilber can you fix this problem, please? I am willing to pay you for it if it will all work anytime soon.
Thanks.


text:
Q: Can't use geolocation in my local html I am trying to use geolocation in my local HTML file. But it looks like, navigator.geolocation.getCurrentPosition only works with https. I don't know how could I use it in my local HTML file for learning.

A: A quick solution would be to use a tunneling service like ngrok. Running ngrok http 12345 with 12345 being your local server port will spin up a tunnel and give you the URL you need to access the tunnelled version of your webserver. ngrok offers both HTTP and HTTPS.

A: It seems that chrome has security restrictions on accessing geolocation data locally. You need to host the file to use the data..


text:
Q: SAS set value less than mean to missing Let's say I have data that look like this:
DATA temp;
  INPUT id a1 b2 d1 f8;
DATALINES;
1 2.3 2.1 4.2 1.2
2 5.3 2.3 1.5 3.2
3 1.2 5.4 6.6 6.6
;
run;

What I want to do is use the data and set statements to say that if the values in a1 and f8 are less than the means of a1 and f8 (respectively), then those values are missing. So the resulting dataset would look like:
 id   a1   b2   d1   f8
  1    .  2.1  4.2    .
  2  5.3  2.3  1.5    .
  3    .  5.4  6.6  6.6

Any tips for how I would start on this? I'm new to SAS and the examples in the manuals have not been very helpful. I had been thinking of something like this (but it doesn't work):
DATA temp2;
    SET temp;
        IF a1 < mean(a1) THEN a1=.;
        IF f8 < mean(f8) THEN f8=.;
 RUN;

A: The SAS implementation of SQL can do automatic application of group or data wise aggregates against a result set.
Proc SQL;
  create table want as
  select
    case when (a1 < mean(a1)) then . else a1 as a1,
    b2,
    d1,
    case when (f8 < mean(f8)) then . else f8 as f8
  from have;

A solution that uses DATA step will need to precompute data set statistics, commonly with a procedure such as MEANS, SUMMARY or UNIVARIATE.
proc means noprint data=have;
  output out=have_means mean(a1 f8)= / autoname;
run;

data want;
  if _n_ = 1 then do;
    set have_means(keep=a1_mean f8_mean);
  end;

  set have;
  if a1 < a1_mean then a1 = .;
  if f8 < f8_mean then f8 = .;

  drop a1_mean f8_mean;
run;

Other techniques can update a data set in place and would use SQL UPDATE or DATA step MODIFY

A: mean function is applied across the row and not within the column in datastep, that is why you are not getting the results. @Richard answer is perfect. to do in datastep to get mean, you need to use DOW loop and then append with main dataset. It is much easier to use proc summary as @Richard explains.
    data temp2_intial(keep= mean_a1 mean_f8);
   do until(eof);
   set temp end =eof;
   tot_a1 = sum(tot_a1, a1);
   cnt_a1=sum(cnt_a1,1);
   mean_a1 = tot_a1/cnt_a1;

  tot_f8 = sum(tot_f8, f8);
  cnt_f8=sum(cnt_f8,1);
  mean_f8 = tot_f8/cnt_f8;
    end;
  run;

  data temp2(drop= mean_a1 mean_f8);
  set temp ;
  if _n_ =1 then set temp2_intial;
  IF a1 < mean_a1 THEN a1=. ;
 IF f8 < mean_f8 THEN f8=.;
  run;


text:
Q: Sharing an AWS EC2 image encrypted with an AWS managed key across the accounts I like to share the image across accounts but the image is encrypted with an AWS managed key and I was wondering how I can transfer this image to another account.
I gather an image encrypted with custome keys is transferrable, and is it the same with the image with an AWS key?

A: KMS
With KMS you have AWS Managed Key and Customer Managed Key (CMK).
To allow another account to use your key it needs to be a CMK, because you need to allow it on your key police.
https://docs.aws.amazon.com/kms/latest/developerguide/key-policy-modifying-external-accounts.html
You can't change police on AWS Managed Key. Which means you can't allow other accounts to use an AWS Managed Key.
So you can't share your encrypted AMI with another account when it is using AWS Managed Key.
AMI
An AMI can't be transferred, but you share it with another account. When it is encrypted you need to share the key as well. See documentation below.
https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/sharingamis-explicit.html
As your current AMI is encrypted with AWS Managed Key, what you can do is create a new AMI without encryption or encrypted with CMK and share it. See documentation below.
https://aws.amazon.com/premiumsupport/knowledge-center/account-transfer-ec2-instance/


text:
Q: How to resize callout bubble after resetting title/subtitle I created an MKAnnotation name PushPin which has a title and subtitle.  I want to be able to dynamically change the title at a later time.  I'm close so I'd rather not have to make a whole new AnnotationView, but if I have to I guess that's ok too.  My problem is that, once I change the text for the title, the window does not resize and some text might get cut off depending on how big the title originally was.
1) Is there an event I can trigger to resize the callout bubble window again?
2) Also, I check to make sure that the annotation actually has a title first before I go resetting the title, but I had some trouble casting it after I checked, can someone help me out with this?  I'm still new to objective-c and this one messed with me for a while.

#import <Foundation/Foundation.h>
#import <MapKit/MKAnnotation.h>

@interface PushPin : NSObject <MKAnnotation> {
 CLLocationCoordinate2D _coordinate;
 NSString *_title;
 NSString *_subtitle;
 NSString *_ID;
}

@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
@property (nonatomic, retain) NSString *title;
@property (nonatomic, retain) NSString *subtitle;
@property (nonatomic, retain) NSString *ID;

- (id) initWithCoordinateAndInformation:(CLLocationCoordinate2D)coordinate title:(NSString *)title subtitle:(NSString *)subtitle;

@end

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
 NSLog(@"Annotation was TAPPED!");

 if ([view.annotation isKindOfClass:[PushPin class]]) {
  view.annotation.title = @"test";

          // warning here, that this might not be implemented...
          // but it is for this class type, how do I cast it to the correct type?
 }

}

A: Still having some problems, but getting closer maybe.  I tried this, but still no luck.  I am partially drawing on the code from http://digdog.tumblr.com/post/252784277/mapkit-annotation-drag-and-drop-with-callout-info
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
    NSLog(@"Annotation was TAPPED!");

    if ([view.annotation isKindOfClass:[PushPin class]]) {
        ((PushPin *)view.annotation).title = @"test";
    }

    [self willChangeValueForKey:@"subtitle"]; // Workaround for SDK 3.0, otherwise callout info won't update.
    [self didChangeValueForKey:@"subtitle"]; // Workaround for SDK 3.0, otherwise callout info won't update.

    [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"MKAnnotationCalloutInfoDidChangeNotification" object:self]];
}

Good news is that, I figured out my casting problem, for others who may be curious.
((PushPin *)view.annotation).title = @"test";


text:
Q: More phase inductance in stepper motor The selected stepper motor not enough to make required torque.
So, I think its better to replace the stepper with higher torque.
But, new stepper motor has 2.8mH  phase inductance,Old one has 1.2mH.
How this inductance effect to the same stepper driver? Is there some advantages or disadvantages?

A: A higher winding inductance means you will need a higher voltage chopping driver to maintain torque at higher step rates where inductance extends the current rise time each time the motor steps.
It's not uncommon to use for example a coil with an ohmic voltage rating of less than 4 volts with a chopping driver backed by a supply of 12 volts or more.  Conversely, a 12 volt rated coil will have very little torque at speed when used with a driver which can only apply 12 volts.
The same motor chassis is usually available wound in different ways.  For performance you generally want to chose the lowest inductance configuration, which is typically also the lowest coil resistance or ohmic coil voltage.
That said, if you're buying something through a discount/surplus channel, you may not be able to select the ideal configuration.
You should also consider if you are getting full rated current through your existing motor before replacing it - it may be that what you really need to replace is the driver.  The most informative way to really evaluate this is with a scope on the driver's current sense resistor while commanding high step rates, but the driver's manual may give you instructions for setting the drive current by theoretical means.


text:
Q: Show button in Django template only when the file is selected through check box? I am getting the check box dynamically in Django template like this:
 <input type="checkbox" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
              {{ choice.file_name }}

There's a unshare button like this:
<button>Unshare</button>

I want to show the Unshare button only when the user clicks on check-box.

A: Firstly add some more id's to your template so that you can identify elements.

{% for choice in choices %}
    <input type="checkbox" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
    {{ choice.file_name }}
{% endfor %}

Then give the button an id and an inline style -
<button id="unshare_button" style="display: none;">Unshare</button>
Then use the following javascript (this shows the button as soon as any one of the
checkboxes is clicked - it doesn't hide the button if they're unchecked).
var choices_table = document.getElementByID('choices');
var checkboxes = choices_table.getElementsByTagName('input');
var unshare_button = document.getElementByID('unshare_button');
for (var i = checkboxes.length; i > 0; i--) {
    checkboxes[i].addEventListener('click', function() {
        unshare_button.style.display = 'inline';
    }
}

I'm afraid I haven't checked this code, but it should give you an idea.


text:
Q: Comparing two numbers given their factorization I'm not an expert, but given the integer factorization of two numbers $a,b$:
$$a = p_{i_1}^{a_1}...p_{i_n}^{a_n}, \quad b = p_{j_1}^{b_1}...p_{j_m}^{b_m}$$

What is the time and space compexity of checking if $a > b$ ?

Suppose that the factors and the exponents are given in binary and the whole input over alphabet $\{0,1,\wedge,;,*\}$ looks like:
$$p_{i_1}\wedge{a_1}*...*p_{i_n}\wedge{a_n};p_{j_1}\wedge{b_1}*...*p_{j_m}\wedge{b_m}$$
What algorithms can be used?

A: According to this paper from 2013 by Etessami, Stewart, and Yannakakis, the time complexity of the [a priori] harder problem where the $p_k$ are not required to be prime is still open.  In that paper the authors show that certain conjectures in number theory would imply that the simple algorithm ("compute enough bits of the logs") runs in polynomial time.  The authors also observe that unconditional on any conjectures the algorithm runs in polynomial time for fixed $m$ and $n$ by Baker's Theorem.  Of course, it is possible that the version of the problem with $p_k$ prime is strictly easier than the more general one.


text:
Q: Scrapy - download images from image url list Scrapy has ImagesPipeline that helps download image. the process is

*

*Spider: start a link and parse all image urls in response, and save
image urls to items.

*ImagesPipeline: items['image_urls'] are processed by ImagesPipeline.

But what if I don't need spider parts and have 100k images URLs ready to be downloaded, for example read URLs from redis, how do I call ImagePipeline directly to download the image?
I know I could simply make Request in spider and save response, but I'd like to see if there is way use default ImagesPipeline to save images directly.

A: I don't think that the use case you describe is the best fit for Scrapy. Wget would work fine for such a constrained problem.
If you really need to use Scrapy for this, make a dummy request to some URL:
def start_requests(self):
    request = Request('http://example.com')
    # load from redis
    redis_img_urls = ...
    request.meta['redis_img_urls'] = redis_img_urls
    yield request

Then on the parse() method return:
def parse(self, response):
    return {'image_urls':request.meta['redis_img_urls'] }

This is ugly but it should work fine...
P.S. I'm not aware of any easy way to bypass the dummy request and inject and Item directly. I'm sure there's one but it's such an unusual thing to do.

A: The idea behind a scrapy Pipeline is to process the items the spider generates explained here.
Now scrapy isn't about "downloading" staff, but a way to create crawlers, spiders, so if you have a list with urls to "download", then just use for loop and download them.
If you still want to use a scrapy Pipeline, then you'll have to return an item with that list inside the image_urls field.
def start_requests(self):
    yield Request('http://httpbin.org/ip', callback=self.parse)

def parse(self, response):
    ...
    yield {'image_urls': [your list]}

Then enable the pipeline on settings.


text:
Q: Clustering Documents in Python I understand that this question has been asked before and there are many links. I have gone through them, well most of them anyway but sadly failed to find a simple, and concise reponse. The number of documents are around 4800.
So here it goes.
I am using nltk for clustering a multitude of text documents. What I have done till now is

*

*Parsing and Tokenization

*Stopword and Stemming

The next step that I am doing is to find a TF-IDF vector for each document. So that I have n vectors of equal length for n documents.
Now I need to feed these vectors into my K-means function and let it rip.
Question is, am I doing it right?
Next question is related to code:
corpus = []
unique_terms = []

def TFIDF(document):
    start_time = time.time()
    word_tfidf = []
    for word in unique_terms:
        word_tfidf.append(collection.tf_idf(word,document))

    print time.time() - start_time
    return word_tfidf

if __name__ == '__main__':
    count = 0
    corpus = cPickle.load(open('C:\\Users\\Salman\\Desktop\\Work\\NLP\\Corpus\\FB\\save-3.p', 'rb'))    ##read the corpus from file
    collection = nltk.TextCollection(corpus)
    unique_terms = list(set(collection))
    vectors = [numpy.array(TFIDF(f)) for f in corpus]
    print "Vectors created."
    print "First 10 words are", unique_terms[:10]
    print "First 10 stats for first document are", vectors[0][0:10]

I have already downloaded the corpus (list of vectors for each document before TF-IDF) to a file that I am reading in corpus.
Problem is that it's been 8 hours and this process hasn't yet completed. Have I missed anything here? Or in general, TF-IDF does take this amount of time.

A: you wrote there is 4800 documents, but didn't specify length of documents. Anyway, 8 hours is really long time (TF_IDF with some standard euclidean distance is not too much expensive).
If you want to know whether it is counting, just look at load balance (e.g. uptime in linux). Most likely there is something wrong and you should look after logging info ...


text:
Q: WPF - How to use Badge in Mahapps HamburgerMenuItem Quick question for who known WPF:
How to add a badge in a Mahapps HamburgerMenuItem?
I use this template:
    <DataTemplate x:Key="MenuItemTemplate" DataType="{x:Type Controls:HamburgerMenuIconItem}">
                <Grid Height="48">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="48" />
                        <ColumnDefinition />
                    </Grid.ColumnDefinitions>
                    <ContentControl Grid.Column="0" HorizontalAlignment="Center" VerticalAlignment="Center">

                            <Rectangle Width="20" Height="20" HorizontalAlignment="Center" VerticalAlignment="Center">
                                <Rectangle.Fill>
                                    <VisualBrush Stretch="Fill" Visual="{Binding Icon}" />
                                </Rectangle.Fill>
                            </Rectangle>

                    </ContentControl>
                    <TextBlock Grid.Column="1" VerticalAlignment="Center" FontSize="16" Foreground="White" Text="{Binding Label}" />
                </Grid>
</DataTemplate>

And here is my Hamburger Items:

            <Controls:HamburgerMenuItemCollection>

                <Controls:HamburgerMenuIconItem Icon="{StaticResource appbar_home_variant}" Label="Home">
                    <Controls:HamburgerMenuIconItem.Tag>
                        <Grid Name="HomeView"></Grid>
                    </Controls:HamburgerMenuIconItem.Tag>
                </Controls:HamburgerMenuIconItem>

                <Controls:HamburgerMenuIconItem Icon="{StaticResource appbar_people_status}" Label="Private" >
                    <Controls:HamburgerMenuIconItem.Tag>
                        <Grid Name="PrivateView"></Grid>
                    </Controls:HamburgerMenuIconItem.Tag>
                </Controls:HamburgerMenuIconItem>

                <Controls:HamburgerMenuIconItem Icon="{StaticResource appbar_page_onenote}" Label="Notes">
                    <Controls:HamburgerMenuIconItem.Tag>
                        <Grid Name="NotesView"></Grid>
                    </Controls:HamburgerMenuIconItem.Tag>
                </Controls:HamburgerMenuIconItem>

                <Controls:HamburgerMenuIconItem Icon="{StaticResource appbar_cog}" Label="Settings">
                    <Controls:HamburgerMenuIconItem.Tag>
                        <Grid Name="SettingsView"></Grid>
                    </Controls:HamburgerMenuIconItem.Tag>
                </Controls:HamburgerMenuIconItem>

            </Controls:HamburgerMenuItemCollection>

        </Controls:HamburgerMenu.ItemsSource>

Here what I am looking for:
HamburgerMenu Badge
Regards,

A: As I found here
You can wrap them arround your Icon.
<Controls:Badged Badge="{Binding Path=BadgeValue}" BadgePlacementMode="BottomRight">
    <!-- Control to wrap goes here -->
    <Button>
        <iconPacks:PackIconFontAwesome Kind="CommentOutline"/>
    </Button>
</Controls:Badged>

In your example it would be:
<Controls:Badged Badge="{Binding Path=BadgeValue}">
    <Controls:HamburgerMenuIconItem Icon="{StaticResource appbar_home_variant}" Label="Home">
            <Controls:HamburgerMenuIconItem.Tag>
                <Grid Name="HomeView"></Grid>
            </Controls:HamburgerMenuIconItem.Tag>
    </Controls:HamburgerMenuIconItem>
</Controls:Badged>

A: it is possible. But it will get cut and does not look very good IMO
Example closed:

Example opened:

How to get it?:
Just wrap your Icon in the DataTemplate with a Badge:
<DataTemplate x:Key="HamburgerMenuItem" DataType="{x:Type Controls:HamburgerMenuGlyphItem}">
        <DockPanel Height="48" LastChildFill="True">
            <Controls:Badged x:Name="IconPart"
                                Width="48"
                                Badge="?"
                                BadgeBackground="Red"
                                DockPanel.Dock="Left">
                <Image Margin="12"
                        HorizontalAlignment="Center"
                        VerticalAlignment="Center"
                        Source="{Binding Glyph}"
                        Stretch="UniformToFill" />
            </Controls:Badged>
            <TextBlock x:Name="TextPart"
                        VerticalAlignment="Center"
                        FontSize="16"
                        Text="{Binding Label}" />
        </DockPanel>
        <DataTemplate.Triggers>
            <DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Controls:HamburgerMenu}}, Path=PanePlacement}" Value="Right">
                <Setter TargetName="IconPart" Property="DockPanel.Dock" Value="Right" />
                <Setter TargetName="TextPart" Property="Margin" Value="8,0,0,0" />
            </DataTrigger>
        </DataTemplate.Triggers>
</DataTemplate>

You can modify this to your needs.
UPDATE: Here are additional information from the maintainer of MahApps: https://github.com/MahApps/MahApps.Metro/issues/3800#issuecomment-631103384
I hope this helps and happy coding
Tim


text:
Q: Windows Server 2008 Service pack 2 - Downloading files using .bat file I was wondering whether there is a way to download files using a .bat file.
Bitsadmin.exe no longer works for 2008R2.
If you could help with this, that would be greatly appreciated.
Thanks in advance!

A: you could use Powershell like so:
(new-object System.Net.WebClient).DownloadFile("http://www.google.co.uk", "c:\temp\tempfile.txt"

A: With a bat file, calling powershell, as I do in senv.bat:
@echo off

@powershell -NoProfile -ExecutionPolicy unrestricted -Command "& \"C:\path\to\ascript.ps1\"" %*

Then a script.ps1 can call DownloadFile as mentioned by Paul.
That same powershell command can actually be called from a regular shell:
C:\> @powershell -NoProfile -ExecutionPolicy unrestricted -Command "(New-Object System.Net.WebClient).DownloadFile('http://an/url','c:/temp/aFile')"


text:
Q: Maximum value of $ x^2 + y^2 $ given $4 x^4 + 9 y^4 = 64$ It is given that $4 x^4 + 9 y^4 = 64$.
Then what will be the maximum value of $x^2 + y^2$?
I have done it using the sides of a right-angled triangle be $2x , 3y $ and hypotenuse as 8 .

A: If $64= (3y^2)^2 + 4x^4$, then $3y^2 =\sqrt{ 64 - 4x^4}$. Plugging that to $x^2+y^2$ we get:
$$x^2+\frac{\sqrt{64 - 4x^4}}{3}.$$
Now you have to maximalize a function of one variable. Remember that if $64 = 4x^4+9y^4$, then (setting $y = 0$) we obtain $16 \ge x^4$, therefore $|x| \le 2$.

A: $x^2=s,\ y^2=t \geq 0$ then $$ (2s)^2+ (3t)^2=8^2 \Rightarrow
2s=4\cos\ \theta,\ 3t=4\sin\ \theta,\ 0\leq\theta \leq
\frac{\pi}{2} $$
Then $$ s+t=2\cos\ \theta + \frac{4}{3}\sin\ \theta=\sqrt{2^2+
\bigg(\frac{4}{3}\bigg)^2} \sin\ (\theta+\alpha),\ 0< \alpha <
\frac{\pi}{2} $$
Let $\theta =\frac{\pi}{2}-\alpha$

A: Without using Lagrange multipliers
It's equivalent to find $x$ that maximizes
$$f(x)=x^2+\frac23\sqrt{16-x^4}$$
You have
$$f'(x)=2x-\frac13\frac{4x^3}{\sqrt{16-x^4}}$$
Hence $f'(x)=0$ iff $x=0$ or
$$\frac{2x^2}{\sqrt{16-x^4}}=3$$
$$2x^2=3\sqrt{16-x^4}$$
$$4x^4=9(16-x^4)$$
$$13x^4=12^2$$
$$x=\pm2\frac{\sqrt{3}}{\sqrt[4]{13}}$$
Let $x_0=2\dfrac{\sqrt{3}}{\sqrt[4]{13}}$. Since $x$ appears only with even powers, sign is not important. And you have
$$f(0)=\frac83$$
$$f(x_0)=\frac{12}{\sqrt{13}}+\frac{2}{3}\sqrt{16-\frac{16\times 9}{13}}$$
$$=\frac{12}{\sqrt{13}}+\frac{2}{3}\sqrt{\frac{64}{13}}=\frac{12+\frac{16}{3}}{\sqrt{13}}=\frac{4\times13}{3\sqrt{13}}=\frac{4}{3}\sqrt{13}$$
And this is larger than $f(0)$ since
$$f(0)^2-f(x_0)^2=\frac{16\times4}{9}-\frac{16\times13\times3}{9}$$
Thus the max is found for $x=\pm x_0$ and
$$y^4=\frac{1}{9}\left(64-4x_0^4\right)=\frac{1}{9}\left(64-4\frac{16\times 9}{13}\right)=\frac{64}{9}\left(1-\frac{9}{13}\right)=\frac{64\times4}{9\times13}$$
Hence
$$y=\pm \frac{4}{\sqrt{3}\sqrt[4]{13}}$$

A: Since you tagged Lagrange Multipliers, I will use that method.
Allow that $F(x,y) = 4x^4+9y^4-64$ and $G(x,y)=x^2+y^2-C$, where $C$ is treated as a constant and is the maximum you wish to find.
We allow that $\nabla F(x,y) = \lambda \nabla G(x,y)$ and find two new equations:
$16x^3 = \lambda 2x$ and
$36y^3 = \lambda 2y$
$\implies x^4 = \frac{\lambda ^2}{64}$ and $y^4 = \frac{\lambda ^2}{324}$.
Plugging those into $F(x,y)$ we find that:
$$\lambda = 26.6256...$$
We now go back to our equations after applying the gradient and solve for $x_{max}$ and $y_{max}$. We get:
$x_{max}=1.8245...$ and $y_{max}=1.21622...$
Plugging this into $x^2+y^2$ we obtain the maximum, $4.80727$.

A: One more stab at the problem. Instead of working with $x$, let's work with $u = x^2$ as it makes the algebra slightly easier.
As $4x^4 + 9y^4 = 64$, we have $y^2 = \frac{1}{3}\sqrt{64-4u^2}$, taking only the positive square roots as $y^2 \geq 0$. Hence want to maximize
$$f(u) = x^2 + y^2 = u + y^2 = u + \frac{1}{3}\sqrt{64-4u^2}$$
Setting the first derivative equal to zero,
$$0 = \frac{df}{du} = 1 - \frac{4}{3}u \frac{1}{\sqrt{64-4u^2}}$$
$$\Longrightarrow  \  64 - 4u^2 = \frac{16}{9}u^2 \hspace{30 mm}$$
$$\Longrightarrow \ \ u^2 = \frac{9}{52}\cdot 64 \ \ \text{ i.e., } u = \frac{12}{\sqrt{13}} \hspace{10 mm}$$
(We take only the positive square root in the last step as $u = x^2 \geq 0$.)
Using the earlier expression for $y^2$, we find for $u = x^2 = \frac{12}{\sqrt{13}}$ that
$$y^2 = \frac{1}{3}\sqrt{64 - 4\cdot \frac{144}{13}} = \frac{16}{3\sqrt{13}}$$
Hence
$$x^2 + y^2 = \frac{12}{\sqrt{13}} + \frac{16}{3\sqrt{13}} = \frac{52}{3\sqrt{13}} = \frac{4}{3}\sqrt{13}$$
This is a maximum as there are other points satisfying the constraint for which $x^2 + y^2 < \frac{4}{3}\sqrt{13}$. For example, for $(x,y) = (2,0)$, $$x^2 + y^2 = 2^2 + 0^2 = 4 < \frac{4}{3}\sqrt{13} \ \text{ as } 16 < \frac{16}{9}\cdot 13$$


text:
Q: Removing the recurring dot using CSS Is it possible to remove the dot before each of these fields using CSS? I cannot seem to find the ability to do so. thanks!
http://www.inksharks.com/kbca-registration/

A: There's a background image added to each li element. You have to remove it by adding the following CSS
ul > li, .dark-icons ul > li {
    background-image: none;
}

A: you may try
.gform_body ul li{list-style:none;}
if above code does not work then
.gform_body ul li{list-style:none !important;}


text:
Q: How to calculate the Final Total sum and calculate percentages Below I have a query where I have the total 1st language spoken by students in each language
CTE
WITH Lang AS
(
    SELECT
        language,
        studentcount,
        SUM(Studentcount) AS total
    FROM
        (SELECT
             l.longtext AS language,
             COUNT(distinct s.studentnr) AS Studentcount
         FROM
             student s
         JOIN
             pupil p on p.id = s.pupilid
         JOIN
             pupillanguage pl on pl.personid = p.id
         JOIN
             language l on l.id = pl.languageid
         GROUP BY
             l.longtext
         ORDER BY
             Studentcount DESC
        ) t
    GROUP BY
        language, Studentcount
)

Query
SELECT initcap(language), Studentcount, total
FROM Lang

UNION ALL

SELECT cast(count(language) as varchar(6)) ||' Languages', null, null
FROM Lang

Now I have 1 major issue which is assigning a TOTAL SUM value of students. I need this so I can calculate the percentage of numbers of students / total students in a column. However obviously my total value is not giving me what I need.
Output
    languages   students    total
    ------------------------------
    French        734        734
    Afrikaans      93         93
    Greek         117        117
    German         55         55
    Armenian      160        160
    Malaysian       5          5
    Danish         15         15
    American        5          5
    Swedish        24         24
    Bulgarian     1043      1043

Expected output:
languages   students    Percentage
-----------------------------------
French        734          24,46
Afrikaans      93           3,12
Greek         117           3,9
German         55           1,83
Armenian      160           5,33
Malaysian       5           0,16
Danish         15           0,5
American        5           0,16
Swedish        24           0,8
Bulgarian     1043         34,76

How can I calculate the final total sum as a value to calculate the percentages

A: demo:db<>fiddle
You could use window functions (https://www.postgresql.org/docs/current/static/tutorial-window.html):
SELECT
    language,
    students,
    SUM(students) OVER () as total,
    students::decimal / SUM(students) OVER () * 100 as percentage
FROM
--- <YOUR QUERY>

The window function SUM(students) OVER () sums up all values of the students column because no limiting frame is given in the OVER clause
The ::decimal cast is necessary to get a float division (100 / 200 = 0.5) instead of an integer division (100 / 200 = 0).

A: you can try like below
with t1 as (
        SELECT l.longtext as language,
       count(distinct s.studentnr) as Studentcount
            FROM student s
                join pupil p on p.id = s.pupilid
                join pupillanguage pl on pl.personid = p.id
                join language l on l.id = pl.languageid
            group by l.longtext
            order by Studentcount desc
        ) select language,Studentcount, sum(Studentcount) over() as total,
      (Studentcount::float/sum(Studentcount) over())*100 as percentage
      from t1


text:
Q: Many named Model on TDB or SDB at jena I'm developing an application that uses the Jena.
I want to use many named Model on TDB or SDB.
However, DataSource Class is has been removed.
In order to do this, I would not without the Model, only use the Graph and DatasetGraph?

A: Use Dataset, the DataSource/Dataset split has been removed. Dataset now has the operations you need.


text:
Q: What is a proper use-case of `std::nullptr_t` template parameters? Today I came to know that C++ allows non-type template parameters of type std::nullptr_t:
template<std::nullptr_t N> struct A { };

template<std::nullptr_t N> void f() { }

For the life of me, I cannot come up with any sensible use-case for these. Can anyone please come up with a rationale for this?

A: I guess it's most useful in a setting like this:
template <typename T, T Value> struct Foo;

Foo<int, 10> x;
Foo<std::nullptr_t, nullptr> y;

No harm in that.
(Maybe std::integral_constant is an example of this.)

A: It seems this is allowed to avoid the need to special case template using a pointer type and a value for std::nullptr_t. That, the use case would look look something like this:
template <typename T, T Ptr>
struct pointer_object {
    static T get_pointer() { return Ptr; }
};

int int_ptr(0);

typedef pointer_object<int*, &int_ptr> int_ptr_t;
typedef pointer_object<std::nullptr_t, nullptr> null_ptr_t;

That is, pointer values can be template arguments and, thus, nullptr should be, too.


text:
Q: HBase shell shows error when listing tables hbase(main):001:0> list
...
ava:75)
        at org.jruby.internal.runtime.methods.InterpretedMethod.call(InterpretedMethod.java:147)
        at org.jruby.internal.runtime.methods.DefaultMethod.call(DefaultMethod.java:163)
        at org.jruby.runtime.callsite.CachingCallSite.cacheAndCall(CachingCallSite.java:292)
        at org.jruby.runtime.callsite.CachingCallSite.call(CachingCallSite.java:135)
        at usr.local.hbase.bin.$_dot_dot_.bin.hirb.block_2$RUBY$start(/usr/local/hbase/bin/../bin/hirb.rb:183)
        at usr$local$hbase$bin$$_dot_dot_$bin$hirb$block_2$RUBY$start.call(usr$local$hbase$bin$$_dot_dot_$bin$hirb$block_2$RUBY$start:65535)
        at org.jruby.runtime.CompiledBlock.yield(CompiledBlock.java:112)
        at org.jruby.runtime.CompiledBlock.yield(CompiledBlock.java:95)
        at org.jruby.runtime.Block.yield(Block.java:130)
        at org.jruby.RubyContinuation.enter(RubyContinuation.java:106)
        at org.jruby.RubyKernel.rbCatch(RubyKernel.java:1192)
        at org.jruby.RubyKernel$s$1$0$rbCatch.call(RubyKernel$s$1$0$rbCatch.gen:65535)
        at org.jruby.runtime.callsite.CachingCallSite.cacheAndCall(CachingCallSite.java:322)
        at org.jruby.runtime.callsite.CachingCallSite.callBlock(CachingCallSite.java:178)
        at org.jruby.runtime.callsite.CachingCallSite.callIter(CachingCallSite.java:187)
        at usr.local.hbase.bin.$_dot_dot_.bin.hirb.method__5$RUBY$start(/usr/local/hbase/bin/../bin/hirb.rb:182)
        at usr$local$hbase$bin$$_dot_dot_$bin$hirb$method__5$RUBY$start.call(usr$local$hbase$bin$$_dot_dot_$bin$hirb$method__5$RUBY$start:65535)
        at org.jruby.internal.runtime.methods.DynamicMethod.call(DynamicMethod.java:203)
        at org.jruby.internal.runtime.methods.CompiledMethod.call(CompiledMethod.java:255)
        at org.jruby.runtime.callsite.CachingCallSite.cacheAndCall(CachingCallSite.java:292)
        at org.jruby.runtime.callsite.CachingCallSite.call(CachingCallSite.java:135)
        at usr.local.hbase.bin.$_dot_dot_.bin.hirb.file(/usr/local/hbase/bin/../bin/hirb.rb:188)
        at usr.local.hbase.bin.$_dot_dot_.bin.hirb.load(/usr/local/hbase/bin/../bin/hirb.rb)
        at org.jruby.Ruby.runScript(Ruby.java:693)
        at org.jruby.Ruby.runScript(Ruby.java:686)
        at org.jruby.Ruby.runNormally(Ruby.java:593)
        at org.jruby.Ruby.runFromMain(Ruby.java:442)
        at org.jruby.Main.doRunFromMain(Main.java:321)
        at org.jruby.Main.internalRun(Main.java:241)
        at org.jruby.Main.run(Main.java:207)
        at org.jruby.Main.run(Main.java:191)
        at org.jruby.Main.main(Main.java:171)
ERROR: org.apache.hadoop.hbase.MasterNotRunningException: Retried 7 times

A: I recently got this same error.
Steps to resolve this (In my case this worked),

*

*start hbase if not started using ./start-hbase.sh

*Again, try to start hbase using ./start-hbase.sh and this time it would say "Master is already ruuning at XXXX process id"

*Copy the process id of master using ps -a command from terminal, kill the process.

*stop hbase using command ./stop-hbase.sh

*Now again start hbase and check the connection using "status" command from hbase shell.

A: ERROR: org.apache.hadoop.hbase.MasterNotRunningException: Retried 7 times
It clearly shows that your HMaster is not running. Make sure you have configured HBase properly with all the necessary properties. Are you able to see anything at HBase's WebUI(hmaster:60010)? See the HMaster logs for more help. You can find logs inside ${HBASE_HOME}/logs if not changed.


text:
Q: Camera following player is jerky and has bad visual effect I am a beginner and have an issue with camera following the player which is jerky. I have a player that moves only in upward direction on tapping, and other enemies that move in x direction. but when the player start jumping the camera starts jerky movements (specially near enemies) and also has a bad effect on enemies' movements too. Below is my code for CameraFollow.`
public class CameraFollow : MonoBehaviour {
[SerializeField]
private float yMin;
[SerializeField]
private float yMax;
[SerializeField]
private float xMin;
[SerializeField]
private float xMax;
private Transform target;

void Start () {
    target = GameObject.Find("Player").transform;
    //player = GameObject.FindGameObjectWithTag("Player");
}

void LateUpdate () {
    transform.position = new Vector3 (Mathf.Clamp(target.position.x, xMin, xMax), Mathf.Clamp(target.position.y, yMin, yMax), transform.position.z);
    if (Input.GetKeyDown(KeyCode.Escape)){
        Application.Quit ();
    }
}

A: The reason it jerks is because you're setting the transform of the camera directly, rather than (for example) smoothly lerping it.
I suggest using Vector3.Lerp.
Example, instead of:
transform.position = new Vector3 (Mathf.Clamp(target.position.x, xMin, xMax), Mathf.Clamp(target.position.y, yMin, yMax), transform.position.z);
try something like these lines:
Vector3 targetPos = new Vector3 (
    Mathf.Clamp(target.position.x, xMin, xMax),
    Mathf.Clamp(target.position.y, yMin, yMax),
    transform.position.z
    );

transform.position = Vector3.Lerp(transform.position, targetPos, 0.5f);

I hope that helps!


text:
Q: Using JayData to filter Header Detail Table - Inner Join SQL, oData Hello Am kinda new and using JayData and oData so please forgive my ignorance.
This is my object structure :
$data.Entity.extend('PlannerModel.vMasterPlanner', {
    'Sequence_Number': { key:true,type:'Edm.Int32',nullable:false,required:true },
    'Scenario_Name': { type:'Edm.String',nullable:true,maxLength:250 },
    'Activity_ID': { type:'Edm.String',nullable:false,required:true,maxLength:250 },
    'Activity_Description': { type:'Edm.String',nullable:true,maxLength:500 },
    'Object_ID': { type:'Edm.String',nullable:true,maxLength:250 },
    'Object_Description': { type:'Edm.String',nullable:true,maxLength:400 },
    'Operation_Code': { type:'Edm.String',nullable:false,required:true,maxLength:250 },
    'Operation_Description': { type:'Edm.String',nullable:true,maxLength:50 },
    'Crew_ID': { type:'Edm.String',nullable:true,maxLength:250 },
    'Crew_Name': { type:'Edm.String',nullable:true,maxLength:50 },
    'Period': { type:'Edm.Int32',nullable:true },
    'vActivity': { type:'PlannerModel.vActivity',required:true,inverseProperty:'vMasterPlanners' }   });

 $data.Entity.extend('PlannerModel.vActivity', {
    'Activity_ID': { key:true,type:'Edm.String',nullable:false,computed:true },
    'Activity_Name': { type:'Edm.String',nullable:false,required:true },
    'vMasterPlanners': { type:'Array',elementType:'PlannerModel.vMasterPlanner',inverseProperty:'vActivity' }   });

$data.EntityContext.extend('PlannerServiceLibrary.PlannerEntities', {
    ProgressDetails: { type: $data.EntitySet, elementType: PlannerModel.ProgressDetails },
      ProgressHeaders: { type: $data.EntitySet, elementType: PlannerModel.ProgressHeader },
      vCrews: { type: $data.EntitySet, elementType: PlannerModel.vCrew },
      vPeriods: { type: $data.EntitySet, elementType: PlannerModel.vPeriod },
      vOperations: { type: $data.EntitySet, elementType: PlannerModel.vOperation },
      vActivities: { type: $data.EntitySet, elementType: PlannerModel.vActivity },
      vMasterPlanners: { type: $data.EntitySet, elementType: PlannerModel.vMasterPlanner }   });

Just a little explanation :
 Table Master planner is a detail table and Table activity is the header table
I need to select all the activities from the activity table (header) where the crew ID which is found in the detail table for example = 2
how can i do that using oData and JayData
am currently using
provider.vActivities.filter(function (ac) {
return ac.vMasterPlanners.Crew_ID == "FM2_F/W" })
               .toArray(function (e) {
                   console.log(e);
               });

and this is the error Unknown expression type to handle: EntitySetExpression
 localhost/mobile-web/htdocs/assets/jayData/jaydata.js
Line 89
Please help anyone !!
Thank You !

A: You need 'some' or 'every' operator, see this http://jaydata.org/blog/using-some-and-every-with-jaydata-odata-provider

A: It looks like a known issue I have added it in to github http://github.com/jaydata/jaydata/issues/70


text:
Q: Creating a cronjob from a makefile? I am trying to let my makefile setup a cronjob for my application. Unfortunately it appears to not be working as the $CRONENTRY variable seems to be empty. What am I doing wrong here?
addcron:
    CRONENTRY="*/2 * * * * /usr/bin/node cronapp.js >> logfile.log"
    crontab -l | { cat; echo ${CRONENTRY}; } | crontab -

A: Each command in a rule executes in its own subshell; variables do not survive from one command to the next. So if you want to use a variable this way, you have to string the commands together.
addcron:
    CRONENTRY="whatever" ; \
  do_something_with $(CRONENTRY)

A: What about
addcron:
    CRONENTRY=
    { crontab -l; echo "*/2 * * * * /usr/bin/node cronapp.js >> logfile.log" } | crontab -

*

*there you have one less pipe element...


text:
Q: How to pass class instances to WndProc in C# How do i pass an instance of an object which is in my main form to WndProc method
For ex:
I have a ComboBox object - objCombo. And i have to capture a certain window message before the system draws the drop down list box.
One way to do this I can have a custom combobox which derives from the ComboBox
public class CustomComboBox : ComboBox
{
   //... some initialization code goes here

   protected override void WndProc(ref Message m)
   {
        if (m.Msg == WM_CTLCOLORLISTBOX)
        {
          // capture the message and do some work.
          //here i can get the reference to the CustomComboBox by using
          //this keyword.
        }
   }

}

However, I want to know is there a way where in I can do this without having go through the process of creating the custom combobox and do exactly the same. i.e. capturing the Windows message inside my Form class using the reference to my combobox instance. ?
i.e.
public class MyForm : Form
{
   //... some initialization code goes here including the InitializeComponent
   // for form objects and other controls

   private void CaptureComboWndProc(ref Message m)
   {
     // this method will capture only the windows message specific to objCombo ??
   }

}

I hope I am being clear with the question
Thanks and Cheers
VATSA

A: Better way is to create a descendant of combobox. Which is very clear way of doing it.
However you can find the control from message, here's how you go.
Use Control.FromHandle to find the control to which message is posted.
   protected override void WndProc(ref Message m)
   {
        if (m.Msg == WM_CTLCOLORLISTBOX)
        {
            if(Control.FromHandle(m.HWnd) == this.objCombo)
            {
                CaptureComboWndProc(ref m);
            }
        }
   }

   private void CaptureComboWndProc(ref Message m)
   {

   }

and... Finally I'd like to say don't do this please.

A: It is possible, the generic technique is called "sub-classing the window" in Windows GUI programming.  It works by replacing the window procedure of a window.  This is already done for every native window control you find back in the toolbox (ListView, ComboBox, etc), that's how they raise events.  And can be done repeatedly.  No need to pinvoke, the NativeWindow class supports it with its AssignHandle() method.
You have to derive your own class from NativeWindow and override the WndProc() method to implement custom message handling.  Use, say, the form's Load event to attach it.  Roughly:
public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
    }

    private class ComboHooker : NativeWindow {
        protected override void WndProc(ref Message m) {
            if (m.Msg == 0x134) {
                // etc...
            }
            else {
                // Stop sub-classing on WM_NCDESTROY
                if (m.Msg == 0x82) this.ReleaseHandle();
                base.WndProc(ref m);
            }
        }
    }

    private void hookComboBoxes(Control.ControlCollection ctls) {
        foreach (Control ctl in ctls) {
            if (ctl.GetType() == typeof(ComboBox)) {
                new ComboHooker().AssignHandle(ctl.Handle);
            }
            hookComboBoxes(ctl.Controls);
        }
    }

    protected override void OnLoad(EventArgs e) {
        hookComboBoxes(this.Controls);
        base.OnLoad(e);
    }
}


text:
Q: Android http client upload not working in some server I m using the following code to upload file to a server. It works quite well in localhost and bluehost. But it is not working in some hosting like(Go Daddy). Would anybody explain why???
   data = IOUtils.toByteArray(inputStream);
   HttpClient httpClient = new DefaultHttpClient();
   HttpPost httpPost = new HttpPost(upload_url);
   InputStreamBody inputStreamBody = new InputStreamBody(new ByteArrayInputStream(data), fileName);
   CustomMultiPartEntity multipartEntity = new CustomMultiPartEntity();
   multipartEntity.setUploadProgressListener(this);
   multipartEntity.addPart("pdf", inputStreamBody);
   multipartEntity.addPart("title", new StringBody(title));
   multipartEntity.addPart("subject", new StringBody(subject));
   multipartEntity.addPart("college", new StringBody(college));
   multipartEntity.addPart("stream", new StringBody(stream));
   multipartEntity.addPart("branch", new StringBody(branch));
   multipartEntity.addPart("userID", new  StringBody(String.valueOf(userid)));
   httpPost.setEntity(multipartEntity);
   HttpResponse httpResponse = httpClient.execute(httpPost);

I performed a lot of testing. When I retrieve the values via $_POST[] in the server, the value is null. HttpUrlConnection works in all server. But we have to write everything ourselves. I mean why to write so much code from scratch for a simple function like upload... Is there no library with simple callbacks.?

A: HttpClient, HttpPost.. are deprecated in API 22, So you should try to use HttpURLConnection instead.


text:
Q: what is the scope of Viewbag in mvc3 and how do we maintain state in MVC
*

*what is the scope of Viewbag in mvc3 is it only available on the page we are rendering through my action method.

*How do we maintain information across the  page in MVC. Suppose i Create new employee and and when I move to next page I want that employee information.

*How do we maintain state in MVC.

A: *

*the view bag is part of the httpcontext. it's primarily set in the controller action and  read in the view, but it can be accessed from just about anywhere in the mvc framework within an http request/response.

*the web does not have state, like you would in a rich client app. To maintain values from page to page (or more appropriately, request to request) you can use cookies, session, query string, the request body (think post/put requests).

*same as #2.

A: *

*ViewBag is a dynamic expression and it is available for all the pages. The data in ViewBag is the thing that changes as per we have assigned. If we are assigning ViewBag.items=itemlist; for a View, then it will be constant for that View. We can put as many data into ViewBag per page as we want like , for a single page, we can have
ViewBag.items=itemlist;
ViewBag.table=usertable;

*You can maintain the information across the pages in MVC by passing the data as a parameter to the method which rendres the View on which we want to maintain the information as below:
public ActionResult CreateEmployee(EmployeeModel emp)
{
     //Add Employee to db
     ViewBag.employee=emp;
     RedirectToAction("MethodToCall","Controller");
}

Thus the next page can have the employee information contained in the ViewBag
Alternatively, you can use ViewData as well.
3] State can be maintained using sessions, cookies etc


text:
Q: Running FFMPEG in Android
Possible Duplicate:
ffmpeg for a android (using tutorial: "ffmpeg and Android.mk")

I have tried several things running FFMPEG in android, searched around the whole net,No fruitful or direct solutions available. Refereed this and related was very helpful though.
Moreover currently I am able to build the FFMPEG in Ubuntu 12. Created all the .SO binary everything.
My question is, how do I change the ffmeg.c file which will enable me to pass ffmpeg commands ?
According to this by following steps this is possible.
With the design above, the change for ffmpeg.c is simple.
Change the main(int argc, char **argv) function prototype to a java JNI interface prototype that Android java code can call.
Change the output to stdout to the text files we created.
Comment out a few lines that cause the compilation error.

But I'm unable to change the main and how it would be.
Please help me on this. If somebody have already achieved this thing.


text:
Q: Generate .h and .cpp from .ui file Suppose I have the file about.ui.
How can I make the "about.h" and the "about.cpp" from my .ui file?  I have to create a .moc file too?
How can I compile this after the creaton to see if all ocurred correctly?

A: If automatic generation does not work (like in my case) you can use uic to generate the header file manually. uic file.ui > file.h

A: You don't.
The about.ui  generates a ui_about.h which you include in your own about.h
You then create you own class deriving from this class
class about :   public QDialog, public Ui::about
{
    Q_OBJECT;
....
}

A: Short answer:
In QtCreator there are two ways of create a form from windows assistant:
-  Qt Designer Form Class
-  QtDesigner Form
you must create a new "Qt Designer Form Class" instead of "Qt Designer Form", because you choose "Qt Designer Form"  qt creator doesn't create the .h and .cpp from .ui file:
Long Answer:
When you create "QTCreator Form" only create .ui  file this is useful if you already have an existing class for the UI business logic and you want rebuilt user interface but keep business logic, you can  call buttom or components with same name and interchange  ui.

A: QMake (actually uic) will automatically generate a ui_about.h file that you can use to make about.cpp (just make sure to get the .pro file right). Here's a tutorial
You might want to use the lastest Qt (4.6) too btw.

A: IN VS2008 Follow this step
Go to Form Files->Add->Class->Qt4Classes->Q4GuiClass->Add , then
Fill the class name and click on Finish.

A: if you are using qt creator in windows, just right click your project and click execute qmake, then it will generate a ui_xxx.h and you can add #include ui_xxx.h in your file.


text:
Q: pdf generation using html-pdf npm package , deploy on AWS as a GET api I am able to generate a pdf using html-pdf in nodejs locally on my mac. The minute I deploy the my GET api using serverless on AWS everything fails. The pdf does not get generated and I get 400 bad request and message as html-pdf: Received the exit code '127'\n/var/task/node_modules/phantomjs-prebuilt/lib/phantom/bin/phantomjs: error while loading shared libraries: libfontconfig.so.1: cannot open shared object file: No such file or directory\n
I changed version of the html-pdf package , tried installing fontmanager but nothing helped.
//pdf generation class
{
.....
const pdfSettings = {
                "border": '1cm',
                "header": {
                    "height": "15mm"
                }
            };

            const PDFBuffer = new Promise((resolve, reject) => {
                pdf.create(pdfContent, pdfSettings).toBuffer(
                    (err, buffer) => {
                        err ? reject(err) : resolve(buffer);
                    });
            });

            const buffer = await PDFBuffer;
            return actions.downloadPDF(contactId, buffer);
}

//function which returns pdf in binary to api gateway
downloadPDF(pdfName, pdfBuffer) {

    let responseObj = {
      statusCode: 200,
      isBase64Encoded: true,
      headers: {
        'Content-type': 'application/pdf',
        'accept-ranges': 'bytes',
        'Content-Disposition': 'attachment; filename=' + pdfName + '.pdf'
      },
      body: pdfBuffer && JSON.stringify(pdfBuffer.toString('base64'))
    }
    return responseObj;
  }

I should be able to generate pdf using the GET api in AWS. Please let me know any valuable suggestion that could help me with this issue. Thanks in advance

A: faced the same issue with html-pdf on aws ubuntu and here is what I did.
test html-pdf package using the example:
root@APP-AP-1A-01:/home/user01/server-a7# node node_modules/html-pdf/bin/index.js node_modules/html-pdf/examples/businesscard/businesscard.html /tmp/test-prod.pdf
/home/user01/server-a7/node_modules/html-pdf/bin/index.js:30
    if (err) throw err
             ^

Error: html-pdf: Received the exit code '127'
/home/user01/server-a7/node_modules/phantomjs-prebuilt/lib/phantom/bin/phantomjs: error while loading shared libraries: libfontconfig.so.1: cannot open shared object file: No such file or directory

    at ChildProcess.respond (/home/user01/server-a7/node_modules/html-pdf/lib/pdf.js:121:31)
    at ChildProcess.emit (events.js:210:5)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:272:12)

^  this error was seen on Aws running Ubuntu (4.4.0-1072-aws)
and it was due to missing library phantomjs is dependent on; the npm -i did not install/ update it quite well on the server.
Here are the steps:

*

*ldd - print shared object dependencies (note that it flagged, libfontconfig.so.1 => not found)

*install the missing library (apt-get install fontconfig)

*check the dependencies again using ldd

*run the example and this time it created the pdf from html

run as root user or use sudo :-
root@APP-AP-1A-01:/home/user01/server-a7# ldd /home/user01/server-a7/node_modules/phantomjs-prebuilt/lib/phantom/bin/phantomjs
        linux-vdso.so.1 =>  (0x00007ffea155d000)
        libz.so.1 => /lib/x86_64-linux-gnu/libz.so.1 (0x00007fd639645000)
        libfontconfig.so.1 => not found
        libfreetype.so.6 => /usr/lib/x86_64-linux-gnu/libfreetype.so.6 (0x00007fd63939b000)
        libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007fd639197000)
        librt.so.1 => /lib/x86_64-linux-gnu/librt.so.1 (0x00007fd638f8f000)
        libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007fd638d72000)
        libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007fd6389f0000)
        libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007fd6386e7000)
        libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007fd6384d1000)
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fd638107000)
        /lib64/ld-linux-x86-64.so.2 (0x00007fd63985f000)
        libpng12.so.0 => /lib/x86_64-linux-gnu/libpng12.so.0 (0x00007fd637ee2000)

root@APP-AP-1A-01:/home/user01/server-a7# ls -l /usr/lib/x86_64-linux-gnu/libfontconfig.so.1
ls: cannot access '/usr/lib/x86_64-linux-gnu/libfontconfig.so.1': No such file or directory

root@APP-AP-1A-01:/home/user01/server-a7# apt-get install fontconfig
Reading package lists... Done
:
The following additional packages will be installed:
  fontconfig-config fonts-dejavu-core libfontconfig1
The following NEW packages will be installed:
  fontconfig fontconfig-config fonts-dejavu-core libfontconfig1
:
Do you want to continue? [Y/n] y
Get:1 http://ap-south-1.ec2.archive.ubuntu.com/ubuntu xenial/main amd64 fonts-dejavu-core all 2.35-1 [1,039 kB]
Get:2 http://ap-south-1.ec2.archive.ubuntu.com/ubuntu xenial-updates/main amd64 fontconfig-config all 2.11.94-0ubuntu1.1 [49.9 kB]
Get:3 http://ap-south-1.ec2.archive.ubuntu.com/ubuntu xenial-updates/main amd64 libfontconfig1 amd64 2.11.94-0ubuntu1.1 [131 kB]
Get:4 http://ap-south-1.ec2.archive.ubuntu.com/ubuntu xenial-updates/main amd64 fontconfig amd64 2.11.94-0ubuntu1.1 [178 kB]
Fetched 1,398 kB in 1s (928 kB/s)
:
:
Regenerating fonts cache... done.
Processing triggers for libc-bin (2.23-0ubuntu11.2) ...

root@APP-AP-1A-01:/home/user01/server-a7# ldd /home/user01/server-a7/node_modules/phantomjs-prebuilt/lib/phantom/bin/phantomjs
        linux-vdso.so.1 =>  (0x00007ffcdf49c000)
        libz.so.1 => /lib/x86_64-linux-gnu/libz.so.1 (0x00007f65a4723000)
        libfontconfig.so.1 => /usr/lib/x86_64-linux-gnu/libfontconfig.so.1 (0x00007f65a44e0000)
        libfreetype.so.6 => /usr/lib/x86_64-linux-gnu/libfreetype.so.6 (0x00007f65a4236000)
        libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f65a4032000)
        librt.so.1 => /lib/x86_64-linux-gnu/librt.so.1 (0x00007f65a3e2a000)
        libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f65a3c0d000)
        libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f65a388b000)
        libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f65a3582000)
        libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f65a336c000)
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f65a2fa2000)
        /lib64/ld-linux-x86-64.so.2 (0x00007f65a493d000)
        libexpat.so.1 => /lib/x86_64-linux-gnu/libexpat.so.1 (0x00007f65a2d79000)
        libpng12.so.0 => /lib/x86_64-linux-gnu/libpng12.so.0 (0x00007f65a2b54000)

root@APP-AP-1A-01:/home/user01/server-a7# node node_modules/html-pdf/bin/index.js node_modules/html-pdf/examples/businesscard/businesscard.html /tmp/test-prod.pdf

root@APP-AP-1A-01:/home/user01/server-a7# ls -lrt /tmp/test-prod.pdf
-rw-r--r-- 1 root root 11250 Jul 10 10:05 /tmp/test-prod.pdf

created the pdf in /tmp/test-prod.pdf

A: I was able to reach a better solution by using puppeteer library. Reasons for choosing a different library

*html-pdf is deprecated

*puppeteer has much better options

*puppeteer has async/await feature
Although to make this work in AWS with serverless & serverless-plugin-optimize , I did face many challenges. Note out the following points while implementing this kind of similar scenario
For API gateway to send any binary file(pdf / jpeg / jpg) as response

*Binary Media Types should be set to */* in API Gateway resource Settings options , if going through serverless under provider in serverless.yaml add
 apiGateway:
    binaryMediaTypes:
      - */*

*if by any chance you are using serverless-plugin-optimize to reduce lambda size , use "external" option for this package chrome-aws-lambda , ref link https://www.npmjs.com/package/serverless-plugin-optimize


text:
Q: RecyclerView still displays images after removing them I'm facing some problems with removing positions (mainly images) from RecyclerView. I store images in app's memory and have a reference in DB to them (as a path).
Additionally, I use glide to load images from memory into images View. I tried to implement deleting a pics:

*

*I removed a database rows (using ContentREsolver & ContentProvider)

*I removed the image from the memory and the list containing pics

Information (list of MyFunnyImg objects)
Everything looks fine at first - the image disappears from list but after reentering this fragment (containing recyclerView) the image suddenly appears...
I tried to find something in the Internet but nothing worked, here is my code ( in 'developing' state):
deleting method from ContentProvider:
@Override
public int delete(@NonNull Uri uri, @Nullable String where, @Nullable String[] whereArgs) {
    int numbersOfRowsDeleted=0;
    switch (uriMatcher.match(uri)) {
        case ONE_PIC:
            numbersOfRowsDeleted=dbHelper.getWritableDatabase().delete(DatabaseDescription.Picture.TABLE_NAME_,
                   DatabaseDescription.Picture._ID+"="+uri.getLastPathSegment(),whereArgs);

            break;
        default:
            unsupportedOperation();
    }
    if(numbersOfRowsDeleted>0){
        getContext().getContentResolver().notifyChange(uri,null);
    }
    return numbersOfRowsDeleted;
}

methods from RecyclerViewAdapter for deleting images and rows from DB
private boolean onSingleMenuItemClick(MenuItem item,ImageView imageView,int position){
    int id=item.getItemId();
    switch (id){
        case R.id.share:
           // instructions
            break;
        case R.id.more_info:
           // instructions
            break;
        case R.id.delete_img:
            deleteImg(position);
            break;
        default:
            //instructions
    }
    return true;
}

private void deleteImg(int position){
    removeImgFile(argsToShow.get(position).getFileName());
    deleteFromDatabase(position);
    argsToShow.remove(position);
    //notifyDataSetChanged();
   // notifyItemRemoved(position);

    notifyItemRangeChanged(position,argsToShow.size());
}`private void removeImgFile(String fName){

    String root=null;
    try {
        root = activity.getExternalFilesDir(Environment.DIRECTORY_PICTURES).toString();
    }catch(NullPointerException ex){
        ex.printStackTrace();
        Log.e("Error","NullPointerException while deleting BitMap");
    }

    File dir=new File(root+"/saved_images");

    File file=new File(dir,fName);

}

private void deleteFromDatabase(int position){

    // we create URI referrimng to whole table
    Uri uri= DatabaseDescription.Picture.CONTENT_URI;

    String id=String.valueOf(position);

    uri=uri.buildUpon().appendPath(id).build();

    ContentResolver contentResolver=activity.getContentResolver();

   int count= contentResolver.delete(uri,null,null);
   ViewUtils.showToast(activity,"Deleted: "+count+" rows");
}


text:
Q: Too many connections I am getting Too many connections error. If I increase max_connections number it doesn't come but it will eventually come.I am creating new session in each method but also closing it.
This is sample method:
      public List<ActivityLog> loadRecords(Integer stageId) {
      Session session = createSession();
      List<ActivityLog> resultsSelect = null;
      try {
        String hqlSelect = "FROM ActivityLog C WHERE stage_id=:stageId and         status=:status";
        Query querySelect = session.createQuery(hqlSelect);
        querySelect.setParameter("stageId", stageId);
        querySelect.setParameter("status", "Select");
        resultsSelect = querySelect.list();
    } finally {
        session.close();
    }
    return resultsSelect;

}

This is my connection factory:
public static SessionFactory createSessionFactory(Configuration configuration) {
    serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    return sessionFactory;
}

public static Session createSession() {
    Configuration cfg = new Configuration();
    cfg.configure("hibernate.cfg.xml");
    SessionFactory factory = createSessionFactory(cfg);
    Session session = factory.openSession();
    return session;
}

Here is the error I am getting:
enter image description here
Please help me.
Error:

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Data source rejected establishment of connection,  message from server: "Too many connections"


text:
Q: What does mean for sub_ids in grouped_slice(ids) in Tryton? I want to understand an instruction that I have seen a lot. What does for sub_ids in grouped_slice(ids) mean in Tryton?
Here is a fragment of a method where such instruction is used:
@classmethod
def get_duration(cls, works, name):
    pool = Pool()
    Line = pool.get('timesheet.line')
    transaction = Transaction()
    cursor = transaction.connection.cursor()
    context = transaction.context

    table_w = cls.__table__()
    line = Line.__table__()
    ids = [w.id for w in works]
    durations = dict.fromkeys(ids, None)
    where = Literal(True)
    if context.get('from_date'):
        where &= line.date >= context['from_date']
    if context.get('to_date'):
        where &= line.date <= context['to_date']
    if context.get('employees'):
        where &= line.employee.in_(context['employees'])

    query_table = table_w.join(line, 'LEFT',
        condition=line.work == table_w.id)

    for sub_ids in grouped_slice(ids):
        red_sql = reduce_ids(table_w.id, sub_ids)
        cursor.execute(*query_table.select(table_w.id, Sum(line.duration),
                where=red_sql & where,
                group_by=table_w.id))
        for work_id, duration in cursor:
            # SQLite uses float for SUM
            if duration and not isinstance(duration, datetime.timedelta):
                duration = datetime.timedelta(seconds=duration)
            durations[work_id] = duration
    return durations

A: grouped_slice is a function we use in tryton to read a list of objects in several subs sets (the default number depends on the database backend. For example the value is 2000 in the PostgreSQL backend).
This is used to limit the number of parameters that we pass to the database because this may cause some issues when the number of input records is bigger than the max number of parameters accepted by the sql driver.
Here is a simple example which provides a visual representation of how everything works:
>>> from trytond.tools import grouped_slice
>>> ids = list(range(0, 30))
>>> for i, sub_ids in enumerate(grouped_slice(ids, count=10)):
...     print("Loop", i, ','.join(map(str, sub_ids)))
...
Loop 0 0,1,2,3,4,5,6,7,8,9
Loop 1 10,11,12,13,14,15,16,17,18,19
Loop 2 20,21,22,23,24,25,26,27,28,29

As you see we have a list of 30 ids, which are processed in sets of 10 (as I used 10 as count argument).