text:
Q: How to do good benchmarking of complex functions? I am about to embark in very detailed benchmarking of a set of complex functions in C. This is "science level" detail. I'm wondering, what would be the best way to do serious benchmarking? I was thinking about running them, say, 10 times each, averaging the timing results and give the standard dev, for instance, just using <time.h>. What would you guys do to obtain good benchmarks?

A: Reporting an average and standard deviation gives a good description of a distribution when the distribution in question is approximately normal.  However, this is rarely true of computational performance measurements.  Instead, performance measurements tend to more closely resemble a poisson distribution.  This makes sense, because not many random events on a computer will cause a program to go faster; essentially all of the measurement noise is in how many random events occur that cause it to slow down.  (A normal distribution, by contrast, makes no intuitive sense at all; it would require the belief that a program has a non-zero probability of finishing in negative time).
In light of this, I find it most useful to report the minimum time over many runs of a program, rather than the average; the noise in the distribution is typically noise of the measuring system, rather than meaningful information about the algorithm.  For complex algorithms that have early out conditions, and other shortcuts, you need to be a little more careful, but the minimum of many runs where each run handles a representative balance of inputs usually works well.
"10 times each" sounds like very few iterations to me.  I generally do something on the order of thousands (or more, depending on the function/system) of runs unless that's completely infeasible.  At a bare minimum, you need to make sure that you run the timing for sufficiently long as to shake out any dependence on system state, some of which may change at fairly large time granularity.
The other thing you should be aware of is that essentially every system has a platform-specific timer available that is much more accurate than what is available <time.h>.  Find out what it is on your target platform[s] and use it instead.

A: I am assuming you are looking at benchmarking pure Algorithmic computation in your program and there is no user input or output which can take unpredictable time.
Now for purely number crunching programs, your results could vary based on the time your program actually runs which will be impacted by other ongoing activities in the system. There could be other factor which you may choose to ignore depending upon level of accuracy desired i.e. impact due to cache miss, different access time through the memory hierarchy"
One of the methods is as you suggested calculation average over a number of runs.
Or you could try to look at the assembly code and see the instructions generated. And then based on the processor get the cycle count for these instructions. This method may not be practical depending on the amount of code you are looking to benchmark. If you are particular about memory hierarchy impact then you may want to control execution environment very carefully i.e. where program is loaded, where its data is loaded etc. But as I mentioned depending on the accuracy desired, you may absorb the variation caused due to memory hierarchy in you statistical variation" .
You may need to carefully design the test input for you functions to ensure the path coverage and may choose to publish statistics of performance as a function of test input. This will show how function behaves across range of inputs


text:
Q: Displaying trailing zeros except when a whole number Is there a way (in .NET) of removing trailing zeros from a number when using .ToString("..."), but to display to 2 decimal places if the number is not a whole number:

*

*(12345.00).ToString(...) should display as 12345

*(12345.10).ToString(...) should display as 12345.10

*(12345.12).ToString(...) should display as 12345.12

Is there 1 number format string that will work in all these scenarios?
.ToString("#.##") nearly works but doesn't show the trailing 0 for scenario 2...
Also, other cultures aren't an issue, i just want a decimal point (not a comma etc.)

A: Something along these lines?
            if (number % 1 == 0)
                Console.WriteLine(string.Format("{0:0}", number));
            else
                Console.WriteLine(string.Format("{0:0.00}", number));

EDIT
There is a little bug in this code though:) 1.001 will be printed as "1.00"... this may not be what you want, if you need to print 1.001 as "1" you'll need to change the if(...) test to check for a finite tolerance. As this question is more about the formatting I will leave the answer unchanged but in production code you might want to consider this kind of issue.

A: Dirty way:
string.Format("{0:0.00}", number).Replace(".00","")

A: Not in one format but it fits in one line:
double a = 1.0;
string format = string.Format((a == (int)a) ? "{0:0}" : "{0:0.00}", a);

A: I can't say I've come across a single mask that will do that. I would use
string output = (value % 1 > 0) ? String.Format("{0:0.00}", value) : String.Format("{0:0.##}", value);

A: You could write an extension method like this to do the formatting for you:
public static string FormatNumberString(this double input)
    {
        int temp;
        string inputString = input.ToString();
        return Int32.TryParse(inputString, out temp) ? inputString : input.ToString("0.00");
    }

A: If you were looking to do this in ASP MVC Razor then you could try this
@string.Format(item.DecimalNumber % 1 == 0 ? "{0:0}" : "{0:0.00}", item.DecimalNumber)

This will behave like so:
Value: 2.5 --> Display: 2.50
Value: 5 --> Display: 5
Value: 2.45 --> Display: 2.45

A: I guess you could do your very own method to produce that display, since it's conditional to whether or not it is an integer.
public static class Extensions
{
    public static string ToCustomString(this decimal d)
    {
        int i = (int)d;
        if (i == d)
            return i.ToString();

        return d.ToString("#.00");
    }
}

A: If you want to use it to display currency, you can use following
float fVal = 1234.20f;
String strVal = fVal.Tostring("c");

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I create inhomogen background with css? I want to create some kind of texture for the background of my HTML text. Can I do something like that in css?

A: Check this out:
With CSS 3 you can do something like this.
http://lea.verou.me/css3patterns/#
Example usage:
<!DOCTYPE html>
<html>
<head>
    <title>Page Title</title>

    <style>
        body {
            background:
            radial-gradient(hsl(0, 100%, 27%) 4%, hsl(0, 100%, 18%) 9%, hsla(0, 100%, 20%, 0) 9%) 0 0,
            radial-gradient(hsl(0, 100%, 27%) 4%, hsl(0, 100%, 18%) 8%, hsla(0, 100%, 20%, 0) 10%) 50px 50px,
            radial-gradient(hsla(0, 100%, 30%, 0.8) 20%, hsla(0, 100%, 20%, 0)) 50px 0,
            radial-gradient(hsla(0, 100%, 30%, 0.8) 20%, hsla(0, 100%, 20%, 0)) 0 50px,
            radial-gradient(hsla(0, 100%, 20%, 1) 35%, hsla(0, 100%, 20%, 0) 60%) 50px 0,
            radial-gradient(hsla(0, 100%, 20%, 1) 35%, hsla(0, 100%, 20%, 0) 60%) 100px 50px,
            radial-gradient(hsla(0, 100%, 15%, 0.7), hsla(0, 100%, 20%, 0)) 0 0,
            radial-gradient(hsla(0, 100%, 15%, 0.7), hsla(0, 100%, 20%, 0)) 50px 50px,
            linear-gradient(45deg, hsla(0, 100%, 20%, 0) 49%, hsla(0, 100%, 0%, 1) 50%, hsla(0, 100%, 20%, 0) 70%) 0 0,
            linear-gradient(-45deg, hsla(0, 100%, 20%, 0) 49%, hsla(0, 100%, 0%, 1) 50%, hsla(0, 100%, 20%, 0) 70%) 0 0;
            background-color: #300;
            background-size: 100px 100px;
        }

    </style>
</head>
<body>

</body>
</html>


text:
Q: long to wide data restructure in data.table I have a data.table which is in long format and I want to re-structure it to wide format. Something similar to case to vars in SPSS. I have the data which is created in long format using melt
library(data.table)
set.seed(71)
DT <- data.table(town = rep(c('A','B'), each=17),
                 tc = rep(c('C','D'), 17),
                 one = rnorm(34,1,1),
                 two = rnorm(34,2,1),
                 three = rnorm(34,3,1),
                 four = rnorm(34,4,1),
                 five = rnorm(34,5,2),
                 six = rnorm(34,6,2),
                 seven = rnorm(34,7,2),
                 eight = rnorm(34,28,3))

DT1 <- melt(DT, id.vars = c("town","tc"),measure=3:10)

DT1[, `:=` (mn = mean(value,na.rm = TRUE), sdev = sd(value,na.rm = TRUE), uplimit = mean(value,na.rm = TRUE)+1.96*sd(value,na.rm = TRUE), lowlimit=mean(value,na.rm = TRUE)-1.96*sd(value,na.rm = TRUE)), by = .(town,tc,variable)][, outlier := +(value < mn - 1.96*sdev | value > mn + 1.96*sdev)]

so originally the data had 34 records and we had 8 key variables "one" to "eight". using melt we get a data similar to the one that is generated by above code and column "value" holds the data from the original data. Now on this data we do some computation and create the other variables "mn", "sd", "up", "low", "out". Now this data needs to be merged with the original data which has only 34 records. So I want to re-structure this data so that the restructured data has 34 records and eight variable each for "mn", "sd", "uplimit", "lowlimit", "out". How can I achieve this? I was trying dcast but not very clear of ~ and + how to use in the formula.....not clearly mentioned in ?dcast and other notes. Do you have something to share which explains this with an example. can the requirement be achieved using dcast?

A: finally I have found answer to my question post multiple tries. So basically the key to note is that the original data had to have a unique ID identifier which in this case was not present. So I added sequential unique numbers at the end in variable "unique".
library(data.table)
set.seed(71)
DT <- data.table(town = rep(c('A','B'), each=17),
                 tc = rep(c('C','D'), 17),
                 one = rnorm(34,1,1),
                 two = rnorm(34,2,1),
                 three = rnorm(34,3,1),
                 four = rnorm(34,4,1),
                 five = rnorm(34,5,2),
                 six = rnorm(34,6,2),
                 seven = rnorm(34,7,2),
                 eight = rnorm(34,28,3),
                 unique = 1:34)

This have me the data with a column having uniqueIDs. Then when converting the data in long format, I have used this unique variable as well in melt.
DT1 <- melt(DT, id.vars = c("town","tc","unique"),measure=3:10)

Then created the new variables that were needed
DT1[, `:=` (mn = mean(value,na.rm = TRUE), sdev = sd(value,na.rm = TRUE), uplimit = mean(value,na.rm = TRUE)+1.96*sd(value,na.rm = TRUE), lowlimit=mean(value,na.rm = TRUE)-1.96*sd(value,na.rm = TRUE)), by = .(town,tc,variable)][, outlier := +(value < mn - 1.96*sdev | value > mn + 1.96*sdev)]

Then when converting this long data to wide format so that I have same number of records as in the original data, I have taken help of this unique variable in dcast
DT2 <- dcast(DT1,town+tc+unique~variable,value.var = c("mn","sdev","outlier","uplimit","lowlimit"))

This gave me the desired output with same number of records (34) as in the original data and created the desired number of columns and each cell having same data as that in the long format.
I hope you all find this useful :)!!


text:
Q: How to compare utilization rates? I have the utilization rates of several machines for each week over a year. These differ per week because of the occurrence of machine failures and changes of orders. Meaning that one week a machine could be a bottleneck and the other week not. I want to rank these machines based on the utilization and so determine their criticality. However if I calculate the mean utilization, information gets lost. The same is when I count the events the utilization is bigger than a threshold. For example;

*

*machine A has a utilization of 50% and 14 weeks the utlization > 90%

*machine B has a utilization of 70% and 7 weeks the utlization > 90%

*machine C has a utliziation of 68% and 7 weeks the utlization > 90%

In my opinion machine A is more critical than machine B. So ranking based on a threshold value seems reasonable. However when comparing machine B and C this is not that clear. Does anyone know a statistical/mathematical method to get a good comparison?
Thanks in advance.

A: I found a solution:
The problem is a multi-criteria decision analysis (MCDA), as I want to rank the machines based on several (available) criteria. With intially the following criteria; downtime costs and utilization. However with utilization there was the following problem; if the events are counted that surpasses a threshold or the average utilization is used, both situations would lead to loss of information. As it is a MCDA, both criteria can be added, thus the criteria are now:

*

*downtime costs per time unit

*average utilization per timespan

*number of events the utilization that surpasses a threshold (e.g. 95%)

As these factors are not directly commensurable and differ in importance, a weighted method is needed. To select the appropriate method 7 guidelines are used (Guitouni and Martel, 1998);

*

*Guideline G1: Determine the stakeholders of the decision process. If there are many decision makers (judges), one should think about group decision making methods or group decision support systems (GDSS).

*Guideline G2: Consider the Decision Maker (DM) `cognition' (DM way of thinking) when choosing a particular preference elucidation mode. If he is more comfortable with pairwise comparisons, why using tradeoffs and vice versa?

*Guideline G3: Determine the decision problematic pursued by the DM. If the DM wants to get an alternatives ranking, then a ranking method is appropriate, and so on.

*Guideline G4: Choose the Multi Criteria Analysis Problem (MCAP) that can handle properly the input information available and for which the DM can easily provide the required information; the quality and the quantities of the information are major factors in the choice of the method.

*Guideline G5: The compensation degree of the MCAP method is an important aspect to consider and to explain to the DM. If he refuses any compensation, then many MCAP will not be considered.

*Guideline G6: The fundamental hypothesis of the method are to be met (verified), otherwise one should choose another method.

*Guideline G7: The decision support system coming with the method is an important aspect to be considered when the time comes to choose a MCDA method.

The result based on all guideline except guideline G6, results in the following suitable methods: Analytic Hierarchy Process (AHP) or Promethee II. However AHP has the assumption that inner and outer criteria are independent. A correlation test showed that, there exists significant correlation between criteria 2 and 3, thus the criteria are not independent. Promethee II is therefore the appropriate method for ranking the machines given my problem situation.

Guitouni, A., Martel, J.-M., 1998. Tentative guidelines to help choosing an appropriate MCDA method. Eur. J. Oper. Res. 109, 501–521.


text:
Q: Upgrading Spring boot version to version 3. Problem with javax.cache library I'm trying to upgrade spring boot from 2.7.x to 3.0.1. The last thing I have left to upgrade is the library.
<dependency>
   <groupId>javax.cache</groupId>
   <artifactId>cache-api</artifactId>
   <version>1.1.1</version>
</dependency>

Have any of you had a similar problem? I didn't see any information on how to do this in the guide.

A: Remove this dependency and use from spring boot starters.
This is already having Vulnerabilities from dependencies:CVE-2020-15250.MVN REPO CACHE 1.1.1


text:
Q: WPF XAML Generics Class Binding Can you bind in XAML to a Class that takes a type T?
If I have a class myCLASS<T> and I want to bind a List<myClass<int>> to XAML can you do it?
Or do  you have to write a wrapper class newMyClass: myClass<int> and then bind the XAML to newMyClass?
Thanks.

A: XAML 2009 supports it using x:TypeArguments, but it isn't an comfortable option at the moment since it isn't supported by Microsoft's XAML to BAML compiler. For XAML 2009, you would have to read the XAML using XamlReader yourself, but then lose greater functionality like a code behind. You're best off doing as you suggested at the moment.

A: The WPF binding subsystem supports any type of object, structures, classes, generic classes and even dynamic objects.  All that matters is that the instances have properties.
You cannot create generic classes in the resources of a typical WPF application because the object creation syntax does not support it.  Nevertheless, objects that are created in code-behind, in your view-model, or by services (even if they are instances of generic types or nested generic types), can still participate in binding.
Here's an example based on the question.  Here's some XAML for a window:
<Grid>
    <ListBox ItemsSource="{Binding}" Padding="10">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding X}"/>
                    <TextBlock Text=" , "/>
                    <TextBlock Text="{Binding Y}"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

and here's a generic class that resembles a Point class:
class myClass<T>
{
    public T X { get; set; }
    public T Y { get; set; }
}

and here is some code-behind to support the binding in the XAML above:
void Window_Loaded(object sender, RoutedEventArgs e)
{
    DataContext = new List<myClass<int>>
    {
        new myClass<int> { X = 1, Y = 2 },
        new myClass<int> { X = 3, Y = 4 },
    };
}

and this is what it looks like:

We created instances of the generic class in the code-behind but bound to that data using XAML.


text:
Q: Email not sending when new user registers using devise I have my User model that users devise and I have added a mailer to send myself an email when a user signs up. When I run my code, I get no error. In the command line, it says that the email has been sent but I don't get anything. What do you think is the reason for this.
My welcome_mailer:
class WelcomeMailer < ApplicationMailer

    default :from => "jasonbig@gmail.com"

    def welcome_send(user)
        @user = user
        mail to: "jasonbig@gmail.com", subject: "New user added", from: "jasonbig@gmail.com"
    end

end

Application mailer:
class ApplicationMailer < ActionMailer::Base
  default from: "jasonbig@gmail.com"
  layout 'mailer'
end

My user model:
class User < ActiveRecord::Base

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  after_create :welcome_send

  def welcome_send
    WelcomeMailer.welcome_send(self).deliver
  end

end

Welcome_mailer view(welcome_send.html.erb):

Hello, <%= @user.email %> has been added

development.rb in config(maybe the error is in the smtp settings):
Rails.application.configure do

  config.cache_classes = false

  config.eager_load = false

  config.consider_all_requests_local       = true
  config.action_controller.perform_caching = false
  config.action_mailer.delivery_method = :smtp

  # these options are only needed if you choose smtp delivery
  config.action_mailer.smtp_settings = {
    :address        => 'smtp.gmail.com',
    :port           => 25,
    :domain         => 'gmail.com',
    :authentication => :login,
    :user_name      => 'jasonbig',
    :password       => 'I have entered my actual password here'
  }

  config.action_mailer.raise_delivery_errors = true

  config.action_mailer.perform_deliveries = true

  config.active_support.deprecation = :log

  config.active_record.migration_error = :page_load

  config.assets.debug = true

  config.assets.digest = true

  config.assets.raise_runtime_errors = true

end

These are the only files I have related to ActionMailer. Please let me know if I have to add any more files or change something.
My command line email sent confirmation:

A: Try with:
config.action_mailer.smtp_settings = {
  :address        => 'smtp.gmail.com',
  :port           => 587,
  :domain         => 'gmail.com',
  :authentication => :login,
  :user_name      => 'jasonbig',
  :password       => 'I have entered my actual password here'
  :enable_starttls_auto => true
}

A: Following Rails Guide:
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
  address:              'smtp.gmail.com',
  port:                 587,
  domain:               'example.com',
  user_name:            '<username>',
  password:             '<password>',
  authentication:       'plain',
  enable_starttls_auto: true
}

And I would add this configs:
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
config.action_mailer.raise_delivery_errors = true
config.action_mailer.perform_deliveries = true

And see if you have enabled 2F auth in gmail

A: Try
:authentication => :plain,

Additionally, if you have two-factor authentication for your Gmail account, you need to follow the instructions in this document:
https://support.google.com/accounts/answer/6010255?hl=en
and replace
:password => LESS_SECURE_APP_GMAIL_PASSWORD,


text:
Q: Unable to download website's contents using mechanize I got a python script from here to download web contents from a course website:
from mechanize import Browser
b = Browser()
b.open("https://wiki.engr.illinois.edu/display/cs498cc/Home")
b.select_form(nr=0)
b["user"] = "myusername"
b["passwrd"] = "blabla"
b.submit()

response = b.response().read()
if "Salve <b>johnconnor</b>" in response:
print "Logged in!"

I'm getting an error:
mechanize._form.ControlNotFoundError: no control matching name 'user'

I'm not sure how to do this since I've just started learning python and discovered that library.
I've tried using the --user=X --password=Y flags with wget too, but it only downloads the login page!

A: The form elements have different names:
<input type="text" name="os_username" id="os_username" class="text   " data-focus="0">
<input type="password" name="os_password" id="os_password" class="password ">

Change user to os_username and passwrd to os_password and it might work.


text:
Q: Can anyone explain to me what this equation does/ how to read it? I'm following this paper to create my own version of Poisson image editing. However, I don't quite understand what equation 1 and 2 are asking me.

The simplest interpolant $f$ of $f^*$ over $\Omega$ is the membrane interpolant defined as the solution of the minimization problem:
  $$\underset{f}{\text{min}}\iint_\Omega\left|\nabla f\right|^2\ \text{with}\ f|_{\partial\Omega}=f^*|_{\partial\Omega},\tag1$$ where $\nabla.=[\frac{\partial.}{\partial x}\frac{\partial.}{\partial y}]$ is the gradient operator.  The minimizer must satisfy the associated Euler-Lagrange equation $$\Delta f=0\ \text{over}\ \Omega\ \text{with}\ f|_{\partial\Omega}=f^*|_{\partial\Omega},\tag2$$ where $\Delta.=\frac{\partial^2.}{\partial x^2}+\frac{\partial^2.}{\partial y^2}$ is the Laplacian operator.  [...]
Poisson Image Editing by Pérez, Gangnet, Blake from Microsoft Research UK.  http://www.irisa.fr/vista/Papers/2003_siggraph_perez.pdf

A: For equation $(1)$, the problem asks you to consider functions $f:\Omega\subset \Bbb R^2\longrightarrow \Bbb R$ that agree with $f^*$ on the boundary $\partial \Omega$ of $\Omega$, that is, $f=f^*$ on $\partial\Omega$.
There are many such functions.
For each of them, we may consider the value
$$I(f) = \int_\Omega{\lVert\nabla f\rVert}^2$$
Because $\Omega\subset\Bbb R^2$, we have that $f$ is a function of two variables, say $(x,y)$.
Then, $\nabla f(x,y)$ is the vector of partial derivatives $\left(\frac\partial{\partial x}f(x,y), \frac\partial{\partial y}f(x,y)\right)$.
Hence,
$${\lVert\nabla f(x,y)\rVert}^2 = {\left(\frac\partial{\partial x}f(x,y)\right)}^2 + {\left(\frac\partial{\partial y}f(x,y)\right)}^2,$$
which is a real number, so the integral $I(f)$ is a real number too.
Equation $(2)$ tells you that the 'simplest interpolant $f$ of $f^*$ over $\Omega$' is the $f$ which minimizes $I(f)$; call it $f_0$.
Moreover, equation$(2)$ tells you that $f_0$ satisfies
$$\Delta f_0 = 0$$
on $\Omega$, meaning that for all $(x,y)$ on $\Omega$
$$\Delta f_0(x,y) =
\frac{\partial^2}{\partial x^2}f(x,y) + \frac{\partial^2}{\partial y^2}f(x,y) = 0.$$


text:
Q: exit(0) vs return 0
When exit(0) is used to exit from program, destructors for locally
  scoped non-static        objects are not called. But destructors are
  called if return 0 is used.Note that static      objects will be
  cleaned up even if we call exit().

There should be some reason behind this logic. i just want to know what it is? Thank you.

A: In the case of exit( 0 ), you're calling a function.  You
don't expect the destructors of local variables to be called if
you're calling a function.  And the compiler doesn't know,
a priori, that there is anything special about exit( 0 ).
In fact, this rationale really only applies to C++ before
exceptions.  The standard could redefine exit() to throw an
implementation defined exception with the argument, and specify
that the call to main is wrapped in a try block which catches
this exception, and passes the return code back to the system.
This would mean that exit have a completely different
semantics in C and in C++, however; at any rate, there's been no
proposal before the committee to make this change.


text:
Q: How to speed Meteor.js build times? When I make a change to Javascript file and save it, it takes over 5 seconds to build and restart the development server even if it is simple 10 line example app. I am new to Meteor.js so I don't know if it's normal, but I though changes should appear instantly (about a second or two) on a browser? 5-6 seconds feels pretty long time for me.
Selecting package versions and downloading packages seem to take the major part of the time.
There is one websocket pending (Chrome Dev tools Network tab) when it's restarting. I'm using Meteor 1.0.

A: That's a known problem they're working on. You can read about it and follow the progress in issue #2846.

A: There is a new issue about this: https://github.com/meteor/meteor/issues/4284
Upgrading to a pre-release of 1.3 seems one of the best options right now:
meteor update --release METEOR@1.3-modules-beta.8
And upgrading to 1.3 when it comes out (should come around march-april 2016).

Quick measurements to get a rough idea:
BryanARivera says on the thread that updating to 1.3-modules-beta.8 gets him From 6-10s to 1-2s.
I tried on the https://github.com/wekan/wekan project by changing a view component (on an early-2013 mbp with SSD):
with `METEOR@1.2.1`                    ~10s to reload
with `METEOR@1.2.2-faster-rebuilds.0`  ~5s  to reload
with `METEOR@1.3-modules-beta.8`       ~4s  to reload

A: This was my purely hardware solution to the problem of slow Meteor build times.
When I decided to get into development I was adamant that I wasn't going to run out and buy the latest and greatest in hardware until I actually knew how to code and knew what my requirements were in the long term.
So I went out and bought a used 15" Acer laptop; it had the following spec:

*

*Memory: 6Gb RAM

*Processor: Intel Pentium CPu 6200 @ 2.13GHz *2

*OS: Ubuntu 16.04.1 LTS 32-bit

*Storage: 153.5GB HDD

With this setup I saw rebuild times of between 15s ~ 30s (including the browser refresh) of a side project using Meteor 1.4, Reactand a Mongo db instance with around 1500 records. I found these times to be excruciatingly slow when it came to making multiple changes. You can see the initial version of the project I was working on herehere.
After trying to get work done in cafe's and libraries I realised that I was much happier working at home, and once the side project was complete I decided I would reward myself with an upgrade.
My initial choices were between a Macbook Pro and a gaming PC such as the Asus ROG, but since the former are very expensive and the later's graphics abilities were of no use to me (I'm not a gamer) I ruled them both out. These being quality machines, when I compared them against reviews of other PC's and laptops I noticed that where other systems scored higher in performance, they were lower in build quality and vice versa and there was no overall winner that had me sold.
I decided, a self build was in order and that it would be great if I could fit it all into a mini-ITX board and case. My requirements became:

*

*An SSD drive (faster read/write times than a HDD)

*Ubuntu: On account of it being free and faster that MacOS

*Mini-ITX: so that it can unobtrusively fit onto my desk

*Quite

*16Gb DDR4 RAM: this seems the bare minimum for development.

After some searching I came across these instructions for a $682 Skylake Mac Mini Hackintosh Build, which formed the basis of my build.
As I currently have no intention of working with MacOS, as per the Hackintosh instructions, I did not change the Wifi card.
My new spec list along with what I paid for each item were as follows:

*

*Intel Core i7 Quad-Core i7-6700 3.4GHz Processor £279.97

*Crucial Ballistix Sport 16 GB kit (8 GB x 2) DDR4 2400MT/s UDIMM 288-Pin Memory £121.00

*Samsung 850 Pro 250GB SSD £121.00

*Gigabyte H-170 Motherboard £109.00

*Noctua NH-L9i CPU Cooler £35.00

*External PicoPSU Power Brick £24.00

*MiniBox 160W PicoPSU £40.00

*Streacom F1C-WS £90.00

*Noctua NF-A4x10 FLX £10.99
Making a total spend of £830 (correct at time of writing).

The case comes in two finishes; black and silver, I went with the former to keep my monitor my main point of focus on my desk. It took me about an hour as a newbie to put it all together. I imagine it would be much faster if I did this for living.
Pros:

*

*My rebuild times were drastically reduced to only 2s using Meteor 1.4.

*The PC as a whole takes only 15 seconds to boot up whereas the laptop could take as long as 2 minutes.

*With the laptop, a Meteor reload would fully load the CPU whereas with the PC the 4 cores barley rose above a few percent, as viewed from the System Monitor tool.

*It has a footprint of 19cm x 19cm making which is smaller than my laptop.

*It was super quite, the fans were barley noticeable on most days.

Cons:

*

*The draw back of such a small case is that there is no room for a graphics card should I want to start gaming in the future.

*All the ports are at the rear. However, this does give the front a clean look.

*There is no reset button but the power switch can be configured via the bios to act as a "soft" switch such that, pressing it brings up a dialogue giving you the option to restart/suspend/shutdown.

Conclusion:
Overall I am very happy with the choice of components I made and the money I saved by self-building.The PC is powerful enough for video editing and I am working towards editing my first Youtube tutorials.
Being more wise about my needs means that I am now using Docker to create isolated development environments to prevent software conflicts which in themselves can chew up time in resolving.
The component research I did means that I am aware of the massive progress that PC cases, coolers, cables, memory cards, fans have made since I left college. You can now build something not only small and powerful but also attractive with options like tempered glass, liquid coolers, custom braided cables, case strobe lighting and shaped cases.


text:
Q: How To Link To Another Page in React? What I'm trying to do: I'm trying to get my React Web-App NavBar to link to other pages inside my app.
What I've tried:

*

*Inside my App.js file, I've set up React-Router-Dom as you can see.

*I've also inserted the links inside my NavBar

*Now, I face a problem when looking at the site on my local server. (See screenshot)

Here's the code for App.js
import React from "react"
import NavBar from "./NavBar"
import Dashboard from "./Dashboard"
import {BrowserRouter as Router, Switch, Route} from "react-router-dom";

function App() {
    return (
        <Router>

            <NavBar />
            <Route path="/dashboard" component={Dashboard} />

        </Router>
        )
}

export default App

Here's the code for the NavBar
import React from "react"
import "./Style.css"
import { link } from 'react-router-dom'

class NavBar extends React.Component {
    render() { return (

Hello

                <link to={"./Dashboard"}>

Dashboard

                </link>

    )
    }
}

export default NavBar

Here is a screenshot of the error:
enter image description here

A: you are using link the wrong way

import {Link} from "react-router-dom";

<Link to="/Dashboard"> Dashboard </Link>

use this and see if it works

A: Link component must start with capital letter L in both import and JSX.
  import { Link } from 'react-router-dom'

  <Link to={"./Dashboard"}>
    Dashboard
  </Link>

Read more at https://reactrouter.com/web/api/Link, there are a few examples too.
BTW: Link should be inside li

A: In app.js file : add Switch Router as shown below and add exact word to route
 return (
    <Router>

        <NavBar />
         <Switch>
        <Route exact path="/dashboard" component={Dashboard} />
       </Switch>

    </Router>
    )

export default App
In navbar file: do changes acc.
return (

Hello

<link to="/dashboard">Dashboard<link>

)

Note : its not /Dashboard its /dashboard  as in route u mentioned in that way
export default NavBar

A: In App.js, use

        <Switch>
          <Route exact path="/" component={HomeScreen}/>
          <Route exact path="/product/:id" component={ProductScreen}/>
          <Route exact path="/cart" component={CartScreen}/>

        </Switch>


text:
Q: Graphic issues with installing Ubuntu on PC with Radeon 7770 Haven't found anything about the issue I'm experiencing and would like someone to help me with it.
I'm trying to install Ubuntu 14.04, but for some reason installation does load, but I get on monitor tiles of size 4px by 8px in zig-zag black/orange and can't see anything from them.
Managed somehow to get to select screen, but that is where issues start since I can't discern what option is what.
Anyone has idea how to fix it?
See screenshot below:

A: Try booting with nomodeset. After installing, you can install the proprietary drivers which may help.  It would also help to get this fixed if you could file a bug for your problem at http://wiki.x.org/wiki/radeon/


text:
Q: Elastic Beanstalk Ruby 2.6 running on 64bit Amazon Linux 2/3.1.2 platform update error: Early termination of worker Suddenly, after an automatic platform update to version 3.1.2, I get this message in the puma log repeatedly and constantly:
Early termination of worker
+ Gemfile in context: /var/app/current/Gemfile

But the log won't show what the actual error is.

A: In summary, I fixed this error by adding this in my Gemfile
gem 'nio4r', '2.5.3'

and then running bundle update, pushing code and re-deploying my app.
I share a more detailed explanation into how I got to the solution in this stack overflow answer


text:
Q: jquery.kyco.googleplusfeed.min.js Unminified Source code Where is the unminified jquery.kyco.googleplusfeed.min.js source code?
All source files are minified at the GitHub repo.

A: Here's the unminified source code for jquery.kyco.googleplusfeed.js:
https://github.com/kyco/jquery.kyco.googleplusfeed/blob/master/src/jquery.kyco.googleplusfeed.js

A: The unminified source can be found here. You might also want to take a look at the source code of v2 here.


text:
Q: Android Location client returns same location I want to get the user's location for some time interval. I tried fused location. But it returns same location after the phone goes to sleep mode.
    public class FusedActivity extends Activity implements OnClickListener,
    GooglePlayServicesClient.ConnectionCallbacks,
    GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {
    private static final long FIVE_MINUTES = 300000;

private LocationClient locationclient;
private LocationRequest locationrequest;
private Intent mIntentService;
private PendingIntent mPendingIntent;

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    itemsFindViewById();

    mIntentService = new Intent(this, LocationService.class);
    mPendingIntent = PendingIntent.getService(this, 1, mIntentService, 0);

    int resp = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    if (resp == ConnectionResult.SUCCESS) {
        locationclient = new LocationClient(this, this, this);
        locationclient.connect();
        log.i(TAG, "ConnectionResult.SUCCESS");
    } else {
        Toast.makeText(this, "Google Play Service Error " + resp,
                Toast.LENGTH_LONG).show();
    }

}
    private void startLocationUpdates() {
    if (locationclient != null) {
        locationrequest = LocationRequest.create();
        locationrequest.setInterval(FIVE_MINUTES);
        locationrequest.setFastestInterval(FIVE_MINUTES);
        locationrequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationclient.requestLocationUpdates(locationrequest,
                mPendingIntent);
        startStopBtn.setText("Stop");
        log.i(TAG, " register location updates");
    } else
        log.i(TAG, "location client null");
}

private void stopLocationUpdates() {
    if (locationclient != null) {
        locationclient.removeLocationUpdates(mPendingIntent);
        log.i(TAG, " Unregister location updates");
        startStopBtn.setText("Start");
    }
}

//INTENT SERVICE
Intent service class...
    public class LocationService extends IntentService {

private static final String TAG = "LocationService";

Logger log;

public LocationService() {
    super("Fused Location");
    log = Logger.getInstance(this);
}

@Override
protected void onHandleIntent(Intent intent) {
    Location location = intent
            .getParcelableExtra(LocationClient.KEY_LOCATION_CHANGED);
    if (location != null) {
        Toast.makeText(this, "Received Location Update", Toast.LENGTH_SHORT)
                .show();
        getBatteryLevel();
        StringBuilder sb = new StringBuilder();
        StringBuilderPrinter sbp = new StringBuilderPrinter(sb);
        location.dump(sbp, "");
        log.i(TAG, sb.toString());
    }

}

private void getBatteryLevel() {
    float lev;
    Intent batteryIntent = registerReceiver(null, new IntentFilter(
            Intent.ACTION_BATTERY_CHANGED));
    int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

    if (level == -1 || scale == -1) {
        lev = 50.0f;
    } else {
        lev = ((float) level / (float) scale) * 100.0f;
    }
    log.i(TAG, "Battery Level" + lev);
}

}
Logs
Here is the logs...
I 05-12-13 19:40:37.566+0530 FusedActivityFusedActivity Created
I 05-12-13 19:40:37.582+0530 FusedActivityConnectionResult.SUCCESS
I 05-12-13 19:40:37.684+0530 FusedActivity onConnected
I 05-12-13 19:55:08.582+0530 FusedActivity register location updates
I 05-12-13 19:55:08.615+0530 LocationServiceBattery Level82.0
I 05-12-13 19:55:08.620+0530 LocationServicemProvider=fused mTime=1386253508567
mLatitude=12.9785261 mLongitude=80.2296999
mHasAltitude=false mAltitude=0.0
mHasSpeed=false mSpeed=0.0
mHasBearing=false mBearing=0.0
mHasAccuracy=true mAccuracy=655.0
mExtras=null

I 05-12-13 20:00:09.433+0530 LocationServiceBattery Level82.0
I 05-12-13 20:00:09.436+0530 LocationServicemProvider=fused mTime=1386253809354
mLatitude=12.9806657 mLongitude=80.2298551
mHasAltitude=false mAltitude=0.0
mHasSpeed=false mSpeed=0.0
mHasBearing=false mBearing=0.0
mHasAccuracy=true mAccuracy=1035.0
mExtras=null

I 05-12-13 20:05:10.473+0530 LocationServiceBattery Level81.0
I 05-12-13 20:05:10.481+0530 LocationServicemProvider=fused mTime=1386254110368
mLatitude=12.9806657 mLongitude=80.2298551
mHasAltitude=false mAltitude=0.0
mHasSpeed=false mSpeed=0.0
mHasBearing=false mBearing=0.0
mHasAccuracy=true mAccuracy=1035.0
mExtras=null

I 05-12-13 20:10:12.477+0530 LocationServiceBattery Level81.0
I 05-12-13 20:10:12.479+0530 LocationServicemProvider=fused mTime=1386254412369
mLatitude=12.9806657 mLongitude=80.2298551
mHasAltitude=false mAltitude=0.0
mHasSpeed=false mSpeed=0.0
mHasBearing=false mBearing=0.0
mHasAccuracy=true mAccuracy=1035.0
mExtras=null

I 05-12-13 20:15:14.482+0530 LocationServiceBattery Level81.0
I 05-12-13 20:15:14.487+0530 LocationServicemProvider=fused mTime=1386254714360
mLatitude=12.9806657 mLongitude=80.2298551
mHasAltitude=false mAltitude=0.0
mHasSpeed=false mSpeed=0.0
mHasBearing=false mBearing=0.0
mHasAccuracy=true mAccuracy=1035.0
mExtras=null

I 05-12-13 20:20:18.442+0530 LocationServiceBattery Level80.0
I 05-12-13 20:20:18.444+0530 LocationServicemProvider=fused mTime=1386255018354
mLatitude=12.9806657 mLongitude=80.2298551
mHasAltitude=false mAltitude=0.0
mHasSpeed=false mSpeed=0.0
mHasBearing=false mBearing=0.0
mHasAccuracy=true mAccuracy=1035.0
mExtras=null

I 05-12-13 20:25:18.583+0530 LocationServiceBattery Level80.0
I 05-12-13 20:25:18.590+0530 LocationServicemProvider=fused mTime=1386255318418
mLatitude=12.9806657 mLongitude=80.2298551
mHasAltitude=false mAltitude=0.0
mHasSpeed=false mSpeed=0.0
mHasBearing=false mBearing=0.0
mHasAccuracy=true mAccuracy=1035.0
mExtras=null

I 05-12-13 20:30:19.439+0530 LocationServiceBattery Level80.0
I 05-12-13 20:30:19.441+0530 LocationServicemProvider=fused mTime=1386255619342
mLatitude=12.9806657 mLongitude=80.2298551
mHasAltitude=false mAltitude=0.0
mHasSpeed=false mSpeed=0.0
mHasBearing=false mBearing=0.0
mHasAccuracy=true mAccuracy=1035.0
mExtras=null

I 05-12-13 20:35:21.478+0530 LocationServiceBattery Level80.0
I 05-12-13 20:35:21.482+0530 LocationServicemProvider=fused mTime=1386255921356
mLatitude=12.9811803 mLongitude=80.2320268
mHasAltitude=false mAltitude=0.0
mHasSpeed=false mSpeed=0.0
mHasBearing=false mBearing=0.0
mHasAccuracy=true mAccuracy=964.0
mExtras=null

I 05-12-13 20:40:26.732+0530 LocationServiceBattery Level79.0
I 05-12-13 20:40:26.742+0530 LocationServicemProvider=fused mTime=1386256226616
mLatitude=12.9806657 mLongitude=80.2298551
mHasAltitude=false mAltitude=0.0
mHasSpeed=false mSpeed=0.0
mHasBearing=false mBearing=0.0
mHasAccuracy=true mAccuracy=1035.0
mExtras=null

I 05-12-13 20:45:29.515+0530 LocationServiceBattery Level79.0
I 05-12-13 20:45:29.516+0530 LocationServicemProvider=fused mTime=1386256529414
mLatitude=12.9806657 mLongitude=80.2298551
mHasAltitude=false mAltitude=0.0
mHasSpeed=false mSpeed=0.0
mHasBearing=false mBearing=0.0
mHasAccuracy=true mAccuracy=1035.0
mExtras=null

I 05-12-13 20:50:32.442+0530 LocationServiceBattery Level79.0
I 05-12-13 20:50:32.445+0530 LocationServicemProvider=fused mTime=1386256832334
mLatitude=12.9806657 mLongitude=80.2298551
mHasAltitude=false mAltitude=0.0
mHasSpeed=false mSpeed=0.0
mHasBearing=false mBearing=0.0
mHasAccuracy=true mAccuracy=1035.0
mExtras=null

I 05-12-13 20:55:35.539+0530 LocationServiceBattery Level79.0
I 05-12-13 20:55:35.541+0530 LocationServicemProvider=fused mTime=1386257135439
mLatitude=12.9806657 mLongitude=80.2298551
mHasAltitude=false mAltitude=0.0
mHasSpeed=false mSpeed=0.0
mHasBearing=false mBearing=0.0
mHasAccuracy=true mAccuracy=1035.0
mExtras=null

I 05-12-13 21:00:38.489+0530 LocationServiceBattery Level78.0
I 05-12-13 21:00:38.491+0530 LocationServicemProvider=fused mTime=1386257438383
mLatitude=12.9806657 mLongitude=80.2298551
mHasAltitude=false mAltitude=0.0
mHasSpeed=false mSpeed=0.0
mHasBearing=false mBearing=0.0
mHasAccuracy=true mAccuracy=1035.0
mExtras=null

I 05-12-13 21:05:40.601+0530 LocationServiceBattery Level78.0
I 05-12-13 21:05:40.603+0530 LocationServicemProvider=fused mTime=1386257740373
mLatitude=12.9806657 mLongitude=80.2298551
mHasAltitude=false mAltitude=0.0
mHasSpeed=false mSpeed=0.0
mHasBearing=false mBearing=0.0
mHasAccuracy=true mAccuracy=1035.0
mExtras=null

I 05-12-13 21:10:42.440+0530 LocationServiceBattery Level78.0
I 05-12-13 21:10:42.442+0530 LocationServicemProvider=fused mTime=1386258042334
mLatitude=12.9806657 mLongitude=80.2298551
mHasAltitude=false mAltitude=0.0
mHasSpeed=false mSpeed=0.0
mHasBearing=false mBearing=0.0
mHasAccuracy=true mAccuracy=1035.0
mExtras=null

I 05-12-13 21:15:46.011+0530 LocationServiceBattery Level78.0
I 05-12-13 21:15:46.013+0530 LocationServicemProvider=fused mTime=1386258345906
mLatitude=12.9806657 mLongitude=80.2298551
mHasAltitude=false mAltitude=0.0
mHasSpeed=false mSpeed=0.0
mHasBearing=false mBearing=0.0
mHasAccuracy=true mAccuracy=1035.0
mExtras=null

I 05-12-13 21:20:49.474+0530 LocationServiceBattery Level78.0
I 05-12-13 21:20:49.475+0530 LocationServicemProvider=fused mTime=1386258649342
mLatitude=12.9806657 mLongitude=80.2298551
mHasAltitude=false mAltitude=0.0
mHasSpeed=false mSpeed=0.0
mHasBearing=false mBearing=0.0
mHasAccuracy=true mAccuracy=1035.0
mExtras=null

I 05-12-13 21:25:53.515+0530 LocationServiceBattery Level78.0
I 05-12-13 21:25:53.520+0530 LocationServicemProvider=fused mTime=1386258953407
mLatitude=12.9806657 mLongitude=80.2298551
mHasAltitude=false mAltitude=0.0
mHasSpeed=false mSpeed=0.0
mHasBearing=false mBearing=0.0
mHasAccuracy=true mAccuracy=1035.0
mExtras=null

I 05-12-13 21:30:54.393+0530 LocationServiceBattery Level77.0
I 05-12-13 21:30:54.395+0530 LocationServicemProvider=fused mTime=1386259254329
mLatitude=12.9806657 mLongitude=80.2298551
mHasAltitude=false mAltitude=0.0
mHasSpeed=false mSpeed=0.0
mHasBearing=false mBearing=0.0
mHasAccuracy=true mAccuracy=1035.0
mExtras=null

I 05-12-13 21:35:55.496+0530 LocationServiceBattery Level77.0
I 05-12-13 21:35:55.498+0530 LocationServicemProvider=fused mTime=1386259555342
mLatitude=12.9806657 mLongitude=80.2298551
mHasAltitude=false mAltitude=0.0
mHasSpeed=false mSpeed=0.0
mHasBearing=false mBearing=0.0
mHasAccuracy=true mAccuracy=1035.0
mExtras=null


text:
Q: PostgreSQL Mountain Lion socket issue I've been trying to set up PostgreSQL on my system (OSX 10.8, clean install), but I'm running into trouble with using psql, createdb, etc. I've tried various solutions and none seem to work.
The install was successful, and I proceeded to fix the known sockets issue using the following:
mkdir /var/pgsql_socket
sudo chown $USER /var/pgsql_socket

Then I edited postgresql.conf, set unix_socket_directory to
unix_socket_directory = '/var/pgsql_socket'

and restarted Pg.
That should apparently have fixed the socket issue, but I'm still getting:
psql: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/tmp/.s.PGSQL.5432"?

Also, I've checked the status of the server, and it appears to be running, but I still get 'no such file or directory'
Any ideas?

A: According to the error message, the psql command that appears first in the $PATH has /tmp as the hard-coded  default unix socket directory.
Since the actual directory is in fact /var/pgsql_socket, you should tell it explicitly rather than relying on the default:
$ psql -h /var/pgsql_socket [other options]

The same applies to other client-side commands like createdb, dropdb, createuser...
If you don't want to specify -h each time, it can be put into the PGHOST environment variable.
Some people also solve this by using TCP connections to localhost rather than using the Unix socket directory.
The root cause of this issue would be that after installing PostgreSQL on Mac OS X, the system ends up having two different instances of the postgres client set (the libpq library, psql and other associated utilities), one that is bundled with MacOS and the other that comes with the PostgreSQL installer.
Therefore yet another method is to change your $PATH so that the psql installed with PostgreSQL gets choosen before the one installed with the system (presumably /usr/bin/psql).

A: I encountered this same issue when installing PostgreSQL 9.2 via Homebrew. psql that comes with this build looks to /tmp for a socket when called without any options.
I didn't feel like adding any new environment variables like PGHOST or creating aliases for psql. There's nothing wrong with doing any of these things, but I just didn't feel like adding to the clutter of my environment.
So, why not just set unix_socket_directory in postgresql.conf to /tmp? I did:
unix_socket_directory = '/tmp'      # (change requires restart)
#unix_socket_group = ''             # (change requires restart)
#unix_socket_permissions = 0777     # begin with 0 to use octal notation

After a reload, I can just run $ psql with no -h option, without having added an alias or environment variable.

A: I had the same problem, and after doing what you'd done I also had to change my path so that /usr/local/bin (where Homebrew puts everything) comes before /usr/bin.  I don't know why this isn't the default anymore, but it's easy to change.
sudo vi /etc/paths

then edit the file to have the /usr/local/bin line at the top.
Or alternately if you just want this change to happen for your specific user account, edit your ~/.bash_profile file:
touch ~/.bash_profile
vi ~/.bash_profile

and add this line: export PATH="/usr/local/bin:$PATH"
then run source ~/.bash_profile for the changes to take effect.

A: See accepted answer for question/link below. Worked for me, but note the setting to change is unix_socket_directories (plural) not unix_socket_directory as stated.
https://dba.stackexchange.com/questions/21587/postgresql-is-running-locally-but-i-cannot-connect-why


text:
Q: jqGrid Subgrid data not showing up I have seen the same question being asked but none of them contained an answer that I could use. I am using jqgrid 4.4. The main grid loads data fine, in the subgrid I can see the response from my java controller but not sure how to get it to show up.
function(){
        jQuery("#subGrid").jqGrid({
            url: CONTEXT_ROOT+"/cartonPremium",
            id:'gridtable',
            datatype: "json",
            height: 190,
            jsonReader : {
                       root: 'gridModel',
                       page: 'page',
                       total: 'total',
                       records: 'records',
                       repeatitems: false,
                       id: '0'
             },
            colNames:['idPremium','Name','Week', 'Departure Region' ],
            colModel:[
            {name:'idPremium',hidden:false, width:100},
            {name:'name',index:'name', width:300},
            {name:'sequence',index:'sequence', width:90},
            {name:'departureRegion',index:'departureRegion',width:100}
            ],
            hidegrid: false,
            rowNum:20,
            rowList:[20,40,80],
            pager: '#psubGrid',
            sortname: 'name',
            viewrecords: true,
            sortorder: "desc",
            multiselect: false,
            sortable: true,
            autowidth: false,
            pagerButtons:true,
            navigator:true,
            //loadonce: true,
            altRows: true,
            viewsortcols: [true,'vertical',true],
            subGrid: true,
            // define the icons in subgrid
            subGridOptions: {
                "plusicon" : "ui-icon-triangle-1-e",
                "minusicon" : "ui-icon-triangle-1-s",
                "openicon" : "ui-icon-arrowreturn-1-e"//,
                //expand all rows on load
                //"expandOnLoad" : true
            },
            subGridRowExpanded: function(subgrid_id, row_id) {

                var subgrid_table_id, pager_id;
                subgrid_table_id = subgrid_id+"_t";
                pager_id = "p_"+subgrid_table_id;

                $("#"+subgrid_id).html("

");

                jQuery("#"+subgrid_table_id).jqGrid({
                    url:CONTEXT_ROOT+"/premiumCasePackOption?rowId="+row_id,
                    datatype: "json",
                    colNames:['idCasePackOptions','cypharecommended','distributorapproved', 'height', 'length','statuscode','weight','width'],
                    colNames:['idCasePackOptions'],
                    colModel: [
                        {name:'idCasePackOptions', width:170,hidden:false}
                    ],
                    rowNum:8,
                    pager: pager_id,
                    sortname: 'idCasePackOptions',
                    sortorder: "asc",
                    sortable: true,
                    height: 400
                });
            jQuery("#"+subgrid_table_id).jqGrid('navGrid',"#"+pager_id,{edit:false,add:true,del:false});
            }
        }
    );
    jQuery("#subGrid").jqGrid('navGrid','#psubGrid',{add:false,edit:false,del:false});
}

);
Here is response from server
{"total":1,"page":1,"gridModel":[{"idCasePackOptions":1},{"idCasePackOptions":2},{"idCasePackOptions":3},{"idCasePackOptions":4},{"idCasePackOptions":5},{"idCasePackOptions":6}],"records":6,"rows":8}

Help!! What am I missing?

A: I finally got it to working...yipeee!!! the magic that was missing from the subgrid
jsonReader: {
  root: 'gridModel',
  repeatitems: false
}

So the working version looks like this
$(document).ready(
function(){
        jQuery("#subGrid").jqGrid({
            url: CONTEXT_ROOT+"/cartonPremium",
            id:'gridtable',
            datatype: "json",
            height: '100%' ,
            mtype: 'POST',
            jsonReader : {
                       root: 'gridModel',
                       page: 'page',
                       total: 'total',
                       records: 'records',
                       repeatitems: false,
                       id: '0'
             },
            colNames:['idPremium','Name','Week' ],
            colModel:[
            {name:'idPremium',hidden:false, width:100},
            {name:'name',index:'name', width:300},
            {name:'sequence',index:'sequence', width:90}
            ],
            hidegrid: false,
            rowNum:20,
            rowList:[20,40,80],
            pager: '#psubGrid',
            sortname: 'name',
            viewrecords: true,
            sortorder: "desc",
            multiselect: false,
            sortable: true,
            autowidth: false,
            pagerButtons:true,
            navigator:true,
            //loadonce: true,
            altRows: true,
            viewsortcols: [true,'vertical',true],
            subGrid: true,
            // define the icons in subgrid
            subGridOptions: {
                "plusicon" : "ui-icon-triangle-1-e",
                "minusicon" : "ui-icon-triangle-1-s",
                "openicon" : "ui-icon-arrowreturn-1-e",
                "reloadOnExpand" : true
            },
            subGridRowExpanded: function(subgrid_id, row_id) {
                var subgrid_table_id, pager_id;
                subgrid_table_id = subgrid_id+"_t";
                pager_id = "p_"+subgrid_table_id;
                $("#"+subgrid_id).html("

");

                jQuery("#"+subgrid_table_id).jqGrid({
                    url:CONTEXT_ROOT+"/premiumCasePackOption?rowId="+row_id,
                    datatype: "json",
                    mtype: 'POST',
                    colNames:['idCasePackOptions','cypharecommended','distributorapproved', 'height', 'length','statuscode','weight','width'],
                    colModel: [
                        {name:'idCasePackOptions', width:170,hidden:false},
                        {name:'cypharecommended',index:'cypharecommended', width:170},
                        {name:'distributorapproved',index:'distributorapproved', width:170},
                        {name:'height',index:'height', width:100},
                        {name:'length',index:'length', width:80, align:"right"},
                        {name:'statuscode',index:'statuscode', width:90, align:"right"},
                        {name:'weight',index:'weight', width:100,align:"right"},
                        {name:'width',index:'width', width:100}
                    ],
                    rowNum:8,
                    pager: pager_id,
                    sortname: 'idCasePackOptions',
                    sortorder: "asc",
                    viewrecords: true,
                    sortable: true,
                    height: '100%' ,
                    autowidth: true,
                    jsonReader: {
                        root: 'gridModel',
                        repeatitems: false
                    }

                });
            jQuery("#"+subgrid_table_id).jqGrid('navGrid',"#"+pager_id,{edit:false,add:true,del:false});
            }
        }
    );
    //jQuery("#subGrid").jqGrid('navGrid','#psubGrid',{add:false,edit:false,del:false});
}

);

A: Your data in the subgrid will not be displayed (as well) if one of your given functions do not exist. So if you make a typo empty lines will be displayed:
afterSave: ReloadSubGrid, onError: UpdateFailed, delOptions:...
...
function ReloadSbuGrid(rowid, response) {
    ...
}

Typo: ReloadSbuGrid should have been ReloadSubGrid


text:
Q: Drupal 8 - Weird behaviour with parameters I have a form that accepts one input and after submits redirects to a controller that does some search stuff with solr.
I have discovered some weird behavior when certain words are used as a search term for the parameters of the route:
This is the SearchBoxForm form when the form is submitted, as you see it just redirects to the search controller

This is the controller action that accepts the redirect:

This is the route file:

So as you can see, the url can be as domain.com/search to domain/search/term/tab/page/filter.
No the problem, certain search words causes drupal to not properly load all js, some words are:
"cache", "chemistry" but other words work just fine like "student" or "economy".
The page works fine if you hit it with default parameters, ie domain.com/search
But domain.com/search/cache or domain.com/search/cache/all/1/undefined will not load js in any way.
Has anyone seen this problem before, or see something obvious that I have missed? I really hope this is not the render array or something that somehow sees cache in the parameters and thinks it something else..


text:
Q: Copy .txt files from a .tar.gz file to other directory I am trying to copy all the .txt files from a compressed file (this file has unknown_name_folders):
.txt files location ---> my_path/?unknown_name_folder?/file.txt
I want to do --->  my_path/file.txt
I did this code, but I have this error: EOFError: Compressed file ended before the end-of-stream marker was reached. Any idea?
file=my_path+"/"+fil
if file.endswith('.tar.gz'):

    tarf = tarfile.open(file, "r:gz")
    for info in tarf:

        if info.name.endswith('.txt'):
            print(info.name)

            tar = tarfile.open(file) #extracting
            tar.extractall()
            tar.close()
            code=os.system('cp ' + my_path+'/'+info.name +' '+ file)

A: As Paulo mentioned, you missed off the "gz" flag the second time you opened the tar file. Also, your target for copying the file was the original tarball - I assume you wanted it in a separate directory ("targdir" here)
You only need to extract the contents once, so the code becomes:
file=my_path+"/"+fil
targdir='dest'
if file.endswith('.tar.gz'):

    tarf = tarfile.open(file, "r:gz")
    tarf.extractall()
    for info in tarf:

        if info.name.endswith('.txt'):
            print(info.name)
            code=os.system('cp ' + info.name +' '+ targdir)

(edit - you don't need 'mypath' in the "cp" command - you have extracted the tarball into the current directory, so "info.name! is the full path to the file)


text:
Q: Node is still in commissioning state! I work in a lab, I have 2 Dell blades and a switch. I'm trying to create openStack using juju and MAAS. The blades are connected to the switch and have a private 192... network, and each blade itself is connected to the 10... internet.
I have installed the MAAS server using Ubuntu 13.04 and added the node to it, but the status of the node is still in commissioning! I already checked the hardware clock and it is fine.
How can I fix this issue?

A: Not 100% sure if this will answer your question, but I did have this in a virtual environment. I actually just had to reboot the node, it seemed to fix what was needed on the pxe setup the second time around.

A: I am really sorry for not being able to +1 Ross' answer, like it should be,, but being my first post, I cannot simply comment. I have to ANSWER.
I am currently deploying a private cloud using MAAS (Ubuntu 14.04) on a few Dell PE2950s, and found out a few things. The one related to this (fairly old) question is:
1) Once your "nodes" load go on "commissioning", they will be shut down ON PURPOSE, by PXE. You can actually see this on the log related to each node. EDIT the type of power control you have on that node and THEN start it again. I chose Wake on lan, and entered the MAC address detected by MAAS. The NEXT time you start the node, it will boot up and start another routine, which will actually READ the resources from that particular node (amount of memory, number of disks, how many cored, etc). After that is finished, the node will be shut down again, and will be listed as READY on MAAS.
Since we are talking about strange things, here is a few more I noticed and how I solved. Hopefully Google and other spider-indexing systems will find this as well, sharing the info with other people.
I initially tried deploying MAAS in a multi-homed machine, with two network cards, so I could have the cloud controller connected to the internet, but the nodes isolated. Just because I am paranoid. This failed miserably, because once the nodes booted up, they would fail referring to the correct IP address, where to load the images.
The only way to get it working was deploying MAAS with a single NIC (or, at least, only one NIC configured) and they things started to make sense, BUT, you definitely cannot deploy a cloud during your lunch break.
Or, if YOU can, let me know where you work, because you must have a 4 hour lunch break for sure !
I am pretty sure this can be fixed by tweaking a few parameters on configuration files, BUT, first, this is not the goal, second, reconfiguring MAAS, entering (again) the correct IP address did not fix this as one would expect.
Anyway, the objective here is to shed some light on this subject, helping those suffering souls like myself out there.
Cheers.
------ UPDATE --- UPDATE --- UPDATE ---- 15 Jan 2016
I found out that enabling IPMI on the server (probably one of the last prompts before the machine tries to boot; Usually Control E) will allow you to enable and configure IMPI's behaviour, and this is GREAT, because MAAS will use it to control that node, reboot it and shut it down as needed.
I have not tested all the steps on the process, but it looks promising.
Being more detailed, enable IPMI on the NIC used for DHCP, not the other(s). Sounds obvious, but after 3:00am all ideas start to get a bit fuzzy. ALSO, make sure the power mode (on MAAS) of each of the nodes is actually IPMI. MAAS seems to be start enough and test all NICs for IPMI capability.
Looks like MAAS is VERY happy when it controls metal based on IPMI. An alternative (I have not tested) would be setting the nodes to wake-on-lan. This may give a little more latitude regarding timeouts.
--- UPDATE --- UPDATE --- UPDATE --- 16 Jan 2016
IPMI makes a difference, and nodes are automatically powered on and off, BUT, make sure you have the latest firmware installed on your system.
Look for SUU and SLI on Dell's web site. Different versions of IPMI (firmware) behave differently as well.
PLASE NOTE that you still have to select your servers and say "COMMISSION" or "DEPLOY", but MAAS will take care of switching them on of off. No pressing buttons !
ALSO, one of my servers shows ALWAYS with the power on, no matter what. It is probably the firmware thing I mentioned. I had to REMOVE the POWER CABLE and re-connect it a minute latter in order to trigger the right reading on MAAS.  Only one unexplored variant here: this specific unit has multiple NICs, off-board. (Just found out you can select the server and say "POWER OFF" to match its actual state).


text:
Q: Can any sheaf be produced from constant sheaves by taking direct limit? Let $X$ be a topological space and let $K$ be a field.
If $F$ is a sheaf of $K$-vector spaces over $X$, can $F$ be produced from constant sheaves $K_{U_i}$ on some open subsets$U_i \subset X$ by taking direct limit?
In other words, is there any directed system $(K_{U_i}, f_{ij})$ that satisfies
$F = \varinjlim K_{U_i}$
If it is true, how can I prove it?


text:
Q: WANem to route between machines? I have installed WANem 3.0 Beta 2 on a physical machine with 2 interfaces, and I have 2 Linux boxes connected to it. Like so:
Linux1:100.100.100.2 <--> 100.100.100.1:WANem:200.200.200.1 <--> 200.200.200.2 Linux2
I have set each Linux box to use the WANem interface they are connected to as their gateway. Each Linux box can ping the addresses of both WANem interfaces (ie, Linux1 can ping both 100.100.100.1 and 200.200.200.1). However neither of them can ping each other. From reading tutorials, it seems that it should work by default, but it is not working. Does anyone know how to set up WANem to do this kind of routing? I'm not familiar with the WANem shell.
Thanks!
EDIT: It seems that in this configuration you need to manually add IP forwarding - in the WANem shell I typed:
echo 1 > /proc/sys/net/ipv4/ip_forward

and I was able to ping both endpoints from each other. This is just a temporary change, so if you reboot it will revert to not forwarding. I haven't tried it yet but apparently this is controlled by the file /etc/network/options, so you can edit this and change ip_forward=no to ip_forward=yes and the change should be permanent.

A: A bit late to the show here, but as there have been no new releases of WANem since this was posted, it's relevant.
There was actually a Debian Squeeze bug that was present in the version of knoppix that WANem 3.0 was based on that complicates this a bit.
The solution is to add the setting net.ipv4.ip_forward = 1 to /etc/sysctl.conf (because in Debian Squeeze, the /etc/network/options was deprecated).
This is only part of the solution though, due to the bug. Debian Squeeze executed /etc/init.d/procps (which applies the settings in sysctl configuration) before the modules for networking were loaded, thus they were ignored by the modules. To work around this, you need to restart the /etc/init.d/procps service in /etc/rc.local. Full credit for this workaround goes to this post by Vladislav Kononenko
The linked issue was based on a system that had an empty rc.local file, so use this example instead, as WANem has necessary logic in rc.local for it's startup.
rc.local
#!/bin/bash
#
# rc.local
#
# Load kernel variables from /etc/sysctl.d and /etc/sysctl.conf
/etc/init.d/procps restart

# Start local services after hardware detection
SERVICES="apache2 ajaxterm"

for i in $SERVICES; do
  [ -x /etc/init.d/"$i" ] && /etc/init.d/"$i" start >/dev/null 2>&1
done

exit 0

That will fix and enable ip_forwarding for you and will persist across reboots (if you've installed WANem to the harddrive of the VM with 0wn


text:
Q: text alignment changing on live server I am try to add this table on wordpress site but when i adding "p tag" formating remove and its automatically goes to left. When i am testing same code on local machine its working fine. What's Problem with it

Wordpress themes	Theme customization	Custome Theme

Price
From $200

From $400

        Work Delivery Terms

Up to 5 business days

from $400

        Theme design and coding

Logo, theme colors, layout is changed according to your preferences. Sub pages css styles of the theme are edited according to the theme style.

Custom, unique homepage and up to 10 sub pages designed and coded. Psd design mockup is provided only for the homepage.

        Plugins installation/design

Up to 3 plugins installation and setup.

Up to 5 plugins installation, setup and style change according to the theme.

        Additional plugins installation/design

$30 per hour

$30 per hour

        Slider on the Home Page

$35

Included

        Logo

Simple non-vector logo (1 concept)

Simple non-vector logo (max 2 concepts

        Additinal pages design/coding

$30 per hour

$30 per hour

        Footer backlink removal fee

$30

$30


text:
Q: Solving a complex Gaussian Integral for Path Integral Formalism I am trying to solve the following integral, $$\int dz_1d\bar{z}_1\cdots dz_nd\bar{z}_n\:\exp(-\sum_{i,j}\bar{z}_i A_{ij}z_j),$$ where $A_{ij}$ is an $n\times n$ hermitian matrix. I know how to do this for the usual Gaussian integral with real coordinates, namely, let $A = O^{-1}\cdot D\cdot O$ where $D$ is a diagonal matrix; then let $y_i = O_{ij}x_j$, and simplify until you find $D_{ii}y^2_i$ and use a previous Gaussian integral which gives an answer of $\pi^{n/2}(\det{A})^{-1/2}$. I would like to do something similar for the complex integral, where I would perform the same change of variables, but then check for poles and use Cauchy's Residue theorem.
This was an identity given to me to use for solving path integrals, but I would like to know where it comes from (the above explantaion originally came from Zee's textbook, but for this more 'complex' integral (literally), I would like some guidance).
I would attempt what I said above, but I am not confident in using Residue Theorem and performing contour integrals (hence I am here). Any help/hints are appreciated, thanks!


text:
Q: Kubuntu 16.04 - PHP 5.6 - mssql driver I just updated my kubuntu box, and PHP got updated to 7.x.
Now, as of PHP 7.x does not have the mssql_* deprecated functions, I need to downgrade to php 5.6. (PDO dblib is way to slow for this project)
Though ppa:ondrej/php does not have the mssql extension for php 5.6.
Is there any way I can force kubuntu to downgrade PHP ?

A: che your repository list if you have this repo "deb http://ppa.launchpad.net/ondrej/php/"
if yes, remove all php packages and install your stack with:
apt-get install php5.6-mysql php5.6-sqlite

if no, remove all old ondrej repository and add the new repo:
 ppa:ondrej/php
 deb http://ppa.launchpad.net/ondrej/php/ubuntu <version> main


text:
Q: Monotouch blows up on LINQ query when using device builds Here's the error I get:
| mscorlib |  | Attempting to JIT compile method 'System.Linq.OrderedEnumerable`1:GetEnumerator ()' while running with --aot-only.
From what I've read it looks like the compiler doesn't include a method in this case "GetEnumerator", that the code needs because of LINQ.  What is the correct course of action for making sure the compiler includes it?
Pretty much everyone that runs into this that I've found online just gets rid of the linq query and moves on with life but I am tired of re-writing my code when something like this pops up.  Also I'm not sure exactly which linq query is causing the issue and I'm slowly going through my code and re-writing all the linq queries until I find it.

A: The GetEnumerator method is not really missing - but it was not AOT-ed before getting into the device. So the JIT is trying to compile it on the device. Now due to Apple restriction MonoTouch (or anything else) cannot JIT code on devices (but that will work on the simulator where no such restriction exists).
So what's the real error: it's that  (generic) type hat the AOT compiler could not predict (and compile code for it).
A trick to find your issue (easier than re-writing every LINQ code you have) is to compile your C# code and then ildasm the assembly. Next find in which method(s) OrderedEnumerable`1 is being used (LINQ can hide things very easily).
Once found you might need to rewrite that part but, in some cases, you can "help" the AOT compiler by making it more obvious that the type (represented by `1) will be needed.

A: Does number #17 help you in this link?
http://ios.xamarin.com/Documentation/Troubleshoot
"System.ExecutionEngineException: Attempting to JIT compile method (wrapper managed-to-managed) Foo[]:System.Collections.Generic.ICollection`1.get_Count()"
You may well need to "hack" a workaround to fix this, sadly - but it is fixable. Can you please update your question with the actual LINQ query?

A: Found the offending line of code:
// currentDates is a List<DateTime>
return (from dt in currentDates orderby dt.Date ascending select dt).ToList();
I changed it to use
CurrentDates.Sort()

and that avoided calling the GetEnumerator that wasn't getting AOT-ed. No longer blows up.


text:
Q: Auto validate Div inputs My knowledge on JavaScript is very limited and I need to implement this front end validation please.
So I am using Spring back-end and need to do some front end validation on a form input I have.
There will be 10 of these rows enclosed as Divs with the same input for each row.
eg. the inputs will be in this format
total[0]|qty[0]||qty[0]||qty[0]
total[1]|qty[1]||qty[1]||qty[1]
total[2]|qty[2]||qty[2]||qty[2]

etc...
total[10]|qty[10]||qty[10]||qty[10]

The user will first have the option to enter a total amount first.
The user has the option to enter inputs for qty of each row.
If the total of qty[0] are not equal to the total (total[0]) the user entered, the input box corresponding to that row will turn red(to inform the user they have inputted the wrong total).
  eg qty[0] + qty[0] qty[0] != total[0] (BOX GOES RED FOR total[0])
     qty[1] + qty[1] qty[1] = total[1] (NO CHANGE TO TOTAL BOX FOR total[1])

No other validation is needed apart from a visual one after the user keys in the last input for qty on that individual row.
Upon Clicking enter on the last input(qty[0] or qty[1] if the user is on the second row, or qty[10] if the user is on the last row) the validation will kick in and check is the box with id ="total[${status.index}]" = the three inputs with id = "qty[${status.index}]"

       <form:input path="items[${status.index}].total" size="4"
        id = "total[${status.index}]" />

   <form:input path="items[${status.index}].qtyDis"size="4"
      onblur="findTotal()"
     id ="qty[${status.index}]" />

   <form:input path="items[${status.index}].qtyAva"size="4"
      onblur="findTotal()"
     id ="qty[${status.index}]" />

   <form:input path="items[${status.index}].qtyDat"size="4"
      onblur="findTotal()"
     id ="qty[${status.index}]" />

I am very weak at Javascript and this is all I was able to come up with. I know it will be far of, but any help would be greatly appreciated.

A: Use this fiddle:
JS:
function findTotal($this) {
            var cls = $($this).attr("class");
            var index = cls.split('qty')[1];
            var totalsum = 0;
            $('.' + cls).each(function () {
                if ($.isNumeric($(this).val())) {
                    totalsum += parseInt($(this).val());
                }
            });
            if ($.isNumeric($(".total" + index).val())) {

                if (totalsum != parseInt($(".total" + index).val())) {
                    $(".total" + index).addClass('error');
                }
                else {
                    $(".total" + index).removeClass('error');
                }
            }

        }

HTML:

total1:<input type="text" class="total1" />

qty1<input type="text" class="qty1" onblur="findTotal(this)" />

qty1<input type="text" class="qty1" onblur="findTotal(this)" />

qty1<input type="text" class="qty1" onblur="findTotal(this)" />

total2:<input type="text" class="total2" />

qty2<input type="text" class="qty2" onblur="findTotal(this)" />

qty2<input type="text" class="qty2" onblur="findTotal(this)" />

qty2<input type="text" class="qty2" onblur="findTotal(this)" />

A: I would do something like this:
This is just to make you an idea of how could you do, don't copy/paste directly because maybe there is some typo. But the main steps are:

*

*Add classes to each Quantity input so you can select them by row

*Recover the total by row

*Make a loop for all Quantities by Row and compare with total

In your HTML add classes to identify each element of any row

   <form:input path="items[${status.index}].total" size="4"
    class="total${status.index}"
    id = "total[${status.index}]" />

 <form:input path="items[${status.index}].qtyDis"size="4"
    onblur="findTotal()" class="qty${status.index}"
   id ="qty[${status.index}]" />

   <form:input path="items[${status.index}].qtyAva"size="4"
     onblur="findTotal()" class="qty${status.index}"
    id ="qty[${status.index}]" />

   <form:input path="items[${status.index}].qtyDat"size="4"
    onblur="findTotal()" class="qty${status.index}"
    id ="qty[${status.index}]" />

Then in your JS


text:
Q: Microsoft Graph Client - Filter I'm trying to get a list of all calendars that the authenticated user owns.
The following code works, but doesn't specify that I want calendars the authenticated user owns.
await this.graphClient
                .api('/me/calendars')
                .select('name, id, canEdit, owner')
                .get();

When I added
await this.graphClient
                .api('/me/calendars')
                .select('name, id, canEdit, owner')
                .filter(`equals(owner.address, '${this.authenticatedUserEmail}')`)
                .get();

I get no result ( I should get 4 results ). I'm assuming this is because of the way I wrote .filter
Basically owner is an object with name and address .
How do i fix this?

A: As Vadim pointed out, this is a complex property, not a linked entity.
This means this filter cannot work and the filter cannot be applied.


text:
Q: load data in a file into several arrays I want to plot every value in a .dat file with data as follows using Matlab:
100  20  30  40  70
200  32  122  45  483

200  388  93  344  23  222
234  23  122
123  984  344  34

213  12  43  9
23

For each row, data is separated by "  "(2 spaces) as delimiters. An empty row (should be another kind of delimiter) separates the data into different arrays.
Therefore, I want to plot the three arrays in one graph: array 1 has 2 row with "red dot" in the graph; array 2 has 3 rows with "blue dots" and array 3 has 2 rows with "green dots".
How can I program to load the file data into three arrays (or matrices), and then plot them?
EDIT:
By the way, the number of items in each row may be different. How to pad short rows with "0"s to make all the rows have same length?

A: See this :
strsplit(str,delimiter)

To split the array into different variables, you can do something like this :
# Where OriginalInputData is a string containing the whole .dat file.
InputData = strsplit(OriginalInputData, /n/n) #Cell array of strings
PreArray1 = strsplit(InputData(1), /n)
Array1(1,:) = strsplit(PreArray1(1), "  ")
Array1(2,:) = strsplit(PreArray1(2), "  ")
#Plot Array1

Apply this same logic to your other arrays. It will also fill the "empty cells" with "0"s.


text:
Q: Cannot setup the function with out parameter using lambda expression I've found loads of questions to the error message, but not one that matches my specific case.
I have a method with this signature in a cache implementation:
public bool TryGet(TKey key, out TValue returnVal, Func<TKey, TValue> externalFunc = null)

I have a class derived from that with TKey : CompositeKey and TValue : string.
I'm trying to mock it for unit testing like this:
_cacheMock
    .Setup(x => x.TryGet(It.IsAny<CompositeKey>(), out It.Ref<string>.IsAny, It.IsAny<Func<CompositeKey, string>>()))
    .Returns((CompositeKey key, out string s, Func<CompositeKey, string> fetchOne) => { s = ""; return true; });

I get a compilation error for the .Returns line:

"Cannot convert lambda expression to type 'bool' because it is not a
  delegate type"

If I remove the "out" modifier it compiles OK - but of course doesn't match the signature of the call and I can't get the out value out.
Is there a way to fix the Returns() part of the statement without modifying the TryGet() method itself?

A: This might work for you:
//define the callback delegate
delegate void TryGetCallback(CompositeKey key, out string str, Func<CompositeKey, string> func);

mock.Setup(x => x.TryGet(
        It.IsAny<CompositeKey>(),
        out It.Ref<string>.IsAny,
        It.IsAny<Func<CompositeKey, string>>()))
    .Callback(new TryGetCallback((CompositeKey key, out string str, Func<CompositeKey, string>  func) =>
    {
        str = "foo bar";
    }))
    .Returns(true);

with such a setup you could archive what you want
string actualValue;
bool result = mock.Object.TryGet(new CompositeKey(), out actualValue)
//actualValue = "foo bar", result = true


text:
Q: Is there a way to lock a particular instance of vs code while working with multiple instances? There are times when one is working with multiple instances of vs-code... In that situation, It becomes soo easy to put code in wrong instance... Is there any way to lock a particular vs-code instance while working with multiple instances.
This question is more of a suggestion for vs-code developers to add this feature

A: With the extension When File you can color your VSC instances differently depending on the workspace it has open.
Or you can create a Multi Root Workspace and have all your workspaces open in one VSC instance


text:
Q: Add Access File on SharePoint Designer 2013 How can I add .accdb file on SharePoint Designer 2013?
I looked blocked file types on Central Administration but I didn't find accdb and I didn't remove from the list.

When I create new access app I got errors:

AddAccessApp.ValidateUserHasInstallRights: Validate that the user has app Install permissions 9f81119d-d671-c067-e92a-0d034159d910
AddAccessApp.OpenExistingApp: FileName=KUH_HPB_Dbase_v1.3.accdb;
  ContentType=application/octet-stream; Size=11145216.    9f81119d-d671-c067-e92a-0d034159d910
Access Services                 Application Design              allm8   Medium      TemplateManager.InstallAccessPackageAndDoNotWait: Validating the Access .app package    9f81119d-d671-c067-e92a-0d034159d910
AccessPackageBuilder.ValidateAccessPackage: Validating the Access app package.    9f81119d-d671-c067-e92a-0d034159d910
UserProfileDBCache.GetChangedDBItemsPrimaryKeys: m_AllPropertyIDs = 1;3;9;2;5009;7;23;13;14;22;5065;5061;5062;5040;5042;5091;5092;5093;5096;5097;5098;
ccessPackageBuilder.IsValidAccessAppPackage: Validating the Access app package threw an exception: {System.IO.FileFormatException: File contains corrupted data.     at MS.Internal.IO.Zip.ZipIOEndOfCentralDirectoryBlock.FindPosition(Stream archiveStream)     at MS.Internal.IO.Zip.ZipIOBlockManager.LoadEndOfCentralDirectoryBlock()     at MS.Internal.IO.Zip.ZipArchive.OpenOnStream(Stream stream, FileMode mode, FileAccess access, Boolean streaming)     at System.IO.Packaging.ZipPackage..ctor(Stream s, FileMode mode, FileAccess access, Boolean streaming)     at System.IO.Packaging.Package.Open(Stream stream, FileMode packageMode, FileAccess packageAccess, Boolean streaming)     at Microsoft.Office.Access.Services.Design.AccessPackageBuilder.IsValidAccessAppPackage(Stream appPackageStream)}.  9f81119d-d671-c067-e92a-0d034159d910
AddAccessApp.OpenExistingApp: Unexpected exception thrown while creating the Access app. Message: {System.IO.FileFormatException: File contains corrupted data.     at MS.Internal.IO.Zip.ZipIOEndOfCentralDirectoryBlock.FindPosition(Stream archiveStream)     at MS.Internal.IO.Zip.ZipIOBlockManager.LoadEndOfCentralDirectoryBlock()

A: I'm guessing you are trying to add the access file in a SharePoint library. There is a related article on storing Access related files here. It describes that even though some access file types are blocked some are allowed(Example .accdb and .accdp) in SP 2013.
I'm using SP 2013 Foundation. Tried manually adding a .accdb in a SP 2013 library.  SharePoint takes some time to add the access database file in to the SP library. I could see the .accdb among the list items, not immediately but after 2 seconds delay. (Note that my .accdb file size is very small, 370 kb). So it seems adding .accdb is not an issue. Could you please check the file size. Not sure whether that's causing any trouble for you.
But if you are trying to manipulate the file using SP Designer, could you explain a bit more on what you are attempting to do


text:
Q: Sorting Complicated Data I have an Excel spreadsheet of data and I'm not sure the best way to sort it.
It is for an insurance plan. The data includes subscribers, spouses, and children, each with their own row. Each subscriber is given a unique identifier, and there is a column that includes the same unique identifier by row for the subscriber, spouse, and children so that the dependents can be matched up to the subscriber.
I am trying to sort the data by last name so it is alphabetical, but also make sure that if any dependents have different last name, they are still blocked with the subscriber based on the unique identifier. Furthermore, I would like the last "sort" to be the "Relationship" Column, as this identifies Subscriber, Spouse, Child, and I'd like the data to be in that order.
Is this possible for Excel?

A: Let's say your data looks like this:

I suggest adding two helper columns to the worksheet.

*

*In Cell E1 enter a new column title "IDLast"

*In cell E2 enter the formula =$C2&$D2

*In cell F1 enter a new column title "SubscriberName"

*In cell F2 enter the formula =INDEX($B:$B,MATCH($C2&"Subscriber",$E:$E,0))

*Copy the formulas from E2:F2 to the rest of the rows with data

Column E now contains the ID from this row followed by the relationship.
Column F now contains the last name of the subscriber associated with the person on this row.
This works because MATCH will return the row that has this row's ID followed by "Subscriber" in column E. INDEX will now return the last name from the row identified by MATCH.
You can now sort the data first by column F (SubscriberName) in ascending order and then by column D (relationship) in descending order.

Note that the relationships you mentioned just happens to be in reverse alphabetical order. If there are other relationships that should not appear in that order, you will need a 3rd helper column to translate the relationship into a number that can be sorted on.
If you don't want the helper columns to be visible, you can hide them by selecting the helper columns, right-clicking and choosing "Hide" from the context menu.


text:
Q: Wordpress Fatal error: Allowed memory size exhausted I'm in the process of importing a huge number of files via .CSV - all that seems to be going fine but after an import finished I started getting this error:
on the WordpPress post management page (http://localhost/wordpress/wp-admin/edit.php)
( ! ) Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 524288 bytes) in C:\wamp\www\wordpress\wp-includes\class-wp-walker.php on line 176
Call Stack
#   Time    Memory  Function    Location
1   0.0016  857424  {main}( )   ..\edit.php:0
2   9.4654  31424712    WP_List_Table->display( )   ..\edit.php:249
3   9.4655  31425264    WP_List_Table->display_tablenav( )  ..\class-wp-list-table.php:709
4   9.4660  31425808    WP_Posts_List_Table->extra_tablenav( )  ..\class-wp-list-table.php:761
5   10.0549 31394480    wp_dropdown_categories( )   ..\class-wp-posts-list-table.php:222
6   16.4317 261790880   walk_category_dropdown_tree( )  ..\category-template.php:370
7   16.4441 266681480   call_user_func_array ( )    ..\category-template.php:763
8   16.4441 266682016   Walker->walk( ) ..\category-template.php:0
9   16.4441 266682064   func_get_args ( )   ..\class-wp-walker.php:176

and on the import CSV page (http://localhost/wordpress/wp-admin/tools.php?page=csv-importer/csv_importer.php) I get
( ! ) Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 63 bytes) in C:\wamp\www\wordpress\wp-includes\class-wp-walker.php on line 176
Call Stack
#   Time    Memory  Function    Location
1   0.0006  707784  {main}( )   ..\tools.php:0
2   0.0014  827336  require_once( 'C:\wamp\www\wordpress\wp-admin\admin.php' )  ..\tools.php:10
3   0.2692  30508160    do_action( )    ..\admin.php:151
4   0.2692  30509656    call_user_func_array ( )    ..\plugin.php:405
5   0.2692  30509688    CSVImporterPlugin->form( )  ..\plugin.php:0
6   0.2694  30510936    wp_dropdown_categories( )   ..\csv_importer.php:111
7   6.3437  260920048   walk_category_dropdown_tree( )  ..\category-template.php:370
8   6.3582  265810672   call_user_func_array ( )    ..\category-template.php:763
9   6.3582  265811208   Walker->walk( ) ..\category-template.php:0
10  6.3582  265811256   func_get_args ( )   ..\class-wp-walker.php:176

I've been searching the last few days trying to figure this out - all fixes seem to point towards moding the php.ini with memory_limit (tried -1 and 9999m) or moding the WP config with define('WP_MEMORY_LIMIT', '64M'); I echo'd out the php info to make sure changes where taking place and it seems they are. I'm running WAMP on windows 64x if that helps.
All posts show up fine on the frontend, it's just in the backend they seem to be producing this error. Honestly I've got no idea what to try next. Any ideas are welcome!

A: Some webservers may impose memory limits. Check your Apache settings to make sure its not the culprit.

A: Try setting this bit of code at the top of csv_importer.php:
ini_set('memory_limit', '1024M');

A:     Try these different settings in C:\wamp\bin\apache\apache2.2.6\bin\php.ini

    Find:
    post_max_size = 8M
    upload_max_filesize = 2M
    max_execution_time = 30
    max_input_time = 60
    memory_limit = 8M

    Change to:
    post_max_size = 750M
    upload_max_filesize = 750M
    max_execution_time = 5000
    max_input_time = 5000
    memory_limit = 1000M

    And add this to C:\wamp\bin\mysql\mysql5.0.45\my.ini:

    max_allowed_packet = 200M

    Then restart wamp


text:
Q: Nuxt - Using router.push inside a component not changing pages correctly index.vue -
<template>

        <SearchForm />

</template>

jobs.vue -
<template>

    <SearchForm />

 Results for "{{q}}"

                {{ item.job_title }}
                {{ item.job_city }}
                {{ item.job_state }}
                {{ item.job_work_remote }}

</template>

SearchForm.vue component -
<template>

         keyword

        location

        Find Jobs

</template>

The route for "http://localhost:3000/" returns the index.vue page.
In this vue page, I have a component with a search form. Once you complete these form and hit the seach button, it will re-direct to a results page
if this.form.keyword = "Data", the next URL will be "http://localhost:3000/jobs?q=Data" and it will be using the jobs.vue page.
The issue I'm running into is the CSS is not being loaded from the jobs.vue page. It's still coming from the index.vue page for some reason. If I refresh the page, then the CSS from jobs.vue is loading. I need the CSS to load from jobs.vue on the initial redirect. All of the query data is working as expected so thats a plus.
However, the following CSS is being applied from index.vue for some reason instead of the CSS from the jobs.vue page -
display: flex;
justify-content: center;

Does anyone know whats going on here? This app is SSR and not SPA.

A: You have to scope your css from the index.vue page to the other pages with the scoped directive (see docs https://vue-loader.vuejs.org/guide/scoped-css.html)

You can add your global CSS in your layouts/default.vue file.

A: This solved the issue -
methods: {
    onSubmit() {
        window.location = 'http://localhost:3000/jobs?q=' + this.form.keyword;
    }
},


text:
Q: How to provide a @ControllerAdvice conditional on bean? I'm creating a framework that I'd like to reuse in all of my future projects. If the sub project does not define a @ControllerAdvice, I want my framework to automatically initialize a default Advice for exception handling.
public class ExHandler implements IAdvice {
    ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ResponseBody
    public ErrorDTO default(xception e) {
        return new ErrorDTO();
    }
}

I tried as follows, but does not work:
@Configuration
static class MyConfig {
    @ControllerAdvice
    @ConditionalOnMissingBean(IAdvice.class)
    static class AdviceExHandler extends ExHandler {

    }
}

In Sub project:
@ControllerAdvice
public class SubHandler extends ExHandler {
}

Result: It works. BUT: if the subproject does not define the ExHandler, the bean is not initialized at all! But why?
Sidenote: I'm trying to prevent mutliple ControllerAdvice because error handling depends on the order of methods inside the exception handler. Thus I don't want to mess the order by introducing multiple classes.

A: You could use it without wrappers. Just declare @ControllerAdvice annotated class as following in Kotlin:
@ControllerAdvice
@ConditionalOnMissingBean(annotation = [ControllerAdvice::class])
class ExceptionHandler {

    @ResponseStatus(HttpStatus.EXPECTATION_FAILED)
    @ResponseBody
    @ExceptionHandler
    fun handleProcessingException(e: Exception): ErrorDto {
        return ErrorDto()
    }
}

And just declare it in spring.factories file if you're doing it for starter:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  ru.raiffeisen.ecommerce.controller.ExceptionHandler

That's all. If there is no @ControllerAdvice annotated classes, then will be used class from configuration.

A: You may use @ConditionalOnMissingBean(annotation = ControllerAdvice.class) to configure condition on missing bean with ControllerAdvice annotation.
@ControllerAdvice
public abstract class FrameworkAdvice {
...
}

And conditionally configure it:
@Configuration
@ConditionalOnMissingBean(annotation = ControllerAdvice.class)
public class FrameworkAdviceConfig {
    @Bean
    public FrameworkAdvice frameworkAdvice() {
        return new FrameworkAdvice() {
        };
    }
}

And if there is another controller advice in project, it will be used instead.
@ControllerAdvice
public class CustomAdvice {
...
}


text:
Q: How to give high CPU to a Program in Windows 7 I am running a computation intensive (solving a number theory problem) standalone java program from eclipse on my Windows 7 machine. No other application is running.
Now I started task manager and see javaw.exe taking only ~50%. Even after raising priority to high, as suggested here, it still takes just 50%.
Is it possible to provide high CPU (say 90%) to this program?

A: The problem here is that your program is not designed with multithreading or multi processor based computation. Because of this the program is using, fully, one of the (im guessing) 2 cores of your machine.
Can you verify in the task manager tab "Performance" that one of the two boxes is showing full usage (100%) and one is low?

A: If it is the only CPU intensive program running and it only gets ~50% CPU then there are two possible reasons:

*

*It is waiting for something else. (Often disk access)

*It is not multi threaded.With 50% this is most likely the case. Especially if you have a dual core CPU and the program is running flat out on one core, while the other core is idle.

Edit: You can test option 2 by starting two instances of the program. That will probably raise your CPU usage to 100%.


text:
Q: How to learn language to read math text? I recently discover new mathematical wealth in non-English texts. Sadly, the two language that I speak are not German, Russian, Chinese, French, or languages that belong to the world leading math research nations.
I want to learn these specifically for mathematics with NO emphasis on speaking, listening, basically NO conversation in general, just math - which would make the process more tedious.
What is the best way to achieve this goal? Would using a dictionary to read an article a good way to learn? But every language has some structure behind it and it may be impossible to figure out what certain things mean without that knowledge.

A: When I was a junior math major at a small midwestern (US) liberal
arts college, my instructor chose a book in French for the text.
He brushed away complaints that none of us knew French by saying
that the math would be so hard that we'd hardly notice the inconvenience
of learning French. He was correct on both counts.
That is my introduction to agreeing with @JeanMarie that you might
do well to start with French. There are a lot of cognate words and French
mathematicians seem to specialize in simple, elegant presentations.
(With French, it does help to have someone around who knows the
pronunciation, because it makes reading easier. The rules are fairly simple,
and almost correct is good enough.)
Learning to read mathematics in any foreign language is made simpler
by several almost-facts: almost everything is in the present tense and the
third person, and
you can begin by choosing books and articles on familiar topics so that you
almost know what the words amongst the equations must mean.
One recommendation as you begin is that it may help to start with
books written by people who were writing in what was to them a
foreign language. Copy editors will have fixed the mistakes and the
vocabulary will tend to be utilitarian. A Pole writing French, a Russian writing German,
etc. Specifically, Casimir Kuratowski's Topologie and A. N. Kolmogorov's
foundational tract on probability theory in German.
Another recommendation is to be absolutely fearless. No one will know about the initial mistakes
you make. When writing my PhD thesis I needed to use a Russian journal
article during the summer when all the Russian speakers I knew were on vacation.
I knew no Russian, not even the alphabet. It took me almost half an hour
to look up the first word, but then I (almost) knew the alphabet. I encountered a
couple of places where it mattered whether the text was saying 'A of B' or 'B of A',
but a quick look at a grammar text took care of that. Fortunately, the
article was only 3.5 pages long, mostly equations. Three days, and I got what I needed.
I have no recommendations on getting started with Chinese.